diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 71eb719051..3934f75db8 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -4,7 +4,7 @@ on: push: branches: [main] pull_request: - branches: [main] + branches: [main, cpp-migration] workflow_dispatch: concurrency: @@ -32,7 +32,7 @@ jobs: - name: Check machine-code inputs with LLVM 15 run: | sudo apt-get update -q - sudo apt-get install -y --no-install-recommends llvm-15 spirv-tools spirv-cross + sudo apt-get install -y --no-install-recommends llvm-15 spirv-tools spirv-cross glslang-tools python3 -B - <<'PY' import runpy import sys @@ -41,6 +41,7 @@ jobs: SPIRV = ["spirv-as", "spirv-val", "spirv-cross"] CHECKS = [ (["tests/compute_store_check.py", *COMMON_LLVM], {}), + (["tests/compute_alu_negabs_check.py", *COMMON_LLVM], {}), (["tests/compute_buffer_atomics_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_load_format_check.py", *COMMON_LLVM], {}), (["tests/compute_heap_view_check.py", *COMMON_LLVM], {}), @@ -50,6 +51,7 @@ jobs: (["tests/sampled_coverage_check.py", *COMMON_LLVM], {}), (["tests/pixel_compare_gather_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1"], {}), (["tests/pixel_gather_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1"], {}), + (["tests/pixel_sample_clamp_check.py", *COMMON_LLVM, "llc-15"], {}), (["tests/pixel_sample_gradient_check.py", *COMMON_LLVM, "llc-15"], {}), (["tests/pixel_sample_gradient_check.py", "binary-coarse", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1", "llc-15"], {}), (["tests/depth_mask_check.py", *COMMON_LLVM], {}), @@ -65,6 +67,9 @@ jobs: (["tests/spirv_window/check.py"], {}), (["tests/spirv_window/compare_sampler.py", *SPIRV], {}), (["tests/pixel_sample_offset_check.py", *COMMON_LLVM], {}), + (["tests/pixel_compare_lod_check.py", *COMMON_LLVM], {}), + (["tests/pixel_compare_grad_check.py", *COMMON_LLVM, "llc-15"], {}), + (["tests/pixel_compare_grad_check.py", "glsl", "glslangValidator", "spirv-val", "spirv-dis"], {}), (["tests/pixel_compare_sample_check.py", *COMMON_LLVM], {}), (["tests/pixel_compare_check.py", *COMMON_LLVM], {}), (["tests/pixel_attribute_sampled_check.py", *COMMON_LLVM], {}), @@ -84,48 +89,71 @@ jobs: (["tests/mesh_shadow_check.py", *COMMON_LLVM], {}), (["tests/startup_sampler_heap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_sdwa_cndmask_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_loop_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_lane_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "decode", "libLLVM-15.so.1"], {}), + (["tests/startup_gfx2hlsl_scalar_null_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_scalar_null_check.py", "decode", "libLLVM-15.so.1"], {}), + (["tests/startup_compute_global_load_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_compute_global_load_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_cmp16_check.py", "binary", "llvm-mc-15", "llvm-objcopy-15"], {}), (["tests/startup_image_sample_l_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_b_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_lod_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_image_sample_d_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_record_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_heap_word_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_store_format_xyzw_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_int3_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_mip_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_round_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_2d_array_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_a16_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_image_load_d16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_load_d16_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_transcendental_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_int_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_f16_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_p2_hi_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_sgpr_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), + (["tests/shader_signed_zero_minmax_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_compute_spill_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_compute_mask_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b128_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_far_early_out_check.py", "binary", "llvm-mc-15", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_joined_table_pointer_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_dpp_quad_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_mad64_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_mul_hi_i32_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mul_mad_i24_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cube_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), @@ -146,8 +174,10 @@ jobs: (["tests/compute_dpp_row_shr_check.py", *COMMON_LLVM], {}), (["tests/startup_compute_lds_dual_atomics_check.py", "binary", "llvm-mc-15"], {}), ] - sys.exit(runpy.run_path("tools/run_checks_parallel.py", - run_name="run_checks_parallel")["run_checks"](CHECKS)) + runner = runpy.run_path("tools/run_checks_parallel.py", run_name="run_checks_parallel") + # Checks listed in tests/checks/pixel-binary/*.txt run after the inline list. + CHECKS = runner["merge_checks"](CHECKS, "tests/checks/pixel-binary") + sys.exit(runner["run_checks"](CHECKS)) PY python-linux: name: Run platform-independent Python checks on Linux @@ -167,6 +197,7 @@ jobs: - name: Run Python checks run: | python -B tools/run_checks_parallel.py \ + --from-dir tests/checks/python-linux \ tests/script_state_check.py \ tests/resource_root_check.py \ tests/pe_authentihash_check.py \ @@ -222,6 +253,7 @@ jobs: tests/startup_image_sample_l_check.py \ tests/startup_image_sample_b_check.py \ tests/startup_image_sample_lod_check.py \ + tests/startup_image_sample_d_check.py \ tests/startup_image_gather_lz_check.py \ tests/startup_compute_gather_lz_check.py \ tests/startup_compute_image_store_check.py \ @@ -232,23 +264,29 @@ jobs: tests/startup_compute_store_format_xyzw_check.py \ tests/startup_image_gather_c_lz_check.py \ tests/startup_image_sample_c_check.py \ + tests/startup_gfx2hlsl_float_alu_check.py \ tests/startup_image_3d_check.py \ tests/startup_image_load_mip_check.py \ tests/startup_gfx2hlsl_operand_count_check.py \ + tests/startup_gfx2hlsl_float_round_check.py \ tests/startup_gfx2hlsl_scalar_arity_check.py \ tests/startup_gfx2hlsl_scalar_table_arity_check.py \ tests/startup_image_2d_array_check.py \ tests/startup_image_sample_a16_check.py \ tests/startup_image_load_d16_check.py \ tests/startup_host_cpu_check.py \ + tests/startup_window_capture_check.py \ tests/startup_live_telemetry_check.py \ tests/startup_gfx2hlsl_cvt_alu_check.py \ tests/startup_gfx2hlsl_cvt_pk_u8_check.py \ tests/startup_gfx2hlsl_cvt_pk_int16_check.py \ + tests/startup_gfx2hlsl_scalar_null_check.py \ + tests/startup_compute_global_load_check.py \ tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py \ tests/startup_gfx2hlsl_int_med3_check.py \ tests/startup_gfx2hlsl_cselect_mask_check.py \ tests/startup_gfx2hlsl_mask_overwrite_check.py \ + tests/startup_gfx2hlsl_mask_data_check.py \ tests/startup_gfx2hlsl_image_get_lod_check.py \ tests/startup_gfx2hlsl_add_sub_co_check.py \ tests/startup_gfx2hlsl_add_sub_co_ci_check.py \ @@ -257,49 +295,83 @@ jobs: tests/startup_gfx2hlsl_capture_check.py \ tests/startup_gfx2hlsl_watch_check.py \ tests/startup_translator_check.py \ + tests/startup_gfx2hlsl_int3_alu_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_gfx2hlsl_desc_vcc_check.py \ tests/startup_gfx2hlsl_sload_const_offset_check.py \ tests/startup_archive_requests_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_compute_request_offline_check.py \ tests/compute_container_index_check.py \ tests/startup_shader_cache_rekey_check.py \ + tests/startup_shader_cache_revision_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_mesh57_skeleton_check.py \ + tests/startup_mesh57_depth_only_check.py \ + tests/startup_mesh57_loop_refusal_check.py \ + tests/startup_mesh57_loop_check.py \ + tests/startup_mesh57_lane_spill_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ tests/startup_gfx2hlsl_join_symbols_check.py \ + tests/startup_joined_table_pointer_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ + tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py \ tests/startup_compute_readfirstlane_check.py \ + tests/startup_gfx2hlsl_heap_record_check.py \ + tests/startup_gfx2hlsl_heap_word_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ + tests/startup_gfx2hlsl_far_early_out_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ tests/startup_run_sh_check.py \ tests/startup_flat_param_check.py \ + tests/startup_gfx2hlsl_float_transcendental_check.py \ tests/startup_ps_input_scan_check.py \ + tests/startup_packed_position_provenance_check.py \ tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ - tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ + tests/startup_gfx2hlsl_int_alu_check.py \ + tests/startup_gfx2hlsl_interp_f16_check.py \ + tests/startup_gfx2hlsl_interp_p2_hi_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ + tests/startup_gfx2hlsl_spill_branches_check.py \ tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_neg_check.py \ + tests/shader_signed_zero_minmax_check.py \ tests/startup_gfx2hlsl_compute_check.py \ + tests/startup_gfx2hlsl_compute_spill_check.py \ + tests/startup_gfx2hlsl_compute_mask_spill_check.py \ tests/startup_compute_lds_b64_check.py \ tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_s_abs_check.py \ + tests/startup_gfx2hlsl_s_quadmask_b64_check.py \ + tests/startup_gfx2hlsl_s_ff0_check.py \ + tests/startup_gfx2hlsl_s_bitset_check.py \ + tests/startup_gfx2hlsl_s_flbit_check.py \ + tests/startup_gfx2hlsl_s_ff1_check.py \ + tests/startup_gfx2hlsl_src_scc_check.py \ + tests/startup_gfx2hlsl_s_quadmask_check.py \ tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_shift64_literal_check.py \ + tests/startup_gfx2hlsl_mad64_check.py \ + tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py \ + tests/startup_gfx2hlsl_mul_hi_i32_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ tests/startup_gfx2hlsl_cmp16_check.py \ tests/startup_gfx2hlsl_draw_skip_check.py \ tests/startup_gfx2hlsl_sdwa_cvt_check.py \ + tests/startup_gfx2hlsl_sdwa_cndmask_check.py \ tests/startup_gfx2hlsl_sop2_complement_check.py \ tests/startup_gfx2hlsl_pack_absdiff_check.py \ tests/startup_gfx2hlsl_sopk_accum_check.py \ + tests/startup_gfx2hlsl_bfm_b64_check.py \ tests/startup_gfx2hlsl_f32_lg_check.py \ tests/startup_gfx2hlsl_f32_nan_check.py \ tests/startup_gfx2hlsl_f32_sdwa_check.py \ @@ -307,7 +379,11 @@ jobs: tests/startup_gfx2hlsl_sopk_signext_check.py \ tests/startup_gfx2hlsl_mul_hi_check.py \ tests/startup_gfx2hlsl_sad_check.py \ + tests/startup_gfx2hlsl_sad_hi_msad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ + tests/startup_gfx2hlsl_const_copy_join_check.py \ + tests/startup_gfx2hlsl_s_bit_scan_check.py \ + tests/startup_gfx2hlsl_pack_b32_f16_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ tests/startup_buffer_format_word3_table_check.py \ @@ -328,6 +404,7 @@ jobs: tests/startup_gfx2hlsl_getpc_refusal_check.py \ tests/startup_gfx2hlsl_image_arity_check.py \ tests/startup_compute_lds_dual_atomics_check.py \ + tests/startup_gfx2hlsl_desc_ptr_prop_check.py \ tests/run_checks_parallel_check.py build-and-test: name: Build and test on Windows @@ -421,6 +498,14 @@ jobs: ctest --preset dev --no-tests=error --parallel 4 -E '_hardware$' --output-junit "$PWD/out/test-results.xml" } exit $LASTEXITCODE + - name: Check native DXIL generation on migration pull requests + if: github.base_ref == 'cpp-migration' + shell: pwsh + run: | + .\tools\dev.ps1 + cmake --build --preset dev --target compile_dxil + if ($LASTEXITCODE) { exit $LASTEXITCODE } + ctest --preset dev --no-tests=error -R '^native_dxil_llvm_ident_controls$' - name: Require the SPIR-V bridge WARP tests if: ${{ !cancelled() }} shell: pwsh diff --git a/AGENTS.md b/AGENTS.md index 89516ec2ac..8b5b46c435 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -167,12 +167,26 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_neg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_interp_p2_hi_check.py +./out/pe-env/bin/python -B tests/shader_signed_zero_minmax_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_spill_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_mask_spill_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py +./out/pe-env/bin/python -B tests/startup_pixel_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_store_3d1d_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_record_check.py ./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_heap_word_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_abs_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_quadmask_b64_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff0_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_bitset_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_flbit_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_ff1_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_s_quadmask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py @@ -191,17 +205,25 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_depth_only_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_loop_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_lane_spill_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_recompute_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_absdiff_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cndmask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_accum_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_int_med3_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cselect_mask_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_overwrite_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_bfm_b64_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_data_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_get_lod_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_ci_check.py @@ -242,19 +264,27 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_run_sh_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_bit_alu_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sgpr_spill_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_spill_branches_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_shift64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_sdwa_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_lg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_const_copy_join_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_b32_f16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pk_minmax_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_hi_msad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cvt_pk_int16_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_null_check.py +./out/pe-env/bin/python -B tests/startup_compute_global_load_check.py ``` `tests/pixel_aot_check.py binary` additionally needs LLVM with gfx1013 support @@ -268,7 +298,9 @@ newer versions may print a different `exp` spelling. | `src/` | Windows runtime shims and shared shader helpers. | | `tools/` | Offline translators, PE/image probes and inventory tools. | | `tests/` | C++, HLSL, MASM and Python fixtures. `tests/cpu/` holds the PE fixtures. | -| `docs/experiments.md` | Measured results, assumptions and reproduction commands. | +| `docs/experiments.md` | Older measured results, assumptions and reproduction commands. New notes go in `docs/experiments/.md`. | +| `tests/cmake/` | One `.cmake` file per test family or pull request, included by `CMakeLists.txt` (see its README). | +| `tests/checks/` | Text files that add Python checks to the Linux CI jobs; see its README. | | `game-files/` | Local inputs; gitignored. Never commit or upload. | | `out/` | Build, generated sources and reports; gitignored. | diff --git a/CMakeLists.txt b/CMakeLists.txt index 5a367699d2..252816910f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,38 @@ project(Xbox2Windows LANGUAGES CXX) enable_testing() +if(WIN32) + include(CheckIncludeFiles) + check_include_files("windows.h;dxcapi.h" X2W_HAVE_DXCAPI LANGUAGE CXX) + if(X2W_HAVE_DXCAPI) + add_library(x2w_shader_compiler STATIC src/gfx1013_pixel.cpp src/gfx1013_compute_clear.cpp + src/shader_compute_request.cpp src/guest_shader_container.cpp src/gfx1013_isa.cpp src/direct_compute_cache.cpp src/gfx1013_compute_native.cpp src/native_compute_pipeline.cpp + src/gfx1013_compute_ir.cpp src/gfx1013_sampled_pixel.cpp src/gfx1013_vertex_id.cpp src/gfx1013_rect_geometry.cpp src/shader_dxil_compiler.cpp) + set(native_shader_revision "") + foreach(source gfx1013_compute_native.cpp gfx1013_compute_native.h gfx1013_compute_opcodes.inl gfx1013_graphics_wqm.inl + gfx1013_isa_tables.inl gfx1013_isa.cpp gfx1013_isa.h gfx1013_compute_alu.inl gfx1013_direct_compute.inl gfx1013_compute_ir.cpp gfx1013_compute_ir.h + gfx1013_compute_mtbuf.inl gfx1013_direct_graphics.inl gfx1013_direct_mesh.inl gfx1013_pixel_waterfall.inl gfx1013_rect_geometry.cpp guest_shader_container.cpp guest_shader_container.h + dxil_module.h mesh_pixel_heap.h direct_compute_cache.cpp direct_compute_cache.h + shader_compute_request.cpp shader_compute_request.h startup_stubs/inflate.h) + set(native_shader_file "${CMAKE_CURRENT_SOURCE_DIR}/src/${source}") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${native_shader_file}") + file(SHA256 "${native_shader_file}" native_shader_part) + string(APPEND native_shader_revision "${native_shader_part}") + endforeach() + string(SHA256 native_shader_revision "${native_shader_revision}") + file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/native_shader_revision.h" + CONTENT "#define X2W_NATIVE_SHADER_REVISION \"${native_shader_revision}\"\n") + target_include_directories(x2w_shader_compiler PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated") + target_include_directories(x2w_shader_compiler PUBLIC src) + target_compile_features(x2w_shader_compiler PUBLIC cxx_std_17) + target_link_libraries(x2w_shader_compiler PRIVATE bcrypt d3d12) + add_executable(compile_dxil tools/startup/compile_dxil.cpp) + target_link_libraries(compile_dxil PRIVATE x2w_shader_compiler) + set_target_properties(compile_dxil x2w_shader_compiler PROPERTIES + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + endif() +endif() + # Python never caches the bytecode of the script it is started with, so every start of a big # tests/.py recompiled it. tests/pyc_main.py runs that file through the import system, # which reuses a valid .pyc. The add_test calls below keep naming the script; this wrapper swaps in @@ -102,6 +134,13 @@ target_compile_features(memory_query_check PRIVATE cxx_std_17) target_link_libraries(memory_query_check PRIVATE psapi) add_test(NAME desktop_memory_query COMMAND memory_query_check) +# tracy_new.cpp against a recording stand-in for Tracy's memory macros (no Tracy fetched, runs in every build). +add_executable(tracy_new_check tests/tracy_new_check.cpp) +target_compile_features(tracy_new_check PRIVATE cxx_std_17) +target_include_directories(tracy_new_check PRIVATE tests/fixtures/tracy_fake) +target_compile_definitions(tracy_new_check PRIVATE X2W_TRACY=1 X2W_TRACY_HEAP="test C++ heap") +add_test(NAME tracy_new COMMAND tracy_new_check) + add_executable(xmem_committed_memory_check tests/xmem_committed_memory_check.cpp) target_compile_features(xmem_committed_memory_check PRIVATE cxx_std_17) target_link_libraries(xmem_committed_memory_check PRIVATE OneCore) @@ -238,6 +277,10 @@ if(EXISTS "${INTAKE_PYTHON}") # and section count the DirectStorage heartbeat reports from it. add_test(NAME xmem_page_stats COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_page_stats_check.py" "$") + # A page-token write names granted pages only: no section outside a grant, and a fresh grant reads zero. + add_test(NAME xmem_physical_write_owner COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_physical_write_owner_check.py" "$") + set_tests_properties(xmem_physical_write_owner PROPERTIES TIMEOUT 120) # A few mapped pages commit about those pages, not the whole 256 MiB slab that holds them (#1199). add_test(NAME xmem_mapped_pages_commit COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_mapped_pages_commit_check.py" "$") @@ -255,7 +298,7 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(xmem_lazy_commit_off PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=0") add_test(NAME xmem_lazy_startup COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_lazy_startup_check.py" "$") - set_tests_properties(xmem_lazy_startup PROPERTIES TIMEOUT 60 + set_tests_properties(xmem_lazy_startup PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE ENVIRONMENT "X2W_XMEM_LAZY_COMMIT=1;X2W_XMEM_LAZY_STARTUP=1") # Control: with X2W_XMEM_LAZY_STARTUP off, the startup blocks are committed as before. add_test(NAME xmem_lazy_startup_off COMMAND "${INTAKE_PYTHON}" -B @@ -388,6 +431,12 @@ set_target_properties(d3d12_xs_shim PROPERTIES OUTPUT_NAME d3d12_xs) target_include_directories(d3d12_xs_shim PRIVATE src) target_compile_features(d3d12_xs_shim PRIVATE cxx_std_17) target_link_libraries(d3d12_xs_shim PRIVATE d3d12) +# X2W_NATIVE_SHADERS: the stand-in translates slot 67 compute requests in-process +# (src/startup_stubs/d3d12_compute_dispatch.inl). Both use the static CRT. +if(TARGET x2w_shader_compiler) + target_link_libraries(d3d12_xs_shim PRIVATE x2w_shader_compiler) + target_compile_definitions(d3d12_xs_shim PRIVATE X2W_NATIVE_SHADERS) +endif() # The creation-IID gate and refusal text of D3D12XboxCreateDevice (src/d3d12x_device_slots.h), # without a device. The mutated run is the negative control. add_executable(d3d12x_device_slots_check tests/d3d12x_device_slots_check.cpp src/d3d12x_device_slots.cpp) @@ -551,11 +600,15 @@ target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 d3dcompiler dxgi x2w_bu target_compile_options(d3d12_xs_shim PRIVATE /bigobj) set_target_properties(xmem_shim d3d12_xs_shim ${startup_stub_targets} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -# Developer-only measurement build: Tracy zones in the stand-ins (src/startup_stubs/profile_zone.h). +# Exactly what tools/startup/run.ps1 copies next to the title (xmem, d3d12_xs, AcpHal, XCRDAPI, chad, xapu, xg_xs and +# GameInput .dll) and the build revision stamp, without the test executables: `cmake --build --preset runtime`. +add_custom_target(startup_runtime) +add_dependencies(startup_runtime xmem_shim d3d12_xs_shim ${startup_stub_targets} x2w_build_rev_generate) +# Developer-only measurement build: Tracy zones and memory pools in the stand-ins (src/startup_stubs/profile_zone.h). # One shared TracyClient.dll serves every instrumented DLL. Off (the default), nothing is fetched, defined or linked. # On, Tracy (BSD-3-Clause, see docs/startup-runtime.md) is fetched at the pinned commit below, or taken from an existing # checkout with -DFETCHCONTENT_SOURCE_DIR_TRACY=. The client opens a local socket; see docs/startup-runtime.md. -option(X2W_TRACY "Instrument the startup stand-ins with Tracy zones (fetches Tracy v0.15.0)" OFF) +option(X2W_TRACY "Instrument the startup stand-ins with Tracy zones and memory pools (fetches Tracy v0.15.0)" OFF) if(X2W_TRACY) include(FetchContent) set(CMAKE_POLICY_DEFAULT_CMP0091 NEW) # Tracy's 3.13 minimum would otherwise ignore MSVC_RUNTIME_LIBRARY @@ -576,7 +629,8 @@ if(X2W_TRACY) RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") foreach(target IN ITEMS d3d12_xs_shim startup_stub_xcrdapi xmem_shim) target_link_libraries(${target} PRIVATE Tracy::TracyClient) - target_compile_definitions(${target} PRIVATE X2W_TRACY=1) + target_compile_definitions(${target} PRIVATE X2W_TRACY=1 X2W_TRACY_HEAP="${target} C++ heap") + target_sources(${target} PRIVATE src/startup_stubs/tracy_new.cpp) endforeach() endif() add_executable(startup_null_views_check tests/startup_null_views_check.cpp) @@ -614,6 +668,30 @@ target_compile_features(startup_null_texture_view_check PRIVATE cxx_std_17) add_test(NAME startup_null_texture_view COMMAND startup_null_texture_view_check) add_test(NAME startup_null_texture_view_unchecked_fallback_control COMMAND startup_null_texture_view_check --mutate unchecked-fallback) set_tests_properties(startup_null_texture_view_unchecked_fallback_control PROPERTIES WILL_FAIL TRUE) +# Device views with ViewDimension 0 (UNKNOWN) or a dimension that does not fit the resource +# (src/startup_stubs/view_dimension.h). The control must FAIL. +add_executable(startup_view_dimension tests/startup_view_dimension_check.cpp) +target_include_directories(startup_view_dimension PRIVATE src) +target_compile_features(startup_view_dimension PRIVATE cxx_std_17) +add_test(NAME startup_view_dimension COMMAND startup_view_dimension) +add_test(NAME startup_view_dimension_control COMMAND startup_view_dimension --control) +set_tests_properties(startup_view_dimension_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# The same through d3d12_xs.dll: an unknown-dimension SRV samples its texture's colour, an incompatible explicit SRV is +# refused without device removal, and a refused replacement leaves a null descriptor, not the slot's old view. The +# off control (X2W_D3D12_VIEW_DEFAULTS=off) must fail on the missing default view alone, with the device not removed. +add_executable(startup_view_dimension_device tests/startup_view_dimension_device.cpp) +target_compile_features(startup_view_dimension_device PRIVATE cxx_std_17) +target_link_libraries(startup_view_dimension_device PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_view_dimension_${backend} COMMAND startup_view_dimension_device ${backend}) + set_tests_properties(startup_view_dimension_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0") +endforeach() +add_test(NAME startup_view_dimension_off_control_warp COMMAND startup_view_dimension_device warp off) +set_tests_properties(startup_view_dimension_off_control_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_D3D12_VIEW_DEFAULTS=off" + PASS_REGULAR_EXPRESSION "FAIL: \\(a\\) default view reads 0\\.000 0\\.000 0\\.000 0\\.000, expected 0\\.200 0\\.600 0\\.800 1\\.000; device not removed.*cases complete" + FAIL_REGULAR_EXPRESSION "FAIL: setup|FAIL: \\(b\\)|FAIL: \\(c\\)|FAIL: \\(d\\)|DEVICE REMOVED|removed the device") # The slot and label of the x2w-render totals line each null-binding cause is counted under # (src/startup_stubs/null_binding_cause.h). The mutated run is the negative control. add_executable(startup_null_cause_labels_check tests/startup_null_cause_labels_check.cpp) @@ -710,6 +788,9 @@ set_tests_properties(startup_placement_publish_shrink_control PROPERTIES WILL_FA add_executable(startup_resource_address_index_check tests/startup_resource_address_index_check.cpp) target_compile_features(startup_resource_address_index_check PRIVATE cxx_std_17) target_include_directories(startup_resource_address_index_check PRIVATE src) +# The 180000 lookups walk std::multimap and std::map nodes; MSVC Debug iterator checks (level 2) made that take +# minutes. The test checks the lookup answers, not iterator validity, so this one target runs without them. +target_compile_definitions(startup_resource_address_index_check PRIVATE $<$,$>:_ITERATOR_DEBUG_LEVEL=0>) add_test(NAME startup_resource_address_index COMMAND startup_resource_address_index_check) add_test(NAME startup_resource_address_index_skip_control COMMAND startup_resource_address_index_check --mutate skip) add_test(NAME startup_resource_address_index_unsync_control COMMAND startup_resource_address_index_check --mutate unsync) @@ -749,6 +830,15 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_list_copy_texture_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +# Stage-by-stage trace and regression for horizontal alternating row bands on textured indexed UI draws (#3132). +add_executable(startup_ui_texture_bands_check tests/startup_ui_texture_bands_check.cpp) +target_compile_features(startup_ui_texture_bands_check PRIVATE cxx_std_17) +target_link_libraries(startup_ui_texture_bands_check PRIVATE d3d12_xs_shim startup_stub_xg_xs d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_ui_texture_bands_${backend} COMMAND startup_ui_texture_bands_check ${backend}) + set_tests_properties(startup_ui_texture_bands_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() add_executable(startup_storage_file_range tests/startup_storage_file_range.cpp) target_compile_features(startup_storage_file_range PRIVATE cxx_std_17) target_include_directories(startup_storage_file_range PRIVATE src) @@ -836,6 +926,19 @@ set_tests_properties(startup_storage_refused_reuse startup_storage_refused_reuse set_tests_properties(startup_storage_refused_reuse_accept_refused_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: R1 destination taken as data matches the stream prefix in 0 of 4096 byte") +# #2788: the DirectStorage stand-in frees its COM objects at final Release, the queue's worker leaves +# before the queue is freed, and a pending entry keeps the status array and source file it uses alive +# after the guest releases them. The control deletes at zero without that accounting and must fail. +add_executable(startup_xcrdapi_lifetime tests/startup_xcrdapi_lifetime.cpp) +target_compile_features(startup_xcrdapi_lifetime PRIVATE cxx_std_17) +add_dependencies(startup_xcrdapi_lifetime startup_stub_xcrdapi) +add_test(NAME startup_xcrdapi_lifetime + COMMAND startup_xcrdapi_lifetime "$") +add_test(NAME startup_xcrdapi_lifetime_naive_control + COMMAND startup_xcrdapi_lifetime "$" control) +set_tests_properties(startup_xcrdapi_lifetime startup_xcrdapi_lifetime_naive_control PROPERTIES TIMEOUT 60) +set_tests_properties(startup_xcrdapi_lifetime_naive_control PROPERTIES WILL_FAIL TRUE) + # Test-only BCPack encoder (tests/bcpack_encoder.h): random synthetic streams must decode back to their # symbols. Interleaving with a 7-byte cycle budget is the negative control. add_executable(bcpack_encoder_check tests/bcpack_encoder_check.cpp) @@ -922,6 +1025,17 @@ if(X2W_WITH_OPUS) add_dependencies(startup_xapu_opus_check startup_stub_xapu) add_test(NAME startup_xapu_opus COMMAND startup_xapu_opus_check "$") set_tests_properties(startup_xapu_opus PROPERTIES TIMEOUT 60) + + # Bounded telemetry for the same optional decode path: decoded packets, dequeued completions and + # refusals by reason. Generates its tones with libopus; no captured packet is stored. + add_executable(startup_xapu_opus_count_check tests/startup_xapu_opus_count_check.cpp) + target_compile_features(startup_xapu_opus_count_check PRIVATE cxx_std_17) + target_include_directories(startup_xapu_opus_count_check PRIVATE src) + target_link_libraries(startup_xapu_opus_count_check PRIVATE Opus::opus) + set_target_properties(startup_xapu_opus_count_check PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_dependencies(startup_xapu_opus_count_check startup_stub_xapu) + add_test(NAME startup_xapu_opus_count COMMAND startup_xapu_opus_count_check "$") + set_tests_properties(startup_xapu_opus_count PROPERTIES TIMEOUT 60) endif() add_executable(startup_chad_check tests/startup_chad_check.cpp) @@ -929,6 +1043,15 @@ target_compile_features(startup_chad_check PRIVATE cxx_std_17) add_dependencies(startup_chad_check startup_stub_chad) add_test(NAME startup_chad_check COMMAND startup_chad_check "$") set_tests_properties(startup_chad_check PROPERTIES TIMEOUT 60) +# Activity counter of the AcpHal and XApu stand-ins (X2W_AUDIO_ACTIVITY=1): exact counts, a zero-write control, the +# same results with the counter on and off, and a caller that unloads both DLLs and must exit cleanly +# (docs/startup-runtime.md). +add_executable(startup_acphal_xma_activity tests/startup_acphal_xma_activity.cpp) +target_compile_features(startup_acphal_xma_activity PRIVATE cxx_std_17) +add_dependencies(startup_acphal_xma_activity startup_stub_acphal startup_stub_xapu) +add_test(NAME startup_acphal_xma_activity COMMAND startup_acphal_xma_activity "$" + "$") +set_tests_properties(startup_acphal_xma_activity PROPERTIES TIMEOUT 60) # BMP writer of the draw dumps (src/startup_stubs/draw_bmp.h); the mutated runs are negative controls. add_executable(startup_draw_bmp_check tests/startup_draw_bmp.cpp) @@ -941,6 +1064,10 @@ endforeach() add_executable(startup_command_list_slot_names tests/startup_command_list_slot_names.cpp) target_compile_features(startup_command_list_slot_names PRIVATE cxx_std_17) add_test(NAME startup_command_list_slot_names COMMAND startup_command_list_slot_names) +# Root constants kept per recorded list (src/startup_stubs/root_constant_store.h, compute list slots 37 and 39, #870; slot 40 keeps its own graphics words). +add_executable(startup_root_constant_store tests/startup_root_constant_store.cpp) +target_compile_features(startup_root_constant_store PRIVATE cxx_std_17) +add_test(NAME startup_root_constant_store COMMAND startup_root_constant_store) # Game-save stand-in storage (src/startup_stubs/save_store.h): a blob written by one process is read by a second. add_executable(startup_gamesave_persist tests/startup_gamesave_persist.cpp) target_compile_features(startup_gamesave_persist PRIVATE cxx_std_17) @@ -1055,6 +1182,24 @@ target_compile_features(startup_runtime_gpa_patch PRIVATE cxx_std_17) add_test(NAME startup_runtime_gpa_patch COMMAND startup_runtime_gpa_patch) add_test(NAME startup_runtime_gpa_patch_name_only_control COMMAND startup_runtime_gpa_patch --mutate name-only) set_tests_properties(startup_runtime_gpa_patch_name_only_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# X2W_DEVICE_TYPE: the OEM ConsoleMode registry read, answered or passed on, against fake registry +# functions. A source-built decoy DLL exports the same registry names and must stay unhooked. The +# control leaves the switch unset for the answered cases; the provider control matches registry +# imports by name alone. Both must FAIL. +add_library(startup_console_mode_decoy SHARED + tests/startup_console_mode_decoy.cpp + tests/startup_console_mode_decoy.def) +target_compile_features(startup_console_mode_decoy PRIVATE cxx_std_17) +add_executable(startup_console_mode tests/startup_console_mode_check.cpp) +target_include_directories(startup_console_mode PRIVATE src) +target_compile_features(startup_console_mode PRIVATE cxx_std_17) +add_dependencies(startup_console_mode startup_console_mode_decoy) +add_test(NAME startup_console_mode COMMAND startup_console_mode --decoy "$") +add_test(NAME startup_console_mode_control + COMMAND startup_console_mode --control --decoy "$") +add_test(NAME startup_console_mode_provider_control + COMMAND startup_console_mode --control provider --decoy "$") +set_tests_properties(startup_console_mode_control startup_console_mode_provider_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, # unrelated same-named export stays original. Notification only enqueues; rewrite runs after link. if (WIN32) @@ -1116,6 +1261,14 @@ target_compile_features(startup_debug_probe PRIVATE cxx_std_17) # The DLL the probe calls for the debugger's call-hook case (--trace-calls). add_library(startup_debug_calls SHARED tests/startup_debug_calls.cpp) add_dependencies(startup_debug_probe startup_debug_calls) +# Input for the launcher's --map-drive check (tests/startup_map_drive_check.py): the consumer opens its +# package through a mapped letter, and the launcher rewrites that open. +add_executable(startup_map_drive_consumer tests/startup_map_drive_consumer.cpp) +target_compile_features(startup_map_drive_consumer PRIVATE cxx_std_17) +# A visible window that changes its picture at a known time: input for the --capture-every check (tests/startup_debug_window_check.py). +add_executable(startup_window_probe tests/startup_window_probe.cpp) +target_compile_features(startup_window_probe PRIVATE cxx_std_17) +target_link_libraries(startup_window_probe PRIVATE user32 gdi32) # Input for tests/startup_inflate_check.py: the DirectStorage stand-in's zlib decoder on one stream. add_executable(startup_inflate_probe tests/startup_inflate_probe.cpp) target_compile_features(startup_inflate_probe PRIVATE cxx_std_17) @@ -1148,6 +1301,11 @@ target_compile_features(startup_overlay_window PRIVATE cxx_std_17) target_include_directories(startup_overlay_window PRIVATE src) target_link_libraries(startup_overlay_window PRIVATE user32) add_test(NAME startup_overlay_window COMMAND startup_overlay_window) +# Text of the x2w-budget commit fields and the commit-exhausted line (src/startup_stubs/commit_state.h). +add_executable(startup_commit_state_check tests/startup_commit_state_check.cpp) +target_compile_features(startup_commit_state_check PRIVATE cxx_std_17) +target_include_directories(startup_commit_state_check PRIVATE src) +add_test(NAME startup_commit_state COMMAND startup_commit_state_check) # WASAPI render sink (Refs #1145); exit 77 when the machine has no usable render endpoint. The sink is # compiled once for this check and the pacing control below. add_library(startup_audio_sink_obj OBJECT src/startup_stubs/audio_sink.cpp) @@ -1195,6 +1353,17 @@ add_test(NAME startup_dump_fence_removed_control_warp COMMAND startup_dump_fence set_tests_properties(startup_dump_fence_removed_control_warp PROPERTIES ENVIRONMENT "X2W_SHIM_DRAW_ADAPTER=warp" TIMEOUT 45 WILL_FAIL TRUE) +# Per-draw texel history: three source-built draws where only the second covers the watched texel, +# then a control without that draw. The report must name draw 2 and leave the texel black in the control. +add_executable(startup_pixel_history tests/startup_pixel_history.cpp tests/desktop_gpu.cpp) +target_compile_features(startup_pixel_history PRIVATE cxx_std_17) +target_include_directories(startup_pixel_history PRIVATE src) +target_link_libraries(startup_pixel_history PRIVATE d3d12 dxgi d3dcompiler) +add_test(NAME startup_pixel_history_warp COMMAND startup_pixel_history) +set_tests_properties(startup_pixel_history_warp PROPERTIES TIMEOUT 60) +add_test(NAME startup_pixel_history_hardware COMMAND startup_pixel_history hardware) +set_tests_properties(startup_pixel_history_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(startup_typed_buffer_view tests/startup_typed_buffer_view.cpp) target_compile_features(startup_typed_buffer_view PRIVATE cxx_std_17) add_test(NAME startup_typed_buffer_view COMMAND startup_typed_buffer_view) @@ -1209,6 +1378,17 @@ target_link_libraries(startup_stream_consumer PRIVATE d3d12_xs_shim startup_stub target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_root_reset.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_memory_srv_diag.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_pixel_uav.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_rect_gap.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_slot67_indirect.cpp tests/desktop_gpu.cpp) + +# The shared indexed rectangle-expansion stage (startup_stubs/indexed_rect_geometry.h) drawn on its own, with +# back-face culling on: the axis order, a swung order of the same corners and a rotated rectangle (#3131). +# tests/cmake/startup_rect_gap.cmake registers its tests and the runtime draw. +add_executable(startup_rect_geometry tests/startup_rect_geometry.cpp) +target_compile_features(startup_rect_geometry PRIVATE cxx_std_17) +target_include_directories(startup_rect_geometry PRIVATE src) +target_link_libraries(startup_rect_geometry PRIVATE d3d12 dxgi d3dcompiler) add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) @@ -1371,6 +1551,46 @@ foreach(backend IN ITEMS warp hardware) endforeach() +# X2W_D3D12_VIEW_CENSUS=1 counts new distinct view records by slot and logs capacity and buckets before they grow. +# `off` runs without the switch (nothing reported); `vary` is the negative control: the repeated stream is made distinct, +# and the fixture must say so. +add_executable(startup_view_census tests/startup_view_census.cpp) +target_compile_features(startup_view_census PRIVATE cxx_std_17) +target_link_libraries(startup_view_census PRIVATE d3d12_xs_shim d3d12 dxgi psapi) +foreach(backend IN ITEMS warp hardware) + foreach(mode IN ITEMS on off vary) + set(census_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + list(APPEND census_env "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/startup_view_census_${mode}_${backend}.log") + if(NOT mode STREQUAL "off") + list(APPEND census_env "X2W_D3D12_VIEW_CENSUS=1") + endif() + if(mode STREQUAL "on") + set(census_test startup_view_census_${backend}) + add_test(NAME ${census_test} COMMAND startup_view_census ${backend}) + else() + set(census_test startup_view_census_${mode}_${backend}) + add_test(NAME ${census_test} COMMAND startup_view_census ${backend} ${mode}) + endif() + set_tests_properties(${census_test} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "${census_env}") + if(mode STREQUAL "vary") + set_tests_properties(${census_test} PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: the repeated stream added records") + endif() + endforeach() +endforeach() + +# #2653: a failed wrapper allocation returns E_OUTOFMEMORY with a null output from device creation and slots 8, 9, 14, +# 16, 55, 73, 127 and both paths through slot 133. `control` never arms the failure. +add_executable(startup_wrap_allocation tests/startup_wrap_allocation.cpp) +target_compile_features(startup_wrap_allocation PRIVATE cxx_std_17) +target_link_libraries(startup_wrap_allocation PRIVATE d3d12_xs_shim d3d12 dxgi) +add_test(NAME startup_wrap_allocation_warp COMMAND startup_wrap_allocation) +add_test(NAME startup_wrap_allocation_control_warp COMMAND startup_wrap_allocation control) +set_tests_properties(startup_wrap_allocation_warp startup_wrap_allocation_control_warp PROPERTIES + TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0") +set_tests_properties(startup_wrap_allocation_control_warp PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: Device::slot55 derived pipeline with the wrapper allocation failing") + add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) target_include_directories(startup_resource_retire_title PRIVATE src) target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) @@ -1387,8 +1607,8 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_RESOURCE_INDEX_CHECK=1;X2W_D3D12_DEBUG=0") endforeach() -# X2W_D3D12_RELEASE_RETIRED_VIEWS=1 frees a released class texture that only tracked slot-18 descriptor slots keep alive by -# replacing those slots with null descriptors. `keep` is the negative control (views switch off, or retire switch off). +# Preserve live SRVs and their copies with and without the legacy views switch. Also verify that an +# explicit overwrite permits ordinary retirement, and that disabling base retirement keeps the resource. add_executable(startup_resource_retire_views tests/startup_resource_retire_views.cpp) target_include_directories(startup_resource_retire_views PRIVATE src) target_compile_features(startup_resource_retire_views PRIVATE cxx_std_17) @@ -1401,7 +1621,7 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "${retire_views_env};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_RELEASE_RETIRED_VIEWS=1") endforeach() set(retire_views_keep "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") - add_test(NAME startup_resource_retire_views_keep_${backend} COMMAND startup_resource_retire_views ${backend} keep) + add_test(NAME startup_resource_retire_views_keep_${backend} COMMAND startup_resource_retire_views ${backend}) set_tests_properties(startup_resource_retire_views_keep_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${retire_views_keep};X2W_D3D12_RELEASE_RETIRED=1") add_test(NAME startup_resource_retire_views_noretire_${backend} COMMAND startup_resource_retire_views ${backend} keep) @@ -1421,9 +1641,16 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_dispatch_${backend} COMMAND startup_indirect_dispatch ${backend}) add_test(NAME startup_indirect_root_constants_${backend} COMMAND startup_indirect_dispatch ${backend} constants) add_test(NAME startup_indirect_count_${backend} COMMAND startup_indirect_dispatch ${backend} count) - set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} PROPERTIES TIMEOUT 30) + # The same cases with the opt-in split of a batched or counted Dispatch into single commands + # (split_indirect_dispatch.h), plus the follow-up Dispatch and the pending-allocator reset. The plain count tests + # keep the native call. + add_test(NAME startup_indirect_count_split_${backend} COMMAND startup_indirect_dispatch ${backend} count) + set_tests_properties(startup_indirect_count_split_${backend} PROPERTIES ENVIRONMENT "X2W_SPLIT_INDIRECT_DISPATCH=1") + set_tests_properties(startup_indirect_dispatch_${backend} startup_indirect_root_constants_${backend} startup_indirect_count_${backend} + startup_indirect_count_split_${backend} PROPERTIES TIMEOUT 30) endforeach() -set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware startup_indirect_count_hardware PROPERTIES SKIP_RETURN_CODE 77) +set_tests_properties(startup_indirect_dispatch_hardware startup_indirect_root_constants_hardware startup_indirect_count_hardware + startup_indirect_count_split_hardware PROPERTIES SKIP_RETURN_CODE 77) # Occlusion queries recorded through command-list slots 28 to 30 reach the readback buffer (#870). add_executable(startup_list_queries tests/startup_list_queries.cpp tests/desktop_gpu.cpp) @@ -1447,6 +1674,7 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} draw) add_test(NAME startup_indirect_translated_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated) add_test(NAME startup_indirect_translated_refusal_census_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated-refusal-census) + add_test(NAME startup_indirect_translated_targets_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated-targets) add_test(NAME startup_indirect_other_refusal_census_${backend} COMMAND startup_indirect_draw_indexed ${backend} indirect-other-refusal-census) add_test(NAME startup_indirect_copy_provenance_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance) add_test(NAME startup_indirect_copy_provenance_off_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance-off) @@ -1471,6 +1699,7 @@ foreach(backend IN ITEMS warp hardware) startup_indirect_mesh_amplified_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_translated_draw_${backend} startup_indirect_translated_refusal_census_${backend} + startup_indirect_translated_targets_${backend} startup_indirect_other_refusal_census_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_copy_provenance_${backend} startup_indirect_copy_provenance_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) @@ -1490,6 +1719,9 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_indirect_mesh_request_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_MESH_REQUEST_FIXTURE=1") endforeach() +add_test(NAME startup_missing_shader_fallback_warp COMMAND startup_indirect_draw_indexed warp missing-shader-fallback) +add_test(NAME startup_missing_shader_fallback_off_warp COMMAND startup_indirect_draw_indexed warp missing-shader-fallback-off) +set_tests_properties(startup_missing_shader_fallback_warp startup_missing_shader_fallback_off_warp PROPERTIES TIMEOUT 60) # Negative control for the x2w-render indirect line: one forwarded call too many must be reported as a mismatch. add_test(NAME startup_indirect_counts_control_warp COMMAND startup_indirect_draw_indexed warp count-control) # "got" is printed only for a mismatch, and the pattern holds the real counts. No semicolons: CMake would split it. @@ -1508,11 +1740,12 @@ add_test(NAME startup_indirect_other_refusal_census_control_warp set_tests_properties(startup_indirect_other_refusal_census_control_warp PROPERTIES TIMEOUT 60 PASS_REGULAR_EXPRESSION "got +'x2w-d3d12 indirect-other refusals: total 3. distinct keys 2, distinct pairs 2 \\(overflow calls 0\\)'") -# Teardown of the two per-device caches that keep desktop D3D12 objects (#2572): the built d3d12_xs.dll is +# Teardown of the four per-device caches that keep desktop D3D12 objects (#2572): the built d3d12_xs.dll is # loaded by explicit path, warmed through its own probe, then unloaded -- the caches must release what they -# own and the module must go -- and a second load is left to process termination, where the caches must -# release nothing because the display driver is already stopped. This check runs the built DLL itself, so -# unlike the Python-driven startup_* tests it needs no INTAKE_PYTHON guard. +# own and the module must go -- and a second load is run in a child process that leaves the module loaded to +# process termination, where the caches must detach every owned reference (the shim reports it under +# X2W_TEARDOWN_REPORT, and X2W_TEARDOWN_NO_GUARD has to make that check fail). This check runs the built DLL +# itself, so unlike the Python-driven startup_* tests it needs no INTAKE_PYTHON guard. add_executable(startup_teardown_unload tests/startup_teardown_unload.cpp) target_compile_features(startup_teardown_unload PRIVATE cxx_std_17) target_link_libraries(startup_teardown_unload PRIVATE d3d12 dxgi) @@ -1681,6 +1914,202 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) + +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend warp hardware) + add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_mrt_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_mrt_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_varying_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_varying_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_TEST_NATIVE_MESH57_VARYING=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_uint_heap_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_uint_heap_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_UINT_HEAP=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_pixel_heap_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_pixel_heap_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_PIXEL_HEAP=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_waterfall_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_waterfall_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_WATERFALL=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_waterfall_fine_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_waterfall_fine_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_WATERFALL=1;X2W_TEST_NATIVE_MESH57_FINE_LOD=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_buffers_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_buffers_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_BUFFERS=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_constant_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_constant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_CONSTANT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_mask_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_mask_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_TEST_NATIVE_MESH57_MASK=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() + add_executable(native_store_replay tests/native_store_replay.cpp tests/desktop_gpu.cpp) + target_include_directories(native_store_replay PRIVATE src tests) + target_link_libraries(native_store_replay PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_store_replay PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_scalar_lds_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_scalar_lds_check.py" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_scalar_lds_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_adjacent_srv_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_adjacent_srv_check.py" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_adjacent_srv_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_mtbuf_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mtbuf_check.py" "$" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_mtbuf_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_indexed_atomic_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_indexed_atomic_check.py" "$" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_indexed_atomic_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(native_wave_request_gpu tests/native_wave_request_gpu.cpp tests/native_compute_grid.cpp tests/native_half_grid.cpp tests/desktop_gpu.cpp) + target_link_libraries(native_wave_request_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_wave_request_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_wave_request_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave_request_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_wave_request_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_executable(native_lds_gpu tests/native_lds_gpu.cpp tests/desktop_gpu.cpp) + target_link_libraries(native_lds_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_lds_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_executable(native_sampled_pixel_gpu tests/native_sampled_pixel_gpu.cpp tests/desktop_gpu.cpp) + add_executable(native_buffered_vertex_gpu tests/native_buffered_vertex_gpu.cpp tests/desktop_gpu.cpp) + target_link_libraries(native_buffered_vertex_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_buffered_vertex_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_link_libraries(native_sampled_pixel_gpu PRIVATE x2w_shader_compiler d3d12 dxgi) + set_target_properties(native_sampled_pixel_gpu PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_sampled_replay COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_sampled_replay_check.py" + "$" "$" "${DXC_BIN_DIR}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_indexed_pixel_texture_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_indexed_pixel_texture_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_indexed_pixel_texture_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_buffered_vertex_${backend} COMMAND native_buffered_vertex_gpu ${backend} "${DXC_BIN_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}/native-buffered-${backend}") + set_tests_properties(native_buffered_vertex_${backend} PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_sampled_pixel_${backend} COMMAND native_sampled_pixel_gpu ${backend} "${DXC_BIN_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}/native-sampled-${backend}") + set_tests_properties(native_sampled_pixel_${backend} PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_lds_${backend} COMMAND native_lds_gpu ${backend} "${DXC_BIN_DIR}" + "${CMAKE_SOURCE_DIR}/tests/native_lds_gpu.hlsl" "${CMAKE_CURRENT_BINARY_DIR}/native-lds-${backend}") + set_tests_properties(native_lds_${backend} PROPERTIES SKIP_RETURN_CODE 77) + endforeach() + add_test(NAME native_lds_control_flow COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_lds_control_flow_check.py") + add_test(NAME native_compute_clear COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_clear_check.py" "$" "${DXC_BIN_DIR}") + add_test(NAME native_compute_raw_root COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_raw_root_check.py" "$" "${DXC_BIN_DIR}") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_native_graphics_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_native_graphics_draw_check.py" + "$" "${DXC_BIN_DIR}" ${adapter} "$") + set_tests_properties(startup_native_graphics_draw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + foreach(backend IN ITEMS hardware warp) + add_test(NAME native_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_descriptor_scc_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME startup_compute_descriptor_scc_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_descriptor_scc_check.py" runtime "$" + "$" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(startup_compute_descriptor_scc_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() + add_test(NAME native_direct_container + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" + "$" "${DXC_BIN_DIR}") + add_test(NAME native_direct_mesh + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_direct_mesh_check.py" + "$" "${DXC_BIN_DIR}") + add_executable(native_frozen_request_check tests/native_frozen_request_check.cpp) + target_include_directories(native_frozen_request_check PRIVATE src) + target_compile_features(native_frozen_request_check PRIVATE cxx_std_17) + target_link_libraries(native_frozen_request_check PRIVATE x2w_shader_compiler) + set_property(TARGET native_frozen_request_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_frozen_request COMMAND native_frozen_request_check) + add_executable(native_compute_pack_check tests/native_compute_pack_check.cpp) + target_link_libraries(native_compute_pack_check PRIVATE x2w_shader_compiler) + target_include_directories(native_compute_pack_check PRIVATE src) + target_compile_features(native_compute_pack_check PRIVATE cxx_std_17) + set_property(TARGET native_compute_pack_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_compute_pack COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_pack_check.py" "$" + "$" "${DXC_BIN_DIR}") + add_test(NAME native_compute_pack_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_pack_check.py" hardware "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_pack_hardware PROPERTIES SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + foreach(case IN ITEMS r rg rgb array volume rgba sparse) + add_test(NAME native_image_store_exact_width_${adapter}_${case} + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_image_store_exact_width_check.py" + "$" "${DXC_BIN_DIR}" "$" ${adapter} ${case}) + set_tests_properties(native_image_store_exact_width_${adapter}_${case} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + endforeach() + add_test(NAME native_dpp_mirror_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_mirror_check.py" "$" + "$" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_mirror_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_graphics_wqm_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_graphics_wqm_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_graphics_wqm_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + foreach(adapter warp hardware) + add_test(NAME native_graphics_sampler_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_graphics_sampler_heap_check.py" "$" + "$" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_graphics_sampler_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() + add_test(NAME native_graphics_interface_library + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_graphics_interface_library_check.py" + "$" "${DXC_BIN_DIR}") + add_executable(native_recording_check tests/native_recording_check.cpp) + target_include_directories(native_recording_check PRIVATE src) + target_compile_features(native_recording_check PRIVATE cxx_std_17) + target_link_libraries(native_recording_check PRIVATE x2w_shader_compiler dxgi d3d12) + set_property(TARGET native_recording_check PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_test(NAME native_comparison_pso_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --sampler-pso + "${DXC_BIN_DIR}" "$") + set_tests_properties(native_comparison_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_graphics_comparison_pso_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --graphics-sampler-pso + "${DXC_BIN_DIR}" "$") + set_tests_properties(native_graphics_comparison_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + # Cycle 1 of the global SRV work: ResourceDescriptorHeap[index] from a native DXIL module against a DXC reference. + add_executable(native_heap_handle_probe tests/native_heap_handle_probe.cpp) + target_include_directories(native_heap_handle_probe PRIVATE src) + target_compile_features(native_heap_handle_probe PRIVATE cxx_std_17) + target_link_libraries(native_heap_handle_probe PRIVATE x2w_shader_compiler dxgi d3d12) + set_property(TARGET native_heap_handle_probe PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_heap_handle_probe_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_heap_handle_probe_check.py" "$" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_heap_handle_probe_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() + add_test(NAME native_recording_pages_warp COMMAND native_recording_check) + add_test(NAME native_dispatch_states_warp COMMAND native_recording_check --subresources) + set_tests_properties(native_dispatch_states_warp PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(native_recording_pages_warp PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_rectangle_pso_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --rect-pso + "$" "${DXC_BIN_DIR}" "$") + set_tests_properties(native_rectangle_pso_warp PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME native_rectangle_geometry_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_direct_container_check.py" --rect-pso + "$" "${DXC_BIN_DIR}" "$" + "$") + set_tests_properties(native_rectangle_geometry_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_pixel_dxil + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_pixel_dxil_check.py" + "$" "${DXC_BIN_DIR}") +endif() target_compile_definitions(root_probe PRIVATE SDK_DXC_DIR=L"${DXC_BIN_DIR}/") add_executable(offscreen_check tests/offscreen_check.cpp tests/compute_check.cpp tests/dxr_check.cpp tests/buffer_ops.cpp tests/descriptor_heap_paging.cpp) @@ -1751,6 +2180,7 @@ if(OFFSCREEN_AGILITY_620_DIR) endforeach() target_compile_definitions(offscreen_check PRIVATE OFFSCREEN_AGILITY_620) target_compile_definitions(startup_indirect_draw_indexed PRIVATE OFFSCREEN_AGILITY_620) + target_compile_definitions(startup_stream_consumer PRIVATE OFFSCREEN_AGILITY_620) endif() set(OFFSCREEN_WARP_DIR "" CACHE PATH "Directory containing an app-local x64 d3d10warp.dll (Microsoft.Direct3D.WARP)") if(OFFSCREEN_WARP_DIR) @@ -1809,6 +2239,29 @@ add_custom_command(OUTPUT "${pixel_vs_linear}" COMMAND "${DXC_EXECUTABLE}" -T vs target_sources(offscreen_check PRIVATE tests/pixel_aot_render.cpp tests/pixel_compare_render.cpp "${pixel_vs}" "${pixel_vs_linear}") target_sources(offscreen_check PRIVATE tests/desktop_gpu.cpp tests/mesh_entry_draw.cpp tests/mesh_shadow_draw.cpp) +add_executable(meshlet_builder_check tests/meshlet_builder_check.cpp src/meshlet_builder.cpp) +target_include_directories(meshlet_builder_check PRIVATE src) +target_compile_features(meshlet_builder_check PRIVATE cxx_std_17) +add_test(NAME meshlet_builder COMMAND meshlet_builder_check) +set_tests_properties(meshlet_builder PROPERTIES TIMEOUT 30) + +set(meshlet_pipeline_headers) +foreach(stage_spec IN ITEMS "as:as_6_5:ASMain" "ms:ms_6_5:MSMain" "vs:vs_6_0:VSMain" "ps:ps_6_0:PSMain") + string(REPLACE ":" ";" stage_parts "${stage_spec}") + list(GET stage_parts 0 stage_name) + list(GET stage_parts 1 stage_profile) + list(GET stage_parts 2 stage_entry) + set(header "${CMAKE_CURRENT_BINARY_DIR}/meshlet_pipeline_${stage_name}.h") + add_custom_command(OUTPUT "${header}" + COMMAND "${DXC_EXECUTABLE}" -T ${stage_profile} -E ${stage_entry} + -Vn meshlet_pipeline_${stage_name} -Fh "${header}" + "${CMAKE_CURRENT_SOURCE_DIR}/src/shaders/meshlet_pipeline.hlsl" + DEPENDS src/shaders/meshlet_pipeline.hlsl VERBATIM) + list(APPEND meshlet_pipeline_headers "${header}") +endforeach() +target_sources(offscreen_check PRIVATE src/meshlet_builder.cpp src/mesh_shader_pipeline.cpp + tests/mesh_shader_pipeline_draw.cpp ${meshlet_pipeline_headers}) +target_include_directories(offscreen_check PRIVATE src) target_sources(offscreen_check PRIVATE tests/stream_root_srv.cpp) foreach(stage IN ITEMS vs ps) string(TOUPPER "${stage}" entry) @@ -1897,6 +2350,32 @@ foreach(mutation IN ITEMS sampler-alone bind-unrestorable) add_test(NAME startup_heap_indexed_root_${mutation}_control COMMAND startup_heap_indexed_root_check --mutate ${mutation}) set_tests_properties(startup_heap_indexed_root_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Slot 14 (Dispatch) forward-or-refuse decision (src/startup_stubs/list_dispatch.h), without a device. +add_executable(startup_list_dispatch_check tests/startup_list_dispatch_check.cpp) +target_include_directories(startup_list_dispatch_check PRIVATE src) +target_compile_features(startup_list_dispatch_check PRIVATE cxx_std_17) +add_test(NAME startup_list_dispatch COMMAND startup_list_dispatch_check) +foreach(mutation IN ITEMS no-limit no-state no-root-args no-pairing no-bound) + add_test(NAME startup_list_dispatch_${mutation}_control COMMAND startup_list_dispatch_check --mutate ${mutation}) + set_tests_properties(startup_list_dispatch_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() +add_executable(upload_reservation_check tests/upload_reservation_check.cpp) +target_include_directories(upload_reservation_check PRIVATE src) +target_compile_features(upload_reservation_check PRIVATE cxx_std_17) +add_test(NAME upload_reservation COMMAND upload_reservation_check) +# The same slot driven through the stand-in on a desktop device: one refusal line per refused case, and the +# forwarded calls counted by a pipeline-statistics query on the desktop list. +add_executable(startup_list_dispatch_native tests/startup_list_dispatch_native.cpp) +target_compile_features(startup_list_dispatch_native PRIVATE cxx_std_17) +target_link_libraries(startup_list_dispatch_native PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_list_dispatch_native_${backend} COMMAND startup_list_dispatch_native ${backend}) + set_tests_properties(startup_list_dispatch_native_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) +endforeach() +# Negative control: without slot 43 the first forwarded case is refused, and the fixture must report it. +add_test(NAME startup_list_dispatch_native_skip_srv_warp_control COMMAND startup_list_dispatch_native warp skip-srv) +set_tests_properties(startup_list_dispatch_native_skip_srv_warp_control PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "bound: expected no Dispatch line, got 1 Dispatch line\\(s\\)[\r\n]+ x2w-render Dispatch\\(2, 3, 1\\) refused: a compute root SRV is not bound") target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) @@ -1923,6 +2402,28 @@ foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_sharedexp_target_${adapter} COMMAND offscreen_check ${adapter} --startup-sharedexp-target) set_tests_properties(startup_sharedexp_target_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) endforeach() +# Presented planes (src/startup_stubs/present_planes.h): the plane record layout and the composite order +# on synthetic records. The control reads 0x40-byte records and composites plane 0 alone, and must FAIL. +add_executable(startup_present_planes tests/startup_present_planes_check.cpp) +target_include_directories(startup_present_planes PRIVATE src) +target_compile_features(startup_present_planes PRIVATE cxx_std_17) +add_test(NAME startup_present_planes COMMAND startup_present_planes) +add_test(NAME startup_present_planes_control COMMAND startup_present_planes --control) +set_tests_properties(startup_present_planes_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# The window's plane composite (src/startup_stubs/plane_compositor.h) read back on WARP: a single-plane +# baseline, stacked planes with transparent, partly transparent and opaque overlays, and skipped repeats +# and empty records. The control then removes the overlays and passes only on "control ok:", printed when +# the baseline matched, every fence completed and the overlay-free picture differs from the stacked +# expectation in exactly the overlay cells. Any FAIL line (setup, fence, device removal, pixels) fails it. +add_executable(startup_present_composite_warp tests/startup_present_composite_warp.cpp) +target_include_directories(startup_present_composite_warp PRIVATE src) +target_compile_features(startup_present_composite_warp PRIVATE cxx_std_17) +target_link_libraries(startup_present_composite_warp PRIVATE d3d12 dxgi d3dcompiler) +add_test(NAME startup_present_composite_warp COMMAND startup_present_composite_warp) +add_test(NAME startup_present_composite_overlay_removed_control_warp COMMAND startup_present_composite_warp --control) +set_tests_properties(startup_present_composite_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +set_tests_properties(startup_present_composite_overlay_removed_control_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 + PASS_REGULAR_EXPRESSION "control ok: baseline matched" FAIL_REGULAR_EXPRESSION "FAIL: ") # Static samplers built from smp and smpc manifest lines (src/startup_stubs/translated_sampler_bindings.h). add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison_check.cpp) target_include_directories(startup_sampler_comparison_check PRIVATE src) @@ -1954,7 +2455,7 @@ add_executable(startup_memory_srv_buffer_check tests/startup_memory_srv_buffer_c target_include_directories(startup_memory_srv_buffer_check PRIVATE src) target_compile_features(startup_memory_srv_buffer_check PRIVATE cxx_std_17) add_test(NAME startup_memory_srv_buffer COMMAND startup_memory_srv_buffer_check) -foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers) +foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers unplaced-heap-limit exact-start raw-exact) add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() @@ -2059,6 +2560,17 @@ endforeach() add_test(NAME startup_committed_heap_state_upload_texture_control COMMAND startup_committed_heap_state_check warp --mutate upload-texture) set_tests_properties(startup_committed_heap_state_hardware PROPERTIES SKIP_RETURN_CODE 77) set_tests_properties(startup_committed_heap_state_upload_texture_control PROPERTIES WILL_FAIL TRUE) +# Device slot 76 (desktop CreateCommittedResource argument order) through the device wrapper: a render +# target with a clear value and buffers on the default, upload and readback heaps. The control asks for a +# 2D texture on an upload heap, which no runtime creates, and must FAIL. +add_executable(startup_committed_slot76_check tests/startup_committed_slot76_check.cpp) +target_compile_features(startup_committed_slot76_check PRIVATE cxx_std_17) +target_link_libraries(startup_committed_slot76_check PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_committed_slot76_${adapter} COMMAND startup_committed_slot76_check ${adapter}) +endforeach() +set_tests_properties(startup_committed_slot76_hardware PROPERTIES SKIP_RETURN_CODE 77) +add_test(NAME startup_committed_slot76_control COMMAND startup_committed_slot76_check warp --control) # Opt-in BC7 4 KiB standard surfaces (src/startup_stubs/bc7_4k_s.h): accepted descriptions, padded # sizes, block order and detile; the mutated run (x-first bit order) is the negative control. add_executable(startup_bc7_4k_s_check tests/startup_bc7_4k_s_check.cpp) @@ -2130,6 +2642,10 @@ add_executable(startup_local_log_check tests/startup_local_log_check.cpp) target_include_directories(startup_local_log_check PRIVATE src) target_compile_features(startup_local_log_check PRIVATE cxx_std_17) add_test(NAME startup_local_log COMMAND startup_local_log_check) +add_test(NAME startup_local_log_precheck_off COMMAND startup_local_log_check --phase precheck-off) +set_tests_properties(startup_local_log_precheck_off PROPERTIES ENVIRONMENT "X2W_PROBE_PRECHECK=0") +add_test(NAME startup_local_log_precheck_off_debugger COMMAND startup_local_log_check --phase precheck-off-debugger) +set_tests_properties(startup_local_log_precheck_off_debugger PROPERTIES ENVIRONMENT "X2W_PROBE_PRECHECK=0") add_test(NAME startup_local_log_guard_drop_control COMMAND startup_local_log_check --mutate guard-drop) set_tests_properties(startup_local_log_guard_drop_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_local_log_reopen_control COMMAND startup_local_log_check --mutate reopen) @@ -2942,6 +3458,13 @@ set_tests_properties(offscreen_invalid_operation_warp PROPERTIES TIMEOUT 45) add_test(NAME offscreen_capability_table_self_test COMMAND offscreen_check --self-test) set_tests_properties(offscreen_capability_table_self_test PROPERTIES TIMEOUT 45) +foreach(adapter IN ITEMS hardware warp) + add_test(NAME mesh_shader_pipeline_${adapter} COMMAND offscreen_check ${adapter} --mesh-shader-pipeline) + add_test(NAME mesh_shader_pipeline_fallback_${adapter} + COMMAND offscreen_check ${adapter} --mesh-shader-pipeline-fallback) + set_tests_properties(mesh_shader_pipeline_${adapter} mesh_shader_pipeline_fallback_${adapter} + PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) +endforeach() foreach(adapter IN ITEMS hardware warp) add_test(NAME descriptor_heap_paging_${adapter} COMMAND offscreen_check ${adapter} --descriptor-heap-paging) add_test(NAME descriptor_heap_paging_swapped_${adapter} @@ -3080,6 +3603,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "$" "$" "$") set_tests_properties(startup_stubs PROPERTIES TIMEOUT 120) + # `cmake --build --preset runtime` builds the eight DLLs run.ps1 copies and no executable. + # It deletes and rebuilds the DLLs other tests load, so it must not run beside them (RUN_SERIAL). + add_test(NAME startup_runtime_target COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_runtime_target_check.py" "${CMAKE_COMMAND}" "${CMAKE_BINARY_DIR}" + "${CMAKE_CURRENT_SOURCE_DIR}/tools/startup/run.ps1" + "$" "$" + "$" "$" "$" + "$" "$" "$") + set_tests_properties(startup_runtime_target PROPERTIES TIMEOUT 300 RUN_SERIAL TRUE) add_test(NAME startup_storage_directory_batch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_storage_directory_batch.py" "$") set_tests_properties(startup_storage_directory_batch PROPERTIES TIMEOUT 30) @@ -3106,6 +3638,17 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_ngg_slice_check.py") add_test(NAME startup_image_sample_l COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_check.py") + add_test(NAME startup_image_sample_d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_d_check.py") + # image_sample_d drawn on D3D12 (FXC 5_1 and DXC 6_0): GPU readback of the mip chosen by explicit gradients. + add_test(NAME startup_image_sample_d_draw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_d_draw_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_d_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_d_draw_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_d_draw_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_image_gather_lz COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_gather_lz_check.py") add_test(NAME startup_compute_gather_lz COMMAND "${INTAKE_PYTHON}" -B @@ -3114,6 +3657,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_gfx2hlsl_image_store_3d1d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_store_3d1d_check.py") + add_test(NAME startup_gfx2hlsl_heap_record COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_record_check.py") + add_test(NAME startup_gfx2hlsl_heap_word COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_heap_word_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_compute_gather_l COMMAND "${INTAKE_PYTHON}" -B @@ -3157,9 +3706,25 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_op_refusals COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_op_refusals_check.py") set_tests_properties(startup_gfx2hlsl_op_refusals PROPERTIES TIMEOUT 60) + # gfx2hlsl carries a descriptor pointer through s_add_u32 / s_addc_u32 with a literal offset (#1723). + add_test(NAME startup_joined_table_pointer_cpu COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_joined_table_pointer_check.py") + add_test(NAME startup_gfx2hlsl_desc_ptr_prop COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_ptr_prop_check.py") + set_tests_properties(startup_gfx2hlsl_desc_ptr_prop PROPERTIES TIMEOUT 60) # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") + # gfx2hlsl binary32 rounding (VEC_F floor, ceil, trunc, fract, rndne): translation controls, then a draw of + # the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_round_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_round_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_round_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_round_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_round_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl refuses a scalar ALU operation whose operand list is too short. add_test(NAME startup_gfx2hlsl_scalar_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_arity_check.py") @@ -3172,6 +3737,57 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") + # gfx2hlsl lowers s_abs_i32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV readback on + # WARP/hardware (same dispatch pattern as startup_gfx2hlsl_s_ff1 / pack_absdiff). + add_test(NAME startup_gfx2hlsl_s_abs COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_abs_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_abs_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_abs_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl lowers s_quadmask_b64 (SOP1, #1723): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_quadmask_b64 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_quadmask_b64_check.py") + # gfx2hlsl lowers s_ff0_i32_b32 (SOP1, #1723): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_ff0 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff0_check.py") + # gfx2hlsl lowers s_bitset0_b32 and s_bitset1_b32 (SOP1, #2023 Item J): CPU evaluation and refusals. + add_test(NAME startup_gfx2hlsl_s_bitset COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset_check.py") + # gfx2hlsl lowers s_flbit_i32_b32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV + # readback on WARP/hardware (same dispatch pattern as s_ff1 / s_abs / pack_absdiff). + + add_test(NAME startup_gfx2hlsl_s_flbit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_flbit_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_flbit_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_flbit_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_flbit_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl lowers s_ff1_i32_b32 of a general scalar and s_ff1_i32_b64 of a zero-extended + # immediate (#2022 Item F); live SGPR-pair b64 is owned by open #2072. CPU evaluation, then + # a D3D12 UAV readback on WARP/hardware (same dispatch pattern as pack_absdiff). + add_test(NAME startup_gfx2hlsl_s_ff1 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff1_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_ff1_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_ff1_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_ff1_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl lowers s_quadmask_b32 (SOP1, #1723): CPU evaluation, then a D3D12 UAV + # readback on WARP/hardware (same dispatch pattern as s_ff1 / s_abs / pack_absdiff). + add_test(NAME startup_gfx2hlsl_s_quadmask COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_quadmask_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_quadmask_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_quadmask_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_s_quadmask_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") @@ -3195,6 +3811,32 @@ if(EXISTS "${INTAKE_PYTHON}") # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_check.py") + # 1D image sampling with an explicit level (#1721). + add_test(NAME startup_gfx2hlsl_image_1d COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_1d_check.py") + # Handlers that do not model a modifier they can receive refuse it (#1771). + add_test(NAME startup_gfx2hlsl_modifier_free COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_modifier_free_check.py") + # The src_scc scalar source (#1820). + add_test(NAME startup_gfx2hlsl_src_scc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py") + # D3D12 UAV readback of s_cmp_eq_u32 + s_mov_b32 sX, src_scc on WARP/hardware vs the CPU reference, + # with a mutated-lowering negative control (same dispatch pattern as s_ff1). + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_src_scc_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_src_scc_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + # src_scc at a branch target that one uniform SCC write reaches on every path. + add_test(NAME startup_gfx2hlsl_src_scc_join COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_join_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_src_scc_join_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_src_scc_join_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_src_scc_join_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # image_sample_c_lz with sampler word 2 bits 28-30 set (#1723). add_test(NAME startup_gfx2hlsl_sample_c_lz_mip COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sample_c_lz_mip_check.py") @@ -3204,6 +3846,9 @@ if(EXISTS "${INTAKE_PYTHON}") # The binary16 class comparison (#1855). add_test(NAME startup_gfx2hlsl_cmp_class_f16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_check.py") + # The SDWA forms of the binary16 class comparison and their negative controls; the draws are registered below. + add_test(NAME startup_gfx2hlsl_cmp_class_f16_sdwa COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py") # The 16-bit vector ALU: add, sub, mul, min, max, fma forms and the i16/u16 conversions (#1723). add_test(NAME startup_gfx2hlsl_f16_alu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_check.py") @@ -3222,12 +3867,24 @@ if(EXISTS "${INTAKE_PYTHON}") # s_brev_b32 of a known constant folds to a known word (a sampler built from it is a constant descriptor). add_test(NAME startup_gfx2hlsl_scalar_brev_fold COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_brev_fold_check.py") + # A copy of a plain constant scalar register still assigns at run time and drops its constant at a join. + add_test(NAME startup_gfx2hlsl_const_copy_join COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_const_copy_join_check.py") + # v_pack_b32_f16 with op_sel and the neg/abs source modifiers, evaluated against a bit reference. + add_test(NAME startup_gfx2hlsl_pack_b32_f16 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py") # Scalar sign-extends and conditional moves (batch 3 #2). add_test(NAME startup_gfx2hlsl_s_sext_cmov COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_sext_cmov_check.py") + # s_bfm_b64 (#1723). + add_test(NAME startup_gfx2hlsl_bfm_b64 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bfm_b64_check.py") # SDWA forms of the float-result conversions (#1727). add_test(NAME startup_gfx2hlsl_sdwa_cvt COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py") + # The SDWA form of v_cndmask_b32: fixture and model controls; the draws are registered below. + add_test(NAME startup_gfx2hlsl_sdwa_cndmask COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cndmask_check.py") # VOPC SDWA compares (#1906): every integer compare, select and sext() evaluated against an integer # reference; floating-point SDWA forms and unsupported modifiers are refused. The draws are registered below. add_test(NAME startup_gfx2hlsl_vopc_sdwa COMMAND "${INTAKE_PYTHON}" -B @@ -3238,6 +3895,10 @@ if(EXISTS "${INTAKE_PYTHON}") # refusals of every other DPP control. The draws are registered below. add_test(NAME startup_gfx2hlsl_dpp_pair COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_pair_check.py") + # DPP16 quad reads in a pixel program with a uniform loop and branch: the whole-program convergence proof and its + # refusals (vccz loop, SCC from a lane mask, EXEC write reaching the read, late s_wqm). The draws are below. + add_test(NAME startup_gfx2hlsl_dpp_quad_flow COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_flow_check.py") # DPP16 quad broadcasts quad_perm:[k,k,k,k] (#2125): lowered to QuadReadLaneAt, so the pixel stage compiles as # ps_6_0; the controls and refusals run here, the draws below compare every pixel with a CPU reference. add_test(NAME startup_gfx2hlsl_dpp_quad_broadcast COMMAND "${INTAKE_PYTHON}" -B @@ -3280,6 +3941,9 @@ if(EXISTS "${INTAKE_PYTHON}") # A typed buffer load of BUF_FMT_16_16_16_16_FLOAT reads four halves from one 8-byte element (#1695). add_test(NAME startup_gfx2hlsl_tbuffer_16f COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_tbuffer_16f_check.py") + # A typed buffer load of BUF_FMT_2_10_10_10_UNORM reads three 10-bit fields and a 2-bit one from one dword (#1723). + add_test(NAME startup_gfx2hlsl_tbuffer_2101010 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_tbuffer_2101010_check.py") # The draw's DXGI -> FORMAT table for typed views read by buffer_load_format_* matches the translation's switch. add_test(NAME startup_buffer_format_word3_table COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_buffer_format_word3_table_check.py") @@ -3292,10 +3956,22 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh requests (#2413): the one accepted group-memory shape translates; each mutation is refused. add_test(NAME startup_mesh57_skeleton COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py") + # Slot 57 mesh with a depth-only pixel stage (#2413 T5): the null export keeps its discard, no colour target. + add_test(NAME startup_mesh57_depth_only COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_depth_only_check.py") + # Slot 57 mesh loop refusal outside the accepted exchanges (#2413 T6); mutant drops the back-edge. + add_test(NAME startup_mesh57_loop_refusal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_refusal_check.py") + # Slot 57 mesh constant-trip loop lowering outside the accepted exchanges (#2413 T6). + add_test(NAME startup_mesh57_loop COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_check.py") + # Slot 57 constant-lane v_writelane_b32 / v_readlane_b32 spill idiom (#2413 T7). + add_test(NAME startup_mesh57_lane_spill COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_lane_spill_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") - # s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 against an integer reference (#1723). + # s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 against an integer reference (#1723); the _warp/_hardware tests also draw them (D3D12 readback). add_test(NAME startup_gfx2hlsl_pack_absdiff COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_absdiff_check.py") foreach(adapter IN ITEMS warp hardware) @@ -3355,7 +4031,13 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: a scalar load or select into a former lane-mask SGPR clears its mask mark. add_test(NAME startup_gfx2hlsl_mask_overwrite_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mask_overwrite_check.py") - # Startup shader translator: image_get_lod on a 2D texture (CalculateLevelOfDetail / Unclamped). + # Startup shader translator: lane masks cannot be used as vector data words. + add_test(NAME startup_gfx2hlsl_mask_data_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mask_data_check.py") + # Startup shader translator: a plain image_sample past a uniform join keeps its implicit LOD (Sample, not level 0). + add_test(NAME startup_image_sample_implicit_lod_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_implicit_lod_check.py") + # Startup shader translator: image_get_lod on 2D and 2D-array textures. add_test(NAME startup_gfx2hlsl_image_get_lod_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_get_lod_check.py") foreach(adapter IN ITEMS warp hardware) @@ -3392,6 +4074,12 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_u8_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pack_b32_f16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_pack_b32_f16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 (#1723): VOP3A saturating 16-bit integer packs, encoding/refusal # controls, and WARP/hardware draws (FXC 5_1 and DXC 6_0) with four mutations per opcode. add_test(NAME startup_gfx2hlsl_cvt_pk_int16_controls COMMAND "${INTAKE_PYTHON}" -B @@ -3402,6 +4090,28 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_int16_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl RDNA 2 scalar null operand (code 125) and Stage.scalar destination guards (#2618, #1723, #2463): + # 32-bit null-destination SCC updates, null source (0u), explicit Unsupported refusals replacing TypeError, and + # WARP/hardware draws + root-constant buffer readbacks with negative controls. + add_test(NAME startup_gfx2hlsl_scalar_null_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_null_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_scalar_null_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_null_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_scalar_null_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl compute 32-bit GLOBAL saddr load (global_load_dword vdst, vaddr, s[base:base+1] [offset:imm]) (#2618, #2022): + # proven 64-bit root buffer pointer pairs (direct, copied, literal-advanced), signed 12-bit immediate offsets, + # check_encoding unused-bit guards, refusals, and WARP/hardware compute readbacks with negative mutations. + add_test(NAME startup_compute_global_load_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_global_load_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_global_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_global_load_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_global_load_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cvt_off_f32_i4 (VOP1 0x0e and VOP3A 0x18e): signed 4-bit nibble conversion with output modifiers, # low16_only provenance, uniformity tracking, refusals, and WARP/hardware draws with mutated controls. add_test(NAME startup_gfx2hlsl_cvt_off_f32_i4_controls COMMAND "${INTAKE_PYTHON}" -B @@ -3467,6 +4177,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_image_3d_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_3d_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_image_1d_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_image_1d_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_image_1d_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_image_load_mip_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_load_mip_check.py" --draw "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -3515,6 +4229,24 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_sample_b_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl image_sample_b past a divergent EXEC: EXEC branches decided per quad, drawn against a CPU reference. + add_test(NAME startup_image_sample_b_flow_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_b_flow_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_b_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_b_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_b_flow_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl image_get_lod past a divergent EXEC: EXEC branches decided per quad, drawn against a CPU reference. + add_test(NAME startup_image_get_lod_flow_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_get_lod_flow_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_get_lod_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_get_lod_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_get_lod_flow_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # Constant-sampler LOD limits of image_sample, _l and _lz (#2177): each form drawn alone against a plain-smp control. foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_image_sample_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B @@ -3522,6 +4254,12 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_sample_lod_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_implicit_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_implicit_lod_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_implicit_lod_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl level-zero D16 image_load narrowing and pairwise packing (#2023). add_test(NAME startup_image_load_d16_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_load_d16_check.py") @@ -3551,11 +4289,19 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_check.py") add_test(NAME startup_ps_input_scan_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_cli_check.py") + # The pixel input masks come from the captured stream description of the exact pipeline (#1629): a decoy + # description, stale or missing masks and contradictory enable/address masks; then the #1634 gradient draw. + add_test(NAME startup_packed_screen_position_provenance COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_provenance_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_packed_screen_position_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_check.py" "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_packed_screen_position_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_packed_screen_position_provenance_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_provenance_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_packed_screen_position_provenance_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_flat_param_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_flat_param_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) @@ -3565,6 +4311,25 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(raster_winding_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # s_bcnt0/1_i32_b32/b64, s_ff0/ff1_i32_b64 and s_flbit_i32_b64/i64 against an integer reference (#1723); the _warp/_hardware tests also draw them (D3D12 readback). + add_test(NAME startup_gfx2hlsl_s_bit_scan COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bit_scan_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bit_scan_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bit_scan_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bit_scan_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl three-source integer vector operations (VEC_U): translation controls, then a draw of the translated + # pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_int3_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int3_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_int3_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int3_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_int3_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl per-lane bit operations: CPU evaluation of the translated text against an independent # reference with mutation controls, then a desktop draw of the translated pairs (FXC 5_1 and DXC 6_0). add_test(NAME startup_gfx2hlsl_bit_alu_controls COMMAND "${INTAKE_PYTHON}" -B @@ -3575,6 +4340,36 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_bit_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # s_bfm_b64 read back on a desktop adapter: widths 0/1/31/32/33/63 x offsets 0/1/31/32/63 from run-time root + # constants against the bit-loop reference (FXC 5_1 and DXC 6_0), with an uncapped reference and a mutated lowering + # that the draw must reject. The startup_gfx2hlsl_bfm_b64 test above holds the CPU controls. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bfm_b64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_bfm_b64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_bfm_b64_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl two- and one-source integer vector operations (VEC_U): translation controls, then the same draw + # of the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_int_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_int_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_int_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl abs (`|src|` and `-|src|`) on v_cndmask_b32_e64 data sources: CPU evaluation of the translated + # text over 32-bit bit patterns, then a desktop draw of the translated pair (FXC ps_5_1 and DXC ps_6_0) + # with order-reversed and abs-dropped mutation controls. + add_test(NAME startup_gfx2hlsl_cndmask_abs_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cndmask_abs_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cndmask_abs_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cndmask_abs_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cndmask_abs_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cube{id,sc,tc,ma}_f32: the source-built cube directions are drawn and compared with the # LLVM ConstantFoldAMDGCNCubeIntrinsic model; swapped id/sc, tie-order and cubema-factor controls must fail. foreach(adapter IN ITEMS warp hardware) @@ -3604,6 +4399,14 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_dpp_pair_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl DPP16 quad reads (swap, broadcast, pair) inside a uniform scalar loop with an if: 16 x 16 pixels against + # a CPU reference of the per-pass neighbour words; a read taking the wrong lane must fail. DXC ps_6_0 only. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_dpp_quad_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_dpp_quad_flow_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers DPP16 quad swaps (quad_perm [1,0,3,2], [2,3,0,1], [3,2,1,0]) in a pixel stage to QuadReadAcross*. add_test(NAME startup_gfx2hlsl_dpp_quad_swap_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_swap_check.py") @@ -3622,6 +4425,25 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sgpr_spill_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # The same spill slots on wave64 lanes 32..63 and in a vertex stage (k and k + 32 on one VGPR refused). + add_test(NAME startup_gfx2hlsl_spill_wave64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_wave64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_spill_wave64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_wave64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_spill_wave64_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + # wave32 vcc_hi as an ordinary scalar register (compare/carry destination, mask, scalar operand) when the program + # proves it; the 64-bit vcc pair, an unproven VALU vcc_lo write and exec_hi writes are refused, not crashes. + add_test(NAME startup_gfx2hlsl_vcc_hi_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_vcc_hi_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_vcc_hi_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_vcc_hi_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_vcc_hi_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 24-bit multiplies, v_xnor_b32 and the funnel shifts: CPU evaluation of the translated text # against an independent reference built from unbounded integers. add_test(NAME startup_gfx2hlsl_mul24_align COMMAND "${INTAKE_PYTHON}" -B @@ -3634,6 +4456,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_mul24_align_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # The same spill slots across branches: a write must reach the read on every path, outside non-uniform regions. + add_test(NAME startup_gfx2hlsl_spill_branches COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_branches_check.py") + # The same branches drawn on D3D12 (FXC 5_1 and DXC 6_0): two uniform choices write different words to one slot, + # GPU readback of the reload after the join against each arm's reference, the opposite arm as a negative control. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_spill_branches_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_spill_branches_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_spill_branches_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 16-bit vector ALU (#1723): the translated pairs drawn on WARP and hardware (FXC 5_1 and DXC 6_0), # four result words per draw against an exact binary16 reference. add_test(NAME startup_gfx2hlsl_f16_alu_draw_controls COMMAND "${INTAKE_PYTHON}" -B @@ -3642,7 +4475,7 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_f16_alu_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_draw_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) - set_tests_properties(startup_gfx2hlsl_f16_alu_draw_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + set_tests_properties(startup_gfx2hlsl_f16_alu_draw_${adapter} PROPERTIES TIMEOUT 900 SKIP_RETURN_CODE 77) endforeach() # gfx2hlsl v_cmpx_le_i32_sdwa on a sign-extended byte decides which of 16 x 16 pixels survive, checked # pixel by pixel (#1906); translations without the select or without sext() must fail the same draw. @@ -3651,6 +4484,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_vopc_sdwa_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_vopc_sdwa_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_cmp_class_f16_sdwa_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cmp_class_f16_sdwa_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_gfx2hlsl_dpp_quad_broadcast_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) @@ -3659,6 +4496,11 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cvt_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sdwa_cvt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + # Four SDWA v_cndmask_b32 selects over 16 x 16 pixels against a bit model; six mutated selects must fail. + add_test(NAME startup_gfx2hlsl_sdwa_cndmask_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sdwa_cndmask_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_sdwa_cndmask_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() # gfx2hlsl v_cmp/v_cmpx lg and nlg f32 over every pair of +-0, denormal, +-1, +-max, +-inf and NaN words decide # 16 x 16 pixels, checked pixel by pixel (#1920); the old != lowering must fail the same draws. @@ -3686,6 +4528,14 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() add_test(NAME startup_gfx2hlsl_mad_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_check.py") + add_test(NAME shader_signed_zero_minmax_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_signed_zero_minmax_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME shader_signed_zero_minmax_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_signed_zero_minmax_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(shader_signed_zero_minmax_${adapter} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) + endforeach() foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_mad_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_check.py" dispatch "${DXC_EXECUTABLE}" @@ -3696,6 +4546,15 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_mad_u32_u16: low-16 unsigned multiply-add with 32-bit addend and wraparound. + add_test(NAME startup_gfx2hlsl_mad_u32_u16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_u32_u16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mad_u32_u16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad_u32_u16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mad_u32_u16_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_fma_mix*: every translated form dispatched against a CPU reference that decodes the VOP3P # word itself, plus a control that drops the high-half shift. foreach(adapter IN ITEMS warp hardware) @@ -3748,6 +4607,13 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") + # The shared one-device case runner of the GPU draw checks (tests/gpu_case_runner.py, issue #448). + add_test(NAME gpu_case_runner COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/gpu_case_runner_check.py") + set_tests_properties(gpu_case_runner PROPERTIES TIMEOUT 120) + # The GPU check package replays these cases on a contributor's adapter (tools/record_gpu_cases.py). + add_test(NAME gpu_case_recorder COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/gpu_case_recorder_check.py" "${DXC_EXECUTABLE}") + set_tests_properties(gpu_case_recorder PROPERTIES TIMEOUT 300) foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_compute_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" dispatch "${DXC_EXECUTABLE}" @@ -3757,8 +4623,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control mbcnt "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap - j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched) + foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast f-second-fill g-swapped-offsets g-overlap + j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched n-unmasked o-mask-kept o-subset-remask-dropped + n-dropped-broadcast p-dropped-andn2 p-dropped-or p-block-entered q-block-entered q-not-all-ones + s-min-strict s-borrow-flipped) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -3766,6 +4634,48 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl constant-lane SGPR spills of descriptor and pointer words in compute stages, across branches (#1723). + add_test(NAME startup_gfx2hlsl_compute_spill_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_spill_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_compute_spill_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_spill_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_spill_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS s-arm-swapped s-store-dropped p-store-dropped) + add_test(NAME startup_gfx2hlsl_compute_spill_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_spill_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_spill_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() + # gfx2hlsl constant-lane SGPR spills of lane masks in compute stages (#1723). + add_test(NAME startup_gfx2hlsl_compute_mask_spill_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_mask_spill_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_compute_mask_spill_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_mask_spill_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_mask_spill_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS m-saveexec-dropped m-mask-inverted v-branch-inverted) + add_test(NAME startup_gfx2hlsl_compute_mask_spill_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_mask_spill_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_compute_mask_spill_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() + # gfx2hlsl v_mad_u64_u32 / v_mad_i64_i32: helper math against a 64-bit reference, carry-out mask, refusals (Part of #1723). + add_test(NAME startup_gfx2hlsl_mad64 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad64_check.py") + set_tests_properties(startup_gfx2hlsl_mad64 PROPERTIES TIMEOUT 60) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mad64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mad64_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mad64_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl bounded 64-bit LDS exchanges (ds_write_b64, ds_read_b64) across s_barrier (Refs #2274, #1541). add_test(NAME startup_compute_lds_b64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b64_check.py") @@ -3782,6 +4692,22 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl COMPUTE_PGM_RSRC2.TG_SIZE_EN wave-ID masking for single-wave groups <= 32 threads (Refs #2274). + add_test(NAME startup_compute_tg_size_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_tg_size_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_tg_size_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_tg_size_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_tg_size_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS dropped-base swapped-mask) + add_test(NAME startup_compute_tg_size_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_tg_size_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_tg_size_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl bounded 128-bit LDS exchanges (ds_write_b128, ds_read_b128) and mixed 32/64/128-bit ops (Refs #1541). add_test(NAME startup_compute_lds_b128_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b128_check.py") @@ -3801,12 +4727,23 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl 64-bit VOP3 shifts: binary round-trip, overlap, guards and WARP/hardware draws (Refs #1723). add_test(NAME startup_gfx2hlsl_shift64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py") + add_test(NAME startup_gfx2hlsl_shift64_literal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_literal_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_shift64_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_shift64_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl signed multiply-high (v_mul_hi_i32, s_mul_hi_i32): helper math, refusals, mutations and draws. + add_test(NAME startup_gfx2hlsl_mul_hi_i32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_i32_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mul_hi_i32_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_i32_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mul_hi_i32_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_fract_f32 goes through the clamped fract32 helper, never a bare D3D frac (#1741). add_test(NAME startup_gfx2hlsl_fract COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fract_check.py") @@ -3837,6 +4774,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sload_s104_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_gfx2hlsl_desc_vcc_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_vcc_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_desc_vcc_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() # gfx2hlsl dual-offset/stride-64 32-bit LDS ops and 32-bit LDS atomics (Refs #1541, #2274). add_test(NAME startup_compute_lds_dual_atomics_controls COMMAND "${INTAKE_PYTHON}" -B @@ -3882,6 +4823,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sad_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_sad_hi_u8 (0x15b) and v_msad_u8 (0x171): the shared sad4_u8 helper, value evaluation against the + # tools/pixel_aot.py formulas (zero-src1-byte and 2^32 carry cases), refusals and the unchanged v_sad_u8 output. + add_test(NAME startup_gfx2hlsl_sad_hi_msad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sad_hi_msad_check.py") add_test(NAME startup_xg_bc_tiling COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc_tiling_check.py" "$") set_tests_properties(startup_xg_bc_tiling PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") @@ -3899,6 +4844,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_inline_sampler_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl binary32 reciprocal, roots, exp2 and log2 (VEC_F) on exact inputs: translation controls, then a + # draw of the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_transcendental_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_transcendental_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_transcendental_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_transcendental_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_transcendental_${adapter} PROPERTIES TIMEOUT 300 + SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_gfx2hlsl_scalar_shift64_bfe_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py") add_test(NAME startup_gfx2hlsl_scalar_m0_controls COMMAND "${INTAKE_PYTHON}" -B @@ -3921,6 +4877,13 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_launch_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_launch_cli_check.py") set_tests_properties(startup_launch_cli_check PROPERTIES TIMEOUT 30) + # The debugger's function hooks and concurrent calls (#1281): the step window's bookkeeping, then two + # threads through one hooked function with the other thread held for each step, and without. + add_test(NAME startup_hook_window COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_hook_check.py") + add_test(NAME startup_hook_overlap COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_hook_check.py" "$") + set_tests_properties(startup_hook_window PROPERTIES TIMEOUT 30) + set_tests_properties(startup_hook_overlap PROPERTIES TIMEOUT 600) find_program(STARTUP_POWERSHELL NAMES powershell pwsh REQUIRED) add_test(NAME startup_stage_package COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stage_package_check.py" "${STARTUP_POWERSHELL}") @@ -3938,6 +4901,28 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${group}) set_tests_properties(${startup_debug_test} PROPERTIES TIMEOUT 300) endforeach() + # Periodic window pictures (--capture-every): the pure parts, then a real window that turns red to blue. + add_test(NAME startup_window_capture_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_window_capture_check.py") + set_tests_properties(startup_window_capture_check PROPERTIES TIMEOUT 60) + add_test(NAME startup_debug_window COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_debug_window_check.py" "$") + set_tests_properties(startup_debug_window PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + + # tools/startup/debug_launch.py --map-drive: a console package on another volume is opened through + # a mapped letter, and the launcher rewrites that open in the caller's own name. + add_test(NAME startup_map_drive COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_map_drive_check.py" + "$" "${CMAKE_SOURCE_DIR}/tools/startup/debug_launch.py" + "${CMAKE_CURRENT_BINARY_DIR}") + set_tests_properties(startup_map_drive PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + # Two threads with their own caller-owned names in flight at once: all 64 opens are rewritten, succeed + # and restore their caller strings while the debugger holds the other threads for each step; the + # control without holding them (--suspend-others 0) must lose opens. Needs the step window (#1281). + add_test(NAME startup_map_drive_overlap COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_map_drive_check.py" + "$" "${CMAKE_SOURCE_DIR}/tools/startup/debug_launch.py" + "${CMAKE_CURRENT_BINARY_DIR}" overlap) + set_tests_properties(startup_map_drive_overlap PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) add_test(NAME startup_stream_request_warp COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_check.py" "$") @@ -3967,11 +4952,48 @@ if(EXISTS "${INTAKE_PYTHON}") PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) set_tests_properties(startup_compute_translate_e2e_wrong_group_${adapter} PROPERTIES PASS_REGULAR_EXPRESSION "control wrong-group: rejected at word=[0-9]+ ") + add_test(NAME startup_compute_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_slot67_indirect_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot67_indirect_dispatch_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_slot67_indirect_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_heap_word_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_word_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_input_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_input_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_live_retry_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_live_retry_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_entry_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_entry_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_compute_dispatch_two_mips_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter} two-mips) + set_tests_properties(startup_compute_dispatch_${adapter} startup_compute_dispatch_texture_${adapter} + startup_compute_dispatch_heap_${adapter} startup_compute_dispatch_heap_word_${adapter} + startup_compute_live_retry_${adapter} startup_compute_dispatch_entry_${adapter} + startup_compute_dispatch_input_${adapter} startup_compute_dispatch_two_mips_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" "$" hardware filter) set_tests_properties(startup_stream_adapter_filter PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) + add_test(NAME startup_indirect_dispatch_adapter_filter COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/hardware_adapter_filter_check.py" + "$" hardware count) + set_tests_properties(startup_indirect_dispatch_adapter_filter PROPERTIES TIMEOUT 30) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" @@ -4019,6 +5041,10 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_draw_depth_target_${backend} startup_draw_depth_target_drop_control_${backend} startup_draw_depth_target_debug_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(compiler IN ITEMS fxc dxc) + add_test(NAME startup_joined_table_pointer_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_joined_table_pointer_check.py" + "$" "${backend}" "${compiler}" "${DXC_EXECUTABLE}" "${STARTUP_FXC}") + set_tests_properties(startup_joined_table_pointer_${compiler}_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_mrt_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mrt_check.py" "$" "${backend}" "${compiler}" "${DXC_EXECUTABLE}" "${STARTUP_FXC}") @@ -4104,6 +5130,18 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_buffer_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_copied_vertex_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_copied_vertex_srv_check.py" + "$" "${backend}") + set_tests_properties(startup_copied_vertex_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_table_alias_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_table_alias_check.py" + "$" "${backend}") + set_tests_properties(startup_table_alias_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_direct_index_late_write_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_direct_index_late_write_check.py" + "$" "${backend}") + set_tests_properties(startup_direct_index_late_write_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_mubuf_descriptor_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mubuf_descriptor_check.py" "$" "${backend}") @@ -4116,6 +5154,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_d16_srv_check.py" "$" "${backend}") set_tests_properties(startup_d16_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # A translated pixel-stage image store bound from the title's table (#1996 item F): the stored texel and + # every other word of four textures read back, each refusal by its reason, and the exec controls. + add_test(NAME startup_pixel_uav_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_pixel_uav_check.py" + "$" "${backend}") + set_tests_properties(startup_pixel_uav_${backend} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) add_test(NAME startup_frame_copy_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_frame_copy_check.py" "$" ${backend}) @@ -4133,8 +5177,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "${backend}") set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) # Uploads of by-address textures recorded while the queue waits on a fence keep their bytes until the - # queue has run them. The ring control fills them from the shared upload ring and must lose the first. - foreach(gate IN ITEMS gate gate-ring) + # queue has run them. The ring control fills them from the shared upload ring, which must refuse the uploads + # past its 256 MiB cap while the queue is held. gate-ring-reuse: once those submits have completed, the ring + # must accept a new upload again. + # gate-ring-keep(-release): a closed list that is never Reset, without and with X2W_D3D12_RING_RELEASE_AT_SUBMIT. + foreach(gate IN ITEMS gate gate-ring gate-ring-reuse gate-ring-keep gate-ring-keep-release) string(REPLACE "-" "_" gate_name "${gate}") add_test(NAME startup_address_console_${gate_name}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" @@ -4165,9 +5212,21 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: the SMEM offset 'off' is the literal 0; m0 and other operands keep their handling (#1674). add_test(NAME startup_gfx2hlsl_smem_offset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_smem_offset_check.py") + # gfx2hlsl binary32 arithmetic (VEC_F): translation controls, then a draw of the translated pairs with exact + # reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_alu_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_alu_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_alu_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_alu_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # Startup shader translator: s_load descriptor into s[104:107] (vcc is s106/s107) (#1723). add_test(NAME startup_gfx2hlsl_sload_s104 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py") + add_test(NAME startup_gfx2hlsl_desc_vcc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_desc_vcc_check.py") # Startup shader translator: scalar constants are dropped at a branch join that another path writes (loop counters). add_test(NAME startup_gfx2hlsl_loop_constants COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_loop_constants_check.py") @@ -4194,6 +5253,9 @@ if(EXISTS "${INTAKE_PYTHON}") # v_readfirstlane_b32 past the entry block of a branched program: recomputed definition, joins and EXEC refused. add_test(NAME startup_gfx2hlsl_readfirstlane_recompute COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py") + # A uniform compute buffer load past the entry block: per-lane temporary, joins, EXEC and per-lane addresses refused. + add_test(NAME startup_gfx2hlsl_readfirstlane_load_recompute COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py") add_test(NAME startup_gfx2hlsl_calculated_target COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_calculated_target_check.py") # Startup shader translator: read-only census of every refusal site (--refusals). @@ -4211,6 +5273,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_check.py") add_test(NAME runtime_shader_cache_rekey_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_cli_check.py") + # The launchers' warning when the shader cache and the translator come from different revisions (#2815). + add_test(NAME startup_shader_cache_revision COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_revision_check.py") # Partial colour exports carry their channel mask to the manifest; compressed exports of whole pairs lower (#1674). add_test(NAME startup_gfx2hlsl_export_mask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_export_mask_check.py") @@ -4219,6 +5284,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_export_mask_drop_control PROPERTIES WILL_FAIL TRUE) add_test(NAME startup_triage_run COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_check.py") + add_test(NAME runtime_startup_triage_run_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_triage_run_cli_check.py") + set_tests_properties(runtime_startup_triage_run_cli_check PROPERTIES TIMEOUT 60) add_test(NAME startup_run_ps1 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_run_ps1_check.py") # The Linux launcher's check exits 77 on Windows; the Ubuntu job runs it. @@ -4240,6 +5308,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/emit_variants_cli_check.py") add_test(NAME coverage_svg COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/coverage_svg_check.py") + add_test(NAME ci_coverage_svg_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/coverage_svg_cli_check.py") + set_tests_properties(ci_coverage_svg_cli_check PROPERTIES TIMEOUT 60) # Compile-only: outcome classification and GVN pass shares, no wall-time threshold (#775). add_test(NAME dxc_compile_time_gvn COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dxc_compile_time_check.py" "${DXC_EXECUTABLE}") @@ -4281,8 +5352,14 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() add_test(NAME spirv_window_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_sampler_split_check.py") + add_test(NAME shader_spirv_ballot_extract_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/spirv_ballot_extract_check.py") + set_tests_properties(shader_spirv_ballot_extract_check PROPERTIES TIMEOUT 60) add_test(NAME spirv_address_window_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_check.py") + add_test(NAME shader_spirv_address_window_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_cli_check.py") + set_tests_properties(shader_spirv_address_window_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_section_probe_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/section_probe_cli_check.py") # Outside a Git checkout, such as a source archive, the tracked-path check cannot run. @@ -4315,6 +5392,20 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/cpu/${script}.py" "$" ${pairs} DEPENDS ${image} tests/cpu/${script}.py tools/emit_variants.py ${ARGN} VERBATIM) endfunction() + # A long check is split into parallel CTest cases _. The original keeps its name (the + # form-coverage source header and the docs name it), runs the cheap remainder, and requires every part + # through a CTest fixture, so it is "not run" (not covered) unless every part passed. + function(x2w_add_check_part test part) + add_test(NAME ${test}_${part} COMMAND ${ARGN}) + set_tests_properties(${test}_${part} PROPERTIES FIXTURES_SETUP ${test}_${part}) + endfunction() + function(x2w_require_check_parts test) + set(required) + foreach(part IN LISTS ARGN) + list(APPEND required ${test}_${part}) + endforeach() + set_tests_properties(${test} PROPERTIES FIXTURES_REQUIRED "${required}") + endfunction() function(cpu_translation image translator entry) cmake_parse_arguments(BIND "FFX_DESTROY;IMAGE_DATA;HOST_CPU" "PROVIDER;SYMBOL;LINK_NAME;CALLBACK_OFFSET;IMPORT_ARGUMENTS;RETURN_BYTES;NAME;RANGES;SECOND_PROVIDER;SECOND_SYMBOL;SECOND_LINK_NAME;SECOND_IMPORT_ARGUMENTS;SECOND_RETURN_BYTES" "STACK_OUTPUT" ${ARGN}) @@ -4475,6 +5566,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" check "${CPU_FUZZ_SEED}" "${CPU_FUZZ_FUNCTIONS}" "$" "$" "${cpu_fuzz_o2}") set_tests_properties(cpu_aot_fuzz_smoke PROPERTIES TIMEOUT 60) + add_test(NAME tooling_fuzz_cpu_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/fuzz_cpu_cli_check.py") + set_tests_properties(tooling_fuzz_cpu_cli_check PROPERTIES TIMEOUT 60) # Fixed RSP frames: saved nonvolatile registers, partial spill overlaps and a planted reload fault. set(CPU_FUZZ_FRAMES_SEED "0xF4A3" CACHE STRING "Seed for the CPU differential fuzz frame test") set(CPU_FUZZ_FRAMES_FUNCTIONS "16" CACHE STRING "Number of generated functions in the CPU differential fuzz frame test") @@ -5292,6 +6386,29 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_avx_int_ymm_pack PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_pack.txt") + # cpu_avx_int_ymm_widen_unpack_checks + set(cpu_avx_int_ymm_widen_unpack_exports + "op_vpmovsxbw_ymm,op_vpmovsxbd_ymm,op_vpmovsxbq_ymm,op_vpmovsxwd_ymm,op_vpmovsxwq_ymm,op_vpmovsxdq_ymm," + "op_vpmovzxbw_ymm,op_vpmovzxbd_ymm,op_vpmovzxbq_ymm,op_vpmovzxwd_ymm,op_vpmovzxwq_ymm,op_vpmovzxdq_ymm," + "op_vpunpckldq_ymm,op_vpunpckhdq_ymm,op_vpunpcklqdq_ymm,op_vpunpckhqdq_ymm," + "op_vpmovsxbd_ymm_stale_dst,op_vpmovsxbw_ymm_alias,op_vpmovzxdq_ymm_alias," + "op_vpunpckldq_ymm_dst_src1,op_vpunpckhqdq_ymm_dst_src2,op_vpunpckhdq_ymm_all," + "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq,op_chain_ymm_widen_unpack") + string(CONCAT cpu_avx_int_ymm_widen_unpack_exports ${cpu_avx_int_ymm_widen_unpack_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_int_ymm_widen_unpack_${variant} avx_int_ymm_widen_unpack) + cpu_translation(cpu_avx_int_ymm_widen_unpack_${variant} cpu_avx_int_aot "${cpu_avx_int_ymm_widen_unpack_exports}") + endforeach() + target_compile_definitions(cpu_avx_int_ymm_widen_unpack_altered PRIVATE ALTER_YMM) + add_test(NAME cpu_aot_avx_int_ymm_widen_unpack COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_int_ymm_widen_unpack_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_int_ymm_widen_unpack PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_widen_unpack.txt") set(cpu_avx_move_exports "op_andpd_xmm,op_andpd_ymm,op_andps_xmm,op_andps_ymm,op_andnpd_xmm,op_andnpd_ymm," "op_andnps_xmm,op_andnps_ymm,op_orpd_xmm,op_orpd_ymm,op_orps_xmm,op_orps_ymm," @@ -5656,12 +6773,23 @@ if(EXISTS "${INTAKE_PYTHON}") cpu_translation(cpu_sse_fp_pd_${variant} cpu_sse_fp_aot "${cpu_sse_fp_pd_exports}") endforeach() target_compile_definitions(cpu_sse_fp_pd_altered PRIVATE ALTER_IMM) + # The five checks of sse_fp_pd_check.py run as separate cases; cpu_aot_sse_fp_pd runs the rejections + # and requires the other four. + foreach(part IN ITEMS differential modes cmp_differential cmp_modes) + x2w_add_check_part(cpu_aot_sse_fp_pd ${part} "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse_fp_pd_check.py" + "$" + "$" + "$" + "$" ${part}) + endforeach() add_test(NAME cpu_aot_sse_fp_pd COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/sse_fp_pd_check.py" "$" "$" "$" - "$") + "$" rejections) + x2w_require_check_parts(cpu_aot_sse_fp_pd differential modes cmp_differential cmp_modes) # cpu_sse_fp_pd_logic_checks set(cpu_sse_fp_pd_logic_exports "op_andpd,op_andpd_mem,op_andpd_mem_disp,op_andpd_self," @@ -6341,9 +7469,15 @@ if(EXISTS "${INTAKE_PYTHON}") tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) add_library(cpu_xchg_${variant} SHARED "${xchg_fixture}") endforeach() + x2w_add_check_part(cpu_aot_xchg native "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" + check-native "$") + x2w_add_check_part(cpu_aot_xchg lifted "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" + check-lifted "$") + x2w_add_check_part(cpu_aot_xchg controls "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" + check-controls "$" "$") add_test(NAME cpu_aot_xchg COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xchg.py" - check "$" "$" - "$" "$") + check-rejections) + x2w_require_check_parts(cpu_aot_xchg native lifted controls) cpu_asm_fixture(cpu_address_size address_size) set(address_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_address_size_lifted.cpp") add_custom_command(OUTPUT "${address_fixture}" @@ -6369,6 +7503,31 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$" "$" "$" "$") set_tests_properties(cpu_aot_movbe PROPERTIES SKIP_RETURN_CODE 77) + + # cpu_aot_movbe_dedicated + set(cpu_movbe_aot_exports + "op_movbe_load16,op_movbe_load16_disp,op_movbe_load32,op_movbe_load32_disp," + "op_movbe_load64,op_movbe_load64_disp," + "op_movbe_store16,op_movbe_store16_disp,op_movbe_store32,op_movbe_store32_disp," + "op_movbe_store64,op_movbe_store64_disp," + "op_movbe_flags_cf_zf_of_pf,op_movbe_flags_sf_of_pf,op_movbe_flags_all_clear," + "op_r8_source_then_store,op_movbe_discarded_read") + string(CONCAT cpu_movbe_aot_exports ${cpu_movbe_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_movbe_aot_${variant} movbe_aot) + cpu_translation(cpu_movbe_aot_${variant} cpu_movbe_aot "${cpu_movbe_aot_exports}") + endforeach() + target_compile_definitions(cpu_movbe_aot_altered PRIVATE ALTER_MOVBE) + add_test(NAME cpu_aot_movbe_dedicated COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/movbe_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_movbe_dedicated PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_movbe_dedicated.txt") cpu_asm_fixture(cpu_bmi1 bmi1) set(bmi1_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_bmi1_lifted.cpp") add_custom_command(OUTPUT "${bmi1_fixture}" @@ -6482,6 +7641,32 @@ if(EXISTS "${INTAKE_PYTHON}") SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_shift.txt") + # cpu_aot_bmi2_bit + set(cpu_bmi2_bit_exports + "op_bzhi32,op_bzhi64,op_mulx32,op_mulx64,op_mulx32_alias,op_mulx64_alias," + "op_pdep32,op_pdep64,op_pext32,op_pext64," + "op_bzhi32_mem,op_bzhi64_mem,op_mulx32_mem,op_mulx64_mem," + "op_pdep32_mem,op_pdep64_mem,op_pext32_mem,op_pext64_mem," + "op_mem_r8_source,op_bzhi32_flags,op_bzhi64_flags," + "op_flags_preserve32,op_flags_preserve64,op_flags_preserve_pf," + "op_flags_preserve_mem,op_bmi2_bit_discarded_read") + string(CONCAT cpu_bmi2_bit_exports ${cpu_bmi2_bit_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi2_bit_${variant} bmi2_bit_aot) + cpu_translation(cpu_bmi2_bit_${variant} cpu_bmi2_bit_aot "${cpu_bmi2_bit_exports}") + endforeach() + target_compile_definitions(cpu_bmi2_bit_altered PRIVATE ALTER_BMI2_BIT) + add_test(NAME cpu_aot_bmi2_bit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi2_bit_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi2_bit PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_bit.txt") + # cpu_aot_bmi1_bit set(cpu_bmi1_aot_exports "op_blsi32,op_blsi64,op_blsmsk32,op_blsmsk64,op_blsr32,op_blsr64," @@ -6506,6 +7691,30 @@ if(EXISTS "${INTAKE_PYTHON}") SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi1_bit.txt") + # cpu_aot_bmi1_logic + set(cpu_bmi1_logic_aot_exports + "op_andn32,op_andn64,op_bextr32,op_bextr64,op_tzcnt32,op_tzcnt64," + "op_andn32_mem,op_andn64_mem,op_bextr32_mem,op_bextr64_mem,op_tzcnt32_mem,op_tzcnt64_mem," + "op_andn32_flags,op_andn64_flags,op_bextr32_flags,op_bextr64_flags," + "op_tzcnt32_flags,op_tzcnt64_flags,op_bextr64_mem_flags,op_tzcnt64_mem_flags," + "op_r8_source_then_store,op_dst_alias_src,op_bmi1_logic_discarded_read") + string(CONCAT cpu_bmi1_logic_aot_exports ${cpu_bmi1_logic_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi1_logic_aot_${variant} bmi1_logic_aot) + cpu_translation(cpu_bmi1_logic_aot_${variant} cpu_bmi1_logic_aot "${cpu_bmi1_logic_aot_exports}") + endforeach() + target_compile_definitions(cpu_bmi1_logic_aot_altered PRIVATE ALTER_BMI1_LOGIC) + add_test(NAME cpu_aot_bmi1_logic COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi1_logic_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi1_logic PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi1_logic.txt") + cpu_asm_fixture(cpu_sse2_packed_cvt sse2_packed_cvt) target_sources(cpu_sse2_packed_cvt PRIVATE tests/cpu/sse2_mxcsr_test.asm) set(sse2_packed_cvt_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_sse2_packed_cvt_lifted.cpp") @@ -6681,6 +7890,37 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_crypto_aes_pclmul PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_aes_pclmul + set(cpu_aes_pclmul_aot_exports + "op_aesenc_reg,op_aesenclast_reg,op_aesdec_reg,op_aesdeclast_reg," + "op_aesimc_reg,op_aeskeygenassist_reg," + "op_pclmulqdq_00_reg,op_pclmulqdq_11_reg,op_pclmulqdq_ignore_bits_reg," + "op_aesenc_mem,op_aesenclast_mem,op_aesdec_mem,op_aesdeclast_mem," + "op_aesimc_mem,op_aeskeygenassist_mem,op_pclmulqdq_01_mem," + "op_vaesenc_reg,op_vaesenclast_reg,op_vaesdec_reg,op_vaesdeclast_reg," + "op_vaesimc_reg,op_vaeskeygenassist_reg," + "op_vpclmulqdq_10_reg,op_vpclmulqdq_ignore_bits_reg," + "op_vaesenc_mem,op_vaesenclast_mem,op_vaesdec_mem,op_vaesdeclast_mem," + "op_vaesimc_mem,op_vaeskeygenassist_mem,op_vpclmulqdq_11_mem," + "op_sse_preserves_ymm_hi,op_vex_zeroes_ymm_hi,op_vzeroupper_clears_ymm_hi," + "op_r8_source_then_store,op_dst_alias_src,op_aes_pclmul_discarded_read") + string(CONCAT cpu_aes_pclmul_aot_exports ${cpu_aes_pclmul_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_aes_pclmul_aot_${variant} aes_pclmul_aot) + cpu_translation(cpu_aes_pclmul_aot_${variant} cpu_aes_pclmul_aot "${cpu_aes_pclmul_aot_exports}") + endforeach() + target_compile_definitions(cpu_aes_pclmul_aot_altered PRIVATE ALTER_AES_PCLMUL) + add_test(NAME cpu_aot_aes_pclmul COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/aes_pclmul_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_aes_pclmul PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_aes_pclmul.txt") + # cpu_aot_sha256 set(cpu_sha256_aot_exports "op_sha256rnds2_reg,op_sha256rnds2_mem,op_sha256rnds2_mem_r8," @@ -6824,6 +8064,40 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_sse34_fp PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_sse41_fp + set(cpu_sse41_fp_aot_exports + "op_roundps_reg_0,op_roundps_reg_1,op_roundps_reg_2,op_roundps_reg_3,op_roundps_reg_4,op_roundps_reg_8," + "op_roundps_mem_rcx,op_roundps_mem_rdx,op_roundps_mem_r8," + "op_roundpd_reg_0,op_roundpd_reg_1,op_roundpd_reg_2,op_roundpd_reg_3,op_roundpd_reg_4," + "op_roundpd_mem_rcx,op_roundpd_mem_rdx,op_roundpd_mem_r8," + "op_roundss_reg_0,op_roundss_reg_1,op_roundss_reg_2,op_roundss_reg_3,op_roundss_reg_4," + "op_roundss_mem_rcx,op_roundss_mem_rdx,op_roundss_mem_r8," + "op_roundsd_reg_0,op_roundsd_reg_1,op_roundsd_reg_2,op_roundsd_reg_3,op_roundsd_reg_4," + "op_roundsd_mem_rcx,op_roundsd_mem_rdx,op_roundsd_mem_r8," + "op_dpps_reg_f1,op_dpps_reg_ff,op_dpps_reg_5a,op_dpps_reg_0f," + "op_dpps_mem_rcx,op_dpps_mem_rdx,op_dpps_mem_r8," + "op_dppd_reg_33,op_dppd_reg_11,op_dppd_reg_22,op_dppd_reg_03," + "op_dppd_mem_rcx,op_dppd_mem_rdx,op_dppd_mem_r8," + "op_insertps_reg_s1_d2_z5,op_insertps_reg_s3_d0_z0,op_insertps_reg_s0_d3_z8," + "op_insertps_mem_rcx,op_insertps_mem_rdx,op_insertps_mem_r8," + "op_extractps_r32_lane2,op_extractps_r64_lane3,op_extractps_mem_lane1," + "op_sse41_glue_pipeline") + string(CONCAT cpu_sse41_fp_aot_exports ${cpu_sse41_fp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sse41_fp_aot_${variant} sse41_fp_aot) + cpu_translation(cpu_sse41_fp_aot_${variant} cpu_sse41_fp_aot "${cpu_sse41_fp_aot_exports}") + endforeach() + target_compile_definitions(cpu_sse41_fp_aot_altered PRIVATE ALTER_SSE41_FP) + add_test(NAME cpu_aot_sse41_fp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse41_fp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_sse41_fp PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sse41_fp.txt") + cpu_asm_fixture(cpu_avx_packed_int avx_packed_int) set(avx_packed_int_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_packed_int_lifted.cpp") add_custom_command(OUTPUT "${avx_packed_int_fixture}" @@ -6884,6 +8158,35 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_avx_horiz_fp PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_avx_horiz_fp_dedicated + set(cpu_avx_horiz_fp_aot_exports + "op_vhaddps_xmm_reg,op_vhaddpd_xmm_reg,op_vhsubps_xmm_reg,op_vhsubpd_xmm_reg," + "op_vaddsubps_xmm_reg,op_vaddsubpd_xmm_reg," + "op_vhaddps_xmm_mem,op_vhaddpd_xmm_mem,op_vhsubps_xmm_mem,op_vhsubpd_xmm_mem," + "op_vaddsubps_xmm_mem,op_vaddsubpd_xmm_mem," + "op_vhaddps_ymm_reg,op_vhaddpd_ymm_reg,op_vhsubps_ymm_reg,op_vhsubpd_ymm_reg," + "op_vaddsubps_ymm_reg,op_vaddsubpd_ymm_reg," + "op_vhaddps_ymm_mem,op_vhaddpd_ymm_mem,op_vhsubps_ymm_mem,op_vhsubpd_ymm_mem," + "op_vaddsubps_ymm_mem,op_vaddsubpd_ymm_mem," + "op_vhaddps_ymm_mem_rcx,op_vaddsubpd_ymm_mem_r8," + "op_vhaddps_ymm_alias_dst_src1,op_vhaddpd_ymm_alias_dst_src2," + "op_vhsubps_ymm_alias_src1_src2,op_vaddsubps_ymm_alias_all,op_vaddsubpd_xmm_alias_dst_src2") + string(CONCAT cpu_avx_horiz_fp_aot_exports ${cpu_avx_horiz_fp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_horiz_fp_aot_${variant} avx_horiz_fp_aot) + cpu_translation(cpu_avx_horiz_fp_aot_${variant} cpu_avx_horiz_fp_aot "${cpu_avx_horiz_fp_aot_exports}") + endforeach() + target_compile_definitions(cpu_avx_horiz_fp_aot_altered PRIVATE ALTER_AVX_HORIZ_FP) + add_test(NAME cpu_aot_avx_horiz_fp_dedicated COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_horiz_fp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_horiz_fp_dedicated PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_horiz_fp_dedicated.txt") + cpu_asm_fixture(cpu_avx_addsub_fp avx_addsub_fp) set(avx_addsub_fp_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_addsub_fp_lifted.cpp") add_custom_command(OUTPUT "${avx_addsub_fp_fixture}" @@ -6932,6 +8235,41 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_avx_cvt_cmp_test PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_avx_cmp + set(cpu_avx_cmp_aot_exports) + foreach(mnem IN ITEMS vcmpps_ymm vcmppd_ymm vcmpss vcmpsd) + foreach(hi IN ITEMS 0 1) + foreach(lo IN ITEMS 0 1 2 3 4 5 6 7 8 9 a b c d e f) + list(APPEND cpu_avx_cmp_aot_exports "op_${mnem}_p${hi}${lo}") + endforeach() + endforeach() + endforeach() + list(APPEND cpu_avx_cmp_aot_exports + op_vcmpps_xmm_reg op_vcmppd_xmm_reg op_vcmpps_xmm_mem op_vcmppd_xmm_mem + op_vcmpps_ymm_mem_rcx op_vcmpps_ymm_mem_rdx op_vcmpps_ymm_mem_r8 + op_vcmppd_ymm_mem_rcx op_vcmppd_ymm_mem_rdx op_vcmppd_ymm_mem_r8 + op_vcmpss_mem_rcx op_vcmpss_mem_rdx op_vcmpss_mem_r8 + op_vcmpsd_mem_rcx op_vcmpsd_mem_rdx op_vcmpsd_mem_r8 + op_vcmpps_imm_highbits + op_vcmpps_alias_dst_src1 op_vcmppd_alias_dst_src2 op_vcmpps_alias_src1_src2 op_vcmpsd_alias_all + op_vmovss_mem_glue op_vmovsd_mem_glue op_vmovss_reg_merge_glue op_vmovsd_reg_merge_glue + op_vmov_aligned_glue) + string(JOIN "," cpu_avx_cmp_aot_exports_csv ${cpu_avx_cmp_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_cmp_aot_${variant} avx_cmp_aot) + cpu_translation(cpu_avx_cmp_aot_${variant} cpu_avx_cmp_aot "${cpu_avx_cmp_aot_exports_csv}") + endforeach() + target_compile_definitions(cpu_avx_cmp_aot_altered PRIVATE ALTER_AVX_CMP) + add_test(NAME cpu_aot_avx_cmp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_cmp_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_cmp PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_cmp.txt") + cpu_asm_fixture(cpu_avx_scalar_fp avx_scalar_fp) set(avx_scalar_fp_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_avx_scalar_fp_lifted.cpp") add_custom_command(OUTPUT "${avx_scalar_fp_fixture}" @@ -7025,6 +8363,43 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${tsc_controls}) endforeach() set_tests_properties(cpu_aot_rdtscp PROPERTIES SKIP_RETURN_CODE 77) + set(cpu_amd_monitor_rdpru_aot_exports + "op_rdpru_mperf,op_rdpru_aperf,op_rdpru_twice,op_rdpru_unused," + "op_monitorx_mwaitx_r8,op_monitorx_mwaitx_intbrk,op_monitorx_rcx_rdx," + "op_add32_rdpru,op_cmp32_mwaitx") + string(CONCAT cpu_amd_monitor_rdpru_aot_exports ${cpu_amd_monitor_rdpru_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_amd_monitor_rdpru_aot_${variant} amd_monitor_rdpru_aot) + cpu_translation(cpu_amd_monitor_rdpru_aot_${variant} cpu_amd_monitor_rdpru_aot "${cpu_amd_monitor_rdpru_aot_exports}") + endforeach() + target_compile_definitions(cpu_amd_monitor_rdpru_aot_altered PRIVATE ALTER_AMD_EXT) + set(cpu_amd_monitor_rdpru_o2 "${CMAKE_CURRENT_BINARY_DIR}/cpu_amd_monitor_rdpru_aot_original_lifted_o2.dll") + add_custom_command(OUTPUT "${cpu_amd_monitor_rdpru_o2}" + COMMAND "${CMAKE_CXX_COMPILER}" /nologo /O2 /W4 /LD + "${CMAKE_CURRENT_BINARY_DIR}/cpu_amd_monitor_rdpru_aot_original_lifted.cpp" + "/Fo${CMAKE_CURRENT_BINARY_DIR}/cpu_amd_monitor_rdpru_aot_original_lifted_o2.obj" + "/Fe${cpu_amd_monitor_rdpru_o2}" + DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/cpu_amd_monitor_rdpru_aot_original_lifted.cpp" VERBATIM) + add_custom_target(cpu_amd_monitor_rdpru_aot_original_lifted_o2 ALL DEPENDS "${cpu_amd_monitor_rdpru_o2}") + set(cpu_amd_monitor_rdpru_mutants_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpu_amd_monitor_rdpru_aot_mutants.cpp") + add_custom_command(OUTPUT "${cpu_amd_monitor_rdpru_mutants_cpp}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/amd_monitor_rdpru_aot_check.py" + emit-mutants "$" "${cpu_amd_monitor_rdpru_mutants_cpp}" + DEPENDS cpu_amd_monitor_rdpru_aot_original tests/cpu/amd_monitor_rdpru_aot_check.py + tools/cpu_amd_monitor_rdpru_aot.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_amd_monitor_rdpru_aot_mutants SHARED "${cpu_amd_monitor_rdpru_mutants_cpp}") + add_dependencies(cpu_amd_monitor_rdpru_aot_mutants cpu_amd_monitor_rdpru_aot_original_lifted_o2) + add_test(NAME cpu_aot_amd_monitor_rdpru COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/amd_monitor_rdpru_aot_check.py" + "$" + "$" + "${cpu_amd_monitor_rdpru_o2}" + "$" + "$" + "$") + set_tests_properties(cpu_aot_amd_monitor_rdpru PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_amd_monitor_rdpru.txt") cpu_asm_fixture(cpu_rdrand_harness rdrand_harness) # The opt-in host-entropy profile. RDRAND and RDSEED have their own fixtures and tests, each exiting 77 when # the host lacks the instruction. Each part has the lifted DLL, deterministic succeed and fail variants that @@ -7466,9 +8841,15 @@ if(EXISTS "${INTAKE_PYTHON}") list(APPEND x87_scale_control_files "$") endif() endforeach() + x2w_add_check_part(cpu_aot_x87_scale native "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" + check-native "$" "$") + x2w_add_check_part(cpu_aot_x87_scale lifted "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" + check-lifted "$" "$") + x2w_add_check_part(cpu_aot_x87_scale controls "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" + check-controls "$" "$" ${x87_scale_control_files}) add_test(NAME cpu_aot_x87_scale COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_scale.py" - check "$" "$" - "$" ${x87_scale_control_files}) + check-rejections) + x2w_require_check_parts(cpu_aot_x87_scale native lifted controls) cpu_asm_fixture(cpu_x87_fcmov x87_fcmov) # The lifted DLL and eight mutated controls that the check requires to mismatch. set(x87_fcmov_control_files "") @@ -7553,9 +8934,15 @@ if(EXISTS "${INTAKE_PYTHON}") list(APPEND x87_fprem_control_files "$") endif() endforeach() + x2w_add_check_part(cpu_aot_x87_fprem lifted "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" + check-lifted "$" "$") + x2w_add_check_part(cpu_aot_x87_fprem native "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" + check-native "$" "$") + x2w_add_check_part(cpu_aot_x87_fprem controls "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" + check-controls "$" "$" ${x87_fprem_control_files}) add_test(NAME cpu_aot_x87_fprem COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_fprem.py" - check "$" "$" - "$" ${x87_fprem_control_files}) + check-light) + x2w_require_check_parts(cpu_aot_x87_fprem lifted native controls) cpu_asm_fixture(cpu_x87_fldcw x87_fldcw) # The checked translation and seventeen mutated controls that the check requires to mismatch. set(x87_fldcw_control_files "") @@ -8852,6 +10239,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$") add_test(NAME script_state_probe_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_state_probe_check.py") + add_test(NAME script_state_probe_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/script_state_probe_cli_check.py") + set_tests_properties(script_state_probe_cli_check PROPERTIES TIMEOUT 60) add_test(NAME script_typed_path_dispatch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$" TypedScriptPathTests) add_test(NAME bcpack_prefix_and_mip_tail COMMAND "${INTAKE_PYTHON}" -B @@ -8879,6 +10269,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/bc7_blocks_cli_check.py") add_test(NAME texture_descriptors_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/texture_descriptors_check.py") + add_test(NAME textures_texture_descriptors_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/texture_descriptors_cli_check.py") + set_tests_properties(textures_texture_descriptors_cli_check PROPERTIES TIMEOUT 60) add_test(NAME resource_range_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/resource_ranges_check.py") add_test(NAME ttpf_batch_export COMMAND "${INTAKE_PYTHON}" -B @@ -8891,6 +10284,14 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/awc_metadata_cli_check.py") add_test(NAME sgd5_effect_candidates COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_check.py") + add_test(NAME pixel_aot_sample_clamp_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_clamp_check.py") + add_test(NAME pixel_aot_sample_clamp_compile COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_clamp_check.py" compile "${DXC_EXECUTABLE}") + set_tests_properties(pixel_aot_sample_clamp_compile PROPERTIES TIMEOUT 90) + add_test(NAME shader_sgd5_effects_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_cli_check.py") + set_tests_properties(shader_sgd5_effects_cli_check PROPERTIES TIMEOUT 60) add_test(NAME rdna2_tools_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/rdna2_tools_check.py") add_test(NAME rdna2_cli_checks COMMAND "${INTAKE_PYTHON}" -B @@ -8964,10 +10365,28 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_mesh57_skeleton_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_loop_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_loop_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_loop_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_lane_spill_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_lane_spill_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_lane_spill_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_skeleton_wave_shift_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" shift "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_mesh57_skeleton_wave_shift_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + # A slot 57 pair whose pixel stage exports only to the null target, drawn depth-only (#2413 T5). + add_test(NAME startup_mesh57_skeleton_depth_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" depth "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_skeleton_depth_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + # A slot 57 colour pair whose pixel stage leaves a kill through the early-exit null export (#2413). + add_test(NAME startup_mesh57_skeleton_kill_exit_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" killexit "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_skeleton_kill_exit_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_formatted_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" formatted "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9141,11 +10560,21 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mubuf_subword_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_subword_${adapter}.txt") + add_test(NAME compute_store_aot_alu_vop1_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_alu_vop1_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_alu_vop1_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_alu_vop1_${adapter}.txt") add_test(NAME compute_store_aot_f32_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-f32 "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(compute_store_aot_f32_${adapter} PROPERTIES TIMEOUT 60 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_f32_${adapter}.txt") + add_test(NAME compute_store_aot_alu_bfm_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_alu_bfm_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_alu_bfm_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_alu_bfm_${adapter}.txt") add_test(NAME compute_store_aot_cvt_u32_f32_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-cvt-u32-f32 "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9260,6 +10689,13 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mubuf_float_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_float_${adapter}.txt") + foreach(float_extra IN ITEMS float-cmpswap float-x2) + add_test(NAME compute_store_aot_mubuf_${float_extra}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" "draw-mubuf-${float_extra}" "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mubuf_${float_extra}_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_${float_extra}_${adapter}.txt") + endforeach() add_test(NAME compute_store_aot_mubuf_vector_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mubuf-vector "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9280,6 +10716,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_alu_xor3_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_alu_xor3_${adapter}.txt") + add_test(NAME compute_store_aot_f32_negabs_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_alu_negabs_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_f32_negabs_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_alu_bcnt_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_alu_bcnt_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9387,6 +10827,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_gfx1013_gather4_l_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_gather4_l_${adapter}.txt") + add_test(NAME compute_store_aot_salu_bitset_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_salu_bitset_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_salu_bitset_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_salu_bitset_${adapter}.txt") add_test(NAME compute_store_aot_mimg_store_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mimg-store "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9437,6 +10882,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_lds_private_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_lds_private_${adapter}.txt") + add_test(NAME compute_store_aot_lds_shared_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-lds-shared "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_lds_shared_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_lds_shared_${adapter}.txt") add_test(NAME compute_store_aot_lds_packed_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-lds-packed "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9490,6 +10940,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_descriptor_load_format_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME compute_store_aot_descriptor_load_format_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_load_format_check.py" draw-d16 "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_descriptor_load_format_d16_${adapter} PROPERTIES TIMEOUT 120 + SKIP_RETURN_CODE 77) add_test(NAME compute_store_aot_heap_view_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_heap_view_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9578,6 +11033,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_f16_exact_extra_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_exact_extra_${adapter}.txt") + add_test(NAME pixel_aot_f16_cvt_norm_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-cvt-norm "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_f16_cvt_norm_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_cvt_norm_${adapter}.txt") add_test(NAME pixel_aot_sdwa_cvt_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-sdwa-cvt "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9721,6 +11181,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_sample_offset_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sample_offset_${adapter}.txt") + # Keep these desktop differential results out of opcode coverage until native gfx1030 is measured. + add_test(NAME pixel_aot_sample_clamp_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_sample_clamp_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sample_clamp_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77 RUN_SERIAL TRUE) add_test(NAME pixel_aot_sample_gradient_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_sample_gradient_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -9985,6 +11450,19 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_pack_b32_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_pack_b32_${adapter}.txt") + foreach(mode IN ITEMS level bias) + set(test_name pixel_aot_compare_lod_${mode}_${adapter}) + add_test(NAME ${test_name} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_compare_lod_check.py" draw "${mode}" "${DXC_EXECUTABLE}" + "$" "${adapter}") + set_tests_properties(${test_name} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/${test_name}.txt") + endforeach() + add_test(NAME pixel_aot_compare_grad_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_compare_grad_check.py" draw "${DXC_EXECUTABLE}" + "$" "${adapter}") + set_tests_properties(pixel_aot_compare_grad_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_compare_grad_${adapter}.txt") add_test(NAME pixel_aot_compare_sample_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_compare_sample_check.py" draw "${DXC_EXECUTABLE}" "$" "${adapter}") @@ -10113,8 +11591,13 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_BINARY_DIR}/triangle_vs.cso" "${DXC_BIN_DIR}/dxil.dll") set_tests_properties(shader_metadata_probe PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME shader_metadata_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_probe_check.py") + add_test(NAME shader_rdna_cvt_pk_u8_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/rdna_cvt_pk_u8_cli_check.py") + set_tests_properties(shader_rdna_cvt_pk_u8_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_metadata_census COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") + add_test(NAME shader_census_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_census_cli_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_profile_audit_check.py") add_test(NAME shader_profile_audit_cli_check COMMAND "${INTAKE_PYTHON}" -B @@ -10178,16 +11661,25 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$") add_test(NAME layout_chunk_summary COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/layout_chunks_check.py") + add_test(NAME textures_paged_resource_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/paged_resource_check.py") + set_tests_properties(textures_paged_resource_check PROPERTIES TIMEOUT 60) add_test(NAME dependency_paths_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dependency_paths_check.py") add_test(NAME pe_dependency_paths_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dependency_paths_cli_check.py") add_test(NAME pe_package_import_closure COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_check.py") + add_test(NAME pe_package_preflight_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_cli_check.py") + set_tests_properties(pe_package_preflight_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_inventory_cli_check.py") add_test(NAME call_evidence_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/call_evidence_check.py") + add_test(NAME pe_call_evidence_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/call_evidence_cli_check.py") + set_tests_properties(pe_call_evidence_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_run_package_invalid_pe COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_run_package_invalid_check.py") add_test(NAME pe_run_package_plan_check COMMAND "${INTAKE_PYTHON}" -B @@ -10196,6 +11688,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pe_run_package_cli_check.py") add_test(NAME pe_intake_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/intake_exe_check.py") + add_test(NAME pe_intake_exe_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/intake_exe_cli_check.py") + set_tests_properties(pe_intake_exe_cli_check PROPERTIES TIMEOUT 60) add_test(NAME pe_host_commit_preflight COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/host_commit_check.py") add_test(NAME xgameruntime_preflight_stub_refused COMMAND "${INTAKE_PYTHON}" -B @@ -10210,14 +11705,23 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(pe_run_package_trap_missing PROPERTIES TIMEOUT 60) add_test(NAME bink_heap_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_heap_aot_check.py") + add_test(NAME runtime_bink_heap_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_heap_aot_cli_check.py") + set_tests_properties(runtime_bink_heap_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_frame_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_frame_aot_check.py") + add_test(NAME runtime_bink_frame_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_frame_aot_cli_check.py") + set_tests_properties(runtime_bink_frame_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME cpu_stdio_exe_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu_stdio_exe_aot_check.py") # Documented in the AGENTS platform-independent list but never registered here, so ctest did # not run them locally while the CI Python job did. add_test(NAME bidi_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bidi_controls_check.py") + add_test(NAME ci_form_reference_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/form_reference_cli_check.py") + set_tests_properties(ci_form_reference_cli_check PROPERTIES TIMEOUT 60) add_test(NAME compat_report COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compat_report_check.py") add_test(NAME pe_compat_report_cli_check COMMAND "${INTAKE_PYTHON}" -B @@ -10228,6 +11732,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/gpu_report_format_check.py") add_test(NAME hardware_reports COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/hardware_reports_check.py") + add_test(NAME tooling_hardware_reports_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/hardware_reports_cli_check.py") + set_tests_properties(tooling_hardware_reports_cli_check PROPERTIES TIMEOUT 60) add_test(NAME shader_corpus_report COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_corpus_report_check.py") add_test(NAME xgameruntime_table COMMAND "${INTAKE_PYTHON}" -B @@ -10240,8 +11747,14 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/probe_root_devices_check.py") add_test(NAME ffx_working_set_delta_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/ffx_working_set_delta_check.py") + add_test(NAME ffx_working_set_delta_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ffx_working_set_delta_cli_check.py") + set_tests_properties(ffx_working_set_delta_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bink_descriptors_aot_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_check.py") + add_test(NAME tooling_bink_descriptors_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_cli_check.py") + set_tests_properties(tooling_bink_descriptors_aot_cli_check PROPERTIES TIMEOUT 60) add_test(NAME range_manifest_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/range_manifest_check.py") add_test(NAME pe_resource_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B @@ -10304,6 +11817,14 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() endif() +# Per-family registration fragments (see tests/cmake/README.md). Included after every helper and +# target above and before the slow-test costs below, in name order. A new file re-runs configure. +file(GLOB X2W_TEST_FRAGMENTS CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/tests/cmake/*.cmake") +list(SORT X2W_TEST_FRAGMENTS) +foreach(x2w_fragment IN LISTS X2W_TEST_FRAGMENTS) + include("${x2w_fragment}") +endforeach() + # Start the slowest tests first so the ctest worker pool has no long tail at the end. # COST only changes scheduling order under `ctest --parallel`; no test, argument or assertion changes. # Costs are measured seconds (approx.) from the Windows CI ctest log taken when this list was added diff --git a/CMakePresets.json b/CMakePresets.json index 1327cb6171..8fff29df28 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,10 +29,16 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", - "startup_indirect_dispatch", "startup_indirect_draw_indexed" + "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check", + "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", + "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", + "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", + "xmem_page_runs_device_check", "linear_buffer_backing_check", + "bcpack_formats_check", "startup_stub_consumer" ] }, - { "name": "release", "configurePreset": "release" } + { "name": "release", "configurePreset": "release" }, + { "name": "runtime", "configurePreset": "release", "targets": ["startup_runtime"] } ], "testPresets": [ { "name": "dev", "configurePreset": "dev", "output": { "outputOnFailure": true } }, @@ -42,7 +48,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package)$" } } }, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f960f92a10..372442385a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,10 +27,14 @@ Start with the [first build](README.md#first-build). Create the Python environme | `src/` | Windows runtime implementations and their observable behavior. | | `tests/` | C++, HLSL and generated-input fixtures. Tests ending in `_warp` use the software adapter. Those ending in `_hardware` use a physical GPU. | | `tools/` | Build setup and offline metadata tools. The PE fixtures live in `tests/intake/`. | -| `docs/experiments.md` | Measured results, assumptions and reproduction commands. | +| `docs/experiments.md` | Older measured results, assumptions and reproduction commands. New notes go in `docs/experiments/.md`. | +| `tests/cmake/` | One `.cmake` file per test family or pull request; [CMakeLists.txt](CMakeLists.txt) includes each. See [its README](tests/cmake/README.md). | +| `tests/checks/` | Text files that add Python checks to the Linux CI jobs without editing the workflow. See [its README](tests/checks/README.md). | On pull requests, `Build and test on Windows` builds the smoke-test targets with `cmake --build --preset pr` and runs `ctest --preset pr --no-tests=error`. The preset selects tests for CPU translation, PE startup, memory, archive decoding and WARP rendering, including the SPIR-V bridge checks. The bridge checks can skip locally if their tools are missing; hosted CI installs the pinned tools and requires the WARP bridge checks to pass. For a strict local run, run [the pinned tool setup](tools/setup-spirv-tools.ps1) (`.\tools\setup-spirv-tools.ps1` in PowerShell) before configuring or reconfiguring, then set `$env:X2W_REQUIRE_SPIRV_TOOLS = '1'` before running CTest. Run the tests for your specific change locally and include their results in the PR. +Pull requests into `cpp-migration` also build `compile_dxil` and run `native_dxil_llvm_ident_controls` on Windows to check direct DXIL generation. + On `main` and manual runs, CI runs the full non-hardware suites in Debug and Release (/O2), generates the coverage chart and smoke-tests the standalone GPU package. To check a branch in both configurations before merge, select it under **Actions → Windows checks → Run workflow**. The Ubuntu jobs assemble gfx1013 fixtures with LLVM 15 and run the platform-independent Python checks. [CI workflow](.github/workflows/windows.yml) Contributors supply physical GPU coverage. Record the commit, adapter and driver, Windows version, test names and debug-layer status. Include the feature tier or wave width when relevant. Report capability skips separately from passes and failures. [Non-Windows host guide](docs/non-windows-hosts.md) diff --git a/README.md b/README.md index 39a74b4385..bd6b59850d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Xbox2Windows -**[Join the Xbox2Windows Dev Discord](https://discord.gg/DMcmNtpd6R)** · [Project status](#current-results-and-open-work) · [Get involved](#community-and-contributions) · [Build on Windows](#first-build) · [Run the GPU check](#run-the-gpu-check) +**[Join the Xbox2Windows Dev Discord](https://discord.gg/DMcmNtpd6R)** · [Project status](#current-results-and-open-work) · [Get involved](#community-and-contributions) · [Build on Windows](#first-build) · [Choose an experiment](#choose-an-experiment) · [Coverage chart](#instruction-coverage) · [Run the GPU check](#run-the-gpu-check) Xbox2Windows researches static recompilation from Xbox Series X|S (Scarlett) to x64 Windows. It translates selected x64 machine code into C++ and selected gfx1013 shaders into desktop DXIL. You can run the public tests without a game installation. @@ -109,7 +109,8 @@ After the full [Windows build](#first-build), run one comparison from the reposi | PE 32/64-bit base fixups against Windows | `ctest --preset dev --no-tests=error -R '^cpu_native_highlow$' -V` · [scope and controls](docs/experiments.md#highlow-and-mixed-width-base-relocations) | | [CPU counted cache-line zero loops](docs/experiments.md#counted-cache-line-zero-loops) | `ctest --preset release --no-tests=error -R '^cpu_counted_clzero$' -V` | | [Experimental startup stand-ins and debugger (trap-by-default DLLs)](docs/startup-runtime.md) | `ctest --preset release --no-tests=error -R '^startup_stubs$' -V` | -| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight' -V` | +| [Diagnostic fallback for missing graphics shader translations](docs/experiments/missing-shader-fallback.md) | `ctest --preset dev --no-tests=error -R '^startup_missing_shader_fallback(_off)?_warp$' -V` | +| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) · [page runs](docs/experiments/xmem-page-runs.md) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` | | [Sample a texture by address in a translated draw](docs/startup-runtime.md#textures-published-by-address-device-slot-70) | `ctest --preset release --no-tests=error -R '^startup_address_console_' -V` | | [Desktop audio render sink and its three-case fixture (WASAPI)](docs/experiments.md#desktop-audio-render-sink) | `ctest --preset release --no-tests=error -R '^startup_audio_output$' -V` | @@ -123,7 +124,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | CPU differential fuzz | Generate 20 deterministic leaf functions from seed `0xA902`, translate them, and compare native, default and `/O2` builds over 313 inputs each. | `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_smoke$' -V` | | Script states | Reproduce a parent/child lookup, an ambiguous selection or a damaged sibling link with a synthetic tree. | `ctest --preset dev --no-tests=error -R '^script_(state_literals\|path_links)$' -V` | | Resource metadata | Check a [relocated resource root](docs/experiments.md#relocated-resource-root) against its block directory and type schema. | `ctest --preset dev --no-tests=error -R '^resource_relocated_root$' -V` | -| Texture recovery | [Decode MDU rANS symbols](docs/experiments.md#decoding-mdu-rans-symbol-streams) using [bcpack-rs by Ahmet Dedeler](https://github.com/Ahmet-Dedeler/bcpack-rs), or check a packed mip tail, a first refill byte, the fields of a generated BC7 block, or a resident mip drawn on the software adapter. [Look up a texture key across archives and inspect a matching descriptor](docs/experiments.md#reading-logical-ranges-and-probing-structured-resources). [Batch export TTPF textures with optional Rust kernels](docs/experiments.md#batch-export-ttpf-textures-to-dds). | `ctest --preset dev --no-tests=error -R '^(bcpack_prefix_and_mip_tail\|bcpack_rans_symbols\|bc7_block_reference\|bc7_draw_warp\|resource_range_controls)$' -V` | +| Texture recovery | [Check standalone BCPack BC1–BC7 reconstruction](docs/experiments/bcpack-standalone.md) or [decode MDU rANS symbols](docs/experiments.md#decoding-mdu-rans-symbol-streams) using [bcpack-rs by Ahmet Dedeler](https://github.com/Ahmet-Dedeler/bcpack-rs), or check a packed mip tail, a first refill byte, the fields of a generated BC7 block, or a resident mip drawn on the software adapter. [Look up a texture key across archives and inspect a matching descriptor](docs/experiments.md#reading-logical-ranges-and-probing-structured-resources). [Batch export TTPF textures with optional Rust kernels](docs/experiments.md#batch-export-ttpf-textures-to-dds). | `ctest --preset dev --no-tests=error -R '^(bcpack_all_formats\|startup_bcpack_storage\|bcpack_prefix_and_mip_tail\|bcpack_rans_symbols\|bc7_block_reference\|bc7_draw_warp\|resource_range_controls)$' -V` | | Audio metadata | Inventory stream counts, codec IDs and sample rates in a bounded [AWC sound-effect or music bank](docs/experiments.md#awc-sound-effect-format-metadata) with flag word `0xff000001` or `0xff020001`. | `ctest --preset dev --no-tests=error -R '^audio_awc_metadata$' -V` | | Compute shader recompilation | Translate fixed, indexed and row-pitch raw UAV stores for 1D, 2D and 3D thread groups, including an optional runtime constant buffer, and compare the complete buffer on D3D12. [Bindings and commands](docs/experiments.md#compute-uav-stores-from-a-native-container) · [Bounded gfx1030 DS lane routing](docs/experiments.md#bounded-gfx1030-ds-lane-routing) · [Private gfx1030 LDS access and updates, including 64-bit min/max and xor](docs/experiments.md#private-gfx1030-lds-word-access) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_'` | | gfx1013 compute DPP16 | Lower `v_or_b32_dpp` with `quad_perm`, and `v_or_b32_dpp`/`v_add_nc_u32_dpp` with `row_shr:1`–`15` with or without `bound_ctrl`, under full row/bank masks; compare source-built fixtures with logical-thread references. Scope and limits: [quad_perm](docs/experiments.md#gfx1013-compute-dpp16-quad-permutation), [row_shr](docs/experiments.md#gfx1013-compute-dpp16-row-shift-right) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_dpp_' -V` | @@ -139,6 +140,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 atomic buffer exchanges | Lower [fixed-address MUBUF integer swap and compare-swap](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-exchanges) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_exchange'` | | gfx1030 conditional atomic subtract | Lower [fixed-address `buffer_atomic_csub`](docs/experiments.md#gfx1030-fixed-address-mubuf-conditional-subtract) when the program discards the old value. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_csub_'` | | gfx1030 atomic buffer float min/max | Lower [fixed-address `buffer_atomic_fmin`/`fmax`](docs/experiments.md#gfx1030-fixed-address-mubuf-float-minmax) under the caller's finite-normal domain and verify the folded word against a CPU float reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float_'` | +| gfx1030 floating buffer compare-swap and x2 | Lower [fixed-address FP32 compare-swap and FP64 compare-swap/min/max](docs/experiments.md#gfx1030-fixed-address-mubuf-float-compare-swap-and-x2) for finite normals. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float-(cmpswap|x2)_'` | | gfx1030 atomic buffer counters | Lower [fixed-address MUBUF bounded increment and decrement](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-counters) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_counter'` | | gfx1013 32-bit buffer atomics | Lower [raw UAV add, unsigned max and compare-swap](docs/experiments.md#gfx1013-32-bit-mubuf-buffer-atomics) and check old-value returns and contended add serialization. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_buffer_atomics_'` | | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | @@ -148,6 +150,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1013 image atomics | Lower [2D `R32_UINT` `image_atomic_add`, `umax` and `cmpswap`](docs/experiments.md#gfx1013-2d-image-atomics) with the gfx1030 lowering and compare every texel of a three-mip texture, including contended adds. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_atomics_'` | | gfx1013 image gathers | Lower [one 2D `image_gather4_l` with a constant sampler and a known integer LOD](docs/experiments.md#gfx1013-2d-explicit-lod-image-gathers) on an RGBA32 FLOAT view. Compare all four taps at three mips and on a view that starts at mip 1. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_gather4_l_'` | | Startup compute mip-zero gather | Dispatch a [gfx1013 `image_gather4_lz`](docs/experiments.md#compute-mip-zero-gather) and compare four texels from the first visible mip against a CPU reference. | `ctest --preset dev --no-tests=error -R '^startup_compute_gather_lz'` | +| Startup compute FP32 and packed D16 array image store | Bind a [2D-array UAV](docs/experiments/startup-compute-array-uav.md) through the startup runtime, verify the nonzero first slice and per-lane EXEC, and compare every texel after the fence. | `ctest --preset dev --no-tests=error -R '^startup_compute_dispatch_array_'` | | Startup compute D16 image store | Write [four packed half-floats](docs/experiments.md#startup-compute-d16-image-store) per active thread and check all three mips. | `ctest --preset dev --no-tests=error -R '^startup_compute_image_store_d16'` | | Startup explicit-LOD 2D gather | Dispatch and draw [gfx1013 `image_gather4_l`](docs/experiments.md#explicit-lod-2d-gather) across explicit mips, view offsets, clamped edges, and dynamic per-lane LOD against CPU references. | `ctest --preset dev --no-tests=error -R '^startup_compute_gather_l'` | | Startup compute buffer atomics | Dispatch [gfx1013 32-bit MUBUF raw buffer atomics](docs/experiments.md#startup-compute-raw-buffer-atomics) with thread contention, `glc` old-value returns, `cmpswap` order, and `EXEC` masking. | `ctest --preset dev --no-tests=error -R '^startup_compute_buffer_atomics'` | @@ -168,10 +171,12 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | | gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. The experimental `xyz` form requires a caller-verified W-preservation contract. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | -| Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw`](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | +| Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | | Heap-view buffer loads | Lower [gfx1013 indexed `buffer_load_format_xy/xyzw` from a run-time view record](docs/experiments.md#heap-view-buffer-loads): base, stride, `num_records` and format come from the record at a chosen slot. An index past `num_records` reads zero; a view that is not live, a bad slot or a bad format leaves the output unwritten. The record table is a side table inside t0; the SM 6.6 heap lookup is not wired yet. | `ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_\|heap_view_controls$)'` | | Descriptor-format buffer stores | Lower [indexed `buffer_store_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-stores), reading the GFX10 or legacy format from V# word 3. Unknown formats are refused. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_store_format_'` | | gfx1030 depth-comparison sampling | Lower [2D comparison samples with and without offsets](docs/experiments.md#gfx1030-2d-comparison-sampling). | `ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_' -V` | +| gfx1030 comparison sample gradients | Lower [2D comparison samples with explicit FP32 or G16 gradients](docs/experiments.md#gfx1030-2d-comparison-sample-gradients) and optional signed offsets for a two-mip point-filtered view. | `ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_compare_grad_' -V` | +| gfx1030 comparison sample LOD and bias | Lower [2D comparison samples with explicit LOD or instruction bias](docs/experiments.md#gfx1030-2d-comparison-sample-lod-and-bias) for two point-filtered mips, with optional signed offsets. | `ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_compare_lod_' -V` | | gfx1030 pixel sampling offsets | Lower [four 2D sample offset forms](docs/experiments.md#offline-pixel-shader-recompilation) with a known packed XY displacement. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_offset_' -V` | | gfx1030 coarse-gradient pixel sampling | Lower [four 2D coarse-gradient forms](docs/experiments.md#gfx1030-2d-explicit-and-coarse-gradient-sampling) with statically known finite slopes. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_coarse_gradient_' -V` | | gfx1030 explicit-gradient pixel sampling | Lower [four 2D gradient sample forms](docs/experiments.md#offline-pixel-shader-recompilation), including packed binary16 slopes and immediate offsets. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_gradient_' -V` | @@ -211,17 +216,18 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | Adapter or backend | Default native lanes | Forced wave64 | BVH differential | Evidence | |---|---:|---|---|---| | NVIDIA GeForce RTX 2060 | 32 | Skipped | 408 queries passed | [Maintainer baseline](docs/experiments.md#independent-bvh-checks-on-pc) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077064410) | -| NVIDIA GeForce RTX 3070 (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [RTX 3070 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063566753) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064780514) · [Independent 32.0.16.2101 run, source build at b860dd5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070552394) · [Independent 32.0.16.1088 run, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084482487) | +| NVIDIA GeForce RTX 3070 (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [RTX 3070 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063566753) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064780514) · [Independent 32.0.16.2101 run, source build at b860dd5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070552394) · [Independent 32.0.16.1088 run, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084482487) · [32.0.16.1742 report by @hencydsouza, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7170984432) · [32.0.16.1656 report by @upipibi, source 2f7fd28, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7175561067) | | NVIDIA GeForce RTX 3070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1692 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7099622883) · [32.0.16.1742 report, Windows build 26200](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7121943659) · [32.0.16.2114 report by @Maxim-Root, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7129028243) · [32.0.16.1088 (610.88) report by @wanchudao](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7166634226) | -| NVIDIA GeForce RTX 4060 Laptop GPU | 32 | Skipped | 408 queries passed | [Second maintainer workstation](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7058907095) · [Independent Windows run, driver 32.0.16.2124](https://github.com/R0Y00/Xbox2Windows/issues/60) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064580375) · [32.0.16.1091 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082946105) | +| NVIDIA GeForce RTX 4060 Laptop GPU | 32 | Skipped | 408 queries passed | [Second maintainer workstation](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7058907095) · [Independent Windows run, driver 32.0.16.2124](https://github.com/R0Y00/Xbox2Windows/issues/60) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064580375) · [32.0.16.1091 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082946105) · [32.0.16.2124 report by @vfd9654, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7165908151) | | NVIDIA GeForce RTX 5070 | 32 on every run | Skipped on every run, lane range 32–32 | 408 queries passed per run | [32.0.16.1692, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063361337) · [32.0.16.2135 retest, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063626309) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066814242) · [32.0.16.1686 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067154644) · [Independent 32.0.16.2135 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068151257) · [38.0.1.104 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066183143) | | AMD Radeon RX 6600 (driver 32.0.21045.16010) | 32 | Passed, 64 lanes; skipped, Shader Model 6.5 on build 19044 | 408 queries passed | [RX 6600 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063312495) · [32.0.11037.4004 retest](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063794169) · [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064667296) · [32.0.21030.2001 report, Windows 10 build 19044](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080061922) · [31.0.22017.3004 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080963908) · [Independent 32.0.21045.29003 run, Windows build 26300](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7122426568) | | AMD Radeon RX 6750 XT (driver 32.0.21045.29003) | 32 | Passed, 64 lanes | 408 queries passed | [RX 6750 XT report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7062253227) | | AMD Radeon RX 6800 XT (driver 32.0.21043.5001) | 32 | Passed, 64 lanes | 408 queries passed | [RX 6800 XT report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063629409) · [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7114922639) | | AMD Radeon RX 9070 (driver 32.0.22042.14002) | 64 | Passed, 64 lanes | 408 queries passed | [RX 9070 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7062384428) · [32.0.32029.2010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066611485) | -| AMD Radeon RX 9070 XT (driver 32.0.32015.16001) | 64 | Passed, 64 lanes | 408 queries passed | [RX 9070 XT report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063426420) · [32.0.32029.2010 retest, D3D12 warning 989](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063787553) · [32.0.32015.16001 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064744246) · [32.0.32015.7029 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065371244) · [32.0.32029.2010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065554754) · [32.0.32029.2010 run 3](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066677824) · [32.0.32029.2010 run 4](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066940493) · [32.0.32029.2010 run 5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068364653) · [32.0.32015.12012 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068740351) · [32.0.32029.2010 source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071126769) · [32.0.32029.2010 run 6, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085696786) · [32.0.31044.16 source build, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7113579998) · [32.0.32015.7029 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7133166858) | +| AMD Radeon RX 9070 XT (driver 32.0.32015.16001) | 64 | Passed, 64 lanes; lane range 32–64 | 408 queries passed | [RX 9070 XT report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063426420) · [32.0.32029.2010 retest, D3D12 warning 989](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063787553) · [32.0.32015.16001 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064744246) · [32.0.32015.7029 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065371244) · [32.0.32029.2010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065554754) · [32.0.32029.2010 run 3](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066677824) · [32.0.32029.2010 run 4](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066940493) · [32.0.32029.2010 run 5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068364653) · [32.0.32015.12012 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068740351) · [32.0.32029.2010 source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071126769) · [32.0.32029.2010 run 6, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085696786) · [32.0.31044.16 source build, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7113579998) · [32.0.32015.7029 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7133166858) · [32.0.32029.2010 source build at 49f53ae6, Windows build 26200.9974, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7190843348) | | NVIDIA GeForce RTX 4060 Ti (driver 32.0.16.1742) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063740292) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066549178) | | AMD Radeon RX 7900 GRE (driver 32.0.32015.7029) | 32 | Passed, 64 lanes | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063746749) | +| AMD Radeon RX 7900 XT (driver 32.0.32029.2010) | 32 | Skipped, Shader Model 6.6 unavailable (capped at 6.5 on Windows 10 build 19045) | 408 queries passed | [Windows 10 report, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7207902686) | | NVIDIA GeForce RTX 4070 Ti SUPER (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063783462) · [32.0.15.7270 report, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066125394) | | NVIDIA GeForce RTX 5080 (driver 32.0.16.2124) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063834333) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065170340) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065546749) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065671431) · [32.0.16.1692 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069515442) · [32.0.16.1714 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7073236219) · [32.0.16.2114 report, debug layer enabled, adapter filter RTX 5080](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120729216) | | NVIDIA GeForce RTX 5080 Laptop GPU (driver 32.0.15.8142) | 32 | Skipped, lane range 32–32 | Passed | [Package report by ChazY11](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118193451) | @@ -242,7 +248,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | NVIDIA GeForce RTX 3080 Ti Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2135 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064722299) | | AMD Radeon RX 6700 XT | 32 | Passed, 64 lanes; skipped at SM 6.5 on 32.0.21045.9003 | 408 queries passed | [32.0.21045.16010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064730965) · [32.0.21045.29003 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7076337541) · [Independent 32.0.21045.29003 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7081698039) · [32.0.21045.9003 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7106794867) | | NVIDIA GeForce RTX 4090 Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1656 report](https://github.com/R0Y00/Xbox2Windows/issues/64) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7138088095) | -| NVIDIA GeForce RTX 5070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064221428) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066648123) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068298651) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071681613) · [32.0.16.1714 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7086202845) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7135432772) | +| NVIDIA GeForce RTX 5070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064221428) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066648123) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068298651) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071681613) · [32.0.16.1714 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7086202845) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7135432772) · [32.0.16.2124 report by @alecselle, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7123603068) | | NVIDIA GeForce RTX 5050 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064238316) | | AMD Radeon RX 7800 XT | 32 on every run | Skipped on Windows 10 runs capped at Shader Model 6.5. Passed with 64 lanes in the other reports | 408 queries passed per run | [32.0.32015.16001 report, Windows 10 build 19045](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064791654) · [32.0.32029.2010 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/101) · [Independent 32.0.32029.2010 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068788175) · [32.0.32015.7029 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079560197) · [32.0.32015.16001 report, build 26300, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084752103) · [Third 32.0.32029.2010 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085397975) · [32.0.32029.2010 report, Windows 10 build 19045, Shader Model 6.5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7093682244) · [32.0.32029.2010 report, Windows build 26300.10075, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7124179405) | | NVIDIA GeForce GTX 1070 | 32 | Skipped, lane range 32–32 | Skipped, DXR tier 1.0 | [32.0.15.8180 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064831532) · [32.0.15.8278 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7078694248) · [32.0.15.8266 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079940198) | @@ -296,6 +302,9 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | NVIDIA GeForce GTX 1660 | 32 | Skipped, lane range 32–32 | Skipped, DXR tier 1.0 | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7127289449) | | AMD Radeon RX 6600M | 32 | Skipped, Shader Model 6.5 | 408 queries passed | [32.0.21045.29003 report, Windows 10 build 19045](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7128601597) | | AMD Radeon RX 7700 XT | 32 | Passed, 64 lanes | 408 queries passed | [32.0.32029.2010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7133365031) | +| Intel Arc A770 (driver 32.0.101.9175) | 32 (16 on direct run) | Skipped, lane range 8–32 | 408 queries passed per run | [Two runs by @Alexofbulgaria, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7190203497) | +| Intel Arc A380 | 16 | Skipped, lane range 8–32 | 408 queries passed | [32.0.101.9150 report, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7215498163) | +| NVIDIA GeForce RTX 3090 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2140 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7222246091) | | Microsoft WARP (software) | 4 | Skipped | 408 queries passed | [Maintainer baseline](docs/experiments.md#independent-bvh-checks-on-pc) · [10.0.26100.9711 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070173394) · [Independent 10.0.26100.9711 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070473372) · [10.0.26100.9711 source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071126769) · [10.0.26100.9818 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071853781) · [Independent 10.0.26100.9818 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077972845) | Under Linux translation layers (Wine or Proton with vkd3d-proton), Mesa RADV on an [AMD Ryzen 5 integrated GPU](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067289597), an [RX 9070 XT reported by @barbiscool](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069870226) and an [RX 570](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080566188) passed all forced-wave64 groups with zero mismatches; RADV defaults to 32-lane waves on the 9070 XT where Windows drivers default to 64. On the RX 570, vkd3d-proton exposes Shader Model 6.6, so forced wave64 ran where the Windows row skips at Shader Model 6.5; the BVH differential skipped at DXR tier 0. NVIDIA translation-layer runs on an [RTX 4070](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064884397), [RTX 5060 Ti](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067186626) and [RTX 3060](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064204388) reported a 32-lane maximum, skipped forced wave64 and passed 408 BVH comparisons. A [GTX 750 Ti](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080565902) also reported a 32-lane maximum and skipped forced wave64; its BVH differential skipped at DXR tier 0. The RX 570 and GTX 750 Ti reports show DXVK's placeholder driver 35.0.65535.65535 in the adapter line and name the physical card in the comment. diff --git a/docs/experiments.md b/docs/experiments.md index c84ebab6c6..8b26e9100a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1,5 +1,133 @@ # Experiment notes and reproduction commands +New notes go in `docs/experiments/.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes. + +## First native graphics draw through the stand-in + +Set `X2W_NATIVE_SHADERS` to the desktop DXC directory and `X2W_SHADER_CACHE` to a writable cache. +The stand-in reads the published graphics request, links the pair, and uses the compiler's persistent +frontend and bytecode caches. The runtime consumes the same supported binding manifest as the offline +compiler. The source-built triangle fixture uses one RGBA8 target and checks all 32 pixels in each +of two processes. A third process supplies an unsupported pixel stage and checks the untouched clear. + +```powershell +cmake --build --preset dev --target startup_stream_consumer d3d12_xs_shim compile_dxil +ctest --preset dev --no-tests=error -V -R '^startup_native_graphics_draw_(hardware|warp)$' +``` + +## Implicit derivatives in direct compute + +[Group shapes, lane mapping and readback fixtures](experiments/native-compute-implicit-derivatives.md) + +## Slot 67 wave size in direct compute + +State block A bit 20 of dword 4 selects the guest wave size. +[Capture inference and hardware fixture](experiments/native-slot67-wave-size.md) + +## Plain binary16 arithmetic in direct compute + +VOP2 and VOP3 add, sub, subrev and mul use binary32 arithmetic and an integer nearest-even conversion back +to binary16. [Plain-form experiment](experiments/f16-alu-direct.md) + +## SDWA binary16 arithmetic in direct compute + +The same four operations accept VGPR half selection, input abs and neg, and half-word destination placement +with pad or preserve. The readback fixture checks both halves and untouched buffer guards. +[SDWA experiment](experiments/native-sdwa-f16.md) + +## Guest logical 64-bit shift sources in direct compute + +Logical 64-bit shifts accept sign-extended inline integers, zero-extended +32-bit literals and numeric even SGPR pairs. The compute fixture checks +both directions, boundary shift amounts and the inline-float refusal. +[Experiment and reproduction commands](experiments/native-shift64-sources.md) + +## Guest quad permutations in direct compute + +DPP16 quad permutations reuse the row mirror's EXEC and operand handling. +The compute fixture checks arithmetic, lane selection and disabled sources. +[Experiment and reproduction commands](experiments/native-dpp-quad-compute.md) + +## Guest DPP16 row shifts and rotates in direct compute + +Full-mask row shifts and rotates stay inside each 16-lane row and apply +BOUND_CTRL to unusable sources. [Experiment and reproduction commands](experiments/native-dpp-row.md) + +## Guest permlane16 and permlanex16 in direct compute + +VOP3A row permutations select lanes using uniform packed selectors. +[Experiment and reproduction commands](experiments/native-permlane.md) + +## Guest lane reads and writes in direct compute + +`v_readlane_b32` and `v_writelane_b32` lower with a constant or SGPR lane; lane writes ignore EXEC. +Lane reads may refill `vcc_lo` and, in wave32, `vcc_hi` as ordinary scalar data. +[Experiment and reproduction commands](experiments/native-lane-access-compute.md) + +[Descriptor lane spill experiment](experiments/native-lane-spill-descriptor.md) + +## 64-bit scalar operations in direct compute + +`s_bfm_b64`, `s_cselect_b64` and `s_not_b64` lower to two scalar words. +The compute fixture reads both result words and SCC from two workgroups. +[Experiment and reproduction commands](experiments/native-salu64-ops.md) + +## Byte-window stores in direct compute + +Raw buffer stores accept a descriptor with a cleared stride, a byte count +derived from that descriptor's clamped stride, and the raw OOB selector. +The compute fixture reads back all four store widths across two workgroups. +[Experiment and reproduction commands](experiments/native-bytewin-store.md) + +## Guest row mirrors and masked branches in the direct DXIL frontend + +The hardware fixture gives each guest lane a distinct value. DPP16 control +`0x141` reverses each group of eight and `0x140` reverses each group of +sixteen. The reference implementation at Victory revision `9376fd6` computes +these indices in `victory-shader/src/emit/lower.rs::dpp`. Its `cross_lane` +check restricts pixel shaders to quad-local operations. The older Python +`pixel_aot.parse_dpp` also checks whether both halves use the same quad +permutation. The compute shader exchanges the first operand before applying the +local second operand. A sparse EXEC mask distinguishes fetching an inactive +source, supplying zero and retaining the destination. The test checks both +workgroups and the surrounding buffer guards. + +Wave32 direct compute lowers `s_or_saveexec_b32`. As with `s_mov_b32 exec_lo`, EXEC keeps bits past the group; a lane runs only if its own bit is set. + +The pixel fixture opens EXEC to all lanes, seeds a guest register with scalar +lane writes and reads back lanes in each half of a guest wave64. The compiler +can track those words independently of the desktop rasterizer's choice of +quads. A second fixture uses repeated min/max, alternate-row selection and +a scalar lane broadcast. An ordinary WQM pixel input whose source lies in +another quad still requires a guest pixel-wave layout. For structured vertex +EXEC branches the container fixture checks control-flow joins, saved-mask +clobbers and scalar values escaping a masked arm. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check +ctest --preset dev --no-tests=error -R '^(native_dpp_mirror_hardware|native_direct_container)$' +``` + +### Pixel coverage and whole-wave mask branches + +For a mask held in scalar registers, `s_wqm_b32` and `s_wqm_b64` expand +each occupied four-bit group to four ones. A scalar region that saves the +expanded EXEC or branches on zero tests the complete guest width. The fixture +includes a wave64 with only bit 32 set and a wave32 with the same two input +words. They take opposite branches. + +A separate pixel fixture interpolates a value, removes covered lanes where it +is negative, runs a quad permutation under WQM and restores exact coverage +before exporting. A survivor can read a neighbor whose coverage was removed. +Successive filters intersect the surviving coverage. This lowering checks that +an empty quad cannot contribute to another quad or leave an observable store. +A cross-quad permutation in the same live arm is a rejection control. + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -V -R '^native_graphics_wqm_hardware$' +``` + ## Desktop culling and front-face winding `raster_winding_warp` and `raster_winding_hardware` draw two mirrored triangles @@ -81,11 +209,37 @@ cmake --build --preset dev --target startup_present_producer ctest --preset dev --no-tests=error -R '^startup_present_producer_(warp|hardware)$' -V ``` +## Per-draw texel history + +`X2W_DRAW_DUMP_FRAME=` with `X2W_DRAW_DUMP_PIXEL=,` keeps one texel of render target 0 after +each translated draw of that frame instead of copying the whole target. The completed reads are +written to `pixel_history.txt` in `X2W_DRAW_DUMP_DIR`: `draw=` is the copy ordinal, `frame=` is the +frame that recorded it, `x=` and `y=` name the texel, `key=` is the translated manifest key, and +`rgba=` is decoded for R8G8B8A8/B8G8R8A8 UNORM or sRGB. +The same 48-copy bound as the full dump applies. A reader can follow the value after every draw and +name the one that last changed the texel. [`tools/startup/scene_color_report.py`](../tools/startup/scene_color_report.py) +turns a dump directory into a bounded Markdown report that selects a frame and pixel and names the +first retained change as well as the last writer; see [the report note](experiments/startup-scene-color-report.md). + +`startup_pixel_history` builds three draws on a 4x4 target. The first and third are scissored to the +top-left texel; only the second covers the watched texel (1, 1). The report must name draw 2 with its +manifest key, and the control that omits draw 2 must leave the texel black at draw 3. + +```powershell +cmake --build --preset dev --target startup_pixel_history +ctest --preset dev --no-tests=error -R '^startup_pixel_history_' -V +``` + ### Translated indirect triangles `X2W_TRANSLATED_INDIRECT_DRAW=1` lets a slot 57 cached translation record one non-indexed -`ExecuteIndirect` Draw on a direct list with triangle-list topology, one single-sample colour -target, an explicit viewport and scissor, and the root signature used to create the guest pipeline. +`ExecuteIndirect` Draw on a direct list with triangle-list topology, single-sample bound colour +and/or depth-stencil targets (up to 8 colour targets, colour plus depth-stencil, or depth-only), +an explicit viewport and scissor, and the root signature used to create the guest pipeline. +Sampled texture bindings must not alias any bound colour target or writable depth view, and a +translated pipeline with depth or stencil writes is refused against a read-only depth view +(`read_only_depth_write`). Non-translated desktop graphics pipelines keep the single colour-target +requirement without a depth view. The translated path binds its usual pipeline, root and sampled textures, then forwards the placed desktop argument buffer and offset. Its producer supplies legal D3D12 draw arguments. The shim checks the placed buffer range without reading the draw fields or limiting the GPU-generated vertex count. @@ -94,14 +248,14 @@ whose reflected constants depend on the draw's start vertex or instance. It also shader bytecode. A deferred guest root can still supply the recorded tables to the translated root. A missing cached translation retains the request publishing path. -Table buffer views bind their complete byte range, up to 16 MiB, from the recording's upload allocation, +Table buffer views bind their complete byte range up to the D3D12 raw-view limit from the recording's upload allocation, one unique aliased placed buffer, or a wrapped resource with desktop backing and no title shadow. The runtime refuses non-DWORD ranges, misaligned offsets, cross-device views, any view of the same resource that contains the indirect arguments, and copied placements with unproven desktop contents. It binds the accepted resource directly as a desktop raw SRV and uses its recorded stride for the shader entry. Run `cmake --build --preset release --target startup_indirect_draw_indexed` and -`ctest --preset release -j1 --no-tests=error -R '^startup_indirect_translated_draw_' -V`. +`ctest --preset release -j1 --no-tests=error -R '^startup_indirect_translated_(draw|targets)_' -V`. The fixture compiles source-built desktop shaders and installs their translation-cache manifest. A compute writer records one triangle at a nonzero offset in a placed GPU buffer with separate title backing. A fenced readback compares the argument, guard words and every colour pixel. @@ -110,7 +264,15 @@ binding the wrong root, using a short argument range or using a shader that read leaves the target clear. A second compute writer supplies distinguishing colours to a table buffer. The table's nonzero offset and stride select the second colour, the short view reads zero, and a non-aliased placement is refused. A raw descriptor over a recording-owned upload page reads the -same colour and refuses a view that crosses its allocation. +same colour and refuses a view that crosses its allocation. `startup_indirect_translated_targets_{warp,hardware}` +additionally checks two-target MRT, colour plus depth-stencil, depth-only (zero colour targets with a +depth view), refusal of zero attachments, and refusal of a sampled texture aliasing render target 1. + +The same test reads the last DWORD of a GPU-backed raw view extending 16 bytes beyond +16 MiB. The compute writer puts red there and green one element earlier. Shortening the +view by one element makes the pixel read zero although the resource still contains red. +The shim binds the existing GPU range directly and checks the complete range against its +backing and the D3D12 raw-view element limit. ### Index views backed by a recording upload @@ -158,6 +320,16 @@ The source is a same-device desktop resource with no title shadow, a unique alia or an already covered range. Later overlapping copies invalidate earlier coverage. The recording discards this proof at Close, so another recording needs its own writer. +`X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1` lets a translated compute Dispatch read an input that lies in a placed buffer which does +not alias title memory. That buffer's desktop copy is a committed default buffer that holds zeros, so the bytes the title wrote +exist only in title memory. The input resolves in this order: a validated GPU copy of the current recording (the proof above, +which needs `X2W_TRANSLATED_INDIRECT_COPY_RANGES=1`), else a snapshot of the range (at most 16 MiB) taken from title memory +into the snapshot pool when the Dispatch is recorded, else the refusal `an input is in a placed buffer that does not alias title +memory`. A guest write after the recording is not seen, and data a GPU pass wrote into such a buffer is not either. The first +use per pipeline key logs `x2w-draw compute input (...) comes from a GPU copy this list made|a snapshot of title +memory`, and the render totals line counts both paths. Off by default. To turn it on for a run, set `$env:X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT = "1"` in the PowerShell session before +starting `tools/startup/run.ps1`, which passes the session's environment on to the run. The snapshots have a pool of their own (128 MiB, chunks of 16 MiB, built like the shared upload ring: a chunk is reused once no recording can submit its bytes and every queue that used it has finished), so draw and texture uploads cannot starve them and a long run is not stopped by a full pool; a reservation it cannot serve logs `x2w-draw snapshot pool reservation refused: no unused capacity`. `startup_compute_dispatch_input` covers it with the `dispatch-input-snapshot` case and, for the recycling, `dispatch-input-snapshot-long` (48 frames of an 8 MiB snapshot, 384 MiB in all). + The source-built fixture reproduces a 68-byte request shape with source offset `0xbfffa0`. Its compute writer fills the source with contrasting colours. The consumer reads red from the second DWORD in the destination while the title-side green sentinel stays @@ -189,7 +361,10 @@ file names are never printed. The check is For each pixel shader the tool reads only the disassembly and records a contract: the vector registers read before any write (live-in), the I/J register pairs that feed attribute interpolation, and the live-in registers split into low and high 16-bit halves. Compare forms give -no half evidence. A first read is a live-in register unless a backward branch spans it and the +no half evidence. A read is a first read when the register is not written earlier in program +order or not written on every path to the read: at each join the definitions of the incoming edges +are intersected, so a write that a forward branch can skip does not hide a live-in read after the +join. A first read is a live-in register unless a backward branch spans it and the register is written later in program order: that value can be loop-carried, so the register is reported as ambiguous and takes no part in any rule, and evidence taken from such a read is dropped. Aliases made by `v_mov_b32` do not cross a branch or a branch target. A branch whose @@ -262,7 +437,7 @@ to check RGBA8 texel and alpha values, rebinding, and a mismatched 2D view on ha ## Offline vertex buffer stores -`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses version 2 manifests, so no store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. +`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses the `raw` uav line by name (it binds only pixel-stage `tex2d` stores), so no buffer store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. The descriptor modifications that compute buffer stores accept are accepted here too, with the same checks: the stride clear of DW1 and the structured-to-raw conversion (stride DW1[29:16] extracted, optionally clamped to at least 1, DW2 NUM_RECORDS scaled by it, DW3 OOB_SELECT set to 3, stride cleared), all four words from one descriptor load. The store and manifest are those of the unmodified descriptor. In the vertex stage, as in compute, a descriptor load through a pointer other than the untouched pair is tagged with the constant high word of a 32-bit table pointer, or otherwise with its own load, so the conversion cannot mix words of two loads. Any other modification stays refused. As for compute, matching out-of-range behavior would need a UAV view sized to the converted byte count; the runtime binds no vertex-stage UAV yet. @@ -393,6 +568,21 @@ ctest --preset dev --no-tests=error -R '^startup_vertex_fetch_formats_(controls| `BUF_FMT_16_16_SNORM` (format 24, DXGI `R16G16_SNORM` 37) sign-extends each half, divides by 32767 and clamps to -1.0, so -32768 and -32767 both give -1.0 (the Direct3D and Vulkan SNORM rule, as in LLVM 15 and Mesa `ac_formats`). The device run compares `round(v * 32767)` against the same byte decode, with a wrong reference that reads the halves unsigned and a mutated translation that does the same. The pattern the harness writes to t0 holds no 0x8000, so `startup_vertex_fetch_formats_controls` also evaluates the emitted expressions on 0x8000, 0x8001, 0x7fff, 0x0000, 0xffff and 0x4000 in each half, and four wrong forms (unsigned read, no clamp, divisor 32768, one half for both) must fail that check. The D3D12 draw has not been run on Linux. +`BUF_FMT_2_10_10_10_UNORM` (gfx10 format 50, DXGI `R10G10B10A2_UNORM` 24) reads one dword with x, y and z as 10-bit fields in bits 9:0, 19:10 and 29:20 and w as the 2-bit field in bits 31:30, each divided by its maximum (1023, 1023, 1023, 3). This is the 10-bit-x layout that Mesa maps R10G10B10A2 to; `BUF_FMT_10_10_10_2_UNORM` (format 44) has a 2-bit x and is not added here. It is checked on Linux by the Python evaluation `startup_gfx2hlsl_tbuffer_2101010`, which also covers the DXGI table entry; the D3D12 draws `startup_vertex_fetch_formats_warp` and `startup_vertex_fetch_formats_hardware` read it back (stride 6 / offset 2 and through the descriptor path). + + +In a graphics shader with only forward branches, a 32-bit root-table pointer +can be advanced by a literal byte offset and copied with `s_mov_b32`. At a +join the table and its offset must agree on every incoming path. A later +write to the source register leaves the copy intact. A path that changes the +copy to another address makes the subsequent descriptor load ambiguous. + +The `startup_joined_table_pointer` checks use two R8 textures with distinct +red values. The guest table stores their 32-byte records at offsets 0 and 32. +Each draw reads the table and exports the branch's root constant in green. +Swapping the textures reverses the red values. Changing the compiled +manifest's byte offset changes all 32 pixels and preserves the green values. + `buffer_load_format_x`, `_xy`, `_xyz` and `_xyzw` (MUBUF) use FORMAT (word 3 bits 12 to 18) and DST_SEL (bits 0 to 11) from the buffer descriptor. The draw snapshots the hardware table descriptor and provides word 3 as `udsrc descword3 `. It refuses missing hardware descriptor metadata, unsupported FORMAT codes and unresolved buffer ranges before submitting the draw. The shader decodes using the same expressions as the tbuffer path. Selectors 4 to 7 choose x, y, z and w, while selectors 0 and 1 choose constants 0 and 1. For a load after a branch, the vertex or pixel shader must load all four descriptor words in the same basic block as the use. The root table pointer must reach the load or its local pointer copy without any intervening write along the control-flow predecessors. It refuses rewritten descriptor words. `startup_vertex_fetch_formats_*` covers twelve formats, component swizzles, integer 1 and mutations that must differ on readback, plus three `buffer_load_format_xyzw` device cases (identity, a two-channel format whose z and w are the defaults 0 and 1, and the word (w, 1, 0, x)), each of which must also fail through the xyz translation of the same load. `startup_mubuf_descriptor_*` draws with the real binding path on WARP and hardware. Missing metadata, unsupported FORMAT and unresolved backing leave the target blue, while valid zero and one draw black and red. `BUF_FMT_8_8_8_8_UINT` (gfx10 format 60, DXGI `R8G8B8A8_UINT` 30) reads four unsigned bytes into X, Y, Z and W in increasing address order. With stride 5 and byte offset 3, the 16-vertex fixture visits all four dword alignments. On WARP, all 64 component words matched the byte reference. Swapping channels in the reference or normalizing the green byte in the generated shader each triggered a mismatch. @@ -400,7 +590,7 @@ ctest --preset dev --no-tests=error -R '^startup_vertex_fetch_formats_(controls| A typed buffer view that the title creates through the runtime (`CreateShaderResourceView`, `BUFFER`, no flags, no structure stride) leaves no hardware descriptor in the table. For this case the draw builds word 3 the way the console driver builds it from the view, using `view_word3()` in `src/startup_stubs/buffer_format_word3.h`: -- FORMAT is the code of the DXGI format whose typed read gives the same components. The 14 formats in the switch are covered: `R8_UNORM` 1, `R8_UINT` 5, `R8G8_UNORM` 14, `R32_FLOAT` 22, `R16G16_UNORM` 23, `R16G16_SNORM` 24, `R16G16_UINT` 27, `R16G16_FLOAT` 29, `R8G8B8A8_UNORM` 56, `R8G8B8A8_UINT` 60, `R32G32_FLOAT` 64, `R16G16B16A16_FLOAT` 71, `R32G32B32_FLOAT` 74 and `R32G32B32A32_FLOAT` 77. The codes are the LLVM 15 `llvm-mc -mcpu=gfx1013` encodings of the tbuffer `format:` operand. +- FORMAT is the code of the DXGI format whose typed read gives the same components. The 15 formats in the switch are covered: `R8_UNORM` 1, `R8_UINT` 5, `R8G8_UNORM` 14, `R32_FLOAT` 22, `R16G16_UNORM` 23, `R16G16_SNORM` 24, `R16G16_UINT` 27, `R16G16_FLOAT` 29, `R10G10B10A2_UNORM` 50, `R8G8B8A8_UNORM` 56, `R8G8B8A8_UINT` 60, `R32G32_FLOAT` 64, `R16G16B16A16_FLOAT` 71, `R32G32B32_FLOAT` 74 and `R32G32B32A32_FLOAT` 77. The codes are the LLVM 15 `llvm-mc -mcpu=gfx1013` encodings of the tbuffer `format:` operand. - DST_SEL comes from `Shader4ComponentMapping`: a channel becomes 4 to 7, a forced 0 becomes 0 and a forced 1 becomes 1. The draw is refused, not read as zeros, whenever a translated formatted load has no resolved word 3: @@ -475,6 +665,8 @@ python3 -B tests/startup_buffer_address_check.py controls ## Startup translator: SMEM combined register and immediate offsets +Direct C++ compute, in wave32 and wave64, accepts numeric `vcc_lo` and `vcc_hi` as SMEM offsets and scalar load destinations through s107. + In RDNA 2 SMEM instructions (`s_load_dword*` and `s_buffer_load_dword*`), a scalar register `SOFFSET` (`s0`..`s105` or `m0`) and a non-zero 21-bit signed immediate `OFFSET` (`w1[20:0]`) can be active at the same time: [`tools/disasm_rdna2.py`](../tools/disasm_rdna2.py) prints the register in `ops[2]` and the signed immediate in `mods` (`offset:0x...` or `offset:-0x...`). Previously, `Stage.op_s_buffer_load_dword()` and `Stage.op_s_load_dwordx4()` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) ignored `mods`, silently dropping `offset:0x...` on register-addressed buffer and dynamic sampler-heap loads, accepting unknown modifiers, reading negative 21-bit signed encodings (`0x100000`..`0x1fffff`) as `+1`..`2` MiB, and overwriting a runtime SGPR `soffset` mid-load when a multi-dword `s_buffer_load_dwordx*` wrote into that register first. `gfx2hlsl.py` now parses and validates SMEM modifiers (`glc`, `dlc` and at most one non-negative 21-bit signed `offset:` up to `0xfffff`), adds the immediate byte offset to register-addressed `s_buffer_load_dword*` and opt-in sampler-heap `s_load_dwordx4` loads, saves an overlapping runtime SGPR `soffset` into `a` before writing destination registers, and validates non-SGPR/`m0` `soffset` operands (`vcc_lo`, `exec_lo`, `ttmp*`, VGPRs, register ranges, or descriptor-holding SGPRs) across `s_buffer_load_dword*` and both sampler-heap modes of `s_load_dwordx4`. Negative 21-bit signed immediates (`0x100000`..`0x1fffff` or negative literals) — which hardware `s_load_*` sign-extends — remain an unlowered translator gap and are refused by name rather than silently reading at `+1`..`2` MiB. @@ -558,6 +750,12 @@ Build outputs and downloaded tool sources live under `out/`. [Microsoft xbdepend ## Recovering a failed startup command-list recording +The `startup_list_resubmit` fixture also records a translated sampler snapshot and +submits its list to two queues. The second queue waits on a CPU-released fence. +Releasing the list and resetting the allocator keeps the snapshot alive while the +second submission is blocked. Once both tracked queues complete, reusing the first +allocator releases the snapshot. The untracked-submit case keeps it retained. + The source-built `startup_list_resubmit` fixture keeps a valid compute submission behind a queue wait, then calls `RSSetViewports` on a second recording of the same list. Desktop `Close` fails and the shim drops that recording. A `Reset` with a direct allocator must @@ -619,6 +817,12 @@ requires no title files or allocations. External providers with process-lifetime workers can use `--pin-shim DLL` alongside `--shim DLL PATH`. This pins the provider immediately before the first guest image loads, and only in execution mode. Run packages in a child process when using pinned providers. The guest must still join its own workers and quiesce any host calls into guest code before returning. `cpu_package_shim_lifetime` verifies that the selected provider remains loaded after the entry returns and the ordinary provider unloads. +An external provider that is not a loadable image (empty, truncated or not a PE) fails its load quietly, and its symbols are reported as missing. The runner sets `SEM_FAILCRITICALERRORS` on the calling thread for each provider `LoadLibraryExW` and restores the thread's previous mode afterwards, so the guest runs with the host's setting. Without the flag, Windows showed a modal "Bad Image" dialog (status `0xc0000020` for an empty file) in an interactive session, and the load blocked until the dialog was closed. `pe_run_package_cli_check` records the thread error mode at each provider load and checks that it is restored after the run. Loading the mapper DLL in execution mode is unchanged. + +```powershell +ctest --preset dev --no-tests=error -R '^pe_run_package_cli_check$' -V +``` + `--trap-callable DLL!SYMBOL` (or `DLL!#ORDINAL`, repeatable) is a diagnostic execution mode for finding the last startup stage a package reaches. By default the runner refuses any unresolved external before mapping. An import table entry names a symbol, but it does not say whether the caller calls it or reads it as data, so this mode binds only the unresolved externals the caller lists as callable. Each listed name gets a numbered trap, and the traps are listed on stderr in sorted `dll!symbol` order. Any unlisted unresolved external is still refused before mapping, and so is a listed name that is not an unresolved external. A trap never returns: it prints `trap N: : !` and terminates the process with `0xE7A00000 | N`. The report is best effort, and termination does not depend on it. No DLL is written or loaded under the missing name, and a trap is not a provider. If the entry returns without reaching a trap, the JSON result adds `unhit_traps`. The option cannot be combined with `--preflight-only`, and `plan(report, allow_external=False)` still refuses the same package. `pe_run_package_trap_missing` checks this with two source-built EXEs that import from a module nothing provides: two functions in one, plus a data import in the other. @@ -1830,12 +2034,16 @@ Run `ctest --preset dev --no-tests=error -R '^cpu_aot_xchg$' -V`. `cpu_hint_nop_fixture` compares native execution against the lowered body for the same bytes. One generator (`tests/cpu/hint_nop_fixture.py`) assembles the exact byte sequences and lowers the same instructions, so the two arms cannot drift apart. A prologue sets RAX from the input and the arithmetic flags from an `ADD`; each case then executes the encoding under test and stores the flags in AH with `LAHF`, so a changed register or flag shows up as a different return value. The memory forms are handed a pointer to a `PAGE_NOACCESS` page as the base register, and both the native and the lifted call run under the same exception guard, so a lowering that evaluated the operand is reported as a mismatch rather than crashing the fixture. Two controls make that meaningful: a real load from the same page must fault, and a real `mov eax, imm` with the same inputs must return a different value. Run `ctest --preset dev --no-tests=error -R '^cpu_hint_nop_fixture$' -V`. +**Non-temporal stores.** The shared lowering accepts the legacy SSE stores `MOVNTPS` (`0F 2B /r`), `MOVNTPD` (`66 0F 2B /r`) and `MOVNTDQ` (`66 0F E7 /r`) from XMM0 to XMM2, the registers it models for `MOVAPS`, and `MOVNTI` (`0F C3 /r`) from a 32- or 64-bit register. Each lowers to the streaming-store intrinsic of its width (`_mm_stream_si128`, `_mm_stream_si32`, `_mm_stream_si64`), so the non-temporal hint and the weak ordering stay the guest's: only the guest's own `SFENCE`, `MFENCE` or a locked instruction orders them. No flag changes. The XMM forms test the target against 15 first and raise the aligned-operand fault, as `MOVAPS` does, before anything is written; `MOVNTI` has no alignment requirement. The MMX `MOVNTQ`, the SSE4a scalar `MOVNTSS` and `MOVNTSD`, the VEX `VMOVNTPS`, `VMOVNTPD` and `VMOVNTDQ`, the `MOVNTDQA` load and XMM3 and above stay refused. `cpu_nt_store` (`tests/cpu/nt_store_check.py`) pins eight accepted encodings to their intrinsic and alignment test and eight neighbours to a refusal. `cpu_nt_store_fixture` (`tests/cpu/nt_store_fixture.py`) generates the native bytes and the lowered C++ from one list and runs both into separate sentinel-filled buffers: stores at aligned and displaced targets and `MOVNTI` at odd addresses must match native and an independent reference byte for byte; misaligned XMM targets must raise the access violation at address -1 natively and translated with nothing written; and a `PAGE_NOACCESS` target must raise the same write fault at the same address. Three controls must break a rule: `noalign` removes the alignment test and stores with `memcpy` (the streaming intrinsic is itself `MOVNTDQ` and would fault anyway), so it must store where native faults; `nostore` replaces the native store with a NOP and must miss the reference; and a native `MOVUPS` to the misaligned target must not fault, so the fault comes from the alignment rule. Run `ctest --preset dev --no-tests=error -R '^cpu_nt_store(_fixture)?$' -V`; the `release` preset runs the same checks. + A 67h address-size prefix selects 32-bit addressing. The lowering wraps base + index × scale + displacement at 32 bits and zero-extends the result, ignoring the upper halves of the registers as the hardware does. In this mode iced reports a displacement of -8 as `0xfffffff8`, so the wrap is also needed when the upper halves are zero. EIP-relative operands are rejected because the hardware adds the low 32 bits of the runtime RIP, which an RVA binding cannot represent. `cpu_aot_address_size` builds `lea`, load and store forms such as `lea rax, [ecx+edx*8-8]` and `mov [ecx+edx], r8d` from MASM source. It translates them and compares both images with a 32-bit reference over wrapped sums and upper-half noise. The loads and stores use a page committed below 4 GiB, and each store must leave the rest of the page unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_address_size$' -V`. XLATB replaces AL with the byte at RBX + AL. AL is zero-extended, and bits 8 to 63 of RAX and the flags are unchanged. With a 67h prefix the base is EBX and the sum wraps at 32 bits, so the upper half of RBX is ignored. A REX.W prefix (`48 d7`) does not change the operation. `cpu_aot_xlatb` builds four exports from [MASM source](../tests/cpu/xlatb.asm): the plain, REX.W and 67h forms, and two lookups in a row. Each export runs on a 256-byte permutation table in a page committed below 4 GiB. The check compares RAX and ZF/CF for every AL value, with noise in the upper bits of RAX and, for the 67h form, in the upper half of RBX, against the native DLL and an independent reference. Three controls mutate the generated C++ and must mismatch: `signed` sign-extends AL, `noaddr32` keeps the upper half of RBX in the 67h sum (whose reads fault), and `clear` writes the loaded byte over all of RAX. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_xlatb$' -V`. RDTSC and RDTSCP use an explicit host TSC profile: they supply host ticks and, for RDTSCP, the host IA32_TSC_AUX, with no guarantee of a guest TSC frequency or of a virtual-CPU number. The counter passes through unscaled: EAX holds the low 32 bits and EDX the high 32 bits, with the upper halves of RAX and RDX zeroed and the flags unchanged. RDTSCP also writes TSC_AUX to ECX, zero-extending RCX. The lowering calls `__rdtsc()` and `__rdtscp()`, so each keeps its own instruction, with no fence added to the generated code. It stores the result in a `volatile` local, so a read stays in the code even when the guest overwrites its result; without it, MSVC `/O2` removes such an RDTSC. Because the counter changes between reads, the checks test properties rather than bytes. The [RDTSC source](../tests/cpu/rdtsc.asm) has one RDTSC and two RDTSC in a row, and the [RDTSCP source](../tests/cpu/rdtscp.asm) one RDTSCP, each after `add r8, r8` sets ZF and CF from one of four presets; each file also has one read without a preset whose result is overwritten with 7. The single reads first fill RAX and RDX, and RDTSCP also RCX, with all ones. A [native harness](../tests/cpu/rdtsc_harness.asm), never translated, supplies CPUID and the measurement reads. The checks pin the thread to one logical processor and confirm that it runs there before reading. For the single RDTSC and the RDTSCP they require that the translated read lies between two native reads, each serialized by LFENCE before and after. For every read with a preset they require that the upper halves of the results are zero and that ZF and CF keep their preset. The second of two RDTSC must not be earlier than the first and must differ from it in at least one of the 2,000 rounds. RDTSCP must return the TSC_AUX of the pinned processor, which the RDTSCP check chooses as the highest of the affinity mask with a nonzero TSC_AUX. The exports with overwritten results must return 7. Controls mutate the generated C++ and must break a property: `constant` returns a zero RDTSC counter, `swap` exchanges the halves, `noext` leaves the whole counter in RAX, `noaux` drops TSC_AUX, `stale` keeps the value of each RDTSC's first call, and `flags` and `pflags` flip ZF and CF after RDTSC and RDTSCP. The translation is also built with `cl /O2`. A walk that follows every branch from each export must find every RDTSC and RDTSCP of the source, including the overwritten ones, and the `/O2` build must keep the properties above. The `plain` control removes `volatile` and is built only at `/O2`; there the walk must find the overwritten RDTSC missing. `cpu_aot_rdtsc` checks RDTSC with `constant`, `swap`, `noext`, `stale`, `flags` and both `/O2` builds, and runs on every host. `cpu_aot_rdtscp` checks RDTSCP with `swap`, `noext`, `noaux`, `pflags` and the translated `/O2` build. Each source counts toward coverage only through its own test. `cpu_aot_rdtscp` exits 77 on a host without RDTSCP (CPUID 80000000h reports no leaf 80000001h, or its EDX bit 27 is clear). It also exits 77, after its other checks, on a host whose TSC_AUX is 0 on every processor of the affinity mask, where `noaux` cannot fail. Guest code that converts ticks with its own frequency will see host time; whether a guest-frequency profile belongs in the runtime is open in [#739](https://github.com/R0Y00/Xbox2Windows/issues/739). Run `ctest --preset dev --no-tests=error -R '^cpu_aot_rdtscp?$' -V`. +`cpu_aot_amd_monitor_rdpru` ([lifter](../tools/cpu_amd_monitor_rdpru_aot.py), [fixture](../tests/cpu/amd_monitor_rdpru_aot.asm), [check](../tests/cpu/amd_monitor_rdpru_aot_check.py)) lifts bounded Windows x64 leaf functions using AMD Zen 2 user-mode `monitorx`, `mwaitx`, and `rdpru` alongside bounded volatile GPR arithmetic/flags (`add`/`cmp` 32/64-bit, `xor`, `or`, `shl`, `setcc`, `lea`, `[r8 + disp]` stores). Under the lifter's bounded approximations, `rdpru` statically validates `ECX` (`0` = MPERF, `1` = APERF) and **maps both selectors to a serialized host `RDTSC` read** (verifying monotonic progression, `EAX->RAX` / `EDX->RDX` zero-extension, `RCX`/`RFLAGS` preservation, and `/O2` anti-CSE/anti-DCE barriers rather than distinct hardware MPERF/APERF counter values), `mwaitx` lowers to a **fenced `_mm_pause()`** (an allowed early wake-up preserving GPRs, `RFLAGS`, and surrounding store order, with timer extension `ECX[1]` rejected), and `monitorx` probes flat `[rcx|rdx|r8]` readability preserving `#PF` fault ordering. On `13th Gen Intel(R) Core(TM) i7-13620H` (`dev` and `release`), 6 sequences were accepted, 41 rejection controls, `/O2` `RDTSC`/`PAUSE` barrier walks, 579 lifted Debug checks, 579 `/O2` checks (including 32-bit `add`/`cmp` flag paths and NULL fault ordering), 6 altered-build controls, and 6 compiled C++ mutant controls (including an `op_cmp32` CF comparison flip) passed before exiting 77 (capability skip: host lacks `CPUID Fn8000_0001:ECX[29]` MWAITX and `Fn8000_0008:EBX[4]` RDPRU). Run `ctest --preset release --no-tests=error -j 1 -R '^cpu_aot_amd_monitor_rdpru$' -V`. + RDRAND and RDSEED are lowered only in an opt-in host-entropy profile, `lower(..., host_entropy=True)`; the default profile still rejects both. Their precondition is the host CPUID bit: CPUID.01H:ECX bit 30 for RDRAND and CPUID.(EAX=07H,ECX=0):EBX bit 18 for RDSEED. Each guest execution runs the host instruction once through `_rdrand16_step` to `_rdseed64_step`, with no retry and no fence; CF is the intrinsic's result, so guest code keeps control of retrying. On CF=0 the destination gets zero at its width. A 16-bit destination keeps bits 16 to 63, and a 32-bit one clears the upper half. The lowering clears ZF and OF, and PF only in a checked x87 function whose body reads it (JP, JNP, FCMOVU or FCMOVNU). SF and AF are not modelled by the shared lowering, so the translation cannot show the hardware's clearing of them. The result is a `volatile` local, so a read stays in the code when the guest discards it; without it, MSVC `/O2` removes such a read. `cpu_aot_rdrand` ([source](../tests/cpu/rdrand.asm)) and `cpu_aot_rdseed` ([source](../tests/cpu/rdseed.asm)) each exit 77 when the host lacks their own instruction. A [native harness](../tests/cpu/rdrand_harness.asm), never translated, supplies CPUID and confirms on the host that OF, SF, ZF, AF and PF are 0 after the 64-bit instruction, from two `add` presets that set them first. Each check confirms that the default profile rejects every read, then runs 2,000 rounds of the 16-, 32- and 64-bit reads, natively and translated, after `add r8, r8` sets ZF, CF and OF from four presets. Every read must be a success (CF 1) or a failure (CF 0, zero at the width) with ZF and OF clear and the width rules above. Natural failures are counted and printed, never required. Two deterministic variants replace the host read and must pass on every host: `succeed` reports CF 1 with a fixed pattern, and `fail` reports CF 0 after storing that pattern, so the zero and carry rules are checked even when the host never fails. The reads whose result is discarded must return the overwritten value. Controls mutate the generated C++ and must break a rule: `constant` succeeds with a fixed value, `nocarry` drops CF, `noext` keeps the upper half of a 32-bit destination, `wide16` replaces a 16-bit destination's upper bits, `flags` leaves ZF and OF as preset, and `nozero` keeps the pattern after a failed read. The translation is also built with `cl /O2`. A walk that follows every branch must find each RDRAND or RDSEED of the source, including the discarded one, and the `/O2` build must keep the rules. The `plain` control removes `volatile` and is built only at `/O2`; there the walk must find the discarded read missing. Variation checks require at least two different successful values at each width and one 64-bit success with a nonzero upper half. They catch a constant translation and do not assess entropy quality. A host with fewer than two natural successes at a width still runs every deterministic check, then exits 77 with the variation named as not measurable. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_rd(rand|seed)$' -V`. The shared lowering models PF for its readers JP, JNP, SETP, SETNP, CMOVP and CMOVNP outside the x87 profile when every path from the entry reaches the reader through an instruction whose lowering assigns PF: VCOMISS, VUCOMISS, VCOMISD and VUCOMISD (PF = unordered), PTEST, VPTEST, VTESTPS, VTESTPD and the PCMPxSTRx string compares (which clear it), or a register ADD, SUB or CMP that a LAHF reads. A call, a host binding, an instruction that leaves PF undefined, any other PF writer, or a join where the paths disagree makes PF unknown, and the reader is refused (`check_parity`); so is a reader that no path from the entry reaches. Inside the x87 profile, `x87_lower.check_flags` keeps deciding, and it now also counts the four VEX compares as PF producers. CMOVP and CMOVNP read a memory source whatever PF says and zero-extend a 32-bit destination either way, like the other CMOVcc. Functions without a PF reader keep their generated code. `cpu_aot_parity` ([source](../tests/cpu/parity.asm)) follows each VEX compare, and FUCOMIP in the x87 profile, with SETNP, SETP, SETE, SETB, CMOVP from a register, CMOVNP from memory and JP, for twelve operand pairs written at run time: ordered, equal, signed zeros, infinities, and quiet and signaling NaNs in either operand. It runs under MXCSR 0x1F80, with every exception masked, which the native harness sets and restores; floating-point exception behavior is outside this fixture. Native and translated results must match the flags the compares define (unordered sets ZF, PF and CF). Under masked exceptions VCOMISS and VUCOMISS set the same flags, so the fixture does not tell them apart. FLD quiets a signaling NaN under the default x87 control word, so FUCOMIP compares it as a quiet NaN. The float-equality idiom `setnp; sete; and` must hold, SETP after a LAHF-read ADD must match the parity of the sum's low byte, and a CMOVNP or CMOVP source on an inaccessible page must fault for ordered and unordered pairs. Three exports must be refused: PF after ADD, PF known on one incoming path only, and CMOVP after IMUL leaves PF undefined; so must a PF reader after a host-bound compare and an unreached reader. Two controls must break a rule: `stale` drops the compare's PF assignment, and `reversed` swaps every PF condition. The translation is also built with `cl /O2`. The native comparison needs AVX; without it the translated results are still checked against the fixed flags. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_parity$' -V`; the `release` preset runs the same check. @@ -1912,6 +2120,8 @@ The shared lowering also handles signed relational and flag-conditional forms ac The shared lowering also handles 32-bit and 64-bit ADX forms (`adcx`, `adox`) and `seto`, tracking `OF` independently from `CF` so interleaved `adcx`/`adox` chains preserve each other's carry flag. `cpu_aot_adx` probes CPUID leaf 7 EBX bit 19 (`ADX`) before invoking the native fixture and exits 77 (capability skip) on unsupported hosts; on ADX-capable hosts it builds all five exports from MASM source (`tests/cpu/adx.asm`), translates them, and compares sums and `(CF << 1) | OF` against the native DLL and a reference model. Run `cmake --build --preset dev --target cpu_adx_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_adx$' -V`. +`cpu_aot_adx_dedicated` ([lifter](../tools/cpu_adx_aot.py), [fixture](../tests/cpu/adx_aot.asm), [check](../tests/cpu/adx_aot_check.py)) provides a standalone bounded leaf lifter for 32-bit and 64-bit `adcx` and `adox` (register and flat `[rcx|rdx|r8]` memory operands) with `ALTER_ADX` build divergence controls, 14 oracle-quirk controls, `/O2` discarded-read NULL fault verification (`load_always<>`), 32-bit zero-extension pinning via `mov rax, rcx` (`op_adcx32_c0`, `op_adox32_o0`, `op_adcx32_flags`, `op_adox32_flags`), and 54+ rejection/CLI controls (3 alt + 35 IR + 4 raw + 12 PE-patched + CLI). Portable lifted, `/O2`, mutant, and rejection checks run unconditionally; native differential checks probe `CPUID.07H.00H:EBX[19]` (`ADX`) and exit 77 on hosts without ADX. Run `cmake --build --preset dev --target cpu_adx_aot_original cpu_adx_aot_original_lifted cpu_adx_aot_altered cpu_adx_aot_altered_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_adx_dedicated$' -V`. + The shared lowering also handles 128-bit and 256-bit AVX2 integer broadcasts (`vpbroadcastb`, `vpbroadcastw`, `vpbroadcastd`, `vpbroadcastq`) and variable per-lane shifts (`vpsllvd`, `vpsrlvd`, `vpsravd`, `vpsllvq`, `vpsrlvq`), zeroing upper 128 bits on 128-bit VEX destinations and clamping out-of-range shift counts to match hardware. `cpu_aot_avx2_shifts` probes CPUID (`OSXSAVE`, `XCR0` YMM state, and leaf 7 EBX bit 5 `AVX2`) before invoking the native fixture and exits 77 (capability skip) on unsupported hosts; on AVX2-capable hosts it builds all 44 exports from MASM source (`tests/cpu/avx2_shifts.asm`), translates them, and compares outputs against the native DLL and a reference model across 128-bit and 256-bit register/memory operands, register-aliasing forms (`dst == src1`, `dst == src2`, `dst == src1 == src2`), and boundary shift counts while checking deterministic rejections for untracked registers, EVEX encodings, segment prefixes, and EIP-relative operands. Run `cmake --build --preset dev --target cpu_avx2_shifts_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_avx2_shifts$' -V`. The shared lowering also handles AVX2 128-bit lane operations, dword blends, and cross-lane permutes (`vbroadcasti128`, `vextracti128`, `vinserti128`, `vpblendd`, `vperm2i128`, `vpermd`, `vpermps`, `vpermq`, `vpermpd`). `cpu_aot_avx2_permutes` probes CPUID (`OSXSAVE`, `XCR0` YMM state, and leaf 7 EBX bit 5 `AVX2`) before invoking the native fixture and exits 77 (capability skip) on unsupported hosts; on AVX2-capable hosts it builds all 17 exports from MASM source (`tests/cpu/avx2_permutes.asm`), translates them, and compares outputs against the native DLL and a reference model. The `vpblendd` memory tests check that native and translated code both fault before writing output when either only masked-off lanes cross into an inaccessible page or all lanes are masked off and the whole operand is inaccessible. Run `cmake --build --preset dev --target cpu_avx2_permutes_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_avx2_permutes$' -V`. @@ -3852,7 +4062,13 @@ out-of-range cases. A separate mesh program with one changed compare operand adds two controls. Windows WARP with the D3D12 debug layer enabled matched all 1,024 pixels for each of the eight cases. Physical hardware and startup pipeline integration remain open in [#1760](https://github.com/R0Y00/Xbox2Windows/issues/1760). -[Windows verification](https://github.com/avt0m4t48/Xbox2Windows/actions/runs/45485172952) + +The bounded mesh lowerers reuse the concrete scalar bit tests described below. +They also accept a 32-bit test of a constant-buffer word immediately followed +by an SCC branch that forms a verified descriptor join. Both branch polarities +and constant-buffer bit indices have readback controls. Descriptor words, +unwritten operands and 64-bit dynamic predicates remain refused. +Reproduce with `mesh_bitcmp_cpu` and `mesh_bitcmp_draw_{warp,hardware}`. ### Sampler heap samplers in bounded runtime mesh @@ -4366,6 +4582,36 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mtbuf_load_(warp|hardware)$' -V ``` +### Pixel-stage sparse image stores + +A pixel-stage 2D `image_store` with a partial DMASK writes only the selected +components. `dmask:0x5` lowers to `w0[uint2(v0, v1)].xz = float2(...)`. The +store does not read the texel, so two invocations can update disjoint channels +of one texel without writing the other invocation's stale channels back. A +float4 read-modify-write is not used. Compute stores, D16 stores and array +stores still require `dmask:0xf`. A full-mask pixel 2D-array store stays a +float4 assignment, `w0[uint3(x, y, layer)] = asfloat(uint4(...))`, with a +`tex2da` manifest line. + +The source-built fixture draws two pixels in one pass. Both address texel +(1, 2). One invocation stores x (`dmask:0x1`, 1.0) and the other stores z +(`dmask:0x4`, 2.0). The image starts at -1 in every channel, so the texel +must read back (1, -1, 2, -1) and every other texel must stay -1. Writing the +second value into y instead of z must mismatch. A manifest line that ends in +`typedload` is refused before the draw when the format has no typed UAV load. +The component store does not ask for that load. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_pixel_image_store' -V +``` + +```bash +python3 -B tests/startup_pixel_image_store_check.py +python3 -B tests/startup_pixel_image_store_check.py binary llvm-mc-15 +``` + +Refs #2618. + ### gfx1013 2D float image stores and mip loads The fixed compute profile accepts a 2D `R32G32B32A32_FLOAT` `image_store` @@ -4538,19 +4784,21 @@ python3 -B tests/compute_mimg_float_store_d16_check.py --binary llvm-mc-15 llvm- ### gfx1013 2D image atomics -The gfx1013 profile accepts `image_atomic_add`, `image_atomic_umax` and -`image_atomic_cmpswap` on a 2D `R32_UINT` UAV at mip 0 and lowers them with -the gfx1030 image atomic lowering described below. The emitted HLSL is -identical for both targets. The atomics return nothing: `glc` and the other -cache, `a16`, `d16`, `tfe`, `lwe` and `r128` flags stay refused, as on gfx1030. -On gfx1013 every other image atomic (`sub`, `and`, `or`, `xor`, `umin`, +The gfx1013 profile accepts `image_atomic_add`, `image_atomic_umin`, +`image_atomic_umax` and `image_atomic_cmpswap` on a 2D `R32_UINT` UAV at mip 0 +and lowers them with the gfx1030 image atomic lowering described below. The +emitted HLSL is identical for both targets. The atomics return nothing: `glc` +and the other cache, `a16`, `d16`, `tfe`, `lwe` and `r128` flags stay refused, as +on gfx1030. On gfx1013 every other image atomic (`sub`, `and`, `or`, `xor`, `swap`, `inc`, `dec`) is refused by name. So are the signed and float formats, a nonzero UAV mip, array and 3D dimensions, a second atomic and a store to the -same image. +same image. `umin` stays unsigned (`InterlockedMin` without `asint`); the +minmax operand `0x80000011` makes unsigned ordering differ from signed `smin` +on the CPU reference (M200-01 A). The fixtures are the gfx1030 cases with the gfx1013 profile. One add writes unique texels, a contended add sends two lanes to each texel of one row, and a -`umax` and a `cmpswap` each write unique texels. Each runs with one and two +`umin`, a `umax` and a `cmpswap` each write unique texels. Each runs with one and two groups, and the readback compares all 336 words of a three-mip texture with a CPU reference, including the untouched texels and mips. For each case and group count, one mutant must mismatch at the first word its reference @@ -4611,6 +4859,11 @@ LLVM and LLD 15 build the code object and verify one instruction of each kind in its disassembly. The CPU witnesses and mutations pass independently. Native readback remains pending, including the raw miss and disabled-slot words. The probe leaves translator behavior and form coverage unchanged. +The node model and its witness set are described in +[bvh-node-model.md](experiments/bvh-node-model.md). +The translator slices that consume the model are the +[FP32 and binary16 box nodes](experiments/startup-gfx2hlsl-bvh-box32.md) and the +[triangle nodes](experiments/startup-gfx2hlsl-bvh-triangle.md). ### gfx1013 2D explicit-LOD image gathers @@ -4838,6 +5091,86 @@ ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_mimg_msaa_(warp| python3 -B tests/compute_mimg_msaa_check.py --binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` +### Experimental gfx1030 2D per-instruction minimum LOD + +The ordinary pixel path accepts the following full-width, non-comparison +`dmask:0xf` Texture2D forms with sequential VGPRs. The output is four VGPRs, +and the existing `vmcnt(0)` rule applies. Coordinates must retain whole-quad +provenance. The offset is a known canonical packed XY DWORD, with signed +six-bit fields at bits 5:0 and 13:8, limited to the DXIL range `[-8, 7]`. + +| Instruction | gfx1030 opcode | Active address DWORDs | Desktop HLSL | +| --- | --- | --- | --- | +| `image_sample_cl` | `0x21` | `u, v, clamp` | `Sample(s, uv, int2(0, 0), clamp)` | +| `image_sample_cl_o` | `0x31` | `offset, u, v, clamp` | `Sample(s, uv, offset, clamp)` | +| `image_sample_b_cl` | `0x26` | `bias, u, v, clamp` | `SampleBias(s, uv, bias, int2(0, 0), clamp)` | +| `image_sample_b_cl_o` | `0x36` | `offset, bias, u, v, clamp` | `SampleBias(s, uv, bias, offset, clamp)` | + +`--cpu gfx1030 --sample-clamp-mips N` opts into this experiment. The caller +must bind matching float 2D views of 1 to 16 visible mips and a normalized +clamp-to-edge sampler with point XY and mip filters, zero sampler bias and +minimum LOD, and maximum LOD at or above the last view mip. The instruction +clamp must be a known finite float in `[0, N-1]`. The instruction bias, when +present, must be a known float in the HLSL range `[-16, 15.99]`. The draw +cases use integral LODs and avoid point mip ties. Fractional and near-tie +native rounding remain unmeasured. Comparison, explicit gradient, gather, +NSA, `a16`, `d16`, runtime LOD operands and other sampler profiles are outside +this experiment. + +**Source discrepancy.** The [AMD RDNA 2 reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture), +Table 44, says `_CL` clamps computed LOD “to be no larger than this value.” +Table 43 and section 8.2.5 describe the address order. LLVM 15.0.7's +[AMDGPU intrinsic definitions](https://github.com/llvm/llvm-project/blob/llvmorg-15.0.7/llvm/include/llvm/IR/IntrinsicsAMDGPU.td) +append the operand named `clamp` after the coordinates, and its +[MIMG instruction table](https://github.com/llvm/llvm-project/blob/llvmorg-15.0.7/llvm/lib/Target/AMDGPU/MIMGInstructions.td) +assigns the four opcodes above. Those LLVM definitions establish the operand +order and encoding. In Mesa 25.1.0, the +[SPIR-V reader](https://github.com/chaotic-cx/mesa-mirror/blob/mesa-25.1.0/src/compiler/spirv/spirv_to_nir.c) +maps `MinLod` to `nir_tex_src_min_lod`. The +[ACO selector](https://github.com/chaotic-cx/mesa-mirror/blob/mesa-25.1.0/src/amd/compiler/aco_instruction_selection.cpp) +selects the four `_cl` forms, and the +[Mesa AMD LLVM builder](https://github.com/chaotic-cx/mesa-mirror/blob/mesa-25.1.0/src/amd/llvm/ac_llvm_build.c) +appends `min_lod` to the `.cl` intrinsics. The +[Vulkan scale-factor rules](https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#textures-level-of-detail-operation) +and [Direct3D per-sample MinLOD rules](https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#5.9.4.5.4%20Per-sample%20MinLOD%20Clamp) +define a lower bound on the biased LOD. The desktop experiment follows the +compiler mapping and uses the native DXIL `Sample` and `SampleBias` clamp +operands. AMD's pinned LLPC independently maps SPIR-V `MinLod` to the same +AMDGPU intrinsics. [AMD LLPC SPIR-V reader](https://github.com/GPUOpen-Drivers/llpc/blob/40cb8d95ad8d6f7f1652e3fd47d39667594cce08/llpc/translator/lib/SPIRV/SPIRVReader.cpp#L7814) · +[AMD LLPC image builder](https://github.com/GPUOpen-Drivers/llpc/blob/40cb8d95ad8d6f7f1652e3fd47d39667594cce08/lgc/builder/ImageBuilder.cpp) + +The fixture checks four LLVM intrinsic-to-ISA argument orders with distinct +literal words and four source assembly-to-container CLI round trips. The +CPU model selects `max(implicit LOD + bias, clamp)` before point mip selection +and predicts all 64 RGBA pixels from three spatially distinct mips. The +translated shader and independent desktop `SampleLevel` oracle use the same +texture, sampler and CPU reference. Controls drop the clamp, force the clamp +as the LOD, drop the bias, apply it after the clamp, or remove the offset. +For example, dropping the `_cl` clamp first changes pixel `(0,0)` red from +`0.5` to `0.25` in the CPU model. The offline DXC check verifies the clamp, +bias and nonzero offset operands in the emitted DXIL. + +```bash +python3 -B tests/pixel_sample_clamp_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 llc-15 +``` + +```powershell +ctest --preset dev --no-tests=error -R '^pixel_aot_sample_clamp_(controls|compile)$' -V +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_sample_clamp_(warp|hardware)$' -V +``` + +**Native publication gate.** Before publishing opcode support or recording +form coverage, capture the rendered mip identifiers from a source-built +native gfx1030 pixel shader for all four opcodes. Use the same sampler and +spatial mips, confirm the native instruction in the submitted shader's +disassembly, and record device target, driver, shader hash and full readback. +Use cases where the computed LOD is below and above the operand, plus the +negative bias case that distinguishes bias-before-clamp from the opposite +order. Desktop DXIL readback tests the Direct3D implementation. The test +registration omits form coverage records while the native direction remains +unresolved. + ### gfx1030 2D image gathers The pixel AOT tool accepts `image_gather4`, `image_gather4_o`, @@ -5472,6 +5805,110 @@ because their per-lane regions can overlap. The fixtures compare every UAV word and detect a wrong qword offset, a missing data word, or reversed dual read offsets at word 0. +### Group-shared LDS on gfx1013 + +`--cpu gfx1013 --lds-bytes N` declares a group LDS allocation of N bytes (a multiple of 4, at most the +32 KiB D3D12 groupshared limit) and lowers LDS as `groupshared uint lds[N / 4]`, shared by every thread of +the group ([#1541](https://github.com/R0Y00/Xbox2Windows/issues/1541)). gfx1013 has no private LDS +profile, so the allocation alone selects this mode; without it, DS instructions and `s_barrier` are +refused as before. `v_lshlrev_b32 vD, k, vL` on a local-ID VGPR gives an address word +`local << k`, and the existing integer ALU subset combines address words. Each DS instruction reads its +byte address from a VGPR, adds the instruction offset (`offset0`/`offset1` in elements of the access +size, times 64 for the `st64` forms), and accesses word `(address >> 2) + i`. The accepted forms are: + +- `ds_write_b32`, `ds_read_b32`, `ds_write_b64`, `ds_read_b64`, `ds_write_b128` and `ds_read_b128`; +- `ds_write2_b32`, `ds_read2_b32`, `ds_write2st64_b32`, `ds_read2st64_b32`, `ds_write2_b64`, + `ds_read2_b64`, `ds_write2st64_b64` and `ds_read2st64_b64`, with two different offsets; +- the non-returning `ds_add_u32`, `ds_sub_u32`, `ds_and_b32`, `ds_or_b32`, `ds_xor_b32`, `ds_min_u32` and + `ds_max_u32`, as HLSL `Interlocked*` operations (`ds_sub_u32` is two `InterlockedAdd` calls on the same + word, `~v` and then `1`, see below); +- `s_barrier`. + +The profile is one guest wave per group. A group of at most 32 threads is one wave at either guest wave +width and needs no statement. A group of 33 to 64 threads needs `--wave-size 64`, the caller's statement that +the program runs as wave64; that statement is accepted only with a shared LDS allocation. Larger groups, and +groups of more than 32 threads under `--wave-size 32`, are several guest waves and are refused. + +Within that one wave, DS instructions take effect in program order: every DS instruction is followed by +`GroupMemoryBarrierWithGroupSync()`, so a read sees the writes of every earlier instruction from all lanes +and a later write cannot overtake an earlier read. The HLSL barrier waits for the whole group, which on the +desktop may run as several host waves; with one guest wave this reproduces the guest order. With several +guest waves the per-instruction barriers would also order DS operations between waves before `s_barrier`, +which the guest program does not guarantee, so that case is left until it has its own native comparison. +`s_barrier` becomes the same barrier and adds one only where no DS barrier precedes it. Barriers need +uniform control flow, so a DS instruction or `s_barrier` after a lane guard is refused. + +The caller guarantees the LDS input contract, which is not checked: +- every access is in bounds and aligned: b32 accesses to 4 bytes, wider ones to their size; +- every word that a read or an atomic touches was written earlier in the group; +- no two lanes of one non-atomic write store to the same word. + +Outside the contract, each access is still guarded by `index < N / 4`: a word past the allocation reads as +zero and is not written, and the low two address bits are dropped. That rule keeps an access from reaching +other words; it is not compared with hardware. Not lowered yet: the returning (`_rtn`) forms, whose results depend on the +order of lanes that update one word; `ds_write_b96`/`ds_read_b96`; byte, short and d16 accesses; signed +min/max; float atomics; and `ds_permute`/`ds_bpermute` and the other lane-routing forms on gfx1013. + +`compute_store_aot_lds_shared` runs eight 64-thread wave64 programs with a 1024-byte allocation on one and +two groups (one group for the four-word programs), and compares every UAV word with a CPU reference. Each lane +writes its own words, and after a barrier reads another lane's: +- the next lane's word and the mirrored lane's word (`63 - l`); +- pairs 64 words apart through `write2`/`read2` and `st64`; +- a qword and qword pairs, written with `ds_write2_b64` and read with `ds_read2st64_b64`, and the other way + round; +- a 16-byte record of the next lane. + +A counter program sets seven words, has every lane add, subtract, AND, OR, XOR, take the minimum and take +the maximum of its index or a mixed word, and reads them back. With two groups, each group's sums cover +only its own threads, which shows that each group has its own LDS. Three mutations of the programs, and +one of the HLSL described below, must mismatch at the first word they change: +- the next-but-one lane, at word 0; +- an `st64` read spelled as a plain `read2`, at word 1; +- `ds_min_u32` in place of `ds_max_u32`, at word 11. + +The translation controls check the barrier count, the `Interlocked*` methods, the allocation guard on every +access and the rejections listed above. The one-wave controls accept a 32-thread group without a statement +and refuse 64 threads without one, 64 threads and a 32 x 2 group under wave32, 128 threads under wave64, and +the wave64 statement without a shared allocation or on gfx1030. Every program is also assembled and disassembled with LLVM 15 for gfx1013, and the CLI must emit the +same HLSL. + +Measured on `b96960b` with this change, Windows 10 build 19045: + +| Adapter | Result | Debug layer | +|---|---|---| +| WARP 1.0.22 (the app-local `d3d10warp.dll`) | passed | enabled | +| NVIDIA GeForce RTX 3080, driver 32.0.15.9174 | passed | enabled | + +The mutations mismatched at their expected words on both adapters. Of the gfx1013 forms in +`tools/form_coverage.py`, the test adds only `s_barrier`, because the gfx1030 private-LDS fixtures already +record the DS mnemonics. + +`ds_sub_u32` used to be one `InterlockedAdd(lds[i], (0u - v))`. On an NVIDIA GeForce RTX 5080 (driver +32.0.16.2124, Windows 11 build 26300.9974, debug layer unavailable) `CreateComputePipelineState` refused that +program with `E_OUTOFMEMORY`, so `compute_store_aot_lds_shared_hardware` failed. The DXIL is valid, and WARP +and an AMD Radeon iGPU (driver 32.0.11034.2) ran it. A reduction to a 64-thread shader isolates the case. The +PSO fails whenever an `InterlockedAdd` on groupshared memory takes `sub i32 0, x` for a runtime `x`. DXC +folds every tried spelling to that instruction, including `~x + 1u`, `x * 0xffffffffu`, `-(int)x` and +`-Od`. The same negation does not fail with `InterlockedAdd` on a UAV, with `InterlockedExchange`, `Xor` or +`Max` on groupshared memory, or with a plain groupshared store. Neither does `5u - x`, `0u - x * 3u` or a +constant addend. The translator now emits two additions on the word, `~v` and then `1u`. That is +`mem - v` modulo 2^32. The step has no return value and ends with a barrier, so no lane reads the +intermediate word. A fourth mutation of the HLSL drops the second addition and must mismatch at word 1. The +translation controls require the two additions and no `0u - ` in the counter program. + +On this change, with the hardware run on the RTX 5080 and then with `XBOX2WINDOWS_ADAPTER=Radeon`: + +| Adapter | Result | Debug layer | +|---|---|---| +| Microsoft Basic Render Driver (WARP), 10.0.26100.9818 | passed | unavailable | +| NVIDIA GeForce RTX 5080, driver 32.0.16.2124 | passed (failed before: `E_OUTOFMEMORY`) | unavailable | +| AMD Radeon(TM) Graphics, driver 32.0.11034.2 | passed | unavailable | + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^compute_store_aot_lds_shared_(warp|hardware)$' -V +``` + An optional `--constant-descriptor BYTE_OFFSET` binds a second table entry to b0. It must be distinct from the 16-byte u0 descriptor. The translator accepts aligned immediate `s_buffer_load_dword`, `s_buffer_load_dwordx2`, and @@ -5821,7 +6258,7 @@ uses reproduces the ISA result bit-for-bit on the byte-addressed UAV: `outputData.InterlockedCompareExchange(offset, expected, next, observed)`. The operand stays 32-bit with `glc` clear, the address stays fixed, and the atomic remains the sole UAV operation; a missing, misspelled or -unused domain, `_x2`, `glc`, `idxen`/`offen`, and every other reduction +unused domain, `glc`, `idxen`/`offen`, and every other reduction binding violation is rejected with the family's diagnostics. Four source-built gfx1030 cases cover both operations with and without @@ -5847,6 +6284,38 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float_' -V ``` +### gfx1030 fixed-address MUBUF float compare-swap and x2 + +The same non-returning raw `u0` profile accepts `buffer_atomic_fcmpswap` +(opcode 62) and `buffer_atomic_fcmpswap_x2`, `buffer_atomic_fmin_x2`, +`buffer_atomic_fmax_x2` (94–96). The address is a fixed aligned byte +immediate; `_x2` uses eight-byte alignment and SM 6.6 raw UAV integer +atomics. The caller declares finite-normal memory at the corresponding +width, and both the replacement and compare operands (or the min/max +operand) must be statically known finite normals. `glc`, dynamic addresses, +non-normal values, and mixed UAV operations are outside this profile. + +On finite normals float equality is bit equality. AMD places replacement +before compare in the VGPR tuple; the HLSL CAS takes compare first. The +unsigned sign-adjusted minimum/maximum ordering extends to 64 bits, using +one CAS over both little-endian DWORDs. The fixtures compare all 320 words +at one and two 32-lane groups, including adjacent sentinel words and a +compare miss triggered by changing only the low bit. An operand-order or +min/max mutation is checked against the independent CPU model and the +original expected readback. These cases contend on one address with the +same literal operands, not distinct per-lane inputs. + +```sh +python3 -B tests/compute_store_check.py binary-mubuf-float-extra llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +```powershell +python -B tests/compute_store_check.py compile-mubuf-float-cmpswap dxc +python -B tests/compute_store_check.py compile-mubuf-float-x2 dxc +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float-(cmpswap|x2)_' -V +``` + ### Indexed gfx1030 raw vector reads The compute store profile also lowers `buffer_load_dwordx2`, @@ -6132,7 +6601,6 @@ The gfx1013 compute store profile lowers `buffer_load_format_x`, `_xy`, `_xyz` a This is the format decoder of item A of #2022. The descriptor still comes from the static table offset (`--source-descriptor`, `--source-stride`). Taking the descriptor from a run-time view record is the [next slice](#heap-view-buffer-loads), so this alone does not count as coverage of any application dispatch. The address is `idxen` only and 4-byte aligned, and four bytes per opcode channel must fit inside the stated stride. These stay refused with this flag: -- the `d16_` forms; - `offen`; - gfx1030; - `--source-format`. @@ -6199,6 +6667,41 @@ On the invalid runs, these mutated sources must fail: Dropping only the -1 clamp is not observable: long division of 32768 by 32767 also gives 1.0. With the lowering removed, or with its channel count changed, the translation controls fail. LLVM 15 assembles the fixture, and `lower` of the disassembly and the CLI output both match `lower` of the source. +The seven matching and fourteen intentionally wrong references use the same shader. The fixture passes +them to `offscreen_check --compute-store-batch ...` in order. They share +one D3D12 device, root signature and pipeline. Each case gets fresh buffers, submits its own dispatch and +compares all 320 words after the fence. The renderer reports `pass`, `mismatch` or `error` for each case +and exits with status 1 if any case fails. The eleven shader mutations still compile and dispatch separately. + +#### d16 forms + +`buffer_load_format_d16_x`, `_xy`, `_xyz` and `_xyzw` use the same format word, validity rule and refusal, and pack two 16-bit channels per result word, x in the low half. The format's type decides the 16-bit value: +- **FLOAT16 formats:** the stored halves, unchanged. +- **UNORM and SNORM16:** binary16 of the value above (`x / (2^n - 1)` or `max(x / 32767, -1)`), rounded to nearest even by long division. Binary16 denormals are kept, so `1/65535` is `0x0100`. +- **16-bit UINT and SINT:** the 16-bit integer, not a float. +- **32-bit formats:** no d16 rule is established here, so `32_UINT` and `32_FLOAT` in one to four channels are invalid under d16 and publish nothing. + +Whether the RDNA format unit rounds the same way, or keeps binary16 denormals, is not verified. + +An odd channel count leaves the high half of the last result word undefined. That word is low-16 only: it reaches a whole-word store or an ALU operand only through `v_and_b32 0xffff`, as for the existing caller-format D16 reads. + +The d16 fixture makes ten loads over the same t0 words, one per format with a d16 rule, and stores them in a 64-byte u0 record. The checks: +- **Readback:** WARP and the hardware adapter compare all 320 words for one group and for two. +- **Invalid formats:** three runs each make one load invalid, and each must leave u0 unwritten. They use `32_32_FLOAT` under `d16_xy`, `16_16_UNORM` under `d16_x`, and `8_SNORM`. +- **Wrong references:** on the two-group run, each of these must fail at its first differing word: + - truncated binary16, and flushed binary16 denormals; + - 16-bit UINT converted like 16-bit UNORM, and 16-bit SINT converted like 16-bit SNORM; + - halves packed high first; + - the legacy word ignored; + - the neighbouring thread's element. +- **Mutated HLSL:** each of these must also fail: + - a binary16 ratio that never rounds up, and flushed binary16 denormals; + - the two integer formats converted; + - halves packed high first, and the SNORM16 half sign dropped; + - the binary32 conversion used under d16; + - on the invalid runs, a 32-bit format accepted under d16, and the refusal removed. +- **Translation controls:** they reject the odd half when the mask is missing, when an ALU operation uses it, and when the destination range is too wide. With the d16 flag dropped, the low-half marking removed, or 32-bit formats given a d16 arm, they fail. + ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_descriptor_load_format_|load_format_controls$)' -V @@ -6222,6 +6725,11 @@ Run `ctest --preset dev -R '^compute_(heap_store_controls|store_aot_heap_view_st ### Packed D16 heap-view stores +The `compute_store_aot_heap_view_store_{warp,hardware}` tests group matching readbacks by shader. +One renderer process per shader runs 12 UINT4 cases and 12, 16, 17 and 17 cases for D16 XYZW, X, +XY and XYZ respectively. Each case dispatches separately and compares 320 words. The 52 shader +mutations run individually and retain their readback diagnostics. + With the same `--heap-store-view` binding, gfx1013 `buffer_store_format_d16_xyzw` reads X/Y from the low/high halves of the first VGPR and Z/W from the second. A live identity `BUF_FMT_32_32_32_32_FLOAT` view (format 77) receives four binary32 words. Two source VGPRs still require 16 writable bytes in the destination. `buffer_store_format_d16_x` takes one source VGPR, converts its low 16 bits (`& 0xffffu`) via `f16tof32`, and writes one 4-byte binary32 word into a live identity `BUF_FMT_32_FLOAT` view (format 22, `0x01016fac`), enforcing 4-byte offset/stride/base alignment and `(bytes - view.x - offset - 4u) / stride` bounds without a raw UAV read-modify-write. A view whose format differs from the required component count or numeric type leaves the output untouched. [AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [HLSL half-to-float conversion](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/f16tof32) The heap-store CTest selection above runs the UINT4 program and all four packed D16 widths. Each D16 fixture checks 320 words across its heap-view cases (with `D16_X` additionally checking four binary16 payload patterns with poisoned high halves: `1.0`..`1.00293`, `-2.0`.., minimum positive subnormal + `+0.0`, and `-0.0` + negative subnormals, plus `UINT1` and `FLOAT4` mismatch rejections and untouched adjacent sentinel dwords). Eleven compiled shader mutations check addressing, view selection, and half-float extraction, including swapping high for low bits, checking the wrong format word, and writing packed values directly. @@ -6271,6 +6779,10 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_|heap_view_controls$)' -V ``` +The 56 matching references and seven wrong references run in two shader batches, one for XY and one for +XYZW. Each dispatch still checks all 320 words. Each wrong reference must report its first differing +word, including the expected and actual values. The fourteen recompiled mutations run individually. + ```sh python3 -B tests/compute_heap_view_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` @@ -6428,6 +6940,18 @@ The fixture in `tests/compute_alu_med3_check.py` keeps the guarded read and stor The translator rejects `clamp`, `op_sel`, neg and abs on a source, which LLVM does not accept for these opcodes. It also rejects the 16-bit and binary32 medians, a register range, an unknown, pending or descriptor SGPR, an unknown VGPR and a literal wider than 32 bits, each with `Unsupported compute instruction`. A destination past `v255` gets `Unverified ALU operand`. A result used as a store address or as a guard operand is rejected, and so is a chain of medians whose expression exceeds the limit. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_med3_(warp|hardware)$' -V`. Without Windows, `tests/compute_alu_med3_check.py controls` runs the exact-text and rejection checks. +#### VOP1 bit reverse and signed leading-bit count + +Two VOP1 forms lower on one known word, with the same sources, data-only results and 1024-character limit as the forms above: + +| Instruction | Result | +|---|---| +| `v_bfrev_b32_e32 vD, a` | `reversebits(a)`: bit i of the result is bit 31 - i of `a` | +| `v_ffbh_i32_e32 vD, a` | the position of the first bit that differs from the sign bit, counting from the MSB with the sign bit as position 0; 0xffffffff for 0 and 0xffffffff | + +`v_ffbh_i32` follows the RDNA 2 ISA definition (`D = -1; for i in 1..31, the first i with S0[31 - i] != S0[31]`), so 1 and 0xfffffffe give 31, and 0x40000000 and 0x80000000 give 1. It lowers as `v_ffbh_u32` of `m = a ^ (a >> 31)`, with an arithmetic shift, spelled `firstbitlow(reversebits(m))`. That is `31 - firstbithigh(m)` and reads 0xffffffff for `m = 0`, and it names `a` only twice. The `_e64`, SDWA and DPP forms, source and output modifiers, register ranges, `v_ffbh_u32`, `v_ffbl_b32` and the scalar `s_brev_b32` and `s_flbit_i32` stop the lowering with `Unsupported compute instruction`. An unknown, pending or descriptor source fails with `Unverified ALU operand`. + +The fixture is the read-compute-write kernel above with a 16-byte element per lane. For the source word `w`, it stores `bfrev(w)`, `ffbh_i32(w << (w & 31))`, `ffbh_i32(ashr(bfrev(w), (w >> 5) & 31))` and `((bfrev(gid) ^ ffbh_i32(cap)) + ffbh_i32(-1)) ^ bfrev(0x12345678)`, with `cap = params[0].y = 0xfffffffe`. Over the 70 active lanes, the scanned words have both signs, include 0 and 0xffffffff, and give every result from 1 to 30 except 14 and 16. The cap gives 31. The expected words come from Python bit loops written from the ISA text, not from the lowering. The WARP readback compares all 320 words for no active lane, a split wave and three groups with 70 active lanes. On the last dispatch, each of these must fail at the first word where it differs: a reference with one word off, lane 70 also writing, `ffbh_u32` for `ffbh_i32`, a count that leaves out the sign bit, an LSB-first index, 32 for 0 and -1, and `bfrev` as a copy. So must recompiled HLSL with `bfrev` as a copy or a complement, and `ffbh_i32` as `ffbh_u32`, with a logical sign fold, as an LSB-first index, as 32 for 0 and -1, or as the count minus one. Run `python -B tests/compute_alu_vop1_check.py controls` for the translator checks only, or `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_vop1_(warp|hardware)$' -V`. #### Signed 24-bit multiply-add `v_mad_i32_i24 vD, a, b, c` (VOP3 opcode 0x142) is the signed counterpart of `v_mad_u32_u24`: each multiplicand is the signed integer in bits [23:0] of its word, and `c` is a whole word, so the result is `sext24(a) * sext24(b) + c`, modulo 2^32. It takes the same sources as `v_mad_u32_u24`. The lowering sign-extends with `asuint(asint(x << 8u) >> 8u)` and multiplies and adds as `uint`, which gives the same low 32 bits as the signed product. `clamp`, the text forms `-v` and `|v|` (LLVM rejects them for this opcode), a source that is not a known word, a byte offset (which stays a row pitch only for `v_mad_u32_u24`) and a destination past v255 each stop the lowering. `v_mul_i32_i24` and `v_mad_i64_i32` are still outside the subset. @@ -6455,7 +6979,7 @@ Four VOP2 forms lower to one rounded binary32 operation each, on the bit pattern A source is a VGPR, an SGPR that holds a known word, a 32-bit literal, the integer zero or one of the inline float constants LLVM prints (`0.5`, `1.0`, `2.0`, `4.0`, their negatives and `0.15915494`). The second source is a VGPR. Each operation is a small HLSL helper whose result is `precise`, so a multiply followed by an add is not contracted into one fused operation. The helpers are emitted only when the program uses them. -Fused multiply-add is not in this subset. `v_fma_f32`, `v_fmac_f32_e32` and `v_mac_f32_e32` stop the lowering at that instruction, because DXIL has no binary32 form whose single rounding is guaranteed. The `_e64` spellings, `clamp`, `abs` and negation modifiers, an SGPR as the second source, `v_max_f32`, `v_min_f32` and `v_mul_legacy_f32` are refused too. +Fused multiply-add is not in this subset. `v_fma_f32`, `v_fmac_f32_e32` and `v_mac_f32_e32` stop the lowering at that instruction, because DXIL has no binary32 form whose single rounding is guaranteed. The unmodified `_e64` spellings, `clamp`, `abs` and negation modifiers on the `_e32` spellings, an SGPR as the second source, `v_max_f32`, `v_min_f32` and `v_mul_legacy_f32` are refused too. The `_e64` spellings with source modifiers are described under [Negated and absolute binary32 sources](#negated-and-absolute-binary32-sources). NaN, infinity and denormals are not claimed. A literal, an inline integer or a scalar move that is one of them is refused with `Unverified float operand`. A word read from memory is not known statically, so its value is not checked: a caller that binds such a word must keep every operand and result finite and normal. The fixture below builds its operands with integer operations so that they always are. @@ -6477,6 +7001,24 @@ The source-built 32-thread fixture stores four words per thread (`128` words act The fixture replaces the `umin` of the read-compute-write fixture with two `v_xor3_b32`, hand-edited in LLVM 15 spelling: `out = (p ^ key ^ gid) ^ 0x2c5a96e1 ^ -16`, where `p` is the product above and `key = params[0].y = 0xa5c30f96`. Its sources are a result, the dispatch index, an SGPR constant word, a literal and a negative inline constant. The expected words come from a Python model of the instruction definition; lane 0 is also worked by hand (`0x2d574c65`). The readback uses the read harness and its three dispatches and compares all 320 words. On five groups with `n = 150`, each of these references must fail at the first word where it differs: one word off, lane 150 also writing, OR, AND or an add instead of XOR, each source dropped, and `+16` for `-16`. So must recompiled HLSL with an OR for either XOR, the key read from `params[0].z`, the dispatch index dropped, the literal off by one bit, or the inline constant dropped. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_xor3_(warp|hardware)$' -V`. The translation controls alone are `python -B tests/compute_alu_xor3_check.py controls`. +#### Bitfield mask (`v_bfm_b32`) + +`v_bfm_b32 vD, a, b` is VOP3 only on gfx10. Its result is `((1 << (a & 31)) - 1) << (b & 31)`, modulo 2^32: `a` is the width and `b` the offset. A width field of 0 gives 0. A width of 32 cannot be encoded, so the widest mask is `0x7fffffff`. Mask bits shifted past bit 31 are dropped. Both sources are known words, as for `v_mul_lo_u32`, and the result is data only. + +The fixture in `tests/compute_alu_bfm_check.py` is the read-compute-write kernel above with its ALU lines replaced by hand. With `w` the source word of lane `gid` and `cap = params[0].y = 0xc0de0029`, it stores `bfm(w, w >> 5) ^ bfm(cap, 0x7b) ^ bfm(44, gid)`. The sources are two VGPRs, an SGPR with a literal, and an inline constant with the dispatch index. Bits above bit 4 are set in every width and offset word. Lanes 0 to 31 see every width from 0 to 31, and many lanes have masks cut at bit 31. The expected words come from a Python model that builds each mask bit by bit. Five lanes are also worked out by hand: lane 0 is `0x78000fff`, lane 14 (width 31) is `0x0bffc000`, lane 31 (width 0) is `0x78000000`, lane 32 is `0x07ff0fff` and lane 149 is `0xf81f8000`. + +The Windows run uses the read harness and its three dispatches and compares all 320 words. Each of these references must fail at the first word where it differs: one word off by one bit, lane 150 also writing, the operands swapped, a 6-bit width or offset field, a width of 0 read as 32, and the cut bits rotated into the low bits. So must recompiled HLSL with the `- 1u` dropped, the inline width 43, the cap term's operands swapped, or the cap read from `params[0].z`. The translation controls refuse `abs` and negation modifiers, `clamp`, a register range, `vcc_lo`, `exec_lo`, a float inline constant, the `_e64` spelling, `s_bfm_b32`, `s_bfm_b64`, `v_bfe_u32` and `v_bfi_b32` with `Unsupported compute instruction`. Unknown sources and a destination past v255 fail with `Unverified ALU operand`. A result used as a store address or a lane-guard operand is refused. The fixture text is checked against LLVM 19 `llvm-mc` only; the test does not assemble it. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_alu_bfm_(warp|hardware)$' -V`. + +#### Negated and absolute binary32 sources + +Issue #1546 lists the `-|v|` operand form among the gaps of the measured compute programs. The four binary32 forms above also lower in their VOP3 spelling, `v_add_f32_e64`, `v_sub_f32_e64`, `v_subrev_f32_e64` and `v_mul_f32_e64`, when at least one source carries a source modifier as LLVM 15 prints it on a register: `-v`, `|v|` or `-|v|` (likewise for an SGPR). The modifiers act on the sign bit of the 32-bit word, abs first and then neg, as the pixel translator does for `v_cvt_f64_f32_e64` and the binary64 compare sources: `|v|` is `(w & 0x7fffffffu)`, `-v` is `(w ^ 0x80000000u)` and `-|v|` is `((w & 0x7fffffffu) ^ 0x80000000u)`. They are integer operations on the word, so a signed zero or a NaN payload keeps its other bits; no float `abs()` or unary minus is emitted. In this spelling either source may be a VGPR, an SGPR that holds a known word, a literal, the integer zero or an inline float constant. The operation, its rounding and its finite-and-normal caller contract are those of the `_e32` forms. + +The unmodified `_e64` spelling stays refused at the instruction. `clamp` and the output modifiers `mul:2`, `mul:4` and `div:2` are refused with `Unsupported float output modifier`. The `abs()` and `neg()` spellings, unbalanced bars, a nested modifier and a modifier on a constant (`|1.0|`, `neg(0x3f800000)`, `-0x3f800000`) are refused with `Unsupported float source modifier`. A modified source that is not a known word, or a constant that is NaN, infinite or denormal, is refused with `Unverified float operand`. Modifiers on the `_e32` spellings, other binary32 and binary16 opcodes and `v_fma_f32` stop the lowering at the instruction. + +The fixture in `tests/compute_alu_negabs_check.py` is the read-compute-write kernel with the read bindings and `cap = params[0].y`, the float -0.75. From the source word it builds `x` in [1.5, 2) and `y` in [3, 4) as in the fixture above, then `d = x - 1.75`, which is negative on some lanes and positive on others, `z = 0 * d`, a signed zero, and `a = |d| + y`, `b = -d * a`, `c = b - (-|d|)`, `e = (-c) - |cap|`, `f = -|z| * y` (-0.0 on every lane) and `out = e ^ f` with the integer XOR, so bit 31 of `f` reaches the readback. Each modifier appears on two operations, and the SGPR and a second source carry one. The expected words come from a Python model that applies the modifiers to the bits and rounds each step to binary32. The translation controls pin the exact store, evaluate the three modifier expressions on +0, -0, quiet and signalling NaN payloads, -infinity, a negative value and a denormal word against the bit model, and refuse each form listed above. Dropping the abs or the neg in the lowering, emitting the negation as a float negation, or accepting an output modifier, unbalanced bars or a modified constant each fails them. + +The readback uses the read harness and its three dispatches and compares all 320 words. For each modified source, a reference with the negation dropped, the abs dropped, or abs and negation exchanged (12 references) must fail at its first differing word. So must recompiled HLSL with any one of the four abs masks dropped, or any one of the four sign flips dropped or replaced by an abs (12 mutations). The `binary` mode assembles the fixture with LLVM 15, requires the disassembly to print the five modified lines unchanged and to translate identically; it runs in the Ubuntu job. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_f32_negabs_(warp|hardware)$' -V`. The translation controls alone are `python -B tests/compute_alu_negabs_check.py controls`. + #### Bit count plus addend (`v_bcnt_u32_b32`) `v_bcnt_u32_b32 vD, a, b` is `D = CountOneBits(a) + b`, the addend wrapping modulo 2^32 (RDNA2 instruction set; @@ -6627,6 +7169,17 @@ The result becomes an inline HLSL expression, like a vector result, and a vector The check assembles one fixture that chains all six operations over the cap word and the bound, and requires the decoded program to lower to the same HLSL as its text. +#### Single-bit set and clear + +The SOP1 forms `s_bitset0_b32 sD, s` and `s_bitset1_b32 sD, s` clear or set bit `s[4:0]` of `sD` and keep its other bits (RDNA ISA: `D.u32[S0.u32[4:0]] = 0` or `1`; SCC is not written). They read `sD` as well as write it, so `sD` must already hold a known word, and `s` is a known word as above. The result is `sD & ~(1u << (s & 31u))` or `sD | (1u << (s & 31u))`. A destination that holds no known word (an unwritten SGPR, a descriptor, the table pointer, a group ID, the saved exec mask, or a load still waiting), an unknown or wider-than-32-bit source, a destination past s105, a vector source and the 64-bit forms stop the lowering, as does an expression over 1024 characters. + +`tests/compute_salu_bitset_check.py` dispatches one invocation that applies both forms to eight root constant words and stores eight results. Between its two constant sets it sets bit 0, clears and sets bit 31 (through a runtime index, the inline constants `63` and `-1`), uses runtime indices above 31 (`0x47`, `0x20`, `0xffffffe3`), sets bits that are already set, clears bits that are already clear, and reads a destination that is also the source. A CPU reference that rewrites one entry of the word's bit list gives the expected words, and the check also lists them as hand-worked values. Swapped set and clear, an unmasked index, a dropped destination and the other run's words must each fail the readback, and so must mutated translations. `controls` runs the translator checks only: + +```powershell +.\out\pe-env\Scripts\python.exe -B tests/compute_salu_bitset_check.py controls +ctest --preset dev --no-tests=error -R '^compute_store_aot_salu_bitset_warp$' -V +``` + #### Scalar bit-field extract `s_bfe_u32 sD, S0, S1` and `s_bfe_i32 sD, S0, S1` (SOP2) extract a `S1[22:16]`-bit field starting at `S1[4:0]` from a known 32-bit scalar word `S0`, zero- or sign-extending to 32 bits (`0` when `S1[22:16] == 0`, and `S0 >> S1[4:0]` when `S1[4:0] + S1[22:16] > 32`). `SCC` is written (`D != 0`) but unread in this subset. Both lower to explicit HLSL helpers (`s_bfe_u32` and `s_bfe_i32`) emitted only when referenced, so a width of `0` returns `0` rather than shifting by `32`, and every shift count stays in `0..31`. @@ -6685,7 +7238,7 @@ The `SUB_CO` fixture in `tests/compute_store_check.py` (`draw-sub-co`, `compute_ `v_mac_f32_e32 vD, S0, vS1` (VOP2 `0x1f`) and `v_mac_f32_e64 vD, S0, S1` (VOP3) compute `D = S0 * S1 + D` as an unfused binary32 multiply-add: the intermediate product `S0 * S1` rounds to binary32 before the addition. `D` is both an input accumulator and the destination. Lowering uses `f32_mac(a, b, c)` with separate `precise float p = asfloat(a) * asfloat(b)` and `precise float r = p + asfloat(c)` so DXC does not contract the operation to FMA. NaN/Inf/denormal literal constants, uninitialized/unknown or pending `S0`/`S1`/`D`, `vD > 255`, source modifiers (`-`, `|.|`), `clamp`, `omod`, and bare `v_mac_f32` are refused. -The `MAC_F32` fixture in `tests/compute_store_check.py` (`draw-mac-f32`, `compute_store_aot_mac_f32_${adapter}`) runs one 64-thread group (`buffer_store_dwordx4`, 256 output words plus 64 `SENTINEL` words), including `4097 * 4097 + (-16785408)` and `(1 + 2^-23) * (1 + 2^-23) - (1 + 2^-22)` where unfused and fused results differ, and compares all 320 words against an independent Python model. Reference controls (fused FMA at word 0, `p - c` at word 2, accumulator zeroed at word 3, sentinel modified at word 256) and recompiled-HLSL mutations (`mad()` fused multiply-add, `p - asfloat(c)`) must all fail. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_mac_f32_(warp|hardware)$' -V`. +The `MAC_F32` fixture in `tests/compute_store_check.py` (`draw-mac-f32`, `compute_store_aot_mac_f32_${adapter}`) runs one 64-thread group (`buffer_store_dwordx4`, 256 output words plus 64 `SENTINEL` words), including `4097 * 4097 + (-16785408)` and `(1 + 2^-23) * (1 + 2^-23) - (1 + 2^-22)` where unfused and fused results differ, and compares all 320 words against an independent Python model. Reference controls (fused FMA at word 0, `p - c` at word 2, accumulator zeroed at word 3, sentinel modified at word 256) and recompiled-HLSL mutations (`mad()` fused multiply-add, `p - asfloat(c)`) must all fail. DXIL lets the driver fuse `mad()` (`FMad`) or not, so on hardware the `mad()` mutation is first read back against the fused and the unfused model. Word 0 has only constant operands, and DXC 1.9.2602.17 folds its `mad()` at compile time to the unfused +0, so the fused model fuses only the thread-dependent words and keeps word 0 unfused; the two models differ at words 2, 10, 18, … ([#2883](https://github.com/R0Y00/Xbox2Windows/issues/2883)). Exactly one must match all 320 words; anything else fails the test, and the failure names each model's first mismatch. Where the fused model matches (an RTX 4090), the mutation must be detected. `mac_f32_controls()` runs the probe against a simulated renderer: an unfused readback and the folded fused readback are classified, and a fully fused readback or a renderer exit of 3 fails. Where the unfused model matches (an RX 5700 XT and an RX 9070 XT, [#2730](https://github.com/R0Y00/Xbox2Windows/issues/2730)), the mutation equals the lowering, and the test logs it as inapplicable on that adapter. The full comparison, the reference controls and the other mutations stay mandatory. Run `ctest --preset dev --no-tests=error -R '^compute_store_aot_mac_f32_(warp|hardware)$' -V`. ```powershell ctest --preset dev --no-tests=error -R '^compute_store_aot_salu_i32_(warp|hardware)$' -V @@ -7554,6 +8107,38 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_to_pixel_(warp|hardware)$' -V ``` +## Signed zero in floating-point min and max + +The RDNA 2 ISA defines `-0 < +0` for `V_MIN_F32`, `V_MAX_F32`, `V_MIN_F16` +and `V_MAX_F16` (§12.7, pp. 132–133 and 136). Its three-input min and max +compose these operations (§12.12, p. 170), and its packed instructions apply +min or max to each half (§12.10, p. 164). The median description specifies a +median without a separate mixed-zero rule. The fixture uses the same signed-zero +ordering for the median. DXIL FMin and FMax permit either operand when their +values compare equal. [AMD RDNA 2 ISA](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content), [DXIL operation reference](https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#fmax) + +Both translators now resolve a pair of zeros from the sign bits. Maximum ANDs +the signs and minimum ORs them. The startup shader cache revision advances to +`x2w-startup-shader-18`, so translations cached before the change are not reused. The pixel translator applies the same rule to +each widened half for packed binary16 min and max. It retains the packed NaN +selection and the existing output modifiers. The startup translator retains +its own median NaN behavior. Scalar binary16 min/max, three-input binary16 +forms and startup SDWA min/max remain outside the supported instruction set. + +On Windows 10 (10.0.19045.6456), the in-box WARP baseline (10.0.19041.5794) +returned `00000000` for `(-0, +0)` and `80000000` for `(+0, -0)` for both +two-input operations. Three-input and packed results also varied with operand +order. WARP differed from the reference on 50 of 252 result words. The GTX 1060 +(32.0.15.6094) already matched all 252. With the helper, both adapters matched +all words, including single quiet NaN inputs and binary16 packed results. +The draws use DXC for the offline pixel path and DXC and FXC for the startup +path. These comparisons cover desktop results. Median and packed tie behavior +on console hardware, signaling NaNs and NaN payload propagation were unmeasured. + +Run `ctest --preset dev --no-tests=error -R '^shader_signed_zero_minmax_' -V`. +The Python test pins each emitted lowering and the LLVM 15 check reassembles +the source-built instructions. + ## Offline pixel shader recompilation The 64-bit scalar set and clear forms are s_bitset0_b64 and s_bitset1_b64. @@ -7769,6 +8354,28 @@ all 2,376 CPU evaluations and all 1,024 exported 32-bit words of the 16 x 16 pix reference, while five mutated HLSL controls fail against the reference and match their own models. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sdwa_cvt(_warp|_hardware)?$' -V`. +The SDWA form of the VOP2 select, `v_cndmask_b32_sdwa vD, src0, src1, vcc_lo`, was refused as +`SDWA form of v_cndmask_b32`. `sdwa()` now lowers it as a two-source integer operation: each source takes its +`src0_sel`/`src1_sel` field, zero-extended or sign-extended under `sext()`, the select reads VCC the way the plain +`v_cndmask_b32` does and picks `src1` where the lane's bit is set, and `dst_sel`/`dst_unused` place the result by +the same rules as the other integer SDWA forms. The mask is always VCC, printed as the fourth operand; ` clamp`, +float modifiers and `UNUSED_SEXT` stay refused. The semantics are the integer SDWA rules already used for the +other forms with the select as the operation; they are not checked against the ISA document here and not measured +on a console. `startup_gfx2hlsl_sdwa_cndmask` draws a constructed gfx1013 pixel stage with four selects over +16 x 16 pixels: VCC is bit 31 of a per-pixel product clear (set in 160 of 256 pixels), and the selects cover byte +and word sources from two registers, a sign-extended `BYTE_2` widened into `WORD_0`, and `WORD_0`, `BYTE_1` and +`BYTE_2` destinations under `UNUSED_PRESERVE` over 1.0, which keeps every exported word a normal binary32 value +(asserted, since the target is `R32G32B32A32_FLOAT`). All 1,024 exported words match a bit model, and six +mutated selects (swapped operands, the mask ignored, the mask inverted, a dropped `sext()`, the neighbouring source +byte and the wrong destination byte) each fail against the model and match their own; that is 26 draws per adapter +with FXC (`ps_5_1`) and DXC (`ps_6_0`). Translating the fixture with the previous translator stops at the +refusal. `startup_gfx2hlsl_sdwa_cndmask_check.py binary ` requires LLVM 15 to assemble the fixture for +gfx1013 to the same words and to print each select as written. Verified on commit base `0736f67c`, Windows 11 +(build `26200.9974`), D3D12 debug layer enabled (`debug_errors=0 debug_warnings=0`), on Microsoft Basic Render +Driver (`1414:008c`, driver `10.0.26100.9818`) and NVIDIA GeForce RTX 5090 (`10de:2b85`, driver `32.0.16.1088`), +with LLVM 15.0.7. This shows that the translated select computes the stated words on desktop GPUs, not that the +console does. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sdwa_cndmask(_warp|_hardware)?$' -V`. + **The binary32 class comparison.** `v_cmp_class_f32` and `v_cmpx_class_f32` had no lowering, so both census forms were refused - 2 of the remaining refused shaders in the first main-game loading-screen cache (#870, issue #1797). They now lower to a ten-class helper carried in the shader preamble (ported from @@ -7987,6 +8594,85 @@ one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked as lane masks are refused because their per-lane projections lose the other bits. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitcmp$' -V`. +**Scalar absolute value.** Startup translation lowers `s_abs_i32` to +`(asint(S0) < 0 ? (0u - S0) : S0)` with `SCC = (D != 0)`, matching `pixel_aot` +(INT_MIN stays). Lane masks and descriptor-bearing sources are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_abs_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated expression into a +compute shader and compare UAV readback for INT_MIN, -1, 0 and a positive +word (plus an SCC-dependent branch token) against the same reference: +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_abs_dispatch_warp$' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + +**Scalar 64-bit quad mask.** Startup translation lowers `s_quadmask_b64` so each +output bit is the OR of one four-bit group of the 64-bit source: sixteen nibbles +become bits 0..15 of `D.lo`, `D.hi` is 0, and `SCC = (D.lo | D.hi) != 0`, matching +`pixel_aot`. Integer inline constants are interpreted at 64 bits. +An encoded 32-bit literal zero-extends to 64 bits. +Lane masks, descriptor-bearing SGPRs, and odd-aligned pairs are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_quadmask_b64$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_quadmask_b64_check.py`). The fixture is +CPU-only and compares negative inline constants with 32-bit literals that +have the same low word. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + +**Scalar find-first-zero.** Startup translation lowers `s_ff0_i32_b32` to +`firstbitlow(~S0)` (0xffffffff when every bit is set), matching `pixel_aot` / +`ff0_i32_b32`. SCC is unchanged. Lane masks and descriptor-bearing sources are +refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_ff0$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_ff0_check.py`). The fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + +**Scalar bit set and clear.** Startup translation lowers `s_bitset0_b32` and +`s_bitset1_b32` in place: bit `S0[4:0]` of the destination is cleared or set, +and SCC is unchanged (same form as `pixel_aot` / #1579; Refs #2023 Item J). +Lane masks and descriptor-bearing SGPRs are refused. A known constant +destination with a known bit index folds. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bitset$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_bitset_check.py`). The fixture is +CPU-only; Windows WARP/hardware draws are left for an independent retest. +**Scalar find-first-one.** Startup translation lowers `s_ff1_i32_b32` of a +general scalar to `firstbitlow` (0xffffffff when the word is zero), matching +`pixel_aot` / Mesa. The compute-entry special case on `exec_lo` still folds to +lane 0. SCC is unchanged. Lane masks and descriptor-bearing sources are +refused. `s_ff1_i32_b64` accepts a 32-bit SOP1 literal/inline (ISA zero-extends +the high word to 0) and folds it, and also lowers a live SGPR pair with the same +64-bit firstbitlow scan as the scalar bit-scan forms. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_ff1$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_ff1_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated `firstbitlow` into a +compute shader and compare UAV readback for inputs 0, 1, 0x80000000 and +0x00010000 (and the zero-extended b64 immediates) against the same reference: +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_ff1_dispatch_warp$' -V`. +[Refs #2022](https://github.com/R0Y00/Xbox2Windows/issues/2022) Item F. + +**Scalar find-first-bit-high.** Startup translation lowers `s_flbit_i32_b32` to +`S0 == 0 ? 0xffffffff : 31 - firstbithigh(S0)`, matching `pixel_aot` / +`dpp_ffbh_u32`. SCC is unchanged. Lane masks and descriptor-bearing sources +are refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_flbit$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_flbit_check.py`). The `_dispatch_warp` +/ `_dispatch_hardware` variants compile the translated expression into a +compute shader and compare UAV readback for 0, 1, 0x80000000 and 0x00010000 +against the same reference (including `flbit(0) == 0xffffffff`): +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_flbit_dispatch_warp$' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + +**Scalar quad mask.** Startup translation lowers `s_quadmask_b32` so each +output bit is the OR of one four-bit group of the source (8-bit result), with +`SCC = (D != 0)`, matching `pixel_aot`. Lane masks and descriptor-bearing +sources are refused. The 64-bit form stays refused. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_quadmask$' -V` +(or `python3 -B tests/startup_gfx2hlsl_s_quadmask_check.py`). The +`_dispatch_warp` / `_dispatch_hardware` variants compile the translated +expression into a compute shader and compare UAV readback for 0, a low +nibble, bit 31 and `0x000f0000` (plus an SCC-dependent branch token): +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_quadmask_dispatch_warp$' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723). + **Scalar immediate comparisons.** The startup translator sign-extends the 16-bit field of `s_movk_i32` and `s_cmpk_*_i32`, and zero-extends the field of `s_cmpk_*_u32`. The source-built check covers all six relations against @@ -8275,7 +8961,7 @@ The draws (`pixel_aot_cmp_f64_warp` and `_hardware`) run eight predicate groups ctest --preset dev --no-tests=error -R '^pixel_aot_cmp_f64_(warp|hardware)$' -V ``` -The 64-bit `VOP3` shifts `v_lshlrev_b64`, `v_lshrrev_b64` and `v_ashrrev_i64` (issue #928) follow the [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §12.12 (opcodes 767-769): `D = S1 << S0[5:0]`, `S1 >> S0[5:0]` and `signext(S1) >> S0[5:0]`. The opcodes match the LLVM 15 gfx1013 encodings, and LLVM 15 folds an IR shift by `x & 63` into the bare instruction while keeping `x & 31`. The value uses the two-word representation of the 64-bit comparisons above, so the HLSL needs no 64-bit type: both source words are read into temporaries before the destination pair is written, so the in-place form keeps the original value, and the result is selected for amounts below and above 32, so no 32-bit HLSL shift receives a count of 32 or more. Only `v_ashrrev_i64` fills with the sign bit. The amount is a VGPR, an SGPR, an inline integer from -16 to 64 or a literal; the value is a VGPR pair, an SGPR pair or an inline integer, sign-extended to 64 bits as for the comparisons (assumed, not sourced). At most one source may be an SGPR or a literal (the ISA's one scalar broadcast constant; LLVM 15 refuses the others with `violates constant bus restrictions`). `_e32`, `clamp`, `op_sel` and source modifiers, a destination that is not a pair in `v0`..`v255` or has an outstanding image sample, float amounts and use inside a masked region are refused. The draw (`tests/pixel_aot_check.py draw-shift64`, tests `pixel_aot_shift64_warp` and `pixel_aot_shift64_hardware`) compiles three programs per instruction (register sources; the in-place pair next to the literal amount `0x41`, which wraps to 1; and an SGPR-pair value next to the inline `-1`) and reads the four result words back through `R32G32B32A32_UINT` for three values (one with a negative high word) and the amounts 0, 1, 31, 32, 33, 63, 64, 65, `0xffffffc1` and `0x80000020`, against a Python reference written from the ISA formulas. Three mutated `v_ashrrev_i64` shaders must each mismatch: the amount masked to five bits, the sign fill replaced with zeros, and the result words swapped. The LLVM 15 round trip covers the nine programs; the scanner accepts the same operand shapes and `tests/rdna2_tools_check.py` pins them. The draw pins the translator's model on a desktop adapter; it is not evidence for gfx1013 hardware. +The 64-bit `VOP3` shifts `v_lshlrev_b64`, `v_lshrrev_b64` and `v_ashrrev_i64` (issue #928) follow the [AMD RDNA 2 ISA guide](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §12.12 (opcodes 767-769): `D = S1 << S0[5:0]`, `S1 >> S0[5:0]` and `signext(S1) >> S0[5:0]`. The opcodes match the LLVM 15 gfx1013 encodings, and LLVM 15 folds an IR shift by `x & 63` into the bare instruction while keeping `x & 31`. The value uses the two-word representation of the 64-bit comparisons above, so the HLSL needs no 64-bit type: both source words are read into temporaries before the destination pair is written, so the in-place form keeps the original value, and the result is selected for amounts below and above 32, so no 32-bit HLSL shift receives a count of 32 or more. Only `v_ashrrev_i64` fills with the sign bit. The amount is a VGPR, an SGPR, an inline integer from -16 to 64 or a literal; the value is a VGPR pair, an SGPR pair, an inline integer, sign-extended to 64 bits as for the comparisons (assumed, not sourced), or a 32-bit hex literal (`0x0` to `0xffffffff`, written in hex form). A literal fills the low word; the high word is zero for `v_lshlrev_b64` and `v_lshrrev_b64` and copies bit 31 for `v_ashrrev_i64`. The same hex literal is now also the 64-bit source of the scalar `s_lshl_b64`, `s_lshr_b64`, `s_ashr_i64`, `s_bfe_u64` and `s_bfe_i64`, which refused it before; the high word is zero for the unsigned operations and copies bit 31 for the signed ones (`s_ashr_i64`, `s_bfe_i64`). Only `s_mov_b64` zero-extended a hex literal before this change. The extension rule is an assumption, not sourced from the ISA text. A decimal literal outside -16 to 64, a hex literal wider than 32 bits and a literal as destination stay refused. `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_shift64_literal$' -V` checks six lowered vector forms and the scalar `s_ashr_i64`, `s_lshr_b64`, `s_bfe_i64` and `s_bfe_u64` (including `0x80000000` and `0xffffffff`, where the signed forms differ) and these refusals; it is pure Python and needs no adapter. At most one source may be an SGPR or a literal (the ISA's one scalar broadcast constant; LLVM 15 refuses the others with `violates constant bus restrictions`). `_e32`, `clamp`, `op_sel` and source modifiers, a destination that is not a pair in `v0`..`v255` or has an outstanding image sample, float amounts and use inside a masked region are refused. The draw (`tests/pixel_aot_check.py draw-shift64`, tests `pixel_aot_shift64_warp` and `pixel_aot_shift64_hardware`) compiles three programs per instruction (register sources; the in-place pair next to the literal amount `0x41`, which wraps to 1; and an SGPR-pair value next to the inline `-1`) and reads the four result words back through `R32G32B32A32_UINT` for three values (one with a negative high word) and the amounts 0, 1, 31, 32, 33, 63, 64, 65, `0xffffffc1` and `0x80000020`, against a Python reference written from the ISA formulas. Three mutated `v_ashrrev_i64` shaders must each mismatch: the amount masked to five bits, the sign fill replaced with zeros, and the result words swapped. The LLVM 15 round trip covers the nine programs; the scanner accepts the same operand shapes and `tests/rdna2_tools_check.py` pins them. The draw pins the translator's model on a desktop adapter; it is not evidence for gfx1013 hardware. The non-packed 16-bit integer `VOP3` ops (issue #669) `v_add_nc_u16`, `v_add_nc_i16`, `v_sub_nc_u16`, `v_sub_nc_i16`, `v_min_u16`, `v_max_u16`, `v_min_i16`, `v_max_i16`, `v_mul_lo_u16`, `v_lshlrev_b16`, `v_lshrrev_b16` and `v_ashrrev_i16` compute on the low 16 bits of two sources and reuse the lane arithmetic of the packed forms: results wrap modulo 2^16, signed min, max and shifts sign-extend the 16-bit value, and shift counts are masked to 4 bits (`& 15`, so a count of 16 shifts by 0). Only the low 16 bits of the result are defined and tracked: the lowering records the destination as `("low16", alu)`, a value whose HLSL variable holds the zero-extended result but whose upper half no accepted reader observes. The destination's previous value is not merged, so a destination may hold anything (a tracked value, an untracked register or another low16 result); a destination with an outstanding image sample is refused. The same applies to the unsuffixed and the `_e64` spelling. The readers that see a low16 value are the 12 ops themselves (a chain of two ops is accepted), the 16-bit integer compares `v_cmp_{eq,ne,lt,le,gt,ge}_{i16,u16}` and `v_mov_b32_sdwa` with `src0_sel:WORD_0`, `BYTE_0` or `BYTE_1` (also with `sext()`), which widens the low half into a fully defined word. Every whole-word or high-half reader is refused: 32-bit integer and float arithmetic, moves, `v_cndmask_b32` data operands, DPP, packed `VOP3P` forms, conversions (including `v_cvt_f32_f16`, which is out of scope for integer low16; binary16 arithmetic results use the distinct `half16` tag, below), dot products, class compares, packs, both export forms and image sample coordinates raise `Expected a numeric register`, `Expected a numeric VGPR in DPP`, `Unsupported pack operand`, `Unsupported export` or `Unsupported texture coordinate`; `v_cvt_f16_f32` into a low16 destination raises `Unsupported conversion destination`; and `v_mov_b32_sdwa` with `WORD_1`, `BYTE_2`, `BYTE_3` or `DWORD` on a low16 source, or with `dst_unused:UNUSED_PRESERVE` into a low16 destination, raises `Reads the undefined high half of a 16-bit result`. A source may be a VGPR in 0 to 255 that holds a tracked value, a tracked SGPR in 0 to 105, an integer inline constant from -16 to 64 or a literal up to `0xffff`. `op_sel`, `clamp`, source modifiers, DPP, SDWA, the f16 ops, float tokens, wider literals, inline integers outside -16 to 64 (llvm-mc would encode `-17` as the literal `0xffef`; the translator refuses it by policy, as for the 16-bit compares), an untracked source, a register out of range and a destination with an outstanding image sample are refused. `tests/form_coverage_check.py` asserts that the 12 unsuffixed forms are counted while the f16 neighbours are not. `tools/scan_unsupported_shaders.py` matches instructions syntactically and cannot see the low16 tags, so it can report a shader as supported that the translator then refuses at a whole-word reader. The binary fixtures (four programs; groups 0 to 2 widen all four results and group 3 its two low-half results with `v_mov_b32_sdwa ... src0_sel:WORD_0`) round-trip through LLVM 15.0.7, and the controls refuse every form above with its message. Reproduce with `ctest --preset dev --no-tests=error -R "^pixel_aot_int16_vop3_"`: groups 0 to 2 preload `v24` to `v27` with a `0xa5c3xxxx` sentinel, run four ops on constant words, widen each result into `v12` to `v15` with SDWA `WORD_0` and export through the bit-exact `R32G32B32A32_UINT` target against a Python reference written from the semantics that contains only the zero-extended low halves; group 3 chains `v_add_nc_u16` into `v_mul_lo_u16` and selects between whole words with `v_cmp_lt_u16` and `v_cmp_lt_i16` on low16 results. Six word sets cover `0x7fff` against `0x8000`, `0xffff + 1`, `0 - 1`, shift counts 15, 16, 17 and 31, a negative operand under `ashrrev`, signed and unsigned min and max that disagree, the overflow `0x1234 * 0x0567`, and sources whose high half differs from the low half. Five mutations of the generated shader must each report a pixel mismatch (a source read from bits 31:16, a shift mask of 31 instead of 15, `v_min_i16` replaced by `v_min_u16`, and a `>> 16u` read of a low16 result by the chained op and by the first compare), and a widening that selects `WORD_1` instead of `WORD_0` must be refused at lowering. The sentinel preloads do not detect a high-half leak, because every accepted reader skips the high half; that half is guarded only by the refusal controls. The binary round trip disassembles through libLLVM; `tools/disasm_rdna2.py` decodes the same encodings. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) @@ -8363,6 +9049,8 @@ The carry-out add and subtracts `v_add_co_u32`, `v_sub_co_u32` and `v_subrev_co_ The carry-in add and subtracts `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` lower in both encodings, VOP2 (`_e32`) and VOP3 (`_e64`), as the carry-out operations above with the carry or borrow of each lane read from a lane mask. The add computes `src0 + src1 + carry` and writes 1 when the 33-bit sum does not fit in 32 bits; `v_sub_co_ci_u32` computes `src0 - src1 - borrow` and writes 1 when `src1 + borrow > src0` (unsigned); `v_subrev_co_ci_u32` computes `src1 - src0 - borrow` and writes 1 when `src0 + borrow > src1`. The lowering keeps both steps in 32-bit unsigned arithmetic: the add carries when either step wraps, and a subtract borrows when the subtrahend exceeds the minuend or the borrow-in exceeds the partial difference. The source is again the LLVM 15 AMDGPU backend, read at tag `llvmorg-15.0.7`: it selects `V_ADDC_U32_e64` for `ISD::ADDCARRY` and `V_SUBB_U32_e64` for `ISD::SUBCARRY` (`AMDGPUISelDAGToDAG.cpp`, `SelectAddcSubb`), the multiple-precision add and subtract with carry or borrow in and out; it defines `V_SUBBREV_U32` with `v_subb_u32` as its reversed-operand counterpart (`VOP2Instructions.td`); and LLVM 15 prints the three on gfx10 as `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32`. The semantics are not checked against the ISA document here and not measured on a console. LLVM 15 prints both encodings with their suffix, so only those spellings are accepted. The `_e32` form reads and writes `vcc` or `vcc_lo` and takes a VGPR as `src1`; the `_e64` form names both masks, each `vcc`, `vcc_lo`, one SGPR or an SGPR pair, and both must have the same width. Each source is a register, an inline constant or a literal. The carry-in must be a per-lane condition the translator tracks, written by a comparison or a carry-out, exactly as for `v_cndmask_b32`, and the carry-out replaces the condition in its mask. The forms without a suffix, ` clamp`, a float modifier, `exec` or a VGPR as either mask, an `_e32` form with another mask or an SGPR `src1`, masks of different widths, a carry-in that no instruction wrote or that holds a constant, a missing or extra operand, an unwritten register, and the DPP and SDWA forms are refused. Three programs, one per operation, export through the `R32G32B32A32_UINT` readback target and are compared bit for bit. Each takes A, B, C and D from the constants, computes the carry-out form of the same operation on (A, B) into `vcc_lo` and on (A, D) into `s60`, then op(C, D, `vcc_lo`) in the `_e32` encoding and op(D, C, `s60`) in the `_e64` encoding with its carry-out in `s61`. Two `v_cndmask_b32_e64` selects turn the carry-outs into 0.5 or 1.0, and 2.0 (0x40000000) is added to both results, a bijection modulo 2^32 that moves the all-ones word of a borrow taken from the borrow-in alone to a normal number. Each operation runs on four rows: both carry-ins set with both carry-outs coming from the carry-in alone (C + D is 0xffffffff, or C = D), both carry-ins clear with a carry or borrow from the operands, and one row each with only `vcc_lo` or only `s60` set. Each carry-in and each carry-out takes both states, and every input and every exported word is a normal binary32 or zero, which the test asserts. Twenty-seven wrong references, each replacing one channel of one row, must report `pixel_mismatch`: a dropped carry-in or borrow-in, a carry-in read as set, a carry-out or borrow-out without the carry-in term on each mask, a dropped carry-out of the operands, the carry-in of one encoding read from the other's mask, subtract for add, add for subtract, a borrow-in added, reversed operands, and the borrow-out of the other operand order. That is 39 draws from 3 compiles and 3 renderer launches. As a check of the fixture, dropping the `{r} < {p}` term from the add's carry-out in `tools/pixel_aot.py` makes the first row mismatch on WARP. They run as their own tests, `pixel_aot_carry_in_hardware` and `pixel_aot_carry_in_warp` (`tests/pixel_aot_check.py draw-carry-in`), with their own coverage record, and the LLVM 15 round trip covers the three programs. They passed on the NVIDIA GeForce RTX 5080 (driver 32.0.16.2124), on the AMD Radeon(TM) Graphics iGPU (vendor 1002, device 13c0, driver 32.0.11034.2, selected with `XBOX2WINDOWS_ADAPTER=Radeon`) and on WARP (Microsoft Basic Render Driver 10.0.26100.9818), Windows 11 (build 26300), with the debug layer unavailable. They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_carry_in_' -V`. The 64-bit multiply-adds `v_mad_u64_u32` and `v_mad_i64_i32` lower as `D = S0 * S1 + S2` modulo 2^64 with two 32-bit factors and a 64-bit `S2`, written to a VGPR pair `v[d:d+1]`. The product is built from `a * b` and the `mul_hi_u32` or `mul_hi_i32` helper of the scalar multiply-high, the add runs on two `uint` words with the carry of the low word added to the high word, and no 64-bit HLSL type is used. The unsigned form zero-extends the factors and writes the carry-out of the 64-bit add (the high-word step wraps) to the lane mask, tracked like a comparison result so that `v_cndmask_b32` can read it. The semantics come from LLVM 15 `VOP3Instructions.td`, which defines both (VOP3B opcodes 374 and 375, as in `tools/disasm_rdna2.py`) as `VOP3b_I64_I1_I32_I32_I64`: a 64-bit result and a one-bit carry-out per lane; they are not checked against the ISA document here and not measured on a console. The carry-out of the signed form is not established here, so the translator has no mask for it: the signed form is accepted only with the discarding `null` destination, which LLVM 15 assembles, and any other destination is refused, so a later read of a mask the signed form seems to have written is refused as an unwritten register. The mask of the unsigned form is `vcc`, `vcc_lo`, one SGPR or an SGPR pair; `null` there is refused. `S0` and `S1` take a register, an inline constant or a literal; `S2` takes a VGPR pair, an aligned SGPR pair or an inline constant from -16 to 64, sign-extended to 64 bits. Unaligned VGPR pairs are accepted because LLVM 15 assembles them (hardware legality is assumed, not measured). A literal `S2`, ` clamp`, any operand modifier, an output modifier, an `_e64` suffix, a destination or `S2` that is not a two-register VGPR range, a mask of the wrong width or alignment, an unwritten register and DPP controls are refused. Four programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit: `u64_pair` (VGPR-pair `S2` with its carry in `vcc_lo`, and an inline -1 `S2` with its carry in `s60`), `u64_mixed` (SGPR-pair `S2`, an inline factor 3 and an unaligned destination), `i64_pair` and `i64_mixed` (the same for the signed form, with an inline -1 and -3). The unsigned rows cover a carry out of the high word with both factors above 2^31, a carry from the low into the high word without a carry out, a sum that wraps to exactly zero and carries, a zero `S2` and a zero factor; the signed rows cover negative times positive, negative times negative with a negative `S2`, and positive times positive with a negative `S2`. Every input and every exported word is a normal binary32 or zero, which the test asserts. Twenty-three wrong references, each replacing one channel of one row, must report `pixel_mismatch`: the signed product for the unsigned form and the unsigned product for the signed form, a dropped `S2`, a dropped carry-out, a carry-out on a low-to-high carry only, a dropped low-word carry, a dropped carry when the sum wraps to zero, a wrong carry of the inline -1 on a non-zero and a zero product, a zero-extended inline -1 and -3, an inline 3 read as 1 and an inline -3 read as 3, and a dropped high word of `S2`. They run as their own tests, `pixel_aot_mad64_hardware` and `pixel_aot_mad64_warp` (`tests/pixel_aot_check.py draw-mad64`), with their own coverage record, and the LLVM 15 round trip covers the four programs. They passed on the NVIDIA GeForce RTX 3080 (driver 32.0.16.2124) and on WARP (Microsoft Basic Render Driver 10.0.26100.9818), Windows 11 (build 26200). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_mad64_' -V`. +For the wave64 skipped-block liveness proof, an unsigned VOP3B carry-out with `vcc_lo` may also write `vcc_hi`; a discarded carry does not invalidate either half. The signed form's admitted `null` destination is unchanged. `startup_gfx2hlsl_mad64_check.py` verifies these effects and the clear-fact transfer at a skipped-block join. + The exact conversions `v_cvt_f64_i32` and `v_cvt_f64_u32` lower as the binary64 value of a 32-bit signed or unsigned integer, written to a VGPR pair `v[d:d+1]` (low word in `v[d]`, high word in `v[d+1]`). Every 32-bit integer is exactly representable in binary64, so there is no rounding and no dependence on a rounding mode. The translator builds both words from `uint` operations and uses no `double` and no `asdouble`: the sign (bit 31 of the signed form, zero otherwise), the magnitude, an exponent of 1023 plus the index of the highest set bit, and the bits below it shifted to the top of the 52-bit fraction. Zero gives +0.0 (both words 0) and `INT_MIN` gives `0xc1e00000_00000000`. The shader therefore needs no double-precision capability, and the draw tests have no capability skip for it (the WARP fault on double comparisons noted for `v_div_fmas_f32` is not reachable). The semantics come from LLVM 15 `VOP1Instructions.td` (`v_cvt_f64_i32` and `v_cvt_f64_u32` are VOP1 with a 64-bit result and a 32-bit integer source); they are not checked against the ISA document here and not measured on a console. LLVM 15 prints the unmodified VOP1 form with the `_e32` suffix and accepts it without; both spellings are lowered, with a VGPR, SGPR, inline-constant or literal source. An `_e64` suffix (with or without modifiers), ` clamp`, an output modifier, DPP, SDWA, a destination that is not a two-register VGPR range (one register, a reversed or three-register range, an SGPR range, a pair that ends above v255), a source that is not one dword or an untracked register, and any use inside a masked region are refused. LLVM 15 itself does not assemble `-v` or `|v|` on the integer source; the translator refuses those spellings as well. The translator tracks the pair as two ordinary numeric words (`alul` and `aluh`): a later integer or binary32 instruction that reads one word, such as `v_add_f32`, still lowers and sees the raw word, and `v_mad_u64_u32` may take the pair as its `S2`. A supported binary64 comparison can consume the pair directly. Binary64 arithmetic and conversions back to binary32 or an integer remain unsupported. Four programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit with Python's own `struct.pack('> 16`, `B >> 12` and the arithmetic `B >> 16` in the shader and packs those with A, a literal 0x12345 and an inline -16. A word whose high half saturates is not a normal binary32, so those channels are exported through an xor with 0x40000000. Each program runs on two rows. In the first row A is positive and B negative: the unsigned pack must turn the literal, `B >> 12`, A and the negative arithmetic shift into 0xffff, and the signed pack must turn A and the zero-extended `B >> 16` into 0x7fff and keep the inline -16 as 0xfff0. In the second row A is negative, which the signed pack turns into 0x8000, and `B >> 12` is 0xfff, which both packs keep. Every input and every expected result is a normal binary32 or zero, which the test asserts. Fifteen wrong references, each replacing one channel on the first row, must report `pixel_mismatch`: truncation instead of saturation in either half, swapped halves, the signed bound on the unsigned pack and the reverse, a negative source clamped to zero or kept, a value above 32767 kept, and the inline constant read as unsigned. That is 19 draws from 2 compiles and 2 renderer launches. They run as their own tests, `pixel_aot_pack_int16_hardware` and `pixel_aot_pack_int16_warp` (`tests/pixel_aot_check.py draw-pack-int16`), with their own coverage record, and the LLVM 15 round trip covers both programs; LLVM 15 prints the two instructions without an encoding suffix. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. +`v_cvt_pk_u16_u32` and `v_cvt_pk_i16_i32` lower through the integer table as two-source operations that exist in the VOP3 encoding only on gfx10. The AMD RDNA 2 ISA reference (30 November 2020, VOP3 opcodes 874 and 875) gives the layout: `D.u16_lo = u32_to_u16(S0.u32); D.u16_hi = u32_to_u16(S1.u32)` and `D.i16_lo = i32_to_i16(S0.i32); D.i16_hi = i32_to_i16(S1.i32)`, so src0 is the low half and src1 the high half. Neither that document nor the RDNA 3.5 reference defines `u32_to_u16` or `i32_to_i16`, and LLVM 15 gives the instructions no meaning beyond their types (`VOP_V2I16_I32_I32`, selected only from the `llvm.amdgcn.cvt.pk.u16` and `llvm.amdgcn.cvt.pk.i16` intrinsics). The saturation used here is the one Mesa states: its NIR operations `pack_uint_2x16` and `pack_sint_2x16` are documented as "Convert two unsigned integers into a packed unsigned short (clamp is applied)" and the signed counterpart, their constant folding clamps each source to 0..65535 or to -32768..32767, and the ACO backend selects exactly these two instructions for them with no clamp of its own. That is a statement by the open source driver for this hardware family, not by the ISA document, and it is not measured on the console. The lowering is `min(S0, 65535) | (min(S1, 65535) << 16)` on unsigned words, and the signed form clamps each source as a signed word and keeps its low 16 bits. The e32 spelling (gfx10 has none), ` clamp`, a float modifier, a wrong operand count, an unwritten register, a literal wider than 32 bits and the SDWA spelling are refused. The float packs `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32`, `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` and `v_cvt_pk_u8_f32` stay unsupported in `pixel_aot`; for direct DXIL, `v_cvt_pknorm_i16_f32` and `v_cvt_pknorm_u16_f32` lower under an unmeasured single-rounding RNE model (`clamp(x) * 32767` / `* 65535`, `NaN -> 0`; see [native-cvt-pknorm-f32.md](experiments/native-cvt-pknorm-f32.md)), while RDNA 2 silicon probing remains open. Two programs export through the `R32G32B32A32_UINT` readback target and are compared bit for bit, with A and B taken from constants s44 and s45. A normal binary32 word is outside both 16-bit ranges, so each program first derives `B >> 16`, `B >> 12` and the arithmetic `B >> 16` in the shader and packs those with A, a literal 0x12345 and an inline -16. A word whose high half saturates is not a normal binary32, so those channels are exported through an xor with 0x40000000. Each program runs on two rows. In the first row A is positive and B negative: the unsigned pack must turn the literal, `B >> 12`, A and the negative arithmetic shift into 0xffff, and the signed pack must turn A and the zero-extended `B >> 16` into 0x7fff and keep the inline -16 as 0xfff0. In the second row A is negative, which the signed pack turns into 0x8000, and `B >> 12` is 0xfff, which both packs keep. Every input and every expected result is a normal binary32 or zero, which the test asserts. Fifteen wrong references, each replacing one channel on the first row, must report `pixel_mismatch`: truncation instead of saturation in either half, swapped halves, the signed bound on the unsigned pack and the reverse, a negative source clamped to zero or kept, a value above 32767 kept, and the inline constant read as unsigned. That is 19 draws from 2 compiles and 2 renderer launches. They run as their own tests, `pixel_aot_pack_int16_hardware` and `pixel_aot_pack_int16_warp` (`tests/pixel_aot_check.py draw-pack-int16`), with their own coverage record, and the LLVM 15 round trip covers both programs; LLVM 15 prints the two instructions without an encoding suffix. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operations on desktop GPUs, not that the console does. `v_pack_b32_f16` lowers through the integer table as a two-source operation that exists in the VOP3OpSel encoding only on gfx10. The AMD RDNA ISA reference gives `D[15:0].f16 = S0.f16; D[31:16].f16 = S1.f16`: each source's low binary16 encoding is copied into its half of the destination with no conversion, rounding or NaN handling, so the lowering is `(S0 & 0xffff) | ((S1 & 0xffff) << 16)` on the raw words. LLVM 15 prints the gfx1013 form without a suffix, and `tools/ffx_dispatch_aot.py` already lowers the same mnemonic with this expression. The e32 spelling (gfx10 has none), ` clamp`, ` op_sel` (only the default `[0,0]` shape is modelled), a float modifier, a wrong operand count, an unwritten or out-of-range register, a literal wider than 32 bits and the SDWA spelling are refused; sources go through the existing integer operand rules, so an outstanding sample is refused as well. An inline float constant is the exception: `llvm-mc` types these sources as binary16 and prints the constant as a decimal float, and its binary16 encoding is used (`1.0` is `0x3c00`), as for the packed `VOP3P` forms (not measured on the console); any other decimal float is refused. One program exports through the `R32G32B32A32_UINT` readback target and is compared bit for bit, with A and B taken from constants s44 and s45, copied to v18 and v19 and carrying the distinct noisy upper halves 0xa5a5 and 0x5a5a. Three packs read A and B as register/register, SGPR/register and register/SGPR; a fourth writes back to v18, its own src0, so a lowering that writes the destination before reading src0 differs. Five rows vary the low halves: an asymmetric pair for the controls, a quiet NaN half, a signed-zero half, a NaN half in src1 (which lands in bits 31:16 but still yields a normal binary32 word) and two zero halves, which must give zero. Every input and every expected word is a normal binary32 or zero, which the test asserts; the NaN and signed-zero half patterns are copied as bits with no quieting or conversion and stay in the low halves of the packed words. Five wrong references, each replacing one channel of the first row, must report `pixel_mismatch`: swapped halves, src0's high half leaked into the low half, src0 taken from bits 31:16, src1 placed in the low half, and src0 read after the in-place destination write. The tests run as `pixel_aot_pack_b32_hardware` and `pixel_aot_pack_b32_warp` (`tests/pixel_aot_check.py draw-pack-b32`), with their own coverage record, and the LLVM 15 round trip covers the program. They passed on the NVIDIA GeForce RTX 3060 (driver 32.0.15.9636) and on WARP (Microsoft Basic Render Driver 10.0.19041.5794), Windows 10 (10.0.19045.6466). They show that the translated shader computes the stated operation on desktop GPUs, not that the console does. The inline-constant variant also goes through the LLVM 15 round trip. Its integer render target compares 0xc0003c00 with the old binary32-low-half result 0xc0000000, which must report a mismatch on each desktop backend. @@ -8578,19 +9266,19 @@ On Windows build 26200, the pre-executable inventory covered 16 package DLLs and ## Heap and process memory -`src/era_heap.cpp` is a desktop handler. It splits the attribute word using SlimEra's Xbox One ERA layout: object type in bits 0–13, page size in bits 14–15, allocator ID in bits 16–23, log2 alignment in bits 24–28, memory type in bits 29–32 and reserved bits 33–63. Object type and allocator ID are carried as tags and do not affect placement, as in SlimEra's default heap. +`src/era_heap.cpp` now decodes the GDK 261000 XALLOC_ATTRIBUTES layout: object type in bits 0–13, page size in bits 14–15, allocator ID in bits 16–23, log2 alignment in bits 24–28, memory type in bits 29–32, an address-below-4-GiB bit at 33 and 30 reserved bits at 34–63. Object type and allocator ID are carried as tags and do not affect placement. The earlier desktop experiments compared the handler with SlimEra's Xbox One ERA layout, which treated bits 33–63 as reserved; those observations stay scoped to that historical layout. The desktop handling is: - **Heap (memory type 0):** served from the CRT heap at the requested alignment, minimum 16 bytes, and zero-filled. The page size does not affect these requests. SlimEra passes every heap request to `_aligned_malloc`, which commits the alignment padding as heap memory, so a 257-byte request with exponent 31 would commit more than 2 GiB. The desktop handler instead gives alignments above the page size their own reservation and commits only the pages that hold the payload; `VirtualAlloc` returns them zeroed. - **Graphics (memory types 1–6):** committed as a separate `VirtualAlloc` region. `release_with_attributes` frees it with `VirtualFree`. The region starts on the desktop allocation granularity, which covers 4 KB and 64 KB pages. This is ordinary CPU-visible memory; no GPU mapping or caching behavior is modeled. -- **Rejected:** physical memory types 7–9, undefined types 10–15, the undefined page-size value 3, reserved bits, and graphics requests whose page size or alignment exceeds the allocation granularity all return a null pointer. +- **Rejected:** physical memory types 7–9, undefined types 10–15, the undefined page-size value 3, the 30 reserved bits (34–63), the address-below-4-GiB bit (33), and graphics requests whose page size or alignment exceeds the allocation granularity all return a null pointer. A below-4-GiB request stays refused until the allocator can provide such an address. `release` frees heap allocations. It frees a page-backed block with `VirtualFree` when `VirtualQuery` reports it as the base of its own allocation; a CRT block never is, because `_aligned_malloc` stores its base pointer below the returned address. `release_with_attributes` takes the allocation's attribute word, as `XMemFree` callers do. -What is measured is the desktop behavior above. Under the ERA layout, the two recorded words give alignments that match their callers' own arithmetic: 32 bytes for Bink and 256 bytes for AMD. The following remain unconfirmed on Scarlett: +What is measured is the desktop behavior above. Under the 261000 layout, the two recorded words give alignments that match their callers' own arithmetic: 32 bytes for Bink and 256 bytes for AMD. The recorded words leave bit 33 and the 30 reserved bits at zero, so they do not by themselves distinguish the 261000 layout from the older SlimEra interpretation. The following remain unconfirmed on Scarlett: -- that Scarlett uses the ERA layout at all; +- whether the title's attribute words use the 261000 contract beyond the zero bits observed here; - what allocator ID `0xe5` means; - the GPU visibility and caching of memory type 5 and the other graphics types; - the console's error conventions. @@ -8600,14 +9288,14 @@ What is measured is the desktop behavior above. Under the ERA layout, the two re | CTest case | Inputs and checks | |---|---| | `era_heap_allocation` | Allocate 257 bytes using six alignment exponents. Check alignment of at least 16 bytes and the requested alignment, initial zeroing, writes and release. Debug builds also compare CRT heap snapshots. | -| `era_heap_failure` | Each reserved bit, combined with a heap alignment and with the AMD graphics word, returns a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 4 MB pages or a 128 KiB alignment, zero size and excessive size. | +| `era_heap_failure` | Each of the 30 reserved bits (34–63) and the address-below-4-GiB bit at 33, combined with a heap alignment and with the AMD graphics word, return a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 2 MB pages or a 128 KiB alignment, zero size and excessive size. | | `era_heap_reuse` | For three alignment exponents and three sizes, fill a block with `0xa5` and release it. Then hold up to 32 new blocks of the same shape until the released address returns. Every new block must read as zero. The output reports `recycled_address`, the number of the nine cases in which the CRT returned the dirty address. glibc returned all nine in a Linux build with a `posix_memalign` stand-in. Windows 11 build 26200.9974 with MSVC 14.44.35207 returned the dirty address in all nine cases in both Debug and Release. Low-fragmentation heap randomization can lower it. | -| `era_heap_observed_words` | Desktop handling of the two recorded words. Under the ERA layout, the Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | +| `era_heap_observed_words` | Desktop handling of the two recorded words. The words were measured under the older SlimEra interpretation and leave bit 33 and the 30 reserved bits at 0, so they do not distinguish the two layouts. The Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | | `era_heap_large_alignment` | Exponents 13, 16, 17, 20 and 31 with sizes of 1 and 257 bytes, one page, one page plus one byte and three pages minus one byte. Each block must be aligned and zeroed. `VirtualQuery` must report the block as the base of its own private read/write allocation, with a committed region equal to the payload rounded up to whole pages. After release the address must be `MEM_FREE`. The output reports the 25 cases, the committed bytes and the summed alignments. With the previous `_aligned_malloc` path, the first case already fails because the block lies inside a CRT heap allocation. | -| `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 4 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | +| `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 2 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | | `era_heap_concurrency` | Four threads run 100 rounds each. They hold simultaneous allocations, write distinct values, compare every byte and release the memory. | | `era_heap_caller_layout` | Owned desktop storage covers all 32 base residues at eight payload sizes. Each Bink-style wrapper recovers its original base after a payload write and preserves the surrounding guard bytes. Ten AMD-style requests check 256-byte size rounding and the unused tail. These cases establish caller-side arithmetic. The Bink-style storage uses the recorded Bink word. | -| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf` and 31 reserved bits. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type and the reserved bits at 0. So without this scenario, a 12-bit object-type mask and a reserved field taken from bit 32 both decoded them unchanged and passed every other scenario. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. | +| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf`, the address-below-4-GiB bit at 33 and the 30 reserved bits at 34–63. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type, the address bit and the reserved bits at 0. Without this scenario, a 12-bit object-type mask would decode the widest object type unchanged; the all-ones word and the address-bit case also distinguish the 30-bit reserved field from one that includes bit 33. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. A word with bit 33 set is still refused by the allocator because it does not provide an address below 4 GiB. | `desktop_memory_query` supplies Windows observations for `XMemVirtualQuery` and `XMemGetWorkingSetStatistics`. The test reserves memory, commits and writes 1,024 pages, checks the read-only/writable boundary, then decommits. It verifies residency of a locked page and records working set, peak working set and private commit at three points. Values vary between runs. Scarlett structure layout, units and accounting scope remain unconfirmed. [Windows working sets](https://learn.microsoft.com/en-us/windows/win32/memory/working-set) @@ -8675,6 +9363,93 @@ python3 -B tests/pixel_compare_sample_check.py binary llvm-mc-15 llvm-objcopy-15 ctest --preset dev --no-tests=error -R '^pixel_aot_compare_sample_(warp|hardware)$' -V ``` +### gfx1030 2D comparison sample LOD and bias + +`image_sample_c_l` and `image_sample_c_l_o` lower to `SampleCmpLevel`. +`image_sample_c_b` and `image_sample_c_b_o` lower to `SampleCmpBias`. +The forms accept a contiguous sequence of full-width address VGPRs with an +optional packed XY offset, an instruction bias for `_b`, the reference, U and V, +and an explicit LOD for `_l`. Bias and LOD each accept binary32 `+0.0` and `1.0` +when known statically. The bias forms require whole-quad UVs. The matching +comparison sampler uses point XY and mip filtering, clamp-to-edge addressing, +`MIN_LOD = 0`, `MAX_LOD = 1`, and no sampler LOD bias. Bind a 2D R32_FLOAT view +with both mips visible and a desktop comparison sampler with the same LOD range. +The forms use `dmask:0x1` and the existing reference range, offset and wait rules. + +The synthetic fixture uses different depth patterns in its 8×8 and 4×4 mips. +It draws at 8×8 and 16×16 with a mip-zero footprint of one texel per pixel, so +explicit LOD 1 and instruction bias +1 each select the second mip. A CPU model +predicts all RGBA values, including where the signed offset `(1, -2)` clamps to +an edge. Zeroing the LOD or bias selects mip zero. Zeroing the offset changes the +lookup in mip one. Each mutated draw must match its own full CPU reference and +first differ from the original reference at the predicted pixel and values. + +LLVM 15 assembles and disassembles the four forms and checks that the container +CLI emits the same HLSL as the text path. The optional `compile` command runs +DXC and computes the expected first differences on the CPU. + +```sh +python3 -B tests/pixel_compare_lod_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +```powershell +python -B tests/pixel_compare_lod_check.py compile level dxc +python -B tests/pixel_compare_lod_check.py compile bias dxc +ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_compare_lod_(level|bias)_(warp|hardware)$' -V +``` + +The Level tests require PS 6.7 and `AdvancedTextureOpsSupported`. The Bias tests +require PS 6.8 and `SampleCmpGradientAndBiasSupported`. The renderer uses the +Windows SDK 10.0.26100 headers for these capability queries. CTest reports an +unsupported profile, SDK header set or device capability as a skip (77). +Intel Arc B390 and WARP passed the Level tests. WARP passed the Bias tests. +Arc B390 reported the Bias capability unavailable and skipped those tests. + +### gfx1030 2D comparison sample gradients + +`image_sample_c_d`, `image_sample_c_d_o`, `image_sample_c_d_g16`, and +`image_sample_c_d_o_g16` lower to `SampleCmpGrad` for a 2D `R32_FLOAT` view +with two visible mips and `dmask:0x1`. The contiguous address starts with the +optional packed signed XY offset, then the comparison reference, the explicit +gradients in `(du/dx, dv/dx, du/dy, dv/dy)` order, and the full-width UV pair. +G16 packs each gradient vector as two binary16 components with U in the low +half and V in the high half. The gradient inputs must be statically known +normal values or zero in their input precision. The explicit gradients do not +require whole-quad UV provenance. The comparison sampler uses point XY and +mip filtering, clamp-to-edge addressing, `MIN_LOD = 0`, `MAX_LOD = 1`, and no +sampler LOD bias. Bind the same range on the desktop comparison sampler. + +The depth fixture compares every RGBA pixel at 8×8 and 16×16 against the CPU +reference. A horizontal V slope of −1/4 at 8×8 and a vertical U slope of +1/4 +at 16×16 each select mip one. Zeroing the active slope selects mip zero. In +the offset forms, replacing `(1, -2)` with `(0, 0)` changes the taps in mip one. +Each mutation must match its complete CPU reference and first differ from the +original at the predicted pixel and values. The fixture measures these whole +mip choices and leaves fractional LOD transitions unmeasured. + +LLVM 15 code generation checks the comparison reference, optional offset and +gradient order for all four encodings, including the two distinct G16 packed +words. LLVM MC, the disassembler and the container CLI check the end-to-end +machine-code path. The GLSL `sampler2DShadow` check validates the explicit +reference and `Grad` or `Grad|ConstOffset` operands in SPIR-V. The DXC compile +check verifies four distinct gradient components in the emitted DXIL call. + +```sh +python3 -B tests/pixel_compare_grad_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 llc-15 +python3 -B tests/pixel_compare_grad_check.py glsl glslangValidator spirv-val spirv-dis +``` + +```powershell +python -B tests/pixel_compare_grad_check.py compile dxc +ctest --preset dev --no-tests=error -j 1 -R '^pixel_aot_compare_grad_(warp|hardware)$' -V +``` + +The draw requires PS 6.8 and `D3D12_OPTIONS21.SampleCmpGradientAndBiasSupported`. +An unsupported shader profile or missing SDK or device capability produces a +capability skip (77). WARP passed readback for all four forms. Intel Arc B390 +reported the comparison gradient capability unavailable and skipped the test. +Physical GPU readback requires an adapter that reports this capability. + ### Desktop xmem.dll `src/xmem_shim.cpp` builds `xmem.dll`, which exports the four functions the package DLLs import by name. The call shapes come from the observed call sites, not from a published header: @@ -9109,6 +9884,111 @@ cmake --build --preset dev --target startup_indirect_dispatch ctest --preset dev --no-tests=error -R '^startup_indirect_count_(warp|hardware)$' -V ``` +On a multi-GPU system, set `$env:XBOX2WINDOWS_ADAPTER` to a case-insensitive part of the hardware +adapter's name, then run `startup_indirect_count_hardware`. The fixture prints the selected adapter, +driver, GPU-written count and fenced result. An unmatched or overlong hardware selector fails the test. + +#### Batched indirect Dispatch on RDNA 1 + +On an AMD Radeon RX 5700 XT (RDNA 1, vendor `1002`, device `731f`), Windows 11 +build 26200.9974, debug layer unavailable, desktop `ExecuteIndirect` with a +12-byte Dispatch signature runs exactly one command whatever its +`MaxCommandCount`, with or without a count buffer. A standalone D3D12 program +without the shim ran three records `(2,1,1)`, `(1,2,1)`, `(1,1,3)` and got only +the first one's groups. This held for the direct and compute queues, a root UAV +and a descriptor table, `numthreads(1,1,1)` and `(64,1,1)`, records of 64 +groups, arguments in a DEFAULT or UPLOAD heap, a count buffer in the argument +buffer or apart from it, and strides of 12 and 16. A single-command call also +ignores its count buffer: a count word of 0 still ran the record. Three +single-command calls without a count buffer were exact. WARP 10.0.26100.9818 +was exact in every case. Drivers 32.0.21045.29003, 32.0.21045.16010, +32.0.21025.10016, 32.0.12033.1030 and 31.0.23013.1023 (Adrenalin 26.11.2 back +to 23.12.1) behave the same. On the issue, an NVIDIA GeForce RTX 4060 +(32.0.15.9579), an Intel UHD Graphics 770 (32.0.101.5973) and WARP +10.0.26100.9711 matched all nine standalone variants. No second RDNA 1 adapter +has been measured, and the cause is not established. +[Report](https://github.com/R0Y00/Xbox2Windows/issues/2626) + +With `X2W_SPLIT_INDIRECT_DISPATCH=1`, slot 61 splits a batched or counted +Dispatch ([`split_indirect_dispatch.h`](../src/startup_stubs/split_indirect_dispatch.h)). +It is opt-in: without the variable the native call runs on every adapter, +RDNA 1 included, until a second RDNA 1 adapter has been measured. It applies +only to a rootless Dispatch signature with a desktop compute pipeline and root; +the translated compute path and the other indirect command kinds are +unchanged. The count word and the records are copied into a scratch buffer. A +compute pass rewrites record `i` as itself while `i < min(count, MaxCommandCount)` +and as `(0,0,0)` otherwise. `MaxCommandCount` single-command calls without a +count buffer then read the rewritten records. + +The pass replaces the compute root and pipeline. The compute state a title can +set on the desktop list is the pipeline (slot 25), the root (slot 33) and root +SRVs (slot 43); the other compute root setters are not forwarded. The split +sets the pipeline again, and `restore_compute_root` sets the root with every +view recorded by `bind_compute_root_view`. The indexed-draw validation pass +uses the same restore. Slot 43 records its root SRVs through +`bind_compute_root_view`. The fixture's result UAV is a desktop address that no +guest slot can bind, so the fixture binds it through the export +`x2w_d3d12_fixture_compute_root_uav`, which records it through the same +function. A UAV bound on the desktop list directly is lost after the split: in +an earlier fixture that did so, the split left the result at its sentinel. + +The scratch is kept with the recording's desktop allocator +(`x2w_d3d12_recording_scratches` reports how many it holds) and is released +only when that allocator is reset after every queue that ran it has passed its +fence. The rewrite's root signature and pipeline are kept for the life of the +process in an instance that is never destroyed. In #2683 the instance was a +function-local static: on an RX 9070 XT (driver 32.0.32029.2010) its destructor +released the pipeline during DLL detach and the process exited with 0xC0000409 +in `amdxc64.dll` after every readback had passed. A never-destroyed instance +exited 0 in 3 of 3 runs there. +[Review](https://github.com/R0Y00/Xbox2Windows/pull/2683) +On the same adapter and driver, with this change merged onto main, +`startup_indirect_count_split_hardware` passed and 6 of 6 direct runs exited 0; +with only `split_indirect_dispatch.h` restored to the static, 4 of 4 runs ended +in 0xC0000409, the dump showing the static's destructor in +`_execute_onexit_table` at DLL detach. +[Measurement](https://github.com/R0Y00/Xbox2Windows/pull/2734) + +The cache is process-owned and released only by process exit. Explicitly +unloading and reloading `d3d12_xs.dll` in a live host is not a supported path: +each load allocates a new cache and nothing tears the previous one down outside +the loader lock. Supporting it needs that teardown and its own coverage. The +kept root signature and pipeline each hold a reference to their device: on the +RX 5700 XT and WARP 10.0.26100.9818 the device count went from 1 to 3 with both +objects created, and stayed at 2 after the application released its own +reference. So a cached device is never destroyed, and `entry_for`, which matches +devices by pointer, cannot see a new device at a reused address while an entry +holds those objects. An entry whose build failed holds neither. + +`startup_indirect_count_(warp|hardware)` keep the native call. On the RX 5700 +XT (driver 32.0.21045.29003) the hardware test still fails at its first case +(`result=0x31415929`, expected `0x31415935`), which shows the driver behavior. +`startup_indirect_count_split_(warp|hardware)` run the same fixture with the +split on. Each case checks the whole readback, sentinel and guard included: + +- GPU-written counts 2, 9 (above the maximum of 3), 0, 1 and 3; a zero count + leaves the result at its sentinel; +- an omitted writer, no count buffer, and the five refusals; +- a follow-up `Dispatch(1, 1, 2)` recorded on the desktop list after the split, + which adds 102 only if the consumer pipeline, its compute root and the result + UAV are still bound; +- the scratch count after Close (one per accepted call with the split on, none + otherwise); +- a submission through a guest queue that waits on a gate fence. The guest + allocator is reset while the work is pending, the recording must still hold + its scratch, and after the gate opens the records produce the count-2 result. + +Both pass on WARP 10.0.26100.9818 and the RX 5700 XT. Two local controls, not +committed, each failed both: skipping `restore_compute_root` after the pass +(first case, `result=0x31415926`, expected `0x31415935`), and not retaining the +scratch with the recording ("recording holds 0 split scratch buffers after +Close, expected 1"). + +```powershell +cmake --build --preset dev --target startup_indirect_dispatch +ctest --preset dev --no-tests=error -R '^startup_indirect_count(_split)?_(warp|hardware)$' -V +``` + #### Root constants in an indirect dispatch signature Device slot 41 also accepts a compute signature with a root signature, whose @@ -9468,11 +10348,23 @@ stores the primitive and vertex counts, every wave passes a barrier, wave 0 sends one allocation request and the other wave reads the counts back; the code around it exports vertex and primitive `thread` under `count > thread`. `mesh_skeleton` in `tools/startup/gfx2hlsl.py` states -the shape and refuses every other program with the first difference. The -lowering clamps both counts to the 128 threads of a group and each index to +the shape and refuses every other program with the first difference. Before +the count exchange, a full EXEC reset followed by +`v_cmpx_gt_u32_e32` or `v_cmpx_lt_u32_e32` may narrow EXEC. Only nops and waits +may separate the compare from an `s_cbranch_execz` to the first count barrier. +The compare accepts SGPRs, inline constants or literals, and VGPRs defined +for every lane. The skipped block allows nops, waits, clauses and +lane-predicated instructions without scalar or EXEC writes, and scalar ALU +whose SGPR results are not read from the count exchange on (SCC is rewritten by the exchange's +`s_cmp_eq_i32`). Both guest exchange paths replace the incoming mask before +lane-dependent work, so skipping per lane in HLSL has the same visible effects +as skipping per wave on the guest for any compare predicate. In HLSL thread 0 +stores both counts, every thread passes the group barrier, and full EXEC is +restored before exports. +The lowering clamps both counts to the 128 threads of a group and each index to the last vertex. It reads 9-bit indices, ignores the edge flags, and gives a primitive whose null bit (31) is set one vertex three times, so it covers no -pixel. A depth-only pixel program is refused. The source-built fixture draws +pixel. A depth-only pixel program is translated (see below). The source-built fixture draws on WARP and a hardware adapter and matches a CPU rasteriser. The runtime does not load the translated pair, so the dispatch stays unforwarded. @@ -9488,11 +10380,64 @@ The one-pixel negative control uses that same published pair. The translator also accepts the same slot 57 mesh shape with an empty `req_.ps57`. It emits the mesh stage alone, keeping position and -primitive exports, and records `ps none` in `.ms57.txt`. A null-export -depth-only pixel stage is still refused. Run +primitive exports, and records `ps none` in `.ms57.txt`. Run `python -B tests/startup_mesh57_skeleton_check.py` for the source and cache checks, or run the `startup_mesh57_skeleton` CTest checks below for the DXC mode. +A pixel stage whose only export is `exp null off, off, off, off done vm` (the +depth-only form of LLVM `SILateBranchLowering` and Mesa ACO +`create_fs_null_export`) is translated with the pair. The null target writes +no channel; when the stage narrowed EXEC first, as an alpha test does, the `vm` +flag keeps its `discard`. The pixel stage is emitted as `void main(PSIn i)` +with no `SV_Target`, and the manifest has an empty `targets` line instead of +`ps none`, because the stage still decides coverage. Run +`python -B tests/startup_mesh57_depth_only_check.py`: it checks the discard, +the empty `targets` line, a control without the EXEC narrowing (no discard) +and a null export followed by a position export (still refused). A slot 57 +pixel stage that has the null export next to an `mrt0`, `mrtz` or `param0` +export, in either order, is refused before any source or manifest is written; +the general pixel path keeps those mixed forms. + +One mixed form is accepted: the early exit of a kill. LLVM +`SILateBranchLowering` and Mesa ACO place it after the program's `s_endpgm`: +`exp null off, off, off, off done vm` then the final `s_endpgm`, and every +branch into the block enters with EXEC zero, so the export writes nothing +(`kill_exit_block` in `gfx2hlsl.py`). An entry is `s_cbranch_execz`, or the +demote form: `s_cbranch_scc0` directly after `s_cselect_b32 exec_lo, exec_lo, 0` +or `s_cselect_b64 exec, exec, 0`. `s_cselect` leaves SCC, so the taken branch +follows the select of 0; no branch may land on the `s_cbranch_scc0` itself. The +rest of the stage, here an `mrt0` export after the kill, is translated as usual +and keeps its `vm` discard. `startup_mesh57_depth_only_check.py` checks both +forms and refuses ten near misses with the mixed-export message: the colour +export falling through into the null export, a block no branch reaches, a block +entered by `s_branch`, an exit export without `vm`, another instruction in the +block, and for the demote form `s_cbranch_scc0` without the `s_cselect`, an +`s_cselect` that keeps EXEC, one into another register, an instruction between +the two, and `s_cbranch_scc1`. The +`startup_mesh57_skeleton_kill_exit_{warp,hardware}` CTest checks draw both +colour pairs with `offscreen_check --mesh-indexed`; lanes whose flat attribute 0 +red is at or below 0.5 are killed, so two of the four triangles are dropped. +Each draw must match the CPU rasteriser without them, and the same mesh with the +pixel stage that does not kill must differ at exactly the 115 killed pixels. +Nothing here shows that a runtime path loads the pair. + +The +`startup_mesh57_skeleton_depth_{warp,hardware}` CTest checks draw a +source-built depth-only pair (`v_interp_mov_f32`, `v_cmpx_lt_f32 0.5, v0`, +`exp null off, off, off, off done vm`, `s_endpgm`) twice with +`offscreen_check --mesh-depth-pair` into a D32 target cleared to the sentinel +1.0, depth test LESS. Colour must stay cleared and depth must match the CPU +rasteriser: of 259 covered pixels, 181 keep a written depth and 78 keep the +sentinel only because of the discard. A reference without the depth writes +(181 mismatches) and the same mesh with a null export that does not discard +(134 mismatches) must each fail. The offline check also refuses the drawn +stage with a colour export before its null export, a pair whose pixel stage +does not match its key, and the mesh shapes the paired path refuses next to +the depth-only pixel stage; it checks that `pending_keys` keeps +the pair pending until both `.ms57.cso` and `.ps57.cso` are complete. The +runtime does not load slot 57 results yet, so these draws are not submitted +through the guest path. + The pending scan checks the DXContainer header and file length for every required slot 57 bytecode artifact. A `ps none` result needs the mesh artifact only. A missing or truncated required artifact leaves the request pending @@ -9508,6 +10453,30 @@ and unproven wave masks remain unsupported. Use Append `draw ` for CPU-reference readback of the SCC paths and lane-masked if/else. +The `startup_mesh57_loop_refusal` check is a source-built program with the same +exchanges plus one deliberate back-edge after the count exchange +(`tests/startup_mesh57_loop_refusal.s`). Tip refuses it with +`slot 57 mesh: a loop outside the group-memory exchanges is not covered`. The +mutant replaces that back-edge with a second `s_nop` and must not stop on that +loop message. The oracle is an exact string match; a stub that only checks for +any `unsupported:` result would accept a wrong reason and is rejected by the +check. Host-only (no WARP/hardware draw). Run +`python -B tests/startup_mesh57_loop_refusal_check.py`, or the matching CTest. +The `startup_mesh57_loop` check is a source-built program with the same +exchanges plus one constant-trip scalar loop after the count exchange +(`tests/startup_mesh57_loop.s`: `s_mov_b32 s40, 0`, then four iterations of +`s_add_u32` / `s_cmp_lt_u32` / `s_cbranch_scc1`). `translate_mesh57` unrolls +the proven trip count and publishes `ms_6_5`; vertex red is 1.0 when the final +counter equals 4. Unsupported shapes still refuse with +`slot 57 mesh: a loop outside the group-memory exchanges is not covered`: an +unconditional back-edge, a data-dependent compare against a root constant, and +a loop body that writes EXEC. The once-through mutant replaces the back-edge +with `s_nop` so the counter stays 1 and red stays 0; the draw reference for the +constant-trip image must fail on that mutant. Run +`python -B tests/startup_mesh57_loop_check.py` on the host, and +`ctest --preset release --no-tests=error -j 1 -V -R '^startup_mesh57_loop_(warp|hardware)$'` +for WARP and hardware draws against the CPU rasteriser. + A forward `s_cbranch_vccz` or `s_cbranch_vccnz` can also branch on the lane's VCC bit when EXEC is full and every incoming path last wrote VCC with a full-EXEC `v_cmp_*` from wave-uniform SGPRs or constants. A compare with a @@ -9515,6 +10484,19 @@ VGPR source, a different VCC write, or a narrowed EXEC at the branch invalidates the proof. The CPU-reference draws cover both outcomes for each branch polarity and a VCC-zero branch after a join. +The `startup_mesh57_lane_spill_{warp,hardware}` tests cover the constant-lane +`v_writelane_b32` / `v_readlane_b32` spill idiom in `translate_mesh57` (#2413 T7). +A source-built program parks ordinary scalars in fixed wave64 lanes of a spill-only +VGPR (including lane 63), reloads them, and uses the colour reload as vertex red. +Raw `exec_lo` / `exec_hi` sources stay refused under the one-lane model. Host checks +also refuse an unwritten slot, a register-selected lane, lane 64, ordinary vector use +of the spill VGPR, and a spill into an exchange VGPR. The draw compares all 1,024 +pixels with a CPU rasterizer; zeroing the spilled colour assignment in HLSL (not the +multi-decl) must change the image. +Run `python -B tests/startup_mesh57_lane_spill_check.py` for host refusals, or +`ctest --preset release --no-tests=error -R '^startup_mesh57_lane_spill' -V` +for WARP and hardware. + The `startup_mesh57_skeleton_wave_shift_{warp,hardware}` tests cover a single `s_lshl_b32` behind a forward EXEC-zero branch after the count exchange. From full EXEC a compare selects the threads with index below an unsigned constant. @@ -9524,7 +10506,27 @@ vertex red. The draw checks a vertex in the upper half of a partially active wave and vertices in a second, empty wave that retain the previous value. It also compiles a per-lane branch and checks its different image. The proof requires a straight path from the count exchange and an immediate EXEC -restore. Scalar memory operations in the skipped region remain unsupported. +restore. + +Between the group-index and count exchanges, one forward EXEC-zero block can +contain a single `s_buffer_load_dword` whose SGPR result is live at the join. +Full EXEC followed by `v_cmpx_gt_u32_e32` must select the proven thread indices +below a wave-uniform SGPR bound. The translator evaluates +`(tid & ~63u) < bound` at the compare and branches around the load when the +guest wave is empty. A mixed wave gets the loaded word in every lane. Vector +instructions inside the block still follow per-lane EXEC. The proof requires a +wave-uniform address and a defined, wave-uniform previous value. It refuses +other scalar instructions inside the block, wider loads, non-buffer scalar +loads, stores, atomics and branches into the block. + +The slot 57 skeleton `draw` fixture uses bound 6 and vertices from threads 39 +and 5 in the mixed wave. Their flat red is 255, and only thread 5 gets green +255 from the lane-predicated write. The empty wave keeps red 64 and green 0. +Its byte address is 736, beyond the 512 bytes of input and the renderer's +80-byte trace padding. The CPU reference reads byte 480 +only for the mixed wave, reuses that word across its lanes, then rasterizes +the triangles. Swapping the two waves' red values in the reference must +change every covered pixel. The `startup_mesh57_formatted_load_{warp,hardware}` tests use one `buffer_load_format_x` to set vertex red. The fixture supplies descriptor word 3 @@ -9732,7 +10734,7 @@ Title memory follows XMem (`src/xmem_mapped_pages.cpp`). The section pool is one | Path | Backing | |---|---| | `share` | The pool is opened once as a heap: `OpenExistingHeapFromAddress` on a whole-pool view of the section, or on the allocation base for the private range (`OpenExistingHeapFromFileMapping` leaks Windows commit, #2234), after `D3D12_FEATURE_EXISTING_HEAPS`. A cross-adapter buffer is placed at the slot offset. Nothing is copied. | -| `copy` | A default buffer fed from a two-slot upload ring. The ring wraps like `reserve_upload_ring`, but refuses a slot whose fence has not completed (`DXGI_ERROR_WAS_STILL_DRAWING`). Title memory is copied into the ring at one named copy point: `bind` (as `upload_from_title`), `record` (as `frame_copy`) or `submit`, just before `ExecuteCommandLists`. The ring slot is copied into the buffer at the start of the submission. When a use declares GPU writes, the buffer is copied to readback at the end, and completion of that fence copies readback to title memory. | +| `copy` | A default buffer fed from a two-slot upload ring. The modeled ring wraps only after a slot's fence completes; otherwise it refuses (`DXGI_ERROR_WAS_STILL_DRAWING`). Title memory is copied into the ring at one named copy point: `bind` (as `upload_from_title`), `record` (as `frame_copy`) or `submit`, just before `ExecuteCommandLists`. The ring slot is copied into the buffer at the start of the submission. When a use declares GPU writes, the buffer is copied to readback at the end, and completion of that fence copies readback to title memory. | | `fallback` | Sharing is forced to fail: the section through a `FILE_MAP_READ` handle, or an interior address of the private range. The fixture records the HRESULT. The path falls back to `copy` only when the copy can keep the guarantees. A GPU-written use with no completion point is refused with the sharing HRESULT. | | `slot133` | A model of slot 133's fallback. A non-`MEM_PRIVATE` address is refused before D3D12 with `E_INVALIDARG`, and a committed default buffer stands in with `S_OK` and no copy. A private range is aliased through its allocation base. | @@ -11088,11 +12090,25 @@ On success the caller exits with `0x8AC`, also with `CPU_CRC_TEST_LIVE_WORKER=1` ```powershell ctest --preset dev --no-tests=error -R '^cpu_native_acphal_hal$' -V ctest --preset release --no-tests=error -R '^cpu_native_acphal_hal$' -V +``` ### ApuFree in the AcpHal stand-in The desktop `AcpHal.dll` stand-in (not the fixture provider above) now returns `ApuAlloc` blocks on `ApuFree` through a first-fit free list with coalescing, so repeated allocate and free cycles no longer exhaust the heap. It is a stand-in contract only: the console's error codes, alignment limits and zero-size behaviour are not public, and the codes chosen are listed in [startup-runtime.md](startup-runtime.md#apu-heap-stand-in). The source-built check is `ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V`. +### XMA context activity in the AcpHal stand-in + +With `X2W_AUDIO_PERMISSIVE=1` and `X2W_AUDIO_ACTIVITY=1`, the desktop `AcpHal.dll` and `xapu.dll` stand-ins count what a caller does with the audio processor. This is a first measurement for [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145), before any decoding. AcpHal compares the XMA context array it allocated with a copy inside the calls that count, at most once per 10 ms, and counts contexts filled (all zero to nonzero), changed and cleared, plus HAL slot2 submits by type. xapu counts `XApuEnqueueCommand` calls by command class with no cap. Neither DLL starts a thread; each logs at most a line per second, from a counted call at least a second after its previous line, when a count moved (later counts wait for a later call); the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts` return the totals. Line formats and limits are in [startup-runtime.md](startup-runtime.md#activity-counter). + +`startup_acphal_xma_activity` runs one source-built caller script in three child processes, plus an unload case. With the counter on, the caller fills 5 contexts, changes 3 and clears 2, submits 4 HAL commands of types 1, 1, 3 and 12, and enqueues 6 XApu commands of classes 1, 2 and 0x20, one null command, one command on an unknown handle and one type 3 command whose 8-byte header ends where free address space begins, sent with `X2W_XAPU_TYPED_COMPLETIONS=1` (every case sets `X2W_PROBE_PRECHECK=1`, so the free tail is refused without a fault). An `X2W_WITH_OPUS` build refuses that one with `E_POINTER` as too short to decode, and it must still count as class 3; only that build tells a counted refusal from an uncounted one. The exports and the summed log lines must give exactly those counts, and an array freed and allocated again must not be counted. The zero-write control writes only the 64 bytes after the last context and sends nothing: every count must be 0 and no line may be logged. With the counter off, the exports report nothing and no line is logged. Every result, output, last error and the final context bytes must match between the on and off runs. The unload case allocates the contexts a second time without `ApuFree`, then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. + +```powershell +cmake --build --preset release --target startup_acphal_xma_activity +ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V +``` + +The 64-byte context stride and the command class (the first `UINT32` of a command) are stand-in conventions, not console contracts. The counter identifies no field inside a context, such as an enable flag, decodes nothing, and does not establish which counted event starts playback. + ### XApu command-queue caller and recorder A source-built caller ([`xapu_queue_caller.asm`](../tests/cpu/xapu_queue_caller.asm)) imports the five `xapu.dll` command-queue functions by name (`XApuConnect`, `XApuEnqueueCommand`, `XApuGetResultCount`, `XApuDequeueResult`, `XApuDisconnect`), plus `finish_exe` from `cpu_exe_io.dll`, and starts through [`exe_startup.asm`](../tests/cpu/exe_startup.asm). A test-only recording provider ([`xapu_queue_provider.cpp`](../tests/cpu/xapu_queue_provider.cpp)) serves the five names. This is not a production `xapu.dll`, and this change adds no binding. @@ -11867,6 +12883,20 @@ mapping, archive stream discovery and rendered pixels remain separate work. The existing prefix probe keeps its diagnostic behavior. No local archive or texture payload is used by these checks. +### Standalone BCPack block reconstruction + +The startup DirectStorage stand-in reconstructs BC1–BC7 packed blocks without an +installed GDK or external table file. BC1's fitted endpoint window and quadrant +masks are removed; BC2 and BC6H now decode rather than report blank success. +See [the standalone implementation notes](experiments/bcpack-standalone.md) for +source provenance, synthetic golden checks, atomic storage tests, and optional +oracle reproduction commands. + +```powershell +cmake --build --preset dev --target bcpack_formats_check startup_stub_consumer startup_stub_xcrdapi +ctest --preset dev --no-tests=error -R '^(bcpack_all_formats|startup_bcpack_storage)' -V +``` + ### BCPack lane decoder paths The startup storage stand-in decodes BCPack streams with `decode_lanes` in @@ -12756,6 +13786,12 @@ mip-2 reference reported its mismatch at pixel (0, 0). The integer-clamp cases o `spirv_minlod_levels_*` read mips 0, 1, 2 and 3 at clamps 0 to 3 on the same adapter, with zero D3D12 debug errors and warnings. The fractional case on the same adapter resolves both boundary clamps to the lower mip: `spirv_minlod_fractional_hardware` reads mip 1 at clamps `1.5` and `1.5625`, where the same case on WARP reads mip 2. The fixture accepts either mip at those two clamps, so this records which side the adapter takes rather than a mismatch: clamp `1.4375` reads mip 1, `3.75` reads mip 3, and the wrong-clamp control reads mip 0 on both adapters. +The four registered `spirv_minlod_*_hardware` entries also pass on an AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`, Windows 11 build 26200.9974, DXC `1.9.2602.17`, tree `5a41adba`, debug layer unavailable) in three consecutive runs, with identical per-entry output in all three. The first run also carried the two toolchain controls `spirv_address_window_hardware` and `spirv_compare_sampler_hardware`, which pass with the same `spirv-cross`. On this machine the Vulkan SDK `1.4.363.1` `spirv-cross` makes all four entries report `skip: SPIRV-Cross lacks MinLod support`, with the smoke entry printing the underlying `MinLod texture operand not supported in HLSL`; the pinned build from `tools/setup-spirv-tools.ps1` (SPIRV-Tools v2025.5 `262bdab4`, SPIRV-Cross `57e4efc` with `patches/spirv-cross-minlod.patch`, which leaves `M spirv_hlsl.cpp` in that source tree and makes `--revision` print `57e4efc+`) is what lets them run. + +`spirv_minlod_hardware` matched the 64-pixel, 256-channel reference with `max_absolute_error=0` for the implicit, bias-with-offset and gradient samples, and its `no-clamp` control reported `pixel_mismatch` at (0, 0). `spirv_minlod_exact_hardware` read mip 1 at clamp 1 for the translated module and the direct HLSL control, with the stale mip-2 reference failing at (0, 0) in both. `spirv_minlod_levels_hardware` selected mips 0, 1, 2 and 3 at integer clamps 0 to 3, and its nine blend clamps from 1 to 3.75 matched the exact mip blend: `max_absolute_error` was 0 at seven of them and 0.000781298 at clamp 1.3 and 0.00195312 at 1.001953125, inside the 1/128 the fixture allows. The wrong-clamp control at 1.25 failed at (0, 0) and the direct HLSL control matched at every clamp. + +`spirv_minlod_fractional_hardware` reads mip 2 at clamps 1.5 and 1.5625, as in-box WARP 10.0.26100.9818 above does and unlike the Intel Arc 140T, which reads mip 1 there; 1.4375 and 1.49609375 read mip 1, 1.99609375 and 2 read mip 2, and 3.75 reads mip 3. The wrong-mip control at 1.5625 read mip 0 and failed at (0, 0), and the direct HLSL control selected the same mip at every clamp. + `spirv_minlod_levels_*` compiles at `ps_6_0`: - With point mip filtering, each integer clamp from 0 through 3 selects its @@ -13988,6 +15024,16 @@ python3 -B tests/rdna2_tools_check.py Scope: recognition only. No translator lowers these forms through this change, and no hardware or Windows run backs them. +## RDNA2 lane permutations in the unsupported-shader report + +`tools/scan_unsupported_shaders.py` reports `v_permlane16_b32` and +`v_permlanex16_b32` as `VALU (Cross-lane)` in `unsupported_details`. +The former can gather a value from another lane in the same 16-lane row. +The latter selects from the paired row. Both remain unsupported by the +pixel translator with either a declared wave32 or wave64 layout. The +lane-local byte-selection instruction `v_perm_b32` retains its ordinary +VALU classification. [AMD RDNA 2 ISA, §12.12](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + ## gfx1013 VOP1 rounding, frexp and operand-free opcodes `tools/disasm_rdna2.py` named only part of the VOP1 table; eleven opcodes in two contiguous gaps printed as `v_vop1_NN` @@ -14147,17 +15193,31 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cselect_mask_controls$ `tools/startup/gfx2hlsl.py` records the SGPRs that hold a lane mask (a `v_cmp` destination, a saveexec copy) in `Stage.masks`, and lowers a scalar logic op with a mask source as a mask op whose result is the lane's bit. The generic scalar path cleared the mark when it wrote ordinary data into such a register, but the other scalar writers did not. After `v_cmp_eq_u32_e64 s6, v0, v1` and `s_buffer_load_dword s6, s[16:19], 0x0`, s6 holds a buffer word, yet `s_or_b32 s8, s6, s7` was lowered as `s8 = (s6 | s7) & 1;`. Every write through `set_s` now clears the mark, the writers of a mask mark the register again after the write, and `s_load` clears the mark on its destination registers, also in the forms that only record a descriptor symbol. -`tests/startup_gfx2hlsl_mask_overwrite_check.py` writes a mask with a compare, overwrites it with an `s_buffer_load`, an `s_load` through a root pointer, an `s_load` of a descriptor or an `s_cselect_b32`, and evaluates the following `s_or_b32` on a buffer word with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py`. Controls: without the overwrite the OR stays a mask OR, and a compare or a mask logic op after a load marks the register again. On the translator before this change seven checks fail (the mark stays and the OR is cut to bit 0). Test: `startup_gfx2hlsl_mask_overwrite_controls`. Not covered: a draw through a translated pipeline; the other symbol-only scalar writes (for example an `s_mov` of a descriptor) still keep a mark they find. +`tests/startup_gfx2hlsl_mask_overwrite_check.py` writes a mask with a compare, overwrites it with an `s_buffer_load`, an `s_load` through a root pointer, an `s_load` of a descriptor or an `s_cselect_b32`, and evaluates the following `s_or_b32` on a buffer word with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py`. Controls: without the overwrite the OR stays a mask OR, and a compare or a mask logic op after a load marks the register again. On the translator before this change seven checks fail (the mark stays and the OR is cut to bit 0). Test: `startup_gfx2hlsl_mask_overwrite_controls`. Not covered: a draw through a translated pipeline. + +Scalar ALU on descriptor data (an `s_mov` of a descriptor word, a field extract or mask of one, an `s_add_u32` to a descriptor pointer) records only a symbol for its destination and did not clear the mark. A register that had held a mask and then a descriptor field kept the mark, so in a captured pixel program the stride clamp of a structured-to-raw conversion (`s_bfe_u32 s23, s45, 0xe0010`, then `s_max_u32 s23, s23, 1`) read as a lane-mask read. The descriptor-data path now clears the mark on its destination SGPRs before it writes them. The sources are classified before that, so a mask read by the same instruction is treated as before. The check runs these four writes after a compare in a pixel and a vertex stage and the clamp after the extract; a descriptor write into another SGPR keeps the mark on s6 (control). On the translator before this change (700522ef) six checks fail: the `s_bfe_u32` and `s_add_u32` clearing checks and the stride clamp, which is refused as `s_max_u32 reads lane mask s6 as numeric data`, each in both stages. + +The extract and the clamp emit no HLSL: the clamped stride is a symbol, and a numeric read of it is refused as before (`numeric use of s6 holding descnum`), with or without the earlier mask. It changes output only where it feeds the structured-to-raw conversion of a buffer store, which is recognized in compute and vertex programs. Case I-raw-mask of `tests/startup_gfx2hlsl_compute_check.py` covers that on the GPU: `v_cmp_gt_u32_e64 s21, 3, v0` in a 24-lane group, then the clamped conversion into s21 and the store of case A. The dispatch compares all 320 words with the CPU reference. The translation differs from case I-raw only by the dead compare. Control: `s_max_u32 s21, s21, 1` straight after the compare is still refused. On the translator before this change the case is refused (`s_max_u32 reads lane mask s21 as numeric data`), so the controls and the dispatch fail. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mask_overwrite_controls$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|warp|hardware)$' -V ``` +## Startup translator: lane masks used as vector data + +The one-lane model stores a mask as the current lane's bit. RDNA 2 reads the whole mask word when the register is +a data source. For example, after `v_cmp_eq_u32_e64 s[30:31], 0, v0`, reading s30 as data gives +`0xffffffff` if all 32 lanes pass. The translator refuses lane masks in either data operand of +`v_cndmask_b32` and in the source of `v_mov_b32`, including SDWA DWORD. Source modifiers still identify the +underlying mask register. Lane masks remain valid as selectors, and ordinary scalar words remain valid as data. +The synthetic controls run under `startup_gfx2hlsl_mask_data_controls`. + ## Startup translator: 32-bit add and subtract with a carry out `tools/startup/gfx2hlsl.py` refused the VOP3b forms `v_add_co_u32`, `v_sub_co_u32` and `v_subrev_co_u32` as unknown instructions. It now lowers them from the AMD RDNA 2 ISA description: `D = S0 + S1` with the carry out of bit 31, `D = S0 - S1` with a borrow when `S1 > S0`, and `SUBREV` with the sources swapped. These forms take no carry-in. The carry goes to the lane's bit of VCC or of the SGPR destination, which becomes a lane mask and is never a uniform source. The result and the carry are computed into the scratch registers `a` and `w` before either destination is written, so a destination may overlap a source. When `exec` is not known, an inactive lane keeps D and writes a 0 carry, as the compare lowering does. `clamp`, other modifiers, an EXEC carry-out and a wrong operand count are refused. -`tests/startup_gfx2hlsl_add_sub_co_check.py` decodes synthetic VOP3b words for the three forms with an SGPR and a VCC carry-out, evaluates the emitted lines with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py` on a grid of edge values, and compares them with Python references written from the ISA description. It also checks that the carry-out SGPR is a lane mask, that a readfirstlane of a copy of it is refused, the exec-masked form, an overlapping destination and the refusals. Negative control: a borrow with the comparison reversed disagrees with the reference on the grid. On the translator before this change every form is refused. Test: `startup_gfx2hlsl_add_sub_co_controls`. Not covered: DXC compilation and a draw through a translated pipeline; the check evaluates the emitted HLSL text only. +`tests/startup_gfx2hlsl_add_sub_co_check.py` decodes synthetic VOP3b words for the three forms with an SGPR and a VCC carry-out, evaluates the emitted lines with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py` on a grid of edge values, and compares them with Python references written from the ISA description. It also checks that the carry-out SGPR is a lane mask, that moving it as vector data is refused, the exec-masked form, an overlapping destination and the refusals. Negative control: a borrow with the comparison reversed disagrees with the reference on the grid. On the translator before this change every form is refused. Test: `startup_gfx2hlsl_add_sub_co_controls`. Not covered: DXC compilation and a draw through a translated pipeline; the check evaluates the emitted HLSL text only. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_add_sub_co_controls$' -V @@ -14200,13 +15260,30 @@ For binary32 arithmetic and compare sources, the translator reads the inline int ## Startup translator: explicit-LOD image sampling -`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) +`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array and multisample dimensions (a cube lowers since #2943, see [startup-image-cube](experiments/startup-image-cube.md)), an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) + +## Startup translator: binary32 arithmetic + +No check ran these binary32 operations of the `VEC_F` table in `tools/startup/gfx2hlsl.py` before: `v_add_f32`, `v_sub_f32`, `v_subrev_f32`, `v_mul_f32`, `v_mul_legacy_f32`, `v_min_f32`, `v_max_f32`, `v_fma_f32`, `v_mad_f32`, `v_mad_legacy_f32`, `v_med3_f32`, `v_min3_f32` and `v_max3_f32`. `tests/startup_gfx2hlsl_float_alu_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation to each of four pixels' flat inputs, alternating the `_e32` and `_e64` spellings of the VOP2 forms, and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference: `v_subrev` is S1 - S0, the legacy multiply reads 0 when either factor is 0 even against an infinity or a NaN, and `v_med3_f32` is the middle value. Every input set has an exact result, so the check does not depend on rounding or on whether a compiler fuses a multiply and an add. + +Each operation has a wrong lowering whose first draw must read its own mutated words: +- the add, subtract and multiply exchanged or reversed; +- the legacy product doubled; +- min and max exchanged; +- `a * b - c` for the multiply-adds; +- `max3` for `med3`. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 52 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 26 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_float_alu_controls`, `startup_gfx2hlsl_float_alu_warp` and `startup_gfx2hlsl_float_alu_hardware`. + +Not covered: inexact products. The translation writes both `v_fma_f32`, which rounds once, and `v_mad_f32`, which rounds the product and then the sum, as `a * b + c`. With `a = b = 1 + 2^-12` and `c = -(1 + 2^-11)`, a single rounding gives 2^-24 (`0x33800000`) and two roundings give 0. Through both FXC and DXC, both operations read 0 on WARP and `0x33800000` on the RX 6600. The result of either operation on an inexact product therefore depends on the adapter. NaN and signed-zero ordering in min, max and med3, and denormals, are not covered either. ## Startup translator: biased image sampling -`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form is refused outside a pixel stage, after the exec mask was modified and after a branch (there the plain sample is lowered to level 0, which would drop the bias), and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D and multisample dimensions (a cube lowers since #2943, see [startup-image-cube](experiments/startup-image-cube.md)), an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. -`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). +`tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform (scc) join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC or a vcc/exec-conditioned branch before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). ```powershell cmake --build --preset dev --target offscreen_check @@ -14217,7 +15294,7 @@ ctest --preset dev --no-tests=error -R '^startup_image_sample_b' -V The guest sampler's MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) clamp the LOD of every sample form. `tools/startup/gfx2hlsl.py` now carries them for `image_sample`, `image_sample_l` and `image_sample_lz` when the sampler is a constant, through the `smpl` manifest line and `decode_sampler` that `image_sample_b` introduced (#2051); the slice is #2177, split from the run-time heap case (#2221). The three forms share one validation with `image_sample_b`: a descriptor LOD bias (word 2 bits 19:0) and MIN_LOD above MAX_LOD are refused, with the form's own name in the message. Behavior change: a constant sampler with either of those fields set used to translate for these forms (limits ignored) and is now refused. A mip filter of 0 (mipmapping disabled) is not refused for these forms, unlike `image_sample_b` where the bias would count: such a sampler keeps its ordinary `smp` line and its previous behavior. Refusing it would drop every pipeline with an all-zero inline sampler (seven existing check scripts build one); `image_sample_lz` and `_l` with level 0 would be harmless anyway. The one-argument switch is `mip_filter_none_ok` in `Stage.lod_sampler_words`. Also changed: a constant sampler with a non-zero MAX_LOD now clamps the level (it was unbounded before), which is the intended fix. -Not changed: a sampler read through the sampler heap (table or default-sampler shortcut) keeps the ordinary static or heap sampler and is not validated; `translate_to` and `translate_compute` write one line per module to stderr (`: image_sample, image_sample_l through a sampler heap: sampler MIN_LOD, MAX_LOD and LOD bias are not validated (#2221)`). Since then the run-time heap table applies each entry's MIN_LOD and MAX_LOD (`dynamic_sampler()` in `src/startup_stubs/translated_sampler_bindings.h`, checked by `startup_sampler_lod_*`); the entry's LOD bias is not carried, a MIN_LOD above MAX_LOD is passed through unchanged, and the default-sampler shortcut keeps a static sampler with an unbounded LOD range. A sampler that is neither heap nor constant is refused as before. `image_sample_c` keeps its MAX_LOD rule. +Not changed: a sampler read through the sampler heap (table or default-sampler shortcut) keeps the ordinary static or heap sampler and is not validated; `translate_to` and `translate_compute` write one line per module to stderr (`: image_sample, image_sample_l through a sampler heap: sampler MIN_LOD, MAX_LOD and LOD bias are not validated (#2221)`). Since then the run-time heap table applies each entry's MIN_LOD and MAX_LOD (`dynamic_sampler()` in `src/startup_stubs/translated_sampler_bindings.h`, checked by `startup_sampler_lod_*`); the entry's LOD bias is not carried, a MIN_LOD above MAX_LOD is passed through unchanged, and the default-sampler shortcut keeps a static sampler with an unbounded LOD range. Other nonconstant samplers remain refused except for the [proven two-sampler explicit-LOD join](experiments/startup-sampler-join.md). `image_sample_c` keeps its MAX_LOD rule. `tests/startup_image_sample_lod_check.py` draws each form on its own (`startup_image_sample_lod_warp`, `startup_image_sample_lod_hardware`) against the 4x4, two-slice, three-mip array, point sampler with mip filter point, where all six cells differ. Each form's control is the same program through the ordinary `smp` line, which must read a different mip: `image_sample_l` with explicit level 2 and MAX_LOD 1 reads mip 1 (`smp`: mip 2); `image_sample` with MIN_LOD 2 above the implicit level 1 reads mip 2 (`smp`: mip 1); `image_sample_lz` with MIN_LOD 1 reads mip 1 (`smp`: mip 0). The implicit level 1 comes from the technique of the bias check: only the `u` initialiser of the translated HLSL is replaced by `0.75 + 0.5 * (SV_Position.x - 0.5)`, the `Sample` call is untouched. Refusal controls per form: bias, secondary bias and MIN_LOD 3 above MAX_LOD 2; accepted controls per form: mip filter 0 (`smp` line) and a heap sampler (table and default-sampler shortcut, logged once). The three `image_sample_b` discriminators are unchanged. Not covered: a fractional MIN_LOD or MAX_LOD, a linear mip filter, 1D, 3D and packed `a16` draws, the run-time heap sampler's LOD fields (#2221), and compute stages. @@ -14242,6 +15319,15 @@ The two adapters and WARP [measured on the desktop](https://github.com/R0Y00/Xbo differed at exact half-mip boundaries with point mip filtering. The regression uses linear filtering for the fractional lower clamp. Native console readback remains open. +The same startup lowering admits 2D arrays with three guest address registers. +DXIL `CalculateLOD` takes just the two spatial coordinates for a `Texture2DArray`; +the slice is not part of the level calculation. The portable controls verified +both dimensions, including a non-sequential address with a different slice register, +and retained the existing derivative, sampler and mask refusals. +The array-view fixture compares raw translated and direct HLSL readbacks for +two encoded slice values and two gradients against the independent LOD reference. +The array GPU lane was not run on Apple Silicon. + ```powershell ctest --preset dev --no-tests=error -R '^startup_image_get_lod_view_' -V ``` @@ -14334,6 +15420,10 @@ with normalized clamp addressing, bilinear XY, point mip filtering, and zero minimum LOD and bias. Implicit, explicit-LOD, comparison, offset, and non-2D forms remain outside this slice. +Plain `image_gather4` reports `requires the guest implicit mip level`. +Translating it through the fixed-mip path could read a different level +because Direct3D gather uses the first visible mip of the bound view. + The sampler's Z address mode (`CLAMP_Z`, SQ_IMG_SAMP_WORD0 bits 8:6) is not checked: a 2D view has no third coordinate, and the Direct3D 11.3 functional spec (22.4.2, gather4) says only the sampler's addressing modes @@ -14397,12 +15487,13 @@ ctest --preset release --no-tests=error -R '^startup_compute_gather_lz(_warp|_ha ### Startup compute D16 image store -The startup compute translator accepts a 2D `image_store d16` with all four -DMASK bits set, full-width X/Y and eight intact image descriptor words from a -fixed table offset. The R/G half-floats occupy the low/high halves of the first +The startup compute translator accepts 2D and 2D-array `image_store d16` +with all four DMASK bits set, full-width X/Y (and layer for an array), and eight +intact image descriptor words from a fixed table offset. The R/G half-floats occupy the low/high halves of the first data VGPR. B/A occupy the second. The translator widens the four halves for a typed UAV store under the lane's EXEC bit. The version 2 compute manifest -records `uav N tex2d float table P O channels 4`. Raw buffer and texture UAVs +records `uav N tex2d float table P O channels 4` or, for an array, +`uav N tex2da float table P O channels 4`. Raw buffer and texture UAVs share a register index space. The consumer must validate the bound view against its dimension and float type. [AMD RDNA 2 ISA, §§8.2.1 and 8.2.5](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content) @@ -14412,7 +15503,10 @@ write 16 texels to mip zero of an RGBA16_FLOAT UAV. Each run compares all 1,344 half-words across three mips, including signed zeros, subnormals and untouched texels. A second program masks out the second row. Omitting the store, swapping R/G, swapping the packed registers and dropping the EXEC guard produce 64, 32, -64 and 32 differences respectively. Slot-67 runtime binding is tracked in #2274. +64 and 32 differences respectively. Slot-67 2D runtime binding is tracked in #2274. +The [array UAV runtime fixture](experiments/startup-compute-array-uav.md) also +checks packed D16 through the production slot-67/slot-14 path with a nonzero +FirstArraySlice, all six physical slices and five negative controls. ```powershell cmake --build --preset release --target offscreen_check @@ -14421,26 +15515,18 @@ ctest --preset release --no-tests=error -R '^startup_compute_image_store_d16' -V ### Startup compute 32-bit float image store -The startup compute translator also accepts a 2D 32-bit `image_store` (with or -without the integer-coordinate `unorm` modifier) when all four DMASK bits are -set, coordinates are two full-width VGPRs, data comes from four consecutive -VGPRs and the eight image descriptor words come from an unmodified fixed table -offset. The translator emits `asfloat(uint4(...))` into a `RWTexture2D` -under the lane's EXEC bit and records `uav N tex2d float table P O channels 4` -in the version 2 compute manifest. Pixel-stage 2D `image_store` also accepts -`unorm`. +The startup compute translator accepts the full-mask FP32 image_store on +dim:SQ_RSRC_IMG_2D_ARRAY with three full-width address VGPRs for x, y and layer. +It emits an RWTexture2DArray store under the lane EXEC bit and records +uav N tex2da float table P O channels 4 in the version 2 manifest. +The [startup runtime array UAV binding](experiments/startup-compute-array-uav.md) +consumes this manifest for full-mask FP32 and packed D16 compute stores. +Pixel arrays and the 1D, 3D and cube store forms remain refused. -The standalone dispatch reuses the source and CPU reference from the -[gfx1013 2D float store fixture](#gfx1013-2d-float-image-stores-and-mip-loads). -Two groups write 16 texels to mip zero of an `R32G32B32A32_FLOAT` UAV while -comparing all 1,344 words across three mips. A second program masks out the -second row. Omitting the store, swapping R/B, swapping RG/BA and dropping the -EXEC guard produce 64, 32, 64 and 32 mismatches respectively. - -```powershell -cmake --build --preset release --target offscreen_check -ctest --preset release --no-tests=error -R '^startup_compute_image_store(_warp|_hardware)?$' -V -``` +The standalone GPU fixture writes the same four words into mip zero of layer 1 +and layer 3 of a four-layer allocation. It compares all 5,376 words and detects +64 differences with the store omitted and 128 with the layer changed. Use the +startup_compute_image_store CTests above to repeat the comparison. ### Explicit-LOD 2D gather @@ -14578,6 +15664,34 @@ ctest --preset dev --no-tests=error -R '^startup_image_gather_c_lz(_warp|_hardwa python3 -B tests/startup_image_gather_c_lz_check.py --llvm-mc llvm-mc-15 ``` +## Startup translator: three-source integer operations + +No check ran the three-source integer operations of the `VEC_U` table in `tools/startup/gfx2hlsl.py` before: `v_bfe_u32`, `v_mad_u32_u24`, `v_lshl_add_u32`, `v_add_lshl_u32`, `v_add3_u32`, `v_or3_b32`, `v_and_or_b32`, `v_lshl_or_b32`, `v_xad_u32` and `v_bfi_b32`. All ten are VOP3 only. `tests/startup_gfx2hlsl_int3_alu_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation to each of four pixels' flat inputs and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference with plain integer arithmetic: +- `v_bfe_u32` takes an unsigned field of width S2[4:0] at offset S1[4:0]; +- `v_mad_u32_u24` multiplies the low 24 bits of S0 and S1; +- shift counts come from bits 4:0; +- sums wrap at 32 bits; +- `v_bfi_b32` is the insert `(S0 & S1) | (~S0 & S2)`. + +The inputs include shift counts and widths above 31, sources with bits above bit 23, and sums that wrap. + +Each operation also has a wrong lowering whose first draw must read its own mutated words: +- the bfe mask without `- 1`; +- a full-width first factor; +- add and OR exchanged in the shift-add pair; +- a 4-bit shift count; +- `a + b - c` for `v_add3_u32`; +- XOR for `v_or3_b32`; +- XOR for the OR in `v_and_or_b32`; +- OR for the XOR in `v_xad_u32`; +- an insert without the complement. + +An earlier mutation masked the bfe width to 4 bits. FXC `ps_5_1` compiled that mutated shader to one that read all zeros on WARP, so the mutation no longer tests only the lowering, and it was replaced. The correct lowering matched through both compilers. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 40 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 20 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_int3_alu_controls`, `startup_gfx2hlsl_int3_alu_warp` and `startup_gfx2hlsl_int3_alu_hardware`. + ## Startup translator: per-lane bit operations The startup scalar lowering also covers `s_lshl1_add_u32` through @@ -14589,7 +15703,7 @@ against an integer reference on the CPU and separately checks refusal of lane masks and the discard destination. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_lshl_add$' -V`. -`tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, `v_bfm_b32`, the 24-bit multiplies and `v_alignbit_b32`. +`tools/startup/gfx2hlsl.py` now lowers six gfx1013 per-lane bit operations that it used to refuse: `v_bfe_i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32`, `v_ffbh_i32` and `v_bfrev_b32`. They become single HLSL expressions, so no helper function is added to the output: `countbits(a) + b`, `firstbitlow(a)`, `reversebits(a)`, and, for the two high scans, `a == 0u ? 0xffffffffu : 31u - firstbithigh(a)` (the signed form scans `~a` for a negative value and reads 0xffffffff for 0 and -1). `v_bfe_i32` takes the offset from bits 4:0 of source 1 and the width from bits 4:0 of source 2, reads 0 for a width of 0, and sign-extends the field from its top bit; when offset plus width passes 32, the bits above bit 31 repeat bit 31, which is an arithmetic shift of the whole word. The formulas and edge cases are the ones `tools/pixel_aot.py` already draws on WARP. `v_bfe_i32` and `v_bcnt_u32_b32` exist only as VOP3 on gfx1013 (llvm-mc 19 rejects `_e32`); the other four assemble in both `_e32` and `_e64`. Source modifiers, `clamp`, output modifiers, `op_sel` and a wrong operand count are refused with `Unsupported`; the operand count is now checked for every integer operation in this table, where a missing operand used to raise `IndexError`. Not lowered here: the 64-bit carry forms, the 24-bit multiplies and `v_alignbit_b32` (`v_bfm_b32` is lowered separately, see the next entry). `tests/startup_gfx2hlsl_bit_alu_check.py` translates a source-built pixel stage that applies each operation to four lanes (the VOP1 operations alternate `_e32` and `_e64`) and evaluates the generated text with a small 32-bit HLSL evaluator against a reference written from the ISA description with bit loops, string reversal and integer arithmetic. The grid holds 17,459 inputs for `v_bfe_i32` (every offset and width 0 to 31 for 17 base words, plus offsets and widths above 31), 324 for `v_bcnt_u32_b32` and 81 for each scan. Each lowering also has a mutation that must read a wrong word: no sign extension, a subtracted addend, 0 instead of 0xffffffff for zero, no `31u -`, a negative value scanned unchanged, and no bit reversal. On `origin/main` the check fails with `Unsupported: v_bfe_i32`. `binary ` reassembles the fixtures (llvm-mc 19 here; the CI job passes llvm-mc 15). The `draw` mode compiles the translated pair with FXC and DXC and draws one pixel per four input sets through `offscreen_check --startup-flat-param`; the inputs travel as flat vertex parameters so the compilers cannot fold them. It also draws the first set of each operation with the mutated lowering and requires the mutated words in the readback. The evaluator and reference results above come from Linux. The draw mode passed at `48d9571d` on Windows 11 build 26300.9974 with DXC 1.8.2502.11 and the Windows SDK 10.0.26100 FXC, with the debug layer on and 0 errors and 0 warnings. It passed on WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003). On each adapter, all 34 draws (17 through FXC `ps_5_1` and 17 through DXC `ps_6_0`) matched the reference words, and all 12 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_bit_alu_controls`, `startup_gfx2hlsl_bit_alu_warp` and `startup_gfx2hlsl_bit_alu_hardware`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) `v_xor3_b32` (`D = S0 ^ S1 ^ S2`, the LLVM 15 and RDNA 2 definition, as in the compute lowering of #1573) joins the same check with 729 grid inputs and three draw sets whose three sources differ in every byte (0x13579bdf, 0x2468ace0, 0xfedcba98 and their rotations); its mutation drops the third operand and reads `src0 ^ src1`. Source modifiers, `clamp`, `op_sel` and a wrong operand count stay refused. `binary` matches the xor3 words with llvm-mc 23; the draw has not run on Windows for it yet. @@ -14597,16 +15711,47 @@ lane masks and the discard destination. Run The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands. A binary32 source may carry the `neg`/`abs` modifier (`-vN`, `|vN|`, `-|vN|`): the permuted word is read from the neighbour first and the modifier applies to that value (RDNA 2 ISA 12.19, LLVM 15 prints them on the `_dpp` spelling), while integer sources, SGPR sources and every other modifier stay refused. Vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks and operations without a table entry are refused. `fi:1` (fetch inactive) is accepted under the same whole-quad proof, where no source lane is disabled, and gives the same translation. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. `startup_gfx2hlsl_dpp_quad_swap_controls` checks `-v0` and `|v0|` against the emitted `QuadReadAcrossX` text and keeps an integer `-v0` refused; the draw mode also checks all 256 pixels of a binary32 multiply-by-one fixture. Its three channels use NEG, ABS and NEG+ABS on different neighbours, and each dropped modifier produces a mismatch. The binary mode reassembles the modified DPP source words. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) -The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writelane_b32 vN, sM, k` followed by `v_readlane_b32 sD, vN, k` with an inline constant lane `k` (0..31) becomes one scalar slot per (VGPR, lane), written and read back as plain assignments. Both instructions ignore EXEC and touch only lane `k`, so with a constant `k` and a VGPR that no other instruction names, no cross-lane read exists to model. Refused, each with a reason: a lane chosen by an SGPR, lanes outside 0..31, a VGPR that any other instruction also names (vector use or register range), a read of a slot nothing wrote, branches (write-before-read needs straight-line order), a lane mask, `m0` or modifier on the value, a destination that is not a plain SGPR, and vertex stages. A constant value reloads as a constant. `tests/startup_gfx2hlsl_sgpr_spill_check.py` builds a pixel program with four slots in three VGPRs, clobbers the source SGPRs, reloads them (one slot after a second write) and ORs each word into the packed screen position; it draws 16 x 16 pixels and compares every word with an integer reference computed from the slot rule. Four wrong lowerings (overwrite ignored, lane 31 read as lane 0, a second VGPR read as the first, no reload) must read a different image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sgpr_spill_' -V`. The Python controls and the `binary` assembler check run on Linux; the draws need DXC and `offscreen_check` on Windows. +The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writelane_b32 vN, sM, k` followed by `v_readlane_b32 sD, vN, k` with an inline constant lane `k` (0..31) becomes one scalar slot per (VGPR, lane), written and read back as plain assignments. Both instructions ignore EXEC and touch only lane `k`, so with a constant `k` and a VGPR that no other instruction names, no cross-lane read exists to model. Refused, each with a reason: a lane chosen by an SGPR, lanes outside 0..31, a VGPR that any other instruction also names (vector use or register range), a read of a slot nothing wrote, a read in a program with branches that the proof below does not cover, a lane mask, `m0` or modifier on the value, a destination that is not a plain SGPR, and vertex stages. A constant value reloads as a constant. `tests/startup_gfx2hlsl_sgpr_spill_check.py` builds a pixel program with four slots in three VGPRs, clobbers the source SGPRs, reloads them (one slot after a second write) and ORs each word into the packed screen position; it draws 16 x 16 pixels and compares every word with an integer reference computed from the slot rule. Four wrong lowerings (overwrite ignored, lane 31 read as lane 0, a second VGPR read as the first, no reload) must read a different image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sgpr_spill_' -V`. The Python controls and the `binary` assembler check run on Linux; the draws need DXC and `offscreen_check` on Windows. + +The same slots are lowered in pixel stages with branches. The slot variable is assigned on the pixel's own path, while the hardware lane holds the last write on the wave's path; the two differ only inside the region of a branch not proven uniform (`s_cbranch_execz`/`_vccz` and their `nz` forms, or an SCC branch on varying data: the blocks between the branch and its immediate post-dominator, or the loop range of a backward branch), where the wave also runs blocks the pixel skips. A forward must-dataflow over the basic blocks (intersection at joins, fixed point through loops) gives, for each `v_readlane_b32`, the writes of its (VGPR, lane) that can supply it. One write: every path into the read ran it, so it is accepted unless the write lies in such a region and the read is outside it (a loop or arm the wave can run after the pixel left it). Several writes: accepted only when none lies in such a region; the reload keeps a constant only if every write stored it and is not claimed uniform. Refused, each by name: no write on some path (including another lane on another path), a write later in a loop that reaches the read through the back edge, a single write in a non-uniform region the read is outside, joined writes with one in a non-uniform region, and a reaching write that was itself refused. The lane-mask, descriptor, lane-range and vector-use refusals above are unchanged; the lane-mask test still follows program order, not the joins. On a local set of 79 vertex/pixel requests whose first refusal was the straight-line requirement under a development translator, 32 reach that refusal on main; with this change all 32 pass it and stop next at a lane-mask or descriptor spill source (30) or a spill VGPR also used as a vector (2). The other 47 stop earlier on main (`v_fma_mix_f32` 39, a joined symbol 8). `tests/startup_gfx2hlsl_spill_branches_check.py` (`startup_gfx2hlsl_spill_branches`) translates synthetic programs through `Stage.translate()`: six accepted shapes with their exact emitted lines, seven refusals with their exact reasons, and six translator mutations (union at joins, one pass instead of the fixed point, lanes keyed by their spelling, each region rule removed, every branch counted uniform) that must each turn a control red. One whole pixel stage is also generated: the slot is declared once and assigned on both arms of a uniform branch before the read after the join. The same file also draws it (`startup_gfx2hlsl_spill_branches_warp`/`_hardware`, FXC 5_1 and DXC 6_0): two uniform SCC choices write different binary32 words to one slot, the join reloads it and exports it OR-ed with the packed screen position, and the readback of all 16x16 pixels must equal the selected arm; the opposite arm's reference must mismatch. + +Wave64 lanes and vertex stages: the same slot model now accepts lanes 0..63 and vertex stages. A wave32 program takes the lane select modulo 32, so lanes `k` and `k + 32` of one VGPR would be one slot there and two in wave64; the translator does not know the wave size and refuses that pair. Lane 64 and above, compute stages and register-selected lanes stay refused. `tests/startup_gfx2hlsl_spill_wave64_check.py` draws a pixel program with slots on lanes 32, 33, 40 and 63 (16 x 16 pixels) and a vertex program with slots on lanes 0 and 48 whose reloads reach a flat parameter (one pixel), each compared with a reference replayed from the slot rule; wrong-lane and ignored-overwrite translations must fail. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_spill_wave64" -V`. + +Compute stages: the same slots are lowered in `cs` (with branches, through the same write-before-read proof), and a spilled descriptor or pointer word (`desc`, `ptr`, `ptrhi` symbols) is carried by identity: the slot holds the symbol, nothing is emitted, and the reload restores the same symbol. A word whose symbol does not name one value (a modified descriptor word, a pointer with a non-numeric offset) is refused when it is spilled; writes of different symbols joined at a read are refused; lane masks are the next step (`startup_gfx2hlsl_compute_mask_spill`, below). A reload also keeps the provenance of the word it restores: a formatted buffer load past the entry block accepts a reloaded descriptor only when every write that can supply it was spilled from the entry block or from one untouched local table load of a proven pointer, i.e. when the original would have been accepted at the write. `tests/startup_gfx2hlsl_compute_spill_check.py` (`startup_gfx2hlsl_compute_spill*`) builds two gfx1013 compute fixtures from source (a read descriptor spilled in the entry block and the store descriptor spilled on both arms of a uniform branch, reloaded inside an `s_cbranch_execz` region for a formatted load and a store; a table pointer pair spilled and reloaded to load a descriptor), eight refused variants each with its exact reason, probes for `ptrhi` and modified words, eleven translator mutations that must each turn a control red, and a WARP/hardware dispatch with three mutated translations that must mismatch. + +Lane masks in compute: `v_writelane_b32` accepts `vcc_lo` or an SGPR the translator tracks as a mask (not proven-on-every-path marks, exec, `vcc_hi` and m0 stay refused), and `v_readlane_b32` reloads it into an SGPR (marked a mask again) or into `vcc_lo`. The translator models a mask per invocation as that invocation's own bit (a v_cmp stores `w`, or `exec & w` once EXEC is not known), and the write and the reload both ignore EXEC and copy the whole wave mask, so a reload used only as a mask has, in every invocation, the bit the invocation had at the write: the slot variable takes the mask's variable at the write and the reload copies it back. A reload is refused when an instruction reachable before its next write reads it as anything but a lane select or carry-in, an `s_cbranch_vccz` / `_vccnz` condition, a copy into `exec_lo` / `vcc_lo` or another spill, and when it may see two writes of which one is a mask. `tests/startup_gfx2hlsl_compute_mask_spill_check.py` (`startup_gfx2hlsl_compute_mask_spill*`) builds two gfx1013 compute fixtures from source (a `vcc_lo` and an SGPR compare result spilled, a uniform branch, both reloaded into SGPRs and used by `v_cndmask_b32_e64` and `s_and_saveexec_b32`; a `vcc_lo` reloaded into `vcc_lo` and used by `v_cndmask_b32_e32` and `s_cbranch_vccz`), twelve refused variants, translator mutations that must each turn a control red, and a WARP/hardware dispatch with three mutated translations that must mismatch. The binary32 table (`VEC_F`) applies the same operand-count rule. Before this change, a form one source short (`v_add_f32 v1, v2`) raised `IndexError` in `Stage.one` instead of `Unsupported`. A form with one source too many (`v_med3_f32 v1, v2, v3, v4, v5`) translated with the extra source dropped. `tests/startup_gfx2hlsl_operand_count_check.py` (`startup_gfx2hlsl_operand_count`) checks every operation of both tables: one source fewer and one source more are refused, and the exact count translates. It also checks that the constant and accumulator forms (`v_fmac_f32`, `v_mac_f32`, `v_fmamk_f32`, `v_fmaak_f32`, `v_madmk_f32`, `v_madak_f32`) keep translating with their usual operands. As a control, it loads the translator with the new `VEC_F` guard removed and requires both old failures to come back. +## Startup translator: binary32 rounding + +No check ran the rounding operations of the `VEC_F` table in `tools/startup/gfx2hlsl.py` before: `v_floor_f32`, `v_ceil_f32`, `v_trunc_f32`, `v_fract_f32` and `v_rndne_f32`. They lower to HLSL `floor`, `ceil`, `trunc`, `frac` and `round`. `tests/startup_gfx2hlsl_float_round_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`, one operation per lane on flat inputs, alternating the `_e32` and `_e64` spellings, and compares the four result words exactly. + +The references follow the AMD RDNA 2 ISA reference: +- A zero result keeps the sign of the source: `ceil(-0.75)`, `trunc(-0.75)` and `rndne(-2^-30)` are -0. +- `v_rndne_f32` rounds halves to even: 2.5 → 2, 3.5 → 4, -2.5 → -2, 1000000.5 → 1000000. +- `v_fract_f32` is `x - floor(x)`, capped at the largest binary32 below 1.0. With -2^-30 the exact difference rounds to 1.0, and the instruction gives `0x3f7fffff`. + +The inputs also include the binary32 just below 0.5 and 8388607.5. + +Each operation has a wrong lowering whose first draw must read its own mutated words: floor and ceil exchanged, floor for trunc, `x - trunc(x)` for frac, and trunc for round. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 20 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 10 mutated draws read their mutated words. On both adapters, HLSL `frac` of -2^-30 read `0x3f7fffff`, so the lowering kept the cap on these two adapters without an explicit comparison. Tests: `startup_gfx2hlsl_float_round_controls`, `startup_gfx2hlsl_float_round_warp` and `startup_gfx2hlsl_float_round_hardware`. ## Startup translator: v_swap_b32 `tools/startup/gfx2hlsl.py` now lowers `v_swap_b32` (VOP1, opcode 101), which it used to refuse. Both VGPRs exchange their old values, so the lowering reads the destination into a temporary before either register is written: `{ uint t = v1; v1 = v2; v2 = t; }`. The RDNA 2 ISA allows no input or output modifier on it, and LLVM 15 assembles only the 32-bit VOP1 spelling for gfx1013 (the `_e64`, `_dpp` and `_sdwa` forms and a scalar, constant, negated or 64-bit operand are rejected), so the translator refuses all of those and a modifier. A register-to-itself swap assembles and keeps its value. A proven-uniform register keeps that proof across the swap only while the exec mask is known. `tests/startup_gfx2hlsl_swap_check.py` (`startup_gfx2hlsl_swap`) decodes the documented VOP1 words, evaluates the translated text of seven programs on the CPU against a plain exchange of two list entries, and checks the refusals. Two mutations (write before read, only one destination written) are loaded from the translator source and must fail the fixtures. `python -B tests/startup_gfx2hlsl_swap_check.py binary llvm-mc-15` also reassembles the source lines. This is translation only; no draw was run. +## Signed zero in startup binary16 multiplication + +The `startup_gfx2hlsl_f16_alu_draw` fixture draws plain, packed and SDWA binary16 products +with independently computed raw-word expectations. In the SDWA high-word preserve case, +the lower 16 bits start at `abcd`. Multiplying negative zero by positive zero and applying +the fixture's export tag must read back `e000abcd`. Losing the sign gives `6000abcd`. +The HLSL multiply uses a `precise` binary32 product before the binary16 rounding step. +Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_f16_alu_draw_(warp|hardware)$' -V`. + ## Startup translator: v_fma_mix_f32 `tools/startup/gfx2hlsl.py` now lowers `v_fma_mix_f32` (VOP3P, opcode 0x20), which it used to refuse. It shares one handler with `v_fma_mixlo_f16` and `v_fma_mixhi_f16`. Each source is read as LLVM 15 selects it (`SelectVOP3PMadMixModsImpl`): `op_sel_hi` set means a binary16 source, and `op_sel` then picks its high half. abs and then neg apply after widening. The binary32 result is written to the whole VGPR, with optional `clamp`. @@ -14636,6 +15781,14 @@ Measured at `741ff02c` plus the dispatch mode, `dev` preset, Windows 11 26300.99 ctest --preset dev --no-tests=error -j1 -R '^startup_gfx2hlsl_fma_mix(_fxc|_dispatch_(warp|hardware))?$' -V ``` +### Signed zero: a `precise` `mad` (cache revision 28) + +On an AMD Radeon RX 5700 XT (#2729) and an RX 9070 XT (#2746), the `-0` case read back `00000000` instead of `80000000`; WARP kept the sign. Their probes lost it only when a binary16 operand widened by `f16tof32` fed a non-`precise` multiply or `mad`, and kept it under `precise`. Non-`precise` HLSL arithmetic does not have to keep a zero's sign. + +All three forms now call `mix32(a, b, c)`, whose body is `precise float result = mad(a, b, c); return result;`. Operand order, half selection and modifiers are unchanged, and `saturate` stays outside the call. DXC 1.9.2602.17 emits it as `FMad` with `!dx.precise` on the `FMad` and on the `legacyF16ToF32` that feeds it. `mad` still lets a backend fuse or round the product, so the 1 ULP note above still applies. The dispatch mode prints `mad(4097, 4097, -16785408)` per adapter as information: `3f800000` means fused and `00000000` unfused. A second control shader uses a helper that clears the sign of a `-0` result. It must fail only the `-0` case. + +Measured on this branch, `dev` preset, Windows 11 26300, DXC 1.9.2602.17, D3D12 debug layer on with 0 errors and 0 warnings. WARP (1414:008c, 10.0.26100.9818): 17 of 17 words, `-0` kept, unfused. NVIDIA GeForce RTX 4090 (10de:2684, 32.0.16.1088): 17 of 17, fused. Both controls behaved as described. The RTX 4090 also passed before this change, so these runs do not show the fix on RDNA. The RX 5700 XT and RX 9070 XT retests are still pending. + ## Non-fused multiply-add in the startup translator The gfx1013 `v_mad_f32`, `v_mac_f32`, `v_madmk_f32`, `v_madak_f32` and @@ -14685,6 +15838,26 @@ python3 -B tests/startup_gfx2hlsl_calculated_target_check.py python3 -B tests/startup_gfx2hlsl_calculated_target_check.py binary llvm-mc-15 ``` +### Statically resolved far early-outs through the two-exit profile + +The gfx1013 pixel two-exit extractor accepts a single proven forward calculated transfer onto an +instruction-aligned terminating continuation containing only `s_nop`/`v_nop` and a plain `s_endpgm`. +The contiguous `s_getpc_b64`/`s_add_u32`/`s_addc_u32`/`s_setpc_b64` chain uses a fresh aligned scalar +pair and a constant displacement with matching sign extension. The repository and LLVM instruction +inventories must agree, and no branch may enter the chain interior. Observable continuation effects +remain refused. The standalone `pixel_aot.lower()` retains its single-export, single-exit scope. + +The source-built fixture compares short direct, short calculated and far calculated transfers using +both selector outcomes and an independent arithmetic reference. The far displacement exceeds the +131068-byte positive SOPP range. The bounded FSSM extraction check requires LLVM 15; its absence is +reported separately from translation. Refusal controls cover malformed chains, escaping scratch +words or SCC, effectful continuations and unaligned or out-of-range destinations. + +```bash +python3 -B tests/startup_gfx2hlsl_far_early_out_check.py +python3 -B tests/startup_gfx2hlsl_far_early_out_check.py binary llvm-mc-15 +``` + ## Compute stage in the startup translator `gfx2hlsl.ComputePipeline` translates one gfx1013 compute program with the root and resource model of @@ -14725,6 +15898,28 @@ covers a nested `if`, an `if`/`else` whose arms have their own `s_cbranch_execz` restore reads a mask saved inside the block. The proof starts at the branch, so it is not run for a block that a branch from outside enters. +A definition of an SGPR or `vcc` that is live at the join is still accepted when exec absorbs every read of +it. With the block's exec writes proven, a skipped lane's exec bit is clear at the join, in the wave and in +the model. In the straight run that starts at the join, which only the block enters, and before any exec +write in it, `W & exec` and `exec & W` (`s_and`) give that lane 0, and `~(W & exec)` (`s_nand`) and +`W | ~exec` (`s_orn2` with exec second) give it 1, whatever the block left in W. The search follows every path +from the join until W is written again. Any other read keeps the refusal: a copy, a data read, a branch on +`vccz`, an absorbed form after an exec write or a branch target, or one at a join that a loop re-enters. The +reason names the first such read the search meets. `m0` and SCC have implicit readers and are not accepted +this way. Case N runs a compare in a block whose join computes `s_and_b32 s23, vcc_lo, exec_lo` before it restores +exec; its control `n-unmasked` drops the AND, so the two lanes that skip the block store with a stale `vcc`. +`s_nand` on a lane mask is still refused by the lane-mask lowering itself. + +A mask that the block only narrows is also accepted. When every write of W in the block is +`s_andn2 W, W, X` and the exec-write pass shows X clear for a skipped lane at that instruction, on every path +from the branch, the lane keeps its bit of W, so W at the join holds the model's bit. A read after the join is +then proven when it is a bitwise mask operation that takes bit n of its result from bit n of W, in the same +half of the wave, and writes that result to the exec word of that half or back to W, such as the restore +`s_mov_b32 exec_lo, W`. A copy of W into another register, a data read, a write of W of another form, X not +known clear, or a block that a branch from outside enters keeps the refusal. Case O narrows the saved mask +with `s_andn2_b32 s0, s0, exec_lo` in the block and the join moves s0 into exec; its control `o-mask-kept` +drops the narrowing, so the lanes the block handled store again. + Each instruction's reads and writes come from its printed operands, checked against the repository decoder's spelling: - `v_cmpx` prints no destination (its e64 form prints an unused SDST field), so all of its operands are reads; @@ -14732,7 +15927,7 @@ decoder's spelling: - `v_div_fmas` reads `vcc`; - the high half of a mask is tracked apart from the low half. -One live definition is accepted, the lane mask of the compiler's if-conversion: a 32-bit mask M (`vcc_lo` or one +A third live definition is accepted, the lane mask of the compiler's if-conversion: a 32-bit mask M (`vcc_lo` or one SGPR) that `s_mov_b32 M, 0` zeroes before the branch, with only straight-line code between the zeroing and the branch, and that the block sets only with `s_mov_b32 M, exec_lo` or `s_and_b32 M, X, exec_lo` (either operand order). Exec only narrows in the block, so each such write leaves the bit of a lane whose exec bit is clear at 0. @@ -14742,12 +15937,24 @@ be the lane select of `v_cndmask`, the carry-in of `v_addc`, `v_subb`, `v_add_co `s_and_saveexec_b32` / `s_and_b32` with exec. `s_cbranch_vccz`, `s_cbranch_vccnz`, `s_cmp`, a copy of M and M as a data operand see the other lanes' bits, which the one-lane model does not have, and keep the refusal. +The same lane mask is accepted with three more block writes, each exact only under a condition. All of them need +every mask the write uses to hold lane bits (bit 0 is the lane's own bit: a `v_cmp`, an `s_and` with exec, a copy +of exec, or 0 / -1), not data such as a group id or `s_mov_b32 M, 16`, whose lane bit sits at bit `lane` in the wave: +- preserving: `s_andn2_b32 M, M, exec_lo` and `s_or_b32 M, M, T`, with T written in the block by a `v_cmp` or an + `s_and` of exec and a lane mask. A skipped lane keeps its bit, so M needs no zeroing, but M's last write before the + branch must itself hold lane bits (no branch or branch target after it); +- compare: a `v_cmp` (not `v_cmpx`) into M, only when `s_mov_b32 M, 0` (or `s_movk_i32 M, 0`) is the last write before the branch; +- all ones: `s_orn2_b32 M, X, exec_lo`, X a lane mask, only when `s_mov_b32 M, -1` is the last write before the branch. +Zeroing and all-ones writes do not mix, and any other write of M that no later zeroing or all-ones write overwrites +keeps the refusal. + The block is still refused in these cases: -- a definition that is live at the join, other than the lane mask above (or one of its conditions fails: zeroing - with a value other than 0 or missing, a branch or a branch target between the zeroing and the branch, a write - of M that is not from exec, a `vcc_hi` or 64-bit write, a whole-mask read after the join); +- a definition that is live at the join, unless the absorbed-read or narrowed-mask rule proves every read of it + or it is the lane mask above; a lane mask with a failed condition stays refused (zeroing with a value other + than 0 or missing, a branch or a branch target between the zeroing and the branch, a write of M that is not + one of the forms above, a `vcc_hi` or 64-bit write, a whole-mask read after the join); - any other exec write: exec set from a compare alone, restored from a mask saved before the block or on only - some of the paths, written by a form the pass does not follow (`s_orn2`, `s_nand`, `s_nor`, `s_xnor`, `s_not`, + some of the paths, written by a form the pass does not follow (`s_orn2` into exec, `s_nand`, `s_nor`, `s_xnor`, `s_not`, the other saveexec and wrexec forms), written in a block that a branch from outside enters (a proven calculated `s_setpc_b64` jump counts), or restored from a copy of the other exec half; - an effect outside scalar registers, such as a scalar store or atomic, a barrier, `s_endpgm` or `v_writelane`; @@ -14836,6 +16043,46 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_' -V python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 ``` +### Counted loop exit inside a compute EXEC-zero block (#2645 T2) + +The 112-byte gfx1013 fixture in `tests/startup_gfx2hlsl_compute_check.py` starts with eight +lanes and keeps lanes 0–2 in two saved masks. At counter values 1, 2 and 3 it removes each +remaining lane whose ID is below the counter. The wave exits when the second mask becomes +empty. The wave and singleton traces both store `[9, 1, 2, 9, 9, 9, 9, 9]`. + +Reading the counter after restoring EXEC exposes the difference. The wave exits with 3 for +every lane. In the singleton model lanes 0 and 1 exit early with 1 and 2. Lanes 3–7 skip the +guarded block and take the latch until the counter reaches 4. The translator reports +`loop exit crosses a backward s_cbranch_scc0` for the early exit in both variants. +Run `python -B tests/startup_gfx2hlsl_compute_check.py` for the host controls and add +`binary llvm-mc-15` to reassemble the fixture. + +`subset_after` tracks pre-branch mask-subset facts (`sM <= EXEC`) across instructions and joins into `Stage.execz_refusals`, so saving `s22 <= EXEC` (or `s_mov_b32 exec_lo, s22` before `s_cbranch_execz`) proves `s_mov_b32 exec_lo, s22` inside the skipped block (#2645 T1). On the no-exit variant (`O-loop-subset`) DXC `cs_6_0` produces `[9, 1, 2, 9, 9, 9, 9, 9]` while `LOOP_BREAK_WORDS` still refuses `+0x30` with `loop exit crosses a backward s_cbranch_scc0`, and pre-branch narrowing (`s_and_saveexec_b32`, `v_cmpx_gt_u32`), mask overwrites, and unproven joins remain refused as `exec write`. + +### Scalar run before the EXEC restore at a compute exit target (#2645 T3) + +The 104-byte gfx1013 fixture `EXIT_RUN_*` in `tests/startup_gfx2hlsl_compute_check.py` narrows +EXEC to lanes with `tid.x < 6` before a guarded block. Inside it, `s_andn2_b32` removes the +breaking lanes from a saved EXEC mask and `s_cbranch_scc0` tests that mask. The staying path +installs the same mask into EXEC before its vector work. Both paths reach a scalar descriptor +load and wait, followed by `s_mov_b32 exec_lo, s21` to restore EXEC. + +For groups of up to 32 threads (`x * y * z <= 32`; larger workgroups are rejected and left for +follow-up work), the translator accepts this straight exit when the staying path's vector work is +lane-local and predicated off for exiting lanes. The shared run allows scalar ALU, loads and waits +with regular SGPRs. It must reach a restore from an unchanged copy of EXEC, and the two paths must +agree on the run's inputs and any scalar state used afterward. +The wave and singleton traces both produce `[9, 9, 9, KEY^3, KEY^4, KEY^5, KEY^6, KEY^7]`. +With three threads, the whole wave also takes the exit and both traces produce `[9, 9, 9]`. + +The wrong remask and a bypassed scalar write produce different values for lane 0 and are +refused. Additional controls cover unsafe scalar effects, incoming EXEC and live SCC, clobbered +and missing restores, invalid targets, and control flow or vector work in the run. The T2 loop +keeps its backward-latch diagnostic. Removing its latch still leaves two different remasks and +scalar counter work on the staying path, outside this proof. Run +`python -B tests/startup_gfx2hlsl_compute_check.py` for the host controls and add +`binary llvm-mc-15` to reassemble the fixture. + ### Startup compute formatted buffer reads The offline compute translator lowers `buffer_load_format_x`, `_xy`, `_xyz` and `_xyzw` using @@ -14904,6 +16151,17 @@ python -B tests/startup_compute_store_format_xyzw_check.py binary llvm-mc-15 Not covered here: hardware adapters, the `llvm-mc-15` `binary` step, formats with fewer than four channels (they write nothing), `OOB_SELECT` 1, a dispatch against a host view shorter than the guest range (the guard is checked only as emitted text), and runtime binding of the three entry constants. +### Startup compute address carry + +The startup compute translator accepts a numeric `s_add_u32 sN, a, b` followed +immediately by `s_add_u32 sN+1, 0, src_scc` when both execute in the same +basic block. The first add produces the low word and unsigned carry. The second +stores the carry as the high word and clears SCC. A branch directly to the high +add, a lane-mask addend or symbolic descriptor arithmetic keeps the refusal. +The `address-carry` fixture +adds group IDs 0 through 3 to `0xfffffffe` and reads back both words and the +final SCC. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|warp|hardware)$' -V`. + ### First active lane at compute entry The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the @@ -14959,8 +16217,16 @@ and produces a predictable wrong word. A second control swaps the two offsets. The RDNA 2 ISA describes a single access when the offsets coincide. This slice requires distinct offsets. [AMD RDNA 2 ISA, §10.4, LDS Access](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) -The startup translator accepts one straight-line, full-EXEC fill in a 1D -group, one group barrier, and reads from that initialized span. The fill +Case F-two-fills adds a second consecutive `ds_write_b32` using the same +address VGPR and a disjoint byte range. It writes `4 * X` at byte +`320 + 4 * X`. After the barrier, the peer read uses the first bank and +the broadcast reads 148 from the second bank. On WARP all 320 words matched. +Writing zero in the second store changed 128 words, first at word 1 (148 to +zero). The host check rejects a missing second store and a read in the gap. + +The startup translator accepts one straight-line, full-EXEC fill or two such +consecutive dword fills in a 1D group, one group barrier, and reads whose +individual accesses fit entirely inside an initialized span. The dword fill address is the entry X ID shifted left by two. Read addresses come from an immediately preceding literal move or AND with an aligned literal mask. The bounds check includes the instruction's byte offset. The LDS allocation @@ -14971,7 +16237,7 @@ the 32 KiB groupshared limit. The barrier becomes an unconditional and [HLSL group barrier](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/groupmemorybarrierwithgroupsync). ```powershell -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|(f-peer_|f-broadcast_|g-swapped-offsets_|g-overlap_)?(warp|hardware))$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|(f-peer_|f-broadcast_|f-second-fill_|g-swapped-offsets_|g-overlap_)?(warp|hardware))$' -V python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 ``` @@ -15035,6 +16301,23 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_refusals$' -V python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache ``` +## Startup translator descriptor words in VCC + +An `s_load_dwordx4` from a descriptor table can end at `s[104:107]` +because the translator tracks the four words symbolically (#2057). The same +tracking applies when `s_mov_b64 vcc, s[n:n+1]` copies two descriptor words +from an even-aligned pair into s106/s107. The source registers can then be +overwritten. A load through `s[104:107]` requires four consecutive words of +the same descriptor. Reading VCC as a mask before a new VCC definition is +refused, including on a branch path that bypasses the definition. + +`startup_gfx2hlsl_desc_vcc` checks the symbol copy, descriptor validation, and +mask refusals. The WARP and hardware variants assemble a direct and an aliased +pixel shader and compare both readbacks with the same four words. The +flat-parameter runner binds only entry constants, so the fixture supplies the +buffer bytes through an HLSL load function after checking the translated +resource key and load calls. + ## Startup translator: SMEM offset operands `tools/startup/gfx2hlsl.py` accepts these offset operands for the scalar memory loads ([issue #1674](https://github.com/R0Y00/Xbox2Windows/issues/1674)): @@ -15049,6 +16332,23 @@ python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache `off` names no offset at all, so it is translated exactly as the literal 0: the same emitted HLSL, the same descriptor offset for a table load, and the same fixed-word marking of an `s_buffer_load` result. Before this change, `s_buffer_load_dword s0, s[4:7], off` was refused with `operand 'off'`, and the `s_load` form with the misleading register-offset message. `tests/startup_gfx2hlsl_smem_offset_check.py` drives each load handler on a scalar symbol state with no machine code. It compares the `off` form of `s_buffer_load_dword`, `_dwordx2` and `_dwordx4`, of `s_load_dword` and `_dwordx2` from a root buffer and of `s_load_dwordx8` from a descriptor table with the literal 0, keeps the literal and `m0` behaviour above, and requires five other operand spellings to be refused by both kinds of load. With the `off` handling removed in-process, both `off` forms must be refused again. Test: `startup_gfx2hlsl_smem_offset`. Not covered here: whether the full set of locally refused shaders now translates, which needs local inputs. +## Startup translator: integer vector operations + +The `VEC_U` table of `tools/startup/gfx2hlsl.py` lowers these two- and one-source integer operations to single HLSL expressions, and no check ran them before: `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32`, `v_mul_lo_u32`, `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_not_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, `v_min_u32`, `v_max_u32`, `v_min_i32`, `v_max_i32` and `v_mul_u32_u24`. + +`tests/startup_gfx2hlsl_int_alu_check.py` draws them with the pixel fixture of the bit-operation check above. The shared runner is `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation to each of four pixels' flat inputs. The lanes alternate the `_e32` and `_e64` spellings (`v_mul_lo_u32` exists only as VOP3), and the four result words are compared exactly. + +The references follow the AMD RDNA 2 ISA reference: 32-bit wrapping arithmetic, `rev` shifts of S1 by S0[4:0], an arithmetic shift for `v_ashrrev_i32`, signed or unsigned comparisons by name, and the product of the low 24 bits for `v_mul_u32_u24`. Every operation has eight input sets (two draws). They include shift counts above 31, sign-bit values for the signed and unsigned pairs, wrapping products, and sources with bits above bit 23. + +Each operation also has a wrong lowering that must read its own mutated words in the first draw: +- add as subtract, the two subtract orders exchanged; +- a 24-bit multiply for `v_mul_lo_u32`, a full multiply for `v_mul_u32_u24`; +- OR, XOR and AND exchanged, NOT dropped; +- shift operands exchanged, the shift count masked to 4 bits, a logical shift for the arithmetic one; +- min and max exchanged, unsigned comparisons for the signed pair. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 64 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 32 mutated draws read their mutated words. The controls also keep modifiers (`clamp`, `-v`, `|v|`, `mul:2`) and wrong operand counts refused. `binary ` reassembles the pixel bodies (llvm-mc 19 here; the CI job passes llvm-mc 15). Tests: `startup_gfx2hlsl_int_alu_controls`, `startup_gfx2hlsl_int_alu_warp` and `startup_gfx2hlsl_int_alu_hardware`. + **Constant register offsets for `s_load_dword*`.** An SGPR that holds a known constant (`s_movk_i32 s9, 0x40` before the load) is translated as the literal offset, which reaches descriptors in a bindless heap. Limits: the proof is used only in shaders without branches, because symbols are not merged at control-flow joins; `s_movk_i32` sign-extends its 16-bit immediate, so `0x8000` and above become negative and stay refused; the run-time sampler heap index is unchanged; an SGPR with an unknown value, `m0`, and a total above 0xfffff stay refused. Measured on CPU only (translation checks); D3D12 and GPU behavior are not measured. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sload_const_offset$' -V` or `python3 -B tests/startup_gfx2hlsl_sload_const_offset_check.py`. [Part of #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) ### Scalar writes to and symbolic tracking of `m0` @@ -15066,10 +16366,14 @@ python -B tests/startup_gfx2hlsl_scalar_m0_check.py binary llvm-mc-15 ## Startup translator: uniform sources of v_readfirstlane_b32 +In a compute entry block, the translator can bound the bits of an untouched X thread ID by the local group size. For `((tid.x & mask) | scalar) >> n`, the result is `scalar >> n` if every possible thread-ID bit selected by the mask is shifted away. For `v_bfe_u32` with literal offset and width, the translator applies the extraction to the possible thread-ID bits first. If the following shift clears them all, the result is zero. The `masked-tid` and `extracted-tid` compute fixtures read both results after a branch and store one word per thread. Their controls retain a bit in the mask or enlarge the group enough to populate a previously zero bit in the field. + The startup shaders are compiled with FXC (shader model 5), which has no wave intrinsics. The translator lowers `v_readfirstlane_b32 sD, vS` to `sD = vS` only when it proves that `vS` holds the same value in every lane. The previous proof covered only a `v_cvt_i32_f32` of a fixed buffer word. An unproven source still produces `v_readfirstlane_b32 requires a proven uniform source` (see [issue #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723)). In straight-line code with a known `exec`, the proof follows `v_cvt_u32_f32`, `v_cvt_i32_f32`, `v_cvt_f32_u32`, `v_cvt_f32_ubyte0`, `v_mul_f32`, `v_fma_f32`, `v_fmaak_f32`, `v_rcp_f32`, `v_med3_f32`, and `v_mov_b32`, including e32 and e64 forms. Every source must be uniform. The float operations that lower operands as floats accept negation and absolute-value source modifiers. The float-result forms accept the modeled output modifiers `clamp`, `mul:2`, `mul:4`, and `div:2`. +The proof also follows pure 32-bit integer vector ops: `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32`, `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_not_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, `v_mul_lo_u32`, `v_mul_u32_u24`, `v_min_u32`, `v_max_u32`, `v_min_i32` and `v_max_i32`. Each lane computes the result from its own sources only (no carry-out, lane ID or cross-lane read), so uniform sources give a uniform result and a first-lane read of the chain (for example `(s27 + s27) << 1`, or a VGPR overwritten by a constant and then shifted) translates. A chain from the thread id or from a lane-mask scalar stays refused with `v_readfirstlane_b32 requires a proven uniform source`. The recomputed expression of a VGPR is kept only up to `UNIFORM_EXPR_LIMIT` (4096) characters, because a register used as both operands (`v10 = v10 + v10`) doubles the text each time; a chain past the limit has no recomputable expression, while an entry-block read still copies the VGPR. `tests/startup_compute_readfirstlane_check.py` reads the integer chain and the constant shift back on the GPU with pinned `dropped-int-read` and `dropped-const-shift` controls, and `tests/startup_gfx2hlsl_readfirstlane_uniform_check.py` covers the refused sources and the bounded doubling chain. + Uniform sources include inline constants and literals, SGPRs holding constants, user data or fixed buffer words, other SGPRs tracked as uniform, and VGPRs with an existing proof. A scalar result is tracked as varying when its expression depends on `vcc`, `exec`, `m0`, a varying scalar register, a VGPR without a proof, or a varying `scc`. Descriptor, pointer, and sampler symbols, and SGPRs holding a lane mask (a compare result, even from uniform operands), are treated as non-uniform sources. A 64-bit move proves its high word only from the source high word as it was before the move, never when the destination overlaps it, and a descriptor-path move carries a high-word symbol only when that symbol does not depend on the register's run-time contents. SCC follows the same dependency tracking, with saveexec and wrexec marking it varying. A scalar write to `m0` that also sets SCC judges SCC from the write's sources, so `s_and_b32 m0, vcc_lo, -1` makes it varying while a write from uniform scalars makes it uniform. Instructions whose SCC result is not modelled (`s_add`, `s_sub`, `s_min` and `s_max`, `s_wqm`, and scalar ops on symbolic descriptor words, which emit nothing) mark SCC varying. Scalar buffer loads track the original offset across every destination word, including when the emitted code saves it in a temporary. An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read takes no modifiers. In straight-line code and in the entry block of a program with branches (before the first branch target and before the first terminator), the proof and the read require known `exec` and the read copies the VGPR; past the entry block the read recomputes the definition instead (below). Every path reaches those instructions through the same instructions, so the program-order tracking is exact there. A branch back to the first instruction ends the entry block at the first instruction, because a loop re-enters it. It now explicitly checks for a single SGPR destination and a single VGPR source. @@ -15083,15 +16387,28 @@ Past the entry block of a program with branches, the read does not copy the VGPR A lane that was inactive at the definition keeps an older VGPR value; the recomputed expression gives every lane the first active lane's value instead. `exec` need not be known at the definition. A conditional branch between the definition and the read is a fall-through, not a join, and is accepted. The one case where hardware can differ is a read with no active lane: it returns lane 0's VGPR, which the program cannot rely on. `tests/startup_gfx2hlsl_readfirstlane_recompute_check.py` checks the accepted forms (including one-path scalars and uniform loop counters both inside and after loops) and refuses each condition above, including a definition under a narrower `exec` than the read, a rewritten scalar input, a loop back edge, a divergent `else`-arm write before a join, a non-uniform loop back-edge and a join where two definitions reach. +A compute buffer load through a read-only descriptor and uniform address is also accepted past the entry block when the entry EXEC mask is still known. The lowering saves the uniform value in a function-scope temporary so the read uses the value held when the load ran, even if the offset scalar later changes. A narrowed mask may be empty. In that case RDNA 2 reads the previous lane-zero VGPR, which an unguarded reload cannot reproduce. Branch targets, EXEC writes and VGPR overwrites invalidate the proof between the load and read. A loop may revisit the load after changing EXEC. The lowering follows control-flow edges from EXEC writers to catch this case, including detours outside the loop's instruction range. A loop that changes EXEC only after it exits still qualifies. The source-built controls cover scalar and vector addresses, the second dword, formatted loads, and a lane-zero sentinel followed by empty EXEC. + [`tests/startup_compute_readfirstlane_check.py`](../tests/startup_compute_readfirstlane_check.py) pairs that unit coverage with a source-built gfx1013 compute fixture (`(4, 1, 1)` local threads x `(2, 1, 1)` groups) containing both a one-path SGPR across a uniform forward branch join and a four-iteration uniform loop counter read via `v_readfirstlane_b32` inside the loop and after exit, machine-code refusal patches (non-uniform `s_cbranch_vccnz` back-edge, divergent `else`/`then` write before a join, lane-mask loop update) and 320-word GPU readback with pinned `dropped-one-path`, `dropped-loop-read` and `dropped-post-loop` negative controls. Verified with zero mismatches and zero D3D12 debug-layer errors or warnings on Windows 11 25H2 (build 26200.9974) across WARP 10.0.26100.9818 and an AMD Radeon RX 7900 XTX (driver 32.0.32029.2010). `tests/startup_gfx2hlsl_readfirstlane_uniform_check.py` translates short sequences through the stage's dispatch without shader machine code. It checks emitted assignments for the listed operations, supported modifiers, and in-place and cross-register chains, the median of three that clamps a scalar to `[0, 0.5]`, including the unsigned-division reciprocal estimate (`v_cvt_f32_u32`, `v_rcp_f32`, `v_mul_f32` by `0x4f7ffffe`, `v_cvt_u32_f32`) that compiled shaders read back with `v_readfirstlane_b32`. That chain stays refused from a lane-varying source or a lane mask, across an `exec` write or an overwrite, and from a definition in another block. Refusal cases cover varying sources and offsets, overwrites that invalidate a proof, WQM, a restored `exec` copy and other exec writes, lane masks, overlapping and descriptor-path 64-bit moves, branch and operand restrictions (a read at the first branch target, in a loop whose header is in the entry block, at a backward branch target, in an entry block re-entered by a loop, or after `s_endpgm` in a branch-free program; a read after the first terminator is recomputed), and constructor-less probes with incomplete tracking state. The negative control empties the allowlist and requires every accepted sequence to refuse. ```powershell -ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(uniform|recompute)|startup_compute_readfirstlane(_(warp|hardware))?)$' -V +ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(uniform|recompute|load_recompute)|startup_compute_readfirstlane(_(warp|hardware))?)$' -V python -B tests/startup_compute_readfirstlane_check.py --llvm-mc llvm-mc-15 ``` +The same checks exercise a [four-thread resource-index waterfall](../tests/startup_compute_waterfall.py) for #2644. +`v_readfirstlane_b32` selects a key and the following `v_cmpx_eq_i32` enables the lanes sharing that key. A saved +copy of `exec_lo`, `s_andn2_wrexec_b32` and a backward `s_cbranch_scc1` serve the remaining lanes. Each participating +lane can execute one visit with its own key when the body performs proven lane-local operations and its temporary +scalars are dead at exit, or are live at exit only when they are key-independent: a scalar written from constants or +other loop-invariant inputs, without reading the key or a key-dependent scalar, holds the same value in every pass. The fixtures vary the active count from zero to four, restore EXEC, and check both an +arithmetic result and a key-dependent byte offset in one fixed raw buffer. A read of the group's active mask, +a store inside the loop, a live-out scalar that depends on the key (or is computed from it) or a key-selected +descriptor keeps an instruction-specific refusal. The fixtures include a key-independent live-out read after the loop +(accepted, checked against a D3D12 WARP readback) and key-dependent live-outs (refused). + ## Desktop audio render sink `startup_audio_output` drives a small WASAPI shared-mode render sink ([`audio_sink.h`](../src/startup_stubs/audio_sink.h)) with generated PCM blocks. It is the first slice of [issue #1145](https://github.com/R0Y00/Xbox2Windows/issues/1145). The sink takes `submit(format, frames, bytes)`, converts the block to the endpoint mix format (32-bit float or 16-bit PCM only) and records the first accepted block, the submitted format, per-block frame counts and peaks, consumed frames (submitted minus `GetCurrentPadding`), the `IAudioClock` position, the drained interval and the recovery. The fixture runs three cases in one process: no submission; eight 40 ms blocks with distinct amplitudes, one of them intentionally silent; and a producer that withholds the next block until the queue is empty, then resumes. @@ -15147,6 +16464,54 @@ and array views and for unreadable arguments. `startup_address_srv_hardware` and `startup_address_srv_warp` also match the five lines of their refused calls (zero address, other width, interior address, a buffer view, a destination off the heap) and show the descriptor unchanged. +### Copied raw vertex-buffer SRVs + +`startup_copied_vertex_srv` publishes 512-byte and 256-byte raw views of the +same source-built buffer into separate slots. It copies each view in turn to +the bound table slot, compares the guest-visible descriptor bytes with the +source slot, and draws a band with that binding. The vertex shader reads +distinct words at byte offsets 224 and 288. All 32 pixels must show both words +with the full view, only the first word with the stale short view, and both +words again after copying the full view back. This covers the copy and lookup +sequence through slot 24 for #2695. The descriptor producer in the executable's +diagnostic run remains unidentified. + +The same test also copies views of two independent placed buffers into one +table. It checks both guest records after each copy, then reads the same +byte offset of each buffer in one vertex shader. Swapping the two views +exchanges the red and green channels, and restoring them restores both +channels. As a control, both manifest bindings name the first record. +That makes both channels match the first record in all 32 pixels while the +guest records remain distinct. + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -R '^startup_(copied_vertex_srv|address_buffer_srv|frame_copy)_(warp|hardware)$' -V +``` + +### Direct indexed draws after CPU writes + +For a direct translated draw with no vertex-stream SRVs, the shim binds a +live placed index-buffer alias when the drawn range and alignment are known. +The recording holds the desktop resource. The draw can then consume CPU +changes completed before submission, as required for CPU-accessible buffers +by [ID3D12Resource::Map](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map#advanced-usage-models). +Draws that slice and rebase a vertex stream still use the recording-time +index snapshot together with the stream range computed from it. + +`startup_direct_index_late_write` reuses the source-built #2714 repro. It +draws a visible or fully clipped triangle and compares all 32 pixels after +the fence. Unchanged controls, both directions of a pre-submit rewrite, and +a 32-bit index view with one leading decoy element distinguish the requested +range and the time at which its contents are read. The fixture requires +support for opening existing heaps. It does not identify the index writer +or geometry used by an executable trace. + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -R '^startup_direct_index_late_write_(warp|hardware)$' -V +``` + ```powershell cmake --build --preset release --target startup_memory_srv_report_check startup_stream_consumer d3d12_xs_shim ctest --preset release --no-tests=error -R '^(startup_memory_srv_report|startup_address_srv_)' -V @@ -15264,17 +16629,24 @@ a partial-tile BC view does after a later row copy. An upload of a console-layout texture owns its upload buffer. The buffer and the texture stay referenced by the recording and by each submit of it until the queue has completed that submit; the shared -upload ring, which is reused without waiting for a queue, is not used. `startup_address_console_gate_{warp,hardware}` +upload ring is not used. `startup_address_console_gate_{warp,hardware}` starts by closing and resetting an unsubmitted recording of payload 0, then records the identical bytes again. It makes the queue wait on a fence the fixture holds (queue slot 17), then records and submits eighteen lists on one list object, resetting the allocator and the list between them. Each republishes one 2048 by 2048 RGBA8 texture at `0x109` (16 MiB) from the same address with a new payload and draws it, payload 0 over the left half of the target and the others over the right half. No submit may complete before the fixture signals the fence. After the last one completes, the left half must hold payload 0 and the right half payload 17, and the log must report eighteen retained submits released. -`startup_address_console_gate_ring_{warp,hardware}` is the control: with -`X2W_TEST_ADDRESS_UPLOAD_RING=1` (fixtures only) the same uploads come from the 256 MiB ring, the -later ones pass over the bytes of payload 0 before the queue copies them, and the left half must not -hold payload 0. +`startup_address_console_gate_ring_{warp,hardware}` uses the shared ring +instead. It requires a reservation refusal after exhaustion, payload 0 +preserved on the left, the null view on the right, and no retained-upload +release line. The ring no longer reuses live storage. The revised Windows +readback control remains unmeasured on macOS. +`startup_address_console_gate_ring_reuse_{warp,hardware}` runs the same +sequence, opens the gate, waits until every submit has completed and then +draws payload 18 from the ring over the right half. That reservation must not +be refused ([#2837](https://github.com/R0Y00/Xbox2Windows/issues/2837)). With +chunk reuse disabled, as before the fix, it fails while `gate_ring` still +passes. The equations are checked against addrlib and against the three existing layout headers, not against console memory. Which layouts a given console build writes for which textures is not established by @@ -15287,6 +16659,73 @@ ctest --preset release --no-tests=error --output-on-failure -R '^startup_gfx10_l ctest --preset release --no-tests=error --output-on-failure -j 1 -R '^startup_address_(console|console_gate|console_gate_ring|bc_view|srv)_(hardware|warp)$' ``` +#### Volumes in the 4 KiB standard layout + +Slot 70 also reads an uncompressed 3D texture whose layout is `0x105`, at first a single mip. addrlib lays it +out in thick 4 KiB blocks (`GFX10_SW_4K_S3_PATINFO`). `startup_gfx10_volume` needs no device. It +checks the address bit of every x, y and z bit against the restated one-pipe rows for the five element +sizes, the block sizes, and the order of blocks in a 17 by 17 by 17 RGBA8 volume. It also checks that +the elements of ten volumes (odd sides included) have their own bytes, that they tile and detile back +to their rows, 15 layouts on either side of the accepted set, six slot 70 descriptions and seven +views. `startup_gfx10_volume_thin_control` lays each volume out as a thin 2D array of its layers and +must fail. `startup_gfx10_volume_addrlib` compares the size and every element address of 190 volumes +(276,885 addresses) with `Addr2ComputeSurfaceInfo` and `Addr2ComputeSurfaceAddrFromCoord` +(`ADDR_RSRC_TEX_3D`, `ADDR_SW_4KB_S`) on the Navi21 configuration the other addrlib checks use; it +skips (77) when the build has no addrlib (`-DXBOX2WINDOWS_ADDRLIB_DIR`). + +`startup_address_console_{warp,hardware}` now also draws two volumes, RGBA8 17 by 17 by 17 and 33 by +9 by 18, whose backing it builds in Python from the same S3 row. Each target tile of the volume's +width and height loads one depth layer, and every layer must appear. All 65,536 pixels must match. +A third volume, RGBA8 64 by 8 by 40, takes 163,840 bytes in the layout, but its desktop footprint +rounded to 64 KiB is only 131,072. It must be held as `console_layout_beyond_xg_size`. Before this +change the hold counted that footprint once for each of the 40 layers, and the volume would have been +published. + +Two local mutations were run once and are not registered tests: the layer pitch of the upload set +to zero, and the hold counting one footprint per layer. Each fails `startup_address_console_warp`: +the first on the first volume's pixels, the second on the held volume. + +Volumes with a mip chain are read too. Each layer of blocks holds that layer of every mip: the tail +block first, then the mips from the smallest to the largest. A mip at most a block wide and half a +block high goes in the tail while at most five mips remain, at an origin read from its byte offset +in the tail block. `startup_gfx10_volume` checks the addresses of a 32 by 32 by 32 RGBA8 volume with +six mips: 11 blocks to a layer, mip 1 after the tail block, mip 0 after mip 1, and mips 2 to 5 at +(0,8), (4,4), (4,0) and (0,4) in the tail block. It also checks the distinct bytes and tile/detile +round trips of every mip of ten chains (a tail from mip 0, a chain with no tail, odd sides, a deep +volume whose depth allows the mip count), and the mip chains slot 70 takes and the views of them it +allows. `startup_gfx10_volume_tail_control` puts every tail mip at the start of the tail block and +must fail. `startup_gfx10_volume_addrlib` now also compares every mip count of four chains for each +element size: 305 volumes and 12,704,487 element addresses with 0 mismatches. + +`startup_address_console_{warp,hardware}` draws four mips of two chains, RGBA8 32 by 32 by 32 with +six mips (mip 1, and mip 3 in the tail) and 20 by 24 by 16 with five mips (mip 1, and mip 3 in the +tail), from a backing that holds every mip with its own texels. All 65,536 pixels of each must match. +A local mutation that drops the tail origins of a volume, run once, fails it on the first tail mip, +which then reads another mip's texels. A chain whose layout runs past the size the XG stand-in +reports is held as before: RGBA8 33 by 9 by 18 with six mips takes 135,168 bytes in the layout against +65,536 reported. + +Block-compressed volumes are read too. addrlib turns the texel sides of a BC volume into 4x4 blocks +before it lays the volume out, and does not divide the depth: the volume is the volume of its blocks, +each one depth layer deep, with every mip size counted in blocks from there. `startup_gfx10_volume` +checks that BC1 64 by 64 by 16 with five mips and BC7 48 by 20 by 9 with three mips take, element for +element, the addresses of the 8-byte and 16-byte volumes of their blocks, and adds the distinct bytes +and round trips of seven BC volumes (BC1 to BC7, with and without a chain, sides that are not powers +of two). `startup_gfx10_volume_bc_control` sizes a BC volume by its texel sides instead and must fail; +it fails four checks. `startup_gfx10_volume_addrlib`, passing each BC format to addrlib as itself, now +compares every mip count of four chains for each of BC1 to BC7 too: 501 volumes and 13,205,290 +element addresses with 0 mismatches. + +`startup_address_console_{warp,hardware}` draws three BC1 volume mips: 48 by 40 by 12 with one mip, +and mips 1 and 3 (the second in the tail) of 64 by 64 by 8 with five mips. Each block is one solid +colour, and all 65,536 pixels of each must match. A local mutation that sizes the thick layout by +texels instead of blocks, run once, fails it on the first BC volume. + +```powershell +ctest --preset release --no-tests=error --output-on-failure -R '^startup_gfx10_volume' +ctest --preset release --no-tests=error --output-on-failure -j 1 -R '^startup_address_console_(hardware|warp)$' +``` + ### Six BC5/BC7 mips on a 64 KiB standard layout `startup_xg_bc_chain_{warp,hardware}` uses a source-built 1024×1024 BC5_UNORM or BC7_UNORM texture with six mip levels, one slice, one sample, explicit layout `0x109` (64 KiB standard, no XOR), default alignment and zero flags. The guest chain occupies `0x160000` bytes. The six offsets starting at mip 0 are `0x60000, 0x20000, 0x10000, 0x8000, 0x4000, 0x2000`. The three smallest mips share tile zero. These offsets and all 87,360 visible block addresses were checked with `Addr2ComputeSurfaceInfo` and `Addr2ComputeSurfaceAddrFromCoord` on the pinned Navi21 configuration. [AMD addrlib revision](https://gitlab.freedesktop.org/mesa/mesa/-/tree/5c142e46f3f6e752ed745fd48912ebb8fad67145/src/amd/addrlib) · [XCL comparison](https://github.com/ivall/xcl/blob/64b3f35599bb7102f55d640e1a791e7d6dd3b175/crates/xcl/src/gpu/tiling.rs) @@ -15418,6 +16857,8 @@ The [MASM fixture](../tests/cpu/sse4a.asm) exports 24 translated `op_*` function Not covered by this experiment: non-temporal cache-bypass hints, runtime `offset + width > 64` hardware-undefined behavior in register-form `extrq`/`insertq`, control flow or nonvolatile prologues, and title CPU code execution. +Not covered by this experiment: host segment-base writes (`wrfsbase`/`wrgsbase`, which require an explicit isolation/restoration profile), cross-thread `FS_BASE`/`GS_BASE` migration, and title CPU code execution. + ## Host-CPU RDFSBASE, RDGSBASE, and RDPID lifting in cpu_switch_aot [The switch translator](../tools/cpu_switch_aot.py) adds an opt-in `--host-cpu` (`host_cpu=True`) mode lifting read-only `rdfsbase`, `rdgsbase` (32- and 64-bit register forms), and `rdpid` (64-bit register form) from `docs/coverage/x64_zen2.tsv` group `Integer` to the `` intrinsics (`_readfsbase_u32`, `_readfsbase_u64`, `_readgsbase_u32`, `_readgsbase_u64`, `_rdpid_u32`): @@ -15470,11 +16911,26 @@ The [MASM fixture](../tests/cpu/vex_parity.asm) and [differential check](../test ctest --preset release --no-tests=error -R '^cpu_aot_vex_parity$' -V ``` +## Startup translator: reciprocal, roots, exp2 and log2 + +The `VEC_F` table of `tools/startup/gfx2hlsl.py` lowers six operations to HLSL with no check that ran them before: `v_rcp_f32` and `v_rcp_iflag_f32` to `1.0 / x`, `v_sqrt_f32` to `sqrt`, `v_rsq_f32` to `rsqrt`, `v_exp_f32` to `exp2` and `v_log_f32` to `log2`. `tests/startup_gfx2hlsl_float_transcendental_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation per lane on flat inputs, alternates the `_e32` and `_e64` spellings, and compares the four result words exactly. + +Every input is a power of two, or 0 and 9 for the square root, so every result is exactly representable. The check therefore tests which function each operation is lowered to and the base 2 of `v_exp_f32` and `v_log_f32`. It does not test how many ulps an adapter's approximation may be off. + +Adapters need not return these results exactly. `v_log_f32` accepts 4 ulps per lane, and the other operations stay exact. The Direct3D 11.3 functional specification (section 22.10.8) bounds `log` to 2^-21 relative error, or 2^-21 absolute error for inputs in [0.5, 2]. In this fixture, either bound is at least 4 ulps of the binary32 result. The DXIL documentation gives no accuracy for `Log`. The renderer still compares exactly. The runner accepts a mismatch only when every lane it reports as `actual=` is within the bound. The mutated draw must read words within the bound of the mutation and outside the bound of the reference. A run whose debug layer reports an error still fails. A ulp bound is effectively exact where the result is 0, as for `log2(1)`: this is much tighter than the absolute 2^-21 the specification allows, and all three adapters return 0 there. + +Each operation has a wrong lowering whose first draw must read its own mutated words: +- `2.0 / x` for the reciprocals; +- sqrt and rsqrt exchanged; +- the exponent off by one; +- the logarithm plus one. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 24 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 12 mutated draws read their mutated words. On an NVIDIA GeForce RTX 4090 (driver 32.0.16.1088, debug layer enabled, 0 errors), the same 24 and 12 pass with the bound, through both compilers (#2797). Three `v_log_f32` lanes are not exact: `0.125` reads `c03fffff` (1 ulp above -3.0), `2^-20` reads `c19fffff` (1 ulp above -20.0) and `0.5` reads `bf7ffffe` (2 ulps above -1.0). With the bound at 0, the first FXC draw fails on `c03fffff`, as reported. With the bound at 1, the FXC mutated draw fails: it reads `bffffffe` for `log2(0.125) + 1`, 2 ulps above -2.0. `v_sin_f32` and `v_cos_f32` are not covered: their results at the few exact points depend on the approximation. Tests: `startup_gfx2hlsl_float_transcendental_controls`, `startup_gfx2hlsl_float_transcendental_warp` and `startup_gfx2hlsl_float_transcendental_hardware`. ### gfx1013 pixel DPP16 quad broadcast -The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted only in a straight-line pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. Without that proof the instruction is refused, as are swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `bound_ctrl:0`, non-VGPR sources and vertex stages. `fi:1` is accepted with the proof and changes nothing, since no source lane is disabled. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. +The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted in the entry straight-line prefix of a pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. A later uniform loop or forward branch elsewhere in the same stage does not drop that proof (the M200-01/003 shape). Without the proof the instruction is refused, as are a broadcast after a branch target, after EXEC changed, or with divergent EXEC before the broadcast, swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `bound_ctrl:0`, non-VGPR sources and vertex stages. `fi:1` is accepted with the proof and changes nothing, since no source lane is disabled. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. -Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V`. The controls cover the translation, every refusal and the missing `s_wqm`; the WARP and hardware draws compare all 256 pixels of two fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. This does not establish full-game startup. +Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V`. The controls cover the translation, every refusal, the missing `s_wqm`, the loop fixture and the divergent-EXEC control; the WARP and hardware draws compare all 256 pixels of the integer, float and loop fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. This does not establish full-game startup. ## Startup root signature changes @@ -15572,6 +17028,20 @@ rewrite the lowering to the uncapped `frac` and to a `min`-form cap and require ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fract$' -V ``` +## Startup scalar bit counts and scans + +`tools/startup/gfx2hlsl.py` lowers eight scalar bit operations that it used to refuse with `Unsupported`: `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_bcnt0_i32_b64`, `s_bcnt1_i32_b64`, `s_ff0_i32_b64`, `s_ff1_i32_b64`, `s_flbit_i32_b64` and `s_flbit_i32_i64`. Each writes one 32-bit SGPR. The counts set `SCC` to `result != 0`. The scans return `0xffffffff` when no bit qualifies and leave `SCC` alone. `s_flbit_i32_i64` counts the leading bits equal to the sign bit, so it complements a negative value before it counts. The 32-bit scan forms were already covered elsewhere and are not changed. + +Scope: the source is a register only (`s0` to `s105`, an even-aligned pair for the `b64` forms; an odd start is refused). Literals, inline constants, `exec`, `vcc`, `m0`, a pair that crosses `s105`, source or destination modifiers and a wrong operand count are refused. A source that holds a lane mask is refused with `... on a lane mask`; a destination that held a mask stops being one. The destination must be one SGPR in `s0..s105`. + +`tests/startup_gfx2hlsl_s_bit_scan_check.py` builds the SOP1 words, translates them, runs the emitted HLSL on the integer evaluator of `startup_gfx2hlsl_bit_alu_check.py` and compares every result with a loop-and-string reference written from the ISA description. The same file has a `draw` mode: a pixel stage loads literals into `s4`/`s5`, runs each of the eight forms on four lanes, and the adapter output words are read back against the same reference (FXC 5_1 and DXC 6_0). The fixture XORs the result with `0x3f000000` before the float export so every expected integer is carried as a finite normal bit pattern. A wrong-count reference must produce a readback mismatch. + +```bash +python3 -B tests/startup_gfx2hlsl_s_bit_scan_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bit_scan$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_s_bit_scan_warp$' -V +``` + ## Vulkan subnormal preservation in a pixel shader `tests/pixel_denorm_vulkan_check.py` compiles one source-built `ps_6_2` pixel shader with DXC for Vulkan 1.2 and draws it with `tests/vk_pixel_draw.c`. Seven operations (`1 * 2^-149`, `0x007fffff + 0`, `minnorm * 0.5`, `minnorm - 2^-149`, `2^-149 + 2^-149`, `-0x00000003 * 1` and `2^-149 * 2^23`) take or produce binary32 subnormals. The inputs come from a constant buffer so DXC cannot fold them, and each result word is read back from an RGBA32UI pixel. The reference is IEEE binary32 arithmetic in Python. `-denorm preserve` must match it on all seven; `-denorm ftz` is the negative control and must differ on at least one, which shows that the probe separates preserve from flush. A device with `shaderDenormPreserveFloat32` false is a capability skip, and a module that `spirv-val` or the driver refuses is a validation refusal; both are reported apart from mismatches. The check shows how a driver treats subnormals in this one shader. It does not show that translated shaders from `tools/pixel_aot.py` render the same bits under Vulkan. @@ -15639,7 +17109,11 @@ would be folded at compile time and the lowering under test would never run. The `0x7fc00000`, `0x40400000`, `0x3fc00000` and `0x3f000000`; the expected words are `0x3f800000`, `0x40000000`, `0x3fc00000` and `0x3f800000`. The control that counts restores the branchless helper in the same pair and requires a mismatch on the NaN lane alone: `0x40000000` where the ISA asks `0x3f800000`, the -other three lanes unchanged. A negative control that passes is reported as a failure, not accepted. +other three lanes unchanged. A negative control that passes is reported as a failure, not accepted. The +restored helper computes its median as `precise`. Without it, an RX 5700 XT (driver 32.0.21045.29003) folded +the median against the constant bounds into a clamp and drew the ISA's `0x3f800000` on the NaN lane with FXC +and DXC, so the defect escaped. With `precise` that adapter and WARP draw `0x40000000` there and match the +other three lanes. [Issue](https://github.com/R0Y00/Xbox2Windows/issues/2730) ```powershell cmake --build --preset dev --target offscreen_check @@ -15660,7 +17134,7 @@ Measured on 2026-11-25 with base `25317c63` plus this change, DXC 1.10.2605.37 a | NVIDIA RTX 3060 Laptop, driver 620.70.06, `shaderDenormPreserveFloat32` = 0 | none | exit 77 | | NVIDIA RTX 3060 Laptop | `--allow-denorm-mismatch` | exit 1, `pixel_mismatch x=16 y=0` | -The NVIDIA mismatch is a measurement: in that pixel, byte 37 reads back `0x3e14a000` where the reference has `0x3e148000`. The reference comes from `export16` in `tools/pixel_aot.py`, which converts with `f32tof16`, steps the half down by one when `f16tof32` of it exceeds the input in magnitude, and widens it again, so the value is rounded toward zero to a binary16. One hypothesis, not tested further, is that the NVIDIA compiler folds `f16tof32(f32tof16(x))` to `x`, so that rounding does not happen. A compute probe on the same device gave the correct binary16 `0x30a5` and a widened value `0x3e149495`, which is consistent with that hypothesis but does not prove it. It is not known whether the NVIDIA D3D12 driver behaves the same way. The run is a diagnostic and says nothing about NVIDIA's subnormal handling. +The NVIDIA mismatch was in pixel x=16, byte 37: `0x3e14a000` where the reference has `0x3e148000`. The reference comes from `export16` in `tools/pixel_aot.py`, which rounds toward zero to a binary16 and widens it again. It used to convert with `f32tof16` and `f16tof32`, and the NVIDIA compiler folded `f16tof32(f32tof16(x))` into `x`, so the rounding did not happen (a compute probe on the same device gave the correct binary16 `0x30a5` and a widened value `0x3e149495`). `export16` is now built on the integer helpers `narrow16` and `widen16`, and the same NVIDIA run with `--allow-denorm-mismatch` exits 0. The NVIDIA D3D12 driver read `0x3e148000` on an RTX 4060 before the change. The diagnostic run says nothing about NVIDIA's subnormal handling. This shows that these shaders produce the same bits on two Vulkan drivers for the covered modes. It does not cover the other `offscreen_check` modes or title-memory cases, and it is not a D3D12 result. @@ -15687,6 +17161,52 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. +## Concurrent calls through a startup debugger hook + +The startup debugger holds every other thread while it steps one over a hooked function, so two threads entering the same hooked function are both traced ([#1281](https://github.com/R0Y00/Xbox2Windows/issues/1281)). A run ends with `hook windows: ... unprotected=U`, the windows in which another thread could not be held or the 2 s deadline passed; `--suspend-others 0` (`run.ps1 -SuspendOthers 0`, `run.sh --suspend-others 0`) turns the holding off, which frame-rate and load-time runs need (holding cut the post-first-run load to 3–5 fps on one host). See [Concurrent calls through a hooked function](startup-runtime.md#concurrent-calls-through-a-hooked-function). + +```powershell +cmake --build --preset dev --target startup_launch_probe +ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V +``` + +### Startup shader translator: `v_bfm_b32` + +`tools/startup/gfx2hlsl.py` now lowers the gfx1013 bit-field mask `v_bfm_b32` (a VOP3-only instruction: the bare and `_e64` spellings translate, `_e32` is refused) that it used to refuse. The result is a mask of S0[4:0] ones shifted left by S1[4:0], emitted as `(((1u << (a & 31)) - 1) << (b & 31))`, so a width of 0 gives 0 and a shift past the top drops the bits. `v_bfm_b32` is a row of `tests/startup_gfx2hlsl_bit_alu_check.py`: the emitted text runs on its integer evaluator over 1368 width/offset pairs against a plain-integer reference, a swapped width/offset mutation must read other words, and the `draw` mode renders the translated pixel stage on the adapter (FXC 5_1 and DXC 6_0) and reads the words back. Source modifiers, `clamp` and output modifiers are refused with `Unsupported`, as for the sibling integer operations. The WARP draw of the same formula is the existing `pixel_aot_bfm_` test. + +```bash +python3 -B tests/startup_gfx2hlsl_bit_alu_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_bit_alu_(controls|warp)$' -V +``` + +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`. Of the compute root arguments, only root SRVs (slot 43) reach the desktop list: slot 35 records descriptor tables without setting them, and slots 37, 39, 41 and 45 have no handler yet, so a dispatch under any other argument would run with it unset. The first 16 refusals in a process are logged as `x2w-render Dispatch(x, y, z) refused: `. + +`tests/startup_list_dispatch_check.cpp` checks the decision without a device; its five mutated runs must fail. `tests/startup_list_dispatch_native.cpp` drives slots 86, 25, 33, 43, 148, 14, 9 and 139 of the stand-in on a desktop device, on WARP and on a hardware adapter (77 without one), with the debug layer when it is installed. Each refused case must log exactly one refusal line with the expected reason: a root SRV never set, a rejected or misaligned slot 43 replacement after a valid one, a root changed and changed back without slot 43, a pipeline built against another root, a root with a descriptor table, a root with a static sampler, an unset root SRV with zero groups, more than 65535 groups, a closed list, and a Reset list without new bindings. A forwarded case must log no line. Around each call on an open list the fixture records a pipeline-statistics query on the desktop list: `CSInvocations` must be 4 per group for a forwarded call and 0 for a refused one. The fully bound call is recorded alone and counted first, so a slot 14 that records nothing fails on its count. Each of the three recordings is executed to a fence, and the debug layer must report no error. The shader only declares its root SRV, so this shows that the desktop `Dispatch` is recorded and runs, not what a shader reads through the bound SRV. The `skip_srv` control drops slot 43 from the first forwarded case and must report that case as refused. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check startup_list_dispatch_native +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` + +## Startup translator: explicit-gradient image_sample_d + +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_d` form in a pixel stage to `tex.SampleGrad(smp, uv, ddx, ddy)`. The address dwords are ddx, then ddy (one register per coordinate axis each), then the coordinates: six registers for 2D, seven for a 2D array (slice last), nine for a volume (a contiguous nine-dword volume address encoded as a sixteen-register range is trimmed to nine). Only `dim:`, `dmask:` and the cache-policy bits `dlc`, `glc`, `slc` are accepted. + +Refused with a named reason: `image_sample_c_d` (it would need `SampleCmpGrad`, shader model 6.8; only `image_sample_c` and `_c_lz` are lowered), `image_sample_d_o` and every other offset, bias, clamp, `a16`, `tfe` or `lwe` form, an empty `dmask`, a 1D image, and an address count that does not match the dimension. + +The guest sampler LOD range is kept: a constant sampler carries MIN_LOD and MAX_LOD to the static sampler through the same `smpl` line as `image_sample`, `_l` and `_lz` (sampler words `(0, 0, 0x04000000, 0)` stay capped at mip 0), with the same refusals for a LOD bias and for MIN_LOD above MAX_LOD. A mip filter of 0 keeps the ordinary sampler, and a heap sampler is not validated and is logged once per module. + +Verified: the Python translation checks (address order, refusals, the LOD cap, fixture words against `llvm-mc`) and a D3D12 draw on WARP and hardware (`tests/startup_image_sample_d_draw_check.py`): four `SampleGrad` probes on a three-mip, two-slice fixture read back against a CPU reference, with a MAX_LOD 0 sampler and an implicit `Sample` as negative controls. + +```bash +./out/pe-env/bin/python -B tests/startup_image_sample_d_check.py +./out/pe-env/bin/python -B tests/startup_image_sample_d_check.py binary +ctest --preset dev --no-tests=error -R "^startup_image_sample_d" -V +ctest --preset dev --no-tests=error -R "^startup_image_sample_d_draw_(warp|hardware)$" -V +``` + ### Startup 24-bit multiplies, v_xnor_b32 and the funnel shifts `tools/startup/gfx2hlsl.py` translates `v_mul_i32_i24`, `v_mad_i32_i24`, `v_mul_hi_i32_i24`, `v_xnor_b32`, `v_alignbit_b32` and `v_alignbyte_b32` (VOP2 and VOP3 spellings) in 32-bit integer arithmetic, with no 64-bit type. The signed forms sign-extend the low 24 bits of each source with a left shift of 8 and an arithmetic right shift; the high product is assembled from 12-bit halves so that it stays inside 32 bits. @@ -15695,6 +17215,17 @@ Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and `tests/startup_gfx2hlsl_mul24_align_check.py` translates each instruction, evaluates the emitted text on the CPU against a reference written with unbounded integers, and checks that `v_mul_hi_u32_u24` is refused. Run with `python3 -B tests/startup_gfx2hlsl_mul24_align_check.py` (`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mul24_align$' -V`). `tests/startup_gfx2hlsl_mul24_align_draw_check.py` draws the six translated instructions through FXC `ps_5_1` and DXC `ps_6_0` and compares the GPU readback with the same reference (`startup_gfx2hlsl_mul24_align_warp` and `_hardware`); both compilers run before the test fails, so one compiler's failure does not hide the other's result. The draw covers the six translated instructions only. +## Startup list Dispatch + +Command-list slot 14 (`Dispatch`) is recorded on the desktop list only when the list is open and direct or compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares no static samplers and only root SRV parameters (slot 43), the compute pipeline was built against that same root signature, every root SRV the root declares was set since the root was bound (a rejected or unaligned replacement clears its binding), and every group count is at most 65535. Zero groups on an axis is forwarded and runs nothing. A root with other parameters is refused with `compute root arguments are not forwarded`, a pipeline from another root with `compute pipeline was built against another root signature`, an unset or rejected root SRV with `a compute root SRV is not bound`, because this path forwards none of the compute root-argument slots (35, 37, 39, 41, 45) to the desktop list and the dispatch would run with them unset. Other refusals are logged as `x2w-render Dispatch(x, y, z) refused: `. + +Only the decision is checked: `tests/startup_list_dispatch_check.cpp` runs without a device and its five mutated runs must fail. Executing a dispatch on a GPU, with real results read back, is not verified yet. + +```powershell +cmake --build --preset dev --target startup_list_dispatch_check +ctest --preset dev --no-tests=error -R "^startup_list_dispatch" -V +``` + ## Non-constant scalar symbols at branch targets in the startup translator Follow-up to #2279, which drops scalar constants at a join that another path writes, over the textual range between @@ -15717,6 +17248,152 @@ is 0, so bit 0 of the result is 0 (1 for `s_orn2_b64`) whatever S holds. This re a lane whose exec bit is 0 takes the branch; it is pure Python only, not run on a GPU, and its words are built from the field layouts rather than assembled. +## Translated compute Dispatch + +With a device slot 67 placeholder bound, command-list slot 14 looks up the translation of the pipeline's published request (`.txt` with `stage cs`, and `.cs.cso`) and records it on the desktop list. It binds, from the compute descriptor tables of slot 35: raw buffers named by 16-byte hardware buffer descriptors, and 2D textures named by the token of a view the caller created (device slot 18 for an input, slot 19 for an output the program stores `float4` to). `smp` manifest lines become static samplers, and entry values come from the compute root constants of slots 37 and 39. A buffer input must resolve to a complete GPU-backed range; a buffer output must be a placed buffer that aliases the caller's memory and allows unordered access; a texture view must be 2D, created on the desktop, and for an output have a float or normalized format that is not packed, on a texture that is not also an input of the call. Any other manifest line (other texture kinds, sampler heaps, comparison samplers, root views, entry values that are neither a root constant nor a buffer descriptor word) leaves the pipeline untranslated, and a Dispatch that cannot be bound completely is refused with one logged reason: no Dispatch is recorded and nothing is bound (the upload of an input texture the caller filled in memory may already be recorded; it only syncs content). No view is ever bound null. The entry values live in the compute root-constant store of #1975: a word no slot 37 or 39 call wrote since the compute root was set (slot 33 with another root, or a list reset) has no value and is refused with `an entry value was not set since the compute root`; setting the same root again keeps the words, and the graphics words of slot 40 are separate. + +`tests/startup_compute_dispatch_check.py` drives a source-built gfx1013 program through the stand-in's list on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back from the aliased memory. Controls in the same run: before the offline translation, without a Dispatch, and with the two descriptors exchanged, every output word must keep its sentinel. The two entry values arrive through slot 37 and slot 39, with other values written through slot 40 in between; `dispatch-same-root` must still give the expected words, and five refused modes must log their reason and keep the sentinels: a missing word, another compute root set and the first set again, a list reset, a compute root that is not the pipeline's, and one buffer named as input and output. `tests/startup_compute_dispatch_texture_check.py` does the same for a program that stores to a 32x8 RGBA16_FLOAT texture (1024 halves read back through CopyTextureRegion; controls: before translation, without a Dispatch, a texture without unordered access) and for the raw buffer program with a level-zero sample of a 1x1 texture XORed into each stored word (control: no view at the table entry). The texture output program is also bound under a manifest edited to declare no entry values. + +`startup_compute_dispatch_two_mips_` writes two distinct patterns through two UAVs of one RGBA16_FLOAT texture in the same translated Dispatch. The test compares all 1,280 half values in the 32×8 and 16×4 subresources, including the sentinel values outside the written rectangles. Before translation both mips keep their sentinels. Exchanging the two views moves the patterns to opposite mips and changes 64 half values relative to the ordered case. + +Every 300 render frames, `x2w-render upload ring: reserved MiB in reservations, refusals , capacity MiB` reports +cumulative successful reservations and their 512-byte-rounded sizes, including reservations in recycled chunks. +`refusals` counts reservation attempts that exhaust the allocator's available options. The submit-time rejection +of a list whose chunks were recycled is logged separately. `capacity` is the total allocated chunk size. +With `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, completed fenced submits can make chunks reusable sooner, +so cumulative reserved bytes can exceed capacity. These totals do not measure current occupancy. + +The log line `x2w-render compute dispatches: translated , refused , no translation , not modelled , builder gate refused ` follows the upload ring totals. The builder gate field counts dispatches refused by `X2W_COMPUTE_BUILDER_GATE`. The "not modelled" field counts calls whose manifest exists but holds a line the runtime does not bind. It is followed by a census: the refused calls per first refusal reason of their key, and every dispatched key by call count, each with its count, the calls recorded and the first refused table descriptor. + +The sampling fixture uses a 1x1 texture, so it does not tell sampler filter or address modes apart. Programs with other texture kinds, sampler heaps, the same texture as input and output, or buffer outputs in memory that is not aliased are not dispatched. + +The `startup_compute_live_retry_warp` and `startup_compute_live_retry_hardware` tests keep the device and +slot 67 pipeline alive across two fenced Dispatch calls. The first observes the missing translation and +preserves all 320 output words. The test runs `gfx2hlsl.py --pending` while the process waits, then checks +the second output against the source program once the one-second manifest poll interval has elapsed. +A second run keeps the manifest absent and checks both refusals and both untouched outputs. +Run the two backends with `ctest --preset release --no-tests=error -j 1 -R '^startup_compute_live_retry_(warp|hardware)$' -V`. + +```powershell +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V +``` + +### GPU-written indirect Dispatch + +For a translated slot 67 pipeline with fixed-table raw buffers, command-list slot 61 accepts one rootless +Dispatch record in a placed argument buffer. It binds the same translated pipeline and descriptors as direct +Dispatch, transitions the argument buffer and records desktop `ExecuteIndirect`. The GPU reads the group counts. + +The fixture records a compute producer, a copy of the argument record and the indirect consumer on one list. +After the queue fence it checks the leading guard, the neighboring three-word guard record, all three argument words, +the input and all 320 output words. +Counts of 2 and 5 write exactly that many words. Direct Dispatch with the same bindings and counts must produce +the same outputs. Omitting the producer leaves the zero record and the output sentinel intact. Omitting the +translation preserves the output and reports the refusal. Other controls exercise multiple commands, a count +buffer, an out-of-range record and an argument buffer also bound as shader output. + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -j 1 -R '^startup_slot67_indirect_dispatch_(warp|hardware)$' -V +python -B tests/startup_slot67_indirect_dispatch_check.py mutation +``` + +#### GPU-written indirect Dispatch to an offscreen pixel (#3209) + +The same fixture also records the GPU writer on a first guest DIRECT list submission, waits for guest +fence value 1, and checks the seven DWORDs (leading guard, 12-byte Dispatch at byte interval [4,16), +neighboring three-DWORD guard at [16,28)). A second recording on that queue copies the same placed +resource immediately before guest list slot 61, then submits and waits for value 2 before checking the +second snapshot. The native resource pointer and GPU virtual address must agree across both boundaries. +The translated slot 67 shader reads its normal raw-buffer table and XORs one input word per group into +the aliased output UAV. The check requires a translated dispatch in the census, not just an untouched buffer. + +A source-built desktop vertex/pixel shader draws a fullscreen triangle to an 8x4 RGBA8 offscreen target. +The pixel shader reads the actual output buffer via a root SRV, discards the sentinel, and writes the +low three bytes of the compute word as RGB. The graphics recording uses the same underlying DIRECT +queue after the guest consumer fence; no CPU readback is copied into the graphics input. The native +queue and output resource identities are checked. Separate clear and post-draw copies are checked +after the graphics fence. The input and all 320 output words are also checked. + +| Case | Both argument snapshots | Changed pixels / 32 | +| --- | --- | ---: | +| GPU writer, X=2 | (2,1,1) | 8 | +| GPU writer, X=5 | (5,1,1) | 20 | +| GPU writer, X=0 | (0,1,1) | 0 | +| Writer omitted | (0,0,0) | 0 | + +The unchanged pixels must match the clear value, and all changed pixels must match their exact RGB +reference. The stale-SRV control binds the original input instead of the compute output; the unchanged +positive pixel oracle rejects it, while the independently predicted stale colours match the GPU readback. +The device-free mutation mode also detects individual changed pixel words and short readbacks. +The existing outside-record, multi-command, count-buffer, output-alias and manifest refusal controls +remain in the same test. The observer checks native D3D12 debug errors when the info queue is available. +The commands above run both the original and extended fixtures; use dev instead of release for Debug. +This is a synthetic producer-to-pixel proof through translated indirect Compute, with a desktop graphics +observer; it does not establish a translated graphics shader, a retail-scene producer, or a performance gain. + +### Entry values from a buffer descriptor + +A formatted buffer load passes the input's stride and word 3 as entry values (`udsrc stride `, `udsrc descword3 `), and a formatted buffer store (`buffer_store_format_d16_x`, and `buffer_store_format_xyzw` of #2530) passes the output's word 3, the upper half of word 1 and the record count (`uav_descword3`, `uav_stride`, `uav_numrecords`). At Dispatch the stand-in takes each from the descriptor words the same call binds the view from: the stride as the draw path takes it (from the hardware descriptor, or from the title's buffer view for a token), word 3 through the draw path's formatted-buffer check (a token's word is built from its view; a FORMAT the program does not decode refuses the dispatch with `a formatted input has no word 3 the program decodes`), and the output words unmasked, since the store helper checks the swizzle bits itself. A descriptor that is not bound refuses the dispatch as before; an entry value naming a texture slot leaves the pipeline untranslated, and so does any other source. + +`tests/startup_compute_dispatch_entry_check.py` dispatches two source-built programs on WARP and on a physical adapter (exit 77 without one) and reads the 320 output words back: the formatted load of `startup_gfx2hlsl_compute_check.py` with two word-3 values on one translation, and the `buffer_store_format_d16_x` program of `startup_compute_store_d16_x_check.py` with four output descriptors (two formats, another stride and record count, and SWIZZLE_ENABLE set in word 1, for which the translated program stores nothing). A FORMAT the program does not decode is refused with every output word at its sentinel. Returning a constant output stride and record count in the runtime, or masking the stride to 14 bits as the draw path does, makes a store run fail. The record count cannot be checked apart from the bound range, which is sized from the same word. + +Measured on two synthetic programs. In a local set of 29 compute programs whose first refusal was this manifest line (about 1.4 million calls in one run), 27 now pass the manifest (about 1.39 million calls; 17 of them, about 0.6 million calls, use the store of #2530) and 2 stop at a 1D or 3D texture input. Every formatted store in the 27 passes a zero `soffset`: a nonzero one in structured mode can store past `stride * records` bytes, outside the bound range, and is not checked here. Which bind-time reason the 27 meet next has not been measured. + +```powershell +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_entry_" -V +``` + +### Static samplers with a LOD clamp + +The translator writes a constant sampler of `image_sample`, `_l` or `_lz` whose mip filter is not 0 as an `smpl` line (#2482): a static sampler whose MinLOD and MaxLOD come from the descriptor's word 1. The compute Dispatch now reads `smpl` lines as the draw path does, through the same `TranslatedSamplers::read_manifest_line` and `create_translated_root`; the only difference for compute is that the root signature is set with `SetComputeRootSignature`, and static samplers need nothing else. The run-time sampler heap table (`smpheap`) is still refused, as "a sampler from the sampler heap". An `smpc` line is read since #3075: see [comparison samplers in a published compute manifest](experiments/startup-compute-comparison-sampler.md). Binding the heap table for compute would need the draw path's sampler snapshot (`snapshot_samplers`, `create_sampler_snapshot_heap`) taken from the compute root's sampler heap pointer, the sampler heap set with `SetDescriptorHeaps` and its table set with `SetComputeRootDescriptorTable`. + +`tests/startup_compute_dispatch_texture_check.py` adds a filtered case: the texture input program with a wrap, linear sampler (`smpl 0 0x0 0xc00000 0x18500000 0x0`) reads a 2x1 RGBA8 texture whose left texel has red 0 and right texel red 1.0, at the left edge. Only a linear filter that wraps reads 0.5 there. On WARP and on a physical adapter, every thread read red 0.5, and the debug layer reported no error. The control is the same program with the manifest's sampler changed to clamp: it reads red 0, which the check refuses. The `smpheap` line refuses with its reason and leaves the output untouched. Without the new `smpl` reading, the Dispatch refuses with "a sampler that is not a plain static one" and the case fails. The texture has one mip, so the LOD clamp itself is not exercised here. + +In a local census, 7 compute programs (about 135 thousand Dispatch calls) had an `smpl` line as their first refusal, each with one or two `smpl` lines and no other sampler form. Read against the classifier, all 7 manifests now load; their next refusal, if any, comes from the bindings at Dispatch and has not been measured. + +### An input named by a resource heap record + +A compute root signature that indexes the resource heap directly (root flag 0x400) passes the heap pointer in one SGPR after the root parameters. `gfx2hlsl.py` lowers one form of a load through that pointer: `s_lshl_b32 R, , 5`, then, with no write of `R` and no branch target in between, `s_load_dwordx4 D, s[H:H+1], R` with a constant zero in `s[H+1]` and no `offset:` modifier. `D` is then a buffer descriptor, and the manifest names it `srv buf heap rootconst `. Slot 32 now records the title memory of the list's view heap on every call; at Dispatch the stand-in reads the 16-byte descriptor at byte `word << 5` (32-bit arithmetic, as the program computes it) of that memory and binds the buffer through the path a `table` record takes. A record outside the heap refuses the dispatch (`a heap record is outside the list's view heap`) and binds nothing. + +Every other form keeps a refusal that names it: another shift or index, an index register written again, a branch target between the shift and the load, a high word that is not a constant zero, an `offset:` modifier, eight dwords (an image record), and an index read from a buffer in any form other than the one below (`s_load of a resource heap record whose index is read from a buffer other than a table buffer at a dispatch-constant offset`). A formatted load or a store through such a record, and the graphics stages, are refused as before. + +`tests/startup_gfx2hlsl_heap_record_check.py` compares the manifest and the HLSL of a source-built gfx1013 program whole, runs 19 refused controls and one translator mutation (without the write tracking, a refused control translates), and with `--llvm-mc` reassembles every instruction. `tests/startup_compute_dispatch_heap_check.py` dispatches that program through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the input descriptor is only in heap record 2, records 0 and 1 hold the output's descriptor, and all 320 output words must match; before translation and for a record outside the heap every word keeps its sentinel. Changing the runtime's shift to 4, or ignoring the index, makes the dispatch test fail (`an output buffer is also an input`). + +Measured on one synthetic program. The offset is a literal byte offset into the title's heap memory, as a table offset is; a heap whose descriptor increment on the desktop adapter is not 32 bytes (WARP is such an adapter, so its run covers the literal offset only) is not checked against a caller that addresses records by that increment. In a local set of 184 compute programs with a register-offset load through the heap pointer, every such load lowers in 4 programs and none of the 184 translates yet: 151 hold a load whose index is read from a buffer, and the 4 stop at other instructions. + +```powershell +python -B tests/startup_gfx2hlsl_heap_record_check.py --llvm-mc llvm-mc-15 +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_" -V +``` + +#### A heap record index read from a table buffer + +The index can also be a word of a table buffer. `gfx2hlsl.py` accepts `s_buffer_load_dword(xN)` from a table buffer descriptor that no instruction modified, at a literal byte offset or at ` * k + c` built with `s_mul_i32`, `s_mulk_i32`, `s_add_u32`, `s_add_i32` or `s_addk_i32` and literals (plus any `offset:` modifier), dword-aligned, with no branch target between the arithmetic and the load or between the load and the shift. The manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the stand-in reads the table record, computes the byte offset in 32-bit arithmetic, reads the index word from the buffer's memory and binds the heap record it names as above. The read is made at record time, so it is sound only when the GPU does not write the word: the stand-in reads it only when the buffer lies in the recording's upload memory (list slot 148), which no GPU command writes. A buffer elsewhere refuses the dispatch (`a heap index word is not in the list's upload memory`), and so does a word past the buffer's `stride * num_records` bytes (`a heap index word is outside its table buffer`). An index from a per-thread value, a group ID, another buffer word, a register sum or a modified descriptor keeps the refusal. + +`tests/startup_gfx2hlsl_heap_word_check.py` compares the manifest and the HLSL of a source-built program whole, with six more accepted forms and ten refused controls, and with `--llvm-mc` reassembles every new instruction. `tests/startup_compute_dispatch_heap_word_check.py` dispatches it on WARP and on a physical adapter: only the word at `288 + 336 * ` names the input's record, every other word names an output record, and all 320 output words must match; a record outside the heap, a buffer that ends before the word and a buffer outside upload memory each refuse with one reason and leave every output word at its sentinel. Ignoring the scale, the byte offset or the read word, or dropping the upload or range check, makes the dispatch test fail; dropping the alignment, descriptor, register-offset or branch-target checks makes a translator control fail. + +Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index. All 153 change their first refusal and none translates fully yet: 145 now stop at a later instruction (82 at a per-lane `vcc` live at an `s_cbranch_execz` join, 24 at `v_fma_mix_f32`, 14 at `src_scc` in `s_mul_i32`, 25 at others), 6 at a buffer read in another form and 2 at an 8-dword record. 145 programs hold a heap load that now lowers, but 120 of the 158 still hold a refused heap-record load somewhere: 101 a buffer read in another form, 32 an offset that is not a root constant shifted by 5, 2 an 8-dword record (this counts every refusal site, including sites after an earlier refusal). Most of the buffer-form sites compute the offset or read the word before a branch target, which ends the marks because another path into the join may hold a different word; in about 97 programs an 8-dword (image) heap record would stay refused even past that. + +```powershell +python -B tests/startup_gfx2hlsl_heap_word_check.py --llvm-mc llvm-mc-15 +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_word_" -V +``` + +#### Named reasons for an input buffer range + +The refusal `an input is not a complete GPU-backed buffer range` is split into the condition that failed, in the same census lines: `an input buffer descriptor has zero records`; a range over 16 MiB or not whole dwords; a range that crosses the end of a placed buffer or of its upload allocation; an address outside any placed buffer; `an input is in a placed buffer that does not alias title memory`; a view token that is not a buffer view of a desktop resource, has no element size, names upload memory, is not on a default or upload heap, or whose resource does not hold its range; a null address; a range not 16-byte aligned in its resource; a released resource, one not created in the common state, one on another device, and a range outside its desktop buffer. The first refusal of a key also logs which input it was and where its descriptor was read (`x2w-draw compute first refused input (table|heap ), descriptor at
`). Only the reason changes: what was bound is still bound, what was refused is still refused, and the draw paths that call the same function do not ask for it. + +`tests/startup_compute_dispatch_input_check.py` dispatches case A through the stand-in's list on WARP and on a physical adapter (exit 77 without one): the unchanged recording matches all 320 words, and five replaced input descriptors (zero records, 16 bytes past the placed input, memory between the placed buffers, a buffer placed where the desktop cannot alias it, and the token of a texture view) each refuse with their own reason and the input line, and keep every output word at its sentinel. + +Local observation, one run, counts only, from the four descriptor words the census keeps for each key's first refused call: of 18 keys and 1,143,787 calls refused with the old reason, 1 key with 1,057,520 calls had zero records (a nonzero base, no stride and word 3 zero); 11 keys with 31,649 calls named raw descriptors inside placed buffers that fell back to a separate desktop copy (inferred from the creation log: a base offset not 64 KiB aligned, or one buffer over several memory pieces); and 6 keys with 54,618 calls named a shader resource view token whose failing condition the log does not show. Which input of the zero-record key fails, and whether its record comes from the title or from memory the stand-in never filled, needs a run with this split. A load from a zero-record descriptor whose bounds check is on reads 0 on the hardware, so a null view would read the same, but it is not bound until that run shows where the record comes from. #2218 (open, opt-in) owns backing placed buffers the desktop cannot alias and overlaps this form; whether its scope covers these keys (most sit in one buffer created with unordered access) is not checked. + +```powershell +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_input_" -V +``` + ## Startup compute dual-offset/stride-64 LDS ops and 32-bit LDS atomics [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) (`lds_dual`, `lds_atomic`, `_lds_general_barrier_ok`, refs `#1541`, `#2274`) lowers the remaining 32-bit RDNA 2 DS dual-offset/stride-64 and unsigned/bitwise atomic instructions onto `groupshared uint lds[N]` (`COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE`, nonzero and `<= 32 KiB` / 8192 dwords): @@ -15737,6 +17414,19 @@ python -B tests/startup_compute_lds_dual_atomics_check.py binary llvm-mc-15 Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), signed 32-bit (`ds_min_i32`/`ds_max_i32`), `ds_xor_b32`, `ds_sub_u32`/`ds_rsub_u32`, float LDS atomics, and 64-bit LDS dual/atomic forms. +#### A heap record index read from a table buffer + +The index can also be a word of a table buffer. `gfx2hlsl.py` accepts `s_buffer_load_dword(xN)` from a table buffer descriptor that no instruction modified, at a literal byte offset or at ` * k + c` built with `s_mul_i32`, `s_mulk_i32`, `s_add_u32`, `s_add_i32` or `s_addk_i32` and literals (plus any `offset:` modifier), dword-aligned, with no branch target between the arithmetic and the load or between the load and the shift. The manifest names the word as `srv buf heap word table at [rootconst times ]`. At Dispatch the stand-in reads the table record, computes the byte offset in 32-bit arithmetic, reads the index word from the buffer's memory and binds the heap record it names as above. The read is made at record time, so it is sound only when the GPU does not write the word: the stand-in reads it only when the buffer lies in the recording's upload memory (list slot 148), which no GPU command writes. A buffer elsewhere refuses the dispatch (`a heap index word is not in the list's upload memory`), and so does a word past the buffer's `stride * num_records` bytes (`a heap index word is outside its table buffer`). An index from a per-thread value, a group ID, another buffer word, a register sum or a modified descriptor keeps the refusal. + +`tests/startup_gfx2hlsl_heap_word_check.py` compares the manifest and the HLSL of a source-built program whole, with six more accepted forms and ten refused controls, and with `--llvm-mc` reassembles every new instruction. `tests/startup_compute_dispatch_heap_word_check.py` dispatches it on WARP and on a physical adapter: only the word at `288 + 336 * ` names the input's record, every other word names an output record, and all 320 output words must match; a record outside the heap, a buffer that ends before the word and a buffer outside upload memory each refuse with one reason and leave every output word at its sentinel. Ignoring the scale, the byte offset or the read word, or dropping the upload or range check, makes the dispatch test fail; dropping the alignment, descriptor, register-offset or branch-target checks makes a translator control fail. + +Measured on one synthetic program. That the title leaves the upload memory unchanged between recording and execution is a hypothesis, the same one the heap record read relies on, and which memory the real index buffers live in has not been measured. In a local set of 158 compute requests that hold such a load, 153 stopped first at the buffer-read index. All 153 change their first refusal and none translates fully yet: 145 now stop at a later instruction (82 at a per-lane `vcc` live at an `s_cbranch_execz` join, 24 at `v_fma_mix_f32`, 14 at `src_scc` in `s_mul_i32`, 25 at others), 6 at a buffer read in another form and 2 at an 8-dword record. 145 programs hold a heap load that now lowers, but 120 of the 158 still hold a refused heap-record load somewhere: 101 a buffer read in another form, 32 an offset that is not a root constant shifted by 5, 2 an 8-dword record (this counts every refusal site, including sites after an earlier refusal). Most of the buffer-form sites compute the offset or read the word before a branch target, which ends the marks because another path into the join may hold a different word; in about 97 programs an 8-dword (image) heap record would stay refused even past that. + +```powershell +python -B tests/startup_gfx2hlsl_heap_word_check.py --llvm-mc llvm-mc-15 +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_heap_word_" -V +``` + ## Startup translator: a short operand list is refused, never a translator crash The batch translator records any non-`Unsupported` exception from a handler as @@ -15759,7 +17449,7 @@ The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity `…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game data, because a refusal is observable at the `Stage` entry point. -## Startup translator: v_sad_u8, v_sad_u16 and v_sad_u32 +## Startup translator: v_sad_u8, v_sad_hi_u8, v_msad_u8, v_sad_u16 and v_sad_u32 [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the gfx1013 VOP3A unsigned sum-of-absolute-differences instructions `v_sad_u8` (`0x15a`), `v_sad_u16` (`0x15c`) and `v_sad_u32` (`0x15d`) in `VEC_U` to three on-demand preamble helpers emitted in `Pipeline.common()` only when referenced by a stage (`sad_u8`, `sad_u16`, `sad_u32`): @@ -15768,10 +17458,13 @@ data, because a refusal is observable at the `Stage` entry point. - `sad_u32(uint a, uint b, uint c)` computes `(a > b ? a - b : b - a) + c` using unsigned comparison rather than signed `int` subtraction. - Output modifiers (`clamp`, `omod`), `op_sel`, the per-source `abs` bits (VOP3A `w0[10:8]`) and `neg` bits (`w1[31:29]`), and wrong operand counts remain refused: `check_encoding` refuses the `abs`/`neg` bits in the raw word so `neg` on an inline integer cannot print as `-N` and be read as a negative constant, and `Stage.u` refuses the printed `|vN|` and `-vN` forms, the modifier tokens and a wrong operand count. +`v_sad_hi_u8` (`0x15b`, 347) and `v_msad_u8` (`0x171`, 369) reuse that four-lane sum through a shared on-demand helper `sad4_u8(uint a, uint b, bool masked)`, emitted only when one of them is referenced: `v_msad_u8` leaves out each byte lane whose `src1` byte is zero (`sad4_u8(a, b, true) + c`), while `v_sad_hi_u8` keeps every lane and shifts the sum before adding `src2` (`(sad4_u8(a, b, false) << 16u) + c`), both modulo 2^32. Those are the formulas of the `tools/pixel_aot.py` table, so the two translators agree, and the existing `sad_u8`, `sad_u16` and `sad_u32` helpers and their emitted text are unchanged. [`tests/startup_gfx2hlsl_sad_hi_msad_check.py`](../tests/startup_gfx2hlsl_sad_hi_msad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), checks that each form emits `sad4_u8` plus only its own wrapper and that the unchanged `v_sad_u8` output does not pull in `sad4_u8`, evaluates the emitted HLSL against the AOT formulas over 864 edge/grid triples per form plus pinned normal, zero-`src1`-byte and 2^32-carry rows, and checks the modifier/arity/encoding and unlowered refusals. The semantics are pinned to the AOT reference, not measured on a console: the only hardware draws of these two forms are those of `tests/pixel_aot_check.py`, and what `v_sad_hi_u8` leaves in the high half on Scarlett is not measured here. + [`tests/startup_gfx2hlsl_sad_check.py`](../tests/startup_gfx2hlsl_sad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), verifies on-demand helper emission across `Pipeline` and `ComputePipeline`, evaluates the emitted HLSL across 600 edge/grid triples for `v_sad_u8`, 600 for `v_sad_u16` and 605 for `v_sad_u32` (covering `0xffffffff`, `0x80000000`, `0x7fffffff`, byte/halfword boundary carries and `S2` wraparound), checks all modifier/arity/unlowered refusals, and runs mutated-HLSL negative controls (dropped high byte, dropped high halfword, signed `int` subtraction). The encoding guard is pinned per source slot: one row each for `abs` on sources 0, 1 and 2, one for `neg` on each of them, and the same six again with the modifier on an inline `1` (36 rows), and each row reads the refusal back from `G.decode()`'s refusals list and asserts the exact `v_sad_* with neg/abs` reason. That matters because a narrowed mask still ends up refused, just later and by a different guard: with `w0 & 0x700` narrowed to `w0 & 0x100` the `abs` word decodes to `|v1|` and `Stage.u` refuses it, so the pipeline-level control alone passes; the reason check fails, as does the `w1 & 0xe0000000` → `w1 & 0x20000000` narrowing (which silently accepts `neg` on an inline `1` as `-1`). In `draw` mode on Microsoft WARP (`10.0.26100.9818`, DXC `ps_6_0` and FXC `10.0.26100` `ps_5_1`), all 18 good draws (9 per compiler) matched the Python reference and all 6 mutated draws (3 per compiler) produced the exact mutated readback words; the same 18 good and 6 mutated draws also pass on the NVIDIA GeForce GTX 1660 SUPER (driver 32.0.16.1074, Windows build 26200), where the debug layer is not installed and so the `_debug1` variants skip with exit 77. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_hi_msad_controls$' -V ## Startup translator: signed 4-bit offset conversion (`v_cvt_off_f32_i4`) `tools/startup/gfx2hlsl.py` lowers `v_cvt_off_f32_i4` in VOP1 `_e32` (`0x0e`) and VOP3A `_e64` (`0x18e`) via @@ -15806,7 +17499,7 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec - `drain_retired_resources()` erases the retired wrapper from `resource_address_index()` (under `note_lock`), erases its desktop pointer from `texture_uploads()` (under `draw_lock`), and cleans stale `written_textures()` entries whose generation was not bumped by a newer allocation/write at the same title address (also cleared immediately on final `Release` when no view or live sibling shares the address). - `list_copy_texture.inl` calls `upload_texture()` for a subresource copy only when the resource is not in the retire class or has title memory (`!retire_when_idle || title_memory`), so with the switch off every resource uploads exactly as before; `texture_uploads()` accesses in `list_copy.inl` / `list_copy_texture.inl` are guarded with `draw_lock`. - `view_slot` records a view only when the desktop created it: desktop view creation returns `void`, so a removed device is the only failure it reports, and a failed slot is recorded unmaterialized (releasing its previous view reference and adding none). `retire_hold` reads the wrapper's desktop pointer under the retire lock and marks a use it cannot record, which makes the drain keep that desktop object for the process instead of dropping one a list still names. -- `view_slot<18>` (SRV) tracks descriptor slots via `HeapInfo::shadow` across `note_view`, `note_copy`, and heap destruction (falling back to `retire_leave_class` for untracked slots or slots 19–21), and `draw_translated` holds bound textures with `retire_hold`. +- `view_slot<18>` (SRV) tracks descriptor slots via `HeapInfo::shadow` across `note_view`, `note_copy`, and heap destruction (falling back to `retire_leave_class` for untracked slots), and `draw_translated` holds bound textures with `retire_hold`. Slice 3a extends the same tracking to slots 19-21 (see below). [`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement, the switch-off control that an ordinary committed texture (no title memory) copy still records its upload, and that a newer `written_textures` generation survives the older generation's retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. Case 7 closes the fixture's draw-path gap (review finding B1): a host-built translated pixel shader samples a slot 133 title-memory texture through a descriptor table, its view token must resolve to that texture (a skipped resolve binds a null view and the readback reports `pixel (0,0) got 00000000`), and `retire_hold` in the draw keeps the released texture retained while the closed recording names it (removed, the budget reports `retained=0/0 expected=65536/1` before the recording is dropped); the readback holds the exact sampled words plus a clear sentinel row and column throughout, including after the texture leaves the budget. @@ -15814,6 +17507,95 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V ``` +## Tracking UAV/RTV/DSV descriptor slots in the retire class (Slice 3a) + +`X2W_D3D12_RELEASE_RETIRED=1` now counts a reference for a materialized view in a descriptor slot the shim shadows (`HeapInfo::shadow`) for slots 19 (UAV), 20 (RTV) and 21 (DSV), as it already did for slot 18 (SRV). A slot holds one reference, and a slot-19 UAV holds a second one for its counter resource. `note_view` adds the references when the view is written into a tracked slot, releases the overwritten slot's previous references, and adds nothing when the same view is written again; `note_copy` moves the references with `CopyDescriptors*` copies and releases the references of the view the destination named before; the descriptor heap's `Release` releases every reference its slots still hold. A view call into a descriptor slot no shadow tracks keeps the old `retire_leave_class` fallback (the resource, and a slot-19 counter, leave the class for good), so nothing is freed under a descriptor the shim cannot follow. `view_slot<19..21>` decides the fallback by looking the destination up with `shadow_slot()` under the existing `note_lock`; a tracked destination leaves the accounting to `note_view`. The drain's freeing rule is unchanged: `retire_view_refs == 0`. + +The references free nothing on their own yet. The retire class still excludes a texture created with the render-target, depth-stencil or unordered-access flag (`retire_classify`), so a class texture's 19-21 view call is the console-only case the shim refuses (a UAV of a depth texture, an RTV of a texture without render-target); it records no view, adds no reference, and the texture still retires. Widening the class is a separate lifetime decision. Not covered: the `note_copy` fallback for a copy out of a tracked into an untracked heap, and a texture UAV that names a counter (desktop D3D12 refuses the counter on a non-buffer UAV with `DXGI_ERROR_INVALID_CALL`, so the counter half of the fixture uses a structured buffer UAV). + +`x2w_d3d12_retire_probe` reports the resource's `retire_view_refs` as `view_refs`. [`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) case 8 writes an RTV, a DSV and a UAV (plus a structured-buffer UAV with a counter resource) into tracked heap slots: the probe must show one reference per slot (two for a slot-19 UAV that names a counter), the same view written again must change nothing, and an overwrite, a `CopyDescriptorsSimple` copy and the heap destruction must each return the count to zero (a view in an untracked desktop heap must add none). Case 9 covers the fallback for a refused RTV on a slot-133 class texture: in a tracked slot the texture stays in the class, so the budget's retained column must drop after its release and drain, while the same call into a descriptor slot the shim does not shadow keeps one retained object. Both cases run in the `_off_` mode too, where nothing is freed, as before. + +Measured on WARP (`Microsoft Basic Render Driver`) and an `NVIDIA GeForce GTX 1660 SUPER` with the debug layer off (the debug-layer variants skip with 77 in this environment): `startup_resource_retire_title_{warp,hardware}_debug0` pass with the switch on and `startup_resource_retire_title_off_{warp,hardware}` pass with both new cases asserting nothing is freed. Four mutants fail the fixture with the switch on: no reference added for 19-21 (`FAIL: RTV created in a tracked slot: 0 tracked slot refs, expected 1`), no release on overwrite (`FAIL: RTV overwrote the slot: previous resource: 1 tracked slot refs, expected 0`), the old unconditional `retire_leave_class` (`FAIL: a refused view in a tracked slot kept the texture out of the retire class`, with `retained=65536/1 expected=0/0`), and no release on heap destruction (`FAIL: copy heap destroyed: 1 tracked slot refs, expected 0`). + +```powershell +cmake --build --preset dev --target startup_resource_retire_title startup_resource_retire +ctest --preset dev --no-tests=error -R '^startup_resource_retire(_title)?_' -V +``` + +## Single-wave `TG_SIZE_EN` wave-ID folding in the startup compute translator + +[The startup translator](../tools/startup/gfx2hlsl.py) accepts `COMPUTE_PGM_RSRC2.TG_SIZE_EN` (bit 10) in `ComputePipeline` when the thread-group size is at most 32 threads (`x * y * z <= 32`, one wave per workgroup). The `TG_SIZE` entry SGPR sits immediately after `USER_SGPR` and any enabled `TGID_X/Y/Z` SGPRs (`user + len(groups)`) and is tagged `('tg_size',)`. Only `s_and_b32 R, TG, 0xfc0` (or `0xfc0, TG`) into an SGPR `R <= 105` is accepted for an untouched `TG_SIZE` register: because a single-wave group has wave index `TG_SIZE[11:6] == 0`, it lowers to `R = 0u; scc = false;` with `R` tracked as `('const', 0)` (feeding `v_mbcnt_lo_u32_b32` as a known zero base). Every other read of an untouched `('tg_size',)` register (other masks, moves, arithmetic, vector instructions, or direct `v_mbcnt_lo_u32_b32`) is refused, while overwriting `TG` restores ordinary scalar behavior. Larger groups (`> 32` threads) with `TG_SIZE_EN` remain refused in `ComputePipeline`, and `tools/compute_store_aot.py` continues to refuse `TG_SIZE_EN` unconditionally. + +[The `TG_SIZE_EN` check](../tests/startup_compute_tg_size_check.py) verifies SGPR placement, `s_and_b32` folding, `v_mbcnt_lo_u32_b32` lowering, overwrite/branch/refusal controls, and a two-group `4x2x2` WARP dispatch (`320` words compared, `0` mismatches on Microsoft Basic Render Driver `10.0.26100.9818`, with `dropped-base` rejected at word 5 and `swapped-mask` rejected at word 8). + +```powershell +.\out\pe-env\Scripts\python.exe -B tests/startup_compute_tg_size_check.py +ctest --preset dev --no-tests=error -R '^startup_compute_tg_size_' -V +``` + +## Explicit-level 1D image sampling in the startup translator + +[The startup translator](../tools/startup/gfx2hlsl.py) now lowers 1D `image_sample_lz` and `image_sample_l` onto `Texture1D.SampleLevel` alongside the existing implicit-level `image_sample` path (#1721): + +- `image_sample_lz` takes one address dword (`u`) and lowers to `tex.SampleLevel(smp, F(u), 0)`. +- `image_sample_l` takes two address dwords (`u`, then the explicit `lod`) and lowers to `tex.SampleLevel(smp, F(u), F(lod))`. +- Both explicit-level forms require a non-empty `dmask` and accept only `dim:SQ_RSRC_IMG_1D`, `dmask:*`, and the cache-policy modifiers (`glc`, `slc`, `dlc`). Plain `image_sample` on 1D keeps its existing rule (still refusing cache-policy bits), and layout or address modifiers (`unorm`, `r128`, `a16`, `d16`, `tfe`, `lwe`, reserved bits), wrong address counts, empty `dmask`, `image_sample_b`, and `image_load` on 1D stay refused. + +[The 1D image check](../tests/startup_gfx2hlsl_image_1d_check.py) builds synthetic MIMG instructions against the decoder layout and verifies `image_sample_lz`, `image_sample_l`, plain `image_sample`, 2D separation, cache-policy equivalence, empty `dmask`, and refused forms. Run: + +```powershell +ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_image_1d($|_)' -V +``` + +The draw fixture binds a three-mip Texture1D with a distinct value per mip. With LOD +inputs 1 and 2, the zero-level form reads level 0 and the explicit form reads the +provided level. Forcing the explicit level to zero changes the level-2 readback. + +## Startup translator: v_mad_u32_u16 + +[`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the unmodified gfx1013 VOP3A instruction `v_mad_u32_u16` (`0x373` in [`tools/disasm_rdna2.py`](../tools/disasm_rdna2.py)) via `VEC_U` as `({0} & 0xffffu) * ({1} & 0xffffu) + {2}` (unsigned 32-bit wraparound). In `Stage.lower`, `S0` and `S1` are read with `low16_only=True` because only bits `[15:0]` of those operands are consumed (allowing odd-dmask `d16` `image_load` results in `S0`/`S1` and clearing `low16_only_v` on the 32-bit destination), while `S2` is read with `low16_only=False` (refusing `low16_only_v` sources) so all 32 bits of the addend are preserved. Modifiers (`op_sel`, `clamp`, `omod`, `abs`, `neg`) and wrong operand counts remain refused. + +[`tests/startup_gfx2hlsl_mad_u32_u16_check.py`](../tests/startup_gfx2hlsl_mad_u32_u16_check.py) decodes synthetic gfx1013 VOP3A bytes for 4-lane VGPR forms as well as literal/inline-constant/SGPR forms (`v_mad_u32_u16 v1, 0x1f0, v15, 0`, `v_mad_u32_u16 v3, s4, -1, v9`, `v_mad_u32_u16 v2, v5, 7, 0x12345678`), evaluates the emitted HLSL expressions over 1,800 32-bit input triples (including upper-16 garbage bits `0xffff0000` in `S0`/`S1`, `0xffff * 0xffff`, 32-bit wraparound with `S2 = 0xffffffff`, and upper-bit preservation on `S2`) against `((s0 & 0xffff) * (s1 & 0xffff) + s2) & 0xffffffff`, checks the `low16_only` read/clear/refusal rules, checks `op_sel`/`clamp`/`omod`/`abs`/`neg`/arity refusals and the unlowered-table negative control, and verifies three HLSL mutations (`drop_s0_mask`, `drop_s1_mask`, `mask_s2`). In `draw` mode, both FXC (`vs_5_1`/`ps_5_1`, Windows SDK 10.0.26100) and DXC (`vs_6_0`/`ps_6_0`, Windows SDK 10.0.26100) passed 3 four-lane chunks and all 3 mutated draws on Microsoft WARP (`10.0.26100.9818`). Tests: `startup_gfx2hlsl_mad_u32_u16_controls`, `startup_gfx2hlsl_mad_u32_u16_warp`, `startup_gfx2hlsl_mad_u32_u16_hardware` (not run on physical hardware here). + +```powershell +python -B tests/startup_gfx2hlsl_mad_u32_u16_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mad_u32_u16_' -V +``` + +## Refusing unmodelled modifiers in the startup translator + +Several `Stage` instruction handlers accepted a `mods` list without reading it, so an encoding modifier such as +`clamp`, `omod` (`mul:2`), or `op_sel` on `v_mov_b32`, `v_cvt_pkrtz_f16_f32`, or `v_interp_mov_f32` was silently +dropped from the emitted HLSL (#1771). `MODIFIER_FREE_HANDLERS` declares these five handlers (`op_v_mov_b32`, +`op_v_cvt_pkrtz_f16_f32`, `op_v_interp_p1_f32`, `op_v_interp_p2_f32`, and `op_v_interp_mov_f32`), and `Stage.one` +refuses any non-empty `mods` list before dispatching to them. Scalar-ALU handlers are omitted because their encodings +have no modifier field. Separately, `op_v_interp_p1_f32` and `op_v_interp_p2_f32` refuse `abs`/`neg` modifiers (`|...|` +or `-...`) printed on the ignored data-source operand (`ops[1]`). + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_modifier_free$' -V +``` + +## Source `abs` modifiers (`|src|` and `-|src|`) on `v_cndmask_b32_e64` in the startup translator + +`Stage.u_src` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py#L1506-L1521) now strips `|...|` after `split_neg(tok)` for `v_cndmask_b32_e64` data sources (`src0` and `src1`, both VGPRs and SGPRs), clearing the `off_diag.py` refusal `operand '|v0|' at v_cndmask_b32_e64 v0, v0, |v0|, s30`. Per the RDNA2 VOP3A source-modifier order, `abs` clears bit 31 (`& 0x7fffffffu`) first and `neg` flips bit 31 (`^ 0x80000000u`) second: + +- `|src|` emits `(src & 0x7fffffffu)` +- `-|src|` (and `neg(|src|)`) emits `((src & 0x7fffffffu) ^ 0x80000000u)` (forces bit 31 to `1`) +- `-src` keeps `(src ^ 0x80000000u)` + +`check_encoding()` still refuses `ABS` on inline or literal immediates (`v_cndmask_b32_e64 ABS on an immediate`), `Stage.u()` still refuses `|vN|` when `vN` is in `low16_only_v` (whole-word 32-bit read), `op_v_cndmask_b32` still refuses `abs`/`neg` on the mask operand (`src2`), `v_cndmask_b32` stays out of `UNIFORM_VALU`, and other integer instructions keep using `Stage.u()` so unexpected `|...|` modifiers remain refused. + +```powershell +out\pe-env\Scripts\python.exe -B tests\startup_gfx2hlsl_cndmask_abs_check.py +out\pe-env\Scripts\python.exe -B tests\startup_gfx2hlsl_cndmask_abs_check.py draw dxc.exe out\build\dev\offscreen_check.exe warp fxc.exe +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cndmask_abs_(controls|warp|hardware)$' -V +``` + +### Measured results and open scope + +[`tests/startup_gfx2hlsl_cndmask_abs_check.py`](../tests/startup_gfx2hlsl_cndmask_abs_check.py) decodes synthetic VOP3A bytes with `G.decode()` (no game data) covering `v_cndmask_b32_e64 v0, v0, |v0|, s30`, `|v0|` / `-|v0|` on `src0` and `src1`, SGPR `|s4|` / `-|s4|`, `neg(|v0|)`, and 17 refusal controls, then evaluates the emitted HLSL across 11 32-bit patterns (`+0.0`, `-0.0`, `+1.0`, `-1.0`, `+qNaN`, `-qNaN`, `+inf`, `-inf`, `-denormal`, `0x12345678`, `0x92345678`) under both mask states (`22/22` exact matches; both order-reversed and `abs`-dropped mutations mismatch on `22/22` cases). On WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`, `debug_layer=unavailable`) with FXC (`ps_5_1`) and DXC (`ps_6_0`), all 44 positive draws (22 FXC + 22 DXC) matched bit-for-bit and all 8 mutated draws (4 reverse-order + 4 drop-abs) failed with their expected wrong words. Physical GPU (`startup_gfx2hlsl_cndmask_abs_hardware`) and title shader execution remain unverified here. + ## Binary16 SDWA arithmetic, rounding, scaling and conversions in pixel_aot [The pixel shader translator](../tools/pixel_aot.py) adds 14 contracted binary16 `SDWA` forms (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): @@ -15850,6 +17632,43 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_int_extra_warp|pixel_ao Linux controls, `form_coverage_check.check_sdwa_int_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. +## `src_scc` as a scalar source + +`s_mul_i32 s28, 1.0, src_scc` was refused as `operand 'src_scc'` (issue #1820), one of the refused shaders +in the loading-screen cache (#870). Scalar source code 253 reads the SCC bit as the integer value 0 or 1 +(fitting in 16 bits, so `low16_only=True` returns the same expression), and the generated shader carries SCC +as a `bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC +on every reaching path in the current block (`s_cmp_*` / `s_and_b32` etc. via `set_scc()`, `set_exec_scc()`, +or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at shader entry, across +control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in +`SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`. + +A branch target no longer drops a proven SCC in every case. In the local request cache, 238 of 239 requests +refused this way stop first at `s_mov_b32 sN, src_scc`, and 1 at `s_mul_i32 sN, sN, src_scc`. Walking the +control-flow graph back from each read finds the SCC writes that reach it: `s_bitcmp1_b32 sN, imm` (169 +reads), `s_bitcmp0_b32 sN, imm` (17), `s_cmp_eq_i32 sN, imm` (17), `s_cmp_lg_i32 sN, imm` (16), +`s_cmp_lt_i32` (7), `s_cmp_lt_u32 sN, sN` (6), `s_cmp_eq_u64 sN, sN` (3), `s_and_b64 sN, vcc, exec` (2), or +both `s_cmp_eq_i32` and `s_cmp_lg_i32` (2). One write reaches 230 reads, and two or three different writes +reach 9. In the samples inspected, this is the compiler copying SCC into an SGPR on both arms of an if/else +after `s_cbranch_scc0/1`, with the read in the arm that only the taken edge enters. Program-order tracking +marked that arm unverified because of the other arm's `s_branch`, or a descriptor-elided SCC write there +(`s_bfe_u32` of a descriptor word). + +Each forward branch now carries the offset of the emitted SCC write that reaches it, but only when that write +was uniform (`scc_uniform`). A target keeps SCC proven when the fall-through and every edge into it carry the +same write and no back edge enters it. Every path then ran that one write last, both for the modelled lane +and for the wave. This holds whichever path each took, including a block that `s_cbranch_execz` skips for +one lane only, so the model's SCC is the hardware value. Lane-mask SCC (`set_exec_scc`, a mask op on `vcc` or +`exec`), unmodelled and elided writers, different writes on different paths, and loop heads stay refused. + +The translator was origin/main plus #1821, run over the 239 requests with 4 workers. Before the change, 85 +refuse first on `src_scc`; the other 154 stop earlier, 137 of them on `NEG on an integer or literal source`. +After it, 75 of the 85 move on and 1 translates and compiles. The 10 left are compute requests. Each has a +reaching `s_cmp_*` whose source the model does not prove uniform. In 7 a different write reaches on another +path, and in 3 the path crosses a loop head. +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc(_join)?$' -V`. + ## Startup shader request identity `startup_shader_cache_key` uses the explicit `X2W_FXC=''` manifest-only mode: no GPU @@ -15880,7 +17699,9 @@ PSO-cache change. Canonical output bytes remain unchanged. Two caches keep desktop D3D12 objects for a device for as long as the module that holds them is loaded: the indexed-validation pipeline (`startup_stubs/d3d12_draw.inl`) and the rectangle-list argument converter -(`startup_stubs/rect_indirect_args.h`). Both are function-local statics, so they are destroyed during the +(`startup_stubs/rect_indirect_args.h`); the same boundary covers the placed page aliases of the translated +indirect address route (`startup_stubs/d3d12_xs_device.cpp`) and the draw-dump readbacks +(`startup_stubs/draw_dump_tracking.h`). All four are function-local statics, so they are destroyed during the module's CRT teardown, and that teardown happens at two different moments. At process exit Windows has already detached the display driver: releasing a pipeline state then faults inside the driver (`amdxc64`, at `0x35f2a19`, through `D3D12Core!CPipelineState::FinalRelease`) and the loader turns it into `0xC0000409`. @@ -15898,18 +17719,44 @@ ctest --preset dev --no-tests=error -R "^startup_teardown_unload_(warp|hardware) ctest --preset dev --no-tests=error -R "^startup_indirect_(translated_indexed|rectlist)" -V ``` -The fixture (`tests/startup_teardown_unload.cpp`) loads the built `d3d12_xs.dll` by path, warms both caches -through the module's own probe, and unloads it: the caches must release what they own, the device's reference +The fixture (`tests/startup_teardown_unload.cpp`) loads the built `d3d12_xs.dll` by path, warms one cache at a +time through the module's own probe, and unloads it: the cache must release what it owns, the device's reference count must come back, and the module must be gone. A second load is warmed and left loaded, so process termination exercises the other path. It is source-built and loads no title. +The two caches added with the ownership change own desktop objects that hold no reference on the device handle +the fixture holds, so the fixture measures them on the object: `x2w_d3d12_cached_object_probe` hands over one +reference of the placed buffer, of the readback buffer and of its fence, and that reference has to stay alone +once the module is unloaded. The placed-buffer case also owns the heap that buffer is placed on: the alias +entry keeps the heap as a key only, as the real route does, so `x2w_d3d12_cached_objects_probe` creates the +heap and hands its one reference to the fixture through an out parameter, and bit 4 is not warmed without that +pointer rather than leaving an unowned heap behind. The fixture keeps that heap across the unload, drops the +cache's and its own reference on the placed buffer first, and only then releases the heap -- a heap must +outlive the resources placed in it -- and requires that release to be the last reference, so a heap the cache +still owned would fail the case instead of leaking quietly. The termination load runs in a child of the fixture +(the fixture itself, `--termination-only`), because the evidence only exists while that process tears the module +down: with `X2W_TEARDOWN_REPORT=1` each cache writes `x2w-teardown detached= released=` straight +to stderr (no stdio buffer survives a CRT teardown), and the child has to report every owned reference detached +and none released. `X2W_TEARDOWN_NO_GUARD=` is the negative control: it makes that cache +release instead of detach, and the same check has to fail. Each passing run re-runs the child once per new cache +with the hook set and requires that failure, so a check that passes with and without a guard cannot report +success. Neither variable is read by an ordinary run. + +```powershell +startup_teardown_unload.exe warp +set X2W_TEARDOWN_REPORT=1 +set X2W_TEARDOWN_NO_GUARD=pages +startup_teardown_unload.exe warp # must fail: the pages guard is what detaches +``` + Measured on Windows 11 25H2 (26200.9974, MSVC 19.44.35230), AMD Radeon RX 9070 XT (`1002:7550`, driver -`32.0.32029.2010`), debug layer unavailable: `startup_teardown_unload` passes on WARP and on the card, and the -five `startup_indirect_*_hardware` runs that died with `0xC0000409` now reach their last assertion and exit -`0`. Removing either destructor brings its own failure back and only its own: without the validation-pipeline -destructor the four `translated_indexed*` runs fail and `rectlist` passes; without the converter destructor -`rectlist` fails and the four pass. Not covered: an explicit unload while a device is still referenced by a -title, and any adapter other than the one above. +`32.0.32029.2010`), debug layer unavailable: with the two original cases, `startup_teardown_unload` passes on +WARP and on the card, and the five `startup_indirect_*_hardware` runs that died with `0xC0000409` now reach +their last assertion and exit `0`. Removing either destructor brings its own failure back and only its own: +without the validation-pipeline destructor the four `translated_indexed*` runs fail and `rectlist` passes; +without the converter destructor `rectlist` fails and the four pass. The backing-heap handover is newer than +that run and has not been exercised on either machine yet. Not covered: an explicit unload while a device is +still referenced by a title, and any adapter other than the one above. ## Exact binary16 min, max, fract, and frexp forms (VOP1/VOP2/VOP3/DPP16/DPP8/SDWA) in pixel_aot @@ -15959,3 +17806,199 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_cvt_warp|pixel_aot_sdwa ``` Linux controls, `form_coverage_check.check_sdwa_cvt_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. + +## Startup translator: RDNA 2 scalar `null` operand and `Stage.scalar` destination guards + +`tools/startup/gfx2hlsl.py` lowers the RDNA 2 `null` scalar operand (`code 125`) and replaces `reg_range(...)[1]` `TypeError` crashes on non-SGPR scalar destinations with explicit `Unsupported` refusals (#2618, #1723, #2463): + +- **32-bit `null` source (`code 125`)**: `Stage.u`, `Stage.const_u32`, `Stage.uniform_source`, `Stage.scalar_const`, `SCALAR_CONST_FOLD`, `scalar_bitset`, `op_s_bfm_b32`, and `VOP3_ONLY_VEC_U` in `Stage.lower` read `null` as wave-uniform `0x00000000u`. +- **32-bit `null` destination in `Stage.scalar` and `op_s_bfm_b32`**: plain 32-bit numeric/constant SALU writes to `null` discard the destination register write while still emitting modeled `SCC` updates (`s_and_b32`, `s_or_b32`, `s_xor_b32`, `s_andn2_b32`, `s_orn2_b32`, `s_not_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_ashr_i32`, `s_bfe_u32`, `s_absdiff_i32`) and leaving `SCC` unchanged for non-SCC operations (`s_mov_b32`, `s_movk_i32`, `s_brev_b32`, `s_mul_i32`, `s_bfm_b32`). `s_lshl1..4_add_u32`, `PACK_B16` / `s_sext_*` / `s_mul_hi_*`, and `s_cselect_b32` retain their pinned `null` destination refusals. +- **Explicit `Unsupported` refusals replacing `TypeError`**: `_b64` operations (`s_and_b64 null, exec, s[0:1]`, etc.), lane-mask sources (`exec_lo`, `vcc_lo`, compare-mask SGPRs), `SCC_UNMODELLED` operations (`s_add_u32`, `s_sub_u32`, `s_add_i32`, `s_sub_i32`, `s_min_*`, `s_max_*`), and descriptor/pointer sources written to `null`, as well as unmodelled destinations (`vcc_hi`, `exec_hi`, `ttmp*`), raise specific `gfx2hlsl.Unsupported` reasons instead of `TypeError`. + +[`tests/startup_gfx2hlsl_scalar_null_check.py`](../tests/startup_gfx2hlsl_scalar_null_check.py) constructs synthetic gfx1013 SOP1/SOP2/SOPK/SOPC/VOP2/VOP3A/SMEM words (no game data), verifies all 14 32-bit SCC-writing SALU operations into `null` across boundary pairs, checks LLVM 15 `llvm-mc` / `libLLVM` round-trips, sweeps all 48 `SCA` ops plus `s_bfm_b32` against non-SGPR destinations, and runs D3D12 GPU verification across Microsoft WARP (`1414:008c`, driver `10.0.26100.9818`) and an AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`) with the D3D12 debug layer enabled (`0` errors, `0` warnings): 4 pixel-stage draws (`FXC ps_5_1` + `DXC ps_6_0`) with 6 pixel mutations plus 4 runtime root-constant SALU+branch buffer runs with 4 HLSL mutations per adapter. + +```powershell +ctest --test-dir out/build/release --no-tests=error -R "^startup_gfx2hlsl_scalar_null_(controls|warp|hardware)$" -V +``` +## `src_scc` as a scalar source + +`s_mul_i32 s28, 1.0, src_scc` was refused as `operand 'src_scc'` (issue #1820), one of the refused shaders +in the loading-screen cache (#870). Scalar source code 253 reads the SCC bit as the integer value 0 or 1 +(fitting in 16 bits, so `low16_only=True` returns the same expression), and the generated shader carries SCC +as a `bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC +on every reaching path in the current block (`s_cmp_*` / `s_and_b32` etc. via `set_scc()`, `set_exec_scc()`, +or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at shader entry, across +control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in +`SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`. + + +## Startup translator: derivative image ops under a divergent EXEC + +`image_sample_b` and `image_get_lod` take implicit derivatives of the four lanes of a pixel quad. A pixel program +with such an op and no backward branch now decides its `s_cbranch_execz` / `s_cbranch_execnz` per quad +(`x2w_quad_any(exec)`: some lane of the 2x2 quad has its EXEC bit, from fine derivatives of the 0/1 bit), as the guest's +wave skips a block only when no lane is active and runs it with the other lanes masked. A voted branch parts no quad, +so it keeps `uniform_cf` (#2659); the vote reads the quad, so it is taken only while the control flow is quad-uniform +and no lane-exec break (`s_wqm` of a narrowed EXEC, a discard under an unknown EXEC) came first. With that, a derivative +op may sit under `v_cmpx`, inside an `execz` block, past an `execnz` kill branch, or after an EXEC restore. Still +refused: any branch that can differ between lanes and is not an EXEC branch (VCC, SCC not proven uniform), loops with +such a branch, and an `s_wqm` of a narrowed EXEC before the op. +`tests/startup_image_sample_b_flow_check.py` and `tests/startup_image_get_lod_flow_check.py` draw each shape against a +CPU reference (DXC ps_6_0 and FXC ps_5_1) with wrong-value controls. + +The `_dispatch_warp` and `_dispatch_hardware` tests run `s_cmp_eq_u32` then `s_mov_b32 sX, src_scc` on a D3D12 +UAV dispatch and compare each lane with the CPU reference (SCC 0 and SCC 1, distinct per-case data). A copy of the +lowering mutated to `(scc ? 0u : 1u)` must read back wrong. Run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc_dispatch_warp$' -V`. + +## Startup compute translator: `global_load_dword` with a scalar register pair (`saddr`) + +The source-built dispatch binds the root SRV directly. The startup runtime still +needs support for consuming the resulting `srv ... buf root` manifest record. + +`tools/startup/gfx2hlsl.py` lowers the RDNA 2 `GLOBAL` one-dword `saddr` load (`global_load_dword vdst, vaddr, s[base:base+1] [offset:imm]`, #2618 ticket `C500-01/031`, #2022) in the `cs` stage: + +- **Address, alignment, and resource provenance** (AMD RDNA 2 ISA §9.2, LLVM 15 `SelectGlobalSAddr`): `ADDR = SADDR[63:0] + zext(VADDR[31:0]) + sext(OFFSET[11:0])`. `s[base:base+1]` must be an even-aligned SGPR pair (`0 <= base <= 104`) holding a proven 64-bit root buffer pointer (`('ptr', ('root', index))` and matching `ptr_high_symbol`, including `s_mov_b32` / `s_mov_b64` copies and completed literal `s_add_u32` / `s_addc_u32` advances). Because RDNA 2 low-bit `GLOBAL` alignment depends on `SH_MEM_CONFIG.ALIGNMENT_MODE` (unmeasured on Scarlett) and HLSL `ByteAddressBuffer.Load` requires a multiple of four, `base_off`, `offset`, and `vaddr` (`align4_v` / `align4_s`) must each be proven 4-byte aligned. Each distinct root parameter binds a `ByteAddressBuffer r : register(t)` (`srv buf root ` in the manifest), capturing `a = vaddr` first (so `vdst == vaddr` aliasing is preserved) and guarding the signed 64-bit view-relative sum `zext(a) + base_off + imm` against `[0, 0xffffffff]` before converting to a 32-bit `Load` offset (`a <= 0xffffffff - total_off ? r.Load(a + total_off) : 0u` for `total_off > 0`, `a >= -total_off ? r.Load(a - (-total_off)) : 0u` for `total_off < 0`, and `r.Load(a)` for `total_off == 0`), refusing `|total_off| > 0xffffffff`. +- **Encoding and stage refusals**: `check_encoding` rejects reserved bit `w0[25]`, `nv` (`w1[23]`), and non-zero unused `data` (`w1[15:8]`). `Stage.op_global_load_dword` checks modifiers before arity so `lds` refuses by modifier name, allows cache flags (`glc`, `slc`, `dlc`) and 4-byte-aligned signed 12-bit `offset` (`-2048..2044`), and keeps `off` (`saddr = 0x7d`), unaligned immediate/pointer/`vaddr` offsets, sub-dword and multi-dword `GLOBAL` loads, `GLOBAL` stores/atomics, `FLAT`/`SCRATCH` loads, non-compute stages, table/heap/descriptor/numeric pairs, and incomplete or mismatched pointer pairs refused. + +[`tests/startup_compute_global_load_check.py`](../tests/startup_compute_global_load_check.py) builds 3 synthetic gfx1013 compute kernels (no game data) over 320 pairwise-distinct nonzero words in a bounded root view (`--compute-store-sized-case`), varies per-lane `vaddr`, scalar bases (direct, `s_mov_b64`-copied, single and chained `s_add_u32`/`s_addc_u32` advances, and multi-root SRVs), signed positive/negative immediate offsets (`+8`, `-12`, `-16`, `+2044`, `-2048`), positive-offset 64-bit overflow (`0xfffffffc + 8 -> base + 0x100000004`), negative-offset underflow (`0..12` below `16`/`4`), low-bit runtime offsets masked across distinct neighboring DWORDs, and partial `EXEC` masks, checks LLVM 15 `llvm-mc` / `libLLVM` round-trips, and executes 9 DXC `cs_6_0` dispatches plus 4 reference controls and 10 negative HLSL mutations per adapter on Microsoft WARP (`1414:008c`, driver `10.0.26100.9818`) and an AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`) with `0` debug-layer errors or warnings. + +```powershell +ctest --test-dir out/build/release --no-tests=error -R "^startup_compute_global_load_(controls|warp|hardware)$" -V +``` + +## Design B descriptor retention and host commit on a 16 GiB system (#2379) + +R0Y00's standing decision on #2379 keeps **design B** (#2679): a materialized descriptor and its copies own the +resource until the slot is overwritten, copied over, or the heap wrapper is destroyed. A final guest `Release()` +plus completed release fences retire prior references and submissions, but a live descriptor slot must still +support rebinding, so `drain_retired_resources()` frees a class member only when `retire_view_refs == 0` and no +recording hold or in-flight submission names it. Slice 3 ended with #2719 (slots 19-21 tracked like slot 18); +`X2W_D3D12_RELEASE_RETIRED_VIEWS` stays a legacy diagnostic that logs clearing is disabled. This rule intentionally retains live descriptor-owned bytes. The measurements below report total pressure and, where available, its ownership breakdown. + +### Matched retention pair (AMD Radeon RX 9070 XT, 16 GB, driver 32.0.32029.2010, Windows 11 26300) + +One release build, `main` `6b9fb9d9` (#2468 merged), only `X2W_D3D12_RELEASE_RETIRED` differs; same executable, +saved profile, warm shader cache, 32 GiB job cap, `X2W_D3D12_BUDGET=1`, `run.ps1 -Render`, 600 s window, scripted +input that clears the legal/acceptance page. [Matched RX 9070 XT runs](https://github.com/R0Y00/Xbox2Windows/issues/2379#issuecomment-7173347195) + +| | switch off | switch on | +|---|---|---| +| first failure / timeout | access violation at **490.7 s** after 8x `0x8007000e` | none; still running at the 600 s timeout | +| `0x8007000e` / device removed | 8 / 0 | 0 / 0 | +| desktop references dropped by the drain | 0 | 53,000 | +| texture retained, peak | **10.67 GB / 4,874** | **9.41 GB / 4,364** | +| texture retained, end | 10.67 GB / 4,874 | 9.10 GB / 4,267 | +| DXGI local usage / budget, peak | 20.32 / 14.51 GB | 19.91 / 14.46 GB | +| DXGI non-local usage, peak | 6.01 GB | 6.43 GB | +| system commit 10 s after exit | 24.9 GiB | 25.0 GiB | + +Retention climbs in steps and does not come back down (switch-on: ~0.08 GB at 290 s, 3.80 GB at 375 s, 6.28 GB at +460 s, 9.39 GB at 520 s). Slice 2 removed the out-of-memory failure inside the window but left local usage about +5.4 GB over the DXGI budget; a second switch-on run at `e29b1a7b` reached the timeout with 9.14 GB retained. The +~9 GB is the retained texture budget measured in these runs. The attribution below comes from a separate run. + +### Attribution: live slots vs recording holds vs in-flight work + +A separate roughly six-minute startup run at `1cce2a32` used a local opt-in counter to attribute each final-released resource that was still live. [Attribution report](https://github.com/R0Y00/Xbox2Windows/issues/2379#issuecomment-7174634554) + +``` +x2w-retire held: view-refs=2297/4445110272(oldest 4374f) never-class:buffer=8178/551813120 + never-class:dimension=4/262144 never-class:rt-ds-uav=14/200212480 + view-refs-in-visible-heap=2297/4445110272 total=10493/5197398016 unattributed=0/0 +``` + +About **4.4 GB** (4,445,110,272 bytes / 2,297 objects, oldest 4,374 frames) are slot 133 class members kept alive +only by a descriptor in a shader-visible heap that is never overwritten (`view-refs`, all in visible heaps); +~0.55 GB are never-class buffers and ~0.2 GB never-class RT/DS/UAV textures. `unattributed=0/0`: the counter +accounts for every retained byte. + +Upstream `X2W_D3D12_RETIRE_REASONS=1` (with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`) emits one +`x2w-retire held:` heartbeat line from `retire_reasons_line` (`src/startup_stubs/d3d12_xs_device.cpp`). The `Held` +taxonomy distinguishes the three ownership kinds R0Y00 asked to separate: + +- **live descriptor slots** - `view-refs` (a tracked `HeapInfo::shadow` cell still names the resource), plus + `view-refs-in-visible-heap` for the shader-visible subset; +- **recording holds** - `list-hold` (`retire_list_holds`, a closed recording that names the resource) and + `unqueued` / `drain-pending`; +- **in-flight work** - `flight` (`retire_flights`, a submission behind an unsignalled fence) and + `queued-waiting-fence`; +- resources that left the class are reported as `left-class:{view,view-copy,residency,present,hold-missed}` and + `never-class:{slot,buffer,dimension,msaa,rt-ds-uav,heap-type,heap-flags,title-memory,aliased,reserved}`, with + `total` and `unattributed` (budget `retained` minus the attributed sum) closing the line. + +On a GTX 1660 SUPER diagnostic run with the current tree the line reads +`never-class:buffer=2/131072 never-class:dimension=4/262144 never-class:rt-ds-uav=3/103481344 total=9/103874560 +unattributed=0/0`; the descriptor-owned bytes stay in the budget `retained` column because design B keeps them +resolvable, exactly as the matched pair above measures. + +### Host-commit measurements on a 16 GiB system + +The reporter used a GTX 1660 SUPER with 5,966 MiB of VRAM on Windows 11 and a 22,931.8 MiB system commit limit. A release build of main at `d1b2be6a`, including #2767 and #2770, ran for 180 seconds with `-Render -Translate -FakeUser -GpuMirror -LazyMemory`. It recorded 3,260 storage requests, 3,994 frames, and a host-commit peak of **11,053 MiB**. The reporter observed zero device-removal, out-of-memory or mapping-failure lines during the window. [Main-only result](https://github.com/R0Y00/Xbox2Windows/pull/2780#issuecomment-7187587300) + +A separate experimental build included #2767/#2770 and local versions of #2773/#2775. It enabled lazy textures and the large existing-heap cap and ran for 300 seconds, recording 3,260 storage requests and 6,434 frames. The existing-heap cap used in that build now requires `X2W_D3D12_CAP_EXISTING_HEAP=1`. These figures compare the reported historical baseline with the experimental combination. The runs do not isolate the contribution of individual patches. [Combined experimental result](https://github.com/R0Y00/Xbox2Windows/pull/2775#issuecomment-7186316341) + +| Metric | Reported historical baseline | 300 s experimental combination | +|---|---:|---:| +| Host commit peak | 12,144 MiB | 8,787 MiB | +| DXGI non-local peak | 2,897 MiB | 695 MiB | +| Existing-heap bytes | 2,199 MiB | 0 MiB | + +The experiment identifies remaining commit from slot 133 render-target, depth and UAV textures, small buffers subject to WDDM allocation granularity, and duplicate committed buffers for mapped memory. The descriptor retention rule described above still applies. + +### Verification + +```powershell +ctest --preset dev --no-tests=error -R "^startup_resource_(retire|budget)" -V +ctest --preset dev --no-tests=error -R "^startup_slot133_heap_cap_" -V +ctest --preset dev --no-tests=error -R "^(xmem_|startup_run_ps1)" -V +python -B tests/docs_links_check.py +``` + +`startup_resource_retire_reasons` drives the `Held` attribution line; `startup_resource_retire_views` proves the +design-B keep cases (a live slot stays reboundable after final `Release()` and completed fences). The tables above record contributors' local executable runs. The fixtures validate the retention behavior independently. Refs #2379, #2679, #2719, #1199. + +See [fixed mesh pipelines through slot 57](experiments/native-fixed-mesh57.md) for the source-built indirect-draw fixtures. + +## Binary16 normalized integer conversions (`v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16`) across VOP1/VOP3/DPP16/DPP8/SDWA in pixel_aot + +[The pixel shader translator](../tools/pixel_aot.py) adds 10 exact binary16 normalized integer conversion forms across all 5 encodings (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): + +- `v_cvt_norm_i16_f16` (`VOP1`, `VOP3` `_e64`, `DPP16`, `DPP8`, `SDWA` — 5 forms) +- `v_cvt_norm_u16_f16` (`VOP1`, `VOP3` `_e64`, `DPP16`, `DPP8`, `SDWA` — 5 forms) + +All 10 require explicit `half_denorm="preserve"`, refuse `HALF_RTZ`, enforce the static finite-proof contract (`#839`), and tag plain/e64/DPP/SDWA-DWORD destinations as `("low16", alu)` (readable only by audited 16-bit integer readers). `cvt_norm_i16_f16` (`round_rne(clamp(x, -1, 1) * 32767)`) and `cvt_norm_u16_f16` (`round_rne(clamp(x, 0, 1) * 65535)`) compute the exact rational product in 32-bit unsigned integer arithmetic, avoiding binary32 double-rounding on `0x3801..0x3804` / `0xb801..0xb802` and preserving subnormal inputs (`0x0100`, `0x03ff`, `0x83ff`) under `-denorm ftz`. + +```powershell +python3 tests/pixel_aot_check.py +ctest --preset dev --no-tests=error -R '^(pixel_aot_f16_cvt_norm_warp|pixel_aot_f16_cvt_norm_hardware|pixel_aot_binary)$' -V +``` + +Linux controls (including exhaustive verification against `fractions.Fraction` across all 63,488 finite binary16 values and single-instruction DPP16/DPP8 permutation-to-intrinsic checks pinning `QuadReadAcross{X,Y,Diagonal}` and `QuadReadLaneAt` lane order), `form_coverage_check.check_f16_cvt_norm_forms`, and Python mutation checks ran locally; Ubuntu LLVM 15 `pixel_aot_binary` round-trips run on PR CI, while `pixel_aot_f16_cvt_norm_{warp,hardware}` runs in `dev`/`release` presets and `main` CI (not `ctest --preset pr`). The draw harness compiles each fixture both optimized (`-denorm preserve`) and unoptimized (`-Od -denorm ftz`) so DXC retains the pure-`uint` conversion arithmetic in DXIL rather than constant-folding `plain_e32`/`plain_e64`/`sdwa` to immediate stores (note: because no binary32 float ops are emitted in `cvt_norm_{i16,u16}_f16`, `-denorm ftz` produces the same integer instructions as `-denorm preserve`). + +Independent Windows 11 (`26200.9974`, DXC `1.9.2602.17`, `debug_layer=unavailable`) measurements on `bd8f6f42` ([comment 1](https://github.com/R0Y00/Xbox2Windows/pull/2857#issuecomment-7196200555)) and `3100f363` ([comment 2](https://github.com/R0Y00/Xbox2Windows/pull/2857#issuecomment-7200844836)) passed `pixel_aot_f16_cvt_norm_hardware` (`AMD Radeon RX 9070 XT` `1002:7550`, driver `32.0.32029.2010`) and `pixel_aot_f16_cvt_norm_warp` with `max_absolute_error=0`, all 20 mutation draws mismatching, and DXIL disassembly confirming the `-Od` pass retains the `mul`/`lshr`/`shl` integer path. Scope limits: under `#839`'s static finite-proof contract (`half16_arith_source` / `half16_dpp_source`), operands are statically known per-lane uniform values, so device draw readbacks do not distinguish lane-routing changes on `dpp16`/`dpp8` (the permutation-to-intrinsic mapping is pinned statically in `check_f16_cvt_norm_controls`), mutation draws compile optimized rather than `-Od`, and the exhaustive 63,488-value check runs in Python rather than on-device. + + +## Native raw pixel buffer UAV binding + +The native graphics cache and draw stand-in support a single raw pixel UAV from a tracked descriptor table for a direct non-indexed draw without SRVs. The manifest records the table parameter and byte offset; the runtime requires an aligned raw R32_TYPELESS buffer view with valid bounds, UAV resource flags and compatible state, retains the resource, and orders consecutive UAV uses. Typed/structured views, mixed views and other draw paths are outside this slice (#3212, #3215; separate from #3094/#2981). + +```powershell +cmake --preset dev +cmake --build --preset dev --target startup_stream_consumer d3d12_xs_shim compile_dxil native_raw_buffer_view_check +ctest --preset dev --no-tests=error -j1 -R '^(native_pixel_raw_uav_(warp|hardware)|native_raw_buffer_view_controls)$' +``` + +Repeat with the release preset. The source-built shader pair goes through request publication, native DXIL, actual PSO/draw and GPU readback. The fixture checks full buffer and color-target contents, nonzero/short/end views, decoy and invalid descriptors; the validator also checks alignment and bounds. Local RX 7900 XT/WARP Debug and Release runs passed 54 cases (3,456 DWORDs and 1,728 pixels); the independent review over main 886a5a28 reproduced the same counts on RTX 4060 Laptop and WARP with the D3D12 debug layer enabled and zero errors. Actual title rendering impact is not established. + +## Native pixel raw DWORD atomic add + +The native pixel compiler supports raw DWORD buffer atomic add in a proven straight-line guest block, with exact coverage/EXEC, including restoration from whole-quad entry. GLC returns the old value, preserves inactive VGPRs, and returns zero for an active out-of-view access; without GLC the addend is unchanged. The runtime uses the single raw pixel UAV direct non-indexed draw contract above. Indexed atomics, other atomic operations, general CFG and unproven WQM remain refused (#3216, #3217). + +```powershell +cmake --build --preset dev --target startup_stream_consumer compile_dxil +ctest --preset dev --no-tests=error -j1 -R '^native_pixel_atomic_(warp|hardware)$' -V +``` + +Repeat with the release preset. The source-built fixture verifies 13 actual draws and four refusal controls per adapter/configuration, including contention, guard words, active out-of-view, odd raster edges and real WQM quad-neighbor reads with and without GLC. WQM+GLC records returned old values through a second exact atomic in a private lane slot and checks a valid serialization of the varying addends. Local RX 7900 XT/WARP Debug/Release integration over main 4b0350e passed 52 draws, 3328 DWORD and 1664 pixel comparisons, and 16 refusal controls. The debug layer was unavailable; actual title rendering is not established. diff --git a/docs/experiments/README.md b/docs/experiments/README.md new file mode 100644 index 0000000000..5b903b6c2e --- /dev/null +++ b/docs/experiments/README.md @@ -0,0 +1,9 @@ +# Experiment notes, one file per topic + +Write a new experiment note in `docs/experiments/.md` instead of appending to +[docs/experiments.md](../experiments.md), so two pull requests that each add a note do not edit +the same lines. The older notes stay in `docs/experiments.md`. + +A note follows the same rules as before: what was measured, the exact command, the result, the +environment, and what remains a hypothesis. Start the file with a `#` heading. Links in these +files are checked by `tests/docs_links_check.py`, like every tracked Markdown file. diff --git a/docs/experiments/agility-compute-views.md b/docs/experiments/agility-compute-views.md new file mode 100644 index 0000000000..dad7552550 --- /dev/null +++ b/docs/experiments/agility-compute-views.md @@ -0,0 +1,50 @@ +# Compute texture views with Agility SDK headers + +The translated Compute dispatch keeps the SRV or UAV description until it +recreates the typed view in its desktop descriptor heap. The dispatch now +stores the corresponding D3D12 type, so the temporary description has the +size and alignment specified by the build's headers. The active member +follows the input/output branch that creates the view. + +Guest capture records supply 40 bytes for each view. Dispatch copies that +prefix into a zero-initialized desktop descriptor before recreation. Checking +the record against the desktop size had treated valid 40-byte UAV records as +absent with Agility headers, leading 2D UAVs to use default mip 0 and causing +explicit 3D views to be refused. + +On x64, the Windows SDK 10.0.26100 header reports 40 bytes for both view +types. The Agility SDK 1.620.2 header reports 40 for an SRV and 48 for a +UAV. At `88cddb09`, configuring with `sdk.nupkg` in the Agility directory +therefore stops the `offscreen_check` build at the 40-byte assertion in +`record_translated_dispatch`. + +## Reproduction + +Use x64 Visual Studio Developer PowerShell with DXC and Python configured. +Set `$agility` to the absolute path of the directory with the Agility x64 +DLLs and `sdk.nupkg`, and `$warp` to the absolute path of the WARP x64 DLL +directory. The versions used +were [Agility SDK 1.620.2](https://www.nuget.org/packages/Microsoft.Direct3D.D3D12/1.620.2) +and [WARP 1.0.22](https://www.nuget.org/packages/Microsoft.Direct3D.WARP/1.0.22). + +```powershell +cmake --preset release +cmake --build --preset release --target startup_stream_consumer d3d12_xs_shim +cmake --preset release -B out/build/agility "-DOFFSCREEN_AGILITY_620_DIR=$agility" "-DOFFSCREEN_WARP_DIR=$warp" +cmake --build out/build/agility --target offscreen_check startup_stream_consumer d3d12_xs_shim compile_dxil +$tests = '^startup_compute_dispatch_(texture|two_mips)_(warp|hardware)$' +ctest --test-dir out/build/release --no-tests=error -j 1 -R $tests -V +ctest --test-dir out/build/agility --no-tests=error -j 1 -R $tests -V +ctest --test-dir out/build/agility --no-tests=error -j 1 -R '^(shader_wave32_warp|native_image_atomic_warp)$' -V +``` + +These cases exercise translated SRV and UAV binding, texture views with +different dimensions, and two UAVs at different mips of one resource. +On Windows 11 build `26300.10075`, all four texture cases passed with +both header configurations. The two-mip test matched 1,280 halfwords and +detected 64 changed halfwords when the views were swapped. The wave32 +probe and all seven native image-atomic readbacks also passed on app-local +WARP 1.0.22 with the Agility headers. + +The [WARP setup report](https://github.com/R0Y00/Xbox2Windows/issues/3160#issuecomment-7226553102) +records the two header sizes. diff --git a/docs/experiments/bc4-format-number.md b/docs/experiments/bc4-format-number.md new file mode 100644 index 0000000000..46b3fe7456 --- /dev/null +++ b/docs/experiments/bc4-format-number.md @@ -0,0 +1,18 @@ +# BC4 typed format number + +`texture_blocks.format_info("BC4_UNORM")` returns DXGI format 80, the public +`DXGI_FORMAT_BC4_UNORM` value. The old table returned 79, which names the typeless +parent. Both formats have eight-byte blocks, so the byte-row and volume tests +alone did not detect this metadata error. + +The two existing format-table checks now expect 80 independently of the module's +table. With the old implementation each check failed with `79 != 80`; after the +correction all 17 tests pass on Windows with Python 3.14: + +```powershell +python -B tests/texture_blocks_check.py +python -B tests/texture_bc_volume_check.py +``` + +This checks the format metadata and synthetic block rows. It does not establish +any change in rendered console textures or in the BCPack decoder. diff --git a/docs/experiments/bcpack-standalone.md b/docs/experiments/bcpack-standalone.md new file mode 100644 index 0000000000..b2a5245758 --- /dev/null +++ b/docs/experiments/bcpack-standalone.md @@ -0,0 +1,133 @@ +# Standalone BCPack BC1–BC7 reconstruction + +`src/startup_stubs/bcpack_decoder.h` reconstructs the seven BC block formats from +complete BCPack streams. BC2 uses fifteen lanes and BC6H uses sixteen. BC1 now +uses independent endpoint/index references and the full 255-entry initial +dictionary. The old fitted BC1 endpoint window and quadrant masks are removed. +BC6H supports all fourteen modes and changes of precision/subset count across +historical references. The output is packed BC blocks, not RGBA pixels. + +The DirectStorage stand-in decodes into a temporary buffer and publishes it +only after the complete request succeeds. BC2/BC6H no longer return successful +blank textures. An invalid format or malformed stream fails. Existing file, +memory, outer RFC 1950 zlib and physical-page destination handling applies. +Historical `bcpack-blank` counters remain in the log schema for compatibility; +this decoder does not produce blank-success requests. + +## Sources and constants + +The entropy decoder and existing BC3/4/5/7 code retain their bcpack-rs and +silicon-rans notices in [THIRD_PARTY_NOTICES.md](../../tools/_bcpack_rans/THIRD_PARTY_NOTICES.md). +The new BC1/2/6H routines are original C++ reconstruction code. Research used +the installed GDK interface, local implementation inspection, and comparisons +with public bcpack-rs and VIctory implementations. This is not a claim of a +strict clean-room process. No GPL implementation or binary table blob was +copied into these files. + +`bcpack_tables_extra.inl` contains fixed format dictionaries and rank mappings. +They were reconstructed by sending chosen, entirely synthetic lane streams to +the developer oracle's `BCPackDecompress` API and reading the resulting standard +BC fields. There is no sample fitting, approximation, per-asset lookup or +run-time learning. The recovery tool does not read the DLL's data section. + +The BC6H wire descriptors adapt Microsoft's MIT-licensed +[DirectXTex BC6HBC7.cpp](https://github.com/microsoft/DirectXTex/blob/a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379/DirectXTex/BC6HBC7.cpp), +revision `a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379`, SHA-256 +`187434fab12351df0f875ae09390981034e8479159a6f4aaaf0904f007182b8a`. +The emitted BCPack blocks use ascending high base-endpoint bits in modes 13/14; +the descriptor generator applies that ordering explicitly. Preserve the +DirectXTex MIT notice when redistributing those descriptors. + +Normal builds, tests and runtime DLLs require neither GDK nor BCPack.dll. +The optional oracle target and script below are development tools only. They +require a separately installed developer oracle, which is not redistributed. + +## Reproduce the public checks + +From an x64 Visual Studio developer PowerShell: + +```powershell +. ./tools/dev.ps1 +cmake --preset dev +cmake --build --preset dev --target bcpack_formats_check startup_stub_consumer startup_stub_xcrdapi +ctest --preset dev --no-tests=error -R '^(bcpack_all_formats|startup_bcpack_storage)' -V +python -B tests/bcpack_tables_check.py +``` + +The golden test generates 12,330 synthetic streams from source. It checks all +255 initial references plus the zero predictor, independently selected endpoint +and index references, all fourteen BC6H modes and all 32 partitions. Random +symbol streams cover all seven formats and block counts 2, 17, 255, 256, 257 +and 1024, including mode changes and history-ring wrap. BC7 selects all 285 +mapped controls. Every supported entropy path must reproduce the same bytes. + +Each group is checked against a fixed FNV-1a-64 hash of the independent oracle's +complete output. The expected hashes are not generated by the decoder under +test. A one-byte mutation must fail the golden control. Truncation, wrong output +alignment, nonzero trailing data and invalid formats must fail with zero bytes +reported. An undefined BC6H mode must fail too. The storage test checks full BC2 +and BC6H destination bytes against fixed synthetic oracle outputs across +memory/file, raw/zlib and linear/cross-page requests. Missing page grants, unsupported formats and a bad final BC6H mode after +three valid blocks must preserve the destination; a following valid request +must still succeed. + +The unchanged `synthetic_11` BC1 input in `startup_stub_consumer.cpp` had 491 +wrong bytes in its former 512-byte expected output. Its first eight expected +bytes were `85 31 64 d5 af be ff bf`; the oracle returns +`8d 73 0a 07 ea b8 fa be`. The fixture now checks the oracle's complete 512 +bytes, keeping the original input, size and malformed-input controls. + +## Optional oracle reproduction + +For the original experiment the installed BCPack library reported version +`1.2603.3.0`. Its binaries, private headers and title payloads are not part of +this repository. Supply paths to your own local installation and to the public +DirectXTex source pinned above: + +```powershell +cmake --build --preset dev --target bcpack_oracle_bridge +./out/build/dev/bcpack_formats_check.exe --oracle 'C:/path/to/BCPack.dll' +python -B tools/bcpack_recover_constants.py ` + --sdk 'C:/path/to/BCPack.dll' ` + --bridge out/build/dev/bcpack_oracle_bridge.dll ` + --bc6-reference out/DirectXTex/DirectXTex/BC6HBC7.cpp ` + --output out/bcpack_tables_extra.inl ` + --storage-goldens out/bcpack_storage_goldens.h +python -c "from pathlib import Path; assert Path('src/startup_stubs/bcpack_tables_extra.inl').read_text() == Path('out/bcpack_tables_extra.inl').read_text()" +python -c "from pathlib import Path; assert Path('tests/bcpack_storage_goldens.h').read_text() == Path('out/bcpack_storage_goldens.h').read_text()" +``` + +The recovery script queries each dictionary entry separately. BC1/2 ranks are +recovered with zero predictors. BC6H's base endpoint uses the sixteen-bit mode; +the other endpoints use modes exposing their complete stored precision. The +generated table file reproduced LF-normalized SHA-256 +`181f279bbc84a3e93aa4d44bf6f7c6e522493b3a92538b7209e4b22721a3a12e`. +An oracle change may change output; investigate differences before replacing +goldens or format constants. + +## Local comparison and limits + +A separate read-only comparison covered 105,845 chunks from 45 local archive +pools, totaling 16,356,958,208 decoded bytes. Every chunk was compared byte for +byte with the installed oracle on the AVX2 path. A distributed sample of 882 +chunks also used the reference and scalar paths. There were no byte mismatches +or guard violations. No archive bytes or extracted textures are included here. + +| Format | Local archive chunks | +|---|---:| +| BC1 | 100,020 | +| BC2 | 0 | +| BC3 | 35 | +| BC4 | 77 | +| BC5 | 325 | +| BC6H | 268 | +| BC7 | 5,120 | + +An additional 312 oracle-compressed synthetic cases across BC1–BC7 matched +byte for byte on all three paths, including random, repeated and historical +blocks and individual BC6H/BC7 modes. Inputs rejected by the oracle compressor +were excluded from that successful-compression count, not called passes. +The public synthetic golden suite supplies BC2 coverage independently of the +local archives. These are packed-block decoding checks, not GPU image or +full-application startup measurements. Finite test coverage cannot establish +correctness for every possible stream. diff --git a/docs/experiments/bvh-node-model.md b/docs/experiments/bvh-node-model.md new file mode 100644 index 0000000000..3f8b184752 --- /dev/null +++ b/docs/experiments/bvh-node-model.md @@ -0,0 +1,102 @@ +# Console BVH node model and witness set + +Refs [#1759](https://github.com/R0Y00/Xbox2Windows/issues/1759), +[#2413](https://github.com/R0Y00/Xbox2Windows/issues/2413) and +[#2603](https://github.com/R0Y00/Xbox2Windows/pull/2603). This note covers the +pure-Python node model in `tests/gfx1030_bvh_box/bvh_model.py` and the +model-only witness set in `tests/gfx1030_bvh_box/check.py --model-only`. The +HIP kernel, the gfx1030 code object and the shader translator are unchanged. + +## Node formats + +A node pointer has its kind in the low three bits. The rest addresses a +64-byte node as `(pointer >> 3) << 6`. The 32-bit form adds that offset to a +40-bit base held in descriptor DWORD 0 and the low byte of DWORD 1, in +256-byte units. The 64-bit form uses the absolute pointer. + +| Kind | Node | Bytes | Layout | +|---|---|---|---| +| 0-3 | triangle 0-3 | 64 | five vertices, three f32 each, bytes 0-59; ID DWORD at byte 60 | +| 4 | box, f16 bounds | 64 | four child pointers, then four boxes of six f16 from byte 16 | +| 5 | box, f32 bounds | 128 | four child pointers, then four boxes of six f32 from byte 16; bytes 112-127 unused | +| 6, 7 | instance, procedural | - | not read by this instruction | + +`TRIANGLE_VERTICES` is `((0, 1, 2), (1, 3, 2), (2, 3, 4), (2, 4, 0))`. +Triangle `k` uses those three node vertices. The ID byte for triangle `k` +selects the vertices weighted by I and J in bits 1:0 and 3:2; the remaining +vertex is `3 - I - J`. Bits 7:4 of the ID byte are ignored. A malformed ID +that names the fourth map nibble reads node vertex 0, as the arithmetic +lands. + +Descriptor DWORD 1 bit 31 enables nearest-first box sorting. DWORD 3 bit 24 +selects triangle return mode 1. DWORD 3 bits 31:28 hold the resource type, +`0x8`. + +## Results + +A box node returns four child pointers. A hit is included at its entry +distance; a miss or an absent child is `0xffffffff`. Sorting uses a strict +comparison, so equal entries keep their child order; misses sort last when +sorting is enabled. + +Triangle return mode 1 is `{t_num, t_denom, I_num, J_num}`, all as f32. On a +miss it is `{+inf, 1.0, 0.0, 0.0}`. The instruction does not test the ray +extent for triangles. Return mode 0 is not modeled in this slice. + +## Assumptions + +- Arithmetic is binary32 at each step, rounding to nearest even. Python + floats only carry the values; the result DWORDs are the f32 bit patterns. +- The inverse direction is an instruction input. The box test clamps it to + `+-FLT_MAX` before multiplying, so an origin exactly on a face does not + create `0 * infinity`. +- `fmin`/`fmax` return the non-NaN operand when one is NaN. A NaN minimum x + marks an absent box. Other NaN box components are outside the defined + input. +- A box is hit when `leave >= max(0, enter)` and `enter < extent`. An entry + exactly at the extent is not a hit. A box containing the origin can be hit + at a negative entry. +- The triangle test is the watertight Woop, Benthin and Wald formulation used + by RADV. A ray exactly through an edge or vertex hits both triangles that + share it. A NaN vertex, a zero determinant or a triangle behind the ray + misses. +- A zero direction gives an infinite inverse; the triangle shear then + produces NaN and the triangle misses. + +These choices follow Mesa RADV's MIT-licensed software emulation and the +RDNA 2 ISA descriptor tables. They are a CPU model, not a native measurement: +hardware rounding, which of two equally near boxes is returned first, and the +exact edge case remain assumptions. No code is copied from the GPL-3.0 +VIctory reference. + +## Witness set + +The model-only run has 315 cases: 231 node cases and 84 pointer-decoding +cases. The node cases are 66 f32 box, 46 f16 box and 119 triangle cases. The +expected four-DWORD results are literals in `check.py`; the runner does not +recompute them with the model. The existing five-ray FP32 box assertions in +`model_check()` still run before the witness set. + +Coverage includes sorted and unsorted hits, misses, ties, extent clipping, +disabled and zero child pointers, inverted and infinite bounds, negative +zero, NaN bounds and vertices, zero directions, f16 rounding, subnormals and +65504, all six triangle vertex permutations for each kind, ID high bits, +malformed IDs, shared edges and vertices, t = 0, triangles behind the ray, +and degenerate triangles. Pointer cases cover every kind, nonzero and +high bases, 48-bit wrap and the absolute 64-bit form. + +## Reproduce + +```sh +python3 -B tests/gfx1030_bvh_box/check.py --model-only +``` + +The command needs no GPU, HIP library or code object. The native five-ray +case still needs LLVM/LLD 15 and a gfx1030 HIP device: + +```sh +sh tests/gfx1030_bvh_box/build.sh +python3 -B tests/gfx1030_bvh_box/check.py --device 0 +``` + +No game files, dumps or third-party source are part of this fixture. diff --git a/docs/experiments/compute-output-buffer-reasons.md b/docs/experiments/compute-output-buffer-reasons.md new file mode 100644 index 0000000000..0ccfcba270 --- /dev/null +++ b/docs/experiments/compute-output-buffer-reasons.md @@ -0,0 +1,98 @@ +# Named reasons for a compute output buffer range + +A translated compute program's buffer output is bound only when a placed buffer aliases the title memory it +names, so the GPU writes reach the title. The single refusal `an output is not an aliased placed buffer range +with unordered access` is split into the condition that failed, in the same log and census lines, checked in +this order: + +1. `an output buffer descriptor is a view token` +2. `an output buffer descriptor has zero records` +3. `an output buffer range is over 16 MiB or not whole dwords` +4. `an output range crosses the end of a placed buffer` (also a range that two placements claim) +5. `an output is in title memory outside any placed buffer` +6. `an output is in a placed buffer that does not alias title memory` (a copied placement) +7. `an output buffer's resource was not created in the common state` (also an aliased resource with no recorded + information, which no fixture reaches) +8. `an output buffer range is not 16-byte aligned in its resource` +9. `an output buffer has no unordered access` + +Only the reason changes: what was bound is still bound and what was refused is still refused. Output view tokens +are lowered separately in #2961 (open), which binds a buffer UAV token before these checks; with it, reason 1 is +not reached. The census keeps one reason per key, the first one that key was refused with, and counts all of the +key's untranslated dispatches under it. A start-up run with this build therefore gives first-refusal buckets, not +a count per condition: a later dispatch of the same key can fail on another condition, and the per-call refusal +lines are capped. + +`tests/startup_compute_dispatch_output_check.py` dispatches case A of `startup_gfx2hlsl_compute_check.py` through +the stand-in's list on WARP and on a physical adapter (exit 77 without one). The unchanged recording matches all +320 words. Each of the nine conditions is then produced by one change to the output descriptor or its buffer, +and each dispatch refuses with its own reason in the log and the census and leaves every output word at its +sentinel. The common-state case also checks that its buffer was aliased. `dispatch-swapped` in +`startup_compute_dispatch_check.py` now expects reason 9. + +```powershell +ctest --preset dev --no-tests=error -R "^startup_compute_dispatch(_output)?_(warp|hardware)$" -V +``` + +Both tests pass on WARP (10.0.26100.9818) and on an RTX 4090 (driver 32.0.16.1088), Windows 11 build 26300, +debug layer on. With only the split reverted, the unchanged dispatch still matches and all nine cases are still +refused, each with the old reason, so all nine expectations fail: the set of refused cases is the same. + +Local observation, one 300 s start-up run with this build (`79edac55`; translator at `ad306425`, whose `gfx2hlsl.py` +is unchanged since `2e12dd8e`), counts only. A run of the parent build with the same settings refused 25 keys and +505,473 of 5,490,863 compute dispatches with the old reason as their first refusal. With the split, the same 25 +keys fall in these first-refusal buckets: + +| First refusal of the key | Keys | Untranslated dispatches of those keys | +|---|---|---| +| 1, view token | 23 | 141,224 | +| 2, zero records | 2 | 2,015 | +| 3 to 9 | 0 (no key had one of these first refusals) | 0 | + +The run made 1,490,517 compute dispatches in all, so the share in these buckets is about the same (9.2% and 9.6%). +In the first refused dispatch of each of the 23 keys, the token named a view created through device slot 19, the +form #2961 binds. In that of each of the two zero-record keys, the descriptor was all zero. No key had a copied +placement, the initial state, alignment or the unordered-access flag as its first refusal; later dispatches were +not recorded per condition. + +The same run with #2961 merged locally (`51aef000`, not pushed; reason 1 dropped, #2961's token branch first): + +| The 23 token keys | Keys | Dispatches | +|---|---|---| +| every dispatch translated, no refusal | 12 | 32,043 | +| first refusal: `an entry value reads the descriptor of an output named by a view token` | 10 | 9,372 untranslated | +| first refusal: `an output buffer view range is empty, unaligned or outside its resource` | 1 | 190,397 untranslated | + +No key had `an output view token is not a buffer UAV of a desktop resource` as its first refusal: every dispatch of +the 12 translated keys, and the first refused dispatch of each of the other 11, named a buffer unordered access view +of a desktop resource. That run made 2,453,727 compute dispatches, so dispatch counts compare only within one run. +Whether the 12 translated keys write the right values was not checked. + +## Published half-width buffer stores + +A native slot 67 request with a `half_buffer_uav` now publishes +`uav bufhalf table bytes `. The +stride selects a typed buffer view of `R16_FLOAT`, `R16G16_FLOAT` or +`R16G16B16A16_FLOAT` for 2, 4 or 8 bytes respectively. The runtime +requires the matching gfx10 buffer format, identity selects over the +written components and structured out-of-bounds mode. It binds the +descriptor's record count and element-aligned offset into an aliased +placed buffer after checking typed-store support. The typed range can +end on a halfword. Raw outputs keep their dword and 16-byte alignment +checks. Buffer UAV tokens are tracked in #2961. + +The source-built check compiles a D16 store for each width with +`compile_dxil --requests`, then runs the published translation through +slot 14. Each dispatch attempts more stores than the view has records. +The reference checks 13 records at a nonzero view offset, plus the +full prefix and suffix. Invalid formats, selectors, strides, swizzle, +out-of-bounds mode and ranges are refused before a dispatch is recorded. + +```powershell +ctest --preset release --no-tests=error -R '^startup_compute_half_buffer_uav_' -V +``` + +The descriptor checks follow the buffer resource format in the +[AMD RDNA 2 ISA](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). +The matching desktop view uses `FirstElement` and `NumElements` from +the [D3D12 buffer UAV contract](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_buffer_uav). diff --git a/docs/experiments/direct-compute-exact-width-image-store.md b/docs/experiments/direct-compute-exact-width-image-store.md new file mode 100644 index 0000000000..dd95da6d9a --- /dev/null +++ b/docs/experiments/direct-compute-exact-width-image-store.md @@ -0,0 +1,26 @@ +# Exact-width image stores in direct compute + +The direct gfx1013 compute translator lowers non-D16 `image_store` with +`dmask:0x1`, `0x3`, or `0x7` on 2D, 2D array, and 3D images. It consumes +one, two, or three consecutive VDATA VGPRs and declares a typed float, +float2, or float3 UAV. The DXIL store uses the full typed-store mask. +The narrower resource type determines which components reach the texture. +The `unorm` instruction modifier continues to leave the integer texel +coordinates unchanged. + +Manifest version 2 describes these outputs with +`uav float table channels <1|2|3>`. +The in-process path gets the same width from the translated binding. +The runtime requires the view and resource formats to have the specified +component count and checks adapter support for typed stores on the resource +format. It creates the UAV with that format and retains the bound subresource +range. This makes each accepted store a whole texel write. Sparse masks still +receive the translator's descriptor modifier refusal. + +The readback fixture dispatches two X groups of 4x2x1 threads into a 32x8 mip. +It explicitly sets EXEC to `0x55`, writing columns 0, 2, 4, and 6 in rows +0 and 1. The array and volume cases use relative slice 1 of a view that +starts at physical slice 1. Every other texel retains its sentinel. +The format cases use R32_FLOAT, R32G32_FLOAT, and R11G11B10_FLOAT. The +RGBA8 control leaves the complete image untouched and checks the runtime +channel-count refusal. diff --git a/docs/experiments/dxc-gvn-off-warp.md b/docs/experiments/dxc-gvn-off-warp.md new file mode 100644 index 0000000000..003e0bdea2 --- /dev/null +++ b/docs/experiments/dxc-gvn-off-warp.md @@ -0,0 +1,102 @@ +# DXC without GVN: pass shares, DXIL size and an oracle check on WARP and an RTX 4090 + +[DXC compile time on a mixed-sampler compute shader](../experiments.md#dxc-compile-time-on-a-mixed-sampler-compute-shader) +found that Global Value Numbering (GVN) dominates DXC's time on the generated `samplebranch_N` +and `condstore_N` shaders. It also found that `-opt-disable gvn` removes most of that time, and +noted that the GVN-off DXIL had not been checked on a GPU. This note adds four things: + +- GVN's pass share at the two larger `samplebranch_N` sizes; +- the DXIL size cost of switching GVN off; +- the sampler oracle on WARP and on an RTX 4090, run on GVN-off and default DXIL; +- how long each adapter takes to create and run those pipelines. + +The shaders are the synthetic families of `tools/dxc_compile_time.py`, not translated title +shaders. + +## Environment + +Measured on 27.11.2026 on a Ryzen 9 7900X (12C/24T), Windows 11 build 26300, one compile at a time. + +- **DXC:** 1.9.0.5512 (`01b62ad47`) from LunarG Vulkan SDK 1.4.363.0, the same build as the earlier tables. +- **WARP:** 10.0.26100.9818. +- **GPU:** NVIDIA GeForce RTX 4090 (`10de:2684`), driver 32.0.16.1088. No other GPU test was running. +- **Oracle:** `offscreen_check` from a Debug `dev` build. The checkout was at `1ec2c938`; the binary was not rebuilt for this note. It printed `debug_layer=enabled`, and the layer reported 0 errors and 0 warnings on every run. +- **Repetitions:** every row is a single run. The earlier note found 20-45 % variation between sessions on the largest variants. + +## GVN share of pass time + +```powershell +out\pe-env\Scripts\python.exe -B tools\dxc_compile_time.py --dxc --variants samplebranch_4096 --ftime-report --timeout 90 --out out\dxc-compile-time\passes.json +out\pe-env\Scripts\python.exe -B tools\dxc_compile_time.py --dxc --variants samplebranch_8192,samplebranch_16384 --ftime-report --timeout 300 --out out\dxc-compile-time\passes-large.json +out\pe-env\Scripts\python.exe -B tools\dxc_compile_time.py --dxc --variants samplebranch_4096,samplebranch_8192,samplebranch_16384 --extra-arg=-opt-disable --extra-arg=gvn --ftime-report --timeout 300 --out out\dxc-compile-time\nogvn.json +``` + +| variant | HLSL bytes | wall s, default | pass s, default | GVN s (share) | other passes s | wall s, GVN off | pass s, GVN off | +|---|---:|---:|---:|---:|---:|---:|---:| +| samplebranch_4096 | 968,577 | 4.907 | 4.234 | 2.672 (63.1 %) | 1.56 | 2.328 | 1.609 | +| samplebranch_8192 | 1,946,457 | 17.821 | 16.453 | 12.688 (77.1 %) | 3.77 | 5.140 | 3.703 | +| samplebranch_16384 | 3,915,833 | 60.028 | 57.188 | 48.562 (84.9 %) | 8.63 | 11.194 | 8.125 | + +- **GVN grows about fourfold per doubling** (4.75x, then 3.83x). The other passes grow 2.4x and 2.3x. +- **The other passes take a similar total time with GVN off:** 1.61, 3.70 and 8.13 s, against 1.56, 3.77 and 8.63 s for the passes other than GVN in the default runs. These are single-run totals. They do not show whether time moves between individual passes. +- **Speed-up:** 2.1x, 3.5x and 5.4x in wall time. `samplebranch_16384` compiles in 11.2 s here, against 18-28 s on the Ryzen 7 3700X in the earlier note. That earlier figure is still slower than `-Od`. +- **Largest passes with GVN off:** instruction combining (25.6-29.1 %) and the always-inline inliner (12.5-14.6 %). +- **Timer resolution:** the reported pass times are multiples of about 15.6 ms. Shares on variants below about 0.5 s are not meaningful. + +## DXIL size + +| variant | DXIL bytes, default | DXIL bytes, GVN off | change | +|---|---:|---:|---:| +| control | 4,020 | 4,024 | +0.1 % | +| samplebranch_4096 | 827,400 | 976,744 | +18.0 % | +| samplebranch_8192 | 1,802,276 | 2,071,784 | +15.0 % | +| samplebranch_16384 | 3,724,428 | 4,244,768 | +14.0 % | + +A second compile with `--work-dir` gave the same sizes; the contents were not compared. On WARP and +the RTX 4090, the larger DXIL took the same time to create and run as the default DXIL (below). +Whether the driver's compiler recovers what GVN would have removed in the final GPU code is not +measured. + +## Oracle on WARP and an RTX 4090 + +```powershell +out\pe-env\Scripts\python.exe -B tools\dxc_compile_time.py --dxc --variants control,samplebranch_4096,samplebranch_8192 --extra-arg=-opt-disable --extra-arg=gvn --timeout 300 --work-dir out\dxc-oracle\nogvn --out out\dxc-oracle\nogvn.json +out\pe-env\Scripts\python.exe -B tools\dxc_compile_time.py --dxc --variants control,samplebranch_4096,samplebranch_8192 --timeout 300 --work-dir out\dxc-oracle\gvn --out out\dxc-oracle\gvn.json +out\build\dev\offscreen_check.exe warp --spirv-sampler-views out\dxc-oracle\nogvn\samplebranch_4096.cso +out\build\dev\offscreen_check.exe hardware --spirv-sampler-views out\dxc-oracle\nogvn\samplebranch_4096.cso +``` + +Each CSO ran once per adapter, one at a time. + +`offscreen_check --spirv-sampler-views` dispatches the shader under three sampler +arrangements and compares UAV words 0-3 with the fixture's expected values. Its UAV holds 16 +bytes, so the generated body's stores fall outside it. The oracle shows that the GVN-off +DXIL creates a pipeline, dispatches, and keeps the control stores right. It does not check +the body that GVN would have optimized. + +Wall times cover pipeline creation and three dispatches of two groups each. + +| CSO | WARP result | WARP wall s | RTX 4090 result | RTX 4090 wall s | +|---|---|---:|---|---:| +| control, GVN off | pass | not timed | pass | 0.8 | +| samplebranch_4096, default | pass | 79.2 | pass | 18.0 | +| samplebranch_4096, GVN off | pass | 79.1 | pass | 18.2 | +| samplebranch_8192, default | no result: blocked, stopped by hand | about 1,080 | pass | 83.9 | +| samplebranch_8192, GVN off | not run | - | pass | 85.6 | +| negative control | fails as expected | not timed | fails as expected | 17.6 | + +- **Passing runs:** every one printed `sample 0.25 0.75, comparison 0 1`, then `0.75 0.25, 0 1`, then `0.25 0.75, 1 0`. +- **Negative control:** in the GVN-off `samplebranch_4096` HLSL, the u coordinate of the first control store was changed from 1.25 to 0.25, and the file was compiled with the same flags. With a clamping sampler the shader then reads texel 0 instead of texel 1. On both adapters the oracle exited with status 1 and reported word 1 of swaps 0 and 2 and word 0 of swap 1 as `expected=3f400000 actual=3e800000` (0.75 against 0.25). +- **Same adapter time with or without GVN:** on both adapters, the 15-18 % larger GVN-off DXIL took the same time as the default DXIL, within 2 %. +- **The adapter, not DXC, takes most of the time:** on the RTX 4090, creating and running `samplebranch_4096` takes 3.7 times DXC's time with GVN on (18.0 against 4.9 s) and 7.8 times with GVN off. At `samplebranch_8192` it takes 4.7 and 17 times. WARP takes 79 s at `samplebranch_4096`, 16 and 34 times DXC's time. +- **RTX 4090 time grows 4.7x per doubling:** 18.0 to 83.9 s with default DXIL, and 18.2 to 85.6 s with GVN off. Because the dispatches are two groups each, this is most likely pipeline creation, but the split was not measured. +- **`samplebranch_8192` blocked on WARP:** the default-optimization CSO used 27.4 s of CPU time. After that, sampled 17 minutes after the start, the process had one thread, the same CPU time in two samples 3 s apart, and a steady 228 MiB working set. It was stopped after about 18 minutes, so it did not reach a readback. Where it waits was not determined. The GVN-off 8192 CSO was not run on WARP. The same default CSO passed on the RTX 4090, so the DXIL itself creates a working pipeline. +- **Earlier runs:** the earlier note ran WARP only up to `samplebranch_4096`, with default optimization. On an RTX 4060, `samplebranch_12288` pipeline creation did not return within about 9 minutes. + +## Not covered + +- Adapters other than WARP and the one RTX 4090, AMD GPUs in particular, WARP beyond `samplebranch_4096`, and either adapter beyond `samplebranch_8192`. +- How each adapter's time splits between pipeline creation and the three dispatches. +- The body stores of the generated shaders, and any translated title shader. +- Whether `-opt-disable gvn` is safe as a translation setting. This note does not propose it as one. +- Why GVN scales this way. The earlier note's mechanism, repeated handle creation feeding non-local memory-dependence queries, remains a hypothesis. diff --git a/docs/experiments/exe-structurization.md b/docs/experiments/exe-structurization.md new file mode 100644 index 0000000000..d1b76d37b9 --- /dev/null +++ b/docs/experiments/exe-structurization.md @@ -0,0 +1,223 @@ +# EXEC removal and structurization for the shader frontend + +The startup translator refuses a large fraction of the title's shaders on control-flow and lane-mask +shapes. The same shapes recur across compute, graphics and mesh programs: + +| Refusal family | Example measured on 26 November 2026 | Count | +|---|---|---:| +| `s_cbranch_execz` / `s_cbranch_scc0` inside a skipped block | `s_branch inside an s_cbranch_execz block` | 331 (RTX 3090 run) | +| Slot 57 mesh skipped-block effects | `slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes` | 241 | +| `v_readfirstlane_b32` without a proven uniform source | `v_readfirstlane_b32 requires a proven uniform source` | 526 | +| `src_scc` with unverified SCC | `src_scc with unverified SCC` | 762 (rev28 census) | +| Wave reductions in branched programs | `wave reduction in a program with branches` | present in the census | + +The 26 November census held 3,007 `.fail` records (2,564 compute, 275 graphics, 162 mesh). Adding +one accepted shape at a time moves a request to the next refusal more often than it produces a +complete translation. The mesh notes record exactly that: a change accepts 91 of 407 requests at one +pre-check, and all 91 stop at the next refusal, with no new complete translation. + +This note proposes a structural fix: lower the program **as one lane runs it**, without EXEC, then +emit HLSL from the structured control flow. It is a design for the C++ frontend; the current Python +translator remains the reference for instructions that already translate. + +## Why the local pattern approach does not converge + +EXEC, VCC, SCC and the saved-exec registers are one dependency graph. A rule that proves a scalar +dead at one join, or a mask equal to a lane's own bit, depends on the paths that reach the join and +on every writer of the mask. A pattern that accepts one shape without a general representation of +that graph leaves the next shape refused. The refused shapes also interact: + +- a branch on a mask test is also a join of the mask; +- a scalar load inside an EXEC-zero block is uniform only because the guest runs the block once per + wave, while the per-lane model may run it per lane; +- a `v_readfirstlane_b32` waterfall has one descriptor per lane and needs the per-lane source that + produced it; +- a wave reduction is a loop over lanes that changes EXEC on purpose. + +## Proposed pipeline + +``` +decode -> CFG/SSA -> normalise special registers -> per-lane mask booleans + -> structurize without EXEC -> path-sensitive guard proof + -> resource/address tracing -> HLSL -> DXIL +``` + +### 1. Decode and CFG/SSA + +Keep the existing gfx10 decoder. Build basic blocks and SSA values for VGPRs, SGPRs, SCC, VCC and +EXEC. The CFG must be reducible for DXIL; refuse irreducible graphs with a named reason rather than +guessing. Record, for each instruction, the block and the word offset for diagnostics. + +### 2. Normalise special registers + +Turn writes to EXEC, VCC, VCCZ and the saved-exec registers into explicit values. A write from +`v_cmp*`, `s_and_b64`, `s_or_b64`, `s_cselect_b64`, `s_mov_b64` or `s_*_saveexec` becomes a mask +value, not an opaque register. A write the pass cannot follow becomes an `Opaque` mask atom and is +kept as a per-lane boolean, with a refusal only where a later use needs a stronger fact. + +### 3. Per-lane mask booleans + +Represent a lane mask as a Boolean function over these atoms: + +- `Lane(value)`: the lane's bit of a VALU-written compare or carry result, before EXEC masking; +- `Uniform(value)`: an SCC value that is the same in every lane; +- `Phi(value)`: a mask joined at a block entry; +- `Quad(value)`: an `s_wqm` result (some lane of the quad is in the source mask); +- `Opaque(value)`: a mask the pass cannot see into; +- `Constant(mask)`: all lanes, no lanes, or a constant mask. + +A reduced ordered binary decision diagram (BDD) gives canonical equality and cheap `and`/`or`/ +`not`/`ite`. The alternative is a bitset per atom set; the BDD wins when the same mask is rebuilt +along many paths, and loses on pathological atom counts. Whichever representation is chosen, the +interface must expose: `lane_bit(mask, lane)`, `is_all`, `is_none`, `is_equal(a,b)`, and substitution +of a lane's bit for a uniform branch. + +### 4. Remove EXEC + +Translate the program as one lane. For each vector instruction, compute the guard +`lane_bit(EXEC_at_instruction, lane)`. If the guard is `true` for every lane that reaches the +instruction, emit it unguarded. Otherwise emit a per-lane `if` around it. This is valid because the +guest drops the instruction's side effects outside EXEC, and PC hardware only requires the same +result in the lanes that matter; helper-lane work is dead except where derivatives or quad +operations read it. + +A branch on a wave-wide mask test (`s_cbranch_execz`, `s_cbranch_vccz`, an SCC computed from a mask) +becomes a branch on `lane_bit(mask, lane)` for the lane being modelled. A path-sensitive pass then +proves where the guard is constant and removes the `if`. + +### 5. Structurize + +Recover `if`/`else`, `break`, `continue` and loops from the reducible CFG. Keep the block shape so +diagnostics and the existing instruction offsets survive. A loop's EXEC changes must be modelled per +iteration; the pass must not hoist a mask out of a loop unless the loop is proven not to change it. + +### 6. Path-sensitive guard proof + +For each instruction, collect the mask facts that hold on every path to it. Prove a guard `true` when +all reaching paths imply it; prove `false` when none reaches it. Only emit a per-lane `if` when the +proof cannot decide. This is the step that turns the general model into the small HLSL the current +translator emits for its accepted shapes. + +### 7. Resource and address tracing + +Trace each descriptor and scalar address to a root parameter (table, heap, root descriptor, root +constant) or to a raw title address. A descriptor that a waterfall reads in the first lane is traced +to the per-lane load or choice that produced it. A raw address is a 40-bit title address, not a +desktop pointer; it needs the page directory and a bound resource, or a named refusal. + +## Mapping to the C++ frontend + +The Python translator's accepted instruction set is the semantic reference, not the architecture. +Keep its tests and its refusal strings. Move the following into the C++ frontend as separate passes +with their own fixtures: + +| Current Python area | C++ pass | Keep | Replace | +|---|---|---|---| +| `Stage.execz_refusals`, per-shape mask proofs | CFG/SSA + mask BDD | refusal reasons and tested shapes | ad-hoc shape matching | +| `spill_*`, `uniform_branches` | normalise special registers + guard proof | spill-slot semantics | per-instruction exception tables | +| `uniform_image_load_regs` / `v_readfirstlane` proof | resource/address tracing | per-lane descriptor facts | local scan heuristics | +| wave-reduction recogniser | cross-lane operation pass | opcode set and wave32/wave64 rules | pattern matching on the chain | +| mesh skeleton | mesh pass on the same CFG | group-index/count exchange rules | duplicated EXEC rules | + +The frontend should keep a `--explain` path that names the first unresolved fact for each refused +program, so a census remains comparable with the Python `.fail` reasons. + +## Phases + +### Phase 1: uniform skipped blocks + +Accept an `s_cbranch_execz` block entered by a wave-uniform condition whose scalar writes are dead at +the join. Emit the block once per wave, predicate vector writes by the lane's EXEC bit, and keep an +empty wave from issuing loads. This is the shape already measured in the slot 57 notes; it is a +useful first test of the model but not the end state. + +Acceptance: a source-built gfx1013 compute or mesh program with a uniform skip and a dead scalar +write translates; a control with a live scalar at the join is refused by name; the current +translator's accepted programs still produce the same pixels. + +### Phase 2: mask joins and SCC branches + +Add the BDD or bitset representation. Cover `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_not_b64`, +`s_cselect_b64`, `s_cmov_b32`, `s_cbranch_scc0/1`, and `v_cndmask_b32` mask selection. The first +target is the 762 `src_scc` census entries and the 95 `s_cbranch_scc0` inside skipped blocks. + +Acceptance: a differential set of programs where the current translator accepts one form and the new +pass accepts the neighbours; a control that uses a varying SCC as a uniform branch must be refused, +not miscompiled. + +### Phase 3: `v_readfirstlane` and waterfalls + +Trace the per-lane source of a first-lane read through `v_cndmask_b32`, an if/else whose arms set +the same descriptor, or a load from a per-lane descriptor. Cover the 526 first-lane refusals and the +remaining mesh group-index reads. + +Acceptance: a source-built descriptor waterfall whose lanes select different buffers; a control with +an unproven lane source is refused; a draw reads the expected texels. + +### Phase 4: wave reductions + +Model the reduction as a lane loop or as the corresponding wave intrinsic when the shape is proven. +Keep the existing wave32/wave64 opcode set (`v_or_b32`, `v_min_u32`, `v_max_u32`, the saveexec form) +and extend only with a tested shape. The current straight-line-only restriction is the thing to +remove; the identity fill and the partial-mask rules must stay explicit. + +Acceptance: a reduction inside a branch and a loop; a wave64 control; a partial-mask control that +must refuse. + +### Phase 5: helper lanes, quads and mesh + +Helper lanes count as live for derivatives and quad operations. Model `s_wqm`, quad reads and the +mesh group-index/count exchange on the same CFG. This is where the slot 57 mesh path and the pixel +helper-lane path converge; do not fork a second EXEC model for mesh. + +Acceptance: the existing quad/helper-lane fixtures, the mesh wave-block fixtures, and a new mesh +program with a count exchange and a real export. + +## Test and oracle strategy + +- **Differential against the current translator:** for every shape the Python translator accepts, + the new pass must produce the same pixels or the same raw words. This is the strongest regression + oracle and costs no new golden data. +- **Source-built gfx1013 programs:** one program per phase, assembled with the existing fixtures, + with expected values written out independently of the pass. +- **Negative controls:** a live scalar at a join, a varying SCC used as a uniform branch, an + unproven first-lane source, a partial-mask reduction, and an irreducible CFG. Each must be refused + by name, not translated approximately. +- **GPU coverage:** WARP for every shape; hardware on the available Radeon/NVIDIA adapters for the + first program of each phase. Report capability skips separately. + +## Risks and non-goals + +- **BDD blow-up:** cap the atom count and fall back to a bitset or a named refusal. A cap that + silently changes semantics is not acceptable. +- **Irreducible CFG:** refuse; DXIL requires reducible control flow. +- **Helper lanes:** a per-lane model can drop work that derivatives read. Keep helper lanes live in + pixel stages and prove the quad operations. +- **Wave width:** wave64 semantics on a wave32 host need exact lane-mask handling; the existing + wave64 tests remain the reference. +- **Resource tracing is not part of the control-flow pass.** Keep it separate so a mask bug does not + hide a binding bug. +- **Non-goal:** translating every instruction at once. The pass order must land behind tests, one + phase at a time. + +## Recommended first patch + +Start with Phase 1 in the C++ frontend or, if the frontend is not ready, add the same uniform-skip +rule to the Python translator behind a narrow fixture. The patch should: + +1. accept one wave-uniform `s_cbranch_execz` block with scalar writes dead at the join; +2. predicate vector writes by the lane's EXEC bit; +3. refuse a live scalar at the join and an empty-wave load by name; +4. prove it on the existing slot 57 wave-block fixture and one compute program. + +That is small enough for one reviewable PR and gives the C++ frontend its first end-to-end control- +flow test without pretending the general pass is finished. + +## References + +- `tools/startup/gfx2hlsl.py`: `Stage.execz_refusals`, `spill_*`, `op_v_readfirstlane_b32`, the + wave-reduction recogniser, and the slot 57 skeleton. +- `docs/experiments/startup-mesh57-wave-block.md` and `startup-mesh57-dead-block-scalar.md`. +- Issues #2125, #2413, #2023, #1723 and #1143. +- The public design description of DexNom/VIctory's `structure.rs` (GPL-3.0; read-only, no code + copied): per-lane booleans, EXEC removal, structured control flow, helper lanes. diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md new file mode 100644 index 0000000000..0e12b27e1f --- /dev/null +++ b/docs/experiments/f16-alu-direct.md @@ -0,0 +1,66 @@ +# Binary16 arithmetic in the direct compute path + +The direct C++ compute frontend supports VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`, plus VOP1 and VOP3 `v_rcp_f16`, `v_sqrt_f16`, `v_rsq_f16` and `v_exp_f16`. All eight operations support SDWA. Graphics programs keep the generic direct-lowering refusal. + +## Semantics + +- Each source is its low 16 bits by default. An inline float uses the binary16 rounding of that f32 value. An integer inline or a literal uses its low 16 bits. SDWA accepts WORD_0, WORD_1 or DWORD (low half). +- abs clears bit 15 of the half, then neg toggles it. +- The operation is an f32 add, sub or mul. An f32 value has a 24-bit significand, which covers a correctly rounded binary16 add, sub or mul. +- Reciprocal computes `1.0 / x` in f32. The other unary operations use DXIL Sqrt (24), Rsqrt (25) and Exp (21, base two). +- Reciprocal exchanges signed zeros and signed infinities. Square root preserves signed zero and produces NaN for negative nonzero inputs. Exp returns 1 for either signed zero, infinity at and above 16, positive zero at and below -25, and the canonical quiet NaN for NaN inputs. The emitter handles the exact underflow tie at -25 explicitly. +- The result is rounded with the same integer round-to-nearest-even conversion `v_cvt_f16_f32` uses. The low 16 bits are written and the high half is preserved. SDWA writes the selected half and pads or preserves the other half. +- Rsq maps +0 to +infinity, -0 to -infinity and +infinity to +0. It returns a quiet NaN for NaN and negative nonzero inputs, including -infinity. +- The emitter selects these results using the binary16 source bits after abs and neg. D3D Rsqrt does not guarantee -infinity for -0, so the rsq zero result takes its sign directly from the source. +- `v_subrev_f16` subtracts the first source from the second. +- DPP16 VOP2 permutes the full src0 VGPR word before selecting its low half and honors FI, BOUND_CTRL, and row and bank write masks. + +## Exp and rsq accuracy + +The Shader Model 4 assembly references specify a maximum relative error of 2^-21 for both host operations. For a normal f32 result this is less than eight f32 ULP. Every binary16 exp rounding midpoint is in the normal f32 range. [Microsoft Learn exp](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/exp--sm4---asm-) and [Microsoft Learn rsq](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/rsq--sm4---asm-). + +Exp targets RDNA 2's 0.5 ULP by selecting the correctly rounded half for the 70 non-tie inputs within that window and resolving the exact tie separately. The [90-digit generator](../../tests/f16_exp_midpoints.py) enumerates the binary16 inputs and the model check compares its entries with the C++ array. The IR and GPU comparisons require exact exp bits, including the canonical NaN, the tie at -25, and all 70 inputs in both VOP1 and VOP3. The table covers 0x11c4, 0x11c5 and 0x11c6. Modifier cases exercise correction after source selection and modification. + +For positive finite rsq results, a relative error of 2^-21 contributes at most 2^-10 of a binary16 ULP. Integer RNE adds at most 0.5 ULP in the rounding interval, for a total of at most 0.5 + 2^-10 < 0.51 ULP. The [reference model](../../tests/f16_packed_model.py) compares squared rational endpoints against the exact input to locate the result. It accepts either adjoining half only when the exact result is closer than eight f32 ULP to their midpoint. Both plain encodings and SDWA cover 0x3bfe, which exercises the alternate result. + +The [plain-form fixture](../../tests/native_f16_alu_check.py) covers signed zeros and infinities, quiet and signaling NaNs, negative finite values, subnormals, 1, powers of two and general values. Its IR interpreter models Rsqrt returning +infinity for -0 to exercise the sign fix. The [SDWA fixture](../../tests/native_sdwa_f16_check.py) exercises source selection and modifiers, destination padding and preservation, and negation of +0 before rsq. + +## Refused forms + +The SDWA operand profile is covered by the [SDWA experiment](native-sdwa-f16.md). + +Each of these is a named diagnostic: + +- DPP8 +- clamp or omod +- a high-half `op_sel` (instruction bits 11 through 14) +- a binary16 rounding mode other than round-to-nearest-even, an f16 denormal mode other than keep on input and output, or `FP16_OVFL` +- `s_setreg_b32` of those MODE bits, because the source is a register + +`s_round_mode` and `s_denorm_mode` that leave the f16 fields at that contract, and that leave the f32 fields unchanged, are accepted. A write that changes an f32 rounding or denormal field keeps the previous control-instruction refusal. A guest branch together with a MODE write makes the contract unprovable and is refused with the rounding diagnostic. + +For the plain scalar-half forms, fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup and the VOP1 ops other than rcp, sqrt, exp and rsq stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16`, `v_min_f16` and `v_log_f16`. The host Log absolute error allowance of 2^-21 near an input of 1 can exceed 0.51 ULP of the small binary16 result, so log needs a tighter bound or a bounded correction before lowering. [Microsoft Learn log](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/log--sm4---asm-). + +## Linux + +Python 3.12.3. `compile_dxil` is created only in the `WIN32` section of `CMakeLists.txt`, so this host did not build that target. The IR dumper was compiled from `src/gfx1013_compute_native.cpp`, `src/gfx1013_isa.cpp`, `src/guest_shader_container.cpp`, `src/gfx1013_compute_ir.cpp` and `tests/native_compute_ir_dump.cpp` with g++ 13.3.0 and a local stub of `d3d12.h` and `wrl/client.h`. That stub is not in the tree. + +``` +python3 -B tests/native_f16_alu_check.py model +python3 -B tests/native_f16_alu_check.py ir +``` + +- Before unary coverage was added, `model` checked 82 results, including controls for a sub/subrev swap and a zeroed upper half. +- Before unary coverage was added, `ir` reported 82 results and 20 refusals. The module used `legacyF16ToF32`, `fadd`, `fsub` and `fmul`, and the integer round contained the constant `939524096`. + +`native_f16_alu_hardware` was not run. It is registered with skip code 77, the same code `native_store_replay` returns when the device cannot run a wave32 shader. WARP is expected to take that skip. + +## Windows + +Pending. On the Windows test machine: + +``` +cmake --preset dev +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -R "^native_f16_alu_(ir|hardware)$" -V -j 1 +``` diff --git a/docs/experiments/gdk-exports.md b/docs/experiments/gdk-exports.md new file mode 100644 index 0000000000..8ca41fb0a6 --- /dev/null +++ b/docs/experiments/gdk-exports.md @@ -0,0 +1,51 @@ +# GDK exports and shim coverage + +tools/gdk_exports.py reads captured dumpbin /exports text or a PE DLL and writes +an inventory with module, file, SHA-256, export name, ordinal and RVA. +tools/gdk_shim_coverage.py compares that inventory with the Xbox2Windows .def +files and writes a JSON matrix plus a Markdown table. + +The SHA-256 identifies the captured .txt when parse-dumpbin is used, and the +DLL when scan-pe is used. A module with no inventory entry, a capture with zero +exports, or a partially parsed capture is reported as unmeasured; +--fail-on-missing fails on those rows as well as on missing names. + +The GDK libraries and the full inventory stay outside the repository. The +inventory used for the 261000 edition has 89 modules and 8,035 export names. +When a module has both a .lib and a .dll, the coverage tool merges their exports +and deduplicates the names, so d3d12_xs reports the union of the two files. + + python -B tests/gdk_exports_check.py + python -B tools/gdk_exports.py parse-dumpbin D:\gdk-oracle\dumpbin\xg_xs.txt --json out\xg_xs.json --kind dll + python -B tools/gdk_shim_coverage.py --exports D:\gdk-oracle\knowledge\exports-all.json --repo . --json out\coverage.json --markdown out\coverage.md + +Measured on 28 November 2026 with the 261000 LIB/DLL set: + +| Module | GDK functions | Shim functions | Covered | Missing | Status | +|---|---:|---:|---:|---:|---| +| xmem | 36 | 27 | 13 | 23 | ok | +| d3d12_xs | 28 | 5 | 4 | 24 | ok | +| acphal | 10 | 10 | 9 | 1 | ok | +| xapu | 6 | 6 | 5 | 1 | ok | +| chad | 7 | 5 | 5 | 2 | ok | +| xg_xs | 27 | 2 | 2 | 25 | ok | +| xcrdapi | 1 | 3 | 1 | 0 | ok | +| gameinput | 1 | 1 | 1 | 0 | ok | + +`xgameruntime` is intentionally outside `DEFAULT_DEFS`: its `.def` is +fixture-only and its exported thunk names are generated from +`XGAMERUNTIME_THUNK_TABLE`, so a name comparison would report every GDK runtime +export as missing. An inventory entry that is absent or unreadable is reported +as unmeasured rather than covered. + +The xg_xs gap remains the largest: layout computation, DCC, tile shapes, +hardware-version setup and descriptor validation are not exported by the shim. +xmem lacks the statistics, tags, Win32 heap and configuration families. d3d12_xs +lacks the desktop D3D12 entry points and several DXGIX helpers; the IID list is +counted as data, not functions. + +The counts are names, not signatures and not tests. A name can exist with a +different calling convention, and a covered name can still be untested at +runtime. The ordinals are recorded where dumpbin prints them; a title that +imports by ordinal still needs the matching import library and a runtime check. +Xbox One gen8 libraries have their own names and are outside this table. diff --git a/docs/experiments/gdk-knowledge-report.md b/docs/experiments/gdk-knowledge-report.md new file mode 100644 index 0000000000..bac9dbfca5 --- /dev/null +++ b/docs/experiments/gdk-knowledge-report.md @@ -0,0 +1,97 @@ +# GDK knowledge coverage report + +tools/gdk_knowledge_report.py merges the JSON knowledge base under +D:\gdk-oracle\knowledge and writes a deterministic coverage JSON and a +Markdown summary. It uses only the Python standard library and never reads a +GDK header, library or binary. + +## Inputs + +All categories are optional. A missing directory or file is reported as a +missing category; it is not treated as an empty fact. + +| Path | Accepted shape | +| --- | --- | +| layouts/*.json | classes array with name, size and members, or a class array | +| abi/*.json | facts array with kind, name and value, or a fact array | +| exports/*.json | exports array with name, ordinal and rva, module groups, or a module map | +| exports-all.json | the same export rows, including the file and kind group form | +| behavior/*.json | observations array, or an observation array | +| platform/*.json | define, include and library lists, plus a flag list or object | +| shaders/corpus.json or shaders/corpus/corpus.json | cases array, or a case array | + +Every fact is normalised to module, kind, name, value, source, confidence and +targets. Layout classes become layout facts whose value contains size and +members; ABI sizeof and struct facts keep their kind. Exports carry their +ordinal and RVA. Runtime observations become behavior facts, and the +observation kind is retained inside the value when it adds information. +Modules are merged case-insensitively. + +A top-level source of msvc-layout, compiled-probe, dumpbin, runtime-oracle or +header-msvc-layout is treated as a method: it becomes the confidence and the +source stays the JSON path. Other source values are kept as given. + +## Conflicts + +The report emits stable value, size, ordinal, enum and type-size entries. Each +entry names the module, the fact, every distinct value with its source, and a +short message. + +- size compares all size-bearing facts for one module and type, including a + layout member list and an ABI sizeof fact. +- type-size compares a named type across modules and reports incompatible + sizes. Equal sizes in two modules are not a conflict. +- ordinal compares only ordinals that both sources report. A missing ordinal + in an import library and a present ordinal in a DLL do not conflict. +- enum compares enum facts with the same module and name. +- value covers every other fact with the same module, kind and name. +- RVAs are retained in the facts but are not compared: Debug, Release, import + library and DLL records legitimately differ. + +MSVC anonymous tags include the text unnamed-tag in their display name. Several +distinct anonymous unions or structs can share that text, so they are kept as +facts and counted as types but excluded from conflict comparisons. Their +display name is not a stable identity. + +## Coverage and shims + +The summary counts modules, unique classes/types, unique exports and raw export +rows, runtime facts, shader facts, platforms and all normalised facts. A +per-module table gives the same breakdown. + +--defs accepts the repository src directory, one .def file, or a JSON mapping. +The parser reads LIBRARY, export names, aliases and ordinals, and ignores +internal x2w_* and X2W* helpers. A shim export is associated when its name or +alias target matches any fact name. The JSON and Markdown list the remaining +exports. + +## Commands + + python -B tests/gdk_knowledge_report_check.py + + $root = 'D:\gdk-oracle\knowledge' + python -B tools/gdk_knowledge_report.py report --root $root --json "$root\coverage.json" --markdown "$root\report.md" --defs src + +Add --check to exit 1 on conflicts. Add --require layouts,abi,exports to also +exit 1 when one of those categories is missing. Bad JSON, a bad schema, an +unknown required category or an unusable path exits 2. Without --check, +missing categories and conflicts are only reported. + +## Measured run + +On 2026-11-28, the local knowledge root produced 45 modules, 11,145 unique +types, 4,714 unique exports from 8,035 export rows, 12 runtime facts, 6 shader +cases and 3 platform profiles. The 9,677 ABI sizeof facts matched their layout +sizes, so the conflict list was empty. All six categories were present. All 70 +GDK-facing shim exports matched an export fact. + +## Limits + +A header fact does not prove the runtime. A layout or ABI row only reports what +the header or compile probe describes. A runtime observation is separate +evidence. An export name proves neither a signature nor a working +implementation, and a shim name match does not prove matching behaviour. The +report intentionally does not compare RVAs, infer missing categories, or turn +an absent oracle into a pass. The generated coverage JSON can be large because +it retains every normalised fact; keep it outside the repository with the rest +of the knowledge base. diff --git a/docs/experiments/gdk-layouts.md b/docs/experiments/gdk-layouts.md new file mode 100644 index 0000000000..2aebd968d2 --- /dev/null +++ b/docs/experiments/gdk-layouts.md @@ -0,0 +1,40 @@ +# GDK layouts and ABI probes + +tools/gdk_layouts.py parses the output of MSVC /d1reportAllClassLayout and keeps +only class names, sizes, member names, offsets and flags. tools/gdk_abi_probe.py +turns that JSON into a C++ probe: static_asserts for a compile check, or a +program that prints sizeof and offsetof values for a GRDK/GXDK comparison. + +The logs are produced outside the repository. No GDK header, LIB or DLL enters +the tree. The parser is tested on a synthetic log with a base class, vftable, +bitfield, array and alignment member, so the Python check runs on Linux. + + python -B tests/gdk_layouts_check.py + python -B tools/gdk_layouts.py parse D:\gdk-oracle\fixtures\layout-xg-one.log --json out\xg.json --module xg_xs_gen8 --platform Gaming.Xbox.XboxOne.x64 --msvc 19.44.35207 + python -B tools/gdk_abi_probe.py generate --layouts out\xg.json --out out\xg-probe.cpp --include windows.h --include xg.h --prefix XG_ --print + +Measured on 28 November 2026 with MSVC 19.44.35207 and the 261000 headers: + +| Header | Platform | Classes in the log | Probe | +|---|---|---:|---| +| XboxOne/xg.h | Gaming.Xbox.XboxOne.x64 | 2,098 | 16 XG_ types; sizeof probe compiled | +| XboxOne/d3d12_x.h | Gaming.Xbox.XboxOne.x64 | 3,029 | 74 D3D12XBOX_ types; 25 anonymous skipped; compiled | +| GameInput.h | Gaming.Desktop.x64 | 3,344 | 41 GameInput types; 1 anonymous skipped; compiled | +| XGameRuntime.h | Gaming.Desktop.x64 | 3,363 | 30 selected public types; 3 anonymous skipped; compiled with windows.h first | + +The Xbox One headers use these macros: _GAMING_XBOX, _GAMING_XBOX_XBOXONE and +WINAPI_FAMILY=WINAPI_FAMILY_GAMES. The GRDK headers use _GAMING_DESKTOP and +WINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP. XGameRuntime.h needs windows.h before +it, because XTaskQueue.h uses STDAPI. + +The parser treats a single-token member line, such as Width, as an unknown type +with a known name. MSVC prints that form for some typedefs. Anonymous nested +classes appear as NAME::; the probe generator skips them because +C++ cannot name them. + +Limits: a layout is a compile-time fact for one compiler and one macro set. It +does not prove runtime behavior, and a mismatch between a header layout and a +live library still needs an ABI probe or a runtime oracle. Private members and +non-standard-layout classes need review before offsetof is enabled; the generator +emits offsetof only for classes without bases or a vftable and for named, +non-bitfield fields. diff --git a/docs/experiments/gdk-platform-profiles.md b/docs/experiments/gdk-platform-profiles.md new file mode 100644 index 0000000000..1f25a1fb20 --- /dev/null +++ b/docs/experiments/gdk-platform-profiles.md @@ -0,0 +1,45 @@ +# GDK MSBuild platform profiles + +tools/gdk_platform_profiles.py reads the GDK platform files under +VS2022/flatDeployment/MSBuild/Microsoft/VC/v170 and writes a JSON profile per +platform. It keeps the MSBuild conditions and resolves the simple variables +defined in the same files. Variables that refer to the installed edition +(DurangoXdkInstallPath, DurangoGRDKInstallPath, XdkEdition) stay visible instead +of being guessed. + +The GDK installation and the JSON profiles stay outside the repository. + + python -B tests/gdk_platform_profiles_check.py + python -B tools/gdk_platform_profiles.py list --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK + python -B tools/gdk_platform_profiles.py scan --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK --platform Gaming.Xbox.Scarlett.x64 --json out\scarlett.json + +The --sdk option selects the versioned subdirectory (261000, 999999, ...). A +platform directory without that subdirectory is rejected before any output is +written, so the reported SDK, the source paths and the extracted values always +refer to the same edition. + +Measured on 28 November 2026 from the 261000 payload: + +| Platform | Sources | Defines | Includes | Libs | Dependencies | +|---|---:|---:|---:|---:|---:| +| Gaming.Desktop.x64 (GRDK) | 10 | 2 | 1 | 1 | 6 | +| Gaming.Xbox.Scarlett.x64 | 10 | 7 | 3 | 3 | 1 | +| Gaming.Xbox.XboxOne.x64 | 10 | 7 | 3 | 3 | 1 | + +The console profiles define _GAMING_XBOX, _GAMING_XBOX_SCARLETT or +_GAMING_XBOX_XBOXONE, WIN32_LEAN_AND_MEAN and +WINAPI_FAMILY=WINAPI_FAMILY_GAMES, plus the ATL/WRL strict-COM macros. The +desktop profile defines _GAMING_DESKTOP and +WINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP. Gaming.Desktop.arm64 is not present in +this payload. + +The include and library roots are Console_EndpointIncludeRoot and +Console_EndpointLibRoot. The console dependency list in Console_Libs is +pixevt.lib, d3d12_xs.lib, gameinput.lib, xgameplatform.lib, xgameruntime.lib, +xmem.lib and xg_xs.lib. The Scarlett profile also sets +EnableEnhancedInstructionSet=AdvancedVectorExtensions, FloatingPointModel=Fast +and /favor:AMD64 for v142/v143. + +The profile is a build recipe, not a runtime fact. A fixture generated from it +still needs the matching compiler, Windows SDK and GDK edition; the unresolved +installation variables are kept exactly because their values differ per host. diff --git a/docs/experiments/gdk-runtime-oracle.md b/docs/experiments/gdk-runtime-oracle.md new file mode 100644 index 0000000000..4312dcb9f7 --- /dev/null +++ b/docs/experiments/gdk-runtime-oracle.md @@ -0,0 +1,37 @@ +# GDK runtime oracle: GRDK and shim + +tools/gdk_runtime_oracle.py compiles the same original fixture twice: once +against the GRDK import library and once against the Xbox2Windows shim. It runs +both executables, masks handles, console ids and per-user temp paths, and writes +a normalized diff and a JSON report. + + python tools/gdk_runtime_oracle.py run --gdk-root "D:\gdk-ref\261000\grdk\Microsoft GDK\261000\GRDK" --shim-dir "out\build\dev\fixture-shims" --fixture "tests\gdk\runtime_families_probe.cpp" --out "out\gdk-runtime" --vcvars "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" + +On a host without cl.exe the command returns 77. The normalization and diff +subcommands need no SDK: + + python tools/gdk_runtime_oracle.py normalize out\gdk-runtime\candidate.txt + python tools/gdk_runtime_oracle.py diff out\gdk-runtime\reference.txt out\gdk-runtime\candidate.txt + +Measured on 28 November 2026, Windows 11 build 26200, the inbox +xgameruntime.dll 10.0.26100.9656 and the local shim: + +| Observation | GRDK reference | Xbox2Windows shim | +|---|---|---| +| XGameRuntimeInitialize | S_OK | not exported | +| XSystemGetDeviceType | 1 (Pc) | 1 (Pc) | +| XSystemGetConsoleId | S_OK, 39 bytes, all-zero id | S_OK, 39 bytes, 58325731...01 | +| XGameGetXboxTitleId | 0x80070490 (ERROR_NOT_FOUND) | S_OK, 0x58325731 | +| XPersistentLocalStorageGetPathSize | 0x80004005 | S_OK, 78 | +| XPersistentLocalStorageGetSpaceInfo | 0x80004005 | S_OK, 64 MiB total, 16 MiB used | +| XPackageMount of a missing identifier | 0x80004001 (E_NOTIMPL) | S_OK, synthetic handle and temp path | +| XTaskQueueCreate(Manual, Manual) | S_OK | S_OK | +| XTaskQueueDispatch(Completion, 0) | false | false | +| XSystemGetXboxLiveSandboxId | S_OK, RETAIL | not exported | + +The desktop runtime has no package identity on this host, so the title id and +persistent-local-storage calls fail. The shim synthesizes those values. The +oracle makes the difference explicit; it does not claim the shim matches the +console. Console-only APIs have static oracles only (headers, LIB exports and +vtables), and a successful mount of a missing identifier is an error-path +observation, not a package-format result. diff --git a/docs/experiments/gdk-shader-corpus.md b/docs/experiments/gdk-shader-corpus.md new file mode 100644 index 0000000000..b1bfb9da33 --- /dev/null +++ b/docs/experiments/gdk-shader-corpus.md @@ -0,0 +1,38 @@ +# GDK shader corpus + +tools/gdk_shader_corpus.py compiles original HLSL with the GXDK Scarlett dxc, +retargets the Xbox container with tools/dxil_retarget.py, and records the +source and container SHA-256 values. The HLSL sources are versioned; the .cso +files and the corpus manifest stay outside the repository. + + python -B tests/gdk_shader_corpus_check.py + python -B tools/gdk_shader_corpus.py build --gdk-root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000 --corpus tests\gdk\shaders --out D:\gdk-oracle\knowledge\shaders\corpus + python -B tools/gdk_shader_corpus.py verify --manifest D:\gdk-oracle\knowledge\shaders\corpus\corpus.json + +Measured on 28 November 2026 with dxcompiler_xs 1.8, build +2610.2608.12522.14643: + +| Case | Profile | Xbox bytes | Desktop bytes | Triple | +|---|---|---:|---:|---| +| wave64_ballot_ps | ps_6_0 | 4,316 | 4,152 | dxil-ms-xb2 -> dxil-ms-dx | +| root_constants_vs | vs_6_0 | 3,972 | 3,804 | dxil-ms-xb2 -> dxil-ms-dx | +| image_sample_c_lz_ps | ps_6_0 | 3,912 | 3,756 | dxil-ms-xb2 -> dxil-ms-dx | +| packed_types_cs | cs_6_0 | 3,224 | 3,068 | dxil-ms-xb2 -> dxil-ms-dx | +| derivatives_ps | ps_6_0 | 3,204 | 3,048 | dxil-ms-xb2 -> dxil-ms-dx | +| mesh_ngg_ms | ms_6_5 | 3,104 | 2,944 | dxil-ms-xb2 -> dxil-ms-dx | + +All six cases compiled, retargeted and verified. The retarget removed the +xbox.compiler.options named metadata in every case. The sources cover wave +ballot and lane access, a root signature with one constant buffer, a +comparison sample at level zero, packed 16-bit fields in compute, implicit +derivatives and fwidth, and a fixed three-vertex mesh shader. + +The check runs on Linux without dxc and covers case loading, hashing, manifest +verification, triple checks and the missing-dxc skip. build returns 77 when +dxc is absent. + +Limits: a retargeted container is not a GPU execution result. The corpus does +not prove that a desktop driver accepts the mesh or pixel pipeline, and it does +not cover game shaders. It records the compiler version, the source SHA-256, +the container sizes and the metadata the retarget removed. The mesh case is a +fixed topology and does not exercise NGG culling or amplification. diff --git a/docs/experiments/hardware-gtx1080ti.md b/docs/experiments/hardware-gtx1080ti.md new file mode 100644 index 0000000000..7db9c05400 --- /dev/null +++ b/docs/experiments/hardware-gtx1080ti.md @@ -0,0 +1,50 @@ +# Windows hardware CTest on a GeForce GTX 1080 Ti + +The source revision was `96a7b4fb265840c3bbe594be922f3e66c6c2f182`. +The host ran Windows 10 22H2 x64 (build 19045.6456) with an NVIDIA GeForce +GTX 1080 Ti and driver 32.0.15.8278 (582.78). The Debug build used MSVC +19.31.31105.0, Python 3.12.14 and DXC 1.8.2502.11 from Windows SDK 10.0.26100.0. + +From a dedicated worktree at that revision, set up the Python environment and +run the suite serially from PowerShell. + +```powershell +python -m venv out/pe-env +.\out\pe-env\Scripts\python.exe -m pip install -r requirements-dev.txt +. .\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev -j 8 +$env:XBOX2WINDOWS_ADAPTER = 'NVIDIA GeForce GTX 1080 Ti' +ctest --preset dev --no-tests=error -j 1 -R '_hardware' --output-junit (Join-Path $PWD 'out/hardware-junit.xml') +``` + +The filter selects every test whose name contains `_hardware`, including the +device-independent `tooling_hardware_reports_cli_check`. Supported fixtures +are expected to pass. A fixture that reports an unsupported capability is +counted separately as a skip. + +## Adapter capabilities + +The capability probes reported Shader Model 6.5, DXR Tier 1.0, a wave lane +range of 32–32 and mesh shader tier 0. The D3D12 debug layer was available. +The logs show it enabled for the offscreen fixtures and off for fixtures +configured to exercise the no-debug path. + +## Results + +CTest completed all 685 selected entries in 4194.11 seconds and returned exit +code 8. It recorded 577 passes, 19 failures and 89 skips. The failures +included seven segmentation faults and one timeout. + +The first failure was `startup_view_dimension_hardware`. CTest reported +`SegFault` after 0.35 seconds with the debug layer off. The last fixture +diagnostic was that the runtime skipped a view whose dimension did not suit the +resource. The two sampler variants also reported the same readback +difference at table 2, probe 3. Both expected 34 and read back 34.25. +`startup_image_load_d16_hardware` hit its 120-second CTest timeout. + +Skip diagnostics include mesh shader, Shader Model 6.6, wave-width and DXR +Tier 1.1 requirements. Fourteen SPIR-V bridge tests skipped because +`spirv-as`, `spirv-val` and `spirv-cross` were absent at configure time. +The two-exit mesh draw also reported a missing LLVM 15 AMDGPU prerequisite. +The run covers the repository's source-built fixtures on this configuration. diff --git a/docs/experiments/mesh57-dxil-plan.md b/docs/experiments/mesh57-dxil-plan.md new file mode 100644 index 0000000000..3d09fdcd73 --- /dev/null +++ b/docs/experiments/mesh57-dxil-plan.md @@ -0,0 +1,167 @@ +# Slot 57 mesh: plan for a complete DXIL translation + +Slot 57 is the fixed mesh pipeline path: the title creates a mesh pipeline whose programs are +console gfx1013, then issues `DispatchMesh` (directly or through an indirect signature). The +tracking issue #2413 recorded 298 distinct requests and **0 complete translations**. The partial +slices merged so far remove pre-checks; they do not produce a complete program, and the next +refusal is always waiting. + +This note separates the work that must happen before a first complete translation from the runtime +work that consumes it. It is a plan, not a claim that a scene renders. + +## Dependency map + +``` +device slot 57 request + -> gfx2hlsl inspect_mesh57_request (pre-checks, skeleton, pixel stage) + -> translate_mesh57 (mesh body, exports, container) + -> .ms.cso / .ps57.cso + -> runtime CreateMeshPipelineState + root signature + -> DispatchMesh (direct or indirect signature) + -> GPU mesh pipeline + pixel stage +``` + +The translator and the runtime have separate gates. A program can translate and still not run if +the runtime refuses `DispatchMesh` (`#1759`) or the pipeline root; a runtime path can be ready and +draw nothing without a translation. Keep them as separate PRs. + +## Measured refusal shapes + +From the local capture census in the #2413 notes and the 26 November runs: + +| Shape | Requests | Where it stops | +|---|---:|---| +| `s_cbranch_execz` pre-exchange block with scalar loads | 407 | `s_cbranch_execz skips code with effects outside active lanes` | +| Same, after the wave-block and dead-scalar slices | 91 | `v_readfirstlane_b32 outside the group-index read is not covered` | +| Branch inside the skipped block, `src_scc`, or `v_cmpx_lt_u32 v, v` | 316 | one of those named refusals | +| Pixel stage mixes the null export with another export | 97 | `slot 57 pixel stage mixes the null export with another export` | +| Group-index/count exchange shape | 15 | exchange refusal | +| Loops | 11 | loop refusal | +| `v_fma_mix_f32` reading the upper half of `v_interp_p2_f16` | 39 | pixel-stage refusal | +| `s_load` with a register offset through the resource heap | 47 | resource-heap refusal | + +The numbers are counts from one capture, not a promise that fixing a shape completes a program. The +91-request slice is the clearest evidence: two accepted blocks still produced zero complete +translations because the next refusal was waiting. + +## The smallest end-to-end target + +Do not start from the 298 real requests. Start from a source-built slot 57 program with the smallest +shape the runtime can create and dispatch: + +- one mesh workgroup, one output lane per thread (wave64 or wave32 depending on the fixture); +- three vertices and one triangle, written through the mesh export path; +- a group-index read through `v_readfirstlane_b32` of a formatted buffer load; +- one `SetMeshOutputCounts` and no LDS exchange beyond the group index; +- a constant-colour pixel stage, then a textured pixel stage. + +This program proves the chain: request -> `MeshPixelStage` -> DXIL mesh container -> desktop +`CreateMeshPipelineState` -> `DispatchMesh` -> readback. Only then take the first real request whose +shape is closest to this program. + +## Pass plan + +### 1. Mesh skeleton and wave model + +The existing `mesh_skeleton` already handles the group-index/count exchange, the wave64 lane masks +and the fixed user-SGPR layout. Keep it. The mesh stage must model one thread per output lane and +must not reuse the pixel helper-lane rules blindly. + +Requirements: user SGPRs start at s16; the root layout is s16 tables, a root descriptor pair, root +constants, then heap bases; a program with one fewer table shifts by one. `s_bitcmp0_b32 s20, 28` +tests a packed root-constant field, not a hardware system value. Resource-heap records are indexed +as `(rootconst & 0x3ff) << 5` and loaded with `s_load_dwordx4` from the 32-bit heap base. + +### 2. `v_readfirstlane_b32` of the group index + +The 91 requests that pass the wave block stop on a first-lane read of a formatted buffer load in the +pre-exchange code. The pass must trace that read to the per-lane descriptor and the lane that +produced it. This is the same fact the compute waterfall path needs; do not add a mesh-only rule. + +Acceptance: the source-built group-index program translates and reads the expected index; a control +whose first-lane source is not proven is refused by name. + +### 3. Branches and SCC inside skipped blocks + +The 316 remaining pre-check requests have a branch inside the block, `src_scc`, or the +`v_cmpx_lt_u32 v, v` compare form. Do not add one pattern per shape. Use the EXEC/SSA structurization +from `docs/experiments/exe-structurization.md`: represent the block as one lane, branch on the lane's +own mask bit, and prove the scalar values that survive the join. A mesh-specific exception table is +the wrong direction. + +### 4. Group memory and output counts + +The mesh stage writes group memory (LDS) and then exports vertices and primitives. The pass must: + +- keep the group-index and count exchanges wave-uniform; +- keep `SetMeshOutputCounts` once per workgroup, not once per lane; +- respect the declared maximum vertices/primitives and the output-size limit; +- map `v_mbcnt`, `ds_*` and the export registers to the DXIL mesh output arrays; +- keep helper lanes out of the mesh output count path. + +Acceptance: a source-built triangle with three vertices and one primitive; a control with a wrong +count, a wrong index, and a missing export each produces a named failure or a pixel mismatch. + +### 5. Pixel stage linkage + +The slot 57 pixel stage is a separate console program. Link its inputs to the mesh outputs by +semantic, not by register order. The 97 requests that stop on `slot 57 pixel stage mixes the null +export with another export` are the early-exit form: the null export after the main `s_endpgm` is a +kill, not a second colour target. Accept only that block; leave other mixed-export forms refused. + +### 6. Runtime creation and dispatch + +The translator can publish `.ms.cso` and `.ps57.cso` before the runtime consumes them. The +runtime needs: + +- `CreateMeshPipelineState` with the translated root signature and the MS/PS bytecode; +- the mesh container fields (max vertices, max primitives, topology, output size); +- `DispatchMesh` direct and indirect, with the console command signature; +- the pipeline root and the group counts on the same command list. + +Keep the runtime slice behind a source-built `startup_mesh57_*` fixture; a translation without a +runtime fixture is not an end-to-end result. + +## Phased schedule + +| Phase | Scope | Observable acceptance | Owner | +|---|---|---|---| +| A | source-built minimal mesh + group-index read | translate, create PSO, dispatch, read back 3 vertices/1 triangle on WARP and hardware | translator + runtime | +| B | `v_readfirstlane` group index on a real request shape | the 91-request class moves past the refusal; one request translates completely if the rest is present | translator | +| C | EXEC/SSA branches inside skipped blocks | the 316-request class moves; no mesh-only exception table | frontend | +| D | group memory, counts, export limits | source-built triangle with LDS and count controls | translator | +| E | pixel-stage linkage and null-export kill | 97-request class pixel programs translate and draw the expected pixels | translator + GPU | +| F | one real slot 57 request end-to-end | a real request creates a desktop mesh PSO and `DispatchMesh` draws the expected geometry in a capture | runtime + GPU | + +Phase A is the only one that can claim a complete translation. B-E are enabling slices; each should +say how many requests moved and whether any complete translation resulted. + +## Risks + +- **Wave64 on wave32:** the title's mesh programs use 64-lane waves and 64-bit EXEC operations. A + wave32 host needs exact lane-mask handling; a silent 32-lane assumption changes the group index + and the export count. +- **Workgroup size and LDS:** the console mesh group is not the desktop mesh group. The pass must + preserve the group-index/count exchange and the LDS size the program declares. +- **Output limits:** DXIL mesh outputs have a size limit; a program that fits the console may need a + refusal or a split. Do not let the validator fail at runtime without a named translation refusal. +- **Slot 57 vs slot 86:** slot 57 is the fixed mesh pipeline; slot 86 is the stream pipeline path. + Do not merge their request formats or their root rules. +- **Helper lanes:** a pixel stage that uses derivatives needs helper lanes; a mesh-only per-lane + model that drops them will produce wrong edges. + +## First patch recommendation + +Add the `v_readfirstlane_b32` group-index read to the mesh skeleton, with the source-built minimal +mesh from Phase A. The 91 requests already pass the wave block and stop there; the patch tests the +same fact on a program that can be drawn end-to-end. If the minimal program cannot yet create a +desktop mesh PSO, land the translator test and the runtime fixture separately and do not claim a +complete translation. + +## References + +- Issue #2413 and its comments, especially the T6/T7 wave and dead-scalar slices. +- `docs/experiments/startup-mesh57-wave-block.md`, `startup-mesh57-dead-block-scalar.md`. +- `tools/startup/gfx2hlsl.py`: `inspect_mesh57_request`, `translate_mesh57`, `MeshPixelStage`. +- The public design description of DexNom/VIctory's mesh emitter and diff tests (GPL-3.0; read-only, + no code copied). diff --git a/docs/experiments/missing-shader-fallback.md b/docs/experiments/missing-shader-fallback.md new file mode 100644 index 0000000000..4b8dfe02dc --- /dev/null +++ b/docs/experiments/missing-shader-fallback.md @@ -0,0 +1,20 @@ +# Missing graphics shader fallback + +With `X2W_DRAW_MISSING_SHADER=1`, a direct triangle-list draw can use a +diagnostic PSO while its translation manifest is absent. It uses the bound +attachment formats and clips all geometry without writing colour, depth or +UAV data. Downstream passes still depend on the missing shader's actual +outputs. The runtime publishes and polls the normal translation request. + +On Windows, build the fixture and run the two WARP cases from the repo root. + +```powershell +cmake --build --preset dev --target startup_indirect_draw_indexed +ctest --preset dev --no-tests=error -R '^startup_missing_shader_fallback(_off)?_warp$' -V +``` + +The fixture checks pipeline statistics and reads back an RTV and DSV. The +enabled case expects three IA vertices with both attachments still at their +clear values. The disabled control expects zero IA vertices and the same +clear values. Both then publish the source-built translation and expect the +same guest pipeline to produce a red render target after the manifest retry. diff --git a/docs/experiments/native-bytewin-store.md b/docs/experiments/native-bytewin-store.md new file mode 100644 index 0000000000..fc0fe5091a --- /dev/null +++ b/docs/experiments/native-bytewin-store.md @@ -0,0 +1,43 @@ +# Byte-window stores in the direct C++ compute path + +Issue #2965 covers raw stores through a rewritten table descriptor. The +guest loads the descriptor with `s_load_dwordx4`, extracts the stride +from word 1 with `s_bfe_u32` and clamps it to at least 1 with +`s_max_u32`. It clears the stride in word 1 with `0xc000ffff`, scales +word 2 by the clamped stride with `s_mul_i32`, and sets the raw OOB +selector in word 3 with `s_or_b32` and `0x30000000`. + +The compiler proves that all three edits originate from the descriptor +selected by word 0. The OR works on a loaded word 3 or one whose selector +has already been cleared. The original table slot supplies the raw UAV. +The host UAV's extent determines which writes are in range. +Direct compute raw stores accept and ignore the GLC, DLC and SLC cache-policy bits. +Non-indexed dword atomics reuse the raw store UAV window, and the wave32 fixture checks add with and without GLC, unsigned min, compare-and-swap, and indexed and 64-bit refusals. + +## Verification + +`native_bytewin_store_controls` expects refusal for a plain SGPR +multiplier, a byte count from another table slot, and the OOB mask +`0x20000000`. It also refuses an indexed atomic and a 64-bit atomic through the byte +window. Dropping the stride proof or accepting a foreign +descriptor's word should make the corresponding control fail. + +`native_bytewin_store_hardware` dispatches two 32-thread groups through +`native_store_replay`. Each store width has a 1024-byte plane with a +16-byte slot per lane. Widths 1 to 4 write the first 1 to 4 words of each +slot with `16 * lane + component + 1`. Unwritten words and both +eight-word guards retain `0x69696969`. All writes fit in the 8192-byte +raw UAV. Hardware without shader model 6.6 and wave32 support returns +skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_bytewin_store_(controls|hardware)$' +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) all four store widths +matched in both workgroups, with the unwritten words and guards intact, and the controls were refused. A later change +accepts non-indexed dword atomics through the byte window: add with and without GLC, unsigned min and compare-and-swap +read back against a CPU reference, while an indexed atomic and a 64-bit atomic through the window stay refused. +Dropping the clamped-stride proof lets the constant-multiplier control compile, and ignoring descriptor identity +lets the foreign word 2 control compile; each fails the controls. diff --git a/docs/experiments/native-compile-dxil-refusals.md b/docs/experiments/native-compile-dxil-refusals.md new file mode 100644 index 0000000000..090ad0bf15 --- /dev/null +++ b/docs/experiments/native-compile-dxil-refusals.md @@ -0,0 +1,57 @@ +# `.fail` diagnostics and read-only `--refusals` summary in `compile_dxil` + +[The test fixture](../../tests/native_compile_dxil_refusals_check.py) verifies two diagnostics in +`tools/startup/compile_dxil.cpp` and their ingestion by `tools/startup/triage_run.py` on `cpp-migration` +(part of #2935): + +1. **Per-request `.fail` lifecycle in `--requests` batch mode:** + - Refused graphics (`req_.a`) and slot-67 compute (`req_.c67`) requests atomically publish a + single-line `.fail` file alongside withdrawing any prior `.txt`, while publishing no stage + `.cso` bytecode. + - Re-running `--requests` after fixing a refused request removes the stale `.fail` once `.txt` + is published. + - `tools/startup/triage_run.py` classifies native `.fail` entries under allowlisted categories in + `SHADER_REASONS` without echoing private strings or raw instruction bytes. +2. **Read-only `--refusals REQUEST_DIRECTORY [--jobs N] [--json]`:** + - Summarizes first-refusal counts across graphics (`req_.a`) and slot-67 compute (`req_.c67`) + requests without invoking DXC or writing any cache or output files. + - Strips PC offsets and normalizes hex words, byte offsets, and register indices so repeated failures + across different instructions or requests aggregate into one row. + +3. **Compute programs without a runtime manifest (#3224):** + - A slot-67 compute program that translates but that `format_compute_runtime_manifest` + (`src/direct_compute_cache.cpp`) cannot describe gets one fixed reason, for example + `unsupported startup runtime manifest bindings: SRV kind root_buffer_srv`. The reasons name the + exit: a zero group dimension, root constants above parameter 15 or more than 8 in one parameter, + more than 32 user data words, a resource or sampler heap view, a view above root parameter 15, + non-contiguous SRV or UAV registers, an SRV or UAV kind with no manifest line (the kind, and for + images the dimension and `array`; a texture SRV of dimension 1D, 2D, 3D or 2D array has a line, a + cube or multisampled one does not), more than 32 SRVs or 8 UAVs, a comparison sampler, and stride + words from a view that is not one raw vector SRV. No register numbers, offsets or keys. + - `--requests` still publishes `.cs.cso` and no `.txt`, still counts the request as + compiled and still removes `.fail`. It prints the reason in that job's report as + `no_manifest input=req_.c67 `. It writes no `.fail`, because `.fail` is the retry + marker of both watchers: with `X2W_SKIP_FAILED=1` / `--skip-failed` the Python watcher keeps + selecting such a key in a live cache. + - `--watch`, which refuses the key, writes the same line to `.fail` instead of the former + reasonless one. `--refusals` counts the request under it instead of under no refusal. + `triage_run.py` reports the `.fail` line as `runtime manifest: `. + +## Verification + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil native_compute_manifest_reasons +ctest --preset release --no-tests=error -V -R "^(native_compile_dxil_refusals|native_compute_manifest_reasons(_requests)?)$" +.\out\pe-env\Scripts\python.exe -B tests/startup_triage_run_check.py +``` + +## Limits + +- `--refusals` reports the first refusal reached per request by `read_graphics_request` / + `prepare_direct_graphics(..., /*write_cache=*/false)` and `read_compute_request` / `translate_compute`; it + does not walk past the first refusal or invoke DXC. +- Graphics requests use `req_.a` and `req_.rtv` ([RTV variant note](native-rtv-variant-requests.md)); + when both markers share a key, the variant takes precedence. Slot-57 mesh requests remain outside the + native path. diff --git a/docs/experiments/native-compile-dxil-rekey.md b/docs/experiments/native-compile-dxil-rekey.md new file mode 100644 index 0000000000..0a886e986c --- /dev/null +++ b/docs/experiments/native-compile-dxil-rekey.md @@ -0,0 +1,44 @@ +# Native cache re-keying (`compile_dxil --rekey`) + +Added `--rekey` to `tools/startup/compile_dxil.cpp` as the native C++ equivalent of +`tools/startup/shader_cache_rekey.py` (`Refs #2935`). + +## Usage + +```powershell +compile_dxil --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] +``` + +This mode runs without `SDK_DIRECTORY` or DXC: + +- Scans `OLD_CACHE_DIR` (non-recursively) for `req_<16-hex>` markers (`.a`, `.c67`, + `.m57`, `.rtv`), counts `.m86` markers, and ignores result/diagnostic files + (`.txt`, `.fail`, `.cso`, `.psdep`). +- Validates and recomputes keys in parallel using the current output revision + strings (`x2w-startup-shader-29`, `x2w-startup-shader-29cs`, + `x2w-startup-mesh-57-3` via shared helpers in `src/shader_compute_request.cpp`), + while the readers retain `x2w-startup-shader-28` and `x2w-startup-shader-28cs` + input compatibility. +- Rewrites `.psin` and `.rtv` payloads under their updated keys while leaving all + shader bytecode/root/layout parts intact. +- Fails with exit code `1` before creating or writing `NEW_REQUEST_DIR` if any + request is incomplete, unreadable, or malformed; exits `2` on invalid CLI usage + or when `OLD_CACHE_DIR` and `NEW_REQUEST_DIR` refer to the same directory. +- Publishes files atomically (ready markers `.a`, `.c67`, `.m57` written last) + and preserves already-present files in `NEW_REQUEST_DIR`. + +## Verification + +Build `compile_dxil` and run the native rekey parity and control check: + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil +ctest --preset release --no-tests=error -V -R '^native_compile_dxil_rekey$' +``` + +Expected: `native_compile_dxil_rekey` exits `0` and verifies byte-for-byte parity +with `tools/startup/shader_cache_rekey.py`, `gfx2hlsl.pending_keys` compatibility, +idempotency, read-only preservation of `OLD_CACHE_DIR`, and all incomplete-request +and CLI negative controls. diff --git a/docs/experiments/native-compile-dxil-watch.md b/docs/experiments/native-compile-dxil-watch.md new file mode 100644 index 0000000000..1c5b5f8167 --- /dev/null +++ b/docs/experiments/native-compile-dxil-watch.md @@ -0,0 +1,29 @@ +# `--watch` mode in `compile_dxil` + +[The test fixture](../../tests/native_compile_dxil_watch_check.py) verifies continuous and one-shot +`--watch` operation in `tools/startup/compile_dxil.cpp` on `cpp-migration` (part of #2935): + +- `compile_dxil --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once]` + loads and fingerprints the DXC SDK once and translates pending startup graphics (`req_.a`) and slot-67 + compute (`req_.c67`) requests into `.{vs,ps,cs}.cso`, optional `.psdep`, and `.txt`, or + writes `.fail` on refusal. +- Pending and resume checks match `tools/startup/gfx2hlsl.py`: completed `.txt` entries with valid DXBC `.cso` + containers are skipped, truncated or missing stage `.cso` files are resumed, `.psin` additions/updates/removals + trigger rechecks, pre-existing `.fail` entries are retried once on the first pass, and unchanged `.fail` entries + are skipped on subsequent passes until the marker or `.psin` is rewritten. + +## Verification + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil +ctest --preset release --no-tests=error -V -R "^native_compile_dxil_watch$" +``` + +## Limits + +- Watches startup graphics (`req_.a`), RTV variant (`req_.rtv`), and slot-67 compute + (`req_.c67`) requests; slot-57 mesh requests remain outside the native path. +- `run.ps1 -Translate` still invokes `gfx2hlsl.py --watch` until the remaining graphics/runtime migration items + in #2935 land. diff --git a/docs/experiments/native-compute-implicit-derivatives.md b/docs/experiments/native-compute-implicit-derivatives.md new file mode 100644 index 0000000000..8e86ee0163 --- /dev/null +++ b/docs/experiments/native-compute-implicit-derivatives.md @@ -0,0 +1,41 @@ +# Implicit derivatives in direct compute + +Groups with a multiple of four threads can use implicit derivatives when +they pass the existing wave guards: a group of more than 32 threads must be +a multiple of 32, and a wave64 group a multiple of 64. The DXIL module uses +`numthreads(X*Y*Z,1,1)` and validator version 1.8 only when it emits +compute derivatives. Guest local X, Y and Z are reconstructed from the +linear guest index. + +A guest quad is four consecutive guest lanes. The emitter reconstructs +the linear guest index as host wave rank * 32 + host lane index. The +SM 6.6 derivatives spec section "1D quads" guarantees the matching position +within each quad. The full reconstruction also assumes that host lane +order follows thread order within a wave, including across quads. + +A 6-thread wave32 group has an incomplete quad and refuses with +"implicit derivatives require a pixel stage". A 36-thread wave32 group +has complete quads and fails the earlier wave guard with "partial final +wave in multi-wave group". Implicit Gather with a constant sampler requires +that sampler to be fixed to mip zero (LOD range word zero). + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_compute_implicit_lod_' -V +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, Release), the hardware fixture +matches its CPU reference for 4-, 12-, 32- and 96-thread wave32 groups, +64- and 128-thread wave64 groups, and the multidimensional (8,4,1) and +(8,4,2) groups. The multidimensional fixture varies the texture coordinate +only in the quad's vertical direction. Its derivative spans 0.75 texels +for consecutive quads and three texels for spatial 2D quads. This keeps +the expected sample below the first mip transition and leaves the wrong +quad layout observable with the fixture's trilinear sampler. +The compile controls check that implicit shaders emit flattened DXIL +group dimensions and explicit-LOD shaders keep the requested dimensions. +Its other readbacks cover bias selecting mip 2, point depth +comparison at mip 1, both LOD query outputs, and the four taps of mip-zero +Gather. Bias and Gather each use the same CPU reference for their implicit +and explicit-LOD shaders. Inbox WARP reports the capability skip +"requires SM 6.6, WaveOps, and a 32-lane wave". diff --git a/docs/experiments/native-compute-warp.md b/docs/experiments/native-compute-warp.md new file mode 100644 index 0000000000..5a083bc84e --- /dev/null +++ b/docs/experiments/native-compute-warp.md @@ -0,0 +1,120 @@ +# Native wave32 compute on app-local WARP 1.0.22 + +Refs [#3160](https://github.com/R0Y00/Xbox2Windows/issues/3160) (stage 1), +[#145](https://github.com/R0Y00/Xbox2Windows/issues/145), [#147](https://github.com/R0Y00/Xbox2Windows/pull/147). + +Every direct compute module declares wave size 32 (`src/dxil_module.h`). The in-box WARP has 4-lane waves, so the +native compute `_warp` tests skip with 77. This note measures them with the Microsoft WARP 1.0.22 package placed +beside the test executables. No translator or test code changes. + +## Result + +**The app-local `d3d10warp.dll` is what provides 32-lane waves. The Agility SDK runtime alone does not:** loaded +through `CreateDeviceFactory` (see below), Agility 1.620.2 with the in-box WARP reports 4..4 lanes. On this machine, +WARP 1.0.22 loaded by the in-box D3D12 runtime reports `WaveOps=1`, lanes 4 to 128 and SM 6.8. A configure with +`OFFSCREEN_WARP_DIR` already copies the DLL into the build root, next to every test executable, so the tests below +use it without any change to their CMake targets. + +| Test | Executable | In-box runtime, in-box WARP (`10.0.26100.9818`) | In-box runtime, WARP 1.0.22 beside the EXE | +|---|---|---|---| +| `native_comparison_pso_warp` | `native_recording_check` | skip 77, `range=4..4` | pass: cold and cached comparison-sampling compute PSOs (no dispatch) | +| `native_heap_handle_probe_warp` | `native_heap_handle_probe` | skip 77, `(4..4)` | pass: reference and native modules, selectors 0 and 1 match the CPU reference, guard intact | +| `native_global_srv_heap_replay_warp` | `native_global_srv_heap_replay` | skip 77, `(4..4)` | pass: record and offline replay, 64 words per selector, refusals | +| `startup_compute_dispatch_native_warp` | `startup_stream_consumer` | skip 77, refusal checks pass | **fail**: `Dispatch(3, 2, 2) translated`, then `word=0 got=c5c5c5c5 expected=ea74e376 (288 words differ)` | +| `native_startup_request_cache_warp` | `startup_stream_consumer`, `offscreen_check` | pass (4-lane fallback branch) | **fail**: `compute dispatch output mismatch` (translated branch) | +| `shader_wave32_warp` (gate) | `offscreen_check` | not run | pass: `forced32 width=32 waves=2 ... mismatches=0`, debug layer enabled, 0 errors | +| `bvh_wave64_warp` (#145) | `offscreen_check` | not run | **fail**: `record=0 field=25 expected=f0094d90 actual=f03aeb40` | + +Control: with `d3d10warp.dll` renamed away, the same `warp122` binaries of `native_heap_handle_probe_warp` and +`native_global_srv_heap_replay_warp` report `(4..4)` and skip with 77. The `native_comparison_pso_warp` row in the +in-box column comes from the options-unset build. The three executables have no export table, so the in-box `D3D12Core.dll` loads. A scratch probe started from the same +directory printed `C:\WINDOWS\SYSTEM32\D3D12Core.dll` and the `d3d10warp.dll` from the build root. + +Negative control: changing one expected word in `reference_output()` of `tests/native_global_srv_heap_replay.cpp` +(a temporary local edit, reverted) makes `native_global_srv_heap_replay_warp` fail with +`mismatch word 5: got 0xa0000005 expected 0xa0000004`. The pass is a real comparison, not a skip. + +With the options unset (an options-unset build of this commit), all five native compute tests give the same results +as before: four skip with 77 and `native_startup_request_cache_warp` passes through its 4-lane branch. + +## The two stand-in failures + +Both run the native module through the stand-in (`d3d12_xs_shim`). The dispatch is recorded and the fence signals, +but the output keeps its `0xc5c5c5c5` fill. This is not the #145 shape, where values arrive from the wrong lanes: +here no word is written. `startup_compute_dispatch_warp` uses the same stand-in, executable and WARP, with an HLSL +module compiled by DXC, and it passes. A rerun with `X2W_TEST_DEBUG_LAYER=1` set printed no `x2w-d3d12-debug` line. +I did not confirm that the debug layer was active on that path. + +On the RTX 4090 (driver 32.0.16.1088), `startup_compute_dispatch_native_hardware` (all 320 words match, from an +empty cache and from a published translation) and `native_startup_request_cache_hardware` pass in the same build. +The failure is therefore specific to WARP. It happens with a native module dispatched through the stand-in, and not +with the standalone native fixtures or with an HLSL module dispatched through the stand-in. + +**Still open:** the cause. A WARP 1.0.22 defect and a translator or stand-in construct that hardware tolerates are +both possible. + +## Agility SDK 1.620.2 on this machine + +- **The export-based load fails.** Exporting `D3D12SDKVersion = 620` and `D3D12SDKPath = ".\\D3D12\\"` (the + `offscreen_check` pattern) makes every D3D12 call return `0x887E0003` (`D3D12_ERROR_INVALID_REDIST`). The loader's + debug output reads `Unable to load D3D12Core.dll. Verify D3D12SDKPath is correct.` The same happens from a second + directory on another drive. With these exports added as a local edit, the three standalone tests above skip or fail. +- **The DLL itself is fine.** `LoadLibrary` of the same `D3D12Core.dll` succeeds. + `ID3D12SDKConfiguration1::CreateDeviceFactory(620, )` loads it, and WARP 1.0.22 again reports lanes + 4 to 128. +- **Unknown:** the cause of the export-path failure on this build. +- **The opt-in build does not compile on current `main`.** `src/startup_stubs/d3d12_compute_dispatch.inl` asserts + `sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40` and the same for the UAV description. With the Agility 1.620 headers + the UAV description is 48 bytes (the SRV description stays 40), so `d3d12_xs_shim` and `offscreen_check` fail to build when `OFFSCREEN_AGILITY_620_DIR` is set. + That is why the last four rows were measured in an options-unset build with the DLL copied in by hand. + +## #145 and the native lowerings + +`bvh_wave64_warp` still fails at field 25, the non-uniform `WaveReadLaneAt` shuffle that #145 describes. On this +machine the value is different. With the #145 encoding (`0xf0000001 ^ (lane * 0x319db)`): +- expected `f0094d90` is lane 3; +- this run's `f03aeb40` decodes to lane 19; +- the `f053ba18` in #145 decodes to lane 27, the inverse permutation. + +This run used the in-box runtime, not Agility. I have not investigated it further. + +None of the three passing native tests lowers `v_readlane`, DPP or `v_permlane*`. Those fixtures run on +`native_store_replay`, which creates its device on the default adapter and has only `_hardware` entries. So whether +#145 affects native compute on WARP is still unmeasured. + +## Reproduce + +Microsoft NuGet packages, not committed: [Agility SDK 1.620.2](https://www.nuget.org/packages/Microsoft.Direct3D.D3D12/1.620.2) +(35,006,223 bytes, kept as `sdk.nupkg` next to its x64 `D3D12Core.dll` and `d3d12SDKLayers.dll`) and +[WARP 1.0.22](https://www.nuget.org/packages/Microsoft.Direct3D.WARP/1.0.22) (15,564,228 bytes, extracted). + +```powershell +cmake --preset dev -B out/build/warp122 "-DOFFSCREEN_AGILITY_620_DIR=" "-DOFFSCREEN_WARP_DIR=/build/native/bin/x64" +cmake --build out/build/warp122 --target compile_dxil native_recording_check native_heap_handle_probe native_global_srv_heap_replay +ctest --test-dir out/build/warp122 --no-tests=error -j1 -V -R '^native_(comparison_pso|heap_handle_probe|global_srv_heap_replay)_warp$' +``` + +The stand-in rows and the gate rows need `offscreen_check` and `startup_stream_consumer`, which do not build with the +Agility option (see above). Build them with the options unset and copy the DLL in for the run: + +```powershell +cmake --build --preset dev --target offscreen_check compile_dxil startup_stream_consumer +Copy-Item /build/native/bin/x64/d3d10warp.dll out/build/dev/ +ctest --test-dir out/build/dev --no-tests=error -j1 -V -R '^(startup_compute_dispatch_native|native_startup_request_cache|shader_wave32|bvh_wave64)_warp$' +Remove-Item out/build/dev/d3d10warp.dll +``` + +## Environment + +Commit `88cddb09`. Windows 11 build 26300, in-box `D3D12Core.dll` 10.0.26100.9818 (SDK version 616). MSVC +14.44.35207, Windows SDK 10.0.26100 (DXC from that SDK), Debug build. NVIDIA GeForce RTX 4090 (driver 32.0.16.1088), +used only for the two stand-in `_hardware` runs. WARP `d3d10warp.dll` 1.0.22.0.20261027.1 and Agility `D3D12Core.dll` +1.620.2.0.20261106.5 were Microsoft-signed. `offscreen_check` reported `debug_layer=enabled`. The native fixtures +do not enable the debug layer. + +## Hypotheses + +- The in-box result depends on this Windows build. On Windows 10, #147 found that WARP 1.0.22 on the in-box runtime + misses every DXR ray. That is why `OFFSCREEN_WARP_DIR` requires `OFFSCREEN_AGILITY_620_DIR`. The in-box runtimes of + CI runner images have not been measured. +- The cause of the two WARP-only stand-in failures is unknown (see above). diff --git a/docs/experiments/native-cvt-norm-f16.md b/docs/experiments/native-cvt-norm-f16.md new file mode 100644 index 0000000000..7d26f5d084 --- /dev/null +++ b/docs/experiments/native-cvt-norm-f16.md @@ -0,0 +1,57 @@ +# Normalized integer conversion from binary16 (`v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`) in direct DXIL + +The native frontend lowers gfx1013 VOP1 (`0x63` / `0x64`) and VOP3 (`0x1e3` / +`0x1e4`) `v_cvt_norm_i16_f16` and `v_cvt_norm_u16_f16` in +`DirectCompute::float_alu()` for both Compute and Pixel shaders. + +## Exact integer lowering and semantics + +The lowering matches [pixel_aot.py](../../tools/pixel_aot.py)'s +`f16_cvt_norm_result` contract in exact 32-bit integer arithmetic instead of +widening to binary32: + +- Decodes the binary16 exponent (`mag >> 10`) and significand (normal `0x400 | + (mag & 0x3ff)` or subnormal `mag`), multiplies by `32767` (`i16`) or `65535` + (`u16`), and rounds once to nearest even with exact remainder/midpoint checks. + This avoids binary32 double-rounding mismatches (such as `0x3801` and + `0xb802`) and preserves binary16 subnormal inputs. +- `+0.0` and `-0.0` map to `0`. +- Inputs with magnitude `>= 1.0` (including `±Inf`) saturate to `+32767` / + `-32767` (`i16`) or `65535` / `0` (`u16`). +- Any negative value (`sign != 0`) maps to `0` on `v_cvt_norm_u16_f16`. +- Non-finite NaN operands (`mag > 0x7c00`) map to `0`. +- Supported VOP3 modifiers are `abs[0]`, `neg[0]`, `op_sel[0]` (VGPR high-half + source read), and `op_sel[3]` (high-half destination write), preserving the + unwritten destination half and respecting `EXEC` masking. +- Supported sources are VGPRs (`256..511`), numeric SGPRs (`0..105`), 32-bit + literals (`255`), inline binary16 float constants (`240..248`), and inline + integer words (`128..208`). + +## Refused encodings and mode gate + +The translator refuses `v_cvt_norm_i16_f16` and `v_cvt_norm_u16_f16` when any +of the following hold: + +- VOP3 `clamp != 0` or `omod != 0`. +- Unused VOP3 operand modifiers (`abs[2:1]`, `neg[2:1]`, `op_sel[2:1]`, + non-zero `src1` / `src2`). +- High-half `op_sel[0]` on a non-VGPR source (`src0 < 256`). +- DPP16, SDWA, permuted/subword encodings, or special scalar sources such as + `vcc_lo` (`106`). +- Non-default binary16 rounding/denormal mode + (`((mode_bits ^ 0xf0u) & 0x8000ccu) != 0`) or dynamic/unknown `MODE` writes. + +## Fixture coverage and reproduction + +[native_cvt_norm_f16_check.py](../../tests/native_cvt_norm_f16_check.py) checks +30 Compute cases (`<= 32` words/lane in `native_store_replay`), 11 refusal +controls, and lossless 16-bit Pixel readback across 15 draws (29 full-`EXEC` +cases padded to 30) on WARP and hardware: + +```powershell +cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -j 1 -R '^native_cvt_norm_f16_' -V +``` + +Compute replay requires shader model 6.6 with wave32; adapters without wave32 +report a skip (`77`) on `native_cvt_norm_f16_compute_hardware`. diff --git a/docs/experiments/native-cvt-off-f32-i4.md b/docs/experiments/native-cvt-off-f32-i4.md new file mode 100644 index 0000000000..6a0ddfce02 --- /dev/null +++ b/docs/experiments/native-cvt-off-f32-i4.md @@ -0,0 +1,27 @@ +# Signed 4-bit offset to binary32 (`v_cvt_off_f32_i4`) in direct compute + +The native compute frontend translates both the VOP1 (`0x0e`) and VOP3A +(`0x18e`) encodings of gfx1013 `v_cvt_off_f32_i4`. It sign-extends `src0[3:0]` +to a signed integer in `[-8, +7]` and multiplies by `0.0625` (`1/16`), +producing exact binary32 values in `[-0.5, +0.4375]`. VOP3A output modifiers +(`omod` and `clamp`) apply to the float result. + +Integer source modifiers (`abs`, `neg`), `op_sel`, and nonzero unused +`src1`/`src2` fields on the VOP3A encoding are refused. + +Section 12.6 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_cvt_off_f32_i4_' -V +``` + +The compile controls validate the generated DXIL and refuse five VOP3A +modifier/unused-source encodings (`abs`, `neg`, `op_sel`, nonzero `src1`, +nonzero `src2`). Three source-built dispatches exercise all 16 nibble values +across VOP1, VOP3A, `mul:2`, `clamp`, a sparse `EXEC` mask, and a no-clamp +negative control (2,048 result words and 16 guard words per dispatch). The +native replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-cvt-pknorm-f32.md b/docs/experiments/native-cvt-pknorm-f32.md new file mode 100644 index 0000000000..878f42673f --- /dev/null +++ b/docs/experiments/native-cvt-pknorm-f32.md @@ -0,0 +1,63 @@ +# Packed normalized integer conversion from binary32 (`v_cvt_pknorm_i16_f32` / `v_cvt_pknorm_u16_f32`) in direct DXIL + +The native frontend lowers gfx1013 VOP3 `v_cvt_pknorm_i16_f32` (`0x368`) and +`v_cvt_pknorm_u16_f32` (`0x369`) in `DirectCompute::float_alu()` for both Compute +and Pixel shaders, packing `cvt_norm(S0.f32)` into `D[15:0]` and +`cvt_norm(S1.f32)` into `D[31:16]`. + +## Exact 32-bit integer RNE lowering and model status + +Both lanes compute single-rounding `round_rne(clamp(x, -1, 1) * 32767)` (`i16`) +and `round_rne(clamp(x, 0, 1) * 65535)` (`u16`) in 32-bit unsigned integer +arithmetic without floating-point intermediaries or 64-bit integers. + +- **Model status:** Unlike `v_cvt_pk_u8_f32` (`tools/rdna_cvt_pk_u8.py`), + `v_cvt_pknorm_i16_f32` and `v_cvt_pknorm_u16_f32` have not yet been measured + with a silicon probe on physical RDNA 2 hardware, and the AMD RDNA 2 ISA + reference leaves rounding/bounds/NaN details of the `float32_to_snorm16` / + `float32_to_unorm16` helpers implicit. This direct DXIL lowering implements a + single RNE rounding of the exact scaled product (`clamp(x) * 32767` or `* + 65535`) with `NaN -> 0`; the fixture explicitly includes the four inputs + (`0x3F000400`, `0x38400180`, `0x3F000200`, `0x37C000C0`) that separate + single-rounding exact multiplication from a binary32 multiply followed by RNE. + +- For normal binary32 inputs with `mag in [2^-17, 1.0)` (`exp in [110, 126]`), + the 24-bit significand `m` is multiplied by `2^k - 1` (`k = 15` for `i16`, + `k = 16` for `u16`) as `(m << k) - m` split cleanly at bit `k` into `(p_hi, + p_lo)`, and rounded to nearest even using both `rem_hi` against `mid_hi` and + the nonzero carry-over `p_lo != 0` bit. +- Magnitudes `< 2^-17` (zeros and all binary32 subnormals included) round to `0`. +- Magnitudes `>= 1.0` (`±Inf` included) saturate to `±32767` (`i16`) or `65535` + / `0` (`u16`). +- Any negative value (`sign != 0`) maps to `0` on `v_cvt_pknorm_u16_f32`. +- Non-finite NaN operands (`mag > 0x7f800000`) map to `0`. +- Supported VOP3 input modifiers are `abs[1:0]` and `neg[1:0]` on `S0` and + `S1`, with `EXEC`-masked destination writes and VGPR, SGPR, 32-bit literal, + and inline `f32`/integer sources via `operand32()`. + +## Refused encodings + +The translator refuses `v_cvt_pknorm_i16_f32` and `v_cvt_pknorm_u16_f32` when +any of the following hold: + +- VOP3 `clamp != 0` or `omod != 0`. +- Any `op_sel` bits (`op_sel[3:0]`), third-operand `abs`/`neg` bits + (`abs[2]`/`neg[2]`), or non-zero `src2`. +- DPP16, SDWA, permuted/subword encodings, or unsupported operand codes (such as + `254`). + +## Fixture coverage and reproduction + +[native_cvt_pknorm_f32_check.py](../../tests/native_cvt_pknorm_f32_check.py) +checks 28 Compute cases (`<= 32` words/lane in `native_store_replay`), 8 +refusal controls, single-rounding vs binary32-multiply-then-RNE separation, and +lossless 16-bit Pixel readback across 14 draws (27 full-`EXEC` cases padded to +28) on WARP and D3D12 hardware: + +```powershell +cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -j 1 -R '^native_cvt_pknorm_f32_' -V +``` + +Compute replay requires shader model 6.6 with wave32; adapters without wave32 +report a skip (`77`) on `native_cvt_pknorm_f32_compute_hardware`. diff --git a/docs/experiments/native-descriptor-stride-scc.md b/docs/experiments/native-descriptor-stride-scc.md new file mode 100644 index 0000000000..7df3ecb032 --- /dev/null +++ b/docs/experiments/native-descriptor-stride-scc.md @@ -0,0 +1,32 @@ +# Buffer-stride condition code in direct compute + +The direct DXIL frontend can carry a guest buffer descriptor symbolically +while calculating SCC from its bound stride. It recognizes a 14-bit stride +extraction from descriptor word 1 and the subsequent unsigned max with 1. The +first sets SCC when the extracted stride is nonzero. The max sets SCC when its +first operand wins strictly, so both operand orders have meaningful tests. + +This applies to fixed, unambiguous buffer SRV slots covered by a declared +descriptor-table range. The compiler adds one stride word per descriptor, +after the regular root constants. Native dispatch and the published manifest +both use the stride from the input view the runtime has already resolved. The +symbolic descriptor fields still carry their slot identity for later buffer +addressing. A dynamic heap or CBV/UAV slot, unproven stride source, and numeric +reads of other symbolic fields retain their refusals. + +The [source-built fixture](../../tests/native_descriptor_scc_check.py) checks +the layout and cache replay, then dispatches with strides of 0, 1, 4 and 16. +The runtime fixture changes guest descriptor fields between runs of the same +shader on the in-process and published paths. It compares the three status +words, the neighboring root constant, and every untouched output word. +The isolated replay also verifies 14-bit extraction and refuses to dispatch +if the stride input is missing. The fixtures use the repository's MIT license. + +```powershell +cmake --build --preset release --target compile_dxil native_store_replay startup_stream_consumer +ctest --preset release --no-tests=error -R '^(native_descriptor_scc|startup_compute_descriptor_scc)_' -V +``` + +The direct shaders require Shader Model 6.6 and 32-lane waves. An available +adapter without wave32 reports a skip. The instruction behavior follows the +[AMD RDNA 2 ISA, revision 1.0](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture). diff --git a/docs/experiments/native-direct-absdiff.md b/docs/experiments/native-direct-absdiff.md new file mode 100644 index 0000000000..66535433eb --- /dev/null +++ b/docs/experiments/native-direct-absdiff.md @@ -0,0 +1,58 @@ +# s_absdiff_i32 in the direct C++ compute path + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) used to refuse `s_absdiff_i32` with +`direct DXIL lowering for s_absdiff_i32`. It now lowers it as the RDNA 2 ISA describes it: + +- D = S0 - S1, as a 32-bit difference that wraps. +- If D is negative, D = -D. So a difference of 0x80000000 stays 0x80000000. +- SCC = D != 0, written by the shared scalar tail as for the other SOP2 integer operations. + +The rules are the same as those of `gfx2hlsl.py` (`asuint(abs(asint({0} - {1})))`, SCC `$ != 0`), `tools/pixel_aot.py` and the +HLSL path in `src/gfx1013_compute_native.cpp`. + +## Fixture + +`tests/native_absdiff_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_absdiff_' -V`). + +- **Encoding:** the program is built with the encoding helpers of the other native fixtures (`scalar`, `sop1`, `vop2`, `vmove`). + Each word was checked with `tools/disasm_rdna2.py --hex`. +- **Inputs:** two groups of 32 lanes. `s24 = group * 0x01000193`. Six register pairs are XORed with `s24` at run time, so group 1 + sees different values, and equal pairs stay equal: + - (5, 3), (3, 5); + - (0x80000000, 0) and (0x7fffffff, 0xffffffff), whose differences wrap to 0x80000000; + - (0x80000000, 1), whose difference wraps to a positive value; + - (7, 7). +- **Constant operands:** two more cases take S1 as the literal 0xfffffff0 and as the inline constant -1. +- **What is read back:** each lane stores the result and SCC (through `s_cselect_b32`) of each of the eight cases. + - Before the equal pair, SCC is 1, so a lowering that left SCC unchanged would show there. +- **Controls:** + - The program must compile. + - Both wrap results and the zero result must be present in the expected words. + - The reference must differ from each of these mutated references: + - a difference that does not wrap; + - the unsigned distance; + - 0x80000000 saturated to 0x7fffffff; + - the difference without the absolute value; + - SCC left unchanged. + +## Measured + +Measured on 27.11.2026: `main` `1ec2c938` plus this change, Windows 11 Pro 10.0.26200, NVIDIA GeForce RTX 5090 (driver +32.0.16.1088), dev preset with the debug layer on. + +- **Controls:** printed `compiled; the unwrapped, unsigned, saturated, signed-difference and SCC-unchanged references each differ`. +- **Readback:** printed `s_absdiff_i32: 1024 words of two groups and the guards matched`. +- **Negative controls:** each mutation below was built and run. + + | Mutation | Result | + |---|---| + | Lowering removed | Both tests fail (`direct DXIL lowering for s_absdiff_i32`) | + | No absolute value | The readback fails (`0xfffffffe` for (3, 5), expected 2) | + | SCC not written | The readback fails at the SCC words | + +- **Not run:** the readback has not been run on WARP or on an AMD GPU. +- **Local start-up capture:** `compile_dxil --refusals` was run on one capture of 2,689 compute requests (counts only). + - At `main` `1ec2c938`, 399 compile and 7 stop first at `s_absdiff_i32`. + - With this change, 1 of the 7 compiles, so the total that compile goes from 399 to 400. + - The other 6 stop at a later refusal: 3 at `direct descriptor address outside bound table`, 2 at + `direct image opcode or descriptor modifiers` and 1 at `unbound numeric SGPR sN`. diff --git a/docs/experiments/native-direct-add-sub-sat.md b/docs/experiments/native-direct-add-sub-sat.md new file mode 100644 index 0000000000..2e269e4e58 --- /dev/null +++ b/docs/experiments/native-direct-add-sub-sat.md @@ -0,0 +1,31 @@ +# Signed and saturating 32-bit add/sub in the direct C++ compute path (#3009) + +The direct compute frontend refused the VOP3-only `v_add_nc_i32` and `v_sub_nc_i32` with `direct DXIL lowering for +`, and the `clamp` forms of `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` with `direct ALU operand +modifiers`. It now lowers them: + +- without `clamp`, the signed forms wrap modulo 2^32 like the unsigned ones; +- with `clamp`, `v_*_nc_i32` saturates to the i32 range (an overflow saturates toward the sign of S0) and + `v_*_nc_u32` saturates to 0 or 0xffffffff. + +LLVM 15.0.7 selects exactly these clamp forms for `llvm.sadd.sat.i32`, `llvm.ssub.sat.i32`, `llvm.uadd.sat.i32` and +`llvm.usub.sat.i32` (`clang -nogpulib -target amdgcn-- -mcpu=gfx1013 -O2 -S`). `tools/startup/gfx2hlsl.py` has no +lowering for these forms. `tools/compute_store_aot.py` lowers the unclamped signed forms the same way (wrap) and +refuses clamp (`tests/compute_store_check.py`, `vadd_nc_i32_controls`). Overflow is detected with 32-bit sign tests, so the module needs no 64-bit integers. +Source negation or abs, omod, op_sel, SDWA and DPP forms are refused. + +## Fixture + +`tests/native_add_sub_sat_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_add_sub_sat_' +-V`). The VOP3 words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). Four cases set S0 and S1 by `v_mov` literals at the i32 and u32 edges: 0x7fffffff + 1, +0x80000000 - 1, -1 + 0x80000000 and 0x7fffffff - (-1). Every lane of two groups stores the seven results of each case. + +The controls compile the program and check the module for the add, sub and select. They check that a neg modifier on +S0 is refused. They also check that three references each differ from the expected words: unclamped, signedness +swapped, saturation toward the sign of S1, and `v_subrev_nc_u32` without the operand swap. The log of this run is +`out/logs/addsub_ctest.log` (not committed). + +Measured on 27.11.2026, `cpp-migration` `e0d83759` plus this change, Windows 10.0.26100, with an NVIDIA Quadro M1000M +(driver 32.0.15.7371, debug layer unavailable). The controls passed. The readback reported a skip (77) because it needs +shader model 6.6 with wave32. The readback is not measured. diff --git a/docs/experiments/native-direct-align-bfm.md b/docs/experiments/native-direct-align-bfm.md new file mode 100644 index 0000000000..fd94d397b6 --- /dev/null +++ b/docs/experiments/native-direct-align-bfm.md @@ -0,0 +1,34 @@ +# v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32 in the direct C++ compute path (#2985) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers three VOP3 bit operations that it +refused with `direct DXIL lowering for `. The semantics are the expressions of the `gfx2hlsl.py` VOP3 table: + +- `v_alignbit_b32`: bits [k + 31 : k] of the 64-bit value {S0, S1}, with k = S2[4:0]. A zero k returns S1. +- `v_alignbyte_b32`: the same with k = 8 * S2[1:0]. +- `v_bfm_b32`: ((1 << S0[4:0]) - 1) << S1[4:0], the rule `s_bfm_b32` already uses in this path. + +Shift amounts are masked to five bits. The zero case is a select, so the masked shift by 32 - k in the other arm +stays in range. + +These three were found with a local probe that is not part of this change. It compiles one instruction per VOP3 +name of `src/gfx1013_isa_tables.inl` (VOP3 encoding, VGPR operands) through `compile_dxil ... gfx1013-direct-cs@0`. +On `cpp-migration` `05438d65` it saw 79 names refused, and these three had a `gfx2hlsl.py` lowering and no issue or +PR at the time. + +## Fixture + +`tests/native_align_bfm_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_align_bfm_' -V`). The words were assembled with LLVM 15.0.7 (`clang +-cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- The dispatch has two groups of 32 lanes. Lane L of group g uses S0 = 0x89abcdef, S1 = 0x01234567 and + S2 = L + 32g, so every shift 0 to 31 and every byte count appears. Group 1 repeats them with bit 5 set, which the + field must ignore. `v_bfm_b32` takes S0 = S2 and S1 = S2 ^ 0x15. The 192 results and the guard words are compared + with a CPU reference. +- The controls compile the program and check that the references with the zero shift not special-cased, with S0 + and S1 exchanged, and with the field not masked each differ from the expected words. + +Measured on 27.11.2026, `cpp-migration` `05438d65` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled; the zero-shift, exchanged-source and unmasked references each differ from the expected words`. The +readback printed `requires shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver +32.0.15.7371, debug layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-bitscan.md b/docs/experiments/native-direct-bitscan.md new file mode 100644 index 0000000000..3644fec3d5 --- /dev/null +++ b/docs/experiments/native-direct-bitscan.md @@ -0,0 +1,52 @@ +# 32-bit bit counts and bit scans in the direct C++ compute path + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) used to refuse these operations with +`direct DXIL lowering for `. It now lowers them through DXIL `Countbits` (31), `FirstbitLo` (32), `FirstbitHi` (33) and `FirstbitSHi` (34). + +| Operation | Result | SCC | +|---|---|---| +| `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32` | number of zero or one bits of S0 | D != 0 | +| `s_ff0_i32_b32`, `s_ff1_i32_b32`, `v_ffbl_b32` | index of the first zero or one bit, counted from bit 0 | unchanged | +| `s_flbit_i32_b32`, `v_ffbh_u32` | position of the first one bit, counted from bit 31 | unchanged | +| `s_flbit_i32`, `v_ffbh_i32` | position of the first bit that differs from the sign bit, counted from bit 31 | unchanged | + +- **No qualifying bit:** every scan returns `0xffffffff`. That covers 0 for all of them, and `0xffffffff` for the signed forms and `s_ff0_i32_b32`. +- **Counting direction:** DXIL `FirstbitHi` and `FirstbitSHi` already count from bit 31, as the gfx10 scans do. That is why HLSL's `firstbithigh` compiles to `31 - FirstbitHi`, and why no subtraction is emitted here. +- **Not covered:** the 64-bit scalar forms (`*_b64`). Like the other integer VOP3 forms, source abs/neg, clamp and output modifiers stay refused with `direct ALU operand modifiers`. + +## Fixture + +`tests/native_bitscan_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_bitscan_' -V`). + +- **Encoding:** the program is built with the encoding helpers of the other native fixtures, `sop1`, `scalar`, `vop2` and `vmove`. Each word was checked with `tools/disasm_rdna2.py --hex`. +- **Inputs:** two groups of 32 lanes. Lane L of group g holds: + - x = (0x80000000 >> g) >> L, shifted arithmetically. Group 0 holds negative values down to `0xffffffff`; group 1 holds single bits down to 0. + - z = x ^ mul_u32_u24(L + 32g, 0x9e3779). + - The scalar inputs are s9 = g * 0xff0f0010, which is 0 in group 0, and s10 = ~s9. +- **What is read back:** each lane stores 16 words: the three vector scans of x and of z, the six scalar results for s9, two SCC words, and `s_flbit_i32` and `s_ff0_i32_b32` of s10. + - One SCC word is read after an `s_bcnt1_i32_b32` followed by an `s_ff1_i32_b32`, so a scan that wrote SCC would show. + - The other is read straight after `s_bcnt0_i32_b32`. +- **Controls:** + - The program must compile. + - The VOP3 `v_ffbl_b32` with the clamp bit must be refused. + - The reference must differ from each of these mutated references: scans counted from the wrong end, the unsigned scan in place of the signed one, a scan of 0 that returns 32, a bit count that leaves SCC alone, and a scan that writes SCC. + +## Measured + +Measured on 27.11.2026: `main` `98007de5` plus this change, Windows 11 Pro 10.0.26200, NVIDIA GeForce RTX 5090 (driver 32.0.16.1088), dev preset with the debug layer on. + +- **Controls:** printed `compiled; clamp refused; the wrong-end, unsigned, zero-is-32, SCC-dropped and SCC-written references each differ`. +- **Readback:** printed `bit counts and scans: 1024 words of two groups and the guards matched`. +- **Negative controls:** each mutation below was built and run. + + | Mutation | Result | + |---|---| + | Lowering removed | Both tests fail (`direct DXIL lowering for v_ffbh_u32`) | + | `FirstbitLo` and `FirstbitHi` exchanged | The readback fails | + | Scans that also write SCC | The readback fails at the SCC word after `s_ff1_i32_b32` | + +- **Not run:** the readback has not been run on WARP or on an AMD GPU. +- **Local start-up capture:** `compile_dxil --refusals` was run on one capture of 2,689 compute requests (counts only). + - 12 requests stopped first at one of these operations: `s_bcnt1_i32_b32` (5), `s_ff1_i32_b32` (3), `v_ffbl_b32` (3) and `v_ffbh_i32` (1). + - With this change, 6 of the 12 compile, so the total that compile goes from 392 to 398. + - The other 6 stop at a later refusal: 2 at `s_absdiff_i32`, 2 at `unbound numeric SGPR`, 1 at `direct descriptor address outside bound table` and 1 at `non-contiguous resource descriptor`. diff --git a/docs/experiments/native-direct-cvt-f16-i16.md b/docs/experiments/native-direct-cvt-f16-i16.md new file mode 100644 index 0000000000..838acae2c0 --- /dev/null +++ b/docs/experiments/native-direct-cvt-f16-i16.md @@ -0,0 +1,39 @@ +# Binary16 <-> 16-bit integer conversions in the direct C++ compute path (#3148) + +`src/gfx1013_direct_compute.inl` now lowers `v_cvt_f16_u16`, `v_cvt_f16_i16`, `v_cvt_u16_f16`, and `v_cvt_i16_f16` +(VOP1 and VOP3A) in the direct C++ compute path (`DirectCompute::float_alu()`): + +- **High-half preservation:** Every operation reads `S0[15:0]`, writes the converted 16-bit result into `D[15:0]`, and + preserves `D[31:16]`, matching LLVM `GCNSubtarget::zeroesHigh16BitsOfDest` (`"On gfx10, all 16-bit instructions preserve + the high bits"`). +- **`v_cvt_f16_u16` / `v_cvt_f16_i16`:** Sign-extends (for `i16`) or zero-extends (for `u16`) `S0[15:0]`, converts to + binary32 (`sitofp`/`uitofp`), rounds to nearest-even binary16 with `packed_half_rne()` (e.g. `2049 -> 2048`, `2051 -> + 2052`, `65519 -> 65504`, `65520 -> +inf`, `32767 -> 32768.0h`), and optionally applies VOP3 `clamp` (`[0.0, 1.0]`). +- **`v_cvt_u16_f16` / `v_cvt_i16_f16`:** Applies optional VOP3 `abs`/`neg` on `S0[15:0]`, widens with + `@dx.op.legacyF16ToF32`, truncates toward zero, saturates to `[0, 65535]` / `[-32768, 32767]`, and maps NaN to `0`. +- **Mode & modifier contract:** Included in `half_binary` in `DirectCompute::lower()` so the default FP16 rounding + (`round16 = 0` RNE) and denormal (`denorm16 = 3` keep, `FP16_OVFL = 0`) mode contract is enforced. Refuses DPP, SDWA, + output modifiers (`omod`), `clamp` on `*_f16` integer targets, `op_sel` high-half bits, `abs`/`neg` on integer sources, + unused VOP3 `src1`/`src2`, and non-default FP16 modes. Inline float constants use the same binary16 bit table as + `v_add_f16`. + +## Fixture + +[`tests/native_cvt_f16_i16_check.py`](../../tests/native_cvt_f16_i16_check.py) via +[`tests/cmake/native_half_int_cvt.cmake`](../../tests/cmake/native_half_int_cvt.cmake) (`native_cvt_f16_i16_ir`, +`native_cvt_f16_i16_controls`, `native_cvt_f16_i16_hardware`): + +- **IR (`native_cvt_f16_i16_ir`):** Evaluates lane 0 across 82 conversion cases (VGPR, SGPR, literal, inline integer, + inline float, VOP3 `clamp`, `abs`, `neg`, `-|x|`, rounding ties, saturation, subnormals, infinities, NaNs, and + non-zero upper halves) plus 38 refusal cases (DPP, SDWA, `omod`, `op_sel`, illegal `abs`/`neg`/`clamp`, `src1`, and + MODE writes). +- **Controls (`native_cvt_f16_i16_controls`):** Compiles the full 82-case shader to DXIL via `compile_dxil` and checks + `dxc.exe -dumpbin` plus all 38 refusals. +- **Hardware (`native_cvt_f16_i16_hardware`):** Replays all 82 conversions on hardware via `native_store_replay --direct`. + +Measured on 27.11.2026, `main` `429f11d5` plus this change, Windows 10.0.26100 (`dev` preset): `native_cvt_f16_i16_ir` +(`1.09s`: 82 conversions + 38 refusals), `native_cvt_f16_i16_controls` (`3.84s`), all 47 `native_*_(controls|ir)` tests +(`54.43s`), and `tests/docs_links_check.py` (`101` Markdown files, `589` links) passed; `native_cvt_f16_i16_hardware` +skipped (`77`, Quadro M1000M does not support shader model 6.6 with wave32, so GPU readback is not measured). Five +broken-lowering sensitivity checks (`zero_high_half`, `drop_ordered_nan`, `swap_signed`, `drop_clamp`, +`wrong_inline_float`) each failed `native_cvt_f16_i16_ir`. diff --git a/docs/experiments/native-direct-cvt-pk-u8.md b/docs/experiments/native-direct-cvt-pk-u8.md new file mode 100644 index 0000000000..9db695fd01 --- /dev/null +++ b/docs/experiments/native-direct-cvt-pk-u8.md @@ -0,0 +1,62 @@ +# v_cvt_pk_u8_f32 in the direct C++ compute path (#2997) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers `v_cvt_pk_u8_f32`, which it refused with +`direct DXIL lowering for v_cvt_pk_u8_f32`. It computes +D = (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]). + +The conversion is the one `gfx2hlsl.py` (`op_v_cvt_pk_u8_f32`) uses, measured on RDNA 2 hardware +(`docs/experiments.md`, `tools/rdna_cvt_pk_u8.py`): round to nearest even, saturate to [0, 255]. NaN, both zeros and +every negative value give 0; +inf gives 255. + +The lowering rounds the binary32 word with integer operations. The original DXIL +`FMin` / `Round_ne` / `fptoui` sequence returned 1 for literal 0.5 on multiple +NVIDIA adapters ([#3052](https://github.com/R0Y00/Xbox2Windows/issues/3052)). +The same issue reports 0 when 0.5 is computed at runtime. The cause inside the +driver remains unverified. + +The unsigned test `(bits - 1) < 0x7f800000` accepts positive subnormals through ++Inf. Values above 255 are bounded to 255, and inputs that must produce zero +are bounded to 0.5, which rounds to zero. With the input in [0.5, 255], the +number of discarded significand bits is in [16, 24]. The lowering adds half +the discarded range minus one, plus the least significant retained bit, +before shifting. An exact tie rounds up only when the retained integer is +odd. The resulting byte is merged into S2. + +Source and output modifiers stay refused (`direct ALU operand modifiers`), as `gfx2hlsl.py` refuses them. + +## Fixture + +`tests/native_cvt_pk_u8_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_cvt_pk_u8_' -V`). + +Sixteen cases set S0 and S1 by `v_mov` literals over S2 = 0xa5a5a5a5, and every lane of two groups stores the +results. The cases cover: +- the ties 0.5, 1.5, 2.5 and 254.5; +- the bound 255.5, 1e30 and +inf; +- -0.0, -1.0 and -inf; +- a quiet NaN; +- the smallest subnormal; +- 127.4999, 0.0 and 255.0; +- all four byte selects, plus a select of 6 that must use only its low two bits. + +The VOP3 word (opcode 0x15e) was assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 +-filetype asm -show-encoding`). + +The second dispatch uses the lane and group to generate every integer from +0 to 255, its upper half tie and both adjacent binary32 inputs. Each dispatch +compares 1,024 packed results and all guard and untouched words. + +The controls: +- compile both programs and check with `dxc -dumpbin` that neither module emits + `Round_ne` (DXIL opcode 26) or `fptoui`; +- refuse it with a negated S0; +- check that three references differ from the expected words: rounding half up, truncating, and letting negatives + through. + +The reference agrees with `model_rne_sat` of `tools/rdna_cvt_pk_u8.py` for all sixteen inputs (checked once while +writing the fixture). Fourteen of the sixteen inputs are also rows of the measured table +`tests/data/rdna_cvt_pk_u8_measured.tsv`; 1e30 and 127.4999 rely on the model only. + +The original compile-only check passed on `cpp-migration` `4ff5e36d` plus #2998 +on Windows build 26100.9711. Its readback skipped on the NVIDIA Quadro M1000M +(32.0.15.7371) because the replay requires shader model 6.6 with wave32. diff --git a/docs/experiments/native-direct-cvt-pk16.md b/docs/experiments/native-direct-cvt-pk16.md new file mode 100644 index 0000000000..e8696911e9 --- /dev/null +++ b/docs/experiments/native-direct-cvt-pk16.md @@ -0,0 +1,34 @@ +# v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 in the direct C++ compute path (#2995) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers the two saturating 16-bit packs that it +refused with `direct DXIL lowering for `. The semantics are the `gfx2hlsl.py` VOP3-table expressions. Each +saturates S0 and S1 to 16 bits and packs S0 into the low half and S1 into the high half: + +- `v_cvt_pk_u16_u32`: min(S, 0xffff) of the unsigned values. +- `v_cvt_pk_i16_i32`: the signed values clamped to [-32768, 32767]. + +A nonzero unused SRC2 field is refused (` with unused src2 field set`), as in `gfx2hlsl.py`, and so are the +op_sel bits (` with op_sel`). Source and output modifiers stay refused like the other integer VOP3 forms. + +As `docs/experiments.md` notes for the Python path, the RDNA 2 ISA text does not define the `u32_to_u16` and +`i32_to_i16` conversions. The saturation follows Mesa and the existing translators, and it is not measured on the +console. + +## Fixture + +`tests/native_cvt_pk16_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_cvt_pk16_' -V`). Eight operand pairs are set by `v_mov` literals and +converted by both instructions; each of 64 lanes stores the sixteen results. The pairs cross both bounds of both forms: +0, 0xffff, 0x10000, 0xffffffff, -32768, -32769, 32767, 32768, 0x7fffffff and 0x80000000 all occur. The VOP3 words +were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). +The other words were checked with `tools/disasm_rdna2.py --hex`. + +- The controls compile the program, refuse the same program with SRC2 = 3 or an op_sel bit, and check that references that truncate + instead of saturating, or that apply the unsigned bound to the signed form, differ from the expected words. The + reference agrees with the `gfx2hlsl.py` table expressions evaluated in Python for all eight pairs. This was checked + once while writing the fixture. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled; a nonzero src2 field and op_sel refused; the truncating and unsigned-bound references differ`. The readback printed +`requires shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, +debug layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-f16-high-half.md b/docs/experiments/native-direct-f16-high-half.md new file mode 100644 index 0000000000..667ac8ad17 --- /dev/null +++ b/docs/experiments/native-direct-f16-high-half.md @@ -0,0 +1,33 @@ +# Binary16 add, sub, subrev and mul keep the destination's high half + +In the direct compute path (`src/gfx1013_direct_compute.inl`), the non-SDWA forms of `v_add_f16`, `v_sub_f16`, +`v_subrev_f16` and `v_mul_f16` wrote the rounded binary16 result to D[15:0] and zeroed D[31:16]. They now keep +D[31:16]. + +- **LLVM:** `GCNSubtarget::zeroesHigh16BitsOfDest` lists exactly these four operations, in both the VOP2 and VOP3 encodings. It states "On gfx10, all 16-bit instructions preserve the high bits" and returns false from GFX10 on. +- **The same path:** `v_cvt_f16_f32` already keeps the high half. +- **#669:** for the non-packed 16-bit integer operations, an inline-assembly measurement on RDNA 2 silicon found the high half kept. + +No silicon measurement of these four f16 operations is known to me. + +SDWA forms still place the result through their `dst_sel` and `dst_unused` fields, and are unchanged. + +## Fixture + +`tests/native_f16_alu_check.py model|ir|gpu` (`native_f16_alu_ir`, `native_f16_alu_hardware`). Every destination +already held `0xabcd` in its high half before the operation. The model, the IR interpreter and the readback now +require each stored word to be `0xabcd` in the high half and the binary16 result in the low half. A zeroed high half +is a rejected mutant, in place of the earlier mutant that rejected a kept one. + +## Measured + +On `cpp-migration` `999e17cd` plus this change, Windows 10 build 19045, NVIDIA GeForce RTX 3080, driver +32.0.15.9174: +- **Model:** 82 results match. +- **IR:** 82 results and 16 refusals match. +- **Readback:** all 164 words match with the high half kept. +- **Old lowering:** with the previous zeroing restored, both the IR check and the readback fail at the first stored word. + +The readback used a local copy of `native_store_replay` linked with the app-local Agility SDK exports +(`D3D12SDKVersion` 620). The registered test reports a skip (77) on Windows 10, whose inbox runtime does not report +shader model 6.6. diff --git a/docs/experiments/native-direct-fma-f16.md b/docs/experiments/native-direct-fma-f16.md new file mode 100644 index 0000000000..2450d2489c --- /dev/null +++ b/docs/experiments/native-direct-fma-f16.md @@ -0,0 +1,41 @@ +# Scalar binary16 FMA in the direct C++ compute path (#3186) + +`src/gfx1013_direct_compute.inl` now lowers `v_fma_f16` (VOP3), `v_fmac_f16` (VOP2/VOP3A), `v_fmamk_f16` (VOP2), and +`v_fmaak_f16` (VOP2) in the direct C++ compute path (`DirectCompute::float_alu()`): + +- **Exact single-rounded FMA (`fused_half_rne()`):** Reuses the shared 32-bit integer `fused_half_rne(a, b, c)` helper + (introduced in #3151 for `v_pk_fma_f16`) so `a * b + c` computes an exact product, aligns the addend with a sticky + bit, and rounds once to nearest-even binary16 rather than double-rounding through binary32. +- **High-half preservation by default:** The default forms read `S0..S2[15:0]` / `K[15:0]` / `D[15:0]`, + writes the result into `D[15:0]`, and keeps `D[31:16]` unchanged. +- **Modifiers & MODE contract:** Supports VOP3 `abs`, `neg`, and `clamp` (`[0.0, 1.0]` saturation); refuses DPP, SDWA, + `omod`, high-half `op_sel` and third-source modifiers/`src2` on `v_fmac_f16_e64`, and non-default FP16 MODE writes + (`half_binary` in `DirectCompute::lower()`). +- **Test adjustment:** Updated the unlowered-instruction refusal placeholder in + [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py) from `v_fmac_f16` to `v_pk_fmac_f16`, and added + `@dx.op.unaryBits.i32(i32 33, ...)` (`FirstbitHi`) evaluation to its IR interpreter so `native_fma_f16_ir` evaluates + `fused_half_rne()` directly. + +Direct compute also accepts VOP3 `v_fma_f16` with `op_sel`. Bits 0 to 2 select the high half of the respective VGPR source before abs and neg. Bit 3 selects the high destination half and preserves its low half. A clear destination selector writes the low half and preserves the high half. Selected non-VGPR sources and clamp combined with `op_sel` are refused. The [half-selection fixture](../../tests/native_fma_f16_opsel_check.py) checks six captured forms in IR and direct GPU replay. + +## Fixture + +[`tests/native_fma_f16_check.py`](../../tests/native_fma_f16_check.py) via +[`tests/cmake/native_fma_f16.cmake`](../../tests/cmake/native_fma_f16.cmake) (`native_fma_f16_ir`, +`native_fma_f16_controls`, `native_fma_f16_hardware`): + +- **IR (`native_fma_f16_ir`):** Evaluates lane 0 across 41 cases (all 4 `#2073` single-rounding vs double-rounding tie + witnesses across all 4 instructions, SGPR/literal/inline-float/inline-int sources, `dst = src0` overlap, VOP3 + `abs`/`neg`/`clamp`, signed zeros, exact cancellation, subnormals, `diff_e >= 30` sticky-bit midpoint, underflow + ties, overflow, `Inf`/`NaN`) against an exact `fractions.Fraction` reference, plus 12 refusals. +- **Controls (`native_fma_f16_controls`):** Compiles the full 41-case shader to DXIL via `compile_dxil` and verifies all + 12 refusals. +- **Hardware (`native_fma_f16_hardware`):** Replays all 41 cases via `native_store_replay --direct`. + +Measured on 27.11.2026, `main` `c45bf9ab` plus this change, Windows 10.0.26100 (`dev` preset): `native_fma_f16_ir` +(41 cases + 12 refusals), `native_fma_f16_controls`, `native_f16_alu_ir`, `native_packed_f16_controls`, +`native_packed_f16_pixel_warp`, `native_packed_f16_pixel_hardware`, all 57 `^native_.*_(controls|ir)$` tests, and +`tests/docs_links_check.py` passed; `native_fma_f16_hardware` skipped (`77`, +`Intel(R) HD Graphics 530` `31.0.101.2111`: requires shader model 6.6 with wave32, so GPU compute readback is +not measured). Five broken-lowering sensitivity checks (`zero_high_half`, `drop_sticky`, `swap_fmamk_fmaak`, +`drop_clamp`, `drop_inf_cancel_nan`) each failed `native_fma_f16_ir` (exit `1`). diff --git a/docs/experiments/native-direct-gather-compare.md b/docs/experiments/native-direct-gather-compare.md new file mode 100644 index 0000000000..c257de1f38 --- /dev/null +++ b/docs/experiments/native-direct-gather-compare.md @@ -0,0 +1,45 @@ +# Comparison gather in the direct C++ image path (#2969) + +`image_io` in `src/gfx1013_direct_compute.inl` now lowers `image_gather4_c_lz` (MIMG opcode 79), which +`tools/startup/gfx2hlsl.py` lowers as `op_image_gather4_c_lz`. Before, the direct frontend refused it with +`direct image opcode or descriptor modifiers`, while the same program with `image_sample_c_lz` compiled (the fixture +keeps that control). + +## The form + +- 2D and 2D-array images with `dmask` 0x1. The address is the reference, then u and v (and the slice), as for + the comparison samples of this path. +- The lowering is DXIL `textureGatherCmp` (opcode 74). It uses channel 0, because gather4_c compares the resource's + red component, and takes the reference as its compare value. Like `image_gather4_lz` here, the gather reads the + view's first mip: DXIL gathers have no LOD operand, so the static sampler is fixed to mip zero. +- The sampler is a constant comparison sampler under the existing field checks of `sampler_index` (from + `pixel_aot.comparison_sampler_state`). +- The four results come back in the order DXIL returns them, the same assumption `image_gather4` and + `image_gather4_lz` already make in this path. A console readback is not part of this change. +- This is wider than the `gfx2hlsl.py` contract, which takes the form only in pixel stages, on 2D images and with + a bilinear comparison sampler (`pixel_aot.check_gather_sampler`). Here compute stages and 2D arrays are accepted, + as for the comparison samples of this path, and so is the point filter of the existing comparison field checks. + A gather reads the same four texels whatever the filter (D3D11.3 gather rule; not measured on the console). + +Refused by name (`direct image opcode or descriptor modifiers`): other dmasks, cube and 3D images, +`image_gather4_c` with implicit LOD, `_c_l` and `_c_b`. D16 is refused at decode +(`unsupported image dimension or D16`). Offset forms keep their existing refusal (not covered by the fixture). + +## Fixture + +`tests/native_gather_compare_check.py ` +(`ctest --preset dev --no-tests=error -R '^native_gather_compare_warp$' -V`). The programs reuse +`comparison_program()` of `tests/native_direct_container_check.py`: clamp X/Y, point with TRUNC_COORD, LESS. + +- A compute container compiles. `dxc -dumpbin` shows one `textureGatherCmp` with zero offsets, channel 0 and a float + compare value, and no `textureGather` or `sampleCmp`. +- dmask 0x2, a cube image, a 3D image, D16, `image_gather4_c`, `_c_l` and `_c_b` are refused by message; a 2D + array compiles. The module check traces each float operand to its register: u from v1, v from v2 and the + compare value from v0, the reference. +- `native_recording_check --graphics-sampler` creates, on WARP, the graphics pipeline of + `native_graphics_comparison_pso_warp`, with its comparison sample replaced by this gather. It runs cold and from + the cache, and checks the comparison and regular static samplers. + +Measured on 27.11.2026, `cpp-migration` `b260984f` plus this change, Windows 10.0.26100.9711: all three checks passed +(the pipeline on WARP, Microsoft Basic Render Driver 10.0.26100.9711). The gather results themselves are not read +back. diff --git a/docs/experiments/native-direct-global-load.md b/docs/experiments/native-direct-global-load.md new file mode 100644 index 0000000000..fe6efbff56 --- /dev/null +++ b/docs/experiments/native-direct-global-load.md @@ -0,0 +1,77 @@ +# Root-pointer global loads in the direct C++ compute path (#2962) + +The direct compute frontend (`src/gfx1013_compute_native.cpp`, `src/gfx1013_direct_compute.inl`) now lowers +`global_load_dword` in the `saddr` form, the form `tools/startup/gfx2hlsl.py` (`op_global_load_dword`) lowers for +the Python path. Before, the frontend refused it with `unsupported instruction global_load_dword` (measured with +`0xdc308000`). + +## The form + +ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, FLAT/GLOBAL addressing). SADDR must be the unadvanced +root address of a root SRV, with its matching high half: the same symbol and binding (`root_buffer_srv`) the +scalar root loads of this path already use. The load becomes a raw buffer load from that view. + +- The 32-bit byte offset zext(VADDR) + OFFSET is guarded to [0, 2^32): a positive offset reads 0 when VADDR is + above 2^32 - 1 - OFFSET, a negative one reads 0 when VADDR is below -OFFSET. Above the range, the unguarded + 32-bit sum would wrap into an in-bounds word of the view; the fixture shows this case. Below it, the wrapped value + lies near 2^32, outside any view under 4 GiB, so that guard does not change a result here. +- The immediate offset must be a multiple of 4. The low two bits of the address are dropped, as for + `buffer_load_dword` in this path, which assumes the DWORD alignment mode. `gfx2hlsl.py` instead refuses a VADDR it + cannot prove 4-byte aligned; the console's `SH_MEM_CONFIG.ALIGNMENT_MODE` is not measured. +- `glc`, `slc` and `dlc` are accepted (compiled, not measured). +- The binding's minimum size grows to the immediate offset plus 4 bytes for a positive offset; other loads keep + the size the scalar loads need. + +Refused by name: the `off` form (no SADDR), the FLAT and scratch segments, other opcodes (stores, +atomics), the `lds` form, an SADDR that is not a root address, a replaced high half, and an unaligned immediate +offset. An SADDR advanced by scalar arithmetic is refused earlier, as an unbound numeric SGPR; `gfx2hlsl.py` accepts +a pointer advanced by a known literal. Graphics stages never decode the FLAT encoding and keep +`unsupported instruction` (not covered by the fixture). + +## Limits + +- Addresses outside the bound view read 0. On the console the same address reads whatever memory lies there: + before the buffer for a negative byte offset, or past the end of the view. The translation then differs from + the guest unless the runtime binds a view that covers every address the program reads. `gfx2hlsl.py` has the + same limit. How the runtime sizes the view on `cpp-migration` was not checked here. + +## Fixture + +`tests/native_global_load_check.py ` +(`ctest --preset dev --no-tests=error -R '^native_global_load_hardware$' -V`). Every word was assembled with +LLVM 15.0.7: `clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`. + +- Eleven refusals are checked by message, and a load with `glc slc dlc` compiles. +- `dxc -dumpbin` of the dispatch program's module must show six raw buffer loads (five global and one scalar root + load), two upper-bound guards and one lower-bound guard. +- The dispatch (two groups of 32 lanes) reads the root SRV that `native_store_replay` fills with + 0x51aa0000 + dword index, sized to 64 dwords by a scalar load at byte 252. Each lane stores five words: offsets 0, + 16 and -8, a VADDR of 0xfffffff0 or above with offset 16 (guarded to 0), and an unaligned VADDR. References with + the offset dropped or the upper guard dropped must differ from the readback. + +The original single-DWORD change was measured on 27.11.2026, `cpp-migration` `e3670100`, Windows 10.0.26100.9711 (24H2): the refusals +and the module checks passed. The dispatch reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371), +because `native_store_replay` needs shader model 6.6 with wave32. The readback is not measured. With the frontend +change reverted, the first refusal check fails on `unsupported instruction global_load_dword`. + +## Multi-DWORD loads + +`global_load_dwordx2`, `global_load_dwordx3`, and `global_load_dwordx4` use +the same root-address proof and write consecutive VGPRs under EXEC. The +lowering computes the address once before writing any destination, including +when the destination aliases VADDR. The last DWORD must also fit the 32-bit +view offset. The minimum view size accounts for the full transfer width. +Reads across the end of the bound view return zero for the out-of-range +components. The view must cover every guest address whose value is needed. + +The same fixture hand-assembles the three wider forms. On `88cddb09` the +compiler refused all three at guest offset `+0x38`. On RTX 4070, driver +`32.0.16.2124` and Windows 11 build `26300.10075`, the updated fixture +checks the address/destination alias, the end of a 64-word view, negative +offsets with sparse EXEC, and positive overflow. Reversing the returned +registers changes 128 words for x2 and x3 and 256 for x4 across two groups. +The direct module requires shader model 6.6 and wave32. + +The address and width follow the [AMD RDNA 2 ISA, §9.2](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +and [LLVM 21.1.0 GFX1030 FLAT syntax](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#flat), +release commit `3623fe661ae35c6c80ac221f14d85be76aa870f1` under Apache-2.0 WITH LLVM-exception. diff --git a/docs/experiments/native-direct-int16-ternary.md b/docs/experiments/native-direct-int16-ternary.md new file mode 100644 index 0000000000..7f9cdd550b --- /dev/null +++ b/docs/experiments/native-direct-int16-ternary.md @@ -0,0 +1,59 @@ +# Three-source 16-bit integer VOP3 operations in the direct C++ compute path (#669) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers the eight three-source 16-bit integer +VOP3 operations that it refused with `direct DXIL lowering for `: +- `v_mad_u16` and `v_mad_i16` +- `v_min3_u16` and `v_min3_i16` +- `v_max3_u16` and `v_max3_i16` +- `v_med3_u16` and `v_med3_i16` + +## Semantics + +Each operation computes `D[15:0]` from `S0[15:0]`, `S1[15:0]` and `S2[15:0]`, and **`D[31:16]` preserves its +previous value** (measured on RDNA 2 silicon; LLVM `GCNSubtarget::zeroesHigh16BitsOfDest`: "On gfx10, all 16-bit +instructions preserve the high bits"). + +- `v_mad_u16` and `v_mad_i16`: `(S0[15:0] * S1[15:0] + S2[15:0]) mod 2^16`. As LLVM 15.0.7 notes + (`VOP3_Profile` with `Ternary_i16_Pats`), the signed and unsigned + forms have identical low 16 bits when clamp is not modelled. +- `v_min3_u16`, `v_max3_u16`, `v_med3_u16`: unsigned minimum, maximum and median of the three 16-bit halfwords. +- `v_min3_i16`, `v_max3_i16`, `v_med3_i16`: sign-extended minimum, maximum and median of the three 16-bit halfwords. + +## Refusals + +`op_sel` (bits 11..14 of VOP3 word 0) would select high halves and stays refused (`unsupported op_sel`). +Modifiers such as `clamp`, `scale`, `neg` and `abs` are refused with `direct ALU operand modifiers` by the path's +existing common rule. + +## Fixture + +`tests/native_int16_ternary_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_int16_ternary_' -V`). The words were assembled with LLVM 15.0.7 +(`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- **Dispatch:** two groups of 32 lanes (64 lanes total). With G = lane + 32 * group: + - S0 = mul_u32_u24(G, 0x05f3d1) ^ 0xa5800000 + - S1 = mul_u32_u24(G, 0x000371) ^ 0x7f9abcde + - S2 = mul_u32_u24(G, 0x001001) ^ 0x80007fff + Both halves are nonzero, values cross the 16-bit signed boundary (0x8000), 63 of 64 lanes wrap mad modulo $2^{16}$, + and all permutations of signed and unsigned orders are exercised. +- **Destinations:** destination registers `v10` through `v17` are preloaded with `0xcafebabe`. Each lane writes all + 8 results into the UAV buffer at offset $G \times 32$. +- **Controls:** verify CSO compilation, spot-check definitions, require `op_sel` and `clamp` to be refused, and + verify that mutated references differ from the expected words: + - zeroed high half (tests high-half preservation); + - signed comparisons as unsigned; + - median computed as minimum; + - mad computed without addend; + - mad operand read from high half instead of low half. +- **Hardware:** dispatches the shader through `native_store_replay --direct` and compares all 512 words and the + sentinel guards against the independent CPU reference. + +## Measured + +Measured on 27.11.2026, Windows 11 build 26300, AMD Radeon RX 6600M, driver 32.0.21045.11001. + +| Check | Result | +|---|---| +| `native_int16_ternary_controls` | pass: compiled; op_sel and clamp refused; definitions spot-checked; all mutants differ | +| `native_int16_ternary_hardware` | pass: eight 16-bit ternary operations: 512 words of two groups and the guards matched, high halves kept | diff --git a/docs/experiments/native-direct-int16.md b/docs/experiments/native-direct-int16.md new file mode 100644 index 0000000000..0bf86a0de6 --- /dev/null +++ b/docs/experiments/native-direct-int16.md @@ -0,0 +1,51 @@ +# Non-packed 16-bit integer VOP3 operations in the direct C++ compute path + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers twelve VOP3-only 16-bit integer operations +that it refused with `direct DXIL lowering for `: +- `v_add_nc_u16`, `v_sub_nc_u16`, `v_add_nc_i16` and `v_sub_nc_i16`; +- `v_mul_lo_u16`; +- `v_lshlrev_b16`, `v_lshrrev_b16` and `v_ashrrev_i16`; +- `v_min_u16`, `v_max_u16`, `v_min_i16` and `v_max_i16`. + +Each writes D[15:0] from S0[15:0] and S1[15:0], and D[31:16] keeps its value. #669 records two sources for keeping +the high half on RDNA 2: +- an inline-assembly measurement on RDNA 2 silicon, which kept D[31:16] for all of these without `op_sel`; +- LLVM's `GCNSubtarget::zeroesHigh16BitsOfDest`: "On gfx10, all 16-bit instructions preserve the high bits". + +The shifts take S1 shifted by S0[3:0]. Additions, subtractions and the multiply wrap modulo 2^16. The `_i16` +minimum and maximum compare signed halves, and `v_ashrrev_i16` sign-extends S1[15:0]. + +`op_sel` selects other halves, so it stays refused (`unsupported op_sel`). Source modifiers and `clamp` +stay refused by the path's existing rule. + +The three-source 16-bit forms are not covered here: `v_mad_u16`, `v_mad_i16`, `v_min3`, `v_max3` and +`v_med3` `_i16`/`_u16`. + +## Fixture + +`tests/native_int16_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_int16_' -V`). The words were assembled with LLVM 15 +(`llvm-mc -arch=amdgcn -mcpu=gfx1013 -show-encoding`). + +- **Dispatch:** two groups of 32 lanes. G = L + 32g is the lane's global index. +- **Sources:** S0 = G * 0x9e3779b9 and S1 = (G * 0x7f4a7c15) ^ 0x5bd1e995. Both high halves are nonzero, the shift counts cover 0..15, and bit 4 of S0 varies. +- **Destinations:** each is set to 0xcafebabe first, then the twelve results are stored per lane. +- **Readback:** the 768 results and the guard words are compared with a CPU reference. +- **Controls:** they compile the program, check spot values, and require `op_sel` on `v_add_nc_u16` to be refused. These references must each differ from the expected words: + - a zeroed high half; + - a five-bit shift count; + - signed and unsigned order exchanged; + - a logical shift for `v_ashrrev_i16`. + +## Measured + +On `cpp-migration` `999e17cd` plus this change, Windows 10 build 19045, NVIDIA GeForce RTX 3080, driver +32.0.15.9174: +- **Controls:** pass. +- **Readback:** matched all 768 words and the guards. +- **Mutated lowerings:** each fails the readback. The mutations are the high half zeroed, which reads back `0x0000e995` against the expected `0xcafee995`, a five-bit shift count, and signed minimum and maximum compared unsigned. +- **Neighbour:** the existing `native_align_bfm` readback still passes. + +The registered `native_store_replay` reports a skip (77) on Windows 10, whose inbox D3D12 runtime does not report +shader model 6.6. These readbacks used a local copy of the replay linked with the app-local Agility SDK exports +(`D3D12SDKVersion` 620, as `offscreen_check` has them). That local copy is not part of this change. diff --git a/docs/experiments/native-direct-ldexp.md b/docs/experiments/native-direct-ldexp.md new file mode 100644 index 0000000000..9acbae4f2b --- /dev/null +++ b/docs/experiments/native-direct-ldexp.md @@ -0,0 +1,44 @@ +# v_ldexp_f32 in the direct C++ compute path (#3013) + +The direct compute frontend refused `v_ldexp_f32` with `direct DXIL lowering for v_ldexp_f32`. It now lowers it with +the semantics of `tools/pixel_aot.py`'s `ldexp32`: + +- the result is S0 scaled exactly by 2^S1; +- zero, Inf and NaN pass unchanged, including the NaN payload; +- a denormal S0 is normalized rather than flushed; +- S1 is a signed integer clamped to [-512, 512]; +- a result above the range becomes a signed Inf; a result below the normal range is a denormal rounded to nearest + even, or a signed zero at or below 2^-150 (2^-150 itself is a tie that rounds to even zero); +- `clamp` saturates the result with integer tests: NaN and negative values (also -0) give +0, values from 1.0 give + 1.0, and a denormal stays. `pixel_aot` uses HLSL `saturate`, which agrees except that it may flush a denormal or + keep -0 depending on the float mode; the integer form leaves nothing to that mode. + +Every step is an integer bit operation, so no float operation can flush or round. A denormal mantissa is normalized +by five conditional left shifts (16, 8, 4, 2, 1), not by a bit-scan intrinsic. Every shift amount stays in 1..24, also +in lanes whose result a later select discards. Abs and neg on S0 are bit operations. +Abs or neg on S1 or S2, a nonzero src2 field, omod, op_sel, SDWA and DPP forms are refused. + +## Fixture + +`tests/native_ldexp_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_ldexp_' -V`). The +VOP3 words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). Eight cases set S0 and S1 by `v_mov` literals. Every lane of two groups stores `v_ldexp_f32` of S0, +of -|S0| and the clamp form. The cases cover: + +- an ordinary scale; +- a denormal input; +- the two round-to-even ties (1.5 * 2^-149 and 2^-150); +- a NaN payload; +- -0 with a huge exponent; +- a saturated result; +- an overflow to -Inf. + +The controls compile the program. They check the module for integer shifts and for no `fmul` and no DXIL unary float +operation. They check that neg on S1, abs on S1, omod, an op_sel bit and a nonzero src2 field are refused (the SDWA +and DPP refusals are not exercised: LLVM 15 has no such encodings of `v_ldexp_f32`). They also check that five +references each differ from the expected words: flushed denormals, truncation, rounding half away from zero, an +unclamped S1 that wraps, and a float clamp that flushes denormals and keeps -0. + +Measured on 27.11.2026, `main` `36d2cbeb` plus this change, Windows 10.0.26100. The controls passed. The +readback reported a skip (77) because the default adapter does not report shader model 6.6 with wave32. The readback +is not measured. The log of this run is `out/logs/ldexp_ctest.log` (not committed). diff --git a/docs/experiments/native-direct-mad32.md b/docs/experiments/native-direct-mad32.md new file mode 100644 index 0000000000..5bb8adacfb --- /dev/null +++ b/docs/experiments/native-direct-mad32.md @@ -0,0 +1,40 @@ +# Unfused f32 multiply-adds in the direct C++ compute path (#3005) + +The direct compute frontend lowered the fused `v_fma_f32` family (DXIL `FMad`). It refused `v_mad_f32` and +`v_mad_legacy_f32` with `direct DXIL lowering for `, and the VOP2 accumulators `v_mac_f32` and +`v_mac_legacy_f32` had no lowering. It now lowers all four with the semantics of `gfx2hlsl.py`'s `mad32`, which matches +`pixel_aot`. `gfx2hlsl.py` has no `v_mac_legacy_f32` entry; its semantics follow the derivation in +`tests/pixel_aot_check.py` (the `v_mac_legacy_f32` comment): + +- denormal inputs are flushed to signed zero; +- the product is rounded on its own; the legacy forms make 0 * anything +0; +- the flushed addend is added (`v_mac_*` add the destination); +- the sum is flushed. + +The product and the sum are plain `fmul` and `fadd`. They carry no fast-math flags, so DXIL does not allow them to be +contracted into `FMad`. The flush is an integer mask that keeps the sign bit of a denormal. Source and output +modifiers follow the other f32 VOP3 forms of this path. A `v_mac_*` VOP3 form with abs or neg on the accumulator +(src2) is refused, as in `pixel_aot`. + +## Fixture + +`tests/native_mad32_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_mad32_' -V`). The +VOP3 and VOP2 words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). Six cases set S0, S1 and S2 by `v_mov` literals. Each lane of two groups stores the four results of +every case. The cases cover: + +- (1 + 2^-12)^2 - 1, whose separately rounded product gives 2^-11, while fused rounding would give 2^-11 + 2^-24; +- a denormal input; +- 0 * inf, which is NaN for the plain forms and gives 2.0 for the legacy forms; +- -0 * 1 + -0, which gives -0 for the plain forms and +0 for the legacy forms; +- a sum of 2^-127, which is flushed to +0; +- an ordinary value. + +The controls compile the program. They check that the module has separate `fmul` and `fadd`, no `FMad` (DXIL tertiary +opcode 46) and no fast-math flags. They also check that three references each differ from the expected words: fused, +unflushed, and legacy treated like plain. In the readback, NaN results compare by class. + +Measured on 27.11.2026, `cpp-migration` `e0d83759` plus this change, Windows 10.0.26100.9711. The controls passed. The +readback reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug layer unavailable): it needs +shader model 6.6 with wave32. The readback is not measured, and in particular whether the desktop driver honours the +missing contract flag is not measured. diff --git a/docs/experiments/native-direct-mad64.md b/docs/experiments/native-direct-mad64.md new file mode 100644 index 0000000000..a6ae631c69 --- /dev/null +++ b/docs/experiments/native-direct-mad64.md @@ -0,0 +1,43 @@ +# v_mad_u64_u32 and v_mad_i64_i32 in the direct C++ compute path (#3000) + +The direct compute frontend now lowers the two 64-bit multiply-adds. Before, it refused them with +`direct DXIL lowering for `. The contract is `gfx2hlsl.py` `mad64`: D = S0 * S1 + S2 modulo 2^64, with +32-bit factors and a 64-bit S2. The factors are zero-extended for `v_mad_u64_u32` and sign-extended for +`v_mad_i64_i32`. + +- `v_mad_u64_u32` writes the carry-out of the 64-bit add (sum < S2, unsigned) to its VOP3B SDST, which is VCC or + an SGPR. This uses the lane-mask path of the other carry instructions (`write_ballot`). `carry_destination` in + `src/gfx1013_compute_native.cpp` names its SDST so that the symbolic state forgets the old SGPR value. +- `v_mad_i64_i32` is lowered only with the null SDST. As in `gfx2hlsl.py`, the signed carry-out is not + established. Any other SDST is refused with `v_mad_i64_i32 carry-out destination`. +- S2 must be a VGPR pair or an aligned SGPR pair. Inline and literal 64-bit addends are refused, a narrower + contract than `gfx2hlsl.py`'s `i64_words`. +- In VOP3B, the ABS field holds SDST, so only NEG, clamp and the output modifier are refused among the modifiers. + SDWA, DPP, pixel stages and graphics inputs are refused as for the carry adds. An inline float factor is refused, + as in `gfx2hlsl.py`. +- The unsigned form with the null SDST is refused by the symbolic transfer (`unsupported carry mask destination`), + also as in `gfx2hlsl.py`, which takes only VCC or an SGPR there. + +## Fixture + +`tests/native_mad64_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_mad64_' -V`). +The words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). + +- The dispatch has two groups of 32 lanes. With n = lane + 32 * group: + - S0 = mul_u32_u24(n, 0x0f0f0f) ^ 0xffff0000 + - S1 = mul_u32_u24(n, 0x123457) ^ 0xfff00000 + - S2 = {((n & 1) << 31) | 0x10, mul_u32_u24(n, 0x777777) ^ 0x89abcdef} + + The products lie just below 2^64, so the unsigned sum carries exactly for the odd lanes (mask 0xaaaaaaaa). Each + lane stores the unsigned and signed results and the carry mask copied from s30. +- The controls: + - check the module for two `mul i64`, a sign extension and the unsigned carry compare; + - refuse `v_mad_i64_i32` with an SGPR carry-out, `v_mad_u64_u32` with the null SDST, and an inline float factor; + - check that both groups have mixed carries; + - check that three mutated references each differ from the expected words: high word dropped, signed factors + zero-extended, and no carry. + +Measured on 27.11.2026, `cpp-migration` `e0d83759` plus this change, Windows 10.0.26100.9711. The controls passed. +The readback reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug layer unavailable): it +needs shader model 6.6 with wave32. The readback is not measured. diff --git a/docs/experiments/native-direct-perm-lerp.md b/docs/experiments/native-direct-perm-lerp.md new file mode 100644 index 0000000000..93533b2dde --- /dev/null +++ b/docs/experiments/native-direct-perm-lerp.md @@ -0,0 +1,49 @@ +# v_perm_b32 and v_lerp_u8 in the direct C++ compute path + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers two VOP3 byte operations that it refused +with `direct DXIL lowering for `. The semantics are the RDNA 2 ISA definitions, as the `gfx2hlsl.py` +lowerings in #2875 and #2873 state them: + +- **`v_perm_b32`:** each result byte i takes the selector s = S2[8i+7:8i]. + - s 0..7 picks byte s of the 64-bit value {S0, S1}; S1 holds bytes 0..3. + - s 8..11 gives 0xff or 0x00 from bit 15 of S1, bit 31 of S1, bit 15 of S0 or bit 31 of S0. + - s 12 gives 0x00, and s 13..255 give 0xff. +- **`v_lerp_u8`:** each result byte is (S0 + S1 + S2[8i]) >> 1. Only the low bit of each S2 byte rounds. + +Source modifiers and `clamp` stay refused (`direct ALU operand modifiers`). The path's existing rule for 32-bit +operations ignores `op_sel` bits, and this change does not alter that. + +A local probe found both names. It compiles one instruction per VOP3 name of `src/gfx1013_isa_tables.inl` through +`compile_dxil ... gfx1013-direct-cs@0`, and is not part of this change. On `cpp-migration` `999e17cd` it saw 68 of +120 names refused. These two have `gfx2hlsl.py` pull requests from the start-up census, and neither had an issue +or pull request for the direct path. + +## Fixture + +`tests/native_perm_lerp_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_perm_lerp_' -V`). The words were assembled with LLVM 15 +(`llvm-mc -arch=amdgcn -mcpu=gfx1013 -show-encoding`). + +- **Dispatch:** two groups of 32 lanes. G = L + 32g is the lane's global index. +- **`v_perm_b32`:** S0 = 0x1b6c9e37, S1 = 0x80f07ad5, and the S2 bytes are 4G .. 4G+3. So the 64 lanes cover all 256 selectors once. A second `v_perm_b32` exchanges S0 and S1. The two words differ at bits 15 and 31, and their bits 7 and 23 differ from bits 15 and 31. +- **`v_lerp_u8`:** S1 = G * 0x9e3779b9, S0 = S1 ^ 0xff80017f, and S2 = G * 0x01030507. +- **Readback:** the 192 results and the guard words are compared with a CPU reference. +- **Controls:** they compile the program and check spot values of the definitions. These references must each differ from the expected words: + - S0 and S1 exchanged; + - the sign read from bits 7 and 23; + - selector 12 as 0xff; + - the lerp rounding bit dropped, or taken from the whole S2 byte. + +## Measured + +On `cpp-migration` `999e17cd` plus this change, Windows 10 build 19045, NVIDIA GeForce RTX 3080, driver +32.0.15.9174: +- **Controls:** pass. +- **Readback:** matched all 192 words and the guards. +- **Mutated lowerings:** each fails the readback at its first affected words. The mutations are the sign always taken from S0, the lerp rounding bit dropped, and selector 12 as 0xff. +- **Neighbour:** the existing `native_align_bfm` readback still passes. + +The registered `native_store_replay` uses the inbox D3D12 runtime. On Windows 10 that runtime does not report +shader model 6.6, so the readback reports a skip (77) there. These readbacks used a local copy of the replay +linked with the app-local Agility SDK exports (`D3D12SDKVersion` 620), as `offscreen_check` has them. That local +copy is not part of this change. diff --git a/docs/experiments/native-direct-sad.md b/docs/experiments/native-direct-sad.md new file mode 100644 index 0000000000..65dd82ece3 --- /dev/null +++ b/docs/experiments/native-direct-sad.md @@ -0,0 +1,40 @@ +# Sum-of-absolute-differences operations in the direct C++ compute path (#2987) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers `v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, +`v_sad_u32` and `v_msad_u8`, which it refused with `direct DXIL lowering for `. The results are those of +`gfx2hlsl.py`'s `sad_u8`, `sad4_u8`, `sad_u16` and `sad_u32` helpers and of `tools/pixel_aot.py`. Each adds S2 and +wraps modulo 2^32: + +- `v_sad_u8`: the sum of the four unsigned byte differences |S0 byte - S1 byte|. +- `v_sad_hi_u8`: that sum shifted left by 16. +- `v_sad_u16`: the two unsigned halfword differences. +- `v_sad_u32`: the unsigned difference of the dwords. +- `v_msad_u8`: like `v_sad_u8`, but a byte whose S1 byte is zero contributes nothing. + +Source abs/neg, clamp and output modifiers stay refused, with `direct ALU operand modifiers` as for the other +integer VOP3 forms. The fixture checks clamp. + +## Fixture + +`tests/native_sad_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_sad_' -V`). The +words were assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm +-show-encoding`). + +- The dispatch has two groups of 32 lanes. With n = lane + 32 * group: + - S0 = mul_u32_u24(n, 0x050311) ^ 0x80f00a33 + - S1 = mul_u32_u24(n, 0x010203) & 0xffff00ff. Byte 1 is always zero, so `v_msad_u8` skips it. + - S2 = mul_u32_u24(n, 0x1001) + + S0 bytes both above and below the S1 bytes occur. The 320 results and the guard words are compared with a CPU + reference. +- That reference agrees, for all 64 lanes, with the existing references in `tests/startup_gfx2hlsl_sad_check.py` + (`ref_sad_u8`, `ref_sad_u16`, `ref_sad_u32`) and `tests/startup_gfx2hlsl_sad_hi_msad_check.py` (`sad4_u8`). + This was checked once by hand while writing the fixture; the fixture does not import those files. +- The controls compile the program and refuse the `v_sad_u8` form with the clamp bit. They also check that four + mutated references each differ from the expected words: signed byte differences, `v_msad_u8` without its mask, + `v_sad_hi_u8` without its shift, and S2 dropped. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls printed +`compiled; clamp refused; the signed, unmasked, unshifted and S2-dropped references each differ`. The readback +printed `requires shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver +32.0.15.7371, debug layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-salu-bfe64-brev64.md b/docs/experiments/native-direct-salu-bfe64-brev64.md new file mode 100644 index 0000000000..411e86a1f6 --- /dev/null +++ b/docs/experiments/native-direct-salu-bfe64-brev64.md @@ -0,0 +1,32 @@ +# 64-bit scalar bitfield extract and bit-reverse in the direct C++ compute path + +Issue #3086 (part of #2935) lowers `s_brev_b64`, `s_bfe_u64`, and `s_bfe_i64` +in `src/gfx1013_direct_compute.inl` and updates the symbolic pair-clear rule +in `src/gfx1013_compute_native.cpp` (`transfer()`) to include `_u64`. + +- `s_brev_b64`: lowers via pure 32-bit DXIL `@dx.op.unary.i32` opcode `30` + (`reversebits`) on both halves before writing the aligned even SGPR pair + (swapping low and high words), leaving `SCC` unchanged and requiring no + `Int64Ops` feature bit. +- `s_bfe_u64` / `s_bfe_i64`: reads `S0` (aligned even SGPR pair, `null`, + inline integer `-16..64`, or 32-bit literal sign-extended only for + `s_bfe_i64`) and `S1` (`S1[5:0]` offset, `S1[22:16]` width) before writing + the aligned even SGPR destination pair and setting `SCC = (D != 0)`. +- Symbolic liveness: `transfer()` in `src/gfx1013_compute_native.cpp` now + clears `s[dst + 1]` for `_u64` suffix instructions (`s_bfe_u64`), and + `uses_scc_after()` in `src/gfx1013_direct_compute.inl` marks + `s_bfe_u64`/`s_bfe_i64` as overwriting `SCC` and `s_brev_b64` as preserving `SCC`. + +## Verification + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay native_compute_ir_dump +ctest --preset dev --no-tests=error -R '^(native_salu_bfe64_brev64_|native_salu_shift64_|native_salu64_)' -V +ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' -j 4 --output-on-failure +``` + +Results (base `ca659396`): +- `native_salu_bfe64_brev64_controls`: Passed (`1.30s`) — verified pure 32-bit DXIL lowering of `s_brev_b64` (`@dx.op.unary.i32(i32 30, ...)` without `i64` ops), combined compilation of all 21 `s_brev_b64`/`s_bfe_u64`/`s_bfe_i64` cases, symbolic `transfer()` `_u64` descriptor-clobber refusal, 9 negative operand/destination refusal controls, and all 6 oracle mutants. +- `native_salu_bfe64_brev64_hardware`: Skipped (exit code `77`, `requires shader model 6.6 with wave32`) on local NVIDIA Quadro M1000M (SM 6.1); GPU readback is unmeasured locally. +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' -j 4`: `27/27` passed (`18.72s`). +- `tests/docs_links_check.py`: `79` Markdown files, `586` links passed. diff --git a/docs/experiments/native-direct-salu-bitscan64.md b/docs/experiments/native-direct-salu-bitscan64.md new file mode 100644 index 0000000000..896422769d --- /dev/null +++ b/docs/experiments/native-direct-salu-bitscan64.md @@ -0,0 +1,37 @@ +# 64-bit scalar bit counts and bit scans in the direct C++ compute path (#3072) + +`src/gfx1013_direct_compute.inl` now lowers the six 64-bit-source SOP1 bit-count and bit-scan instructions +`s_bcnt0_i32_b64`, `s_bcnt1_i32_b64`, `s_ff0_i32_b64`, `s_ff1_i32_b64`, `s_flbit_i32_b64` and `s_flbit_i32_i64` +using 32-bit DXIL `unaryBits.i32` (`31` `Countbits`, `32` `FirstbitLo`, `33` `FirstbitHi`), matching +`tools/startup/gfx2hlsl.py`: + +- **Destination:** general 32-bit SGPR (`s0..s105`), leaving `s[dst + 1]` untouched. +- **Source `S0`:** aligned SGPR pair (`s0..s104` even), EXEC (`exec_lo`/`exec_hi`, both words, in wave32 and wave64), inline integer (`-16..64`, sign-extended when negative), or + 32-bit literal (sign-extended for `s_flbit_i32_i64`, zero-extended for `_b64`). +- **Semantics & `SCC`:** `s_bcnt0_i32_b64` and `s_bcnt1_i32_b64` sum 32-bit `Countbits` over both halves and write + `SCC = (D != 0)`. `s_ff0_i32_b64`, `s_ff1_i32_b64`, `s_flbit_i32_b64` and `s_flbit_i32_i64` preserve `SCC` and return + `0xffffffff` when no qualifying bit exists. +- **Analysis & liveness:** `transfer()` in `src/gfx1013_compute_native.cpp` checks `i.name.find("_i32_") == Name::npos` + before clearing `s[dst + 1]` on `_b64` SOP1/SOP2 instructions so 32-bit-destination `_i32_b64` ops do not clobber + adjacent descriptors. `uses_scc_after()` in `src/gfx1013_direct_compute.inl` marks `s_bcnt0_i32_b64` and + `s_bcnt1_i32_b64` as overwriting `SCC`. + +## Fixture + +`tests/native_salu_bitscan64_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_salu_bitscan64_' -V`). +Encodings were verified with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- **Controls:** compiles all 6 ops and checks `dxc.exe -dumpbin` for `@dx.op.unaryBits.i32` opcodes `31`, `32`, `33` + with no `i64` shifts; tests `s_ff1_i32_b64 s31, s[22:23]` right below `s[32:35]` to verify `s32` stays intact; + checks 6 invalid destination/source refusals (`vcc`/`exec` dst, odd/`vcc`/`exec_hi`/float `S0`; since EXEC became a valid `S0`, the source control uses the odd `exec_hi`); checks 6 mutant + references differ. +- **EXEC as `S0`:** read back with `s_bcnt1_i32_b64` by `tests/native_wave64_exec_salu_check.py`, including masks that + span both host halves of a wave64 (`ctest --preset dev --no-tests=error -R '^native_wave64_exec_salu_hardware$' -V`). + The other five ops accept EXEC through the same source check but are not run with it. +- **Hardware cases:** all 6 ops across `(0, 0)`, `(0xffffffff, 0xffffffff)`, `(0, 1)`, `(0x80000000, 0)`, + `(0xfffffffe, 0xffffffff)`, `(0, 0x80000000)`, `(1, 0)`; inline `-1`; 32-bit literal `0x80000001`; explicit `SCC` + preservation (`0` and `1`) across count-then-scan sequences; overlapping `s22 = ff1(s[22:23])`. + +Measured on 27.11.2026, `main` `428c08c1` plus this change, Windows 10.0.26100 (`dev` preset): `native_salu_bitscan64_controls` +passed; `native_salu_bitscan64_hardware` skipped (`77`, Quadro M1000M does not support shader model 6.6 with wave32, so +readback is not measured). diff --git a/docs/experiments/native-direct-salu-cmov.md b/docs/experiments/native-direct-salu-cmov.md new file mode 100644 index 0000000000..fec14c8cdc --- /dev/null +++ b/docs/experiments/native-direct-salu-cmov.md @@ -0,0 +1,46 @@ +# Scalar conditional moves in the direct C++ compute path (#3070) + +`src/gfx1013_direct_compute.inl` now lowers `s_cmov_b32`, `s_cmov_b64` (SOP1) and `s_cmovk_i32` (SOPK) in the direct +compute path: + +- **Operation:** `D = SCC ? S0 : D`, leaving `SCC` unchanged. +- **32-bit forms (`s_cmov_b32`, `s_cmovk_i32`):** destination is a general SGPR (`s0..s105`), `vcc_lo` (`106`), or wave32 + `vcc_hi` (`107`). `s_cmovk_i32` sign-extends its 16-bit immediate; `s_cmov_b32` accepts a general SGPR, `vcc_lo`, wave32 + `vcc_hi`, inline constant, or 32-bit literal. +- **64-bit form (`s_cmov_b64`):** destination is an aligned SGPR pair (`s0..s104` even) or `vcc` (`106`). `S0` accepts an + aligned SGPR pair, inline integer (`-16..64`, sign-extended when negative), or 32-bit literal (`pair_high()` zero-extends + 32-bit literals consistently with `s_mov_b64`, `s_cselect_b64`, `s_not_b64`, and `s_lshr_b64`; unmeasured on wave32 + hardware here). +- **Differences from [`tools/startup/gfx2hlsl.py`](../../tools/startup/gfx2hlsl.py) `scalar_cmov`:** the HLSL startup path + refuses `vcc` and lane-mask operands and takes only an SGPR pair as the 64-bit `s_cmov_b64` source, whereas the direct + compute path accepts `vcc` as the `s_cmov_b64` destination, wave32 `vcc_lo`/`vcc_hi` on the 32-bit forms, and inline + integer or 32-bit literal sources on `s_cmov_b64`. +- **Analysis & liveness:** reading the previous destination through `operand32()` refuses symbolic-descriptor destinations. + `transfer()` in `src/gfx1013_compute_native.cpp` clears constant/symbolic state on `s_cmovk_i32` (observed by refusing a + table descriptor load whose high word had been constant zero prior to `s_cmovk_i32`). `uses_scc_after()` in + `src/gfx1013_direct_compute.inl` marks all three instructions in `reads_scc` (matching the existing `uncertain_scalar` + coverage). + +## Fixture + +`tests/native_salu_cmov_check.py ir|controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_salu_cmov_' -V`). +Encodings were verified with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- **IR (`native_salu_cmov_ir`):** dumps DXIL IR via `native_compute_ir_dump` for all 24 cases (`SCC = 0` and `SCC = 1` across + all 12 accepted forms: `s_cmov_b32` SGPR, literal, `1.0`, wave32 `vcc_hi` dst and src; `s_cmovk_i32` `-1234`, `0x7FFF`, + wave32 `vcc_hi` dst; `s_cmov_b64` pair, `-1`, literal `0x80000001`, `vcc` dst), evaluates lane 0 to verify exact + `D = SCC ? S0 : D`, preserved `SCC`, untouched neighbor words, and sign-extended `-1234` (`4294966062` rather than + `64302`), verifies the 8 invalid operand refusals, verifies 3 no-epilogue symbolic-descriptor destination refusals at exact + pc `+0x20` (`unbound numeric SGPR s24`), and verifies the `transfer()` `s_cmovk_i32` positive baseline + refusal at `+0x10` + (`direct descriptor address outside bound table`). +- **Controls (`native_salu_cmov_controls`):** compiles all 12 accepted forms into DXIL via `compile_dxil` and checks + `dxc.exe -dumpbin` for `select i1`, runs the same `transfer()` baseline and 12 exact diagnostic/pc refusals, and checks + the 5 mutant references differ. +- **Hardware (`native_salu_cmov_hardware`):** dispatches all 24 cases via `native_store_replay --direct` and checks output + words, preserved `SCC`, and guard words. + +Measured on 27.11.2026, `main` `429f11d5` plus this change, Windows 10.0.26100 (`dev` preset): `native_salu_cmov_ir`, +`native_salu_cmov_controls`, and all 47 `native_*_(controls|ir)` tests passed; `native_salu_cmov_hardware` skipped (`77`, +Quadro M1000M does not support shader model 6.6 with wave32, so GPU readback is not measured). Six deliberate broken +builds (`ignores_scc`, `inverted_select`, `writes_nothing`, `zero_ext_cmovk`, `keeps_old_high_word`, and dropping +`s_cmovk_i32` from `transfer()`) each failed `native_salu_cmov_ir`. diff --git a/docs/experiments/native-direct-salu-cmp64.md b/docs/experiments/native-direct-salu-cmp64.md new file mode 100644 index 0000000000..448982f6d5 --- /dev/null +++ b/docs/experiments/native-direct-salu-cmp64.md @@ -0,0 +1,43 @@ +# 64-bit scalar SOPC comparisons in the direct C++ compute path + +Issue #3078 (part of #2935) lowers the remaining 64-bit SOPC scalar comparison +and bit-test instructions in the direct C++ compute DXIL path +(`src/gfx1013_direct_compute.inl`): `s_cmp_eq_u64`, `s_cmp_lg_u64`, +`s_bitcmp0_b64`, and `s_bitcmp1_b64`. + +All four instructions write `SCC` only and leave scalar registers untouched. +`s_cmp_eq_u64` and `s_cmp_lg_u64` accept aligned even SGPR pairs, `null` (`0`), +sign-extended negative inline integers (`-1..-16`), and zero-extended positive +inline integers (`0..64`) or 32-bit literals (`0x80000001` -> `(0x80000001, 0)`), +while refusing `vcc`, `exec`, `m0`, `scc`, floats, and odd SGPRs. +`s_bitcmp0_b64` and `s_bitcmp1_b64` test bit `S1 & 63` of the 64-bit `S0` operand +using pure 32-bit DXIL operations (no `Int64Ops` shader feature bit required). + +## Verification + +`native_salu_cmp64_ir` dumps DXIL IR via `native_compute_ir_dump` for all 22 +test cases, asserts pure 32-bit IR (no 64-bit integer IR ops), evaluates lane 0 +to verify both the preserved SGPR pair (`s[22:23]`) and exact `SCC` output +(pinning compare operands, sign/zero-extension rules, and bit-5 high-word +selection), and verifies all 7 negative operand refusal controls. +`native_salu_cmp64_controls` compiles all 22 test cases together with +`compile_dxil`, checks `dxc.exe -dumpbin` for pure 32-bit IR (`icmp eq i32`, +`icmp ne i32`, `lshr i32`) with no 64-bit integer IR ops, checks 7 negative +operand refusal controls, and checks 6 oracle mutants (`low_word_only_cmp`, +`high_word_only_cmp`, `zero_ext_neg_inline`, `sign_ext_lit`, +`ignore_bit5_bitcmp`, `inverted_bitcmp`). `native_salu_cmp64_hardware` runs +`native_store_replay --direct` and returns skip code 77 when shader model 6.6 +wave32 hardware is unavailable. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay native_compute_ir_dump +ctest --preset dev --no-tests=error -R '^native_salu_cmp64_' -V +ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure +``` + +Results (Windows `10.0.26100`, `dev` preset, base `88cddb09`): +- `native_salu_cmp64_ir`: Passed (`0.98s`) — evaluated DXIL IR for all 22 cases in pure 32-bit IR (`s[22:23]` preserved + exact `SCC`), verified 7 operand refusals, and caught 6 oracle mutants. Five deliberate broken lowerings (`low_word_only_cmp`, `high_word_only_cmp`, `swap_and_or`, `ignore_bit5`, `invert_bitcmp`) each failed `native_salu_cmp64_ir` (`exit 1`). +- `native_salu_cmp64_controls`: Passed (`1.14s`) — compiled all 22 cases together in pure 32-bit DXIL IR (`6.77 ms` cold DXIL compile, `6948` bytes), passed 7 negative operand refusal checks, and caught all 6 SCC oracle mutants. +- `native_salu_cmp64_hardware`: Skipped (exit code `77`, `requires shader model 6.6 with wave32`) on local NVIDIA Quadro M1000M (SM 6.1); GPU readback is unmeasured locally. +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: `47/47` passed (`51.67s`). +- `tests/docs_links_check.py`: `102` Markdown files, `589` links passed. diff --git a/docs/experiments/native-direct-salu-shift64.md b/docs/experiments/native-direct-salu-shift64.md new file mode 100644 index 0000000000..0b8cc38f74 --- /dev/null +++ b/docs/experiments/native-direct-salu-shift64.md @@ -0,0 +1,31 @@ +# 64-bit scalar shifts in the direct C++ compute path (#3062) + +`src/gfx1013_direct_compute.inl` now lowers the SOP2 64-bit scalar shifts `s_lshl_b64`, `s_lshr_b64` and `s_ashr_i64` +matching `tools/startup/gfx2hlsl.py`'s `scalar_wide_op`: + +- **Destination:** aligned SGPR pair (`s0..s104` even) or `vcc` (`106`). +- **Source 0 (`S0`):** aligned SGPR pair (`s0..s104` even), inline integer (`-16..64`), or 32-bit literal (zero-extended + for `s_lshl_b64` and `s_lshr_b64`, sign-extended for `s_ashr_i64`). +- **Source 1 (`S1`):** general SGPR (`s0..s105`), inline integer (`-16..64`), or 32-bit literal, masked with `& 63`. +- **Execution:** all sources are read before writing `D[0:1]` so overlapping destinations (`s[22:23]` as both source and + destination) keep their original input values. Sets `ir.features |= 1048576` (`Int64Ops`) and `SCC = (D != 0)`. +- **Analysis & liveness:** `src/gfx1013_compute_native.cpp` (`transfer()`) now clears `s[dst + 1]` for SOP1/SOP2 + `_i64` instructions as well as `_b64`, preventing a stale symbolic descriptor tag on `s_ashr_i64`. `uses_scc_after()` + in `src/gfx1013_direct_compute.inl` marks all three shifts as overwriting `SCC`. + +## Fixture + +`tests/native_salu_shift64_check.py controls|hardware` (`ctest --preset dev --no-tests=error -R '^native_salu_shift64_' -V`). +Encodings were verified with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- **Controls:** compiles a combined shader exercising `s_lshl_b64`, `s_lshr_b64` and `s_ashr_i64` and checks `dxc.exe -dumpbin` + for `shl i64`, `lshr i64` and `ashr i64`; compiles an `s_load_dwordx2` -> `s_ashr_i64` -> `v_mov_b32` sequence confirming + both symbolic pair tags are cleared; checks 7 invalid destination/source refusals (`exec`, odd destination, odd `S0`, + `vcc` as `S0`, inline float as `S0`, inline float as `S1`, `vcc_lo` as `S1`); checks 6 mutant references differ. +- **Hardware cases:** SGPR pair `(0x89ABCDEF, 0x81234567)` across amounts `0, 1, 31, 32, 33, 63` and wrapped `65` via odd + SGPR `s27`; inline integers `-1, -16, 1, 64`; 32-bit literal `0x80000001` for `s_lshr_b64` and `s_ashr_i64`; overlapping + in-place `s[22:23]` shifts; high-word-only `vcc` (`SCC = 1`); zero result clearing primed `SCC = 1`. + +Measured on 27.11.2026, `main` `db28a796` plus this change, Windows 10.0.26100 (`dev` preset): `native_salu_shift64_controls` +passed; `native_salu_shift64_hardware` skipped (`77`, Quadro M1000M does not support shader model 6.6 with wave32, so +readback is not measured). diff --git a/docs/experiments/native-direct-signed-forms.md b/docs/experiments/native-direct-signed-forms.md new file mode 100644 index 0000000000..7aa95187b8 --- /dev/null +++ b/docs/experiments/native-direct-signed-forms.md @@ -0,0 +1,36 @@ +# v_ashrrev_i64 and v_mad_i32_i24 in the direct C++ compute path (#2991) + +The direct compute frontend (`src/gfx1013_direct_compute.inl`) lowered `v_lshrrev_b64`, `v_lshlrev_b64` and +`v_mad_u32_u24`, but refused their signed counterparts with `direct DXIL lowering for `. It now lowers them: + +- `v_ashrrev_i64`: an arithmetic `ashr i64` of S1 by S0[5:0]. The shifted value takes the operands of the + logical shifts: a VGPR or SGPR pair, an inline integer sign-extended to 64 bits, or a 32-bit literal. Following + `gfx2hlsl.py` `i64_words(signed=True)`, the literal is sign-extended for this form, where the logical shifts + zero-extend it. +- `v_mad_i32_i24`: sext(S0[23:0]) * sext(S1[23:0]) + S2 modulo 2^32, the `gfx2hlsl.py` VOP3-table expression. + +## Fixture + +`tests/native_signed_forms_check.py controls|hardware` +(`ctest --preset dev --no-tests=error -R '^native_signed_forms_' -V`). The words were assembled with LLVM 15.0.7 +(`clang -cc1as -triple amdgcn -target-cpu gfx1013 -filetype asm -show-encoding`). + +- The controls check the modules with `dxc -dumpbin`: exactly one `ashr i64` per shift program, and an arithmetic + shift right with `mul i32` for the multiply-add. +- The shift dispatches reuse `native_shift64_check.compute_program` with the `v_ashrrev_i64` opcode (VOP3 0x301). + They cover shift amounts 0, 1, 31, 32, 33 and 63 and six sources: inline -1, -16, 64 and 1, the literal 0x80000001 + and the negative SGPR pair 0x89abcdef:01234567. References with a zero-extended literal or a logical shift must + differ from the expected words. +- The multiply-add dispatch uses, with n = lane + 32 * group: + - S0 = mul_u32_u24(n, 0x05f3d1) ^ 0xa5800000 + - S1 = mul_u32_u24(n, 0x0371) ^ 0x7f9abcde + - S2 = mul_u32_u24(n, 0x1001) + + Bit 23 is set in many factors and the bits above it are not zero. References with unsigned or unmasked factors + must differ. + +Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls compiled all +programs and printed `compiled six v_ashrrev_i64 sources and v_mad_i32_i24; the zero-extended-literal, logical, +unsigned and unmasked references each differ`. `native_shift64_controls` still passes. The readback printed `requires +shader model 6.6 with wave32` and reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug +layer unavailable). The readback is not measured. diff --git a/docs/experiments/native-direct-vopc-cmp64.md b/docs/experiments/native-direct-vopc-cmp64.md new file mode 100644 index 0000000000..c1cef41c4d --- /dev/null +++ b/docs/experiments/native-direct-vopc-cmp64.md @@ -0,0 +1 @@ +Direct C++ compute lowers signed and unsigned 64-bit integer VOPC comparisons to DXIL i64 predicates with the existing VCC, SGPR, and EXEC lane-mask writes. diff --git a/docs/experiments/native-dot2-f32-f16.md b/docs/experiments/native-dot2-f32-f16.md new file mode 100644 index 0000000000..da380d331c --- /dev/null +++ b/docs/experiments/native-dot2-f32-f16.md @@ -0,0 +1,38 @@ +# Direct DXIL `v_dot2_f32_f16` Translation + +Experiment for direct Compute and Pixel DXIL lowering of RDNA 2 VOP3P `v_dot2_f32_f16` (`0x13`), addressing `#3238` and `#2935`. + +## What Changed + +- Lowered `v_dot2_f32_f16` in `DirectCompute::float_alu()` inside [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl): + - Enforces the full RDNA 2 `MODE` contract (`((mode_bits ^ 0xf0u) & 0x8000ffu)` and `half_mode_known`, requiring RNE rounding and denormal preservation for both binary16 and binary32, plus `half_binary = true` in `DirectCompute::lower()`). + - Accepts `op_sel[1:0]` (`i.a >> 11`), `op_sel_hi[1:0]` (`i.b >> 27`), `neg_lo[2:0]` (`i.neg`: pair 0 binary16 signs + `src2` binary32 sign), `neg_hi[1:0]` (`i.abs`: pair 1 binary16 signs), and `clamp` (`dx.op.unary.f32` opcode `7`, saturate). Ignores unused `op_sel_hi[2]` (bit 14). + - Decodes `src0` and `src1` through `packed_f16_inline_constant()` (binary16 inline float constants `240..248` with zero high half, plus inline integers `128..208`) or `operand32()`, widens each selected half via `dx.op.legacyF16ToF32`, computes `((a0 * b0) + (a1 * b1)) + c`, and preserves binary32 subnormal accumulators `c` (`0 < |c| < 2^-126`) across desktop DXIL `fadd` / `saturate` when `(a0 * b0) + (a1 * b1) == +/-0.0` (every finite nonzero binary16 product sum has magnitude `>= 2^-48 >> 2^-126`). + - Refuses reserved `op_sel[2]` / `neg_hi[2]` bits (`i.a & 0x2400`), DPP/permuted encodings, special scalar registers on `src0`/`src1`/`src2`, and unsupported or dynamic rounding/denormal modes. +- Extended the Python DXIL IR evaluator in [tests/native_f16_alu_check.py](../../tests/native_f16_alu_check.py) to evaluate `dx.op.unary.f32(i32 7, ...)` (`Saturate`). +- Added compute/pixel test coverage in [tests/native_dot2_f32_f16_check.py](../../tests/native_dot2_f32_f16_check.py) (including `inline_int_src2_129` `0x00000001` plus VGPR-sourced binary32 subnormals `0x00000001` and `0x80400000` with and without `clamp=1`, and an `s_denorm_mode 0xC` binary32 flush refusal) and registered CTest targets in [tests/cmake/native_packed_dot2_f16.cmake](../../tests/cmake/native_packed_dot2_f16.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` and `release` (`/O2`) presets, DXC `10.0.26100.0`. + +- `cmake --build --preset dev` & `--preset release` (`compile_dxil`, `native_compute_ir_dump`, `native_store_replay`, `offscreen_check`): passed. +- `ctest --preset dev --no-tests=error --output-on-failure -j 1 -V -R '^native_(packed_dot2(_f16)?_.*|packed_f16_inline_(ir|controls|compute_hardware)|f16_alu_(ir|hardware))$'`: + - `native_packed_dot2_f16_ir`: **passed** (`30` cases matched exact binary32 model; `10` refusals matched). + - `native_packed_dot2_f16_controls`: **passed** (`30` cases compiled to DXIL; verified `10` refusals). + - `native_packed_dot2_f16_pixel_warp`: **passed** (`Microsoft Basic Render Driver` `10.0.26100.9711`, `7` quad draws matched, including `inline_int_src2_129` and all 4 VGPR subnormal cases). + - `native_packed_dot2_f16_pixel_hardware`: **passed** (`NVIDIA Quadro M1000M` `32.0.15.7371`, `7` quad draws matched; debug layer unavailable). + - `native_packed_dot2_f16_compute_hardware`: **skipped** (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111` requires SM 6.6 with wave32). + - Neighbor `native_packed_dot2_controls`, `native_packed_f16_inline_ir/controls`, and `native_f16_alu_ir` passed (`*_hardware` compute tests skipped `77` on HD 530). +- `ctest --preset release --no-tests=error --output-on-failure -j 1 -V -R '^native_(packed_dot2(_f16)?_.*|packed_f16_inline_(ir|controls|compute_hardware)|f16_alu_(ir|hardware))$'`: + - Same `8` IR/controls/pixel tests **passed** and `4` SM 6.6 wave32 compute tests skipped (`77`) on HD 530. +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **69/69 passed** (`0` failures, `0` skips). +- Sensitivity mutants in `src/gfx1013_direct_compute.inl`: + - `drop_subnormal_keep` (`keep_subnormal = "0"`): failed `native_packed_dot2_f16_pixel_warp` (`rc=8`, `00000001,00000001,80400000,00000001` vs `00000000,00000000,00000000,00000000`). + - `drop_hi_term`, `drop_neg_c`, `drop_clamp`, and `swap_opsel_hi`: failed `native_packed_dot2_f16_ir` (`rc=8`). +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- Direct Compute GPU execution (`native_packed_dot2_f16_compute_hardware`) could not run locally because `Intel(R) HD Graphics 530` lacks SM 6.6 wave32 (`77` skip). Compute IR evaluation, DXIL `controls`, and Pixel WARP + NVIDIA hardware draws (including binary32 subnormal retention on inline and VGPR `src2`) are verified. +- `signed_zero_keep`, `signed_zero_cancel_pos`, `inf_propagation`, `nan_propagation`, and `clamp_nan_to_zero` (`pixel_safe=False`) are verified in IR/controls/compute fixtures because `--startup-pixel-words` checks bitwise equality where drivers can vary on qNaN payload bits or pixel export `-0.0`. diff --git a/docs/experiments/native-dpp-quad-compute.md b/docs/experiments/native-dpp-quad-compute.md new file mode 100644 index 0000000000..dc160a80f9 --- /dev/null +++ b/docs/experiments/native-dpp-quad-compute.md @@ -0,0 +1,43 @@ +# DPP16 quad_perm in the direct C++ compute path + +Issue #2936 covers DPP16 control values 0–255 with full row and bank masks. +The decoder retains the reserved-bit check and decodes FI, BOUND_CTRL, abs and +neg. The compute emitter uses the destination lane's low two bits to select a +two-bit field in the control byte. It adds that field to the base of the +destination lane's quad and reads source 0 from that physical wave32 lane. +Quads fit within each physical half of a split guest wave64. + +Direct compute also lowers DPP8 selectors within each eight-lane group. FI reads the saved source VGPR and otherwise an inactive source supplies zero. + +Without FI, the guest EXEC bit of the selected source decides whether it can +be read. BOUND_CTRL supplies a zero source for a disabled lane. With +BOUND_CTRL clear, the instruction preserves the old destination. FI reads the +last VGPR value from a disabled source. Destination writes still obey EXEC. +The arithmetic and modifier checks are shared with the row mirror lowering. + +## Refused forms + +Compute requires a group size divisible by four for quad permutations. +Controls above 255 require a supported row mirror, shift or rotate. +[Row shift and rotate coverage](native-dpp-row.md) + +## Verification + +`native_dpp_quad_controls` checks compilation of a valid swap and named +refusals for row_share:0 and a 30-thread group. +`native_dpp_quad_hardware` compares both workgroups and buffer guards against +an independent CPU model. The fixtures cover integer OR and float add with +pairwise swaps, reverse subtraction with quad-local broadcast, identity, +rotation and the three disabled-source behaviors. The rotation exposes +reversed field order and the sparse EXEC add exposes ignored BOUND_CTRL. +Hardware without shader model 6.6 and wave32 support returns skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_dpp_quad_(controls|hardware)$' +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) both tests passed: all eight +hardware programs matched the CPU reference for both groups and the guard words. At the time of that run, +the controls refused `row_shl:1` and a 30-thread group. Reading the permutation in reversed lane order fails the first case, and +ignoring BOUND_CTRL fails the disabled-source zero case. diff --git a/docs/experiments/native-dpp-row.md b/docs/experiments/native-dpp-row.md new file mode 100644 index 0000000000..d77aabe241 --- /dev/null +++ b/docs/experiments/native-dpp-row.md @@ -0,0 +1,39 @@ +# DPP16 row shifts and rotates in direct C++ compute + +Issue #3008 adds `row_shl:N`, `row_shr:N` and `row_ror:N` for N from 1 to 15 +with full row and bank masks. A left shift reads from row lane r + N, a right +shift reads from r - N, and a rotate reads from (r - N) modulo 16. Each row +fits inside one physical wave32, including in a split guest wave64. + +The source is usable when it is in the row and either FI is set or its guest +EXEC bit is set. For an unusable source, BOUND_CTRL supplies a zero source +word. With BOUND_CTRL clear, the destination keeps its old value. Destination +writes continue to obey guest EXEC. Row shifts and rotates require a thread +count divisible by 16. `row_share`, `row_xmask`, the pre-GFX10 controls +(`0x130..0x13c`, `0x142`, `0x143`) and partial row or bank masks stay refused. + +`native_dpp_row_controls` checks a valid shift and four refusals covering +row_share:0, control 0x142, a partial row mask, and a 24-thread group. +`native_dpp_row_hardware` exercises sparse EXEC in two physical wave32s per +group. The reference checks all output words, including sentinel guards. +The fixtures cover moves with boundary shift and rotation amounts, integer +add with FI, and floating-point add and min with BOUND_CTRL. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_dpp_row_(controls|hardware)$' +``` + +On Windows 11 with an NVIDIA GeForce RTX 5080 and DXC from the Windows SDK +10.0.26100, on `cpp-migration` `999e17cd` plus this change, both checks passed: +16 GPU programs matched the CPU reference with all 2,064 output words, and the +four controls were refused. Three manual mutants each fail the hardware check: +rotating left instead of right (the shift 1 and 15 cases; `row_ror:8` is its +own inverse), treating an out-of-row source as usable, and ignoring BOUND_CTRL. + +On a local capture of 2,689 compute requests (counts and instruction shape +only), 80 requests stopped first at "unsupported DPP lane selection": 62 with +`row_ror:8` and BOUND_CTRL, 18 with `row_shr:1` and FI. With this change, the +compiled count goes from 392 to 393 on `999e17cd`, and none that compiled before +stops. Of the other 79, 32 now stop first at `v_permlane16_b32`/`v_permlanex16_b32` +and 25 at "SDWA or DPP vector operands". diff --git a/docs/experiments/native-dxil-llvm-ident.md b/docs/experiments/native-dxil-llvm-ident.md new file mode 100644 index 0000000000..9ea877b984 --- /dev/null +++ b/docs/experiments/native-dxil-llvm-ident.md @@ -0,0 +1,63 @@ +# Direct DXIL `!llvm.ident` metadata for AMD RDNA 4 pipeline creation (#2915) + +[The fixture](../../tests/native_dxil_llvm_ident_check.py) verifies that every direct DXIL emitter in +`src/dxil_module.h` (`DxilModule::finish_compute`, covering `cs`, `vs`, `gs`, and `ps`) and +`src/gfx1013_pixel.cpp` (`x2w::direct_gfx1013_constant_pixel`) emits `!llvm.ident = !{!}` (`!{!"x2w"}`), +and draws both direct pixel paths on WARP and hardware with negative controls. + +## Cause of the AMD `0xC0000005` PSO crash + +On `cpp-migration` (`40365770`..`ee76dfa8`), all direct-DXIL `_hardware` tests crashed with `0xC0000005` +inside `amdxc64.dll` during `CreateComputePipelineState` and `CreateGraphicsPipelineState` on an +AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`), even though `IDxcValidator::Validate` +accepted every container and both WARP and NVIDIA passed: + +- `native_scalar_lds_hardware` +- `native_adjacent_srv_hardware` +- `native_mtbuf_hardware` +- `native_indexed_atomic_hardware` +- `native_dpp_mirror_hardware` +- `native_graphics_wqm_hardware` +- `native_graphics_vertex_vcc_join_hardware` + +Comparing disassembled DXIL modules (`dxc.exe -dumpbin`) re-assembled through `IDxcAssembler::AssembleToContainer` +and `IDxcValidator::Validate` isolated the crash to a single missing named metadata entry: + +- Re-assembling DXC's `ps_6_6` output passed (`rc = 0`, `debug_errors=0 debug_warnings=0`). +- Re-assembling `DxilModule` output as-is crashed (`0xC0000005`), and bumping `!dx.valver` to `1.8` or `1.9` + alone still crashed (`0xC0000005`). +- Adding `!llvm.ident = !{!}` (`!{!"x2w"}`) alone made the identical `DxilModule` IR pass (`rc = 0`, + `debug_errors=0 debug_warnings=0`). + +`dxc.exe` always emits `!llvm.ident`; `IDxcValidator` treats it as optional, whereas `amdxc64.dll` queries +`llvm::Module::getNamedMetadata("llvm.ident")` and dereferences the returned `NamedMDNode*` (`[rcx + 0x40]`) +without a null check. + +## Verification and negative controls + +1. **`container` mode (`native_dxil_llvm_ident_controls`):** compiles source-built shaders across + `gfx1013-container-cs`, `gfx1013-container-vs`, `gfx1013-container-ps`, `gfx1013-container-rect` + (`vs`, `gs`, `ps`), and `gfx1013-direct-constant-ps`, checks `dxc.exe -dumpbin` for `!llvm.ident` + resolving to `!"x2w"`, and runs a negative control that strips `!llvm.ident`, re-assembles + validates + through `dxcompiler.dll` / `dxil.dll`, and verifies the `!llvm.ident` check rejects the stripped module. +2. **`draw` mode (`native_dxil_llvm_ident_warp`, `native_dxil_llvm_ident_hardware`):** pairs a direct-DXIL + fullscreen-triangle vertex shader (`gfx1013-container-vs`) with `gfx1013-direct-constant-ps` and + `gfx1013-container-ps` on an `8x2` float target, checks bit-exact RGBA readback and zero D3D12 debug-layer + errors/warnings, and requires mutated-channel negative controls on each path to fail readback. + +```powershell +cmake --build --preset release --target compile_dxil native_store_replay native_recording_check offscreen_check +ctest --preset release --no-tests=error -V -R "^native_dxil_llvm_ident_(controls|warp|hardware)$" +``` + +Verified on Windows 11 (`10.0.26100`), Release build, with the D3D12 debug layer enabled (`0` errors, `0` warnings) +across Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.9818`) and AMD Radeon RX 9070 XT (`1002:7550`, +driver `32.0.32029.2010`), alongside all seven direct-DXIL `_hardware` tests listed above. + +## Limits + +- The committed `draw` check does not execute the stripped negative-control container on a GPU adapter, because + triggering an access violation inside a user-mode driver is driver-version-dependent rather than a D3D12 + contract. +- The separate adapter-independent decoder refusal message in `native_wave_request_hardware` is tracked independently + on #2915. diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md new file mode 100644 index 0000000000..aa73960277 --- /dev/null +++ b/docs/experiments/native-fixed-mesh57.md @@ -0,0 +1,88 @@ +# Fixed mesh pipelines through device slot 57 + +The varying fixture sends two distinct values through PARAM12.xy to the pixel shader. With the six-attachment configuration the covered texel reads back as `0xffff00ff`. A mismatched fixed descriptor and a missing color attachment each preserve the clear color. Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_varying_(warp|hardware)$' -V` to reproduce. + +For an independently supplied raw pixel stage, `compile_dxil SDK CACHE gfx1013-raw-mesh-ps INPUT OUTPUT` reads a sibling `.pslayout` containing `meshps1 ENABLE ADDRESS WAVE_SIZE` as decimal integers. ENABLE and ADDRESS are the pixel input masks. WAVE_SIZE is 32 or 64. Append `guest_root` to load the corresponding serialized 1.1 root signature from the sibling `.root` file. A raw mesh producer using the same interface specifies `packed_parameters` in its `.mslayout`. Each PARAM occupies one signature register, following position at register zero. Channels with conflicting interpolation modes in one PARAM require a different layout. + +The source-built fixture creates a fixed pipeline with guest MS and PS instructions. The stand-in translates both to DXIL using its C++ shader library, creates a desktop mesh PSO and submits a guest command-list slot 61 indirect command. A GPU compute pass supplies the dispatch arguments. The tested interface uses an empty guest root, one to eight single-sample color attachments, explicit rasterizer, blend, depth and stencil state, and an MS with no resource bindings. The PS exports a constant to color target zero. + +From the x64 Windows build environment: + +```powershell +cmake --build --preset dev --target startup_indirect_draw_indexed +ctest --preset dev --no-tests=error --output-on-failure -R '^(native_fixed_mesh57(_mask|_mrt)?|startup_indirect_mesh_(request|cache))_(warp|hardware)$' +``` + +The three fixture variants use one color target, six color targets with depth/stencil, and the same six with a red-only target-zero write mask. The six-target formats are 29, 28, 28, 28, 34 and 28, with depth/stencil format 20. Back-face culling, counterclockwise front faces, greater-or-equal depth, depth writes and stencil replacement are enabled. The four-by-two GPU readback has a single covered texel at (2,0). It is white with all channels enabled or red with the narrower write mask. Depth/stencil at that texel changes from 0.25/3 to 0.5/7. The other color attachments retain their clear values. Changing a fixed descriptor word or removing a color attachment produces no color or depth/stencil change. + +The ten tests above passed on the working tree based on `671b9ac`, Windows build 26200, with the debug layer enabled on WARP and an NVIDIA GeForce RTX 4060 Laptop GPU (driver 32.0.16.1656). + +## Per-pixel texture selection + +The `native_fixed_mesh57_waterfall_{warp,hardware}` fixture draws a triangle covering eight pixels. The guest PS uses READFIRSTLANE, CMPX, an indexed descriptor load, IMAGE_SAMPLE and a WREXEC retry. Neighboring pixels select different Texture2D views. With a unit UV gradient the two views return red and green from mip 1. The `waterfall_fine` variant holds UV constant and both views return blue from mip 0. The shader computes quad derivatives before sampling the per-pixel texture. Both gradient cases passed on WARP and the RTX 4060 Laptop with the debug layer enabled. Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_(pixel_heap|waterfall(_fine)?)_(warp|hardware)$'` to reproduce. + +## Exact state records + +Set `X2W_SHADER_CACHE` to the request cache and `X2W_MESH57_CAPTURE_STATE=1` to retain the fixed creation state when a matching root consumes a mesh pipeline. A `req_.s57` file contains the little-endian 64-bit stage/root request key, three little-endian 32-bit lengths, and the corresponding byte spans for the normalized descriptor, register block A and register block B. For the base layout the stand-in clears the captured root and span pointer fields at DWORD-pair indices 0, 1, 3, 5 and 13. It preserves the lengths and other fields. The variant key extends the existing stage/root key with those three length-prefixed spans. Distinct fixed states can coexist for one stage pair. The fixture overwrites both blocks after creation and checks their archived bytes for accepted and refused variants. + +Native preparation reads a separately reviewed `.mesh57-state` profile from the cache. Its versioned Windows x64 header is defined by `Mesh57Profile` in `src/startup_stubs/mesh57_profile.h`. The header supplies the MS entry layout and desktop fixed-function state. The file ends with the normalized descriptor, register blocks, serialized root and both guest programs. The stand-in compares every byte before building a PSO. The fixture authors this profile from its own known inputs. A captured register block alone does not establish the desktop rasterizer state or MS entry layout. + +For the recognized 0x300-byte fixed layout, the variant key ignores relocation +of the two shader record blocks and retains their relative offsets. +`startup_indirect_mesh_create_result` checks two source-built relocated +descriptors, a changed metadata byte, a changed relative offset, and an +unrecognized extended layout whose section fields remain unchanged. + +The source-built `native_fixed_mesh57_constant_{warp,hardware}` tests exercise +one reviewed MS root-constant block with a deferred guest root. The version 3 +sidecar stores the physical SGPR, guest root index and DWORD count after the +pixel entry. Slot 61 packs all written words into desktop MS b0 after checking +the creation root and the compiler's binding metadata. Changing guest root 4 +(b5, space 2) changes the rendered green channel from 64 to 191 on the same +PSO. A missing word preserves the clear color. This profile supports one block +of up to eight words. + +Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_buffers_'` +for the version 4 fixed mesh raw SRV fixture. One slot 61 command reads root +table 0 at byte 2848, root table 1 at bytes 32 and 96, a root 3 byte buffer +at offset 4, and the root 4 constant. Each contributes distinct bits to an +exported value. The expected RGBA at (2,0) is (255,62,255,255). A four-byte +view for an eight-byte span, a readable CPU address outside a GPU allocation, +and a missing root 4 word each preserve the clear color. Static tables share +immutable descriptor pages with other recorded commands on the same desktop +allocator; its queue fences govern page reuse. + +The version 5 mesh profile enables one directly indexed R32_UINT buffer read +alongside the static bindings. The compiler supplies the root word and mask. +Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_uint_heap_'`. +The fixture uses two different first elements in one GPU buffer. Selectors +147 and 151 yield RGBA (64,62,64,64) and (191,62,191,191). Replacing view +147 with the second view yields the latter color; shortening the view to one +element yields (0,62,0,0) when reading element 1. A float SRV, absent slot +and out-of-range selector preserve the clear color. The guest source heap +and resource are released after recording and before submission. + +The version 6 mesh profile also binds pixel texture reads from the directly +indexed guest resource heap. An eight-DWORD descriptor load must select a +32-byte-aligned slot within a proven interval. At recording time, each slot +in that interval must contain a registered float or normalized texture SRV +of the expected dimension, or an explicit typed null. The private desktop +heap retains the selected views for the recording and reserves separate +slots for the mesh-stage buffer selector and static bindings. + +Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_pixel_heap_'`. +With the same mesh and pixel programs, changing root 4 selects guest slot 32 +or 36. The source-built test reads back red or green respectively. Both SRVs +expose mip 1 and both textures have a blue mip 0. A typed null reads as +transparent black. An unregistered slot or an array view in the Texture2D +interval preserves the opaque clear color. + +For offline fixed mesh pixel translation, `tools/startup/mesh57_pixel_entry.py` +takes a `req_.ps57`, its creation archive `req_.s57`, and a +reviewed `.mesh57-state`. It checks the two content keys and compares +all six input spans before printing the `meshps1` line for the offline +compiler. The enable mask, address mask and wave size come from the reviewed +pixel entry. A creation archive alone preserves the two register blocks but +does not assign hardware register meanings to their offsets. Reproduce the +source-built positive and altered-stage controls with +`ctest --preset dev --no-tests=error -R '^native_direct_mesh$'`. diff --git a/docs/experiments/native-fract-f16.md b/docs/experiments/native-fract-f16.md new file mode 100644 index 0000000000..0a59c712d8 --- /dev/null +++ b/docs/experiments/native-fract-f16.md @@ -0,0 +1,54 @@ +# Binary16 fractional part (`v_fract_f16`) in direct DXIL + +The native frontend lowers gfx1013 VOP1 (`0x5f`) and VOP3 (`0x1df`) +`v_fract_f16` in `DirectCompute::float_alu()` for both Compute and Pixel +shaders. + +## Semantics and supported forms + +For each active lane: + +- Finite binary16 inputs (decoded with `legacyF16ToF32`) compute + `x - floor(x)` in binary32, round to binary16 round-to-nearest-even via + `packed_half_rne()`, and clamp a result of `1.0` (`0x3c00`, produced by tiny + negative fractions such as `-2^-12` or `-2^-24`) strictly below `1.0` to + `0x3bff`, matching `min(x - floor(x), 0x3bff)`. Exact integers and `-0.0` + produce `+0.0` (`0x0000`), and positive binary16 subnormals are preserved. +- Non-finite inputs (`+Inf`, `-Inf`, and NaN) produce canonical quiet NaN + (`0x7e00`), or `+0.0` (`0x0000`) when `clamp=1`. Because finite outputs already + lie in `[+0.0, 1.0)`, `clamp=1` preserves finite results unchanged. +- Supported VOP3 modifiers are `abs[0]`, `neg[0]`, `clamp`, `op_sel[0]` + (VGPR high-half source read), and `op_sel[3]` (high-half destination write), + preserving the unwritten half of the destination VGPR under `EXEC` masking. +- Supported sources are VGPRs (`256..511`), numeric SGPRs (`0..105`), 32-bit + literals (`255`), inline binary16 float constants (`240..248`), and inline + integer words (`128..208`). + +## Refused encodings and mode gate + +The translator refuses `v_fract_f16` when any of the following hold: + +- Non-zero VOP3 output modifier (`omod != 0`). +- Unused VOP3 operand modifiers (`abs[2:1]`, `neg[2:1]`), unused `op_sel[2:1]`, + or non-zero `src1` / `src2` fields. +- High-half `op_sel[0]` on a non-VGPR source (`src0 < 256`). +- DPP16, SDWA, permuted/subword encodings, or special scalar sources such as + `vcc_lo` (`106`). +- Non-default binary16 rounding/denormal mode (`((mode_bits ^ 0xf0u) & 0x8000ccu) != 0`), + or an unknown/dynamic `MODE` state (for example a conditional `s_denorm_mode` + write). + +## Fixture coverage and reproduction + +[native_fract_f16_check.py](../../tests/native_fract_f16_check.py) checks +32 Compute cases (`<= 32` words/lane in the `native_store_replay` buffer), +10 refusal controls, and lossless 16-bit Pixel readback across 16 draws (31 +full-`EXEC` cases, padded to 32) on both WARP and D3D12 hardware: + +```powershell +cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check +ctest --test-dir out/build/dev --no-tests=error --output-on-failure -j 1 -R '^native_fract_f16_' -V +``` + +Compute replay requires shader model 6.6 with wave32; adapters without wave32 +report a skip (`77`) on `native_fract_f16_compute_hardware`. diff --git a/docs/experiments/native-fract-f32-bound.md b/docs/experiments/native-fract-f32-bound.md new file mode 100644 index 0000000000..e55f023cb9 --- /dev/null +++ b/docs/experiments/native-fract-f32-bound.md @@ -0,0 +1,46 @@ +# Direct binary32 fract upper bound + +The direct DXIL frontend accepted `v_fract_f32` but emitted only DXIL `Frc`. +For the synthetic inputs `0xb0800000` (-2^-30) and `0xb1800000` (-2^-28), +that returned `0x3f800000` (1.0) on the tested desktop adapter. The gfx1013 +instruction keeps its result strictly below one, returning `0x3f7fffff` for +these inputs. The Python translator already applies this bound; see the +[earlier fract experiments](../experiments.md), +[#267](https://github.com/R0Y00/Xbox2Windows/pull/267) and +[#2010](https://github.com/R0Y00/Xbox2Windows/pull/2010). This is the same +boundary in the newer direct DXIL path, rather than a change to those Python +lowerings. + +The direct frontend now caps a result at or above 1.0 with an ordered comparison. +A NaN fails that comparison and passes through. The cap precedes the output +scale and clamp: `mul:2` of these tiny negative inputs must yield `0x3fffffff`, +not 2.0. Changing the direct frontend also changes its generated cache revision. + +The fixture constructs eight inputs and four instruction forms per input: +VOP1, VOP3 with input negation, VOP3 with clamp, and VOP3 with `mul:2`. +Each lane of two wave32 groups writes all 32 results. The readback compares +2,048 output words and 16 guard words, accepting NaNs by class. The controls +compile and validate DXIL and reject reference mutations that omit the cap or +replace NaN with the finite cap. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -V -R '^native_fract_f32_(controls|hardware)$' +``` + +At parent revision `240e0fb9c460f24d51683abe2d4cce2800b136c1`, the hardware +fixture failed on 384 of 2,064 words. With the bound, all words matched. +The adapter was an NVIDIA GeForce RTX 4070 Ti SUPER, driver 32.0.15.7270, +on Windows 10 build 19045, with DXC 1.9.2609 and Agility SDK 1.620.2. +The ordinary Windows 10 fixture executable reported the shader-model capability +skip; the measured runs relinked the same fixture objects locally with the +Agility SDK version/path exports and placed its matching runtime beside them. +The D3D12 debug layer was not enabled for those compute readbacks. +The compile controls, `native_f16_alu_ir`, `native_frexp_f32_controls` and +`native_mad32_controls` all passed. No console hardware or full program run +is claimed by these fixture results. + +After rebasing onto `aeef65b2da356b15cf1a81c5d6a73bd6cee77bcd`, the two +targets rebuilt, the compile controls passed, and the Agility-linked hardware +fixture again matched all 2,064 words. The ordinary executable still reported +the capability skip. diff --git a/docs/experiments/native-frexp-f16.md b/docs/experiments/native-frexp-f16.md new file mode 100644 index 0000000000..ac3db3dc02 --- /dev/null +++ b/docs/experiments/native-frexp-f16.md @@ -0,0 +1,32 @@ +# Direct DXIL `v_frexp_mant_f16` and `v_frexp_exp_i16_f16` + +Lowers `v_frexp_mant_f16` (VOP1 `0x59` / VOP3A `0x1d9`) and +`v_frexp_exp_i16_f16` (VOP1 `0x5a` / VOP3A `0x1da`) in the native direct-DXIL +compute path (`src/gfx1013_direct_compute.inl`) via exact integer IEEE-754 +binary16 manipulation while preserving `D[31:16]`. + +## Scope + +- Covers ±0.0h, normals, smallest normal, largest and smallest subnormals, and + +Inf across VOP1 and VOP3A (`neg`, `abs`, and `clamp` on `v_frexp_mant_f16`), + verifying `D[31:16]` preservation on every output. +- An inline float source (`0.5` … `-4.0`, `1/(2pi)`; encodings 240–248) reads + the binary16 value of the constant, as `v_add_f16` does, not the low half of + its f32 pattern. `native_frexp_f16_ir` evaluates the emitted IR (no GPU, no + DXC) for all nine constants with both ops, three VOP3A forms with + `abs`/`neg`/`clamp` and one VGPR control: `v_frexp_mant_f16 v3, 1.0` must + give `0x3800` and `v_frexp_exp_i16_f16 v3, 1.0` must give `1`. +- Refuses unsupported modifiers (`clamp` on `v_frexp_exp_i16_f16`, `omod` on + `v_frexp_mant_f16`). +- Negative controls: flushing denormals, omitting `clamp`, and zeroing + `D[31:16]` each differ from the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay native_compute_ir_dump +ctest --preset dev --no-tests=error -R '^native_frexp_f16_' -V +``` diff --git a/docs/experiments/native-frexp-f32.md b/docs/experiments/native-frexp-f32.md new file mode 100644 index 0000000000..f1634a452d --- /dev/null +++ b/docs/experiments/native-frexp-f32.md @@ -0,0 +1,25 @@ +# Direct DXIL `v_frexp_exp_i32_f32` and `v_frexp_mant_f32` + +Lowers `v_frexp_exp_i32_f32` (VOP1 `0x3f` / VOP3A `0x1bf`) and +`v_frexp_mant_f32` (VOP1 `0x40` / VOP3A `0x1c0`) in the native direct-DXIL +compute path (`src/gfx1013_direct_compute.inl`) via exact 32-bit integer +IEEE-754 binary32 manipulation. + +## Scope + +- Covers ±0.0, normals, smallest normal, largest and smallest subnormals, and + +Inf across VOP1 and VOP3A (`neg`, `abs`, and `clamp` on `v_frexp_mant_f32`). +- Refuses unsupported modifiers (`clamp` on `v_frexp_exp_i32_f32`, `omod` on + `v_frexp_mant_f32`). +- Negative controls: flushing denormals and omitting `clamp` each differ from + the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_frexp_f32_' -V +``` diff --git a/docs/experiments/native-gather-lod.md b/docs/experiments/native-gather-lod.md new file mode 100644 index 0000000000..4b2354328c --- /dev/null +++ b/docs/experiments/native-gather-lod.md @@ -0,0 +1,31 @@ +# Explicit-LOD 2D gather in the direct DXIL frontend + +The direct C++ frontend lowers gfx1013 `image_gather4_l` for a fixed +table-bound 2D SRV. The instruction reads U, V and explicit LOD from three +contiguous VGPRs and returns the four taps of one component. The supported +constant sampler has normalized clamp addressing, zero minimum LOD, point +mip filtering and no mip bias. Unsupported image and sampler forms refuse. +The direct path (`image_io`) and the HLSL compute emitter (`image`) treat MIMG word 1 bits 29:26 as reserved; bit 25 is the top bit of the sampler index. + +The lowering follows the existing startup HLSL implementation. Clamp LOD +to the sampler's maximum, round with `floor(lod + 0.5)`, and cap the index +at the last visible mip. Both dimension queries and texel loads use +view-relative mip indices. The four loads use the lower-left, lower-right, +upper-right, upper-left order of the gather footprint. Nonfinite coordinates +or LOD produce zeroes in the active destination lanes. +[AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +[Microsoft Texture2D GetDimensions](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-texture2d-getdimensions) + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_gather_lod_' -V +``` + +The compile controls check for four texture loads and two dimension queries. +Source-built pixel and compute programs cover all four channels, both sides +of the half-mip threshold, sampler and view limits, clamped coordinates and +nonfinite operands. The readback covers a two-mip SRV starting at resource +mip 1 and a full view. Four compute lanes select different LODs in a single +dispatch. A shader forced to mip zero fails the higher-mip comparison. +Compute replay requires shader model 6.6 and wave32. Guest implicit mip +selection is tracked separately in #1802. diff --git a/docs/experiments/native-global-srv-heap-replay.md b/docs/experiments/native-global-srv-heap-replay.md new file mode 100644 index 0000000000..f267ca20ca --- /dev/null +++ b/docs/experiments/native-global-srv-heap-replay.md @@ -0,0 +1,160 @@ +# GPU-selected global SRV heap slots: capture and replay of view types + +Issue #2908, branch `cpp-migration`. Builds on the heap read in the direct C++ DXIL path from #2912 +(`ResourceDescriptorHeap[slot]` for a raw buffer read, `src/gfx1013_direct_compute.inl` `heap_resource`). + +## What changed + +- The direct compute translation takes a view contract for a GPU-selected heap slot (`x2w::HeapViewContract`: + `none`, `raw_buffer`, `other`). An SMEM descriptor load from the resource heap is refused unless the contract is + `raw_buffer`; without a contract the existing text stays: "direct resource-heap load requires the selected GPU slot and + its view type". A scalar buffer load from the heap base, a heap descriptor load with an immediate offset or a constant + index (both could address another slot than the captured selection), and a numeric use of a GPU-selected slot's + stride in the direct path are refused with their own texts. The contract is part of the frontend cache key when it is + not `none`. +- Byte-address rewrite (#3023): under `raw_buffer` the direct path tracks the rewrite of the loaded heap descriptor that + `byte_descriptor_field` already models for table descriptors (`s_bfe_u32 ... 0xe0010` stride, `s_max_u32 ... 1`, + `s_mul_i32` byte count, `s_and_b32 ... 0xc000ffff`, `s_and_b32 ... 0xcfffffff`, `s_or_b32 ... 0x30000000`, word 0 + copied). A raw load through the rewritten descriptor reads the same `ResourceDescriptorHeap[slot]` raw view. The words + must all come from one heap load (same pc). As a precaution, a backward branch whose loop contains that heap load + refuses the window, because the loop would run the load again for another selection. Loops elsewhere in the program + do not refuse it. The caller's contract: every slot the + program can select is a raw view of exactly `num_records * max(stride, 1)` bytes; the translator does not check that, + nor the swizzle bits or the other word 3 fields. Without the contract the first refusal stays as before. +- Modules that read `ResourceDescriptorHeap` now also set shader flag `0x40000000`, as DXC does for the HLSL reference. + Without it the validator refuses the module ("Flags must match usage. Validation failed."), measured by removing the + flag and running the hardware test. +- `src/startup_stubs/native_global_srv.h` writes and reads version 2 of the view metadata, which adds the buffer size: + + ``` + x2w-global-srv-views 2 + select + need + slot + ``` + +- `compile_dxil ... gfx1013-container-cs` reads an optional `req_.views` next to the `.cdx` (single file and + `--requests`). It decodes the file, refuses a selection whose slot holds another view type than `need`, refuses a `need` + other than `raw_buffer`, translates with the `raw_buffer` contract and prints `global_srv select= need=`. Every + refusal happens before the `.cso` is published. Without the file a heap-reading shader is refused as before. The + `.views` file is not part of the `.cdx`/`.root` content key: it describes one captured dispatch. + +## Meaning of "native recording" and "runtime path" here + +The issue's reproduction names `native_recording_check` and `native_dispatch_states_warp`, which test +`x2w_startup::NativeRecording` (descriptor-table pages) and `x2w_startup::NativeDispatchStates` (dispatch barriers). On +`cpp-migration` only tests use these classes. The D3D12 stand-in translates slot 67 requests natively since #2958 +(opt-in `X2W_NATIVE_SHADERS`) through `translate_compute` without a heap view contract, so a GPU-selected heap read is +still refused there; passing captured views into that path is follow-up work. The fixture's `record` +mode records the dispatch with both classes and applies the view guard before `Dispatch`; that is the native recording +path checked here, and its unchanged UAV sentinels are the "runtime path" sentinels of the issue. The startup runtime +itself is not covered. + +The slot is selected by GPU data. The `record` mode reads the selector back from its GPU buffer before recording the +dispatch (one copy to a readback buffer and one fence per recorded dispatch) and uses that value as the captured +selection, so the guard checks the slot the GPU input actually selects, before the shader runs. + +## Fixture + +The wave32 replay covers direct raw dword through dwordx4 loads with `off` and SGPR offsets, plus immediate, inline, and `offen` address cases. + +`tests/native_global_srv_heap_replay.cpp` with `tests/native_global_srv_heap_replay_check.py`. A source-built compute +container (two root inputs: a descriptor table in s[0:1], the descriptor heap in s[2:3]; instruction words assembled with +LLVM 15 `clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -show-encoding`) loads the selector from t0, loads +the descriptor of `ResourceDescriptorHeap[selector]`, reads 64 words through it and stores them to u0. Heap slots: 0 and +1 raw buffers with different data, 2 a Texture2D, 3 a typed buffer. u0 holds 72 words; the last 8 and, on a refused +selection, all 72 must keep the sentinel `0x69696969`. + +The check runs, in order: + +1. `compile_dxil --requests` on the request without `.views`: refused with the heap text, no `.cso`. +2. `record` for selections 0 and 1: fenced output equals the selected slot's data, sentinels intact, `.views` captured. + Selections 2 and 3: "global SRV slot 2 has view type texture, the shader needs raw_buffer" (and `typed_buffer` for 3) + before the dispatch, nothing dispatched, sentinels intact. +3. Discrimination control: `record --no-guard` on slot 0 expecting a refusal sees the changed sentinels (exit 3). A + texture slot is not dispatched without the guard: reading a texture descriptor as a raw buffer is undefined in D3D12. +4. `compile_dxil --requests` on each captured selection: 0 and 1 compile, 2 and 3 are refused with the slot/type text + and publish no `.cso`. +5. `replay` of the compiled `.cso` for 0 and 1 matches the CPU reference; the `.views` of 2 and 3 are refused before the + dispatch with sentinels intact. +6. Mutation control: replaying selection 0 against the slot 1 reference reports a mismatch. +7. Negative controls on both `compile_dxil` and `replay`: slot 0 rewritten to `texture`, no `need` line, no `select` + line, no line for the selected slot, `select 7`, and (replay) a missing `.views` file. Each gives an explicit + diagnostic, no `.cso`, and intact sentinels. +8. Shader shapes refused by `compile_dxil` even with valid metadata: a constant heap index, a heap descriptor load with + an immediate offset, a stride read used as a number (`unbound numeric SGPR s24`), and four byte-address rewrites the + raw slot view cannot stand for: a wrong stride mask (`unbound numeric SGPR s21`), word 0 from a second heap load + (`non-contiguous resource descriptor`), a store through the rewritten descriptor (`a GPU-selected heap slot is read + as a raw buffer SRV only`) and a never-taken backward branch to (or before) the heap load (`heap byte window loaded + inside a loop`). +9. The byte-address rewrite: a stride read that nothing uses compiles, a never-taken backward branch after the heap + load (the loop does not contain the load) compiles, and the program with the full rewrite is recorded + for selections 0 and 1 (output equals the slot's data), compiled by `compile_dxil --requests`, replayed with the + same result, and replaying selection 0 against the slot 1 reference reports a mismatch. + +Section 11 of the check (#3224) forms the heap descriptor address the way a waterfall loop over a lane-selected slot +does: `s_add_u32 s24, s2, s17`, `s_add_u32 s25, 0, src_scc`, `s_load_dwordx4 s[20:23], s[24:25], 0x0` instead of the +SGPR offset of the load. The compiler tracks SCC as the carry of that add and reads the pair as the same indexed heap +descriptor, under the same contract. Without `.views` it is refused with the heap text. The program is recorded, +compiled and replayed for selections 0 and 1 like PROGRAM, with the slot 1 mismatch control. The other operand order +with `s_addc_u32 s25, 0, 0` compiles. These stay refused: a constant offset (`unbound numeric SGPR s2`), `s_mov_b32 +s25, 0` or an `s_cmp` between the adds (`heap descriptor address high word is not the carry of its offset add`) and an +immediate offset on the load. `tests/native_heap_offset_add_check.py` compiles the same form from a slot 67 request with +both heap flags: it reaches the heap text like the SGPR-offset form, and the controls keep their refusals. + +## Result + +``` +cmake --preset dev +cmake --build --preset dev +ctest --preset dev --no-tests=error -R "^native_global_srv_heap_replay(_warp|_hardware)?$" -V +``` + +- `native_global_srv_heap_replay_hardware`: passed, 70 assertions (NVIDIA GeForce RTX 3080, driver 32.0.16.2124, + Windows 11 build 26200, MSVC toolset 14.51.36231, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled). +- `native_global_srv_heap_replay_warp`: skipped (77), "adapter has no 32-lane waves (4..4)". The native module declares + `WaveSize=32`; WARP offers 4-lane waves only. The skip is not evidence for the fixture. +- `ctest --preset dev --no-tests=error -R ^native_ -j 1`: same result as before the change apart from the two new tests + (one known failure, `native_wave_request_hardware`, #2915, addressed by #2928). +- Revert control: with the heap refusal restored for every contract, `record` for selection 0 exits 4 with "direct + resource-heap load requires the selected GPU slot and its view type". +- Byte-address rewrite (#3023): `native_global_srv_heap_replay_hardware` passed, 83 assertions, on the same machine and + driver. The check run against `compile_dxil` and the fixture built at `999e17cd` (before the change) fails at + `stride_read` (old text "a GPU-selected heap slot stride read is not translated with a view contract") and, with the + shapes skipped, at "an unused stride read compiles" (the run stops there, so the full-rewrite record step was not + reached on that build). `ctest --preset dev --no-tests=error -R + "native_|startup_compute_dispatch|compute_heap" -j 6`: 147 tests, 142 passed, 4 skipped (77, WARP), 1 failed + (`native_cvt_pk_u8_hardware`, failing before the change as well). `compile_dxil --refusals` on a local start-up + capture gives the same output as before (it translates without a contract). +- Loop guard narrowed: the first version of the guard refused the window for any backward branch in the program. + With the contract forced locally (an uncommitted switch), it refused 921 of the 2,689 requests of the same capture. + With the guard limited to loops around the heap load, none of these is refused for a loop; 906 then stop at a typed + load (`buffer_load_format_*`) through the heap descriptor. After the change, the test passes with 84 assertions. The + run against the earlier commit `7582c01d` fails at the `window_loop` shape (old text "heap byte window in a program + with a backward branch"). The run stops there. +- Added heap address (#3224), dev build on `main` `8007a539` plus the change, NVIDIA GeForce RTX 4090 (driver + 32.0.16.1088), Windows 11 build 26300, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled: + `native_global_srv_heap_replay_hardware` passed, 118 assertions. `native_heap_offset_add` passed, 5 of 5. `_warp` + skipped (77) as above. + - With the compiler sources of `8007a539` (before the change), the replay fails at the first section 11 assertion + (`unbound numeric SGPR s2`) and `native_heap_offset_add` fails 3 of 5 (`unbound numeric SGPR s5`). + - With the high-word check removed, both tests fail at the `mov_high` controls. + - `ctest --preset dev --no-tests=error -R "native_|startup_compute|compile_dxil" -j 8`: 415 tests, 404 passed and + 11 skipped (77, WARP). + +## Limits + +- Only raw buffer heap reads are translated; other view classes are refused with a named diagnostic. +- The selected slot's index is per-lane VGPR data in general; reads stay inside the raw buffer view, which returns 0 + out of bounds. No static index bound is checked. +- Replay regenerates the slot contents deterministically from the slot index; `.views` captures type, stride and size, + not contents. +- In the direct DXIL path a GPU-selected slot's stride is never a number: it is tracked symbolically and only the + byte-address rewrite consumes it. The fixture's descriptor words are never evaluated, so a stride above 1 and the + size rule of the contract are not exercised. The HLSL path's `heap_stride_srv` (`src/gfx1013_compute_native.cpp`, + used by `tests/native_compute_grid.cpp`) is unchanged. +- Typed loads (`buffer_load_format_*`) through a heap descriptor and scalar loads through the rewritten descriptor stay + refused. The startup runtime + does not pass a contract yet, so none of this reaches a title run (#3023). +- The captured `select` must be the slot index the dispatch addresses; producing it from a title capture is outside this + fixture. diff --git a/docs/experiments/native-graphics-wqm-cross-quad.md b/docs/experiments/native-graphics-wqm-cross-quad.md new file mode 100644 index 0000000000..74d4946d39 --- /dev/null +++ b/docs/experiments/native-graphics-wqm-cross-quad.md @@ -0,0 +1,110 @@ +# Cross-quad WQM/EXECZ in a native pixel draw (#2907) + +[The fixture](../../tests/native_graphics_wqm_check.py) draws source-built gfx1013 pixel stages through the +direct DXIL frontend. In each one, an `s_cbranch_execz` under WQM decides a scalar that every surviving pixel +exports. The branch is skipped only when EXEC is zero in the whole guest wave. A quad with no EXEC bit at the +branch therefore still sees whether another quad of its wave kept the wave from skipping. + +## The accepted form + +``` +s_mov sE, exec ; s_wqm exec, exec +v_cmp_* vcc, ... ; s_andn2 sE, sE, vcc one or more coverage filters +v_cmp_* vcc, ... ; s_andn2 sM, sE|exec, vcc the branch mask, from the survivors or the whole-quad EXEC +v_cmp_* vcc, ... ; s_andn2 sM, sM, vcc optional further terms +s_wqm exec, sM ; s_cbranch_execz J the region writes only scalars +J: s_mov exec, sE then a terminal colour export +``` + +Following the maintainers' decision on the issue, the branch condition is `WaveActiveAnyTrue` of the +quad-complete EXEC bit: +- the modelled mask predicate is OR-ed with its `QuadReadAcrossX`, `QuadReadAcrossY` and + `QuadReadAcrossDiagonal`; +- quad reads see helper lanes, so a quad whose EXEC bits sit only on helpers or on covered pixels that did + not survive still votes, as it does on the guest; +- all of this uses Shader Model 6.0 operations, with no `[WaveOpsIncludeHelperLanes]`. + +The calls are emitted before the first conditional branch, where the whole quad still runs. The IR test checks +this, and checks that their declarations carry the attributes DXC gives the HLSL intrinsics. + +These still keep a refusal by name: +- inside the region: a vector or DPP instruction, an EXEC or VCC read, a hardware register access + (`s_setreg`/`s_getreg`), a branch, or an EXEC write other than the restore; +- a restore that is not the branch target; +- a second branch; +- anything after the restore other than lane-local ALU and colour exports. + +`raster_program(2.5, cross=True)` keeps its existing refusal. + +## Contract and what this shows + +The lowering decides the branch once per **desktop** wave. It relies on the packing contract of #2835 and +#2854: a correct program cannot depend on which quads the console puts in one wave. A program can only see the +branch outcome through an effect outside EXEC, here an SGPR. This fixture builds such a dependency on purpose, +so its reference comes from the measured desktop layout. + +**The draws show that the lowering votes over the desktop wave. They do not show equivalence with the console +for an output that depends on another quad.** + +## Measured layout + +Two HLSL pixel stages on the same draw report, for every covered pixel: +- its wave: the smallest covered id in it; +- the ids of its three quad peers; +- whether each peer is a helper (`IsHelperLane`, SM 6.6). + +Wave operations leave helpers out, so the helper flags come from quad reads. The fixture checks that every +desktop quad is the aligned 2x2 block, and that all covered lanes of a quad report the same quad. Quads are +per primitive. On WARP the two middle quads of the 8x2 target are each shaded twice, once with each row covered +and the other row as helpers, as if the full-screen triangle were drawn as two primitives. The layout is +measured in separate draws with the same vertex stage and target. The reference follows the measured quads. + +| Adapter | Lanes | Full draw | Diagonal draw | +|---|---|---|---| +| NVIDIA GeForce RTX 3070, driver 32.0.16.2101 | 32 | 4 quads in 1 wave, no helpers | 3 quads in 1 wave, 3 helpers | +| Microsoft Basic Render Driver, 10.0.26100.9818 | 4 | 6 quads in 6 waves, 8 helpers | 5 quads in 5 waves, 11 helpers | + +## Cases and controls + +| Draw | Mask | Shows | +|---|---|---| +| full | survivors with x <= 1 (14 survivors) | another quad's survivors keep the wave from skipping | +| full | survivors with x <= 4.5 (all 16) | as above, one quad without bits | +| full | x <= -1 | empty wave: the branch is taken, every vote agrees | +| full | whole-quad EXEC with x >= 4.5, survivors x <= 3.5 | bits only on covered pixels that did not survive | +| full | survivors with x >= 4.5 | no bits: WQM never makes a zero mask non-zero | +| diagonal | whole-quad EXEC, x >= 5, y >= 1 | the bit only on the diagonal helper of (4,0) | +| diagonal | whole-quad EXEC, x >= 5, y <= 1 | the bit only on the horizontal helper | +| diagonal | whole-quad EXEC, x = 4..5, y >= 1 | the bit only on the vertical helper | + +Each case is drawn against the measured-layout reference. Each control redraws the same program against a +different reference and must differ: +- a quad-local vote; +- a wave vote without the quad OR; +- a vote over surviving pixels only. + +Pixels outside exact coverage keep the clear value -1.0. + +## Command and result + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check native_store_replay native_pixel_ir_dump +ctest --preset dev --no-tests=error -V -R '^native_graphics_wqm_(hardware|warp|ir)$' +``` + +See the pull request for the measured counts. +- **On the RTX 3070** every control differs. +- **On WARP** (one quad per wave), the quad-local control cannot differ, and the test prints + `SKIPPED cross-quad quad-local control`. The three helper cases still differ from the no-OR and survivor + votes, at pixel (4,0). +- On a physical adapter with no wave holding two quads, the hardware entry exits 77 after the other checks. + +## Limits + +- **Helper lanes after the vote:** wave intrinsics are undefined on helper lanes, so the branch may diverge for + them. That is safe only while nothing after the branch reads another lane. +- **Adapters:** a 64-lane adapter has not been run. The RX 9070 XT is blocked by #2915. AMD and Intel have + not been run. +- **Programs:** only the form above is accepted. Real programs and captures have not been run. +- **Clipping:** a console that clips or splits primitives differently from the desktop forms different quads. + This holds for the existing quad-local path too. diff --git a/docs/experiments/native-image-atomics.md b/docs/experiments/native-image-atomics.md new file mode 100644 index 0000000000..0ded7913e9 --- /dev/null +++ b/docs/experiments/native-image-atomics.md @@ -0,0 +1,69 @@ +# Direct Compute atomics on unsigned 2D textures + +The native Compute compiler lowers `image_atomic_add`, `image_atomic_umax`, +`image_atomic_cmpswap`, `image_atomic_swap`, `image_atomic_umin`, +`image_atomic_and`, `image_atomic_or` and `image_atomic_xor` on a fixed table +descriptor for a 2D `R32_UINT` UAV. Swap, umin, and, or and xor use DXIL +`AtomicBinOp` Exchange (8), UMin (6), And (1), Or (2) and Xor (3). Signed +`image_atomic_smin` and `_smax` are outside the verified scope and stay +refused, as do `sub`, `inc`, `dec` and the float atomics. + +DXIL uses `RWTexture2D` with two integer coordinates and honours the +guest EXEC mask. GLC writes the pre-operation value to the data VGPR. +Compare-and-swap takes replacement from the first data VGPR and comparison +from the next one. Atomic writes are included when translating memory waits +and barriers. + +Other dimensions, packed addresses, non-sequential coordinate lists, cache +modifiers, status returns, and noncanonical operand masks are refused. +Published compute manifests describe this binding as +`uav tex2d uint table channels 1`. The stand-in accepts +the manifest and checks the actual UAV format before recording a dispatch. +In-process binding for this type can follow the changes in #3049 and #3154. + +## Reproduction + +From an x64 Visual Studio Developer PowerShell with Python and DXC configured: + +```powershell +$env:XBOX2WINDOWS_ADAPTER = 'RTX 4070' +cmake --preset dev +cmake --build --preset dev --target compile_dxil offscreen_check startup_stream_consumer d3d12_xs_shim +ctest --preset dev --no-tests=error -j 1 -R '^native_image_atomic_' -V +``` + +The [synthetic fixture](../../tests/native_image_atomic_check.py) compares +336 words per case, including unchanged texels and mips. It exercises unsigned +max across the sign boundary, compare success and failure, and a contended +add with only 16 active lanes. Each returning operation also feeds its result +to a second atomic. Clearing only the first operation's GLC bit changes the +second readback and fails the comparison. + +The [binary-operation fixture](../../tests/native_image_atomic_binops_check.py) +reuses that program for swap, umin, and, or and xor. Its controls check each +`AtomicBinOp` code, the operand refusals and the refused opcodes. Its readback +compares the same 336 words for distinct and contended texels, with GLC on and +off and 16 active lanes. + +The runtime fixture publishes the native compiler's DXIL and manifest from a +source-built device slot 67 request. A dispatch through the stand-in matches +all 256 words, with the one target texel incremented by 32 across two groups. +The same program with a float UAV is refused and leaves all 1,024 halfwords +unchanged. On Windows 11 build `26300.10075` the synthetic and runtime fixtures +ran on the RTX 4070 with driver `32.0.16.2124`. The binary-operation fixture +passed on an NVIDIA GeForce RTX 5080 (Windows 11, driver `32.0.16.2101`). +Direct DXIL requires wave32. Local WARP exposes four +lanes, so the native execution test reports a capability skip there. + +## References + +- [AMD RDNA 2 ISA, §8.2](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + and [LLVM 21.1.0 GFX1030 MIMG](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#mimg) + document the encoding and operands. LLVM release commit + `3623fe661ae35c6c80ac221f14d85be76aa870f1` is Apache-2.0 WITH LLVM-exception. +- [DXIL AtomicBinOp and AtomicCompareExchange](https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#atomicbinop) + define the destination and coordinate contract. +- The public [shadPS4 compare-and-swap report](https://github.com/shadps4-emu/shadPS4/pull/4109) + was observed 2026-11-27 at merge `85476e55ea70201c470eb618193864844bead976` + under GPL-2.0. It documents capability. The implementation and fixtures + in this repository were developed independently. diff --git a/docs/experiments/native-image-cache-flags.md b/docs/experiments/native-image-cache-flags.md new file mode 100644 index 0000000000..009ee4c0d5 --- /dev/null +++ b/docs/experiments/native-image-cache-flags.md @@ -0,0 +1,36 @@ +# Direct DXIL Read-Only Image Cache Flags (`GLC` / `DLC`) + +Experiment for accepting MIMG cache-policy flags `GLC` (word 0 bit 13, `0x2000`) and `DLC` (word 0 bit 7, `0x0080`) on read-only image operations in `DirectCompute::image_io()`, addressing `#3242`, `#3224` (Rank 8), and `#2935`. + +## What Changed + +- Updated `DirectCompute::image_io()` in [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl) so `(i.a & (store ? 0x3e0c0u : 0x3c040u))` accepts `GLC` (`0x2000`) and `DLC` (`0x0080`) on read-only image instructions (`image_load`, `image_load_mip`, `image_sample*`, `image_gather4*`, `image_getlod`, `image_getresinfo`) while keeping refusals for: + - `image_store` with `GLC` or `DLC` (`0x3e0c0u`) + - `LWE` (`0x20000`), `TFE` (`0x10000`), `R128` (`0x8000`), and reserved word 0 bits (`0x4040`) + - word 1 reserved bits (`0x3c000000u`) +- Added [tests/native_image_cache_flags_check.py](../../tests/native_image_cache_flags_check.py) and registered CTest entries in [tests/cmake/native_image_cache_flags.cmake](../../tests/cmake/native_image_cache_flags.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` preset, DXC `10.0.26100.0`. + +- `cmake --build --preset dev --target compile_dxil offscreen_check native_compute_ir_dump`: passed. +- `ctest --preset dev --no-tests=error -R '^(native_image_cache_flags_|native_gather_|native_image_atomic_|native_sample_ssamp_)' -V`: + - `native_image_cache_flags_controls`: **passed** (`48` flagged DXIL modules matched plain `flags=0` baselines across Compute and Pixel stages and `GLC`/`DLC`/`SLC`/`GLC|DLC|SLC`; `16` refusals matched across Compute and Pixel). + - `native_image_cache_flags_ps_warp`: **passed** (`12` cached-flag `image_gather4_l` cases matched on Microsoft Basic Render Driver `10.0.26100.9711`). + - `native_image_cache_flags_ps_hardware`: **passed** (`12` cached-flag `image_gather4_l` cases matched on `NVIDIA Quadro M1000M` `32.0.15.7371`; debug layer unavailable). + - `native_image_cache_flags_cs_hardware`: **passed** (`12` cached-flag `image_gather4_l` cases matched on `NVIDIA Quadro M1000M` `32.0.15.7371`; debug layer unavailable). + - `native_image_cache_flags_cs_warp`: **skipped** (`77`, Microsoft Basic Render Driver has 4-lane waves and lacks SM 6.6 wave32). + - Neighbor suites (`native_gather_compare_warp`, `native_gather_lod_controls/ps_warp/ps_hardware/cs_hardware`, `native_image_atomic_controls/hardware`, `native_sample_ssamp_hardware`): passed (with SM 6.6 wave32 WARP tests skipping `77`; `native_image_atomic_runtime_hardware` failed on this dual-GPU host because `startup_stream_consumer` runs on adapter 0 `Intel(R) HD Graphics 530` which lacks SM 6.6 wave32). +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **67/67 passed** (`0` failures, `0` skips). +- Sensitivity mutants in `src/gfx1013_direct_compute.inl` tested against `native_image_cache_flags_controls`: + - `revert_ro_cache_flags` (`(i.a & 0x3e0c0u)`): failed (`rc=8`, rejected `image_load` with `GLC`). + - `drop_r128_refusal` (`(i.a & (store ? 0x3e0c0u : 0x34040u))`): failed (`rc=8`, accepted `sample_r128`). + - Clean tree restored, rebuilt, and `native_image_cache_flags_controls` passed (`48` modules, `16` refusals). +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- `native_image_cache_flags_cs_warp` skips (`77`) on WARP because WARP uses 4-lane waves. +- `GLC` and `DLC` remain refused on `image_store*` and explicit/policy-checked on `image_atomic_*` (`image_atomic()`). +- Local `offscreen_check` hardware runs reported `debug_layer=unavailable` on `NVIDIA Quadro M1000M`. diff --git a/docs/experiments/native-lane-access-compute.md b/docs/experiments/native-lane-access-compute.md new file mode 100644 index 0000000000..4e94a56507 --- /dev/null +++ b/docs/experiments/native-lane-access-compute.md @@ -0,0 +1,34 @@ +# Lane access in direct compute DXIL + +This experiment covers numeric SGPR spill and refill through VGPR lanes +(#2940). A lane selector is masked to the guest wave width. Split guest +wave64 reads exchange the values from the two physical wave32 halves. +Lane writes select a guest lane independently of EXEC. Scalar lane reads +can target `vcc_lo` and `vcc_hi` in direct compute. In wave32, `vcc_hi` +(SGPR 107) holds ordinary scalar data and VCC uses only `vcc_lo`. A +wave32 scalar pair read of VCC reads s106 and s107, as the hardware does. In +wave64, `vcc_hi` holds the high half of the VCC mask. Refills carry +numeric values and clear the destination's symbolic provenance. + +Direct compute `s_mov_b32 exec_hi` stores a readable high word in wave32 and updates the upper-half EXEC mask in split wave64. + +The source-built hardware fixture compares two 32-thread workgroups with +a CPU reference and checks the untouched buffer words. It covers constant +and SGPR selectors, writes to an EXEC-disabled lane, and lane reads feeding +VCC. It also reads back wave32 `vcc_hi` after both lane-read instructions +and a scalar move, and checks the high word of a pair move from VCC. +Compile controls exercise partial waves, out-of-range direct lane-read +destinations, and HLSL-native lane reads targeting either VCC register. +Graphics lane reads also reject both VCC destinations. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_lane_access_hardware$' +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) the test +matched all 768 lane-access words and the guards in both workgroups. Reading lane `lane ^ 1`, +letting `v_writelane_b32` honour EXEC, reading `vcc_hi` as zero in wave32, and reading the high word of a +wave32 VCC pair as zero each fail it. +The fixture is one 32-thread wave32 group per workgroup; the wave64 half selection and the +accepted partial-wave constant lane are not exercised. diff --git a/docs/experiments/native-lane-spill-descriptor.md b/docs/experiments/native-lane-spill-descriptor.md new file mode 100644 index 0000000000..b8688eca35 --- /dev/null +++ b/docs/experiments/native-lane-spill-descriptor.md @@ -0,0 +1,35 @@ +# Descriptor lane spills in direct compute DXIL + +The direct C++ path can carry an immediate table descriptor, a table +pointer word, a root address word or an unbound value through a constant +guest VGPR lane. An unbound value refilled is still unbound and is refused +where it is used. +The CFG tracks the identity per VGPR and guest lane. A symbolic spill or +refill emits no DXIL. A refilled descriptor still has to pass the usual +binding checks. A numeric write clears only its lane's identity. Any +other write to a VGPR holding symbolic lanes is refused. +Joins require the same identity on each path. If any path has a symbol +but the identity differs, the refill is refused. + +Numeric lane operations use the existing DXIL lowering. In a split +guest wave64, that lowering selects the physical lane and exchanges +values between the wave32 halves as needed. Symbolic slots use the guest +lane before the physical mapping. Indexed descriptors that carry a +runtime index remain outside this experiment. + +The source-built fixture spills four SRV descriptor words into lanes +0 through 3 and two numeric words into lanes 4 and 5, then clobbers the +descriptor SGPRs. It refills the six words and stores the loaded SRV +value and both numeric values for every lane. The CPU reference covers +192 written words across two wave32 workgroups and 1,872 guard and +unwritten words. Compile controls cover VGPR and SGPR lane selectors, +a VALU overwrite followed by descriptor refill, a conflicting CFG +join, and a direct VALU read of a VGPR with symbolic lanes. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_lane_spill_descriptor_(warp|hardware)$' +``` + +The fixture is registered for Microsoft WARP and the default hardware +adapter. It requires shader model 6.6 and wave32 support. diff --git a/docs/experiments/native-ldexp-f16.md b/docs/experiments/native-ldexp-f16.md new file mode 100644 index 0000000000..7d092b469d --- /dev/null +++ b/docs/experiments/native-ldexp-f16.md @@ -0,0 +1,26 @@ +# Direct DXIL `v_ldexp_f16` + +Lowers `v_ldexp_f16` (VOP2 `0x3b` / VOP3A `0x13b`) in the native direct-DXIL +compute path (`src/gfx1013_direct_compute.inl`) via exact 32-bit integer +IEEE-754 binary16 scaling while preserving `D[31:16]`. + +## Scope + +- Covers normal scaling, negative 16-bit signed exponents, denormal-to-normal + promotion, normal-to-subnormal underflow with round-to-nearest-even ties, + overflow to `±Inf`, VOP3A `abs`/`neg`/`clamp`, and `D[31:16]` preservation. +- Refuses unsupported modifiers (`omod`, `neg`/`abs` on the integer exponent + `src1`, `op_sel`, unused `src2`). +- Negative controls: flushing denormals, truncating subnormals instead of + round-to-nearest-even, omitting `clamp`, and zeroing `D[31:16]` each differ + from the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_ldexp_f16_' -V +``` diff --git a/docs/experiments/native-mad32-k.md b/docs/experiments/native-mad32-k.md new file mode 100644 index 0000000000..e6fde9205f --- /dev/null +++ b/docs/experiments/native-mad32-k.md @@ -0,0 +1,35 @@ +# Direct DXIL `v_madmk_f32` and `v_madak_f32` Translation + +Experiment for direct Compute and Pixel DXIL lowering of RDNA 2 unfused literal multiply-adds `v_madmk_f32` (`VOP2 0x20`: `S0 * K + S1`) and `v_madak_f32` (`VOP2 0x21`: `S0 * S1 + K`), addressing `#3249`, `#2935`, and `#3005`. + +## What Changed + +- Extended `unfused_mad` inside `DirectCompute::float_alu()` in [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl) to cover `v_madmk_f32` and `v_madak_f32`: + - Uses the existing `#3005` unfused sequence: flush denormal inputs to signed zero (`ftz`), round `fmul` separately without fast-math/FMA contraction, flush the product, add the flushed addend (`S1` for `v_madmk_f32`, trailing 32-bit literal `K` for `v_madak_f32`), and flush the sum. + - Refuses invalid non-VOP2 forms (`i.wide || i.subword || i.dpp_control || permuted`). +- Added [tests/native_mad32_k_check.py](../../tests/native_mad32_k_check.py) and registered CTest entries in [tests/cmake/native_mad32_k.cmake](../../tests/cmake/native_mad32_k.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` preset, DXC `10.0.26100.0`. + +- `cmake --build --preset dev --target compile_dxil native_compute_ir_dump native_store_replay offscreen_check`: passed. +- `ctest --preset dev --no-tests=error -R '^(native_mad32_k_|native_mad32_)' -V`: + - `native_mad32_k_ir`: **passed** (`14` cases matched unfused FTZ model; `4` refusals matched). + - `native_mad32_k_controls`: **passed** (`14` cases compiled with separate `fmul`/`fadd` and no `tertiary.f32(i32 46,)` or fast-math flags; `4` refusals matched). + - `native_mad32_k_pixel_warp`: **passed** (`Microsoft Basic Render Driver`, `3` quad draws matched). + - `native_mad32_k_pixel_hardware`: **passed** (`NVIDIA Quadro M1000M`, `3` quad draws matched; debug layer unavailable). + - `native_mad32_k_compute_hardware`: **skipped** (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111` requires SM 6.6 with wave32). + - Neighbor `native_mad32_controls` passed (`native_mad32_hardware` skipped `77` on HD 530). +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **68/68 passed** (`0` failures, `0` skips). +- Sensitivity mutants in `src/gfx1013_direct_compute.inl` tested against `native_mad32_k_ir`: + - `swap_madmk_madak` (`v_madak_f32` vs `v_madmk_f32` literal role): failed (`rc=8`). + - `drop_ftz_input` (`auto x = a;`): failed (`rc=8`, `madmk_ftz_src0`). + - `drop_vop3_refusal` (bypass `literal_k` non-VOP2 check): failed (`rc=8`, `unsupported v_madmk_f32 encoding`). + - Clean tree restored, rebuilt `native_compute_ir_dump`, and `native_mad32_k_ir` passed again. +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- Direct Compute GPU execution (`native_mad32_k_compute_hardware`) could not run locally because `Intel(R) HD Graphics 530` lacks SM 6.6 wave32 (`77` skip). Compute IR, DXIL `controls`, and Pixel WARP + NVIDIA hardware draws are verified. +- `madak_ftz_sum`, `madmk_zero_inf_nan`, and `madak_neg_zero` (`pixel_safe=False`) are verified in IR/controls/compute fixtures rather than `--startup-pixel-words` because WARP/GPU drivers can differ on raw `-0.0`/qNaN payload patterns on pixel export. diff --git a/docs/experiments/native-mul24.md b/docs/experiments/native-mul24.md new file mode 100644 index 0000000000..fffd1a6db4 --- /dev/null +++ b/docs/experiments/native-mul24.md @@ -0,0 +1,29 @@ +# 24-bit integer multiplies (`v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_hi_u32_u24`) in direct compute + +The native compute frontend translates both the VOP2 (`0x09`, `0x0a`, `0x0c`) +and VOP3A (`0x109`, `0x10a`, `0x10c`) encodings of `v_mul_i32_i24`, +`v_mul_hi_i32_i24`, and `v_mul_hi_u32_u24`. Each instruction reads only the +low 24 bits of `src0` and `src1` (sign-extended for `i24`, zero-extended for +`u24`). `v_mul_i32_i24` returns bits `[31:0]` of the product; the two `hi` +forms return bits `[63:32]` of the 48-bit product via an exact 12+12 split in +32-bit integer arithmetic. + +`clamp`, `omod`, `abs`, `neg`, `op_sel`, and nonzero unused `src2` on the +VOP3A encoding are refused. + +Section 12.7 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_mul24_' -V +``` + +The compile controls validate the generated DXIL and refuse five VOP3A +modifier/unused-source encodings (`clamp`, `op_sel`, `abs`, `neg`, nonzero +`src2`). Two source-built dispatches exercise eight input patterns across all +three opcodes, both VOP2 and VOP3A encodings, upper-byte noise, sign +combinations, and a sparse `EXEC` mask (2,048 result words and 16 guard words +per dispatch). The native replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-packed-dot2.md b/docs/experiments/native-packed-dot2.md new file mode 100644 index 0000000000..f44cfe8791 --- /dev/null +++ b/docs/experiments/native-packed-dot2.md @@ -0,0 +1,30 @@ +# Packed halfword dot products in direct compute + +The gfx1013 VOP3P instructions `v_dot2_i32_i16` and `v_dot2_u32_u16` +multiply corresponding halfwords and add both products to the 32-bit +accumulator. The opcode determines the signedness of the halfwords and +accumulator. The ordinary result wraps at 32 bits. The clamped form saturates +the exact final sum to the signed or unsigned destination range. +[AMD RDNA 2 ISA, section 12.10](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + +Each product fits in one word. The clamped lowering tracks the carries from +both additions and, for the signed instruction, the sign extensions of the +products and accumulator. This uses only 32-bit DXIL arithmetic. The upper +word determines whether the exact sum fits the destination range. Waiting +until the last addition matters when both signed products are `2^30` and +the accumulator is `-2^31`. The exact result is zero, but clamping the product +sum first would give -1. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_packed_dot2_' -V +``` + +The source-built fixture compares two dispatches with full and sparse EXEC +against a Python integer reference. It covers the signed cancellation, +signed overflow in both directions, unsigned double carry, exact bounds and +guard words. A third dispatch removes the clamp bits and checks the wrapping +readback. The compile controls reject five noncanonical selector or +negation encodings. The native replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-packed-dot4.md b/docs/experiments/native-packed-dot4.md new file mode 100644 index 0000000000..c6fcc228f2 --- /dev/null +++ b/docs/experiments/native-packed-dot4.md @@ -0,0 +1,60 @@ +# Packed byte dot products in direct compute + +The native compute frontend translates the gfx1013 VOP3P instructions +`v_dot4_i32_i8` and `v_dot4_u32_u8`. Each instruction multiplies corresponding +bytes in two packed words and adds their four products to a 32-bit accumulator. +The byte and accumulator signedness follows the opcode. Without `clamp`, the +result wraps modulo 2³². With `clamp`, the final sum saturates to the signed or +unsigned 32-bit range. + +The DXIL operation is `Dot4AddI8Packed` or `Dot4AddU8Packed`. The clamped path +uses a zero accumulator for the packed dot because the four products alone fit +in 32 bits. It then detects overflow on the addition of the guest accumulator. +The supported encoding uses the canonical VOP3P operand selectors and no +negation modifiers. + +Section 12.10 of the AMD guide defines the guest operands and accumulator. +The DXIL opcode definitions specify the corresponding packed operations. +[AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +[DXIL opcode definitions](https://github.com/microsoft/DirectXShaderCompiler/blob/main/include/dxc/DXIL/DxilConstants.h) + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_packed_dot4_' -V +``` + +The compile controls check the signed and unsigned DXIL instructions and +refuse noncanonical selectors and negation. Two source-built dispatches use +eight input patterns, both opcodes and both clamp modes. They exercise signed +overflow in both directions, unsigned carry, the exact saturation boundaries +and a sparse EXEC mask. A third dispatch drops all clamp bits and verifies +that the affected words change to the wrapping results. Each dispatch +compares 2,048 words and 16 guards. The native replay requires shader model +6.6 and wave32. + +## VOP2 dot-accumulate + +The frontend also translates the VOP2 form `v_dot4c_i32_i8`. It is the signed +byte dot, with the destination register as its accumulator: +`D = dot4(S0, S1) + D`, wrapping modulo 2^32. It uses `Dot4AddI8Packed`, the +same as `v_dot4_i32_i8`. S0 may be a VGPR, an SGPR, an inline constant or a +literal; S1 is a VGPR. + +Only the plain 32-bit VOP2 encoding is accepted. The VOP3 form and any abs, +neg, clamp or output modifier are refused with "unsupported packed byte +dot-accumulate operand modifiers". DPP16 is refused with "unsupported DPP +arithmetic", and SDWA with "unimplemented direct SDWA operand profile". + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_dot4c_(ir|hardware)$' -V +``` + +`native_dot4c_ir` checks the DXIL for literal, SGPR, inline and VGPR sources, +and the DPP16 and SDWA refusals. `native_dot4c_hardware` dispatches two 32-lane +groups for each case and compares every output word against expected values. +The cases include accumulators that cross the signed 32-bit boundary in both +directions and a sparse EXEC mask, +under which inactive lanes keep their old destination value. diff --git a/docs/experiments/native-packed-dot8.md b/docs/experiments/native-packed-dot8.md new file mode 100644 index 0000000000..58203a9f28 --- /dev/null +++ b/docs/experiments/native-packed-dot8.md @@ -0,0 +1,33 @@ +# Packed 4-bit nibble dot products in direct compute + +The native compute frontend translates the gfx1013 VOP3P instructions +`v_dot8_i32_i4` (`0x18`) and `v_dot8_u32_u4` (`0x19`). Each instruction +multiplies corresponding 4-bit nibbles in two packed 32-bit words and adds +their eight products to a 32-bit accumulator. The nibble and accumulator +signedness follows the opcode. Without `clamp`, the result wraps modulo 2^32. +With `clamp`, the final sum saturates to the signed or unsigned 32-bit range. + +Because eight 4-bit products sum to `[-448, 512]` (signed) or `[0, 1800]` +(unsigned), the dot product itself always fits in 32 bits; only the final +addition with the guest accumulator can overflow and saturate. The supported +encoding requires canonical VOP3P operand selectors (`OP_SEL = 0`, +`OP_SEL_HI = [1, 1, 1]`) and zero negation modifiers (`NEG_LO = 0`, +`NEG_HI = 0`). + +Section 12.10 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest operands and accumulator semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_packed_dot8_' -V +``` + +The compile controls validate the generated DXIL and refuse five noncanonical +selector and negation encodings. Two source-built dispatches exercise eight +input patterns, both opcodes, both clamp modes, signed overflow in both +directions, unsigned carry, exact saturation boundaries and a sparse `EXEC` +mask. A third dispatch drops all `clamp` bits and confirms that the affected +words change to the wrapping results. Each dispatch compares 2,048 words and +16 guard words. The native replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-packed-f16-inline.md b/docs/experiments/native-packed-f16-inline.md new file mode 100644 index 0000000000..436284b8de --- /dev/null +++ b/docs/experiments/native-packed-f16-inline.md @@ -0,0 +1,37 @@ +# Inline constants in direct packed binary16 arithmetic and min/max (#3226) + +`src/gfx1013_direct_compute.inl` now accepts inline constant sources in both `DirectCompute::packed_f16_alu()` +(`v_pk_add_f16`, `v_pk_mul_f16`, `v_pk_fma_f16`) and `DirectCompute::packed_minmax()` (`v_pk_min_f16`, `v_pk_max_f16`, +`v_pk_min_{i,u}16`, `v_pk_max_{i,u}16`): + +- **Shared `packed_f16_inline_constant()` contract:** + - Inline binary16 float constants (`240..248`: `0.5`, `-0.5`, `1.0`, `-1.0`, `2.0`, `-2.0`, `4.0`, `-4.0`, `1/(2*pi)`) + decode to the low 16 bits (`0x3800`, `0xb800`, `0x3c00`, `0xbc00`, `0x4000`, `0xc000`, `0x4400`, `0xc400`, `0x3118`) + with bits `[31:16]` zeroed, matching `gfx1013` hardware (`op_sel_hi = 1` reads `+0.0`). + - Inline integer constants (`128..208`: `0..64` and `-1..-16`) decode to full 32-bit sign-extended values (`0..64`, + `0xFFFFFFFF..0xFFFFFFF0`). + - Integer `v_pk_min_{i,u}16` / `v_pk_max_{i,u}16` accept `128..208` and continue refusing float `240..248`. +- **Kept refusals:** `vcc_lo`/`vcc_hi`, `m0`, `exec_lo`/`exec_hi`, `scc`, `clamp` on packed f16 arithmetic, reserved + VOP3P bits, and non-default FP16 MODE writes keep their existing named diagnostics. + +## Fixture + +[`tests/native_packed_f16_inline_check.py`](../../tests/native_packed_f16_inline_check.py) via +[`tests/cmake/native_packed_f16_inline.cmake`](../../tests/cmake/native_packed_f16_inline.cmake) +(`native_packed_f16_inline_ir`, `native_packed_f16_inline_controls`, `native_packed_f16_inline_compute_hardware`, +`native_packed_f16_inline_pixel_warp`, `native_packed_f16_inline_pixel_hardware`): + +- Covers 24 cases: all 9 inline f16 constants `240..248`, `op_sel_hi` high-half zeroing (`+0.0`), `neg_lo`/`neg_hi` + (including `-0.0`), single-rounding FMA tie witness with inline `0.5` (`240`) + `2^-24` (`129`), inline integer + constants (`128..208`), `v_pk_min_f16`/`v_pk_max_f16` (including `193` NaN selection), and `v_pk_min_u16`/`v_pk_max_i16`, + plus 10 refusals. + +Measured on 28.11.2026, `main` `c7215add` plus this change, Windows 10.0.26100 (`dev` preset): +- `native_packed_f16_inline_ir` (24 cases + 10 refusals, `0.68s`), `native_packed_f16_inline_controls` (24 compiled + 10 + refusals, `1.47s`), `native_packed_f16_inline_pixel_warp` (12 paired draws / 24 cases, `2.18s`), and + `native_packed_f16_inline_pixel_hardware` (`Intel(R) HD Graphics 530`, 12 paired draws / 24 cases, `5.20s`) passed. +- `native_packed_f16_inline_compute_hardware` skipped (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111`: requires shader + model 6.6 with wave32, so GPU compute readback is not measured). +- `^native_.*_(controls|ir)$`: 65/65 passed (`80.10s`). +- Four broken-lowering sensitivity checks (`replicate_high_half`, `use_f32_inline`, `zero_extend_neg_int`, + `drop_minmax_float_inline`) each failed `native_packed_f16_inline_ir` (exit `1`). diff --git a/docs/experiments/native-packed-f16.md b/docs/experiments/native-packed-f16.md new file mode 100644 index 0000000000..4d5be91013 --- /dev/null +++ b/docs/experiments/native-packed-f16.md @@ -0,0 +1,69 @@ +# Packed binary16 arithmetic in direct Pixel and Compute DXIL + +The direct compiler lowers the VOP3P `v_pk_add_f16`, `v_pk_mul_f16`, and +`v_pk_fma_f16` instructions. Each result half has independent source-half +selectors, input negation, and optional VOP3P `clamp` (`[+0.0, 1.0]` +saturation per half after rounding, mapping `-0.0` and `NaN` to `+0.0`). The +packed word uses the normal EXEC-masked destination write. The lowering accepts +numeric registers, literal words, inline integers, and inline binary16 float +constants. + +ADD and MUL widen the inputs, use binary32 arithmetic, then round to binary16 +with the existing integer nearest-even conversion. FMA forms the exact 22-bit +product and aligns the addend in integer arithmetic. Alignment keeps a sticky +bit for distant operands, where cancellation cannot reach the discarded bits. +The intermediate keeps 24 significant bits, with its last bit set to one when +discarded bits are nonzero. This round-to-odd step preserves which side of a +binary16 midpoint the exact sum fell on. The final nearest-even conversion +therefore agrees with a single binary16 rounding. + +The supported MODE preserves subnormals, rounds to nearest even, and leaves +`FP16_OVFL` clear. Unused third-operand modifier fields on `add`/`mul`, +unsupported source encodings, and undetermined or unsupported MODE keep +explicit refusals. NaN results without `clamp` use the canonical `0x7e00` half +from the project's arithmetic reference. NaN payload behavior has not been +measured on an RDNA2 device. + +In addition to [native_packed_f16_check.py](../../tests/native_packed_f16_check.py), +[native_packed_f16_clamp_check.py](../../tests/native_packed_f16_clamp_check.py) +verifies VOP3P `clamp` across `v_pk_add_f16`, `v_pk_mul_f16`, and +`v_pk_fma_f16` in IR, DXIL controls, and lossless Pixel readbacks (WARP and +hardware), plus Compute replay where SM 6.6 wave32 is supported. + +## Reproduction + +Run from an x64 Visual Studio Developer PowerShell with DXC and Python configured. + +```powershell +$env:XBOX2WINDOWS_ADAPTER = 'RTX 4070' +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_packed_f16_' -V +``` + +The [source-built fixture](../../tests/native_packed_f16_check.py) compares +both halves against the [exact rational model](../../tests/f16_packed_model.py). +Compute checks full and sparse EXEC readbacks, including inactive lanes and +buffer guards. Pixel checks the same FMA cases and alternates ADD and MUL in +the other two output channels. Two FMA cases distinguish one binary16 rounding +from a nearest-even binary32 intermediate. The first stores `0x3e053e01`, +where the double-rounded version would store `0x3e043e02`. The second stores +`0x6201be01` instead of `0x6202be02`. Compute replay requires wave32. + +On Windows 11 with SDK 10.0.26100 and DXC 1.9.2602.17, the RTX 4070 +(driver `32.0.16.2124`) matched all 2,064 Compute readback words in each of +the full and sparse dispatches. Pixel matched all ten cases on both the RTX +4070 and WARP (`10.0.26100.10068`). The local WARP adapter exposes four +lanes, so the wave32 Compute replay used the RTX 4070. + +## References + +- [AMD RDNA 2 ISA, section 12.10](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) + and [LLVM 21.1.0 GFX1030 assembly syntax](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#vop3p) + document the operand fields. The LLVM release is `3623fe661ae35c6c80ac221f14d85be76aa870f1`, Apache-2.0 WITH LLVM-exception. +- [Boldo and Melquiond, *Emulation of a FMA and Correctly Rounded Sums*](https://guillaume.melquiond.fr/doc/08-tc.pdf) + explains rounding to odd and the subsequent nearest-even conversion. +- [shadPS4 #4354](https://github.com/shadps4-emu/shadPS4/pull/4354) demonstrates + the corresponding translation scope. Observed 2026-11-27 at + `34b35b526e3bfbb8a6f22c11035cb051174ac6f1`, GPL-2.0. The code and + fixtures in this repository were developed independently. diff --git a/docs/experiments/native-packed-minmax.md b/docs/experiments/native-packed-minmax.md new file mode 100644 index 0000000000..45892d7e76 --- /dev/null +++ b/docs/experiments/native-packed-minmax.md @@ -0,0 +1,53 @@ +# Packed 16-bit min/max in direct DXIL + +The native frontend lowers the six gfx1013 VOP3P forms +`v_pk_min/max_{i16,u16,f16}` for both Compute and Pixel shaders. Each source +supplies one halfword to each result lane through `op_sel` and `op_sel_hi`. The +instruction writes one packed word and uses the existing vector write predicate. +It accepts numeric VGPRs and SGPRs, literal words and inline zero. It refuses +unused third-operand fields (`src2`, `op_sel[2]`, and third-operand +`neg_lo[2]`/`neg_hi[2]`). On the integer variants (`v_pk_min/max_{i16,u16}`), +`neg_lo`, `neg_hi` and `clamp` remain refused. + +Signed and unsigned integer lanes compare the selected 16-bit values. +Binary16 lanes (`v_pk_min_f16`, `v_pk_max_f16`) support `neg_lo[1:0]`, +`neg_hi[1:0]` and `clamp`: `neg_lo`/`neg_hi` flip the sign bit of the selected +low/high binary16 input half per operand before comparison, and `clamp` +saturates each resulting half to `[+0.0, 1.0]` with `NaN -> +0.0` after min/max +selection. Binary16 lanes compare the bit patterns using the startup HLSL +`minmax16_bits` contract. This preserves signed-zero ordering and +subnormal encodings and prefers the numeric operand over a NaN. Two NaNs +produce the repository's canonical quiet NaN, a payload convention that +still needs RDNA hardware evidence. A non-preserving or unproven binary16 +denormal mode is refused. + +The public shadPS4 packed-FP16 work helped identify this family as a +recompiler capability to check. The observation was made on 2026-11-27 +at its merged commit `34b35b526e3bfbb8a6f22c11035cb051174ac6f1` under +GPL-2.0. The DXIL lowering and fixtures were written in Xbox2Windows. +[shadPS4 PR #4354](https://github.com/shadps4-emu/shadPS4/pull/4354) +[Pinned shadPS4 commit](https://github.com/shadps4-emu/shadPS4/commit/34b35b526e3bfbb8a6f22c11035cb051174ac6f1) + +Instruction forms and half selectors follow AMD's public ISA and LLVM +21.1.0 syntax documentation. The LLVM revision observed on 2026-11-27 +was `3623fe661ae35c6c80ac221f14d85be76aa870f1` (Apache-2.0 with the +LLVM exception). The existing HLSL path provides the Xbox2Windows +reference for the selected halves and floating-point edge behavior. +[AMD RDNA 2 ISA, §12.10](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +[LLVM 21.1.0 GFX1030 syntax](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#vop3p) +[LLVM licence](https://github.com/llvm/llvm-project/blob/3623fe661ae35c6c80ac221f14d85be76aa870f1/llvm/LICENSE.TXT) + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_packed_minmax_' -V +``` + +The synthetic Compute replays compare 2,064 words per type, including the +untouched words and guards, plus 9 packed modifier cases (`MOD_CASES` for +`neg_lo`, `neg_hi`, and `clamp` across both `v_pk_min_f16` and `v_pk_max_f16`) +when validating `f16`. A sparse EXEC replay checks that inactive lanes keep +their previous word. Swapping the low and high selector groups changes the +binary16 readback. The Pixel fixture exports each resulting halfword as an +exactly representable binary32 integer and checks both results across 4 integer +cases per integer type and 13 `f16` cases (4 base cases plus 9 modifier cases). +Compute replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-permlane.md b/docs/experiments/native-permlane.md new file mode 100644 index 0000000000..eb4478711f --- /dev/null +++ b/docs/experiments/native-permlane.md @@ -0,0 +1,45 @@ +# Permlane16 and permlanex16 in direct C++ compute + +Issue #3021 lowers `v_permlane16_b32` (VOP3A opcode 0x377) and +`v_permlanex16_b32` (0x378). S0 and the destination are VGPRs. The uniform +selectors are SGPRs, inline constants, or a trailing 32-bit literal. S1 and +S2 can each reference the same literal word. Selectors refuse `vcc_lo` and, +on the wave64 path, `vcc_hi`. In wave32, `vcc_hi` is ordinary scalar data. + +S1 packs the selectors for row lanes 0 through 7 and S2 for lanes 8 through +15. Each lane extracts its four-bit selector at runtime. Permlane16 reads the +selected lane in its own row and permlanex16 reads from the paired row in the +same physical wave32. Guest wave64 uses two physical wave32s, with s126 and +s127 supplying guest EXEC for the lower and upper halves respectively. + +VOP3A op_sel bits 0 and 1 encode FI and BOUND_CTRL. By analogy with DPP, FI +allows reading a source whose guest EXEC bit is clear. Without FI, an +inactive source supplies zero with BOUND_CTRL or preserves the destination +otherwise. Destination writes obey guest EXEC. Other modifier bits and +nonuniform selectors are refused. Thread counts must be divisible by 16 for +permlane16 and by 32 for permlanex16. + +`native_permlane_controls` covers the literal form, six refusals, and +compilation of a split-wave64 container with distinct EXEC halves. +`native_permlane_hardware` uses sparse guest EXEC in 64-thread wave32 groups. +It compares lane-dependent selectors, including a shared literal in S1 and +S2, and inline zero against a CPU reference, including every sentinel word +outside the two groups' stores. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_permlane_(controls|hardware)$' +``` + +On Windows 11 with an NVIDIA GeForce RTX 5080 and DXC from the Windows SDK 10.0.26100, on `main` (`6057071b`) +plus this branch, `native_permlane_controls` and `native_permlane_hardware` passed. The six original readbacks matched a +CPU reference in all 2,064 words. Three manual mutants each fail the hardware check: reading the same row for +`x16`, swapping S1 and S2, and ignoring BOUND_CTRL. The inactive-source rule is assumed from DPP; the readback +checks the lowering against that model, not RDNA2 itself. On `main`, the wave64 branch of `lower_permlane` +is compiled by the container control. Slot 67 requests use the wave32 model until #3006 lands, so readback +exercises wave32 only. + +On `cpp-migration` (`999e17cd`) plus #3010, a local capture of 2,689 compute requests (counts and instruction +shape only) had 47 requests stop first at one of the two ops. With this change, 34 of them compile and none that compiled before stops: 393 to 427 +compiled. The other 13 stop later, 7 of them at "direct scalar move destination". All 47 have the wave32 bit of +#2999 clear; without #3006 they still compile on the wave32 model. diff --git a/docs/experiments/native-pk-add-sub-16.md b/docs/experiments/native-pk-add-sub-16.md new file mode 100644 index 0000000000..ae055a07e1 --- /dev/null +++ b/docs/experiments/native-pk-add-sub-16.md @@ -0,0 +1,30 @@ +# Packed 16-bit integer add/sub in direct compute + +The native compute frontend translates the gfx1013 VOP3P instructions +`v_pk_add_i16` (`0x02`), `v_pk_sub_i16` (`0x03`), `v_pk_add_u16` (`0x0a`), +and `v_pk_sub_u16` (`0x0b`). Each instruction adds or subtracts two +independent 16-bit lanes selected by `op_sel[1:0]` (low output half) and +`op_sel_hi[1:0]` (high output half). + +Without `clamp`, each lane wraps modulo 2^16. With `clamp`, signed forms +saturate each lane to `[-32768, 32767]` and unsigned forms saturate each lane +to `[0, 65535]`. `neg_lo`, `neg_hi`, `op_sel[2]` and nonzero `src2` are +refused; `op_sel_hi[2]` (bit 14, LLVM's default on 2-source VOP3P) is ignored. + +Section 12.10 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_pk_add_sub_16_' -V +``` + +The compile controls validate the generated DXIL and refuse four noncanonical +modifier and reserved-bit encodings (`op_sel[2]`, `neg_hi`, `neg_lo`, nonzero +`src2`). Three source-built dispatches exercise eight input patterns across all +four opcodes, default and swizzled/broadcast `op_sel`/`op_sel_hi` modes, signed +and unsigned saturation in both directions, a sparse `EXEC` mask, and a +no-clamp negative control (2,048 result words and 16 guard words per dispatch). +The native replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-pk-mul-mad-16.md b/docs/experiments/native-pk-mul-mad-16.md new file mode 100644 index 0000000000..50481f00e8 --- /dev/null +++ b/docs/experiments/native-pk-mul-mad-16.md @@ -0,0 +1,32 @@ +# Packed 16-bit integer multiply and multiply-add in direct compute + +The native compute frontend translates the gfx1013 VOP3P instructions +`v_pk_mul_lo_u16` (`0x01`), `v_pk_mad_u16` (`0x09`), and `v_pk_mad_i16` +(`0x00`). Each instruction operates on two independent 16-bit lanes selected +by `op_sel` (low output half) and `op_sel_hi` (high output half). + +`v_pk_mul_lo_u16` wraps each 16-bit product modulo 2^16 and refuses `clamp`, +`op_sel[2]`, and nonzero `src2` (ignoring LLVM's default 2-source +`op_sel_hi[2]` bit 14). `v_pk_mad_u16` and `v_pk_mad_i16` wrap modulo 2^16 +when unclamped, or saturate each lane to `[0, 65535]` / `[-32768, 32767]` when +`clamp` is set (32-bit intermediates never overflow). `neg_lo` and `neg_hi` +are refused on all three opcodes. + +Section 12.10 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_pk_mul_mad_16_' -V +``` + +The compile controls validate the generated DXIL and refuse five noncanonical +modifier and reserved-bit encodings (`clamp`, `op_sel[2]`, and nonzero `src2` +on `v_pk_mul_lo_u16`; `neg_hi` and `neg_lo` on `v_pk_mad_i16`). Three +source-built dispatches exercise eight input patterns across all three opcodes, +2-source and 3-source `op_sel`/`op_sel_hi` swizzles, signed and unsigned +saturation, a sparse `EXEC` mask, and a no-clamp negative control (2,048 result +words and 16 guard words per dispatch). The native replay requires shader model +6.6 and wave32. diff --git a/docs/experiments/native-pk-shift16.md b/docs/experiments/native-pk-shift16.md new file mode 100644 index 0000000000..883aabddff --- /dev/null +++ b/docs/experiments/native-pk-shift16.md @@ -0,0 +1,33 @@ +# Packed 16-bit integer shifts in direct compute + +The native compute frontend translates the gfx1013 VOP3P instructions +`v_pk_lshlrev_b16` (`0x04`), `v_pk_lshrrev_b16` (`0x05`), and +`v_pk_ashrrev_i16` (`0x06`). Each instruction shifts two independent 16-bit +lanes of `src1` by the low 4 bits (`& 15`) of the corresponding 16-bit lanes +of `src0`, selected by `op_sel[1:0]` (low output half) and `op_sel_hi[1:0]` +(high output half). + +`v_pk_lshlrev_b16` masks each shifted lane to 16 bits so bits shifted above +bit 15 do not bleed into the high half. `v_pk_ashrrev_i16` places each +selected 16-bit half in bits `[31:16]` and performs a signed arithmetic right +shift by `16 + (amt & 15)` (always in `[16, 31]`). `clamp`, `neg_lo`, +`neg_hi`, `op_sel[2]` and nonzero `src2` are refused; `op_sel_hi[2]` (bit 14, +LLVM's default on 2-source VOP3P) is ignored. + +Section 12.10 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_pk_shift16_' -V +``` + +The compile controls validate the generated DXIL and refuse five noncanonical +modifier and reserved-bit encodings (`clamp`, `op_sel[2]`, `neg_hi`, `neg_lo`, +nonzero `src2`). Two source-built dispatches exercise eight input patterns across +all three opcodes, default and swizzled/broadcast `op_sel`/`op_sel_hi` modes, +shift counts above 15, sign extension, and a sparse `EXEC` mask (2,048 result +words and 16 guard words per dispatch). The native replay requires shader model +6.6 and wave32. diff --git a/docs/experiments/native-rcp-iflag-f32.md b/docs/experiments/native-rcp-iflag-f32.md new file mode 100644 index 0000000000..ad586d23e2 --- /dev/null +++ b/docs/experiments/native-rcp-iflag-f32.md @@ -0,0 +1,32 @@ +# Direct DXIL `v_rcp_iflag_f32` Translation + +Experiment for direct Compute and Pixel DXIL lowering of `v_rcp_iflag_f32` (`VOP1 0x2b`, `VOP3 0x1ab`, SDWA, DPP16), addressing `#3252` and `#2935`. + +## What Changed + +- [src/gfx1013_compute_alu.inl](../../src/gfx1013_compute_alu.inl): added `v_rcp_iflag_f32` alongside `v_rcp_f32` (`1.0 / {0}`, also enabling `alu_rules` lookup in `DirectCompute::dpp()`). +- [src/gfx1013_compute_opcodes.inl](../../src/gfx1013_compute_opcodes.inl): added `case 0x2b: return "v_rcp_iflag_f32";`. +- [src/gfx1013_compute_native.cpp](../../src/gfx1013_compute_native.cpp): added `"v_rcp_iflag_f32"` to the SDWA `floats` set next to `"v_rcp_f32"`. +- [src/gfx1013_direct_compute.inl](../../src/gfx1013_direct_compute.inl): lowered `v_rcp_iflag_f32` identically to `v_rcp_f32` (`fdiv float 1.000000e+00, a`) in `DirectCompute::float_alu()`. +- Added [tests/native_rcp_iflag_check.py](../../tests/native_rcp_iflag_check.py) and registered CTest entries in [tests/cmake/native_rcp_iflag.cmake](../../tests/cmake/native_rcp_iflag.cmake). + +## Verification + +Host: Windows 10.0.26100, `dev` preset, DXC `10.0.26100.0`. + +- `cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check native_compute_ir_dump`: passed. +- `ctest --preset dev --no-tests=error -R '^native_rcp_iflag_' -V`: + - `native_rcp_iflag_controls`: **passed** (`16` Compute + `4` Pixel cases compiled identically to `v_rcp_f32` DXIL; `2` refusals matched). + - `native_rcp_iflag_pixel_warp`: **passed** (`Microsoft Basic Render Driver`, `4` quad draws matched). + - `native_rcp_iflag_pixel_hardware`: **passed** (`NVIDIA Quadro M1000M`, `4` quad draws matched; debug layer unavailable). + - `native_rcp_iflag_compute_hardware`: **skipped** (`77`, `Intel(R) HD Graphics 530` `31.0.101.2111` requires SM 6.6 with wave32). +- `ctest --preset dev --no-tests=error -R '^native_.*_(controls|ir)$' --output-on-failure`: **68/68 passed** (`0` failures, `0` skips). +- Sensitivity mutants verified against `native_rcp_iflag_controls`: + - `drop_direct_iflag` (`src/gfx1013_direct_compute.inl`): failed (`rc=8`, `direct DXIL lowering for v_rcp_iflag_f32`). + - `drop_sdwa_iflag` (`src/gfx1013_compute_native.cpp`): failed (`rc=8`, `unimplemented direct SDWA operand profile`). + - Clean tree restored, rebuilt `compile_dxil`, and `native_rcp_iflag_controls` passed again. +- `python -B tests/docs_links_check.py`: passed (`131` Markdown files, `631` links). + +## Limits + +- Direct Compute GPU execution (`native_rcp_iflag_compute_hardware`) could not run locally because `Intel(R) HD Graphics 530` lacks SM 6.6 wave32 (`77` skip). Compute DXIL (`controls`), Pixel WARP, and Pixel hardware (`NVIDIA Quadro M1000M`) are verified on power-of-two operands (`0 ULP`); non-power-of-two reciprocal ULP tolerance matches DXIL `fdiv` hardware behavior. diff --git a/docs/experiments/native-replay-adapter.md b/docs/experiments/native-replay-adapter.md new file mode 100644 index 0000000000..68801708ff --- /dev/null +++ b/docs/experiments/native-replay-adapter.md @@ -0,0 +1,29 @@ +# Identify the D3D12 adapter used by native compute replay + +`native_store_replay` honors `XBOX2WINDOWS_ADAPTER` as a case-insensitive +substring of a D3D12 hardware adapter's description. With the variable unset, +it uses the default D3D12 device. With an unmatched or overlong filter, it +exits with code 2 before constructing a shader pipeline or writing a readback. + +The runner writes the actual adapter name, vendor and device IDs, DXGI driver +version when available, and the LUID from the D3D12 device to stderr. The LUID +distinguishes adapters with the same name within a run. Binding rows still +go to stdout. [Microsoft's DXGI adapter lookup documentation](https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_4/nf-dxgi1_4-idxgifactory4-enumadapterbyluid) +describes how to look up the adapter using the device's LUID. + +From x64 Visual Studio Developer PowerShell with Python and DXC configured: + +```powershell +cmake --preset dev +cmake --build --preset dev --target native_store_replay +$env:XBOX2WINDOWS_ADAPTER = 'RTX 4070' +ctest --preset dev --no-tests=error -j 1 -R '^native_(store_replay_adapter_controls|cvt_pk_u8_hardware)$' -V +``` + +Choose a filter for your hardware. The controls set their own filters and +require the expected errors without a shader file or output. The packed-U8 +test runs synthetic literal and lane-derived shaders. On Windows 11 build +`26300.10075`, both matched 2,064 words on RTX 4070 with driver +`32.0.16.2124`. The report showed the same LUID with the explicit filter and +with the variable unset. Selection between multiple physical GPUs was not +measured on this host. diff --git a/docs/experiments/native-round-f16.md b/docs/experiments/native-round-f16.md new file mode 100644 index 0000000000..95fad404e3 --- /dev/null +++ b/docs/experiments/native-round-f16.md @@ -0,0 +1,28 @@ +# Direct DXIL `v_floor_f16`, `v_ceil_f16`, `v_trunc_f16`, and `v_rndne_f16` + +Lowers `v_floor_f16` (VOP1 `0x5b` / VOP3A `0x1db`), `v_ceil_f16` (VOP1 `0x5c` / +VOP3A `0x1dc`), `v_trunc_f16` (VOP1 `0x5d` / VOP3A `0x1dd`), and `v_rndne_f16` +(VOP1 `0x5e` / VOP3A `0x1de`) in the native direct-DXIL compute path +(`src/gfx1013_direct_compute.inl`) using exact 32-bit integer IEEE-754 binary16 +rounding while preserving `D[31:16]`. + +## Scope + +- Covers `-0.0h`, `±min_sub`, `0.5h`, `1.5h`, `2.5h`, `-1.5h`, `1023.5h` + (mantissa-to-exponent carry), and inline binary16 float constants `240..248` + (`0.5`, `-0.5`, `1.0`, `-1.0`, `2.0`, `-2.0`, `4.0`, `1/(2*pi)`) across VOP1 + and VOP3A with pre-seeded `D[31:16]`. +- Refuses unsupported modifiers (`omod`, `op_sel`, unused VOP3 sources). +- Negative controls: round-half-away-from-zero, losing `-0.0h`, reading inline + float constants as `0x0000`, and zeroing `D[31:16]` each differ from the + reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_round_f16_' -V +``` diff --git a/docs/experiments/native-rtv-variant-requests.md b/docs/experiments/native-rtv-variant-requests.md new file mode 100644 index 0000000000..37abd967f8 --- /dev/null +++ b/docs/experiments/native-rtv-variant-requests.md @@ -0,0 +1,148 @@ +# RTV variant requests in `compile_dxil --requests` (#2980) + +[The fixture](../../tests/native_rtv_variant_check.py) gives `compile_dxil gfx1013-container-pair --requests` a +directory with one source-built VS/PS base request and RTV variant requests that share its base key. It checks the +published entries, their format metadata and, through the stand-in, a fenced readback of a target of each format. + +## What changed + +1. **Reader (`src/shader_compute_request.cpp`).** `read_graphics_request` accepts `req_.rtv`. The text is + checked as `tools/startup/gfx2hlsl.py::request_source` checks it: at most 256 bytes, `rtv1 + ...` in decimal with one to eight formats and nothing else, and the FNV-1a hash of the text equal to + the key in the file name (`invalid RTV variant request`); the base key at most 64 bits and each format at most + 32 bits (`invalid RTV variant values`). The base parts `req_.{a,b,root}` and the optional `.ia` and + `.psin` are then read and checked against the base key by the existing base path. Its refusals are prefixed + with `RTV variant source: `. +2. **Translation (`src/direct_compute_cache.cpp`, `src/gfx1013_direct_graphics.inl`).** The ordered formats type + the pixel stage's color targets as `mrt_kind` does in `gfx2hlsl.py`: `u32` or `i32` for the integer formats, + `f32` for every other format. `R32G32B32_UINT` (7) and `R32G32B32_SINT` (8) have no verified readback there + and are refused as `unverified UINT RTV format 7` and `unverified SINT RTV format 8`, as there only when the + pixel stage exports to that target. A float32 target needs no extra mechanism: the pixel stage stores the + register bits as a float. +3. **Cache and manifest.** The target types are part of the `.pairir` key, so formats of one type share a + frontend entry. A base request adds nothing to its key, and its translation takes the same path as before. + (The frontend sources feed `X2W_NATIVE_SHADER_REVISION`, so existing `.pairir` entries are rekeyed once, as + with any frontend change.) The runtime manifest accepts an integer target only for the variant whose format + asked for it, and ends with the request text, which the runtime compares with the request it made. The entry + is published as `.vs.cso`, `.ps.cso` and then `.txt`. +4. **Tool (`tools/startup/compile_dxil.cpp`).** The pair profile scans `req_.rtv` next to `req_.a`. The + report line is `rtv_variant types=,...`. A variant whose pair has no runtime manifest (an + input layout or vertex fetch, for example) is refused as `RTV variant has no runtime manifest`, where a base + pair still publishes its stages. A key with both markers is one request, the variant, as in `request_source`. + The rectangle profile does not take variants. + +Two differences from `gfx2hlsl.py`, both refusals where it translates: it types a target by the format alone, +while a container whose own output signature gives another type is refused here (`RTV variant format disagrees +with the pixel signature of target N`); and it has no runtime-manifest condition. + +The stand-in is not changed. It already publishes `req_.rtv` and loads `.txt`. + +## Pair, formats and expected values + +The vertex container covers the viewport from the vertex index. The pixel container moves the words `ffff7ffe`, +`15`, `eb` and `68` into `v0..v3` and exports them to MRT0. + +| Request formats | Target types | `SV_Target0` in the compiled stage | Expected MRT0 bytes | +|---|---|---|---| +| `R16G16B16A16_UINT` (12), `R8G8B8A8_UNORM` (28) | `u32,f32` | `uint` | `ffff 1500 eb00 6800`: the first word clamps to 65535 | +| `R16G16B16A16_SINT` (14), `R8G8B8A8_UNORM` (28) | `i32,f32` | `int` | `0080 1500 eb00 6800`: the first word, -32770, clamps to -32768 | +| `R32G32B32A32_FLOAT` (2) | `f32` | `float` | `fe7fffff 15000000 eb000000 68000000`: all four words bit for bit, the first a NaN with a payload | + +For the two integer formats the consumer binds a second RGBA8 target, which the pixel stage does not write. It +keeps the clear value `0000ffff`. The base pair drawn to an RGBA8 target stores `00000000` over the blue clear +(a NaN and three denormals as UNORM). + +## Controls + +`native_rtv_variant_controls` needs no device: + +1. The base, the three variants of the table and a fourth, `R16G16_UINT` (36) with RGBA8, compile from an empty + compiler cache with `--jobs 4` (`requests=5 compiled=5 refused=0`). The two UINT variants have the same target + types and share one frontend entry. Each variant manifest is the base manifest plus the request line, the + report names the types, and `dxc -dumpbin` shows `SV_Target0` as `uint`, `int` and `float`. The base manifest + has no `rtv1` line and its pixel stage is `float`. A second run reports a frontend cache hit and two bytecode + cache hits for every request and publishes the same bytes. `gfx2hlsl.pending_keys` then lists nothing. +2. Refusals, each leaving only `.fail` with the reason under the variant key (the `.fail` lifecycle of + [#2984](native-compile-dxil-refusals.md)): a forged variant key, base content that no longer + matches the base key, no format, nine formats, a format above 32 bits, a trailing newline, a missing base, + format 7 and format 8 in the exported slot, and a forged variant file under the base's own key. Where the + base request is intact, it still compiles (`compiled=1 refused=1`). Format 7 in the slot the pixel stage does + not export to compiles (`types=u32,u32`); moved to the exported slot it is refused although the frontend entry + of those types is cached by then. A base with an input layout publishes its stages without a manifest, as + before; its variant is refused for having none, and again when the layout no longer matches the base key. +3. A published variant whose base then changes is refused on the next run (`requests=5 compiled=0 refused=5`) + and no `.txt` is left in the directory. +4. With a pixel container whose output signature says `uint`, the UINT variant compiles, the FLOAT variant is + refused by name, and the base pair publishes no manifest, as before. + +`native_rtv_variant_{warp,hardware}`: the consumer creates the pair through device slot 86 and draws one pixel +into a target of each format, so the stand-in publishes the base request and the three variant requests. The +tool compiles the directory cold and warm with the checks of step 1. The consumer then draws each format in a +new process. The log names the desktop pipeline for the variant key with the bound formats (`0x00000000`) and the +drawn call, and the readback after the fence equals the table above. The base pair is drawn last. + +## Command and result + +```powershell +cmake --preset dev # run here with -DINTAKE_PYTHON=, the worktree having none +cmake --build --preset dev +ctest --preset dev --no-tests=error -V -R '^native_rtv_variant_' +``` + +Commit `be9a0706` on `cpp-migration` at `4ff5e36d`, Windows 11 build 26300.9974, Debug build, Windows SDK +10.0.26100 DXC, D3D12 debug layer enabled. + +| Test | Adapter, driver | Result | +|---|---|---| +| `native_rtv_variant_controls` | none (no device) | PASS. | +| `native_rtv_variant_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS. The three readbacks match the table. No debug-layer error message. | +| `native_rtv_variant_warp` | Microsoft Basic Render Driver, 10.0.26100.9818 | PASS. The three readbacks match the table. No debug-layer error message. | + +Release: the same commit built with the `release` preset (`cmake --preset release`, `cmake --build --preset +release`, `ctest --preset release` with the same filters; MSVC 19.44.35230) on the same machine. The three tests +pass on both adapters with the same readbacks and no debug-layer error message, the controls pass 12 runs in a +row, and the first regression set below gives the same 45 passes and 3 capability skips. The pull request +preset is a Debug preset and was not run in Release. + +Baseline: at `05438d65` the tool does not scan `.rtv` files. A directory with a base request and one variant +request gives `requests=1 compiled=1 refused=0` and nothing under the variant key (run with a format 2 request +published by the stand-in on each of the two adapters). + +Mutation: with the format ignored where the target is typed, `native_rtv_variant_controls` and +`native_rtv_variant_warp` fail. This was run on an earlier state of the branch, on `05438d65`; the mutated line +is the same in `be9a0706`. + +Regression runs at the same commit, same machine: + +```powershell +ctest --preset dev --no-tests=error -R '^(native_rtv_variant_|native_compile_dxil_refusals|native_startup_request_cache|startup_mrt_|native_direct_container|native_sampled_replay|native_global_srv_heap_replay|native_recording|native_graphics|native_dxil_llvm_ident|native_.*_pso_|startup_stream_|startup_compute_dispatch_native)' +ctest --preset pr --no-tests=error +``` + +- The first set: 45 of 48 pass. Capability skips, not passes: `native_comparison_pso_warp`, + `native_global_srv_heap_replay_warp` and `startup_compute_dispatch_native_warp`. +- The pull request preset: 36 of 40 pass. Capability skips, not passes: `spirv_minlod_warp`, + `spirv_minlod_exact_warp`, `spirv_minlod_levels_warp` and `spirv_minlod_fractional_warp`. + +These two sets were not run at `4ff5e36d` without the change, so whether the seven skips predate it was not +measured here. + +## Limits + +- Three formats were drawn: 12, 14 and 2. The other integer formats take the same two types and were compiled + by no fixture here. The readback sets of `gfx2hlsl.py` were verified with that translator's output, not with + this one. +- One pair: no resources, no samplers, no root constants, a pixel stage that writes MRT0 only. A variant whose + pixel stage writes two typed targets was not run. +- The readbacks use containers without an output signature. The signature branch is compiled by the controls + and was not drawn. +- The controls ran the directory with four workers 12 times in a row without a failure. That is the only + evidence for two requests publishing one frontend entry side by side, beyond reading the cache code. +- The variants came from slot 86 containers. A raw slot 57 pair with a `.psin` goes through the same reader + path, and no fixture ran one as a variant. +- A format that is not an integer format is typed `f32` without a check that it is a renderable format, as in + `gfx2hlsl.py`. +- The runtime's `mrtbits` entry value is not used: the native pixel stage keeps float32 bits without it. This + was measured for the four words above on the two adapters only. +- Only the two adapters above were run, in Debug and Release builds on one machine. No start-up run used a + variant compiled this way. diff --git a/docs/experiments/native-s-lshl-add-u32.md b/docs/experiments/native-s-lshl-add-u32.md new file mode 100644 index 0000000000..8830759af9 --- /dev/null +++ b/docs/experiments/native-s-lshl-add-u32.md @@ -0,0 +1,26 @@ +# Scalar shift-and-add (`s_lshl{1,2,3,4}_add_u32`) in direct compute + +The native compute frontend translates the gfx1013 SOP2 instructions +`s_lshl1_add_u32` (`0x2e`), `s_lshl2_add_u32` (`0x2f`), `s_lshl3_add_u32` +(`0x30`), and `s_lshl4_add_u32` (`0x31`). Each computes +`temp = ((uint64)S0 << k) + (uint64)S1`, writes `temp[31:0]` to `D`, and sets +`SCC = (temp >= 2^32)` (true when either `S0 >> (32 - k) != 0` or the 32-bit +addition carries). + +Section 12.1 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_s_lshl_add_u32_' -V +``` + +The compile controls validate the generated DXIL and verify that omitting +shift-out overflow diverges from the reference. Two source-built dispatches +exercise eight input pairs across all four shift amounts (`k = 1..4`), +verifying both `D` and `SCC` (including shift-out-only overflow, addition +carry, and exact `0xFFFFFFFF` / `0x100000000` boundaries; 2,048 result/SCC +words and 16 guard words per dispatch). The native replay requires shader +model 6.6 and wave32. diff --git a/docs/experiments/native-s-quadmask.md b/docs/experiments/native-s-quadmask.md new file mode 100644 index 0000000000..243d30ca78 --- /dev/null +++ b/docs/experiments/native-s-quadmask.md @@ -0,0 +1,24 @@ +# Direct DXIL `s_quadmask_b32` and `s_quadmask_b64` + +Lowers `s_quadmask_b32` (SOP1 `0x2c`) and `s_quadmask_b64` (SOP1 `0x2d`) in the +native direct-DXIL compute path (`src/gfx1013_direct_compute.inl`), packing one +bit per non-zero 4-bit quad (`bits[7:0]` for `b32`, `bits[15:0]` with zeroed +high dword for `b64`) and setting `SCC = (D != 0)`. + +## Scope + +- Covers 8 32-bit cases for `s_quadmask_b32` and 4 64-bit cases (including + hi-only non-zero and in-place destination aliasing) for `s_quadmask_b64`. +- Refuses odd destination or odd source SGPR pairs on `s_quadmask_b64`. +- Negative controls: requiring all 4 quad bits set and ignoring the high dword + of `s_quadmask_b64` each differ from the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_s_quadmask_' -V +``` diff --git a/docs/experiments/native-s-sext-i32.md b/docs/experiments/native-s-sext-i32.md new file mode 100644 index 0000000000..5b65240208 --- /dev/null +++ b/docs/experiments/native-s-sext-i32.md @@ -0,0 +1,24 @@ +# Direct DXIL `s_sext_i32_i8` and `s_sext_i32_i16` + +Lowers `s_sext_i32_i8` (SOP1 `0x19`) and `s_sext_i32_i16` (SOP1 `0x1a`) in the +native direct-DXIL compute path (`src/gfx1013_direct_compute.inl`) as 32-bit +arithmetic sign extensions (`ashr(shl(a, 24), 24)` and `ashr(shl(a, 16), 16)`) +that preserve `SCC`. + +## Scope + +- Covers 8 representative 32-bit inputs across positive, negative, boundary, + and upper-bit-junk cases for both `s_sext_i32_i8` and `s_sext_i32_i16`, + verifying both the sign-extended result and `SCC` preservation. +- Negative controls: zero-extending instead of sign-extending and overwriting + `SCC` with `result != 0` each differ from the reference. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_s_sext_i32_' -V +``` diff --git a/docs/experiments/native-salu64-ops.md b/docs/experiments/native-salu64-ops.md new file mode 100644 index 0000000000..8f89595cfa --- /dev/null +++ b/docs/experiments/native-salu64-ops.md @@ -0,0 +1,39 @@ +# 64-bit scalar operations in the direct C++ compute path + +Issue #2957 adds `s_bfm_b64`, `s_cselect_b64` and `s_not_b64`. +`s_bfm_b64` uses the low six bits of each 32-bit source as its width and +offset, writes both words of an aligned SGPR pair, and preserves SCC. +`s_cselect_b64` selects both words using SCC and preserves SCC. +`s_not_b64` complements both words and sets SCC when either result word +is nonzero. Both take aligned SGPR pairs or constants, with sign extension +for inline negatives and zero extension for other integers. They can +write VCC as a pair. `s_bfm_b64` and `s_not_b64` may also write EXEC, as both +words, in wave32 and wave64. `s_cselect_b64` still refuses EXEC destinations. +`s_not_b64` and `s_cselect_b64` also take VCC and EXEC as 64-bit sources +(`tests/native_s_not_b64_exec_check.py`, `ctest --preset dev --no-tests=error -R '^native_s_not_b64_exec_'`). + +Direct compute also accepts `s_bitreplicate_b64_b32 exec, imm`, writing both EXEC words and preserving SCC. Wave32 lane activity uses only `exec_lo`. + +## Verification + +`native_salu64_controls` checks that compiling `s_cselect_b64 exec, -1, 0` +fails. `native_salu64_hardware` checks both result words, SCC, and the +buffer guards across two 32-thread groups. It covers mask widths 0, 1, 31, +32, 33, 63 and 64, including the captured width and offset of 32, with +the raw width 64 wrapping to 0. The select cases cover both SCC values, +an SGPR pair, inline -1 and the literal `0x80000001`. The complement +cases include zero output and output with only the high word nonzero. +Hardware without shader model 6.6 and wave32 support returns skip code 77. +`native_wave64_exec_salu_hardware` covers `s_bfm_b64 exec, 16, 0` and `exec, 32, 32` in wave64, 64- and +128-thread groups (the wave32 EXEC destination is accepted but not run), checking which lanes stay active through a per-lane store. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_salu64_(controls|hardware)$' +ctest --preset dev --no-tests=error -R '^native_wave64_exec_salu_hardware$' +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) all fifteen cases +matched their 64-bit words and SCC in both workgroups, with the guards intact, and the control refused an EXEC +destination. A 32-bit `s_bfm_b64`, a zero-extended `-1` in `s_cselect_b64` and an `s_not_b64` SCC taken +from the low word only each fail the hardware check. diff --git a/docs/experiments/native-sampler-heap.md b/docs/experiments/native-sampler-heap.md new file mode 100644 index 0000000000..59dab0b62b --- /dev/null +++ b/docs/experiments/native-sampler-heap.md @@ -0,0 +1,122 @@ +# Sampler descriptors read from the directly indexed sampler heap at a fixed index (translator, stage 1) + +Issue #3076, part of #2935 (related #1143). The native compute translator now accepts a sampler that the program loads from +the sampler heap with `s_load_dwordx4` / `s_load_dwordx8` at a constant 16-byte aligned offset and uses with +`image_sample_l` or `image_sample_lz`. It lowers the sampler to `SamplerDescriptorHeap[index]` in the DXIL module. This is +stage 1: the translator, the binding record, the cache, the root signature and `bind()`. Binding a real, mirrored sampler heap +at dispatch time in the runtime is stage 2 and is not part of this change. + +## Why + +A local start-up capture (counts only; `compile_dxil` at the base commit, 2,689 slot 67 compute requests): 400 compile, +1,830 contain `image_sample*` or `image_gather*`, and in 993 of those at least one sampler is loaded from memory. The +pattern has root flags `0xc00`; the entry SGPR after the resource heap holds the sampler heap base; the program copies it +into an even SGPR pair, sets the high word to 0 and loads one sampler with `s_load_dwordx4` (or two with `s_load_dwordx8`) at +a 16-byte aligned immediate offset; `image_sample_lz` or `image_sample_l` then uses it (95,839 and 20,556 of 127,822 +sample and gather instructions). Before this change the native translator left that SGPR `unbound`, so the load was refused +("direct descriptor address outside bound table") and `sampler_index` refused non-literal words ("nonconstant sampler"). +There is no compiled-count gain on its own: with the mixed-contract chain of #3023 applied locally (uncommitted probe), 130 +requests stop first at such a load (117 `dwordx4`, 13 `dwordx8`). The change removes the next blocker of that chain. + +## What changed + +- `compute_sampler_heap` (`~0u - 1`) is a second sentinel next to `compute_resource_heap`. Under the existing condition + (root flags `0xc00`, exactly two user SGPRs left after the root parameters) the SGPR after the resource heap is now the table + `{table, compute_sampler_heap}` instead of `unbound`. Entry `n` of the sampler heap is title byte offset `16 * n`. +- Direct path, load from the sampler heap (`gfx1013_direct_compute.inl`), refused in this order: a scalar buffer load ("scalar + buffer load from the sampler heap is not translated"); an SGPR offset ("sampler heap load with an SGPR offset (a + GPU-selected sampler) is not translated"); any width but `dwordx4` / `dwordx8` ("sampler heap load must read one or two + samplers"); an immediate offset that is not a multiple of 16 ("sampler heap offset is not a multiple of 16"); an entry + index above 2046 ("sampler heap index beyond 2046 (2047 is the runtime fallback entry)"). The existing rule that the table + address has a constant zero high word then applies. +- HLSL path: a load through that base is refused ("sampler heap reads need the direct DXIL path"). +- `Emit::binding`: a descriptor from the sampler heap used as an image or buffer is refused ("a sampler heap descriptor is + read as a resource"). +- `sampler_index` returns `SamplerRef {heap, index}`. Four words that are all literals take the static-sampler path as before; + four contiguous words of one sampler-heap entry make a heap sampler; anything else is "nonconstant sampler". For a heap + sampler, in this order: gathers ("gather through the sampler heap is not translated"), comparison samplers ("comparison + sampler from the sampler heap is not translated"), gradient samplers ("sampler from the sampler heap needs image_sample_l or + image_sample_lz"). Static and heap samplers may appear in one program (the mixed fixture). +- DXIL: `DxilModule::sampler_heap_handle` emits `createHandleFromHeap(i32 218, i32 , i1 true, i1 false)` and + `annotateHandle` with resource properties `{14, 0}`; the emitter sets module flag `0x80000000` (sampler heap indexing), as DXC + does for `SamplerDescriptorHeap[i]` (DXC reference: flags `0x80000010` with raw buffers). +- Binding record: `ComputeViewKind::heap_sampler`, one per program, `{heap_sampler, compute_sampler_heap, byte_offset 0, + register 0, required_bytes 16 * (highest index + 1)}`. The frontend cache accepts the kind with exactly that root value; an + older decoder rejects it and recomputes. `format_compute_runtime_manifest` returns no manifest for it (root parameter above + 15), so `compile_dxil --requests` publishes `.cs.cso` without `.txt`; the in-process dispatch route refuses the + kind. `compile_dxil` reports `sampler_heap span=`. +- `create_native_compute_pipeline`: `sampler_heap_indexed` adds root flag `0x800` (`SAMPLER_HEAP_DIRECTLY_INDEXED`) and does not + set `heap_indexed` or `0x400`. `NativeComputePipeline::bind` has a last parameter `ID3D12DescriptorHeap *sampler_heap`: with + `sampler_heap_indexed` a null heap throws ("a sampler heap is needed"); with views too, the heaps are set as views first, then + samplers; without it nothing changes. A root without `0x800` and a shader that reads `SamplerDescriptorHeap` fails + `CreateComputePipelineState` with `E_INVALIDARG` (debug layer: "Shader uses sampler descriptor heap indexing, but root + signature is missing the D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED flag"), measured on the RTX 3080 with a + throw-away probe; a root with static samplers and `0x800` with a shader that reads one static and one heap sampler creates + without a debug-layer message. + +## Assumptions for stage 2 + +The runtime must fill the sampler heap bound for a natively translated compute dispatch so that entry `n` is title byte offset +`16 * n` (index parity), with `dynamic_sampler()` decoding (`src/startup_stubs/translated_sampler_bindings.h`: MIN_LOD and MAX_LOD +applied, which is why only the explicit-LOD forms are translated), and entry 2047 (`translated_sampler_fallback`) holding the +fallback sampler. The translator refuses index 2047, so the fallback is never read. None of this is implemented here; the fixture +builds its heap with `dynamic_sampler()` and the index parity itself. + +## Fixture + +`tests/native_sampler_heap.cpp`, `tests/native_sampler_heap_check.py`, `tests/cmake/native_sampler_heap.cmake`; tests +`native_sampler_heap_hardware` and `native_sampler_heap_warp` (`SKIP_RETURN_CODE 77`: WARP has no 32-lane waves). + +The script writes source-built compute requests (`.c67`, as `tests/native_compute_raw_root_check.py`) with the root +`RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))`, group 32x1x1 and +seven user SGPRs (s4 table, s5 resource heap, s6 sampler heap). The instruction words were assembled once with LLVM 15 +(`clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -filetype asm -show-encoding`) and are embedded with one source +comment per instruction; the test needs no LLVM. One SRV+UAV table is accepted by the direct path (no split into two tables was +needed). The programs copy s6 into an even SGPR pair with a constant-zero high word and sample a 4x4 two-mip texture at (1.375, +-0.375), outside [0, 1]: + +| Program | Shape | Expected | +|---|---|---| +| SAMPLE | `s_load_dwordx4` at 0x430 (entry 67), `image_sample_lz` | wrap texel (1, 2) of mip 0 | +| TWO | `s_load_dwordx8` at 0x430, two samples | entry 67 wrap, entry 68 clamp (a swapped second group fails) | +| LOD | `image_sample_l`, LOD 1 | MaxLOD 1 picks mip 1; decoys with MaxLOD 0 (bilinear and point) pick mip 0 | +| MIXED | one literal static sampler and entry 67 | static clamp texel and heap wrap texel; one static sampler in the program | + +The fixture dispatches on the RTX 3080 with a 128-entry sampler heap made with `dynamic_sampler()`. Every entry but the entries +under test is a decoy (clamp, mirror, border, a bilinear border with a white colour). It compares every lane with a CPU model, +then dispatches once per decoy with the decoy in place of the entry under test and requires the result to change. It also calls +`prepare_direct_compute` twice on the same fresh cache directory (a miss, then a hit) and requires exactly one binding +`{heap_sampler, compute_sampler_heap, 0, 0, 16 * (highest index + 1)}` in the computed and in the cached program, and that +`bind()` without a sampler heap throws. + +The script also compiles the refusal shapes and requires each exact text and no `.cso`: offset 0x438, entry 2047, `dwordx8` +at entries 2046 and 2047, `dwordx2` and `dwordx16`, an SGPR offset, a scalar buffer load, a sampler heap entry used as an image +descriptor, mixed literal and heap words in one sampler, a join that replaces the copied base on one path, `image_gather4_lz`, +`image_gather4_c_lz`, `image_sample_c_lz` and `image_sample_d` with a heap sampler, the HLSL profile, and a root with only +`0x400` (today's refusal, unchanged). Each has a control that compiles (entry 2046, `dwordx8` at 2045 and 2046, the branch +without the overwrite, the four operations with a literal sampler). + +## Result + +Environment: NVIDIA GeForce RTX 3080, Windows SDK 10.0.26100.0 DXC, D3D12 debug layer not enabled in the fixture. + +``` +ctest --preset dev --no-tests=error -R "^native_sampler_heap_(hardware|warp)$" -V +``` + +`native_sampler_heap_hardware` passes with 69 `ok:` assertions in the check script (the fixture's own per-mode checks print +`pass:` lines and are counted inside them); +`native_sampler_heap_warp` skips (77: no 32-lane waves). The regression set +`ctest --preset dev --no-tests=error -R "native_|startup_compute_dispatch|compute_heap" -j 6` passes (163 tests, 0 failed, 5 +skips: the four WARP tests that already skipped and the new one). + +## Limits + +- Stage 1 only: no runtime binding of a mirrored sampler heap for natively translated compute dispatch. +- GPU-selected sampler indices (SGPR offset), comparison, gather and gradient sampling through the heap, and containers are + refused. Roots with only the `0x800` flag (10 requests in the capture) are not covered. +- The fixture samples with point filters and compares exact texels; decoys are checked to change the result (and to run: + not the output sentinel), bilinear decoys only that. +- Not exercised by a test: the highest accepted entry 2046 in a sample (the edge controls only load it), and `bind()`'s + "a view heap is needed" throw (no test program reads the sampler heap without a view table). +- A passing fixture supports the behaviour under test; it does not establish that any title shader runs. diff --git a/docs/experiments/native-sat-pk-u8-i16.md b/docs/experiments/native-sat-pk-u8-i16.md new file mode 100644 index 0000000000..1065cb9f9b --- /dev/null +++ b/docs/experiments/native-sat-pk-u8-i16.md @@ -0,0 +1,26 @@ +# Packed signed-16 to saturated-u8 conversion (`v_sat_pk_u8_i16`) in direct compute + +The native compute frontend translates both the VOP1 (`0x62`) and VOP3A +(`0x1e2`) encodings of gfx1013 `v_sat_pk_u8_i16`. It sign-extends both 16-bit +halves of `src0`, clamps each to `[0, 255]`, packs the low and high results +into `D[7:0]` and `D[15:8]`, and zeroes `D[31:16]`. + +`clamp`, `omod`, `abs`, `neg`, `op_sel`, SDWA, DPP, and nonzero unused +`src1`/`src2` fields on the VOP3A encoding are refused. + +Section 12.6 of the [AMD RDNA 2 ISA](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) +defines the guest semantics. + +## Reproduce + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_sat_pk_u8_i16_' -V +``` + +The compile controls validate the generated DXIL and refuse six VOP3A +modifier/unused-source encodings (`clamp`, `op_sel`, `abs`, `neg`, nonzero +`src1`, nonzero `src2`). Two source-built dispatches exercise 16 input patterns +across both VOP1 and VOP3A encodings, verifying upper-half zeroing (`D[31:16] = 0`) +and a sparse `EXEC` mask (2,048 result words and 16 guard words per dispatch). +The native replay requires shader model 6.6 and wave32. diff --git a/docs/experiments/native-saveexec-wrexec.md b/docs/experiments/native-saveexec-wrexec.md new file mode 100644 index 0000000000..91c910c592 --- /dev/null +++ b/docs/experiments/native-saveexec-wrexec.md @@ -0,0 +1,48 @@ +# Remaining SOP1 `*_saveexec_*` and `*_wrexec_*` instructions in direct Compute DXIL + +Issue #3296 (Refs #2935) lowers the remaining 12 SOP1 EXEC-mask instructions in +the direct Compute DXIL path (`src/gfx1013_direct_compute.inl`), updates +`uses_scc_after()` so `SCC` liveness treats all scalar mask and SAVEEXEC/WREXEC +definitions consistently, and updates `transfer()` in +`src/gfx1013_compute_native.cpp` so all wave32 `*_saveexec_b32` and +`*_wrexec_b32` instructions clear symbolic provenance on both the destination +register and `EXEC_LO`. + +## Lowered Instructions + +- **Wave32 (`SOP1`, 32-bit):** + - `s_xor_saveexec_b32` (`0x3e`): `D = EXEC_LO; EXEC_LO = S0 ^ EXEC_LO` + - `s_andn2_saveexec_b32` (`0x3f`): `D = EXEC_LO; EXEC_LO = S0 & ~EXEC_LO` + - `s_orn2_saveexec_b32` (`0x40`): `D = EXEC_LO; EXEC_LO = S0 | ~EXEC_LO` + - `s_nand_saveexec_b32` (`0x41`): `D = EXEC_LO; EXEC_LO = ~(S0 & EXEC_LO)` + - `s_nor_saveexec_b32` (`0x42`): `D = EXEC_LO; EXEC_LO = ~(S0 | EXEC_LO)` + - `s_xnor_saveexec_b32` (`0x43`): `D = EXEC_LO; EXEC_LO = ~(S0 ^ EXEC_LO)` + - `s_andn1_saveexec_b32` (`0x44`): `D = EXEC_LO; EXEC_LO = ~S0 & EXEC_LO` + - `s_orn1_saveexec_b32` (`0x45`): `D = EXEC_LO; EXEC_LO = ~S0 | EXEC_LO` + - `s_andn1_wrexec_b32` (`0x46`): `EXEC_LO = ~S0 & EXEC_LO; D = EXEC_LO` +- **Wave64 (`SOP1`, 64-bit):** + - `s_andn1_saveexec_b64` (`0x37`): `D = EXEC; EXEC = ~S0 & EXEC` + - `s_orn1_saveexec_b64` (`0x38`): `D = EXEC; EXEC = ~S0 | EXEC` + - `s_andn1_wrexec_b64` (`0x39`): `EXEC = ~S0 & EXEC; D = EXEC` + +All 12 instructions update `SCC` from `(new_exec != 0)` across all participating +bits (`EXEC_LO` in wave32; both `EXEC_LO` and `EXEC_HI` in wave64). + +## Destination & Mode Rules + +- Newly lowered wave32 ops require `dst <= 107` (`SGPR` / `VCC`), refusing + `M0`/`EXEC_LO` destinations with `unsupported wave32 SAVEEXEC destination`, and + are restricted to wave32 compute shaders. +- `s_andn1_wrexec_b64` matches `s_andn2_wrexec_b64` rules (`compute && wave64`, + even SGPR pair `<= 104` for both `dst` and `src`). + +## Verification + +- [native_saveexec_wrexec_check.py](../../tests/native_saveexec_wrexec_check.py) + covers all 12 instructions across non-zero (`SCC = 1`), zero-result + (`SCC = 0`), high-word-only (`SCC = 1` from `EXEC_HI`), `dst == src` aliasing, + `vcc_lo`/`exec_lo`/inline/literal sources, partial-wave dispatches, and 8 + negative operand/mode refusal cases. +- CMake/CTest targets (`tests/cmake/native_saveexec_wrexec.cmake`): + `native_saveexec_wrexec_ir`, `native_saveexec_wrexec_controls`, and + `native_saveexec_wrexec_hardware`. diff --git a/docs/experiments/native-sdwa-f16.md b/docs/experiments/native-sdwa-f16.md new file mode 100644 index 0000000000..9d308123a0 --- /dev/null +++ b/docs/experiments/native-sdwa-f16.md @@ -0,0 +1,56 @@ +# SDWA binary16 arithmetic in direct compute + +Issue #2963 adds SDWA to `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`. +Each source can be a VGPR, SGPR, or inline constant. WORD_0 and DWORD read the low +half, and WORD_1 reads the high half. Inline floats use a low-half binary16 encoding +with a zero high half. Source abs clears the binary16 sign bit before neg toggles it. The compiler +widens the halves to binary32, performs the operation, and rounds once to binary16 +using the integer nearest-even path from the [plain forms](f16-alu-direct.md). +The binary16 rounding and denormal mode requirements apply to both forms. + +WORD_0 and WORD_1 destinations accept UNUSED_PAD, which zeroes the other half, +and UNUSED_PRESERVE, which copies it from the old destination. DWORD and byte +destinations, UNUSED_SEXT, byte sources, source sext, literals, +clamp, and output modifiers are refused. SDWA min and max remain refused. + +Direct wave32 compute SDWA VOPC compares can write a 32-bit mask to `vcc_hi` and read it as a scalar source. + +Direct compute `v_cvt_f32_f16_sdwa` supports clamp with WORD_0 or WORD_1 and DWORD/UNUSED_PAD (NaN and -0 become +0), and still refuses omod. + +## Fixture + +The wave32 GPU fixture also covers SDWA packed RTZ f32-to-f16 placement and add-with-carry, including per-lane VCC input and output before destination placement. + +The fixture compares the IR and hardware results against the same exact binary16 +model as the plain-form fixture. The hardware run dispatches two wave32 groups, +with one lane per group writing the case words. Every untouched word must keep +the guard value `69696969`. An adapter without wave32 support returns skip code 77. + +| Destination and sources | Add | Sub | Subrev | Mul | +|---|---|---|---|---| +| WORD_0 preserve, WORD_1 and DWORD | a55a4200 | a55abc00 | a55a3c00 | a55a4000 | +| WORD_0 pad, DWORD and WORD_0 | 00004400 | 00004000 | 0000c000 | 00004200 | +| WORD_1 preserve, neg(abs(WORD_0)) and WORD_1 | 3c001357 | c2001357 | 42001357 | c0001357 | + +The add of `3c01` and `1000` rounds its tie to `a55a3c02` with low-half preserve. +The product of `0003` and `3800` rounds to the subnormal word `00000002`. +The product of `7bff` and `4000` overflows to `7c000000` with high-half pad. +The add of `7e01` and `3c00` expects a NaN in the low half and exactly `a55a` +in the preserved high half. The NaN payload and sign may vary. + +Compile-only controls cover DWORD destination, BYTE_1 source, source sext, +UNUSED_SEXT, clamp, omod, min and max. The scalar-source fixture separately +covers SGPR and inline source selection, literal refusal, and scalar source sext. +Swapping WORD_0 and WORD_1 on either source and forcing UNUSED_PRESERVE to pad +are manual lowering mutations that must fail the readback comparison. + +```powershell +cmake --preset dev +cmake --build --preset dev --target native_compute_ir_dump native_store_replay +ctest --preset dev --no-tests=error -R "^native_sdwa_f16_(ir|hardware)$" -V -j 1 +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) the IR check matched all +17 results and the 10 refusals, and the GPU check matched 34 results in two workgroups with 2,030 guard words +intact. Reading the other half of a WORD_0/WORD_1 source, and writing the result without its SDWA placement, +each fail both checks, and so does dropping abs or dropping neg. diff --git a/docs/experiments/native-shift64-sources.md b/docs/experiments/native-shift64-sources.md new file mode 100644 index 0000000000..758446dc08 --- /dev/null +++ b/docs/experiments/native-shift64-sources.md @@ -0,0 +1,32 @@ +# Logical 64-bit shift sources in the direct C++ compute path + +Issue #2951 covers the shifted value for `v_lshrrev_b64` and `v_lshlrev_b64`. +Inline integers supply their 32-bit value as the low word and all ones as the +high word for negative values. Nonnegative integers and 32-bit literals +supply a zero high word. An even SGPR pair from `s[0:1]` through `s[104:105]` +supplies the low and high words in register order. Both SGPRs must be numeric. +VGPR pairs and inline zero remain accepted. The shift amount uses its low six +bits. + +Inline floats, odd or out-of-range SGPR pairs and special registers are +refused with `direct 64-bit shift operand`. + +## Verification + +`native_shift64_controls` checks that an inline float is refused during +compilation. `native_shift64_hardware` uses source-built programs and checks +both words and the buffer guards across two 32-thread groups against an +independent masked Python integer reference. The fixture shifts inline +`-1`, `-16`, `64` and `1`, literal `0x80000001`, and SGPR pair +`0x01234567_89abcdef` in both directions by 0, 1, 31, 32, 33 and 63. +Hardware without shader model 6.6 and wave32 support returns skip code 77. + +```powershell +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_shift64_(controls|hardware)$' +``` + +Results: on an NVIDIA GeForce RTX 5080 (Windows 11, DXC from the Windows SDK 10.0.26100) the controls refused the +inline float, and every source matched its 64-bit reference for both directions and all six shift amounts, in both +workgroups, with the guards intact. Zero-extending the inline values, sign-extending the literal and swapping the +SGPR pair's words each fail the hardware check. diff --git a/docs/experiments/native-slot67-wave-size.md b/docs/experiments/native-slot67-wave-size.md new file mode 100644 index 0000000000..fb745305a5 --- /dev/null +++ b/docs/experiments/native-slot67-wave-size.md @@ -0,0 +1,72 @@ +# Slot 67 wave size in direct compute + +Issue #2999. Slot 67 compute requests carry no documented wave size, and direct compute used to compile every +`.c67` request as wave32. Bit 20 of `.sa` dword 4 (little-endian; bits 15:0 are Z) now sets +`ComputeRequest::wave32`: set means wave32, clear means wave64. A `.sa` that is not 28 bytes is still refused. + +## Why this bit + +This is an inference from a local capture of 2,689 slot 67 requests, not from documentation. The capture was +decoded up to the first `s_endpgm`, and only counts and instruction shape were kept. + +- Every program with a `*_saveexec_b32` and no `*_saveexec_b64` has the bit set (1,385 of 1,385). Every program + with a `*_saveexec_b64` and no `*_saveexec_b32` has it clear (565 of 565). +- The next best bit of `.sa` or `.sb` agrees on 87%: bit 5 of dword 3, the X = 32 bit. +- `v_mbcnt_hi_u32_b32` appears only with the bit clear (197 programs). Every bit-clear program that uses + `v_mbcnt_lo_u32_b32` also uses `v_mbcnt_hi_u32_b32`. The 84 bit-set programs that use `v_mbcnt_lo_u32_b32` + never use `v_mbcnt_hi_u32_b32`. +- Group sizes mostly follow the bit. Of the 784 requests with a 64-thread group, 739 have it clear. Of the 1,433 + with a 32-thread group, 1,405 have it set. +- Bits 31:16 of dword 4 take only two values in the capture, 0x0000 and 0x0010. + +## Translation + +The direct DXIL route of `translate_compute` compiles a wave64 request through the wave64 path that +`translate_compute_container` already uses for a stage without `wave32` (two 32-lane host waves per guest wave). +A wave64 request whose group has at most 32 threads stays on the wave32 model, as before the wave size was read. +Its one guest wave only has lanes 0..31, so EXEC's high word is zero and `v_mbcnt_hi` adds nothing for its lanes. +One known difference remains: a wave64 compare or carry-out also writes zero to the high word of an SGPR pair +destination, and the wave32 model leaves that word as it was. The legacy HLSL profile and the container route are +unchanged. + +Compute requests keep their `29cs` keys, and revision-28 archives are still read. Published native compute manifests now include `native 1`. +`compile_dxil --watch` rebuilds an older native output under the same key. The stand-in refuses it until +the rebuilt manifest appears, looking again on subsequent dispatches on the ManifestRetry schedule (1 s, doubling up to 32 s). An unmarked +manifest with a `.cs.hlsl` sidecar is a Python translation and stays usable. `--requests` rebuilds +every output, the frontend cache is keyed on a hash of the compiler sources, and the in-process route +translates again in each process. A native publish now removes a `.cs.hlsl` left by the Python translator, +so the pair cannot pass as a Python output. One case is not detected: a directory where an earlier +`compile_dxil` already republished a Python-translated key keeps that key's `.cs.hlsl` next to an unmarked +native manifest. Rerun `--requests` into such a directory once. The reload of a refused +manifest is not covered by a test; each check runs a new process. + +Measured with `compile_dxil --jobs 8 gfx1013-direct-cs@36 --requests` on `cpp-migration` `e0d83759`, before and +after: + +| Requests | Compiled before | Compiled after | Newly compiled | No longer compiled | +|---|---|---|---|---| +| Capture, 2,689 | 389 | 393 | 46 | 42 | +| One start-up run, 2,718 | 402 | 406 | 46 | 42 | + +- The 46 newly compiled requests are wave64 programs with 64-thread groups. +- The 42 that no longer compile are wave64 programs that the wave32 model used to accept. They now stop at + "multi-wave64 exchange requires converged group control flow", a limit of the existing wave64 path. + +## Fixture + +`tests/native_slot67_wave_size_check.py` builds the same program as three slot 67 requests that differ in this +bit and in the group size. The program stores `v_mbcnt_lo` followed by `v_mbcnt_hi` at each thread's index. The +CPU reference expects: + +- with the bit clear and 64-thread groups, `tid % 64`; +- with the bit set and 64-thread groups, `tid % 32`; +- with the bit clear and 32-thread groups, `tid % 32`. + +The fixture also checks every untouched buffer word. + +```powershell +ctest --preset dev --no-tests=error -R '^native_slot67_wave_size_hardware$' -V +``` + +The fixture returns 77 when replay reports that the required adapter capabilities are unavailable. Source-built +fixtures that relied on the wave32 default now set the bit. diff --git a/docs/experiments/native-startup-request-cache.md b/docs/experiments/native-startup-request-cache.md new file mode 100644 index 0000000000..85fe9f4c99 --- /dev/null +++ b/docs/experiments/native-startup-request-cache.md @@ -0,0 +1,97 @@ +# Startup request consumption and runtime cache publication in `compile_dxil` (#2933) + +[The fixture](../../tests/native_startup_request_cache_check.py) verifies that `compile_dxil --requests` consumes +revision-29 startup graphics (`x2w-startup-shader-29`, including ASCII `req_.psin` pixel-input descriptions) +and compute (`x2w-startup-shader-29cs`, `req_.c67`) requests, publishes runtime-named stage binaries and +manifests (`.vs.cso` / `.ps.cso` or `.cs.cso`, followed by `.txt`), and loads directly through +the startup runtime cache loaders on WARP and hardware without manual renaming or conversion. + +## First dispatch of a slot-67 compute request + +With `X2W_NATIVE_SHADERS` enabled, the runtime retains the six immutable parts +used to publish each new compute key. First dispatch takes those bytes and checks +their extents before invoking the ordinary C++ translator. Evicted requests use +the disk reader, which also verifies the key. The capture files remain available +for independent replay. + +`X2W_NATIVE_COMPUTE_REQUEST_CACHE_MIB` sets the per-process byte budget from 0 +through 256 MiB. The default is 32 MiB. Zero selects disk reads. The queue holds +at most 4,096 keys, evicts the oldest retained request first and releases each +snapshot on consumption. The render totals report hits, misses, evictions, +retained bytes and retained requests every 300 frames. Run +`ctest --preset dev --no-tests=error -R '^native_frozen_request$'` for the +ownership, budget, eviction and malformed-description controls. + +### Prewarming captured compute requests + +`compile_dxil --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY 0` validates +the six capture parts and prepares the same entry-zero frontend used at first dispatch. +It writes `CACHE_DIRECTORY/compute-0.pack` atomically. Each record contains either +DXIL IR with its binding layout or the exact typed frontend refusal. Other errors +are printed per request, omitted from the pack, and cause a nonzero command status. +If every input fails with an ordinary error, an existing pack is preserved. + +Set `X2W_NATIVE_COMPUTE_PACK` to the absolute pack path before startup. The runtime +loads the index once when native compute requests are published. At first use it +checks the frontend revision, entry offset and SHA-256 of all six frozen parts. +A miss takes the ordinary translation path. A matched refusal proceeds to the +existing published-translation loader. Successful hits run the usual binding +checks, device capability checks, bytecode compilation/cache lookup and PSO creation. +The heartbeat reports prepared hits, matched refusals and pack misses. + +```powershell +cmake --build --preset release --target compile_dxil native_compute_pack_check startup_stream_consumer d3d12_xs_shim +ctest --preset release --no-tests=error -R '^native_compute_pack(_hardware)?$' +``` + +## Alignment between `compile_dxil --requests` and the startup cache + +1. **Request keys and `.psin` stream descriptions (`src/shader_compute_request.cpp`):** + - Graphics requests validate `x2w-startup-shader-29` or the archived revision 28 over `.a`, `.b`, `.root`, and optional `.ia`. When + `req_.psin` is present, the reader parses `psin1 ena=0x addr=0x`, checks that the + embedded key matches `` and `(ena & ~addr) == 0`, and folds `b"psin1" + struct.pack(".vs.cso` / + `.ps.cso`, `.gs.cso` for `gfx1013-container-rect`, and `.cs.cso` for compute), withdraws any + prior `.txt` before rewriting stages or on refusal, records `.psdep` when `.psin` was used, and + atomically publishes `.txt` after all stage `.cso` files are in place. + +## Verification and negative controls + +1. **`controls` mode (`native_startup_request_cache_controls`):** + - Compiles two `.psin`-described VS/PS requests (`(0x8002, 0x8003)` placing `POS_FIXED_PT` in `v4` after an + allocated-only `PERSP_SAMPLE` pair, and `(0x8002, 0x8002)` placing `POS_FIXED_PT` in `v2`) and a `.c67` + compute request in place, checks that `.txt` is written after stage `.cso` files and recognised as + complete by `gfx2hlsl.pending_keys`, and verifies that mutating a stage blob behind an existing `.psin` + withdraws `.txt`. + - Exercises eight fresh-directory refusal controls (graphics key mismatch, compute key mismatch, `.psin` + naming another pipeline, missing `addr`, missing `ena`, contradictory `ena`/`addr`, malformed `.psin`, and + reading an allocated-but-disabled pixel input VGPR), requiring a clear diagnostic on `stderr` and no + `.txt` or stage `.cso` output. +2. **`e2e` mode (`native_startup_request_cache_warp`, `native_startup_request_cache_hardware`):** + - Draws both `.psin` pairs through `offscreen_check --startup-packed-position` (all 91 pixels match, while a + mismatched-mask control fails readback). + - Drives a runtime-published graphics pair and a runtime-published slot-67 `.c67` compute request through + `startup_stream_consumer` -> `compile_dxil --requests` -> `d3d12_xs` (`load_translation` / `draw_translated` + and `load_compute_translation` / `record_translated_dispatch`) with the D3D12 debug layer enabled (`0` + errors), checking all 32 RGBA pixels and all 320 compute output dwords. + +```powershell +cmake --preset release +cmake --build --preset release --target compile_dxil startup_stream_consumer offscreen_check +ctest --preset release --no-tests=error -V -R "^native_startup_request_cache_(controls|warp|hardware)$" +``` + +## Limits + +- Startup runtime manifests are emitted only for stage bindings that the existing `d3d12_xs` manifest loaders + bind directly (for example, pairs without IA `InputLayout` vertex elements and compute shaders using raw table + buffers, 2D textures, 2D/2D-array float image UAVs, static non-comparison samplers, and root constants). +- Direct compute shaders carry `[WaveSize(32)]`; on Wave-4 WARP (`10.0.26100`), `load_compute_translation` + verifies the manifest, loads `.cs.cso`, and creates the desktop root signature before `CreateComputePipelineState` + declines `[WaveSize(32)]`, while full GPU dispatch and 320-word readback run on Wave-32 hardware (`AMD Radeon RX 9070 XT`). diff --git a/docs/experiments/native-v-xnor-b32.md b/docs/experiments/native-v-xnor-b32.md new file mode 100644 index 0000000000..97aea20fc9 --- /dev/null +++ b/docs/experiments/native-v-xnor-b32.md @@ -0,0 +1,22 @@ +# Direct DXIL `v_xnor_b32` + +Lowers `v_xnor_b32` (VOP2 `0x1e`, VOP3A `0x11e`, and VOP2 SDWA) in the native +direct-DXIL compute path (`src/gfx1013_direct_compute.inl` and +`src/gfx1013_compute_native.cpp`) as `~(S0 ^ S1)`. + +## Scope + +- Covers VOP2 VGPR+VGPR, VOP2 literal+VGPR, VOP3A VGPR+VGPR, and VOP2 SDWA + (`SEXT(BYTE_0)` with `WORD_0`) in a synthetic direct-compute fixture. +- Negative control: omitting the final bitwise invert (`S0 ^ S1`) differs from + the reference readback. +- Does not establish full-game execution. + +## Reproduction + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target compile_dxil native_store_replay +ctest --preset dev --no-tests=error -R '^native_v_xnor_b32_' -V +``` diff --git a/docs/experiments/native-vertex-vcc-join.md b/docs/experiments/native-vertex-vcc-join.md new file mode 100644 index 0000000000..c23853f960 --- /dev/null +++ b/docs/experiments/native-vertex-vcc-join.md @@ -0,0 +1,46 @@ +# Per-vertex VCC across a vertex-stage join in the direct DXIL frontend (#2906) + +[The fixture](../../tests/native_graphics_vertex_vcc_join_check.py) draws two source-built gfx1013 vertex +stages through the direct DXIL frontend and compares the readback with a per-vertex CPU model. + +## The two programs + +1. A root word that the harness supplies at draw time picks the arm, so the branch is uniform but not known + to the compiler. Each arm runs its own `SV_VertexID` compare into VCC and writes its own constant. After + the join one CNDMASK selects that constant or 0.5 per vertex. Both outcomes are drawn. The emitted IR + joins the two compares in a `phi` that feeds the select, and the test requires that. +2. One compare writes VCC and also splits the vertices between a THEN and an ELSE arm under saved EXEC. + After EXEC is restored a CNDMASK on the same VCC keeps the arm's constant or its negation, so one draw + holds both VCC values and both arm values. The frontend lowers these guest arms to per-vertex selects in + one block, so this program has a guest join and no IR join. + +## Readback and controls + +A desktop pixel stage reads the three vertex values with `GetAttributeAtVertex`, so each of the 8 pixels +reports every vertex without interpolation. The comparison is bit-exact. + +Each control redraws a changed program against the unchanged reference and must differ at all 8 pixels: + +- arm B of the first program loses its compare, so that edge carries the stale mask of an earlier compare. + Arm A still matches with the same change; +- a uniform `v0 == v0` compare overwrites the joined mask, in both arms of the first program and in the + second. + +## Command and result + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -V -R '^native_graphics_vertex_vcc_join_(warp|hardware)$' +``` + +On Windows 11 build 26300, Debug build, both tests passed with the debug layer enabled and no debug errors +or warnings: Microsoft Basic Render Driver (driver 10.0.26100.9818) and NVIDIA GeForce RTX 4090 +(driver 32.0.16.1088). Neither reported a capability skip. + +## Limits + +- Branches that need a whole-wave VCC vote are not drawn. Neither is a compare inside a per-vertex masked + arm, whose VCC on the other lanes depends on the rest of the guest wave. +- An adapter without per-vertex attribute support fails pipeline creation instead of reporting a skip. That + path has not been observed. +- The pixel stage is desktop HLSL. A translated pixel stage linked to this vertex stage is not covered. diff --git a/docs/experiments/pack-b32-f16-direct.md b/docs/experiments/pack-b32-f16-direct.md new file mode 100644 index 0000000000..5e36a62e99 --- /dev/null +++ b/docs/experiments/pack-b32-f16-direct.md @@ -0,0 +1,43 @@ +# v_pack_b32_f16 in the direct C++ DXIL path + +Covers the lowering of VOP3 `v_pack_b32_f16` (0x311) in `src/gfx1013_direct_compute.inl` (Fixes #2909) and +what was and was not verified. + +## Semantics + +- For each of the two sources, `op_sel` bit 11 (source 0) or 12 (source 1) picks the low or high half. +- abs clears bit 15 of the half, then neg toggles it, so neg after abs. +- D[15:0] is source 0 and D[31:16] is source 1. +- Only `lshr`/`and`/`xor`/`shl`/`or` on i32 are emitted. Signed zero and NaN payloads keep their exact bits. +- Both sources are read before the destination is written, so the destination may overlap a source. +- VGPR and SGPR sources are supported. + +## Refused forms + +Each is refused with a named diagnostic, with no approximation: clamp, omod, a destination `op_sel` bit (14), +`op_sel` bit 13 (third source), abs/neg on the third source, inline constants, a literal source. + +## Linux IR verification + +`python -B tests/native_pack_b32_f16_check.py ir ` evaluates the emitted IR and compares it +with `ref()` of `tests/startup_gfx2hlsl_pack_b32_f16_check.py`: 261 results match (issue words, control, 64 +`op_sel`/abs/neg forms x 4 value pairs, overlap, SGPR sources, refusals). The swapped-half and neg-before-abs +variants differ from the emitted bits. The dumper was built on Linux from the C++ sources with the Wine d3d12 +headers and a stub `wrl/client.h`. + +## Windows result (review of PR #2917) + +Windows 11 build 26300.9974, AMD Radeon RX 9070 XT, driver 32.0.32029.2010, MSVC 19.44.35221, `release` +preset, Windows SDK 10.0.26100 DXC, D3D12 debug layer not enabled. + +- `native_pack_b32_f16_ir`: passed. +- `compile_dxil ... gfx1013-container-ps` on the issue words: rc 0, and `dxc -dumpbin` reads the `.cso`. +- `native_pack_b32_f16_hardware`: not verified. `native_store_replay --direct` exits `0xC0000005` with no output, + the crash tracked in #2915. + +## GPU readback: no run yet + +`native_pack_b32_f16_check.py gpu` has not produced a result on any machine. Workgroups are 128 words apart so +that the 66 results of one group (64 forms, the SGPR case, the overlap case) never share a word with another +group; `group_offsets` asserts this. There is no WARP variant because `native_store_replay` takes the default +adapter. A hardware result is still needed once #2915 is fixed or on an adapter that does not crash. diff --git a/docs/experiments/packed-d16-x-uav-manifest.md b/docs/experiments/packed-d16-x-uav-manifest.md new file mode 100644 index 0000000000..341949361f --- /dev/null +++ b/docs/experiments/packed-d16-x-uav-manifest.md @@ -0,0 +1,44 @@ +# Published manifest names for D16 buffer stores + +`view_kind_name` names `packed_d16_x_uav` and `indexed_raw_srv`. A refusal that +mentions either kind prints that name. + +`format_compute_runtime_manifest` emits +`uav bufd16x table bytes 2` only when the binding +kind is `packed_d16_x_uav`, the binding is one register, and the payload is two +bytes. The dispatch reader accepts that line next to `bufhalf` and still checks +the view with `native_buffer_store_view`. A format, stride or flag that check +rejects keeps the reason `formatted D16 write has an incompatible typed buffer UAV`. + +A one-component `buffer_store_format` with the D16 bit is the half-buffer UAV. +It publishes `uav bufhalf table bytes 2`, the same +line the half-buffer fixture already requires. It does not publish `bufd16x`. + +The source-built fixture is `tests/startup_compute_packed_d16_x_uav_check.py`. +It has no title data. It checks that this store's manifest line is the half-buffer +line and not `bufd16x`. Thirteen lanes write `0x3c00 + lane` at byte 8 of a +sentinel buffer. An R32_UINT view, a stride other than 2, and a descriptor with +the swizzle flag set must refuse with +`a half buffer store requires matching format, stride and structured bounds`. +Before the manifest exists the dispatch is `no translation`. + +On Linux the reference half of the fixture runs with no compiler and no device: + +```bash +./out/pe-env/bin/python -B tests/startup_compute_packed_d16_x_uav_check.py +``` + +The compile and dispatch halves need Windows, DXC and the stand-in. WARP is the CI +adapter. A hardware adapter is selected the same way as the other `startup_compute_*` +dispatch tests and returns 77 when none is available. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_compute_(packed_d16_x_uav_|half_buffer_uav_)' -V +``` + +A 900 s start-up run of a retail title on the Windows test PC, runtime built from `main` +`aec2e08`, counted 23 shaders and 86,436 untranslated dispatches (5.7% of that run's +untranslated compute dispatches) whose published-route refusal was +`unsupported startup runtime manifest bindings: UAV kind unknown` for a one-component +D16 store. Those counts are from that run. Windows results for this correction are not +in this note. diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md new file mode 100644 index 0000000000..c3bca9b48d --- /dev/null +++ b/docs/experiments/patch-manifests.md @@ -0,0 +1,145 @@ +# Patch manifests: schema, loader and hash gate + +A patch manifest describes adjustments to a source-translated build without changing the input +file on disk. This first step defines the format and the loader, `tools/patch_manifest.py`. +Nothing applies a patch yet. Memory patches at load time, data patches in the file layer and +translator hooks will each come in their own change ([#3037](https://github.com/R0Y00/Xbox2Windows/issues/3037)). + +## Format + +```toml +[target] +input_sha256 = "" + +[[patch]] +id = "p001" +kind = "memory" +why = "" +remove_when = "" +rva = 0x1010 # first byte to replace +expect_sha256 = "" +bytes = "90c3" # the replacement, lowercase hex +``` + +- **Hash gate:** the manifest applies only to the file whose SHA-256 equals `input_sha256`. Any other input is refused with `manifest is for another input`. +- **Bytes already read:** `load_data(manifest, data)` is `load` for a caller that has already read the input: it hashes `data`, so the bytes that pass the gate are the bytes the caller goes on to use, even if the file changes in between. +- **No partial apply:** the whole manifest is validated, and the input hash compared, before the loader returns anything. One bad patch refuses the manifest. +- **Every patch** needs a unique `id`, a `kind`, and non-empty `why` and `remove_when`. +- **Strict keys:** unknown keys and missing keys are refused at every level, so a misspelled key fails instead of being ignored. +- **Nesting:** `tomllib` recurses once per nested array or inline table. A manifest nested past the interpreter's recursion limit is refused with `manifest is nested too deeply to parse`, and the CLI exits with status 1 instead of printing a traceback. +- **Kinds:** `kind` must be a string, and `memory` and `shader` are defined. `hook`, `data` and any other kind are refused as `not supported`. +- **Memory patches:** `bytes` must be non-empty, and every byte it replaces needs an RVA below 2^32: a 1-byte patch at `0xffffffff` is accepted, a 2-byte one is not. Two memory patches may not overlap. Whether the span lies in a mapped section is checked later, by the runtime stage. +- **Original bytes are never stored:** `expect_sha256` is a hash of the bytes the patch replaces. The loader only checks its shape; the memory stage will compare it with the mapped image. +- **Reporting:** the loader returns `manifest_sha256`, the SHA-256 of the manifest file's bytes, with the patch ids, for run reports to record. + +### Shader patches + +A shader patch names the translation files of one shader cache key, for the runtime to read instead +of the shader cache's. The loader checks their shape only. Reading and hashing the files, and +serving them, belong to a later consumer; none exists yet. + +```toml +[[patch]] +id = "s001" +kind = "shader" +why = "" +remove_when = "" +key = "0123456789abcdef" # the cache key, 16 lowercase hex digits +pipeline = "compute" # graphics, compute or mesh86 +revision = "x2w-startup-shader-29cs" +files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, + { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "" }] +``` + +| `pipeline` | `revision` form | Files the runtime reads | Required | +|---|---|---|---| +| `graphics` | `x2w-startup-shader-` | `.txt`, `.vs.cso`, `.ps.cso`, `.gs.cso` | `.txt`, `.vs.cso`, `.ps.cso` | +| `compute` | `x2w-startup-shader-cs` | `.txt`, `.cs.cso`, `.cs.hlsl` | `.txt`, `.cs.cso` | +| `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | + +The runtime reads a graphics key's `.gs.cso` for a published fixed rectangle pipeline, a compute key's `.cs.hlsl` when its `.txt` has no `native` line, and a mesh86 key's `.ps.cso` for a request with a pixel shader. All three stay optional in the manifest. + +- **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. +- **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. That consumer is the runtime, which runs on Windows, so a name Windows would not open as a file of that name in the directory is refused too: one with `<`, `>`, `"`, `|`, `?`, `*` or a control character, one ending in a dot or a space (Windows drops them), and a device name (`CON`, `PRN`, `AUX`, `NUL`, `COM0`-`COM9`, `LPT0`-`LPT9`, `COM` and `LPT` with a superscript 1 to 3, `CONIN$`, `CONOUT$`) in any case, alone or before an extension, as Microsoft's "Naming Files, Paths, and Namespaces" lists them. `sha256` is lowercase. +- **One patch per key:** two shader patches for the same `key` are refused. Shader patches take no part in the memory overlap check. + +Input-specific manifests stay local under `game-files/patches/`, which is gitignored. Do not +publish them or the hashes in them. + +## Check + +```bash +./out/pe-env/bin/python -B tests/patch_manifest_check.py +python -B tools/patch_manifest.py MANIFEST INPUT +``` + +On Windows: `ctest --preset dev --no-tests=error -R '^patch_manifest_controls$' -V`. + +The check builds a synthetic PE32+ at run time with `build_pe32_plus` from +`tests/call_evidence_check.py`. Its manifest replaces two bytes at the start of the `.rdata` section. + +- **Bound input:** the manifest loads with every field of `p001` as written, and the CLI prints the manifest hash and `p001`. +- **Wrong input:** the same image with its last byte flipped makes the CLI exit with status 1 and `manifest is for another input`, with nothing on stdout. An input file that does not exist also gives status 1, with a `patch manifest: [Errno ...]` message and no traceback. +- **Malformed manifests:** each of these is refused with its own message: a misspelled key, kind `hook`, a list or inline-table `kind`, a missing `why`, a blank `remove_when`, a duplicate id, overlapping patches, odd-length or empty `bytes`, a boolean `rva`, a 2-byte patch at `0xffffffff`, an upper-case `input_sha256`, an `input_sha256` or `expect_sha256` with trailing text, no patches, and a TOML syntax error. +- **Edge of the RVA range:** a 1-byte patch at `0xffffffff` loads. +- **Memory patches side by side:** four memory patches load when listed in descending RVA, three of them adjacent and one at RVA 0. Their ids follow neither the RVA order nor its reverse, so no order by id is an order by address. Two patches that share one byte are refused as an overlap, in either order. +- **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. +- **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. +- **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, compute with and without its `.cs.hlsl`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, a `file` with `*`, `?`, `<`, `>`, `|`, `"`, a tab or U+0001, `s001.txt.` and `s001.txt ` (trailing space), the device names `NUL`, `CON.txt`, `Com1`, `nul .txt`, `CONIN$`, `conout$.txt`, `COM` + U+00B9 and `lpt` + U+00B3 + `.cso`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. +- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and the optional ones are graphics `.gs.cso` for fixed rectangles, mesh86's `.ps.cso`, read only for a request with a pixel shader, and compute's `.cs.hlsl`, looked for only when the `.txt` has no `native` line (`NativeComputeOutput::unmarked`). +- **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. +- **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. +- **Mutations:** + + | Change | Result | + |---|---| + | Input hash comparison removed | The wrong-input test fails. | + | Overlap check removed | The overlap case fails. | + | String check on `kind` removed | Both wrong-type cases raise `TypeError`, and the CLI prints a traceback. | + | Span check removed | The 2-byte patch at `0xffffffff` is accepted. | + | Span check off by one (`>=`) | The 1-byte case at `0xffffffff` is refused. | + | `load_data` compares the target with itself | The flipped image is accepted by `load_data`. | + | Revision form check removed | The other-pipeline, number-less and leading-zero revision cases are accepted. | + | The runtime's graphics revision gets a suffix (`x2w-startup-shader-29b`) | The revision-form pin fails for graphics. | + | The runtime's graphics revision is bumped (`-29` to `-30`), loader untouched | Control: the check stays green. | + | Bare-name check on `file` removed | The six non-bare `file` cases are accepted. | + | Check for `<>"\|?*` in `file` removed | The six cases with one of those characters are accepted. | + | Control-character check on `file` removed | The tab and U+0001 cases are accepted. | + | Trailing dot or space check removed; or it checks the dot only; or the space only | Both cases; the trailing space; the trailing dot are accepted. | + | Device-name check removed | The eight device-name cases are accepted. | + | Device names matched case-sensitively | The upper- and mixed-case ones (`NUL`, `CON.txt`, `Com1`, `CONIN$`, `COM` + U+00B9) are accepted. | + | Device names matched as a prefix (`match`, not `fullmatch`) | `console.txt`, `nulls.cso`, `com10.txt` and `conin.txt` are refused. | + | Device name matched against the whole `file`, not the part before the first dot | `CON.txt`, `nul .txt`, `conout$.txt` and `lpt` + U+00B3 + `.cso` are accepted. | + | Trailing spaces kept on the part before the dot | `nul .txt` is accepted. | + | `CONIN$` and `CONOUT$` dropped from the device names | Both cases are accepted. | + | Superscript `COM` and `LPT` dropped from the device names | Both cases are accepted. | + | The runtime reads `.vx.cso` instead of `.vs.cso` (`d3d12_draw.inl`) | The files pin fails for graphics. | + | Required-file check removed | Both missing-file cases are accepted. | + | Same-key check removed | The two-patches-for-one-key case is accepted. | + | `RecursionError` no longer caught | The deep-nesting case raises `RecursionError`. | + | `SHA256.fullmatch` changed to `match` | The `input_sha256` and `expect_sha256` cases with trailing text are accepted. | + | Shader `KEY.fullmatch` changed to `match` | The 17-digit key is accepted. | + | `bytes` pattern allows zero digit pairs (`*`) | The empty `bytes` case is accepted. | + | Overlap check `<` changed to `<=` | The side-by-side case refuses its adjacent patches. | + | Spans no longer sorted before the overlap check | The side-by-side case refuses its descending order. | + | Spans sorted by id (`key=lambda s: s[2]`), ascending or descending, instead of by address | The side-by-side case refuses its patches, whose ids do not follow the addresses. | + | `rva` lower bound `0 <=` changed to `0 <` | The side-by-side case refuses its patch at RVA 0. | + | `why` dropped from a memory patch | The bound-input case finds a patch without `why`. | + | The CLI catches `ValueError` only | The missing input file ends in a traceback. | + +Measured on 27.11.2026 on Windows 11 Pro with Python 3.14: 3 tests, all passed. The `python-linux` +CI job ran the first version of the check with Python 3.12 and passed. + +With the nesting, shader, `load_data` and side-by-side memory cases: 9 tests, all passed on Linux +(Debian 13) with Python 3.13.5 and pefile 2024.8.26. Each mutation in the table above made the check +fail, and the revision-bump control stayed green. Not yet run on Windows. + +With the side-by-side ids out of step with the addresses: 9 tests, all passed on Linux (Debian 13) with +Python 3.13.5 and pefile 2024.8.26. The ascending id sort above, which passed before this change, and the +descending one now fail the check on the side-by-side case. A sort by span end (`key=lambda s: s[1]`) +still passes: for spans of at least one byte it flags an overlap exactly when the sort by start does, so +it is not counted as a survivor. + +With the Windows file-name refusals (review of `4968e124`): 9 tests, all passed on Linux (Debian 13) with +Python 3.13.5 and pefile 2024.8.26. Each of the twelve mutations of the refusal in the table above made the +check fail, and the 24 earlier loader mutations still did. Not run on Windows. diff --git a/docs/experiments/startup-compute-array-uav.md b/docs/experiments/startup-compute-array-uav.md new file mode 100644 index 0000000000..dfd17b2d3c --- /dev/null +++ b/docs/experiments/startup-compute-array-uav.md @@ -0,0 +1,48 @@ +# Startup compute FP32 and packed D16 array UAV binding + +Refs [#2742](https://github.com/R0Y00/Xbox2Windows/issues/2742). +Depends on the full-mask FP32 compute array image store lowering in +[#2744](https://github.com/R0Y00/Xbox2Windows/pull/2744) and the production +binding in [#2777](https://github.com/R0Y00/Xbox2Windows/pull/2777). Packed +D16 compute stores reuse that binding and the existing 2D two-VGPR lowering; +no new manifest or runtime path is needed. Pixel array stores remain refused. + +The production startup compute manifest consumer accepts +`uav N tex2da float table P O channels 4`. It requires an explicitly described +2D array UAV with a valid single-plane mip and slice range, retains the caller's +FirstArraySlice and ArraySize and refuses a plain 2D UAV before Dispatch. +The existing 2D and raw buffer paths are unchanged. Shader layer indices are +view-relative and are not clamped. + +The fixture publishes the encoded program through slot 67, translates it with +DXC, and binds a 32x8 RGBA32_FLOAT resource through slot 19. Its six physical +slices have distinct sentinels; the UAV selects four slices starting at +FirstArraySlice=1. Relative layers 1 and 3 write physical slices 2 and 4. +The actual translated dispatch goes through slot 14. After the fence, compare +all 6,144 words, including every adjacent and out-of-view slice. Full and +partial EXEC are checked for both layers. The wrong-layer and dropped-EXEC +controls must differ by 128 and 32 words respectively. A mismatched 2D view +must be refused with all 1,024 words untouched. + +The packed D16 case uses the same 32x8 six-slice allocation with +RGBA16_FLOAT and a 256-byte row pitch. Packed VGPRs 0xc0003c00 and +0x7bff3800 produce half encodings 0x3c00, 0xc000, 0x3800 and 0x7bff +(R/G/B/A). The reference compares all 6,144 raw halfwords after the fence. +For each relative layer (1 and 3), full and partial EXEC must have no +mismatches. The wrong-layer, dropped-EXEC, swapped first two halves, swapped +VGPRs and omitted-store controls must differ by 128, 32, 32, 64 and 64 +halfwords respectively; each mutated output is also compared with its own +CPU reference. An incompatible RGBA16_FLOAT 2D view must be refused with +1,024 halfwords unchanged. Before translation, all six slices must remain +unchanged. The source-built instruction sequences for both layers and EXEC +variants are checked against LLVM 15 with the D16 translation controls. + +Reproduce on Windows (source-built fixtures only): + +```powershell +cmake --build --preset dev --target startup_stream_consumer offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^startup_compute_dispatch_array(_d16)?_(warp|hardware)$' -V +``` + +No game input, retail program coverage, title execution or guest +out-of-bounds behavior is established. diff --git a/docs/experiments/startup-compute-builder-gate.md b/docs/experiments/startup-compute-builder-gate.md new file mode 100644 index 0000000000..a1734ef25d --- /dev/null +++ b/docs/experiments/startup-compute-builder-gate.md @@ -0,0 +1,59 @@ +# All-or-none gate for the BVH builder's compute stages + +The console ray-tracing structure builder is a set of compute programs from `XboxBvhBuilder.dll`. +Its stages feed each other through title memory; a stage that runs on data a missing stage never +wrote computes store offsets from garbage. In the observed failure, 14 of 35 translated stages ran +and the title died within a second on pointers that had become bounding-box bit patterns. + +`X2W_COMPUTE_BUILDER_GATE=1` makes the set run all or none. It is off by default and changes no +existing path when unset. + +## Identification + +At device slot 62, the gate resolves the caller module of the return address with +`GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)` and compares the basename with +`XboxBvhBuilder.dll`, case-insensitively. A compute pipeline is tracked only when that resolution +succeeds; an unresolved caller is left untracked rather than guessed. The header's pure classifier +and state machine are tested without a device or a title module. + +## Decision + +A builder Dispatch is allowed when every tracked builder pipeline has a real desktop PSO. On the +first builder Dispatch the gate makes the missing pipelines on the spot. If one cannot be made, the +builder is turned off for the rest of the run and the Dispatch is refused with a named reason. A +non-builder Dispatch is unchanged. The gate is keyed on the slot 62 wrapper's builder tag, not on +`compute_request_key`: slot 67 never receives that tag, so its request publication path is +unchanged. The gate is counted in the compute totals line as `builder gate refused N`. + +When the gate completes the set it also refreshes the recording's cached compute state +(`pipeline_real`, `compute_pipeline`, `compute_pipeline_root`) and binds the new desktop PSO, and +the matching desktop root when the title already bound it. Without that refresh the caller's own +`Dispatch` decision still sees the placeholder that was bound before the gate ran and drops the +first Dispatch. + +## Scope and limits + +This is a safety gate, not a translation. The slot 62 programs are console GPU code; the gate's +on-the-spot creation first requires a structurally valid desktop compute container and a desktop +root signature. A console DXIL program fails by name and latches the builder off, which is the +intended conservative result until the translation path publishes real compute PSOs. + +The runtime test loads a source-built `XboxBvhBuilder.dll` helper and calls the public slot 62 +path through it. In the incomplete-set mode two fake console pipelines are tracked, a direct +`Dispatch` and an indirect `ExecuteIndirect` are both refused with the gate enabled, and the same +direct call through a non-builder slot 62 wrapper is left untouched. In the completed-set mode two +desktop DXIL compute shaders are tracked, the gate reports `all have a desktop PSO`, and the first +direct `Dispatch` plus an indirect `ExecuteIndirect` with a placed argument buffer reach the list. +A separate run of the existing slot 67 request check with `X2W_COMPUTE_BUILDER_GATE=1` passes, so +request publication keeps its normal path. + +The helper test proves the caller-module tag, the wiring into both public Dispatch paths, and the +completed-set refresh on source-built desktop DXIL. It does not prove a translated builder set from +the title; the fake console container still fails desktop PSO creation by name and latches the +builder off, which is the intended conservative result. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_compute_builder_gate$' -V +ctest --preset dev --no-tests=error -R '^startup_compute_builder_gate_runtime$' -V +ctest --preset dev --no-tests=error -R '^startup_compute_builder_gate_request_warp$' -V +``` diff --git a/docs/experiments/startup-compute-comparison-sampler.md b/docs/experiments/startup-compute-comparison-sampler.md new file mode 100644 index 0000000000..fc1f3ccfbd --- /dev/null +++ b/docs/experiments/startup-compute-comparison-sampler.md @@ -0,0 +1,90 @@ +# Comparison samplers in a published compute manifest (#3075) + +The stand-in reads the published translation of a slot 67 compute request from `.txt` +(`load_compute_translation`, `src/startup_stubs/d3d12_compute_dispatch.inl`). It refused every `smpc` line there +with `a comparison sampler`. It now reads `smpc ` under the same index and whole-line +checks as `smp` and `smpl`, through `TranslatedSamplers::read_manifest_line`. `decode_statics` already turns the +line into a comparison static sampler for the draw path, and the compute root signature takes it the same way. +An `smpheap` line is still refused with `a sampler from the sampler heap`. + +## What this covers + +- Only `tools/startup/gfx2hlsl.py` writes `smpc` for a compute program today (`image_sample_c_lz` and + `image_sample_c` with a constant comparison sampler). Before this change the runtime refused that translation + when it loaded the manifest, so such a request could not be dispatched. +- The C++ compiler's publisher is unchanged. `format_compute_runtime_manifest` (`src/direct_compute_cache.cpp`) + returns no manifest for a comparison sampler, so `compile_dxil` publishes no compute `smpc` line. +- The in-process route (`X2W_NATIVE_SHADERS`, `translate_compute_natively`) is unchanged. It reads no manifest + lines and refuses every sampler, and every view that is not a raw buffer, before it reaches one. + +## Fixture + +[`tests/startup_compute_dispatch_texture_check.py`](../../tests/startup_compute_dispatch_texture_check.py) gains +a compared case. It is case A of +[`startup_gfx2hlsl_compute_check.py`](../../tests/startup_gfx2hlsl_compute_check.py) (group size 2x3x4, 3x2x2 +groups, one word stored per thread) with these instructions before the store: + +``` +s_mov_b64 s[20:21], 0 +s_mov_b64 s[22:23], 0 +s_mov_b32 s20, 0x8001012 +s_load_dwordx8 s[24:31], s[10:11], 0x40 +v_cvt_f32_u32_e32 v7, v2 +v_cvt_f32_u32_e32 v8, v0 +v_mov_b32_e32 v9, 0 +image_sample_c_lz v12, v[7:9], s[24:31], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_2D +v_xor_b32_e32 v5, v5, v12 +``` + +The five instructions that are new here were not assembled by llvm-mc. The check asserts that the Python decoder +reads them as written, that the HLSL holds +`v12 = U(r1.SampleCmpLevelZero(q0, float2(F(v8), F(v9)), F(v7)));` and that the manifest ends with +`smpc 0 0x8001012 0x0 0x0 0x0` (clamp in U and V, TRUNC_COORD, point filters, LESS). + +The consumer's new mode `dispatch-sampled-depth` binds a 2x1 `R32_FLOAT` texture with depths 1.0 (left) and 2.5 +(right). The reference is the thread's z id (0.0 to 3.0). u is its x id: 0 reads the left texel and 1 clamps to +the right one. The CPU model XORs the bits of 1.0f into a word where `reference < texel` and leaves the word as +case A wrote it otherwise. That is 144 of the 288 written words. The 32 words past them keep the sentinel. + +1. Before the translation is published, the Dispatch is refused and every word keeps the sentinel. +2. After `gfx2hlsl.py --pending`, all 320 words match the model and the debug layer reports no error. +3. Control: the same program with the manifest's word 0 changed to GREATER (`0x8004012`) matches the model of + `reference > texel` (108 words pass). The two models differ at 252 words, so the function bound is the + manifest's. + +The case replaces an older control in the same file, which rewrote an `smpl` line as `smpc` and expected the +refusal. + +## Command and result + +```powershell +.\tools\dev.ps1 +cmake --build --preset dev --target startup_stream_consumer +ctest --preset dev --no-tests=error -R '^startup_compute_dispatch_texture_(warp|hardware)$' -V +``` + +Measured on 27.11.2026: `main` at `e1ea515d` plus this change, Windows 11 build 26300.9974, Windows SDK +10.0.26100, DXC 1.9.2602.17, Debug build, D3D12 debug layer enabled. + +| Test | Adapter, driver | Result | +|---|---|---| +| `startup_compute_dispatch_texture_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS (18.81 s). The compared case matched all 320 words under LESS and under GREATER, with no debug layer error. | +| `startup_compute_dispatch_texture_warp` | Microsoft Basic Render Driver, 10.0.26100.9818 | PASS (7.72 s), with the same lines. | + +There was no capability skip. + +Negative control: with `src/startup_stubs/d3d12_compute_dispatch.inl` put back to `e1ea515d` and the same target +rebuilt, both tests fail in the compared case, after the cases before it pass: + +``` +AssertionError: smpc LESS: x2w-draw compute e9f1d94c2215f572 Dispatch(3, 2, 2) refused: a comparison sampler +``` + +## Not measured + +- A bilinear comparison filter, a border address mode, a 2D array and the other six functions. The fixture runs + point, clamp, LESS and GREATER on a 2D texture with one mip. +- A comparison sampler on the in-process route or from the C++ compiler's publisher. Both still stop before the + manifest reader, as listed above. +- Console behaviour. The comparison is the desktop sampler's. The function mapping is the draw path's + (`decode_sampler` in `src/startup_stubs/translated_sampler_bindings.h`). diff --git a/docs/experiments/startup-compute-native-dispatch.md b/docs/experiments/startup-compute-native-dispatch.md new file mode 100644 index 0000000000..2af49da9b7 --- /dev/null +++ b/docs/experiments/startup-compute-native-dispatch.md @@ -0,0 +1,104 @@ +# In-process compute translation in the stand-in (#2934) + +[The fixture](../../tests/startup_compute_dispatch_native_check.py) dispatches a source-built gfx1013 compute +program through the stand-in's device slot 67 and Dispatch path with `X2W_NATIVE_SHADERS` set, an empty shader +cache and no offline translator, and compares all 320 output words with a CPU reference. + +## Route + +1. Slot 67 creation publishes the request as before. +2. On the first Dispatch of the pipeline, `translate_compute_natively` + (`src/startup_stubs/d3d12_compute_dispatch.inl`) reads the request back with `x2w::read_compute_request`, + which checks the six parts against the key in the file name. It then runs the C++ frontend + (`x2w::translate_compute`, entry 0) and compiles the module with `ShaderDxilCompiler::runtime_worker`. +3. The entry values and views fill the same `ComputeTranslation` a published `.txt` fills. The existing + dispatch path then resolves the table descriptors, sets the resource states and records the Dispatch. + +Accepted: root constants, a raw table buffer loaded per lane and a raw table buffer stored to. These are the +bindings the fixture runs. Refused: every other view kind (a scalar buffer load included), a sampler, more than +32 entry values or inputs or 8 outputs, an adapter without 32-lane waves, and whatever the frontend refuses. The +stand-in logs the first 16 refusals of a process with their reason. A refused key is left to a published +translation. The in-process translation is tried once per key and before a published `.txt`. + +`NativeRecording` and `NativeDispatchStates` are not used. The dispatch path already allocates the descriptors +and tracks the states of these buffers. + +## Program and controls + +The program is case A of [`startup_gfx2hlsl_compute_check.py`](../../tests/startup_gfx2hlsl_compute_check.py): +two root constants, group size 2x3x4, 3x2x2 groups, one input word read and one word stored per thread. Its +`s_load_dwordx8` is replaced by two `s_load_dwordx4`, at table bytes 0 and 32. The C++ frontend reads a table as +32-byte records. It refuses case A as written (`unaligned descriptor table entry`), because that program takes +its second descriptor from table byte 16. The fixture checks the two replaced instructions with the Python +decoder, and the consumer's `dispatch-records32` mode writes the table with the output's descriptor at byte 32. + +1. Native: all 320 words match the case's CPU expectation (288 written, 32 left at the sentinel). The log names + the native translation. Afterwards the cache holds the request files and the compiler's own cache, and no + `.txt`, `.cs.cso` or `.fail`. +2. The same program over the plain table layout has no descriptor at byte 32. Its Dispatch is refused when it is + bound and every word keeps the sentinel, so the record at byte 32 is what the first run bound. +3. Unsupported workload: case A as written. The stand-in logs the frontend's reason, the Dispatch is refused with + `no translation` and every word keeps the sentinel. +4. Fallback: `gfx2hlsl.py --pending` then publishes both requests. With native translation still on, the next + run dispatches case A through the published translation and all 320 words match. +5. Order: the first program runs again with its published translation in the cache. The log still names the + native translation, and all 320 words match. + +Without 32-lane waves, step 1 instead checks that the native translation is refused by that name with every word +untouched. Step 2 is left out, steps 3 and 4 run, step 5 runs the first program through its published +translation, and the check exits 77. + +## Command and result + +```powershell +cmake --build --preset dev --target d3d12_xs_shim startup_stream_consumer compile_dxil native_wave_request_gpu offscreen_check +ctest --preset dev --no-tests=error -V -R '^startup_compute_dispatch_(native_)?(warp|hardware)$' +ctest --preset dev --no-tests=error -V -R '^native_wave_request_hardware$' +``` + +Commit `a58e08f9` on `cpp-migration` at `e3670100`, Windows 11 build 26300.9974, Debug build, D3D12 debug layer +enabled. + +| Test | Adapter, driver | Result | +|---|---|---| +| `startup_compute_dispatch_native_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS. All 320 words match after the in-process translation from an empty cache and again with a published translation in the cache. The plain table layout and case A are refused with every word untouched. No debug-layer error message. | +| `startup_compute_dispatch_hardware` | NVIDIA GeForce RTX 4090, 32.0.16.1088 | PASS (the published-translation route, unchanged). | +| `native_wave_request_hardware` | the same machine (the test prints no adapter line) | PASS. | +| `startup_compute_dispatch_warp` | Microsoft Basic Render Driver, 10.0.26100.9818 | PASS. | + +Capability skip, not a pass: `startup_compute_dispatch_native_warp` exits 77 on the Microsoft Basic Render +Driver 10.0.26100.9818, which reports no 32-lane waves. Before it exits, the check confirms that the native +translation is refused by that name with every word untouched, that case A is refused and then runs through a +published translation, and that the first program matches all 320 words through its published translation. + +The other WARP dispatch tests were run as a regression check and pass (9 tests): + +```powershell +ctest --preset dev --no-tests=error -V -R '^(startup_compute_dispatch(_.*)?|startup_slot67_indirect_dispatch|startup_compute_translate_e2e)_warp$' +``` + +## Limits + +- Compute only. Graphics pipelines are not translated in-process. +- A scalar buffer load, a texture, a sampler and the typed, half and indexed views are refused. This is the + in-process route. The published-manifest route (`.txt` from `compile_dxil --requests`) binds a + title's 1D, 2D, 2D-array and 3D texture SRV (`srv N tex1d|tex2d|tex2da|tex3d table R B`). For 1D, 2D-array + and 3D the title's view must be described, have the manifest's dimension and fit its texture, otherwise the + Dispatch is refused (on a dimension mismatch the draw path binds a null view instead). "Fits" is + `address_view_fits`: the view format is the storage format or a member of its typeless family, the mip and + slice range lie inside the texture, and ResourceMinLODClamp is 0. Cube texture SRVs are not published. +- One descriptor shape was dispatched: stride 4 and 320 records, for the input and for the output. +- An indirect Dispatch of a natively translated program was not run. +- A captured request starts with a 36-byte prefix of `v_nop` words before `s_inst_prefetch`. The route passes + entry 0. With `compile_dxil`, a synthetic prefix translates to the same bindings from entry 0 and from entry + 36. The fixture does not dispatch a prefixed program. +- Only the two adapters above were run, in a Debug build. `run.ps1` takes its stand-ins from the release build + directory by default, and no start-up run used the switch. The launcher switch was checked with stubs. +- An adapter whose lane range excludes 32 refuses every program. +- The result is not published, so each process translates a key again. The compiler's DXIL cache under + `\native` is reused. +- The GPU-check package ships `offscreen_check.exe`, which compiles the stand-in source without + `X2W_NATIVE_SHADERS`. That variant builds and `offscreen_warp` passes. The package script (`tools/package-gpu-check.ps1`) was run at + `89a75318` (the same code): the extracted package passes its WARP run on the Microsoft Basic Render Driver + 10.0.26100.9818 with 11 tests passing and 68 of 68 recorded shader cases. `bvh_wave64_warp` reports a capability + skip there (no 64-lane waves). diff --git a/docs/experiments/startup-compute-root-srv.md b/docs/experiments/startup-compute-root-srv.md new file mode 100644 index 0000000000..e44bece927 --- /dev/null +++ b/docs/experiments/startup-compute-root-srv.md @@ -0,0 +1,79 @@ +# Startup compute root SRV (`srv buf root `) manifest consumer + +Refs [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618), +[#2274](https://github.com/R0Y00/Xbox2Windows/issues/2274). +Follows the compute `global_load_dword` lowering in +[#2715](https://github.com/R0Y00/Xbox2Windows/pull/2715) (ticket `C500-01/031`). + +When a translated compute shader loads through a 64-bit root SRV pointer via +`global_load_dword`, `tools/startup/gfx2hlsl.py` emits `srv buf root ` +in the compute manifest (`.txt`) and lowers the read to +`ByteAddressBuffer r : register(t)` in the translated descriptor table. + +The production startup compute manifest consumer in +`src/startup_stubs/d3d12_compute_dispatch.inl` and command-list tracking in +`src/startup_stubs/d3d12_xs_device.cpp` now consume `srv buf root `: + +- Command-list slot 43 (`SetComputeRootShaderResourceView`) records the guest + address and a bound bit per compute root parameter on the open recording while + a compute root signature is bound. Binding a different compute root signature + in slot 33 (`SetComputeRootSignature`), closing the list (slot 9), or + resetting the list (slot 139) clears the recorded compute root SRV bindings; + re-binding the same compute root signature preserves them. +- `load_compute_translation` parses `srv %u buf root %d%n` (requiring an exact + whole-line match, `param >= 0`, and sequential `i == tr.srvs.size()`), and + rejects descriptor-word entry values (`stride`, `descword3`) that reference a + root SRV slot. +- At translated compute `Dispatch` (slot 14), `compute_root_srv_buffer` resolves + each `buf root ` input by verifying that `` in the bound compute + root signature has `D3D12_ROOT_PARAMETER_TYPE_SRV`, was set by slot 43 since + the compute root signature was bound or reset, has a non-null 4-byte-aligned + guest address at a 16-byte-aligned offset (`D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT`) + inside either a recording upload allocation (slot 148) or a live aliased + placed buffer in `COMMON` state (slot 133) with at least one whole dword + remaining, and does not alias an output UAV buffer. The resolved range is + bound as a raw `DXGI_FORMAT_R32_TYPELESS` `ByteAddressBuffer` view from that + offset to the end of its backing allocation or placed buffer (up to 16 MiB). + +## Verification + +`tests/startup_compute_root_srv_dispatch_check.py` (registered in +`tests/cmake/startup_compute_root_srv.cmake`) drives source-built gfx1013 +compute `global_load_dword` programs (1-root-SRV and 2-root-SRV variants) +through slot 67, slot 33, slot 43, slot 37/39, slot 35, and slot 14 in +`startup_stream_consumer` with `X2W_D3D12_DEBUG=1` on both `warp` and `hardware` +(`AMD Radeon RX 9070 XT`): + +- **Single and two-root-SRV dispatches:** 3x2x2 groups of 2x3x4 threads (288 + active lanes, 320 total output words) load at offset `0` and `+128` bytes from + one or two distinct placed input buffers (`srv 0 buf root 2` and + `srv 1 buf root 3`), including re-binding the same compute root signature, + non-zero byte offsets into placed buffers (`+16` bytes on root SRV 0, `+32` + bytes on root SRV 1) and recording upload memory (`+16` bytes via slot 148), + and out-of-bounds loads (`v4 + 128u` past the bounded 1,280-byte backing) + returning `0` rather than reading adjacent `0xdeadbeef` / `0xfeedface` + neighbor words in the same 64 KiB page. +- **Refusal controls:** malformed manifest lines (`root -1`, trailing tokens, + non-sequential SRV index, `udsrc ... stride` on a root SRV), unset root SRV + slot (first or second), root SRV cleared by `Reset` or by binding a different + compute root signature, wrong root parameter kind (`D3D12_ROOT_PARAMETER_TYPE_CBV` + at ``), null guest address, unaligned guest address (`addr + 2`), + non-16-byte-aligned interior resource offset (`addr + 4`), unmapped guest + address between placed buffers, non-aliased copied placed buffer, and + input-aliases-output-UAV hazard all refuse cleanly with their expected log + reasons and leave all 320 output sentinel words (`0xc5c5c5c5`) untouched. +- **Negative controls:** skipping `Dispatch`, swapping `srv 0 buf root 2` and + `srv 1 buf root 3` in the manifest, or dropping the `+ 128u` offset in the + translated HLSL changes all 288 active output words as predicted. + +Reproduce on Windows: + +```powershell +cmake --build --preset release --target d3d12_xs_shim startup_stream_consumer +ctest --preset release -j1 --no-tests=error -R '^startup_compute_root_srv_dispatch_(warp|hardware)$' -V +``` + +What remains a hypothesis: retail title compute dispatches that combine root SRV +pointers with unplaced host memory outside slot-133 placed buffers and slot-148 +recording upload allocations are not yet modelled here and remain refused until +a title call site establishes their backing contract. diff --git a/docs/experiments/startup-compute-volume-line-uav.md b/docs/experiments/startup-compute-volume-line-uav.md new file mode 100644 index 0000000000..0a3d4560e0 --- /dev/null +++ b/docs/experiments/startup-compute-volume-line-uav.md @@ -0,0 +1,14 @@ +# Startup compute stores to 3D and 1D UAVs + +The startup translator lowers full-channel compute `image_store` to +`RWTexture3D` with an integer XYZ address or `RWTexture1D` +with a scalar integer address. A 3D address can be a VGPR tuple or an NSA list. +Both forms use the fixed table descriptor and emit a `tex3d` or `tex1d` UAV +entry. Requests refused before this change are retried by `--pending`, so +the compute cache revision is unchanged. + +Dispatch uses the title's view at its selected mip. For 3D the shader's Z +coordinate is relative to `FirstWSlice`, and a W size of all ones selects +the remaining slices. The Dispatch fixture compares all mip-one texels +against a CPU reference and checks that a 2D view or an out-of-range W +selection leaves the texels unchanged. diff --git a/docs/experiments/startup-exit-report.md b/docs/experiments/startup-exit-report.md new file mode 100644 index 0000000000..ddc7d6b3b4 --- /dev/null +++ b/docs/experiments/startup-exit-report.md @@ -0,0 +1,55 @@ +# Startup exit report + +Refs [#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This reader answers a narrower question than +`triage_run.py`: how did one startup run end, and what was the last presented frame? + +## Command + +```powershell +python -B tools/startup/exit_report.py [--json ] +``` + +The directory is the one written by `tools/startup/debug_launch.py` or `tools/startup/run.ps1`. The tool reads +`events.txt`, `finished.txt`, `run.out`, `stderr.txt`, `stdout.txt` and `trap.log` when present. + +## Output + +The Markdown table reports: + +| Item | Source | +|---|---| +| Exit code | `EXIT_PROCESS` in `events.txt`, or `process exited with ...` in `finished.txt` | +| Classification | one of `clean exit`, `nonzero exit`, `exception stop`, `timeout`, `stopped by request`, `missing exit event` | +| End time | the timestamp of the exit, stop, timeout or stop-file record | +| Last present | the highest `x2w-d3d12 heartbeat: N frames presented in T s` sample | +| Last presented surface | the last `x2w-render presented surface` sample | +| First / last exception | only the 32-bit code and first- or second-chance | +| Observed exceptions | count after the loader, single-step, thread-name and debug-output first-chance events are excluded | + +The JSON form contains the same allowlisted fields. It never contains an input path, a module name, a raw +address, an exception parameter or free-form log text. + +Each log is read once, capped at 16 MiB, and only the capped text is parsed. `finished.txt` is parsed after +the other logs because it is authoritative for the final exit code and end time; a duplicate exit event in +`events.txt` cannot overwrite it. The highest present sample wins regardless of file order. + +## What it proves + +It distinguishes a process that returned 0 from one that returned 1, an exception stop, a timeout and a +stop-file request. It also names the last present sample, so an exit at 307.6 s can be compared with the last +presented frame at 301.8 s without opening the raw logs. + +It does not prove that the exit code came from the title rather than a runtime stub, and it does not identify +the code path that called `ExitProcess`. Those need a debugger breakpoint or a runtime-side hook. The tool is +the bounded receipt; it is not the fix. + +## Tests + +```powershell +python -B tests/startup_exit_report_check.py +``` + +The synthetic check covers a clean exit, a nonzero exit, an exception stop, a timeout, a stop-file request, a +missing exit event, filtered first-chance events, hostile paths and addresses, the highest present sample, +the 16 MiB cap, the `finished.txt` authority, a second-chance filtered code, and the JSON form. It is listed +in `tests/checks/python-linux/startup_exit_report.txt` for the Linux CI job. diff --git a/docs/experiments/startup-gather-implicit-mip.md b/docs/experiments/startup-gather-implicit-mip.md new file mode 100644 index 0000000000..0ae35b4c87 --- /dev/null +++ b/docs/experiments/startup-gather-implicit-mip.md @@ -0,0 +1,30 @@ +# Derivative-selected gather with a nonzero SRV base mip + +This differential for #1802 keeps UV at `(9/16, 9/16)` at the checked pixel. +The source-built gfx1013 shader routes the result of `image_get_lod` to +`image_gather4_l` using the existing startup translator. The four taps are +read back as RGBA32F. An 8×8 texture has three patterned levels, and the main +SRV exposes resource mips 1 and 2. + +| UV step per pixel | Relative mip | Resource mip | +| --- | ---: | ---: | +| 1/4 | 0 | 1 | +| 1/2 | 1 | 2 | + +The expected taps come from the texel pattern and are checked independently +against `image_gather4_lz` on one-level views of the two resource mips. Both +levels contain four distinct, interior taps at the chosen UV. A separate +`image_gather4_lz` draw on the original two-level view continues to read its +first visible mip. That control differs at all four taps when the derivatives +select resource mip 2. Desktop 2D Gather uses the top level of the view. +[Microsoft gather4 instruction reference](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/gather4--sm4-1---asm-) + +The fixture covers two exact integer mip selections with a constant point-mip +sampler and an ordinary 2D SRV. The guest implicit opcode still requires proof +of the guest mip selection. Fractional thresholds and RDNA hardware readback +are open. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^startup_gather_implicit_mip_(warp|hardware)$' -V +``` diff --git a/docs/experiments/startup-gfx10-linear-1d.md b/docs/experiments/startup-gfx10-linear-1d.md new file mode 100644 index 0000000000..86c7d66e8f --- /dev/null +++ b/docs/experiments/startup-gfx10-linear-1d.md @@ -0,0 +1,54 @@ +# Slot-70 one-dimensional textures in the console linear layout (0x100) + +[startup-gfx10-linear.md](startup-gfx10-linear.md) reads two-dimensional `0x100` textures through +device slot 70. A one-dimensional `0x100` description was still refused with +`reason=unsupported_description`, because `gfx10::supports` took only 2D textures and +`address_view_fits` had no 1D view. + +## Layout + +`Gfx10Lib::HwlComputeSurfaceInfoLinear` (Mesa 25.1.0, `src/amd/addrlib`, MIT) lays out a 1D surface +with the same rule as a 2D one, one row per mip: each mip is padded to 256 bytes and the mips are +stored from the smallest up. It returns `ADDR_INVALIDPARAMS` for a 1D surface taller than one row. +A 300-texel RGBA8 texture with 4 mips (300, 150, 75 and 38 texels, rounded up at each level) has +mip 3 at 0, mip 2 at 256, mip 1 at 768 and mip 0 at 1536. + +The change: + +- `gfx10_layout.h`: `supports` takes a 1D texture in the linear mode with a height of one and an + element of one texel. Block-compressed formats, 1D arrays and the tiled modes stay refused for 1D. +- `address_texture.h`: a 1D array is refused, since the draw uploads a 1D texture only when it is not + an array (`d3d12_draw.inl`). `address_view_fits` takes a `TEXTURE1D` view of a 1D texture that fits + the mip range with no LOD clamp. +- `d3d12_memory_srv.inl`: the desktop format check asks for `D3D12_FORMAT_SUPPORT1_TEXTURE1D` for a + 1D texture. + +## Results + +Build: `slot70/linear-1d`, stacked on `slot70/linear-layout` (ce2d6f50), dev preset (debug layer on). +Windows 11 Pro 10.0.26200, NVIDIA GeForce RTX 5090 (driver 32.0.16.1088) and Microsoft WARP. + +| Test | Result | +| --- | --- | +| `startup_gfx10_layout` | PASS: 15 round trips (2 new 1D linear shapes: RGBA8 sRGB 300 with 9 mips, R8 4096 with 13 mips), 15 refusals (new: 1D in `0x105`, 1D two rows high, 1D BC1, a 1D array), 22 address descriptions (new: a 1D texture is accepted, a 1D array and a desktop-layout 1D texture are refused), 33 views (new: the whole 1D chain, its last mip, past the chain, an LOD clamp, a 1D view of a 2D texture and a 2D view of a 1D texture) | +| `startup_gfx10_layout_linear_addrlib` | PASS: 349,547 sizes and element addresses match addrlib, now with three 1D textures (`ADDR_RSRC_TEX_1D`: RGBA8 sRGB 300 with 9 mips, R8 4096 with 13 mips, RGBA16F 1000 with 10 mips) | +| `startup_address_console_{warp,hardware}` | PASS: 3 new 1D draws through a `Texture1D` view are exact on all 65,536 pixels: RGBA8 300 with one mip, and its 4-mip chain viewed at mip 0 and at mip 2 | +| `startup_address_console_linear_unpadded_{warp,hardware}` | PASS (control): the 4-mip 1D chain with its mips packed without padding (mip 2 at 152 instead of 256) is published and all 65,536 pixels of the mip-2 draw differ; the 2D case is unchanged (63,488 differ) | + +Without the source change (ce2d6f50), the first 1D draw reads the null view: pixel (0,0) is +`00000000`, but `010300ff` was expected. + +Commands (PowerShell, at the repository root, after `. .\tools\dev.ps1`): + +```powershell +cmake --preset dev -DXBOX2WINDOWS_ADDRLIB_DIR=/src/amd/addrlib +cmake --build --preset dev +ctest --preset dev --no-tests=error -R '^startup_gfx10_layout' +ctest --preset dev --no-tests=error -R '^startup_address_console_(warp|hardware|linear_unpadded_(warp|hardware))$' -V +``` + +## Open + +- As for 2D, the rule is addrlib's desktop GFX10 rule; that console memory uses it for `0x100` is + inferred from the layout word, not measured on console hardware. +- 1D arrays and 1D textures in the tiled modes stay refused. diff --git a/docs/experiments/startup-gfx10-linear.md b/docs/experiments/startup-gfx10-linear.md new file mode 100644 index 0000000000..43bc91a5c5 --- /dev/null +++ b/docs/experiments/startup-gfx10-linear.md @@ -0,0 +1,56 @@ +# Slot-70 textures in the console linear layout (0x100) + +Device slot 70 publishes a texture by address. A description whose `Layout` is `0x100` (the swizzle +mode word for `ADDR_SW_LINEAR`) was refused with `reason=unsupported_description` unless it was a +single texel, because the extent of its rows was not established. This note establishes it from AMD +addrlib and reads such textures like the tiled console layouts. + +## Layout + +`Gfx10Lib::HwlComputeSurfaceInfoLinear` (Mesa 25.1.0, commit +[5c142e46](https://gitlab.freedesktop.org/mesa/mesa/-/blob/5c142e46f3f6e752ed745fd48912ebb8fad67145/src/amd/addrlib/src/gfx10/gfx10addrlib.cpp), +`src/amd/addrlib`, MIT) gives the linear mode: + +- The pitch of a mip is its width in elements, rounded up at each level (`GetMipSize`), then aligned + to `256 / element bytes` elements: 256 bytes. +- The mip rows are packed with no tail block. The mips run from the smallest to the largest, so the + largest mip comes last. +- A slice is the sum of its mips, and the array slices follow one another. + +`src/startup_stubs/gfx10_layout.h` restates this rule for two-dimensional textures. The rest of the +slot-70 console path is unchanged: view checks, the XG holds and the upload as desktop footprint rows. +One-dimensional and three-dimensional linear textures are still refused. + +## Results + +Build: `slot70/linear-layout` on main 6ee878d8, dev preset (debug layer on). Windows 11 Pro 10.0.26200, +NVIDIA GeForce RTX 5090 (driver 32.0.16.1088) and Microsoft WARP. + +| Test | Result | +| --- | --- | +| `startup_gfx10_layout` | PASS: 13 round trips (4 of them linear, including a 2-slice R8 chain and a 3-slice BC1 chain) and one hand-worked linear chain (a 100x10 RGBA16F texture with 3 mips: 32x3 elements at offset 0, 64x5 at 768, 128x10 at 3328, 13568 bytes a slice) | +| `startup_gfx10_layout_linear_order_control` | expected failure: with the largest mip first, all 6 offset and address checks fail | +| `startup_gfx10_layout_linear_addrlib` | PASS: 338,763 sizes and element addresses of 11 linear textures (R8 to RGBA32F, BC1, BC7, odd sizes, up to 9 mips and 3 slices) match `Addr2ComputeSurfaceInfo` and `Addr2ComputeSurfaceAddrFromCoord` with `ADDR_SW_LINEAR`; skips (77) without addrlib | +| `startup_address_console_{warp,hardware}` | PASS: 4 new linear draws are exact on all 65,536 pixels. They are RGBA8 100x40 (400-byte rows padded to 512); its 4-mip chain viewed at mip 0 and at mip 2; and BC1 200x96 (50 blocks padded to 64). The 7 earlier draws and the 3 held/late cases are unchanged | +| `startup_address_console_linear_unpadded_{warp,hardware}` | PASS (control): the same RGBA8 100x40 texture with rows written at 400 bytes is published, and 63,488 of 65,536 pixels differ | + +Without the `gfx10_layout.h` and `address_texture.h` change (main 6ee878d8), the first linear draw +reads the null view: pixel (0,0) is `00000000`, but `010300ff` was expected. There is also no +`published console layout` line in the log. + +Commands (PowerShell, at the repository root, after `. .\tools\dev.ps1`; addrlib fetched with +`tools/fetch_addrlib.py`): + +```powershell +cmake --preset dev -DXBOX2WINDOWS_ADDRLIB_DIR=/src/amd/addrlib +cmake --build --preset dev +ctest --preset dev --no-tests=error -R '^startup_gfx10_layout' +ctest --preset dev --no-tests=error -R '^startup_address_console_(warp|hardware|linear_unpadded_(warp|hardware))$' -V +``` + +## Open + +- The rule is addrlib's desktop GFX10 rule. That the console stores `0x100` textures with the same + 256-byte pitch is inferred from the layout word naming `ADDR_SW_LINEAR`; no console hardware + measurement backs it. +- One-dimensional linear textures are covered in [startup-gfx10-linear-1d.md](startup-gfx10-linear-1d.md). diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md new file mode 100644 index 0000000000..967256e65d --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -0,0 +1,87 @@ +# First `image_bvh_intersect_ray` slice: FP32 and binary16 box nodes + +`tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for +the two box-node forms: the 128-byte FP32 node (kind 5) and the 64-byte binary16 node (kind 4). The result is +four child pointers, with `0xffffffff` for a disabled child or a missed box. The helper performs the four slab +tests, clips against `ray_extent`, and sorts hits by entry distance only when bit 31 of descriptor DWORD 1 is +set. With sorting disabled each result remains in its original child slot, including holes. Sorted misses use +a positive-infinity key so that a valid hit at `FLT_MAX` still precedes them. + +The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, +`coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa +`radv_nir_rt_common.c` (MIT): inverse direction clamped to finite extremes, `tmin`/`tmax` from the three axes, +an inactive box whose `min.x` is NaN, `tmax >= max(0, tmin)`, `tmin < ray_extent`, and the five compare-exchange +stages that sort the four children. A child word of `0xffffffff` is a miss even when its stored box would hit. +The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (encoded in 256-byte units), reserved 54:40, +box growing 62:55, box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. + +The binary16 node has the same four child words at bytes 0..15 and four boxes of six binary16 values at +16..63. `f16tof32` widens each bound exactly before the same slab test. The inactive-box marker is still a NaN +in `min.x`. + +## Accepted slice + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` + for the eleven consumed dwords); +- a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, + size field (a count minus one in 64-byte units) whose decoded extent covers the node (one unit + for binary16, two for FP32; `size=0` is a one-unit span) and below 4 GiB; +- a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the + same 4 GiB relative address window; the entire node must fit within the 48-bit absolute address space; +- either value of the sort bit, and either value of the triangle return mode bit (bit 120); + it selects the triangle result layout and does not change a box result. + +The manifest names the node allocation with `srv bvh base 0x size 0x`, using the decoded +byte address for `base` and the unchanged descriptor size field for `size`. All four original descriptor +DWORDs are passed to the helper. For example, base field `0x1000` means byte address `0x100000`, and +`0x1008` means `0x100800`; both are aligned by construction. The host must bind a raw +`ByteAddressBuffer` at the decoded base covering `(size + 1) * 64` bytes. That host binding is not part +of this change. + +## Refused by name + +Every node kind other than 4 and 5, `image_bvh64_intersect_ray`, A16, +non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# +loaded at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that +does not cover the node, size bits above 4 GiB, a node address that wraps the 48-bit address space, +and reserved T# fields. The checks assert that a refusal emits no helper call and no destination +VGPR assignment. + +## Evidence + +```sh +python3 -B tests/gfx1030_bvh_box/check.py --model-only +python3 -B tests/startup_gfx2hlsl_bvh_check.py +``` + +The translator check compares synthetic nodes and rays against the independently existing binary32 +reference in `tests/gfx1030_bvh_box/bvh_model.py`. It checks the sort-bit negative control (word 0 +changes from `0x1d` to `0x25`), the three-hit FP32 sort-disabled result with its second slot still invalid +(`0x25, 0xffffffff, 0x2d, 0x35`), and the finite `FLT_MAX` hit with infinite extent. The binary16 fixtures +are packed as `binary16` bytes and read back through the same independent model, including a bound at 1.1 +that rounds to 1.099609375 so a ray extent between the two values proves `f16tof32` is used. It separately +checks the translation, full descriptor literals, and manifest for `0x1000`, `0x1008`, and a base using +the high byte of DWORD 1, for both node kinds. The top-of-address-space witness checks a valid node ending at +the 48-bit boundary and refuses a node whose start wraps to zero in the independent model, before binding a +resource or emitting a helper. The check also covers the named refusals and the actual emitted helpers' +mutation sites. It compiles the translated compute shader with DXC when available; without DXC it prints +`dxc compile: skip` and does not count that compilation as a pass. + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp +``` + +The dispatch mode compiles both helpers with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes four FP32 nodes, four binary16 nodes and twenty-one rays, and compares the +four result DWORDs for every case (1232-byte readback). All eight sorted FP32 cases, three unsorted FP32 +cases, eight sorted binary16 cases (including the rounded bound and both encoded bases) and two unsorted +binary16 cases pass on a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`) and on an +AMD Radeon RX 9060 XT (`1002:7590`, driver `32.0.32029.2010`), in both the dev and release presets. Its +negative controls remove miss filling, compact the unsorted slots, substitute `FLT_MAX` for the infinite +miss key, reintroduce the erroneous low-byte alignment check, and ignore the high byte of the encoded base +in the zero-base check. Each mutant must change its designated witness result; the compact and box16 +miss-fill controls use binary16 witnesses. + +This is a translator slice. It does not execute the native gfx1030 probe, does not establish the +host binding of the node allocation on a D3D12 device, and does not establish any title behavior. diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md new file mode 100644 index 0000000000..73e87d9eec --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -0,0 +1,81 @@ +# `image_bvh_intersect_ray` triangle nodes + +`tools/startup/gfx2hlsl.py` now lowers the 64-byte triangle node forms (kinds 0..3) of the 32-bit +`image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230), in addition to the FP32 and binary16 box nodes. + +## Node and test + +A triangle node is 64 bytes: five `float3` vertices at bytes 0..59 and one ID dword at byte 60. The +kind selects one of the four 8-bit maps in the ID dword. Each map holds `i` in two bits and `j` in +two bits; the third index is `(3 - i - j) & 3`. The kind also selects the base vertex triple, which +is the table in Mesa 25.1.0 RADV's `radv_bvh_triangle_node` (MIT): + +```text +kind 0: 0 1 2 +kind 1: 1 3 2 +kind 2: 2 3 4 +kind 3: 2 4 0 +``` + +The test is the watertight ray/triangle formulation from Woop, Benthin and Wald, as RADV uses it. +The helper projects the vertices onto the dominant ray axis, shears them, computes the three +barycentric numerators `u`, `v` and `w`, the determinant `u + (v + w)` and +`t = u*az + v*bz + w*cz` in binary32. A hit requires all three barycentrics to share a sign and +`t` to have the matching sign. The instruction does not test `ray_extent` for triangles. + +## Return and descriptor + +Triangle return mode 1 (bit 120 of the BVH T#, bit 24 of descriptor DWORD 3) returns the four words +`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. For triangle nodes, +return mode 0 and every other reserved word-3 bit are refused by name before any HLSL is emitted. +Box nodes (kinds 4 and 5) ignore bit 24 because one T# can cover both node types; every other +word-3 bit is still refused for them. + +The accepted slice uses: + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form; +- a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, + size field (a count minus one in 64-byte units) whose decoded extent covers the node; `size=0` is + a one-unit span, and the field stays below 4 GiB; +- a constant node pointer whose low three bits are 0..3 and whose address is inside the descriptor + size and the 48-bit absolute address space; +- either value of the sort bit; it is ignored for triangles. + +The manifest still names the allocation with `srv bvh base 0x size 0x`, using the +decoded byte address for `base`. The host binds `(size + 1) * 64` bytes. That binding remains +outside this change. + +## Refused by name + +Return mode 0, every node kind other than 0..3, `image_bvh64_intersect_ray`, A16, non-sequential +addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded +at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that does not +cover the node, size bits above 4 GiB, a 48-bit node wrap, and every reserved T# field. The checks +assert that a refusal emits no helper call and no destination VGPR assignment. + +## Evidence + +```sh +python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py +python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py dispatch warp +``` + +The check reuses the 119 triangle witnesses in `tests/gfx1030_bvh_box/check.py` and the independent +model in `tests/gfx1030_bvh_box/bvh_model.py`. These witnesses come from the CPU model (#2921), not a +hardware capture; the dispatch shows that the HLSL matches the model, not RDNA 2 hardware. It covers +all four kinds, each of the four ID map bytes, edge and vertex hits, outside and behind rays, zero +direction and negative zero, `t = 0`, `extent = 0`, 1024x scaling in both directions, degenerate and +malformed nodes, and the unknown kinds 6 and 7 (instance and procedural in the model). + +The dispatch writes 71 unique triangle images at 64-byte offsets, runs the emitted helper for all +119 witnesses, and compares all 476 result words. It passes on WARP (`1414:008c`, driver +`10.0.26100.10068`) and on an AMD Radeon RX 9060 XT (`1002:7590`, driver `32.0.32029.2010`), in +both the dev and release presets, with `dxc -Gis` matching the runtime's strict-IEEE compile. Four +mutants change the determinant sign, the ID shift, the `u` term and the miss words; each must change +at least one witness. The existing box32/box16 tests still pass 6/6 in both presets. + +This is a translator slice. It does not bind the node buffer on a D3D12 device, does not execute the +native gfx1030 probe, and does not establish title behavior. The runtime manifest loader does not yet +consume the `bvhbase` line, so a real dispatch is refused rather than bound at a wrong address. + diff --git a/docs/experiments/startup-gfx2hlsl-cselect-descnum.md b/docs/experiments/startup-gfx2hlsl-cselect-descnum.md new file mode 100644 index 0000000000..1e33a3f2fc --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-cselect-descnum.md @@ -0,0 +1,87 @@ +# Scalar select on descriptor-derived data in gfx2hlsl compute stages (#2618, the C500 rows) + +In 250 compute rows of the C500-01 and C500-02 batches, the recorded refusal is `numeric use of sX holding descnum` +at `s_cselect_b32 sX, 0, sX`. Before this change, `Stage.scalar_select` in `tools/startup/gfx2hlsl.py` read both +sources as run-time values. A number computed from a buffer descriptor (`descnum`) has none, so the select refused. + +## Contract + +A select between descriptor data and zero can disable a buffer by zeroing its size. On the console such a buffer +returns zeros. A lowering that keeps only the descriptor arm would read real data instead. So in a compute stage, +`s_cselect_b32 sD, a, b` into an SGPR, where one source holds `descnum` and each other source is a constant, emits +no HLSL. sD holds `('descnum', 'cselect', offset, arm a, arm b)`: both arms and the offset of the select, whose +SCC picks one. + +Nothing reads that symbol as a value: + +- A numeric read still refuses with `numeric use of sD holding descnum`. This covers VALU and SALU sources, compares, + m0, store data and lane writes. +- `s_mov_b32` and `s_mov_b64` copy the symbol. Any other scalar ALU instruction with it in any register of a source + (the high word of a 64-bit pair too) refuses with ` on a select of descriptor data` + (`Stage.refuse_select_source`). It would otherwise become a plain `descnum` or an in-place edit of a descriptor + word, which loses the arm. This also covers the structured-to-raw conversion when its stride comes from such a + select. +- An access whose descriptor operand has the symbol in any word refuses with + `descriptor operand s[N:M]: sK holds a select of descriptor data` (`Stage.select_word`, called by + `Stage.descriptor`). On main b505c32b a buffer load ignores edits to words 1–3 of its descriptor (#2901), so + without this check a copied select would reach the load with the zero arm dropped. +- In compute, an access whose descriptor operand holds a word joined at a branch target after its first word + refuses with `descriptor operand s[N:M]: sK holds a word joined at a branch target` (`Stage.joined_word`). A join + of different symbols leaves only that mark, so a select that reaches a descriptor word on one path, or through a + loop back edge, would otherwise be dropped. This also refuses compute joins that bring two different non-select + words there. Main translates those, ignoring the difference, as in #2901. +- The select still refuses with `scc from descriptor data in s_cselect_b32` when its SCC came from an ALU + instruction on descriptor data, because that SCC is not emitted. + +Unchanged: `s_cselect_b64`, an m0, exec or vcc destination, a raw descriptor word or a pointer as a source, a +run-time register next to the `descnum` source, and every non-compute stage. + +A row only gets past the select if sX is dead afterwards or is only copied. Where sX is read later, the refusal moves +to that read. The packets record only the first refusal, so how often each case occurs is not known yet. + +## Checks + +`tests/startup_gfx2hlsl_cselect_descnum_check.py` splices synthetic instructions into case A of +`tests/startup_gfx2hlsl_compute_check.py`. The decoder must print the expected text for each one. + +- Accepted: the select with its result dead, in both source orders, with a literal source and on an extracted + stride. The HLSL may differ from case A only by the compare's `scc` line, and sD must hold both arms and the offset. +- Refused, each checked by its reason: every later use listed above, a copy into word 1, 2 or 3 of the load + descriptor (also through a second copy), a copy into the store descriptor, and SCC from descriptor data. +- Branches: the select writes no HLSL variable, so a join must not turn sD back into a run-time register. A read + after a forward join where one path skips the select, and a read at a loop head reached by a back edge after the + select, both refuse with `numeric use of s21 holding joined at a branch target`. The same forward join with a + run-time write in place of the select translates. +- Descriptor words through a join, from the #2903 review: a load after a join where one path selects into word 2 + of its descriptor, and the same select at the bottom of a loop whose head is the load, refuse as joined words. + The same join with the loaded word on both paths, and the same loop without the select, translate. A select in + the high word of `s_or_b64 s[14:15], s[20:21], 0` refuses. +- Only buffer load and store operands are exercised for the descriptor-operand refusal. Image, sampler and + `s_buffer_load` operands go through the same `Stage.descriptor` check but have no control here. +- Still refused as before: the unchanged forms above, in the compute stage and in the vertex and pixel probe stages. +- Negative controls, each a mutated translator that must fail a named check: + - `zero-arm-dropped`: the select keeps only its `descnum` source. The structured-to-raw conversion with the + selected stride then translates. + - `load-check-removed`: `select_word` finds nothing. A load through a copied select then translates. + - `alu-check-removed`: `refuse_select_source` accepts everything. An ALU copy into word 2 then reaches the load. + - `join-check-removed`: `joined_word` finds nothing. The load after the join, and the load at the loop head, then + translate. + - `high-word-unchecked`: `refuse_select_source` sees only the low word of each source. The `s_or_b64` case then + translates. + +```powershell +python -B tests/startup_gfx2hlsl_cselect_descnum_check.py +ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_cselect_descnum_(controls|warp)$" -V +``` + +The `warp` and `hardware` tests translate case A with the dead select, compile it with DXC `cs_6_0`, dispatch it +and compare all 320 words with case A's reference. + +Measured on Windows 11 build 26300 with Python 3.14 at the commit that adds this note (base b505c32b): the controls +pass (41 first-pass checks, and each of the five controls fails its named check). On b505c32b the same file fails +20 of its 34 first-pass checks. The four accepted cases are refused at the select, and 16 later-use, branch and +review checks get that refusal instead of their own reason. The mutation phase cannot run there, because the helpers +don't exist yet. + +Still a hypothesis: which later use of sX matters in the C500 rows. The packets don't show the instructions that +produce sX, write SCC or read sX afterwards. diff --git a/docs/experiments/startup-gfx2hlsl-pixel-first-lane.md b/docs/experiments/startup-gfx2hlsl-pixel-first-lane.md new file mode 100644 index 0000000000..a286b66c94 --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-pixel-first-lane.md @@ -0,0 +1,61 @@ +# First active lane in gfx2hlsl pixel stages (#2618, the F rows) + +`s_ff1_i32_b32 sD, exec_lo` gives the index of the lowest lane in EXEC, and `v_readlane_b32 sX, vY, sD` copies `vY` +from that lane whatever EXEC says (RDNA 2 ISA, S_FF1_I32_B32 and V_READLANE_B32; in wave32 the lane select uses bits +4:0). Together they read `vY` from the first active lane. `tools/startup/gfx2hlsl.py` folded the `s_ff1` only at +compute dispatch entry (#2389), and refused it in a pixel stage with "s_ff1_i32_b32 of exec_lo outside compute". + +## Lowering and contract + +The contract is the one of the wave reductions ([the note](startup-gfx2hlsl-wave-reduce.md)): the console packs +pixels into waves in its own way, so a correct program cannot depend on which pixel is first. The pair becomes +`WaveReadLaneFirst(vY)` over the active lanes of the desktop wave. The lane number itself has no desktop meaning, so +`sD` is a symbol with no run-time value. Each read of it up to its next write must be the lane select of a +`v_readlane_b32`, and every other read is refused, for example a shift, a copy to another SGPR or a move to a VGPR. + +It is accepted only where the one-lane model knows the whole wave's EXEC: + +- a straight-line pixel stage (no branches); +- EXEC still the entry mask at the `s_ff1` and at each readlane, with no `s_wqm` before them. On the console the + helper lanes are then out of EXEC, and on the desktop wave operations leave them out; +- a readlane source that is an ordinary VGPR, not a `v_writelane_b32` spill slot; +- no `exec_hi` or 64-bit `exec` operand in the program. The decoder prints wave32 syntax, and in wave64 `exec_lo` is + half the wave: an empty low half gives -1, which a readlane reads as lane 63. + +An EXEC that is changed and then restored before the readlane is refused although it is the entry mask again, because +the one-lane model no longer knows that. That refusal is conservative. + +## Checks + +`startup_gfx2hlsl_pixel_first_lane_controls` runs the source pair on a 32-lane model written from the ISA text, for +500 random EXEC masks: the readlane result is the input of the lowest active lane. The controls cover three cases +that translate: + +- the pair; +- two reads of one first lane; +- a lane number overwritten after its readlane and then read as a number. + +They also check every refusal by its reason, and that vertex and mesh stages keep the "outside compute" refusal. The +controls run in the Linux `python-linux` job (`tests/checks/python-linux/startup_gfx2hlsl_pixel_first_lane.txt`), and +the `binary` mode in the `pixel-binary` job (`tests/checks/pixel-binary/startup_gfx2hlsl_pixel_first_lane.txt`). + +`startup_gfx2hlsl_pixel_first_lane_{warp,hardware}` draw the triangle of the wave reduction test over 32 x 32 pixels. +The test replaces the fourth channel of the translated stage with the lane index, the lane count and +`WaveActiveMin` of the pixel id. That names the wave without using the intrinsic under test. The test then reads the +target back through `offscreen_check --startup-pixel-dump`. Each covered pixel is compared with the input, or the +packed position, of the covered pixel with the lowest lane index in its wave. Planted errors in the translated text +must fail: + +- the lane's own value; +- the largest value of the wave; +- the first lane of the quad, which is a helper lane where the quad is partly covered; +- the lane after the first. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_pixel_first_lane' -V +python -B tests/startup_gfx2hlsl_pixel_first_lane_check.py binary +``` + +WARP runs 4-lane waves (one quad per wave), so on WARP the reference only separates covered lanes from helper lanes +within a quad. Only a hardware adapter picks a first lane across quads. This does not measure console behavior or a +title. Whether the F rows of #2618 stop at this pair needs a replay against the captured requests. diff --git a/docs/experiments/startup-gfx2hlsl-pk-minmax.md b/docs/experiments/startup-gfx2hlsl-pk-minmax.md new file mode 100644 index 0000000000..351ce797c9 --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-pk-minmax.md @@ -0,0 +1,27 @@ +# Startup packed binary16 min/max + +The startup translator lowers `v_pk_min_f16` and `v_pk_max_f16` on gfx1013. +Each source is a single VGPR, numeric SGPR, 32-bit hex literal, or inline +integer zero. The inputs are packed words. `op_sel` selects each source's +half for the result's low half and `op_sel_hi` selects each source's half for +the result's high half. The defaults select the low and high halves +respectively. Other modifiers and source forms are refused. Packed add, mul +and fma still require VGPRs. + +The helper strips the binary16 sign and compares the remaining encoding +against infinity to identify NaNs. One NaN yields the other operand's +encoding. Two NaNs yield the chosen canonical quiet NaN `0x7e00`. The +two-NaN payload choice has no hardware confirmation. Numeric comparison uses +ordered integer keys and returns the original bits. In either operand order, +min chooses negative zero and max chooses positive zero when the signs +differ. Equal zeros retain their sign. + +The Python controls check emitted HLSL and operand refusals. The WARP and +hardware draw modes use a source-built gfx1013 fixture and compare both halves +with an independent CPU reference, including signed zeros, NaNs, infinity, +subnormals and literal and SGPR selector flips. + +```sh +python -B tests/startup_gfx2hlsl_pk_minmax_check.py +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_pk_minmax' +``` diff --git a/docs/experiments/startup-gfx2hlsl-wave-reduce.md b/docs/experiments/startup-gfx2hlsl-wave-reduce.md new file mode 100644 index 0000000000..047964de0e --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-wave-reduce.md @@ -0,0 +1,106 @@ +# Whole-wave reductions in gfx2hlsl pixel stages (#2125 item D) + +The mirror steps of a reduction read lanes outside the pixel quad, which the one-lane model cannot prove, so +`tools/startup/gfx2hlsl.py` recognises the whole wave32 chain instead of its instructions, in the three shapes the +two censuses in [#2125](https://github.com/R0Y00/Xbox2Windows/issues/2125) report for every wave32 chain. + +## The shapes + +Each chain is `s_or_saveexec_b32 sS, -1`, the identity fill `v_cndmask_b32_e64 vT, , vX, sS` (the input +where the saved mask has the lane, the identity elsewhere), the DPP16 steps `quad_perm:[1,0,3,2]`, +`quad_perm:[2,3,0,1]`, `row_half_mirror` and `row_mirror` on `vT, vT, vT` (full row and bank masks, `fi:1`), +`v_permlanex16_b32 vP, vT, 0, 0`, the combine of `vT` and `vP`, `s_mov_b32 exec_lo, sS` and +`v_readlane_b32 sD, vT, 31`. The operations are `v_or_b32`, `v_min_u32` and `v_max_u32`, with identities `0`, `-1` +and `0`. + +- The or and max chains read lane 31 right after the restore. +- The min chain reads it later: after its restore come one `v_cndmask_b32_sdwa`, the `s_or_saveexec_b32 sS2, -1` of + a max chain, and only then its readlane, which the max chain carries before its own fill. Readlane ignores EXEC, so + that readlane still sees the min result as long as nothing in between writes `vT` (refused if it does) and the + readlane does not overwrite `sS2` (refused too). The `v_cndmask_b32_sdwa` keeps its own handler under the restored + EXEC. +- A readlane right after the restore is also accepted for a min chain alone. + +With every lane enabled each lane ends with the operation over the lanes that were active, the others adding the +identity (so `fi` and `bound_ctrl` have nothing to decide), and `vT` and `sD` become one `WaveActiveBitOr`, +`WaveActiveMin` or `WaveActiveMax` of `vX`, emitted at the restore, with `sD` copied from `vT` at the readlane. + +## Contract and helper lanes + +The console packs pixels into waves in its own way, so a correct program cannot depend on which pixels share a wave; +the contract is the active lanes of the desktop wave. The chain is accepted in a pixel stage whose EXEC is still the +entry mask and was not widened by `s_wqm`, so on the console the helper lanes hold the identity, and on the desktop +the wave operations leave them out (the draws check it). The chain itself stays straight: no branch instruction and +no branch target inside it, and EXEC is saved and restored as in the shapes above. A uniform branch (an SCC branch +the translator has proved uniform, or an unconditional branch) may sit before the chain, after it, or both. Every +lane takes that branch together, so the lanes that reach the chain are the whole entry mask, which is what +`WaveActive*` reduces. + +## Refusals + +The fill is one table, `Stage.WAVE_REDUCE_FILLS`, holding that form only. Everything else that starts like a chain +(an `s_or_saveexec` with -1 followed within 16 instructions by a mirror step or `v_permlanex16_b32`) is refused with +its reason: + +- wave64; another fill (another constant, another saved mask, a copy, none); a wrong identity; +- missing or reordered steps, another DPP control, partial row or bank masks, other or mixed operations; +- lane selects other than 0, 0 or `op_sel` on the permlane; a readlane lane other than 31 or before the restore; EXEC + not restored from `sS`; +- for the later readlane: another instruction in place of the `v_cndmask_b32_sdwa`, `vT` rewritten before it, a + missing readlane, a readlane that overwrites the max chain's saved EXEC, a later readlane in an or or max chain, a + chain other than max carrying it, an `s_or_saveexec_b32` after it that starts no chain; +- a branch target inside the chain; a branch instruction inside the chain; a non-uniform branch that changes EXEC + inside the chain (`s_and_saveexec_b32` together with `s_cbranch_execz` / `s_cbranch_execnz` before the readlane); + any other branch that is not proven uniform, before the chain or after it; a vertex stage; `s_wqm` before the + chain; and `vP` (which holds the other row) read after the restore before a VALU rewrites it. A uniform branch + outside the chain is accepted. Wave64 stays refused, including when a uniform branch precedes it. + +Eight of these are conservative: reordered steps, other permlane selects, `op_sel`, lane 30, the readlane before the +restore, another instruction in place of the `v_cndmask_b32_sdwa`, a later readlane in an or or max chain (the +fixture uses max), and an or chain carrying it. The lane model shows they would still reduce; they are refused +because the censuses do not show them. + +## Checks + +`startup_gfx2hlsl_wave_reduce_controls` checks that the fill table holds the census form only. The fixtures are the +three shapes: or, min and max alone, min then max interleaved with `vT` shared by the two chains and with a `vT` of +its own, min then max each read at once, and an or followed by the interleaved pair. The source chains run on a +32-lane model written from the ISA text (DPP16 sources with `fi`, the permlane row exchange, readlane, the SDWA +select), not from the lowering: for random EXEC masks the readlane result is the reduction of the active lanes, and +each refused mutation either is not (wrong identity, no fill, the input copied without the identity, missing step, +`row_shr:1`, mixed operations, partial row mask, missing later readlane, `vT` rewritten before it, the max chain's +saved EXEC overwritten) or is one of the conservative refusals. A planted error on the model, the min readlane moved +after the max fill with `vT` shared, must not be the min. The controls check the translation of every fixture, with +one wave operation per chain in program order and the `v_cndmask_b32_sdwa` between them, four accepted variants +(`bound_ctrl`, no `fi`, the combine sources the other way round, a VOP3 combine), a uniform branch before each +operation and after (and both around) a max chain, and every refusal by name. The uniform branch is +`s_cmp_eq_u32` of a constant with itself and `s_cbranch_scc0` over one `s_nop`: the compare is true, so the branch +is not taken, and the other edge lands on the chain, so every lane runs it. A mutant that replaces the lowered +`WaveActiveMax` with the lane's own value is not that lowering. Putting the straight-line refusal back (the check +wraps the matcher) refuses the uniform-branch programs and still lowers the straight-line chain. These +controls run in the Linux `python-linux` job (`tests/checks/python-linux/startup_gfx2hlsl_wave_reduce.txt`), and the +`binary` mode in the `pixel-binary` job (`tests/checks/pixel-binary/startup_gfx2hlsl_wave_reduce.txt`). + +`startup_gfx2hlsl_wave_reduce_{warp,hardware}` draw a triangle over 32 x 32 pixels for each operation, for the +interleaved pair, and for a max chain with a uniform branch before it and an or chain with a uniform branch after +it. The input is `1 << x` for or and a different word per pixel otherwise, and the pair also writes the +`v_cndmask_b32_sdwa` result. The desktop packing cannot be known in advance, so the test replaces the fourth channel +of the translated stage with the lane index, the lane count and `WaveReadLaneFirst` of the pixel id, reads the target +back through `offscreen_check --startup-pixel-dump`, groups the covered pixels by wave and compares each result with +the operation over the inputs of the covered pixels of its wave. The triangle leaves 30 quads partly covered. Planted +errors in the translated text must fail: another operation, the lane's own value and the first lane's value for +each operation, and signed for unsigned where that rewrite changes the program (min and max, including the +uniform-branch-before max; `v_or_b32` has no signed form, so that plant is not applied to the or draws, including +the uniform-branch-after or chain). For the pair: the min readlane lowered after the max, min and max swapped, and +the `v_cndmask_b32_sdwa` dropped. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_wave_reduce' -V +python -B tests/startup_gfx2hlsl_wave_reduce_check.py binary +``` + +The `binary` mode assembles every fixture and compares the words; the programs with a branch are assembled to an +object (`-filetype=obj`) and compared with its `.text`, because `-show-encoding` prints a branch to a label with its +offset still unresolved. WARP runs 4-lane waves (one quad per wave), so only +a hardware adapter reduces across quads. This does not measure console behavior or a title, and wave64 chains are +the next slice. diff --git a/docs/experiments/startup-image-cube.md b/docs/experiments/startup-image-cube.md new file mode 100644 index 0000000000..a4f6b9d85d --- /dev/null +++ b/docs/experiments/startup-image-cube.md @@ -0,0 +1,83 @@ +# Cube image sampling in gfx2hlsl (#2943) + +`tools/startup/gfx2hlsl.py` lowers `image_sample`, `image_sample_lz`, `image_sample_l` and `image_sample_b` with +`dim:SQ_RSRC_IMG_CUBE` to `TextureCube` `Sample`, `SampleLevel` and `SampleBias` (outside a pixel stage the +implicit-LOD form samples level 0 and the bias form is refused, as for 2D textures), and +writes the manifest kind `texcube` for the binding. Before, the stage was refused with +`image dimension SQ_RSRC_IMG_CUBE`. + +## The address + +On gfx10 a cube sample takes three address dwords after any bias: the face coordinates `s` and `t` and the face +id. Mesa's `prepare_cube_coords` (`src/amd/common/nir/ac_nir_lower_tex.c`, read at Mesa 25.0.7 through the +`openbsd/xenocara` mirror, commit `d31967950e30`) builds `s = sc / |ma| + 1.5` and `t = tc / |ma| + 1.5` from +`v_cubesc`, `v_cubetc` and `v_cubema`, and a cube-array id as `8 * layer + face`. LLVM 15.0.7 +`ConstantFoldAMDGCNCubeIntrinsic` (`llvm/lib/Analysis/ConstantFolding.cpp`) defines `v_cubema` as twice the signed +major coordinate, so `s` and `t` lie in [1, 2] and `s - 1`, `t - 1` are the position on the face. + +The translator emits a helper `x2w_cube_dir(s, t, face)` that rebuilds a direction whose major component is +1 or +-1 for the face and whose other components are `u = 2(s - 1.5)` and `v = 2(t - 1.5)` with the signs of the per-face +`sc` and `tc` that the existing `v_cube*` lowering uses: +X (1, -v, -u), -X (-1, -v, u), +Y (u, 1, v), -Y (u, -1, -v), ++Z (u, -v, 1), -Z (-u, -v, -1). Projecting that direction again gives back `u` and `v`. + +## Refused + +- `image_load` and `image_load_mip` on a cube (`Load is not defined on a TextureCube`), `image_sample_d` + (cube derivatives are not converted), `image_get_lod`, `a16` and `d16`. +- A cube in a compute program: the compute dispatch has no `texcube` view binding. +- A constant sampler with `DISABLE_CUBE_WRAP` (`SQ_IMG_SAMP_WORD0` bit 28, Mesa + `src/amd/registers/gfx10-rsrc.json`): the guest then filters without crossing face edges, while a D3D12 cube + always filters across them. With the bit clear both cross. +- Compare, gather and store forms were already limited to 2D and 2D arrays and are unchanged. + +## Limits + +- A cube-array view is not recognisable from the instruction (gfx10 MIMG has no array bit; the descriptor sets + the dimension). The helper keeps the face bits of the id (`id & 7`) and samples layer 0 of a `TextureCube`, + which is wrong for a later layer of a cube array. +- A face id of 6 or 7 maps to face 5, a negative, NaN or huge id to face 0, and `s` or `t` outside `[1, 2]` are + assumed to clamp to `[-1, 1]` on the face edge. Mesa does not produce these for a finite non-zero direction; + clamping outside `[1, 2]` is not tested and none of these out-of-range inputs is measured. +- The implicit-LOD and bias forms take the desktop derivatives of the rebuilt direction. Inside one face these + follow the guest's face coordinates; a quad that straddles a face edge can choose another level. +- Heap and register samplers are not read at translation, so their `DISABLE_CUBE_WRAP` bit is not validated (a set + bit would filter differently at face edges), and their LOD range stays unvalidated as for 2D textures. +- Only pixel-stage draws are measured; the vertex-stage form is translated but not drawn. +- The runtime binding of a `texcube` view landed in PR #2938 (`7fcde81f`). + +## Fixture + +`tests/startup_image_cube_check.py` (controls, `binary `, `draw `). +`offscreen_check --startup-image-cube` binds six 4x4 R32G32B32A32_FLOAT faces as a TextureCube whose texel (x, y) +of face f holds ((1 + x + 4y + 16f) / 128, x, y, f). The sampler is the all-zero inline sampler (point, wrap), and +every `s` and `t` is a texel centre (in `{1.125, 1.375, 1.625, 1.875}`). + +- Seven programs set `(s, t, face)` as constants (`1.125` or `1.875`), without `v_cube*`, so the reference is only the + address meaning (`x = floor(4 * (s - 1))`, `y = floor(4 * (t - 1))`). The desktop driver picks the face of the + rebuilt direction itself, so a wrong face, sign, axis or `2.0 * (s - 1.5)` / `2.0 * (t - 1.5)` scale in the helper + reads another texel. Every face has a case whose texel has x != y. +- `image_sample`, `image_sample_l` and `image_sample_b` each draw one case. +- Controls: the face one higher and `s`, `t` exchanged must read those texels; `image_sample_l` and + `image_sample_b` with the face in the LOD or bias dword must read face 0. +- Fifteen translator mutants edit the emitted helper (for each face the sign of the `u` term flipped, `u` and `v` + exchanged, faces 2 and 3 exchanged, and dropping the `2.0 *` scale on `u` or `v`). Each must read the texel a D3D + cube lookup of its direction gives. +- Six programs run the `v_cube` chain (`v_cubema`, `v_cubesc`, `v_cubetc`, `v_cubeid`, `v_rcp_f32` of `|ma|` and + `v_fma_f32` with 1.5) on one direction per face. Each must match the face texel LLVM's table gives and a desktop + pixel shader that samples the same direction from the TextureCube. + +Measured on 28.11.2026, commit f7da3f69 plus this change, Windows 11 24H2 (10.0.26100.9711), debug layer +unavailable on both adapters: the 22 reference draws (7 literal, 3 forms, 6 chain, 6 desktop TextureCube) matched +on NVIDIA Quadro M1000M (driver 32.0.15.7371) and on WARP (Microsoft Basic Render Driver 10.0.26100.9711), and all +19 controls and mutants read the texel they predict (`dev` and `release` `/O2`). With the translator change reverted, +the controls fail on `image dimension SQ_RSRC_IMG_CUBE`, and dropping the `2.0 *` scale on `u` fails both +`startup_image_cube_controls` and `startup_image_cube_warp`. +The 16 fixture programs reassemble to the recorded words with LLVM 15.0.7. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_image_cube_' -V +``` + +Not shown: that the console's face order and face orientation equal D3D's. That rests on LLVM's cube table being +the D3D cube face table. LOD and bias values on a cube are not tested, because only one mip is bound; the +`image_sample_l` and `image_sample_b` draws only show that the extra address dword is not read as a coordinate. diff --git a/docs/experiments/startup-input-trace.md b/docs/experiments/startup-input-trace.md new file mode 100644 index 0000000000..65c2a3a2c0 --- /dev/null +++ b/docs/experiments/startup-input-trace.md @@ -0,0 +1,103 @@ +# Startup input trace + +`X2W_INPUT_TRACE=1` makes the `GameInput.dll` stand-in log the gamepad state it resolves for each +`IGameInput::GetCurrentReading` call. The state is read after the keyboard, XInput pad 0, the +`Local\x2w_input_pad` shared block, `X2W_INPUT_PRESS` and `X2W_INPUT_SCRIPT` have been merged, so the +trace shows the values the runtime returns to the title. It is a diagnostic for checking that a +scripted stick, trigger or button reaches the runtime when the corresponding picture is presented. +The switch is off by default and adds no line without it. + +## Checking it + +Build the source-built fixture and run its CTest: + +```powershell +cmake --build --preset dev --target startup_gameinput_trace +ctest --preset dev --no-tests=error -R '^startup_gameinput_trace$' -V +``` + +For a normal startup run, set the switch next to the script: + +```powershell +$env:X2W_INPUT_SCRIPT = 'wait,mark=screen@+0,lx=1@+0.5+2,4@+2.5' +$env:X2W_INPUT_TRACE = '1' +.\tools\startup\run.ps1 ... +``` + +The trace goes to stderr and to the file named by `X2W_TRAP_LOG`, like the stand-in's other lines. + +## Line format + +Every line starts with `x2w-input-trace`. A state line is written when the resolved gamepad state +changes and, while it is unchanged, at most once every 250 ms: + +```text +x2w-input-trace state buttons=0x00000000 lt=0.000 rt=0.000 lx=1.000 ly=0.500 rx=0.000 ry=0.000 script=2.500 present=11 +``` + +`buttons` is the GameInput button mask in hexadecimal. `lt`, `rt`, `lx`, `ly`, `rx` and `ry` use +the units of `GamepadState` (triggers in [0, 1], sticks in [-1, 1]). `script` is the current time on +the script's time base in seconds, or `off` when no timed entry or wait/mark is active. `present` +is the latest present number published by the picture signature, or `none` when no presenter +sample is available. The state line does not depend on the title having called +`GetGamepadState`; it is sampled when the stand-in captures a reading. + +Script marks and waits add one event line each: + +```text +x2w-input-trace wait event=begun item=2 at=0.000 elapsed=0.000 signal=1 +x2w-input-trace wait event=changed item=2 at=1.000 elapsed=1.000 signal=1 +x2w-input-trace wait event=done item=2 at=1.500 elapsed=1.500 signal=1 +x2w-input-trace wait event=timeout item=4 at=2.000 elapsed=2.000 signal=0 stopped=0 group=- +x2w-input-trace mark label=turn item=5 at=2.500 present=11 +x2w-input-trace group label=list items=2-6 failed_item=4 at=3.000 +``` + +`item` is the 1-based script item, and `at` is on the same shifted script time base as the state +lines. A wait that times out names its group, or `-` when it has none. A mark without a presenter +prints `present=none`. + +## Volume + +The trace logs one state line per change and one periodic line per 250 ms of unchanged state, so a +steady run produces at most four state lines per second. Wait, mark and group lines occur once per +script event, and the parser limits a script to 256 timed items, so the event volume follows the +script. Without `X2W_INPUT_TRACE=1`, the stand-in reads no clock for the trace and writes no +`x2w-input-trace` line. + +## What it verifies for movement + +The `script` and `present` fields on one line tie an input value to the picture being presented. For +a movement question, this distinguishes an input that never reached the runtime from one that was +present but produced no visible movement. It also exposes axis signs and trigger ranges before they +are consumed: `lx=1.000` is right, `ly=1.000` is up, and a trigger outside [0, 1] would be a runtime +mapping problem rather than a rendering problem. Marks name the frame where a movement starts, and +waits show how long the script blocked before the movement was allowed to run. + +The trace covers the GameInput stand-in only. It does not prove that the title read the reading, +that the reading was used by a particular title system, or that a draw or present changed. Pair it +with the stand-in's `x2w-input gamepad buttons ... read by the title` line, a present/capture log, +or a title-side movement observation for that evidence. + +## Fixture + +`startup_gameinput_trace` runs one synthetic script in a child process with the switch on and again +with it off. The child sets `X2W_INPUT_CLOCK_MS` before every poll and publishes a new picture at +1.0 s. The script is: + +```text +mark=start@0,wait=0.5/2,4@+0.5+0.5,lx=1@+0.5+1,mark=turn@+0,ly=0.5@+0+0.5,8@+1.1+0.1 +``` + +The wait completes at 1.5 s, so A is down at 2.0-2.5 s and the left stick is right with Y at 0.5 at +2.5-3.0 s. A 0.1 s B press runs at 3.6-3.7 s, off the 250 ms heartbeat grid. The trace child must +contain the exact state lines at 2.000 s, 2.500 s and 3.600 s, the begun, changed and done wait +lines, both marks, no timeout, and between 12 and 21 state lines over the four second run. The +control must observe the same gamepad states, keep the ordinary `x2w-input script` +mark line, and contain no `x2w-input-trace` line. The expected states and trace lines are built from +source; the fixture uses no game files, dump or captured input. + +On the local Windows x64 Debug build (MSVC 19.44, CMake/Ninja), `startup_gameinput_trace` passed +with both modes. The same build ran `startup_gameinput_script_long`, +`startup_gameinput_script_entries` and `startup_gameinput_script_syntax` successfully, and the +stand-in's keys, history and contract checks still passed without the switch. diff --git a/docs/experiments/startup-mesh57-dead-block-scalar.md b/docs/experiments/startup-mesh57-dead-block-scalar.md new file mode 100644 index 0000000000..60491fd082 --- /dev/null +++ b/docs/experiments/startup-mesh57-dead-block-scalar.md @@ -0,0 +1,39 @@ +# Slot 57 mesh: dead scalar ALU in any EXEC-zero block + +Part of #2413. Stacked on the pre-exchange wave block (#2783). + +#2643 accepted scalar ALU with no reader past the count exchange, but only in the block that +`s_cbranch_execz` skips into the count exchange. Every other `s_cbranch_execz` block refused any +scalar instruction with `slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes`. + +The model skips per lane, while the guest skips per wave. A scalar result that no path reads past +the join is invisible either way: +- A lane that skips the block never reads it. +- A lane that runs the block computes the wave-uniform value the guest wave computes. + +This change applies that rule to every `s_cbranch_execz` block. The instruction must be scalar ALU +that `mesh_wave_block_scalar` (#2783) accepts: SGPR, SCC and VCC operands only, with no EXEC, M0, +`src_*`, MODE, memory, branch or message. Each register it writes, including the SCC every `s_` op +may write, must not be live at the join. Scalar loads keep their own rules. + +## Tests + +`tests/startup_mesh57_skeleton_check.py`: +- **New draw case:** the lane-masked if/else with `s_add_u32 s50, s13, 1` in the then arm. It is + drawn on WARP and hardware with the if/else image of the existing case. +- **Former #2643 refusal controls, now accepted translations:** + - `dead scalar ALU in a different EXEC-zero block`; + - `an EXEC-zero branch that skips a dead scalar write`. +- **New refusal:** the same if/else with `v_mov_b32 v8, s50` after the EXEC restore, so the scalar is + live at the join. +- **Fail-first:** without `dead_block_scalar`, all three accepted cases go red. + +## Local capture census (counts only) + +- On a local capture at main `96a7b4fb`, together with #2783: 91 of 407 slot 57 requests that stop + at the execz refusal now pass it. +- They stop at `v_readfirstlane_b32 outside the group-index read is not covered`. That is a + first-lane read of a formatted buffer load in the pre-exchange code. +- The 91 are all post-count primitive-export blocks with an `s_add_u32` that is dead past the jump + to `s_endpgm`. +- No complete translation is added yet. diff --git a/docs/experiments/startup-mesh57-wave-block.md b/docs/experiments/startup-mesh57-wave-block.md new file mode 100644 index 0000000000..61ca9cdeb5 --- /dev/null +++ b/docs/experiments/startup-mesh57-wave-block.md @@ -0,0 +1,97 @@ +# Slot 57 mesh: a pre-exchange wave block with several scalar loads + +Part of #2413, follow-up to #2660. + +## Shape + +Between the group-index exchange and the count exchange of a slot 57 mesh program: + +``` +s_mov_b64 exec, -1 +... ; no EXEC or VCC operand, no branch entering from outside +v_cmpx_gt_u32_e32 s, v ; v the proven v_mbcnt thread index +... ; no EXEC write +s_cbranch_execz SKIP + ... straight-line: s_buffer_load_dword*, s_load_dword*, scalar ALU, + ... lane-only vector code, a per-lane v_cmp into VCC +SKIP: +``` + +#2660 accepted exactly one `s_buffer_load_dword` whose result is read after the join, with the reset +directly before the compare. +This change accepts any number of the listed scalar loads and any scalar ALU in the block. The reset +may be further up when nothing between it and the compare names EXEC or VCC and no branch from +outside lands in that range. + +## Semantics + +The guest runs the block once per wave when any lane of the wave is active. The active lanes are a +prefix (`thread < bound`). +- The lowering computes `wave_any = (tid & ~63u) < bound` at the compare, as in #2660. +- It branches around the whole block only when `wave_any` is false. +- Every scalar instruction of the block then runs for every lane of a wave with an active lane, so + each lane holds the values the guest wave holds. +- Vector writes stay predicated by each lane's EXEC bit. +- An empty wave issues no load, so an out-of-range address on it is never read. + +Requirements, refused with `slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes` +unless noted: +- **Scalar instructions** may only read and write SGPRs, SCC and VCC. EXEC, M0, `src_*` operands, + `s_*_saveexec`, MODE writes, branches, barriers, messages, stores and atomics are refused. +- **VCC written in the block, and SCC an ALU op writes there,** must not be read after the join. + A scalar load does not write SCC, so a #2660-shaped block is unaffected. +- **Scalars read after the join** must be wave-uniform and defined before the block. An empty wave + keeps their old values. +- **Another compare form**, an EXEC write between the reset and the compare, a branch into that + range from outside, and any branch inside the block are refused. +- **Branches past the compare:** a branch landing between the compare and the execz branch is + refused, because that path reaches the block without the compare. +- **Implicit EXEC writers** (`v_cmpx`, `s_*_saveexec`) between the reset and the compare end the + reset search. The EXEC tracker of `mesh_skeleton` then refuses them with its own messages. +- **A block ending at the count exchange** keeps the exchange refusal of #2643. + +## Tests + +`tests/startup_mesh57_skeleton_check.py`, source-built fixture `WAVE_BLOCK_MESH` (assembled words checked +by the `binary` mode). The block holds: +- two `s_buffer_load_dword`, the second at an offset computed by `s_add_u32` in the block; +- a dead `s_load_dwordx4` table read; +- a dead `v_cmp_class_f32` into VCC; +- a scalar write between the reset and the compare. + +The draw (`startup_mesh57_skeleton_draw_warp` / `_hardware`, same geometry as #2660) covers: +- a mixed wave whose provoking thread is outside EXEC and reads the loaded word; +- an empty wave that keeps the old scalar while its addresses lie past the buffer; +- the swapped old/new selection, which must fail on 259 pixels; +- a mutant that replaces the wave predicate by the lane's own EXEC bit. It must differ from the wave + image on 66 pixels and match its own per-lane image. + +Controls: +- New refusals: + - VCC live at the join, `src_scc` in the block and EXEC copied in the block; + - a branch inside the block; + - a branch from outside between the reset and the compare, and a branch from that range past + the compare to the execz branch; + - an EXEC write between the reset and the compare. +- Without the compare-bypass rule, the bypass control translates. That is how the control was + checked. +- Changed #2660 controls: + - A wider `s_buffer_load` and a dead loaded scalar are now accepted. + - The `s_nop` that replaced the adjacent reset now reaches the reset that closes the group-index + exchange, so it is accepted. + - The missing-reset control now writes EXEC from an SGPR pair. + - The second live scalar write stays refused, because its register has no value before the + block. + - The register-offset `s_load` now stops at the existing register-offset rule. + +## Local capture census (counts only) + +On a local capture, 407 slot 57 requests stop at the refusal above on main `96a7b4fb`. +- 91 of them now pass the pre-exchange block. +- They stop at the same message one block later: an `s_add_u32` that is dead after the join, in the + post-count primitive-export block, which jumps to `s_endpgm`. A separate pull request covers that + block. +- With both changes applied, they stop at `v_readfirstlane_b32 outside the group-index read is not + covered`. +- No new complete translation results from either change. +- The other 316 have a branch inside the block, `src_scc`, or the `v_cmpx_lt_u32 v, v` compare form. diff --git a/docs/experiments/startup-opus-completion-count.md b/docs/experiments/startup-opus-completion-count.md new file mode 100644 index 0000000000..d4dd02effe --- /dev/null +++ b/docs/experiments/startup-opus-completion-count.md @@ -0,0 +1,65 @@ +# Startup Opus completion counters + +Refs [#1145](https://github.com/R0Y00/Xbox2Windows/issues/1145) and +[#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This note covers the optional Opus +decode path built with `-DX2W_WITH_OPUS=ON` and `X2W_XAPU_TYPED_COMPLETIONS=1`. + +## What is counted + +`xapu.dll` keeps process-wide saturating counters for: + +| Counter | Meaning | +|---|---| +| `type3` | readable type 3 commands seen while typed completions are on | +| `packets` | commands libopus decoded successfully | +| `completions` | type 3 results dequeued by the caller | +| `refusals` | sum of the refusal counters below | +| `invalid_argument` | a field or output range failed before libopus | +| `opus_error` | libopus rejected the packet | +| `capacity` | libopus reported `OPUS_BUFFER_TOO_SMALL` | +| `queue_full` | the per-connection queue was full | +| `short_command` | the decode fields crossed the readable header | +| `unknown_handle` | the command named a handle that was not connected | +| `out_of_memory` | a new decoder could not be created | +| `header` | the command header was null or unreadable | + +The counters start on the first readable type 3 command. A run with typed completions off reads +and writes nothing here. + +The audio sink also reports `accepted` and `not_open` submissions, so a run can distinguish an +endpoint that never opened from one that accepted decoded blocks. + +## Summary line + +At the last `XApuDisconnect`, and from `atexit` when a run never disconnects, the stand-in writes +one stable line when the counters moved since the previous summary: + +```text +x2w-audio XApu opus summary: type3=10 packets=2 completions=2 refusals=9 invalid_argument=3 opus_error=1 capacity=1 queue_full=1 short_command=1 unknown_handle=1 out_of_memory=0 header=1 +``` + +The line is written to stderr and to `X2W_TRAP_LOG`, like the other audio lines. It is a snapshot; +two threads can move different fields between their loads. Each field is exact on its own. + +## Test + +```powershell +cmake --preset dev -DX2W_WITH_OPUS=ON -DOpus_DIR=/lib/cmake/Opus +cmake --build --preset dev --target startup_stub_xapu startup_xapu_opus_count_check +ctest --preset dev --no-tests=error -R '^startup_xapu_opus_count$' -V +``` + +The fixture encodes synthetic 1 kHz tones with libopus and drives the real stand-in exports. It +checks two successful decodes and dequeues, a malformed packet, insufficient capacity, an invalid +rate, an out-of-range slot in both the legacy and typed-stream paths, a short command, an unknown +handle, a full queue, a null header, saturation at `UINT64_MAX`, one summary after the last +disconnect, and that typed completions off neither decode nor add a summary line. It passed in +Debug with libopus 1.5.2 on Windows 11 build 26300. + +## Limits + +The counters prove that the optional decode path ran and that the caller consumed the results. +They do not prove that the output was audible, that the desktop sink accepted the same block, or +that XMA/AcpHal works. The `startup_audio_output` fixture covers the sink's accepted/not-open +counters separately. The title run that produced the 27/11 audio observation was not available +locally, so this change adds the measurement, not the run receipt. diff --git a/docs/experiments/startup-pso-recipe.md b/docs/experiments/startup-pso-recipe.md new file mode 100644 index 0000000000..266c2adefa --- /dev/null +++ b/docs/experiments/startup-pso-recipe.md @@ -0,0 +1,61 @@ +# Translated PSO recipes + +The shader cache stores the translated vertex and pixel bytecode, the root signature and the +sampler descriptions. It does not store the draw state that produced a desktop graphics pipeline +state object: the blend state, depth-stencil state, rasterizer state, target formats and DSV format. +A run therefore creates each translated PSO on its first draw. + +`X2W_PSO_RECIPE_DIR=` records that state after a successful +`CreateGraphicsPipelineState` and replays matching records before creating a new PSO on a later +run. It is off by default. + +## Format + +One text file per translation key: `/pso_.txt`. The file holds up to 64 +records and 64 KiB. Each record starts with `x2w-pso-recipe 1` and ends with `end`. It carries the +translation key, the target/depth/raster state key, the target count and formats, the DSV format, +the `indexed_rect` flag, the effective blend state after export write masks, the depth-stencil +state, the rasterizer state, the sample mask and count, and the topology type. No pointers or +process addresses are written. + +The parser recomputes the state key from the recorded fields. A record whose recomputed key does +not match the key it names, whose target formats or DSV do not match the current pass, or whose +version is unknown is ignored and the unchanged creation path runs. A malformed or oversized file +is counted and ignored. + +The writer applies the same parser before it appends. It refuses to add a record when the file +already holds 64 complete records, when any existing line is rejected, or when the new record +would cross 64 KiB. A 65th record would never be read back, so refusing it keeps the cache and the +parser at the same boundary. It also refuses when a non-empty file does not end in LF: the parser +accepts such a final record, but appending would join its `end` to the next header on one line. The +file is left unchanged. + +The read, count/size check and append share one exclusive file handle. A second process that +reaches the append path while the file is owned keeps the PSO it already created and skips the +cache write; a reader denied by that handle also falls back to the unchanged creation path. +Neither side can seek to an end offset that another writer selected. + +## Scope and limits + +This is state reconstruction, not a D3D12 pipeline library. A replayed record still calls +`CreateGraphicsPipelineState`; the driver may compile or find the PSO in its own cache. The change +moves the state reconstruction and the first-use creation earlier, and makes the exact draw state +available without a title run. It does not claim to eliminate driver compilation. + +The device-free test `startup_pso_recipe` covers the serializer/parser round trip, two appended +records, a corrupt state key, an unknown version, an oversized file, target-format and DSV +mismatches, and the 63/64/65 record boundary (63 accepts one more, 64 refuses a 65th, and the +parser rejects a 65th). `startup_stream_draw_warp` runs the two-process replay: the first +translated stream draw writes a recipe, a second process with the same directory loads and +precreates it, and all 32 RGBA bytes match. It also holds the recipe file exclusively during a +draw and checks that the draw still renders with exact pixels while the file size stays unchanged. +It then seeds 63 valid records for another translation key, checks that the next draw appends the +matching record as number 64 and the following process logs `precreated 1`, and seeds 64 records to +check that the draw still renders while the file stays at 64. It removes the final LF from that +parseable file, runs another draw and checks that the file is byte-for-byte unchanged and still +readable. That test covers the unused depth-stencil normalisation as well. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_pso_recipe$' -V +ctest --preset dev --no-tests=error -R '^startup_stream_draw_warp$' -V +``` diff --git a/docs/experiments/startup-rect-gap.md b/docs/experiments/startup-rect-gap.md new file mode 100644 index 0000000000..c6fc115ee3 --- /dev/null +++ b/docs/experiments/startup-rect-gap.md @@ -0,0 +1,86 @@ +# The indexed rectangle rule and a 12-byte vertex stream (#3131) + +Issue #3131 reports that an indexed UI gradient draw leaves a sharply bounded region of its colour target +uncovered, with a diagonal boundary, and that the draw's recording-time vertex read uses a 12-byte stride. The +reported rule was checked against source-built input: an eight-vertex quad and edge ring, 12-byte vertex +records with XY at +4, an indexed triangle list, a mask-controlled pixel shader and an RGBA8 target, through +the runtime entry (`startup_stream_consumer`), plus a fixture for the shared rectangle-expansion stage alone. + +## What the runtime draw measured + +`tests/startup_rect_gap.cpp` (draw) and `tests/startup_rect_gap_check.py` (input, model and comparison) bind a +placed 12-byte-record stream twice, slot 0 as R32_FLOAT (the mask at +0) and slot 1 as R32G32_FLOAT at +4, and +draw four triangles: records 0-1-2 and 0-2-6 (the edge ring), then 3-4-5 and 3-5-7 (the inner quad), so the +same eight records serve an R16 indexed triangle list and a six-vertex rectangle list. A mask-controlled pixel +shader paints the quad red and the ring green; a constant-red pixel shader is the coverage control. The target +is cleared blue, and the check compares all 32 pixels with a point-in-triangle model of the two triangles. + +Every mode covered exactly the pixels the model expects, on WARP and through the `hardware` backend: + +| mode | draw | result | +|---|---|---| +| `triangle` / `triangle-copy` | R16 indexed list, placed stream / unregistered stream (recording-time copy and index scan) | 12 red, 20 green | +| `rect` / `rect8` / `rect8-copy` | six- and eight-vertex rectangle lists, expanded by the vertex stage | 12 red, 20 green | +| `rect8`, `triangle` with the constant shader | coverage only | 32 red | +| `triangle-rotated` / `rect-rotated` | the same rectangles turned by 15 degrees | 12 red, 18 green, 2 clear | +| `none` | no draw | 32 clear | + +The check also asserts the bound bytes (8 records of 12 bytes, then the 12 indices), the input-layout request +(`TEXCOORD 0 41 0 0 0 0` and `POSITION 0 16 1 4 0 0`), and the generated vertex stage's two loads, +`a = (vid + ud1) * ud3 + 4;` for POSITION and `a = (vid + ud1) * ud4 + 0;` for the mask. With +`X2W_TEST_RASTERIZER=back` (back-face culling, clockwise front) the picture is unchanged, and with `back-ccw` +(counter-clockwise front) every triangle is culled and the target stays clear, so the winding survives the +expansion. The described diagonal gap did not appear in any of these draws. + +## The one stage that did leave a region uncovered + +`tests/startup_rect_geometry.cpp` compiles the shared rule (`src/startup_stubs/indexed_rect_geometry.h`) the way +the runtime does, binds it with back-face culling on, and draws one rectangle named by three corners. Its +`axis` order was covered exactly; its `rotated` order, the same square turned by 15 degrees, was dropped whole: +32 of 32 pixels kept the clear colour. The rule located the right-angle corner by looking for a corner that +shares an x or a y with each of its neighbours, so a rectangle with no axis-aligned edge matched no corner and +the stage returned without emitting either triangle. The vertex-stage rectangle expansion never had that +restriction: it uses `v0 + v2 - v1` directly, so the two implementations of the same rule disagreed, and a +rotated UI rectangle lost both of its triangles. + +The fix identifies the same corner from the shape: the right-angle corner is the vertex opposite the diagonal, +which is the longest of the three edges, and the two sides must also meet at a right angle. Both +`indexed_rect_geometry.h` and the native rule in `src/gfx1013_rect_geometry.cpp` now use it, with the axis test +keeping precedence, so every input the old rule accepted is unchanged. After the fix `axis`, `swung` (the same +square in another corner order, which back-face culling rejects by its winding), `rotated` and `skewed` all +match the model: 0 of 32 pixels differ. `skewed` moves the top-left corner a quarter of the way toward the +top-right; it has no axis corner and no right angle, so the stage must leave the target clear and pins the +right-angle guard in both copies. + +The native IR copy had the same corner rule, but its LLVM IR wrote the tolerance as the decimal +`1.000000e-06`; LLVM rejects that non-representable float constant, so every native rectangle pair was +refused before a PSO existed. It now uses the binary32 value's exact hexadecimal double, +`0x3EB0C6F7A0000000`. `native_rectangle_geometry_warp` compiles that geometry CSO and runs the same +`axis`, `swung`, `rotated` and `skewed` scenes through the native VS/PS pair with back-face culling on; all +four cover exactly the literal model's 32 pixels. The HLSL and native implementations are therefore pinned +to the same rule by readback, not only by compiling the IR. + +## Commands and environment + +```powershell +ctest --preset dev --no-tests=error -R '^(startup_rect_geometry|startup_rect_gap)_(warp|hardware)$' -V +ctest --preset dev --no-tests=error -R '^(native_rectangle_pso|native_rectangle_geometry)_warp$' -V +ctest --preset dev --no-tests=error -R '^(startup_indirect_translated_indexed_rect|startup_indirect_rectlist|native_direct_container|rectlist_topology|rectlist_draw)_(warp|hardware)?$' +``` + +Measured on Windows 11 build 26300, MSVC 19.44.35228, Windows SDK 10.0.26100.0 (DXC 10.0.26100.0), at +`63a30dc1` with this change on top. `startup_rect_geometry` ran on WARP (Microsoft Basic Render Driver +10.0.26100.10068) and on the AMD Radeon RX 9060 XT (driver 32.0.32029.2010). The runtime draw reported the +Microsoft Basic Render Driver in both of its backends, so its picture is a WARP result. The D3D12 debug layer is +not installed on this machine (`D3D12GetDebugInterface` fails), so the fixtures report `debug_layer=unavailable` +and no debug-layer messages were collected. + +## What remains open + +Which draw produced the reported gap is not established. A stream renamed by a view that declares fewer bytes +than the indices name draws nothing at all here (both the placed view and the recording-time copy stop at the +declared size), so that is a separate, unverified candidate. The indexed rectangle stage is only reached through +an indirect draw, and two of its paths are not covered by these fixtures: a translated non-indexed indirect +rectangle list keeps the title's three-vertices-per-rectangle count (the vertex stage then draws half of the +rectangles), and the stage's flat (`FPARAM`) outputs take the value of the first vertex for both triangles +instead of each triangle's provoking vertex. Neither was exercised here. diff --git a/docs/experiments/startup-root-srv-at-draw.md b/docs/experiments/startup-root-srv-at-draw.md new file mode 100644 index 0000000000..51f7f6c552 --- /dev/null +++ b/docs/experiments/startup-root-srv-at-draw.md @@ -0,0 +1,100 @@ +# Graphics root SRV: no desktop copy that no draw reads (opt-in) + +Refs [#2948](https://github.com/R0Y00/Xbox2Windows/issues/2948), +[#2949](https://github.com/R0Y00/Xbox2Windows/pull/2949). + +List slot 44 (`SetGraphicsRootShaderResourceView`) at a title address without an upload mapping copies a 64 KiB +window of title memory into the shared upload ring and binds it on the desktop list (`list_root_srv`). In the current +code no draw reads that desktop binding: + +- Translated draws set their own root signature and read the SRV from its title address (`pass.root_address`, + `source == 2` in `draw_translated`) at the draw. +- `list_draw` forwards a draw only with `pass.pipeline_real`, which `list_pipeline` sets for a desktop pipeline + without an indirect graphics root. `build_stream_pipeline` accepts a graphics stream only with VS/PS or MS/PS + ("desktop indirect graphics stream needs ...") and gives every accepted one that root, so `pipeline_real` holds only + for compute pipelines. A vertex-only desktop stream is refused by the same rule. +- An indirect graphics draw (list slot 61) requires `pass.indirect_graphics.root == pass.graphics_root`: an empty + root signature (`root_without_bindings`), or for a cached mesh pipeline the title's root, whose only root SRV + (`cached_srv_root`) the draw binds from its validated lease. + +## What the switch changes + +- `X2W_D3D12_ROOT_SRV_AT_DRAW=1`: slot 44 skips that copy. The title address is kept for translated draws as before, + and the parameter stays unbound on the desktop list (`srv_bound` clear), so a forwarded `list_draw` that needs bit 0 + is skipped rather than drawn with an older binding. A desktop graphics pipeline that reads a root SRV, if one is + added, would need the copy at its draw. +- With the switch set, the render totals are followed every 300 frames by + `x2w-render root SRV copies (X2W_D3D12_ROOT_SRV_AT_DRAW): skipped N, copied M`. +- Unset, slot 44 copies at every call, as before. + +## Fixture + +```powershell +ctest --preset release --no-tests=error -j 1 -R '^startup_root_srv_draw_(warp|hardware)$' -V +``` + +`startup_root_srv_draw_*` (`X2W_TEST_ROOT_SRV_DRAW=write-after`, `tests/startup_root_srv_draw.cpp`): the stream +root's parameter 0 is a root SRV. Slot 44 binds a `VirtualAlloc` buffer holding red, the title writes green, then a +translated draw reads the SRV through its root pointer. Both modes draw green over the left half. After the draw is +recorded the fixture reads the stand-in's counts (`x2w_d3d12_root_srv_copies`): unset, `skipped 0, copied 1`; set, +`skipped 1, copied 0`. Mutant: ignoring the switch fails +`X2W_D3D12_ROOT_SRV_AT_DRAW=1: copies (skipped, copied) (0, 1), expected (1, 0)`. + +Not covered: a desktop draw that reads the binding, because none can be built (see above). + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, 16 GB, release +build on `main` `98e4a2ee`, warm shader cache (revision 29), scripted input, 250 s. One build; only the switches +differ. Aggregates only; logs stay local. The first two tables were measured with the first revision of this change +(`bedfcafc`), which kept the address pending for a desktop draw instead of skipping the copy; no run made a copy at +a draw, so slot 44 did the same work as now. + +Each switch alone, against no switch: + +| | none | `ROOT_SRV_AT_DRAW` | `RING_RELEASE_AT_SUBMIT` | +|---|---|---|---| +| null bindings with cause `buffer` | 164,727 | 88 | 0 | +| `upload ring reservation refused` logged | yes | yes | no | +| visible | single black frames in the post-load animation | none seen | not watched | + +With `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` and `X2W_D3D12_TABLE_ALIAS=1` set in every run, two pairs, the second in +reverse order: + +| | switch unset | switch set | +|---|---|---| +| mean fps 150–240 s, pair 1 / pair 2 | 6.3 / 7.1 | 14.8 / 14.0 | +| frames presented, pair 1 / pair 2 | 3,663 / 3,541 | 4,689 / 4,804 | +| executes, pair 1 / pair 2 | 33,408 / 36,029 | 72,177 / 70,916 | +| slot 44 time 150–240 s (threads; µs per call) | 1.14–1.19; 43–49 | 0.28–0.29; 5 | +| copies not made at slot 44 / made at a draw | n/a | about 7 million / 0 | +| null bindings `token` per 1,000 translated draws | 33.8 / 32.3 | 36.7 / 26.9 | +| null bindings `buffer`, device removal | 0, none | 0, none | +| process commit peak | 19.1 / 19.0 GiB | 19.8 / 19.4 GiB | + +- The slot 44 copies were most of the upload ring traffic that #2948 describes: the switch alone removes all but + 88 of the buffer null bindings, but some reservations are still refused, so it complements #2949 rather than + replacing it. +- Without the table alias the frame rate barely changes (5.9 → 6.1 fps): the draw path is then bound by `frame_copy` + under `draw_lock`. +- Every run read `deferred N, made at a draw 0`: no draw in these runs read the desktop binding. + +Retest of this revision (merged with `main` `3b6c38a8`), same machine, cache and input, ring and alias set in every +run, two pairs, the second in reverse order: + +| | switch unset | switch set | +|---|---|---| +| mean fps 150–240 s, pair 1 / pair 2 | 6.3 / 6.5 | 13.9 / 13.4 | +| frames presented, pair 1 / pair 2 | 3,839 / 3,706 | 4,798 / 4,960 | +| executes, pair 1 / pair 2 | 24,065 / 33,220 | 69,730 / 54,789 | +| slot 44 time 150–240 s (threads; µs per call) | 1.17 / 1.11; 52 / 48 | 0.29 / 0.29; 5 / 6 | +| copies skipped / copied (render totals) | n/a | 6.9 / 4.9 million; 0 | +| null bindings `token` per 1,000 translated draws | 23.4 / 29.8 | 24.2 / 33.0 | +| null bindings `wrapper`, pair 1 / pair 2 | 0 / 40 | 107 / 101 | +| null bindings `buffer`, ring refusals, device removal | 0, none, none | 0, none, none | +| process commit peak | 18.7 / 18.5 GiB | 18.7 / 18.7 GiB | + +- `wrapper` null bindings also appear in an unset run (40). Per 1,000 translated draws they are 0 / 0.26 unset and + 0.37 / 0.40 set: few, but not explained here. + +Not established: desktop graphics pipelines that read a root SRV (none can be built today), and other adapters. diff --git a/docs/experiments/startup-sampler-join.md b/docs/experiments/startup-sampler-join.md new file mode 100644 index 0000000000..eb6efeb2b4 --- /dev/null +++ b/docs/experiments/startup-sampler-join.md @@ -0,0 +1,21 @@ +# Two inline samplers at a uniform forward join + +For 2D explicit-level `image_sample_l` and `image_sample_lz`, a single forward SCC diamond may select two inline four-word sampler definitions. Both arms must finish by writing all four words as literals, with proven uniform control flow and unchanged EXEC. Only normalized point wrap/clamp XY addressing and point mip filtering are admitted, with validated LOD limits. Two `smpl` static bindings preserve the descriptors; the selected runtime word chooses between complete `SampleLevel` calls. Any intervening overlap write invalidates the join proof. Implicit derivatives, partial definitions and more complex control flow retain their existing refusals. + +The source-built fixture evaluates both root-constant selector outcomes for both sample forms with an independent point-texel oracle. A third variant holds word 0 unchanged and varies only MAX_LOD in word 1; the explicit level selects mip 1 or mip 0. Swapping sampler bindings changes the result in every variant. A decoded negative diamond keeps every field valid but sets bit 24 of word 1, above the whole-word-1 mask, so the guard refuses it as unsupported joined sampler words. Seven refusal controls and ten binary assembly variants are included. + +Both portable checks passed on Apple Silicon; the expanded ten-variant fixture was assembled with LLVM 15.0.7. + +```bash +python3 -B tests/startup_image_sample_l_join_check.py +python3 -B tests/startup_image_sample_l_join_check.py binary llvm-mc +``` + +The registered Windows draw consumes the actual translated shader, both manifest lines and the runtime selector. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^startup_image_sample_l_join_' -V +``` + +DXC/WARP/hardware draw execution requires Windows and remains unmeasured locally. diff --git a/docs/experiments/startup-scene-color-report.md b/docs/experiments/startup-scene-color-report.md new file mode 100644 index 0000000000..daedaa12a5 --- /dev/null +++ b/docs/experiments/startup-scene-color-report.md @@ -0,0 +1,113 @@ +# Startup scene-colour report from per-draw texel history + +Refs [#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This note documents an +offline reader for the draw diagnostics that already exist. No title run was made for +this change, and no dump, game file or GPU result is checked in. + +## Command + +```powershell +python -B tools/startup/scene_color_report.py ` + [--frame ] [--pixel ,] [--baseline-raw <0xRRGGBBAA>] [--max-rows ] +``` + +The directory is the one passed to `X2W_DRAW_DUMP_DIR`. `--frame` and `--pixel` +choose the sample group; without either option the tool selects the largest group +and says so. `--baseline-raw` supplies a known pre-draw word, for the case where +the first retained sample is already the first colour write. + +The tool prints Markdown to standard output. The input path, file names, raw log +lines and arbitrary text never appear in the report. + +## Input + +`pixel_history.txt` starts with `x2w-pixel-history 1 samples=`. Each following +line is written by [`pixel_history_write`](../../src/startup_stubs/pixel_history.h): + +```text +draw= frame= x= y= key=<16 hex> count= format= raw=<8 hex> [rgba=r,g,b,a] +``` + +The runtime records one texel of render target 0 after each translated draw of +`X2W_DRAW_DUMP_FRAME` (and the following frame, when the copy completes there). It +decodes `rgba=` for `R8G8B8A8_UNORM`, `R8G8B8A8_UNORM_SRGB`, `B8G8R8A8_UNORM` and +`B8G8R8A8_UNORM_SRGB`. The copy budget is 48, so a history that reaches 48 samples +may be missing later draws. See [Per-draw texel history](../experiments.md#per-draw-texel-history) +and the [startup runtime options](../startup-runtime.md#switches). + +The `draw=` value is the runtime copy ordinal, not a title draw-call number. It is +monotonic in one process and is used here only to order the retained samples. + +When full-dump BMPs from `X2W_DRAW_DUMP_FRAME` are present, the tool reads their +headers and the selected pixel. The runtime writes either the full BMP set or the +texel history in one run, so the two are never merged: only a BMP with the same +`draw`, `key` and `count` is compared. BMP files carry no frame field. The reader +accepts BI_RGB 24-bit or 32-bit bottom-up or top-down BMPs and ignores the alpha +byte, which the runtime forces to 255. + +## What the report shows + +For the selected frame and pixel it lists the retained samples with frame, copy +ordinal, opaque pipeline key, draw `count`, DXGI format, `raw` word and decoded +`rgba`. It names both the first retained sample whose value differs from the +baseline and the last retained writer, rather than only the final value. + +| Classification | Meaning | +| --- | --- | +| `no_draw` (aucun draw) | No retained sample matches the selected frame and pixel. It does not prove the title issued no draw. | +| `ui_only` (draw UI seulement) | Samples exist, but no retained sample changes the selected pixel. This is an observation, not proof that the draws are UI. | +| `target_write` (écriture de cible) | At least one sample changed the value and the final value differs from the baseline. | +| `value_unchanged` (valeur inchangée) | At least one change was observed, but the final value equals the baseline; also used for one sample with no baseline, where no transition is observable. | +| `history_truncated` (historique tronqué) | The 48-copy cap, the input bound or a header/record-count mismatch was reached. The first and last writers are still reported from the retained samples. | +| `target_non_rgba8` (cible non-RGBA8) | The format is outside the four decodable 8-bit four-channel formats. The raw word is shown, but no colour change is evaluated. | + +The report is bounded: at most 1 MiB of history, 4,096 records, 64 BMPs, eight +sample groups and 64 timeline rows are considered. Timeline rows omitted by the +default 24-row bound are counted. Invalid lines are counted and ignored, never +echoed. When `rgba=` disagrees with `raw`, the decoded value is used and the +mismatch is counted. + +## What it proves and what it does not + +It proves only that, among the translated draws retained in `pixel_history.txt` +for the selected frame and pixel, a particular value appeared after a particular +copy ordinal and changed on a particular later draw. A BMP with the same +`draw`/`key`/`count` confirms the RGB at that pixel. + +It does not replace a run of the title. It does not show that a draw is a scene +draw rather than a UI draw, that a scene was visible, that a clear happened, or +that an untranslated draw was absent. It does not cover render targets other than +target 0, formats other than the four RGBA8/BGRA8 formats, draws after the 48-copy +cap, or the presented image. + +The history has no sample before the first draw. If the first retained draw is +itself the first colour write, the tool cannot see the transition unless the +caller supplies `--baseline-raw`. The report states that limitation next to the +baseline. A frame whose first sample is the known clear colour is the simplest +way to see the first write without an extra baseline. + +## Tests + +```powershell +python -B tests/startup_scene_color_report_check.py +``` + +The synthetic check passes 14 cases: first change and last writer, a first change +that is also the last writer, a write that restores the baseline, no observed +change, an empty history, a malformed line, a non-RGBA8 target, BGRA channel +order, the 48-sample cap with a bounded table, frame and pixel selection, a +supplied baseline, BMP match and mismatch, a header/record mismatch, and a +missing history file. The check is listed in +[`tests/checks/python-linux/scene_color_report.txt`](../../tests/checks/python-linux/scene_color_report.txt) +so the Linux CI job runs it without Windows, a GPU or a dump. + +No local dump was available under `out/` during this change, so the checked +results are synthetic. The tool was not run against the title. + +## Limits + +The parser accepts only the version-1 header and the exact field order above. +The BMP path accepts BI_RGB 24-bit or 32-bit images up to 16,384 pixels per side +and 64 MiB. A 48-sample history is reported as truncated by design, even when the +title happened to stop after exactly 48 copies. + diff --git a/docs/experiments/startup-slot70-cube.md b/docs/experiments/startup-slot70-cube.md new file mode 100644 index 0000000000..64e6775ac4 --- /dev/null +++ b/docs/experiments/startup-slot70-cube.md @@ -0,0 +1,54 @@ +# Slot-70 cube views of console-layout textures + +Device slot 70 publishes a texture by address. A description that is a two-dimensional array of six slices +in a console layout, with a `TEXTURECUBE` view, was refused with `reason=unsupported_description`, because +`address_view_fits` had no cube view. This note takes such views and binds them in a translated draw that +declares a cube texture. + +The translator does not declare one yet: `tools/startup/gfx2hlsl.py` refuses an image instruction with +`dim:SQ_RSRC_IMG_CUBE` (`image dimension SQ_RSRC_IMG_CUBE`). Until it lowers cube sampling to a +`TextureCube` and writes the `texcube` manifest kind, no translated shader reads these views. The draws here +use a hand-written pixel shader and manifest. + +## Change + +- `src/startup_stubs/address_texture.h`: `address_view_fits` takes a `TEXTURECUBE` view of a 2D texture of + exactly six slices that fits the mip range with no LOD clamp. The faces are the slices in D3D order + (+X, -X, +Y, -Y, +Z, -Z). The slices are already addressed and uploaded like any 2D array. +- `src/startup_stubs/d3d12_memory_srv.inl`: the desktop format check also asks for + `D3D12_FORMAT_SUPPORT1_TEXTURECUBE` for a cube view. +- `src/startup_stubs/d3d12_draw.inl`: a manifest `srv` line of kind `texcube` (kind 5) binds a + `TEXTURECUBE` view. The view dimension of each kind is now in one function. + A cube view where the shader declares `tex2da`, or the reverse, still binds null (view dimension mismatch). + The d16 exact path still takes only kinds 1 to 4. + +## Results + +Build: `slot70/cube-views`, stacked on `slot70/linear-1d` (42c3bff5), dev preset (debug layer on). +Windows 11 Pro 10.0.26200, NVIDIA GeForce RTX 5090 (driver 32.0.16.1088) and Microsoft WARP. + +| Test | Result | +| --- | --- | +| `startup_gfx10_layout` | PASS: 39 views (new: a whole BC1 cube chain, its last mip, past the chain, an LOD clamp, a cube view of one slice and of an array of twelve) | +| `startup_address_console_{warp,hardware}` | PASS: 3 new cube draws are exact on all 65,536 pixels, covering every texel of all six faces: RGBA8 64x64 in `0x105`, its 4-mip chain viewed at mip 1, and BC1 64x64 in `0x105`. The shader point-samples each texel centre along the face's direction | +| `startup_address_console_cube_order_{warp,hardware}` | PASS (control): the first cube with face f written into slice 5 - f is published and all 65,536 pixels differ | + +Without the source change (42c3bff5), the first cube draw reads the null view: pixel (0,0) is `00000000`, +but `010300ff` was expected. + +Commands (PowerShell, at the repository root, after `. .\tools\dev.ps1`): + +```powershell +cmake --preset dev +cmake --build --preset dev +ctest --preset dev --no-tests=error -R '^startup_gfx10_layout$' +ctest --preset dev --no-tests=error -R '^startup_address_console_(warp|hardware|cube_order_(warp|hardware))$' -V +``` + +## Open + +- The translator side: `image_sample*` and `image_load*` with `dim:SQ_RSRC_IMG_CUBE`. A GFX10 cube sample + takes face-relative coordinates and a face index that the `v_cube*` instructions compute (which + `tools/startup/gfx2hlsl.py` already lowers). A lowering to `TextureCube` would rebuild a direction from + them. That is not attempted here. +- A cube view of a larger array, and cube arrays (`TEXTURECUBEARRAY`), stay refused. diff --git a/docs/experiments/startup-table-srv-alias.md b/docs/experiments/startup-table-srv-alias.md new file mode 100644 index 0000000000..7b8e51cfca --- /dev/null +++ b/docs/experiments/startup-table-srv-alias.md @@ -0,0 +1,104 @@ +# Table buffer views over aliased placed buffers (opt-in) + +A translated draw copies every buffer it reads from the title's descriptor table into the upload ring +(`frame_copy`, see [Copies of title memory within a frame](../startup-runtime.md#copies-of-title-memory-within-a-frame)). +Within a frame the copy is reused only after a full comparison with the bytes it was made from, and the copy is +cut at 16 MiB. Vertex streams and live indices in a slot 133 placed buffer that aliases title memory bind that +alias instead (#2724, #2834). `X2W_D3D12_TABLE_ALIAS=1` does the same for table buffer views. + +## What the switch changes + +- In the `draw_translated` view loop, a table buffer view (`source 0`) that is not a formatted load, with a + nonzero range of at most 512 MiB, looks its whole range up with `placed_buffer_range`. When that finds one live + placement of kind `aliased_buffer` and the view starts 16-byte aligned in it, the draw keeps the alias alive + with the recording, requires the shader-resource states and creates a raw view over the full range. +- The raw view covers whole DWORDs, so the lookup uses the range rounded up to 4 bytes. A view whose rounded + range would run past the placement keeps the copy. +- When the same alias is also the draw's live index buffer, it is put in the index-buffer and both + shader-resource states at once, so neither binding leaves the other in a wrong state. +- The GPU then reads the title's bytes at execution. A title write between recording and submission is visible + to the draw, as on the console, where the GPU reads the same memory when the work runs. With the copy, each + draw sees the bytes as they were when it was recorded. +- Ranges past 16 MiB are bound in full; the copy reads zeros there. +- Everything else keeps the copy: formatted loads, views outside a placement or across its end, placements + that are copied or shared (`X2W_D3D12_LINEAR_BUFFERS`), released resources, unaligned offsets. +- Unset, nothing changes. + +## Fixture + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -j 1 -R '^startup_table_alias_(warp|hardware)$' -V +``` + +`X2W_TEST_TABLE_ALIAS_WRITE`: a 256-byte slot 133 buffer placed on `VirtualAlloc` memory, a raw view the title +creates over it (device slot 18) at table entry 0, and a vertex shader that reads one 8-byte record. The title +writes 40, draws the left half, writes 80, draws the right half, and writes 120 after recording, before the +list runs. + +- Unset: left 40, right 80 (each draw's copy). +- Set: both halves 120 (the alias, read at execution). +- Negative control: the same fixture with the buffer in image memory (a static array) is placed "not aliased", + and the set arm then reads 40 | 80 and fails. + +Two more cases run with the switch set. The fixture skips (77) when the adapter has no existing heaps. + +- `shared-index`: the buffer also holds the indices of one indexed draw (indices 0–2 at offset 0, index view + over the same placement). It runs under the debug layer with GPU-based validation + (`X2W_TEST_DEBUG_LAYER=1 X2W_TEST_GPU_VALIDATION=1`) and must report no error and draw 40. +- `odd-size`: a 254-byte buffer under a structured view of 127 two-byte records. The 256-byte raw view would + run past the alias, so the draw takes the copy and shows 40, not the value 120 written after recording. + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, release +build of this change on top of #2949 with `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, warm shader cache, +`run.ps1 -Render` without `-Translate`, scripted input, 250 s. One build; only `X2W_D3D12_TABLE_ALIAS` differs. +Two pairs, the second in reverse order. Aggregates only; logs stay local. + +| frames per second, 30 s windows | 150–180 s | 180–210 s | 210–240 s | +|---|---|---|---| +| unset, pair 1 / pair 2 | 8.9 / 8.6 | 5.1 / 7.8 | 3.7 / 4.2 | +| set, pair 1 / pair 2 | 11.5 / 9.8 | 8.0 / 11.2 | 6.6 / 6.1 | + +| per run, pair 1 / pair 2 | unset | set | +|---|---|---| +| translated draws | 64,296 / 88,027 | 97,419 / 100,254 | +| list executes | 14,774 / 18,151 | 22,979 / 21,373 | +| null bindings with cause `buffer` | 0 / 0 | 0 / 0 | +| null bindings per 1,000 load-phase draws (all cause `token`) | 53.8 / 46.5 | 54.0 / 50.8 | +| process commit peak | 18.1 / 17.1 GiB | 17.9 / 18.1 GiB | +| device removal | none | none | + +- Before 150 s (intro and menus) both settings run at about 30 fps. +- Where the time went, from local timers that are not part of this change (150–240 s, threads busy): + - unset: about 1.9 threads waited for `draw_lock`; the lock was held about 58 % of the time, mostly by + `draw_translated`, and 86 % of that hold was `frame_copy`; + - 97 % of the `frame_copy` time was one view: 16 MiB (cut from a 90 MiB slot 133 placed buffer that aliases + title memory) compared in full on about 140 draws per second, almost always unchanged; + - set: the lock waits fell to about 0.1–0.3 threads and the copy of that view was gone. +- A user watching the set run saw no visual difference or glitches. + +Retest after the review fixes (index state, rounded range), same settings, two more pairs (the second again in +reverse order), build = this branch after merging `main` `fb955a51`, on top of #2949: + +| frames per second, 30 s windows | 150–180 s | 180–210 s | 210–240 s | mean | +|---|---|---|---|---| +| unset, pair 3 / pair 4 | 6.3 / 7.9 | 9.3 / 4.5 | 3.8 / 4.0 | 6.5 / 5.5 | +| set, pair 3 / pair 4 | 11.9 / 11.7 | 7.9 / 10.8 | 6.5 / 8.0 | 8.8 / 10.2 | + +| per run, pair 3 / pair 4 | unset | set | +|---|---|---| +| translated draws | 73,904 / 89,833 | 120,081 / 122,176 | +| list executes | 16,022 / 21,080 | 28,516 / 25,474 | +| not drawn in the load (missing translations) | 47 % / 50 % | 50 % / 49 % | +| null bindings with cause `buffer` | 0 / 0 | 0 / 0 | +| process commit peak | 17.5 / 17.3 GiB | 17.6 / 17.5 GiB | +| device removal | none | none | + +- `draw_lock` waits 150–240 s: unset 1.0–1.5 threads, set 0.08–0.14; the draw hold 0.4–0.56 vs 0.07–0.09. +- Unset, the 16 MiB view is again 83–86 % of `frame_copy` time; set, no copy above 64 KiB remains. +- The pair 4 set arm reached the load later (27.8 fps at 120–150 s vs 19.2), which favours its later windows. + +Not established: other titles, AMD adapters, and whether any draw in this title depends on a value written +between recording and submission (none was seen). diff --git a/docs/experiments/startup-ui-regression-matrix.md b/docs/experiments/startup-ui-regression-matrix.md new file mode 100644 index 0000000000..884f1e378d --- /dev/null +++ b/docs/experiments/startup-ui-regression-matrix.md @@ -0,0 +1,104 @@ +# Startup UI regression matrix + +This note describes a report tool for the startup UI sampler, BC7 and indexed-rectangle work. It runs +existing CTest cases and does not change the runtime, the shaders or the fixtures. The matrix is a +way to collect comparable pass, skip and fail rows across builds; it is not a new rendering +measurement. + +The default rows are: + +| CTest family | Related change | What the fixture measures | +|---|---|---| +| startup_sampler_heap_wrapped_{warp,hardware} | #3153 | The wrapped D3D12 path creates a three-record sampler heap at the title's 16-byte stride, returns the title CPU handle, creates two distinct samplers, copies a record and a two-record range, and checks the destination words. The test enables X2W_D3D12_PERMISSIVE=1 and X2W_D3D12_DEBUG=1. | +| startup_xg_bc7_draw_{warp,hardware} | #3153 | A source-built BC7 surface is uploaded through the wrapped XG path with X2W_XG_BC7_4K_S_LAYOUT=1. The draw checks a 64x64 surface (4,096 pixels) and the visible part of an 81x69 surface (5,589 pixels), for both linear and 4 KiB tiled backing. | +| startup_rect_gap_{warp,hardware} | #3142 | A synthetic eight-record, 12-byte-stride stream is drawn as an R16 indexed triangle list and as six- and eight-vertex rectangle lists. A mask-controlled pixel shader and a constant-colour control distinguish coverage from attribute interpolation. The check compares all 32 target pixels with a point-in-triangle model, including a 15-degree rotation and the back-face-culling control. | +| startup_ui_texture_bands_{warp,hardware} | #3141 | A source-built 32x32, three-mip RGBA8 texture follows an indexed gradient draw and an indexed textured UI draw. The stage-by-stage check covers a linear CopyTextureRegion reference, a slot-133 copy, a compact small-texture path, and slot-70 0x105/0x10a layouts, with wrong-row-pitch negative controls. | + +The first two families are registered in the base tree used for this note. startup_rect_gap is +registered by PR #3142 and startup_ui_texture_bands by PR #3141. A build that contains only one of +those changes reports only the families it registers; the matrix does not invent missing tests. + +## Run it + +From the repository root on Windows, enter the developer environment and build the selected +configuration: + +~~~powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev +~~~ + +List the fixture names that this build actually registers: + +~~~powershell +ctest --preset dev -N -R '^(startup_sampler_heap_wrapped|startup_xg_bc7_draw|startup_rect_gap|startup_ui_texture_bands)_(warp|hardware)$' +~~~ + +Run the default matrix: + +~~~powershell +python -B tools/startup/ui_regression_matrix.py ` + --build-dir out/build/dev ` + --json out/ui-regression-matrix.json ` + --output out/ui-regression-matrix.md +~~~ + +The script accepts --ctest for a CTest executable, --adapter warp or --adapter hardware to restrict +the rows, and --filter (or one positional filter) for a CTest name regex. For example, this run +reports only the rotated-rectangle regression introduced by PR #3142: + +~~~powershell +python -B tools/startup/ui_regression_matrix.py ` + --build-dir out/build/dev ` + --filter '^startup_rect_geometry_(warp|hardware)$' ` + --json out/rect-geometry-matrix.json ` + --output out/rect-geometry-matrix.md +~~~ + +The tool first asks CTest for the matching names with --show-only=json-v1, applies the adapter +filter to that list, and then runs exactly those names with -R. It reads CTest's JUnit report, so +a CTest testcase with no failure or skip marker is the only thing counted as a pass. A notrun +testcase is a skip only when its skipped message starts with SKIP_RETURN_CODE or +SKIP_REGULAR_EXPRESSION; a missing executable, missing configuration or disabled test is a fail. +A testcase carrying a skipped element after a runnable status is a skip; a failure or error is a +fail. The Markdown +table keeps the three states visible and the JSON object has the same rows plus the summary counts +and the CTest command. + +Exit status is 0 when every selected row passed, 1 when at least one row failed or CTest returned +nonzero without a failed row, 3 when there were no failures but at least one skip, and 2 for a +malformed or empty selection, a missing CTest executable or a build that produced no usable JUnit +report. A skip therefore never turns a matrix green. A selected build with no matching tests is +rejected before any output is written. + +## What remains a limit + +- The matrix observes the fixtures registered by the current build. It does not merge PR #3141 or + PR #3142, and a family absent from that build is not a failure row. +- startup_rect_gap does not reproduce the exact indexed UI draw from issue #3131. Its synthetic + input passes without showing the reported diagonal gap. The fixed rotated-corner case is in + startup_rect_geometry; the #3142 note records the remaining unverified candidates. +- startup_ui_texture_bands demonstrates the tested upload and sampling routes. It does not prove + that the original UI draw in #3132 has the same input, texture layout or draw path. +- The adapter suffix in a CTest name is the requested backend. It is not proof that the runtime + selected that device: the rectangle fixture, for example, can report the Microsoft Basic Render + Driver for a hardware invocation. Record the observed adapter, driver, Windows build and + debug-layer status separately when a row is used as hardware evidence. +- A skip is a capability or environment result, not a pass. CTest's notrun status also covers a + missing executable, a missing multi-config configuration and a disabled test; those rows are + failures unless the skipped message explicitly carries SKIP_RETURN_CODE or + SKIP_REGULAR_EXPRESSION. A nonzero CTest exit with no failed row is also a failure. +- The matrix does not run the full startup, does not load game files and does not establish a + playable port or a frame rate. + +## References + +- [PR #3153: runtime: restore menu sampler bindings and BC7 display uploads](https://github.com/R0Y00/Xbox2Windows/pull/3153) +- [PR #3141: runtime: trace UI texture row-pitch bands and fix XG mip-0 and CopyTextureRegion tracking](https://github.com/R0Y00/Xbox2Windows/pull/3141) +- [PR #3142: startup: identify a rotated rectangle corner by its diagonal](https://github.com/R0Y00/Xbox2Windows/pull/3142) +- [Issue #3131: native UI gradient draw leaves a diagonal gap](https://github.com/R0Y00/Xbox2Windows/issues/3131) +- [Issue #3132: horizontal color bands from a textured UI draw](https://github.com/R0Y00/Xbox2Windows/issues/3132) + +The PRs provide the regression matrix and its fixtures. This note makes no closing claim for +#3131 or #3132; those conversations remain with the authors and reviewers of the respective PRs. diff --git a/docs/experiments/startup-upload-ring-release-at-submit.md b/docs/experiments/startup-upload-ring-release-at-submit.md new file mode 100644 index 0000000000..b24ea0e27e --- /dev/null +++ b/docs/experiments/startup-upload-ring-release-at-submit.md @@ -0,0 +1,78 @@ +# Upload ring: release a closed list's chunks at its fenced submit (opt-in) + +Refs [#2837](https://github.com/R0Y00/Xbox2Windows/issues/2837), +[#2849](https://github.com/R0Y00/Xbox2Windows/pull/2849). + +Since #2823 a reservation in the shared upload ring keeps its bytes until its chunk is recycled, and #2849 +recycles a chunk only when no command-list recording holds it and every queue that used it has passed its +fence. A closed list keeps its hold until Reset, Release or a failed Close, because D3D12 lets it be submitted +again. `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` moves that release to the list's fenced submit and sizes the ring +in 16 MiB chunks up to 512 MiB. + +## What the switch changes + +- After a submit whose queue fence was signalled, each submitted list stops holding its chunks + (`release_upload_chunks_at_submit`). The queue fence still keeps those chunks from reuse until the GPU has + passed it. Without a signalled fence nothing changes: the chunk stays busy, as without the switch. +- The list records the generation of each chunk it released. If the same list is submitted again before its + Reset, chunks with an unchanged generation are fenced again by that submit + (`resubmitted_upload_chunks`). If a chunk was recycled in between, the list would read replaced bytes: the + queue leaves it out of `ExecuteCommandLists` (`released_chunks_recycled`, checked with `draw_lock` and + `allocator_lock` held, the same locks the submit bookkeeping holds), counts it and logs the first eight + (`... were reused; refused, it is not executed`). The other lists of that call still run, as a list that is not + closed is left out today. It stays refused until its Reset, which records it afresh. +- The ring grows in 16 MiB chunks up to 512 MiB, so one list that is still recording or waiting to be submitted + pins 16 MiB instead of a chunk of up to 128 MiB. +- Unset, the ring behaves exactly as before: doubling chunks up to 256 MiB, holds until Reset. + +## Fixtures + +```powershell +cmake --build --preset release --target startup_stream_consumer upload_reservation_check d3d12_xs_shim +ctest --preset release --no-tests=error -j 1 -R '^(upload_reservation|startup_address_console_gate_ring_keep(_release)?_(warp|hardware))$' -V +``` + +- `upload_reservation`: `check_release_at_submit` releases two chunks after a fenced submit, keeps them from + reuse until the fence passes, reuses one, then finds the other intact and the reused one recycled on a + resubmit, and fences the intact one again. Mutants: keeping the holds fails "release: holds dropped"; + ignoring generations fails "a resubmit finds chunk 1 intact and chunk 0 reused". +- `startup_address_console_gate_ring_keep_*` (`X2W_TEST_CONSOLE_KEEP`): a second list A uploads 32 by-address + payloads of 16 MiB each from the ring (512 MiB), is submitted, completes and is never Reset. The fixture's own + list then draws payload 32 over the right half of the target, A is submitted again, and the target is read back + after that submit. + - Without the switch, A keeps every chunk: the ring refuses past 256 MiB and the right half reads the null + view. + - `..._keep_release_*` sets the switch: the right half holds payload 32 from a chunk A released. A's second + submit would read a reused chunk, so it is refused and not executed: the right half still holds payload 32, + not A's payload 31. + - Mutants: disabling the release leaves the right half on the null view; executing the stale resubmit (the + check before the execute removed) puts A's draws back over the right half and fails on wrong pixels. +- Fixtures that describe the default ring clear the switch for their own process, so they keep testing the + default mode when it is set in the environment: the #2849 `startup_address_console_gate_ring{,_reuse}_*` + (a refusal at the 256 MiB cap) and `startup_slot133_heap_cap_capped_*` (doubling growth to 48 MiB). + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, 16 GB, +release build of this change, warm shader cache, `run.ps1 -Render` without `-Translate`, scripted input, 250 s. +One build; only the switch differs. Aggregates only; logs stay local. + +| | switch unset | switch set | +|---|---|---| +| null bindings with cause `buffer` | 33,632 | 0 | +| `upload ring reservation refused` logged | yes | no | +| resubmits after a reuse (now refused) | n/a | 0 | +| process commit peak | 16.7 GiB | 18.1 GiB | +| visible | single full black frames in the post-load animation | none seen | + +- Without the switch, a census at each refusal showed every chunk held by closed lists not yet Reset, while + every queue had passed the chunk's fence. Most refused requests were 64 KiB: the window + `upload_from_title` copies for a graphics root SRV without an existing upload mapping. +- The title never submitted a closed list again without a Reset: 0 of more than 500,000 submits over five runs. + A title that does resubmit after a reuse gets the refusal described above: that list does not run. +- The larger ring cost about 1 GiB of process commit at peak in this run. +- Repeated after the stale-resubmit refusal, on a later `main`, same settings: buffer null bindings 50,665 → + 0, reservation refusals logged → none, stale resubmits refused 0 → 0, commit peak 17.9 → 18.0 GiB, black + frames → none seen. + +Not established: other titles' resubmit behaviour, and whether 512 MiB is enough on other workloads. diff --git a/docs/experiments/ttpf-manifest-dds-path.md b/docs/experiments/ttpf-manifest-dds-path.md new file mode 100644 index 0000000000..302ec99114 --- /dev/null +++ b/docs/experiments/ttpf-manifest-dds-path.md @@ -0,0 +1,32 @@ +# TTPF manifest and DDS paths + +The batch exporter rejects a manifest path that names a DDS requested by the +same batch or a supplied history or calibration input. Previously, choosing +`--indices 0 --manifest out/tex_00000.dds -o out` +could report a successful export and then replace that DDS with the JSON +manifest. A failed or skipped export could also lose a DDS preserved from a +previous run when the manifest was published. +Likewise, naming the history or calibration file as the manifest replaced the +input profile with an export-results array, preventing its reuse on the next run. + +The path check runs after reading the pool count, before creating the output +directory or starting any export. It uses the existing resolved-path and file +identity checks. A manifest with the same filename in a different directory is +still accepted. +Profile collisions are rejected before loading the decoder tools. + +The synthetic regression exercises successful, failed and skipped exports with +and without an existing DDS. All six cases fail with the old exporter because +it accepts the collision. The separate-directory control succeeds and verifies +the DDS bytes against the manifest checksum. +Two further cases verify that history and calibration inputs remain unchanged; +both fail with the old exporter because it accepts and overwrites the profile. + +```powershell +python -B tests/ttpf_batch_export_check.py +python -B tests/ttpf_batch_export_cli_check.py +``` + +These checks use the mocked exporter and generated inputs; the optional local +Leonida integration test can skip when its tools are not installed. They make +no claim about image decoding correctness. diff --git a/docs/experiments/xmem-page-runs.md b/docs/experiments/xmem-page-runs.md new file mode 100644 index 0000000000..148b3fb9b2 --- /dev/null +++ b/docs/experiments/xmem-page-runs.md @@ -0,0 +1,63 @@ +# XMem page runs: placeholder splits, joins and run breaks + +Refs [#2911](https://github.com/R0Y00/Xbox2Windows/pull/2911). The fixtures below cover the shim's mapping of +physical pages into XMem reservations with shared views (`X2W_XMEM_SHARED_VIEWS=1`). The results quoted here were +measured under Wine (Proton Experimental, November 2026) on Linux x64, with a clang-cl cross build and each CTest +entry's command run through Wine in one prefix. They are not Windows results. The D3D12 fixtures at the end have no +result there. + +## Placeholder split for queue slot 31 + +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. Limit: the fallback cannot tell a reserved page of a private allocation made with `VirtualAlloc2(MEM_REPLACE_PLACEHOLDER)` from a placeholder, because Wine does not refuse the release for that kind of allocation. After the refused view, the batch retries each page on its own and releases the reserved first page, which cuts it out of the caller's allocation: under Wine the committed page's allocation then starts one page later. The fixture prints where that allocation starts and asserts only that the first page is still one reserved page at its own address. Where the OS reports the bit, the fallback is not used. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. + +## Split before map + +`xmem_map_split_first` maps eight single pages with `XMemMapPhysicalPages`, each into the middle of the +reservation's placeholder. xmem splits first and maps once, so the eight pages take eight `MapViewOfFile3` attempts +and eight splits, and an exact placeholder left by an unmap is mapped without a split. `xmem_map_split_first_control` +runs the old map-first order in the test-controls build (`X2W_XMEM_TEST_MAP_FIRST=1`) and must measure 16 attempts. +`xmem_map_split_first_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must measure +8. Measured under Wine: 8, 16 and 8. Run `ctest --preset dev --no-tests=error -R '^xmem_map_split_first' -V`. + +## Joins across mapping calls + +With shared views, the pages of one call that are adjacent slots of one section share a view. A call joins the run +that ends at its address only with `X2W_XMEM_JOIN_CALLS=1`, which counts only with shared views on. It is off by +default; `tools/startup/run.sh` sets it, and `tools/startup/run.ps1 -LazyMemory` does not. `xmem_cross_call_merge` +checks the joined layout (32 single-page calls on consecutive slots give one view of 32 pages) and the cases around +it. `xmem_cross_call_merge_no_join` checks that the deployed shim with shared views and no join switch keeps a view +per call (32 views). `xmem_cross_call_merge_control` turns the merge off in the test-controls build +(`X2W_XMEM_TEST_NO_MERGE=1`) and must also show 32 views; `xmem_cross_call_merge_deployed` sets that switch for the +deployed shim, which ignores it and joins. All passed under Wine. Run +`ctest --preset dev --no-tests=error -R '^xmem_cross_call_merge' -V`. + +## Run breaks and the fault handler + +Unmapping a page of a shared view unmaps the whole view and maps its other pages again; a join and a slot 31 batch do +the same for the runs they change. `xmem_run_break_readers` holds that window open (the test-controls build's +`X2W_XMEM_TEST_HOLD_WINDOW`) and checks that each reader either waits for it or, for a pipe `ReadFile`, fails inside +it without being run again (under Wine with `ERROR_NOACCESS`, both queued messages kept). The access-violation +handler retries a fault on a page whose view was mapped inside a break, once per break and thread. +`xmem_run_break_readers_stamps` holds a fault's handler while 63, 64 and 200 later breaks run on another page; each +fault is retried (under Wine the later breaks took 3, 4 and 10 ms). In the same mode, a page made no-access faults +once on a run no break has mapped (passed on at once) and twice after a break mapped it (one retry), counted by a +first-chance handler of the test. Run `ctest --preset dev --no-tests=error -R '^xmem_run_break_readers' -V`. + +## DirectStorage copies into runs + +`startup_dstorage_break_window` submits a memory-source request into a page of a run while an unmap holds the run +apart: the request must not complete during the 1000 ms hold, then lands; its control, an XCRDAPI that judges the +destination with its own query, refuses inside the window. The copy takes xmem's mapping mutex only when the +destination or source overlaps a run: `startup_dstorage_break_window_plain` measures a `VirtualAlloc` destination +copied without it and a run destination with it, and `startup_dstorage_break_window_views_off` an XMem page +destination copied without it when shared views are off (`x2w_xmem_copy_counts`, test-controls build). +`startup_dstorage_break_window_outcomes` forces each copy error (`X2W_XMEM_TEST_COPY_ERROR`) and checks the outcome +XCRDAPI logs for it. All passed under Wine. Run +`ctest --preset dev --no-tests=error -R '^startup_dstorage_break_window' -V`. + +## D3D12 fixtures (not run here) + +`xmem_page_runs_device_warp`, `xmem_page_runs_device_join_warp` and `linear_buffer_backing_share_warp` check view +boundaries through D3D12 placed resources. They need D3D12 with WARP, which the Wine prefix above does not provide: +they fail there (`linear_buffer_backing_share_warp`: "WARP device not created"), so this note has no result for +them. diff --git a/docs/non-windows-hosts.md b/docs/non-windows-hosts.md index cf71bc2ca6..e868b1f2d9 100644 --- a/docs/non-windows-hosts.md +++ b/docs/non-windows-hosts.md @@ -83,6 +83,7 @@ LLVM_LIB="$LLVM_PREFIX/lib/libLLVM-15.dylib" \ The [CI workflow](../.github/workflows/windows.yml) runs the platform-independent Python suite on Ubuntu 24.04 with Python 3.12 (`python-linux`) and the `gfx1013` machine-code checks on Ubuntu 22.04 with LLVM 15 (`pixel-binary`). Both jobs use `tools/run_checks_parallel.py`; the machine-code matrix supplies per-check LLVM arguments and environment overrides. +Besides the inline lists, both jobs also run the checks listed in `tests/checks/python-linux/*.txt` and `tests/checks/pixel-binary/*.txt` (`--from-dir`); a new check can go in its own file there, see [tests/checks/README.md](../tests/checks/README.md). The runner lists checks that exit 77 under `SKIPPED:` and other nonzero exits under `FAILED:`. Either summary makes the runner exit 1 so CI catches required checks that did not run. Open a skipped check's log group to see its output. On Debian/Ubuntu, install `python3-venv` first. Without it, `python3 -m venv` fails with `ensurepip is not available`: @@ -178,7 +179,7 @@ With the Linux build of DXC, `spirv-val` and `spirv-dis` from SPIRV-Tools, a C c python3 -B tests/pixel_denorm_vulkan_check.py /path/to/dxc tests/vk_pixel_draw.c --device Intel ``` -`--device` is a substring of the Vulkan device name (repeat it for several adapters), and `VK_DRIVER_FILES` selects a driver such as lavapipe. To build the host once and reuse it, run `cc -std=c11 -O1 -o out/vk/vk_pixel_draw tests/vk_pixel_draw.c -lvulkan` and pass `out/vk/vk_pixel_draw` instead of the `.c` file. +`--device` is a substring of the Vulkan device name (repeat it for several adapters), and `VK_DRIVER_FILES` selects a driver such as lavapipe. To build the host once and reuse it, run `mkdir -p out/vk && cc -std=c11 -O1 -o out/vk/vk_pixel_draw tests/vk_pixel_draw.c -lvulkan` and pass `out/vk/vk_pixel_draw` instead of the `.c` file. A `ps_6_2` pixel shader runs seven operations whose inputs or results are binary32 subnormals and writes each result word to its own RGBA32UI pixel. DXC compiles it with `-spirv -fspv-target-env=vulkan1.2 -fvk-b-shift 0 0 -fvk-t-shift 16 0 -fvk-s-shift 32 0 -fvk-u-shift 48 0`. The words read back must equal IEEE binary32 arithmetic computed in Python under `-denorm preserve`. The same shader compiled with `-denorm ftz` is the negative control and must differ, otherwise the check fails because it cannot tell preserve from flush. The log lists the device, driver, DXC and SPIRV-Tools versions, the SPIR-V execution mode, every word read back for both modes and the cases where the control differs. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 1353b96e3f..8c4a1625fb 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -47,15 +47,13 @@ controls for other barrier types, flagged barriers, invalid resources and arrays ## Occlusion queries -Which console methods sit at command-list slots 28 to 30 is not established by any fixture here. The repository -places `ResourceBarrier` at 26 and four additional console methods in the 26 to 31 range -(32 is `SetDescriptorHeaps`, desktop 28 plus four). It also shows that -the plus-four run has ended by 61 (`ExecuteIndirect`, desktop 59 plus two). As a hypothesis, slots 28 to 30 are -implemented as `BeginQuery(heap, type, index)`, `EndQuery(heap, type, index)` and -`ResolveQueryData(heap, type, start, count, buffer, offset)`. Because that is a hypothesis, the bindings are a -diagnostic opt-in: only with `X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay -no-ops as before. The fixture below calls those slots directly, so it checks the forwarding, the refusals and the -end at Close, not the numbering. +The GXDK 261000 `ID3D12GraphicsCommandList8` table confirms `BeginQuery`, `EndQuery` and +`ResolveQueryData` at command-list slots 28 to 30, and `SetPredication` at 31. Slots 32 to 55 +are the desktop slots 28 to 51 plus four; slots 56 to 58 are `SetMarker`, `BeginEvent` and +`EndEvent`, and `ExecuteIndirect` is 61. The query bindings stay a diagnostic opt-in: only with +`X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay no-ops +as before. The fixture below calls those slots directly, so it checks the forwarding, the +refusals and the end at Close, not the numbering. The query heap comes from device slot 39 with the desktop desc, which the stand-in keeps. Only occlusion and binary-occlusion queries on an occlusion heap, recorded on a DIRECT list, are forwarded to the desktop list. A @@ -76,7 +74,7 @@ the console `Map`. It then checks that the refused calls, among them resolves ov with a hole and an index ended with the other occlusion type, leave the sentinel untouched with no debug-layer error, and it leaves one query open at Close. `startup_list_queries_default_{warp,hardware}_control` runs it without the switch: the slots stay no-ops and it must report the untouched sentinel in the first word. -`command_list_slot_names.h` still names 56 to 58 as the query methods by the plus-four rule. +Slots 56 to 58 are the desktop marker methods, not query methods. ## Depth target on translated draws @@ -118,7 +116,11 @@ the registers the routine loaded. The routine's code is not in the shader contai The stand-in reads the `INPUT_LAYOUT` subobject and publishes it next to the request as `req_.ia`, before `.a`. The file holds `ia1 ` and then one line per element: semantic, index, format, slot, offset, class -and step rate. A stream with a non-empty layout includes that text in its cache key; other keys are unchanged. +and step rate. A stream with a non-empty layout includes that text in its cache key; other keys are unchanged. A layout declared +with zero elements publishes nothing by default, so the fetch is refused and not drawn, like an absent or unreadable +layout. With the experimental opt-in `X2W_STREAM_ZERO_FILL=1` it is published as the single line `ia1 0`, and the +translation reads every fetched register as zero. That zero value is an assumption, not a measurement: no independent +reference shows what a fetched input holds for a zero-element layout, so no startup claim rests on it. One log line per stream gives the element count and, for each element, format, slot, offset and class: `x2w-draw stream input layout: 2 elements (format/slot/offset/class) 6/0/0/0 6/0/4294967295/0`. @@ -204,10 +206,25 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-17`. Earlier translations lower `v_med3_f32` through a -branchless median, which returns the smaller of the other two operands when a source is NaN. The matching -compute (`x2w-startup-shader-17cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance -because those stages use the shared lowering. +Graphics and compute use cache revisions `x2w-startup-shader-29` and `x2w-startup-shader-29cs`. +Revision 29 invalidates compute translations whose skipped-block proof kept a stale clear `vcc_hi` fact +across an unsigned `v_mad_u64_u32` carry-out, which may write `vcc_hi` in wave64 like the compares and +the other carry-outs. +Revision 28 lowers `v_fma_mix*` through a `precise` `mad`, so a zero product keeps its sign. +Revision 25 preserves the sign of zero in binary16 multiply, including the packed and SDWA forms. +Revision 24 invalidates translations that revision 23 wrongly accepted: `vcc_hi_scalar_mask_read` now also +treats a whole-word lane-read writer (`v_readfirstlane`/`v_readlane`) of vcc_hi, in branch order too, as +making a later VOP3 lane-mask read of vcc_hi refuse instead of lowering to bit 0. The two cache keys advance together. +Revision 22 invalidates compute shaders that assumed the entry EXEC mask at a load reached on a later +loop iteration after an EXEC write. The two cache keys advance together. +Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data). +Revision 20 decodes MTBUF/MUBUF format 50 (`R10G10B10A2_UNORM`) in the run-time FORMAT switch. +Revision 19 folds `s_mov_b32` from a scalar register that holds a plain constant, so later reads of the copy use the constant word. The fixed slot 57 mesh +(`x2w-startup-mesh-57-3`) key stays, because that shader is not translated from guest code. +Revisions before 19 read a register copied from a constant as a run-time value. +Revision 18 preserves the sign of zero in floating-point min, max, min3, max3 and med3. +Revisions before 17 lower `v_med3_f32` through a branchless median, which returns the smaller of the +other two operands when a source is NaN. Revisions before 16 lower `v_fract_f32` through a bare `frac` instead of the clamped `fract32` helper. Revisions before 15 lower `v_cvt_pk_u8_f32` with a float clamp and accept `s_setreg_imm32_b32` writes of the rounding mode. @@ -271,6 +288,79 @@ presenter, its owned window and a dialog stay visible. Where the host lets the t it also checks that the foreground moves to the output window. A run under Wine did; the fixture prints which case applied. +### Presented planes + +A console present (CommandQueue slot 32) carries a plane count and an array of plane records +(`src/startup_stubs/present_planes.h`). Measured from the first presents: one record is 0x48 bytes, +with +0x00 a frame token, +0x08 the resource count and +0x10 a pointer to the resource array. On the +Series S profile a title presented two planes: plane 0 at 1920x1080 stayed black and plane 1 at +3840x2160 held the picture, with alpha 255 wherever it drew. Showing plane 0 alone gave a black +window. Why plane 0 stays black is not known. + +By default the output window still shows plane 0 alone, as before the planes were decoded. The +experimental `X2W_PRESENT_COMPOSITE=1` makes it composite the planes instead +(`src/startup_stubs/plane_compositor.h`, shared by the window presenter and its fixture). It stays +opt-in until a matched comparison on the same executable, with this change alone, shows what it does +to a real present. The contract under the switch: + +- Order: plane 0 first, each later plane over it, in plane order (`composite_steps`). At most four + planes are read. +- The lowest drawn plane is opaque: its colour replaces the window and its alpha is ignored. +- Each later plane is blended by its own alpha, not premultiplied: + `rgb = src.rgb * src.a + dst.rgb * (1 - src.a)`, `a = src.a + dst.a * (1 - src.a)` (D3D12 + `SRC_ALPHA` / `INV_SRC_ALPHA`, alpha `ONE` / `INV_SRC_ALPHA`). Alpha 0 leaves what is below, + alpha 255 replaces it, and the window alpha stays 255. +- Left out: a plane whose record or resource array is unreadable or empty, a surface that is not a + known resource or that the presenter cannot draw (`present_view_format.h`), and a repeat of a + surface already drawn. If plane 0 is left out, the next drawn plane is the opaque base. +- Each plane is scaled to the whole window with a linear, clamped sampler. The planes' source and + destination rectangles in the record (after +0x10) are not decoded; a plane that covers only part + of the screen on the console is stretched here. +- The baseline capture is unchanged with or without the switch: the frame capture, the presented + signature, `X2W_D3D12_DUMP_SURFACE` and the `x2w-render presented` readback all read plane 0's + first resource, as before. Under the switch the highest plane above plane 0 with a known resource + is also sampled on the same frames, before compositing, and logged as a raw plane: + + ```text + x2w-render raw plane (not composited): surface x format , sample , mean level /255, mean alpha /255 + ``` + + Neither line is the composited window picture. + +The diagnostic readback publishes pixels only after its queue fence reaches +the submitted value without reporting device removal. A timeout, a failed +event registration or an incomplete fence after the event registers a drain: +a threadpool wait on the submitted fence value that releases the held surface +and queue references once the fence completes and publishes no pixels, so a +final sample no longer keeps them for the module lifetime. The drain releases +only the submission it was registered for (a later sample owns its own) and +never releases pending, failed-signal or device-removed work; a failed signal +or removed device disables further diagnostic readback for the module +lifetime. `startup_present_readback` exercises the completion policy and the +ownership retirement without a GPU. + +The first presents and every 300th log each plane: + +```text +x2w-present frame plane /: x format flags=0x +``` + +`ctest --preset dev --no-tests=error -R '^startup_present_planes(_control)?$'` checks the record layout +and the composite order on synthetic records; the control reads 0x40-byte records and composites +plane 0 alone, and must print `FAIL:`. +`ctest --preset dev --no-tests=error -R '^startup_present_composite_(warp|overlay_removed_control_warp)$'` +draws source-built planes through the same records, `composite_steps` and compositor (directly, without +the switch) into a 64x32 RGBA8 target on WARP and reads every texel back: a single plane is shown as is (including a cell with alpha 0); a black +plane 0 under a plane with alpha 0, 128, 5 and 255 cells and a third plane with opaque and +half-transparent cells gives 0, 128, 5 and 255 levels and the plane-order result 128,0,127 for half +red over blue (within 1 for blended cells, exact otherwise); a repeated surface and an empty record +are left out. The control runs the same cases, then removes the overlays and composites the black +plane 0 alone. It passes only on `control ok: baseline matched, ...`, printed when the baseline and +stacked cases matched, every fence completed without device removal, and the overlay-free picture is +black and differs from the stacked expectation in exactly the six cells the overlays draw. Any `FAIL:` +line fails it, including queue, compositor, target or plane setup, a fence that does not complete and +device removal. Both exit 77 without a WARP adapter. + ## Null Texture2D descriptors When the adapter lacks typed UAV support for B5G5R5A1_UNORM or render-target support for @@ -285,6 +375,52 @@ dimensions, formats, resources and counters that are left alone. A rewrite must field of the description. `startup_null_texture_view_unchecked_fallback_control` rewrites without asking about R8G8B8A8 and must fail. +## Unknown and mismatched view dimensions + +A view description with `ViewDimension` 0 (UNKNOWN) makes desktop D3D12 remove the device instead of +failing the call, and so does a dimension that does not suit the resource (debug layer: "The +ViewDimension in the View Desc is incompatible with the type of the Resource"). Measured: a console +package module made such SRVs on 2D RGBA8 textures. Views of device slots 18 to 21 (shader resource, +unordered access, render target, depth stencil) are now checked before they are forwarded: + +- an SRV (slot 18) with dimension 0 gets the resource's default view (a null description) where + desktop allows one: a texture with a typed format that is not a depth format. The default view + replaces the whole description, including its format and component mapping. Only this SRV case is + measured. With dimension 0 every other view is skipped; +- a dimension whose resource dimension differs from the resource's is skipped. + +The default view for UAV, RTV and DSV descriptions with dimension 0 is an explicit experiment, +`X2W_D3D12_VIEW_DEFAULTS=all`: it is unmeasured, and it drops the requested format the same way. +`X2W_D3D12_VIEW_DEFAULTS=off` skips the SRV case too. Any other value, or none, keeps the SRV +default. + +A refused SRV, for any reason, writes a null SRV (R8G8B8A8_UNORM, the requested dimension where it +is a texture dimension, else 2D) into its destination descriptor. Otherwise the slot would keep the +view it held before. That view would still be bindable and would be copied by `CopyDescriptors`, +although the slot's record no longer keeps its resource alive. Translated draws already resolve the +slot to nothing. + +A refused UAV, RTV or DSV leaves the previous descriptor and its tracking record in place. + +The first of each are logged (`x2w-d3d12 Device::slot view dimension ...`), and when a view still +removes the device, its forwarded description and the resource's shape are logged +(`removing view desc`). Run +`ctest --preset dev --no-tests=error -R '^startup_view_dimension(_control)?$'` +(`src/startup_stubs/view_dimension.h`); the control swaps the resource dimension of the mismatched +cases for the matching one and must print `FAIL:`. + +`startup_view_dimension_warp` goes through `d3d12_xs.dll` on WARP. A compute shader samples each +descriptor of a shader-visible heap through the wrapper's desktop heap. The fixture checks three +cases. An unknown-dimension SRV of a texture filled with one distinct colour must read back that +colour. An explicit TEXTURE3D SRV of a 2D texture must be refused with the device not removed. +A descriptor slot that held a valid view of a second colour, then receives a refused TEXTURE2D +SRV of a buffer, must read zero, and so must a `CopyDescriptorsSimple` copy of it. The slot gate +for UAV, RTV and DSV is checked without a device by `startup_view_dimension`. +`startup_view_dimension_off_control_warp` runs the same fixture with +`X2W_D3D12_VIEW_DEFAULTS=off`. It must print `FAIL: (a) default view` with `device not removed`, +so it fails on the missing default view and not on setup or a removed device. Both return 77 +without WARP. + ## 16-bit packed targets A description that asks for a B5G5R5A1_UNORM, B4G4R4A4_UNORM or B5G6R5_UNORM render target is created as @@ -394,6 +530,17 @@ one address between two draws of a frame, such as a dynamic constant buffer, gav data. The comparison uses the kept bytes because the ring is write-combined memory that is slow to read. `startup_frame_copy_{warp,hardware}` rewrites a constant buffer between two draws and checks both halves. +A table buffer view (an SRV read from the title's descriptor table) is copied the same way, at most 16 MiB of it. +For a large view the comparison costs a full read of the kept bytes on every draw, under `draw_lock`. With +`X2W_D3D12_TABLE_ALIAS=1` (opt-in, render mode), a table buffer whose whole range lies in a slot 133 placed buffer +that aliases title memory binds that alias instead, as vertex streams and live indices already do: no copy, no +comparison, and no 16 MiB cut. The GPU then reads the bytes as they are when the list runs, not as they were when +the draw was recorded, so a title write between recording and submission becomes visible to the draw (on the +console, the GPU also reads the shared memory at execution). Formatted loads, views over other memory and +unaligned offsets keep the copy. `startup_table_alias_{warp,hardware}` writes a record, draws, rewrites it, draws +again and rewrites it after recording: unset, the halves show the first two values; set, both show the third. See +[the experiment note](experiments/startup-table-srv-alias.md). + ## Root signature changes and dropped root constants Command-list slot 34 (`SetGraphicsRootSignature`) clears the translated draw's cached descriptor tables, root @@ -434,8 +581,9 @@ Three census lines follow the five-second report whenever their counts changed - `x2w-d3d12 memory SRV refusals (slot 70): total N; n, ...; distinct shapes K` counts every refused slot 70 call by reason. It then prints one `x2w-d3d12 memory SRV refused shape i:` line per distinct `reason`, dimension, format, size, mips, layout and flags, for the reasons that depend on the - description (all but `null_destination`, `unreadable_resource`, `unreadable_view`, `null_address` and - `destination_outside_view_heaps`). The reasons include the partial-tile holds (`partial_tile_*`) and the + description (all but `null_destination`, `unreadable_resource`, `unreadable_view`, `null_address`, + `destination_outside_view_heaps` and the acceleration-structure holds `as_unaligned`, `as_not_placed` and + `as_wrong_state`). The reasons include the partial-tile holds (`partial_tile_*`) and the console-layout holds (`unsupported_desktop_format`, `console_layout_*`, `overlapping_resource`). Up to 128 shapes are kept; later shapes are only counted. The periodic report lists the shapes counted since it last ran. @@ -537,6 +685,13 @@ one on the desktop list, as before; a flagged one is deferred (`root signature . the desktop list`, first three). Root SRVs (slot 44) are not forwarded under a deferred root. Translated draws use their own root signature (no flags) and are unaffected. +A root SRV (slot 44) at a title address without an upload mapping copies a 64 KiB window of title memory into the +upload ring for the desktop binding. No draw reads that binding today: translated draws set their own root signature +and copy the SRV from its title address at the draw, a forwarded slot 12 draw needs a desktop pipeline without an +indirect graphics root (only compute pipelines), and an indirect graphics draw binds a pipeline over the list's root. +With the opt-in `X2W_D3D12_ROOT_SRV_AT_DRAW=1`, slot 44 skips the copy and leaves the parameter unbound on the desktop +list (`startup_root_srv_draw_*`; see [the experiment note](experiments/startup-root-srv-at-draw.md)). + A real draw under a deferred root is decided by `src/startup_stubs/heap_indexed_root.h`: it may bind only when the list holds a mirror of every heap the root indexes, covering the indices the draw reads, and every root constant, descriptor table and root descriptor can be set again. A one-entry sampler heap covers only index 0 and never stands @@ -652,7 +807,14 @@ ctest --preset release --no-tests=error -R '^startup_stubs$' -V ``` The build produces `xmem.dll`, `d3d12_xs.dll`, `AcpHal.dll`, `XCRDAPI.dll`, `chad.dll`, `xapu.dll`, -`xg_xs.dll` and `GameInput.dll`. Without the switches, every export that has no implementation +`xg_xs.dll` and `GameInput.dll`. To run a title you need only these eight and the build revision stamp, not the test +executables: `cmake --preset release` once, then + +```powershell +cmake --build --preset runtime +``` + +builds the `startup_runtime` target, which depends on exactly the files `run.ps1` copies. Without the switches, every export that has no implementation traps: it logs `x2w-trap !` with its argument registers and ends the process with a code that names the export (see `src/startup_stubs/trap.h`). @@ -665,15 +827,20 @@ Alternatively, stage one executable and its adjacent DLLs with: .\tools\startup\stage_package.ps1 -PackageDir -Exe .exe -RunDir <fresh run folder> ``` -The destination must be absent or empty and separate from the package. Archives and subdirectories -are not copied. Keep using the package root as `-DataDir`, then run the staged executable: +The destination must be absent or empty and separate from the package. The helper checks resolved +paths as well as their spelling, and stops if Windows cannot resolve an existing path (which can +occur on some network shares). Archives and subdirectories are not copied. Keep using the package +root as `-DataDir`, then run the staged executable: ```powershell .\tools\startup\run.ps1 -Exe <folder>\<title>.exe -DataDir <package root> -LogDir out\startup\run1 ` -Seconds 180 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70" ``` -`run.ps1` copies the stand-ins next to the executable and starts `tools/startup/debug_launch.py`. +`run.ps1` copies the stand-ins next to the executable (build them with `cmake --build --preset runtime`) and starts +`tools/startup/debug_launch.py`. +Use `-BuildDir` to select their build directory; relative paths are relative to the repository root, +and absolute paths are used as supplied. The default is `out/build/release`. It runs the debugger with `out/pe-env/Scripts/python.exe` when that environment exists, because `-HostCpu` needs `iced-x86` from `requirements-dev.txt`; otherwise it falls back to `python` from `PATH`. @@ -700,6 +867,20 @@ that its fixture's module and export are in that list, that a source-built DLL l movie-player module name is not hooked by default, that each of its 7 export calls is counted with `--trace-calls 1`, and that `--trace-calls 1` with file tracing off counts nothing and says why. +**Window pictures.** At the end of a run that is still going, `debug_launch.py` saves the client area of the +title's window as `window.png`. `--capture-every <seconds>` (`run.ps1 -CaptureEvery`, `run.sh --capture-every`) +also saves it every N seconds (N is at least 1; 0, the default, is off) as `window_<sss>s.png`, with the seconds +since the process started, so a run that passes several screens leaves one picture per screen. A frame whose +pixels equal the previous frame is not saved, at most 120 files are written (later changes are counted, not +saved), and the summary prints one line such as `window captures: 12 saved, 7 unchanged skipped, first change +at 74 s`. A thread of its own takes the pictures, so a capture never delays the debug events, and the +conversion to PNG uses whole-buffer slices instead of a per-byte loop. The end-of-run `window.png` is +unchanged. `tests/startup_window_capture_check.py` checks the file names, the skip, the cap, the summary line +and the pixels of the PNG against a per-pixel reference. `tests/startup_debug_window_check.py` runs the +source-built `tests/startup_window_probe.cpp` (a window that is red, then blue after 3.5 s) with +`--capture-every 1`: one red and one blue frame are saved, the others are skipped, the reported first change +falls in the second the probe changes it, and without the option no `window_<sss>s.png` exists. + `run.ps1 -TraceApi` sets `X2W_TRACE_API=1` for the child process and enables `x2w-api` lines for individual runtime provider methods. Use `-TraceCalls` for the debugger breakpoints described above. The switches work independently and @@ -740,6 +921,38 @@ It writes: | `<log>/files.txt` | every file the process opened | | `<log>/translate.txt` | with `-Translate`: one line per shader request translated during the run | +### Package on another volume + +A console executable opens its package at a fixed drive letter, so a package that lives on another +volume never mounts: the first open returns "not found", nothing is mounted, and the run usually +stops within a second on a table sized from data that was never loaded. `-MapDrive` rewrites opens on +a mapped letter to the real folder, in the caller's own path structure and inside the debugger's +existing file hook, so the letter does not have to be free and a real volume on it is not disturbed: + +```powershell +.\tools\startup\run.ps1 -Exe <folder>\<title>.exe -DataDir <package root> -LogDir out\startup\run1 ` + -MapDrive "G=D:\package" +``` + +The value is `LETTER=FOLDER`, and several mappings are separated by `;`. The debugger logs a `MAP` +line for each rewrite and the rewritten path in `<log>/files.txt`. An open on a letter that is not +mapped is left untouched. The rewritten name is borrowed for the hooked call only: the caller's +`UNICODE_STRING` is restored (length, buffer pointer and contents) when the call returns, so a +failure or a retry sees the name it built. When the replacement does not fit the caller's buffer the +debugger borrows a name buffer for the duration of that call and returns it to a pool on restore, so +serial opens reuse one buffer instead of allocating per open and overlapping calls do not share one. +One limit remains: only opens that pass through the file hooks are rewritten, so a title that reads +its package through a memory-mapped API is not covered. A call that enters the same hooked function on +another thread is rewritten too: the debugger holds the other threads for each step over a hooked byte +([Concurrent calls through a hooked function](#concurrent-calls-through-a-hooked-function), #1281). +`startup_map_drive` covers the rewrite, the negative control without the option, that an unmapped letter +is left alone, and one caller-owned `UNICODE_STRING` reused across 32 serially opened files with its +length, buffer pointer and contents checked after every return and a single name buffer. +`startup_map_drive_overlap` runs two threads of 32 opens each with their own caller-owned names: all 64 +opens must see the mapped name and succeed, every caller string must be back as built and the debugger must +report no unprotected window, three times. Its control without holding the other threads +(`--suspend-others 0`) must lose opens. + ### Translating shaders during a run With `-Render -Translate`, `run.ps1` starts `tools/startup/gfx2hlsl.py --watch <shader cache>` beside @@ -747,32 +960,74 @@ the debugger and stops it, with its worker processes, when the debugger returns without `-Render` is ignored with a warning). The watcher repeats the `--pending` scan every 2 seconds (`--watch <dir> <seconds>` sets another interval), so a pipeline the title creates during the run is translated within seconds, and the runtime picks it up on a later draw instead of on the -next run. The cache persists: a later run reads every published `<key>.txt` and translates only new +next run. The runtime looks for an absent manifest again 1 second after the first miss and doubles +the wait with each further miss up to 32 seconds. A translation published during the run is therefore +used on a draw or Dispatch at most 32 seconds later, and a key that never gets a translation costs one +cache lookup every 32 seconds instead of one per second (each lookup holds `draw_lock`, which every draw +and Dispatch takes). The cache persists: a later run reads every published `<key>.txt` and translates only new requests. The watcher's first pass retries every earlier failure once, so a translator update reaches requests that failed in an earlier run; after that, a request whose `<key>.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites -it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written -to `<key>.fail` as `translator error: ...`, ending with the function, file name and line that raised -it, skipping standard-library frames (`(in scalar_select, gfx2hlsl.py line 1234)`), instead of -stopping the scan. An operand refusal +it). The one-shot `--pending` scan retries every failure unless `--skip-failed` (`-s`) or +`X2W_SKIP_FAILED=1` is set, which skips requests whose `<key>.fail` is already up to date with their +ready marker and stream description. During `--watch`, published requests are kept in an in-memory +completion set so repeated passes skip re-reading container bytecode from disk when +request files, descriptions and published stage metadata are unchanged. An unexpected +translator error is written to `<key>.fail` as `translator error: ...`, ending with the function, file +name and line that raised it, skipping standard-library frames (`(in scalar_select, gfx2hlsl.py line 1234)`), +instead of stopping the scan. An operand refusal in `<key>.fail` names the instruction that refused it (`operand '-v30' in v_and_b32_e64`); the refusal's own message, which `--refusals` counts, stays `operand '-v30'`. A worker killed from outside (for example out of memory) ends that watcher pass only; its requests are retried on the next pass. FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than one pending request translates them in parallel processes, one per logical processor (at most 61 on -Windows, the `ProcessPoolExecutor` limit) unless `X2W_TRANSLATE_JOBS` sets the count; each request -writes only its own files. On a 16-thread host, +Windows, the `ProcessPoolExecutor` limit) unless `--jobs <n>` (`-j <n>` or `--jobs=<n>`) or +`X2W_TRANSLATE_JOBS` sets the count; each request writes only its own files. On a 16-thread host, 3,513 requests (132 translated, 3,381 refused) took 56.9 s with one process and 7.8 s in parallel, with byte-identical results. Check with `python3 -B tests/startup_gfx2hlsl_watch_check.py` (ctest `startup_gfx2hlsl_watch`): a request without its ready marker is not consumed, the watcher retries an earlier failure once and -then leaves failures alone, it translates a request written while it runs, four parallel workers +then leaves failures alone, `--skip-failed` skips up-to-date failures, the in-memory cache skips +published requests without re-checking container bytecode, four parallel workers print the same results and write the same failures as one, an unexpected translator error becomes `<key>.fail`, and an invalid `X2W_TRANSLATE_JOBS` falls back to the processor count. `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together with a child process. +### Translating compute programs in the stand-in + +With `X2W_NATIVE_SHADERS=<directory of dxcompiler.dll and dxil.dll>` (`run.ps1 -Render -NativeShaders <dir>`), +the stand-in translates a device slot 67 request itself, with the C++ compiler in +`src/gfx1013_compute_native.cpp`, on the first Dispatch of its pipeline. No watcher is needed for those +pipelines, and the cache can start empty: the request files the stand-in wrote are read back, checked +against their key, translated and compiled to DXIL in the process. The compiler's own cache goes to +`<shader cache>\native`. Nothing is published as `<key>.txt`. + +The existing dispatch path records the result, and a program is accepted only with the bindings a +fixture has run through it: root constants, raw table buffers loaded per lane (`buffer_load_dword`) +and raw table buffers stored to, with their descriptors in 32-byte table records. Anything else (a +scalar buffer load, a texture, a sampler, a typed or indexed view, an instruction the compiler does +not lower) is refused. Programs published as `<key>.txt` also bind 1D, 2D, 2D-array and 3D texture SRVs +(`srv N tex1d|tex2d|tex2da|tex3d table R B`) from the title's described view of that dimension, or are +refused by name; cube texture SRVs are not published. The first 16 refusals of a process are logged as +`compute pipeline <key> not translated natively: <reason>`. A refused key is left to the +published translations, so `-Translate` can run beside it for those pipelines. A direct module declares +wave size 32, so an adapter without 32-lane waves refuses every program by that name. The in-process +translation is tried once per key and before a published `<key>.txt`. It covers compute only; graphics +pipelines still need a published translation. + +Published compute translations from `compile_dxil --requests` and `--watch` carry a `native 1` line in the +`x2w-manifest 2` manifest. The stand-in requires the current native output revision. An unmarked manifest +is accepted with a `<key>.cs.hlsl` sidecar, which identifies a Python translation. `compile_dxil --watch` +rebuilds stale native outputs and leaves Python publications in place. The stand-in retries a stale or +absent manifest on subsequent dispatches on the ManifestRetry schedule (1 s, doubling up to 32 s), so a running process can +pick up a rebuilt output (by the code path; no test covers the reload). Compute request keys stay at `29cs`, and revision-28 archives are still read. + +Check with `ctest --preset dev -R '^startup_compute_dispatch_native_(warp|hardware)$' -V` +([`tests/startup_compute_dispatch_native_check.py`](../tests/startup_compute_dispatch_native_check.py); +[route, controls and results](experiments/startup-compute-native-dispatch.md)). + ### Compute pipeline requests Device slot 67 creates a pipeline from a console compute program. The stand-in reads 12 64-bit words of the @@ -1052,6 +1307,11 @@ the stop. The report copies only the 32-bit exception code and whether it was fi Check with `python3 -B tests/startup_triage_run_check.py` (ctest `startup_triage_run`). +`tools/startup/exit_report.py` is a narrower reader for the same directory when the question is only how the +process ended. It reports the `EXIT_PROCESS` code, one of six fixed end-state labels, the last present/frame +sample and the last presented surface. It does not copy module names, paths or addresses. Check with +`python3 -B tests/startup_exit_report_check.py`. + ## Iterating on start-up runs This is one way to turn repeated start-up runs into a list of translator work that others can pick up. It combines the tools above (`run.ps1`, `gfx2hlsl.py`, `triage_run.py`) with Windows Sandbox and a logon script that you write yourself; the script is not in this repository. Nothing from a run (executable, package, logs, shaders, captures) is committed or posted. Only instruction names, refusal reasons and counts leave the machine. @@ -1105,7 +1365,7 @@ Archive each run's logs together with a copy of `shader_cache/`, and leave the c When the translator handles more, the next `--pending` pass retries the waiting requests from the same cache. This holds only while the pipeline key is unchanged. The key hashes a translation revision string (`x2w-startup-shader-N`, in `pipeline_key` in `gfx2hlsl.py` and in the runtime). After a revision change the runtime asks for new keys, and the old requests stay in the cache. -**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies the graphics, RTV variant and slot 67 compute requests of the old cache under the keys of the current revision, computed with `pipeline_key` and `compute_key` of the `gfx2hlsl.py` next to it. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: +**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies graphics, RTV variant, slot 67 compute and slot 57 mesh requests under their current keys. It uses `pipeline_key`, `compute_key` and `mesh57_key` from the adjacent `gfx2hlsl.py` and updates each RTV variant with its new graphics key. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: ```powershell .\out\pe-env\Scripts\python.exe -B tools\startup\shader_cache_rekey.py out\startup\shader_cache out\startup\shader_cache_rekeyed @@ -1113,11 +1373,11 @@ When the translator handles more, the next `--pending` pass retries the waiting robocopy out\startup\shader_cache_rekeyed out\startup\shader_cache /XC /XN /XO ``` -1. The re-key step only reads the old cache and writes request files (`req_*`) only, never results or `.fail`. A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes: if a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. Slot 57 and slot 86 mesh requests have their own key strings and are not re-keyed. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. +1. The re-key step reads the old cache and writes only request files (`req_*`). A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes. If a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. A slot 57 request requires `.ps57`, `.root` and the `.m57` ready marker. The `.ps57` file is empty when there is no pixel stage. Slot 86 mesh requests are only counted. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. 2. `--pending` translates the re-keyed requests offline, as it does for a running title's cache. 3. The `robocopy` switches skip every file that already exists in the cache, so results the runtime or a later pass wrote are kept. A `robocopy` exit code below 8 means success: 1 is set when files were copied, and 2 is set because the cache holds files that the new directory does not. A code of 8 or more is a failure. On Linux, run the same steps with `./out/pe-env/bin/python` and merge with `cp -rn out/startup/shader_cache_rekeyed/. out/startup/shader_cache/`, which also keeps existing files. -`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer revision gives other names, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. +`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer graphics and compute revision gives other names for those requests, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. When `fxc` is available, a request that later translates loses its `.fail`. In manifest-only mode (`X2W_FXC` empty) the old `.fail` stays, so on a kept cache the `.fail` categories in `triage.md` can include pipelines that now have a `.txt`. That table counts category tokens over all `.fail` files, up to `--max-items`. @@ -1147,7 +1407,8 @@ For a timeline instead of the counters, configure a separate build tree with `-D - **Client settings.** On-demand (nothing is recorded until a profiler connects), localhost only, no broadcast, no call stacks, no system tracing and no crash handler. - **Output.** One shared `TracyClient.dll` is linked into `d3d12_xs.dll`, `XCRDAPI.dll` and `xmem.dll`; copy it beside them. - **Zones.** `ExecuteCommandLists`, `Present` (with a frame mark), the frame-wait sleep, window present, desktop pipeline creation, `device_memory_srv` with its resource scans, each DirectStorage request, and the xmem page map and physical write. `src/startup_stubs/profile_zone.h` defines the macros. -- **Off.** Without the option nothing is fetched, defined or linked, and the macros expand to nothing. +- **Memory.** Three kinds of data for Tracy's Memory view, by name: the pool `XMemAlloc` (every block `XMemAlloc` returns until its `XMemFree`), one pool per instrumented DLL for its C++ heap (`<target> C++ heap`, `operator new`/`delete` replaced in `src/startup_stubs/tracy_new.cpp`), and the plot `XMemVirtualAlloc commits (bytes, cumulative)`. That last one is a plot because the title releases those ranges with Win32 calls the stand-in does not see. Memory the title takes straight from Win32 (`VirtualAlloc`, its own heaps) and what the graphics driver commits are not tracked; compare the pools with the `commit peak=` heartbeat to size that remainder. A profiler that connects late misses earlier allocations (on-demand client). +- **Off.** Without the option nothing is fetched, defined or linked, and the macros expand to nothing or a no-op. To capture without a GUI, build Tracy's `capture` tool from the same checkout (`cmake -S <checkout>/capture -B <dir>`; that project fetches its own dependencies), start `capture -o run.tracy -a 127.0.0.1 -s <seconds>` and then the instrumented run. Open the file with the Tracy profiler, or export zone statistics with `csvexport`. @@ -1274,11 +1535,11 @@ cmake --build --preset release --target startup_inflate_probe ## DirectStorage destinations that are not writable -A request whose destination (a plain pointer, not 64 KiB page tokens) is not writable up to its declared capacity fails before any byte is written: the stand-in walks the destination with `VirtualQuery`, and a page that is uncommitted, read-only, `PAGE_GUARD` or `PAGE_NOACCESS` refuses the whole request. The log line ends `destination not writable`, `requests_failed` counts it, the next status entry reports `E_FAIL` and the queue goes on with later requests. Before this check, a destination shorter in memory than its declared capacity faulted inside the stand-in's copy (#870). The check covers the whole declared capacity, not only the bytes the request would write. Cost: one `VirtualQuery` per region the destination spans, per request that reaches the copy. +A request whose destination (a plain pointer, not 64 KiB page tokens) is not writable up to its declared capacity fails before any byte is written: the stand-in reads the attributes of the destination's pages without touching them, and a page that is uncommitted, read-only, `PAGE_GUARD` or `PAGE_NOACCESS` refuses the whole request. When every page is resident and plain read-write (`QueryWorkingSetEx`: valid, `PAGE_READWRITE` or `PAGE_EXECUTE_READWRITE`, no guard bit), the request goes ahead; otherwise the destination is walked with `VirtualQuery`, which also accepts copy-on-write pages. The log line ends `destination not writable`, `requests_failed` counts it, the next status entry reports `E_FAIL` and the queue goes on with later requests. Before this check, a destination shorter in memory than its declared capacity faulted inside the stand-in's copy (#870). The check covers the whole declared capacity, not only the bytes the request would write. Cost: one `QueryWorkingSetEx` per 512 pages of the declared capacity, per request that reaches the copy, plus the `VirtualQuery` walk when a page is not resident and plain read-write. On the title's multi-gigabyte regions each `VirtualQuery` scans to the end of the region, about 10 ms of kernel time per request (#2684). Failed requests report distinct status HRESULTs where the cause is known (#1843). A destination smaller than the data (`destination capacity exceeded`) reports `0x8007007A` (`ERROR_INSUFFICIENT_BUFFER`); a file read at or past the end, or crossing it, reports `0x80070026` (`ERROR_HANDLE_EOF`); every other cause stays `E_FAIL`. The same code is the `HRESULT` of the first-failure record. `OpenFile` with a null path returns `E_INVALIDARG`, `CreateQueue` with a null descriptor returns `E_INVALIDARG`, and a null output pointer returns `E_POINTER`; the output is set to null on every refusal. `tests/startup_dstorage_destination_check.cpp` pins each code on the real stand-in. -`tests/startup_dstorage_destination_check.cpp` (ctest `startup_dstorage_destination`) sends memory-source requests through the real queue: a read-only, a guard and a no-access middle page, and a capacity one page past the committed pages. Each must fail with the process alive and the bytes of the pages before the bad one still `0xAA`. Afterwards, requests into a fully writable (`PAGE_READWRITE`) buffer and a copy-on-write (`PAGE_WRITECOPY`) mapped view on the same queue must write every byte: +`tests/startup_dstorage_destination_check.cpp` (ctest `startup_dstorage_destination`) sends memory-source requests through the real queue: a read-only, a guard and a no-access middle page, and a capacity one page past the committed pages. Each must fail with the process alive and the bytes of the pages before the bad one still `0xAA`; the guard page must still be `PAGE_GUARD` afterwards, and a vectored exception handler must see no guard-page exception. A copy-on-write page followed by a no-access page must be refused with the first page still shared (`QueryWorkingSetEx`) and unchanged. A writable destination whose capacity is three pages but whose data is one page must succeed with the two unwritten pages still `0xAA`, and a committed page that was never touched (not resident) must be accepted. Afterwards, requests into a fully writable (`PAGE_READWRITE`) buffer and a copy-on-write (`PAGE_WRITECOPY`) mapped view on the same queue must write every byte: ```powershell ctest --preset release --no-tests=error -R '^startup_dstorage_destination$' -V @@ -1308,7 +1569,15 @@ the two recovery checks are its sole failures), `probe_readable` (invalid-pointer and zero-length refusals, multi-page reads, `PAGE_NOACCESS` / `MEM_RESERVE` prefix truncation, and `PAGE_GUARD` re-arming verified by `VirtualQuery` and a second probe), and `readable`/`writable` boundaries across `PAGE_READONLY`, `PAGE_READWRITE`, -`PAGE_WRITECOPY`, `PAGE_NOACCESS`, `PAGE_GUARD`, and `MEM_RESERVE`. No GPU is required: +`PAGE_WRITECOPY`, `PAGE_NOACCESS`, `PAGE_GUARD`, and `MEM_RESERVE`. +A first-chance exception stops the whole process while a debugger is attached, so `probe_readable` and the fault-safe +copies (`guarded_memcpy`: `copy_title_bytes`, the linear-buffer `guarded_copy`) first, when `X2W_PROBE_PRECHECK` is set to anything but `0`, or when it is unset and a debugger is attached (read once; `X2W_PROBE_PRECHECK=0` keeps it off under the debugger that title runs start in, and off, the plain touch / `__try` path runs at no extra cost), ask `VirtualQuery` (one entry per +region, cached per thread) whether the source is in free address space (`MEM_FREE`) and refuse it with no exception. +Reserved, committed, guard and no-access pages still go through the touch / `__try` path, because a reserved page may be +a lazily committed xmem page that the fault handler commits on first touch; `__try` stays the last guard. The render +totals line prints `reads refused before a fault <n>` after the textures count. The check adds an unmapped range +that must return false and 0 with no exception seen by a vectored handler, for the probe and the copy, and counts the +avoided faults. No GPU is required: ```powershell cmake --build --preset dev --target startup_local_log_check startup_local_log_cache_failure_check @@ -1331,36 +1600,84 @@ cmake --build --preset dev --target startup_trap_header_check ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_precedence_control)?$' -V ``` +## Concurrent calls through a hooked function + +The debugger's file, socket and allocation hooks are one patched byte per function. To run the original +instruction it restores the byte, single-steps the thread that hit it and patches the byte again. A second thread that +entered the function inside that window ran untraced, so `files.txt` could miss opens and the +offline mode could miss a refused socket. Now every other thread is held for the step and resumes when the stepping +thread is done (`tools/startup/hook_window.py`). A thread that had already trapped when it was held goes back to the +hook address and traps again afterwards, so its call is traced once, not twice. Each window has a 2 s deadline, so a +thread is never held forever. Per-thread state of a call in flight (the return address and stack pointer it will come back to) is +keyed by thread id, not shared. + +Every run ends with `hook windows: entries=N windows=W unprotected=U deferred=D timeouts=T protection=on|off` in the +console output, `finished.txt` and `files.txt`, also when everything is 0. `unprotected` (`U`) counts the exposed step windows in which another thread could +not be held (a thread that has already exited is not counted: it runs no code), or the deadline passed, or protection was off with other threads alive (one exposed window can miss multiple calls). `--suspend-others 0` turns the holding off, to measure what it costs or to see the loss. +The launchers pass it on: `run.ps1 -SuspendOthers 0`, `run.sh --suspend-others 0` (default 1 = hold). + +Holding has a cost in long title runs. A run opens tens of thousands of step windows with about 100 threads alive, +most of them during the load after the first-run pages. On one host (RTX 3080 Ti, i7-4790K, Windows 10), with the same +build and input script, holding cut the frame rate in that load from 18–23 to 3–5 fps and made it take 2–3 times as +long (four runs with holding, three without). Use `-SuspendOthers 0` for frame-rate and load-time runs, and keep the +default when `files.txt` or the offline socket refusals must be complete. + +`tests/startup_hook_check.py` has two parts. `startup_hook_window` checks the bookkeeping with fake threads and needs no +Windows. `startup_hook_overlap` runs the source-built `startup_launch_probe` in its `overlap` mode under the debugger: four threads +enter `CreateFileW` together 16 times each on one file, and all 64 opens must show in `files.txt` with their result and +`unprotected=0`. The control, `--suspend-others 0`, must lose opens and report `unprotected` above 0. + +```powershell +cmake --build --preset dev --target startup_launch_probe +ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V +``` + ## Switches | Variable | Effect | |---|---| | `X2W_XMEM_PERMISSIVE=1` | accepts the reservation, mapping and allocation shapes a startup run uses | | `X2W_XMEM_STARTUP_BELOW_40=1` (`run.ps1 -StartupBelow40`) | startup compatibility configuration ([#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758)): the large-page startup blocks with attribute `0x283` (null address, type `0x20003000`, protection `0x2004` or `0x2404`) are placed so that the whole block, last byte included, lies below 2^40. A block that does not fit there returns NULL with the Windows error and logs `x2w-xmem startup block below 2^40 refused:`; nothing is truncated or placed higher. Other shapes and explicit addresses keep their placement. See [Startup blocks below 2^40](experiments.md#startup-blocks-below-240) | +| `X2W_LOW_ADDRESSES=1` (`run.ps1 -LowAddresses`) | [#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758): `tools/startup/launch.py` and `debug_launch.py` start the title with bottom-up ASLR always off (`PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY`, `PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF`), so the title's own `VirtualAlloc` blocks come from the low end of the address space instead of a random start above 2^40. The package acceleration-structure builder refuses a destination address with bits set above bit 39 and receives the title's CPU address, which the shim cannot move. `startup_launch` runs a probe four times with the switch (every block ends below 2^40) and eight times without (at least one block ends above 2^40). | | `X2W_XMEM_LAZY_COMMIT=1` | experimental ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): a fresh physical-page slot is committed on its first CPU access instead of when its page is mapped. A vectored exception handler commits the slot. Writers that cannot fault one in (the main module's `ReadFile`, slot 133 placement, stand-in writes behind a commit check) call `x2w_xmem_commit_range` first. See [Mapped pages committed on first touch](experiments.md#mapped-pages-committed-on-first-touch) | -| `X2W_XMEM_LAZY_STARTUP=1` | experimental, with `X2W_XMEM_LAZY_COMMIT=1` ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): the [startup commit profile](experiments.md#reserve-and-commit-startup-blocks) only reserves blocks of 32 MiB and up, and the same handler commits them 256 KiB at a time on first touch. Slot 133 commits a whole block (`x2w_xmem_commit_block`) before a GPU resource is placed in it. The main module's `VirtualFree` import drops released blocks. Blocks placed by `X2W_XMEM_STARTUP_BELOW_40` stay committed up front. See [Startup blocks committed on first touch](experiments.md#startup-blocks-committed-on-first-touch) | +| `X2W_XMEM_LAZY_STARTUP=1` (`run.ps1 -LazyMemory`, which also sets `X2W_XMEM_LAZY_COMMIT=1` and `X2W_XMEM_SHARED_VIEWS=1`) | experimental, with `X2W_XMEM_LAZY_COMMIT=1` ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): the [startup commit profile](experiments.md#reserve-and-commit-startup-blocks) only reserves blocks of 32 MiB and up, and the same handler commits them 256 KiB at a time on first touch. Slot 133 commits a whole block (`x2w_xmem_commit_block`) before a GPU resource is placed in it. The main module's `VirtualFree` import drops released blocks. Blocks of 32 MiB and up placed below 2^40 by `X2W_XMEM_STARTUP_BELOW_40` are also reserved lazily. See [Startup blocks committed on first touch](experiments.md#startup-blocks-committed-on-first-touch) | +| `X2W_XMEM_JOIN_CALLS=1` (with `X2W_XMEM_SHARED_VIEWS=1`; `tools/startup/run.sh` sets both, `run.ps1 -LazyMemory` only `X2W_XMEM_SHARED_VIEWS`) | experimental: a mapping call whose pages continue the shared view that ends at its address joins that view instead of mapping a view of its own ([Physical pages in shared sections](#physical-pages-in-shared-sections)). Read once, with `X2W_XMEM_SHARED_VIEWS`, by the first mapping call; without shared views it does nothing | | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | +| `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | | `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}`, when needed RTV variants `req_<key>.rtv`, and for device slot 67 compute pipelines `req_<key>.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_<key>.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | -| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it, otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | -| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | +| `X2W_NATIVE_SHADERS=<dir>` (`run.ps1 -NativeShaders <dir>`) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `<dir>` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | +| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | +| `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | +| `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | +| `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) | +| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | -| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | +| `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | +| `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | +| `X2W_D3D12_TABLE_ALIAS=1` | opt-in, render mode: a translated draw's table buffer view whose whole range lies in a slot 133 placed buffer that aliases title memory binds that alias instead of a per-draw frame copy, so the GPU reads the bytes at execution and the view is not cut at 16 MiB (`startup_table_alias_*`). Unset, every table buffer view is copied as before. See [Copies of title memory within a frame](#copies-of-title-memory-within-a-frame) | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=<n>` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | | `X2W_D3D12_DUMP_SURFACE=<bmp>` | writes the last presented surface | +| `X2W_PRESENT_COMPOSITE=1` | experimental, in render mode: the output window composites every presented plane, bottom to top, instead of showing plane 0 alone, and the highest plane above plane 0 is sampled as `x2w-render raw plane <i> (not composited)`. Off by default; the baseline capture and `x2w-render presented` read plane 0 either way. See [Presented planes](#presented-planes) | +| `X2W_PRESENT_PLANE=<n>` | diagnostic, in render mode: the output window shows plane `n` of each present alone (plane 0 when `n` is past the count), with or without `X2W_PRESENT_COMPOSITE`. See [Presented planes](#presented-planes) | | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | -| `X2W_DRAW_DUMP_FRAME=<n>`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | +| `X2W_DRAW_DUMP_FRAME=<n>`, `X2W_DRAW_DUMP_DIR`, `X2W_DRAW_DUMP_PIXEL=<x>,<y>` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). With `X2W_DRAW_DUMP_PIXEL`, each copy covers one texel instead and the present writes `pixel_history.txt` in `X2W_DRAW_DUMP_DIR`: one line per translated draw with `draw=`, `frame=`, `x=`, `y=`, `key=`, `count=`, `format=`, `raw=` and, for an 8-bit four-channel target, `rgba=`. The bounded history names the last draw that changed the texel (`src/startup_stubs/pixel_history.h`, `ctest --preset dev --no-tests=error -R '^startup_pixel_history_' -V`). | +| `X2W_TEARDOWN_REPORT=1`, `X2W_TEARDOWN_NO_GUARD=<pages, readbacks or all>` | Test accounting for the caches whose destructors run during the module's CRT teardown (`src/startup_stubs/d3d12_teardown.h`, #2572). With `X2W_TEARDOWN_REPORT`, each destroyed cache writes one `x2w-teardown <cache> detached=<n> released=<n>` line to stderr with `WriteFile`, because a stdio buffer would not be flushed from a CRT teardown. `X2W_TEARDOWN_NO_GUARD` names a cache whose detach at process exit becomes an ordinary release again: the negative control `startup_teardown_unload` runs against itself, where the termination check has to fail. Unset, both change nothing and no line is written. | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | +| `X2W_AUDIO_ACTIVITY=1` | with `X2W_AUDIO_PERMISSIVE=1`, counts XMA context changes, HAL submits and XApu commands, and logs at most a line per second when a count moved ([Activity counter](#activity-counter)) | | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | -| `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is UTF-8, with a trailing separator added when missing. If the path is invalid or exceeds 259 bytes including the separator, the proxy logs the refusal and uses `S:\` (`src/startup_stubs/storage_root_utf8.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`). | +| `X2W_DEVICE_TYPE=<n>` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | +| `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is the root of the drive the title sees, not its save folder: the title appends `x2w-gamesave` itself. It is UTF-8, with a trailing separator added when missing. If the path is invalid or exceeds 259 bytes including the separator, the proxy logs the refusal and uses `S:\` (`src/startup_stubs/storage_root_utf8.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`). | | `X2W_INPUT_SCRIPT=mask@sec,...` | timed virtual gamepad presses, holds, stick or trigger values and waits for the presented picture: see [Input script](#input-script); keyboard and XInput pad 0 also work. Up to 256 entries and 4,095 characters; a longer value is ignored and logged, and dropped or malformed entries are logged (`ctest --preset dev --no-tests=error -R '^startup_gameinput_script_(long|entries|syntax)$'`) | +| `X2W_INPUT_TRACE=1` | opt-in: logs the resolved virtual gamepad state (buttons and all six axes), the script time or `off`, the present number or `none`, and one line per script wait, mark or skipped group, all prefixed `x2w-input-trace`. At most one state line per change and one per 250 ms while unchanged; unset, nothing is logged. See [Input trace](#input-trace). | | `X2W_SAMPLER_HEAP=1` | `gfx2hlsl.py` translates a sampler-heap load with a run-time offset into `SamplerState qh[2048] : register(s0, space1)` and writes `smpheap 2048 1 fallback 2047`. The stand-in uses entries 0 to 2046 for the bound heap and reserves entry 2047 for unaligned or out-of-range offsets. It also accepts the original `smpheap 2048 1` manifest with all 2,048 entries available. [#1143](https://github.com/R0Y00/Xbox2Windows/issues/1143) | | `X2W_XG_VERBOSE=1` | logs every texture layout query with its mip sizes | | `X2W_XG_BC7_4K_S_LAYOUT=1` | enables the BC7 tiled layout, copy and draw upload when `X2W_D3D12_PERMISSIVE=1` | @@ -1381,11 +1698,56 @@ handle returns `0x80004005`. The startup shader cache key includes the translator revision. After updating from an earlier translation revision, run the recording build once to emit requests, run `python tools/startup/gfx2hlsl.py --pending <cache-directory>`, -then start the build again. The new key keeps the former bytecode and manifest +then start the build again. +The first request of a process also writes the runtime's revisions to `<cache-directory>/revision.txt` +(`graphics`, `compute` and `mesh57` lines). With `-Render -Translate` (`--render --translate`), +`run.ps1` and `run.sh` compare that file with the `gfx2hlsl.py` they start +(`tools/startup/shader_cache_revision.py`) and print one warning naming both revisions when they differ, +or when the cache holds requests but no `revision.txt`: every cached request would be refused as a key +mismatch. The warning comes before the watcher starts, or after the run when the run's own stand-ins +wrote the first `revision.txt`. Rebuild the stand-ins from the same checkout, or start with an empty cache: +`-FreshShaderCache` (`--fresh-shader-cache`) moves a cache that is not empty to `<cache>.old-<date>-<time>` first +([#2815](https://github.com/R0Y00/Xbox2Windows/issues/2815)). The new key keeps the former bytecode and manifest together under their original name. A 16-dword table load can contain two independent image descriptors at offsets 0 and 32 from the load address. For a read-only census of cached shader refusals, use `python -B tools/startup/gfx2hlsl.py --refusals <cache-directory> [--json]` with a translator that supports the flag. Earlier versions treat it as `--pending` and write into the directory. See [Startup translator refusal census](experiments.md#startup-translator-refusal-census). +## Console profile + +`X2W_DEVICE_TYPE` answers the two registry reads a title makes of +`HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM\ConsoleMode` +(`src/startup_stubs/console_mode.h`, `registry_console_mode.inl`): with `X2W_RUNTIME_PROXY=1` the +stand-in rewrites the registry imports of the EXE and package helpers. `6` answers 0x60 (Series S), +`7` answers 0x64 (Series X) and `1` reports the value missing (PC); unset, every call goes to the real +registry. Only registry imports that the Windows registry provides are rewritten: an IAT entry must +name `advapi32.dll`, `kernelbase.dll`, `kernel32.dll` or an `api-ms-win-core-registry-*` API set and be +bound inside the system-directory copy of the first three, and `GetProcAddress` must be called on one +of those modules. A package DLL that exports the same names keeps its own exports and is never kept as +the real registry. Opening the key and reading the value are logged a few times either way, and a +seventeenth OEM key handle open at once is logged once and not tracked. What the values mean on the +console is taken from public notes, not measured here. +`ctest --preset dev --no-tests=error -R '^startup_console_mode(_control|_provider_control)?$'` runs it +against fake registry functions and a source-built decoy DLL with the same export names, with the switch +unset and set. The control leaves the switch unset for the answered cases and the provider control +matches registry imports by name alone; both must print `FAIL:`. `startup_runtime_proxy_scope` checks the +same decoy rule through the real loader against `advapi32.dll`. + +The switch changes only what the registry reads answer. A title can take a different start-up path +for each profile: on the Series S profile, one loaded an upscaler package module that the other +profiles do not, and that module met desktop refusals the other profiles did not reach +(`Device::slot76`, views with `ViewDimension` 0, and `R9G9B9E5_SHAREDEXP` textures with unordered +access, the last covered by the +[shared-exponent stand-in](#shared-exponent-render-and-unordered-access-targets)). Choosing a profile +is not evidence that the path it leads to runs. + +A title on the Series S profile may present its picture on a plane above plane 0 and leave plane 0 +black (see [Presented planes](#presented-planes) for a measured case). The output window shows plane 0 alone by +default, so it then stays black. `X2W_PRESENT_COMPOSITE=1` composites the planes, and +`X2W_PRESENT_PLANE=<n>` shows one plane alone. Whether other titles, or other profiles, present +this way is not known. Under either switch, `X2W_D3D12_DUMP_SURFACE` and the `x2w-render presented` +readback still read plane 0. With `X2W_PRESENT_COMPOSITE=1`, the `x2w-render raw plane <n>` line +shows whether the higher plane holds a picture. + ## D3D12 resource budget Set `X2W_D3D12_BUDGET=1` before startup to add one `x2w-budget` line to each @@ -1393,6 +1755,18 @@ D3D12 present heartbeat. `local` and `nonlocal` show DXGI current usage and budget in bytes for node 0 of the adapter matching the desktop device LUID. An unavailable segment reads `n/a`. +The line ends with the system commit and the physical-page pool (#1199): +`commit=<used>/<limit> avail=<free>` in MiB (all processes: RAM plus page files, what a new commit can still +get) and `sections=<n> slabs=<n> slots=<in use>/<free>` (live 64 KiB physical-page sections, open slabs, slots in +the open slabs), then `job_peak=<MiB> job_limit=<MiB>`: the peak commit of the job the title runs in and its memory +limit (`run.ps1 -MemoryGiB`; `none` without a limit). Each reads `n/a` when it cannot be read. A run that ends on error 1455 shows from these whether +the pool (a flat `sections`) or the resources below (committed texture bytes) grew. The first three commit failures +(error 1455 or 8) of the page pool also +log `x2w-xmem commit exhausted at <call> (error N): job memory limit N GiB reached (run.ps1 -MemoryGiB)` when the job peak is within 256 MiB of its limit (otherwise `job memory limit not reached`), then the job numbers, `system commit=... avail=...` and `pool sections=... slabs=... +slots=.../...` with the hint that `X2W_XMEM_LAZY_COMMIT=1` (`run.ps1 -LazyMemory`) keeps untouched pages out of +the commit. `tests/startup_commit_state_check.cpp` checks the text, `tests/startup_triage_run_check.py` that +`triage_run.py` still reads the line with and without these fields. + Each allocation category reads `live-bytes/live-objects+retained-bytes/retained-objects`. The categories are desktop placed resources, committed textures, committed buffers, upload buffers, readback buffers, and explicit heaps. Resource sizes @@ -1425,32 +1799,26 @@ unordered-access flag, and live in a default heap without heap flags: reusing the same title address or desktop pointer does not skip uploads or resolve a retired wrapper. -`X2W_D3D12_RELEASE_RETIRED_VIEWS=1` (only with `X2W_D3D12_RELEASE_RETIRED=1`) ends the -`view-refs` retention. Once a released class texture's release-time fences have passed, -the drain (a try-lock, never blocking) replaces every tracked slot-18 descriptor slot -that names it, in every heap and so every `CopyDescriptors*` copy, by a null SRV of the -same dimension: the shadow entry and its ref are dropped, the desktop descriptor is -rewritten with `CreateShaderResourceView(nullptr, ...)`, the view records naming the -resource lose it, and the view token in title descriptor memory is cleared when it -still carries that id. A draw that reads the slot afterwards binds a null texture -(zeros). The texture is then freed by the normal rules: lists and submissions that hold -it through `retire_hold` keep the desktop object until the recording is dropped or the -submission's fence passes. No recorded list or submission reads a title heap's SRV -descriptor (translated draws build their own descriptors from the tokens at draw time -and hold what they sample), so the rewrite cannot reach GPU work. A slot that cannot be -rewritten keeps its ref and the texture stays retained. Not covered: a title thread -that writes the same slot at the moment of the drain, and a guest that uses the -resource after its final release (unsupported with the switch, as before). -`startup_resource_retire_views_*` reads the desktop descriptors back through a compute -probe; the `keep` and `noretire` cases are the negative controls. +A slot-18 descriptor and each tracked copy hold the resource until the slot is explicitly overwritten +or its heap is destroyed. A later binding of that slot still reads the resource after the last guest +Release and the release-time fences. A list or submission holding the resource keeps it alive after +the slot is overwritten, until the recording is discarded or the submission retires. + +The legacy `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` setting only enables the retirement breakdown below and +logs that clearing live slots is disabled. The memory-pressure A/B in +[#2379](https://github.com/R0Y00/Xbox2Windows/issues/2379#issuecomment-7179801296) used the earlier +experimental rewrite. `startup_resource_retire_views_*` checks GPU readback from the original and +copied descriptors, and from a recorded copy behind a gated queue. It also checks retirement after +explicit overwrite and normal completion, with the legacy setting on and off. `X2W_D3D12_RETIRE_REASONS=1` (with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`) adds a diagnostic line to the heartbeat. It counts every resource whose final guest Release happened and whose desktop object is still alive, once, by the first cause that applies. Format: `reason=count/bytes(oldest Nf)`, bytes from the budget ticket, `oldest` in frames since the final Release: -- `view-refs`: a tracked slot 18 descriptor still names it; - `view-refs-in-visible-heap` is the part with a descriptor in a shader-visible heap. +- `view-refs`: a tracked descriptor slot still names it (a slot 18 SRV, and since + Slice 3a a slot 19 UAV, 20 RTV or 21 DSV); `view-refs-in-visible-heap` is the + slot-18 part with a descriptor in a shader-visible heap. - `list-hold`, `flight`: a closed or recording list, or a submission, holds a desktop reference. - `queued-waiting-fence`: queued, the release-time fence of a queue has not passed; @@ -1468,24 +1836,46 @@ recorded and no line is built. Every other resource (buffers, placed buffers, reserved resources, render/depth/UAV targets, and slot 127 `__XMemAllocationHooks__` textures) keeps the lifetime -described above. A resource leaves the class for good when a UAV/RTV/DSV view is -created for it (slots 19 to 21, also a refused one), when a slot 18 SRV targets -an untracked descriptor slot or is copied out of tracked heaps, when it is passed -to MakeResident or Evict (slots 34 and 35), or when it is presented. A slot 18 -SRV keeps the resource only when the desktop created the view: desktop view -creation returns `void`, so a removed device is the only failure it reports, and -a slot whose creation failed is recorded without a reference. Tracked -slot 18 SRVs (including slot 70 `device_memory_srv`) keep the resource retained +described above. A descriptor slot the shim shadows (`HeapInfo::shadow`) holds one +reference for each materialized view it names: a slot 18 SRV, and since Slice 3a +also a slot 19 UAV (one for the view resource and one for its counter resource), +a slot 20 RTV and a slot 21 DSV. `note_view` adds the references when a view is +written into a tracked slot (writing the same view again adds nothing), and the +same functions release exactly the references they added: `note_view` on an +overwrite, `note_copy` when a copy moves another view over the slot or into +another tracked slot, and the heap's `Release` through `retire_drop_heap_views` +when the slot's heap is destroyed. A view the desktop did not create (a removed +device) is recorded unmaterialized: it releases the slot's previous references +and adds none. A resource leaves the class for good when a view call targets a +descriptor slot no heap shadow tracks, or a copy moves a tracked view into an +untracked heap (`retire_leave_class`, slots 18-21, a slot 19 counter too), when +it is passed to MakeResident or Evict (slots 34 and 35), or when it is presented. +Tracked views (including slot 70 `device_memory_srv`) keep the resource retained while any descriptor slot in `HeapInfo::shadow` names it (updated across `note_view`, `CopyDescriptors*`, and heap `Release`), and translated draws hold bound textures via `retire_hold`. Only wrappers can be in the class; a raw desktop pointer never is. Sampler feedback is not checked: no device slot of the stand-in reaches it. +The 19-21 references free nothing on their own yet: the class still excludes a +texture created with the render-target, depth-stencil or unordered-access flag +(`retire_classify`), and desktop creates a UAV/RTV/DSV only on a resource that +carries the matching flag. A class texture's 19-21 view call is therefore the +console-only case the shim refuses (a UAV of a depth texture, an RTV of a texture +without render-target); it records no view, adds no reference, and the texture +still retires once it is released and its fences have passed. The accounting is +the prerequisite for a later slice that admits those textures. The slots 19-21 +fallback is unchanged: in a heap the shim does not shadow the call keeps +`retire_leave_class`, so nothing is freed under a descriptor the shim cannot +follow. `X2W_D3D12_RELEASE_RETIRED_VIEWS` no longer clears live descriptors; it is a legacy +diagnostic that logs that clearing is disabled and enables the retirement +breakdown. A tracked descriptor reference in any of slots 18-21 keeps its resource +until the slot is overwritten, copied over, or its heap is destroyed (#2679). + The final guest release signals a private desktop fence on every queue the stand-in created. The desktop object is released when all of those fences have -passed, all tracked slot 18 SRV descriptor refs have dropped to zero, and no -recorded list or submission still holds it. A copy (list slot 17), texture copy (16), +passed, all tracked descriptor references (slots 18-21) have dropped to zero, and +no recorded list or submission still holds it. A copy (list slot 17), texture copy (16), resolve destination (19), or translated draw SRV bind that the stand-in forwards makes the list hold a desktop reference to each resource of the class it names, source and destination, until the list is Reset, fails to Close or is destroyed. A list @@ -1527,13 +1917,120 @@ and a translated draw that samples such a texture through a descriptor table (th token's resolution and the draw's `retire_hold`: the readback holds the sampled texels and a clear sentinel corner, and the texture leaves the budget only after the closed draw recording is dropped); the `_off_` case checks that an ordinary committed texture (no -title memory) still records its upload. The fixture-only exports `x2w_d3d12_retire_probe`, -`x2w_d3d12_resource_index_probe`, `x2w_d3d12_texture_upload_probe` and +title memory) still records its upload. Since Slice 3a the title fixture also drives the +19-21 descriptor references: case 8 creates an RTV, a DSV and a UAV (and a buffer UAV with +a counter resource) in tracked heap slots and checks through the retire probe that each +materialized view adds one reference per slot - slot 19 one for its resource and one for +its counter - that the same view written again adds nothing, and that overwrite, a +`CopyDescriptorsSimple` copy and heap destruction each release exactly what was added +(including a view in an untracked desktop heap, which adds none); case 9 checks the +`view_slot` fallback in both switch modes: a refused RTV on a class texture in a tracked +slot stays in the class and retires, while the same call into a descriptor slot the shim +does not shadow keeps `retire_leave_class` and the texture stays retained. The fixture-only +exports `x2w_d3d12_retire_probe` (which reports the resource's tracked slot references as +`view_refs`), `x2w_d3d12_resource_index_probe`, `x2w_d3d12_texture_upload_probe` and `x2w_d3d12_written_probe` read the bookkeeping the shim keeps; the retire probe returns FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` runs the same steps without the switch. The hardware cases report 77 without a physical adapter, and the debug-layer cases report 77 where the debug layer is not installed. +## D3D12 view allocation failure + +A new view record goes into three containers: the record vector, the vector of +materialization flags and the map from content to id. If one of them cannot +allocate, the record goes into none of them, the process continues and the first +eight failures are logged: + +`x2w-d3d12 note_view: out of memory in <view_records|view_materialized|view_ids> -> view of slot <n> not recorded, destination descriptor untracked` + +The device's view slots return nothing, so the log line is the only report. The +destination descriptor is left untracked: its shadow entry and its token in +title memory are cleared, and the view it named before loses its reference. A +draw then sees a descriptor without a view, not the earlier one. If the desktop +view was created, its resources leave the retire class of +`X2W_D3D12_RELEASE_RETIRED` and are not released early. Earlier ids stay valid, +and a later view is recorded if its allocations succeed. Records already copied +elsewhere are not touched. + +This handles the failure; it does not reduce the memory the records use, and it +does not cover other allocations, such as the map of render and depth targets. + +`startup_view_alloc_<records|materialized|ids>_<warp|hardware>` fails the +allocation at one site three times through the fixture-only export +`x2w_d3d12_fail_view_allocations`. The failure is injected, not produced by +exhausting memory. For `view_ids` it is raised before the insertion, so the +fixture relies on the standard guarantee that a failed single insertion leaves +an `unordered_map` unchanged. The `control` variants never inject it and must +fail. The failure is exercised on slot 18 and on a slot 19 view with a counter +resource. For slot 19 only the reference counts are checked: resources that +allow unordered access are never in the retire class. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_view_alloc_' --output-on-failure +``` + +## D3D12 view census + +The stand-in keeps one record per distinct view: slot, resource, counter, +description bytes and whether the desktop view was created. Records are not +removed. `X2W_D3D12_VIEW_CENSUS=1` shows which slot adds them. It changes no +record, id or descriptor binding. + +The heartbeat adds a line: + +`x2w-view-census distinct by slot: cbv= srv= uav= rtv= dsv= sampler= records= capacity= ids= buckets= grows-records= grows-ids= missed=` + +- `cbv` to `sampler`: new records from device slots 17 to 22. +- `records`, `capacity`: size and capacity of the record vector. +- `ids`, `buckets`: size and bucket count of the hash map from content to id. + +Before an insertion that is expected to grow either container, the same fields +are logged as `x2w-view-census before growth of <records|ids|records and ids>`, +with the slot of the new record. The values are those before the growth. The line +is written before the allocation, so it is in the log when that allocation fails, +also when no further heartbeat follows. The growth is predicted: from the +vector's capacity, and for the map from the MSVC rehash rule (the new size over +the bucket count exceeds the maximum load factor). `missed` counts capacity or +bucket changes that no line announced. + +The census counts distinct byte contents, not distinct views. It does not say +why two records differ (for example a changing address, or description bytes +that the view type does not use), and it does not measure the size of the +containers in bytes or reduce it. + +`startup_view_census_<warp|hardware>` calls slots 17, 18 and 22 of the device. +A repeated descriptor must add no record and grow nothing. A stream of 200,000 +distinct constant buffer views, 3,000 buffer SRVs and 100 samplers must be +counted by slot, with one log line per announced growth. Both streams run under +a job commit limit 256 MiB above the commit held after setup. `off` checks that +nothing is reported without the switch; in `vary` the repeated stream changes +every call, and the fixture must fail. Slots 19 to 21 are not exercised. + +```powershell +cmake --build --preset dev --target startup_view_census +ctest --preset dev --no-tests=error -R "^startup_view_census" -V +``` + +## Wrapper allocation failure + +Every object the D3D12 stand-in returns is a wrapper allocated in `wrap()`. When that allocation (or its +registration) fails, the creating call releases the desktop object it made and returns `E_OUTOFMEMORY` with +a null output ([#2653](https://github.com/R0Y00/Xbox2Windows/issues/2653)). Before, the failure was a write +through a null pointer inside the stand-in. This was seen at the job commit limit in a startup run, at the +slot 55 derived-pipeline placeholder. Whether the title handles the error is not established. + +`startup_wrap_allocation_warp` makes the next wrapper allocation fail through the fixture-only export +`x2w_d3d12_fail_wraps`. Device creation and slots 8, 9, 14, 16, 55, 73 and 127 must return +`E_OUTOFMEMORY` with a null output, then succeed. After a failed attempt to create a second device, +`GetDevice` on a live queue must still return the original device. The +`startup_wrap_allocation_control_warp` test leaves the failure injection disabled and checks that +the fixture detects the unexpected success. + +```powershell +cmake --build --preset dev --target startup_wrap_allocation +ctest --preset dev --no-tests=error -R "^startup_wrap_allocation" -V +``` + ## Input script `X2W_INPUT_SCRIPT` (`run.ps1 -InputScript`) drives the virtual gamepad of the `GameInput.dll` @@ -1585,6 +2082,31 @@ ctest --preset dev --no-tests=error -R '^startup_gameinput_script_(long|entries| It exits 77 (skip) after the parser checks when XInput pad 0 is connected, because that pad's values merge into every reading. +### Input trace + +`X2W_INPUT_TRACE=1` (off by default) logs the gamepad state the stand-in resolves after the +keyboard, XInput pad 0, the shared pad block, `X2W_INPUT_PRESS` and `X2W_INPUT_SCRIPT` have been +merged. Every line starts with `x2w-input-trace` and goes to stderr and `X2W_TRAP_LOG` like the +stand-in's other lines. A state line has the form + +```text +x2w-input-trace state buttons=0x00000004 lt=0.000 rt=0.000 lx=1.000 ly=0.500 rx=0.000 ry=0.000 script=2.500 present=11 +``` + +where `script` is the script time in seconds or `off`, and `present` is the latest present number +from the picture signature or `none` without a presenter sample. One state line is written per +change and, while the state is unchanged, at most once every 250 ms. Waits, marks and skipped +groups add one `x2w-input-trace wait`, `mark` or `group` line each, with the script item and shifted +script time. The fixture `startup_gameinput_trace` runs one script with the switch on and off: + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gameinput_trace$' -V +``` + +The control must observe the same gamepad states and write no trace line. See +[the input trace experiment](experiments/startup-input-trace.md) for the exact line fields, the +fixture's expected states and the movement evidence it supports. + `IGameInput::GetTemporalReading` uses the v0 ABI and returns `E_NOTIMPL` as [documented by Microsoft](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/deprecated/interfaces/igameinput/methods/igameinput_gettemporalreading). The `startup_gameinput_contracts_check` fixture covers the refusal. @@ -1625,7 +2147,9 @@ reduces them to 32 x 18 cells of mean luma. Command lists do not hold the resour sampler holds its own reference to the presented surface until the copy's fence has passed; a title may release the surface right after the present. If `Signal` fails after the copy was submitted, sampling stops and the surface, command list and readback buffer stay referenced for the rest of the -process. It publishes them in a named block, +process. A removed device (the fence reporting `UINT64_MAX`) is never treated as a completion: +the readback is not mapped, no sample is published, sampling stops, and the surface stays referenced +for the rest of the process. It publishes them in a named block, `Local\x2w_present_signature_<process id>`, so other tools can read it too (`src/startup_stubs/present_signature.h` describes the layout). The 8-bit and 10:10:10:2 colour formats are read; for others it logs @@ -1731,6 +2255,11 @@ exists succeeds. Names must be one plain path component of at most 128 bytes (no case) and a blob is at most 64 MiB. The storage root itself is trusted; a container directory or blob that is a symbolic link or, on Windows, a junction is refused by every operation. +`X2W_STORAGE_PATH` is the root of the console drive, not the save folder. The title appends +`x2w-gamesave` to it, so `S:\` stores the files under `S:\x2w-gamesave` while +`S:\x2w-gamesave` stores them under `S:\x2w-gamesave\x2w-gamesave`. Point it at the drive root +(or a folder mounted as a drive) and keep one path per profile set. + Blob writes and deletes are kept with the update and reach the disk only when the update is submitted (the public API makes the whole update atomic at submit). An update closed without a submit changes nothing. At submit every write goes to a staging file and every delete is checked @@ -1857,8 +2386,19 @@ These are measured on one executable; treat them as hypotheses for others. integer VOP1/VOP2 SDWA forms: a source selection is zero-extended, or sign-extended under `sext()`, and the low bits of the result are placed in the destination field, with `UNUSED_PAD` zeroing the others and `UNUSED_PRESERVE` keeping them. The selection helpers match `tools/pixel_aot.py`, which - already lowers the same forms. Float SDWA forms and a `dst_unused:UNUSED_SEXT` destination still + already lowers the same forms. The VOP2 select `v_cndmask_b32_sdwa` lowers the same way, with VCC as + its mask (`startup_gfx2hlsl_sdwa_cndmask`, drawn on WARP and hardware). Most float SDWA forms and a + `dst_unused:UNUSED_SEXT` destination still stop translation rather than translating to something inexact. [#1141](https://github.com/R0Y00/Xbox2Windows/issues/1141) + The one float exception is the binary16 arithmetic set `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and + `v_mul_f16` (`_sdwa`). `src0_sel`/`src1_sel` accept `WORD_0`, `WORD_1` or `DWORD` (`DWORD` reads the + low half, as the 16-bit operation does); sources are single VGPRs, with `abs` and `neg`. The result + is rounded once to binary16 and written to `dst_sel:WORD_0` or `WORD_1`, with `UNUSED_PAD` zeroing the + other half (the default) and `UNUSED_PRESERVE` keeping the old one. Refused: `dst_sel:DWORD` and byte + selects, `sext()`, `clamp`, output modifiers, `UNUSED_SEXT`, and non-VGPR sources. Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_f16_alu"`: the check covers the accepted and + refused forms, and the draws on WARP and hardware read back every selector and unused mode against a + CPU binary16 reference. The VOPC SDWA compares (`v_cmp_*_sdwa`, `v_cmpx_*_sdwa`) of the existing 32-bit compare table lower too: i32 and u32 sources take their `src0_sel`/`src1_sel` field, sign-extended under `sext()`, and the compare reads the extended value as its type. f32 SDWA compares stay refused (#1920). The @@ -1868,11 +2408,15 @@ These are measured on one executable; treat them as hypotheses for others. integer form against an integer reference, and the draws on WARP and hardware check 16 x 16 pixels that a `v_cmpx_le_i32_sdwa` on a sign-extended byte keeps or discards, with translations that drop the select or `sext()` as failing controls. [#1906](https://github.com/R0Y00/Xbox2Windows/issues/1906) +- **Packed binary16 min/max.** `v_pk_min_f16` and `v_pk_max_f16` select each result half from + packed VGPR, numeric SGPR, hex literal or inline zero sources. The bitwise comparison preserves + signed zeros and returns the numeric operand when its partner is NaN. See + [the packed min/max experiment](experiments/startup-gfx2hlsl-pk-minmax.md) for the fixture and checks. - **DPP quad pair broadcasts.** The four pair permutations of a pixel stage (`quad_perm:[1,1,3,3]`, `[0,0,2,2]`, `[2,3,2,3]`, `[0,1,0,1]`, with `row_mask:0xf bank_mask:0xf`, and `bound_ctrl` since no source lane is disabled) lower on any VOP1 or VOP2 whose first source is a VGPR. The four lanes of the quad are read with the shader model 6.0 `QuadReadLaneAt` and the lane `quad_perm` names is selected by the parity of `SV_Position`; a stage that uses it compiles with DXC `ps_6_0` (`X2W_DXC`), and the result goes through a scratch register so a second source naming the same register keeps the pixel's own word. The form needs the four lanes of a quad to run together, as in a pixel - shader with helper lanes, proved by `s_wqm_b64 exec, exec` on the entry mask (a restored exact mask loses the proof): vertex stages, branches and a changed EXEC are refused, as are `row_*`, `wave_*`, partial masks and `fi`. Run + shader with helper lanes, proved by `s_wqm_b64 exec, exec` on the entry mask (a restored exact mask loses the proof): vertex stages and a changed EXEC are refused (branches and loops: see below), as are `row_*`, `wave_*`, partial masks and `fi`. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_pair"`: the controls model a quad on the CPU, and the draws on WARP and hardware compare 16 x 16 pixels of every pattern with a reference written from the lane table, with wrong-lane, own-lane, transposed-lane-index and permuted-second-source translations as failing controls. @@ -1888,9 +2432,59 @@ These are measured on one executable; treat them as hypotheses for others. check the translation and every refusal, and the draws on WARP and hardware compare all 256 pixels of two fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. [#2125](https://github.com/R0Y00/Xbox2Windows/issues/2125) +- **DPP quad reads in branches and loops.** The quad swaps, broadcasts and pair broadcasts above also lower in a pixel + program with branches or loops when a whole-program check proves that the four threads of the quad reach the read + together: the `s_wqm exec, exec` runs before every branch and target, no other EXEC write can reach the read (an + exact-mask restore after the last read is fine), and every conditional branch that can reach it is wave-uniform + (SCC proven uniform; `s_cbranch_execz`/`execnz` under the whole-quad mask). A `vccz`/`vccnz` loop, SCC taken from a + lane mask, an EXEC write inside the loop and a late `s_wqm` are refused with the offset that breaks the proof. No + wave size is assumed. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_flow"`: the draws on + WARP and hardware run swap, broadcast and pair reads inside a five-pass scalar loop with an `if`, compare 16 x 16 + pixels with a CPU reference, and require wrong-lane translations to fail. +- **wave32 `vcc_hi`.** In wave32 only `vcc_lo` is the condition mask and compilers allocate `vcc_hi` like any other + scalar register. The decoder prints wave32 syntax, so the translator renames `vcc_hi` to an SGPR the program never + names only when that is exact in both wave sizes: no instruction names the 64-bit pair `vcc`, and either a VALU + compare or carry-out writes `vcc_hi` (or an odd SGPR), a VOP3 mask source reads one (a misaligned pair in wave64), + or no VALU instruction and no `vccz`/`vccnz` branch uses `vcc_lo` as a lane mask (in wave64 those see `vcc_hi` for lanes 32..63). Otherwise `vcc_hi` stays refused; scalar writes into `vcc_hi` or + `exec_hi` are now refusals instead of a Python TypeError. Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_vcc_hi"`: the draws on WARP and hardware compare 16 x 16 + pixels of a compare, a carry and a scalar use of `vcc_hi` with a CPU reference, with translations that drop the + compare bit, the carry or read `vcc_hi` as zero as failing controls. +- **Wave reductions.** A whole wave32 reduction chain in a pixel stage (`s_or_saveexec_b32 sS, -1`, + the identity fill `v_cndmask_b32_e64 vT, <identity>, vX, sS`, four `_dpp` steps `quad_perm:[1,0,3,2]`, + `quad_perm:[2,3,0,1]`, `row_half_mirror`, `row_mirror`, `v_permlanex16_b32 vP, vT, 0, 0`, the combine, + `s_mov_b32 exec_lo, sS` and `v_readlane_b32 sD, vT, 31`) of `v_or_b32`, `v_min_u32` or `v_max_u32` is recognised + as one `WaveActiveBitOr`, `WaveActiveMin` or `WaveActiveMax` over the active lanes of the desktop wave (a correct + program cannot depend on how pixels are packed into waves). The min chain may read its lane later, as the #2125 + censuses show: after its restore, one `v_cndmask_b32_sdwa` (lowered as usual), the saveexec of a max chain, then the + readlane, carried by that max chain before its fill. The entry EXEC must still hold, without `s_wqm`, so helper + lanes are left out on both sides. The chain itself stays straight. A uniform branch may sit before it, after it, or + both; a branch that is not proven uniform, a branch target inside the chain, and wave64 stay refused. Other shapes + that start like a chain are refused with their reason + ([the note](experiments/startup-gfx2hlsl-wave-reduce.md)). Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_wave_reduce"`. + [#2125](https://github.com/R0Y00/Xbox2Windows/issues/2125) +- **First active lane.** In a straight-line pixel stage whose EXEC is still the entry mask, without `s_wqm`, + `s_ff1_i32_b32 sD, exec_lo` followed by `v_readlane_b32 sX, vY, sD` becomes `WaveReadLaneFirst(vY)` over the active + lanes of the desktop wave. This follows the packing contract of the wave reductions. `sD` has no run-time value, + and any other read of it is refused ([the note](experiments/startup-gfx2hlsl-pixel-first-lane.md)). Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_pixel_first_lane"`. + [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618) +- **Select on descriptor data.** In a compute stage, `s_cselect_b32 sD, a, b` with one source a number computed + from a descriptor (`descnum`) and the others constants, such as `sX, 0, sX`, emits no HLSL. sD keeps both arms as + a symbol with no run-time value. A numeric read, scalar ALU other than a move, or a descriptor operand holding it + (also as a word joined at a branch target) is refused, so an arm that zeroes a buffer's size is never dropped + ([the note](experiments/startup-gfx2hlsl-cselect-descnum.md)). Run + `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_cselect_descnum"`. + [#2618](https://github.com/R0Y00/Xbox2Windows/issues/2618) - **Soft asserts.** Retail code keeps `int3` instructions followed by a continuation. Without a debugger the title's handler steps over them; under the startup debugger use - `-ContinueAsserts N`. One of them fires about ten times a second in the texture-streaming path + `-AssertSites N` (`--assert-sites N` for `run.sh`), which steps over every hit at up to N distinct + main-image `int3` sites, so a site that repeats never runs the budget out however long the run is. + The first hit at one more site still stops the run, as do `X2W_STOP_AT` sites. `-ContinueAsserts N` + counts hits instead: it steps over the first N hits at any site. A hit is stepped over when either + budget allows it, and each budget counts only the hits it covers: the site budget takes the first N + distinct sites, and the hit budget counts the hits at other sites. Run `ctest --preset dev --no-tests=error -R "^startup_debug"`. One of them fires about ten times a second in the texture-streaming path (a chunked read whose length ends inside a compressed chunk); its cause is open. - **Struct-returning methods.** When both register arguments of a wrapped method look like objects, the one on the calling thread's stack is the return buffer. @@ -1992,14 +2586,47 @@ These are measured on one executable; treat them as hypotheses for others. - **Pixel-stage image stores.** In a pixel stage, `image_store` with `dim:SQ_RSRC_IMG_2D` and `dmask:0xf` becomes a typed store to a `RWTexture2D<float4>` at its own `u` register, under the lane's exec bit, and the manifest becomes version 2 with a - `uav <index> tex2d table <table> <offset>` line. The cache-policy bits are accepted. A partial - channel mask (a typed store writes all four channels), other dimensions, `d16`, `a16`, `tfe`, - `lwe`, `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads - and stores the same image are refused by name. The runtime does not bind UAVs on the translated - graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. A - hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 - texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run + `uav <index> tex2d table <table> <offset>` line. The same full mask on `dim:SQ_RSRC_IMG_2D_ARRAY` + uses three address registers, a `RWTexture2DArray<float4>` and a `tex2da` line. The cache-policy + bits are accepted. A partial pixel-stage 2D DMASK writes only the selected components + (`w0[uint2(x, y)].xz = ...`) and does not read the texel, so two invocations can update disjoint + channels of one texel. Compute stores, D16 stores and array stores still require `dmask:0xf`. An + empty or out-of-range mask, a dimension other than 2D or 2D-array, `d16`, `a16`, `tfe`, `lwe`, + `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads and + stores the same image are refused by name. A hand-assembled program stores four distinct values at + texel (1, 2). Another draws two pixels in one pass; both address that texel, one with `dmask:0x1` + and one with `dmask:0x4`, and both updates must survive. Writing the second value into y instead of + z must fail. The desktop draw reads all 16 texels of a 4x4 image back; deleting the store or + exchanging x and y must fail. Run `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. +- **Compute stores to 3D and 1D images.** A compute `image_store` with `dmask:0xf` on a 3D or 1D image + becomes a store to `RWTexture3D<float4>` or `RWTexture1D<float4>`, and Dispatch binds the title's + 3D or 1D view after checking its mip and, for 3D, its W range. See + [Startup compute stores to 3D and 1D UAVs](experiments/startup-compute-volume-line-uav.md). +- **Binding pixel-stage image stores.** A translated draw binds each `uav N tex2d|tex2da table P O` line + as a UAV range `u0..` placed after the SRVs in the translated root signature's view table. The view is made from the unordered-access + view the title created at that table entry (`resolve_pixel_uavs` in `d3d12_draw.inl`), on + mip 0 of a 2D texture, or of a 2D array when the line says `tex2da`, and the texture is in `UNORDERED_ACCESS` for the draw. Refusals are logged + with their reason and nothing is bound in place of the view. When the manifest is loaded, the + translation is not used for another image kind, a buffer line (`uav N raw table P O`, + the vertex-stage store of #2059), a view qualifier (`float`, `uint`, `sint`, as in the compute line), another source, extra fields such as + `channels`, an index out of order or more than eight views. A trailing `typedload` is the one extra + word that is read: the binding must also support a typed UAV load. The translator does not emit it + for a component store, which does not read the texel. At draw time, + the draw is not translated for no table at the parameter, an entry outside the bound table, an + entry without a view, a view that is not a UAV, a resource without `ALLOW_UNORDERED_ACCESS`, a + `tex2d` line on an array resource, a `tex2da` line whose view is not a 2D array, a 3D, 1D or + multisampled resource, a view of another dimension, mip or plane, an integer, + sRGB or non-colour format, a format without typed UAV store, a `typedload` binding whose format has + no typed UAV load, and a texture that is also an SRV, + a render target or the depth texture of the draw; these checks run before any view of the draw is + written or any texture changes state. Indirect draws refuse a translation with a `uav` line. Compute UAVs and barriers between + draws that write and read the same texture are not covered. `tests/startup_pixel_uav_check.py` + draws the program above through the runtime with four 4x4 two-mip textures in which every word is + a distinct sentinel. The texel lands only in the texture the table names, and every other word of + the four textures stays unchanged; each refusal leaves every word unchanged. The exec-off variant + leaves the texel, and must fail once recompiled without its guard. Run + `ctest --preset release --no-tests=error -R '^startup_pixel_uav_' -V`. - **Explicit mip loads.** For 2D textures, 2D arrays and 3D textures, `image_load_mip` passes the final address register to `Texture.Load` as the mip level (`int4(x, y, slice, mip)` for an array, whose four registers are x, y, slice and mip). Ordinary `image_load` still reads mip zero. @@ -2028,8 +2655,8 @@ These are measured on one executable; treat them as hypotheses for others. for a load. Before, the stage was refused and every draw through its pipeline was skipped. Two source-built pixel stages draw one texel of a 2x2 texture with two slices on WARP and hardware with DXC and FXC; a slice fixed to 0 and exchanged coordinates fail it - (`ctest --preset release --no-tests=error -R "^startup_image_2d_array_"`). Cube, multisampled - and 1D images are still refused. Not covered: binding a single-slice 2D view to an array declaration + (`ctest --preset release --no-tests=error -R "^startup_image_2d_array_"`). Multisampled + and 1D images are still refused here; cube sampling is lowered since #2943 (`startup_image_cube_`). Not covered: binding a single-slice 2D view to an array declaration in the draw path. - **2D array depth comparison.** `image_sample_c_lz` and `image_sample_c` (sampler MAX_LOD 0) with `dim:SQ_RSRC_IMG_2D_ARRAY` take the reference, u, v and the slice as four address registers and lower to @@ -2097,6 +2724,16 @@ These are measured on one executable; treat them as hypotheses for others. · [Microsoft DirectStorage overview](https://learn.microsoft.com/en-us/xbox/gdk/docs/features/console/storage/directstorage/directstorage-overview#geterroreventretrieveerrorrecord) · [DSTORAGE_ERROR_RECORD](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/structs/dstorage_error_record?view=gdk-2604) · [DSTORAGE_COMMAND_TYPE](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/enums/dstorage_command_type?view=gdk-2604) +- **DirectStorage request totals (#2816).** The heartbeat's totals line and the first `Queue::EnqueueStatus` lines print + `requests raw=<n> inflated=<n> failed=<n> bcpack-blank=<n> completed=<n>`. `raw` counts the uncompressed copies only + (it was printed as `done=`, which read as zero for a title whose requests are all compressed), `inflated` every + compressed stream that was decoded (zlib, standalone or embedded BCPack), `bcpack-blank` the BCPack requests that + completed without decoded data, and `completed` is `raw + inflated + bcpack-blank`: every request that finished and + wrote its destination (a failed request is not in it). The text `inflated=<n> failed=<n>` is unchanged; + `tools/startup/live_view.py` parses it, takes `completed` from new lines and rebuilds it from `done`, `inflated` and + `bcpack-blank` on older ones. `startup_storage_failure_counts` checks the totals of a mixed run and of a run with only zlib + requests (`raw=0`, `completed` equal to the finished requests); `startup_live_telemetry_check.py` checks both line formats. + [Microsoft DirectStorage overview](https://learn.microsoft.com/en-us/xbox/gdk/docs/features/console/storage/directstorage/directstorage-overview) - **DirectStorage failure causes (#1198).** After its totals line, the heartbeat prints `x2w-dstorage heartbeat <n> s: failed requests by cause` with one count for each of `read-at-or-past-eof`, `read-crossing-eof`, `read-other`, `destination-capacity`, @@ -2217,7 +2854,7 @@ These are measured on one executable; treat them as hypotheses for others. `src/startup_stubs/logical_view_table.h` without a device. It covers the first and last records, one past the end, handles inside a record or below the heap, missing heap fields, memory that wraps past the top of the address space, and records crossing the end of a window. -- BCPack DirectStorage requests are decoded for BC7 and BC1 streams into destination memory as single atomic texture payloads; each request decompresses a complete multi-lane rANS chunk directly into its destination buffer and is excluded from chunk continuation caching. Unhandled formats fall back to zero-filled destinations. At process exit, one `x2w-dstorage BCPack summary` line reports request and zero-filled counts for every format 1..15 that was requested. The consumer fixture sends a format 6 request and checks that it succeeds, leaves a zero-filled destination, and appears in both counts; BC1 and BC7 requests must not be counted as zero-filled. +- BCPack DirectStorage requests decode BC1–BC7 complete multi-lane rANS payloads into temporary memory and publish only after success. They are excluded from continuation caching. BC2/BC6H now reconstruct packed blocks; invalid formats and damaged streams fail without publishing blank textures. BC1 uses independent endpoint/index history and exact format dictionaries; the fitted window and quadrant masks have been removed. File and memory sources, outer zlib and physical-page destinations share this path. Historical zero-filled counters remain in the summary log schema but are no longer incremented. [Implementation, synthetic fixtures and oracle reproduction](experiments/bcpack-standalone.md). - The XG stand-in normally uses desktop copyable footprints. Its opt-in BC7 diagnostic reports standard GFX10 4 KiB tiled geometry for a single-slice, single-mip, non-MSAA `BC7_UNORM` 2D texture with an unknown layout, default alignment, and no resource flags. @@ -2264,7 +2901,7 @@ These are measured on one executable; treat them as hypotheses for others. mip 0 and mip 3 instead: `ctest --preset dev --no-tests=error -R '^startup_sampler_lod_' -V`. - The startup shader translator lowers `image_sample_l` (explicit level, 2D and 3D, any `dmask`) to `SampleLevel(sampler, uv, level)`, taking the level from the last address register. Offset, compare, - gather, clamp, cube, 1D and `unorm` forms are refused. Only the translation is checked + gather, clamp, 1D and `unorm` forms are refused; a cube lowers since #2943 ([note](experiments/startup-image-cube.md)). Only the translation is checked (`python -B tests/startup_image_sample_l_check.py`); a WARP readback of distinct mip levels is still open. - `image_sample_b` in a pixel stage lowers to `SampleBias(sampler, uv, bias)` for 2D, 2D-array and 3D textures; the bias is the first address register. Offset, clamp, compare and gather forms, other stages, code after a branch, a sampler with a @@ -2441,13 +3078,23 @@ observed callers. The experimental mode echoes any 32-bit type value at `+0x00` (including unobserved types such as `4`) rather than rejecting it, while keeping payload bytes outside `+0x00` and `+0x04` zero (`+0x34` carries decoded bytes only in the optional Opus build below). Handles are never reused, and each connection's queue buffer is released on `XApuDisconnect`. Default non-permissive mode still traps on every export -(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). +(`ctest --preset dev --no-tests=error -R '^startup_xapu_queue$' -V`). With `X2W_AUDIO_ACTIVITY=1` it also counts +commands by class (see [Activity counter](#activity-counter)). The default build does not depend on libopus. Configuring with `-DX2W_WITH_OPUS=ON` (and `Opus_DIR` pointing at an installed libopus CMake package) links libopus into `xapu.dll`. The stand-ins link the static MSVC runtime, so libopus must be built with `-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded$<$<CONFIG:Debug>:Debug>`. Tested with libopus 1.5.2; its notice is in [`src/startup_stubs/THIRD_PARTY_NOTICES.md`](../src/startup_stubs/THIRD_PARTY_NOTICES.md). With typed -completions on, a type `3` command then decodes one Opus packet. The command fields as one title fills them: +completions on, a type `3` command then decodes one Opus packet. For a connection with processing kind +`1`, activate (type `1`) supplies the stream channel count at `+0x18`. The decoder runs at 48 kHz. +Process skips the leading frames at `+0x20` and returns at most the frame count at `+0x24` and the output +capacity at `+0x34`. Connection option bit `4` selects planar stereo. The result echoes the first 24 +command bytes, reports kept frames at `+0x30` and byte count at `+0x34`, and returns the output pointer, +input byte count and input pointer at `+0x38`, `+0x44` and `+0x48`. Pitch conversion and result events +are outside the tested subset. The source-built stereo check compares both output orders to libopus and +verifies that a 960-frame packet with a 312-frame prefix produces 648 frames. + +The earlier packet-only fixture path uses the following fields: `+0x1C` sample rate (32-bit float: 8000, 12000, 16000, 24000 or 48000), `+0x24` frames, `+0x28` packet bytes, `+0x2C` packet pointer, `+0x34` output bytes (frames × channels × 4, 1 or 2 channels) and `+0x38` output pointer (interleaved 32-bit float). The result carries the decoded byte count at `+0x34`, which is smaller than the output @@ -2463,8 +3110,8 @@ are copied from scratch only after the result is queued. ```powershell cmake --preset dev -DX2W_WITH_OPUS=ON -DOpus_DIR=<libopus install>/lib/cmake/Opus -cmake --build --preset dev --target startup_stub_xapu startup_xapu_queue_check startup_xapu_opus_check -ctest --preset dev --no-tests=error -R '^startup_xapu_(queue|opus)$' -V +cmake --build --preset dev --target startup_stub_xapu startup_xapu_queue_check startup_xapu_opus_check startup_xapu_opus_count_check +ctest --preset dev --no-tests=error -R '^startup_xapu_(queue|opus|opus_count)$' -V ``` `startup_xapu_opus` encodes generated 1 kHz tones with the same libopus and checks exact byte counts (3840 for @@ -2474,6 +3121,12 @@ an untouched output and an empty queue, a full queue that leaves the slot's stre starting a fresh decoder, a rate change on a live slot, and that type `3` decodes nothing with typed completions off. It is registered only in the optional build. +`startup_xapu_opus_count` uses the same libopus tones to check the bounded telemetry: decoded +packets, dequeued completions and each refusal reason. The stand-in writes one +`x2w-audio XApu opus summary:` line at the last disconnect or at process exit, and the audio sink +reports `accepted` and `not_open` submissions. See +[the completion-count note](experiments/startup-opus-completion-count.md). + `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), converts each submitted block (format, frame count, bytes) to it, and writes it through @@ -2511,14 +3164,18 @@ longer exhausts the heap. While nothing has been freed the offsets are the ones - A block is aligned in address (a power of two, 16 at least; 0, anything below 16 and a value that is not a power of two all mean 16). Size and alignment are 32 bits. `ApuCreateHeap` creates and publishes the heap under one lock, so - competing first calls cannot reset a heap that already has live blocks. -- Null output is `E_POINTER`; size 0 is `E_INVALIDARG`; no - room, or a full extent table, is `E_OUTOFMEMORY`. A refused call leaves the heap and the optional - APU-address output as they were, and writes null to the virtual-address output when non-null. + competing first calls cannot reset a heap that already has live blocks. A heap whose 64 KiB-rounded size + exceeds 4 GiB is refused with `E_INVALIDARG` without committing memory, so every block fits the APU range. +- Null or non-writable output (`virtual_address` or optional `apu_address`) is `E_POINTER` without + allocating; size 0 is `E_INVALIDARG`; no room, an offset past 32 bits, or a full extent table is + `E_OUTOFMEMORY`. A refused call leaves the heap and the optional APU-address output as they were, + and writes null to the virtual-address output when writable. - A block that is reused is zeroed, as fresh heap memory is. - `ApuFree(NULL)` is `S_OK`. An address that does not start a live block (never allocated, inside a block, already freed) is `E_INVALIDARG` and changes nothing. -- `ApuIsVirtualAddressValid` and the two map calls still test the whole heap range, not live blocks. +- `ApuIsVirtualAddressValid` and the two map calls read the published heap bounds under the heap lock and + test the allocatable 32-bit APU range `[0x10000, min(heap_bytes, 4 GiB))` (excluding the unused guard + range below `0x10000`), not live blocks. The shape-context allocation (`AcpHalAllocateShapeContexts`, types other than 4) returns `E_NOTIMPL`, rolling back any already allocated XMA block and zeroing its output pointer and APU address. The source-built @@ -2530,6 +3187,48 @@ address validity/mapping exports, then runs 4 threads of 1000 rounds against an ctest --preset dev --no-tests=error -R '^startup_acphal_apu_free$' -V ``` +### Activity counter + +With `X2W_AUDIO_ACTIVITY=1` as well, the stand-ins count what a caller does with the audio processor without decoding +anything. `AcpHal.dll` keeps a copy of the XMA context array that `AcpHalAllocateShapeContexts` hands out and compares +the array with it inside the calls that count (HAL submits, `AcpHalAllocateShapeContexts`, every `ApuFree` once counting +started and `x2w_acphal_xma_activity`), at most once per 10 ms. Each 64-byte context is taken as a whole and no field in +it is read: one that goes from all zero to nonzero counts as filled, one that changes while nonzero as changed, one that +returns to all zero as cleared. HAL slot2 submits are counted by their type argument. `xapu.dll` counts every +`XApuEnqueueCommand` call by command class, taken as the first `UINT32` of the command, with no cap; unreadable commands +and unknown handles are counted apart; `commands=` is the classes plus the unreadable commands, and `rejected=` calls +are not in it. In an `X2W_WITH_OPUS` build with `X2W_XAPU_TYPED_COMPLETIONS=1`, a type 3 command too short to decode +returns `E_POINTER` before the queue and is still counted, as class 3. +Neither DLL starts a thread: a counted call at least a second after a DLL's previous line (or its first +counted call) logs the next line, with the counts since that line, only when a count moved, so nothing of either DLL +runs after a caller unloads it. Until then the counts wait for a later call: counts from the last second before a +caller's final call, and changes after it, are not logged, though the exports still return them. With the fixture's +caller, for example: + +``` +x2w-audio xma-activity t=1.1 s: contexts filled=5 changed=3 cleared=2 live=0/0; hal submits=4 by type 1=2 3=1 other=1 +x2w-audio xapu-activity t=1.1 s: commands=7 by class 1=3 2=2 other=1 unreadable=1; rejected=1 (not in commands) +``` + +`t` is seconds since the process started, the same base in both DLLs; the fixture's line comes after its `ApuFree`, so +no context is watched (`live=0/0`). A context written across a sample counts twice, and one filled and cleared between +two samples is not counted. `ApuFree` of the array ends the count before the block can be reused, and a second +`AcpHalAllocateShapeContexts` samples the old array once more and then watches only the new one. The totals are also +returned by the experimental exports `x2w_acphal_xma_activity` and `x2w_xapu_command_counts`. The 64-byte stride and the +command class are stand-in conventions, not a console layout, and no field inside a context, such as an enable flag, is +identified. With the variable unset nothing runs: no read of caller memory, no line. + +The source-built check runs four child processes: counter on (the exports and the logged lines give exactly what the +caller script did, and an array freed and allocated again is no longer counted), counter on with a caller that writes +only the 64 bytes after the last context and sends nothing (every count 0, no line), counter off (no count, no line), +and an unload case. That one allocates the contexts twice without `ApuFree` (the old array's unsampled change counts, +later ones do not), then frees both DLLs, checks that they are unmapped, waits 1.5 s and must exit 0. Every result, +output, last error and the final context bytes must match between the on and off runs: + +``` +ctest --preset release --no-tests=error -R '^startup_acphal_xma_activity$' -V +``` + ## Uniform first-lane reads The startup shader translator accepts `v_readfirstlane_b32` in straight-line code with the @@ -2613,11 +3312,13 @@ process's peak and current commit charge in MiB and the number of live 64 KiB ph (the heartbeat still calls them sections), so runs that stop at different points can be compared by memory spent rather than by elapsed time. A physical page holds a slot from its first use (a mapping or a DirectStorage write) until its grant is released; `xmem.dll` publishes that count through the -experimental `x2w_xmem_page_stats` export. +experimental `x2w_xmem_page_stats` export. A page-token write (`x2w_xmem_write_physical`) to a page +that has no grant is refused with `ERROR_INVALID_PARAMETER`, like a mapping of it. The slots are 64 KiB pieces of shared 256 MiB slabs (4096 slots each, `src/xmem_slab_slots.h`). A slab reserves its capacity with `SEC_RESERVE`. Each slot commits on the first mapping or write. A freed slot remains -committed, is zeroed on reuse, and is chosen before a fresh slot. The experimental `x2w_xmem_slab_stats` +committed, is zeroed on reuse, and is chosen before a fresh slot; once all slots of a slab are freed and +unpinned, the empty slab is closed and its commit is returned to the OS. The experimental `x2w_xmem_slab_stats` export reports open slabs and used and free slots. `xmem_slab_slots` checks the bookkeeping without Windows calls. `xmem_mapped_pages_commit` measures commit for a small map, and `xmem_mapped_pages_commit_failure` injects a commitment failure and checks that the reservation and slab counts are unchanged and the pages @@ -2634,8 +3335,7 @@ arrive. It reports frame counts and FPS from the graphics heartbeat without infe draws were executed. Network refusals are shown when observed; the window does not establish that all network activity is blocked. To check this presentation with generated logs, run `python -B tests/startup_live_telemetry_check.py`. See [#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199) -for memory accounting and [#1281](https://github.com/R0Y00/Xbox2Windows/issues/1281) for -the launcher's concurrent-hook limitation. +for memory accounting. ```powershell cmake --build --preset release --target xmem_shim startup_stub_xcrdapi xmem_slab_slots_check @@ -2790,21 +3490,64 @@ view (`src/xmem_mapped_pages.cpp`). Before, every page had a section and a view slow for a start-up batch of about 100,000 pages (measured under Wine: 42.9 s for 100,000 pages, 82 ms with shared sections and views). +Start-up maps nearly every page with a call of its own, and under Wine each map costs more the +more views the process has. With `X2W_XMEM_JOIN_CALLS=1` as well (off by default; `tools/startup/run.sh` +sets it, `run.ps1 -LazyMemory` does not), a mapping call whose pages all continue the view that ends at its +address, on the next slots of the same section and inside the same reservation of the shim, joins +that view: the view is unmapped, its placeholder is joined with the new pages' placeholder, and one +view is mapped over both. It is taken apart the same way as in an unmap (below), and if a step is +refused the view is mapped again as it was and the new pages get a view of their own. A joined +view stops at 64 pages (`max_merged_run_pages`): a page that would make it longer starts a view of +its own, which the next pages join. Every later unmap inside a joined view takes the whole view +apart, so the cap bounds that work too. Only joined views are capped: a view mapped by one call +covers as many of its pages as follow each other in address and in their section, and an unmap inside it maps the surviving pages again +with one view per contiguous stretch, as long as before the cap. Measured under Wine with every byte of the view written +(`xmem_cross_call_merge_check timing`): an unmap inside a view of 64 pages took 0.28 ms, of 512 +pages 2.1 ms and of 4096 pages 13 ms; joining a page to a view of 63 took 1.5 ms, about what a page +mapped on its own costs (1.4 ms). + Unmapping a page inside a shared view unmaps that view and maps its other pages again. A thread -that touches one of those pages in between takes an access violation. A vectored handler retries -it only when the address is inside a view that the unmap in progress, or the last finished one, -took apart, the page is recorded and covered by a view once that unmap is over, and the thread -has not already retried that page for that unmap. Any other fault is passed on, after at most one -retry. +that touches one of those pages in between takes an access violation. Each view mapped inside an +unmap, a join or a page batch keeps that one's id. A vectored handler retries the fault only when, +once the one in progress (if any) is over, the page is recorded, covered by a view, and that view +carries such an id, and the thread has not already retried that page for that id. A handler that +runs late, after any number of later unmaps or joins of other views (one call joins a CPU view and +then its GPU mirror), still finds the one that mapped the page again. Any other fault is passed on, +after at most one retry for each unmap or join that mapped the page's view. A fault with none in +progress or beginning or ending around a region query of the page, and no mapped view there, is +passed on without waiting for the mapping lock. Shared views are opt-in. The caller chooses before the first mapping call by setting -`X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. +`X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. It also +reads it once when `xmem.dll` loads: with it set then, the main module's `VirtualQueryEx`, +`ReadFile` and `WriteFile` imports are wrapped (see below), and the module is pinned at load when +one is. + +A region query or a kernel copy does not fault, so inside an unmap it would see the pages of the +view being taken apart as reserved. With shared views such readers run through the export +`x2w_xmem_stable_call`: the reader runs once, and runs again after the unmap if one began or ended +around it. `XMemVirtualQuery`, the main module's `VirtualQueryEx` imports and the shim's own +`VirtualQuery` and `ReadProcessMemory` readers (`src/startup_stubs/local_log.h`, slot 133, +the sampler snapshot) use it. Without shared views every page has a view of its own and readers +run once, as before. + +Inside an unmap a kernel copy into or out of a page of that view fails at once. Measured under +Wine: `ReadFile` fails with `ERROR_NOACCESS` and leaves the file position as it was, `WriteFile` +with `ERROR_INVALID_USER_BUFFER`. The main module's `ReadFile` and `WriteFile` imports therefore +run again, up to 4 times in all, when a synchronous call on a disk file fails with one of those +errors while an unmap or join was in progress or began or ended around it, and its buffer lies in +a view of a run; they wait for that one to end first. A call on a pipe, socket or console is not +run again. Under Wine an anonymous pipe read inside an unmap fails with `ERROR_NOACCESS` and leaves +its data queued (measured). Whether Windows consumes or sends any data in a call that fails this way +is unmeasured, and if it does, running the call again would lose or repeat that data. +Overlapped I/O (the copy happens at completion), a call cut short after part of the copy, and I/O +from other modules are not covered. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| -| Views | one per page | one per run of adjacent pages | +| Views | one per page | one per run of adjacent pages of one call; with `X2W_XMEM_JOIN_CALLS=1` a call can also join the view that ends at its address | | Fault handler | none | registered by the first mapping call, never removed | -| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends | +| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends (at load when the main module imports `VirtualQueryEx`, `ReadFile` or `WriteFile`, else at the first mapping call) | The handler is process-wide, and Windows has no removal that also waits for a dispatch already under way, so the opt-in keeps the module, the handler and the shim's state in place for the life @@ -2823,6 +3566,20 @@ freed slots are reused in address order so that pages reused together share a vi bytes from the queried page to the end of the view, not one page. A placed buffer on such memory is not affected: section-backed pages already took the committed, not-aliased path. +## Committed resources (device slot 76) + +Device slot 76 (Xbox order, +0x260) takes the seven arguments of desktop `CreateCommittedResource`: +heap properties, heap flags, desc, initial state, clear value, riid and ppv. Measured: a console +package module (an upscaler) creates its resources through it. The stand-in shares the +committed-resource path of slot 127 (the `CreateCommittedResource3` order, with protected session and +castable formats, which slot 76 does not pass): the same initial-state choice per heap, the same +clear-value retry and title memory, and a log line naming the slot. Run +`ctest --preset dev --no-tests=error -R '^startup_committed_slot76_(warp|control)$'` +(`tests/startup_committed_slot76_check.cpp`): a render target with a clear value and buffers on the +default, upload and readback heaps, passed with initial state 0xffffffff as a title passes them, must +be created and leave the device alive. The control asks for a 2D texture on an upload heap and must +return `E_INVALIDARG` with no resource and leave the device alive. The control also requires all four valid creations to pass. `startup_committed_slot76_hardware` runs the creation checks on a physical GPU. + - `ctest --preset release --no-tests=error -R '^xmem_shim_(mapped_pages|page_runs)$' -V` runs the earlier contract check and `tests/xmem_page_runs_check.py`: a batch across two sections with holes, moved and reused pages; `VirtualQuery` before and after a view is split; two views of @@ -2892,18 +3649,39 @@ texture with that description exists at the address, its view is created as befo 70 already read from an address keep their own paths unchanged: the single texel, the `0x105` BC3/BC7 surface (partial last tiles included) and the `0x109` BC chains. For any other description with no live texture whose `Layout` is `0x101`, `0x102`, `0x105`, `0x106`, `0x109` or `0x10a` (256 B, -4 KiB and 64 KiB blocks in the standard and display orders, no XOR), the texels are read from the +4 KiB and 64 KiB blocks in the standard and display orders, no XOR) or the linear mode `0x100` (rows +whose pitch is rounded up to 256 bytes, the mips stored from the smallest up), the texels are read from the address in that console layout (`src/startup_stubs/address_texture.h`, device-free). A translated draw that samples the view copies each mip of each array slice from that layout into desktop footprint rows (`src/startup_stubs/gfx10_layout.h`: address equations, block sizes and mip-tail rules after AMD addrlib, Mesa 25.1.0, `src/amd/addrlib`, MIT). A 256 B layout is taken with one mip only. -The description must be two-dimensional, at most 16384 texels a side, with 1 to 15 mips, one sample, +The description must be two-dimensional, or in the linear mode `0x100` one-dimensional and not an array (one row per mip, no block-compressed format), at most 16384 texels a side, with 1 to 15 mips, one sample, no target, depth or unordered-access flag, and a format with a known element size (8- to 128-bit -texels and BC1 to BC7, whose largest mip must then be whole 4x4 blocks). The view must use a supported typed format that matches the storage format or belongs to its typeless parent. The 2D or 2D-array view must fit the mip and slice ranges. A mismatched or interior view overlapping a live resource preserves the destination descriptor. -Anything else is refused as before and leaves the destination descriptor unchanged: layout `0` and -the linear mode `0x100` without a live texture, three-dimensional and cube views, multisampled -textures, the XOR swizzle modes and every other layout value. The texels must be readable and span +texels and BC1 to BC7, whose largest mip must then be whole 4x4 blocks). The view must use a supported typed format that matches the storage format or belongs to its typeless parent. The 1D, 2D or 2D-array view must match the texture's dimension and fit the mip and slice ranges. A cube view is taken on a 2D array of exactly six slices (the faces, +X to -Z) and is bound where a translation's manifest declares `texcube`; `tools/startup/gfx2hlsl.py` does not emit that kind yet, because it refuses `dim:SQ_RSRC_IMG_CUBE`. A mismatched or interior view overlapping a live resource preserves the destination descriptor. + + +A three-dimensional description is taken in one layout only: `0x105` (4 KiB standard), one sample, +at most 2048 texels on each side and a format with a known element size (8- to 128-bit texels and +BC1 to BC7, whose largest mip must then be whole 4x4 blocks across and down; the depth is any), with +one mip or a mip chain its largest side (depth included) allows, viewed as a Texture3D whose mips fit +the chain. A block-compressed volume is laid out as the volume of its 4x4 blocks, each one depth layer +deep: the sides are rounded up to whole blocks first, and every mip size after that is counted in +blocks (`ElemLib::AdjustSurfaceInfo`), so a mip whose texel side is not a multiple of 4 can be a block +wider in the layout than in the view. addrlib lays a 3D resource in a standard or display mode out in thick blocks +(`Gfx10Lib::HwlIsThick`): the 12 address bits of a block follow the one-pipe rows of +`GFX10_SW_4K_S3_PATINFO`, the block is 16x16x16, 8x16x16, 8x16x8, 8x8x8 or 4x8x8 elements for 1- to +16-byte elements, and the volume is stored a layer of blocks (one block deep) at a time. Each layer +holds that layer of every mip: first the shared tail block when the chain has one, then the mips from +the smallest to the largest, each in blocks along x, then y, with every side rounded up at each level +and padded to whole blocks. A mip is in the tail when it is at most a block wide and half a block high +and at most five mips remain; tail mip k from the end starts at byte k x 256 of the tail block, which, +read as 256-byte micro blocks, gives its origin in x and y (`ComputeSurfaceInfoMacroTiled`). Each +depth layer is copied to its own footprint rows. +Anything else is refused as before and leaves the destination descriptor unchanged: layout `0` +without a live texture, cube views of other arrays, three-dimensional descriptions in any +other layout, multisampled textures, the XOR swizzle modes and +every other layout value. The texels must be readable and span at most 64 MiB. A console-layout description is held (not published, descriptor unchanged) in the two cases a @@ -2912,7 +3690,7 @@ for the address wrote desktop-footprint rows, so the bytes are not in the layout names. As for a partial-tile view, a texture already published there samples the null view while that is so. `console_layout_beyond_xg_size`: the layout runs past the size the XG stand-in reports for the description (the desktop copyable footprints of a slice rounded up to 64 KiB, times the -slices), which the title may not own. +slices; a volume is one slice, whose footprints span every depth layer), which the title may not own. Upload lifetime: each upload of a console-layout texture is written into an upload buffer of its own (`x2w_upload::make_page`), not into the shared upload ring. The recording keeps a reference to the @@ -2942,6 +3720,11 @@ Limits and choices that are not measured against a console: elements are checked only against the addrlib pattern rows restated from the addrlib source text in `startup_gfx10_layout_check.cpp` (all five element sizes) and in the Python oracle of `startup_address_console_check.py` (4- and 8-byte elements), both written from the same source. +- The thick `0x105` volume layout is compared with addrlib itself when the build has it + (`startup_gfx10_volume_addrlib`: every element address of every mip of 501 volumes, 115 of the uncompressed ones + with a mip chain, and 196 block-compressed ones, every mip count of four chains for each of BC1 + to BC7). Only BC1 volumes are drawn. Volumes in the other modes are not handled; they stay + refused. Log lines (stderr and `X2W_TRAP_LOG`): @@ -2949,22 +3732,57 @@ Log lines (stderr and `X2W_TRAP_LOG`): for each new combination of format, layout, one or several mips, one or several slices, flags, dimension, view format, view dimension and outcome (at most 200). The outcome is `existing resource`, `published BC shape` (the earlier `0x105` and `0x109` BC paths), - `published console layout`, one of the two hold reasons or `texture_unavailable`. + `published console layout`, one of the two hold reasons, `texture_no_resource` (no live resource at that base and description), `texture_unreadable` (the texels are not readable), `texture_over_64mib` (more than the 64 MiB single-copy limit) or `texture_unavailable` (publication failed otherwise). - `x2w-draw by-address uploads: <n> submits completed and released (...)`, for the first twelve submits that drop retained uploads. Checks (reproduction in `docs/experiments.md`, "Sample by-address textures of the non-XOR console layouts"): -- `ctest --preset release --no-tests=error -R '^startup_gfx10_layout' -V` +- `ctest --preset release --no-tests=error -R '^startup_gfx10_(layout|volume)' -V` - `ctest --preset release --no-tests=error -j 1 -R '^startup_address_console_' -V` ## Linear buffer backing (device slot 133, opt-in) -By default slot 133 aliases a buffer only in private memory, through an existing heap cached by -allocation base and opened without a `D3D12_FEATURE_EXISTING_HEAPS` query. Anything else gets a +By default slot 133 aliases a buffer in private memory allocations of any size, through an existing heap cached by +allocation base and opened without a `D3D12_FEATURE_EXISTING_HEAPS` query. The opt-in +`X2W_D3D12_CAP_EXISTING_HEAP=1` limits that to allocations up to 256 MiB (`unplaced_existing_heap_allowed`): +the default keeps the formerly aliased path for larger allocations because a capped copied placement is +refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after +recording and before submit, while the cap skips multi-GiB existing heaps to avoid pinning them. With +`X2W_XMEM_LAZY_STARTUP=1`, `commit_lazy_block` runs only when the buffer is eligible to open an existing heap +(checking `MEM_PRIVATE`, 64 KiB offset alignment, nonzero width, containment inside `allocation_bytes`, and the +256 MiB cap when `X2W_D3D12_CAP_EXISTING_HEAP=1` via `can_commit_lazy_placed_buffer` before re-measuring an +uncovered prefix, and right before +`OpenExistingHeapFromAddress` opens the heap). Anything else gets a committed default buffer that does not alias the title memory, holds zeros and is reported as -success (`not aliased` in the log). `X2W_D3D12_LINEAR_BUFFERS` changes this for one buffer kind: a +success (`not aliased` in the log). `reserve_upload_ring` grows in demand +chunks from 16 MiB up to the 256 MiB total cap. A reservation owns its mapped +bytes until its chunk is recycled. The allocator tries the active chunk, the +remaining capacity and older unused tails first. Only then does it recycle a +chunk, and only one that no command-list recording holds (a closed list keeps +its hold until Reset, Release or a failed Close, because it can be submitted +again) and whose last submit on every queue has completed. A failed fence +signal or a removed device keeps the chunk busy. When no chunk qualifies, the +reservation is refused; live storage is never reset. Recycling bumps the +chunk's generation, and a cached frame copy from an older generation is not +reused. +With the opt-in `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, a closed list stops +holding its chunks as soon as its submit is fenced: the queue fence alone then +keeps the chunks from reuse until the GPU has passed it. The ring grows in +16 MiB chunks up to 512 MiB in this mode. If the same list is submitted again +before its Reset, the submit fences its chunks again when their generation is +unchanged. If a chunk was recycled in between, the list would read replaced +bytes: it is left out of `ExecuteCommandLists` before the execute, counted and +logged (`closed list ... submitted again after its released chunks ... were +reused; refused, it is not executed`) until its Reset. The mode therefore suits +titles that Reset a list before submitting it again. `startup_address_console_gate_ring_keep_*` keeps one list +closed and never Reset while a second list needs ring space, without and with +the switch. See [the experiment note](experiments/startup-upload-ring-release-at-submit.md). +`upload_reservation` exercises the shared cursor and returned-pointer contract +without D3D12; on non-Windows hosts run +`c++ -std=c++17 -Isrc tests/upload_reservation_check.cpp -o out/upload_reservation_check && out/upload_reservation_check`. +`X2W_D3D12_LINEAR_BUFFERS` changes placement for one buffer kind: a buffer description with row-major or unknown layout and initial state `COMMON` (`src/startup_stubs/linear_buffer_backing.h`, [#1914](https://github.com/R0Y00/Xbox2Windows/issues/1914)). Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, keep the default backing. @@ -3001,7 +3819,7 @@ Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, kee A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=<hr> share=<hr> -> <hr> shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal <hr>, use=... type=... existing-heaps=<hr> share=<hr>)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. A refused submission logs `x2w-d3d12 linear buffers: submission on queue <queue> refused: its refresh would have to wait for queue <queue> (<reason>), so it has no safe completion order; none of its lists ran` (the first eight). `x2w_d3d12_linear_buffer_totals` counts `kept_default`, `refresh_failures` and `unsafe_refresh_refusals`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=<n>` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=<n>` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. Point 3 instead parks the next title `Wait` (queue slot 17) after the desktop `Wait` and before it is recorded, while it holds that queue's order lock. `X2W_TEST_LINEAR_BUFFER_MUTANT=<name>` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). -Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. +Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind (not with `X2W_D3D12_ROOT_SRV_AT_DRAW=1`). Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. ## Buffer memory SRVs (device slot 70) @@ -3019,7 +3837,9 @@ descriptions with: re-checking committed status to handle title memory deallocation/reallocation. On adapters supporting `D3D12_FEATURE_EXISTING_HEAPS` for `MEM_PRIVATE` memory, it opens the existing heap and creates a zero-copy placed resource alias; otherwise (or on WARP), it falls back to a committed upload buffer and - synchronizes memory from the host. When the device wrapper is released (`refs == 0`), + synchronizes memory from the host. If the page offset cannot be expressed in whole elements for a + non-raw view, an upload copy starts at the view address. Cached backings leave this option available + even when an earlier raw call has already created a page backing. When the device wrapper is released (`refs == 0`), `clear_unplaced_buffers` safely cleans up cached entries. Once resolved, it checks alignment and bounds, adjusts `FirstElement` by `(address - base) / element_bytes`, and forwards to `CreateShaderResourceView` (slot 18). @@ -3050,7 +3870,9 @@ typed format, views that end exactly at the end of the buffer, raw alignment of element, widths, addresses and first elements above 4 GiB, page extent calculation, and cache range coverage. Its `_control` runs (`height`, `exact-fit`, `first-32`, `unplaced-extent`, `unplaced-covers`) expect wrong answers and must fail. `startup_address_buffer_srv_*` exercises placed and unplaced buffer -views with valid addresses on a device (WARP and hardware), and verifies the refusal lines. +views with valid addresses on a device (WARP and hardware), and verifies the refusal lines. Its +readback checks stride-12 views before and after a raw view on the same page, and compares stride-16 +views on fresh pages with and without a preceding unaligned raw call. `startup_memory_srv_volume` is device-free and validates volume (Texture3D) memory SRVs in device slot 70 (`supports_volume_memory_srv`, `address_view_fits`, `volume_texture_bytes`). @@ -3063,7 +3885,8 @@ footprint layout (256-byte row pitch alignment and 512-byte subresource placemen `startup_address_volume_srv_*` exercises volume SRVs on a device (WARP and hardware) with multiple depth slices and mip levels, where footprint row pitch (256 bytes) exceeds packed row bytes (16 bytes), and verifies refusal lines for mismatched view dimensions, short backings, out-of-bounds mips, explicit clamps, -and console layouts. On Windows 11 Build 26100 with an AMD Radeon RX 6600M (driver 32.0.21045.11001), +and a console-layout description over the live volume (`overlapping_resource`; before mip chains of `0x105` +volumes were read, `unsupported_description`). On Windows 11 Build 26100 with an AMD Radeon RX 6600M (driver 32.0.21045.11001), `startup_address_volume_srv_hardware` passed with all 32 RGBA pixels exact. - `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer|volume)$' -V` diff --git a/docs/wine.md b/docs/wine.md index 3864e71290..d7bf05c84f 100644 --- a/docs/wine.md +++ b/docs/wine.md @@ -57,6 +57,7 @@ set yourself stays, except `XDG_RUNTIME_DIR`, which it always unsets: |---|---| | The `run.ps1` set: `X2W_AUDIO_PERMISSIVE`, `X2W_D3D12_DEVICE_NOOP`, `X2W_D3D12_LIST_NOOP`, `X2W_D3D12_PERMISSIVE`, `X2W_XMEM_PERMISSIVE`, `X2W_RUNTIME_PROXY` (all `=1`) | The same stand-in behaviour as a Windows run. `run.sh` sets the variables behind `--render`, `--fake-user`, `--gpu-mirror` and `--host-cpu` as [Switches](startup-runtime.md#switches) lists them | | `X2W_XMEM_SHARED_VIEWS=1` | With one section and view per page, a start-up batch of about 100,000 pages took 42.9 s under Wine. With shared views it took 82 ms ([Physical pages in shared sections](startup-runtime.md#physical-pages-in-shared-sections)). Without it, the measured runs did not get past start-up | +| `X2W_XMEM_JOIN_CALLS=1` | Start-up maps nearly every page with a call of its own. With it, such a call joins the shared view that ends at its address instead of adding a view, and under Wine each map costs more the more views the process has ([Behaviour seen only under Wine](#behaviour-seen-only-under-wine)). It needs `X2W_XMEM_SHARED_VIEWS=1` | | `XDG_RUNTIME_DIR` unset | Wine then backs sections in `/tmp`, not on a small tmpfs ([Startup debugger under Wine](non-windows-hosts.md#startup-debugger-under-wine)). This also breaks audio; see the next section | | `PULSE_SERVER=unix:/run/user/$(id -u)/pulse/native` | Restores audio while `XDG_RUNTIME_DIR` stays unset. `run.sh` sets it only when that socket exists | | `WINEDLLOVERRIDES=d3d12,d3d12core,dxgi,d3d11=n`, `WINEFSYNC=1` | Wine's built-in D3D12 is not enough; the prefix holds vkd3d-proton and DXVK | diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp new file mode 100644 index 0000000000..2b63b99354 --- /dev/null +++ b/src/direct_compute_cache.cpp @@ -0,0 +1,1173 @@ +#include "direct_compute_cache.h" +#include "guest_shader_container.h" +#include "gfx1013_isa.h" +#include "native_graphics_bindings.h" +#include "shader_compute_request.h" +#include "native_compute_output.h" +#include "native_shader_revision.h" +#include "shader_dxil_compiler.h" +#include <atomic> +#include <algorithm> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <charconv> +#include <sstream> +#include <set> +#include <map> +#include <memory> +#include <mutex> +#include <d3d12.h> +#include <wrl/client.h> + +namespace x2w { +namespace { +namespace fs = std::filesystem; +using Bytes = std::string; +void word(Bytes &data, uint32_t value) { data.append(reinterpret_cast<const char *>(&value), sizeof(value)); } +bool embedded_graphics_id(std::string_view raw) { + // Alternative compiler variants can share the embedded ID encoded in two + // literal-bearing V_NOPs. A common executable prologue is not an ID. + if (raw.size() < 24) return false; + for (unsigned pc : {0u,12u}) { + if (static_cast<uint8_t>(raw[pc+2]) != 0x80 || static_cast<uint8_t>(raw[pc+3]) != 0xd5) return false; + const auto op = gfx1013::instruction(raw,pc); + if (op.form != gfx1013::Form::vop3 || op.name != "v_nop" || op.size != 12) return false; + } + return true; +} +GuestShaderStage match_graphics_stage(std::string_view raw, const Bytes &blob, bool &exact, + std::optional<GpuStage> required = {}) { + auto stages = read_guest_shader_container(blob); + int best = 0; + size_t selected = 0; + bool tie = false; + for (size_t i = 0; i < stages.size(); ++i) { + const auto &stage = stages[i]; + if (required ? stage.stage != *required : (stage.stage != GpuStage::vs && stage.stage != GpuStage::ps)) + continue; + // A pixel container can carry materialized export instructions in a + // patch table. The running PS already contains the selected export. + int rank = 0; + if (raw == stage.code) rank = stage.exports.empty() ? 3 : 2; + if (!stage.exports.empty() && raw == stage.full_precision_code()) rank = 3; + if (!rank && raw.substr(0,24) == std::string_view(stage.code).substr(0,24) && embedded_graphics_id(raw) && + (!required || (stage.container_identifier && native_shader_identifier(raw) == stage.container_identifier))) + rank = 1; + if (rank > best) { best = rank; selected = i; tie = false; } + else if (rank && rank == best) tie = true; + } + if (!best) throw UnsupportedComputeShader("raw stage and interface identity disagree"); + if (tie) throw UnsupportedComputeShader("ambiguous native stage in graphics interface"); + exact = best == 3; + return std::move(stages[selected]); +} +struct Reader { + std::string_view remaining; + std::string_view take(size_t size) { + if (size > remaining.size()) + throw std::runtime_error("short frontend cache"); + auto bytes = remaining.substr(0, size); + remaining.remove_prefix(size); + return bytes; + } + uint32_t word() { + uint32_t n; + std::memcpy(&n, take(sizeof n).data(), sizeof n); + return n; + } + uint32_t count(uint32_t max) { + auto n = word(); + if (n > max) + throw std::runtime_error("invalid frontend cache count"); + return n; + } +}; + +Bytes encode(const NativeComputeShader &program) { + Bytes out; + word(out, program.instruction_count); + for (unsigned n : program.group) + word(out, n); + word(out, static_cast<uint32_t>(program.bindings.size())); + for (const auto &b : program.bindings) { + word(out, static_cast<uint32_t>(b.kind)); + for (unsigned n : {b.root_parameter, b.byte_offset, b.shader_register, b.required_bytes, b.array_count, + b.array_position, b.image_dimension, unsigned(b.scalar_table)}) + word(out, n); + } + word(out, static_cast<uint32_t>(program.constants.size())); + for (const auto &c : program.constants) + for (unsigned n : {c.root_parameter, c.first_sgpr, c.count}) + word(out, n); + word(out, program.sampler_heap); + word(out, static_cast<unsigned>(program.stride_srvs.size())); + for (unsigned srv : program.stride_srvs) + word(out, srv); + word(out, static_cast<uint32_t>(program.samplers.size())); + for (const auto &s : program.samplers) { + for (auto n : s.words) + word(out, n); + word(out, s.explicit_lod); + word(out, s.comparison); + } + for (const auto *signature : {&program.inputs, &program.outputs}) { + word(out, static_cast<unsigned>(signature->size())); + for (const auto &row : *signature) { + word(out, static_cast<unsigned>(row.name.size())); + out += row.name; + for (auto field : + {row.index, row.row, row.first, row.width, row.component, row.used, row.kind, row.interpolation}) + word(out, field); + } + } + word(out, program.vertex_fetch); + for (auto mask : program.pixel_writes) + word(out, mask); + out += program.dxil_ir; + return out; +} +NativeComputeShader decode(std::string_view bytes) { + Reader in{bytes}; + NativeComputeShader shader{}; + shader.instruction_count = in.count(1 << 18); + shader.group = {in.count(1024), in.count(1024), in.count(64)}; + unsigned n = in.count(1000000); + shader.bindings.reserve(n); + for (unsigned j = 0; j < n; ++j) { + auto kind = static_cast<ComputeViewKind>(in.count(static_cast<unsigned>(ComputeViewKind::indexed_raw_srv))); + ComputeViewBinding b{kind, in.word(), in.word(), in.word(), in.word(), in.word(), in.word(), in.count(7)}; + b.scalar_table = static_cast<ComputeViewBinding::ScalarTable>(in.count(unsigned(ComputeViewBinding::ScalarTable::srv))); + const bool sampler_heap = kind == ComputeViewKind::heap_sampler; + if (!b.array_count || b.array_position >= b.array_count || + (sampler_heap ? b.root_parameter != compute_sampler_heap + : b.root_parameter >= 16 && b.root_parameter != compute_resource_heap)) + throw std::runtime_error("invalid cached binding"); + shader.bindings.push_back(b); + } + n = in.count(32); + for (unsigned j = 0; j < n; ++j) { + ComputeConstants c{in.count(15), in.count(105), in.count(32)}; + if (!c.count || c.count > 106 - c.first_sgpr) + throw std::runtime_error("invalid cached constants"); + shader.constants.push_back(c); + } + shader.sampler_heap = in.count(1) != 0; + n = in.count(32); + for (unsigned j = 0; j < n; ++j) + shader.stride_srvs.push_back(in.count(31)); + n = in.count(2048); + for (unsigned j = 0; j < n; ++j) { + ComputeSampler sampler{}; + for (auto &w : sampler.words) + w = in.word(); + sampler.explicit_lod = in.count(1) != 0; + sampler.comparison = in.count(1) != 0; + shader.samplers.push_back(sampler); + } + for (auto *signature : {&shader.inputs, &shader.outputs}) { + unsigned count = in.count(128); + for (unsigned j = 0; j < count; ++j) { + GraphicsLinkage row{}; + row.name = in.take(in.count(4096)); + row.index = in.word(); + row.row = in.word(); + row.first = in.count(3); + row.width = in.count(4); + row.component = in.word(); + row.used = in.count(15); + row.kind = in.count(31); + row.interpolation = in.count(7); + const bool unpacked = row.row == UINT_MAX && (signature == &shader.outputs || + (row.name == "SV_Barycentrics" && row.kind == 28 && row.component == 9 && + row.width == 3 && !row.first && row.index < 2 && row.interpolation >= 2)); + if (row.row >= 32 && !unpacked) + throw std::runtime_error("invalid cached signature register"); + if (row.name.empty() || !row.width || row.first + row.width > 4 || row.used >= (1u << row.width)) + throw std::runtime_error("invalid cached signature"); + signature->push_back(std::move(row)); + } + } + shader.vertex_fetch = in.count(1) != 0; + for (auto &mask : shader.pixel_writes) + mask = in.count(15); + if (in.remaining.empty()) + throw std::runtime_error("missing cached DXIL IR"); + shader.dxil_ir = in.remaining; + return shader; +} +bool lookup(const fs::path &path, const Bytes &key, Bytes &payload) { + HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) + return false; + LARGE_INTEGER size{}; + bool ok = false; + if (GetFileSizeEx(handle, &size) && size.QuadPart > 128 && size.QuadPart <= 256ll * 1024 * 1024) { + Bytes id(64, 0), checksum(64, 0); + payload.resize(static_cast<size_t>(size.QuadPart) - 128); + DWORD got_id = 0, got_sum = 0, got_body = 0; + ok = ReadFile(handle, id.data(), 64, &got_id, nullptr) && got_id == 64 && id == key && + ReadFile(handle, checksum.data(), 64, &got_sum, nullptr) && got_sum == 64 && + ReadFile(handle, payload.data(), static_cast<DWORD>(payload.size()), &got_body, nullptr) && + got_body == payload.size() && shader_digest(payload) == checksum; + } + CloseHandle(handle); + return ok; +} +void publish(const fs::path &path, const Bytes &key, const Bytes &payload) { + fs::create_directories(path.parent_path()); + static std::atomic<unsigned> serial{}; + auto temp = path; + temp += L"." + std::to_wstring(GetCurrentProcessId()) + L"." + std::to_wstring(serial++) + L".tmp"; + try { + std::ofstream file(temp, std::ios::binary); + file.exceptions(std::ios::badbit | std::ios::failbit); + file << key << shader_digest(payload); + file.write(payload.data(), payload.size()); + file.close(); + if (!MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) { + Bytes winner; + if (!lookup(path, key, winner) || winner != payload) + throw std::runtime_error("could not publish direct frontend cache"); + std::error_code ignored; + fs::remove(temp, ignored); + } + } catch (...) { + std::error_code ignored; + fs::remove(temp, ignored); + throw; + } +} +using InterfaceMap = std::map<Bytes, Bytes>; +const Bytes &catalog_version() { + static const Bytes version = shader_digest("x2w graphics interface catalog 1"); + return version; +} +bool digest_text(std::string_view s) { + return s.size() == 64 && s.find_first_not_of("0123456789abcdef") == s.npos; +} +std::shared_ptr<const InterfaceMap> load_interfaces(const fs::path &dir) { + auto marker = dir / "catalog"; + if (!fs::exists(marker)) return {}; + Bytes generation; + if (!lookup(marker, catalog_version(), generation) || !digest_text(generation)) + throw std::runtime_error("invalid graphics interface catalog marker"); + static std::mutex lock; + static Bytes resident_id; + static std::shared_ptr<const InterfaceMap> resident; + std::lock_guard guard(lock); + if (resident && generation == resident_id) return resident; + Bytes index; + if (!lookup(dir / (generation + ".index"), generation, index) || shader_digest(index) != generation) + throw std::runtime_error("invalid graphics interface catalog index"); + auto entries = std::make_shared<InterfaceMap>(); + Reader reader{index}; + while (!reader.remaining.empty()) { + auto key = reader.take(65), value = reader.take(64); + if (std::string_view("FIMN").find(key.front()) == std::string_view::npos || !digest_text(key.substr(1)) || + (!digest_text(value) && value != Bytes(64,'-')) || !entries->emplace(key,value).second) + throw std::runtime_error("invalid graphics interface catalog entry"); + } + resident_id = generation; + resident = entries; + return resident; +} +Bytes indexed_interface(const fs::path &dir, const InterfaceMap &entries, std::string_view raw, const Bytes &hash, bool mesh = false) { + auto it = entries.find((mesh ? "M" : "F") + hash); + if (it == entries.end() && embedded_graphics_id(raw)) + it = entries.find((mesh ? "N" : "I") + shader_digest(raw.substr(0,24))); + if (it == entries.end()) return {}; + if (it->second.front() == '-') throw UnsupportedComputeShader("ambiguous reviewed graphics interfaces"); + Bytes container; + if (!lookup(dir / (it->second + ".stage"), it->second, container) || shader_digest(container) != it->second) + throw std::runtime_error("invalid indexed graphics interface container"); + return container; +} +} // namespace + +GuestShaderStage reviewed_graphics_stage(std::string_view raw, GpuStage kind, const fs::path &cache, bool &exact) { + const auto dir = cache / "interfaces" / "library"; + const auto entries = load_interfaces(dir); + if (!entries) throw UnsupportedComputeShader("missing reviewed graphics interfaces"); + const auto blob = indexed_interface(dir, *entries, raw, shader_digest(raw), kind == GpuStage::ms); + if (blob.empty()) throw UnsupportedComputeShader("stage absent from reviewed graphics interfaces"); + return match_graphics_stage(raw, blob, exact, kind); +} + +size_t index_graphics_interfaces(const fs::path &source, const fs::path &cache) { + const auto dir = cache / "interfaces" / "library"; + InterfaceMap index; + size_t count = 0; + for (const auto &entry : fs::recursive_directory_iterator(source)) { + if (!entry.is_regular_file() || entry.path().extension() != L".cdxil") continue; + auto blob = read_shader_container_bytes(entry.path()); + auto stages = read_guest_shader_container(blob); + const auto id = shader_digest(blob); + auto add = [&](const Bytes &key) { + auto [it, fresh] = index.emplace(key,id); + if (!fresh && it->second != id) it->second.assign(64,'-'); + }; + bool graphics = false; + for (const auto &stage : stages) { + const bool mesh = stage.stage == GpuStage::ms; + if (!mesh && stage.stage != GpuStage::vs && stage.stage != GpuStage::ps) continue; + graphics = true; + add((mesh ? "M" : "F") + shader_digest(stage.code)); + if (!stage.exports.empty()) add("F" + shader_digest(stage.full_precision_code())); + if (embedded_graphics_id(stage.code)) + add((mesh ? "N" : "I") + shader_digest(std::string_view(stage.code).substr(0,24))); + } + if (!graphics) continue; + publish(dir / (id + ".stage"), id, blob); + ++count; + } + if (!count) throw std::runtime_error("no graphics .cdxil containers in interface directory"); + Bytes encoded; + for (const auto &[key,id] : index) { encoded += key; encoded += id; } + const auto generation = shader_digest(encoded); + publish(dir / (generation + ".index"), generation, encoded); + publish(dir / "catalog", catalog_version(), generation); + return count; +} +namespace { +Bytes slot67_digest(const ComputeRequest &request, unsigned entry) { + Bytes identity = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6"; + word(identity, entry); + for (const auto *part : {&request.code, &request.data, &request.root, &request.description, &request.sa, &request.sb}) + identity += shader_digest(*part); + return shader_digest(identity); +} +template<class Translate> +NativeComputeShader cached_compute_ir(const fs::path &cache, const Bytes &key, bool &hit, Translate translate) { + const auto path = cache / (key + ".csir"); + Bytes payload; + hit = lookup(path, key, payload); + if (hit) { + try { return decode(payload); } + catch (const std::runtime_error &) { hit = false; } + } + auto program = translate(); + publish(path, key, encode(program)); + return program; +} +Bytes pack_version(unsigned entry) { + Bytes version = X2W_NATIVE_SHADER_REVISION "/slot67/cs_6_6/prepared-1"; + word(version, entry); + return shader_digest(version); +} +} +NativeComputeShader prepare_direct_compute(const fs::path &input, unsigned entry, bool container, + const fs::path &cache, bool &cache_hit, HeapViewContract heap_view) { + if (!container) { + if (heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs a container request"); + const auto request = read_compute_request(input); + return cached_compute_ir(cache, slot67_digest(request, entry), cache_hit, + [&] { return translate_compute(request, entry, true); }); + } + auto packed = read_compute_container(input); + Bytes identity = X2W_NATIVE_SHADER_REVISION "/container/cs_6_6"; + word(identity, 0); + if (heap_view != HeapViewContract::none) + identity += heap_view == HeapViewContract::raw_buffer ? "/heap-view/raw_buffer" : "/heap-view/other"; + identity += shader_digest(packed.bytes) + shader_digest(packed.root); + return cached_compute_ir(cache, shader_digest(identity), cache_hit, + [&] { return translate_compute_container(std::move(packed), heap_view); }); +} + +ComputePackCounts build_compute_frontend_pack(const fs::path &requests, const fs::path &cache, unsigned entry) { + std::vector<fs::path> markers; + for (const auto &file : fs::directory_iterator(requests)) + if (file.is_regular_file() && file.path().extension() == ".c67" && file.path().stem().wstring().rfind(L"req_",0) == 0) + markers.push_back(file.path()); + if (markers.empty() || markers.size() > 100000) + throw std::runtime_error("invalid compute pack request count"); + std::sort(markers.begin(), markers.end()); + Bytes pack; + word(pack, 0); + ComputePackCounts counts; + for (const auto &marker : markers) { + try { + const auto request = read_compute_request(marker); + const auto digest = slot67_digest(request, entry); + Bytes payload; + bool unsupported = false, hit = false; + try { + auto program = cached_compute_ir(cache, digest, hit, [&] { return translate_compute(request, entry, true); }); + payload = encode(program); + + } catch (const UnsupportedComputeShader &error) { + payload = error.what(); + unsupported = true; + + } + constexpr size_t limit = (256u << 20) - 128; + if (payload.empty() || payload.size() > limit || pack.size() + 80 + payload.size() > limit) + throw std::runtime_error("invalid compute pack size"); + word(pack, static_cast<uint32_t>(request.key)); + word(pack, static_cast<uint32_t>(request.key >> 32)); + pack += digest; + word(pack, unsupported); + word(pack, static_cast<uint32_t>(payload.size())); + pack += payload; + if (unsupported) ++counts.unsupported; + else ++counts.prepared; + } catch (const std::runtime_error &e) { + counts.errors.push_back(marker.filename().string() + ": " + e.what()); + } + } + const uint32_t total = static_cast<uint32_t>(counts.prepared + counts.unsupported); + if (!total) throw std::runtime_error(counts.errors.at(0)); + std::memcpy(pack.data(), &total, sizeof(total)); + publish(cache / ("compute-" + std::to_string(entry) + ".pack"), pack_version(entry), pack); + return counts; +} + +ComputeFrontendPack ComputeFrontendPack::load(const fs::path &file, unsigned entry) { + Bytes bytes; + if (!x2w::lookup(file, pack_version(entry), bytes)) + throw std::runtime_error("missing, stale or damaged compute pack"); + Reader in{bytes}; + ComputeFrontendPack pack; + pack.entry_ = entry; + auto count = in.count(100000); + if (!count) throw std::runtime_error("empty compute pack"); + pack.records_.reserve(count); + for (unsigned j = 0; j < count; ++j) { + uint64_t key = in.word(); + key |= uint64_t(in.word()) << 32; + auto digest = in.take(64); + bool unsupported = in.count(1) != 0; + auto payload = in.take(in.word()); + if (!digest_text(digest) || payload.empty() || (unsupported && payload.size() > 4096) || + !pack.records_.emplace(key, Record{Bytes(digest), Bytes(payload), unsupported}).second) + throw std::runtime_error("invalid compute pack record"); + } + if (!in.remaining.empty()) throw std::runtime_error("trailing compute pack data"); + return pack; +} + +ComputePackResult ComputeFrontendPack::lookup(const ComputeRequest &request, unsigned entry, + NativeComputeShader &program, Bytes &diagnostic) const { + auto it = records_.find(request.key); + if (it == records_.end() || entry != entry_ || it->second.digest != slot67_digest(request, entry)) + return ComputePackResult::miss; + if (it->second.unsupported) { + diagnostic = it->second.payload; + return ComputePackResult::unsupported; + } + try { program = decode(it->second.payload); } + catch (const std::runtime_error &) { return ComputePackResult::miss; } + return ComputePackResult::prepared; +} + +unsigned dxil_io_component(unsigned format) { + switch (format) { + case DXGI_FORMAT_R32_FLOAT: + case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R32G32B32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R16_FLOAT: + case DXGI_FORMAT_R16G16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16_SNORM: + case DXGI_FORMAT_R16G16_SNORM: + case DXGI_FORMAT_R16G16B16A16_SNORM: + case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8G8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8_SNORM: + case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R8G8B8A8_SNORM: + case DXGI_FORMAT_R10G10B10A2_UNORM: + return 9; + case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32A32_UINT: + case DXGI_FORMAT_R10G10B10A2_UINT: + return 5; + case DXGI_FORMAT_R8_SINT: + case DXGI_FORMAT_R8G8_SINT: + case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_R16_SINT: + case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32_SINT: + case DXGI_FORMAT_R32G32_SINT: + case DXGI_FORMAT_R32G32B32_SINT: + case DXGI_FORMAT_R32G32B32A32_SINT: + return 4; + } + return 0; +} + +// The capture writer serializes the guest's D3D12_INPUT_ELEMENT_DESC array as ia1. +// Keep APPEND_ALIGNED_ELEMENT intact so D3D12 uses the preceding element of its slot. +static std::vector<NativeVertexElement> vertex_layout(std::string_view text, const NativeComputeShader &vs) { + std::vector<NativeVertexElement> elements; + std::set<std::pair<std::string, unsigned>> names; + auto upper = [](std::string name) { + for (char &c : name) + if (c >= 'a' && c <= 'z') + c -= 'a' - 'A'; + return name; + }; + if (!text.empty()) { + std::istringstream in{std::string(text)}; + std::string token; + auto number = [&]() { + unsigned value = 0; + if (!(in >> token)) + throw UnsupportedComputeShader("truncated input layout"); + const auto end = token.data() + token.size(); + auto parsed = std::from_chars(token.data(), end, value); + if (parsed.ec != std::errc{} || parsed.ptr != end) + throw UnsupportedComputeShader("invalid input layout number"); + return value; + }; + if (!(in >> token) || token != "ia1") + throw UnsupportedComputeShader("invalid input layout version"); + const unsigned count = number(); + if (!count || count > 32) + throw UnsupportedComputeShader("invalid input element count"); + for (unsigned i = 0; i < count; ++i) { + NativeVertexElement e{}; + if (!(in >> e.semantic) || e.semantic.empty() || e.semantic.size() > 63 || + e.semantic.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") != + std::string::npos || + (e.semantic.front() >= '0' && e.semantic.front() <= '9')) + throw UnsupportedComputeShader("invalid input semantic"); + e.semantic = upper(e.semantic); + e.index = number(); + e.format = number(); + e.slot = number(); + e.offset = number(); + e.classification = number(); + e.step_rate = number(); + if (!dxil_io_component(e.format)) + throw UnsupportedComputeShader("unsupported vertex input format"); + if (e.slot >= 8 || e.classification > 1 || (!e.classification && e.step_rate) || + (e.offset != UINT_MAX && e.offset >= D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES)) + throw UnsupportedComputeShader("unsupported vertex input slot, offset or classification"); + if (!names.emplace(e.semantic, e.index).second) + throw UnsupportedComputeShader("duplicate input semantic"); + for (const auto &prior : elements) + if (e.slot == prior.slot && + (e.classification != prior.classification || e.step_rate != prior.step_rate)) + throw UnsupportedComputeShader("inconsistent input slot classification"); + elements.push_back(std::move(e)); + } + if (in >> token) + throw UnsupportedComputeShader("trailing input layout elements"); + } + for (const auto &row : vs.inputs) { + const auto name = upper(row.name); + if (name.rfind("SV_", 0) == 0) + continue; + auto it = std::find_if(elements.begin(), elements.end(), + [&](const auto &e) { return e.semantic == name && e.index == row.index; }); + if (it == elements.end()) + throw UnsupportedComputeShader("missing vertex input element " + name); + if (dxil_io_component(it->format) != row.component) + throw UnsupportedComputeShader("vertex format disagrees with shader input " + name); + it->used = true; + } + return elements; +} + +DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view b, const fs::path &cache, + bool &cache_hit, std::string_view root, std::string_view input_layout, + std::string_view pixel_entry, bool write_cache, + const std::vector<unsigned> &rtv_formats) { + // An RTV variant types each color target by its format, as tools/startup/gfx2hlsl.py mrt_kind does: u32 or i32 + // for the integer formats, f32 for every other format. + std::array<unsigned char, 8> targets{}; + if (rtv_formats.size() > targets.size()) throw UnsupportedComputeShader("invalid RTV variant values"); + for (size_t i = 0; i < rtv_formats.size(); ++i) { + const unsigned component = dxil_io_component(rtv_formats[i]); + targets[i] = static_cast<unsigned char>(component == 5 || component == 4 ? component : 9); + } + // The two three-channel 32-bit integer formats have no verified readback there. As there, one is refused by + // name only when the pixel stage exports to its target; the stage's cached form does not depend on which + // format of a type was asked for, so this is checked on a cache hit too. + const auto verified = [&](DirectGraphicsPair pair) { + for (size_t i = 0; i < rtv_formats.size(); ++i) + if (pair.pixel.pixel_writes[i] && + (rtv_formats[i] == DXGI_FORMAT_R32G32B32_UINT || rtv_formats[i] == DXGI_FORMAT_R32G32B32_SINT)) + throw UnsupportedComputeShader(std::string("unverified ") + (targets[i] == 5 ? "UINT" : "SINT") + + " RTV format " + std::to_string(rtv_formats[i])); + return pair; + }; + // A fixed PSO can expose a shorter serialized desktop root than the + // guest's hardware descriptor table. An explicitly supplied companion + // describes the guest ABI. Never use its executable code in the pair. + std::array<Bytes, 2> companions; + const std::array<std::string_view, 2> raw{a, b}; + const std::array<Bytes, 2> digests{shader_digest(a), shader_digest(b)}; + Bytes identity = Bytes(X2W_NATIVE_SHADER_REVISION) + "/linked/vs_ps_6_6/"; + if (!cache.empty() && a.substr(0,4) != "DXBC" && b.substr(0,4) != "DXBC") { + for (size_t i = 0; i < raw.size(); ++i) { + auto file = cache / "interfaces" / (digests[i] + ".cdxil"); + if (std::filesystem::exists(file)) companions[i] = read_shader_container_bytes(file); + } + if (companions[0].empty() || companions[1].empty()) { + const bool pinned = !companions[0].empty() || !companions[1].empty(); + const auto library = cache / "interfaces" / "library"; + if (auto index = load_interfaces(library)) { + for (size_t i = 0; i < raw.size(); ++i) + if (companions[i].empty()) companions[i] = indexed_interface(library,*index,raw[i],digests[i]); + // An incomplete library must still allow a self-describing raw pair. + if (!pinned && (companions[0].empty() || companions[1].empty())) companions = {}; + } + } + } + for (size_t i = 0; i < raw.size(); ++i) { + identity += digests[i]; + identity += shader_digest(companions[i]); + } + const bool reflected = !companions[0].empty(); + if (reflected != !companions[1].empty()) throw UnsupportedComputeShader("incomplete raw graphics interface pair"); + if (reflected && root.empty()) throw UnsupportedComputeShader("missing captured root for reflected graphics"); + // The base pair keeps its key. A variant adds its target types, so formats of one type share an entry. + const Bytes typed = rtv_formats.empty() ? Bytes{} + : shader_digest(std::string_view(reinterpret_cast<const char *>(targets.data()), targets.size())); + const auto key = shader_digest(identity + shader_digest(root) + shader_digest(input_layout) + shader_digest(pixel_entry) + typed); + const auto path = cache / (key + ".pairir"); + Bytes payload; + cache_hit = write_cache && !cache.empty() && lookup(path, key, payload); + auto effective_layout = [&](const NativeComputeShader &vs) { + if (!input_layout.empty() || !vs.vertex_fetch) return std::string(input_layout); + unsigned count = 0; + std::ostringstream elements; + for (const auto &r : vs.inputs) { + if (r.name != "X2W_RAW_VERTEX") continue; + unsigned format = 0; + if (r.component == 5 && r.width == 1) format = DXGI_FORMAT_R8_UINT; + if (r.component == 5 && r.width == 2) format = DXGI_FORMAT_R32G32_UINT; + if (r.component == 5 && r.width == 3) format = DXGI_FORMAT_R32G32B32_UINT; + if (r.component == 5 && r.width == 4) format = DXGI_FORMAT_R32G32B32A32_UINT; + if (r.component == 9 && r.width == 1) format = DXGI_FORMAT_R8_UNORM; + if (r.component == 9 && r.width == 2) format = DXGI_FORMAT_R8G8_UNORM; + if (r.component == 9 && r.width == 4) format = DXGI_FORMAT_R8G8B8A8_UNORM; + if (!format) throw UnsupportedComputeShader("unsupported fixed vertex format"); + elements << " X2W_RAW_VERTEX " << r.index << ' ' << format << " 0 " << r.index << " 0 0"; + ++count; + } + return count ? "ia1 " + std::to_string(count) + elements.str() : std::string{}; + }; + if (cache_hit) { + try { + Reader in{payload}; + auto vertex = decode(in.take(in.word())); + auto elements = vertex_layout(effective_layout(vertex), vertex); + return verified({std::move(vertex), decode(in.remaining), std::move(elements), targets}); + } catch (const UnsupportedComputeShader &) { + throw; + } catch (const std::runtime_error &) { + cache_hit = false; + } + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty{}; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *desc = ∅ + Microsoft::WRL::ComPtr<ID3D12VersionedRootSignatureDeserializer> sig; + if (!root.empty()) { + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(root.data(), root.size(), IID_PPV_ARGS(&sig))) || + FAILED(sig->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc))) + throw UnsupportedComputeShader("invalid captured graphics root signature"); + } + const auto &layout = desc->Desc_1_1; + std::map<GpuStage, GuestShaderStage> interfaces; + std::optional<GpuStage> first_stage; + bool exact_pair = reflected; + bool exact_pixel_code = false; + Bytes entry; + const bool fixed_entry = pixel_entry.size() == 12 && pixel_entry.substr(0,4) == "PSI1"; + if (fixed_entry && !reflected) + throw UnsupportedComputeShader("fixed graphics entry requires matching stage interfaces"); + bool packed_xy = false; + std::optional<unsigned> captured_interp_count; + std::optional<std::array<bool,2>> stage_wave32; + if (reflected) { + for (size_t i = 0; i < companions.size(); ++i) { + bool exact = false; + auto matched = match_graphics_stage(raw[i],companions[i],exact); + exact_pair &= exact; + auto stage = matched.stage; + if (stage == GpuStage::ps) exact_pixel_code = exact; + if (i == 0) first_stage = stage; + if (!interfaces.emplace(stage, std::move(matched)).second) + throw UnsupportedComputeShader("duplicate reflected graphics stage"); + } + if (!interfaces.count(GpuStage::vs) || !interfaces.count(GpuStage::ps)) + throw UnsupportedComputeShader("missing vertex or pixel interface"); + const auto &pixel_defaults = interfaces.at(GpuStage::ps); + stage_wave32 = {{interfaces.at(GpuStage::vs).wave32, pixel_defaults.wave32}}; + if (fixed_entry) { + // Fixed slot 57 supplies ADDR and NUM_INTERP, not ENA. Intersect + // the observed ABI with the reviewed stage and the raw consumers. + uint32_t address, interpolants; + std::memcpy(&address, pixel_entry.data() + 4, 4); + std::memcpy(&interpolants, pixel_entry.data() + 8, 4); + if (!interpolants || interpolants > 7 || interpolants > pixel_defaults.attributes.size()) + throw UnsupportedComputeShader("captured interpolation count disagrees with pixel interface"); + captured_interp_count = interpolants; + packed_xy = address == 0x8002 && pixel_defaults.pixel_input_address == 0x302; + if (!(address == 2 && pixel_defaults.pixel_input_address == 2) && !packed_xy) + throw UnsupportedComputeShader("unsupported fixed pixel entry layout"); + // Center I/J and, in the specialized position variant, packed XY + // are the only allocated inputs. The raw frontend checks each + // register use; the interpolants are checked below after linking. + entry = "psin1"; + word(entry, address); + word(entry, address); + pixel_entry = entry; + } + if (exact_pair && !pixel_entry.empty()) { + auto &ps = interfaces.at(GpuStage::ps); + uint32_t enable_mask = 0, address_mask = 0; + if (pixel_entry.size() != 13 || pixel_entry.substr(0, 5) != "psin1") + throw UnsupportedComputeShader("invalid raw pixel entry record"); + std::memcpy(&enable_mask, pixel_entry.data() + 5, 4); + std::memcpy(&address_mask, pixel_entry.data() + 9, 4); + if (enable_mask > 0xffff || address_mask > 0xffff || (enable_mask & ~address_mask)) + throw UnsupportedComputeShader("contradictory pixel input enable/address masks"); + exact_pair = ps.pixel_input_address == address_mask; + if (exact_pair) + ps.pixel_input_enable = enable_mask; + } + if (pixel_entry.empty() && !exact_pair) { + const auto &ps = interfaces.at(GpuStage::ps); + if (ps.pixel_input_address != 2 || ps.attributes.empty() || ps.attributes.size() > 7) + throw UnsupportedComputeShader("raw graphics requires its captured pixel entry"); + entry = "psin1"; + word(entry, ps.pixel_input_address); + word(entry, ps.pixel_input_address); + pixel_entry = entry; + } + } + DirectGraphicsPair pair; + if (exact_pair) { + for (size_t i = 0; i < raw.size(); ++i) { + auto type = i == 0 ? *first_stage : *first_stage == GpuStage::vs ? GpuStage::ps : GpuStage::vs; + auto &stage = interfaces.at(type); + stage.code.assign(raw[i]); + stage.exports.clear(); + } + interfaces.at(GpuStage::ps).target_components = targets; + pair = translate_reflected_graphics(interfaces.at(GpuStage::vs),interfaces.at(GpuStage::ps),layout); + } else pair = translate_graphics_pair(a, b, layout, pixel_entry, first_stage, targets, stage_wave32); + pair.target_components = targets; + if (!entry.empty()) { + const auto &attrs = interfaces.at(GpuStage::ps).attributes; + std::vector<unsigned> channels(attrs.size()); + for (const auto &r : pair.pixel.inputs) { + if (r.kind == 28 && r.interpolation == 2) continue; + if (packed_xy && r.kind == 3 && r.name == "SV_Position" && r.first == 0 && + r.index == 0 && r.width == 4 && r.interpolation == 4) continue; + // Fixed pipelines may specialize individual components from + // P1/P2 to VINTRP_MOV P0. The raw front end links each observed + // component to a VS PARAM channel and emits flat mode only for + // that P0 instruction. It may drop unused reflected rows, too. + if (r.name != "TEXCOORD" || r.index / 4 >= channels.size() || + (captured_interp_count && r.index / 4 >= *captured_interp_count) || + (r.interpolation != 2 && !(fixed_entry && r.interpolation == 1)) || + r.width != 1 || r.first != r.index % 4) + throw UnsupportedComputeShader("raw and reflected interpolation inputs disagree"); + channels[r.index / 4] |= 1u << r.first; + } + for (const auto &attr : attrs) { + // A specialized raw PS can read more components of the same PARAM + // than its library variant. The raw VS/PS link above has already + // checked every consumed component against a matching VS export. + const bool linked_raw_row = fixed_entry && !exact_pixel_code && attr.row == attr.location; + if (attr.usage != 6 || attr.location >= channels.size() || attr.flags != 2 || + (!linked_raw_row && (channels[attr.location] & ~attr.mask)) || !attr.mask) + throw UnsupportedComputeShader("raw and reflected interpolation channels disagree at location " + + std::to_string(attr.location) + " (usage " + std::to_string(attr.usage) + ", flags " + + std::to_string(attr.flags) + ", reflected mask " + std::to_string(attr.mask) + + ", raw mask " + std::to_string(attr.location < channels.size() ? channels[attr.location] : 0) + ")"); + channels[attr.location] = 0; + } + if (std::any_of(channels.begin(), channels.end(), [](unsigned bits) { return bits != 0; })) + throw UnsupportedComputeShader("raw interpolation has no reflected attribute"); + } + pair.input_layout = vertex_layout(effective_layout(pair.vertex), pair.vertex); + if (!root.empty()) { + for (auto *stage : {&pair.vertex, &pair.pixel}) { + const bool vertex = stage == &pair.vertex; + const auto visibility = vertex ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL; + auto parameter = [&](unsigned index) -> const D3D12_ROOT_PARAMETER1 & { + if (index >= layout.NumParameters || + layout.Flags & (vertex ? D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS + : D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS)) + throw UnsupportedComputeShader("graphics root parameter inaccessible"); + const auto &p = layout.pParameters[index]; + if (p.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL && p.ShaderVisibility != visibility) + throw UnsupportedComputeShader("graphics root parameter stage visibility mismatch"); + return p; + }; + for (const auto &c : stage->constants) { + const auto &p = parameter(c.root_parameter); + if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS || + c.count > p.Constants.Num32BitValues) + throw UnsupportedComputeShader("graphics root constant span mismatch"); + } + for (auto &binding : stage->bindings) { + const auto &p = parameter(binding.root_parameter); + if (binding.kind == ComputeViewKind::root_buffer_srv) { + if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_CBV && p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) + throw UnsupportedComputeShader("graphics scalar load requires a root CBV or SRV"); + continue; + } + if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE || binding.byte_offset % 32) + throw UnsupportedComputeShader("graphics binding is outside a descriptor table"); + const auto slot = binding.byte_offset / 32; + const auto kind = + compute_uav(binding.kind) ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + uint64_t next = 0; + bool found = false; + for (unsigned i = 0; i < p.DescriptorTable.NumDescriptorRanges; ++i) { + const auto &range = p.DescriptorTable.pDescriptorRanges[i]; + const uint64_t first = + range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next + : range.OffsetInDescriptorsFromTableStart; + next = first + range.NumDescriptors; + // Scalar buffer loads also consume CBV table records. The + // resolver supplies a raw SRV over the recorded CBV window. + if (first <= slot && slot < next && (kind == range.RangeType || + (accepts_cbv_window(binding.kind) && range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV))) + found = true; + } + if (reflected && binding.array_count == 1) { + const auto &iface = interfaces.at(vertex ? GpuStage::vs : GpuStage::ps); + unsigned sgpr = 8; + for (unsigned k = 0; k < binding.root_parameter; ++k) { + const auto &prev = layout.pParameters[k]; + sgpr += prev.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE ? 1 : + prev.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? prev.Constants.Num32BitValues : 2; + } + const bool used = apply_reflected_table_use(binding, iface, + exact_pair ? std::optional<unsigned>{} : std::optional<unsigned>{sgpr}); + const bool needs_record = !found || (!exact_pair && (accepts_cbv_window(binding.kind) || + binding.kind == ComputeViewKind::texture_srv || + binding.kind == ComputeViewKind::d16_sample_srv)); + if (!used && needs_record && binding.kind != ComputeViewKind::heap_stride_srv) + throw UnsupportedComputeShader(std::string("missing reflected resource: ") + (vertex ? "VS" : "PS") + " root " + std::to_string(binding.root_parameter) + " offset " + std::to_string(binding.byte_offset) + " kind " + std::to_string(static_cast<unsigned>(binding.kind)) + " user SGPR " + std::to_string(sgpr)); + found |= used; + } + apply_scalar_table_layout(binding, p.DescriptorTable); + if (!found) + throw UnsupportedComputeShader(std::string("graphics descriptor range does not cover resource: ") + + (vertex ? "VS" : "PS") + " root " + std::to_string(binding.root_parameter) + + " byte offset " + std::to_string(binding.byte_offset) + " slot " + std::to_string(slot)); + } + } + } + if (write_cache && !cache.empty()) { + auto vertex = encode(pair.vertex); + payload.clear(); + word(payload, static_cast<uint32_t>(vertex.size())); + payload += vertex; + payload += encode(pair.pixel); + publish(path, key, payload); + } + return verified(std::move(pair)); +} + +static const char *view_kind_name(ComputeViewKind kind) { + static const char *const names[] = { + "buffer_srv", "typed_buffer_srv", "texture_srv", "texture_uav", "raw_vector_srv", "half_scalar_uav", + "heap_stride_srv", "raw_buffer_uav", "typed_buffer_uav", "half_buffer_uav", "root_buffer_srv", + "comparison_texture_srv", "half2_texture_uav", "half4_texture_uav", "cube_sample_srv", "cube_comparison_srv", + "indexed_atomic_uav", "d16_sample_srv", "byte_window_srv", "heap_buffer_srv", "heap_sampler", + "uint_texture_uav", "float_texture_uav", "float2_texture_uav", "float3_texture_uav", + "packed_d16_x_uav", "indexed_raw_srv"}; + const auto index = static_cast<size_t>(kind); + return index < std::size(names) ? names[index] : "unknown"; +} + +// "SRV kind texture_srv 3d": the binding kind, and for image kinds the ISA dimension and a descriptor array. +static std::string view_shape(const char *type, const ComputeViewBinding &b) { + std::string out = std::string(type) + " kind " + view_kind_name(b.kind); + if (std::string_view(out).find("texture") != std::string_view::npos || + std::string_view(out).find("sample") != std::string_view::npos || + std::string_view(out).find("cube") != std::string_view::npos) { + static const char *const dims[] = {"1d", "2d", "3d", "cube", "1d-array", "2d-array", "2d-msaa", "2d-msaa-array"}; + out += ' '; + out += b.image_dimension < std::size(dims) ? dims[b.image_dimension] : "unknown-dimension"; + } + if (b.array_count != 1) + out += " array"; + return out; +} + +std::optional<std::string> format_compute_runtime_manifest(const NativeComputeShader &program, std::string *reason) { + auto refuse = [&](std::string why) -> std::optional<std::string> { + if (reason) + *reason = std::move(why); + return std::nullopt; + }; + if (!program.group[0] || !program.group[1] || !program.group[2]) + return refuse("group size has a zero dimension"); + unsigned ud_count = 0; + for (const auto &block : program.constants) { + if (block.root_parameter >= 16) + return refuse("root constants above root parameter 15"); + if (block.count > 8) + return refuse("more than 8 root constants in one root parameter"); + ud_count += block.count; + } + ud_count += static_cast<unsigned>(program.stride_srvs.size()); + if (ud_count > 32) + return refuse("more than 32 user data words"); + + auto sorted = program.bindings; + std::sort(sorted.begin(), sorted.end(), [](const auto &a, const auto &b) { + const bool ua = compute_uav(a.kind), ub = compute_uav(b.kind); + if (ua != ub) + return !ua; + return a.shader_register < b.shader_register; + }); + + unsigned srv_count = 0, uav_count = 0; + std::ostringstream srv_lines, uav_lines, sampler_lines; + for (const auto &b : sorted) { + if (b.root_parameter == compute_resource_heap) + return refuse("resource heap view"); + if (b.root_parameter == compute_sampler_heap) + return refuse("sampler heap"); + if (b.root_parameter >= 16) + return refuse("view above root parameter 15"); + if (!compute_uav(b.kind)) { + if (b.shader_register != srv_count++) + return refuse("SRV registers not contiguous"); + if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || + b.kind == ComputeViewKind::byte_window_srv) { + srv_lines << "srv " << b.shader_register << " buf table " << b.root_parameter << ' ' << b.byte_offset + << '\n'; + } else if (b.kind == ComputeViewKind::texture_srv && b.array_count == 1 && + (b.image_dimension == 0 || b.image_dimension == 1 || b.image_dimension == 2 || + b.image_dimension == 5)) { + const char *tex = b.image_dimension == 0 ? "tex1d" + : b.image_dimension == 1 ? "tex2d" + : b.image_dimension == 2 ? "tex3d" + : "tex2da"; + srv_lines << "srv " << b.shader_register << ' ' << tex << " table " << b.root_parameter << ' ' + << b.byte_offset << '\n'; + } else { + return refuse(view_shape("SRV", b)); + } + } else { + if (b.shader_register != uav_count++) + return refuse("UAV registers not contiguous"); + if (b.kind == ComputeViewKind::raw_buffer_uav) { + uav_lines << "uav " << b.shader_register << " table " << b.root_parameter << ' ' << b.byte_offset + << '\n'; + } else if (b.kind == ComputeViewKind::half_buffer_uav && b.array_count == 1 && + (b.required_bytes == 2 || b.required_bytes == 4 || b.required_bytes == 8)) { + uav_lines << "uav " << b.shader_register << " bufhalf table " << b.root_parameter << ' ' + << b.byte_offset << " bytes " << b.required_bytes << '\n'; + } else if (b.kind == ComputeViewKind::packed_d16_x_uav && b.array_count == 1 && b.required_bytes == 2) { + // One halfword. A wider element (R32_UINT holds two) is not published as this store. + uav_lines << "uav " << b.shader_register << " bufd16x table " << b.root_parameter << ' ' + << b.byte_offset << " bytes " << b.required_bytes << '\n'; + } else if (b.kind == ComputeViewKind::uint_texture_uav && b.image_dimension == 1 && b.array_count == 1) { + uav_lines << "uav " << b.shader_register << " tex2d uint table " << b.root_parameter << ' ' + << b.byte_offset << " channels 1\n"; + } else if (const auto channels = exact_texture_uav_channels(b.kind); channels && b.array_count == 1 && + (b.image_dimension == 1 || b.image_dimension == 2 || b.image_dimension == 5)) { + const char *dimension = b.image_dimension == 2 ? "tex3d" : b.image_dimension == 5 ? "tex2da" : "tex2d"; + uav_lines << "uav " << b.shader_register << ' ' << dimension << " float table " << b.root_parameter + << ' ' << b.byte_offset << " channels " << channels << '\n'; + } else if ((b.kind == ComputeViewKind::texture_uav || b.kind == ComputeViewKind::half4_texture_uav) && + (b.image_dimension == 1 || b.image_dimension == 5 || + (b.kind == ComputeViewKind::texture_uav && b.image_dimension == 2)) && b.array_count == 1) { + uav_lines << "uav " << b.shader_register << (b.image_dimension == 5 ? " tex2da" : b.image_dimension == 2 ? " tex3d" : " tex2d") + << " float table " << b.root_parameter << ' ' << b.byte_offset << " channels 4\n"; + } else { + return refuse(view_shape("UAV", b)); + } + } + } + if (srv_count > 32) + return refuse("more than 32 SRVs"); + if (uav_count > 8) + return refuse("more than 8 UAVs"); + + for (size_t i = 0; i < program.samplers.size(); ++i) { + const auto &s = program.samplers[i]; + if (s.comparison) + return refuse("comparison sampler"); + char line[64]; + std::snprintf(line, sizeof(line), "%s %zu %08x %08x %08x %08x\n", s.explicit_lod ? "smpl" : "smp", i, + s.words[0], s.words[1], s.words[2], s.words[3]); + sampler_lines << line; + } + + std::ostringstream out; + out << "x2w-manifest 2\nstage cs\ngroup " << program.group[0] << ' ' << program.group[1] << ' ' << program.group[2] + << "\nud " << ud_count << '\n'; + unsigned ud_index = 0; + for (const auto &block : program.constants) + for (unsigned j = 0; j < block.count; ++j) + out << "udsrc " << ud_index++ << " rootconst " << block.root_parameter << ' ' << j << '\n'; + for (unsigned srv : program.stride_srvs) { + if (srv >= srv_count || sorted[srv].kind != ComputeViewKind::raw_vector_srv || + sorted[srv].array_count != 1) + return refuse("stride words from a view that is not one raw vector SRV"); + out << "udsrc " << ud_index++ << " stride " << srv << '\n'; + } + out << srv_lines.str() << uav_lines.str() << sampler_lines.str() + << "native " << native_compute_output_revision << '\n'; + return out.str(); +} + +std::optional<std::string> format_graphics_runtime_manifest(const DirectGraphicsPair &pair, std::string_view rtv_request) { + const bool fixed_stream = pair.vertex.vertex_fetch && !pair.input_layout.empty(); + if (pair.vertex.vertex_fetch != !pair.input_layout.empty()) + return std::nullopt; + for (const auto &e : pair.input_layout) + if (e.semantic != "X2W_RAW_VERTEX" || e.slot || e.offset != e.index || e.classification || e.step_rate || + !e.used || (e.format != DXGI_FORMAT_R8_UNORM && e.format != DXGI_FORMAT_R8G8_UNORM && + e.format != DXGI_FORMAT_R8G8B8A8_UNORM && e.format != DXGI_FORMAT_R32G32_UINT && + e.format != DXGI_FORMAT_R32G32B32_UINT && e.format != DXGI_FORMAT_R32G32B32A32_UINT && + e.format != DXGI_FORMAT_R8_UINT)) + return std::nullopt; + for (const auto &in : pair.vertex.inputs) + if (in.name != "SV_VertexID" && in.name != "SV_InstanceID" && !(fixed_stream && in.name == "X2W_RAW_VERTEX")) + return std::nullopt; + // An integer target is published only for the RTV variant whose format asked for that type. + for (const auto &out : pair.pixel.outputs) + if (out.name == "SV_Target" && out.component != 9 && + (out.index >= pair.target_components.size() || out.component != pair.target_components[out.index])) + return std::nullopt; + + std::optional<NativeGraphicsBindings> maybe_bindings; + GraphicsConstantLayout constants; + try { + maybe_bindings.emplace(pair); + constants = pair.constant_layout(); + } catch (const std::exception &) { + return std::nullopt; + } + const auto &bindings = *maybe_bindings; + const unsigned uav_count = static_cast<unsigned>(bindings.views.size()) - bindings.srv_count; + if (bindings.srv_count > 32 || uav_count > 8) + return std::nullopt; + for (unsigned count : constants.counts) + if (count > 8) + return std::nullopt; + const unsigned total_constants = constants.offset(static_cast<unsigned>(constants.counts.size())); + if (total_constants > 32) + return std::nullopt; + + std::ostringstream srv_lines, uav_lines, sampler_lines; + for (unsigned i = 0; i < bindings.srv_count; ++i) { + const auto &b = bindings.views[i]; + if (b.root_parameter >= 16) + return std::nullopt; + if (b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv || + b.kind == ComputeViewKind::byte_window_srv) { + srv_lines << "srv " << i << " buf table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + } else if (b.kind == ComputeViewKind::indexed_raw_srv && b.array_count == 1 && + b.required_bytes && !(b.required_bytes % 4) && b.required_bytes <= 2048) { + srv_lines << "srv " << i << " idxbuf table " << b.root_parameter << ' ' << b.byte_offset << ' ' << b.required_bytes << '\n'; + } else if (b.kind == ComputeViewKind::root_buffer_srv && b.byte_offset == 0 && b.array_count == 1) { + srv_lines << "srv " << i << " buf root " << b.root_parameter << '\n'; + } else if (b.kind == ComputeViewKind::texture_srv || b.kind == ComputeViewKind::comparison_texture_srv) { + const char *tex = b.image_dimension == 0 ? "tex1d" + : b.image_dimension == 1 ? "tex2d" + : b.image_dimension == 2 ? "tex3d" + : b.image_dimension == 5 ? "tex2da" + : nullptr; + if (!tex) + return std::nullopt; + srv_lines << "srv " << i << ' ' << tex << " table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + } else { + return std::nullopt; + } + } + for (unsigned j = 0; j < uav_count; ++j) { + const auto &b = bindings.views[bindings.srv_count + j]; + if (b.root_parameter >= 16 || b.array_count != 1) + return std::nullopt; + if (b.kind == ComputeViewKind::raw_buffer_uav) { + // First slice: one pixel UAV with no other resource views. Vertex stores, + // mixed views and aliases need their own runtime acceptance. + if (uav_count != 1 || bindings.srv_count || !pair.vertex.bindings.empty()) + return std::nullopt; + uav_lines << "uav " << j << " raw table " << b.root_parameter << ' ' << b.byte_offset << '\n'; + continue; + } + if (b.kind != ComputeViewKind::texture_uav && b.kind != ComputeViewKind::half4_texture_uav) + return std::nullopt; + if (b.image_dimension != 1 && b.image_dimension != 5) + return std::nullopt; + uav_lines << "uav " << j << (b.image_dimension == 5 ? " tex2da table " : " tex2d table ") << b.root_parameter + << ' ' << b.byte_offset << '\n'; + } + if (bindings.samplers.heap) sampler_lines << "smpheap 2048 1 fallback 2047\n"; + for (size_t i = 0; i < bindings.samplers.statics.size(); ++i) { + const auto &w = bindings.samplers.statics[i]; + const bool cmp = i < bindings.samplers.comparison.size() && bindings.samplers.comparison[i]; + const bool lod = !cmp && i < bindings.samplers.lod_limits.size() && bindings.samplers.lod_limits[i]; + char line[64]; + std::snprintf(line, sizeof(line), "%s %zu %08x %08x %08x %08x\n", cmp ? "smpc" : lod ? "smpl" : "smp", i, w[0], + w[1], w[2], w[3]); + sampler_lines << line; + } + + unsigned params = 0; + for (const auto &out : pair.vertex.outputs) + if (out.name == "TEXCOORD") + params = (std::max)(params, out.index / 4 + 1); + + std::ostringstream out; + out << "x2w-manifest " << (fixed_stream ? 3 : uav_count ? 2 : 1) << "\nud " << (total_constants ? total_constants : 1u) << '\n'; + for (const auto &e : pair.input_layout) + out << "fixedvb " << e.offset << ' ' << e.format << '\n'; + if (!total_constants) { + out << "udsrc 0 rect\n"; + } else { + unsigned ud_index = 0; + for (unsigned r = 0; r < constants.counts.size(); ++r) + for (unsigned j = 0; j < constants.counts[r]; ++j) + out << "udsrc " << ud_index++ << " rootconst " << r << ' ' << j << '\n'; + } + out << srv_lines.str() << uav_lines.str() << sampler_lines.str() << "params " << params << "\ntargets"; + bool any_target = false; + for (unsigned t = 0; t < pair.pixel.pixel_writes.size(); ++t) { + if (!pair.pixel.pixel_writes[t]) + continue; + out << ' ' << t; + any_target = true; + } + if (!any_target) + out << ' '; + out << '\n'; + for (unsigned t = 0; t < pair.pixel.pixel_writes.size(); ++t) { + const unsigned mask = pair.pixel.pixel_writes[t]; + if (mask > 0 && mask < 0xf) { + char line[16]; + std::snprintf(line, sizeof(line), "wmask %u 0x%x\n", t, mask); + out << line; + } + } + if (!rtv_request.empty()) + out << rtv_request << '\n'; + return out.str(); +} +} // namespace x2w diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h new file mode 100644 index 0000000000..ec388dc541 --- /dev/null +++ b/src/direct_compute_cache.h @@ -0,0 +1,43 @@ +#pragma once + +#include "gfx1013_compute_native.h" +#include <unordered_map> + +// The result includes the emitted DXIL module and its exact desktop/guest binding layout. +namespace x2w { +enum class ComputePackResult { miss, prepared, unsupported }; +struct ComputePackCounts { size_t prepared{}, unsupported{}; std::vector<std::string> errors; }; +class ComputeFrontendPack { + struct Record { std::string digest, payload; bool unsupported; }; + std::unordered_map<uint64_t, Record> records_; + unsigned entry_{}; +public: + static ComputeFrontendPack load(const std::filesystem::path &file, unsigned entry); + ComputePackResult lookup(const ComputeRequest &request, unsigned entry, NativeComputeShader &program, + std::string &diagnostic) const; + size_t size() const { return records_.size(); } +}; +ComputePackCounts build_compute_frontend_pack(const std::filesystem::path &requests, const std::filesystem::path &cache, + unsigned entry); +size_t index_graphics_interfaces(const std::filesystem::path &source, const std::filesystem::path &cache); +// A logical match identifies the source shader. Only exact matches establish +// the compiled entry ABI, instruction offsets, and resource register layout. +GuestShaderStage reviewed_graphics_stage(std::string_view raw, GpuStage kind, + const std::filesystem::path &cache, bool &exact); +// Signature component (f32/u32/i32) for supported typed IA and RTV formats. +unsigned dxil_io_component(unsigned dxgi_format); +NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, + const std::filesystem::path &cache, bool &cache_hit, + HeapViewContract heap_view = HeapViewContract::none); +DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view b, + const std::filesystem::path &cache, bool &cache_hit, + std::string_view root = {}, std::string_view input_layout = {}, + std::string_view pixel_entry = {}, bool write_cache = true, + const std::vector<unsigned> &rtv_formats = {}); +// Without a manifest, reason (when given) receives a fixed refusal text: no register numbers, offsets or keys. +std::optional<std::string> format_compute_runtime_manifest(const NativeComputeShader &program, + std::string *reason = nullptr); +// rtv_request: the "rtv1 ..." text of an RTV variant, written as the manifest's last line for the runtime to match. +std::optional<std::string> format_graphics_runtime_manifest(const DirectGraphicsPair &pair, + std::string_view rtv_request = {}); +} diff --git a/src/dxil_module.h b/src/dxil_module.h new file mode 100644 index 0000000000..ee64237295 --- /dev/null +++ b/src/dxil_module.h @@ -0,0 +1,342 @@ +#pragma once +#include <algorithm> +#include <bitset> +#include <cctype> +#include <climits> +#include <deque> +#include <map> +#include <set> +#include <sstream> +#include <stdexcept> +#include <string> +#include <tuple> +#include <vector> + +namespace x2w { +// LLVM's DXIL dialect. Resource declarations, handle annotations and entry metadata +// are produced together so the bytecode and the runtime binding contract agree. +class DxilModule { + public: + using Text = std::string; + struct Resource { + unsigned cls, reg, kind, component, width, bytes; + unsigned count = 1; + bool comparison = false; + unsigned space = 0; + }; + std::ostringstream body, setup, globals; + bool uses_wave = false; + bool heap_used = false; + unsigned mesh_vertices = 0, mesh_primitives = 0; + unsigned features = 0; + struct Signature { + Text name; + unsigned semantic_index, kind, component, row, first, width, interpolation, used = 0; + }; + // The final bit marks rasterizer inputs without a packed signature row. + // They vary between lanes but occupy no slot in the ViewID matrix. + using InputMask = std::bitset<129>; + bool track_inputs = false; + bool loop_dependencies = false; + std::map<Text, InputMask> dependencies; + std::map<Text, std::vector<Text>> consumers; + std::map<unsigned, std::vector<Text>> output_values; + std::vector<Signature> inputs, outputs; + std::map<unsigned, InputMask> output_dependencies; + Text value(const Text &instruction) { + auto name = "%t" + std::to_string(sequence++); + if (track_inputs) { + InputMask sources; + for (size_t at = 0; (at = instruction.find('%', at)) != Text::npos;) { + size_t end = at + 1; + while (end < instruction.size() && + (std::isalnum(static_cast<unsigned char>(instruction[end])) || instruction[end] == '_')) + ++end; + auto operand = instruction.substr(at, end - at); + if (loop_dependencies && + (operand.rfind("%t", 0) == 0 || operand.rfind("%p", 0) == 0 || operand.rfind("%indexed", 0) == 0)) + consumers[operand].push_back(name); + auto found = dependencies.find(operand); + if (found != dependencies.end()) + sources |= found->second; + at = end; + } + if (sources.any()) + dependencies.emplace(name, sources); + } + body << " " << name << " = " << instruction << "\n"; + return name; + } + void finish_loop_dependencies() { + std::deque<Text> pending; + for (const auto &[name, mask] : dependencies) + if (mask.any()) + pending.push_back(name); + while (!pending.empty()) { + auto source = std::move(pending.front()); + pending.pop_front(); + auto it = consumers.find(source); + if (it == consumers.end()) + continue; + const auto mask = dependencies.at(source); + for (const auto &user : it->second) { + auto &dest = dependencies[user]; + if ((mask & ~dest).none()) + continue; + dest |= mask; + pending.push_back(user); + } + } + for (const auto &[channel, values] : output_values) + for (const auto &value : values) + output_dependencies[channel] |= dependencies[value]; + } + Text binary(const Text &op, const Text &a, const Text &b) { return value(op + " i32 " + a + ", " + b); } + Text invoke(const Text &type, const Text &name, unsigned opcode, const std::vector<std::pair<Text, Text>> &args, + const Text &attr) { + Text decl = "declare " + type + " @dx.op." + name + "(i32", + call = "call " + type + " @dx.op." + name + "(i32 " + std::to_string(opcode); + for (auto &[t, v] : args) { + decl += ", " + t; + call += ", " + t + " " + v; + } + decl += ") " + attr; + call += ")"; + auto [it, ok] = declarations.emplace(name, decl); + if (!ok && it->second != decl) + throw std::logic_error("inconsistent DXIL declaration"); + if (type != "void") + return value(call); + body << " " << call << "\n"; + return {}; + } + Text handle(Resource r, const Text &offset = {}) { + const Text reg = std::to_string(r.reg), cls = std::to_string(r.cls); + const auto found = std::find_if(resources.begin(), resources.end(), [&](const Resource &other) { + return other.cls == r.cls && other.reg == r.reg && other.space == r.space; + }); + Text h = "%h" + cls + "_" + reg; + if (r.space) h += "_s" + std::to_string(r.space); + if (found != resources.end()) { + if (found->kind != r.kind || found->width != r.width || found->component != r.component || + found->bytes != r.bytes || found->count != r.count || found->comparison != r.comparison) + throw std::logic_error("incompatible DXIL binding declarations"); + } else + resources.push_back(r); + if (offset.empty() && !static_handles.insert(h).second) + return h; + Text index = reg; + auto &out = offset.empty() ? setup : body; + if (!offset.empty()) { + index = r.reg ? binary("add", reg, offset) : offset; + h = "%indexed" + std::to_string(sequence++); + if (track_inputs) { + if (auto it = dependencies.find(index); it != dependencies.end()) + dependencies[h] = it->second; + if (loop_dependencies) + consumers[index].push_back(h); + } + } + const unsigned props = r.cls == 2 ? r.bytes : r.component + r.width * 256; + out << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromBinding(i32 217, %dx.types.ResBind { i32 " + << reg << ", i32 " << r.reg + r.count - 1 << ", i32 " << r.space << ", i8 " << cls << " }, i32 " << index << ", i1 " + << (offset.empty() ? "false" : "true") << ")\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 " << (r.kind + (r.cls == 1 ? 4096 : 0) + (r.comparison ? 32768 : 0)) << ", i32 " << props + << " })\n"; + return h; + } + // A handle taken from the descriptor heap at a run-time index (SM 6.6 ResourceDescriptorHeap[index]), annotated with + // the view class the shader reads: `kind` is the DXIL resource kind (11 raw buffer, 2 Texture2D) and `props` the + // second ResourceProperties word. No resource record is declared: the binding is the whole heap. + Text heap_handle(const Text &index, unsigned kind, unsigned props, bool uav = false, bool nonuniform = true) { + heap_used = true; + const Text h = "%heap" + std::to_string(sequence++); + if (track_inputs) { + if (auto it = dependencies.find(index); it != dependencies.end()) dependencies[h] = it->second; + if (loop_dependencies) consumers[index].push_back(h); + } + body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index + << ", i1 false, i1 " << (nonuniform ? "true" : "false") << ")\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 " << (kind + (uav ? 4096 : 0)) << ", i32 " << props << " })\n"; + return h; + } + // A sampler taken from the directly indexed sampler heap at a constant index (SM 6.6 SamplerDescriptorHeap[index]). + // The handle is annotated as a sampler (resource kind 14). The caller sets the module flag 0x80000000. + Text sampler_heap_handle(const Text &index) { + heap_used = true; + const Text h = "%heap" + std::to_string(sequence++); + body << " " << h << "b = call %dx.types.Handle @dx.op.createHandleFromHeap(i32 218, i32 " << index + << ", i1 true, i1 false)\n" + << " " << h << " = call %dx.types.Handle @dx.op.annotateHandle(i32 216, %dx.types.Handle " << h + << "b, %dx.types.ResourceProperties { i32 14, i32 0 })\n"; + return h; + } + // DXIL validator 1.8 accepts implicit-derivative operations in compute; every other + // module keeps validator 1.6. + unsigned validator_minor = 6; + Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") { + std::ostringstream out; + out << "target datalayout = " + "\"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\"\n" + "target triple = \"dxil-ms-dx\"\n" + "%dx.types.Handle = type { i8* }\n%dx.types.ResBind = type { i32, i32, i32, i8 }\n" + "%dx.types.ResourceProperties = type { i32, i32 }\n%dx.types.ResRet.i32 = type " + "{i32,i32,i32,i32,i32}\n" + "%dx.types.ResRet.f32 = type {float,float,float,float,i32}\n%dx.types.CBufRet.i32 = type " + "{i32,i32,i32,i32}\n" + "%dx.types.fouri32 = type {i32,i32,i32,i32}\n" + "%dx.types.Dimensions = type {i32,i32,i32,i32}\n"; + std::vector<Text> metadata; + auto node = [&](const Text &content) { + auto id = "!" + std::to_string(metadata.size()); + metadata.push_back(content); + return id; + }; + auto list = [&](const std::vector<Text> &ids) { + Text content; + for (auto &id : ids) { + if (!content.empty()) + content += ", "; + content += id; + } + return ids.empty() ? Text("null") : node(content); + }; + std::vector<Text> groups[4]; + std::sort(resources.begin(), resources.end(), + [](const auto &a, const auto &b) { + return std::tie(a.cls, a.space, a.reg) < std::tie(b.cls, b.space, b.reg); + }); + for (auto &r : resources) { + const Text type = "%res" + std::to_string(r.cls) + "_" + std::to_string(r.reg) + + (r.space ? "_s" + std::to_string(r.space) : ""); + Text scalar = r.component == 9 ? "float" : "i32"; + Text member = r.cls == 2 ? "[" + std::to_string(r.bytes / 16) + " x <4 x i32>]" + : r.width > 1 ? "<" + std::to_string(r.width) + " x " + scalar + ">" + : scalar; + out << type << " = type { " << member << " }\n"; + const Text symbol = r.count == 1 ? type : "[" + std::to_string(r.count) + " x " + type + "]"; + Text md = "i32 " + std::to_string(groups[r.cls].size()) + ", " + symbol + "* undef, !\"\", i32 " + + std::to_string(r.space) + ", i32 " + + std::to_string(r.reg) + ", i32 " + std::to_string(r.count) + ", i32 " + + std::to_string(r.cls == 2 ? r.bytes + : r.cls == 3 ? unsigned(r.comparison) + : r.kind); + if (r.cls == 0) + md += ", i32 0"; + if (r.cls == 1) + md += ", i1 false, i1 false, i1 false"; + md += ", " + (r.component ? node("i32 0, i32 " + std::to_string(r.component)) : Text("null")); + groups[r.cls].push_back(node(md)); + } + Text res = "null"; + if (!resources.empty()) + res = node(list(groups[0]) + ", " + list(groups[1]) + ", " + list(groups[2]) + ", " + list(groups[3])); + // AMD's DXIL compiler (amdxc64.dll) dereferences Module::getNamedMetadata("llvm.ident") without a null check. + const auto ident = node("!\"x2w\""), version = node("i32 1, i32 6"), + model = node("!\"" + stage + "\", i32 6, i32 6"); + // 0x8000: more than 8 UAV slots. DXC sums the declared UAV range sizes; the validator + // refuses a module whose flags do not match. + unsigned uav_slots = 0; + for (const auto &r : resources) + if (r.cls == 1) + uav_slots += (std::min)(r.count, 9u); + const unsigned flags = features | (uses_wave ? 524288 : 0) | (uav_slots > 8 ? 0x8000 : 0); + Text properties = "null", signature = "null", view_state; + if (stage == "cs") { + const auto size = + node("i32 " + std::to_string(x) + ", i32 " + std::to_string(y) + ", i32 " + std::to_string(z)); + const auto wave = node("i32 32"); + properties = node((flags ? "i32 0, i64 " + std::to_string(flags) + ", " : "") + "i32 4, " + size + + ", i32 11, " + wave); + } else { + if (flags) + properties = node("i32 0, i64 " + std::to_string(flags)); + if (stage == "gs") + properties = node("i32 1, " + node("i32 3, i32 6, i32 1, i32 5, i32 1")); + if (stage == "ms") { + const auto size = node("i32 " + std::to_string(x) + ", i32 " + std::to_string(y) + + ", i32 " + std::to_string(z)); + const auto mesh = node(size + ", i32 " + std::to_string(mesh_vertices) + ", i32 " + + std::to_string(mesh_primitives) + ", i32 2, i32 0"); + properties = node((flags ? "i32 0, i64 " + std::to_string(flags) + ", " : "") + "i32 9, " + mesh); + } + auto signature_list = [&](const std::vector<Signature> &rows, unsigned &scalars) { + std::vector<Text> ids; + for (const auto &r : rows) { + if (r.name.empty() || + r.name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") != + Text::npos || + (r.row >= 32 && r.row != UINT_MAX) || !r.width || r.first + r.width > 4) + throw std::runtime_error("invalid graphics signature"); + if (r.row != UINT_MAX) + scalars = (std::max)(scalars, r.row * 4 + r.first + r.width); + auto index = node("i32 " + std::to_string(r.semantic_index)); + auto used = r.used ? node("i32 3, i32 " + std::to_string(r.used)) : Text("null"); + ids.push_back(node("i32 " + std::to_string(ids.size()) + ", !\"" + r.name + "\", i8 " + + std::to_string(r.component) + ", i8 " + std::to_string(r.kind) + ", " + index + + ", i8 " + std::to_string(r.interpolation) + ", i32 1, i8 " + + std::to_string(r.width) + ", i32 " + + (r.row == UINT_MAX ? "-1" : std::to_string(r.row)) + ", i8 " + + (r.row == UINT_MAX ? "-1" : std::to_string(r.first)) + ", " + used)); + } + return list(ids); + }; + unsigned in_count = 0, out_count = 0; + const auto in_sig = signature_list(inputs, in_count), out_sig = signature_list(outputs, out_count); + signature = node(in_sig + ", " + out_sig + ", null"); + std::vector<unsigned> matrix{in_count, out_count}; + unsigned stride = (out_count + 31) / 32; + matrix.resize(2 + in_count * stride); + for (const auto &[output, mask] : output_dependencies) + for (unsigned i = 0; i < in_count; ++i) + if (mask.test(i)) + matrix.at(2 + i * stride + output / 32) |= 1u << (output % 32); + if (stage == "gs") + matrix.resize(matrix.size() + 3); // no outputs on streams 1 to 3 + if (stage == "ms") + matrix.push_back(0); // no per-primitive signature elements + Text values; + for (auto word : matrix) { + if (!values.empty()) + values += ", "; + values += "i32 " + std::to_string(word); + } + auto id = "!" + std::to_string(metadata.size()); + metadata.push_back("[" + std::to_string(matrix.size()) + " x i32] [" + values + "]"); + view_state = "!dx.viewIdState = !{" + id + "}\n"; + } + const auto entry = node("void ()* @main, !\"main\", " + signature + ", " + res + ", " + properties); + out << view_state; + out << globals.str() << "define void @main() {\nentry:\n" << setup.str() << body.str() << "}\n"; + for (auto &[name, decl] : declarations) + out << decl << "\n"; + if (heap_used) { + out << "declare %dx.types.Handle @dx.op.createHandleFromHeap(i32,i32,i1,i1) nounwind readnone\n"; + if (resources.empty()) + out << "declare %dx.types.Handle " + "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; + } + if (!resources.empty()) + out << "declare %dx.types.Handle @dx.op.createHandleFromBinding(i32,%dx.types.ResBind,i32,i1) nounwind " + "readnone\n" + "declare %dx.types.Handle " + "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; + out << "!llvm.ident = !{" << ident << "}\n!dx.version = !{" << version << "}\n!dx.valver = !{" << node("i32 1, i32 " + std::to_string(validator_minor)) + << "}\n!dx.shaderModel = !{" << model << "}\n"; + if (res != "null") + out << "!dx.resources = !{" << res << "}\n"; + out << "!dx.entryPoints = !{" << entry << "}\n"; + for (size_t i = 0; i < metadata.size(); ++i) + out << "!" << i << " = !{" << metadata[i] << "}\n"; + return out.str(); + } + + private: + unsigned sequence = 0; + std::vector<Resource> resources; + std::set<Text> static_handles; + std::map<Text, Text> declarations; +}; +} // namespace x2w diff --git a/src/era_heap.cpp b/src/era_heap.cpp index 25520fc730..10e0f15cfc 100644 --- a/src/era_heap.cpp +++ b/src/era_heap.cpp @@ -76,7 +76,8 @@ Fields decode(std::uint64_t attributes) noexcept static_cast<std::uint32_t>((attributes >> 16) & 0xff), static_cast<std::uint32_t>((attributes >> 24) & 0x1f), static_cast<std::uint32_t>((attributes >> 29) & 0xf), - attributes >> 33, + static_cast<std::uint32_t>((attributes >> 33) & 1), + static_cast<std::uint32_t>((attributes >> 34) & 0x3fffffff), }; } @@ -87,6 +88,11 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept if (bytes == 0 || fields.reserved != 0 || fields.page_size == 3) { return nullptr; } + // The title asked for an address below 4 GiB. This allocator does not yet provide + // one, so refuse instead of returning an address above that boundary. + if (fields.address_below_4gib) { + return nullptr; + } const auto alignment = std::size_t{1} << std::max(4u, fields.alignment); // Leave room for CRT alignment bookkeeping even for deliberately oversized input. const auto limit = static_cast<std::size_t>(std::numeric_limits<std::ptrdiff_t>::max()); @@ -112,7 +118,7 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept // SlimEra commits graphics memory as a separate virtual allocation. The desktop // places it on an allocation-granularity boundary (64 KiB on x64 Windows), which // covers 4 KB and 64 KB pages. Larger page sizes or alignments are not honored here. - constexpr std::size_t page_bytes[]{std::size_t{4} << 10, std::size_t{64} << 10, std::size_t{4} << 20}; + constexpr std::size_t page_bytes[]{std::size_t{4} << 10, std::size_t{64} << 10, std::size_t{2} << 20}; if (std::max(page_bytes[fields.page_size], alignment) > allocation_granularity()) { return nullptr; } diff --git a/src/era_heap.h b/src/era_heap.h index 3c288b390f..515468cfd0 100644 --- a/src/era_heap.h +++ b/src/era_heap.h @@ -3,20 +3,21 @@ #include <cstddef> #include <cstdint> -// Desktop handling of attribute words decoded with the public Xbox One ERA -// XALLOC_ATTRIBUTES layout (SlimEra era.h): objectType:14, pageSize:2, allocatorId:8, -// alignment:5, memoryType:4, reserved:31. That Scarlett uses this layout is an -// assumption; allocator-ID meaning and GPU visibility of graphics types are unconfirmed. +// Desktop handling of attribute words decoded with the XALLOC_ATTRIBUTES layout +// published by the GDK 261000 xmem.h: objectType:14, pageSize:2, allocatorId:8, +// alignment:5, memoryType:4, an address-below-4-GiB bit at 33 and reserved:30 above it. +// Allocator-ID meaning and GPU visibility of graphics types remain unconfirmed. // Heap and graphics memory types are served. Physical memory types, undefined // field values and alignments the desktop cannot honor return a null pointer. namespace era_heap { struct Fields { std::uint32_t object_type; - std::uint32_t page_size; // 0: 4 KB, 1: 64 KB, 2: 4 MB, 3: undefined + std::uint32_t page_size; // 0: 4 KB, 1: 64 KB, 2: 2 MB, 3: undefined std::uint32_t allocator_id; std::uint32_t alignment; // log2 of the requested alignment std::uint32_t memory_type; // 0: heap, 1-6: graphics, 7-9: physical - std::uint64_t reserved; + std::uint32_t address_below_4gib; // 1: the caller asks for an address below 4 GiB + std::uint32_t reserved; // 30 bits, must be zero }; Fields decode(std::uint64_t attributes) noexcept; diff --git a/src/frozen_compute_requests.h b/src/frozen_compute_requests.h new file mode 100644 index 0000000000..c938e2c517 --- /dev/null +++ b/src/frozen_compute_requests.h @@ -0,0 +1,74 @@ +#pragma once + +#include "shader_compute_request.h" +#include <list> +#include <mutex> +#include <optional> +#include <unordered_map> + +namespace x2w { +// Slot 67 publishes requests before their first dispatch. Keep recent captures +// until dispatch takes ownership; eviction leaves the normal file replay intact. +class FrozenComputeRequests { + const size_t max_bytes_, max_entries_; + size_t bytes_{}; + std::mutex lock_; + std::list<ComputeRequest> requests_; + std::unordered_map<uint64_t, decltype(requests_)::iterator> index_; + uint64_t hits_{}, misses_{}, evicted_{}; + + static size_t size(const ComputeRequest &r) { + return r.code.capacity() + r.data.capacity() + r.root.capacity() + + r.description.capacity() + r.sa.capacity() + r.sb.capacity(); + } + +public: + struct Stats { uint64_t hits, misses, evicted; size_t bytes, entries; }; + FrozenComputeRequests(size_t max_bytes = 32u << 20, size_t max_entries = 4096) + : max_bytes_(max_bytes), max_entries_(max_entries) {} + bool enabled() const { return max_entries_ && max_bytes_; } + Stats stats() { + std::lock_guard guard(lock_); + return {hits_, misses_, evicted_, bytes_, requests_.size()}; + } + + void put(ComputeRequest request) { + const auto bytes = size(request); + if (!max_entries_ || bytes > max_bytes_) return; + std::lock_guard guard(lock_); + if (index_.count(request.key)) return; + while (requests_.size() >= max_entries_ || bytes_ > max_bytes_ - bytes) { + const auto &old = requests_.front(); + bytes_ -= size(old); + index_.erase(old.key); + requests_.pop_front(); + ++evicted_; + } + requests_.push_back(std::move(request)); + auto node = std::prev(requests_.end()); + try { + index_.emplace(node->key, node); + } catch (...) { + requests_.pop_back(); + throw; + } + bytes_ += bytes; + } + + std::optional<ComputeRequest> take(uint64_t key) { + std::lock_guard guard(lock_); + const auto found = index_.find(key); + if (found == index_.end()) { + ++misses_; + return {}; + } + ++hits_; + const auto node = found->second; + bytes_ -= size(*node); + auto request = std::move(*node); + requests_.erase(node); + index_.erase(found); + return request; + } +}; +} diff --git a/src/gfx1013_compute_alu.inl b/src/gfx1013_compute_alu.inl new file mode 100644 index 0000000000..926bf006f2 --- /dev/null +++ b/src/gfx1013_compute_alu.inl @@ -0,0 +1,54 @@ +// One native lowering rule per supported register ALU operation. +static const std::map<Name,AluRule> alu_rules = { + {"v_xor_b32",{2,AluType::Bits,"{0} ^ {1}"}}, + {"v_add_f32",{2,AluType::Float,"{0} + {1}"}}, + {"v_add_lshl_u32",{3,AluType::Bits,"({0} + {1}) << ({2} & 31)"}}, + {"v_add_nc_u32",{2,AluType::Bits,"{0} + {1}"}}, + {"v_and_b32",{2,AluType::Bits,"{0} & {1}"}}, + {"v_and_or_b32",{3,AluType::Bits,"({0} & {1}) | {2}"}}, + {"v_ashrrev_i32",{2,AluType::Bits,"uint(int({1}) >> ({0} & 31))"}}, + {"v_bfe_u32",{3,AluType::Bits,"({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)"}}, + {"v_bfi_b32",{3,AluType::Bits,"({0} & {1}) | (~{0} & {2})"}}, + {"v_cvt_f32_i32",{1,AluType::ToFloat,"float(int({0}))"}}, + {"v_cvt_f32_u32",{1,AluType::ToFloat,"float({0})"}}, + {"v_cvt_f32_ubyte0",{1,AluType::ToFloat,"float({0} & 255)"}}, + {"v_cvt_i32_f32",{1,AluType::Bits,"uint(int(asfloat({0})))"}}, + {"v_exp_f32",{1,AluType::Float,"exp2({0})"}}, + {"v_rndne_f32",{1,AluType::Float,"round({0})"}}, + {"v_rsq_f32",{1,AluType::Float,"rsqrt({0})"}}, + {"v_cvt_u32_f32",{1,AluType::Bits,"(!(asfloat({0})>0.0f)?0u:(asfloat({0})>=4294967296.0f?0xffffffffu:uint(asfloat({0}))))"}}, + {"v_mul_hi_u32",{2,AluType::Bits,"uint((uint64_t({0})*uint64_t({1}))>>32)"}}, + {"v_min_u32",{2,AluType::Bits,"min({0},{1})"}}, + {"v_max_u32",{2,AluType::Bits,"max({0},{1})"}}, + {"v_floor_f32",{1,AluType::Float,"floor({0})"}}, + {"v_fma_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_fmaak_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_fmac_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_fmamk_f32",{3,AluType::Float,"mad({0},{1},{2})"}}, + {"v_log_f32",{1,AluType::Float,"log2({0})"}}, + {"v_lshl_add_u32",{3,AluType::Bits,"({0} << ({1} & 31)) + {2}"}}, + {"v_lshl_or_b32",{3,AluType::Bits,"({0} << ({1} & 31)) | {2}"}}, + {"v_lshlrev_b32",{2,AluType::Bits,"{1} << ({0} & 31)"}}, + {"v_lshrrev_b32",{2,AluType::Bits,"{1} >> ({0} & 31)"}}, + {"v_max3_f32",{3,AluType::Float,"max({0}, max({1}, {2}))"}}, + {"v_max_f32",{2,AluType::Float,"max({0}, {1})"}}, + {"v_mbcnt_hi_u32_b32",{2,AluType::Bits,"{1}"}}, + {"v_mbcnt_lo_u32_b32",{2,AluType::Bits,"({1}+countbits({0}&(laneBit-1u)))"}}, + {"v_med3_f32",{3,AluType::Float,"med3({0}, {1}, {2})"}}, + {"v_med3_i32",{3,AluType::Bits,"uint(max(min(int({0}), int({1})), min(max(int({0}), int({1})), int({2}))))"}}, + {"v_min3_f32",{3,AluType::Float,"min({0}, min({1}, {2}))"}}, + {"v_min_f32",{2,AluType::Float,"min({0}, {1})"}}, + {"v_mov_b32",{1,AluType::Bits,"{0}"}}, + {"v_mul_f32",{2,AluType::Float,"{0} * {1}"}}, + {"v_mul_hi_i32",{2,AluType::Bits,"uint((int64_t(asint({0}))*int64_t(asint({1})))>>32)"}}, + {"v_mul_lo_u32",{2,AluType::Bits,"{0} * {1}"}}, + {"v_mul_u32_u24",{2,AluType::Bits,"({0} & 0xffffffu) * ({1} & 0xffffffu)"}}, + {"v_or_b32",{2,AluType::Bits,"{0} | {1}"}}, + {"v_rcp_f32",{1,AluType::Float,"1.0 / {0}"}}, + {"v_rcp_iflag_f32",{1,AluType::Float,"1.0 / {0}"}}, + {"v_sin_f32",{1,AluType::Float,"sin({0} * 6.283185307)"}}, + {"v_sqrt_f32",{1,AluType::Float,"sqrt({0})"}}, + {"v_sub_f32",{2,AluType::Float,"{0} - {1}"}}, + {"v_sub_nc_u32",{2,AluType::Bits,"{0} - {1}"}}, + {"v_subrev_f32",{2,AluType::Float,"{1} - {0}"}}, +}; diff --git a/src/gfx1013_compute_clear.cpp b/src/gfx1013_compute_clear.cpp new file mode 100644 index 0000000000..3783079fa3 --- /dev/null +++ b/src/gfx1013_compute_clear.cpp @@ -0,0 +1,118 @@ +#include "gfx1013_compute_clear.h" +#include "shader_compute_request.h" +#include <windows.h> +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <array> +#include <charconv> +#include <cstring> +#include <fstream> +#include <stdexcept> +#include <tuple> + +namespace fs = std::filesystem; +namespace { +using Bytes = std::string; +template<class T> T read(const Bytes& data,size_t offset) { + if(offset>data.size() || sizeof(T)>data.size()-offset) throw std::runtime_error("truncated compute request"); + T value; + std::memcpy(&value,data.data()+offset,sizeof(value)); + return value; +} +enum class Kind { unknown, zero, table, descriptor, tg_size, wave_base, low_count, bin }; +struct Value { + Kind kind{}; + unsigned parameter{},offset{}; +}; +} + +x2w::ComputeClear x2w::replay_group_clear(const fs::path& marker,unsigned entry_offset) { + const auto request=read_compute_request(marker); + const auto& code=request.code; + const auto& root=request.root; + const auto& sa=request.sa; + if(entry_offset%4) throw std::runtime_error("unaligned entry offset"); + const unsigned xy=read<uint32_t>(sa,12),x=xy&65535,y=xy>>16,z=read<uint32_t>(sa,16)&65535; + if(!x || !y || !z || uint64_t(x)*y*z!=256 || read<uint32_t>(sa,24)!=((6u<<1)|(1u<<10))) + throw std::runtime_error("unsupported group-clear entry layout"); + Microsoft::WRL::ComPtr<ID3D12VersionedRootSignatureDeserializer> signature; + if(FAILED(D3D12CreateVersionedRootSignatureDeserializer(root.data(),root.size(),IID_PPV_ARGS(&signature)))) + throw std::runtime_error("invalid compute root signature"); + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* layout=nullptr; + if(FAILED(signature->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1,&layout)) || + layout->Desc_1_1.NumParameters!=2) throw std::runtime_error("expected two descriptor tables"); + std::array<Value,128> scalar{}; + std::array<Value,256> vector{}; + // A descriptor occupies four SGPRs. Updating any component makes the old base unusable. + auto write_scalar=[&](unsigned reg,Value value) { + auto& base=scalar[reg & ~3u]; + if(base.kind==Kind::descriptor) base={}; + scalar[reg]=value; + }; + for(unsigned i=0;i<2;++i) { + if(layout->Desc_1_1.pParameters[i].ParameterType!=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + throw std::runtime_error("compute parameter is not a descriptor table"); + scalar[4+i]={Kind::table,i}; + } + scalar[6]={Kind::tg_size}; + unsigned pc=entry_offset; + auto word=[&](){ auto v=read<uint32_t>(code,pc);pc+=4;return v; }; + ComputeClear result; + std::vector<Value> stores; + for(;;) { + unsigned at=pc; + uint32_t op=word(); + auto require=[&](bool ok){if(!ok) throw std::runtime_error("unsupported group-clear operand or instruction at byte "+std::to_string(at));}; + if(op==0xbf810000) break; + if((op>>16)==0xbfa0 || (op>>16)==0xbfa1 || op==0xbf8cc07f) continue; // prefetch, clause, wait for scalar loads + if((op&0xff80ff00)==0xbe800300) { + unsigned source=op&255; + require(((op>>16)&127)<102 && (source==128 || source<102)); + require(source==128 || (scalar[source].kind!=Kind::descriptor && scalar[source].kind!=Kind::unknown)); + write_scalar((op>>16)&127,source==128?Value{Kind::zero}:scalar[source]); + } else if((op&~0x1fffu)==0xf4080000) { // s_load_dwordx4 + unsigned base=(op&63)*2,dst=(op>>6)&127; + auto imm=word(); + require((imm&0xfff00000)==0xfa000000 && dst+3<102 && !(dst%4) && scalar[base].kind==Kind::table && scalar[base+1].kind==Kind::zero); + auto table=scalar[base]; + std::fill_n(scalar.begin()+dst,4,Value{}); + scalar[dst]={Kind::descriptor,table.parameter,imm&0xfffff}; + } else if((op&0xff80ff00)==0x8700ff00) { // s_and_b32 with literal wave-base mask + require(((op>>16)&127)<102 && (op&255)<102 && scalar[op&255].kind==Kind::tg_size && word()==0xfc0); + write_scalar((op>>16)&127,{Kind::wave_base}); + } else if((op&0xffffff00)==0xd7000000) { + unsigned dst=op&255; + require(dst<255 && word()==0x10080); // v_lshrrev_b64 with zero shift and zero source + vector[dst]=vector[dst+1]={Kind::zero}; + } else if((op>>8)==0xd76500 || (op>>8)==0xd76600) { + auto operands=word(); + require((operands&0xfffc01ff)==193); + unsigned source=(operands>>9)&511; + bool low=(op>>8)==0xd76500; + require(low ? source<128 && scalar[source].kind==Kind::wave_base : + source>=256 && vector[source-256].kind==Kind::low_count); + vector[op&255]={low?Kind::low_count:Kind::bin}; + } else if(op==0xe2102000) { // buffer_store_format_d16_x, idxen only, offset zero + auto args=word(); + require((args&0xffe00000)==0x80000000); + auto resource=scalar[((args>>16)&31)*4]; + require(vector[args&255].kind==Kind::bin && vector[(args>>8)&255].kind==Kind::zero && + resource.kind==Kind::descriptor && !(resource.offset%32)); + stores.push_back(resource); + } else require(false); + } + if(stores.empty()) throw std::runtime_error("compute program has no clears"); + std::sort(stores.begin(),stores.end(),[](Value a,Value b){return std::tie(a.parameter,a.offset)<std::tie(b.parameter,b.offset);}); + for(auto value:stores) { + if(!result.bindings.empty() && value.parameter==result.bindings.back().parameter && value.offset==result.bindings.back().byte_offset) continue; + unsigned reg=static_cast<unsigned>(result.bindings.size()); + result.bindings.push_back({value.parameter,value.offset}); + auto id=std::to_string(reg); + result.hlsl+="RWBuffer<uint> out"+id+" : register(u"+id+");\n"; + } + result.hlsl+="[numthreads("+std::to_string(x)+","+std::to_string(y)+","+std::to_string(z)+")]\nvoid main(uint bin:SV_GroupIndex){\n"; + for(unsigned reg=0;reg<result.bindings.size();++reg) result.hlsl+="out"+std::to_string(reg)+"[bin]=0;\n"; + result.hlsl+="}\n"; + return result; +} diff --git a/src/gfx1013_compute_clear.h b/src/gfx1013_compute_clear.h new file mode 100644 index 0000000000..f349cf2514 --- /dev/null +++ b/src/gfx1013_compute_clear.h @@ -0,0 +1,18 @@ +#pragma once +#include <cstdint> +#include <filesystem> +#include <string> +#include <vector> + +namespace x2w { +struct ClearBinding { + unsigned parameter; + unsigned byte_offset; +}; +struct ComputeClear { + std::string hlsl; + // Entry i must bind the guest's 256-element R32_UINT UAV to register ui. + std::vector<ClearBinding> bindings; +}; +ComputeClear replay_group_clear(const std::filesystem::path& marker, unsigned entry_offset); +} diff --git a/src/gfx1013_compute_ir.cpp b/src/gfx1013_compute_ir.cpp new file mode 100644 index 0000000000..8edda418d0 --- /dev/null +++ b/src/gfx1013_compute_ir.cpp @@ -0,0 +1,168 @@ +#include "gfx1013_compute_ir.h" +#include "gfx1013_compute_native.h" +#include <charconv> +#include <cstdint> +#include <optional> +#include <stdexcept> +#include <string_view> + +namespace x2w { +LocalDataAccess decode_local_data(uint32_t instruction, uint32_t operands) { + if ((instruction & 0xfc030000u) != 0xd8000000u) + throw std::runtime_error("expected a local DS instruction with GDS clear"); + const unsigned op = (instruction >> 18) & 255, offset = instruction & 65535; + const unsigned addr = operands & 255, data0 = (operands >> 8) & 255, data1 = (operands >> 16) & 255, + dst = operands >> 24; + LocalDataAccess access{offset, addr, data0, data1, dst, 1}; + // The DS opcode/tuple layout follows Victory 9376fd6 gfx10/{opcodes,fields}.rs. + // The 32-bit read-modify-write operations follow compute_store_aot.py LDS_RMW. + switch (op) { + case 0x00: case 0x20: case 0x01: case 0x21: + access.atomic_ir = "add"; access.atomic_hlsl = "Add"; access.subtract = (op & 1) != 0; + break; + case 0x07: case 0x27: access.atomic_ir = "umin"; access.atomic_hlsl = "Min"; break; + case 0x08: case 0x28: access.atomic_ir = "umax"; access.atomic_hlsl = "Max"; break; + case 0x09: case 0x29: access.atomic_ir = "and"; access.atomic_hlsl = "And"; break; + case 0x0a: case 0x2a: access.atomic_ir = "or"; access.atomic_hlsl = "Or"; break; + case 0x0b: case 0x2b: access.atomic_ir = "xor"; access.atomic_hlsl = "Xor"; break; + case 0x2d: access.atomic_ir = "xchg"; access.atomic_hlsl = "Exchange"; break; + case 0x30: access.compare_exchange = true; break; + case 0x36: access.read = true; break; // read_b32 + case 0x76: access.read = true; access.count = 2; break; + case 0xfe: access.read = true; access.count = 3; break; + case 0xff: access.read = true; access.count = 4; break; + case 0x0d: break; // write_b32 + case 0x4d: access.count = 2; break; + case 0xde: access.count = 3; break; + case 0xdf: access.count = 4; break; + case 0x0e: case 0x0f: case 0x37: case 0x38: + case 0x4e: case 0x4f: case 0x77: case 0x78: + access.pair_words = op >= 0x40 ? 2 : 1; + access.count = 2 * access.pair_words; + access.read = (op & 0x3f) >= 0x37; + access.stride64 = (op & 0x3f) == 0x0f || (op & 0x3f) == 0x38; + break; + default: + throw UnsupportedComputeShader("unsupported local DS opcode " + std::to_string(op)); + } + access.return_old = access.compare_exchange || (access.atomic_ir && op >= 0x20); + const unsigned first_width = access.pair_words ? access.pair_words : access.count; + if (access.read ? data0 || data1 || dst + access.count > 256 : + (!access.return_old && dst) || (!access.compare_exchange && !access.pair_words && data1) || + data0 + first_width > 256 || data1 + access.pair_words > 256) + throw std::runtime_error("invalid local DS register tuple"); + return access; +} + +static std::string lower_lds(uint32_t instruction, uint32_t operands) { + const auto access = decode_local_data(instruction, operands); + // Preserve the input address when a read writes back to the address VGPR. + std::string out = "if (exec & 1u) { uint ds_addr = v" + std::to_string(access.address) + "; "; + for (unsigned i = 0; i < access.count; ++i) { + auto location = "lds[(ds_addr + " + std::to_string(access.byte_offset(i)) + "u) >> 2]"; + auto reg = "v" + std::to_string(access.read ? access.destination + i : access.data_register(i)); + if (access.compare_exchange) { + out += "InterlockedCompareExchange(" + location + ", " + reg + ", v" + std::to_string(access.data1) + + ", v" + std::to_string(access.destination) + "); "; + } else if (access.atomic_ir) { + auto value = access.subtract ? "(0u - " + reg + ")" : reg; + out += std::string("Interlocked") + access.atomic_hlsl + "(" + location + ", " + value; + if (access.return_old) + out += ", v" + std::to_string(access.destination); + out += "); "; + } else + out += access.read ? reg + " = " + location + "; " : location + " = " + reg + "; "; + } + return out + "}"; +} + +// Single-word VOP2 with an optional 32-bit literal. SGPR and lane-special +// operands require provenance from the entry layout and stay in the frontend. +static std::string lower_vop2(uint32_t word, std::optional<uint32_t> literal) { + const auto src0 = word & 511u; + if ((word >> 31) || (src0 == 255) != literal.has_value()) + throw std::runtime_error("invalid VOP2 word or literal length"); + std::string a; + if (src0 >= 256) + a = "v" + std::to_string(src0 - 256); + else if (literal) + a = std::to_string(*literal) + "u"; + else if (src0 >= 128 && src0 <= 192) + a = std::to_string(src0 - 128) + "u"; + else if (src0 >= 193 && src0 <= 208) + a = std::to_string(192u - src0) + "u"; + else + throw std::runtime_error("unsupported VOP2 source"); + const std::string b = "v" + std::to_string((word >> 9) & 255); + const std::string dst = "v" + std::to_string((word >> 17) & 255); + std::string expr; + switch (word >> 25) { + case 3: + expr = "asuint(asfloat(" + a + ") + asfloat(" + b + "))"; + break; + case 4: + expr = "asuint(asfloat(" + a + ") - asfloat(" + b + "))"; + break; + case 5: + expr = "asuint(asfloat(" + b + ") - asfloat(" + a + "))"; + break; + case 8: + expr = "asuint(asfloat(" + a + ") * asfloat(" + b + "))"; + break; + case 11: + expr = "(" + a + " & 0xffffffu) * (" + b + " & 0xffffffu)"; + break; + case 26: + expr = b + " << (" + a + " & 31u)"; + break; + case 37: + expr = a + " + " + b; + break; + default: + throw std::runtime_error("unsupported VOP2 opcode"); + } + return "if (exec & 1u) " + dst + " = " + expr + ";"; +} + +std::string expand_gfx1013_compute(const std::string &source) { + constexpr std::string_view lds = "#pragma x2w_lds ", alu = "#pragma x2w_vop2 "; + std::string output; + size_t pos = 0; + while (pos < source.size()) { + auto end = source.find('\n', pos); + if (end == source.npos) + end = source.size(); + std::string_view line(source.data() + pos, end - pos); + auto first = line.find_first_not_of(" \t"); + const auto trimmed = first == line.npos ? std::string_view{} : line.substr(first); + const bool ds = trimmed.substr(0, lds.size()) == lds; + if (ds || trimmed.substr(0, alu.size()) == alu) { + auto args = trimmed.substr(ds ? lds.size() : alu.size()); + if (!args.empty() && args.back() == '\r') + args.remove_suffix(1); + if ((args.size() != 17 || args[8] != ' ') && (ds || args.size() != 8)) + throw std::runtime_error("invalid native compute instruction length"); + auto parse = [](std::string_view token) { + uint32_t word{}; + auto r = std::from_chars(token.data(), token.data() + token.size(), word, 16); + if (r.ec != std::errc{} || r.ptr != token.data() + token.size()) + throw std::runtime_error("invalid compute word"); + return word; + }; + auto instruction = parse(args.substr(0, 8)); + std::optional<uint32_t> second; + if (args.size() == 17) + second = parse(args.substr(9)); + output += ds ? lower_lds(instruction, *second) : lower_vop2(instruction, second); + } else { + if (trimmed.substr(0, 12) == "#pragma x2w_") + throw std::runtime_error("unknown native compute pragma"); + output.append(line); + } + if (end < source.size()) + output += '\n'; + pos = end + 1; + } + return output; +} +} // namespace x2w diff --git a/src/gfx1013_compute_ir.h b/src/gfx1013_compute_ir.h new file mode 100644 index 0000000000..d141faa943 --- /dev/null +++ b/src/gfx1013_compute_ir.h @@ -0,0 +1,26 @@ +#pragma once +#include <cstdint> +#include <string> + +namespace x2w { +struct LocalDataAccess { + unsigned offset, address, data0, data1, destination, count; + unsigned pair_words; // Width of each independently offset element; zero for a single address. + bool read, stride64, return_old; + const char *atomic_ir, *atomic_hlsl; + bool subtract, compare_exchange; + unsigned byte_offset(unsigned element) const { + if (!pair_words) return offset + 4 * element; + unsigned encoded = (offset >> (8 * (element / pair_words))) & 255; + return 4 * (encoded * pair_words * (stride64 ? 64 : 1) + element % pair_words); + } + unsigned data_register(unsigned element) const { + return pair_words && element >= pair_words ? data1 + element - pair_words : data0 + element; + } +}; +LocalDataAccess decode_local_data(uint32_t instruction, uint32_t operands); + +// Expand compute instruction words in the register-based HLSL frontend. +// Bit zero of exec is the current lane's EXEC bit. lds is groupshared uint[]. +std::string expand_gfx1013_compute(const std::string &source); +} // namespace x2w diff --git a/src/gfx1013_compute_mtbuf.inl b/src/gfx1013_compute_mtbuf.inl new file mode 100644 index 0000000000..96b94552a4 --- /dev/null +++ b/src/gfx1013_compute_mtbuf.inl @@ -0,0 +1,126 @@ +// MTBUF uses the instruction's explicit format and the descriptor's byte range. +// Format numbers follow tools/disasm_rdna2.py MTBUF_FORMATS. Conversion and +// unaligned addressing follow gfx2hlsl.tbuffer / ldu, cross-checked against +// Victory 9376fd6 format_load. Only the runtime-checked identity raw SRV is used. +enum class ChannelNumber { unorm, snorm, uscaled, sscaled, uint_, sint, float_ }; +struct MtbufFamily { + unsigned first, last, bits, components; + ChannelNumber first_number; +}; +string normalized_channel(const string &field, unsigned width, bool snorm) { + // p/(2^k-1) has binary expansion 0.ppp... (p padded to k bits). + // Rotate the first set bit to the top, repeat at least 25 bits, then + // round a 24-bit significand. A nonzero repeating tail is never a tie. + const unsigned k = width - unsigned(snorm); + const auto max = to_string((1u << k) - 1); + string p = field, sign = "0"; + if (snorm) { + sign = ir.binary("and", field, "2147483648"); + p = select(cmp("slt", field, "0"), ir.binary("sub", "0", field), field); + p = select(cmp("ugt", p, max), max, p); + } + // p has at most 16 bits; converting it to binary32 is exact. + auto exp = ir.binary("lshr", ir.value("bitcast float " + ir.value("uitofp i32 " + p + " to float") + " to i32"), "23"); + auto distance = ir.binary("and", ir.binary("sub", to_string(126 + k), exp), "31"); + auto right = ir.binary("and", ir.binary("sub", to_string(k), distance), "31"); + auto period = ir.binary("and", ir.binary("or", ir.binary("shl", p, distance), ir.binary("lshr", p, right)), max); + unsigned periods = (25 + k - 1) / k, precision = periods * k; + unsigned repeats = 0; + for (unsigned i = 0; i < periods; ++i) + repeats |= 1u << (i * k); + auto digits = ir.binary("mul", period, to_string(repeats)); + auto rounded = ir.binary("add", ir.binary("lshr", digits, to_string(precision - 24)), + ir.binary("and", ir.binary("lshr", digits, to_string(precision - 25)), "1")); + auto base = ir.binary("shl", ir.binary("sub", exp, to_string(k + 1)), "23"); + auto magnitude = select(cmp("eq", p, "0"), "0", ir.binary("add", base, rounded)); + return snorm ? ir.binary("or", magnitude, sign) : magnitude; +} +void formatted_byte_load(const Inst &i, const State &s, const string &byte_window = {}) { + constexpr MtbufFamily families[] = { + {1, 6, 8, 1, ChannelNumber::unorm}, {7, 13, 16, 1, ChannelNumber::unorm}, + {14, 19, 8, 2, ChannelNumber::unorm}, {20, 22, 32, 1, ChannelNumber::uint_}, + {23, 29, 16, 2, ChannelNumber::unorm}, {44, 49, 0, 4, ChannelNumber::unorm}, + {50, 55, 0, 4, ChannelNumber::unorm}, {56, 61, 8, 4, ChannelNumber::unorm}, + {62, 64, 32, 2, ChannelNumber::uint_}, {65, 71, 16, 4, ChannelNumber::unorm}, + {72, 74, 32, 3, ChannelNumber::uint_}, {75, 77, 32, 4, ChannelNumber::uint_} + }; + const unsigned format = (i.a >> 19) & 127, count = i.op + 1; + const auto family = std::find_if(std::begin(families), std::end(families), [&](const auto &f) { + return format >= f.first && format <= f.last; + }); + if (family == std::end(families) || count > family->components) + refuse(i.pc, "unsupported MTBUF format or absent component"); + if (i.dst + count > 256) + refuse(i.pc, "MTBUF destination tuple overflow"); + const auto component_width=[&](unsigned j) { + // The name lists the most significant field first; logical X is + // the low field. See Victory lower.rs format_layout. + return family->bits ? family->bits : j==(family->first==44 ? 0u : 3u) ? 2u : 10u; + }; + unsigned requested_bits=0; + for (unsigned j=0;j<count;++j) requested_bits+=component_width(j); + const auto numeric = static_cast<ChannelNumber>(unsigned(family->first_number) + format - family->first); + const auto handle = byte_window.empty() ? resource(i, s, (i.b >> 16 & 31) * 4, ComputeViewKind::raw_vector_srv, 4) : byte_window; + const unsigned scalar_offset = i.b >> 24; + auto addr = to_string(i.a & 4095); + if (scalar_offset != 125 && scalar_offset != 128) + addr = ir.binary("add", addr, operand32(i, scalar_offset)); + if (i.a & 0x1000) + addr = ir.binary("add", addr, read(256 + (i.b & 255))); + // RDNA2 checks the whole formatted element. Desktop raw loads by + // themselves can return some in-range components from a truncated element. + auto dimensions = ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", handle}, {"i32", "undef"}}, "nounwind readonly"); + auto bytes = ir.value("extractvalue %dx.types.Dimensions " + dimensions + ", 0"); + auto size = to_string(family->bits ? family->bits * family->components / 8 : 4u); + auto valid = ir.value("and i1 " + cmp("uge", bytes, size) + ", " + + cmp("ule", addr, ir.binary("sub", bytes, size))); + const auto aligned = ir.binary("and", addr, "4294967292"); + const auto shift_bits = ir.binary("shl", ir.binary("and", addr, "3"), "3"); + const unsigned word_count = (requested_bits + 31) / 32; + const auto chunk = load_buffer(handle, aligned, true, word_count); + std::array<string, 5> words; + for (unsigned j = 0; j < word_count; ++j) + words[j] = ir.value("extractvalue %dx.types.ResRet.i32 " + chunk + ", " + to_string(j)); + if (requested_bits > 8) { + const auto next = ir.binary("add", aligned, to_string(word_count * 4)); + const auto high = load_buffer(handle, next, true, 1); + words[word_count] = select(cmp("ult", next, aligned), "0", + ir.value("extractvalue %dx.types.ResRet.i32 " + high + ", 0")); + } + // Snapshot all address-derived values before writing destinations: OFFEN's + // VGPR can be any member of the output tuple. + const auto aligned_access = cmp("eq", shift_bits, "0"); + const auto inverse = ir.binary("and", ir.binary("sub", "0", shift_bits), "31"); + for (unsigned j = 0; j < word_count; ++j) { + const auto low = ir.binary("lshr", words[j], shift_bits); + words[j] = words[j + 1].empty() ? low : + ir.binary("or", low, select(aligned_access, "0", ir.binary("shl", words[j + 1], inverse))); + } + unsigned bit_offset=0; + for (unsigned j = 0; j < count; ++j) { + const auto width=component_width(j); + auto field = words[bit_offset / 32]; + if (width < 32) { + field = ir.binary("lshr", field, to_string(bit_offset % 32)); + field = ir.binary("and", field, to_string((1u << width) - 1)); + } + bit_offset+=width; + const bool signed_field = numeric == ChannelNumber::sint || numeric == ChannelNumber::snorm || + numeric == ChannelNumber::sscaled; + if (signed_field && width < 32) { + auto distance = to_string(32 - width); + field = ir.binary("ashr", ir.binary("shl", field, distance), distance); + } + if (numeric == ChannelNumber::float_ && width == 16) { + auto f = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", field}}, "nounwind readnone"); + field = ir.value("bitcast float " + f + " to i32"); + } else if (numeric == ChannelNumber::unorm || numeric == ChannelNumber::snorm) { + field = normalized_channel(field, width, signed_field); + } else if (numeric == ChannelNumber::uscaled || numeric == ChannelNumber::sscaled) { + auto f = ir.value(string(signed_field ? "sitofp" : "uitofp") + " i32 " + field + " to float"); + field = ir.value("bitcast float " + f + " to i32"); + } + vector_write(256 + i.dst + j, select(valid, field, "0")); + } +} diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp new file mode 100644 index 0000000000..5e5c51d230 --- /dev/null +++ b/src/gfx1013_compute_native.cpp @@ -0,0 +1,2281 @@ +#include "gfx1013_compute_native.h" +#include "gfx1013_compute_ir.h" +#include "dxil_module.h" +#include "guest_shader_container.h" +#include "gfx1013_isa.h" +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <array> +#include <cstring> +#include <deque> +#include <iomanip> +#include <functional> +#include <map> +#include <optional> +#include <set> +#include <sstream> +#include <stdexcept> +#include <string_view> + +namespace { +using namespace x2w; +using std::string; +using std::to_string; +using Word = uint32_t; +using Name = std::string_view; + +static bool binary16_alu(std::string_view name) { + return name == "v_add_f16" || name == "v_sub_f16" || name == "v_subrev_f16" || name == "v_mul_f16"; +} + +static bool binary16_unary(std::string_view name) { + return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" || + name == "v_rsq_f16"; +} + +[[noreturn]] void refuse(unsigned pc, const string &reason) { + std::ostringstream out; + out << "native compute +0x" << std::hex << pc << ": " << reason; + throw UnsupportedComputeShader(out.str()); +} +Word word(const string &bytes, unsigned at) { + if (at > bytes.size() || bytes.size() - at < 4) + refuse(at, "truncated word"); + Word n; + std::memcpy(&n, bytes.data() + at, 4); + return n; +} +string hexword(Word n) { + char s[12]; + snprintf(s, sizeof(s), "0x%08xu", n); + return s; +} +enum class Encoding { Sopp, Sop1, Sop2, Sopc, Sopk, Vop1, Vop2, Vopc, QuadCompare, Vop3, Mix, Smem, Image, Mubuf, Lds, Export, Interp, Fetch, FixedSetup, FixedFetch }; +#include "gfx1013_compute_opcodes.inl" +struct Inst { + unsigned pc = 0, next = 0, op = 0, dst = 0; + Encoding enc{}; + Word a = 0, b = 0, literal = 0; + std::array<Word, 3> image_address_words{}; + std::array<unsigned, 3> src{}; + Name name; + unsigned abs = 0, neg = 0, scale = 0; + bool clamp = false, wide = false, subword = false; + // 0..255 selects within a quad. Row operations and mirrors cross quads. + std::optional<unsigned> dpp_control; + unsigned dpp_row_mask = 15, dpp_bank_mask = 15; + std::optional<Word> dpp8_selectors; + bool dpp_fetch_inactive = false; + bool dpp_bound_zero = false; + unsigned mirror_mask() const { return dpp_control == 0x141 ? 7 : dpp_control == 0x140 ? 15 : 0; } + enum class DppRowOp { None, Shl, Shr, Ror }; + struct DppRow { + DppRowOp op; + unsigned amount; + }; + DppRow dpp_row() const { + const unsigned control = dpp_control.value_or(0); + const unsigned amount = control & 15; + if (amount) { + switch (control & ~15u) { + case 0x100: return {DppRowOp::Shl, amount}; + case 0x110: return {DppRowOp::Shr, amount}; + case 0x120: return {DppRowOp::Ror, amount}; + } + } + return {DppRowOp::None, 0}; + } + std::array<unsigned, 2> src_select{6, 6}; + std::array<bool, 2> src_sext{}; + unsigned dst_select = 6, dst_unused = 0; + bool branch() const { + return enc == Encoding::Sopp && (op == 2 || op == 4 || op == 5 || op == 6 || op == 7 || op == 8 || op == 9); + } + unsigned target() const { return next + 4 * static_cast<int16_t>(a & 65535); } +}; +unsigned memory_count(const Inst &i) { return 1u << (i.op & 7); } +// Direct compute stores both VCC words in scalar registers. +unsigned smem_sgpr_limit(bool direct_compute) { return direct_compute ? 108 : 106; } + +Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=false, bool wave64=false) { + const auto encoded=gfx1013::instruction(bytes,pc); + Inst i; + i.pc = pc; + i.next = pc; + auto take = [&]() { + auto n = word(bytes, i.next); + i.next += 4; + return n; + }; + Word a = i.a = take(); + if (graphics && (encoded.form == gfx1013::Form::exp || encoded.form == gfx1013::Form::vintrp || + a == 0xbe842104)) { + if (encoded.form == gfx1013::Form::exp) { + i.enc = Encoding::Export; + i.b = take(); + } else i.enc = encoded.form == gfx1013::Form::vintrp ? Encoding::Interp : Encoding::Fetch; + i.name = encoded.name; + return i; + } + auto form = a & 0xff800000u; + bool lit = false; + if (form == 0xbf800000) { + i.enc = Encoding::Sopp; + i.op = (a >> 16) & 127; + } else if (form == 0xbe800000) { + i.enc = Encoding::Sop1; + i.op = (a >> 8) & 255; + i.dst = (a >> 16) & 127; + i.src[0] = a & 255; + lit = i.src[0] == 255; + } else if (form == 0xbf000000) { + i.enc = Encoding::Sopc; + i.op = (a >> 16) & 127; + i.src = {a & 255, (a >> 8) & 255, 0}; + lit = i.src[0] == 255 || i.src[1] == 255; + } else if ((a >> 28) == 11) { + i.enc = Encoding::Sopk; + i.op = (a >> 23) & 31; + i.dst = (a >> 16) & 127; + // s_setreg_imm32_b32 carries the written value in a literal word. + lit = i.op == 0x15; + } else if ((a >> 30) == 2) { + i.enc = Encoding::Sop2; + i.op = (a >> 23) & 127; + i.dst = (a >> 16) & 127; + i.src = {a & 255, (a >> 8) & 255, 0}; + lit = i.src[0] == 255 || i.src[1] == 255; + } else if ((a >> 31) == 0) { + auto k = a >> 25; + i.dst = 256 + ((a >> 17) & 255); + i.src = {a & 511, 256 + ((a >> 9) & 255), 106}; + if (k == 63) { + i.enc = Encoding::Vop1; + i.op = (a >> 9) & 255; + } else if (k == 62) { + i.enc = Encoding::Vopc; + i.op = (a >> 17) & 255; + i.dst = 106; + } else { + i.enc = Encoding::Vop2; + i.op = k; + } + lit = i.src[0] == 255 || + (i.enc == Encoding::Vop2 && (k == 0x20 || k == 0x21 || k == 0x2c || k == 0x2d || k == 0x37 || k == 0x38)); + } else if ((a & 0xfc000000u) == 0xf4000000) { + i.enc = Encoding::Smem; + i.b = take(); + i.op = (a >> 18) & 255; + i.dst = (a >> 6) & 127; + i.src[0] = (a & 63) * 2; + const unsigned soffset = i.b >> 25; + const unsigned limit = smem_sgpr_limit(direct && !graphics); + if ((i.b & 0x01f00000u) || (a & 0x14000) || (i.op & ~8u) > 4 || + (soffset != 125 && ((!direct && i.op < 8 && i.op != 2) || soffset >= limit))) + refuse(pc, "unsupported scalar memory addressing"); + if (direct && !graphics && i.dst + memory_count(i) > limit) + refuse(pc, "unsupported scalar memory destination range"); + i.name = "smem"; + } else if ((a & 0xfc000000u) == 0xf0000000) { + i.enc = Encoding::Image; + i.b = take(); + i.op = ((a >> 18) & 127) | ((a & 1) << 7); + i.dst = (i.b >> 8) & 255; + unsigned extra = (a >> 1) & 3; + if (!direct && extra > 1) + refuse(pc, "image NSA count"); + for (unsigned j = 0; j < extra; ++j) + i.image_address_words[j] = take(); + const bool sample_d16 = direct && (i.op == 32 || i.op == 34 || i.op == 36 || i.op == 37 || i.op == 39) && + ((a >> 3) & 7) != 3; + if ((!direct && ((a >> 3) & 7) != 1) || ((i.b & 0x80000000u) && !sample_d16 && + (i.op != 8 || (!direct && ((a >> 8) & 15) != 1)))) + refuse(pc, "unsupported image dimension or D16"); + i.name = "image"; + } else if ((a & 0xfc000000u) == 0xe0000000u) { + i.b = take(); + i.op = (a >> 18) & 127; + i.op |= (a >> 18) & 0x80; + if (direct && encoded.name.substr(0, 14) == "buffer_atomic_") { + // Byte offset plus optional VGPR address and GLC old-value return. + // Indexed atomics currently access the first dword of the chosen element. + if ((a & 0x00038000u) || (i.b & 0x00e00000u)) + refuse(pc, "unsupported buffer atomic addressing or cache policy"); + if ((a & 0x2000u) && (graphics || (a & 0x1fffu) || + ((i.b >> 24) != 128 && (i.b >> 24) != 125))) + refuse(pc, "indexed compute atomic requires zero byte offsets"); + i.name = encoded.name; + } else if ((i.op >= 4 && i.op <= 7) || (i.op >= 0x84 && i.op <= 0x87)) { + if ((a & 0x3ffffu) != 0x2000u || (i.b & 0xffe00000u) != 0x80000000u || i.op == 0x86) + refuse(pc, "formatted store needs an index-only linear view and supported component count"); + i.name = "buffer_store_format"; + } else if (i.op >= 0x1c && i.op <= 0x1f) { + // Direct compute ignores GLC, DLC and SLC cache-policy hints on raw stores. + const bool compute = direct && !graphics; + if ((a & (compute ? 0x32000u : 0x3e000u)) || + (i.b & (compute ? 0xa00000u : 0xe00000u))) + refuse(pc, "raw store needs a linear byte offset"); + i.name = "buffer_store_raw"; + } else if (i.op >= 0x0c && i.op <= 0x0f) { + if (direct && !graphics) { + // GLC, DLC and SLC are cache-policy hints on raw loads. + if ((a & 0x02032000u) || (i.b & 0x00a00000u)) + refuse(pc, "raw buffer load needs a linear byte offset and no modifiers"); + // The MUBUF encoding has no trailing literal word. + const unsigned soffset = i.b >> 24; + if (soffset > 105 && !(soffset >= 128 && soffset <= 208)) + refuse(pc, "raw buffer load scalar offset needs an SGPR or inline integer"); + } else if (direct && graphics && !(a & 0x2000u)) { + const unsigned soffset = i.b >> 24; + if ((a & 0x02032000u) || (i.b & 0x00a00000u) || (soffset > 105 && soffset != 128)) + refuse(pc, "raw graphics load requires linear addressing without LDS or TFE"); + } else if (!(direct && (a & 0x0203f000u) == 0x2000u && + (i.b & 0xffe00000u) == 0x80000000u) && + ((a & 0x0203f000u) != 0x1000u || (i.b & 0xffe00000u) != 0x80000000u)) { + refuse(pc, "raw buffer load needs offen with zero scalar offset and no modifiers"); + } + i.name = "buffer_load_dword"; + } else { + if (i.op > 3) + refuse(pc, "unsupported buffer operation"); + const auto addressing = a & 0x3ffffu; + if ((addressing != 0x2000u && !(direct && addressing == 0)) || + (a & 0x02000000u) || (i.b & 0xffe00000u) != 0x80000000u) + refuse(pc, "formatted load requires zero or a single linear index"); + i.name = "buffer_load_format"; + } + i.enc = Encoding::Mubuf; + i.dst = (i.b >> 8) & 255; + } else if (direct && !graphics && encoded.form == gfx1013::Form::mtbuf) { + i.b = take(); + i.op = encoded.opcode; + if (i.op > 3 || (a & 0xe000u) || (i.b & 0xe00000u)) + refuse(pc, "MTBUF requires a non-D16 load without index, cache modifiers or TFE"); + i.enc = Encoding::Mubuf; + i.name = encoded.name; + i.dst = (i.b >> 8) & 255; + } else if (direct && !graphics && (a & 0xfc000000u) == 0xdc000000u) { + // FLAT encoding, segment 2 (GLOBAL), with an SGPR-pair base: + // ADDR = SADDR + zext(VADDR) + sext(OFFSET). + // SADDR 125 is `off` on gfx10. LDS, the other segments and opcodes stay refused. + i.b = take(); + i.op = (a >> 18) & 127; + const unsigned saddr = (i.b >> 16) & 127; + if (((a >> 14) & 3) != 2 || i.op < 12 || i.op > 15 || (a & 0x2000u) || saddr == 125 || saddr == 127) + refuse(pc, "direct global memory supports only DWORD loads with a scalar address pair"); + i.enc = Encoding::Mubuf; + i.name = encoded.name; + i.dst = i.b >> 24; + } else if ((a & 0xfc000000u) == 0xd8000000) { + i.enc = Encoding::Lds; + i.b = take(); + i.name = "lds"; + } else if ((a & 0xfc000000u) == 0xd4000000 || (a & 0xff800000u) == 0xcc000000) { + i.wide = true; + i.b = take(); + i.enc = (a >> 26) == 0x35 ? Encoding::Vop3 : Encoding::Mix; + i.op = (a >> 16) & (i.enc == Encoding::Mix ? 0x7f : 0x3ff); + i.src = {i.b & 511, (i.b >> 9) & 511, (i.b >> 18) & 511}; + i.abs = (a >> 8) & 7; + i.neg = i.b >> 29; + i.scale = (i.b >> 27) & 3; + i.clamp = (a & 0x8000) != 0; + i.dst = 256 + (a & 255); + if (i.enc == Encoding::Vop3 && i.op < 256) { + i.enc = Encoding::Vopc; + i.dst = a & 255; + } else if (i.enc == Encoding::Vop3 && i.op >= 0x100 && i.op < 0x140) { + i.enc = Encoding::Vop2; + i.op -= 0x100; + } else if (i.enc == Encoding::Vop3 && i.op >= 0x180 && i.op < 0x200) { + i.enc = Encoding::Vop1; + i.op -= 0x180; + } + if (direct && !graphics && i.enc == Encoding::Vop3 && (i.op == 0x377 || i.op == 0x378)) { + // The shared extent decoder already counts the trailing literal word. + // S1 and S2 may both reference that word. + if (i.src[0] == 255) + refuse(pc, "permlane S0 cannot be a literal"); + } + lit = std::find(i.src.begin(), i.src.end(), 255) != i.src.end(); + } else + refuse(pc, "unsupported instruction " + string(encoded.name) + " " + hexword(a)); + if (!i.wide && (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vopc)) { + const bool half_alu = !graphics && ((i.enc == Encoding::Vop2 && binary16_alu(encoded.name)) || + (i.enc == Encoding::Vop1 && binary16_unary(encoded.name))); + const bool dpp8 = i.src[0] == 233 || i.src[0] == 234; + if (direct && half_alu && (dpp8 || (i.enc == Encoding::Vop1 && i.src[0] == 250))) + refuse(pc, "unsupported " + string(encoded.name) + " DPP form"); + const bool sdwa_logic = i.enc == Encoding::Vop2 && i.op == 0x1d; + const bool sdwa_class = i.enc == Encoding::Vopc && (i.op == 0x88 || (direct && i.op == 0x8f)); + const bool sdwa_compare = i.enc == Encoding::Vopc && !sdwa_class; + const unsigned sdwa_mask_limit = direct && !graphics && !wave64 ? 107 : 106; + if (direct && i.src[0] == 249 && (sdwa_compare || i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2)) { + // Operand profiles from disasm_rdna2's GFX10 VOP1/VOP2 SDWA + // decoder. Admit only profiles with a direct result placement. + static const std::set<Name> bits{ + "v_mov_b32", "v_not_b32", "v_cndmask_b32", "v_bfrev_b32", "v_mul_u32_u24", + "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_add_co_ci_u32", + "v_and_b32", "v_or_b32", "v_xor_b32", "v_xnor_b32", "v_min_u32", "v_max_u32", + "v_min_i32", "v_max_i32", "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32"}; + static const std::set<Name> floats{ + "v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32", "v_min_f32", "v_max_f32", + "v_floor_f32", "v_ceil_f32", "v_fract_f32", "v_trunc_f32", "v_rndne_f32", + "v_exp_f32", "v_log_f32", "v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32"}; + const auto name = encoded.name; + const bool fp_input = half_alu || floats.count(name) || name == "v_cvt_u32_f32" || name == "v_cvt_i32_f32" || + name == "v_cvt_f16_f32" || name == "v_cvt_f32_f16" || name == "v_cvt_pkrtz_f16_f32" || + (sdwa_compare && (name.substr(name.size()-4) == "_f32" || name.substr(name.size()-4) == "_f16")); + const bool conversion = name == "v_cvt_f32_i32" || name == "v_cvt_f32_u32" || + name.substr(0,15) == "v_cvt_f32_ubyte"; + if (!(fp_input || conversion || bits.count(name) || sdwa_compare) || + (graphics && (name == "v_cvt_pkrtz_f16_f32" || name == "v_add_co_ci_u32"))) + refuse(pc, "unimplemented direct SDWA operand profile"); + const Word ext = take(); + const unsigned sources = i.enc == Encoding::Vop1 ? 1 : 2; + if (sdwa_compare) { + if ((ext & 0x8000) && (name.substr(0,7) == "v_cmpx_" || ((ext >> 8) & 127) > sdwa_mask_limit)) + refuse(pc, "invalid SDWA compare destination"); + i.dst = ext & 0x8000 ? (ext >> 8) & 127 : 106; + } else { + i.dst_select = (ext >> 8) & 7; + i.dst_unused = (ext >> 11) & 3; + i.scale = (ext >> 14) & 3; + i.clamp = (ext & (1u << 13)) != 0; + if (half_alu && ((i.dst_select != 4 && i.dst_select != 5) || + (i.dst_unused != 0 && i.dst_unused != 2))) + refuse(pc, "unsupported SDWA destination modifier"); + const bool clamp_only = !graphics && name == "v_cvt_f32_f16"; + if (i.dst_select == 7 || i.dst_unused == 3 || + ((i.scale || (i.clamp && !clamp_only)) && !floats.count(name) && !conversion) || + (sources == 1 && (ext & 0xbf000000u))) + refuse(pc, "unsupported SDWA destination modifier"); + } + for (unsigned j = 0; j < sources; ++j) { + const unsigned control = (ext >> (16 + 8*j)) & 255; + i.src_select[j] = control & 7; + i.src_sext[j] = (control & 8) != 0; + if (half_alu && i.src_select[j] < 4) + refuse(pc, "invalid SDWA source modifier"); + if (i.src_select[j] == 7 || (control & 64) || (fp_input && i.src_sext[j]) || (!fp_input && (control & 0x30))) + refuse(pc, "invalid SDWA source modifier"); + i.abs |= ((control >> 5) & 1) << j; + i.neg |= ((control >> 4) & 1) << j; + const unsigned reg = j ? (a >> 9) & 255 : ext & 255; + if ((control & 128) && reg == 255) + refuse(pc, "literal is unavailable in SDWA"); + i.src[j] = reg + ((control & 128) ? 0 : 256); + } + i.subword = true; + lit = false; + } else if (i.src[0] == 249 && (sdwa_logic || sdwa_class)) { + const Word ext = take(); + i.src_select = {(ext >> 16) & 7, (ext >> 24) & 7}; + i.src_sext = {bool(ext & (1u << 19)), bool(ext & (1u << 27))}; + if (sdwa_logic) { + i.dst_select = (ext >> 8) & 7; + i.dst_unused = (ext >> 11) & 3; + if ((ext & 0x7070e000u) || i.dst_select == 7 || i.dst_unused == 3) + refuse(pc, "invalid or unsupported integer SDWA modifiers"); + } else { + // VOPC has a scalar mask destination in the same bits that VOP2 uses for placement. + i.dst = ext & 0x8000 ? (ext >> 8) & 127 : 106; + if ((ext & 0x70480000u) || i.dst > sdwa_mask_limit) + refuse(pc, "invalid SDWA class modifiers or mask destination"); + i.neg = (ext >> 20) & 1; + i.abs = (ext >> 21) & 1; + } + if (i.src_select[0] == 7 || i.src_select[1] == 7) + refuse(pc, "invalid or unsupported integer SDWA modifiers"); + i.src[0] = (ext & 255) + (ext & (1u << 23) ? 0 : 256); + i.src[1] = ((a >> 9) & 255) + (ext & (1u << 31) ? 0 : 256); + if (i.src[0] == 255 || i.src[1] == 255) + refuse(pc, "literal is unavailable in SDWA"); + i.subword = true; + lit = false; + } else if (i.src[0] == 249 && i.enc == Encoding::Vop2 && (i.op == 1 || i.op == 0x25)) { + auto ext = take(); + if ((ext & 0xfff8ff00u) != 0x06000600u || ((ext >> 16) & 7u) > 6) + refuse(pc, "SDWA source or destination modifier"); + i.subword = true; + i.src_select[0] = (ext >> 16) & 7u; + i.src[0] = 256 + (ext & 255); + lit = false; + } else if (direct && i.src[0]==250 && (graphics || i.enc!=Encoding::Vopc) && !lit) { + auto control=take(); + // DPP_CTRL[8] selects patterns outside a quad; bit 17 is + // reserved. FI and BOUND_CTRL are independent of the pattern. + if (!half_alu && (control >> 24) != 0xff) refuse(pc,"DPP requires a full-row, full-bank mask"); + if (control & (1u << 17)) refuse(pc,"reserved DPP16 control bit"); + const auto pattern = (control >> 8) & 0x1ff; + i.dpp_control = pattern; + i.dpp_row_mask = control >> 28; + i.dpp_bank_mask = (control >> 24) & 15; + if (pattern > 255 && !i.mirror_mask() && i.dpp_row().op == Inst::DppRowOp::None) + refuse(pc,"unsupported DPP lane selection"); + i.dpp_fetch_inactive = (control & (1u << 18)) != 0; + i.dpp_bound_zero = (control & (1u << 19)) != 0; + i.src[0]=256+(control&255); + i.neg=((control>>20)&1)|((control>>21)&2); + i.abs=((control>>21)&1)|((control>>22)&2); + } else if (direct && !graphics && dpp8 && i.enc != Encoding::Vopc && !lit) { + const Word control = take(); + i.dpp8_selectors = control >> 8; + i.dpp_fetch_inactive = i.src[0] == 234; + i.src[0] = 256 + (control & 255); + } else if (graphics && dpp8 && i.enc != Encoding::Vopc && !lit) { + // pixel_aot.parse_dpp: both halves of an octet must select the + // same local 2x2 permutation to map to desktop quad operations. + const Word control = take(); + unsigned perm = 0; + for (unsigned lane = 0; lane < 4; ++lane) { + const unsigned low = (control >> (8 + 3 * lane)) & 7; + const unsigned high = (control >> (20 + 3 * lane)) & 7; + if (low >= 4 || high != low + 4) refuse(pc, "DPP8 requires repeating quad-local selections"); + perm |= low << (2 * lane); + } + i.dpp_control = perm; + i.dpp_fetch_inactive = i.src[0] == 234; + i.src[0] = 256 + (control & 255); + } else if (i.src[0] == 249 || i.src[0] == 250 || i.src[0] == 233 || i.src[0] == 234) + refuse(pc, "SDWA or DPP vector operands"); + } + if (lit) + i.literal = take(); + if (i.enc == Encoding::Vop1 && !i.op) i.name = "v_nop"; + if (i.name.empty()) { + const char *name = mnemonic(i.enc,i.op); + if (!name && (direct || encoded.name == "v_readlane_b32") && !encoded.name.empty()) + name = encoded.name.data(); + if (!name) + refuse(pc, "unsupported opcode " + hexword(a)); + i.name = name; + if (i.name.substr(0, 7) == "v_cmpx_") + i.dst = 126; + if (i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32") { + i.dst -= 256; + if (i.dst > (graphics ? 105u : 107u)) + refuse(pc, "invalid scalar lane read destination"); + } + } + // Keep permuted VCC compares separate from unpermuted compare/EXEC proofs. + if (i.enc == Encoding::Vopc && i.dpp_control) { + if (i.dst != 106 || i.name.substr(0,6) != "v_cmp_" || i.name.substr(i.name.size()-4) != "_f32" || + i.name.find("_class_") != Name::npos || *i.dpp_control > 255) + refuse(pc,"unsupported DPP pixel compare"); + i.enc = Encoding::QuadCompare; + } + if(i.next-pc!=encoded.size)refuse(pc,"instruction extent mismatch for "+string(encoded.name)); + return i; +} +// VOP2 (including SDWA) writes carry to VCC. VOP3B encodes its own scalar destination. +static std::optional<unsigned> carry_destination(const Inst &i) { + if (i.name == "v_add_co_u32" || i.name == "v_sub_co_u32" || i.name == "v_subrev_co_u32" || + i.name == "v_add_co_ci_u32" || i.name == "v_sub_co_ci_u32" || i.name == "v_subrev_co_ci_u32") + return i.wide ? (i.a >> 8) & 127 : 106; + if (i.name == "v_mad_u64_u32") // VOP3B: the carry-out of the 64-bit add (#3000) + return (i.a >> 8) & 127; + return {}; +} +struct Symbol { + enum class Type { unknown, constant, masked, table, descriptor, indexed_descriptor, sampler_heap, sampler_word, root_address, root_stride_one_high, primitive_mask, + stride, byte_stride, zero_stride_word, byte_count, clear_oob, byte_oob, lane_mask, uniform_mask, + heap_offset, heap_carry, unbound } type{}; + Word value = 0, offset = 0; + unsigned index_mask = 0, definition = 0; + bool numeric() const { return type == Type::unknown || type == Type::constant || type == Type::masked || type == Type::uniform_mask; } + bool operator==(const Symbol &r) const { return type == r.type && value == r.value && offset == r.offset && + index_mask == r.index_mask && definition == r.definition; } +}; +struct State { + std::array<Symbol, 128> scalar{}; + // Encoded VGPR and guest lane. A join can lose the identity while + // retaining the fact that some path omitted the runtime lane write. + std::map<std::pair<unsigned, unsigned>, std::optional<Symbol>> lane_spills; + // SCC, tracked only as the carry of a heap offset add (see heap_offset_add). + Symbol scc{}; + Symbol &operator[](unsigned n) { return scalar[n]; } + const Symbol &operator[](unsigned n) const { return scalar[n]; } + const Symbol &at(unsigned n) const { return scalar.at(n); } + size_t size() const { return scalar.size(); } + auto begin() { return scalar.begin(); } + auto end() { return scalar.end(); } + auto begin() const { return scalar.begin(); } + auto end() const { return scalar.end(); } + bool has_spill(unsigned reg) const { + const auto it = lane_spills.lower_bound({reg, 0}); + return it != lane_spills.end() && it->first.first == reg; + } + void clear_spills(unsigned reg, unsigned count = 1) { + lane_spills.erase(lane_spills.lower_bound({reg, 0}), lane_spills.lower_bound({reg + count, 0})); + } +}; +static std::optional<Word> constant32(const Inst &i, unsigned r) { + static constexpr Word floats[]{0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, 0x40000000, + 0xc0000000, 0x40800000, 0xc0800000, 0x3e22f983}; + if (r >= 128 && r <= 192) return r - 128; + if (r >= 193 && r <= 208) return Word(192) - r; + if (r >= 240 && r <= 248) return floats[r - 240]; + if (r == 255) return i.literal; + return {}; +} +static std::optional<unsigned> guest_spill_lane(const Inst &i, bool wave64) { + if (auto selector = constant32(i, i.src[1])) + return *selector & (wave64 ? 63 : 31); + return {}; +} +static bool identity_spill(const Symbol &s) { + // Indexed descriptors and their derived fields still use an SGPR's + // runtime index. Erasing a lane operation would lose that payload. + // An unbound value stays unbound after a refill, so it is refused at its use. + return !s.numeric() && + s.type != Symbol::Type::indexed_descriptor && !s.definition; +} +static void clear_vector_spills(const Inst &i, State &s) { + if (s.lane_spills.empty()) return; + switch (i.enc) { + case Encoding::Vop1: case Encoding::Vop2: case Encoding::Vop3: case Encoding::Mix: + if (i.dst >= 256 && i.name != "v_nop") { + const bool pair = i.name == "v_mad_u64_u32" || i.name == "v_mad_i64_i32" || i.name == "v_lshlrev_b64" || + i.name == "v_lshrrev_b64" || i.name == "v_ashrrev_i64"; + s.clear_spills(i.dst, pair ? 2 : 1); + if (i.name == "v_swap_b32") s.clear_spills(i.src[0]); + } + break; + case Encoding::Mubuf: + if (i.name == "buffer_load_dword") { + constexpr unsigned widths[]{1, 2, 4, 3}; + s.clear_spills(256 + i.dst, widths[i.op & 3]); + } else if (i.name == "buffer_load_format" || i.name.substr(0, 8) == "tbuffer_") + s.clear_spills(256 + i.dst, (i.op & 3) + 1); + else if (i.name == "global_load_dword" || + (i.name.substr(0, 14) == "buffer_atomic_" && (i.a & 0x4000))) + s.clear_spills(256 + i.dst); + break; + case Encoding::Image: + if (i.op != 8) { + unsigned count = 0; + for (unsigned mask = (i.a >> 8) & 15; mask; mask >>= 1) + count += mask & 1; + if (i.op == 68) count = 4; + if (i.b >> 31) count = (count + 1) / 2; + s.clear_spills(256 + i.dst, count); + } + break; + default: break; + } +} +// FSSM root descriptors carry a guest address in two SGPRs. Preserve the +// identity of each half through scalar moves and CFG joins (Victory resource.rs). +void bind_root_address(State &state, const ShaderRootInput &input, unsigned limit) { + const unsigned at = input.user_data; + if (input.sgpr_count != 2 || at >= limit || limit - at < 2 || input.root_parameter >= 16 || + input.offset_dwords || state[at].type != Symbol::Type::unbound || state[at+1].type != Symbol::Type::unbound) + refuse(0, "invalid FSSM root descriptor pair"); + for (unsigned half = 0; half < 2; ++half) + state[at + half] = {Symbol::Type::root_address, input.root_parameter, half}; +} +Symbol source(const Inst &i, unsigned code, const State &s) { + if (code < 128) + return s[code]; + if (code <= 192) + return {Symbol::Type::constant, code - 128}; + if (code <= 208) + return {Symbol::Type::constant, 192u - code}; + if (code == 255) + return {Symbol::Type::constant, i.literal}; + return {}; +} +// The low word of a resource-heap descriptor address formed by adding a byte offset, as in a waterfall loop over a +// lane-selected slot: s_add_u32 lo, <resource heap>, <byte offset SGPR>, then the carry into the high word. Returns the +// operand index of the offset. A constant offset is not matched: the selected slot must come from GPU data. +static std::optional<unsigned> heap_offset_add(const Inst &i, const State &s) { + if (i.name != "s_add_u32" || i.dst > 105) return {}; + for (unsigned k = 0; k < 2; ++k) { + const auto heap = source(i, i.src[k], s), offset = source(i, i.src[1 - k], s); + if (heap.type == Symbol::Type::table && heap.value == compute_resource_heap && !heap.offset && + i.src[1 - k] <= 105 && offset.numeric() && offset.type != Symbol::Type::constant) + return 1 - k; + } + return {}; +} +// The high word of that address: s_add_u32 hi, 0, src_scc or s_addc_u32 hi, 0, 0. +static bool heap_offset_carry(const Inst &i) { + return i.dst <= 105 && ((i.name == "s_add_u32" && ((i.src[0] == 128 && i.src[1] == 253) || + (i.src[0] == 253 && i.src[1] == 128))) || + (i.name == "s_addc_u32" && i.src[0] == 128 && i.src[1] == 128)); +} +// s[base:base+1] holds the resource-heap base plus a byte offset with its own carry in the high word. +static bool heap_offset_address(const State &s, unsigned base) { + return base + 1 < s.size() && s[base].type == Symbol::Type::heap_offset && + s[base + 1].type == Symbol::Type::heap_carry && s[base + 1].definition == s[base].definition; +} +// Derive the rewritten byte-address V# symbolically. Each field carries its +// source table/slot identity. Numeric consumption still requires real bits. +// heap_window: the direct path under HeapViewContract::raw_buffer also rewrites a +// descriptor loaded from the GPU-selected heap slot (its words keep the load pc). +static std::optional<Symbol> byte_descriptor_field(const Inst &i, const State &s, bool heap_window = false) { + using T = Symbol::Type; + if (i.enc != Encoding::Sop2 || i.dst > 105) return {}; + auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + auto component = [heap_window](const Symbol &v, unsigned ch) { + return v.offset % 32 == ch*4 && ((v.type == T::descriptor && v.value != compute_resource_heap) || + (heap_window && v.type == T::indexed_descriptor && v.value == compute_resource_heap)); + }; + auto field = [](Symbol v, T kind) { + v.type = kind; + v.offset &= ~31u; + return v; + }; + if (i.name == "s_bfe_u32" && component(a, 1) && b.type == T::constant && b.value == 0xe0010) + return field(a, T::stride); + if (i.name == "s_mul_i32") { + if (a.type == T::byte_stride) std::swap(a,b); + if (component(a, 2) && b == field(a,T::byte_stride)) return field(a, T::byte_count); + } + if (a.type == T::constant) std::swap(a,b); + if (b.type != T::constant) return {}; + // Address bits occupy the low halfword. Setting bit 16 in the high + // address word constructs a buffer descriptor with byte stride one. + if (i.name == "s_or_b32" && a.type == T::root_address && a.offset == 1 && b.value == 0x10000) { + a.type = T::root_stride_one_high; + return a; + } + if (i.name == "s_max_u32" && a.type == T::stride && b.value == 1) return field(a, T::byte_stride); + if (i.name == "s_and_b32" && b.value == 0xc000ffff && component(a,1)) return field(a,T::zero_stride_word); + if (i.name == "s_and_b32" && b.value == 0xcfffffff && component(a,3)) return field(a,T::clear_oob); + if (i.name == "s_or_b32" && b.value == 0x30000000 && (a.type == T::clear_oob || component(a,3))) + return field(a,T::byte_oob); + return {}; +} +State transfer(const Inst &i, State s, bool wave64, bool graphics, bool heap_window, bool direct, + bool narrow_wave64 = false) { + auto set = [&](unsigned n, Symbol v) { + if (n >= s.size()) + refuse(i.pc, "invalid SGPR"); + s[n] = v; + }; + const Symbol carry = s.scc; + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopc || i.enc == Encoding::Sopk) + s.scc = {}; + const auto heap_add = direct && !graphics ? heap_offset_add(i, s) : std::nullopt; + if (direct && !graphics) { + if (i.name == "v_writelane_b32") { + if (auto lane = guest_spill_lane(i, wave64)) { + const auto key = std::make_pair(i.dst, *lane); + const auto value = source(i, i.src[0], s); + if (i.src[0] <= 105 && identity_spill(value)) + s.lane_spills[key] = value; + else + s.lane_spills.erase(key); + } + return s; + } + if (i.name == "v_readlane_b32") { + const auto lane = guest_spill_lane(i, wave64); + const auto slot = lane ? s.lane_spills.find({i.src[0], *lane}) : s.lane_spills.end(); + set(i.dst, slot != s.lane_spills.end() && slot->second ? *slot->second : Symbol{}); + return s; + } + clear_vector_spills(i, s); + } + auto mask = carry_destination(i); + const bool compared = graphics && i.enc == Encoding::Vopc && i.dst < 106 && i.name.substr(0,6) == "v_cmp_"; + if (mask || compared) { + const unsigned dst = mask.value_or(i.dst); + const bool numeric_vcc_hi = dst == 107 && direct && !graphics && !wave64; + if ((dst > 106 && !numeric_vcc_hi) || (wave64 && (dst & 1))) + refuse(i.pc, compared ? "unsupported comparison mask destination" : "unsupported carry mask destination"); + const bool tagged = graphics && dst != 106; + set(dst, tagged ? Symbol{Symbol::Type::lane_mask,i.pc,0} : Symbol{}); + if (wave64) set(dst + 1, tagged ? Symbol{Symbol::Type::lane_mask,i.pc,1} : Symbol{}); + } else if (graphics && i.name == "s_cselect_b64" && i.dst <= 104 && !(i.dst & 1) && + (i.src[0] == 193 || i.src[0] == 128) && (i.src[1] == 193 || i.src[1] == 128)) { + set(i.dst,{Symbol::Type::uniform_mask,i.pc,0}); + set(i.dst+1,{Symbol::Type::uniform_mask,i.pc,1}); + } else if (heap_add) { + const auto offset = source(i, i.src[*heap_add], s); + set(i.dst, {Symbol::Type::heap_offset, compute_resource_heap, 0, + offset.type == Symbol::Type::masked ? offset.value : ~0u, i.pc}); + s.scc = {Symbol::Type::heap_carry, compute_resource_heap, 0, 0, i.pc}; + } else if (direct && !graphics && carry.type == Symbol::Type::heap_carry && heap_offset_carry(i)) { + set(i.dst, carry); + } else if (auto field = byte_descriptor_field(i,s,heap_window)) { + set(i.dst,*field); + } else if (i.enc == Encoding::FixedSetup) { + for (unsigned r = i.dst; r < i.dst + i.op && r < s.size(); ++r) s[r] = {}; + } else if (i.enc == Encoding::Fetch) { + s[4].type = s[5].type = Symbol::Type::unbound; + } else if (i.enc == Encoding::Smem) { + auto base = s[i.src[0]]; + const unsigned offset_reg = i.b >> 25; + const Symbol index = offset_reg < smem_sgpr_limit(direct && !graphics) ? s[offset_reg] : Symbol{}; + unsigned n = memory_count(i); + const bool heap_address = i.op == 2 && i.b >> 25 == 125 && heap_offset_address(s, i.src[0]); + for (unsigned j = 0; j < n; ++j) { + Symbol v{}; + if (heap_address) { + v = {Symbol::Type::indexed_descriptor, compute_resource_heap, (i.b & 0xfffff) + 4 * j, base.index_mask, i.pc}; + } else if (graphics && i.op == 3 && base.type == Symbol::Type::table && base.value == compute_resource_heap) { + const bool fixed = offset_reg == 125 || index.type == Symbol::Type::constant; + const Word offset = (i.b & 0xfffff) + (offset_reg != 125 && fixed ? index.value : 0); + v = {Symbol::Type::indexed_descriptor, base.value, offset + 4*j, + fixed ? 0u : index.type == Symbol::Type::masked ? index.value : ~0u, i.pc}; + } else if (i.op == 2 && base.type == Symbol::Type::sampler_heap) { + v = {Symbol::Type::sampler_word, i.dst, j, 0, i.pc}; + } else if ((i.op == 2 || (graphics && i.op == 3)) && offset_reg != 125 && base.type == Symbol::Type::table) { + v = {Symbol::Type::indexed_descriptor, base.value, (i.b & 0xfffff) + 4*j, + index.type == Symbol::Type::masked || index.type == Symbol::Type::constant ? index.value : ~0u, i.pc}; + } else if (i.op < 8 && base.type == Symbol::Type::table) + v = {Symbol::Type::descriptor, base.value, (i.b & 0xfffff) + 4 * j}; + set(i.dst + j, v); + } + } else if (i.name == "s_mov_b32" || i.name == "s_mov_b64") { + auto v = source(i, i.src[0], s); + Symbol high = i.src[0] < 127 ? s[i.src[0] + 1] + : Symbol{Symbol::Type::constant, (i.src[0] >= 193 && i.src[0] <= 208) ? ~0u : 0u}; + set(i.dst, v); + if (i.name == "s_mov_b64") + set(i.dst + 1, high); + } else if (!graphics && !wave64 && i.enc == Encoding::Sop1 && + ((i.name.size() > 13 && i.name.substr(i.name.size() - 13) == "_saveexec_b32") || + i.name == "s_andn1_wrexec_b32" || i.name == "s_andn2_wrexec_b32")) { + // Both the saved/written destination and the updated EXEC are numeric mask words. + set(i.dst, {}); + set(126, {}); + } else if (!graphics && i.enc == Encoding::Sop1 && i.name.size() >= 13 && + (i.name.substr(i.name.size() - 13) == "_saveexec_b64" || + i.name.substr(i.name.size() - 11) == "_wrexec_b64")) { + // These instructions also overwrite both EXEC words implicitly. + set(i.dst, {}); + set(i.dst + 1, {}); + set(126, {}); + set(127, {}); + } else if (i.name == "s_and_b32" || i.name == "s_lshl_b32") { + const auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + Symbol out{}; + if (i.name == "s_and_b32" && (a.type == Symbol::Type::constant || b.type == Symbol::Type::constant)) + out = {Symbol::Type::masked, a.type == Symbol::Type::constant ? a.value : b.value}; + if (i.name == "s_lshl_b32" && b.type == Symbol::Type::constant && a.numeric()) { + const Word mask = a.type == Symbol::Type::masked ? a.value : ~0u; + out = {Symbol::Type::masked, mask << (b.value & 31)}; + } + if (a.type == Symbol::Type::constant && b.type == Symbol::Type::constant) + out = {Symbol::Type::constant,i.name=="s_and_b32" ? a.value & b.value : a.value << (b.value & 31)}; + set(i.dst, out); + } else if (!graphics && i.name == "s_bfm_b64") { + auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + Symbol lo{}, hi{}; + if (a.type == Symbol::Type::constant && b.type == a.type) { + const auto mask = ((uint64_t{1} << (a.value & 63)) - 1) << (b.value & 63); + lo = {a.type, Word(mask)}; + hi = {a.type, Word(mask >> 32)}; + } + set(i.dst, lo); + set(i.dst + 1, hi); + } else if (i.name == "s_bfm_b32") { + auto a = source(i, i.src[0], s), b = source(i, i.src[1], s); + Symbol v{}; + if (a.type == Symbol::Type::constant && b.type == a.type) + v = {a.type, ((1u << (a.value & 31)) - 1u) << (b.value & 31)}; + set(i.dst, v); + } else if (i.name == "s_movk_i32") { + set(i.dst, {Symbol::Type::constant, Word(int16_t(i.a))}); + } else if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Vopc || i.enc == Encoding::QuadCompare || + i.name == "s_mulk_i32" || i.name == "s_addk_i32" || i.name == "s_cmovk_i32" || + i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32") + { + set(i.dst, {}); + const bool compare_pair = (wave64 && (i.enc == Encoding::Vopc || i.enc == Encoding::QuadCompare)) || + (narrow_wave64 && i.enc == Encoding::Vopc && i.dst == 126); + if (compare_pair || ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && + i.name.size() >= 4 && + (i.name.substr(i.name.size() - 4) == "_b64" || i.name.substr(i.name.size() - 4) == "_i64" || + i.name.substr(i.name.size() - 4) == "_u64") && + i.name.find("_i32_") == Name::npos) || i.name == "s_bitreplicate_b64_b32") + set(i.dst + 1, {}); + } + return s; +} +struct Program { + bool graphics_wave64 = false; + std::vector<Inst> code; + std::map<unsigned, size_t> at; + std::vector<State> before; + std::vector<bool> reached; +}; +// Recognize slot-zero vertex-buffer loads as a group. Other scalar table +// loads interleaved by the scheduler stay in the normal instruction stream. +std::map<unsigned, Inst> fixed_vertex_loads(const string &code) { + std::map<unsigned, Inst> result; + unsigned pc = 0; + while (pc + 12 <= code.size()) { + const Word a = word(code, pc); + if ((a & 0xff80ffffu) == 0xbe800400u) break; + const auto i = decode(code, pc, true, true); + if (!(i.name == "v_nop" || i.name == "s_nop" || i.name == "s_setprio" || + i.name == "s_inst_prefetch" || i.name == "s_clause" || + ((i.name == "s_mov_b32" || i.enc == Encoding::Smem) && i.dst >= 3 && i.dst < 106))) + return {}; + pc = i.next; + } + if (pc + 12 > code.size()) return {}; + const unsigned ptr = (word(code, pc) >> 16) & 127; + if (ptr < 4 || ptr > 104 || (ptr & 1) || word(code,pc+4) != (0x9380ff00u | ((ptr+1)<<16) | (ptr+1)) || + word(code,pc+8) != 0x80000u) return {}; + auto setup = [&](unsigned bytes, unsigned dst, unsigned count) { + Inst i{}; + i.pc = pc; i.next = pc + bytes; i.enc = Encoding::FixedSetup; i.name = "fixed_vertex_setup"; + i.dst = dst; i.op = count; result.emplace(pc,i); pc = i.next; + }; + setup(4, ptr, 2); + setup(8, ptr + 1, 1); + unsigned desc = UINT_MAX; + while (pc + 8 <= code.size()) { + Word a = word(code,pc), b = word(code,pc+4); + if ((a & 0xffff0000u) == 0xbfa10000u) { pc += 4; continue; } + if ((a & 0xffffe000u) != 0xf4080000u) return {}; + const unsigned dst = (a >> 6) & 127, base = (a & 63) * 2; + if (base == ptr && b == 0xfa000000u && !(dst & 3) && dst <= 100) { + desc = dst; + setup(8, dst, 4); + break; + } + if (base == ptr || (b >> 25) != 125 || (dst < ptr + 2 && ptr < dst + 4) || dst < 3) + return {}; + pc += 8; + } + if (desc == UINT_MAX || pc + 8 > code.size() || word(code,pc) != 0x4a000002u || + word(code,pc+4) != 0xbf8cc07fu) return {}; + setup(4, 256, 1); // v0 is the adjusted fetch index, consumed by the IA. + pc += 4; + if (pc + 4 <= code.size() && (word(code,pc) & 0xffff0000u) == 0xbfa10000u) pc += 4; + bool found = false, overwrote_index = false; + while (pc + 8 <= code.size()) { + const Word a = word(code,pc), b = word(code,pc+4); + const Word form = a & ~4095u; + unsigned width, alignment; + bool normalized; + switch (form) { + case 0xe0342000u: width = 2; alignment = 4; normalized = false; break; + case 0xe0382000u: width = 4; alignment = 4; normalized = false; break; // buffer_load_dwordx4 idxen + case 0xe03c2000u: width = 3; alignment = 4; normalized = false; break; + case 0xe8282000u: width = 1; alignment = 1; normalized = false; break; // BUF_FMT_8_UINT + case 0xe8082000u: width = 1; alignment = 1; normalized = true; break; // BUF_FMT_8_UNORM + case 0xe8712000u: width = 2; alignment = 2; normalized = true; break; // BUF_FMT_8_8_UNORM + case 0xe9c32000u: width = 4; alignment = 4; normalized = true; break; // BUF_FMT_8_8_8_8_UNORM + default: return found ? result : std::map<unsigned, Inst>{}; + } + if (overwrote_index || (b & 0xffff00ffu) != (0x80000000u | ((desc / 4) << 16))) return {}; + Inst i{}; + i.pc = pc; i.next = pc + 8; i.enc = Encoding::FixedFetch; i.name = "fixed_vertex_fetch"; + i.dst = 256 + ((b >> 8) & 255); + i.op = width; + i.a = normalized; + i.literal = a & 4095u; + if (i.literal % alignment || i.literal >= 2048 || i.dst+i.op > 512) return {}; + result.emplace(pc, i); + found = true; overwrote_index = i.dst == 256; pc += 8; + } + return found ? result : std::map<unsigned, Inst>{}; +} +Program parse(const string &code, unsigned entry, const State &initial, bool graph, bool graphics=false, bool wave64=false, bool fixed_vertex=false, + bool heap_window=false, bool narrow_wave64=false) { + Program p; + p.graphics_wave64 = graphics && wave64; + if ((entry & 3) || entry >= code.size() || code.size() > 1u << 20) + refuse(entry, "invalid entry"); + if (graph) { + const auto fixed = fixed_vertex ? fixed_vertex_loads(code) : std::map<unsigned, Inst>{}; + std::map<unsigned, Inst> instructions; + std::deque<unsigned> pending{entry}; + while (!pending.empty()) { + unsigned pc = pending.front(); + pending.pop_front(); + auto next = instructions.lower_bound(pc); + if (next != instructions.end() && next->first == pc) continue; + if (pc >= code.size() || (next != instructions.begin() && std::prev(next)->second.next > pc)) + refuse(pc, "branch outside code or into an instruction"); + const auto fetch = fixed.find(pc); + auto instruction = fetch != fixed.end() ? fetch->second : decode(code, pc,true,graphics,wave64); + if (next != instructions.end() && instruction.next > next->first) + refuse(pc, "overlapping instruction boundaries"); + instructions.emplace_hint(next, pc, instruction); + if (instruction.branch()) pending.push_back(instruction.target()); + if (instruction.name != "s_endpgm" && !(instruction.branch() && instruction.op == 2)) + pending.push_back(instruction.next); + } + for (const auto &[pc, instruction] : instructions) { + p.at.emplace(pc, p.code.size()); + p.code.push_back(instruction); + } + } else { + for (unsigned pc = entry;;) { + auto i = decode(code, pc); + p.at.emplace(pc, p.code.size()); + p.code.push_back(i); + if (i.name == "s_endpgm") break; + pc = i.next; + } + } + // Include the loop's entry and all branch joins when proving descriptor provenance. + p.before.resize(p.code.size()); + p.reached.resize(p.code.size()); + const size_t start = p.at.at(entry); + p.before[start] = initial; + p.reached[start] = true; + std::deque<size_t> work{start}; + while (!work.empty()) { + auto k = work.front(); + work.pop_front(); + auto &i = p.code[k]; + auto after = transfer(i, p.before[k], wave64, graphics, heap_window, graph, narrow_wave64); + auto merge = [&](size_t t) { + bool changed = !p.reached[t]; + auto &in = p.before[t]; + if (changed) { + in = after; + p.reached[t] = true; + } else { + for (unsigned n = 0; n < in.size(); ++n) + if (!(in[n] == after[n])) { + Symbol merged{}; + if (!in[n].numeric() || !after[n].numeric()) + merged.type = Symbol::Type::unbound; + if (!(in[n] == merged)) { + in[n] = merged; + changed = true; + } + } + if (!(in.scc == after.scc) && !(in.scc == Symbol{})) { + in.scc = {}; + changed = true; + } + for (auto &[key, value] : in.lane_spills) { + const auto other = after.lane_spills.find(key); + if (value && (other == after.lane_spills.end() || !(other->second == value))) { + value.reset(); + changed = true; + } + } + for (const auto &slot : after.lane_spills) + changed |= in.lane_spills.emplace(slot.first, std::nullopt).second; + } + if (changed) + work.push_back(t); + }; + if (i.branch()) { + auto t = p.at.find(i.target()); + if (t == p.at.end()) + refuse(i.pc, "invalid branch target"); + merge(t->second); + } + if (i.name != "s_endpgm" && !(i.branch() && i.op == 2)) + merge(p.at.at(i.next)); + } + return p; +} +string reg(unsigned n) { return n >= 256 ? "v" + to_string(n - 256) : "s" + to_string(n); } +string operand(const Inst &i, unsigned n) { + if ((n <= 105) || n == 106 || n == 126 || n >= 256) + return reg(n); + if (n == 253) + return "uint(scc)"; + if (auto constant = constant32(i, n)) + return hexword(*constant); + refuse(i.pc, "unsupported operand " + to_string(n)); +} +enum class AluType { Bits, Float, ToFloat }; +struct AluRule { + unsigned arity; + AluType type; + Name expression; +}; +#include "gfx1013_compute_alu.inl" + +struct Emit { + NativeComputeShader result{}; + const Program &program; + const D3D12_ROOT_SIGNATURE_DESC1 &layout; + std::ostringstream body; + unsigned srv = 0, uav = 0, first_sampler = 0; + string binding(const Inst &i, const State &state, unsigned base, unsigned width, ComputeViewKind kind, + unsigned bytes = 0,unsigned dimension = 1) { + auto sym = state.at(base); + const bool indexed = sym.type == Symbol::Type::indexed_descriptor; + if ((!indexed && sym.type != Symbol::Type::descriptor) || base + width > state.size()) + refuse(i.pc, "unproven resource descriptor s" + to_string(base)); + if (sym.value == compute_sampler_heap) + refuse(i.pc, "a sampler heap descriptor is read as a resource"); + const bool byte_window = kind == ComputeViewKind::byte_window_srv || + (kind == ComputeViewKind::raw_buffer_uav && width == 4 && + (i.name == "buffer_store_raw" || i.name == "buffer_load_dword" || + i.enc == Encoding::Smem || + (i.name.substr(0, 14) == "buffer_atomic_" && !(i.a & 0x2000u))) && + state[base + 1].type == Symbol::Type::zero_stride_word); + for (unsigned j = 1; j < width; ++j) { + Symbol expected = sym; + if (byte_window) { + constexpr Symbol::Type fields[] = {Symbol::Type::descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; + expected.type = fields[j]; + } else expected.offset += j * 4; + if (!(state[base + j] == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + if (sym.offset % 32) + refuse(i.pc, "unaligned descriptor table entry"); + auto &list = result.bindings; + if (sym.value == compute_resource_heap) + refuse(i.pc, "whole-heap buffer access needs a matching descriptor at the GPU-selected index"); + if (indexed) { + if ((width != 4 && width != 8) || compute_uav(kind) || (sym.index_mask & 31)) + refuse(i.pc, "indexed descriptor requires a bounded 32-byte-aligned SRV offset"); + const unsigned first = sym.offset / 32, count = 1 + sym.index_mask / 32; + if (sym.value >= layout.NumParameters || layout.pParameters[sym.value].ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + refuse(i.pc, "missing indexed descriptor table range"); + const auto &table = layout.pParameters[sym.value].DescriptorTable; + const uint64_t end = uint64_t(first) + count; + if (count > D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1 || + end > (uint64_t(UINT_MAX) + 1) / 32) + refuse(i.pc, "indexed SRV span exceeds its declared root range"); + std::vector<std::pair<uint64_t, uint64_t>> covered; + uint64_t next = 0; + for (unsigned j = 0; j < table.NumDescriptorRanges; ++j) { + const auto &range = table.pDescriptorRanges[j]; + uint64_t start = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next : range.OffsetInDescriptorsFromTableStart; + next = start + range.NumDescriptors; + if (start >= end || next <= first) continue; + if (range.RangeType != D3D12_DESCRIPTOR_RANGE_TYPE_SRV) + refuse(i.pc, "indexed SRV span overlaps a non-SRV root range"); + covered.emplace_back((std::max)(uint64_t(first), start), (std::min)(end, next)); + } + // These are physical slots relative to the bound table. Adjacent + // SRV ranges may name unrelated guest registers or register spaces. + std::sort(covered.begin(), covered.end()); + uint64_t cursor = first; + for (const auto &[lo, hi] : covered) { + if (lo > cursor) break; + cursor = (std::max)(cursor, hi); + } + if (cursor != end) + refuse(i.pc, "indexed SRV span exceeds its declared root range"); + auto span = std::find_if(list.begin(), list.end(), [&](const auto &b) { + return b.kind == kind && b.root_parameter == sym.value && b.byte_offset == sym.offset && + b.array_count == count && b.image_dimension == dimension && !b.array_position; + }); + unsigned first_reg = srv; + if (span == list.end()) { + for (unsigned j = 0; j < count; ++j) + list.push_back({kind, sym.value, sym.offset + j * 32, srv++, bytes, count, j, dimension}); + } else { + first_reg = span->shader_register; + for (unsigned j = 0; j < count; ++j) + span[j].required_bytes = (std::max)(span[j].required_bytes, bytes); + } + return "r"+to_string(first_reg)+(count==1 ? "" : "[NonUniformResourceIndex("+reg(base)+")]"); + } + auto it = std::find_if(list.begin(), list.end(), [&](const auto &b) { + if (compute_buffer_uav(kind) && b.kind == kind && b.root_parameter == sym.value && + b.byte_offset == sym.offset && kind != ComputeViewKind::raw_buffer_uav && b.required_bytes != bytes) + refuse(i.pc, "incompatible formatted store widths on one slot"); + return b.array_count == 1 && b.image_dimension==dimension && b.kind == kind && b.root_parameter == sym.value && b.byte_offset == sym.offset; + }); + bool write = compute_uav(kind); + if (it == list.end()) { + list.push_back({kind, sym.value, sym.offset, write ? uav++ : srv++, bytes,1,0,dimension}); + it = std::prev(list.end()); + } + it->required_bytes = (std::max)(it->required_bytes, bytes); + return (write ? "w" : "r") + to_string(it->shader_register); + } + // heap: the sampler is entry `index` of the directly indexed sampler heap. Otherwise `index` is the static sampler register. + struct SamplerRef { + bool heap; + unsigned index; + }; + SamplerRef sampler_index(const Inst &i, const State &state, bool lod, bool gather_base_level = false, + bool implicit_sample = false, bool comparison = false) { + const unsigned base = ((i.b >> 21) & 31) * 4; + ComputeSampler sampler{{}, lod, comparison}; + unsigned literal = 0, heap = 0; + const auto &first = state.at(base); + for (unsigned j = 0; j < 4; ++j) { + const auto &s = state.at(base + j); + literal += s.type == Symbol::Type::constant; + // The heap content is fixed within a dispatch, so contiguity of the four words of one 16-byte entry is enough. + heap += s.type == Symbol::Type::descriptor && s.value == compute_sampler_heap && !s.definition && + first.offset % 16 == 0 && s.offset == first.offset + 4 * j; + if (s.type == Symbol::Type::constant) + sampler.words[j] = s.value; + } + if (literal != 4 && heap != 4) + refuse(i.pc, "nonconstant sampler"); + if (heap == 4) { + if (gather_base_level) + refuse(i.pc, "gather through the sampler heap is not translated"); + if (comparison) + refuse(i.pc, "comparison sampler from the sampler heap is not translated"); + if (implicit_sample) + refuse(i.pc, "sampler from the sampler heap needs image_sample_l or image_sample_lz"); + const unsigned entry = first.offset / 16, bytes = 16 * (entry + 1); + auto &list = result.bindings; + auto found = std::find_if(list.begin(), list.end(), + [](const auto &b) { return b.kind == ComputeViewKind::heap_sampler; }); + if (found == list.end()) + list.push_back({ComputeViewKind::heap_sampler, compute_sampler_heap, 0, 0, bytes}); + else + found->required_bytes = (std::max)(found->required_bytes, bytes); + return {true, entry}; + } + if (comparison) { + // Field constraints from pixel_aot.comparison_sampler_state. The + // native static sampler also preserves the mip filter and LOD limits. + auto &[address, limits, filter, border] = sampler.words; + const unsigned mag = (filter >> 20) & 3, min = (filter >> 22) & 3, mip = (filter >> 26) & 3; + if ((address & 63) != 0x12 || (address & ((7u << 9) | (1u << 15) | (3u << 19) | (3u << 29))) || + mag != min || mag > 1 || mip == 3 || ((address >> 27) & 1) != (mag == 0) || + (filter & 0xfffff) || (filter >> 28 & (implicit_sample ? 15 : 8)) || (border & 0x3ffff000)) + refuse(i.pc, "unsupported comparison sampler fields"); + if (limits & 0xfff) + refuse(i.pc, "comparison sampler requires minimum LOD zero"); + if (!mip) + limits &= ~0x00fff000u; + } else if (implicit_sample) { + // The static sampler carries MIN_LOD and MAX_LOD. Only encode a + // gradient-derived LOD when its mip filter and bias are representable. + unsigned mip = (sampler.words[2] >> 26) & 3; + if ((sampler.words[2] & 0xfffff) || (mip != 1 && mip != 2) || + (sampler.words[1] & 0xfff) > ((sampler.words[1] >> 12) & 0xfff)) + refuse(i.pc, "implicit sample with unsupported sampler LOD fields"); + } + if (gather_base_level) { + // DXIL textureGather has no explicit LOD operand. A dedicated static + // sampler fixes the gather footprint to the first mip of the SRV. + if (sampler.words[1] & 0xfffu) + refuse(i.pc, "base-level gather with a nonzero minimum LOD"); + sampler.words[1] &= ~0x00fff000u; + sampler.explicit_lod = true; + } + auto &all = result.samplers; + auto it = std::find_if(all.begin(), all.end(), + [&](const auto &s) { return s.words == sampler.words && s.explicit_lod == sampler.explicit_lod && + s.comparison == sampler.comparison; }); + if (it == all.end()) { + all.push_back(sampler); + it = std::prev(all.end()); + } + return {false, first_sampler + static_cast<unsigned>(it - all.begin())}; + } + void image(const Inst &i, const State &state) { + unsigned mask = (i.a >> 8) & 15, base = ((i.b >> 16) & 31) * 4, addr = i.b & 255; + const bool half_store = i.op == 8 && (i.b & 0x80000000u); + if (!mask || (i.a & 0x3e0c0u) || (i.b & 0x3c000000u)) + refuse(i.pc, "unsupported image flags"); + bool store = i.op == 8, lod = i.op == 39, gather = i.op == 71; + if (i.op != 0 && !store && !lod && !gather) + refuse(i.pc, "unsupported image opcode"); + auto tex = binding(i, state, base, 8, half_store ? ComputeViewKind::half_scalar_uav : + store ? ComputeViewKind::texture_uav : ComputeViewKind::texture_srv); + string x = reg(256 + addr), y = reg(256 + (((i.a >> 1) & 3) ? (i.image_address_words[0] & 255) : addr + 1)); + if (i.b & 0x40000000u) { + if (lod || gather || (store && !half_store) || (half_store && ((i.a >> 1) & 3))) + refuse(i.pc, "packed sample address"); + y = "(" + x + ">>16)"; + x = "(" + x + "&65535u)"; + } + if (store) { + if (half_store) { + body << "if(active) " << tex << "[uint2(" << x << "," << y << ")]=f16tof32(" + << reg(256+i.dst) << "&65535u);\n"; + return; + } + if (mask != 15 || i.dst > 252) + refuse(i.pc, "unsupported image store mask"); + body << "if(active) " << tex << "[uint2(" << x << "," << y << ")]=asfloat(uint4("; + for (unsigned k = 0; k < 4; ++k) + body << (k ? "," : "") << reg(256 + i.dst + k); + body << "));\n"; + return; + } + if (lod || gather) { + if (gather && mask != 1) + refuse(i.pc, "unsupported gather channel"); + const auto sampler = sampler_index(i, state, lod); + if (sampler.heap) + refuse(i.pc, "sampler heap reads need the direct DXIL path"); + body << "t=" << tex << (lod ? ".SampleLevel(" : ".GatherRed(") << "q" << sampler.index + << ",float2(asfloat(" << x << "),asfloat(" << y << "))" << (lod ? ",0);\n" : ");\n"); + } else + body << "t=" << tex << ".Load(int3(" << x << "," << y << ",0));\n"; + unsigned dst = i.dst; + for (unsigned k = 0; k < 4; ++k) + if (gather || ((mask >> k) & 1)) { + if (dst >= 256) + refuse(i.pc, "image destination overflow"); + body << "if(active) " << reg(256 + dst++) << "=asuint(t." << "xyzw"[k] << ");\n"; + } + } + void require_numeric(const Inst &i, unsigned reg, unsigned limit = 106) const { + if ((reg < limit || reg == 124) && !program.before[program.at.at(i.pc)][reg].numeric()) + refuse(i.pc, reg == 124 ? "unbound numeric M0" : "unbound numeric SGPR s" + to_string(reg)); + } + void scalar(const Inst &i) { + auto n = i.name; + string a = operand(i, i.src[0]), b = operand(i, i.src[1]), d = reg(i.dst), e; + if (n == "s_mov_b32" || n == "s_mov_b64") { + if (n == "s_mov_b64") { + if (i.dst == 126) + require_numeric(i, i.src[0]); + if ((i.dst & 1) || i.dst + 1 >= 128 || (i.src[0] < 128 && (i.src[0] & 1))) + refuse(i.pc, "scalar pair overflow"); + body << reg(i.dst + 1) << "=" + << (i.src[0] < 105 ? reg(i.src[0] + 1) + : i.src[0] >= 193 && i.src[0] <= 208 ? "0xffffffffu" + : "0u") + << ";\n"; + } + if (i.dst == 106 || i.dst == 126) + require_numeric(i, i.src[0]); + body << d << "=" << a << ";\n"; + if (i.dst == 126) + body << "active=(s126&laneBit)!=0;\n"; + return; + } + if (n == "s_bfe_u32" && i.src[0] <= 105) { + const auto &state = program.before[program.at.at(i.pc)]; + const auto word = state[i.src[0]]; + const auto bits = source(i, i.src[1], state); + if (word.type == Symbol::Type::indexed_descriptor && word.value == compute_resource_heap && + (word.offset & 31) == 4 && bits.type == Symbol::Type::constant && bits.value == 0xe0010) { + auto &bindings = result.bindings; + auto it = std::find_if(bindings.begin(), bindings.end(), [](const auto &b) { + return b.kind == ComputeViewKind::heap_stride_srv; + }); + if (it == bindings.end()) { + bindings.push_back({ComputeViewKind::heap_stride_srv, compute_resource_heap, 0, srv++, 4}); + it = std::prev(bindings.end()); + } + body << d << "=r" << it->shader_register << ".Load((" << a << "+" + << word.offset / 32 << "u)*4u)&16383u; scc=(" << d << "!=0);\n"; + return; + } + } + if (i.enc == Encoding::Sopk && n != "s_movk_i32") + require_numeric(i, i.dst); + if (i.enc != Encoding::Sopk) + require_numeric(i, i.src[0]); + if (i.enc == Encoding::Sop2 || i.enc == Encoding::Sopc) + require_numeric(i, i.src[1]); + if (n == "s_movk_i32") { + body << d << "=" << hexword(Word(int16_t(i.a))) << ";\n"; + return; + } + if (n == "s_and_saveexec_b32") { + body << "{uint old=s126;s126&=" << a << ";" << d << "=old;active=(s126&laneBit)!=0;scc=s126!=0;}\n"; + return; + } + if (n == "s_andn2_wrexec_b32") { + body << "s126=" << a << "&~s126;" << d << "=s126;active=(s126&laneBit)!=0;scc=s126!=0;\n"; + return; + } + if (n == "s_cmp_eq_i32" || n == "s_cmp_eq_u32") + e = a + "==" + b; + else if (n == "s_cmp_lt_u32") + e = a + "<" + b; + else if (n == "s_cmp_lg_i32" || n == "s_cmp_lg_u32") + e = a + "!=" + b; + else if (n == "s_cmp_lt_i32") + e = "asint(" + a + ")<asint(" + b + ")"; + else if (n == "s_bitcmp1_b32") + e = "((" + a + ">>(" + b + "&31))&1)!=0"; + if (!e.empty()) { + body << "scc=" << e << ";\n"; + return; + } + if (n == "s_mulk_i32") { + body << d << "*=" << hexword(Word(int16_t(i.a))) << ";\n"; + return; + } + if (n == "s_cmpk_lg_i32") { + body << "scc=" << d << "!=" << hexword(Word(int16_t(i.a))) << ";\n"; + return; + } + if (n == "s_min_u32" || n == "s_max_u32") { + body << "{uint lhs=" << a << ",rhs=" << b << ";scc=lhs" << (n == "s_min_u32" ? "<" : ">") << "rhs;" << d + << "=scc?lhs:rhs;}\n"; + return; + } + if (n == "s_sub_u32") { + body << "{uint lhs=" << a << ",rhs=" << b << ";scc=lhs<rhs;" << d << "=lhs-rhs;}\n"; + return; + } + if (n == "s_mul_hi_u32") { + body << d << "=uint((uint64_t(" << a << ")*uint64_t(" << b << "))>>32);\n"; + return; + } + if (n == "s_mul_i32") { + body << d << "=" << a << "*" << b << ";\n"; + return; + } + if (n == "s_add_u32") { + body << "{uint lhs=" << a << ", sum=lhs+" << b << ";scc=sum<lhs;" << d << "=sum;}\n"; + return; + } + if (n == "s_and_b32") + e = a + "&" + b; + else if (n == "s_andn2_b32") + e = a + "&~" + b; + else if (n == "s_or_b32") + e = a + "|" + b; + else if (n == "s_nor_b32") + e = "~(" + a + "|" + b + ")"; + else if (n == "s_not_b32") + e = "~" + a; + else if (n == "s_lshr_b32") + e = a + ">>(" + b + "&31)"; + else if (n == "s_lshl_b32") + e = a + "<<(" + b + "&31)"; + else if (n == "s_bfe_u32") + e = "extractBits(" + a + "," + b + ",(" + b + ">>16)&127u)"; + else if (n == "s_bfm_b32") + e = "((1u<<(" + a + "&31))-1u)<<(" + b + "&31)"; + else if (n == "s_absdiff_i32") + e = "uint(abs(asint(" + a + ")-asint(" + b + ")))"; + else if (n == "s_cselect_b32") { + body << d << "=scc?" << a << ":" << b << ";\n"; + return; + } else if (i.enc == Encoding::Sop2 && i.op >= 0x2e && i.op <= 0x31) { + const unsigned shift = i.op - 0x2d; + body << "scc=(" << a << ">>" << (32 - shift) << ")!=0||((" << a << "<<" << shift << ")+" << b << ")<" << b + << ";\n" + << d << "=(" << a << "<<" << shift << ")+" << b << ";\n"; + return; + } else + refuse(i.pc, string(n)); + body << d << "=" << e << ";scc=" << d << "!=0;\n"; + } + void vector(const Inst &i) { + auto n = i.name; + if ((n == "v_readfirstlane_b32" || n == "v_readlane_b32") && i.dst >= 106) + refuse(i.pc, "invalid scalar lane read destination"); + if (n == "v_readlane_b32") + refuse(i.pc, "unsupported HLSL instruction v_readlane_b32"); + auto selected = [&](unsigned j) { + require_numeric(i, i.src[j]); + auto s = operand(i, i.src[j]); + if (i.subword && j < 2 && i.src_select[j] < 6) { + unsigned sel = i.src_select[j]; + unsigned shift = sel < 4 ? sel * 8 : (sel - 4) * 16; + s = "((" + s + ">>" + to_string(shift) + ")&" + to_string(sel < 4 ? 255 : 65535) + "u)"; + if (i.src_sext[j]) { + const auto sign = sel < 4 ? "128u" : "32768u"; + s = "((" + s + "^" + sign + ")-" + sign + ")"; + } + } + return s; + }; + auto val = [&](unsigned j, bool fp) { + auto s = selected(j); + if (fp) { + s = "asfloat(" + s + ")"; + if ((i.abs >> j) & 1) + s = "abs(" + s + ")"; + if ((i.neg >> j) & 1) + s = "(-" + s + ")"; + } else if (((i.abs | i.neg) >> j) & 1) { + if (n != "v_fma_mix_f32") + refuse(i.pc, "unexpected integer modifier"); + } + return s; + }; + auto d = reg(i.dst); + if (n == "v_cos_f32" || n == "v_cvt_f32_f16") { + if (i.wide) + refuse(i.pc, "unsupported wide conversion or cosine modifiers"); + if (n == "v_cvt_f32_f16") + body << "if(active) " << d << "=asuint(f16tof32(" << selected(0) << "&65535u));\n"; + else { + body << "if(active){float turns=" << val(0,true) + << ";float phase=turns-round(turns);" << d + << "=asuint(abs(phase)==0.25f?0.0f:cos(phase*6.283185307f));}\n"; + } + return; + } + if (n == "v_swap_b32") { + if (i.wide || i.src[0] < 256 || i.src[0] > 511) + refuse(i.pc, "swap requires two VGPRs in a VOP1 encoding"); + const auto src = reg(i.src[0]); + body << "if(active){uint old=" << d << ";" << d << "=" << src << ";" << src << "=old;}\n"; + return; + } + if (n == "v_readfirstlane_b32") { + if (i.abs || i.neg || i.scale || i.clamp) + refuse(i.pc, "readfirstlane modifiers"); + body << d << "=WaveReadLaneAt(" << val(0, false) << ",s126==0?0u:uint(firstbitlow(s126)));\n"; + return; + } + if (i.enc == Encoding::Vopc) { + bool fp = n.find("f32") != n.npos; + auto a = val(0, fp), b = val(1, fp); + string pred; + if (!fp && n.find("_u32") == n.npos) { + a = "asint(" + a + ")"; + b = "asint(" + b + ")"; + } + if (n == "v_cmp_class_f32") { + // Apply floating-point abs/neg to the raw sign bit, including for signed zero and NaNs. + auto bits = selected(0); + if (i.abs & 1) bits = "(" + bits + "&0x7fffffffu)"; + if (i.neg & 1) bits = "(" + bits + "^0x80000000u)"; + if ((i.abs | i.neg) & 2) refuse(i.pc, "unexpected class mask modifier"); + pred = "(fpClass(" + bits + ")&" + selected(1) + ")!=0u"; + } + else if (n.find("_nle_") != n.npos) + pred = "!(" + a + "<=" + b + ")"; + else { + string op = n.find("_lt_") != n.npos ? "<" + : n.find("_le_") != n.npos ? "<=" + : n.find("_gt_") != n.npos ? ">" + : n.find("_ge_") != n.npos ? ">=" + : n.find("_eq_") != n.npos ? "==" + : "!="; + pred = "(" + a + op + b + ")"; + } + body << d << "=WaveActiveBallot((uint(active)&uint(" << pred << "))!=0u).x;\n"; + if (i.dst == 126) + body << "active=(s126&laneBit)!=0;\n"; + return; + } + if (n == "v_cndmask_b32") { + require_numeric(i, i.src[2]); + auto a = val(0, true), b = val(1, true); + body << "if(active) " << d << "=((" << operand(i, i.src[2]) << "&laneBit)!=0)?asuint(" << b << "):asuint(" + << a << ");\n"; + return; + } + if (n == "v_lshrrev_b64") { + auto src = i.src[1]; + if (src == 128 && i.dst < 511) { + body << "if(active){" << d << "=0;" << reg(i.dst + 1) << "=0;}\n"; + return; + } + if (src < 256 || src >= 511 || i.dst >= 511) + refuse(i.pc, "invalid shift pair"); + body << "if(active){uint64_t w=(uint64_t(" << reg(src + 1) << ")<<32)|" << reg(src) << "; w>>=(" + << val(0, false) << "&63u);" << d << "=uint(w);" << reg(i.dst + 1) << "=uint(w>>32);}\n"; + return; + } + if (n == "v_fma_mix_f32") { + std::array<string, 3> args; + for (unsigned j = 0; j < 3; ++j) { + require_numeric(i, i.src[j]); + auto a = operand(i, i.src[j]); + bool half = j == 2 ? (i.a & 0x4000) != 0 : ((i.b >> (27 + j)) & 1) != 0; + args[j] = half ? "f16tof32((" + a + ">>" + to_string(((i.a >> (11 + j)) & 1) * 16) + ")&65535u)" + : "asfloat(" + a + ")"; + if ((i.abs >> j) & 1) + args[j] = "abs(" + args[j] + ")"; + if ((i.neg >> j) & 1) + args[j] = "-" + args[j]; + } + body << "if(active) " << d << "=asuint(mad(" << args[0] << "," << args[1] << "," << args[2] << "));\n"; + return; + } + auto it = alu_rules.find(n); + if (it == alu_rules.end()) + refuse(i.pc, string(n)); + const auto &rule = it->second; + bool fp = rule.type == AluType::Float; + std::array<string, 3> args; + for (unsigned j = 0; j < rule.arity; ++j) { + if (j == 2 && n == "v_fmac_f32") + args[j] = "asfloat(" + d + ")"; + else if ((n == "v_fmamk_f32" && j == 1) || (n == "v_fmaak_f32" && j == 2)) + args[j] = "asfloat(" + hexword(i.literal) + ")"; + else + args[j] = val(n == "v_fmamk_f32" && j == 2 ? 1 : j, fp); + } + string e; + for (size_t k = 0; k < rule.expression.size(); ++k) { + if (rule.expression[k] == '{') { + e += args[rule.expression[k + 1] - '0']; + k += 2; + } else + e += rule.expression[k]; + } + if (i.scale) + e = "(" + e + ")*" + (i.scale == 1 ? "2.0" : i.scale == 2 ? "4.0" : "0.5"); + if (i.clamp) + e = "saturate(" + e + ")"; + if (i.dst_select < 6) { + const unsigned width = i.dst_select < 4 ? 8 : 16; + const unsigned shift = width == 8 ? i.dst_select * 8 : (i.dst_select - 4) * 16; + const Word mask = (1u << width) - 1u; + e = "((" + e + ")&" + hexword(mask) + ")"; + if (i.dst_unused == 1) { + const auto sign = hexword(1u << (width - 1)); + e = "((" + e + "^" + sign + ")-" + sign + ")"; + } + e = "(" + e + "<<" + to_string(shift) + ")"; + if (i.dst_unused == 2) + e += "|(" + d + "&" + hexword(~(mask << shift)) + ")"; + } + body << "if(active) " << d << "=" << (rule.type != AluType::Bits ? "asuint(" + e + ")" : e) << ";\n"; + } + void instruction(size_t index) { + const auto &i = program.code[index]; + const auto &s = program.before[index]; + if (i.enc == Encoding::Mubuf) { + if (i.name == "buffer_store_format" || i.name == "buffer_store_raw") { + const bool raw = i.name == "buffer_store_raw"; + const bool half = (i.op & 0x80) != 0; + constexpr unsigned raw_widths[]{1, 2, 4, 3}; + const unsigned count = raw ? raw_widths[i.op & 3] : (i.op & 3) + 1; + if (i.dst + (half ? (count + 1) / 2 : count) > 256) + refuse(i.pc, "buffer store data register overflow"); + const auto kind = raw ? ComputeViewKind::raw_buffer_uav : + half ? ComputeViewKind::half_buffer_uav : ComputeViewKind::typed_buffer_uav; + auto view = binding(i, s, ((i.b >> 16) & 31) * 4, 4, kind, raw ? 4 : count * (half ? 2 : 4)); + auto address = reg(256 + (i.b & 255)); + if (raw) { + const unsigned scalar = i.b >> 24; + if (scalar > 105 && (scalar < 128 || scalar > 192)) + refuse(i.pc, "unsupported raw store scalar offset"); + require_numeric(i, scalar); + address = "((" + ((i.a & 0x1000) ? address : "0u") + "+" + operand(i, scalar) + + "+" + to_string(i.a & 4095) + "u)&~3u)"; + } + const string suffix = count == 1 ? "" : to_string(count); + string data; + for (unsigned j = 0; j < count; ++j) { + if (j) data += ","; + auto src = reg(256 + i.dst + (half ? j / 2 : j)); + data += half ? "f16tof32((" + src + ">>" + to_string((j%2)*16) + ")&65535u)" : src; + } + if (count > 1) data = (half ? "float" : "uint") + suffix + "(" + data + ")"; + body << "if(active) " << view; + if (raw) body << ".Store" << suffix << "(" << address << "," << data << ");\n"; + else body << "[" << address << "]=" << data << ";\n"; + return; + } + if (i.name == "buffer_load_dword") { + constexpr unsigned widths[] = {1, 2, 4, 3}; + const unsigned count = widths[i.op - 0x0c]; + if (i.dst + count > 256) + refuse(i.pc, "raw load destination overflow"); + auto r = binding(i, s, ((i.b >> 16) & 31) * 4, 4, ComputeViewKind::raw_vector_srv, 4); + // Address generation precedes every writeback, including when vaddr is a destination. + body << "if(active){uint address=(" << reg(256 + (i.b & 255)) << "+" << (i.a & 4095) + << "u)&~3u;"; + const string suffix = count == 1 ? "" : to_string(count); + body << "uint" << suffix << " loaded=" << r << ".Load" << suffix << "(address);"; + for (unsigned k = 0; k < count; ++k) { + body << reg(256 + i.dst + k) << "=loaded"; + if (count > 1) body << "." << "xyzw"[k]; + body << ";"; + } + body << "}\n"; + return; + } + const auto buffer = + binding(i, s, ((i.b >> 16) & 31) * 4, 4, ComputeViewKind::typed_buffer_srv, 4 * (1 + i.op)); + if (i.dst + i.op >= 256) + refuse(i.pc, "formatted load destination overflow"); + body << "if(active){uint4 loaded=" << buffer << ".Load(" << reg(256 + (i.b & 255)) << ");"; + for (unsigned j = 0; j <= i.op; ++j) + body << reg(256 + i.dst + j) << "=loaded[" << j << "];"; + body << "}\n"; + return; + } + if (i.enc == Encoding::Image) { + image(i, s); + return; + } + if (i.enc == Encoding::Smem) { + if (i.op < 8) { + if (s.at(i.src[0]).type != Symbol::Type::table) + refuse(i.pc, "unknown scalar table base"); + if (s.at(i.src[0]).value == compute_sampler_heap) + refuse(i.pc, "sampler heap reads need the direct DXIL path"); + if (s.at(i.src[0]).value == compute_resource_heap && i.b >> 25 == 125) + refuse(i.pc, "unsupported immediate whole-heap descriptor"); + if (i.b >> 25 != 125) { + const auto high = s.at(i.src[0]+1); + if (high.type != Symbol::Type::constant || high.value || ((i.b & 0xfffff) % 32)) + refuse(i.pc,"unproven indexed table address"); + require_numeric(i,i.b>>25); + if (s.at(i.src[0]).value == compute_resource_heap) { + const auto offset = s.at(i.b >> 25); + if ((offset.type != Symbol::Type::masked && offset.type != Symbol::Type::constant) || + (offset.value & 31)) + refuse(i.pc, "whole-heap descriptor offset is not proven 32-byte aligned"); + } + body << "{uint slot=" << reg(i.b>>25) << ">>5;"; + for (unsigned j=0;j<4;++j) body << reg(i.dst+j) << "=slot;"; + body << "}\n"; + } + return; + } + unsigned off = i.b & 0xfffff, count = memory_count(i); + const unsigned offset_reg = i.b >> 25; + const bool dynamic = offset_reg != 125; + if (dynamic) + require_numeric(i, offset_reg); + auto r = binding(i, s, i.src[0], 4, ComputeViewKind::buffer_srv, dynamic ? 4 : off + count * 4); + // The offset can alias any destination SGPR. Snapshot it before committing the first word. + if (dynamic) + body << "{uint address=(" << reg(offset_reg) << "+" << off << "u)&~3u;\n"; + for (unsigned j = 0; j < count; ++j) + body << reg(i.dst + j) << "=" << r << ".Load(" << (dynamic ? "address+" : "") + << (dynamic ? 0 : off) + 4 * j << "u);\n"; + if (dynamic) + body << "}\n"; + return; + } + if (i.enc == Encoding::Lds) { + std::ostringstream line; + line << "#pragma x2w_lds " << std::hex << std::setfill('0') << std::setw(8) << i.a << " " << std::setw(8) + << i.b; + body << "{uint exec=uint(active);" << expand_gfx1013_compute(line.str()) << "}\n"; + return; + } + if (i.enc == Encoding::Sopp) { + if (i.name == "s_barrier") + body << "GroupMemoryBarrierWithGroupSync();\n"; + return; + } + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk || i.enc == Encoding::Sopc) + scalar(i); + else + vector(i); + } +}; +string branch_test(const Inst &i) { + if (i.op == 2) + return "true"; + if (i.op == 4) + return "!scc"; + if (i.op == 5) + return "scc"; + if (i.op == 6 || i.op == 7) + return i.op == 6 ? "s106==0" : "s106!=0"; + return i.op == 8 ? "s126==0" : "s126!=0"; +} +void lower_blocks(Emit &e) { + const auto &p = e.program; + std::set<unsigned> starts{p.code.front().pc}; + for (const auto &i : p.code) + if (i.branch()) { + starts.insert(i.target()); + starts.insert(i.next); + } + std::map<unsigned, unsigned> ends; + for (const auto &i : p.code) + if (i.branch() && i.target() < i.pc) { + if (*std::prev(starts.upper_bound(i.pc)) != i.target() || i.op == 2) + refuse(i.pc, "unsupported loop shape"); + ends[i.target()] = i.pc; + } + auto &out = e.body; + out << "uint pc=" << p.code.front().pc << "u;\n"; + for (size_t k = 0; k < p.code.size(); ++k) { + auto &i = p.code[k]; + if (starts.count(i.pc)) { + out << "if(pc==" << i.pc << "u){\n"; + if (ends.count(i.pc)) + out << "[loop] do {\n"; + } + if (i.branch()) { + if (i.target() < i.pc) + out << "}while(" << branch_test(i) << "); pc=" << i.next << "u;\n"; + else + out << "pc=(" << branch_test(i) << ")?" << i.target() << "u:" << i.next << "u;\n"; + } else { + if (i.name != "v_nop") e.instruction(k); + if (starts.count(i.next)) + out << "pc=" << i.next << "u;\n"; + } + if (k + 1 == p.code.size() || starts.count(i.next)) + out << "}\n"; + } +} +#include "gfx1013_direct_compute.inl" +#include "gfx1013_direct_graphics.inl" +#include "gfx1013_direct_mesh.inl" +} // namespace +static NativeComputeShader translate_program(const ComputeRequest &request, unsigned entry, bool direct_dxil, const GuestShaderStage *stage, + HeapViewContract heap_view) { + if (entry == 36 && ((word(request.code, 0) >> 16) != 0xd580 || (word(request.code, 12) >> 16) != 0xd580 || + (word(request.code, 24) >> 16) != 0xd580 || (word(request.code, 36) >> 16) != 0xbfa0)) + refuse(entry, "unrecognized compute header"); + if(direct_dxil && entry==36){ + for(unsigned at=0;at<entry;){ + auto prefix=gfx1013::instruction(request.code,at); + if(prefix.name!="v_nop" || prefix.size>entry-at)refuse(at,"executable instruction in capture prefix"); + at+=prefix.size; + } + } + unsigned xy = stage ? 0 : word(request.sa, 12); + unsigned z = stage ? stage->threads[2] : word(request.sa, 16) & 65535; + unsigned rsrc2 = stage ? stage->rsrc2 : word(request.sa, 24); + unsigned lds = (rsrc2 >> 15) & 511; + unsigned x = stage ? stage->threads[0] : xy & 65535; + unsigned y = stage ? stage->threads[1] : xy >> 16; + if (x > 1024 || y > 1024 || z > 64) refuse(entry, "compute dimension exceeds desktop limit"); + const uint64_t threads = uint64_t(x) * y * z; + unsigned local_axes = 1 + ((rsrc2 >> 11) & 3); + unsigned user = (rsrc2 >> 1) & 31; + if (!threads || threads > 1024 || z > 64 || local_axes > 3) + refuse(entry, "invalid compute group shape"); + if (rsrc2 & ~0xff9fbeu || lds > 64) + refuse(entry, "unsupported compute resource flags"); + if (!direct_dxil && threads > 32 && threads % 32) + refuse(entry, "partial final wave in multi-wave group"); + Microsoft::WRL::ComPtr<ID3D12VersionedRootSignatureDeserializer> sig; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty{}; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *layout = ∅ + if (!stage || !request.root.empty()) { + HRESULT hr = D3D12CreateVersionedRootSignatureDeserializer(request.root.data(), request.root.size(), + IID_PPV_ARGS(&sig)); + if (SUCCEEDED(hr)) hr = sig->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &layout); + if (hr == E_INVALIDARG) refuse(entry, "invalid root layout"); + if (FAILED(hr)) throw std::runtime_error("invalid root layout: deserializer HRESULT " + std::to_string(hr)); + if (layout->Desc_1_1.NumParameters > 16) refuse(entry, "invalid root layout"); + } + unsigned next = 4; + State initial{}; + for (unsigned k = 0; k <= 105; ++k) + initial[k].type = Symbol::Type::unbound; + initial[124].type = Symbol::Type::unbound; // RDNA2 M0 is a separate 32-bit register. + std::vector<ComputeConstants> constants; + if (stage) { + std::array<bool,32> assigned{}; + for (const auto &input : stage->inputs) { + if (input.type == 1) { + bind_root_address(initial, input, user); + assigned[input.user_data] = assigned[input.user_data + 1] = true; + continue; + } + if (input.type != 0 && input.type != 3 && input.type != 5) continue; + unsigned at = input.user_data; + unsigned count = input.type == 0 ? input.sgpr_count : 1; + if (!count || at >= user || count > user - at || (input.type != 5 && input.root_parameter >= 16)) + refuse(entry, "invalid FSSM user-data range"); + if (input.type == 0) { + constants.push_back({input.root_parameter, at, count}); + for (unsigned j = at; j < at + count; ++j) { + if (assigned[j]) refuse(entry, "overlapping FSSM constants"); + assigned[j] = true; + initial[j] = {}; + } + } else { + Symbol table{Symbol::Type::table, input.type == 5 ? compute_resource_heap : input.root_parameter}; + if (assigned[at] && !(initial[at] == table)) refuse(entry, "ambiguous FSSM table"); + initial[at] = table; + assigned[at] = true; + } + } + } + unsigned system = user; + for (unsigned flag : {128u, 256u, 512u, 1024u}) + if (rsrc2 & flag) + initial[system++] = {}; + for (unsigned i = 0; !stage && i < layout->Desc_1_1.NumParameters; ++i) { + const auto ¶m = layout->Desc_1_1.pParameters[i]; + if (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) { + if (next >= user) + refuse(entry, "descriptor table exceeds user SGPRs"); + initial[next++] = {Symbol::Type::table, i}; + } else if (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + unsigned count = param.Constants.Num32BitValues; + if (next > user || count > user - next) + refuse(entry, "root constants exceed user SGPRs"); + constants.push_back({i, next, count}); + for (unsigned j = 0; j < count; ++j) + initial[next + j] = {}; + next += count; + } else if (direct_dxil && (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || + param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || + param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV)) { + // Same packed entry layout as gfx2hlsl.Stage.setup: a root address + // occupies two consecutive SGPRs, even when only later parameters are used. + if (next > user || user - next < 2) + refuse(entry, "root descriptor pair exceeds user SGPRs"); + bind_root_address(initial, {1, 0, 2, 0, static_cast<uint8_t>(next), static_cast<uint8_t>(i)}, user); + next += 2; + } else + refuse(entry, "root-address parameter"); + } + // In this compute ABI the two directly indexed heaps follow the user root parameters. + // Require both flags and exactly two remaining user SGPRs, as in the matched native layouts. + if (!stage && (UINT(layout->Desc_1_1.Flags) & 0xc00u) == 0xc00u && next + 2 == user) { + initial[next] = {Symbol::Type::table, compute_resource_heap}; + initial[next + 1] = {Symbol::Type::table, compute_sampler_heap}; + } + // The legacy HLSL profile models wave32. Direct DXIL supports both guest wave sizes. A wave64 request whose + // group has at most 32 threads stays on the wave32 model, as before the wave size was read: its one guest wave + // has lanes 0..31 only, so EXEC's high word is zero and v_mbcnt_hi adds nothing for its lanes. The model + // does not write the zero high word that a wave64 compare or carry-out stores in an SGPR pair destination. + const bool packed_state = !stage && direct_dxil && word(request.sa,0)==0x4005cf00 && + word(request.sa,4)==0x6c090102; + const bool wave64 = stage ? !stage->wave32 : direct_dxil && !request.wave32 && threads > 32; + const bool narrow_wave64 = !stage && direct_dxil && !request.wave32 && !wave64; + // The byte-address rewrite of a GPU-selected heap descriptor is read only under the raw_buffer contract. + const bool heap_window = direct_dxil && heap_view == HeapViewContract::raw_buffer; + auto program = parse(request.code, entry, initial, direct_dxil, false, wave64, false, heap_window, narrow_wave64); + Emit emit{{}, program,layout->Desc_1_1}; + emit.result.constants = constants; + if (!lds) + for (const auto &inst : program.code) + if (inst.enc == Encoding::Lds) + refuse(inst.pc, "LDS instruction without allocation"); + if (direct_dxil) { + const bool guest_wave32 = stage ? stage->wave32 : request.wave32; + DirectCompute compiler{emit}; + compiler.wave64 = wave64; + compiler.narrow_wave64 = narrow_wave64; + compiler.heap_view = heap_view; + compiler.heap_window = heap_window; + for (size_t i = 0; i < program.code.size(); ++i) { + const auto& inst = program.code[i]; + if (!program.reached[i]) continue; + // The narrow wave64 model still requires a guest-aligned carry destination pair. + if (!guest_wave32 && carry_destination(inst) == 107) + refuse(inst.pc, "unsupported carry mask destination"); + // s107 is a numeric wave32 mask only for a guest wave32. + if (!guest_wave32 && inst.name == "v_cndmask_b32" && inst.src[2] == 107) + refuse(inst.pc, "unsupported wave32 conditional mask source"); + if (!guest_wave32 && inst.name.find("_ci_") != Name::npos && inst.src[2] == 107) + refuse(inst.pc, "unsupported carry-in mask source"); + if (inst.enc != Encoding::Mubuf || inst.name != "buffer_store_raw") continue; + const auto& symbol = program.before[i].at(((inst.b >> 16) & 31) * 4); + if (symbol.type == Symbol::Type::descriptor) + compiler.read_write_raw_views.emplace(symbol.value, symbol.offset); + } + if (threads % (wave64 ? 64 : 32)) + for (const auto &i : program.code) + if (i.name == "v_readlane_b32" || i.name == "v_writelane_b32") + DirectCompute::validate_lane_shape(i, static_cast<unsigned>(threads), wave64 ? 64 : 32); + if (threads > 32 && threads % 32) + refuse(entry, "partial final wave in multi-wave group"); + if (wave64 && threads % 64) refuse(entry, "wave64 exchange requires complete guest waves"); + if (wave64 && threads > 64) { + const auto &code = program.code; + const bool branches = std::any_of(code.begin(), code.end(), + [](const Inst &i) { return i.branch() && i.op != 2; }); + const bool synchronizes = std::any_of(code.begin(), code.end(), [](const Inst &i) { + return i.enc == Encoding::Vopc || i.enc == Encoding::Lds || carry_destination(i) || + i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32" || i.name == "s_barrier"; + }); + if (branches && synchronizes) { + if (!packed_state) refuse(entry, "multi-wave64 exchange requires converged group control flow"); + compiler.virtual_waves = static_cast<unsigned>(threads / 64); + } + } + auto translated = compiler.lower(entry,user,rsrc2,x,y,z); + for (auto &binding : translated.bindings) { + if (stage) apply_reflected_table_use(binding, *stage); + if (!request.root.empty()) { + const auto &desc = layout->Desc_1_1; + if (binding.kind == ComputeViewKind::buffer_srv && binding.root_parameter < desc.NumParameters) { + const auto ¶m = desc.pParameters[binding.root_parameter]; + if (param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + apply_scalar_table_layout(binding, param.DescriptorTable); + } + if (binding.kind != ComputeViewKind::root_buffer_srv) continue; + if (binding.root_parameter >= desc.NumParameters) + refuse(entry, "missing compute root descriptor"); + const auto ¶m = desc.pParameters[binding.root_parameter]; + if ((param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_CBV && + param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) || + param.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL) + refuse(entry, "compute root descriptor type or visibility"); + } + } + translated.group = {x, y, z}; + return translated; + } + lower_blocks(emit); + std::ostringstream h; + h << R"( +uint extractBits(uint v,uint offset,uint width){return width>=32?v>>(offset&31u):(v>>(offset&31u))&((1u<<width)-1u);} +float med3(float a,float b,float c){return max(min(a,b),min(max(a,b),c));} +uint fpClass(uint v){ + uint a=v&0x7fffffffu;bool neg=(v>>31)!=0; + if(a>0x7f800000u)return (a&0x400000u)?2u:1u; + if(a==0x7f800000u)return neg?4u:512u; + if(a>=0x800000u)return neg?8u:256u; + if(a!=0)return neg?16u:128u; + return neg?32u:64u; +} +)"; + for (auto &b : emit.result.bindings) { + auto r = b.shader_register; + if (b.array_position) continue; + if (b.kind == ComputeViewKind::raw_buffer_uav) + h << "RWByteAddressBuffer w" << r << ":register(u" << r << ");\n"; + else if (compute_buffer_uav(b.kind)) { + const bool half = b.kind == ComputeViewKind::half_buffer_uav; + const unsigned n = b.required_bytes / (half ? 2 : 4); + h << "RWBuffer<" << (half ? "float" : "uint") << (n == 1 ? "" : to_string(n)) << "> w" + << r << ":register(u" << r << ");\n"; + } else if (b.kind == ComputeViewKind::half_scalar_uav) + h << "RWTexture2D<float> w" << r << ":register(u" << r << ");\n"; + else if (b.kind == ComputeViewKind::texture_uav) + h << "RWTexture2D<float4> w" << r << ":register(u" << r << ");\n"; + else + h << (b.kind == ComputeViewKind::heap_stride_srv || b.kind == ComputeViewKind::buffer_srv || b.kind == ComputeViewKind::raw_vector_srv ? "ByteAddressBuffer" + : b.kind == ComputeViewKind::typed_buffer_srv ? "Buffer<uint4>" + : "Texture2D<float4>") + << " r" << r << (b.array_count>1 ? "["+to_string(b.array_count)+"]" : "") << ":register(t" << r << ");\n"; + } + for (size_t j = 0; j < emit.result.samplers.size(); ++j) + h << "SamplerState q" << j << ":register(s" << j << ");\n"; + unsigned constant_words = 0; + for (const auto &block : constants) + constant_words += block.count; + if (constant_words) + h << "cbuffer EntryConstants:register(b0){uint4 rootWords[" << (constant_words + 3) / 4 << "];};\n"; + if (lds) + h << "groupshared uint lds[" << lds * 128 << "];\n"; + if (threads > 64) + h << "groupshared uint waveStarts[" << threads << "];\n"; + h << "[WaveSize(32)] [numthreads(" << x << "," << y << "," << z + << ")] void main(uint3 g:SV_GroupID,uint idx:SV_GroupIndex){\n"; + for (unsigned j = 0; j < 128; ++j) + h << "uint s" << j << "=0;\n"; + for (unsigned j = 0; j < 256; ++j) + h << "uint v" << j << "=0;\n"; + if (threads <= 32) + h << "uint wave=0u;\n"; + else if (threads == 64) + h << "uint wave=WaveActiveMin(idx)==0u?0u:1u;\n"; + else { + // Order host waves by their lowest group index. Physical lane order need not be row-major. + h << "uint first=WaveActiveMin(idx);waveStarts[idx]=uint(idx==first);GroupMemoryBarrierWithGroupSync();" + "uint wave=0;for(uint p=0;p<first;++p)wave+=waveStarts[p];\n"; + } + h << "uint lane=WaveGetLaneIndex();uint guestIndex=wave*32u+lane;uint laneBit=1u<<lane;" + "bool active=true,scc=false;float4 t=0;s126=WaveActiveBallot(true).x;v0=guestIndex%" + << x << "u;\n"; + if (local_axes >= 2) + h << "v1=(guestIndex/" << x << "u)%" << y << "u;\n"; + if (local_axes == 3) + h << "v2=guestIndex/" << x * y << "u;\n"; + unsigned sys = user; + for (unsigned axis = 0; axis < 3; ++axis) + if (rsrc2 & (1u << (7 + axis))) + h << "s" << sys++ << "=g." << "xyz"[axis] << ";\n"; + if (rsrc2 & 1024) + h << "s" << sys << "=" << (threads + 31) / 32 << "u|(wave<<20)|(wave==0u?0x80000000u:0u);\n"; + unsigned offset = 0; + for (const auto &block : constants) + for (unsigned j = 0; j < block.count; ++j, ++offset) + h << "s" << block.first_sgpr + j << "=rootWords[" << offset / 4 << "][" << offset % 4 << "];\n"; + h << emit.body.str() << "}\n"; + emit.result.hlsl = h.str(); + emit.result.instruction_count = static_cast<unsigned>(program.code.size()); + emit.result.group = {x, y, z}; + return std::move(emit.result); +} + +// Native FSSM UsedResource and RootParam use dword table offsets and an +// explicit user SGPR. See victory-shader native.rs and victory-gpu draw.rs. +bool x2w::apply_reflected_table_use(ComputeViewBinding &binding, const GuestShaderStage &stage, + std::optional<unsigned> packed_sgpr) { + if (binding.array_count != 1 || binding.kind == ComputeViewKind::heap_stride_srv || + binding.kind == ComputeViewKind::root_buffer_srv || binding.root_parameter == compute_resource_heap) + return false; + const ShaderResourceUse *match = nullptr; + for (const auto &use : stage.resources) { + if (use.root_type != 3 || use.root_parameter != binding.root_parameter || + uint64_t(use.offset_dwords) * 4 != binding.byte_offset) continue; + if (packed_sgpr) { + if (use.user_data != *packed_sgpr) continue; + } else if (std::none_of(stage.inputs.begin(), stage.inputs.end(), [&](const auto &input) { + return input.type == 3 && input.root_parameter == use.root_parameter && input.user_data == use.user_data; + })) { + throw UnsupportedComputeShader("reflected table record has no matching user SGPR"); + } + if (match) throw UnsupportedComputeShader("ambiguous reflected table record"); + match = &use; + } + if (!match) return false; + const bool scalar = accepts_cbv_window(binding.kind); + const bool buffer = scalar || compute_buffer_uav(binding.kind) || binding.kind == ComputeViewKind::raw_vector_srv || + binding.kind == ComputeViewKind::typed_buffer_srv || binding.kind == ComputeViewKind::byte_window_srv || + binding.kind == ComputeViewKind::indexed_raw_srv; + if (match->dwords != (buffer ? 4u : 8u) || + (match->type != (compute_uav(binding.kind) ? 3u : 0u) && !(scalar && match->type == 2))) + throw UnsupportedComputeShader("raw load disagrees with reflected table record at root " + std::to_string(binding.root_parameter) + " offset " + std::to_string(binding.byte_offset) + " kind " + std::to_string(static_cast<unsigned>(binding.kind)) + " reflected type " + std::to_string(match->type) + " width " + std::to_string(match->dwords)); + if (scalar) + binding.scalar_table = match->type == 2 ? ComputeViewBinding::ScalarTable::reflected_cbv + : ComputeViewBinding::ScalarTable::srv; + return true; +} + +void x2w::apply_scalar_table_layout(ComputeViewBinding &binding, const D3D12_ROOT_DESCRIPTOR_TABLE1 &table) { + using Table = ComputeViewBinding::ScalarTable; + if (!accepts_cbv_window(binding.kind) || binding.scalar_table != Table::unknown || binding.byte_offset % 32) + return; + uint64_t end = 0; + const auto slot = binding.byte_offset / 32; + bool cbv = false, srv = false; + for (unsigned i = 0; i < table.NumDescriptorRanges; ++i) { + const auto &range = table.pDescriptorRanges[i]; + const uint64_t first = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? end : range.OffsetInDescriptorsFromTableStart; + end = first + range.NumDescriptors; + if (first <= slot && slot < end) { + cbv |= range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_CBV; + srv |= range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + } + } + if (cbv != srv) binding.scalar_table = cbv ? Table::declared_cbv : Table::srv; +} + +x2w::NativeComputeShader x2w::translate_compute(const ComputeRequest &request, unsigned entry, bool direct_dxil) { + return translate_program(request, entry, direct_dxil, nullptr, HeapViewContract::none); +} + +x2w::NativeComputeShader x2w::translate_compute_container(ComputeContainer container, HeapViewContract heap_view) { + auto stages = read_guest_shader_container(container.bytes); + GuestShaderStage *compute = nullptr; + for (auto &stage : stages) { + if (stage.stage != GpuStage::cs) continue; + if (compute) refuse(0, "ambiguous native compute program"); + compute = &stage; + } + if (!compute) refuse(0, "expected one compute program"); + ComputeRequest request{}; + request.code = std::move(compute->code); + request.root = std::move(container.root); + return translate_program(request, 0, true, compute, heap_view); +} + +x2w::NativeComputeShader x2w::translate_graphics_container(const std::string &bytes,bool pixel) { + auto stages=read_guest_shader_container(bytes); + GuestShaderStage *selected=nullptr; + for(auto &stage:stages)if(stage.stage==(pixel?GpuStage::ps:GpuStage::vs)){ + if(selected)refuse(0,"ambiguous native graphics stage"); + selected=&stage; + } + if(!selected)refuse(0,"missing native graphics stage"); + return lower_graphics(*selected); +} + +x2w::NativeComputeShader x2w::translate_mesh_program(const std::string &code, const MeshStageLayout &layout) { + return lower_mesh(code,layout); +} + +x2w::NativeComputeShader x2w::translate_mesh_program(const std::string &code, const MeshStageLayout &layout, + const D3D12_ROOT_SIGNATURE_DESC1 &root) { + return lower_mesh(code,layout,nullptr,root); +} + +x2w::NativeComputeShader x2w::translate_mesh_container(const std::string &bytes, bool validate_uint_heap_reads) { + const auto stages=read_guest_shader_container(bytes); + const GuestShaderStage *mesh=nullptr; + for (const auto &s : stages) if (s.stage==GpuStage::ms) { + if (mesh) refuse(0,"ambiguous mesh stage"); + mesh=&s; + } + if (!mesh) refuse(0,"missing mesh stage"); + MeshStageLayout layout{mesh->threads[0],mesh->max_vertices,mesh->max_primitives, + mesh->topology,mesh->mesh_group_stride,mesh->wave32}; + layout.validate_uint_heap_reads=validate_uint_heap_reads; + return lower_mesh(mesh->code,layout,mesh); +} + +x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::string_view b) { + return translate_graphics_pair(a, b, {}); +} + +// Fixed-descriptor draws publish the bounded native stages in export order, +// without FSSM signatures. Link PARAM exports to interpolator reads using +// the captured entry layout and the channels actually named by each stage. +static bool raw_center_inputs(unsigned enable_mask) { + // SPI_PS_INPUT_ADDR allocates the enabled X/Y/Z/W components after + // the center I/J pair. The packed screen coordinate is a later VGPR. + // victory-shader 9376fd6 io.rs::PS_VGPRS uses the same allocation. + constexpr unsigned position_inputs = (0xfu << 8) | (1u << 15); + return (enable_mask & ~position_inputs) == 2; +} +static GuestShaderStage read_raw_graphics(std::string_view bytes, const D3D12_ROOT_SIGNATURE_DESC1 &layout, + unsigned enable_mask, unsigned address_mask, bool mesh_pixel = false) { + if (bytes.empty() || bytes.size() % 4 || bytes.size() > (1u << 20)) + throw UnsupportedComputeShader("invalid raw graphics extent"); + GuestShaderStage stage{}; + unsigned extent = 0; + bool position = false, color = false, ended = false; + struct Parameter { unsigned exported = 0, smooth = 0, flat = 0; }; + std::vector<Parameter> params(mesh_pixel ? 31 : 7); + const bool has_params = raw_center_inputs(enable_mask) || mesh_pixel; + std::map<unsigned, unsigned> visited; + std::deque<unsigned> pending{0}; + while (!pending.empty()) { + const unsigned pc = pending.front(); + pending.pop_front(); + auto next = visited.lower_bound(pc); + if (next != visited.end() && next->first == pc) continue; + if (pc >= bytes.size() || (next != visited.begin() && std::prev(next)->second > pc)) + refuse(pc, "raw graphics branch outside code or into an instruction"); + auto op = gfx1013::instruction(bytes, pc); + if (next != visited.end() && pc + op.size > next->first) + refuse(pc, "overlapping raw graphics instructions"); + visited.emplace_hint(next, pc, pc + op.size); + extent = (std::max)(extent, pc + op.size); + if (op.form == gfx1013::Form::ds || op.name == "s_swappc_b64" || (!has_params && (op.form == gfx1013::Form::vintrp || + op.name.substr(0,9) == "s_cbranch" || op.name == "s_branch" || op.name.find("exec") != Name::npos || + op.name.substr(0,7) == "v_cmpx_" || op.name.find("wqm") != Name::npos))) + refuse(pc, "raw graphics requires a verified stage interface or wave state"); + if (op.form == gfx1013::Form::vintrp) { + Word w; std::memcpy(&w, bytes.data()+pc, sizeof(w)); + const unsigned attr = (w >> 10) & 63; + if (attr >= params.size()) refuse(pc, "raw interpolation attribute exceeds entry count"); + auto &mask = ((w >> 16) & 3) == 2 ? params[attr].flat : params[attr].smooth; + mask |= 1u << ((w >> 8) & 3); + } + if (op.form == gfx1013::Form::exp) { + Word w; std::memcpy(&w, bytes.data()+pc, sizeof(w)); + const unsigned target = (w >> 4) & 63; + if (target == 12) position = true; + else if (target < 8) color = true; + else if (target == 9 && !(w & 15)) {} // Null export on a pixel kill path. + else if (has_params && target >= 32 && target - 32 < params.size() && + !params[target - 32].exported && !(w & 0x400)) params[target - 32].exported = w & 15; + else refuse(pc, "raw graphics varying or system export requires a stage interface"); + } + if (op.name == "s_endpgm") { + ended = true; + continue; + } + if (op.name == "s_branch" || op.name.substr(0,9) == "s_cbranch") { + int16_t displacement; + std::memcpy(&displacement, bytes.data() + pc, sizeof(displacement)); + pending.push_back(pc + op.size + 4 * displacement); + } + if (op.name != "s_branch") pending.push_back(pc + op.size); + } + if (!ended || position == color) refuse(extent, "ambiguous raw graphics stage"); + stage.stage = position ? GpuStage::vs : GpuStage::ps; + stage.fixed_vertex_abi = position && has_params; + stage.code.assign(bytes.substr(0,extent)); + if (color) { + stage.pixel_input_address = address_mask; + stage.pixel_input_enable = enable_mask; + } + if ((color && (enable_mask & 0x8f00)) || (position && has_params)) + (color ? stage.input_signature : stage.output_signature).push_back({"SV_Position",0,1,3,0,15,15}); + for (uint8_t attr = 0; attr < params.size(); ++attr) { + const auto &p = params[attr]; + if ((position && (p.smooth || p.flat)) || (color && p.exported) || (p.smooth & p.flat)) + refuse(0, "ambiguous raw varying interface"); + if (mesh_pixel && p.smooth && p.flat) + refuse(0, "mixed interpolation modes in one packed mesh PARAM"); + // A PARAM may mix smooth channels and provoking-vertex fetches. + for (unsigned ch = 0; ch < 4; ++ch) { + const uint8_t bit = uint8_t(1u << ch); + if (!((p.exported | p.smooth | p.flat) & bit)) continue; + const unsigned index = 4 * attr + ch; + const uint8_t row = uint8_t(1 + (mesh_pixel ? attr : index)); + (position ? stage.outputs : stage.attributes).push_back({6,row,bit,attr,0,uint8_t(bool(p.flat & bit))}); + (position ? stage.output_signature : stage.input_signature).push_back({"TEXCOORD",index,0,3,row,bit,bit}); + } + } + // Same fixed-descriptor user data layout as the legacy graphics path. + unsigned sgpr = 8; + for (unsigned j=0; j<layout.NumParameters; ++j) { + const auto &p=layout.pParameters[j]; + const bool table=p.ParameterType==D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + const bool constants=p.ParameterType==D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + const unsigned count=table ? 1 : constants ? p.Constants.Num32BitValues : 2; + if (!count || count>106-sgpr || j>=16) refuse(0,"raw graphics user data exceeds register range"); + if (p.ShaderVisibility==D3D12_SHADER_VISIBILITY_ALL || + p.ShaderVisibility==(position ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL)) + stage.inputs.push_back({table ? 3u : constants ? 0u : 1u,0,count,0,uint8_t(sgpr),uint8_t(j)}); + sgpr+=count; + } + if (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { + if (sgpr >= 106) refuse(0, "resource heap outside graphics user data"); + stage.inputs.push_back({5,0,1,0,uint8_t(sgpr++),0}); + } + if (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { + if (sgpr >= 106) refuse(0, "sampler heap outside graphics user data"); + stage.inputs.push_back({6,0,1,0,uint8_t(sgpr),0}); + } + return stage; +} + +x2w::NativeComputeShader x2w::translate_mesh_pixel_program(std::string_view code, unsigned enable, unsigned address, + unsigned wave_size, const D3D12_ROOT_SIGNATURE_DESC1 *root) { + if (address > 0xffff || (enable & ~address) || (wave_size != 32 && wave_size != 64)) + refuse(0,"invalid fixed mesh pixel entry"); + const D3D12_ROOT_SIGNATURE_DESC1 layout = root ? *root : D3D12_ROOT_SIGNATURE_DESC1{}; + auto ps = read_raw_graphics(code, layout, enable, address, true); + if (ps.stage != GpuStage::ps) refuse(0,"mesh pixel program has no color export"); + ps.wave32 = wave_size == 32; + return lower_graphics(ps, 0, 0, nullptr, layout, 0, root != nullptr); +} + +x2w::DirectGraphicsPair x2w::translate_graphics_pair(std::string_view a,std::string_view b, + const D3D12_ROOT_SIGNATURE_DESC1 &layout, std::string_view pixel_entry, + std::optional<GpuStage> first_stage, + const std::array<unsigned char, 8> &target_components, + std::optional<std::array<bool,2>> stage_wave32) { + const bool raw = a.substr(0,4)!="DXBC" && b.substr(0,4)!="DXBC"; + unsigned enable_mask=0, address_mask=0; + if (!pixel_entry.empty()) { + if (!raw || pixel_entry.size()!=13 || pixel_entry.substr(0,5)!="psin1") + refuse(0,"invalid raw pixel entry record"); + std::memcpy(&enable_mask,pixel_entry.data()+5,4); + std::memcpy(&address_mask,pixel_entry.data()+9,4); + if (enable_mask > 0xffff || address_mask > 0xffff || (enable_mask & ~address_mask)) + refuse(0,"contradictory pixel input enable/address masks"); + } + auto read_stage = [&](std::string_view bytes) { + return raw ? std::vector<GuestShaderStage>{read_raw_graphics(bytes,layout,enable_mask,address_mask)} : read_guest_shader_container(bytes); + }; + auto left=read_stage(a),right=read_stage(b); + if(left.size()!=1 || right.size()!=1)refuse(0,"expected a distinct stage per graphics container"); + if (first_stage && left.front().stage != *first_stage) + refuse(0,"raw exports disagree with reflected stage"); + auto *vs=&left.front(),*ps=&right.front(); + if(vs->stage==GpuStage::ps)std::swap(vs,ps); + if(vs->stage!=GpuStage::vs || ps->stage!=GpuStage::ps)refuse(0,"expected vertex and pixel stages"); + ps->target_components=target_components; + if (raw && stage_wave32) { + vs->wave32 = (*stage_wave32)[0]; + ps->wave32 = (*stage_wave32)[1]; + } + return translate_reflected_graphics(*vs,*ps,layout); +} +x2w::DirectGraphicsPair x2w::translate_reflected_graphics(GuestShaderStage &vs, GuestShaderStage &ps, + const D3D12_ROOT_SIGNATURE_DESC1 &layout) { + GraphicsConstantLayout constants; + for (const auto *stage:{&vs,&ps}) + for(const auto &input:stage->inputs) + if(input.type==0) constants.include(input.root_parameter,input.sgpr_count); + auto vertex=lower_graphics(vs,0,0,&constants,layout); + const unsigned vertex_uavs = static_cast<unsigned>(std::count_if(vertex.bindings.begin(), vertex.bindings.end(), + [](const auto &binding) { return compute_uav(binding.kind); })); + auto pixel = lower_graphics(ps, static_cast<unsigned>(vertex.bindings.size()) - vertex_uavs, + static_cast<unsigned>(vertex.samplers.size()), &constants, layout, vertex_uavs); + for (auto &binding : vertex.bindings) apply_reflected_table_use(binding, vs); + for (auto &binding : pixel.bindings) apply_reflected_table_use(binding, ps); + validate_raster_link(vertex, pixel); + return {std::move(vertex),std::move(pixel)}; +} +void x2w::validate_raster_link(const NativeComputeShader &vertex, const NativeComputeShader &pixel) { + for(const auto &input:pixel.inputs){ + if(input.name=="SV_IsFrontFace" || input.kind==28) continue; + auto producer=std::find_if(vertex.outputs.begin(),vertex.outputs.end(),[&](auto &out){ + return out.name==input.name && out.index==input.index && out.row==input.row && out.component==input.component && + ((out.used<<out.first)&(input.used<<input.first))==(input.used<<input.first); + }); + if(producer==vertex.outputs.end())refuse(0,"graphics stages disagree on "+input.name+to_string(input.index)); + } +} diff --git a/src/gfx1013_compute_native.h b/src/gfx1013_compute_native.h new file mode 100644 index 0000000000..d7ccd7f907 --- /dev/null +++ b/src/gfx1013_compute_native.h @@ -0,0 +1,207 @@ +#pragma once +#include "mesh_pixel_heap.h" +#include "shader_compute_request.h" +#include <array> +#include <optional> +#include <stdexcept> +#include <string_view> +#include <vector> + +struct D3D12_ROOT_SIGNATURE_DESC1; +struct D3D12_ROOT_DESCRIPTOR_TABLE1; +namespace x2w { +enum class GpuStage; +struct GuestShaderStage; +class UnsupportedComputeShader : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; +enum class ComputeViewKind { + buffer_srv, + typed_buffer_srv, + texture_srv, + texture_uav, + raw_vector_srv, + half_scalar_uav, + heap_stride_srv, + raw_buffer_uav, + typed_buffer_uav, + half_buffer_uav, + root_buffer_srv, + comparison_texture_srv, + half2_texture_uav, + half4_texture_uav, + cube_sample_srv, + cube_comparison_srv, + indexed_atomic_uav, + d16_sample_srv, + byte_window_srv, + heap_buffer_srv, // A raw buffer read through ResourceDescriptorHeap[slot]; the slot is a GPU value. + // The directly indexed sampler heap; entry n = title byte offset 16 * n (index parity); the runtime fills entries with + // dynamic_sampler() (LOD clamp applied, valid for the explicit-LOD forms translated here); entry 2047 is the runtime + // fallback and never read. + heap_sampler, + uint_texture_uav, + float_texture_uav, + float2_texture_uav, + float3_texture_uav, + packed_d16_x_uav, // Single low-halfword payload; desktop buffer view determines the element size. + indexed_raw_srv // Fixed-stride record read. required_bytes is one complete record and its checked stride. +}; +inline unsigned exact_texture_uav_channels(ComputeViewKind kind) { + switch (kind) { + case ComputeViewKind::float_texture_uav: return 1; + case ComputeViewKind::float2_texture_uav: return 2; + case ComputeViewKind::float3_texture_uav: return 3; + default: return 0; + } +} +inline bool accepts_cbv_window(ComputeViewKind kind) { + return kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::byte_window_srv; +} +inline constexpr unsigned compute_resource_heap = ~0u; +// the directly indexed sampler heap; entry n is title byte offset 16 * n +inline constexpr unsigned compute_sampler_heap = ~0u - 1; +// A binding of the whole descriptor heap: it has no table register and no root parameter. +inline bool compute_heap_binding(ComputeViewKind kind) { return kind == ComputeViewKind::heap_buffer_srv; } +inline bool compute_buffer_uav(ComputeViewKind kind) { + return kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::typed_buffer_uav || + kind == ComputeViewKind::half_buffer_uav || kind == ComputeViewKind::packed_d16_x_uav || + kind == ComputeViewKind::indexed_atomic_uav; +} +struct IndexedAtomicView { + unsigned stride = 0, count = 0; // Bytes per guest index and number of valid indices. +}; +inline bool compute_uav(ComputeViewKind kind) { + return kind == ComputeViewKind::texture_uav || kind == ComputeViewKind::half_scalar_uav || + kind == ComputeViewKind::half2_texture_uav || kind == ComputeViewKind::half4_texture_uav || + kind == ComputeViewKind::uint_texture_uav || exact_texture_uav_channels(kind) || compute_buffer_uav(kind); +} +struct ComputeViewBinding { + ComputeViewKind kind; + unsigned root_parameter; + unsigned byte_offset; + unsigned shader_register; + unsigned required_bytes; + unsigned array_count = 1, array_position = 0; + unsigned image_dimension = 1; // ISA dimension field; 1 denotes Texture2D. + enum class ScalarTable { unknown, reflected_cbv, declared_cbv, srv }; + ScalarTable scalar_table = ScalarTable::unknown; +}; +bool apply_reflected_table_use(ComputeViewBinding &binding, const GuestShaderStage &stage, + std::optional<unsigned> packed_sgpr = {}); +void apply_scalar_table_layout(ComputeViewBinding &binding, const D3D12_ROOT_DESCRIPTOR_TABLE1 &table); +struct ComputeSampler { + std::array<unsigned, 4> words; + bool explicit_lod; + bool comparison = false; +}; +struct ComputeConstants { + unsigned root_parameter; + unsigned first_sgpr; + unsigned count; +}; +// Both graphics stages read a single desktop b0. Pack each guest root once, +// in parameter order, irrespective of the SGPR order in either stage. +struct GraphicsConstantLayout { + std::array<unsigned, 16> counts{}; + unsigned offset(unsigned parameter) const { + unsigned position = 0; + for (unsigned r = 0; r < parameter; ++r) + position += counts.at(r); + return position; + } + void include(unsigned parameter, unsigned count) { + if (parameter >= counts.size() || !count || count > 32) + throw UnsupportedComputeShader("invalid graphics root constant range"); + if (counts[parameter] < count) + counts[parameter] = count; + if (offset(static_cast<unsigned>(counts.size())) > 32) + throw UnsupportedComputeShader("linked graphics root exceeds 32 words"); + } +}; +struct GraphicsLinkage { + std::string name; + unsigned index, row, first, width, component, used, kind, interpolation; +}; +struct MeshHeapRead { + unsigned root_parameter, dword, mask; // R32_UINT SRV at (root constant & mask). +}; +struct NativeComputeShader { + std::vector<PixelHeapSpan> pixel_heap_spans; + std::vector<MeshHeapRead> mesh_heap_reads; + std::vector<GraphicsLinkage> inputs, outputs; + std::vector<ComputeConstants> constants; + // Additional b0 words, after root constants, read from these bound SRVs. + std::vector<unsigned> stride_srvs; + std::string hlsl, dxil_ir; + std::vector<ComputeViewBinding> bindings; + std::vector<ComputeSampler> samplers; + bool sampler_heap = false; + unsigned instruction_count{}; + std::array<unsigned, 3> group{}; + bool vertex_fetch = false; + std::array<unsigned, 8> pixel_writes{}; +}; +// The view class a GPU-selected descriptor heap slot is read as. none: the slot and its view type are not known, so a +// heap read is refused. raw_buffer: the capture says the selected slot is a raw buffer SRV. other: the capture names a +// view type that is not translated (refused when the shader reads the heap). +// Under raw_buffer the direct path also reads the byte-address rewrite of the selected descriptor (stride read, +// max(stride, 1), byte count, stride cleared, raw out-of-bounds mode) as the same raw view. The caller guarantees that +// every slot the program can select is a raw view whose size is the guest range num_records * max(stride, 1); the +// translator does not check that, nor the swizzle bits (word 1 bits 31:30) or the other word 3 fields, and a program +// with two heap loads from different selectors is outside what one captured selection covers. +enum class HeapViewContract : unsigned { none, raw_buffer, other }; +NativeComputeShader translate_compute(const ComputeRequest &request, unsigned entry_byte_offset, + bool direct_dxil = false); +NativeComputeShader translate_compute_container(ComputeContainer container, + HeapViewContract heap_view = HeapViewContract::none); +struct NativeVertexElement { + std::string semantic; + unsigned index, format, slot, offset, classification, step_rate; + bool used = false; +}; +struct DirectGraphicsPair { + NativeComputeShader vertex, pixel; + std::vector<NativeVertexElement> input_layout; + // GuestShaderStage::target_components of the pixel stage: the target types an RTV variant asked for. + std::array<unsigned char, 8> target_components{}; + GraphicsConstantLayout constant_layout() const { + GraphicsConstantLayout layout; + for (auto *stage : {&vertex, &pixel}) + for (const auto &block : stage->constants) + layout.include(block.root_parameter, block.count); + return layout; + } +}; +DirectGraphicsPair translate_graphics_pair(std::string_view a, std::string_view b, + const D3D12_ROOT_SIGNATURE_DESC1 &layout, std::string_view pixel_entry = {}, + std::optional<GpuStage> first_stage = {}, + const std::array<unsigned char, 8> &target_components = {}, + std::optional<std::array<bool,2>> stage_wave32 = {}); +DirectGraphicsPair translate_graphics_pair(std::string_view a, std::string_view b); +void validate_raster_link(const NativeComputeShader &producer, const NativeComputeShader &pixel); +DirectGraphicsPair translate_reflected_graphics(GuestShaderStage &vs, GuestShaderStage &ps, + const D3D12_ROOT_SIGNATURE_DESC1 &layout); +std::string native_rectangle_geometry(const std::vector<GraphicsLinkage>& vertex_outputs, + const std::vector<GraphicsLinkage>& pixel_inputs); +NativeComputeShader translate_graphics_container(const std::string &bytes, bool pixel); +struct MeshRootInput { + unsigned sgpr, root_parameter, constant_count; // Zero words denotes a table unless root_address is set. + bool root_address{}; +}; +struct MeshStageLayout { + unsigned threads, max_vertices, max_primitives, topology, group_stride; + bool wave32; + std::vector<MeshRootInput> root_inputs{}; + std::optional<unsigned> resource_heap_sgpr{}; + bool validate_uint_heap_reads{}; + bool packed_parameters{}; +}; +NativeComputeShader translate_mesh_pixel_program(std::string_view code, unsigned enable, unsigned address, + unsigned wave_size, const D3D12_ROOT_SIGNATURE_DESC1 *root = nullptr); +NativeComputeShader translate_mesh_program(const std::string &code, const MeshStageLayout &layout); +NativeComputeShader translate_mesh_program(const std::string &code, const MeshStageLayout &layout, + const D3D12_ROOT_SIGNATURE_DESC1 &root); +NativeComputeShader translate_mesh_container(const std::string &container, bool validate_uint_heap_reads = false); +} // namespace x2w diff --git a/src/gfx1013_compute_opcodes.inl b/src/gfx1013_compute_opcodes.inl new file mode 100644 index 0000000000..555e168dff --- /dev/null +++ b/src/gfx1013_compute_opcodes.inl @@ -0,0 +1,202 @@ +// Opcode spellings and fields follow the repository gfx1013 disassembler. +static const char* mnemonic(Encoding enc, unsigned op) { + switch (enc) { + case Encoding::Sopp: + switch (op) { + case 0x0: return "s_nop"; + case 0x1: return "s_endpgm"; + case 0x2: return "s_branch"; + case 0x4: return "s_cbranch_scc0"; + case 0x5: return "s_cbranch_scc1"; + case 0x6: return "s_cbranch_vccz"; + case 0x7: return "s_cbranch_vccnz"; + case 0x8: return "s_cbranch_execz"; + case 0x9: return "s_cbranch_execnz"; + case 0xa: return "s_barrier"; + case 0xc: return "s_waitcnt"; + case 0x20: return "s_inst_prefetch"; + case 0x21: return "s_clause"; + default: break; + } + break; + case Encoding::Sop1: + switch (op) { + case 0x3: return "s_mov_b32"; + case 0x4: return "s_mov_b64"; + case 0x7: return "s_not_b32"; + case 0x3c: return "s_and_saveexec_b32"; + case 0x47: return "s_andn2_wrexec_b32"; + default: break; + } + break; + case Encoding::Sop2: + switch (op) { + case 0x1: return "s_sub_u32"; + case 0x7: return "s_min_u32"; + case 0x9: return "s_max_u32"; + case 0x20: return "s_lshr_b32"; + case 0x35: return "s_mul_hi_u32"; + case 0: return "s_add_u32"; + case 0x26: return "s_mul_i32"; + case 0xa: return "s_cselect_b32"; + case 0xe: return "s_and_b32"; + case 0x10: return "s_or_b32"; + case 0x14: return "s_andn2_b32"; + case 0x1a: return "s_nor_b32"; + case 0x1e: return "s_lshl_b32"; + case 0x24: return "s_bfm_b32"; + case 0x27: return "s_bfe_u32"; + case 0x2c: return "s_absdiff_i32"; + case 0x2e: return "s_lshl1_add_u32"; + case 0x2f: return "s_lshl2_add_u32"; + case 0x30: return "s_lshl3_add_u32"; + case 0x31: return "s_lshl4_add_u32"; + default: break; + } + break; + case Encoding::Sopc: + switch (op) { + case 0x6: return "s_cmp_eq_u32"; + case 0x7: return "s_cmp_lg_u32"; + case 0xa: return "s_cmp_lt_u32"; + case 0x0: return "s_cmp_eq_i32"; + case 0x1: return "s_cmp_lg_i32"; + case 0x4: return "s_cmp_lt_i32"; + case 0xd: return "s_bitcmp1_b32"; + default: break; + } + break; + case Encoding::Sopk: + switch (op) { + case 0x4: return "s_cmpk_lg_i32"; + case 0x10: return "s_mulk_i32"; + case 0x0: return "s_movk_i32"; + default: break; + } + break; + case Encoding::Vop1: + switch (op) { + case 0x0b: return "v_cvt_f32_f16"; + case 0x36: return "v_cos_f32"; + case 0x65: return "v_swap_b32"; + case 2: return "v_readfirstlane_b32"; + case 0x1: return "v_mov_b32"; + case 0x5: return "v_cvt_f32_i32"; + case 0x6: return "v_cvt_f32_u32"; + case 0x8: return "v_cvt_i32_f32"; + case 0x11: return "v_cvt_f32_ubyte0"; + case 0x23: return "v_rndne_f32"; + case 0x2e: return "v_rsq_f32"; + case 0x7: return "v_cvt_u32_f32"; + case 0x24: return "v_floor_f32"; + case 0x25: return "v_exp_f32"; + case 0x27: return "v_log_f32"; + case 0x2a: return "v_rcp_f32"; + case 0x2b: return "v_rcp_iflag_f32"; + case 0x33: return "v_sqrt_f32"; + case 0x35: return "v_sin_f32"; + default: break; + } + break; + case Encoding::Vop2: + switch (op) { + case 0x1d: return "v_xor_b32"; + case 0x13: return "v_min_u32"; + case 0x1: return "v_cndmask_b32"; + case 0x3: return "v_add_f32"; + case 0x4: return "v_sub_f32"; + case 0x5: return "v_subrev_f32"; + case 0x8: return "v_mul_f32"; + case 0xb: return "v_mul_u32_u24"; + case 0xf: return "v_min_f32"; + case 0x10: return "v_max_f32"; + case 0x16: return "v_lshrrev_b32"; + case 0x18: return "v_ashrrev_i32"; + case 0x1a: return "v_lshlrev_b32"; + case 0x1b: return "v_and_b32"; + case 0x1c: return "v_or_b32"; + case 0x25: return "v_add_nc_u32"; + case 0x26: return "v_sub_nc_u32"; + case 0x2b: return "v_fmac_f32"; + case 0x2c: return "v_fmamk_f32"; + case 0x2d: return "v_fmaak_f32"; + default: break; + } + break; + case Encoding::Vopc: + switch (op) { + case 0x0d: return "v_cmp_neq_f32"; + case 0x81: return "v_cmp_lt_i32"; + case 0x84: return "v_cmp_gt_i32"; + case 0x86: return "v_cmp_ge_i32"; + case 0x91: return "v_cmpx_lt_i32"; + case 0x92: return "v_cmpx_eq_i32"; + case 0x93: return "v_cmpx_le_i32"; + case 0x94: return "v_cmpx_gt_i32"; + case 0x95: return "v_cmpx_ne_i32"; + case 0x96: return "v_cmpx_ge_i32"; + case 0xc1: return "v_cmp_lt_u32"; + case 0xc2: return "v_cmp_eq_u32"; + case 0xc3: return "v_cmp_le_u32"; + case 0xc4: return "v_cmp_gt_u32"; + case 0xc5: return "v_cmp_ne_u32"; + case 0xc6: return "v_cmp_ge_u32"; + case 0xd1: return "v_cmpx_lt_u32"; + case 0xd2: return "v_cmpx_eq_u32"; + case 0xd3: return "v_cmpx_le_u32"; + case 0xd4: return "v_cmpx_gt_u32"; + case 0xd5: return "v_cmpx_ne_u32"; + case 0xd6: return "v_cmpx_ge_u32"; + case 0x1: return "v_cmp_lt_f32"; + case 0x2: return "v_cmp_eq_f32"; + case 0x3: return "v_cmp_le_f32"; + case 0x4: return "v_cmp_gt_f32"; + case 0x6: return "v_cmp_ge_f32"; + case 0xc: return "v_cmp_nle_f32"; + case 0x82: return "v_cmp_eq_i32"; + case 0x83: return "v_cmp_le_i32"; + case 0x85: return "v_cmp_ne_i32"; + case 0x88: return "v_cmp_class_f32"; + default: break; + } + break; + case Encoding::Vop3: + switch (op) { + case 0x148: return "v_bfe_u32"; + case 0x14a: return "v_bfi_b32"; + case 0x14b: return "v_fma_f32"; + case 0x151: return "v_min3_f32"; + case 0x154: return "v_max3_f32"; + case 0x157: return "v_med3_f32"; + case 0x158: return "v_med3_i32"; + case 0x16a: return "v_mul_hi_u32"; + case 0x169: return "v_mul_lo_u32"; + case 0x16c: return "v_mul_hi_i32"; + case 0x300: return "v_lshrrev_b64"; + case 0x340: return "v_mad_u16"; + case 0x346: return "v_lshl_add_u32"; + case 0x347: return "v_add_lshl_u32"; + case 0x352: return "v_min3_i16"; + case 0x353: return "v_min3_u16"; + case 0x355: return "v_max3_i16"; + case 0x356: return "v_max3_u16"; + case 0x358: return "v_med3_i16"; + case 0x359: return "v_med3_u16"; + case 0x35e: return "v_mad_i16"; + case 0x365: return "v_mbcnt_lo_u32_b32"; + case 0x366: return "v_mbcnt_hi_u32_b32"; + case 0x36f: return "v_lshl_or_b32"; + case 0x371: return "v_and_or_b32"; + default: break; + } + break; + case Encoding::Mix: + switch (op) { + case 0x20: return "v_fma_mix_f32"; + default: break; + } + break; + default: break; + } + return nullptr; +} diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl new file mode 100644 index 0000000000..1bfcfc31d4 --- /dev/null +++ b/src/gfx1013_direct_compute.inl @@ -0,0 +1,4614 @@ +// Lower the shared decoded CFG to DXIL operations. A scalar register holds one +// 32-bit word per wave. Ordinary vector writes retain their old value on inactive lanes. +struct DirectCompute { + // The nine inline float constants as binary16, which an f16 operand reads instead of the f32 pattern. + static constexpr Word inline_half_words[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, + 0xc000, 0x4400, 0xc400, 0x3118}; + // D3D exp (sm4 asm) has relative error <= 2^-21, or < 8 ULP for normal f32 results. + // tests/f16_exp_midpoints.py generates the non-tie cases within that window + // using a 90-digit reference. The exact tie at -25 is handled separately. + struct ExpF16Midpoint { Word source, result; }; + static constexpr ExpF16Midpoint exp_f16_midpoints[]{ + {0x11c3, 0x3c00}, {0x11c4, 0x3c00}, {0x11c5, 0x3c01}, {0x11c6, 0x3c01}, + {0x11c7, 0x3c01}, {0x1853, 0x3c01}, {0x1b34, 0x3c02}, {0x1b35, 0x3c03}, + {0x1e7a, 0x3c04}, {0x1fea, 0x3c06}, {0x2164, 0x3c08}, {0x221b, 0x3c08}, + {0x2389, 0x3c0a}, {0x2bdb, 0x3c2c}, {0x2e7c, 0x3c4a}, {0x2ea7, 0x3c4c}, + {0x2fe7, 0x3c5b}, {0x36b6, 0x3d5a}, {0x3863, 0x3dd9}, {0x39f8, 0x3eb5}, + {0x3a8a, 0x3f0c}, {0x3b12, 0x3f62}, {0x3b82, 0x3faa}, {0x3efc, 0x42b5}, + {0x3f45, 0x430c}, {0x3f89, 0x4362}, {0x3fc1, 0x43aa}, {0x417e, 0x46b5}, + {0x437e, 0x4ab5}, {0x44bf, 0x4eb5}, {0x45bf, 0x52b5}, {0x46bf, 0x56b5}, + {0x47bf, 0x5ab5}, {0x8dc3, 0x3c00}, {0x8dc4, 0x3c00}, {0x8dc5, 0x3c00}, + {0x8dc6, 0x3bff}, {0x8dc7, 0x3bff}, {0x8dc8, 0x3bff}, {0x9454, 0x3bff}, + {0x9455, 0x3bfe}, {0x9738, 0x3bfd}, {0x990e, 0x3bfc}, {0x9a80, 0x3bfb}, + {0x9bf2, 0x3bfb}, {0x9e25, 0x3bf7}, {0x9f98, 0x3bf5}, {0xa2b4, 0x3bed}, + {0xa52d, 0x3be3}, {0xa86d, 0x3bd0}, {0xa8b4, 0x3bcc}, {0xa9d1, 0x3bc0}, + {0xabe0, 0x3baa}, {0xaf57, 0x3b63}, {0xaf70, 0x3b62}, {0xb1d8, 0x3b0c}, + {0xb410, 0x3ab5}, {0xb4db, 0x3a7c}, {0xb73a, 0x39d9}, {0xb8a5, 0x395a}, + {0xbc3f, 0x37aa}, {0xbc77, 0x3762}, {0xbcbb, 0x370c}, {0xbd04, 0x36b5}, + {0xc082, 0x32b5}, {0xc282, 0x2eb5}, {0xc441, 0x2ab5}, {0xc541, 0x26b5}, + {0xc641, 0x22b5}, {0xc741, 0x1eb5}, + }; + static void validate_lane_shape(const Inst &i, unsigned threads, unsigned width) { + const auto constant = constant32(i, i.src[1]); + const auto remaining = threads % width; + if (((i.src[1] <= 105 || (width == 32 && i.src[1] == 107)) && threads % 32) || + (constant && remaining && (*constant & (width - 1)) >= remaining)) + refuse(i.pc, "lane read/write needs full waves"); + } + Emit &analysis; + const GuestShaderStage *graphics_interface = nullptr; + DxilModule ir; + std::set<unsigned> allocated; + string lane, lane_bit, half_index, upper_half, exchange_base; + unsigned exchange_words = 0; + unsigned virtual_waves = 0; + bool uses_exchange = false; + bool wave64 = false; + bool narrow_wave64 = false; + // The view class a GPU-selected heap slot is read as; see HeapViewContract. + HeapViewContract heap_view = HeapViewContract::none; + // heap_view is raw_buffer and the path is direct: the byte-address rewrite of a heap descriptor is tracked. + bool heap_window = false; + // Binary16 arithmetic is lowered only while MODE stays at + // the contract this path implements: round-to-nearest-even, f16 denormals + // kept on input and output, and FP16_OVFL clear. mode_bits holds the + // fields this path tracks (round in [3:0], denorm in [7:4], FP16_OVFL in + // bit 23). A guest branch together with a MODE write makes the value at + // the arithmetic unprovable. + bool half_binary = false; + bool half_mode_known = true; + unsigned mode_bits = 0xf0; + std::vector<bool> scc_live; + std::map<std::pair<unsigned,unsigned>,string> descriptor_strides; + unsigned label_number = 0; + bool pixel_stage = false; + bool pixel_heap_enabled = false; + struct PixelHeapIndex { string index; unsigned first, last; bool nonuniform; }; + bool complete_compute_quads = false; + bool compute_derivatives = false; + // Straight-line graphics stages keep exact SSA definitions; a missing + // entry value is resolved through the container's stage signature. + std::function<string(unsigned)> graphics_input; + std::function<void(unsigned)> after_graphics_write; + std::map<unsigned, string> graphics_registers; + string graphics_predicate; + unsigned graphics_pc = 0; + const State *compute_state = nullptr; + unsigned compute_pc = 0; + bool perspective_center_pair = false; + bool exact_pixel_entry = false; + std::function<bool(unsigned)> helper_result_unobserved; + unsigned pixel_entry_vgprs = 0; + std::function<bool(unsigned)> untouched_pixel_register; + // P1/P2 consume the entry IJ pair symbolically. After an exact-mask + // write, covered lanes can use the replacement. Materialize the entry + // barycentric only when an observer can also see the unmodified lanes. + std::map<unsigned, std::pair<string, string>> guarded_ij; + string materialize_ij(unsigned r) { + auto [predicate, updated] = guarded_ij.at(r); + auto value = select(predicate, updated, graphics_input(r)); + graphics_registers[r] = value; + guarded_ij.erase(r); + return value; + } + string address(unsigned r) { + const auto name = "%r" + to_string(r); + if (virtual_waves) { + const auto type = "[" + to_string(virtual_waves) + " x i32]"; + if (allocated.insert(r).second) ir.setup << " " << name << " = alloca " << type << ", align 4\n"; + return ir.value("getelementptr " + type + ", " + type + "* " + name + ", i32 0, i32 %virtualWave"); + } + if (allocated.insert(r).second) + ir.setup << " " << name << " = alloca i32, align 4\n"; + return name; + } + string read_storage(unsigned r) { + if (graphics_input) { + auto guarded = guarded_ij.find(r); + if (guarded != guarded_ij.end()) + return guarded->second.first == graphics_predicate ? guarded->second.second : materialize_ij(r); + auto found = graphics_registers.find(r); + if (found != graphics_registers.end()) { + if (found->second.empty()) + refuse(graphics_pc, "graphics register undefined on an incoming path: " + to_string(r)); + return found->second; + } + auto value = graphics_input(r); + graphics_registers.emplace(r, value); + return value; + } + return ir.value("load i32, i32* " + address(r) + ", align 4"); + } + string read(unsigned r) { + if (compute_state && compute_state->has_spill(r)) + refuse(compute_pc, "symbolic VGPR lane read of " + reg(r)); + return read_storage(r); + } + bool lane_write = false; // v_writelane_b32 updates one lane of a VGPR that may hold symbolic lanes + void write(unsigned r, const string &value) { + // A VGPR write the analysis did not model as clearing its symbolic lanes + // would let a later v_readlane_b32 return a stale identity. + if (compute_state && !lane_write && compute_state->has_spill(r)) + refuse(compute_pc, "write to a VGPR holding symbolic lanes: " + reg(r)); + if (graphics_input) { + guarded_ij.erase(r); + graphics_registers[r] = value; + after_graphics_write(r); + return; + } + const auto ptr = address(r); + ir.body << " store i32 " << value << ", i32* " << ptr << ", align 4\n"; + } + string cmp(const string &predicate, const string &a, const string &b) { + return ir.value("icmp " + predicate + " i32 " + a + ", " + b); + } + string select(const string &predicate, const string &yes, const string &no) { + return ir.value("select i1 " + predicate + ", i32 " + yes + ", i32 " + no); + } + string active() { + if (graphics_input) + return "true"; + return cmp("ne", ir.binary("and", wave64 ? select(upper_half, read(127), read(126)) : read(126), lane_bit), "0"); + } + void vector_write(unsigned r, const string &value, const string &sampled_float = {}) { + if (graphics_input && graphics_predicate.empty()) + write(r, value); + else if (perspective_center_pair && (r == 256 || r == 257) && + (!graphics_registers.count(r) || (guarded_ij.count(r) && guarded_ij.at(r).first == graphics_predicate))) { + write(r, {}); + guarded_ij.emplace(r, std::make_pair(graphics_predicate, value)); + } else if (exact_pixel_entry && helper_result_unobserved(r) && pixel_entry_vgprs && r >= 256 + pixel_entry_vgprs && + !graphics_registers.count(r) && untouched_pixel_register(r)) { + // Only covered lanes can observe this result. In particular no + // subsequent implicit LOD or quad operation can inspect helpers. + write(r, value); + } else if (exact_pixel_entry && !graphics_predicate.empty() && !sampled_float.empty()) { + // Keep the floating sample and the incoming register live on the + // corresponding sides of the exact/helper predicate. Select has + // no floating-point arithmetic and preserves the old register bits. + auto previous = ir.value("bitcast i32 " + read(r) + " to float"); + auto result = ir.value("select i1 " + graphics_predicate + ", float " + sampled_float + ", float " + previous); + write(r, ir.value("bitcast float " + result + " to i32")); + } else + write(r, select(graphics_input ? graphics_predicate : active(), value, read_storage(r))); + } + string operand32(const Inst &i, unsigned n, unsigned sgpr_limit = 106) { + if (graphics_input && n == 106) + refuse(i.pc, "graphics instruction consumes a full wave mask"); + // M0 holds ordinary numeric ALU bits here, not an implicit memory/indexing operand. + const bool numeric_m0 = !graphics_input && n == 124 && i.enc != Encoding::Mubuf && i.enc != Encoding::Smem; + if (n <= 106 || n == 126 || n == 127 || (!graphics_input && n == 107) || numeric_m0 || (n >= 256 && n < 512)) { + analysis.require_numeric(i, n, sgpr_limit); + return read(n); + } + if (n == 253) + return read(128); // internal slot for SCC + if (auto constant = constant32(i, n)) + return to_string(*constant); + refuse(i.pc, "direct DXIL operand encoding"); + } + string ballot(const string &pred) { + ir.uses_wave = true; + auto b = ir.invoke("%dx.types.fouri32", "waveActiveBallot", 116, {{"i1", pred}}, "nounwind"); + return ir.value("extractvalue %dx.types.fouri32 " + b + ", 0"); + } + string group_intrinsic(const string &name, unsigned opcode, unsigned axis) { + return ir.invoke("i32", name, opcode, {{"i32", to_string(axis)}}, "nounwind readnone"); + } + string shared_address(const string &name, unsigned words, const string &index) { + const string type = "[" + to_string(words) + " x i32]"; + return ir.value("getelementptr " + type + ", " + type + " addrspace(3)* @" + name + ", i32 0, i32 " + index); + } + void barrier(unsigned mode = 9) { + ir.invoke("void", "barrier", 80, {{"i32", to_string(mode)}}, "nounwind noduplicate"); + } + // Each guest wave owns two scratch words. Multi-wave groups that use + // exchange must reach these workgroup barriers in the same order. + std::array<string, 2> exchange_halves(const string &word) { + const auto tag = to_string(label_number++); + if (!uses_exchange) { + ir.globals << "@waveExchange = internal addrspace(3) global [" << exchange_words << " x i32] undef, align 4\n"; + uses_exchange = true; + } + auto ptr = shared_address("waveExchange", exchange_words, half_index); + auto first = cmp("eq", lane, "0"); + ir.body << " br i1 " << first << ", label %publish" << tag << ", label %published" << tag + << "\npublish" << tag << ":\n store i32 " << word << ", i32 addrspace(3)* " << ptr + << ", align 4\n br label %published" << tag << "\npublished" << tag << ":\n"; + barrier(); + std::array<string, 2> pair; + for (unsigned j = 0; j != 2; ++j) + pair[j] = ir.value("load i32, i32 addrspace(3)* " + shared_address("waveExchange", exchange_words, ir.binary("add", exchange_base, to_string(j))) + ", align 4"); + barrier(); + return pair; + } + void write_ballot(unsigned dst, const string &condition) { + auto mask = ballot(ir.value("and i1 " + active() + ", " + condition)); + if (wave64) { + if ((dst & 1) || (dst > 104 && dst != 106 && dst != 126)) + throw UnsupportedComputeShader("invalid wave64 mask destination"); + auto pair = exchange_halves(mask); + write(dst, pair[0]); + write(dst + 1, pair[1]); + } else { + write(dst, mask); + // V_CMPX replaces EXEC. A narrow guest wave64 has no upper + // lanes, even if a preceding scalar write set bits in EXEC_HI. + if (narrow_wave64 && dst == 126) + write(127, "0"); + } + } + string pair_high(const Inst &i, unsigned src) { + if (src <= 104 || src == 106 || src == 126) { + if (src & 1) refuse(i.pc, "unaligned scalar mask pair"); + return operand32(i, src + 1); + } + if ((src >= 128 && src <= 192) || src == 255) return "0"; + if (src >= 193 && src <= 208) return "4294967295"; + refuse(i.pc, "unsupported wave64 scalar pair"); + } + void initialize(unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { + unsigned threads = x * y * z; + complete_compute_quads = threads % 4 == 0; + if (!virtual_waves) { + lane = ir.invoke("i32", "waveGetLaneIndex", 111, {}, "nounwind readnone"); + lane_bit = ir.binary("shl", "1", lane); + } + write(126, ballot("true")); + if (!wave64) { + write(127, "0"); + // s107 is ordinary scalar data in wave32; a VCC pair read sees zero until it is written. + write(107, "0"); + } + string wave = "0"; + if (virtual_waves) { + wave = ir.binary("add",ir.binary("shl","%virtualWave","1"),half_index); + } else if (threads > 32) { + auto flat = ir.invoke("i32", "flattenedThreadIdInGroup.i32", 96, {}, "nounwind readnone"); + auto first = + ir.invoke("i32", "waveActiveOp.i32", 119, {{"i32", flat}, {"i8", "2"}, {"i8", "1"}}, "nounwind"); + if (threads == 64) + wave = ir.value("zext i1 " + cmp("ne", first, "0") + " to i32"); + else { + ir.globals << "@waveStarts = internal addrspace(3) global [" << threads << " x i32] undef, align 4\n"; + auto ptr = shared_address("waveStarts", threads, flat); + auto leader = ir.value("zext i1 " + cmp("eq", first, flat) + " to i32"); + ir.body << " store i32 " << leader << ", i32 addrspace(3)* " << ptr << ", align 4\n"; + barrier(); + ir.body << " br label %rankLoop\nrankLoop:\n %idx = phi i32 [0, %entry], [%step, %count]\n" + " %rank = phi i32 [0, %entry], [%sum, %count]\n"; + auto more = cmp("ult", "%idx", first); + ir.body << " br i1 " << more << ", label %count, label %rankDone\ncount:\n"; + auto addr = shared_address("waveStarts", threads, "%idx"); + auto flag = ir.value("load i32, i32 addrspace(3)* " + addr + ", align 4"); + ir.body << " %sum = add i32 %rank, " << flag + << "\n %step = add i32 %idx, 1\n br label %rankLoop\nrankDone:\n"; + wave = "%rank"; + } + } + if (wave64) { + if (!virtual_waves) { + exchange_words = threads / 32; + half_index = wave; + exchange_base = ir.binary("and", wave, "4294967294"); + upper_half = cmp("ne", ir.binary("and", wave, "1"), "0"); + } + write(127, "4294967295"); + } + auto logical = ir.binary("add", ir.binary("mul", wave, "32"), lane); + write(256, ir.binary("urem", logical, to_string(x))); + if (((flags >> 11) & 3) >= 1) + write(257, ir.binary("urem", ir.binary("udiv", logical, to_string(x)), to_string(y))); + if (((flags >> 11) & 3) >= 2) + write(258, ir.binary("udiv", logical, to_string(x * y))); + for (unsigned j = 0; j < 3; ++j) + if (flags & (128u << j)) + write(user++, group_intrinsic("groupId.i32", 94, j)); + if (flags & 1024) { + if (wave64) wave = ir.binary("lshr", wave, "1"); + auto info = ir.binary("or", ir.binary("shl", wave, "20"), to_string(wave64 ? threads / 64 : (threads + 31) / 32)); + write(user, ir.binary("or", info, select(cmp("eq", wave, "0"), "2147483648", "0"))); + } + initialize_constants(); + } + void initialize_constants(const GraphicsConstantLayout *linked = nullptr) { + unsigned words = static_cast<unsigned>(descriptor_strides.size()); + for (const auto &block : analysis.result.constants) + words += block.count; + if (words) { + if (linked) + words = linked->offset(static_cast<unsigned>(linked->counts.size())); + auto h = ir.handle({2, 0, 13, 0, 0, (words + 3) / 4 * 16}); + unsigned pos = 0; + std::map<unsigned, string> vectors; + const auto word_at = [&](unsigned at) { + auto &vec = vectors[at / 4]; + if (vec.empty()) + vec = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, + {{"%dx.types.Handle", h}, {"i32", to_string(at / 4)}}, "nounwind readonly"); + return ir.value("extractvalue %dx.types.CBufRet.i32 " + vec + ", " + to_string(at % 4)); + }; + for (const auto &block : analysis.result.constants) { + if (linked) + pos = linked->offset(block.root_parameter); + for (unsigned j = 0; j < block.count; ++j, ++pos) + write(block.first_sgpr + j, word_at(pos)); + } + for (auto &entry : descriptor_strides) + entry.second = ir.binary("and",word_at(pos++),"16383"); + } + } + // Refuses a GPU-selected heap read that the contract does not cover. raw_buffer is the only class that is translated. + void refuse_heap_contract(unsigned pc) const { + if (heap_view == HeapViewContract::none) + refuse(pc, "direct resource-heap load requires the selected GPU slot and its view type"); + if (heap_view == HeapViewContract::other) + refuse(pc, "GPU-selected heap slot view type is not raw_buffer; only raw buffer heap reads are translated"); + } + // A raw buffer SRV chosen by a GPU value in the whole descriptor heap: ResourceDescriptorHeap[slot]. The view class the + // shader reads is the one this handle is annotated with (raw buffer); a slot holding another class is refused by the + // dispatch before the shader runs. The binding names the heap (no table register); the pipeline indexes it directly. + // A byte window is the byte-address rewrite of that descriptor (word 0 copied, word 1 without stride, word 2 the + // byte count, word 3 with the raw out-of-bounds mode; see byte_descriptor_field): read as the same raw slot view. + string heap_resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes) { + const auto &symbol = s.at(base); + refuse_heap_contract(i.pc); + const bool window = kind == ComputeViewKind::byte_window_srv; + if (kind != ComputeViewKind::raw_vector_srv && kind != ComputeViewKind::buffer_srv && !window) + refuse(i.pc, "a GPU-selected heap slot is read as a raw buffer SRV only"); + if (symbol.offset % 32 || s[base].type != Symbol::Type::indexed_descriptor) + refuse(i.pc, "unaligned heap descriptor"); + // Precaution: the rewritten words are compared by the pc of their heap load (symbol.definition), which a loop + // around that load executes again for another selection. A loop that does not contain the load runs it once. + // The scan also sees unreached code up to s_endpgm, which can only refuse more. + if (window) + for (const auto &inst : analysis.program.code) + if (inst.branch() && inst.target() <= symbol.definition && symbol.definition <= inst.pc) + refuse(i.pc, "heap byte window loaded inside a loop"); + constexpr Symbol::Type window_words[] = {Symbol::Type::indexed_descriptor, Symbol::Type::zero_stride_word, + Symbol::Type::byte_count, Symbol::Type::byte_oob}; + for (unsigned j = 1; j < 4; ++j) { + Symbol expected = symbol; + if (window) + expected.type = window_words[j]; // field() already cleared the word offset + else + expected.offset += 4 * j; + if (!(s.at(base + j) == expected)) + refuse(i.pc, "non-contiguous resource descriptor"); + } + auto &bindings = analysis.result.bindings; + auto it = std::find_if(bindings.begin(), bindings.end(), [](const auto &b) { + return b.kind == ComputeViewKind::heap_buffer_srv; + }); + if (it == bindings.end()) + bindings.push_back({ComputeViewKind::heap_buffer_srv, compute_resource_heap, 0, 0, bytes}); + else + it->required_bytes = (std::max)(it->required_bytes, bytes); + // 16: raw buffers. 0x40000000: the module reads ResourceDescriptorHeap (DXC sets both for the HLSL reference, + // see tests/native_heap_handle_probe_check.py); the validator refuses a module whose flags do not match. + ir.features |= 16 | 0x40000000; + return ir.heap_handle(ir.binary("add", read(base), to_string(symbol.offset / 32)), 11, 0); + } + std::set<std::pair<unsigned,unsigned>> read_write_raw_views; + string resource(const Inst &i, const State &s, unsigned base, ComputeViewKind kind, unsigned bytes, + unsigned *bound_register = nullptr) { + const auto &symbol = s.at(base); + const bool indexed = symbol.type == Symbol::Type::indexed_descriptor; + if (indexed && symbol.value == compute_resource_heap) + return heap_resource(i, s, base, kind, bytes); + if (!indexed && symbol.type == Symbol::Type::descriptor && + (kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::raw_vector_srv || + kind == ComputeViewKind::byte_window_srv) && + read_write_raw_views.count({symbol.value, symbol.offset})) { + // Both instructions read the same descriptor table entry. A + // second, SRV binding would conflict with its writable resource state. + kind = ComputeViewKind::raw_buffer_uav; + } + const unsigned count = indexed ? 1 + symbol.index_mask / 32 : 1; + analysis.binding(i, s, base, 4, kind, bytes); + auto it = std::find_if(analysis.result.bindings.begin(), analysis.result.bindings.end(), [&](const auto &b) { + return !b.array_position && b.array_count == count && b.kind == kind && b.root_parameter == s[base].value && + b.byte_offset == s[base].offset; + }); + if (it == analysis.result.bindings.end()) + throw std::logic_error("missing direct binding"); + if (bound_register) *bound_register = it->shader_register; + const bool raw = kind == ComputeViewKind::raw_buffer_uav || kind == ComputeViewKind::buffer_srv || + kind == ComputeViewKind::raw_vector_srv || kind == ComputeViewKind::byte_window_srv || + kind == ComputeViewKind::indexed_atomic_uav || kind == ComputeViewKind::indexed_raw_srv; + const bool half = kind == ComputeViewKind::half_buffer_uav; + const unsigned width = kind == ComputeViewKind::typed_buffer_srv ? 4 : + kind == ComputeViewKind::packed_d16_x_uav ? 1 : bytes / (half ? 2 : 4); + if (raw) + ir.features |= 16; + return ir.handle({unsigned(compute_uav(kind)), it->shader_register, raw ? 11u : 10u, + raw ? 0u + : half ? 9u + : 5u, + raw ? 0u : width, 0, count}, + indexed && count > 1 ? read(base) : ""); + } + string load_buffer(const string &h, const string &addr, bool raw, unsigned count) { + using Arg = std::pair<string, string>; + std::vector<Arg> args{{"%dx.types.Handle", h}, {"i32", addr}, {"i32", "undef"}}; + if (raw) { + args.emplace_back("i8", to_string((1u << count) - 1)); + args.emplace_back("i32", "4"); + } + return ir.invoke("%dx.types.ResRet.i32", raw ? "rawBufferLoad.i32" : "bufferLoad.i32", raw ? 139 : 68, args, + "nounwind readonly"); + } + void buffer_atomic(const Inst &i, const State &s, const string &pixel_predicate = {}) { + // The operation set and VGPR ordering follow gfx2hlsl.MUBUF_ATOMIC_OPS. + static const std::map<Name, unsigned> operations{ + {"buffer_atomic_add", 0}, {"buffer_atomic_sub", 0}, {"buffer_atomic_and", 1}, {"buffer_atomic_or", 2}, + {"buffer_atomic_xor", 3}, {"buffer_atomic_smin", 4}, {"buffer_atomic_smax", 5}, {"buffer_atomic_umin", 6}, + {"buffer_atomic_umax", 7}, {"buffer_atomic_swap", 8}}; + const bool exchange = i.name == "buffer_atomic_cmpswap"; + const auto op = operations.find(i.name); + if ((!exchange && op == operations.end()) || (exchange && i.dst == 255)) + refuse(i.pc, "unsupported buffer atomic width or operation"); + const unsigned data = 256 + i.dst; + const bool indexed = (i.a & 0x2000) != 0; + unsigned reg; + auto h = resource(i, s, ((i.b >> 16) & 31) * 4, + indexed ? ComputeViewKind::indexed_atomic_uav : ComputeViewKind::raw_buffer_uav, 4, ®); + string address, in_range; + if (indexed) { + // b(1 + uav register) is filled from the exact recorded buffer view. + // Test the element count before multiplication to reject wrapped indices. + auto cb = ir.handle({2, reg + 1, 13, 0, 0, 16}); + auto shape = ir.invoke("%dx.types.CBufRet.i32", "cbufferLoadLegacy.i32", 59, + {{"%dx.types.Handle", cb}, {"i32", "0"}}, "nounwind readonly"); + auto stride = ir.value("extractvalue %dx.types.CBufRet.i32 " + shape + ", 0"); + auto count = ir.value("extractvalue %dx.types.CBufRet.i32 " + shape + ", 1"); + auto index = read(256 + (i.b & 255)); + in_range = cmp("ult", index, count); + address = ir.binary("mul", index, stride); + } else { + address = ir.binary("add", operand32(i, i.b >> 24), to_string(i.a & 4095)); + if (i.a & 0x1000) + address = ir.binary("add", address, read(256 + (i.b & 255))); + } + address = ir.binary("and", address, "4294967292"); + auto value = read(data); + if (i.name == "buffer_atomic_sub") + value = ir.binary("sub", "0", value); + std::vector<std::pair<string, string>> args{{"%dx.types.Handle", h}}; + if (!exchange) + args.emplace_back("i32", to_string(op->second)); + args.emplace_back("i32", address); + args.emplace_back("i32", "undef"); + args.emplace_back("i32", "undef"); + if (exchange) + args.emplace_back("i32", read(data + 1)); + args.emplace_back("i32", value); + auto tag = to_string(label_number++), pred = active(); + if (!pixel_predicate.empty()) { + // Graphics uses SSA rather than the compute VGPR allocas. The caller + // proves a single guest block and supplies exact coverage and EXEC. + // Keep the original VGPR for inactive lanes, including helpers. + const auto size = ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", h}, {"i32", "undef"}}, "nounwind readonly"); + const auto bytes = ir.value("extractvalue %dx.types.Dimensions " + size + ", 0"); + const auto in_view = cmp("ult", address, bytes); // aligned DWORD, raw view length is a multiple of 4 + const auto fallback = (i.a & 0x4000) ? select(pixel_predicate, "0", value) : ""; + const auto execute = ir.value("and i1 " + pixel_predicate + ", " + in_view); + ir.body << " br i1 " << execute << ", label %atomic" << tag << ", label %atomicSkip" << tag + << "\natomic" << tag << ":\n"; + const auto previous = ir.invoke("i32", "atomicBinOp.i32", 78, args, "nounwind"); + ir.body << " br label %atomicEnd" << tag << "\natomicSkip" << tag + << ":\n br label %atomicEnd" << tag << "\natomicEnd" << tag << ":\n"; + if (i.a & 0x4000) { + auto returned = ir.value("phi i32 [ " + previous + ", %atomic" + tag + " ], [ " + + fallback + ", %atomicSkip" + tag + " ]"); + // Contention makes the old value varying even with uniform operands. + ir.dependencies[returned].set(128); + write(data, returned); + } + return; + } + if (indexed) { + if (i.a & 0x4000) { + auto out_of_range = ir.value("and i1 " + pred + ", " + ir.value("xor i1 " + in_range + ", true")); + write(data, select(out_of_range, "0", read(data))); + } + pred = ir.value("and i1 " + pred + ", " + in_range); + } + ir.body << " br i1 " << pred << ", label %atomic" << tag << ", label %atomicEnd" << tag << "\natomic" << tag + << ":\n"; + auto previous = ir.invoke("i32", exchange ? "atomicCompareExchange.i32" : "atomicBinOp.i32", exchange ? 79 : 78, + args, "nounwind"); + if (i.a & 0x4000) + write(data, previous); + ir.body << " br label %atomicEnd" << tag << "\natomicEnd" << tag << ":\n"; + } + #include "gfx1013_compute_mtbuf.inl" + + string root_buffer_handle(unsigned parameter, unsigned span) { + auto &bindings = analysis.result.bindings; + auto binding = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { + return b.kind == ComputeViewKind::root_buffer_srv && b.root_parameter == parameter; + }); + if (binding == bindings.end()) { + bindings.push_back({ComputeViewKind::root_buffer_srv, parameter, 0, analysis.srv++, span}); + binding = std::prev(bindings.end()); + } else + binding->required_bytes = (std::max)(binding->required_bytes, span); + ir.features |= 16; + return ir.handle({0, binding->shader_register, 11}); + } + + // Global DWORD loads in the saddr form: ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, + // FLAT/GLOBAL addressing), with SADDR the unadvanced root address of a root SRV, as for the scalar root loads. + // Guard the first and last DWORD offsets against 32-bit wrap. The low two address bits are dropped, + // as for buffer_load_dword in this path (DWORD alignment mode). + void global_load(const Inst &i, const State &s) { + constexpr unsigned widths[]{1, 2, 4, 3}; // GFX10 opcodes 12..15. + const unsigned count = widths[i.op - 12]; + if (i.dst + count > 256) + refuse(i.pc, "global load destination register range"); + const unsigned base = (i.b >> 16) & 127; + if (base > 104 || (base & 1)) + refuse(i.pc, "global load base must be an aligned SGPR pair"); + const auto &low = s.at(base); + if (low.type != Symbol::Type::root_address) + refuse(i.pc, "global load base is not a root buffer address"); + const Symbol high{Symbol::Type::root_address, low.value, 1}; + if (low.offset || !(s.at(base + 1) == high)) + refuse(i.pc, "global load base is an advanced or mismatched root address"); + const int offset = int(Word(i.a) << 20) >> 20; + if (offset % 4) + refuse(i.pc, "global load at an unaligned immediate offset"); + const unsigned span = static_cast<unsigned>((std::max)(offset, 0)) + count * 4; + const auto h = root_buffer_handle(low.value, span); + const auto vaddr = read(256 + (i.b & 255)); + string in_range; + if (offset < 0) + in_range = cmp("uge", vaddr, to_string(-offset)); + const int last_offset = offset + static_cast<int>((count - 1) * 4); + if (last_offset > 0) { + const auto upper = cmp("ule", vaddr, to_string(0xffffffffu - static_cast<unsigned>(last_offset))); + in_range = in_range.empty() ? upper : ir.value("and i1 " + in_range + ", " + upper); + } + const auto addr = offset ? ir.binary("add", vaddr, to_string(offset)) : vaddr; + const auto ret = load_buffer(h, ir.binary("and", addr, "4294967292"), true, count); + for (unsigned j = 0; j < count; ++j) { + auto value = ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", " + to_string(j)); + if (!in_range.empty()) + value = ir.value("select i1 " + in_range + ", i32 " + value + ", i32 0"); + vector_write(256 + i.dst + j, value); + } + } + void memory(const Inst &i, const State &s) { + if (i.name.substr(0, 17) == "global_load_dword") { + global_load(i, s); + return; + } + if (i.enc == Encoding::Mubuf && i.name.substr(0, 8) == "tbuffer_") { + formatted_byte_load(i, s); + return; + } + if (i.enc == Encoding::Mubuf && i.name.substr(0, 14) == "buffer_atomic_") { + buffer_atomic(i, s); + return; + } + if (i.enc == Encoding::Smem) { + unsigned so = i.b >> 25; + const unsigned limit = smem_sgpr_limit(!graphics_input); + const auto &low = s.at(i.src[0]); + if (low.type == Symbol::Type::sampler_heap) { + if (i.op != 2 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant, 0})) + refuse(i.pc, "sampler heap requires a four-word load with zero high address"); + if (so == 125 || s.at(so).type == Symbol::Type::constant) + refuse(i.pc, "constant sampler heap offset has no validated sampler-table contract"); + auto bytes = ir.binary("add", operand32(i, so), to_string(i.b & 0xfffff)); + // gfx2hlsl.x2w_sampler_entry: slot 2047 is reserved by the runtime. + auto aligned = cmp("eq", ir.binary("and", bytes, "15"), "0"); + auto in_range = cmp("ult", bytes, "32752"); + auto valid = ir.value("and i1 " + aligned + ", " + in_range); + auto index = select(valid, ir.binary("lshr", bytes, "4"), "2047"); + for (unsigned j = 0; j < 4; ++j) + write(i.dst + j, index); + return; + } + if (pixel_heap_enabled && low.type == Symbol::Type::table && low.value == compute_resource_heap && i.op == 3) { + if (i.dst + 8 > 106 || !(s.at(i.src[0] + 1) == Symbol{Symbol::Type::constant,0})) + refuse(i.pc, "invalid pixel heap texture descriptor address"); + const Word offset = i.b & 0xfffff; + if (offset & 31) refuse(i.pc, "unaligned pixel heap immediate byte offset"); + string index = to_string(offset / 32); + if (so != 125) { + const auto value = s.at(so); + if ((value.type != Symbol::Type::masked && value.type != Symbol::Type::constant) || + (value.value & 31) || value.value > UINT_MAX - offset) + refuse(i.pc,"pixel heap byte offset has no proven aligned range"); + auto address = ir.binary("add", operand32(i,so), to_string(offset)); + index = ir.binary("lshr",address,"5"); + } + for (unsigned j=0;j<8;++j) write(i.dst+j,index); + return; + } + const bool root = low.type == Symbol::Type::root_address; + // Table and heap-offset descriptor lowering track identities and slot indices instead of + // loading payload bits. + if (wave64 && !graphics_input && i.op < 8 && + (low.type == Symbol::Type::table || low.type == Symbol::Type::heap_offset) && + i.dst + memory_count(i) > 106) + refuse(i.pc, "symbolic scalar memory destination overlaps wave64 VCC"); + if (low.type == Symbol::Type::heap_offset) { + // A resource-heap address formed by s_add_u32 (heap_offset_add): the same slot read as the SGPR-offset + // load below, with the byte offset in the low word. + if (!heap_offset_address(s, i.src[0])) + refuse(i.pc, "heap descriptor address high word is not the carry of its offset add"); + if (i.op != 2) + refuse(i.pc, "heap descriptor address must load one descriptor with s_load_dwordx4"); + refuse_heap_contract(i.pc); + if (so != 125) + refuse(i.pc, "heap descriptor address with a second offset register"); + if (i.b & 0xfffff) + refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); + auto index = ir.binary("lshr", read(i.src[0]), "5"); + for (unsigned j = 0; j < 4; ++j) + write(i.dst + j, index); + return; + } + if (!root && low.type == Symbol::Type::table && low.value == compute_resource_heap) { + // Reads from the whole descriptor heap: only the indexed descriptor load of a captured raw buffer slot. + if (i.op >= 8) + refuse(i.pc, "scalar buffer load from the descriptor heap is not translated"); + refuse_heap_contract(i.pc); + if (so == 125) + refuse(i.pc, "heap descriptor load needs a GPU-selected index (SGPR offset)"); + // The captured selection names the slot the GPU data selects; a constant index or an immediate offset + // would address another slot than the one the guard checked. + if (s.at(so).type == Symbol::Type::constant) + refuse(i.pc, "heap descriptor index is a constant; the captured selection must come from GPU data"); + if (i.b & 0xfffff) + refuse(i.pc, "heap descriptor load with an immediate offset addresses another slot than the captured selection"); + } + if (!root && low.type == Symbol::Type::table && low.value == compute_sampler_heap) { + // Reads from the directly indexed sampler heap: one or two samplers at a constant 16-byte aligned offset. + if (i.op >= 8) + refuse(i.pc, "scalar buffer load from the sampler heap is not translated"); + if (so != 125) + refuse(i.pc, "sampler heap load with an SGPR offset (a GPU-selected sampler) is not translated"); + if (i.op != 2 && i.op != 3) + refuse(i.pc, "sampler heap load must read one or two samplers"); + if ((i.b & 0xfffff) % 16) + refuse(i.pc, "sampler heap offset is not a multiple of 16"); + if ((i.b & 0xfffff) / 16 + (i.op == 3 ? 2 : 1) - 1 > 2046) + refuse(i.pc, "sampler heap index beyond 2046 (2047 is the runtime fallback entry)"); + } + if (i.op < 8 && !root) { + if (s.at(i.src[0]).type != Symbol::Type::table || + s.at(i.src[0] + 1).type != Symbol::Type::constant || s.at(i.src[0] + 1).value != 0) + refuse(i.pc, "direct descriptor address outside bound table"); + if (so != 125) { + const bool pixel_texture = pixel_stage && i.op == 3 && low.value != compute_resource_heap; + if ((!pixel_texture && i.op != 2) || so >= limit || (pixel_texture && i.dst + 8 > limit)) + refuse(i.pc, "direct indexed descriptor load shape"); + auto index = ir.binary("lshr", operand32(i, so, limit), "5"); + for (unsigned j = 0; j < memory_count(i); ++j) + write(i.dst + j, index); + } + return; // The CFG transfer already associated every destination word with its table slot. + } + unsigned off = i.b & 0xfffff, n = memory_count(i); + string h; + if (root) { + const Symbol high{Symbol::Type::root_address, low.value, 1}; + const bool stride_one = i.op >= 8 && s.at(i.src[0] + 1) == + Symbol{Symbol::Type::root_stride_one_high, low.value, 1}; + if (low.offset || (!(s.at(i.src[0] + 1) == high) && !stride_one)) + refuse(i.pc, "mismatched root address high half"); + // Like Victory's Source::Built, retain the root identity through + // SGPR copies. Scalar buffer loads read dwords at byte offsets. + // Accept a finite byte bound or the unbounded NUM_RECORDS form + // only for this verified zero-stride, byte-address V# layout. + const bool built = i.op >= 8; + if (built && (s.at(i.src[0] + 2).type != Symbol::Type::constant || + !(s.at(i.src[0] + 3) == Symbol{Symbol::Type::constant, stride_one ? 0x11014facu : 0x31016facu}))) + refuse(i.pc, "unsupported synthesized scalar buffer descriptor fields"); + unsigned span = off + 4 * n; + if (off % 4 || span > 65536 || i.dst + n > limit) + refuse(i.pc, "unsupported root descriptor load range"); + if (so != 125) { + const auto &index = s.at(so); + if ((index.type != Symbol::Type::masked && index.type != Symbol::Type::constant) || + (index.value & 3) || index.value > 65536 - span) + refuse(i.pc, "unbounded or unaligned root descriptor index"); + span += index.value; + } + if (built && span > s.at(i.src[0] + 2).value) + refuse(i.pc, "scalar load exceeds synthesized descriptor byte bound"); + h = root_buffer_handle(low.value, span); + } else + h = resource(i, s, i.src[0], ComputeViewKind::buffer_srv, so == 125 ? off + 4 * n : 4); + auto addr = so == 125 ? to_string(off) + : ir.binary("and", ir.binary("add", operand32(i, so, limit), to_string(off)), "4294967292"); + for (unsigned j = 0; j < n; j += 4) { + unsigned width = (std::min)(4u, n - j); + auto chunk = so == 125 ? to_string(off + j * 4) : + j ? ir.binary("add", addr, to_string(j * 4)) : addr; + auto ret = load_buffer(h, chunk, true, width); + for (unsigned k = 0; k < width; ++k) + write(i.dst + j + k, ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", " + to_string(k))); + } + return; + } + bool store = i.name == "buffer_store_raw" || i.name == "buffer_store_format"; + bool raw = i.name == "buffer_load_dword" || i.name == "buffer_store_raw"; + bool half = i.name == "buffer_store_format" && (i.op & 128); + constexpr unsigned widths[]{1, 2, 4, 3}; + unsigned n = raw ? widths[i.op & 3] : (i.op & 3) + 1, data = 256 + i.dst; + if (i.dst + (half ? (n + 1) / 2 : n) > 256) + refuse(i.pc, "direct buffer data overflow"); + // A one-component D16 store is the half-buffer UAV. Its published line is + // `bufhalf` with a 2-byte stride. packed_d16_x_uav is a different binding + // and is the only kind that publishes `bufd16x`. + auto kind = store ? (raw ? ComputeViewKind::raw_buffer_uav + : half ? ComputeViewKind::half_buffer_uav + : ComputeViewKind::typed_buffer_uav) + : raw && s.at(((i.b >> 16) & 31) * 4 + 1).type == Symbol::Type::zero_stride_word + ? ComputeViewKind::byte_window_srv + : raw ? ComputeViewKind::raw_vector_srv + : ComputeViewKind::typed_buffer_srv; + const unsigned base = ((i.b >> 16) & 31) * 4; + string h; + if (!store && raw && (i.a & 0x2000)) { + const auto &descriptor = s.at(base); + const unsigned offset = i.a & 4095; + if (!graphics_interface || descriptor.type != Symbol::Type::descriptor) + refuse(i.pc, "indexed raw load needs a reflected table SRV"); + std::optional<unsigned> record_stride; + for (const auto &use : graphics_interface->resources) { + if (use.type || use.root_type != 3 || use.dwords != 4 || + use.root_parameter != descriptor.value || uint64_t(use.offset_dwords)*4 != descriptor.offset) continue; + if (record_stride && *record_stride != use.stride) refuse(i.pc, "ambiguous indexed SRV record stride"); + record_stride = use.stride; + } + const unsigned stride = record_stride.value_or(0); + if (!stride || stride > 2048 || (stride | offset) % 4 || offset + 4*n > stride) + refuse(i.pc, "indexed raw load outside a verified dword-aligned record"); + h = resource(i, s, base, ComputeViewKind::indexed_raw_srv, stride); + auto index = read(256 + (i.b & 255)); + auto dimensions = ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", h}, {"i32", "undef"}}, "nounwind readonly"); + auto size = ir.value("extractvalue %dx.types.Dimensions " + dimensions + ", 0"); + auto valid = cmp("ult", index, ir.binary("udiv", size, to_string(stride))); + auto start = ir.binary("add", ir.binary("mul", index, to_string(stride)), to_string(offset)); + auto result = load_buffer(h, start, true, n); + for (unsigned j=0; j<n; ++j) { + auto word = ir.value("extractvalue %dx.types.ResRet.i32 " + result + ", " + to_string(j)); + vector_write(data + j, select(valid, word, "0")); + } + return; + } + if (!store && raw && s.at(base).type == Symbol::Type::root_address) { + const auto &low = s.at(base); + // Byte-stride V#, unbounded NUM_RECORDS, raw OFFEN access. + // A shorter guest bound needs its own per-access bounds check. + const bool stride_one=s.at(base+1)==Symbol{Symbol::Type::root_stride_one_high,low.value,1} && + s.at(base+3)==Symbol{Symbol::Type::constant,0x11014fac}; + // With IDXEN clear, the original zero-stride, byte-count V# + // also reads exactly the OFFEN byte window of its root SRV. + const bool byte_bounds=s.at(base+1)==Symbol{Symbol::Type::root_address,low.value,1} && + s.at(base+3)==Symbol{Symbol::Type::constant,0x31016fac}; + if (low.offset || (!stride_one && !byte_bounds) || + !(s.at(base+2) == Symbol{Symbol::Type::constant, 0xffffffff}) || + (i.a & 0x3fff) != 0x1000 || (i.b >> 24) != 128) + refuse(i.pc, "unsupported raw root buffer descriptor or offset"); + h = root_buffer_handle(low.value, 4*n); + } else { + h = resource(i, s, base, kind, raw ? 4 : n * (half ? 2 : 4)); + } + auto addr = (i.a & (raw ? 0x1000 : 0x2000)) ? read(256 + (i.b & 255)) : "0"; + if (raw) { + addr = ir.binary("add", addr, to_string(i.a & 4095)); + addr = ir.binary("and", ir.binary("add", addr, operand32(i, i.b >> 24)), "4294967292"); + } + if (!store) { + auto ret = load_buffer(h, addr, raw, n); + for (unsigned k = 0; k < n; ++k) + vector_write(data + k, ir.value("extractvalue %dx.types.ResRet.i32 " + ret + ", " + to_string(k))); + return; + } + const string tag = to_string(label_number++), pred = active(); + if (!graphics_input) + ir.body << " br i1 " << pred << ", label %store" << tag << ", label %after" << tag << "\nstore" << tag + << ":\n"; + std::vector<std::pair<string, string>> args{{"%dx.types.Handle", h}, {"i32", addr}, {"i32", "undef"}}; + for (unsigned j = 0; j < 4; ++j) { + string value = "undef"; + if (j < n || !raw) { + const unsigned component = (std::min)(j, n - 1); + value = read(data + (half ? component / 2 : component)); + if (half) { + if (component % 2) + value = ir.binary("lshr", value, "16"); + value = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", value}}, "nounwind readnone"); + } + } + args.emplace_back(half ? "float" : "i32", value); + } + args.emplace_back("i8", to_string(raw ? (1u << n) - 1 : 15)); + if (raw) + args.emplace_back("i32", "4"); + ir.invoke("void", + raw ? "rawBufferStore.i32" + : half ? "bufferStore.f32" + : "bufferStore.i32", + raw ? 140 : 69, args, "nounwind"); + if (!graphics_input) + ir.body << " br label %after" << tag << "\nafter" << tag << ":\n"; + } + string select_float(const string &condition, const string &yes, const string &no) { + return ir.value("select i1 " + condition + ", float " + yes + ", float " + no); + } + // Invert the cube projection. Each pair of faces has a common major + // axis, with the negative face second. The two minor axes span [-1,1]. + std::array<string, 3> cube_axes(const string &face, const string &u, const string &v, bool tangent) { + const auto nu = ir.value("fsub float -0.0, " + u), nv = ir.value("fsub float -0.0, " + v); + const auto axis = ir.binary("lshr", ir.binary("and", face, "7"), "1"); + const auto is_x = cmp("eq", axis, "0"), is_y = cmp("eq", axis, "1"); + const auto negative = cmp("ne", ir.binary("and", face, "1"), "0"); + const auto major = tangent ? "0.0" : select_float(negative, "-1.0", "1.0"); + return {select_float(is_x, major, select_float(is_y, u, select_float(negative, nu, u))), + select_float(is_y, major, nv), + select_float(is_x, select_float(negative, u, nu), select_float(is_y, select_float(negative, nv, v), major))}; + } + string pixel_heap_texture(const Inst &i, const State &s, unsigned base, unsigned dim, + std::optional<PixelHeapIndex> selected) { + const auto sym = s.at(base); + if (!pixel_heap_enabled || sym.type != Symbol::Type::indexed_descriptor || + sym.value != compute_resource_heap || base+8>106 || (sym.offset & 31) || (dim != 1 && dim != 5)) + refuse(i.pc, "unproven pixel heap Texture2D descriptor"); + for (unsigned j=1;j<8;++j) { + auto expected = sym; + expected.offset += 4*j; + if (!(s.at(base+j)==expected)) refuse(i.pc,"mixed pixel heap texture descriptor words"); + } + if (!selected) { + if ((sym.index_mask & 31) || sym.index_mask > UINT_MAX - sym.offset) + refuse(i.pc,"pixel texture heap requires a proven slot domain"); + selected = PixelHeapIndex{read(base),sym.offset/32,(sym.offset+sym.index_mask)/32,false}; + } + auto &spans = analysis.result.pixel_heap_spans; + const auto &key=*selected; + if (key.first>key.last || key.last>UINT_MAX/32) refuse(i.pc,"invalid pixel texture heap range"); + auto it=std::find_if(spans.begin(),spans.end(),[&](const auto &v){ + return v.first==key.first && v.last==key.last && v.dimension==dim; + }); + if (it==spans.end()) { + const unsigned first=spans.empty()? first_pixel_heap_slot : + spans.back().host_first+(spans.back().last-spans.back().first+1); + if (uint64_t(first)+key.last-key.first+1 > D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1-256) + refuse(i.pc,"pixel texture heap domain exceeds desktop descriptor capacity"); + spans.push_back({key.first,key.last,dim,first}); + it=std::prev(spans.end()); + } + auto physical=ir.binary("add",key.index,to_string(it->host_first-key.first)); + ir.features |= 0x40000000; + return ir.heap_handle(physical,dim==1?2u:7u,1033,false,key.nonuniform); + } + string texture_dimensions(const string &handle, const string &mip) { + return ir.invoke("%dx.types.Dimensions", "getDimensions", 72, + {{"%dx.types.Handle", handle}, {"i32", mip}}, "nounwind readonly"); + } + void explicit_gather_2d(const Inst &i, const State &s, const string &handle, + const std::array<string, 3> &coords, unsigned mask) { + const unsigned sampler_base = ((i.b >> 21) & 31) * 4; + std::array<Word, 4> words{}; + for (unsigned j = 0; j < words.size(); ++j) { + const auto &word = s.at(sampler_base + j); + if (word.type != Symbol::Type::constant) + refuse(i.pc, "explicit 2D gather requires a constant sampler"); + words[j] = word.value; + } + // Match gfx2hlsl's normalized clamp profile. Point/bilinear XY and + // CLAMP_Z do not change this 2D footprint; the mip filter must be point. + constexpr Word xy_filter = (3u << 20) | (3u << 22); + if ((words[0] & ~(7u << 6)) != 0x12 || (words[1] & ~0x00fff000u) || + (words[2] & ~xy_filter) != 0x04000000 || ((words[2] >> 20) & 3) > 1 || + ((words[2] >> 22) & 3) > 1 || words[3]) + refuse(i.pc, "unsupported explicit 2D gather sampler"); + auto finite = [&](const string &bits) { + return cmp("ne", ir.binary("and", bits, "2139095040"), "2139095040"); + }; + auto valid = finite(coords[0]); + for (unsigned j = 1; j < coords.size(); ++j) + valid = ir.value("and i1 " + valid + ", " + finite(coords[j])); + auto safe_float = [&](unsigned j) { + return ir.value("bitcast i32 " + select(valid, coords[j], "0") + " to float"); + }; + auto clamp_float = [&](const string &value, const string &max) { + auto low = ir.invoke("float", "binary.f32", 35, {{"float", value}, {"float", "0.0"}}, "nounwind readnone"); + return ir.invoke("float", "binary.f32", 36, {{"float", low}, {"float", max}}, "nounwind readnone"); + }; + auto floor = [&](const string &value) { + return ir.invoke("float", "unary.f32", 27, {{"float", value}}, "nounwind readnone"); + }; + auto dimension = [&](const string &dims, unsigned j) { + return ir.value("extractvalue %dx.types.Dimensions " + dims + ", " + to_string(j)); + }; + auto last = [&](const string &count) { + return select(cmp("ne", count, "0"), ir.binary("sub", count, "1"), "0"); + }; + auto max_lod = ir.value("uitofp i32 " + to_string(words[1] >> 12) + " to float"); + max_lod = ir.value("fmul float " + max_lod + ", 3.906250e-03"); // unsigned 4.8 MAX_LOD + auto bounded = clamp_float(safe_float(2), max_lod); + auto rounded = ir.value("fptoui float " + floor(ir.value("fadd float " + bounded + ", 0.5")) + " to i32"); + auto count = dimension(texture_dimensions(handle, "0"), 3); + auto last_mip = last(count); + auto mip = select(cmp("ult", rounded, last_mip), rounded, last_mip); + auto dimensions = texture_dimensions(handle, mip); + auto have_view = ir.value("and i1 " + valid + ", " + cmp("ne", count, "0")); + std::array<std::array<string, 2>, 2> taps; + for (unsigned axis = 0; axis < 2; ++axis) { + auto size = dimension(dimensions, axis); + auto edge = last(size); + // Clamping UV first keeps the conversion in range. Outside [0,1] + // both taps clamp to the edge, as with clamping after flooring. + auto uv = clamp_float(safe_float(axis), "1.0"); + auto scaled = ir.value("fmul float " + uv + ", " + ir.value("uitofp i32 " + size + " to float")); + auto origin = ir.value("fptosi float " + floor(ir.value("fsub float " + scaled + ", 0.5")) + " to i32"); + for (unsigned j = 0; j < 2; ++j) { + auto index = j ? ir.binary("add", origin, "1") : origin; + auto nonnegative = select(cmp("slt", index, "0"), "0", index); + taps[axis][j] = select(cmp("ugt", nonnegative, edge), edge, nonnegative); + } + } + unsigned channel = 0; + while (!(mask & (1u << channel))) ++channel; + constexpr unsigned x[]{0, 1, 1, 0}, y[]{1, 1, 0, 0}; + for (unsigned j = 0; j < 4; ++j) { + auto texel = ir.invoke("%dx.types.ResRet.f32", "textureLoad.f32", 66, + {{"%dx.types.Handle", handle}, {"i32", mip}, {"i32", taps[0][x[j]]}, {"i32", taps[1][y[j]]}, + {"i32", "undef"}, {"i32", "undef"}, {"i32", "undef"}, {"i32", "undef"}}, "nounwind readonly"); + auto value = ir.value("extractvalue %dx.types.ResRet.f32 " + texel + ", " + to_string(channel)); + vector_write(256 + i.dst + j, select(have_view, ir.value("bitcast float " + value + " to i32"), "0")); + } + } + static int image_atomic_binop(unsigned op) { + switch (op) { + case 0x0f: return 8; // Exchange + case 0x11: return 0; // IAdd + case 0x15: return 6; // UMin + case 0x17: return 7; // UMax + case 0x18: return 1; // And + case 0x19: return 2; // Or + case 0x1a: return 3; // Xor + // Signed min/max is not verified on this R32_UINT binding. + default: return -1; + } + } + static bool is_image_atomic(const Inst &i) { + return i.enc == Encoding::Image && (i.op == 0x10 || image_atomic_binop(i.op) >= 0); + } + void image_atomic(const Inst &i, const State &s) { + const bool compare_exchange = i.op == 16; + const bool return_old = (i.a & 0x2000u) != 0; // GLC returns the pre-operation value. + const unsigned coord = i.b & 255, base = ((i.b >> 16) & 31) * 4; + const unsigned mask = (i.a >> 8) & 15, dim = (i.a >> 3) & 7; + if (graphics_input || dim != 1 || (i.a & 0x3c0c6u) || (i.b & 0xffe00000u) || + mask != (compare_exchange ? 3u : 1u) || coord == 255 || (compare_exchange && i.dst == 255) || + s.at(base).type != Symbol::Type::descriptor) + refuse(i.pc, "unsupported typed 2D image atomic operands"); + constexpr auto kind = ComputeViewKind::uint_texture_uav; + analysis.binding(i, s, base, 8, kind, 0, dim); + const auto &bindings = analysis.result.bindings; + const auto &descriptor = s.at(base); + const auto it = std::find_if(bindings.begin(), bindings.end(), [&](const auto &b) { + return b.kind == kind && b.root_parameter == descriptor.value && b.byte_offset == descriptor.offset; + }); + if (it == bindings.end()) + throw std::logic_error("missing image atomic binding"); + const auto handle = ir.handle({1, it->shader_register, 2, 5, 1, 0}); // RWTexture2D<uint> + const auto label = to_string(label_number++); + const auto enabled = active(); + ir.body << " br i1 " << enabled << ", label %imageAtomic" << label << ", label %imageAtomicEnd" << label + << "\nimageAtomic" << label << ":\n"; + std::vector<std::pair<string, string>> args{{"%dx.types.Handle", handle}}; + if (!compare_exchange) + args.emplace_back("i32", to_string(image_atomic_binop(i.op))); + args.emplace_back("i32", read(256 + coord)); + args.emplace_back("i32", read(257 + coord)); + args.emplace_back("i32", "undef"); + if (compare_exchange) + args.emplace_back("i32", read(257 + i.dst)); + args.emplace_back("i32", read(256 + i.dst)); + const auto previous = ir.invoke("i32", compare_exchange ? "atomicCompareExchange.i32" : "atomicBinOp.i32", + compare_exchange ? 79 : 78, args, "nounwind"); + if (return_old) + write(256 + i.dst, previous); + ir.body << " br label %imageAtomicEnd" << label << "\nimageAtomicEnd" << label << ":\n"; + } + void image_io(const Inst &i, const State &s, std::optional<PixelHeapIndex> selected = {}) { + if (is_image_atomic(i)) { + image_atomic(i, s); + return; + } + const bool bias = i.op == 37, gradient = i.op == 34, query = i.op == 96, dimensions = i.op == 14; + // With a different texture in neighboring lanes, compute the quad's + // derivatives on the original coordinates, independently of the + // descriptor selected by each iteration of the guest waterfall. + const bool quad_gradient = selected && selected->nonuniform && i.op==32; + if (quad_gradient && (i.a & 0x1000u)) + refuse(i.pc,"nonuniform implicit sampling requires normalized coordinates"); + // image_gather4_c_lz (79) is the comparison gather at the view's first mip (#2969): DXIL textureGatherCmp. + const bool compare_gather = i.op == 79; + const bool compare = i.op == 40 || i.op == 47 || compare_gather; + const bool implicit = i.op == 32 || i.op == 40 || bias || query || i.op == 64; + if (implicit && !pixel_stage) { + if (!complete_compute_quads) + refuse(i.pc, "implicit derivatives require a pixel stage"); + if (virtual_waves) + refuse(i.pc, "implicit derivatives with virtual wave64 groups"); + compute_derivatives = true; + } + const bool gather = i.op == 64 || i.op == 71 || compare_gather; + const bool gather_lod = i.op == 68; + const bool sample = (!gather && implicit) || (compare && !gather) || gradient || i.op == 39 || i.op == 36, + store = i.op == 8, + half = store && (i.b >> 31); + const bool lod = i.op == 1 || i.op == 36; + const unsigned mask = (i.a >> 8) & 15, addr = i.b & 255, base = ((i.b >> 16) & 31) * 4, dim = (i.a >> 3) & 7; + constexpr unsigned dx_kind[]{1, 2, 4, 5, 6, 7, 3, 8}; + constexpr unsigned coord_count[]{1, 2, 3, 3, 2, 3, 2, 3}; + const unsigned coords = coord_count[dim]; + const bool indexed = pixel_stage && !store && s.at(base).type == Symbol::Type::indexed_descriptor; + const bool exact_store = store && !half && !graphics_input && (dim == 1 || dim == 2 || dim == 5) && + (mask == 1 || mask == 3 || mask == 7); + // Read-only image ops ignore GLC (bit 13, 0x2000) and DLC (bit 7, 0x0080) cache hints; + // LWE (0x20000), TFE (0x10000), R128 (0x8000), reserved bits (0x4040), and store GLC/DLC stay refused. + if ((i.op != 0 && i.op != 1 && !store && !sample && !gather && !gather_lod && !dimensions) || !mask || + (i.a & (store ? 0x3e0c0u : 0x3c040u)) || + (i.b & 0x3c000000u) || (gather && ((mask & (mask - 1)) || (dim != 1 && dim != 3 && dim != 5))) || + (query && ((dim != 1 && dim != 3) || (mask & ~3u))) || + (compare && (mask != 1 || (dim != 1 && dim != 3 && dim != 5) || (i.a & 0x1000u))) || + (compare_gather && dim == 3) || + ((sample || gather) && (i.a & 0x1000u) && gradient) || + (dimensions && (dim == 4 || dim >= 6 || (i.b & 0x40000000u))) || + (store && !half && mask != 15 && !exact_store) || (half && mask != 1 && mask != 3 && mask != 15) || + (!indexed && s.at(base).type != Symbol::Type::descriptor)) + refuse(i.pc, "direct image opcode or descriptor modifiers"); + if (gather_lod && (dim != 1 || (mask & (mask - 1)) || (i.a & 0x1006u) || (i.b & 0xc0000000u) || i.dst > 252)) + refuse(i.pc, "unsupported explicit 2D gather operands"); + if ((dim == 3 && ((!sample && !gather && !dimensions) || (i.a & 0x1000u))) || + (dim >= 6 && (sample || gather || store || lod))) + refuse(i.pc, "unsupported cube or multisample operation"); + const bool d16_sample = !store && (i.b >> 31); + const unsigned channels = (half || exact_store) && mask == 1 ? 1 : + (half || exact_store) && mask == 3 ? 2 : exact_store ? 3 : 4; + const bool cube_sample = dim == 3 && (sample || gather); + const auto kind = half ? (channels == 1 ? ComputeViewKind::half_scalar_uav : + channels == 2 ? ComputeViewKind::half2_texture_uav : ComputeViewKind::half4_texture_uav) + : exact_store ? (channels == 1 ? ComputeViewKind::float_texture_uav : + channels == 2 ? ComputeViewKind::float2_texture_uav : ComputeViewKind::float3_texture_uav) + : store ? ComputeViewKind::texture_uav + : cube_sample ? (compare ? ComputeViewKind::cube_comparison_srv : ComputeViewKind::cube_sample_srv) + : d16_sample ? ComputeViewKind::d16_sample_srv + : compare ? ComputeViewKind::comparison_texture_srv + : ComputeViewKind::texture_srv; + string h; + if (selected || (indexed && s[base].value==compute_resource_heap)) { + if (kind != ComputeViewKind::texture_srv) refuse(i.pc,"unsupported pixel heap texture view class"); + h=pixel_heap_texture(i,s,base,dim,selected); + } else { + analysis.binding(i, s, base, 8, kind, 0, dim); + const auto &bs = analysis.result.bindings; + const unsigned count = indexed ? 1 + s[base].index_mask / 32 : 1; + auto it = std::find_if(bs.begin(), bs.end(), [&](const auto &b) { + return !b.array_position && b.array_count == count && b.image_dimension == dim && b.kind == kind && + b.root_parameter == s[base].value && b.byte_offset == s[base].offset; + }); + if (it == bs.end()) + throw std::logic_error("missing image binding"); + h = ir.handle({unsigned(store), it->shader_register, cube_sample ? 9u : dx_kind[dim], 9, compare ? 1u : channels, 0, count}, + indexed && count > 1 ? read(base) : ""); + } + auto coordinate = [&](unsigned j) { + unsigned r = addr + j; + if (j && (i.a & 6)) { + const unsigned word_index = (j - 1) / 4; + if (word_index >= ((i.a >> 1) & 3)) + refuse(i.pc, "incomplete image NSA address list"); + r = (i.image_address_words[word_index] >> (8 * ((j - 1) % 4))) & 255; + } + if (r > 255) + refuse(i.pc, "image coordinate register overflow"); + return read(256 + r); + }; + if (gather_lod) { + explicit_gather_2d(i, s, h, {coordinate(0), coordinate(1), coordinate(2)}, mask); + return; + } + if (dimensions) { + auto info = texture_dimensions(h, coordinate(0)); + unsigned dst = i.dst; + for (unsigned ch = 0; ch < 4; ++ch) { + if (!(mask & (1u << ch))) continue; + if (dst > 255) refuse(i.pc, "image destination overflow"); + auto value = ch == 3 || ch < (dim == 3 ? 2 : coords) ? ir.value("extractvalue %dx.types.Dimensions " + info + ", " + to_string(ch)) : "1"; + vector_write(256 + dst++, value); + } + return; + } + std::array<string, 4> c{"undef", "undef", "undef", "undef"}; + string level = "0"; + const unsigned spatial = coords - unsigned(dim == 3 || dim == 4 || dim == 5); + const bool a16 = (i.b & 0x40000000u) != 0; + if (a16) { + if (dim != 1 || lod || (i.a & 6) || (sample && i.op != 32 && i.op != 39) || gather || (store && !half)) + refuse(i.pc, "packed image addressing"); + auto packed = coordinate(0); + c[0] = ir.binary("and", packed, "65535"); + c[1] = ir.binary("lshr", packed, "16"); + } else { + for (unsigned j = 0; j < coords; ++j) + c[j] = coordinate(j + unsigned(bias || compare) + (gradient ? 2 * spatial : 0)); + if (bias || compare) + level = coordinate(0); + if (lod || dim >= 6) + level = coordinate(coords); + } + if (!store) { + string r; + if (sample || gather) { + string sampler; + const unsigned sampler_base = ((i.b >> 21) & 31) * 4; + const auto &first = s.at(sampler_base); + if (first.type == Symbol::Type::sampler_word) { + if (compare || gather) + refuse(i.pc, "unsupported heap sampler operation or destination"); + for (unsigned j = 0; j < 4; ++j) + if (!(s.at(sampler_base+j) == Symbol{Symbol::Type::sampler_word,first.value,j,0,first.definition})) + refuse(i.pc, "mixed sampler heap descriptor words"); + analysis.result.sampler_heap = true; + sampler = ir.handle({3, 0, 14, 0, 0, 0, 2048, false, 1}, read(sampler_base)); + } else { + const auto sampler_ref = analysis.sampler_index(i, s, sample || implicit, i.op == 71 || compare_gather, + implicit || gradient, compare); + if (i.op == 64 && !sampler_ref.heap && + (analysis.result.samplers.at(sampler_ref.index - analysis.first_sampler).words[1] & 0xffffff)) + refuse(i.pc, "implicit gather requires a sampler fixed to mip zero"); + if (sampler_ref.heap) { + ir.features |= 0x80000000; + sampler = ir.sampler_heap_handle(to_string(sampler_ref.index)); + } else + sampler = ir.handle({3, sampler_ref.index, 14, 0, 0, 0, 1, compare}); + } + using Arg = std::pair<string, string>; + std::vector<Arg> args{{"%dx.types.Handle", h}, {"%dx.types.Handle", sampler}}; + const auto size = (i.a & 0x1000u) ? texture_dimensions(h, "0") : string{}; + for (unsigned j = 0; j < coords; ++j) { + c[j] = a16 ? ir.invoke("float", "legacyF16ToF32", 131, {{"i32", c[j]}}, "nounwind readnone") : + ir.value("bitcast i32 " + c[j] + " to float"); + if (!size.empty() && j < spatial) { + auto extent = ir.value("extractvalue %dx.types.Dimensions " + size + ", " + to_string(j)); + auto scale = ir.value("uitofp i32 " + extent + " to float"); + c[j] = ir.value("fdiv float " + c[j] + ", " + scale); + } + } + string face; + if (dim == 3) { + // GFX packs face + 8 * layer. Desktop cube arrays take a + // direction plus the layer relative to the bound view. + face = ir.value("fptosi float " + c[2] + " to i32"); + auto projected = [&](const string &a) { + return ir.value("fsub float " + ir.value("fmul float " + a + ", 2.0") + ", 3.0"); + }; + auto direction = cube_axes(face, projected(c[0]), projected(c[1]), false); + std::copy(direction.begin(), direction.end(), c.begin()); + c[3] = ir.value("sitofp i32 " + ir.binary("ashr", face, "3") + " to float"); + } + if (query) { + for (unsigned j = 0; j < 3; ++j) + args.emplace_back("float", c[j]); + args.emplace_back("i1", "true"); + unsigned dst = i.dst; + for (unsigned ch = 0; ch < 2; ++ch) { + if (!(mask & (1u << ch))) continue; + if (dst > 255) refuse(i.pc, "image destination overflow"); + args.back().second = ch ? "false" : "true"; + auto result = ir.invoke("float", "calculateLOD.f32", 81, args, "nounwind readonly"); + vector_write(256 + dst++, ir.value("bitcast float " + result + " to i32")); + } + return; + } + for (unsigned j = 0; j < 4; ++j) + args.emplace_back("float", c[j]); + const unsigned offsets = dim == 3 ? 0 : spatial; + for (unsigned j = 0; j < (sample ? 3u : 2u); ++j) + args.emplace_back("i32", j < offsets ? "0" : "undef"); + if (gather) { + unsigned channel = 0; + while (!(mask & (1u << channel))) ++channel; + args.emplace_back("i32", to_string(channel)); + // textureGatherCmp takes the reference after the channel; the comparison reads red. + if (compare_gather) + args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); + } else if (compare) { + args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); + if (implicit) + args.emplace_back("float", "undef"); + } else if (gradient || quad_gradient) { + // Victory emit/lower.rs: d/dx and then d/dy of spatial + // coordinates precede the coordinates, excluding array slices. + for (unsigned axis = 0; axis < 2; ++axis) { + std::array<string, 3> d{"undef", "undef", "undef"}; + for (unsigned j = 0; j < spatial; ++j) + d[j] = quad_gradient ? ir.invoke("float","unary.f32",83+axis,{{"float",c[j]}},"nounwind readnone") : + ir.value("bitcast i32 " + coordinate(axis * spatial + j) + " to float"); + if (dim == 3) + d = cube_axes(face, ir.value("fmul float " + d[0] + ", 2.0"), + ir.value("fmul float " + d[1] + ", 2.0"), true); + for (const auto &component : d) args.emplace_back("float", component); + } + args.emplace_back("float", "undef"); + } else if (implicit) { + if (bias) + args.emplace_back("float", ir.value("bitcast i32 " + level + " to float")); + args.emplace_back("float", "undef"); // no per-instruction minimum LOD clamp + } else + args.emplace_back("float", lod ? ir.value("bitcast i32 " + level + " to float") : "0.0"); + const char *method = compare_gather ? "textureGatherCmp.f32" : + compare ? (implicit ? "sampleCmp.f32" : "sampleCmpLevelZero.f32") : + gather ? "textureGather.f32" : (gradient || quad_gradient) ? "sampleGrad.f32" : + bias ? "sampleBias.f32" : implicit ? "sample.f32" : "sampleLevel.f32"; + const unsigned opcode = compare_gather ? 74 : compare ? (implicit ? 64 : 65) : gather ? 73 : + (gradient || quad_gradient) ? 63 : bias ? 61 : implicit ? 60 : 62; + r = ir.invoke("%dx.types.ResRet.f32", method, opcode, args, "nounwind readonly"); + } else + r = ir.invoke("%dx.types.ResRet.f32", "textureLoad.f32", 66, + {{"%dx.types.Handle", h}, + {"i32", level}, + {"i32", c[0]}, + {"i32", c[1]}, + {"i32", c[2]}, + {"i32", "undef"}, + {"i32", "undef"}, + {"i32", "undef"}}, + "nounwind readonly"); + unsigned dst = i.dst; + string pending_half; + for (unsigned c = 0; c < 4; ++c) + if (gather || (mask & (1u << c))) { + if (dst > 255) + refuse(i.pc, "image destination overflow"); + auto value = ir.value("extractvalue %dx.types.ResRet.f32 " + r + ", " + to_string(c)); + auto bits = ir.value("bitcast float " + value + " to i32"); + if (d16_sample) { + bits = packed_half_rne(bits); + if (pending_half.empty()) { + pending_half = bits; + continue; + } + bits = ir.binary("or", pending_half, ir.binary("shl", bits, "16")); + pending_half.clear(); + } + vector_write(256 + dst++, bits, !d16_sample && (sample || gather) ? value : string{}); + } + if (!pending_half.empty()) vector_write(256 + dst, pending_half); + } else { + if (i.dst + (half ? (channels + 1) / 2 : channels) > 256) + refuse(i.pc, "image data overflow"); + string label = to_string(label_number++), pred = active(); + if (!graphics_input) + ir.body << " br i1 " << pred << ", label %img" << label << ", label %imgover" << label << "\nimg" << label + << ":\n"; + std::vector<std::pair<string, string>> args{ + {"%dx.types.Handle", h}, {"i32", c[0]}, {"i32", c[1]}, {"i32", c[2]}}; + std::array<string, 4> values; + string packed; + for (unsigned c = 0; c < channels; ++c) { + if (half) { + if (!(c & 1)) packed = read(256 + i.dst + c / 2); + const auto bits = c & 1 ? ir.binary("lshr", packed, "16") : packed; + values[c] = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + } else + values[c] = ir.value("bitcast i32 " + read(256 + i.dst + c) + " to float"); + } + // DXIL typed stores use a full write mask; narrower views ignore the tail. + for (unsigned c = 0; c < 4; ++c) + args.emplace_back("float", values[(std::min)(c, channels - 1)]); + args.emplace_back("i8", "15"); + ir.invoke("void", "textureStore.f32", 67, args, "nounwind"); + if (!graphics_input) + ir.body << " br label %imgover" << label << "\nimgover" << label << ":\n"; + } + } + void local_memory(const Inst &i, unsigned words) { + if (((i.a >> 18) & 255) == 0x3e && virtual_waves) { + const unsigned offset = i.a & 65535; + if ((i.a & 0x30000) || (i.b & 0xffffff) || offset % 4 || offset / 4 >= words) + refuse(i.pc, "invalid local append counter"); + const auto count_bits = [&](unsigned reg) { + return ir.invoke("i32", "unaryBits.i32", 31, {{"i32", read(reg)}}, "nounwind readnone"); + }; + const auto count = ir.binary("add", count_bits(126), count_bits(127)); + const auto leader = ir.value("and i1 " + cmp("eq", half_index, "0") + ", " + cmp("eq", lane, "0")); + auto take = ir.value("and i1 " + leader + ", " + cmp("ne", count, "0")); + const auto tag = to_string(label_number++); + barrier(); + ir.body << " br i1 " << take << ", label %append" << tag << ", label %skipAppend" << tag + << "\nappend" << tag << ":\n"; + auto ptr = shared_address("lds", words, to_string(offset / 4)); + auto old = ir.value("atomicrmw add i32 addrspace(3)* " + ptr + ", i32 " + count + " monotonic"); + ir.body << " br label %afterAppend" << tag << "\nskipAppend" << tag << ":\n br label %afterAppend" + << tag << "\nafterAppend" << tag << ":\n"; + const auto result = ir.value("phi i32 [ " + old + ", %append" + tag + " ], [ 0, %skipAppend" + tag + " ]"); + vector_write(256 + (i.b >> 24), exchange_halves(result)[0]); + return; + } + const auto op = decode_local_data(i.a, i.b); + // The host executes a guest wave64 on two wave32s. Meet before + // each operation, outside its lane predicate, as in Victory split_lds. + if (wave64) + barrier(); + const auto label = to_string(label_number++); + auto enabled = active(); + ir.body << " br i1 " << enabled << ", label %ds" << label << ", label %dsDone" << label << "\nds" << label + << ":\n"; + const auto address = read(256 + op.address); + for (unsigned j = 0; j < op.count; ++j) { + auto index = ir.binary("lshr", ir.binary("add", address, to_string(op.byte_offset(j))), "2"); + auto ptr = shared_address("lds", words, index); + if (op.read) + write(256 + op.destination + j, ir.value("load i32, i32 addrspace(3)* " + ptr + ", align 4")); + else { + auto data = read(256 + op.data_register(j)); + if (op.compare_exchange) { + auto result = ir.value("cmpxchg i32 addrspace(3)* " + ptr + ", i32 " + data + ", i32 " + + read(256 + op.data1) + " monotonic monotonic"); + write(256 + op.destination, ir.value("extractvalue { i32, i1 } " + result + ", 0")); + } else if (op.atomic_ir) { + if (op.subtract) + data = ir.binary("sub", "0", data); + auto old = ir.value(string("atomicrmw ") + op.atomic_ir + " i32 addrspace(3)* " + ptr + + ", i32 " + data + " monotonic"); + if (op.return_old) + write(256 + op.destination, old); + } else + ir.body << " store i32 " << data << ", i32 addrspace(3)* " << ptr << ", align 4\n"; + } + } + ir.body << " br label %dsDone" << label << "\ndsDone" << label << ":\n"; + } + string shift(const string &op, const string &a, const string &b) { + return ir.binary(op, a, ir.binary("and", b, "31")); + } + string subword(const string &value, unsigned sel, bool sign) { + if (sel == 6) + return value; + unsigned width = sel < 4 ? 8 : 16, bit = sel < 4 ? 8 * sel : 16 * (sel - 4); + auto slice = ir.binary("lshr", value, to_string(bit)); + if (!sign) + return ir.binary("and", slice, to_string((1u << width) - 1)); + auto left = ir.binary("shl", slice, to_string(32 - width)); + return ir.binary("ashr", left, to_string(32 - width)); + } + string place_subword(const Inst &i, const string &value) { + if (i.dst_select == 6) + return value; + unsigned sel = i.dst_select, width = sel < 4 ? 8 : 16, bit = sel < 4 ? 8 * sel : 16 * (sel - 4); + Word mask = (1u << width) - 1; + string result = subword(value, sel < 4 ? 0 : 4, i.dst_unused == 1); + if (bit) + result = ir.binary("shl", result, to_string(bit)); + if (i.dst_unused == 2) + result = ir.binary("or", result, ir.binary("and", read(i.dst), to_string(~(mask << bit)))); + return result; + } + string cube_alu(Name op, const string &x, const string &y, const string &z) { + auto magnitude = [&](const string &v) { + return ir.invoke("float", "unary.f32", 6, {{"float", v}}, "nounwind readnone"); + }; + auto at_least = [&](const string &a, const string &b) { return ir.value("fcmp oge float " + a + ", " + b); }; + auto negative = [&](const string &a) { return ir.value("fcmp olt float " + a + ", 0.0"); }; + auto negate = [&](const string &a) { return ir.value("fsub float -0.0, " + a); }; + const auto ax = magnitude(x), ay = magnitude(y), az = magnitude(z); + // The tie order is Z, Y, X, as in pixel_aot's cube lowering. + const auto major_z = ir.value("and i1 " + at_least(az, ax) + ", " + at_least(az, ay)); + const auto major_y = at_least(ay, ax); + auto axis = [&](const string &xf, const string &yf, const string &zf) { + return select_float(major_z, zf, select_float(major_y, yf, xf)); + }; + if (op == "v_cubeid_f32") + return axis(select_float(negative(x), "1.0", "0.0"), select_float(negative(y), "3.0", "2.0"), + select_float(negative(z), "5.0", "4.0")); + if (op == "v_cubesc_f32") + return axis(select_float(negative(x), z, negate(z)), x, select_float(negative(z), negate(x), x)); + if (op == "v_cubetc_f32") { + const auto ny = negate(y); + return axis(ny, select_float(negative(y), negate(z), z), ny); + } + return ir.value("fmul float " + axis(x, y, z) + ", 2.0"); + } + string packed_half_rne(const string &bits) { + // Round the integer significand to nearest even. Some desktop + // implementations truncate legacyF32ToF16 (Victory 9376fd6, + // emit/lower.rs::f16_nearest). This also preserves subnormals. + const auto sign = ir.binary("and", ir.binary("lshr", bits, "16"), "32768"); + const auto mag = ir.binary("and", bits, "2147483647"); + const auto exp = ir.binary("lshr", mag, "23"); + const auto frac = ir.binary("and", mag, "8388607"); + auto round_shift = [&](const string &v, const string &shift, const string &half) { + const auto odd = ir.binary("and", ir.binary("lshr", v, shift), "1"); + const auto bias = ir.binary("add", ir.binary("sub", half, "1"), odd); + return ir.binary("lshr", ir.binary("add", v, bias), shift); + }; + const auto normal = round_shift(ir.binary("sub", mag, "939524096"), "13", "4096"); + const auto sub_range = ir.value("and i1 " + cmp("uge", exp, "102") + ", " + cmp("ule", exp, "112")); + const auto shift = select(sub_range, ir.binary("sub", "126", exp), "14"); + const auto half = ir.binary("shl", "1", ir.binary("sub", shift, "1")); + const auto sub = round_shift(ir.binary("or", frac, "8388608"), shift, half); + auto h = select(cmp("ule", exp, "112"), select(sub_range, sub, "0"), normal); + h = select(cmp("ugt", exp, "142"), "31744", h); + const auto nan = cmp("ugt", mag, "2139095040"); + h = select(nan, ir.binary("or", ir.binary("lshr", frac, "13"), "32256"), h); + return ir.binary("or", h, sign); + } + static bool packed_f16_arithmetic(Name n) { + return n == "v_pk_add_f16" || n == "v_pk_mul_f16" || n == "v_pk_fma_f16" || n == "v_pk_fmac_f16"; + } + string fused_half_rne(const string &a, const string &b, const string &c) { + auto both = [&](const string &x, const string &y) { return ir.value("and i1 " + x + ", " + y); }; + auto either = [&](const string &x, const string &y) { return ir.value("or i1 " + x + ", " + y); }; + auto clz = [&](const string &value) { + // FirstbitHi counts from the most significant bit. OR-ing in bit + // zero leaves every nonzero count unchanged and bounds zero's shift. + return ir.invoke("i32", "unaryBits.i32", 33, + {{"i32", ir.binary("or", value, "1")}}, "nounwind readnone"); + }; + struct Half { string magnitude, sign, significand, exponent; }; + auto decode = [&](const string &word) { + auto magnitude = ir.binary("and", word, "32767"); + auto field = ir.binary("lshr", magnitude, "10"); + auto normal = cmp("ne", field, "0"); + auto hidden = select(normal, "1024", "0"); + return Half{magnitude, ir.binary("and", word, "32768"), + ir.binary("or", ir.binary("and", word, "1023"), hidden), + ir.binary("sub", select(normal, field, "1"), "25")}; + }; + auto x = decode(a), y = decode(b), z = decode(c); + auto product_sign = ir.binary("xor", x.sign, y.sign); + auto product = ir.binary("mul", x.significand, y.significand); + auto product_exp = ir.binary("add", x.exponent, y.exponent); + + // Normalize both exact terms at bit 30, leaving space for a carry. + // The product has at most 22 bits and the addend at most 11. Close + // exponents therefore align exactly, including after cancellation. + auto normalize = [&](const string &mantissa, const string &exponent) { + auto leading = clz(mantissa); + return std::pair{ + ir.binary("shl", mantissa, ir.binary("sub", leading, "1")), + select(cmp("eq", mantissa, "0"), "-128", + ir.binary("add", exponent, ir.binary("sub", "31", leading)))}; + }; + auto [product_mantissa, product_top] = normalize(product, product_exp); + auto [addend_mantissa, addend_top] = normalize(z.significand, z.exponent); + auto product_larger = either(cmp("sgt", product_top, addend_top), + both(cmp("eq", product_top, addend_top), cmp("uge", product_mantissa, addend_mantissa))); + auto big = select(product_larger, product_mantissa, addend_mantissa); + auto smaller_mantissa = select(product_larger, addend_mantissa, product_mantissa); + auto big_exp = select(product_larger, product_top, addend_top); + auto small_exp = select(product_larger, addend_top, product_top); + auto sign = select(product_larger, product_sign, z.sign); + auto distance = ir.binary("sub", big_exp, small_exp); + auto shift = select(cmp("ult", distance, "31"), distance, "31"); + auto aligned = ir.binary("lshr", smaller_mantissa, shift); + // A wide alignment has no significant cancellation. Retain a sticky + // bit for discarded data so a nearby midpoint still rounds correctly. + auto sticky = cmp("ne", ir.binary("shl", aligned, shift), smaller_mantissa); + aligned = ir.binary("or", aligned, ir.value("zext i1 " + sticky + " to i32")); + auto same_sign = cmp("eq", product_sign, z.sign); + auto magnitude = select(same_sign, ir.binary("add", big, aligned), ir.binary("sub", big, aligned)); + auto leading = clz(magnitude); + auto normalized = ir.binary("shl", magnitude, leading); + auto exponent = ir.binary("sub", ir.binary("add", big_exp, "128"), leading); + + // Encode the exact sum rounded to odd at binary32 precision. If any + // bits were lost, set the last retained bit. The final binary16 + // nearest-even conversion then sees the correct side of every tie. + auto odd = cmp("ne", ir.binary("and", normalized, "255"), "0"); + auto significand = ir.binary("or", ir.binary("lshr", normalized, "8"), + ir.value("zext i1 " + odd + " to i32")); + auto binary32 = ir.binary("or", ir.binary("shl", sign, "16"), + ir.binary("or", ir.binary("shl", exponent, "23"), ir.binary("and", significand, "8388607"))); + auto zero = select(both(cmp("eq", product, "0"), cmp("eq", z.magnitude, "0")), + ir.binary("and", product_sign, z.sign), "0"); + auto finite = select(cmp("eq", magnitude, "0"), zero, packed_half_rne(binary32)); + + auto x_inf = cmp("eq", x.magnitude, "31744"), y_inf = cmp("eq", y.magnitude, "31744"); + auto product_inf = either(x_inf, y_inf), c_inf = cmp("eq", z.magnitude, "31744"); + auto invalid_product = either(both(x_inf, cmp("eq", y.magnitude, "0")), + both(y_inf, cmp("eq", x.magnitude, "0"))); + auto invalid_sum = both(both(product_inf, c_inf), cmp("ne", product_sign, z.sign)); + auto nan = either(either(cmp("ugt", x.magnitude, "31744"), cmp("ugt", y.magnitude, "31744")), + either(cmp("ugt", z.magnitude, "31744"), either(invalid_product, invalid_sum))); + return select(nan, "32256", + select(product_inf, ir.binary("or", product_sign, "31744"), select(c_inf, c, finite))); + } + static std::optional<uint32_t> packed_f16_inline_constant(unsigned r) { + if (r >= 240 && r <= 248) { + // On gfx1013 (RDNA 2), inline binary16 float constants occupy bits [15:0] with bits [31:16] zeroed. + constexpr uint32_t halves[]{0x3800u, 0xb800u, 0x3c00u, 0xbc00u, 0x4000u, + 0xc000u, 0x4400u, 0xc400u, 0x3118u}; + return halves[r - 240]; + } + if (r >= 128 && r <= 192) + return r - 128u; + if (r >= 193 && r <= 208) + return static_cast<uint32_t>(192u - r); + return std::nullopt; + } + void packed_f16_alu(const Inst &i, const string *permuted = nullptr) { + const bool fmac = i.name == "v_pk_fmac_f16"; + const bool fused = i.name == "v_pk_fma_f16" || fmac; + if (fmac) { + if (i.enc != Encoding::Vop2 || i.wide || i.subword || i.dpp_control || permuted || + i.abs || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported packed binary16 arithmetic encoding"); + } else if (i.enc != Encoding::Mix || (!fused && (i.src[2] || (i.a & 0x2400) || (i.neg & 4)))) { + refuse(i.pc, "unsupported packed binary16 arithmetic encoding"); + } + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + std::array<string, 3> words; + for (unsigned j = 0; j < (fmac ? 2u : fused ? 3u : 2u); ++j) { + unsigned r = i.src[j]; + if (auto inline_word = packed_f16_inline_constant(r)) + words[j] = to_string(*inline_word); + else if (r <= 105 || r == 255 || (r >= 256 && r < 512)) + words[j] = operand32(i, r); + else + refuse(i.pc, "unsupported packed binary16 arithmetic source"); + } + if (fmac) + words[2] = read(i.dst); + auto lane = [&](unsigned selectors, unsigned negate) { + auto operand = [&](unsigned j) { + auto bits = (selectors & (1u << j)) ? ir.binary("lshr", words[j], "16") + : ir.binary("and", words[j], "65535"); + return (negate & (1u << j)) ? ir.binary("xor", bits, "32768") : bits; + }; + auto a = operand(0), b = operand(1); + string bits; + if (fused) { + bits = fused_half_rne(a, b, operand(2)); + } else { + auto widen = [&](const string &half_bits) { + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", half_bits}}, "nounwind readnone"); + }; + const auto op = i.name == "v_pk_mul_f16" ? "fmul" : "fadd"; + auto result = ir.value(string(op) + " float " + widen(a) + ", " + widen(b)); + bits = packed_half_rne(ir.value("bitcast float " + result + " to i32")); + bits = select(cmp("ugt", ir.binary("and", bits, "32767"), "31744"), "32256", bits); + } + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", bits, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", bits, "32768"), "0")); + bits = select(low, "0", select(cmp("ugt", bits, "15359"), "15360", bits)); + } + return bits; + }; + // In VOP3P, NEG_HI occupies the ABS field and OP_SEL_HI[2] lives in word 0. + // VOP2 v_pk_fmac_f16 runs low halves (pair 0) and high halves (pair 1) with no modifiers. + auto low = lane(fmac ? 0u : ((i.a >> 11) & 7u), fmac ? 0u : i.neg); + auto high = lane(fmac ? 7u : (((i.b >> 27) & 3u) | ((i.a >> 12) & 4u)), fmac ? 0u : i.abs); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + } + bool float_alu(const Inst &i, const string *permuted = nullptr) { + auto n = i.name; + if (packed_f16_arithmetic(n)) { + packed_f16_alu(i, permuted); + return true; + } + const bool dot2c = n == "v_dot2c_f32_f16"; + if (n == "v_dot2_f32_f16" || dot2c) { + if (dot2c) { + if (i.enc != Encoding::Vop2 || i.wide || i.subword || i.dpp_control || permuted || + i.abs || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported v_dot2c_f32_f16 encoding"); + } else if (i.enc != Encoding::Mix || i.dpp_control || permuted || (i.a & 0x2400)) { + refuse(i.pc, "unsupported v_dot2_f32_f16 encoding"); + } + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ffu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto half_pair = [&](unsigned j) { + const unsigned r = i.src[j]; + if (auto inline_word = packed_f16_inline_constant(r)) + return to_string(*inline_word); + if (r <= 105 || r == 255 || (r >= 256 && r < 512)) + return operand32(i, r); + refuse(i.pc, dot2c ? "unsupported v_dot2c_f32_f16 source" : "unsupported v_dot2_f32_f16 source"); + }; + const auto s0 = half_pair(0), s1 = half_pair(1); + string cbits; + if (dot2c) { + cbits = read(i.dst); + } else { + const unsigned r2 = i.src[2]; + if ((r2 > 105 && r2 < 128) || (r2 > 208 && r2 < 240) || (r2 > 248 && r2 < 255) || r2 >= 512) + refuse(i.pc, "unsupported v_dot2_f32_f16 source"); + cbits = operand32(i, r2); + if (i.neg & 4u) + cbits = ir.binary("xor", cbits, "2147483648"); + } + const auto c = ir.value("bitcast i32 " + cbits + " to float"); + auto term = [&](const string &word, unsigned selector, bool negate) { + auto bits = selector ? ir.binary("lshr", word, "16") : ir.binary("and", word, "65535"); + if (negate) + bits = ir.binary("xor", bits, "32768"); + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + }; + // VOP3P pair 0 uses OP_SEL[1:0]/NEG_LO[1:0] and pair 1 uses OP_SEL_HI[1:0]/NEG_HI[1:0] (in ABS). + // VOP2 v_dot2c_f32_f16 always dots low halves (pair 0 = 0) and high halves (pair 1 = 3) with no modifiers. + const unsigned op_sel = dot2c ? 0u : ((i.a >> 11) & 3u); + const unsigned op_sel_hi = dot2c ? 3u : ((i.b >> 27) & 3u); + auto a0 = term(s0, op_sel & 1u, (i.neg & 1u) != 0); + auto b0 = term(s1, (op_sel >> 1) & 1u, (i.neg & 2u) != 0); + auto a1 = term(s0, op_sel_hi & 1u, (i.abs & 1u) != 0); + auto b1 = term(s1, (op_sel_hi >> 1) & 1u, (i.abs & 2u) != 0); + auto p0 = ir.value("fmul float " + a0 + ", " + b0); + auto p1 = ir.value("fmul float " + a1 + ", " + b1); + auto sum = ir.value("fadd float " + p0 + ", " + p1); + auto sum_bits = ir.value("bitcast float " + sum + " to i32"); + auto res = ir.value("fadd float " + sum + ", " + c); + // Desktop DXIL fadd/saturate flush binary32 denormals to zero, whereas + // gfx1013 starts with MODE[5:4] = 3 (keep FP32 denormals). Every nonzero + // binary16*binary16 sum has |sum| >= 2^-48 >> 2^-126, so a binary32 + // subnormal accumulator c is observable iff sum == +/-0.0. + auto c_mag = ir.binary("and", cbits, "2147483647"); + auto sum_zero = cmp("eq", ir.binary("and", sum_bits, "2147483647"), "0"); + auto c_subnormal = ir.value("and i1 " + cmp("ne", c_mag, "0") + ", " + cmp("ult", c_mag, "8388608")); + auto keep_subnormal = ir.value("and i1 " + sum_zero + ", " + c_subnormal); + string res_bits; + if (i.clamp) { + auto sat = ir.invoke("float", "unary.f32", 7, {{"float", res}}, "nounwind readnone"); + auto clamped_sub = select(cmp("slt", cbits, "0"), "0", cbits); + res_bits = select(keep_subnormal, clamped_sub, ir.value("bitcast float " + sat + " to i32")); + } else { + res_bits = select(keep_subnormal, cbits, ir.value("bitcast float " + res + " to i32")); + } + vector_write(i.dst, res_bits); + return true; + } + if ((i.subword || (!i.wide && !i.dpp_control && !permuted)) && + (n == "v_cvt_f16_f32" || n == "v_cvt_f32_f16")) { + const bool narrow = n == "v_cvt_f16_f32"; + if (i.scale || (i.clamp && (narrow || !i.subword)) || i.src_sext[0]) + refuse(i.pc, "unsupported SDWA half conversion modifier"); + string bits = operand32(i, i.src[0]); + if (i.subword) bits = subword(bits, i.src_select[0], false); + if (i.abs) bits = ir.binary("and", bits, narrow ? "2147483647" : "32767"); + if (i.neg) bits = ir.binary("xor", bits, narrow ? "2147483648" : "32768"); + if (narrow) { + bits = packed_half_rne(bits); + if (!i.subword) bits = ir.binary("or", bits, ir.binary("and", read(i.dst), "4294901760")); + } else { + auto f = ir.invoke("float", "legacyF16ToF32", 131, {{"i32",bits}}, "nounwind readnone"); + bits = ir.value("bitcast float " + f + " to i32"); + if (i.clamp) { + // Integer clamp, as v_ldexp does: a set sign bit or NaN gives +0, values above 1.0 give 1.0. + // dx.op saturate may keep -0 or flush a denormal depending on the float mode. + auto nan = cmp("ugt", ir.binary("and", bits, "2147483647"), "2139095040"); + auto low = ir.value("or i1 " + nan + ", " + cmp("slt", bits, "0")); + bits = select(low, "0", select(cmp("sgt", bits, "1065353215"), "1065353216", bits)); + } + } + vector_write(i.dst, place_subword(i, bits)); + return true; + } + if (n == "v_floor_f16" || n == "v_ceil_f16" || n == "v_trunc_f16" || n == "v_rndne_f16") { + if (i.subword || i.dpp_control || permuted || i.scale || + (i.wide && ((i.a & 0x7800) || ((i.abs | i.neg) & 6) || i.src[1] || i.src[2]))) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + const unsigned r = i.src[0]; + auto bits = r >= 240 && r <= 248 ? to_string(inline_half_words[r - 240]) + : ir.binary("and", operand32(i, r), "65535"); + if (i.abs & 1) bits = ir.binary("and", bits, "32767"); + if (i.neg & 1) bits = ir.binary("xor", bits, "32768"); + auto sign = ir.binary("and", bits, "32768"); + auto mag = ir.binary("and", bits, "32767"); + auto exp = ir.binary("and", ir.binary("lshr", bits, "10"), "31"); + auto nz = cmp("ne", mag, "0"); + auto neg = cmp("ne", sign, "0"); + auto pos = cmp("eq", sign, "0"); + string sub_one = sign; + if (n == "v_floor_f16") + sub_one = select(ir.value("and i1 " + nz + ", " + neg), "48128", sign); + else if (n == "v_ceil_f16") + sub_one = select(ir.value("and i1 " + nz + ", " + pos), "15360", sign); + else if (n == "v_rndne_f16") + sub_one = select(cmp("ugt", mag, "14336"), ir.binary("or", sign, "15360"), sign); + auto frac_bits = select(cmp("ult", exp, "15"), "1", + select(cmp("ugt", exp, "24"), "1", ir.binary("sub", "25", exp))); + auto unit = ir.binary("shl", "1", frac_bits); + auto mask = ir.binary("sub", unit, "1"); + auto half = ir.binary("lshr", unit, "1"); + auto frac = ir.binary("and", bits, mask); + auto base = ir.binary("and", bits, ir.binary("xor", mask, "65535")); + string mid = base; + if (n != "v_trunc_f16") { + string inc; + if (n == "v_floor_f16") + inc = ir.value("and i1 " + neg + ", " + cmp("ne", frac, "0")); + else if (n == "v_ceil_f16") + inc = ir.value("and i1 " + pos + ", " + cmp("ne", frac, "0")); + else + inc = ir.value("or i1 " + cmp("ugt", frac, half) + ", " + + ir.value("and i1 " + cmp("eq", frac, half) + ", " + + cmp("ne", ir.binary("and", base, unit), "0"))); + mid = select(inc, ir.binary("add", base, unit), base); + } + auto result = select(cmp("uge", exp, "25"), bits, select(cmp("ult", exp, "15"), sub_one, mid)); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } + if (n == "v_pack_b32_f16") { + // VOP3 only: D[15:0] = S0.f16, D[31:16] = S1.f16. Every step is an + // integer bit operation so signed zeros and NaN payloads survive. + // Unsupported forms: clamp, omod, a destination or third-source + // op_sel bit, third-source abs/neg, inline constants, literals, + // SDWA and DPP. They are refused rather than approximated. + if (!i.wide || i.enc != Encoding::Vop3 || i.subword || i.dpp_control || permuted) + refuse(i.pc, "v_pack_b32_f16 requires the VOP3 encoding"); + if (i.clamp || i.scale) + refuse(i.pc, "unsupported v_pack_b32_f16 clamp or omod"); + if ((i.a & 0x6000) || ((i.abs | i.neg) & 4)) + refuse(i.pc, "unsupported v_pack_b32_f16 destination or third-source modifier"); + auto half = [&](unsigned j) { + const unsigned r = i.src[j]; + if (r >= 128 && r < 256) + refuse(i.pc, "unsupported v_pack_b32_f16 constant source"); + auto bits = operand32(i, r); + if ((i.a >> (11 + j)) & 1) bits = ir.binary("lshr", bits, "16"); + bits = ir.binary("and", bits, "65535"); + // Clear the sign for abs first, then toggle it for neg. + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "32767"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "32768"); + return bits; + }; + auto low = half(0), high = half(1); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + return true; + } + if (n == "v_frexp_exp_i16_f16" || n == "v_frexp_mant_f16") { + const bool exp_op = n == "v_frexp_exp_i16_f16"; + if (i.subword || i.dpp_control || permuted || i.scale || (exp_op && i.clamp) || + (i.wide && ((i.a & 0x7800) || ((i.abs | i.neg) & 6) || i.src[1] || i.src[2]))) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + // An inline float (240-248) reads its binary16 value, as v_add_f16 does. + const unsigned r = i.src[0]; + auto bits = r >= 240 && r <= 248 ? to_string(inline_half_words[r - 240]) + : ir.binary("and", operand32(i, r), "65535"); + if (i.abs & 1) bits = ir.binary("and", bits, "32767"); + if (i.neg & 1) bits = ir.binary("xor", bits, "32768"); + auto sign = ir.binary("and", bits, "32768"); + auto exponent = ir.binary("and", ir.binary("lshr", bits, "10"), "31"); + auto mantissa = ir.binary("and", bits, "1023"); + auto keep = ir.value("or i1 " + cmp("eq", exponent, "31") + ", " + + cmp("eq", ir.binary("and", bits, "32767"), "0")); + string x = mantissa, steps = "0"; + for (unsigned k : {8u, 4u, 2u, 1u}) { + auto low = cmp("ult", x, to_string(1u << (11 - k))); + x = select(low, ir.binary("shl", x, to_string(k)), x); + steps = select(low, ir.binary("add", steps, to_string(k)), steps); + } + auto denormal = cmp("eq", exponent, "0"); + string result; + if (exp_op) { + auto e = select(denormal, ir.binary("sub", "1", steps), exponent); + result = select(keep, "0", ir.binary("sub", e, "14")); + } else { + auto frac = select(denormal, ir.binary("and", x, "1023"), mantissa); + result = select(keep, bits, ir.binary("or", sign, ir.binary("or", "14336", frac))); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } + if (n == "v_cvt_f16_u16" || n == "v_cvt_f16_i16" || n == "v_cvt_u16_f16" || n == "v_cvt_i16_f16") { + if (graphics_input) + return false; + const bool to_f16 = n == "v_cvt_f16_u16" || n == "v_cvt_f16_i16"; + const bool is_signed = n == "v_cvt_f16_i16" || n == "v_cvt_i16_f16"; + if (i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " DPP form"); + if (i.subword) + refuse(i.pc, "unsupported " + string(n) + " SDWA form"); + if (i.scale || (!to_f16 && i.clamp)) + refuse(i.pc, "unsupported " + string(n) + " clamp or omod"); + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel"); + if ((to_f16 && (i.abs || i.neg)) || (i.wide && (((i.abs | i.neg) & 6) || i.src[1] || i.src[2]))) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + const unsigned r = i.src[0]; + string bits; + if (r >= 240 && r <= 248) { + constexpr unsigned halves[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, + 0xc000, 0x4400, 0xc400, 0x3118}; + bits = to_string(halves[r - 240]); + } else if (r == 255) { + bits = to_string(i.literal & 65535u); + } else if (r >= 128 && r <= 192) { + bits = to_string((r - 128) & 65535u); + } else if (r >= 193 && r <= 208) { + bits = to_string((192u - r) & 65535u); + } else { + bits = ir.binary("and", operand32(i, r), "65535"); + } + string result; + if (to_f16) { + string f; + if (is_signed) { + auto s16 = ir.binary("ashr", ir.binary("shl", bits, "16"), "16"); + f = ir.value("sitofp i32 " + s16 + " to float"); + } else { + f = ir.value("uitofp i32 " + bits + " to float"); + } + auto fbits = ir.value("bitcast float " + f + " to i32"); + result = packed_half_rne(fbits); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + } else { + if (i.abs & 1) + bits = ir.binary("and", bits, "32767"); + if (i.neg & 1) + bits = ir.binary("xor", bits, "32768"); + auto f = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + auto lower = ir.value("fcmp oge float " + f + ", " + (is_signed ? "-32768.0" : "0.0")); + auto upper = ir.value("fcmp olt float " + f + ", " + (is_signed ? "32768.0" : "65536.0")); + auto safe = select_float(ir.value("and i1 " + lower + ", " + upper), f, "0.0"); + auto converted = ir.value(string(is_signed ? "fptosi" : "fptoui") + " float " + safe + " to i32"); + auto bounded = select(upper, converted, is_signed ? "32767" : "65535"); + bounded = select(lower, bounded, is_signed ? "32768" : "0"); + auto ordered = ir.value("fcmp ord float " + f + ", " + f); + result = ir.binary("and", select(ordered, bounded, "0"), "65535"); + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } + const bool fract = n == "v_fract_f16"; + const bool cvt_norm = n == "v_cvt_norm_i16_f16" || n == "v_cvt_norm_u16_f16"; + if (fract || cvt_norm) { + if (i.enc != Encoding::Vop1 || i.subword || i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " encoding"); + if (fract ? i.scale : (i.clamp || i.scale)) + refuse(i.pc, fract ? "unsupported v_fract_f16 omod" : ("unsupported " + string(n) + " clamp or omod")); + const unsigned op_sel = i.wide ? ((i.a >> 11) & 15u) : 0u; + if ((i.wide && (((i.abs | i.neg) & 6) || i.src[1] || i.src[2])) || (op_sel & 6u)) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + if ((op_sel & 1u) && i.src[0] < 256) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel on non-VGPR source"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + const unsigned r = i.src[0]; + string bits; + if (op_sel & 1u) { + bits = ir.binary("lshr", operand32(i, r), "16"); + } else if (r >= 240 && r <= 248) { + bits = to_string(inline_half_words[r - 240]); + } else if (r == 255) { + bits = to_string(i.literal & 65535u); + } else if (r >= 128 && r <= 192) { + bits = to_string((r - 128) & 65535u); + } else if (r >= 193 && r <= 208) { + bits = to_string((192u - r) & 65535u); + } else if (r <= 105 || (r >= 256 && r < 512)) { + bits = ir.binary("and", operand32(i, r), "65535"); + } else { + refuse(i.pc, "unsupported " + string(n) + " source"); + } + if (i.abs & 1u) + bits = ir.binary("and", bits, "32767"); + if (i.neg & 1u) + bits = ir.binary("xor", bits, "32768"); + string result; + if (fract) { + auto non_finite = cmp("uge", ir.binary("and", bits, "32767"), "31744"); + auto a = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + auto fl = ir.invoke("float", "unary.f32", 27, {{"float", a}}, "nounwind readnone"); + auto diff = ir.value("fsub float " + a + ", " + fl); + auto h = packed_half_rne(ir.value("bitcast float " + diff + " to i32")); + // Tiny negative fractions round x - floor(x) up to 1.0 (0x3c00); hardware clamps strictly below 1.0 (0x3bff). + auto finite = select(cmp("eq", h, "15360"), "15359", h); + result = select(non_finite, i.clamp ? "0" : "32256", finite); + } else { + // Match tools/pixel_aot.py::f16_cvt_norm_result in exact 32-bit integer RNE arithmetic to avoid + // binary32 double-rounding (0x3801..0x3804 / 0xb801..0xb802) and preserve binary16 subnormals. + const bool signed_out = n == "v_cvt_norm_i16_f16"; + auto sign = cmp("ne", ir.binary("and", bits, "32768"), "0"); + auto mag = ir.binary("and", bits, "32767"); + auto is_nan = cmp("ugt", mag, "31744"); + auto is_zero = cmp("eq", mag, "0"); + auto ge_one = cmp("uge", mag, "15360"); + auto exp = ir.binary("lshr", mag, "10"); + auto is_sub = cmp("eq", exp, "0"); + auto mant = select(is_sub, mag, ir.binary("or", "1024", ir.binary("and", mag, "1023"))); + // Keep shift in [1, 24] when mag >= 1.0 (exp >= 15); ge_one selects `scale` there anyway. + auto shift = select(is_sub, "24", select(cmp("ult", exp, "15"), ir.binary("sub", "25", exp), "1")); + const string scale = signed_out ? "32767" : "65535"; + auto prod = ir.binary("mul", mant, scale); + auto q0 = ir.binary("lshr", prod, shift); + auto mid = ir.binary("shl", "1", ir.binary("sub", shift, "1")); + auto mask = ir.binary("sub", ir.binary("shl", "1", shift), "1"); + auto rem = ir.binary("and", prod, mask); + auto tie_even = ir.value("and i1 " + cmp("eq", rem, mid) + ", " + cmp("ne", ir.binary("and", q0, "1"), "0")); + auto round_up = ir.value("or i1 " + cmp("ugt", rem, mid) + ", " + tie_even); + auto q_frac = ir.binary("add", q0, select(round_up, "1", "0")); + auto q_mag = select(ge_one, scale, q_frac); + if (signed_out) { + auto neg_q = ir.binary("and", ir.binary("sub", "0", q_mag), "65535"); + auto signed_val = select(sign, neg_q, q_mag); + result = select(ir.value("or i1 " + is_nan + ", " + is_zero), "0", signed_val); + } else { + auto zero_out = ir.value("or i1 " + is_nan + ", " + ir.value("or i1 " + is_zero + ", " + sign)); + result = select(zero_out, "0", q_mag); + } + } + auto dst_old = read(i.dst); + auto packed_dst = (op_sel & 8u) + ? ir.binary("or", ir.binary("and", dst_old, "65535"), ir.binary("shl", result, "16")) + : ir.binary("or", ir.binary("and", dst_old, "4294901760"), result); + vector_write(i.dst, packed_dst); + return true; + } + if (n == "v_ldexp_f32") { + // pixel_aot.py ldexp32 (#3013): exact binary32 scaling of S0 by 2^S1. Zero, Inf and NaN pass unchanged, + // a denormal S0 is normalized rather than flushed, and a denormal result rounds to nearest even. S1 is + // a signed integer clamped to [-512, 512]. clamp saturates the result with integer tests: NaN and + // negative values (also -0) give +0, values from 1.0 give 1.0, and a denormal stays. + if (!i.wide || i.subword || i.dpp_control || permuted || i.scale || (i.a & 0x7800) || ((i.abs | i.neg) & 6) || + i.src[2]) + refuse(i.pc, "unsupported v_ldexp_f32 operand modifiers"); + auto bits = operand32(i, i.src[0]); + if (i.abs & 1) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & 1) bits = ir.binary("xor", bits, "2147483648"); + auto delta = operand32(i, i.src[1]); + auto sign = ir.binary("and", bits, "2147483648"); + auto exponent = ir.binary("and", ir.binary("lshr", bits, "23"), "255"); + auto mantissa = ir.binary("and", bits, "8388607"); + auto keep = ir.value("or i1 " + cmp("eq", exponent, "255") + ", " + + cmp("eq", ir.binary("and", bits, "2147483647"), "0")); + // Normalize a denormal mantissa: shift it left until bit 23 is set (5 halving steps, at most 23). + string x = mantissa, steps = "0"; + for (unsigned k : {16u, 8u, 4u, 2u, 1u}) { + auto low = cmp("ult", x, to_string(1u << (24 - k))); + x = select(low, ir.binary("shl", x, to_string(k)), x); + steps = select(low, ir.binary("add", steps, to_string(k)), steps); + } + auto denormal = cmp("eq", exponent, "0"); + mantissa = select(denormal, ir.binary("and", x, "8388607"), mantissa); + auto e = select(denormal, ir.binary("sub", "1", steps), exponent); + delta = select(cmp("slt", delta, "-512"), "-512", select(cmp("sgt", delta, "512"), "512", delta)); + e = ir.binary("add", e, delta); + auto normal = ir.binary("or", sign, ir.binary("or", ir.binary("shl", e, "23"), mantissa)); + // A result below the normal range: shift the full significand right by 1 - e (1..24) and round to + // nearest even. + auto full = ir.binary("or", mantissa, "8388608"); + // Every shift stays in 1..24, also in the lanes whose result another select discards. + auto amount = select(cmp("sgt", e, "0"), "1", select(cmp("slt", e, "-23"), "24", ir.binary("sub", "1", e))); + auto half = ir.binary("shl", "1", ir.binary("sub", amount, "1")); + auto rest = ir.binary("and", full, ir.binary("sub", ir.binary("shl", half, "1"), "1")); + auto q = ir.binary("lshr", full, amount); + auto up = ir.value("or i1 " + cmp("ugt", rest, half) + ", " + + ir.value("and i1 " + cmp("eq", rest, half) + ", " + + cmp("ne", ir.binary("and", q, "1"), "0"))); + auto subnormal = ir.binary("or", sign, ir.binary("add", q, ir.value("zext i1 " + up + " to i32"))); + string result = select(cmp("sgt", e, "0"), normal, select(cmp("slt", e, "-23"), sign, subnormal)); + result = select(cmp("sgt", e, "254"), ir.binary("or", sign, "2139095040"), result); + result = select(keep, bits, result); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "2147483647"), "2139095040"); + auto low = ir.value("or i1 " + nan + ", " + cmp("slt", result, "0")); + result = select(low, "0", select(cmp("sgt", result, "1065353215"), "1065353216", result)); + } + vector_write(i.dst, result); + return true; + } + if (n == "v_frexp_exp_i32_f32" || n == "v_frexp_mant_f32") { + const bool exp_op = n == "v_frexp_exp_i32_f32"; + if (i.subword || i.dpp_control || permuted || i.scale || (exp_op && i.clamp) || + (i.wide && ((i.a & 0x7800) || ((i.abs | i.neg) & 6) || i.src[1] || i.src[2]))) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + auto bits = operand32(i, i.src[0]); + if (i.abs & 1) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & 1) bits = ir.binary("xor", bits, "2147483648"); + auto sign = ir.binary("and", bits, "2147483648"); + auto exponent = ir.binary("and", ir.binary("lshr", bits, "23"), "255"); + auto mantissa = ir.binary("and", bits, "8388607"); + auto keep = ir.value("or i1 " + cmp("eq", exponent, "255") + ", " + + cmp("eq", ir.binary("and", bits, "2147483647"), "0")); + string x = mantissa, steps = "0"; + for (unsigned k : {16u, 8u, 4u, 2u, 1u}) { + auto low = cmp("ult", x, to_string(1u << (24 - k))); + x = select(low, ir.binary("shl", x, to_string(k)), x); + steps = select(low, ir.binary("add", steps, to_string(k)), steps); + } + auto denormal = cmp("eq", exponent, "0"); + string result; + if (exp_op) { + auto e = select(denormal, ir.binary("sub", "1", steps), exponent); + result = select(keep, "0", ir.binary("sub", e, "126")); + } else { + auto frac = select(denormal, ir.binary("and", x, "8388607"), mantissa); + result = select(keep, bits, ir.binary("or", sign, ir.binary("or", "1056964608", frac))); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "2147483647"), "2139095040"); + auto low = ir.value("or i1 " + nan + ", " + cmp("slt", result, "0")); + result = select(low, "0", select(cmp("sgt", result, "1065353215"), "1065353216", result)); + } + } + vector_write(i.dst, result); + return true; + } + if (n == "v_cvt_pkrtz_f16_f32") { + if (i.clamp || i.scale || (i.wide && (i.a & 0x7800))) + refuse(i.pc, "unsupported packed half conversion modifier"); + // SDWA: both sources are full f32 words (src_sel DWORD); only the destination placement differs. + if (i.subword && (i.src_select[0] != 6 || i.src_select[1] != 6)) + refuse(i.pc, "unsupported packed half conversion SDWA source selection"); + auto pack = [&](unsigned j) { + auto bits = operand32(i, i.src[j]); + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "2147483648"); + auto f = ir.value("bitcast i32 " + bits + " to float"); + auto h = ir.invoke("i32", "legacyF32ToF16", 130, {{"float",f}}, "nounwind readnone"); + auto mag = ir.binary("and", h, "32767"); + auto back = ir.invoke("float", "legacyF16ToF32", 131, {{"i32",mag}}, "nounwind readnone"); + auto abs = ir.value("bitcast i32 " + ir.binary("and", bits, "2147483647") + " to float"); + auto rounded_up = ir.value("fcmp ogt float " + back + ", " + abs); + return ir.binary("and", ir.binary("sub", h, ir.value("zext i1 " + rounded_up + " to i32")), "65535"); + }; + auto low = pack(0), high = pack(1); + auto result = ir.binary("or", low, ir.binary("shl", high, "16")); + vector_write(i.dst, place_subword(i, result)); + return true; + } + if (n == "v_cvt_pknorm_i16_f32" || n == "v_cvt_pknorm_u16_f32") { + if (i.enc != Encoding::Vop3 || i.subword || i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " encoding"); + if (i.clamp || i.scale) + refuse(i.pc, "unsupported " + string(n) + " clamp or omod"); + if ((i.a & 0x7800) || ((i.abs | i.neg) & 4) || i.src[2]) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + const bool signed_out = n == "v_cvt_pknorm_i16_f32"; + const unsigned k = signed_out ? 15u : 16u; + const string scale = signed_out ? "32767" : "65535"; + const string lo_mask = signed_out ? "32767" : "65535"; + auto cvt_lane = [&](unsigned j) { + auto bits = operand32(i, i.src[j]); + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "2147483648"); + // Exact 32-bit integer RNE of clamp(|x|, 0, 1) * (2^k - 1) via m*(2^k - 1) split at bit k. + auto sign = cmp("ne", ir.binary("and", bits, "2147483648"), "0"); + auto mag = ir.binary("and", bits, "2147483647"); + auto is_nan = cmp("ugt", mag, "2139095040"); + auto too_small = cmp("ult", mag, "922746880"); + auto ge_one = cmp("uge", mag, "1065353216"); + auto exp = ir.binary("lshr", mag, "23"); + auto in_range = ir.value("and i1 " + cmp("uge", exp, "110") + ", " + cmp("ule", exp, "126")); + auto safe_exp = select(in_range, exp, "126"); + auto s2 = ir.binary("sub", to_string(150u - k), safe_exp); + auto m = ir.binary("or", ir.binary("and", mag, "8388607"), "8388608"); + auto m_hi = ir.binary("lshr", m, to_string(k)); + auto m_lo = ir.binary("and", m, lo_mask); + auto borrow = select(cmp("ne", m_lo, "0"), "1", "0"); + auto p_lo = ir.binary("and", ir.binary("sub", "0", m_lo), lo_mask); + auto p_hi = ir.binary("sub", ir.binary("sub", m, m_hi), borrow); + auto q0 = ir.binary("lshr", p_hi, s2); + auto mid_hi = ir.binary("shl", "1", ir.binary("sub", s2, "1")); + auto rem_mask = ir.binary("sub", ir.binary("shl", "1", s2), "1"); + auto rem_hi = ir.binary("and", p_hi, rem_mask); + auto tie_or_above = ir.value("or i1 " + cmp("ne", p_lo, "0") + ", " + + cmp("ne", ir.binary("and", q0, "1"), "0")); + auto round_up = ir.value("or i1 " + cmp("ugt", rem_hi, mid_hi) + ", " + + ir.value("and i1 " + cmp("eq", rem_hi, mid_hi) + ", " + tie_or_above)); + auto q_frac = ir.binary("add", q0, select(round_up, "1", "0")); + auto q_mag = select(too_small, "0", select(ge_one, scale, q_frac)); + if (signed_out) { + auto neg_q = ir.binary("and", ir.binary("sub", "0", q_mag), "65535"); + return select(is_nan, "0", select(sign, neg_q, q_mag)); + } + return select(ir.value("or i1 " + is_nan + ", " + sign), "0", q_mag); + }; + auto low = cvt_lane(0), high = cvt_lane(1); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + return true; + } + if (n == "v_ldexp_f16") { + if (graphics_input) + return false; + if (i.subword || i.dpp_control || permuted || i.scale || + (i.wide && ((i.a & 0x7800) || ((i.abs | i.neg) & 6) || i.src[2]))) + refuse(i.pc, "unsupported v_ldexp_f16 operand modifiers"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto inline_s0 = i.src[0] >= 240 && i.src[0] <= 248 ? packed_f16_inline_constant(i.src[0]) : std::nullopt; + auto bits = inline_s0 ? to_string(*inline_s0) : ir.binary("and", operand32(i, i.src[0]), "65535"); + if (i.abs & 1) bits = ir.binary("and", bits, "32767"); + if (i.neg & 1) bits = ir.binary("xor", bits, "32768"); + auto delta = ir.binary("ashr", ir.binary("shl", operand32(i, i.src[1]), "16"), "16"); + auto sign = ir.binary("and", bits, "32768"); + auto exponent = ir.binary("and", ir.binary("lshr", bits, "10"), "31"); + auto mantissa = ir.binary("and", bits, "1023"); + auto keep = ir.value("or i1 " + cmp("eq", exponent, "31") + ", " + + cmp("eq", ir.binary("and", bits, "32767"), "0")); + string x = mantissa, steps = "0"; + for (unsigned k : {8u, 4u, 2u, 1u}) { + auto low = cmp("ult", x, to_string(1u << (11 - k))); + x = select(low, ir.binary("shl", x, to_string(k)), x); + steps = select(low, ir.binary("add", steps, to_string(k)), steps); + } + auto denormal = cmp("eq", exponent, "0"); + mantissa = select(denormal, ir.binary("and", x, "1023"), mantissa); + auto e = select(denormal, ir.binary("sub", "1", steps), exponent); + delta = select(cmp("slt", delta, "-64"), "-64", select(cmp("sgt", delta, "64"), "64", delta)); + e = ir.binary("add", e, delta); + auto normal = ir.binary("or", sign, ir.binary("or", ir.binary("shl", e, "10"), mantissa)); + auto full = ir.binary("or", mantissa, "1024"); + auto amount = select(cmp("sgt", e, "0"), "1", select(cmp("slt", e, "-10"), "11", ir.binary("sub", "1", e))); + auto half = ir.binary("shl", "1", ir.binary("sub", amount, "1")); + auto rest = ir.binary("and", full, ir.binary("sub", ir.binary("shl", half, "1"), "1")); + auto q = ir.binary("lshr", full, amount); + auto up = ir.value("or i1 " + cmp("ugt", rest, half) + ", " + + ir.value("and i1 " + cmp("eq", rest, half) + ", " + + cmp("ne", ir.binary("and", q, "1"), "0"))); + auto subnormal = ir.binary("or", sign, ir.binary("add", q, ir.value("zext i1 " + up + " to i32"))); + string result = select(cmp("sgt", e, "0"), normal, select(cmp("slt", e, "-10"), sign, subnormal)); + result = select(cmp("sgt", e, "30"), ir.binary("or", sign, "31744"), result); + result = select(keep, bits, result); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + auto kept = ir.binary("and", read(i.dst), "4294901760"); + vector_write(i.dst, ir.binary("or", kept, ir.binary("and", result, "65535"))); + return true; + } + if (binary16_alu(n) || binary16_unary(n)) { + // The graphics frontend shares this ALU. Leave those programs on the + // existing refusal; this lowering is the direct compute path. + if (graphics_input) + return false; + if (i.clamp || i.scale) + refuse(i.pc, "unsupported " + string(n) + " clamp or omod"); + // op_sel bits 11..14 select a high half. Bit 15 is clamp, already refused. + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto half_bits = [&](unsigned j) { + const unsigned r = i.src[j]; + string bits; + if (!j && permuted) { + bits = ir.binary("and", *permuted, "65535"); + } else if (i.subword) { + auto inline_word = packed_f16_inline_constant(r); + auto word = inline_word ? to_string(*inline_word) : operand32(i, r); + // Select from the full operand word. DWORD reads the low half. + const unsigned sel = i.src_select[j]; + // Only the binary16 value of an inline constant is modelled; its other + // half under SDWA is not documented here, so a high-half pick stays refused. + if (inline_word && sel != 4 && sel != 6) + refuse(i.pc, "unsupported SDWA binary16 inline constant selection"); + bits = subword(word, sel == 6 ? 4 : sel, false); + } else if (r >= 240 && r <= 248) { + // Inline floats are f32 patterns. The f16 operation consumes the + // binary16 rounding of that value. + bits = to_string(inline_half_words[r - 240]); + } else if (r == 255) + bits = to_string(i.literal & 65535u); + else if (r >= 128 && r <= 192) + bits = to_string((r - 128) & 65535u); + else if (r >= 193 && r <= 208) + bits = to_string((192u - r) & 65535u); + else + bits = ir.binary("and", operand32(i, r), "65535"); + if (i.abs & (1u << j)) + bits = ir.binary("and", bits, "32767"); + if (i.neg & (1u << j)) + bits = ir.binary("xor", bits, "32768"); + return bits; + }; + auto widen = [&](const string &bits) { + return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + }; + const auto source = half_bits(0); + auto a = widen(source); + const bool rsq = n == "v_rsq_f16", exp = n == "v_exp_f16"; + string widened; + if (n == "v_rcp_f16") { + widened = ir.value("fdiv float 1.000000e+00, " + a); + } else if (binary16_unary(n)) { + const unsigned opcode = rsq ? 25 : exp ? 21 : 24; + widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone"); + } else { + auto b = widen(half_bits(1)); + if (n == "v_subrev_f16") + std::swap(a, b); + const char *op = n == "v_mul_f16" ? "fmul" : n == "v_add_f16" ? "fadd" : "fsub"; + widened = ir.value(string(op) + " float " + a + ", " + b); + } + auto bits = ir.value("bitcast float " + widened + " to i32"); + // Round with the same integer nearest-even conversion v_cvt_f16_f32 uses. + auto rounded = packed_half_rne(bits); + if (rsq) { + // Enforce RDNA2's exact special results from the modified half bits. + // The D3D Rsqrt contract does not guarantee a negative infinity for -0. + // Select the other special results explicitly as well. + const auto magnitude = ir.binary("and", source, "32767"); + // Every encoding above +infinity is negative or a positive NaN. + rounded = select(cmp("ugt", source, "31744"), "32256", rounded); + rounded = select(cmp("eq", source, "31744"), "0", rounded); + const auto zero_result = ir.binary("or", source, "31744"); + rounded = select(cmp("eq", magnitude, "0"), zero_result, rounded); + } else if (exp) { + for (const auto &entry : exp_f16_midpoints) + rounded = select(cmp("eq", source, to_string(entry.source)), to_string(entry.result), rounded); + // 2^-25 is exactly halfway between zero and the smallest half subnormal. + rounded = select(cmp("eq", source, to_string(0xce40)), "0", rounded); + const auto magnitude = ir.binary("and", source, "32767"); + rounded = select(cmp("ugt", magnitude, "31744"), "32256", rounded); + } + // D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest says + // "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does. + vector_write(i.dst, i.subword ? place_subword(i, rounded) + : ir.binary("or", ir.binary("and", read(i.dst), "4294901760"), + ir.binary("and", rounded, "65535"))); + return true; + } + if (n == "v_fma_f16" || n == "v_fmac_f16" || n == "v_fmamk_f16" || n == "v_fmaak_f16") { + if (graphics_input) + return false; + if (i.dpp_control || permuted) + refuse(i.pc, "unsupported " + string(n) + " DPP form"); + if (i.subword) + refuse(i.pc, "unsupported " + string(n) + " SDWA form"); + if (i.scale) + refuse(i.pc, "unsupported " + string(n) + " omod"); + const unsigned op_sel = i.wide ? (i.a >> 11) & 15u : 0; + if (op_sel && (n != "v_fma_f16" || i.enc != Encoding::Vop3 || i.clamp)) + refuse(i.pc, "unsupported " + string(n) + " high-half op_sel"); + for (unsigned j = 0; j < 3; ++j) { + if ((op_sel & (1u << j)) && i.src[j] < 256) + refuse(i.pc, "unsupported v_fma_f16 high-half op_sel on non-VGPR source"); + } + if (n == "v_fmac_f16" && i.wide && (((i.abs | i.neg) & 4) || i.src[2])) + refuse(i.pc, "unsupported v_fmac_f16 third-source modifier"); + if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu)) + refuse(i.pc, "unsupported binary16 rounding or denormal mode"); + auto half_bits = [&](unsigned j) { + const unsigned r = i.src[j]; + string bits; + if (op_sel & (1u << j)) { + bits = ir.binary("lshr", operand32(i, r), "16"); + } else if (r >= 240 && r <= 248) { + constexpr unsigned halves[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000, + 0xc000, 0x4400, 0xc400, 0x3118}; + bits = to_string(halves[r - 240]); + } else if (r == 255) + bits = to_string(i.literal & 65535u); + else if (r >= 128 && r <= 192) + bits = to_string((r - 128) & 65535u); + else if (r >= 193 && r <= 208) + bits = to_string((192u - r) & 65535u); + else + bits = ir.binary("and", operand32(i, r), "65535"); + if (i.abs & (1u << j)) + bits = ir.binary("and", bits, "32767"); + if (i.neg & (1u << j)) + bits = ir.binary("xor", bits, "32768"); + return bits; + }; + auto a = half_bits(0); + auto b = n == "v_fmamk_f16" ? to_string(i.literal & 65535u) : half_bits(1); + auto c = n == "v_fma_f16" ? half_bits(2) + : n == "v_fmac_f16" ? ir.binary("and", read(i.dst), "65535") + : n == "v_fmamk_f16" ? half_bits(1) + : to_string(i.literal & 65535u); + auto result = fused_half_rne(a, b, c); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + const bool dst_high = (op_sel & 8u) != 0; + auto kept = ir.binary("and", read(i.dst), dst_high ? "65535" : "4294901760"); + auto placed = dst_high ? ir.binary("shl", result, "16") : ir.binary("and", result, "65535"); + vector_write(i.dst, ir.binary("or", kept, placed)); + return true; + } + const auto rule = alu_rules.find(n); + const bool byte_to_float = + n.size() == 16 && n.substr(0, 15) == "v_cvt_f32_ubyte" && n.back() >= '0' && n.back() <= '3'; + const bool off_i4_to_float = n == "v_cvt_off_f32_i4"; + const bool round = n == "v_fract_f32" || n == "v_trunc_f32" || n == "v_ceil_f32"; + const bool to_integer = n == "v_cvt_i32_f32" || n == "v_cvt_u32_f32" || + n == "v_cvt_flr_i32_f32" || n == "v_cvt_rpi_i32_f32"; + const bool cube = n == "v_cubeid_f32" || n == "v_cubesc_f32" || n == "v_cubetc_f32" || n == "v_cubema_f32"; + const bool mixed = i.enc == Encoding::Mix && (n == "v_fma_mix_f32" || n == "v_fma_mixlo_f16" || n == "v_fma_mixhi_f16"); + const bool unfused_mad = n == "v_mad_f32" || n == "v_mad_legacy_f32" || n == "v_mac_f32" || + n == "v_mac_legacy_f32" || n == "v_madmk_f32" || n == "v_madak_f32"; + if (!mixed && !to_integer && !byte_to_float && !off_i4_to_float && !round && !cube && !unfused_mad && + n != "v_mul_legacy_f32" && + n != "v_cos_f32" && (rule == alu_rules.end() || rule->second.type == AluType::Bits)) + return false; + auto source = [&](unsigned j) { + auto v = !j && permuted ? *permuted : operand32(i, i.src[j]); + if (i.subword && j < 2) + v = subword(v, i.src_select[j], i.src_sext[j]); + return v; + }; + auto fp = [&](unsigned j) { + auto bits = source(j); + if (i.abs & (1u << j)) + bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) + bits = ir.binary("xor", bits, "2147483648"); + return ir.value("bitcast i32 " + bits + " to float"); + }; + auto unary = [&](unsigned op, const string &v) { + return ir.invoke("float", "unary.f32", op, {{"float", v}}, "nounwind readnone"); + }; + auto binary = [&](unsigned op, const string &a, const string &b) { + return ir.invoke("float", "binary.f32", op, {{"float", a}, {"float", b}}, "nounwind readnone"); + }; + string result; + if (to_integer) { + if (i.scale || i.clamp) + refuse(i.pc, "integer conversion output modifier"); + auto a = fp(0); + if (n == "v_cvt_rpi_i32_f32") + a = ir.value("fadd float " + a + ", 0.5"); + if (n == "v_cvt_rpi_i32_f32" || n == "v_cvt_flr_i32_f32") + a = unary(27, a); + const bool sign = n != "v_cvt_u32_f32"; + // Only convert a representable input. Select the ISA's saturated + // result (and zero for NaN) independently of LLVM poison behavior. + auto lower = ir.value("fcmp oge float " + a + ", " + (sign ? "-2147483648.0" : "0.0")); + auto upper = ir.value("fcmp olt float " + a + ", " + (sign ? "2147483648.0" : "4294967296.0")); + auto safe = select_float(ir.value("and i1 " + lower + ", " + upper), a, "0.0"); + auto converted = ir.value(string(sign ? "fptosi" : "fptoui") + " float " + safe + " to i32"); + auto bounded = select(upper, converted, sign ? "2147483647" : "4294967295"); + if (sign) + bounded = select(lower, bounded, "2147483648"); + else + bounded = select(lower, bounded, "0"); + auto ordered = ir.value("fcmp ord float " + a + ", " + a); + vector_write(i.dst, place_subword(i, select(ordered, bounded, "0"))); + return true; + } + if (mixed) { + // GFX10 VOP3P splits OP_SEL_HI between the two instruction words. + const unsigned half = ((i.b >> 27) & 3) | ((i.a >> 12) & 4); + std::vector<std::pair<string,string>> args; + for (unsigned j = 0; j < 3; ++j) { + auto bits = source(j); + if (half & (1u << j)) { + bits = subword(bits, 4 + ((i.a >> (11 + j)) & 1), false); + const auto value = ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); + bits = ir.value("bitcast float " + value + " to i32"); + } + if (i.abs & (1u << j)) bits = ir.binary("and", bits, "2147483647"); + if (i.neg & (1u << j)) bits = ir.binary("xor", bits, "2147483648"); + args.emplace_back("float", ir.value("bitcast i32 " + bits + " to float")); + } + result = ir.invoke("float", "tertiary.f32", 46, args, "nounwind readnone"); + if (i.clamp) result = unary(7, result); + if (n == "v_fma_mix_f32") { + vector_write(i.dst, ir.value("bitcast float " + result + " to i32")); + } else { + auto h = ir.invoke("i32", "legacyF32ToF16", 130, {{"float", result}}, "nounwind readnone"); + const bool high = n == "v_fma_mixhi_f16"; + auto keep = ir.binary("and", read(i.dst), high ? "65535" : "4294901760"); + vector_write(i.dst, ir.binary("or", keep, high ? ir.binary("shl", h, "16") : ir.binary("and", h, "65535"))); + } + return true; + } + if (byte_to_float || off_i4_to_float || (rule != alu_rules.end() && rule->second.type == AluType::ToFloat)) { + if (i.abs || i.neg) + refuse(i.pc, "integer conversion source modifier"); + if (off_i4_to_float && i.wide && (i.src[1] != 0 || i.src[2] != 0)) + refuse(i.pc, "v_cvt_off_f32_i4 with unused src1/src2 field set"); + if (off_i4_to_float && i.wide && (i.a & 0x7800)) + refuse(i.pc, "v_cvt_off_f32_i4 with op_sel"); + auto a = source(0); + if (byte_to_float) { + unsigned shift_bits = 8u * (n.back() - '0'); + if (shift_bits) + a = ir.binary("lshr", a, to_string(shift_bits)); + a = ir.binary("and", a, "255"); + } + if (off_i4_to_float) { + auto nibble = ir.binary("ashr", ir.binary("shl", a, "28"), "28"); + auto f = ir.value("sitofp i32 " + nibble + " to float"); + result = ir.value("fmul float " + f + ", 0.0625"); + } else { + result = ir.value(string(n == "v_cvt_f32_i32" ? "sitofp" : "uitofp") + " i32 " + a + " to float"); + } + } else { + auto a = fp(0); + if (n == "v_fma_f32" || n == "v_fmac_f32" || n == "v_fmamk_f32" || n == "v_fmaak_f32") { + // Victory emit/lower.rs uses DXIL FMad for gfx10 f32 FMA. + auto as_float = [&](const string &bits) { return ir.value("bitcast i32 " + bits + " to float"); }; + auto b = n == "v_fmamk_f32" ? as_float(to_string(i.literal)) : fp(1); + auto c = n == "v_fmac_f32" ? as_float(read(i.dst)) : n == "v_fmaak_f32" ? as_float(to_string(i.literal)) : + n == "v_fmamk_f32" ? fp(1) : fp(2); + result = ir.invoke("float", "tertiary.f32", 46, {{"float", a}, {"float", b}, {"float", c}}, "nounwind readnone"); + } else if (unfused_mad) { + // gfx2hlsl.py mad32 and pixel_aot (#3005): flush denormal inputs to signed zero, round the product on + // its own (the legacy form makes 0 * anything 0), add the flushed addend and flush the sum. Plain + // fmul and fadd carry no fast-math flags, so DXIL does not allow them to be contracted into FMad. + auto ftz = [&](const string &x) { + auto bits = ir.value("bitcast float " + x + " to i32"); + auto tiny = cmp("ult", ir.binary("and", bits, "2147483647"), "8388608"); + auto kept = ir.binary("and", bits, select(tiny, "2147483648", "4294967295")); + return ir.value("bitcast i32 " + kept + " to float"); + }; + const bool legacy = n == "v_mad_legacy_f32" || n == "v_mac_legacy_f32"; + const bool literal_k = n == "v_madmk_f32" || n == "v_madak_f32"; + if (literal_k && (i.wide || i.subword || i.dpp_control || permuted)) + refuse(i.pc, "unsupported " + string(n) + " encoding"); + if (n.substr(0, 5) == "v_mac" && ((i.abs | i.neg) & 4)) + refuse(i.pc, "unsupported " + string(n) + " accumulator modifier"); + auto lit_float = [&]() { return ir.value("bitcast i32 " + to_string(i.literal) + " to float"); }; + auto x = ftz(a); + auto y = ftz(n == "v_madmk_f32" ? lit_float() : fp(1)); + auto c = n.substr(0, 5) == "v_mac" ? ir.value("bitcast i32 " + read(i.dst) + " to float") + : n == "v_madak_f32" ? lit_float() + : n == "v_madmk_f32" ? fp(1) + : fp(2); + auto product = ir.value("fmul float " + x + ", " + y); + if (legacy) { + auto zero = ir.value("or i1 " + ir.value("fcmp oeq float " + x + ", 0.0") + ", " + + ir.value("fcmp oeq float " + y + ", 0.0")); + product = select_float(zero, "0.0", product); + } + result = ftz(ir.value("fadd float " + ftz(product) + ", " + ftz(c))); + } else if (n == "v_mul_legacy_f32") { + auto b = fp(1); + auto zero = ir.value("or i1 " + ir.value("fcmp oeq float " + a + ", 0.0") + ", " + + ir.value("fcmp oeq float " + b + ", 0.0")); + result = select_float(zero, "0.0", ir.value("fmul float " + a + ", " + b)); + } else if (n == "v_sin_f32" || n == "v_cos_f32") { + // Victory trig_turns: reduce in turns before converting to + // radians, preserving signed zero and exact quarter-turn zeros. + auto part = ir.value("fsub float " + a + ", " + unary(26, a)); + part = select_float(ir.value("fcmp oeq float " + a + ", 0.0"), a, part); + const bool cosine = n == "v_cos_f32"; + auto radians = ir.value("fmul float " + part + ", 0x401921FB60000000"); + auto exact = ir.value("fcmp oeq float " + unary(6, part) + (cosine ? ", 0.25" : ", 0.5")); + result = select_float(exact, "0.0", unary(cosine ? 12 : 13, radians)); + } else if (cube) + result = cube_alu(n, a, fp(1), fp(2)); + else if (n == "v_add_f32" || n == "v_sub_f32" || n == "v_subrev_f32" || n == "v_mul_f32") { + auto b = fp(1); + if (n == "v_subrev_f32") + std::swap(a, b); + result = ir.value(string(n == "v_add_f32" ? "fadd" + : n == "v_mul_f32" ? "fmul" + : "fsub") + + " float " + a + ", " + b); + } else if (n == "v_med3_f32") { + auto b = fp(1), c = fp(2); + auto lo = binary(36, a, b), hi = binary(35, a, b); + auto median = binary(35, lo, binary(36, hi, c)); + auto nan = ir.value("or i1 " + ir.value("fcmp uno float " + a + ", " + b) + ", " + + ir.value("fcmp uno float " + c + ", " + c)); + result = select_float(nan, binary(36, lo, c), median); + } else if (n == "v_min_f32" || n == "v_max_f32" || n == "v_min3_f32" || n == "v_max3_f32") { + unsigned op = n.substr(2, 3) == "min" ? 36 : 35; + result = binary(op, a, fp(1)); + if (rule->second.arity == 3) + result = binary(op, result, fp(2)); + } else if (n == "v_exp_f32") + result = unary(21, a); + else if (n == "v_log_f32") + result = unary(23, a); + else if (n == "v_rndne_f32") + result = unary(26, a); + else if (n == "v_floor_f32") + result = unary(27, a); + else if (round) { + result = unary(n == "v_fract_f32" ? 22 : n == "v_ceil_f32" ? 28 : 29, a); + // A host Frc can round tiny negative inputs up to 1.0. The guest's + // result stays below 1.0; an ordered comparison keeps NaNs intact. + if (n == "v_fract_f32") + result = select_float(ir.value("fcmp oge float " + result + ", 1.0"), + ir.value("bitcast i32 1065353215 to float"), result); + } else if (n == "v_sqrt_f32") + result = unary(24, a); + else if (n == "v_rsq_f32") + result = unary(25, a); + else if (n == "v_rcp_f32" || n == "v_rcp_iflag_f32") + result = ir.value("fdiv float 1.000000e+00, " + a); + else + return false; + } + if (i.scale) + result = ir.value("fmul float " + result + ", " + (i.scale == 1 ? "2.0" : i.scale == 2 ? "4.0" : "0.5")); + if (i.clamp) + result = unary(7, result); + vector_write(i.dst, place_subword(i, ir.value("bitcast float " + result + " to i32"))); + return true; + } + string graphics_lane_mask(const Inst &i, const State &state, unsigned src, const char *failure) { + if (src == 106) return read(106); + if (src < 106) { + const auto &mask = state[src]; + if ((mask.type == Symbol::Type::lane_mask || mask.type == Symbol::Type::uniform_mask) && !mask.offset && + (!analysis.program.graphics_wave64 || (!(src & 1) && + state[src+1] == Symbol{mask.type,mask.value,1}))) + return read(1024+mask.value); + } + refuse(i.pc,failure); + } + string comparison(const Inst &i) { + if (graphics_input && i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported graphics compare operand selection"); + if ((i.abs || i.neg) && i.name.find("_f16") == Name::npos && i.name.find("_f32") == Name::npos) + refuse(i.pc, "integer comparison with floating modifier"); + auto input = [&](unsigned j) { + auto value = operand32(i,i.src[j]); + return i.subword ? subword(value,i.src_select[j],i.src_sext[j]) : value; + }; + auto a = input(0), b = input(1); + return comparison(i,a,b); + } + string integer_comparison64(const Inst &i, Name op, bool sign) { + if (i.subword || i.abs || i.neg || i.clamp || i.scale || (i.wide && (i.a & 0x7800))) + refuse(i.pc, "unsupported 64-bit integer comparison modifiers"); + string predicate(op); + if (op == "lt" || op == "le" || op == "gt" || op == "ge") + predicate.insert(0, 1, sign ? 's' : 'u'); + else if (op != "eq" && op != "ne") + refuse(i.pc, "direct comparison width"); + + auto extend = [&](const char *how, unsigned src) { + return ir.value(string(how) + " i32 " + operand32(i, src) + " to i64"); + }; + auto input = [&](unsigned src) { + if ((src <= 104 && !(src & 1)) || (src >= 256 && src < 511)) { + auto low = extend("zext", src), high = extend("zext", src + 1); + auto upper = ir.value("shl i64 " + high + ", 32"); + return ir.value("or i64 " + upper + ", " + low); + } + // A 64-bit integer operand sign-extends an inline constant for both i64 and u64. + if (src >= 128 && src <= 208) + return extend("sext", src); + refuse(i.pc, "direct 64-bit integer comparison operand"); + }; + auto lhs = input(i.src[0]), rhs = input(i.src[1]); + ir.features |= 1048576; + return ir.value("icmp " + predicate + " i64 " + lhs + ", " + rhs); + } + string comparison(const Inst &i, const string &lhs, const string &rhs) { + Name n = i.name; + const auto at = n.rfind('_'); + if (at == n.npos) + refuse(i.pc, "comparison missing type"); + Name type = n.substr(at + 1), stem = n.substr(0, at); + Name op = stem.substr(stem.rfind('_') + 1); + bool fp = type == "f16" || type == "f32"; + bool sign = type == "i16" || type == "i32"; + bool half = type == "f16" || type == "i16" || type == "u16"; + if (!fp && !sign && type != "u16" && type != "u32") + refuse(i.pc, "direct comparison width"); + if (op == "f") + return "false"; + if (op == "t" || op == "tru") + return "true"; + string a = lhs, b = rhs; + auto bits = [&](string v, unsigned j) { + if (i.abs & (1u << j)) + v = ir.binary("and", v, half ? "32767" : "2147483647"); + if (i.neg & (1u << j)) + v = ir.binary("xor", v, half ? "32768" : "2147483648"); + return v; + }; + if (op == "class" && fp) { + if ((i.abs | i.neg) & 2 || + (i.subword && (i.src_select[0] != 6 || i.src_sext[0])) || + (i.wide && (i.a & 0x7800))) + refuse(i.pc, "unsupported floating class operand selection"); + // The class mask is integer data. Testing raw bits keeps sNaNs, + // subnormals and negative zero distinct (gfx2hlsl's class16/32). + auto word = bits(a,0); + auto neg = cmp("ne", ir.binary("and",word,half ? "32768" : "2147483648"), "0"); + auto exp = ir.binary("and", word, half ? "31744" : "2139095040"); + auto frac = ir.binary("and", word, half ? "1023" : "8388607"); + auto empty = cmp("eq", frac, "0"); + auto nan = select(cmp("ne",ir.binary("and",frac,half ? "512" : "4194304"),"0"), "2", "1"); + auto zero_or_tiny = select(empty, select(neg,"32","64"), select(neg,"16","128")); + auto normal = select(neg,"8","256"); + auto cls = select(cmp("eq",exp,half ? "31744" : "2139095040"), + select(empty,select(neg,"4","512"),nan), + select(cmp("eq",exp,"0"),zero_or_tiny,normal)); + return cmp("ne",ir.binary("and",cls,b),"0"); + } + if (fp) { + auto convert = [&](const string &v, unsigned j) { + auto value = bits(v, j); + return half ? ir.invoke("float", "legacyF16ToF32", 131, {{"i32", ir.binary("and", value, "65535")}}, + "nounwind readnone") + : ir.value("bitcast i32 " + value + " to float"); + }; + a = convert(a, 0); + b = convert(b, 1); + static const std::map<Name, Name> predicates{{"lt", "olt"}, {"le", "ole"}, {"eq", "oeq"}, {"lg", "one"}, + {"gt", "ogt"}, {"ge", "oge"}, {"o", "ord"}, {"u", "uno"}, + {"nge", "ult"}, {"nlg", "ueq"}, {"ngt", "ule"}, {"nle", "ugt"}, + {"neq", "une"}, {"nlt", "uge"}}; + auto it = predicates.find(op); + if (it == predicates.end()) + refuse(i.pc, "unknown floating comparison predicate"); + return ir.value("fcmp " + string(it->second) + " float " + a + ", " + b); + } + if (half) { + a = subword(a, 4, sign); + b = subword(b, 4, sign); + } + if (op == "eq") + return cmp("eq", a, b); + if (op == "lg" || op == "ne") + return cmp("ne", a, b); + if (op != "lt" && op != "le" && op != "gt" && op != "ge") + refuse(i.pc, "unknown integer comparison predicate"); + return cmp(string(sign ? "s" : "u") + string(op), a, b); + } + // Compute SCC liveness once, only for programs that construct buffer + // descriptors symbolically. A join can observe the old SCC through either + // predecessor. Closed loops without a read do not make it live. + bool uses_scc_after(const Inst &definition) { + const auto &program = analysis.program; + if (scc_live.empty()) { + scc_live.resize(program.code.size()); + std::vector<std::vector<size_t>> predecessors(program.code.size()); + std::vector<size_t> pending; + for (size_t j = 0; j < program.code.size(); ++j) { + const auto &inst = program.code[j]; + const auto n = inst.name; + const bool reads_scc = n == "s_cselect_b32" || n == "s_cselect_b64" || + n == "s_cmov_b32" || n == "s_cmov_b64" || n == "s_cmovk_i32" || + std::find(inst.src.begin(), inst.src.end(), 253u) != inst.src.end(); + // These scalar mask operations set SCC from their entire + // result and do not consume the incoming SCC. An explicit + // SRC_SCC operand still takes precedence below. + const bool mask_scc = n == "s_andn2_b64" || n == "s_and_b64" || n == "s_or_b64" || + n == "s_xor_b64" || n == "s_orn2_b64" || n == "s_nand_b64" || n == "s_nor_b64" || + n == "s_xnor_b64" || n == "s_not_b64" || n == "s_wqm_b32" || n == "s_wqm_b64" || + n == "s_quadmask_b32" || n == "s_quadmask_b64" || + n == "s_and_saveexec_b64" || n == "s_or_saveexec_b64" || n == "s_xor_saveexec_b64" || + n == "s_andn2_saveexec_b64" || n == "s_orn2_saveexec_b64" || + n == "s_nand_saveexec_b64" || n == "s_nor_saveexec_b64" || n == "s_xnor_saveexec_b64" || + n == "s_andn1_saveexec_b64" || n == "s_orn1_saveexec_b64" || + n == "s_andn1_wrexec_b64" || n == "s_andn2_wrexec_b64"; + const bool overwrites = mask_scc || n == "s_abs_i32" || + n == "s_bcnt0_i32_b32" || n == "s_bcnt1_i32_b32" || + n == "s_bcnt0_i32_b64" || n == "s_bcnt1_i32_b64" || + inst.enc == Encoding::Sopc || n == "s_bfe_u32" || n == "s_and_b32" || + n == "s_or_b32" || n == "s_max_u32" || n == "s_min_u32" || n == "s_min_i32" || + n == "s_max_i32" || n == "s_absdiff_i32" || n == "s_add_u32" || n == "s_sub_u32" || + n == "s_add_i32" || n == "s_sub_i32" || n == "s_and_saveexec_b32" || + n == "s_or_saveexec_b32" || n == "s_xor_saveexec_b32" || n == "s_andn2_saveexec_b32" || + n == "s_orn2_saveexec_b32" || n == "s_nand_saveexec_b32" || n == "s_nor_saveexec_b32" || + n == "s_xnor_saveexec_b32" || n == "s_andn1_saveexec_b32" || n == "s_orn1_saveexec_b32" || + n == "s_andn1_wrexec_b32" || n == "s_andn2_wrexec_b32" || n == "s_andn2_b32" || + n == "s_orn2_b32" || n == "s_nor_b32" || n == "s_nand_b32" || n == "s_xnor_b32" || + n == "s_not_b32" || + n == "s_lshr_b32" || n == "s_lshl_b32" || n == "s_ashr_i32" || + n == "s_lshl_b64" || n == "s_lshr_b64" || n == "s_ashr_i64" || n == "s_xor_b32" || + n == "s_bfe_u64" || n == "s_bfe_i64" || + n == "s_lshl1_add_u32" || n == "s_lshl2_add_u32" || n == "s_lshl3_add_u32" || n == "s_lshl4_add_u32"; + const bool preserves_pair = n == "s_mul_i32" || n == "s_mul_hi_i32" || n == "s_mul_hi_u32" || + n == "s_bfm_b32" || n == "s_bfm_b64" || n == "s_pack_ll_b32_b16" || n == "s_pack_lh_b32_b16" || + n == "s_pack_hh_b32_b16"; + const bool preserves_sop1 = n == "s_mov_b32" || n == "s_mov_b64" || + n == "s_brev_b32" || n == "s_brev_b64" || + n == "s_ff0_i32_b32" || n == "s_ff0_i32_b64" || + n == "s_ff1_i32_b32" || n == "s_ff1_i32_b64" || + n == "s_flbit_i32_b32" || n == "s_flbit_i32_b64" || + n == "s_flbit_i32" || n == "s_flbit_i32_i64" || + n == "s_sext_i32_i8" || n == "s_sext_i32_i16" || + n == "s_bitset0_b32" || n == "s_bitset0_b64" || + n == "s_bitset1_b32" || n == "s_bitset1_b64" || n == "s_bitreplicate_b64_b32"; + const bool uncertain_scalar = (inst.enc == Encoding::Sopk && n != "s_movk_i32") || + (inst.enc == Encoding::Sop2 && !overwrites && !preserves_pair) || + (inst.enc == Encoding::Sop1 && !overwrites && !preserves_sop1); + if (reads_scc || uncertain_scalar || (inst.branch() && (inst.op == 4 || inst.op == 5))) { + scc_live[j] = true; + pending.push_back(j); + continue; + } + if (overwrites || n == "s_endpgm") continue; + if (inst.branch()) predecessors[program.at.at(inst.target())].push_back(j); + if (!inst.branch() || inst.op != 2) + predecessors[program.at.at(inst.next)].push_back(j); + } + while (!pending.empty()) { + const auto j = pending.back(); + pending.pop_back(); + for (auto prev : predecessors[j]) { + if (scc_live[prev]) continue; + scc_live[prev] = true; + pending.push_back(prev); + } + } + } + return scc_live[program.at.at(definition.next)]; + } + void prepare_descriptor_strides() { + const auto &p = analysis.program; + const auto &layout = analysis.layout; + std::map<std::pair<unsigned,unsigned>,size_t> sources; + for (size_t n = 0; n < p.code.size(); ++n) { + if (!p.reached[n]) continue; + const auto &i = p.code[n]; + const auto field = byte_descriptor_field(i,p.before[n],heap_window); + if (!field || (field->type != Symbol::Type::stride && field->type != Symbol::Type::byte_stride) || + field->definition || field->value >= layout.NumParameters || !uses_scc_after(i)) + continue; + const auto ¶meter = layout.pParameters[field->value]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE || + parameter.ShaderVisibility != D3D12_SHADER_VISIBILITY_ALL) + continue; + // The runtime provides the stride only for a fixed buffer SRV. + const auto &table = parameter.DescriptorTable; + const auto slot = field->offset / 32; + uint64_t next = 0; + unsigned srvs = 0, other = 0; + for (unsigned j = 0; j < table.NumDescriptorRanges; ++j) { + const auto &range = table.pDescriptorRanges[j]; + const uint64_t start = range.OffsetInDescriptorsFromTableStart == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND + ? next : range.OffsetInDescriptorsFromTableStart; + next = start + range.NumDescriptors; + if (start <= slot && slot < next) { + if (range.RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SRV) ++srvs; + else ++other; + } + } + if (srvs == 1 && !other) + sources.try_emplace({field->value,field->offset},n); + } + for (const auto &[source, n] : sources) { + const auto [root, offset] = source; + if (read_write_raw_views.count(source)) continue; + State descriptor; + for (unsigned j=0; j<4; ++j) + descriptor[j] = {Symbol::Type::descriptor,root,offset+4*j}; + analysis.binding(p.code[n],descriptor,0,4,ComputeViewKind::raw_vector_srv,4); + analysis.result.stride_srvs.push_back(analysis.result.bindings.back().shader_register); + descriptor_strides.try_emplace(source); + } + if (!descriptor_strides.empty()) { + size_t words = descriptor_strides.size(); + for (const auto &block : analysis.result.constants) words += block.count; + if (words > 32) + refuse(p.code.front().pc,"descriptor stride metadata exceeds the 32-word compute entry layout"); + } + } + string saturated_add(const string &a, const string &b, bool sign) { + auto sum = ir.binary("add", a, b); + if (!sign) + return select(cmp("ult", sum, a), "4294967295", sum); + auto overflow = ir.binary("and", ir.binary("xor", a, sum), ir.binary("xor", b, sum)); + return select(cmp("slt", overflow, "0"), select(cmp("slt", a, "0"), "2147483648", "2147483647"), sum); + } + bool packed_minmax(const Inst &i, const State &state) { + if (i.enc != Encoding::Mix) + return false; + const auto n = i.name; + const bool floating = n == "v_pk_min_f16" || n == "v_pk_max_f16"; + const bool signed_int = n == "v_pk_min_i16" || n == "v_pk_max_i16"; + if (!floating && !signed_int && n != "v_pk_min_u16" && n != "v_pk_max_u16") + return false; + // VOP3P NEG_HI/LO occupy the usual ABS/NEG fields. The third + // OP_SEL_HI bit and third-operand modifiers are unused here. + const bool bad_mods = floating ? ((i.abs & 4) || (i.neg & 4)) : (i.clamp || i.abs || i.neg); + if (bad_mods || i.src[2] || (i.a & 0x2000)) + refuse(i.pc, "unsupported packed 16-bit min/max encoding"); + if (floating && (!half_mode_known || (mode_bits & 0xc0u) != 0xc0u)) + refuse(i.pc, "unsupported packed binary16 min/max denormal mode"); + auto source = [&](unsigned src) { + if (floating) { + if (auto inline_word = packed_f16_inline_constant(src)) + return to_string(*inline_word); + } else if (src >= 128 && src <= 208) { + return operand32(i, src); + } + if (src <= 105) { + if (state[src].type == Symbol::Type::masked || state[src].type == Symbol::Type::uniform_mask) + refuse(i.pc, "packed 16-bit min/max uses a lane mask"); + } else if (src < 256 && src != 255) { + refuse(i.pc, "unsupported packed 16-bit min/max source"); + } + return operand32(i, src); + }; + const auto a = source(i.src[0]), b = source(i.src[1]); + const bool maximum = n.substr(5, 3) == "max"; + auto half = [&](const string &word, bool high) { + return high ? ir.binary("lshr", word, "16") : ir.binary("and", word, "65535"); + }; + auto order_key = [&](const string &bits) -> string { + if (floating) { + // Binary16 encodings are monotone within each sign. Reverse + // the negative half of that order and keep -0 below +0. + auto negative = cmp("uge", bits, "32768"); + return ir.binary("xor", bits, select(negative, "65535", "32768")); + } + return signed_int ? ir.binary("xor", bits, "32768") : bits; + }; + auto lane = [&](unsigned selectors, unsigned negate) { + auto x = half(a, selectors & 1), y = half(b, selectors & 2); + if (floating && (negate & 1u)) + x = ir.binary("xor", x, "32768"); + if (floating && (negate & 2u)) + y = ir.binary("xor", y, "32768"); + auto result = select(cmp(maximum ? "ugt" : "ult", order_key(x), order_key(y)), x, y); + if (floating) { + // Follow the existing startup contract. One NaN selects + // the numeric side. Two NaNs use the canonical quiet NaN. + auto x_nan = cmp("ugt", ir.binary("and", x, "32767"), "31744"); + auto y_nan = cmp("ugt", ir.binary("and", y, "32767"), "31744"); + result = select(x_nan, select(y_nan, "32256", y), select(y_nan, x, result)); + if (i.clamp) { + auto nan = cmp("ugt", ir.binary("and", result, "32767"), "31744"); + auto low = ir.value("or i1 " + nan + ", " + cmp("ne", ir.binary("and", result, "32768"), "0")); + result = select(low, "0", select(cmp("ugt", result, "15359"), "15360", result)); + } + } + return result; + }; + auto low = lane((i.a >> 11) & 3, i.neg), high = lane((i.b >> 27) & 3, i.abs); + vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16"))); + return true; + } + void arithmetic(const Inst &i, const State &state, const string *permuted = nullptr, bool compute = false) { + auto n = i.name; + if (compute) { + if (const auto offset = heap_offset_add(i, state)) { + // The heap base is slot 0 of ResourceDescriptorHeap: the low word keeps the byte offset, the carry is 0. + write(i.dst, operand32(i, i.src[*offset])); + write(128, "0"); + return; + } + } + const bool dot_accumulate = n == "v_dot4c_i32_i8"; + if (compute && (dot_accumulate || n == "v_dot4_i32_i8" || n == "v_dot4_u32_u8")) { + // Integer dots use both packed words as-is. The VOP3P forms + // require canonical OP_SEL/OP_SEL_HI and zero NEG_LO/NEG_HI. + if (dot_accumulate) { + if (i.enc != Encoding::Vop2 || i.wide || i.subword || i.dpp_control || permuted || + i.abs || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported packed byte dot-accumulate operand modifiers"); + } else if (i.enc != Encoding::Mix || (i.a & 0x7f00) != 0x4000 || (i.b >> 27) != 3) + refuse(i.pc, "unsupported packed byte dot operand modifiers"); + const bool sign = n != "v_dot4_u32_u8"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + auto acc = operand32(i, dot_accumulate ? i.dst : i.src[2]); + // The dot alone fits into i32 even for four unsigned 255*255 + // products. Saturate only the final addition to the accumulator. + auto dot = ir.invoke("i32", "dot4AddPacked.i32", sign ? 163 : 164, + {{"i32", i.clamp ? "0" : acc}, {"i32", a}, {"i32", b}}, "nounwind readnone"); + vector_write(i.dst, i.clamp ? saturated_add(dot, acc, sign) : dot); + return; + } + const bool signed_add_sub = n == "v_add_nc_i32" || n == "v_sub_nc_i32"; + if (signed_add_sub || (i.clamp && (n == "v_add_nc_u32" || n == "v_sub_nc_u32" || n == "v_subrev_nc_u32"))) { + // AMD RDNA 2 ISA: the VOP3-only signed forms wrap like the unsigned ones, and clamp saturates the + // result: signed for v_*_nc_i32, unsigned for v_*_nc_u32. LLVM 15 selects these clamp forms for + // llvm.sadd.sat, llvm.ssub.sat, llvm.uadd.sat and llvm.usub.sat (#3009). + if ((signed_add_sub && !i.wide) || i.subword || i.dpp_control || permuted || i.abs || i.neg || i.scale || + (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " operand modifiers"); + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + if (n == "v_subrev_nc_u32") std::swap(a, b); + const bool add = n.substr(0, 5) == "v_add"; + auto result = ir.binary(add ? "add" : "sub", a, b); + if (i.clamp) { + if (signed_add_sub) { + // Overflow when the operands' signs make the true result leave the i32 range; it saturates + // toward the sign of the first operand. + auto overflow = add ? ir.binary("and", ir.binary("xor", a, result), ir.binary("xor", b, result)) + : ir.binary("and", ir.binary("xor", a, b), ir.binary("xor", a, result)); + result = select(cmp("slt", overflow, "0"), + select(cmp("slt", a, "0"), "2147483648", "2147483647"), result); + } else if (add) + result = select(cmp("ult", result, a), "4294967295", result); + else + result = select(cmp("ult", a, b), "0", result); + } + vector_write(i.dst, result); + return; + } + if (compute && (n == "v_dot8_i32_i4" || n == "v_dot8_u32_u4")) { + // Integer dot products use both packed words as-is. Require the + // canonical VOP3P OP_SEL/OP_SEL_HI and zero NEG_LO/NEG_HI. + if (i.enc != Encoding::Mix || (i.a & 0x7f00) != 0x4000 || (i.b >> 27) != 3) + refuse(i.pc, "unsupported packed nibble dot operand modifiers"); + const bool sign = n == "v_dot8_i32_i4"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]), acc = operand32(i, i.src[2]); + auto nibble = [&](const string &word, unsigned shift) { + if (sign) { + auto aligned = shift < 28 ? ir.binary("shl", word, to_string(28 - shift)) : word; + return ir.binary("ashr", aligned, "28"); + } + auto shifted = shift ? ir.binary("lshr", word, to_string(shift)) : word; + return shift < 28 ? ir.binary("and", shifted, "15") : shifted; + }; + // Eight 4-bit products sum to [-448, 512] (signed) or [0, 1800] (unsigned), + // which always fits in i32. Saturate only the final addition to the accumulator. + string dot = ir.binary("mul", nibble(a, 0), nibble(b, 0)); + for (unsigned shift = 4; shift < 32; shift += 4) + dot = ir.binary("add", dot, ir.binary("mul", nibble(a, shift), nibble(b, shift))); + vector_write(i.dst, i.clamp ? saturated_add(dot, acc, sign) : ir.binary("add", dot, acc)); + return; + } + if (n == "v_mad_u32_u16" || n == "v_mad_i32_i16") { + // AMD RDNA 2 ISA, VOP3A opcodes 883/885. Only the two + // multiplicands are halfwords. The addend and result are dwords. + if (!i.wide || i.abs || i.neg || i.scale || (i.a & 0x6000)) + refuse(i.pc, "unsupported halfword MAD operand modifiers"); + const bool sign = n == "v_mad_i32_i16"; + auto half = [&](unsigned j) { + auto value = operand32(i, i.src[j]); + if (i.a & (1u << (11 + j))) return ir.binary(sign ? "ashr" : "lshr", value, "16"); + return sign ? ir.binary("ashr", ir.binary("shl", value, "16"), "16") + : ir.binary("and", value, "65535"); + }; + auto product = ir.binary("mul", half(0), half(1)); + auto addend = operand32(i, i.src[2]); + auto sum = i.clamp ? saturated_add(product, addend, sign) : ir.binary("add", product, addend); + vector_write(i.dst, sum); + return; + } + if (compute && (n == "v_pk_mul_lo_u16" || n == "v_pk_mad_u16" || n == "v_pk_mad_i16")) { + const bool mad = n != "v_pk_mul_lo_u16"; + const bool sign = n == "v_pk_mad_i16"; + if (i.enc != Encoding::Mix || (i.a & 0x0700) || (i.b >> 29) || + (!mad && (i.clamp || (i.a & 0x2000) || i.src[2]))) + refuse(i.pc, "unsupported packed 16-bit mul/mad operand modifiers"); + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + string c = mad ? operand32(i, i.src[2]) : string(); + auto half = [&](const string &word, bool hi, bool sext) { + if (sext) + return hi ? ir.binary("ashr", word, "16") + : ir.binary("ashr", ir.binary("shl", word, "16"), "16"); + return hi ? ir.binary("lshr", word, "16") : ir.binary("and", word, "65535"); + }; + auto lane = [&](bool hi_out) { + const bool sel_a = hi_out ? ((i.b >> 27) & 1) != 0 : ((i.a >> 11) & 1) != 0; + const bool sel_b = hi_out ? ((i.b >> 28) & 1) != 0 : ((i.a >> 12) & 1) != 0; + const bool sel_c = hi_out ? ((i.a >> 14) & 1) != 0 : ((i.a >> 13) & 1) != 0; + const bool sext = i.clamp && sign; + auto res = ir.binary("mul", half(a, sel_a, sext), half(b, sel_b, sext)); + if (mad) { + res = ir.binary("add", res, half(c, sel_c, sext)); + if (i.clamp) { + if (sign) { + res = select(cmp("sgt", res, "32767"), "32767", res); + res = select(cmp("slt", res, "-32768"), "-32768", res); + } else { + res = select(cmp("ugt", res, "65535"), "65535", res); + } + } + } + return ir.binary("and", res, "65535"); + }; + auto lo = lane(false), hi = lane(true); + vector_write(i.dst, ir.binary("or", lo, ir.binary("shl", hi, "16"))); + return; + } + if (n == "v_mad_u64_u32" || n == "v_mad_i64_i32") { + // D = S0 * S1 + S2 modulo 2^64 with 32-bit factors and a 64-bit S2 (#3000, gfx2hlsl.py mad64). The + // unsigned form writes the carry-out of the 64-bit add as a lane mask; the signed carry-out is not + // established, so the signed form is lowered only with the discarding null SDST. In VOP3B the ABS field + // holds SDST, so only NEG, clamp and the output modifier are refused here. + const bool sign = n == "v_mad_i64_i32"; + const unsigned sdst = (i.a >> 8) & 127, addend = i.src[2]; + if (pixel_stage || graphics_input || i.subword || i.dpp_control || i.neg || i.clamp || i.scale) + refuse(i.pc, "unsupported " + string(n) + " stage or operand modifiers"); + if (sign ? sdst != 125 : (sdst > 105 && sdst != 106)) + refuse(i.pc, string(n) + " carry-out destination"); + const bool vgpr_pair = addend >= 256 && addend < 511, sgpr_pair = addend <= 104 && !(addend & 1); + if (!(vgpr_pair || sgpr_pair) || i.dst >= 511) + refuse(i.pc, string(n) + " addend or destination operand"); + for (unsigned j = 0; j < 2; ++j) // gfx2hlsl.py refuses an inline float as a factor + if (i.src[j] >= 240 && i.src[j] <= 248) + refuse(i.pc, string(n) + " with an inline float factor"); + const char *extend = sign ? "sext" : "zext"; + auto wide = [&](const char *how, const string &x) { return ir.value(string(how) + " i32 " + x + " to i64"); }; + auto c = ir.value("or i64 " + ir.value("shl i64 " + wide("zext", operand32(i, addend + 1)) + ", 32") + ", " + + wide("zext", operand32(i, addend))); + auto product = ir.value("mul i64 " + wide(extend, operand32(i, i.src[0])) + ", " + + wide(extend, operand32(i, i.src[1]))); + auto sum = ir.value("add i64 " + product + ", " + c); + auto carry = ir.value("icmp ult i64 " + sum + ", " + c); + ir.features |= 1048576; + vector_write(i.dst, ir.value("trunc i64 " + sum + " to i32")); + vector_write(i.dst + 1, ir.value("trunc i64 " + ir.value("lshr i64 " + sum + ", 32") + " to i32")); + if (!sign) + write_ballot(sdst, carry); + return; + } + if (auto dst = carry_destination(i)) { + if (pixel_stage || (graphics_input && ir.loop_dependencies) || i.dpp_control || i.clamp || i.neg || i.scale) + refuse(i.pc, "unsupported carry instruction stage or operand modifiers"); + // Victory add_sub_carry and pixel_aot model unsigned carry/borrow + // as lane bits. Snapshot both operands and carry-in before writing + // the result VGPR or its possibly aliased scalar mask. + const bool add = n.substr(0, 5) == "v_add"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + if (i.subword) { + a = subword(a, i.src_select[0], i.src_sext[0]); + b = subword(b, i.src_select[1], i.src_sext[1]); + } + if (n.substr(0, 8) == "v_subrev") std::swap(a, b); + auto result = ir.binary(add ? "add" : "sub", a, b); + auto carry = add ? cmp("ult", result, a) : cmp("ult", a, b); + if (n.find("_ci_") != n.npos) { + unsigned src = i.src[2]; + // vcc_hi is a numeric wave32 mask in direct compute; translate_program refuses a guest wave64. + if (src > 107 || (src == 107 && (wave64 || graphics_input))) + refuse(i.pc, "unsupported carry-in mask source"); + string bit; + if (graphics_input) { + bit = cmp("ne",graphics_lane_mask(i,state,src,"unproven vertex carry-in mask"),"0"); + } else { + auto mask = operand32(i, src); + if (wave64) mask = select(upper_half, pair_high(i, src), mask); + bit = cmp("ne", ir.binary("and", mask, lane_bit), "0"); + } + auto edge = cmp("eq", result, add ? "4294967295" : "0"); + auto extra = ir.value("and i1 " + edge + ", " + bit); + carry = ir.value("or i1 " + carry + ", " + extra); + result = ir.binary(add ? "add" : "sub", result, ir.value("zext i1 " + bit + " to i32")); + } + vector_write(i.dst, place_subword(i, result)); + if (graphics_input) { + if (!graphics_predicate.empty()) carry = ir.value("and i1 " + graphics_predicate + ", " + carry); + auto bit = ir.value("zext i1 " + carry + " to i32"); + // An explicit VOP3B SDST leaves VCC untouched. Its per-lane + // bit may feed another carry, but neither dword is numeric. + if (*dst != 106) write(*dst,{}); + if (analysis.program.graphics_wave64) write(*dst+1,{}); + write(*dst == 106 ? 106 : 1024+i.pc,bit); + } else write_ballot(*dst, carry); + return; + } + if (auto field = byte_descriptor_field(i,state,heap_window)) { + // Keep derived words symbolic, including the status bit until a + // later instruction overwrites it. Never let a numeric branch + // observe a placeholder for this field or its SCC. + // The byte-address OOB selector ORs in two nonzero bits. + // Its SCC is known for every source descriptor. + if (field->type == Symbol::Type::byte_oob || field->type == Symbol::Type::root_stride_one_high) + write(128, "1"); + else if (n != "s_mul_i32" && uses_scc_after(i)) { + const auto stride = descriptor_strides.find({field->value,field->offset}); + if (stride == descriptor_strides.end() || field->definition || + (field->type != Symbol::Type::stride && field->type != Symbol::Type::byte_stride)) + refuse(i.pc, "numeric SCC from a symbolic descriptor field"); + string condition; + if (field->type == Symbol::Type::stride) + condition = cmp("ne",stride->second,"0"); + else if (source(i,i.src[0],state).type == Symbol::Type::stride) + condition = cmp("ugt",stride->second,"1"); + else + condition = cmp("ult",stride->second,"1"); + write(128,ir.value("zext i1 " + condition + " to i32")); + } + if (graphics_input) write(i.dst, {}); + return; + } + if (packed_minmax(i, state) || float_alu(i, permuted)) + return; + if (compute && i.enc == Encoding::Vopc && n.size() >= 10) { + const auto type = n.substr(n.size() - 4); + if (type == "_i64" || type == "_u64") { + const auto stem = n.substr(0, n.size() - 4); + auto condition = integer_comparison64(i, stem.substr(stem.rfind('_') + 1), type == "_i64"); + write_ballot(i.dst, condition); + return; + } + } + if (i.enc == Encoding::Vopc && !i.clamp && !i.scale && + (n.find("class") == n.npos || n.find("_f16") != n.npos || n.find("_f32") != n.npos)) { + auto condition = comparison(i); + write_ballot(i.dst, condition); + return; + } + if (compute && (n == "v_pk_add_i16" || n == "v_pk_sub_i16" || + n == "v_pk_add_u16" || n == "v_pk_sub_u16")) { + // Two-source VOP3P packed 16-bit add/sub accept op_sel[1:0], op_sel_hi[1:0] + // and clamp (ignoring LLVM's default op_sel_hi[2] bit 14) and refuse neg and reserved bits. + if (i.enc != Encoding::Mix || (i.a & 0x2700) || (i.b >> 29) || i.src[2]) + refuse(i.pc, "unsupported packed 16-bit add/sub operand modifiers"); + const bool sign = n == "v_pk_add_i16" || n == "v_pk_sub_i16"; + const bool sub = n == "v_pk_sub_i16" || n == "v_pk_sub_u16"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + auto half = [&](const string &word, bool hi, bool sext) { + if (sext) + return hi ? ir.binary("ashr", word, "16") + : ir.binary("ashr", ir.binary("shl", word, "16"), "16"); + return hi ? ir.binary("lshr", word, "16") : ir.binary("and", word, "65535"); + }; + auto lane = [&](bool hi_out) { + const bool sel_a = hi_out ? ((i.b >> 27) & 1) != 0 : ((i.a >> 11) & 1) != 0; + const bool sel_b = hi_out ? ((i.b >> 28) & 1) != 0 : ((i.a >> 12) & 1) != 0; + auto x = half(a, sel_a, i.clamp && sign); + auto y = half(b, sel_b, i.clamp && sign); + auto res = ir.binary(sub ? "sub" : "add", x, y); + if (i.clamp) { + if (sign) { + auto low = select(cmp("slt", res, "-32768"), "32768", ir.binary("and", res, "65535")); + return select(cmp("sgt", res, "32767"), "32767", low); + } else if (sub) { + res = select(cmp("ugt", x, y), res, "0"); + } else { + res = select(cmp("ugt", res, "65535"), "65535", res); + } + } + return ir.binary("and", res, "65535"); + }; + auto lo = lane(false), hi = lane(true); + vector_write(i.dst, ir.binary("or", lo, ir.binary("shl", hi, "16"))); + return; + } + if (compute && (n == "v_dot2_i32_i16" || n == "v_dot2_u32_u16")) { + // These VOP3P dot forms consume both halfwords as-is. + if (i.enc != Encoding::Mix || (i.a & 0x7f00) != 0x4000 || (i.b >> 27) != 3) + refuse(i.pc, "unsupported packed halfword dot operand modifiers"); + const bool sign = n == "v_dot2_i32_i16"; + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]), acc = operand32(i, i.src[2]); + auto low_half = [&](const string &word) { + return sign ? ir.binary("ashr", ir.binary("shl", word, "16"), "16") + : ir.binary("and", word, "65535"); + }; + auto low_product = ir.binary("mul", low_half(a), low_half(b)); + auto high_half = sign ? "ashr" : "lshr"; + auto high_product = ir.binary("mul", ir.binary(high_half, a, "16"), ir.binary(high_half, b, "16")); + auto pair = ir.binary("add", low_product, high_product); + auto sum = ir.binary("add", pair, acc); + if (i.clamp) { + // Accumulate both carries and the three sign extensions in + // the upper word. Clamp only after the accumulator is added. + auto carry = [&](const string &result, const string &left) { + return ir.value("zext i1 " + cmp("ult", result, left) + " to i32"); + }; + auto upper = ir.binary("add", carry(pair, low_product), carry(sum, pair)); + if (sign) { + for (const auto &word : {low_product, high_product, acc}) + upper = ir.binary("add", upper, ir.binary("ashr", word, "31")); + auto fits = cmp("eq", upper, ir.binary("ashr", sum, "31")); + auto bound = select(cmp("slt", upper, "0"), "2147483648", "2147483647"); + sum = select(fits, sum, bound); + } else { + sum = select(cmp("eq", upper, "0"), sum, "4294967295"); + } + } + vector_write(i.dst, sum); + return; + } + if (compute && (n == "v_pk_lshlrev_b16" || n == "v_pk_lshrrev_b16" || n == "v_pk_ashrrev_i16")) { + // Two-source VOP3P packed 16-bit shifts accept op_sel[1:0] and op_sel_hi[1:0] + // (ignoring LLVM's default op_sel_hi[2] bit 14) and refuse clamp, neg and reserved bits. + if (i.enc != Encoding::Mix || i.clamp || (i.a & 0x2700) || (i.b >> 29) || i.src[2]) + refuse(i.pc, "unsupported packed 16-bit shift operand modifiers"); + auto a = operand32(i, i.src[0]), b = operand32(i, i.src[1]); + auto lane = [&](bool hi_out) { + const bool sel_a = hi_out ? ((i.b >> 27) & 1) != 0 : ((i.a >> 11) & 1) != 0; + const bool sel_b = hi_out ? ((i.b >> 28) & 1) != 0 : ((i.a >> 12) & 1) != 0; + auto amt = ir.binary("and", sel_a ? ir.binary("lshr", a, "16") : a, "15"); + if (n == "v_pk_ashrrev_i16") { + auto aligned = sel_b ? b : ir.binary("shl", b, "16"); + auto shift = ir.binary("add", amt, "16"); + return ir.binary("and", ir.binary("ashr", aligned, shift), "65535"); + } + auto val = sel_b ? ir.binary("lshr", b, "16") : ir.binary("and", b, "65535"); + if (n == "v_pk_lshrrev_b16") + return ir.binary("lshr", val, amt); + return ir.binary("and", ir.binary("shl", val, amt), "65535"); + }; + auto lo = lane(false), hi = lane(true); + vector_write(i.dst, ir.binary("or", lo, ir.binary("shl", hi, "16"))); + return; + } + const bool select_mods = n == "v_cndmask_b32" && i.wide && !((i.abs | i.neg) & 4); + if ((i.subword && i.enc != Encoding::Vop1 && i.enc != Encoding::Vop2) || ((i.abs || i.neg) && !select_mods) || i.clamp || i.scale) + refuse(i.pc, "direct ALU operand modifiers"); + auto val = [&](unsigned j) { + auto value = !j && permuted ? *permuted : operand32(i, i.src[j]); + if (select_mods && (i.abs & (1u << j))) value = ir.binary("and", value, "2147483647"); + if (select_mods && (i.neg & (1u << j))) value = ir.binary("xor", value, "2147483648"); + return i.subword && j < 2 ? subword(value, i.src_select[j], i.src_sext[j]) : value; + }; + if (n == "s_mov_b32" || n == "s_mov_b64") { + const bool exec_hi = i.dst == 127 && (wave64 || (compute && n == "s_mov_b32")); + if (i.dst > 106 && i.dst != 126 && !(compute && i.dst == 107) && !exec_hi && + !(compute && i.dst == 124 && n == "s_mov_b32")) + refuse(i.pc, "direct scalar move destination"); + if (i.src[0] <= 105 && !state[i.src[0]].numeric()) { + if (i.dst > 105) + refuse(i.pc, "descriptor used as mask"); + if (n == "s_mov_b64" && ((i.dst | i.src[0]) & 1)) + refuse(i.pc, "unaligned scalar pair"); + auto indexed = [](const Symbol &v) { + return v.type == Symbol::Type::indexed_descriptor || v.type == Symbol::Type::sampler_word; + }; + if (indexed(state[i.src[0]])) + write(i.dst, read(i.src[0])); + if (n == "s_mov_b64" && indexed(state.at(i.src[0] + 1))) + write(i.dst + 1, read(i.src[0] + 1)); + // Transfer tracks symbolic low words; preserve numeric high words of a pair independently. + if (n == "s_mov_b64" && state.at(i.src[0] + 1).numeric()) + write(i.dst + 1, operand32(i, i.src[0] + 1)); + return; + } + string a = val(0); + if (n == "s_mov_b64") { + unsigned src = i.src[0]; + if (src >= 240 && src != 255) + refuse(i.pc, "floating inline constant in 64-bit move"); + if ((i.dst & 1) || (src < 128 && (src & 1))) + refuse(i.pc, "unaligned scalar pair"); + auto hi = graphics_input && !wave64 && src == 106 ? "0" : pair_high(i, src); + write(i.dst + 1, hi); + } + write(i.dst, a); + return; + } + if (i.enc == Encoding::Sopk && (n.substr(0, 7) == "s_cmpk_" || n == "s_addk_i32" || n == "s_mulk_i32")) { + auto a = operand32(i, i.dst); + auto immediate = to_string(n.find("_u32") != n.npos ? Word(uint16_t(i.a)) : Word(int16_t(i.a))); + if (n.substr(0, 7) == "s_cmpk_") { + write(128, ir.value("zext i1 " + comparison(i, a, immediate) + " to i32")); + return; + } + auto result = ir.binary(n == "s_mulk_i32" ? "mul" : "add", a, immediate); + if (n == "s_addk_i32") { + auto overflow = ir.binary("and", ir.binary("xor", a, result), ir.binary("xor", immediate, result)); + write(128, ir.binary("lshr", overflow, "31")); + } + write(i.dst, result); + return; + } + if (n == "s_movk_i32") { + write(i.dst, to_string(Word(int16_t(i.a)))); + return; + } + if (compute && (n == "s_cmov_b32" || n == "s_cmov_b64" || n == "s_cmovk_i32")) { + // RDNA 2 ISA SOP1/SOPK (#3070): D = SCC ? S0 : D; SCC is unchanged. + const bool pair = n == "s_cmov_b64"; + if (pair ? ((i.dst & 1) || (i.dst > 104 && i.dst != 106)) + : (i.dst > 106 && !(!wave64 && i.dst == 107))) + refuse(i.pc, "invalid " + string(n) + " destination"); + const unsigned s0 = i.src[0]; + if (pair) { + if (!((s0 <= 104 && !(s0 & 1)) || (s0 >= 128 && s0 <= 208) || s0 == 255)) + refuse(i.pc, "invalid s_cmov_b64 source"); + } else if (n == "s_cmov_b32") { + if (s0 > 106 && !(!wave64 && s0 == 107) && !constant32(i, s0)) + refuse(i.pc, "invalid s_cmov_b32 source"); + } + auto cond = cmp("ne", read(128), "0"); + auto old_lo = operand32(i, i.dst); + if (pair) { + auto old_hi = operand32(i, i.dst + 1); + auto new_lo = operand32(i, s0); + auto new_hi = pair_high(i, s0); + write(i.dst, select(cond, new_lo, old_lo)); + write(i.dst + 1, select(cond, new_hi, old_hi)); + } else { + auto next = n == "s_cmovk_i32" ? to_string(Word(int16_t(i.a))) : operand32(i, s0); + write(i.dst, select(cond, next, old_lo)); + } + return; + } + if (compute && (n == "v_readlane_b32" || n == "v_writelane_b32")) { + if (i.enc != Encoding::Vop3 || i.dpp_control || (i.a & 0x7800u) || i.src[2]) + refuse(i.pc, "lane read/write encoding or operand modifiers"); + const bool reading = n == "v_readlane_b32"; + if ((reading && (i.src[0] < 256 || i.src[0] >= 512 || i.dst > 107)) || + (!reading && (i.src[0] >= 256 || i.dst < 256 || i.dst >= 512))) + refuse(i.pc, "lane read/write register operand"); + const unsigned width = wave64 ? 64 : 32; + const unsigned selector = i.src[1]; + const auto guest = guest_spill_lane(i, wave64); + const unsigned vector = reading ? i.src[0] : i.dst; + if (guest && reading) { + const auto slot = state.lane_spills.find({vector, *guest}); + if (slot != state.lane_spills.end()) { + if (!slot->second) + refuse(i.pc, "symbolic VGPR lane read has conflicting incoming values"); + if (i.dst > 105) + refuse(i.pc, "symbolic VGPR lane read needs an ordinary SGPR destination"); + return; // Transfer associated the destination SGPR with this identity. + } + } + if (!reading && i.src[0] <= 105 && identity_spill(state[i.src[0]])) { + if (!guest) + refuse(i.pc, "symbolic VGPR lane write needs a constant lane"); + return; + } + string selected; + if (selector <= 105 || (!wave64 && selector == 107)) { + if (state.has_spill(vector)) + refuse(i.pc, "symbolic VGPR lane read or write needs a constant lane"); + selected = ir.binary("and", val(1), to_string(width - 1)); + } else { + if (!guest) + refuse(i.pc, "lane read/write needs a constant or SGPR lane"); + selected = to_string(*guest); + } + if (reading) { + const auto physical = wave64 ? ir.binary("and", selected, "31") : selected; + auto value = ir.invoke("i32", "waveReadLaneAt.i32", 117, + {{"i32", read_storage(vector)}, {"i32", physical}}, "nounwind"); + if (wave64) { + const auto halves = exchange_halves(value); + value = select(cmp("uge", selected, "32"), halves[1], halves[0]); + } + write(i.dst, value); + } else { + const auto guest_lane = wave64 ? ir.binary("or", lane, select(upper_half, "32", "0")) : lane; + // The lane selector is the sole write predicate, independent of guest EXEC. + lane_write = true; + write(i.dst, select(cmp("eq", guest_lane, selected), val(0), read_storage(i.dst))); + lane_write = false; + } + return; + } + if (n == "v_readfirstlane_b32") { + if (compute && (i.dpp_control || (i.wide && (i.a & 0x7800u)))) + refuse(i.pc, "readfirstlane modifiers"); + // Guest EXEC selects the first lane, even if it is not physical lane zero. + auto low = read(126); + auto mask = wave64 ? select(upper_half, read(127), low) : low; + auto first = ir.invoke("i32", "unaryBits.i32", 32, {{"i32", mask}}, "nounwind readnone"); + first = select(cmp("eq", mask, "0"), "0", first); + auto value = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32", val(0)}, {"i32", first}}, "nounwind"); + if (wave64) { + auto candidates = exchange_halves(value); + value = select(cmp("ne", low, "0"), candidates[0], candidates[1]); + } + write(i.dst, value); + return; + } + if (n == "v_lshrrev_b64" || n == "v_lshlrev_b64" || n == "v_ashrrev_i64") { + // v_ashrrev_i64 (#2991) sign-extends a 32-bit literal, as gfx2hlsl.py's i64_words(signed=True) does. + const bool arithmetic = n == "v_ashrrev_i64"; + unsigned src = i.src[1]; + const bool sgpr_pair = src <= 104 && (src & 1) == 0; + const bool vgpr_pair = src >= 256 && src < 511; + const bool inline_int = src >= 128 && src <= 208; + if (i.dst >= 511 || !(sgpr_pair || vgpr_pair || inline_int || src == 255)) + refuse(i.pc, "direct 64-bit shift operand"); + string lo = "0", hi = "0"; + if (src != 128) { + lo = operand32(i, src); + if (sgpr_pair || vgpr_pair) + hi = operand32(i, src + 1); + else if (inline_int && src >= 193) + hi = "4294967295"; + else if (src == 255 && arithmetic) + hi = ir.binary("ashr", lo, "31"); + auto low = ir.value("zext i32 " + lo + " to i64"), high = ir.value("zext i32 " + hi + " to i64"); + auto bits = ir.value("shl i64 " + high + ", 32"); + bits = ir.value("or i64 " + bits + ", " + low); + auto amt = ir.value("zext i32 " + ir.binary("and", val(0), "63") + " to i64"); + bits = ir.value(string(arithmetic ? "ashr" : n == "v_lshrrev_b64" ? "lshr" : "shl") + " i64 " + bits + + ", " + amt); + lo = ir.value("trunc i64 " + bits + " to i32"); + hi = ir.value("trunc i64 " + ir.value("lshr i64 " + bits + ", 32") + " to i32"); + ir.features |= 1048576; + } + vector_write(i.dst, lo); + vector_write(i.dst + 1, hi); + return; + } + if (n == "s_bfe_u32" && i.src[0] <= 105) { + const auto &descriptor = state[i.src[0]]; + const auto field = source(i, i.src[1], state); + if (descriptor.type == Symbol::Type::indexed_descriptor && descriptor.value == compute_resource_heap && + descriptor.offset % 32 == 4 && field.type == Symbol::Type::constant && field.value == 0xe0010) { + // Reachable only through a heap descriptor load, which needs the raw_buffer contract. A raw buffer view + // has no stride to read, so the stride of a GPU-selected slot stays untranslated in the direct path. + // With the raw_buffer contract a stride read into s0-s105 is tracked symbolically + // (byte_descriptor_field) and does not reach here. + refuse_heap_contract(i.pc); + refuse(i.pc, "a GPU-selected heap slot stride read is not translated with a view contract"); + } + } + if (compute && (n == "s_cmp_eq_u64" || n == "s_cmp_lg_u64" || n == "s_bitcmp0_b64" || n == "s_bitcmp1_b64")) { + // Issue #3078: lower 64-bit SOPC scalar comparisons to pure 32-bit DXIL writes of SCC. + auto scalar64 = [&](unsigned src) -> std::pair<string, string> { + if (src == 125) + return {"0", "0"}; + if (src == 106 || src == 126) + refuse(i.pc, "invalid " + string(n) + " source"); + return {operand32(i, src), pair_high(i, src)}; + }; + auto [a_lo, a_hi] = scalar64(i.src[0]); + string cond; + if (n == "s_cmp_eq_u64" || n == "s_cmp_lg_u64") { + auto [b_lo, b_hi] = scalar64(i.src[1]); + const bool eq = n == "s_cmp_eq_u64"; + const auto op = eq ? "eq" : "ne"; + const auto combine = eq ? "and" : "or"; + cond = ir.value(string(combine) + " i1 " + cmp(op, a_lo, b_lo) + ", " + cmp(op, a_hi, b_hi)); + } else { + const unsigned index_src = i.src[1]; + if (!(index_src <= 105 || (index_src >= 128 && index_src <= 208) || index_src == 255)) + refuse(i.pc, "invalid " + string(n) + " bit index"); + auto idx = operand32(i, index_src); + auto upper = cmp("ne", ir.binary("and", idx, "32"), "0"); + auto word = select(upper, a_hi, a_lo); + auto bit = ir.binary("and", shift("lshr", word, idx), "1"); + cond = cmp(n == "s_bitcmp0_b64" ? "eq" : "ne", bit, "0"); + } + write(128, ir.value("zext i1 " + cond + " to i32")); + return; + } + if (compute && n == "s_bfm_b64") { + if ((i.dst & 1) || (i.dst > 104 && i.dst != 126)) + refuse(i.pc, "invalid s_bfm_b64 destination"); + if ((i.src[0] > 105 && !constant32(i, i.src[0])) || + (i.src[1] > 105 && !constant32(i, i.src[1]))) + refuse(i.pc, "invalid s_bfm_b64 source"); + auto width = ir.binary("and", val(0), "63"); + auto offset = ir.binary("and", val(1), "63"); + auto wide_width = ir.value("zext i32 " + width + " to i64"); + auto wide_offset = ir.value("zext i32 " + offset + " to i64"); + // Width and offset are six-bit fields, so both shifts stay below 64 and a raw + // width of 64 is an empty mask. + auto mask = ir.value("sub i64 " + ir.value("shl i64 1, " + wide_width) + ", 1"); + auto bits = ir.value("shl i64 " + mask + ", " + wide_offset); + write(i.dst, ir.value("trunc i64 " + bits + " to i32")); + write(i.dst + 1, ir.value("trunc i64 " + ir.value("lshr i64 " + bits + ", 32") + " to i32")); + ir.features |= 1048576; + return; + } + if (compute && (n == "s_cselect_b64" || n == "s_not_b64")) { + const bool invert = n == "s_not_b64"; + if ((i.dst & 1) || (i.dst > 104 && i.dst != 106 && !(invert && i.dst == 126))) + refuse(i.pc, "invalid " + string(n) + " destination"); + auto scalar64 = [&](unsigned src) -> std::pair<string, string> { + if (!((src <= 104 && !(src & 1)) || src == 106 || src == 126 || + (src >= 128 && src <= 208) || src == 255)) + refuse(i.pc, "invalid " + string(n) + " source"); + return {operand32(i, src), pair_high(i, src)}; + }; + auto [lo, hi] = scalar64(i.src[0]); + if (!invert) { + auto [other_lo, other_hi] = scalar64(i.src[1]); + auto condition = cmp("ne", read(128), "0"); + lo = select(condition, lo, other_lo); + hi = select(condition, hi, other_hi); + } else { + lo = ir.binary("xor", lo, "4294967295"); + hi = ir.binary("xor", hi, "4294967295"); + } + write(i.dst, lo); + write(i.dst + 1, hi); + if (invert) + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); + return; + } + if (compute && (n == "s_lshl_b64" || n == "s_lshr_b64" || n == "s_ashr_i64")) { + // gfx2hlsl.py scalar_wide_op (#3062): D = f(S0, S1 & 63); SCC = (D != 0). Read all sources before + // writing the destination pair so an overlapping destination cannot observe a half-written input. + if ((i.dst & 1) || (i.dst > 104 && i.dst != 106)) + refuse(i.pc, "invalid " + string(n) + " destination"); + const unsigned s0 = i.src[0], s1 = i.src[1]; + const bool s0_pair = s0 <= 104 && !(s0 & 1); + const bool s0_int = s0 >= 128 && s0 <= 208; + const bool s1_ok = s1 <= 105 || (s1 >= 128 && s1 <= 208) || s1 == 255; + if (!(s0_pair || s0_int || s0 == 255) || !s1_ok) + refuse(i.pc, "invalid " + string(n) + " source"); + const bool arithmetic = n == "s_ashr_i64"; + auto lo = operand32(i, s0); + string hi = "0"; + if (s0_pair) + hi = operand32(i, s0 + 1); + else if (s0 >= 193 && s0 <= 208) + hi = "4294967295"; + else if (s0 == 255 && arithmetic && (i.literal & 0x80000000u)) + hi = "4294967295"; + auto amt = ir.value("zext i32 " + ir.binary("and", operand32(i, s1), "63") + " to i64"); + auto wide = ir.value("or i64 " + ir.value("shl i64 " + ir.value("zext i32 " + hi + " to i64") + ", 32") + + ", " + ir.value("zext i32 " + lo + " to i64")); + auto shifted = ir.value(string(arithmetic ? "ashr" : n == "s_lshr_b64" ? "lshr" : "shl") + + " i64 " + wide + ", " + amt); + auto out_lo = ir.value("trunc i64 " + shifted + " to i32"); + auto out_hi = ir.value("trunc i64 " + ir.value("lshr i64 " + shifted + ", 32") + " to i32"); + ir.features |= 1048576; + write(i.dst, out_lo); + write(i.dst + 1, out_hi); + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", out_lo, out_hi), "0") + " to i32")); + return; + } + if (compute && (n == "s_quadmask_b32" || n == "s_quadmask_b64")) { + auto quadmask32 = [&](const string &x) { + auto t = ir.binary("or", x, ir.binary("lshr", x, "2")); + t = ir.binary("and", ir.binary("or", t, ir.binary("lshr", t, "1")), "286331153"); + t = ir.binary("and", ir.binary("or", t, ir.binary("lshr", t, "3")), "50529027"); + t = ir.binary("and", ir.binary("or", t, ir.binary("lshr", t, "6")), "983055"); + return ir.binary("and", ir.binary("or", t, ir.binary("lshr", t, "12")), "255"); + }; + if (n == "s_quadmask_b32") { + auto q = quadmask32(operand32(i, i.src[0])); + write(i.dst, q); + write(128, ir.value("zext i1 " + cmp("ne", q, "0") + " to i32")); + return; + } + if ((i.dst & 1) || i.dst > 104) + refuse(i.pc, "invalid s_quadmask_b64 destination"); + const unsigned s0 = i.src[0]; + const bool s0_pair = s0 <= 104 && !(s0 & 1); + const bool s0_int = s0 >= 128 && s0 <= 208; + if (!(s0_pair || s0 == 125 || s0_int || s0 == 255)) + refuse(i.pc, "invalid s_quadmask_b64 source"); + auto lo = s0 == 125 ? "0" : operand32(i, s0); + string hi = "0"; + if (s0_pair) + hi = operand32(i, s0 + 1); + else if (s0 >= 193 && s0 <= 208) + hi = "4294967295"; + auto out_lo = ir.binary("or", quadmask32(lo), ir.binary("shl", quadmask32(hi), "8")); + write(i.dst, out_lo); + write(i.dst + 1, "0"); + write(128, ir.value("zext i1 " + cmp("ne", out_lo, "0") + " to i32")); + return; + } + if (compute && (n == "s_brev_b64" || n == "s_bfe_u64" || n == "s_bfe_i64")) { + if ((i.dst & 1) || i.dst > 104) + refuse(i.pc, "invalid " + string(n) + " destination"); + const unsigned s0 = i.src[0]; + const bool s0_pair = s0 <= 104 && !(s0 & 1); + const bool s0_int = s0 >= 128 && s0 <= 208; + const bool sign = n == "s_bfe_i64"; + if (!(s0_pair || s0 == 125 || s0_int || s0 == 255)) + refuse(i.pc, "invalid " + string(n) + " source"); + if (n != "s_brev_b64") { + const unsigned s1 = i.src[1]; + if (!(s1 <= 105 || s1 == 125 || (s1 >= 128 && s1 <= 208) || s1 == 255)) + refuse(i.pc, "invalid " + string(n) + " source"); + } + // Read all inputs before writing the destination pair so overlapping registers stay intact (#3086). + auto lo = s0 == 125 ? "0" : operand32(i, s0); + string hi = "0"; + if (s0_pair) + hi = operand32(i, s0 + 1); + else if (s0 >= 193 && s0 <= 208) + hi = "4294967295"; + else if (s0 == 255 && sign && (i.literal & 0x80000000u)) + hi = "4294967295"; + if (n == "s_brev_b64") { + auto rev_lo = ir.invoke("i32", "unary.i32", 30, {{"i32", hi}}, "nounwind readnone"); + auto rev_hi = ir.invoke("i32", "unary.i32", 30, {{"i32", lo}}, "nounwind readnone"); + write(i.dst, rev_lo); + write(i.dst + 1, rev_hi); + return; + } + auto ctrl = i.src[1] == 125 ? "0" : operand32(i, i.src[1]); + auto offset = ir.binary("and", ctrl, "63"); + auto width = ir.binary("and", ir.binary("lshr", ctrl, "16"), "127"); + auto wide = ir.value("or i64 " + ir.value("shl i64 " + ir.value("zext i32 " + hi + " to i64") + ", 32") + + ", " + ir.value("zext i32 " + lo + " to i64")); + auto off64 = ir.value("zext i32 " + offset + " to i64"); + auto shifted = ir.value(string(sign ? "ashr" : "lshr") + " i64 " + wide + ", " + off64); + auto pad = ir.value("zext i32 " + ir.binary("and", ir.binary("sub", "64", width), "63") + " to i64"); + auto narrow = ir.value(string(sign ? "ashr" : "lshr") + " i64 " + ir.value("shl i64 " + shifted + ", " + pad) + + ", " + pad); + auto non_zero = ir.value("select i1 " + cmp("uge", width, "64") + ", i64 " + shifted + ", i64 " + narrow); + auto result = ir.value("select i1 " + cmp("eq", width, "0") + ", i64 0, i64 " + non_zero); + auto out_lo = ir.value("trunc i64 " + result + " to i32"); + auto out_hi = ir.value("trunc i64 " + ir.value("lshr i64 " + result + ", 32") + " to i32"); + ir.features |= 1048576; + write(i.dst, out_lo); + write(i.dst + 1, out_hi); + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", out_lo, out_hi), "0") + " to i32")); + return; + } + if (compute && (n == "s_bcnt0_i32_b64" || n == "s_bcnt1_i32_b64" || + n == "s_ff0_i32_b64" || n == "s_ff1_i32_b64" || + n == "s_flbit_i32_b64" || n == "s_flbit_i32_i64")) { + // RDNA 2 ISA SOP1 / gfx2hlsl.py SCALAR_BITS (#3072): 64-bit source, 32-bit i32 destination. + // Uses only 32-bit DXIL unaryBits.i32 (31=Countbits, 32=FirstbitLo, 33=FirstbitHi). + // Only the counts write SCC (D != 0); all four scans preserve SCC and return ~0 when no bit qualifies. + if (i.dst > 105) + refuse(i.pc, "invalid " + string(n) + " destination"); + const unsigned s0 = i.src[0]; + const bool s0_pair = (s0 <= 104 && !(s0 & 1)) || s0 == 126; + const bool s0_int = s0 >= 128 && s0 <= 208; + if (!(s0_pair || s0_int || s0 == 255)) + refuse(i.pc, "invalid " + string(n) + " source"); + const bool signed_flbit = n == "s_flbit_i32_i64"; + auto lo = operand32(i, s0); + string hi = "0"; + if (s0_pair) + hi = operand32(i, s0 + 1); + else if (s0 >= 193 && s0 <= 208) + hi = "4294967295"; + else if (s0 == 255 && signed_flbit && (i.literal & 0x80000000u)) + hi = "4294967295"; + if (n == "s_bcnt0_i32_b64" || n == "s_bcnt1_i32_b64") { + if (n == "s_bcnt0_i32_b64") { + lo = ir.binary("xor", lo, "4294967295"); + hi = ir.binary("xor", hi, "4294967295"); + } + auto clo = ir.invoke("i32", "unaryBits.i32", 31, {{"i32", lo}}, "nounwind readnone"); + auto chi = ir.invoke("i32", "unaryBits.i32", 31, {{"i32", hi}}, "nounwind readnone"); + auto count = ir.binary("add", clo, chi); + write(i.dst, count); + write(128, ir.value("zext i1 " + cmp("ne", count, "0") + " to i32")); + } else if (n == "s_ff0_i32_b64" || n == "s_ff1_i32_b64") { + if (n == "s_ff0_i32_b64") { + lo = ir.binary("xor", lo, "4294967295"); + hi = ir.binary("xor", hi, "4294967295"); + } + auto ilo = ir.invoke("i32", "unaryBits.i32", 32, {{"i32", lo}}, "nounwind readnone"); + auto ihi = ir.invoke("i32", "unaryBits.i32", 32, {{"i32", hi}}, "nounwind readnone"); + auto hi_pos = select(cmp("ne", hi, "0"), ir.binary("add", ihi, "32"), "4294967295"); + write(i.dst, select(cmp("ne", lo, "0"), ilo, hi_pos)); + } else { + if (signed_flbit) { + auto neg = cmp("slt", hi, "0"); + lo = select(neg, ir.binary("xor", lo, "4294967295"), lo); + hi = select(neg, ir.binary("xor", hi, "4294967295"), hi); + } + auto lzhi = ir.invoke("i32", "unaryBits.i32", 33, {{"i32", hi}}, "nounwind readnone"); + auto lzlo = ir.invoke("i32", "unaryBits.i32", 33, {{"i32", lo}}, "nounwind readnone"); + auto lo_pos = select(cmp("ne", lo, "0"), ir.binary("add", lzlo, "32"), "4294967295"); + write(i.dst, select(cmp("ne", hi, "0"), lzhi, lo_pos)); + } + return; + } + auto a = val(0); + string b, z; + const bool scalar = n.substr(0, 2) == "s_"; + if (i.enc != Encoding::Vop1 && i.enc != Encoding::Sop1) + b = val(1); + // As in Victory's SALU lowering and pixel_aot's SGPR-pair rules, + // bitset reads its previous destination and leaves SCC alone. + if (n == "s_bitset0_b32" || n == "s_bitset1_b32" || n == "s_bitset0_b64" || n == "s_bitset1_b64") { + const bool pair = n.substr(n.size() - 3) == "b64"; + if (i.dst > 105 || (pair && (i.dst & 1))) + refuse(i.pc, "bitset requires a general scalar destination or aligned pair"); + auto old = operand32(i, i.dst); + auto bit = shift("shl", "1", a); + auto replace = [&](const string &value) { + return n[8] == '1' ? ir.binary("or", value, bit) + : ir.binary("and", value, ir.binary("xor", bit, "4294967295")); + }; + if (pair) { + auto high = operand32(i, i.dst + 1); + auto upper = cmp("ne", ir.binary("and", a, "32"), "0"); + write(i.dst, select(upper, old, replace(old))); + write(i.dst + 1, select(upper, replace(high), high)); + } else + write(i.dst, replace(old)); + return; + } + if (n == "s_bitreplicate_b64_b32") { + if ((i.dst > 104 && (graphics_input || (i.dst != 106 && i.dst != 126))) || (i.dst & 1)) + refuse(i.pc, "bitreplicate requires an aligned general scalar pair or compute VCC/EXEC"); + // pixel_aot expands each 16-bit half into the even positions, + // then duplicates each of the original bits into its neighbour. + auto replicate = [&](string half) { + unsigned shift = 8; + for (Word mask : {0x00ff00ffu, 0x0f0f0f0fu, 0x33333333u, 0x55555555u}) { + half = ir.binary("and", ir.binary("or", half, ir.binary("shl", half, to_string(shift))), to_string(mask)); + shift >>= 1; + } + return ir.binary("or", half, ir.binary("shl", half, "1")); + }; + write(i.dst, replicate(ir.binary("and", a, "65535"))); + write(i.dst + 1, replicate(ir.binary("lshr", a, "16"))); + return; + } + if (n == "s_pack_ll_b32_b16" || n == "s_pack_lh_b32_b16" || n == "s_pack_hh_b32_b16") { + const auto lo = n == "s_pack_hh_b32_b16" ? ir.binary("lshr", a, "16") : ir.binary("and", a, "65535"); + const auto hi = n == "s_pack_ll_b32_b16" ? ir.binary("shl", b, "16") : ir.binary("and", b, "4294901760"); + write(i.dst, ir.binary("or", lo, hi)); + return; + } + if (i.enc == Encoding::Sop2 && i.op >= 0x2e && i.op <= 0x31) { + unsigned amount = i.op - 0x2d; + auto shifted = ir.binary("shl", a, to_string(amount)); + auto sum = ir.binary("add", shifted, b); + auto shifted_out = cmp("ne", ir.binary("lshr", a, to_string(32 - amount)), "0"); + auto carry = ir.value("or i1 " + shifted_out + ", " + cmp("ult", sum, shifted)); + write(i.dst, sum); + write(128, ir.value("zext i1 " + carry + " to i32")); + return; + } + if (compute && n == "s_bcnt1_i32_b64") { + const auto count = [&](const string &word) { + return ir.invoke("i32", "unaryBits.i32", 31, {{"i32", word}}, "nounwind readnone"); + }; + auto total = ir.binary("add", count(a), count(pair_high(i, i.src[0]))); + write(i.dst, total); + write(128, ir.value("zext i1 " + cmp("ne", total, "0") + " to i32")); + return; + } + auto combine_scalar_mask = [&](Name op, const string &left, const string &right) -> string { + if (op == "and" || op == "or" || op == "xor") + return ir.binary(string(op), left, right); + if (op == "andn2" || op == "orn2") + return ir.binary(op == "andn2" ? "and" : "or", left, ir.binary("xor", right, "4294967295")); + if (op == "andn1" || op == "orn1") + return ir.binary(op == "andn1" ? "and" : "or", ir.binary("xor", left, "4294967295"), right); + if (op == "nand" || op == "nor" || op == "xnor") + return ir.binary("xor", ir.binary(op == "nand" ? "and" : op == "nor" ? "or" : "xor", left, right), + "4294967295"); + return {}; + }; + if ((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2) && n.size() > 6 && n.substr(n.size() - 4) == "_b64") { + bool save = n.find("_saveexec_") != Name::npos; + const bool wrexec = compute && + (((wave64 || narrow_wave64) && n == "s_andn2_wrexec_b64") || + (wave64 && n == "s_andn1_wrexec_b64")); + auto op = n.substr(2, n.find('_', 2) - 2); + if (wrexec ? ((i.dst | i.src[0]) & 1) || i.dst > 104 || i.src[0] > 104 + : (i.dst & 1) || (i.dst > 104 && i.dst != 106 && i.dst != 126) || + (save ? i.enc != Encoding::Sop1 : i.enc != Encoding::Sop2)) + refuse(i.pc, "unsupported wave64 scalar operation"); + auto ah = pair_high(i, i.src[0]); + const bool updates_exec = save || wrexec; + auto bl = updates_exec ? read(126) : b; + // The narrow model starts EXEC_HI at zero. Scalar code can + // explicitly write it, and later scalar instructions can read it. + auto bh = updates_exec ? read(127) : pair_high(i, i.src[1]); + // SAVEEXEC and WREXEC combine the source with old EXEC in ISA operand order. + // WREXEC stores the new mask in the destination pair. + auto lo = combine_scalar_mask(op, a, bl), hi = combine_scalar_mask(op, ah, bh); + if (lo.empty()) + refuse(i.pc, "unsupported wave64 scalar mask operation"); + write(i.dst, save ? bl : lo); + write(i.dst + 1, save ? bh : hi); + if (updates_exec) { write(126, lo); write(127, hi); } + write(128, ir.value("zext i1 " + cmp("ne", ir.binary("or", lo, hi), "0") + " to i32")); + return; + } + const bool saveexec32 = i.enc == Encoding::Sop1 && n.size() > 13 && n.substr(n.size() - 13) == "_saveexec_b32"; + const bool wrexec32 = n == "s_andn2_wrexec_b32" || (compute && !wave64 && n == "s_andn1_wrexec_b32"); + if (n == "s_and_saveexec_b32" || n == "s_andn2_wrexec_b32" || + (compute && !wave64 && (saveexec32 || wrexec32))) { + const bool save = saveexec32; + const bool strict_dst = n != "s_and_saveexec_b32" && n != "s_andn2_wrexec_b32"; + if (strict_dst && i.dst > 107) + refuse(i.pc, "unsupported wave32 SAVEEXEC destination"); + auto op = n.substr(2, n.find('_', 2) - 2); + auto old = read(126); + // Like s_mov_b32 exec_lo, EXEC keeps every bit; a lane runs only if its own bit is set. + auto mask = combine_scalar_mask(op, a, old); + if (mask.empty()) + refuse(i.pc, "unsupported wave32 scalar mask operation"); + write(i.dst, save ? old : mask); + write(126, mask); + write(128, ir.value("zext i1 " + cmp("ne", mask, "0") + " to i32")); + return; + } + if (n == "s_add_i32" || n == "s_sub_i32") { + auto z = ir.binary(n == "s_add_i32" ? "add" : "sub", a, b); + auto left = ir.binary("xor", a, z); + auto right = ir.binary("xor", n == "s_add_i32" ? b : a, n == "s_add_i32" ? z : b); + write(128, ir.binary("lshr", ir.binary("and", left, right), "31")); + write(i.dst, z); + return; + } + if (n == "s_addc_u32" || n == "s_subb_u32") { + auto carry = read(128); + bool add = n == "s_addc_u32"; + auto partial = ir.binary(add ? "add" : "sub", a, b), + result = ir.binary(add ? "add" : "sub", partial, carry); + auto flag = add ? cmp("ult", partial, a) : cmp("ult", a, b); + auto carry2 = add ? cmp("ult", result, partial) : cmp("ult", partial, carry); + write(i.dst, result); + write(128, ir.value("zext i1 " + ir.value("or i1 " + flag + ", " + carry2) + " to i32")); + return; + } + if (n == "s_ff1_i32_b32") { + write(i.dst, ir.invoke("i32", "unaryBits.i32", 32, {{"i32", a}}, "nounwind readnone")); + return; + } + if (n == "s_brev_b32" || n == "v_bfrev_b32" || n == "v_bcnt_u32_b32") { + bool count = n == "v_bcnt_u32_b32"; + auto value = ir.invoke("i32", count ? "unaryBits.i32" : "unary.i32", count ? 31 : 30, {{"i32", a}}, + "nounwind readnone"); + if (scalar) + write(i.dst, value); + else + vector_write(i.dst, place_subword(i, count ? ir.binary("add", value, b) : value)); + return; + } + if (n == "s_bcnt0_i32_b32" || n == "s_bcnt1_i32_b32") { + auto bits = n == "s_bcnt0_i32_b32" ? ir.binary("xor", a, "4294967295") : a; + auto count = ir.invoke("i32", "unaryBits.i32", 31, {{"i32", bits}}, "nounwind readnone"); + write(i.dst, count); + write(128, ir.value("zext i1 " + cmp("ne", count, "0") + " to i32")); + return; + } + if (n == "s_ff0_i32_b32" || n == "s_ff1_i32_b32" || n == "v_ffbl_b32" || n == "s_flbit_i32_b32" || + n == "v_ffbh_u32" || n == "s_flbit_i32" || n == "v_ffbh_i32") { + // DXIL FirstbitLo (32) counts from bit 0; FirstbitHi (33) and FirstbitSHi (34) count from bit 31, + // as these gfx10 scans do. All three return ~0 when no bit qualifies, and none of the scans writes SCC. + bool low = n == "s_ff0_i32_b32" || n == "s_ff1_i32_b32" || n == "v_ffbl_b32"; + bool sign = n == "s_flbit_i32" || n == "v_ffbh_i32"; + auto bits = n == "s_ff0_i32_b32" ? ir.binary("xor", a, "4294967295") : a; + auto index = ir.invoke("i32", "unaryBits.i32", low ? 32 : sign ? 34 : 33, {{"i32", bits}}, + "nounwind readnone"); + if (scalar) + write(i.dst, index); + else + vector_write(i.dst, place_subword(i, index)); + return; + } + if (n == "v_swap_b32") { + if (i.wide || i.src[0] < 256) + refuse(i.pc, "invalid vector swap source"); + auto old = read(i.dst); + vector_write(i.dst, a); + vector_write(i.src[0], old); + return; + } + if (n == "s_cselect_b32") { + write(i.dst, select(cmp("ne", read(128), "0"), a, b)); + return; + } + if (n == "s_bitcmp1_b32" || n == "s_bitcmp0_b32") { + auto bit = ir.binary("and", shift("lshr", a, b), "1"); + write(128, n == "s_bitcmp0_b32" ? ir.binary("xor", bit, "1") : bit); + return; + } + if (n == "s_min_u32" || n == "s_max_u32" || n == "s_min_i32" || n == "s_max_i32" || + n == "v_min_u32" || n == "v_max_u32" || n == "v_min_i32" || n == "v_max_i32") { + const string sign = n.substr(n.size() - 3) == "i32" ? "s" : "u"; + auto pred = cmp(sign + (n.substr(2, 3) == "min" ? "lt" : "gt"), a, b); + auto result = select(pred, a, b); + if (scalar) { + write(i.dst, result); + write(128, ir.value("zext i1 " + pred + " to i32")); + } else { + vector_write(i.dst, place_subword(i, result)); + } + return; + } + if (n == "v_cndmask_b32") { + // In direct compute s107 holds numeric data; translate_program refuses a guest wave64 here. + if (!wave64 && i.src[2] == 107 && graphics_input) + refuse(i.pc, "unsupported wave32 conditional mask source"); + z = select(cmp("ne", ir.binary("and", wave64 ? select(upper_half, pair_high(i, i.src[2]), val(2)) : val(2), lane_bit), "0"), b, a); + } else if (n == "v_mov_b32") + z = a; + else if (n == "s_absdiff_i32") { + // D = S0 - S1 wrapped to 32 bits, negated when negative, so 0x80000000 stays; SCC = D != 0 below. + auto difference = ir.binary("sub", a, b); + z = select(cmp("slt", difference, "0"), ir.binary("sub", "0", difference), difference); + } else if (n == "s_mul_i32" || n == "v_mul_lo_u32" || n == "v_mul_lo_i32") + z = ir.binary("mul", a, b); + else if (n == "v_mul_hi_u32" || n == "v_mul_hi_i32" || n == "s_mul_hi_u32" || n == "s_mul_hi_i32") { + // Accumulate 16-bit partial products without requiring Int64ShaderOps. + auto lo = [&](const string &v) { return ir.binary("and", v, "65535"); }; + auto hi = [&](const string &v) { return ir.binary("lshr", v, "16"); }; + auto al = lo(a), ah = hi(a), bl = lo(b), bh = hi(b); + auto middle = ir.binary("add", ir.binary("mul", ah, bl), hi(ir.binary("mul", al, bl))); + auto carry = hi(ir.binary("add", lo(middle), ir.binary("mul", al, bh))); + z = ir.binary("add", ir.binary("add", ir.binary("mul", ah, bh), hi(middle)), carry); + if (n == "v_mul_hi_i32" || n == "s_mul_hi_i32") { + z = ir.binary("sub", z, select(cmp("slt", a, "0"), b, "0")); + z = ir.binary("sub", z, select(cmp("slt", b, "0"), a, "0")); + } + } else if (n == "s_abs_i32") + z = select(cmp("slt", a, "0"), ir.binary("sub", "0", a), a); + else if (n == "s_sext_i32_i8" || n == "s_sext_i32_i16") { + const char *bits = n == "s_sext_i32_i8" ? "24" : "16"; + write(i.dst, ir.binary("ashr", ir.binary("shl", a, bits), bits)); + return; + } else if (n == "v_add_nc_u32" || n == "s_add_u32") + z = ir.binary("add", a, b); + else if (n == "s_lshl1_add_u32" || n == "s_lshl2_add_u32" || + n == "s_lshl3_add_u32" || n == "s_lshl4_add_u32") { + const unsigned k = static_cast<unsigned>(n[6] - '0'); + auto shifted = ir.binary("shl", a, to_string(k)); + z = ir.binary("add", shifted, b); + auto shift_overflow = cmp("ne", ir.binary("lshr", a, to_string(32 - k)), "0"); + auto add_carry = cmp("ult", z, shifted); + auto flag = ir.value("or i1 " + shift_overflow + ", " + add_carry); + write(i.dst, z); + write(128, ir.value("zext i1 " + flag + " to i32")); + return; + } + else if (n == "s_sub_u32" || n == "v_sub_nc_u32") + z = ir.binary("sub", a, b); + else if (n == "v_subrev_nc_u32") + z = ir.binary("sub", b, a); + else if (n == "v_not_b32") + z = ir.binary("xor", a, "4294967295"); + else if (n == "s_and_b32" || n == "v_and_b32") + z = ir.binary("and", a, b); + else if (n == "s_or_b32" || n == "v_or_b32") + z = ir.binary("or", a, b); + else if (n == "v_xor_b32" || n == "s_xor_b32") + z = ir.binary("xor", a, b); + else if (n == "v_xnor_b32") + z = ir.binary("xor", ir.binary("xor", a, b), "4294967295"); + else if (n == "v_and_or_b32") + z = ir.binary("or", ir.binary("and", a, b), val(2)); + else if (n == "v_xad_u32") + z = ir.binary("add", ir.binary("xor", a, b), val(2)); + else if (n == "v_or3_b32" || n == "v_xor3_b32" || n == "v_add3_u32") { + const char *op = n == "v_or3_b32" ? "or" : n == "v_xor3_b32" ? "xor" : "add"; + z = ir.binary(op, ir.binary(op, a, b), val(2)); + } else if (n == "v_add_lshl_u32") + z = shift("shl", ir.binary("add", a, b), val(2)); + else if (n == "v_mul_i32_i24" || n == "v_mad_i32_i24") { + if (n == "v_mul_i32_i24" && i.wide && i.src[2] != 0) + refuse(i.pc, "v_mul_i32_i24 with unused src2 field set"); + if (n == "v_mul_i32_i24" && i.wide && (i.a & 0x7800)) + refuse(i.pc, "v_mul_i32_i24 with op_sel"); + // sext(S0[23:0]) * sext(S1[23:0]) (+ S2) modulo 2^32. + auto sext24 = [&](const string &x) { return ir.binary("ashr", ir.binary("shl", x, "8"), "8"); }; + z = ir.binary("mul", sext24(a), sext24(b)); + if (n == "v_mad_i32_i24") + z = ir.binary("add", z, val(2)); + } else if (n == "v_mul_hi_i32_i24" || n == "v_mul_hi_u32_u24") { + if (i.wide && i.src[2] != 0) + refuse(i.pc, string(n) + " with unused src2 field set"); + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, string(n) + " with op_sel"); + const bool sign = n == "v_mul_hi_i32_i24"; + // Split each 24-bit operand as top * 2^12 + low (low in 0..4095, top signed or unsigned 12-bit). + // All intermediates stay inside 32 bits; floor division nests exactly for both signs. + auto top = [&](const string &x) { + return sign ? ir.binary("ashr", ir.binary("shl", x, "8"), "20") + : ir.binary("and", ir.binary("lshr", x, "12"), "4095"); + }; + auto low = [&](const string &x) { return ir.binary("and", x, "4095"); }; + auto ah = top(a), al = low(a), bh = top(b), bl = low(b); + auto hh = ir.binary("mul", ah, bh); + auto mid = ir.binary("add", ir.binary("mul", ah, bl), ir.binary("mul", al, bh)); + auto t = ir.binary("add", mid, ir.binary("lshr", ir.binary("mul", al, bl), "12")); + const char *rshift = sign ? "ashr" : "lshr"; + z = ir.binary(rshift, ir.binary("add", hh, ir.binary(rshift, t, "12")), "8"); + } else if (n == "v_mul_u32_u24" || n == "v_mad_u32_u24") { + z = ir.binary("mul", ir.binary("and", a, "16777215"), ir.binary("and", b, "16777215")); + if (n == "v_mad_u32_u24") + z = ir.binary("add", z, val(2)); + } else if ((n.substr(2, 3) == "min" || n.substr(2, 3) == "max" || n.substr(2, 4) == "med3") && + (n.substr(n.size() - 4) == "_u32" || n.substr(n.size() - 4) == "_i32") && !scalar) { + const bool signed_order = n.substr(n.size() - 4) == "_i32"; + auto bound = [&](const string &x, const string &y, bool minimum) { + return select(cmp(signed_order ? (minimum ? "slt" : "sgt") : (minimum ? "ult" : "ugt"), x, y), x, y); + }; + bool minimum = n.substr(2, 3) == "min"; + if (n.substr(2, 4) == "med3") { + auto c = val(2); + z = bound(bound(a, b, true), bound(bound(a, b, false), c, true), false); + } else { + z = bound(a, b, minimum); + if (n[5] == '3') + z = bound(z, val(2), minimum); + } + } else if (!scalar && (n == "v_mad_u16" || n == "v_mad_i16" || + n == "v_min3_u16" || n == "v_min3_i16" || + n == "v_max3_u16" || n == "v_max3_i16" || + n == "v_med3_u16" || n == "v_med3_i16")) { + // Three-operand 16-bit integer VOP3 operations (#669): each computes D[15:0] from + // S0[15:0], S1[15:0] and S2[15:0], and D[31:16] keeps its value (measured on RDNA 2 + // silicon; LLVM GCNSubtarget: "On gfx10, all 16-bit instructions preserve the high bits"). + // op_sel would select other halves and stays refused. Modifiers (clamp, scale, neg, abs) + // are refused by the path's common rule. + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " op_sel"); + auto low = [&](const string &x) { return ir.binary("and", x, "65535"); }; + auto sext = [&](const string &x) { return ir.binary("ashr", ir.binary("shl", x, "16"), "16"); }; + auto c = val(2); + string r; + if (n == "v_mad_u16" || n == "v_mad_i16") { + r = ir.binary("add", ir.binary("mul", low(a), low(b)), low(c)); + } else { + const bool signed_order = n.substr(n.size() - 4) == "_i16"; + auto bound = [&](const string &x, const string &y, bool minimum) { + return select(cmp(signed_order ? (minimum ? "slt" : "sgt") : (minimum ? "ult" : "ugt"), x, y), x, y); + }; + auto x = signed_order ? sext(a) : low(a); + auto y = signed_order ? sext(b) : low(b); + auto z_val = signed_order ? sext(c) : low(c); + if (n.substr(2, 4) == "med3") { + r = bound(bound(x, y, true), bound(bound(x, y, false), z_val, true), false); + } else { + bool minimum = n.substr(2, 3) == "min"; + r = bound(bound(x, y, minimum), z_val, minimum); + } + } + z = ir.binary("or", ir.binary("and", read(i.dst), "4294901760"), low(r)); + } else if (n == "v_sad_u8" || n == "v_sad_hi_u8" || n == "v_sad_u16" || n == "v_sad_u32" || n == "v_msad_u8") { + // Sums of unsigned absolute differences plus S2, modulo 2^32 (#2987), as gfx2hlsl.py's sad_u8, sad4_u8, + // sad_u16 and sad_u32 helpers and tools/pixel_aot.py compute them. v_msad_u8 skips each byte whose S1 + // byte is zero; v_sad_hi_u8 places the byte sum in the high half. + auto absdiff = [&](const string &x, const string &y) { + return select(cmp("ult", x, y), ir.binary("sub", y, x), ir.binary("sub", x, y)); + }; + auto field = [&](const string &x, unsigned at, unsigned mask) { + return ir.binary("and", at ? ir.binary("lshr", x, to_string(at)) : x, to_string(mask)); + }; + string sum; + if (n == "v_sad_u32") + sum = absdiff(a, b); + else { + const bool half = n == "v_sad_u16"; + for (unsigned at = 0; at < 32; at += half ? 16 : 8) { + const unsigned mask = half ? 65535 : 255; + auto x = field(a, at, mask), y = field(b, at, mask); + auto term = absdiff(x, y); + if (n == "v_msad_u8") + term = select(cmp("eq", y, "0"), "0", term); + sum = sum.empty() ? term : ir.binary("add", sum, term); + } + if (n == "v_sad_hi_u8") + sum = ir.binary("shl", sum, "16"); + } + z = ir.binary("add", sum, val(2)); + } else if (n == "v_alignbit_b32" || n == "v_alignbyte_b32") { + // Bits [k + 31 : k] of the 64-bit value {S0, S1}, with k = S2[4:0] or 8 * S2[1:0] (#2985, the + // gfx2hlsl.py VOP3 table). A zero k returns S1; the masked shift keeps the other arm in range. + auto k = n == "v_alignbit_b32" ? ir.binary("and", val(2), "31") + : ir.binary("shl", ir.binary("and", val(2), "3"), "3"); + auto joined = ir.binary("or", shift("lshr", b, k), shift("shl", a, ir.binary("sub", "32", k))); + z = select(cmp("eq", k, "0"), b, joined); + } else if (n == "v_perm_b32" || n == "v_lerp_u8") { + // Byte-wise (RDNA 2 ISA V_PERM_B32 and V_LERP_U8; gfx2hlsl.py #2875 and #2873). v_perm_b32: selector byte + // S2[8i+7:8i] picks byte 0..7 of {S0, S1} (S1 low), 8..11 the sign of bit 15 or 31 of S1 or S0 as 0x00 or + // 0xff, 12 gives 0x00 and 13..255 give 0xff. v_lerp_u8: (S0 + S1 + S2[8i]) >> 1 for each byte i. + auto byte = [&](const string &x, const string &at) { return ir.binary("and", ir.binary("lshr", x, at), "255"); }; + for (unsigned i = 0; i < 4; ++i) { + const string at = to_string(8 * i); + string v; + if (n == "v_lerp_u8") { + auto round = ir.binary("and", ir.binary("lshr", val(2), at), "1"); + v = ir.binary("lshr", ir.binary("add", ir.binary("add", byte(a, at), byte(b, at)), round), "1"); + } else { + auto sel = byte(val(2), at); + auto picked = byte(select(cmp("ult", sel, "4"), b, a), ir.binary("shl", ir.binary("and", sel, "3"), "3")); + auto sign = ir.binary("and", ir.binary("lshr", select(cmp("ult", sel, "10"), b, a), + ir.binary("or", ir.binary("shl", ir.binary("and", sel, "1"), "4"), "15")), "1"); + v = select(cmp("ult", sel, "8"), picked, + select(cmp("ult", sel, "12"), ir.binary("mul", sign, "255"), + select(cmp("eq", sel, "12"), "0", "255"))); + } + v = i ? ir.binary("shl", v, at) : v; + z = i ? ir.binary("or", z, v) : v; + } + } else if (n == "v_bfm_b32") + z = shift("shl", ir.binary("sub", shift("shl", "1", a), "1"), b); // like s_bfm_b32 (#2985) + else if (n == "v_bfi_b32") + z = ir.binary("or", ir.binary("and", a, b), ir.binary("and", ir.binary("xor", a, "4294967295"), val(2))); + else if (n == "s_bfe_u32" || n == "s_bfe_i32") { + const bool sign = n == "s_bfe_i32"; + auto offset = ir.binary("and", b, "31"); + auto width = ir.binary("and", ir.binary("lshr", b, "16"), "127"); + auto shifted = ir.binary(sign ? "ashr" : "lshr", a, offset); + auto pad = ir.binary("and", ir.binary("sub", "32", width), "31"); + auto narrow = ir.binary(sign ? "ashr" : "lshr", ir.binary("shl", shifted, pad), pad); + z = select(cmp("eq", width, "0"), "0", select(cmp("uge", width, "32"), shifted, narrow)); + } + else if (n == "v_cvt_pk_u16_u32" || n == "v_cvt_pk_i16_i32") { + // Saturate S0 and S1 to 16 bits and pack S0 low, S1 high (#2995, gfx2hlsl.py's VOP3 table). The + // instructions have two sources; like gfx2hlsl.py, refuse a nonzero unused SRC2 field. + if (i.src[2] != 0) + refuse(i.pc, string(n) + " with unused src2 field set"); + if (i.a & 0x7800) + refuse(i.pc, string(n) + " with op_sel"); + auto narrow = [&](const string &x) { + if (n == "v_cvt_pk_u16_u32") + return select(cmp("ugt", x, "65535"), "65535", x); + auto low = select(cmp("slt", x, "-32768"), "-32768", x); + return ir.binary("and", select(cmp("sgt", low, "32767"), "32767", low), "65535"); + }; + z = ir.binary("or", narrow(a), ir.binary("shl", narrow(b), "16")); + } + else if (n == "v_sat_pk_u8_i16") { + // RDNA 2 ISA VOP1 0x62 / VOP3A 0x1e2: clamp each signed 16-bit half of S0 to [0, 255], + // pack into D[7:0] and D[15:8], and zero D[31:16]. + if (i.wide && (i.src[1] != 0 || i.src[2] != 0)) + refuse(i.pc, "v_sat_pk_u8_i16 with unused src1/src2 field set"); + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "v_sat_pk_u8_i16 with op_sel"); + auto clamp_u8 = [&](const string &s16) { + auto nonneg = select(cmp("slt", s16, "0"), "0", s16); + return select(cmp("sgt", nonneg, "255"), "255", nonneg); + }; + auto lo = clamp_u8(ir.binary("ashr", ir.binary("shl", a, "16"), "16")); + auto hi = clamp_u8(ir.binary("ashr", a, "16")); + z = ir.binary("or", lo, ir.binary("shl", hi, "8")); + } + else if (n == "v_bfe_u32") + z = ir.binary("and", shift("lshr", a, b), ir.binary("sub", shift("shl", "1", val(2)), "1")); + else if (n == "v_bfe_i32") { + auto width = ir.binary("and", val(2), "31"); + auto pad = ir.binary("sub", "32", width); + auto field = shift("ashr", a, b); + z = select(cmp("eq", width, "0"), "0", shift("ashr", shift("shl", field, pad), pad)); + } else if (n == "v_cvt_pk_u8_f32") { + // Round and saturate the binary32 bits directly. Literal 0.5 through DXIL Round_ne + // and fptoui read back as 1 on some NVIDIA drivers (#3052). + constexpr auto half_bits = "1056964608"; // 0x3f000000 + constexpr auto max_byte_bits = "1132396544"; // 0x437f0000 (255.0) + auto positive = cmp("ult", ir.binary("sub", a, "1"), "2139095040"); // subnormal through +inf + auto bounded = select(cmp("ugt", a, max_byte_bits), max_byte_bits, a); + // Values at or below 0.5 yield zero, so clamp them and invalid inputs to + // exactly 0.5 to keep the significand shift in the range 16..24. + auto in_range = ir.value("and i1 " + positive + ", " + cmp("uge", bounded, half_bits)); + bounded = select(in_range, bounded, half_bits); + auto discard = ir.binary("sub", "150", ir.binary("lshr", bounded, "23")); // 23 + exponent bias + auto significand = ir.binary("or", ir.binary("and", bounded, "8388607"), "8388608"); + auto truncated = ir.binary("lshr", significand, discard); + auto halfway = ir.binary("shl", "1", ir.binary("sub", discard, "1")); + // Bias by halfway - 1, then add the low retained bit so only odd ties round up. + auto bias = ir.binary("add", ir.binary("sub", halfway, "1"), ir.binary("and", truncated, "1")); + auto byte = ir.binary("lshr", ir.binary("add", significand, bias), discard); + auto amount = ir.binary("shl", ir.binary("and", b, "3"), "3"); + auto keep = ir.binary("xor", ir.binary("shl", "255", amount), "4294967295"); + z = ir.binary("or", ir.binary("and", val(2), keep), ir.binary("shl", byte, amount)); + } else if (n == "s_orn2_b32") + z = ir.binary("or", a, ir.binary("xor", b, "4294967295")); + else if (n == "s_nand_b32" || n == "s_xnor_b32") + z = ir.binary("xor", ir.binary(n == "s_nand_b32" ? "and" : "xor", a, b), "4294967295"); + else if (n == "s_ashr_i32") + z = shift("ashr", a, b); + else if (n == "s_bfm_b32") + z = shift("shl", ir.binary("sub", shift("shl", "1", a), "1"), b); + else if (n == "s_not_b32") + z = ir.binary("xor", a, "4294967295"); + else if (n == "s_andn2_b32" || n == "s_nor_b32") + z = n == "s_andn2_b32" ? ir.binary("and", a, ir.binary("xor", b, "4294967295")) + : ir.binary("xor", ir.binary("or", a, b), "4294967295"); + else if (n == "s_lshl_b32" || n == "s_lshr_b32") + z = shift(n == "s_lshl_b32" ? "shl" : "lshr", a, b); + else if (n == "v_lshlrev_b32" || n == "v_lshrrev_b32" || n == "v_ashrrev_i32") + z = shift(n == "v_lshlrev_b32" ? "shl" : n == "v_lshrrev_b32" ? "lshr" : "ashr", b, a); + else if (n == "v_lshl_add_u32" || n == "v_lshl_or_b32") + z = ir.binary(n == "v_lshl_add_u32" ? "add" : "or", shift("shl", a, b), val(2)); + else if (n == "v_mbcnt_hi_u32_b32" || n == "v_mbcnt_lo_u32_b32") { + bool high = n == "v_mbcnt_hi_u32_b32"; + auto before = ir.binary("sub", lane_bit, "1"); + auto mask = wave64 ? select(upper_half, high ? before : "4294967295", high ? "0" : before) + : high ? "0" : before; + auto lower = ir.binary("and", a, mask); + z = ir.binary("add", b, ir.invoke("i32", "unaryBits.i32", 31, {{"i32", lower}}, "nounwind readnone")); + } else if (!scalar && (n == "v_add_nc_u16" || n == "v_sub_nc_u16" || n == "v_add_nc_i16" || n == "v_sub_nc_i16" || + n == "v_mul_lo_u16" || n == "v_lshlrev_b16" || n == "v_lshrrev_b16" || + n == "v_ashrrev_i16" || n == "v_min_u16" || n == "v_max_u16" || n == "v_min_i16" || + n == "v_max_i16")) { + // Non-packed 16-bit integer VOP3 (#669): the result is D[15:0], computed from S0[15:0] and S1[15:0], + // and D[31:16] keeps its value (measured on RDNA 2 silicon; LLVM: "On gfx10, all 16-bit instructions + // preserve the high bits"). op_sel would select other halves and stays refused. + if (i.wide && (i.a & 0x7800)) + refuse(i.pc, "unsupported " + string(n) + " op_sel"); + auto low = [&](const string &x) { return ir.binary("and", x, "65535"); }; + auto sext = [&](const string &x) { return ir.binary("ashr", ir.binary("shl", x, "16"), "16"); }; + const bool sign = n.substr(n.size() - 3) == "i16"; + string r; + if (n == "v_add_nc_u16" || n == "v_add_nc_i16") + r = ir.binary("add", a, b); + else if (n == "v_sub_nc_u16" || n == "v_sub_nc_i16") + r = ir.binary("sub", a, b); + else if (n == "v_mul_lo_u16") + r = ir.binary("mul", a, b); + else if (n == "v_lshlrev_b16" || n == "v_lshrrev_b16" || n == "v_ashrrev_i16") { + // D = S1 shifted by S0[3:0]. + auto amount = ir.binary("and", a, "15"); + r = n == "v_lshlrev_b16" ? ir.binary("shl", b, amount) + : n == "v_lshrrev_b16" ? ir.binary("lshr", low(b), amount) + : ir.binary("ashr", sext(b), amount); + } else { + auto x = sign ? sext(a) : low(a), y = sign ? sext(b) : low(b); + const bool minimum = n.substr(2, 3) == "min"; + r = select(cmp(sign ? (minimum ? "slt" : "sgt") : (minimum ? "ult" : "ugt"), x, y), x, y); + } + z = ir.binary("or", ir.binary("and", read(i.dst), "4294901760"), low(r)); + } else if (i.enc == Encoding::Sopc || i.enc == Encoding::Vopc || n.substr(0, 6) == "v_cmpx" || + n.substr(0, 6) == "v_cmp_") { + auto condition = comparison(i, a, b); + if (scalar) + write(128, ir.value("zext i1 " + condition + " to i32")); + else + write_ballot(i.dst, condition); + return; + } else + refuse(i.pc, "direct DXIL lowering for " + string(n)); + if (scalar) { + write(i.dst, z); + if (n != "s_mul_i32" && n != "s_mul_hi_u32" && n != "s_mul_hi_i32" && n != "s_bfm_b32") { + auto flag = n == "s_add_u32" ? cmp("ult", z, a) + : n == "s_sub_u32" ? cmp("ult", a, b) + : cmp("ne", z, "0"); + write(128, ir.value("zext i1 " + flag + " to i32")); + } + } else + vector_write(i.dst, place_subword(i, z)); + } + void lower_permlane(const Inst &i, unsigned threads) { + const bool cross_row = i.name == "v_permlanex16_b32"; + if (threads % (cross_row ? 32 : 16)) + refuse(i.pc, string(i.name) + " needs a thread count divisible by " + (cross_row ? "32" : "16")); + + // VOP3A retains op_sel in word 0 bits 11..14: bit 0 is FI and bit 1 is BOUND_CTRL. + const unsigned op_sel = (i.a >> 11) & 15; + if ((op_sel & ~3u) || i.neg || i.abs || i.clamp || i.scale) + refuse(i.pc, "unsupported permlane modifier or op_sel"); + const bool fi = op_sel & 1; + const bool bound_zero = op_sel & 2; + + // D and S0 are VGPRs. S1 and S2 are uniform SGPRs or constants. + if (i.src[0] < 256) + refuse(i.pc, "permlane S0 must be a VGPR"); + for (unsigned reg : {i.src[1], i.src[2]}) + if (reg > 105 && (wave64 || reg != 107) && !constant32(i, reg)) + refuse(i.pc, "permlane selectors must be uniform SGPRs or constants"); + + // S1 packs the nibbles for row lanes 0..7 and S2 packs those for 8..15. + auto row_lane = ir.binary("and", lane, "15"); + auto selectors = select(cmp("uge", row_lane, "8"), operand32(i, i.src[2]), operand32(i, i.src[1])); + auto shift = ir.binary("shl", ir.binary("and", row_lane, "7"), "2"); + auto pick = ir.binary("and", ir.binary("lshr", selectors, shift), "15"); + + // Permlane16 uses the current row; permlanex16 toggles row bit 4. + // Both rows of the pair are in the same physical wave32, even for guest wave64. + auto row_base = ir.binary("and", lane, "4294967280"); + if (cross_row) + row_base = ir.binary("xor", row_base, "16"); + auto source_lane = ir.binary("or", row_base, pick); + auto src = operand32(i, i.src[0]); + auto value = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32",src},{"i32",source_lane}}, "nounwind"); + + // Assume DPP's inactive-source rule: FI bypasses the guest EXEC test. + // Otherwise an inactive source yields zero with BOUND_CTRL or preserves D. + if (!fi) { + auto exec = wave64 ? select(upper_half, read(127), read(126)) : read(126); + auto source_bit = ir.binary("shl", "1", source_lane); + auto source_usable = cmp("ne", ir.binary("and", exec, source_bit), "0"); + value = select(source_usable, value, bound_zero ? "0" : read(i.dst)); + } + // Guest EXEC still predicates the destination write. + vector_write(i.dst, value); + } + void lower_dpp(const Inst &i, const State &state, unsigned threads) { + // All lane selections stay in one physical wave32 for split guest wave64. + // Shader control flow stays wave-uniform. Guest EXEC predicates VGPR + // writes, so FI can fetch the last VGPR value from a disabled thread. + const unsigned mask = i.mirror_mask(); + const auto row = i.dpp_row(); + const bool row_op = row.op != Inst::DppRowOp::None; + const unsigned group_size = i.dpp8_selectors ? 8 : row_op ? 16 : mask ? mask + 1 : 4; + if (threads % group_size) + refuse(i.pc, i.dpp8_selectors ? "DPP8 needs a thread count divisible by eight" + : row_op ? "DPP row shift or rotate needs a thread count divisible by 16" + : mask ? "DPP mirror needs complete source lane groups" + : "DPP quad_perm needs a thread count divisible by four"); + const auto rule = alu_rules.find(i.name); + if (!binary16_alu(i.name) && (rule == alu_rules.end() || rule->second.arity > 2)) + refuse(i.pc, "unsupported DPP arithmetic"); + if (i.enc == Encoding::Vop1 && ((i.neg | i.abs) & 2)) + refuse(i.pc, "unexpected second DPP source modifier"); + string source_lane, source_usable; + if (i.dpp8_selectors) { + auto octet_base = ir.binary("and", lane, "4294967288"); + auto octet_lane = ir.binary("and", lane, "7"); + auto shift = ir.binary("mul", octet_lane, "3"); + auto fields = ir.binary("lshr", to_string(*i.dpp8_selectors), shift); + source_lane = ir.binary("or", octet_base, ir.binary("and", fields, "7")); + } else if (row_op) { + auto row_base = ir.binary("and", lane, "4294967280"); + auto row_lane = ir.binary("and", lane, "15"); + auto amount = to_string(row.amount); + const bool shl = row.op == Inst::DppRowOp::Shl; + auto peer = ir.binary(shl ? "add" : "sub", row_lane, amount); + if (row.op != Inst::DppRowOp::Ror) + source_usable = cmp("ult", peer, "16"); + // Keep the physical lane index safe even when the shift is out of row. + source_lane = ir.binary("or", row_base, ir.binary("and", peer, "15")); + } else if (mask) + source_lane = ir.binary("xor", lane, to_string(mask)); + else { + auto quad_base = ir.binary("and", lane, "4294967292"); + auto quad_lane = ir.binary("and", lane, "3"); + auto shift = ir.binary("shl", quad_lane, "1"); + auto fields = ir.binary("lshr", to_string(*i.dpp_control), shift); + source_lane = ir.binary("or", quad_base, ir.binary("and", fields, "3")); + } + auto src = operand32(i, i.src[0]); + auto word = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32",src},{"i32",source_lane}}, "nounwind"); + if (!i.dpp_fetch_inactive) { + auto exec = wave64 ? select(upper_half, read(127), read(126)) : read(126); + auto source_enabled = cmp("ne", ir.binary("and", exec, ir.binary("shl", "1", source_lane)), "0"); + source_usable = source_usable.empty() ? source_enabled + : ir.value("and i1 " + source_usable + ", " + source_enabled); + } + string write_enabled; + if (!source_usable.empty()) { + // DPP8 supplies zero for a disabled source when FI is clear. + if (i.dpp8_selectors || i.dpp_bound_zero) word = select(source_usable, word, "0"); + else write_enabled = source_usable; + } + // Row and bank masks gate destination writes independently of the source and BOUND_CTRL. + auto apply_mask = [&](unsigned mask, const string &index) { + auto enabled = cmp("ne", ir.binary("and", to_string(mask), ir.binary("shl", "1", index)), "0"); + write_enabled = write_enabled.empty() ? enabled : ir.value("and i1 " + write_enabled + ", " + enabled); + }; + if (i.dpp_row_mask != 15) { + auto row_index = ir.binary("lshr", lane, "4"); + if (wave64) row_index = ir.binary("or", row_index, select(upper_half, "2", "0")); + apply_mask(i.dpp_row_mask, row_index); + } + if (i.dpp_bank_mask != 15) + apply_mask(i.dpp_bank_mask, ir.binary("and", ir.binary("lshr", lane, "2"), "3")); + string previous; + if (!write_enabled.empty()) previous = read(i.dst); + arithmetic(i, state, &word); + if (!previous.empty()) + write(i.dst, select(write_enabled, read(i.dst), previous)); + } + // Returns true when the instruction is a MODE write this path has accepted + // (including a no-op that leaves the implemented contract in place). + bool consume_half_mode(const Inst &i) { + if (!half_binary || graphics_input) + return false; + constexpr unsigned f16_bits = 0x8000ccu; // round16 [3:2], denorm16 [7:6], FP16_OVFL + constexpr unsigned contract = 0xf0u; // denorm32 = denorm16 = 3 (keep) + auto bad = [&]() { refuse(i.pc, "unsupported binary16 rounding or denormal mode"); }; + auto accept = [&](unsigned updated) { + if ((updated ^ contract) & f16_bits) + bad(); + // A write that moves a bit this path does not model (f32 round or + // f32 denorm) keeps the previous refusal. + if ((updated ^ mode_bits) & ~f16_bits) + return false; + mode_bits = updated; + return true; + }; + const auto &n = i.name; + if (n == "s_round_mode" || n == "s_denorm_mode") { + // Both immediates use [1:0] for f32 and [3:2] for f16/f64. Bits above + // the low nibble are ignored by the instruction. + const unsigned nibble = i.a & 15u; + const unsigned mask = n == "s_round_mode" ? 0xfu : 0xf0u; + const unsigned field = n == "s_round_mode" ? nibble : nibble << 4; + if (!half_mode_known && ((field ^ mode_bits) & mask & f16_bits)) + bad(); + return accept((mode_bits & ~mask) | field); + } + if (n != "s_setreg_b32" && n != "s_setreg_imm32_b32") + return false; + // SIMM16 = {size[4:0], offset[4:0], hwRegId[5:0]}. hwRegId 1 is MODE. + const unsigned simm = i.a & 0xffffu; + const unsigned hw = simm & 63u; + const unsigned offset = (simm >> 6) & 31u; + const unsigned size = ((simm >> 11) & 31u) + 1u; + if (hw != 1u || offset >= 32u || size > 32u - offset) + return false; + const unsigned mask = size == 32u ? 0xffffffffu : ((1u << size) - 1u) << offset; + if ((mask & f16_bits) == 0) + return false; + // The SGPR form, and any form reached from more than one path, does not + // prove the bits that this lowering implements. + if (n == "s_setreg_b32" || !half_mode_known) + bad(); + const unsigned updated = (mode_bits & ~mask) | ((i.literal << offset) & mask); + return accept(updated); + } + // A 64-thread desktop group executes one guest wave at a time. Register + // banks and resume PCs are private to each virtual wave; guest LDS is + // shared. Yield at branches for fairness and park at guest barriers. + void start_virtual_group(const std::set<unsigned>& labels) { + constexpr auto initial = "4294967294"; + const auto type = "[" + to_string(virtual_waves) + " x i32]"; + ir.setup << " %vpc = alloca " << type << ", align 4\n %cursor = alloca i32, align 4\n"; + std::vector<string> positions; + for (unsigned j=0; j<virtual_waves; ++j) { + auto ptr=ir.value("getelementptr " +type+", "+type+"* %vpc, i32 0, i32 "+to_string(j)); + positions.push_back(ptr); + ir.body << " store i32 " << initial << ", i32* " << ptr << "\n"; + } + lane=ir.invoke("i32","waveGetLaneIndex",111,{},"nounwind readnone"); + lane_bit=ir.binary("shl","1",lane); + auto flat=ir.invoke("i32","flattenedThreadIdInGroup.i32",96,{},"nounwind readnone"); + auto first=ir.invoke("i32","waveActiveOp.i32",119,{{"i32",flat},{"i8","2"},{"i8","1"}},"nounwind"); + upper_half=cmp("ne",first,"0"); + half_index=ir.value("zext i1 "+upper_half+" to i32"); + exchange_base="0"; exchange_words=2; + ir.body << " br label %cycle\ncycle:\n store i32 0, i32* %cursor\n br label %choose\nchoose:\n" + << " %virtualWave = load i32, i32* %cursor\n %currentPC = getelementptr " << type << ", " << type + << "* %vpc, i32 0, i32 %virtualWave\n %resume = load i32, i32* %currentPC\n" + << " switch i32 %resume, label %yield [ i32 " << initial << ", label %initializeWave\n"; + for (auto pc:labels) ir.body << " i32 " << pc << ", label %pc" << pc << "\n"; + ir.body << " ]\nyield:\n"; + barrier(11); + auto next=ir.binary("add","%virtualWave","1"); + ir.body << " store i32 " << next << ", i32* %cursor\n"; + auto again=cmp("ult",next,to_string(virtual_waves)); + ir.body << " br i1 " << again << ", label %choose, label %checkCycle\ncheckCycle:\n"; + string runnable="false", waiting="false"; + for (const auto& ptr:positions) { + auto pc=ir.value("load i32, i32* "+ptr); + runnable=ir.value("or i1 "+runnable+", "+cmp("ult",pc,"2147483648")); + waiting=ir.value("or i1 "+waiting+", "+cmp("ne",pc,"4294967295")); + } + ir.body << " br i1 " << runnable << ", label %cycle, label %rendezvous\nrendezvous:\n"; + for (const auto& ptr:positions) { + auto pc=ir.value("load i32, i32* "+ptr); + auto resumed=select(cmp("eq",pc,"4294967295"),pc,ir.binary("and",pc,"2147483647")); + ir.body << " store i32 " << resumed << ", i32* " << ptr << "\n"; + } + ir.body << " br i1 " << waiting << ", label %cycle, label %finished\nfinished:\n ret void\ninitializeWave:\n"; + } + void yield_virtual_wave(const string& next) { + ir.body << " store i32 " << next << ", i32* %currentPC\n br label %yield\n"; + } + NativeComputeShader lower(unsigned entry, unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { + const unsigned lds_words = ((flags >> 15) & 511) * 128; + const bool uses_lds = std::any_of(analysis.program.code.begin(), analysis.program.code.end(), + [](const Inst &i) { return i.enc == Encoding::Lds; }); + if (uses_lds) + ir.globals << "@lds = internal addrspace(3) global [" << lds_words << " x i32] undef, align 4\n"; + prepare_descriptor_strides(); + const auto &p = analysis.program; + mode_bits = 0xf0; + bool mode_write = false, conditional = false; + for (size_t k = 0; k < p.code.size(); ++k) { + if (!p.reached[k]) + continue; + const auto &op = p.code[k]; + if (binary16_alu(op.name) || binary16_unary(op.name) || + op.name == "v_pk_min_f16" || + op.name == "v_pk_max_f16" || + op.name == "v_cvt_f16_u16" || + op.name == "v_cvt_f16_i16" || + op.name == "v_cvt_u16_f16" || + op.name == "v_cvt_i16_f16" || + op.name == "v_fma_f16" || + op.name == "v_fmac_f16" || + op.name == "v_fmamk_f16" || + op.name == "v_fmaak_f16" || + op.name == "v_fract_f16" || + op.name == "v_ldexp_f16" || + op.name == "v_cvt_norm_i16_f16" || + op.name == "v_cvt_norm_u16_f16") + half_binary = true; + if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" || + op.name == "s_setreg_imm32_b32") + mode_write = true; + if (packed_f16_arithmetic(op.name) || op.name == "v_dot2_f32_f16" || op.name == "v_dot2c_f32_f16") + half_binary = true; + if (op.branch() && op.op != 2) + conditional = true; + } + half_mode_known = !(half_binary && mode_write && conditional); + const bool writes_uavs = std::any_of(p.code.begin(), p.code.end(), [](const Inst &i) { + return i.name.substr(0, 12) == "buffer_store" || i.name.substr(0, 13) == "buffer_atomic" || + (i.enc == Encoding::Image && i.op == 8) || is_image_atomic(i); + }); + std::set<unsigned> labels{entry}; + for (auto &i : p.code) + if (i.branch()) { + labels.insert(i.target()); + if (i.op != 2) + labels.insert(i.next); + } + if (virtual_waves) for (const auto &i : p.code) + if (i.name == "s_barrier") labels.insert(i.next); + if (virtual_waves) start_virtual_group(labels); + initialize(user, flags, x, y, z); + ir.body << " br label %pc" << entry << "\n"; + for (size_t k = 0; k < p.code.size(); ++k) { + const auto &i = p.code[k]; + compute_pc = i.pc; + compute_state = &p.before[k]; + if (labels.count(i.pc)) { + if (k && p.code[k - 1].name != "s_endpgm" && !p.code[k - 1].branch() && + !(virtual_waves && p.code[k-1].name=="s_barrier")) + ir.body << " br label %pc" << i.pc << "\n"; + ir.body << "pc" << i.pc << ":\n"; + } + if (!p.reached[k]) { + ir.body << " unreachable\n"; + while (k + 1 < p.code.size() && !labels.count(p.code[k + 1].pc)) + ++k; + continue; + } + if (i.branch()) { + if (i.op == 2) { + if (virtual_waves) yield_virtual_wave(to_string(i.target())); + else ir.body << " br label %pc" << i.target() << "\n"; + } + else { + unsigned r = i.op == 4 || i.op == 5 ? 128 : i.op == 6 || i.op == 7 ? 106 : 126; + auto mask = wave64 && r != 128 ? ir.binary("or", read(r), read(r + 1)) : read(r); + auto pred = cmp((i.op & 1) ? "ne" : "eq", mask, "0"); + if (virtual_waves) yield_virtual_wave(select(pred,to_string(i.target()),to_string(i.next))); + else ir.body << " br i1 " << pred << ", label %pc" << i.target() << ", label %pc" << i.next << "\n"; + } + } else if (i.dpp_control || i.dpp8_selectors) + lower_dpp(i, p.before[k], x*y*z); + else if (i.name == "v_permlane16_b32" || i.name == "v_permlanex16_b32") + lower_permlane(i, x*y*z); + else if (i.name == "s_endpgm") { + if (virtual_waves) yield_virtual_wave("4294967295"); + else ir.body << " ret void\n"; + } + // Hardware scheduling and register-dependency waits have no SGPR + // operands. SSA dependencies carry these constraints into DXIL. + else if (i.name == "v_nop" || i.name == "s_inst_prefetch" || i.name == "s_clause" || i.name == "s_nop" || + i.name == "s_waitcnt" || i.name == "s_waitcnt_depctr" || i.name == "s_setprio") + continue; + else if (i.enc == Encoding::Mubuf || i.enc == Encoding::Smem) + memory(i, p.before[k]); + else if (i.enc == Encoding::Lds) + local_memory(i, lds_words); + else if (i.name == "s_barrier") { + if (virtual_waves) yield_virtual_wave(to_string(i.next | 0x80000000u)); + else barrier(writes_uavs ? 11 : 9); + } + else if (i.name == "s_waitcnt_vscnt" || i.name == "s_waitcnt_vmcnt" || + i.name == "s_waitcnt_lgkmcnt" || i.name == "s_waitcnt_expcnt") { + // null,0 drains this wave's counter. Memory-only barriers + // preserve ordering without rendezvousing other workgroup waves. + if (i.dst != 125 || (i.a & 65535)) + refuse(i.pc, "compute counter wait requires null and a zero threshold"); + if (i.name == "s_waitcnt_lgkmcnt" && uses_lds) + barrier(8); + if ((i.name == "s_waitcnt_vscnt" || i.name == "s_waitcnt_vmcnt") && writes_uavs) + barrier(2); + } + else if (consume_half_mode(i)) + continue; + else if (i.enc == Encoding::Sopp) + refuse(i.pc, "unsupported compute control instruction " + string(i.name)); + else if (i.enc == Encoding::Image) + image_io(i, p.before[k]); + else + arithmetic(i, p.before[k], nullptr, true); + } + auto &r = analysis.result; + r.instruction_count = unsigned(p.code.size()); + const unsigned rank_words = !virtual_waves && x * y * z > 64 ? x * y * z : 0; + if ((uses_lds ? lds_words : 0) + rank_words + (uses_exchange ? exchange_words : 0) > 8192) + refuse(entry, "combined shared storage exceeds 32 KiB"); + // SM 6.6 forms consecutive linear quads for 1D groups. In 2D it forms + // spatial 2x2 quads, which can cross the guest's consecutive lane quads. + // initialize() still reconstructs guest IDs using the original dimensions. + // The wave64 split occurs at lane 32, a quad boundary. + if (compute_derivatives) + ir.validator_minor = 8; + r.dxil_ir = virtual_waves ? ir.finish_compute(64, 1, 1) + : compute_derivatives ? ir.finish_compute(x * y * z, 1, 1) + : ir.finish_compute(x, y, z); + return std::move(r); + } +}; diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl new file mode 100644 index 0000000000..2bf090b7b7 --- /dev/null +++ b/src/gfx1013_direct_graphics.inl @@ -0,0 +1,2357 @@ +// Graphics stages share decoded operands, scalar provenance, +// vector arithmetic, memory operations and binary resource declarations with CS. +// Signature rows describe how native exports meet the desktop rasterizer. +struct GraphicsStage { + const GuestShaderStage &stage; + DirectCompute &alu; + bool pixel; + std::map<unsigned, unsigned> exported; + unsigned pc = 0; + + struct Interpolation { + unsigned attribute, channel, source, mode; + }; + std::map<unsigned, Interpolation> partial; + std::set<unsigned> overwritten_inputs; + std::map<unsigned, string> branch_inputs; + // SPI_PS_INPUT_ADDR order and DXIL interpolation modes, following + // victory-shader (9376fd6), io.rs and emit/lower.rs::barycentric. + static constexpr unsigned bary_modes[] = {6, 2, 3, 0, 7, 4, 5}; + const string &incoming_input(unsigned reg) { + auto [it, new_value] = branch_inputs.try_emplace(reg); + if (!new_value || reg < 256 || reg >= 512) + return it->second; + // An input untouched on one predecessor still has its entry value. + // Its load must dominate every edge of the phi at the join. + alu.ir.setup.swap(alu.ir.body); + try { + it->second = input(reg); + } catch (const UnsupportedComputeShader &) { + // A temporary may legitimately be undefined on a dead edge. + // A subsequent read of this merged register reports the refusal. + } + alu.ir.setup.swap(alu.ir.body); + return it->second; + } + void interpolate(Word w) { + unsigned op = (w >> 16) & 3, attr = (w >> 10) & 63, channel = (w >> 8) & 3, src = w & 255, + dest = 256 + ((w >> 18) & 255); + if (!pixel) + refuse(pc, "interpolation outside pixel stage"); + const auto it = std::find_if(stage.attributes.begin(), stage.attributes.end(), + [&](auto &a) { return a.location == attr && (a.mask & (1u << channel)); }); + if (it == stage.attributes.end() || it->usage != 6 || (it->flags & 0x18)) + refuse(pc, "missing or packed interpolation attribute"); + unsigned mode = 1; + if (op == 2) { + if (src != 2 || !(it->flags & 1)) + refuse(pc, "unsupported provoking vertex or smooth flat fetch"); + } else { + unsigned base = 0, first = UINT_MAX; + for (unsigned bit = 0; bit < 7; ++bit) + if (stage.pixel_input_address & (1u << bit)) { + if ((stage.pixel_input_enable & (1u << bit)) && src == base + (op == 1)) { + mode = bary_modes[bit]; + first = base; + break; + } + base += bit == 3 ? 3 : 2; + } + if (op > 1 || !mode || first == UINT_MAX || (it->flags & 1) || overwritten_inputs.count(256 + src)) + refuse(pc, "interpolation barycentric source is not an entry register"); + if (op == 0) { + partial[dest] = {attr, channel, src, mode}; + alu.graphics_registers.erase(dest); + alu.guarded_ij.erase(dest); + overwritten_inputs.insert(dest); + return; + } + const auto prev = partial.find(dest); + if (prev == partial.end() || prev->second.attribute != attr || prev->second.channel != channel || + prev->second.source != first || prev->second.mode != mode) + refuse(pc, "unmatched interpolation pair"); + } + partial.erase(dest); + alu.write(dest, load(generic(true, it->row, channel, mode), channel)); + overwritten_inputs.insert(dest); + } + unsigned system(const string &name) { + if (name == "SV_Position") + return 3; + if (name == "SV_VertexID") + return 1; + if (name == "SV_InstanceID") + return 2; + if (name == "SV_Target") + return 16; + if (name.rfind("SV_", 0) == 0) + refuse(pc, "unsupported graphics system semantic " + name); + return 0; + } + unsigned row(bool input, const string &name, unsigned index, unsigned kind, unsigned component, unsigned reg, + unsigned mask, unsigned interpolation) { + auto &rows = input ? alu.ir.inputs : alu.ir.outputs; + const bool unpacked = pixel && reg == UINT_MAX && (input ? kind == 28 && mask == 7 : mask == 1); + if ((reg >= 32 && !unpacked) || !mask || mask > 15) + refuse(pc, "invalid signature register or component mask"); + unsigned first = 0, width = 0; + while (!(mask & (1u << first))) + ++first; + while (mask & (1u << (first + width))) + ++width; + if (mask != ((1u << width) - 1) << first) + refuse(pc, "noncontiguous signature channels"); + for (unsigned j = 0; j < rows.size(); ++j) { + const auto &r = rows[j]; + if (r.name == name && r.semantic_index == index) { + if (r.row != reg || r.first != first || r.width != width || r.interpolation != interpolation || + r.component != component || r.kind != kind) + refuse(pc, "inconsistent graphics signature row"); + return j; + } + if (reg != UINT_MAX && r.row == reg && mask & (((1u << r.width) - 1) << r.first)) + refuse(pc, "overlapping graphics signature rows"); + } + rows.push_back({name, index, kind, component, reg, first, width, interpolation}); + return static_cast<unsigned>(rows.size() - 1); + } + unsigned generic(bool input, unsigned reg, unsigned channel, unsigned interpolation) { + const auto &signature = input ? stage.input_signature : stage.output_signature; + for (const auto &s : signature) { + if (s.row != reg || !(s.mask & (1u << channel)) || s.system) + continue; + unsigned component = s.component == 1 ? 5 : s.component == 2 ? 4 : s.component == 3 ? 9 : 0; + if (!component) + refuse(pc, "unknown signature component"); + return row(input, s.name, s.index, system(s.name), component, s.row, s.mask, + !input && component != 9 ? 1 : interpolation); + } + refuse(pc, "missing generic graphics signature row"); + } + string load(unsigned id, unsigned channel) { + auto &s = alu.ir.inputs.at(id); + const unsigned col = channel - s.first; + const bool fp = s.component == 9; + auto v = alu.ir.invoke(fp ? "float" : "i32", fp ? "loadInput.f32" : "loadInput.i32", 4, + {{"i32", to_string(id)}, {"i32", "0"}, {"i8", to_string(col)}, {"i32", "undef"}}, + "nounwind readnone"); + alu.ir.dependencies[v].set(s.row == UINT_MAX ? 128 : s.row * 4 + channel); + s.used |= 1u << col; + return fp ? alu.ir.value("bitcast float " + v + " to i32") : v; + } + string input(unsigned reg) { + if (partial.count(reg)) + refuse(pc, "intermediate interpolation value used outside its pair"); + if (reg < 256) + refuse(pc, "undefined graphics register " + to_string(reg)); + unsigned vgpr = reg - 256; + if (pixel) { + // SPI_PS_INPUT_ADDR allocates enabled inputs consecutively. The + // pull-model barycentrics consume three VGPRs and line stipple one. + unsigned first = 0; + for (unsigned bit = 0; bit < 16; ++bit) { + if (!(stage.pixel_input_address & (1u << bit))) + continue; + const unsigned width = bit == 3 ? 3 : bit < 7 ? 2 : 1; + if (vgpr >= first && vgpr < first + width) { + if (!(stage.pixel_input_enable & (1u << bit))) + break; + if (bit < 7 && bary_modes[bit]) { + // I/J weight vertices one and two. Distinct guest + // pairs may need distinct host system-value elements. + const unsigned mode = bary_modes[bit]; + auto perspective = [](unsigned m) { return m == 2 || m == 3 || m == 6; }; + unsigned index = 0; + for (const auto &r : alu.ir.inputs) { + if (r.kind != 28) continue; + if (r.interpolation == mode) { + index = r.semantic_index; + break; + } + if (perspective(r.interpolation) == perspective(mode)) + refuse(pc, "two barycentric locations in the same perspective mode"); + ++index; + } + alu.ir.features |= 1u << 22; + auto id = row(true, "SV_Barycentrics", index, 28, 9, UINT_MAX, 7, mode); + return load(id, 1 + vgpr - first); + } + if (bit == 15) { + for (const auto &s : stage.input_signature) { + if (s.system != D3D_NAME_POSITION || s.component != 3 || (s.mask & 3) != 3) + continue; + auto id = row(true,"SV_Position",0,3,9,s.row,s.mask,4); + auto coord = [&](unsigned axis) { + auto fp = alu.ir.value("bitcast i32 " + load(id,axis) + " to float"); + return alu.ir.value("fptoui float " + fp + " to i32"); + }; + auto x=coord(0), y=coord(1); + return alu.ir.binary("or", alu.ir.binary("and",x,"65535"), alu.ir.binary("shl",y,"16")); + } + refuse(pc,"packed position requires screen XY"); + } + if (bit == 12) { + for (const auto &s : stage.input_signature) + if (s.system == D3D_NAME_IS_FRONT_FACE && s.mask == 1 && s.component == 1) + return load(row(true, "SV_IsFrontFace", 0, 13, 5, s.row, 1, 1), 0); + refuse(pc, "front face absent from pixel signature"); + } + if (bit < 8 || bit > 11) + break; + unsigned channel = bit - 8; + for (const auto &signature : stage.input_signature) { + if (signature.system != 1 || signature.component != 3 || !(signature.mask & (1u << channel))) + continue; + if (stage.pixel_input_address & 0x11) + refuse(pc, "sample-frequency position input"); + const bool conservative = std::any_of(stage.output_signature.begin(), + stage.output_signature.end(), [](const auto &out) { + return out.system == D3D_NAME_DEPTH_GREATER_EQUAL || + out.system == D3D_NAME_DEPTH_LESS_EQUAL; + }); + return load( + row(true, "SV_Position", 0, 3, 9, signature.row, signature.mask, conservative ? 5 : 4), + channel); + } + refuse(pc, "position absent from pixel input signature"); + } + first += width; + } + refuse(pc, "unsupported pixel entry VGPR " + to_string(vgpr)); + } + if (alu.analysis.result.vertex_fetch) + for (const auto &a : stage.attributes) { + if (vgpr < a.location || vgpr - a.location > a.last_component) + continue; + if (a.usage != 6) + refuse(pc, "unsupported vertex fetch semantic"); + unsigned channel = vgpr - a.location; + return load(generic(true, a.row, channel, 0), channel); + } + if (vgpr != 0 && vgpr != 3) + refuse(pc, "unbound vertex VGPR " + to_string(vgpr)); + string name = vgpr ? "SV_InstanceID" : "SV_VertexID"; + unsigned free = 0; + for (const auto &s : stage.input_signature) { + if (s.name == name) + return load(row(true, name, 0, system(name), 5, s.row, 1, 0), 0); + free = (std::max)(free, s.row + 1); + } + for (unsigned id = 0; id < alu.ir.inputs.size(); ++id) { + const auto &s = alu.ir.inputs[id]; + if (s.name == name && !s.semantic_index && s.kind == system(name)) + return load(id, 0); + free = (std::max)(free, s.row + 1); + } + return load(row(true, name, 0, system(name), 5, free, 1, 0), 0); + } + string quad_source(const Inst &i) { + const unsigned perm = *i.dpp_control; + string word = alu.operand32(i, i.src[0]); + if (perm == 0xe4) + return word; + alu.ir.uses_wave = true; + auto pick = [&](unsigned n) { + return alu.ir.invoke("i32", "quadReadLaneAt.i32", 122, {{"i32", word}, {"i32", to_string(n)}}, "nounwind"); + }; + if (perm == (perm & 3) * 0x55u) + return pick(perm & 3); + if (perm == 0xb1 || perm == 0x4e || perm == 0x1b) + return alu.ir.invoke("i32", "quadOp.i32", 123, + {{"i32", word}, + {"i8", perm == 0xb1 ? "0" + : perm == 0x4e ? "1" + : "2"}}, + "nounwind"); + for (const auto &s : stage.input_signature) { + if (s.system != D3D_NAME_POSITION || s.component != 3 || (s.mask & 3) != 3) + continue; + const bool conservative = + std::any_of(stage.output_signature.begin(), stage.output_signature.end(), [](const auto &out) { + return out.system == D3D_NAME_DEPTH_GREATER_EQUAL || out.system == D3D_NAME_DEPTH_LESS_EQUAL; + }); + auto id = row(true, "SV_Position", 0, 3, 9, s.row, s.mask, conservative ? 5 : 4); + auto parity = [&](unsigned channel) { + auto pos = alu.ir.value("bitcast i32 " + load(id, channel) + " to float"); + auto pixel = alu.ir.invoke("float", "unary.f32", 27, {{"float", pos}}, "nounwind readnone"); + return alu.ir.binary("and", alu.ir.value("fptosi float " + pixel + " to i32"), "1"); + }; + auto x = parity(0), y = parity(1); + auto lane = alu.ir.binary("or", x, alu.ir.binary("shl", y, "1")); + std::array<string, 4> picked; + for (unsigned j = 0; j < 4; ++j) { + unsigned source = (perm >> (2 * j)) & 3; + if (picked[source].empty()) + picked[source] = pick(source); + } + auto result = picked[(perm >> 6) & 3]; + for (int j = 2; j >= 0; --j) + result = alu.select(alu.cmp("eq", lane, to_string(j)), picked[(perm >> (2 * j)) & 3], result); + return result; + } + refuse(i.pc, "general pixel quad permutation requires position XY"); + } + unsigned output(unsigned target, unsigned &channel) { + if (pixel && target < 8) { + // An RTV variant types the target by its format. A signature that says otherwise is not reinterpreted. + const unsigned asked = stage.target_components[target]; + for (const auto &s : stage.output_signature) { + if (s.system != D3D_NAME_TARGET || s.index != target) + continue; + if (s.row != target || !(s.mask & (1u << channel)) || !s.component || s.component > 3) + refuse(pc, "color export incompatible with pixel signature"); + const unsigned component = s.component == 3 ? 9 : s.component == 2 ? 4 : 5; + if (asked && asked != component) + refuse(pc, "RTV variant format disagrees with the pixel signature of target " + to_string(target)); + return row(false, "SV_Target", target, 16, component, s.row, s.mask, 0); + } + if (!stage.output_signature.empty()) + refuse(pc, "color target absent from pixel signature"); + return row(false, "SV_Target", target, 16, asked ? asked : 9, target, 15, 0); + } + if (pixel && target == 8) { + for (const auto &s : stage.output_signature) { + unsigned kind = 0; + if (!channel && s.system == D3D_NAME_DEPTH) + kind = 17; + if (!channel && s.system == D3D_NAME_DEPTH_LESS_EQUAL) + kind = 18; + if (!channel && s.system == D3D_NAME_DEPTH_GREATER_EQUAL) + kind = 19; + if (channel == 1 && s.system == D3D_NAME_STENCIL_REF) + kind = 20; + if (channel == 2 && s.system == D3D_NAME_COVERAGE) + kind = 14; + if (!kind) + continue; + if (s.row != UINT_MAX || s.mask != 1 || s.index || s.component != (channel ? 1u : 3u)) + refuse(pc, "invalid depth, stencil or coverage signature"); + if (kind == 20) + alu.ir.features |= 2048; + return row(false, s.name, 0, kind, channel ? 5 : 9, UINT_MAX, 1, 0); + } + refuse(pc, "unmapped depth, stencil or coverage export"); + } + if (!pixel && target == 12) { + for (const auto &s : stage.output_signature) + if (s.system == 1 || s.name == "SV_Position") + return row(false, "SV_Position", 0, 3, 9, s.row, s.mask, 4); + if (!stage.outputs.empty()) + refuse(pc, "missing position register"); + return row(false, "SV_Position", 0, 3, 9, 0, 15, 4); + } + if (!pixel && (target == 13 || target == 14)) { + // With no misc position vector, POS1 and POS2 pack clip distances + // followed by cull distances, in semantic index/component order. + std::vector<const ShaderSemantic *> distances; + for (const auto &s : stage.output_signature) { + if (s.system == D3D_NAME_RENDER_TARGET_ARRAY_INDEX || s.system == D3D_NAME_VIEWPORT_ARRAY_INDEX || + s.name == "PSIZE") + refuse(pc, "ambiguous clip/cull position export"); + if (s.system == D3D_NAME_CLIP_DISTANCE || s.system == D3D_NAME_CULL_DISTANCE) + distances.push_back(&s); + } + std::sort(distances.begin(), distances.end(), [](const auto *a, const auto *b) { + return std::pair{a->system, a->index} < std::pair{b->system, b->index}; + }); + unsigned index = (target - 13) * 4 + channel; + for (const auto *s : distances) { + if (s->component != 3) + refuse(pc, "non-float clip/cull distance"); + for (unsigned c = 0; c < 4; ++c) + if (s->mask & (1u << c)) { + if (index == 0) { + channel = c; + return row(false, s->name, s->index, s->system == D3D_NAME_CLIP_DISTANCE ? 6 : 7, 9, s->row, + s->mask, 2); + } + --index; + } + } + refuse(pc, "unmapped position export channel"); + } + if (!pixel && target >= 32) + for (const auto &a : stage.outputs) + if (a.location == target - 32 && (!a.mask || (a.mask & (1u << channel)))) { + if (a.usage != 6 || (a.flags & 3)) + refuse(pc, "unsupported packed vertex export"); + return generic(false, a.row, channel, 2); + } + refuse(pc, "unmapped graphics export"); + } + void emit_export(Word first, Word sources) { + const unsigned target = (first >> 4) & 63, mask = first & 15; + const bool compressed = (first & 0x400) != 0; + if ((first & 0x03ffe000) || (compressed && (!pixel || target >= 8 || (mask != 3 && mask != 12 && mask != 15))) || + !exported.emplace(target, mask).second) + refuse(pc, "unsupported graphics export mask or repeated target"); + if (target == 9 || (!pixel && target == 32 && stage.outputs.empty() && + std::none_of(stage.output_signature.begin(), stage.output_signature.end(), + [](const auto &s) { return !s.system; }))) + return; + if (!mask) + refuse(pc, "empty enabled graphics export"); + unsigned signature_mask = 15; + if (!pixel && target >= 32) { + // PARAM exports have four hardware lanes, including padding when + // the logical signature row is narrower. Preserve packed semantics + // belonging to the same row and let stage linkage check all PS reads. + unsigned channels = 0; + for (const auto &a : stage.outputs) { + if (a.location != target - 32 || a.usage != 6 || (a.flags & 3)) continue; + unsigned declared = 0; + for (const auto &s : stage.output_signature) + if (s.row == a.row && !s.system) declared |= s.mask; + if (!declared) refuse(pc, "vertex parameter has no output signature"); + channels |= declared; + } + if (channels) signature_mask = channels; + } + if (pixel && target < 8) + alu.analysis.result.pixel_writes[target] = mask; + for (unsigned c = 0; c < 4; ++c) + if (mask & signature_mask & (1u << c)) { + auto bits = alu.read(256 + ((sources >> (8 * (compressed ? c / 2 : c))) & 255)); + unsigned channel = c; + auto id = output(target, channel); + auto &s = alu.ir.outputs[id]; + if (s.row == UINT_MAX) + channel = 0; + if (channel < s.first || channel >= s.first + s.width) + refuse(pc, "export outside signature"); + const bool fp = s.component == 9; + if (compressed) { + if (!fp) refuse(pc, "packed color export requires floating target"); + auto half = alu.subword(bits, 4 + (c & 1), false); + auto value = alu.ir.invoke("float", "legacyF16ToF32", 131, {{"i32",half}}, "nounwind readnone"); + bits = alu.ir.value("bitcast float " + value + " to i32"); + } + auto v = fp ? alu.ir.value("bitcast i32 " + bits + " to float") : bits; + alu.ir.invoke("void", fp ? "storeOutput.f32" : "storeOutput.i32", 5, + {{"i32", to_string(id)}, + {"i32", "0"}, + {"i8", to_string(channel - s.first)}, + {fp ? "float" : "i32", v}}, + "nounwind"); + s.used |= 1u << (channel - s.first); + if (s.row == UINT_MAX) + continue; + if (alu.ir.loop_dependencies) + alu.ir.output_values[s.row * 4 + channel].push_back(v); + if (auto d = alu.ir.dependencies.find(v); d != alu.ir.dependencies.end()) + alu.ir.output_dependencies[s.row * 4 + channel] |= d->second; + } + } +}; + +// Acyclic scalar branches preserve the rasterizer's per-invocation SSA values. +// An SGPR comparison can select a path without introducing a guest EXEC mask. +struct GraphicsBlock { + size_t begin, end; + std::vector<unsigned> successors; + unsigned predecessors = 0; +}; +// An EXECZ skip over lane-local ALU with an exact restore has a per-lane +// equivalent. Mark that region before building the scalar CFG so the merge +// is a select on each VGPR, including the old value of inactive lanes. +struct GraphicsMaskRegions { + std::set<unsigned> saves, complements, restores; + std::set<unsigned> sample_begins, sample_ends; + std::set<unsigned> compares, cmpx_starts, unions, intersections, inner_saves, inner_restores; + std::map<unsigned, std::set<unsigned>> expired; + std::map<unsigned, unsigned> enclosing_mask; + std::map<unsigned, unsigned> branch_saves; + std::map<unsigned, std::pair<unsigned,bool>> lane_branches; + std::map<unsigned, unsigned> branch_merges; + struct MaskCapture { unsigned skip, value; }; + std::map<unsigned, MaskCapture> captures; + std::set<unsigned> vertex_anchors, vertex_partitions; + std::map<unsigned,unsigned> mask_inputs; + std::map<unsigned,unsigned> inverted_compare; + std::set<unsigned> vertex_mask_compares, uniform_mask_tests; + std::set<unsigned> scalar_mask_selects; + std::map<unsigned,unsigned> then_fallthroughs; + std::set<unsigned> scalar_tail_merges; + static unsigned scalar_width(const Inst &i) { + if (i.enc == Encoding::Smem) return memory_count(i); + if (i.enc == Encoding::Vopc) return 2; + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk) + return i.name.find("64") == Name::npos ? 1 : 2; + return i.name == "v_readfirstlane_b32" || i.name == "v_readlane_b32" ? 1 : 0; + } + // Track pairs equal to the initial EXEC, on every path. An inner save + // followed by a restore may preserve the value even across nested skips. + static bool preserves_exec(const Program &p, size_t begin, size_t end, unsigned parent = 126) { + using Pairs = std::bitset<128>; + std::vector<std::optional<Pairs>> incoming(end-begin+1); + incoming.front().emplace().set(126).set(parent); + for (size_t j = begin; j < end; ++j) { + const auto &at = incoming[j-begin]; + if (!at) continue; + auto known = *at; + const auto &i = p.code[j]; + const bool was_exec = known[126]; + const bool copy = i.name == "s_mov_b64" && i.src[0] < 128 && known[i.src[0]]; + auto clobber = [&](unsigned dst,unsigned count) { + for (unsigned n = dst; n < dst + count && n < 128; ++n) + known.reset(n & ~1u); + }; + clobber(i.dst, scalar_width(i)); + if (auto carry = carry_destination(i)) clobber(*carry,2); + if (i.name.find("saveexec") != Name::npos) { + known[126] = false; + known[i.dst] = was_exec; + } else if (copy) known[i.dst] = true; + auto edge = [&](size_t target) { + if (target <= j) return false; + if (target > end) return parent != 126; + auto &destination = incoming[target-begin]; + if (destination) *destination &= known; + else destination = known; + return true; + }; + if (i.branch() && !edge(p.at.at(i.target()))) return false; + if ((!i.branch() || i.op != 2) && !edge(j+1)) return false; + } + return incoming.back() && (*incoming.back())[126] && (*incoming.back())[parent]; + } + static bool local_alu(const Inst &i) { + return (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3) && + i.dst >= 256 && !i.dpp_control && i.name.find("lane") == Name::npos && + i.name.find("mbcnt") == Name::npos && i.name.find("_co_") == Name::npos; + } + static void skip_proven(Inst &skip) { + skip.enc = Encoding::Sopp; + skip.op = 0; + skip.name = "s_nop"; // VGPR writes use the corresponding lane predicate. + } + // A material flag is tested with a CLASS mask, then the compare bits + // are complemented before selecting an optional read. All active lanes + // take exactly one arm. Require a reaching save of the enclosing EXEC, + // side-effect-free bodies and a join that restores precisely that mask. + void pixel_class_arms(const Program &p,const std::multimap<unsigned,unsigned> &entries) { + const auto &code=p.code; + for (size_t k=0;k+5<code.size();++k) { + const auto &cmp=code[k], &invert=code[k+1], &narrow=code[k+2], &skip=code[k+3]; + if ((cmp.name!="v_cmp_class_f32" && cmp.name!="v_cmp_class_f16") || cmp.dst>104 || (cmp.dst&1) || + invert.name!="s_not_b64" || invert.dst!=cmp.dst || invert.src[0]!=cmp.dst || + narrow.name!="s_and_b64" || narrow.dst!=126 || narrow.src[0]!=cmp.dst || narrow.src[1]!=126 || + !skip.branch() || skip.op!=8 || skip.target()<=skip.next) continue; + const size_t middle=p.at.at(skip.target()); + const auto &otherwise=code[middle]; + const auto parent=otherwise.src[0]; + if (otherwise.name!="s_andn2_b64" || otherwise.dst!=126 || parent>104 || (parent&1) || + parent==cmp.dst || otherwise.src[1]!=126) continue; + auto pure=[](const Inst &i) { + return (local_alu(i) && !carry_destination(i)) || i.name=="s_waitcnt" || i.name=="s_nop" || + (i.enc==Encoding::Mubuf && i.name=="buffer_load_dword"); + }; + size_t end=middle+1; + while (end<code.size() && pure(code[end])) ++end; + if (end==code.size() || end==middle+1 || code[end].name!="s_mov_b64" || + code[end].dst!=126 || code[end].src[0]!=parent || + !std::all_of(code.begin()+k+4,code.begin()+middle,pure)) continue; + bool external=false; + for (auto it=entries.upper_bound(cmp.pc);it!=entries.end() && it->first<=code[end].pc;++it) + if (it->second!=skip.pc) external=true; + if (external) continue; + bool saved=false; + for (size_t j=k;j && !entries.count(code[j].pc);) { + const auto &prev=code[--j]; + if (prev.name=="s_mov_b64" && ((prev.dst==126 && prev.src[0]==parent) || + (prev.dst==parent && prev.src[0]==126))) {saved=true; break;} + const auto w=scalar_width(prev); + if (prev.branch() || prev.name.find("exec")!=Name::npos || carry_destination(prev) || + (w && ((prev.dst<parent+2 && parent<prev.dst+w) || prev.dst+w>126))) break; + } + if (!saved) continue; + inverted_compare[invert.pc]=1024+cmp.pc; + mask_inputs[narrow.pc]=1024+invert.pc; + const unsigned predicate=1024+narrow.pc; + branch_saves[narrow.pc]=predicate; + lane_branches.emplace(skip.pc,std::make_pair(predicate,false)); + branch_merges[otherwise.pc]=branch_merges[code[end].pc]=predicate; + then_fallthroughs[code[middle-1].pc]=code[end].pc; + expired[otherwise.pc].insert(128); + expired[code[end].pc].insert(128); + } + } + void vertex_scalar_tails(const Program &p, const std::multimap<unsigned,unsigned> &entries) { + const auto &code = p.code; + for (size_t k=0; k+2<code.size(); ++k) { + const auto &mask=code[k], &skip=code[k+1]; + if (!skip.branch() || skip.op != 8 || skip.target() <= skip.next || lane_branches.count(skip.pc)) continue; + const bool cmpx = mask.enc == Encoding::Vopc && mask.dst == 126 && mask.name.substr(0,7) == "v_cmpx_" && + !mask.scale && !mask.clamp && !mask.subword && mask.name.find("class") == Name::npos; + if (!cmpx && !(mask.name == "s_and_b64" && mask.dst == 126 && + ((mask.src[0] == 106 && mask.src[1] == 126) || (mask.src[0] == 126 && mask.src[1] == 106)))) continue; + const size_t join = p.at.at(skip.target()); + const auto &inv = code[join]; + const bool has_else = inv.name == "s_andn2_b64" && inv.dst == 126 && inv.src[1] == 126; + size_t tail = join + has_else; + if (has_else) while (tail < code.size() && local_alu(code[tail])) ++tail; + size_t end = tail; + while (end < code.size() && (code[end].enc == Encoding::Smem || + code[end].name == "s_waitcnt" || code[end].name == "s_nop")) ++end; + if (end == code.size() || (!has_else && end == tail)) continue; + const auto &restore = code[end]; + const unsigned parent = restore.src[0]; + if (restore.name != "s_mov_b64" || restore.dst != 126 || parent > 104 || (parent & 1) || + (has_else && inv.src[0] != parent)) continue; + // An earlier restore may dominate across a uniform diamond. + // Exclude outside entries and prove that both EXEC and the saved + // pair retain the anchor's value on all paths reaching the mask. + size_t anchor = k; + bool anchored = false; + while (anchor) { + const auto &a = code[--anchor]; + if (a.name != "s_mov_b64" || !((a.dst == 126 && a.src[0] == parent) || + (a.dst == parent && a.src[0] == 126))) continue; + auto entry = entries.upper_bound(a.pc); + for (; entry != entries.end() && entry->first <= mask.pc; ++entry) + if (entry->second < a.pc || entry->second >= mask.pc) break; + anchored = (entry == entries.end() || entry->first > mask.pc) && preserves_exec(p,anchor+1,k,parent); + break; + } + if (!anchored) continue; + for (auto entry=entries.upper_bound(mask.pc); entry!=entries.end() && entry->first<=restore.pc; ++entry) + if (entry->second != skip.pc) + refuse(entry->first,"branch enters a vertex EXEC scalar-tail region"); + std::set<unsigned> modified{106,107,128}; + for (size_t j=k+2; j<end; ++j) { + const auto &op=code[j]; + if (has_else && j==join) continue; + const bool scalar = op.enc == Encoding::Smem || op.enc == Encoding::Sopc || + ((op.enc == Encoding::Sop1 || op.enc == Encoding::Sop2 || op.enc == Encoding::Sopk) && op.dst<106); + if (op.name.find("exec") != Name::npos || !(local_alu(op) || scalar || op.name=="s_waitcnt" || op.name=="s_nop" || + (op.enc==Encoding::Mubuf && op.name.find("load")!=Name::npos) || + (op.enc==Encoding::Image && (op.op==0 || op.op==1 || op.op==36 || op.op==39)))) + refuse(op.pc,"unsupported operation inside a vertex EXEC scalar-tail region"); + const unsigned width = scalar_width(op); + if (width && op.dst < parent+2 && parent < op.dst+width) + refuse(op.pc,"vertex scalar-tail region overwrites its saved EXEC"); + if (j<join) + for (unsigned r=op.dst; r<op.dst+width && r<128; ++r) modified.insert(r); + } + const unsigned condition = 1024 + mask.pc; + branch_saves.emplace(mask.pc,condition); + lane_branches.emplace(skip.pc,std::make_pair(condition,false)); + if (code[anchor].dst == parent && !branch_saves.count(code[anchor].pc) && !saves.count(code[anchor].pc)) + vertex_anchors.insert(code[anchor].pc); + if (has_else) { + // Only the vector prefix obeys complementary EXEC. The wave + // runs the scalar tail even when all ELSE lanes are disabled. + then_fallthroughs.emplace(code[join-1].pc,code[tail].pc); + branch_merges.emplace(inv.pc,condition); + expired[inv.pc].insert(modified.begin(),modified.end()); + } + branch_merges.emplace(code[tail].pc,condition); + if (tail != end) scalar_tail_merges.insert(code[tail].pc); + expired[code[tail].pc].insert(modified.begin(),modified.end()); + branch_merges.emplace(restore.pc,condition); + } + } + explicit GraphicsMaskRegions(Program &program, bool wave32, bool vertex) { + std::multimap<unsigned, unsigned> entries; + for (const auto &i : program.code) + if (i.branch()) entries.emplace(i.target(), i.pc); + // Only carry SCC into a full numeric mask if its reaching producer + // compares ordinary scalar operands, with no join or intervening + // scalar writer. Per-lane predicates cannot establish those 64 bits. + bool scalar_test = false; + auto scalar_data = [](unsigned r) { return r <= 105 || (r >= 128 && r <= 248) || r == 255; }; + for (const auto &i : program.code) { + if (entries.count(i.pc)) scalar_test = false; + if (i.name == "s_cselect_b64" && scalar_test) scalar_mask_selects.insert(i.pc); + if (i.enc == Encoding::Sopc) + scalar_test = (i.name.substr(0,6) == "s_cmp_" || i.name.substr(0,8) == "s_bitcmp") && + scalar_data(i.src[0]) && scalar_data(i.src[1]); + else if (i.branch() || i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk) + scalar_test = false; + } + // Follow the selected lane's bit from a compare into an explicit + // SGPR pair, through VCC intersections, up to its AND_SAVEEXEC. + // Restrict the chain to one block and the same reaching EXEC. + if (vertex && !wave32) { + const auto &code = program.code; + for (size_t j=0; j<code.size(); ++j) { + const auto &cmp = code[j]; + if (cmp.enc != Encoding::Vopc || cmp.dst > 104 || (cmp.dst & 1) || + cmp.name.substr(0,6) != "v_cmp_" || cmp.name.find("class") != Name::npos || + cmp.clamp || cmp.scale || cmp.subword) continue; + unsigned bit = 1024 + cmp.pc; + std::map<unsigned,unsigned> chain; + for (size_t k=j+1; k<code.size() && !entries.count(code[k].pc); ++k) { + const auto &op = code[k]; + if (op.name == "s_and_b64" && op.dst == cmp.dst && + op.src[0] == 106 && op.src[1] == cmp.dst) { + chain[op.pc] = bit; + bit = 1024 + op.pc; + continue; + } + if (op.name == "s_and_saveexec_b64" && op.src[0] == cmp.dst) { + vertex_mask_compares.insert(cmp.pc); + chain[op.pc] = bit; + mask_inputs.insert(chain.begin(),chain.end()); + break; + } + const auto width = scalar_width(op); + auto clobbers = [&](unsigned r) {return width && op.dst < r+2 && r < op.dst+width;}; + if (op.branch() || clobbers(126) || clobbers(cmp.dst) || carry_destination(op) || + op.name.find("saveexec") != Name::npos) break; + } + } + } + for (size_t k = 0; k + 2 < program.code.size(); ++k) { + auto save = program.code[k]; + const auto mov = wave32 ? "s_mov_b32" : "s_mov_b64"; + const auto &narrow = program.code[k + 1]; + const bool split = save.name == mov && save.src[0] == 126 && + narrow.name == (wave32 ? "s_and_b32" : "s_and_b64") && narrow.dst == 126 && + ((narrow.src[0] == 126 && narrow.src[1] == 106) || (narrow.src[0] == 106 && narrow.src[1] == 126)); + const bool cmpx = !wave32 && save.enc == Encoding::Vopc && + save.name.substr(0,7) == "v_cmpx_" && save.dst == 126 && !save.subword && !save.scale && + !save.clamp && save.name.find("class") == Name::npos; + // Input is an individual bit proven by an earlier scalar mask + // intersection. Its numeric SGPR pair remains inaccessible. + const bool from_mask = mask_inputs.count(save.pc) && save.dst == 126; + const bool saved_mask = mask_inputs.count(save.pc) && save.name == "s_and_saveexec_b64"; + bool refilter = false; + if (!vertex && !from_mask && save.name==(wave32 ? "s_and_b32" : "s_and_b64") && save.dst==126 && + ((save.src[0]==106 && save.src[1]==126) || (save.src[0]==126 && save.src[1]==106)) && + narrow.branch() && narrow.op==8 && narrow.target()>narrow.next) { + // A material lookup can reuse an earlier saved EXEC across + // independent arithmetic, including reads of other SGPRs. + const auto &other=program.code[program.at.at(narrow.target())]; + if (other.name==(wave32 ? "s_andn2_b32" : "s_andn2_b64") && other.dst==126 && other.src[1]==126 && + other.src[0]<=(wave32 ? 105u : 104u) && (wave32 || !(other.src[0]&1))) { + const unsigned parent=other.src[0]; + for (size_t j=k; j && !entries.count(program.code[j].pc);) { + const auto &prev=program.code[--j]; + if (prev.name==mov && ((prev.dst==126 && prev.src[0]==parent) || + (prev.dst==parent && prev.src[0]==126))) { + save.dst=parent; + refilter=true; + break; + } + const auto n=scalar_width(prev); + auto changes=[&](unsigned r) {return n && prev.dst<r+(wave32 ? 1 : 2) && r<prev.dst+n;}; + if (prev.branch() || changes(126) || changes(parent) || carry_destination(prev) || + prev.name.find("exec")!=Name::npos) break; + } + } + } + if (!cmpx && !from_mask && !saved_mask && !split && !refilter && (save.name != (wave32 ? "s_and_saveexec_b32" : "s_and_saveexec_b64") || + save.src[0] != 106)) continue; + auto &skip = program.code[k + 1 + split]; + if (!skip.branch() || skip.op != 8 || skip.target() <= skip.next) continue; + const auto join = program.at.at(skip.target()); + const auto &capture = program.code[join]; + if (!vertex && cmpx) { + // GFX10 CMPX updates EXEC, not VCC. A lane-local pixel arm + // followed by the exact restore can branch on its own bit + // when no downstream observer needs helpers or a wave vote. + // An ordinary image_load has no implicit derivatives. Keep + // implicit sampling, wave reads and writes outside this rule. + if (capture.name != mov || capture.dst != 126 || + std::any_of(program.code.begin(), program.code.begin() + k, [](const Inst &i) { + return i.branch() || i.name.find("wqm") != Name::npos; + }) || + !preserves_exec(program, 0, k) || + !std::all_of(program.code.begin() + k + 2, program.code.begin() + join, [](const Inst &i) { + return local_alu(i) || (i.enc == Encoding::Image && i.op == 0) || + (i.enc == Encoding::Smem && i.dst + memory_count(i) <= 106) || + (i.enc == Encoding::Vopc && i.dst == 106 && i.name.substr(0,6) == "v_cmp_") || + i.name == "s_waitcnt" || i.name == "s_nop"; + }) || !std::all_of(program.code.begin() + join + 1, program.code.end(), [](const Inst &i) { + return local_alu(i) || (i.enc == Encoding::Export && ((i.a >> 4) & 63) < 8) || + i.name == "s_waitcnt" || i.name == "s_endpgm"; + })) + continue; + } + const bool captured = cmpx && capture.name == "s_and_b64" && capture.dst <= 104 && !(capture.dst & 1) && + ((capture.src[0] == 106 && capture.src[1] == 126) || (capture.src[0] == 126 && capture.src[1] == 106)); + const auto middle = join + captured; + if (middle >= program.code.size()) continue; + const auto &inverse = program.code[middle]; + if (cmpx || from_mask) { + if ((inverse.name != "s_andn2_b64" && inverse.name != mov) || inverse.dst != 126 || + inverse.src[0] > 104 || (inverse.src[0] & 1)) continue; + save.dst = inverse.src[0]; + // A dominating save or restore with no subsequent writer + // identifies the exact parent of this CMPX, including nested + // regions where the currently executing lane is already active. + bool parent = false; + for (size_t back = k; back && !entries.count(program.code[back].pc);) { + const auto &prev = program.code[--back]; + if (prev.name == mov && ((prev.dst == 126 && prev.src[0] == save.dst) || + (prev.dst == save.dst && prev.src[0] == 126))) { + parent = true; + if (prev.src[0] == 126) vertex_anchors.insert(prev.pc); + break; + } + const unsigned width = scalar_width(prev); + auto overlaps = [&](unsigned r) {return width && prev.dst < r+2 && r < prev.dst+width;}; + if (prev.branch() || overlaps(126) || overlaps(save.dst) || carry_destination(prev) || + prev.name.find("saveexec") != Name::npos) break; + } + if (!parent || (captured && capture.dst == save.dst)) continue; + } + if (save.dst > (wave32 ? 105u : 104u) || (!wave32 && (save.dst & 1))) continue; + const bool two_arms = inverse.name == (wave32 ? "s_andn2_b32" : "s_andn2_b64") && + inverse.dst == 126 && inverse.src[0] == save.dst && inverse.src[1] == 126; + if (two_arms && middle + 1 >= program.code.size()) continue; + auto &else_skip = program.code[two_arms ? middle + 1 : middle]; + if (two_arms && (!else_skip.branch() || else_skip.op != 8 || else_skip.target() <= else_skip.next)) continue; + const auto end = two_arms ? program.at.at(else_skip.target()) : middle; + const auto &restore = program.code[end]; + if (restore.name != mov || restore.dst != 126 || restore.src[0] != save.dst) continue; + const auto begin = k + 2 + split; + // For a VS with control flow inside the masked region, keep a + // real lane branch. Victory 9376fd6 ir.rs::without_skips and + // gfx2hlsl.py's EXECZ analysis both require that scalar effects + // of a skipped arm cannot escape. Here the branch guards reads + // and the merge invalidates scalar definitions from either arm. + // A pixel material selection can load different scalar records on the + // two sides of SAVEEXEC. The loads are read-only, and each invocation + // needs only the VGPR values selected by its own bit after reconvergence. + bool pixel_records = !vertex && two_arms && !cmpx && !from_mask && !saved_mask && !split; + bool has_scalar_load = false; + for (size_t j=begin; pixel_records && j<end; ++j) { + if (j==middle || j==middle+1) continue; + const auto &v=program.code[j]; + const bool load=v.enc==Encoding::Smem && v.op>=8 && v.dst+memory_count(v)<=106; + has_scalar_load |= load; + pixel_records = load || local_alu(v) || v.name=="s_waitcnt" || v.name=="s_nop" || v.name=="s_clause" || + (v.name=="s_add_u32" && v.dst<=105) || + (v.enc==Encoding::Vopc && v.dst<=106 && !(v.dst&1) && v.name.substr(0,6)=="v_cmp_" && + !v.subword && !v.scale && !v.clamp && !v.dpp_control); + } + const bool branched = (pixel_records && has_scalar_load) || cmpx || from_mask || saved_mask || (vertex && std::any_of(program.code.begin()+begin,program.code.begin()+end, + [&](const Inst &i) {return i.branch() && (!two_arms || i.pc != else_skip.pc);})); + if (refilter && !(pixel_records && has_scalar_load)) continue; + if (branched) { + for (auto it = entries.upper_bound(save.pc); it != entries.end() && it->first <= restore.pc; ++it) { + const unsigned dst = it->first, src = it->second; + if (src == skip.pc || (two_arms && src == else_skip.pc)) continue; + const unsigned start = two_arms && src >= else_skip.next ? else_skip.next : skip.next; + const unsigned limit = two_arms && src < inverse.pc ? capture.pc : restore.pc; + if (src < start || src >= limit || dst < start || dst > limit || dst <= src) + refuse(dst, "branch enters or crosses a masked vertex arm"); + } + const std::set<unsigned> implicit_writes = pixel_records && has_scalar_load ? + std::set<unsigned>{128} : std::set<unsigned>{106,107,128}; + auto first_writes = implicit_writes, second_writes = implicit_writes; + for (size_t j=begin; j<end; ++j) { + const auto &v=program.code[j]; + if (two_arms && (j == middle || j == middle+1)) continue; + if ((v.branch() && (v.target() < skip.next || v.target() > restore.pc)) || + v.name == "s_endpgm" || v.enc == Encoding::Export || v.enc == Encoding::Lds || + v.enc == Encoding::Fetch || v.enc == Encoding::FixedFetch || + (v.enc == Encoding::Image && v.op != 0 && v.op != 1 && v.op != 14 && + v.op != 34 && v.op != 36 && v.op != 39 && v.op != 47 && v.op != 71) || + (v.enc == Encoding::Mubuf && v.name.find("load") == Name::npos)) + refuse(v.pc,"masked vertex arm has an unsupported exit or memory effect"); + auto &writes = two_arms && j > middle ? second_writes : first_writes; + auto record = [&](unsigned dst,unsigned width) { + if (width && dst < save.dst + (wave32 ? 1u : 2u) && save.dst < dst + width) + refuse(v.pc,"masked vertex arm overwrites its saved EXEC"); + for (unsigned x = dst; x < dst + width && x < 128; ++x) writes.insert(x); + }; + record(v.dst,scalar_width(v)); + if (auto carry = carry_destination(v)) record(*carry,2); + const auto arm_start = two_arms && j > middle ? middle+2 : begin; + if (!wave32 && v.name == "s_and_b64" && v.dst <= 104 && v.src[0] == v.dst && + v.src[1] == 126 && j > arm_start) { + const auto &cmp = program.code[j-1]; + auto uniform_source = [](unsigned s) { + return s <= 105 || (s >= 128 && s <= 248) || s == 255; + }; + if (cmp.enc == Encoding::Vopc && cmp.dst == v.dst && cmp.name.substr(0,6) == "v_cmp_" && + cmp.name.find("class") == Name::npos && !cmp.subword && !cmp.clamp && !cmp.scale && + uniform_source(cmp.src[0]) && uniform_source(cmp.src[1]) && !entries.count(v.pc) && + preserves_exec(program,arm_start,j-1)) { + vertex_mask_compares.insert(cmp.pc); + mask_inputs[v.pc] = 1024 + cmp.pc; + uniform_mask_tests.insert(v.pc); + } + } + } + if (two_arms && !preserves_exec(program,begin,join)) + refuse(capture.pc, captured ? "VCC capture requires the reaching CMPX mask on every path" : + "vertex ELSE requires its THEN mask on every path"); + if (captured) { + if (!two_arms) refuse(capture.pc,"VCC capture requires a matching ELSE and restore"); + const unsigned bit = 1024 + capture.pc; + captures.emplace(capture.pc, MaskCapture{skip.pc,bit}); + // Captured pair is numeric poison. A following AND with + // VCC may feed another EXEC-only arm through its bit. + branch_merges.emplace(capture.pc,1024 + save.pc); + if (end+3 < program.code.size() && !second_writes.count(capture.dst) && + !second_writes.count(capture.dst+1)) { + const auto &cmp = program.code[end+1], &andv = program.code[end+2], &act = program.code[end+3]; + if (cmp.enc == Encoding::Vopc && cmp.dst == 106 && andv.name == "s_and_b64" && + andv.dst == capture.dst && andv.src[0] == 106 && andv.src[1] == capture.dst && + act.name == "s_and_b64" && act.dst == 126 && act.src[0] == capture.dst && + act.src[1] == 126 && !entries.count(cmp.pc) && !entries.count(andv.pc) && !entries.count(act.pc)) { + mask_inputs[andv.pc] = bit; + mask_inputs[act.pc] = 1024 + andv.pc; + } + } + } + // Unique virtual register; no guest write aliases it. + const unsigned condition = 1024 + save.pc; + branch_saves.emplace(save.pc,condition); + lane_branches.emplace(skip.pc,std::make_pair(condition,false)); + if (split) skip_proven(program.code[k+1]); + if (two_arms) { + branch_merges.emplace(inverse.pc, condition); + if (pixel_records && has_scalar_load) { + // These two straight-line arms partition exactly the saved + // coverage. A lane completing THEN goes straight to the + // join. A lane entering ELSE must execute its record load. + then_fallthroughs.emplace(program.code[middle-1].pc,restore.pc); + skip_proven(else_skip); + } else { + lane_branches.emplace(else_skip.pc,std::make_pair(condition,true)); + } + expired[inverse.pc].insert(first_writes.begin(),first_writes.end()); + } + branch_merges.emplace(restore.pc, condition); + expired[restore.pc].insert(first_writes.begin(),first_writes.end()); + expired[restore.pc].insert(second_writes.begin(),second_writes.end()); + continue; // inner structured regions still need classification + } + for (auto it = entries.upper_bound(save.pc); it != entries.end() && it->first <= restore.pc; ++it) + if (it->second != skip.pc && (!two_arms || it->second != else_skip.pc)) + refuse(it->first, "branch enters a masked graphics region"); + for (size_t j = k + 2 + split; j < end; ++j) { + const auto &body = program.code[j]; + if (two_arms && (j == middle || j == middle + 1)) continue; + if (body.pc != program.code[j - 1].next || body.next != program.code[j + 1].pc || + !(local_alu(body) || body.name == "s_waitcnt" || body.name == "s_nop" || + (!vertex && body.name == "buffer_atomic_add" && !(body.a & 0x2000)) || + (body.enc == Encoding::Image && body.op == 0x27))) + refuse(body.pc, "masked graphics region requires lane-local vector arithmetic"); + } + saves.insert(save.pc); + restores.insert(restore.pc); + if (split) skip_proven(program.code[k + 1]); + skip_proven(skip); + if (two_arms) { + complements.insert(inverse.pc); + skip_proven(else_skip); + } + k = end; + } + // GFX10 CMPX changes EXEC alone. With no wave-wide skip these arms + // still partition a proven enclosing mask. No entry may bypass CMPX. + const auto &code = program.code; + for (size_t k = 0; k < code.size(); ++k) { + const auto &start = code[k]; + auto restore_mask = [wave32](const Inst &i) { + return i.dst == 126 && ((wave32 && i.name == "s_mov_b32" && i.src[0] <= 105) || + (i.name == "s_mov_b64" && i.src[0] <= 104 && !(i.src[0] & 1))); + }; + if (!restore_mask(start)) continue; + size_t end = k + 1; + bool sampled = false; + for (; end < code.size(); ++end) { + const auto &i = code[end]; + if (i.enc == Encoding::Image && (i.op == 0 || (i.op >= 0x20 && i.op <= 0x3f))) sampled = true; + else if (i.name != "s_waitcnt" && i.name != "s_nop") break; + } + if (!sampled || end == code.size() || !restore_mask(code[end]) || code[end].src[0] == start.src[0]) continue; + auto entry = entries.upper_bound(start.pc); + if (entry != entries.end() && entry->first <= code[end].pc) continue; + sample_begins.insert(start.pc); + sample_ends.insert(code[end].pc); + k = end; + } + for (size_t k = 0; !wave32 && k < code.size(); ++k) { + const auto &cmp = code[k]; + if (cmp.enc != Encoding::Vopc || cmp.name.substr(0,7) != "v_cmpx_" || + cmp.dst != 126 || cmp.scale || cmp.clamp || cmp.subword) continue; + auto local = [&](const Inst &i) { + return local_alu(i) || (i.enc == Encoding::Vopc && i.dst == 106 && + i.name.substr(0,6) == "v_cmp_" && !i.clamp && !i.scale && !i.subword && + i.name.find("class") == Name::npos); + }; + size_t mid = k + 1; + while (mid < code.size() && local(code[mid])) ++mid; + if (mid == code.size()) continue; + const auto &inverse = code[mid]; + if (inverse.name != "s_andn2_b64" || inverse.dst != 126 || inverse.src[0] > 104 || + (inverse.src[0] & 1) || inverse.src[1] != 126) continue; + size_t end = mid + 1; + while (end < code.size() && local(code[end])) ++end; + if (end == code.size()) continue; + const auto &restore = code[end]; + if (restore.name != "s_mov_b64" || restore.dst != 126 || restore.src[0] != inverse.src[0]) continue; + auto entry = entries.upper_bound(cmp.pc); + if (entry != entries.end() && entry->first <= restore.pc) + refuse(entry->first,"branch enters a CMPX region"); + if (vertex) { + // Both arms contain only vector instructions. Each VS + // invocation reaches this point with its own enclosing bit + // set. Prove the complement uses that same saved EXEC. + size_t anchor = k; + while (anchor && (code[anchor-1].name == "s_waitcnt" || code[anchor-1].name == "s_nop")) + --anchor; + if (!anchor) continue; + const auto &save = code[anchor-1]; + const auto entrant = entries.upper_bound(save.pc); + if (save.name != "s_mov_b64" || save.src[0] != 126 || save.dst != inverse.src[0] || + (entrant != entries.end() && entrant->first <= cmp.pc)) continue; + vertex_anchors.insert(save.pc); + vertex_partitions.insert(cmp.pc); + } + cmpx_starts.insert(cmp.pc); + enclosing_mask.emplace(cmp.pc,inverse.src[0]); + complements.insert(inverse.pc); + restores.insert(restore.pc); + k = end; + } + // A second compare may target an SGPR mask and be ORed with VCC. + // Each arm is a straight-line region. Conditional SMEM results are + // usable within their arm only; poison them before lowering its join. + for (size_t k = 0; k + 4 < program.code.size(); ++k) { + auto &code = program.code; + const auto &cmp = code[k], &combine = code[k+1], &active = code[k+2]; + auto &skip = code[k+3]; + if (wave32 || cmp.enc != Encoding::Vopc || cmp.name.substr(0,6) != "v_cmp_" || + cmp.dst > 104 || (cmp.dst & 1) || cmp.subword || cmp.clamp || cmp.scale || + combine.name != "s_or_b64" || combine.src[0] != 106 || combine.src[1] != cmp.dst || + combine.dst != cmp.dst || active.name != "s_and_b64" || active.dst != 126 || + active.src[0] != cmp.dst || active.src[1] != 126 || !skip.branch() || skip.op != 8 || + skip.target() <= skip.next) continue; + const size_t mid = program.at.at(skip.target()); + if (mid + 1 >= code.size()) continue; + const auto &inverse = code[mid]; + auto &skip_else = code[mid+1]; + if (inverse.name != "s_andn2_b64" || inverse.dst != 126 || inverse.src[0] > 104 || + (inverse.src[0] & 1) || inverse.src[1] != 126 || !skip_else.branch() || + skip_else.op != 8 || skip_else.target() <= skip_else.next) continue; + const size_t end = program.at.at(skip_else.target()); + const auto &restore = code[end]; + if (restore.name != "s_mov_b64" || restore.dst != 126 || restore.src[0] != inverse.src[0]) continue; + for (auto it = entries.upper_bound(cmp.pc); it != entries.end() && it->first <= restore.pc; ++it) + if (it->second != skip.pc && it->second != skip_else.pc) + refuse(it->first, "branch enters a partitioned EXEC region"); + for (auto [begin, limit] : {std::pair{k+4,mid}, std::pair{mid+2,end}}) { + unsigned saved = UINT_MAX; + auto &dead = expired[code[limit].pc]; + for (size_t j = begin; j < limit; ++j) { + const auto &i = code[j]; + if (i.next != code[j+1].pc) refuse(i.pc,"noncontiguous EXEC region"); + if (local_alu(i) || i.name == "s_waitcnt" || i.name == "s_nop" || + (i.enc == Encoding::Image && i.op == 0x27)) continue; + unsigned width = 0; + if (i.enc == Encoding::Smem) { + width = memory_count(i); + } else if (i.name == "s_and_saveexec_b64" && saved == UINT_MAX && + i.src[0] <= 104 && !(i.src[0] & 1) && !(i.dst & 1)) { + saved = i.dst; inner_saves.insert(i.pc); width = 2; + } else if (i.name == "s_or_saveexec_b64" && i.src[0] == saved && !(i.dst & 1)) { + saved = UINT_MAX; inner_restores.insert(i.pc); width = 2; + } else refuse(i.pc,"unsupported operation inside partitioned EXEC"); + if (i.dst + width > 106 || + (i.dst < inverse.src[0]+2 && inverse.src[0] < i.dst+width) || + (saved != UINT_MAX && i.enc == Encoding::Smem && i.dst < saved+2 && saved < i.dst+width)) + refuse(i.pc,"clobbered enclosing EXEC mask"); + for (unsigned r = i.dst; r < i.dst + width; ++r) dead.insert(r); + } + if (saved != UINT_MAX) refuse(code[limit].pc, "unbalanced inner EXEC"); + } + compares.insert(cmp.pc); unions.insert(combine.pc); intersections.insert(active.pc); + enclosing_mask.emplace(active.pc,inverse.src[0]); + complements.insert(inverse.pc); restores.insert(restore.pc); + skip_proven(skip); skip_proven(skip_else); + k = end; + } + if (vertex && !wave32) vertex_scalar_tails(program,entries); + if (!vertex && !wave32) pixel_class_arms(program,entries); + } +}; +std::map<unsigned, GraphicsBlock> graphics_blocks(const Program &program, const GraphicsMaskRegions ®ions) { + std::set<unsigned> leaders{0}; + for (auto edge : regions.then_fallthroughs) leaders.insert(edge.second); + for (const auto &i : program.code) { + if (!i.branch()) + continue; + if (i.op != 2 && (i.op < 4 || i.op > 7) && !regions.lane_branches.count(i.pc)) { + const auto k = program.at.at(i.pc); + if (k && (i.op == 8 || i.op == 9)) { + const auto &writer = program.code[k - 1]; + if (writer.next == i.pc && writer.dst == 126 && + (writer.name == "s_wqm_b32" || writer.name == "s_wqm_b64")) + refuse(i.pc, "WQM branch on a wave mask needs the complete guest vote or a quad-local continuation"); + } + refuse(i.pc, "graphics branch on a wave mask"); + } + leaders.insert(i.target()); + if (i.op != 2) + leaders.insert(i.next); + } + std::map<unsigned, GraphicsBlock> blocks; + for (auto it = leaders.begin(); it != leaders.end(); ++it) { + const auto next = std::next(it); + size_t end = next == leaders.end() ? program.code.size() : program.at.at(*next); + auto &block = blocks.emplace(*it, GraphicsBlock{program.at.at(*it), end}).first->second; + const auto &last = program.code[end - 1]; + if (last.branch()) + block.successors.push_back(last.target()); + if (last.name != "s_endpgm" && (!last.branch() || (last.op != 2 && last.target() != last.next))) + block.successors.push_back(regions.then_fallthroughs.count(last.pc) ? + regions.then_fallthroughs.at(last.pc) : last.next); + } + for (const auto &[label, block] : blocks) + for (auto next : block.successors) + ++blocks.at(next).predecessors; + return blocks; +} + +struct GraphicsEdge { + unsigned from; + std::map<unsigned, string> values; + std::set<unsigned> written; + std::map<unsigned, GraphicsStage::Interpolation> partial; + std::map<unsigned, unsigned> exports; +}; + +void join_graphics(GraphicsStage &g, std::vector<GraphicsEdge> &edges, const GraphicsMaskRegions ®ions) { + auto &alu = g.alu; + alu.guarded_ij.clear(); + if (edges.size() == 1) { + auto &edge = edges.front(); + alu.graphics_registers = std::move(edge.values); + g.overwritten_inputs = std::move(edge.written); + g.partial = std::move(edge.partial); + g.exported = std::move(edge.exports); + return; + } + alu.graphics_registers.clear(); + g.partial.clear(); + g.exported = edges.front().exports; + g.overwritten_inputs.clear(); + for (const auto &edge : edges) { + if (edge.exports != g.exported) + refuse(g.pc, "inconsistent graphics exports at branch join"); + g.overwritten_inputs.insert(edge.written.begin(), edge.written.end()); + } + for (const auto &[reg, part] : edges.front().partial) { + bool same = std::all_of(edges.begin() + 1, edges.end(), [&](const auto &edge) { + auto it = edge.partial.find(reg); + if (it == edge.partial.end()) + return false; + const auto &v = it->second; + return v.attribute == part.attribute && v.channel == part.channel && v.source == part.source && + v.mode == part.mode; + }); + if (same) + g.partial.emplace(reg, part); + } + DxilModule::InputMask control_inputs; + if (auto merge = regions.branch_merges.find(g.pc); merge != regions.branch_merges.end()) { + for (const auto &edge : edges) + control_inputs |= alu.ir.dependencies[edge.values.at(merge->second)]; + } + for (unsigned r : g.overwritten_inputs) { + if (g.partial.count(r)) + continue; + string first, incoming; + bool same = true, defined = true; + for (const auto &edge : edges) { + auto it = edge.values.find(r); + const string absent; + const auto &value = it != edge.values.end() ? it->second + : edge.written.count(r) ? absent + : g.incoming_input(r); + if (value.empty()) { + defined = false; + break; + } + if (incoming.empty()) + first = value; + else { + same &= value == first; + incoming += ", "; + } + incoming += "[ " + value + ", %g" + to_string(edge.from) + " ]"; + } + alu.graphics_registers[r] = !defined ? string{} : same ? first : alu.ir.value("phi i32 " + incoming); + if (defined && !same) + alu.ir.dependencies[alu.graphics_registers[r]] |= control_inputs; + } +} + +// A loop may consume a VGPR defined on a backedge. Give each requested +// block-entry value a name, then populate its phi once all exits are known. +// Only registers actually read through a block boundary acquire phis. +template <class EmitInstruction> +void emit_graphics_loops(GraphicsStage &g, const Program &program, const std::map<unsigned, GraphicsBlock> &blocks, + EmitInstruction emit) { + auto &alu = g.alu; + auto &ir = alu.ir; + using Values = std::map<unsigned, string>; + using Entry = std::pair<unsigned, unsigned>; + std::map<unsigned, std::vector<unsigned>> preds; + std::map<unsigned, Values> exits; + std::map<unsigned, string> body, phis; + std::set<Entry> requested; + std::deque<Entry> pending; + std::vector<string> predicates; + std::optional<std::map<unsigned, unsigned>> exports; + auto initial = alu.graphics_registers; + auto entry_input = alu.graphics_input; + std::ostringstream prologue; + prologue.swap(ir.body); + ir.loop_dependencies = true; + auto phi = [&](unsigned block, unsigned reg) { + Entry key{block, reg}; + if (requested.insert(key).second) + pending.push_back(key); + return "%p" + to_string(block) + "r" + to_string(reg); + }; + for (const auto &[label, block] : blocks) + for (auto target : block.successors) + preds[target].push_back(label); + for (const auto &[label, block] : blocks) { + g.exported.clear(); + g.partial.clear(); + g.overwritten_inputs.clear(); + alu.graphics_registers.clear(); + alu.graphics_input = [&, label](unsigned r) { + if (g.partial.count(r)) + refuse(g.pc, "intermediate interpolation value consumed in loop"); + return phi(label, r); + }; + for (size_t k = block.begin; k < block.end; ++k) { + const auto &i = program.code[k]; + if (i.branch() || i.name == "s_endpgm") + continue; + if (i.enc == Encoding::Export && !block.successors.empty()) + refuse(i.pc, "looping graphics shader exports before its exit block"); + if ((i.enc == Encoding::Interp || i.enc == Encoding::Fetch) && (label || !preds[label].empty())) + refuse(i.pc, "looping graphics shader uses an entry input operation after a branch"); + emit(i, program.before[k]); + } + if (!g.partial.empty()) + refuse(label, "interpolation pair crosses a loop block boundary"); + const auto &last = program.code[block.end - 1]; + if (block.successors.empty()) { + if (g.exported.empty() || (!g.pixel && !g.exported.count(12)) || (exports && *exports != g.exported)) + refuse(last.pc, "inconsistent loop exit exports"); + exports = g.exported; + ir.body << " br label %graphicsEnd\n"; + } else if (block.successors.size() == 1) { + ir.body << " br label %g" << block.successors.front() << "\n"; + } else { + auto cond = alu.cmp((last.op & 1) ? "ne" : "eq", alu.read(last.op >= 6 ? 106 : 128), "0"); + predicates.push_back(cond); + ir.body << " br i1 " << cond << ", label %g" << last.target() << ", label %g" << last.next << "\n"; + } + exits.emplace(label, std::move(alu.graphics_registers)); + body.emplace(label, ir.body.str()); + ir.body.str({}); + } + if (!exports) + refuse(0, "graphics loop has no reachable exit"); + alu.graphics_input = std::move(entry_input); + ir.body.swap(prologue); + g.partial.clear(); + while (!pending.empty()) { + auto [label, reg] = pending.front(); + pending.pop_front(); + auto name = phi(label, reg); + string incoming; + auto add = [&](const string &v, const string &from) { + if (v.empty()) + refuse(label, "graphics register undefined on an incoming loop edge"); + if (!incoming.empty()) + incoming += ", "; + incoming += "[ " + v + ", %" + from + " ]"; + if (!v.empty() && v.front() == '%') + ir.consumers[v].push_back(name); + }; + if (label == 0) { + auto value = initial.find(reg); + if (value == initial.end()) + value = initial.emplace(reg, g.input(reg)).first; + add(value->second, "entry"); + } + for (unsigned pred : preds[label]) { + const auto &values = exits.at(pred); + auto value = values.find(reg); + add(value != values.end() ? value->second : phi(pred, reg), "g" + to_string(pred)); + } + phis[label] += " " + name + " = phi i32 " + incoming + "\n"; + } + ir.finish_loop_dependencies(); + for (const auto &condition : predicates) + if (ir.dependencies[condition].any()) + refuse(0, "graphics loop condition depends on a varying input"); + ir.body << " br label %g0\n"; + for (const auto &[label, code] : body) + ir.body << "g" << label << ":\n" << phis[label] << code; +} + +// An all-ones EXEC island can use VGPRs as a wave-wide register array. +// Keep separately defined guest lanes in SSA. This also works when the +// desktop PS runs on wave32 or has only a single covered quad. A varying +// pre-island pixel value has no proven address in this guest lane array. +struct GraphicsFullWave { + DirectCompute &alu; + unsigned width; + std::optional<unsigned> saved; + using Lanes = std::vector<string>; + std::map<unsigned, Lanes> vectors; + + bool emit(const Inst &i, const Program &program) { + const bool narrow = width == 32; + const auto mov = narrow ? "s_mov_b32" : "s_mov_b64"; + if (!saved) { + if (i.name != (narrow ? "s_or_saveexec_b32" : "s_or_saveexec_b64") || i.src[0] != 193) + return false; + if (i.dst > (narrow ? 105u : 104u) || (!narrow && (i.dst & 1)) || !alu.graphics_predicate.empty()) + refuse(i.pc, "invalid full-wave EXEC save"); + auto close = std::find_if(program.code.begin()+program.at.at(i.pc)+1, program.code.end(), + [&](const Inst &j) { return j.branch() || j.name == "s_endpgm" || (j.name == mov && j.dst == 126); }); + if (close == program.code.end() || close->name != mov || close->src[0] != i.dst || + std::any_of(program.code.begin(), program.code.end(), [&](const Inst &j) { + return j.branch() && j.target() > i.pc && j.target() <= close->pc; + })) + refuse(i.pc, "full-wave EXEC island needs a matching restore in the same block"); + saved = i.dst; + alu.write(*saved, {}); + if (!narrow) alu.write(*saved+1, {}); + alu.write(128, "1"); // Nonempty EXEC after OR with all ones. + return true; + } + if (i.name == mov && i.dst == 126 && i.src[0] == *saved) { + for (const auto &[reg, values] : vectors) { + const bool uniform = std::all_of(values.begin()+1, values.end(), + [&](const string &v) { return v == values.front(); }); + alu.write(reg, uniform ? values.front() : string{}); + } + vectors.clear(); + saved.reset(); + return true; + } + if (i.subword || i.abs || i.neg || i.scale || i.clamp || (i.wide && (i.a & 0x7800u))) + refuse(i.pc, "unsupported full-wave operand modifier"); + auto scalar = [&](unsigned r) { + if (r >= 256 || r == *saved || (!narrow && r == *saved+1)) + refuse(i.pc, "full-wave source needs the original pixel lane values"); + if (r == 126 || (!narrow && r == 127)) return to_string(~Word{0}); + auto value = alu.operand32(i,r); + if (alu.ir.loop_dependencies || alu.ir.dependencies[value].any()) + refuse(i.pc, "full-wave scalar source depends on pixel input"); + return value; + }; + auto constant = [&](unsigned r) { + if (r == 126 || (!narrow && r == 127)) return ~Word{0}; + if (r == *saved || (!narrow && r == *saved+1)) refuse(i.pc, "saved EXEC used as a lane selector"); + const auto value = source(i, r, program.before[program.at.at(i.pc)]); + if (value.type != Symbol::Type::constant) refuse(i.pc, "dynamic pixel wave lane selector"); + return value.value; + }; + auto lane_value = [&](unsigned r, unsigned lane) -> string { + if (r < 256) return scalar(r); + auto found = vectors.find(r); + if (found == vectors.end() || found->second[lane].empty()) + refuse(i.pc, "pixel wave register needs an unobserved source lane"); + return found->second[lane]; + }; + if (i.name == "v_writelane_b32") { + auto &lanes = vectors.try_emplace(i.dst, width).first->second; + lanes[constant(i.src[1]) & (width-1)] = scalar(i.src[0]); + return true; + } + if (i.name == "v_readlane_b32") { + if (i.dst == *saved || (!narrow && i.dst == *saved+1)) + refuse(i.pc, "lane read overwrites saved EXEC"); + alu.write(i.dst, lane_value(i.src[0],constant(i.src[1]) & (width-1))); + return true; + } + if (i.name == "v_permlane16_b32" || i.name == "v_permlanex16_b32") { + const Word selectors[]{constant(i.src[1]),constant(i.src[2])}; + const unsigned other = i.name == "v_permlanex16_b32" ? 16 : 0; + Lanes result(width); + for (unsigned lane=0; lane<width; ++lane) { + unsigned pick = (selectors[(lane >> 3) & 1] >> (4*(lane & 7))) & 15; + result[lane] = lane_value(i.src[0], ((lane & ~15u) ^ other) + pick); + } + vectors[i.dst] = std::move(result); + return true; + } + if (i.name != "v_mov_b32" && i.name != "v_min_u32" && i.name != "v_max_u32" && i.name != "v_xor_b32") + refuse(i.pc, "unsupported pixel full-wave operation " + string(i.name)); + Lanes result(width); + // Broadcasts and reductions frequently leave many equal SSA pairs. + // Reuse each expression so a wave-uniform result can leave the island. + std::map<std::pair<string,string>,string> terms; + for (unsigned lane=0; lane<width; ++lane) { + unsigned from = lane; + if (i.mirror_mask()) from ^= i.mirror_mask(); + else if (i.dpp_control) from = (lane & ~3u) | ((*i.dpp_control >> (2*(lane & 3))) & 3); + auto a = lane_value(i.src[0],from); + if (i.name == "v_mov_b32") result[lane] = a; + else { + auto b = lane_value(i.src[1],lane); + auto &term = terms[{a,b}]; + if (term.empty()) + term = i.name == "v_xor_b32" ? alu.ir.binary("xor",a,b) : a == b ? a : + alu.select(alu.cmp(i.name == "v_min_u32" ? "ult" : "ugt",a,b),a,b); + result[lane] = term; + } + } + vectors[i.dst] = std::move(result); + return true; + } +}; + +#include "gfx1013_graphics_wqm.inl" +#include "gfx1013_pixel_waterfall.inl" + +NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = 0, unsigned first_sampler = 0, + const GraphicsConstantLayout *linked_constants = nullptr, + const D3D12_ROOT_SIGNATURE_DESC1 &layout = {}, unsigned first_uav = 0, bool pixel_heap = false) { + Program program; + Emit emitter{{}, program, layout}; + emitter.srv = first_srv; + emitter.uav = first_uav; + emitter.first_sampler = first_sampler; + DirectCompute alu{emitter}; + const bool pixel = stage.stage == GpuStage::ps; + alu.graphics_interface = &stage; + alu.pixel_stage = pixel; + alu.pixel_heap_enabled = pixel_heap && pixel; + alu.perspective_center_pair = pixel && (stage.pixel_input_address & 3) == 2 && (stage.pixel_input_enable & 2) != 0; + if (pixel && !(stage.pixel_input_address >> 16)) + for (unsigned b = 0; b < 16; ++b) + if (stage.pixel_input_address & (1u << b)) + alu.pixel_entry_vgprs += b == 3 ? 3 : b < 7 ? 2 : 1; + GraphicsStage graphics{stage, alu, pixel}; + alu.untouched_pixel_register = [&](unsigned r) { return !graphics.overwritten_inputs.count(r); }; + alu.ir.track_inputs = true; + alu.graphics_input = [&](unsigned r) { return graphics.input(r); }; + State initial{}; + for (auto &s : initial) + s.type = Symbol::Type::unbound; + std::set<unsigned> assigned; + for (const auto &input : stage.inputs) { + unsigned at = input.user_data; + if (input.type == 5 && alu.pixel_heap_enabled) { + if (!(layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) || + at >= 106 || input.sgpr_count != 1 || input.offset_dwords || !assigned.insert(at).second) + refuse(0, "invalid graphics resource heap input"); + initial[at] = {Symbol::Type::table, compute_resource_heap}; + continue; + } + if (input.type == 6) { + // Offline single-stage jobs may omit the root signature. An unused + // heap does not require a binding; any actual load stays unbound. + if (!(layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED)) + continue; + if (at >= 106 || input.sgpr_count != 1 || input.offset_dwords || !assigned.insert(at).second) + refuse(0, "invalid graphics sampler heap input"); + initial[at].type = Symbol::Type::sampler_heap; + continue; + } + if (input.type == 1) { + bind_root_address(initial, input, 106); + assigned.insert(at); + assigned.insert(at + 1); + continue; + } + if (input.type != 0 && input.type != 3) + continue; + if (at >= 106 || input.root_parameter >= 16) + refuse(0, "graphics root input outside ABI"); + if (input.type == 3) { + Symbol table{Symbol::Type::table, input.root_parameter}; + if (!assigned.insert(at).second && !(initial[at] == table)) + refuse(0, "ambiguous graphics table"); + initial[at] = table; + } else { + if (!input.sgpr_count || input.sgpr_count > 32 || input.sgpr_count > 106 - at) + refuse(0, "invalid graphics constant count"); + emitter.result.constants.push_back({input.root_parameter, at, input.sgpr_count}); + for (unsigned j = 0; j < input.sgpr_count; ++j) { + if (!assigned.insert(at + j).second) + refuse(0, "overlapping graphics constants"); + initial[at + j] = {}; + } + } + } + alu.after_graphics_write = [&](unsigned r) { + // The provenance of an entry EXEC pair is valid only while both + // halves keep their reaching definition on every predecessor. + if (r <= 105) { + auto tag = 512u + (stage.wave32 ? r : (r & ~1u)); + if (alu.graphics_registers.erase(tag)) graphics.overwritten_inputs.insert(tag); + } + graphics.partial.erase(r); + graphics.overwritten_inputs.insert(r); + }; + // The PS primitive mask follows user data (the legacy graphics entry ABI). + // Keep it symbolic: desktop interpolation supplies the primitive, and a + // numeric use of this SGPR or of M0 must still be refused. + if (pixel && layout.NumParameters) { + unsigned end = 8; + for (unsigned p = 0; p < layout.NumParameters && end < 106; ++p) { + const auto ¶m = layout.pParameters[p]; + end += param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE ? 1 : + param.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? param.Constants.Num32BitValues : 2; + } + end += (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) != 0; + end += (layout.Flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) != 0; + if (end < 106 && initial[end].type == Symbol::Type::unbound && + std::none_of(stage.inputs.begin(), stage.inputs.end(), [end](auto &p) {return p.user_data >= end || p.sgpr_count > end - p.user_data;})) + initial[end].type = Symbol::Type::primitive_mask; + } + alu.initialize_constants(linked_constants); + const auto code = stage.full_precision_code(); + program = parse(code, 0, initial, true, true, !stage.wave32, stage.fixed_vertex_abi); + // A pixel discards when its invocation bit is removed from EXEC and the + // only remaining work is local ALU plus its color export. The wave-empty + // shortcut then reaches an empty EXP_NULL/end block. See Victory's pixel + // export/discard lowering and gfx2hlsl.py's masked color export. + unsigned discard_pc = UINT_MAX, combine_pc = UINT_MAX, mask_reg = UINT_MAX; + if (pixel && !stage.wave32 && program.code.size() >= 6) { + auto &ops = program.code; + const size_t null = ops.size() - 2; + const auto &output = ops[null]; + unsigned branches = 0; + for (const auto &i : ops) branches += i.branch(); + if (branches == 1 && output.enc == Encoding::Export && (output.a & 0x1fff) == 0x1890 && + ops.back().name == "s_endpgm" && ops[null-1].name == "s_endpgm") { + for (size_t n = 2; n + 1 < null; ++n) { + auto &skip = ops[n]; + const auto &remove = ops[n-1], &combine = ops[n-2]; + if (!skip.branch() || skip.op != 8 || skip.target() != output.pc || + remove.name != "s_andn2_b64" || remove.dst != 126 || remove.src[0] != 126 || + combine.name != "s_or_b64" || combine.dst > 104 || (combine.dst & 1) || + remove.src[1] != combine.dst || + !((combine.src[0] == combine.dst && combine.src[1] == 106) || + (combine.src[1] == combine.dst && combine.src[0] == 106))) continue; + const bool local = std::all_of(ops.begin()+n+1, ops.begin()+null-1, [](const auto &op) { + return GraphicsMaskRegions::local_alu(op) || op.name == "s_waitcnt" || + (op.enc == Encoding::Export && ((op.a >> 4) & 63) < 8); + }); + if (!local) break; + mask_reg = combine.dst; + combine_pc = combine.pc; + discard_pc = remove.pc; + GraphicsMaskRegions::skip_proven(skip); + program.at.erase(output.pc); + program.at.erase(ops.back().pc); + ops.resize(null); + break; + } + } + } + PixelWaterfalls waterfalls; + if (pixel) waterfalls.find(program,stage.wave32); + PixelWqm wqm; + if (pixel) { + wqm.raster_guard(program,stage.wave32); + wqm.raster_vote(program,stage.wave32); + wqm.numeric_guards(program,stage.wave32); + } + GraphicsMaskRegions regions(program, stage.wave32, !pixel); + const auto first_branch = std::find_if(program.code.begin(), program.code.end(), + [](const auto &i) { return i.branch(); }); + const bool straight = first_branch == program.code.end(); + const bool entry_backedge = std::any_of(program.code.begin(), program.code.end(), + [](const auto &i) { return i.branch() && i.target() <= i.pc; }); + const unsigned prologue_end = straight ? UINT_MAX : entry_backedge ? 0 : first_branch->pc; + // Once EXEC returns to coverage for the last time, helper results are + // unobservable if the remaining code only reads local data at explicit + // LOD, packs colors, and exports them. A forward uniform branch can + // cross this suffix without converting coverage into a wave-wide vote. + auto tail_instruction = [](const Inst &i) { + if (i.enc == Encoding::Sopp) + return !i.branch() || i.op == 2 || i.op == 4 || i.op == 5; + return i.enc == Encoding::Interp || i.enc == Encoding::Export || + (i.enc == Encoding::Smem && i.dst + memory_count(i) <= 106) || + (i.enc == Encoding::Image && i.op == 0x27) || i.name == "v_cvt_pkrtz_f16_f32"; + }; + auto last_observer = std::find_if_not(program.code.rbegin(), program.code.rend(), tail_instruction); + // In a terminal straight-line suffix, helper values cannot reach a + // neighboring lane or an externally visible store. Only covered lanes + // commit the color export. Implicit LOD and all mask reductions end it. + auto color_tail = [](const Inst &i) { + if (GraphicsMaskRegions::local_alu(i)) return true; + if (i.enc == Encoding::Export) return true; + if (i.enc == Encoding::Smem) return i.dst + memory_count(i) <= 106; + if (i.enc == Encoding::Image) return i.op == 0 || i.op == 0x27; + if (i.enc == Encoding::Sopp) + return i.name == "s_endpgm" || i.name == "s_waitcnt" || i.name == "s_clause" || i.name == "s_nop"; + if (i.enc == Encoding::Vopc) return i.dst == 106 && i.name.substr(0,6) == "v_cmp_"; + if (i.name == "s_cselect_b64" && i.dst == 106) + return (i.src[0] == 128 || i.src[0] == 193) && (i.src[1] == 128 || i.src[1] == 193); + return (i.enc == Encoding::Sopc || (i.enc == Encoding::Sop2 && i.dst < 106)) && + std::none_of(i.src.begin(),i.src.end(),[](unsigned s) { return s >= 106 && s <= 127; }); + }; + auto terminal_mask = std::find_if_not(program.code.rbegin(),program.code.rend(),color_tail); + auto lane_local = [](const Inst &i) { + if (i.enc == Encoding::Sopp) return !i.branch(); + if (i.enc == Encoding::Interp || i.enc == Encoding::Export || i.enc == Encoding::Mix) return true; + if (i.enc == Encoding::Sop1) return i.name == "s_mov_b64" || i.name == "s_mov_b32"; + if (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vop3 || i.enc == Encoding::Vopc) + return !i.dpp_control && i.name.find("lane") == Name::npos && i.name.find("mbcnt") == Name::npos; + return false; + }; + const auto last_lane_observer = std::find_if_not(program.code.rbegin(), program.code.rend(), lane_local); + // A later lane observer matters only if the new value can reach it. + // Conservatively record every potential touch up to the final observer, + // including inputs to ordinary instructions that could propagate the value. + std::array<unsigned,256> last_helper_touch{}; + if (pixel && straight && last_lane_observer != program.code.rend()) { + for (const auto &op : program.code) { + if (op.pc > last_lane_observer->pc) break; + auto touch = [&](unsigned r) { + if (r >= 256 && r < 512) last_helper_touch[r-256] = op.pc; + }; + if (op.enc == Encoding::Sopp || op.enc == Encoding::Smem || + op.enc == Encoding::Sop1 || op.enc == Encoding::Sop2) continue; + if (op.enc == Encoding::Interp) { + touch(256 + (op.a & 255)); + touch(256 + ((op.a >> 18) & 255)); + } else if (op.name == "v_readfirstlane_b32" || op.name == "v_cvt_i32_f32" || + op.name == "v_mov_b32" || op.name == "v_and_b32") { + for (auto r : op.src) touch(r); + touch(op.dst); + } else if (op.enc == Encoding::Image && !(op.a & 6) && + ((op.op == 32 && ((op.a >> 3) & 7) == 1) || + (op.op == 0 && ((op.a >> 3) & 7) == 5))) { + // Plain 2D sample or 2D-array load; no NSA address list. + unsigned count = op.op == 32 ? 2 : 3; + for (unsigned j = 0; j < count; ++j) touch(256 + (op.b & 255) + j); + for (unsigned j = 0; j < 4; ++j) touch(256 + op.dst + j); + } else { + last_helper_touch.fill(op.pc); + } + } + } + alu.helper_result_unobserved = [&](unsigned r) { + return straight && r >= 256 && r < 512 && alu.graphics_pc >= last_helper_touch[r-256]; + }; + bool whole_quad = false; + bool exact_after_wqm = false; + bool exact_sample_region = false; + std::map<unsigned,bool> saved_exec; + std::string covered; + string discard_lane; + std::string parent_predicate, arm_condition, inner_parent; + bool scalar_entry = true; + std::set<string> uniform_vector_values; + std::set<string> uniform_vcc_values; + // A slot index needs a finite material range for relocation. Track bounds + // by SSA value so SGPR/VGPR clobbers and control-flow joins cannot reuse + // a proof about an earlier definition of the same register. + struct IndexRange { unsigned first, last, zero_bits; }; + std::map<string,IndexRange> heap_ranges; + auto scalar_operand = [](unsigned s) { return s <= 105 || (s >= 128 && s <= 248) || s == 255; }; + auto covered_lane = [&] { + auto helper = alu.ir.invoke("i1","isHelperLane.i1",221,{},"nounwind readonly"); + alu.ir.dependencies[helper].set(128); + return alu.ir.value("xor i1 " + helper + ", true"); + }; + GraphicsFullWave full_wave{alu, stage.wave32 ? 32u : 64u}; + auto instruction = [&](const Inst &i, const State &state) { + const auto pc = alu.graphics_pc = graphics.pc = i.pc; + if (waterfalls.restores.count(pc)) return; + if (auto dead=waterfalls.poisoned.find(pc);dead!=waterfalls.poisoned.end()) + for (unsigned reg:dead->second) alu.write(reg,{}); + if (waterfalls.exits.count(pc)) alu.write(128,"0"); // no remaining lanes + if (auto access=waterfalls.accesses.find(pc);access!=waterfalls.accesses.end()) { + const auto &which=access->second; + auto key=alu.read(which.key); + auto range=heap_ranges.find(key); + if (range==heap_ranges.end() || (which.key_is_bytes && (range->second.zero_bits & 31)!=31)) + refuse(pc,"waterfall requires a bounded aligned material index"); + unsigned first=range->second.first, last=range->second.last; + if (which.key_is_bytes) { + key=alu.ir.binary("lshr",key,"5"); first >>= 5; last >>= 5; + } else if (last>0x07ffffffu) { + refuse(pc,"waterfall slot range crosses a 32-bit descriptor-byte wrap"); + } + const auto &descriptor=state.at(((i.b>>16)&31)*4); + if (descriptor.definition!=which.descriptor_pc || !alu.graphics_predicate.empty()) + refuse(pc,"waterfall requires the selected descriptor and its enclosing pixel coverage"); + alu.image_io(i,state,DirectCompute::PixelHeapIndex{key,first,last,true}); + return; + } + if (pixel && full_wave.emit(i,program)) return; + if (wqm.packed.count(pc) && (whole_quad || exact_after_wqm || !alu.graphics_predicate.empty())) + refuse(pc, "numeric EXEC region requires exact pixel entry coverage"); + if (pixel && wqm.emit_packed(alu,i,stage.wave32)) return; + if (wqm.filters.count(pc)) { + const auto tag=alu.graphics_registers.find(512+i.dst); + if (!whole_quad || exact_after_wqm || !alu.graphics_predicate.empty() || + (wqm.survivor.empty() && (tag==alu.graphics_registers.end() || tag->second!="0"))) + refuse(pc,"WQM coverage filter requires saved exact entry EXEC"); + const auto keep=alu.cmp("eq",alu.read(106),"0"); + const auto previous=wqm.survivor.empty() ? covered_lane() : wqm.survivor; + wqm.survivor=alu.ir.value("and i1 "+previous+", "+keep); + alu.write(i.dst,{}); if (!stage.wave32) alu.write(i.dst+1,{}); + alu.write(128,{}); + return; + } + if (auto vote=wqm.vote_masks.find(pc); vote!=wqm.vote_masks.end()) { + if (!whole_quad || exact_after_wqm || !alu.graphics_predicate.empty() || wqm.survivor.empty()) + refuse(pc,"cross-quad EXECZ mask requires whole-quad EXEC after a coverage filter"); + // Every lane of a covered quad, helpers included, is in the + // whole-quad EXEC; the filtered coverage holds only survivors. + const auto keep=alu.cmp("eq",alu.read(106),"0"); + using Source=PixelWqm::MaskSource; + if (vote->second==Source::narrowed && wqm.vote_lane.empty()) + refuse(pc,"cross-quad EXECZ mask narrowed before it is written"); + wqm.vote_lane=vote->second==Source::whole_quad ? keep : + alu.ir.value("and i1 "+(vote->second==Source::survivors ? wqm.survivor : wqm.vote_lane)+", "+keep); + alu.write(i.dst,{}); if (!stage.wave32) alu.write(i.dst+1,{}); + alu.write(128,{}); + return; + } + if (pc==wqm.vote_wqm) { + if (wqm.vote_lane.empty()) refuse(pc,"cross-quad EXECZ vote has no modelled EXEC"); + // EXEC at the branch is the WQM expansion of the mask: OR it over + // the quad (quad reads see helper lanes), then vote over the wave. + alu.ir.uses_wave=true; + auto bit=alu.ir.value("zext i1 "+wqm.vote_lane+" to i32"); + auto quad=bit; + for (unsigned op=0;op<3;++op) + quad=alu.ir.binary("or",quad, + alu.ir.invoke("i32","quadOp.i32",123,{{"i32",bit},{"i8",to_string(op)}},"nounwind")); + auto vote=alu.ir.invoke("i1","waveAnyTrue",113,{{"i1",alu.cmp("ne",quad,"0")}},"nounwind"); + alu.write(128,alu.ir.value("zext i1 "+vote+" to i32")); + return; + } + if (wqm.quad_guards.count(pc)) { + // Helpers have no input coverage bit. Broadcast the four survivor + // bits while the quad is intact. Only a terminal colour region + // proven independent across quads can use this projection. + auto bit=alu.ir.value("zext i1 "+wqm.survivor+" to i32"); + auto any=bit; + alu.ir.uses_wave=true; + for (unsigned axis=0;axis<2;++axis) { + auto peer=alu.ir.invoke("i32","quadOp.i32",123,{{"i32",any},{"i8",to_string(axis)}},"nounwind"); + any=alu.ir.binary("or",any,peer); + } + auto live=alu.cmp("ne",any,"0"); + const auto label=to_string(pc); + alu.ir.body<<" br i1 "<<live<<", label %wqmLive"<<label<<", label %wqmEmpty"<<label<<"\nwqmEmpty"<<label<<":\n"; + alu.ir.invoke("void","discard",82,{{"i1","true"}},"nounwind"); + alu.ir.body<<" ret void\nwqmLive"<<label<<":\n"; + alu.write(128,{}); // Whole-wave SCC is not the quad vote. + return; + } + if (pc==wqm.exact_restore) { + auto killed=alu.ir.value("xor i1 "+wqm.survivor+", true"); + alu.ir.invoke("void","discard",82,{{"i1",killed}},"nounwind"); + return; + } + if (i.enc == Encoding::Vopc && i.dst == mask_reg && pc < combine_pc && + i.name.substr(0,6) == "v_cmp_" && !i.subword && !i.scale && !i.clamp && !i.abs && !i.neg && + i.name.find("class") == Name::npos && alu.graphics_predicate.empty() && !whole_quad) { + auto lhs = alu.operand32(i, i.src[0]), rhs = alu.operand32(i, i.src[1]); + alu.write(i.dst, {}); alu.write(i.dst + 1, {}); + discard_lane = alu.comparison(i, lhs, rhs); + return; + } + if (pc == combine_pc) { + if (discard_lane.empty()) refuse(pc, "discard mask has no reaching lane comparison"); + discard_lane = alu.ir.value("or i1 " + discard_lane + ", " + alu.cmp("ne",alu.read(106),"0")); + alu.write(128, {}); + return; + } + if (pc == discard_pc) { + if (whole_quad || !alu.graphics_predicate.empty()) refuse(pc, "discard requires exact pixel coverage"); + alu.ir.invoke("void", "discard", 82, {{"i1", discard_lane}}, "nounwind"); + alu.write(128, {}); + return; + } + if (!discard_lane.empty() && pc < combine_pc && i.dst < 106) { + const unsigned width = i.enc == Encoding::Smem ? memory_count(i) : + i.name.find("_b64") != Name::npos || i.enc == Encoding::Vopc ? 2 : 1; + if (i.dst < mask_reg + 2 && mask_reg < i.dst + width) discard_lane.clear(); + } + + if (auto it = regions.expired.find(pc); it != regions.expired.end()) + for (auto reg : it->second) alu.write(reg, {}); + if (regions.vertex_anchors.count(pc) || regions.captures.count(pc)) { + // A single invocation observes one bit of this saved wave mask. + // Never substitute that bit for a numeric 64-bit SGPR read. + alu.write(i.dst,{}); + alu.write(i.dst+1,{}); + if (regions.captures.count(pc)) alu.write(128,{}); + return; + } + auto vertex_compare_bit = [&] { + return alu.ir.value("zext i1 " + alu.comparison(i) + " to i32"); + }; + if (auto at=regions.inverted_compare.find(pc);at!=regions.inverted_compare.end()) { + alu.write(1024+pc,alu.ir.binary("xor",alu.read(at->second),"1")); + alu.write(i.dst,{}); alu.write(i.dst+1,{}); alu.write(128,{}); + return; + } + if (regions.vertex_mask_compares.count(pc)) { + alu.write(1024+pc,vertex_compare_bit()); + alu.write(i.dst,{}); alu.write(i.dst+1,{}); + return; + } + if (auto it = regions.branch_saves.find(pc); it != regions.branch_saves.end()) { + if (!alu.graphics_predicate.empty()) + refuse(pc,"vertex EXEC branch requires an active enclosing invocation"); + string bit; + if (i.enc == Encoding::Vopc) { + bit = vertex_compare_bit(); + } else if (auto input = regions.mask_inputs.find(pc); input != regions.mask_inputs.end()) { + bit = alu.read(input->second); + } else { + bit = alu.read(106); + } + if (i.dst != 126) { + alu.write(i.dst,{}); + if (!stage.wave32) alu.write(i.dst+1,{}); + } + alu.write(128,{}); + alu.write(it->second, bit); + return; + } + if (auto input = regions.mask_inputs.find(pc); input != regions.mask_inputs.end()) { + if (regions.uniform_mask_tests.count(pc)) { + auto bit = alu.read(input->second); + if (alu.ir.dependencies[bit].any()) + refuse(pc,"non-uniform compare needs a full guest-wave SCC reduction"); + // We are inside a proven nonempty EXEC arm. Every active + // lane agrees on the comparison, so any(mask) equals it. + alu.write(i.dst,{}); alu.write(i.dst+1,{}); alu.write(128,bit); + return; + } + if (i.dst == 126 || i.name != "s_and_b64") refuse(pc,"mask-fed EXEC has no matching restore"); + auto bit = alu.ir.binary("and",alu.read(106),alu.read(input->second)); + alu.write(1024+pc,bit); + alu.write(i.dst,{}); alu.write(i.dst+1,{}); alu.write(128,{}); + return; + } + if (regions.branch_merges.count(pc) && !regions.scalar_tail_merges.count(pc)) return; + const bool cmpx = regions.cmpx_starts.count(pc) != 0; + if (cmpx || regions.compares.count(pc)) { + if (i.name.find("class") != Name::npos || + ((i.abs || i.neg) && i.name.find("_f") == Name::npos)) + refuse(pc,"unsupported partitioned compare modifiers"); + auto lhs = alu.operand32(i,i.src[0]), rhs = alu.operand32(i,i.src[1]); + arm_condition = alu.comparison(i,lhs,rhs); + if (!cmpx) { + alu.write(i.dst, {}); alu.write(i.dst+1, {}); + return; + } + } + if (regions.unions.count(pc)) { + auto vcc = alu.cmp("ne",alu.read(106),"0"); + arm_condition = alu.ir.value("or i1 " + vcc + ", " + arm_condition); + alu.write(128, {}); + return; + } + if (cmpx || regions.intersections.count(pc)) { + const auto tag = alu.graphics_registers.find(512 + regions.enclosing_mask.at(pc)); + const bool known_parent = regions.vertex_partitions.count(pc) || + (whole_quad && !exact_after_wqm && tag != alu.graphics_registers.end() && tag->second == "1"); + if (!known_parent || !alu.graphics_predicate.empty()) + refuse(pc,"unproven enclosing whole-quad EXEC"); + parent_predicate.clear(); + alu.graphics_predicate = arm_condition; + if (!cmpx) alu.write(128, {}); + return; + } + if (regions.inner_saves.count(pc)) { + const auto tag = alu.graphics_registers.find(512 + i.src[0]); + if (tag == alu.graphics_registers.end() || tag->second != "0") + refuse(pc,"inner EXEC requires saved entry coverage"); + inner_parent = alu.graphics_predicate; + auto exact = covered_lane(); + alu.graphics_predicate = alu.ir.value("and i1 " + inner_parent + ", " + exact); + alu.write(i.dst, {}); alu.write(i.dst+1, {}); alu.write(128, {}); + return; + } + if (regions.inner_restores.count(pc)) { + alu.graphics_predicate = inner_parent; + alu.write(i.dst, {}); alu.write(i.dst+1, {}); alu.write(128, {}); + return; + } + if (regions.saves.count(pc)) { + parent_predicate = alu.graphics_predicate; + arm_condition = alu.cmp("ne", alu.read(106), "0"); + alu.graphics_predicate = parent_predicate.empty() ? arm_condition : + alu.ir.value("and i1 " + parent_predicate + ", " + arm_condition); + saved_exec.erase(i.dst); + alu.write(i.dst, {}); + if (!stage.wave32) alu.write(i.dst + 1, {}); + alu.write(128, {}); + return; + } + if (regions.complements.count(pc)) { + auto other = alu.ir.value("xor i1 " + arm_condition + ", true"); + alu.graphics_predicate = parent_predicate.empty() ? other : + alu.ir.value("and i1 " + parent_predicate + ", " + other); + alu.write(128, {}); + return; + } + if (regions.restores.count(pc)) { + alu.graphics_predicate = parent_predicate; + return; + } + const bool short_mask = stage.wave32 && i.name == "s_mov_b32"; + const bool move_exec = pixel && (short_mask || i.name == "s_mov_b64") && (i.dst == 126 || i.src[0] == 126); + if (move_exec && i.dst == 126 && pc >= prologue_end && !entry_backedge && whole_quad && + alu.graphics_predicate.empty() && terminal_mask != program.code.rend() && terminal_mask->pc == pc) { + const auto tag = alu.graphics_registers.find(512 + i.src[0]); + if (tag == alu.graphics_registers.end() || tag->second != "0") + refuse(pc,"terminal pixel export requires saved entry coverage"); + return; + } + if (pixel && pc >= prologue_end && (regions.sample_begins.count(pc) || regions.sample_ends.count(pc))) { + const bool begin = regions.sample_begins.count(pc) != 0; + const auto saved = alu.graphics_registers.find(512 + i.src[0]); + if (!whole_quad || saved == alu.graphics_registers.end() || saved->second != (begin ? "0" : "1") || + (begin ? !alu.graphics_predicate.empty() : !exact_sample_region)) + refuse(pc,"unproven EXEC for a conditional sample"); + exact_after_wqm = alu.exact_pixel_entry = exact_sample_region = begin; + if (begin) { + // Run read-only sampling with the quad intact for derivatives, + // then merge only the writes made under the guest coverage. + alu.graphics_predicate = covered_lane(); + } else alu.graphics_predicate.clear(); + return; + } + if (!straight && pc >= prologue_end && exact_after_wqm && !exact_sample_region) + refuse(pc, "exact pixel mask crosses a control-flow edge"); + if (move_exec && (short_mask ? i.dst <= 105 : i.dst <= 104 && !(i.dst & 1)) && + i.src[0] == 126 && (pc < prologue_end || waterfalls.saves.count(pc))) { + saved_exec[i.dst] = whole_quad && !exact_after_wqm; + // Numeric use of either half needs actual wave-mask lowering. + alu.write(i.dst,{}); + if (!short_mask) alu.write(i.dst+1,{}); + alu.write(512+i.dst, saved_exec.at(i.dst) ? "1" : "0"); + return; + } + if (move_exec && i.dst == 126 && pc < prologue_end && saved_exec.count(i.src[0]) && + alu.graphics_registers.count(512 + i.src[0])) { + exact_after_wqm = whole_quad && !saved_exec.at(i.src[0]); + if (whole_quad && exact_after_wqm && !entry_backedge && + last_observer != program.code.rend() && pc == last_observer->pc) { + while (!alu.guarded_ij.empty()) { + auto it = alu.guarded_ij.begin(); + if (!covered.empty() && it->second.first == covered) { + alu.graphics_registers[it->first] = it->second.second; + alu.guarded_ij.erase(it); + } else { + alu.materialize_ij(it->first); + } + } + whole_quad = false; + exact_after_wqm = false; + alu.exact_pixel_entry = false; + alu.graphics_predicate.clear(); + return; + } + if (exact_after_wqm) { + if (covered.empty()) { + covered = covered_lane(); + } + alu.graphics_predicate = covered; + alu.exact_pixel_entry = true; + } else { + alu.graphics_predicate.clear(); + alu.exact_pixel_entry = false; + } + return; + } + if (i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk || + i.enc == Encoding::Smem || i.enc == Encoding::Vop3 || i.enc == Encoding::Vop1) { + // Invalidate both halves of a saved mask when scalar code reuses them. + const unsigned width = i.enc == Encoding::Smem ? memory_count(i) : + i.name.find("_b64") != Name::npos ? 2 : 1; + if (i.dst<128) + for (auto it=saved_exec.begin(); it!=saved_exec.end();) + if (i.dst<it->first+(stage.wave32 ? 1u : 2u) && it->first<i.dst+width) it=saved_exec.erase(it); + else ++it; + } + if (exact_after_wqm && i.enc != Encoding::Smem && i.enc != Encoding::Sopp && + i.enc != Encoding::Sop1 && i.enc != Encoding::Sop2 && i.enc != Encoding::Sopk && + i.enc != Encoding::Export && + !(i.name == "v_mov_b32" && i.dst >= 256 && !i.dpp_control && !i.subword) && + !(i.enc==Encoding::Image && (i.op==0 || (i.op>=0x20 && i.op<=0x3f))) && + !(i.name == "buffer_atomic_add" && !(i.a & 0x2000))) + refuse(pc,"unsupported exact-mask operation after whole-quad entry"); + if ((i.name == "s_wqm_b32" || i.name == "s_wqm_b64") && i.dst == 126 && i.src[0] == 126) { + if (!stage.wave32 && i.name == "s_wqm_b32") + refuse(pc, "whole-quad operation affects only half of the guest EXEC mask"); + if (!pixel || pc >= prologue_end || !scalar_entry || whole_quad) + refuse(pc, "whole-quad mode requires an unmodified pixel entry mask"); + whole_quad = true; + alu.graphics_registers[128] = {}; // SCC describes the physical wave mask. + return; + } + if (i.branch() || !((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Smem || + i.enc == Encoding::Sopk) && i.dst < 106) && + i.name != "v_nop" && i.name != "s_nop" && i.name != "s_clause" && + i.name != "s_setprio" && i.name != "s_inst_prefetch" && i.name != "s_waitcnt") + scalar_entry = false; + if (i.dpp_control) { + if (i.mirror_mask()) + refuse(pc, i.mirror_mask() == 7 ? "DPP half-row mirror requires a proven eight-lane pixel layout" + : "DPP row mirror requires a proven sixteen-lane pixel layout"); + // In whole-quad mode all four possible sources participate. At + // exact coverage the desktop helper's VGPR contents are unproven. + if (i.dpp_fetch_inactive && (!whole_quad || exact_after_wqm)) + refuse(pc, "DPP fetch-inactive source requires a proven whole quad"); + if (!whole_quad || exact_after_wqm) + refuse(pc, "pixel quad permutation without whole-quad entry"); + if (i.enc == Encoding::QuadCompare) { + if (!pixel || !alu.graphics_predicate.empty()) + refuse(pc,"DPP compare requires all four source lanes"); + const auto first = graphics.quad_source(i); + const auto pred = alu.comparison(i,first,alu.operand32(i,i.src[1])); + alu.write(106,alu.ir.value("zext i1 "+pred+" to i32")); + if (!stage.wave32) alu.write(107,{}); + return; + } + const auto op = alu_rules.find(i.name); + if (i.name != "v_mov_b32" && (op == alu_rules.end() || op->second.arity > 2)) + refuse(pc, "unsupported DPP arithmetic"); + if (i.enc == Encoding::Vop1 && (i.neg & 2 || i.abs & 2)) + refuse(pc, "unexpected second DPP source modifier"); + auto first = graphics.quad_source(i); + alu.arithmetic(i, state, &first); + return; + } + if (i.enc == Encoding::FixedSetup) { + if (pixel || !straight) refuse(pc,"inline vertex fetch requires a straight-line VS"); + for (unsigned r = i.dst; r < i.dst + i.op; ++r) alu.write(r, {}); + if (i.next - pc == 8 && i.op == 1) alu.write(128, {}); // BFE sets SCC. + return; + } + if (i.enc == Encoding::FixedFetch) { + if (pixel || !straight) refuse(pc,"inline vertex fetch requires a straight-line VS"); + const auto &inputs = alu.ir.inputs; + auto prior = std::find_if(inputs.begin(), inputs.end(), [&](const auto &r) { + return r.name == "X2W_RAW_VERTEX" && r.semantic_index == i.literal; + }); + unsigned row = prior != inputs.end() ? prior->row : static_cast<unsigned>(inputs.size()); + const auto id = graphics.row(true, "X2W_RAW_VERTEX", i.literal, 0, i.a ? 9 : 5, + row, (1u << i.op) - 1, 0); + for (unsigned c = 0; c < i.op; ++c) alu.write(i.dst + c, graphics.load(id, c)); + emitter.result.vertex_fetch=true; + return; + } + if (i.enc == Encoding::Fetch) { + if (pixel) + refuse(pc, "vertex fetch call in a pixel shader"); + if (std::any_of(program.code.begin(),program.code.begin()+program.at.at(pc), + [](const Inst &prefix) { return prefix.name != "v_nop"; })) + refuse(pc, "vertex fetch call outside the entry"); + // The stream fetch ABI supplies each declared input VGPR through + // the input assembler. Its return address is opaque to guest ALU. + if (stage.attributes.empty()) + refuse(pc, "vertex fetch call without fetch records"); + std::bitset<256> destinations; + for (const auto &a : stage.attributes) { + if (a.usage != 6 || !a.location || a.last_component > 3 || (a.mask >> a.last_component) != 1 || + a.location + a.last_component >= 256) + refuse(pc, "invalid vertex fetch record"); + for (unsigned j = 0; j <= a.last_component; ++j) { + if (destinations.test(a.location + j)) + refuse(pc, "overlapping vertex fetch destinations"); + destinations.set(a.location + j); + } + } + emitter.result.vertex_fetch = true; + for (unsigned r : {4u, 5u}) { + alu.graphics_registers[r] = {}; + graphics.overwritten_inputs.insert(r); + } + return; + } + if (i.enc == Encoding::Export) { + graphics.emit_export(i.a, i.b); + return; + } + if (i.enc == Encoding::Interp) { + graphics.interpolate(i.a); + return; + } + if (i.name == "s_nop" || i.name == "v_nop" || i.name == "s_setprio" || i.name == "s_clause" || i.name == "s_inst_prefetch" || + i.name == "s_waitcnt") + return; + if (i.enc == Encoding::Vopc && i.dst <= 106 && i.name.substr(0, 6) == "v_cmp_" && !i.scale && !i.clamp) { + // Keep the invocation bit for CNDMASK and predicated regions. + // A whole-wave VCC branch also requires a uniform condition. + auto pred = alu.comparison(i); + if (!alu.graphics_predicate.empty()) + pred = alu.ir.value("and i1 " + alu.graphics_predicate + ", " + pred); + auto bit = alu.ir.value("zext i1 " + pred + " to i32"); + if (i.dst == 106) alu.write(106,bit); + else { + alu.write(i.dst,{}); + if (!stage.wave32) alu.write(i.dst+1,{}); + alu.write(1024+pc,bit); + } + if (i.dst == 106 && alu.graphics_predicate.empty() && scalar_operand(i.src[0]) && scalar_operand(i.src[1]) && + alu.ir.dependencies[bit].none()) uniform_vcc_values.insert(bit); + return; + } + if (i.name == "v_cndmask_b32" && !i.abs && !i.neg && !i.scale && !i.clamp) { + if (i.wide && (i.a & 0x7800)) refuse(pc,"unsupported graphics CNDMASK operand selection"); + auto a = alu.operand32(i, i.src[0]), b = alu.operand32(i, i.src[1]); + if (i.subword) { + a = alu.subword(a, i.src_select[0], i.src_sext[0]); + b = alu.subword(b, i.src_select[1], i.src_sext[1]); + } + auto mask = alu.graphics_lane_mask(i,state,i.src[2],"unproven graphics CNDMASK source"); + alu.vector_write(i.dst, alu.place_subword(i, alu.select(alu.cmp("ne",mask,"0"), b, a))); + return; + } + if (pixel && i.name == "s_mov_b32" && i.dst == 124 && i.src[0] < 106 && + state[i.src[0]].type == Symbol::Type::primitive_mask) + return; + if (i.name == "v_readfirstlane_b32" && i.dst < 106 && i.src[0] >= 256 && + !i.subword && !i.scale && !i.clamp && !i.abs && !i.neg && alu.graphics_predicate.empty()) { + auto value = alu.read(i.src[0]); + if (!uniform_vector_values.count(value)) + refuse(pc,"graphics readfirstlane requires a wave-uniform reaching value"); + alu.write(i.dst,value); + return; + } + if (whole_quad && !exact_after_wqm && alu.graphics_predicate.empty() && + i.name == "s_and_b64" && i.dst <= 104 && !(i.dst & 1) && + ((i.src[0] == 106 && i.src[1] == 126) || (i.src[1] == 106 && i.src[0] == 126))) { + auto bit = alu.read(106); + if (!uniform_vcc_values.count(bit)) + refuse(pc,"varying VCC requires a full-wave nonzero reduction"); + // An executing invocation belongs to a nonempty guest wave. For + // a uniform comparison VCC & EXEC is nonzero iff its bit is set. + // The numeric SGPR pair still depends on the actual wave mask. + alu.write(i.dst, {}); alu.write(i.dst + 1, {}); alu.write(128,bit); + return; + } + if (i.name == "s_cselect_b64" && i.dst == 106 && + (i.src[0] == 128 || i.src[0] == 193) && (i.src[1] == 128 || i.src[1] == 193)) { + auto scc = alu.read(128); + alu.write(106, alu.select(alu.cmp("ne",scc,"0"),i.src[0] == 193 ? "1" : "0", + i.src[1] == 193 ? "1" : "0")); + alu.write(107, {}); + return; + } + if (i.name == "s_cselect_b64" && i.dst <= 104 && !(i.dst & 1) && + (i.src[0] == 128 || i.src[0] == 193) && (i.src[1] == 128 || i.src[1] == 193)) { + if (!regions.scalar_mask_selects.count(pc) || alu.ir.loop_dependencies) + refuse(pc,"full scalar mask requires a reaching scalar SCC comparison"); + auto scc = alu.read(128); + if (alu.ir.dependencies[scc].any()) + refuse(pc,"full scalar mask depends on a varying SCC"); + auto word = alu.select(alu.cmp("ne",scc,"0"),i.src[0] == 193 ? "4294967295" : "0", + i.src[1] == 193 ? "4294967295" : "0"); + alu.write(i.dst,word); alu.write(i.dst+1,word); + alu.write(1024+pc,word); + return; + } + if (((i.enc == Encoding::Sop1 || i.enc == Encoding::Sop2 || i.enc == Encoding::Sopk) && i.dst >= 106) || + i.branch() || i.enc == Encoding::Sopp || i.enc == Encoding::Lds || i.enc == Encoding::Vopc || + i.name.find("exec") != Name::npos || i.name.find("lane") != Name::npos || + i.name.find("mbcnt") != Name::npos || i.name == "v_cndmask_b32") + refuse(i.pc, "graphics wave or control-flow instruction"); + if (i.enc == Encoding::Smem || i.enc == Encoding::Mubuf) { + if (i.name.find("atomic") != Name::npos) { + // ponytail: branch splitting stays inside one guest block; general + // graphics CFG edges would need to track the new predecessor labels. + if (!pixel || i.name != "buffer_atomic_add" || (i.a & 0x2000) || !straight) + refuse(i.pc, "graphics buffer atomic requires a straight-line pixel raw DWORD add"); + if (whole_quad && !exact_after_wqm) + refuse(i.pc, "pixel atomic requires exact coverage after WQM"); + auto pred = covered_lane(); + if (!alu.graphics_predicate.empty()) + pred = alu.ir.value("and i1 " + pred + ", " + alu.graphics_predicate); + alu.buffer_atomic(i, state, pred); + return; + } + alu.memory(i, state); + if (i.name == "buffer_load_format" && (i.a & 0x3ffffu) == 0 && alu.graphics_predicate.empty()) { + // A read-only uniform table entry and the literal element zero + // supply the same bits to every active invocation. + for (unsigned n = 0; n <= (i.op & 3); ++n) { + auto value = alu.read(256 + i.dst + n); + if (alu.ir.dependencies[value].none()) uniform_vector_values.insert(value); + } + } + } else if (i.enc == Encoding::Image) { + alu.image_io(i, state); + } else { + // SGPR values and inline constants are common to the wave. + // Propagate that fact through pure VS arithmetic before a write + // can replace an overlapping source. An FMAC also reads its dst. + bool uniform_vertex = false; + auto rule = alu_rules.find(i.name); + if (!pixel && !alu.ir.loop_dependencies && alu.graphics_predicate.empty() && + !i.subword && GraphicsMaskRegions::local_alu(i) && rule != alu_rules.end()) { + auto uniform = [&](unsigned r) { + if (scalar_operand(r)) return true; + auto source = alu.graphics_registers.find(r); + return r >= 256 && source != alu.graphics_registers.end() && + uniform_vector_values.count(source->second) != 0; + }; + const bool mac = i.name == "v_fmac_f32"; + const unsigned count = mac || i.name == "v_fmamk_f32" || i.name == "v_fmaak_f32" ? 2 : rule->second.arity; + uniform_vertex = std::all_of(i.src.begin(),i.src.begin()+count,uniform) && (!mac || uniform(i.dst)); + } + // Two complementary packed FMAs under the same EXEC define + // the entire VGPR. Its incoming bits are dead when neither operation + // also reads it as an explicit operand (Victory lower.rs: mixlo/mixhi). + const bool low = i.name == "v_fma_mixlo_f16"; + if (pixel && (low || i.name == "v_fma_mixhi_f16") && alu.graphics_predicate.empty() && + !alu.graphics_registers.count(i.dst) && !graphics.partial.count(i.dst)) { + for (size_t k = program.at.at(i.pc) + 1; k < program.code.size(); ++k) { + const auto &j = program.code[k]; + if (std::find(j.src.begin(), j.src.end(), i.dst) != j.src.end()) + break; + // A scheduled FP32 FMA accesses exactly three scalar-width + // sources and one destination. It cannot change EXEC. + if ((j.name == "v_fma_f32" || j.name == "v_fma_mixlo_f16" || + j.name == "v_fma_mixhi_f16" || j.name == "v_mul_f32" || j.name == "s_waitcnt") && j.dst != i.dst) + continue; + if (j.dst == i.dst && j.name == (low ? "v_fma_mixhi_f16" : "v_fma_mixlo_f16") && + std::find(i.src.begin(), i.src.end(), i.dst) == i.src.end()) + alu.graphics_registers.emplace(i.dst, "0"); + break; + } + } + std::optional<IndexRange> heap_range; + if (pixel && !waterfalls.accesses.empty() && alu.graphics_predicate.empty() && !i.subword && + !i.abs && !i.neg && !i.clamp && !i.scale && !i.dpp_control && + (i.name=="v_and_b32" || i.name=="v_or_b32" || i.name=="v_lshlrev_b32")) { + for (unsigned n=0;n<2;++n) { + auto scalar=source(i,i.src[n],state); + if (scalar.type!=Symbol::Type::constant) continue; + unsigned c=scalar.value; + if (i.name=="v_and_b32") heap_range=IndexRange{0,c,~c}; + else if (auto in=heap_ranges.find(alu.operand32(i,i.src[1-n]));in!=heap_ranges.end()) { + const auto r=in->second; + if (i.name=="v_or_b32" && (r.zero_bits & c)==c) + heap_range=IndexRange{r.first|c,r.last|c,r.zero_bits & ~c}; + if (i.name=="v_lshlrev_b32" && n==0 && c<32 && r.last<=(UINT_MAX>>c)) + heap_range=IndexRange{r.first<<c,r.last<<c,(r.zero_bits<<c)|((1u<<c)-1)}; + } + } + } + alu.arithmetic(i, state); + if (heap_range) heap_ranges[alu.read(i.dst)]=*heap_range; + const bool uniform_conversion = pixel && straight && alu.graphics_predicate.empty() && + i.name == "v_cvt_i32_f32" && !i.dpp_control && !i.subword && i.src[0] <= 105; + if (uniform_vertex || uniform_conversion || (pixel && i.name == "v_med3_f32" && alu.graphics_predicate.empty() && + std::all_of(i.src.begin(), i.src.end(), scalar_operand))) { + auto value = alu.read(i.dst); + if (alu.ir.dependencies[value].none()) uniform_vector_values.insert(value); + } + } + }; + auto blocks = graphics_blocks(program, regions); + std::map<unsigned, std::vector<GraphicsEdge>> edges; + std::vector<unsigned> ready; + if (!blocks.at(0).predecessors) + ready.push_back(0); + std::vector<unsigned> order; + while (!ready.empty()) { + unsigned label = ready.back(); + ready.pop_back(); + order.push_back(label); + for (auto next : blocks.at(label).successors) + if (!--blocks.at(next).predecessors) + ready.push_back(next); + } + if (order.size() != blocks.size()) { + if (!regions.lane_branches.empty()) refuse(0, "masked vertex control flow requires an acyclic graph"); + emit_graphics_loops(graphics, program, blocks, instruction); + } else { + alu.ir.body << " br label %g0\n"; + std::optional<std::map<unsigned, unsigned>> final_exports; + for (unsigned label : order) { + auto &block = blocks.at(label); + alu.ir.body << "g" << label << ":\n"; + graphics.pc = label; + if (label) { + join_graphics(graphics, edges.at(label), regions); + edges.erase(label); + } + for (size_t k = block.begin; k < block.end; ++k) { + const auto &i = program.code[k]; + if (!i.branch() && i.name != "s_endpgm") + instruction(i, program.before[k]); + } + const auto &last = program.code[block.end - 1]; + alu.graphics_pc = last.pc; + if (!block.successors.empty()) { + // Each predecessor must carry the value for covered and helper + // lanes before its definitions become incoming phi operands. + while (!alu.guarded_ij.empty()) alu.materialize_ij(alu.guarded_ij.begin()->first); + } + if (block.successors.empty()) { + if (graphics.exported.empty() || (!pixel && !graphics.exported.count(12)) || + (final_exports && *final_exports != graphics.exported)) + refuse(last.pc, "incomplete or inconsistent terminal graphics exports"); + final_exports = graphics.exported; + alu.ir.body << " br label %graphicsEnd\n"; + } else if (block.successors.size() == 2) { + const auto branch = regions.lane_branches.find(last.pc); + auto condition = branch != regions.lane_branches.end() ? + alu.cmp(branch->second.second ? "ne" : "eq", alu.read(branch->second.first), "0") : + alu.cmp((last.op & 1) ? "ne" : "eq", alu.read(last.op >= 6 ? 106 : 128), "0"); + // The cross-quad EXECZ vote is uniform over the desktop wave; + // its input dependencies still reach the values merged after it. + // Wave intrinsics are undefined on helper lanes, so a helper may + // take the other edge: safe only while nothing after the branch + // reads another lane (raster_vote keeps the tail lane-local). + if (branch == regions.lane_branches.end() && alu.ir.dependencies[condition].any() && + last.pc != wqm.vote_skip) + refuse(last.pc, "graphics scalar condition depends on a varying input"); + alu.ir.body << " br i1 " << condition << ", label %g" << last.target() << ", label %g" << last.next + << "\n"; + } else + alu.ir.body << " br label %g" << block.successors.front() << "\n"; + for (size_t j = 0; j < block.successors.size(); ++j) { + auto &incoming = edges[block.successors[j]]; + if (j + 1 == block.successors.size()) + incoming.push_back({label, std::move(alu.graphics_registers), + std::move(graphics.overwritten_inputs), std::move(graphics.partial), + std::move(graphics.exported)}); + else + incoming.push_back({label, alu.graphics_registers, graphics.overwritten_inputs, graphics.partial, + graphics.exported}); + if (auto capture = regions.captures.find(block.successors[j]); capture != regions.captures.end()) { + auto &edge = incoming.back(); + auto vcc = edge.values.find(106); + const bool skip = last.pc == capture->second.skip; + if (!skip && (vcc == edge.values.end() || vcc->second.empty())) + refuse(last.pc,"missing active VCC contribution to EXEC intersection"); + edge.values[capture->second.value] = skip ? "0" : vcc->second; + edge.written.insert(capture->second.value); + } + } + } + } + emitter.result.instruction_count = static_cast<unsigned>(program.code.size()); + alu.ir.body << "graphicsEnd:\n ret void\n"; + auto copy_signature = [](const auto &rows, auto &out) { + for (const auto &r : rows) + out.push_back( + {r.name, r.semantic_index, r.row, r.first, r.width, r.component, r.used, r.kind, r.interpolation}); + }; + copy_signature(alu.ir.inputs, emitter.result.inputs); + copy_signature(alu.ir.outputs, emitter.result.outputs); + if (!pixel && emitter.uav != first_uav) alu.ir.features |= 1u << 16; // UAVsAtEveryStage + emitter.result.dxil_ir = alu.ir.finish_compute(0, 0, 0, pixel ? "ps" : "vs"); + return std::move(emitter.result); +} diff --git a/src/gfx1013_direct_mesh.inl b/src/gfx1013_direct_mesh.inl new file mode 100644 index 0000000000..df5200ac5b --- /dev/null +++ b/src/gfx1013_direct_mesh.inl @@ -0,0 +1,1122 @@ +// RDNA2 merged-wave mesh entry, GS_ALLOC_REQ and EXP encoding. The slot-57 +// exchange proof is also described in tools/startup/gfx2hlsl.py:mesh_skeleton. +// The desktop MS writes lane-indexed vertices and triangle indices directly. +NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout, + const GuestShaderStage *reflected = nullptr, + const D3D12_ROOT_SIGNATURE_DESC1 &root = {}) { + if (!layout.threads || layout.threads > 128 || !layout.max_vertices || layout.max_vertices > 256 || + !layout.max_primitives || layout.max_primitives > 256 || layout.topology != 2 || + code.empty() || code.size() % 4) + refuse(0,"unsupported mesh group, output dimensions or topology"); + Program program; + // This subset has a single forward path after the proven exchange. + // The shared ALU's SGPR provenance lookup uses the current state. + program.graphics_wave64=!layout.wave32; + program.before.emplace_back(); + for (auto &s : program.before.front()) s.type=Symbol::Type::unbound; + Emit emitter{{},program,root}; + DirectCompute alu{emitter}; + GuestShaderStage fixed_outputs{}; + fixed_outputs.output_signature.push_back({"SV_Position",0,1,3,0,15,15}); + GraphicsStage graphics{reflected ? *reflected : fixed_outputs,alu,false}; + auto &ir = alu.ir; + ir.mesh_vertices = layout.max_vertices; + ir.mesh_primitives = layout.max_primitives; + auto thread = ir.invoke("i32","flattenedThreadIdInGroup.i32",96,{},"nounwind readnone"); + const unsigned width = layout.wave32 ? 32 : 64; + const auto wave_lane = ir.binary("and",thread,to_string(width-1)); + const auto wave_number = ir.binary("lshr",thread,layout.wave32 ? "5" : "6"); + alu.graphics_input = [&](unsigned r) -> string { + refuse(alu.graphics_pc,"unproven mesh entry register " + to_string(r)); + }; + alu.after_graphics_write = [&](unsigned r) { + if (r<106) program.before.front()[r].type=alu.graphics_registers.at(r).empty() ? + Symbol::Type::unbound : Symbol::Type::unknown; + }; + auto &state=program.before.front(); + auto inputs=layout.root_inputs; + auto heap=layout.resource_heap_sgpr; + if (reflected) { + for (const auto &input : reflected->inputs) { + if (input.type==5) { + if (heap) refuse(0,"duplicate mesh resource heap"); + heap=reflected->physical_user_sgpr(input.user_data); + } + if (input.type==1) inputs.push_back({reflected->physical_user_sgpr(input.user_data),input.root_parameter,0,true}); + if (input.type==0 || input.type==3) + inputs.push_back({reflected->physical_user_sgpr(input.user_data),input.root_parameter, + input.type==0 ? input.sgpr_count : 0}); + } + } + for (const auto &input : inputs) { + const auto at=input.sgpr, param=input.root_parameter, count=input.constant_count; + if (at<8 || at>=106 || count>106-at || param>=16) + refuse(0,"mesh root input outside user SGPR range"); + if (!reflected || root.NumParameters) { + if (param>=root.NumParameters) refuse(0,"missing mesh root parameter"); + const auto &binding=root.pParameters[param]; + if (input.root_address ? binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_SRV : + count ? (binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS || + binding.Constants.Num32BitValues!=count) : + binding.ParameterType!=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + refuse(0,"mesh root parameter kind or size disagrees with entry"); + } + if (input.root_address) { + if (count || at+1>=106 || state[at].type!=Symbol::Type::unbound || state[at+1].type!=Symbol::Type::unbound) + refuse(0,"invalid mesh root address pair"); + state[at]={Symbol::Type::root_address,param,0}; + state[at+1]={Symbol::Type::root_address,param,1}; + } else if (!count) { + const Symbol table{Symbol::Type::table,param}; + if (state[at].type!=Symbol::Type::unbound && !(state[at]==table)) + refuse(0,"overlapping mesh entry table"); + state[at]=table; + } else { + for (unsigned j=0;j<count;++j) { + if (state[at+j].type!=Symbol::Type::unbound) refuse(0,"overlapping mesh entry constants"); + state[at+j]={}; + } + emitter.result.constants.push_back({param,at,count}); + } + } + if (heap) { + if (*heap<8 || *heap>=106 || state[*heap].type!=Symbol::Type::unbound) refuse(0,"invalid mesh resource heap SGPR"); + state[*heap]={Symbol::Type::table,compute_resource_heap}; + } + alu.initialize_constants(); + struct RootBits { unsigned param, dword, mask, shift; }; + std::map<string,RootBits> root_values; + std::map<unsigned,RootBits> heap_fetches; + for (const auto &block : emitter.result.constants) + for (unsigned j=0;j<block.count;++j) + root_values.emplace(alu.read(block.first_sgpr+j),RootBits{block.root_parameter,j,~0u,0}); + std::set<string> uniform_values; + string exec_value[2], wave_active, lane_active; + std::map<string,std::pair<string,string>> active_uniform, mask_uniform; + auto uniform=[&](const string &v) -> string { + if (v.empty()) return {}; + if (v.find_first_not_of("0123456789-")==string::npos || uniform_values.count(v)) return v; + auto it=active_uniform.find(v); return it==active_uniform.end() || it->second.first!=lane_active ? string{} : it->second.second; + }; + auto remember_scalar=[&](unsigned r) { + const auto it=alu.graphics_registers.find(r); + if (it!=alu.graphics_registers.end() && !it->second.empty()) uniform_values.insert(it->second); + }; + std::set<string> wave_bases, low_group, low_lane, whole_lane, linear_threads; + std::set<unsigned> partial_writes; + bool full_exec = true, allocated = false, position = false, indices = false; + std::set<unsigned> parameter_exports; + std::optional<Word> allocation_word; + unsigned vertices = 0, primitives = 0; + string vertex_count, primitive_count, export_limit; + std::map<string,unsigned> upper_bound; + auto bound=[&](const Inst &op,unsigned source) { + if (auto c=constant32(op,source)) return *c; + auto it=alu.graphics_registers.find(source); + if (it!=alu.graphics_registers.end() && upper_bound.count(it->second)) return upper_bound.at(it->second); + return ~0u; + }; + string exchanged_group; + if (layout.group_stride) { + const auto group = ir.invoke("i32","groupId.i32",94,{{"i32","0"}},"nounwind readnone"); + exchanged_group = ir.binary("mul",group,to_string(layout.group_stride)); + } + unsigned scope = 0; + auto guarded = [&](const string &limit, auto body) { + auto tag = to_string(scope++); + auto pred = alu.cmp("ult",thread,limit); + ir.body << " br i1 " << pred << ", label %mesh_write" << tag << ", label %mesh_next" << tag + << "\nmesh_write" << tag << ":\n"; + body(); + ir.body << " br label %mesh_next" << tag << "\nmesh_next" << tag << ":\n"; + }; + // Scalar forward if/else only. Keep both predecessor register files so + // a value live after the join is selected from the edge that wrote it. + struct Edge { + State symbols; + decltype(alu.graphics_registers) regs; + string group; + std::set<unsigned> partial; + }; + struct Diamond { + unsigned start, alternate, join; + Edge entry, first; + }; + std::optional<Diamond> branch; + unsigned lane_else=0; + constexpr unsigned vcc_words=0x70000000, vcc_nonempty=vcc_words+2; + std::map<string,string> mask_parent; + auto covered_by=[&](string current,const string &ancestor) { + if (ancestor.empty()) return true; + while (current!=ancestor) { + auto it=mask_parent.find(current); + if (it==mask_parent.end()) return false; + current=it->second; + } + return true; + }; + auto terminate_arm=[&](unsigned start,bool first) { + const string edge=(first ? "mesh_then_end" : "mesh_else_end")+to_string(start); + ir.body<<" br label %"<<edge<<"\n"<<edge<<":\n br label %mesh_join"<<start<<"\n"; + }; + struct MaskState { bool full; string lane,wave,lo,hi; decltype(alu.graphics_registers) regs; std::set<unsigned> partial; }; + std::map<unsigned,MaskState> saved_exec; + std::map<string,Edge> before_narrowing; + auto saved_mask=[&](unsigned source)->const MaskState * { + if (source>104 || (source&1)) return nullptr; + const auto &lo=state[source], &hi=state[source+1]; + if (lo.type!=Symbol::Type::lane_mask || hi.type!=lo.type || lo.offset || hi.offset!=1 || lo.value!=hi.value) + return nullptr; + const auto it=saved_exec.find(lo.value); return it==saved_exec.end() ? nullptr : &it->second; + }; + auto pure_lane_arm=[&](unsigned begin,unsigned end) { + for (auto at=begin;at<end;) { + const auto inst=decode(code,at,true,true); + const bool vector=inst.dst>=256 && (inst.enc==Encoding::Vop1 || inst.enc==Encoding::Vop2 || inst.enc==Encoding::Vop3); + const bool compare=inst.enc==Encoding::Vopc && inst.dst==106 && inst.name.substr(0,6)=="v_cmp_"; + const bool literal=inst.name=="s_mov_b32" && inst.dst<106 && constant32(inst,inst.src[0]); + if ((!vector && !compare && !literal && inst.name!="s_nop") || inst.next<=at || inst.next>end) + return false; + at=inst.next; + } + return true; + }; + // Prove scalar dependencies when two mutually exclusive lane arms + // gather uniform buffer records. Scalar registers execute per wave, so + // the inverse arm may observe the first arm's writes unless it defines + // them itself before first use. + struct GatherArm { std::set<unsigned> writes, inputs; }; + auto gather_arm=[&](unsigned begin,unsigned end)->std::optional<GatherArm> { + GatherArm arm; + auto use=[&](unsigned r) { if (r<=107 && !arm.writes.count(r)) arm.inputs.insert(r); }; + for (unsigned at=begin;at<end;) { + auto op=decode(code,at,true,true); + if (op.next<=at || op.next>end || op.subword || op.dpp_control) return {}; + if (op.name=="s_add_u32" && op.dst<106) { + use(op.src[0]); use(op.src[1]); arm.writes.insert(op.dst); arm.writes.insert(128); + } else if (op.enc==Encoding::Smem && op.op==12 && op.dst+16<=106) { + for (unsigned j=0;j<4;++j) use(op.src[0]+j); + use(op.b>>25); + for (unsigned j=0;j<16;++j) arm.writes.insert(op.dst+j); + } else if (op.enc==Encoding::Vopc && op.name=="v_cmp_gt_i32" && op.dst<=106 && !(op.dst&1)) { + use(op.src[0]); use(op.src[1]); arm.writes.insert(op.dst); arm.writes.insert(op.dst+1); + } else if (op.name=="v_mov_b32" && op.dst>=256) use(op.src[0]); + else if (op.name=="v_cndmask_b32" && op.dst>=256 && op.src[2]<=106) { + use(op.src[0]); use(op.src[1]); use(op.src[2]); use(op.src[2]+1); + } else if (op.name!="s_waitcnt") return {}; + at=op.next; + } + return arm; + }; + std::set<unsigned> lane_scalar_clobbers; + struct Skip { unsigned start,end; Edge entry; bool per_lane; string guard; }; + std::vector<Skip> skip_parents; + std::optional<Skip> exec_skip; + unsigned mask_generation=0x1000000; + auto merge_edges=[&](const Edge &first, const string &l, const string &r) { + auto phi=[&](const string &a,const string &b) {return ir.value("phi i32 [ "+a+", %"+l+" ], [ "+b+", %"+r+" ]");}; + std::map<unsigned,std::pair<Symbol,string>> masks; + for (unsigned reg=0;reg<=104;reg+=2) { + const auto bit=[&](const Symbol &s,const auto ®s) -> string { + if ((s.type!=Symbol::Type::lane_mask && s.type!=Symbol::Type::uniform_mask) || s.offset) return {}; + auto it=regs.find(1024+s.value);return it==regs.end() ? string{} : it->second; + }; + const auto a=bit(first.symbols[reg],first.regs), b=bit(state[reg],alu.graphics_registers); + if (a.empty() || b.empty() || first.symbols[reg]==state[reg]) continue; + if (!layout.wave32 && (first.symbols[reg+1].value!=first.symbols[reg].value || + state[reg+1].value!=state[reg].value || first.symbols[reg+1].offset!=1 || state[reg+1].offset!=1 || + first.symbols[reg+1].type!=first.symbols[reg].type || state[reg+1].type!=state[reg].type)) continue; + const auto id=mask_generation++; + masks.emplace(reg,std::make_pair(Symbol{Symbol::Type::lane_mask,id,0},a==b ? a : phi(a,b))); + } + for (const auto &[reg,v] : first.regs) alu.graphics_registers.try_emplace(reg); + for (auto &[reg,v] : alu.graphics_registers) { + const auto a=first.regs.find(reg); + if (a==first.regs.end() || a->second.empty() || v.empty()) v.clear(); + else if (a->second!=v) { + const auto av=uniform(a->second), bv=uniform(v); + v=phi(a->second,v); + if (!lane_else && !av.empty() && !bv.empty()) active_uniform[v]={lane_active,av==bv ? av : phi(av,bv)}; + } + } + for (unsigned j=0;j<state.size();++j) { + if (!(first.symbols[j]==state[j])) + state[j].type=j<106 && alu.graphics_registers.count(j) && + !alu.graphics_registers.at(j).empty() ? Symbol::Type::unknown : Symbol::Type::unbound; + } + for (const auto &[r,entry] : masks) { + state[r]=entry.first; + if (!layout.wave32) {state[r+1]=entry.first;state[r+1].offset=1;} + alu.graphics_registers[1024+entry.first.value]=entry.second; + } + if (exchanged_group!=first.group) exchanged_group.clear(); + partial_writes.insert(first.partial.begin(),first.partial.end()); + }; + auto save_edge=[&]() { return Edge{state,alu.graphics_registers,exchanged_group,partial_writes}; }; + struct Incoming { + Edge edge; + string label, lane, wave; + bool full; + }; + std::map<unsigned,std::vector<Incoming>> forward; + bool live=true; + unsigned next_edge=0; + auto arrive=[&](unsigned target) { + string label="mesh_edge"+to_string(next_edge++); + forward[target].push_back({save_edge(),label,lane_active,wave_active,full_exec}); + return label; + }; + auto restore=[&](const Edge &e) { + state=e.symbols; alu.graphics_registers=e.regs; exchanged_group=e.group; partial_writes=e.partial; + }; + unsigned pc = 0; + while (pc < code.size()) { + // All handled scalar branches are forward, so every predecessor is + // available when we reach its target. Funnel arbitrary fan-in into + // binary PHI blocks, preserving descriptor and mask provenance too. + if (!live && !forward.count(pc)) { + auto next=forward.lower_bound(pc); + if (next==forward.end()) refuse(pc,"mesh forward branch has no reachable successor"); + pc=next->first; + } + if (forward.count(pc)) { + if (live) ir.body<<" br label %"<<arrive(pc)<<"\n"; + auto inputs=std::move(forward.at(pc)); forward.erase(pc); + for (const auto &in : inputs) + if (in.full!=full_exec || in.lane!=lane_active || in.wave!=wave_active) + refuse(pc,"mesh scalar branch merges different EXEC definitions"); + restore(inputs[0].edge); + string current=inputs[0].label; + ir.body<<current<<":\n"; + for (size_t j=1;j<inputs.size();++j) { + const auto join="mesh_phi"+to_string(next_edge++); + ir.body<<" br label %"<<join<<"\n"<<inputs[j].label<<":\n br label %"<<join<<"\n"<<join<<":\n"; + const auto first=save_edge(); + restore(inputs[j].edge); + merge_edges(first,current,inputs[j].label); + current=join; + } + live=true; + } + if (exec_skip && pc==exec_skip->end) { + const auto tag=to_string(exec_skip->start); + ir.body<<" br label %mesh_done"<<tag<<"\nmesh_done"<<tag<<":\n br label %mesh_resume"<<tag + <<"\nmesh_resume"<<tag<<":\n"; + if (exec_skip->per_lane) { + // A SALU write was made by each active wave. Inactive lanes + // skipped that invocation; deny later reads of changed scalar + // definitions. Vector values keep their actual incoming edge. + for (unsigned r=0;r<=128;++r) { + auto now=alu.graphics_registers.find(r), old=exec_skip->entry.regs.find(r); + if (now!=alu.graphics_registers.end() && (old==exec_skip->entry.regs.end() || now->second!=old->second)) { + now->second.clear(); + if (r<128) state[r].type=Symbol::Type::unbound; + } + } + } + merge_edges(exec_skip->entry,"mesh_empty"+tag,"mesh_done"+tag); + exec_skip.reset(); + if (!skip_parents.empty()) { + exec_skip=std::move(skip_parents.back());skip_parents.pop_back(); + if (pc==exec_skip->end) continue; + } + } + if (branch && pc==branch->alternate) { + if (pc==branch->join || lane_else) { + branch->first=save_edge(); + terminate_arm(branch->start,true); + } + const auto &entry=branch->entry; + state=entry.symbols; + alu.graphics_registers=entry.regs; + exchanged_group=entry.group; + partial_writes=entry.partial; + ir.body<<"\nmesh_else"<<branch->start<<":\n"; + if (lane_else) { pc=lane_else; continue; } + } + if (branch && pc==branch->join) { + const auto &first=branch->first; + terminate_arm(branch->start,false); + ir.body<<"mesh_join"<<branch->start<<":\n"; + if (lane_else) { + // A scalar literal in a nonempty wave may be written even + // for its inactive lanes. Refuse later numeric use unless a + // subsequent definition overwrites it. VCC is wave-wide too. + for (unsigned r=0;r<=128;++r) { + const auto old=branch->entry.regs.find(r); + const auto differs=[&](const auto ®s) { + auto v=regs.find(r); + return v!=regs.end() && (old==branch->entry.regs.end() || v->second!=old->second); + }; + if (differs(first.regs) || differs(alu.graphics_registers)) { + alu.graphics_registers[r].clear(); + if (r<106) state[r].type=Symbol::Type::unbound; + } + } + lane_else=0; + } + merge_edges(first,"mesh_then_end"+to_string(branch->start),"mesh_else_end"+to_string(branch->start)); + for (auto r:lane_scalar_clobbers) { + alu.write(r,{}); + if (r<state.size()) state[r].type=Symbol::Type::unbound; + } + if (lane_scalar_clobbers.count(106)) { + alu.write(vcc_words,{}); alu.write(vcc_words+1,{}); alu.write(vcc_nonempty,{}); + } + lane_scalar_clobbers.clear(); + branch.reset(); + } + program.at[pc]=0; + alu.graphics_pc = pc; + const auto raw = word(code,pc); + // All paths through this diamond rendezvous exactly once. Wave zero + // writes its first lane's mesh-group identifier before the rendezvous, + // the other waves read the same LDS word after it. Only v_readfirstlane + // may use the result; v0 and the inactive lanes of v5 are not uniform. + if (raw == 0xbefe0481 && code.size()-pc >= 64) { + const Word save = word(code,pc+4), mask = word(code,pc+8); + constexpr Word tail[]{0x0f000000,0xbf850007,0x2c0a0a87,0x7e000280,0xd8340008,0x500, + 0xbfa3ffe3,0xbf8a0000,0xbf820004,0xbf8a0000,0x7e000280,0xd8d80008,0x05000000}; + bool exchange = (save & 0xff80ffff) == 0xbe80047e && (mask & 0xff80ffff) == 0x8700ff03; + for (unsigned k=0;k<std::size(tail);++k) exchange &= word(code,pc+12+4*k)==tail[k]; + const unsigned saved = (save>>16)&127, temp = (mask>>16)&127; + if (exchange && !branch && !exec_skip && full_exec && !layout.wave32 && layout.group_stride && !alu.graphics_registers.count(3) && + !alu.graphics_registers.count(261) && saved<=104 && !(saved&1) && temp<106 && + temp!=saved && temp!=saved+1) { + alu.write(saved,"1"); + alu.write(saved+1,"0"); + const auto merged = ir.binary("shl",wave_number,"24"); + alu.write(temp,merged); + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",merged,"0")+" to i32")); + if (exchanged_group.empty()) refuse(pc,"mesh exchange lost the entry group VGPR"); + exchanged_group = ir.binary("lshr",exchanged_group,"7"); + alu.write(256,{}); + alu.write(261,{}); + full_exec=false; + pc+=64; + continue; + } + } + // A wave-zero producer sends GS_ALLOC_REQ and shares its two count + // SGPRs with the other waves through LDS. Verify the complete + // sequence, including both rendezvous, every LDS offset and every + // def-use edge before replacing it with group-shared DXIL. + if (raw==0xbf8a0000 && pc+128<=code.size() && !allocated && !branch && !exec_skip && forward.empty()) { + auto w=[&](unsigned n) { return word(code,pc+4*n); }; + const unsigned wave=w(1)&127, mask=w(3)&127, p=w(5)&255, v=w(7)&255; + const unsigned data=(w(5)>>17)&255, addr=(w(6)>>17)&255, vdata=(w(7)>>17)&255; + const unsigned temp=(w(15)>>16)&127, rp=(w(24)>>24)&255, rv=(w(26)>>24)&255; + const unsigned raddr=(w(22)>>17)&255; + const auto vector_mov=[](unsigned dst,unsigned src) { return 0x7e000200u|(dst<<17)|src; }; + bool match=w(1)==(0xbf008000u|wave) && w(2)==0xbf840010 && w(3)==(0xbefe0400u|mask) && + w(4)==0xbf880007 && w(5)==vector_mov(data,p) && w(6)==vector_mov(addr,128) && + w(7)==vector_mov(vdata,v) && data!=addr && addr!=vdata && vdata!=data && + w(8)==0xd8340000 && w(9)==((data<<8)|addr) && w(10)==0xd8340004 && w(11)==((vdata<<8)|addr) && + w(12)==0xbefe04c1 && w(13)==0xbfa3ffe3 && w(14)==0xbf8a0000 && + w(15)==(0x8f008c00u|(temp<<16)|p) && w(16)==(0x887c0000u|(v<<8)|temp) && + w(17)==0xbf900009 && w(18)==0xbf82000d && w(19)==0xbf8a0000 && w(20)==w(3) && w(21)==0xbf880009 && + w(22)==vector_mov(raddr,128) && w(23)==0xd8d80000 && w(24)==((rp<<24)|raddr) && + w(25)==0xd8d80004 && w(26)==((rv<<24)|raddr) && rp!=rv && rp!=raddr && + w(27)==0xbf8cc17f && w(28)==(0x7e000500u|(p<<17)|rp) && w(29)==0xbf8cc07f && + w(30)==(0x7e000500u|(v<<17)|rv) && w(31)==0xbefe04c1; + if (match) { + if (mask>104 || (mask&1) || p>=106 || v>=106 || p==v || temp>=106 || temp==v || + alu.read(wave)!=wave_number || alu.read(mask)!="1" || alu.read(mask+1)!="0") + refuse(pc,"unproven mesh count exchange wave or lane-zero mask"); + auto input_v=alu.read(v), input_p=alu.read(p); + if (!upper_bound.count(input_v) || !upper_bound.count(input_p) || + upper_bound.at(input_v)>(std::min)(layout.max_vertices,layout.threads) || + upper_bound.at(input_p)>(std::min)(layout.max_primitives,layout.threads)) + refuse(pc,"mesh count exchange exceeds declared range or lacks an unsigned bound"); + ir.globals<<"@meshCounts = internal addrspace(3) global [2 x i32] undef, align 4\n"; + auto ptr0=alu.shared_address("meshCounts",2,"0"),ptr1=alu.shared_address("meshCounts",2,"1"); + alu.barrier(); + guarded("1",[&] { + ir.body<<" store i32 "<<input_v<<", i32 addrspace(3)* "<<ptr0<<", align 4\n" + <<" store i32 "<<input_p<<", i32 addrspace(3)* "<<ptr1<<", align 4\n"; + }); + alu.barrier(); + vertex_count=ir.value("load i32, i32 addrspace(3)* "+ptr0+", align 4"); + primitive_count=ir.value("load i32, i32 addrspace(3)* "+ptr1+", align 4"); + ir.invoke("void","setMeshOutputCounts",168,{{"i32",vertex_count},{"i32",primitive_count}},"nounwind"); + alu.write(v,vertex_count); alu.write(p,primitive_count); + for (auto r:{data,addr,vdata,rp,rv,raddr}) alu.write(256+r,{}); + alu.write(temp,{}); alu.write(128,{}); + full_exec=true; lane_active.clear(); wave_active.clear(); exec_value[0].clear(); exec_value[1].clear(); + allocated=true; pc+=128; continue; + } + } + const auto op = gfx1013::instruction(code,pc); + if ((branch || exec_skip || !forward.empty()) && ((op.form==gfx1013::Form::exp && export_limit.empty()) || op.name=="s_endpgm" || raw==0xbf900009 || + raw==0xbefe0481 || raw==0xbefe04c1 || (op.name=="s_mov_b32" && ((raw>>16)&127)==124))) + refuse(pc,"mesh scalar branch crosses allocation, EXEC or export"); + if (op.name=="s_endpgm") { + if (!allocated || !position || !indices) refuse(pc,"mesh ended without complete position and triangle exports"); + ir.body << " ret void\n"; + emitter.result.dxil_ir=ir.finish_compute(layout.threads,1,1,"ms"); + emitter.result.group={layout.threads,1,1}; + for (const auto &sig : ir.outputs) + emitter.result.outputs.push_back({sig.name,sig.semantic_index,sig.row,sig.first,sig.width, + sig.component,sig.used,sig.kind,sig.interpolation}); + return std::move(emitter.result); + } + if (op.name=="s_nop" || op.name=="v_nop" || op.name=="s_clause" || op.name=="s_inst_prefetch" || + op.name=="s_waitcnt" || op.name=="s_waitcnt_depctr" || op.name=="s_setprio") { + pc+=op.size; + continue; + } + // HW_REG_FLAT_SCR_LO / HI are not numeric SGPRs. Scratch accesses + // and hardware-register reads are still rejected at their own PCs. + if (raw == 0xba80f814 || raw == 0xba80f815) { + pc += op.size; + continue; + } + if (raw==0xbf900009) { + if (allocated || !allocation_word) refuse(pc,"mesh allocation requires one uniform, bounded m0 count word"); + vertices=*allocation_word & 4095; primitives=(*allocation_word>>12)&4095; + if ((*allocation_word>>24) || vertices>layout.max_vertices || primitives>layout.max_primitives || + vertices>layout.threads || primitives>layout.threads || (!vertices && primitives)) + refuse(pc,"mesh allocation exceeds declared lane-indexed output range"); + ir.invoke("void","setMeshOutputCounts",168,{{"i32",to_string(vertices)},{"i32",to_string(primitives)}},"nounwind"); + vertex_count=to_string(vertices); primitive_count=to_string(primitives); + allocated=true; pc+=4; continue; + } + if (op.form==gfx1013::Form::exp) { + const unsigned target=(raw>>4)&63, channels=raw&15; + if ((!full_exec && (export_limit.empty() || !exec_skip || exec_skip->guard!=lane_active || + export_limit!=(target==20 ? primitive_count : vertex_count))) || !allocated || (raw&0x400)) + refuse(pc,"unsupported mesh export mask or allocation"); + const auto sources=word(code,pc+4); + if ((target==12 && channels==15 && !position) || + (target>=32 && channels && parameter_exports.insert(target).second)) { + position |= target==12; + graphics.pc=pc; + guarded(vertex_count,[&] { + for (unsigned c=0;c<4;++c) { + if (!(channels & (1u<<c))) continue; + if (!reflected && target>=32) { + // Identical fixed-pipeline convention to the raw PS + // interpolator: semantic index = 4 * PARAM + channel. + const unsigned id=4*(target-32)+c; + const unsigned reg=1+(layout.packed_parameters ? target-32 : id); + if (reg>=32) refuse(pc,"raw mesh PARAM exceeds signature registers"); + const auto row=static_cast<uint8_t>(reg), bit=static_cast<uint8_t>(1u<<c); + fixed_outputs.outputs.push_back({6,row,bit,static_cast<uint8_t>(target-32),0,0}); + fixed_outputs.output_signature.push_back({"TEXCOORD",id,0,3,row,bit,bit}); + } + unsigned channel=c; + const auto id=graphics.output(target,channel); + auto &sig=ir.outputs.at(id); + const unsigned col=channel-sig.first; + auto bits=alu.read(256+((sources>>(8*c))&255)); + const bool fp=sig.component==9; + ir.invoke("void",fp ? "storeVertexOutput.f32" : "storeVertexOutput.i32",171, + {{"i32",to_string(id)},{"i32","0"},{"i8",to_string(col)}, + {fp ? "float" : "i32",fp ? ir.value("bitcast i32 "+bits+" to float") : bits}, + {"i32",thread}},"nounwind"); + sig.used|=1u<<col; + } + }); + } else if (target==20 && channels==1 && !indices) { + indices=true; + guarded(primitive_count,[&] { + auto packed=alu.read(256+(sources&255)); + auto culled=alu.cmp("slt",packed,"0"); + std::array<string,3> triangle; + for (unsigned c=0;c<3;++c) { + triangle[c]=ir.binary("and",ir.binary("lshr",packed,to_string(10*c)),"1023"); + culled=ir.value("or i1 "+culled+", "+alu.cmp("uge",triangle[c],to_string(vertices))); + } + ir.invoke("void","emitIndices",169,{{"i32",thread},{"i32",alu.select(culled,"0",triangle[0])}, + {"i32",alu.select(culled,"0",triangle[1])},{"i32",alu.select(culled,"0",triangle[2])}},"nounwind"); + }); + } else refuse(pc,"unmapped mesh export target "+to_string(target)); + pc+=op.size; continue; + } + const auto i=decode(code,pc,true,op.form!=gfx1013::Form::mtbuf); + std::optional<unsigned> result_bound; + if (i.name=="s_and_b32") result_bound=(std::min)(bound(i,i.src[0]),bound(i,i.src[1])); + if (i.name=="s_bfe_u32") { + if (auto field=constant32(i,i.src[1]); field && ((*field>>16)&127)<32) + result_bound=(1u<<((*field>>16)&127))-1; + } + if (i.name=="s_add_u32") { + uint64_t sum=uint64_t(bound(i,i.src[0]))+bound(i,i.src[1]); + if (sum<=UINT32_MAX) result_bound=static_cast<unsigned>(sum); + } + if (i.name=="s_cselect_b32") result_bound=(std::max)(bound(i,i.src[0]),bound(i,i.src[1])); + const unsigned vec_dst=i.enc==Encoding::Mubuf ? 256+i.dst : i.dst; + std::array<string,4> before_vec; + std::array<bool,4> before_partial{}; + if (!full_exec && !lane_active.empty() && vec_dst>=256 && vec_dst<512) { + for (unsigned j=0;j<4;++j) { + const auto old=alu.graphics_registers.find(vec_dst+j); + if (old!=alu.graphics_registers.end()) before_vec[j]=old->second; + before_partial[j]=partial_writes.count(vec_dst+j)!=0; + } + } + const bool export_cmp=i.name=="v_cmpx_gt_i32" && allocated && i.src[0]<106 && full_exec && + (alu.read(i.src[0])==vertex_count || alu.read(i.src[0])==primitive_count); + if ((i.name=="v_cmpx_gt_u32" || export_cmp) && full_exec && !branch && !exec_skip && i.enc==Encoding::Vopc && !i.wide && !i.subword && !i.dpp_control && + i.src[0]<106 && linear_threads.count(alu.operand32(i,i.src[1]))) { + // Lane-linear count comparison in a merged workgroup. Construct + // both halves from the guest wave start, independent of native + // WaveGetLaneCount. Saturation avoids shifts by 32 or unsigned + // underflow when the last group wave is empty. + const auto limit=alu.operand32(i,i.src[0]); + export_limit=export_cmp ? limit : string{}; + const auto capped=alu.select(alu.cmp("ult",limit,to_string(layout.threads)),limit,to_string(layout.threads)); + const auto base=ir.binary("sub",thread,wave_lane); + wave_active=alu.cmp("ugt",capped,base); + lane_active=alu.cmp("ult",thread,capped); + for (unsigned j=0;j<2;++j) { + if (j && layout.wave32) { exec_value[j]="0"; continue; } + const auto begin=j ? ir.binary("add",base,"32") : base; + const auto n=alu.select(alu.cmp("ugt",capped,begin),ir.binary("sub",capped,begin),"0"); + const auto bits=ir.binary("sub",ir.binary("shl","1",ir.binary("and",n,"31")),"1"); + exec_value[j]=alu.select(alu.cmp("uge",n,"32"),"4294967295",bits); + } + full_exec=false; + } else if (i.name=="v_cmpx_gt_i32" && !branch && exec_skip && !lane_active.empty() && + i.enc==Encoding::Vopc && !i.wide && !i.subword && !i.dpp_control) { + const auto a=decode(code,i.next,true,true); + if (a.name!="s_cbranch_execz" || a.target()<=a.next || a.target()>=code.size()) + refuse(pc,"mesh signed CMPX requires paired EXECZ arms"); + const auto inverse=decode(code,a.target(),true,true); + const auto b=decode(code,inverse.next,true,true); + if (inverse.name!="s_andn2_b64" || inverse.dst!=126 || inverse.src[1]!=126 || inverse.src[0]>104 || + b.name!="s_cbranch_execz" || b.target()<=b.next || b.target()>=code.size() || + !pure_lane_arm(a.next,a.target()) || !pure_lane_arm(b.next,b.target())) + refuse(pc,"mesh CMPX arms contain an unproven wave effect"); + const auto mask=saved_mask(inverse.src[0]); + if (!mask || mask->lane!=lane_active || mask->wave!=wave_active || mask->full!=full_exec) + refuse(pc,"mesh CMPX inverse lacks the saved parent EXEC"); + branch=Diamond{pc,a.target(),b.target(),save_edge(),{}}; + lane_else=b.next; + auto take=alu.comparison(i); + ir.body<<" br i1 "<<take<<", label %mesh_then"<<pc<<", label %mesh_else"<<pc + <<"\nmesh_then"<<pc<<":\n"; + pc=a.next; continue; + } else if (i.name=="v_cmpx_eq_u32" && !branch && !i.dpp_control && !i.subword && !i.abs && !i.neg && + !i.scale && !i.clamp && (full_exec || !lane_active.empty())) { + const auto before=lane_active; + auto pred=alu.comparison(i); + lane_active=full_exec ? pred : ir.value("and i1 "+before+", "+pred); + mask_parent[lane_active]=before; + full_exec=false; wave_active.clear(); exec_value[0].clear();exec_value[1].clear(); + } else if (i.name=="s_cbranch_execz" && !full_exec && !lane_active.empty() && !branch && + i.target()>i.next && i.target()<code.size()) { + if (exec_skip) { + if (i.target()>exec_skip->end) refuse(pc,"overlapping mesh EXECZ exits"); + skip_parents.push_back(std::move(*exec_skip)); + } + exec_skip=Skip{pc,i.target(),save_edge(),wave_active.empty(),lane_active}; + ir.body<<" br i1 "<<(wave_active.empty() ? lane_active : wave_active)<<", label %mesh_work"<<pc<<", label %mesh_empty"<<pc + <<"\nmesh_empty"<<pc<<":\n br label %mesh_resume"<<pc<<"\nmesh_work"<<pc<<":\n"; + } else if (i.name=="s_cbranch_scc0" || i.name=="s_cbranch_scc1" || + i.name=="s_cbranch_vccz" || i.name=="s_cbranch_vccnz") { + const auto other=i.target(); + if (lane_else || (!full_exec && !exec_skip) || allocated || other<=i.next || other>=code.size() || + (exec_skip && other>exec_skip->end)) + refuse(pc,"unsupported mesh scalar branch destination"); + for (unsigned at=i.next;at<other;) { + const auto next=at+gfx1013::instruction(code,at).size; + if (next<=at || next>other) refuse(pc,"mesh branch target splits instruction"); + at=next; + } + const bool vcc=i.name=="s_cbranch_vccz" || i.name=="s_cbranch_vccnz"; + string value; + if (!vcc) value=alu.read(128); + else { + auto nonempty=alu.graphics_registers.find(vcc_nonempty); + if (nonempty!=alu.graphics_registers.end() && !nonempty->second.empty()) value=nonempty->second; + else { + auto lo=alu.graphics_registers.find(vcc_words), hi=alu.graphics_registers.find(vcc_words+1); + if (lo==alu.graphics_registers.end() || lo->second.empty() || + hi==alu.graphics_registers.end() || hi->second.empty()) + refuse(pc,"mesh VCC branch lacks a proven guest whole-wave mask"); + value=ir.binary("or",lo->second,hi->second); + } + } + auto take=alu.cmp(i.name=="s_cbranch_scc0" || i.name=="s_cbranch_vccz" ? "eq" : "ne",value,"0"); + const auto edge=arrive(other), fall="mesh_fall"+to_string(pc); + ir.body<<" br i1 "<<take<<", label %"<<edge<<", label %"<<fall<<"\n"<<fall<<":\n"; + } else if (i.name=="s_branch" && !lane_else && i.target()>=i.next && i.target()<code.size() && + (!exec_skip || i.target()<=exec_skip->end)) { + const auto target=i.target(); + for (unsigned at=i.next;at<target;) { + const auto next=at+gfx1013::instruction(code,at).size; + if (next<=at || next>target) refuse(pc,"mesh branch target splits instruction"); + at=next; + } + ir.body<<" br label %"<<arrive(target)<<"\n"; + live=false; + } else if (auto field=byte_descriptor_field(i,state)) { + alu.write(i.dst,{}); + state[i.dst]=*field; + if (i.name!="s_mul_i32") + alu.write(128,field->type==Symbol::Type::byte_oob || field->type==Symbol::Type::root_stride_one_high ? + "1" : string{}); + } else if (i.enc==Encoding::Smem) { + const auto offset_reg=i.b>>25; + if ((offset_reg!=125 && offset_reg>=106) || i.src[0]>=105 || i.dst+memory_count(i)>106) + refuse(pc,"unsupported mesh scalar memory address"); + if (i.op<8 && state[i.src[0]].type!=Symbol::Type::table) + refuse(pc,"mesh scalar memory needs a verified guest root mapping: "+string(op.name)); + if (i.op<8 && offset_reg!=125 && state[i.src[0]].value!=compute_resource_heap) + refuse(pc,"indexed mesh descriptor table lacks a binding contract"); + auto next=transfer(i, state, !layout.wave32, true, false, true); + const bool global=state[i.src[0]].value==compute_resource_heap && state[i.src[0]].type==Symbol::Type::table; + if (global && layout.validate_uint_heap_reads) { + if (i.op!=2 || offset_reg>=106 || (i.b&0xfffff) || + !(state[i.src[0]+1]==Symbol{Symbol::Type::constant,0})) + refuse(pc,"unsupported mesh heap descriptor address"); + const auto bytes=alu.operand32(i,offset_reg); + const auto bits=root_values.find(bytes); + if (bits==root_values.end() || bits->second.shift!=5) + refuse(pc,"mesh heap slot lacks masked root constant provenance"); + heap_fetches[pc]=bits->second; + } else alu.memory(i,state); + if (i.op<8) { + for (unsigned j=0;j<memory_count(i);++j) alu.write(i.dst+j,{}); + } + state=next; + } else if (i.name=="buffer_load_format" && i.op==0 && full_exec && (i.a&0x3ffff)==0x2000) { + const auto base=((i.b>>16)&31)*4; + const auto sym=state[base]; + if (sym.type!=Symbol::Type::indexed_descriptor || sym.value!=compute_resource_heap || + !heap_fetches.count(sym.definition) || sym.offset) + refuse(pc,"formatted mesh load lacks an R32_UINT resource heap contract"); + for (unsigned j=1;j<4;++j) { + auto expected=sym; + expected.offset=j*4; + if (!(expected==state[base+j])) refuse(pc,"overwritten mesh heap descriptor"); + } + const auto guard=heap_fetches.at(sym.definition); + const auto entry=std::find_if(root_values.begin(),root_values.end(),[&](const auto &x) { + return x.second.param==guard.param && x.second.dword==guard.dword && !x.second.shift && x.second.mask==~0u; + }); + if (entry==root_values.end()) refuse(pc,"missing mesh heap selector"); + emitter.result.mesh_heap_reads.push_back({guard.param,guard.dword,guard.mask}); + const auto descriptor=ir.binary("and",entry->first,to_string(guard.mask)); + ir.features|=0x40000000; + const auto handle=ir.heap_handle(descriptor,10,261); // TypedBuffer, one U32 component. + const auto index=alu.read(256+(i.b&255)); + const auto word=ir.value("extractvalue %dx.types.ResRet.i32 "+alu.load_buffer(handle,index,false,1)+", 0"); + alu.write(256+i.dst,word); + if (uniform_values.count(index)) uniform_values.insert(word); + } else if (op.form==gfx1013::Form::mtbuf && (full_exec || exec_skip)) { + const auto base=((i.b>>16)&31)*4; + const auto low=state[base]; + string window; + if (low.type==Symbol::Type::root_address) { + const bool zero_stride=state[base+1]==Symbol{Symbol::Type::root_address,low.value,1} && + state[base+3]==Symbol{Symbol::Type::constant,0x31016fac}; + const bool byte_stride=state[base+1]==Symbol{Symbol::Type::root_stride_one_high,low.value,1} && + state[base+3]==Symbol{Symbol::Type::constant,0x11014fac}; + if (low.offset || (!zero_stride && !byte_stride) || + !(state[base+2]==Symbol{Symbol::Type::constant,0xffffffff})) + refuse(pc,"mesh formatted root load requires an unbounded byte window"); + window=alu.root_buffer_handle(low.value,4); + } + alu.formatted_byte_load(i,state,window); + if (!full_exec) for (unsigned j=0;j<=i.op;++j) partial_writes.insert(256+i.dst+j); + } else if (i.name=="buffer_load_dword" && (full_exec || exec_skip)) { + alu.memory(i,state); + if (!full_exec) { + constexpr unsigned counts[]{1,2,4,3}; + for (unsigned j=0;j<counts[i.op&3];++j) partial_writes.insert(256+i.dst+j); + } + } else if (i.enc==Encoding::Vopc && i.name.substr(0,6)=="v_cmp_" && i.dst<=106 && + !i.dpp_control && !i.scale && !i.clamp && (full_exec || !lane_active.empty())) { + auto next=transfer(i, state, !layout.wave32, true, false, true); + auto pred=alu.comparison(i); + if (!full_exec) pred=ir.value("and i1 "+pred+", "+lane_active); + const auto bit=ir.value("zext i1 "+pred+" to i32"); + if (!i.subword) { + const auto lhs=uniform(alu.operand32(i,i.src[0])), rhs=uniform(alu.operand32(i,i.src[1])); + if (!lhs.empty() && !rhs.empty()) mask_uniform[bit]={lane_active,alu.comparison(i,lhs,rhs)}; + } + if (i.dst==106) { + alu.write(106,bit); + alu.write(vcc_words,{}); alu.write(vcc_words+1,{}); alu.write(vcc_nonempty,{}); + next[106].type=next[107].type=Symbol::Type::unbound; + } else { + alu.write(i.dst,{}); + if (!layout.wave32) alu.write(i.dst+1,{}); + alu.write(1024+i.pc,bit); + } + state=next; + } else if (i.name=="v_cndmask_b32" && !i.scale && !i.clamp && !i.dpp_control && + (full_exec || !lane_active.empty())) { + if ((i.wide && (i.a&0x7800)) || ((i.abs|i.neg)&4)) refuse(pc,"unsupported mesh CNDMASK operand selection"); + auto a=alu.operand32(i,i.src[0]), b=alu.operand32(i,i.src[1]); + if (i.subword) { + a=alu.subword(a,i.src_select[0],i.src_sext[0]); + b=alu.subword(b,i.src_select[1],i.src_sext[1]); + } + if (i.abs&1) a=ir.binary("and",a,"2147483647"); + if (i.abs&2) b=ir.binary("and",b,"2147483647"); + if (i.neg&1) a=ir.binary("xor",a,"2147483648"); + if (i.neg&2) b=ir.binary("xor",b,"2147483648"); + auto bit=alu.graphics_lane_mask(i,state,i.src[2],"unproven mesh CNDMASK"); + const auto value=alu.place_subword(i,alu.select(alu.cmp("ne",bit,"0"),b,a)); + alu.write(i.dst,value); + if (mask_uniform.count(bit) && mask_uniform.at(bit).first==lane_active && !uniform(a).empty() && !uniform(b).empty() && !i.subword) + active_uniform[value]={lane_active,alu.select(mask_uniform.at(bit).second,uniform(b),uniform(a))}; + if (!full_exec) partial_writes.insert(i.dst); + } else if (i.name=="s_cselect_b64" && !(i.dst&1) && i.dst<=106 && + (i.src[0]==128 || i.src[0]==193) && (i.src[1]==128 || i.src[1]==193)) { + auto bit=alu.select(alu.cmp("ne",alu.read(128),"0"),i.src[0]==193 ? "1" : "0",i.src[1]==193 ? "1" : "0"); + if (i.dst==106) { + alu.write(106,bit); + auto word=ir.binary("sub","0",bit); + mask_uniform[bit]={"",alu.cmp("ne",bit,"0")}; + alu.write(vcc_words,word); alu.write(vcc_words+1,word); alu.write(vcc_nonempty,word); + state[106]={}; state[107]={}; + } else { + auto next=transfer(i, state, !layout.wave32, true, false, true); + const auto word=ir.binary("sub","0",bit); + alu.write(i.dst,word); alu.write(i.dst+1,word); + alu.write(1024+i.pc,bit); + state=next; + } + } else if (i.name=="s_cselect_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]==126 && + i.src[1]==128 && (full_exec || !lane_active.empty())) { + const auto cond=alu.cmp("ne",alu.read(128),"0"); + const auto pred=full_exec ? cond : ir.value("and i1 "+cond+", "+lane_active); + alu.write(i.dst,alu.select(cond,full_exec ? "4294967295" : exec_value[0],"0")); + alu.write(i.dst+1,alu.select(cond,full_exec ? (layout.wave32 ? "0" : "4294967295") : exec_value[1],"0")); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; + state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + const auto lane=ir.value("zext i1 "+pred+" to i32"); + alu.write(1024+pc,lane); mask_uniform[lane]={lane_active,cond}; + } else if (i.name=="s_not_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]<=104 && !(i.src[0]&1)) { + const auto a=alu.graphics_lane_mask(i,state,i.src[0],"unproven mesh NOT mask"); + std::array<string,2> data{}; + for (unsigned j=0;j<2;++j) { + auto it=alu.graphics_registers.find(i.src[0]+j); + if (it!=alu.graphics_registers.end() && !it->second.empty()) data[j]=ir.binary("xor",it->second,"4294967295"); + } + alu.write(i.dst,data[0]); alu.write(i.dst+1,data[1]); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + alu.write(1024+pc,ir.binary("xor",a,"1")); alu.write(128,{}); + } else if (i.name=="s_and_b64" && i.dst==126 && i.src[1]==126 && i.src[0]<=104 && + !full_exec && exec_skip && !branch && !lane_active.empty() && + [&] { + auto a=decode(code,i.next,true,true); + if (a.name!="s_cbranch_execz" || a.target()<=a.next || a.target()+8>=code.size()) return false; + auto inv=decode(code,a.target(),true,true); + auto b=decode(code,inv.next,true,true); + if (inv.name!="s_andn2_b64" || inv.dst!=126 || inv.src[1]!=126 || + b.name!="s_cbranch_execz" || b.target()<=b.next || b.target()+4>code.size()) return false; + auto reset=decode(code,b.target(),true,true); + auto parent=saved_mask(inv.src[0]); + if (!parent || parent->lane!=lane_active || parent->wave!=wave_active || + reset.name!="s_mov_b64" || reset.dst!=126 || reset.src[0]!=inv.src[0]) return false; + auto left=gather_arm(a.next,a.target()),right=gather_arm(b.next,b.target()); + if (!left || !right) return false; + for (auto r : right->inputs) if (left->writes.count(r)) return false; + for (auto r : {inv.src[0],inv.src[0]+1}) if (left->writes.count(r) || right->writes.count(r)) return false; + branch=Diamond{pc,a.target(),b.target(),save_edge(),{}}; + lane_scalar_clobbers=left->writes; + lane_scalar_clobbers.insert(right->writes.begin(),right->writes.end()); + lane_scalar_clobbers.insert(128); + lane_else=b.next; + auto take=alu.cmp("ne",alu.graphics_lane_mask(i,state,i.src[0],"unproven mesh gather mask"),"0"); + ir.body<<" br i1 "<<take<<", label %mesh_then"<<pc<<", label %mesh_else"<<pc + <<"\nmesh_then"<<pc<<":\n"; + pc=a.next; + return true; + }()) { + continue; + } else if ((i.name=="s_or_b64" || i.name=="s_and_b64" || i.name=="s_andn2_b64") && + (i.dst<=106 || i.dst==126) && !(i.dst&1)) { + auto lane_bit=[&](unsigned src) { + if (src==126 && (full_exec || !lane_active.empty())) + return full_exec ? string("1") : ir.value("zext i1 "+lane_active+" to i32"); + return alu.graphics_lane_mask(i,state,src,"unproven mesh mask operand"); + }; + auto mask_word=[&](unsigned src,unsigned j) -> string { + if (src==126) return full_exec ? (j && layout.wave32 ? "0" : "4294967295") : exec_value[j]; + if (src==106) src=vcc_words; + auto v=alu.graphics_registers.find(src+j); + return v==alu.graphics_registers.end() ? string{} : v->second; + }; + const auto a=lane_bit(i.src[0]),b=lane_bit(i.src[1]); + auto combine=[&](const string &x,const string &y,bool lane) { + if (x.empty() || y.empty()) return string{}; + return ir.binary(i.name=="s_or_b64" ? "or" : "and",x,i.name=="s_andn2_b64" ? + ir.binary("xor",y,lane ? "1" : "4294967295") : y); + }; + const auto lo=combine(mask_word(i.src[0],0),mask_word(i.src[1],0),false); + const auto hi=combine(mask_word(i.src[0],1),mask_word(i.src[1],1),false); + const auto bit=combine(a,b,true); + string any; + if (!lo.empty() && !hi.empty()) any=ir.binary("or",lo,hi); + else if (((i.src[0]==126) || (i.src[1]==126 && i.name=="s_and_b64")) && (i.name=="s_andn2_b64" || i.name=="s_and_b64") && mask_uniform.count(i.src[0]==126 ? b : a) && + covered_by(lane_active,mask_uniform.at(i.src[0]==126 ? b : a).first) && + (full_exec || !wave_active.empty() || (exec_skip && exec_skip->guard==lane_active))) { + auto flag=mask_uniform.at(i.src[0]==126 ? b : a).second; + if (i.name=="s_andn2_b64") flag=ir.value("xor i1 "+flag+", true"); + if (!wave_active.empty()) flag=ir.value("and i1 "+flag+", "+wave_active); + any=ir.value("zext i1 "+flag+" to i32"); + } + if (i.dst==126) { + const auto before=lane_active; + if (i.name=="s_and_b64" && (i.src[0]==126 || i.src[1]==126)) + before_narrowing[before]=save_edge(); + full_exec=false; + lane_active=alu.cmp("ne",bit,"0"); + if (i.name!="s_or_b64" && (i.src[0]==126 || (i.name=="s_and_b64" && i.src[1]==126))) mask_parent[lane_active]=before; + wave_active=lo.empty() || hi.empty() ? string{} : alu.cmp("ne",ir.binary("or",lo,hi),"0"); + exec_value[0]=lo; exec_value[1]=hi; + } else if (i.dst==106) { + alu.write(106,bit); + alu.write(vcc_words,lo); alu.write(vcc_words+1,hi); alu.write(vcc_nonempty,any); + state[106].type=lo.empty()?Symbol::Type::unbound:Symbol::Type::unknown; + state[107].type=hi.empty()?Symbol::Type::unbound:Symbol::Type::unknown; + } else { + alu.write(i.dst,lo); alu.write(i.dst+1,hi); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; + state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + alu.write(1024+pc,bit); + } + alu.write(128,any.empty() ? string{} : ir.value("zext i1 "+alu.cmp("ne",any,"0")+" to i32")); + } else if ((i.name=="s_bitset0_b32" || i.name=="s_bitset1_b32") && i.dst<106) { + auto bit=ir.binary("shl","1",ir.binary("and",alu.operand32(i,i.src[0]),"31")); + const auto old=alu.operand32(i,i.dst); + alu.write(i.dst,i.name=="s_bitset0_b32" ? ir.binary("and",old,ir.binary("xor",bit,"4294967295")) : + ir.binary("or",old,bit)); + } else if (i.name=="s_bitcmp0_b32" || i.name=="s_bitcmp1_b32" || i.name=="s_cmp_lt_u32" || + i.name=="s_mulk_i32" || i.name=="s_addk_i32" || i.name=="s_mul_i32" || i.name=="s_add_u32" || i.name=="s_add_i32" || + i.name=="s_cmp_gt_i32" || i.name=="s_cmp_lt_i32" || i.name=="s_cmp_ge_i32" || i.name=="s_cmp_eq_u32" || i.name=="s_cmp_eq_i32" || i.name=="s_cmp_lg_u32" || i.name=="s_cmp_ge_u32" || i.name=="s_cmp_lg_i32" || i.name=="s_cmp_gt_u32" || i.name=="s_cselect_b32") { + alu.arithmetic(i,state); + } else if (raw==0xbefe04c1) { + full_exec=true; + export_limit.clear(); + for (auto r : partial_writes) alu.write(r,{}); + partial_writes.clear(); + wave_active.clear(); lane_active.clear(); + exec_value[0].clear(); exec_value[1].clear(); + } else if (i.name=="s_mov_b64" && i.dst==106 && (i.src[0]==128 || i.src[0]==193)) { + const bool set=i.src[0]==193; + auto value=set ? "4294967295" : "0"; + alu.write(106,set ? "1" : "0"); alu.write(vcc_words,value); alu.write(vcc_words+1,value); + alu.write(vcc_nonempty,value); + state[106]=state[107]={Symbol::Type::constant,set ? ~0u : 0u}; + // Thread the known-zero predecessor through a mask test before + // merging with paths that computed its optional buffer values. + if (!set && i.next+8<=code.size() && !branch && gfx1013::instruction(code,i.next).name=="s_and_b64") { + auto test=decode(code,i.next,true,true); + auto jump=decode(code,test.next,true,true); + if (test.name=="s_and_b64" && test.dst<=104 && !(test.dst&1) && + ((test.src[0]==106 && test.src[1]==126) || (test.src[0]==126 && test.src[1]==106)) && + jump.name=="s_cbranch_scc0" && jump.target()>=jump.next && jump.target()<code.size() && + (!exec_skip || jump.target()<=exec_skip->end)) { + alu.write(test.dst,"0"); alu.write(test.dst+1,"0"); alu.write(128,"0"); + state[test.dst]={Symbol::Type::uniform_mask,test.pc,0}; + state[test.dst+1]={Symbol::Type::uniform_mask,test.pc,1}; + alu.write(1024+test.pc,"0"); + ir.body<<" br label %"<<arrive(jump.target())<<"\n"; + live=false; + } + } + } else if (i.name=="s_mov_b64" && i.dst==106 && i.src[0]<=104 && !(i.src[0]&1)) { + const auto src=i.src[0]; + const auto old=state; + const auto next=transfer(i, state, !layout.wave32, true, false, true); + auto physical=[&](unsigned r) { + auto it=alu.graphics_registers.find(r); return it==alu.graphics_registers.end() ? string{} : it->second; + }; + const auto lo=physical(src), hi=physical(src+1); + string bit; + if (old[src].type==Symbol::Type::lane_mask || old[src].type==Symbol::Type::uniform_mask) + bit=alu.graphics_lane_mask(i,old,src,"unproven mesh VCC move"); + else if (!lo.empty() && !hi.empty()) { + auto half=alu.select(alu.cmp("ult",wave_lane,"32"),lo,hi); + bit=ir.binary("and",ir.binary("lshr",half,ir.binary("and",wave_lane,"31")),"1"); + } + alu.write(106,bit); alu.write(vcc_words,lo); alu.write(vcc_words+1,hi); + alu.write(vcc_nonempty,lo.empty() || hi.empty() ? string{} : ir.binary("or",lo,hi)); + state=next; + } else if (i.name=="s_mov_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]==126 && + (full_exec || !lane_active.empty())) { + alu.write(i.dst,full_exec ? "4294967295" : exec_value[0]); + alu.write(i.dst+1,full_exec ? (layout.wave32 ? "0" : "4294967295") : exec_value[1]); + state[i.dst]={Symbol::Type::lane_mask,pc,0}; state[i.dst+1]={Symbol::Type::lane_mask,pc,1}; + alu.write(1024+pc,full_exec ? "1" : ir.value("zext i1 "+lane_active+" to i32")); + saved_exec[pc]={full_exec,lane_active,wave_active,exec_value[0],exec_value[1],alu.graphics_registers,partial_writes}; + } else if (i.name=="s_mov_b64" && i.dst==126 && i.src[0]<=104 && !(i.src[0]&1)) { + const auto mask=saved_mask(i.src[0]); + if (!mask) refuse(pc,"mesh EXEC restore lacks a still-valid reaching mask"); + if (mask->lane!=lane_active) { + auto at_narrow=before_narrowing.find(mask->lane); + const auto ®s=at_narrow==before_narrowing.end() ? mask->regs : at_narrow->second.regs; + const auto &valid=at_narrow==before_narrowing.end() ? mask->partial : at_narrow->second.partial; + std::set<unsigned> remaining; + for (auto r:partial_writes) { + auto at=regs.find(r); + if (at==regs.end() || at->second.empty() || at->second!=alu.graphics_registers.at(r)) + alu.write(r,{}); + else if (valid.count(r)) remaining.insert(r); + } + partial_writes=std::move(remaining); + } + full_exec=mask->full; lane_active=mask->lane; wave_active=mask->wave; + exec_value[0]=mask->lo; exec_value[1]=mask->hi; + } else if (i.name=="s_mov_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]<=104 && !(i.src[0]&1)) { + auto next=transfer(i, state, !layout.wave32, true, false, true); + auto src=alu.graphics_registers.find(i.src[0]), high=alu.graphics_registers.find(i.src[0]+1); + auto lo=src==alu.graphics_registers.end() ? string{} : src->second; + auto hi=high==alu.graphics_registers.end() ? string{} : high->second; + alu.write(i.dst,lo); + alu.write(i.dst+1,hi); + state=next; + } else if (i.name=="s_mov_b64" && i.dst<=104 && !(i.dst&1) && i.src[0]>=128 && i.src[0]<=208) { + auto next=transfer(i, state, !layout.wave32, true, false, true); + alu.write(i.dst,to_string(next[i.dst].value)); alu.write(i.dst+1,to_string(next[i.dst+1].value)); + state=next; + } else if (i.name=="s_mov_b32" && i.dst==125 && constant32(i,i.src[0])) { + // NULL discards the scalar move; MOV does not write SCC. + } else if (i.name=="s_mov_b32" && i.dst==124) { + allocation_word=constant32(i,i.src[0]); + } else if (i.name=="s_mov_b32" && i.dst<106) { + const auto provenance=source(i,i.src[0],state); + if (auto value=constant32(i,i.src[0])) alu.write(i.dst,to_string(*value)); + else if (i.src[0]<=107) { + const auto source=alu.graphics_registers.find(i.src[0]<106 ? i.src[0] : vcc_words+i.src[0]-106); + alu.write(i.dst,source==alu.graphics_registers.end() ? string{} : source->second); + } else if (i.src[0]==253) alu.write(i.dst,alu.read(128)); + else refuse(pc,"unsupported scalar mesh entry operand"); + state[i.dst]=provenance; + } else if (i.name=="s_bfe_u32" && i.src[0]==3 && !alu.graphics_registers.count(3) && + i.src[1]==255 && i.literal==0x40018 && i.dst<106) { + alu.write(i.dst,wave_number); + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",wave_number,"0")+" to i32")); + } else if (i.name=="s_bcnt1_i32_b64" && i.src[0]<=104 && !(i.src[0]&1) && i.dst<106) { + auto pop=[&](unsigned r) { + return ir.invoke("i32","unaryBits.i32",31,{{"i32",alu.read(r)}},"nounwind readnone"); + }; + const auto lo=pop(i.src[0]), hi=pop(i.src[0]+1); + const auto sum=ir.binary("add",lo,hi); + alu.write(i.dst,sum); + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",sum,"0")+" to i32")); + } else if (i.name=="s_bfe_u32" || i.name=="s_min_u32") { + alu.arithmetic(i,state); + } else if (i.name=="v_readfirstlane_b32" && i.dst<106 && i.src[0]==261 && !exchanged_group.empty() && full_exec) { + alu.write(i.dst,exchanged_group); + } else if (i.name=="v_readfirstlane_b32" && i.dst<106 && (full_exec || exec_skip) && + !uniform(alu.read(i.src[0])).empty()) { + alu.write(i.dst,uniform(alu.read(i.src[0]))); + } else if (i.name=="s_pack_ll_b32_b16" || i.name=="s_pack_hh_b32_b16") { + const auto a=alu.operand32(i,i.src[0]),b=alu.operand32(i,i.src[1]); + const bool high=i.name=="s_pack_hh_b32_b16"; + alu.write(i.dst,ir.binary("or",high ? ir.binary("lshr",a,"16") : ir.binary("and",a,"65535"), + high ? ir.binary("and",b,"4294901760") : ir.binary("shl",b,"16"))); + } else if (i.enc==Encoding::Sop2 && i.dst<106 && (i.name=="s_lshr_b32" || i.name=="s_lshl_b32" || + i.name=="s_or_b32" || i.name=="s_and_b32")) { + const auto known=[&](unsigned r) { + return constant32(i,r).has_value() || + (alu.graphics_registers.count(r) && !alu.graphics_registers.at(r).empty()); + }; + if (known(i.src[0]) && known(i.src[1])) { + const auto a=alu.operand32(i,i.src[0]), b=alu.operand32(i,i.src[1]); + const bool shift=i.name=="s_lshl_b32" || i.name=="s_lshr_b32"; + const auto value=ir.binary(i.name=="s_lshl_b32" ? "shl" : i.name=="s_lshr_b32" ? "lshr" : + i.name=="s_or_b32" ? "or" : "and",a,shift ? ir.binary("and",b,"31") : b); + if (i.name=="s_lshl_b32" && a==wave_number && constant32(i,i.src[1])==(layout.wave32 ? 5u : 6u)) + wave_bases.insert(value); + const auto bits=root_values.find(a); + const auto imm=constant32(i,i.src[1]); + if (bits!=root_values.end() && imm && !bits->second.shift) { + auto out=bits->second; + if (i.name=="s_and_b32") { out.mask&=*imm; root_values.emplace(value,out); } + if (i.name=="s_lshl_b32" && *imm==5 && out.mask<=0x7ffffffu) { + out.shift=5; root_values.emplace(value,out); + } + } + const auto next=transfer(i, state, !layout.wave32, true, false, true); + alu.write(i.dst,value); + state[i.dst]=next[i.dst]; + alu.write(128,ir.value("zext i1 "+alu.cmp("ne",value,"0")+" to i32")); + } + else { + alu.write(i.dst,{}); + alu.write(128,{}); + } + } else if (full_exec && (i.name=="v_mbcnt_lo_u32_b32" || i.name=="v_mbcnt_hi_u32_b32") && i.src[0]==193) { + const auto add=i.name=="v_mbcnt_lo_u32_b32" ? alu.select(alu.cmp("ult",wave_lane,"32"),wave_lane,"32") : + alu.select(alu.cmp("ult",wave_lane,"32"),"0",ir.binary("sub",wave_lane,"32")); + const auto base=alu.operand32(i,i.src[1]); + const auto value=ir.binary("add",base,add); + if (i.name=="v_mbcnt_lo_u32_b32") { + if (base=="0") low_lane.insert(value); + if (wave_bases.count(base)) low_group.insert(value); + } else { + if (low_lane.count(base)) whole_lane.insert(value); + if (low_group.count(base)) linear_threads.insert(value); + } + alu.write(i.dst,value); + } else if (i.name=="v_perm_b32" && !i.abs && !i.neg && !i.clamp && !i.scale && !i.subword && + !i.dpp_control && (full_exec || exec_skip)) { + // RDNA V_PERM_B32: selectors 0..3 index src1, 4..7 index src0, + // 8..11 replicate the sign of each halfword; 12 zero-fills. + const auto selectors=constant32(i,i.src[2]); + if (!selectors) refuse(pc,"dynamic mesh byte permutation"); + const auto a=alu.operand32(i,i.src[0]), b=alu.operand32(i,i.src[1]); + string result="0"; + for (unsigned j=0;j<4;++j) { + const unsigned sel=(*selectors>>(j*8))&255; + string byte; + if (sel<8) byte=ir.binary("and",ir.binary("lshr",sel<4 ? b : a,to_string((sel&3)*8)),"255"); + else if (sel<12) { + const auto bit=ir.binary("and",ir.binary("lshr",sel<10 ? b : a,to_string((sel&1)*16+15)),"1"); + byte=alu.select(alu.cmp("ne",bit,"0"),"255","0"); + } else byte=sel==12 ? "0" : "255"; + result=ir.binary("or",result,ir.binary("shl",byte,to_string(j*8))); + } + alu.write(i.dst,result); + if (!full_exec) partial_writes.insert(i.dst); + } else if ((full_exec || exec_skip) && (i.name=="v_trunc_f32" || i.name=="v_floor_f32" || + i.name=="v_ceil_f32" || i.name=="v_rndne_f32" || i.name=="v_fract_f32" || + i.name=="v_cvt_u32_f32" || i.name=="v_mul_u32_u24" || i.name=="v_lshl_or_b32" || + i.name=="v_add_lshl_u32" || i.name=="v_lshrrev_b64" || i.name=="v_lshlrev_b64" || i.name=="v_mad_legacy_f32" || + i.name=="v_mul_lo_u32" || i.name=="v_mac_f32" || i.name=="v_mul_legacy_f32" || i.name=="v_sub_f32" || + i.name=="v_subrev_f32" || i.name=="v_fmac_f32" || i.name=="v_fmaak_f32" || + i.name=="v_rsq_f32" || i.name=="v_rcp_f32" || i.name=="v_sin_f32" || i.name=="v_cos_f32" || + i.name.substr(0,15)=="v_cvt_f32_ubyte" || i.name=="v_min_u32" || i.name=="v_max_f32" || + i.name=="v_mad_u32_u24" || i.name=="v_add3_u32" || i.name=="v_bfe_u32" || i.name=="v_mov_b32" || i.name=="v_add_nc_u32" || i.name=="v_lshlrev_b32" || + i.name=="v_lshrrev_b32" || i.name=="v_or_b32" || i.name=="v_and_b32" || + i.name=="v_xor_b32" || i.name=="v_lshl_add_u32" || i.name=="v_cvt_f32_u32" || i.name=="v_cvt_f32_i32" || + i.name=="v_mul_f32" || i.name=="v_add_f32" || i.name=="v_fma_f32")) { + const bool flat=i.name=="v_lshl_add_u32" && alu.operand32(i,i.src[0])==wave_number && + constant32(i,i.src[1])==(layout.wave32 ? 5u : 6u) && + whole_lane.count(alu.operand32(i,i.src[2])); + alu.arithmetic(i,state); + if (flat) linear_threads.insert(alu.read(i.dst)); + if (!full_exec) { + partial_writes.insert(i.dst); + if (i.name=="v_lshrrev_b64" || i.name=="v_lshlrev_b64") partial_writes.insert(i.dst+1); + } + } else refuse(pc,"unsupported mesh instruction or EXEC state: "+string(op.name)); + for (unsigned j=0;j<4;++j) { + if (!before_vec[j].empty() && !before_partial[j] && partial_writes.count(vec_dst+j)) { + auto &value=alu.graphics_registers.at(vec_dst+j); + auto u=uniform(value); + value=alu.select(lane_active,value,before_vec[j]); + if (!u.empty()) active_uniform[value]={lane_active,u}; + partial_writes.erase(vec_dst+j); + } + } + if (result_bound && *result_bound<UINT32_MAX && i.dst<106) { + auto it=alu.graphics_registers.find(i.dst); + if (it!=alu.graphics_registers.end() && !it->second.empty()) upper_bound[it->second]=*result_bound; + } + if (i.dst<106 && i.enc!=Encoding::Smem) remember_scalar(i.dst); + if (i.name=="v_mov_b32" && i.src[0]<106) remember_scalar(i.src[0]); + if (i.dst==261 || (i.enc==Encoding::Mubuf && i.dst==5)) exchanged_group.clear(); + pc=i.next; + } + refuse(pc,"unterminated mesh shader"); +} diff --git a/src/gfx1013_graphics_wqm.inl b/src/gfx1013_graphics_wqm.inl new file mode 100644 index 0000000000..38f1062df7 --- /dev/null +++ b/src/gfx1013_graphics_wqm.inl @@ -0,0 +1,305 @@ +// A numeric SGPR mask contains every guest lane, independently of the +// desktop wave size. A raster coverage mask instead has one known bit per +// invocation. Keep these two representations distinct. +// See victory-shader 9376fd6, structure.rs (Atom::Quad) and emit/lower.rs +// (wave_wide). The raster path below requires a quad-local live arm. +struct PixelWqm { + std::set<unsigned> packed, packed_reads, packed_restores; + std::set<unsigned> filters, quad_guards; + unsigned exact_restore = UINT_MAX; + string survivor; + // Cross-quad EXECZ (#2907): each write of the branch mask, taken from the + // filtered coverage or the whole-quad EXEC, or narrowing the mask again. + enum class MaskSource { survivors, whole_quad, narrowed }; + std::map<unsigned, MaskSource> vote_masks; + unsigned vote_wqm = UINT_MAX, vote_skip = UINT_MAX; + string vote_lane; + + static bool local(const Inst &i) { + return GraphicsMaskRegions::local_alu(i) || i.name == "s_waitcnt" || i.name == "s_nop" || + (i.dpp_control && !i.mirror_mask() && i.dst >= 256); + } + static bool is_wqm(const Inst &i, bool narrow) { return i.name == (narrow ? "s_wqm_b32" : "s_wqm_b64"); } + // Within a scalar-only diamond the lane bits can be inspected without + // assigning any desktop pixel a guest lane index. The original EXEC must + // be restored before committing vector results. + void numeric_guards(Program &p, bool narrow) { + const auto mov = narrow ? "s_mov_b32" : "s_mov_b64"; + std::multimap<unsigned, unsigned> incoming; + for (const auto &op : p.code) + if (op.branch()) + incoming.emplace(op.target(), op.pc); + for (size_t n = 0; n + 2 < p.code.size(); ++n) { + const auto &wqm = p.code[n]; + auto &skip = p.code[n + 1]; + if (!is_wqm(wqm, narrow) || wqm.dst != 126 || wqm.src[0] >= 106 || !skip.branch() || + (skip.op != 8 && skip.op != 9) || skip.target() <= skip.pc) + continue; + size_t end = n + 2; + std::vector<unsigned> reads; + for (; end < p.code.size(); ++end) { + const auto &i = p.code[end]; + if (i.name == mov && i.dst == 126) + break; + if (i.name == mov && i.src[0] == 126 && i.dst < 106) { + reads.push_back(i.pc); + continue; + } + if (i.branch() && i.target() > i.pc && (i.op == 2 || i.op == 4 || i.op == 5)) + continue; + if (i.name == "s_nop") + continue; + if ((i.enc != Encoding::Sop1 && i.enc != Encoding::Sop2 && i.enc != Encoding::Sopc && + i.enc != Encoding::Sopk) || + i.dst >= 106 || i.name.find("exec") != Name::npos || + std::any_of(i.src.begin(), i.src.end(), [](unsigned r) { return r == 126 || r == 127; })) + break; + } + if (end == p.code.size()) + continue; + const auto &restore = p.code[end]; + if (restore.name != mov || restore.dst != 126 || restore.src[0] >= 106 || skip.target() > restore.pc) + continue; + bool closed = true; + for (auto it = incoming.upper_bound(wqm.pc); it != incoming.end() && it->first <= restore.pc; ++it) + if (it->second < wqm.pc || it->second >= restore.pc) + closed = false; + for (size_t k = n + 1; k < end; ++k) + if (p.code[k].branch() && p.code[k].target() > restore.pc) + closed = false; + if (!closed) + continue; + packed.insert(wqm.pc); + packed_reads.insert(reads.begin(), reads.end()); + packed_restores.insert(restore.pc); + // SCC from WQM is exactly (lo | hi) != 0. No instruction + // between WQM and the branch can overwrite SCC. + skip.op = skip.op == 8 ? 4 : 5; + skip.name = skip.op == 4 ? "s_cbranch_scc0" : "s_cbranch_scc1"; + } + } + void raster_guard(Program &p, bool narrow) { + auto &code = p.code; + if (code.size() < 8) + return; + const size_t null = code.size() - 2; + if (code[null].enc != Encoding::Export || (code[null].a & 0x1fff) != 0x1890 || + code.back().name != "s_endpgm" || code[null - 1].name != "s_endpgm") + return; + std::vector<size_t> guards, updates; + unsigned mask = UINT_MAX; + for (size_t k = 0; k < null; ++k) { + if (!code[k].branch()) + continue; + if (k < 2 || code[k].op != 8 || code[k].target() != code[null].pc) + return; + const auto &wqm = code[k - 1]; + if (!is_wqm(wqm, narrow) || wqm.dst != 126 || wqm.src[0] > (narrow ? 105u : 104u) || + (!narrow && (wqm.src[0] & 1)) || (mask != UINT_MAX && mask != wqm.src[0])) + return; + mask = wqm.src[0]; + size_t f = k - 1; + while (f > 0 && local(code[f - 1])) + --f; + if (!f) + return; + const auto &keep = code[f - 1]; + if (keep.name != (narrow ? "s_andn2_b32" : "s_andn2_b64") || keep.dst != mask || keep.src[0] != mask || + keep.src[1] != 106) + return; + if (!guards.empty()) { + // Only intact quads reach another filter. Comparing again + // can remove more covered lanes, never revive a dead quad. + for (size_t j = guards.back() + 1; j < f - 1; ++j) + if (!local(code[j]) && !(code[j].enc == Encoding::Vopc && code[j].dst == 106 && + code[j].name.substr(0, 6) == "v_cmp_")) + return; + } + guards.push_back(k); + updates.push_back(f - 1); + } + if (guards.empty()) + return; + size_t r = guards.back() + 1; + while (r < null - 1 && local(code[r])) + ++r; + if (r >= null - 1 || code[r].name != (narrow ? "s_mov_b32" : "s_mov_b64") || code[r].dst != 126 || + code[r].src[0] != mask) + return; + for (size_t j = r + 1; j < null - 1; ++j) { + const auto &i = code[j]; + if (!(GraphicsMaskRegions::local_alu(i) || i.name == "s_waitcnt" || + (i.enc == Encoding::Export && ((i.a >> 4) & 63) < 8))) + return; + } + // Each surviving quad runs the same finite local instructions as in + // the nonempty guest wave. An empty quad has no observable result + // on either edge: the only exports use the restored survivor bits. + for (size_t j = 0; j < guards.size(); ++j) { + filters.insert(code[updates[j]].pc); + quad_guards.insert(code[guards[j] - 1].pc); + GraphicsMaskRegions::skip_proven(code[guards[j]]); + } + exact_restore = code[r].pc; + p.at.erase(code[null].pc); + p.at.erase(code.back().pc); + code.resize(null); + } + // A scalar instruction that neither reads nor writes EXEC or VCC. + static bool plain_scalar(const Inst &i) { + if (i.enc != Encoding::Sop1 && i.enc != Encoding::Sop2 && i.enc != Encoding::Sopc && + i.enc != Encoding::Sopk) + return false; + return (i.enc == Encoding::Sopc || i.dst < 106) && i.name.find("exec") == Name::npos && + std::none_of(i.src.begin(), i.src.end(), [](unsigned r) { return r >= 106 && r <= 127; }); + } + // Cross-quad EXECZ under WQM (#2907): + // s_mov sE, exec; s_wqm exec, exec + // one or more coverage filters v_cmp_* vcc; s_andn2 sE, sE, vcc + // v_cmp_* vcc; s_andn2 sM, sX, vcc sX = sE (survivors) or exec (whole quads) + // s_wqm exec, sM; s_cbranch_execz J the region writes only scalars + // J: s_mov exec, sE then a terminal colour export + // Lanes are skipped only when EXEC is zero in the whole guest wave, so the + // branch is a vote over the wave. It is lowered over the desktop wave, + // under the #2835 packing contract: a correct program cannot depend on + // which quads share a guest wave. The vote reads EXEC as modelled at the + // branch, OR-ed across the quad, so helper lanes count as on the guest. + void raster_vote(Program &p, bool narrow) { + auto &code = p.code; + const auto mov = narrow ? "s_mov_b32" : "s_mov_b64", andn2 = narrow ? "s_andn2_b32" : "s_andn2_b64"; + const unsigned last_reg = narrow ? 105u : 104u; + auto aligned = [&](unsigned r) { return r <= last_reg && (narrow || !(r & 1)); }; + auto overlaps = [&](const Inst &i, unsigned r) { + const unsigned width = i.name.find("_b64") != Name::npos ? 2 : 1; + return i.enc != Encoding::Sopc && i.dst < r + (narrow ? 1u : 2u) && r < i.dst + width; + }; + auto compare = [](const Inst &i) { + return i.enc == Encoding::Vopc && i.dst == 106 && i.name.substr(0, 6) == "v_cmp_" && + i.name.find("class") == Name::npos; + }; + if (!filters.empty() || code.size() < 10 || code[0].name != mov || code[0].src[0] != 126 || + !aligned(code[0].dst) || !is_wqm(code[1], narrow) || code[1].dst != 126 || code[1].src[0] != 126) + return; + const unsigned entry = code[0].dst; + size_t n = 2; + while (n + 1 < code.size() && !code[n].branch() && !(is_wqm(code[n], narrow) && code[n].dst == 126)) + ++n; + if (n + 1 >= code.size() || code[n].branch() || !code[n + 1].branch() || code[n + 1].op != 8 || + code[n + 1].target() <= code[n + 1].pc) + return; + const auto &wqm = code[n]; + auto &skip = code[n + 1]; + if (!aligned(wqm.src[0]) || wqm.src[0] == entry) + return; + const unsigned mask = wqm.src[0]; + // Before the vote: filters on sE, the mask write and lane-local work. + std::vector<unsigned> filter_pcs; + std::map<unsigned, MaskSource> mask_writes; + bool vcc_from_compare = false; + for (size_t k = 2; k < n; ++k) { + const auto &i = code[k]; + if (compare(i)) { + vcc_from_compare = true; + continue; + } + if (i.name == andn2 && i.src[1] == 106) { + if (!vcc_from_compare) + return; + if (i.dst == entry && i.src[0] == entry && mask_writes.empty()) + filter_pcs.push_back(i.pc); + else if (i.dst == mask && mask_writes.empty() && (i.src[0] == entry || i.src[0] == 126)) + mask_writes.emplace(i.pc, i.src[0] == 126 ? MaskSource::whole_quad : MaskSource::survivors); + else if (i.dst == mask && i.src[0] == mask && !mask_writes.empty()) + mask_writes.emplace(i.pc, MaskSource::narrowed); + else + return; + vcc_from_compare = false; + continue; + } + if (local(i) && !(i.dst < 256 && (i.dst == 106 || i.dst == 107))) + continue; + if (plain_scalar(i) && !overlaps(i, entry) && !overlaps(i, mask)) + continue; + return; + } + if (filter_pcs.empty() || mask_writes.empty()) + return; + // The region: from here on the shape is claimed, so refuse by name. + size_t r = n + 2; + for (; r < code.size() && !(code[r].name == mov && code[r].dst == 126); ++r) { + const auto &i = code[r]; + if (i.name == "s_nop" || i.name == "s_waitcnt") + continue; + if (i.branch()) + refuse(i.pc, "cross-quad EXECZ region contains a branch"); + if (i.name.find("s_setreg") == 0 || i.name.find("s_getreg") == 0) + refuse(i.pc, "cross-quad EXECZ region accesses a hardware register with " + string(i.name)); + if (!plain_scalar(i)) + refuse(i.pc, "cross-quad EXECZ region may only write scalars; " + string(i.name) + + " depends on the lanes the vote leaves out"); + if (overlaps(i, entry)) + refuse(i.pc, "cross-quad EXECZ region overwrites the saved coverage"); + } + if (r == code.size() || code[r].src[0] != entry || skip.target() != code[r].pc) + refuse(skip.pc, "cross-quad EXECZ must branch to the exact coverage restore"); + for (size_t j = r + 1; j < code.size(); ++j) { + const auto &i = code[j]; + if (i.name == "s_endpgm" && j + 1 == code.size()) + break; + if (!(GraphicsMaskRegions::local_alu(i) || i.name == "s_waitcnt" || + (i.enc == Encoding::Export && ((i.a >> 4) & 63) < 8))) + refuse(i.pc, "cross-quad EXECZ needs a terminal colour export after the restore"); + } + for (const auto &i : code) + if (i.branch() && i.pc != skip.pc) + refuse(i.pc, "cross-quad EXECZ program has another branch"); + filters.insert(filter_pcs.begin(), filter_pcs.end()); + vote_masks.insert(mask_writes.begin(), mask_writes.end()); + vote_wqm = wqm.pc; + vote_skip = skip.pc; + exact_restore = code[r].pc; + // SCC carries the vote; it is uniform over the desktop wave. + skip.op = 4; + skip.name = "s_cbranch_scc0"; + } + string expand(DxilModule &ir, const string &mask) const { + auto pair = ir.binary("or", mask, ir.binary("lshr", mask, "1")); + auto nibble = ir.binary("or", pair, ir.binary("lshr", pair, "2")); + return ir.binary("mul", ir.binary("and", nibble, "286331153"), "15"); + } + bool emit_packed(DirectCompute &alu, const Inst &i, bool narrow) const { + if (packed_restores.count(i.pc)) { + auto tag = alu.graphics_registers.find(512 + i.src[0]); + if (tag == alu.graphics_registers.end() || tag->second != "0") + refuse(i.pc, "numeric EXEC region requires saved raster entry coverage"); + alu.write(126, {}); + if (!narrow) + alu.write(127, {}); + return true; + } + if (packed_reads.count(i.pc)) { + if (!narrow && ((i.dst & 1) || i.dst > 104)) + refuse(i.pc, "unaligned EXEC read"); + alu.write(i.dst, alu.read(126)); + if (!narrow) + alu.write(i.dst + 1, alu.read(127)); + return true; + } + const bool to_exec = packed.count(i.pc) != 0; + const bool word = i.name == "s_wqm_b32"; + if (!to_exec && ((!word && i.name != "s_wqm_b64") || i.dst >= 106)) + return false; + if (!alu.graphics_predicate.empty()) + refuse(i.pc, "WQM scalar result inside a lane branch"); + if (i.src[0] >= 106 || (!word && ((i.src[0] | i.dst) & 1))) + refuse(i.pc, "numeric WQM requires an aligned general register source"); + auto low = expand(alu.ir, alu.operand32(i, i.src[0])); + auto high = word ? string{} : expand(alu.ir, alu.operand32(i, i.src[0] + 1)); + auto either = word ? low : alu.ir.binary("or", low, high); + alu.write(i.dst, low); + if (!word) + alu.write(i.dst + 1, high); + alu.write(128, alu.ir.value("zext i1 " + alu.cmp("ne", either, "0") + " to i32")); + return true; + } +}; diff --git a/src/gfx1013_isa.cpp b/src/gfx1013_isa.cpp new file mode 100644 index 0000000000..f909250898 --- /dev/null +++ b/src/gfx1013_isa.cpp @@ -0,0 +1,143 @@ +#include "gfx1013_isa.h" +#include <cstring> +#include <iterator> +#include <stdexcept> +#include <string> + +namespace x2w::gfx1013 { +namespace { +#include "gfx1013_isa_tables.inl" +struct Names { + const char *const *data; + size_t size; +}; +template <size_t N> constexpr Names names(const char *const (&a)[N]) { return {a, N}; } +constexpr Names table[]{names(sopp_names), names(sop1_names), names(sop2_names), names(sopc_names), + names(sopk_names), names(vop1_names), names(vop2_names), names(vopc_names), + names(vop3_names), names(vop3p_names), names(vintrp_names), names(smem_names), + names(mubuf_names), names(mtbuf_names), names(mimg_names), names(ds_names), + names(flat_names), names(global_names), names(scratch_names)}; +std::string_view lookup(Form form, unsigned index) { + if (form == Form::exp) + return "exp"; + const auto &t = table[static_cast<unsigned>(form)]; + return index < t.size && t.data[index] ? t.data[index] : ""; +} +} // namespace +Instruction instruction(std::string_view code, unsigned pc) { + auto word = [&](unsigned index) { + uint64_t at = uint64_t(pc) + 4 * index; + if ((pc & 3) || at > code.size() || code.size() - at < 4) + throw std::runtime_error("truncated or misaligned gfx1013 instruction at byte " + std::to_string(pc)); + uint32_t n; + std::memcpy(&n, code.data() + at, 4); + return n; + }; + const auto a = word(0); + const unsigned top = a >> 26, major = a >> 25; + Form form; + unsigned op, count = 1; + if (!(a >> 31)) { + form = major == 63 ? Form::vop1 : major == 62 ? Form::vopc : Form::vop2; + op = form == Form::vop1 ? (a >> 9) & 255 : form == Form::vopc ? (a >> 17) & 255 : major; + const auto src = a & 511; + bool extension = src == 233 || src == 234 || src == 249 || src == 250 || src == 255; + if (form == Form::vop2) { + const auto name = lookup(form, op); + extension |= name.find("madmk") != name.npos || name.find("madak") != name.npos || + name.find("fmamk") != name.npos || name.find("fmaak") != name.npos; + } + count += extension; + } else if ((a >> 30) == 2) { + switch (a >> 23) { + case 0x17d: + form = Form::sop1; + op = (a >> 8) & 255; + count += (a & 255) == 255; + break; + case 0x17e: + form = Form::sopc; + op = (a >> 16) & 127; + count += (a & 255) == 255 || ((a >> 8) & 255) == 255; + break; + case 0x17f: + form = Form::sopp; + op = (a >> 16) & 127; + break; + default: + if ((a >> 28) == 11) { + form = Form::sopk; + op = (a >> 23) & 31; + count += lookup(form, op) == "s_setreg_imm32_b32"; + } else { + form = Form::sop2; + op = (a >> 23) & 127; + count += (a & 255) == 255 || ((a >> 8) & 255) == 255; + } + } + } else { + count = 2; + switch (top) { + case 0x32: + form = Form::vintrp; + op = (a >> 16) & 3; + count = 1; + break; + case 0x33: + case 0x35: { + form = top == 0x33 ? Form::vop3p : Form::vop3; + op = (a >> 16) & (top == 0x33 ? 127 : 1023); + auto b = word(1); + count += ((b & 511) == 255 || ((b >> 9) & 511) == 255 || ((b >> 18) & 511) == 255); + break; + } + case 0x36: + form = Form::ds; + op = (a >> 18) & 255; + break; + case 0x37: { + unsigned segment = (a >> 14) & 3; + if (segment == 3) + throw std::runtime_error("reserved FLAT segment at byte " + std::to_string(pc)); + form = segment == 0 ? Form::flat : segment == 1 ? Form::scratch : Form::global; + op = (a >> 18) & 127; + break; + } + case 0x38: + form = Form::mubuf; + op = (a >> 18) & 255; + break; + case 0x3a: + form = Form::mtbuf; + op = ((a >> 16) & 7) | ((word(1) >> 18) & 8); + break; + case 0x3c: + form = Form::mimg; + op = ((a >> 18) & 127) | ((a & 1) << 7); + count += (a >> 1) & 3; + break; + case 0x3d: + form = Form::smem; + op = (a >> 18) & 255; + break; + case 0x3e: + form = Form::exp; + op = 0; + break; + default: + throw std::runtime_error("unknown gfx1013 instruction format at byte " + std::to_string(pc)); + } + } + word(count - 1); + auto name = lookup(form, op); + if (form == Form::vop3 && name.empty()) { + if (op < 0x100) + name = lookup(Form::vopc, op); + else if (op < 0x140) + name = lookup(Form::vop2, op - 0x100); + else if (op >= 0x180 && op < 0x200) + name = lookup(Form::vop1, op - 0x180); + } + return {form, op, 4 * count, name}; +} +} // namespace x2w::gfx1013 diff --git a/src/gfx1013_isa.h b/src/gfx1013_isa.h new file mode 100644 index 0000000000..1200dd314f --- /dev/null +++ b/src/gfx1013_isa.h @@ -0,0 +1,34 @@ +#pragma once +#include <cstdint> +#include <string_view> + +namespace x2w::gfx1013 { +enum class Form { + sopp, + sop1, + sop2, + sopc, + sopk, + vop1, + vop2, + vopc, + vop3, + vop3p, + vintrp, + smem, + mubuf, + mtbuf, + mimg, + ds, + flat, + global, + scratch, + exp +}; +struct Instruction { + Form form; + unsigned opcode, size; + std::string_view name; +}; +Instruction instruction(std::string_view code, unsigned pc); +} // namespace x2w::gfx1013 diff --git a/src/gfx1013_isa_tables.inl b/src/gfx1013_isa_tables.inl new file mode 100644 index 0000000000..8e68357a17 --- /dev/null +++ b/src/gfx1013_isa_tables.inl @@ -0,0 +1,748 @@ +// 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. +// + +// Generated by tools/startup/import_gfx10_tables.py. +// The secondary entries come from X2W's gfx1013 disassembler. + +constexpr const char* sopp_names[] = { + "s_nop", "s_endpgm", "s_branch", "s_wakeup", + "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", + "s_cbranch_execz", "s_cbranch_execnz", "s_barrier", "s_setkill", + "s_waitcnt", "s_sethalt", "s_sleep", "s_setprio", + "s_sendmsg", "s_sendmsghalt", "s_trap", "s_icache_inv", + "s_incperflevel", "s_decperflevel", "s_ttracedata", "s_cbranch_cdbgsys", + "s_cbranch_cdbguser", "s_cbranch_cdbgsys_or_user", "s_cbranch_cdbgsys_and_user", "s_endpgm_saved", + nullptr, nullptr, "s_endpgm_ordered_ps_done", "s_code_end", + "s_inst_prefetch", "s_clause", "s_wait_idle", "s_waitcnt_depctr", + "s_round_mode", "s_denorm_mode", nullptr, nullptr, + "s_ttracedata_imm", +}; + +constexpr const char* sop1_names[] = { + nullptr, nullptr, nullptr, "s_mov_b32", + "s_mov_b64", "s_cmov_b32", "s_cmov_b64", "s_not_b32", + "s_not_b64", "s_wqm_b32", "s_wqm_b64", "s_brev_b32", + "s_brev_b64", "s_bcnt0_i32_b32", "s_bcnt0_i32_b64", "s_bcnt1_i32_b32", + "s_bcnt1_i32_b64", "s_ff0_i32_b32", "s_ff0_i32_b64", "s_ff1_i32_b32", + "s_ff1_i32_b64", "s_flbit_i32_b32", "s_flbit_i32_b64", "s_flbit_i32", + "s_flbit_i32_i64", "s_sext_i32_i8", "s_sext_i32_i16", "s_bitset0_b32", + "s_bitset0_b64", "s_bitset1_b32", "s_bitset1_b64", "s_getpc_b64", + "s_setpc_b64", "s_swappc_b64", "s_rfe_b64", nullptr, + "s_and_saveexec_b64", "s_or_saveexec_b64", "s_xor_saveexec_b64", "s_andn2_saveexec_b64", + "s_orn2_saveexec_b64", "s_nand_saveexec_b64", "s_nor_saveexec_b64", "s_xnor_saveexec_b64", + "s_quadmask_b32", "s_quadmask_b64", "s_movrels_b32", "s_movrels_b64", + "s_movreld_b32", "s_movreld_b64", nullptr, nullptr, + "s_abs_i32", "s_mov_fed_b32", nullptr, "s_andn1_saveexec_b64", + "s_orn1_saveexec_b64", "s_andn1_wrexec_b64", "s_andn2_wrexec_b64", "s_bitreplicate_b64_b32", + "s_and_saveexec_b32", "s_or_saveexec_b32", "s_xor_saveexec_b32", "s_andn2_saveexec_b32", + "s_orn2_saveexec_b32", "s_nand_saveexec_b32", "s_nor_saveexec_b32", "s_xnor_saveexec_b32", + "s_andn1_saveexec_b32", "s_orn1_saveexec_b32", "s_andn1_wrexec_b32", "s_andn2_wrexec_b32", + nullptr, "s_movrelsd_2_b32", +}; + +constexpr const char* sop2_names[] = { + "s_add_u32", "s_sub_u32", "s_add_i32", "s_sub_i32", + "s_addc_u32", "s_subb_u32", "s_min_i32", "s_min_u32", + "s_max_i32", "s_max_u32", "s_cselect_b32", "s_cselect_b64", + nullptr, nullptr, "s_and_b32", "s_and_b64", + "s_or_b32", "s_or_b64", "s_xor_b32", "s_xor_b64", + "s_andn2_b32", "s_andn2_b64", "s_orn2_b32", "s_orn2_b64", + "s_nand_b32", "s_nand_b64", "s_nor_b32", "s_nor_b64", + "s_xnor_b32", "s_xnor_b64", "s_lshl_b32", "s_lshl_b64", + "s_lshr_b32", "s_lshr_b64", "s_ashr_i32", "s_ashr_i64", + "s_bfm_b32", "s_bfm_b64", "s_mul_i32", "s_bfe_u32", + "s_bfe_i32", "s_bfe_u64", "s_bfe_i64", nullptr, + "s_absdiff_i32", nullptr, "s_lshl1_add_u32", "s_lshl2_add_u32", + "s_lshl3_add_u32", "s_lshl4_add_u32", "s_pack_ll_b32_b16", "s_pack_lh_b32_b16", + "s_pack_hh_b32_b16", "s_mul_hi_u32", "s_mul_hi_i32", +}; + +constexpr const char* sopc_names[] = { + "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", + "s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64", + nullptr, nullptr, "s_cmp_eq_u64", "s_cmp_lg_u64", +}; + +constexpr const char* sopk_names[] = { + "s_movk_i32", "s_version", "s_cmovk_i32", "s_cmpk_eq_i32", + "s_cmpk_lg_i32", "s_cmpk_gt_i32", "s_cmpk_ge_i32", "s_cmpk_lt_i32", + "s_cmpk_le_i32", "s_cmpk_eq_u32", "s_cmpk_lg_u32", "s_cmpk_gt_u32", + "s_cmpk_ge_u32", "s_cmpk_lt_u32", "s_cmpk_le_u32", "s_addk_i32", + "s_mulk_i32", nullptr, "s_getreg_b32", "s_setreg_b32", + nullptr, "s_setreg_imm32_b32", "s_call_b64", "s_waitcnt_vscnt", + "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", "s_subvector_loop_begin", + "s_subvector_loop_end", +}; + +constexpr const char* vop1_names[] = { + "v_nop", "v_mov_b32", "v_readfirstlane_b32", "v_cvt_i32_f64", + "v_cvt_f64_i32", "v_cvt_f32_i32", "v_cvt_f32_u32", "v_cvt_u32_f32", + "v_cvt_i32_f32", nullptr, "v_cvt_f16_f32", "v_cvt_f32_f16", + "v_cvt_rpi_i32_f32", "v_cvt_flr_i32_f32", "v_cvt_off_f32_i4", "v_cvt_f32_f64", + "v_cvt_f64_f32", "v_cvt_f32_ubyte0", "v_cvt_f32_ubyte1", "v_cvt_f32_ubyte2", + "v_cvt_f32_ubyte3", "v_cvt_u32_f64", "v_cvt_f64_u32", "v_trunc_f64", + "v_ceil_f64", "v_rndne_f64", "v_floor_f64", "v_pipeflush", + nullptr, nullptr, nullptr, nullptr, + "v_fract_f32", "v_trunc_f32", "v_ceil_f32", "v_rndne_f32", + "v_floor_f32", "v_exp_f32", nullptr, "v_log_f32", + nullptr, nullptr, "v_rcp_f32", "v_rcp_iflag_f32", + nullptr, nullptr, "v_rsq_f32", "v_rcp_f64", + nullptr, "v_rsq_f64", nullptr, "v_sqrt_f32", + "v_sqrt_f64", "v_sin_f32", "v_cos_f32", "v_not_b32", + "v_bfrev_b32", "v_ffbh_u32", "v_ffbl_b32", "v_ffbh_i32", + "v_frexp_exp_i32_f64", "v_frexp_mant_f64", "v_fract_f64", "v_frexp_exp_i32_f32", + "v_frexp_mant_f32", "v_clrexcp", "v_movreld_b32", "v_movrels_b32", + "v_movrelsd_b32", nullptr, nullptr, nullptr, + "v_movrelsd_2_b32", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_cvt_f16_u16", "v_cvt_f16_i16", "v_cvt_u16_f16", "v_cvt_i16_f16", + "v_rcp_f16", "v_sqrt_f16", "v_rsq_f16", "v_log_f16", + "v_exp_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_floor_f16", + "v_ceil_f16", "v_trunc_f16", "v_rndne_f16", "v_fract_f16", + "v_sin_f16", "v_cos_f16", "v_sat_pk_u8_i16", "v_cvt_norm_i16_f16", + "v_cvt_norm_u16_f16", "v_swap_b32", nullptr, nullptr, + "v_swaprel_b32", +}; + +constexpr const char* vop2_names[] = { + nullptr, "v_cndmask_b32", "v_dot2c_f32_f16", "v_add_f32", + "v_sub_f32", "v_subrev_f32", "v_mac_legacy_f32", "v_mul_legacy_f32", + "v_mul_f32", "v_mul_i32_i24", "v_mul_hi_i32_i24", "v_mul_u32_u24", + "v_mul_hi_u32_u24", "v_dot4c_i32_i8", nullptr, "v_min_f32", + "v_max_f32", "v_min_i32", "v_max_i32", "v_min_u32", + "v_max_u32", nullptr, "v_lshrrev_b32", nullptr, + "v_ashrrev_i32", nullptr, "v_lshlrev_b32", "v_and_b32", + "v_or_b32", "v_xor_b32", "v_xnor_b32", "v_mac_f32", + "v_madmk_f32", "v_madak_f32", nullptr, nullptr, + nullptr, "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", + "v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32", "v_fmac_f32", + "v_fmamk_f32", "v_fmaak_f32", nullptr, "v_cvt_pkrtz_f16_f32", + nullptr, nullptr, "v_add_f16", "v_sub_f16", + "v_subrev_f16", "v_mul_f16", "v_fmac_f16", "v_fmamk_f16", + "v_fmaak_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", + "v_pk_fmac_f16", +}; + +constexpr const char* vopc_names[] = { + "v_cmp_f_f32", "v_cmp_lt_f32", "v_cmp_eq_f32", "v_cmp_le_f32", + "v_cmp_gt_f32", "v_cmp_lg_f32", "v_cmp_ge_f32", "v_cmp_o_f32", + "v_cmp_u_f32", "v_cmp_nge_f32", "v_cmp_nlg_f32", "v_cmp_ngt_f32", + "v_cmp_nle_f32", "v_cmp_neq_f32", "v_cmp_nlt_f32", "v_cmp_tru_f32", + "v_cmpx_f_f32", "v_cmpx_lt_f32", "v_cmpx_eq_f32", "v_cmpx_le_f32", + "v_cmpx_gt_f32", "v_cmpx_lg_f32", "v_cmpx_ge_f32", "v_cmpx_o_f32", + "v_cmpx_u_f32", "v_cmpx_nge_f32", "v_cmpx_nlg_f32", "v_cmpx_ngt_f32", + "v_cmpx_nle_f32", "v_cmpx_neq_f32", "v_cmpx_nlt_f32", "v_cmpx_tru_f32", + "v_cmp_f_f64", "v_cmp_lt_f64", "v_cmp_eq_f64", "v_cmp_le_f64", + "v_cmp_gt_f64", "v_cmp_lg_f64", "v_cmp_ge_f64", "v_cmp_o_f64", + "v_cmp_u_f64", "v_cmp_nge_f64", "v_cmp_nlg_f64", "v_cmp_ngt_f64", + "v_cmp_nle_f64", "v_cmp_neq_f64", "v_cmp_nlt_f64", "v_cmp_tru_f64", + "v_cmpx_f_f64", "v_cmpx_lt_f64", "v_cmpx_eq_f64", "v_cmpx_le_f64", + "v_cmpx_gt_f64", "v_cmpx_lg_f64", "v_cmpx_ge_f64", "v_cmpx_o_f64", + "v_cmpx_u_f64", "v_cmpx_nge_f64", "v_cmpx_nlg_f64", "v_cmpx_ngt_f64", + "v_cmpx_nle_f64", "v_cmpx_neq_f64", "v_cmpx_nlt_f64", "v_cmpx_tru_f64", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_cmp_f_i32", "v_cmp_lt_i32", "v_cmp_eq_i32", "v_cmp_le_i32", + "v_cmp_gt_i32", "v_cmp_ne_i32", "v_cmp_ge_i32", "v_cmp_t_i32", + "v_cmp_class_f32", "v_cmp_lt_i16", "v_cmp_eq_i16", "v_cmp_le_i16", + "v_cmp_gt_i16", "v_cmp_ne_i16", "v_cmp_ge_i16", "v_cmp_class_f16", + "v_cmpx_f_i32", "v_cmpx_lt_i32", "v_cmpx_eq_i32", "v_cmpx_le_i32", + "v_cmpx_gt_i32", "v_cmpx_ne_i32", "v_cmpx_ge_i32", "v_cmpx_t_i32", + "v_cmpx_class_f32", "v_cmpx_lt_i16", "v_cmpx_eq_i16", "v_cmpx_le_i16", + "v_cmpx_gt_i16", "v_cmpx_ne_i16", "v_cmpx_ge_i16", "v_cmpx_class_f16", + "v_cmp_f_i64", "v_cmp_lt_i64", "v_cmp_eq_i64", "v_cmp_le_i64", + "v_cmp_gt_i64", "v_cmp_ne_i64", "v_cmp_ge_i64", "v_cmp_t_i64", + "v_cmp_class_f64", "v_cmp_lt_u16", "v_cmp_eq_u16", "v_cmp_le_u16", + "v_cmp_gt_u16", "v_cmp_ne_u16", "v_cmp_ge_u16", nullptr, + "v_cmpx_f_i64", "v_cmpx_lt_i64", "v_cmpx_eq_i64", "v_cmpx_le_i64", + "v_cmpx_gt_i64", "v_cmpx_ne_i64", "v_cmpx_ge_i64", "v_cmpx_t_i64", + "v_cmpx_class_f64", "v_cmpx_lt_u16", "v_cmpx_eq_u16", "v_cmpx_le_u16", + "v_cmpx_gt_u16", "v_cmpx_ne_u16", "v_cmpx_ge_u16", nullptr, + "v_cmp_f_u32", "v_cmp_lt_u32", "v_cmp_eq_u32", "v_cmp_le_u32", + "v_cmp_gt_u32", "v_cmp_ne_u32", "v_cmp_ge_u32", "v_cmp_t_u32", + "v_cmp_f_f16", "v_cmp_lt_f16", "v_cmp_eq_f16", "v_cmp_le_f16", + "v_cmp_gt_f16", "v_cmp_lg_f16", "v_cmp_ge_f16", "v_cmp_o_f16", + "v_cmpx_f_u32", "v_cmpx_lt_u32", "v_cmpx_eq_u32", "v_cmpx_le_u32", + "v_cmpx_gt_u32", "v_cmpx_ne_u32", "v_cmpx_ge_u32", "v_cmpx_t_u32", + "v_cmpx_f_f16", "v_cmpx_lt_f16", "v_cmpx_eq_f16", "v_cmpx_le_f16", + "v_cmpx_gt_f16", "v_cmpx_lg_f16", "v_cmpx_ge_f16", "v_cmpx_o_f16", + "v_cmp_f_u64", "v_cmp_lt_u64", "v_cmp_eq_u64", "v_cmp_le_u64", + "v_cmp_gt_u64", "v_cmp_ne_u64", "v_cmp_ge_u64", "v_cmp_t_u64", + "v_cmp_u_f16", "v_cmp_nge_f16", "v_cmp_nlg_f16", "v_cmp_ngt_f16", + "v_cmp_nle_f16", "v_cmp_neq_f16", "v_cmp_nlt_f16", "v_cmp_tru_f16", + "v_cmpx_f_u64", "v_cmpx_lt_u64", "v_cmpx_eq_u64", "v_cmpx_le_u64", + "v_cmpx_gt_u64", "v_cmpx_ne_u64", "v_cmpx_ge_u64", "v_cmpx_t_u64", + "v_cmpx_u_f16", "v_cmpx_nge_f16", "v_cmpx_nlg_f16", "v_cmpx_ngt_f16", + "v_cmpx_nle_f16", "v_cmpx_neq_f16", "v_cmpx_nlt_f16", "v_cmpx_tru_f16", +}; + +constexpr const char* vop3_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_add_co_ci_u32", "v_sub_co_ci_u32", "v_subrev_co_ci_u32", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_mad_legacy_f32", "v_mad_f32", "v_mad_i32_i24", "v_mad_u32_u24", + "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32", + "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_fma_f32", + "v_fma_f64", "v_lerp_u8", "v_alignbit_b32", "v_alignbyte_b32", + "v_mullit_f32", "v_min3_f32", "v_min3_i32", "v_min3_u32", + "v_max3_f32", "v_max3_i32", "v_max3_u32", "v_med3_f32", + "v_med3_i32", "v_med3_u32", "v_sad_u8", "v_sad_hi_u8", + "v_sad_u16", "v_sad_u32", "v_cvt_pk_u8_f32", "v_div_fixup_f32", + "v_div_fixup_f64", nullptr, nullptr, nullptr, + "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_div_scale_f32", "v_div_scale_f64", "v_div_fmas_f32", + "v_div_fmas_f64", "v_msad_u8", "v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8", + "v_trig_preop_f64", "v_mqsad_u32_u8", "v_mad_u64_u32", "v_mad_i64_i32", + "v_xor3_b32", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "v_interp_mov_f32", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, "v_lshlrev_b64", + "v_lshrrev_b64", "v_ashrrev_i64", nullptr, "v_add_nc_u16", + "v_sub_nc_u16", "v_mul_lo_u16", nullptr, "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_pack_b32_f16", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", + "v_lshlrev_b16", nullptr, nullptr, nullptr, + nullptr, "v_subrev_co_u32", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_mad_u16", nullptr, "v_interp_p1ll_f16", "v_interp_p1lv_f16", + "v_perm_b32", "v_xad_u32", "v_lshl_add_u32", "v_add_lshl_u32", + nullptr, nullptr, nullptr, "v_fma_f16", + nullptr, nullptr, nullptr, nullptr, + nullptr, "v_min3_f16", "v_min3_i16", "v_min3_u16", + "v_max3_f16", "v_max3_i16", "v_max3_u16", "v_med3_f16", + "v_med3_i16", "v_med3_u16", "v_interp_p2_f16", nullptr, + nullptr, nullptr, "v_mad_i16", "v_div_fixup_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", nullptr, + "v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_pk_u16_u32", "v_cvt_pk_i16_i32", + nullptr, "v_add3_u32", nullptr, "v_lshl_or_b32", + nullptr, "v_and_or_b32", "v_or3_b32", "v_mad_u32_u16", + nullptr, "v_mad_i32_i16", "v_sub_nc_i32", "v_permlane16_b32", + "v_permlanex16_b32", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, "v_add_nc_i32", +}; + +constexpr const char* vop3p_names[] = { + "v_pk_mad_i16", "v_pk_mul_lo_u16", "v_pk_add_i16", "v_pk_sub_i16", + "v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16", "v_pk_max_i16", + "v_pk_min_i16", "v_pk_mad_u16", "v_pk_add_u16", "v_pk_sub_u16", + "v_pk_max_u16", "v_pk_min_u16", "v_pk_fma_f16", "v_pk_add_f16", + "v_pk_mul_f16", "v_pk_min_f16", "v_pk_max_f16", "v_dot2_f32_f16", + "v_dot2_i32_i16", "v_dot2_u32_u16", "v_dot4_i32_i8", "v_dot4_u32_u8", + "v_dot8_i32_i4", "v_dot8_u32_u4", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16", +}; + +constexpr const char* vintrp_names[] = { + "v_interp_p1_f32", "v_interp_p2_f32", "v_interp_mov_f32", +}; + +constexpr const char* smem_names[] = { + "s_load_dword", "s_load_dwordx2", "s_load_dwordx4", "s_load_dwordx8", + "s_load_dwordx16", "s_scratch_load_dword", "s_scratch_load_dwordx2", "s_scratch_load_dwordx4", + "s_buffer_load_dword", "s_buffer_load_dwordx2", "s_buffer_load_dwordx4", "s_buffer_load_dwordx8", + "s_buffer_load_dwordx16", nullptr, nullptr, nullptr, + "s_store_dword", "s_store_dwordx2", "s_store_dwordx4", nullptr, + nullptr, "s_scratch_store_dword", "s_scratch_store_dwordx2", "s_scratch_store_dwordx4", + "s_buffer_store_dword", "s_buffer_store_dwordx2", "s_buffer_store_dwordx4", nullptr, + nullptr, nullptr, nullptr, "s_gl1_inv", + "s_dcache_inv", "s_dcache_wb", nullptr, nullptr, + "s_memtime", "s_memrealtime", "s_atc_probe", "s_atc_probe_buffer", + "s_dcache_discard", "s_dcache_discard_x2", "s_get_waveid_in_workgroup", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_buffer_atomic_swap", "s_buffer_atomic_cmpswap", "s_buffer_atomic_add", "s_buffer_atomic_sub", + "s_buffer_atomic_smin", "s_buffer_atomic_umin", "s_buffer_atomic_smax", "s_buffer_atomic_umax", + "s_buffer_atomic_and", "s_buffer_atomic_or", "s_buffer_atomic_xor", "s_buffer_atomic_inc", + "s_buffer_atomic_dec", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_buffer_atomic_swap_x2", "s_buffer_atomic_cmpswap_x2", "s_buffer_atomic_add_x2", "s_buffer_atomic_sub_x2", + "s_buffer_atomic_smin_x2", "s_buffer_atomic_umin_x2", "s_buffer_atomic_smax_x2", "s_buffer_atomic_umax_x2", + "s_buffer_atomic_and_x2", "s_buffer_atomic_or_x2", "s_buffer_atomic_xor_x2", "s_buffer_atomic_inc_x2", + "s_buffer_atomic_dec_x2", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_atomic_swap", "s_atomic_cmpswap", "s_atomic_add", "s_atomic_sub", + "s_atomic_smin", "s_atomic_umin", "s_atomic_smax", "s_atomic_umax", + "s_atomic_and", "s_atomic_or", "s_atomic_xor", "s_atomic_inc", + "s_atomic_dec", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "s_atomic_swap_x2", "s_atomic_cmpswap_x2", "s_atomic_add_x2", "s_atomic_sub_x2", + "s_atomic_smin_x2", "s_atomic_umin_x2", "s_atomic_smax_x2", "s_atomic_umax_x2", + "s_atomic_and_x2", "s_atomic_or_x2", "s_atomic_xor_x2", "s_atomic_inc_x2", + "s_atomic_dec_x2", +}; + +constexpr const char* mubuf_names[] = { + "buffer_load_format_x", "buffer_load_format_xy", "buffer_load_format_xyz", "buffer_load_format_xyzw", + "buffer_store_format_x", "buffer_store_format_xy", "buffer_store_format_xyz", "buffer_store_format_xyzw", + "buffer_load_ubyte", "buffer_load_sbyte", "buffer_load_ushort", "buffer_load_sshort", + "buffer_load_dword", "buffer_load_dwordx2", "buffer_load_dwordx4", "buffer_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_store_byte", "buffer_store_byte_d16_hi", "buffer_store_short", "buffer_store_short_d16_hi", + "buffer_store_dword", "buffer_store_dwordx2", "buffer_store_dwordx4", "buffer_store_dwordx3", + "buffer_load_ubyte_d16", "buffer_load_ubyte_d16_hi", "buffer_load_sbyte_d16", "buffer_load_sbyte_d16_hi", + "buffer_load_short_d16", "buffer_load_short_d16_hi", "buffer_load_format_d16_hi_x", "buffer_store_format_d16_hi_x", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_atomic_swap", "buffer_atomic_cmpswap", "buffer_atomic_add", "buffer_atomic_sub", + "buffer_atomic_csub", "buffer_atomic_smin", "buffer_atomic_umin", "buffer_atomic_smax", + "buffer_atomic_umax", "buffer_atomic_and", "buffer_atomic_or", "buffer_atomic_xor", + "buffer_atomic_inc", "buffer_atomic_dec", "buffer_atomic_fcmpswap", "buffer_atomic_fmin", + "buffer_atomic_fmax", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_atomic_swap_x2", "buffer_atomic_cmpswap_x2", "buffer_atomic_add_x2", "buffer_atomic_sub_x2", + nullptr, "buffer_atomic_smin_x2", "buffer_atomic_umin_x2", "buffer_atomic_smax_x2", + "buffer_atomic_umax_x2", "buffer_atomic_and_x2", "buffer_atomic_or_x2", "buffer_atomic_xor_x2", + "buffer_atomic_inc_x2", "buffer_atomic_dec_x2", "buffer_atomic_fcmpswap_x2", "buffer_atomic_fmin_x2", + "buffer_atomic_fmax_x2", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, "buffer_gl0_inv", "buffer_gl1_inv", nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "buffer_load_format_d16_x", "buffer_load_format_d16_xy", "buffer_load_format_d16_xyz", "buffer_load_format_d16_xyzw", + "buffer_store_format_d16_x", "buffer_store_format_d16_xy", "buffer_store_format_d16_xyz", "buffer_store_format_d16_xyzw", +}; + +constexpr const char* mtbuf_names[] = { + "tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", "tbuffer_load_format_xyzw", + "tbuffer_store_format_x", "tbuffer_store_format_xy", "tbuffer_store_format_xyz", "tbuffer_store_format_xyzw", + "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw", + "tbuffer_store_format_d16_x", "tbuffer_store_format_d16_xy", "tbuffer_store_format_d16_xyz", "tbuffer_store_format_d16_xyzw", +}; + +constexpr const char* mimg_names[] = { + "image_load", "image_load_mip", "image_load_pck", "image_load_pck_sgn", + "image_load_mip_pck", "image_load_mip_pck_sgn", nullptr, nullptr, + "image_store", "image_store_mip", "image_store_pck", "image_store_mip_pck", + nullptr, nullptr, "image_get_resinfo", "image_atomic_swap", + "image_atomic_cmpswap", "image_atomic_add", "image_atomic_sub", nullptr, + "image_atomic_smin", "image_atomic_umin", "image_atomic_smax", "image_atomic_umax", + "image_atomic_and", "image_atomic_or", "image_atomic_xor", "image_atomic_inc", + "image_atomic_dec", "image_atomic_fcmpswap", "image_atomic_fmin", "image_atomic_fmax", + "image_sample", "image_sample_cl", "image_sample_d", "image_sample_d_cl", + "image_sample_l", "image_sample_b", "image_sample_b_cl", "image_sample_lz", + "image_sample_c", "image_sample_c_cl", "image_sample_c_d", "image_sample_c_d_cl", + "image_sample_c_l", "image_sample_c_b", "image_sample_c_b_cl", "image_sample_c_lz", + "image_sample_o", "image_sample_cl_o", "image_sample_d_o", "image_sample_d_cl_o", + "image_sample_l_o", "image_sample_b_o", "image_sample_b_cl_o", "image_sample_lz_o", + "image_sample_c_o", "image_sample_c_cl_o", "image_sample_c_d_o", "image_sample_c_d_cl_o", + "image_sample_c_l_o", "image_sample_c_b_o", "image_sample_c_b_cl_o", "image_sample_c_lz_o", + "image_gather4", "image_gather4_cl", nullptr, nullptr, + "image_gather4_l", "image_gather4_b", "image_gather4_b_cl", "image_gather4_lz", + "image_gather4_c", "image_gather4_c_cl", nullptr, nullptr, + "image_gather4_c_l", "image_gather4_c_b", "image_gather4_c_b_cl", "image_gather4_c_lz", + "image_gather4_o", "image_gather4_cl_o", nullptr, nullptr, + "image_gather4_l_o", "image_gather4_b_o", "image_gather4_b_cl_o", "image_gather4_lz_o", + "image_gather4_c_o", "image_gather4_c_cl_o", nullptr, nullptr, + "image_gather4_c_l_o", "image_gather4_c_b_o", "image_gather4_c_b_cl_o", "image_gather4_c_lz_o", + "image_get_lod", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "image_sample_cd", "image_sample_cd_cl", "image_sample_c_cd", "image_sample_c_cd_cl", + "image_sample_cd_o", "image_sample_cd_cl_o", "image_sample_c_cd_o", "image_sample_c_cd_cl_o", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "image_msaa_load", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_d_g16", "image_sample_d_cl_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_c_d_g16", "image_sample_c_d_cl_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_d_o_g16", "image_sample_d_cl_o_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_sample_c_d_o_g16", "image_sample_c_d_cl_o_g16", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "image_bvh_intersect_ray", "image_bvh64_intersect_ray", + "image_sample_cd_g16", "image_sample_cd_cl_g16", "image_sample_c_cd_g16", "image_sample_c_cd_cl_g16", + "image_sample_cd_o_g16", "image_sample_cd_cl_o_g16", "image_sample_c_cd_o_g16", "image_sample_c_cd_cl_o_g16", +}; + +constexpr const char* ds_names[] = { + "ds_add_u32", "ds_sub_u32", "ds_rsub_u32", "ds_inc_u32", + "ds_dec_u32", "ds_min_i32", "ds_max_i32", "ds_min_u32", + "ds_max_u32", "ds_and_b32", "ds_or_b32", "ds_xor_b32", + "ds_mskor_b32", "ds_write_b32", "ds_write2_b32", "ds_write2st64_b32", + "ds_cmpst_b32", "ds_cmpst_f32", "ds_min_f32", "ds_max_f32", + "ds_nop", "ds_add_f32", nullptr, nullptr, + "ds_gws_sema_release_all", "ds_gws_init", "ds_gws_sema_v", "ds_gws_sema_br", + "ds_gws_sema_p", "ds_gws_barrier", "ds_write_b8", "ds_write_b16", + "ds_add_rtn_u32", "ds_sub_rtn_u32", "ds_rsub_rtn_u32", "ds_inc_rtn_u32", + "ds_dec_rtn_u32", "ds_min_rtn_i32", "ds_max_rtn_i32", "ds_min_rtn_u32", + "ds_max_rtn_u32", "ds_and_rtn_b32", "ds_or_rtn_b32", "ds_xor_rtn_b32", + "ds_mskor_rtn_b32", "ds_wrxchg_rtn_b32", "ds_wrxchg2_rtn_b32", "ds_wrxchg2st64_rtn_b32", + "ds_cmpst_rtn_b32", "ds_cmpst_rtn_f32", "ds_min_rtn_f32", "ds_max_rtn_f32", + "ds_wrap_rtn_b32", "ds_swizzle_b32", "ds_read_b32", "ds_read2_b32", + "ds_read2st64_b32", "ds_read_i8", "ds_read_u8", "ds_read_i16", + "ds_read_u16", "ds_consume", "ds_append", "ds_ordered_count", + "ds_add_u64", "ds_sub_u64", "ds_rsub_u64", "ds_inc_u64", + "ds_dec_u64", "ds_min_i64", "ds_max_i64", "ds_min_u64", + "ds_max_u64", "ds_and_b64", "ds_or_b64", "ds_xor_b64", + "ds_mskor_b64", "ds_write_b64", "ds_write2_b64", "ds_write2st64_b64", + "ds_cmpst_b64", "ds_cmpst_f64", "ds_min_f64", "ds_max_f64", + nullptr, "ds_add_rtn_f32", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_add_rtn_u64", "ds_sub_rtn_u64", "ds_rsub_rtn_u64", "ds_inc_rtn_u64", + "ds_dec_rtn_u64", "ds_min_rtn_i64", "ds_max_rtn_i64", "ds_min_rtn_u64", + "ds_max_rtn_u64", "ds_and_rtn_b64", "ds_or_rtn_b64", "ds_xor_rtn_b64", + "ds_mskor_rtn_b64", "ds_wrxchg_rtn_b64", "ds_wrxchg2_rtn_b64", "ds_wrxchg2st64_rtn_b64", + "ds_cmpst_rtn_b64", "ds_cmpst_rtn_f64", "ds_min_rtn_f64", "ds_max_rtn_f64", + nullptr, nullptr, "ds_read_b64", "ds_read2_b64", + "ds_read2st64_b64", nullptr, nullptr, nullptr, + nullptr, nullptr, "ds_condxchg32_rtn_b64", nullptr, + "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", + nullptr, "ds_write_src2_b32", nullptr, nullptr, + nullptr, nullptr, "ds_min_src2_f32", "ds_max_src2_f32", + nullptr, "ds_add_src2_f32", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_write_b8_d16_hi", "ds_write_b16_d16_hi", "ds_read_u8_d16", "ds_read_u8_d16_hi", + "ds_read_i8_d16", "ds_read_i8_d16_hi", "ds_read_u16_d16", "ds_read_u16_d16_hi", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "ds_write_addtid_b32", "ds_read_addtid_b32", "ds_permute_b32", "ds_bpermute_b32", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "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", + nullptr, "ds_write_src2_b64", nullptr, nullptr, + nullptr, nullptr, "ds_min_src2_f64", "ds_max_src2_f64", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "ds_write_b96", "ds_write_b128", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "ds_read_b96", "ds_read_b128", +}; + +constexpr const char* flat_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_load_ubyte", "flat_load_sbyte", "flat_load_ushort", "flat_load_sshort", + "flat_load_dword", "flat_load_dwordx2", "flat_load_dwordx4", "flat_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_store_byte", "flat_store_byte_d16_hi", "flat_store_short", "flat_store_short_d16_hi", + "flat_store_dword", "flat_store_dwordx2", "flat_store_dwordx4", "flat_store_dwordx3", + "flat_load_ubyte_d16", "flat_load_ubyte_d16_hi", "flat_load_sbyte_d16", "flat_load_sbyte_d16_hi", + "flat_load_short_d16", "flat_load_short_d16_hi", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_atomic_swap", "flat_atomic_cmpswap", "flat_atomic_add", "flat_atomic_sub", + nullptr, "flat_atomic_smin", "flat_atomic_umin", "flat_atomic_smax", + "flat_atomic_umax", "flat_atomic_and", "flat_atomic_or", "flat_atomic_xor", + "flat_atomic_inc", "flat_atomic_dec", "flat_atomic_fcmpswap", "flat_atomic_fmin", + "flat_atomic_fmax", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "flat_atomic_swap_x2", "flat_atomic_cmpswap_x2", "flat_atomic_add_x2", "flat_atomic_sub_x2", + nullptr, "flat_atomic_smin_x2", "flat_atomic_umin_x2", "flat_atomic_smax_x2", + "flat_atomic_umax_x2", "flat_atomic_and_x2", "flat_atomic_or_x2", "flat_atomic_xor_x2", + "flat_atomic_inc_x2", "flat_atomic_dec_x2", "flat_atomic_fcmpswap_x2", "flat_atomic_fmin_x2", + "flat_atomic_fmax_x2", +}; + +constexpr const char* global_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "global_load_ubyte", "global_load_sbyte", "global_load_ushort", "global_load_sshort", + "global_load_dword", "global_load_dwordx2", "global_load_dwordx4", "global_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, "global_load_dword_addtid", "global_store_dword_addtid", + "global_store_byte", "global_store_byte_d16_hi", "global_store_short", "global_store_short_d16_hi", + "global_store_dword", "global_store_dwordx2", "global_store_dwordx4", "global_store_dwordx3", + "global_load_ubyte_d16", "global_load_ubyte_d16_hi", "global_load_sbyte_d16", "global_load_sbyte_d16_hi", + "global_load_short_d16", "global_load_short_d16_hi", nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "global_atomic_swap", "global_atomic_cmpswap", "global_atomic_add", "global_atomic_sub", + "global_atomic_csub", "global_atomic_smin", "global_atomic_umin", "global_atomic_smax", + "global_atomic_umax", "global_atomic_and", "global_atomic_or", "global_atomic_xor", + "global_atomic_inc", "global_atomic_dec", "global_atomic_fcmpswap", "global_atomic_fmin", + "global_atomic_fmax", nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "global_atomic_swap_x2", "global_atomic_cmpswap_x2", "global_atomic_add_x2", "global_atomic_sub_x2", + nullptr, "global_atomic_smin_x2", "global_atomic_umin_x2", "global_atomic_smax_x2", + "global_atomic_umax_x2", "global_atomic_and_x2", "global_atomic_or_x2", "global_atomic_xor_x2", + "global_atomic_inc_x2", "global_atomic_dec_x2", "global_atomic_fcmpswap_x2", "global_atomic_fmin_x2", + "global_atomic_fmax_x2", +}; + +constexpr const char* scratch_names[] = { + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "scratch_load_ubyte", "scratch_load_sbyte", "scratch_load_ushort", "scratch_load_sshort", + "scratch_load_dword", "scratch_load_dwordx2", "scratch_load_dwordx4", "scratch_load_dwordx3", + nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, + "scratch_store_byte", "scratch_store_byte_d16_hi", "scratch_store_short", "scratch_store_short_d16_hi", + "scratch_store_dword", "scratch_store_dwordx2", "scratch_store_dwordx4", "scratch_store_dwordx3", + "scratch_load_ubyte_d16", "scratch_load_ubyte_d16_hi", "scratch_load_sbyte_d16", "scratch_load_sbyte_d16_hi", + "scratch_load_short_d16", "scratch_load_short_d16_hi", +}; diff --git a/src/gfx1013_pixel.cpp b/src/gfx1013_pixel.cpp new file mode 100644 index 0000000000..0dd516ceb2 --- /dev/null +++ b/src/gfx1013_pixel.cpp @@ -0,0 +1,96 @@ +#include "gfx1013_pixel.h" +#include <array> +#include <cstdint> +#include <cstring> +#include <optional> +#include <sstream> +#include <stdexcept> + +static std::array<uint32_t, 4> decode_color(std::string_view code) { + std::array<std::optional<uint32_t>, 256> vgpr{}; + size_t pc = 0; + auto word = [&]() { + if (code.size() - pc < 4) + throw std::runtime_error("truncated pixel program at " + std::to_string(pc)); + uint32_t value; + std::memcpy(&value, code.data() + pc, 4); + pc += 4; + return value; + }; + std::optional<std::array<uint32_t, 4>> result; + while (pc < code.size()) { + const auto address = pc; + const auto op = word(); + if (op == 0xbf810000 && result.has_value() && pc == code.size()) + return *result; + if (result.has_value()) + throw std::runtime_error("expected final s_endpgm at " + std::to_string(address)); + if ((op & 0xfe01fe00u) == 0x7e000200u) { + const auto src = op & 511; + auto &dst = vgpr[(op >> 17) & 255]; + if (src >= 256 && vgpr[src - 256]) + dst = vgpr[src - 256]; + else if (src == 255) + dst = word(); + else if (src >= 128 && src <= 192) + dst = src - 128; + else if (src >= 193 && src <= 208) + dst = 192u - src; + else if (src >= 240 && src <= 247) { + constexpr uint32_t floats[]{0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, + 0x40000000, 0xc0000000, 0x40800000, 0xc0800000}; + dst = floats[src - 240]; + } else + throw std::runtime_error("unresolved v_mov source at " + std::to_string(address)); + } else if (op == 0xf800180f) { + const auto sources = word(); + result.emplace(); + for (unsigned component = 0; component < 4; ++component) { + const auto &value = vgpr[(sources >> (component * 8)) & 255]; + if (!value) + throw std::runtime_error("uninitialized export VGPR at " + std::to_string(address)); + (*result)[component] = *value; + } + } else + throw std::runtime_error("unsupported pixel instruction at " + std::to_string(address)); + } + throw std::runtime_error("missing final MRT0 export or s_endpgm"); +} + +std::string x2w::translate_gfx1013_constant_pixel(std::string_view code) { + std::string out = "float4 main() : SV_Target0 { return asfloat(uint4("; + for (auto word : decode_color(code)) + out += std::to_string(word) + "u,"; + out.back() = ')'; + return out + "); }"; +} + +std::string x2w::direct_gfx1013_constant_pixel(std::string_view code) { + auto color = decode_color(code); + std::ostringstream out; + out << "target triple = \"dxil-ms-dx\"\ndefine void @main() {\n"; + for (unsigned c = 0; c < color.size(); ++c) + out << " call void @dx.op.storeOutput.f32(i32 5, i32 0, i32 0, i8 " << c << ", float bitcast (i32 " + << color[c] << " to float))\n"; + out << R"( ret void +} +declare void @dx.op.storeOutput.f32(i32,i32,i32,i8,float) nounwind +!llvm.ident = !{!0} +!dx.version = !{!1} +!dx.valver = !{!1} +!dx.shaderModel = !{!2} +!dx.viewIdState = !{!3} +!dx.entryPoints = !{!4} +!0 = !{!"x2w"} +!1 = !{i32 1, i32 0} +!2 = !{!"ps", i32 6, i32 0} +!3 = !{[2 x i32] [i32 0, i32 4]} +!4 = !{void ()* @main, !"main", !5, null, null} +!5 = !{null, !6, null} +!6 = !{!7} +!7 = !{i32 0, !"SV_Target", i8 9, i8 16, !8, i8 0, i32 1, i8 4, i32 0, i8 0, !9} +!8 = !{i32 0} +!9 = !{i32 3, i32 15} +)"; + return out.str(); +} diff --git a/src/gfx1013_pixel.h b/src/gfx1013_pixel.h new file mode 100644 index 0000000000..c8c8397523 --- /dev/null +++ b/src/gfx1013_pixel.h @@ -0,0 +1,10 @@ +#pragma once +#include <string> +#include <string_view> + +namespace x2w { +// Accepts a headerless, little-endian gfx1013 pixel program with one full, +// uncompressed float MRT0 export. Unknown instructions and entry VGPRs fail. +std::string direct_gfx1013_constant_pixel(std::string_view code); +std::string translate_gfx1013_constant_pixel(std::string_view code); +} // namespace x2w diff --git a/src/gfx1013_pixel_waterfall.inl b/src/gfx1013_pixel_waterfall.inl new file mode 100644 index 0000000000..d61103594c --- /dev/null +++ b/src/gfx1013_pixel_waterfall.inl @@ -0,0 +1,92 @@ +// Single-block read-only descriptor waterfalls. See victory-shader/resource.rs +// (waterfall) and tools/startup/gfx2hlsl.py (waterfall_refusal). Every pass +// removes exactly the lanes it sampled. No other loop effect can be projected +// onto an individual invocation. +struct PixelWaterfalls { + struct Access { unsigned key, descriptor_pc; bool key_is_bytes; }; + std::map<unsigned,Access> accesses; + std::map<unsigned,std::vector<unsigned>> poisoned; + std::set<unsigned> exits, saves, restores; + + void find(Program &p, bool wave32) { + auto &code=p.code; + const auto mov=wave32 ? "s_mov_b32" : "s_mov_b64"; + const auto remaining_op=wave32 ? "s_andn2_wrexec_b32" : "s_andn2_wrexec_b64"; + auto idle=[](const Inst &i) {return i.name=="s_waitcnt" || i.name=="s_nop";}; + auto pair=[&](unsigned r) {return wave32 ? r<=105 : r<=104 && !(r&1);}; + for (size_t tail=2; tail+1<code.size(); ++tail) { + auto &retry=code[tail]; + const auto &advance=code[tail-1], &restore=code[tail+1]; + if (!retry.branch() || (retry.op!=5 && retry.op!=9) || retry.target()>=retry.pc || + advance.name!=remaining_op || !pair(advance.dst) || advance.src[0]!=advance.dst || + restore.name!=mov || restore.dst!=126 || !pair(restore.src[0]) || restore.src[0]==advance.dst) continue; + const size_t head=p.at.at(retry.target()); + std::vector<size_t> body; + for (size_t j=head;j<tail-1;++j) if (!idle(code[j])) body.push_back(j); + if (body.size()!=4 && body.size()!=5) continue; + const auto &read=code[body[0]], &cmp=code[body[1]], &load=code[body[body.size()-2]], + &image=code[body.back()]; + if (read.name!="v_readfirstlane_b32" || read.src[0]<256 || read.subword || read.dpp_control || + (cmp.name!="v_cmpx_eq_i32" && cmp.name!="v_cmpx_eq_u32") || cmp.dst!=126 || + cmp.src[0]!=read.dst || cmp.src[1]!=read.src[0] || cmp.abs || cmp.neg || cmp.scale || + cmp.clamp || cmp.subword || cmp.dpp_control || load.enc!=Encoding::Smem || load.op!=3 || + load.dst>98 || (load.b>>25)!=read.dst || (load.b&0xfffff) || + image.enc!=Encoding::Image || (image.op!=32 && image.op!=39 && image.op!=0) || + ((image.b>>16)&31)*4!=load.dst) continue; + const auto &table=p.before[body[body.size()-2]].at(load.src[0]); + if (table.type!=Symbol::Type::table || table.value!=compute_resource_heap) continue; + // The slot or the already shifted byte offset may be the key. + bool bytes=body.size()==4; + if (!bytes) { + const auto &shift=code[body[2]]; + if (shift.name!="s_lshl_b32" || shift.dst!=read.dst || shift.src[0]!=read.dst || + !(source(shift,shift.src[1],p.before[body[2]])==Symbol{Symbol::Type::constant,5})) continue; + } + const unsigned width=wave32 ? 1u : 2u; + auto overlaps=[](unsigned a,unsigned na,unsigned b,unsigned nb) {return a<b+nb && b<a+na;}; + if (overlaps(read.dst,1,advance.dst,width) || overlaps(read.dst,1,restore.src[0],width) || + overlaps(load.dst,8,advance.dst,width) || overlaps(load.dst,8,restore.src[0],width) || + overlaps(load.src[0],2,load.dst,8) || overlaps(load.src[0],2,read.dst,1) || + overlaps(load.dst,8,read.dst,1)) continue; + // Copies of exactly the entering EXEC must reach both the retry and + // the restore. No alternate edge may enter past either copy. + auto anchor=[&](unsigned r)->std::optional<size_t> { + for (size_t at=head; at;) { + const auto &save=code[--at]; + if (save.name!=mov || save.dst!=r || save.src[0]!=126) continue; + if (!GraphicsMaskRegions::preserves_exec(p,at+1,head,r)) return {}; + for (const auto &edge:code) { + if (!edge.branch() || edge.pc==retry.pc) continue; + if (edge.target()>save.pc && edge.target()<=restore.pc && + (edge.pc<save.pc || edge.pc>=retry.pc || edge.target()>code[head].pc)) return {}; + } + return at; + } + return {}; + }; + auto parent=anchor(restore.src[0]), left=anchor(advance.dst); + if (!parent || !left) continue; + saves.insert(code[*parent].pc); + saves.insert(code[*left].pc); + restores.insert(restore.pc); + auto forget=[&](unsigned pc,unsigned r,unsigned n) { + for (unsigned j=0;j<n;++j) poisoned[pc].push_back(r+j); + }; + // Keep the actual saves in the instruction stream. They can have + // consumers earlier in the shader; only this validated restore + // is an identity on the original coverage. + forget(read.pc,read.dst,1); + forget(load.pc,load.dst,8); + forget(advance.pc,advance.dst,width); + exits.insert(advance.pc); + accesses.emplace(image.pc,Access{read.src[0],load.pc,bytes}); + for (size_t j=head;j<=tail;++j) + if (code[j].pc!=image.pc) GraphicsMaskRegions::skip_proven(code[j]); + // The final iteration's uniform descriptor cannot escape the loop + // as a varying handle. Later genuine loads have a new definition. + for (size_t j=tail+2;j<code.size();++j) + for (auto &sym:p.before[j]) if (sym.type==Symbol::Type::indexed_descriptor && sym.definition==load.pc) + sym.type=Symbol::Type::unbound; + } + } +}; diff --git a/src/gfx1013_rect_geometry.cpp b/src/gfx1013_rect_geometry.cpp new file mode 100644 index 0000000000..46ae6a8f26 --- /dev/null +++ b/src/gfx1013_rect_geometry.cpp @@ -0,0 +1,150 @@ +#include "dxil_module.h" +#include "gfx1013_compute_native.h" + +namespace x2w { +// Apply the startup rectangle rule (indexed_rect_geometry.h) to post-VS +// values. IA, base vertex, instance IDs and the original VS stay intact. +std::string native_rectangle_geometry(const std::vector<GraphicsLinkage> &outputs, + const std::vector<GraphicsLinkage> &pixel_inputs) { + using std::string; + using std::to_string; + if (std::any_of(pixel_inputs.begin(), pixel_inputs.end(), [](const auto &input) { return input.kind == 28; })) + throw UnsupportedComputeShader("numeric barycentrics on an expanded rectangle"); + struct Channel { + unsigned id, column, scalar; + bool floating, flat; + std::array<string, 3> vertex; + string a, b, fourth; + }; + DxilModule ir; + std::vector<Channel> channels; + std::array<std::array<string, 4>, 3> position; + DxilModule::InputMask guard_inputs; + bool has_position = false; + for (const auto &r : outputs) { + const bool pos = r.kind == 3; + if (r.row >= 32 || !r.width || r.first + r.width > 4 || (!pos && r.kind != 0 && r.kind != 6 && r.kind != 7)) + throw UnsupportedComputeShader("unsupported rectangle stage interface"); + if (pos && (has_position || r.component != 9 || r.first || r.used != 15 || r.width != 4)) + throw UnsupportedComputeShader("rectangle requires a complete float4 position"); + has_position |= pos; + auto consumer = std::find_if(pixel_inputs.begin(), pixel_inputs.end(), + [&](const auto &p) { return p.name == r.name && p.index == r.index; }); + const bool flat = + !pos && (r.component != 9 || (consumer != pixel_inputs.end() && consumer->interpolation == 1)); + const unsigned id = static_cast<unsigned>(ir.inputs.size()); + ir.inputs.push_back({r.name, r.index, r.kind, r.component, r.row, r.first, r.width, r.interpolation, r.used}); + ir.outputs.push_back(ir.inputs.back()); + if (flat) + ir.outputs.back().interpolation = 1; + for (unsigned col = 0; col < r.width; ++col) { + if (!(r.used & (1u << col))) + continue; + Channel c{id, col, r.row * 4 + r.first + col, r.component == 9, flat}; + for (unsigned v = 0; v < (flat ? 1u : 3u); ++v) { + c.vertex[v] = + ir.invoke(c.floating ? "float" : "i32", c.floating ? "loadInput.f32" : "loadInput.i32", 4, + {{"i32", to_string(id)}, {"i32", "0"}, {"i8", to_string(col)}, {"i32", to_string(v)}}, + "nounwind readnone"); + if (pos) + position[v][col] = c.vertex[v]; + } + if (pos) + guard_inputs.set(c.scalar); + channels.push_back(std::move(c)); + } + } + if (!has_position) + throw UnsupportedComputeShader("rectangle requires a position"); + auto both = [&](const string &a, const string &b) { return ir.value("and i1 " + a + ", " + b); }; + auto either = [&](const string &a, const string &b) { return ir.value("or i1 " + a + ", " + b); }; + auto compare = [&](const char *relation, const string &a, const string &b) { + return ir.value("fcmp " + string(relation) + " float " + a + ", " + b); + }; + auto finite = [&](const string &v) { + return ir.invoke("i1", "isSpecialFloat.f32", 10, {{"float", v}}, "nounwind readnone"); + }; + string valid = compare("ogt", position[0][3], "0.000000e+00"); + for (unsigned i = 0; i < 3; ++i) { + for (const auto &v : position[i]) + valid = both(valid, finite(v)); + if (i) + valid = both(valid, compare("oeq", position[0][3], position[i][3])); + } + std::array<string, 3> corner; + for (unsigned i = 0; i < 3; ++i) { + auto &p = position[i], &a = position[(i + 1) % 3], &b = position[(i + 2) % 3]; + auto x = compare("oeq", p[0], a[0]), y = compare("oeq", p[1], b[1]); + auto other_x = compare("oeq", p[0], b[0]), other_y = compare("oeq", p[1], a[1]); + corner[i] = both(either(both(x, y), both(other_x, other_y)), + both(compare("one", a[0], b[0]), compare("one", a[1], b[1]))); + } + // A rotated rectangle has no corner that shares an axis with a neighbour, so the axis test above misses it + // and the whole rectangle would be dropped (#3131). The right-angle corner is the vertex opposite the + // rectangle's diagonal, the longest of its three edges: for corner c with neighbours a and b, |a - b| is the + // diagonal and is longer than both sides. The sides must also meet at a right angle, so a shape that is not a + // rectangle stays undrawn. The axis corners keep precedence, as they did before. + auto squared = [&](const string &p, const string &q) { + auto d = ir.value("fsub float " + p + ", " + q); + return ir.value("fmul float " + d + ", " + d); + }; + const auto distance2 = [&](const std::array<string, 4> &p, const std::array<string, 4> &q) { + auto dx = squared(p[0], q[0]), dy = squared(p[1], q[1]); + return ir.value("fadd float " + dx + ", " + dy); + }; + std::array<string, 3> geometric; + for (unsigned i = 0; i < 3; ++i) { + auto &p = position[i], &a = position[(i + 1) % 3], &b = position[(i + 2) % 3]; + auto across = distance2(a, b), to_a = distance2(p, a), to_b = distance2(p, b); + // (p - a) . (p - b), squared, against the binary32 value of 1e-6 of |p - a|^2 |p - b|^2: the two + // sides meet at a right angle. The hex double is the only spelling LLVM IR accepts for this + // non-representable decimal constant. + auto diff = [&](const string &u, const string &v) { return ir.value("fsub float " + u + ", " + v); }; + auto times = [&](const string &u, const string &v) { return ir.value("fmul float " + u + ", " + v); }; + auto dot = ir.value("fadd float " + times(diff(p[0], a[0]), diff(p[0], b[0])) + ", " + + times(diff(p[1], a[1]), diff(p[1], b[1]))); + auto limit = ir.value("fmul float " + times(to_a, to_b) + ", 0x3EB0C6F7A0000000"); + geometric[i] = both(both(compare("ogt", across, to_a), compare("ogt", across, to_b)), + compare("ole", times(dot, dot), limit)); + } + auto any_axis = either(corner[0], either(corner[1], corner[2])); + for (unsigned i = 0; i < 3; ++i) + corner[i] = either(corner[i], both(ir.value("xor i1 " + any_axis + ", true"), geometric[i])); + valid = both(valid, either(corner[0], either(corner[1], corner[2]))); + // Only a non-degenerate rectangle has a unique matching corner. + for (auto &c : channels) { + if (c.flat) + continue; + auto rotate = [&](unsigned n) { + auto rest = ir.value("select i1 " + corner[1] + ", float " + c.vertex[(n + 1) % 3] + ", float " + + c.vertex[(n + 2) % 3]); + return ir.value("select i1 " + corner[0] + ", float " + c.vertex[n] + ", float " + rest); + }; + c.a = rotate(1); + c.b = rotate(2); + auto sum = ir.value("fadd float " + c.a + ", " + c.b); + c.fourth = ir.value("fsub float " + sum + ", " + rotate(0)); + if (ir.outputs[c.id].kind == 3) + valid = both(valid, finite(c.fourth)); + } + ir.body << " br i1 " << valid << ", label %draw, label %done\ndraw:\n"; + for (unsigned v = 0; v < 6; ++v) { + for (const auto &c : channels) { + const auto &value = c.flat ? c.vertex[0] : v < 3 ? c.vertex[v] : v == 3 ? c.a : v == 4 ? c.fourth : c.b; + ir.invoke("void", c.floating ? "storeOutput.f32" : "storeOutput.i32", 5, + {{"i32", to_string(c.id)}, + {"i32", "0"}, + {"i8", to_string(c.column)}, + {c.floating ? "float" : "i32", value}}, + "nounwind"); + ir.output_dependencies[c.scalar] = guard_inputs; + ir.output_dependencies[c.scalar].set(c.scalar); + } + ir.invoke("void", "emitStream", 97, {{"i8", "0"}}, "nounwind"); + if (v == 2 || v == 5) + ir.invoke("void", "cutStream", 98, {{"i8", "0"}}, "nounwind"); + } + ir.body << " br label %done\ndone:\n ret void\n"; + return ir.finish_compute(0, 0, 0, "gs"); +} +} // namespace x2w diff --git a/src/gfx1013_sampled_pixel.cpp b/src/gfx1013_sampled_pixel.cpp new file mode 100644 index 0000000000..ff3d8ac4cf --- /dev/null +++ b/src/gfx1013_sampled_pixel.cpp @@ -0,0 +1,289 @@ +#include "gfx1013_sampled_pixel.h" +#include <array> +#include <cstdint> +#include <cstring> +#include <optional> +#include <stdexcept> +#include <tuple> +#include <vector> + +namespace { +using Word = uint32_t; +using std::string; +enum class Type { undefined, constant, table, descriptor_word, value, primitive_mask }; +struct Scalar { + Type type{}; + Word number{}, offset{}; + string value; +}; +struct Vector { + string value; + std::array<string,2> halves{}; + int interpolation = -1; +}; +struct Binding { + Word table, offset; + bool texture; +}; + +class PixelProgram { + std::string_view code; + size_t pc{}, start{}; + std::optional<Word> instruction_literal; + unsigned temporary{}; + std::array<Scalar,102> scalars{}; + std::array<Vector,256> vectors{}; + std::vector<Binding> resources; + std::vector<std::array<Word,4>> samplers; + bool primitive_mask=false; + std::array<bool,2> exported{}; + bool done=false; + string declarations, body, bindings; + + [[noreturn]] void fail(const char* why) const { + throw std::runtime_error(string(why)+" at pixel byte "+std::to_string(start)); + } + void require(bool ok,const char* why) const { if(!ok) fail(why); } + Word word() { + require(code.size()-pc>=4,"truncated instruction"); + Word v; std::memcpy(&v,code.data()+pc,4); pc+=4; return v; + } + string symbol(const char* type,const string& expression) { + auto name="p"+std::to_string(temporary++); + body+=" "+string(type)+" "+name+" = "+expression+";\n"; + return name; + } + Scalar source(Word index) { + if(index<scalars.size()) return scalars[index]; + Word bits{}; + if(index>=128 && index<=192) bits=index-128; + else if(index>=193 && index<=208) bits=192u-index; + else if(index>=240 && index<=247) { + constexpr Word floats[]{0x3f000000,0xbf000000,0x3f800000,0xbf800000,0x40000000,0xc0000000,0x40800000,0xc0800000}; + bits=floats[index-240]; + } else if(index==255) { + // Every literal selector in the instruction names the same trailing dword. + if(!instruction_literal) instruction_literal=word(); + bits=*instruction_literal; + } + else fail("unsupported scalar operand"); + return {Type::constant,bits}; + } + static string literal(Word bits) {return std::to_string(bits)+"u";} + string as_float(Word index) { + if(index>=256) { + const auto& v=vectors[index-256]; + require(!v.value.empty(),"undefined float VGPR"); + return v.value; + } + auto s=source(index); + if(s.type==Type::value) return "asfloat("+s.value+")"; + require(s.type==Type::constant,"expected float operand"); + return "asfloat("+literal(s.number)+")"; + } + void put(Word reg,const string& expr) { + vectors[reg]=Vector{symbol("float",expr)}; + } + string resource(Word base,unsigned words,bool texture) { + require(base+words<=scalars.size(),"invalid descriptor SGPR range"); + auto first=scalars[base]; + require(first.type==Type::descriptor_word && first.offset%32==0,"unresolved descriptor base"); + for(unsigned i=1;i<words;++i) { + auto s=scalars[base+i]; + require(s.type==first.type && s.number==first.number && s.offset==first.offset+4*i,"incomplete descriptor"); + } + unsigned i=0; + for(auto b:resources) { + if(b.table==first.number && b.offset==first.offset) { + require(b.texture==texture,"conflicting descriptor type"); + return "r"+std::to_string(i); + } + ++i; + } + auto n=std::to_string(i); + declarations+=(texture?"Texture2D<float4>":"ByteAddressBuffer")+string(" r")+n+" : register(t"+n+");\n"; + bindings+="srv "+n+(texture?" tex2d table ":" buf table ")+std::to_string(first.number)+" "+std::to_string(first.offset)+"\n"; + resources.push_back({first.number,first.offset,texture}); + return "r"+n; + } + std::array<Word,4> sampler_words(Word base) { + require(base+4<=scalars.size(),"invalid sampler SGPR range"); + std::array<Word,4> bits{}; + for(unsigned i=0;i<4;++i) { + require(scalars[base+i].type==Type::constant,"unresolved sampler"); + bits[i]=scalars[base+i].number; + } + return bits; + } + string sampler(const std::array<Word,4>& bits) { + unsigned i=0; + for(const auto& s:samplers) {if(s==bits) return "q"+std::to_string(i); ++i;} + auto n=std::to_string(i); + declarations+="SamplerState q"+n+" : register(s"+n+");\n"; + bindings+="sampler "+n; + for(auto b:bits) bindings+=" "+std::to_string(b); + bindings+="\n"; + samplers.push_back(bits); + return "q"+n; + } + void scalar_load(Word op) { + auto base=(op&63)*2, dst=(op>>6)&127; + auto imm=word(); + require((imm&0xfff00000)==0xfa000000,"unsupported scalar byte offset"); + unsigned off=imm&0xfffff; + if((op&~0x1fffu)==0xf4240000) { + require(dst+2<=scalars.size() && off%4==0,"invalid buffer load"); + auto r=resource(base,4,false); + for(unsigned i=0;i<2;++i) + scalars[dst+i]={Type::value,0,0,symbol("uint",r+".Load("+literal(off+4*i)+")")}; + return; + } + unsigned count=(op&~0x1fffu)==0xf4080000 ? 4 : 16; + require(base+1<scalars.size() && dst+count<=scalars.size(),"invalid descriptor load"); + auto ptr=scalars[base],hi=scalars[base+1]; + require(ptr.type==Type::table && hi.type==Type::constant && hi.number==0,"expected a descriptor table"); + for(unsigned i=0;i<count;++i) scalars[dst+i]={Type::descriptor_word,ptr.number,off+4*i}; + } + void sample(Word op) { + auto args=word(), addr=args&255, dst=(args>>8)&255, mask=(op>>8)&15; + require(!(args&0xfc000000) && mask && addr<255,"invalid image_sample_lz"); + auto r=resource(((args>>16)&31)*4,8,true); + auto bits=sampler_words(((args>>21)&31)*4); + const bool implicit = (op & 0xfffff0ff) == 0xf0800008; + const int bias = int((bits[2] & 0x3fff) ^ 0x2000) - 0x2000; + const unsigned mip_filter = (bits[2] >> 26) & 3; + require(!(bits[2] & 0xfc000), "unsupported secondary sampler bias"); + require(!implicit || mip_filter == 1 || mip_filter == 2, "unsupported implicit mip filter"); + // The primary s6.8 field must fit the desktop SampleBias range [-16, 15.99]. + require(!bias || (implicit && bias >= -4096 && bias <= 4093), + "unsupported primary sampler bias"); + require((bits[1]&0xfff) <= ((bits[1]>>12)&0xfff), "inverted sampler LOD limits"); + bits[2] &= ~0x3fffu; + auto q=sampler(bits); + auto uv="float2("+as_float(256+addr)+","+as_float(257+addr)+")"; + string call; + if (bias) call=r+".SampleBias("+q+","+uv+","+std::to_string(bias)+".0/256.0)"; + else if (implicit) call=r+".Sample("+q+","+uv+")"; + else call=r+".SampleLevel("+q+","+uv+",0)"; + auto value=symbol("float4",call); + for(unsigned bit=0;bit<4;++bit) if(mask&(1u<<bit)) { + require(dst<256,"sample destination overflows VGPR file"); + vectors[dst++]=Vector{value+"."+"xyzw"[bit]}; + } + } + void export_mrt(Word op) { + auto args=word(); + unsigned mrt=(op>>4)&63; + require(mrt<2 && !exported[mrt],"unexpected render target export"); + require((op&15)==(mrt?3u:15u) && (args&0xffff0000)==0x80800000,"unsupported compressed export mask"); + unsigned channels=mrt?1:3; + string value; + for(unsigned i=0;i<channels;++i) { + auto& v=vectors[(args>>(8*(i/2)))&255]; + auto half=v.halves[i%2]; + require(!half.empty(),"undefined live render target channel"); + if(i) value+=","; + value+="f16tof32("+half+")"; + } + body+=" o.c"+std::to_string(mrt)+" = "+(mrt?value:"float3("+value+")")+";\n"; + exported[mrt]=true; + done=(op&0x800)!=0; + } + void instruction(Word op) { + auto dst=(op>>16)&127; + if((op>>16)==0xbfa0 || (op>>16)==0xbfa1 || (op>>16)==0xbf8c) return; // prefetch, clause and waitcnt + if((op&0xff80ff00)==0xbe800300 || (op&0xff80ff00)==0xbe800400) { + auto s=source(op&255); + if(dst==124) { + require(((op>>8)&255)==3 && s.type==Type::primitive_mask,"unsupported m0 write"); + primitive_mask=true;return; + } + require(dst<scalars.size() && s.type!=Type::undefined,"invalid scalar move"); + if(((op>>8)&255)==4) { + const unsigned selector=op&255; + require(dst+1<scalars.size(),"invalid scalar pair destination"); + if(selector<scalars.size()-1) { + require(scalars[selector+1].type!=Type::undefined,"undefined scalar pair source"); + scalars[dst+1]=scalars[selector+1]; + } else if(selector==255 && !(s.number>>31)) { + scalars[dst+1]={Type::constant,0}; + } else { + require(selector>=128 && selector<=208,"unsupported 64-bit scalar constant"); + scalars[dst+1]={Type::constant,selector<=192?0u:0xffffffffu}; + } + } + scalars[dst]=s; + } else if((op&0xff800000)==0xb0000000) { + require(dst<scalars.size(),"invalid movk destination"); + scalars[dst]={Type::constant,static_cast<Word>(static_cast<int16_t>(op))}; + } else if((op&0xff800000)==0x92000000 || (op&0xff800000)==0x92800000) { + auto a=source(op&255),b=source((op>>8)&255); + require(dst<scalars.size() && a.type==Type::constant && b.type==Type::constant,"unresolved bfm operands"); + if (op&0x800000) { + require(!(dst&1) && dst+1<scalars.size(),"invalid bfm scalar pair"); + const uint64_t mask=((uint64_t{1}<<(a.number&63))-1)<<(b.number&63); + scalars[dst]={Type::constant,static_cast<Word>(mask)}; + scalars[dst+1]={Type::constant,static_cast<Word>(mask>>32)}; + } else scalars[dst]={Type::constant,((1u<<(a.number&31))-1)<<(b.number&31)}; + } else if((op&~0x1fffu)==0xf4080000 || (op&~0x1fffu)==0xf4100000 || (op&~0x1fffu)==0xf4240000) { + scalar_load(op); + } else if((op&0xfc000000)==0xc8000000) { + unsigned d=(op>>18)&255, attr=(op>>10)&63, component=(op>>8)&3, phase=(op>>16)&3; + require(primitive_mask && attr==0 && phase<2 && (op&255)==phase,"unsupported interpolation interface"); + require(vectors[phase].value.empty() && vectors[phase].interpolation==-1 && + vectors[phase].halves[0].empty() && vectors[phase].halves[1].empty(),"overwritten IJ input"); + if(!phase) { vectors[d]={}; vectors[d].interpolation=component; } + else { + require(vectors[d].interpolation==int(component),"interpolation phase mismatch"); + put(d,"param0."+string(1,"xyzw"[component])); + } + } else if((op&0xfffff0ff)==0xf09c0008 || (op&0xfffff0ff)==0xf0800008) { + sample(op); + } else if((op&0xffffff00)==0xd54b0000 || (op&0xffffff00)==0xcc214000 || (op&0xffffff00)==0xcc224000) { + auto args=word(), d=op&255; + auto a=as_float(args&511), b=as_float((args>>9)&511); + if((op>>16)==0xd54b) { + require(!(args&0xf8000000),"unsupported FMA modifiers"); + auto c=as_float((args>>18)&511); + put(d,"mad("+a+","+b+","+c+")"); + } else { + require((args&0xfffc0000)==0x82000000,"expected negated zero half addend"); + unsigned half=(op>>16)==0xcc22; + auto& v=vectors[d]; + if(!v.value.empty()) { + v.halves[0]="(asuint("+v.value+") & 65535u)"; + v.halves[1]="(asuint("+v.value+") >> 16)"; + } + v.value.clear();v.interpolation=-1; + v.halves[half]=symbol("uint","f32tof16(mad("+a+","+b+",asfloat(0x80000000u)))"); + } + } else if(op>>25==3 || op>>25==5 || op>>25==43) { + auto d=(op>>17)&255; + auto a=as_float(op&511), b=as_float(256+((op>>9)&255)); + if(op>>25==43) put(d,"mad("+a+","+b+","+as_float(256+d)+")"); + else put(d,op>>25==3?a+"+"+b:b+"-"+a); + } else if(op==0xf800040f || op==0xf8001c13) export_mrt(op); + else fail("unsupported sampled pixel instruction"); + } +public: + explicit PixelProgram(std::string_view bytes) : code(bytes) {} + x2w::SampledPixel translate() { + scalars[8]={Type::table,0};scalars[9]={Type::table,1};scalars[10]={Type::primitive_mask}; + while(pc<code.size()) { + start=pc;instruction_literal.reset();auto op=word(); + if(op==0xbf810000) { + require(done && exported[0] && exported[1] && pc==code.size(),"incomplete pixel exports or trailing instructions"); + return {declarations+"struct Out {float3 c0:SV_Target0; float c1:SV_Target1;};\n" + "Out main(float4 param0:PARAM0){\n Out o;\n"+body+" return o;\n}\n",bindings}; + } + require(!done,"instruction after final export"); + instruction(op); + } + fail("missing endpgm"); + } +}; +} + +x2w::SampledPixel x2w::translate_gfx1013_sampled_pixel(std::string_view code) { + return PixelProgram(code).translate(); +} diff --git a/src/gfx1013_sampled_pixel.h b/src/gfx1013_sampled_pixel.h new file mode 100644 index 0000000000..9a4d4f7f11 --- /dev/null +++ b/src/gfx1013_sampled_pixel.h @@ -0,0 +1,16 @@ +#pragma once +#include <string> +#include <string_view> + +namespace x2w { +struct SampledPixel { + std::string hlsl; + std::string bindings; +}; + +// Straight-line pixel programs with two entry descriptor tables (s8/s9), +// primitive mask in s10, perspective-center IJ in v0/v1, attr0 -> PARAM0, +// and R11G11B10_FLOAT/R16_FLOAT targets. The caller verifies this interface. +// code spans the instructions from entry through s_endpgm, without padding. +SampledPixel translate_gfx1013_sampled_pixel(std::string_view code); +} diff --git a/src/gfx1013_vertex_id.cpp b/src/gfx1013_vertex_id.cpp new file mode 100644 index 0000000000..d8ed79ffb1 --- /dev/null +++ b/src/gfx1013_vertex_id.cpp @@ -0,0 +1,290 @@ +#include "gfx1013_vertex_id.h" +#include <array> +#include <cstdint> +#include <cstring> +#include <optional> +#include <stdexcept> +#include <vector> + +namespace { +using Word = std::uint32_t; + +class VertexProgram { + std::string_view code; + std::size_t pc = 0, address = 0; + std::array<std::string, 256> values; + std::optional<Word> literal; + bool position = false; + std::array<bool, 2> parameters{}; + const bool buffered; + enum class Kind { undefined, value, table, vb_table, vb_tagged_high, vb_high, zero_high, desc }; + struct Scalar { + Kind kind{}; + int table{}; + unsigned offset{}; + std::string value; + }; + std::array<Scalar, 102> scalars{}; + std::vector<std::pair<int, unsigned>> buffers; + std::string declarations, bindings; + unsigned next = 0; + std::string body; + + [[noreturn]] void fail(const char *reason) const { + throw std::runtime_error(std::string(reason) + " at vertex byte " + std::to_string(address)); + } + Word read() { + if (code.size() - pc < sizeof(Word)) fail("truncated instruction"); + Word result; + std::memcpy(&result, code.data() + pc, sizeof(result)); + pc += sizeof(result); + return result; + } + std::string operand(Word selector) { + if (selector >= 256) { + const auto &value = values[selector - 256]; + if (value.empty()) fail("undefined VGPR"); + return value; + } + if (buffered && selector < scalars.size()) { + if (scalars[selector].kind == Kind::zero_high) return "0u"; + if (scalars[selector].kind != Kind::value) fail("unresolved scalar input"); + return scalars[selector].value; + } + Word bits = 0; + if (selector >= 128 && selector <= 192) + bits = selector - 128; + else if (selector >= 193 && selector <= 208) + bits = 192u - selector; + else if (selector >= 240 && selector <= 247) { + constexpr Word constants[]{0x3f000000, 0xbf000000, 0x3f800000, 0xbf800000, + 0x40000000, 0xc0000000, 0x40800000, 0xc0800000}; + bits = constants[selector - 240]; + } else if (selector == 255) { + if (!literal) literal = read(); + bits = *literal; + } else + fail("unsupported input selector"); + return std::to_string(bits) + "u"; + } + std::string temporary(const std::string &expression) { + auto name = "r" + std::to_string(next++); + body += " uint " + name + " = " + expression + ";\n"; + return name; + } + void assign(Word reg, const std::string &expression) { values[reg] = temporary(expression); } + std::string buffer(Word base, bool vertex) { + if (base + 4 > scalars.size()) fail("invalid buffer descriptor range"); + const auto &first = scalars[base]; + if (first.kind != Kind::desc || (first.table < 0) != vertex) fail("unexpected buffer descriptor"); + for (unsigned i = 1; i < 4; ++i) { + const auto &part = scalars[base + i]; + if (part.kind != Kind::desc || part.table != first.table || part.offset != first.offset + 4 * i) + fail("overwritten buffer descriptor"); + } + const auto id = std::make_pair(first.table, first.offset); + unsigned reg = 0; + for (const auto &entry : buffers) { + if (entry == id) break; + ++reg; + } + const auto number = std::to_string(reg); + if (reg == buffers.size()) { + buffers.push_back(id); + declarations += "ByteAddressBuffer b" + number + " : register(t" + number + ");\n"; + bindings += + "srv " + number + " buf " + + (vertex ? "vb 0" : "table " + std::to_string(first.table) + " " + std::to_string(first.offset)) + + "\n"; + } + return "b" + number; + } + void scalar_load(Word op) { + const Word base = (op & 63) * 2, dest = (op >> 6) & 127, offset_word = read(); + if ((offset_word & 0xfff00003) != 0xfa000000) fail("unsupported scalar load offset"); + const Word offset = offset_word & 0xfffff; + const auto opcode = op & ~0x1fffu; + const unsigned count = opcode == 0xf4300000 ? 16 : 4; + if (base + 1 >= scalars.size() || dest + count > scalars.size()) fail("scalar load register range"); + if (opcode == 0xf4080000) { + const auto pointer = scalars[base]; + const auto high = scalars[base + 1].kind; + if (pointer.kind == Kind::vb_table) { + if (offset || high != Kind::vb_high) fail("expected vertex stream zero"); + } else if (pointer.kind != Kind::table || high != Kind::zero_high || offset % 32) + fail("unresolved root table"); + for (unsigned i = 0; i < count; ++i) + scalars[dest + i] = {Kind::desc, pointer.table, offset + 4 * i}; + } else { + const auto resource = buffer(base, false); + for (unsigned i = 0; i < count; ++i) + scalars[dest + i] = {Kind::value, 0, 0, + temporary(resource + ".Load(" + std::to_string(offset + 4 * i) + "u)")}; + } + } + void load_vertex(Word op) { + const auto args = read(); + if ((args & 0xffe00000) != 0x80000000) fail("unsupported vertex load operands"); + const auto resource = buffer(((args >> 16) & 31) * 4, true); + const unsigned count = (op & 0xfffff000) == 0xe03c2000 ? 3 : 2; + const unsigned dest = (args >> 8) & 255; + if (dest + count > values.size()) fail("vertex load destination range"); + const auto address = + temporary(operand(256 + (args & 255)) + " * ud3 + " + std::to_string(op & 4095) + "u"); + for (unsigned i = 0; i < count; ++i) + assign(dest + i, resource + ".Load(" + address + "+" + std::to_string(4 * i) + "u)"); + } + bool buffer_instruction(Word op) { + const auto dest = (op >> 16) & 127, src = op & 255; + if ((op & 0xff80ff00) == 0xbe800300 || (op & 0xff80ff00) == 0xbe800400) { + if (dest >= scalars.size()) fail("invalid scalar destination"); + if (((op >> 8) & 255) == 4) { + if (dest + 1 >= scalars.size() || src + 1 >= scalars.size() || src % 2 || dest % 2 || + scalars[src].kind == Kind::undefined || scalars[src + 1].kind == Kind::undefined) + fail("unsupported scalar pair"); + const auto low = scalars[src], high = scalars[src + 1]; + scalars[dest] = low; + scalars[dest + 1] = high; + } else if (src == 128) + scalars[dest] = {Kind::zero_high}; + else if (src < scalars.size() && scalars[src].kind != Kind::undefined) + scalars[dest] = scalars[src]; + else + fail("unsupported scalar move"); + } else if ((op & 0xff80ff00) == 0x9380ff00) { + if (read() != 0x80000 || dest >= scalars.size() || src >= scalars.size() || + scalars[src].kind != Kind::vb_tagged_high) + fail("unsupported vertex address high word"); + scalars[dest] = {Kind::vb_high}; + } else if ((op & ~0x1fffu) == 0xf4080000 || (op & ~0x1fffu) == 0xf4280000 || + (op & ~0x1fffu) == 0xf4300000) { + scalar_load(op); + } else if ((op & 0xfffff000) == 0xe03c2000 || (op & 0xfffff000) == 0xe0342000) { + load_vertex(op); + } else if ((op & 0xfe01fe00) == 0x7e005c00) { + assign((op >> 17) & 255, "asuint(rsqrt(asfloat(" + operand(op & 511) + ")))"); + } else if ((op & 0xffffff00) == 0xd5030000) { + const auto args = read(); + if (args & 0x9ffc0000) fail("unsupported add modifiers"); + const auto a = operand(args & 511), b = operand((args >> 9) & 511); + assign(op & 255, std::string("asuint(") + ((args >> 29) & 1 ? "-" : "") + "asfloat(" + a + ") + " + + ((args >> 30) & 1 ? "-" : "") + "asfloat(" + b + "))"); + } else if (op >> 25 == 3 || op >> 25 == 4 || op >> 25 == 5 || op >> 25 == 8 || op >> 25 == 37 || + op >> 25 == 43) { + const auto d = (op >> 17) & 255; + auto a = operand(op & 511), b = operand(256 + ((op >> 9) & 255)); + if (op >> 25 == 37) + assign(d, a + " + " + b); + else { + a = "asfloat(" + a + ")"; + b = "asfloat(" + b + ")"; + if (op >> 25 == 5) std::swap(a, b); + const auto value = op >> 25 == 43 ? "mad(" + a + "," + b + ",asfloat(" + operand(256 + d) + "))" + : a + + (op >> 25 == 8 ? " * " + : op >> 25 == 3 ? " + " + : " - ") + + b; + assign(d, "asuint(" + value + ")"); + } + } else + return (op >> 16) == 0xbfa1 || (op >> 16) == 0xbf8c; // clause and waitcnt + return true; + } + void export_value(bool pos, Word mask, unsigned param = 0) { + if (pos ? position : parameters[param]) fail("duplicate vertex export"); + const Word sources = read(); + std::string vector; + for (unsigned i = 0; i < 4; ++i) { + if (i) vector += ", "; + const Word reg = (sources >> (8 * i)) & 255; + if (mask & (1u << i)) + vector += "asfloat(" + operand(256 + reg) + ")"; + else { + if (reg != 128) fail("unexpected disabled export operand"); + vector += "0.0"; + } + } + body += (pos ? " o.pos" : " o.param" + std::to_string(param)) + " = float4(" + vector + ");\n"; + (pos ? position : parameters[param]) = true; + } + + public: + VertexProgram(std::string_view bytes, bool uses_buffers) : code(bytes), buffered(uses_buffers) { + values[0] = "vid"; + scalars[0] = {Kind::vb_table, -1}; + scalars[1] = {Kind::vb_tagged_high}; + scalars[2] = {Kind::value, 0, 0, "ud1"}; + scalars[8] = {Kind::table, 0}; + scalars[9] = {Kind::table, 1}; + } + x2w::BufferedVertex translate() { + while (pc < code.size()) { + address = pc; + literal.reset(); + const auto op = read(); + if (op == 0xbf810000) { + if (!position || !parameters[0] || pc != code.size()) + fail("incomplete exports or trailing instructions"); + const std::string param1 = parameters[1] ? "float4 param1 : PARAM1; " : ""; + return {declarations + "cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; " + + (buffered ? "uint ud3; " : "") + "};\nstruct Out { float4 param0 : PARAM0; " + param1 + + "float4 pos : SV_Position; };\nOut vertex(uint vid) {\n Out o;\n" + body + + R"( return o; +} +Out main(uint vid : SV_VertexID) { + if (!ud0) return vertex(vid); + uint first = (vid / 6) * 3, corner = vid % 6; + if (corner < 3) return vertex(first + corner); + if (corner == 3) return vertex(first); + if (corner == 4) return vertex(first + 2); + Out a = vertex(first), b = vertex(first + 1), c = vertex(first + 2), o; + o.pos = a.pos + c.pos - b.pos; + o.param0 = a.param0 + c.param0 - b.param0; +)" + (parameters[1] ? " o.param1 = a.param1 + c.param1 - b.param1;\n" : "") + + R"( return o; +} +)", + bindings}; + } + if ((op >> 16) == 0xbfa0 || (op & ~3u) == 0xbf8f0000) continue; // prefetch and priority + if (buffered && buffer_instruction(op)) continue; + if ((op & 0xfe01fe00) == 0x7e000200 || (op & 0xfe01fe00) == 0x7e000a00) { + auto value = operand(op & 511); + if ((op & 0x1fe00) == 0xa00) value = "asuint(float(asint(" + value + ")))"; + assign((op >> 17) & 255, value); + } else if (op >> 25 == 26 || op >> 25 == 27) { + auto a = operand(op & 511); + auto b = operand(256 + ((op >> 9) & 255)); + assign((op >> 17) & 255, op >> 25 == 26 ? b + " << (" + a + " & 31u)" : a + " & " + b); + } else if ((op & 0xffffff00) == 0xd54b0000) { + const auto args = read(); + if (args & (buffered ? 0x18000000u : 0xf8000000u)) fail("unsupported FMA modifiers"); + auto a = operand(args & 511); + auto b = operand((args >> 9) & 511); + auto c = operand((args >> 18) & 511); + const auto f = [&](const std::string &v, unsigned bit) { + return ((args >> bit) & 1 ? "-asfloat(" : "asfloat(") + v + ")"; + }; + assign(op & 255, "asuint(mad(" + f(a, 29) + ", " + f(b, 30) + ", " + f(c, 31) + "))"); + } else if (op == 0xf80008cf) { + export_value(true, 15); + } else if ((op & ~15u) == 0xf8000200 && (op & 15)) { + export_value(false, op & 15); + } else if (buffered && (op & ~15u) == 0xf8000210 && (op & 15)) { + export_value(false, op & 15, 1); + } else + fail("unsupported vertex instruction"); + } + fail("missing endpgm"); + } +}; +} // namespace + +std::string x2w::translate_gfx1013_vertex_id(std::string_view code) { + return VertexProgram(code, false).translate().hlsl; +} + +x2w::BufferedVertex x2w::translate_gfx1013_buffered_vertex(std::string_view code) { + return VertexProgram(code, true).translate(); +} diff --git a/src/gfx1013_vertex_id.h b/src/gfx1013_vertex_id.h new file mode 100644 index 0000000000..21c1b961c7 --- /dev/null +++ b/src/gfx1013_vertex_id.h @@ -0,0 +1,17 @@ +#pragma once +#include <string> +#include <string_view> + +namespace x2w { +// Raw straight-line vertex entry with SV_VertexID in v0, POS0 and PARAM0. +// Root constant b0.x selects the runtime's rectangle-list expansion. +std::string translate_gfx1013_vertex_id(std::string_view code); + +struct BufferedVertex { + std::string hlsl; + std::string bindings; +}; +// Vertex-buffer table in s[0:1], base vertex in s2, root tables in s8/s9. +// One indexed raw vertex stream, float PARAM0/1, no input-layout fetch routine. +BufferedVertex translate_gfx1013_buffered_vertex(std::string_view code); +} diff --git a/src/guest_shader_container.cpp b/src/guest_shader_container.cpp new file mode 100644 index 0000000000..c4b99da993 --- /dev/null +++ b/src/guest_shader_container.cpp @@ -0,0 +1,261 @@ +#include "guest_shader_container.h" +#include "startup_stubs/inflate.h" +#include <algorithm> +#include <cstring> +#include <stdexcept> + +// Xbox DXIL/XDAT, XBCH and FSSM record fields follow the native-stage layout +// documented in victory-shader native.rs at 9376fd6. The parser and bounds +// checks below are independently implemented using the repository's inflater. +namespace x2w { +namespace { +using Span = std::string_view; +Span slice(Span data, uint64_t offset, uint64_t size) { + if (offset > data.size() || size > data.size() - offset) + throw std::runtime_error("shader record outside its parent"); + return data.substr(static_cast<size_t>(offset), static_cast<size_t>(size)); +} +template <class T> T le(Span data, uint64_t offset) { + T v; + std::memcpy(&v, slice(data, offset, sizeof v).data(), sizeof v); + return v; +} +uint32_t u32(Span s, uint64_t off) { return le<uint32_t>(s, off); } +uint64_t u64(Span s, uint64_t off) { return le<uint64_t>(s, off); } +std::vector<ShaderSemantic> read_signature(Span part, bool extended) { + std::vector<ShaderSemantic> result; + auto count = u32(part, 0); + if (count > 128) + throw std::runtime_error("invalid signature element count"); + const unsigned stride = extended ? 32 : 24; + auto rows = slice(part, u32(part, 4), size_t(count) * stride); + for (unsigned i = 0; i < count; ++i) { + auto row = rows.substr(i * stride, stride); + if (extended && u32(row, 0) != 0) + throw std::runtime_error("unsupported signature stream"); + if (extended) + row.remove_prefix(4); + auto start = u32(row, 0); + auto end = part.find(char(0), start); + if (end == Span::npos || end == start || end - start > 255) + throw std::runtime_error("invalid shader semantic name"); + auto name = part.substr(start, end - start); + result.push_back({std::string(name), u32(row, 4), u32(row, 8), u32(row, 12), u32(row, 16), uint8_t(row[20]), + uint8_t(row[21])}); + } + return result; +} +void graphics_io(GuestShaderStage &stage, Span io) { + const bool pixel = stage.stage == GpuStage::ps; + auto attributes = [&](unsigned offset, unsigned size, unsigned count_at, bool output) { + auto count = u32(io, count_at); + if (count > 32) + throw std::runtime_error("too many native shader attributes"); + auto records = slice(io, offset, uint64_t(count) * size); + for (unsigned n = 0; n < count; ++n) { + auto e = records.substr(n * size, size); + ShaderAttribute a{}; + a.usage = uint8_t(e[0]); + a.row = uint8_t(e[1]); + if (output) { + a.location = uint8_t(e[2]); + a.flags = uint8_t(e[5]); + } else { + a.mask = uint8_t(e[2]) & 15; + a.location = uint8_t(e[3]); + if (pixel) { + a.second_row = uint8_t(e[5]); + a.flags = uint8_t(e[7]); + } else a.last_component = uint8_t(e[4]); + } + (output ? stage.outputs : stage.attributes).push_back(a); + } + }; + if (pixel) { + attributes(0x24, 8, 0x124, false); + stage.pixel_input_address = u32(io, 0x134); + stage.depth_control = u32(io, 0x138); + unsigned words = u32(io, 0x148); + if (words > 10) + throw std::runtime_error("invalid pixel export patch size"); + for (unsigned mrt = 0; mrt < 8; ++mrt) { + unsigned at = 0x14c + mrt * 404, where = u32(io, at); + if (where == UINT32_MAX) + continue; + slice(stage.code, uint64_t(where) * 4, 4 * words); + for (const auto &other : stage.exports) + if (words && uint64_t(where) < other.word_offset + other.full_precision.size() / 4 && + uint64_t(other.word_offset) < uint64_t(where) + words) + throw std::runtime_error("overlapping pixel export patches"); + stage.exports.push_back({mrt, where, std::string(slice(io, at + 4 + 360, 4 * words))}); + } + } else { + attributes(0x24, 5, 0xc4, false); + attributes(0xc8, 6, 0x188, true); + if (stage.stage == GpuStage::ms) { + stage.mesh_clip_control = u32(io, 0x194); + stage.threads[0] = le<uint16_t>(io, 0x448); + stage.max_vertices = le<uint16_t>(io, 0x44a); + stage.max_primitives = le<uint16_t>(io, 0x44c); + stage.topology = le<uint8_t>(io, 0x44f); + } + } +} +void stages(Span packed, std::vector<GuestShaderStage> &result, size_t &total) { + if (slice(packed, 0, 4) != "XBCH" || u32(packed, 4) != 3) + throw std::runtime_error("unsupported native blob version"); + auto payload = slice(packed, 24, u64(packed, 8)); + auto size = u64(packed, 16); + if (size < 16 || size > 16u << 20 || total + size > 64u << 20) + throw std::runtime_error("native stage size out of range"); + total += static_cast<size_t>(size); + std::string inflated(static_cast<size_t>(size), 0); + size_t produced = 0; + if (!x2w_inflate::inflate_zlib(reinterpret_cast<const unsigned char *>(payload.data()), payload.size(), + reinterpret_cast<unsigned char *>(inflated.data()), inflated.size(), + &produced) || + produced != size) + throw std::runtime_error("native stage inflation failed"); + if (slice(inflated, 0, 4) != "FSSM" || u32(inflated, 4) != 0x101 || u64(inflated, 8) != size - 16) + throw std::runtime_error("invalid FSSM header"); + auto body = slice(inflated, 16, size - 16); + if (u64(body, 0) != 6) + throw std::runtime_error("unknown FSSM slot layout"); + constexpr unsigned offsets[]{8, 16, 24, 32, 40, 48, 72, 96}; + for (unsigned i = 0; i < 8; ++i) { + auto off = u64(body, offsets[i]); + if (off == 0xdeadbeefdeadbeefull) + continue; + auto record = slice(body, off, 84); + GuestShaderStage stage{}; + stage.stage = static_cast<GpuStage>(i); + stage.wave32 = (u32(record, 20) & 32) != 0; + stage.vgprs = u32(record, 80) & 1023; + stage.lds_bytes = u32(record, 76); + if (stage.vgprs > 256) + throw std::runtime_error("invalid native register count"); + auto code = slice(body, u64(record, 0), u64(record, 8)); + if (code.size() > 1u << 20) + throw std::runtime_error("native instruction stream too large"); + stage.code = code; + if (stage.code.empty() || stage.code.size() % 4) + throw std::runtime_error("invalid native code size"); + for (unsigned t = 0; t < 2; ++t) { + auto count = u32(record, 56 + t * 4); + if (!count) + continue; + if (count > 65536) + throw std::runtime_error("native resource layout too large"); + auto entries = slice(body, u64(record, 40 + t * 8), uint64_t(count) * 20); + for (unsigned j = 0; j < count; ++j) { + auto e = entries.substr(20ull * j, 20); + if (t == 0) + stage.inputs.push_back( + {u32(e, 0), u32(e, 4), u32(e, 8), u32(e, 12), uint8_t(e[16]), uint8_t(e[17])}); + else + stage.resources.push_back({uint8_t(e[0]), uint8_t(e[1]), u32(e, 4), u32(e, 8), u32(e, 12), + uint8_t(e[16]), uint8_t(e[17]), uint8_t(e[18])}); + } + } + if (stage.stage == GpuStage::cs) { + auto io = slice(body, off + 84 + 36, 16); + stage.rsrc2 = u32(io, 0); + for (unsigned j = 0; j < 3; ++j) + stage.threads[j] = u32(io, 4 + j * 4); + } + if (stage.stage == GpuStage::vs || stage.stage == GpuStage::ms || stage.stage == GpuStage::ps) + graphics_io(stage, body.substr(static_cast<size_t>(off) + 84)); + result.push_back(std::move(stage)); + } +} +} // namespace +unsigned GuestShaderStage::physical_user_sgpr(unsigned logical) const noexcept { + switch (stage) { + case GpuStage::ls: + case GpuStage::hs: + case GpuStage::es: + case GpuStage::gs: + case GpuStage::ms: + return logical + 8; + default: + return logical; + } +} + +std::optional<ShaderIdentifier> native_shader_identifier(std::string_view code) { + // Two literal-bearing V_NOPs carry the sixteen DXBC HASH bytes. Each + // operand selector contributes eight bits; bit 8 is an encoding bit. + if (code.size() < 24) return {}; + ShaderIdentifier id{}; + for (unsigned half = 0; half < 2; ++half) { + const unsigned off = half * 12; + const uint32_t inst = u32(code, off), operands = u32(code, off + 4); + if (inst >> 16 != 0xd580 || (operands & 0xfffe0100u) != 0x03fe0100u) return {}; + auto* bytes = id.data() + half * 8; + bytes[0] = static_cast<uint8_t>(inst); + bytes[1] = static_cast<uint8_t>(inst >> 8); + bytes[2] = static_cast<uint8_t>(operands); + bytes[3] = static_cast<uint8_t>(operands >> 9); + std::memcpy(bytes + 4, code.data() + off + 8, 4); + } + return id; +} +std::string GuestShaderStage::full_precision_code() const { + auto patched = code; + for (const auto &p : exports) + patched.replace(size_t(p.word_offset) * 4, p.full_precision.size(), p.full_precision); + return patched; +} +std::vector<GuestShaderStage> read_guest_shader_container(std::string_view bytes) { + if (slice(bytes, 0, 4) != "DXBC" || u32(bytes, 24) != bytes.size()) + throw std::runtime_error("invalid DXBC length"); + std::vector<GuestShaderStage> result; + size_t total = 0; + std::vector<ShaderSemantic> inputs, outputs; + std::optional<ShaderIdentifier> identifier; + std::optional<unsigned> mesh_threads; + const auto count = u32(bytes, 28); + if (count > 4096) + throw std::runtime_error("invalid DXBC part count"); + auto offsets = slice(bytes, 32, 4ull * count); + for (unsigned i = 0; i < count; ++i) { + uint64_t part = u32(offsets, 4ull * i); + auto data = slice(bytes, part + 8, u32(bytes, part + 4)); + auto kind = slice(bytes, part, 4); + if (kind == "HASH" && data.size() == 20) { + ShaderIdentifier parsed; + std::memcpy(parsed.data(), data.data() + 4, parsed.size()); + if (identifier && *identifier != parsed) throw std::runtime_error("conflicting shader identifiers"); + identifier = parsed; + } + if (kind == "PSV0" && data.size() >= 52 && u32(data, 0) >= 48 && u32(data, 0) <= data.size() - 4) + mesh_threads = u32(data, 40); + if (kind == "ISG1" || kind == "ISGN") + inputs = read_signature(data, kind == "ISG1"); + if (kind == "OSG1" || kind == "OSGN") + outputs = read_signature(data, kind == "OSG1"); + if (kind != "DXIL" || data.size() < 36 || data.substr(24, 4) != "XDAT") + continue; + auto n = u32(data, 28); + if (n > 64) + throw std::runtime_error("invalid XDAT entry count"); + auto entries = slice(data, 36, 12ull * n); + for (unsigned j = 0; j < n; ++j) { + auto row = entries.substr(12ull * j, 12); + auto chunk = slice(data, u32(row, 4), u32(row, 8)); + if (u32(row, 0) == 13) + stages(chunk, result, total); + } + } + for (auto &stage : result) + if (stage.stage == GpuStage::vs || stage.stage == GpuStage::ps || stage.stage == GpuStage::ms) { + stage.input_signature = inputs; + stage.output_signature = outputs; + stage.container_identifier = identifier; + if (stage.stage == GpuStage::ms) + stage.mesh_group_stride = mesh_threads + ? std::max({*mesh_threads, stage.max_vertices, stage.max_primitives}) : stage.threads[0]; + } + return result; +} +} // namespace x2w diff --git a/src/guest_shader_container.h b/src/guest_shader_container.h new file mode 100644 index 0000000000..16445b03a9 --- /dev/null +++ b/src/guest_shader_container.h @@ -0,0 +1,59 @@ +#pragma once +#include <array> +#include <cstdint> +#include <optional> +#include <string> +#include <string_view> +#include <vector> + +namespace x2w { +enum class GpuStage { ls, hs, es, gs, vs, ps, ms, cs }; +using ShaderIdentifier = std::array<uint8_t, 16>; +std::optional<ShaderIdentifier> native_shader_identifier(std::string_view code); +struct ShaderRootInput { + uint32_t type, offset_dwords, sgpr_count, base_register; + uint8_t user_data, root_parameter; +}; +struct ShaderResourceUse { + uint8_t type, root_type; + uint32_t offset_dwords, lower_bound, stride; + uint8_t dwords, user_data, root_parameter; +}; +struct ShaderAttribute { + uint8_t usage, row, mask, location, second_row, flags; + uint8_t last_component{}; +}; +struct PixelExportPatch { + unsigned target, word_offset; + std::string full_precision; +}; +struct ShaderSemantic { + std::string name; + unsigned index, system, component, row; + uint8_t mask, io_mask; +}; +struct GuestShaderStage { + GpuStage stage; + bool wave32; + bool fixed_vertex_abi{}; + unsigned vgprs, lds_bytes; + std::string code; + std::optional<ShaderIdentifier> container_identifier; + std::vector<ShaderRootInput> inputs; + std::vector<ShaderResourceUse> resources; + std::array<unsigned, 3> threads{}; + unsigned rsrc2{}; + std::vector<ShaderAttribute> attributes, outputs; + std::vector<PixelExportPatch> exports; + std::vector<ShaderSemantic> input_signature, output_signature; + unsigned pixel_input_address{}, pixel_input_enable = ~0u, depth_control{}; + // The signature component (9 f32, 5 u32, 4 i32) an RTV variant request asks of each color target; 0 when none. + std::array<unsigned char, 8> target_components{}; + unsigned mesh_clip_control{}, max_vertices{}, max_primitives{}, topology{}; + unsigned mesh_group_stride{}; + // Merged hardware stages reserve the first eight SGPRs for the system entry. + unsigned physical_user_sgpr(unsigned logical) const noexcept; + std::string full_precision_code() const; +}; +std::vector<GuestShaderStage> read_guest_shader_container(std::string_view container); +} // namespace x2w diff --git a/src/mesh_pixel_heap.h b/src/mesh_pixel_heap.h new file mode 100644 index 0000000000..dfb6924830 --- /dev/null +++ b/src/mesh_pixel_heap.h @@ -0,0 +1,7 @@ +#pragma once + +namespace x2w { +// A private shader-visible heap mirrors each proven guest interval once per draw. +struct PixelHeapSpan { unsigned first, last, dimension, host_first; }; +inline constexpr unsigned first_pixel_heap_slot = 1024; // preceding slots reserved for the MS uint selector +} diff --git a/src/mesh_shader_pipeline.cpp b/src/mesh_shader_pipeline.cpp new file mode 100644 index 0000000000..67cc6993c1 --- /dev/null +++ b/src/mesh_shader_pipeline.cpp @@ -0,0 +1,385 @@ +#include "mesh_shader_pipeline.h" + +#include <algorithm> +#include <cstdio> +#include <cstring> +#include <stdexcept> +#include <string> + +#if defined(OFFSCREEN_AGILITY_620) +extern "C" const UINT D3D12SDKVersion; +#endif + +namespace x2w::meshlet { + +namespace { + +using Microsoft::WRL::ComPtr; + +void throw_if_failed(HRESULT hr, const char* context) { + if (FAILED(hr)) { + char buf[128]; + std::snprintf(buf, sizeof(buf), "%s (HRESULT 0x%08lx)", context, static_cast<unsigned long>(hr)); + throw std::runtime_error(buf); + } +} + +HRESULT check_feature_compat(ID3D12Device* device, D3D12_FEATURE feature, void* data, UINT size) { +#if defined(OFFSCREEN_AGILITY_620) && defined(__ID3D12Device16_INTERFACE_DEFINED__) + ComPtr<ID3D12Device16> versioned; + if (SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&versioned)))) { + return versioned->CheckFeatureSupport1(feature, data, size, D3D12SDKVersion); + } +#endif + return device->CheckFeatureSupport(feature, data, size); +} + +D3D12_BLEND_DESC default_opaque_blend() { + D3D12_BLEND_DESC desc{}; + desc.AlphaToCoverageEnable = FALSE; + desc.IndependentBlendEnable = FALSE; + auto& rt = desc.RenderTarget[0]; + rt.BlendEnable = FALSE; + rt.LogicOpEnable = FALSE; + rt.SrcBlend = D3D12_BLEND_ONE; + rt.DestBlend = D3D12_BLEND_ZERO; + rt.BlendOp = D3D12_BLEND_OP_ADD; + rt.SrcBlendAlpha = D3D12_BLEND_ONE; + rt.DestBlendAlpha = D3D12_BLEND_ZERO; + rt.BlendOpAlpha = D3D12_BLEND_OP_ADD; + rt.LogicOp = D3D12_LOGIC_OP_NOOP; + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + return desc; +} + +D3D12_RASTERIZER_DESC default_rasterizer() { + D3D12_RASTERIZER_DESC desc{}; + desc.FillMode = D3D12_FILL_MODE_SOLID; + desc.CullMode = D3D12_CULL_MODE_BACK; + desc.FrontCounterClockwise = FALSE; + desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS; + desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP; + desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS; + desc.DepthClipEnable = TRUE; + desc.MultisampleEnable = FALSE; + desc.AntialiasedLineEnable = FALSE; + desc.ForcedSampleCount = 0; + desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + return desc; +} + +D3D12_DEPTH_STENCIL_DESC default_depth_stencil(DXGI_FORMAT dsv_format) { + D3D12_DEPTH_STENCIL_DESC desc{}; + if (dsv_format != DXGI_FORMAT_UNKNOWN) { + desc.DepthEnable = TRUE; + desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; + } else { + desc.DepthEnable = FALSE; + desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + desc.StencilEnable = FALSE; + desc.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + desc.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + const D3D12_DEPTH_STENCILOP_DESC noop{ + D3D12_STENCIL_OP_KEEP, + D3D12_STENCIL_OP_KEEP, + D3D12_STENCIL_OP_KEEP, + D3D12_COMPARISON_FUNC_ALWAYS, + }; + desc.FrontFace = noop; + desc.BackFace = noop; + return desc; +} + +template <typename Stream> +void populate_common_stream_fields( + Stream& stream, + ID3D12RootSignature* root_sig, + D3D12_SHADER_BYTECODE ps, + DXGI_FORMAT rtv_format, + DXGI_FORMAT dsv_format) { + stream.root_signature.value = root_sig; + stream.ps.value = ps; + stream.blend.value = default_opaque_blend(); + stream.sample_mask.value = UINT_MAX; + stream.rasterizer.value = default_rasterizer(); + stream.depth_stencil.value = default_depth_stencil(dsv_format); + + D3D12_RT_FORMAT_ARRAY rtv_array{}; + rtv_array.NumRenderTargets = 1; + rtv_array.RTFormats[0] = rtv_format; + stream.rtv_formats.value = rtv_array; + + stream.dsv_format.value = dsv_format; + stream.sample_desc.value = DXGI_SAMPLE_DESC{1, 0}; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; +} + +ComPtr<ID3D12RootSignature> serialize_and_create_root( + ID3D12Device* device, + const D3D12_ROOT_SIGNATURE_DESC& desc, + const char* label) { + ComPtr<ID3DBlob> blob; + ComPtr<ID3DBlob> error_blob; + const HRESULT ser_hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &error_blob); + if (FAILED(ser_hr)) { + std::string msg = label; + if (error_blob) { + msg += ": "; + msg.append(static_cast<const char*>(error_blob->GetBufferPointer()), error_blob->GetBufferSize()); + } + throw_if_failed(ser_hr, msg.c_str()); + } + ComPtr<ID3D12RootSignature> root; + throw_if_failed(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), + label); + return root; +} + +ComPtr<ID3D12Resource> upload_typed_buffer( + ID3D12Device* device, + const void* data, + std::size_t byte_size, + const char* label) { + const UINT64 alloc_size = std::max<UINT64>(4, static_cast<UINT64>(byte_size)); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_UPLOAD; + heap.CreationNodeMask = 1; + heap.VisibleNodeMask = 1; + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = alloc_size; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + + ComPtr<ID3D12Resource> buffer; + throw_if_failed(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&buffer)), + label); + if (byte_size > 0 && data != nullptr) { + void* mapped = nullptr; + const D3D12_RANGE empty{0, 0}; + throw_if_failed(buffer->Map(0, &empty, &mapped), label); + std::memcpy(mapped, data, byte_size); + buffer->Unmap(0, nullptr); + } + return buffer; +} + +} // namespace + +MeshShaderCapabilities query_mesh_shader_capabilities(ID3D12Device* device) { + MeshShaderCapabilities caps{}; + if (!device) return caps; + + D3D12_FEATURE_DATA_D3D12_OPTIONS7 options7{}; + if (SUCCEEDED(check_feature_compat(device, D3D12_FEATURE_D3D12_OPTIONS7, &options7, sizeof(options7)))) { + caps.mesh_shader_tier = options7.MeshShaderTier; + } + + for (const D3D_SHADER_MODEL candidate : { + D3D_SHADER_MODEL_6_6, + D3D_SHADER_MODEL_6_5, + D3D_SHADER_MODEL_6_4, + D3D_SHADER_MODEL_6_0, + D3D_SHADER_MODEL_5_1, + }) { + D3D12_FEATURE_DATA_SHADER_MODEL sm{candidate}; + const HRESULT hr = check_feature_compat(device, D3D12_FEATURE_SHADER_MODEL, &sm, sizeof(sm)); + if (SUCCEEDED(hr)) { + caps.highest_shader_model = sm.HighestShaderModel; + break; + } + } + + ComPtr<ID3D12Device2> device2; + caps.has_device2 = SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device2))); + caps.has_command_list6 = caps.has_device2 && (caps.mesh_shader_tier >= D3D12_MESH_SHADER_TIER_1); + return caps; +} + +bool MeshShaderPipeline::initialize( + ID3D12Device* device, + const MeshShaderBytecode& shaders, + MeshShaderPipelineMode mode, + DXGI_FORMAT rtv_format, + DXGI_FORMAT dsv_format) { + if (!device) throw std::invalid_argument("MeshShaderPipeline::initialize requires a valid ID3D12Device"); + + caps_ = query_mesh_shader_capabilities(device); + has_amplification_ = shaders.as.pShaderBytecode != nullptr && shaders.as.BytecodeLength > 0; + + if (mode == MeshShaderPipelineMode::ForceMeshShader) { + if (!caps_.supported()) { + using_mesh_shaders_ = false; + return false; + } + using_mesh_shaders_ = true; + } else if (mode == MeshShaderPipelineMode::ForceVertexFallback) { + using_mesh_shaders_ = false; + } else { + using_mesh_shaders_ = caps_.supported(); + } + + if (using_mesh_shaders_) { + D3D12_ROOT_PARAMETER params[7]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[0].Descriptor = {0, 0}; + params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + + for (UINT i = 0; i < 5; ++i) { + params[1 + i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params[1 + i].Descriptor = {i, 0}; + params[1 + i].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + } + + params[6].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[6].Descriptor = {0, 0}; + params[6].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.NumParameters = 7; + root_desc.pParameters = params; + root_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + root_signature_ = serialize_and_create_root(device, root_desc, "Create mesh shader root signature"); + + ComPtr<ID3D12Device2> device2; + throw_if_failed(device->QueryInterface(IID_PPV_ARGS(&device2)), "Query ID3D12Device2"); + + if (has_amplification_) { + MeshAmplifiedPipelineStream stream{}; + populate_common_stream_fields(stream, root_signature_.Get(), shaders.ps, rtv_format, dsv_format); + stream.as.value = shaders.as; + stream.ms.value = shaders.ms; + D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), &stream}; + throw_if_failed(device2->CreatePipelineState(&stream_desc, IID_PPV_ARGS(&pipeline_state_)), + "Create amplified mesh shader PSO"); + } else { + MeshOnlyPipelineStream stream{}; + populate_common_stream_fields(stream, root_signature_.Get(), shaders.ps, rtv_format, dsv_format); + stream.ms.value = shaders.ms; + D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), &stream}; + throw_if_failed(device2->CreatePipelineState(&stream_desc, IID_PPV_ARGS(&pipeline_state_)), + "Create mesh shader PSO"); + } + return true; + } + + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + param.Descriptor = {0, 0}; + param.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; + + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.NumParameters = 1; + root_desc.pParameters = ¶m; + root_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + root_signature_ = serialize_and_create_root(device, root_desc, "Create vertex fallback root signature"); + + static const D3D12_INPUT_ELEMENT_DESC kInputLayout[]{ + {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 16, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 32, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + }; + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root_signature_.Get(); + pso_desc.VS = shaders.vs; + pso_desc.PS = shaders.ps; + pso_desc.BlendState = default_opaque_blend(); + pso_desc.SampleMask = UINT_MAX; + pso_desc.RasterizerState = default_rasterizer(); + pso_desc.DepthStencilState = default_depth_stencil(dsv_format); + pso_desc.InputLayout = {kInputLayout, static_cast<UINT>(std::size(kInputLayout))}; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = rtv_format; + pso_desc.DSVFormat = dsv_format; + pso_desc.SampleDesc = {1, 0}; + + throw_if_failed(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pipeline_state_)), + "Create vertex fallback PSO"); + return true; +} + +MeshletGpuResources MeshShaderPipeline::create_gpu_resources(ID3D12Device* device, const MeshletBufferData& data) const { + if (!device) throw std::invalid_argument("MeshShaderPipeline::create_gpu_resources requires a valid ID3D12Device"); + + if (using_mesh_shaders_ && std::any_of(data.meshlets.begin(), data.meshlets.end(), [](const MeshletDescriptor& meshlet) { + return meshlet.vertex_count > kMaxMeshletVertices || meshlet.primitive_count > kMaxMeshletPrimitives; + })) { + throw std::invalid_argument("Meshlet exceeds the mesh shader output capacity (64 vertices, 126 primitives)"); + } + + MeshletGpuResources res; + const std::size_t vb_bytes = data.vertices.size() * sizeof(MeshletVertex); + const std::size_t ib_bytes = data.source_indices.size() * sizeof(std::uint32_t); + + res.vertices = upload_typed_buffer(device, data.vertices.data(), vb_bytes, "Create meshlet vertices buffer"); + res.indices = upload_typed_buffer(device, data.source_indices.data(), ib_bytes, "Create fallback index buffer"); + res.meshlets = upload_typed_buffer(device, data.meshlets.data(), + data.meshlets.size() * sizeof(MeshletDescriptor), "Create meshlets buffer"); + res.bounds = upload_typed_buffer(device, data.bounds.data(), + data.bounds.size() * sizeof(MeshletBounds), "Create meshlet bounds buffer"); + res.unique_vertex_indices = upload_typed_buffer(device, data.unique_vertex_indices.data(), + data.unique_vertex_indices.size() * sizeof(std::uint32_t), + "Create unique vertex indices buffer"); + res.packed_primitives = upload_typed_buffer(device, data.packed_primitives.data(), + data.packed_primitives.size() * sizeof(std::uint32_t), + "Create packed primitives buffer"); + + res.vbv.BufferLocation = res.vertices->GetGPUVirtualAddress(); + res.vbv.SizeInBytes = static_cast<UINT>(vb_bytes); + res.vbv.StrideInBytes = sizeof(MeshletVertex); + + res.ibv.BufferLocation = res.indices->GetGPUVirtualAddress(); + res.ibv.SizeInBytes = static_cast<UINT>(ib_bytes); + res.ibv.Format = DXGI_FORMAT_R32_UINT; + + res.meshlet_count = static_cast<std::uint32_t>(data.meshlets.size()); + res.index_count = static_cast<std::uint32_t>(data.source_indices.size()); + return res; +} + +void MeshShaderPipeline::record_draw( + ID3D12GraphicsCommandList* list, + D3D12_GPU_VIRTUAL_ADDRESS scene_cb_va, + D3D12_GPU_VIRTUAL_ADDRESS stats_uav_va, + const MeshletGpuResources& resources) const { + if (!list || !root_signature_ || !pipeline_state_) { + throw std::runtime_error("MeshShaderPipeline::record_draw called before initialize"); + } + + list->SetGraphicsRootSignature(root_signature_.Get()); + list->SetPipelineState(pipeline_state_.Get()); + list->SetGraphicsRootConstantBufferView(0, scene_cb_va); + + if (using_mesh_shaders_) { + if (resources.meshlet_count == 0) return; + list->SetGraphicsRootShaderResourceView(1, resources.vertices->GetGPUVirtualAddress()); + list->SetGraphicsRootShaderResourceView(2, resources.meshlets->GetGPUVirtualAddress()); + list->SetGraphicsRootShaderResourceView(3, resources.bounds->GetGPUVirtualAddress()); + list->SetGraphicsRootShaderResourceView(4, resources.unique_vertex_indices->GetGPUVirtualAddress()); + list->SetGraphicsRootShaderResourceView(5, resources.packed_primitives->GetGPUVirtualAddress()); + list->SetGraphicsRootUnorderedAccessView(6, stats_uav_va); + + ComPtr<ID3D12GraphicsCommandList6> mesh_list; + throw_if_failed(list->QueryInterface(IID_PPV_ARGS(&mesh_list)), "Query ID3D12GraphicsCommandList6"); + const UINT group_count = has_amplification_ ? (resources.meshlet_count + 31u) / 32u : resources.meshlet_count; + mesh_list->DispatchMesh(group_count, 1, 1); + } else { + if (resources.index_count == 0) return; + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->IASetVertexBuffers(0, 1, &resources.vbv); + list->IASetIndexBuffer(&resources.ibv); + list->DrawIndexedInstanced(resources.index_count, 1, 0, 0, 0); + } +} + +} // namespace x2w::meshlet diff --git a/src/mesh_shader_pipeline.h b/src/mesh_shader_pipeline.h new file mode 100644 index 0000000000..984ae323b0 --- /dev/null +++ b/src/mesh_shader_pipeline.h @@ -0,0 +1,132 @@ +#pragma once + +#include "meshlet_builder.h" + +#include <d3d12.h> +#include <wrl/client.h> + +#include <cstdint> + +namespace x2w::meshlet { + +struct MeshShaderCapabilities { + D3D12_MESH_SHADER_TIER mesh_shader_tier = D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; + D3D_SHADER_MODEL highest_shader_model = D3D_SHADER_MODEL_5_1; + bool has_device2 = false; + bool has_command_list6 = false; + + bool supported() const noexcept { + return mesh_shader_tier >= D3D12_MESH_SHADER_TIER_1 && + highest_shader_model >= D3D_SHADER_MODEL_6_5 && + has_device2; + } +}; + +MeshShaderCapabilities query_mesh_shader_capabilities(ID3D12Device* device); + +template <D3D12_PIPELINE_STATE_SUBOBJECT_TYPE Type, typename Value> +struct alignas(void*) PipelineSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = Type; + Value value{}; +}; + +// D3D12_PIPELINE_STATE_STREAM_DESC layout matching D3DX12_MESH_SHADER_PIPELINE_STATE_DESC +// (AS + MS + PS) without requiring an external d3dx12.h dependency. +struct MeshAmplifiedPipelineStream { + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*> root_signature; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE> as; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE> ms; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE> ps; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC> blend; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT> sample_mask; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC> rasterizer; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC> depth_stencil; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY> rtv_formats; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT> dsv_format; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC> sample_desc; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE> topology; +}; + +// Variant without AS subobject (an empty AS subobject is invalid in D3D12). +struct MeshOnlyPipelineStream { + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, ID3D12RootSignature*> root_signature; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE> ms; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE> ps; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC> blend; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT> sample_mask; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC> rasterizer; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC> depth_stencil; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY> rtv_formats; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT> dsv_format; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC> sample_desc; + PipelineSubobject<D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, D3D12_PRIMITIVE_TOPOLOGY_TYPE> topology; +}; + +enum class MeshShaderPipelineMode { + Auto, + ForceMeshShader, + ForceVertexFallback, +}; + +struct MeshShaderBytecode { + D3D12_SHADER_BYTECODE as{}; + D3D12_SHADER_BYTECODE ms{}; + D3D12_SHADER_BYTECODE vs{}; + D3D12_SHADER_BYTECODE ps{}; +}; + +struct alignas(256) SceneConstantsGPU { + float view_proj[16]{}; + float frustum_planes[6][4]{}; + float camera_pos[4]{}; + std::uint32_t meshlet_count = 0; + std::uint32_t pad0 = 0; + std::uint32_t pad1 = 0; + std::uint32_t pad2 = 0; +}; +static_assert(sizeof(SceneConstantsGPU) == 256, "SceneConstantsGPU must be 256-byte CBV aligned"); + +struct MeshletGpuResources { + Microsoft::WRL::ComPtr<ID3D12Resource> vertices; + Microsoft::WRL::ComPtr<ID3D12Resource> indices; + Microsoft::WRL::ComPtr<ID3D12Resource> meshlets; + Microsoft::WRL::ComPtr<ID3D12Resource> bounds; + Microsoft::WRL::ComPtr<ID3D12Resource> unique_vertex_indices; + Microsoft::WRL::ComPtr<ID3D12Resource> packed_primitives; + D3D12_VERTEX_BUFFER_VIEW vbv{}; + D3D12_INDEX_BUFFER_VIEW ibv{}; + std::uint32_t meshlet_count = 0; + std::uint32_t index_count = 0; +}; + +class MeshShaderPipeline { +public: + // Returns false only when mode == ForceMeshShader and the device lacks MeshShaderTier_1 / SM 6.5 / ID3D12Device2. + bool initialize( + ID3D12Device* device, + const MeshShaderBytecode& shaders, + MeshShaderPipelineMode mode, + DXGI_FORMAT rtv_format, + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN); + + // The mesh path accepts up to 64 vertices and 126 primitives per meshlet. + MeshletGpuResources create_gpu_resources(ID3D12Device* device, const MeshletBufferData& data) const; + + void record_draw( + ID3D12GraphicsCommandList* list, + D3D12_GPU_VIRTUAL_ADDRESS scene_cb_va, + D3D12_GPU_VIRTUAL_ADDRESS stats_uav_va, + const MeshletGpuResources& resources) const; + + bool using_mesh_shaders() const noexcept { return using_mesh_shaders_; } + const MeshShaderCapabilities& capabilities() const noexcept { return caps_; } + +private: + MeshShaderCapabilities caps_{}; + bool using_mesh_shaders_ = false; + bool has_amplification_ = false; + Microsoft::WRL::ComPtr<ID3D12RootSignature> root_signature_; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pipeline_state_; +}; + +} // namespace x2w::meshlet diff --git a/src/meshlet_builder.cpp b/src/meshlet_builder.cpp new file mode 100644 index 0000000000..35c3f271e7 --- /dev/null +++ b/src/meshlet_builder.cpp @@ -0,0 +1,309 @@ +#include "meshlet_builder.h" + +#include <algorithm> +#include <array> +#include <cmath> +#include <limits> +#include <stdexcept> +#include <unordered_map> + +namespace x2w::meshlet { + +namespace { + +struct Vec3 { + float x; + float y; + float z; +}; + +Vec3 to_vec3(const float v[3]) { + return {v[0], v[1], v[2]}; +} + +Vec3 operator+(const Vec3& a, const Vec3& b) { + return {a.x + b.x, a.y + b.y, a.z + b.z}; +} + +Vec3 operator-(const Vec3& a, const Vec3& b) { + return {a.x - b.x, a.y - b.y, a.z - b.z}; +} + +Vec3 operator*(const Vec3& a, float s) { + return {a.x * s, a.y * s, a.z * s}; +} + +float dot(const Vec3& a, const Vec3& b) { + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +Vec3 cross(const Vec3& a, const Vec3& b) { + return { + a.y * b.z - a.z * b.y, + a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x, + }; +} + +float length_sq(const Vec3& v) { + return dot(v, v); +} + +bool normalize(const Vec3& v, Vec3& out) { + const float len_sq = length_sq(v); + if (len_sq <= 1e-12f) return false; + const float inv_len = 1.0f / std::sqrt(len_sq); + out = v * inv_len; + return true; +} + +std::uint32_t pack_primitive(std::uint32_t i0, std::uint32_t i1, std::uint32_t i2) { + return (i0 & 0xFFu) | ((i1 & 0xFFu) << 8) | ((i2 & 0xFFu) << 16); +} + +MeshletBounds compute_bounds( + const std::vector<MeshletVertex>& vertices, + const std::uint32_t* unique_vertices, + std::uint32_t vertex_count, + const std::uint32_t* packed_primitives, + std::uint32_t primitive_count) { + MeshletBounds result{}; + result.cone_cutoff = 2.0f; // > 1.0 disables backface cone culling by default. + + if (vertex_count == 0) return result; + + Vec3 min_p = to_vec3(vertices[unique_vertices[0]].position); + Vec3 max_p = min_p; + for (std::uint32_t i = 1; i < vertex_count; ++i) { + const Vec3 p = to_vec3(vertices[unique_vertices[i]].position); + min_p.x = std::min(min_p.x, p.x); + min_p.y = std::min(min_p.y, p.y); + min_p.z = std::min(min_p.z, p.z); + max_p.x = std::max(max_p.x, p.x); + max_p.y = std::max(max_p.y, p.y); + max_p.z = std::max(max_p.z, p.z); + } + + const Vec3 center = (min_p + max_p) * 0.5f; + float max_dist_sq = 0.0f; + for (std::uint32_t i = 0; i < vertex_count; ++i) { + const Vec3 p = to_vec3(vertices[unique_vertices[i]].position); + max_dist_sq = std::max(max_dist_sq, length_sq(p - center)); + } + + result.center[0] = center.x; + result.center[1] = center.y; + result.center[2] = center.z; + result.radius = std::sqrt(max_dist_sq); + + struct TrianglePlane { + Vec3 p0; + Vec3 normal; + }; + std::vector<TrianglePlane> planes; + planes.reserve(primitive_count); + + Vec3 normal_sum{0.0f, 0.0f, 0.0f}; + for (std::uint32_t p = 0; p < primitive_count; ++p) { + const std::uint32_t packed = packed_primitives[p]; + const std::uint32_t i0 = unique_vertices[packed & 0xFFu]; + const std::uint32_t i1 = unique_vertices[(packed >> 8) & 0xFFu]; + const std::uint32_t i2 = unique_vertices[(packed >> 16) & 0xFFu]; + const Vec3 v0 = to_vec3(vertices[i0].position); + const Vec3 v1 = to_vec3(vertices[i1].position); + const Vec3 v2 = to_vec3(vertices[i2].position); + Vec3 n{}; + if (!normalize(cross(v1 - v0, v2 - v0), n)) continue; + normal_sum = normal_sum + n; + planes.push_back({v0, n}); + } + + Vec3 cone_axis{}; + if (planes.empty() || !normalize(normal_sum, cone_axis)) { + result.cone_apex[0] = center.x; + result.cone_apex[1] = center.y; + result.cone_apex[2] = center.z; + return result; + } + + float min_dot = 1.0f; + for (const auto& plane : planes) { + min_dot = std::min(min_dot, dot(plane.normal, cone_axis)); + } + + result.cone_axis[0] = cone_axis.x; + result.cone_axis[1] = cone_axis.y; + result.cone_axis[2] = cone_axis.z; + + if (min_dot <= 0.1f) { + result.cone_apex[0] = center.x; + result.cone_apex[1] = center.y; + result.cone_apex[2] = center.z; + result.cone_cutoff = 2.0f; + return result; + } + + float max_t = 0.0f; + for (const auto& plane : planes) { + const float denom = dot(cone_axis, plane.normal); + max_t = std::max(max_t, dot(center - plane.p0, plane.normal) / denom); + } + + const Vec3 cone_apex = center - cone_axis * max_t; + result.cone_apex[0] = cone_apex.x; + result.cone_apex[1] = cone_apex.y; + result.cone_apex[2] = cone_apex.z; + result.cone_cutoff = std::sqrt(std::max(0.0f, 1.0f - min_dot * min_dot)); + return result; +} + +void append_quad( + std::vector<MeshletVertex>& vertices, + std::vector<std::uint32_t>& indices, + float x0, float y0, + float x1, float y1, + float z, + bool front_facing_cw, + const std::array<float, 4>& color) { + const std::uint32_t base = static_cast<std::uint32_t>(vertices.size()); + const float nz = front_facing_cw ? -1.0f : 1.0f; + const auto make_vertex = [&](float x, float y) -> MeshletVertex { + return MeshletVertex{ + {x, y, z}, 0.0f, + {0.0f, 0.0f, nz}, 0.0f, + {color[0], color[1], color[2], color[3]}, + }; + }; + vertices.push_back(make_vertex(x0, y0)); // 0: bottom-left + vertices.push_back(make_vertex(x0, y1)); // 1: top-left + vertices.push_back(make_vertex(x1, y1)); // 2: top-right + vertices.push_back(make_vertex(x1, y0)); // 3: bottom-right + + if (front_facing_cw) { + indices.insert(indices.end(), {base + 0, base + 1, base + 2, base + 0, base + 2, base + 3}); + } else { + indices.insert(indices.end(), {base + 0, base + 2, base + 1, base + 0, base + 3, base + 2}); + } +} + +} // namespace + +MeshletBufferData build_meshlets( + const std::vector<MeshletVertex>& vertices, + const std::vector<std::uint32_t>& indices, + std::uint32_t max_vertices, + std::uint32_t max_primitives) { + if (indices.size() % 3 != 0) { + throw std::invalid_argument("Meshlet index buffer length must be a multiple of 3"); + } + if (max_vertices < 3 || max_vertices > kHardwareMaxMeshletVertices) { + throw std::invalid_argument("Meshlet max_vertices must be in [3, 256]"); + } + if (max_primitives == 0 || max_primitives > kHardwareMaxMeshletPrimitives) { + throw std::invalid_argument("Meshlet max_primitives must be in [1, 256]"); + } + for (const std::uint32_t idx : indices) { + if (idx >= vertices.size()) { + throw std::invalid_argument("Meshlet index exceeds vertex buffer bounds"); + } + } + + MeshletBufferData out; + out.vertices = vertices; + out.source_indices = indices; + + if (indices.empty()) return out; + + std::unordered_map<std::uint32_t, std::uint32_t> local_map; + local_map.reserve(max_vertices); + std::uint32_t current_vertex_offset = 0; + std::uint32_t current_primitive_offset = 0; + std::uint32_t current_vertex_count = 0; + std::uint32_t current_primitive_count = 0; + + auto flush_meshlet = [&]() { + if (current_primitive_count == 0) return; + MeshletDescriptor desc{ + current_vertex_count, + current_vertex_offset, + current_primitive_count, + current_primitive_offset, + }; + out.meshlets.push_back(desc); + out.bounds.push_back(compute_bounds( + out.vertices, + out.unique_vertex_indices.data() + current_vertex_offset, + current_vertex_count, + out.packed_primitives.data() + current_primitive_offset, + current_primitive_count)); + current_vertex_offset = static_cast<std::uint32_t>(out.unique_vertex_indices.size()); + current_primitive_offset = static_cast<std::uint32_t>(out.packed_primitives.size()); + current_vertex_count = 0; + current_primitive_count = 0; + local_map.clear(); + }; + + const std::size_t tri_count = indices.size() / 3; + for (std::size_t t = 0; t < tri_count; ++t) { + const std::uint32_t tri[3]{ + indices[t * 3 + 0], + indices[t * 3 + 1], + indices[t * 3 + 2], + }; + + std::uint32_t new_vertices = 0; + for (int k = 0; k < 3; ++k) { + bool seen_in_tri = false; + for (int prev = 0; prev < k; ++prev) { + if (tri[prev] == tri[k]) { + seen_in_tri = true; + break; + } + } + if (!seen_in_tri && local_map.find(tri[k]) == local_map.end()) { + ++new_vertices; + } + } + + if (current_primitive_count > 0 && + (current_primitive_count + 1 > max_primitives || + current_vertex_count + new_vertices > max_vertices)) { + flush_meshlet(); + } + + std::uint32_t local_tri[3]{}; + for (int k = 0; k < 3; ++k) { + auto [it, inserted] = local_map.emplace(tri[k], current_vertex_count); + if (inserted) { + out.unique_vertex_indices.push_back(tri[k]); + ++current_vertex_count; + } + local_tri[k] = it->second; + } + out.packed_primitives.push_back(pack_primitive(local_tri[0], local_tri[1], local_tri[2])); + ++current_primitive_count; + } + + flush_meshlet(); + return out; +} + +MeshletBufferData build_culling_test_scene() { + std::vector<MeshletVertex> vertices; + std::vector<std::uint32_t> indices; + vertices.reserve(16); + indices.reserve(24); + + // Meshlet 0: visible green quad on the left. + append_quad(vertices, indices, -0.8f, -0.7f, -0.1f, 0.7f, 0.5f, true, {0.0f, 1.0f, 0.0f, 1.0f}); + // Meshlet 1: visible blue quad on the right. + append_quad(vertices, indices, 0.1f, -0.7f, 0.8f, 0.7f, 0.5f, true, {0.0f, 0.0f, 1.0f, 1.0f}); + // Meshlet 2: back-facing red quad in the center (culled by AS normal cone and VS CULL_MODE_BACK). + append_quad(vertices, indices, -0.4f, -0.4f, 0.4f, 0.4f, 0.25f, false, {1.0f, 0.0f, 0.0f, 1.0f}); + // Meshlet 3: front-facing yellow quad outside the right frustum plane (culled by AS frustum test). + append_quad(vertices, indices, 2.5f, -0.5f, 3.5f, 0.5f, 0.5f, true, {1.0f, 1.0f, 0.0f, 1.0f}); + + return build_meshlets(vertices, indices, kMaxMeshletVertices, 2); +} + +} // namespace x2w::meshlet diff --git a/src/meshlet_builder.h b/src/meshlet_builder.h new file mode 100644 index 0000000000..fd8870664a --- /dev/null +++ b/src/meshlet_builder.h @@ -0,0 +1,62 @@ +#pragma once + +#include <cstdint> +#include <vector> + +namespace x2w::meshlet { + +inline constexpr std::uint32_t kMaxMeshletVertices = 64; +inline constexpr std::uint32_t kMaxMeshletPrimitives = 126; +inline constexpr std::uint32_t kHardwareMaxMeshletVertices = 256; +inline constexpr std::uint32_t kHardwareMaxMeshletPrimitives = 256; + +struct alignas(16) MeshletVertex { + float position[3]; + float pad0; + float normal[3]; + float pad1; + float color[4]; +}; +static_assert(sizeof(MeshletVertex) == 48, "MeshletVertex must match HLSL StructuredBuffer stride (48 bytes)"); + +struct MeshletDescriptor { + std::uint32_t vertex_count; + std::uint32_t vertex_offset; + std::uint32_t primitive_count; + std::uint32_t primitive_offset; +}; +static_assert(sizeof(MeshletDescriptor) == 16, "MeshletDescriptor must match HLSL StructuredBuffer stride (16 bytes)"); + +struct alignas(16) MeshletBounds { + float center[3]; + float radius; + float cone_apex[3]; + float cone_cutoff; + float cone_axis[3]; + float pad0; +}; +static_assert(sizeof(MeshletBounds) == 48, "MeshletBounds must match HLSL StructuredBuffer stride (48 bytes)"); + +struct MeshletBufferData { + std::vector<MeshletVertex> vertices; + std::vector<std::uint32_t> source_indices; + std::vector<MeshletDescriptor> meshlets; + std::vector<MeshletBounds> bounds; + std::vector<std::uint32_t> unique_vertex_indices; + std::vector<std::uint32_t> packed_primitives; +}; + +// Partitions an indexed triangle list into meshlets bounded by max_vertices and max_primitives, +// emitting per-meshlet bounding spheres and normal cones for amplification shader culling. +// max_vertices must be in [3, 256] (a triangle can need three vertex slots) and max_primitives in [1, 256]; +// no meshlet exceeds either limit. +MeshletBufferData build_meshlets( + const std::vector<MeshletVertex>& vertices, + const std::vector<std::uint32_t>& indices, + std::uint32_t max_vertices = kMaxMeshletVertices, + std::uint32_t max_primitives = kMaxMeshletPrimitives); + +// Synthetic 4-meshlet scene exercising visible, backface-culled, and frustum-culled meshlets. +MeshletBufferData build_culling_test_scene(); + +} // namespace x2w::meshlet diff --git a/src/native_buffer_store_view.h b/src/native_buffer_store_view.h new file mode 100644 index 0000000000..8e2ec3c099 --- /dev/null +++ b/src/native_buffer_store_view.h @@ -0,0 +1,91 @@ +#pragma once +#include "gfx1013_compute_native.h" +#include "startup_stubs/native_buffer_stride.h" +#include <d3d12.h> + +// Preserve the guest view window. The HLSL resource type determines the desktop component type. +namespace x2w { +inline DXGI_FORMAT native_half_buffer_format(unsigned bytes) { + switch (bytes) { + case 2: return DXGI_FORMAT_R16_FLOAT; + case 4: return DXGI_FORMAT_R16G16_FLOAT; + case 8: return DXGI_FORMAT_R16G16B16A16_FLOAT; + default: return DXGI_FORMAT_UNKNOWN; + } +} + +inline bool native_buffer_store_view(const ComputeViewBinding &binding, D3D12_UNORDERED_ACCESS_VIEW_DESC &view, + UINT64 resource_bytes, IndexedAtomicView *atomic = nullptr) { + if (view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER || view.Buffer.CounterOffsetInBytes || + !view.Buffer.NumElements) + return false; + if (binding.kind == ComputeViewKind::indexed_atomic_uav) { + if (!atomic) return false; + // Victory's view_stride: structured indices advance by StructureByteStride, + // raw indices are byte offsets and typed indices advance by format width. + const bool raw = view.Buffer.Flags == D3D12_BUFFER_UAV_FLAG_RAW; + const UINT structured = view.Buffer.StructureByteStride; + if (raw) { + if (structured || view.Format != DXGI_FORMAT_R32_TYPELESS) return false; + } else if (view.Buffer.Flags) { + return false; + } else if (structured) { + if (view.Format != DXGI_FORMAT_UNKNOWN || structured % 4 || + structured > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) return false; + } else if (view.Format != DXGI_FORMAT_R32_UINT && view.Format != DXGI_FORMAT_R32_SINT) { + return false; + } + UINT guest_stride = 0; + if (!x2w_startup::native_view_stride(19, &view, sizeof(view), guest_stride)) return false; + const UINT bytes_per_element = raw ? 4 : guest_stride; + const UINT64 bytes = UINT64(view.Buffer.NumElements) * bytes_per_element; + const UINT64 capacity = resource_bytes / bytes_per_element; + if (bytes > UINT32_MAX || view.Buffer.FirstElement > capacity || + view.Buffer.NumElements > capacity - view.Buffer.FirstElement) return false; + const UINT64 start = view.Buffer.FirstElement * bytes_per_element; + if (start % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) return false; + *atomic = {guest_stride, raw ? UINT(bytes - 3) : view.Buffer.NumElements}; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.Buffer.FirstElement = start / 4; + view.Buffer.NumElements = UINT(bytes / 4); + view.Buffer.StructureByteStride = 0; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + return true; + } + if (view.Buffer.StructureByteStride) return false; + UINT stride = binding.required_bytes; + if (binding.kind == ComputeViewKind::raw_buffer_uav) { + if (view.Format != DXGI_FORMAT_R32_TYPELESS || view.Buffer.Flags != D3D12_BUFFER_UAV_FLAG_RAW || + view.Buffer.FirstElement % (D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT / 4)) + return false; + stride = 4; + } else if (view.Buffer.Flags) { + return false; + } else if (binding.kind == ComputeViewKind::packed_d16_x_uav) { + if (stride != 2) return false; + if (view.Format == DXGI_FORMAT_R32_UINT) stride = 4; + else if (view.Format == DXGI_FORMAT_R16_FLOAT || view.Format == DXGI_FORMAT_R16_UINT) + view.Format = DXGI_FORMAT_R16_UINT; + else return false; + } else if (binding.kind == ComputeViewKind::half_buffer_uav) { + const auto format = native_half_buffer_format(stride); + if (format == DXGI_FORMAT_UNKNOWN || view.Format != format) + return false; + } else if (binding.kind == ComputeViewKind::typed_buffer_uav) { + const DXGI_FORMAT formats[][3] = { + {DXGI_FORMAT_R32_UINT,DXGI_FORMAT_R32_SINT,DXGI_FORMAT_R32_FLOAT}, + {DXGI_FORMAT_R32G32_UINT,DXGI_FORMAT_R32G32_SINT,DXGI_FORMAT_R32G32_FLOAT}, + {DXGI_FORMAT_R32G32B32_UINT,DXGI_FORMAT_R32G32B32_SINT,DXGI_FORMAT_R32G32B32_FLOAT}, + {DXGI_FORMAT_R32G32B32A32_UINT,DXGI_FORMAT_R32G32B32A32_SINT,DXGI_FORMAT_R32G32B32A32_FLOAT} + }; + if (stride < 4 || stride > 16 || stride % 4) return false; + const auto &shape = formats[stride / 4 - 1]; + if (view.Format != shape[0] && view.Format != shape[1] && view.Format != shape[2]) return false; + view.Format = shape[0]; + } else { + return false; + } + const UINT64 capacity = resource_bytes / stride; + return view.Buffer.FirstElement <= capacity && view.Buffer.NumElements <= capacity - view.Buffer.FirstElement; +} +} diff --git a/src/native_compute_output.h b/src/native_compute_output.h new file mode 100644 index 0000000000..24b8ccd3ba --- /dev/null +++ b/src/native_compute_output.h @@ -0,0 +1,34 @@ +#pragma once + +#include <charconv> +#include <string_view> + +namespace x2w { +// Bump whenever a native translation of an unchanged request can change meaning. +constexpr unsigned native_compute_output_revision = 1; + +enum class NativeComputeOutput { unmarked, current, incompatible }; + +inline NativeComputeOutput native_compute_output(std::string_view manifest) +{ + auto output = NativeComputeOutput::unmarked; + while (!manifest.empty()) { + const auto end = manifest.find('\n'); + auto line = manifest.substr(0, end); + manifest.remove_prefix(end == std::string_view::npos ? manifest.size() : end + 1); + if (!line.empty() && line.back() == '\r') + line.remove_suffix(1); + if (line != "native" && line.substr(0, 7) != "native ") + continue; + if (output != NativeComputeOutput::unmarked || line.size() <= 7) + return NativeComputeOutput::incompatible; + unsigned revision = 0; + const auto last = line.data() + line.size(); + const auto parsed = std::from_chars(line.data() + 7, last, revision); + if (parsed.ec != std::errc{} || parsed.ptr != last || revision != native_compute_output_revision) + return NativeComputeOutput::incompatible; + output = NativeComputeOutput::current; + } + return output; +} +} diff --git a/src/native_compute_pipeline.cpp b/src/native_compute_pipeline.cpp new file mode 100644 index 0000000000..f0f51b1299 --- /dev/null +++ b/src/native_compute_pipeline.cpp @@ -0,0 +1,158 @@ +#include "native_compute_pipeline.h" +#include "direct_compute_cache.h" +#include "startup_stubs/translated_sampler_bindings.h" +#include <algorithm> +#include <chrono> +#include <stdexcept> + +namespace x2w { +namespace { +using Clock = std::chrono::steady_clock; +double elapsed(Clock::time_point start) { + return std::chrono::duration<double, std::milli>(Clock::now() - start).count(); +} +bool is_uav(const ComputeViewBinding &binding) { return compute_uav(binding.kind); } +} // namespace + +NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, + const std::filesystem::path &marker, unsigned entry, + const std::filesystem::path &cache, bool direct_dxil, + HeapViewContract heap_view) { + if (!direct_dxil && heap_view != HeapViewContract::none) + throw std::runtime_error("a heap view contract needs the direct DXIL path"); + NativeComputePipeline pipeline; + auto start = Clock::now(); + auto program = direct_dxil + ? prepare_direct_compute(marker,entry,marker.extension()==L".cdx",cache,pipeline.frontend_cache_hit,heap_view) + : translate_compute(read_compute_request(marker), entry, direct_dxil); + pipeline.instructions = program.instruction_count; + pipeline.bindings = std::move(program.bindings); + std::sort(pipeline.bindings.begin(), pipeline.bindings.end(), [](auto &a, auto &b) { + if (is_uav(a) != is_uav(b)) + return !is_uav(a); + return a.shader_register < b.shader_register; + }); + + UINT counts[2]{}; + for (const auto &binding : pipeline.bindings) { + if (binding.kind == ComputeViewKind::heap_sampler) { + pipeline.sampler_heap_indexed = true; // SamplerDescriptorHeap reads: no table register + continue; + } + if (compute_heap_binding(binding.kind)) { + pipeline.heap_indexed = true; // ResourceDescriptorHeap reads: no table register + continue; + } + auto &count = counts[is_uav(binding)]; + if (binding.shader_register != count++) + throw std::runtime_error("noncontiguous compute register range"); + } + pipeline.uav_count = counts[1]; + pipeline.constants = std::move(program.constants); + pipeline.stride_srvs = std::move(program.stride_srvs); + for (const auto &block : pipeline.constants) + pipeline.constant_words += block.count; + pipeline.srv_count = counts[0]; + std::vector<D3D12_STATIC_SAMPLER_DESC> samplers; + for (const auto &sampler : program.samplers) { + samplers.push_back(x2w_startup::decode_sampler(sampler.words, static_cast<UINT>(samplers.size()), sampler.comparison, + sampler.explicit_lod)); + } + pipeline.frontend_ms = elapsed(start); + start = Clock::now(); + auto shader = compiler.compile(direct_dxil ? program.dxil_ir : program.hlsl, L"cs_6_6", cache, + direct_dxil ? ShaderSourceFormat::dxil_ir : ShaderSourceFormat::hlsl); + pipeline.backend_ms = elapsed(start); + pipeline.cache_hit = shader.cache_hit; + + start = Clock::now(); + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + for (const auto &b : pipeline.bindings) + pipeline.atomic_views += b.kind == ComputeViewKind::indexed_atomic_uav; + const auto b0_words = pipeline.constant_words + static_cast<unsigned>(pipeline.stride_srvs.size()); + if (unsigned(bool(counts[0])) + unsigned(bool(counts[1])) + b0_words + + 2 * pipeline.atomic_views > D3D12_MAX_ROOT_COST) + throw UnsupportedComputeShader("indexed atomic view metadata exceeds root parameter budget"); + std::vector<D3D12_ROOT_PARAMETER> params(3 + pipeline.atomic_views); + unsigned param_count = 0; + for (UINT i = 0; i < 2; ++i) { + if (!counts[i]) + continue; + auto ¶m = params[param_count++]; + ranges[i].RangeType = i ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + ranges[i].NumDescriptors = counts[i]; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + param.DescriptorTable = {1, &ranges[i]}; + } + if (b0_words) { + auto ¶m = params[param_count++]; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues = b0_words; + } + for (const auto &b : pipeline.bindings) { + if (b.kind != ComputeViewKind::indexed_atomic_uav) continue; + auto ¶m = params[param_count++]; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {b.shader_register + 1, 0, 2}; + } + const UINT root_flags = (pipeline.heap_indexed ? 0x400u : 0u) // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | (pipeline.sampler_heap_indexed ? 0x800u : 0u); // SAMPLER_HEAP_DIRECTLY_INDEXED + D3D12_ROOT_SIGNATURE_DESC desc{param_count, params.data(), static_cast<UINT>(samplers.size()), samplers.data(), + static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(root_flags)}; + Microsoft::WRL::ComPtr<ID3DBlob> blob; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&pipeline.root)))) + throw std::runtime_error("native compute root signature creation failed"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = pipeline.root.Get(); + pso.CS = {shader.dxil.data(), shader.dxil.size()}; + if (FAILED(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline.state)))) + throw std::runtime_error("native compute PSO creation failed"); + pipeline.pipeline_ms = elapsed(start); + return pipeline; +} + +void NativeComputePipeline::bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, + D3D12_GPU_DESCRIPTOR_HANDLE first, UINT increment, const unsigned *words, + const std::vector<IndexedAtomicView> &atomic, ID3D12DescriptorHeap *sampler_heap, + const std::vector<unsigned> &strides) const { + if (constant_words && !words) + throw std::runtime_error("compute root constants missing"); + if (atomic.size() != atomic_views) + throw std::runtime_error("indexed atomic view metadata missing"); + if (strides.size() != stride_srvs.size()) + throw std::runtime_error("compute descriptor stride metadata missing"); + const bool views = srv_count || uav_count || heap_indexed; + if (sampler_heap_indexed) { + if (!sampler_heap) + throw std::runtime_error("a sampler heap is needed"); + if (views) { + if (!heap) + throw std::runtime_error("a view heap is needed"); + // Views first, then samplers, as bind_translated_heaps does. + ID3D12DescriptorHeap *heaps[2]{heap, sampler_heap}; + list->SetDescriptorHeaps(2, heaps); + } else + list->SetDescriptorHeaps(1, &sampler_heap); + } else if (views) + list->SetDescriptorHeaps(1, &heap); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(state.Get()); + unsigned parameter = 0; + if (srv_count) + list->SetComputeRootDescriptorTable(parameter++, first); + first.ptr += UINT64(srv_count) * increment; + if (uav_count) + list->SetComputeRootDescriptorTable(parameter++, first); + if (constant_words) + list->SetComputeRoot32BitConstants(parameter, constant_words, words, 0); + if (!strides.empty()) + list->SetComputeRoot32BitConstants(parameter, static_cast<UINT>(strides.size()), strides.data(), constant_words); + if (constant_words || !strides.empty()) ++parameter; + for (const auto &shape : atomic) { + const unsigned pair[]{shape.stride, shape.count}; + list->SetComputeRoot32BitConstants(parameter++, 2, pair, 0); + } +} +} // namespace x2w diff --git a/src/native_compute_pipeline.h b/src/native_compute_pipeline.h new file mode 100644 index 0000000000..6dc3d8044e --- /dev/null +++ b/src/native_compute_pipeline.h @@ -0,0 +1,41 @@ +#pragma once + +#include "gfx1013_compute_native.h" +#include "shader_dxil_compiler.h" +#include <d3d12.h> + +namespace x2w { + +// Bindings are in desktop heap order: t0..tN followed by u0..uM. +// Each entry retains the guest table and byte offset determined by translation. +struct NativeComputePipeline { + Microsoft::WRL::ComPtr<ID3D12RootSignature> root; + Microsoft::WRL::ComPtr<ID3D12PipelineState> state; + std::vector<ComputeViewBinding> bindings; + std::vector<ComputeConstants> constants; + std::vector<unsigned> stride_srvs; + unsigned srv_count = 0; + unsigned uav_count = 0; + unsigned constant_words = 0, atomic_views = 0; + unsigned instructions = 0; + bool cache_hit = false, frontend_cache_hit = false; + bool heap_indexed = false; // reads ResourceDescriptorHeap: the root signature indexes the heap directly, which must be set + // on the list (bind() does it) and holds the selectable slots from index 0 + bool sampler_heap_indexed = false; // reads SamplerDescriptorHeap: the root has the directly indexed sampler heap flag (0x800), + // and bind() needs the shader-visible sampler heap (entry n = title byte offset 16 * n) + double frontend_ms = 0; + double backend_ms = 0; + double pipeline_ms = 0; + + void bind(ID3D12GraphicsCommandList *list, ID3D12DescriptorHeap *heap, D3D12_GPU_DESCRIPTOR_HANDLE first, + UINT increment, const unsigned *words = nullptr, + const std::vector<IndexedAtomicView> &atomic = {}, ID3D12DescriptorHeap *sampler_heap = nullptr, + const std::vector<unsigned> &strides = {}) const; +}; + +NativeComputePipeline create_native_compute_pipeline(ID3D12Device *device, ShaderDxilCompiler &compiler, + const std::filesystem::path &marker, unsigned entry, + const std::filesystem::path &cache, bool direct_dxil = false, + HeapViewContract heap_view = HeapViewContract::none); + +} // namespace x2w diff --git a/src/native_graphics_bindings.h b/src/native_graphics_bindings.h new file mode 100644 index 0000000000..48058797ea --- /dev/null +++ b/src/native_graphics_bindings.h @@ -0,0 +1,37 @@ +#pragma once + +#include "gfx1013_compute_native.h" +#include "startup_stubs/translated_sampler_bindings.h" + +namespace x2w { +// Registers were assigned by the pair linker in vertex, then pixel order. +// Preserve the guest source of each SRV and both sampler modes through PSO creation. +struct NativeGraphicsBindings { + std::vector<ComputeViewBinding> views; + unsigned srv_count = 0; + x2w_startup::TranslatedSamplers samplers; + + explicit NativeGraphicsBindings(const DirectGraphicsPair &pair) { + std::vector<ComputeViewBinding> writes; + for (const auto *stage : {&pair.vertex, &pair.pixel}) { + samplers.heap |= stage->sampler_heap; + samplers.reserved_fallback |= stage->sampler_heap; + for (const auto &v : stage->bindings) { + auto &range = compute_uav(v.kind) ? writes : views; + if (v.shader_register != range.size()) + throw std::runtime_error("unsupported graphics register order"); + range.push_back(v); + } + for (const auto &s : stage->samplers) { + samplers.statics.push_back(s.words); + samplers.comparison.push_back(s.comparison); + samplers.lod_limits.push_back(s.explicit_lod); + } + } + srv_count = static_cast<unsigned>(views.size()); + views.insert(views.end(), writes.begin(), writes.end()); + if (views.size() > 32) + throw std::runtime_error("graphics root capacity exceeded"); + } +}; +} diff --git a/src/native_texture_store_view.h b/src/native_texture_store_view.h new file mode 100644 index 0000000000..a8b68d0f3b --- /dev/null +++ b/src/native_texture_store_view.h @@ -0,0 +1,20 @@ +#pragma once +#include "gfx1013_compute_native.h" +#include <dxgiformat.h> + +namespace x2w { +struct NativeHalfStoreFormat { + DXGI_FORMAT typed{}, typeless{}; + bool accepts(DXGI_FORMAT view, DXGI_FORMAT resource) const { + return view == typed && (resource == typed || resource == typeless); + } +}; +inline NativeHalfStoreFormat native_half_store_format(ComputeViewKind kind) { + switch (kind) { + case ComputeViewKind::half_scalar_uav: return {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_TYPELESS}; + case ComputeViewKind::half2_texture_uav: return {DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_TYPELESS}; + case ComputeViewKind::half4_texture_uav: return {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_TYPELESS}; + default: return {}; + } +} +} diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp new file mode 100644 index 0000000000..b502e57160 --- /dev/null +++ b/src/shader_compute_request.cpp @@ -0,0 +1,366 @@ +#include "shader_compute_request.h" +#include <charconv> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <stdexcept> +#include <string_view> +#include <utility> +#include <vector> + +namespace fs = std::filesystem; +namespace { +using Bytes = std::string; +template <class T> T read(const Bytes &data, size_t offset) { + if (offset > data.size() || sizeof(T) > data.size() - offset) + throw std::runtime_error("truncated compute request"); + T value; + std::memcpy(&value, data.data() + offset, sizeof(value)); + return value; +} +Bytes part(fs::path path, const char *suffix, size_t limit) { + path.replace_extension(suffix); + std::ifstream file(path, std::ios::binary | std::ios::ate); + auto size = file.tellg(); + if (size < 0 || size > static_cast<std::streamoff>(limit)) + throw std::runtime_error(std::string("missing or oversized ") + suffix); + Bytes bytes(static_cast<size_t>(size), 0); + file.seekg(0); + if (size && !file.read(bytes.data(), size)) + throw std::runtime_error("short read"); + return bytes; +} +void hash_bytes(uint64_t &key, const void *data, size_t size) { + const auto *bytes = static_cast<const unsigned char *>(data); + for (size_t i = 0; i < size; ++i) + key = (key ^ bytes[i]) * 1099511628211ull; +} +bool lower_hex(std::string_view text) { + if (text.empty()) return false; + for (char c : text) + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) + return false; + return true; +} +void check_compute_extents(const Bytes &desc, size_t code, size_t data, size_t sa, size_t sb) { + if (desc.size() != 96 || read<uint64_t>(desc, 48) != code || read<uint64_t>(desc, 64) != data || + read<uint64_t>(desc, 16) != sa || read<uint64_t>(desc, 32) != sb) + throw std::runtime_error("inconsistent compute request"); +} +uint64_t parse_request_stem(std::string_view stem, const char *error_message) { + const std::string_view digits = stem.substr(4); + uint64_t expected = 0; + if (!lower_hex(digits)) + throw std::runtime_error(error_message); + const auto end = digits.data() + digits.size(); + const auto parsed = std::from_chars(digits.data(), end, expected, 16); + if (parsed.ec != std::errc{} || parsed.ptr != end) + throw std::runtime_error(error_message); + return expected; +} +} // namespace + +std::string x2w::format_pixel_input_description(uint64_t key, uint32_t ena, uint32_t addr) { + char text[64]; + std::snprintf(text, sizeof(text), "psin1 %016llx ena=0x%04x addr=0x%04x\n", + static_cast<unsigned long long>(key), ena, addr); + return text; +} + +x2w::PixelInputDescription x2w::parse_pixel_input_description(std::string_view raw, uint64_t expected) { + std::string_view line = raw; + if (!line.empty() && line.back() == '\n') + line.remove_suffix(1); + if (line.size() < 22 || line.substr(0, 6) != "psin1 " || line.find_first_of("\r\n") != std::string_view::npos) + throw std::runtime_error("invalid pixel input description"); + const std::string_view key_hex = line.substr(6, 16); + if (!lower_hex(key_hex)) + throw std::runtime_error("invalid pixel input description"); + uint64_t described_key = 0; + const auto key_end = key_hex.data() + key_hex.size(); + if (std::from_chars(key_hex.data(), key_end, described_key, 16).ptr != key_end) + throw std::runtime_error("invalid pixel input description"); + bool has_ena = false, has_addr = false; + uint32_t ena = 0, addr = 0; + unsigned fields = 0; + size_t pos = 22; + while (pos < line.size()) { + if (line[pos] != ' ' || ++fields > 2) + throw std::runtime_error("invalid pixel input description"); + ++pos; + const size_t next = line.find(' ', pos); + const std::string_view token = line.substr(pos, next == std::string_view::npos ? line.size() - pos : next - pos); + pos = next == std::string_view::npos ? line.size() : next; + const bool is_ena = token.substr(0, 6) == "ena=0x"; + const bool is_addr = token.substr(0, 7) == "addr=0x"; + if (!is_ena && !is_addr) + throw std::runtime_error("invalid pixel input description"); + const std::string_view mask_hex = token.substr(is_ena ? 6 : 7); + if (mask_hex.empty() || mask_hex.size() > 4 || !lower_hex(mask_hex) || (is_ena ? has_ena : has_addr)) + throw std::runtime_error("invalid pixel input description"); + uint32_t value = 0; + const auto mask_end = mask_hex.data() + mask_hex.size(); + if (std::from_chars(mask_hex.data(), mask_end, value, 16).ptr != mask_end) + throw std::runtime_error("invalid pixel input description"); + if (is_ena) { + has_ena = true; + ena = value; + } else { + has_addr = true; + addr = value; + } + } + if (described_key != expected) + throw std::runtime_error("pixel input description names another pipeline"); + if (!has_ena) + throw std::runtime_error("pixel input enable mask missing from the stream description"); + if (!has_addr) + throw std::runtime_error("pixel input address mask missing from the stream description"); + if (ena & ~addr) + throw std::runtime_error("contradictory pixel input enable/address masks"); + PixelInputDescription parsed; + parsed.ena = ena; + parsed.addr = addr; + parsed.entry.assign("psin1", 5); + const uint32_t words[2]{ena, addr}; + parsed.entry.append(reinterpret_cast<const char *>(words), sizeof(words)); + parsed.canonical_text = format_pixel_input_description(expected, ena, addr); + return parsed; +} + +x2w::RtvVariantDescription x2w::parse_rtv_variant_text(std::string_view text, uint64_t expected) { + if (text.size() > 256) + throw std::runtime_error("invalid RTV variant request"); + const uint64_t key = fnv1a_64(text); + std::vector<std::string_view> tokens; + std::string_view rest = text; + bool valid = rest.substr(0, 5) == "rtv1 "; + if (valid) rest.remove_prefix(5); + while (valid) { + const size_t end = rest.find(' '); + const auto token = rest.substr(0, end); + valid = !token.empty() && token.size() <= (tokens.empty() ? 20u : 10u) && + token.find_first_not_of("0123456789") == token.npos; + tokens.push_back(token); + if (end == rest.npos) break; + rest.remove_prefix(end + 1); + } + if (!valid || tokens.size() < 2 || tokens.size() > 9 || key != expected) + throw std::runtime_error("invalid RTV variant request"); + RtvVariantDescription result; + for (size_t i = 0; i < tokens.size(); ++i) { + uint64_t value = 0; + const auto parsed = std::from_chars(tokens[i].data(), tokens[i].data() + tokens[i].size(), value); + if (parsed.ec != std::errc{} || (i && value > 0xffffffffull)) + throw std::runtime_error("invalid RTV variant values"); + if (!i) result.base_key = value; + else result.formats.push_back(static_cast<unsigned>(value)); + } + return result; +} + +std::string x2w::format_rtv_variant_text(uint64_t base_key, const std::vector<unsigned> &formats) { + std::string out = "rtv1 " + std::to_string(base_key); + for (unsigned format : formats) { + out.push_back(' '); + out += std::to_string(format); + } + return out; +} + +uint64_t x2w::fnv1a_64(std::string_view bytes) { + uint64_t key = 1469598103934665603ull; + hash_bytes(key, bytes.data(), bytes.size()); + return key; +} + +uint64_t x2w::graphics_request_key(std::string_view a, std::string_view b, std::string_view root, + std::string_view input_layout, std::string_view pixel_entry, + std::string_view revision_override) { + constexpr char revision[] = "x2w-startup-shader-29"; + uint64_t key = fnv1a_64(revision_override.empty() ? std::string_view(revision, sizeof(revision) - 1) + : revision_override); + for (const auto part_view : {a, b, root, input_layout, pixel_entry}) + hash_bytes(key, part_view.data(), part_view.size()); + return key; +} + +uint64_t x2w::compute_request_key(std::string_view code, std::string_view data, std::string_view root, + std::string_view description, std::string_view sa, std::string_view sb, + std::string_view revision_override) { + constexpr char revision[] = "x2w-startup-shader-29cs"; + uint64_t key = fnv1a_64(revision_override.empty() ? std::string_view(revision, sizeof(revision) - 1) + : revision_override); + for (const auto part_view : {code, data, root, description, sa, sb}) { + const uint64_t size = part_view.size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, part_view.data(), part_view.size()); + } + return key; +} + +uint64_t x2w::mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root) { + constexpr char revision[] = "x2w-startup-mesh-57-3"; + uint64_t key = fnv1a_64(std::string_view(revision, sizeof(revision) - 1)); + for (const auto part_view : {code, ps57, root}) { + const uint64_t size = part_view.size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, part_view.data(), part_view.size()); + } + return key; +} + +namespace { +void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { + fs::path path = marker; + path.replace_extension(".psin"); + std::ifstream file(path, std::ios::binary | std::ios::ate); + const auto size = file.tellg(); + if (size < 0 || size > 128) + throw std::runtime_error("invalid pixel input description"); + Bytes raw(static_cast<size_t>(size), 0); + file.seekg(0); + if (size && !file.read(raw.data(), size)) + throw std::runtime_error("short read"); + auto parsed = x2w::parse_pixel_input_description(raw, expected); + entry = std::move(parsed.entry); + description = std::move(parsed.canonical_text); +} +// tools/startup/gfx2hlsl.py request_source: at most 256 bytes of "rtv1 <base key> <format> ..." in decimal with one to +// eight formats and nothing else, whose FNV-1a hash is the key in the file name. The variant is translated from its +// base request's parts, which are read and checked against the base key like any base request. +x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { + const auto stem = marker.stem().string(); + if (stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.rtv"); + const uint64_t expected = parse_request_stem(stem, "invalid RTV variant request key"); + Bytes text; + try { + text = part(marker, ".rtv", 256); + } catch (const std::runtime_error &) { + throw std::runtime_error("invalid RTV variant request"); + } + auto parsed = x2w::parse_rtv_variant_text(text, expected); + char name[32]; + std::snprintf(name, sizeof(name), "req_%016llx.a", static_cast<unsigned long long>(parsed.base_key)); + x2w::GraphicsRequest request; + try { + request = x2w::read_graphics_request(marker.parent_path() / name); + } catch (const std::runtime_error &error) { + throw std::runtime_error(std::string("RTV variant source: ") + error.what()); + } + request.key = expected; + request.rtv_request = std::move(text); + request.rtv_formats = std::move(parsed.formats); + return request; +} +void read_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { + if (fs::exists(fs::path(marker).replace_extension(".psin"))) + parse_pixel_inputs(marker, expected, entry, description); + if (fs::exists(fs::path(marker).replace_extension(".ps57in"))) { + if (!entry.empty()) + throw std::runtime_error("conflicting stream and slot-57 pixel entry records"); + entry = part(marker, ".ps57in", 12); + if (entry.size() != 12 || entry.compare(0, 4, "PSI1")) + throw std::runtime_error("invalid slot-57 pixel entry record"); + description = entry; + } +} +} // namespace + +std::string x2w::read_pixel_input_description(const fs::path &base_marker) { + const auto stem = base_marker.stem().string(); + if (base_marker.extension() != ".a" || stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.a"); + const uint64_t expected = parse_request_stem(stem, "invalid graphics request key"); + Bytes entry, description; + read_pixel_inputs(base_marker, expected, entry, description); + return description; +} + +x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { + if (marker.extension() == ".rtv") return read_rtv_variant(marker); + auto stem = marker.stem().string(); + if (marker.extension() != ".a" || stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.a"); + const uint64_t expected = parse_request_stem(stem, "invalid graphics request key"); + GraphicsRequest request{part(marker, ".a", 64 << 20), part(marker, ".b", 64 << 20), + part(marker, ".root", 16 << 20), {}, {}, {}, expected}; + if (fs::exists(fs::path(marker).replace_extension(".ia"))) + request.input_layout = part(marker, ".ia", 1 << 20); + read_pixel_inputs(marker, expected, request.pixel_entry, request.pixel_input_description); + if (request.root.empty()) + throw std::runtime_error("graphics request key mismatch or missing root"); + // Match new runtime captures and keep revision-28 archives replayable. + if (x2w::graphics_request_key(request.a, request.b, request.root, request.input_layout, request.pixel_entry) != + expected && + x2w::graphics_request_key(request.a, request.b, request.root, request.input_layout, request.pixel_entry, + "x2w-startup-shader-28") != expected) { + if (!request.pixel_entry.empty()) + throw std::runtime_error("stale pixel input description: graphics request key mismatch"); + throw std::runtime_error("graphics request key mismatch or missing root"); + } + return request; +} + +x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { + auto name = marker.stem().string(); + if (marker.extension() != ".c67" || name.size() != 20 || name.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.c67"); + const uint64_t expected = parse_request_stem(name, "invalid request key"); + auto code = part(marker, ".c67", 1 << 20), data = part(marker, ".data", 1 << 20), + root = part(marker, ".root", 16 << 20); + auto desc = part(marker, ".desc", 96), sa = part(marker, ".sa", 4096), sb = part(marker, ".sb", 4096); + if (desc.size() != 96 || read<uint64_t>(desc, 48) != code.size() || read<uint64_t>(desc, 64) != data.size() || + read<uint64_t>(desc, 16) != sa.size() || read<uint64_t>(desc, 32) != sb.size()) + throw std::runtime_error("inconsistent compute request"); + if (x2w::compute_request_key(code, data, root, desc, sa, sb) != expected && + x2w::compute_request_key(code, data, root, desc, sa, sb, "x2w-startup-shader-28cs") != expected) + throw std::runtime_error("compute request key mismatch"); + ComputeRequest request{std::move(code), std::move(data), std::move(root), std::move(desc), std::move(sa), std::move(sb), expected}; + validate_compute_request_shape(request); + // Bit 20 of dword 4 (bits 15:0 are Z): set for wave32, clear for wave64. Inferred from captured requests + // (docs/experiments/native-slot67-wave-size.md). Read only after the shape check has proved 28 bytes. + request.wave32 = (static_cast<unsigned char>(request.sa[18]) & 0x10) != 0; + return request; +} + +void x2w::validate_compute_request_shape(const ComputeRequest &r) { + check_compute_extents(r.description, r.code.size(), r.data.size(), r.sa.size(), r.sb.size()); + if (r.root.size() > (16u << 20) || r.code.size() > (1u << 20) || + r.data.size() > (1u << 20) || r.sa.size() > 4096 || r.sb.size() > 4096) + throw std::runtime_error("inconsistent compute request"); + if (r.root.empty() || r.sa.size() != 28 || r.code.empty() || r.data.empty() || r.code.size() % 4) + throw std::runtime_error(r.sa.size() != 28 ? "compute state block A is not 28 bytes" : "inconsistent compute request"); +} + +std::string x2w::read_shader_container_bytes(const fs::path &file) { + std::ifstream stream(file, std::ios::binary | std::ios::ate); + auto length = stream.tellg(); + if (length < 32 || length > 64 * 1024 * 1024) + throw std::runtime_error("missing or oversized shader container"); + std::string bytes(static_cast<size_t>(length), 0); + stream.seekg(0); + if (!stream.read(bytes.data(), length)) throw std::runtime_error("truncated shader container"); + return bytes; +} +x2w::ComputeContainer x2w::read_compute_container(const fs::path &file) { + auto bytes=read_shader_container_bytes(file); + const auto stem=file.stem().string(); + if (stem.compare(0,4,"req_") != 0) return {std::move(bytes), {}}; + uint64_t expected=0; + if (stem.size()!=20 || file.extension()!=".cdx") + throw std::runtime_error("invalid container request filename"); + auto parsed=std::from_chars(stem.data()+4,stem.data()+stem.size(),expected,16); + if(parsed.ec!=std::errc{} || parsed.ptr!=stem.data()+stem.size()) + throw std::runtime_error("invalid container request key"); + auto root=part(file,".root",16<<20); + uint64_t key=1469598103934665603ull, size=root.size(); + constexpr char revision[]="native-container-1"; + hash_bytes(key,revision,sizeof(revision)-1); + hash_bytes(key,&size,sizeof(size)); + hash_bytes(key,root.data(),root.size()); + hash_bytes(key,bytes.data(),bytes.size()); + if (root.empty() || key!=expected) throw std::runtime_error("container request key mismatch"); + return {std::move(bytes),std::move(root)}; +} diff --git a/src/shader_compute_request.h b/src/shader_compute_request.h new file mode 100644 index 0000000000..b8bd53dad5 --- /dev/null +++ b/src/shader_compute_request.h @@ -0,0 +1,59 @@ +#pragma once +#include <cstdint> +#include <filesystem> +#include <string> +#include <string_view> +#include <vector> + +namespace x2w { +uint64_t fnv1a_64(std::string_view bytes); +uint64_t graphics_request_key(std::string_view a, std::string_view b, std::string_view root, + std::string_view input_layout = {}, std::string_view pixel_entry = {}, + std::string_view revision = {}); +uint64_t compute_request_key(std::string_view code, std::string_view data, std::string_view root, + std::string_view description, std::string_view sa, std::string_view sb, + std::string_view revision = {}); +uint64_t mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root); + +struct PixelInputDescription { + uint32_t ena{}; + uint32_t addr{}; + std::string entry; + std::string canonical_text; +}; +PixelInputDescription parse_pixel_input_description(std::string_view text, uint64_t expected_key); +std::string format_pixel_input_description(uint64_t key, uint32_t ena, uint32_t addr); + +struct RtvVariantDescription { + uint64_t base_key{}; + std::vector<unsigned> formats; +}; +RtvVariantDescription parse_rtv_variant_text(std::string_view text, uint64_t expected_key); +std::string format_rtv_variant_text(uint64_t base_key, const std::vector<unsigned> &formats); + +struct ComputeRequest { + std::string code, data, root, description, sa, sb; + uint64_t key; + bool wave32 = true; +}; +struct ComputeContainer { + std::string bytes, root; +}; +struct GraphicsRequest { + std::string a, b, root, input_layout, pixel_entry, pixel_input_description; + uint64_t key{}; + // An RTV variant (req_<key>.rtv): its "rtv1 <base key> <format> ..." text and the ordered target formats. The + // parts above are then its base request's, checked against the base key, and key is the variant's. + std::string rtv_request; + std::vector<unsigned> rtv_formats; +}; +// marker: req_<key>.a, or req_<key>.rtv for an RTV variant of a base request in the same directory. +GraphicsRequest read_graphics_request(const std::filesystem::path &marker); +// Canonical pixel-input sidecar (.psin or .ps57in) content for req_<key>.a; empty when absent, throws if invalid/conflicting. +std::string read_pixel_input_description(const std::filesystem::path &base_marker); +std::string read_shader_container_bytes(const std::filesystem::path &file); +ComputeContainer read_compute_container(const std::filesystem::path &file); +// Verify the content key over all six immutable capture parts before exposing any bytes. +ComputeRequest read_compute_request(const std::filesystem::path &marker); +void validate_compute_request_shape(const ComputeRequest &request); +} // namespace x2w diff --git a/src/shader_dxil_compiler.cpp b/src/shader_dxil_compiler.cpp new file mode 100644 index 0000000000..520f4af79e --- /dev/null +++ b/src/shader_dxil_compiler.cpp @@ -0,0 +1,209 @@ +#include <windows.h> +#include <bcrypt.h> +#include "shader_dxil_compiler.h" +#include "gfx1013_compute_ir.h" +#include <algorithm> +#include <array> +#include <atomic> +#include <fstream> +#include <limits> +#include <stdexcept> + +namespace fs = std::filesystem; +using Microsoft::WRL::ComPtr; +namespace { +using Bytes = std::vector<unsigned char>; +bool try_read_file(const fs::path& path, Bytes& bytes) { + HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}; + const bool sized = GetFileSizeEx(handle, &size) && size.QuadPart >= 0 && size.QuadPart <= 256ll * 1024 * 1024; + bool ok = sized; + if (sized) { + bytes.resize(static_cast<size_t>(size.QuadPart)); + DWORD read_bytes = 0; + ok = !size.QuadPart || (ReadFile(handle, bytes.data(), static_cast<DWORD>(size.QuadPart), &read_bytes, nullptr) && + read_bytes == static_cast<DWORD>(size.QuadPart)); + } + CloseHandle(handle); + return ok; +} +Bytes read_file(const fs::path& path) { + Bytes bytes; + if (!try_read_file(path, bytes)) throw std::runtime_error("unreadable or oversized input"); + return bytes; +} +std::string digest(const void* data, size_t size) { + if (size > ULONG_MAX) throw std::length_error("digest input too large"); + std::array<unsigned char,32> hash{}; + if (BCryptHash(BCRYPT_SHA256_ALG_HANDLE,nullptr,0, + static_cast<PUCHAR>(const_cast<void*>(data)),static_cast<ULONG>(size), + hash.data(),static_cast<ULONG>(hash.size())) < 0) throw std::runtime_error("SHA-256 failed"); + std::string result; + constexpr char hex[] = "0123456789abcdef"; + for (auto byte : hash) { result += hex[byte >> 4]; result += hex[byte & 15]; } + return result; +} +void checked(HRESULT status) { + if (FAILED(status)) throw std::runtime_error("DXC API failure " + std::to_string(status)); +} +} +namespace x2w { +std::string shader_digest(std::string_view bytes) { return digest(bytes.data(),bytes.size()); } +struct ShaderDxilCompiler::Sdk { + struct Module { + HMODULE handle{}; + bool process_lifetime{}; + ~Module() { if (handle && !process_lifetime) FreeLibrary(handle); } + Module() = default; + Module(const Module&) = delete; + Module& operator=(const Module&) = delete; + } validator, compiler; + std::string identity; + DxcCreateInstanceProc create{}; + explicit Sdk(const fs::path& directory); +}; + +ShaderDxilCompiler::Sdk::Sdk(const fs::path& sdk_directory) { + auto load = [&](Module& module, const wchar_t* name) { + auto path = fs::canonical(sdk_directory / name); + auto file = read_file(path); + identity += digest(file.data(), file.size()); + module.handle = LoadLibraryExW(path.c_str(),nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!module.handle) throw std::runtime_error("could not load DXC SDK module"); + }; + load(validator, L"dxil.dll"); + load(compiler, L"dxcompiler.dll"); + create = reinterpret_cast<DxcCreateInstanceProc>(GetProcAddress(compiler.handle,"DxcCreateInstance")); + if (!create) throw std::runtime_error("DXC entry missing"); +} + +ShaderDxilCompiler::ShaderDxilCompiler(const fs::path& directory) + : ShaderDxilCompiler(std::make_shared<Sdk>(directory)) {} + +ShaderDxilCompiler::ShaderDxilCompiler(std::shared_ptr<const Sdk> sdk) : sdk_(std::move(sdk)) { + checked(sdk_->create(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler_))); + checked(sdk_->create(CLSID_DxcUtils, IID_PPV_ARGS(&utils_))); +} + +ShaderDxilCompiler ShaderDxilCompiler::new_worker() const { + return ShaderDxilCompiler(sdk_); +} + +ShaderDxilCompiler ShaderDxilCompiler::runtime_worker(const fs::path& directory) { + static const auto sdk = [&] { + auto loaded = std::make_shared<Sdk>(directory); + // The loader releases these two runtime references at process shutdown. + // A shim static destructor runs under loader lock, after DXC may detach. + loaded->compiler.process_lifetime = true; + loaded->validator.process_lifetime = true; + return loaded; + }(); + return ShaderDxilCompiler(sdk); +} + +HRESULT ShaderDxilCompiler::reflect(const void* bytecode,size_t bytes,REFIID iid,void** result) { + DxcBuffer buffer{bytecode,bytes,0}; + return utils_->CreateReflection(&buffer,iid,result); +} + +CompiledShader ShaderDxilCompiler::compile(const std::string& source_text, const std::wstring& profile, + const fs::path& cache, ShaderSourceFormat format) { + const bool direct = format == ShaderSourceFormat::dxil_ir; + const bool native_ir = source_text.find("#pragma x2w_") != std::string::npos; + // Bump the native IR version when instruction semantics change. Keying + // before expansion lets a validated hit bypass instruction lowering. + const char* revision = direct ? "x2w-direct-dxil-1/validated/" : native_ir ? "x2w-dxil-native-ir-1/main/-Gis/-O3/" : "x2w-dxil-1/main/-Gis/-O3/"; + const std::string identity = revision + sdk_->identity + digest(profile.data(),profile.size()*sizeof(wchar_t)) + + digest(source_text.data(),source_text.size()); + const auto key = digest(identity.data(),identity.size()); + const auto path = cache / (key + ".bin"); + Bytes cached; + if (try_read_file(path, cached) && cached.size() > 128 && std::equal(key.begin(), key.end(), cached.begin())) { + const auto hash = digest(cached.data() + 128, cached.size() - 128); + if (std::equal(hash.begin(), hash.end(), cached.begin() + 64)) + return {Bytes(cached.begin() + 128, cached.end()), true}; + } + ComPtr<IDxcBlob> blob; + if (direct) { + ComPtr<IDxcBlobEncoding> input; + checked(utils_->CreateBlob(source_text.data(),static_cast<UINT32>(source_text.size()),DXC_CP_UTF8,&input)); + ComPtr<IDxcAssembler> assembler; + checked(sdk_->create(CLSID_DxcAssembler,IID_PPV_ARGS(&assembler))); + auto take_result = [](IDxcOperationResult *result) { + HRESULT hr; + checked(result->GetStatus(&hr)); + if (FAILED(hr)) { + ComPtr<IDxcBlobEncoding> error; + result->GetErrorBuffer(&error); + throw std::runtime_error(error ? std::string(static_cast<const char*>(error->GetBufferPointer()), + error->GetBufferSize()) : "DXIL assembly/validation failed"); + } + ComPtr<IDxcBlob> bytes; + checked(result->GetResult(&bytes)); + return bytes; + }; + ComPtr<IDxcOperationResult> assembled, validated; + checked(assembler->AssembleToContainer(input.Get(),&assembled)); + blob=take_result(assembled.Get()); + ComPtr<IDxcValidator> validator; + const auto create_validator = reinterpret_cast<DxcCreateInstanceProc>( + GetProcAddress(sdk_->validator.handle,"DxcCreateInstance")); + if (!create_validator) throw std::runtime_error("SDK DXIL validator export unavailable"); + checked(create_validator(CLSID_DxcValidator,IID_PPV_ARGS(&validator))); + checked(validator->Validate(blob.Get(),DxcValidatorFlags_InPlaceEdit,&validated)); + blob=take_result(validated.Get()); + } else { + std::string expanded; + if (native_ir) { + expanded=expand_gfx1013_compute(source_text); + if (expanded!=source_text && profile.rfind(L"cs_",0)!=0) + throw std::runtime_error("native register lowering requires a compute profile"); + } + const auto& hlsl=native_ir ? expanded : source_text; + DxcBuffer source{hlsl.data(),hlsl.size(),DXC_CP_UTF8}; + const wchar_t* args[] = {L"-E",L"main",L"-T",profile.c_str(),L"-Gis",L"-O3"}; + ComPtr<IDxcResult> result; + checked(compiler_->Compile(&source,args,ARRAYSIZE(args),nullptr,IID_PPV_ARGS(&result))); + HRESULT status; + checked(result->GetStatus(&status)); + if (FAILED(status)) { + ComPtr<IDxcBlobUtf8> errors; + checked(result->GetOutput(DXC_OUT_ERRORS,IID_PPV_ARGS(&errors),nullptr)); + throw std::runtime_error(errors && errors->GetStringLength() ? errors->GetStringPointer() : "DXC compile failed"); + } + checked(result->GetOutput(DXC_OUT_OBJECT,IID_PPV_ARGS(&blob),nullptr)); + } + const auto* start = static_cast<const unsigned char*>(blob->GetBufferPointer()); + Bytes bytes(start,start+blob->GetBufferSize()); + auto hash = digest(bytes.data(),bytes.size()); + fs::create_directories(cache); + static std::atomic<unsigned long long> serial{}; + auto temp = path; + temp += "."+std::to_string(GetCurrentProcessId())+"."+std::to_string(serial++)+".tmp"; + try { + std::ofstream out(temp,std::ios::binary | std::ios::trunc); + out.exceptions(std::ios::badbit | std::ios::failbit); + out << key << hash; + out.write(reinterpret_cast<const char*>(bytes.data()),bytes.size()); + out.close(); + if (!MoveFileExW(temp.c_str(),path.c_str(),MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + // Another process may already have published and opened the same + // entry without FILE_SHARE_DELETE. Only accept an identical winner. + auto winner=read_file(path); + if(winner.size()!=128+bytes.size() || !std::equal(key.begin(),key.end(),winner.begin()) || + !std::equal(hash.begin(),hash.end(),winner.begin()+64) || + !std::equal(bytes.begin(),bytes.end(),winner.begin()+128)) + throw std::runtime_error("could not publish DXIL cache entry"); + fs::remove(temp); + } + } catch (...) { + std::error_code ignored; + fs::remove(temp,ignored); + throw; + } + return {std::move(bytes),false}; +} +} diff --git a/src/shader_dxil_compiler.h b/src/shader_dxil_compiler.h new file mode 100644 index 0000000000..64f097d548 --- /dev/null +++ b/src/shader_dxil_compiler.h @@ -0,0 +1,45 @@ +#pragma once + +#include <windows.h> +#include <objidl.h> +#include <oleauto.h> +#include <dxcapi.h> +#include <wrl/client.h> +#include <filesystem> +#include <memory> +#include <string> +#include <string_view> +#include <vector> + +namespace x2w { + +std::string shader_digest(std::string_view bytes); +enum class ShaderSourceFormat { hlsl, dxil_ir }; + +struct CompiledShader { + std::vector<unsigned char> dxil; + bool cache_hit = false; +}; + +// The caller supplies a matching SDK dxcompiler.dll and dxil.dll in the same directory. +// Source must be self-contained. The backend never resolves process-relative includes. +class ShaderDxilCompiler { +public: + explicit ShaderDxilCompiler(const std::filesystem::path& sdk_directory); + ShaderDxilCompiler(const ShaderDxilCompiler&) = delete; + ShaderDxilCompiler& operator=(const ShaderDxilCompiler&) = delete; + // Independent DXC interfaces, with the same loaded and fingerprinted SDK. + ShaderDxilCompiler new_worker() const; + // The startup shim uses one SDK directory for the lifetime of the process. + static ShaderDxilCompiler runtime_worker(const std::filesystem::path& sdk_directory); + CompiledShader compile(const std::string& hlsl, const std::wstring& profile, + const std::filesystem::path& cache, ShaderSourceFormat format = ShaderSourceFormat::hlsl); + HRESULT reflect(const void* bytecode, size_t bytes, REFIID iid, void** result); +private: + struct Sdk; + explicit ShaderDxilCompiler(std::shared_ptr<const Sdk> sdk); + std::shared_ptr<const Sdk> sdk_; + Microsoft::WRL::ComPtr<IDxcCompiler3> compiler_; + Microsoft::WRL::ComPtr<IDxcUtils> utils_; +}; +} diff --git a/src/shaders/meshlet_pipeline.hlsl b/src/shaders/meshlet_pipeline.hlsl new file mode 100644 index 0000000000..d4f969af64 --- /dev/null +++ b/src/shaders/meshlet_pipeline.hlsl @@ -0,0 +1,154 @@ +struct MeshletVertex { + float3 position; + float pad0; + float3 normal; + float pad1; + float4 color; +}; + +struct MeshletDescriptor { + uint vertex_count; + uint vertex_offset; + uint primitive_count; + uint primitive_offset; +}; + +struct MeshletBounds { + float3 center; + float radius; + float3 cone_apex; + float cone_cutoff; + float3 cone_axis; + float pad0; +}; + +cbuffer SceneConstants : register(b0) { + row_major float4x4 view_proj; + float4 frustum_planes[6]; + float4 camera_pos; // xyz = camera world position, w > 0.5 enables AS culling + uint meshlet_count; + uint pad0; + uint pad1; + uint pad2; +}; + +StructuredBuffer<MeshletVertex> g_vertices : register(t0); +StructuredBuffer<MeshletDescriptor> g_meshlets : register(t1); +StructuredBuffer<MeshletBounds> g_bounds : register(t2); +StructuredBuffer<uint> g_unique_vertex_indices : register(t3); +StructuredBuffer<uint> g_packed_primitives : register(t4); +RWStructuredBuffer<uint> g_cull_stats : register(u0); // [0]=tested, [1]=frustum_culled, [2]=backface_culled, [3]=dispatched + +struct MeshletPayload { + uint meshlet_indices[32]; +}; + +struct MeshOutput { + float4 position : SV_Position; + float4 color : COLOR0; +}; + +struct VSInput { + float3 position : POSITION; + float3 normal : NORMAL; + float4 color : COLOR0; +}; + +groupshared MeshletPayload s_payload; +groupshared uint s_visible_count; + +bool is_frustum_culled(MeshletBounds b) { + [unroll] + for (uint i = 0; i < 6; ++i) { + if (dot(frustum_planes[i].xyz, b.center) + frustum_planes[i].w < -b.radius) { + return true; + } + } + return false; +} + +bool is_backface_culled(MeshletBounds b) { + if (b.cone_cutoff >= 1.5f) { + return false; + } + float3 to_apex = b.cone_apex - camera_pos.xyz; + float len_sq = dot(to_apex, to_apex); + if (len_sq <= 1e-12f) { + return false; + } + float3 view_dir = to_apex * rsqrt(len_sq); + return dot(view_dir, b.cone_axis) >= b.cone_cutoff; +} + +[numthreads(32, 1, 1)] +void ASMain(uint dtid : SV_DispatchThreadID, uint gtid : SV_GroupIndex) { + if (gtid == 0) { + s_visible_count = 0; + } + GroupMemoryBarrierWithGroupSync(); + + if (dtid < meshlet_count) { + InterlockedAdd(g_cull_stats[0], 1); + MeshletBounds b = g_bounds[dtid]; + bool culled = false; + + if (camera_pos.w > 0.5f) { + if (is_frustum_culled(b)) { + InterlockedAdd(g_cull_stats[1], 1); + culled = true; + } else if (is_backface_culled(b)) { + InterlockedAdd(g_cull_stats[2], 1); + culled = true; + } + } + + if (!culled) { + uint slot = 0; + InterlockedAdd(s_visible_count, 1, slot); + s_payload.meshlet_indices[slot] = dtid; + InterlockedAdd(g_cull_stats[3], 1); + } + } + + GroupMemoryBarrierWithGroupSync(); + DispatchMesh(s_visible_count, 1, 1, s_payload); +} + +[outputtopology("triangle")] +[numthreads(64, 1, 1)] +void MSMain( + uint gtid : SV_GroupIndex, + uint gid : SV_GroupID, + in payload MeshletPayload payload, + out vertices MeshOutput verts[64], + out indices uint3 tris[126]) { + uint meshlet_id = payload.meshlet_indices[gid]; + MeshletDescriptor desc = g_meshlets[meshlet_id]; + + SetMeshOutputCounts(desc.vertex_count, desc.primitive_count); + + if (gtid < desc.vertex_count) { + uint v_idx = g_unique_vertex_indices[desc.vertex_offset + gtid]; + MeshletVertex v = g_vertices[v_idx]; + MeshOutput o; + o.position = mul(float4(v.position, 1.0f), view_proj); + o.color = v.color; + verts[gtid] = o; + } + + for (uint p = gtid; p < desc.primitive_count; p += 64) { + uint packed = g_packed_primitives[desc.primitive_offset + p]; + tris[p] = uint3(packed & 0xFFu, (packed >> 8) & 0xFFu, (packed >> 16) & 0xFFu); + } +} + +MeshOutput VSMain(VSInput input) { + MeshOutput o; + o.position = mul(float4(input.position, 1.0f), view_proj); + o.color = input.color; + return o; +} + +float4 PSMain(MeshOutput input) : SV_Target { + return input.color; +} diff --git a/src/startup_stubs/acphal.cpp b/src/startup_stubs/acphal.cpp index c6c25a4fe9..8e66537537 100644 --- a/src/startup_stubs/acphal.cpp +++ b/src/startup_stubs/acphal.cpp @@ -6,6 +6,8 @@ #include "startup_stubs/local_log.h" #include <array> +#include <cstring> +#include <new> #include <utility> X2W_TRAP_EXPORT(2, AcpHalReleaseShapeContexts) @@ -18,12 +20,15 @@ using u64 = std::uint64_t; bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } -// APU heap: one committed region; an APU address is an offset into it. A table of extents, sorted by -// offset, tiles [heap_start, heap_bytes) and each extent is free or used. Allocation is first-fit in -// address order, so while nothing has been freed it hands out the same offsets a bump allocator would; -// a freed extent is merged with free neighbours. The table is static: when it is full a request that -// needs a split fails like an exhausted heap. All state is guarded by heap_lock. +// APU heap: one reserved region committed on demand; an APU address is an offset into it. A table of +// extents, sorted by offset, tiles [heap_start, heap_bytes) and each extent is free or used. Allocation +// is first-fit in address order, so while nothing has been freed it hands out the same offsets a bump +// allocator would; a freed extent is merged with free neighbours and whole freed pages are decommitted. +// The table is static: when it is full a request that needs a split fails like an exhausted heap. All +// state is guarded by heap_lock. constexpr u64 heap_start = 0x10000; // APU address 0 stays unused +constexpr u64 heap_max_bytes = 0x100000000ull; // the APU address space: 4 GiB +constexpr u64 page_size = 0x1000; constexpr std::size_t max_extents = 4096; struct Extent { u64 start, size; @@ -43,6 +48,28 @@ void heap_reset() noexcept high_water = heap_start; } +void heap_snapshot(unsigned char*& base, u64& bytes) noexcept +{ + AcquireSRWLockShared(&heap_lock); + base = heap_base; + bytes = heap_bytes; + ReleaseSRWLockShared(&heap_lock); +} + +// The allocatable 32-bit APU range [heap_start, min(heap_bytes, 4 GiB)). +bool in_apu_range(const void* virtual_address, u64& offset_out) noexcept +{ + unsigned char* base = nullptr; + u64 bytes = 0; + heap_snapshot(base, bytes); + const auto address = reinterpret_cast<std::uintptr_t>(virtual_address); + const auto base_addr = reinterpret_cast<std::uintptr_t>(base); + const u64 limit = bytes > 0x100000000ull ? 0x100000000ull : bytes; + if (!base || limit <= heap_start || address < base_addr + heap_start || address - base_addr >= limit) return false; + offset_out = static_cast<u64>(address - base_addr); + return true; +} + // bytes and alignment (a power of two) are checked by the callers; both stay far below 2^63. unsigned char* heap_take(u64 bytes, u64 alignment) { @@ -57,19 +84,27 @@ unsigned char* heap_take(u64 bytes, u64 alignment) const u64 tail = e.size - pad - bytes; const std::size_t extra = (pad ? 1 : 0) + (tail ? 1 : 0); if (extent_count + extra > max_extents) continue; + const u64 block_start = e.start + pad; + const u64 block_end = block_start + bytes; + const u64 page_begin = block_start & ~(page_size - 1); + const u64 page_end = (block_end + page_size - 1) & ~(page_size - 1); + if (page_end > page_begin && + !VirtualAlloc(heap_base + page_begin, static_cast<SIZE_T>(page_end - page_begin), MEM_COMMIT, + PAGE_READWRITE)) { + break; + } std::memmove(&extents[i + 1 + extra], &extents[i + 1], (extent_count - i - 1) * sizeof(Extent)); std::size_t at = i; if (pad) extents[at++] = {e.start, pad, false}; - extents[at++] = {e.start + pad, bytes, true}; - if (tail) extents[at] = {e.start + pad + bytes, tail, false}; + extents[at++] = {block_start, bytes, true}; + if (tail) extents[at] = {block_end, tail, false}; extent_count += extra; - result = heap_base + e.start + pad; - const u64 end = e.start + pad + bytes; - if (e.start + pad < high_water) { - zero_from = e.start + pad; - zero_bytes = (end < high_water ? end : high_water) - zero_from; + result = heap_base + block_start; + if (block_start < high_water) { + zero_from = block_start; + zero_bytes = (block_end < high_water ? block_end : high_water) - zero_from; } - if (end > high_water) high_water = end; + if (block_end > high_water) high_water = block_end; } ReleaseSRWLockExclusive(&heap_lock); if (zero_bytes) std::memset(heap_base + zero_from, 0, static_cast<std::size_t>(zero_bytes)); // fresh pages are zero @@ -98,10 +133,19 @@ bool heap_give(const void* virtual_address) std::memmove(&extents[lo + 1], &extents[lo + 2], (extent_count - lo - 2) * sizeof(Extent)); --extent_count; } + std::size_t free_idx = lo; if (lo > 0 && !extents[lo - 1].used) { extents[lo - 1].size += extents[lo].size; std::memmove(&extents[lo], &extents[lo + 1], (extent_count - lo - 1) * sizeof(Extent)); --extent_count; + free_idx = lo - 1; + } + const u64 free_begin = extents[free_idx].start; + const u64 free_end = free_begin + extents[free_idx].size; + const u64 decommit_begin = (free_begin + page_size - 1) & ~(page_size - 1); + const u64 decommit_end = free_end & ~(page_size - 1); + if (decommit_end > decommit_begin) { + VirtualFree(heap_base + decommit_begin, static_cast<SIZE_T>(decommit_end - decommit_begin), MEM_DECOMMIT); } done = true; } @@ -110,6 +154,149 @@ bool heap_give(const void* virtual_address) return done; } +// Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1. It watches the XMA context array that +// AcpHalAllocateShapeContexts hands out and counts how its 64-byte contexts change, without reading any field +// in them: a context that goes from all zero to nonzero is filled, one that changes while nonzero is changed, +// one that returns to all zero is cleared. HAL slot2 submits are counted by their type argument. There is no thread: +// the array is compared with a copy inside the calls that count (a HAL submit, AcpHalAllocateShapeContexts, every +// ApuFree once counting started, x2w_acphal_xma_activity), at most once per 10 ms except where a call below says it +// samples now. A context written across a sample counts twice, and one filled and cleared between two samples not at +// all. Such a call at least a second after the previous line (or the first counted event) writes the next line, with +// the counts since that line, if a count moved; until then the counts wait for a later call. +// Nothing here runs outside a call into this DLL, so a caller that unloads it leaves no code of it running. Off, +// nothing here runs: no read of caller memory, no line. +bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } + +constexpr std::size_t context_words = 64 / sizeof(u64); +constexpr unsigned submit_types = 8; // types 0..7 one by one, then all other types together +struct Activity { + u64 filled, changed, cleared; + u64 submits[submit_types + 1]; +}; +SRWLOCK activity_lock = SRWLOCK_INIT; // guards the eight below +const volatile u64* watched; // the XMA contexts, or null +u64* shadow; // their words at the last sample +std::uint32_t watched_count, live; +Activity activity, reported; // the counts now and at the last line +ULONGLONG last_sample, last_line; // GetTickCount64 of the last sample and of the last line written + // (or of the first counted event) +volatile LONG activity_started; // set with the first counted event, never cleared + +// Compares the watched contexts with the copy and counts the ones that moved. Hold activity_lock. +void sample_locked() noexcept +{ + live = 0; + for (std::uint32_t c = 0; watched && c < watched_count; ++c) { + bool was = false, now = false, moved = false; + for (std::size_t w = 0; w < context_words; ++w) { + const u64 value = watched[c * context_words + w]; // one aligned 8-byte load, never torn + u64& old = shadow[c * context_words + w]; + was = was || old; + now = now || value; + moved = moved || value != old; + old = value; + } + live += now; + if (moved) ++(!was ? activity.filled : now ? activity.changed : activity.cleared); + } +} + +// Samples the contexts (always when now is set, else at most once per 10 ms); if the last line is at least a second old +// and a count moved, writes the next line into text and returns true. Hold activity_lock; log the text after +// releasing it. +bool poll_locked(bool now, char (&text)[512]) noexcept +{ + const ULONGLONG tick = GetTickCount64(); + if (now || tick - last_sample >= 10) { + sample_locked(); + last_sample = tick; + } + if (tick - last_line < 1000 || !std::memcmp(&activity, &reported, sizeof(activity))) return false; + last_line = tick; + char types[256] = ""; + std::size_t used = 0; + u64 submits = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + const u64 n = activity.submits[t] - reported.submits[t]; + submits += n; + if (!n || used >= sizeof(types)) continue; + used += static_cast<std::size_t>(t < submit_types ? std::snprintf(types + used, sizeof(types) - used, " %u=%llu", t, n) + : std::snprintf(types + used, sizeof(types) - used, " other=%llu", n)); + } + std::snprintf(text, sizeof(text), + "x2w-audio xma-activity t=%.1f s: contexts filled=%llu changed=%llu cleared=%llu live=%u/%u; " + "hal submits=%llu by type%s", + x2w_local::process_seconds(), activity.filled - reported.filled, activity.changed - reported.changed, + activity.cleared - reported.cleared, live, watched_count, submits, types); + reported = activity; + return true; +} + +// The first counted event starts the one-second line interval. Hold activity_lock. +void start_locked() noexcept +{ + if (activity_started) return; + activity_started = 1; + last_line = GetTickCount64(); +} + +// Watches a newly allocated XMA array; its content now is the baseline. The caller's last error is kept. +void watch(unsigned char* contexts, std::uint32_t count) noexcept +{ + const DWORD error = GetLastError(); + auto* copy = new (std::nothrow) u64[std::size_t{count} * context_words]; + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + const bool line = poll_locked(true, text); // samples now: an earlier array's last changes still count + delete[] shadow; + shadow = copy; + watched = copy ? reinterpret_cast<const volatile u64*>(contexts) : nullptr; + watched_count = copy ? count : 0; + if (copy) std::memcpy(copy, contexts, std::size_t{count} * 64); + start_locked(); + ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); + x2w_local::logf(copy ? "x2w-audio xma-activity: watching %u contexts" : "x2w-audio xma-activity: no memory to watch %u contexts", + count); + SetLastError(error); +} + +// Every ApuFree once counting started: samples (now, if the block is the watched array) and may write the line. ApuFree +// of the watched array: its last changes count, then watching stops before the block can be reused. +void unwatch(const void* block) noexcept +{ + if (!activity_started) return; + const DWORD error = GetLastError(); + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + const bool hit = watched && static_cast<const volatile void*>(watched) == block; + const bool line = poll_locked(hit, text); // samples now if the watched array is freed + if (hit) { + watched = nullptr; + watched_count = live = 0; + delete[] shadow; + shadow = nullptr; + } + ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); + if (hit) x2w_local::logf("x2w-audio xma-activity: contexts freed, no longer watched"); + SetLastError(error); +} + +void count_submit(unsigned type) noexcept +{ + if (!activity_on()) return; + const DWORD error = GetLastError(); + char text[512]; + AcquireSRWLockExclusive(&activity_lock); + ++activity.submits[type < submit_types ? type : submit_types]; + start_locked(); + const bool line = poll_locked(false, text); + ReleaseSRWLockExclusive(&activity_lock); + if (line) x2w_local::logf("%s", text); + SetLastError(error); +} + // AcpHal object (not COM: slot 0 is the first method). Seen: slot 0 (0x1000, 0x1000) -> HRESULT, a // connect with two queue lengths; slot 2 (type, id, frame, &value, 0) -> HRESULT, a command submit. // Both succeed and are logged; every other slot traps and names itself. @@ -127,6 +314,7 @@ long __stdcall hal_connect(void*, unsigned commands, unsigned messages) } long __stdcall hal_submit(void*, unsigned type, u64 id, unsigned frame, const unsigned* input, u64 extra) { + count_submit(type); static LONG calls; if (x2w_local::first_calls(calls, 16)) x2w_local::logf("x2w-audio AcpHal::slot2(submit) type=%u id=0x%llx frame=0x%x input=%p [0x%x] extra=0x%llx -> S_OK", type, @@ -154,8 +342,12 @@ extern "C" __declspec(noinline) long ApuCreateHeap(u64 rcx, u64 rdx, u64 r8, u64 AcquireSRWLockExclusive(&heap_lock); if (!heap_base) { const u64 bytes = ((cached + non_cached) + 0xFFFF) & ~u64{0xFFFF}; - void* memory = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); - if (memory) { + // The whole heap must be APU-addressable (offsets below 4 GiB), so every extent, tail included, is + // representable. A larger request is refused up front without reserving or committing memory. + void* memory = bytes > heap_max_bytes ? nullptr : VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_READWRITE); + if (bytes > heap_max_bytes) { + hr = static_cast<long>(0x80070057); // E_INVALIDARG + } else if (memory) { heap_bytes = bytes; heap_reset(); heap_base = static_cast<unsigned char*>(memory); @@ -210,7 +402,10 @@ extern "C" __declspec(noinline) long AcpHalAllocateShapeContexts(u64 rcx, u64 rd rollback(); return static_cast<long>(0x8007000E); } - const u64 offset = static_cast<u64>(memory - heap_base); + unsigned char* base = nullptr; + u64 total_bytes = 0; + heap_snapshot(base, total_bytes); + const u64 offset = static_cast<u64>(memory - base); if (offset > 0xFFFFFFFFull) { heap_give(memory); rollback(); @@ -222,6 +417,7 @@ extern "C" __declspec(noinline) long AcpHalAllocateShapeContexts(u64 rcx, u64 rd x2w_local::logf("x2w-audio XMA contexts: %u x 64 bytes at %p (apu 0x%x)", counts[i], static_cast<void*>(memory), apu[i]); } + if (allocated[4] && activity_on()) watch(arrays[4], counts[4]); return 0; } @@ -230,13 +426,12 @@ extern "C" __declspec(noinline) long AcpHalCreate(u64 rcx, u64 rdx, u64 r8, u64 { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "AcpHalCreate", 1, rcx, rdx, r8, r9, _ReturnAddress()); - static auto table = hal_table(std::make_index_sequence<48>{}); - static bool ready = false; - if (!ready) { - table[0] = reinterpret_cast<void*>(&hal_connect); - table[2] = reinterpret_cast<void*>(&hal_submit); - ready = true; - } + static const auto table = [] { + auto slots = hal_table(std::make_index_sequence<48>{}); + slots[0] = reinterpret_cast<void*>(&hal_connect); + slots[2] = reinterpret_cast<void*>(&hal_submit); + return slots; + }(); static void* const* const object = table.data(); if (!rcx || !x2w_local::writable(reinterpret_cast<void*>(rcx), sizeof(void*))) return static_cast<long>(0x80004003); *reinterpret_cast<void* const* const**>(rcx) = &object; @@ -247,7 +442,9 @@ extern "C" __declspec(noinline) long AcpHalCreate(u64 rcx, u64 rdx, u64 r8, u64 // ApuAlloc(&virtualAddress, apuAddress* or null, size, alignment, flags) -> HRESULT (first call: // size 0x222e00, alignment 0x800, null APU-address output). Size and alignment are taken as 32 bits. // First fit; ApuFree returns blocks, and a reused block is zeroed as fresh heap memory is. -// A null output is E_POINTER, size 0 is E_INVALIDARG; an alignment below 16 or not a power of two means 16, and no room is E_OUTOFMEMORY; a failure leaves the heap as it was. +// A null or non-writable output is E_POINTER, size 0 is E_INVALIDARG; an alignment below 16 or not a +// power of two means 16, and no room (or an offset past 32 bits) is E_OUTOFMEMORY; a failure leaves +// the heap as it was. extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint32_t* apu_address, u64 size, u64 alignment, u64 flags) { @@ -257,11 +454,33 @@ extern "C" __declspec(noinline) long ApuAlloc(void** virtual_address, std::uint3 const u64 bytes = static_cast<std::uint32_t>(size); u64 align = static_cast<std::uint32_t>(alignment); if (align < 16 || (align & (align - 1))) align = 16; - const bool valid = bytes != 0; - unsigned char* memory = virtual_address && valid ? heap_take(bytes, align) : nullptr; - const long hr = memory ? 0 : static_cast<long>(!virtual_address ? 0x80004003 : valid ? 0x8007000E : 0x80070057); - if (virtual_address) *virtual_address = memory; - if (memory && apu_address) *apu_address = static_cast<std::uint32_t>(memory - heap_base); + const bool virtual_ok = virtual_address && x2w_local::writable(virtual_address, sizeof(void*)); + const bool apu_ok = !apu_address || x2w_local::writable(apu_address, sizeof(std::uint32_t)); + unsigned char* memory = nullptr; + u64 offset = 0; + long hr = 0; + if (!virtual_ok || !apu_ok) { + hr = static_cast<long>(0x80004003); // E_POINTER + } else if (!bytes) { + hr = static_cast<long>(0x80070057); // E_INVALIDARG + } else { + memory = heap_take(bytes, align); + if (memory) { + unsigned char* base = nullptr; + u64 total_bytes = 0; + heap_snapshot(base, total_bytes); + offset = static_cast<u64>(memory - base); + if (offset > 0xFFFFFFFFull) { + heap_give(memory); + memory = nullptr; + hr = static_cast<long>(0x8007000E); // E_OUTOFMEMORY + } + } else { + hr = static_cast<long>(0x8007000E); // E_OUTOFMEMORY + } + } + if (virtual_ok) *virtual_address = memory; + if (memory && apu_address) *apu_address = static_cast<std::uint32_t>(offset); static LONG calls; if (FAILED(hr) || x2w_local::first_calls(calls, 8)) x2w_local::logf("x2w-audio ApuAlloc size=0x%llx align=0x%llx flags=0x%llx apu_out=%p -> 0x%08lx %p", bytes, align, @@ -278,6 +497,7 @@ extern "C" __declspec(noinline) long ApuFree(void* virtual_address) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuFree", 5, reinterpret_cast<u64>(virtual_address), 0, 0, 0, _ReturnAddress()); if (!virtual_address) return 0; + unwatch(virtual_address); const long hr = heap_give(virtual_address) ? 0 : static_cast<long>(0x80070057); static LONG calls; if (FAILED(hr) || x2w_local::first_calls(calls, 4)) @@ -292,8 +512,8 @@ extern "C" __declspec(noinline) int ApuIsVirtualAddressValid(void* virtual_addre if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuIsVirtualAddressValid", 6, reinterpret_cast<u64>(virtual_address), 0, 0, 0, _ReturnAddress()); - auto* p = static_cast<unsigned char*>(virtual_address); - const int valid = heap_base && p >= heap_base && p < heap_base + heap_bytes; + u64 offset = 0; + const int valid = in_apu_range(virtual_address, offset) ? 1 : 0; static LONG calls; if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuIsVirtualAddressValid %p -> %d", virtual_address, valid); return valid; @@ -303,8 +523,11 @@ extern "C" __declspec(noinline) void* ApuMapApuAddress(u64 apu_address) { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuMapApuAddress", 7, apu_address, 0, 0, 0, _ReturnAddress()); + unsigned char* base = nullptr; + u64 bytes = 0; + heap_snapshot(base, bytes); const u64 offset = static_cast<std::uint32_t>(apu_address); - void* result = heap_base && offset && offset < heap_bytes ? heap_base + offset : nullptr; + void* result = base && offset >= heap_start && offset < bytes ? base + offset : nullptr; static LONG calls; if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuMapApuAddress 0x%llx -> %p", offset, result); return result; @@ -315,10 +538,43 @@ extern "C" __declspec(noinline) std::uint32_t ApuMapVirtualAddress(void* virtual if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "ApuMapVirtualAddress", 8, reinterpret_cast<u64>(virtual_address), 0, 0, 0, _ReturnAddress()); - auto* p = static_cast<unsigned char*>(virtual_address); - const std::uint32_t result = heap_base && p >= heap_base && p < heap_base + heap_bytes - ? static_cast<std::uint32_t>(p - heap_base) : 0; + u64 offset = 0; + const std::uint32_t result = in_apu_range(virtual_address, offset) ? static_cast<std::uint32_t>(offset) : 0; static LONG calls; if (x2w_local::first_calls(calls, 4)) x2w_local::logf("x2w-audio ApuMapVirtualAddress %p -> 0x%x", virtual_address, result); return result; } + +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): samples now, writes the line +// if one is due, as a counted call does, and writes the totals since start to out[0..14]: contexts watched, contexts +// live, filled, changed, cleared, HAL submits, then submits of types 0..7 and of all other types. With +// X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +extern "C" BOOL WINAPI x2w_acphal_xma_activity(ULONGLONG* out) +{ + if (!out) return FALSE; + const bool on = activity_on(); + Activity now{}; + std::uint32_t count = 0, live_now = 0; + char text[512]; + bool line = false; + if (on) { + AcquireSRWLockExclusive(&activity_lock); + line = poll_locked(true, text); + now = activity; + count = watched_count; + live_now = live; + ReleaseSRWLockExclusive(&activity_lock); + } + if (line) x2w_local::logf("%s", text); + out[0] = count; + out[1] = live_now; + out[2] = now.filled; + out[3] = now.changed; + out[4] = now.cleared; + out[5] = 0; + for (unsigned t = 0; t <= submit_types; ++t) { + out[5] += now.submits[t]; + out[6 + t] = now.submits[t]; + } + return on; +} diff --git a/src/startup_stubs/acphal.def b/src/startup_stubs/acphal.def index 70a0480079..d316315427 100644 --- a/src/startup_stubs/acphal.def +++ b/src/startup_stubs/acphal.def @@ -9,3 +9,4 @@ EXPORTS ApuIsVirtualAddressValid ApuMapApuAddress ApuMapVirtualAddress + x2w_acphal_xma_activity diff --git a/src/startup_stubs/address_texture.h b/src/startup_stubs/address_texture.h index 11d8337391..59171ef235 100644 --- a/src/startup_stubs/address_texture.h +++ b/src/startup_stubs/address_texture.h @@ -5,9 +5,11 @@ // device, which of those descriptions the startup renderer reads from the address: a sampled-only, // two-dimensional, single-sample texture whose Layout field holds a console swizzle mode that // gfx10_layout.h addresses. Its texels are in that console layout. -// Everything else is refused here: the desktop's unknown layout and the console's linear mode (the -// extent of such rows is not established), other dimensions, multisampled textures, textures that -// are also targets, formats without a known element size and swizzle modes without an equation. +// The console's linear mode (0x100) is one of those layouts: rows with addrlib's 256-byte pitch. In +// that mode a one-dimensional texture that is not an array is taken too. +// Everything else is refused here: the desktop's unknown layout, other dimensions, multisampled +// textures, textures that are also targets, formats without a known element size and swizzle modes +// without an equation. #include "startup_stubs/gfx10_layout.h" @@ -29,7 +31,11 @@ inline bool console_address_texture(const D3D12_RESOURCE_DESC& r) static_cast<UINT>(D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); if (!gfx10::supports(r) || r.SampleDesc.Quality || (static_cast<UINT>(r.Flags) & incompatible_flags) || r.DepthOrArraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION || - !((std::max)(r.Width, UINT64{r.Height}) >> (r.MipLevels - 1)) || + // The draw uploads a one-dimensional texture only when it is not an array (d3d12_draw.inl). + (r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && r.DepthOrArraySize != 1) || + // The largest side, depth included for a volume, must allow the mip count. + !((std::max)({r.Width, UINT64{r.Height}, + UINT64{r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? r.DepthOrArraySize : 1u}}) >> (r.MipLevels - 1)) || (r.Alignment && r.Alignment != D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT && r.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) || address_depth_format(r.Format)) @@ -70,7 +76,8 @@ inline bool address_component_mapping(UINT mapping) return true; } -// A two-dimensional or array view that stays inside the texture and reads its texels as stored. +// A one-dimensional, two-dimensional, array or cube view that stays inside the texture and reads its texels +// as stored. inline bool address_view_fits(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) { if (!address_view_format(r.Format, v.Format) || !address_component_mapping(v.Shader4ComponentMapping)) @@ -81,6 +88,9 @@ inline bool address_view_fits(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_R const auto mips_fit = [&](UINT first, UINT count) { return count == ~0u ? first < r.MipLevels : inside(first, count, r.MipLevels); }; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE1D) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && r.DepthOrArraySize == 1 && + mips_fit(v.Texture1D.MostDetailedMip, v.Texture1D.MipLevels) && v.Texture1D.ResourceMinLODClamp == 0.0f; if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.DepthOrArraySize == 1 && mips_fit(v.Texture2D.MostDetailedMip, v.Texture2D.MipLevels) && @@ -90,6 +100,10 @@ inline bool address_view_fits(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_R mips_fit(v.Texture2DArray.MostDetailedMip, v.Texture2DArray.MipLevels) && inside(v.Texture2DArray.FirstArraySlice, v.Texture2DArray.ArraySize, r.DepthOrArraySize) && !v.Texture2DArray.PlaneSlice && v.Texture2DArray.ResourceMinLODClamp == 0.0f; + // A cube view reads the six slices of a two-dimensional array of six as its faces (+X, -X, +Y, -Y, +Z, -Z). + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURECUBE) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.DepthOrArraySize == 6 && + mips_fit(v.TextureCube.MostDetailedMip, v.TextureCube.MipLevels) && v.TextureCube.ResourceMinLODClamp == 0.0f; if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D) return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && mips_fit(v.Texture3D.MostDetailedMip, v.Texture3D.MipLevels) && diff --git a/src/startup_stubs/audio_sink.cpp b/src/startup_stubs/audio_sink.cpp index 635f10040e..d8f1ca8671 100644 --- a/src/startup_stubs/audio_sink.cpp +++ b/src/startup_stubs/audio_sink.cpp @@ -124,7 +124,10 @@ void AudioSink::observe(bool withholding) Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* bytes) { const uint32_t call = calls_++; - if (!p_) return Submit::NotOpen; + if (!p_) { + ++r_.not_open; + return Submit::NotOpen; + } ResampleState trial = resample_; // committed only once the block is accepted if (!convert_block(in, bytes, frames, mix_, conv_buf_, &trial)) { ++r_.unsupported; @@ -132,7 +135,10 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt } const uint32_t out_frames = static_cast<uint32_t>(conv_buf_.size() / mix_.frame_bytes()); const uint32_t pad = padding(); - if (pad == padding_failed) return Submit::NotOpen; + if (pad == padding_failed) { + ++r_.not_open; + return Submit::NotOpen; + } if (out_frames > buffer_frames_ - pad) { ++r_.rejected_full; return Submit::Full; @@ -141,9 +147,15 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt if (timer_.drained_start >= 0) timer_.resume(now_ms(), r_.consumed_frames); // the producer is back if (out_frames > 0) { BYTE* dst = nullptr; - if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) return Submit::NotOpen; + if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) { + ++r_.not_open; + return Submit::NotOpen; + } std::memcpy(dst, conv_buf_.data(), conv_buf_.size()); - if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) return Submit::NotOpen; + if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) { + ++r_.not_open; + return Submit::NotOpen; + } } resample_ = std::move(trial); if (r_.first_block < 0) { @@ -153,6 +165,7 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt r_.frames.push_back(out_frames); r_.peaks.push_back(block_peak(in, bytes, frames)); r_.submitted_frames += out_frames; + ++r_.accepted; if (!started_ && SUCCEEDED(p_->client->Start())) started_ = true; return Submit::Accepted; } diff --git a/src/startup_stubs/audio_sink.h b/src/startup_stubs/audio_sink.h index c55ffbf768..f00edbca1b 100644 --- a/src/startup_stubs/audio_sink.h +++ b/src/startup_stubs/audio_sink.h @@ -259,7 +259,8 @@ struct Report { uint64_t submitted_frames = 0; // frames written to the endpoint uint64_t consumed_frames = 0; // submitted frames minus frames still queued uint64_t clock_frames = 0; // IAudioClock position converted to frames - uint32_t unsupported = 0, rejected_full = 0; + uint64_t accepted = 0; // submit() calls that returned Submit::Accepted + uint32_t unsupported = 0, rejected_full = 0, not_open = 0; uint32_t padding_errors = 0; // GetCurrentPadding failed (e.g. the endpoint went away): not a measurement double drained_ms = 0, recovery_ms = -1; // recovery_ms < 0: not measured // Glitches: the render API exposes no discontinuity flag, so this stays "not available". diff --git a/src/startup_stubs/audio_telemetry.h b/src/startup_stubs/audio_telemetry.h new file mode 100644 index 0000000000..e7f9b3a671 --- /dev/null +++ b/src/startup_stubs/audio_telemetry.h @@ -0,0 +1,97 @@ +// Experimental (docs/startup-runtime.md): bounded counters for the optional Opus decode path. +// +// Every counter saturates at UINT64_MAX instead of wrapping. The values are process-wide and are +// read without a single coherent snapshot: a summary taken while another thread enqueues can show +// one field from before that enqueue and another from after it. Each field is exact on its own. +#pragma once + +#include <atomic> +#include <cstdint> +#include <limits> + +namespace x2w_audio { + +inline void saturating_add(std::atomic<std::uint64_t>& counter, std::uint64_t amount = 1) noexcept +{ + std::uint64_t seen = counter.load(std::memory_order_relaxed); + for (;;) { + const std::uint64_t next = amount > (std::numeric_limits<std::uint64_t>::max)() - seen + ? (std::numeric_limits<std::uint64_t>::max)() + : seen + amount; + if (next == seen || counter.compare_exchange_weak(seen, next, std::memory_order_relaxed, + std::memory_order_relaxed)) + return; + } +} + +// Counters for one process's type-3 Opus path. `type3_commands` counts every readable type-3 +// command while typed completions are on. `packets_decoded` counts calls libopus accepted with a +// non-empty packet. `decoded_completions` counts type-3 results dequeued by the caller, so a packet +// that decodes but is never consumed is not in it. The refusal fields name the first check that +// refused the command; `header` covers a null or unreadable XApuEnqueueCommand header. +struct OpusCounters { + std::atomic<std::uint64_t> type3_commands{0}; + std::atomic<std::uint64_t> packets_decoded{0}; + std::atomic<std::uint64_t> decoded_completions{0}; + std::atomic<std::uint64_t> refused_header{0}; + std::atomic<std::uint64_t> refused_short_command{0}; + std::atomic<std::uint64_t> refused_unknown_handle{0}; + std::atomic<std::uint64_t> refused_queue_full{0}; + std::atomic<std::uint64_t> refused_invalid_argument{0}; + std::atomic<std::uint64_t> refused_opus_error{0}; + std::atomic<std::uint64_t> refused_capacity{0}; + std::atomic<std::uint64_t> refused_out_of_memory{0}; +}; + +struct OpusCounterSnapshot { + std::uint64_t type3_commands = 0; + std::uint64_t packets_decoded = 0; + std::uint64_t decoded_completions = 0; + std::uint64_t refused_header = 0; + std::uint64_t refused_short_command = 0; + std::uint64_t refused_unknown_handle = 0; + std::uint64_t refused_queue_full = 0; + std::uint64_t refused_invalid_argument = 0; + std::uint64_t refused_opus_error = 0; + std::uint64_t refused_capacity = 0; + std::uint64_t refused_out_of_memory = 0; +}; + +inline OpusCounterSnapshot snapshot(const OpusCounters& counters) noexcept +{ + return {counters.type3_commands.load(std::memory_order_relaxed), + counters.packets_decoded.load(std::memory_order_relaxed), + counters.decoded_completions.load(std::memory_order_relaxed), + counters.refused_header.load(std::memory_order_relaxed), + counters.refused_short_command.load(std::memory_order_relaxed), + counters.refused_unknown_handle.load(std::memory_order_relaxed), + counters.refused_queue_full.load(std::memory_order_relaxed), + counters.refused_invalid_argument.load(std::memory_order_relaxed), + counters.refused_opus_error.load(std::memory_order_relaxed), + counters.refused_capacity.load(std::memory_order_relaxed), + counters.refused_out_of_memory.load(std::memory_order_relaxed)}; +} + +inline std::uint64_t saturating_total(std::uint64_t& total, std::uint64_t value) noexcept +{ + total = value > (std::numeric_limits<std::uint64_t>::max)() - total + ? (std::numeric_limits<std::uint64_t>::max)() + : total + value; + return total; +} + +inline std::uint64_t refused_total(const OpusCounterSnapshot& s) noexcept +{ + std::uint64_t total = 0; + saturating_total(total, s.refused_header); + saturating_total(total, s.refused_short_command); + saturating_total(total, s.refused_unknown_handle); + saturating_total(total, s.refused_queue_full); + saturating_total(total, s.refused_invalid_argument); + saturating_total(total, s.refused_opus_error); + saturating_total(total, s.refused_capacity); + saturating_total(total, s.refused_out_of_memory); + return total; +} + +} // namespace x2w_audio diff --git a/src/startup_stubs/bcpack_blocks_extra.inl b/src/startup_stubs/bcpack_blocks_extra.inl new file mode 100644 index 0000000000..0ff5487be1 --- /dev/null +++ b/src/startup_stubs/bcpack_blocks_extra.inl @@ -0,0 +1,173 @@ +// Standalone BC1, BC2 and BC6H block reconstruction from BCPack lane symbols. +// SPDX-License-Identifier: MIT + +template<class State, size_t Count> +inline State bcpack_predictor(size_t block, size_t reference, const State (&history)[256], + const State (&dictionary)[Count]) { + if (reference == 0) return {}; + if (reference <= block) return history[(block - reference) & 255]; + const size_t index = reference - block - 1; + return index < Count ? dictionary[index] : State{}; +} + +inline void bcpack_quad(const uint8_t (&rank)[256][4], uint16_t symbol, size_t quadrant, + const uint8_t* predictor, uint8_t* positions) { + const size_t base = (quadrant >> 1) * 8 + (quadrant & 1) * 2; + constexpr size_t offsets[4] = {0, 1, 4, 5}; + for (size_t k = 0; k < 4; ++k) { + const size_t p = base + offsets[k]; + positions[p] = static_cast<uint8_t>((predictor[p] + rank[symbol & 255][k]) & 3); + } +} + +inline bool decode_bc1_blocks(const std::vector<uint16_t>& symbols, size_t blocks, + uint8_t* output, size_t capacity) { + if (blocks > capacity / 8 || blocks > symbols.size() / 12) return false; + constexpr uint8_t widths[6] = {5,6,5,5,6,5}; + Bc1FullState history[256] = {}; + for (size_t i = 0; i < blocks; ++i) { + // Lane 1 is the index distance. Lane 0 is a zigzag delta from it to + // the endpoint distance; they can select different historical blocks. + const size_t xr = symbols[blocks + i] & 255; + const size_t er = static_cast<size_t>(static_cast<int>(xr) + unzigzag(symbols[i])) & 255; + const auto ep = bcpack_predictor(i,er,history,BC1_FULL_DICTIONARY); + const auto ix = bcpack_predictor(i,xr,history,BC1_FULL_DICTIONARY); + Bc1FullState state{}; + for (size_t c = 0; c < 6; ++c) { + state.ep[c] = static_cast<uint8_t>((ep.ep[c] + unzigzag(symbols[(2+c)*blocks+i])) & ((1u<<widths[c])-1)); + } + for (size_t q = 0; q < 4; ++q) { + bcpack_quad(BC1_POSITION_RANK,symbols[(8+q)*blocks+i],q,ix.ix,state.ix); + } + pack_colour(state.ep,state.ix,output+i*8); + history[i&255] = state; + } + return true; +} + +inline bool decode_bc2_blocks(const std::vector<uint16_t>& symbols, size_t blocks, + uint8_t* output, size_t capacity) { + if (blocks > capacity / 16 || blocks > symbols.size() / 30) return false; + const size_t target = blocks*2; + Bc2State history[256] = {}; + for (size_t i = 0; i < blocks; ++i) { + const uint8_t d = interleave(symbols[2*i],symbols[2*i+1]); + const size_t xr = interleave(symbols[target+2*i],symbols[target+2*i+1]); + const size_t er = static_cast<size_t>(static_cast<int>(xr)+unzigzag(d)) & 255; + const auto ep = bcpack_predictor(i,er,history,BC2_FULL_DICTIONARY); + const auto ix = bcpack_predictor(i,xr,history,BC2_FULL_DICTIONARY); + Bc2State state{}; + uint64_t alpha = 0; + for (size_t p = 0; p < 16; ++p) { + // BC2 stores explicit four-bit alpha, biased around eight. Its + // predictor follows endpoint history, independently of colour indices. + state.alpha[p] = static_cast<uint8_t>((ep.alpha[p]+unzigzag(symbols[(2+p/2)*target+2*i+p%2])) & 15); + alpha |= static_cast<uint64_t>(state.alpha[p]^8) << (4*p); + } + for (size_t c = 0; c < 3; ++c) { + const unsigned bits = c == 1 ? 6 : 5; + for (size_t e = 0; e < 2; ++e) { + state.ep[3*e+c] = static_cast<uint8_t>((ep.ep[3*e+c]+unzigzag(symbols[(10+c)*target+2*i+e])) & ((1u<<bits)-1)); + } + } + for (size_t q = 0; q < 4; ++q) { + bcpack_quad(BC2_POSITION_RANK,symbols[(13+q/2)*target+2*i+q%2],q,ix.ix,state.ix); + } + std::memcpy(output+i*16,&alpha,8); + pack_colour(state.ep,state.ix,output+i*16+8); + history[i&255] = state; + } + return true; +} + +inline uint16_t bcpack_wide(uint16_t even, uint16_t odd) { + uint16_t value = 0; + for (unsigned bit = 0; bit < 8; ++bit) { + value |= static_cast<uint16_t>(((even>>bit)&1)<<(2*bit) | ((odd>>bit)&1)<<(2*bit+1)); + } + return value; +} + +inline uint16_t bcpack_add_aligned(uint16_t predictor, int32_t delta, unsigned shift) { + const uint32_t aligned = static_cast<uint32_t>(static_cast<uint16_t>(delta)) << shift; + return static_cast<uint16_t>((predictor+aligned) & (0xffffu<<shift)); +} + +inline void bcpack_put_bit(uint8_t* output, size_t at, unsigned bit) { + output[at/8] |= static_cast<uint8_t>((bit&1)<<(at%8)); +} + +inline bool decode_bc6_blocks(const std::vector<uint16_t>& symbols, size_t blocks, + uint8_t* output, size_t capacity) { + if (blocks > capacity/16 || blocks > symbols.size()/32) return false; + const size_t target = blocks*2; + constexpr uint8_t codes[14] = {0,1,2,6,10,14,18,22,26,30,3,7,11,15}; + Bc6State history[256] = {}; + for (size_t i = 0; i < blocks; ++i) { + const unsigned mode = symbols[15*target+2*i]+1; + if (mode < 1 || mode > 14) return false; + const bool two = mode <= 10; + const unsigned part = symbols[15*target+2*i+1]&31; + const uint8_t d = interleave(symbols[2*i],symbols[2*i+1]); + const size_t xr = interleave(symbols[target+2*i],symbols[target+2*i+1]); + const size_t er = static_cast<size_t>(static_cast<int>(xr)+unzigzag(d)) & 255; + const auto ep = bcpack_predictor(i,er,history,BC6_DICTIONARY); + const auto ix = bcpack_predictor(i,xr,history,BC6_DICTIONARY); + Bc6State state{}; + // Keep signed/bias-centred values left aligned, so changing modes can + // reuse a predictor without confusing its original precision with this mode's. + for (size_t c = 0; c < 3; ++c) { + const unsigned s0 = 16-BC6_ENDPOINT_BITS[mode][0]; + const unsigned sc = 16-BC6_ENDPOINT_BITS[mode][c+1]; + const uint16_t v0 = bcpack_wide(symbols[(2+c)*target+2*i],symbols[(2+c)*target+2*i+1]); + const uint16_t v1 = bcpack_wide(symbols[(5+c)*target+2*i],symbols[(5+c)*target+2*i+1]); + state.ep[0][c] = bcpack_add_aligned(ep.ep[0][c],unzigzag(v0),s0); + state.ep[1][c] = bcpack_add_aligned(ep.ep[1][c],unzigzag(v1),sc); + if (two) { + state.ep[2][c] = bcpack_add_aligned(ep.ep[2][c],unzigzag(symbols[(8+c)*target+2*i]),sc); + state.ep[3][c] = bcpack_add_aligned(ep.ep[3][c],unzigzag(symbols[(8+c)*target+2*i+1]),sc); + } else { + // One-subset blocks still update the hidden second-subset + // history used by a later two-subset block. + state.ep[2][c] = static_cast<uint16_t>((state.ep[0][c]>>s0)<<sc); + state.ep[3][c] = state.ep[1][c]; + } + } + const unsigned bits = two ? 3 : 4; + for (size_t pair = 0; pair < 8; ++pair) { + const uint16_t v = symbols[(11+pair/2)*target+2*i+pair%2]; + for (size_t h = 0; h < 2; ++h) { + // The last two pairs swap the lane's even/odd bit assignment. + const unsigned parity = pair < 6 ? 1-static_cast<unsigned>(h) : static_cast<unsigned>(h); + uint16_t nibble = 0; + for (unsigned k = 0; k < 4; ++k) nibble |= ((v>>(2*k+parity))&1)<<k; + const size_t p = 2*pair+h; + state.ix[p] = bcpack_add_aligned(ix.ix[p],unzigzag(nibble),16-bits); + } + } + uint8_t* block = output+i*16; + std::memset(block,0,16); + const size_t header = two ? 82 : 65; + for (size_t at = 0; at < header; ++at) { + const auto wire = BC6_WIRE[mode-1][at]; + unsigned value; + if (wire.field == 0) value = codes[mode-1]; + else if (wire.field == 1) value = part; + else { + const unsigned k = (wire.field-2)/3, c = (wire.field-2)%3; + const unsigned shift = 16-BC6_ENDPOINT_BITS[mode][k == 0 ? 0 : c+1]; + value = (state.ep[k][c]^0x8000u)>>shift; + } + bcpack_put_bit(block,at,value>>wire.bit); + } + size_t at = header; + const size_t anchor = two ? ANCHOR_2[part] : 0; + for (size_t p = 0; p < 16; ++p) { + const unsigned width = bits-static_cast<unsigned>(p == 0 || p == anchor); + const unsigned value = (state.ix[p]>>(16-bits))+(1u<<(bits-1)); + for (unsigned b = 0; b < width; ++b) bcpack_put_bit(block,at++,value>>b); + } + history[i&255] = state; + } + return true; +} diff --git a/src/startup_stubs/bcpack_decoder.h b/src/startup_stubs/bcpack_decoder.h index e255040f50..a279b804c5 100644 --- a/src/startup_stubs/bcpack_decoder.h +++ b/src/startup_stubs/bcpack_decoder.h @@ -2,6 +2,7 @@ // Adapted from bcpack-rs by Ahmet Dedeler (https://github.com/Ahmet-Dedeler, https://ahmetdedeler.com). // Source: https://github.com/Ahmet-Dedeler/bcpack-rs // SPDX-License-Identifier: MIT OR Apache-2.0 +// New BC1/2/6H reconstruction in bcpack_blocks_extra.inl is an original MIT contribution. // Incorporates rANS interval models derived from Microsoft silicon-rans (MIT License). #pragma once @@ -1119,48 +1120,6 @@ inline bool decode_bc7_blocks(const std::vector<uint16_t>& symbols, size_t num_b return true; } -inline bool decode_bc1_blocks(const std::vector<uint16_t>& symbols, size_t target, - uint8_t* output, size_t output_capacity) { - if (output_capacity < target * 8) return false; - const uint8_t ENDPOINT_WIDTHS[6] = { 5, 6, 5, 5, 6, 5 }; - uint8_t hist[256][6] = {}; - for (size_t i = 0; i < target; ++i) { - uint16_t l0_sym = symbols[0 * target + i]; - size_t v = l0_sym & 0xFF; - size_t d = (v & 1) ? (255 - (v >> 1)) : (v >> 1); - uint8_t pred[6] = {}; - if (d == 0) { - // zero - } else if (d <= i) { - std::memcpy(pred, hist[(i - d) & 255], 6); - } else { - size_t slot = (static_cast<int>(i) - static_cast<int>(d)) & 255; - std::memcpy(pred, BC1_WINDOW[slot], 6); - } - uint8_t e[6]; - for (int k = 0; k < 6; ++k) { - uint16_t sym = symbols[(2 + k) * target + i]; - int32_t res = unzigzag(sym); - uint32_t mask = (1u << ENDPOINT_WIDTHS[k]) - 1; - e[k] = static_cast<uint8_t>((pred[k] + res) & mask); - } - std::memcpy(hist[i & 255], e, 6); - uint16_t c0 = (static_cast<uint16_t>(e[0]) << 11) | (static_cast<uint16_t>(e[1]) << 5) | e[2]; - uint16_t c1 = (static_cast<uint16_t>(e[3]) << 11) | (static_cast<uint16_t>(e[4]) << 5) | e[5]; - uint32_t idx0 = symbols[8 * target + i] & 0xFF; - uint32_t idx1 = symbols[9 * target + i] & 0xFF; - uint32_t idx2 = symbols[10 * target + i] & 0xFF; - uint32_t idx3 = symbols[11 * target + i] & 0xFF; - uint32_t w = BC1_QUAD_MASKS[0][idx0] | BC1_QUAD_MASKS[1][idx1] | - BC1_QUAD_MASKS[2][idx2] | BC1_QUAD_MASKS[3][idx3]; - uint8_t* blk = output + i * 8; - std::memcpy(blk + 0, &c0, 2); - std::memcpy(blk + 2, &c1, 2); - std::memcpy(blk + 4, &w, 4); - } - return true; -} - inline constexpr uint8_t ALPHA_CODE[8] = { 0, 2, 3, 4, 5, 6, 7, 1 }; inline constexpr uint8_t COLOUR_CODE[4] = { 0, 2, 3, 1 }; @@ -1419,83 +1378,46 @@ inline bool decode_bc3_blocks(const std::vector<uint16_t>& symbols, size_t num_b return true; } +#include "bcpack_blocks_extra.inl" + inline bool decode_bcpack(const unsigned char* input, size_t input_size, unsigned bc_format, unsigned char* output, size_t output_size, size_t* produced) { - if (!input || !output || !produced) return false; - if (input_size == 0 || output_size == 0) return false; - - if (bc_format == 7) { - if (output_size % 16 != 0) return false; - size_t num_blocks = output_size / 16; - size_t target_per_lane = num_blocks * 2; - const uint8_t ab[16] = { 3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 16, target_per_lane, symbols)) { - return false; - } - if (!decode_bc7_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 1) { - if (output_size % 8 != 0) return false; - size_t num_blocks = output_size / 8; - size_t target_per_lane = num_blocks; - const uint8_t ab[12] = { 7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc1_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 4) { - if (output_size % 8 != 0) return false; - size_t num_blocks = output_size / 8; - size_t target_per_lane = num_blocks; - const uint8_t ab[12] = { 7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc4_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 5) { - if (output_size % 16 != 0) return false; - size_t num_blocks = output_size / 16; - size_t target_per_lane = num_blocks * 2; - const uint8_t ab[12] = { 3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc5_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; - } else if (bc_format == 3) { - if (output_size % 16 != 0) return false; - size_t num_blocks = output_size / 16; - size_t target_per_lane = num_blocks * 2; - const uint8_t ab[12] = { 3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7 }; - std::vector<uint16_t> symbols; - if (!decode_lanes(input, input_size, ab, 12, target_per_lane, symbols)) { - return false; - } - if (!decode_bc3_blocks(symbols, num_blocks, output, output_size)) { - return false; - } - *produced = output_size; - return true; + if (!produced) return false; + *produced = 0; + if (!input || !output || input_size == 0 || output_size == 0 || + bc_format < 1 || bc_format > 7) return false; + + // Hardware alphabet indices, not literal symbol bit widths. + static constexpr uint8_t alphabets[7][16] = { + {7,7,4,5,4,4,5,4,7,7,7,7}, + {3,3,3,3,3,3,3,3,3,3,4,5,4,7,7}, + {3,3,7,5,5,5,5,4,5,4,7,7}, + {7,7,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,7,4,4,4,5,5,5,7,7,7,7,4}, + {3,3,7,7,7,7,7,6,6,4,5,7,7,7,7,4}, + }; + const size_t bytes_per_block = bc_format == 1 || bc_format == 4 ? 8 : 16; + if (output_size % bytes_per_block) return false; + const size_t blocks = output_size / bytes_per_block; + const size_t target = output_size / 8; + const size_t lanes = bc_format >= 6 ? 16 : bc_format == 2 ? 15 : 12; + std::vector<uint16_t> symbols; + if (target > symbols.max_size() / lanes) return false; + if (!decode_lanes(input, input_size, alphabets[bc_format-1], lanes, target, symbols)) return false; + bool ok = false; + switch (bc_format) { + case 1: ok = decode_bc1_blocks(symbols,blocks,output,output_size); break; + case 2: ok = decode_bc2_blocks(symbols,blocks,output,output_size); break; + case 3: ok = decode_bc3_blocks(symbols,blocks,output,output_size); break; + case 4: ok = decode_bc4_blocks(symbols,blocks,output,output_size); break; + case 5: ok = decode_bc5_blocks(symbols,blocks,output,output_size); break; + case 6: ok = decode_bc6_blocks(symbols,blocks,output,output_size); break; + case 7: ok = decode_bc7_blocks(symbols,blocks,output,output_size); break; } - return false; + if (!ok) return false; + *produced = output_size; + return true; } } // namespace x2w_bcpack diff --git a/src/startup_stubs/bcpack_tables.h b/src/startup_stubs/bcpack_tables.h index 47f2d3d5b4..50dfd8e53d 100644 --- a/src/startup_stubs/bcpack_tables.h +++ b/src/startup_stubs/bcpack_tables.h @@ -1,6 +1,6 @@ // Generated BCPack model and codebook tables. -// Codebook, rank, and dictionary tables (BC7_CONTROL_TABLE, BC7_DICTIONARY, BC1_WINDOW, -// BC1_QUAD_MASKS, plus bcpack_tables_bcn.inl: RANK_PAIR_BC4, BC4_DICTIONARY, RANK_PAIR_BC5, +// Codebook, rank, and dictionary tables (BC7_CONTROL_TABLE, BC7_DICTIONARY, +// plus bcpack_tables_bcn.inl: RANK_PAIR_BC4, BC4_DICTIONARY, RANK_PAIR_BC5, // BC5_DICTIONARY, RANK_PAIR_BC3_ALPHA, RANK_QUAD_BC3_COLOUR, BC3_DICTIONARY) adapted // from bcpack-rs (pinned revision c55c5fad539644b8cf5a705051df214291763fc0) // by Ahmet Dedeler (https://github.com/Ahmet-Dedeler, https://ahmetdedeler.com). @@ -1623,404 +1623,7 @@ inline constexpr Bc7DictEntry BC7_DICTIONARY[255] = { { 0, { { 0x7f, 0x7f, 0x7e, 0x7e, 0x56, 0x3e, 0xfe, 0xfe }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { { 0x04, 0x04, 0x0a, 0x00, 0x0f, 0x04, 0x01, 0x01, 0x0b, 0x00, 0x0d, 0x0b, 0x0c, 0x0d, 0x0b, 0x04 }, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, }; -inline constexpr uint8_t BC1_WINDOW[256][6] = { - { 0, 0, 0, 0, 0, 0 }, - { 7, 29, 6, 8, 30, 7 }, - { 15, 29, 15, 16, 36, 17 }, - { 20, 37, 14, 3, 6, 2 }, - { 0, 0, 0, 0, 0, 0 }, - { 10, 21, 11, 6, 15, 7 }, - { 12, 23, 11, 7, 15, 6 }, - { 12, 26, 12, 7, 15, 7 }, - { 22, 36, 15, 20, 32, 14 }, - { 14, 23, 8, 1, 2, 1 }, - { 23, 5, 30, 9, 5, 30 }, - { 11, 22, 11, 7, 15, 7 }, - { 17, 22, 7, 10, 11, 3 }, - { 12, 25, 12, 7, 16, 7 }, - { 13, 28, 8, 5, 12, 3 }, - { 11, 20, 8, 16, 31, 14 }, - { 23, 32, 30, 17, 12, 29 }, - { 8, 44, 30, 6, 26, 30 }, - { 10, 24, 30, 6, 45, 30 }, - { 10, 12, 4, 8, 8, 2 }, - { 16, 23, 30, 14, 6, 26 }, - { 12, 25, 13, 10, 22, 12 }, - { 19, 27, 10, 13, 16, 5 }, - { 11, 24, 12, 4, 11, 6 }, - { 29, 60, 29, 6, 13, 6 }, - { 17, 31, 11, 1, 2, 1 }, - { 26, 54, 24, 12, 24, 10 }, - { 23, 48, 30, 20, 37, 30 }, - { 16, 23, 10, 10, 15, 6 }, - { 11, 24, 10, 6, 13, 5 }, - { 18, 52, 30, 14, 22, 30 }, - { 14, 51, 30, 9, 34, 30 }, - { 2, 3, 1, 19, 37, 16 }, - { 14, 15, 30, 10, 32, 30 }, - { 29, 57, 27, 27, 52, 25 }, - { 13, 29, 15, 8, 20, 11 }, - { 13, 17, 5, 9, 10, 3 }, - { 18, 50, 29, 15, 10, 29 }, - { 11, 25, 13, 8, 19, 10 }, - { 17, 31, 12, 6, 12, 4 }, - { 22, 18, 30, 19, 41, 30 }, - { 10, 22, 11, 8, 18, 9 }, - { 18, 30, 31, 10, 44, 30 }, - { 25, 50, 24, 2, 4, 1 }, - { 11, 30, 31, 7, 15, 29 }, - { 12, 19, 8, 11, 16, 7 }, - { 19, 29, 30, 14, 55, 28 }, - { 9, 20, 10, 4, 10, 5 }, - { 12, 23, 10, 7, 14, 5 }, - { 26, 53, 25, 6, 13, 6 }, - { 19, 27, 31, 11, 19, 30 }, - { 21, 31, 30, 22, 31, 30 }, - { 10, 19, 5, 11, 21, 6 }, - { 30, 50, 3, 29, 46, 2 }, - { 15, 9, 30, 7, 9, 30 }, - { 14, 18, 6, 11, 14, 4 }, - { 28, 56, 26, 4, 7, 3 }, - { 8, 20, 10, 6, 13, 7 }, - { 28, 58, 26, 15, 32, 14 }, - { 10, 19, 8, 7, 10, 4 }, - { 16, 22, 9, 13, 17, 7 }, - { 1, 2, 1, 14, 28, 12 }, - { 22, 45, 30, 9, 15, 30 }, - { 19, 22, 30, 16, 23, 31 }, - { 25, 50, 24, 21, 43, 20 }, - { 6, 11, 4, 16, 31, 13 }, - { 13, 25, 8, 3, 6, 1 }, - { 5, 9, 3, 12, 24, 10 }, - { 16, 29, 13, 8, 14, 6 }, - { 20, 37, 16, 13, 26, 10 }, - { 18, 35, 15, 5, 9, 3 }, - { 13, 25, 11, 7, 12, 5 }, - { 11, 21, 7, 7, 14, 4 }, - { 20, 39, 16, 11, 21, 8 }, - { 16, 31, 12, 4, 8, 2 }, - { 22, 41, 30, 18, 23, 30 }, - { 24, 50, 24, 9, 20, 8 }, - { 3, 12, 7, 4, 16, 8 }, - { 18, 27, 12, 16, 22, 10 }, - { 24, 49, 23, 13, 28, 12 }, - { 24, 49, 24, 18, 38, 18 }, - { 17, 32, 12, 14, 28, 9 }, - { 20, 10, 31, 13, 10, 31 }, - { 7, 8, 2, 5, 5, 1 }, - { 1, 2, 1, 10, 21, 9 }, - { 10, 18, 6, 1, 1, 0 }, - { 22, 46, 21, 1, 3, 1 }, - { 11, 20, 8, 8, 14, 5 }, - { 17, 35, 31, 14, 14, 29 }, - { 16, 22, 31, 12, 40, 31 }, - { 12, 22, 9, 8, 15, 6 }, - { 18, 15, 30, 15, 33, 31 }, - { 19, 32, 30, 15, 43, 31 }, - { 18, 35, 15, 8, 15, 5 }, - { 21, 43, 20, 18, 37, 17 }, - { 10, 17, 6, 9, 15, 6 }, - { 14, 27, 12, 7, 14, 5 }, - { 8, 15, 7, 12, 26, 11 }, - { 18, 37, 17, 1, 1, 0 }, - { 17, 45, 30, 15, 33, 31 }, - { 13, 24, 11, 8, 17, 7 }, - { 23, 47, 22, 16, 32, 15 }, - { 18, 33, 13, 11, 22, 8 }, - { 4, 10, 4, 8, 17, 7 }, - { 1, 2, 1, 3, 7, 3 }, - { 11, 22, 9, 6, 12, 4 }, - { 16, 28, 11, 13, 24, 9 }, - { 12, 24, 12, 7, 13, 6 }, - { 23, 47, 22, 7, 15, 6 }, - { 11, 32, 30, 11, 31, 30 }, - { 14, 26, 11, 10, 19, 7 }, - { 20, 41, 19, 1, 3, 1 }, - { 14, 27, 12, 8, 17, 6 }, - { 11, 21, 9, 8, 15, 6 }, - { 1, 2, 1, 7, 13, 6 }, - { 19, 34, 14, 16, 30, 12 }, - { 13, 27, 13, 7, 16, 7 }, - { 15, 32, 16, 8, 19, 9 }, - { 15, 42, 31, 11, 22, 30 }, - { 23, 48, 23, 5, 10, 4 }, - { 22, 45, 21, 11, 23, 10 }, - { 31, 62, 30, 31, 61, 29 }, - { 13, 26, 11, 5, 8, 3 }, - { 19, 39, 19, 9, 21, 10 }, - { 7, 14, 2, 6, 12, 2 }, - { 21, 42, 20, 4, 7, 3 }, - { 10, 17, 7, 8, 13, 5 }, - { 10, 22, 8, 11, 19, 7 }, - { 19, 33, 31, 12, 31, 31 }, - { 21, 43, 20, 5, 11, 5 }, - { 9, 21, 8, 8, 13, 7 }, - { 10, 21, 10, 6, 13, 6 }, - { 15, 29, 12, 11, 21, 8 }, - { 21, 43, 20, 9, 19, 8 }, - { 3, 8, 3, 5, 11, 5 }, - { 16, 31, 13, 9, 18, 7 }, - { 11, 21, 11, 6, 13, 6 }, - { 10, 21, 10, 7, 15, 7 }, - { 27, 3, 1, 26, 1, 0 }, - { 18, 37, 18, 16, 32, 16 }, - { 12, 23, 10, 9, 18, 7 }, - { 12, 25, 12, 8, 18, 8 }, - { 11, 20, 9, 2, 5, 1 }, - { 7, 15, 7, 8, 18, 9 }, - { 17, 33, 15, 13, 24, 11 }, - { 9, 19, 9, 7, 15, 7 }, - { 21, 43, 20, 13, 28, 12 }, - { 17, 36, 17, 2, 4, 2 }, - { 10, 19, 9, 6, 13, 5 }, - { 20, 41, 19, 7, 14, 7 }, - { 3, 9, 6, 2, 8, 5 }, - { 13, 24, 10, 11, 20, 8 }, - { 18, 39, 18, 6, 10, 5 }, - { 19, 38, 18, 8, 17, 8 }, - { 16, 35, 17, 4, 11, 4 }, - { 11, 23, 11, 10, 21, 10 }, - { 17, 36, 17, 7, 15, 7 }, - { 13, 27, 13, 7, 13, 7 }, - { 9, 15, 4, 8, 13, 4 }, - { 9, 19, 7, 6, 9, 3 }, - { 19, 39, 19, 11, 25, 11 }, - { 11, 23, 11, 8, 17, 8 }, - { 14, 29, 14, 7, 16, 7 }, - { 12, 22, 8, 5, 9, 4 }, - { 10, 20, 9, 8, 17, 8 }, - { 21, 41, 19, 15, 32, 14 }, - { 14, 28, 13, 1, 2, 0 }, - { 8, 16, 8, 7, 14, 7 }, - { 9, 18, 8, 8, 16, 7 }, - { 10, 17, 7, 3, 4, 1 }, - { 14, 28, 13, 2, 4, 1 }, - { 14, 30, 14, 3, 6, 3 }, - { 19, 38, 18, 5, 11, 5 }, - { 12, 26, 12, 1, 2, 1 }, - { 9, 16, 6, 8, 13, 5 }, - { 8, 13, 4, 7, 11, 4 }, - { 16, 35, 16, 4, 8, 4 }, - { 13, 28, 13, 4, 9, 4 }, - { 15, 31, 15, 6, 13, 6 }, - { 12, 24, 11, 9, 19, 9 }, - { 9, 19, 8, 7, 14, 6 }, - { 14, 28, 13, 5, 10, 4 }, - { 10, 21, 7, 4, 6, 2 }, - { 16, 34, 17, 11, 25, 12 }, - { 15, 30, 15, 8, 16, 8 }, - { 13, 27, 13, 10, 20, 10 }, - { 9, 20, 9, 0, 1, 0 }, - { 16, 32, 15, 2, 4, 2 }, - { 13, 27, 12, 3, 6, 3 }, - { 13, 26, 12, 12, 23, 11 }, - { 12, 25, 12, 5, 11, 5 }, - { 11, 23, 11, 5, 11, 5 }, - { 16, 34, 16, 7, 13, 6 }, - { 16, 35, 31, 15, 25, 31 }, - { 16, 33, 16, 7, 16, 7 }, - { 13, 26, 13, 8, 19, 8 }, - { 18, 35, 17, 11, 23, 10 }, - { 18, 36, 18, 13, 28, 13 }, - { 12, 25, 12, 4, 9, 4 }, - { 9, 18, 7, 6, 11, 4 }, - { 15, 30, 14, 9, 20, 9 }, - { 17, 35, 16, 9, 19, 9 }, - { 11, 24, 11, 2, 4, 2 }, - { 16, 33, 16, 0, 1, 0 }, - { 15, 31, 15, 4, 9, 4 }, - { 16, 31, 15, 14, 27, 13 }, - { 14, 29, 14, 13, 25, 12 }, - { 11, 23, 11, 3, 6, 3 }, - { 16, 32, 16, 10, 22, 10 }, - { 11, 22, 11, 4, 9, 4 }, - { 11, 22, 10, 1, 2, 0 }, - { 8, 14, 5, 2, 4, 1 }, - { 9, 16, 6, 6, 10, 4 }, - { 10, 21, 10, 9, 19, 9 }, - { 14, 29, 14, 11, 23, 11 }, - { 9, 18, 8, 6, 13, 6 }, - { 6, 13, 6, 5, 11, 5 }, - { 7, 14, 6, 0, 1, 0 }, - { 4, 7, 2, 3, 4, 1 }, - { 10, 20, 9, 4, 8, 4 }, - { 9, 17, 7, 5, 9, 3 }, - { 7, 14, 7, 1, 2, 1 }, - { 10, 20, 10, 6, 11, 5 }, - { 8, 15, 5, 4, 6, 2 }, - { 8, 17, 8, 1, 2, 1 }, - { 10, 20, 10, 3, 6, 3 }, - { 7, 10, 3, 6, 8, 3 }, - { 8, 15, 7, 6, 12, 6 }, - { 9, 19, 9, 2, 4, 2 }, - { 6, 11, 4, 3, 4, 1 }, - { 6, 11, 4, 0, 1, 0 }, - { 8, 16, 7, 2, 5, 2 }, - { 16, 34, 16, 15, 29, 15 }, - { 7, 16, 7, 5, 10, 5 }, - { 8, 14, 5, 5, 9, 3 }, - { 9, 18, 8, 4, 8, 4 }, - { 5, 9, 3, 4, 7, 2 }, - { 9, 18, 8, 5, 10, 5 }, - { 6, 12, 6, 2, 4, 2 }, - { 7, 12, 5, 4, 7, 3 }, - { 5, 11, 5, 1, 2, 1 }, - { 8, 17, 8, 3, 6, 3 }, - { 16, 31, 31, 16, 32, 31 }, - { 7, 14, 7, 3, 6, 3 }, - { 5, 11, 6, 4, 9, 4 }, - { 7, 15, 7, 4, 8, 4 }, - { 2, 4, 2, 0, 0, 1 }, - { 5, 11, 5, 3, 6, 3 }, - { 4, 8, 4, 1, 1, 1 }, - { 3, 6, 3, 1, 2, 1 }, - { 2, 4, 1, 1, 2, 1 }, - { 4, 8, 4, 3, 6, 3 }, - { 3, 6, 3, 2, 4, 2 }, - { 4, 9, 4, 2, 4, 2 }, - { 17, 27, 31, 15, 34, 31 }, - { 0, 0, 1, 0, 0, 0 }, -}; - -inline constexpr uint32_t BC1_QUAD_MASKS[4][256] = { - { - 0x00000a0au, 0x00000f0fu, 0x00000000u, 0x00000505u, 0x00000f0au, 0x00000a0fu, 0x00000f0bu, 0x00000b0fu, - 0x00000f0eu, 0x00000e0fu, 0x00000b0bu, 0x00000e0eu, 0x00000d0fu, 0x00000b0au, 0x0000050au, 0x00000a0eu, - 0x0000070fu, 0x00000e0au, 0x00000a0bu, 0x00000f07u, 0x00000f0du, 0x00000a05u, 0x0000050fu, 0x00000f05u, - 0x00000d0du, 0x00000707u, 0x00000606u, 0x00000909u, 0x0000020au, 0x0000080au, 0x00000a02u, 0x00000500u, - 0x00000005u, 0x00000a08u, 0x00000101u, 0x0000090au, 0x00000404u, 0x0000030fu, 0x00000a06u, 0x00000a09u, - 0x00000c0fu, 0x00000b0eu, 0x00000f0cu, 0x00000f03u, 0x0000060au, 0x00000e0bu, 0x0000070eu, 0x00000e07u, - 0x00000d0bu, 0x00000b0du, 0x0000070au, 0x00000a07u, 0x00000d0au, 0x0000000fu, 0x00000a0du, 0x00000507u, - 0x00000d05u, 0x0000000au, 0x0000050du, 0x00000705u, 0x0000020fu, 0x0000060eu, 0x00000f00u, 0x0000080fu, - 0x00000f08u, 0x00000e06u, 0x0000030du, 0x00000f02u, 0x00000b09u, 0x00000205u, 0x0000070cu, 0x0000090bu, - 0x0000030bu, 0x00000805u, 0x00000c0eu, 0x00000e0cu, 0x00000508u, 0x00000b03u, 0x00000d03u, 0x00000a00u, - 0x00000502u, 0x00000d0eu, 0x0000070bu, 0x0000020bu, 0x00000b07u, 0x0000050eu, 0x00000c07u, 0x00000e0du, - 0x0000050bu, 0x00000b02u, 0x0000080eu, 0x00000c0cu, 0x0000060fu, 0x00000109u, 0x00000f06u, 0x0000090fu, - 0x00000604u, 0x00000e08u, 0x00000e05u, 0x00000209u, 0x00000f09u, 0x00000303u, 0x00000406u, 0x00000202u, - 0x00000b05u, 0x00000d07u, 0x0000020du, 0x00000708u, 0x00000506u, 0x00000806u, 0x00000808u, 0x00000608u, - 0x00000901u, 0x00000905u, 0x00000902u, 0x00000d02u, 0x00000807u, 0x0000070du, 0x00000706u, 0x00000607u, - 0x0000090du, 0x00000509u, 0x00000605u, 0x00000d09u, 0x00000105u, 0x00000307u, 0x00000903u, 0x0000050cu, - 0x00000c06u, 0x00000305u, 0x0000060cu, 0x00000c0du, 0x00000309u, 0x00000405u, 0x00000d0cu, 0x00000504u, - 0x00000703u, 0x00000501u, 0x00000503u, 0x00000c05u, 0x0000020eu, 0x0000080bu, 0x0000080du, 0x00000207u, - 0x00000e02u, 0x0000010fu, 0x00000f04u, 0x0000010du, 0x00000d08u, 0x00000f01u, 0x00000702u, 0x00000a03u, - 0x0000040fu, 0x00000704u, 0x00000b08u, 0x00000c0au, 0x0000030au, 0x00000a0cu, 0x00000d01u, 0x00000809u, - 0x00000407u, 0x00000206u, 0x00000602u, 0x00000908u, 0x00000700u, 0x0000000du, 0x00000a01u, 0x0000010au, - 0x0000040au, 0x0000060bu, 0x0000010bu, 0x00000d00u, 0x00000a04u, 0x00000e09u, 0x00000007u, 0x00000b01u, - 0x0000090eu, 0x00000b06u, 0x00000e04u, 0x0000040eu, 0x00000b0cu, 0x00000e03u, 0x0000030eu, 0x00000c0bu, - 0x00000802u, 0x00000301u, 0x00000002u, 0x00000208u, 0x0000040cu, 0x00000103u, 0x00000c04u, 0x00000200u, - 0x0000000eu, 0x0000000bu, 0x00000008u, 0x00000906u, 0x00000800u, 0x00000e00u, 0x00000009u, 0x00000b00u, - 0x00000609u, 0x00000600u, 0x00000006u, 0x00000900u, 0x00000203u, 0x00000907u, 0x0000080cu, 0x00000d06u, - 0x00000201u, 0x0000060du, 0x00000709u, 0x00000302u, 0x00000c08u, 0x00000408u, 0x00000804u, 0x00000107u, - 0x00000102u, 0x00000d04u, 0x0000040du, 0x00000701u, 0x00000001u, 0x00000306u, 0x00000603u, 0x0000090cu, - 0x00000c09u, 0x00000400u, 0x00000004u, 0x00000100u, 0x00000e01u, 0x00000601u, 0x00000904u, 0x00000409u, - 0x0000040bu, 0x0000010eu, 0x00000b04u, 0x00000106u, 0x00000003u, 0x0000000cu, 0x00000c00u, 0x00000402u, - 0x00000801u, 0x00000108u, 0x00000300u, 0x00000204u, 0x00000c03u, 0x0000030cu, 0x00000c02u, 0x00000104u, - 0x00000401u, 0x00000803u, 0x0000020cu, 0x00000308u, 0x00000403u, 0x00000304u, 0x0000010cu, 0x00000c01u, - }, - { - 0x0000a0a0u, 0x0000f0f0u, 0x00000000u, 0x00005050u, 0x0000f0a0u, 0x0000a0f0u, 0x0000f0b0u, 0x0000b0f0u, - 0x0000f0e0u, 0x0000e0f0u, 0x0000b0b0u, 0x0000e0e0u, 0x0000d0f0u, 0x0000b0a0u, 0x000050a0u, 0x0000a0e0u, - 0x000070f0u, 0x0000e0a0u, 0x0000a0b0u, 0x0000f070u, 0x0000f0d0u, 0x0000a050u, 0x000050f0u, 0x0000f050u, - 0x0000d0d0u, 0x00007070u, 0x00006060u, 0x00009090u, 0x000020a0u, 0x000080a0u, 0x0000a020u, 0x00005000u, - 0x00000050u, 0x0000a080u, 0x00001010u, 0x000090a0u, 0x00004040u, 0x000030f0u, 0x0000a060u, 0x0000a090u, - 0x0000c0f0u, 0x0000b0e0u, 0x0000f0c0u, 0x0000f030u, 0x000060a0u, 0x0000e0b0u, 0x000070e0u, 0x0000e070u, - 0x0000d0b0u, 0x0000b0d0u, 0x000070a0u, 0x0000a070u, 0x0000d0a0u, 0x000000f0u, 0x0000a0d0u, 0x00005070u, - 0x0000d050u, 0x000000a0u, 0x000050d0u, 0x00007050u, 0x000020f0u, 0x000060e0u, 0x0000f000u, 0x000080f0u, - 0x0000f080u, 0x0000e060u, 0x000030d0u, 0x0000f020u, 0x0000b090u, 0x00002050u, 0x000070c0u, 0x000090b0u, - 0x000030b0u, 0x00008050u, 0x0000c0e0u, 0x0000e0c0u, 0x00005080u, 0x0000b030u, 0x0000d030u, 0x0000a000u, - 0x00005020u, 0x0000d0e0u, 0x000070b0u, 0x000020b0u, 0x0000b070u, 0x000050e0u, 0x0000c070u, 0x0000e0d0u, - 0x000050b0u, 0x0000b020u, 0x000080e0u, 0x0000c0c0u, 0x000060f0u, 0x00001090u, 0x0000f060u, 0x000090f0u, - 0x00006040u, 0x0000e080u, 0x0000e050u, 0x00002090u, 0x0000f090u, 0x00003030u, 0x00004060u, 0x00002020u, - 0x0000b050u, 0x0000d070u, 0x000020d0u, 0x00007080u, 0x00005060u, 0x00008060u, 0x00008080u, 0x00006080u, - 0x00009010u, 0x00009050u, 0x00009020u, 0x0000d020u, 0x00008070u, 0x000070d0u, 0x00007060u, 0x00006070u, - 0x000090d0u, 0x00005090u, 0x00006050u, 0x0000d090u, 0x00001050u, 0x00003070u, 0x00009030u, 0x000050c0u, - 0x0000c060u, 0x00003050u, 0x000060c0u, 0x0000c0d0u, 0x00003090u, 0x00004050u, 0x0000d0c0u, 0x00005040u, - 0x00007030u, 0x00005010u, 0x00005030u, 0x0000c050u, 0x000020e0u, 0x000080b0u, 0x000080d0u, 0x00002070u, - 0x0000e020u, 0x000010f0u, 0x0000f040u, 0x000010d0u, 0x0000d080u, 0x0000f010u, 0x00007020u, 0x0000a030u, - 0x000040f0u, 0x00007040u, 0x0000b080u, 0x0000c0a0u, 0x000030a0u, 0x0000a0c0u, 0x0000d010u, 0x00008090u, - 0x00004070u, 0x00002060u, 0x00006020u, 0x00009080u, 0x00007000u, 0x000000d0u, 0x0000a010u, 0x000010a0u, - 0x000040a0u, 0x000060b0u, 0x000010b0u, 0x0000d000u, 0x0000a040u, 0x0000e090u, 0x00000070u, 0x0000b010u, - 0x000090e0u, 0x0000b060u, 0x0000e040u, 0x000040e0u, 0x0000b0c0u, 0x0000e030u, 0x000030e0u, 0x0000c0b0u, - 0x00008020u, 0x00003010u, 0x00000020u, 0x00002080u, 0x000040c0u, 0x00001030u, 0x0000c040u, 0x00002000u, - 0x000000e0u, 0x000000b0u, 0x00000080u, 0x00009060u, 0x00008000u, 0x0000e000u, 0x00000090u, 0x0000b000u, - 0x00006090u, 0x00006000u, 0x00000060u, 0x00009000u, 0x00002030u, 0x00009070u, 0x000080c0u, 0x0000d060u, - 0x00002010u, 0x000060d0u, 0x00007090u, 0x00003020u, 0x0000c080u, 0x00004080u, 0x00008040u, 0x00001070u, - 0x00001020u, 0x0000d040u, 0x000040d0u, 0x00007010u, 0x00000010u, 0x00003060u, 0x00006030u, 0x000090c0u, - 0x0000c090u, 0x00004000u, 0x00000040u, 0x00001000u, 0x0000e010u, 0x00006010u, 0x00009040u, 0x00004090u, - 0x000040b0u, 0x000010e0u, 0x0000b040u, 0x00001060u, 0x00000030u, 0x000000c0u, 0x0000c000u, 0x00004020u, - 0x00008010u, 0x00001080u, 0x00003000u, 0x00002040u, 0x0000c030u, 0x000030c0u, 0x0000c020u, 0x00001040u, - 0x00004010u, 0x00008030u, 0x000020c0u, 0x00003080u, 0x00004030u, 0x00003040u, 0x000010c0u, 0x0000c010u, - }, - { - 0x0a0a0000u, 0x0f0f0000u, 0x00000000u, 0x05050000u, 0x0f0a0000u, 0x0a0f0000u, 0x0f0b0000u, 0x0b0f0000u, - 0x0f0e0000u, 0x0e0f0000u, 0x0b0b0000u, 0x0e0e0000u, 0x0d0f0000u, 0x0b0a0000u, 0x050a0000u, 0x0a0e0000u, - 0x070f0000u, 0x0e0a0000u, 0x0a0b0000u, 0x0f070000u, 0x0f0d0000u, 0x0a050000u, 0x050f0000u, 0x0f050000u, - 0x0d0d0000u, 0x07070000u, 0x06060000u, 0x09090000u, 0x020a0000u, 0x080a0000u, 0x0a020000u, 0x05000000u, - 0x00050000u, 0x0a080000u, 0x01010000u, 0x090a0000u, 0x04040000u, 0x030f0000u, 0x0a060000u, 0x0a090000u, - 0x0c0f0000u, 0x0b0e0000u, 0x0f0c0000u, 0x0f030000u, 0x060a0000u, 0x0e0b0000u, 0x070e0000u, 0x0e070000u, - 0x0d0b0000u, 0x0b0d0000u, 0x070a0000u, 0x0a070000u, 0x0d0a0000u, 0x000f0000u, 0x0a0d0000u, 0x05070000u, - 0x0d050000u, 0x000a0000u, 0x050d0000u, 0x07050000u, 0x020f0000u, 0x060e0000u, 0x0f000000u, 0x080f0000u, - 0x0f080000u, 0x0e060000u, 0x030d0000u, 0x0f020000u, 0x0b090000u, 0x02050000u, 0x070c0000u, 0x090b0000u, - 0x030b0000u, 0x08050000u, 0x0c0e0000u, 0x0e0c0000u, 0x05080000u, 0x0b030000u, 0x0d030000u, 0x0a000000u, - 0x05020000u, 0x0d0e0000u, 0x070b0000u, 0x020b0000u, 0x0b070000u, 0x050e0000u, 0x0c070000u, 0x0e0d0000u, - 0x050b0000u, 0x0b020000u, 0x080e0000u, 0x0c0c0000u, 0x060f0000u, 0x01090000u, 0x0f060000u, 0x090f0000u, - 0x06040000u, 0x0e080000u, 0x0e050000u, 0x02090000u, 0x0f090000u, 0x03030000u, 0x04060000u, 0x02020000u, - 0x0b050000u, 0x0d070000u, 0x020d0000u, 0x07080000u, 0x05060000u, 0x08060000u, 0x08080000u, 0x06080000u, - 0x09010000u, 0x09050000u, 0x09020000u, 0x0d020000u, 0x08070000u, 0x070d0000u, 0x07060000u, 0x06070000u, - 0x090d0000u, 0x05090000u, 0x06050000u, 0x0d090000u, 0x01050000u, 0x03070000u, 0x09030000u, 0x050c0000u, - 0x0c060000u, 0x03050000u, 0x060c0000u, 0x0c0d0000u, 0x03090000u, 0x04050000u, 0x0d0c0000u, 0x05040000u, - 0x07030000u, 0x05010000u, 0x05030000u, 0x0c050000u, 0x020e0000u, 0x080b0000u, 0x080d0000u, 0x02070000u, - 0x0e020000u, 0x010f0000u, 0x0f040000u, 0x010d0000u, 0x0d080000u, 0x0f010000u, 0x07020000u, 0x0a030000u, - 0x040f0000u, 0x07040000u, 0x0b080000u, 0x0c0a0000u, 0x030a0000u, 0x0a0c0000u, 0x0d010000u, 0x08090000u, - 0x04070000u, 0x02060000u, 0x06020000u, 0x09080000u, 0x07000000u, 0x000d0000u, 0x0a010000u, 0x010a0000u, - 0x040a0000u, 0x060b0000u, 0x010b0000u, 0x0d000000u, 0x0a040000u, 0x0e090000u, 0x00070000u, 0x0b010000u, - 0x090e0000u, 0x0b060000u, 0x0e040000u, 0x040e0000u, 0x0b0c0000u, 0x0e030000u, 0x030e0000u, 0x0c0b0000u, - 0x08020000u, 0x03010000u, 0x00020000u, 0x02080000u, 0x040c0000u, 0x01030000u, 0x0c040000u, 0x02000000u, - 0x000e0000u, 0x000b0000u, 0x00080000u, 0x09060000u, 0x08000000u, 0x0e000000u, 0x00090000u, 0x0b000000u, - 0x06090000u, 0x06000000u, 0x00060000u, 0x09000000u, 0x02030000u, 0x09070000u, 0x080c0000u, 0x0d060000u, - 0x02010000u, 0x060d0000u, 0x07090000u, 0x03020000u, 0x0c080000u, 0x04080000u, 0x08040000u, 0x01070000u, - 0x01020000u, 0x0d040000u, 0x040d0000u, 0x07010000u, 0x00010000u, 0x03060000u, 0x06030000u, 0x090c0000u, - 0x0c090000u, 0x04000000u, 0x00040000u, 0x01000000u, 0x0e010000u, 0x06010000u, 0x09040000u, 0x04090000u, - 0x040b0000u, 0x010e0000u, 0x0b040000u, 0x01060000u, 0x00030000u, 0x000c0000u, 0x0c000000u, 0x04020000u, - 0x08010000u, 0x01080000u, 0x03000000u, 0x02040000u, 0x0c030000u, 0x030c0000u, 0x0c020000u, 0x01040000u, - 0x04010000u, 0x08030000u, 0x020c0000u, 0x03080000u, 0x04030000u, 0x03040000u, 0x010c0000u, 0x0c010000u, - }, - { - 0xa0a00000u, 0xf0f00000u, 0x00000000u, 0x50500000u, 0xf0a00000u, 0xa0f00000u, 0xf0b00000u, 0xb0f00000u, - 0xf0e00000u, 0xe0f00000u, 0xb0b00000u, 0xe0e00000u, 0xd0f00000u, 0xb0a00000u, 0x50a00000u, 0xa0e00000u, - 0x70f00000u, 0xe0a00000u, 0xa0b00000u, 0xf0700000u, 0xf0d00000u, 0xa0500000u, 0x50f00000u, 0xf0500000u, - 0xd0d00000u, 0x70700000u, 0x60600000u, 0x90900000u, 0x20a00000u, 0x80a00000u, 0xa0200000u, 0x50000000u, - 0x00500000u, 0xa0800000u, 0x10100000u, 0x90a00000u, 0x40400000u, 0x30f00000u, 0xa0600000u, 0xa0900000u, - 0xc0f00000u, 0xb0e00000u, 0xf0c00000u, 0xf0300000u, 0x60a00000u, 0xe0b00000u, 0x70e00000u, 0xe0700000u, - 0xd0b00000u, 0xb0d00000u, 0x70a00000u, 0xa0700000u, 0xd0a00000u, 0x00f00000u, 0xa0d00000u, 0x50700000u, - 0xd0500000u, 0x00a00000u, 0x50d00000u, 0x70500000u, 0x20f00000u, 0x60e00000u, 0xf0000000u, 0x80f00000u, - 0xf0800000u, 0xe0600000u, 0x30d00000u, 0xf0200000u, 0xb0900000u, 0x20500000u, 0x70c00000u, 0x90b00000u, - 0x30b00000u, 0x80500000u, 0xc0e00000u, 0xe0c00000u, 0x50800000u, 0xb0300000u, 0xd0300000u, 0xa0000000u, - 0x50200000u, 0xd0e00000u, 0x70b00000u, 0x20b00000u, 0xb0700000u, 0x50e00000u, 0xc0700000u, 0xe0d00000u, - 0x50b00000u, 0xb0200000u, 0x80e00000u, 0xc0c00000u, 0x60f00000u, 0x10900000u, 0xf0600000u, 0x90f00000u, - 0x60400000u, 0xe0800000u, 0xe0500000u, 0x20900000u, 0xf0900000u, 0x30300000u, 0x40600000u, 0x20200000u, - 0xb0500000u, 0xd0700000u, 0x20d00000u, 0x70800000u, 0x50600000u, 0x80600000u, 0x80800000u, 0x60800000u, - 0x90100000u, 0x90500000u, 0x90200000u, 0xd0200000u, 0x80700000u, 0x70d00000u, 0x70600000u, 0x60700000u, - 0x90d00000u, 0x50900000u, 0x60500000u, 0xd0900000u, 0x10500000u, 0x30700000u, 0x90300000u, 0x50c00000u, - 0xc0600000u, 0x30500000u, 0x60c00000u, 0xc0d00000u, 0x30900000u, 0x40500000u, 0xd0c00000u, 0x50400000u, - 0x70300000u, 0x50100000u, 0x50300000u, 0xc0500000u, 0x20e00000u, 0x80b00000u, 0x80d00000u, 0x20700000u, - 0xe0200000u, 0x10f00000u, 0xf0400000u, 0x10d00000u, 0xd0800000u, 0xf0100000u, 0x70200000u, 0xa0300000u, - 0x40f00000u, 0x70400000u, 0xb0800000u, 0xc0a00000u, 0x30a00000u, 0xa0c00000u, 0xd0100000u, 0x80900000u, - 0x40700000u, 0x20600000u, 0x60200000u, 0x90800000u, 0x70000000u, 0x00d00000u, 0xa0100000u, 0x10a00000u, - 0x40a00000u, 0x60b00000u, 0x10b00000u, 0xd0000000u, 0xa0400000u, 0xe0900000u, 0x00700000u, 0xb0100000u, - 0x90e00000u, 0xb0600000u, 0xe0400000u, 0x40e00000u, 0xb0c00000u, 0xe0300000u, 0x30e00000u, 0xc0b00000u, - 0x80200000u, 0x30100000u, 0x00200000u, 0x20800000u, 0x40c00000u, 0x10300000u, 0xc0400000u, 0x20000000u, - 0x00e00000u, 0x00b00000u, 0x00800000u, 0x90600000u, 0x80000000u, 0xe0000000u, 0x00900000u, 0xb0000000u, - 0x60900000u, 0x60000000u, 0x00600000u, 0x90000000u, 0x20300000u, 0x90700000u, 0x80c00000u, 0xd0600000u, - 0x20100000u, 0x60d00000u, 0x70900000u, 0x30200000u, 0xc0800000u, 0x40800000u, 0x80400000u, 0x10700000u, - 0x10200000u, 0xd0400000u, 0x40d00000u, 0x70100000u, 0x00100000u, 0x30600000u, 0x60300000u, 0x90c00000u, - 0xc0900000u, 0x40000000u, 0x00400000u, 0x10000000u, 0xe0100000u, 0x60100000u, 0x90400000u, 0x40900000u, - 0x40b00000u, 0x10e00000u, 0xb0400000u, 0x10600000u, 0x00300000u, 0x00c00000u, 0xc0000000u, 0x40200000u, - 0x80100000u, 0x10800000u, 0x30000000u, 0x20400000u, 0xc0300000u, 0x30c00000u, 0xc0200000u, 0x10400000u, - 0x40100000u, 0x80300000u, 0x20c00000u, 0x30800000u, 0x40300000u, 0x30400000u, 0x10c00000u, 0xc0100000u, - }, -}; - #include "bcpack_tables_bcn.inl" +#include "bcpack_tables_extra.inl" } // namespace x2w_bcpack diff --git a/src/startup_stubs/bcpack_tables_extra.inl b/src/startup_stubs/bcpack_tables_extra.inl new file mode 100644 index 0000000000..6fcce900d0 --- /dev/null +++ b/src/startup_stubs/bcpack_tables_extra.inl @@ -0,0 +1,1470 @@ +// BCPack format constants reconstructed with synthetic lane streams. +// No SDK binaries or title data are embedded. See docs/experiments/bcpack-standalone.md. +// BC6H wire descriptors adapt the MIT-licensed Microsoft DirectXTex BC6HBC7.cpp. +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: MIT + +struct Bc1FullState { uint8_t ep[6]; uint8_t ix[16]; }; +struct Bc2State { uint8_t alpha[16]; uint8_t ep[6]; uint8_t ix[16]; }; +struct Bc6State { uint16_t ep[4][3]; uint16_t ix[16]; }; +struct Bc6WireBit { uint8_t field; uint8_t bit; }; + +inline constexpr uint8_t BC1_POSITION_RANK[256][4] = { + { 1, 1, 1, 1 }, + { 2, 2, 2, 2 }, + { 0, 0, 0, 0 }, + { 3, 3, 3, 3 }, + { 1, 1, 2, 2 }, + { 2, 2, 1, 1 }, + { 2, 1, 2, 2 }, + { 2, 2, 2, 1 }, + { 1, 2, 2, 2 }, + { 2, 2, 1, 2 }, + { 2, 1, 2, 1 }, + { 1, 2, 1, 2 }, + { 2, 2, 3, 2 }, + { 1, 1, 2, 1 }, + { 1, 1, 3, 3 }, + { 1, 2, 1, 1 }, + { 2, 2, 2, 3 }, + { 1, 1, 1, 2 }, + { 2, 1, 1, 1 }, + { 2, 3, 2, 2 }, + { 3, 2, 2, 2 }, + { 3, 3, 1, 1 }, + { 2, 2, 3, 3 }, + { 3, 3, 2, 2 }, + { 3, 2, 3, 2 }, + { 2, 3, 2, 3 }, + { 1, 3, 1, 3 }, + { 3, 1, 3, 1 }, + { 1, 1, 1, 0 }, + { 1, 1, 0, 1 }, + { 1, 0, 1, 1 }, + { 0, 0, 3, 3 }, + { 3, 3, 0, 0 }, + { 0, 1, 1, 1 }, + { 3, 0, 3, 0 }, + { 1, 1, 3, 1 }, + { 0, 3, 0, 3 }, + { 2, 2, 2, 0 }, + { 1, 3, 1, 1 }, + { 3, 1, 1, 1 }, + { 2, 2, 0, 2 }, + { 1, 2, 2, 1 }, + { 0, 2, 2, 2 }, + { 2, 0, 2, 2 }, + { 1, 1, 1, 3 }, + { 2, 1, 1, 2 }, + { 1, 2, 2, 3 }, + { 2, 3, 1, 2 }, + { 2, 1, 3, 2 }, + { 3, 2, 2, 1 }, + { 1, 1, 2, 3 }, + { 2, 3, 1, 1 }, + { 1, 1, 3, 2 }, + { 2, 2, 0, 0 }, + { 3, 2, 1, 1 }, + { 2, 3, 3, 3 }, + { 3, 3, 3, 2 }, + { 1, 1, 0, 0 }, + { 3, 2, 3, 3 }, + { 3, 3, 2, 3 }, + { 2, 2, 1, 0 }, + { 1, 2, 1, 3 }, + { 0, 0, 2, 2 }, + { 2, 2, 0, 1 }, + { 0, 1, 2, 2 }, + { 1, 3, 1, 2 }, + { 3, 2, 2, 0 }, + { 1, 0, 2, 2 }, + { 3, 1, 2, 1 }, + { 3, 3, 1, 0 }, + { 0, 2, 2, 3 }, + { 2, 1, 3, 1 }, + { 2, 1, 2, 0 }, + { 3, 3, 0, 1 }, + { 1, 2, 0, 2 }, + { 0, 2, 1, 2 }, + { 0, 1, 3, 3 }, + { 2, 0, 2, 1 }, + { 2, 0, 3, 2 }, + { 0, 0, 1, 1 }, + { 1, 0, 3, 3 }, + { 1, 2, 3, 2 }, + { 2, 1, 2, 3 }, + { 2, 1, 1, 0 }, + { 2, 3, 2, 1 }, + { 1, 2, 3, 3 }, + { 2, 3, 0, 2 }, + { 3, 2, 1, 2 }, + { 2, 1, 3, 3 }, + { 1, 0, 2, 1 }, + { 1, 2, 0, 1 }, + { 0, 2, 0, 2 }, + { 2, 2, 1, 3 }, + { 3, 1, 3, 0 }, + { 1, 3, 2, 2 }, + { 2, 2, 3, 1 }, + { 0, 3, 1, 3 }, + { 0, 1, 1, 2 }, + { 3, 3, 1, 2 }, + { 3, 1, 1, 0 }, + { 3, 1, 2, 2 }, + { 2, 0, 2, 0 }, + { 1, 3, 0, 3 }, + { 1, 0, 1, 0 }, + { 3, 3, 2, 1 }, + { 2, 3, 3, 2 }, + { 3, 2, 1, 0 }, + { 0, 1, 2, 3 }, + { 1, 3, 3, 3 }, + { 1, 3, 0, 1 }, + { 0, 1, 0, 1 }, + { 0, 1, 1, 3 }, + { 3, 0, 3, 1 }, + { 3, 3, 3, 1 }, + { 1, 0, 3, 1 }, + { 1, 0, 3, 2 }, + { 2, 3, 0, 1 }, + { 3, 2, 2, 3 }, + { 1, 3, 2, 3 }, + { 2, 3, 1, 3 }, + { 3, 2, 3, 1 }, + { 3, 1, 3, 3 }, + { 3, 3, 1, 3 }, + { 3, 1, 3, 2 }, + { 3, 3, 3, 0 }, + { 2, 3, 2, 0 }, + { 2, 0, 3, 1 }, + { 0, 2, 3, 3 }, + { 1, 3, 0, 2 }, + { 3, 3, 2, 0 }, + { 0, 2, 1, 3 }, + { 3, 2, 0, 2 }, + { 3, 1, 2, 0 }, + { 3, 3, 0, 3 }, + { 0, 2, 3, 2 }, + { 0, 3, 3, 3 }, + { 2, 0, 2, 3 }, + { 3, 0, 3, 3 }, + { 2, 0, 3, 3 }, + { 3, 3, 0, 2 }, + { 1, 2, 1, 0 }, + { 2, 1, 0, 1 }, + { 3, 2, 0, 1 }, + { 2, 3, 1, 0 }, + { 1, 0, 1, 2 }, + { 2, 2, 3, 0 }, + { 0, 3, 2, 2 }, + { 3, 2, 3, 0 }, + { 0, 1, 3, 2 }, + { 3, 0, 2, 2 }, + { 1, 0, 2, 3 }, + { 2, 0, 1, 1 }, + { 2, 2, 0, 3 }, + { 0, 3, 2, 3 }, + { 0, 1, 2, 1 }, + { 1, 1, 0, 2 }, + { 1, 1, 2, 0 }, + { 0, 2, 1, 1 }, + { 3, 0, 3, 2 }, + { 3, 1, 0, 1 }, + { 2, 3, 0, 3 }, + { 1, 3, 1, 0 }, + { 1, 0, 1, 3 }, + { 0, 1, 3, 1 }, + { 0, 0, 2, 3 }, + { 3, 2, 0, 0 }, + { 3, 0, 1, 1 }, + { 1, 1, 3, 0 }, + { 1, 1, 0, 3 }, + { 2, 1, 1, 3 }, + { 2, 1, 3, 0 }, + { 0, 0, 3, 2 }, + { 0, 3, 1, 1 }, + { 3, 1, 1, 2 }, + { 2, 3, 0, 0 }, + { 3, 0, 2, 1 }, + { 1, 2, 3, 1 }, + { 1, 3, 2, 1 }, + { 0, 3, 1, 2 }, + { 1, 2, 0, 3 }, + { 0, 2, 2, 1 }, + { 2, 0, 1, 2 }, + { 1, 2, 2, 0 }, + { 2, 1, 0, 2 }, + { 1, 0, 0, 1 }, + { 3, 0, 2, 0 }, + { 1, 0, 0, 0 }, + { 0, 1, 1, 0 }, + { 0, 2, 0, 3 }, + { 2, 0, 3, 0 }, + { 0, 3, 0, 2 }, + { 0, 0, 1, 0 }, + { 1, 2, 0, 0 }, + { 2, 1, 0, 0 }, + { 0, 1, 0, 0 }, + { 1, 3, 3, 1 }, + { 0, 0, 0, 1 }, + { 0, 0, 1, 2 }, + { 3, 1, 0, 0 }, + { 0, 0, 2, 1 }, + { 3, 1, 1, 3 }, + { 0, 0, 1, 3 }, + { 1, 3, 0, 0 }, + { 0, 0, 3, 1 }, + { 2, 0, 1, 0 }, + { 2, 3, 3, 1 }, + { 0, 2, 0, 1 }, + { 1, 3, 3, 2 }, + { 3, 0, 1, 0 }, + { 3, 2, 1, 3 }, + { 3, 1, 2, 3 }, + { 1, 0, 2, 0 }, + { 0, 1, 0, 2 }, + { 0, 1, 0, 3 }, + { 0, 3, 0, 1 }, + { 2, 3, 3, 0 }, + { 1, 0, 3, 0 }, + { 0, 3, 3, 2 }, + { 3, 2, 0, 3 }, + { 3, 0, 2, 3 }, + { 3, 0, 0, 0 }, + { 1, 3, 2, 0 }, + { 2, 0, 1, 3 }, + { 0, 2, 3, 1 }, + { 3, 1, 0, 2 }, + { 0, 0, 0, 3 }, + { 0, 3, 0, 0 }, + { 0, 0, 3, 0 }, + { 3, 0, 1, 2 }, + { 1, 3, 3, 0 }, + { 0, 3, 3, 1 }, + { 3, 1, 0, 3 }, + { 2, 1, 0, 3 }, + { 1, 2, 3, 0 }, + { 0, 3, 2, 1 }, + { 3, 0, 1, 3 }, + { 2, 0, 0, 0 }, + { 0, 2, 0, 0 }, + { 0, 0, 0, 2 }, + { 1, 0, 0, 3 }, + { 3, 0, 0, 1 }, + { 0, 1, 3, 0 }, + { 0, 0, 2, 0 }, + { 0, 3, 1, 0 }, + { 2, 0, 0, 2 }, + { 0, 2, 2, 0 }, + { 1, 0, 0, 2 }, + { 3, 0, 0, 3 }, + { 0, 3, 3, 0 }, + { 2, 0, 0, 1 }, + { 0, 2, 1, 0 }, + { 0, 1, 2, 0 }, + { 2, 0, 0, 3 }, + { 0, 3, 2, 0 }, + { 0, 2, 3, 0 }, + { 3, 0, 0, 2 }, +}; + +inline constexpr Bc1FullState BC1_FULL_DICTIONARY[255] = { + { { 0, 0, 1, 0, 0, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 17, 27, 31, 15, 34, 31 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 4, 9, 4, 2, 4, 2 }, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { { 3, 6, 3, 2, 4, 2 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 4, 8, 4, 3, 6, 3 }, { 1, 0, 3, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 1, 0, 0 } }, + { { 2, 4, 1, 1, 2, 1 }, { 1, 0, 3, 3, 1, 1, 0, 3, 1, 1, 1, 1, 0, 1, 1, 1 } }, + { { 3, 6, 3, 1, 2, 1 }, { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 4, 8, 4, 1, 1, 1 }, { 3, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 } }, + { { 5, 11, 5, 3, 6, 3 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 2, 3, 3, 2, 2, 3 } }, + { { 2, 4, 2, 0, 0, 1 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 7, 15, 7, 4, 8, 4 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1 } }, + { { 5, 11, 6, 4, 9, 4 }, { 3, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 7, 14, 7, 3, 6, 3 }, { 3, 0, 0, 3, 0, 0, 0, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 16, 31, 31, 16, 32, 31 }, { 3, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 8, 17, 8, 3, 6, 3 }, { 0, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 5, 11, 5, 1, 2, 1 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 2, 2, 3, 3, 2, 2, 3 } }, + { { 7, 12, 5, 4, 7, 3 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 6, 12, 6, 2, 4, 2 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 9, 18, 8, 5, 10, 5 }, { 1, 1, 0, 3, 1, 1, 0, 3, 0, 1, 0, 3, 3, 0, 0, 3 } }, + { { 5, 9, 3, 4, 7, 2 }, { 0, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 9, 18, 8, 4, 8, 4 }, { 3, 2, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1, 3, 0, 0, 0 } }, + { { 8, 14, 5, 5, 9, 3 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 0, 0 } }, + { { 7, 16, 7, 5, 10, 5 }, { 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 16, 34, 16, 15, 29, 15 }, { 3, 3, 2, 3, 0, 0, 3, 3, 1, 1, 0, 3, 0, 0, 0, 0 } }, + { { 8, 16, 7, 2, 4, 2 }, { 3, 2, 2, 3, 3, 3, 2, 3, 0, 3, 3, 3, 1, 0, 0, 3 } }, + { { 6, 11, 4, 0, 1, 0 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 1, 0, 0, 3 } }, + { { 6, 11, 4, 3, 4, 1 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 9, 19, 9, 2, 4, 2 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0 } }, + { { 8, 15, 7, 6, 12, 6 }, { 1, 0, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3 } }, + { { 7, 10, 3, 6, 8, 3 }, { 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 10, 20, 10, 3, 6, 3 }, { 3, 3, 0, 1, 3, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0 } }, + { { 8, 17, 8, 1, 2, 1 }, { 3, 2, 2, 3, 3, 3, 3, 3, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 8, 15, 5, 4, 6, 2 }, { 1, 1, 0, 3, 0, 3, 3, 3, 3, 2, 2, 3, 2, 2, 2, 3 } }, + { { 10, 20, 10, 5, 10, 5 }, { 3, 3, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0 } }, + { { 7, 14, 7, 1, 2, 1 }, { 0, 0, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 9, 17, 7, 5, 9, 3 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 10, 20, 9, 4, 8, 4 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 4, 7, 2, 3, 4, 1 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 7, 14, 6, 0, 1, 0 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 2, 2 } }, + { { 6, 13, 6, 5, 11, 5 }, { 3, 0, 0, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 9, 18, 8, 6, 13, 6 }, { 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 14, 30, 14, 11, 22, 11 }, { 3, 3, 0, 1, 3, 2, 3, 0, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 10, 21, 10, 9, 19, 9 }, { 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 0, 3, 3, 3, 3, 3 } }, + { { 9, 16, 6, 6, 10, 4 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0 } }, + { { 8, 14, 5, 2, 4, 1 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 11, 22, 10, 1, 2, 0 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 11, 22, 11, 4, 9, 4 }, { 1, 1, 1, 1, 0, 3, 3, 3, 3, 3, 2, 3, 0, 3, 3, 3 } }, + { { 16, 32, 16, 10, 21, 10 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 23, 11, 3, 6, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 14, 29, 14, 13, 25, 12 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 16, 31, 15, 14, 27, 13 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 0, 1, 0, 0, 0, 0 } }, + { { 15, 31, 15, 4, 9, 4 }, { 1, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 16, 33, 16, 0, 1, 0 }, { 3, 0, 0, 3, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 0 } }, + { { 11, 24, 11, 2, 4, 2 }, { 3, 2, 0, 1, 3, 2, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0 } }, + { { 17, 35, 16, 9, 18, 9 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 } }, + { { 15, 30, 14, 9, 19, 9 }, { 3, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 9, 18, 7, 6, 11, 4 }, { 3, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 12, 25, 12, 4, 8, 4 }, { 3, 3, 0, 3, 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 3, 0 } }, + { { 18, 37, 18, 13, 27, 13 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3 } }, + { { 18, 36, 17, 11, 22, 10 }, { 3, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 13, 27, 13, 8, 18, 8 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 0 } }, + { { 16, 33, 16, 7, 15, 7 }, { 3, 3, 3, 3, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 16, 35, 31, 15, 25, 31 }, { 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 16, 34, 16, 6, 12, 5 }, { 1, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 23, 11, 5, 11, 5 }, { 3, 3, 0, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 25, 12, 5, 10, 5 }, { 3, 2, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 13, 26, 12, 12, 23, 11 }, { 3, 3, 3, 3, 3, 0, 0, 0, 3, 3, 1, 1, 3, 3, 0, 0 } }, + { { 13, 27, 12, 3, 6, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3 } }, + { { 16, 32, 15, 2, 4, 2 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 9, 20, 9, 0, 1, 0 }, { 3, 3, 0, 3, 0, 0, 0, 3, 1, 1, 0, 0, 1, 0, 0, 0 } }, + { { 13, 27, 13, 10, 20, 10 }, { 3, 3, 0, 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 0, 0, 0 } }, + { { 15, 30, 15, 8, 16, 8 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 16, 34, 17, 11, 25, 12 }, { 0, 0, 0, 0, 0, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 10, 20, 7, 4, 6, 2 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 0, 0, 0, 0 } }, + { { 14, 28, 13, 5, 10, 4 }, { 3, 2, 3, 3, 2, 2, 3, 0, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 9, 19, 8, 7, 14, 6 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 1, 0, 1, 1, 1, 1 } }, + { { 12, 24, 11, 9, 19, 9 }, { 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 31, 15, 6, 13, 6 }, { 0, 0, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 13, 28, 13, 4, 9, 4 }, { 3, 3, 2, 3, 0, 0, 3, 3, 1, 1, 1, 0, 1, 1, 1, 1 } }, + { { 16, 34, 16, 3, 7, 3 }, { 3, 3, 2, 3, 0, 3, 3, 3, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 8, 13, 4, 7, 11, 4 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 9, 16, 6, 8, 13, 5 }, { 3, 0, 0, 0, 3, 0, 1, 0, 3, 0, 0, 0, 3, 0, 0, 0 } }, + { { 12, 26, 12, 1, 2, 1 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 0, 0, 2, 3, 0, 0 } }, + { { 19, 38, 18, 5, 11, 5 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 1, 3, 3, 0, 0, 0, 3 } }, + { { 14, 30, 14, 3, 6, 3 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 14, 28, 13, 2, 4, 1 }, { 0, 0, 0, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 0, 0 } }, + { { 10, 17, 7, 3, 4, 1 }, { 3, 2, 0, 1, 3, 2, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 9, 18, 8, 8, 16, 7 }, { 1, 0, 0, 1, 0, 3, 3, 0, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 8, 16, 8, 7, 14, 7 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0 } }, + { { 14, 29, 13, 1, 1, 0 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 0, 0, 0 } }, + { { 21, 42, 19, 15, 31, 14 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 0, 3, 3, 0, 1, 0 } }, + { { 10, 20, 9, 8, 17, 8 }, { 3, 2, 2, 2, 3, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 22, 9, 5, 8, 3 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 14, 29, 14, 7, 15, 7 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 11, 23, 11, 8, 17, 8 }, { 0, 0, 0, 3, 0, 0, 0, 3, 0, 3, 3, 3, 0, 3, 2, 3 } }, + { { 19, 40, 19, 11, 24, 11 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 10, 19, 7, 5, 9, 3 }, { 3, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 9, 15, 4, 8, 13, 4 }, { 3, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 3, 0, 3, 3 } }, + { { 13, 27, 13, 6, 12, 6 }, { 0, 0, 1, 1, 3, 0, 1, 1, 3, 3, 0, 0, 2, 2, 3, 0 } }, + { { 17, 36, 17, 7, 14, 7 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 11, 23, 11, 10, 21, 10 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 16, 35, 17, 4, 10, 4 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 19, 38, 18, 8, 17, 8 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 1, 3, 3, 0, 0, 3, 3 } }, + { { 18, 38, 18, 4, 7, 3 }, { 1, 0, 3, 3, 0, 0, 3, 3, 0, 3, 2, 3, 3, 2, 2, 3 } }, + { { 13, 24, 10, 11, 20, 8 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 2, 2, 3, 3 } }, + { { 3, 9, 6, 2, 8, 5 }, { 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 3, 3, 0, 0, 3, 3 } }, + { { 20, 41, 19, 7, 14, 7 }, { 3, 2, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 10, 20, 9, 6, 12, 5 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1 } }, + { { 17, 36, 17, 2, 4, 2 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 21, 43, 20, 13, 27, 12 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 1, 0, 0, 3 } }, + { { 9, 19, 9, 7, 15, 7 }, { 0, 0, 0, 3, 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3, 0 } }, + { { 17, 33, 15, 13, 24, 11 }, { 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 2, 3, 2, 2, 2, 3 } }, + { { 7, 15, 7, 8, 18, 9 }, { 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 3, 0, 3, 0, 0, 1 } }, + { { 11, 21, 9, 2, 4, 1 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 2, 3, 1, 0, 3, 3 } }, + { { 12, 25, 12, 8, 17, 8 }, { 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 12, 23, 10, 9, 17, 7 }, { 3, 0, 0, 1, 3, 3, 3, 0, 3, 3, 0, 0, 0, 0, 0, 1 } }, + { { 18, 37, 18, 16, 32, 16 }, { 0, 0, 0, 3, 1, 1, 0, 3, 1, 1, 0, 0, 0, 0, 0, 0 } }, + { { 27, 3, 1, 26, 1, 0 }, { 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 1, 0, 3, 3 } }, + { { 10, 21, 10, 7, 15, 7 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1 } }, + { { 11, 22, 11, 6, 12, 6 }, { 3, 2, 2, 3, 0, 3, 2, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 16, 31, 13, 9, 17, 7 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 3, 8, 3, 5, 11, 5 }, { 0, 0, 0, 3, 0, 0, 3, 3, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 21, 43, 20, 9, 18, 8 }, { 2, 2, 3, 3, 2, 2, 3, 0, 2, 2, 3, 0, 2, 2, 3, 0 } }, + { { 15, 29, 12, 11, 20, 8 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0 } }, + { { 10, 21, 10, 6, 13, 6 }, { 3, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 0, 0, 0, 1 } }, + { { 10, 20, 9, 7, 13, 6 }, { 0, 3, 2, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 21, 43, 20, 5, 11, 5 }, { 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0, 1 } }, + { { 19, 33, 31, 12, 31, 31 }, { 3, 0, 0, 0, 3, 0, 1, 0, 3, 3, 0, 0, 3, 2, 3, 3 } }, + { { 11, 20, 8, 9, 17, 7 }, { 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 10, 17, 7, 8, 13, 5 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 21, 42, 20, 3, 7, 3 }, { 0, 0, 0, 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 14, 2, 6, 12, 2 }, { 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 } }, + { { 19, 39, 19, 9, 20, 10 }, { 3, 2, 3, 0, 3, 3, 0, 1, 3, 3, 1, 1, 0, 0, 0, 1 } }, + { { 13, 26, 11, 5, 8, 3 }, { 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 31, 62, 30, 31, 61, 29 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3 } }, + { { 22, 45, 21, 11, 22, 10 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 0, 1, 1, 0, 0, 1, 1 } }, + { { 23, 48, 23, 4, 9, 4 }, { 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 0, 3, 2, 3, 0 } }, + { { 15, 42, 31, 11, 22, 30 }, { 3, 0, 1, 1, 3, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3 } }, + { { 15, 33, 16, 8, 18, 9 }, { 3, 2, 2, 2, 0, 3, 2, 3, 0, 3, 2, 2, 0, 0, 2, 2 } }, + { { 13, 27, 13, 7, 15, 7 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 19, 35, 14, 16, 29, 12 }, { 3, 0, 0, 3, 0, 0, 1, 0, 3, 0, 0, 3, 3, 3, 3, 2 } }, + { { 1, 2, 1, 7, 13, 6 }, { 3, 0, 0, 3, 0, 0, 0, 0, 3, 3, 3, 0, 3, 2, 2, 3 } }, + { { 11, 21, 9, 8, 15, 6 }, { 1, 0, 3, 3, 1, 0, 3, 3, 0, 3, 2, 3, 3, 3, 2, 3 } }, + { { 14, 28, 12, 8, 16, 6 }, { 3, 3, 3, 3, 0, 3, 3, 3, 1, 3, 3, 3, 1, 0, 3, 3 } }, + { { 20, 41, 19, 1, 3, 1 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 2, 3 } }, + { { 14, 26, 11, 10, 18, 7 }, { 1, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 32, 30, 11, 31, 30 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 23, 47, 22, 7, 14, 6 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 12, 24, 12, 6, 12, 6 }, { 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 3 } }, + { { 16, 29, 11, 13, 23, 9 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 22, 9, 6, 11, 4 }, { 0, 0, 3, 3, 0, 0, 3, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 1, 2, 1, 3, 7, 3 }, { 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 4, 10, 4, 8, 17, 7 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 0, 0, 1, 3, 3, 0, 0 } }, + { { 18, 33, 13, 11, 21, 8 }, { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 3, 0, 0, 0 } }, + { { 23, 47, 22, 16, 32, 15 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 13, 25, 11, 8, 16, 7 }, { 0, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 17, 45, 30, 15, 33, 31 }, { 3, 2, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 18, 37, 17, 1, 1, 0 }, { 3, 0, 0, 1, 3, 3, 0, 0, 3, 3, 0, 0, 2, 3, 0, 0 } }, + { { 8, 16, 7, 12, 25, 11 }, { 1, 1, 0, 3, 0, 1, 1, 0, 3, 0, 1, 1, 3, 3, 0, 1 } }, + { { 14, 27, 12, 7, 13, 5 }, { 0, 0, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 0, 0, 0 } }, + { { 10, 17, 6, 9, 15, 6 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3 } }, + { { 21, 43, 20, 18, 37, 17 }, { 3, 3, 2, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 18, 35, 15, 8, 15, 5 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 19, 32, 30, 15, 43, 31 }, { 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 18, 15, 30, 15, 33, 31 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 22, 9, 8, 15, 6 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 0 } }, + { { 16, 22, 31, 12, 40, 31 }, { 3, 3, 3, 3, 3, 0, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3 } }, + { { 17, 35, 31, 14, 14, 29 }, { 1, 1, 0, 3, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0, 3 } }, + { { 11, 20, 8, 8, 14, 5 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 22, 46, 21, 1, 3, 1 }, { 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3 } }, + { { 10, 18, 6, 1, 1, 0 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 2, 2, 2, 3 } }, + { { 1, 2, 1, 10, 21, 9 }, { 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 7, 8, 2, 5, 5, 1 }, { 1, 0, 0, 0, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0 } }, + { { 20, 10, 31, 13, 10, 31 }, { 3, 3, 0, 3, 3, 2, 3, 0, 3, 3, 3, 0, 0, 0, 0, 0 } }, + { { 17, 33, 12, 14, 27, 9 }, { 1, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 24, 50, 24, 18, 37, 18 }, { 3, 3, 0, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 24, 49, 23, 13, 28, 12 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 18, 27, 12, 16, 22, 10 }, { 1, 1, 0, 3, 1, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2 } }, + { { 3, 12, 7, 4, 16, 8 }, { 1, 1, 0, 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 24, 50, 24, 9, 19, 8 }, { 3, 2, 3, 0, 3, 2, 2, 3, 3, 2, 3, 3, 2, 2, 2, 3 } }, + { { 22, 41, 30, 18, 23, 30 }, { 0, 3, 2, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 16, 31, 12, 4, 8, 2 }, { 3, 2, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1, 3, 0, 0, 1 } }, + { { 20, 39, 16, 11, 20, 8 }, { 3, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 11, 21, 7, 7, 13, 4 }, { 0, 0, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 3 } }, + { { 13, 25, 11, 6, 11, 4 }, { 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 0, 0, 1, 1, 1, 1 } }, + { { 18, 35, 15, 5, 9, 3 }, { 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1 } }, + { { 20, 38, 16, 13, 25, 10 }, { 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 16, 29, 13, 7, 13, 5 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 0, 1, 1 } }, + { { 5, 9, 3, 12, 24, 10 }, { 3, 2, 3, 3, 3, 2, 3, 0, 3, 3, 3, 0, 3, 0, 0, 1 } }, + { { 13, 25, 8, 3, 6, 1 }, { 3, 0, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 0, 3, 3 } }, + { { 6, 11, 4, 16, 31, 13 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 25, 50, 24, 21, 43, 20 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 19, 22, 30, 16, 23, 31 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 22, 45, 30, 9, 15, 30 }, { 3, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } }, + { { 1, 2, 1, 14, 28, 12 }, { 1, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2, 3, 0, 3, 2, 3 } }, + { { 16, 22, 9, 13, 17, 7 }, { 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 0, 3, 0, 1 } }, + { { 11, 19, 8, 6, 9, 4 }, { 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 0, 0, 3, 0, 0, 0 } }, + { { 28, 58, 26, 15, 32, 14 }, { 1, 0, 0, 3, 1, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 9, 20, 10, 5, 13, 7 }, { 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 3 } }, + { { 28, 56, 26, 4, 7, 3 }, { 1, 0, 2, 3, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0 } }, + { { 14, 18, 6, 11, 14, 4 }, { 1, 0, 0, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 0, 0, 3 } }, + { { 15, 9, 30, 7, 9, 30 }, { 1, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0 } }, + { { 30, 50, 3, 29, 46, 2 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0 } }, + { { 10, 19, 5, 11, 21, 6 }, { 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 21, 31, 30, 22, 31, 30 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 19, 27, 31, 11, 19, 30 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3 } }, + { { 26, 53, 25, 6, 13, 6 }, { 3, 2, 2, 3, 3, 2, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 12, 24, 10, 7, 13, 5 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 } }, + { { 9, 20, 10, 4, 10, 5 }, { 0, 0, 0, 3, 1, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0 } }, + { { 19, 29, 30, 14, 55, 28 }, { 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0 } }, + { { 12, 19, 8, 11, 16, 7 }, { 0, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 0, 0, 3, 3 } }, + { { 11, 30, 31, 7, 15, 29 }, { 1, 0, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 0, 3, 3 } }, + { { 25, 50, 24, 2, 4, 1 }, { 3, 3, 2, 3, 0, 0, 0, 3, 3, 3, 0, 0, 3, 2, 3, 3 } }, + { { 18, 30, 31, 10, 44, 30 }, { 0, 3, 2, 3, 0, 3, 2, 3, 0, 3, 3, 3, 0, 3, 3, 3 } }, + { { 10, 22, 11, 8, 18, 9 }, { 3, 2, 3, 0, 3, 2, 3, 3, 0, 3, 2, 3, 0, 0, 3, 3 } }, + { { 22, 18, 30, 19, 41, 30 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 3, 0 } }, + { { 17, 32, 12, 6, 11, 4 }, { 3, 2, 3, 0, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 25, 13, 8, 19, 10 }, { 3, 0, 0, 3, 3, 0, 0, 0, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 18, 50, 29, 15, 10, 29 }, { 3, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3 } }, + { { 13, 17, 5, 9, 10, 3 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 1, 3, 3, 0, 0 } }, + { { 13, 29, 15, 8, 20, 11 }, { 0, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 0, 2, 3, 3, 3 } }, + { { 29, 57, 27, 27, 52, 25 }, { 3, 3, 2, 3, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 } }, + { { 14, 15, 30, 9, 31, 30 }, { 3, 3, 0, 3, 3, 3, 0, 0, 3, 3, 0, 1, 3, 0, 1, 1 } }, + { { 2, 3, 1, 19, 37, 16 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 14, 51, 30, 9, 34, 30 }, { 3, 0, 0, 3, 0, 3, 3, 3, 1, 0, 3, 3, 0, 0, 3, 3 } }, + { { 18, 52, 30, 14, 22, 30 }, { 3, 3, 0, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 24, 10, 6, 13, 5 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 0, 3, 3, 0, 3, 2, 2 } }, + { { 16, 23, 10, 10, 14, 6 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 23, 49, 30, 20, 36, 30 }, { 3, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 26, 54, 24, 12, 24, 10 }, { 0, 1, 1, 1, 0, 1, 1, 1, 3, 0, 1, 1, 2, 3, 0, 1 } }, + { { 17, 31, 11, 1, 2, 1 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 0, 1, 2, 2, 0, 0 } }, + { { 29, 60, 29, 6, 13, 6 }, { 3, 2, 3, 3, 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 11, 24, 12, 4, 11, 6 }, { 1, 3, 2, 3, 0, 3, 2, 3, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 19, 27, 10, 12, 15, 5 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 3, 3, 3, 3, 3 } }, + { { 12, 25, 13, 10, 22, 12 }, { 1, 0, 2, 3, 0, 0, 3, 3, 3, 0, 0, 0, 3, 0, 0, 0 } }, + { { 16, 23, 30, 14, 6, 26 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3 } }, + { { 10, 12, 4, 8, 8, 2 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 2, 2, 3, 0 } }, + { { 10, 24, 30, 6, 45, 30 }, { 0, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 3 } }, + { { 8, 44, 30, 6, 26, 30 }, { 1, 1, 1, 1, 0, 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 23, 32, 30, 17, 12, 29 }, { 3, 0, 0, 0, 3, 0, 0, 1, 3, 3, 0, 1, 3, 2, 3, 1 } }, + { { 11, 20, 8, 16, 31, 14 }, { 3, 3, 0, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 0, 0, 0 } }, + { { 13, 28, 8, 5, 11, 3 }, { 0, 0, 0, 3, 0, 0, 0, 3, 1, 1, 3, 3, 0, 0, 3, 3 } }, + { { 12, 25, 12, 7, 16, 7 }, { 0, 0, 1, 1, 0, 0, 1, 1, 3, 3, 0, 0, 3, 2, 2, 3 } }, + { { 17, 22, 7, 10, 11, 3 }, { 1, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 11, 22, 11, 7, 15, 7 }, { 3, 0, 0, 0, 3, 0, 0, 1, 3, 3, 0, 1, 3, 2, 3, 0 } }, + { { 23, 5, 30, 9, 5, 30 }, { 3, 3, 0, 3, 3, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1 } }, + { { 14, 23, 8, 1, 2, 1 }, { 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 2, 3, 3 } }, + { { 22, 36, 15, 20, 32, 14 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 12, 26, 12, 7, 14, 7 }, { 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 12, 24, 11, 7, 14, 6 }, { 3, 3, 3, 3, 0, 1, 0, 0, 0, 1, 1, 0, 3, 3, 3, 3 } }, + { { 10, 22, 11, 6, 14, 7 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 0, 3, 3, 3, 3, 3, 3 } }, + { { 12, 27, 13, 6, 12, 6 }, { 0, 0, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 3, 0, 3, 3 } }, + { { 20, 38, 14, 3, 5, 2 }, { 3, 0, 0, 3, 0, 0, 0, 3, 3, 3, 0, 3, 3, 2, 3, 3 } }, + { { 15, 29, 15, 16, 36, 17 }, { 3, 3, 0, 3, 0, 0, 0, 0, 3, 3, 3, 0, 3, 2, 3, 0 } }, + { { 7, 29, 6, 8, 30, 7 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1, 2, 2, 3, 0 } }, +}; + +inline constexpr uint8_t BC2_POSITION_RANK[256][4] = { + { 1, 1, 1, 1 }, + { 3, 3, 3, 3 }, + { 2, 2, 2, 2 }, + { 0, 0, 0, 0 }, + { 3, 3, 0, 0 }, + { 0, 0, 3, 3 }, + { 3, 3, 1, 1 }, + { 0, 0, 2, 2 }, + { 2, 2, 0, 0 }, + { 1, 1, 3, 3 }, + { 1, 1, 2, 2 }, + { 2, 2, 1, 1 }, + { 3, 3, 2, 2 }, + { 1, 2, 1, 1 }, + { 1, 1, 1, 2 }, + { 2, 1, 1, 1 }, + { 1, 1, 2, 1 }, + { 1, 1, 0, 0 }, + { 2, 2, 3, 3 }, + { 0, 0, 1, 1 }, + { 3, 3, 3, 2 }, + { 3, 3, 2, 3 }, + { 3, 2, 3, 3 }, + { 2, 3, 3, 3 }, + { 1, 1, 0, 1 }, + { 1, 1, 1, 0 }, + { 1, 2, 1, 2 }, + { 1, 0, 1, 1 }, + { 3, 2, 1, 0 }, + { 0, 1, 1, 1 }, + { 3, 3, 2, 1 }, + { 2, 1, 2, 1 }, + { 1, 2, 2, 2 }, + { 0, 1, 2, 3 }, + { 2, 2, 1, 2 }, + { 2, 2, 2, 1 }, + { 1, 0, 3, 2 }, + { 2, 3, 0, 1 }, + { 2, 1, 2, 2 }, + { 3, 3, 1, 0 }, + { 3, 3, 0, 1 }, + { 1, 3, 1, 3 }, + { 3, 1, 3, 1 }, + { 3, 3, 1, 2 }, + { 1, 0, 3, 3 }, + { 1, 2, 3, 3 }, + { 2, 1, 3, 3 }, + { 0, 2, 0, 2 }, + { 0, 1, 3, 3 }, + { 2, 3, 0, 0 }, + { 0, 0, 2, 3 }, + { 3, 2, 3, 2 }, + { 0, 0, 3, 2 }, + { 1, 2, 2, 1 }, + { 3, 2, 0, 0 }, + { 0, 2, 2, 3 }, + { 3, 2, 2, 0 }, + { 0, 0, 1, 2 }, + { 2, 3, 2, 2 }, + { 1, 0, 2, 2 }, + { 2, 1, 0, 0 }, + { 2, 0, 2, 0 }, + { 1, 1, 2, 3 }, + { 2, 3, 1, 1 }, + { 2, 3, 2, 3 }, + { 2, 1, 1, 2 }, + { 1, 2, 0, 0 }, + { 1, 1, 3, 2 }, + { 3, 2, 2, 2 }, + { 3, 2, 1, 1 }, + { 0, 1, 2, 2 }, + { 2, 2, 0, 1 }, + { 2, 2, 2, 3 }, + { 2, 2, 1, 0 }, + { 0, 0, 2, 1 }, + { 2, 3, 0, 2 }, + { 2, 2, 3, 2 }, + { 0, 3, 0, 3 }, + { 2, 0, 3, 2 }, + { 3, 1, 1, 0 }, + { 0, 1, 1, 3 }, + { 0, 2, 1, 3 }, + { 3, 3, 3, 1 }, + { 3, 0, 3, 3 }, + { 1, 3, 3, 3 }, + { 3, 1, 2, 0 }, + { 3, 3, 3, 0 }, + { 3, 3, 0, 3 }, + { 1, 3, 0, 1 }, + { 3, 1, 3, 3 }, + { 0, 3, 3, 3 }, + { 3, 3, 1, 3 }, + { 1, 0, 3, 1 }, + { 0, 1, 1, 2 }, + { 1, 0, 2, 1 }, + { 3, 0, 3, 0 }, + { 2, 1, 1, 0 }, + { 1, 2, 0, 1 }, + { 0, 0, 0, 1 }, + { 1, 0, 0, 0 }, + { 0, 1, 0, 0 }, + { 3, 2, 2, 1 }, + { 1, 2, 2, 3 }, + { 3, 2, 3, 1 }, + { 1, 3, 2, 3 }, + { 2, 3, 1, 2 }, + { 2, 1, 3, 2 }, + { 1, 3, 1, 1 }, + { 0, 0, 1, 0 }, + { 1, 1, 1, 3 }, + { 2, 0, 3, 1 }, + { 1, 3, 0, 2 }, + { 3, 1, 1, 1 }, + { 3, 3, 0, 2 }, + { 3, 1, 3, 2 }, + { 0, 1, 0, 1 }, + { 1, 1, 3, 1 }, + { 2, 3, 1, 3 }, + { 3, 3, 2, 0 }, + { 1, 0, 1, 2 }, + { 1, 0, 1, 0 }, + { 2, 1, 0, 1 }, + { 0, 1, 2, 1 }, + { 2, 0, 3, 3 }, + { 1, 2, 1, 0 }, + { 0, 2, 3, 3 }, + { 0, 2, 2, 2 }, + { 2, 2, 2, 0 }, + { 0, 0, 0, 2 }, + { 2, 2, 0, 2 }, + { 0, 1, 0, 2 }, + { 1, 0, 2, 3 }, + { 2, 0, 2, 2 }, + { 2, 3, 1, 0 }, + { 2, 0, 0, 0 }, + { 1, 2, 0, 2 }, + { 0, 2, 0, 0 }, + { 3, 2, 0, 1 }, + { 0, 2, 1, 2 }, + { 0, 1, 3, 2 }, + { 2, 1, 2, 0 }, + { 3, 2, 2, 3 }, + { 0, 0, 2, 0 }, + { 2, 0, 1, 0 }, + { 2, 3, 3, 2 }, + { 1, 1, 0, 2 }, + { 3, 1, 0, 0 }, + { 2, 0, 2, 1 }, + { 2, 3, 2, 1 }, + { 3, 2, 3, 0 }, + { 1, 2, 1, 3 }, + { 1, 3, 0, 0 }, + { 0, 2, 0, 1 }, + { 1, 2, 3, 2 }, + { 3, 1, 2, 1 }, + { 1, 0, 2, 0 }, + { 0, 0, 1, 3 }, + { 2, 1, 2, 3 }, + { 1, 3, 1, 2 }, + { 0, 0, 3, 1 }, + { 2, 0, 1, 1 }, + { 3, 2, 1, 2 }, + { 0, 3, 2, 3 }, + { 2, 1, 3, 1 }, + { 1, 1, 2, 0 }, + { 0, 2, 1, 1 }, + { 3, 0, 3, 2 }, + { 2, 3, 0, 3 }, + { 0, 1, 3, 1 }, + { 3, 1, 3, 0 }, + { 1, 0, 0, 1 }, + { 1, 3, 2, 2 }, + { 0, 3, 1, 3 }, + { 1, 0, 1, 3 }, + { 0, 1, 1, 0 }, + { 3, 1, 0, 1 }, + { 1, 3, 1, 0 }, + { 0, 2, 0, 3 }, + { 2, 2, 3, 1 }, + { 3, 0, 0, 0 }, + { 2, 2, 1, 3 }, + { 1, 3, 0, 3 }, + { 0, 3, 0, 0 }, + { 3, 1, 2, 2 }, + { 0, 0, 0, 3 }, + { 3, 0, 3, 1 }, + { 3, 0, 2, 0 }, + { 0, 0, 3, 0 }, + { 2, 1, 0, 2 }, + { 2, 3, 2, 0 }, + { 2, 0, 2, 3 }, + { 2, 0, 1, 2 }, + { 0, 2, 2, 1 }, + { 3, 2, 0, 2 }, + { 0, 3, 0, 2 }, + { 0, 2, 3, 2 }, + { 1, 2, 2, 0 }, + { 0, 3, 2, 2 }, + { 3, 0, 1, 1 }, + { 1, 3, 2, 1 }, + { 1, 1, 0, 3 }, + { 2, 0, 3, 0 }, + { 2, 2, 3, 0 }, + { 0, 1, 0, 3 }, + { 3, 0, 1, 0 }, + { 1, 2, 3, 1 }, + { 3, 0, 2, 2 }, + { 2, 2, 0, 3 }, + { 3, 1, 1, 2 }, + { 0, 3, 1, 1 }, + { 2, 1, 1, 3 }, + { 1, 1, 3, 0 }, + { 0, 3, 1, 2 }, + { 0, 3, 0, 1 }, + { 2, 1, 3, 0 }, + { 1, 2, 0, 3 }, + { 1, 0, 3, 0 }, + { 3, 0, 2, 1 }, + { 1, 3, 3, 2 }, + { 2, 3, 3, 1 }, + { 0, 3, 3, 2 }, + { 3, 0, 2, 3 }, + { 2, 0, 0, 1 }, + { 1, 0, 0, 2 }, + { 3, 2, 1, 3 }, + { 3, 1, 2, 3 }, + { 3, 2, 0, 3 }, + { 1, 2, 3, 0 }, + { 2, 3, 3, 0 }, + { 0, 1, 2, 0 }, + { 0, 3, 2, 1 }, + { 0, 2, 3, 1 }, + { 1, 3, 2, 0 }, + { 2, 0, 0, 2 }, + { 0, 2, 1, 0 }, + { 2, 0, 1, 3 }, + { 3, 0, 1, 2 }, + { 2, 1, 0, 3 }, + { 3, 0, 0, 1 }, + { 3, 1, 0, 2 }, + { 1, 0, 0, 3 }, + { 0, 2, 2, 0 }, + { 1, 3, 3, 1 }, + { 0, 1, 3, 0 }, + { 3, 1, 1, 3 }, + { 0, 3, 1, 0 }, + { 0, 3, 3, 0 }, + { 3, 0, 0, 3 }, + { 3, 0, 0, 2 }, + { 2, 0, 0, 3 }, + { 1, 3, 3, 0 }, + { 0, 3, 2, 0 }, + { 0, 2, 3, 0 }, + { 0, 3, 3, 1 }, + { 3, 0, 1, 3 }, + { 3, 1, 0, 3 }, +}; + +inline constexpr Bc2State BC2_FULL_DICTIONARY[255] = { + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 0, 1, 0, 0, 0 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 3, 15, 10, 2, 14, 10 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 12, 25, 12, 11, 22, 11 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 16, 33, 16, 15, 31, 15 }, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 10, 29, 31, 9, 28, 31 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 21, 32, 5, 20, 31, 5 }, { 3, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 6, 11, 5, 4, 9, 4 }, { 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 3, 5, 2, 1, 2, 1 }, { 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 21, 15, 8, 20, 15, 7 }, { 1, 1, 0, 3, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 31, 63, 31, 0, 0, 0 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 1, 2, 1, 0, 1, 0 }, { 3, 0, 1, 1, 3, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 10, 21, 10, 9, 18, 9 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } }, + { { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }, { 30, 61, 30, 29, 60, 29 }, { 1, 0, 3, 3, 0, 3, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 30, 49, 15, 29, 49, 15 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 3, 3, 0, 0 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 2, 63, 15, 1, 62, 15 }, { 0, 0, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 8, 62, 15, 6, 62, 16 }, { 3, 3, 0, 1, 2, 2, 3, 3, 2, 2, 2, 3, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 5, 10, 5, 4, 8, 4 }, { 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 16, 31, 16, 15, 34, 16 }, { 1, 1, 0, 3, 1, 0, 3, 2, 0, 3, 2, 2, 3, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 31, 63, 31, 0, 0, 0 }, { 1, 1, 0, 3, 1, 1, 0, 3, 1, 1, 0, 3, 1, 0, 3, 2 } }, + { { 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 }, { 21, 49, 17, 21, 48, 20 }, { 3, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 0, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 31, 32, 31, 31, 30, 31 }, { 3, 3, 0, 1, 3, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }, { 23, 48, 23, 22, 47, 23 }, { 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1 } }, + { { 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 12, 62, 15, 10, 62, 15 }, { 3, 2, 2, 3, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 18, 8, 28, 18, 8 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 5, 8, 2, 4, 6, 2 }, { 3, 2, 2, 2, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 11, 21, 10, 9, 17, 8 }, { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 13, 6, 1, 1, 1 }, { 3, 3, 0, 0, 3, 0, 0, 3, 3, 1, 0, 3, 0, 0, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 16, 13, 8, 13, 10, 6 }, { 1, 1, 0, 3, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 18, 37, 17, 1, 2, 4 }, { 3, 2, 2, 2, 3, 2, 2, 2, 0, 3, 2, 2, 0, 0, 2, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 21, 41, 20, 19, 36, 18 }, { 2, 2, 3, 3, 2, 2, 3, 0, 3, 3, 0, 1, 3, 0, 1, 1 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 18, 62, 15, 13, 62, 15 }, { 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 } }, + { { 15, 15, 15, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0 }, { 8, 62, 15, 6, 62, 16 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1, 3, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 30, 60, 29, 1, 2, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 0, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 30, 55, 19, 30, 54, 18 }, { 1, 0, 3, 3, 1, 0, 3, 2, 1, 0, 3, 2, 0, 0, 3, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 24, 48, 24, 22, 43, 22 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, 0, 0, 0, 3, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 15, 31, 14, 12, 24, 12 }, { 3, 3, 0, 1, 3, 3, 0, 1, 3, 3, 0, 0, 3, 0, 0, 0 } }, + { { 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, { 19, 43, 17, 18, 41, 16 }, { 3, 0, 1, 1, 3, 0, 1, 1, 3, 3, 1, 1, 3, 0, 0, 0 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 8, 62, 15, 6, 62, 16 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2 } }, + { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 16, 32, 31, 15, 31, 31 }, { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 9, 15, 4, 8, 12, 3 }, { 3, 3, 2, 3, 3, 3, 3, 3, 0, 1, 0, 3, 0, 0, 0, 0 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 17, 31, 31, 15, 31, 31 }, { 1, 1, 0, 3, 1, 1, 0, 3, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 20, 9, 5, 18, 9 }, { 3, 0, 0, 3, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 26, 54, 26, 25, 50, 25 }, { 0, 0, 0, 3, 0, 1, 0, 3, 0, 1, 0, 3, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 2, 5, 5, 1, 2, 2 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 16, 32, 31, 15, 31, 31 }, { 2, 2, 3, 0, 2, 3, 0, 1, 3, 0, 1, 1, 0, 0, 1, 1 } }, + { { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, { 24, 43, 20, 23, 41, 19 }, { 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 43, 20, 1, 6, 1 }, { 0, 0, 1, 1, 3, 3, 0, 0, 2, 3, 3, 3, 2, 2, 2, 2 } }, + { { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }, { 27, 53, 24, 26, 50, 23 }, { 3, 2, 2, 2, 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 21, 40, 17, 15, 30, 14 }, { 0, 0, 0, 3, 0, 0, 0, 3, 1, 1, 0, 3, 0, 0, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 39, 20, 16, 34, 17 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 3, 1, 1, 3, 3, 0, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 11, 23, 11, 7, 14, 7 }, { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 14, 7, 3, 6, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 0, 0, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 22, 45, 22, 15, 30, 15 }, { 3, 3, 0, 3, 2, 2, 3, 3, 3, 2, 2, 3, 2, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 38, 16, 15, 32, 14 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 14, 62, 15, 9, 62, 15 }, { 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 41, 18, 22, 39, 18 }, { 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 15, 26, 12, 13, 24, 11 }, { 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 22, 43, 18, 19, 37, 16 }, { 3, 2, 2, 3, 3, 3, 3, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 8, 8, 1, 1, 1, 0 }, { 3, 2, 2, 3, 3, 3, 3, 3, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 15, 0, 0, 0, 15, 15, 0, 0, 15, 15, 15, 0, 15, 15, 15, 15 }, { 9, 62, 15, 6, 62, 15 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 48, 24, 21, 44, 23 }, { 1, 0, 3, 3, 1, 1, 3, 3, 1, 1, 3, 3, 1, 0, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 0, 0, 0, 0 }, { 10, 62, 15, 7, 62, 15 }, { 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 0, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 11, 21, 10, 1, 2, 1 }, { 1, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0 }, { 14, 62, 15, 8, 61, 15 }, { 0, 0, 3, 2, 1, 0, 3, 2, 1, 1, 0, 3, 1, 1, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 27, 56, 27, 26, 53, 26 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 9, 15, 4, 5, 8, 2 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 4, 15, 9, 3, 14, 8 }, { 1, 1, 1, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 34, 15, 17, 31, 14 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 48, 23, 1, 2, 1 }, { 3, 3, 3, 3, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 5, 10, 5, 1, 2, 1 }, { 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 38, 18, 7, 14, 7 }, { 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 11, 20, 8, 9, 16, 6 }, { 2, 2, 2, 2, 3, 3, 2, 2, 0, 0, 3, 3, 1, 1, 0, 0 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }, { 2, 5, 2, 1, 3, 1 }, { 3, 3, 3, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 17, 34, 16, 14, 29, 14 }, { 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 17, 36, 17, 10, 21, 10 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 5, 17, 2, 4, 15, 1 }, { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, { 22, 46, 21, 20, 43, 19 }, { 1, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5 }, { 29, 59, 29, 27, 56, 27 }, { 3, 2, 2, 3, 3, 2, 3, 3, 3, 2, 3, 0, 2, 2, 3, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 11, 22, 10, 6, 12, 6 }, { 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0 } }, + { { 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 5, 6, 6, 6, 6 }, { 29, 59, 29, 27, 56, 27 }, { 3, 3, 0, 1, 0, 3, 3, 0, 1, 1, 0, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 15, 30, 14, 1, 2, 1 }, { 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3, 1, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 11, 28, 15, 7, 21, 11 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 14, 15, 0, 1, 14, 15, 0, 1, 14, 15, 0, 1, 14, 15, 0, 0 }, { 11, 62, 15, 7, 60, 15 }, { 3, 3, 3, 3, 0, 1, 1, 0, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 27, 49, 22, 26, 47, 22 }, { 3, 0, 0, 1, 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 28, 57, 26, 2, 3, 1 }, { 3, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 31, 62, 31, 26, 52, 26 }, { 3, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 20, 13, 0, 15, 11 }, { 3, 0, 0, 1, 3, 3, 3, 3, 2, 2, 2, 3, 2, 2, 2, 2 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 25, 62, 15, 17, 62, 15 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 0, 2, 2, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 46, 23, 12, 24, 12 }, { 3, 3, 0, 1, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 24, 49, 24, 19, 38, 19 }, { 3, 3, 2, 2, 0, 0, 3, 3, 1, 1, 0, 0, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 26, 53, 26, 9, 19, 9 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 3, 0, 0, 2, 2, 3, 0 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 2, 61, 18, 0, 61, 18 }, { 2, 2, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1, 0, 1, 1, 1 } }, + { { 15, 15, 0, 1, 15, 15, 0, 1, 15, 15, 0, 1, 15, 0, 0, 1 }, { 2, 62, 17, 1, 61, 15 }, { 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 28, 16, 0, 21, 14 }, { 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 13, 26, 13, 6, 11, 5 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 2, 3, 3, 3, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 30, 62, 30, 22, 46, 23 }, { 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 0, 0, 15, 14, 1, 0, 15, 14, 1, 0, 15, 14, 1, 0, 15, 14 }, { 11, 60, 15, 7, 60, 15 }, { 1, 1, 1, 1, 0, 0, 1, 1, 3, 0, 0, 0, 3, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 24, 43, 17, 22, 39, 16 }, { 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 25, 50, 23, 22, 44, 20 }, { 1, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2, 3, 1, 0, 3, 3 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 21, 32, 14, 19, 29, 12 }, { 3, 0, 0, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 2, 2 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 14, 0, 0, 15, 14 }, { 2, 61, 15, 1, 61, 13 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 25, 47, 19, 18, 37, 15 }, { 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 0, 3 } }, + { { 4, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }, { 29, 58, 28, 27, 54, 26 }, { 3, 3, 3, 3, 3, 3, 0, 1, 3, 3, 0, 1, 3, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 9, 18, 7, 2, 4, 1 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 18, 32, 13, 17, 31, 13 }, { 3, 2, 0, 1, 3, 2, 0, 1, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 0, 0, 0, 15, 0, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15 }, { 8, 61, 15, 5, 61, 15 }, { 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 20, 33, 12, 16, 25, 9 }, { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 5, 5, 5, 4, 5, 5, 4, 4, 5, 5, 4, 4, 5, 5, 4, 4 }, { 28, 56, 28, 25, 51, 25 }, { 1, 1, 1, 1, 1, 1, 1, 0, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 60, 11, 1, 57, 8 }, { 3, 0, 1, 1, 3, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0 }, { 18, 62, 15, 15, 61, 16 }, { 1, 0, 0, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 13, 22, 9, 8, 11, 4 }, { 3, 2, 2, 2, 3, 2, 2, 2, 0, 3, 2, 2, 1, 0, 3, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 2, 12, 9, 0, 2, 2 }, { 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 0, 0, 3, 3 } }, + { { 14, 15, 15, 0, 14, 15, 15, 0, 14, 15, 0, 0, 14, 15, 0, 0 }, { 17, 31, 31, 14, 31, 31 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3 }, { 24, 48, 23, 21, 43, 21 }, { 3, 2, 2, 2, 0, 3, 3, 3, 1, 0, 3, 3, 1, 0, 0, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 13, 10, 0, 6, 8 }, { 1, 1, 1, 1, 0, 0, 1, 1, 0, 3, 3, 3, 3, 3, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 7, 5, 9, 6, 4, 8 }, { 2, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 }, { 2, 61, 19, 1, 60, 19 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 2, 3, 0, 2, 2, 2, 3 } }, + { { 10, 10, 10, 11, 10, 10, 10, 11, 10, 10, 10, 11, 10, 10, 10, 11 }, { 17, 35, 17, 16, 34, 16 }, { 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 15, 0 }, { 2, 61, 17, 1, 61, 16 }, { 2, 3, 0, 1, 2, 3, 0, 1, 3, 0, 1, 1, 3, 0, 1, 1 } }, + { { 9, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }, { 3, 6, 3, 1, 2, 1 }, { 1, 1, 1, 0, 1, 1, 0, 3, 1, 0, 3, 2, 0, 3, 2, 2 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 27, 56, 26, 26, 53, 25 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0 } }, + { { 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 3, 3, 3, 3 }, { 26, 53, 26, 23, 47, 23 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 19, 38, 18, 13, 25, 12 }, { 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 20, 40, 20, 18, 36, 18 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3 } }, + { { 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, { 24, 44, 19, 22, 40, 17 }, { 1, 1, 0, 0, 1, 1, 0, 3, 1, 0, 3, 2, 1, 0, 3, 2 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 31, 63, 0, 31, 62, 31 }, { 1, 1, 0, 0, 1, 0, 0, 3, 0, 3, 3, 3, 3, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 10, 25, 6, 10, 24, 5 }, { 3, 2, 2, 3, 2, 2, 2, 3, 3, 3, 0, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 23, 44, 18, 14, 30, 12 }, { 3, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 1 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 9, 10, 10, 10, 10 }, { 3, 7, 3, 1, 2, 1 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 14, 28, 12, 4, 8, 3 }, { 1, 0, 2, 3, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 1, 0, 15, 14, 2, 0, 15, 14, 2, 1, 15, 14, 1, 1, 15, 14 }, { 2, 60, 17, 1, 60, 16 }, { 0, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 0, 15, 15, 1, 0, 15, 15, 1, 1, 0, 15, 1, 1, 0, 0 }, { 2, 61, 15, 1, 61, 13 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 1, 0, 0, 0, 0 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15 }, { 18, 37, 18, 14, 28, 14 }, { 1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 58, 28, 16, 33, 16 }, { 1, 1, 0, 3, 0, 1, 1, 0, 3, 3, 0, 1, 3, 3, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 28, 49, 17, 24, 41, 14 }, { 1, 1, 0, 3, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 22, 38, 12, 16, 25, 7 }, { 3, 0, 0, 1, 3, 0, 0, 1, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3 }, { 25, 44, 19, 22, 40, 17 }, { 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 3, 0, 2, 2, 3, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 21, 48, 27, 19, 43, 26 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1, 0, 0, 1, 1 } }, + { { 15, 15, 14, 13, 15, 15, 14, 13, 15, 14, 14, 13, 15, 14, 14, 13 }, { 18, 32, 31, 14, 31, 31 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 3, 3, 3, 1, 0, 0, 3 } }, + { { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, { 24, 41, 16, 23, 39, 15 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15 }, { 19, 61, 14, 14, 60, 13 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 2, 1, 15, 14, 2, 1, 15, 13, 2, 1, 14, 13, 1, 1, 15, 14 }, { 12, 58, 14, 7, 58, 15 }, { 1, 0, 3, 2, 1, 1, 0, 3, 1, 1, 0, 0, 0, 0, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 17, 29, 11, 9, 14, 4 }, { 3, 3, 2, 2, 0, 3, 3, 2, 1, 0, 3, 3, 1, 0, 0, 0 } }, + { { 15, 15, 15, 0, 15, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }, { 2, 61, 17, 1, 60, 16 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 }, { 17, 53, 15, 2, 45, 12 }, { 3, 2, 2, 3, 3, 2, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 59, 29, 7, 14, 7 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 0, 0, 3, 3 } }, + { { 12, 12, 12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 23, 46, 21, 18, 39, 18 }, { 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0 } }, + { { 0, 0, 1, 1, 15, 0, 0, 1, 14, 15, 0, 0, 14, 14, 15, 0 }, { 15, 59, 14, 8, 58, 15 }, { 3, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 0, 3, 3, 3, 3 } }, + { { 15, 15, 0, 1, 15, 15, 0, 1, 15, 15, 0, 1, 15, 0, 0, 1 }, { 31, 62, 16, 28, 57, 16 }, { 3, 0, 0, 3, 3, 0, 3, 3, 0, 1, 3, 2, 0, 0, 3, 3 } }, + { { 12, 12, 11, 11, 12, 12, 11, 11, 12, 12, 11, 11, 12, 12, 11, 11 }, { 21, 43, 20, 18, 38, 18 }, { 3, 3, 0, 0, 3, 3, 0, 0, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 12, 12, 13, 13 }, { 22, 46, 21, 19, 41, 18 }, { 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 25, 50, 25, 18, 36, 18 }, { 1, 0, 2, 3, 1, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 0 } }, + { { 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 17, 56, 11, 5, 53, 7 }, { 3, 3, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 15, 14, 14, 0, 0, 15, 15, 0, 0, 0, 15, 0, 1, 0, 0 }, { 16, 59, 14, 7, 58, 14 }, { 3, 3, 3, 3, 0, 0, 3, 3, 1, 1, 0, 3, 0, 0, 0, 3 } }, + { { 11, 11, 11, 11, 11, 11, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 16, 32, 21, 15, 31, 20 }, { 3, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 1, 1 } }, + { { 15, 14, 15, 15, 15, 15, 15, 0, 15, 0, 0, 1, 0, 0, 1, 1 }, { 16, 59, 15, 9, 58, 15 }, { 3, 0, 1, 1, 3, 0, 0, 1, 3, 3, 0, 1, 2, 2, 3, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 57, 26, 20, 39, 16 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 1, 1, 0, 15, 1, 1, 15, 14, 1, 0, 15, 14, 0, 15, 14, 14 }, { 15, 58, 15, 7, 58, 14 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 0, 1, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 14, 15 }, { 18, 58, 15, 8, 58, 13 }, { 3, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 2, 3 } }, + { { 13, 13, 13, 13, 12, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 12 }, { 17, 32, 31, 14, 33, 30 }, { 3, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1, 1, 0, 0, 0, 0 } }, + { { 3, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 }, { 27, 55, 27, 23, 46, 23 }, { 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15 }, { 31, 62, 14, 27, 57, 9 }, { 3, 2, 2, 3, 0, 3, 3, 3, 1, 1, 3, 2, 0, 0, 3, 3 } }, + { { 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 15, 15, 1, 0, 15, 14 }, { 2, 60, 17, 1, 60, 18 }, { 1, 0, 3, 3, 1, 0, 0, 3, 1, 1, 0, 0, 1, 1, 1, 1 } }, + { { 3, 3, 4, 4, 2, 3, 4, 4, 2, 3, 4, 4, 2, 3, 3, 4 }, { 27, 54, 26, 23, 46, 22 }, { 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 17, 33, 16, 15, 31, 15 }, { 0, 0, 1, 1, 3, 3, 0, 0, 3, 3, 3, 3, 2, 2, 3, 3 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 10, 9, 9, 9, 10, 9, 9, 9 }, { 3, 5, 3, 1, 1, 1 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 0, 3, 3 } }, + { { 9, 9, 9, 10, 9, 9, 9, 10, 9, 9, 10, 10, 9, 9, 10, 10 }, { 4, 8, 4, 1, 2, 1 }, { 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 1 } }, + { { 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, { 21, 34, 15, 19, 30, 13 }, { 3, 0, 0, 3, 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 0 } }, + { { 14, 14, 0, 1, 14, 14, 0, 1, 14, 15, 1, 2, 15, 0, 1, 2 }, { 16, 59, 15, 9, 57, 15 }, { 3, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, + { { 3, 2, 2, 1, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3, 3, 2 }, { 25, 50, 24, 21, 42, 20 }, { 0, 0, 3, 3, 0, 3, 3, 3, 0, 3, 3, 0, 0, 3, 0, 1 } }, + { { 14, 15, 0, 2, 13, 15, 1, 2, 13, 14, 1, 2, 14, 15, 0, 2 }, { 3, 60, 16, 2, 58, 17 }, { 1, 1, 1, 1, 0, 0, 0, 1, 3, 3, 3, 0, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 0, 24, 15, 0, 10, 9 }, { 2, 2, 3, 3, 2, 2, 3, 0, 2, 3, 0, 1, 2, 3, 0, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 16, 25, 8, 3, 4, 1 }, { 0, 0, 1, 1, 3, 0, 1, 1, 2, 3, 0, 0, 2, 2, 3, 0 } }, + { { 0, 0, 0, 0, 15, 0, 0, 0, 15, 0, 0, 1, 15, 0, 0, 0 }, { 18, 35, 17, 16, 33, 16 }, { 1, 1, 0, 0, 1, 0, 0, 3, 0, 0, 3, 2, 3, 3, 2, 2 } }, + { { 14, 15, 1, 2, 14, 14, 1, 2, 13, 14, 1, 2, 13, 14, 0, 1 }, { 16, 59, 15, 8, 56, 15 }, { 1, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 0, 0, 0, 3 } }, + { { 14, 15, 0, 1, 14, 15, 0, 1, 14, 14, 0, 1, 14, 14, 15, 0 }, { 21, 54, 16, 4, 51, 16 }, { 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 10, 60, 16, 9, 57, 22 }, { 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 3, 0, 3, 3, 0, 1 } }, + { { 15, 0, 1, 1, 15, 0, 1, 1, 14, 15, 0, 1, 14, 14, 15, 1 }, { 2, 61, 17, 1, 60, 16 }, { 1, 1, 0, 3, 1, 1, 0, 0, 0, 3, 0, 3, 3, 3, 3, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 16, 27, 9, 13, 21, 7 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 2, 1, 14, 12, 3, 1, 14, 12, 3, 2, 14, 12, 3, 2, 14, 13 }, { 10, 57, 16, 5, 57, 16 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 1, 35, 19, 0, 30, 17 }, { 0, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 3, 2, 2, 2, 3 } }, + { { 15, 15, 15, 0, 15, 15, 0, 0, 15, 0, 0, 1, 15, 0, 1, 1 }, { 25, 58, 12, 11, 54, 10 }, { 1, 1, 0, 0, 1, 1, 0, 0, 3, 3, 0, 0, 2, 2, 3, 3 } }, + { { 10, 11, 11, 12, 10, 10, 11, 11, 10, 10, 10, 11, 9, 10, 10, 10 }, { 8, 16, 8, 2, 5, 3 }, { 3, 3, 3, 0, 3, 3, 0, 0, 3, 3, 0, 0, 2, 3, 0, 0 } }, + { { 0, 0, 1, 1, 15, 0, 0, 1, 15, 15, 0, 0, 14, 15, 15, 0 }, { 26, 59, 13, 13, 54, 11 }, { 0, 0, 0, 0, 1, 1, 1, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 13, 13, 14, 13, 12, 12, 13, 12, 12, 11, 11, 12, 11, 11, 11, 11 }, { 13, 26, 13, 5, 10, 5 }, { 3, 0, 0, 0, 3, 0, 0, 0, 3, 3, 0, 1, 3, 0, 0, 1 } }, + { { 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 }, { 19, 39, 19, 15, 30, 15 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0, 0 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 11, 10, 9, 9, 13, 11, 10, 10 }, { 21, 42, 18, 14, 33, 15 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 15, 23, 3, 7, 11, 1 }, { 1, 1, 0, 3, 1, 0, 0, 3, 0, 0, 3, 3, 0, 0, 0, 3 } }, + { { 11, 11, 12, 12, 11, 11, 11, 12, 11, 11, 12, 13, 11, 11, 12, 12 }, { 23, 47, 22, 18, 40, 19 }, { 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 1, 1 } }, + { { 15, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2 }, { 21, 42, 21, 15, 30, 15 }, { 3, 3, 3, 3, 3, 3, 0, 0, 3, 3, 0, 0, 0, 0, 0, 1 } }, + { { 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12 }, { 9, 18, 9, 3, 6, 3 }, { 3, 0, 0, 3, 3, 0, 0, 1, 3, 3, 3, 0, 3, 3, 3, 3 } }, + { { 0, 1, 2, 3, 1, 1, 2, 3, 2, 2, 3, 4, 3, 3, 4, 4 }, { 26, 54, 26, 22, 44, 22 }, { 0, 0, 1, 1, 3, 0, 0, 1, 3, 3, 3, 0, 2, 2, 2, 3 } }, + { { 12, 11, 11, 11, 12, 12, 12, 12, 14, 14, 14, 14, 15, 15, 15, 15 }, { 15, 30, 15, 6, 12, 6 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 0, 0, 3, 3, 0, 0, 3 } }, + { { 0, 0, 0, 15, 15, 15, 15, 14, 13, 13, 13, 13, 13, 12, 12, 12 }, { 18, 36, 18, 8, 18, 9 }, { 3, 0, 0, 1, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 12, 12, 11, 11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10, 10, 10 }, { 9, 18, 9, 3, 7, 3 }, { 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 3, 3 } }, + { { 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14 }, { 17, 33, 16, 12, 25, 12 }, { 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15 }, { 21, 32, 4, 21, 30, 4 }, { 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, 1, 3, 3, 0, 0 } }, + { { 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0 }, { 23, 47, 23, 17, 34, 17 }, { 3, 0, 0, 1, 3, 3, 0, 1, 2, 2, 3, 0, 2, 2, 3, 0 } }, + { { 2, 3, 3, 3, 2, 2, 3, 3, 1, 1, 2, 2, 0, 0, 1, 1 }, { 24, 49, 24, 18, 37, 18 }, { 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0 } }, + { { 14, 13, 13, 13, 14, 14, 14, 14, 15, 14, 14, 14, 15, 15, 15, 15 }, { 15, 30, 15, 10, 20, 10 }, { 3, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 17, 38, 23, 9, 25, 17 }, { 0, 0, 1, 1, 0, 0, 0, 0, 3, 3, 3, 3, 2, 2, 2, 2 } }, + { { 0, 15, 14, 14, 0, 15, 14, 14, 0, 0, 15, 14, 0, 0, 15, 15 }, { 18, 53, 17, 3, 53, 17 }, { 1, 1, 0, 3, 0, 0, 1, 0, 3, 3, 0, 1, 3, 3, 3, 0 } }, + { { 10, 10, 11, 13, 9, 10, 11, 11, 9, 9, 10, 10, 9, 9, 9, 10 }, { 23, 45, 18, 14, 34, 15 }, { 3, 3, 2, 3, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 28, 54, 23, 13, 23, 8 }, { 3, 2, 3, 3, 3, 3, 3, 0, 3, 3, 0, 0, 0, 0, 0, 0 } }, + { { 14, 15, 0, 1, 14, 15, 0, 2, 14, 15, 0, 2, 14, 15, 0, 1 }, { 25, 60, 15, 15, 57, 14 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 1, 0, 0, 0, 0, 0 } }, + { { 3, 2, 1, 0, 4, 3, 1, 0, 4, 3, 2, 1, 4, 4, 3, 2 }, { 26, 54, 26, 22, 45, 23 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1 } }, + { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 53, 23, 1, 55, 23 }, { 1, 1, 1, 1, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { { 11, 10, 10, 10, 11, 11, 10, 10, 12, 11, 10, 10, 12, 11, 11, 10 }, { 9, 18, 9, 3, 6, 3 }, { 3, 3, 3, 0, 2, 3, 0, 0, 3, 0, 1, 0, 3, 0, 0, 0 } }, + { { 2, 2, 2, 3, 2, 2, 3, 3, 2, 2, 3, 3, 2, 2, 3, 3 }, { 25, 50, 24, 18, 39, 19 }, { 3, 0, 0, 3, 0, 0, 0, 3, 0, 3, 3, 3, 3, 3, 2, 2 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 1, 18, 17, 0, 2, 2 }, { 1, 1, 1, 1, 0, 3, 3, 0, 1, 1, 0, 1, 1, 1, 1, 1 } }, + { { 11, 11, 11, 11, 11, 11, 11, 10, 11, 11, 10, 10, 11, 11, 10, 10 }, { 8, 15, 8, 3, 7, 3 }, { 1, 0, 2, 3, 1, 0, 3, 0, 0, 3, 0, 0, 3, 0, 0, 1 } }, + { { 13, 13, 12, 12, 13, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 }, { 5, 0, 0, 3, 0, 0 }, { 1, 1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 12, 12, 12, 12, 13, 13, 12, 12, 14, 14, 14, 14, 14, 14, 14, 14 }, { 17, 27, 30, 14, 26, 30 }, { 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 3, 3, 3, 3 } }, + { { 10, 10, 10, 11, 10, 10, 11, 11, 10, 11, 11, 12, 11, 11, 12, 13 }, { 10, 20, 10, 3, 7, 4 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3 } }, + { { 0, 0, 15, 15, 0, 15, 15, 15, 15, 15, 14, 14, 15, 14, 14, 14 }, { 15, 54, 19, 6, 55, 19 }, { 3, 3, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 10, 11, 12, 12, 10, 11, 12, 12, 10, 11, 12, 12, 10, 11, 12, 12 }, { 9, 32, 30, 4, 30, 28 }, { 3, 2, 3, 0, 3, 2, 3, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 24, 48, 23, 12, 24, 11 }, { 1, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 }, { 7, 14, 7, 4, 8, 4 }, { 3, 0, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 4, 4, 3, 2, 4, 4, 2, 2, 4, 3, 2, 1, 3, 3, 2, 1 }, { 27, 54, 26, 22, 45, 22 }, { 3, 3, 0, 1, 3, 2, 3, 0, 3, 3, 3, 3, 0, 0, 0, 0 } }, + { { 13, 12, 12, 11, 13, 12, 11, 11, 12, 11, 11, 10, 12, 11, 11, 11 }, { 11, 23, 11, 4, 9, 5 }, { 3, 2, 3, 1, 3, 2, 3, 1, 2, 2, 3, 1, 2, 2, 3, 0 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 19, 43, 26, 3, 6, 3 }, { 3, 0, 0, 3, 0, 0, 3, 3, 1, 0, 3, 3, 1, 0, 3, 3 } }, + { { 7, 3, 13, 8, 7, 3, 12, 8, 7, 3, 11, 8, 7, 3, 12, 8 }, { 14, 31, 11, 2, 8, 3 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 3, 0, 1, 1 } }, + { { 1, 15, 14, 14, 2, 0, 14, 14, 2, 1, 15, 14, 2, 1, 0, 15 }, { 13, 57, 14, 6, 56, 14 }, { 3, 3, 2, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 12, 14, 1, 3, 12, 13, 1, 3, 12, 13, 2, 3, 13, 14, 1, 3 }, { 13, 59, 15, 8, 53, 15 }, { 3, 3, 0, 1, 3, 3, 0, 0, 3, 3, 3, 3, 0, 0, 0, 3 } }, + { { 11, 11, 10, 10, 12, 11, 10, 10, 14, 13, 11, 10, 0, 13, 12, 11 }, { 16, 32, 14, 5, 12, 6 }, { 3, 2, 2, 2, 3, 3, 3, 3, 3, 0, 0, 0, 3, 3, 0, 3 } }, + { { 3, 3, 3, 3, 2, 2, 2, 2, 1, 0, 1, 0, 0, 15, 15, 15 }, { 26, 53, 27, 22, 45, 23 }, { 3, 3, 2, 2, 3, 3, 3, 2, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 14, 14, 13, 13, 14, 14, 14, 14, 0, 15, 15, 15, 0, 0, 15, 15 }, { 18, 37, 18, 9, 17, 9 }, { 3, 0, 0, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 0, 14, 14, 14, 0, 15, 15, 14, 1, 1, 0, 15, 2, 2, 1, 0 }, { 3, 59, 17, 2, 58, 17 }, { 3, 3, 0, 0, 3, 3, 0, 1, 3, 3, 0, 0, 0, 0, 0, 0 } }, + { { 8, 11, 1, 7, 8, 12, 1, 7, 8, 13, 2, 7, 8, 13, 3, 7 }, { 14, 29, 10, 1, 4, 2 }, { 3, 3, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0, 3 } }, + { { 15, 15, 0, 0, 14, 14, 15, 15, 12, 12, 13, 13, 11, 11, 12, 12 }, { 19, 38, 18, 7, 16, 8 }, { 0, 3, 2, 2, 0, 3, 2, 2, 1, 0, 3, 2, 1, 0, 3, 2 } }, + { { 14, 14, 15, 0, 14, 15, 0, 1, 15, 0, 1, 2, 0, 1, 2, 2 }, { 2, 60, 17, 1, 58, 17 }, { 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 0, 0, 3, 3, 0, 0 } }, + { { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }, { 18, 37, 17, 3, 6, 3 }, { 3, 0, 0, 3, 0, 0, 3, 3, 0, 3, 3, 3, 3, 2, 2, 3 } }, + { { 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 13, 14, 15, 15 }, { 16, 31, 15, 5, 11, 6 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 3, 0, 1, 1 } }, + { { 14, 13, 12, 12, 15, 14, 12, 12, 15, 14, 13, 12, 14, 14, 13, 12 }, { 16, 33, 16, 6, 13, 6 }, { 0, 3, 2, 2, 1, 0, 3, 2, 1, 0, 3, 3, 1, 0, 0, 3 } }, + { { 0, 15, 15, 0, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 4, 4 }, { 27, 54, 27, 22, 45, 22 }, { 1, 1, 0, 3, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 15, 0, 1, 2, 14, 15, 0, 2, 13, 13, 15, 0, 12, 12, 14, 15 }, { 23, 49, 23, 19, 40, 20 }, { 3, 0, 0, 3, 0, 0, 3, 3, 1, 3, 3, 3, 0, 3, 3, 0 } }, + { { 0, 1, 2, 3, 15, 0, 3, 3, 15, 1, 3, 3, 0, 1, 2, 3 }, { 26, 54, 26, 22, 46, 23 }, { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3 } }, + { { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }, { 21, 49, 22, 3, 50, 20 }, { 3, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 3, 3, 2, 3, 3 } }, + { { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 11, 11 }, { 7, 15, 7, 5, 10, 5 }, { 3, 0, 0, 3, 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 14, 14, 15, 0, 14, 14, 15, 0, 14, 15, 15, 0, 15, 15, 0, 0 }, { 21, 52, 20, 4, 51, 19 }, { 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 } }, + { { 13, 12, 11, 11, 14, 13, 12, 12, 0, 15, 14, 13, 2, 2, 0, 15 }, { 23, 47, 22, 18, 37, 18 }, { 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0 } }, + { { 14, 15, 15, 0, 14, 14, 15, 15, 13, 14, 15, 15, 13, 14, 14, 15 }, { 17, 34, 17, 9, 19, 10 }, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 3, 3, 0, 1 } }, + { { 0, 13, 12, 12, 14, 13, 12, 11, 13, 12, 11, 11, 12, 12, 11, 11 }, { 17, 34, 16, 5, 11, 5 }, { 3, 3, 3, 3, 0, 3, 3, 3, 0, 3, 2, 3, 0, 3, 2, 3 } }, + { { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }, { 29, 56, 21, 5, 7, 1 }, { 3, 0, 0, 3, 3, 0, 0, 0, 3, 3, 0, 1, 2, 2, 0, 1 } }, + { { 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 11, 10, 11, 12, 13 }, { 21, 42, 19, 15, 33, 15 }, { 3, 2, 2, 2, 0, 0, 0, 0, 3, 3, 0, 3, 3, 3, 3, 3 } }, + { { 11, 12, 13, 15, 10, 11, 12, 13, 10, 10, 12, 12, 10, 10, 11, 11 }, { 13, 26, 12, 4, 8, 4 }, { 0, 0, 0, 3, 0, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3 } }, + { { 7, 7, 7, 6, 2, 2, 1, 0, 15, 14, 13, 12, 9, 9, 8, 8 }, { 20, 41, 18, 5, 11, 6 }, { 0, 3, 3, 3, 0, 3, 3, 0, 0, 3, 3, 0, 3, 3, 0, 0 } }, + { { 11, 11, 13, 14, 11, 12, 14, 15, 12, 13, 15, 1, 13, 14, 0, 2 }, { 23, 47, 22, 17, 37, 18 }, { 1, 0, 2, 3, 0, 3, 3, 3, 3, 3, 3, 0, 3, 0, 0, 0 } }, + { { 12, 12, 12, 11, 14, 15, 14, 14, 1, 1, 1, 0, 2, 3, 3, 2 }, { 18, 37, 17, 5, 12, 7 }, { 3, 2, 3, 3, 2, 2, 3, 0, 3, 3, 3, 0, 3, 3, 0, 1 } }, + { { 10, 10, 11, 12, 10, 10, 12, 13, 10, 11, 13, 14, 11, 12, 13, 1 }, { 17, 36, 16, 5, 9, 5 }, { 1, 0, 0, 1, 0, 3, 3, 0, 0, 3, 3, 3, 0, 0, 0, 0 } }, + { { 0, 15, 14, 13, 1, 0, 14, 13, 1, 0, 14, 13, 1, 0, 14, 13 }, { 14, 50, 19, 4, 50, 19 }, { 3, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 2, 3, 0 } }, + { { 5, 5, 3, 0, 4, 3, 1, 15, 0, 15, 13, 11, 14, 12, 9, 9 }, { 16, 33, 14, 7, 17, 9 }, { 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 1, 0, 3, 3 } }, + { { 2, 15, 12, 11, 13, 12, 11, 11, 11, 11, 10, 10, 11, 10, 10, 10 }, { 19, 40, 18, 13, 29, 14 }, { 3, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3, 0, 3, 3, 3 } }, + { { 9, 8, 8, 8, 13, 12, 11, 11, 0, 0, 15, 15, 6, 7, 6, 6 }, { 16, 33, 14, 7, 17, 9 }, { 3, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } }, + { { 3, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 3, 3, 2, 2 }, { 15, 31, 15, 14, 30, 15 }, { 0, 0, 0, 3, 0, 1, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0 } }, +}; + +inline constexpr Bc6State BC6_DICTIONARY[255] = { + { { { 32768, 33088, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768 } }, + { { { 62592, 62592, 59520 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 24576, 32768, 24576, 24576, 24576, 24576, 24576, 32768, 24576, 32768, 24576, 24576, 24576, 24576, 24576 } }, + { { { 32768, 33536, 62336 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576, 32768, 24576 } }, + { { { 62144, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768 } }, + { { { 32768, 32768, 32768 }, { 32768, 32768, 63488 }, { 32768, 32768, 32768 }, { 32768, 32768, 63488 } }, { 32768, 0, 24576, 57344, 40960, 8192, 16384, 49152, 49152, 16384, 8192, 40960, 57344, 24576, 0, 32768 } }, + { { { 58176, 58176, 57856 }, { 34816, 36864, 36864 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 16384, 16384, 40960, 32768, 16384, 16384, 40960, 32768, 16384, 16384, 40960, 40960, 16384, 16384, 40960 } }, + { { { 53760, 52992, 52480 }, { 37888, 43008, 45056 }, { 39936, 47104, 45056 }, { 38912, 43008, 43008 } }, { 40960, 32768, 32768, 24576, 40960, 32768, 32768, 24576, 40960, 32768, 32768, 24576, 40960, 32768, 32768, 24576 } }, + { { { 64128, 64128, 64256 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 49152, 24576, 8192, 32768, 49152, 16384, 8192, 40960, 40960, 8192, 16384, 49152, 32768, 8192, 24576, 49152 } }, + { { { 52864, 54688, 52000 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 }, { 32768, 36864, 36864 } }, { 32768, 32768, 32768, 32768, 24576, 24576, 24576, 24576, 32768, 32768, 32768, 32768, 24576, 24576, 24576, 24576 } }, + { { { 52608, 54272, 51840 }, { 34816, 40960, 36864 }, { 36864, 36864, 36864 }, { 34816, 36864, 36864 } }, { 32768, 49152, 0, 16384, 40960, 57344, 8192, 24576, 24576, 8192, 57344, 40960, 16384, 0, 49152, 32768 } }, + { { { 63904, 63936, 63968 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 }, { 32768, 32768, 36864 } }, { 32768, 40960, 24576, 16384, 49152, 57344, 8192, 0, 0, 8192, 57344, 49152, 16384, 24576, 40960, 32768 } }, + { { { 48768, 49024, 51456 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 }, { 32768, 32768, 32768 } }, { 32768, 16384, 57344, 24576, 32768, 16384, 57344, 24576, 32768, 16384, 57344, 24576, 32768, 16384, 57344, 24576 } }, + { { { 57344, 57344, 55296 }, { 26624, 26624, 25600 }, { 22528, 22528, 21504 }, { 25600, 25600, 25600 } }, { 40960, 32768, 16384, 24576, 57344, 49152, 0, 8192, 8192, 0, 49152, 57344, 24576, 16384, 32768, 40960 } }, + { { { 55936, 55936, 54272 }, { 20480, 22528, 20480 }, { 12288, 16384, 16384 }, { 18432, 20480, 20480 } }, { 32768, 0, 24576, 57344, 40960, 8192, 16384, 49152, 49152, 16384, 8192, 40960, 57344, 24576, 0, 32768 } }, + { { { 51712, 51200, 53248 }, { 38912, 45056, 45056 }, { 36864, 40960, 38912 }, { 37888, 43008, 43008 } }, { 32768, 0, 32768, 24576, 32768, 0, 32768, 24576, 32768, 0, 32768, 24576, 32768, 0, 32768, 24576 } }, + { { { 53600, 54240, 53152 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 } }, { 32768, 57344, 16384, 16384, 57344, 8192, 16384, 8192, 8192, 16384, 8192, 49152, 16384, 8192, 57344, 32768 } }, + { { { 57088, 56704, 55552 }, { 20480, 20480, 20480 }, { 14336, 16384, 16384 }, { 18432, 20480, 20480 } }, { 32768, 40960, 49152, 57344, 57344, 8192, 16384, 24576, 24576, 16384, 8192, 0, 57344, 49152, 40960, 32768 } }, + { { { 56576, 56320, 54784 }, { 26624, 20480, 20480 }, { 23552, 14336, 16384 }, { 26624, 18432, 20480 } }, { 32768, 49152, 8192, 16384, 57344, 8192, 16384, 8192, 16384, 16384, 0, 49152, 16384, 0, 49152, 32768 } }, + { { { 56064, 56064, 54528 }, { 26624, 20480, 18432 }, { 24576, 14336, 16384 }, { 26624, 18432, 20480 } }, { 57344, 57344, 0, 8192, 57344, 57344, 0, 0, 0, 0, 57344, 57344, 0, 0, 57344, 57344 } }, + { { { 57280, 58944, 55168 }, { 24576, 24576, 24576 }, { 18432, 16384, 12288 }, { 22528, 20480, 20480 } }, { 32768, 16384, 16384, 40960, 40960, 16384, 16384, 40960, 40960, 16384, 16384, 40960, 40960, 16384, 16384, 40960 } }, + { { { 56576, 56448, 55424 }, { 45056, 45056, 43008 }, { 49152, 49152, 47104 }, { 43008, 43008, 43008 } }, { 32768, 40960, 40960, 40960, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 40960, 40960, 40960, 40960 } }, + { { { 55552, 57024, 55296 }, { 40960, 38912, 40960 }, { 45056, 43008, 43008 }, { 40960, 38912, 40960 } }, { 32768, 40960, 40960, 57344, 40960, 49152, 57344, 0, 49152, 0, 8192, 16384, 8192, 16384, 16384, 24576 } }, + { { { 60032, 61056, 59136 }, { 22528, 22528, 20480 }, { 18432, 18432, 14336 }, { 20480, 24576, 20480 } }, { 40960, 57344, 8192, 24576, 32768, 49152, 0, 16384, 16384, 0, 49152, 32768, 24576, 8192, 57344, 40960 } }, + { { { 59520, 59840, 59008 }, { 18432, 18432, 18432 }, { 22528, 22528, 22528 }, { 14336, 20480, 20480 } }, { 49152, 0, 49152, 16384, 40960, 0, 49152, 16384, 40960, 0, 49152, 16384, 40960, 0, 49152, 16384 } }, + { { { 54912, 54656, 53504 }, { 49152, 47104, 49152 }, { 14336, 22528, 24576 }, { 47104, 43008, 43008 } }, { 32768, 40960, 40960, 40960, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 40960, 40960, 40960, 40960 } }, + { { { 60800, 60992, 62656 }, { 45056, 45056, 36864 }, { 40960, 40960, 34816 }, { 38912, 38912, 34816 } }, { 49152, 49152, 40960, 40960, 16384, 16384, 8192, 8192, 8192, 8192, 16384, 16384, 40960, 40960, 40960, 49152 } }, + { { { 63936, 64320, 64640 }, { 38912, 57344, 53248 }, { 38912, 61440, 49152 }, { 36864, 61440, 57344 } }, { 49152, 0, 8192, 16384, 40960, 40960, 49152, 57344, 57344, 49152, 40960, 40960, 16384, 8192, 0, 49152 } }, + { { { 56064, 55808, 55040 }, { 16384, 16384, 16384 }, { 18432, 20480, 22528 }, { 40960, 40960, 36864 } }, { 32768, 40960, 49152, 0, 0, 8192, 16384, 24576, 16384, 16384, 8192, 0, 0, 49152, 40960, 40960 } }, + { { { 56320, 55808, 54272 }, { 24576, 24576, 22528 }, { 26624, 25600, 24576 }, { 24576, 23552, 21504 } }, { 32768, 49152, 0, 16384, 49152, 0, 16384, 16384, 0, 16384, 16384, 0, 16384, 16384, 0, 32768 } }, + { { { 54912, 53952, 51584 }, { 24576, 22528, 24576 }, { 18432, 16384, 20480 }, { 20480, 22528, 24576 } }, { 49152, 40960, 16384, 16384, 0, 57344, 0, 8192, 8192, 0, 49152, 57344, 16384, 16384, 40960, 40960 } }, + { { { 54976, 51200, 50112 }, { 20480, 22528, 22528 }, { 20480, 16384, 18432 }, { 22528, 22528, 22528 } }, { 32768, 40960, 40960, 49152, 40960, 49152, 57344, 8192, 49152, 0, 8192, 16384, 8192, 16384, 16384, 16384 } }, + { { { 54016, 54016, 51968 }, { 38912, 49152, 53248 }, { 27648, 22528, 8192 }, { 36864, 45056, 51200 } }, { 32768, 49152, 0, 16384, 49152, 0, 16384, 16384, 8192, 16384, 16384, 0, 16384, 16384, 57344, 32768 } }, + { { { 52992, 53248, 51456 }, { 25600, 14336, 14336 }, { 26624, 16384, 16384 }, { 35840, 38912, 51200 } }, { 57344, 57344, 49152, 40960, 0, 57344, 57344, 49152, 0, 57344, 57344, 49152, 0, 57344, 57344, 57344 } }, + { { { 59456, 60480, 57152 }, { 38912, 36864, 36864 }, { 40960, 40960, 45056 }, { 38912, 36864, 40960 } }, { 49152, 0, 8192, 16384, 40960, 57344, 8192, 16384, 16384, 0, 49152, 40960, 16384, 8192, 57344, 40960 } }, + { { { 61824, 62080, 60992 }, { 34816, 34816, 24576 }, { 34816, 34816, 18432 }, { 34816, 32768, 24576 } }, { 57344, 40960, 49152, 16384, 0, 40960, 49152, 8192, 8192, 49152, 40960, 57344, 16384, 57344, 40960, 49152 } }, + { { { 55552, 54528, 53760 }, { 27648, 14336, 10240 }, { 37888, 51200, 53248 }, { 36864, 45056, 51200 } }, { 40960, 49152, 0, 24576, 49152, 40960, 49152, 8192, 8192, 49152, 40960, 49152, 24576, 0, 49152, 40960 } }, + { { { 54528, 54528, 53632 }, { 16384, 16384, 14336 }, { 16384, 20480, 20480 }, { 14336, 20480, 18432 } }, { 40960, 49152, 8192, 24576, 49152, 32768, 49152, 8192, 8192, 49152, 32768, 49152, 24576, 8192, 49152, 40960 } }, + { { { 55040, 55040, 53504 }, { 25600, 14336, 14336 }, { 36864, 40960, 43008 }, { 27648, 16384, 16384 } }, { 32768, 8192, 16384, 0, 49152, 16384, 16384, 57344, 8192, 16384, 8192, 40960, 16384, 16384, 0, 32768 } }, + { { { 54272, 54272, 52480 }, { 25600, 14336, 16384 }, { 26624, 18432, 20480 }, { 25600, 14336, 18432 } }, { 32768, 49152, 0, 16384, 40960, 57344, 8192, 16384, 49152, 0, 16384, 57344, 57344, 8192, 16384, 40960 } }, + { { { 62272, 32768, 61440 }, { 32768, 32768, 34816 }, { 32768, 32768, 38912 }, { 32768, 32768, 36864 } }, { 57344, 8192, 16384, 16384, 40960, 49152, 0, 8192, 40960, 40960, 49152, 0, 16384, 57344, 40960, 40960 } }, + { { { 52736, 51712, 51200 }, { 37888, 38912, 37888 }, { 44032, 46080, 44032 }, { 38912, 39936, 38912 } }, { 57344, 16384, 57344, 40960, 57344, 8192, 57344, 40960, 49152, 0, 0, 40960, 40960, 0, 8192, 49152 } }, + { { { 59232, 59296, 55744 }, { 36864, 40960, 40960 }, { 36864, 45056, 40960 }, { 34816, 40960, 40960 } }, { 57344, 49152, 32768, 32768, 57344, 57344, 32768, 32768, 57344, 57344, 32768, 32768, 0, 57344, 40960, 32768 } }, + { { { 56704, 57536, 55488 }, { 22528, 20480, 16384 }, { 26624, 24576, 20480 }, { 26624, 24576, 24576 } }, { 32768, 40960, 49152, 57344, 49152, 57344, 8192, 16384, 8192, 16384, 16384, 16384, 16384, 16384, 57344, 40960 } }, + { { { 59552, 32800, 32800 }, { 59392, 32768, 32768 }, { 59392, 32768, 32768 }, { 57344, 32768, 32768 } }, { 32768, 0, 16384, 16384, 8192, 16384, 16384, 8192, 16384, 8192, 57344, 49152, 57344, 49152, 40960, 40960 } }, + { { { 57600, 57856, 56448 }, { 40960, 40960, 43008 }, { 43008, 43008, 45056 }, { 40960, 40960, 43008 } }, { 57344, 49152, 40960, 40960, 8192, 0, 57344, 57344, 16384, 16384, 8192, 8192, 16384, 8192, 49152, 40960 } }, + { { { 40960, 38912, 36864 }, { 38912, 36864, 37888 }, { 38912, 35840, 34816 }, { 38912, 36864, 35840 } }, { 57344, 16384, 49152, 16384, 49152, 8192, 49152, 8192, 40960, 8192, 40960, 0, 40960, 0, 40960, 49152 } }, + { { { 57856, 57856, 56320 }, { 18432, 17408, 15360 }, { 16384, 14336, 13312 }, { 19456, 18432, 16384 } }, { 32768, 49152, 8192, 16384, 40960, 49152, 0, 16384, 40960, 57344, 0, 16384, 40960, 8192, 8192, 16384 } }, + { { { 41984, 37888, 36864 }, { 39936, 35840, 35840 }, { 39936, 35840, 34816 }, { 40960, 36864, 36864 } }, { 32768, 16384, 16384, 16384, 49152, 0, 8192, 8192, 8192, 49152, 49152, 49152, 16384, 40960, 40960, 40960 } }, + { { { 57600, 57344, 55552 }, { 18432, 16384, 17408 }, { 18432, 18432, 17408 }, { 18432, 18432, 17408 } }, { 32768, 16384, 49152, 40960, 0, 16384, 49152, 40960, 16384, 16384, 49152, 40960, 16384, 8192, 49152, 40960 } }, + { { { 47104, 46080, 41984 }, { 51200, 50176, 45056 }, { 54272, 52224, 50176 }, { 52224, 50176, 44032 } }, { 32768, 40960, 0, 16384, 40960, 49152, 8192, 16384, 40960, 0, 16384, 8192, 57344, 8192, 16384, 40960 } }, + { { { 62144, 62592, 63488 }, { 45056, 43008, 43008 }, { 43008, 43008, 43008 }, { 38912, 38912, 38912 } }, { 32768, 8192, 16384, 8192, 16384, 16384, 8192, 57344, 16384, 0, 49152, 40960, 0, 57344, 40960, 40960 } }, + { { { 49664, 49664, 48128 }, { 23552, 23552, 22528 }, { 23552, 24576, 23552 }, { 43008, 38912, 39936 } }, { 32768, 57344, 16384, 16384, 16384, 16384, 8192, 8192, 49152, 49152, 49152, 49152, 40960, 40960, 40960, 40960 } }, + { { { 59008, 58752, 58240 }, { 18432, 20480, 18432 }, { 45056, 38912, 38912 }, { 18432, 22528, 22528 } }, { 32768, 40960, 40960, 40960, 49152, 57344, 57344, 57344, 16384, 16384, 16384, 16384, 16384, 8192, 49152, 40960 } }, + { { { 49664, 46592, 47104 }, { 37888, 36864, 36864 }, { 38912, 38912, 37888 }, { 36864, 35840, 34816 } }, { 32768, 40960, 40960, 57344, 40960, 49152, 0, 8192, 57344, 0, 16384, 16384, 16384, 16384, 0, 40960 } }, + { { { 47104, 45056, 46592 }, { 39936, 38912, 37888 }, { 36864, 35840, 34816 }, { 38912, 37888, 37888 } }, { 32768, 32768, 32768, 40960, 16384, 16384, 16384, 16384, 40960, 40960, 40960, 40960, 16384, 16384, 24576, 24576 } }, + { { { 58112, 57536, 56768 }, { 47104, 45056, 47104 }, { 18432, 20480, 16384 }, { 18432, 20480, 18432 } }, { 32768, 49152, 57344, 8192, 16384, 49152, 0, 16384, 16384, 0, 57344, 16384, 8192, 0, 49152, 40960 } }, + { { { 59392, 59712, 59776 }, { 16384, 18432, 12288 }, { 16384, 20480, 20480 }, { 14336, 26624, 36864 } }, { 57344, 40960, 57344, 16384, 8192, 49152, 49152, 16384, 16384, 49152, 40960, 0, 16384, 57344, 40960, 49152 } }, + { { { 544, 1408, 2112 }, { 20480, 16384, 16384 }, { 22528, 16384, 12288 }, { 22528, 16384, 16384 } }, { 32768, 16384, 8192, 57344, 0, 16384, 0, 49152, 16384, 8192, 57344, 40960, 16384, 0, 49152, 32768 } }, + { { { 32768, 32768, 58752 }, { 34816, 32768, 53248 }, { 34816, 32768, 53248 }, { 34816, 32768, 49152 } }, { 57344, 40960, 0, 16384, 16384, 8192, 8192, 16384, 57344, 57344, 57344, 0, 49152, 40960, 40960, 40960 } }, + { { { 58304, 58176, 60416 }, { 47104, 43008, 43008 }, { 47104, 43008, 43008 }, { 49152, 36864, 28672 } }, { 57344, 57344, 57344, 57344, 57344, 57344, 57344, 57344, 49152, 57344, 57344, 57344, 49152, 57344, 57344, 57344 } }, + { { { 53760, 53760, 40448 }, { 19456, 22528, 32768 }, { 17408, 16384, 34816 }, { 18432, 20480, 34816 } }, { 57344, 0, 16384, 16384, 40960, 40960, 49152, 49152, 0, 8192, 16384, 16384, 40960, 40960, 49152, 49152 } }, + { { { 53504, 53760, 51712 }, { 38912, 53248, 55296 }, { 36864, 49152, 51200 }, { 28672, 22528, 20480 } }, { 57344, 8192, 16384, 8192, 49152, 57344, 16384, 0, 40960, 57344, 8192, 49152, 40960, 57344, 16384, 40960 } }, + { { { 58304, 57536, 56768 }, { 18432, 18432, 16384 }, { 22528, 20480, 20480 }, { 38912, 38912, 38912 } }, { 32768, 8192, 57344, 40960, 49152, 16384, 57344, 40960, 8192, 16384, 0, 40960, 16384, 16384, 8192, 49152 } }, + { { { 51200, 50176, 51200 }, { 57344, 57344, 57344 }, { 57344, 59392, 58368 }, { 57344, 58368, 57344 } }, { 32768, 16384, 32768, 24576, 32768, 16384, 32768, 24576, 32768, 16384, 32768, 24576, 32768, 16384, 40960, 24576 } }, + { { { 53728, 50624, 50240 }, { 20480, 12288, 16384 }, { 20480, 12288, 12288 }, { 22528, 16384, 16384 } }, { 32768, 49152, 0, 16384, 16384, 8192, 57344, 49152, 16384, 8192, 57344, 40960, 8192, 8192, 57344, 40960 } }, + { { { 53888, 53760, 52864 }, { 16384, 18432, 14336 }, { 43008, 40960, 43008 }, { 16384, 20480, 16384 } }, { 57344, 49152, 49152, 40960, 16384, 16384, 8192, 0, 57344, 49152, 49152, 40960, 16384, 8192, 0, 49152 } }, + { { { 60928, 60928, 61312 }, { 47104, 49152, 45056 }, { 43008, 43008, 40960 }, { 40960, 43008, 40960 } }, { 40960, 40960, 40960, 40960, 49152, 49152, 57344, 49152, 16384, 16384, 16384, 16384, 16384, 0, 49152, 40960 } }, + { { { 49920, 50176, 48640 }, { 39936, 51200, 53248 }, { 35840, 57344, 24576 }, { 39936, 47104, 47104 } }, { 57344, 16384, 57344, 49152, 8192, 16384, 57344, 49152, 16384, 16384, 57344, 40960, 8192, 8192, 49152, 40960 } }, + { { { 59584, 60384, 61888 }, { 4096, 8192, 10240 }, { 4096, 8192, 16384 }, { 0, 4096, 6144 } }, { 57344, 32768, 57344, 40960, 0, 40960, 0, 40960, 8192, 40960, 8192, 49152, 16384, 49152, 16384, 49152 } }, + { { { 49664, 48128, 46592 }, { 38912, 39936, 39936 }, { 35840, 36864, 35840 }, { 40960, 43008, 45056 } }, { 32768, 32768, 32768, 57344, 32768, 32768, 32768, 57344, 32768, 32768, 32768, 0, 32768, 32768, 32768, 8192 } }, + { { { 59136, 60000, 61760 }, { 57344, 53248, 55296 }, { 61440, 57344, 55296 }, { 61440, 53248, 45056 } }, { 32768, 40960, 40960, 16384, 40960, 49152, 0, 16384, 40960, 49152, 8192, 16384, 40960, 49152, 8192, 16384 } }, + { { { 59584, 60160, 60416 }, { 14336, 20480, 12288 }, { 10240, 26624, 36864 }, { 16384, 20480, 20480 } }, { 49152, 0, 8192, 16384, 40960, 49152, 0, 8192, 40960, 49152, 57344, 8192, 40960, 40960, 40960, 49152 } }, + { { { 57472, 56960, 56192 }, { 47104, 45056, 43008 }, { 14336, 18432, 22528 }, { 16384, 18432, 20480 } }, { 32768, 40960, 40960, 40960, 0, 0, 0, 40960, 16384, 16384, 8192, 49152, 16384, 16384, 16384, 49152 } }, + { { { 58048, 57984, 57280 }, { 47104, 45056, 47104 }, { 16384, 22528, 22528 }, { 47104, 43008, 43008 } }, { 49152, 49152, 40960, 40960, 16384, 16384, 8192, 0, 57344, 0, 16384, 16384, 40960, 40960, 49152, 49152 } }, + { { { 32768, 59392, 32768 }, { 34816, 0, 32768 }, { 34816, 0, 32768 }, { 34816, 0, 32768 } }, { 32768, 8192, 16384, 8192, 40960, 8192, 16384, 8192, 40960, 8192, 16384, 8192, 40960, 0, 8192, 40960 } }, + { { { 55552, 55200, 53120 }, { 28672, 8192, 8192 }, { 34816, 36864, 40960 }, { 34816, 36864, 40960 } }, { 32768, 49152, 8192, 16384, 40960, 57344, 8192, 16384, 40960, 57344, 8192, 8192, 40960, 40960, 49152, 40960 } }, + { { { 54912, 54528, 53632 }, { 49152, 49152, 49152 }, { 45056, 43008, 40960 }, { 22528, 22528, 22528 } }, { 32768, 57344, 8192, 16384, 8192, 16384, 16384, 16384, 16384, 8192, 16384, 8192, 40960, 40960, 40960, 40960 } }, + { { { 56576, 56064, 54528 }, { 37888, 47104, 49152 }, { 26624, 12288, 10240 }, { 26624, 18432, 16384 } }, { 57344, 49152, 40960, 49152, 8192, 8192, 8192, 8192, 16384, 8192, 8192, 8192, 0, 57344, 40960, 40960 } }, + { { { 58848, 59712, 62208 }, { 49152, 0, 8192 }, { 53248, 63488, 4096 }, { 53248, 2048, 24576 } }, { 49152, 40960, 40960, 40960, 8192, 57344, 49152, 40960, 16384, 8192, 57344, 40960, 16384, 16384, 8192, 49152 } }, + { { { 44544, 38912, 41728 }, { 59392, 47104, 47104 }, { 57344, 34816, 30720 }, { 57344, 45056, 47104 } }, { 32768, 49152, 16384, 16384, 40960, 49152, 8192, 16384, 49152, 49152, 0, 8192, 16384, 0, 49152, 49152 } }, + { { { 54080, 53952, 52352 }, { 36864, 36864, 36864 }, { 38912, 38912, 38912 }, { 36864, 36864, 36864 } }, { 57344, 49152, 57344, 0, 49152, 49152, 8192, 8192, 49152, 57344, 16384, 16384, 16384, 8192, 57344, 40960 } }, + { { { 52096, 51712, 50688 }, { 49152, 49152, 49152 }, { 55296, 53248, 53248 }, { 47104, 49152, 47104 } }, { 32768, 49152, 0, 16384, 40960, 49152, 0, 16384, 49152, 49152, 57344, 8192, 24576, 57344, 40960, 40960 } }, + { { { 55424, 55424, 54912 }, { 12288, 16384, 16384 }, { 51200, 36864, 30720 }, { 14336, 18432, 16384 } }, { 32768, 49152, 4096, 20480, 36864, 53248, 8192, 20480, 40960, 57344, 12288, 24576, 45056, 61440, 12288, 24576 } }, + { { { 57344, 57344, 56320 }, { 37888, 37888, 39936 }, { 20480, 21504, 21504 }, { 22528, 24576, 22528 } }, { 32768, 49152, 8192, 16384, 40960, 49152, 49152, 57344, 16384, 16384, 16384, 8192, 49152, 49152, 49152, 40960 } }, + { { { 49152, 49152, 48128 }, { 45056, 45056, 46080 }, { 27648, 27648, 26624 }, { 38912, 39936, 38912 } }, { 40960, 57344, 8192, 16384, 16384, 40960, 57344, 8192, 49152, 16384, 40960, 57344, 32768, 57344, 16384, 49152 } }, + { { { 54656, 53632, 52128 }, { 40960, 45056, 45056 }, { 38912, 40960, 45056 }, { 26624, 12288, 28672 } }, { 57344, 8192, 49152, 57344, 49152, 0, 8192, 0, 40960, 49152, 8192, 16384, 40960, 49152, 0, 16384 } }, + { { { 55936, 55488, 54208 }, { 47104, 47104, 47104 }, { 55296, 55296, 55296 }, { 43008, 43008, 43008 } }, { 32768, 49152, 16384, 16384, 40960, 57344, 16384, 0, 40960, 57344, 16384, 49152, 40960, 49152, 16384, 40960 } }, + { { { 1664, 2528, 3264 }, { 43008, 45056, 45056 }, { 40960, 40960, 45056 }, { 38912, 40960, 40960 } }, { 57344, 8192, 16384, 57344, 40960, 8192, 8192, 49152, 49152, 8192, 57344, 40960, 16384, 8192, 57344, 40960 } }, + { { { 51200, 53248, 53248 }, { 52224, 54272, 53248 }, { 33792, 33792, 33792 }, { 39936, 40960, 40960 } }, { 57344, 40960, 40960, 16384, 8192, 57344, 40960, 49152, 16384, 8192, 57344, 40960, 16384, 16384, 8192, 49152 } }, + { { { 58944, 60352, 61248 }, { 47104, 45056, 43008 }, { 47104, 36864, 26624 }, { 47104, 43008, 47104 } }, { 40960, 40960, 40960, 49152, 8192, 16384, 16384, 16384, 16384, 8192, 57344, 40960, 16384, 8192, 57344, 40960 } }, + { { { 63712, 64704, 256 }, { 59392, 61440, 61440 }, { 20480, 4096, 4096 }, { 40960, 49152, 49152 } }, { 49152, 40960, 49152, 8192, 40960, 49152, 57344, 16384, 40960, 0, 8192, 16384, 49152, 0, 8192, 16384 } }, + { { { 54432, 55072, 52512 }, { 34816, 45056, 24576 }, { 34816, 40960, 16384 }, { 34816, 40960, 4096 } }, { 57344, 49152, 40960, 40960, 8192, 0, 57344, 49152, 49152, 8192, 8192, 0, 40960, 0, 16384, 16384 } }, + { { { 56320, 56000, 55104 }, { 47104, 47104, 47104 }, { 43008, 43008, 43008 }, { 24576, 22528, 24576 } }, { 57344, 0, 16384, 8192, 57344, 49152, 8192, 0, 40960, 49152, 49152, 40960, 49152, 16384, 57344, 40960 } }, + { { { 59872, 59776, 59072 }, { 24576, 4096, 61440 }, { 24576, 8192, 61440 }, { 26624, 4096, 57344 } }, { 32768, 40960, 0, 16384, 8192, 8192, 16384, 16384, 49152, 57344, 57344, 0, 40960, 40960, 40960, 49152 } }, + { { { 36352, 24576, 1024 }, { 10240, 6144, 5120 }, { 53248, 57344, 59392 }, { 10240, 7168, 6144 } }, { 32768, 0, 57344, 16384, 49152, 16384, 49152, 8192, 57344, 16384, 40960, 57344, 57344, 16384, 40960, 40960 } }, + { { { 59328, 59776, 59776 }, { 49152, 40960, 47104 }, { 45056, 43008, 47104 }, { 6144, 28672, 36864 } }, { 57344, 49152, 40960, 40960, 40960, 0, 57344, 57344, 49152, 0, 8192, 8192, 8192, 8192, 8192, 16384 } }, + { { { 55168, 55296, 54912 }, { 8192, 10240, 14336 }, { 14336, 18432, 16384 }, { 49152, 36864, 28672 } }, { 57344, 49152, 40960, 49152, 8192, 57344, 57344, 16384, 16384, 0, 0, 8192, 49152, 40960, 49152, 49152 } }, + { { { 57536, 57024, 56256 }, { 49152, 45056, 49152 }, { 47104, 43008, 45056 }, { 22528, 22528, 22528 } }, { 40960, 16384, 49152, 32768, 57344, 40960, 16384, 57344, 8192, 57344, 40960, 16384, 16384, 8192, 0, 49152 } }, + { { { 59840, 60352, 61248 }, { 8192, 18432, 16384 }, { 53248, 36864, 24576 }, { 14336, 22528, 16384 } }, { 32768, 40960, 16384, 57344, 57344, 0, 57344, 49152, 16384, 8192, 49152, 40960, 16384, 16384, 49152, 40960 } }, + { { { 55296, 55296, 53760 }, { 12288, 16384, 12288 }, { 12288, 16384, 16384 }, { 18432, 26624, 34816 } }, { 49152, 40960, 16384, 49152, 0, 49152, 16384, 49152, 8192, 49152, 8192, 40960, 8192, 49152, 8192, 40960 } }, + { { { 47360, 46464, 46336 }, { 51200, 51200, 53248 }, { 45056, 45056, 45056 }, { 47104, 47104, 47104 } }, { 32768, 40960, 40960, 40960, 49152, 49152, 40960, 32768, 16384, 8192, 49152, 40960, 24576, 16384, 57344, 40960 } }, + { { { 58176, 57984, 57792 }, { 16384, 18432, 14336 }, { 53248, 38912, 38912 }, { 18432, 20480, 20480 } }, { 57344, 8192, 8192, 0, 40960, 49152, 57344, 0, 16384, 16384, 8192, 0, 8192, 0, 49152, 40960 } }, + { { { 55136, 54464, 52416 }, { 36864, 40960, 40960 }, { 34816, 40960, 40960 }, { 30720, 49152, 32768 } }, { 32768, 16384, 16384, 16384, 49152, 49152, 0, 0, 8192, 0, 57344, 49152, 16384, 16384, 16384, 40960 } }, + { { { 54784, 54784, 53632 }, { 14336, 18432, 14336 }, { 12288, 28672, 34816 }, { 14336, 16384, 18432 } }, { 32768, 16384, 49152, 40960, 49152, 57344, 8192, 49152, 0, 0, 8192, 16384, 8192, 8192, 8192, 16384 } }, + { { { 59456, 59904, 60288 }, { 51200, 40960, 49152 }, { 10240, 28672, 36864 }, { 45056, 43008, 45056 } }, { 49152, 16384, 57344, 40960, 0, 8192, 8192, 8192, 57344, 8192, 8192, 8192, 49152, 57344, 49152, 40960 } }, + { { { 57216, 57088, 56512 }, { 47104, 47104, 49152 }, { 16384, 24576, 24576 }, { 43008, 43008, 43008 } }, { 32768, 49152, 40960, 49152, 49152, 8192, 8192, 8192, 49152, 0, 16384, 16384, 49152, 57344, 8192, 16384 } }, + { { { 56320, 55680, 55040 }, { 16384, 20480, 14336 }, { 45056, 40960, 45056 }, { 45056, 43008, 49152 } }, { 32768, 57344, 24576, 49152, 32768, 57344, 16384, 40960, 40960, 0, 8192, 40960, 40960, 8192, 8192, 32768 } }, + { { { 62368, 64160, 64032 }, { 32768, 0, 30720 }, { 36864, 45056, 22528 }, { 32768, 57344, 28672 } }, { 32768, 49152, 16384, 16384, 40960, 49152, 16384, 0, 40960, 49152, 16384, 49152, 40960, 49152, 16384, 40960 } }, + { { { 63104, 62816, 63296 }, { 18432, 16384, 40960 }, { 16384, 24576, 36864 }, { 20480, 12288, 36864 } }, { 57344, 8192, 16384, 16384, 49152, 0, 8192, 16384, 40960, 57344, 0, 8192, 40960, 40960, 49152, 40960 } }, + { { { 56512, 56448, 55360 }, { 16384, 20480, 18432 }, { 40960, 38912, 38912 }, { 45056, 43008, 47104 } }, { 49152, 16384, 16384, 8192, 49152, 16384, 16384, 0, 40960, 8192, 8192, 49152, 49152, 16384, 0, 40960 } }, + { { { 52992, 54400, 51968 }, { 30720, 0, 61440 }, { 34816, 36864, 36864 }, { 34816, 36864, 36864 } }, { 57344, 16384, 49152, 49152, 16384, 16384, 0, 0, 0, 0, 49152, 49152, 49152, 49152, 40960, 40960 } }, + { { { 59584, 33024, 44544 }, { 4096, 32768, 36864 }, { 61440, 32768, 38912 }, { 2048, 32768, 36864 } }, { 32768, 8192, 16384, 16384, 40960, 8192, 16384, 16384, 49152, 8192, 8192, 8192, 16384, 57344, 40960, 40960 } }, + { { { 62624, 61504, 61568 }, { 16384, 36864, 28672 }, { 18432, 36864, 36864 }, { 28672, 4096, 12288 } }, { 49152, 0, 16384, 16384, 16384, 40960, 49152, 0, 57344, 0, 8192, 40960, 40960, 49152, 49152, 49152 } }, + { { { 55872, 54080, 52736 }, { 22528, 20480, 20480 }, { 24576, 24576, 20480 }, { 38912, 40960, 45056 } }, { 32768, 49152, 40960, 49152, 16384, 8192, 0, 8192, 16384, 16384, 16384, 16384, 8192, 8192, 8192, 40960 } }, + { { { 54784, 54272, 53248 }, { 26624, 26624, 25600 }, { 40960, 40960, 43008 }, { 41984, 39936, 39936 } }, { 32768, 49152, 8192, 16384, 40960, 0, 8192, 49152, 49152, 8192, 57344, 40960, 16384, 8192, 49152, 40960 } }, + { { { 50176, 49152, 47104 }, { 40960, 41984, 43008 }, { 43008, 45056, 47104 }, { 36864, 36864, 36864 } }, { 32768, 16384, 49152, 40960, 49152, 8192, 49152, 40960, 8192, 0, 40960, 40960, 16384, 0, 40960, 40960 } }, + { { { 55232, 54752, 52992 }, { 40960, 45056, 45056 }, { 24576, 16384, 16384 }, { 38912, 40960, 40960 } }, { 49152, 40960, 49152, 0, 16384, 8192, 8192, 0, 0, 16384, 8192, 40960, 49152, 8192, 8192, 40960 } }, + { { { 61088, 61536, 62048 }, { 26624, 20480, 16384 }, { 26624, 16384, 16384 }, { 34816, 40960, 45056 } }, { 53248, 49152, 40960, 40960, 4096, 0, 57344, 49152, 12288, 12288, 4096, 0, 20480, 20480, 16384, 12288 } }, + { { { 41984, 41984, 41984 }, { 34816, 33792, 33792 }, { 56320, 56320, 55296 }, { 53248, 53248, 51200 } }, { 32768, 40960, 57344, 24576, 57344, 40960, 40960, 49152, 8192, 0, 49152, 40960, 16384, 16384, 8192, 49152 } }, + { { { 55552, 55552, 54912 }, { 14336, 16384, 14336 }, { 40960, 38912, 40960 }, { 16384, 18432, 16384 } }, { 57344, 49152, 49152, 16384, 49152, 40960, 49152, 8192, 57344, 57344, 8192, 49152, 8192, 16384, 8192, 40960 } }, + { { { 39936, 39936, 39936 }, { 56320, 56320, 56320 }, { 34816, 33792, 33792 }, { 57344, 57344, 56320 } }, { 57344, 57344, 0, 0, 49152, 57344, 57344, 57344, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 32768 } }, + { { { 48128, 47872, 46080 }, { 38912, 47104, 51200 }, { 37888, 47104, 47104 }, { 29696, 36864, 55296 } }, { 32768, 40960, 40960, 16384, 57344, 57344, 57344, 8192, 8192, 8192, 8192, 49152, 16384, 16384, 16384, 40960 } }, + { { { 59968, 60192, 61184 }, { 57344, 61440, 57344 }, { 57344, 0, 45056 }, { 61440, 0, 10240 } }, { 32768, 40960, 40960, 40960, 57344, 57344, 49152, 49152, 8192, 8192, 8192, 0, 16384, 16384, 16384, 16384 } }, + { { { 63264, 64128, 65376 }, { 40960, 49152, 49152 }, { 45056, 49152, 53248 }, { 26624, 0, 61440 } }, { 32768, 16384, 16384, 0, 40960, 57344, 57344, 49152, 49152, 0, 49152, 40960, 49152, 0, 16384, 40960 } }, + { { { 44800, 41728, 41984 }, { 58368, 45056, 49152 }, { 58368, 47104, 45056 }, { 55296, 34816, 30720 } }, { 49152, 40960, 49152, 24576, 57344, 40960, 40960, 49152, 8192, 57344, 40960, 40960, 16384, 8192, 57344, 40960 } }, + { { { 59648, 59328, 59968 }, { 26624, 36864, 43008 }, { 12288, 36864, 47104 }, { 24576, 34816, 47104 } }, { 32768, 40960, 57344, 57344, 32768, 32768, 57344, 57344, 32768, 32768, 0, 57344, 32768, 32768, 57344, 57344 } }, + { { { 59008, 46336, 56064 }, { 24576, 34816, 38912 }, { 14336, 32768, 43008 }, { 20480, 32768, 40960 } }, { 57344, 49152, 49152, 16384, 16384, 8192, 57344, 57344, 16384, 8192, 57344, 49152, 57344, 57344, 40960, 40960 } }, + { { { 45056, 44800, 41472 }, { 57344, 49152, 47104 }, { 13312, 26624, 30720 }, { 55296, 43008, 45056 } }, { 32768, 57344, 8192, 8192, 8192, 8192, 16384, 16384, 49152, 49152, 49152, 49152, 8192, 16384, 0, 49152 } }, + { { { 58112, 58048, 57536 }, { 18432, 20480, 20480 }, { 22528, 22528, 22528 }, { 43008, 36864, 38912 } }, { 32768, 40960, 49152, 49152, 16384, 57344, 0, 57344, 49152, 0, 8192, 8192, 40960, 49152, 8192, 16384 } }, + { { { 62976, 63744, 64960 }, { 24576, 8192, 12288 }, { 36864, 53248, 57344 }, { 26624, 8192, 8192 } }, { 32768, 49152, 0, 16384, 24576, 8192, 0, 57344, 49152, 49152, 40960, 40960, 40960, 40960, 40960, 40960 } }, + { { { 47616, 47360, 45568 }, { 38912, 47104, 51200 }, { 29696, 36864, 49152 }, { 37888, 47104, 49152 } }, { 40960, 57344, 8192, 24576, 32768, 40960, 49152, 0, 49152, 40960, 40960, 49152, 24576, 57344, 40960, 40960 } }, + { { { 53248, 51712, 48896 }, { 45056, 47104, 44032 }, { 51200, 53248, 52224 }, { 43008, 43008, 40960 } }, { 49152, 40960, 40960, 40960, 0, 57344, 49152, 49152, 40960, 16384, 8192, 0, 16384, 0, 40960, 16384 } }, + { { { 43520, 43008, 44032 }, { 45056, 46080, 44032 }, { 35840, 36864, 35840 }, { 53248, 53248, 51200 } }, { 32768, 49152, 16384, 49152, 57344, 57344, 16384, 49152, 8192, 8192, 16384, 40960, 16384, 8192, 16384, 40960 } }, + { { { 46592, 37376, 40960 }, { 15360, 36864, 36864 }, { 25600, 34816, 36864 }, { 16384, 35840, 38912 } }, { 32768, 16384, 57344, 40960, 40960, 16384, 57344, 40960, 40960, 16384, 57344, 40960, 49152, 16384, 57344, 40960 } }, + { { { 50688, 50176, 48128 }, { 41984, 43008, 45056 }, { 40960, 39936, 44032 }, { 27648, 27648, 25600 } }, { 32768, 16384, 8192, 49152, 40960, 16384, 0, 49152, 49152, 0, 57344, 49152, 16384, 57344, 49152, 40960 } }, + { { { 55808, 49664, 54912 }, { 55296, 40960, 51200 }, { 43008, 38912, 57344 }, { 49152, 34816, 26624 } }, { 32768, 57344, 8192, 8192, 8192, 8192, 8192, 0, 57344, 8192, 16384, 57344, 40960, 49152, 16384, 49152 } }, + { { { 51776, 47424, 48192 }, { 38912, 57344, 53248 }, { 36864, 53248, 53248 }, { 36864, 49152, 49152 } }, { 49152, 8192, 57344, 40960, 40960, 8192, 8192, 57344, 49152, 8192, 8192, 8192, 8192, 8192, 57344, 40960 } }, + { { { 50176, 49152, 48128 }, { 50176, 48128, 48128 }, { 52224, 51200, 51200 }, { 35840, 34816, 33792 } }, { 57344, 8192, 16384, 8192, 40960, 49152, 57344, 49152, 40960, 57344, 0, 49152, 0, 8192, 16384, 49152 } }, + { { { 54432, 51744, 51328 }, { 26624, 20480, 20480 }, { 26624, 20480, 20480 }, { 34816, 45056, 49152 } }, { 32768, 16384, 8192, 57344, 16384, 16384, 57344, 49152, 8192, 57344, 40960, 40960, 49152, 49152, 40960, 40960 } }, + { { { 49664, 49152, 48128 }, { 43008, 44032, 44032 }, { 51200, 53248, 54272 }, { 39936, 40960, 40960 } }, { 57344, 49152, 40960, 49152, 49152, 49152, 49152, 16384, 49152, 49152, 49152, 16384, 16384, 8192, 57344, 40960 } }, + { { { 58880, 57344, 55040 }, { 37888, 34816, 26624 }, { 38912, 34816, 14336 }, { 37888, 34816, 24576 } }, { 32768, 57344, 16384, 16384, 16384, 49152, 49152, 49152, 16384, 49152, 40960, 40960, 0, 49152, 49152, 40960 } }, + { { { 43520, 43264, 38912 }, { 58368, 49152, 47104 }, { 56320, 43008, 45056 }, { 11264, 26624, 30720 } }, { 32768, 40960, 0, 16384, 49152, 57344, 0, 57344, 57344, 0, 8192, 40960, 8192, 16384, 16384, 40960 } }, + { { { 60416, 60352, 31936 }, { 16384, 16384, 32768 }, { 16384, 14336, 32768 }, { 22528, 22528, 32768 } }, { 49152, 16384, 49152, 40960, 0, 49152, 8192, 40960, 8192, 49152, 8192, 49152, 16384, 0, 40960, 57344 } }, + { { { 56768, 56512, 55104 }, { 47104, 47104, 47104 }, { 40960, 40960, 40960 }, { 51200, 51200, 51200 } }, { 32768, 40960, 40960, 49152, 0, 49152, 49152, 0, 16384, 57344, 49152, 16384, 16384, 8192, 0, 49152 } }, + { { { 47104, 46848, 44288 }, { 16384, 14336, 14336 }, { 22528, 36864, 40960 }, { 16384, 14336, 18432 } }, { 49152, 40960, 40960, 40960, 8192, 57344, 49152, 40960, 16384, 8192, 49152, 40960, 16384, 8192, 49152, 40960 } }, + { { { 51200, 50176, 54272 }, { 57344, 57344, 59392 }, { 58368, 58368, 59392 }, { 55296, 55296, 57344 } }, { 32768, 40960, 40960, 40960, 24576, 57344, 49152, 57344, 57344, 57344, 0, 24576, 40960, 40960, 40960, 40960 } }, + { { { 54080, 53760, 52544 }, { 49152, 47104, 47104 }, { 43008, 43008, 43008 }, { 43008, 43008, 43008 } }, { 49152, 49152, 49152, 40960, 40960, 8192, 0, 57344, 0, 49152, 49152, 16384, 16384, 8192, 0, 49152 } }, + { { { 51712, 51200, 49920 }, { 38912, 49152, 51200 }, { 38912, 45056, 47104 }, { 34816, 36864, 26624 } }, { 57344, 0, 8192, 8192, 49152, 57344, 0, 0, 8192, 57344, 49152, 40960, 0, 49152, 40960, 40960 } }, + { { { 61440, 34304, 34176 }, { 36864, 32768, 32768 }, { 36864, 32768, 32768 }, { 34816, 32768, 32768 } }, { 57344, 40960, 57344, 16384, 49152, 8192, 57344, 8192, 40960, 0, 40960, 57344, 40960, 57344, 16384, 49152 } }, + { { { 51456, 45824, 48640 }, { 25600, 40960, 40960 }, { 24576, 43008, 43008 }, { 26624, 40960, 40960 } }, { 32768, 8192, 16384, 16384, 49152, 0, 8192, 16384, 49152, 49152, 57344, 57344, 40960, 40960, 40960, 40960 } }, + { { { 51712, 46592, 43776 }, { 51200, 45056, 43008 }, { 47104, 38912, 36864 }, { 51200, 49152, 54272 } }, { 49152, 49152, 40960, 49152, 0, 8192, 16384, 8192, 40960, 49152, 49152, 57344, 8192, 8192, 16384, 8192 } }, + { { { 50432, 51712, 48896 }, { 25600, 16384, 14336 }, { 34816, 26624, 6144 }, { 25600, 14336, 14336 } }, { 57344, 16384, 49152, 0, 8192, 57344, 49152, 57344, 49152, 57344, 8192, 8192, 57344, 0, 8192, 40960 } }, + { { { 58560, 58560, 57856 }, { 18432, 22528, 12288 }, { 47104, 43008, 51200 }, { 40960, 38912, 40960 } }, { 40960, 40960, 49152, 40960, 49152, 57344, 57344, 57344, 16384, 8192, 16384, 8192, 40960, 8192, 16384, 40960 } }, + { { { 59712, 59392, 60288 }, { 49152, 43008, 57344 }, { 51200, 43008, 51200 }, { 36864, 28672, 24576 } }, { 49152, 40960, 49152, 0, 8192, 49152, 0, 16384, 49152, 49152, 8192, 0, 49152, 57344, 16384, 40960 } }, + { { { 49152, 44032, 41984 }, { 48128, 44032, 38912 }, { 41984, 52224, 33792 }, { 43008, 53248, 36864 } }, { 57344, 0, 49152, 40960, 8192, 0, 49152, 57344, 16384, 57344, 40960, 16384, 8192, 57344, 49152, 49152 } }, + { { { 53760, 53248, 52736 }, { 36864, 36864, 36864 }, { 45056, 46080, 45056 }, { 46080, 47104, 46080 } }, { 32768, 40960, 57344, 16384, 16384, 8192, 57344, 57344, 8192, 0, 49152, 49152, 57344, 49152, 40960, 40960 } }, + { { { 59456, 59328, 60544 }, { 8192, 20480, 14336 }, { 36864, 26624, 22528 }, { 10240, 22528, 18432 } }, { 49152, 8192, 40960, 16384, 49152, 57344, 8192, 57344, 40960, 49152, 0, 40960, 40960, 49152, 0, 16384 } }, + { { { 60224, 60992, 61120 }, { 10240, 22528, 47104 }, { 0, 61440, 43008 }, { 10240, 26624, 40960 } }, { 40960, 40960, 40960, 40960, 40960, 40960, 40960, 49152, 49152, 57344, 8192, 24576, 24576, 0, 40960, 40960 } }, + { { { 45056, 44032, 44032 }, { 43008, 43008, 41984 }, { 50176, 34816, 29696 }, { 43008, 43008, 40960 } }, { 49152, 49152, 49152, 16384, 49152, 57344, 57344, 49152, 49152, 8192, 16384, 49152, 49152, 16384, 16384, 49152 } }, + { { { 60416, 59392, 52224 }, { 60416, 58368, 47104 }, { 59392, 56320, 38912 }, { 59392, 58368, 46080 } }, { 32768, 8192, 57344, 49152, 16384, 8192, 8192, 49152, 49152, 8192, 8192, 49152, 49152, 8192, 8192, 49152 } }, + { { { 53248, 53504, 51200 }, { 25600, 16384, 16384 }, { 24576, 16384, 16384 }, { 28672, 26624, 34816 } }, { 57344, 40960, 40960, 57344, 40960, 57344, 8192, 8192, 8192, 8192, 57344, 49152, 8192, 0, 57344, 40960 } }, + { { { 55296, 48000, 52480 }, { 51200, 43008, 57344 }, { 28672, 34816, 38912 }, { 49152, 40960, 45056 } }, { 32768, 16384, 0, 49152, 8192, 8192, 8192, 57344, 8192, 8192, 8192, 8192, 8192, 57344, 49152, 40960 } }, + { { { 60672, 60864, 61440 }, { 16384, 22528, 16384 }, { 16384, 18432, 14336 }, { 57344, 36864, 24576 } }, { 40960, 40960, 49152, 49152, 16384, 8192, 8192, 8192, 40960, 57344, 8192, 16384, 8192, 8192, 0, 49152 } }, + { { { 45824, 45056, 42496 }, { 56320, 47104, 45056 }, { 56320, 45056, 45056 }, { 11264, 22528, 24576 } }, { 57344, 16384, 16384, 8192, 0, 16384, 8192, 0, 49152, 57344, 49152, 40960, 40960, 40960, 40960, 40960 } }, + { { { 40960, 27392, 46848 }, { 54272, 28672, 49152 }, { 53248, 28672, 47104 }, { 52224, 28672, 43008 } }, { 32768, 16384, 49152, 8192, 0, 57344, 0, 0, 16384, 49152, 8192, 49152, 57344, 57344, 0, 40960 } }, + { { { 60736, 32768, 60000 }, { 57344, 49152, 0 }, { 61440, 49152, 45056 }, { 4096, 49152, 61440 } }, { 57344, 24576, 57344, 49152, 49152, 57344, 49152, 49152, 49152, 49152, 49152, 49152, 16384, 8192, 49152, 40960 } }, + { { { 55680, 55296, 54016 }, { 16384, 20480, 16384 }, { 51200, 49152, 55296 }, { 47104, 43008, 47104 } }, { 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960 } }, + { { { 45056, 44544, 44032 }, { 44032, 44032, 44032 }, { 38912, 38912, 38912 }, { 53248, 54272, 54272 } }, { 32768, 16384, 16384, 8192, 40960, 16384, 8192, 8192, 49152, 8192, 57344, 57344, 40960, 57344, 40960, 40960 } }, + { { { 44032, 43520, 39936 }, { 45056, 39936, 45056 }, { 38912, 39936, 40960 }, { 1024, 29696, 34816 } }, { 32768, 40960, 49152, 57344, 40960, 57344, 8192, 16384, 49152, 8192, 16384, 16384, 40960, 49152, 49152, 49152 } }, + { { { 41984, 36864, 40960 }, { 46080, 36864, 41984 }, { 36864, 32768, 55296 }, { 36864, 32768, 57344 } }, { 40960, 40960, 49152, 16384, 40960, 40960, 49152, 8192, 49152, 49152, 40960, 57344, 8192, 16384, 8192, 49152 } }, + { { { 59776, 60416, 61504 }, { 51200, 43008, 49152 }, { 26624, 36864, 40960 }, { 45056, 40960, 45056 } }, { 32768, 40960, 49152, 16384, 49152, 40960, 40960, 57344, 0, 49152, 40960, 40960, 16384, 0, 40960, 40960 } }, + { { { 50688, 50176, 45568 }, { 21504, 10240, 38912 }, { 38912, 43008, 40960 }, { 22528, 8192, 34816 } }, { 32768, 40960, 49152, 57344, 40960, 49152, 57344, 0, 53248, 57344, 4096, 16384, 0, 8192, 16384, 24576 } }, + { { { 44032, 46336, 41728 }, { 45056, 45056, 45056 }, { 44032, 49152, 45056 }, { 39936, 28672, 34816 } }, { 40960, 0, 8192, 16384, 40960, 57344, 8192, 16384, 49152, 49152, 8192, 16384, 16384, 49152, 57344, 16384 } }, + { { { 44544, 39936, 38912 }, { 40960, 40960, 41984 }, { 29696, 34816, 34816 }, { 38912, 40960, 41984 } }, { 32768, 8192, 16384, 8192, 40960, 49152, 8192, 16384, 57344, 57344, 49152, 0, 8192, 8192, 8192, 40960 } }, + { { { 59200, 59840, 60864 }, { 0, 8192, 14336 }, { 6144, 20480, 16384 }, { 49152, 36864, 24576 } }, { 57344, 49152, 0, 8192, 0, 8192, 16384, 16384, 16384, 16384, 16384, 8192, 8192, 8192, 0, 40960 } }, + { { { 43264, 44800, 40960 }, { 47104, 43008, 47104 }, { 41984, 28672, 36864 }, { 46080, 43008, 47104 } }, { 32768, 49152, 0, 16384, 40960, 57344, 16384, 49152, 49152, 16384, 57344, 40960, 16384, 0, 40960, 40960 } }, + { { { 50432, 50688, 48384 }, { 22528, 14336, 18432 }, { 22528, 12288, 20480 }, { 27648, 32768, 34816 } }, { 32768, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 57344, 57344, 57344, 49152, 0, 57344, 57344, 49152 } }, + { { { 54912, 54784, 54016 }, { 49152, 49152, 49152 }, { 49152, 49152, 47104 }, { 34816, 26624, 24576 } }, { 32768, 0, 8192, 8192, 16384, 0, 8192, 16384, 8192, 49152, 49152, 8192, 0, 40960, 49152, 40960 } }, + { { { 60800, 32832, 59712 }, { 49152, 32768, 16384 }, { 53248, 32768, 36864 }, { 59392, 32768, 47104 } }, { 40960, 8192, 16384, 49152, 49152, 57344, 57344, 57344, 40960, 0, 8192, 8192, 8192, 8192, 8192, 49152 } }, + { { { 53888, 47616, 47968 }, { 10240, 16384, 16384 }, { 51200, 20480, 20480 }, { 55296, 40960, 40960 } }, { 49152, 0, 49152, 57344, 40960, 40960, 49152, 57344, 40960, 49152, 49152, 0, 8192, 8192, 16384, 16384 } }, + { { { 54656, 50048, 52992 }, { 45056, 45056, 53248 }, { 45056, 45056, 45056 }, { 28672, 34816, 40960 } }, { 40960, 40960, 40960, 40960, 40960, 40960, 49152, 57344, 49152, 57344, 16384, 16384, 8192, 16384, 8192, 40960 } }, + { { { 64096, 64160, 63968 }, { 40960, 53248, 24576 }, { 36864, 45056, 24576 }, { 8192, 12288, 34816 } }, { 40960, 16384, 57344, 40960, 40960, 0, 0, 40960, 40960, 49152, 16384, 49152, 40960, 49152, 16384, 57344 } }, + { { { 18432, 18432, 33792 }, { 55296, 53248, 13312 }, { 56320, 51200, 13312 }, { 56320, 54272, 51200 } }, { 32768, 8192, 16384, 16384, 40960, 40960, 40960, 49152, 57344, 57344, 49152, 40960, 16384, 16384, 57344, 49152 } }, + { { { 5120, 62464, 62464 }, { 10240, 62464, 61440 }, { 10240, 62464, 62464 }, { 12288, 62464, 62464 } }, { 32768, 16384, 40960, 40960, 0, 57344, 40960, 8192, 8192, 8192, 0, 57344, 16384, 16384, 8192, 8192 } }, + { { { 59840, 60032, 61120 }, { 40960, 43008, 47104 }, { 40960, 43008, 43008 }, { 28672, 36864, 40960 } }, { 32768, 8192, 40960, 8192, 8192, 8192, 57344, 0, 8192, 8192, 49152, 8192, 57344, 57344, 57344, 0 } }, + { { { 53248, 53248, 51200 }, { 24576, 16384, 14336 }, { 28672, 26624, 36864 }, { 24576, 14336, 20480 } }, { 32768, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 40960, 49152, 49152, 49152, 0, 0, 16384, 24576 } }, + { { { 39360, 58752, 59072 }, { 32768, 20480, 20480 }, { 34816, 16384, 14336 }, { 32768, 22528, 22528 } }, { 32768, 40960, 57344, 16384, 40960, 40960, 57344, 8192, 16384, 16384, 0, 49152, 8192, 8192, 49152, 40960 } }, + { { { 52224, 52480, 50944 }, { 26624, 14336, 14336 }, { 35840, 36864, 26624 }, { 26624, 12288, 12288 } }, { 57344, 40960, 40960, 49152, 0, 49152, 49152, 0, 8192, 0, 0, 8192, 16384, 16384, 16384, 16384 } }, + { { { 48128, 46592, 37376 }, { 23552, 25600, 35840 }, { 18432, 25600, 37888 }, { 16384, 25600, 36864 } }, { 32768, 57344, 8192, 16384, 8192, 49152, 0, 16384, 16384, 8192, 49152, 8192, 8192, 8192, 49152, 40960 } }, + { { { 6656, 14848, 19456 }, { 56320, 8192, 8192 }, { 50176, 13312, 11264 }, { 55296, 52224, 52224 } }, { 57344, 8192, 8192, 0, 16384, 8192, 0, 57344, 0, 57344, 49152, 8192, 49152, 57344, 16384, 40960 } }, + { { { 27392, 49152, 25856 }, { 47104, 26624, 36864 }, { 45056, 20480, 36864 }, { 46080, 12288, 36864 } }, { 40960, 40960, 49152, 16384, 40960, 40960, 49152, 8192, 40960, 40960, 57344, 57344, 40960, 49152, 24576, 40960 } }, + { { { 48128, 36864, 35840 }, { 52224, 35840, 36864 }, { 53248, 36864, 39936 }, { 53248, 36864, 37888 } }, { 32768, 49152, 57344, 16384, 16384, 49152, 57344, 0, 49152, 8192, 16384, 0, 49152, 57344, 49152, 49152 } }, + { { { 58592, 56288, 53536 }, { 26624, 61440, 45056 }, { 26624, 61440, 45056 }, { 34816, 45056, 45056 } }, { 40960, 40960, 40960, 16384, 57344, 57344, 8192, 8192, 8192, 8192, 57344, 57344, 16384, 40960, 40960, 40960 } }, + { { { 57024, 61184, 61632 }, { 45056, 45056, 24576 }, { 40960, 40960, 38912 }, { 45056, 36864, 10240 } }, { 40960, 16384, 49152, 57344, 16384, 57344, 49152, 8192, 40960, 57344, 0, 49152, 16384, 49152, 49152, 49152 } }, + { { { 53248, 53248, 51712 }, { 24576, 24576, 20480 }, { 38912, 38912, 39936 }, { 26624, 25600, 23552 } }, { 32768, 40960, 57344, 16384, 57344, 57344, 8192, 8192, 24576, 49152, 49152, 49152, 40960, 40960, 40960, 40960 } }, + { { { 43008, 39424, 38912 }, { 39936, 41984, 43008 }, { 38912, 39936, 39936 }, { 28672, 34816, 35840 } }, { 57344, 49152, 49152, 8192, 49152, 8192, 8192, 16384, 57344, 8192, 0, 49152, 57344, 49152, 40960, 40960 } }, + { { { 54560, 54400, 52160 }, { 28672, 45056, 40960 }, { 47104, 36864, 36864 }, { 28672, 40960, 40960 } }, { 32768, 49152, 40960, 49152, 8192, 8192, 8192, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384, 16384 } }, + { { { 63072, 63680, 64448 }, { 26624, 8192, 4096 }, { 36864, 53248, 61440 }, { 36864, 53248, 53248 } }, { 32768, 8192, 16384, 0, 8192, 0, 49152, 49152, 16384, 8192, 57344, 49152, 0, 8192, 8192, 49152 } }, + { { { 51200, 50944, 45312 }, { 51200, 40960, 43008 }, { 13312, 24576, 36864 }, { 12288, 22528, 49152 } }, { 57344, 16384, 49152, 49152, 57344, 49152, 49152, 57344, 16384, 8192, 49152, 49152, 8192, 16384, 8192, 40960 } }, + { { { 48384, 47616, 44288 }, { 24576, 0, 49152 }, { 25600, 63488, 36864 }, { 35840, 51200, 45056 } }, { 36864, 36864, 36864, 40960, 57344, 57344, 61440, 61440, 12288, 12288, 16384, 16384, 20480, 24576, 24576, 24576 } }, + { { { 33792, 38912, 32768 }, { 33792, 62464, 32768 }, { 32768, 32768, 32768 }, { 32768, 56320, 37888 } }, { 49152, 49152, 57344, 8192, 8192, 49152, 49152, 8192, 49152, 57344, 49152, 0, 40960, 8192, 8192, 8192 } }, + { { { 49152, 50944, 48128 }, { 39936, 51200, 53248 }, { 39936, 47104, 49152 }, { 35840, 26624, 24576 } }, { 40960, 40960, 40960, 40960, 40960, 49152, 49152, 40960, 49152, 8192, 0, 40960, 16384, 16384, 8192, 49152 } }, + { { { 49664, 50688, 47616 }, { 39936, 49152, 49152 }, { 38912, 49152, 49152 }, { 28672, 26624, 34816 } }, { 49152, 4096, 16384, 24576, 45056, 61440, 12288, 20480, 40960, 57344, 12288, 20480, 36864, 49152, 4096, 16384 } }, + { { { 48128, 46592, 46080 }, { 41984, 41984, 43008 }, { 43008, 43008, 40960 }, { 35840, 34816, 29696 } }, { 32768, 16384, 16384, 16384, 8192, 16384, 16384, 16384, 16384, 16384, 16384, 8192, 16384, 16384, 0, 32768 } }, + { { { 60416, 3072, 60416 }, { 62464, 11264, 61440 }, { 62464, 11264, 62464 }, { 62464, 13312, 62464 } }, { 32768, 40960, 40960, 40960, 49152, 57344, 8192, 16384, 24576, 8192, 0, 57344, 49152, 40960, 40960, 40960 } }, + { { { 54528, 48896, 52736 }, { 37888, 47104, 59392 }, { 27648, 55296, 53248 }, { 27648, 36864, 43008 } }, { 49152, 40960, 40960, 40960, 16384, 49152, 40960, 40960, 40960, 8192, 57344, 49152, 0, 49152, 8192, 49152 } }, + { { { 59968, 33280, 59584 }, { 2048, 32768, 63488 }, { 4096, 32768, 16384 }, { 61440, 32768, 12288 } }, { 32768, 16384, 49152, 57344, 49152, 0, 49152, 8192, 57344, 57344, 49152, 8192, 8192, 57344, 49152, 0 } }, + { { { 15872, 18944, 43008 }, { 7168, 12288, 54272 }, { 7168, 11264, 51200 }, { 58368, 51200, 54272 } }, { 40960, 49152, 8192, 8192, 16384, 0, 49152, 40960, 40960, 57344, 8192, 16384, 8192, 0, 49152, 40960 } }, + { { { 57312, 56384, 54816 }, { 38912, 49152, 53248 }, { 26624, 8192, 4096 }, { 26624, 8192, 0 } }, { 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 16384, 49152, 40960, 32768 } }, + { { { 45056, 40960, 46080 }, { 62464, 60416, 11264 }, { 62464, 60416, 17408 }, { 61440, 59392, 14336 } }, { 32768, 16384, 57344, 49152, 16384, 16384, 8192, 49152, 49152, 0, 8192, 8192, 40960, 40960, 49152, 57344 } }, + { { { 32768, 32768, 32768 }, { 62464, 32768, 32768 }, { 32768, 32768, 32768 }, { 62464, 32768, 32768 } }, { 40960, 8192, 40960, 8192, 40960, 8192, 49152, 8192, 40960, 8192, 8192, 8192, 49152, 8192, 8192, 49152 } }, + { { { 54272, 54272, 53248 }, { 21504, 20480, 20480 }, { 36864, 36864, 36864 }, { 25600, 25600, 24576 } }, { 40960, 40960, 40960, 40960, 16384, 16384, 16384, 0, 40960, 40960, 40960, 40960, 16384, 16384, 0, 49152 } }, + { { { 32768, 64864, 62976 }, { 34816, 49152, 49152 }, { 34816, 61440, 45056 }, { 34816, 57344, 4096 } }, { 32768, 0, 16384, 40960, 49152, 57344, 8192, 0, 0, 57344, 16384, 8192, 8192, 0, 8192, 40960 } }, + { { { 55808, 46080, 39424 }, { 34816, 34816, 52224 }, { 34816, 35840, 49152 }, { 34816, 34816, 51200 } }, { 40960, 40960, 40960, 40960, 16384, 16384, 16384, 16384, 0, 0, 57344, 49152, 49152, 40960, 40960, 40960 } }, + { { { 57472, 57728, 56448 }, { 38912, 22528, 20480 }, { 36864, 22528, 22528 }, { 16384, 34816, 30720 } }, { 32768, 57344, 8192, 57344, 0, 8192, 0, 57344, 16384, 49152, 8192, 8192, 57344, 57344, 8192, 49152 } }, + { { { 64224, 64224, 64032 }, { 49152, 61440, 22528 }, { 20480, 20480, 49152 }, { 4096, 12288, 32768 } }, { 40960, 49152, 16384, 16384, 40960, 49152, 0, 16384, 40960, 40960, 40960, 49152, 40960, 40960, 40960, 40960 } }, + { { { 45568, 44544, 41472 }, { 45056, 41984, 46080 }, { 29696, 29696, 33792 }, { 39936, 39936, 43008 } }, { 32768, 49152, 49152, 57344, 57344, 8192, 16384, 49152, 16384, 49152, 49152, 49152, 16384, 0, 49152, 40960 } }, + { { { 64448, 64256, 64288 }, { 47104, 20480, 12288 }, { 36864, 28672, 57344 }, { 36864, 32768, 4096 } }, { 57344, 0, 61440, 53248, 4096, 4096, 61440, 53248, 12288, 8192, 61440, 53248, 12288, 8192, 61440, 45056 } }, + { { { 62528, 61568, 61728 }, { 24576, 49152, 40960 }, { 38912, 40960, 40960 }, { 24576, 61440, 40960 } }, { 49152, 24576, 49152, 49152, 49152, 57344, 57344, 0, 49152, 40960, 57344, 16384, 49152, 49152, 49152, 49152 } }, + { { { 52736, 48640, 48128 }, { 36864, 35840, 23552 }, { 38912, 36864, 8192 }, { 40960, 36864, 22528 } }, { 40960, 16384, 49152, 57344, 49152, 57344, 49152, 49152, 16384, 8192, 8192, 8192, 57344, 49152, 49152, 40960 } }, + { { { 55040, 54528, 51968 }, { 16384, 12288, 14336 }, { 47104, 47104, 38912 }, { 8192, 10240, 18432 } }, { 49152, 49152, 40960, 49152, 0, 49152, 57344, 0, 57344, 49152, 49152, 8192, 49152, 40960, 57344, 24576 } }, + { { { 53248, 52224, 49152 }, { 23552, 23552, 22528 }, { 28672, 27648, 34816 }, { 20480, 20480, 24576 } }, { 32768, 49152, 57344, 0, 16384, 8192, 49152, 49152, 40960, 49152, 49152, 49152, 8192, 16384, 16384, 8192 } }, + { { { 41472, 42496, 38912 }, { 44032, 40960, 43008 }, { 34816, 29696, 34816 }, { 45056, 40960, 43008 } }, { 32768, 49152, 49152, 16384, 49152, 0, 0, 49152, 49152, 8192, 8192, 57344, 49152, 0, 8192, 16384 } }, + { { { 51712, 51200, 50688 }, { 21504, 23552, 20480 }, { 55296, 34816, 27648 }, { 24576, 23552, 20480 } }, { 40960, 49152, 49152, 16384, 40960, 49152, 57344, 0, 40960, 40960, 57344, 8192, 40960, 40960, 57344, 16384 } }, + { { { 16384, 0, 57344 }, { 58368, 59392, 59392 }, { 56320, 55296, 56320 }, { 56320, 3072, 4096 } }, { 40960, 49152, 49152, 40960, 16384, 8192, 49152, 40960, 16384, 16384, 49152, 49152, 49152, 0, 49152, 40960 } }, + { { { 49664, 43008, 47104 }, { 50176, 35840, 25600 }, { 47104, 37888, 61440 }, { 44032, 38912, 38912 } }, { 32768, 8192, 8192, 0, 16384, 49152, 57344, 8192, 49152, 49152, 57344, 0, 49152, 0, 57344, 49152 } }, + { { { 48896, 40448, 38912 }, { 51200, 40960, 54272 }, { 61440, 34816, 39936 }, { 8192, 34816, 37888 } }, { 49152, 8192, 49152, 8192, 57344, 8192, 57344, 57344, 8192, 49152, 8192, 49152, 8192, 49152, 16384, 40960 } }, + { { { 43520, 43008, 36864 }, { 5120, 25600, 36864 }, { 6144, 25600, 34816 }, { 53248, 35840, 40960 } }, { 36864, 40960, 61440, 20480, 36864, 40960, 57344, 20480, 36864, 40960, 53248, 16384, 40960, 40960, 53248, 16384 } }, + { { { 44544, 36352, 37888 }, { 27648, 36864, 39936 }, { 35840, 38912, 39936 }, { 63488, 35840, 36864 } }, { 40960, 40960, 40960, 49152, 49152, 0, 8192, 16384, 49152, 8192, 8192, 49152, 49152, 16384, 49152, 40960 } }, + { { { 52736, 51712, 48128 }, { 21504, 22528, 20480 }, { 23552, 21504, 18432 }, { 28672, 28672, 35840 } }, { 40960, 40960, 40960, 49152, 49152, 49152, 0, 16384, 16384, 8192, 57344, 49152, 49152, 40960, 40960, 40960 } }, + { { { 50688, 50176, 48640 }, { 41984, 43008, 43008 }, { 53248, 56320, 57344 }, { 50176, 53248, 53248 } }, { 32768, 49152, 49152, 57344, 49152, 0, 16384, 16384, 49152, 49152, 49152, 49152, 8192, 8192, 8192, 49152 } }, + { { { 44032, 43008, 36864 }, { 8192, 26624, 34816 }, { 55296, 36864, 40960 }, { 6144, 27648, 35840 } }, { 32768, 40960, 49152, 16384, 0, 57344, 40960, 40960, 16384, 16384, 0, 57344, 16384, 16384, 16384, 8192 } }, + { { { 47616, 45056, 38912 }, { 46080, 36864, 48128 }, { 8192, 27648, 37888 }, { 8192, 27648, 40960 } }, { 40960, 49152, 49152, 8192, 16384, 8192, 49152, 57344, 57344, 49152, 57344, 49152, 49152, 49152, 16384, 49152 } }, + { { { 45568, 45568, 43008 }, { 56320, 2048, 51200 }, { 38912, 38912, 37888 }, { 37888, 38912, 37888 } }, { 40960, 16384, 49152, 8192, 49152, 16384, 49152, 8192, 57344, 0, 49152, 0, 8192, 49152, 16384, 40960 } }, + { { { 48128, 48128, 46592 }, { 46080, 44032, 47104 }, { 34816, 29696, 28672 }, { 45056, 44032, 43008 } }, { 40960, 49152, 49152, 49152, 49152, 16384, 8192, 49152, 49152, 16384, 16384, 49152, 40960, 49152, 40960, 40960 } }, + { { { 4096, 4096, 13312 }, { 4096, 4096, 15360 }, { 62464, 62464, 62464 }, { 1024, 1024, 9216 } }, { 40960, 40960, 40960, 40960, 49152, 40960, 49152, 24576, 0, 57344, 57344, 49152, 24576, 0, 49152, 40960 } }, + { { { 51712, 52224, 50688 }, { 17408, 22528, 20480 }, { 33792, 28672, 26624 }, { 22528, 23552, 19456 } }, { 32768, 16384, 16384, 16384, 57344, 8192, 24576, 16384, 40960, 0, 16384, 24576, 49152, 0, 16384, 24576 } }, + { { { 48128, 48128, 46080 }, { 45056, 44032, 46080 }, { 43008, 44032, 43008 }, { 33792, 29696, 26624 } }, { 36864, 36864, 36864, 40960, 36864, 36864, 36864, 36864, 36864, 36864, 36864, 40960, 40960, 40960, 40960, 45056 } }, + { { { 41472, 42496, 35840 }, { 47104, 26624, 36864 }, { 49152, 27648, 36864 }, { 46080, 27648, 38912 } }, { 49152, 49152, 49152, 49152, 8192, 16384, 57344, 57344, 40960, 49152, 49152, 16384, 49152, 57344, 49152, 49152 } }, + { { { 32768, 32768, 60288 }, { 32768, 32768, 51200 }, { 32768, 32768, 57344 }, { 32768, 32768, 43008 } }, { 36864, 36864, 36864, 36864, 45056, 45056, 40960, 40960, 0, 61440, 57344, 57344, 20480, 20480, 20480, 16384 } }, + { { { 36352, 59456, 29952 }, { 32768, 18432, 34816 }, { 32768, 12288, 34816 }, { 32768, 12288, 34816 } }, { 40960, 49152, 57344, 16384, 49152, 49152, 49152, 49152, 49152, 49152, 57344, 16384, 57344, 8192, 8192, 40960 } }, + { { { 53248, 40960, 48640 }, { 48128, 37888, 41984 }, { 43008, 34816, 24576 }, { 40960, 34816, 21504 } }, { 40960, 49152, 0, 49152, 40960, 40960, 16384, 49152, 57344, 49152, 8192, 49152, 16384, 0, 49152, 40960 } }, + { { { 53760, 52736, 51200 }, { 27648, 27648, 20480 }, { 43008, 41984, 46080 }, { 48128, 33792, 26624 } }, { 40960, 49152, 40960, 16384, 49152, 49152, 57344, 0, 8192, 57344, 49152, 57344, 8192, 57344, 0, 16384 } }, + { { { 50176, 49664, 48640 }, { 22528, 25600, 20480 }, { 23552, 24576, 18432 }, { 35840, 34816, 26624 } }, { 32768, 49152, 16384, 57344, 49152, 8192, 0, 49152, 16384, 57344, 40960, 40960, 57344, 40960, 40960, 40960 } }, + { { { 45568, 43008, 44032 }, { 49152, 43008, 53248 }, { 41984, 43008, 38912 }, { 29696, 33792, 28672 } }, { 32768, 40960, 57344, 16384, 40960, 40960, 57344, 16384, 57344, 40960, 49152, 57344, 16384, 49152, 40960, 49152 } }, + { { { 52736, 49152, 46080 }, { 34816, 28672, 16384 }, { 43008, 43008, 54272 }, { 40960, 39936, 55296 } }, { 32768, 24576, 49152, 49152, 49152, 40960, 49152, 49152, 8192, 49152, 49152, 40960, 16384, 0, 57344, 40960 } }, + { { { 54016, 52992, 50944 }, { 14336, 12288, 22528 }, { 53248, 51200, 46080 }, { 55296, 55296, 40960 } }, { 32768, 0, 40960, 40960, 16384, 0, 16384, 40960, 16384, 0, 16384, 40960, 16384, 57344, 8192, 16384 } }, + { { { 45568, 42496, 36352 }, { 22528, 28672, 34816 }, { 4096, 36864, 43008 }, { 64512, 35840, 39936 } }, { 32768, 32768, 32768, 40960, 32768, 32768, 32768, 32768, 40960, 32768, 32768, 32768, 24576, 32768, 32768, 32768 } }, + { { { 50176, 49152, 47104 }, { 55296, 38912, 4096 }, { 18432, 27648, 20480 }, { 57344, 35840, 26624 } }, { 49152, 49152, 16384, 8192, 49152, 57344, 49152, 49152, 49152, 24576, 49152, 49152, 57344, 49152, 49152, 49152 } }, + { { { 49664, 47616, 44544 }, { 52224, 38912, 44032 }, { 25600, 27648, 62464 }, { 29696, 34816, 37888 } }, { 40960, 24576, 40960, 16384, 49152, 0, 57344, 8192, 40960, 49152, 49152, 49152, 49152, 49152, 40960, 40960 } }, + { { { 50688, 49664, 49152 }, { 17408, 26624, 20480 }, { 15360, 18432, 20480 }, { 29696, 33792, 27648 } }, { 57344, 49152, 0, 8192, 57344, 8192, 0, 0, 40960, 49152, 0, 49152, 16384, 49152, 57344, 40960 } }, + { { { 53248, 52736, 51200 }, { 19456, 21504, 17408 }, { 29696, 34816, 35840 }, { 18432, 20480, 24576 } }, { 32768, 40960, 8192, 24576, 40960, 49152, 57344, 0, 40960, 0, 49152, 49152, 49152, 16384, 49152, 40960 } }, + { { { 53760, 52736, 50176 }, { 21504, 23552, 25600 }, { 45056, 41984, 44032 }, { 20480, 28672, 34816 } }, { 40960, 40960, 49152, 49152, 40960, 49152, 49152, 57344, 49152, 49152, 57344, 16384, 16384, 57344, 49152, 16384 } }, + { { { 51712, 52224, 48640 }, { 13312, 20480, 18432 }, { 34816, 29696, 36864 }, { 25600, 20480, 24576 } }, { 32768, 40960, 0, 16384, 32768, 40960, 49152, 0, 32768, 32768, 40960, 49152, 32768, 32768, 32768, 40960 } }, + { { { 45056, 40960, 38400 }, { 0, 38912, 45056 }, { 29696, 37888, 36864 }, { 12288, 26624, 45056 } }, { 32768, 24576, 49152, 40960, 49152, 0, 40960, 40960, 8192, 49152, 32768, 40960, 16384, 40960, 40960, 40960 } }, +}; + +inline constexpr uint8_t BC6_ENDPOINT_BITS[15][4] = { + { 0, 0, 0, 0 }, + { 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 }, +}; + +// 0 = mode bit, 1 = partition bit; 2 + 3 * endpoint + channel = endpoint bit. +inline constexpr Bc6WireBit BC6_WIRE[14][82] = { + { // Mode 1 + { 0, 0 }, { 0, 1 }, { 9, 4 }, { 10, 4 }, { 13, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 2 + { 0, 0 }, { 0, 1 }, { 9, 5 }, { 12, 4 }, { 12, 5 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 13, 0 }, { 13, 1 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 10, 5 }, { 13, 2 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 13, 3 }, { 13, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 8, 5 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 11, 5 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 3 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 2, 10 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 3, 10 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 4, 10 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 4 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 2, 10 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 3, 10 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 4, 10 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 13, 0 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 9, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 5 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 2, 10 }, + { 10, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 3, 10 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 4, 10 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 13, 1 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 13, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 6 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 7 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 12, 4 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 13, 2 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 13, 3 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 8, 5 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 11, 5 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 8 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 13, 0 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 9, 5 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 12, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 13, 1 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 9 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 13, 1 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 10, 5 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 13, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 12, 4 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 13, 0 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 13, 2 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 13, 3 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 10 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 12, 4 }, { 13, 0 }, { 13, 1 }, { 10, 4 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 9, 5 }, { 10, 5 }, { 13, 2 }, { 9, 4 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 12, 5 }, { 13, 3 }, { 13, 5 }, { 13, 4 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 9, 0 }, { 9, 1 }, { 9, 2 }, { 9, 3 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 12, 0 }, { 12, 1 }, { 12, 2 }, { 12, 3 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 10, 0 }, { 10, 1 }, { 10, 2 }, { 10, 3 }, { 8, 0 }, { 8, 1 }, { 8, 2 }, { 8, 3 }, { 8, 4 }, + { 8, 5 }, { 11, 0 }, { 11, 1 }, { 11, 2 }, { 11, 3 }, { 11, 4 }, { 11, 5 }, { 1, 0 }, { 1, 1 }, { 1, 2 }, + { 1, 3 }, { 1, 4 }, + }, + { // Mode 11 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 5, 6 }, { 5, 7 }, { 5, 8 }, { 5, 9 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 6, 6 }, { 6, 7 }, { 6, 8 }, { 6, 9 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 7, 6 }, { 7, 7 }, { 7, 8 }, { 7, 9 }, + }, + { // Mode 12 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 5, 6 }, { 5, 7 }, { 5, 8 }, { 2, 10 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 6, 6 }, { 6, 7 }, { 6, 8 }, { 3, 10 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 7, 6 }, { 7, 7 }, { 7, 8 }, { 4, 10 }, + }, + { // Mode 13 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 5, 4 }, + { 5, 5 }, { 5, 6 }, { 5, 7 }, { 2, 10 }, { 2, 11 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 6, 4 }, + { 6, 5 }, { 6, 6 }, { 6, 7 }, { 3, 10 }, { 3, 11 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 7, 4 }, + { 7, 5 }, { 7, 6 }, { 7, 7 }, { 4, 10 }, { 4, 11 }, + }, + { // Mode 14 + { 0, 0 }, { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 }, { 2, 0 }, { 2, 1 }, { 2, 2 }, { 2, 3 }, { 2, 4 }, + { 2, 5 }, { 2, 6 }, { 2, 7 }, { 2, 8 }, { 2, 9 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 3, 3 }, { 3, 4 }, + { 3, 5 }, { 3, 6 }, { 3, 7 }, { 3, 8 }, { 3, 9 }, { 4, 0 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 }, + { 4, 5 }, { 4, 6 }, { 4, 7 }, { 4, 8 }, { 4, 9 }, { 5, 0 }, { 5, 1 }, { 5, 2 }, { 5, 3 }, { 2, 10 }, + { 2, 11 }, { 2, 12 }, { 2, 13 }, { 2, 14 }, { 2, 15 }, { 6, 0 }, { 6, 1 }, { 6, 2 }, { 6, 3 }, { 3, 10 }, + { 3, 11 }, { 3, 12 }, { 3, 13 }, { 3, 14 }, { 3, 15 }, { 7, 0 }, { 7, 1 }, { 7, 2 }, { 7, 3 }, { 4, 10 }, + { 4, 11 }, { 4, 12 }, { 4, 13 }, { 4, 14 }, { 4, 15 }, + }, +}; diff --git a/src/startup_stubs/buffer_format_word3.h b/src/startup_stubs/buffer_format_word3.h index 771ec1dd8d..072ae1aeda 100644 --- a/src/startup_stubs/buffer_format_word3.h +++ b/src/startup_stubs/buffer_format_word3.h @@ -26,6 +26,7 @@ inline std::uint32_t buffer_format_code(DXGI_FORMAT format) case DXGI_FORMAT_R16G16_SNORM: return 24; case DXGI_FORMAT_R16G16_UINT: return 27; case DXGI_FORMAT_R16G16_FLOAT: return 29; + case DXGI_FORMAT_R10G10B10A2_UNORM: return 50; case DXGI_FORMAT_R8G8B8A8_UNORM: return 56; case DXGI_FORMAT_R8G8B8A8_UINT: return 60; case DXGI_FORMAT_R32G32_FLOAT: return 64; diff --git a/src/startup_stubs/command_list_slot_names.h b/src/startup_stubs/command_list_slot_names.h index 472ef63155..4900e6d6de 100644 --- a/src/startup_stubs/command_list_slot_names.h +++ b/src/startup_stubs/command_list_slot_names.h @@ -2,25 +2,24 @@ // `x2w-noop` log so a line reads "CommandList::slot14(Dispatch)" instead of "CommandList::slot14". // Plain standard C++ with no Windows types, so the table can be compiled and tested on its own. // -// What is claimed, and why: -// - Slots 0 to 9 and 12 to 25 follow the public desktop ID3D12GraphicsCommandList order. The -// implemented slots agree with it at both ends of every run: 7 (GetDevice), 9 (Close), 12 and 13 -// (the draws), 20 to 23 (topology, viewports, scissors, blend factor) and 25 (pipeline state), so -// the slots between them (0 to 6, 8, 14 to 19, 24) take the desktop names. -// - Slots 10 and 11 are not named. The desktop order puts Reset and ClearState there, but this -// console list resets through slot 139, so the desktop order is not known to hold at 10 and 11. -// - Slot 26 accepts the UAV form of ResourceBarrier. Slots 27 to 31 are not named here. The slots -// that follow are the desktop ones moved up by four -// (32 is SetDescriptorHeaps, desktop 28), so four console methods sit somewhere in 26 to 31. -// As a hypothesis, d3d12_xs_device.cpp binds 28, 29 and 30 as BeginQuery, EndQuery and -// ResolveQueryData, only with the diagnostic X2W_D3D12_QUERY_SLOTS=1. No fixture here establishes -// which console methods sit there. -// - Slots 32 to 59 are named as the desktop slots 28 to 55 plus four. Implemented and checked -// against the desktop order: 32, 34, 36, 40, 42, 44, 47, 48, 50 and 52. Past 52 the rule is not -// checked: ExecuteIndirect (desktop 59) is at 61, desktop plus two, so the run of four has ended -// by then. The 56 to 58 names below are kept as the rule gives them. -// - Slots 61 (ExecuteIndirect) and 139 (Reset) are implemented in d3d12_xs_device.cpp. -// - Other slots have no confirmed meaning. +// The 0 to 61, 139 and 148 rows were checked against the GXDK 261000 +// ID3D12GraphicsCommandList8 function table through a local oracle outside the repository. The +// header itself is not copied into this repository; only the public desktop method names and the +// slot numbers are recorded. +// - Slots 0 to 8 are IUnknown, ID3D12Object and ID3D12DeviceChild. +// - 9 Close, 10 Reset and 11 ClearState. +// - 12 to 27 follow the desktop ID3D12GraphicsCommandList order through ExecuteBundle. +// - 28 to 31 are BeginQuery, EndQuery, ResolveQueryData and SetPredication. They sit before the +// desktop SetDescriptorHeaps rather than after DiscardResource. +// - 32 to 55 are the desktop slots 28 to 51 plus four: SetDescriptorHeaps through DiscardResource. +// - 56 to 58 are the unshifted desktop SetMarker, BeginEvent and EndEvent. +// - 59 and 60 are console-only marker methods and stay unnamed in this repository. +// - 61 is ExecuteIndirect (desktop 59, plus two). +// - 139 is the console reset path the title calls. The base Reset is at 10; the log calls the +// console path "Reset (console)" so both rows have distinct names. +// - 62 to 138 and 140 and above are console-only methods. They stay unnamed because their names +// and signatures are not needed by the current log. Slot 148 is the allocation path used by +// list_allocate_upload; it stays unnamed here for the same reason. #pragma once #include <cstddef> @@ -48,7 +47,9 @@ static_assert(desktop_method_count == 51, "ID3D12GraphicsCommandList has 51 meth inline constexpr int console_shift = 4; // console slot = desktop slot + 4, from SetDescriptorHeaps on inline constexpr int resource_barrier_slot = 26; inline constexpr int first_shifted_slot = 32; -inline constexpr int last_shifted_slot = 59; +inline constexpr int last_shifted_slot = 55; +inline constexpr int first_desktop_marker_slot = 56; +inline constexpr int last_desktop_marker_slot = 58; inline constexpr int execute_indirect_slot = 61; inline constexpr int reset_slot = 139; @@ -58,11 +59,14 @@ inline const char* name(int slot) noexcept const auto desktop = [](int index) { return desktop_names[index - first_desktop_method]; }; static constexpr const char* iunknown[] = {"QueryInterface", "AddRef", "Release", "GetPrivateData", "SetPrivateData", "SetPrivateDataInterface", "SetName", "GetDevice", "GetType"}; + static constexpr const char* query[] = {"BeginQuery", "EndQuery", "ResolveQueryData", "SetPredication"}; if (slot >= 0 && slot < first_desktop_method) return iunknown[slot]; - if (slot == first_desktop_method || (slot >= 12 && slot <= resource_barrier_slot)) return desktop(slot); + if (slot >= first_desktop_method && slot <= 27) return desktop(slot); + if (slot >= 28 && slot <= 31) return query[slot - 28]; if (slot >= first_shifted_slot && slot <= last_shifted_slot) return desktop(slot - console_shift); + if (slot >= first_desktop_marker_slot && slot <= last_desktop_marker_slot) return desktop(slot); if (slot == execute_indirect_slot) return "ExecuteIndirect"; - if (slot == reset_slot) return "Reset"; + if (slot == reset_slot) return "Reset (console)"; return nullptr; } diff --git a/src/startup_stubs/commit_state.h b/src/startup_stubs/commit_state.h new file mode 100644 index 0000000000..9d7efeaf82 --- /dev/null +++ b/src/startup_stubs/commit_state.h @@ -0,0 +1,96 @@ +// System commit and job memory for the startup run's diagnostics: the x2w-budget heartbeat line and the first +// commit-limit failures of the physical-page pool (xmem_mapped_pages.cpp). Header only, no allocation. +#pragma once + +#include <windows.h> + +#include <cstdio> + +namespace x2w_local { + +struct SystemCommit { + bool known = false; + unsigned long long used_mib = 0; // charged against the system commit limit (all processes) + unsigned long long limit_mib = 0; // RAM plus page files + unsigned long long avail_mib = 0; // limit minus used: what a new commit can still get +}; + +inline SystemCommit system_commit() noexcept +{ + SystemCommit commit; + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (!GlobalMemoryStatusEx(&status) || status.ullAvailPageFile > status.ullTotalPageFile) return commit; + commit.known = true; + commit.limit_mib = status.ullTotalPageFile >> 20; + commit.avail_mib = status.ullAvailPageFile >> 20; + commit.used_mib = (status.ullTotalPageFile - status.ullAvailPageFile) >> 20; + return commit; +} + +// The memory limit of the job the process runs in (debug_launch.py puts the title in a kill-on-close job whose +// JobMemoryLimit is run.ps1 -MemoryGiB) and the peak commit the job has used. +struct JobMemory { + bool known = false; // the job could be queried (the process is in a job) + bool limited = false; // the job has a JobMemoryLimit + unsigned long long limit_mib = 0; + unsigned long long peak_mib = 0; +}; + +inline JobMemory job_memory() noexcept +{ + JobMemory job; + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + if (!QueryInformationJobObject(nullptr, JobObjectExtendedLimitInformation, &info, sizeof(info), nullptr)) return job; + job.known = true; + job.limited = (info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_JOB_MEMORY) != 0; + job.limit_mib = static_cast<unsigned long long>(info.JobMemoryLimit) >> 20; + job.peak_mib = static_cast<unsigned long long>(info.PeakJobMemoryUsed) >> 20; + return job; +} + +// True when a commit that failed was probably refused by the job limit: the job has one and its peak is within +// `slack_mib` of it (a refused request never reaches the limit itself; 256 MiB covers the largest page batch). +inline bool job_limit_reached(const JobMemory& job, unsigned long long slack_mib = 256) noexcept +{ + return job.known && job.limited && job.limit_mib > 0 && job.peak_mib + slack_mib >= job.limit_mib; +} + +// "commit=<used>/<limit> avail=<free>" in MiB, or "commit=n/a avail=n/a". Returns snprintf's result. +inline int format_commit(char* out, std::size_t size, const SystemCommit& commit) noexcept +{ + if (!commit.known) return std::snprintf(out, size, "commit=n/a avail=n/a"); + return std::snprintf(out, size, "commit=%llu/%llu avail=%llu", commit.used_mib, commit.limit_mib, commit.avail_mib); +} + +// "job_peak=<MiB> job_limit=<MiB>", "job_limit=none" for a job without a limit, "n/a" outside a job. +inline int format_job(char* out, std::size_t size, const JobMemory& job) noexcept +{ + if (!job.known) return std::snprintf(out, size, "job_peak=n/a job_limit=n/a"); + if (!job.limited) return std::snprintf(out, size, "job_peak=%llu job_limit=none", job.peak_mib); + return std::snprintf(out, size, "job_peak=%llu job_limit=%llu", job.peak_mib, job.limit_mib); +} + +// ERROR_COMMITMENT_LIMIT (1455: a commit limit) or ERROR_NOT_ENOUGH_MEMORY (8) from a map or commit. +inline bool is_commit_failure(unsigned long error) noexcept { return error == 1455 || error == 8; } + +// The line logged at the first commit failures of the physical-page pool (xmem_mapped_pages.cpp). It names the +// job memory limit when the job is the likely cause, otherwise the system commit. +inline int format_exhausted(char* out, std::size_t size, const char* what, unsigned long error, const SystemCommit& commit, + const JobMemory& job, unsigned long long sections, unsigned long long slabs, + unsigned long long slots_in_use, unsigned long long slots_free) noexcept +{ + char state[80], jobs[64], cause[96]; + format_commit(state, sizeof(state), commit); + format_job(jobs, sizeof(jobs), job); + if (job_limit_reached(job)) + std::snprintf(cause, sizeof(cause), "job memory limit %llu GiB reached (run.ps1 -MemoryGiB)", (job.limit_mib + 512) >> 10); + else + std::snprintf(cause, sizeof(cause), "job memory limit not reached"); + return std::snprintf(out, size, + "x2w-xmem commit exhausted at %s (error %lu): %s; %s; system %s; pool sections=%llu slabs=%llu slots=%llu/%llu; " + "X2W_XMEM_LAZY_COMMIT=1 (run.ps1 -LazyMemory) keeps untouched pages out of the commit", + what, error, cause, jobs, state, sections, slabs, slots_in_use, slots_free); +} + +} // namespace x2w_local diff --git a/src/startup_stubs/compute_builder_gate.h b/src/startup_stubs/compute_builder_gate.h new file mode 100644 index 0000000000..9daab86150 --- /dev/null +++ b/src/startup_stubs/compute_builder_gate.h @@ -0,0 +1,147 @@ +#pragma once + +// Opt-in all-or-none gate for the console BVH builder's compute pipeline set +// (X2W_COMPUTE_BUILDER_GATE=1). Pure helpers and state, with no Windows calls, so a source-built +// control can check the decision without a device or a title module. +// +// A builder pipeline is a compute pipeline created through device slot 62 whose caller module is +// XboxBvhBuilder.dll. A builder Dispatch is allowed only while every tracked builder pipeline has a +// real desktop pipeline state. The first builder Dispatch attempts the missing creations; one failure +// latches the builder off for the rest of the process, so a partial builder cannot write through +// root views into title memory. + +#include <array> +#include <cstddef> +#include <cstdint> +#include <string_view> + +namespace x2w_startup { + +// The basename of a module path, case-insensitive and accepting either slash. The console builder +// is the only module whose slot 62 compute pipelines this gate tracks. +inline bool is_compute_builder_module(std::wstring_view path) noexcept +{ + constexpr wchar_t expected[] = L"XboxBvhBuilder.dll"; + constexpr std::size_t expected_size = sizeof(expected) / sizeof(expected[0]) - 1; + const std::size_t slash = path.find_last_of(L"\\/"); + const std::wstring_view base = slash == std::wstring_view::npos ? path : path.substr(slash + 1); + if (base.size() != expected_size) return false; + for (std::size_t i = 0; i < expected_size; ++i) { + wchar_t got = base[i]; + wchar_t want = expected[i]; + if (got >= L'A' && got <= L'Z') got = static_cast<wchar_t>(got - L'A' + L'a'); + if (want >= L'A' && want <= L'Z') want = static_cast<wchar_t>(want - L'A' + L'a'); + if (got != want) return false; + } + return true; +} + +enum class BuilderGateDecision : std::uint8_t { + unchanged, // gate off, or the Dispatch does not use a tracked builder pipeline + allow, // every tracked builder pipeline has a desktop PSO + refuse_missing, // at least one tracked builder pipeline has no desktop PSO; the caller may attempt creation + refuse_off, // a creation failed earlier; the builder stays off for the rest of the run +}; + +class BuilderGateState { +public: + // 52 builder programs were observed in the inspected module. The margin leaves room for a + // second creation pass without ever allowing an untracked pipeline into the all-or-none set. + static constexpr unsigned max_pipelines = 64; + + explicit BuilderGateState(bool enabled = false) noexcept : enabled_(enabled) {} + + bool enabled() const noexcept { return enabled_; } + bool off() const noexcept { return off_; } + unsigned tracked() const noexcept { return tracked_; } + unsigned with_pso() const noexcept { return with_pso_; } + unsigned refusals() const noexcept { return refusals_; } + const char* first_reason() const noexcept { return reason_; } + + // Records a slot 62 creation. Only builder pipelines are tracked; a non-builder one changes + // nothing. A repeated pointer updates its state instead of adding an entry. Returns false when + // the builder set cannot be tracked completely, in which case the gate latches off. + bool note_pipeline(const void* pipeline, bool builder, bool real) noexcept + { + if (!enabled_ || !builder || !pipeline) return true; + for (unsigned i = 0; i < tracked_; ++i) { + if (entries_[i].pipeline != pipeline) continue; + if (entries_[i].real != real) { + if (real) ++with_pso_; + else --with_pso_; + entries_[i].real = real; + } + return true; + } + if (tracked_ == max_pipelines) { + note_failed("builder pipeline table is full"); + return false; + } + entries_[tracked_++] = Entry{pipeline, real}; + if (real) ++with_pso_; + return true; + } + + // Marks one tracked pipeline as having a real desktop PSO after an on-the-spot creation. + void note_pso(const void* pipeline) noexcept + { + if (!enabled_ || !pipeline) return; + for (unsigned i = 0; i < tracked_; ++i) { + if (entries_[i].pipeline != pipeline || entries_[i].real) continue; + entries_[i].real = true; + ++with_pso_; + return; + } + } + + // Latches the builder off. The pointer must name a static string; it is reported later. + void note_failed(const char* reason) noexcept + { + if (!enabled_ || off_) return; + off_ = true; + reason_ = reason ? reason : "builder pipeline creation failed"; + } + + // The next pipeline without a desktop PSO at or after index. A real entry yields nullptr, so + // callers can walk the whole table while note_pso updates it. + const void* missing_at(unsigned index) const noexcept + { + return index < tracked_ && !entries_[index].real ? entries_[index].pipeline : nullptr; + } + + BuilderGateDecision decide(bool builder_dispatch) const noexcept + { + if (!enabled_ || !builder_dispatch) return BuilderGateDecision::unchanged; + if (off_) return BuilderGateDecision::refuse_off; + if (tracked_ && with_pso_ == tracked_) return BuilderGateDecision::allow; + return BuilderGateDecision::refuse_missing; + } + + void note_refusal() noexcept { ++refusals_; } + +private: + struct Entry { + const void* pipeline = nullptr; + bool real = false; + }; + std::array<Entry, max_pipelines> entries_{}; + unsigned tracked_ = 0; + unsigned with_pso_ = 0; + unsigned refusals_ = 0; + bool enabled_ = false; + bool off_ = false; + const char* reason_ = nullptr; +}; + +inline const char* builder_gate_reason(BuilderGateDecision decision) noexcept +{ + switch (decision) { + case BuilderGateDecision::unchanged: return "unchanged"; + case BuilderGateDecision::allow: return "allow"; + case BuilderGateDecision::refuse_missing: return "not every builder pipeline has a desktop pipeline"; + case BuilderGateDecision::refuse_off: return "the builder is off for the rest of the run"; + } + return "unknown"; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/console_mode.h b/src/startup_stubs/console_mode.h new file mode 100644 index 0000000000..7bc01ac3fd --- /dev/null +++ b/src/startup_stubs/console_mode.h @@ -0,0 +1,96 @@ +// Experimental (docs/startup-runtime.md): which console the title is told it runs on. +// +// Public GDK documentation describes XSystemGetDeviceType and the XSystemDeviceType values +// (Pc = 1, XboxScarlettLockhart = 6, XboxScarlettAnaconda = 7). The proxied runtime calls seen in +// startup runs include no device-type method. A public runtime reimplementation's notes +// (github.com/Marvisak/VIctory, facts only) say the value is not a runtime call: title code reads +// HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM, DWORD value ConsoleMode, where 0x60 is +// Series S, 0x64 is Series X and a missing value is a PC. Those three readings are that source's, +// not measured here. +// +// X2W_DEVICE_TYPE=<n> (with X2W_RUNTIME_PROXY) answers that one value: 6 -> 0x60, 7 -> 0x64, +// 1 -> missing. Unset or any other number passes every read to the real registry. +// Pure helpers, no Windows calls, so a source-built control can check them. +#pragma once + +#include <cstddef> +#include <cstdint> + +namespace x2w_console_mode { + +constexpr long status_ok = 0, status_not_found = 2, status_invalid = 87, status_more_data = 234, status_wrong_type = 1630; +constexpr unsigned long type_dword = 4; +constexpr unsigned long rrf_rt_reg_dword = 0x10; +constexpr std::uint32_t series_s = 0x60, series_x = 0x64; + +inline wchar_t fold(wchar_t c) noexcept +{ + return (c >= L'A' && c <= L'Z') ? static_cast<wchar_t>(c - L'A' + L'a') : c; +} + +inline bool equal_ci(const wchar_t* a, const wchar_t* b) noexcept +{ + if (!a || !b) return false; + for (;; ++a, ++b) { + if (fold(*a) != fold(*b)) return false; + if (!*a) return true; + } +} + +// Subkey of HKEY_LOCAL_MACHINE. One leading or trailing backslash is accepted. +inline bool is_oem_subkey(const wchar_t* subkey) noexcept +{ + static constexpr wchar_t expect[] = L"software\\microsoft\\windows nt\\currentversion\\oem"; + if (!subkey) return false; + if (*subkey == L'\\') ++subkey; + std::size_t i = 0; + for (; expect[i]; ++i) + if (fold(subkey[i]) != expect[i]) return false; + return !subkey[i] || (subkey[i] == L'\\' && !subkey[i + 1]); +} + +inline bool is_console_mode_value(const wchar_t* name) noexcept +{ + return equal_ci(name, L"ConsoleMode"); +} + +enum class Answer { pass, value, missing }; + +// device_set is false when X2W_DEVICE_TYPE is absent or not a number. +inline Answer answer_for(bool device_set, unsigned long device_type, std::uint32_t* mode) noexcept +{ + if (!device_set) return Answer::pass; + switch (device_type) { + case 1: return Answer::missing; + case 6: if (mode) *mode = series_s; return Answer::value; + case 7: if (mode) *mode = series_x; return Answer::value; + default: return Answer::pass; + } +} + +// RegQueryValueExW's output rules for one REG_DWORD. +inline long fill_query(std::uint32_t value, unsigned long* type, unsigned char* data, unsigned long* bytes) noexcept +{ + if (data && !bytes) return status_invalid; + if (type) *type = type_dword; + if (!data) { + if (bytes) *bytes = sizeof(value); + return status_ok; + } + if (*bytes < sizeof(value)) { + *bytes = sizeof(value); + return status_more_data; + } + for (std::size_t i = 0; i < sizeof(value); ++i) data[i] = static_cast<unsigned char>(value >> (8 * i)); + *bytes = sizeof(value); + return status_ok; +} + +// RegGetValueW's: the flags must allow a DWORD (RRF_RT_REG_DWORD, part of RRF_RT_DWORD and RRF_RT_ANY). +inline long fill_get(unsigned long flags, std::uint32_t value, unsigned long* type, void* data, unsigned long* bytes) noexcept +{ + if (!(flags & rrf_rt_reg_dword)) return status_wrong_type; + return fill_query(value, type, static_cast<unsigned char*>(data), bytes); +} + +} // namespace x2w_console_mode diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6f92733f06..4f8e00c18e 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -9,6 +9,28 @@ // TABL (descriptor table binds), PRES (present). tools read it with out/gamerun/capture.py. struct Translation; +bool copy_title_bytes(void* to, const void* from, std::size_t bytes) noexcept; +using FixedMeshBytes = std::shared_ptr<const std::vector<unsigned char>>; +// GPU recordings can outlive guest Release. Share immutable inputs by content until the validated +// request is durably published. The index holds no strong ownership of its own. +FixedMeshBytes intern_fixed_mesh_bytes(std::vector<unsigned char> bytes) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_multimap<u64, std::weak_ptr<const std::vector<unsigned char>>> index; + u64 hash = 1469598103934665603ull; + for (auto byte : bytes) hash = (hash ^ byte) * 1099511628211ull; + x2w_startup::ExclusiveNoteLock guard(lock); + const auto range = index.equal_range(hash); + for (auto it = range.first; it != range.second;) { + if (auto existing = it->second.lock()) { + if (*existing == bytes) return existing; + ++it; + } else it = index.erase(it); + } + auto stage = std::make_shared<const std::vector<unsigned char>>(std::move(bytes)); + index.emplace(hash, stage); + return stage; +} struct PipelineInfo { Translation* stream_translation = nullptr; bool has_stream_blend = false; @@ -22,8 +44,15 @@ struct PipelineInfo { Wrapper* base = nullptr; // slot 55: the pipeline it derives from std::vector<unsigned char> desc; std::vector<unsigned char> state_a, state_b; // slot 57: the two state blocks, copied at creation (the title frees them) + mutable FixedMeshBytes fixed_ms, fixed_ps; + mutable std::vector<x2w::PixelHeapSpan> mesh57_pixel_spans; + mutable UINT mesh57_heap_word = UINT_MAX; // R32_UINT at guest root constant[heap_word] & 1023. + mutable std::vector<x2w_startup::Mesh57BufferRead> mesh57_reads; // Host SRV register order. }; struct ViewRecord { + // Capture the guest descriptor layout, independent of the desktop SDK. + static constexpr std::size_t srv_desc_bytes = 40; + static constexpr std::size_t uav_desc_bytes = 40; std::uint32_t id, slot; // slot: 17 CBV, 18 SRV, 19 UAV, 20 RTV, 21 DSV, 22 sampler u64 resource, counter; // title-side wrapper pointers (or 0) u64 dest_title, dest_desktop; @@ -61,6 +90,45 @@ std::vector<std::uint8_t>& view_materialized() { static std::vector<std::uint8_t std::unordered_map<u64, std::uint32_t>& view_ids() { static std::unordered_map<u64, std::uint32_t> m; return m; } // content hash -> view id LONG64 views_noted, views_distinct, descriptors_copied; +// X2W_D3D12_VIEW_CENSUS=1 (diagnostic only, docs/startup-runtime.md): new distinct view records by slot, and one line +// before an insertion that is expected to grow view_records or the view_ids buckets. All fields: note_lock held. +bool view_census_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_VIEW_CENSUS"); + return on; +} +struct ViewCensus { + u64 distinct[6]; // slots 17..22 + u64 grows_records, grows_ids; // growths announced + u64 missed; // capacity or bucket count changed without an announcement +}; +ViewCensus view_census{}; + +std::size_t view_census_format(char* out, std::size_t capacity, const char* what) +{ + const ViewCensus& c = view_census; + const int n = std::snprintf(out, capacity, + "x2w-view-census %s: cbv=%llu srv=%llu uav=%llu rtv=%llu dsv=%llu sampler=%llu records=%llu capacity=%llu " + "ids=%llu buckets=%llu grows-records=%llu grows-ids=%llu missed=%llu", + what, c.distinct[0], c.distinct[1], c.distinct[2], c.distinct[3], c.distinct[4], c.distinct[5], + static_cast<u64>(view_records().size()), static_cast<u64>(view_records().capacity()), + static_cast<u64>(view_ids().size()), static_cast<u64>(view_ids().bucket_count()), + c.grows_records, c.grows_ids, c.missed); + return n < 0 ? 0 : (std::min)(static_cast<std::size_t>(n), capacity - 1); +} + +// Fixture only (x2w_d3d12_fail_view_allocations, startup_view_alloc): the next `count` allocations at a site fail as an +// exhausted heap would. The vector sites fail only when the vector has to grow; view_ids fails before any insertion, +// because each new entry allocates. +enum ViewAllocation { view_records_site, view_materialized_site, view_ids_site, view_allocation_sites }; +volatile LONG view_allocations_to_fail[view_allocation_sites]; + +void view_allocation_gate(ViewAllocation site) +{ + for (LONG n = view_allocations_to_fail[site]; n > 0; n = view_allocations_to_fail[site]) + if (InterlockedCompareExchange(&view_allocations_to_fail[site], n - 1, n) == n) throw std::bad_alloc(); +} + // The shadow entry for a desktop CPU descriptor handle (note_lock held), or null. std::uint32_t* shadow_slot(u64 desktop_handle, std::uint32_t* room = nullptr) { @@ -81,6 +149,38 @@ std::uint32_t shadow_id(u64 desktop_handle) return id; } +// A descriptor slot that names a desktop resource: 18 SRV, 19 UAV, 20 RTV, 21 DSV. Slot 19 names two resources, the +// view resource and the counter resource it may be paired with; slots 17 (CBV) and 22 (sampler) name none. +bool view_slot_names_resource(std::uint32_t slot) +{ + return slot >= 18 && slot <= 21; +} +// The refs a materialized view record holds in a tracked descriptor slot: one for the slot's resource and, for a +// slot-19 UAV, one more for its counter resource. One ref per slot, so the draw drain (retire_view_refs == 0) frees the +// resource only once no tracked slot names it; repeated writes of the same view add nothing (note_view compares ids). +void view_refs_add(std::uint32_t slot, u64 resource, u64 counter) +{ + if (!view_slot_names_resource(slot)) return; + if (resource) retire_add_view_ref(reinterpret_cast<const void*>(resource)); + if (slot == 19 && counter) retire_add_view_ref(reinterpret_cast<const void*>(counter)); +} +// Drops exactly the refs view_refs_add added for a materialized record: the overwrite in note_view, a copy that moves +// another view over the slot (note_copy), and the destruction of the slot's heap (retire_drop_heap_views). +void view_refs_release(std::uint32_t slot, u64 resource, u64 counter) +{ + if (!view_slot_names_resource(slot)) return; + if (resource) retire_release_view_ref(reinterpret_cast<const void*>(resource)); + if (slot == 19 && counter) retire_release_view_ref(reinterpret_cast<const void*>(counter)); +} +// The untracked-descriptor fallback: no slot can hold the resource for a view in a heap the shim does not shadow, so +// the use takes the resource (and a slot-19 counter) out of the retire class for good, as before. +void view_refs_leave_class(std::uint32_t slot, u64 resource, u64 counter, RetireLeft why) +{ + if (!view_slot_names_resource(slot)) return; + if (resource) retire_leave_class(reinterpret_cast<const void*>(resource), why); + if (slot == 19 && counter) retire_leave_class(reinterpret_cast<const void*>(counter), why); +} + constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV" bool title_backed(u64 title_handle, u64 bytes) @@ -92,6 +192,26 @@ bool title_backed(u64 title_handle, u64 bytes) ReleaseSRWLockShared(&descriptor_lock); return inside; } +// True when the descriptor already holds a view created on the desktop: by its desktop shadow entry, or by a +// materialized token the title copied into title memory with its own memory copy. +bool descriptor_has_live_view(u64 desktop_handle, u64 title_handle) +{ + AcquireSRWLockShared(¬e_lock); + const std::uint32_t* slot = shadow_slot(desktop_handle); + std::uint32_t id = slot ? *slot : 0; + bool live = id && id - 1 < view_records().size() && view_materialized()[id - 1]; + ReleaseSRWLockShared(¬e_lock); + if (live || title_handle == desktop_handle || !title_backed(title_handle, 32) || + !x2w_local::readable(reinterpret_cast<const void*>(title_handle), 32)) + return live; + std::uint32_t words[8]; + std::memcpy(words, reinterpret_cast<const void*>(title_handle), sizeof(words)); + if (words[0] != view_token_magic) return false; + AcquireSRWLockShared(¬e_lock); + live = words[1] < view_records().size() && view_materialized()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + return live; +} void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std::size_t bytes, Translation* translation = nullptr, const D3D12_BLEND_DESC* blend = nullptr, @@ -118,6 +238,25 @@ void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std info.base = as_wrapper(base); const std::size_t have = desc ? readable_window(reinterpret_cast<u64>(desc), bytes) : 0; if (have) info.desc.assign(static_cast<const unsigned char*>(desc), static_cast<const unsigned char*>(desc) + have); + if (path == 57 && have >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info.desc.data(), sizeof(words)); + const auto snapshot = [&](int field, FixedMeshBytes& stage) { + const auto bytes = words[field + 1]; + if (!bytes) return !words[field]; + const auto* data = reinterpret_cast<const void*>(words[field]); + if (bytes > (1u << 20) || !x2w_local::readable(data, bytes)) return false; + std::vector<unsigned char> copy(static_cast<size_t>(bytes)); + if (!copy_title_bytes(copy.data(), data, copy.size())) return false; + stage = intern_fixed_mesh_bytes(std::move(copy)); + return true; + }; + if (!words[9] && !words[10] && words[14] && + (!snapshot(5, info.fixed_ps) || !snapshot(13, info.fixed_ms))) { + info.fixed_ps.reset(); + info.fixed_ms.reset(); + } + } if (path == 57 && have >= 0x28) { u64 words[5]; std::memcpy(words, desc, sizeof(words)); @@ -277,6 +416,62 @@ void note_heap(Wrapper* w, UINT type, UINT count, UINT logical_count, UINT incre static_cast<std::uint32_t*>(VirtualAlloc(nullptr, (u64{count} + 1) * 4, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE))}); ReleaseSRWLockExclusive(¬e_lock); } + +// Room for one more element, with the 1.5x growth push_back would use: reserve(size + 1) would copy on every insert. +template<class T> +void reserve_one_view_entry(std::vector<T>& v, ViewAllocation site) +{ + if (v.size() < v.capacity()) return; + view_allocation_gate(site); + v.reserve(v.capacity() + v.capacity() / 2 + 1); +} + +// Adds a new record to the three view containers, or to none of them (note_lock held). Everything that can allocate +// comes first: the two reservations change no size, and a failed try_emplace leaves the map unchanged. The two +// push_back calls then have room and cannot fail. Returns the name of the container that could not allocate, or null. +const char* store_view(const ViewRecord& record, std::uint8_t created, u64 hash) +{ + const char* growing = "view_records"; + try { + reserve_one_view_entry(view_records(), view_records_site); + growing = "view_materialized"; + reserve_one_view_entry(view_materialized(), view_materialized_site); + growing = "view_ids"; + view_allocation_gate(view_ids_site); + view_ids().try_emplace(hash, record.id); + } catch (const std::bad_alloc&) { + return growing; + } + view_records().push_back(record); + view_materialized().push_back(created); + return nullptr; +} + +// A new view could not be recorded. The desktop descriptor already holds it, so the destination must stop naming the +// view it held before: the slot and its title token are cleared, and a draw refuses the descriptor instead of binding +// the old view. Nothing records the new view's use of its resource, so the resource leaves the retire class and is not +// released early. Allocates nothing. Enters with note_lock held and releases it. +void drop_unrecorded_view(const ViewRecord& record, bool materialized, const char* container) +{ + if (std::uint32_t* slot_ptr = shadow_slot(record.dest_desktop)) { + const std::uint32_t prev = *slot_ptr; + *slot_ptr = 0; + if (prev && prev - 1 < view_records().size() && view_materialized()[prev - 1]) + view_refs_release(view_records()[prev - 1].slot, view_records()[prev - 1].resource, + view_records()[prev - 1].counter); + } + if (materialized) view_refs_leave_class(record.slot, record.resource, record.counter, RetireLeft::view); + ReleaseSRWLockExclusive(¬e_lock); + const std::size_t token_bytes = record.slot == 22 ? x2w_startup::title_sampler_stride : 32u; + if (record.dest_title != record.dest_desktop && title_backed(record.dest_title, token_bytes) && + x2w_local::writable(reinterpret_cast<void*>(record.dest_title), token_bytes)) + std::memset(reinterpret_cast<void*>(record.dest_title), 0, token_bytes); + static LONG failed; + if (first_calls(failed, 8)) + log("x2w-d3d12 note_view: out of memory in %s -> view of slot %u not recorded, destination descriptor untracked", + container, record.slot); +} + // A view is created: remembered by id; the id is also written into title-owned descriptor memory so // that copies the title makes there itself can be followed. void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop, @@ -306,21 +501,53 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ record.id = found->second; } else { record.id = static_cast<std::uint32_t>(view_records().size()); - view_records().push_back(record); - view_materialized().push_back(created); - view_ids()[hash] = record.id; + const bool census = view_census_enabled(); + std::size_t capacity_before = 0, buckets_before = 0; + bool records_full = false, ids_full = false; + if (census) { + capacity_before = view_records().capacity(); + buckets_before = view_ids().bucket_count(); + records_full = view_records().size() == capacity_before; + // MSVC's rule: unordered_map rehashes when the new size would exceed the maximum load factor. + ids_full = static_cast<float>(view_ids().size() + 1) / static_cast<float>(buckets_before) > + view_ids().max_load_factor(); + // Logged before the allocation, so the last line survives an allocation that fails. + if (records_full || ids_full) { + view_census.grows_records += records_full; + view_census.grows_ids += ids_full; + char line[640]; + view_census_format(line, sizeof(line), + records_full && ids_full ? "before growth of records and ids" + : records_full ? "before growth of records" + : "before growth of ids"); + log("%s (new slot %u)", line, record.slot); + } + } + if (const char* container = store_view(record, created, hash)) { + drop_unrecorded_view(record, materialized, container); + return; + } ++views_distinct; + if (census) { + if (record.slot >= 17 && record.slot <= 22) ++view_census.distinct[record.slot - 17]; + view_census.missed += !records_full && view_records().capacity() != capacity_before; + view_census.missed += !ids_full && view_ids().bucket_count() != buckets_before; + } } if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { const std::uint32_t prev = *slot_ptr; *slot_ptr = record.id + 1; + // The same view written to the same slot again keeps its id and changes no reference count. A different view + // takes over the slot: the new record adds its refs, the previous materialized record drops its own. if (prev != record.id + 1) { - if (slot == 18 && resource && materialized) retire_add_view_ref(reinterpret_cast<const void*>(resource)); - if (prev && prev - 1 < view_records().size() && view_records()[prev - 1].slot == 18 && view_materialized()[prev - 1]) - retire_release_view_ref(reinterpret_cast<const void*>(view_records()[prev - 1].resource)); + if (materialized) view_refs_add(static_cast<std::uint32_t>(slot), resource, counter); + if (prev && prev - 1 < view_records().size() && view_materialized()[prev - 1]) + view_refs_release(view_records()[prev - 1].slot, view_records()[prev - 1].resource, + view_records()[prev - 1].counter); } - } else if (slot == 18 && resource) { - retire_leave_class(reinterpret_cast<const void*>(resource), RetireLeft::view); + } else if (view_slot_names_resource(static_cast<std::uint32_t>(slot)) && resource) { + // A descriptor no shadow slot tracks cannot hold the view: the use takes the resource out of the class. + view_refs_leave_class(static_cast<std::uint32_t>(slot), resource, counter, RetireLeft::view); } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; @@ -340,34 +567,37 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, const std::uint32_t* from = shadow_slot(src_desktop, &src_room); if (to && count <= dest_room) { if (from && count <= src_room) { + // Every copied-in view is now named by one more tracked slot; every view the destination named before is + // replaced. Slots 18-21 count one ref (slot 19 one for the resource and one for its counter). for (UINT i = 0; i < count; ++i) { const std::uint32_t src_id = from[i]; - if (src_id && src_id - 1 < view_records().size() && - view_records()[src_id - 1].slot == 18 && view_materialized()[src_id - 1]) - retire_add_view_ref(reinterpret_cast<const void*>(view_records()[src_id - 1].resource)); + if (src_id && src_id - 1 < view_records().size() && view_materialized()[src_id - 1]) + view_refs_add(view_records()[src_id - 1].slot, view_records()[src_id - 1].resource, + view_records()[src_id - 1].counter); } for (UINT i = 0; i < count; ++i) { const std::uint32_t old_id = to[i]; - if (old_id && old_id - 1 < view_records().size() && - view_records()[old_id - 1].slot == 18 && view_materialized()[old_id - 1]) - retire_release_view_ref(reinterpret_cast<const void*>(view_records()[old_id - 1].resource)); + if (old_id && old_id - 1 < view_records().size() && view_materialized()[old_id - 1]) + view_refs_release(view_records()[old_id - 1].slot, view_records()[old_id - 1].resource, + view_records()[old_id - 1].counter); } std::memmove(to, from, u64{count} * 4); } else { for (UINT i = 0; i < count; ++i) { const std::uint32_t old_id = to[i]; - if (old_id && old_id - 1 < view_records().size() && - view_records()[old_id - 1].slot == 18 && view_materialized()[old_id - 1]) - retire_release_view_ref(reinterpret_cast<const void*>(view_records()[old_id - 1].resource)); + if (old_id && old_id - 1 < view_records().size() && view_materialized()[old_id - 1]) + view_refs_release(view_records()[old_id - 1].slot, view_records()[old_id - 1].resource, + view_records()[old_id - 1].counter); } std::memset(to, 0, u64{count} * 4); } } else if (from && count <= src_room) { + // The destination is not tracked: the copy puts the views where no shadow slot can hold them. for (UINT i = 0; i < count; ++i) { const std::uint32_t src_id = from[i]; - if (src_id && src_id - 1 < view_records().size() && - view_records()[src_id - 1].slot == 18 && view_materialized()[src_id - 1]) - retire_leave_class(reinterpret_cast<const void*>(view_records()[src_id - 1].resource), RetireLeft::view_copy); + if (src_id && src_id - 1 < view_records().size() && view_materialized()[src_id - 1]) + view_refs_leave_class(view_records()[src_id - 1].slot, view_records()[src_id - 1].resource, + view_records()[src_id - 1].counter, RetireLeft::view_copy); } } ReleaseSRWLockExclusive(¬e_lock); diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl new file mode 100644 index 0000000000..d028bf7951 --- /dev/null +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -0,0 +1,1227 @@ +// Translated compute programs at Dispatch (list slot 14). A device slot 67 pipeline is a placeholder that keeps +// the key of its published request; gfx2hlsl.py --pending answers the request with <key>.txt (`stage cs`) and +// <key>.cs.cso. Bound from the compute tables recorded by slot 35 and compute root SRVs recorded by slot 43: raw +// buffers (`srv <i> buf table <param> <byte>` and `srv <i> buf root <param>` inputs, `uav <i> table <param> <byte>` +// outputs, `uav <i> bufhalf table <param> <byte> bytes <stride>` for typed half stores, or +// `uav <i> bufd16x table <param> <byte> bytes 2` for a one-component packed D16 store) +// named by hardware buffer descriptors or 64-bit root SRV addresses, and textures +// (`srv <i> tex1d|tex2d|tex2da|tex3d table <param> <byte>` inputs, `uav <i> tex1d/tex2d/tex2da/tex3d float table <param> <byte> channels <n>` outputs) named +// by the token of a view the title created (device slots 18 and 19). `smp`, `smpl` and `smpc` lines become static samplers. Entry +// values come from the compute root constants of slots 37 and 39, or from the descriptor a buffer input or output is +// bound from: its stride and word 3 (`stride`, `descword3`), and word 3, the upper half of word 1 and the record +// count of an output (`uav_descword3`, `uav_stride`, `uav_numrecords`). Any other manifest line makes the translation +// unavailable; a dispatch that cannot be bound completely is refused with one reason and records no Dispatch and +// binds nothing (the upload of an input texture the title filled in memory may already be recorded: it only +// syncs content). + +const char* volume_uav_range_error(const D3D12_RESOURCE_DESC& resource, const D3D12_TEX3D_UAV& view) +{ + if (view.MipSlice >= resource.MipLevels) return "an output 3D texture mip is outside the resource"; + const UINT depth = (std::max)(1u, UINT{resource.DepthOrArraySize} >> (std::min)(view.MipSlice, 15u)); + if (view.FirstWSlice >= depth || !view.WSize || (view.WSize != ~0u && view.WSize > depth - view.FirstWSlice)) + return "an output 3D texture W range is outside the mip"; + return nullptr; +} + +struct ComputeTranslation { + // Root parameter and byte offset (views), or parameter and word (entry values). A heap view names the root + // constant (parameter and word) that indexes its 32-byte record in the list's view heap, or, with word_param + // set, the table buffer (word_param, word_byte) whose word at byte at + root constant (a, b) * times (a < 0: + // at alone) is the index. An entry value that is not a root constant names input or output a by its source. + enum Source { root_constant, input_stride, input_word3, output_word3, output_stride, output_records }; + struct Slot { + int a, b; + bool texture, heap; + int word_param = -1, word_byte = 0; + std::uint32_t at = 0, times = 0; + Source source = root_constant; + D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN; + bool root = false; + bool array = false; + unsigned half_typed_bytes = 0; + bool packed_d16_x = false; + unsigned scalar_window = 0; + bool atomic_uint_texture = false; + unsigned channels = 4; + D3D12_SRV_DIMENSION srv_dimension = D3D12_SRV_DIMENSION_UNKNOWN; + unsigned half_buffer_bytes = 0; + }; + u64 key = 0; + int state = 0; // 0 not loaded, 1 ready, 2 unavailable + x2w_startup::ManifestRetry manifest_retry; // absent and stale manifests can become ready later + std::vector<Slot> uds, srvs, uavs; + UINT heap_srvs = 0; + x2w_startup::TranslatedSamplers samplers; // static ones only + x2w_startup::ComPtr<ID3D12RootSignature> root; + x2w_startup::ComPtr<ID3D12PipelineState> pipeline; + const char* unmodelled = nullptr; // why a manifest that exists cannot be used + bool logged_token_output = false, logged_bound_token_output = false; + u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded + const char* first_refusal = nullptr; // reason of the first refused call + bool input_path_logged = false; // the first time a placed input came from a GPU copy or a title snapshot + std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any; a view token's + // last word is replaced by its view format | dimension << 16 + ~ComputeTranslation() + { + // The per-process cache is destroyed during DLL detach. A driver may already have shut + // down when the process is terminating. Explicit unload still releases both references. + if (x2w_startup::d3d12_process_terminating) { + pipeline.Detach(); + root.Detach(); + } + } +}; + +// Component counts of the float and normalized formats accepted for typed outputs. +unsigned float_output_channels(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_B8G8R8A8_UNORM: + return 4; + case DXGI_FORMAT_R11G11B10_FLOAT: + return 3; + case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: + return 2; + case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_SNORM: + return 1; + default: + return 0; + } +} + +// Published `bufd16x` stores one halfword. native_buffer_store_view accepts an R32_UINT element +// (two halfwords, stride widened to 4) and rewrites R16_FLOAT / R16_UINT to R16_UINT. This path +// keeps that check, then refuses anything that is not the rewritten one-halfword view: a 32-bit +// element would store a zero-extended payload over both halfwords. +const char* packed_d16_x_view_refusal(const std::uint32_t* words, UINT64 offset, UINT64 resource_bytes, + D3D12_UNORDERED_ACCESS_VIEW_DESC& out) +{ + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + const unsigned stride_field = words[1] >> 16; + const unsigned stride = stride_field & 0x3fffu; + const unsigned word3 = words[3]; + const unsigned format = (word3 >> 12) & 127u; + const bool unified = (word3 & 0x01000000u) != 0; + unsigned element = 0; + if (unified && format == 13) { + view.Format = DXGI_FORMAT_R16_FLOAT; + element = 2; + } else if (unified && format == 11) { + view.Format = DXGI_FORMAT_R16_UINT; + element = 2; + } else if (unified && format == 20) { + view.Format = DXGI_FORMAT_R32_UINT; + element = 4; + } + // TYPE, reserved, ADD_TID_ENABLE and INDEX_STRIDE, plus SWIZZLE_ENABLE / CACHE_SWIZZLE and OOB_SELECT. + constexpr unsigned word3_flags = 0xcef80000u; + const bool flags = (stride_field & 0xc000u) != 0 || (word3 & word3_flags) != 0 || ((word3 >> 28) & 3u) != 0; + if (flags) + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + if (!element || (word3 & 7u) != 4u || stride != element) + view.Format = DXGI_FORMAT_UNKNOWN; + const unsigned step = element ? element : 1u; + if (offset % step) + return "an output packed D16 buffer is not element-aligned in its resource"; + view.Buffer.FirstElement = static_cast<UINT>(offset / step); + view.Buffer.NumElements = words[2] ? words[2] : 1u; + const x2w::ComputeViewBinding binding{x2w::ComputeViewKind::packed_d16_x_uav, 0, 0, 0, 2}; + if (!x2w::native_buffer_store_view(binding, view, resource_bytes) || view.Format != DXGI_FORMAT_R16_UINT) + return "formatted D16 write has an incompatible typed buffer UAV"; + out = view; + return nullptr; +} + +bool half_buffer_descriptor_matches(const std::uint32_t* words, unsigned bytes) +{ + // gfx10 V# with identity selectors for each stored component and structured + // bounds (OOB_SELECT=0). Swizzled or padded records need a different view. + const unsigned format = bytes == 2 ? 13 : bytes == 4 ? 29 : 71; + const unsigned selectors = (1u << (3 * (bytes / 2))) - 1; + return (words[1] >> 16) == bytes && (words[3] & (0xfffff000u | selectors)) == + (0x01000000u | (format << 12) | (0xfacu & selectors)); +} +std::unordered_map<u64, ComputeTranslation>& compute_translations() { static std::unordered_map<u64, ComputeTranslation> m; return m; } +LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; +LONG compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib; // inputs by path: this list's GPU copy, a title snapshot + +// The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is +// unavailable, or null when it is ready. +const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, std::size_t bytes) +{ + // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. + if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.empty() ? 1 : tr.uds.size()), + static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root, static_cast<UINT>(tr.uavs.size()), false, tr.heap_srvs))) + return "root signature creation failed"; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = tr.root.Get(); + desc.CS = {code, bytes}; + if (FAILED(device_of(the_device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(&tr.pipeline)))) + return "pipeline creation failed"; + tr.state = 1; + return nullptr; +} + +// draw_lock held. Returns the reason the translation is unavailable, or null when it is ready or still absent. +const char* load_compute_translation(ComputeTranslation& tr) +{ + tr.state = 2; + if (native_shaders_only()) { + tr.manifest_retry.found(); + return nullptr; + } + wchar_t path[MAX_PATH]; + std::string manifest; + if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { + tr.manifest_retry.missed(GetTickCount64()); + return nullptr; + } + // A native manifest from another compiler revision, or an unmarked one without the Python translator's + // <key>.cs.hlsl, is stale: it is looked for again on the same schedule as an absent one. + const auto output = x2w::native_compute_output(manifest); + if (output == x2w::NativeComputeOutput::incompatible) { + tr.manifest_retry.missed(GetTickCount64()); + return "native translation from another compiler revision; rebuild it"; + } + if (output == x2w::NativeComputeOutput::unmarked) { + const DWORD attributes = cache_path(path, L"", tr.key, L".cs.hlsl") + ? GetFileAttributesW(path) : INVALID_FILE_ATTRIBUTES; + if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY)) { + tr.manifest_retry.missed(GetTickCount64()); + return "native translation without a revision; rebuild it"; + } + } + tr.manifest_retry.found(); + unsigned declared_uds = 0, line_number = 0; + for (std::size_t at = 0; at < manifest.size(); ++line_number) { + std::size_t end = manifest.find('\n', at); + if (end == std::string::npos) end = manifest.size(); + std::string line = manifest.substr(at, end - at); + at = end + 1; + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line_number == 0) { + if (line != "x2w-manifest 2") return "manifest version"; + continue; + } + if (line_number == 1) { + if (line != "stage cs") return "not a compute manifest"; + continue; + } + if (line.compare(0, 7, "native ") == 0) continue; + unsigned i = 0, x = 0, y = 0, z = 0, w = 0; + int a = 0, b = 0, c = 0, d = 0, used = 0; + char name[16] = ""; + const auto whole = [&] { return used == static_cast<int>(line.size()); }; + // The manifest names of the Source values after root_constant, in their order. + const auto source = [&] { + static const char* const names[] = {"stride", "descword3", "uav_descword3", "uav_stride", "uav_numrecords"}; + for (int s = 0; s < 5; ++s) + if (!std::strcmp(name, names[s])) return static_cast<ComputeTranslation::Source>(s + 1); + return ComputeTranslation::root_constant; + }; + const auto uav_dimension = [&] { + if (!std::strcmp(name, "tex1d")) return D3D12_UAV_DIMENSION_TEXTURE1D; + if (!std::strcmp(name, "tex2d")) return D3D12_UAV_DIMENSION_TEXTURE2D; + if (!std::strcmp(name, "tex2da")) return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + if (!std::strcmp(name, "tex3d")) return D3D12_UAV_DIMENSION_TEXTURE3D; + return D3D12_UAV_DIMENSION_UNKNOWN; + }; + const auto srv_dimension = [&] { + if (!std::strcmp(name, "tex1d")) return D3D12_SRV_DIMENSION_TEXTURE1D; + if (!std::strcmp(name, "tex2d")) return D3D12_SRV_DIMENSION_TEXTURE2D; + if (!std::strcmp(name, "tex2da")) return D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + if (!std::strcmp(name, "tex3d")) return D3D12_SRV_DIMENSION_TEXTURE3D; + return D3D12_SRV_DIMENSION_UNKNOWN; + }; + if (line.empty() || (std::sscanf(line.c_str(), "group %u %u %u%n", &x, &y, &z, &used) == 3 && whole())) continue; + if (std::sscanf(line.c_str(), "ud %u%n", &declared_uds, &used) == 1 && whole()) continue; + if (std::sscanf(line.c_str(), "udsrc %u rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uds.size()) + tr.uds.push_back({a, b}); + else if (std::sscanf(line.c_str(), "udsrc %u %15s %d%n", &i, name, &a, &used) == 3 && whole() && i == tr.uds.size() && + source() != ComputeTranslation::root_constant) + tr.uds.push_back({a, 0, false, false, -1, 0, 0, 0, source()}); + else if (std::sscanf(line.c_str(), "srv %u buf table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "srv %u buf root %d%n", &i, &a, &used) == 2 && whole() && a >= 0 && + i == tr.srvs.size()) { + tr.srvs.push_back({a, 0}); + tr.srvs.back().root = true; + } + else if (std::sscanf(line.c_str(), "srv %u buf heap rootconst %d %d%n", &i, &a, &b, &used) == 3 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({a, b, false, true}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u%n", &i, &a, &b, &x, &used) == 4 && whole() && + i == tr.srvs.size()) + tr.srvs.push_back({-1, 0, false, true, a, b, x}); + else if (std::sscanf(line.c_str(), "srv %u buf heap word table %d %d at %u rootconst %d %d times %u%n", &i, &a, &b, &x, + &c, &d, &y, &used) == 7 && whole() && i == tr.srvs.size()) + tr.srvs.push_back({c, d, false, true, a, b, x, y}); + else if (std::sscanf(line.c_str(), "uav %u table %d %d%n", &i, &a, &b, &used) == 3 && whole() && i == tr.uavs.size()) + tr.uavs.push_back({a, b}); + else if (std::sscanf(line.c_str(), "uav %u bufhalf table %d %d bytes %u%n", &i, &a, &b, &x, &used) == 4 && + whole() && i == tr.uavs.size() && x2w::native_half_buffer_format(x) != DXGI_FORMAT_UNKNOWN) { + tr.uavs.push_back({a, b}); + tr.uavs.back().half_buffer_bytes = x; + } + else if (std::sscanf(line.c_str(), "uav %u bufd16x table %d %d bytes %u%n", &i, &a, &b, &x, &used) == 4 && + whole() && i == tr.uavs.size() && x == 2) { + tr.uavs.push_back({a, b}); + tr.uavs.back().packed_d16_x = true; + } + else if (std::sscanf(line.c_str(), "uav %u tex2d uint table %d %d channels 1%n", &i, &a, &b, &used) == 3 && + whole() && i == tr.uavs.size()) { + tr.uavs.push_back({a, b, true}); + tr.uavs.back().uav_dimension = D3D12_UAV_DIMENSION_TEXTURE2D; + tr.uavs.back().atomic_uint_texture = true; + } + else if (std::sscanf(line.c_str(), "uav %u %15s float table %d %d channels %u%n", &i, name, &a, &b, &x, &used) == 5 && + whole() && i == tr.uavs.size() && x >= 1 && x <= 4 && uav_dimension() != D3D12_UAV_DIMENSION_UNKNOWN && + (x == 4 || uav_dimension() != D3D12_UAV_DIMENSION_TEXTURE1D)) { + tr.uavs.push_back({a, b, true}); + tr.uavs.back().uav_dimension = uav_dimension(); + tr.uavs.back().channels = x; + } + else if (std::sscanf(line.c_str(), "srv %u %15s table %d %d%n", &i, name, &a, &b, &used) == 4 && whole() && + i == tr.srvs.size() && srv_dimension() != D3D12_SRV_DIMENSION_UNKNOWN) { + tr.srvs.push_back({a, b, true}); + tr.srvs.back().srv_dimension = srv_dimension(); + } + else if (std::sscanf(line.c_str(), "resheap %u %u%n", &x, &y, &used) == 2 && whole()) { + if (tr.heap_srvs || !x || x > x2w_startup::max_translated_resheap || y != x2w_startup::translated_resheap_space) + return "a resource heap range outside the supported layout"; + tr.heap_srvs = x; + } + // A static sampler, decoded as the draw path does: plain (smp), with the descriptor's LOD clamp (smpl) or a + // comparison one (smpc). Not modelled here: the run-time sampler heap table (smpheap). + else if (line.rfind("smpheap", 0) == 0) return "a sampler from the sampler heap"; + else if ((std::sscanf(line.c_str(), "smp %u %x %x %x %x%n", &i, &x, &y, &z, &w, &used) == 5 || + std::sscanf(line.c_str(), "smpl %u %x %x %x %x%n", &i, &x, &y, &z, &w, &used) == 5 || + std::sscanf(line.c_str(), "smpc %u %x %x %x %x%n", &i, &x, &y, &z, &w, &used) == 5) && whole() && + i == tr.samplers.statics.size()) + tr.samplers.read_manifest_line(line.c_str()); + else return line.rfind("srv", 0) == 0 ? "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture" + : line.rfind("uav", 0) == 0 ? "an unsupported compute output view" + : line.rfind("udsrc", 0) == 0 ? "an entry value that is not a root constant or a buffer descriptor word" + : line.rfind("smp", 0) == 0 ? "a sampler that is not a plain static one" : "an unknown manifest line"; + } + if (tr.uds.size() != declared_uds || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) + return "entry value, input or output count"; + for (const ComputeTranslation::Slot& ud : tr.uds) { + const auto& slots = ud.source >= ComputeTranslation::output_word3 ? tr.uavs : tr.srvs; + if (ud.source != ComputeTranslation::root_constant && + (ud.a < 0 || static_cast<std::size_t>(ud.a) >= slots.size() || slots[ud.a].texture || slots[ud.a].root)) + return "an entry value names a descriptor that is not a buffer input or output"; + } + x2w_startup::ComPtr<ID3DBlob> code; + if (!cache_path(path, L"", tr.key, L".cs.cso") || FAILED(D3DReadFileToBlob(path, &code))) return "no compiled program"; + if (const char* failure = create_compute_pipeline(tr, code->GetBufferPointer(), code->GetBufferSize())) return failure; + log("x2w-draw compute pipeline %016llx translated: %zu entry values, %zu inputs, %zu outputs", tr.key, tr.uds.size(), + tr.srvs.size(), tr.uavs.size()); + return nullptr; +} + +// X2W_NATIVE_SHADERS=<directory of dxcompiler.dll and dxil.dll>: the first Dispatch of a slot 67 request translates +// it in this process with the C++ compiler (src/gfx1013_compute_native.cpp), before a published <key>.txt is read +// and with no offline translator running. The dispatch path below binds the result, so a program is accepted only +// with root constants, raw table buffers and exact-width typed texture outputs. +// A refusal is logged and leaves the key to the published translations. draw_lock held. Returns whether tr is ready. +bool translate_compute_natively(ComputeTranslation& tr) +{ +#ifdef X2W_NATIVE_SHADERS + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!length || length >= MAX_PATH) return false; + if (!cache_path(path, L"req_", tr.key, L".c67")) return false; + auto refuse_native = [&](const char* reason) { + tr.uds.clear(); + tr.srvs.clear(); + tr.uavs.clear(); + tr.root.Reset(); + tr.pipeline.Reset(); + static LONG logged; + if (first_calls(logged, 16)) + log("x2w-draw compute pipeline %016llx not translated natively: %s", tr.key, reason); + return false; + }; + try { + // The request as this runtime published it. The reader checks the six parts against the key in the name. + // Entry 0: a source-built program starts there, and the frontend reads a capture's v_nop prefix as code. + auto frozen = frozen_compute_requests().take(tr.key); + if (frozen) x2w::validate_compute_request_shape(*frozen); + else frozen.emplace(x2w::read_compute_request(path)); + x2w::NativeComputeShader program; + auto result = x2w::ComputePackResult::miss; + if (const auto* pack = runtime_compute_pack()) { + std::string diagnostic; + result = pack->lookup(*frozen, 0, program, diagnostic); + if (result == x2w::ComputePackResult::unsupported) { + InterlockedIncrement(&compute_pack_refused); + return refuse_native(diagnostic.c_str()); + } + InterlockedIncrement(result == x2w::ComputePackResult::prepared ? &compute_pack_prepared : &compute_pack_misses); + } + if (result == x2w::ComputePackResult::miss) + program = x2w::translate_compute(*frozen, 0, true); + for (const auto& block : program.constants) + for (unsigned word = 0; word < block.count; ++word) + tr.uds.push_back({static_cast<int>(block.root_parameter), static_cast<int>(word)}); + for (unsigned srv : program.stride_srvs) { + const bool present = std::any_of(program.bindings.begin(), program.bindings.end(), [srv](const auto& view) { + return view.kind == x2w::ComputeViewKind::raw_vector_srv && view.shader_register == srv; + }); + if (!present) throw std::runtime_error("descriptor stride source is not a bound SRV"); + ComputeTranslation::Slot slot{}; + slot.a = static_cast<int>(srv); + slot.source = ComputeTranslation::input_stride; + tr.uds.push_back(slot); + } + std::sort(program.bindings.begin(), program.bindings.end(), + [](const auto& a, const auto& b) { return a.shader_register < b.shader_register; }); + for (const auto& view : program.bindings) { + const unsigned channels = x2w::exact_texture_uav_channels(view.kind); + const bool packed_x = view.kind == x2w::ComputeViewKind::packed_d16_x_uav; + const bool half_typed = packed_x || view.kind == x2w::ComputeViewKind::half_buffer_uav; + const bool texture_input = view.kind == x2w::ComputeViewKind::texture_srv && view.image_dimension == 1; + const bool volume = view.kind == x2w::ComputeViewKind::texture_uav && view.image_dimension == 2; + const bool output = view.kind == x2w::ComputeViewKind::raw_buffer_uav || half_typed || volume || channels; + auto& slots = output ? tr.uavs : tr.srvs; + if ((!output && !texture_input && view.kind != x2w::ComputeViewKind::raw_vector_srv && !x2w::accepts_cbv_window(view.kind)) || view.array_count != 1 || + view.root_parameter >= 16 || view.shader_register != slots.size()) + throw std::runtime_error("view kind " + std::to_string(static_cast<unsigned>(view.kind)) + + " is not bound for a natively translated program"); + slots.push_back({static_cast<int>(view.root_parameter), static_cast<int>(view.byte_offset), volume || texture_input}); + if (volume) slots.back().uav_dimension = D3D12_UAV_DIMENSION_TEXTURE3D; + slots.back().half_typed_bytes = half_typed ? view.required_bytes : 0; + slots.back().packed_d16_x = packed_x; + if (x2w::accepts_cbv_window(view.kind)) + slots.back().scalar_window = view.required_bytes; + if (channels) { + auto& slot = slots.back(); + slot.texture = true; + slot.channels = channels; + slot.uav_dimension = view.image_dimension == 2 ? D3D12_UAV_DIMENSION_TEXTURE3D : + view.image_dimension == 5 ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : + D3D12_UAV_DIMENSION_TEXTURE2D; + } + } + if (!program.samplers.empty() || tr.uds.size() > 32 || tr.srvs.size() > 32 || tr.uavs.size() > 8) + throw std::runtime_error("a sampler, or more entry values, inputs or outputs than the dispatch path binds"); + // A direct module declares wave size 32 (src/dxil_module.h): without it the pipeline cannot be created. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) || + !waves.WaveOps || waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) + throw std::runtime_error("the adapter has no 32-lane waves"); + // Never released: a static destructor would release DXC after its module may have detached. + static x2w::ShaderDxilCompiler* const compiler = + new x2w::ShaderDxilCompiler(x2w::ShaderDxilCompiler::runtime_worker(sdk)); + const auto shader = compiler->compile(program.dxil_ir, L"cs_6_6", std::filesystem::path(path).parent_path() / L"native", + x2w::ShaderSourceFormat::dxil_ir); + if (const char* failure = create_compute_pipeline(tr, shader.dxil.data(), shader.dxil.size())) + throw std::runtime_error(failure); + log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs (frontend %s)", tr.key, + tr.uds.size(), tr.srvs.size(), tr.uavs.size(), + result == x2w::ComputePackResult::prepared ? "prepared" : "live"); + return true; + } catch (const std::exception& error) { + return refuse_native(error.what()); + } +#else + (void)tr; + return false; +#endif +} + +// Resolve a compute root SRV (`srv <i> buf root <param>`) from the guest address recorded by slot 43 for <param> +// to the end of its backing upload allocation or aliased placed buffer (up to the 16 MiB compute raw buffer limit). +IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int param, std::uint32_t (&words)[8], + const char** why) +{ + const auto refuse = [why](const char* reason) { + if (why) *why = reason; + return IndirectBufferView{}; + }; + if (why) *why = nullptr; + const auto* root_params = pass.compute_root_wrapper ? root_info(pass.compute_root_wrapper) : nullptr; + if (!root_params || param < 0 || static_cast<std::size_t>(param) >= root_params->size() || + static_cast<std::size_t>(param) >= pass.compute_root_srvs.size() || + (*root_params)[param].type != D3D12_ROOT_PARAMETER_TYPE_SRV) + return refuse("a compute root input is not a shader resource view parameter"); + if (!(pass.compute_root_srv_set & (u64{1} << param))) + return refuse("a compute root SRV was not set since the compute root"); + const u64 address = pass.compute_root_srvs[param]; + words[0] = static_cast<std::uint32_t>(address); + words[1] = static_cast<std::uint32_t>(address >> 32); + if (!address) return refuse("a compute root SRV has a null address"); + if (address % 4) return refuse("a compute root SRV address is not 4-byte aligned"); + constexpr u64 limit = 16u << 20; + if (const auto allocation = list_upload_tail(self, address); allocation.resource) { + if (allocation.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + return refuse("a compute root SRV range is not 16-byte aligned in its resource"); + const u64 bytes = (std::min)(allocation.bytes, limit) & ~u64{3}; + if (bytes < 4) + return refuse("a compute root SRV has fewer than 4 aligned bytes in its upload allocation"); + words[2] = static_cast<std::uint32_t>(bytes); + return {allocation.resource, allocation.offset, bytes, 0, true}; + } + Wrapper* device = self->own().list_device; + const auto first = placed_buffer_range(device, address, 4); + if (first.reject) return refuse("a compute root SRV crosses the end of a placed buffer"); + if (!first.owner) return refuse("a compute root SRV is in title memory outside any placed buffer"); + if (!InterlockedCompareExchange(&first.owner->own().refs, 0, 0)) + return refuse("a compute root SRV's resource is released"); + const auto* info = resource_info(first.owner); + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) + return refuse("a compute root SRV's resource was not created in the common state"); + const u64 base = reinterpret_cast<u64>(first.owner->own().title_memory); + if (!base || address < base || address - base >= info->bytes) + return refuse("a compute root SRV range is outside its desktop buffer"); + const u64 offset = address - base; + if (offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + return refuse("a compute root SRV range is not 16-byte aligned in its resource"); + const u64 bytes = (std::min)(info->bytes - offset, limit) & ~u64{3}; + if (bytes < 4) + return refuse("a compute root SRV has fewer than 4 aligned bytes in its placed buffer"); + const auto placed = placed_buffer_range(device, address, bytes); + if (placed.reject || placed.owner != first.owner) + return refuse("a compute root SRV crosses the end of a placed buffer"); + auto* native = static_cast<ID3D12Resource*>(placed.owner->own().real); + if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) + return refuse("a compute root SRV is in a placed buffer that does not alias title memory"); + x2w_startup::ComPtr<ID3D12Device> native_device; + if (!native || FAILED(native->GetDevice(IID_PPV_ARGS(native_device.GetAddressOf()))) || + native_device.Get() != device_of(device)) + return refuse("a compute root SRV's resource is on another device"); + const auto desc = native->GetDesc(); + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || + offset > desc.Width || bytes > desc.Width - offset) + return refuse("a compute root SRV range is outside its desktop buffer"); + words[2] = static_cast<std::uint32_t>(bytes); + return {native, offset, bytes, 0, false}; +} + +// A slot-19 token identifies a view, not a four-dword gfx1013 buffer descriptor. +struct ComputeTokenOutput { + ID3D12Resource* resource{}; + u64 offset{}, bytes{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + D3D12_RESOURCE_DESC backing{}; + Placement placement{}; + bool created{}; + u64 guest_base{}, guest_resource{}, counter{}, desktop_gpuva{}; + UINT description_bytes{}; +}; + +const char* compute_token_output(Wrapper* list, const std::uint32_t* words, ComputeTokenOutput& output) +{ + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + if (words[1] < view_records().size()) { + record = view_records()[words[1]]; + output.created = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + if (words[2] != 19 || words[3] || record.slot != 19) + return "an output token does not identify a slot-19 UAV"; + output.guest_resource = record.resource; + output.description_bytes = record.desc_bytes; + output.counter = record.counter; + if (record.desc_bytes >= sizeof(output.view)) std::memcpy(&output.view, record.desc, sizeof(output.view)); + auto* owner = as_wrapper(reinterpret_cast<void*>(record.resource)); + auto* resource = owner && owner->own().kind == resource_kind ? static_cast<ID3D12Resource*>(owner->own().real) : nullptr; + const ResourceInfo* info = owner && owner->own().kind == resource_kind ? resource_info(owner) : nullptr; + if (info) { + output.placement = info->placement; + output.guest_base = reinterpret_cast<u64>(owner->own().title_memory); + output.backing = info->console; + } + if (!output.created || !record.resource || record.counter || record.desc_bytes < sizeof(output.view)) + return "an output token lacks a materialized explicit counterless UAV"; + if (output.view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER || !info || + info->console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + return "a raw buffer writer was bound to a non-buffer UAV"; + if (!resource) return "an output token has no desktop resource"; + output.backing = resource->GetDesc(); + if (output.backing.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + return "a raw buffer writer was bound to a non-buffer backing"; + if (!(output.backing.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || + info->initial_state != D3D12_RESOURCE_STATE_COMMON) + return "an output token's backing lacks tracked UAV access"; + if (trace_compute_outputs()) output.desktop_gpuva = resource->GetGPUVirtualAddress(); + const auto& view = output.view.Buffer; + const bool raw = view.Flags == D3D12_BUFFER_UAV_FLAG_RAW && output.view.Format == DXGI_FORMAT_R32_TYPELESS && + !view.StructureByteStride; + const bool structured = view.Flags == D3D12_BUFFER_UAV_FLAG_NONE && output.view.Format == DXGI_FORMAT_UNKNOWN && + view.StructureByteStride; + const bool typed = view.Flags == D3D12_BUFFER_UAV_FLAG_NONE && !view.StructureByteStride; + const UINT element = raw ? 4 : structured ? view.StructureByteStride : + typed ? x2w_startup::typed_buffer_format_bytes(desktop_format(output.view.Format)) : 0; + if (!element || view.CounterOffsetInBytes || view.FirstElement > UINT64_MAX / element) + return "an output UAV has no supported byte interval"; + output.offset = view.FirstElement * element; + output.bytes = u64{view.NumElements} * element; + if (!output.bytes || output.bytes % 4 || output.bytes > (16u << 20) || + output.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || output.offset > output.backing.Width || + output.bytes > output.backing.Width - output.offset) + return "an output UAV interval is unaligned, oversized or outside its buffer"; + const auto base = reinterpret_cast<u64>(owner->own().title_memory); + if (base) { + if (output.offset > UINT64_MAX - base) return "an output UAV placement address overflows"; + const auto placed = placed_buffer_range(list->own().list_device, base + output.offset, output.bytes); + if (placed.reject) return "an output UAV range overlaps or crosses active placements"; + if (placed.owner != owner) return "an output UAV range no longer resolves to its token owner"; + // A slot-19 token identifies an object. For a complete view its committed + // backing is the host buffer used by subsequent object-based GPU commands. + // This mode does not imply CPU aliasing or make a partial view authoritative. + static const bool copied_views = x2w_local::env_on("X2W_COPIED_OBJECT_UAV"); + const bool whole_copy = copied_views && info->placement == Placement::copied_buffer && + output.offset == 0 && output.bytes == info->bytes && output.bytes == output.backing.Width; + if (placed.alias != resource && !whole_copy) + return "an output token's backing does not uniquely alias its guest byte interval"; + } else { + D3D12_HEAP_PROPERTIES heap{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(resource->GetHeapProperties(&heap, &flags)) || heap.Type != D3D12_HEAP_TYPE_DEFAULT) + return "an output UAV without guest shadow is not on the default heap"; + } + x2w_startup::ComPtr<ID3D12Device> device; + if (FAILED(resource->GetDevice(IID_PPV_ARGS(device.GetAddressOf()))) || device.Get() != device_of(list->own().list_device)) + return "an output UAV belongs to a different device"; + output.resource = resource; + return nullptr; +} + +// Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. +const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch) +{ + auto* list = recording(self); + Pass& pass = pass_of(self); + const u64 key = pass.pipeline->own().compute_request_key; + const auto [x, y, z] = dispatch.groups; + const char* reason = nullptr; + LONG* counter = &compute_dispatches_refused; + struct View { + ID3D12Resource* resource; + u64 offset, bytes; + bool transition, texture, described; + union { + D3D12_SHADER_RESOURCE_VIEW_DESC srv; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav; + } desc; // a described desktop texture or typed buffer view + Wrapper* wrapper; + std::uint32_t words[4]; // a buffer's descriptor words as it was bound from, and its stride + UINT stride; + }; + static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) >= ViewRecord::srv_desc_bytes); + static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) >= ViewRecord::uav_desc_bytes); + const auto type = list->GetType(); + AcquireSRWLockExclusive(&draw_lock); + ComputeTranslation* const tr = &compute_translations()[key]; + tr->key = key; + ++tr->dispatches; + std::uint32_t words[8] = {}; + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) reason = "the list type has no Dispatch"; + else if (x > x2w_startup::max_dispatch_groups || y > x2w_startup::max_dispatch_groups || z > x2w_startup::max_dispatch_groups) + reason = "a group count is over the limit"; + else if (pass.compute_root_wrapper != pass.pipeline->own().compute_request_root) + reason = "the compute root set is not the one the pipeline was created with"; + else if (!ensure_draw_heap(self->own().list_device)) reason = "no descriptor heap on this device"; + else { + if (!tr->state || tr->manifest_retry.due(GetTickCount64())) { + // The in-process translation is tried once per key, before a published one. + if (tr->state || !translate_compute_natively(*tr)) { + tr->unmodelled = load_compute_translation(*tr); + if (tr->unmodelled) log("x2w-draw compute pipeline %016llx not translated: %s", key, tr->unmodelled); + } + } + if (tr->state != 1) { + // A manifest the runtime cannot bind is the dispatch side's work; an absent one is the translator's. + reason = tr->unmodelled ? tr->unmodelled : "no translation"; + counter = tr->unmodelled ? &compute_dispatches_unmodelled : &compute_dispatches_untranslated; + } + } + // A word no slot 37 or 39 call wrote since the compute root was set has no value to pass (it is not 0). + for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) + if (tr->uds[i].source == ComputeTranslation::root_constant && !pass.compute_constants.is_bound(tr->uds[i].a, tr->uds[i].b, 1)) + reason = "an entry value was not set since the compute root"; + const std::size_t inputs = reason ? 0 : tr->srvs.size(), count = reason ? 0 : inputs + tr->uavs.size(); + std::vector<View> views(reason ? 0 : count + tr->heap_srvs); + if (!reason && dispatch.signature && tr->heap_srvs) + reason = "translated indirect Dispatch requires fixed-table raw buffers"; + for (std::size_t i = 0; i < count && !reason; ++i) { + const bool output = i >= inputs; + const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; + if (dispatch.signature && (slot.heap || slot.texture || slot.root)) { + reason = "translated indirect Dispatch requires fixed-table raw buffers"; + break; + } + std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); + std::memset(words, 0, sizeof(words)); + if (!output && slot.root) { + const IndirectBufferView view = compute_root_srv_buffer(self, pass, slot.a, words, &reason); + if (reason && !tr->first_refusal) + log("x2w-draw compute %016llx first refused input %zu (root %d), address 0x%llx", key, i, slot.a, + u64{words[0]} | (u64{words[1]} << 32)); + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + views[i].stride = view.stride; + std::memcpy(views[i].words, words, sizeof(views[i].words)); + continue; + } + if (slot.word_param >= 0) { + // The index word is read now from the recording's upload memory, where the title wrote it (no GPU command + // writes there), at the dword-aligned 32-bit byte offset the program reads it at. + const u64 table_entry = pass.compute_tables.table(slot.word_param).record(static_cast<u64>(slot.word_byte), 16); + if (!table_entry || !x2w_local::readable(reinterpret_cast<const void*>(table_entry), 16)) { + reason = "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast<const void*>(table_entry), 16); + const std::uint32_t at = slot.at + index * slot.times; + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + if (words[0] == view_token_magic || !list_upload_range(self, address + at, 4).resource) { + reason = "a heap index word is not in the list's upload memory"; + break; + } + if (u64{at} + 4 > u64{stride ? stride : 1} * words[2]) { + reason = "a heap index word is outside its table buffer"; + break; + } + std::memcpy(&index, reinterpret_cast<const void*>(address + at), 4); + } + // A heap record sits at the 32-bit byte offset the program computes, the index shifted left by 5, in the + // title memory of the list's view heap: a literal byte offset, as a table's is. + const u64 entry = slot.heap ? ((slot.word_param >= 0 || slot.a >= 0) && index < pass.title_view_heap_entries + ? pass.title_view_heap.record(std::uint32_t{index << 5}, 16) : 0) + : slot.a < 0 || slot.b < 0 ? 0 : pass.compute_tables.table(slot.a).record(static_cast<u64>(slot.b), slot.texture ? 32 : 16); + const std::size_t entry_bytes = slot.texture ? 32 : 16; + if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), entry_bytes)) { + reason = slot.heap ? "a heap record is outside the list's view heap" : "a table descriptor is not bound"; + break; + } + std::memcpy(words, reinterpret_cast<const void*>(entry), entry_bytes); + if (slot.texture) { + // The title's descriptor memory carries the id of the view it created there. Nothing else is bound: + // a null view would read zeros or drop the program's stores without a trace. + ViewRecord record{}; + bool known = false, created = false; + if (words[0] == view_token_magic) { + AcquireSRWLockShared(¬e_lock); + known = words[1] < view_records().size(); + if (known) { + record = view_records()[words[1]]; + created = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + } + Wrapper* const wrapper = known ? as_wrapper(reinterpret_cast<const void*>(record.resource)) : nullptr; + ID3D12Resource* const texture = !wrapper || wrapper->own().kind != resource_kind ? nullptr + : output ? static_cast<ID3D12Resource*>(wrapper->own().real) : sampled_address_texture(wrapper); + const D3D12_RESOURCE_DESC resource = texture ? texture->GetDesc() : D3D12_RESOURCE_DESC{}; + if (!output) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= ViewRecord::srv_desc_bytes; + if (described) std::memcpy(&desc, record.desc, ViewRecord::srv_desc_bytes); + if (desc.Format) desc.Format = desktop_format(desc.Format); + words[3] = static_cast<std::uint32_t>(desc.Format ? desc.Format : resource.Format) | static_cast<std::uint32_t>(desc.ViewDimension) << 16; + if (!known || record.slot != 18) reason = "an input texture entry is not the token of a shader resource view"; + else if (!texture || (resource.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) + reason = "an input texture has no desktop texture to sample"; + else if (slot.srv_dimension != D3D12_SRV_DIMENSION_TEXTURE2D) { + // 1D, 2D array and 3D: only the title's own described view of that dimension, inside its texture. + const bool one = slot.srv_dimension == D3D12_SRV_DIMENSION_TEXTURE1D; + const bool array = slot.srv_dimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + if (!described) + reason = one ? "an input 1D texture has no recorded view description" + : array ? "an input 2D array texture has no recorded view description" + : "an input 3D texture has no recorded view description"; + else if (desc.ViewDimension != slot.srv_dimension) + reason = one ? "an input texture view is not 1D" : array ? "an input texture view is not 2D array" + : "an input texture view is not 3D"; + else if (!x2w_startup::address_view_fits(resource, desc)) + reason = "an input texture view does not fit its texture"; + else if (x2w_startup::packed_target_format(desc.Format)) reason = "an input texture view has a packed format"; + } + else if (described ? desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an input texture view is not 2D"; + // shortcut: a packed format needs the stand-in rules of the draw path; add them with its first user. + else if (x2w_startup::packed_target_format(desc.Format)) reason = "an input texture view has a packed format"; + views[i] = {texture, 0, 0, true, true, described}; + views[i].desc.srv = desc; + views[i].wrapper = wrapper; + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + const bool described = record.desc_bytes >= ViewRecord::uav_desc_bytes; + if (described) std::memcpy(&desc, record.desc, ViewRecord::uav_desc_bytes); + if (desc.Format) desc.Format = desktop_format(desc.Format); + const DXGI_FORMAT format = desc.Format ? desc.Format : resource.Format; + words[3] = static_cast<std::uint32_t>(format) | static_cast<std::uint32_t>(desc.ViewDimension) << 16; + if (!known || record.slot != 19) reason = "an output texture entry is not the token of an unordered access view"; + else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + texture && (resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const auto& view = desc.Texture3D; + if (!described || desc.ViewDimension != slot.uav_dimension || resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) + reason = "an output texture view or resource is not 3D"; + else { + // Slot 19 can retain a rejected range as an unmaterialized view. + reason = volume_uav_range_error(resource, view); + if (!reason && !created) reason = "an output texture view was not created on the desktop"; + } + } else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + texture && (resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + // Checked before `created`, as for 3D: slot 19 records a 1D view with an out-of-range mip as refused. + if (!described || desc.ViewDimension != slot.uav_dimension || resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D) + reason = "an output texture view or resource is not 1D"; + else if (desc.Texture1D.MipSlice >= resource.MipLevels) + reason = "an output 1D texture mip is outside the resource"; + else if (!created) + reason = "an output texture view was not created on the desktop"; + } else if (!created || !texture || !(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output texture view was not created on the desktop"; + else if (slot.uav_dimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY) { + // The layer in HLSL is relative to FirstArraySlice: retain the caller's complete view. + const auto& a = desc.Texture2DArray; + if (!described || desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY) + reason = "an output texture view is not a 2D array"; + else if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.SampleDesc.Count != 1 || + a.PlaneSlice || a.MipSlice >= resource.MipLevels || a.FirstArraySlice >= resource.DepthOrArraySize || + !a.ArraySize || a.ArraySize > resource.DepthOrArraySize - a.FirstArraySlice) + reason = "an output texture array view is outside the resource"; + } else if (described ? desc.ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D || desc.Texture2D.PlaneSlice + : resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || resource.DepthOrArraySize != 1) + reason = "an output texture view is not 2D"; + if (!reason && x2w_startup::packed_target_format(format)) reason = "an output texture view has a packed format"; + if (!reason && slot.atomic_uint_texture && format != DXGI_FORMAT_R32_UINT) + reason = "an image atomic requires an R32_UINT UAV"; + if (!reason && slot.channels < 4) { + if (float_output_channels(format) != slot.channels || float_output_channels(resource.Format) != slot.channels) + reason = "an exact-width image store requires a matching output texture channel count"; + else { + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{resource.Format}; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, + sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) + reason = "an exact-width image store requires typed UAV store support"; + desc.Format = resource.Format; + } + } + if (!reason && !slot.atomic_uint_texture && !float_output_channels(format)) + reason = "an output texture format is not a float or normalized one"; + // One state per resource here: a texture read and written by the same call is refused. Two outputs + // of one texture (two mips) share the unordered access state. + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].wrapper == wrapper) reason = "an output texture is also an input of the dispatch"; + views[i] = {texture, 0, 0, true, true, described}; + views[i].desc.uav = desc; + views[i].wrapper = wrapper; + continue; + } + if (!output) { + // Each condition of a complete GPU-backed buffer range has its own reason. + auto view = indirect_table_buffer(self, words, false, &reason, 16u << 20, D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, true); + if (reason && slot.scalar_window && words[0] != view_token_magic && + !std::strcmp(reason, "an input is in title memory outside any placed buffer")) { + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 extent = u64{stride ? stride : 1} * words[2]; + const u64 bytes = extent; + u64 start{}; + ID3D12Resource* chunk{}; + if (bytes >= slot.scalar_window && bytes <= 65536 && bytes % 4 == 0 && + readable_window(address, bytes) >= bytes && frame_copy(self, address, bytes, &start, &chunk) && chunk) { + view = {chunk, start, bytes, stride, true, 2}; + reason = nullptr; + } + } + if (view.source == 1) InterlockedIncrement(&compute_inputs_gpu_copied); + if (view.source == 2) { + InterlockedIncrement(&compute_inputs_snapshot); + InterlockedExchangeAdd(&compute_inputs_snapshot_kib, static_cast<LONG>((view.bytes + 1023) / 1024)); + } + if (view.source && !tr->input_path_logged) { + tr->input_path_logged = true; + log("x2w-draw compute %016llx input %zu (%s %d %d) comes from %s (%llu bytes)", key, i, slot.heap ? "heap" : "table", slot.a, slot.b, + view.source == 1 ? "a GPU copy this list made" : view.source == 3 ? "zeros for a null descriptor" : "a snapshot of title memory", view.bytes); + } + if (view.resource && view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input buffer range is not 16-byte aligned in its resource"; + if (reason && !tr->first_refusal) // once per key: which input, and where its descriptor was read + log("x2w-draw compute %016llx first refused input %zu (%s %d %d), descriptor at 0x%llx", key, i, + slot.heap ? "heap" : "table", slot.a, slot.b, entry); + views[i] = {view.resource, view.offset, view.bytes, !view.upload}; + views[i].stride = view.stride; + std::memcpy(views[i].words, words, sizeof(views[i].words)); + continue; + } + if (words[0] == view_token_magic) { + ComputeTokenOutput token{}; + reason = compute_token_output(self, words, token); +#ifdef X2W_NATIVE_SHADERS + if (!reason && slot.half_typed_bytes) { + const auto kind = slot.packed_d16_x ? x2w::ComputeViewKind::packed_d16_x_uav : x2w::ComputeViewKind::half_buffer_uav; + const x2w::ComputeViewBinding binding{kind, 0, 0, 0, slot.half_typed_bytes}; + token.view.Format = desktop_format(token.view.Format); + if (!x2w::native_buffer_store_view(binding, token.view, token.backing.Width)) + reason = "formatted D16 write has an incompatible typed buffer UAV"; + } +#endif + if (!reason && slot.packed_d16_x && !slot.half_typed_bytes) { + token.view.Format = desktop_format(token.view.Format); + const x2w::ComputeViewBinding binding{x2w::ComputeViewKind::packed_d16_x_uav, 0, 0, 0, 2}; + if (!x2w::native_buffer_store_view(binding, token.view, token.backing.Width) || + token.view.Format != DXGI_FORMAT_R16_UINT) + reason = "formatted D16 write has an incompatible typed buffer UAV"; + } + if (reason && token.placement == Placement::copied_buffer && + trace_copied_compute_output(key, token.guest_resource, token.guest_base, token.offset, token.bytes)) { + log("x2w-compute-output-watch key=%016llx groups=%u,%u,%u indirect=%u owner=0x%llx gpuva=0x%llx", + key, x, y, z, dispatch.signature != nullptr, token.guest_resource, token.desktop_gpuva); + for (const auto& ud : tr->uds) + if (ud.source == ComputeTranslation::root_constant) + log("x2w-compute-output-constant key=%016llx root=%d word=%d value=0x%08x", key, ud.a, ud.b, + pass.compute_constants.word(ud.a, ud.b)); + } + for (const auto& ud : tr->uds) + if (ud.source >= ComputeTranslation::output_word3 && ud.a == static_cast<int>(i - inputs) && !reason) + reason = "an output token has no original ISA descriptor words for entry constants"; + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].resource == token.resource) reason = "an output buffer is also an input"; + if (!reason && !retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(token.resource))) + reason = "an output token's backing could not be retained with the recording"; + if (!tr->logged_token_output || (!reason && !tr->logged_bound_token_output)) { + tr->logged_token_output = true; + if (!reason) tr->logged_bound_token_output = true; + log("x2w-draw compute UAV %016llx table=%d+%d entry=0x%llx token=%u created=%u dim=%u fmt=%u " + "first=%llu elements=%u stride=%u flags=%u backing-dim=%u backing-bytes=%llu backing-flags=%u " + "placement=%u owner=0x%llx guest-base=0x%llx counter=0x%llx desc-bytes=%u offset=%llu bytes=%llu result=%s", + key, slot.a, slot.b, entry, words[1], token.created, token.view.ViewDimension, token.view.Format, + token.view.Buffer.FirstElement, token.view.Buffer.NumElements, token.view.Buffer.StructureByteStride, + token.view.Buffer.Flags, token.backing.Dimension, token.backing.Width, token.backing.Flags, + static_cast<unsigned>(token.placement), token.guest_resource, token.guest_base, token.counter, + token.description_bytes, token.offset, token.bytes, reason ? reason : "bound"); + } + views[i] = {token.resource, token.offset, token.bytes, true}; + if (!reason && (slot.half_typed_bytes || slot.packed_d16_x)) { + views[i].described = true; + views[i].desc.uav = token.view; + } + continue; + } + if (slot.half_typed_bytes) { + reason = "formatted D16 write needs the original typed buffer view"; + break; + } + // Hardware descriptors address guest memory directly and must name a unique writable alias. + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const unsigned half_bytes = slot.half_buffer_bytes; + const bool packed = slot.packed_d16_x && !slot.half_typed_bytes; + const unsigned alignment = half_bytes ? half_bytes : (packed ? 2u : D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT); + const u64 bytes = u64{stride ? stride : 1} * words[2]; + const bool sized = words[0] != view_token_magic && bytes && (half_bytes || packed || bytes % 4 == 0) && bytes <= (16u << 20); + const auto placed = sized ? placed_buffer_range(self->own().list_device, address, bytes) : PlacedVertexView{}; + const ResourceInfo* info = placed.alias ? resource_info(placed.owner) : nullptr; + const u64 offset = placed.alias ? address - reinterpret_cast<u64>(placed.owner->own().title_memory) : 0; + if (words[0] == view_token_magic) reason = "an output buffer descriptor is a view token"; + else if (half_bytes && !half_buffer_descriptor_matches(words, half_bytes)) + reason = "a half buffer store requires matching format, stride and structured bounds"; + else if (!bytes) reason = "an output buffer descriptor has zero records"; + else if (!sized) reason = half_bytes ? "an output half buffer range is over 16 MiB" + : packed ? "an output packed D16 buffer range is over 16 MiB" + : "an output buffer range is over 16 MiB or not whole dwords"; + else if (placed.reject) reason = "an output range crosses the end of a placed buffer"; + else if (!placed.owner) reason = "an output is in title memory outside any placed buffer"; + else if (!placed.alias) reason = "an output is in a placed buffer that does not alias title memory"; + else if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) + reason = "an output buffer's resource was not created in the common state"; + else if (offset % alignment) reason = half_bytes ? "an output half buffer is not element-aligned in its resource" + : packed ? "an output packed D16 buffer is not element-aligned in its resource" + : "an output buffer range is not 16-byte aligned in its resource"; + else if (!(placed.alias->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + reason = "an output buffer has no unordered access"; + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; + D3D12_UNORDERED_ACCESS_VIEW_DESC packed_desc{}; + if (!reason && packed) + reason = packed_d16_x_view_refusal(words, offset, placed.alias->GetDesc().Width, packed_desc); + if (reason && !tr->first_refusal) + log("x2w-draw compute raw UAV %016llx table=%d+%d entry=0x%llx words=%08x/%08x/%08x/%08x " + "stride=%u bytes=%llu result=%s", key, slot.a, slot.b, entry, words[0], words[1], words[2], words[3], + stride, bytes, reason); + views[i] = {placed.alias, offset, bytes, true}; + if (!reason && half_bytes) { + const auto format = x2w::native_half_buffer_format(half_bytes); + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + constexpr UINT required = D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + (support.Support1 & required) != required || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) { + reason = "an output half buffer format does not support typed UAV stores"; + } else { + views[i].described = true; + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = format; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.FirstElement = offset / half_bytes; + desc.Buffer.NumElements = words[2]; + views[i].desc.uav = desc; + } + } + if (!reason && packed) { + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{packed_desc.Format}; + constexpr UINT required = D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; + if (FAILED(device_of(the_device)->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + (support.Support1 & required) != required || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) { + reason = "an output packed D16 buffer format does not support typed UAV stores"; + } else { + views[i].described = true; + views[i].desc.uav = packed_desc; + } + } + std::memcpy(views[i].words, words, sizeof(views[i].words)); + } + for (UINT r = 0; r < tr->heap_srvs && !reason; ++r) { + std::memset(words, 0, sizeof(words)); + const u64 entry = r < pass.title_view_heap_entries ? pass.title_view_heap.record(u64{r} << 5, 16) : 0; + if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), 16)) { + reason = "a heap record is outside the list's view heap"; + break; + } + std::memcpy(words, reinterpret_cast<const void*>(entry), 16); + const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20); + if (view.resource && view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) + reason = "an input buffer range is not 16-byte aligned in its resource"; + if (reason && !tr->first_refusal) + log("x2w-draw compute %016llx first refused heap record %u, descriptor at 0x%llx", key, r, entry); + for (std::size_t output = inputs; output < count && !reason; ++output) + if (views[output].resource == view.resource) reason = "an output buffer is also an input"; + views[count + r] = {view.resource, view.offset, view.bytes, !view.upload}; + views[count + r].stride = view.stride; + std::memcpy(views[count + r].words, words, sizeof(views[count + r].words)); + } + if (dispatch.argument) + for (std::size_t i = 0; i < count && !reason; ++i) + if (views[i].resource == dispatch.argument) reason = "the indirect argument buffer is also a bound shader resource"; + // An entry value from a descriptor comes from the words its view was bound from in the loop above. + std::uint32_t values[32] = {}; + for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) { + const ComputeTranslation::Slot& ud = tr->uds[i]; + const View& view = views[ud.source >= ComputeTranslation::output_word3 ? inputs + ud.a : ud.a]; + std::uint32_t format = 0, word[4]; + switch (ud.source) { + case ComputeTranslation::root_constant: values[i] = pass.compute_constants.word(ud.a, ud.b); break; + case ComputeTranslation::input_stride: values[i] = view.stride; break; + case ComputeTranslation::input_word3: + std::memcpy(word, view.words, sizeof(word)); + if (formatted_buffer_word3(word, format)) { + reason = "a formatted input has no word 3 the program decodes"; + std::memcpy(words, view.words, sizeof(view.words)); + } + values[i] = word[3]; + break; + case ComputeTranslation::output_word3: values[i] = view.words[3]; break; + case ComputeTranslation::output_stride: values[i] = view.words[1] >> 16; break; // unmasked: the program checks the swizzle bits + case ComputeTranslation::output_records: values[i] = view.words[2]; break; + } + } + // A texture the title filled in memory is brought up to date first. An upload recorded before a later one + // fails only syncs content, as a draw sampling that texture would. + for (std::size_t i = 0; i < inputs && !reason; ++i) + if (views[i].texture && !upload_texture(self, views[i].wrapper, views[i].resource)) { + reason = "an input texture could not be uploaded"; + std::memset(words, 0, sizeof(words)); + } + if (reason) { + if (!tr->first_refusal) { + tr->first_refusal = reason; + std::memcpy(tr->refusal_words, words, sizeof(tr->refusal_words)); + } + ReleaseSRWLockExclusive(&draw_lock); + InterlockedIncrement(counter); + // Dispatches that arrive before the offline translation must not use up the lines for bind refusals. + static LONG untranslated, refusals; + if (!dispatch.signature && first_calls(counter == &compute_dispatches_refused ? refusals : untranslated, 16)) + log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + return reason; + } + const UINT n = static_cast<UINT>(count + tr->heap_srvs); + UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(n))) % draw_heap_size; + if (first + n > draw_heap_size) { + first = 0; + InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(n)); + } + D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + std::size_t{first} * draw_heap_increment}; + for (std::size_t i = 0; i < n; ++i, dest.ptr += draw_heap_increment) { + const View& view = views[i]; + if (i < inputs && view.texture) { + // A compute list accepts no pixel-shader or depth state in a transition. + require_state(self, view.resource, type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + : sampled_state(self, view.resource) | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + device_of(the_device)->CreateShaderResourceView(view.resource, + view.described ? &view.desc.srv : nullptr, dest); + continue; + } + if (i < inputs || i >= count) { + if (view.transition) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + buffer_view(dest, view.resource, view.offset, static_cast<std::size_t>(view.bytes)); + continue; + } + require_state(self, view.resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (view.texture || view.described) { + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, + view.described ? &view.desc.uav : nullptr, dest); + continue; + } + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + desc.Buffer.FirstElement = view.offset / 4; + desc.Buffer.NumElements = static_cast<UINT>(view.bytes / 4); + desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device_of(the_device)->CreateUnorderedAccessView(view.resource, nullptr, &desc, dest); + } + if (!pass.heap_set) { + x2w_startup::bind_translated_heaps(list, draw_heap, nullptr); + pass.heap_set = true; + pass.bound_sampler_heap = nullptr; + } + list->SetPipelineState(tr->pipeline.Get()); + list->SetComputeRootSignature(tr->root.Get()); + if (!tr->uds.empty()) list->SetComputeRoot32BitConstants(0, static_cast<UINT>(tr->uds.size()), values, 0); + if (n) list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + if (dispatch.signature) { + require_state(self, dispatch.argument, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list->ExecuteIndirect(dispatch.signature, 1, dispatch.argument, dispatch.offset, nullptr, 0); + } else { + list->Dispatch(x, y, z); + } + for (std::size_t i = inputs; i < count; ++i) { // a later dispatch on this list reads what this one wrote + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = views[i].resource; + list->ResourceBarrier(1, &barrier); + } + // The translated root replaced the desktop compute root of the title and its arguments. + if (pass.desktop_compute_root) { + list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) + if (const auto address = pass.desktop_compute_upload_srvs[parameter]) list->SetComputeRootShaderResourceView(parameter, address); + } + ++tr->translated; + ReleaseSRWLockExclusive(&draw_lock); + static LONG checks; // as translated draws do: the queue's execute drains the rest + if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated dispatch", dispatch.signature ? 61 : 14); + InterlockedIncrement(&compute_dispatches_translated); + static LONG logged; + if (!dispatch.signature && first_calls(logged, 8)) + log("x2w-draw compute %016llx Dispatch(%u, %u, %u) translated: entry [%x %x %x %x], %zu inputs, %zu outputs", key, x, y, z, + values[0], values[1], values[2], values[3], inputs, count - inputs); + return nullptr; +} + +// With the periodic totals: refused dispatches by the first refusal reason of their key, then every key by +// dispatch count. The per-call log lines above share one small budget, so they cannot rank keys. +void log_compute_census() +{ + struct Reason { const char* text; u64 keys, dispatches; }; + std::vector<Reason> reasons; + std::vector<ComputeTranslation> keys; + AcquireSRWLockShared(&draw_lock); + for (const auto& item : compute_translations()) { + const ComputeTranslation& tr = item.second; + ComputeTranslation copy; + copy.key = tr.key; + copy.dispatches = tr.dispatches; + copy.translated = tr.translated; + copy.first_refusal = tr.first_refusal; + std::memcpy(copy.refusal_words, tr.refusal_words, sizeof(copy.refusal_words)); + keys.push_back(copy); + if (!tr.first_refusal) continue; + auto found = std::find_if(reasons.begin(), reasons.end(), [&](const Reason& r) { return !std::strcmp(r.text, tr.first_refusal); }); + if (found == reasons.end()) found = reasons.insert(reasons.end(), Reason{tr.first_refusal, 0, 0}); + ++found->keys; + found->dispatches += tr.dispatches - tr.translated; + } + ReleaseSRWLockShared(&draw_lock); + if (keys.empty()) return; + std::sort(reasons.begin(), reasons.end(), [](const Reason& a, const Reason& b) { return a.dispatches > b.dispatches; }); + std::sort(keys.begin(), keys.end(), [](const ComputeTranslation& a, const ComputeTranslation& b) { return a.dispatches > b.dispatches; }); + log("x2w-render compute census: %zu keys dispatched", keys.size()); + for (const Reason& r : reasons) + log("x2w-render compute census reason \"%s\": %llu keys, %llu dispatches", r.text, r.keys, r.dispatches); + for (std::size_t i = 0; i < keys.size(); ++i) + log("x2w-render compute census key %016llx: %llu dispatches, %llu translated, first refusal: %s [%08x %08x %08x %08x]", + keys[i].key, keys[i].dispatches, keys[i].translated, keys[i].first_refusal ? keys[i].first_refusal : "none", + keys[i].refusal_words[0], keys[i].refusal_words[1], keys[i].refusal_words[2], keys[i].refusal_words[3]); +} + +// Fixtures: the census without waiting for the frame that logs it. +extern "C" __declspec(dllexport) void x2w_d3d12_compute_census() { log_compute_census(); } + +void scene_argument_probe(Wrapper* self, unsigned event, void* argument, u64 offset, const char* refused) { + static const bool enabled = GetEnvironmentVariableW(L"X2W_SCENE_ARGUMENT_PROBE",nullptr,0) != 0; + if (!enabled || !recording(self) || !draw_dump_frame() || frame_number != draw_dump_frame()) return; + auto& pass = pass_of(self); + if (!pass.pipeline) return; + const u64 key = pass.pipeline->own().compute_request_key; + static const u64 input_key = probe_key("X2W_ARGUMENT_INPUT_KEY"); + static const u64 output_key = probe_key("X2W_ARGUMENT_OUTPUT_KEY"); + static const u64 indirect_key = probe_key("X2W_ARGUMENT_INDIRECT_KEY"); + if (!key || (event == 17 && key != input_key) || (event == 22 && key != output_key) || + (event == 27 && key != indirect_key)) return; + static volatile LONG seen[28]{}; + LONG previous = seen[event]; + if (previous == frame_number || InterlockedCompareExchange(&seen[event],frame_number,previous)!=previous) return; + ID3D12Resource* resource{}; bool upload = false; + u64 entry = 0; UINT words[4]{}; UINT bytes = event == 17 ? 4 : 12; + if (event != 27) { + entry = pass.compute_tables.table(1).record(event == 17 ? 64 : 32,16); + if (!entry || !x2w_local::readable(reinterpret_cast<void*>(entry),16)) return; + std::memcpy(words,reinterpret_cast<void*>(entry),16); + if (event == 17) { + const char* why{}; + auto v = indirect_table_buffer(self,words,false,&why); + const u64 guest = words[0] | (u64{words[1]&0xffff}<<32); + UINT scalar = 0; SIZE_T got = 0; + if (words[0]!=view_token_magic) + ReadProcessMemory(GetCurrentProcess(),reinterpret_cast<void*>(guest+36),&scalar,4,&got); + log("x2w-argument-probe input frame=%ld guest=%llx cpuBytes=%zu cpu=%08x resolve=%s",frame_number,guest,got,scalar,why?why:"bound"); + if (v.bytes < 40) return; + resource=v.resource; offset=v.offset+36; upload=v.upload; + } else { + ComputeTokenOutput token{}; + const char* why = words[0]==view_token_magic ? compute_token_output(self,words,token) : "no token"; + log("x2w-argument-probe after frame=%ld token=%u owner=%llx dispatch=%s view=%s",frame_number,words[1],token.guest_resource,refused?refused:"recorded",why?why:"bound"); + if (token.view.Buffer.FirstElement != 0 || token.backing.Dimension!=D3D12_RESOURCE_DIMENSION_BUFFER) return; + auto* w=as_wrapper(reinterpret_cast<void*>(token.guest_resource)); + if (!w || w->own().kind != resource_kind) return; + resource=static_cast<ID3D12Resource*>(w->own().real); + } + } else { + auto* w=as_wrapper(argument); + if (!w || w->own().kind != resource_kind) return; + resource=static_cast<ID3D12Resource*>(w->own().real); + } + if (!resource || draw_dumps().full()) return; + auto desc=resource->GetDesc(); + if (desc.Dimension!=D3D12_RESOURCE_DIMENSION_BUFFER || offset>desc.Width || bytes>desc.Width-offset) return; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC rd{}; rd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER; rd.Width=bytes; rd.Height=1; rd.DepthOrArraySize=1; rd.MipLevels=1; rd.SampleDesc.Count=1; rd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + DrawDump dump{}; + if(FAILED(device_of(the_device)->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&rd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(dump.buffer.GetAddressOf())))) return; + auto* dst=dump.buffer.Get(); dump.frame=frame_number; dump.count=event; dump.key=key; + auto* list=recording(self); + if (!retain_with_recording(self,x2w_startup::ComPtr<ID3D12Resource>(resource)) || !draw_dumps().record(list,std::move(dump))) return; + auto state=D3D12_RESOURCE_STATE_COMMON; + for (auto& st:pass.states) if (st.first==resource) state=st.second; + if (!upload) require_state(self,resource,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(dst,0,resource,offset,bytes); + if (!upload) require_state(self,resource,state); + log("x2w-argument-probe copied frame=%ld event=%u owner=%p gpu=%llx offset=%llu bytes=%u",frame_number,event,argument,resource->GetGPUVirtualAddress(),offset,bytes); +} diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 16aa47bd07..1933d5f78e 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,14 +9,162 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. +#include "startup_stubs/typed_uav_load.h" + +// A pixel-stage image store (#1996 item F, #2742): tools/startup/gfx2hlsl.py writes 'uav N tex2d|tex2da table P O' +// for the RWTexture2D<float4> or RWTexture2DArray<float4> at u<N>, whose descriptor is at byte O of the title's +// root table P. The native compiler also emits raw table views; a view qualifier or a 'channels' field, as in the compute line, is refused. +// A trailing 'typedload' means the binding must also support a typed UAV load. The translator does not emit it +// for a component store, which does not read the texel. +struct PixelUav { + unsigned index = 0, parameter = 0, offset = 0; + bool array = false; + bool raw = false; + bool needs_typed_load = false; +}; +constexpr unsigned pixel_uav_limit = 8; + +// Returns nullptr and fills out, or the reason the line is refused. +const char* read_pixel_uav_line(const std::string& line, PixelUav& out) +{ + std::vector<std::string> w; + for (std::size_t at = line.find_first_not_of(' '); at != std::string::npos; at = line.find_first_not_of(' ', at)) { + const std::size_t end = line.find(' ', at); + w.push_back(line.substr(at, end == std::string::npos ? std::string::npos : end - at)); + at = end == std::string::npos ? line.size() : end; + } + const auto number = [](const std::string& text, unsigned& value) { + if (text.empty() || text.size() > 9 || text.find_first_not_of("0123456789") != std::string::npos) return false; + value = static_cast<unsigned>(std::strtoul(text.c_str(), nullptr, 10)); + return true; + }; + if (w.size() < 2 || w[0] != "uav" || !number(w[1], out.index)) return "malformed view index"; + if (w.size() < 3) return "missing view kind"; + if (w[2] == "table") return "legacy untyped buffer view is not bound"; + if (w[2] != "tex2d" && w[2] != "tex2da" && w[2] != "raw") return "only tex2d, tex2da and raw views are bound"; + out.array = w[2] == "tex2da"; + out.raw = w[2] == "raw"; + if (w.size() > 3 && (w[3] == "float" || w[3] == "uint" || w[3] == "sint")) return "a view qualifier is not read for pixel stores"; + if (w.size() < 4 || w[3] != "table") return "view source is not a table"; + if (w.size() < 6) return "missing table parameter or offset"; + if (w.size() > 7 || (w.size() == 7 && w[6] != "typedload")) return "unexpected field after the table offset"; + if (!number(w[4], out.parameter) || out.parameter >= 16) return "table parameter out of range"; + if (!number(w[5], out.offset)) return "malformed table offset"; + out.needs_typed_load = w.size() == 7; + if (out.raw && (out.needs_typed_load || out.offset % 32)) return "raw view requires an aligned table record without typedload"; + return nullptr; +} + +// Formats a RWTexture2D<float4> store converts to: float, UNORM and SNORM colour formats. +bool float_uav_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: + return true; + default: + return false; + } +} + +bool integer_uav_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SINT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SINT: + return true; + default: + return false; + } +} + +bool srgb_uav_format(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB || + format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; +} + +// The view of mip 0 of a 2D or 2D-array texture for a pixel UAV. resource is the desktop description, title_view +// the title's own view (nullptr when it passed none) with console format values already mapped, and array is true +// for a manifest 'tex2da' view. Returns nullptr and fills out, or the reason the binding is refused. +const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& resource, + const D3D12_UNORDERED_ACCESS_VIEW_DESC* title_view, bool array, + D3D12_UNORDERED_ACCESS_VIEW_DESC& out, bool needs_typed_load = false) +{ + if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return "resource is not a 2D texture"; + if (!array && resource.DepthOrArraySize != 1) return "resource is a texture array"; + if (resource.SampleDesc.Count != 1) return "resource is multisampled"; + if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "resource lacks ALLOW_UNORDERED_ACCESS"; + DXGI_FORMAT format = resource.Format; + if (array) { + if (!title_view || title_view->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY) + return "view is not a 2D array texture view"; + const auto& a = title_view->Texture2DArray; + if (a.MipSlice != 0) return "view names a mip other than 0"; + if (a.PlaneSlice != 0) return "view names a plane other than 0"; + if (a.FirstArraySlice >= resource.DepthOrArraySize || !a.ArraySize || + a.ArraySize > resource.DepthOrArraySize - a.FirstArraySlice) + return "array view slice range is outside the resource"; + if (title_view->Format != DXGI_FORMAT_UNKNOWN) format = title_view->Format; + } else if (title_view) { + if (title_view->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D) return "view is not a 2D texture view"; + if (title_view->Texture2D.MipSlice != 0) return "view names a mip other than 0"; + if (title_view->Texture2D.PlaneSlice != 0) return "view names a plane other than 0"; + if (title_view->Format != DXGI_FORMAT_UNKNOWN) format = title_view->Format; + } + if (integer_uav_format(format)) return "integer format for a float view"; + if (srgb_uav_format(format)) return "sRGB format"; + if (!float_uav_format(format)) return "format is not a float colour format"; + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) + return "format has no typed UAV store on this device"; + // Before the view is filled, and therefore before the draw. A component store does not set + // needs_typed_load: it never reads the texel. A binding that does is refused when this device + // cannot load the format. + if (needs_typed_load) { + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const bool additional = SUCCEEDED(device->CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) && + options.TypedUAVLoadAdditionalFormats; + if (const char* load = typed_uav_load_refusal(format, support.Support2, additional)) + return load; + } + out = {}; + out.Format = format; + if (array) { + out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + out.Texture2DArray = title_view->Texture2DArray; + } else { + out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + } + return nullptr; +} + struct Translation { - struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a + struct Srv { int kind, source, a, b; UINT expected_stride{}; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable - ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. +#ifdef X2W_NATIVE_SHADERS + bool native_graphics_attempted = false; +#endif + x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw. std::vector<Srv> srvs; + std::vector<PixelUav> uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector<Ud> uds; + std::vector<D3D12_INPUT_ELEMENT_DESC> fixed_stream; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) @@ -26,10 +174,13 @@ struct Translation { std::optional<bool> independent_indirect_entry; std::optional<bool> indexed_indirect_entry; bool indexed_rect_geometry_attempted = false; + std::string fixed_rectangle_ir; + bool fixed_rectangle_on_disk = false; x2w_startup::ComPtr<ID3DBlob> indexed_rect_geometry; int indirect_base_word = -1; x2w_startup::ComPtr<ID3D12CommandSignature> indexed_signature; std::unordered_map<u64, ID3D12PipelineState*> pipelines; // by target formats + std::vector<x2w_startup::PsoRecipe> pso_recipes; // opt-in X2W_PSO_RECIPE_DIR records for this key u64 key = 0; LONG logged_draws = 0, logged_bindings = 0, logged_large = 0; // diagnostics budget per translation }; @@ -49,6 +200,7 @@ struct BoundPipeline { D3D12_RASTERIZER_DESC rasterizer{}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; std::unordered_map<u64, ID3D12PipelineState*> pipelines; // by target formats + std::unordered_set<u64> pso_recipe_targets_tried; // target/dsv signatures already replayed }; // Looks for a desktop-layout D3D12_BLEND_DESC inside a state block: two flags, then eight render @@ -81,6 +233,7 @@ std::unordered_map<u64, Translation*>& translation_by_key() { static std::unorde LONG translated_draws, untranslated_draws, translation_ready, translation_missing, null_bindings; LONG formatted_draws_refused; // draws whose formatted buffer load had no resolved descriptor word 3 (also untranslated) LONG null_by_cause[x2w_local::null_cause_count]; // null_bindings split by cause; the parts add up to it +LONG pso_recipes_loaded, pso_recipes_precreated, pso_recipe_mismatches, pso_recipe_fallbacks; void count_null_binding(x2w_local::NullCause cause) { @@ -116,10 +269,161 @@ bool read_text(const wchar_t* path, std::string& out) return true; } +bool pso_recipe_path(wchar_t* out, u64 translation_key) +{ + wchar_t dir[MAX_PATH]; + const DWORD saved = GetLastError(); + const DWORD length = GetEnvironmentVariableW(L"X2W_PSO_RECIPE_DIR", dir, MAX_PATH); + SetLastError(saved); + if (!length || length >= MAX_PATH) return false; + const wchar_t separator = dir[length - 1] == L'\\' || dir[length - 1] == L'/' ? L'\0' : L'\\'; + const int written = separator + ? swprintf(out, MAX_PATH, L"%s\\pso_%016llx.txt", dir, static_cast<unsigned long long>(translation_key)) + : swprintf(out, MAX_PATH, L"%spso_%016llx.txt", dir, static_cast<unsigned long long>(translation_key)); + return written > 0 && written < MAX_PATH; +} + +bool read_pso_recipe_text(const wchar_t* path, std::string& out, bool& too_large) +{ + too_large = false; + // Deny writers for the whole read: a concurrent append holds the file exclusively, and this + // reader either sees the previous complete file or no file at all. + HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}; + if (!GetFileSizeEx(file, &size) || size.QuadPart < 0 || size.QuadPart > static_cast<LONGLONG>(x2w_startup::pso_recipe_file_limit)) { + too_large = true; + CloseHandle(file); + return false; + } + out.resize(static_cast<std::size_t>(size.QuadPart)); + std::size_t done = 0; + while (done < out.size()) { + DWORD got = 0; + const DWORD wanted = static_cast<DWORD>(std::min<std::size_t>(out.size() - done, 1u << 20)); + if (!ReadFile(file, out.data() + done, wanted, &got, nullptr) || !got) break; + done += got; + } + CloseHandle(file); + if (done != out.size()) out.clear(); + return done == size.QuadPart; +} + +// Called once a translation is ready. A missing directory or file is not an error; the runtime then +// follows the unchanged creation path. +void load_pso_recipes(Translation& tr) +{ + wchar_t path[MAX_PATH]; + if (!pso_recipe_path(path, tr.key)) return; + std::string text; + bool too_large = false; + if (!read_pso_recipe_text(path, text, too_large)) { + if (too_large) { + InterlockedIncrement(&pso_recipe_mismatches); + static LONG logged; + if (first_calls(logged, 16)) log("x2w-draw pso recipe file for %016llx is above the size limit; ignored", tr.key); + } + return; + } + auto parsed = x2w_startup::parse_pso_recipe_file(text); + unsigned rejected = parsed.rejected; + parsed.recipes.erase(std::remove_if(parsed.recipes.begin(), parsed.recipes.end(), [&](const x2w_startup::PsoRecipe& recipe) { + if (recipe.translation_key == tr.key) return false; + ++rejected; + return true; + }), parsed.recipes.end()); + if (rejected) InterlockedAdd(&pso_recipe_mismatches, static_cast<LONG>(rejected)); + if (!parsed.recipes.empty()) { + const std::size_t count = parsed.recipes.size(); + InterlockedAdd(&pso_recipes_loaded, static_cast<LONG>(std::min<std::size_t>(count, LONG_MAX))); + tr.pso_recipes = std::move(parsed.recipes); + } + if (rejected || !tr.pso_recipes.empty()) { + log("x2w-draw pso recipes %016llx: %zu loaded, %u rejected%s%s", tr.key, tr.pso_recipes.size(), rejected, + parsed.error.empty() ? "" : "; first error: ", parsed.error.c_str()); + } +} + +bool append_pso_recipe(const wchar_t* path, const x2w_startup::PsoRecipe& recipe) +{ + const std::string record = x2w_startup::serialize_pso_recipe(recipe); + if (record.size() > x2w_startup::pso_recipe_file_limit) return false; + // One writer owns the file for the whole count/size check and append. A second process that + // reaches this path at the same time fails to open it and keeps the PSO it already created; + // that draw simply does not add a record. Readers also deny writers, so neither side observes + // a half-written record. + HANDLE file = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}; + bool ok = GetFileSizeEx(file, &size) && size.QuadPart >= 0 && + static_cast<std::uint64_t>(size.QuadPart) <= x2w_startup::pso_recipe_file_limit; + std::string existing; + if (ok) { + existing.resize(static_cast<std::size_t>(size.QuadPart)); + LARGE_INTEGER begin{}; + ok = SetFilePointerEx(file, begin, nullptr, FILE_BEGIN) != 0; + std::size_t read = 0; + while (ok && read < existing.size()) { + DWORD got = 0; + const DWORD wanted = static_cast<DWORD>(std::min<std::size_t>(existing.size() - read, 1u << 20)); + ok = ReadFile(file, existing.data() + read, wanted, &got, nullptr) != 0 && got != 0; + read += got; + } + ok = ok && read == existing.size(); + } + ok = ok && x2w_startup::pso_recipe_append_allowed(existing, record); + LARGE_INTEGER at{}; + at.QuadPart = size.QuadPart; + if (ok) ok = SetFilePointerEx(file, at, nullptr, FILE_BEGIN) != 0; + std::size_t done = 0; + while (ok && done < record.size()) { + DWORD written = 0; + const DWORD wanted = static_cast<DWORD>(std::min<std::size_t>(record.size() - done, 1u << 20)); + ok = WriteFile(file, record.data() + done, wanted, &written, nullptr) != 0 && written == wanted; + done += written; + } + CloseHandle(file); + return ok && done == record.size(); +} + +// The revisions every request key starts with. tools/startup/gfx2hlsl.py hashes the same bytes, without a +// trailing NUL (pipeline_key, compute_key, mesh57_key); a change of either side makes every cached request a miss. +namespace shader_cache { +constexpr char revision[] = "x2w-startup-shader-29"; +constexpr char compute_revision[] = "x2w-startup-shader-29cs"; // tools/startup/gfx2hlsl.py compute_key +constexpr char mesh57_revision[] = "x2w-startup-mesh-57-3"; +} // namespace shader_cache + +// Once per process, before its first request: <X2W_SHADER_CACHE>\revision.txt names this runtime's revisions, so +// that the launchers (tools/startup/shader_cache_revision.py) can warn before they start a translator of another +// revision. A file that already says the same is left as it is. +void write_cache_revision() +{ + static LONG written; + if (InterlockedCompareExchange(&written, 1, 0)) return; + wchar_t dir[MAX_PATH], path[MAX_PATH], temporary[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!n || n >= MAX_PATH) return; + swprintf(path, MAX_PATH, L"%s\\revision.txt", dir); + swprintf(temporary, MAX_PATH, L"%s\\revision.txt.%lu.tmp", dir, GetCurrentProcessId()); + const std::string text = std::string("graphics ") + shader_cache::revision + "\ncompute " + shader_cache::compute_revision + + "\nmesh57 " + shader_cache::mesh57_revision + "\n"; + std::string old; + if (read_text(path, old) && old == text) return; + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return; + DWORD done = 0; + const bool complete = WriteFile(file, text.data(), static_cast<DWORD>(text.size()), &done, nullptr) && done == text.size(); + CloseHandle(file); + if (!complete || !MoveFileExW(temporary, path, MOVEFILE_REPLACE_EXISTING)) DeleteFileW(temporary); +} + // Publish each input atomically. The callers write the request's ready marker last. bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std::size_t bytes) { wchar_t path[MAX_PATH], temporary[MAX_PATH], suffix[32]; + write_cache_revision(); if (!cache_path(path, L"req_", key, ext)) return false; if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; swprintf(suffix, std::size(suffix), L"%s.%lu.tmp", ext, GetCurrentProcessId()); @@ -134,26 +438,40 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } -void load_translation(Translation& tr, const std::string& rtv_request = {}) +bool native_shaders_only() +{ + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("X2W_NATIVE_SHADERS_ONLY", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + return enabled; +} + +void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {}) { tr.state = 2; + if (manifest.empty() && native_shaders_only()) { + tr.manifest_retry.found(); + return; + } wchar_t path[MAX_PATH]; - std::string manifest; + const bool provided = !manifest.empty(); if (!cache_path(path, L"", tr.key, L".txt")) return; - if (!read_text(path, manifest)) { - if (!tr.retry_manifest_at) { + if (!provided && !read_text(path, manifest)) { + if (!tr.manifest_retry.pending()) { InterlockedIncrement(&translation_missing); static LONG missing; if (rtv_request.empty() && first_calls(missing, 12)) log("x2w-draw no translation for pipeline %016llx", tr.key); } - tr.retry_manifest_at = GetTickCount64() + 1000; + tr.manifest_retry.missed(GetTickCount64()); return; } // The writer publishes this marker last. A malformed published result stays rejected. - const bool previously_missing = tr.retry_manifest_at != 0; - tr.retry_manifest_at = 0; + const bool previously_missing = tr.manifest_retry.pending(); + tr.manifest_retry.found(); bool matched_rtv = false; + bool fixed_manifest = false; for (std::size_t at = 0; at < manifest.size();) { std::size_t end = manifest.find('\n', at); if (end == std::string::npos) end = manifest.size(); @@ -168,14 +486,28 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } matched_rtv = true; - } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1") { - // Version 2 adds `uav` lines for vertex-stage stores. This runtime does not bind them, - // so it must not draw a translation whose stores it would silently skip (#1723). + } else if (line == "x2w-manifest 3") { + fixed_manifest = true; + } else if (line == "fixedrectgs") { + if (!fixed_manifest) return; + tr.fixed_rectangle_on_disk = true; + } else if (line.compare(0, 8, "fixedvb ") == 0) { + unsigned offset, format; + char extra; + if (!fixed_manifest || std::sscanf(line.c_str(), "fixedvb %u %u %c", &offset, &format, &extra) != 2 || + offset >= 2048 || tr.fixed_stream.size() >= 32 || + (format != DXGI_FORMAT_R8_UNORM && format != DXGI_FORMAT_R8G8_UNORM && format != DXGI_FORMAT_R8G8B8A8_UNORM && + format != DXGI_FORMAT_R32G32_UINT && format != DXGI_FORMAT_R32G32B32_UINT && + format != DXGI_FORMAT_R32G32B32A32_UINT && format != DXGI_FORMAT_R8_UINT) || + std::any_of(tr.fixed_stream.begin(), tr.fixed_stream.end(), [offset](const auto& e){return e.SemanticIndex == offset;})) + return; + tr.fixed_stream.push_back({"X2W_RAW_VERTEX", offset, static_cast<DXGI_FORMAT>(format), 0, offset, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}); + } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1" && line != "x2w-manifest 2") { + // Version 2 adds `uav` lines. Each one is bound (a pixel-stage tex2d store) or refused by name below, + // so a translation whose stores would be silently skipped is never drawn (#1723). log("x2w-draw unsupported manifest version for %016llx", tr.key); return; - } else if (line.compare(0, 4, "uav ") == 0) { - log("x2w-draw unsupported uav line for %016llx", tr.key); - return; } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { Translation::Ud ud{-1, x, y}; if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; @@ -189,8 +521,15 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) if (static_cast<std::size_t>(i) == tr.uds.size() && ud.kind >= 0) tr.uds.push_back(ud); } else if (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { const int texture_kind = !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : - !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : 0; + !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : + !std::strcmp(kind, "texcube") ? 5 : 0; Translation::Srv srv{texture_kind, !std::strcmp(source, "vb") ? 1 : !std::strcmp(source, "root") ? 2 : 0, x, y}; + if (!std::strcmp(kind, "idxbuf")) { + char tail; + if (std::sscanf(line.c_str(), "srv %d idxbuf table %d %d %u %c", &i, &x, &y, + &srv.expected_stride, &tail) != 4 || x < 0 || x >= 16 || y < 0 || y % 32 || + !srv.expected_stride || srv.expected_stride % 4 || srv.expected_stride > 2048) return; + } if (static_cast<std::size_t>(i) == tr.srvs.size()) tr.srvs.push_back(srv); } else if (line.compare(0, 6, "wmask ") == 0) { if (!tr.write_masks.read_manifest_line(line)) { @@ -203,16 +542,23 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } } else if (line.compare(0, 4, "uav ") == 0) { - // tools/startup/gfx2hlsl.py lowers a pixel-stage image_store to a u-register store, but the - // translated root signature has no UAV range and no view is made from the title's descriptor yet. - log("x2w-draw pipeline %016llx stores to an image (%s); pixel-stage UAVs are not bound yet, translation not used", - tr.key, line.c_str()); - return; + // A pixel-stage image_store: the view is made at draw time from the title's unordered-access view at + // that table entry (resolve_pixel_uavs). + PixelUav uav; + const char* refusal = read_pixel_uav_line(line, uav); + if (!refusal && uav.index != tr.uavs.size()) refusal = "view index out of order"; + if (!refusal && tr.uavs.size() >= pixel_uav_limit) refusal = "too many views"; + if (refusal) { + log("x2w-draw pipeline %016llx uav line refused (%s): %s; translation not used", tr.key, refusal, line.c_str()); + return; + } + tr.uavs.push_back(uav); } else if (!tr.samplers.read_manifest_line(line.c_str())) { log("x2w-draw invalid sampler heap manifest for %016llx", tr.key); return; } } + if (fixed_manifest != !tr.fixed_stream.empty()) return; if (matched_rtv != !rtv_request.empty()) { log("x2w-draw RTV manifest missing for %016llx", tr.key); return; @@ -223,32 +569,90 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) (ud.a < 0 || static_cast<std::size_t>(ud.a) >= tr.srvs.size() || !tr.d16_srvs.requires_exact(static_cast<unsigned>(ud.a)))) return; } - if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; - if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; - const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.size()), - static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root); + if (!provided && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs)))) return; + if (!provided && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return; + const HRESULT hr = provided && x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE") ? E_FAIL : + x2w_startup::create_translated_root(device_of(the_device), static_cast<UINT>(tr.uds.size()), + static_cast<UINT>(tr.srvs.size()), tr.samplers, &tr.root, static_cast<UINT>(tr.uavs.size()), fixed_manifest); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast<unsigned long>(hr)); return; } tr.state = 1; + load_pso_recipes(tr); if (previously_missing) InterlockedDecrement(&translation_missing); InterlockedIncrement(&translation_ready); - log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu static samplers, sampler_heap=%u", - tr.key, tr.uds.size(), tr.srvs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); + log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu writable views, %zu static samplers, sampler_heap=%u", + tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); +} + +#ifdef X2W_NATIVE_SHADERS +static bool try_native_graphics(Translation& tr, bool variant = false) +{ + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, variant ? L".rtv" : L".a")) return false; + try { + const auto request = x2w::read_graphics_request(path); + const auto cache = std::filesystem::path(path).parent_path(); + bool frontend_hit = false; + const auto pair = x2w::prepare_direct_graphics(request.a, request.b, cache, frontend_hit, + request.root, request.input_layout, request.pixel_entry, true, request.rtv_formats); + auto manifest = x2w::format_graphics_runtime_manifest(pair, request.rtv_request); + if (!manifest) throw std::runtime_error("unsupported graphics binding layout"); + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + auto stage = [&](const std::string& ir, const wchar_t* profile, bool& hit) { + const auto output = compiler.compile(ir, profile, cache, x2w::ShaderSourceFormat::dxil_ir); + hit = output.cache_hit; + x2w_startup::ComPtr<ID3DBlob> blob; + if (FAILED(D3DCreateBlob(output.dxil.size(), &blob))) throw std::bad_alloc(); + std::memcpy(blob->GetBufferPointer(), output.dxil.data(), output.dxil.size()); + return blob; + }; + bool vs_hit, ps_hit; + auto vs = stage(pair.vertex.dxil_ir, L"vs_6_6", vs_hit); + auto ps = stage(pair.pixel.dxil_ir, L"ps_6_6", ps_hit); + Translation candidate; + candidate.key = tr.key; + candidate.manifest_retry = tr.manifest_retry; + candidate.native_graphics_attempted = true; + if (!pair.input_layout.empty()) { + try { candidate.fixed_rectangle_ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } + catch (const x2w::UnsupportedComputeShader&) {} // Triangle lists and strips still use the original pair. + } + candidate.vs = vs.Get(); + candidate.ps = ps.Get(); + if (x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_MANIFEST_FAILURE")) + manifest->append("\nx2w-manifest 999\n"); + load_translation(candidate, request.rtv_request, std::move(*manifest)); + if (candidate.state != 1) { + if (candidate.root) candidate.root->Release(); + throw std::runtime_error("native graphics manifest or root signature refused"); + } + candidate.vs = vs.Detach(); + candidate.ps = ps.Detach(); + tr = std::move(candidate); + log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u", + tr.key, tr.state == 1, frontend_hit, vs_hit, ps_hit); + return true; + } catch (const std::exception& error) { + log("x2w-draw native graphics %016llx refused: %s", tr.key, error.what()); + return false; + } } +#endif // draw_lock held. Both pipeline forms use the same request writer and shader cache. Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, - const std::vector<unsigned char>& root_blob, const std::string& layout = {}) + const std::vector<unsigned char>& root_blob, const std::string& layout = {}, + const std::string& slot57_entry = {}) { - // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. - // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-17"; - const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); + // Keep pre-fix desktop bytecode and manifests out of this ABI's cache (shader_cache::revision). + const u64 seed = fnv_bytes(shader_cache::revision, sizeof(shader_cache::revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key); + if (!slot57_entry.empty()) key = fnv_bytes(slot57_entry.data(), slot57_entry.size(), key); auto& entry = translation_by_key()[key]; if (!entry) { entry = new Translation; @@ -256,7 +660,8 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* // A legacy cache hit still needs source blobs for late RTV specialization. if (publish_shader_request(key, L".b", b, b_bytes) && publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size()))) + (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size())) && + (slot57_entry.empty() || publish_shader_request(key, L".ps57in", slot57_entry.data(), slot57_entry.size()))) publish_shader_request(key, L".a", a, a_bytes); load_translation(*entry); } @@ -286,12 +691,7 @@ u64 fnv_part(const std::vector<unsigned char>& part, u64 key) // so a title write in between cannot leave a file that does not match its key. bool copy_title_bytes(void* to, const void* from, std::size_t bytes) noexcept { - __try { - std::memcpy(to, from, bytes); - } __except (EXCEPTION_EXECUTE_HANDLER) { - return false; - } - return true; + return x2w_local::guarded_memcpy(to, from, bytes, true); } // Aligned qwords of a published blob that name committed memory of this process (one VirtualQuery each, so @@ -313,11 +713,46 @@ LONG pointer_like_qwords(const std::vector<unsigned char>& blob) SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set<u64>& compute_keys_seen() { static std::unordered_set<u64> s; return s; } +#ifdef X2W_NATIVE_SHADERS +LONG compute_pack_prepared, compute_pack_refused, compute_pack_misses; +const x2w::ComputeFrontendPack* runtime_compute_pack() { + static const auto pack = []() -> std::optional<x2w::ComputeFrontendPack> { + wchar_t path[32768]; + const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_COMPUTE_PACK", path, 32768); + if (!length || length >= 32768) return {}; + try { + auto loaded = x2w::ComputeFrontendPack::load(path, 0); + log("x2w-draw loaded %zu compute frontend pack records", loaded.size()); + return loaded; + } catch (const std::exception& error) { + log("x2w-draw compute frontend pack unavailable: %s", error.what()); + return {}; + } + }(); + return pack ? &*pack : nullptr; +} +x2w::FrozenComputeRequests& frozen_compute_requests() { + static x2w::FrozenComputeRequests requests([]() -> size_t { + char setting[16]{}; + auto n = GetEnvironmentVariableA("X2W_NATIVE_COMPUTE_REQUEST_CACHE_MIB", setting, sizeof(setting)); + if (!n || n >= sizeof(setting)) return 32u << 20; + unsigned mib = 0; + for (unsigned i = 0; i < n; ++i) { + if (setting[i] < '0' || setting[i] > '9') return 32u << 20; + mib = mib * 10 + unsigned(setting[i] - '0'); + if (mib > 256) return 32u << 20; + } + return size_t(mib) << 20; + }()); + return requests; +} +#endif -void publish_compute_request(const void* desc) +// Returns the request key, or 0 when publishing is disabled or the description is refused. +u64 publish_compute_request(const void* desc) { wchar_t marker[MAX_PATH]; - if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return; // publishing disabled + if (!render_mode() || !cache_path(marker, L"req_", 0, L".c67")) return 0; // publishing disabled static LONG logged; const char* refusal = nullptr; u64 words[12]{}; @@ -356,7 +791,7 @@ void publish_compute_request(const void* desc) if (refusal) { InterlockedIncrement(&compute_requests_failed); if (first_calls(logged, 12)) log("x2w-draw compute request not written: %s", refusal); - return; + return 0; } const auto& [code, data, state_a, state_b] = copies; // Pointer words never reach .desc or the key; 9 and 10 are not followed (shortcut: two descriptions that @@ -364,8 +799,7 @@ void publish_compute_request(const void* desc) std::vector<unsigned char> fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-17cs"; // tools/startup/gfx2hlsl.py compute_key - u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); + u64 key = fnv_bytes(shader_cache::compute_revision, sizeof(shader_cache::compute_revision) - 1); const std::vector<unsigned char>* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); // A dedicated lock and an in-memory set: a key seen in this process costs no file access, and draws @@ -375,7 +809,8 @@ void publish_compute_request(const void* desc) return publish_shader_request(key, ext, part.empty() ? &none : part.data(), part.size()); }; AcquireSRWLockExclusive(&compute_request_lock); - bool present = compute_keys_seen().count(key) != 0; + const bool already_seen = compute_keys_seen().count(key) != 0; + bool present = already_seen; bool written = present; if (!present) { present = cache_path(marker, L"req_", key, L".c67") && GetFileAttributesW(marker) != INVALID_FILE_ATTRIBUTES; @@ -385,6 +820,22 @@ void publish_compute_request(const void* desc) if (written) compute_keys_seen().insert(key); } ReleaseSRWLockExclusive(&compute_request_lock); +#ifdef X2W_NATIVE_SHADERS + if (written && !already_seen && GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0)) { + runtime_compute_pack(); // Read once at pipeline creation, outside the render lock. + try { + if (frozen_compute_requests().enabled()) { + auto bytes = [](const std::vector<unsigned char>& part) { + return part.empty() ? std::string{} : std::string(reinterpret_cast<const char*>(part.data()), part.size()); + }; + frozen_compute_requests().put({bytes(code), bytes(data), bytes(root_blob), bytes(fields), + bytes(state_a), bytes(state_b), key}); + } + } catch (const std::bad_alloc&) { + // The ready marker and all immutable parts remain available on disk. + } + } +#endif const LONG pointers = written && !present ? pointer_like_qwords(data) + pointer_like_qwords(state_a) + pointer_like_qwords(state_b) : 0; if (pointers) InterlockedAdd(&compute_blob_pointer_words, pointers); InterlockedIncrement(present ? &compute_requests_present : written ? &compute_requests_published : &compute_requests_failed); @@ -392,6 +843,7 @@ void publish_compute_request(const void* desc) log("x2w-draw compute request %016llx %s (code %llu bytes, data %llu bytes, state blocks %llu + %llu bytes, " "pointer-like blob qwords %ld)", key, present ? "already present" : written ? "published" : "not written", words[6], words[8], words[2], words[4], pointers); + return key; } // Slot 57 fixed descriptors consumed by a decoded DispatchMesh signature. @@ -417,31 +869,41 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector<RootParameter>* bo ReleaseSRWLockShared(¬e_lock); } if (root_blob.empty()) return; - std::vector<unsigned char> mesh, pixel; - const auto copy_stage = [&words](int field, bool required, std::vector<unsigned char>& out) { - const auto* pointer = reinterpret_cast<const void*>(words[field]); - const auto bytes = words[field + 1]; - if (!bytes) return !required && !pointer; - if (bytes > (1u << 20) || !x2w_local::readable(pointer, bytes)) return false; - out.resize(static_cast<std::size_t>(bytes)); - return copy_title_bytes(out.data(), pointer, out.size()); - }; - if (!copy_stage(13, true, mesh) || !copy_stage(5, false, pixel)) return; - constexpr char revision[] = "x2w-startup-mesh-57-2"; - const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(revision, sizeof(revision) - 1)))); static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set<u64> written; x2w_startup::ExclusiveNoteLock guard(request_lock); - if (written.count(key)) return; + if (!info->fixed_ms) return; + const auto& mesh = *info->fixed_ms; + const std::vector<unsigned char> empty; + const auto& pixel = info->fixed_ps ? *info->fixed_ps : empty; + const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(shader_cache::mesh57_revision, + sizeof(shader_cache::mesh57_revision) - 1)))); + if (x2w_local::env_on("X2W_MESH57_CAPTURE_STATE") && + words[2] == info->state_a.size() && words[4] == info->state_b.size()) { + // Payload: request key, three uint32 lengths, normalized descriptor, state A, state B. + const auto desc = x2w_startup::normalize_mesh57_descriptor(info->desc); + const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(desc, key))); + std::vector<unsigned char> packed(sizeof(key) + 3 * sizeof(UINT)); + const UINT lengths[]{static_cast<UINT>(desc.size()), static_cast<UINT>(info->state_a.size()), + static_cast<UINT>(info->state_b.size())}; + std::memcpy(packed.data(), &key, sizeof(key)); + std::memcpy(packed.data() + sizeof(key), lengths, sizeof(lengths)); + for (const auto* bytes : {&desc, &info->state_a, &info->state_b}) + packed.insert(packed.end(), bytes->begin(), bytes->end()); + if (!publish_shader_request(variant, L".s57", packed.data(), packed.size())) + log("x2w-draw fixed mesh state %016llx could not be published", variant); + } const unsigned char none = 0; - if (publish_shader_request(key, L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()) && + if (written.count(key) || (publish_shader_request(key, L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()) && publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - publish_shader_request(key, L".m57", mesh.data(), mesh.size())) { - written.insert(key); + publish_shader_request(key, L".m57", mesh.data(), mesh.size()))) { + const bool first = written.insert(key).second; static LONG logged; - if (first_calls(logged, 12)) + if (first && first_calls(logged, 12)) log("x2w-draw mesh request %016llx: slot57, MS %zu bytes, PS %zu bytes", key, mesh.size(), pixel.size()); + info->fixed_ms.reset(); + info->fixed_ps.reset(); } } @@ -451,7 +913,13 @@ bool stream_input_layout(const unsigned char* subobject, std::string& text) { D3D12_INPUT_LAYOUT_DESC layout; std::memcpy(&layout, subobject + 8, sizeof(layout)); - if (!layout.NumElements) return true; + if (!layout.NumElements) { + // Declared without elements. The value of a fetched input here is unverified, so the zero-fill translation + // is an experimental opt-in (X2W_STREAM_ZERO_FILL=1); by default nothing is published and the fetch is refused. + const char* zero_fill = std::getenv("X2W_STREAM_ZERO_FILL"); + if (zero_fill && zero_fill[0] == '1') text = "ia1 0\n"; + return true; + } if (layout.NumElements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT || !x2w_local::readable(layout.pInputElementDescs, sizeof(D3D12_INPUT_ELEMENT_DESC) * layout.NumElements)) return false; text = "ia1 " + std::to_string(layout.NumElements) + "\n"; @@ -691,7 +1159,18 @@ BoundPipeline* translation_for(Wrapper* pipeline) const std::size_t a_bytes = static_cast<std::size_t>(words[6]), b_bytes = static_cast<std::size_t>(words[10]); if (!root_blob.empty() && a_bytes && b_bytes && a_bytes <= (1u << 20) && b_bytes <= (1u << 20) && x2w_local::readable(a, a_bytes) && x2w_local::readable(b, b_bytes)) { - result = cached_translation(a, a_bytes, b, b_bytes, root_blob); + std::string slot57_entry; +#ifdef X2W_NATIVE_SHADERS + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) && + info->state_a.size() >= 0x60 && a_bytes >= 4 && b_bytes >= 4 && + std::memcmp(a, "DXBC", 4) && std::memcmp(b, "DXBC", 4)) { + // The fixed graphics state has SPI_PS_INPUT_ADDR and SPI_PS_IN_CONTROL + // in adjacent dwords. Capture both intact, including control flags. + slot57_entry = "PSI1"; + slot57_entry.append(reinterpret_cast<const char*>(info->state_a.data() + 0x58), 8); + } +#endif + result = cached_translation(a, a_bytes, b, b_bytes, root_blob, {}, slot57_entry); } } by_pipeline[pipeline] = bound; @@ -761,8 +1240,14 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) { if (!base) return nullptr; if (std::none_of(pass.target_formats, pass.target_formats + pass.target_count, needs_rtv_variant)) { - if (base->retry_manifest_at && GetTickCount64() >= base->retry_manifest_at) + if (base->manifest_retry.due(GetTickCount64())) load_translation(*base); +#ifdef X2W_NATIVE_SHADERS + if ((base->manifest_retry.pending() || native_shaders_only()) && !base->native_graphics_attempted) { + base->native_graphics_attempted = true; + try_native_graphics(*base); + } +#endif return base; } std::string request = "rtv1 " + std::to_string(base->key); @@ -775,10 +1260,14 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) entry->key = key; load_translation(*entry, request); if (entry->state != 1) { - publish_shader_request(key, L".rtv", request.data(), request.size()); + const bool published = publish_shader_request(key, L".rtv", request.data(), request.size()); +#ifdef X2W_NATIVE_SHADERS + if (published && (entry->manifest_retry.pending() || native_shaders_only()) && + try_native_graphics(*entry, true)) return entry; +#endif log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); } - } else if (entry->retry_manifest_at && GetTickCount64() >= entry->retry_manifest_at) { + } else if (entry->manifest_retry.due(GetTickCount64())) { load_translation(*entry, request); } return entry; @@ -790,57 +1279,212 @@ inline DXGI_FORMAT pass_dsv_format(const BoundPipeline& bound, const Pass& pass) return pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; } +// Called under draw_lock. The fallback uses only the bound attachments and +// never binds a descriptor heap or reads a guest buffer. +bool draw_missing_translation(ID3D12Device* device, ID3D12GraphicsCommandList* list, const Pass& pass, + UINT count, UINT instances, UINT start, UINT start_instance) +{ + static const bool enabled = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"X2W_DRAW_MISSING_SHADER", value, 2) == 1 && value[0] == L'1'; + }(); + if (!enabled || list->GetType() != D3D12_COMMAND_LIST_TYPE_DIRECT || + pass.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST || !pass.targets_single_sample || + !pass.viewport_set || !pass.scissor_set) return false; + + struct Pipeline { + x2w_startup::ComPtr<ID3D12RootSignature> root; + x2w_startup::ComPtr<ID3D12PipelineState> state; + }; + static std::unordered_map<u64, Pipeline> pipelines; + u64 key = fnv_bytes(&device, sizeof(device)); + key = fnv_bytes(&pass.graphics_root, sizeof(pass.graphics_root), key); + key = fnv_bytes(&pass.dsv_format, sizeof(pass.dsv_format), key); + key = fnv_bytes(pass.target_formats, pass.target_count * sizeof(DXGI_FORMAT), key); + auto [entry, inserted] = pipelines.try_emplace(key); + auto& pipeline = entry->second; + if (inserted) { + pipeline.root = pass.graphics_root; + HRESULT hr = S_OK; + if (!pipeline.root) { + const D3D12_ROOT_SIGNATURE_DESC empty{}; + x2w_startup::ComPtr<ID3DBlob> signature; + hr = D3D12SerializeRootSignature(&empty, D3D_ROOT_SIGNATURE_VERSION_1, &signature, nullptr); + if (SUCCEEDED(hr)) + hr = device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), + IID_PPV_ARGS(&pipeline.root)); + } + constexpr char source[] = + "float4 vertex() : SV_Position { return float4(2, 0, 0, 1); }\n" + "void pixel() { clip(-1); }\n"; + x2w_startup::ComPtr<ID3DBlob> vs, ps; + if (SUCCEEDED(hr)) + hr = D3DCompile(source, sizeof(source) - 1, nullptr, nullptr, nullptr, "vertex", "vs_5_0", 0, 0, &vs, nullptr); + if (SUCCEEDED(hr)) + hr = D3DCompile(source, sizeof(source) - 1, nullptr, nullptr, nullptr, "pixel", "ps_5_0", 0, 0, &ps, nullptr); + if (SUCCEEDED(hr)) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = pipeline.root.Get(); + desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + desc.SampleMask = ~0u; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = pass.target_count; + std::copy_n(pass.target_formats, pass.target_count, desc.RTVFormats); + desc.DSVFormat = pass.dsv_format; + desc.SampleDesc.Count = 1; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline.state)); + } + if (FAILED(hr)) + log("x2w-draw missing shader fallback setup failed 0x%08lx", static_cast<unsigned long>(hr)); + } + if (!pipeline.state) return false; + list->SetPipelineState(pipeline.state.Get()); + list->SetGraphicsRootSignature(pipeline.root.Get()); + list->DrawInstanced(count, instances, start, start_instance); + return true; +} + +bool effective_blend_state(const BoundPipeline& bound, const Translation& tr, UINT target_count, D3D12_BLEND_DESC& blend) +{ + blend = x2w_startup::default_pso_blend(); + if (bound.has_blend) blend = bound.blend; + return x2w_startup::apply_export_write_masks(blend, tr.write_masks, target_count); +} + +bool prepare_translated_pso_desc(Translation& tr, bool indexed_rect, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) +{ + desc.pRootSignature = tr.root; + desc.InputLayout = {tr.fixed_stream.data(), static_cast<UINT>(tr.fixed_stream.size())}; + desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; + desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; + if (!indexed_rect) return true; + if (!tr.indexed_rect_geometry_attempted) { + tr.indexed_rect_geometry_attempted = true; + x2w_startup::ComPtr<ID3DBlob> errors; + HRESULT hr = E_NOTIMPL; + if (tr.fixed_stream.empty()) + hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors); + else if (tr.fixed_rectangle_on_disk) { + wchar_t path[MAX_PATH]; + if (cache_path(path, L"", tr.key, L".gs.cso")) + hr = D3DReadFileToBlob(path, &tr.indexed_rect_geometry); + } +#ifdef X2W_NATIVE_SHADERS + else if (!tr.fixed_rectangle_ir.empty()) { + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const auto n = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (n && n < MAX_PATH && cache_path(path, L"", tr.key, L".gs.cso")) { + try { + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto result = compiler.compile(tr.fixed_rectangle_ir, L"gs_6_6", + std::filesystem::path(path).parent_path(), x2w::ShaderSourceFormat::dxil_ir); + hr = D3DCreateBlob(result.dxil.size(), &tr.indexed_rect_geometry); + if (SUCCEEDED(hr)) std::memcpy(tr.indexed_rect_geometry->GetBufferPointer(), + result.dxil.data(), result.dxil.size()); + } catch (const std::exception& e) { + log("x2w-draw %016llx native rectangle stage: %s", tr.key, e.what()); + } + } + } +#endif + if (FAILED(hr)) + log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key, + static_cast<unsigned long>(hr), errors ? static_cast<const char*>(errors->GetBufferPointer()) : ""); + } + if (!tr.indexed_rect_geometry) return false; + desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()}; + return true; +} + +// A recipe can only be used when its draw state and the pass match the recipe's key. Other records +// in the same translation file stay on disk for a later pass and are ignored here. +bool replay_pso_recipes(BoundPipeline& bound, Translation& tr, const Pass& pass, DXGI_FORMAT dsv_format, + bool use_depth_stencil, const D3D12_BLEND_DESC& effective_blend) +{ + unsigned precreated = 0, mismatched = 0, failed = 0; + const D3D12_RASTERIZER_DESC bound_rasterizer = bound.has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer(); + for (const x2w_startup::PsoRecipe& recipe : tr.pso_recipes) { + if (recipe.translation_key != tr.key || !x2w_startup::pso_recipe_targets_match(recipe, pass.target_count, + pass.target_formats, dsv_format)) + continue; + if (recipe.use_depth_stencil != use_depth_stencil || + (use_depth_stencil && !x2w_startup::same_pso_depth(recipe.depth_stencil, bound.depth_stencil)) || + recipe.has_rasterizer != bound.has_rasterizer || + !x2w_startup::same_pso_rasterizer(recipe.rasterizer, bound_rasterizer) || + !x2w_startup::same_pso_blend(recipe.blend, effective_blend) || recipe.sample_count != 1 || + recipe.sample_mask != ~0u || recipe.topology != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + ++mismatched; + continue; + } + const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, + use_depth_stencil, bound.depth_stencil, bound.has_rasterizer, + bound.rasterizer, recipe.indexed_rect); + if (key != recipe.state_key) { + ++mismatched; + continue; + } + if (bound.pipelines.count(key)) continue; + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + if (!prepare_translated_pso_desc(tr, recipe.indexed_rect, desc)) { + ++failed; + continue; + } + x2w_startup::apply_pso_recipe(recipe, desc); + ID3D12PipelineState* pipeline = nullptr; + X2W_ZONE("desktop pipeline creation from recipe"); + const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); + check_device("translated CreateGraphicsPipelineState from recipe", 0); + if (FAILED(hr) || !pipeline) { + if (pipeline) pipeline->Release(); + ++failed; + continue; + } + bound.pipelines[key] = pipeline; + ++precreated; + } + if (precreated || mismatched || failed) { + log("x2w-draw pso recipes %016llx: precreated %u, mismatched %u, failed %u", tr.key, precreated, mismatched, failed); + InterlockedAdd(&pso_recipes_precreated, static_cast<LONG>(precreated)); + InterlockedAdd(&pso_recipe_mismatches, static_cast<LONG>(mismatched)); + } + return precreated || mismatched || failed; +} + ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass, bool indexed_rect) { const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass); - u64 key = pass.target_count; - for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast<u64>(pass.target_formats[i]); - key = fnv_bytes(&dsv_format, sizeof(dsv_format), key); // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); - if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); - if (bound.has_rasterizer) key = fnv_bytes(&bound.rasterizer, sizeof(bound.rasterizer), key); - key = fnv_bytes(&indexed_rect, sizeof(indexed_rect), key); + const u64 key = x2w_startup::pso_state_key(pass.target_count, pass.target_formats, dsv_format, use_depth_stencil, + bound.depth_stencil, bound.has_rasterizer, bound.rasterizer, indexed_rect); const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = tr.root; - desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; - desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; - if (indexed_rect) { - if (!tr.indexed_rect_geometry_attempted) { - tr.indexed_rect_geometry_attempted = true; - x2w_startup::ComPtr<ID3DBlob> errors; - const HRESULT hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors); - if (FAILED(hr)) - log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key, - static_cast<unsigned long>(hr), errors ? static_cast<const char*>(errors->GetBufferPointer()) : ""); - } - if (!tr.indexed_rect_geometry) return nullptr; - desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()}; - } - // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and - // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state comes from - // the stream RASTERIZER / RASTERIZER1 subobject, else solid fill, no culling, depth clip on. - for (auto& target : desc.BlendState.RenderTarget) - target = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, - D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; - if (bound.has_blend) desc.BlendState = bound.blend; - // Channels the translated exports leave unwritten stay out of the write mask (#1674). - if (!x2w_startup::apply_export_write_masks(desc.BlendState, tr.write_masks, pass.target_count)) { + D3D12_BLEND_DESC blend{}; + if (!effective_blend_state(bound, tr, pass.target_count, blend)) { log("x2w-draw export write masks incompatible with shared logic op for %016llx", tr.key); bound.pipelines[key] = nullptr; return nullptr; } + const u64 targets_key = x2w_startup::pso_targets_key(pass.target_count, pass.target_formats, dsv_format); + if (!tr.pso_recipes.empty() && bound.pso_recipe_targets_tried.insert(targets_key).second) { + const bool attempted = replay_pso_recipes(bound, tr, pass, dsv_format, use_depth_stencil, blend); + const auto replayed = bound.pipelines.find(key); + if (replayed != bound.pipelines.end()) return replayed->second; + if (attempted) InterlockedIncrement(&pso_recipe_fallbacks); + } + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + if (!prepare_translated_pso_desc(tr, indexed_rect, desc)) return nullptr; + // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and + // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state comes from + // the stream RASTERIZER / RASTERIZER1 subobject, else solid fill, no culling, depth clip on. + desc.BlendState = blend; if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil; desc.SampleMask = ~0u; - if (bound.has_rasterizer) { - desc.RasterizerState = bound.rasterizer; - } else { - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.RasterizerState.DepthClipEnable = TRUE; - } + desc.RasterizerState = bound.has_rasterizer ? bound.rasterizer : x2w_startup::default_pso_rasterizer(); desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; @@ -854,6 +1498,17 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P static_cast<int>(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); check_device("translated CreateGraphicsPipelineState", 0); bound.pipelines[key] = pipeline; + if (pipeline) { + wchar_t path[MAX_PATH]; + if (pso_recipe_path(path, tr.key)) { + const x2w_startup::PsoRecipe recipe = x2w_startup::make_pso_recipe( + tr.key, key, indexed_rect, use_depth_stencil, bound.has_rasterizer, desc); + if (!append_pso_recipe(path, recipe)) { + static LONG logged; + if (first_calls(logged, 16)) log("x2w-draw pso recipe for %016llx was not written (directory, size limit or I/O)", tr.key); + } + } + } return pipeline; } @@ -877,51 +1532,7 @@ bool ensure_draw_heap(Wrapper* device) return true; } -// A recorded table is immutable. Keep it alive until its submission completes, -// including when the title resets the command list with a different allocator. using DrawSamplerHeap = x2w_startup::ComPtr<ID3D12DescriptorHeap>; -std::unordered_map<ID3D12CommandList*, std::vector<DrawSamplerHeap>> recorded_draw_sampler_heaps; -struct SubmittedDrawSamplerHeaps { - x2w_startup::ComPtr<ID3D12Fence> fence; - std::vector<DrawSamplerHeap> heaps; -}; -std::vector<SubmittedDrawSamplerHeaps> submitted_draw_sampler_heaps; - -void discard_draw_sampler_heaps(ID3D12CommandList* list) -{ - AcquireSRWLockExclusive(&draw_lock); - recorded_draw_sampler_heaps.erase(list); - ReleaseSRWLockExclusive(&draw_lock); -} - -// draw_lock held. The lists have already been executed on this queue. A closed list can be -// submitted again until its Reset, so each submit takes its own references and the recording -// keeps its own until discard_draw_sampler_heaps. -void retire_draw_sampler_heaps(ID3D12CommandQueue* queue, const std::vector<ID3D12CommandList*>& lists) -{ - submitted_draw_sampler_heaps.erase(std::remove_if(submitted_draw_sampler_heaps.begin(), - submitted_draw_sampler_heaps.end(), [](const SubmittedDrawSamplerHeaps& batch) { - return batch.fence && batch.fence->GetCompletedValue() != 0; - }), submitted_draw_sampler_heaps.end()); - SubmittedDrawSamplerHeaps batch; - for (auto* list : lists) { - auto it = recorded_draw_sampler_heaps.find(list); - if (it == recorded_draw_sampler_heaps.end()) continue; - for (const auto& heap : it->second) batch.heaps.push_back(heap); - } - if (batch.heaps.empty()) return; - x2w_startup::ComPtr<ID3D12Device> device; - HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); - if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&batch.fence)); - if (SUCCEEDED(hr)) hr = queue->Signal(batch.fence.Get(), 1); - if (FAILED(hr)) { - // Without a completion point the submitted descriptors still belong - // to the queue. Retain them instead of reclaiming them early. - batch.fence.Reset(); - log("x2w-draw sampler heap retirement fence failed 0x%08lx", static_cast<unsigned long>(hr)); - } - submitted_draw_sampler_heaps.push_back(std::move(batch)); -} struct TextureUpload { u64 hash = 0, generation = ~0ull; @@ -936,8 +1547,7 @@ std::unordered_map<ID3D12Resource*, TextureUpload>& texture_uploads() { static s u64 address_upload_revision; // A texture published in a newly supported console layout is not filled through the shared upload ring. -// The ring is reused without waiting for any queue, and a queue held behind a fence can execute a -// recorded copy long after later uploads have passed over its source bytes. Each such upload owns +// The bounded ring can fill while a queue waits on a fence. Each such upload owns // its upload buffer instead. The buffer and the texture it fills stay referenced by the recording, // and by every submit of that recording until the queue it went to has completed the submit, as // for the sampler heaps above. @@ -1060,9 +1670,24 @@ bool resolve_draw_sampler(const x2w_startup::SamplerWords& words, D3D12_SAMPLER_ } // draw_lock held. -bool prepare_draw_sampler_heap(Pass& pass, ID3D12GraphicsCommandList* list, bool reserved_fallback) +bool prepare_draw_sampler_heap(Wrapper* self, Pass& pass, ID3D12GraphicsCommandList* list, bool reserved_fallback) { auto snapshot = x2w_startup::snapshot_samplers(pass.title_samplers, reserved_fallback); + if (!pass.title_samplers.address && pass.sampler_heap_wrapper) { + AcquireSRWLockShared(¬e_lock); + for (const auto& heap : heap_infos()) { + if (heap.wrapper != pass.sampler_heap_wrapper || !heap.shadow) continue; + const UINT capacity = reserved_fallback ? x2w_startup::translated_sampler_fallback : x2w_startup::translated_sampler_count; + snapshot.count = (std::min)(heap.count, capacity); + for (UINT i = 0; i < snapshot.count; ++i) { + if (!heap.shadow[i]) continue; + snapshot.words[i] = {view_token_magic, heap.shadow[i] - 1, 22, 0}; + snapshot.readable.set(i); + } + break; + } + ReleaseSRWLockShared(¬e_lock); + } if (pass.sampler_snapshot && *pass.sampler_snapshot == snapshot) return true; x2w_startup::NullSamplerCounts counts; DrawSamplerHeap heap; @@ -1072,31 +1697,56 @@ bool prepare_draw_sampler_heap(Pass& pass, ID3D12GraphicsCommandList* list, bool log("x2w-draw sampler heap creation failed 0x%08lx", static_cast<unsigned long>(hr)); return false; } + std::unique_ptr<x2w_startup::SamplerSnapshot> cached; + try { + cached = std::make_unique<x2w_startup::SamplerSnapshot>(std::move(snapshot)); + x2w_startup::ExclusiveNoteLock lock(allocator_lock); + const auto recording = list_recordings.find(self); + if (!self->own().list_open || self->own().real != list || + recording == list_recordings.end() || !recording->second) + return false; + recording->second->sampler_snapshots.push_back(heap); + } catch (const std::bad_alloc&) { + return false; + } static LONG reports; if (first_calls(reports, 12)) log("x2w-draw sampler heap: null_sampler_unbound=%u null_sampler_out_of_range=%u " "null_sampler_unreadable=%u null_sampler_invalid_token=%u", counts.unbound, counts.out_of_range, counts.unreadable, counts.invalid_token); - recorded_draw_sampler_heaps[list].push_back(heap); pass.sampler_heap = std::move(heap); - pass.sampler_snapshot = std::make_unique<x2w_startup::SamplerSnapshot>(std::move(snapshot)); + pass.sampler_snapshot = std::move(cached); return true; } +// Fixture entry records a default sampler table through the translated draw path. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_record_sampler_snapshot(void* guest_list) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind || !self->own().real || !the_device) return FALSE; + x2w_startup::ExclusiveNoteLock lock(draw_lock); + auto* list = static_cast<ID3D12GraphicsCommandList*>(self->own().real); + Pass pass; + if (!prepare_draw_sampler_heap(self, pass, list, false)) return FALSE; + ID3D12DescriptorHeap* heaps[] = {pass.sampler_heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + return TRUE; +} + // Copies of title memory made for the current frame, found by (address, bytes). A title may rewrite the same // address between two draws of one frame (a dynamic constant buffer, a reused vertex or index range), so an // entry keeps the bytes it was made from and is reused only while the title's memory still matches them. The // upload ring is write-combined memory that is slow to read, so the comparison is against this copy, not the ring. struct FrameCopy { u64 address = 0; - u64 offset = 0; + UploadReservation slice; std::vector<unsigned char> content; }; std::unordered_map<u64, FrameCopy>& frame_copies() { static std::unordered_map<u64, FrameCopy> m; return m; } LONG frame_copies_frame = -1; // Callers have just probed that [address, address + bytes) is readable (readable_window), and draw_lock is held. -bool frame_copy(u64 address, std::size_t bytes, u64* offset) +bool frame_copy(Wrapper* self, u64 address, std::size_t bytes, u64* offset, ID3D12Resource** resource) { if (frame_copies_frame != frame_number) { frame_copies().clear(); @@ -1107,29 +1757,40 @@ bool frame_copy(u64 address, std::size_t bytes, u64* offset) const auto found = frame_copies().find(key); const bool known = found != frame_copies().end() && found->second.address == address && found->second.content.size() == bytes; if (known && std::memcmp(found->second.content.data(), title, bytes) == 0) { - *offset = found->second.offset; - return true; + const auto& slice = found->second.slice; + AcquireSRWLockExclusive(&allocator_lock); + for (unsigned i = 0; i < upload_chunks.size(); ++i) { + auto& chunk = upload_chunks[i]; + if (chunk.resource == slice.resource && chunk.generation == slice.generation) { + chunk.hold(self->own().upload_chunks, i); + ReleaseSRWLockExclusive(&allocator_lock); + *offset = slice.offset; + if (resource) *resource = slice.resource; + return true; + } + } + ReleaseSRWLockExclusive(&allocator_lock); } - u64 fresh = 0; - auto* ring = reserve_upload_ring(bytes, &fresh); - if (!ring) return false; + const auto slice = reserve_upload_ring(self, bytes); + if (!slice.mapped) return false; // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. const unsigned char* source = title; try { std::vector<unsigned char> content(title, title + bytes); // Use the stored snapshot to fill the ring so the GPU bytes and subsequent comparisons agree. - auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, std::move(content)}); + auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, slice, std::move(content)}); source = entry.first->second.content.data(); } catch (const std::bad_alloc&) { // The ring slice is already reserved. The draw can proceed without another CPU allocation. } - std::memcpy(ring, source, bytes); + std::memcpy(slice.mapped, source, bytes); if (known) { static LONG refreshed; if (first_calls(refreshed, 4)) log("x2w-draw frame copy of 0x%llx (%zu bytes) refreshed: the title changed it since an earlier draw of this frame", address, bytes); } - *offset = fresh; + *offset = slice.offset; + if (resource) *resource = slice.resource; return true; } @@ -1214,25 +1875,32 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) // Any other texture slot 70 publishes holds its texels in the console layout its description names // (gfx10_layout.h, address_texture.h). const bool tiled_bc7 = !tiled_chain && !tiled_address && written.bc7_width != 0; - const bool tiled = tiled_bc7 || tiled_address || tiled_chain; + // Placed sampled BC7 surfaces can carry the same 64 KiB display layout as an address-only SRV. + // GPU-authored resources have already returned above; only detile the CPU backing on upload. + const bool placed_display_bc7 = !tiled_address && original && desc.MipLevels == 1 && + desc.DepthOrArraySize == 1 && desc.Format == DXGI_FORMAT_BC7_UNORM && + x2w_startup::gfx10::swizzle_mode(original->console) == 10 && console_layout_srv(original->console); + const bool detile_console = console || placed_display_bc7; + const bool tiled = tiled_bc7 || tiled_address || tiled_chain || placed_display_bc7; std::optional<x2w_startup::gfx10::Layout> console_layout; - if (console) console_layout.emplace(original->console); + if (detile_console) console_layout.emplace(original->console); const auto generation = written.generation; const x2w_startup::Bc16Surface surface(tiled_bc7 ? written.bc7_width : static_cast<UINT>(desc.Width), tiled_bc7 ? written.bc7_height : desc.Height); - if (tiled_bc7) { + if (tiled_bc7 && !placed_display_bc7) { if (!original || !x2w_startup::supports_bc7_4k_s(original->console) || original->console.Width != written.bc7_width || original->console.Height != written.bc7_height || desc.Format != DXGI_FORMAT_BC7_UNORM || desc.Width != surface.columns * surface.block_texels || desc.Height != surface.rows * surface.block_texels) return true; } - if (tiled && !tiled_chain && !single && !console && (plan.count != 1 || plan.rows[0] != surface.rows || + if (tiled && !tiled_chain && !single && !detile_console && (plan.count != 1 || plan.rows[0] != surface.rows || plan.row_bytes[0] != u64{surface.columns} * surface.block_bytes)) return true; - if (console) { + if (detile_console) { // The desktop footprints must hold exactly the elements the console layout addresses. if (console_layout->mips != mips || console_layout->slices != slices || plan.count != mips) return false; for (UINT i = 0; i < mips; ++i) if (!plan.bytes(i) || plan.rows[i] != console_layout->rows(i) || + plan.placed[i].Footprint.Depth != console_layout->layers(i) || plan.row_bytes[i] != u64{console_layout->columns(i)} * console_layout->bytes_per_element) return false; } // A texture given the 4 KiB allocation answer is read in the compact plan XG describes and writes for it @@ -1246,7 +1914,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) rows_match = compact.level[i].rows == plan.rows[i] && compact.level[i].row_bytes == plan.row_bytes[i]; if (!rows_match) return true; } - const u64 total = tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : console ? console_layout->bytes() + const u64 total = tiled_chain ? x2w_startup::bc64::Chain(original->console).bytes() : detile_console ? console_layout->bytes() : tiled && !single ? surface.size() : is_compact ? compact.bytes : stride * (slices - 1) + slice_total; const bool announced = state.generation != generation; const UINT elapsed = static_cast<UINT>(frame_number) - static_cast<UINT>(state.checked_frame); @@ -1287,24 +1955,27 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) } state.staged = false; require_state(self, texture, D3D12_RESOURCE_STATE_COPY_DEST); - if (console) { + if (detile_console) { for (UINT slice = 0; slice < slices; ++slice) { for (UINT i = 0; i < mips; ++i) { const u64 bytes = plan.bytes(i); u64 offset = owned.cursor; + ID3D12Resource* chunk = nullptr; unsigned char* rows = owned.cpu ? owned.cpu + offset : nullptr; if (owned.cpu) { owned.cursor += (bytes + placement - 1) & ~(placement - 1); } else { - rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); - if (!rows) { + rows = reserve_upload_ring(self, static_cast<std::size_t>(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return false; } std::memset(rows, 0, static_cast<std::size_t>(bytes)); } - console_layout->detile(i, slice, memory, rows, plan.placed[i].Footprint.RowPitch); - plan.upload(list, texture, owned.cpu ? owned.resource.Get() : upload_ring, mips, slices, slice, i, offset); + // The depth layers of a volume follow one another, rows[i] rows apart. + console_layout->detile(i, slice, memory, rows, plan.placed[i].Footprint.RowPitch, + std::size_t{plan.placed[i].Footprint.RowPitch} * plan.rows[i]); + plan.upload(list, texture, owned.cpu ? owned.resource.Get() : chunk, mips, slices, slice, i, offset); } } if (dedicated) { @@ -1317,36 +1988,39 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (UINT i = 0; i < mips; ++i) { const u64 bytes = plan.bytes(i); u64 offset = 0; - auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); - if (!rows) { + ID3D12Resource* chunk = nullptr; + auto* rows = reserve_upload_ring(self, static_cast<std::size_t>(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return true; } std::memset(rows, 0, static_cast<std::size_t>(bytes)); chain.copy<false>(i, slice, rows, memory, plan.placed[i].Footprint.RowPitch); - plan.upload(list, texture, upload_ring, mips, slices, slice, i, offset); + plan.upload(list, texture, chunk, mips, slices, slice, i, offset); } } } else if (tiled && !single) { u64 offset = 0; const auto bytes = plan.bytes(0); - auto* rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); - if (!rows) { + ID3D12Resource* chunk = nullptr; + auto* rows = reserve_upload_ring(self, static_cast<std::size_t>(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return true; } std::memset(rows, 0, static_cast<std::size_t>(bytes)); surface.detile(memory, rows, plan.placed[0].Footprint.RowPitch); - plan.upload(list, texture, upload_ring, 1, 1, 0, 0, offset); + plan.upload(list, texture, chunk, 1, 1, 0, 0, offset); } else { for (UINT s = 0; s < slices; ++s) for (UINT i = 0; i < plan.count; ++i) { const auto& fp = plan.placed[i]; const u64 bytes = plan.bytes(i); u64 offset = 0; + ID3D12Resource* chunk = nullptr; if (is_compact) { - auto* const rows = reserve_upload_ring(static_cast<std::size_t>(bytes), &offset); - if (!rows) { + auto* const rows = reserve_upload_ring(self, static_cast<std::size_t>(bytes), &offset, &chunk); + if (!rows || !chunk) { state.done = false; return true; } @@ -1354,11 +2028,11 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (u64 y = 0; y < level.rows; ++y) std::memcpy(rows + y * fp.Footprint.RowPitch, memory + level.offset + y * level.row_bytes, static_cast<std::size_t>(level.row_bytes)); - } else if (!ring_copy(reinterpret_cast<u64>(memory) + stride * s + fp.Offset, static_cast<std::size_t>(bytes), &offset)) { + } else if (!ring_copy(self, reinterpret_cast<u64>(memory) + stride * s + fp.Offset, static_cast<std::size_t>(bytes), &offset, &chunk) || !chunk) { state.done = false; return true; } - plan.upload(list, texture, upload_ring, mips, slices, s, i, offset); + plan.upload(list, texture, chunk, mips, slices, s, i, offset); } } state.hash = hash; @@ -1389,18 +2063,54 @@ LONG draw_dump_frame() }(); return frame; } +struct DrawDumpPixel { + bool enabled{}; + UINT x{}, y{}; +}; +// X2W_DRAW_DUMP_PIXEL=<x>,<y>: keep one texel after each translated draw of the dumped frame +// instead of the whole target. The report names the draw ordinal, the manifest key and the value. +DrawDumpPixel draw_dump_pixel() +{ + static const DrawDumpPixel pixel = [] { + DrawDumpPixel value{}; + char text[64]{}; + if (!GetEnvironmentVariableA("X2W_DRAW_DUMP_PIXEL", text, sizeof(text))) return value; + unsigned x = 0, y = 0; + char trailing = 0; + if (std::sscanf(text, "%u,%u%c", &x, &y, &trailing) != 2) return value; + value.enabled = true; + value.x = x; + value.y = y; + return value; + }(); + return pixel; +} void draw_dump_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UINT count) { Pass& pass = pass_of(self); const LONG wanted = draw_dump_frame(); - if (!wanted || frame_number < wanted || frame_number > wanted + 1 || !pass.target0 || draw_dumps().full()) return; + const DrawDumpPixel pixel = draw_dump_pixel(); + if (!wanted || !pass.target0 || draw_dumps().full()) return; + if (frame_number < wanted || frame_number > wanted + 1) { + static const u64 sample_key = probe_key("X2W_DRAW_DUMP_SAMPLE_KEY"); + static LONG last{}; + if (!sample_key || key != sample_key || !pixel.enabled || frame_number < wanted || + frame_number % 24 || InterlockedExchange(&last, frame_number) == frame_number) return; + } const D3D12_RESOURCE_DESC desc = pass.target0->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || - !x2w_draw_bmp::supported(desc.Format)) return; + (!x2w_draw_bmp::supported(desc.Format) && !(pixel.enabled && x2w_startup::pixel_history_supported(desc.Format)))) return; + if (pixel.enabled && (pixel.x >= desc.Width || pixel.y >= desc.Height)) return; D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; UINT rows = 0; UINT64 row_bytes = 0, total = 0; - device_of(the_device)->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &row_bytes, &total); + if (pixel.enabled) { + footprint.Footprint = {desc.Format, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT}; + rows = 1; + total = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; + } else { + device_of(the_device)->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &row_bytes, &total); + } const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; D3D12_RESOURCE_DESC buffer{}; buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -1421,22 +2131,66 @@ void draw_dump_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UI dump.key = key; dump.count = count; dump.format = desc.Format; + dump.frame = frame_number; + dump.pixel = pixel.enabled; + dump.pixel_x = pixel.x; + dump.pixel_y = pixel.y; if (!draw_dumps().record(list, std::move(dump))) return; require_state(self, pass.target0, D3D12_RESOURCE_STATE_COPY_SOURCE); D3D12_TEXTURE_COPY_LOCATION target{readback, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; target.PlacedFootprint = footprint; D3D12_TEXTURE_COPY_LOCATION source{pass.target0, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; source.SubresourceIndex = 0; - list->CopyTextureRegion(&target, 0, 0, 0, &source, nullptr); + if (pixel.enabled) { + const D3D12_BOX box{pixel.x, pixel.y, 0, pixel.x + 1, pixel.y + 1, 1}; + list->CopyTextureRegion(&target, 0, 0, 0, &source, &box); + } else { + list->CopyTextureRegion(&target, 0, 0, 0, &source, nullptr); + } require_state(self, pass.target0, D3D12_RESOURCE_STATE_RENDER_TARGET); } void draw_dump_flush() { if (!draw_dump_frame()) return; auto completed = draw_dumps().take_completed(); + completed.erase(std::remove_if(completed.begin(), completed.end(), [](const DrawDump& d) { + if (d.rows || d.format != DXGI_FORMAT_UNKNOWN) return false; + void* data{}; + if (SUCCEEDED(d.buffer->Map(0, nullptr, &data))) { + const auto* w = static_cast<const UINT*>(data); + log("x2w-argument-probe gpu frame=%ld event=%u key=%016llx data=%08x,%08x,%08x", d.frame, d.count, d.key, + w[0], d.count == 17 ? 0 : w[1], d.count == 17 ? 0 : w[2]); + D3D12_RANGE empty{}; d.buffer->Unmap(0,&empty); + } + return true; + }),completed.end()); if (completed.empty()) return; char folder[MAX_PATH] = "."; GetEnvironmentVariableA("X2W_DRAW_DUMP_DIR", folder, sizeof(folder)); + if (draw_dump_pixel().enabled) { + static std::vector<x2w_startup::PixelHistorySample> samples; + std::sort(completed.begin(), completed.end(), [](const DrawDump& a, const DrawDump& b) { return a.index < b.index; }); + for (const DrawDump& dump : completed) { + void* mapped = nullptr; + if (FAILED(dump.buffer->Map(0, nullptr, &mapped))) continue; + x2w_startup::PixelHistorySample sample{}; + sample.draw = dump.index; + sample.frame = dump.frame; + sample.x = dump.pixel_x; + sample.y = dump.pixel_y; + sample.key = dump.key; + sample.count = dump.count; + sample.format = dump.format; + x2w_startup::pixel_history_decode(sample, static_cast<const unsigned char*>(mapped) + dump.footprint.Offset); + const D3D12_RANGE no_writes{}; + dump.buffer->Unmap(0, &no_writes); + samples.push_back(sample); + } + std::sort(samples.begin(), samples.end(), [](const auto& a, const auto& b) { return a.draw < b.draw; }); + const bool written = x2w_startup::pixel_history_write(folder, samples.data(), samples.size()); + log("x2w-draw pixel history: %s %zu samples at %s", written ? "wrote" : "could not write", samples.size(), folder); + return; + } int written = 0; for (const DrawDump& dump : completed) { const int index = static_cast<int>(dump.index); @@ -1457,6 +2211,14 @@ void draw_dump_flush() log("x2w-draw per-draw dump: %d of %zu completed target copies written to %s", written, completed.size(), folder); } +// The view dimension a manifest texture kind declares (Translation::Srv::kind 1 to 5). +D3D12_SRV_DIMENSION translated_view_dimension(int kind) +{ + return kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : + kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : kind == 5 ? D3D12_SRV_DIMENSION_TEXTURECUBE : + D3D12_SRV_DIMENSION_TEXTURE3D; +} + bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16_unorm16)[32]) { if (!tr.d16_srvs.any()) return true; @@ -1471,9 +2233,7 @@ bool d16_srvs_ready(const Translation& tr, const Pass& pass, std::uint32_t (&d16 const Translation::Srv& srv = tr.srvs[i]; if (srv.kind < 1 || srv.kind > 4 || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0) return refuse(i, "non-table texture binding", srv.kind); - const auto dimension = srv.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : - srv.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : - srv.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_TEXTURE3D; + const auto dimension = translated_view_dimension(srv.kind); const u64 entry = pass.view_tables[srv.a].record(static_cast<u64>(srv.b), 32); std::uint32_t words[8] = {}; if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) @@ -1574,6 +2334,7 @@ constexpr const char* sampled_texture_unbindable = "sampled_texture_unbindable"; constexpr const char* incomplete_vertex_stream = "incomplete_vertex_stream"; constexpr const char* incomplete_table_buffer = "incomplete_table_buffer"; constexpr const char* indexed_validation_failed = "indexed_validation_failed"; +constexpr const char* read_only_depth_write = "read_only_depth_write"; } // namespace indirect_refusal_code struct TranslatedIndirectDraw { @@ -1724,14 +2485,7 @@ ID3D12Resource* validate_indexed_arguments(Wrapper* self, ID3D12GraphicsCommandL // The clamp changes the native compute root and invalidates its arguments. // In render mode slot 43 is the forwarded compute parameter setter. - const auto& pass = pass_of(self); - if (pass.desktop_compute_root) { - list->SetComputeRootSignature(pass.desktop_compute_root.Get()); - for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) { - const auto address = pass.desktop_compute_upload_srvs[parameter]; - if (address) list->SetComputeRootShaderResourceView(parameter, address); - } - } + restore_compute_root(pass_of(self), list); return scratch.Get(); } @@ -1740,16 +2494,35 @@ struct IndirectBufferView { u64 offset = 0, bytes = 0; UINT stride = 0; bool upload = false; + int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES), 2 a snapshot of title memory, 3 zeros for a null descriptor }; +// X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1: a translated compute input in a placed buffer that does not alias title memory +// (a committed default buffer that holds zeros) is read from title memory, snapshotted into its own recycled pool. +bool title_input_snapshot_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT"); + return enabled; +} + // For indirect draws, bind the complete descriptor range on a known GPU backing. There is no // fallback to copying an unrelated or stale title allocation into the draw upload ring. -IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words, bool allow_address_alias = false) +// why, when given, receives the condition an empty result failed on. +IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words, bool allow_address_alias = false, + const char** why = nullptr, + u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, + UINT alignment = D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, + bool allow_title_snapshot = false) { - constexpr u64 limit = 16u << 20; + const auto refuse = [why](const char* reason) { + if (why) *why = reason; + return IndirectBufferView{}; + }; u64 address = 0, offset = 0, bytes = 0; UINT stride = 0; const Wrapper* owner = nullptr; + bool own_memory = false; + if (why) *why = nullptr; if (words[0] == view_token_magic) { ViewRecord record{}; AcquireSRWLockShared(¬e_lock); @@ -1765,7 +2538,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor std::memcpy(&view, record.desc, 40); owner = as_wrapper(reinterpret_cast<const void*>(record.resource)); if (!owner || owner->own().kind != resource_kind || !owner->own().real || - view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return {}; + view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return refuse("an input view token is not a buffer view of a desktop resource"); const bool raw = view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW && !view.Buffer.StructureByteStride && view.Format == DXGI_FORMAT_R32_TYPELESS; const bool structured = view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_NONE && view.Buffer.StructureByteStride && @@ -1773,58 +2546,111 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const bool typed = view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_NONE && !view.Buffer.StructureByteStride; const UINT element = raw ? 4 : structured ? view.Buffer.StructureByteStride : typed ? x2w_startup::typed_buffer_format_bytes(view.Format) : 0; - if (!element || view.Buffer.FirstElement > UINT64_MAX / element) return {}; + if (!element || view.Buffer.FirstElement > UINT64_MAX / element) return refuse("an input buffer view has no element size or overflows"); offset = view.Buffer.FirstElement * element; bytes = u64{view.Buffer.NumElements} * element; stride = raw ? 0 : element; if (const auto base = reinterpret_cast<u64>(owner->own().title_memory)) { - if (offset > UINT64_MAX - base) return {}; - address = base + offset; + // A buffer on a custom heap outside the placement index (the memory view path places it in the title's + // own heap) is that memory: the view offset is bound in the token's own desktop resource. + const auto* info = resource_info(owner); + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + own_memory = info && info->placement == Placement::none && + SUCCEEDED(static_cast<ID3D12Resource*>(owner->own().real)->GetHeapProperties(&props, &flags)) && + props.Type == D3D12_HEAP_TYPE_CUSTOM; + if (offset > UINT64_MAX - base) return refuse("an input buffer view has no element size or overflows"); + if (!own_memory) address = base + offset; } + } else { + return refuse("an input view token is not a buffer view of a desktop resource"); } } else { address = words[0] | (u64{words[1] & 0xffff} << 32); stride = (words[1] >> 16) & 0x3fff; bytes = u64{stride ? stride : 1} * words[2]; } - if (!bytes || bytes > limit || bytes % 4) return {}; + // A compute input whose four descriptor words are all zero is an unbound (null) buffer: the hardware reads zeros from + // it, so the dispatch gets 16 bytes of zeros instead of being refused. Any other empty range is still refused. + if (!bytes && allow_title_snapshot && !words[0] && !words[1] && !words[2] && !words[3]) { + u64 zero_offset = 0; + ID3D12Resource* zero_ring = nullptr; + unsigned char* zero_bytes = reserve_upload_ring(self, 16, &zero_offset, &zero_ring, true); + if (!zero_bytes || !zero_ring) return refuse("a null input could not get its zero bytes"); + std::memset(zero_bytes, 0, 16); + return {zero_ring, zero_offset, 16, 0, true, 3}; + } + if (!bytes) return refuse("an input buffer descriptor has zero records"); + if (bytes > limit || bytes % 4) return refuse(limit == (16u << 20) + ? "an input buffer range is over 16 MiB or not whole dwords" + : "an input buffer range exceeds the D3D12 raw SRV limit or is not whole dwords"); ID3D12Resource* native = nullptr; bool upload = false; + int input_source = 0; Wrapper* device = self->own().list_device; if (address) { if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { if (!owner) return {allocation.resource, allocation.offset, bytes, stride, true}; - return {}; + return refuse("an input buffer view token names the list's upload memory"); } const auto placed = placed_buffer_range(device, address, bytes); - if (placed.reject || (owner && owner != placed.owner)) return {}; + if (placed.reject) return refuse("an input range crosses the end of a placed buffer"); + if (owner && owner != placed.owner) return refuse("an input buffer view token's resource does not hold its range"); if (!placed.owner) { - const auto alias = allow_address_alias && !list_upload_range(self, address, 1).resource - ? indirect_address_alias(device, address, bytes) : IndirectAddressAlias{}; + const bool in_upload = list_upload_range(self, address, 1).resource != nullptr; + const auto alias = allow_address_alias && !in_upload && bytes <= (16u << 20) ? indirect_address_alias(device, address, bytes) : IndirectAddressAlias{}; + if (!alias.resource) + return refuse(in_upload ? "an input range crosses the end of its upload allocation" + : "an input is in title memory outside any placed buffer"); return {alias.resource, alias.offset, bytes, stride}; } owner = placed.owner; native = static_cast<ID3D12Resource*>(owner->own().real); offset = address - reinterpret_cast<u64>(owner->own().title_memory); - if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) return {}; + if (!placed.alias) { + if (native && list_copied_gpu_range(self, native, offset, bytes)) { + input_source = 1; // a GPU copy of this list filled the range: the GPU buffer is the truth + } else if (allow_title_snapshot && title_input_snapshot_enabled() && bytes <= (u64{16} << 20)) { + // The buffer is a committed default buffer that holds zeros (it does not alias title memory), so the + // bytes the title wrote are only in title memory: snapshot the range into the snapshot pool now. A later + // guest write is not seen (as title_backed_source for copies); data a GPU pass wrote into this buffer is not either. + u64 ring_offset = 0; + ID3D12Resource* ring = nullptr; + if (readable_window(address, static_cast<std::size_t>(bytes)) < bytes) + return refuse("an input range in title memory is not readable"); + if (!ring_copy(self, address, static_cast<std::size_t>(bytes), &ring_offset, &ring, true) || !ring) + return refuse("an input range could not be copied from title memory"); + return {ring, ring_offset, bytes, stride, true, 2}; + } else { + return refuse("an input is in a placed buffer that does not alias title memory"); + } + } + } else if (own_memory) { + native = static_cast<ID3D12Resource*>(owner->own().real); } else if (owner && !owner->own().title_memory) { native = static_cast<ID3D12Resource*>(owner->own().real); D3D12_HEAP_PROPERTIES props{}; D3D12_HEAP_FLAGS flags{}; if (FAILED(native->GetHeapProperties(&props, &flags)) || - (props.Type != D3D12_HEAP_TYPE_DEFAULT && props.Type != D3D12_HEAP_TYPE_UPLOAD)) return {}; + (props.Type != D3D12_HEAP_TYPE_DEFAULT && props.Type != D3D12_HEAP_TYPE_UPLOAD)) + return refuse("an input buffer view token's resource is not on a default or upload heap"); upload = props.Type == D3D12_HEAP_TYPE_UPLOAD; } - if (!native || offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || - !InterlockedCompareExchange(&owner->own().refs, 0, 0)) return {}; + if (!native) return refuse("an input buffer descriptor has a null address"); + if (offset % alignment) return refuse(alignment == 4 ? "typed input range is not dword aligned" : + "an input buffer range is not 16-byte aligned in its resource"); + if (!InterlockedCompareExchange(&owner->own().refs, 0, 0)) return refuse("an input buffer's resource is released"); const auto* info = resource_info(owner); - if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) return {}; + if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) + return refuse("an input buffer's resource was not created in the common state"); x2w_startup::ComPtr<ID3D12Device> native_device; - if (FAILED(native->GetDevice(IID_PPV_ARGS(native_device.GetAddressOf()))) || native_device.Get() != device_of(device)) return {}; + if (FAILED(native->GetDevice(IID_PPV_ARGS(native_device.GetAddressOf()))) || native_device.Get() != device_of(device)) + return refuse("an input buffer's resource is on another device"); const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || - offset > desc.Width || bytes > desc.Width - offset) return {}; - return {native, offset, bytes, stride, upload}; + offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); + trace_compute_output_use(self, OutputUse::shader_gpu_read, "raw-SRV-range-resolved", owner, 0, offset, bytes); + return {native, offset, bytes, stride, upload, input_source}; } struct FormattedBufferDescriptor { @@ -1832,6 +2658,29 @@ struct FormattedBufferDescriptor { std::uint32_t words[8] = {}; }; +// Word 3 of a buffer descriptor as a formatted load decodes it (words[3]): the title's hardware word, or for a typed +// buffer view the title created (words[0] its token) the word the driver builds from its format and component +// mapping. Returns the refusal, with an unsupported FORMAT in format. Draws and compute Dispatch share it. +const char* formatted_buffer_word3(std::uint32_t* words, std::uint32_t& format) +{ + if (words[0] == view_token_magic) { + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known || record.slot != 18 || record.desc_bytes < 40) return "missing hardware descriptor"; + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, record.desc, 40); + return x2w_startup::view_word3(view, words[3]); + } + if (const auto code = x2w_startup::formatted_buffer_code(words[3]); !x2w_startup::formatted_buffer_supported(code)) { + format = code; + return "unsupported FORMAT"; + } + return x2w_startup::descriptor_word3_refusal(words[3]); +} + bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[32]) { const auto refuse = [&](int slot, const char* reason, std::uint32_t detail = 0) { @@ -1854,32 +2703,176 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), sizeof(descriptor.words))) return refuse(ud.a, "missing hardware descriptor"); std::memcpy(descriptor.words, reinterpret_cast<const void*>(entry), sizeof(descriptor.words)); - if (descriptor.words[0] == view_token_magic) { - // A typed buffer view the title created: the driver builds word 3 from its format and component mapping. - ViewRecord record{}; + std::uint32_t format = 0; + if (const char* reason = formatted_buffer_word3(descriptor.words, format)) return refuse(ud.a, reason, format); + descriptor.entry = entry; + } + return true; +} + +struct PixelUavBinding { + ID3D12Resource* resource = nullptr; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; +}; + +// draw_lock held. The writable views of tr (#1996 F), from the unordered-access views the title created at +// their table entries (pixel_uav_view). False, with the reason logged, when one cannot be bound as the program +// expects: the draw is then not translated, and no other view is bound in its place. +bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding* out) +{ + const auto refuse = [&](std::size_t i, const char* reason, unsigned long long detail) { + static LONG refused; + if (first_calls(refused, 16)) + log("x2w-draw %016llx uav %zu refused: %s (0x%llx); draw not translated", tr.key, i, reason, detail); + return false; + }; + for (std::size_t i = 0; i < tr.uavs.size(); ++i) { + const PixelUav& uav = tr.uavs[i]; + if (uav.raw) { + const UINT stride = device_of(the_device)->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (stride < 32 || uav.offset % stride) + return refuse(i, "raw UAV offset is not a descriptor boundary", uav.offset); + } + const x2w_startup::ViewTable& table = pass.view_tables[uav.parameter]; + if (!table.address) return refuse(i, "no descriptor table at the parameter", uav.parameter); + const u64 entry = table.record(uav.offset, 32); + if (!entry) return refuse(i, "table entry outside the bound table", uav.offset); + std::uint32_t words[8] = {}; + if (!x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) return refuse(i, "table entry unreadable", entry); + std::memcpy(words, reinterpret_cast<const void*>(entry), 32); + if (words[0] != view_token_magic) return refuse(i, "table entry holds no view", words[0]); + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known) return refuse(i, "unknown view token", words[1]); + if (record.slot != 19) return refuse(i, "table entry is not an unordered-access view", record.slot); + Wrapper* resource = as_wrapper(reinterpret_cast<const void*>(record.resource)); + if (!resource || resource->own().kind != resource_kind || !resource->own().real) return refuse(i, "view has no resource", record.resource); + if (resource->own().tiled_address_srv) return refuse(i, "resource is a texture by title address", record.resource); + auto* texture = static_cast<ID3D12Resource*>(resource->own().real); + D3D12_UNORDERED_ACCESS_VIEW_DESC title_view{}; + const bool described = record.desc_bytes >= sizeof(title_view); + if (record.desc_bytes && !described) return refuse(i, "truncated view description", record.desc_bytes); + if (described) { + std::memcpy(&title_view, record.desc, sizeof(title_view)); + title_view.Format = desktop_format(title_view.Format); + } + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + const char* reason = nullptr; + if (uav.raw) { + const auto* info = resource_info(resource); + if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) + return refuse(i, "resource lacks ALLOW_UNORDERED_ACCESS", record.resource); + const x2w::ComputeViewBinding binding{x2w::ComputeViewKind::raw_buffer_uav, uav.parameter, uav.offset, uav.index, 4}; + if (!described || record.counter || !info || info->initial_state != D3D12_RESOURCE_STATE_COMMON || + desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + !x2w::native_buffer_store_view(binding, title_view, desc.Width)) + return refuse(i, "incompatible raw buffer UAV", record.resource); + out[i].view = title_view; + } else { + reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, + uav.array, out[i].view, uav.needs_typed_load); + } + if (reason) { + static LONG refused_view; + if (first_calls(refused_view, 16)) + log("x2w-draw %016llx uav %zu refused: %s (view %s dimension %d mip %u format %d; resource dimension %d array %u " + "flags 0x%x format %d); draw not translated", tr.key, i, reason, described ? "described" : "default", + title_view.ViewDimension, title_view.Texture2D.MipSlice, title_view.Format, desc.Dimension, + static_cast<unsigned>(desc.DepthOrArraySize), static_cast<unsigned>(desc.Flags), desc.Format); + return false; + } + // A texture the draw also renders to or reads cannot be bound for writing. Checked here, before the + // draw records any view or state change. + const bool target = std::find(pass.bound_targets, pass.bound_targets + pass.target_count, texture) != + pass.bound_targets + pass.target_count; + if (target || (pass.bound_depth && pass.bound_depth == texture)) + return refuse(i, "the texture is also a render or depth target of this draw", reinterpret_cast<u64>(texture)); + for (std::size_t s = 0; s < tr.srvs.size(); ++s) { + const Translation::Srv& srv = tr.srvs[s]; + if (srv.kind < 1 || srv.kind > 5 || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0) continue; + const u64 srv_entry = pass.view_tables[srv.a].record(static_cast<u64>(srv.b), 32); + std::uint32_t srv_words[8] = {}; + if (!srv_entry || !x2w_local::readable(reinterpret_cast<const void*>(srv_entry), 32)) continue; + std::memcpy(srv_words, reinterpret_cast<const void*>(srv_entry), 32); + if (srv_words[0] != view_token_magic) continue; AcquireSRWLockShared(¬e_lock); - const bool known = descriptor.words[1] < view_records().size(); - if (known) record = view_records()[descriptor.words[1]]; + const u64 srv_resource = srv_words[1] < view_records().size() ? view_records()[srv_words[1]].resource : 0; ReleaseSRWLockShared(¬e_lock); - if (!known || record.slot != 18 || record.desc_bytes < 40) - return refuse(ud.a, "missing hardware descriptor"); - D3D12_SHADER_RESOURCE_VIEW_DESC view; - std::memcpy(&view, record.desc, 40); - if (const char* reason = x2w_startup::view_word3(view, descriptor.words[3])) return refuse(ud.a, reason); - descriptor.entry = entry; - continue; + if (srv_resource && srv_resource == record.resource) return refuse(i, "the texture is also an SRV of this draw", s); } - const auto format = x2w_startup::formatted_buffer_code(descriptor.words[3]); - if (!x2w_startup::formatted_buffer_supported(format)) - return refuse(ud.a, "unsupported FORMAT", format); - if (const char* reason = x2w_startup::descriptor_word3_refusal(descriptor.words[3])) return refuse(ud.a, reason); - descriptor.entry = entry; + out[i].resource = texture; } return true; } +// Keep the slot-zero view origin: the desktop input assembler applies StartVertex +// or the signed BaseVertex after reading the index, just as the fixed fetch prefix does. +bool fixed_vertex_view(Wrapper* self, const Pass& pass, const Translation& tr, bool indexed, UINT start, UINT count, + D3D12_VERTEX_BUFFER_VIEW& view, ID3D12Resource*& transition_resource) +{ + view = pass.vb[0]; + const u64 address = view.BufferLocation; + if (!indexed && count) { + unsigned attribute_end = 0; + for (const auto& e : tr.fixed_stream) { + const auto bytes = x2w_startup::typed_buffer_format_bytes(e.Format); + attribute_end = (std::max)(attribute_end, e.AlignedByteOffset + bytes); + } + if (view.StrideInBytes > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) return false; + const u64 end = (u64{start} + count - 1) * view.StrideInBytes + attribute_end; + view.SizeInBytes = static_cast<UINT>((std::min)(u64{view.SizeInBytes}, end)); + } + const UINT bytes = view.SizeInBytes; + if (!address || !bytes || bytes > UINT64_MAX - address || + view.StrideInBytes > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) return false; + if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { + view.BufferLocation = allocation.gpu; + return view.BufferLocation != 0; + } + if (list_upload_range(self, address, 1).resource) return false; + const auto placed = placed_buffer_range(self->own().list_device, address, bytes); + if (placed.reject) return false; + ID3D12Resource* resource = nullptr; + u64 offset = 0; + if (placed.owner) { + const auto* info = resource_info(placed.owner); + if (!info || !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0)) return false; + resource = static_cast<ID3D12Resource*>(placed.owner->own().real); + offset = address - reinterpret_cast<u64>(placed.owner->own().title_memory); + if (!resource) return false; + if (!placed.alias && !list_copied_gpu_range(self, resource, offset, bytes)) { + // A non-aliased placement keeps the CPU stream in guest memory. Use the same + // recording-time snapshot as a shader-pulled VB. A partly copied GPU range + // cannot be represented by either single view without merging its sources. + for (const auto& range : pass.copied_gpu_ranges) + if (range.resource == resource && offset < range.offset + range.bytes && range.offset < offset + bytes) + return false; + resource = nullptr; + } else if (info->initial_state != D3D12_RESOURCE_STATE_COMMON) return false; + } else { + const auto alias = indirect_address_alias(self->own().list_device, address, bytes); + resource = alias.resource; + offset = alias.offset; + } + if (!resource) { + ID3D12Resource* chunk = nullptr; + if (bytes > (16u << 20) || readable_window(address, bytes) < bytes || + !frame_copy(self, address, bytes, &offset, &chunk) || !chunk) return false; + view.BufferLocation = chunk->GetGPUVirtualAddress() + offset; + return true; + } + if (!resource->GetGPUVirtualAddress() || offset > UINT64_MAX - resource->GetGPUVirtualAddress() || + !retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(resource))) return false; + view.BufferLocation = resource->GetGPUVirtualAddress() + offset; + transition_resource = resource; + return true; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, - TranslatedIndirectDraw* indirect) + TranslatedIndirectDraw* indirect, bool* used_fallback = nullptr) { auto* list = recording(self); Pass& pass = pass_of(self); @@ -1890,6 +2883,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI AcquireSRWLockExclusive(&draw_lock); BoundPipeline* bound = translation_for(pass.pipeline); Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; + if (used_fallback && tr && tr->manifest_retry.pending() && + draw_missing_translation(device_of(self->own().list_device), list, pass, count, instances, start, start_instance)) { + *used_fallback = true; + ReleaseSRWLockExclusive(&draw_lock); + return true; + } if (indirect && tr) indirect->shader_key = tr->key; std::uint32_t d16_unorm16[32] = {}; FormattedBufferDescriptor formatted_buffers[32] = {}; @@ -1904,6 +2903,19 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + const bool fixed_stream = !tr->fixed_stream.empty(); + D3D12_VERTEX_BUFFER_VIEW fixed_view{}; + ID3D12Resource* fixed_resource = nullptr; + if (fixed_stream && (indirect || !fixed_vertex_view(self, pass, *tr, indexed, start, count, fixed_view, fixed_resource))) { + if (indirect) indirect->set_refusal("fixed vertex stream indirect arguments are unsupported", + indirect_refusal_code::unsupported_resource_or_entry); + static LONG refused; + if (first_calls(refused, 16)) + log("x2w-draw %016llx fixed vertex stream refused: rect=%u indirect=%u vb=%llx bytes=%u", + tr->key, rect, indirect != nullptr, pass.vb[0].BufferLocation, pass.vb[0].SizeInBytes); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (indirect) { if (!bound->guest_root || bound->guest_root != pass.root) { indirect->set_refusal("translated draw requires the guest pipeline's root signature", @@ -1917,6 +2929,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (!tr->uavs.empty()) { + indirect->set_refusal("translated draw with a writable texture is not bound for indirect draws", + indirect_refusal_code::unsupported_resource_or_entry); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } auto& entry = indexed ? tr->indexed_indirect_entry : tr->independent_indirect_entry; if (!entry.has_value()) { bool found_base = !indexed; @@ -1939,36 +2957,95 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (bound->has_depth_stencil && pass.dsv_format != DXGI_FORMAT_UNKNOWN && !pass.depth_view_writable && + ((bound->depth_stencil.DepthEnable && bound->depth_stencil.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO) || + (bound->depth_stencil.StencilEnable && bound->depth_stencil.StencilWriteMask != 0))) { + indirect->set_refusal("translated draw writes depth or stencil to a read-only depth view", + indirect_refusal_code::read_only_depth_write); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } } - ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, indexed_rect) : nullptr; + const bool geometry_rect = indexed_rect || (rect && fixed_stream); + ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, geometry_rect) : nullptr; if (indirect && indexed_rect && !pipeline) { indirect->set_refusal("translated indexed rectangle geometry unavailable", indirect_refusal_code::indexed_rect_unavailable); } - if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { + if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(self, pass, list, tr->samplers.reserved_fallback))) { if (indirect && !(indexed_rect && !pipeline)) indirect->refusal_code = !pipeline ? indirect_refusal_code::pipeline_unavailable : indirect_refusal_code::sampler_heap_unavailable; ReleaseSRWLockExclusive(&draw_lock); return false; } + const bool raw_uav = std::any_of(tr->uavs.begin(), tr->uavs.end(), [](const PixelUav& uav) { return uav.raw; }); + // ponytail: prove direct draws with one writable buffer first. SRVs and indexed + // draws can alias it through guest addresses, so do not guess their independence. + if (raw_uav && (indexed || indirect || tr->uavs.size() != 1 || !tr->srvs.empty())) { + log("x2w-draw %016llx raw UAV requires one writable view and a direct non-indexed draw without SRVs", tr->key); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + PixelUavBinding uav_bindings[pixel_uav_limit]; + if (!resolve_pixel_uavs(*tr, pass, uav_bindings) || + (raw_uav && !retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(uav_bindings[0].resource)))) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } const UINT n = static_cast<UINT>(tr->srvs.size()); - UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(n))) % draw_heap_size; - if (first + n > draw_heap_size) { + const UINT views = n + static_cast<UINT>(tr->uavs.size()); // the SRVs, then the UAVs, in one table + UINT first = static_cast<UINT>(InterlockedExchangeAdd(&draw_heap_cursor, static_cast<LONG>(views))) % draw_heap_size; + if (first + views > draw_heap_size) { first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(n)); + InterlockedExchange(&draw_heap_cursor, static_cast<LONG>(views)); } std::uint32_t strides[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by // -vertex_first and each stream's view starts at vertex_first. const UINT index_bytes = pass.ib.Format == DXGI_FORMAT_R16_UINT ? 2 : 4; - const u64 index_address = pass.ib.BufferLocation + u64{start} * index_bytes; + const u64 index_start = u64{start} * index_bytes; + const u64 index_address = pass.ib.BufferLocation + index_start; const std::size_t index_total = std::size_t{count} * index_bytes; const bool indices_ok = indexed && !indirect && pass.ib.BufferLocation && readable_window(index_address, index_total) >= index_total; + D3D12_INDEX_BUFFER_VIEW live_indices{}; + ID3D12Resource* live_index_resource = nullptr; + bool index_read_as_table = false; // live_index_resource is also bound as a table SRV (X2W_D3D12_TABLE_ALIAS) + const auto stream_needs_slicing = [&](const Translation::Srv& srv) { + if (srv.source != 1) return false; + if (srv.a < 0 || srv.a >= 8) return true; + const auto bytes = pass.vb[srv.a].SizeInBytes; + if (!bytes) return false; + const auto& placed = pass.placed_vb[srv.a]; + const u64 address = pass.vb[srv.a].BufferLocation; + if (!placed.alias || placed.reject || !placed.owner) return true; + if (!InterlockedCompareExchange(&placed.owner->own().refs, 0, 0)) return true; + if (address % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT != 0 || bytes % 4 != 0) return true; + return false; + }; + // A vertex-stream SRV uses the recording-time index scan to size and rebase its view. + // For other draws, a live alias lets IA observe legal CPU writes made before submission. + if (indices_ok && index_total && index_address >= pass.ib.BufferLocation && + (pass.ib.Format == DXGI_FORMAT_R16_UINT || pass.ib.Format == DXGI_FORMAT_R32_UINT) && + index_address % index_bytes == 0 && index_start <= pass.ib.SizeInBytes && + index_total <= pass.ib.SizeInBytes - index_start && + std::none_of(tr->srvs.begin(), tr->srvs.end(), stream_needs_slicing)) { + const auto placed = placed_buffer_range(self->own().list_device, index_address, index_total); + if (!placed.reject && placed.alias && InterlockedCompareExchange(&placed.owner->own().refs, 0, 0)) { + const auto base = reinterpret_cast<u64>(placed.owner->own().title_memory); + const auto offset = index_address - base; + const auto gpu = placed.alias->GetGPUVirtualAddress(); + if (gpu && offset <= ~u64{} - gpu && (gpu + offset) % index_bytes == 0 && + retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(placed.alias))) { + live_indices = {gpu + offset, static_cast<UINT>(index_total), pass.ib.Format}; + live_index_resource = placed.alias; + } + } + } INT vertex_first = indexed ? 0 : static_cast<INT>(start); UINT vertex_count = indexed ? 0 : count; - if (indices_ok) { + if (indices_ok && !live_index_resource && !fixed_stream) { std::uint32_t low = ~0u, high = 0; for (UINT k = 0; k < count; ++k) { const std::uint32_t value = index_bytes == 2 ? reinterpret_cast<const std::uint16_t*>(index_address)[k] @@ -2000,6 +3077,9 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI address += skip; bytes = static_cast<std::size_t>(wanted < bytes - skip ? wanted : bytes - skip); } + if (live_index_resource && placed.alias) { + retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(placed.alias)); + } } else if (srv.source == 2 && srv.a < 16) { address = pass.root_address[srv.a]; bytes = readable_window(address, 0x10000); @@ -2013,10 +3093,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI (entry && x2w_local::readable(reinterpret_cast<const void*>(entry), 32)); if (entry_ok) std::memcpy(words, formatted.entry ? formatted.words : reinterpret_cast<const void*>(entry), 32); bool buffer_token_known = false; - if (srv.kind >= 1 && srv.kind <= 4) { - const auto dimension = srv.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : - srv.kind == 2 ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : - srv.kind == 4 ? D3D12_SRV_DIMENSION_TEXTURE1D : D3D12_SRV_DIMENSION_TEXTURE3D; + if (srv.kind >= 1 && srv.kind <= 5) { + const auto dimension = translated_view_dimension(srv.kind); // A texture: the title's descriptor memory carries the id of the view it created there. ViewRecord record{}; bool known = false; @@ -2058,7 +3136,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (srv.kind == 2) desc.Texture2DArray.ArraySize = 1; } } - if (indirect && (!texture || record.slot != 18 || texture == pass.target0)) { + const auto aliases_writable_target = [&](ID3D12Resource* tex) { + if (!tex) return false; + for (UINT t = 0; t < pass.target_count; ++t) + if (pass.bound_targets[t] == tex) return true; + return pass.bound_depth == tex && pass.depth_view_writable; + }; + if (indirect && (!texture || record.slot != 18 || aliases_writable_target(texture))) { indirect->set_refusal("translated draw requires a matching sampled texture distinct from the target", indirect_refusal_code::sampled_texture_mismatch); ReleaseSRWLockExclusive(&draw_lock); @@ -2111,7 +3195,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI device_of(the_device)->CreateShaderResourceView(texture, texture && record.desc_bytes < 40 ? nullptr : &desc, dest); continue; } - if (indirect) { + if (indirect || srv.expected_stride) { IndirectBufferView view{}; if (srv.source == 1 && indexed) { const auto& vb = pass.vb[0]; @@ -2125,8 +3209,16 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } else if (entry_ok) { view = indirect_table_buffer(self, words); } - if (!view.resource || view.resource == indirect->argument || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) { - indirect->set_refusal( + if (srv.expected_stride && (view.stride != srv.expected_stride || view.bytes > UINT_MAX || + view.bytes % srv.expected_stride)) { + if (indirect) indirect->set_refusal("indexed raw SRV record stride mismatch", + indirect_refusal_code::incomplete_table_buffer); + log("x2w-draw indexed raw SRV %u needs stride %u, got %u", i, srv.expected_stride, view.stride); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (!view.resource || (indirect && view.resource == indirect->argument) || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) { + if (indirect) indirect->set_refusal( srv.source == 1 ? "translated indexed draw requires a complete GPU-backed vertex stream" : "translated draw requires a complete GPU-backed table buffer range", srv.source == 1 ? indirect_refusal_code::incomplete_vertex_stream @@ -2173,6 +3265,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI strides[i] = (words[1] >> 16) & 0x3fff; bytes = static_cast<std::size_t>(strides[i] ? strides[i] : 1) * words[2]; } + const std::size_t view_bytes = bytes; // before the 16 MiB copy cap if (bytes > (16u << 20)) { bytes = 16u << 20; // Formatted loads past the copy would read zeros on the desktop; refuse the draw instead. @@ -2195,6 +3288,31 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_facts.bound = bound; count_null_binding(x2w_local::classify_null_binding(buffer_facts)); }; + // X2W_D3D12_TABLE_ALIAS=1: a table buffer whose whole range lies in a placed buffer that aliases title memory + // binds that alias, as vertex streams do, instead of a frame copy. The GPU then reads the bytes at execution, + // not as they were when the draw was recorded, and the range is not cut at 16 MiB. + static const bool table_alias = x2w_local::env_on("X2W_D3D12_TABLE_ALIAS"); + // The raw view covers whole DWORDs, so the alias must hold the rounded range. + const std::size_t raw_bytes = (view_bytes + 3) & ~std::size_t{3}; + if (table_alias && srv.source == 0 && !formatted.entry && address && view_bytes && raw_bytes <= (512u << 20)) { + const auto table_placed = placed_buffer_range(self->own().list_device, address, raw_bytes); + if (!table_placed.reject && table_placed.alias && table_placed.owner && + InterlockedCompareExchange(&table_placed.owner->own().refs, 0, 0)) { + const u64 view_offset = address - reinterpret_cast<u64>(table_placed.owner->own().title_memory); + if (view_offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0 && + retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(table_placed.alias))) { + // The same alias can also be this draw's live index buffer; it then keeps both read states. + const bool shared_index = table_placed.alias == live_index_resource; + index_read_as_table |= shared_index; + require_state(self, table_placed.alias, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | + (shared_index ? D3D12_RESOURCE_STATE_INDEX_BUFFER : D3D12_RESOURCE_STATE_COMMON)); + buffer_view(dest, table_placed.alias, view_offset, raw_bytes); + count_buffer(true); + continue; + } + } + } if (placed.reject || (placed.owner && !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0))) { buffer_view(dest, nullptr, 0, 0); count_buffer(false); @@ -2204,12 +3322,23 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // Preserve tight byte-sized streams. The desktop raw view is rounded // to a DWORD, so initialise its final padding without reading the guest. const auto padded = (bytes + 3) & ~std::size_t{3}; - auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset) : nullptr; + ID3D12Resource* chunk = nullptr; + const bool readable_range = readable_window(address, bytes) >= bytes; + auto* target = readable_range ? reserve_upload_ring(self, padded, &offset, &chunk) : nullptr; + if (readable_range && !target) { + // The guest memory is there; only the copy failed. A null binding would read zeros as if the title had bound nothing. + static LONG copy_refused; + if (first_calls(copy_refused, 6)) + log("x2w-draw %016llx srv %u: buffer copy failed (upload ring), draw refused", tr->key, i); + count_null_binding(x2w_local::NullCause::ring_full); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (target) { std::memcpy(target, reinterpret_cast<const void*>(address), bytes); std::memset(target + bytes, 0, padded - bytes); } - buffer_view(dest, target ? upload_ring : nullptr, offset, padded); + buffer_view(dest, target ? chunk : nullptr, offset, padded); count_buffer(target != nullptr); continue; } @@ -2218,12 +3347,18 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_view(dest, placed.alias, address - reinterpret_cast<u64>(placed.owner->own().title_memory), bytes); continue; } - bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset); + ID3D12Resource* chunk = nullptr; + const bool readable_range = address && bytes && readable_window(address, bytes) >= bytes; + bool have = readable_range && frame_copy(self, address, bytes, &offset, &chunk); + if (have) trace_compute_output_use(self, OutputUse::shader_guest_read, "graphics-guest-upload-copied", nullptr, + address, 0, bytes, tr->key); // Experiment (X2W_DRAW_NULL_IDENTITY=1): an empty buffer slot reads as repeated identity // matrices instead of zeros. The start-up screen's last pass takes its world matrix from a // slot the title leaves empty here; why is not known yet. static const bool identity_for_null = x2w_local::env_on("X2W_DRAW_NULL_IDENTITY"); if (!have && formatted.entry) { + // A readable range whose copy failed (upload ring full) is a ring_full refusal, not an unresolved buffer. + if (readable_range) count_null_binding(x2w_local::NullCause::ring_full); InterlockedIncrement(&formatted_draws_refused); static LONG refused; if (first_calls(refused, 6)) @@ -2231,14 +3366,24 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (readable_range && !have) { + // The guest memory is readable and only the frame copy failed (upload ring full): refuse the draw instead of + // binding null, which would read zeros as if the title had bound nothing. + static LONG copy_refused; + if (first_calls(copy_refused, 6)) + log("x2w-draw %016llx srv %u: buffer copy failed (upload ring), draw refused", tr->key, i); + count_null_binding(x2w_local::NullCause::ring_full); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (!have && identity_for_null) { static float identity[64]; for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; address = reinterpret_cast<u64>(identity); bytes = sizeof(identity); - have = frame_copy(address, bytes, &offset); + have = frame_copy(self, address, bytes, &offset, &chunk); } - buffer_view(dest, have ? upload_ring : nullptr, offset, bytes); + buffer_view(dest, have ? chunk : nullptr, offset, bytes); count_buffer(have); if (first_calls(tr->logged_bindings, 8)) { char head[3 * 48 + 1] = ""; @@ -2248,6 +3393,28 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI have ? "bound" : "NULL", head); } } + for (UINT j = 0; j < tr->uavs.size(); ++j) { + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + require_state(self, uav_bindings[j].resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (tr->uavs[j].raw) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + barrier.UAV.pResource = uav_bindings[j].resource; + list->ResourceBarrier(1, &barrier); + } + device_of(the_device)->CreateUnorderedAccessView(uav_bindings[j].resource, nullptr, &uav_bindings[j].view, dest); + static LONG shown; + if (first_calls(shown, 6)) { + if (uav_bindings[j].view.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY) + log("x2w-draw %016llx uav %u: resource %p format %d array [%u..%u) mip 0", tr->key, j, + static_cast<void*>(uav_bindings[j].resource), uav_bindings[j].view.Format, + uav_bindings[j].view.Texture2DArray.FirstArraySlice, + uav_bindings[j].view.Texture2DArray.FirstArraySlice + uav_bindings[j].view.Texture2DArray.ArraySize); + else + log("x2w-draw %016llx uav %u: resource %p format %d mip 0", tr->key, j, + static_cast<void*>(uav_bindings[j].resource), uav_bindings[j].view.Format); + } + } static LONG checks; if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated draw views", 0); std::uint32_t values[32] = {}; @@ -2289,6 +3456,10 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } list->SetPipelineState(pipeline); + if (fixed_stream) { + if (fixed_resource) require_state(self, fixed_resource, D3D12_RESOURCE_STATE_GENERIC_READ); + list->IASetVertexBuffers(0, 1, &fixed_view); + } // X2W_DEPTH_STATE: the reference of the decoded stencil test is list state in D3D12. It replaces the one a // preceding OMSetStencilRef set, for draws of this pipeline only when a depth view is bound. const bool scoped_stencil_ref = bound->depth_from_registers && bound->has_stencil_ref && @@ -2303,8 +3474,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.bound_sampler_heap = samplers; } list->SetGraphicsRoot32BitConstants(0, static_cast<UINT>(tr->uds.size()), values, 0); - if (n) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); - if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(n), samplers->GetGPUDescriptorHandleForHeapStart()); + if (views) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(views), samplers->GetGPUDescriptorHandleForHeapStart()); list->IASetPrimitiveTopology(pass.topology == 5 ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); bool drawn = false; if (indirect) { @@ -2321,20 +3492,29 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI drawn = true; } else if (indexed) { u64 offset = 0; - const u64 address = index_address; - const std::size_t bytes = index_total; - if (indices_ok && frame_copy(address, bytes, &offset)) { - const D3D12_INDEX_BUFFER_VIEW view{upload_ring->GetGPUVirtualAddress() + offset, static_cast<UINT>(bytes), - index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + ID3D12Resource* index_chunk = nullptr; + auto view = live_indices; + if (live_index_resource) { + if (live_index_resource != fixed_resource) + require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER | + (index_read_as_table ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + : D3D12_RESOURCE_STATE_COMMON)); + } else if (indices_ok && frame_copy(self, index_address, index_total, &offset, &index_chunk) && index_chunk) { + view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast<UINT>(index_total), + index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; + } + if (view.BufferLocation) { list->IASetIndexBuffer(&view); const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); - list->DrawIndexedInstanced(count, instances ? instances : 1, 0, 0, start_instance); + list->DrawIndexedInstanced(count, instances ? instances : 1, 0, fixed_stream ? base_vertex : 0, start_instance); red_producer_draw_after(self, red_samples); drawn = true; } } else { const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); - list->DrawInstanced(rect ? count / 3 * 6 : count, instances ? instances : 1, 0, start_instance); + list->DrawInstanced(rect && !geometry_rect ? count / 3 * 6 : count, instances ? instances : 1, + fixed_stream ? start : 0, start_instance); red_producer_draw_after(self, red_samples); drawn = true; } @@ -2359,6 +3539,20 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return draw_translated(self, indexed, count, instances, start, base_vertex, start_instance, nullptr); } +LONG missing_shader_fallback_draws; + +void draw_startup_direct(Wrapper* self, UINT count, UINT instances, UINT start, UINT start_instance) +{ + bool used_fallback = false; + const bool drawn = draw_translated(self, false, count, instances, start, 0, start_instance, nullptr, &used_fallback); + if (used_fallback) { + const LONG n = InterlockedIncrement(&missing_shader_fallback_draws); + if (n == 1) log("x2w-draw recorded first missing shader fallback"); + } else { + InterlockedIncrement(drawn ? &translated_draws : &untranslated_draws); + } +} + const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset, const IndirectIndexView& indices) { @@ -2381,34 +3575,52 @@ const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* sign } // List slot 32, SetDescriptorHeaps. Track the title's shader-visible sampler -// source while translated draws use their own physical descriptor heaps. +// source while translated draws use their own physical descriptor heaps, and the +// title memory of the view heap for a program that indexes the heap itself. void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heaps) { x2w_startup::SamplerSource source; - u64 view_heap = 0; + u64 sampler_wrapper = 0; + x2w_startup::ViewTable heap_records; + UINT heap_entries = 0; + x2w_startup::ViewHeapSelection view_heaps; + UINT bound_view_heaps = 0, visible_view_count = 0; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); for (UINT i = 0; i < count; ++i) { for (const HeapInfo& heap : heap_infos()) { if (heap.wrapper == reinterpret_cast<u64>(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && - heap.logical_count > heap.count) - view_heap = heap.wrapper; + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); if (heap.wrapper == reinterpret_cast<u64>(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + { + ++bound_view_heaps; + visible_view_count = heap.desktop_gpu ? heap.logical_count : 0; + heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, + heap.increment, heap.desktop_gpu); + if (heap_records.address) heap_entries = heap.logical_count; + } + if (heap.wrapper == reinterpret_cast<u64>(heaps[i]) && + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER && heap.desktop_gpu) { + sampler_wrapper = heap.wrapper; source = {static_cast<std::uintptr_t>(heap.title_sampler_cpu), heap.count}; + } } } ReleaseSRWLockShared(¬e_lock); } auto& pass = pass_of(self); - if (pass.source_view_heap != view_heap) - { + if (pass.source_view_heap != view_heaps.graphics) { for (auto& table : pass.view_tables) table = {}; - pass.compute_tables.clear(); } - pass.source_view_heap = view_heap; + pass.compute_tables.set_view_heap(view_heaps.compute); + pass.source_view_heap = view_heaps.graphics; pass.title_samplers = source; + pass.sampler_heap_wrapper = sampler_wrapper; + pass.title_view_heap = heap_records; + pass.mesh_heap_slots = bound_view_heaps == 1 && heap_records.address ? visible_view_count : 0; + pass.title_view_heap_entries = heap_entries; } // The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). @@ -2446,6 +3658,17 @@ void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) log("x2w-render compute descriptor table dropped: parameter %u (%u parameters are kept)", parameter, x2w_startup::ComputeTables::max_parameters); } +// Keeps the words of a root constants call; a call outside the 16 x 8 words kept is logged and cut or dropped. +static void store_root_constants(x2w_root_constants::Store& store, const char* kind, UINT parameter, UINT count, + const std::uint32_t* data, UINT offset) +{ + if (!count || !x2w_local::readable(data, std::size_t{count} * 4)) return; + const auto result = store.set(parameter, count, data, offset); + static LONG refused; + if (result != x2w_root_constants::Result::stored && first_calls(refused, 4)) + log("x2w-render %s root constants %s: parameter %u, offset %u, count %u (16 parameters of 8 words are kept)", kind, + result == x2w_root_constants::Result::dropped ? "dropped" : "truncated", parameter, offset, count); +} // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) { @@ -2461,6 +3684,16 @@ void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, co count <= 8 - offset && offset + count <= (*pass.root)[parameter].constants_count) pass.constant_words_bound[parameter] |= static_cast<unsigned char>(((1u << count) - 1) << offset); } +// List slot 37 (desktop 33 + 4), SetComputeRoot32BitConstant(parameter, value, offset). +void __stdcall list_compute_constant(Wrapper* self, UINT parameter, UINT value, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, 1, &value, offset); +} +// List slot 39 (desktop 35 + 4), SetComputeRoot32BitConstants(parameter, count, data, offset). +void __stdcall list_compute_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) +{ + store_root_constants(pass_of(self).compute_constants, "compute", parameter, count, data, offset); +} // List slot 47 (desktop 43 + 4), IASetIndexBuffer(view). void __stdcall list_index_buffer(Wrapper* self, const D3D12_INDEX_BUFFER_VIEW* view) { diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 673084c388..80af4ca834 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -115,9 +115,11 @@ bool desktop_address_view_supported(Wrapper* device, const D3D12_RESOURCE_DESC& D3D12_FEATURE_DATA_FORMAT_SUPPORT storage{r.Format}; if (r.Format == v.Format) storage = view; else if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &storage, sizeof(storage)))) return false; - const UINT req = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? D3D12_FORMAT_SUPPORT1_TEXTURE3D - : D3D12_FORMAT_SUPPORT1_TEXTURE2D; + const UINT req = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? D3D12_FORMAT_SUPPORT1_TEXTURE3D + : r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ? D3D12_FORMAT_SUPPORT1_TEXTURE1D + : D3D12_FORMAT_SUPPORT1_TEXTURE2D; return (storage.Support1 & req) && + (v.ViewDimension != D3D12_SRV_DIMENSION_TEXTURECUBE || (storage.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURECUBE)) && (r.MipLevels == 1 || (storage.Support1 & D3D12_FORMAT_SUPPORT1_MIP)); } @@ -189,7 +191,8 @@ bool address_resource_overlap(u64 address, u64 span) bool found = false; AcquireSRWLockShared(¬e_lock); resource_address_index().for_each_reaching(address, span, [&](const Wrapper* wrapper) { - if (wrapper->own().tiled_address_srv || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0) + if (wrapper->own().tiled_address_srv || wrapper->own().unplaced_srv_backing || + InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0) return false; const auto& info = resource_infos().at(wrapper); const u64 bytes = info.bytes ? info.bytes @@ -238,7 +241,7 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { const auto& info = resource_infos().at(wrapper); if (info.placement != Placement::none || - info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || + wrapper->own().exact_copy || info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0) return false; @@ -258,13 +261,15 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) } // Backing for unplaced buffer memory SRVs: 64 KiB page-aligned placed resource on an existing heap -// (OpenExistingHeapFromAddress zero-copy aliasing on hardware) or committed UPLOAD buffer (fallback). +// (OpenExistingHeapFromAddress zero-copy aliasing on hardware, allocations up to 256 MiB) or committed UPLOAD +// buffer (fallback). struct UnplacedBufferEntry { Wrapper* device = nullptr; void* allocation_base = nullptr; u64 page_start = 0; u64 page_span = 0; bool is_upload = false; + bool exact = false; // starts at the view address (a structured view whose stride does not divide the page offset) x2w_startup::ComPtr<ID3D12Resource> resource; Wrapper* wrapper = nullptr; }; @@ -292,7 +297,8 @@ void clear_unplaced_buffers(Wrapper* device) } } -Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc) +Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc, + u64 elem_bytes, bool raw) { if (address_resource_overlap(address, span_bytes)) return nullptr; u64 page_start = 0, page_span = 0; @@ -307,12 +313,21 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co const auto nearby = placed_buffer_range(device, page_start, page_span, true); if (nearby.reject || nearby.owner) return nullptr; + // A buffer view addresses whole elements from its base. When the base is the 64 KiB page start and the view address is not + // a multiple of the element size past it, no FirstElement can name the address: back the view with an upload copy that + // starts at the address itself (checked above to lie inside memory the title owns). + const bool exact = x2w_startup::unplaced_view_needs_exact_start(address, page_start, elem_bytes, raw); + if (exact) { + page_start = address; + page_span = span_bytes; + } + auto* desktop = device_of(device); if (!desktop) return nullptr; std::lock_guard lock(unplaced_buffer_mutex); for (auto& entry : unplaced_buffers) { - if (entry.device == device && entry.allocation_base == memory.base && + if (entry.device == device && entry.allocation_base == memory.base && entry.exact == exact && x2w_startup::unplaced_buffer_covers(entry.page_start, entry.page_span, address, span_bytes)) { x2w_startup::PlacedBufferRange verify{}; if (!x2w_startup::measure_placed_buffer(reinterpret_cast<void*>(entry.page_start), entry.page_span, verify) || @@ -341,7 +356,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co SUCCEEDED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &existing_support, sizeof(existing_support))) && existing_support.Supported; - if (existing_heaps_supported && memory.type == MEM_PRIVATE) { + if (existing_heaps_supported && memory.type == MEM_PRIVATE && !exact) { std::lock_guard placed_lock(placed_mutex); for (const auto& [known, h] : existing_heaps) { if (known == memory.base) { @@ -350,7 +365,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co break; } } - if (!heap) { + if (!heap && x2w_startup::unplaced_existing_heap_allowed(x2w_startup::allocation_bytes(memory.base))) { ID3D12Device3* device3 = nullptr; if (SUCCEEDED(desktop->QueryInterface(IID_PPV_ARGS(&device3)))) { if (SUCCEEDED(device3->OpenExistingHeapFromAddress(memory.base, IID_PPV_ARGS(&heap)))) { @@ -411,6 +426,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co if (!native_resource) return nullptr; Wrapper* w = wrap(native_resource.Get(), resource_kind); + if (!w) return nullptr; w->own().title_memory = reinterpret_cast<void*>(page_start); D3D12_RESOURCE_DESC rdesc{}; rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -423,6 +439,8 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co rdesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; rdesc.Flags = is_upload ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + w->own().unplaced_srv_backing = true; + w->own().exact_copy = exact; note_resource(w, &rdesc, page_span); if (!is_upload) { w->own().budget = x2w_budget::resource(desktop, native_resource.Get(), x2w_budget::placed); @@ -432,7 +450,7 @@ Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, co w->own().budget = x2w_budget::committed(desktop, native_resource.Get(), D3D12_HEAP_TYPE_UPLOAD); } - unplaced_buffers.push_back(UnplacedBufferEntry{device, memory.base, page_start, page_span, is_upload, native_resource, w}); + unplaced_buffers.push_back(UnplacedBufferEntry{device, memory.base, page_start, page_span, is_upload, exact, native_resource, w}); return w; } @@ -511,21 +529,33 @@ u64 address_texture_bytes(Wrapper* device, const D3D12_RESOURCE_DESC& desc) // copy records a tiled write; the 0x109 BC chains, which XG writes in their layout, keep their own // path and never come through here); // - the layout runs past the size the XG stand-in reports for the description (the desktop copyable -// footprints of a slice rounded up to 64 KiB, times the slices), which the title may not own. +// footprints of a slice rounded up to 64 KiB, times the slices), which the title may not own. A volume +// has one slice: its footprints already span every depth layer. const char* console_address_hold(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc) { if (latest_texture_write_is_rows(address)) return "console_layout_xg_rows"; const x2w_startup::SliceFootprints plan(device_of(device), sanitized(desc), desc.MipLevels); if (plan.size == UINT64_MAX || !plan.size) return "console_layout_without_footprints"; - const u64 reported = ((plan.size + 0xFFFF) & ~u64{0xFFFF}) * desc.DepthOrArraySize; + const u64 slices = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : desc.DepthOrArraySize; + const u64 reported = ((plan.size + 0xFFFF) & ~u64{0xFFFF}) * slices; return x2w_startup::gfx10::Layout(desc).bytes() > reported ? "console_layout_beyond_xg_size" : nullptr; } +// Why publish_tiled_texture (or the lookup of a live resource) gave no texture: the causes the census keeps apart +// (x2w_startup::texture_unavailable_cause). +const char* texture_unavailable_reason(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc, bool published) +{ + const u64 bytes = published ? address_texture_bytes(device, desc) : 0; + return x2w_startup::texture_unavailable_cause(published, bytes, [&] { + return x2w_local::readable(reinterpret_cast<const void*>(address), bytes); + }); +} + Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc) { const auto bytes = address_texture_bytes(device, desc); // The transient upload ring accepts individual copies up to 64 MiB. - if (bytes > (64ull << 20) || !x2w_local::readable(reinterpret_cast<const void*>(address), bytes)) return nullptr; + if (bytes > x2w_startup::max_published_texture_bytes || !x2w_local::readable(reinterpret_cast<const void*>(address), bytes)) return nullptr; std::lock_guard lock(tiled_srv_mutex); const auto [first, last] = tiled_srv_addresses.equal_range(address); for (auto it = first; it != last; ++it) { @@ -538,6 +568,7 @@ Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURC } } Wrapper* resource = wrap(nullptr, resource_kind); + if (!resource) return nullptr; resource->own().title_memory = reinterpret_cast<void*>(address); resource->own().tiled_address_srv = true; note_resource(resource, &desc, bytes); @@ -685,8 +716,8 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou view_slot<18, 2>(self, reinterpret_cast<u64>(texture), reinterpret_cast<u64>(&input->view), destination, 0); note_memory_srv_write(resource, input, destination); } else { - refuse_memory_srv(refused, "unavailable texture at the supplied base and layout", "texture_unavailable", resource, input, - destination); + refuse_memory_srv(refused, "unavailable texture at the supplied base and layout", + texture_unavailable_reason(self, input->address, *resource, true), resource, input, destination); } return; } @@ -697,15 +728,21 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; + D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; + const auto resolve = [&](Wrapper* candidate) { + const auto* info = candidate ? resource_info(candidate) : nullptr; + return info && x2w_startup::resolve_buffer_srv_desc( + reinterpret_cast<u64>(candidate->own().title_memory), info->console.Width, + input->address, input->view, adjusted); + }; Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); - if (!buffer) { - buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource); + bool resolved = resolve(buffer); + if (!buffer || (!resolved && buffer->own().unplaced_srv_backing)) { + buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource, elem_bytes, + input->view.Buffer.Flags == D3D12_BUFFER_SRV_FLAG_RAW); + resolved = resolve(buffer); } - const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; - D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; - if (!buffer || !info || - !x2w_startup::resolve_buffer_srv_desc(reinterpret_cast<u64>(buffer->own().title_memory), - info->console.Width, input->address, input->view, adjusted)) { + if (!resolved) { refuse_memory_srv(refused, "unavailable buffer at the supplied address", "buffer_unavailable", resource, input, destination); return; @@ -746,10 +783,14 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou outcome = "published console layout"; } } - if (!texture) outcome = held ? held : "texture_unavailable (no resource there, or texels not readable or over 64 MiB)"; + // A publication was attempted for a BC / console-layout view; any other view only looks up a live resource. + const char* unavailable = texture || held ? nullptr + : texture_unavailable_reason(self, input->address, *resource, + tiled_bc_srv(*resource) || x2w_startup::bc64::supports(*resource) || console_layout_srv(*resource)); + if (!texture) outcome = held ? held : unavailable; log_address_kind(outcome, *resource, input->view, input->address); if (!texture) { - refuse_memory_srv(refused, "unavailable texture at the supplied base and layout", held ? held : "texture_unavailable", + refuse_memory_srv(refused, "unavailable texture at the supplied base and layout", held ? held : unavailable, resource, input, destination); return; } diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4b..40ff3f6a5f 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -2,25 +2,25 @@ // Included inside d3d12_xs_device.cpp's anonymous namespace, before queue_present. // // A flip-model swap chain on the title window, created on the queue the title presents with; each -// present draws the presented surface into the back buffer with a full-window triangle (the surface -// is usually larger than the window) and flips. Diagnostics go to the window title, because GDI -// drawing does not mix with a flip-model swap chain. +// present draws its planes into the back buffer, bottom to top, with the plane compositor +// (plane_compositor.h: one full-window triangle a plane; a surface is usually larger than the +// window), and flips. Plane 0 alone by default; every plane with X2W_PRESENT_COMPOSITE=1. Diagnostics go to the window title, because GDI drawing does not mix with a +// flip-model swap chain. struct WindowPresenter { IDXGISwapChain3* chain = nullptr; ID3D12DescriptorHeap* targets = nullptr; - ID3D12DescriptorHeap* textures = nullptr; ID3D12Resource* buffers[2] = {}; ID3D12CommandAllocator* allocator = nullptr; ID3D12GraphicsCommandList* list = nullptr; - ID3D12RootSignature* root = nullptr; - ID3D12PipelineState* pipeline = nullptr; + x2w_startup::PlaneCompositor compositor; // shaders, pipelines and plane views ID3D12Fence* fence = nullptr; HANDLE reached = nullptr; UINT64 fence_value = 0; UINT width = 0, height = 0; bool failed = false; }; +constexpr UINT window_planes = 4; WindowPresenter window_presenter; LONG window_presents; @@ -97,7 +97,7 @@ HWND output_window() return output_handle; } -bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) +bool create_window_presenter(ID3D12CommandQueue* queue, HWND window, UINT plane_capacity) { WindowPresenter& p = window_presenter; ID3D12Device* device = device_of(the_device); @@ -124,9 +124,7 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (chain1) chain1->Release(); if (factory) factory->Release(); const D3D12_DESCRIPTOR_HEAP_DESC target_heap{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&target_heap, IID_PPV_ARGS(&p.targets)); - if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&texture_heap, IID_PPV_ARGS(&p.textures)); const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); for (UINT i = 0; SUCCEEDED(hr) && i < 2; ++i) { hr = p.chain->GetBuffer(i, IID_PPV_ARGS(&p.buffers[i])); @@ -138,100 +136,52 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (SUCCEEDED(hr)) hr = p.list->Close(); if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&p.fence)); p.reached = CreateEventW(nullptr, FALSE, FALSE, nullptr); - static const char source[] = - "Texture2D<float4> surface : register(t0); SamplerState smooth : register(s0);\n" - "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" - "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" - "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n"; - ID3DBlob* vs = nullptr; - ID3DBlob* ps = nullptr; - ID3DBlob* blob = nullptr; - if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); - if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); - if (SUCCEEDED(hr)) { - const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_ROOT_PARAMETER parameter{}; - parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameter.DescriptorTable = {1, &range}; - parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - D3D12_STATIC_SAMPLER_DESC sampler{}; - sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; - sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - sampler.MaxLOD = D3D12_FLOAT32_MAX; - sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); - if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&p.root)); - } - if (SUCCEEDED(hr)) { - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = p.root; - desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; - desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - desc.SampleMask = ~0u; - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = 1; - desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.SampleDesc.Count = 1; - hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&p.pipeline)); - } - if (vs) vs->Release(); - if (ps) ps->Release(); - if (blob) blob->Release(); + if (SUCCEEDED(hr)) hr = p.compositor.create(device, DXGI_FORMAT_R8G8B8A8_UNORM, plane_capacity); log("x2w-present window swap chain %ux%u -> 0x%08lx", p.width, p.height, static_cast<unsigned long>(hr)); check_device("window presenter", 0); return SUCCEEDED(hr); } -// Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. -bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) +// Whether the window presenter can draw `surface` (present_view_format.h); logs the first refusals. +bool presentable_surface(ID3D12Resource* surface) +{ + if (!surface) return false; + const D3D12_RESOURCE_DESC desc = surface->GetDesc(); + if (x2w_startup::present_surface_supported(desc)) return true; + static LONG refused; + if (first_calls(refused, 4)) + log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", + desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); + return false; +} + +// Composites the steps of a present (present_planes.h composite_steps) into the window and flips. +// plane_surfaces[step.plane] is that plane's surface (resting in COMMON and presentable), or null to +// leave it out. Returns false if not shown. +bool present_to_window(ID3D12CommandQueue* queue, const x2w_startup::PlaneStep* steps, unsigned count, + ID3D12Resource* const* plane_surfaces, UINT plane_capacity) { X2W_ZONE("window present (blit + fence wait)"); WindowPresenter& p = window_presenter; - if (p.failed || !queue || !surface) return false; - const D3D12_RESOURCE_DESC desc = surface->GetDesc(); - if (!x2w_startup::present_surface_supported(desc)) { - static LONG refused; - if (first_calls(refused, 4)) - log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", - desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); - return false; - } + if (p.failed || !queue || !steps || !count || !plane_surfaces) return false; HWND window = output_window(); if (!window) return false; - if (!p.chain && !create_window_presenter(queue, window)) { + if (!p.chain && !create_window_presenter(queue, window, plane_capacity)) { p.failed = true; return false; } ID3D12Device* device = device_of(the_device); - const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); - D3D12_SHADER_RESOURCE_VIEW_DESC view{}; - view.Format = view_format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(surface, &view, p.textures->GetCPUDescriptorHandleForHeapStart()); const UINT index = p.chain->GetCurrentBackBufferIndex(); const D3D12_CPU_DESCRIPTOR_HANDLE target{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{index} * device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)}; - if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.pipeline))) return false; - transition(p.list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.compositor.initial_pipeline()))) return false; transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); - const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(p.width), static_cast<float>(p.height), 0, 1}; - const D3D12_RECT scissor{0, 0, static_cast<LONG>(p.width), static_cast<LONG>(p.height)}; - p.list->SetGraphicsRootSignature(p.root); - p.list->SetDescriptorHeaps(1, &p.textures); - p.list->SetGraphicsRootDescriptorTable(0, p.textures->GetGPUDescriptorHandleForHeapStart()); - p.list->RSSetViewports(1, &viewport); - p.list->RSSetScissorRects(1, &scissor); - p.list->OMSetRenderTargets(1, &target, FALSE, nullptr); - p.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - p.list->DrawInstanced(3, 1, 0, 0); + const UINT drawn = p.compositor.record(device, p.list, target, p.width, p.height, steps, count, plane_surfaces); transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); - transition(p.list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!drawn) { + p.list->Close(); + return false; + } if (FAILED(p.list->Close())) { p.failed = true; return false; diff --git a/src/startup_stubs/d3d12_teardown.h b/src/startup_stubs/d3d12_teardown.h index 278f27580b..31bbee9900 100644 --- a/src/startup_stubs/d3d12_teardown.h +++ b/src/startup_stubs/d3d12_teardown.h @@ -1,8 +1,10 @@ // Lifetime boundary of the desktop D3D12 objects the stand-in keeps in function-local statics: -// the indexed-validation pipeline (startup_stubs/d3d12_draw.inl) and the rectangle-list argument -// converter (startup_stubs/rect_indirect_args.h). #2572. +// the indexed-validation pipeline (startup_stubs/d3d12_draw.inl), the rectangle-list argument +// converter (startup_stubs/rect_indirect_args.h), the placed page aliases of the translated +// indirect address route (startup_stubs/d3d12_xs_device.cpp) and the draw-dump readbacks +// (startup_stubs/draw_dump_tracking.h). #2572. // -// Both caches hold their objects for as long as this module is loaded -- a conversion or a validation +// These caches hold their objects for as long as this module is loaded -- a conversion or a validation // may still be queued when the call that built the entry returns -- so they are destroyed during this // module's CRT teardown. That teardown runs at two different moments: // @@ -23,10 +25,65 @@ // caches compiled into another module (the test executables include rect_indirect_args.h) keep // releasing normally, and only the DLL that owns the DllMain can silence its own teardown. Being a // zero-initialized bool, it needs no dynamic initialization and no destruction order. +// +// The accounting below is what makes that boundary observable. startup_teardown_unload loads this +// module, warms one cache, and has to show both paths: that the cache releases what it owns when the +// module is unloaded, and that it detaches instead of releasing when the process exits. The two +// variables are read when a cache is destroyed and absent from an ordinary run: +// +// X2W_TEARDOWN_REPORT=1 the cache prints one line on stderr as it is destroyed: +// x2w-teardown <cache> detached=<n> released=<n> +// where n counts the owned references (objects), not the entries. The +// line is written with WriteFile straight to the stderr handle: these +// destructors run during this module's CRT teardown, so a stdio buffer +// would never be flushed. No file is written and no buffer is deferred. +// X2W_TEARDOWN_NO_GUARD=<c> disables the detach of cache <c> (pages, readbacks, or all): that +// cache then releases normally during process exit, which is the crash +// path this boundary exists for. Absent, every guard behaves as it did. +// This is the negative control startup_teardown_unload runs against +// itself: with the variable set, its termination check must fail. +// +// Neither read is cached in a static: a function-local static here would be initialized for the first +// time inside the destructor, during teardown, after the atexit table has already run. #pragma once +#include <windows.h> + +#include <cstdio> +#include <cstring> + namespace x2w_startup { inline bool d3d12_process_terminating = false; +// True when the caller asked the named cache to release instead of detach during process exit. +inline bool teardown_guard_disabled(const char* cache) noexcept +{ + const DWORD saved = GetLastError(); + char value[64]{}; + const DWORD length = GetEnvironmentVariableA("X2W_TEARDOWN_NO_GUARD", value, sizeof(value)); + SetLastError(saved); + if (!length || length >= sizeof(value)) return false; + return std::strcmp(value, "all") == 0 || std::strcmp(value, cache) == 0; +} + +// One stable line per destroyed cache, on stderr, only when X2W_TEARDOWN_REPORT is set. +inline void teardown_report(const char* cache, unsigned detached, unsigned released) noexcept +{ + const DWORD saved = GetLastError(); + char on[2]{}; + const bool wanted = GetEnvironmentVariableA("X2W_TEARDOWN_REPORT", on, sizeof(on)) != 0; + if (wanted) { + char line[128]; + const int length = std::snprintf(line, sizeof(line), "x2w-teardown %s detached=%u released=%u\r\n", cache, + detached, released); + if (length > 0) { + DWORD written = 0; + const int bytes = length < static_cast<int>(sizeof(line)) ? length : static_cast<int>(sizeof(line)) - 1; + WriteFile(GetStdHandle(STD_ERROR_HANDLE), line, static_cast<DWORD>(bytes), &written, nullptr); + } + } + SetLastError(saved); +} + } // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f92272d094..56dbe26c48 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -15,25 +15,34 @@ #include "startup_stubs/trap.h" #include "x2w_build_rev.h" #include "xmem_page_batch.h" +#include "startup_stubs/commit_state.h" #include "startup_stubs/local_log.h" #include "startup_stubs/logical_view_table.h" +#include "startup_stubs/manifest_retry.h" #include "startup_stubs/list_compute_root.h" #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" +#include "startup_stubs/mesh57_profile.h" #include "startup_stubs/draw_dump_tracking.h" +#include "startup_stubs/present_readback_state.h" +#include "startup_stubs/pixel_history.h" #include "startup_stubs/translated_sampler_bindings.h" #include "startup_stubs/export_write_mask.h" +#include "startup_stubs/pso_recipe.h" #include "startup_stubs/depth_state_apply.h" #include "startup_stubs/d16_image_format.h" #include "startup_stubs/formatted_buffer.h" #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" +#include "startup_stubs/list_dispatch.h" +#include "startup_stubs/compute_builder_gate.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" #include "startup_stubs/address_texture.h" #include "startup_stubs/list_upload_pages.h" #include "startup_stubs/resource_budget.h" +#include "startup_stubs/upload_reservation.h" #include <optional> #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" @@ -48,13 +57,17 @@ #include "startup_stubs/buffer_format_word3.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" +#include "startup_stubs/view_dimension.h" #include "startup_stubs/list_copy.h" #include "startup_stubs/d3d12_teardown.h" #include "startup_stubs/rect_indirect_args.h" +#include "startup_stubs/split_indirect_dispatch.h" #include "startup_stubs/profile_zone.h" #include "startup_stubs/slice_footprints.h" #include "startup_stubs/present_signature_sampler.h" +#include "startup_stubs/present_planes.h" +#include "startup_stubs/plane_compositor.h" #include <d3d12.h> #include "command_list_slot_names.h" @@ -63,12 +76,25 @@ #include "descriptor_heap_type.h" #include "small_texture_4k.h" #include "null_binding_cause.h" +#include "root_constant_store.h" #include "null_texture_view.h" #include "packed_target_format.h" #include "present_view_format.h" #include "state_block_blend.h" #include "title_heap_memory.h" #include "startup_stubs/xmem_section_buffer.h" +#include "native_buffer_store_view.h" +#include "native_compute_output.h" +#ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl) +#include "gfx1013_compute_native.h" +#include "gfx1013_pixel.h" +#include "mesh_shader_pipeline.h" +#include <fstream> +#include "native_buffer_store_view.h" +#include "shader_dxil_compiler.h" +#include "direct_compute_cache.h" +#include "frozen_compute_requests.h" +#endif #include <d3d12sdklayers.h> #include <d3d12shader.h> #include <d3dcompiler.h> @@ -140,6 +166,7 @@ struct IndirectGraphicsPipeline { bool cached_depth_writes{}; const std::vector<RootParameter>* guest_root_params{}; UINT cached_srv_root = UINT_MAX; + UINT constant_guest = UINT_MAX; // Single MS b0 mapped from this guest root under a deferred signature. }; // Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. @@ -163,25 +190,33 @@ struct alignas(16) WrapperOwn { bool list_open; // CommandList (render mode): recording between reset and close x2w_upload::Arena* list_uploads; // Current recording's allocations, owned by its desktop allocator. ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. + UploadChunkMask upload_chunks; // Ring and snapshot chunks referenced by this recording, including while closed. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. + bool unplaced_srv_backing; // Resource: synthetic backing for an address-only buffer SRV. + bool exact_copy; // Resource: synthetic backing that starts at the view address. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. bool retire_when_idle; // Resource: in the retire class (X2W_D3D12_RELEASE_RETIRED); cleared by any other use. Plain // accesses: a race needs the guest to use a resource across its own final Release. bool retire_hold_missed; // Resource: retire_hold could not record a use (no desktop object or no room), so the // drain must keep it for the process instead of dropping a list's desktop object. - bool retire_views_stuck; // Resource: X2W_D3D12_RELEASE_RETIRED_VIEWS could not clear every descriptor slot that - // names it, so it stays retained (and is not scanned again). std::uint8_t retire_never; // RetireNever of this resource (set only with X2W_D3D12_RELEASE_RETIRED) std::uint8_t retire_left; // RetireLeft: the first use that took it out of the class volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. bool retire_has_written_gen; // Whether written_textures()[title_memory].generation was snapshotted at Release. u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup. + volatile LONG64 output_trace_recording; bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline + bool builder_pipeline; // PipelineState: slot 62 created it for XboxBvhBuilder.dll (X2W_COMPUTE_BUILDER_GATE) + x2w_startup::BuilderGateState* compute_builder_gate; // Device: tracked builder pipelines, or null until needed u64 compute_trace_key; // Opt-in trace: selected slot 62 container hash const void* compute_trace_root; LONG compute_trace_dispatches; bool root_without_bindings; // RootSignature: decoded and has no parameters or static samplers + ID3D12RootSignature* pipeline_root; // PipelineState: desktop root signature its compute stream declared + u64 compute_request_key; // PipelineState: key of the slot 67 request it published, or 0 + const void* compute_request_root; // PipelineState: root signature wrapper named by that slot 67 description + bool root_srv_only; // RootSignature: decoded, no static samplers, every parameter a root SRV (those are forwarded) volatile LONG queue_wait_seen; // CommandQueue: publish later signals only after GPU completion. void* pass; // CommandList (render mode): recording state (Pass) Wrapper* list_device; // CommandList: wrapper that created this list. @@ -457,19 +492,41 @@ u64 unwrap(u64 value) return w ? reinterpret_cast<u64>(w->own().real) : value; } +volatile LONG wraps_to_fail; // fixture-only, set by x2w_d3d12_fail_wraps +constexpr u64 out_of_memory = static_cast<std::uint32_t>(E_OUTOFMEMORY); // for slots that return u64 + +// Returns nullptr when the wrapper cannot be allocated or registered (#2653). The caller still owns +// `real` then: it releases what it created and returns E_OUTOFMEMORY. Wrapper* wrap(IUnknown* real, Kind kind) { + for (LONG n = wraps_to_fail; n > 0; n = wraps_to_fail) + if (InterlockedCompareExchange(&wraps_to_fail, n - 1, n) == n) return nullptr; const std::size_t area = kind == list_kind ? 0x10000 : sizeof(Wrapper); auto* block = static_cast<unsigned char*>(_aligned_malloc(sizeof(WrapperOwn) + area, 16)); + if (!block) { + static LONG failed; + if (first_calls(failed, 4)) log("x2w-d3d12 wrap(%s): wrapper allocation failed -> E_OUTOFMEMORY", kind_names[kind]); + return nullptr; + } std::memset(block, 0, sizeof(WrapperOwn) + area); auto* w = reinterpret_cast<Wrapper*>(block + sizeof(WrapperOwn)); w->vtable = tables[kind]; w->own().real = real; w->own().refs = 1; w->own().kind = kind; + // The guest checks device byte +0x18 before using its inline descriptor + // writers. Request vtable calls so the shim records the descriptor. + static_assert(offsetof(Wrapper, console_fields) + 2 * sizeof(u64) == 0x18); + if (kind == device_kind) w->console_fields[2] = 1; if (kind == fence_kind && real) w->own().completed = static_cast<LONG64>(static_cast<ID3D12Fence*>(real)->GetCompletedValue()); AcquireSRWLockExclusive(®istry_lock); - registry().insert(w); + try { + registry().insert(w); + } catch (const std::bad_alloc&) { + ReleaseSRWLockExclusive(®istry_lock); + _aligned_free(block); + return nullptr; + } ReleaseSRWLockExclusive(®istry_lock); return w; } @@ -800,17 +857,22 @@ const D3D12_CLEAR_VALUE* packed_clear_value(const D3D12_CLEAR_VALUE* clear, DXGI return © } -bool release_retired_enabled() +bool legacy_retire_view_stats() { - static const bool on = x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); - return on; + static const bool requested = [] { + if (!x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED_VIEWS")) return false; + log("x2w-d3d12: X2W_D3D12_RELEASE_RETIRED_VIEWS no longer clears live descriptors; budget statistics only"); + return true; + }(); + return requested; } -// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (needs X2W_D3D12_RELEASE_RETIRED=1): a released class member that only tracked slot-18 -// descriptor slots keep alive is freed once every such slot has been replaced by a null descriptor. -bool release_retired_views_enabled() +bool release_retired_enabled() { - static const bool on = release_retired_enabled() && x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED_VIEWS"); + static const bool on = [] { + (void)legacy_retire_view_stats(); + return x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); + }(); return on; } @@ -872,6 +934,11 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) x2w_startup::mark_packed_stand_in(static_cast<ID3D12Resource*>(*out), requested_format); Wrapper* child = wrap(static_cast<IUnknown*>(*out), kind); + if (!child) { + static_cast<IUnknown*>(*out)->Release(); + *out = nullptr; + return out_of_memory; + } if constexpr (K == device_kind && N == 27) { if (kind == resource_kind && args[0]) retire_set_class(child, *reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(args[0]), @@ -985,6 +1052,8 @@ void retire_drop_heap_views(Wrapper* heap); void retire_note_title_release(Wrapper* w); void retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); +void release_list_recording(Wrapper* list); +void clear_draw_sampler_snapshot(Wrapper* self); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists); void drain_retired_resources(); @@ -1008,6 +1077,8 @@ ULONG __stdcall release(Wrapper* self) linear_buffers().retire(static_cast<ID3D12Resource*>(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { + release_list_recording(self); + clear_draw_sampler_snapshot(self); discard_mesh_lease_recording(static_cast<ID3D12CommandList*>(self->own().real)); retire_drop_recording(self); } @@ -1043,6 +1114,10 @@ HRESULT __stdcall device_create_command_queue(Wrapper* self, const D3D12_COMMAND desc->Priority, desc->Flags, desc->NodeMask, text, static_cast<unsigned long>(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + if (!*out) { + queue->Release(); + return E_OUTOFMEMORY; + } register_retire_queue(static_cast<Wrapper*>(*out)); return S_OK; } @@ -1067,6 +1142,10 @@ HRESULT __stdcall device_create_command_queue_x(Wrapper* self, const D3D12_COMMA desc->Type, desc->Priority, desc->Flags, desc->NodeMask, text, static_cast<unsigned long>(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + if (!*out) { + queue->Release(); + return E_OUTOFMEMORY; + } register_retire_queue(static_cast<Wrapper*>(*out)); return S_OK; } @@ -1163,7 +1242,7 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND } } *output = wrap(nullptr, command_signature_kind); - return S_OK; + return *output ? u64{S_OK} : out_of_memory; } const u64 result = create_slot<device_kind, 41, 2>(self, reinterpret_cast<u64>(desc), root, iid, out, 0, 0, 0, 0); if (SUCCEEDED(static_cast<HRESULT>(result)) && out && desc && root && desc->NumArgumentDescs > 1) { @@ -1216,7 +1295,7 @@ u64 __stdcall device_create_command_signature(Wrapper* self, const D3D12_COMMAND for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { if (static_cast<UINT>(desc->pArgumentDescs[i].Type) > D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH) { *output = wrap(nullptr, command_signature_kind); - return S_OK; + return *output ? u64{S_OK} : out_of_memory; } } } @@ -1311,7 +1390,6 @@ void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); void reset_list_dynamic_state(Wrapper* self); void discard_list_gpu_writes(Wrapper* self); void commit_list_gpu_writes(Wrapper* self); -void discard_draw_sampler_heaps(ID3D12CommandList* list); void discard_address_uploads(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); @@ -1399,6 +1477,14 @@ struct DesktopAllocator { // Rectangle-list argument scratch of the recordings on this allocator. Retained with the recording, so until every // queue that ran it has passed its fence (the allocator is reused only when idle). std::vector<Microsoft::WRL::ComPtr<ID3D12Resource>> scratches; + // Immutable raw SRV table slices live until the allocator's last queue fence retires. + std::vector<x2w_startup::ComPtr<ID3D12DescriptorHeap>> mesh_view_pages; + UINT mesh_view_cursor = 0; + UINT mesh_heap_index = UINT_MAX; + ID3D12Resource* mesh_heap_buffer = nullptr; // Held in scratches until allocator retirement. + UINT64 mesh_heap_begin = 0, mesh_heap_size = 0; + // Translated draws keep their immutable sampler tables for every submission of the recording. + std::vector<x2w_startup::ComPtr<ID3D12DescriptorHeap>> sampler_snapshots; }; struct TitleAllocator { std::vector<DesktopAllocator*> pool; @@ -1408,9 +1494,27 @@ struct TitleAllocator { SRWLOCK allocator_lock = SRWLOCK_INIT; std::unordered_map<Wrapper*, TitleAllocator> title_allocators; std::unordered_map<Wrapper*, DesktopAllocator*> list_recordings; // list -> allocator holding its recording -std::unordered_map<ID3D12CommandQueue*, std::pair<ID3D12Fence*, UINT64>> queue_submits; +std::unordered_map<ID3D12CommandQueue*, UploadQueue<ID3D12Fence>> queue_submits; +std::vector<UploadRingChunk> upload_chunks; // allocator_lock also protects recording holds and queue fence values +std::vector<UploadRingChunk> snapshot_chunks; // the title input snapshot pool: same rules, its own chunks and budget +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (allocator_lock): chunks each closed list released at a fenced submit, until its Reset. +std::unordered_map<Wrapper*, ReleasedUploadChunks> released_upload_chunks; +LONG upload_resubmits_refused; // closed lists submitted again after a released chunk was reused; not executed + LONG allocator_swaps, allocator_creates; +void release_list_recording(Wrapper* list) +{ + AcquireSRWLockExclusive(&allocator_lock); + if (const auto found = list_recordings.find(list); found != list_recordings.end()) { + --found->second->lists; + list_recordings.erase(found); + } + discard_upload_chunks(list->own().upload_chunks, upload_chunks.data(), snapshot_chunks.data()); + released_upload_chunks.erase(list); + ReleaseSRWLockExclusive(&allocator_lock); +} + // allocator_lock held. TitleAllocator& title_allocator(Wrapper* allocator) { @@ -1426,33 +1530,51 @@ TitleAllocator& title_allocator(Wrapper* allocator) bool allocator_idle(const DesktopAllocator* allocator) { if (allocator->lists || allocator->untracked) return false; - for (const auto& submit : allocator->submits) - if (submit.first->GetCompletedValue() < submit.second) return false; + for (const auto& submit : allocator->submits) { + const UINT64 completed = submit.first->GetCompletedValue(); + if (completed == UINT64_MAX || completed < submit.second) return false; + } return true; } // List slot 148 (Xbox order), allocate CPU-writable upload memory for this recording. void* __stdcall list_allocate_upload(Wrapper* self, UINT64 bytes, UINT64 alignment) { - if (!bytes || !alignment || (alignment & (alignment - 1)) || - bytes > UINT64_MAX - (std::max)(alignment, UINT64{16})) return nullptr; x2w_upload::Allocation allocation{}; + x2w_upload::UploadFailure failure{}; AcquireSRWLockExclusive(&allocator_lock); auto& state = self->own(); const auto found = list_recordings.find(self); - if (state.list_open && state.list_device && found != list_recordings.end() && found->second) { + const bool open = state.list_open, close_failed = state.list_close_failed; + const bool has_device = state.list_device != nullptr; + const bool recording = found != list_recordings.end() && found->second; + if (!bytes || !alignment || (alignment & (alignment - 1)) || + bytes > UINT64_MAX - (std::max)(alignment, UINT64{16})) { + failure = {"invalid request", E_INVALIDARG}; + } else if (!open || !has_device || !recording) { + failure = {!open ? "closed list" : !has_device ? "missing device" : "missing recording", E_UNEXPECTED}; + } else { try { if (!state.list_uploads) { auto arena = std::make_unique<x2w_upload::Arena>(); found->second->uploads.push_back(std::move(arena)); state.list_uploads = found->second->uploads.back().get(); } - allocation = state.list_uploads->allocate(device_of(state.list_device), bytes, alignment); + allocation = state.list_uploads->allocate(device_of(state.list_device), bytes, alignment, &failure); } catch (const std::bad_alloc&) { - // Refuse the allocation without invalidating any range already recorded. + failure = {"CPU allocation", E_OUTOFMEMORY}; } } ReleaseSRWLockExclusive(&allocator_lock); + if (!allocation.cpu) { + static LONG invalid_failures, state_failures, page_failures, cpu_failures; + auto& failures = failure.requested_page ? page_failures : failure.hr == E_INVALIDARG ? invalid_failures : + failure.hr == E_OUTOFMEMORY ? cpu_failures : state_failures; + if (first_calls(failures, 12)) + log("x2w-render slot148 list=%p stage=%s hr=0x%08lx bytes=%llu alignment=%llu pageBytes=%llu open=%d closeFailed=%d device=%d recording=%d", + static_cast<void*>(self), failure.stage, static_cast<unsigned long>(failure.hr), bytes, alignment, + failure.requested_page, open, close_failed, has_device, recording); + } return reinterpret_cast<void*>(allocation.cpu); } @@ -1482,6 +1604,54 @@ ID3D12Resource* recording_rect_scratch(Wrapper* self) return scratch; } +// Keeps `resource` with this recording's desktop allocator, like the rectangle-list scratch above. False if the list +// is not recording (the caller must not use the resource then). +bool retain_with_recording(Wrapper* self, x2w_startup::ComPtr<ID3D12Resource> resource) +{ + bool retained = false; + AcquireSRWLockExclusive(&allocator_lock); + const auto& state = self->own(); + const auto found = list_recordings.find(self); + if (state.list_open && found != list_recordings.end() && found->second) { + try { + found->second->scratches.push_back(std::move(resource)); + retained = true; + } catch (const std::bad_alloc&) { + } + } + ReleaseSRWLockExclusive(&allocator_lock); + return retained; +} + +// Fixture query includes every backing allocator, including old recordings still pending on a queue. +extern "C" __declspec(dllexport) UINT x2w_d3d12_allocator_sampler_snapshots(void* guest_allocator) +{ + Wrapper* allocator = as_wrapper(guest_allocator); + if (!allocator || allocator->own().kind != allocator_kind) return 0; + AcquireSRWLockShared(&allocator_lock); + UINT held = 0; + const auto found = title_allocators.find(allocator); + if (found != title_allocators.end()) + for (const auto* backing : found->second.pool) + held += static_cast<UINT>(backing->sampler_snapshots.size()); + ReleaseSRWLockShared(&allocator_lock); + return held; +} + +// Fixture query: how many scratch buffers the desktop allocator of this list's latest recording still holds (the +// rectangle-list scratch and the split indirect Dispatch records). They are released only when that allocator is +// reset after every queue that ran its recordings has passed its fence (allocator_reset). +extern "C" __declspec(dllexport) UINT x2w_d3d12_recording_scratches(void* guest_list) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind) return 0; + AcquireSRWLockShared(&allocator_lock); + const auto found = list_recordings.find(self); + const UINT held = found != list_recordings.end() && found->second ? static_cast<UINT>(found->second->scratches.size()) : 0; + ReleaseSRWLockShared(&allocator_lock); + return held; +} + // Fixture query for two closed recordings before either is submitted. extern "C" __declspec(dllexport) BOOL x2w_d3d12_distinct_rect_scratch(void* first, void* second) { @@ -1497,11 +1667,30 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_distinct_rect_scratch(void* firs return distinct; } -x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 bytes) +x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 bytes, bool remaining = false) { AcquireSRWLockShared(&allocator_lock); const auto& state = self->own(); - const auto allocation = state.list_open && state.list_uploads ? state.list_uploads->range(address, bytes) : x2w_upload::Allocation{}; + const auto allocation = state.list_open && state.list_uploads ? state.list_uploads->range(address, bytes, remaining) : x2w_upload::Allocation{}; + ReleaseSRWLockShared(&allocator_lock); + return allocation; +} +x2w_upload::Allocation list_upload_tail(Wrapper* self, UINT64 address) +{ + x2w_upload::Allocation allocation{}; + AcquireSRWLockShared(&allocator_lock); + const auto& state = self->own(); + if (state.list_open && state.list_uploads) { + for (auto it = state.list_uploads->allocations.rbegin(); it != state.list_uploads->allocations.rend(); ++it) { + if (address < it->cpu) continue; + const UINT64 offset = address - it->cpu; + if (offset < it->bytes) { + allocation = {static_cast<uintptr_t>(address), it->gpu + offset, it->bytes - offset, it->resource, + it->offset + offset}; + break; + } + } + } ReleaseSRWLockShared(&allocator_lock); return allocation; } @@ -1544,6 +1733,9 @@ HRESULT __stdcall allocator_reset(Wrapper* self) next->uploads.clear(); next->indexed_validation.clear(); next->scratches.clear(); + next->mesh_view_pages.clear(); + next->mesh_view_cursor = 0; + next->sampler_snapshots.clear(); next->submits.clear(); next->close_failed = false; if (next != title.current) InterlockedIncrement(&allocator_swaps); @@ -1566,12 +1758,42 @@ bool submit_fence_fails() return on; } +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (opt-in): a closed list stops holding its upload ring chunks once its submit is +// fenced, so the queue fence alone guards them; the ring then grows in 16 MiB chunks up to 512 MiB. A later submit +// of the same list before its Reset fences its chunks again. One whose chunk was reused meanwhile is refused before +// ExecuteCommandLists (released_chunks_recycled), so it never reads replaced bytes. +bool ring_release_at_submit() +{ + static const bool on = GetEnvironmentVariableW(L"X2W_D3D12_RING_RELEASE_AT_SUBMIT", nullptr, 0) != 0; + return on; +} + +// draw_lock and allocator_lock held, before the queue executes `list`. True when the closed list released its chunks +// at an earlier fenced submit and one of them was reused since: the submit leaves it out, and it stays refused until +// its Reset. Counted and logged. +bool released_chunks_recycled(Wrapper* list) +{ + const auto released = released_upload_chunks.find(list); + if (released == released_upload_chunks.end()) return false; + UploadChunkMask recycled = 0; + resubmitted_upload_chunks(released->second, upload_chunks.data(), recycled, snapshot_chunks.data()); + if (!recycled) return false; + InterlockedIncrement(&upload_resubmits_refused); + static LONG logged; + if (first_calls(logged, 8)) + log("x2w-draw upload ring: closed list %p submitted again after its released chunks 0x%llx were reused; " + "refused, it is not executed", static_cast<void*>(list), static_cast<unsigned long long>(recycled)); + return true; +} + // draw_lock and allocator_lock held, after the lists were executed on queue. Each list's allocator holds a fence value // the queue must pass before the allocator can be reset. If that fence cannot be created or // signalled, the work is on the GPU all the same: the allocators are marked untracked instead. void note_submits(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists) { - auto& [fence, value] = queue_submits[queue]; + auto& submit = queue_submits[queue]; + auto& fence = submit.fence; + auto& value = submit.value; if (!fence && !submit_fence_fails()) { ID3D12Device* device = nullptr; if (SUCCEEDED(queue->GetDevice(IID_PPV_ARGS(&device)))) { @@ -1579,8 +1801,30 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists) device->Release(); } } - if (fence && SUCCEEDED(queue->Signal(fence, value + 1))) { - ++value; + UploadChunkMask chunks = 0; + for (auto* list : lists) { + chunks |= list->own().upload_chunks; + const auto released = released_upload_chunks.find(list); + if (released == released_upload_chunks.end()) continue; + // A list with a reused chunk was refused before the execute, under the same locks: all of them are intact. + UploadChunkMask reused = 0; + chunks |= resubmitted_upload_chunks(released->second, upload_chunks.data(), reused, snapshot_chunks.data()); + } + const bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); + if (signaled) ++value; + submit.submitted(chunks, signaled); + if (signaled && ring_release_at_submit()) { + for (Wrapper* list : lists) { + if (!list->own().upload_chunks) continue; + try { + release_upload_chunks_at_submit(list->own().upload_chunks, upload_chunks.data(), + released_upload_chunks[list], snapshot_chunks.data()); + } catch (const std::bad_alloc&) { + // Keep the holds: the list then pins its chunks until its Reset, as without the switch. + } + } + } + if (signaled) { for (Wrapper* list : lists) { const auto found = list_recordings.find(list); if (found == list_recordings.end()) continue; @@ -1671,6 +1915,9 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) spare->uploads.clear(); spare->indexed_validation.clear(); spare->scratches.clear(); + spare->mesh_view_pages.clear(); + spare->mesh_view_cursor = 0; + spare->sampler_snapshots.clear(); spare->submits.clear(); spare->close_failed = false; target = spare; @@ -1713,8 +1960,11 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) if (on) --on->lists; on = title.current; ++on->lists; + discard_upload_chunks(state.upload_chunks, upload_chunks.data(), snapshot_chunks.data()); + released_upload_chunks.erase(self); state.list_uploads = nullptr; state.list_scratch = nullptr; + InterlockedExchange64(&state.output_trace_recording, 0); state.list_ready = false; state.list_open = true; } @@ -1723,11 +1973,11 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) if (SUCCEEDED(hr)) { reset_list_dynamic_state(self); discard_list_gpu_writes(self); - discard_draw_sampler_heaps(previous); discard_address_uploads(previous); discard_mesh_lease_recording(previous); retire_drop_recording(self); - if (draw_dump_frame()) draw_dumps().discard(previous); + if (draw_dump_frame()) if (auto lost = draw_dumps().discard(previous)) + log("scene argument readbacks discarded on reset: list=%p mask=%08x", previous, lost); discard_red_producer(previous); } InterlockedIncrement(SUCCEEDED(hr) ? &render_resets : &render_reset_failures); @@ -1754,6 +2004,7 @@ HRESULT __stdcall list_close(Wrapper* self) state.list_ready = SUCCEEDED(hr); state.list_close_failed = FAILED(hr); if (FAILED(hr)) { + discard_upload_chunks(state.upload_chunks, upload_chunks.data(), snapshot_chunks.data()); if (const auto found = list_recordings.find(self); found != list_recordings.end() && found->second) found->second->close_failed = true; } @@ -1761,14 +2012,14 @@ HRESULT __stdcall list_close(Wrapper* self) InterlockedIncrement(&render_closes); if (FAILED(hr)) { discard_list_gpu_writes(self); - discard_draw_sampler_heaps(list); discard_address_uploads(list); discard_mesh_lease_recording(list); retire_drop_recording(self); - if (draw_dump_frame()) draw_dumps().discard(list); + if (draw_dump_frame()) if (auto lost = draw_dumps().discard(list)) + log("scene argument readbacks discarded on failed Close: list=%p mask=%08x hr=%08lx", list, lost, hr); discard_red_producer(list); static LONG failures; - if (first_calls(failures, 6)) log("x2w-render list Close failed 0x%08lx", static_cast<unsigned long>(hr)); + if (first_calls(failures, 6)) log("x2w-render list Close failed 0x%08lx list=%p", static_cast<unsigned long>(hr), static_cast<void*>(self)); } return hr; } @@ -1800,6 +2051,92 @@ void complete_when_reached(Wrapper* fence, UINT64 value) SetThreadpoolWait(wait, pending->event, nullptr); } +// The queued diagnostic readback's ownership: the submitted surface and queue references, the +// recording objects and the completion state, module-lifetime storage guarded by a mutex the +// sampling path and the drain below serialize through. The sample's wait event is created lazily +// with the recording, not at module load. +struct PresentedReadback { + std::mutex mutex; + x2w_startup::PresentReadbackState completion; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + ID3D12Resource* readback = nullptr; + UINT64 readback_bytes = 0, fence_value = 0; + ID3D12Resource* submitted_surface = nullptr; + ID3D12CommandQueue* submitted_queue = nullptr; + HANDLE wait_event = nullptr; +} presented_readback; + +// Releases the ownership a completed submission held (exactly once, through retire); the caller +// must hold the mutex and have seen a completed observation. +void release_readback_ownership() +{ + presented_readback.submitted_surface->Release(); + presented_readback.submitted_queue->Release(); + presented_readback.submitted_surface = nullptr; + presented_readback.submitted_queue = nullptr; +} + +// Hold the fence and shim module until the asynchronous callback returns. +struct PendingDrain { + ID3D12Fence* fence; + std::uint64_t value; + HANDLE event; + HMODULE module; +}; + +// Retire only the registered submission; never publish a late diagnostic image. +void CALLBACK readback_drained(PTP_CALLBACK_INSTANCE instance, void* context, PTP_WAIT wait, TP_WAIT_RESULT) +{ + std::unique_ptr<PendingDrain> pending{static_cast<PendingDrain*>(context)}; + CloseThreadpoolWait(wait); + { + const std::lock_guard lock(presented_readback.mutex); + if (presented_readback.fence == pending->fence) + presented_readback.completion.retire(pending->fence->GetCompletedValue(), release_readback_ownership, + pending->value); + } + pending->fence->Release(); + CloseHandle(pending->event); + FreeLibraryWhenCallbackReturns(instance, pending->module); +} + +// Caller holds the readback mutex. On registration failure, retain ownership. +void drain_readback_when_complete() +{ + HMODULE module = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCWSTR>(&presented_readback), + &module)) { + log("x2w-render readback drain unavailable: no shim module reference"); + return; + } + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + auto* pending = event ? new (std::nothrow) PendingDrain{presented_readback.fence, presented_readback.fence_value, + event, module} + : nullptr; + PTP_WAIT wait = pending ? CreateThreadpoolWait(&readback_drained, pending, nullptr) : nullptr; + if (!pending || !wait) { + if (event) CloseHandle(event); + delete pending; + if (wait) CloseThreadpoolWait(wait); + FreeLibrary(module); + log("x2w-render readback drain unavailable: event, wait or context allocation failed"); + return; + } + presented_readback.fence->AddRef(); + const HRESULT hr = presented_readback.fence->SetEventOnCompletion(pending->value, pending->event); + if (FAILED(hr)) { + presented_readback.fence->Release(); + delete pending; + CloseHandle(event); + CloseThreadpoolWait(wait); + FreeLibrary(module); + log("x2w-render readback drain registration failed 0x%08lx", static_cast<unsigned long>(hr)); + return; + } + SetThreadpoolWait(wait, pending->event, nullptr); +} // The presented surface, read back and reduced for the window (BGRA, top-down). constexpr int shown_width = 960, shown_height = 540; std::vector<std::uint32_t> shown_pixels; @@ -1808,14 +2145,54 @@ SRWLOCK shown_lock = SRWLOCK_INIT; char shown_note[160] = "no frame read back yet"; void write_file(const wchar_t* path, const void* data, std::size_t bytes); -void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) -{ - static ID3D12CommandAllocator* allocator; - static ID3D12GraphicsCommandList* list; - static ID3D12Fence* fence; - static ID3D12Resource* readback; - static UINT64 readback_bytes, fence_value; - static HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); +// raw_plane < 0: the baseline capture of the presented surface (plane 0), reduced for the window and +// logged as `x2w-render presented`. raw_plane >= 0 (X2W_PRESENT_COMPOSITE=1 only): a sample of that +// plane's own surface, before compositing, logged as `x2w-render raw plane <n>`; it leaves the window +// copy, the note and the dump alone. Neither is the composited window picture. +void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, int raw_plane = -1) +{ + const bool raw = raw_plane >= 0; + char failure[160] = ""; + const auto report_failure = [&] { + if (!raw) { + std::snprintf(shown_note, sizeof(shown_note), "%s", failure); + return; + } + static LONG raw_failures; + if (first_calls(raw_failures, 4)) log("x2w-render raw plane %d (not composited): %s", raw_plane, failure); + }; + const std::lock_guard lock(presented_readback.mutex); + auto& completion = presented_readback.completion; + auto& allocator = presented_readback.allocator; + auto& list = presented_readback.list; + auto& fence = presented_readback.fence; + auto& readback = presented_readback.readback; + auto& readback_bytes = presented_readback.readback_bytes; + auto& fence_value = presented_readback.fence_value; + auto& submitted_surface = presented_readback.submitted_surface; + auto& submitted_queue = presented_readback.submitted_queue; + HANDLE& event = presented_readback.wait_event; + const auto discard_recording = [&] { + if (list) { list->Release(); list = nullptr; } + if (allocator) { allocator->Release(); allocator = nullptr; } + if (fence) { fence->Release(); fence = nullptr; } + fence_value = 0; + }; + if (completion.unusable()) { + std::snprintf(failure, sizeof(failure), "readback unavailable after fence failure"); + report_failure(); + return; + } + if (completion.pending()) { + const auto state = completion.retire(fence->GetCompletedValue(), release_readback_ownership); + if (state != x2w_startup::FenceCompletion::completed) { + std::snprintf(failure, sizeof(failure), "%s", + state == x2w_startup::FenceCompletion::removed ? + "readback fence reported device removal" : "previous readback still in flight"); + report_failure(); + return; + } + } ID3D12Device* device = device_of(the_device); const D3D12_RESOURCE_DESC desc = surface->GetDesc(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; @@ -1825,7 +2202,8 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) const bool rgba = desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM || desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; const bool bgra = desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; if ((!rgba && !bgra) || total == 0 || total == ~0ull) { - std::snprintf(shown_note, sizeof(shown_note), "presented surface format %d not shown yet", desc.Format); + std::snprintf(failure, sizeof(failure), "presented surface format %d not shown yet", desc.Format); + report_failure(); return; } HRESULT hr = S_OK; @@ -1855,7 +2233,9 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) if (SUCCEEDED(hr)) hr = allocator->Reset(); if (SUCCEEDED(hr)) hr = list->Reset(allocator, nullptr); if (FAILED(hr)) { - std::snprintf(shown_note, sizeof(shown_note), "readback setup failed 0x%08lx", static_cast<unsigned long>(hr)); + discard_recording(); + std::snprintf(failure, sizeof(failure), "readback setup failed 0x%08lx", static_cast<unsigned long>(hr)); + report_failure(); return; } transition(list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -1867,38 +2247,94 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) to.PlacedFootprint = footprint; list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); transition(list, surface, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); - list->Close(); + hr = list->Close(); + if (FAILED(hr)) { + discard_recording(); + std::snprintf(failure, sizeof(failure), "readback close failed 0x%08lx", static_cast<unsigned long>(hr)); + report_failure(); + return; + } + // The sample's wait event is created with the first submission that needs it, not at load. + if (!event) event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (fence_value == UINT64_MAX - 1 || !event || !ResetEvent(event)) { + std::snprintf(failure, sizeof(failure), "readback fence or event unavailable"); + report_failure(); + return; + } + // ExecuteCommandLists does not retain the resources referenced by recorded commands. + surface->AddRef(); + queue->AddRef(); + submitted_surface = surface; + submitted_queue = queue; ID3D12CommandList* lists[] = {list}; queue->ExecuteCommandLists(1, lists); - queue->Signal(fence, ++fence_value); - fence->SetEventOnCompletion(fence_value, event); + hr = queue->Signal(fence, ++fence_value); + if (FAILED(hr)) { + completion.signal_failed(); + std::snprintf(failure, sizeof(failure), "readback fence signal failed 0x%08lx", static_cast<unsigned long>(hr)); + report_failure(); + return; + } + completion.submitted(fence_value); + hr = fence->SetEventOnCompletion(fence_value, event); + if (FAILED(hr)) { + // The submission is signalled but the sample's own event registration failed. Hand it to + // the drain (which registers its own event) instead of keeping the ownership unbounded. + drain_readback_when_complete(); + std::snprintf(failure, sizeof(failure), "readback completion event failed 0x%08lx", static_cast<unsigned long>(hr)); + report_failure(); + return; + } if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { - std::snprintf(shown_note, sizeof(shown_note), "readback timed out"); + // The fence has not reported completion to the sample. Hand the submission to the drain, + // which retires its ownership once the fence completes and publishes no pixels. + drain_readback_when_complete(); + std::snprintf(failure, sizeof(failure), "readback timed out"); + report_failure(); + return; + } + const auto completed = completion.retire(fence->GetCompletedValue(), release_readback_ownership); + if (completed != x2w_startup::FenceCompletion::completed) { + // A removed device cannot confirm completion: keep the ownership and disable reuse. A + // still-pending fence after the event was reported is drained rather than released. + if (completed == x2w_startup::FenceCompletion::pending) drain_readback_when_complete(); + std::snprintf(failure, sizeof(failure), "%s", + completed == x2w_startup::FenceCompletion::removed ? + "readback fence reported device removal" : "readback fence incomplete after wait"); + report_failure(); return; } void* mapped = nullptr; const D3D12_RANGE range{0, static_cast<SIZE_T>(total)}; - if (FAILED(readback->Map(0, &range, &mapped))) return; - AcquireSRWLockExclusive(&shown_lock); - shown_pixels.resize(shown_width * shown_height); - std::uint64_t sum = 0; + hr = readback->Map(0, &range, &mapped); + if (FAILED(hr) || !mapped) { + std::snprintf(failure, sizeof(failure), "readback map failed 0x%08lx", static_cast<unsigned long>(hr)); + report_failure(); + return; + } + if (!raw) { + AcquireSRWLockExclusive(&shown_lock); + shown_pixels.resize(shown_width * shown_height); + } + std::uint64_t sum = 0, alpha_sum = 0; for (int y = 0; y < shown_height; ++y) { const auto* row = static_cast<const unsigned char*>(mapped) + footprint.Offset + static_cast<UINT64>(y) * desc.Height / shown_height * footprint.Footprint.RowPitch; for (int x = 0; x < shown_width; ++x) { const unsigned char* texel = row + static_cast<UINT64>(x) * desc.Width / shown_width * 4; const unsigned r = rgba ? texel[0] : texel[2], g = texel[1], b = rgba ? texel[2] : texel[0]; - shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; + if (!raw) shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; sum += r + g + b; + alpha_sum += texel[3]; } } - ReleaseSRWLockExclusive(&shown_lock); + if (!raw) ReleaseSRWLockExclusive(&shown_lock); // X2W_D3D12_DUMP_SURFACE=<file>: every 40th read-back is also written at full resolution as a // 32-bit BMP (overwritten each time), for looking at detail the reduced overlay copy loses. { static wchar_t dump_path[MAX_PATH]; static const bool dump = GetEnvironmentVariableW(L"X2W_D3D12_DUMP_SURFACE", dump_path, MAX_PATH) != 0; - if (dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { + if (!raw && dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { const UINT width = static_cast<UINT>(desc.Width), height = desc.Height; std::vector<unsigned char> file(54 + std::size_t{width} * height * 4); const std::uint32_t header[] = {static_cast<std::uint32_t>(file.size()), 0, 54, 40, width, static_cast<std::uint32_t>(-static_cast<int>(height)), @@ -1921,6 +2357,15 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) } const D3D12_RANGE none{0, 0}; readback->Unmap(0, &none); + if (raw) { + static LONG raw_frames; + const LONG count = InterlockedIncrement(&raw_frames); + if ((count > 0 && count <= 3) || count % 40 == 0) + log("x2w-render raw plane %d (not composited): surface %llux%u format %d, sample %ld, mean level %.2f/255, mean alpha %.2f/255", + raw_plane, desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height), + alpha_sum / (1.0 * shown_width * shown_height)); + return; + } const LONG count = InterlockedIncrement(&shown_frames); std::snprintf(shown_note, sizeof(shown_note), "surface %llux%u format %d, readback %ld, mean level %.2f/255", desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height)); @@ -1985,6 +2430,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v return hr; } Wrapper* w = wrap(root, root_signature_kind); + if (!w) { + root->Release(); + return E_OUTOFMEMORY; + } note_root_blob(w, blob, size); std::vector<RootParameter> parameters; UINT heap_flags = 0; @@ -1994,8 +2443,10 @@ HRESULT __stdcall device_create_root_signature(Wrapper* self, UINT node, const v if (SUCCEEDED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &desc)) && desc) { heap_flags = static_cast<UINT>(desc->Desc_1_1.Flags) & x2w_startup::root_flags_heap_indexed; w->own().root_without_bindings = !heap_flags && !desc->Desc_1_1.NumParameters && !desc->Desc_1_1.NumStaticSamplers; + w->own().root_srv_only = !heap_flags && !desc->Desc_1_1.NumStaticSamplers && desc->Desc_1_1.NumParameters; for (UINT i = 0; i < desc->Desc_1_1.NumParameters; ++i) { const auto& parameter = desc->Desc_1_1.pParameters[i]; + if (parameter.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV) w->own().root_srv_only = false; RootParameter info{parameter.ParameterType, 0, 0}; if (parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_CBV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_SRV || parameter.ParameterType == D3D12_ROOT_PARAMETER_TYPE_UAV) { @@ -2121,8 +2572,8 @@ std::size_t desktop_stream_size(UINT type) // Converts the supported stream layout to desktop form and creates the pipeline. ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, char* why, std::size_t why_size, - bool& compute, IndirectGraphicsPipeline& graphics, - ID3D12RootSignature* cached_root = nullptr) + bool& compute, IndirectGraphicsPipeline& graphics, ID3D12RootSignature*& pipeline_root, + ID3D12RootSignature* cached_root = nullptr, bool reviewed_stencil = false) { const bool cached_mesh = cached_root != nullptr; const std::size_t bytes = desc->SizeInBytes; @@ -2241,7 +2692,11 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES std::memcpy(&state, stream + offset + sizeof(UINT), size); depth_enabled = state.DepthEnable; depth_writes = depth_enabled && state.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO; - untracked_depth_state = state.StencilEnable || state.DepthBoundsTestEnable; + untracked_depth_state = (state.StencilEnable && !reviewed_stencil) || state.DepthBoundsTestEnable; + if (reviewed_stencil && state.StencilEnable) { + depth_enabled = true; + depth_writes |= state.StencilWriteMask != 0; + } } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC) { samples = *reinterpret_cast<const DXGI_SAMPLE_DESC*>(stream + offset + 4); } @@ -2283,6 +2738,8 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES } check_device("Device CreatePipelineState", 86); } + if (pipeline && compute && root && root->own().kind == root_signature_kind) + pipeline_root = static_cast<ID3D12RootSignature*>(root->own().real); if (pipeline && (vertex || mesh) && (pixel || cached_mesh)) { graphics = {cached_mesh ? cached_root : static_cast<ID3D12RootSignature*>(root->own().real), targets.RTFormats[0], mesh, cached_mesh}; @@ -2297,29 +2754,64 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES return pipeline; } -// Transient data the title addresses by GPU address (fetch tables, vertices, constants) is copied -// from its memory into a desktop upload buffer; the copy's GPU address is bound instead. -ID3D12Resource* upload_ring; -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset); -D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) -{ - u64 offset = 0; - return ring_copy(title_address, bytes, &offset) ? upload_ring->GetGPUVirtualAddress() + offset : 0; -} -unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset) -{ - constexpr u64 ring_bytes = u64{256} << 20; - ID3D12Resource*& ring = upload_ring; - static unsigned char* mapped; - static volatile LONG64 cursor; - static SRWLOCK lock = SRWLOCK_INIT; - if (!ring) { - AcquireSRWLockExclusive(&lock); - if (!ring) { +// Transient guest data is copied into mapped upload chunks. Chunks grow from +// 16 MiB up to 256 MiB in total and stay alive for the process. A full chunk can be reused once +// no recording can submit its bytes and every queue that used it has finished. With +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 the ring uses 16 MiB chunks (larger for oversized reservations), +// up to 512 MiB. A fenced submit releases the list's holds in both pools. + +volatile LONG64 upload_ring_reserved_bytes, upload_ring_capacity_bytes; +volatile LONG upload_ring_reservations, upload_ring_refusals; + +// snapshot = true takes the reservation from the title input snapshot pool (128 MiB, chunks numbered after the ring's). +UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes, bool snapshot = false) +{ + const u64 max_pool_bytes = snapshot ? max_snapshot_pool_bytes : max_upload_ring_bytes; + const unsigned base = snapshot ? snapshot_chunk_base : 0; + const u64 max_alloc_bytes = max_pool_bytes / 4; + UploadReservation reservation; + if (bytes == 0 || bytes > max_alloc_bytes) return reservation; + const u64 rounded = (static_cast<u64>(bytes) + 511) & ~u64{511}; + const auto note_reserved = [snapshot](u64 reserved) { + if (snapshot) return; + InterlockedAdd64(&upload_ring_reserved_bytes, static_cast<LONG64>(reserved)); + InterlockedIncrement(&upload_ring_reservations); + }; + + auto& chunks = snapshot ? snapshot_chunks : upload_chunks; + static unsigned actives[2] = {0, 0}; + static u64 totals[2] = {0, 0}; + unsigned& active = actives[snapshot ? 1 : 0]; + u64& total_bytes = totals[snapshot ? 1 : 0]; + + AcquireSRWLockExclusive(&allocator_lock); + const auto finish = [&](unsigned index) { + active = index; + chunks[index].hold(list->own().upload_chunks, base + index); + ReleaseSRWLockExclusive(&allocator_lock); + return reservation; + }; + if (!chunks.empty()) { + reservation = reserve_upload_chunk(chunks[active], rounded); + if (reservation.mapped) { + note_reserved(rounded); + return finish(active); + } + } + + const bool grow_released_ring = !snapshot && ring_release_at_submit(); + const u64 budget_bytes = grow_released_ring ? max_released_upload_ring_bytes : max_pool_bytes; + const u64 remaining = total_bytes < budget_bytes ? budget_bytes - total_bytes : 0; + if (rounded <= remaining) { + u64 chunk_bytes = chunks.empty() || grow_released_ring ? initial_upload_chunk_bytes : chunks.back().capacity * 2; + if (chunk_bytes < rounded) chunk_bytes = rounded; + if (chunk_bytes > remaining) chunk_bytes = remaining; + auto* device = the_device ? device_of(the_device) : nullptr; + if (device) { const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; D3D12_RESOURCE_DESC buffer{}; buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = ring_bytes; + buffer.Width = chunk_bytes; buffer.Height = 1; buffer.DepthOrArraySize = 1; buffer.MipLevels = 1; @@ -2327,36 +2819,81 @@ unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset) buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ID3D12Resource* created = nullptr; void* base = nullptr; - auto* device = device_of(the_device); if (SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&created)))) { auto* budget = x2w_budget::committed(device, created, D3D12_HEAP_TYPE_UPLOAD); if (SUCCEEDED(created->Map(0, nullptr, &base))) { - mapped = static_cast<unsigned char*>(base); - ring = created; - } else if (budget) { - budget->end_use(); // The failed Map leaves the existing desktop reference held. + try { + chunks.push_back(UploadRingChunk{created, static_cast<unsigned char*>(base), chunk_bytes, 0}); + total_bytes += chunk_bytes; + if (!snapshot) InterlockedAdd64(&upload_ring_capacity_bytes, static_cast<LONG64>(chunk_bytes)); + reservation = reserve_upload_chunk(chunks.back(), rounded); + note_reserved(rounded); + return finish(static_cast<unsigned>(chunks.size() - 1)); + } catch (const std::bad_alloc&) { + created->Unmap(0, nullptr); + if (budget) budget->end_use(); + created->Release(); + } + } else { + if (budget) budget->end_use(); + created->Release(); } } } - ReleaseSRWLockExclusive(&lock); } - if (!ring || bytes == 0 || bytes > ring_bytes / 4) return nullptr; - const u64 rounded = (bytes + 511) & ~u64{511}; // 512: texture footprints are placed in the ring too - u64 start = static_cast<u64>(InterlockedExchangeAdd64(&cursor, static_cast<LONG64>(rounded))) % ring_bytes; - if (start + rounded > ring_bytes) start = static_cast<u64>(InterlockedExchangeAdd64(&cursor, static_cast<LONG64>(rounded) + (ring_bytes - start))) % ring_bytes, start = 0; - *offset = start; - return mapped + start; + // Allocation failed or the cap was reached. Older unused tails are still safe. + for (unsigned index = 0; index < chunks.size(); ++index) { + reservation = reserve_upload_chunk(chunks[index], rounded); + if (reservation.mapped) { + note_reserved(rounded); + return finish(index); + } + } + + for (unsigned index = 0; index < chunks.size(); ++index) { + reservation = reuse_upload_chunk(chunks[index], base + index, rounded, queue_submits); + if (reservation.mapped) { + note_reserved(rounded); + return finish(index); + } + } + + ReleaseSRWLockExclusive(&allocator_lock); + if (!snapshot) InterlockedIncrement(&upload_ring_refusals); + static LONG refused[2]; + if (first_calls(refused[snapshot ? 1 : 0], 8)) + log(snapshot ? "x2w-draw snapshot pool reservation refused: no unused capacity" + : "x2w-draw upload ring reservation refused: no unused capacity"); + return reservation; } -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset) +unsigned char* reserve_upload_ring(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource, bool snapshot = false) { - auto* dest = reserve_upload_ring(bytes, offset); + if (resource) *resource = nullptr; + if (offset) *offset = 0; + const UploadReservation reservation = reserve_upload_ring(list, bytes, snapshot); + if (!reservation.mapped) return nullptr; + if (offset) *offset = reservation.offset; + if (resource) *resource = reservation.resource; + return reservation.mapped; +} + +bool ring_copy(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr, bool snapshot = false) +{ + auto* dest = reserve_upload_ring(list, bytes, offset, resource, snapshot); if (!dest) return false; std::memcpy(dest, reinterpret_cast<const void*>(title_address), bytes); return true; } +D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(Wrapper* list, u64 title_address, std::size_t bytes) +{ + u64 offset = 0; + ID3D12Resource* resource = nullptr; + return ring_copy(list, title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0; +} + // Number of contiguous readable bytes at address, up to wanted. std::size_t readable_window(u64 address, std::size_t wanted) { @@ -2383,8 +2920,13 @@ struct Pass { ID3D12RootSignature* compute_root = nullptr; // latest guest root if it was forwarded x2w_startup::ComPtr<ID3D12RootSignature> desktop_compute_root; // last root actually set on this recording std::array<D3D12_GPU_VIRTUAL_ADDRESS, 64> desktop_compute_upload_srvs{}; + ID3D12RootSignature* compute_pipeline_root = nullptr; // root the bound compute pipeline was built against + UINT compute_srv_bound = 0; // root SRV parameters that reached the desktop list since slot 33 + // Desktop root UAVs a fixture bound through x2w_d3d12_fixture_compute_root_uav, set again after a shim compute pass. + std::array<D3D12_GPU_VIRTUAL_ADDRESS, 64> desktop_compute_root_uavs{}; const std::vector<RootParameter>* compute_params = nullptr; std::unique_ptr<ComputeBindingTrace> compute_trace; + bool compute_root_has_arguments = false; // that root declares parameters other than root SRVs, or static samplers IndirectGraphicsPipeline indirect_graphics; ID3D12RootSignature* graphics_root = nullptr; bool targets_bound = false; @@ -2404,10 +2946,17 @@ struct Pass { UINT topology = 0; x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler + UINT mesh_heap_slots = 0; // Logical descriptor count of a unique visible CBV/SRV/UAV source heap. u64 source_view_heap = 0; + x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) + UINT title_view_heap_entries = 0; // logical descriptor count of title_view_heap (indices 0..count-1) u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; unsigned char constant_words_bound[16] = {}; + x2w_root_constants::Store compute_constants; // compute root constants (slots 37 and 39) + std::array<u64, 64> compute_root_srvs{}; // title address of each compute root SRV (slot 43) + u64 compute_root_srv_set = 0; // bit per compute root parameter set by slot 43 since slot 33 / Reset + Wrapper* compute_root_wrapper = nullptr; // compute root signature last set by slot 33 D3D12_VERTEX_BUFFER_VIEW vb[8] = {}; PlacedVertexView placed_vb[8] = {}; D3D12_INDEX_BUFFER_VIEW ib = {}; @@ -2420,8 +2969,11 @@ struct Pass { ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; + ID3D12Resource* bound_targets[8]{}; // the last accepted bind: targets [0, target_count) and the depth texture + ID3D12Resource* bound_depth = nullptr; bool heap_set = false; x2w_startup::SamplerSource title_samplers; + u64 sampler_heap_wrapper = 0; std::unique_ptr<x2w_startup::SamplerSnapshot> sampler_snapshot; x2w_startup::ComPtr<ID3D12DescriptorHeap> sampler_heap; ID3D12DescriptorHeap* bound_sampler_heap = nullptr; @@ -2441,6 +2993,8 @@ struct Pass { std::vector<OpenQuery> ended_queries; }; LONG render_draws, render_draws_skipped, render_pipelines_real, render_pipelines_missing; +LONG compute_builder_gate_refusals; // builder Dispatches refused by X2W_COMPUTE_BUILDER_GATE +SRWLOCK compute_builder_lock = SRWLOCK_INIT; // Heap-indexed title root signatures not set on the desktop list, and real draws refused under one, by decision. LONG heap_roots_deferred, heap_root_refusals[x2w_startup::real_root_decision_count]; @@ -2451,6 +3005,210 @@ Pass& pass_of(Wrapper* self) return *static_cast<Pass*>(self->own().pass); } +bool compute_builder_gate_enabled() +{ + static const bool on = x2w_local::env_on("X2W_COMPUTE_BUILDER_GATE"); + return on; +} + +// The module holding the slot 62 return address. GetModuleHandleExW with FROM_ADDRESS is the same +// resolution RtlPcToFileHeader performs, is safe for any pointer and leaves no module reference. +bool compute_builder_caller_module(const void* return_address) noexcept +{ + if (!return_address) return false; + const DWORD saved = GetLastError(); + HMODULE module = nullptr; + bool matches = false; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast<LPCWSTR>(return_address), &module) && module) { + std::wstring path(MAX_PATH, L'\0'); + for (;;) { + const DWORD length = GetModuleFileNameW(module, path.data(), static_cast<DWORD>(path.size())); + if (!length) break; + if (length < path.size()) { + matches = x2w_startup::is_compute_builder_module(std::wstring_view(path.data(), length)); + break; + } + if (path.size() >= 32768) break; // longer than any supported Windows path + path.resize(path.size() * 2); + } + } + SetLastError(saved); + return matches; +} + +x2w_startup::BuilderGateState* compute_builder_gate_for(Wrapper* device) +{ + if (!device || device->own().kind != device_kind) return nullptr; + if (!device->own().compute_builder_gate) { + auto* gate = new (std::nothrow) x2w_startup::BuilderGateState(true); + if (gate) device->own().compute_builder_gate = gate; + } + return device->own().compute_builder_gate; +} + +// A structurally valid desktop DXIL compute container. Console DXBC containers (the 52 builder +// programs) have a console DXIL target, so they are refused here instead of being submitted. +const char* desktop_compute_program_reason(const D3D12_SHADER_BYTECODE& code) noexcept +{ + if (!readable_shader_container(code)) return "the console compute program is missing or unreadable"; + const auto* data = static_cast<const unsigned char*>(code.pShaderBytecode); + const auto word = [data](std::size_t offset) { + UINT value; + std::memcpy(&value, data + offset, sizeof(value)); + return value; + }; + const std::size_t bytes = code.BytecodeLength; + if (bytes < 32 || word(24) != bytes) return "the console compute container is malformed"; + const std::size_t parts = word(28); + if (parts > (bytes - 32) / 4) return "the console compute container is malformed"; + const std::size_t header = 32 + parts * 4; + bool found = false; + for (std::size_t i = 0; i < parts; ++i) { + const std::size_t part = word(32 + i * 4); + if (part < header || part > bytes - 8) return "the console compute container is malformed"; + const std::size_t size = word(part + 4); + if (size > bytes - part - 8) return "the console compute container is malformed"; + if (std::memcmp(data + part, "DXIL", 4)) continue; + if (found) return "the console compute container has more than one DXIL part"; + found = true; + const std::size_t program = part + 8; + if (size < 24 || word(program) >> 16 != D3D12_SHVER_COMPUTE_SHADER) return "the DXIL program is not a compute shader"; + const std::size_t bitcode = word(program + 16); + const std::size_t bitcode_size = word(program + 20); + if (word(program + 4) * 4ull != size || std::memcmp(data + program + 8, "DXIL", 4) || bitcode < 16 || + bitcode > size - 8 || bitcode_size < 4 || bitcode_size > size - 8 - bitcode || + std::memcmp(data + program + 8 + bitcode, "BC\xc0\xde", 4)) + return "the DXIL program is malformed"; + } + return found ? nullptr : "the console compute program is not desktop DXIL"; +} + +// The on-the-spot creation for one tracked builder pipeline. This task has no translation step: a +// console program fails by name before reaching D3D12. A future translation can attach its desktop +// pipeline through the same entry point. +bool make_compute_builder_pipeline(Wrapper* device, Wrapper* pipeline, const char** reason) noexcept +{ + if (reason) *reason = nullptr; + if (!device || !pipeline || pipeline->own().kind != pipeline_kind) { + if (reason) *reason = "the tracked object is not a pipeline"; + return false; + } + if (pipeline->own().real) return true; + const PipelineInfo* info = pipeline_info(pipeline); + if (!info || info->path != 62 || info->desc.size() < sizeof(D3D12_COMPUTE_PIPELINE_STATE_DESC)) { + if (reason) *reason = "the slot 62 description is unavailable"; + return false; + } + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + std::memcpy(&desc, info->desc.data(), sizeof(desc)); + if (const char* program_reason = desktop_compute_program_reason(desc.CS)) { + if (reason) *reason = program_reason; + return false; + } + Wrapper* root = as_wrapper(desc.pRootSignature); + if (!root || root->own().kind != root_signature_kind || !root->own().real) { + if (reason) *reason = "the builder root signature has no desktop object"; + return false; + } + desc.pRootSignature = static_cast<ID3D12RootSignature*>(root->own().real); + x2w_startup::ComPtr<ID3D12PipelineState> created; + const HRESULT hr = device_of(device)->CreateComputePipelineState(&desc, IID_PPV_ARGS(created.GetAddressOf())); + if (FAILED(hr)) { + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-render compute builder gate: desktop pipeline creation failed 0x%08lx", hr); + if (reason) *reason = "desktop pipeline creation failed"; + return false; + } + pipeline->own().real = created.Detach(); + pipeline->own().compute_pipeline = true; + pipeline->own().pipeline_root = desc.pRootSignature; + return true; +} + +void note_compute_builder_pipeline(Wrapper* device, Wrapper* pipeline, const void* return_address) +{ + if (!compute_builder_gate_enabled() || !device || !pipeline) return; + if (!compute_builder_caller_module(return_address)) return; + pipeline->own().builder_pipeline = true; + AcquireSRWLockExclusive(&compute_builder_lock); + x2w_startup::BuilderGateState* gate = compute_builder_gate_for(device); + if (!gate) { + static LONG logged; + if (first_calls(logged, 1)) log("x2w-render compute builder gate: no gate state; builder pipelines stay untracked"); + } else { + gate->note_pipeline(pipeline, true, pipeline->own().real != nullptr); + } + ReleaseSRWLockExclusive(&compute_builder_lock); +} + +// Called before the normal Dispatch path. It returns true for a non-builder Dispatch, for the gate +// being off, or when every tracked builder pipeline has a desktop PSO. A refusal has already been +// counted and logged once. +bool compute_builder_dispatch_allowed(Wrapper* list, const char* stage) +{ + if (!compute_builder_gate_enabled() || !list) return true; + Pass& pass = pass_of(list); + if (!pass.pipeline || !pass.pipeline->own().builder_pipeline) return true; + Wrapper* device = list->own().list_device; + AcquireSRWLockExclusive(&compute_builder_lock); + x2w_startup::BuilderGateState* gate = compute_builder_gate_for(device); + if (!gate) { + InterlockedIncrement(&compute_builder_gate_refusals); + static LONG logged; + if (first_calls(logged, 1)) + log("x2w-render compute builder gate: %s refused; no gate state is available", stage); + ReleaseSRWLockExclusive(&compute_builder_lock); + return false; + } + x2w_startup::BuilderGateDecision decision = gate->decide(true); + if (decision == x2w_startup::BuilderGateDecision::refuse_missing && gate->tracked() == 0) + gate->note_failed("no builder pipeline was tracked"); + if (decision == x2w_startup::BuilderGateDecision::refuse_missing) { + for (unsigned i = 0; i < gate->tracked(); ++i) { + const void* missing = gate->missing_at(i); + if (!missing) continue; + const char* reason = nullptr; + if (!make_compute_builder_pipeline(device, const_cast<Wrapper*>(static_cast<const Wrapper*>(missing)), &reason)) { + gate->note_failed(reason); + break; + } + gate->note_pso(missing); + } + decision = gate->decide(true); + } + if (decision == x2w_startup::BuilderGateDecision::allow) { + // The title bound a placeholder wrapper earlier; the gate has just published its real + // desktop PSO. Refresh the recording's cached compute state and bind the PSO so the + // caller's Dispatch decision sees the completed pipeline instead of the placeholder. + if (auto* host = recording(list); host && pass.pipeline && pass.pipeline->own().real) { + pass.pipeline_real = true; + pass.compute_pipeline = true; + pass.compute_pipeline_root = pass.pipeline->own().pipeline_root; + host->SetPipelineState(static_cast<ID3D12PipelineState*>(pass.pipeline->own().real)); + if (pass.compute_root && pass.compute_pipeline_root == pass.compute_root) + host->SetComputeRootSignature(pass.compute_root); + } + static LONG logged; + if (first_calls(logged, 1)) + log("x2w-render compute builder gate: %u tracked pipelines, all have a desktop PSO; %s allowed", + gate->tracked(), stage); + ReleaseSRWLockExclusive(&compute_builder_lock); + return true; + } + gate->note_refusal(); + InterlockedIncrement(&compute_builder_gate_refusals); + static LONG logged; + if (first_calls(logged, 1)) { + const char* reason = gate->first_reason(); + log("x2w-render compute builder gate: %u tracked pipelines, %u with a desktop PSO; %s refused: %s", + gate->tracked(), gate->with_pso(), stage, reason ? reason : "not every builder pipeline has a desktop PSO"); + } + ReleaseSRWLockExclusive(&compute_builder_lock); + return false; +} + bool indirect_copy_ranges() { static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_INDIRECT_COPY_RANGES"); @@ -2530,10 +3288,21 @@ void retire_drop_recording(Wrapper* list) retire_discard_holds(list); } +void clear_draw_sampler_snapshot(Wrapper* self) +{ + if (!self->own().pass) return; + auto& pass = pass_of(self); + pass.sampler_heap.Reset(); + pass.sampler_snapshot.reset(); +} + // A reset list has no viewport or scissor and uses the default stencil reference. void reset_list_dynamic_state(Wrapper* self) { if (!self->own().pass) return; + clear_draw_sampler_snapshot(self); + pass_of(self).compute_root_srvs.fill(0); + pass_of(self).compute_root_srv_set = 0; pass_of(self).stencil_reference = 0; pass_of(self).viewport_set = false; pass_of(self).scissor_set = false; @@ -2560,6 +3329,7 @@ void __stdcall list_pipeline(Wrapper* self, void* pipeline) // a recognized desktop graphics pipeline just before it records the draw. pass.pipeline_real = available && !pass.indirect_graphics.root; pass.compute_pipeline = pass.pipeline_real && w->own().compute_pipeline; + pass.compute_pipeline_root = pass.compute_pipeline ? w->own().pipeline_root : nullptr; pass.pipeline = w && w->own().kind == pipeline_kind ? w : nullptr; InterlockedIncrement(pass.pipeline_real ? &render_pipelines_real : &render_pipelines_missing); if (auto* list = recording(self); list && pass.pipeline_real) list->SetPipelineState(static_cast<ID3D12PipelineState*>(w->own().real)); @@ -2599,31 +3369,100 @@ UINT __stdcall list_resource_barriers(Wrapper* self, UINT count, const D3D12_RES return 0; // no console barrier actions to perform on the caller's side } +// Compute root views on the desktop list. Root SRVs come from slot 43; root UAVs only from the fixture hook +// x2w_d3d12_fixture_compute_root_uav (slot 45 is not forwarded). Both are recorded here so restore_compute_root can set +// them again after a shim compute pass has replaced the desktop compute root. +void bind_compute_root_view(Pass& pass, ID3D12GraphicsCommandList* list, UINT parameter, D3D12_ROOT_PARAMETER_TYPE type, + D3D12_GPU_VIRTUAL_ADDRESS address) +{ + if (type == D3D12_ROOT_PARAMETER_TYPE_SRV) { + pass.desktop_compute_upload_srvs[parameter] = address; + list->SetComputeRootShaderResourceView(parameter, address); + } else if (type == D3D12_ROOT_PARAMETER_TYPE_UAV) { + pass.desktop_compute_root_uavs[parameter] = address; + list->SetComputeRootUnorderedAccessView(parameter, address); + } +} +bool has_compute_root_views(const Pass& pass) +{ + const auto live = [](D3D12_GPU_VIRTUAL_ADDRESS address) { return address != 0; }; + return std::any_of(pass.desktop_compute_upload_srvs.begin(), pass.desktop_compute_upload_srvs.end(), live) || + std::any_of(pass.desktop_compute_root_uavs.begin(), pass.desktop_compute_root_uavs.end(), live); +} +// Sets the title's desktop compute root again, with every view bind_compute_root_view recorded under it, after a shim +// compute pass (indexed-draw validation, split indirect Dispatch) replaced the root and invalidated its arguments. +void restore_compute_root(const Pass& pass, ID3D12GraphicsCommandList* list) +{ + if (!pass.desktop_compute_root) return; + list->SetComputeRootSignature(pass.desktop_compute_root.Get()); + for (UINT parameter = 0; parameter < pass.desktop_compute_upload_srvs.size(); ++parameter) { + if (const auto address = pass.desktop_compute_upload_srvs[parameter]) + list->SetComputeRootShaderResourceView(parameter, address); + if (const auto address = pass.desktop_compute_root_uavs[parameter]) + list->SetComputeRootUnorderedAccessView(parameter, address); + } +} + void __stdcall list_compute_root(Wrapper* self, void* root) { auto* list = recording(self); if (!list) return; Wrapper* w = as_wrapper(root); Pass& pass = pass_of(self); + // A different root signature invalidates the title's cached compute root arguments. + if (pass.compute_root_wrapper != w) { + pass.compute_constants.clear(); + pass.compute_root_srvs.fill(0); + pass.compute_root_srv_set = 0; + } + pass.compute_root_wrapper = w; const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast<ID3D12RootSignature*>(w->own().real) : nullptr; pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; + pass.compute_srv_bound = 0; + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique<ComputeBindingTrace>(); pass.compute_trace->root = w; } + pass.compute_srv_bound = 0; + // Root SRV parameters are forwarded by their own slot; anything else the root declares is not. + pass.compute_root_has_arguments = real && !w->own().root_without_bindings && !w->own().root_srv_only; if (pass.compute_root) { - if (pass.desktop_compute_root.Get() != pass.compute_root) + if (pass.desktop_compute_root.Get() != pass.compute_root) { pass.desktop_compute_upload_srvs.fill(0); + pass.desktop_compute_root_uavs.fill(0); + } pass.desktop_compute_root = pass.compute_root; list->SetComputeRootSignature(pass.compute_root); } } -// Query slots 28 to 30, as a hypothesis (command_list_slot_names.h): no fixture here establishes which console -// methods sit there, so they are bound only with X2W_D3D12_QUERY_SLOTS=1. The heap reaches device slot 39 with the -// desktop desc. Only occlusion queries are +// Fixture binding of a desktop root UAV (a desktop GPU address) on a guest list's recording, under the compute root +// set through slot 33. Not a guest slot: titles have no compute root UAV on the desktop list (slot 45 is not +// forwarded). It records the view through bind_compute_root_view, as slot 43 does for root SRVs, so +// restore_compute_root sets it again after a shim compute pass; a binding made on the desktop list directly would be +// lost there. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* guest_list, UINT parameter, UINT64 address) +{ + Wrapper* self = as_wrapper(guest_list); + if (!self || self->own().kind != list_kind) return FALSE; + auto* list = recording(self); + auto& pass = pass_of(self); + const auto* params = pass.compute_params; + if (!list || !pass.compute_root || !params || parameter >= params->size() || + parameter >= pass.desktop_compute_root_uavs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_UAV || + !address) + return FALSE; + bind_compute_root_view(pass, list, parameter, D3D12_ROOT_PARAMETER_TYPE_UAV, address); + return TRUE; +} + +// Query slots 28 to 30, confirmed by the GXDK 261000 ID3D12GraphicsCommandList8 function table +// (command_list_slot_names.h): they are bound only with X2W_D3D12_QUERY_SLOTS=1 because the behavior is +// diagnostic. The heap reaches device slot 39 with the desktop desc. Only occlusion queries are // forwarded (shortcut: other heap types are refused until a caller needs them); a call that does not fit the // heap it names is refused and logged with its values instead of reaching the desktop list. enum QueryMethod { begin_query, end_query, resolve_query }; @@ -2742,6 +3581,7 @@ HRESULT __stdcall device_create_query_heap(Wrapper* self, const D3D12_QUERY_HEAP // Slot-61 calls by outcome and signature kind (IndirectCommand; none counts placeholder and unknown // signatures), reported with the render totals. 64-bit and never reset, so they neither wrap nor stall. +const char* bind_mesh57_buffers(Wrapper*, Pass&, ID3D12GraphicsCommandList*, ID3D12Resource*); enum { indirect_forwarded, indirect_graphics_pipeline, indirect_compute_pipeline, indirect_placeholder, indirect_other, indirect_outcomes }; volatile LONG64 indirect_calls[indirect_outcomes][5]; @@ -2761,8 +3601,81 @@ struct IndirectIndexView { }; const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset, const IndirectIndexView& indices); +struct TranslatedDispatch { + D3D12_DISPATCH_ARGUMENTS groups{}; + ID3D12CommandSignature* signature = nullptr; + ID3D12Resource* argument = nullptr; + u64 offset = 0; +}; +const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch); u64 known_pipeline_key(Wrapper* pipeline); - +// Each probe is keyed explicitly so independent captures can select their own pipelines. +u64 probe_key(const char* variable) { + char value[24]{}; + const auto n = GetEnvironmentVariableA(variable, value, sizeof(value)); + if (!n || n >= sizeof(value) || std::strspn(value, "0123456789abcdefABCDEF") != n || n > 16) return 0; + return std::strtoull(value, nullptr, 16); +} + +void scene_argument_probe(Wrapper* self, unsigned event, void* argument = nullptr, u64 offset = 0, const char* refused = nullptr); + +// Observe subsequent uses of the first rejected copied UAV owner per compute key. +// Each range is immutable once published; logging is bounded per event type and owner. +enum class OutputUse : unsigned { indirect_argument, indirect_count, indirect_recorded, copy_source, copy_destination, + copy_read_recorded, copy_write_recorded, shader_guest_read, shader_gpu_read, map, unmap }; +bool trace_compute_outputs() { + static const bool enabled = x2w_local::env_on("X2W_D3D12_COMPUTE_OUTPUT_TRACE"); + return enabled; +} +struct TracedComputeOutput { + u64 key{}, owner{}, base{}, length{}; + volatile LONG events{}; +}; +TracedComputeOutput traced_compute_outputs[32]; +volatile LONG traced_compute_output_count{}; +bool trace_copied_compute_output(u64 key, u64 owner, u64 base, u64 offset, u64 bytes) { + // Called under draw_lock. Only publish complete, representable guest intervals. + if (!trace_compute_outputs() || !base || !bytes || offset > UINT64_MAX - base || + bytes > UINT64_MAX - (base + offset)) return false; + const LONG count = InterlockedCompareExchange(&traced_compute_output_count, 0, 0); + for (LONG i = 0; i < count; ++i) + if (traced_compute_outputs[i].key == key) return false; + if (count == 32) return false; + auto& entry = traced_compute_outputs[count]; + entry.key = key; entry.owner = owner; entry.base = base + offset; entry.length = bytes; + InterlockedIncrement(&traced_compute_output_count); + return true; +} +void trace_compute_output_use(Wrapper* list, OutputUse use, const char* event, const void* object, u64 address, + u64 offset, u64 bytes, u64 pipeline = 0) { + if (!trace_compute_outputs()) return; + const LONG count = InterlockedCompareExchange(&traced_compute_output_count, 0, 0); + if (!count) return; + const Wrapper* w = object ? as_wrapper(object) : nullptr; + if (w && w->own().kind == resource_kind) address = reinterpret_cast<u64>(w->own().title_memory); + if (!address || offset > UINT64_MAX - address || !bytes) return; + const u64 first = address + offset; + for (LONG i = 0; i < count; ++i) { + auto& item = traced_compute_outputs[i]; + if (first <= item.base ? item.base - first >= bytes : first - item.base >= item.length) continue; + const bool same = reinterpret_cast<u64>(object) == item.owner; + const LONG flag = 1L << (2 * static_cast<unsigned>(use) + same); + if ((InterlockedCompareExchange(&item.events, 0, 0) & flag) || (InterlockedOr(&item.events, flag) & flag)) continue; + LONG64 recording_id = 0; + if (list) { + static volatile LONG64 serial; + recording_id = InterlockedCompareExchange64(&list->own().output_trace_recording, 0, 0); + if (!recording_id) { + const auto next = InterlockedIncrement64(&serial); + const auto seen = InterlockedCompareExchange64(&list->own().output_trace_recording, next, 0); + recording_id = seen ? seen : next; + } + } + log("x2w-compute-output-use producer=%016llx use=%s list=%p recording=%lld consumer=%016llx owner=%p same=%u " + "guest-first=0x%llx bytes=%llu watched=0x%llx+%llu", + item.key, event, list, recording_id, pipeline, object, same, first, bytes, item.base, item.length); + } +} namespace indirect_other_refusal_code { constexpr const char* list_closed = "list_closed"; constexpr const char* invalid_list_type = "invalid_list_type"; @@ -2796,20 +3709,45 @@ constexpr const char* aliased_index_unaligned = "aliased_index_unaligned"; constexpr const char* mesh_xmem_read = "mesh_xmem_read"; constexpr const char* rect_live_compute_root = "rect_live_compute_root"; constexpr const char* rect_conversion_unavailable = "rect_conversion_unavailable"; +constexpr const char* split_dispatch_unavailable = "split_dispatch_unavailable"; constexpr const char* count_missing_resource = "count_missing_resource"; constexpr const char* count_invalid_offset = "count_invalid_offset"; constexpr const char* count_outside_placed_buffer = "count_outside_placed_buffer"; constexpr const char* count_not_common_state = "count_not_common_state"; +constexpr const char* builder_gate = "builder_gate"; constexpr const char* unknown = "unknown"; } // namespace indirect_other_refusal_code +// Opt-in (X2W_SPLIT_INDIRECT_DISPATCH=1): a batched or counted indirect Dispatch with a desktop compute pipeline is +// split into single-command calls (split_indirect_dispatch.h). Without it the native call runs on every adapter. +bool split_indirect_dispatch_enabled() +{ + return x2w_local::env_on("X2W_SPLIT_INDIRECT_DISPATCH"); +} + // The guest method has independent resource and byte-offset arguments. +// X2W_D3D12_ROOT_SRV_AT_DRAW=1 (opt-in): slot 44 makes no desktop copy of a root SRV without an upload mapping; the +// translated draws read it from its title address at the draw (list_root_srv). +bool root_srv_at_draw() +{ + static const bool on = GetEnvironmentVariableW(L"X2W_D3D12_ROOT_SRV_AT_DRAW", nullptr, 0) != 0; + return on; +} +LONG root_srv_copies_skipped, root_srv_copies_made; + void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { + scene_argument_probe(self, 27, argument, offset); // Every refusal is counted under the signature's kind, including those before the signature is checked. Wrapper* sig = as_wrapper(signature); IndirectCommand kind = sig && sig->own().kind == command_signature_kind ? sig->own().indirect_command : IndirectCommand::none; + if (trace_compute_outputs()) { + const u64 span = sig && sig->own().kind == command_signature_kind ? u64{count} * sig->own().indirect_bytes : 0; + trace_compute_output_use(self, OutputUse::indirect_argument, "indirect-argument-attempt", argument, 0, offset, span); + if (count_buffer) + trace_compute_output_use(self, OutputUse::indirect_count, "indirect-count-attempt", count_buffer, 0, count_offset, 4); + } Wrapper* refusal_pipeline = nullptr; u64 trace_call = 0; const auto refuse = [&kind, &refusal_pipeline, &trace_call](const char* reason, int outcome = indirect_other, @@ -2854,7 +3792,20 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool mesh = command == IndirectCommand::dispatch_mesh; const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); + if (mesh && pass.pipeline && pass.pipeline->own().real && x2w_local::env_on("X2W_MESH57_CAPTURE_STATE") && + (pass.requested_mesh_pipeline != pass.pipeline || pass.requested_mesh_root != pass.root)) { + pass.requested_mesh_pipeline = pass.pipeline; + pass.requested_mesh_root = pass.root; + request_slot57_mesh(pass.pipeline, pass.root); + } refusal_pipeline = pass.pipeline; + // A slot 62 builder pipeline is tracked by the wrapper itself, not by a slot 67 request key. + // Gate its indirect Dispatch before the signature and argument checks so a partial builder + // cannot reach ExecuteIndirect. + if (command == IndirectCommand::dispatch && pass.pipeline && pass.pipeline->own().builder_pipeline && + !compute_builder_dispatch_allowed(self, "ExecuteIndirect")) + return refuse("the compute builder gate refused the Dispatch", indirect_compute_pipeline, indirect_other_refusal_code::builder_gate); + const bool translated_compute = command == IndirectCommand::dispatch && pass.pipeline && pass.pipeline->own().compute_request_key; const bool translated = (command == IndirectCommand::draw || indexed) && pass.pipeline && !pass.pipeline->own().real && (pass.graphics_root || pass.deferred_root) && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); u64 bytes = sig->own().indirect_bytes; @@ -2865,7 +3816,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || - pass.indirect_graphics.root != pass.graphics_root || pass.indirect_graphics.mesh != mesh))) { + (pass.indirect_graphics.constant_guest == UINT_MAX && pass.indirect_graphics.root != pass.graphics_root) || + pass.indirect_graphics.mesh != mesh))) { // A console pipeline (no desktop pipeline) used only here still gets the request a direct draw writes; // nothing is drawn. if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && @@ -2894,14 +3846,25 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, !std::equal(pso.cached_targets, pso.cached_targets + pso.cached_target_count, pass.target_formats)) return refuse("cached mesh requires matching color and depth attachments, viewport and scissor", indirect_other, indirect_other_refusal_code::cached_mesh_attachments); - if (!pass.root || pass.root != pso.guest_root_params || pass.root_heap_flags) - return refuse("cached mesh requires a recorded root without heap indexing", indirect_graphics_pipeline); + if (!pass.root || pass.root != pso.guest_root_params || (pass.root_heap_flags != 0) != (pso.constant_guest != UINT_MAX)) + return refuse("cached mesh creation root or indexing mode differs", indirect_graphics_pipeline); for (std::size_t i = 0; i < pass.root->size(); ++i) { - if (i == pso.cached_srv_root) continue; + if (i == pso.cached_srv_root || (pso.constant_guest != UINT_MAX && i != pso.constant_guest)) continue; const auto mask = (1u << (*pass.root)[i].constants_count) - 1; if ((pass.constant_words_bound[i] & mask) != mask) return refuse("cached mesh root constants are incomplete", indirect_graphics_pipeline); } + } else if (translated) { + if (!pass.targets_bound || (!pass.target_count && pass.dsv_format == DXGI_FORMAT_UNKNOWN) || + !pass.viewport_set || !pass.scissor_set) { + const char* code = + (!pass.targets_bound || (!pass.target_count && pass.dsv_format == DXGI_FORMAT_UNKNOWN)) + ? indirect_other_refusal_code::no_render_target + : indirect_other_refusal_code::missing_viewport_or_scissor; + return refuse("translated indirect draw requires bound target or depth view, viewport and scissor", indirect_other, code); + } + if (!pass.targets_single_sample) + return refuse("draw requires single-sample targets", indirect_other, indirect_other_refusal_code::multisample_target); } else if (!pass.targets_bound || pass.target_count != 1 || !pass.target0 || (!translated && pass.target_formats[0] != pass.indirect_graphics.target_format) || pass.dsv_format != DXGI_FORMAT_UNKNOWN || !pass.viewport_set || !pass.scissor_set) { @@ -2918,11 +3881,14 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, return refuse("indirect rectangle list requires a non-indexed draw", indirect_other, indirect_other_refusal_code::rect_list_indexed); if (!mesh && !rect_list && pass.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) return refuse("indirect draw requires triangle-list or rectangle-list topology", indirect_other, indirect_other_refusal_code::unsupported_topology); - if (!pass.indirect_graphics.cached_mesh) { + if (!pass.indirect_graphics.cached_mesh && !translated) { const auto samples = pass.target0->GetDesc().SampleDesc; if (samples.Count != 1 || samples.Quality) return refuse("draw requires a single-sample render target", indirect_other, indirect_other_refusal_code::multisample_target); } + } else if (translated_compute) { + if (count != 1 || count_buffer || sig->own().signature_root) + return refuse("translated Dispatch requires one rootless command and no count buffer", indirect_compute_pipeline); } else if (!pass.compute_pipeline || !pass.compute_root) { return refuse("requires a desktop compute pipeline and root", indirect_compute_pipeline); } else if (sig->own().signature_root && sig->own().signature_root != pass.compute_root) { @@ -2949,6 +3915,12 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) return refuse("argument buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::argument_not_common_state); auto* resource = static_cast<ID3D12Resource*>(buffer->own().real); + if (translated_compute) { + const TranslatedDispatch dispatch{{}, static_cast<ID3D12CommandSignature*>(sig->own().real), resource, offset}; + if (const char* failure = record_translated_dispatch(self, dispatch)) return refuse(failure, indirect_compute_pipeline); + InterlockedIncrement64(&indirect_calls[indirect_forwarded][static_cast<int>(kind)]); + return; + } IndirectIndexView index_view; if (indexed) { auto view = pass.ib; @@ -3032,8 +4004,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } } if (rect_list) { - if (std::any_of(pass.desktop_compute_upload_srvs.begin(), pass.desktop_compute_upload_srvs.end(), - [](u64 address) { return address != 0; })) + if (has_compute_root_views(pass)) return refuse("rectangle-list conversion would drop live compute root arguments", indirect_other, indirect_other_refusal_code::rect_live_compute_root); // The producer's count names three vertices per rectangle; the desktop draw needs six. Convert on the GPU @@ -3052,8 +4023,17 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } if (graphics) { list->SetPipelineState(static_cast<ID3D12PipelineState*>(pass.pipeline->own().real)); - list->SetGraphicsRootSignature(pass.graphics_root); - if (pass.indirect_graphics.cached_mesh) { + const auto& pso = pass.indirect_graphics; + if (pso.constant_guest == UINT_MAX) list->SetGraphicsRootSignature(pass.graphics_root); + if (pso.constant_guest != UINT_MAX) { + const UINT guest = pso.constant_guest; + UINT words[8]{}; + const auto count = (*pass.root)[guest].constants_count; + std::copy_n(pass.constants[guest], count, words); + if (const char* why = bind_mesh57_buffers(self, pass, list, resource)) + return refuse(why, indirect_graphics_pipeline); + list->SetGraphicsRoot32BitConstants(0, (count + 3) & ~3u, words, 0); + } else if (pass.indirect_graphics.cached_mesh) { const UINT srv = pass.indirect_graphics.cached_srv_root; if (srv != UINT_MAX) list->SetGraphicsRootShaderResourceView(srv, inputs[0].resource->GetGPUVirtualAddress() + inputs[0].offset); @@ -3063,6 +4043,11 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } } } + // Opt-in split of a batched or counted Dispatch for adapters that run only its first command + // (split_indirect_dispatch.h). Only a rootless Dispatch signature with a desktop compute pipeline and root reaches + // here with a count above one or a count buffer; graphics and mesh signatures are refused above. + const bool split = command == IndirectCommand::dispatch && pass.compute_pipeline && pass.compute_root && + (count > 1 || count_buffer) && split_indirect_dispatch_enabled(); ID3D12Resource* counts = nullptr; if (count_buffer) { // The count word is four bytes in a unique placed buffer that also tracks state from COMMON. @@ -3079,7 +4064,35 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!count_info || count_info->initial_state != D3D12_RESOURCE_STATE_COMMON) return refuse("count buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::count_not_common_state); counts = static_cast<ID3D12Resource*>(count_wrapper->own().real); - if (counts != resource) require_state(self, counts, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + if (counts != resource) + require_state(self, counts, split ? D3D12_RESOURCE_STATE_COPY_SOURCE : D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } + if (split) { + // The rewrite reads the title's records and count word by copies only, then replaces the compute root and + // pipeline. The compute state the title can set on the desktop list is the pipeline (slot 25), the root + // (slot 33) and root SRVs (slot 43); the other compute root setters are not forwarded. The pipeline is set + // again here and the root with its views by restore_compute_root, the same code as after the indexed-draw + // validation pass, before the single-command calls. + auto* desktop = device_of(self->own().list_device); + const auto stride = static_cast<UINT>(sig->own().indirect_bytes); + auto rewritten = x2w_startup::SplitIndirectDispatch::make_scratch(desktop, count, stride); + if (!rewritten || !retain_with_recording(self, rewritten)) + return refuse("split indirect Dispatch has no scratch buffer", indirect_other, + indirect_other_refusal_code::split_dispatch_unavailable); + require_state(self, resource, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (!x2w_startup::split_indirect_dispatch().rewrite(list, resource, offset, count, stride, counts, count_offset, + rewritten.Get())) + return refuse("split indirect Dispatch rewrite is unavailable", indirect_other, + indirect_other_refusal_code::split_dispatch_unavailable); + list->SetPipelineState(static_cast<ID3D12PipelineState*>(pass.pipeline->own().real)); + restore_compute_root(pass, list); + const auto first = x2w_startup::SplitIndirectDispatch::rewritten_offset(count, stride); + auto* command = static_cast<ID3D12CommandSignature*>(sig->own().real); + for (UINT i = 0; i < count; ++i) + list->ExecuteIndirect(command, 1, rewritten.Get(), first + u64{i} * sizeof(D3D12_DISPATCH_ARGUMENTS), nullptr, 0); + x2w_startup::SplitIndirectDispatch::finish(list, rewritten.Get()); + InterlockedIncrement64(&indirect_calls[indirect_forwarded][static_cast<int>(kind)]); + return; } if (!leased_arguments && !rect_list) { require_state(self, resource, argument_state); @@ -3087,6 +4100,9 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const auto red_samples = graphics ? red_producer_draw_before(self, list, "indirect-draw", 0) : RedDrawSamples{}; list->ExecuteIndirect(static_cast<ID3D12CommandSignature*>(sig->own().real), count, draw_arguments, draw_offset, counts, counts ? count_offset : 0); + if (trace_compute_outputs()) + trace_compute_output_use(self, OutputUse::indirect_recorded, "indirect-recorded", argument, 0, offset, span, + known_pipeline_key(refusal_pipeline)); red_producer_draw_after(self, red_samples); if (trace_call) log("x2w-mesh86-trace call=%llu stage=record outcome=recorded", trace_call); if (scratch) x2w_startup::RectIndirectArguments::finish(list, scratch); @@ -3392,6 +4408,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO pass.depth_view_writable = false; pass.target_count = 0; pass.target0 = nullptr; + std::fill_n(pass.bound_targets, 8, nullptr); + pass.bound_depth = nullptr; pass.dsv_format = DXGI_FORMAT_UNKNOWN; if (!list) return; static LONG refused, unresolved_logged; @@ -3485,6 +4503,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO } if (dsv_target) require_state(self, dsv_target, dsv_state); pass.target_count = count; + std::copy_n(targets, 8, pass.bound_targets); + pass.bound_depth = dsv_target; pass.dsv_format = dsv_format; const auto single_sample = [](ID3D12Resource* resource) { const auto samples = resource->GetDesc().SampleDesc; @@ -3530,13 +4550,19 @@ void __stdcall list_compute_upload_srv(Wrapper* self, UINT parameter, UINT64 add { auto* list = recording(self); auto& pass = pass_of(self); + if (list && pass.compute_root_wrapper && parameter < pass.compute_root_srvs.size()) { + pass.compute_root_srvs[parameter] = address; + pass.compute_root_srv_set |= u64{1} << parameter; + } const auto* params = pass.compute_params; if (!list || !params || parameter >= params->size() || parameter >= pass.desktop_compute_upload_srvs.size() || (*params)[parameter].type != D3D12_ROOT_PARAMETER_TYPE_SRV) return; const auto gpu = list_upload_gpu(self, address, 1); + // A rejected replacement leaves no valid binding: the desktop list may still hold the previous address. + if (parameter < 32) pass.compute_srv_bound &= ~(1u << parameter); if (gpu && !(gpu % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT)) { - pass.desktop_compute_upload_srvs[parameter] = gpu; - list->SetComputeRootShaderResourceView(parameter, gpu); + bind_compute_root_view(pass, list, parameter, D3D12_ROOT_PARAMETER_TYPE_SRV, gpu); + if (parameter < 32) pass.compute_srv_bound |= 1u << parameter; } } @@ -3559,8 +4585,19 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) pass.srv_bound |= 1u << parameter; return; } + // Without an upload mapping a 64 KiB window of title memory is copied into the upload ring for the desktop binding. + // No draw reads that binding: translated draws set their own root signature and read the SRV from root_address at + // the draw; every desktop graphics pipeline is an indirect one (build_stream_pipeline sets its root), so list_draw + // forwards only with a compute pipeline; and an indirect graphics draw binds a pipeline over the list's root, an + // empty one or, for a cached mesh pipeline, the title's root, whose only SRV it binds from its lease. With + // X2W_D3D12_ROOT_SRV_AT_DRAW=1 the copy is skipped and the parameter stays unbound (srv_bound clear). A desktop + // graphics pipeline that reads a root SRV would need the copy at its draw. + if (root_srv_at_draw()) { + InterlockedIncrement(&root_srv_copies_skipped); + return; + } const std::size_t bytes = readable_window(address, 0x10000); - const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes) : 0; + const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(self, address, bytes) : 0; static LONG logged; if (first_calls(logged, 4)) { char head[3 * 32 + 1]; @@ -3568,9 +4605,19 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) log("x2w-render root SRV %u at title 0x%llx: %zu bytes -> desktop 0x%llx [%s]", parameter, address, bytes, desktop, head); } if (!desktop) return; + InterlockedIncrement(&root_srv_copies_made); list->SetGraphicsRootShaderResourceView(parameter, desktop); pass.srv_bound |= 1u << parameter; } + +// Fixture export (startup_root_srv_draw): slot 44 root SRVs without an upload mapping since the process started. +// `skipped` counts only with X2W_D3D12_ROOT_SRV_AT_DRAW=1; `copied` counts every copy into the upload ring. +extern "C" __declspec(dllexport) void x2w_d3d12_root_srv_copies(LONG* skipped, LONG* copied) +{ + if (skipped) *skipped = root_srv_copies_skipped; + if (copied) *copied = root_srv_copies_made; +} + // List slot 42 (desktop 38 + 4), SetGraphicsRootConstantBufferView(parameter, title GPU address). // A translated shader reads a root CBV through the same pointer source as a root SRV (root_address). Nothing // is forwarded to the desktop list and srv_bound is left alone: bit 0 means a vertex-fetch SRV is bound. @@ -3589,16 +4636,49 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) } pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } +// List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. +void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) +{ + auto* list = recording(self); + const Pass& pass = pass_of(self); + // Slot 62 marks the wrapper itself. Slot 67 has no builder tag, so its request path is + // unchanged; a builder Dispatch is gated here regardless of the request-key field. + if (list && pass.pipeline && pass.pipeline->own().builder_pipeline && + !compute_builder_dispatch_allowed(self, "Dispatch")) return; + if (list && pass.pipeline && pass.pipeline->own().compute_request_key) { + scene_argument_probe(self, 17); + const char* refused = record_translated_dispatch(self, {{x, y, z}}); + scene_argument_probe(self, 22, nullptr, 0, refused); + return; + } + x2w_startup::ListDispatch request; + request.list_open = list != nullptr; + if (list) request.type = list->GetType(); + request.compute_pipeline = pass.compute_pipeline; + request.compute_root = pass.compute_root != nullptr; + request.compute_root_has_arguments = pass.compute_root_has_arguments; + request.root_matches_pipeline = pass.compute_pipeline_root && pass.compute_pipeline_root == pass.compute_root; + const UINT count = pass.compute_params ? static_cast<UINT>(pass.compute_params->size()) : 0; + request.root_arguments_bound = count <= 32 && (pass.compute_srv_bound & (count >= 32 ? ~0u : (1u << count) - 1)) == (count >= 32 ? ~0u : (1u << count) - 1); + request.x = x, request.y = y, request.z = z; + const x2w_startup::DispatchDecision decision = x2w_startup::decide_dispatch(request); + if (decision != x2w_startup::DispatchDecision::forward) { + static LONG refusals; + if (first_calls(refusals, 16)) + log("x2w-render Dispatch(%u, %u, %u) refused: %s", x, y, z, x2w_startup::dispatch_reason(decision)); + return; + } + list->Dispatch(x, y, z); +} extern LONG translated_draws, untranslated_draws, frame_number; -bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance); +void draw_startup_direct(Wrapper* self, UINT count, UINT instances, UINT start, UINT start_instance); // List slot 12, DrawInstanced. void __stdcall list_draw(Wrapper* self, UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) { auto* list = recording(self); Pass& pass = pass_of(self); if (list && !pass.pipeline_real) { - InterlockedIncrement(draw_translated(self, false, vertices, instances, first_vertex, 0, first_instance) ? &translated_draws - : &untranslated_draws); + draw_startup_direct(self, vertices, instances, first_vertex, first_instance); return; } if (list && pass.root_heap_flags) { @@ -3642,9 +4722,9 @@ std::unordered_map<u64, TextureWrite>& written_textures(); ID3D12Resource* sampled_address_texture(Wrapper* resource); bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" +#include "startup_stubs/d3d12_compute_dispatch.inl" #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" -#include "startup_stubs/list_copy_texture.inl" // X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the internal // refresh queue, and queue waits for those refreshes, just before the title's lists. A refresh that @@ -3696,6 +4776,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) for (UINT i = 0; i < count; ++i) { Wrapper* w = as_wrapper(lists[i]); if (w && w->own().kind == list_kind && w->own().list_ready) { + if (released_chunks_recycled(w)) continue; // its upload bytes were replaced: it is not executed ready.push_back(static_cast<ID3D12CommandList*>(w->own().real)); submitted.push_back(w); } @@ -3711,8 +4792,13 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) queue->ExecuteCommandLists(ready_count, native_lists.data()); } }); + if (trace_compute_outputs()) { + for (auto* recorded : wrappers) { + const auto id = InterlockedExchange64(&recorded->own().output_trace_recording, 0); + if (id) log("x2w-compute-output-submit list=%p recording=%lld queue=%p", recorded, id, self); + } + } retire_address_uploads(queue, native_lists); - retire_draw_sampler_heaps(queue, native_lists); note_submits(queue, wrappers); retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w); @@ -3911,6 +4997,9 @@ void* __stdcall queue_get_desc(void* a, void* b) // pointer is that memory (subresource offsets inside it are not modeled). Others map on desktop. HRESULT __stdcall resource_map(Wrapper* self, UINT subresource, const D3D12_RANGE* range, void** data) { + if (trace_compute_outputs() && (!range || range->End > range->Begin)) + trace_compute_output_use(nullptr, OutputUse::map, "map-guest-read-request", self, 0, range ? range->Begin : 0, + range ? range->End - range->Begin : (resource_info(self) ? resource_info(self)->console.Width : 0)); HRESULT hr = S_OK; void* mapped = self->own().title_memory; if (!mapped) hr = static_cast<ID3D12Resource*>(self->own().real)->Map(subresource, range, &mapped); @@ -3924,6 +5013,9 @@ HRESULT __stdcall resource_map(Wrapper* self, UINT subresource, const D3D12_RANG } void __stdcall resource_unmap(Wrapper* self, UINT subresource, const D3D12_RANGE* range) { + if (trace_compute_outputs() && (!range || range->End > range->Begin)) + trace_compute_output_use(nullptr, OutputUse::unmap, "unmap-guest-written-range", self, 0, range ? range->Begin : 0, + range ? range->End - range->Begin : (resource_info(self) ? resource_info(self)->console.Width : 0)); if (!self->own().title_memory) static_cast<ID3D12Resource*>(self->own().real)->Unmap(subresource, range); } @@ -3977,18 +5069,19 @@ void* __stdcall descriptor_heap_get_desc(void* a, void* b) return result; } // The title returns structures of at most 8 bytes in rax (this in rcx), larger ones through a hidden -// pointer passed first. If the second argument is a wrapper, the hidden-pointer form is used instead. +// pointer passed first. receiver() decides which argument is the object: a wrapper first is the object +// even when the caller left another live wrapper in the second register, which a call passing only +// `this` does not set. Only the (return buffer, object) form writes through the first argument. template <class T, class Get> std::uint64_t small_result(void* a, void* b, const char* method, Get get) { - if (Wrapper* w = as_wrapper(b)) { - const T value = get(w); - *static_cast<T*>(a) = value; - return reinterpret_cast<std::uint64_t>(a); - } - Wrapper* w = as_wrapper(a); - if (!w) fail(method, a, b); + void* result = nullptr; + Wrapper* w = receiver(a, b, &result, method); const T value = get(w); + if (w != a) { + *static_cast<T*>(result) = value; + return reinterpret_cast<std::uint64_t>(result); + } std::uint64_t bits = 0; static_assert(sizeof(T) <= sizeof(bits)); std::memcpy(&bits, &value, sizeof(T)); @@ -4067,6 +5160,7 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR // Some callers pass the 16-byte desktop descriptor; the words after it are then unrelated stack // data. The extension is taken only when it holds a pointer and exactly the heap's size. std::uint64_t title_memory = extra[0] >= 0x10000 && extra[1] == bytes ? extra[0] : 0; + const std::uint64_t supplied_memory = title_memory; // The title copies descriptors between heaps with its own memory copies. A view heap without // title memory therefore gets plain memory of ours as its CPU side, so that the view ids written // there (note_view) travel with those copies; the desktop heap behind it is still filled. A heap @@ -4078,6 +5172,11 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR return E_OUTOFMEMORY; } Wrapper* w = wrap(heap, descriptor_heap_kind); + if (!w) { + if (title_memory != supplied_memory) VirtualFree(reinterpret_cast<void*>(title_memory), 0, MEM_RELEASE); + heap->Release(); + return E_OUTOFMEMORY; + } if (title_memory) { w->own().title_cpu = title_memory; AcquireSRWLockExclusive(&descriptor_lock); @@ -4095,6 +5194,39 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR return S_OK; } +// A null R8G8B8A8_UNORM SRV of a texture dimension (2 to 10; any other value gives texture 2D). A null resource +// reads no more of the description than its format and dimension. +D3D12_SHADER_RESOURCE_VIEW_DESC null_srv_desc(unsigned dimension) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.ViewDimension = static_cast<D3D12_SRV_DIMENSION>(x2w_view_dimension::refused_srv_null_dimension(dimension)); + switch (desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; + default: desc.Texture2D.MipLevels = 1; break; + } + return desc; +} + +// X2W_D3D12_VIEW_DEFAULTS (view_dimension.h): which slots give an unknown-dimension view the resource's default view. +x2w_view_dimension::DefaultViews view_defaults_mode() +{ + static const x2w_view_dimension::DefaultViews mode = [] { + char value[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_VIEW_DEFAULTS", value, sizeof(value)); + return x2w_view_dimension::default_views_mode(n && n < sizeof(value) ? value : nullptr); + }(); + return mode; +} + // Device view slots: forwarded with the destination CPU handle (argument D, 0-based after the // object) translated from title to desktop. // Desktop removes the device (DXGI_ERROR_INVALID_CALL) on view calls it rejects, so they are checked @@ -4105,13 +5237,26 @@ template <int N, int D> __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) { Timed timed(time_view); - // UAV, RTV and DSV views keep the resource's old lifetime; slot-18 SRVs stay in the retire class as long as - // their descriptor slots are tracked by shadow_slot and translated draws hold bound resources with retire_hold. - if constexpr (N >= 19 && N <= 21) retire_leave_class(reinterpret_cast<const void*>(a), RetireLeft::view); - if constexpr (N == 19) retire_leave_class(reinterpret_cast<const void*>(b), RetireLeft::view); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); + // Slots 18-21 name a resource in a descriptor slot. While shadow_slot() tracks the destination, note_view() owns the + // slot's reference: the view (slot 19 for its resource and its counter resource) holds the resource in the retire + // class until the slot is overwritten, copied over, or its heap is destroyed. Without a tracked slot the shim cannot + // follow the descriptor, so the use takes the resource out of the class for good, as before. + if constexpr (N >= 19 && N <= 21) { + bool tracked = false; + if (args[D]) { + AcquireSRWLockShared(¬e_lock); + tracked = shadow_slot(args[D]) != nullptr; + ReleaseSRWLockShared(¬e_lock); + } + if (!tracked) { + retire_leave_class(reinterpret_cast<const void*>(a), RetireLeft::view); + if constexpr (N == 19) retire_leave_class(reinterpret_cast<const void*>(b), RetireLeft::view); + } + } + // No desktop destination handle: the view stays title-side, where no shadow slot can follow it. if (!args[D]) { if constexpr (N == 18) retire_leave_class(reinterpret_cast<const void*>(a), RetireLeft::view); return 0; @@ -4119,21 +5264,92 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) const auto record_view = [&](bool materialized) { const u64 raw[4] = {a, b, c, d}; const int described = N == 19 ? 2 : (N == 17 || N == 22) ? 0 : 1; - const std::size_t described_bytes = N == 17 ? 16 : N == 22 ? 52 : N == 18 ? 40 : N == 19 ? 40 : N == 20 ? 20 : 16; + const std::size_t described_bytes = N == 17 ? 16 : N == 22 ? 52 : N == 18 ? ViewRecord::srv_desc_bytes : + N == 19 ? ViewRecord::uav_desc_bytes : N == 20 ? 20 : 16; note_view(N, (N >= 18 && N <= 21) ? raw[0] : 0, N == 19 ? raw[1] : 0, reinterpret_cast<const void*>(raw[described]), described_bytes, title_dest, args[D], materialized); }; const char* skip = nullptr; + bool default_view = false; + bool record_refused_uav = false; if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast<ID3D12Resource*>(args[0])->GetDesc().Flags; if (N == 18 && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) skip = "resource denies shader resource views"; - if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) skip = "resource lacks unordered access"; + if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + skip = "resource lacks unordered access"; + record_refused_uav = true; + } if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; + // Every view description of slots 18-21 starts with Format, then ViewDimension. + const u64 described = N == 19 ? args[2] : args[1]; + UINT view_dimension = 0; + if (!skip && described && x2w_local::readable(reinterpret_cast<const void*>(described), 8)) { + std::memcpy(&view_dimension, reinterpret_cast<const unsigned char*>(described) + 4, sizeof(view_dimension)); + const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast<ID3D12Resource*>(args[0])->GetDesc(); + const auto dimension = static_cast<unsigned>(resource_desc.Dimension); + if (view_dimension == 0) { + // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. By default only + // SRVs (slot 18) get one; UAV, RTV and DSV need X2W_D3D12_VIEW_DEFAULTS=all (view_dimension.h). + const auto mode = view_defaults_mode(); + if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast<unsigned>(resource_desc.Format), mode)) + default_view = true; + else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast<unsigned>(resource_desc.Format), + x2w_view_dimension::DefaultViews::all)) + skip = mode == x2w_view_dimension::DefaultViews::off + ? "unknown view dimension, and default views are off (X2W_D3D12_VIEW_DEFAULTS=off)" + : "unknown view dimension; a default view of this type needs X2W_D3D12_VIEW_DEFAULTS=all"; + else + skip = "unknown view dimension, and the resource has no default view"; + static LONG unknown_dimension; + if (first_calls(unknown_dimension, 6)) + log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, + *reinterpret_cast<const UINT*>(described), dimension, resource_desc.Format, + default_view ? "default view" : "skipped"); + } else if (!x2w_view_dimension::fits(N, view_dimension, dimension)) { + skip = "view dimension does not suit the resource"; + static LONG mismatched; + if (first_calls(mismatched, 6)) + log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, + x2w_view_dimension::needed(N, view_dimension), dimension); + } else if constexpr (N == 19) { + if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE3D && + x2w_local::readable(reinterpret_cast<const void*>(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast<const void*>(described), sizeof(view)); + skip = volume_uav_range_error(resource_desc, view.Texture3D); + record_refused_uav = skip != nullptr; + } else if (view_dimension == D3D12_UAV_DIMENSION_TEXTURE1D && + x2w_local::readable(reinterpret_cast<const void*>(described), sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC))) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + std::memcpy(&view, reinterpret_cast<const void*>(described), sizeof(view)); + if (view.Texture1D.MipSlice >= resource_desc.MipLevels) skip = "an output 1D texture mip is outside the resource"; + record_refused_uav = skip != nullptr; + } + } + } } + // Replace a refused SRV in both the desktop heap and the descriptor record. A skipped UAV, RTV or DSV + // does not write a replacement to the desktop heap, so its previous descriptor record must stay live. + const auto refuse_view = [&] { + if constexpr (N == 18) { + UINT requested = D3D12_SRV_DIMENSION_TEXTURE2D; + if (args[1] && x2w_local::readable(reinterpret_cast<const void*>(args[1]), 8)) + std::memcpy(&requested, reinterpret_cast<const unsigned char*>(args[1]) + 4, sizeof(requested)); + const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = null_srv_desc(requested); + device_of(self)->CreateShaderResourceView(nullptr, &null_view, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(args[D])}); + record_view(false); + } else if constexpr (N == 17) { + record_view(false); // Translated constant-buffer views use only the descriptor record. + } else if constexpr (N == 19) { + // A translated compute Dispatch tells this refusal from a descriptor that holds no view by the record. + // A refused creation leaves a descriptor that still holds a live view as it is. + if (record_refused_uav && !descriptor_has_live_view(args[D], title_dest)) record_view(false); + } + }; if (skip) { - record_view(false); + refuse_view(); static LONG skipped; if (first_calls(skipped, 6)) log("x2w-d3d12 Device::slot%d view skipped: %s", N, skip); return 0; @@ -4155,7 +5371,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) const auto actual = resource->GetDesc().Format; const auto verdict = x2w_startup::packed_view(mapped, actual, x2w_startup::packed_stand_in_of(resource)); if (verdict == x2w_startup::PackedView::refused) { - record_view(false); + refuse_view(); static LONG refused; if (first_calls(refused, 6)) log("x2w-d3d12 Device::slot%d view skipped: packed format %d on a texture of format %d that does not stand in for it", @@ -4183,6 +5399,8 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) *reinterpret_cast<const D3D12_RENDER_TARGET_VIEW_DESC*>(b), null_rtv)) args[1] = reinterpret_cast<u64>(&null_rtv); } + if (default_view) args[desc_index] = 0; + const LONG removed_before = removal_reported; const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view @@ -4199,6 +5417,19 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if ((N == 20 || N == 21) && args[0] && created) note_view_target(args[D], reinterpret_cast<ID3D12Resource*>(args[0]), N); check_device("Device view", N); + if (!removed_before && removal_reported && N >= 18 && N <= 21) { + // The view that removed the device: its forwarded description and the resource's shape. + char bytes[3 * 40 + 1] = {}; + const u64 described = args[desc_index]; + if (described) hex_text(reinterpret_cast<const void*>(described), 40, bytes, sizeof(bytes)); + log("x2w-d3d12 Device::slot%d removing view desc %s", N, described ? bytes : "(null)"); + if (args[0]) { + const D3D12_RESOURCE_DESC rd = reinterpret_cast<ID3D12Resource*>(args[0])->GetDesc(); + log("x2w-d3d12 Device::slot%d removing view resource: dim=%d %llux%u depth/array=%u mips=%u fmt=%d samples=%u flags=0x%x", N, + rd.Dimension, static_cast<unsigned long long>(rd.Width), rd.Height, rd.DepthOrArraySize, rd.MipLevels, rd.Format, + rd.SampleDesc.Count, static_cast<UINT>(rd.Flags)); + } + } static LONG calls; if (first_calls(calls)) log("x2w-d3d12 Device::slot%d view(0x%llx, 0x%llx, 0x%llx, 0x%llx) dest 0x%llx -> 0x%llx", N, a, b, c, d, @@ -4237,6 +5468,45 @@ void __stdcall device_copy_descriptors_simple(Wrapper* self, UINT count, u64 des if (first_calls(calls)) log("x2w-d3d12 Device::CopyDescriptorsSimple count=%u dest=0x%llx src=0x%llx type=%d", count, dest, src, type); } +// Slot 61 accepts the extended console sampler description; its destination is a CPU handle. +void __stdcall device_console_sampler(Wrapper* self, const UINT* words, u64 destination) +{ + if (!words || !x2w_local::readable(words, 27 * sizeof(UINT))) return; + const auto handle = desktop_cpu_handle(destination); + if (!handle) return; + D3D12_SAMPLER_DESC sampler{}; + const auto address_valid = [](UINT value) { + return value >= D3D12_TEXTURE_ADDRESS_MODE_WRAP && value <= D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE; + }; + if (words[1] > 3 || words[2] > 3 || words[3] > 2 || words[5] > 2 || + words[16] > D3D12_COMPARISON_FUNC_ALWAYS || !std::all_of(words + 6, words + 9, address_valid)) { + sampler = x2w_startup::border_sampler(); + device_of(self)->CreateSampler(&sampler, {static_cast<SIZE_T>(handle)}); + note_view(22, 0, 0, &sampler, sizeof(sampler), destination, handle); + static LONG refused; + if (first_calls(refused, 4)) log("x2w-d3d12 unsupported console sampler fields; using border sampler"); + return; + } + sampler.AddressU = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(words[6]); + sampler.AddressV = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(words[7]); + sampler.AddressW = static_cast<D3D12_TEXTURE_ADDRESS_MODE>(words[8]); + sampler.ComparisonFunc = static_cast<D3D12_COMPARISON_FUNC>((std::max)(1u, words[16])); + const auto reduction = words[5] == 1 ? D3D12_FILTER_REDUCTION_TYPE_MINIMUM : + words[5] == 2 ? D3D12_FILTER_REDUCTION_TYPE_MAXIMUM : + words[16] > 1 && words[16] < 8 ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON : D3D12_FILTER_REDUCTION_TYPE_STANDARD; + const bool anisotropic = words[1] >= 2 || words[2] >= 2; + sampler.Filter = anisotropic ? D3D12_ENCODE_ANISOTROPIC_FILTER(reduction) : + D3D12_ENCODE_BASIC_FILTER(words[2] & 1, words[1] & 1, words[3] == 2 ? 1u : 0u, reduction); + sampler.MaxAnisotropy = anisotropic ? std::clamp(words[13], 1u, 16u) : 1u; + std::memcpy(&sampler.MinLOD, words + 9, sizeof(float)); + std::memcpy(&sampler.MaxLOD, words + 10, sizeof(float)); + if (!words[3]) sampler.MaxLOD = sampler.MinLOD; + std::memcpy(&sampler.MipLODBias, words + 11, sizeof(float)); + std::memcpy(sampler.BorderColor, words + 17, sizeof(sampler.BorderColor)); + device_of(self)->CreateSampler(&sampler, {static_cast<SIZE_T>(handle)}); + note_view(22, 0, 0, &sampler, sizeof(sampler), destination, handle); +} + // Device slot 23, desktop CopyDescriptors(destCount, destStarts, destSizes, srcCount, srcStarts, srcSizes, type). void __stdcall device_copy_descriptors(Wrapper* self, UINT dest_count, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, const UINT* dest_sizes, UINT src_count, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, @@ -4321,6 +5591,10 @@ HRESULT __stdcall device_create_command_list_x(Wrapper* self, const void* desc, allocator, pso, text, static_cast<unsigned long>(hr)); if (FAILED(hr)) return hr; Wrapper* child = wrap(list, list_kind); + if (!child) { + list->Release(); + return E_OUTOFMEMORY; + } child->own().list_device = self; *out = child; return S_OK; @@ -4360,6 +5634,70 @@ struct ExistingHeap { }; std::vector<std::pair<void*, ExistingHeap>> existing_heaps; +// Lifetime boundary: one cross-adapter page alias per (heap, page) at a title address, kept for as long as +// this module is loaded, because the GPU may still read a page the title keeps live for the device's +// lifetime. It is the function-local static of placed_page_aliases() below, so it is destroyed during +// this module's CRT teardown -- see startup_stubs/d3d12_teardown.h for the two detaches. On process exit +// the display driver may already be stopped, so the placed buffers are detached and nothing reaches it; +// FreeLibrary leaves the process and the driver alive and the pages release their objects normally. The +// heap and page words are plain addresses, not owned. Each owned buffer is accounted for on the path it +// took and, with X2W_TEARDOWN_REPORT, reported as one x2w-teardown pages line. +struct PlacedPageAliases { + struct Page { + ID3D12Heap* heap; + u64 page; + x2w_startup::ComPtr<ID3D12Resource> resource; + }; + using iterator = std::array<Page, 64>::iterator; + iterator begin() { return entries.begin(); } + iterator end() { return entries.end(); } + + // Test hook (startup_teardown_unload, #2572; the review of the ownership change asked for one): + // enters one alias for a heap and page the caller owns, where the translated indirect address route + // would keep it after its first call. False when that pair is already there or the cache is full. No + // real path calls it, and the entry keeps the heap as a key only, as the route does. + bool insert_for_test(ID3D12Heap* heap, u64 page, ID3D12Resource* resource) + { + if (!heap || !resource) return false; + for (const Page& entry : entries) + if (entry.heap == heap && entry.page == page) return false; + for (Page& entry : entries) { + if (entry.heap) continue; + entry.resource = resource; // AddRef: the cache owns this reference + entry.page = page; + entry.heap = heap; + return true; + } + return false; + } + + ~PlacedPageAliases() + { + const bool detach = x2w_startup::d3d12_process_terminating && !x2w_startup::teardown_guard_disabled("pages"); + unsigned detached = 0, released = 0; + for (auto& entry : entries) { + if (!entry.resource) continue; + if (detach) { + entry.resource.Detach(); + ++detached; + } else { + ++released; + } + } + x2w_startup::teardown_report("pages", detached, released); + } + std::array<Page, 64> entries{}; +}; + +// The cache lives in its own accessor so the fixture probe can reach it, the way +// indexed_validation_pipeline(device) exposes the validation pipeline. One function-local static, built +// on the first translated indirect address. +PlacedPageAliases& placed_page_aliases() +{ + static PlacedPageAliases pages{}; + return pages; +} + IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 bytes) { static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_INDIRECT_ADDRESS_ALIAS"); @@ -4383,8 +5721,8 @@ IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 by [&](const auto& entry) { return entry.first == memory.base; }); if (known == existing_heaps.end()) return {}; auto* heap = known->second.real; - struct Page { ID3D12Heap* heap; u64 page; x2w_startup::ComPtr<ID3D12Resource> resource; }; - static std::array<Page, 64> pages{}; + using Page = PlacedPageAliases::Page; + auto& pages = placed_page_aliases(); auto it = std::find_if(pages.begin(), pages.end(), [&](const Page& entry) { return entry.heap == heap && entry.page == page; }); if (it != pages.end()) return {it->resource.Get(), offset}; it = std::find_if(pages.begin(), pages.end(), [](const Page& entry) { return !entry.heap; }); @@ -4413,6 +5751,11 @@ HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE ID3D12Resource* resource, bool aliased, x2w_budget::Ticket* backing_budget, void** out) { Wrapper* w = wrap(resource, resource_kind); + if (!w) { + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().discard(resource); + resource->Release(); + return E_OUTOFMEMORY; + } if (release_retired_enabled()) w->own().retire_never = static_cast<std::uint8_t>(RetireNever::buffer); w->own().title_memory = address; const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; @@ -4483,6 +5826,10 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (FAILED(texture_hr)) return texture_hr; x2w_startup::mark_packed_stand_in(created, desktop_format(desc->Format)); Wrapper* w = wrap(created, resource_kind); + if (!w) { + created->Release(); + return E_OUTOFMEMORY; + } w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; note_resource(w, desc, 0); @@ -4494,9 +5841,8 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 // buffer is committed in it: one region-information call for a fully committed private // allocation, otherwise a region walk that stops at the end of the buffer. The GPU cannot fault in a lazily // mapped physical page (X2W_XMEM_LAZY_COMMIT), so the buffer's pages are committed first; a lazy startup - // block (X2W_XMEM_LAZY_STARTUP) is committed whole, as the heap opened on it is reused for the block. + // block (X2W_XMEM_LAZY_STARTUP) is committed whole only right before OpenExistingHeapFromAddress opens it. x2w_local::commit_lazy(address, static_cast<std::size_t>(desc->Width)); - x2w_local::commit_lazy_block(address); x2w_startup::PlacedBufferRange range; const bool committed = x2w_startup::measure_placed_buffer(address, desc->Width, range); InterlockedIncrement64(&placed_buffer_calls); @@ -4511,7 +5857,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? static_cast<D3D12_RESOURCE_STATES>(state) : D3D12_RESOURCE_STATE_COMMON; if (initial_state != D3D12_RESOURCE_STATE_COMMON && !(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return E_INVALIDARG; - const UINT64 offset = static_cast<char*>(address) - static_cast<char*>(base); + UINT64 offset = static_cast<char*>(address) - static_cast<char*>(base); // X2W_D3D12_LINEAR_BUFFERS=1 or copy: shared or copied at submit (linear_buffer_backing.h). Where // neither keeps its guarantees, the default backing below is kept and the refusal recorded. X2wLinearBufferInfo linear{}; @@ -4548,9 +5894,33 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 HRESULT hr = S_OK; // Desktop only accepts 64 KiB-aligned offsets, a private (VirtualAlloc) allocation, and a buffer // that lies inside that one allocation. Attempts that cannot succeed are skipped: each failure - // throws inside D3D12Core. + // throws inside D3D12Core. OpenExistingHeapFromAddress also wraps the entire allocation, so the + // opt-in X2W_D3D12_CAP_EXISTING_HEAP=1 skips allocations above 256 MiB (or of unknown size) to keep + // multi-GiB startup blocks out of WorkingSetSize/NonLocal. The cap is opt-in because a capped buffer + // falls back to a copied placement that CopyBufferRegion (slot 15) refuses as title_backed_source, + // losing a late guest write; the default keeps the formerly aliased path so contents stay authoritative. + // A buffer at an aligned nonzero offset inside an eligible lazy startup block leaves [base, address) + // MEM_RESERVE after the span-only commit_lazy; commit the eligible block before re-measuring so + // it can alias without touching unaligned or out-of-bounds allocations (and, with the cap, > 256 MiB). + static const bool cap_existing_heap = x2w_local::env_on("X2W_D3D12_CAP_EXISTING_HEAP"); + if (!range.covered && !range.region_info && range.type == MEM_PRIVATE && + initial_state != D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && + x2w_startup::can_commit_lazy_placed_buffer(address, desc->Width, + cap_existing_heap ? x2w_startup::unplaced_max_span : 0)) { + x2w_local::commit_lazy_block(address); + if (x2w_startup::measure_placed_buffer(address, desc->Width, range)) { + if (range.region_info) InterlockedIncrement64(&placed_buffer_region_info); + InterlockedAdd64(&placed_buffer_queries, range.queries); + base = range.base; + offset = static_cast<char*>(address) - static_cast<char*>(base); + } else { + range.covered = false; + } + } if ((offset & 0xFFFF) || !range.covered || range.type != MEM_PRIVATE || - initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) hr = E_INVALIDARG; + initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE || + (cap_existing_heap && !x2w_startup::unplaced_existing_heap_allowed(x2w_startup::allocation_bytes(base)))) + hr = E_INVALIDARG; if (SUCCEEDED(hr)) { std::lock_guard lock(placed_mutex); for (const auto& [known, h] : existing_heaps) { @@ -4560,6 +5930,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 } } if (!heap) { + x2w_local::commit_lazy_block(address); ID3D12Device3* device3 = nullptr; hr = device_of(self)->QueryInterface(IID_PPV_ARGS(&device3)); if (SUCCEEDED(hr)) { @@ -4600,6 +5971,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 #include "d3d12_memory_srv.inl" #include "startup_stubs/list_copy.inl" +#include "startup_stubs/list_copy_texture.inl" // X2W_D3D12_RELEASE_RETIRED=1 (docs/startup-runtime.md#d3d12-resource-budget): the desktop object of a retire class // member is released after its final guest Release once (1) the release-time fence of every queue has passed (each queue @@ -4684,8 +6056,10 @@ void retire_drop_heap_views(Wrapper* heap) const std::uint32_t id = h.shadow[i]; if (!id) continue; h.shadow[i] = 0; - if (id - 1 < view_records().size() && view_records()[id - 1].slot == 18 && view_materialized()[id - 1]) - retire_release_view_ref(reinterpret_cast<const void*>(view_records()[id - 1].resource)); + // Every tracked view slot loses the ref it held: slots 18-21, slot 19 for the resource and its counter. + if (id - 1 < view_records().size() && view_materialized()[id - 1]) + view_refs_release(view_records()[id - 1].slot, view_records()[id - 1].resource, + view_records()[id - 1].counter); } } ReleaseSRWLockExclusive(¬e_lock); @@ -4859,34 +6233,6 @@ void retire_resource(Wrapper* w) if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch } -// A null SRV of the dimension the title's view had (the draw path binds the same R8G8B8A8_UNORM null for a view that -// resolves to nothing). A null resource reads no more of the description than its format and dimension. -D3D12_SHADER_RESOURCE_VIEW_DESC retire_null_srv_desc(const ViewRecord& record) -{ - D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; - desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - if (record.desc_bytes >= 40) { - D3D12_SRV_DIMENSION dimension; - std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); - if (dimension >= D3D12_SRV_DIMENSION_TEXTURE1D && dimension <= D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) - desc.ViewDimension = dimension; - } - switch (desc.ViewDimension) { - case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; - default: desc.Texture2D.MipLevels = 1; break; - } - return desc; -} - // True when the release-time fence of every queue has passed (retire_lock held). bool retire_fences_reached(const RetiredResource& item) { @@ -4896,106 +6242,10 @@ bool retire_fences_reached(const RetiredResource& item) return reached; } -// X2W_D3D12_RELEASE_RETIRED_VIEWS=1: a released class member whose release-time fences have passed and that only -// tracked slot-18 descriptor slots still name gets those slots replaced by null descriptors, so the main drain loop can -// free it. Every slot of every heap that has a shadow is handled, copies included (they are counted the same way). For -// each slot, under note_lock: the shadow entry is cleared and its ref dropped, and the desktop descriptor is rewritten -// as a null SRV of the same dimension. The view records that name the resource then lose it (so a token that a raw -// title copy left behind resolves to nothing), and the token in title descriptor memory is cleared when it still -// carries the id. A slot that cannot be rewritten keeps its ref, and the resource stays retained. Nothing waits. -// Why this cannot reach GPU work: translated draws never bind a title heap. They build their own descriptors from the -// title's tokens at draw time and retire_hold what they sample, so a descriptor of a title heap is read by no recorded -// list or submission (ClearUnorderedAccessView binds a heap for UAV slots only, and those are not touched here). -void retire_null_ready_views() -{ - std::vector<Wrapper*> ready; - try { - ready.reserve(64); - } catch (const std::bad_alloc&) { - return; - } - if (!TryAcquireSRWLockShared(&retire_lock)) return; - for (const RetiredResource& item : retired_resources) { - Wrapper* w = item.wrapper; - if (ready.size() == ready.capacity()) break; - if (w->own().retire_hold_missed || w->own().retire_views_stuck || !retire_fences_reached(item)) continue; - if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) <= 0) continue; - if (InterlockedCompareExchange(&w->own().refs, 0, 0) != 0) continue; // referenced again: leave its views - ready.push_back(w); - } - ReleaseSRWLockShared(&retire_lock); - if (ready.empty()) return; - - struct Cleared { - u64 title_cpu; - std::uint32_t index, increment, id; - }; - std::vector<Cleared> cleared; - std::size_t stuck = 0; - // draw_lock first, in the order draw_translated takes them: a draw holds it from reading a view record until it - // retire_holds the texture, so clearing the records under it means a draw either recorded its hold already or - // resolves the token to nothing. - if (!TryAcquireSRWLockExclusive(&draw_lock)) return; - if (!TryAcquireSRWLockExclusive(¬e_lock)) { - ReleaseSRWLockExclusive(&draw_lock); - return; - } - try { - std::unordered_set<std::uint32_t> ids; // view ids that name a ready resource - for (std::uint32_t id = 0; id < view_records().size(); ++id) { - const ViewRecord& record = view_records()[id]; - if (record.slot != 18 || !view_materialized()[id]) continue; - if (std::find(ready.begin(), ready.end(), reinterpret_cast<Wrapper*>(record.resource)) != ready.end()) - ids.insert(id); - } - ID3D12Device* const device = the_device ? device_of(the_device) : nullptr; - for (const HeapInfo& h : heap_infos()) { - if (!h.shadow || ids.empty() || !device || !h.desktop_cpu) continue; - for (std::uint32_t i = 0; i < h.count; ++i) { - const std::uint32_t slot_id = h.shadow[i]; - if (!slot_id || !ids.count(slot_id - 1)) continue; - const ViewRecord& record = view_records()[slot_id - 1]; - const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = retire_null_srv_desc(record); - device->CreateShaderResourceView(nullptr, &null_view, - D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(h.desktop_cpu + u64{i} * h.increment)}); - h.shadow[i] = 0; - retire_release_view_ref(reinterpret_cast<const void*>(record.resource)); - if (h.title_cpu && h.title_cpu != h.desktop_cpu) cleared.push_back({h.title_cpu, i, h.increment, slot_id - 1}); - } - } - for (Wrapper* w : ready) { - if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { - w->own().retire_views_stuck = true; - ++stuck; - continue; - } - for (std::uint32_t id : ids) - if (view_records()[id].resource == reinterpret_cast<u64>(w)) view_records()[id].resource = 0; - } - } catch (const std::bad_alloc&) { - } - ReleaseSRWLockExclusive(¬e_lock); - ReleaseSRWLockExclusive(&draw_lock); - for (const Cleared& slot : cleared) { - const u64 token = slot.title_cpu + u64{slot.index} * title_descriptor_stride(slot.title_cpu, slot.increment); - if (!title_backed(token, 32) || !x2w_local::writable(reinterpret_cast<void*>(token), 32)) continue; - std::uint32_t words[2]; - std::memcpy(words, reinterpret_cast<const void*>(token), sizeof(words)); - if (words[0] == view_token_magic && words[1] == slot.id) - InterlockedCompareExchange(reinterpret_cast<volatile LONG*>(token), 0, static_cast<LONG>(view_token_magic)); - } - if (stuck) { - static LONG reported; - if (first_calls(reported, 4)) log("x2w-d3d12 retire: %zu released textures keep an untracked descriptor; they stay retained", stuck); - } -} - - // Never blocks: a contended lock or an unfinished queue leaves the work for the next call. void drain_retired_resources() { if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; - if (release_retired_views_enabled()) retire_null_ready_views(); constexpr std::size_t batch = 256; struct RetiredDrop { Wrapper* wrapper; @@ -5026,10 +6276,7 @@ void drain_retired_resources() ++i; continue; } - bool reached = item.targets.size() <= retire_queues.size(); - for (std::size_t q = 0; q < item.targets.size() && reached; ++q) - reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; - if (!reached) { + if (!retire_fences_reached(item)) { ++i; continue; } @@ -5094,7 +6341,8 @@ void drain_retired_resources() // is recorded and no line is built. bool retire_reasons_enabled() { - static const bool on = release_retired_enabled() && x2w_budget::enabled() && x2w_local::env_on("X2W_D3D12_RETIRE_REASONS"); + static const bool on = release_retired_enabled() && x2w_budget::enabled() && + (legacy_retire_view_stats() || x2w_local::env_on("X2W_D3D12_RETIRE_REASONS")); return on; } @@ -5288,30 +6536,87 @@ extern "C" __declspec(dllexport) std::size_t x2w_d3d12_retire_reasons_line(char* return retire_reasons_line(out, capacity); } +// The census heartbeat line, or an empty string when X2W_D3D12_VIEW_CENSUS is not set. +std::size_t view_census_line(char* out, std::size_t capacity) +{ + if (!out || !capacity) return 0; + out[0] = 0; + if (!view_census_enabled()) return 0; + AcquireSRWLockShared(¬e_lock); + const std::size_t used = view_census_format(out, capacity, "distinct by slot"); + ReleaseSRWLockShared(¬e_lock); + return used; +} + +// Fixture export (startup_view_census): the line the heartbeat logs, now. +extern "C" __declspec(dllexport) std::size_t x2w_d3d12_view_census_line(char* out, std::size_t capacity) +{ + return view_census_line(out, capacity); +} + +// Fixture only (startup_view_alloc): see view_allocation_gate. +extern "C" __declspec(dllexport) void x2w_d3d12_fail_view_allocations(int site, LONG count) +{ + if (site >= 0 && site < view_allocation_sites) InterlockedExchange(&view_allocations_to_fail[site], count); +} + +// Fixture probe (startup_view_alloc): the sizes of the three view containers, the id + 1 that the tracked slot of a +// title descriptor handle names (0: none), and whether a resource is still in the retire class. +struct ViewStoreProbe { + unsigned long long records, materialized, ids, records_capacity, materialized_capacity; + unsigned shadow, view_refs, retire_when_idle; +}; +extern "C" __declspec(dllexport) void x2w_d3d12_view_probe(unsigned long long title_handle, void* resource, ViewStoreProbe* out) +{ + *out = {}; + out->shadow = shadow_id(desktop_cpu_handle(title_handle)); + AcquireSRWLockShared(¬e_lock); + out->records = view_records().size(); + out->materialized = view_materialized().size(); + out->ids = view_ids().size(); + out->records_capacity = view_records().capacity(); + out->materialized_capacity = view_materialized().capacity(); + ReleaseSRWLockShared(¬e_lock); + if (Wrapper* r = as_wrapper(resource); r && r->own().kind == resource_kind) { + out->view_refs = static_cast<unsigned>(InterlockedCompareExchange(&r->own().retire_view_refs, 0, 0)); + out->retire_when_idle = r->own().retire_when_idle; + } +} + +// Fixture-only: the next `count` wrapper allocations fail as an exhausted heap would (#2653). +extern "C" __declspec(dllexport) void x2w_d3d12_fail_wraps(LONG count) +{ + InterlockedExchange(&wraps_to_fail, count); +} + // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many -// resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. +// resources the open recording of a list moved out of COMMON, how many it holds, and how many tracked descriptor slots +// hold the resource (retire_view_refs, slots 18-21). Counts entries only. struct RetireProbe { unsigned cache_entries; unsigned list_states; unsigned list_holds; + unsigned view_refs; }; extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, void* list, RetireProbe* out) { if (!out) return FALSE; *out = {}; if (!release_retired_enabled()) return FALSE; // like x2w_d3d12_budget_snapshot: nothing to report without the switch - if (Wrapper* r = as_wrapper(resource); r && r->own().kind == resource_kind && r->own().real) { - auto* real = static_cast<ID3D12Resource*>(r->own().real); - AcquireSRWLockExclusive(&draw_lock); - out->cache_entries += static_cast<unsigned>(texture_uploads().count(real)); - ReleaseSRWLockExclusive(&draw_lock); - AcquireSRWLockShared(&target_lock); - for (const auto& view : view_targets()) out->cache_entries += view.second.resource == real; - ReleaseSRWLockShared(&target_lock); - AcquireSRWLockShared(&pending_writes_lock); - for (const auto& writes : pending_gpu_writes()) - out->cache_entries += static_cast<unsigned>(std::count(writes.second.begin(), writes.second.end(), real)); - ReleaseSRWLockShared(&pending_writes_lock); + if (Wrapper* r = as_wrapper(resource); r && r->own().kind == resource_kind) { + out->view_refs = static_cast<unsigned>(InterlockedCompareExchange(&r->own().retire_view_refs, 0, 0)); + if (auto* real = static_cast<ID3D12Resource*>(r->own().real)) { + AcquireSRWLockExclusive(&draw_lock); + out->cache_entries += static_cast<unsigned>(texture_uploads().count(real)); + ReleaseSRWLockExclusive(&draw_lock); + AcquireSRWLockShared(&target_lock); + for (const auto& view : view_targets()) out->cache_entries += view.second.resource == real; + ReleaseSRWLockShared(&target_lock); + AcquireSRWLockShared(&pending_writes_lock); + for (const auto& writes : pending_gpu_writes()) + out->cache_entries += static_cast<unsigned>(std::count(writes.second.begin(), writes.second.end(), real)); + ReleaseSRWLockShared(&pending_writes_lock); + } } if (Wrapper* l = as_wrapper(list); l && l->own().kind == list_kind) { if (l->own().pass) out->list_states = static_cast<unsigned>(pass_of(l).states.size()); @@ -5323,16 +6628,28 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } -// Fixture probe (startup_teardown_unload, #2572) for the two caches that keep desktop objects for a -// device: the indexed-validation pipeline (d3d12_draw.inl, bit 0) and the rectangle-list argument -// converter (rect_indirect_args.h, bit 1). Warms the selected caches the way their first real call -// would -- the validation pipeline directly, the converter through one record-only conversion, nothing -// executed -- and answers how many objects they now hold for `device`: the validation entry's device, -// root signature and pipeline (3), plus the converter entry's root signature and pipeline (2). The -// caller can warm one cache at a time to see each one release what it owns when the module is unloaded. -extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Device* device, UINT caches) -{ - if (!device || !caches || (caches & ~3u)) return 0; +// Fixture probe (startup_teardown_unload, #2572) for the four caches that keep desktop objects for a +// device, one bit each: the indexed-validation pipeline (d3d12_draw.inl, bit 1) and the rectangle-list +// argument converter (rect_indirect_args.h, bit 2), the placed page aliases of the translated indirect +// address route (bit 4) and the draw-dump readbacks (bit 8). Warms the selected caches the way their +// first real call would -- the validation pipeline directly, the converter through one record-only +// conversion, an alias entry on a placed buffer of this device, a recorded readback -- and answers how +// many objects they now hold for `device`: the validation entry's device, root signature and pipeline +// (3), the converter entry's root signature and pipeline (2), the alias entry's placed buffer (1), the +// readback entry's buffer and fence (2). The caller can warm one cache at a time to see each one release +// what it owns when the module is unloaded. +// +// `placed_heap` is how bit 4 hands the heap it creates over to the caller. The alias entry keeps that heap +// as a key only -- it owns no reference, as the route's heap belongs to the device's allocation -- so the +// one reference this probe holds is the caller's from the moment the entry is entered, and the caller must +// release it after the cache released the placed buffer (a heap must outlive the resources placed in it). +// Bit 4 is not warmed when `placed_heap` is null: an entry whose backing heap nobody owns is the leak this +// handover exists to rule out. Every other bit leaves `*placed_heap` null. +extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Device* device, UINT caches, + ID3D12Heap** placed_heap) +{ + if (placed_heap) *placed_heap = nullptr; + if (!device || !caches || (caches & ~15u)) return 0; UINT owned = 0; if (caches & 1u) { const auto& validation = indexed_validation_pipeline(device); @@ -5340,31 +6657,147 @@ extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Devic if (validation.root) ++owned; if (validation.pipeline) ++owned; } - if (!(caches & 2u)) return owned; - - x2w_startup::ComPtr<ID3D12CommandAllocator> allocator; - x2w_startup::ComPtr<ID3D12GraphicsCommandList> list; - if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || - FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, - IID_PPV_ARGS(&list)))) - return owned; - D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = 256; - buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - // convert() copies its 16 source words; an uninitialised buffer in the state it requires is enough. - x2w_startup::ComPtr<ID3D12Resource> source; - if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, - nullptr, IID_PPV_ARGS(&source)))) - return owned; - const auto scratch = x2w_startup::RectIndirectArguments::make_scratch(device); - if (scratch && x2w_startup::rect_indirect_arguments().convert(list.Get(), source.Get(), 0, scratch.Get())) - owned += 2; // the converter's root signature and pipeline for this device + if (caches & 2u) { + x2w_startup::ComPtr<ID3D12CommandAllocator> allocator; + x2w_startup::ComPtr<ID3D12GraphicsCommandList> list; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))) + return owned; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 256; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // convert() copies its 16 source words; an uninitialised buffer in the state it requires is enough. + x2w_startup::ComPtr<ID3D12Resource> source; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, + nullptr, IID_PPV_ARGS(&source)))) + return owned; + const auto scratch = x2w_startup::RectIndirectArguments::make_scratch(device); + if (scratch && x2w_startup::rect_indirect_arguments().convert(list.Get(), source.Get(), 0, scratch.Get())) + owned += 2; // the converter's root signature and pipeline for this device + } + if (!(caches & 12u)) return owned; + + // The two caches below hold desktop objects, as their real entries do: draw_dump_after() creates the + // readback buffer on the desktop device, and execute() creates the fence on the desktop device it + // reads from the desktop queue. Two shapes of device reach this probe. A title gets a wrapper from + // D3D12XboxCreateDevice (attach_device wraps the created device), and the desktop device is then the + // one behind it. A fixture creates its device without a parameter block, so that entry returns a + // plain D3D12CreateDevice() result: an unwrapped desktop device. The handle itself is the desktop + // device then. removal_device is not a fallback: attach_device is where it is written, so on the + // unwrapped path it is null or names another device. + Wrapper* wrapper = as_wrapper(device); + ID3D12Device* desktop = wrapper ? device_of(wrapper) : device; + + // Diagnostics for the fixture, off unless X2W_CACHE_PROBE_DEBUG is set: one line per step, so a probe + // that answers fewer objects than expected names the call that refused. Temporary, together with the + // two caches they measure. + char probe_debug[2]{}; + const bool trace = GetEnvironmentVariableA("X2W_CACHE_PROBE_DEBUG", probe_debug, sizeof(probe_debug)) != 0; + if (trace) + std::fprintf(stderr, "x2w-cache-probe device=%p wrapper=%p desktop=%p caches=0x%x\n", + static_cast<void*>(device), static_cast<void*>(wrapper), static_cast<void*>(desktop), caches); + + // Bit 4 needs an owner for the heap it creates, and that owner is the caller: with no out pointer + // there is nowhere to put the reference, so the alias is not warmed at all rather than entered on a + // heap nobody owns for the rest of the process. + if ((caches & 4u) && !placed_heap && trace) + std::fputs("x2w-cache-probe placed: no heap out pointer, bit 4 not warmed\n", stderr); + if ((caches & 4u) && placed_heap) { + // One placed buffer on a heap of this device, entered where the translated indirect address route + // keeps its aliases. The page word is only the cache key: no title address is involved here, and + // the entry never dereferences the heap. The route's buffers carry ALLOW_CROSS_ADAPTER; sharing + // them across adapters needs a heap opened for it and plays no part in the lifetime measured + // here, so this buffer is an ordinary placed buffer. + D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_HEAP_DESC heap_desc{}; + heap_desc.SizeInBytes = 65536; + heap_desc.Properties = properties; + heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; + x2w_startup::ComPtr<ID3D12Heap> heap; + const HRESULT heap_hr = desktop->CreateHeap(&heap_desc, IID_PPV_ARGS(&heap)); + if (trace) std::fprintf(stderr, "x2w-cache-probe heap hr=0x%08lx\n", static_cast<unsigned long>(heap_hr)); + if (FAILED(heap_hr)) return owned; + const D3D12_RESOURCE_DESC placed{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + x2w_startup::ComPtr<ID3D12Resource> alias; + const HRESULT placed_hr = desktop->CreatePlacedResource(heap.Get(), 0, &placed, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&alias)); + if (trace) std::fprintf(stderr, "x2w-cache-probe placed hr=0x%08lx\n", static_cast<unsigned long>(placed_hr)); + if (FAILED(placed_hr)) return owned; + { + std::lock_guard lock(placed_mutex); + auto& pages = placed_page_aliases(); + const bool entered = pages.insert_for_test(heap.Get(), 0x10000, alias.Get()); + unsigned used = 0; + for (const auto& entry : pages) + if (entry.heap) ++used; + if (trace) std::fprintf(stderr, "x2w-cache-probe insert=%d used=%u/64\n", entered ? 1 : 0, used); + if (entered) { + // The route's heap belongs to the device's allocation, not to an alias entry: the shim + // keeps it for the device's lifetime, and the entry only stores the pointer. This probe + // created its own heap, so the one reference it holds is not abandoned here but handed to + // the caller, who owns it from now on and releases it after the placed buffer this entry + // keeps -- a heap must outlive the resources placed in it. + *placed_heap = heap.Detach(); + ++owned; + } + } + } + if (caches & 8u) { + // One recorded draw readback: the READBACK buffer draw_dump_after() keeps and the queue fence + // execute() attaches once the copy is submitted. execute() builds both on the desktop device it + // reads from the desktop queue, so both are desktop objects here too. + D3D12_HEAP_PROPERTIES properties{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 256; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + x2w_startup::ComPtr<ID3D12Resource> staging; + x2w_startup::ComPtr<ID3D12Fence> fence; + const HRESULT staging_hr = desktop->CreateCommittedResource(&properties, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&staging)); + if (trace) std::fprintf(stderr, "x2w-cache-probe readback hr=0x%08lx\n", static_cast<unsigned long>(staging_hr)); + if (FAILED(staging_hr)) return owned; + const HRESULT fence_hr = desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + if (trace) std::fprintf(stderr, "x2w-cache-probe fence hr=0x%08lx\n", static_cast<unsigned long>(fence_hr)); + if (FAILED(fence_hr)) return owned; + const bool recorded = draw_dumps().record_for_test(std::move(staging), std::move(fence)); + if (trace) std::fprintf(stderr, "x2w-cache-probe record=%d\n", recorded ? 1 : 0); + if (recorded) owned += 2; + } return owned; } +// Fixture probe (startup_teardown_unload, #2572) for the ownership of the two caches above: hands the +// caller one reference to an object a warmed entry owns, so the fixture can watch that reference go away +// when the module is unloaded. `cache` and `slot`: 4/0 the placed buffer, 8/0 the readback buffer, 8/1 its +// fence; null for anything else. The caller's reference keeps the object alive after the module is gone, +// which is what makes its count readable then. +extern "C" __declspec(dllexport) IUnknown* x2w_d3d12_cached_object_probe(UINT cache, UINT slot) +{ + IUnknown* object = nullptr; + if (cache == 4u) { + std::lock_guard lock(placed_mutex); + auto& pages = placed_page_aliases(); + for (auto& entry : pages) { + if (!entry.resource) continue; + object = entry.resource.Get(); + break; + } + } else if (cache == 8u) { + object = draw_dumps().owned_for_test(slot); + } + if (!object) return nullptr; + object->AddRef(); + return object; +} + // Fixture probes (startup_resource_retire_title) for state the retire bookkeeping maintains for one resource. They read // the same maps the shim reads and never change them; the address index and the upload cache exist with and without // the switch, so these answer in both modes. @@ -5411,8 +6844,8 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, uns // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that // serves pageSize 2 (bits 14-15) from a 64 MiB block, then asserts that the block was used up: // the console runtime evidently takes committed-resource memory from XMemAlloc with allocatorId -// 0x80. Hypothesis used here: attributes = pageSize (2 from 4 MiB up, else 1) << 14 | 0x80 << 16 | -// log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its +// 0x80. Hypothesis used here: attributes = pageSize (2, a 2 MiB page, selected from 4 MiB up; else 1) +// << 14 | 0x80 << 16 | log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its // own memory and does not alias it. using XMemAllocHook = void*(__stdcall*)(SIZE_T, ULONGLONG); XMemAllocHook title_alloc_hook() @@ -5536,7 +6969,7 @@ HRESULT __stdcall placeholder_ok(Wrapper*, u64, u64, u64) { return S_OK; } // XboxBvhBuilder.dll, followed by SetName on the result. The bytecode is console GPU code, not DXIL, // so no desktop pipeline is built: the result is a placeholder PipelineState until shader translation // exists. Logs the root signature, bytecode address, length and first 32 bytes. -HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0, +HRESULT __stdcall device_create_compute_pipeline_x(Wrapper* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, u64 extra0, u64 extra1, const GUID* iid, void** out) { char text[48]; @@ -5554,9 +6987,11 @@ HRESULT __stdcall device_create_compute_pipeline_x(Wrapper*, const D3D12_COMPUTE static_cast<unsigned long long>(desc->CS.BytecodeLength), desc->NodeMask, desc->Flags, extra0, extra1, text, bytes); if (kind_for(*iid) != pipeline_kind) return E_NOINTERFACE; *out = wrap(nullptr, pipeline_kind); + if (!*out) return E_OUTOFMEMORY; auto* pipeline = static_cast<Wrapper*>(*out); note_pipeline(pipeline, 62, nullptr, desc, sizeof(*desc)); note_compute_binding_pipeline(pipeline, *desc); + note_compute_builder_pipeline(self, pipeline, _ReturnAddress()); return S_OK; } @@ -5587,13 +7022,14 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE D3D12_RASTERIZER_DESC rasterizer{}; bool has_rasterizer = false; bool compute = false; + ID3D12RootSignature* pipeline_root = nullptr; IndirectGraphicsPipeline graphics; u64 mesh86_key = 0; if (render_mode()) { char why[256] = ""; // Recognized desktop stages must reach the native path before the // guest cache creates a pending translation for any DXBC container. - real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics); + real_pipeline = build_stream_pipeline(desc, why, sizeof(why), compute, graphics, pipeline_root); bool mesh_cache_request = false; if (!real_pipeline) real_pipeline = try_cached_mesh86(*desc, why, sizeof(why), graphics, mesh_cache_request, mesh86_key); @@ -5605,7 +7041,12 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE log("x2w-render stream pipeline -> %s%s", real_pipeline ? "REAL desktop pipeline" : "placeholder: ", real_pipeline ? "" : why); } *out = wrap(real_pipeline, pipeline_kind); + if (!*out) { + if (real_pipeline) real_pipeline->Release(); + return E_OUTOFMEMORY; + } static_cast<Wrapper*>(*out)->own().compute_pipeline = real_pipeline && compute; + static_cast<Wrapper*>(*out)->own().pipeline_root = pipeline_root; static_cast<Wrapper*>(*out)->own().indirect_graphics = graphics; static_cast<Wrapper*>(*out)->own().mesh86_key = mesh86_key; note_pipeline(static_cast<Wrapper*>(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, @@ -5633,6 +7074,7 @@ bool is_fixed_mesh57_descriptor(const void* desc) ((!words[5] && !words[6]) || readable_stage(words[5], words[6])); } +#include "startup_stubs/native_mesh57.inl" // Device slots 57 and 67 (Xbox order): (desc*, riid, ppv) with the pipeline // IID. These normally return a placeholder. In render mode slot 67 also // publishes a compute translation request (d3d12_draw.inl). @@ -5660,9 +7102,35 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, hex_text(desc, 96, bytes, sizeof(bytes)); log("x2w-d3d12 Device::slot%d(pipeline?) desc=[%s] riid=%s -> placeholder", N, bytes, text); } - if constexpr (N == 67) publish_compute_request(desc); *out = wrap(nullptr, pipeline_kind); + if (!*out) return E_OUTOFMEMORY; + if constexpr (N == 67) { + // A translated Dispatch finds its program by this key (d3d12_compute_dispatch.inl). + if (const u64 key = publish_compute_request(desc)) { + static const u64 input_key = probe_key("X2W_ARGUMENT_INPUT_KEY"); + static const u64 output_key = probe_key("X2W_ARGUMENT_OUTPUT_KEY"); + if (x2w_local::env_on("X2W_SCENE_ARGUMENT_PROBE") && (key == input_key || key == output_key)) { + u64 p[12]{}; + if (copy_title_bytes(p, desc, sizeof(p))) { + for (const auto index : {1,3,7,9,10}) { + unsigned char block[256]{}; + const auto bytes = index < 9 ? (std::min)(u64{sizeof(block)},p[index+1]) : u64{sizeof(block)}; + if (bytes && copy_title_bytes(block,reinterpret_cast<const void*>(p[index]),bytes)) { + char hex[3*sizeof(block)+1]{}; + hex_text(block,bytes,hex,sizeof(hex)); + log("x2w-argument-probe create key=%016llx part=%d bytes=%llu data=%s",key,index,bytes,hex); + } + } + } + } + static_cast<Wrapper*>(*out)->own().compute_request_key = key; + static_cast<Wrapper*>(*out)->own().compute_request_root = as_wrapper(*static_cast<void* const*>(desc)); + } + } note_pipeline(static_cast<Wrapper*>(*out), N, nullptr, desc, 0x300); +#ifdef X2W_NATIVE_SHADERS + if constexpr (N == 57) if (render_mode()) prepare_native_mesh57(static_cast<Wrapper*>(*out)); +#endif return S_OK; } @@ -5689,6 +7157,7 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun w ? kind_names[w->own().kind] : "not a wrapper", count, bytes, text); } *out = wrap(nullptr, pipeline_kind); + if (!*out) return E_OUTOFMEMORY; note_pipeline(static_cast<Wrapper*>(*out), 55, base, desc, bytes_in_patches); return S_OK; } @@ -5700,10 +7169,10 @@ HRESULT __stdcall device_create_derived_pipeline(Wrapper*, void* base, UINT coun // COMMON, GENERIC_READ on an upload heap and COPY_DEST on a readback heap (the initial states D3D12 // requires there; the Windows 10 runtime refuses COMMON with E_INVALIDARG). When desktop rejects the // clear value it is retried without one. -HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, - const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, - void* session, UINT castable_count, const void* castable, const GUID* iid, - void** out) +// Slot 76 shares the work with the slot number in the log line. +HRESULT create_committed(int slot, Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, void* session, + UINT castable_count, const void* castable, const GUID* iid, void** out) { char text[48]; guid_text(iid, text, sizeof(text)); @@ -5712,7 +7181,7 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP const D3D12_RESOURCE_DESC copy = sanitized(*desc); const auto flags = static_cast<D3D12_HEAP_FLAGS>(heap_flags); const D3D12_RESOURCE_ALLOCATION_INFO info = device_of(self)->GetResourceAllocationInfo(0, 1, ©); - check_device("Device before slot", 127); + check_device("Device before slot", slot); void* const title_memory = info.SizeInBytes != ~0ull ? title_resource_memory(info.SizeInBytes, info.Alignment) : nullptr; ID3D12Resource* resource = nullptr; const D3D12_RESOURCE_STATES initial = props->Type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ @@ -5730,13 +7199,22 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP } static LONG calls; if (first_calls(calls, 12)) - log("x2w-d3d12 Device::slot127(CreateCommittedResource3?) heap=%d flags=0x%x dim=%d %llux%u fmt=%d rflags=0x%x " - "state=0x%x clear=%p%s session=%p castable=%u/%p riid=%s -> 0x%08lx", props->Type, heap_flags, desc->Dimension, + log("x2w-d3d12 Device::slot%d(%s) heap=%d flags=0x%x dim=%d %llux%u fmt=%d rflags=0x%x " + "state=0x%x clear=%p%s session=%p castable=%u/%p riid=%s -> 0x%08lx", slot, + slot == 76 ? "CreateCommittedResource" : "CreateCommittedResource3?", props->Type, heap_flags, desc->Dimension, desc->Width, desc->Height, desc->Format, desc->Flags, state, static_cast<const void*>(clear), clear && !cleared ? "(dropped)" : "", session, castable_count, castable, text, static_cast<unsigned long>(hr)); if (FAILED(hr)) return hr; x2w_startup::mark_packed_stand_in(resource, desktop_format(desc->Format)); Wrapper* w = wrap(resource, resource_kind); + if (!w) { + // The title-memory block is not returned here. __XMemAllocationHooks__ is documented as + // {alloc, free, ...} (title_alloc_hook above), but the free entry's signature and attributes + // have not been verified against the title, so this failure path still leaks the block. A + // follow-up has to confirm those before calling it. + resource->Release(); + return E_OUTOFMEMORY; + } w->own().budget = x2w_budget::committed(device_of(self), resource, props->Type); w->own().title_memory = title_memory; retire_set_class(w, *props, flags, copy, title_memory); @@ -5745,6 +7223,25 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP return S_OK; } +HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, + void* session, UINT castable_count, const void* castable, const GUID* iid, + void** out) +{ + return create_committed(127, self, props, heap_flags, desc, state, clear, session, castable_count, castable, iid, out); +} + +// Device slot 76 (Xbox order, +0x260): the seven arguments of desktop CreateCommittedResource +// (heap properties, heap flags, desc, initial state, clear value, riid, ppv). Seen from a console +// package module (an upscaler) that a title loaded only on the Series S profile. Same desktop +// creation as slot 127 (tests/startup_committed_slot76_check.cpp). +HRESULT __stdcall device_create_committed(Wrapper* self, const D3D12_HEAP_PROPERTIES* props, UINT heap_flags, + const D3D12_RESOURCE_DESC* desc, UINT state, const D3D12_CLEAR_VALUE* clear, + const GUID* iid, void** out) +{ + return create_committed(76, self, props, heap_flags, desc, state, clear, nullptr, 0, nullptr, iid, out); +} + // Device slot 80 (Xbox order): (type, timeout, 0, flags, &token) -> HRESULT, the frame-event wait // that hands out a frame token (called with type 2 / timeout -1 and type 0 / timeout 0, flags 0/2). // Paces to the interval from slot 78 (33.3 ms by default) and returns increasing tokens. @@ -5932,7 +7429,93 @@ void report_budget(ID3D12CommandQueue* queue) if (n < 0 || static_cast<std::size_t>(n) >= sizeof(text) - used) break; used += n; } - log("x2w-budget local=%s nonlocal=%s%s unmeasured=%llu", local, nonlocal, text, counts.unmeasured); + // System commit and the physical-page pool behind it: a run that ends on a commit limit (error 1455) shows + // whether the pool (sections, slots) or the resources above grew (#1199). + char commit[80]; + x2w_local::format_commit(commit, sizeof(commit), x2w_local::system_commit()); + char job[64]; + x2w_local::format_job(job, sizeof(job), x2w_local::job_memory()); + char pool[96] = "sections=n/a slabs=n/a slots=n/a"; + using PageStats = BOOL(WINAPI*)(ULONGLONG*); + using SlabStats = BOOL(WINAPI*)(ULONGLONG*, ULONGLONG*, ULONGLONG*); + HMODULE xmem = nullptr; + if (GetModuleHandleExW(0, L"xmem.dll", &xmem)) { // adds a reference: released below + ULONGLONG sections = 0, slabs = 0, in_use = 0, free_slots = 0; + const auto page_stats = reinterpret_cast<PageStats>(GetProcAddress(xmem, "x2w_xmem_page_stats")); + const auto slab_stats = reinterpret_cast<SlabStats>(GetProcAddress(xmem, "x2w_xmem_slab_stats")); + if (page_stats && slab_stats && page_stats(§ions) && slab_stats(&slabs, &in_use, &free_slots)) + std::snprintf(pool, sizeof(pool), "sections=%llu slabs=%llu slots=%llu/%llu", sections, slabs, in_use, free_slots); + FreeLibrary(xmem); + } + log("x2w-budget local=%s nonlocal=%s%s unmeasured=%llu %s %s %s", local, nonlocal, text, counts.unmeasured, commit, pool, job); +} + +// X2W_PRESENT_COMPOSITE=1 (experimental, docs/startup-runtime.md#presented-planes): the output +// window composites every presented plane. Unset, the window shows plane 0 alone, as before. +bool present_composite_enabled() +{ + static const bool on = x2w_local::env_on("X2W_PRESENT_COMPOSITE"); + return on; +} + +// The planes the output window draws for a present, resolved to real resources it can draw. +// X2W_PRESENT_PLANE=<n> (diagnostic) keeps plane n alone (plane 0 when n is past the count). Otherwise +// plane 0 alone is kept, unless X2W_PRESENT_COMPOSITE=1 keeps every plane for the composite +// (present_planes.h). The baseline capture and readback do not use this: they read plane 0 as before. +struct PresentedPlanes { + ID3D12Resource* drawable[window_planes] = {}; // per plane, null when left out + x2w_startup::PlaneStep steps[window_planes]; + unsigned count = 0; // composite steps + unsigned top_plane = 0; // the highest kept plane with a known resource + ID3D12Resource* top = nullptr; // its surface +}; +PresentedPlanes presented_planes(UINT planes, const void* plane_parameters) +{ + static const long wanted = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_PRESENT_PLANE", value, sizeof(value)) ? std::atol(value) : -1L; + }(); + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + PresentedPlanes out; + std::uint64_t shown[window_planes] = {}; + const unsigned total = planes < window_planes ? planes : window_planes; + const unsigned only = wanted >= 0 ? (static_cast<unsigned long>(wanted) < planes ? static_cast<unsigned>(wanted) : 0u) + : present_composite_enabled() ? ~0u + : 0u; + for (unsigned i = 0; i < total; ++i) { + if (only != ~0u && i != only) continue; + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast<void*>(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) continue; + auto* const real = static_cast<ID3D12Resource*>(surface->own().real); + out.top_plane = i; + out.top = real; + if (!presentable_surface(real)) continue; + out.drawable[i] = real; + shown[i] = resource; + } + out.count = x2w_startup::composite_steps(shown, total, out.steps, window_planes); + return out; +} + +// The first presents and every 300th: each plane's first resource and its shape. +void log_present_planes(LONG frame, UINT planes, const void* plane_parameters) +{ + if (frame > 2 && frame % 300 != 0) return; + static LONG lines; + if (!first_calls(lines, 24)) return; + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + for (unsigned i = 0; i < planes && i < 4; ++i) { + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast<void*>(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) { + log("x2w-present frame %ld plane %u/%u: resource %p is not a known resource", frame, i, planes, reinterpret_cast<void*>(resource)); + continue; + } + const D3D12_RESOURCE_DESC desc = static_cast<ID3D12Resource*>(surface->own().real)->GetDesc(); + log("x2w-present frame %ld plane %u/%u: %llux%u format %d flags=0x%x", frame, i, planes, + static_cast<unsigned long long>(desc.Width), desc.Height, desc.Format, static_cast<UINT>(desc.Flags)); + } } // Queue slot 32 (Xbox order): (plane count, plane parameters*, present parameters*) -> HRESULT, the @@ -5970,7 +7553,13 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } } bool shown_in_window = false; + log_present_planes(frame, planes, plane_parameters); + // X2W_PRESENT_COMPOSITE=1: the highest plane above plane 0, sampled raw below. + ID3D12Resource* raw_surface = nullptr; + unsigned raw_plane = 0; { + // The baseline: plane 0's first resource, captured, sampled and read back as before the planes + // were decoded, with or without X2W_PRESENT_COMPOSITE. Wrapper* surface = nullptr; const auto* words = static_cast<const u64*>(plane_parameters); if (planes && words && x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast<const void*>(words[2]), 8)) @@ -5978,9 +7567,18 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa capture::present(frame, surface); if (surface && surface->own().kind == resource_kind) red_producers().present(static_cast<ID3D12Resource*>(surface->own().real)); - // Render mode: the presented surface goes to the title's window through a swap chain. - if (render_mode() && surface && surface->own().kind == resource_kind && surface->own().real) - shown_in_window = present_to_window(static_cast<ID3D12CommandQueue*>(self->own().real), static_cast<ID3D12Resource*>(surface->own().real)); + // Render mode: the presented planes go to the output window through a swap chain: plane 0 alone + // by default, every plane with X2W_PRESENT_COMPOSITE=1. The compositor draws the steps in order. + if (render_mode()) { + const PresentedPlanes presented = presented_planes(planes, plane_parameters); + if (presented.count) + shown_in_window = present_to_window(static_cast<ID3D12CommandQueue*>(self->own().real), presented.steps, presented.count, + presented.drawable, present_composite_enabled() ? window_planes : 1); + if (present_composite_enabled() && presented.top && presented.top_plane > 0) { + raw_surface = presented.top; + raw_plane = presented.top_plane; + } + } InterlockedExchange(&last_frame_shown, shown_in_window ? 1 : 0); if (render_mode()) present_signature(self, surface, frame); } @@ -6003,6 +7601,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa std::snprintf(shown_note, sizeof(shown_note), "presented object %p is not a known resource", *reinterpret_cast<void* const*>(words[2])); } + // The raw plane sample is that plane's own surface, not the composited window picture. + if (raw_surface) read_back_presented(static_cast<ID3D12CommandQueue*>(self->own().real), raw_surface, static_cast<int>(raw_plane)); } if (shown_in_window) { if (frame % 30 == 0) { @@ -6018,25 +7618,52 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa // The null-binding total and its causes change together under draw_lock (draw_translated holds it), so they are copied there. LONG null_total = 0, null_causes[x2w_local::null_cause_count] = {}; if (render_mode() && frame % 300 == 0) { +#ifdef X2W_NATIVE_SHADERS + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0)) { + const auto stats = frozen_compute_requests().stats(); + if (compute_pack_prepared || compute_pack_refused || compute_pack_misses) + log("x2w-render compute frontend pack: prepared %ld, unsupported %ld, misses %ld", + compute_pack_prepared, compute_pack_refused, compute_pack_misses); + log("x2w-render compute request snapshots: hits %llu, misses %llu, evicted %llu, retained %zu bytes in %zu entries", + stats.hits, stats.misses, stats.evicted, stats.bytes, stats.entries); + } +#endif AcquireSRWLockExclusive(&draw_lock); null_total = null_bindings; for (int c = 0; c < x2w_local::null_cause_count; ++c) null_causes[c] = null_by_cause[c]; ReleaseSRWLockExclusive(&draw_lock); } + if (render_mode() && frame % 300 == 0 && root_srv_at_draw()) + log("x2w-render root SRV copies (X2W_D3D12_ROOT_SRV_AT_DRAW): skipped %ld, copied %ld", root_srv_copies_skipped, + root_srv_copies_made); if (render_mode() && frame % 300 == 0) log("x2w-render totals: resets %ld (failed %ld), closes %ld, clears %ld, target binds %ld (unresolved %ld), executes %ld, draws %ld (skipped %ld), " - "translated draws %ld (not drawn %ld), pipelines translated %ld / missing %ld, null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld), " - "formatted-load draws refused %ld, textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " - "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld, compute requests published %ld (already present %ld, failed %ld, pointer-like blob qwords %ld)", render_resets, + "translated draws %ld (not drawn %ld), pipelines translated %ld / missing %ld, null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld, ring_full %ld), " + "formatted-load draws refused %ld, textures uploaded %ld (%ld KiB, unreadable %ld), reads refused before a fault %ld, heap-indexed roots deferred %ld (real draws refused: view heap %ld, " + "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld, compute requests published %ld (already present %ld, failed %ld, pointer-like blob qwords %ld), " + "missing shader fallback draws %ld", render_resets, render_reset_failures, render_closes, render_clears, render_target_binds, render_target_unresolved, render_executes, render_draws, render_draws_skipped, translated_draws, untranslated_draws, translation_ready, translation_missing, null_total, - null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], formatted_draws_refused, textures_uploaded, - texture_bytes_uploaded, textures_unreadable, heap_roots_deferred, + null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], null_causes[5], formatted_draws_refused, textures_uploaded, + texture_bytes_uploaded, textures_unreadable, static_cast<long>(x2w_local::faults_avoided), heap_roots_deferred, heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::view_heap_missing)], heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::sampler_heap_missing)], heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::both_heaps_missing)], heap_root_refusals[static_cast<int>(x2w_startup::RealRootDecision::state_not_restorable)], indirect_first_lookups, - compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words); + compute_requests_published, compute_requests_present, compute_requests_failed, compute_blob_pointer_words, + missing_shader_fallback_draws); + if (render_mode() && frame % 300 == 0 && (pso_recipes_loaded || pso_recipes_precreated || pso_recipe_mismatches || pso_recipe_fallbacks)) + log("x2w-draw pso recipes totals: loaded %ld, precreated %ld, mismatches %ld, fallbacks %ld", pso_recipes_loaded, + pso_recipes_precreated, pso_recipe_mismatches, pso_recipe_fallbacks); + if (render_mode() && frame % 300 == 0) { + log("x2w-render upload ring: reserved %llu MiB in %ld reservations, refusals %ld, capacity %llu MiB", + static_cast<unsigned long long>(upload_ring_reserved_bytes) >> 20, upload_ring_reservations, upload_ring_refusals, + static_cast<unsigned long long>(upload_ring_capacity_bytes) >> 20); + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld; placed inputs from a GPU copy %ld, from a title snapshot %ld (%ld KiB)", + compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled, + compute_builder_gate_refusals, compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib); + log_compute_census(); + } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). static const char* const outcomes[] = {"forwarded", "refused graphics-pipeline", "compute-pipeline", @@ -6070,6 +7697,10 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "(region-information proofs %lld, region queries %lld)", views_noted, views_distinct, descriptors_copied, static_cast<u64>(heap_infos().size()), static_cast<long long>(placed_buffer_calls), static_cast<long long>(placed_buffer_region_info), static_cast<long long>(placed_buffer_queries)); + { + char line[640]; + if (view_census_line(line, sizeof(line))) log("%s", line); + } { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); @@ -6171,6 +7802,7 @@ void build_tables() tables[device_kind][19] = reinterpret_cast<void*>(&view_slot<19, 3>); // CreateUnorderedAccessView(res, counter, desc, dest) tables[device_kind][20] = reinterpret_cast<void*>(&view_slot<20, 2>); // CreateRenderTargetView(res, desc, dest) tables[device_kind][21] = reinterpret_cast<void*>(&view_slot<21, 2>); // CreateDepthStencilView(res, desc, dest) + tables[device_kind][61] = reinterpret_cast<void*>(&device_console_sampler); tables[device_kind][22] = reinterpret_cast<void*>(&view_slot<22, 1>); // CreateSampler(desc, dest) tables[device_kind][23] = reinterpret_cast<void*>(&device_copy_descriptors); tables[device_kind][24] = reinterpret_cast<void*>(&device_copy_descriptors_simple); @@ -6195,6 +7827,7 @@ void build_tables() tables[device_kind][48] = reinterpret_cast<void*>(&device_create_command_queue_x); tables[device_kind][70] = reinterpret_cast<void*>(&device_memory_srv); tables[device_kind][73] = reinterpret_cast<void*>(&device_create_command_list_x); + tables[device_kind][76] = reinterpret_cast<void*>(&device_create_committed); tables[device_kind][78] = reinterpret_cast<void*>(&device_frame_interval); tables[device_kind][79] = reinterpret_cast<void*>(&device_frame_event); tables[device_kind][80] = reinterpret_cast<void*>(&device_wait_frame_event); @@ -6230,6 +7863,7 @@ void build_tables() list_typed[139] = reinterpret_cast<ListTyped>(&list_reset); list_typed[148] = reinterpret_cast<ListTyped>(&list_allocate_upload); list_typed[12] = reinterpret_cast<ListTyped>(&list_draw); + list_typed[14] = reinterpret_cast<ListTyped>(&list_dispatch); list_typed[16] = reinterpret_cast<ListTyped>(&list_copy_texture); list_typed[20] = reinterpret_cast<ListTyped>(&list_topology); list_typed[21] = reinterpret_cast<ListTyped>(&list_viewports); @@ -6248,12 +7882,14 @@ void build_tables() list_typed[13] = reinterpret_cast<ListTyped>(&list_draw_indexed); list_typed[35] = reinterpret_cast<ListTyped>(&list_compute_table); list_typed[36] = reinterpret_cast<ListTyped>(&list_table); + list_typed[37] = reinterpret_cast<ListTyped>(&list_compute_constant); + list_typed[39] = reinterpret_cast<ListTyped>(&list_compute_constants); list_typed[40] = reinterpret_cast<ListTyped>(&list_root_constants); list_typed[47] = reinterpret_cast<ListTyped>(&list_index_buffer); list_typed[48] = reinterpret_cast<ListTyped>(&list_vertex_buffers); list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast<ListTyped>(&list_execute_indirect); - // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): which console methods sit at 28 to 30 is a hypothesis, so the query - // bindings are opt-in. Unset, the slots stay no-ops. + // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): the 261000 table confirms BeginQuery, EndQuery and + // ResolveQueryData at 28 to 30, but the bindings stay opt-in. Unset, the slots stay no-ops. if (wchar_t on[4]{}; GetEnvironmentVariableW(L"X2W_D3D12_QUERY_SLOTS", on, 4) && on[0] == L'1') { list_typed[28] = reinterpret_cast<ListTyped>(&list_begin_query); list_typed[29] = reinterpret_cast<ListTyped>(&list_end_query); @@ -6311,9 +7947,14 @@ void x2w_startup::attach_device(ID3D12Device* device, void** wrapped) { static const bool ready = (build_tables(), true); (void)ready; + Wrapper* const candidate = wrap(device, device_kind); + *wrapped = candidate; + if (!candidate) { + device->Release(); + return; + } + the_device = candidate; removal_device = device; - the_device = wrap(device, device_kind); - *wrapped = the_device; } HRESULT x2w_startup::resolve_placed_build(void* guest_device, UINT64 dest, UINT64 scratch, @@ -6396,7 +8037,8 @@ HRESULT x2w_d3d12_permissive_create_device(IUnknown* adapter, const void* parame log("x2w-d3d12 D3D12XboxCreateDevice adapter=%p params=[%s] riid=%s -> 0x%08lx build=%s", static_cast<void*>(adapter), block, text, static_cast<unsigned long>(hr), x2w_build_rev); if (FAILED(hr)) return hr; - if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); x2w_startup::attach_device(device, out); + if (!*out) return E_OUTOFMEMORY; + if (debug) device->QueryInterface(IID_PPV_ARGS(&info_queue)); return S_OK; } diff --git a/src/startup_stubs/draw_dump_tracking.h b/src/startup_stubs/draw_dump_tracking.h index cbbbbae611..ae71c47b4c 100644 --- a/src/startup_stubs/draw_dump_tracking.h +++ b/src/startup_stubs/draw_dump_tracking.h @@ -3,6 +3,9 @@ #include <d3d12.h> #include <wrl/client.h> +#include "startup_stubs/d3d12_teardown.h" +#include "startup_stubs/fence_completion.h" + #include <algorithm> #include <cstdint> #include <mutex> @@ -19,6 +22,12 @@ struct DrawDump { UINT count{}; DXGI_FORMAT format{}; UINT index{}; + LONG frame{}; + // Set for a one-texel history sample (X2W_DRAW_DUMP_PIXEL): the copy covers this pixel only and + // the report reads one 32-bit word instead of writing a BMP. + bool pixel{}; + UINT pixel_x{}; + UINT pixel_y{}; }; // A recorded copy belongs to a command-list recording until it is either reset @@ -29,7 +38,10 @@ class DrawReadbacks { Microsoft::WRL::ComPtr<ID3D12Fence> fence; DrawDump dump; }; - static constexpr unsigned limit = 48; + static unsigned limit() { + static const unsigned n = GetEnvironmentVariableW(L"X2W_SCENE_ARGUMENT_PROBE", nullptr, 0) ? 768 : 48; + return n; + } std::mutex mutex_; std::vector<Entry> entries_; unsigned consumed_ = 0; @@ -39,23 +51,57 @@ class DrawReadbacks { bool full() { std::lock_guard<std::mutex> lock(mutex_); - return entries_.size() + consumed_ >= limit; + return entries_.size() + consumed_ >= limit(); } bool record(ID3D12CommandList* list, DrawDump dump) { std::lock_guard<std::mutex> lock(mutex_); - if (entries_.size() + consumed_ >= limit) return false; + if (entries_.size() + consumed_ >= limit()) return false; dump.index = ++sequence_; entries_.push_back({list, {}, std::move(dump)}); return true; } - void discard(ID3D12CommandList* list) + // Test hook (startup_teardown_unload, #2572; the review of the ownership change asked for one): + // enters one recorded copy exactly as execute() leaves it after a submit -- the readback buffer and + // the queue fence that decides its completion -- without a command list, a queue or a draw. No real + // path calls it. False when the capture budget is full. + bool record_for_test(Microsoft::WRL::ComPtr<ID3D12Resource> buffer, Microsoft::WRL::ComPtr<ID3D12Fence> fence) + { + std::lock_guard<std::mutex> lock(mutex_); + if (entries_.size() + consumed_ >= limit()) return false; + DrawDump dump; + dump.buffer = std::move(buffer); + dump.index = ++sequence_; + entries_.push_back({nullptr, std::move(fence), std::move(dump)}); + return true; + } + + // Test hook: the object the first recorded entry owns, without adding a reference -- slot 0 the + // readback buffer, 1 its fence. The fixture takes its own reference and watches it stay alone once + // the module is unloaded. Null for an unknown slot or an empty cache. + IUnknown* owned_for_test(unsigned slot) + { + std::lock_guard<std::mutex> lock(mutex_); + for (auto& entry : entries_) { + if (slot == 0 && entry.dump.buffer) return entry.dump.buffer.Get(); + if (slot == 1 && entry.fence) return entry.fence.Get(); + } + return nullptr; + } + + unsigned discard(ID3D12CommandList* list) { std::lock_guard<std::mutex> lock(mutex_); + unsigned probes = 0; entries_.erase(std::remove_if(entries_.begin(), entries_.end(), - [list](const Entry& e) { return e.recording == list; }), entries_.end()); + [&](const Entry& e) { + if (!list || e.recording != list) return false; + if (!e.dump.rows && e.dump.count < 32) probes |= 1u << e.dump.count; + return true; + }), entries_.end()); + return probes; } HRESULT execute(ID3D12CommandQueue* queue, UINT count, ID3D12CommandList* const* lists) @@ -87,13 +133,12 @@ class DrawReadbacks { std::vector<DrawDump> complete; std::lock_guard<std::mutex> lock(mutex_); for (auto it = entries_.begin(); it != entries_.end();) { - const UINT64 value = it->fence ? it->fence->GetCompletedValue() : 0; - if (!value) { + const auto state = fence_completion(it->fence ? it->fence->GetCompletedValue() : 0, 1); + if (state == FenceCompletion::pending) { ++it; continue; } - // D3D12 reports UINT64_MAX for device removal, including during a wait. - if (value != UINT64_MAX) { + if (state == FenceCompletion::completed) { complete.push_back(std::move(it->dump)); ++consumed_; } @@ -101,5 +146,37 @@ class DrawReadbacks { } return complete; } + + // Lifetime boundary, same contract as the caches in startup_stubs/d3d12_teardown.h: a recorded copy and + // its fence live for as long as this module is loaded, because a list that was resubmitted still holds + // them. This object is a function-local static in draw_dumps(), so it is destroyed during the module's + // CRT teardown. On process exit the display driver is already detached and a release there faults + // inside it, so the references are detached; FreeLibrary keeps the process and the driver alive and + // the entries release their objects normally. Each reference is accounted for on the path it took and, + // with X2W_TEARDOWN_REPORT, reported as one x2w-teardown readbacks line. + ~DrawReadbacks() + { + const bool detach = d3d12_process_terminating && !teardown_guard_disabled("readbacks"); + unsigned detached = 0, released = 0; + for (auto& entry : entries_) { + if (entry.dump.buffer) { + if (detach) { + entry.dump.buffer.Detach(); + ++detached; + } else { + ++released; + } + } + if (entry.fence) { + if (detach) { + entry.fence.Detach(); + ++detached; + } else { + ++released; + } + } + } + teardown_report("readbacks", detached, released); + } }; } // namespace x2w_startup diff --git a/src/startup_stubs/fence_completion.h b/src/startup_stubs/fence_completion.h new file mode 100644 index 0000000000..b13fc53151 --- /dev/null +++ b/src/startup_stubs/fence_completion.h @@ -0,0 +1,16 @@ +#pragma once + +#include <cstdint> + +namespace x2w_startup { + +enum class FenceCompletion { pending, completed, removed }; + +constexpr FenceCompletion fence_completion(std::uint64_t observed, std::uint64_t target) noexcept +{ + // D3D12 returns UINT64_MAX on device removal, not successful completion. + if (observed == UINT64_MAX) return FenceCompletion::removed; + return observed >= target ? FenceCompletion::completed : FenceCompletion::pending; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/formatted_buffer.h b/src/startup_stubs/formatted_buffer.h index 2a216abb01..76ad650eb8 100644 --- a/src/startup_stubs/formatted_buffer.h +++ b/src/startup_stubs/formatted_buffer.h @@ -14,7 +14,7 @@ constexpr bool formatted_buffer_supported(std::uint32_t code) { switch (code) { case 1: case 5: case 14: case 22: case 23: case 24: case 27: - case 29: case 56: case 60: case 64: case 71: case 74: case 77: + case 29: case 50: case 56: case 60: case 64: case 71: case 74: case 77: return true; default: return false; diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index b135633eca..e080d8eada 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -221,8 +221,79 @@ bool read_signal(x2w_input_script::Signal& out) return true; } +// X2W_INPUT_TRACE=1: one "x2w-input-trace" line per resolved gamepad state change, plus at most one +// every 250 ms while the state stays the same. The resolved state is what capture_current() records, +// after keyboard, XInput, the shared block, X2W_INPUT_PRESS and the script have been merged. +bool trace_enabled() +{ + static const bool on = x2w_local::env_on("X2W_INPUT_TRACE"); + return on; +} + +void trace_state(const GamepadState& state, bool scripted, double script_time, bool present, std::uint64_t present_number) +{ + constexpr u64 interval_ms = 250; + static SRWLOCK trace_lock = SRWLOCK_INIT; + static GamepadState last{}; + static bool have_last = false; + static u64 last_ms = 0; + const u64 now = process_milliseconds(); + bool log = false; + AcquireSRWLockExclusive(&trace_lock); + if (!have_last || std::memcmp(&state, &last, sizeof(state)) != 0 || now < last_ms || now - last_ms >= interval_ms) { + log = true; + last = state; + have_last = true; + last_ms = now; + } + ReleaseSRWLockExclusive(&trace_lock); + if (!log) return; + char script[24], present_text[24]; + if (scripted) + std::snprintf(script, sizeof(script), "%.3f", script_time); + else + std::snprintf(script, sizeof(script), "off"); + if (present) + std::snprintf(present_text, sizeof(present_text), "%llu", static_cast<unsigned long long>(present_number)); + else + std::snprintf(present_text, sizeof(present_text), "none"); + x2w_local::logf("x2w-input-trace state buttons=0x%08x lt=%.3f rt=%.3f lx=%.3f ly=%.3f rx=%.3f ry=%.3f script=%s present=%s", + static_cast<unsigned>(state.buttons), state.left_trigger, state.right_trigger, state.left_x, state.left_y, + state.right_x, state.right_y, script, present_text); +} + +void trace_event(const x2w_input_script::Event& e) +{ + using x2w_input_script::Event; + switch (e.type) { + case Event::wait_begun: + case Event::wait_changed: + case Event::wait_done: + x2w_local::logf("x2w-input-trace wait event=%s item=%zu at=%.3f elapsed=%.3f signal=%d", + e.type == Event::wait_begun ? "begun" : e.type == Event::wait_changed ? "changed" : "done", e.item, e.at, + e.elapsed, e.signal ? 1 : 0); + break; + case Event::wait_timeout: + x2w_local::logf("x2w-input-trace wait event=timeout item=%zu at=%.3f elapsed=%.3f signal=%d stopped=%d group=%s", + e.item, e.at, e.elapsed, e.signal ? 1 : 0, e.stopped ? 1 : 0, e.label.empty() ? "-" : e.label.c_str()); + break; + case Event::mark: + if (e.signal) + x2w_local::logf("x2w-input-trace mark label=%s item=%zu at=%.3f present=%llu", e.label.c_str(), e.item, e.at, + static_cast<unsigned long long>(e.present)); + else + x2w_local::logf("x2w-input-trace mark label=%s item=%zu at=%.3f present=none", e.label.c_str(), e.item, e.at); + break; + case Event::group_skipped: + x2w_local::logf("x2w-input-trace group label=%s items=%zu-%zu failed_item=%zu at=%.3f", e.label.c_str(), e.group_item, + e.end_item, e.item, e.at); + break; + } +} + void log_event(const x2w_input_script::Event& e) { + if (trace_enabled()) trace_event(e); using x2w_input_script::Event; switch (e.type) { case Event::wait_begun: @@ -339,8 +410,12 @@ GamepadState sample() // Waits and marks (wait=..., mark=..., @+<s>) go through the timeline; other scripts as before. const x2w_input_script::Script& script = input_script(); const bool timeline = !script.waits.empty() || !script.marks.empty(); + bool scripted = false; + double script_time = 0; if (!script.entries.empty() || timeline) { const double t = script_seconds(script); + scripted = true; + script_time = t; double end = -1; const x2w_input_script::Output out = timeline ? play_timeline(script, t, end) : x2w_input_script::play(script, t); s.buttons |= out.buttons; @@ -354,6 +429,11 @@ GamepadState sample() x2w_local::logf("x2w-input script time passed its last entry (%zu entries, ended at %.3f s on the script time base)", script.entries.size(), end); } + if (trace_enabled()) { + x2w_input_script::Signal signal; + const bool present = read_signal(signal); + trace_state(s, scripted, script_time, present, present ? signal.present : 0); + } return s; } diff --git a/src/startup_stubs/gfx10_layout.h b/src/startup_stubs/gfx10_layout.h index 87deac0414..38cf1a2f40 100644 --- a/src/startup_stubs/gfx10_layout.h +++ b/src/startup_stubs/gfx10_layout.h @@ -5,8 +5,9 @@ // // A console resource description carries its swizzle mode in the Layout field as 0x100 + mode. The // modes handled here are 256 B, 4 KiB and 64 KiB blocks in the standard (S) and display (D) orders: -// 0x101, 0x102, 0x105, 0x106, 0x109 and 0x10a. The address equations, block dimensions and mip-tail -// rules follow AMD addrlib as Mesa carries it under src/amd/addrlib, at the revision +// 0x101, 0x102, 0x105, 0x106, 0x109 and 0x10a, and the linear mode 0x100, which also takes +// one-dimensional textures (one row per mip, no block-compressed formats). The address equations, +// block dimensions and mip-tail rules follow AMD addrlib as Mesa carries it under src/amd/addrlib, at the revision // tools/fetch_addrlib.py pins: Mesa 25.1.0, commit 5c142e46f3f6e752ed745fd48912ebb8fad67145. The three // files used carry this notice: // Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. @@ -16,7 +17,9 @@ // - src/core/addrlib2.cpp: ComputeThinBlockDimension (a block is 2^ceil(n/2) by 2^floor(n/2) elements) // and GetMipTailDim (the tail holds mips up to half a block wide and one block high). // - src/gfx10/gfx10addrlib.cpp: ComputeSurfaceInfoMacroTiled (the tail block comes first in a slice, -// then the mips from the smallest to the largest; offsets and origins inside the tail block). +// then the mips from the smallest to the largest; offsets and origins inside the tail block), and +// HwlComputeSurfaceInfoLinear (ADDR_SW_LINEAR: each mip is rows of a pitch rounded up to 256 bytes, +// the mips stored from the smallest to the largest, with no tail). // The rules are restated here; no addrlib code is included. // Measurements are in elements: one texel, or one 4x4 block of a block-compressed format. @@ -55,6 +58,9 @@ inline UINT swizzle_mode(const D3D12_RESOURCE_DESC& d) return (layout & ~0xffu) == 0x100 ? layout & 0xff : ~0u; } +// ADDR_SW_LINEAR: rows, not blocks. +constexpr UINT linear_mode = 0; + inline UINT block_log2(UINT mode) { switch (mode) { @@ -65,24 +71,52 @@ inline UINT block_log2(UINT mode) } } -// A two-dimensional, single-sample texture whose memory this header can address. +// A three-dimensional texture in the 4 KiB standard mode (0x105), which addrlib lays out in thick blocks +// (Gfx10Lib::HwlIsThick: a 3D resource in a standard or display mode), with a mip chain or without. A +// block-compressed element is a 4x4 block of one depth layer. +inline bool supports_volume(const D3D12_RESOURCE_DESC& d) +{ + const Element element = element_of(d.Format); + return d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && swizzle_mode(d) == 5 && element.bytes && + d.Width && d.Height && d.DepthOrArraySize && d.Width <= 2048 && d.Height <= 2048 && d.DepthOrArraySize <= 2048 && + d.MipLevels && d.MipLevels <= max_mips && d.SampleDesc.Count == 1; +} + +// A two-dimensional, single-sample texture whose memory this header can address, a one-dimensional +// one in the linear mode, or a volume supports_volume takes. addrlib refuses a 1D surface taller than one row (HwlComputeSurfaceInfoLinear). A 1D +// array is refused here as well as in address_view_fits: the draw uploads a 1D texture only when it is not an array. inline bool supports(const D3D12_RESOURCE_DESC& d) { - const UINT log2 = block_log2(swizzle_mode(d)); - if (!log2 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || !element_of(d.Format).bytes) return false; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) return supports_volume(d); + const UINT mode = swizzle_mode(d), log2 = block_log2(mode); + const Element element = element_of(d.Format); + if ((!log2 && mode != linear_mode) || !element.bytes) return false; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + if (mode != linear_mode || d.Height != 1 || d.DepthOrArraySize != 1 || element.texels != 1) return false; + } else if (d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + return false; + } if (!d.Width || !d.Height || d.Width > 16384 || d.Height > 16384 || !d.DepthOrArraySize) return false; if (!d.MipLevels || d.MipLevels > max_mips || d.SampleDesc.Count != 1) return false; - return log2 >= 12 || d.MipLevels == 1; // a 256 B block has no mip tail here + return mode == linear_mode || log2 >= 12 || d.MipLevels == 1; // a 256 B block has no mip tail here } struct Layout { UINT bytes_per_element = 0, texels = 1, width = 0, height = 0, mips = 0, slices = 0; UINT block_bytes = 0, block_width = 0, block_height = 0; + bool is_linear = false; // rows of row_pitch[mip] elements; block_* then describe one 256-byte row step UINT first_tail = 0; // first mip inside the shared tail block; mips when there is none std::uint64_t slice_size = 0; std::array<std::uint64_t, max_mips> start{}; // byte offset of a mip in its slice std::array<UINT, max_mips> blocks_wide{}, origin_x{}, origin_y{}; + std::array<UINT, max_mips> row_pitch{}; // elements per row of a linear mip std::array<UINT, 256> x_bits{}, y_bits{}; // in-block byte offset contributed by a coordinate + // A volume (supports_volume): its depth, the depth of a thick block, the in-block offset contributed by z, + // and the bytes of one layer of blocks, which holds that layer of every mip. Its one slice holds every + // depth layer; a 2D texture keeps 1, 1, 0. + UINT depth = 1, block_depth = 1; + std::array<UINT, 256> z_bits{}; + std::uint64_t layer_size = 0; explicit Layout(const D3D12_RESOURCE_DESC& d) : width(static_cast<UINT>(d.Width)), height(d.Height), mips(d.MipLevels), slices(d.DepthOrArraySize) @@ -90,7 +124,30 @@ struct Layout { const Element element = element_of(d.Format); bytes_per_element = element.bytes; texels = element.texels; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + thick(d); + return; + } const UINT mode = swizzle_mode(d), log2 = block_log2(mode); + const auto shifted = [](UINT v, UINT mip) { return (std::max)(1u, (v + (1u << mip) - 1) >> mip); }; + const UINT columns0 = (width + texels - 1) / texels, rows0 = (height + texels - 1) / texels; + if (mode == linear_mode) { + // HwlComputeSurfaceInfoLinear: the pitch of each mip is its width (rounded up, GetMipSize) + // aligned to 256 bytes, and the smallest mip comes first. + is_linear = true; + first_tail = mips; + block_bytes = 256; + block_width = 256 / bytes_per_element; + block_height = 1; + std::uint64_t offset = 0; + for (UINT mip = mips; mip-- > 0;) { + row_pitch[mip] = (shifted(columns0, mip) + block_width - 1) / block_width * block_width; + start[mip] = offset; + offset += std::uint64_t{row_pitch[mip]} * shifted(rows0, mip) * bytes_per_element; + } + slice_size = offset; + return; + } UINT element_log2 = 0; while ((1u << element_log2) < bytes_per_element) ++element_log2; const UINT count_log2 = log2 - element_log2, width_log2 = (count_log2 + 1) / 2; @@ -126,8 +183,6 @@ struct Layout { } // Mip sizes for the layout round up at every level (addrlib GetMipSize). - const UINT columns0 = (width + texels - 1) / texels, rows0 = (height + texels - 1) / texels; - const auto shifted = [](UINT v, UINT mip) { return (std::max)(1u, (v + (1u << mip) - 1) >> mip); }; const UINT tail_mips = log2 - 4; // most mips one tail block holds, for 4 KiB and 64 KiB blocks first_tail = mips; std::array<std::uint64_t, max_mips> size{}; @@ -164,37 +219,131 @@ struct Layout { } } + // A volume in the 4 KiB standard mode (supports_volume). The 12 address bits of a thick block follow the + // one-pipe rows of GFX10_SW_4K_S3_PATINFO (nibble01 rows 29-33, nibble2 rows 131-135), by element size; + // "0" is a bit inside the element. The block is 2^n texels on each axis, n counting that axis in the row + // (addrlib ComputeThickBlockDimension: Block1K_3d scaled to 4 KiB). + // + // The volume is stored a layer of blocks (block_depth texels deep) at a time, and each layer holds that + // layer of every mip (Gfx10Lib::ComputeSurfaceInfoMacroTiled and ComputeSurfaceAddrFromCoordMacroTiled + // for a thick surface): first the shared tail block when the chain has one, then the mips from the + // smallest to the largest, each pitch x height blocks in x, then y. Mip sizes round up at every level + // (GetMipSize), in elements: a block-compressed volume is first rounded up to whole 4x4 blocks + // (ElemLib::AdjustSurfaceInfo), and its depth is not divided. A mip is in the tail when it is at most a block wide and half a block high + // (GetMipTailDim: a 4 KiB block halves its height) and at most five mips remain (GetMaxNumMipsInTail for + // a thick 4 KiB block). Tail mip k from the end sits at byte (k << 8) of the tail block; that offset, + // read back as 256-byte micro blocks of Block256_3d, is its origin in x and y. Its z is not moved. + void thick(const D3D12_RESOURCE_DESC& d) + { + static constexpr UINT micro[5][2] = {{8, 4}, {4, 4}, {4, 4}, {4, 2}, {2, 2}}; // Block256_3d width, height + static constexpr const char* rows4k[5] = { + "X0X1Z0Y0Z1Y1X2Z2Y2X3Z3Y3", "--X0Z0Y0Z1Y1X1Z2Y2X2Z3Y3", "----X0Y0Z0Y1X1Z1Y2X2Z2Y3", + "------X0Z0Y0X1Z1Y1X2Z2Y2", "--------Z0Y0X0Z1Y1X1Z2Y2"}; + UINT element_log2 = 0; + while ((1u << element_log2) < bytes_per_element) ++element_log2; + depth = slices; + slices = 1; + block_bytes = 4096; + UINT xs = 0, ys = 0, zs = 0; + std::array<UINT, 8> x_at{}, y_at{}, z_at{}; + const char* pattern = rows4k[element_log2]; + for (UINT bit = 0; bit < 12; ++bit) { + const char axis = pattern[2 * bit]; + const UINT index = static_cast<UINT>(pattern[2 * bit + 1] - '0'); + if (axis == 'X') x_at[index] = bit, xs = (std::max)(xs, index + 1); + if (axis == 'Y') y_at[index] = bit, ys = (std::max)(ys, index + 1); + if (axis == 'Z') z_at[index] = bit, zs = (std::max)(zs, index + 1); + } + block_width = 1u << xs; + block_height = 1u << ys; + block_depth = 1u << zs; + for (UINT v = 0; v < 256; ++v) + for (UINT bit = 0; bit < 8; ++bit) { + if (!((v >> bit) & 1)) continue; + if (bit < xs) x_bits[v] |= 1u << x_at[bit]; + if (bit < ys) y_bits[v] |= 1u << y_at[bit]; + if (bit < zs) z_bits[v] |= 1u << z_at[bit]; + } + const auto shifted = [](UINT v, UINT mip) { return (std::max)(1u, (v + (1u << mip) - 1) >> mip); }; + const UINT columns0 = (width + texels - 1) / texels, rows0 = (height + texels - 1) / texels; + constexpr UINT tail_mips = 5; + first_tail = mips; + for (UINT mip = 0; mips > 1 && mip < mips; ++mip) + if (shifted(columns0, mip) <= block_width && shifted(rows0, mip) <= block_height / 2 && mips - mip <= tail_mips) { + first_tail = mip; + break; + } + std::array<std::uint64_t, max_mips> size{}; + for (UINT mip = 0; mip < first_tail; ++mip) { + blocks_wide[mip] = (shifted(columns0, mip) + block_width - 1) / block_width; + size[mip] = std::uint64_t{blocks_wide[mip]} * ((shifted(rows0, mip) + block_height - 1) / block_height) * block_bytes; + } + std::uint64_t offset = first_tail < mips ? block_bytes : 0; + for (UINT mip = first_tail; mip-- > 0;) { + start[mip] = offset; + offset += size[mip]; + } + layer_size = offset; + slice_size = layer_size * ((depth + block_depth - 1) / block_depth); + for (UINT mip = first_tail; mip < mips; ++mip) { + const UINT tail_offset = (tail_mips - 1 - (mip - first_tail)) << 8; + UINT x = 0, y = 0; + for (UINT bit = 0; bit < 2; ++bit) { + y |= ((tail_offset >> (8 + 2 * bit)) & 1) << bit; + x |= ((tail_offset >> (9 + 2 * bit)) & 1) << bit; + } + origin_x[mip] = x * micro[element_log2][0]; + origin_y[mip] = y * micro[element_log2][1]; + } + } + // Elements a mip holds, with the desktop's mip sizes (rounded down, at least one texel). UINT columns(UINT mip) const { return ((std::max)(1u, width >> mip) + texels - 1) / texels; } UINT rows(UINT mip) const { return ((std::max)(1u, height >> mip) + texels - 1) / texels; } + UINT layers(UINT mip) const { return (std::max)(1u, depth >> mip); } std::uint64_t bytes() const { return slice_size * slices; } - // Byte offset of element (x, y) of a mip of a slice from the start of the texture. - std::uint64_t address(UINT mip, UINT x, UINT y, UINT slice) const + // Byte offset of element (x, y) of a mip of a slice from the start of the texture; z is the depth + // layer of a volume. + std::uint64_t address(UINT mip, UINT x, UINT y, UINT slice, UINT z = 0) const { + if (block_depth > 1) { // a volume (thick) + const std::uint64_t layer = std::uint64_t{z / block_depth} * layer_size + start[mip]; + const UINT in_z = z_bits[z % block_depth]; + if (mip >= first_tail) + return layer + (x_bits[(origin_x[mip] + x) % block_width] | y_bits[(origin_y[mip] + y) % block_height] | in_z); + return layer + (std::uint64_t{y / block_height} * blocks_wide[mip] + x / block_width) * block_bytes + + (x_bits[x % block_width] | y_bits[y % block_height] | in_z); + } const std::uint64_t base = slice * slice_size; + if (is_linear) return base + start[mip] + (std::uint64_t{y} * row_pitch[mip] + x) * bytes_per_element; if (mip >= first_tail) return base + (x_bits[(origin_x[mip] + x) & 255] | y_bits[(origin_y[mip] + y) & 255]); const std::uint64_t block = std::uint64_t{y / block_height} * blocks_wide[mip] + x / block_width; return base + start[mip] + block * block_bytes + (x_bits[x % block_width] | y_bits[y % block_height]); } - // Copies one subresource from the console layout at `tiled` to rows `pitch` bytes apart at `linear`. - void detile(UINT mip, UINT slice, const unsigned char* tiled, unsigned char* linear, std::size_t pitch) const + // Copies one subresource from the console layout at `tiled` to rows `pitch` bytes apart at `linear`; + // the depth layers of a volume are `layer_pitch` bytes apart. + void detile(UINT mip, UINT slice, const unsigned char* tiled, unsigned char* linear, std::size_t pitch, + std::size_t layer_pitch = 0) const { - const UINT w = columns(mip), h = rows(mip); - for (UINT y = 0; y < h; ++y) - for (UINT x = 0; x < w; ++x) - std::memcpy(linear + y * pitch + std::size_t{x} * bytes_per_element, tiled + address(mip, x, y, slice), - bytes_per_element); + const UINT w = columns(mip), h = rows(mip), n = layers(mip); + for (UINT z = 0; z < n; ++z) + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) + std::memcpy(linear + z * layer_pitch + y * pitch + std::size_t{x} * bytes_per_element, + tiled + address(mip, x, y, slice, z), bytes_per_element); } // The opposite copy, from rows into the console layout. - void tile(UINT mip, UINT slice, unsigned char* tiled, const unsigned char* linear, std::size_t pitch) const + void tile(UINT mip, UINT slice, unsigned char* tiled, const unsigned char* linear, std::size_t pitch, + std::size_t layer_pitch = 0) const { - const UINT w = columns(mip), h = rows(mip); - for (UINT y = 0; y < h; ++y) - for (UINT x = 0; x < w; ++x) - std::memcpy(tiled + address(mip, x, y, slice), linear + y * pitch + std::size_t{x} * bytes_per_element, - bytes_per_element); + const UINT w = columns(mip), h = rows(mip), n = layers(mip); + for (UINT z = 0; z < n; ++z) + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) + std::memcpy(tiled + address(mip, x, y, slice, z), + linear + z * layer_pitch + y * pitch + std::size_t{x} * bytes_per_element, bytes_per_element); } }; } // namespace x2w_startup::gfx10 diff --git a/src/startup_stubs/indexed_rect_geometry.h b/src/startup_stubs/indexed_rect_geometry.h index c2b6e77df2..84219483c1 100644 --- a/src/startup_stubs/indexed_rect_geometry.h +++ b/src/startup_stubs/indexed_rect_geometry.h @@ -72,6 +72,17 @@ bool corner_between(float2 p, float2 a, float2 b) { return (p.x == a.x && p.y == b.y && p.y != a.y && p.x != b.x) || (p.x == b.x && p.y == a.y && p.y != b.y && p.x != a.x); } +// The right-angle corner is the vertex opposite the rectangle's diagonal, which is the longest of its three +// edges: for the corner c with neighbours a and b, |a - b| is the diagonal and is longer than both sides. The +// axis test above is one case of this; a rotated rectangle has no corner that shares an axis with a neighbour, +// so without this test the stage drops it and leaves the region it covers unpainted (#3131). The two sides must +// also meet at a right angle, so a shape that is not a rectangle stays undrawn as before. +bool corner_off_longest(float2 p, float2 a, float2 b) { + float2 pa = p - a, pb = p - b, ab = a - b; + const float across = dot(ab, ab), side_a = dot(pa, pa), side_b = dot(pb, pb); + const float angle = dot(pa, pb); + return across > side_a && across > side_b && angle * angle <= 1e-6 * side_a * side_b; +} [maxvertexcount(6)] void main(triangle Vertex input[3], inout TriangleStream<Vertex> stream) { Vertex v[3] = input; @@ -80,6 +91,9 @@ void main(triangle Vertex input[3], inout TriangleStream<Vertex> stream) { uint corner = 3; [unroll] for (uint i = 0; i < 3; ++i) if (corner_between(v[i].pos.xy, v[(i + 1) % 3].pos.xy, v[(i + 2) % 3].pos.xy)) corner = i; + if (corner == 3) + [unroll] for (uint j = 0; j < 3; ++j) + if (corner_off_longest(v[j].pos.xy, v[(j + 1) % 3].pos.xy, v[(j + 2) % 3].pos.xy)) corner = j; if (corner == 3) return; uint a = (corner + 1) % 3, b = (corner + 2) % 3; )"; diff --git a/src/startup_stubs/input_script.h b/src/startup_stubs/input_script.h index 0e16ce8cab..b34c4450be 100644 --- a/src/startup_stubs/input_script.h +++ b/src/startup_stubs/input_script.h @@ -132,8 +132,9 @@ inline const char* parse_when(const char* p, double cursor, Entry& entry, bool* const bool relative = p[1] == '+'; p += relative ? 2 : 1; entry.at = std::strtod(p, &stop); - if (stop == p || !std::isfinite(entry.at) || (relative && !(entry.at >= 0))) return "bad time"; + if (stop == p || (relative && !(entry.at >= 0))) return "bad time"; if (relative) entry.at += cursor; + if (!std::isfinite(entry.at)) return "bad time"; // after the sum, so a relative time cannot overflow to infinity p = stop; entry.duration = default_duration; if (had_duration) *had_duration = *p == '+'; diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h index 929a7eca87..18c9a9278e 100644 --- a/src/startup_stubs/linear_buffer_backing.h +++ b/src/startup_stubs/linear_buffer_backing.h @@ -183,6 +183,7 @@ #include "startup_stubs/linear_buffer_report.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/placed_buffer_range.h" #include "startup_stubs/resource_budget.h" @@ -244,13 +245,7 @@ inline bool submit_fence_forced_off() // violation or an in-page error instead of a fault in the DLL. inline bool guarded_copy(void* to, const void* from, std::size_t bytes) noexcept { - __try { - std::memcpy(to, from, bytes); - } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR - ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { - return false; - } - return true; + return x2w_local::guarded_memcpy(to, from, bytes, false); } inline D3D12_RESOURCE_DESC buffer(UINT64 width, D3D12_RESOURCE_FLAGS flags) { @@ -318,22 +313,34 @@ class LinearBuffers { record.info.use = uav ? gpu_written : gpu_read; record.info.feature_hr = S_FALSE; record.info.share_hr = S_FALSE; - const UINT64 offset = static_cast<UINT64>(static_cast<char*>(address) - static_cast<char*>(range.base)); + PlacedBufferRange local_range = range; + UINT64 offset = static_cast<UINT64>(static_cast<char*>(address) - static_cast<char*>(local_range.base)); ID3D12Resource* resource = nullptr; if (linear_buffer_mode() == LinearBufferMode::automatic) { + static const bool cap_existing_heap = x2w_local::env_on("X2W_D3D12_CAP_EXISTING_HEAP"); record.info.feature_hr = feature(device); const bool allowed = SUCCEEDED(record.info.feature_hr) || linear_detail::mutant("ignore-feature"); + if (allowed && !local_range.covered && !local_range.region_info && local_range.type == MEM_PRIVATE && + can_commit_lazy_placed_buffer(address, width, cap_existing_heap ? unplaced_max_span : 0)) { + x2w_local::commit_lazy_block(address); + if (measure_placed_buffer(address, width, local_range)) + offset = static_cast<UINT64>(static_cast<char*>(address) - static_cast<char*>(local_range.base)); + else + local_range.covered = false; + } if (!allowed) record.info.share_hr = record.info.feature_hr; - else if (!range.covered || (offset & 0xFFFF)) + else if (!local_range.covered || (offset & 0xFFFF)) record.info.share_hr = E_INVALIDARG; // decided without D3D12: each failed open throws in D3D12Core - else if (range.type == MEM_MAPPED) + else if (local_range.type == MEM_MAPPED) record.info.share_hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); // an open heap would pin the view - else if (range.type != MEM_PRIVATE) + else if (local_range.type != MEM_PRIVATE) record.info.share_hr = E_INVALIDARG; + else if (cap_existing_heap && !unplaced_existing_heap_allowed(allocation_bytes(local_range.base))) + record.info.share_hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); else - record.info.share_hr = share(device, range, offset, width, uav, &resource, &record.info.heap_generation, - backing_budget); + record.info.share_hr = share(device, local_range, offset, width, uav, &resource, + &record.info.heap_generation, backing_budget); } HRESULT hr = S_OK; if (SUCCEEDED(record.info.share_hr) && record.info.share_hr != S_FALSE) { @@ -862,6 +869,7 @@ class LinearBuffers { ID3D12Heap* heap = nullptr; HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device3)); if (SUCCEEDED(hr)) { + x2w_local::commit_lazy_block(range.base); ++totals_.heap_opens; hr = device3->OpenExistingHeapFromAddress(range.base, IID_PPV_ARGS(&heap)); device3->Release(); diff --git a/src/startup_stubs/list_compute_root.h b/src/startup_stubs/list_compute_root.h index 6e5d89c469..a47b3477db 100644 --- a/src/startup_stubs/list_compute_root.h +++ b/src/startup_stubs/list_compute_root.h @@ -14,6 +14,19 @@ namespace x2w_startup { +// Slot 32 builds this selection afresh for each call. The graphics lookup still singles out +// oversized logical heaps; compute table invalidation also needs ordinary shader-visible heaps. +struct ViewHeapSelection { + std::uint64_t graphics = 0; + std::uint64_t compute = 0; + + void note(std::uint64_t wrapper, bool shader_visible, unsigned logical_count, unsigned desktop_count) + { + if (shader_visible) compute = wrapper; + if (logical_count > desktop_count) graphics = wrapper; + } +}; + class ComputeTables { public: static constexpr unsigned max_parameters = 16; // same range as the graphics tables @@ -26,9 +39,10 @@ class ComputeTables { } // Slot 32 with another view heap: the recorded addresses belong to the old one. - void clear() + void set_view_heap(std::uint64_t heap) { - for (auto& table : tables_) table = {}; + if (heap != view_heap_) clear(); + view_heap_ = heap; } // False when the parameter is out of range (counted). @@ -47,7 +61,13 @@ class ComputeTables { std::uint32_t out_of_range_count() const { return out_of_range_; } private: + void clear() + { + for (auto& table : tables_) table = {}; + } + const void* signature_ = nullptr; + std::uint64_t view_heap_ = 0; ViewTable tables_[max_parameters] = {}; std::uint32_t out_of_range_ = 0; }; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 6538a5cd02..a755eec820 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -218,6 +218,8 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti if (!self->own().list_open) return; const CopyEndpoint to = copy_endpoint(destination); const CopyEndpoint from = copy_endpoint(source); + trace_compute_output_use(self, OutputUse::copy_source, "copy-source-attempt", from.wrapper, 0, source_offset, bytes); + trace_compute_output_use(self, OutputUse::copy_destination, "copy-destination-attempt", to.wrapper, 0, destination_offset, bytes); D3D12_RESOURCE_DESC to_desc{}, from_desc{}; if (to.resource) to_desc = to.resource->GetDesc(); if (from.resource) from_desc = from.resource->GetDesc(); @@ -234,6 +236,8 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast<ID3D12GraphicsCommandList*>(self->own().real) ->CopyBufferRegion(to.resource, destination_offset, from.resource, source_offset, bytes); + trace_compute_output_use(self, OutputUse::copy_read_recorded, "copy-read-recorded", from.wrapper, 0, source_offset, bytes); + trace_compute_output_use(self, OutputUse::copy_write_recorded, "copy-write-recorded", to.wrapper, 0, destination_offset, bytes); if (mesh_xmem_tracking()) { D3D12_HEAP_TYPE source_heap; const bool upload = fixed_heap(from.resource, source_heap) && source_heap == D3D12_HEAP_TYPE_UPLOAD; diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 4f2ca279b5..1583b81b5c 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -1,4 +1,4 @@ -// Included by d3d12_xs_device.cpp after d3d12_draw.inl. Command list slot 16, CopyTextureRegion (#870). +// Included by d3d12_xs_device.cpp after list_copy.inl. Command list slot 16, CopyTextureRegion (#870). // Each location's resource is mapped to its desktop resource, the call is checked by // list_copy_texture.h, the two resources move to COPY_SOURCE / COPY_DEST for the call (the list's Close // puts them back to COMMON), and a call the desktop would reject is counted and logged, not forwarded. @@ -168,6 +168,7 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO to.pResource = real_dst; from.pResource = real_src; static_cast<ID3D12GraphicsCommandList*>(self->own().real)->CopyTextureRegion(&to, x, y, z, &from, box ? box : nullptr); + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource) mark_gpu_written(self, {real_dst, dst_wrapper}); retire_hold(self, dst_wrapper); retire_hold(self, src_wrapper); InterlockedIncrement(&list_copy_texture_forwarded); diff --git a/src/startup_stubs/list_dispatch.h b/src/startup_stubs/list_dispatch.h new file mode 100644 index 0000000000..102446d710 --- /dev/null +++ b/src/startup_stubs/list_dispatch.h @@ -0,0 +1,58 @@ +#pragma once + +// Command-list slot 14, Dispatch(x, y, z). A dispatch is forwarded to the desktop list only when the list is open, +// can run compute, a desktop compute pipeline and a desktop compute root signature are bound, the compute root declares +// no parameters other than root SRVs (of the compute root-argument slots, only slot 43 (root SRV) is forwarded; 35, 37, 39, 41 and 45 are not forwarded yet, so a root that needs +// arguments would run with them unset), and every group count is within the D3D12 limit of 65535 per dimension. Zero groups on any axis is valid and runs nothing. + +#include <d3d12.h> + +namespace x2w_startup { + +constexpr UINT max_dispatch_groups = 65535; + +struct ListDispatch { + bool list_open = false; + D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT; + bool compute_pipeline = false; // the bound pipeline is a desktop compute pipeline + bool compute_root = false; // the bound compute root signature is a desktop root signature + bool compute_root_has_arguments = false; // that root declares parameters or static samplers + bool root_matches_pipeline = true; // the compute pipeline was built against the bound compute root + bool root_arguments_bound = true; // every root SRV the root declares reached the desktop list (a rejected set clears it) + UINT x = 0, y = 0, z = 0; +}; + +enum class DispatchDecision { forward, list_closed, wrong_list_type, no_compute_state, unforwarded_root_arguments, + root_pipeline_mismatch, unbound_root_argument, group_count_over_limit }; +constexpr int dispatch_decision_count = 8; + +inline const char* dispatch_reason(DispatchDecision decision) +{ + switch (decision) { + case DispatchDecision::forward: return "forward"; + case DispatchDecision::list_closed: return "list is closed"; + case DispatchDecision::wrong_list_type: return "requires a direct or compute command list"; + case DispatchDecision::no_compute_state: return "requires a desktop compute pipeline and root"; + case DispatchDecision::unforwarded_root_arguments: return "compute root arguments are not forwarded"; + case DispatchDecision::root_pipeline_mismatch: return "compute pipeline was built against another root signature"; + case DispatchDecision::unbound_root_argument: return "a compute root SRV is not bound"; + case DispatchDecision::group_count_over_limit: return "group count is over 65535"; + } + return "unknown"; +} + +inline DispatchDecision decide_dispatch(const ListDispatch& d) +{ + if (!d.list_open) return DispatchDecision::list_closed; + if (d.type != D3D12_COMMAND_LIST_TYPE_DIRECT && d.type != D3D12_COMMAND_LIST_TYPE_COMPUTE) + return DispatchDecision::wrong_list_type; + if (!d.compute_pipeline || !d.compute_root) return DispatchDecision::no_compute_state; + if (d.compute_root_has_arguments) return DispatchDecision::unforwarded_root_arguments; + if (!d.root_matches_pipeline) return DispatchDecision::root_pipeline_mismatch; + if (!d.root_arguments_bound) return DispatchDecision::unbound_root_argument; + if (d.x > max_dispatch_groups || d.y > max_dispatch_groups || d.z > max_dispatch_groups) + return DispatchDecision::group_count_over_limit; + return DispatchDecision::forward; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/list_upload_pages.h b/src/startup_stubs/list_upload_pages.h index 0892816c16..d435e4c69b 100644 --- a/src/startup_stubs/list_upload_pages.h +++ b/src/startup_stubs/list_upload_pages.h @@ -14,7 +14,12 @@ struct Page { unsigned char* cpu = nullptr; UINT64 gpu = 0, size = 0, cursor = 0; }; -inline HRESULT make_page(ID3D12Device* device, UINT64 bytes, Page& page) { +struct UploadFailure { + const char* stage = nullptr; + HRESULT hr = S_OK; + UINT64 requested_page = 0; +}; +inline HRESULT make_page(ID3D12Device* device, UINT64 bytes, Page& page, UploadFailure* failure = nullptr) { D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_UPLOAD; heap.CreationNodeMask = heap.VisibleNodeMask = 1; @@ -25,16 +30,26 @@ inline HRESULT make_page(ID3D12Device* device, UINT64 bytes, Page& page) { desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&page.resource)); - if (FAILED(hr)) return hr; + if (FAILED(hr)) { + if (failure) *failure = {"CreateCommittedResource", hr, bytes}; + return hr; + } x2w_budget::committed(device, page.resource.Get(), D3D12_HEAP_TYPE_UPLOAD); D3D12_RANGE no_reads{}; void* mapped = nullptr; hr = page.resource->Map(0, &no_reads, &mapped); - if (FAILED(hr)) return hr; + if (FAILED(hr)) { + if (failure) *failure = {"Map", hr, bytes}; + return hr; + } page.cpu = static_cast<unsigned char*>(mapped); page.gpu = page.resource->GetGPUVirtualAddress(); page.size = bytes; - return page.cpu && page.gpu ? S_OK : E_FAIL; + if (!page.cpu || !page.gpu) { + if (failure) *failure = {page.cpu ? "null GPU address" : "null mapped address", E_FAIL, bytes}; + return E_FAIL; + } + return S_OK; } struct Allocation { uintptr_t cpu; UINT64 gpu, bytes; ID3D12Resource* resource; UINT64 offset; }; struct Arena { @@ -44,23 +59,29 @@ struct Arena { // The caller must retire all recordings and GPU submissions before releasing their pages. void reset() { allocations.clear(); pages.clear(); } - Allocation range(UINT64 cpu, UINT64 bytes) const { + Allocation range(UINT64 cpu, UINT64 bytes, bool remaining = false) const { if (!bytes) return {}; for (auto it = allocations.rbegin(); it != allocations.rend(); ++it) { if (cpu < it->cpu) continue; UINT64 offset = cpu - it->cpu; if (offset < it->bytes && bytes <= it->bytes - offset) - return {static_cast<uintptr_t>(cpu), it->gpu + offset, bytes, it->resource, it->offset + offset}; + return {static_cast<uintptr_t>(cpu), it->gpu + offset, remaining ? it->bytes - offset : bytes, it->resource, it->offset + offset}; } return {}; } UINT64 translate(UINT64 cpu, UINT64 bytes) const { return range(cpu, bytes).gpu; } - Allocation allocate(ID3D12Device* device, UINT64 bytes, UINT64 alignment) { - if (!device || !bytes || !alignment || (alignment & (alignment - 1))) return {}; + Allocation allocate(ID3D12Device* device, UINT64 bytes, UINT64 alignment, UploadFailure* failure = nullptr) { + if (!device || !bytes || !alignment || (alignment & (alignment - 1))) { + if (failure) *failure = {"invalid request", E_INVALIDARG}; + return {}; + } alignment = (std::max)(alignment, UINT64{16}); - if (bytes > UINT64_MAX - alignment) return {}; + if (bytes > UINT64_MAX - alignment) { + if (failure) *failure = {"size overflow", E_INVALIDARG}; + return {}; + } auto take = [&](Page& page) -> Allocation { const auto base = reinterpret_cast<uintptr_t>(page.cpu); const UINT64 mask = alignment - 1; @@ -79,10 +100,14 @@ struct Arena { if (a.cpu) return a; } auto page = std::make_unique<Page>(); - if (FAILED(make_page(device, (std::max)(UINT64{65536}, bytes + alignment - 1), *page))) return {}; + const auto page_bytes = (std::max)(UINT64{65536}, bytes + alignment - 1); + if (FAILED(make_page(device, page_bytes, *page, failure))) return {}; pages.push_back(std::move(page)); Allocation a = take(*pages.back()); - if (!a.cpu) pages.pop_back(); + if (!a.cpu) { + pages.pop_back(); + if (failure) *failure = {"new page alignment", E_FAIL, page_bytes}; + } return a; } }; diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index bea306fde9..e044bd11e1 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -5,7 +5,10 @@ #include "startup_stubs/trap.h" #include <cstdarg> +#include <cstdint> +#include <cstring> #include <cstdio> +#include <type_traits> namespace x2w_local { @@ -50,6 +53,80 @@ inline bool first_calls(volatile LONG& counter, LONG limit) noexcept return false; } +// Seconds since this process was created: one time base for lines from different stand-in DLLs. +inline double process_seconds() noexcept +{ + FILETIME created{}, exited{}, kernel{}, user{}, now{}; + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) return 0; + GetSystemTimeAsFileTime(&now); + const auto ticks = [](const FILETIME& t) { return (std::uint64_t{t.dwHighDateTime} << 32) | t.dwLowDateTime; }; + return ticks(now) > ticks(created) ? static_cast<double>(ticks(now) - ticks(created)) / 1e7 : 0.0; +} + +// First-chance exceptions stop the whole process while a debugger is attached, so a probe or a copy that is +// refused before it touches an unmapped address is worth a query. faults_avoided counts those refusals; the +// totals line of the render heartbeat prints it. +inline volatile LONG faults_avoided = 0; + +// Number of leading bytes of [start, start + bytes) that are not in free address space (MEM_FREE), found with +// VirtualQuery. Only MEM_FREE is refused: a reserved or committed page may be a lazily committed xmem page that +// the fault handler commits on first touch, a guard page or no-access page keeps its handling in the callers, +// so those still go to the touch/__try path. One query walks a whole region, which on the title's +// multi-gigabyte blocks costs about a millisecond, so the spans found are cached per thread; a span freed +// after it was cached is caught by the touch/__try path as before (it only costs the fault it always cost). +struct MappedSpan { + std::uintptr_t begin, end; +}; +struct MappedCache { + MappedSpan spans[16]; + int next; +}; +inline thread_local MappedCache mapped_cache; +// Forgets the spans this thread has found (a span can be freed later; a failed touch or copy calls this). +inline void forget_mapped_spans() noexcept { mapped_cache = MappedCache{}; } + +// The pre-check is a debugging aid: it only pays off while a debugger would stop on every first-chance fault. +// X2W_PROBE_PRECHECK decides when it is set (0 off, anything else on); unset, the pre-check runs when a debugger is +// attached. Read once, cached. Title runs always start under debug_launch.py, where a VirtualQuery per probe can +// cost far more than the faults it avoids, so X2W_PROBE_PRECHECK=0 turns it off there. Off, probes and copies keep +// the plain touch / __try path at no extra cost. +inline bool precheck_enabled() noexcept +{ + static const bool enabled = [] { + char value[8] = {}; + const DWORD n = GetEnvironmentVariableA("X2W_PROBE_PRECHECK", value, sizeof(value)); + if (n != 0 && n < sizeof(value)) return value[0] != '0'; + return IsDebuggerPresent() != FALSE; + }(); + return enabled; +} + +inline std::size_t mapped_prefix(std::uintptr_t start, std::size_t bytes) noexcept +{ + if (bytes == 0 || start + bytes < start || !precheck_enabled()) return bytes; + const std::uintptr_t end = start + bytes; + std::uintptr_t at = start; + while (at < end) { + bool hit = false; + for (const MappedSpan& span : mapped_cache.spans) { + if (span.begin <= at && at < span.end) { + at = span.end < end ? span.end : end; + hit = true; + break; + } + } + if (hit) continue; + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast<const void*>(at), &info, sizeof(info))) return bytes; // unknown: let the touch decide + if (info.State == MEM_FREE) return static_cast<std::size_t>(at - start); + const auto begin = reinterpret_cast<std::uintptr_t>(info.BaseAddress); + mapped_cache.spans[mapped_cache.next] = {begin, begin + info.RegionSize}; + mapped_cache.next = (mapped_cache.next + 1) % 16; + at = begin + info.RegionSize < end ? begin + info.RegionSize : end; + } + return bytes; +} + // Number of contiguous readable bytes at start, up to bytes, found by touching one byte per page. // VirtualQuery is not used for this: on the title's multi-gigabyte regions one query takes about a // millisecond (it walks the region to size it). A bad pointer costs a first-chance exception, so @@ -61,7 +138,14 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc std::size_t done = 0; DWORD code = 0; std::uintptr_t at = start; - const std::uintptr_t end = start + bytes; + // Free address space is refused without touching it; the touch below only sees mapped pages. + const std::size_t mapped = mapped_prefix(start, bytes); + const bool refused_tail = mapped < bytes; + if (mapped == 0) { + if (refused_tail) InterlockedIncrement(&faults_avoided); + return 0; + } + const std::uintptr_t end = start + mapped; __try { volatile unsigned char sink = 0; while (at < end) { @@ -79,9 +163,33 @@ inline std::size_t probe_readable(std::uintptr_t start, std::size_t bytes) noexc VirtualProtect(reinterpret_cast<void*>(at & ~std::uintptr_t{0xFFF}), 0x1000, info.Protect | PAGE_GUARD, &old); } } + if (done < mapped) forget_mapped_spans(); // the span was cached, then freed or protected + // A free tail only counts as an avoided fault when the mapped prefix was walked without one: a protected page + // inside the prefix faults exactly as it did before the free tail was refused. + else if (refused_tail) InterlockedIncrement(&faults_avoided); return done; } +// memcpy from title memory that may have been freed or unmapped since it was probed. A source that is in free +// address space is refused up front with no exception (counted in faults_avoided); everything else is copied under +// __try as the last guard. any_exception false: only an access violation or an in-page error is caught. +inline bool guarded_memcpy(void* to, const void* from, std::size_t bytes, bool any_exception) noexcept +{ + if (bytes && mapped_prefix(reinterpret_cast<std::uintptr_t>(from), bytes) < bytes) { + InterlockedIncrement(&faults_avoided); + return false; + } + __try { + std::memcpy(to, from, bytes); + } __except (any_exception || GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || + GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + forget_mapped_spans(); + return false; + } + return true; +} + // With X2W_XMEM_LAZY_COMMIT, physical pages are committed on first touch (xmem_mapped_pages.cpp). A check of the // commit state, or a write that cannot fault (kernel I/O, GPU), commits the range first. A no-op without xmem.dll // or without the switch. @@ -107,6 +215,27 @@ inline void commit_lazy_block(const void* pointer) noexcept if (commit_block) commit_block(pointer); } +// Runs f() outside xmem's run breaks (x2w_xmem_stable_call, X2W_XMEM_SHARED_VIEWS): inside a break the pages of +// the run being taken apart read as reserved to a VirtualQuery and make ReadProcessMemory fail, although a touch of +// them would be retried. f must be a query, or a copy into the caller's memory, that can run again; it may run +// twice. Without xmem.dll, or with one that lacks the export, f runs once, directly. +using StableCall = BOOL(WINAPI*)(void (*)(void*), void*); +inline StableCall stable_call_export() noexcept +{ + static const StableCall stable_call = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast<StableCall>(GetProcAddress(xmem, "x2w_xmem_stable_call")) : nullptr; + }(); + return stable_call; +} +template <typename F> +inline void outside_run_breaks(F&& f) noexcept +{ + const StableCall stable_call = stable_call_export(); + using Call = std::remove_reference_t<F>; + if (!stable_call || !stable_call([](void* context) { (*static_cast<Call*>(context))(); }, &f)) f(); +} + // Readability by probing (see probe_readable); writability by one VirtualQuery (rare callers). inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexcept { @@ -115,7 +244,9 @@ inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexc if (!write) return probe_readable(start, bytes) == bytes; commit_lazy(pointer, bytes); MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(pointer, &info, sizeof(info)) || info.State != MEM_COMMIT) return false; + SIZE_T queried = 0; + outside_run_breaks([&] { queried = VirtualQuery(pointer, &info, sizeof(info)); }); + if (!queried || info.State != MEM_COMMIT) return false; const DWORD protect = info.Protect & 0xFF; if ((info.Protect & PAGE_GUARD) || protect == PAGE_NOACCESS || protect == 0) return false; const bool writable = protect == PAGE_READWRITE || protect == PAGE_EXECUTE_READWRITE || protect == PAGE_WRITECOPY || @@ -129,4 +260,30 @@ inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexc inline bool readable(const void* pointer, std::size_t bytes) noexcept { return accessible(pointer, bytes, false); } inline bool writable(const void* pointer, std::size_t bytes) noexcept { return accessible(pointer, bytes, true); } +// True when every byte of [pointer, pointer + bytes) is committed and writable, with no guard or no-access page +// in between. Walks the regions one VirtualQuery at a time, so a range that spans regions of different +// protection is judged page by page. Nothing is written, touched or committed (see commit_lazy), so it is safe +// under xmem's mapping lock. An empty range is writable; a null or wrapping one is not. +inline bool committed_writable(const void* pointer, std::size_t bytes) noexcept +{ + if (bytes == 0) return true; + std::uintptr_t cursor = reinterpret_cast<std::uintptr_t>(pointer); + if (!pointer || bytes > ~std::uintptr_t{0} - cursor) return false; + const std::uintptr_t end = cursor + bytes; + while (cursor < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast<const void*>(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; + const DWORD protect = info.Protect & 0xFF; + if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && + protect != PAGE_EXECUTE_WRITECOPY) + return false; + const std::uintptr_t region_end = reinterpret_cast<std::uintptr_t>(info.BaseAddress) + info.RegionSize; + if (region_end <= cursor) return false; + cursor = region_end; + } + return true; +} + } // namespace x2w_local diff --git a/src/startup_stubs/manifest_retry.h b/src/startup_stubs/manifest_retry.h new file mode 100644 index 0000000000..71d2824e49 --- /dev/null +++ b/src/startup_stubs/manifest_retry.h @@ -0,0 +1,43 @@ +// When to look again for a shader cache manifest (<key>.txt) that was absent. +// +// The graphics and compute translation paths look for a missing manifest again on a later draw or Dispatch, because +// the translator (run.ps1 -Translate) can publish it while the title runs. Each look opens a file in the shader cache +// while the caller holds draw_lock, which every draw and Dispatch takes. With a fixed 1 s retry, many keys that +// never get a translation each cost one file open per second, and every other list call waits on that lock. +// +// The wait starts at 1 s after the first miss and doubles with each further miss up to 32 s. A translation published +// during the run is still found, within 32 s at the latest; a key that is never translated costs one look every 32 s. +#pragma once + +#include <windows.h> + +namespace x2w_startup { + +constexpr ULONGLONG manifest_retry_first_ms = 1000; +constexpr unsigned manifest_retry_max_doublings = 5; // 1 s, 2 s, 4 s, 8 s, 16 s, then 32 s + +// The wait after the (misses + 1)-th miss in a row. +constexpr ULONGLONG manifest_retry_delay_ms(unsigned misses) noexcept +{ + return manifest_retry_first_ms << (misses < manifest_retry_max_doublings ? misses : manifest_retry_max_doublings); +} + +struct ManifestRetry { + ULONGLONG at = 0; // GetTickCount64 value of the next look, 0 when none is pending + unsigned misses = 0; // misses in a row since the manifest was last found + + bool pending() const noexcept { return at != 0; } + bool due(ULONGLONG now) const noexcept { return at != 0 && now >= at; } + void missed(ULONGLONG now) noexcept + { + at = now + manifest_retry_delay_ms(misses); + if (misses < manifest_retry_max_doublings) ++misses; + } + void found() noexcept + { + at = 0; + misses = 0; + } +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 4031efe12f..ecaeefc3b4 100644 --- a/src/startup_stubs/memory_srv_buffer.h +++ b/src/startup_stubs/memory_srv_buffer.h @@ -127,6 +127,17 @@ inline bool resolve_buffer_srv_desc(std::uint64_t buffer_title_base, std::uint64 return true; } +// Largest unplaced buffer span, and largest allocation an unplaced buffer may wrap as an existing heap. +constexpr std::uint64_t unplaced_max_span = 256ull << 20; + +// OpenExistingHeapFromAddress wraps the whole allocation holding the view, not just the view's pages. A few KiB +// view in a multi-GiB title block must not wrap the block (afterwards each VirtualQuery over the block took +// seconds), so allocations of unknown size (0) or above the span limit take the upload copy instead. +inline bool unplaced_existing_heap_allowed(std::uint64_t allocation_bytes) +{ + return allocation_bytes && allocation_bytes <= unplaced_max_span; +} + // Calculates 64 KiB page-aligned extent and byte span for unplaced buffer memory SRVs. // Returns false on zero address/bytes, arithmetic overflow, or when the span exceeds the maximum allowable limit (256 MiB). inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_bytes, @@ -134,7 +145,7 @@ inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_byt { constexpr std::uint64_t alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; constexpr std::uint64_t mask = alignment - 1; - constexpr std::uint64_t max_span = 256ull << 20; + constexpr std::uint64_t max_span = unplaced_max_span; if (!address || !span_bytes || span_bytes > ~std::uint64_t{0} - address) return false; page_start = address & ~mask; const std::uint64_t end = address + span_bytes; @@ -144,6 +155,15 @@ inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_byt return page_span <= max_span && page_span >= span_bytes; } +// A structured or typed view needs (address - base) to be a whole number of elements. For a base at the 64 KiB page start +// that fails for most sub-allocated addresses; those views take a copy that starts at the address. A raw view never does: +// it keeps the page base so its 16-byte alignment check still sees the address. +inline bool unplaced_view_needs_exact_start(std::uint64_t address, std::uint64_t page_start, std::uint64_t elem_bytes, + bool raw) +{ + return !raw && elem_bytes > 1 && address >= page_start && (address - page_start) % elem_bytes != 0; +} + // Checks whether an existing cached page range completely covers the requested [address, address + span_bytes). inline bool unplaced_buffer_covers(std::uint64_t cached_start, std::uint64_t cached_span, std::uint64_t address, std::uint64_t span_bytes) diff --git a/src/startup_stubs/memory_srv_census.h b/src/startup_stubs/memory_srv_census.h index 9a6a725ec4..037e4a11f6 100644 --- a/src/startup_stubs/memory_srv_census.h +++ b/src/startup_stubs/memory_srv_census.h @@ -29,8 +29,12 @@ namespace x2w_startup { // tools/startup/triage_run.py keeps the same list (SLOT70_REASONS). constexpr const char* memory_srv_reasons[] = { "null_destination", "unreadable_resource", "unreadable_view", "null_address", - "unsupported_description", "destination_outside_view_heaps", "gpu_written_resource", "buffer_unavailable", - "texture_unavailable", + "unsupported_description", "destination_outside_view_heaps", "gpu_written_resource", + // the acceleration-structure holds of publish_as_srv (memory_srv_as.h, as_srv_refusal_name) + "as_unaligned", "as_not_placed", "as_wrong_state", + "buffer_unavailable", "texture_unavailable", + // the three causes texture_unavailable used to lump together (d3d12_memory_srv.inl, texture_unavailable_reason) + "texture_no_resource", "texture_unreadable", "texture_over_64mib", // the partial-tile holds of device_memory_srv (upstream #2105) "partial_tile_xg_rows", "partial_tile_beyond_xg_size", // the console-layout holds of device_memory_srv (#2015) @@ -39,6 +43,21 @@ constexpr const char* memory_srv_reasons[] = { }; constexpr int memory_srv_reason_count = static_cast<int>(sizeof(memory_srv_reasons) / sizeof(memory_srv_reasons[0])); +// The largest layout the transient upload ring accepts for one copy (publish_tiled_texture). +constexpr std::uint64_t max_published_texture_bytes = 64ull << 20; + +// Why no texture came back for a memory SRV (d3d12_memory_srv.inl, texture_unavailable_reason). `published` is true when a +// publication was attempted (BC, console layout, single element), false when only a live resource could have served the +// view. `readable` runs only for a layout within the limit, so a huge layout never pays a page-touch pass. +template <class Readable> +inline const char* texture_unavailable_cause(bool published, std::uint64_t bytes, Readable&& readable) +{ + if (!published) return "texture_no_resource"; + if (bytes > max_published_texture_bytes) return "texture_over_64mib"; + if (!readable()) return "texture_unreadable"; + return "texture_unavailable"; // publication failed for another reason (no wrapper) +} + inline int memory_srv_reason_index(const char* reason) { for (int i = 0; reason && i < memory_srv_reason_count; ++i) @@ -47,10 +66,13 @@ inline int memory_srv_reason_index(const char* reason) } // The reasons that depend on the resource description: their shapes are kept. The others (no -// destination, unreadable arguments, no address, a destination outside the view heaps) do not. +// destination, unreadable arguments, no address, a destination outside the view heaps, and the +// acceleration-structure holds, which read only the view's address) do not. inline bool memory_srv_reason_has_shape(int reason) { return reason < memory_srv_reason_count && reason != memory_srv_reason_index("null_destination") && + reason != memory_srv_reason_index("as_unaligned") && reason != memory_srv_reason_index("as_not_placed") && + reason != memory_srv_reason_index("as_wrong_state") && reason != memory_srv_reason_index("unreadable_resource") && reason != memory_srv_reason_index("unreadable_view") && reason != memory_srv_reason_index("null_address") && reason != memory_srv_reason_index("destination_outside_view_heaps"); } diff --git a/src/startup_stubs/mesh57_profile.h b/src/startup_stubs/mesh57_profile.h new file mode 100644 index 0000000000..84844db93b --- /dev/null +++ b/src/startup_stubs/mesh57_profile.h @@ -0,0 +1,97 @@ +#pragma once +#include "mesh_pixel_heap.h" +#include <d3d12.h> +#include <cstdint> +#include <cstring> +#include <vector> + +namespace x2w_startup +{ +inline std::vector<unsigned char> normalize_mesh57_descriptor(std::vector<unsigned char> desc) +{ + if (desc.size() < 15 * sizeof(std::uint64_t)) + return {}; + for (const auto index : {0, 1, 3, 5, 13}) + std::memset(desc.data() + index * sizeof(std::uint64_t), 0, sizeof(std::uint64_t)); + + // Extended fixed descriptors carry two shader-record blocks. Keep the distances + // between their internal pointers, while removing the process relocation. The + // repeated allocation address at +0x160/+0x2c0 varies independently. + if (desc.size() != 0x300) + return desc; + const auto word = [&](std::size_t offset) { + std::uint32_t value; + std::memcpy(&value, desc.data() + offset, sizeof(value)); + return value; + }; + const auto address = [&](std::size_t offset) { + std::uint64_t value; + std::memcpy(&value, desc.data() + offset, sizeof(value)); + return value; + }; + const auto is_pointer = [](std::uint64_t value) { + return value >= 0x10000 && value < 0x800000000000ull; + }; + const auto section = address(0x38); + const auto allocation = address(0x160); + if (address(0x48) || address(0x50) || !address(0x30) || !address(0x70) || + word(0x11c) != 0x04010000 || word(0x27c) != 0x04010000 || + !is_pointer(section) || !is_pointer(allocation) || allocation != address(0x2c0) || + word(0x110) + 0x10u != word(0x288) || word(0x270) + 0x10u != word(0x120)) + return desc; + + constexpr std::size_t section_pointers[]{ + 0x38, 0x78, 0x120, 0x128, 0x168, 0x178, 0x198, 0x1d8, + 0x280, 0x288, 0x2c8, 0x2d8, 0x2f8 + }; + for (const auto offset : section_pointers) { + const auto value = address(offset); + if (!is_pointer(value) || (value >= section ? value - section : section - value) > INT32_MAX) + return desc; + } + for (const auto offset : section_pointers) { + const auto relative = address(offset) - section; + std::memcpy(desc.data() + offset, &relative, sizeof(relative)); + } + for (const auto offset : {0x110, 0x270}) { + const auto relative = word(offset) - static_cast<std::uint32_t>(section); + std::memcpy(desc.data() + offset, &relative, sizeof(relative)); + } + for (const auto offset : {0x160, 0x2c0}) + std::memset(desc.data() + offset, 0, sizeof(allocation)); + return desc; +} +// A reviewed fixed-state/entry record. The header is followed by the exact normalized fixed +// descriptor, the two register blocks, creation root blob, guest MS and guest PS, in this order. +// Descriptor normalization removes the relocations recognized in each fixed layout. +struct Mesh57Profile { + char magic[8]; + UINT lengths[6]; + UINT threads, vertices, primitives, topology, group_stride, wave_size; + D3D12_BLEND_DESC blend; + D3D12_RASTERIZER_DESC rasterizer; + D3D12_DEPTH_STENCIL_DESC depth; + D3D12_RT_FORMAT_ARRAY targets; + DXGI_FORMAT depth_format; + DXGI_SAMPLE_DESC samples; + UINT sample_mask; +}; +static_assert(sizeof(Mesh57Profile) == 532, "update the offline mesh57 profile reader when the ABI changes"); +// Version 2 stores this immediately after Mesh57Profile, before the six byte spans. +struct Mesh57PixelEntry { + UINT enable, address, wave_size; +}; +// Version 3 adds one reviewed MS entry mapping after the version 2 pixel entry. +struct Mesh57ConstantEntry { + UINT sgpr, root_parameter, count; +}; +// Version 4 adds a count followed by this many MS table/root-address SGPR mappings. +// Version 5 then stores the physical resource-heap SGPR; selector and view class come from the MS. +struct Mesh57ViewEntry { + UINT sgpr, root_parameter, root_address; +}; +struct Mesh57BufferRead { + UINT root_parameter, offset, minimum_bytes; + bool root_address; +}; +} // namespace x2w_startup diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 175671c9b0..0c2fe5b3ef 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -255,7 +255,8 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d std::memcpy(request.stream.data() + request.root_offset + 8, &request.root, sizeof(request.root)); const D3D12_PIPELINE_STATE_STREAM_DESC desktop{request.stream.size(), request.stream.data()}; bool compute = false; - auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, + ID3D12RootSignature* pipeline_root = nullptr; + auto* result = build_stream_pipeline(&desktop, why, why_size, compute, graphics, pipeline_root, static_cast<ID3D12RootSignature*>(request.root->own().real)); if (result) graphics.cached_srv_root = srv_root; static LONG loaded; diff --git a/src/startup_stubs/native_buffer_stride.h b/src/startup_stubs/native_buffer_stride.h new file mode 100644 index 0000000000..8d89e6db6d --- /dev/null +++ b/src/startup_stubs/native_buffer_stride.h @@ -0,0 +1,70 @@ +#pragma once + +#include "memory_srv_buffer.h" +#include <cstddef> +#include <cstring> + +namespace x2w_startup { +inline UINT typed_dword_channels(const D3D12_SHADER_RESOURCE_VIEW_DESC &view) { + if (view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || view.Buffer.StructureByteStride || + view.Buffer.Flags || view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) + return 0; + switch (view.Format) { + case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R32_FLOAT: return 1; + case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R32G32_FLOAT: return 2; + case DXGI_FORMAT_R32G32B32_UINT: case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R32G32B32_FLOAT: return 3; + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32A32_FLOAT: return 4; + default: return 0; + } +} + +inline DXGI_FORMAT typed_dword_uint_format(UINT channels) { + constexpr DXGI_FORMAT formats[]{DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32G32_UINT, + DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32A32_UINT}; + return channels <= 4 ? formats[channels] : DXGI_FORMAT_UNKNOWN; +} + +// Only a verified materialized token supplies the slot and address. Unregistered +// entries keep their empty record (slot zero), even if their heap bytes are zero. +inline bool native_null_typed_array_srv(UINT slot, UINT64 address, const void *bytes, size_t size, + UINT required_bytes, D3D12_SHADER_RESOURCE_VIEW_DESC &view) { + if (slot != 18 || address || !bytes || size < sizeof(view)) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + std::memcpy(&desc, bytes, sizeof(desc)); + const UINT channels = typed_dword_channels(desc); + if (!channels || channels * 4 < required_bytes) return false; + desc.Format = typed_dword_uint_format(channels); + view = desc; + return true; +} + +// The shader indexes raw views in bytes and structured views in elements. +inline bool native_view_stride(UINT slot, const void *bytes, std::size_t size, UINT &stride) { + bool raw = false; + DXGI_FORMAT format{}; + stride = 0; + if (slot == 18) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + if (size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + if (desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return true; + stride = desc.Buffer.StructureByteStride; + raw = (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) != 0; + format = desc.Format; + } else if (slot == 19) { + D3D12_UNORDERED_ACCESS_VIEW_DESC desc{}; + if (size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + if (desc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) return true; + stride = desc.Buffer.StructureByteStride; + raw = (desc.Buffer.Flags & D3D12_BUFFER_UAV_FLAG_RAW) != 0; + format = desc.Format; + } else { + return false; + } + if (!stride) + stride = raw ? 1u : x2w_startup::typed_buffer_format_bytes(format); + return stride > 0 && stride <= 0x3fff; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_copy_ranges.h b/src/startup_stubs/native_copy_ranges.h new file mode 100644 index 0000000000..49aa769a3c --- /dev/null +++ b/src/startup_stubs/native_copy_ranges.h @@ -0,0 +1,55 @@ +#pragma once + +#include <algorithm> +#include <cstdint> +#include <vector> + +namespace x2w_startup { +enum class CopyCoverage { none, partial, full }; + +// A union of disjoint half-open offsets in one placement. Callers validate +// the offsets against the buffer size before adding or looking up a range. +struct NativeCopyRanges { + struct Span { std::uint64_t begin, end; }; + std::vector<Span> spans; + + void add(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return; + auto first = std::lower_bound(spans.begin(), spans.end(), begin, + [](const Span& row, std::uint64_t start) { return row.end < start; }); + auto last = first; + while (last != spans.end() && last->begin <= end) { + begin = (std::min)(begin, last->begin); + end = (std::max)(end, last->end); + ++last; + } + spans.insert(spans.erase(first, last), {begin, end}); + } + + void cpu_write(std::uint64_t begin, std::uint64_t end) { + if (begin >= end) return; + for (auto it = spans.begin(); it != spans.end() && it->begin < end;) { + if (it->end <= begin) { ++it; continue; } + const Span old = *it; + if (old.begin < begin) { + it->end = begin; + ++it; + if (old.end > end) { spans.insert(it, {end, old.end}); return; } + } else if (old.end > end) { + it->begin = end; + return; + } else { + it = spans.erase(it); + } + } + } + + CopyCoverage coverage(std::uint64_t begin, std::uint64_t end) const { + if (begin >= end) return CopyCoverage::none; + auto row = std::lower_bound(spans.begin(), spans.end(), begin, + [](const Span& s, std::uint64_t start) { return s.end <= start; }); + if (row == spans.end() || row->begin >= end) return CopyCoverage::none; + return row->begin <= begin && end <= row->end ? CopyCoverage::full : CopyCoverage::partial; + } +}; +} diff --git a/src/startup_stubs/native_dispatch_states.h b/src/startup_stubs/native_dispatch_states.h new file mode 100644 index 0000000000..8ad02d8e25 --- /dev/null +++ b/src/startup_stubs/native_dispatch_states.h @@ -0,0 +1,101 @@ +#pragma once +#include <d3d12.h> +#include <algorithm> +#include <map> +#include <stdexcept> +#include <string> +#include <vector> + +namespace x2w_startup { +struct NativeTextureWindow { + UINT mip = 0, mips = 1, slice = 0, slices = 1, plane = 0; +}; + +// Build from the resolved descriptors for one dispatch. A single-access +// resource needs one whole-resource state irrespective of its mip/array size. +class NativeDispatchStates { + struct Interval { UINT first, end; bool write; }; + struct Use { + bool read = false, write = false, upload = false; + UINT mips = 0, slices = 0; + std::vector<Interval> intervals; + }; + std::map<ID3D12Resource *, Use> resources; + std::vector<D3D12_RESOURCE_BARRIER> transitions, uavs; + + public: + template<class Views> explicit NativeDispatchStates(const Views &views) { + bool mixed_access = false; + for (const auto &v : views) { + if (!v.resource) continue; + auto &use = resources[v.resource.Get()]; + if (v.write) use.write = true; + else use.read = true; + use.upload |= v.buffer.upload; + mixed_access |= use.read && use.write; + } + if (mixed_access) for (const auto &v : views) { + if (!v.resource) continue; + auto &use = resources.at(v.resource.Get()); + if (!use.read || !use.write) continue; + if (!use.mips) { + const auto desc = v.resource->GetDesc(); + use.mips = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? 1 : desc.MipLevels; + use.slices = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : desc.DepthOrArraySize; + } + const auto &w = v.texture; + if (!w.mip && w.mips == use.mips) { + const UINT first = (w.slice + w.plane * use.slices) * use.mips; + use.intervals.push_back({first, first + w.slices * use.mips, v.write}); + continue; + } + for (UINT a = 0; a < w.slices; ++a) { + const UINT first = w.mip + (w.slice + a + w.plane * use.slices) * use.mips; + use.intervals.push_back({first, first + w.mips, v.write}); + } + } + for (auto &[resource, use] : resources) { + if (!use.write) continue; + if (use.upload) throw std::runtime_error("native UAV aliases an upload heap"); + D3D12_RESOURCE_BARRIER uav{}; + uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + uav.UAV.pResource = resource; + uavs.push_back(uav); + auto &ranges = use.intervals; + std::sort(ranges.begin(), ranges.end(), [](auto &a, auto &b) { return a.first < b.first; }); + for (size_t j = 0; j < ranges.size();) { + auto range = ranges[j++]; + while (j < ranges.size() && ranges[j].first <= range.end) { + if (ranges[j].write != range.write) { + if (ranges[j].first < range.end) + throw std::runtime_error("overlapping compute SRV and UAV subresource " + std::to_string(ranges[j].first)); + break; + } + range.end = (std::max)(range.end, ranges[j++].end); + } + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, range.first, D3D12_RESOURCE_STATE_COMMON, + range.write ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE}; + for (; b.Transition.Subresource < range.end; ++b.Transition.Subresource) + transitions.push_back(b); + } + } + } + bool mixed(ID3D12Resource *resource) const { + auto i = resources.find(resource); + return i != resources.end() && i->second.read && i->second.write; + } + template<class Apply> void whole_states(Apply apply) const { + for (const auto &[resource, use] : resources) + if (!use.upload) + apply(resource, use.write ? (use.read ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_UNORDERED_ACCESS) + : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + const auto &split() const { return transitions; } + const auto &writes() const { return uavs; } + void reverse() { + for (auto &b : transitions) std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + } +}; +} diff --git a/src/startup_stubs/native_global_srv.h b/src/startup_stubs/native_global_srv.h new file mode 100644 index 0000000000..0ea0f62d9a --- /dev/null +++ b/src/startup_stubs/native_global_srv.h @@ -0,0 +1,148 @@ +#pragma once + +#include "native_buffer_stride.h" +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <d3d12.h> +#include <sstream> +#include <string> +#include <vector> + +// The view type of a global (descriptor heap) SRV slot that a dispatch can select from GPU data. +// +// A shader that picks its slot at run time can only be recorded and replayed if the type of every slot it may pick is +// known: the capture keeps {slot, type, stride} for each slot of the heap, and the dispatch is refused, before any +// shader runs, when the selected slot holds another type than the one the shader reads. No heap-indexed data read is +// translated here; this header only classifies, serializes and checks. +// +// A .views file describes the one dispatch it was captured from. It is not part of the .cdx/.root content key of the +// request it sits next to. +namespace x2w_startup { +enum class GlobalSrvType : unsigned { none, raw_buffer, structured_buffer, typed_buffer, texture }; + +inline const char *global_srv_type_name(GlobalSrvType type) { + switch (type) { + case GlobalSrvType::raw_buffer: return "raw_buffer"; + case GlobalSrvType::structured_buffer: return "structured_buffer"; + case GlobalSrvType::typed_buffer: return "typed_buffer"; + case GlobalSrvType::texture: return "texture"; + default: return "none"; + } +} + +inline GlobalSrvType global_srv_type_from_name(const std::string &name) { + for (auto type : {GlobalSrvType::raw_buffer, GlobalSrvType::structured_buffer, GlobalSrvType::typed_buffer, + GlobalSrvType::texture}) + if (name == global_srv_type_name(type)) return type; + return GlobalSrvType::none; +} + +struct GlobalSrvView { + unsigned slot = 0; + GlobalSrvType type = GlobalSrvType::none; + unsigned stride = 0; // Bytes per element for a buffer view (the value native_view_stride gives), 0 for a texture. + std::uint64_t bytes = 0; // Size of the buffer in bytes, 0 for a texture. Set by the caller from the resource description. +}; + +// Classifies the description a title passed for an SRV (slot 18 of the device interface). False: not a view this +// path can name (an unknown dimension, or a buffer view without a usable stride). +inline bool classify_global_srv_view(unsigned heap_slot, const void *bytes, std::size_t size, GlobalSrvView &view) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + if (!bytes || size < sizeof(desc)) return false; + std::memcpy(&desc, bytes, sizeof(desc)); + view = {}; + view.slot = heap_slot; + if (desc.ViewDimension == D3D12_SRV_DIMENSION_UNKNOWN) return false; + if (desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) { + view.type = GlobalSrvType::texture; + return true; + } + if (!native_view_stride(18, bytes, size, view.stride)) return false; + view.type = desc.Buffer.StructureByteStride ? GlobalSrvType::structured_buffer + : (desc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) ? GlobalSrvType::raw_buffer + : GlobalSrvType::typed_buffer; + return true; +} + +// One request's view metadata, the text that travels with a captured request (req_<key>.views). +struct GlobalSrvRequest { + unsigned selected = 0; + GlobalSrvType needed = GlobalSrvType::none; + std::vector<GlobalSrvView> views; + bool has_selected = false; +}; + +inline std::string encode_global_srv_request(const GlobalSrvRequest &request) { + std::ostringstream out; + out << "x2w-global-srv-views 2\nselect " << request.selected << "\nneed " << global_srv_type_name(request.needed) << '\n'; + for (const auto &view : request.views) + out << "slot " << view.slot << ' ' << global_srv_type_name(view.type) << ' ' << view.stride << ' ' << view.bytes << '\n'; + return out.str(); +} + +// False with a diagnostic in `error` for a text that cannot reconstruct the binding. +inline bool decode_global_srv_request(const std::string &text, GlobalSrvRequest &request, std::string &error) { + request = {}; + std::istringstream in(text); + std::string line; + if (!std::getline(in, line) || line != "x2w-global-srv-views 2") { + error = "global SRV view metadata has no 'x2w-global-srv-views 2' header"; + return false; + } + bool has_need = false; + while (std::getline(in, line)) { + std::istringstream fields(line); + std::string key; + fields >> key; + if (key.empty()) continue; + if (key == "select") { + if (!(fields >> request.selected)) { error = "global SRV view metadata: unreadable select line"; return false; } + request.has_selected = true; + } else if (key == "need") { + std::string name; + fields >> name; + request.needed = global_srv_type_from_name(name); + if (request.needed == GlobalSrvType::none) { + error = "global SRV view metadata: unknown needed view type '" + name + "'"; + return false; + } + has_need = true; + } else if (key == "slot") { + GlobalSrvView view; + std::string name; + if (!(fields >> view.slot >> name >> view.stride >> view.bytes)) { + error = "global SRV view metadata: unreadable slot line"; + return false; + } + view.type = global_srv_type_from_name(name); + if (view.type == GlobalSrvType::none) { + error = "global SRV slot " + std::to_string(view.slot) + " has unknown view type '" + name + "'"; + return false; + } + request.views.push_back(view); + } else { + error = "global SRV view metadata: unknown line '" + key + "'"; + return false; + } + } + if (!request.has_selected || !has_need) { + error = std::string("global SRV view metadata lacks the ") + (request.has_selected ? "needed view type" : "selected slot"); + return false; + } + return true; +} + +// Empty when the selected slot holds the type the shader reads. Otherwise the refusal text: it names the slot and the +// view types, and is produced before the shader runs. Used by the native recording and by the replay alike. +inline std::string refuse_global_srv_selection(const std::vector<GlobalSrvView> &views, unsigned selected, + GlobalSrvType needed) { + for (const auto &view : views) { + if (view.slot != selected) continue; + if (view.type == needed) return {}; + return "global SRV slot " + std::to_string(selected) + " has view type " + global_srv_type_name(view.type) + + ", the shader needs " + global_srv_type_name(needed); + } + return "global SRV slot " + std::to_string(selected) + " has no captured view type"; +} +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl new file mode 100644 index 0000000000..b8455b82d3 --- /dev/null +++ b/src/startup_stubs/native_mesh57.inl @@ -0,0 +1,450 @@ +// Included after both the native graphics compiler and the desktop stream validator. +// Resolve every SRV before recording barriers or a descriptor table. A guest root address +// has no descriptor length; use the remaining proven GPU allocation, including for indexed reads. +const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommandList* list, ID3D12Resource* arguments) +{ + const auto* info = pipeline_info(pass.pipeline); + if (!info) return "missing MS creation metadata"; + const auto& reads = info->mesh57_reads; + const auto& spans = info->mesh57_pixel_spans; + if (reads.empty() && spans.empty()) { + list->SetGraphicsRootSignature(pass.indirect_graphics.root); + return nullptr; + } + std::array<IndirectBufferView,32> views{}; + if (reads.size() > views.size()) return "too many MS buffer reads"; + for (size_t i = 0; i < reads.size(); ++i) { + const auto& read = reads[i]; + auto& view = views[i]; + if (read.root_address) { + const auto address = pass.root_address[read.root_parameter]; + if (!address) return "missing MS root SRV address"; + if (auto range = list_upload_range(self, address, read.minimum_bytes, true); range.resource) { + view = {range.resource, range.offset, range.bytes, 0, true}; + } else { + const auto placed = placed_buffer_range(self->own().list_device, address, read.minimum_bytes); + if (placed.reject || !placed.owner || !placed.owner->own().real) + return "MS root SRV lacks a complete GPU-backed range"; + auto* backing = static_cast<ID3D12Resource*>(placed.owner->own().real); + const auto offset = address - reinterpret_cast<u64>(placed.owner->own().title_memory); + const auto width = backing->GetDesc().Width; + if (address >> 48 || offset >= width || width - offset > UINT_MAX) + return "MS root SRV range outside raw buffer limits"; + const UINT words[]{static_cast<UINT>(address), static_cast<UINT>(address >> 32), + static_cast<UINT>(width - offset), 0}; + view = indirect_table_buffer(self, words); + } + } else { + const auto entry = pass.view_tables[read.root_parameter].record(read.offset, 32); + if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) + return "MS descriptor table slot is absent"; + UINT words[8]{}; + std::memcpy(words, reinterpret_cast<const void*>(entry), sizeof(words)); + if (words[0] == view_token_magic) { + x2w_startup::ExclusiveNoteLock lock(note_lock); + if (words[1] >= view_records().size() || view_records()[words[1]].slot != 18) + return "MS descriptor table slot is not an SRV"; + } else if (words[3] != 0x31016fac || (words[1] & 0xffff0000)) { + return "unsupported MS native byte buffer descriptor"; + } + view = indirect_table_buffer(self, words); + } + if (!view.resource || view.resource == arguments || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + view.bytes < read.minimum_bytes || view.bytes % 4 || view.bytes > UINT_MAX) + return "MS buffer read exceeds its usable GPU-backed range"; + } + UINT index = UINT_MAX; + IndirectBufferView typed{}; + if (info->mesh57_heap_word != UINT_MAX) { + if (!pass.mesh_heap_slots) return "MS direct read requires one bound shader-visible view heap"; + index = pass.constants[pass.indirect_graphics.constant_guest][info->mesh57_heap_word] & 1023u; + if (index >= pass.mesh_heap_slots) return "selected MS heap index exceeds its logical descriptor count"; + const auto entry = pass.title_view_heap.record(UINT64{index} * 32, 32); + if (!entry || !x2w_local::readable(reinterpret_cast<const void*>(entry), 32)) + return "selected MS heap slot is outside the bound shader-visible heap"; + UINT words[8]{}; + std::memcpy(words, reinterpret_cast<const void*>(entry), sizeof(words)); + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + if (words[0] != view_token_magic || words[1] >= view_records().size()) + return "selected MS heap slot lacks a registered SRV"; + const auto& record = view_records()[words[1]]; + if (record.slot != 18 || record.desc_bytes < sizeof(view)) return "selected MS heap slot is not an SRV"; + std::memcpy(&view,record.desc,sizeof(view)); + } + if (view.Format != DXGI_FORMAT_R32_UINT || view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || + view.Buffer.Flags != D3D12_BUFFER_SRV_FLAG_NONE || view.Buffer.StructureByteStride || + !view.Buffer.NumElements || view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) + return "selected MS heap SRV requires an R32_UINT buffer"; + typed = indirect_table_buffer(self, words, false, nullptr, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, 4); + if (!typed.resource || typed.resource == arguments || typed.stride != 4 || + typed.bytes != UINT64{view.Buffer.NumElements} * 4) + return "selected MS heap SRV lacks its complete GPU-backed range"; + if (!retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(typed.resource))) + return "selected MS heap SRV could not be retained"; + } + struct Sampled { Wrapper* owner; x2w_startup::ComPtr<ID3D12Resource> resource; D3D12_SHADER_RESOURCE_VIEW_DESC view; UINT slot; }; + std::vector<Sampled> textures; + auto* device = device_of(self->own().list_device); + for (const auto& span : spans) { + if (span.last >= pass.mesh_heap_slots) return "PS texture index exceeds the bound guest heap"; + for (UINT slot=span.first; slot<=span.last; ++slot) { + const auto at=pass.title_view_heap.record(UINT64{slot}*32,32); + if (!at || !x2w_local::readable(reinterpret_cast<const void*>(at),32)) return "PS texture heap slot inaccessible"; + UINT token[2]; + std::memcpy(token,reinterpret_cast<const void*>(at),sizeof(token)); + ViewRecord record{}; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + if (token[0]!=view_token_magic || token[1]>=view_records().size()) return "PS heap slot lacks a registered SRV"; + record=view_records()[token[1]]; + } + if (record.slot!=18 || record.desc_bytes<sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) return "PS texture heap requires an explicit SRV"; + Sampled sampled{}; + auto& srv=sampled.view; + std::memcpy(&srv,record.desc,sizeof(srv)); + srv.Format=desktop_format(srv.Format); + const bool array=span.dimension==5; + if (srv.ViewDimension!=(array?D3D12_SRV_DIMENSION_TEXTURE2DARRAY:D3D12_SRV_DIMENSION_TEXTURE2D)) return "PS heap texture dimension mismatch"; + const auto family=[](DXGI_FORMAT f) { + if (f>=DXGI_FORMAT_BC1_TYPELESS && f<=DXGI_FORMAT_BC1_UNORM_SRGB) return DXGI_FORMAT_BC1_TYPELESS; + if (f>=DXGI_FORMAT_BC7_TYPELESS && f<=DXGI_FORMAT_BC7_UNORM_SRGB) return DXGI_FORMAT_BC7_TYPELESS; + if (f>=DXGI_FORMAT_R8G8B8A8_TYPELESS && f<=DXGI_FORMAT_R8G8B8A8_SINT) return DXGI_FORMAT_R8G8B8A8_TYPELESS; + return f; + }; + if (!float_uav_format(srv.Format) && srv.Format!=DXGI_FORMAT_R8G8B8A8_UNORM_SRGB && + srv.Format!=DXGI_FORMAT_BC1_UNORM && srv.Format!=DXGI_FORMAT_BC1_UNORM_SRGB && + srv.Format!=DXGI_FORMAT_BC7_UNORM && srv.Format!=DXGI_FORMAT_BC7_UNORM_SRGB) + return "PS heap texture requires a supported float or normalized SRV"; + if (record.resource) { + sampled.owner=as_wrapper(reinterpret_cast<const void*>(record.resource)); + auto* tex=sampled_address_texture(sampled.owner); + if (!tex || tex==arguments || std::find(pass.bound_targets,pass.bound_targets+pass.target_count,tex)!=pass.bound_targets+pass.target_count || + (tex==pass.bound_depth && pass.depth_view_writable)) return "PS heap texture missing or aliased to a writable attachment"; + const auto d=tex->GetDesc(); + const UINT first=srv.Texture2D.MostDetailedMip, levels=srv.Texture2D.MipLevels; + if (d.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.SampleDesc.Count!=1 || + (d.Format!=srv.Format && (d.Format!=family(d.Format) || family(srv.Format)!=d.Format)) || + first>=d.MipLevels || !levels || (levels!=UINT_MAX && levels>d.MipLevels-first) || + (array ? (!srv.Texture2DArray.ArraySize || srv.Texture2DArray.FirstArraySlice>=d.DepthOrArraySize || + srv.Texture2DArray.ArraySize>d.DepthOrArraySize-srv.Texture2DArray.FirstArraySlice || srv.Texture2DArray.PlaneSlice) + : (d.DepthOrArraySize!=1 || srv.Texture2D.PlaneSlice))) return "PS texture SRV outside resource format, mip or array range"; + sampled.resource=tex; + if (!retain_with_recording(self,sampled.resource)) return "PS texture lifetime retention failed"; + } + sampled.slot=span.host_first+slot-span.first; + textures.push_back(std::move(sampled)); + } + } + for (auto& texture : textures) + if (texture.resource && !upload_texture(self,texture.owner,texture.resource.Get())) return "PS heap texture upload failed"; + const UINT prefix=spans.empty() ? (typed.resource ? index+1 : 0) : + spans.back().host_first+(spans.back().last-spans.back().first+1); + constexpr UINT capacity = 256; + const auto increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + DrawSamplerHeap heap; + UINT start; + { + x2w_startup::ExclusiveNoteLock guard(allocator_lock); + const auto recording = list_recordings.find(self); + if (!self->own().list_open || recording == list_recordings.end() || !recording->second) + return "MS descriptor table requires an open recording"; + auto& allocator = *recording->second; + const bool changed = index != allocator.mesh_heap_index || + (typed.resource && (allocator.mesh_heap_buffer != typed.resource || allocator.mesh_heap_begin != typed.offset || + allocator.mesh_heap_size != typed.bytes)); + if (!spans.empty() || allocator.mesh_view_pages.empty() || changed || reads.size() > capacity - allocator.mesh_view_cursor) { + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, capacity + prefix, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap)))) return "MS descriptor heap allocation failed"; + try { allocator.mesh_view_pages.push_back(heap); } + catch (const std::bad_alloc&) { return "MS descriptor heap could not be retained with its recording"; } + allocator.mesh_view_cursor = 0; + allocator.mesh_heap_index = index; + allocator.mesh_heap_buffer = typed.resource; + allocator.mesh_heap_begin = typed.offset; + allocator.mesh_heap_size = typed.bytes; + if (typed.resource) { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.FirstElement = typed.offset / 4; + srv.Buffer.NumElements = static_cast<UINT>(typed.bytes / 4); + auto selected = heap->GetCPUDescriptorHandleForHeapStart(); + selected.ptr += SIZE_T{index} * increment; + device->CreateShaderResourceView(typed.resource,&srv,selected); + } + } else { + heap = allocator.mesh_view_pages.back(); + } + start = allocator.mesh_view_cursor + prefix; + allocator.mesh_view_cursor = spans.empty() ? allocator.mesh_view_cursor + static_cast<UINT>(reads.size()) : capacity; + } + for (auto& texture : textures) { + auto dst=heap->GetCPUDescriptorHandleForHeapStart(); + dst.ptr+=SIZE_T{texture.slot}*increment; + device->CreateShaderResourceView(texture.resource.Get(),&texture.view,dst); + if (texture.resource) { + require_state(self, texture.resource.Get(), sampled_state(self, texture.resource.Get())); + if (!texture.owner->own().tiled_address_srv) retire_hold(self, texture.owner); + } + } + auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T{start} * increment; + for (size_t i = 0; i < reads.size(); ++i) { + const auto& view = views[i]; + if (!retain_with_recording(self, x2w_startup::ComPtr<ID3D12Resource>(view.resource))) + return "MS buffer could not be retained with its recording"; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer = {view.offset / 4, static_cast<UINT>(view.bytes / 4), 0, D3D12_BUFFER_SRV_FLAG_RAW}; + device->CreateShaderResourceView(view.resource, &srv, handle); + handle.ptr += increment; + } + for (size_t i = 0; i < reads.size(); ++i) + if (!views[i].upload) require_state(self, views[i].resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + if (typed.resource && !typed.upload) require_state(self, typed.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + auto* native_heap = heap.Get(); + list->SetDescriptorHeaps(1, &native_heap); + list->SetGraphicsRootSignature(pass.indirect_graphics.root); + auto gpu = heap->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += UINT64{start} * increment; + if (!reads.empty()) list->SetGraphicsRootDescriptorTable(1, gpu); + return nullptr; +} +#ifdef X2W_NATIVE_SHADERS +void prepare_native_mesh57(Wrapper* pipeline) +{ + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!sdk_length || sdk_length >= MAX_PATH) + return; + const auto* info = pipeline_info(pipeline); + if (!info || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return; + const auto& ms_bytes = *info->fixed_ms; + const auto& ps_bytes = *info->fixed_ps; + u64 fields[0x300 / sizeof(u64)]; + std::memcpy(fields, info->desc.data(), sizeof(fields)); + auto* root = as_wrapper(reinterpret_cast<const void*>(fields[0])); + if (!root || root->own().kind != root_signature_kind || !root->own().real || !root_info(root) || + fields[2] != info->state_a.size() || fields[4] != info->state_b.size()) + return; + std::vector<unsigned char> root_blob; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + const auto it = root_blobs().find(root); + if (it == root_blobs().end()) + return; + root_blob = it->second; + } + constexpr char revision[] = "x2w-startup-mesh-57-3"; + const u64 key = fnv_part(root_blob, fnv_part(ps_bytes, fnv_part(ms_bytes, fnv_bytes(revision, sizeof(revision) - 1)))); + const auto normalized = x2w_startup::normalize_mesh57_descriptor(info->desc); + const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); + if (!cache_path(path, L"", variant, L".mesh57-state")) + return; + std::ifstream file(std::filesystem::path(path), std::ios::binary); + if (!file) + return; + try { + x2w_startup::Mesh57Profile profile{}; + if (!file.read(reinterpret_cast<char*>(&profile), sizeof(profile))) + throw std::runtime_error("invalid profile header"); + const bool pixel_heap = !std::memcmp(profile.magic,"X2WM576",8); + const bool direct_heap = pixel_heap || !std::memcmp(profile.magic, "X2WM575", 8); + const bool buffers = direct_heap || !std::memcmp(profile.magic, "X2WM574", 8); + const bool mapped = buffers || !std::memcmp(profile.magic, "X2WM573", 8); + const bool varying_pixel = mapped || !std::memcmp(profile.magic, "X2WM572", 8); + x2w_startup::Mesh57PixelEntry entry{}; + if (varying_pixel) { + if (!file.read(reinterpret_cast<char*>(&entry), sizeof(entry))) + throw std::runtime_error("truncated fixed pixel entry"); + } else if (std::memcmp(profile.magic, "X2WM571", 8)) { + throw std::runtime_error("unknown fixed profile version"); + } + x2w_startup::Mesh57ConstantEntry mapping{}; + if (mapped) { + if (!file.read(reinterpret_cast<char*>(&mapping), sizeof(mapping)) || mapping.root_parameter >= 16 || + !mapping.count || mapping.count > 8 || !root_heap_flags(root)) + throw std::runtime_error("invalid MS constant mapping or guest root is not deferred"); + } else if (!root_info(root)->empty() || root_heap_flags(root)) { + throw std::runtime_error("fixed mesh profile lacks guest root mapping"); + } + std::vector<x2w_startup::Mesh57ViewEntry> view_entries; + if (buffers) { + UINT count{}; + if (!file.read(reinterpret_cast<char*>(&count), sizeof(count)) || !count || count > 15) + throw std::runtime_error("invalid MS view entry count"); + view_entries.resize(count); + if (!file.read(reinterpret_cast<char*>(view_entries.data()), count * sizeof(view_entries[0]))) + throw std::runtime_error("truncated MS view mappings"); + for (const auto& e : view_entries) + if (e.root_address > 1) throw std::runtime_error("invalid MS view mapping"); + } + UINT heap_sgpr{}; + if (direct_heap && (!file.read(reinterpret_cast<char*>(&heap_sgpr), sizeof(heap_sgpr)) || + !(root_heap_flags(root) & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED))) + throw std::runtime_error("missing MS resource heap mapping"); + const auto match = [&](UINT part, const void* bytes, size_t size) { + if (size != profile.lengths[part]) + return false; + if (!size) + return true; + std::string copy(size, 0); + return file.read(copy.data(), size) && !std::memcmp(copy.data(), bytes, size); + }; + if (!match(0, normalized.data(), normalized.size()) || !match(1, info->state_a.data(), info->state_a.size()) || + !match(2, info->state_b.data(), info->state_b.size()) || !match(3, root_blob.data(), root_blob.size()) || + !match(4, ms_bytes.data(), ms_bytes.size()) || !match(5, ps_bytes.data(), ps_bytes.size()) || file.peek() != EOF) + throw std::runtime_error("profile input bytes differ"); + if (!profile.targets.NumRenderTargets || profile.targets.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT || + ((profile.depth.DepthEnable || profile.depth.StencilEnable) && profile.depth_format == DXGI_FORMAT_UNKNOWN) || + profile.samples.Count != 1 || + profile.samples.Quality || profile.sample_mask != UINT_MAX || + (profile.wave_size != 32 && profile.wave_size != 64)) + throw std::runtime_error("unsupported fixed attachment or sample state"); + const std::string ms(ms_bytes.begin(), ms_bytes.end()), ps(ps_bytes.begin(), ps_bytes.end()); + x2w::MeshStageLayout mesh_layout{profile.threads, profile.vertices, profile.primitives, + profile.topology, profile.group_stride, profile.wave_size == 32}; + mesh_layout.packed_parameters = varying_pixel; + if (direct_heap) { + mesh_layout.resource_heap_sgpr = heap_sgpr; + mesh_layout.validate_uint_heap_reads = true; + } + x2w_startup::ComPtr<ID3D12VersionedRootSignatureDeserializer> deserializer; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* guest_desc = nullptr; + if (mapped) { + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(root_blob.data(), root_blob.size(), IID_PPV_ARGS(&deserializer))) || + FAILED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &guest_desc))) + throw std::runtime_error("invalid MS creation root signature"); + mesh_layout.root_inputs.push_back({mapping.sgpr, mapping.root_parameter, mapping.count}); + for (const auto& e : view_entries) + mesh_layout.root_inputs.push_back({e.sgpr, e.root_parameter, 0, e.root_address != 0}); + } + auto native = mapped ? x2w::translate_mesh_program(ms, mesh_layout, guest_desc->Desc_1_1) + : x2w::translate_mesh_program(ms, mesh_layout); + const bool mapped_constants = mapped && native.constants.size() == 1 && + native.constants[0].root_parameter == mapping.root_parameter && native.constants[0].count == mapping.count && + native.constants[0].first_sgpr == mapping.sgpr; + if ((mapped ? !mapped_constants : !native.constants.empty()) || (!buffers && !native.bindings.empty()) || !native.samplers.empty() || native.sampler_heap || + (direct_heap ? native.mesh_heap_reads.empty() : !native.mesh_heap_reads.empty())) + throw std::runtime_error("MS needs root or heap bindings"); + UINT heap_word = UINT_MAX; + for (const auto& guard : native.mesh_heap_reads) { + if (guard.root_parameter != mapping.root_parameter || guard.dword >= mapping.count || guard.mask != 1023 || + (heap_word != UINT_MAX && heap_word != guard.dword)) + throw std::runtime_error("unsupported MS resource heap index contract"); + heap_word = guard.dword; + } + std::vector<x2w_startup::Mesh57BufferRead> reads; + if (buffers) { + if (native.bindings.empty() || native.bindings.size() > 32) + throw std::runtime_error("unsupported MS buffer binding count"); + for (auto b : native.bindings) { + if (b.shader_register != reads.size() || b.root_parameter >= guest_desc->Desc_1_1.NumParameters || + b.root_parameter >= 16 || !b.required_bytes || b.array_count != 1 || b.array_position) + throw std::runtime_error("unsupported MS buffer register or span"); + const bool direct = b.kind == x2w::ComputeViewKind::root_buffer_srv; + const auto& param = guest_desc->Desc_1_1.pParameters[b.root_parameter]; + if (direct) { + if (param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV || b.byte_offset) + throw std::runtime_error("MS root buffer requires a root SRV"); + } else { + if (b.kind != x2w::ComputeViewKind::buffer_srv || param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + throw std::runtime_error("MS table read requires a scalar SRV"); + // Validate this creation root's range even when reflection already classified the slot. + using Table = x2w::ComputeViewBinding::ScalarTable; + if (b.scalar_table != Table::unknown && b.scalar_table != Table::srv) + throw std::runtime_error("MS table binding is not an SRV"); + b.scalar_table = Table::unknown; + x2w::apply_scalar_table_layout(b, param.DescriptorTable); + if (b.scalar_table != x2w::ComputeViewBinding::ScalarTable::srv || b.byte_offset % 32) + throw std::runtime_error("MS buffer slot outside a verified SRV range"); + } + reads.push_back({b.root_parameter, b.byte_offset, b.required_bytes, direct}); + } + } + std::string ps_ir; + std::vector<x2w::PixelHeapSpan> spans; + std::vector<D3D12_STATIC_SAMPLER_DESC> samplers; + if (varying_pixel) { + auto pixel = x2w::translate_mesh_pixel_program(ps, entry.enable, entry.address, entry.wave_size, pixel_heap ? &guest_desc->Desc_1_1 : nullptr); + if (pixel_heap) { + if (pixel.pixel_heap_spans.empty()) throw std::runtime_error("missing PS texture heap reads"); + spans=std::move(pixel.pixel_heap_spans); + for (const auto& c:pixel.constants) + if (c.root_parameter!=mapping.root_parameter || c.count!=mapping.count) + throw std::runtime_error("PS constants differ from the bound MS constant block"); + for (const auto& s:pixel.samplers) + samplers.push_back(x2w_startup::decode_sampler(s.words,static_cast<UINT>(samplers.size()),s.comparison,s.explicit_lod)); + } + if ((!pixel_heap && (!pixel.constants.empty() || !pixel.samplers.empty())) || !pixel.bindings.empty() || pixel.sampler_heap) + throw std::runtime_error("PS needs root or heap bindings"); + x2w::validate_raster_link(native, pixel); + ps_ir = std::move(pixel.dxil_ir); + } else { + ps_ir = x2w::direct_gfx1013_constant_pixel(ps); + } + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto cache = std::filesystem::path(path).parent_path(); + const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + const auto ps_output = + compiler.compile(ps_ir, L"ps_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + x2w::meshlet::MeshOnlyPipelineStream stream{}; + stream.root_signature.value = reinterpret_cast<ID3D12RootSignature*>(root); + stream.ms.value = {ms_output.dxil.data(), ms_output.dxil.size()}; + stream.ps.value = {ps_output.dxil.data(), ps_output.dxil.size()}; + stream.blend.value = profile.blend; + stream.sample_mask.value = profile.sample_mask; + stream.rasterizer.value = profile.rasterizer; + stream.depth_stencil.value = profile.depth; + stream.rtv_formats.value = profile.targets; + stream.dsv_format.value = profile.depth_format; + stream.sample_desc.value = profile.samples; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + bool compute = false; + char why[256]{}; + auto& state = pipeline->own(); + x2w_startup::ComPtr<ID3D12RootSignature> host; + if (mapped) { + D3D12_ROOT_PARAMETER params[2]{}; + auto& block = params[0]; + block.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + block.Constants.Num32BitValues = (mapping.count + 3) & ~3u; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, static_cast<UINT>(reads.size())}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + D3D12_ROOT_SIGNATURE_DESC host_desc{reads.empty() ? 1u : 2u, params, static_cast<UINT>(samplers.size()), samplers.data()}; + if (direct_heap) host_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + x2w_startup::ComPtr<ID3DBlob> blob; + if (FAILED(D3D12SerializeRootSignature(&host_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&host)))) + throw std::runtime_error("failed to create MS b0 constant root"); + } + state.real = build_stream_pipeline(&desc, why, sizeof(why), compute, state.indirect_graphics, state.pipeline_root, + host ? host.Get() : static_cast<ID3D12RootSignature*>(root->own().real), true); + if (!state.real) + throw std::runtime_error(why); + if (mapped) { + static constexpr GUID lifetime{0xf74c6928,0xb063,0x4a00,{0xa5,0xf0,0x79,0xe3,0x60,0xa4,0xf1,0x09}}; + auto* desktop = static_cast<ID3D12PipelineState*>(state.real); + if (FAILED(desktop->SetPrivateDataInterface(lifetime, host.Get()))) { + desktop->Release(); + state.real = nullptr; + state.indirect_graphics = {}; + throw std::runtime_error("could not retain MS constant root"); + } + state.indirect_graphics.constant_guest = mapping.root_parameter; + info->mesh57_pixel_spans = std::move(spans); + info->mesh57_reads = std::move(reads); + info->mesh57_heap_word = heap_word; + } + log("x2w-render native slot57 mesh %016llx ready", key); + } catch (const std::exception& e) { + log("x2w-render native slot57 mesh %016llx refused: %s", key, e.what()); + } +} +#endif diff --git a/src/startup_stubs/native_recording.h b/src/startup_stubs/native_recording.h new file mode 100644 index 0000000000..287cf5a181 --- /dev/null +++ b/src/startup_stubs/native_recording.h @@ -0,0 +1,52 @@ +#pragma once +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <stdexcept> +#include <unordered_map> +#include "native_copy_ranges.h" + +namespace x2w_startup { +struct NativeDescriptorTable { + ID3D12DescriptorHeap *heap{}; + D3D12_CPU_DESCRIPTOR_HANDLE cpu{}; + D3D12_GPU_DESCRIPTOR_HANDLE gpu{}; + UINT increment{}; +}; +// draw_lock protects recording and submission. Each reset starts a new +// allocation sequence. A closed recording and each of its submits own the +// same immutable tables, even when the command-list pointer is reused. +struct NativeRecording { + struct BufferCopy { + const void* owner; + std::uint64_t base, begin, end; + Microsoft::WRL::ComPtr<ID3D12Resource> resource; + }; + std::vector<BufferCopy> copies; + std::unordered_map<IUnknown *, Microsoft::WRL::ComPtr<IUnknown>> objects; + NativeDescriptorTable next; + UINT remaining = 0; + void retain(IUnknown *object) { objects.try_emplace(object, object); } + NativeDescriptorTable allocate(ID3D12Device *device, UINT count) { + if (!count) + return {}; + if (remaining < count) { + const UINT capacity = (std::max)(256u, count); + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, capacity, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> page; + if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&page)))) + throw std::runtime_error("native descriptor page allocation failed"); + retain(page.Get()); + next = {page.Get(), page->GetCPUDescriptorHandleForHeapStart(), page->GetGPUDescriptorHandleForHeapStart(), + device->GetDescriptorHandleIncrementSize(desc.Type)}; + remaining = capacity; + } + auto table = next; + next.cpu.ptr += SIZE_T(count) * next.increment; + next.gpu.ptr += UINT64(count) * next.increment; + remaining -= count; + return table; + } +}; +} // namespace x2w_startup diff --git a/src/startup_stubs/null_binding_cause.h b/src/startup_stubs/null_binding_cause.h index faf05a2b25..8fe58a7946 100644 --- a/src/startup_stubs/null_binding_cause.h +++ b/src/startup_stubs/null_binding_cause.h @@ -10,9 +10,10 @@ enum class NullCause : int { unknown_token, // descriptor memory names a view the wrapper does not know texture_wrapper, // the view's resource is missing or is not a resource wrapper dimension_mismatch, // the view dimension does not match the shader + ring_full, // the guest memory was readable but the frame copy found no upload ring space (the draw is refused) }; -constexpr int null_cause_count = 5; -constexpr const char* null_cause_names[null_cause_count] = {"entry", "buffer", "token", "wrapper", "dimension"}; +constexpr int null_cause_count = 6; +constexpr const char* null_cause_names[null_cause_count] = {"entry", "buffer", "token", "wrapper", "dimension", "ring_full"}; struct BindingFacts { bool texture = false; @@ -23,10 +24,12 @@ struct BindingFacts { bool resource_wrapper = false; // texture: the view resolves to a resource wrapper bool dimension_matches = true; // texture: the view dimension suits the shader bool bound = false; // buffer: a readable range was bound + bool ring_failed = false; // buffer: the range is readable but the upload ring had no space for its copy }; inline NullCause classify_null_binding(const BindingFacts& f) { + if (!f.texture && f.ring_failed) return NullCause::ring_full; // A buffer that ended up bound (also through the identity fallback) is not a null binding. if (!f.texture && f.bound) return NullCause::none; if (f.from_table && !f.entry_readable) return NullCause::table_entry; diff --git a/src/startup_stubs/pixel_history.h b/src/startup_stubs/pixel_history.h new file mode 100644 index 0000000000..4f64586d1f --- /dev/null +++ b/src/startup_stubs/pixel_history.h @@ -0,0 +1,79 @@ +// Bounded per-draw texel history for the translated draw path (X2W_DRAW_DUMP_FRAME plus +// X2W_DRAW_DUMP_PIXEL). One sample is the texel after one translated draw, with the draw ordinal, +// the manifest key and the raw 32-bit word, so a reader can name the draw that last changed it. +#pragma once + +#include <dxgiformat.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> + +namespace x2w_startup { + +struct PixelHistorySample { + std::uint64_t draw{}; + long frame{}; + unsigned x{}, y{}; + std::uint64_t key{}; + unsigned count{}; + DXGI_FORMAT format{DXGI_FORMAT_UNKNOWN}; + std::uint32_t raw{}; + bool rgba{}; + unsigned char channels[4]{}; +}; + +// Only the 8-bit four-channel targets the full draw dump already writes: a 1x1 copy of any other +// format would need its own block or element layout. +inline bool pixel_history_supported(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: return true; + default: return false; + } +} + +inline bool pixel_history_decode(PixelHistorySample& sample, const void* pixel) +{ + if (!pixel || !pixel_history_supported(sample.format)) return false; + std::uint32_t word = 0; + std::memcpy(&word, pixel, sizeof(word)); + sample.raw = word; + const unsigned char* bytes = static_cast<const unsigned char*>(pixel); + const bool bgra = sample.format == DXGI_FORMAT_B8G8R8A8_UNORM || sample.format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; + sample.channels[0] = bytes[bgra ? 2 : 0]; + sample.channels[1] = bytes[bgra ? 1 : 1]; + sample.channels[2] = bytes[bgra ? 0 : 2]; + sample.channels[3] = bytes[3]; + sample.rgba = true; + return true; +} + +// Rewrites the report with every sample kept so far. The caller owns the bounded list; this helper +// stays device-free so a fixture can compare the exact text. +inline bool pixel_history_write(const char* folder, const PixelHistorySample* samples, std::size_t count) +{ + if (!folder || !*folder) return false; + char path[512]{}; + const int length = std::snprintf(path, sizeof(path), "%s\\pixel_history.txt", folder); + if (length <= 0 || static_cast<std::size_t>(length) >= sizeof(path)) return false; + std::FILE* file = std::fopen(path, "wb"); + if (!file) return false; + std::fprintf(file, "x2w-pixel-history 1 samples=%zu\n", count); + for (std::size_t i = 0; i < count; ++i) { + const PixelHistorySample& sample = samples[i]; + std::fprintf(file, "draw=%llu frame=%ld x=%u y=%u key=%016llx count=%u format=%d raw=%08x", + static_cast<unsigned long long>(sample.draw), sample.frame, sample.x, sample.y, + static_cast<unsigned long long>(sample.key), sample.count, static_cast<int>(sample.format), sample.raw); + if (sample.rgba) + std::fprintf(file, " rgba=%u,%u,%u,%u", sample.channels[0], sample.channels[1], sample.channels[2], + sample.channels[3]); + std::fputc('\n', file); + } + return std::fclose(file) == 0; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 456cdfe6b6..27d6400788 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -22,6 +22,8 @@ #include <windows.h> #include <cstdint> +#include "startup_stubs/local_log.h" + namespace x2w_startup { struct PlacedBufferRange { @@ -58,11 +60,21 @@ inline QueryRegion query_region() } } // namespace placed_detail -// False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is -// exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the -// full walk measures. -inline bool measure_placed_buffer(const void* address, std::uint64_t width, PlacedBufferRange& out, - PlacedProof proof = PlacedProof::exact) +// Size of the whole allocation holding address, from one region-information call (no page-table scan); +// 0 when the call is missing or fails. +inline std::uint64_t allocation_bytes(const void* address) +{ + placed_detail::RegionInformation info{}; + SIZE_T returned = 0; + const placed_detail::QueryRegion query = placed_detail::query_region(); + if (!address || !query || !query(GetCurrentProcess(), address, 0 /* MemoryRegionInfo */, &info, sizeof(info), &returned)) + return 0; + return info.RegionSize; +} + +namespace placed_detail { +// One pass of measure_placed_buffer; out is reset first, so a second pass replaces the first. +inline bool measure_once(const void* address, std::uint64_t width, PlacedBufferRange& out, PlacedProof proof) { out = PlacedBufferRange{}; if (!address) return false; @@ -106,5 +118,47 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac out.covered = true; return true; } +} // namespace placed_detail + +// False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is +// exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the +// full walk measures. The queries run outside xmem's run breaks (x2w_local::outside_run_breaks): inside +// one, pages of a shared-view run read as reserved, and the buffer would be refused although it is mapped. +inline bool measure_placed_buffer(const void* address, std::uint64_t width, PlacedBufferRange& out, + PlacedProof proof = PlacedProof::exact) +{ + bool committed = false; + unsigned queries = 0; // over every pass: a pass run again after a break replaces out + x2w_local::outside_run_breaks([&] { + committed = placed_detail::measure_once(address, width, out, proof); + queries += out.queries; + }); + out.queries = queries; + return committed; +} + +// True when an uncovered buffer at [address, address + width) lies inside a MEM_PRIVATE +// reservation at a 64 KiB-aligned offset, fits within its whole allocation size (nonzero and at +// most max_allocation_bytes when nonzero), and has nonzero width. Used before committing a lazy +// startup block (X2W_XMEM_LAZY_STARTUP) and re-measuring so an aligned nonzero offset with a +// MEM_RESERVE prefix can still alias an eligible small block without committing ineligible or +// out-of-bounds blocks. +inline bool can_commit_lazy_placed_buffer(const void* address, std::uint64_t width, + std::uint64_t max_allocation_bytes) +{ + if (!address || !width) return false; + MEMORY_BASIC_INFORMATION info{}; + if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info) || info.State != MEM_COMMIT || + info.Type != MEM_PRIVATE || !info.AllocationBase) + return false; + const auto start = reinterpret_cast<std::uintptr_t>(address); + const auto base = reinterpret_cast<std::uintptr_t>(info.AllocationBase); + if (start < base) return false; + const std::uint64_t offset = start - base; + if (offset & 0xFFFF) return false; + const std::uint64_t alloc_bytes = allocation_bytes(info.AllocationBase); + if (!alloc_bytes || (max_allocation_bytes && alloc_bytes > max_allocation_bytes)) return false; + return offset <= alloc_bytes && width <= alloc_bytes - offset; +} } // namespace x2w_startup diff --git a/src/startup_stubs/placed_build.h b/src/startup_stubs/placed_build.h index a8967cbe41..c64520a24a 100644 --- a/src/startup_stubs/placed_build.h +++ b/src/startup_stubs/placed_build.h @@ -3,7 +3,8 @@ #include <d3d12.h> namespace x2w_startup { -// Takes ownership of one reference to the desktop device chosen by the caller. +// Takes ownership of one reference to the desktop device chosen by the caller. *wrapped is null +// when the wrapper cannot be allocated; the reference is released then. void attach_device(ID3D12Device* device, void** wrapped); // Internal desktop build preparation. The caller retains the registered resources diff --git a/src/startup_stubs/plane_compositor.h b/src/startup_stubs/plane_compositor.h new file mode 100644 index 0000000000..b41cd58957 --- /dev/null +++ b/src/startup_stubs/plane_compositor.h @@ -0,0 +1,186 @@ +// Experimental (docs/startup-runtime.md#presented-planes): the draw that composites the planes of a +// console present into one render target. The output window (d3d12_present.inl) records it into its +// back buffer; tests/startup_present_composite_warp.cpp records it into a texture it reads back. +// +// Contract: the steps come from composite_steps (present_planes.h), bottom to top. The first step +// drawn replaces the target with its plane's colour and ignores that plane's alpha (nothing is below +// it); each later step with `blended` set is drawn over the result with +// colour = src.rgb * src.a + dst.rgb * (1 - src.a), alpha = src.a + dst.a * (1 - src.a) +// (SRC_ALPHA / INV_SRC_ALPHA, ONE / INV_SRC_ALPHA), so after an opaque base the target alpha stays 1. +// A step without `blended` (or whose plane has no surface) after the first is drawn opaque or left +// out. Each plane is one full-target triangle sampled with a linear, clamped sampler: a plane the +// size of the target is copied texel for texel; a larger or smaller plane is scaled to fit. +// Plane surfaces must rest in COMMON and pass present_surface_supported (present_view_format.h); they +// are left in COMMON. The target must be in RENDER_TARGET. +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <d3d12.h> +#include <d3dcompiler.h> + +#include "startup_stubs/present_planes.h" +#include "startup_stubs/present_view_format.h" + +namespace x2w_startup { + +class PlaneCompositor { +public: + // Create the opaque pipeline and a heap for up to `max_planes` views. More than one plane also needs a blend pipeline. + HRESULT create(ID3D12Device* device, DXGI_FORMAT target_format, UINT max_planes) + { + release(); + max_planes_ = max_planes ? max_planes : 1; + static const char source[] = + "Texture2D<float4> surface : register(t0); SamplerState smooth : register(s0);\n" + "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" + "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" + "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n" + "float4 ps_over(V i) : SV_Target0 { return surface.Sample(smooth, i.uv); }\n"; + ID3DBlob* vs = nullptr; + ID3DBlob* ps = nullptr; + ID3DBlob* ps_over = nullptr; + ID3DBlob* blob = nullptr; + const D3D12_DESCRIPTOR_HEAP_DESC heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, max_planes_, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + HRESULT hr = device->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&textures_)); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); + if (SUCCEEDED(hr) && max_planes_ > 1) + hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps_over", "ps_5_0", 0, 0, &ps_over, nullptr); + if (SUCCEEDED(hr)) { + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); + if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root_)); + } + if (SUCCEEDED(hr)) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root_; + desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = ~0u; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = target_format; + desc.SampleDesc.Count = 1; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&opaque_)); + if (SUCCEEDED(hr) && ps_over) { + desc.PS = {ps_over->GetBufferPointer(), ps_over->GetBufferSize()}; + D3D12_RENDER_TARGET_BLEND_DESC& blend = desc.BlendState.RenderTarget[0]; + blend.BlendEnable = TRUE; + blend.SrcBlend = D3D12_BLEND_SRC_ALPHA; + blend.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOp = D3D12_BLEND_OP_ADD; + blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&blend_)); + } + } + if (vs) vs->Release(); + if (ps) ps->Release(); + if (ps_over) ps_over->Release(); + if (blob) blob->Release(); + if (FAILED(hr)) release(); + return hr; + } + + // The pipeline a list can be reset with before record(). + ID3D12PipelineState* initial_pipeline() const { return opaque_; } + UINT max_planes() const { return max_planes_; } + + // Records the composite into `list` (open) over `target` (width x height, in RENDER_TARGET). + // steps[0..count) as from composite_steps; plane_surfaces[step.plane] is that plane's surface, + // or null to leave the step out. Returns the number of planes drawn (0: nothing recorded). + UINT record(ID3D12Device* device, ID3D12GraphicsCommandList* list, D3D12_CPU_DESCRIPTOR_HANDLE target, UINT width, + UINT height, const PlaneStep* steps, unsigned count, ID3D12Resource* const* plane_surfaces) + { + if (!opaque_ || !list || !steps || !plane_surfaces) return 0; + ID3D12Resource* drawn[16] = {}; + bool blended[16] = {}; + UINT planes = 0; + const UINT limit = max_planes_ < 16 ? max_planes_ : 16; + for (unsigned i = 0; i < count && planes < limit; ++i) { + ID3D12Resource* const surface = plane_surfaces[steps[i].plane]; + if (!surface) continue; + blended[planes] = planes != 0 && steps[i].blended; // the first plane drawn is the opaque base + drawn[planes++] = surface; + } + if (!planes) return 0; + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < planes; ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = present_view_format(drawn[i]->GetDesc().Format); + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(drawn[i], &view, + D3D12_CPU_DESCRIPTOR_HANDLE{textures_->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{i} * step}); + } + for (UINT i = 0; i < planes; ++i) transition(list, drawn[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast<LONG>(width), static_cast<LONG>(height)}; + list->SetGraphicsRootSignature(root_); + list->SetDescriptorHeaps(1, &textures_); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &target, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + for (UINT i = 0; i < planes; ++i) { + list->SetPipelineState(blended[i] ? blend_ : opaque_); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{textures_->GetGPUDescriptorHandleForHeapStart().ptr + UINT64{i} * step}); + list->DrawInstanced(3, 1, 0, 0); + } + for (UINT i = 0; i < planes; ++i) transition(list, drawn[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + return planes; + } + + void release() + { + if (blend_) blend_->Release(); + if (opaque_) opaque_->Release(); + if (root_) root_->Release(); + if (textures_) textures_->Release(); + blend_ = opaque_ = nullptr; + root_ = nullptr; + textures_ = nullptr; + } + +private: + static void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) + { + 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 = from; + barrier.Transition.StateAfter = to; + list->ResourceBarrier(1, &barrier); + } + + ID3D12DescriptorHeap* textures_ = nullptr; + ID3D12RootSignature* root_ = nullptr; + ID3D12PipelineState* opaque_ = nullptr; // the bottom plane, alpha ignored + ID3D12PipelineState* blend_ = nullptr; // later planes, over it by their alpha + UINT max_planes_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/present_planes.h b/src/startup_stubs/present_planes.h new file mode 100644 index 0000000000..0c71c7ac1d --- /dev/null +++ b/src/startup_stubs/present_planes.h @@ -0,0 +1,61 @@ +// Experimental (docs/startup-runtime.md): the planes of a console present (CommandQueue slot 32). +// +// The present takes a plane count and an array of plane records. Measured from the first presents +// of a console executable: one record is 0x48 bytes, with +0x00 a frame token, +0x08 the resource +// count and +0x10 a pointer to the array of resources; the second plane's token sits at +0x48 when +// two planes are presented. The fields after +0x10 (source and destination rectangles, flags) are +// not decoded here. Pure: the caller passes a readability check, so a control can run it on +// synthetic records. +#pragma once + +#include <cstddef> +#include <cstdint> +#include <cstring> + +namespace x2w_startup { +inline constexpr std::size_t present_plane_stride = 0x48; + +// The first resource of plane `index`, or 0 when the plane, its record or its resource array is +// not readable or has no resource. readable(address, bytes) answers whether memory can be read. +template <class Readable> +std::uint64_t present_plane_resource(const void* planes, unsigned count, unsigned index, Readable&& readable, + std::size_t stride = present_plane_stride) +{ + if (!planes || index >= count) return 0; + const auto* record = static_cast<const unsigned char*>(planes) + std::size_t{index} * stride; + if (!readable(record, 0x18)) return 0; + std::uint64_t resources = 0, resource_count = 0, first = 0; + std::memcpy(&resource_count, record + 0x08, 8); + std::memcpy(&resources, record + 0x10, 8); + if (resource_count == 0 || !resources || !readable(reinterpret_cast<const void*>(resources), 8)) return 0; + std::memcpy(&first, reinterpret_cast<const void*>(resources), 8); + return first; +} + +// One draw of the window composite: plane `plane`, either replacing what is below (the bottom +// layer) or blended over it by the plane's own alpha. +struct PlaneStep { + unsigned plane = 0; + bool blended = false; +}; + +// The window composite of a present, bottom to top, the way planes stack on the console: plane 0 +// first, each later plane over it. `resources[i]` is plane i's surface, 0 when it cannot be shown; +// those planes and repeats of a surface already drawn are left out. The lowest drawn plane is +// opaque (nothing is below it), every later one blended. Returns the number of steps written. +// Measured on a two-plane present: plane 0 was black and plane 1, with alpha 255 wherever the +// picture was, held it; showing plane 0 alone gave a black window. +inline unsigned composite_steps(const std::uint64_t* resources, unsigned count, PlaneStep* steps, unsigned max_steps) +{ + unsigned written = 0; + for (unsigned i = 0; resources && i < count && written < max_steps; ++i) { + if (!resources[i]) continue; + bool repeat = false; + for (unsigned j = 0; j < written; ++j) repeat = repeat || resources[steps[j].plane] == resources[i]; + if (repeat) continue; + steps[written] = PlaneStep{i, written != 0}; + ++written; + } + return written; +} +} // namespace x2w_startup diff --git a/src/startup_stubs/present_readback_state.h b/src/startup_stubs/present_readback_state.h new file mode 100644 index 0000000000..1a333504df --- /dev/null +++ b/src/startup_stubs/present_readback_state.h @@ -0,0 +1,41 @@ +#pragma once + +#include "startup_stubs/fence_completion.h" + +namespace x2w_startup { + +class PresentReadbackState { + std::uint64_t target_ = 0; + bool unusable_ = false; + + FenceCompletion classify(std::uint64_t observed) const noexcept + { + if (unusable_) return target_ ? FenceCompletion::removed : FenceCompletion::pending; + return fence_completion(observed, target_); + } + +public: + void submitted(std::uint64_t target) noexcept { target_ = target; } + void signal_failed() noexcept { unusable_ = true; } + bool pending() const noexcept { return target_ != 0; } + bool unusable() const noexcept { return unusable_; } + FenceCompletion observe(std::uint64_t observed) noexcept + { + const auto state = classify(observed); + if (state == FenceCompletion::removed) unusable_ = true; + if (state == FenceCompletion::completed) target_ = 0; + return state; + } + // A stale drain may observe the fence but must not settle another submission. + template <class Release> + FenceCompletion retire(std::uint64_t observed, Release&& release, std::uint64_t expected = 0) + { + if (expected && expected != target_) return classify(observed); + const bool held = pending(); + const auto state = observe(observed); + if (state == FenceCompletion::completed && held) release(); + return state; + } +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/present_signature_sampler.h b/src/startup_stubs/present_signature_sampler.h index a9af26f9f5..c3c3dbce2b 100644 --- a/src/startup_stubs/present_signature_sampler.h +++ b/src/startup_stubs/present_signature_sampler.h @@ -10,7 +10,9 @@ // presented surface right after the present. The sampler therefore holds its own reference to the // surface from submission until the copy's fence has passed. If Signal fails after the list was // submitted, nothing can tell when the copy ends: the sampler stops sampling and keeps the surface, -// allocator, list and readback buffer referenced for the rest of the process ("stranded"). +// allocator, list and readback buffer referenced for the rest of the process ("stranded"). A removed +// device (the fence reports UINT64_MAX) is the same case, never a completion: no readback is mapped, +// no sample is published, and the source stays held. // // Sampling is opt-in: a sampler made with always = false records copies only while the block's // sampling_wanted is set (a script with a picture wait asks for it); otherwise it creates no GPU @@ -18,6 +20,8 @@ #pragma once #include "resource_budget.h" +#include "startup_stubs/fence_completion.h" + #include "startup_stubs/present_signature.h" #include "startup_stubs/present_view_format.h" @@ -47,33 +51,52 @@ class Sampler { explicit Sampler(int every, bool always = true, bool capture_center = false) : capture_center_(capture_center), every_(every), always_(always) {} - // Called once per present with the presented surface. Returns true when this call published a sample. + // Called once per present with the presented surface. Returns true when this call published a + // sample. A removed fence (device removal reports UINT64_MAX) never counts as completion: the + // readback is not mapped, nothing is published, and the copy's source stays held. bool present(ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Resource* surface, LONG64 present_number, Block* block) { bool published = false; - if (in_flight_ && fence_->GetCompletedValue() >= fence_value_) { - in_flight_ = false; - if (capture_center_) { - last_present_ = copied_present_; - last_format_ = format_; - last_surface_ = source_; - } - retire_source(); - void* mapped = nullptr; - const D3D12_RANGE range{0, static_cast<SIZE_T>(row_stride_ * rows_)}; - if (SUCCEEDED(readback_->Map(0, &range, &mapped))) { - const auto* base = static_cast<const unsigned char*>(mapped); - if (capture_center_) - std::memcpy(last_rgba_, base + row_stride_ * (cells_y / 2) + (width_ / 2) * 4, 4); - std::uint8_t luma[cells]; - for (int band = 0; band < cells_y; ++band) reduce_row(base + row_stride_ * band, width_, layout_, luma + band * cells_x); - if (rows_ > cells_y) - for (int band = 0; band < fine_y; ++band) - reduce_row(base + row_stride_ * (cells_y + band), width_, layout_, fine_ + band * fine_x, fine_x); - const D3D12_RANGE none{0, 0}; - readback_->Unmap(0, &none); - if (block) publish(block, luma, copied_present_, rows_ > cells_y ? fine_ : nullptr); - published = true; + if (in_flight_) { + // One observation per present decision: device removal (UINT64_MAX) is never a + // completion, exactly like a failed Signal. + switch (x2w_startup::fence_completion(fence_->GetCompletedValue(), fence_value_)) { + case x2w_startup::FenceCompletion::completed: + in_flight_ = false; + if (capture_center_) { + last_present_ = copied_present_; + last_format_ = format_; + last_surface_ = source_; + } + retire_source(); + { + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast<SIZE_T>(row_stride_ * rows_)}; + if (SUCCEEDED(readback_->Map(0, &range, &mapped))) { + const auto* base = static_cast<const unsigned char*>(mapped); + if (capture_center_) + std::memcpy(last_rgba_, base + row_stride_ * (cells_y / 2) + (width_ / 2) * 4, 4); + std::uint8_t luma[cells]; + for (int band = 0; band < cells_y; ++band) reduce_row(base + row_stride_ * band, width_, layout_, luma + band * cells_x); + if (rows_ > cells_y) + for (int band = 0; band < fine_y; ++band) + reduce_row(base + row_stride_ * (cells_y + band), width_, layout_, fine_ + band * fine_x, fine_x); + const D3D12_RANGE none{0, 0}; + readback_->Unmap(0, &none); + if (block) publish(block, luma, copied_present_, rows_ > cells_y ? fine_ : nullptr); + published = true; + } + } + break; + case x2w_startup::FenceCompletion::removed: + // Device removal: the copy's end cannot be seen. Publish nothing (the readback + // is stale) and keep the prior historical sample state as it is, as a failed + // Signal does: stranded, so the destructor retains every object the copy uses. + in_flight_ = false; + stranded_ = failed_ = true; + break; + case x2w_startup::FenceCompletion::pending: + break; } } if (block) note_present(block, present_number); @@ -149,14 +172,22 @@ class Sampler { // Waits (at most 10 s) for a copy in flight; if it cannot be seen to end, or the sampler is // stranded, the objects the copy uses stay referenced instead of being released under the GPU. + // A removed fence never counts as completion: the source is kept, and nothing is mapped. ~Sampler() { - if (in_flight_ && !stranded_ && fence_->GetCompletedValue() < fence_value_) { + if (in_flight_ && !stranded_ && + x2w_startup::fence_completion(fence_->GetCompletedValue(), fence_value_) == x2w_startup::FenceCompletion::pending) { HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); if (event && SUCCEEDED(fence_->SetEventOnCompletion(fence_value_, event))) WaitForSingleObject(event, 10000); if (event) CloseHandle(event); } - if (stranded_ || (in_flight_ && fence_->GetCompletedValue() < fence_value_)) return; + // Re-observe after the wait: a copy that completed while it ran releases normally, but + // the removal sentinel never becomes completion, so a fence that reports it (or never + // reached its value in 10 s) keeps every object the copy uses. + if (stranded_ || (in_flight_ && + x2w_startup::fence_completion(fence_->GetCompletedValue(), fence_value_) != + x2w_startup::FenceCompletion::completed)) + return; retire_source(); for (IUnknown* object : {static_cast<IUnknown*>(readback_), static_cast<IUnknown*>(fence_), static_cast<IUnknown*>(list_), static_cast<IUnknown*>(allocator_)}) diff --git a/src/startup_stubs/profile_zone.h b/src/startup_stubs/profile_zone.h index 4981dc672d..e94d7e2f6e 100644 --- a/src/startup_stubs/profile_zone.h +++ b/src/startup_stubs/profile_zone.h @@ -1,12 +1,19 @@ -// Opt-in Tracy zones for the stand-ins (CMake option X2W_TRACY, a local measurement build). -// Without the option every macro expands to nothing and no Tracy header is included. +// Opt-in Tracy zones, memory pools and plots for the stand-ins (CMake option X2W_TRACY, a local measurement build). +// Without the option every macro expands to nothing or a no-op and no Tracy header is included. #pragma once #if X2W_TRACY #include <tracy/Tracy.hpp> #define X2W_ZONE(name) ZoneScopedN(name) #define X2W_FRAME_MARK FrameMark +// A named memory pool: every X2W_ALLOC needs its X2W_FREE with the same pool name. +#define X2W_ALLOC(pointer, bytes, pool) TracyAllocN(pointer, bytes, pool) +#define X2W_FREE(pointer, pool) TracyFreeN(pointer, pool) +#define X2W_PLOT(name, value) TracyPlot(name, value) #else #define X2W_ZONE(name) #define X2W_FRAME_MARK +#define X2W_ALLOC(pointer, bytes, pool) ((void)0) +#define X2W_FREE(pointer, pool) ((void)0) +#define X2W_PLOT(name, value) ((void)0) #endif diff --git a/src/startup_stubs/pso_recipe.h b/src/startup_stubs/pso_recipe.h new file mode 100644 index 0000000000..64028e2352 --- /dev/null +++ b/src/startup_stubs/pso_recipe.h @@ -0,0 +1,653 @@ +// Experimental: a versioned on-disk recipe for a translated desktop graphics pipeline. +// +// The shader cache stores the vertex and pixel bytecode, the root signature and the sampler +// descriptions. It does not store the draw state that produced a desktop pipeline state object +// (PSO). With X2W_PSO_RECIPE_DIR set, the runtime appends that state here after a successful +// CreateGraphicsPipelineState and replays it on a later run before creating another PSO. This is +// state reconstruction, not a D3D12 pipeline library: the driver may still compile or cache the +// PSO internally. +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <d3d12.h> + +// windows.h may already have been included by the translation unit, so NOMINMAX above is too late +// to prevent the min/max function-like macros. std::numeric_limits<T>::max is used below. +#ifdef min +#undef min +#endif +#ifdef max +#undef max +#endif + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <limits> +#include <string> +#include <string_view> +#include <vector> + +namespace x2w_startup { + +constexpr unsigned pso_recipe_version = 1; +constexpr std::size_t pso_recipe_file_limit = 64u * 1024u; +constexpr std::size_t pso_recipe_record_limit = 64; +constexpr unsigned pso_recipe_target_limit = 8; + +struct PsoRecipe { + std::uint64_t translation_key = 0; // the shader-cache key this record belongs to + std::uint64_t state_key = 0; // pipeline_for's target/depth/raster/indexed key + UINT target_count = 0; + DXGI_FORMAT target_formats[pso_recipe_target_limit]{}; + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + bool indexed_rect = false; + bool use_depth_stencil = false; // whether DepthStencilState participated in the PSO + bool has_rasterizer = false; // whether a decoded rasterizer state participated in the key + D3D12_BLEND_DESC blend{}; // effective state, after apply_export_write_masks + D3D12_DEPTH_STENCIL_DESC depth_stencil{}; + D3D12_RASTERIZER_DESC rasterizer{}; + UINT sample_mask = ~0u; + UINT sample_count = 1; + D3D12_PRIMITIVE_TOPOLOGY_TYPE topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; +}; + +struct PsoRecipeParseResult { + std::vector<PsoRecipe> recipes; + unsigned rejected = 0; + std::string error; +}; + +inline std::uint64_t pso_recipe_hash(const void* data, std::size_t bytes, + std::uint64_t hash = 1469598103934665603ull) +{ + const auto* p = static_cast<const unsigned char*>(data); + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull; + return hash; +} + +inline std::uint64_t pso_targets_key(UINT target_count, const DXGI_FORMAT* target_formats, DXGI_FORMAT dsv_format) +{ + std::uint64_t key = target_count; + for (UINT i = 0; i < target_count; ++i) key = key * 131 + static_cast<std::uint64_t>(target_formats[i]); + return pso_recipe_hash(&dsv_format, sizeof(dsv_format), key); +} + +// The same key pipeline_for uses. Keeping it here lets a parsed record prove that its own fields +// reproduce the state key it names. +inline std::uint64_t pso_state_key(UINT target_count, const DXGI_FORMAT* target_formats, DXGI_FORMAT dsv_format, + bool use_depth_stencil, const D3D12_DEPTH_STENCIL_DESC& depth_stencil, + bool has_rasterizer, const D3D12_RASTERIZER_DESC& rasterizer, bool indexed_rect) +{ + std::uint64_t key = pso_targets_key(target_count, target_formats, dsv_format); + if (use_depth_stencil) key = pso_recipe_hash(&depth_stencil, sizeof(depth_stencil), key); + if (has_rasterizer) key = pso_recipe_hash(&rasterizer, sizeof(rasterizer), key); + key = pso_recipe_hash(&indexed_rect, sizeof(indexed_rect), key); + return key; +} + +inline std::uint64_t pso_recipe_state_key(const PsoRecipe& recipe) +{ + return pso_state_key(recipe.target_count, recipe.target_formats, recipe.dsv_format, recipe.use_depth_stencil, + recipe.depth_stencil, recipe.has_rasterizer, recipe.rasterizer, recipe.indexed_rect); +} + +inline D3D12_RENDER_TARGET_BLEND_DESC default_render_target_blend() +{ + return {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; +} + +inline D3D12_BLEND_DESC default_pso_blend() +{ + D3D12_BLEND_DESC blend{}; + for (auto& target : blend.RenderTarget) target = default_render_target_blend(); + return blend; +} + +inline D3D12_RASTERIZER_DESC default_pso_rasterizer() +{ + D3D12_RASTERIZER_DESC rasterizer{}; + rasterizer.FillMode = D3D12_FILL_MODE_SOLID; + rasterizer.CullMode = D3D12_CULL_MODE_NONE; + rasterizer.DepthClipEnable = TRUE; + return rasterizer; +} + +// A valid depth-stencil state for a recipe that does not use one. The serializer writes every +// field, and the parser rejects an invalid stencil op; the zero-filled D3D12 struct is not a +// valid serialized state even when the PSO ignores it. +inline D3D12_DEPTH_STENCIL_DESC default_pso_depth() +{ + D3D12_DEPTH_STENCIL_DESC depth{}; + depth.DepthEnable = FALSE; + depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + depth.StencilEnable = FALSE; + depth.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + depth.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + depth.FrontFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, + D3D12_COMPARISON_FUNC_ALWAYS}; + depth.BackFace = depth.FrontFace; + return depth; +} + +inline bool same_float_bits(float a, float b) +{ + std::uint32_t left = 0, right = 0; + std::memcpy(&left, &a, sizeof(left)); + std::memcpy(&right, &b, sizeof(right)); + return left == right; +} + +inline bool same_render_target_blend(const D3D12_RENDER_TARGET_BLEND_DESC& a, const D3D12_RENDER_TARGET_BLEND_DESC& b) +{ + return a.BlendEnable == b.BlendEnable && a.LogicOpEnable == b.LogicOpEnable && a.SrcBlend == b.SrcBlend && + a.DestBlend == b.DestBlend && a.BlendOp == b.BlendOp && a.SrcBlendAlpha == b.SrcBlendAlpha && + a.DestBlendAlpha == b.DestBlendAlpha && a.BlendOpAlpha == b.BlendOpAlpha && a.LogicOp == b.LogicOp && + a.RenderTargetWriteMask == b.RenderTargetWriteMask; +} + +inline bool same_pso_blend(const D3D12_BLEND_DESC& a, const D3D12_BLEND_DESC& b) +{ + if (a.AlphaToCoverageEnable != b.AlphaToCoverageEnable || a.IndependentBlendEnable != b.IndependentBlendEnable) + return false; + for (unsigned i = 0; i < 8; ++i) + if (!same_render_target_blend(a.RenderTarget[i], b.RenderTarget[i])) return false; + return true; +} + +inline bool same_pso_depth(const D3D12_DEPTH_STENCIL_DESC& a, const D3D12_DEPTH_STENCIL_DESC& b) +{ + return a.DepthEnable == b.DepthEnable && a.DepthWriteMask == b.DepthWriteMask && a.DepthFunc == b.DepthFunc && + a.StencilEnable == b.StencilEnable && a.StencilReadMask == b.StencilReadMask && + a.StencilWriteMask == b.StencilWriteMask && a.FrontFace.StencilFailOp == b.FrontFace.StencilFailOp && + a.FrontFace.StencilDepthFailOp == b.FrontFace.StencilDepthFailOp && + a.FrontFace.StencilPassOp == b.FrontFace.StencilPassOp && a.FrontFace.StencilFunc == b.FrontFace.StencilFunc && + a.BackFace.StencilFailOp == b.BackFace.StencilFailOp && + a.BackFace.StencilDepthFailOp == b.BackFace.StencilDepthFailOp && + a.BackFace.StencilPassOp == b.BackFace.StencilPassOp && a.BackFace.StencilFunc == b.BackFace.StencilFunc; +} + +inline bool same_pso_rasterizer(const D3D12_RASTERIZER_DESC& a, const D3D12_RASTERIZER_DESC& b) +{ + return a.FillMode == b.FillMode && a.CullMode == b.CullMode && a.FrontCounterClockwise == b.FrontCounterClockwise && + a.DepthBias == b.DepthBias && same_float_bits(a.DepthBiasClamp, b.DepthBiasClamp) && + same_float_bits(a.SlopeScaledDepthBias, b.SlopeScaledDepthBias) && a.DepthClipEnable == b.DepthClipEnable && + a.MultisampleEnable == b.MultisampleEnable && a.AntialiasedLineEnable == b.AntialiasedLineEnable && + a.ForcedSampleCount == b.ForcedSampleCount && a.ConservativeRaster == b.ConservativeRaster; +} + +inline bool pso_recipe_targets_match(const PsoRecipe& recipe, UINT target_count, const DXGI_FORMAT* target_formats, + DXGI_FORMAT dsv_format) +{ + if (target_count != recipe.target_count || dsv_format != recipe.dsv_format) return false; + for (UINT i = 0; i < target_count; ++i) + if (target_formats[i] != recipe.target_formats[i]) return false; + return true; +} + +inline PsoRecipe make_pso_recipe(std::uint64_t translation_key, std::uint64_t state_key, bool indexed_rect, + bool use_depth_stencil, bool has_rasterizer, + const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) +{ + PsoRecipe recipe; + recipe.translation_key = translation_key; + recipe.state_key = state_key; + recipe.target_count = desc.NumRenderTargets; + for (UINT i = 0; i < pso_recipe_target_limit; ++i) recipe.target_formats[i] = desc.RTVFormats[i]; + recipe.dsv_format = desc.DSVFormat; + recipe.indexed_rect = indexed_rect; + recipe.use_depth_stencil = use_depth_stencil; + recipe.has_rasterizer = has_rasterizer; + recipe.blend = desc.BlendState; + recipe.depth_stencil = use_depth_stencil ? desc.DepthStencilState : default_pso_depth(); + recipe.rasterizer = has_rasterizer ? desc.RasterizerState : default_pso_rasterizer(); + recipe.sample_mask = desc.SampleMask; + recipe.sample_count = desc.SampleDesc.Count; + recipe.topology = desc.PrimitiveTopologyType; + return recipe; +} + +inline void apply_pso_recipe(const PsoRecipe& recipe, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) +{ + desc.BlendState = recipe.blend; + desc.DepthStencilState = recipe.use_depth_stencil ? recipe.depth_stencil : D3D12_DEPTH_STENCIL_DESC{}; + desc.RasterizerState = recipe.rasterizer; + desc.SampleMask = recipe.sample_mask; + desc.PrimitiveTopologyType = recipe.topology; + desc.NumRenderTargets = recipe.target_count; + for (UINT i = 0; i < pso_recipe_target_limit; ++i) + desc.RTVFormats[i] = i < recipe.target_count ? recipe.target_formats[i] : DXGI_FORMAT_UNKNOWN; + desc.DSVFormat = recipe.dsv_format; + desc.SampleDesc.Count = recipe.sample_count; + desc.SampleDesc.Quality = 0; +} + +inline void append_hex(std::string& out, std::uint64_t value) +{ + char text[17]; + std::snprintf(text, sizeof(text), "%016llx", static_cast<unsigned long long>(value)); + out += text; +} + +inline std::string serialize_pso_recipe(const PsoRecipe& recipe) +{ + std::string out; + out.reserve(1536); + out += "x2w-pso-recipe 1\nstate 0x"; + append_hex(out, recipe.state_key); + out += "\ntranslation 0x"; + append_hex(out, recipe.translation_key); + out += "\ntargets "; + out += std::to_string(recipe.target_count); + for (DXGI_FORMAT format : recipe.target_formats) { + out += ' '; + out += std::to_string(static_cast<unsigned>(format)); + } + out += "\ndsv "; + out += std::to_string(static_cast<unsigned>(recipe.dsv_format)); + out += "\nindexed "; + out += recipe.indexed_rect ? '1' : '0'; + out += "\nblend "; + out += recipe.blend.AlphaToCoverageEnable ? '1' : '0'; + out += ' '; + out += recipe.blend.IndependentBlendEnable ? '1' : '0'; + out += '\n'; + for (unsigned i = 0; i < 8; ++i) { + const auto& t = recipe.blend.RenderTarget[i]; + out += "blend"; + out += std::to_string(i); + out += ' '; + out += t.BlendEnable ? '1' : '0'; + out += ' '; + out += t.LogicOpEnable ? '1' : '0'; + const unsigned values[] = {static_cast<unsigned>(t.SrcBlend), static_cast<unsigned>(t.DestBlend), + static_cast<unsigned>(t.BlendOp), static_cast<unsigned>(t.SrcBlendAlpha), + static_cast<unsigned>(t.DestBlendAlpha), static_cast<unsigned>(t.BlendOpAlpha), + static_cast<unsigned>(t.LogicOp), static_cast<unsigned>(t.RenderTargetWriteMask)}; + for (unsigned value : values) { + out += ' '; + out += std::to_string(value); + } + out += '\n'; + } + out += "depth "; + out += recipe.use_depth_stencil ? '1' : '0'; + const unsigned depth_values[] = { + recipe.depth_stencil.DepthEnable ? 1u : 0u, static_cast<unsigned>(recipe.depth_stencil.DepthWriteMask), + static_cast<unsigned>(recipe.depth_stencil.DepthFunc), recipe.depth_stencil.StencilEnable ? 1u : 0u, + recipe.depth_stencil.StencilReadMask, recipe.depth_stencil.StencilWriteMask, + static_cast<unsigned>(recipe.depth_stencil.FrontFace.StencilFailOp), + static_cast<unsigned>(recipe.depth_stencil.FrontFace.StencilDepthFailOp), + static_cast<unsigned>(recipe.depth_stencil.FrontFace.StencilPassOp), + static_cast<unsigned>(recipe.depth_stencil.FrontFace.StencilFunc), + static_cast<unsigned>(recipe.depth_stencil.BackFace.StencilFailOp), + static_cast<unsigned>(recipe.depth_stencil.BackFace.StencilDepthFailOp), + static_cast<unsigned>(recipe.depth_stencil.BackFace.StencilPassOp), + static_cast<unsigned>(recipe.depth_stencil.BackFace.StencilFunc)}; + for (unsigned value : depth_values) { + out += ' '; + out += std::to_string(value); + } + out += "\nraster "; + out += recipe.has_rasterizer ? '1' : '0'; + std::uint32_t clamp_bits = 0, slope_bits = 0; + std::memcpy(&clamp_bits, &recipe.rasterizer.DepthBiasClamp, sizeof(clamp_bits)); + std::memcpy(&slope_bits, &recipe.rasterizer.SlopeScaledDepthBias, sizeof(slope_bits)); + const unsigned raster_values[] = {static_cast<unsigned>(recipe.rasterizer.FillMode), + static_cast<unsigned>(recipe.rasterizer.CullMode), + recipe.rasterizer.FrontCounterClockwise ? 1u : 0u}; + for (unsigned value : raster_values) { + out += ' '; + out += std::to_string(value); + } + out += ' '; + out += std::to_string(recipe.rasterizer.DepthBias); + char hex[32]; + std::snprintf(hex, sizeof(hex), " 0x%08x 0x%08x", clamp_bits, slope_bits); + out += hex; + const unsigned raster_tail[] = {recipe.rasterizer.DepthClipEnable ? 1u : 0u, + recipe.rasterizer.MultisampleEnable ? 1u : 0u, + recipe.rasterizer.AntialiasedLineEnable ? 1u : 0u, + recipe.rasterizer.ForcedSampleCount, + static_cast<unsigned>(recipe.rasterizer.ConservativeRaster)}; + for (unsigned value : raster_tail) { + out += ' '; + out += std::to_string(value); + } + out += "\nsample "; + out += std::to_string(recipe.sample_count); + out += ' '; + out += std::to_string(recipe.sample_mask); + out += "\ntopology "; + out += std::to_string(static_cast<unsigned>(recipe.topology)); + out += "\nend\n"; + return out; +} + +inline bool parse_unsigned(std::string_view token, std::uint64_t& value, int base = 10) +{ + if (token.empty()) return false; + if (base == 16 && token.size() >= 2 && token[0] == '0' && (token[1] == 'x' || token[1] == 'X')) token.remove_prefix(2); + if (token.empty() || token[0] == '+' || token[0] == '-') return false; + std::uint64_t result = 0; + for (char c : token) { + unsigned digit = 0; + if (c >= '0' && c <= '9') digit = static_cast<unsigned>(c - '0'); + else if (base == 16 && c >= 'a' && c <= 'f') digit = static_cast<unsigned>(c - 'a' + 10); + else if (base == 16 && c >= 'A' && c <= 'F') digit = static_cast<unsigned>(c - 'A' + 10); + else return false; + if (digit >= static_cast<unsigned>(base)) return false; + if (result > (std::numeric_limits<std::uint64_t>::max() - digit) / static_cast<unsigned>(base)) return false; + result = result * static_cast<unsigned>(base) + digit; + } + value = result; + return true; +} + +inline bool parse_integer(std::string_view token, std::int64_t& value) +{ + if (token.empty()) return false; + const bool negative = token[0] == '-'; + if (negative) token.remove_prefix(1); + std::uint64_t magnitude = 0; + if (!parse_unsigned(token, magnitude)) return false; + if (negative) { + if (magnitude > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + 1) return false; + value = magnitude == static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) + 1 + ? std::numeric_limits<std::int64_t>::min() + : -static_cast<std::int64_t>(magnitude); + } else { + if (magnitude > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())) return false; + value = static_cast<std::int64_t>(magnitude); + } + return true; +} + +inline std::vector<std::string_view> pso_recipe_tokens(std::string_view line) +{ + std::vector<std::string_view> tokens; + std::size_t at = 0; + while (at < line.size()) { + while (at < line.size() && line[at] == ' ') ++at; + const std::size_t begin = at; + while (at < line.size() && line[at] != ' ') ++at; + if (begin != at) tokens.push_back(line.substr(begin, at - begin)); + } + return tokens; +} + +inline bool read_bool(const std::vector<std::string_view>& tokens, std::size_t at, bool& out) +{ + std::uint64_t value = 0; + if (at >= tokens.size() || !parse_unsigned(tokens[at], value) || value > 1) return false; + out = value != 0; + return true; +} + +inline bool read_bool(const std::vector<std::string_view>& tokens, std::size_t at, BOOL& out) +{ + bool value = false; + if (!read_bool(tokens, at, value)) return false; + out = value ? TRUE : FALSE; + return true; +} + +inline bool read_uint(const std::vector<std::string_view>& tokens, std::size_t at, unsigned& out) +{ + std::uint64_t value = 0; + if (at >= tokens.size() || !parse_unsigned(tokens[at], value) || value > std::numeric_limits<unsigned>::max()) return false; + out = static_cast<unsigned>(value); + return true; +} + +inline bool read_uint_range(const std::vector<std::string_view>& tokens, std::size_t at, unsigned low, unsigned high, + unsigned& out) +{ + return read_uint(tokens, at, out) && out >= low && out <= high; +} + +inline bool read_hex32(const std::vector<std::string_view>& tokens, std::size_t at, std::uint32_t& out) +{ + std::uint64_t value = 0; + if (at >= tokens.size() || !parse_unsigned(tokens[at], value, 16) || value > 0xffffffffull) return false; + out = static_cast<std::uint32_t>(value); + return true; +} + +inline bool parse_pso_recipe_lines(const std::vector<std::string_view>& lines, std::size_t at, PsoRecipe& recipe, + std::string& why) +{ + if (at + 20 > lines.size()) { + why = "truncated record"; + return false; + } + if (lines[at] != "x2w-pso-recipe 1") { + why = "unknown recipe version"; + return false; + } + recipe = {}; + auto line = [&](std::size_t index) { return pso_recipe_tokens(lines[at + index]); }; + + auto tokens = line(1); + if (tokens.size() != 2 || tokens[0] != "state" || !parse_unsigned(tokens[1], recipe.state_key, 16)) { + why = "malformed state line"; + return false; + } + tokens = line(2); + if (tokens.size() != 2 || tokens[0] != "translation" || !parse_unsigned(tokens[1], recipe.translation_key, 16)) { + why = "malformed translation line"; + return false; + } + tokens = line(3); + if (tokens.size() != 10 || tokens[0] != "targets" || !read_uint(tokens, 1, recipe.target_count) || + recipe.target_count > pso_recipe_target_limit) { + why = "malformed targets line"; + return false; + } + for (unsigned i = 0; i < pso_recipe_target_limit; ++i) { + unsigned format = 0; + if (!read_uint(tokens, 2 + i, format) || format > 0xffff) { + why = "malformed target format"; + return false; + } + recipe.target_formats[i] = static_cast<DXGI_FORMAT>(format); + } + tokens = line(4); + unsigned dsv = 0; + if (tokens.size() != 2 || tokens[0] != "dsv" || !read_uint(tokens, 1, dsv) || dsv > 0xffff) { + why = "malformed dsv line"; + return false; + } + recipe.dsv_format = static_cast<DXGI_FORMAT>(dsv); + tokens = line(5); + if (tokens.size() != 2 || tokens[0] != "indexed" || !read_bool(tokens, 1, recipe.indexed_rect)) { + why = "malformed indexed line"; + return false; + } + tokens = line(6); + if (tokens.size() != 3 || tokens[0] != "blend" || !read_bool(tokens, 1, recipe.blend.AlphaToCoverageEnable) || + !read_bool(tokens, 2, recipe.blend.IndependentBlendEnable)) { + why = "malformed blend line"; + return false; + } + for (unsigned i = 0; i < 8; ++i) { + tokens = line(7 + i); + const std::string expected = "blend" + std::to_string(i); + auto& target = recipe.blend.RenderTarget[i]; + unsigned src = 0, dest = 0, op = 0, src_alpha = 0, dest_alpha = 0, op_alpha = 0, logic = 0, write_mask = 0; + if (tokens.size() != 11 || tokens[0] != expected || !read_bool(tokens, 1, target.BlendEnable) || + !read_bool(tokens, 2, target.LogicOpEnable) || !read_uint_range(tokens, 3, 1, 19, src) || + !read_uint_range(tokens, 4, 1, 19, dest) || !read_uint_range(tokens, 5, 1, 5, op) || + !read_uint_range(tokens, 6, 1, 19, src_alpha) || !read_uint_range(tokens, 7, 1, 19, dest_alpha) || + !read_uint_range(tokens, 8, 1, 5, op_alpha) || !read_uint_range(tokens, 9, 0, 15, logic) || + !read_uint_range(tokens, 10, 0, 15, write_mask)) { + why = "malformed " + expected + " line"; + return false; + } + target.SrcBlend = static_cast<D3D12_BLEND>(src); + target.DestBlend = static_cast<D3D12_BLEND>(dest); + target.BlendOp = static_cast<D3D12_BLEND_OP>(op); + target.SrcBlendAlpha = static_cast<D3D12_BLEND>(src_alpha); + target.DestBlendAlpha = static_cast<D3D12_BLEND>(dest_alpha); + target.BlendOpAlpha = static_cast<D3D12_BLEND_OP>(op_alpha); + target.LogicOp = static_cast<D3D12_LOGIC_OP>(logic); + target.RenderTargetWriteMask = static_cast<UINT8>(write_mask); + } + tokens = line(15); + unsigned depth_enable = 0, write_mask = 0, depth_func = 0, stencil_enable = 0, read_mask = 0, stencil_write_mask = 0; + unsigned front_fail = 0, front_depth_fail = 0, front_pass = 0, front_func = 0; + unsigned back_fail = 0, back_depth_fail = 0, back_pass = 0, back_func = 0; + if (tokens.size() != 16 || tokens[0] != "depth" || !read_bool(tokens, 1, recipe.use_depth_stencil) || + !read_bool(tokens, 2, recipe.depth_stencil.DepthEnable) || + !read_uint_range(tokens, 3, 0, 1, write_mask) || !read_uint_range(tokens, 4, 1, 8, depth_func) || + !read_bool(tokens, 5, recipe.depth_stencil.StencilEnable) || !read_uint_range(tokens, 6, 0, 255, read_mask) || + !read_uint_range(tokens, 7, 0, 255, stencil_write_mask) || !read_uint_range(tokens, 8, 1, 8, front_fail) || + !read_uint_range(tokens, 9, 1, 8, front_depth_fail) || !read_uint_range(tokens, 10, 1, 8, front_pass) || + !read_uint_range(tokens, 11, 1, 8, front_func) || !read_uint_range(tokens, 12, 1, 8, back_fail) || + !read_uint_range(tokens, 13, 1, 8, back_depth_fail) || !read_uint_range(tokens, 14, 1, 8, back_pass) || + !read_uint_range(tokens, 15, 1, 8, back_func)) { + why = "malformed depth line"; + return false; + } + recipe.depth_stencil.DepthWriteMask = static_cast<D3D12_DEPTH_WRITE_MASK>(write_mask); + recipe.depth_stencil.DepthFunc = static_cast<D3D12_COMPARISON_FUNC>(depth_func); + recipe.depth_stencil.StencilReadMask = static_cast<UINT8>(read_mask); + recipe.depth_stencil.StencilWriteMask = static_cast<UINT8>(stencil_write_mask); + recipe.depth_stencil.FrontFace.StencilFailOp = static_cast<D3D12_STENCIL_OP>(front_fail); + recipe.depth_stencil.FrontFace.StencilDepthFailOp = static_cast<D3D12_STENCIL_OP>(front_depth_fail); + recipe.depth_stencil.FrontFace.StencilPassOp = static_cast<D3D12_STENCIL_OP>(front_pass); + recipe.depth_stencil.FrontFace.StencilFunc = static_cast<D3D12_COMPARISON_FUNC>(front_func); + recipe.depth_stencil.BackFace.StencilFailOp = static_cast<D3D12_STENCIL_OP>(back_fail); + recipe.depth_stencil.BackFace.StencilDepthFailOp = static_cast<D3D12_STENCIL_OP>(back_depth_fail); + recipe.depth_stencil.BackFace.StencilPassOp = static_cast<D3D12_STENCIL_OP>(back_pass); + recipe.depth_stencil.BackFace.StencilFunc = static_cast<D3D12_COMPARISON_FUNC>(back_func); + + tokens = line(16); + unsigned fill = 0, cull = 0, conservative = 0; + std::int64_t depth_bias = 0; + std::uint32_t clamp_bits = 0, slope_bits = 0; + if (tokens.size() != 13 || tokens[0] != "raster" || !read_bool(tokens, 1, recipe.has_rasterizer) || + !read_uint_range(tokens, 2, 2, 3, fill) || !read_uint_range(tokens, 3, 1, 3, cull) || + !read_bool(tokens, 4, recipe.rasterizer.FrontCounterClockwise) || !parse_integer(tokens[5], depth_bias) || + depth_bias < std::numeric_limits<INT>::min() || depth_bias > std::numeric_limits<INT>::max() || + !read_hex32(tokens, 6, clamp_bits) || !read_hex32(tokens, 7, slope_bits) || + !read_bool(tokens, 8, recipe.rasterizer.DepthClipEnable) || + !read_bool(tokens, 9, recipe.rasterizer.MultisampleEnable) || + !read_bool(tokens, 10, recipe.rasterizer.AntialiasedLineEnable) || + !read_uint(tokens, 11, recipe.rasterizer.ForcedSampleCount) || !read_uint_range(tokens, 12, 0, 2, conservative)) { + why = "malformed raster line"; + return false; + } + recipe.rasterizer.FillMode = static_cast<D3D12_FILL_MODE>(fill); + recipe.rasterizer.CullMode = static_cast<D3D12_CULL_MODE>(cull); + recipe.rasterizer.DepthBias = static_cast<INT>(depth_bias); + std::memcpy(&recipe.rasterizer.DepthBiasClamp, &clamp_bits, sizeof(clamp_bits)); + std::memcpy(&recipe.rasterizer.SlopeScaledDepthBias, &slope_bits, sizeof(slope_bits)); + recipe.rasterizer.ConservativeRaster = static_cast<D3D12_CONSERVATIVE_RASTERIZATION_MODE>(conservative); + + tokens = line(17); + if (tokens.size() != 3 || tokens[0] != "sample" || !read_uint_range(tokens, 1, 1, 16, recipe.sample_count) || + !read_uint(tokens, 2, recipe.sample_mask)) { + why = "malformed sample line"; + return false; + } + unsigned topology = 0; + tokens = line(18); + if (tokens.size() != 2 || tokens[0] != "topology" || !read_uint_range(tokens, 1, 0, 4, topology)) { + why = "malformed topology line"; + return false; + } + recipe.topology = static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(topology); + if (line(19).size() != 1 || line(19)[0] != "end") { + why = "missing end line"; + return false; + } + + // The serializer records a valid default for an unused state so that every field it writes is + // a legal enum. The state key ignores both blocks when their flags are clear; normalize them + // here so a replay compares the same zero/default values the creation path uses. + if (!recipe.use_depth_stencil) recipe.depth_stencil = {}; + if (!recipe.has_rasterizer) recipe.rasterizer = default_pso_rasterizer(); + if (pso_recipe_state_key(recipe) != recipe.state_key) { + why = "state key does not match the recorded state"; + return false; + } + return true; +} + +inline PsoRecipeParseResult parse_pso_recipe_file(std::string_view text) +{ + PsoRecipeParseResult result; + if (text.size() > pso_recipe_file_limit) { + result.rejected = 1; + result.error = "recipe file exceeds the size limit"; + return result; + } + std::vector<std::string_view> lines; + std::size_t at = 0; + while (at <= text.size()) { + const std::size_t end = text.find('\n', at); + std::string_view line = text.substr(at, end == std::string_view::npos ? std::string_view::npos : end - at); + if (!line.empty() && line.back() == '\r') line.remove_suffix(1); + if (!line.empty()) lines.push_back(line); + if (end == std::string_view::npos) break; + at = end + 1; + } + std::size_t i = 0; + while (i < lines.size()) { + if (lines[i].substr(0, 15) != "x2w-pso-recipe ") { + result.rejected++; + if (result.error.empty()) result.error = "unexpected line outside a recipe"; + ++i; + continue; + } + if (lines[i] != "x2w-pso-recipe 1") { + result.rejected++; + if (result.error.empty()) result.error = "unknown recipe version"; + i += (i + 20 <= lines.size()) ? 20 : 1; + continue; + } + if (result.recipes.size() >= pso_recipe_record_limit) { + result.rejected++; + if (result.error.empty()) result.error = "recipe record limit reached"; + i += (i + 20 <= lines.size()) ? 20 : 1; + continue; + } + PsoRecipe recipe; + std::string why; + if (!parse_pso_recipe_lines(lines, i, recipe, why)) { + result.rejected++; + if (result.error.empty()) result.error = why; + i += (i + 20 <= lines.size()) ? 20 : 1; + continue; + } + result.recipes.push_back(recipe); + i += 20; + } + return result; +} + +// The parser accepts at most pso_recipe_record_limit complete records. The writer must stop at +// the same boundary instead of appending a record the next process will reject. A file with any +// rejected line is left alone: one more append cannot make it parse cleanly. +inline bool pso_recipe_append_allowed(std::string_view existing, std::string_view record) +{ + if (record.empty() || record.size() > pso_recipe_file_limit) return false; + // A parseable last record may still lack its final LF. Appending then joins its `end` to the + // next header on one line, so the next read loses both records. Refuse without writing. + if (!existing.empty() && existing.back() != '\n') return false; + if (existing.size() > pso_recipe_file_limit || record.size() > pso_recipe_file_limit - existing.size()) + return false; + const PsoRecipeParseResult parsed = parse_pso_recipe_file(existing); + if (parsed.rejected != 0) return false; + return parsed.recipes.size() < pso_recipe_record_limit; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/registry_console_mode.inl b/src/startup_stubs/registry_console_mode.inl new file mode 100644 index 0000000000..7af9b49aea --- /dev/null +++ b/src/startup_stubs/registry_console_mode.inl @@ -0,0 +1,314 @@ +// Experimental (docs/startup-runtime.md): registry reads of the console mode (see console_mode.h). +// Included inside runtime_proxy.cpp's anonymous namespace, and on its own by +// tests/startup_console_mode_check.cpp. Needs <windows.h>, <atomic>, local_log.h, +// runtime_gpa_patch.h and console_mode.h. +// +// With X2W_RUNTIME_PROXY the stand-in rewrites five registry imports of the EXE and package helpers +// (regular IAT and GetProcAddress by name), only where the Windows registry provides them: see +// registry_provider_module below. Every call goes to the real function except a read of +// ConsoleMode under HKLM\...\OEM while X2W_DEVICE_TYPE names a known console. Opening the OEM +// key and reading the value are logged a few times in either case, so a run shows whether the +// title asks at all. + +enum RegistryImport { reg_open_key_ex_w, reg_open_key_w, reg_query_value_ex_w, reg_get_value_w, reg_close_key, registry_imports }; +constexpr const char* registry_import_names[registry_imports] = {"RegOpenKeyExW", "RegOpenKeyW", "RegQueryValueExW", "RegGetValueW", + "RegCloseKey"}; +using RegOpenKeyExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY); +using RegOpenKeyWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, PHKEY); +using RegQueryValueExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using RegGetValueWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD); +using RegCloseKeyFn = LSTATUS(WINAPI*)(HKEY); + +std::atomic<void*> real_registry[registry_imports]; + +int registry_import_index(const char* name) noexcept +{ + if (!name) return -1; + for (int i = 0; i < registry_imports; ++i) + if (std::strcmp(name, registry_import_names[i]) == 0) return i; + return -1; +} + +// ---- which modules are the Windows registry ----------------------------------------------------- +// A package DLL can export the same names. Only these system modules count as the registry, for the +// GetProcAddress module, for the module that holds a bound IAT address and for what is remembered +// as the real function. The api-ms-win-core-registry API sets resolve to kernelbase.dll. +constexpr const wchar_t* registry_provider_names[] = {L"advapi32.dll", L"kernelbase.dll", L"kernel32.dll"}; + +#if defined(X2W_CONSOLE_MODE_FIXTURE) +// tests/startup_console_mode_check.cpp keeps its fake registry in the test EXE, which counts as one +// more provider there. Its provider control sets registry_any_provider (name-only matching), which +// the decoy checks must catch. +bool registry_any_provider; +bool fixture_registry_provider(HMODULE module) noexcept { return module == GetModuleHandleW(nullptr); } +#else +constexpr bool registry_any_provider = false; +constexpr bool fixture_registry_provider(HMODULE) noexcept { return false; } +#endif + +// The loaded system-directory copy of a provider, by full path, so a same-named DLL elsewhere does not match. +bool registry_provider_module(HMODULE module) noexcept +{ + if (registry_any_provider) return true; + if (!module) return false; + if (fixture_registry_provider(module)) return true; + const DWORD saved = GetLastError(); + wchar_t path[MAX_PATH]{}; + const UINT length = GetSystemDirectoryW(path, MAX_PATH); + bool found = false; + for (const wchar_t* name : registry_provider_names) { + if (found || !length || length >= MAX_PATH) break; + std::size_t at = length, i = 0; + path[at++] = L'\\'; + for (; name[i] && at + 1 < MAX_PATH; ++i) path[at++] = name[i]; + if (name[i]) break; + path[at] = 0; + found = GetModuleHandleW(path) == module; + } + SetLastError(saved); + return found; +} + +bool registry_provider_address(const void* address) noexcept +{ + if (registry_any_provider) return true; + const DWORD saved = GetLastError(); + HMODULE module = nullptr; + const bool known = address && GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast<LPCWSTR>(address), &module); + SetLastError(saved); + return known && registry_provider_module(module); +} + +// Import DLL names (any case) that supply the registry: the providers above and the +// api-ms-win-core-registry-* API sets. +bool registry_provider_dll(const char* dll) noexcept +{ + if (registry_any_provider) return true; + if (!dll) return false; + const auto lower = [](char c) { return (c >= 'A' && c <= 'Z') ? static_cast<char>(c - 'A' + 'a') : c; }; + const auto equal = [&](const char* expect) { + std::size_t i = 0; + for (; expect[i]; ++i) + if (lower(dll[i]) != expect[i]) return false; + return dll[i] == 0; + }; + if (equal("advapi32.dll") || equal("kernelbase.dll") || equal("kernel32.dll")) return true; + static constexpr char api_set[] = "api-ms-win-core-registry-"; + for (std::size_t i = 0; api_set[i]; ++i) + if (lower(dll[i]) != api_set[i]) return false; + return true; +} + +// ---- OEM key handles the title opened ----------------------------------------------------------- +SRWLOCK oem_lock = SRWLOCK_INIT; +HKEY oem_keys[16]; + +void note_oem_table_full() noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime console mode: %u OEM key handles already open, another is not tracked", + static_cast<unsigned>(sizeof(oem_keys) / sizeof(oem_keys[0]))); +} + +void track_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + bool tracked = false; + for (HKEY& slot : oem_keys) { + if (!slot) { + slot = key; + tracked = true; + break; + } + } + ReleaseSRWLockExclusive(&oem_lock); + if (!tracked) note_oem_table_full(); +} + +bool oem_key(HKEY key) noexcept +{ + if (!key) return false; + AcquireSRWLockShared(&oem_lock); + bool found = false; + for (HKEY slot : oem_keys) found = found || slot == key; + ReleaseSRWLockShared(&oem_lock); + return found; +} + +void untrack_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + for (HKEY& slot : oem_keys) + if (slot == key) slot = nullptr; + ReleaseSRWLockExclusive(&oem_lock); +} + +// ---- the answer --------------------------------------------------------------------------------- +x2w_console_mode::Answer console_answer(std::uint32_t* mode, unsigned long* device) noexcept +{ + const DWORD saved = GetLastError(); + char text[16]{}; + const DWORD length = GetEnvironmentVariableA("X2W_DEVICE_TYPE", text, sizeof(text)); + SetLastError(saved); + char* end = nullptr; + const unsigned long value = length && length < sizeof(text) ? std::strtoul(text, &end, 0) : 0; + const bool set = length && length < sizeof(text) && end && end != text && !*end; + *device = value; + return x2w_console_mode::answer_for(set, value, mode); +} + +void note_oem_open(const char* via, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 4)) + x2w_local::logf("x2w-runtime console mode: %s opened the OEM key, real status %ld", via, static_cast<long>(status)); +} + +// One line per read (the first eight): what was answered, and the real status or value when passed on. +void note_console_read(const char* via, x2w_console_mode::Answer answer, unsigned long device, std::uint32_t value, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (!x2w_local::first_calls(logged, 8)) return; + if (answer == x2w_console_mode::Answer::value) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> 0x%x for X2W_DEVICE_TYPE=%lu, status %ld", via, value, device, + static_cast<long>(status)); + else if (answer == x2w_console_mode::Answer::missing) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> missing (PC) for X2W_DEVICE_TYPE=%lu", via, device); + else if (status == ERROR_SUCCESS) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> 0x%x", via, value); + else + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> status %ld", via, static_cast<long>(status)); +} + +template <class Fn> +Fn real_reg(RegistryImport which) noexcept +{ + return reinterpret_cast<Fn>(real_registry[which].load(std::memory_order_acquire)); +} + +LSTATUS WINAPI hooked_reg_open_key_ex_w(HKEY root, LPCWSTR subkey, DWORD options, REGSAM access, PHKEY out) +{ + const auto real = real_reg<RegOpenKeyExWFn>(reg_open_key_ex_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, options, access, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyExW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +LSTATUS WINAPI hooked_reg_open_key_w(HKEY root, LPCWSTR subkey, PHKEY out) +{ + const auto real = real_reg<RegOpenKeyWFn>(reg_open_key_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +std::uint32_t dword_read(LSTATUS status, const void* data, const DWORD* bytes) noexcept +{ + std::uint32_t value = 0; + if (status == ERROR_SUCCESS && data && bytes && *bytes >= sizeof(value)) std::memcpy(&value, data, sizeof(value)); + return value; +} + +LSTATUS WINAPI hooked_reg_query_value_ex_w(HKEY key, LPCWSTR name, LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD bytes) +{ + const auto real = real_reg<RegQueryValueExWFn>(reg_query_value_ex_w); + if (!x2w_console_mode::is_console_mode_value(name) || !oem_key(key)) + return real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_query(mode, reinterpret_cast<unsigned long*>(type), data, reinterpret_cast<unsigned long*>(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegQueryValueExW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_get_value_w(HKEY key, LPCWSTR subkey, LPCWSTR name, DWORD flags, LPDWORD type, PVOID data, LPDWORD bytes) +{ + const auto real = real_reg<RegGetValueWFn>(reg_get_value_w); + const bool oem = (key == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) || (oem_key(key) && (!subkey || !*subkey)); + if (!oem || !x2w_console_mode::is_console_mode_value(name)) + return real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_get(flags, mode, reinterpret_cast<unsigned long*>(type), data, reinterpret_cast<unsigned long*>(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegGetValueW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_close_key(HKEY key) +{ + const auto real = real_reg<RegCloseKeyFn>(reg_close_key); + untrack_oem(key); + return real ? real(key) : ERROR_PROC_NOT_FOUND; +} + +void* const registry_hooks[registry_imports] = { + reinterpret_cast<void*>(&hooked_reg_open_key_ex_w), reinterpret_cast<void*>(&hooked_reg_open_key_w), + reinterpret_cast<void*>(&hooked_reg_query_value_ex_w), reinterpret_cast<void*>(&hooked_reg_get_value_w), + reinterpret_cast<void*>(&hooked_reg_close_key)}; + +// Keep the first real address for each import: one inside a registry provider, never one of the +// hooks themselves. +bool remember_registry(int which, void* real) noexcept +{ + if (which < 0 || which >= registry_imports || !real) return false; + for (void* hook : registry_hooks) + if (real == hook) return false; + if (!registry_provider_address(real)) return false; + void* expected = nullptr; + real_registry[which].compare_exchange_strong(expected, real, std::memory_order_acq_rel); + return true; +} + +// GetProcAddress by name: the hook for a registry import looked up on a registry provider, or null +// for any other name or module. +FARPROC registry_hook_for(HMODULE module, LPCSTR name, FARPROC real) noexcept +{ + const int which = registry_import_index(name); + if (which < 0 || !registry_provider_module(module) || !remember_registry(which, reinterpret_cast<void*>(real))) return nullptr; + return reinterpret_cast<FARPROC>(registry_hooks[which]); +} + +// Rewrite one image's regular registry IAT slots that import from a registry provider and are bound +// inside one. Delay-import slots hold a thunk and are left alone. +int patch_registry_imports(unsigned char* base, std::size_t image_size) noexcept +{ + int patched = 0; + const auto classify = [](const char* dll, const char* name, x2w_runtime_patch::Kind* kind) { + if (registry_import_index(name) < 0 || !registry_provider_dll(dll)) return false; + *kind = x2w_runtime_patch::Kind::registry; + return true; + }; + x2w_runtime_patch::visit_imports_with(base, image_size, classify, [&](const x2w_runtime_patch::Hit& hit) { + if (hit.delay_import) return; + const int which = registry_import_index(hit.import_name); + auto* slot = reinterpret_cast<ULONGLONG*>(base + hit.first_thunk_rva); + if (*slot == reinterpret_cast<ULONGLONG>(registry_hooks[which])) return; + if (!remember_registry(which, reinterpret_cast<void*>(*slot))) return; + DWORD old = 0; + if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; + *slot = reinterpret_cast<ULONGLONG>(registry_hooks[which]); + VirtualProtect(slot, 8, old, &old); + ++patched; + }); + return patched; +} diff --git a/src/startup_stubs/resident_pages.h b/src/startup_stubs/resident_pages.h new file mode 100644 index 0000000000..6cae74c59e --- /dev/null +++ b/src/startup_stubs/resident_pages.h @@ -0,0 +1,31 @@ +#pragma once +// Shared by XCRDAPI's destination check (src/startup_stubs/xcrdapi.cpp) and xmem's copy into a destination +// (x2w_xmem_copy_to_destination, src/xmem_mapped_pages.cpp). +#include <windows.h> +#include <psapi.h> + +#include <cstdint> + +namespace x2w_local { +// True when every page of [start, end) is resident and plain read-write: valid in the working set, PAGE_READWRITE +// or PAGE_EXECUTE_READWRITE, no guard bit. One QueryWorkingSetEx per 512 pages, so the cost follows the +// destination's size, not the region's. Reads attributes only; no page is touched. +inline bool resident_read_write(std::uintptr_t start, std::uintptr_t end) noexcept +{ + PSAPI_WORKING_SET_EX_INFORMATION pages[512]; + std::uintptr_t page = start & ~std::uintptr_t{0xFFF}; + while (page < end) { + DWORD count = 0; + for (; count < 512 && page < end; ++count, page += 0x1000) pages[count].VirtualAddress = reinterpret_cast<void*>(page); + if (!QueryWorkingSetEx(GetCurrentProcess(), pages, count * sizeof(pages[0]))) return false; + for (DWORD i = 0; i < count; ++i) { + const auto& page_info = pages[i].VirtualAttributes; + const DWORD protect = static_cast<DWORD>(page_info.Win32Protection); + if (!page_info.Valid || page_info.Bad || (protect & PAGE_GUARD) || + ((protect & 0xFF) != PAGE_READWRITE && (protect & 0xFF) != PAGE_EXECUTE_READWRITE)) + return false; + } + } + return true; +} +} // namespace x2w_local diff --git a/src/startup_stubs/root_constant_store.h b/src/startup_stubs/root_constant_store.h new file mode 100644 index 0000000000..45b9914008 --- /dev/null +++ b/src/startup_stubs/root_constant_store.h @@ -0,0 +1,64 @@ +// Experimental (docs/startup-runtime.md, #870): the 32-bit compute root arguments a recorded command list keeps +// (list slots 37 and 39; the graphics slot 40 keeps its own words). Plain standard C++ with no Windows types, so it can be tested on its own. +// +// A list keeps 16 root parameters of 8 words each. A write that starts past those limits is dropped and one +// that runs past them is cut off at the end of the parameter, so the caller can log either case. +#pragma once + +#include <cstddef> +#include <cstdint> + +namespace x2w_root_constants { + +inline constexpr unsigned parameter_count = 16; +inline constexpr unsigned words_per_parameter = 8; + +enum class Result { stored, truncated, dropped }; + +struct Store { + std::uint32_t words[parameter_count][words_per_parameter] = {}; + // One bit per word that a write stored, like the graphics path's `constant_words_bound`, so a later + // dispatch can tell "set to 0" from "never set". + std::uint8_t bound[parameter_count] = {}; + + void clear() noexcept + { + for (auto& row : words) + for (auto& word : row) word = 0; + for (auto& mask : bound) mask = 0; + } + + // True when every word in [offset, offset + count) of `parameter` was written since the last clear. + bool is_bound(unsigned parameter, unsigned offset, unsigned count) const noexcept + { + if (!count || parameter >= parameter_count || offset >= words_per_parameter || count > words_per_parameter - offset) + return false; + const unsigned mask = ((1u << count) - 1) << offset; + return (bound[parameter] & mask) == mask; + } + + // SetXxxRoot32BitConstants(parameter, count, data, offset). `data` must hold `count` words. + Result set(unsigned parameter, unsigned count, const std::uint32_t* data, unsigned offset) noexcept + { + if (!count || !data || parameter >= parameter_count || offset >= words_per_parameter) return Result::dropped; + const bool cut = count > words_per_parameter - offset; + const unsigned n = cut ? words_per_parameter - offset : count; + for (unsigned i = 0; i < n; ++i) words[parameter][offset + i] = data[i]; + bound[parameter] |= static_cast<std::uint8_t>(((1u << n) - 1) << offset); + return cut ? Result::truncated : Result::stored; + } + + // SetXxxRoot32BitConstant(parameter, value, offset). + Result set_one(unsigned parameter, std::uint32_t value, unsigned offset) noexcept { return set(parameter, 1, &value, offset); } + + // The word a shader reads; 0 outside the kept range. + std::uint32_t word(int parameter, int offset) const noexcept + { + return parameter >= 0 && parameter < static_cast<int>(parameter_count) && offset >= 0 && + offset < static_cast<int>(words_per_parameter) + ? words[parameter][offset] + : 0; + } +}; + +} // namespace x2w_root_constants diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index e5b23da826..b9dd8a4d09 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -16,7 +16,8 @@ namespace x2w_runtime_patch { -enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2 }; +// registry: one of the registry imports named by console_mode.h (classified by its own caller). +enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2, registry = 3 }; struct Hit { Kind kind; @@ -113,9 +114,9 @@ inline bool c_string_in_image(const unsigned char* base, std::size_t image_size, return false; } -template <class Fn> +template <class Classify, class Fn> int visit_named_thunks(const unsigned char* base, std::size_t image_size, const char* dll, std::uint32_t name_table_rva, - std::uint32_t iat_rva, bool delay_import, Fn on_hit) + std::uint32_t iat_rva, bool delay_import, Classify classify, Fn on_hit) { int hits = 0; for (std::uint32_t ti = 0;; ++ti) { @@ -139,10 +140,11 @@ int visit_named_thunks(const unsigned char* base, std::size_t image_size, const return hits; } -// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each classified import. -// Returns the number of hits. Malformed images stop the walk and return what was found. -template <class Fn> -int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each import that +// `classify(dll, name, &kind)` accepts. Returns the number of hits. Malformed images stop the walk +// and return what was found. +template <class Classify, class Fn> +int visit_imports_with(const unsigned char* base, std::size_t image_size, Classify classify, Fn on_hit) { if (!readable_range(base, image_size, 0, sizeof(DosStub))) return 0; const auto* dos = reinterpret_cast<const DosStub*>(base); @@ -167,7 +169,7 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!imp->name || !imp->original_first_thunk || !imp->first_thunk) continue; if (!c_string_in_image(base, image_size, imp->name)) continue; const char* dll = reinterpret_cast<const char*>(base + imp->name); - hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, on_hit); + hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, classify, on_hit); } } @@ -181,10 +183,18 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!delay->dll_name || !delay->original_first_thunk || !delay->first_thunk) continue; if (!c_string_in_image(base, image_size, delay->dll_name)) continue; const char* dll = reinterpret_cast<const char*>(base + delay->dll_name); - hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, on_hit); + hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, classify, on_hit); } } return hits; } +// The runtime proxy's own imports: GetProcAddress from any module, QueryApiImpl from xgameruntime.dll. +template <class Fn> +int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +{ + return visit_imports_with(base, image_size, [](const char* dll, const char* name, Kind* kind) { return classify(dll, name, kind); }, + on_hit); +} + } // namespace x2w_runtime_patch diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a170462..bf117e9e82 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -14,6 +14,7 @@ // X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below) // and, while the proxy is on, XStoreCreateContext for that user (see area_call). #include "startup_stubs/api_trace.h" +#include "startup_stubs/console_mode.h" #include "startup_stubs/local_log.h" #include "startup_stubs/runtime_gpa_patch.h" #include "startup_stubs/save_blob_pack.h" @@ -484,12 +485,16 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept return true; } +#include "startup_stubs/registry_console_mode.inl" + FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) { const FARPROC real = GetProcAddress(module, name); if (real && reinterpret_cast<u64>(name) > 0xffff) { static LONG logged; if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast<void*>(module), name, static_cast<void*>(real)); + // Registry exports only when the module is a Windows registry provider (registry_console_mode.inl). + if (const FARPROC hook = registry_hook_for(module, name, real)) return hook; // Wrap gaming-runtime exports only when the provider module is xgameruntime.dll. if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0 && remember_real_query(reinterpret_cast<QueryApi>(real))) @@ -555,6 +560,13 @@ int patch_module(HMODULE module) } VirtualProtect(slot, 8, old, &old); }); + // Registry imports for the console mode (registry_console_mode.inl), counted on their own line. + if (!self) { + const int registry = patch_registry_imports(base, image_size); + if (registry > 0) + x2w_local::logf("x2w-runtime console mode: %d registry import(s) patched in the %s", registry, + module == GetModuleHandleW(nullptr) ? "main module" : "package module"); + } return patched; } @@ -820,8 +832,8 @@ std::string update_container(u64 update) { std::string name; AcquireSRWLockShared(&save_lock); + struct Unlock { ~Unlock() { ReleaseSRWLockShared(&save_lock); } } unlock; if (update >= save_update_handle) name = save_table.update_container(static_cast<std::size_t>(update - save_update_handle)); - ReleaseSRWLockShared(&save_lock); return name; } #include "startup_stubs/save_read.inl" @@ -1190,23 +1202,26 @@ bool save_call(int slot, u64* args, u64* result) // reaches the disk before the update is submitted, and an update closed without a submit // leaves the save as it was. Only an open update is acted on; any other argument is // accepted and dropped as before. - std::string blob; - if (update_container(args[0]).empty() || !read_save_name(args[1], blob)) return true; x2w_save::Action action; - action.remove = slot == 26; - action.blob = blob; - if (!x2w_save::valid_name(blob)) { - *result = e_invalidarg; - return true; - } - if (!action.remove) { - const std::size_t size = static_cast<std::size_t>(args[3]); - if (size > x2w_save::max_blob_bytes || (size && x2w_local::probe_readable(static_cast<std::uintptr_t>(args[2]), size) != size)) { + try { + if (update_container(args[0]).empty() || !read_save_name(args[1], action.blob)) return true; + action.remove = slot == 26; + if (!x2w_save::valid_name(action.blob)) { *result = e_invalidarg; return true; } - const auto* bytes = reinterpret_cast<const unsigned char*>(args[2]); - if (size) action.data.assign(bytes, bytes + size); + if (!action.remove) { + const std::size_t size = static_cast<std::size_t>(args[3]); + if (size > x2w_save::max_blob_bytes || (size && x2w_local::probe_readable(static_cast<std::uintptr_t>(args[2]), size) != size)) { + *result = e_invalidarg; + return true; + } + const auto* bytes = reinterpret_cast<const unsigned char*>(args[2]); + if (size) action.data.assign(bytes, bytes + size); + } + } catch (const std::bad_alloc&) { + *result = e_outofmemory; + return true; } AcquireSRWLockExclusive(&save_lock); const bool staged = args[0] >= save_update_handle && save_table.stage(static_cast<std::size_t>(args[0] - save_update_handle), std::move(action)); diff --git a/src/startup_stubs/save_store.h b/src/startup_stubs/save_store.h index 9887644fee..2237dd77bd 100644 --- a/src/startup_stubs/save_store.h +++ b/src/startup_stubs/save_store.h @@ -13,6 +13,7 @@ #include <fstream> #include <functional> #include <mutex> +#include <new> #include <string> #include <string_view> #include <system_error> @@ -56,12 +57,21 @@ inline bool valid_name(std::string_view name) noexcept same = std::tolower(static_cast<unsigned char>(tail[i])) == suffix[i]; if (same) return false; } - std::string stem(name.substr(0, name.find('.'))); - for (char& c : stem) c = static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c); - while (!stem.empty() && stem.back() == ' ') stem.pop_back(); + std::string_view stem = name.substr(0, name.find('.')); + while (!stem.empty() && stem.back() == ' ') stem.remove_suffix(1); + const auto upper = [](char c) { return static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c); }; + const auto matches = [&](std::string_view device) { + if (stem.size() != device.size()) return false; + for (std::size_t i = 0; i < stem.size(); ++i) + if (upper(stem[i]) != device[i]) return false; + return true; + }; for (const char* device : {"CON", "PRN", "AUX", "NUL"}) - if (stem == device) return false; - if (stem.size() == 4 && (stem.compare(0, 3, "COM") == 0 || stem.compare(0, 3, "LPT") == 0) && stem[3] >= '0' && stem[3] <= '9') return false; + if (matches(device)) return false; + if (stem.size() == 4 && stem[3] >= '0' && stem[3] <= '9') { + stem.remove_suffix(1); + if (matches("COM") || matches("LPT")) return false; + } return true; } @@ -145,8 +155,13 @@ class ContainerTable { { if (update >= capacity || !updates_[update]) return false; if (action.data.size() > max_staged_bytes - staged_bytes_[update]) return false; - staged_bytes_[update] += action.data.size(); - staged_[update].push_back(std::move(action)); + const std::size_t size = action.data.size(); + try { + staged_[update].push_back(std::move(action)); + } catch (const std::bad_alloc&) { + return false; + } + staged_bytes_[update] += size; return true; } // The staged actions in order; the update starts empty again. diff --git a/src/startup_stubs/split_indirect_dispatch.h b/src/startup_stubs/split_indirect_dispatch.h new file mode 100644 index 0000000000..f7f2de0917 --- /dev/null +++ b/src/startup_stubs/split_indirect_dispatch.h @@ -0,0 +1,177 @@ +// Split of a batched indirect Dispatch into single-command calls, for adapters whose driver runs only the first +// command of an ExecuteIndirect with a Dispatch signature. Opt-in only: slot 61 applies it with +// X2W_SPLIT_INDIRECT_DISPATCH=1, to a rootless Dispatch signature with a desktop compute pipeline and root. +// +// On an AMD Radeon RX 5700 XT (RDNA 1, device 731f), drivers 31.0.23013.1023 to 32.0.21045.29003 run exactly one +// command of ExecuteIndirect(Dispatch signature, MaxCommandCount > 1), with or without a count buffer, and ignore +// the count buffer of a single-command call. Single-command calls without a count buffer are exact. Measurements: +// docs/experiments.md#batched-indirect-dispatch-on-rdna-1. +// +// The split copies the count word and the records into a scratch buffer, and a one-group compute pass rewrites +// record i as itself when i < min(count, MaxCommandCount) and as (0,0,0) otherwise. A zero-group Dispatch does +// nothing. The caller then issues MaxCommandCount single-command calls without a count buffer over the rewritten +// records. The title's own buffers are only read by copies, as in rect_indirect_args.h. +#pragma once + +#include <d3d12.h> +#include <d3dcompiler.h> +#include <wrl/client.h> + +#include <mutex> +#include <memory> +#include <vector> + +namespace x2w_startup { + +// Scratch layout: the count word at byte 0, the title's records copied at byte `split_records_copy`, the rewritten +// 12-byte records at `rewritten_offset(...)`. +inline constexpr UINT64 split_records_copy = 16; + +inline constexpr char split_indirect_dispatch_hlsl[] = R"( +RWByteAddressBuffer scratch : register(u0); +cbuffer Split : register(b0) { uint max_count; uint stride; uint counted; uint rewritten; }; + +[numthreads(64, 1, 1)] +void split(uint i : SV_DispatchThreadID) { + if (i >= max_count) return; + uint count = counted != 0 ? scratch.Load(0) : max_count; + uint3 groups = i < count ? scratch.Load3(16 + i * stride) : uint3(0, 0, 0); + scratch.Store3(rewritten + 12 * i, groups); +} +)"; + +class SplitIndirectDispatch { +public: + // Bytes the title's records occupy: every record up to the maximum, the last one only its 12 Dispatch bytes. + static UINT64 record_span(UINT max_count, UINT stride) + { + return UINT64{max_count - 1} * stride + sizeof(D3D12_DISPATCH_ARGUMENTS); + } + static UINT64 rewritten_offset(UINT max_count, UINT stride) + { + return (split_records_copy + record_span(max_count, stride) + 15) & ~UINT64{15}; + } + // A fresh scratch buffer for one call (rests in COMMON). The caller keeps it alive with the recording. + static Microsoft::WRL::ComPtr<ID3D12Resource> make_scratch(ID3D12Device* device, UINT max_count, UINT stride) + { + Microsoft::WRL::ComPtr<ID3D12Resource> scratch; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = rewritten_offset(max_count, stride) + UINT64{max_count} * sizeof(D3D12_DISPATCH_ARGUMENTS); + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (!device || FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&scratch)))) + scratch.Reset(); + return scratch; + } + // Records the copies and the rewrite into `scratch` (from make_scratch, in COMMON) and leaves it in + // INDIRECT_ARGUMENT state. `records` (and `counts`, if given) must already be in a state that includes + // COPY_SOURCE. Returns false if the pass could not be set up (nothing was recorded then). The compute root + // signature and pipeline of the list are replaced: the caller restores them. `finish` puts the scratch back in COMMON. + bool rewrite(ID3D12GraphicsCommandList* list, ID3D12Resource* records, UINT64 records_offset, UINT max_count, UINT stride, + ID3D12Resource* counts, UINT64 count_offset, ID3D12Resource* scratch) + { + Microsoft::WRL::ComPtr<ID3D12Device> device; + if (!list || !records || !scratch || !max_count || stride < sizeof(D3D12_DISPATCH_ARGUMENTS) || + FAILED(list->GetDevice(IID_PPV_ARGS(&device)))) + return false; + Entry* entry = entry_for(device.Get()); + if (!entry) return false; + transition(list, scratch, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + if (counts) list->CopyBufferRegion(scratch, 0, counts, count_offset, sizeof(UINT)); + list->CopyBufferRegion(scratch, split_records_copy, records, records_offset, record_span(max_count, stride)); + transition(list, scratch, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetComputeRootSignature(entry->root.Get()); + list->SetPipelineState(entry->pipeline.Get()); + list->SetComputeRootUnorderedAccessView(0, scratch->GetGPUVirtualAddress()); + const UINT constants[4]{max_count, stride, counts ? 1u : 0u, static_cast<UINT>(rewritten_offset(max_count, stride))}; + list->SetComputeRoot32BitConstants(1, 4, constants, 0); + list->Dispatch((max_count + 63) / 64, 1, 1); + // As in rect_indirect_args.h: make the stores visible to the argument fetch without relying on the transition. + D3D12_RESOURCE_BARRIER written{}; + written.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + written.UAV.pResource = scratch; + list->ResourceBarrier(1, &written); + transition(list, scratch, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + return true; + } + static void finish(ID3D12GraphicsCommandList* list, ID3D12Resource* scratch) + { + transition(list, scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } + +private: + struct Entry { + ID3D12Device* device = nullptr; + Microsoft::WRL::ComPtr<ID3D12RootSignature> root; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pipeline; + }; + static void transition(ID3D12GraphicsCommandList* list, 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; + list->ResourceBarrier(1, &barrier); + } + // Root signature and pipeline per device. Entries are never freed: a rewrite may still be queued when its list is released. + Entry* entry_for(ID3D12Device* device) + { + std::lock_guard<std::mutex> guard(lock_); + for (auto& known : entries_) + if (known->device == device) return known->pipeline ? known.get() : nullptr; + auto entry = std::make_unique<Entry>(); + entry->device = device; + build(device, *entry); + entries_.push_back(std::move(entry)); + return entries_.back()->pipeline ? entries_.back().get() : nullptr; + } + static void build(ID3D12Device* device, Entry& entry) + { + Microsoft::WRL::ComPtr<ID3DBlob> code, error; + if (FAILED(D3DCompile(split_indirect_dispatch_hlsl, sizeof(split_indirect_dispatch_hlsl) - 1, "split_indirect_dispatch", + nullptr, nullptr, "split", "cs_5_0", 0, 0, &code, &error))) + return; + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + parameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameters[1].Constants = {0, 0, 4}; + parameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC desc{2, parameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + Microsoft::WRL::ComPtr<ID3DBlob> serialized; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &serialized, &error)) || + FAILED(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), + IID_PPV_ARGS(&entry.root)))) + return; + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline{}; + pipeline.pRootSignature = entry.root.Get(); + pipeline.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(device->CreateComputePipelineState(&pipeline, IID_PPV_ARGS(&entry.pipeline)))) entry.pipeline.Reset(); + } + std::mutex lock_; + std::vector<std::unique_ptr<Entry>> entries_; +}; + +// Never destroyed: a function-local static would release its root signatures and pipelines in the destructor during +// DLL detach, and on an RX 9070 XT (driver 32.0.32029.2010) the driver fail-fasts there (0xC0000409 in amdxc64, +// review of #2683). The entries are already kept for the life of the process (see entry_for). +// Lifetime boundary: this cache is process-owned and released only by process exit. Explicitly unloading and +// reloading d3d12_xs.dll in a live host is not a supported path: each load allocates a new cache and nothing tears +// the previous one down outside the loader lock, so its entries stay allocated. Supporting it needs that teardown +// and its own coverage. The kept root signature and pipeline each hold a reference to their device, so a cached +// device is never destroyed and its address cannot be reused by another device while the entry lives. +inline SplitIndirectDispatch& split_indirect_dispatch() +{ + static SplitIndirectDispatch* const splitter = new SplitIndirectDispatch; + return *splitter; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/tracy_new.cpp b/src/startup_stubs/tracy_new.cpp new file mode 100644 index 0000000000..046ea0d03a --- /dev/null +++ b/src/startup_stubs/tracy_new.cpp @@ -0,0 +1,35 @@ +// X2W_TRACY builds only (CMakeLists.txt adds this file to each instrumented DLL): the C++ heap of the DLL as a +// Tracy memory pool. The array, sized and nothrow forms of the runtime forward to these four. +#include "profile_zone.h" + +#include <cstdlib> +#include <malloc.h> +#include <new> + +void* operator new(std::size_t bytes) +{ + void* block = std::malloc(bytes ? bytes : 1); + if (!block) throw std::bad_alloc(); + X2W_ALLOC(block, bytes, X2W_TRACY_HEAP); + return block; +} + +void* operator new(std::size_t bytes, std::align_val_t alignment) +{ + void* block = _aligned_malloc(bytes ? bytes : 1, static_cast<std::size_t>(alignment)); + if (!block) throw std::bad_alloc(); + X2W_ALLOC(block, bytes, X2W_TRACY_HEAP); + return block; +} + +void operator delete(void* block) noexcept +{ + if (block) X2W_FREE(block, X2W_TRACY_HEAP); + std::free(block); +} + +void operator delete(void* block, std::align_val_t) noexcept +{ + if (block) X2W_FREE(block, X2W_TRACY_HEAP); + _aligned_free(block); +} diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index a4aca72ddf..658d0a5ecf 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -3,6 +3,8 @@ #include <d3d12.h> #include <wrl/client.h> +#include "startup_stubs/local_log.h" + #include <array> #include <bitset> #include <cstdint> @@ -18,6 +20,8 @@ constexpr UINT translated_sampler_count = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_ constexpr UINT translated_sampler_space = 1; constexpr UINT translated_sampler_fallback = translated_sampler_count - 1; constexpr UINT title_sampler_stride = sizeof(SamplerWords); +constexpr UINT translated_resheap_space = 2; +constexpr UINT max_translated_resheap = 1024; // comparison: the sampler is read through a SamplerComparisonState (manifest line smpc). SQ_IMG_SAMP_WORD0 bits // 14:12 hold SQ_TEX_DEPTH_COMPARE, which lists NEVER..ALWAYS in the order of D3D12_COMPARISON_FUNC minus one. @@ -110,20 +114,31 @@ inline std::vector<D3D12_STATIC_SAMPLER_DESC> decode_statics(const TranslatedSam return statics; } -inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } +// views: the SRVs and UAVs of the view table together. +inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } +// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.., then bounded resheap SRVs (space 2). inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, - const TranslatedSamplers& samplers, ID3D12RootSignature** out) + const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0, + bool input_assembler = false, UINT heap_srvs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameters[0].Constants.Num32BitValues = constants; - const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + // A compute program's outputs (u0..) follow its resources in the same table; bounded heap SRVs follow in space 2. + D3D12_DESCRIPTOR_RANGE view_ranges[3]{}; + UINT range_count = 0; + if (srvs) view_ranges[range_count++] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, srvs, 0, 0, 0}; + if (uavs) view_ranges[range_count++] = {D3D12_DESCRIPTOR_RANGE_TYPE_UAV, uavs, 0, 0, srvs}; + if (heap_srvs) { + view_ranges[range_count++] = { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV, heap_srvs, 0, translated_resheap_space, srvs + uavs}; + } parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameters[1].DescriptorTable = {1, &srv_range}; + parameters[1].DescriptorTable = {range_count, view_ranges}; const D3D12_DESCRIPTOR_RANGE sampler_range{ D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, translated_sampler_count, 0, translated_sampler_space, 0}; - UINT count = sampler_root_parameter(srvs); + UINT count = sampler_root_parameter(srvs + uavs + heap_srvs); if (samplers.heap) { parameters[count].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; parameters[count].DescriptorTable = {1, &sampler_range}; @@ -131,7 +146,8 @@ inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT } const auto statics = decode_statics(samplers); const D3D12_ROOT_SIGNATURE_DESC desc{count, parameters, static_cast<UINT>(statics.size()), statics.data(), - D3D12_ROOT_SIGNATURE_FLAG_NONE}; + input_assembler ? D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + : D3D12_ROOT_SIGNATURE_FLAG_NONE}; ComPtr<ID3DBlob> blob; HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(out)); @@ -173,10 +189,15 @@ inline SamplerSnapshot snapshot_samplers(SamplerSource source, bool reserved_fal const UINT room = static_cast<UINT>((page_size - address % page_size) / title_sampler_stride); const UINT available = snapshot.count - i; const UINT run = room ? (room < available ? room : available) : 1; - SIZE_T copied = 0; const SIZE_T bytes = SIZE_T{run} * title_sampler_stride; - if (ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(address), &snapshot.words[i], bytes, &copied) && - copied == bytes) { + // Outside xmem's run breaks, where a mapped page of the title's heap would read as missing. + bool whole = false; + x2w_local::outside_run_breaks([&] { + SIZE_T copied = 0; + whole = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast<const void*>(address), &snapshot.words[i], bytes, + &copied) && copied == bytes; + }); + if (whole) { for (UINT j = i; j < i + run; ++j) snapshot.readable.set(j); } else { // ReadProcessMemory can copy part of a record on failure. diff --git a/src/startup_stubs/typed_uav_load.h b/src/startup_stubs/typed_uav_load.h new file mode 100644 index 0000000000..c3bab6bc76 --- /dev/null +++ b/src/startup_stubs/typed_uav_load.h @@ -0,0 +1,14 @@ +#pragma once +#include <d3d12.h> + +// A typed UAV load of `format` is available when Support2 has UAV_TYPED_LOAD. +// R32_FLOAT, R32_UINT and R32_SINT do not need TypedUAVLoadAdditionalFormats. +// Every other format does. Returns the refusal reason, or nullptr when a load may proceed. +inline const char* typed_uav_load_refusal(DXGI_FORMAT format, unsigned support2, bool additional_formats) +{ + const bool core = format == DXGI_FORMAT_R32_FLOAT || format == DXGI_FORMAT_R32_UINT || + format == DXGI_FORMAT_R32_SINT; + if ((support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD) != 0 && (core || additional_formats)) + return nullptr; + return "format has no typed UAV load on this device"; +} diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h new file mode 100644 index 0000000000..121bbd6cf3 --- /dev/null +++ b/src/startup_stubs/upload_reservation.h @@ -0,0 +1,141 @@ +#pragma once + +#include <array> +#include <cstdint> +#include <limits> + +struct ID3D12Resource; + +inline constexpr std::uint64_t initial_upload_chunk_bytes = 16ull << 20; +inline constexpr std::uint64_t max_upload_ring_bytes = 256ull << 20; +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: chunks of the initial size, up to this total. +inline constexpr std::uint64_t max_released_upload_ring_bytes = 512ull << 20; +// Each allocation except possibly the final remainder is at least the initial size. +inline constexpr unsigned max_upload_chunks = max_released_upload_ring_bytes / initial_upload_chunk_bytes; +// Title input snapshots have a pool of their own, built like the ring (chunks reused once no recording can submit them and every +// queue that used them has finished), so draw and texture uploads cannot starve them and they cannot starve the ring. Its chunks +// are numbered after the ring's in the same recording mask: bit snapshot_chunk_base + i is chunk i of the snapshot pool. +inline constexpr std::uint64_t max_snapshot_pool_bytes = 128ull << 20; +inline constexpr unsigned max_snapshot_chunks = max_snapshot_pool_bytes / initial_upload_chunk_bytes; +inline constexpr unsigned snapshot_chunk_base = max_upload_chunks; +inline constexpr unsigned upload_chunk_bits = max_upload_chunks + max_snapshot_chunks; +using UploadChunkMask = std::uint64_t; +static_assert(upload_chunk_bits <= std::numeric_limits<UploadChunkMask>::digits); + +template <class Fence> +struct UploadQueue { + Fence* fence = nullptr; + std::uint64_t value = 0; + std::array<std::uint64_t, upload_chunk_bits> last_use{}; + + void submitted(UploadChunkMask chunks, bool signaled) + { + for (unsigned i = 0; chunks; ++i, chunks >>= 1) { + if ((chunks & 1) && last_use[i] != UINT64_MAX) + last_use[i] = signaled ? value : UINT64_MAX; + } + } + + bool completed(unsigned index) const + { + const auto target = last_use[index]; + if (!target) return true; + if (target == UINT64_MAX) return false; + const auto completed = fence->GetCompletedValue(); + return completed != UINT64_MAX && completed >= target; + } +}; + +struct UploadRingChunk { + ID3D12Resource* resource = nullptr; + unsigned char* mapped = nullptr; + std::uint64_t capacity = 0; + std::uint64_t used = 0; + std::uint64_t generation = 0; + unsigned recordings = 0; + + void hold(UploadChunkMask& recording, unsigned index) + { + const auto bit = UploadChunkMask{1} << index; + if (!(recording & bit)) { + recording |= bit; + ++recordings; + } + } +}; + +// Indices below snapshot_chunk_base belong to the upload ring. +template <class Chunk> +inline Chunk& upload_chunk_at(unsigned index, Chunk* chunks, Chunk* snapshot_chunks) +{ + return index < snapshot_chunk_base ? chunks[index] : snapshot_chunks[index - snapshot_chunk_base]; +} +inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks, UploadRingChunk* snapshot_chunks = nullptr) +{ + for (unsigned i = 0; recording; ++i, recording >>= 1) + if (recording & 1) --upload_chunk_at(i, chunks, snapshot_chunks).recordings; +} + +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: the chunks a closed list stopped holding when its submit was fenced, and +// each chunk's generation at that moment. The queue fence keeps those chunks from reuse until the GPU passes it. +struct ReleasedUploadChunks { + UploadChunkMask chunks = 0; + std::array<std::uint64_t, upload_chunk_bits> generation{}; +}; + +// Caller holds the lock, after the queue recorded a signalled fence for the recording's chunks. +inline void release_upload_chunks_at_submit(UploadChunkMask& recording, UploadRingChunk* chunks, + ReleasedUploadChunks& released, UploadRingChunk* snapshot_chunks = nullptr) +{ + for (unsigned i = 0; recording; ++i, recording >>= 1) { + if (!(recording & 1)) continue; + released.chunks |= UploadChunkMask{1} << i; + auto& chunk = upload_chunk_at(i, chunks, snapshot_chunks); + released.generation[i] = chunk.generation; + --chunk.recordings; + } +} + +// Caller holds the lock. A closed list submitted again before its Reset still reads the bytes it reserved: returns +// the released chunks that were not reused since, which the new submit must fence again, and sets `recycled` to +// those that were. +inline UploadChunkMask resubmitted_upload_chunks(const ReleasedUploadChunks& released, const UploadRingChunk* chunks, + UploadChunkMask& recycled, const UploadRingChunk* snapshot_chunks = nullptr) +{ + UploadChunkMask intact = 0; + recycled = 0; + for (unsigned i = 0; i < upload_chunk_bits; ++i) { + const auto bit = UploadChunkMask{1} << i; + if (!(released.chunks & bit)) continue; + (upload_chunk_at(i, chunks, snapshot_chunks).generation == released.generation[i] ? intact : recycled) |= bit; + } + return intact; +} + +struct UploadReservation { + unsigned char* mapped = nullptr; + std::uint64_t offset = 0; + ID3D12Resource* resource = nullptr; + std::uint64_t generation = 0; +}; + +// Caller holds the lock. A successful reservation owns previously unused bytes. +inline UploadReservation reserve_upload_chunk(UploadRingChunk& chunk, std::uint64_t rounded) +{ + if (chunk.used > chunk.capacity || rounded > chunk.capacity - chunk.used) return {}; + const auto start = chunk.used; + chunk.used += rounded; + return {chunk.mapped + start, start, chunk.resource, chunk.generation}; +} + +// Called only after the unused tails and the capacity budget have been tried. +template <class Queues> +UploadReservation reuse_upload_chunk(UploadRingChunk& chunk, unsigned index, std::uint64_t rounded, const Queues& queues) +{ + if (rounded > chunk.capacity || chunk.recordings) return {}; + for (const auto& queue : queues) + if (!queue.second.completed(index)) return {}; + chunk.used = 0; + ++chunk.generation; + return reserve_upload_chunk(chunk, rounded); +} diff --git a/src/startup_stubs/view_dimension.h b/src/startup_stubs/view_dimension.h new file mode 100644 index 0000000000..4c54085361 --- /dev/null +++ b/src/startup_stubs/view_dimension.h @@ -0,0 +1,105 @@ +// Experimental (docs/startup-runtime.md): whether a view description's ViewDimension suits the +// resource it is made on. Desktop D3D12 removes the device (DXGI_ERROR_INVALID_CALL, debug-layer +// message "The ViewDimension in the View Desc is incompatible with the type of the Resource") +// instead of failing the call, so the stand-in checks first and skips such a view with a log. +// Values are the public d3d12.h enumerations. Pure, no Windows calls, so a control can check it. +#pragma once + +namespace x2w_view_dimension { + +enum ResourceDimension : unsigned { unknown = 0, buffer = 1, texture1d = 2, texture2d = 3, texture3d = 4 }; + +// Which resource dimension one view dimension needs, by the device slot that makes the view +// (18 shader resource, 19 unordered access, 20 render target, 21 depth stencil). unknown when the +// view dimension is not one of that view type's values (or is 0); such a view is not judged here. +inline unsigned needed(int slot, unsigned view_dimension) noexcept +{ + switch (slot) { + case 18: // D3D12_SRV_DIMENSION + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: case 9: case 10: return texture2d; // 2D, arrays, MS, cube, cube array + case 8: return texture3d; + default: return unknown; // 11 is a raytracing structure, made with a null resource + } + case 19: // D3D12_UAV_DIMENSION + case 20: // D3D12_RTV_DIMENSION (same numbering) + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: return texture2d; + case 8: return texture3d; + default: return unknown; + } + case 21: // D3D12_DSV_DIMENSION + switch (view_dimension) { + case 1: case 2: return texture1d; + case 3: case 4: case 5: case 6: return texture2d; + default: return unknown; + } + default: + return unknown; + } +} + +// False only when the view dimension names a resource dimension other than the resource's. +inline bool fits(int slot, unsigned view_dimension, unsigned resource_dimension) noexcept +{ + const unsigned need = needed(slot, view_dimension); + return need == unknown || need == resource_dimension; +} + +// A description with ViewDimension 0 (UNKNOWN) is always refused by desktop D3D12. Measured: a +// title module makes one on a two-dimensional RGBA8 texture (format R32G32B32A32_FLOAT, default +// component mapping). The stand-in makes the resource's default view instead (a null description), +// which desktop allows only for a texture with a typed format, and for a shader resource view not +// a depth format. Whether the console gives UNKNOWN that meaning is a hypothesis. +inline bool typeless(unsigned format) noexcept +{ + switch (format) { + case 1: case 5: case 9: case 15: case 19: case 23: case 27: case 33: case 39: case 44: case 48: case 53: case 60: + case 70: case 73: case 76: case 79: case 82: case 90: case 92: case 94: case 97: + return true; + default: + return false; + } +} + +inline bool depth_format(unsigned format) noexcept { return format == 20 || format == 40 || format == 45 || format == 55; } + +// Which slots may get the default view. It is measured only for shader resource views (slot 18) of +// typed textures, so that is the default. The default view also drops the requested format and +// component mapping, so for the other view types it stays an explicit experiment +// (X2W_D3D12_VIEW_DEFAULTS=all). off: every unknown-dimension view is skipped. +enum class DefaultViews : unsigned { off, srv, all }; + +// X2W_D3D12_VIEW_DEFAULTS: "all" or "off"; anything else, or unset, is srv. +inline DefaultViews default_views_mode(const char* value) noexcept +{ + if (!value) return DefaultViews::srv; + if (value[0] == 'a' && value[1] == 'l' && value[2] == 'l' && value[3] == 0) return DefaultViews::all; + if (value[0] == 'o' && value[1] == 'f' && value[2] == 'f' && value[3] == 0) return DefaultViews::off; + return DefaultViews::srv; +} + +inline bool default_view_allowed(int slot, unsigned resource_dimension, unsigned resource_format, DefaultViews mode) noexcept +{ + if (slot < 18 || slot > 21) return false; + if (mode == DefaultViews::off || (mode == DefaultViews::srv && slot != 18)) return false; + if (resource_dimension == unknown || resource_dimension == buffer) return false; + if (resource_format == 0 || typeless(resource_format)) return false; + if (slot == 18 && depth_format(resource_format)) return false; + return true; +} + +// The dimension of the null SRV that replaces a refused one in its destination slot, so that the slot +// cannot keep the view it held before (a skipped call would otherwise leave that descriptor in place, +// bindable and copyable, after the slot's record has dropped its resource). The requested dimension +// when it is a texture dimension (2 to 10), else texture 2D (4). +inline unsigned refused_srv_null_dimension(unsigned requested) noexcept +{ + return requested >= 2 && requested <= 10 ? requested : 4; +} + +} // namespace x2w_view_dimension diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index d3cbc51986..8232d2bfcb 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -4,7 +4,10 @@ #define X2W_TRAP_MODULE_ID 3 #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/audio_telemetry.h" #include <timeapi.h> +#include <algorithm> +#include <cstdlib> #include <cstring> #include <new> #ifdef X2W_HAVE_OPUS @@ -21,12 +24,14 @@ // X2W_XAPU_TYPED_COMPLETIONS=1, also echoes the command type at +0 and slot at +4. // XApuEnqueueCommand(handle, command*, ...) -> HRESULT; reads 32-bit type at +0 and slot at +4. // XApuDisconnect(handle) -// Optional (X2W_WITH_OPUS build, typed completions on): a type 3 command decodes one Opus packet with -// libopus and completes with the decoded byte count at result +0x34. Command fields as one title fills -// them: +0x1C sample rate (float), +0x24 frames, +0x28 packet bytes, +0x2C packet pointer, +0x34 output -// bytes (frames * channels * 4), +0x38 output pointer (interleaved float). Type 2 frees the slot's -// decoder and type 5 resets it. A command with no packet (null pointer, 0 bytes) completes with 0 bytes. +// Optional Opus decoding with typed completions: a process-1 connection uses type 1 to select the +// stream's channels. Type 3 decodes a packet, skips the leading frames at +0x20, and returns the +// window that fits the caller's count and capacity. Connection option 4 requests planar stereo. +// Older untyped-format fixtures describe their decode rate and buffer layout on the type 3 command. +// Type 2 frees the slot's decoder and type 5 resets it. A command with no packet completes with 0 bytes. // A refused decode returns an error, queues nothing and leaves the output untouched. +// The same build keeps bounded counters for decoded packets, dequeued decoded completions and +// refusals by reason, and writes one stable summary at the last disconnect and at process exit. namespace { using u64 = std::uint64_t; constexpr long hr_ok = 0; @@ -38,7 +43,7 @@ constexpr long hr_fail = static_cast<long>(0x80004005); // E_FAIL constexpr long hr_pending_results = static_cast<long>(0x8AC81001); // XAPU_E_PENDING_RESULTS constexpr std::size_t command_header_size = 8; constexpr std::size_t result_size = 0x58; -constexpr std::size_t max_queue_entries = 16384; // 192 KiB cap per connection for undrained commands +constexpr std::size_t max_queue_entries = 16384; constexpr std::uint32_t max_buffer_bytes = 64u << 20; // sanity cap against a bad size, not a measured limit bool permissive() noexcept { return x2w_local::env_on("X2W_AUDIO_PERMISSIVE"); } @@ -48,6 +53,13 @@ struct QueueEntry { std::uint32_t type = 0; std::uint32_t slot = 0; std::uint32_t value = 0; // typed result +0x34: decoded bytes of a type 3 command +#ifdef X2W_HAVE_OPUS + bool decoded = false; // this result came from a successful libopus call + bool stream_command = false; + unsigned char command_tag[16]{}; // sequence, options, caller context + std::uint32_t frames = 0, input_bytes = 0; + u64 input = 0, output = 0; +#endif }; #ifdef X2W_HAVE_OPUS @@ -72,6 +84,8 @@ struct Connection { void* buffer = nullptr; // returned in output +0 #ifdef X2W_HAVE_OPUS SlotDecoder decoders[max_slots]; + bool opus_streams = false; + std::uint32_t options = 0; #endif }; @@ -80,6 +94,64 @@ Connection* connections = nullptr; u64 next_handle = 0x5841500000000001ULL; bool timer_active = false; +#ifdef X2W_HAVE_OPUS +// Telemetry for the optional decode path. It starts with the first readable type-3 command, so a +// default run with typed completions off reads and writes nothing here. +x2w_audio::OpusCounters opus_counts; +std::atomic<bool> opus_counters_on{false}; +SRWLOCK opus_summary_lock = SRWLOCK_INIT; +x2w_audio::OpusCounterSnapshot reported_opus_counts{}; + +bool same_opus_counts(const x2w_audio::OpusCounterSnapshot& a, const x2w_audio::OpusCounterSnapshot& b) noexcept +{ + return a.type3_commands == b.type3_commands && a.packets_decoded == b.packets_decoded && + a.decoded_completions == b.decoded_completions && a.refused_header == b.refused_header && + a.refused_short_command == b.refused_short_command && + a.refused_unknown_handle == b.refused_unknown_handle && + a.refused_queue_full == b.refused_queue_full && + a.refused_invalid_argument == b.refused_invalid_argument && + a.refused_opus_error == b.refused_opus_error && a.refused_capacity == b.refused_capacity && + a.refused_out_of_memory == b.refused_out_of_memory; +} + +// Writes the totals since the previous summary, when they moved. Called at the last disconnect and +// from atexit, so a run that never disconnects still ends with one line on stderr and X2W_TRAP_LOG. +void log_opus_summary() noexcept +{ + if (!opus_counters_on.load(std::memory_order_relaxed)) return; + const x2w_audio::OpusCounterSnapshot now = x2w_audio::snapshot(opus_counts); + AcquireSRWLockExclusive(&opus_summary_lock); + const bool changed = !same_opus_counts(now, reported_opus_counts); + if (changed) reported_opus_counts = now; + ReleaseSRWLockExclusive(&opus_summary_lock); + if (!changed || (!now.type3_commands && !x2w_audio::refused_total(now))) return; + x2w_local::logf("x2w-audio XApu opus summary: type3=%llu packets=%llu completions=%llu refusals=%llu " + "invalid_argument=%llu opus_error=%llu capacity=%llu queue_full=%llu short_command=%llu " + "unknown_handle=%llu out_of_memory=%llu header=%llu", + static_cast<unsigned long long>(now.type3_commands), + static_cast<unsigned long long>(now.packets_decoded), + static_cast<unsigned long long>(now.decoded_completions), + static_cast<unsigned long long>(x2w_audio::refused_total(now)), + static_cast<unsigned long long>(now.refused_invalid_argument), + static_cast<unsigned long long>(now.refused_opus_error), + static_cast<unsigned long long>(now.refused_capacity), + static_cast<unsigned long long>(now.refused_queue_full), + static_cast<unsigned long long>(now.refused_short_command), + static_cast<unsigned long long>(now.refused_unknown_handle), + static_cast<unsigned long long>(now.refused_out_of_memory), + static_cast<unsigned long long>(now.refused_header)); +} + +void start_opus_counters() noexcept +{ + bool expected = false; + if (!opus_counters_on.compare_exchange_strong(expected, true, std::memory_order_relaxed)) return; + std::atexit(log_opus_summary); +} + +enum class DecodeRefusal { none, invalid_argument, opus_error, capacity, out_of_memory }; +#endif + // Makes room for one more entry, so a following place_result cannot fail. bool reserve_result(Connection& conn) noexcept { @@ -146,45 +218,63 @@ void hex(const void* data, std::size_t bytes, char* out, std::size_t size) // Frees (close) or resets (reset) a slot's decoder. Called with connection_lock held. void drop_decoder(Connection& conn, std::uint32_t slot, bool destroy) noexcept { - if (slot >= max_slots || !conn.decoders[slot].decoder) return; + if (slot >= max_slots) return; SlotDecoder& d = conn.decoders[slot]; if (destroy) { - opus_decoder_destroy(d.decoder); + if (d.decoder) opus_decoder_destroy(d.decoder); d = SlotDecoder{}; - } else { + } else if (d.decoder) { opus_decoder_ctl(d.decoder, OPUS_RESET_STATE); } } // Decodes the packet of a type 3 command into a scratch buffer, so a refusal never touches the -// caller's output. On S_OK, *pcm holds `bytes` of interleaved float for *dest. Called with -// connection_lock held, which also guards the scratch buffer. -long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& bytes, const float** pcm, void** dest) noexcept +// caller's output. On S_OK, *pcm holds entry.value bytes of float PCM for *dest. `decoded_packet` +// distinguishes a libopus decode from the no-packet completion, and `refusal` names the first check +// that refused the command. Called with connection_lock held, which also guards the scratch buffer. +long decode_packet(Connection& conn, const unsigned char* c, QueueEntry& entry, const float** pcm, void** dest, + bool& decoded_packet, DecodeRefusal& refusal) noexcept { static float scratch[max_frames * 2]; + static float planar[max_frames * 2]; + decoded_packet = false; + refusal = DecodeRefusal::none; std::uint32_t slot = 0, frames = 0, packet_bytes = 0, out_bytes = 0; + std::uint32_t first_frame = 0; float rate_f = 0; u64 packet = 0, out = 0; std::memcpy(&slot, c + 4, 4); std::memcpy(&rate_f, c + 0x1C, 4); + std::memcpy(&first_frame, c + 0x20, 4); std::memcpy(&frames, c + 0x24, 4); std::memcpy(&packet_bytes, c + 0x28, 4); std::memcpy(&packet, c + 0x2C, 8); std::memcpy(&out_bytes, c + 0x34, 4); std::memcpy(&out, c + 0x38, 8); + if (conn.opus_streams) { + entry.input = packet; + entry.input_bytes = packet_bytes; + entry.output = out; + } if (!packet && !packet_bytes) { // no packet: complete with 0 bytes, as without libopus - bytes = 0; return hr_ok; } - const int rate = rate_f == 8000.0f ? 8000 : rate_f == 12000.0f ? 12000 : rate_f == 16000.0f ? 16000 + if (slot >= max_slots) { + refusal = DecodeRefusal::invalid_argument; + return hr_invalid_arg; + } + SlotDecoder& d = conn.decoders[slot]; + const int rate = conn.opus_streams ? 48000 : rate_f == 8000.0f ? 8000 : rate_f == 12000.0f ? 12000 : rate_f == 16000.0f ? 16000 : rate_f == 24000.0f ? 24000 : rate_f == 48000.0f ? 48000 : 0; - const std::uint32_t channels = frames && frames <= max_frames && out_bytes % (frames * 4) == 0 ? out_bytes / (frames * 4) : 0; - if (slot >= max_slots || !rate || (channels != 1 && channels != 2) || packet_bytes == 0 || packet_bytes > max_packet_bytes || + const std::uint32_t channels = conn.opus_streams ? d.channels : + frames && frames <= max_frames && out_bytes % (frames * 4) == 0 ? out_bytes / (frames * 4) : 0; + if (!rate || (channels != 1 && channels != 2) || packet_bytes == 0 || packet_bytes > max_packet_bytes || !x2w_local::readable(reinterpret_cast<const void*>(packet), packet_bytes) || - !x2w_local::writable(reinterpret_cast<const void*>(out), out_bytes)) + !x2w_local::writable(reinterpret_cast<const void*>(out), out_bytes)) { + refusal = DecodeRefusal::invalid_argument; return hr_invalid_arg; + } // A new rate or channel count gets a new decoder, which replaces the slot's only after a good decode. - SlotDecoder& d = conn.decoders[slot]; OpusDecoder* decoder = d.decoder; const bool fresh = !decoder || d.channels != static_cast<int>(channels) || d.rate != rate; if (fresh) { @@ -192,13 +282,15 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte decoder = opus_decoder_create(rate, static_cast<int>(channels), &error); if (!decoder || error != OPUS_OK) { if (decoder) opus_decoder_destroy(decoder); + refusal = DecodeRefusal::out_of_memory; return hr_out_of_memory; } } const int decoded = opus_decode_float(decoder, reinterpret_cast<const unsigned char*>(packet), - static_cast<opus_int32>(packet_bytes), scratch, static_cast<int>(frames), 0); + static_cast<opus_int32>(packet_bytes), scratch, conn.opus_streams ? max_frames : static_cast<int>(frames), 0); if (decoded < 0) { if (fresh) opus_decoder_destroy(decoder); + refusal = decoded == OPUS_BUFFER_TOO_SMALL ? DecodeRefusal::capacity : DecodeRefusal::opus_error; static LONG errors; if (x2w_local::first_calls(errors, 8)) x2w_local::logf("x2w-audio XApu decode slot=%u bytes=%u -> opus error %d", slot, packet_bytes, decoded); @@ -208,12 +300,94 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte if (d.decoder) opus_decoder_destroy(d.decoder); d = SlotDecoder{decoder, static_cast<int>(channels), rate}; } - bytes = static_cast<std::uint32_t>(decoded) * channels * 4u; - *pcm = scratch; + const auto skipped = conn.opus_streams ? (std::min)(first_frame, static_cast<std::uint32_t>(decoded)) : 0u; + entry.frames = (std::min)({static_cast<std::uint32_t>(decoded) - skipped, frames, out_bytes / (4u * channels)}); + entry.value = entry.frames * channels * 4u; + const float* kept = scratch + skipped * channels; + if (conn.opus_streams && (conn.options & 4u) && channels == 2) { + for (std::uint32_t frame = 0; frame < entry.frames; ++frame) { + planar[frame] = kept[2 * frame]; + planar[entry.frames + frame] = kept[2 * frame + 1]; + } + kept = planar; + } + decoded_packet = true; + *pcm = kept; *dest = reinterpret_cast<void*>(out); return hr_ok; } #endif + +// Activity counter (#1145), off unless X2W_AUDIO_ACTIVITY=1: every XApuEnqueueCommand call, counted by command class, +// taken as the first UINT32 of the command (a stand-in convention, like the result type above), with no cap. Classes +// 0..15 are counted one by one and larger ones together; a command that cannot be read and a call with an unknown +// handle are counted apart. commands= in the line is the classes plus the unreadable ones; rejected calls are not in +// it. There is no thread: a counted call (or x2w_xapu_command_counts) at least a second after the previous line (or the +// first such call) writes the next line, with the counts since that line, if a count moved; until then the counts wait +// for a later call. Nothing here runs outside a call into this DLL. Off, nothing here runs: no read of the command, no +// line. +constexpr unsigned command_classes = 16; +struct CommandCounts { + u64 by_class[command_classes + 1]; // the last entry: every larger class + u64 unreadable, rejected; +}; +SRWLOCK count_lock = SRWLOCK_INIT; // guards the four below +CommandCounts command_counts, reported; // the counts now and at the last line +ULONGLONG last_line; // GetTickCount64 of the last line written, or of the first counted call or counter-on export call +bool counting_started; + +bool activity_on() noexcept { return x2w_local::env_on("X2W_AUDIO_ACTIVITY"); } + +// If the last line is at least a second old and a count moved, writes the next line into text and returns true. +// Hold count_lock exclusively; log the text after releasing it. +bool poll_locked(char (&text)[512]) noexcept +{ + const ULONGLONG tick = GetTickCount64(); + if (!counting_started) { + counting_started = true; + last_line = tick; + } + const CommandCounts& now = command_counts; + if (tick - last_line < 1000 || !std::memcmp(&now, &reported, sizeof(now))) return false; + last_line = tick; + char classes[320] = ""; + std::size_t used = 0; + u64 commands = now.unreadable - reported.unreadable; + for (unsigned c = 0; c <= command_classes; ++c) { + const u64 n = now.by_class[c] - reported.by_class[c]; + commands += n; + if (!n || used >= sizeof(classes)) continue; + used += static_cast<std::size_t>(c < command_classes ? std::snprintf(classes + used, sizeof(classes) - used, " %u=%llu", c, n) + : std::snprintf(classes + used, sizeof(classes) - used, " other=%llu", n)); + } + std::snprintf(text, sizeof(text), + "x2w-audio xapu-activity t=%.1f s: commands=%llu by class%s unreadable=%llu; rejected=%llu (not in commands)", + x2w_local::process_seconds(), commands, classes, now.unreadable - reported.unreadable, + now.rejected - reported.rejected); + reported = now; + return true; +} + +// Counts one XApuEnqueueCommand call; the caller's last error is kept. +void count_command(long hr, const void* command) noexcept +{ + if (!activity_on()) return; + const DWORD error = GetLastError(); + const bool readable = hr != hr_handle && x2w_local::readable(command, sizeof(std::uint32_t)); + const std::uint32_t command_class = readable ? *static_cast<const std::uint32_t*>(command) : 0; + char text[512]; + AcquireSRWLockExclusive(&count_lock); + if (hr == hr_handle) + ++command_counts.rejected; + else if (!readable) + ++command_counts.unreadable; + else + ++command_counts.by_class[command_class < command_classes ? command_class : command_classes]; + const bool line = poll_locked(text); + ReleaseSRWLockExclusive(&count_lock); + if (line) x2w_local::logf("%s", text); + SetLastError(error); +} } // namespace extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r9) @@ -242,6 +416,19 @@ extern "C" __declspec(noinline) long XApuConnect(u64 rcx, u64 rdx, u64 r8, u64 r return hr_out_of_memory; } conn->buffer = buffer; +#ifdef X2W_HAVE_OPUS + std::uint32_t process = 0; + std::memcpy(&process, reinterpret_cast<const void*>(rcx), 4); + if (process == 1 && typed_completions()) { + if (!x2w_local::readable(reinterpret_cast<const void*>(rcx), 24)) { + VirtualFree(buffer, 0, MEM_RELEASE); + delete conn; + return hr_pointer; + } + conn->opus_streams = true; + std::memcpy(&conn->options, reinterpret_cast<const unsigned char*>(rcx) + 20, 4); + } +#endif AcquireSRWLockExclusive(&connection_lock); const u64 handle = next_handle++; if (next_handle == 0) next_handle = 0x5841500000000001ULL; @@ -282,20 +469,29 @@ extern "C" __declspec(noinline) long XApuDequeueResult(u64 rcx, u64 rdx, u64 r8, { if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuDequeueResult", 1, rcx, rdx, r8, r9, _ReturnAddress()); - if (!rdx || !x2w_local::writable(reinterpret_cast<const void*>(rdx), result_size)) { + QueueEntry entry{}; + AcquireSRWLockExclusive(&connection_lock); + Connection* conn = find_connection(rcx); + auto size = result_size; +#ifdef X2W_HAVE_OPUS + if (conn && conn->opus_streams) size = 0x50; // the packed stream result ends after its input pointer +#endif + if (!rdx || !x2w_local::writable(reinterpret_cast<const void*>(rdx), size)) { + ReleaseSRWLockExclusive(&connection_lock); static LONG bad_out_calls; if (x2w_local::first_calls(bad_out_calls, 2)) x2w_local::logf("x2w-audio XApuDequeueResult handle=0x%llx -> E_POINTER", rcx); return hr_pointer; } - QueueEntry entry{}; - AcquireSRWLockExclusive(&connection_lock); - Connection* conn = find_connection(rcx); long hr = hr_handle; if (conn) { if (conn->count > 0) { entry = pop_result(*conn); hr = hr_ok; +#ifdef X2W_HAVE_OPUS + if (entry.decoded && typed_completions()) + x2w_audio::saturating_add(opus_counts.decoded_completions); +#endif } else { hr = hr_pending_results; } @@ -303,11 +499,22 @@ extern "C" __declspec(noinline) long XApuDequeueResult(u64 rcx, u64 rdx, u64 r8, ReleaseSRWLockExclusive(&connection_lock); if (hr == hr_ok) { auto* out = reinterpret_cast<unsigned char*>(rdx); - std::memset(out, 0, result_size); + std::memset(out, 0, size); if (typed_completions()) { std::memcpy(out, &entry.type, sizeof(entry.type)); std::memcpy(out + 4, &entry.slot, sizeof(entry.slot)); std::memcpy(out + 0x34, &entry.value, sizeof(entry.value)); +#ifdef X2W_HAVE_OPUS + if (entry.stream_command) { + const float pitch = 1.0f; + std::memcpy(out + 0x08, entry.command_tag, sizeof(entry.command_tag)); + std::memcpy(out + 0x30, &entry.frames, 4); + std::memcpy(out + 0x38, &entry.output, 8); + std::memcpy(out + 0x40, &pitch, 4); + std::memcpy(out + 0x44, &entry.input_bytes, 4); + std::memcpy(out + 0x48, &entry.input, 8); + } +#endif } } static LONG calls; @@ -321,9 +528,16 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuEnqueueCommand", 3, rcx, rdx, r8, r9, _ReturnAddress()); if (!rdx || !x2w_local::readable(reinterpret_cast<const void*>(rdx), command_header_size)) { +#ifdef X2W_HAVE_OPUS + if (typed_completions()) { + start_opus_counters(); + x2w_audio::saturating_add(opus_counts.refused_header); + } +#endif static LONG bad_cmd_calls; if (x2w_local::first_calls(bad_cmd_calls, 2)) x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx -> E_POINTER", rcx); + count_command(hr_pointer, nullptr); // a header this call refuses as unreadable counts as unreadable return hr_pointer; } QueueEntry entry{}; @@ -331,8 +545,17 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 std::memcpy(&entry.slot, reinterpret_cast<const unsigned char*>(rdx) + 4, sizeof(entry.slot)); #ifdef X2W_HAVE_OPUS const bool decode = entry.type == 3 && typed_completions(); + DecodeRefusal refusal = DecodeRefusal::none; + bool decoded_packet = false; + bool queue_refused = false; + if (decode) { + start_opus_counters(); + x2w_audio::saturating_add(opus_counts.type3_commands); + } if (decode && !x2w_local::readable(reinterpret_cast<const void*>(rdx), decode_command_size)) { + x2w_audio::saturating_add(opus_counts.refused_short_command); x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx short decode command -> E_POINTER", rcx); + count_command(hr_pointer, reinterpret_cast<const void*>(rdx)); // its header was read: counted as class 3 return hr_pointer; } #endif @@ -345,12 +568,43 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 void* dest = nullptr; // Refuse a full queue before touching any decoder state. hr = reserve_result(*conn) ? hr_ok : hr_out_of_memory; + queue_refused = hr != hr_ok; + if (hr == hr_ok && conn->opus_streams && typed_completions()) { + const auto* command = reinterpret_cast<const unsigned char*>(rdx); + if (!x2w_local::readable(command, entry.type == 1 ? 28 : 24)) { + hr = hr_pointer; + } else if (entry.slot >= max_slots) { + refusal = DecodeRefusal::invalid_argument; + hr = hr_invalid_arg; + } else { + entry.stream_command = true; + std::memcpy(entry.command_tag, command + 8, sizeof(entry.command_tag)); + if (entry.type == 1) { + std::uint32_t channels = 0; + std::memcpy(&channels, command + 24, 4); + if (channels != 1 && channels != 2) { + refusal = DecodeRefusal::invalid_argument; + hr = hr_invalid_arg; + } else if (conn->decoders[entry.slot].channels) { + refusal = DecodeRefusal::invalid_argument; + hr = hr_invalid_arg; + } else { + conn->decoders[entry.slot].channels = static_cast<int>(channels); + } + } + } + } if (hr == hr_ok && decode) { - hr = decode_packet(*conn, reinterpret_cast<const unsigned char*>(rdx), entry.value, &pcm, &dest); + hr = decode_packet(*conn, reinterpret_cast<const unsigned char*>(rdx), entry, &pcm, &dest, + decoded_packet, refusal); } else if (hr == hr_ok && (entry.type == 2 || entry.type == 5)) { drop_decoder(*conn, entry.slot, entry.type == 2); } if (hr == hr_ok) { + if (decode) { + entry.decoded = decoded_packet; + if (decoded_packet) x2w_audio::saturating_add(opus_counts.packets_decoded); + } place_result(*conn, entry); if (pcm) std::memcpy(dest, pcm, entry.value); } @@ -359,6 +613,23 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 #endif } ReleaseSRWLockExclusive(&connection_lock); +#ifdef X2W_HAVE_OPUS + if (decode && hr != hr_ok) { + if (!conn) + x2w_audio::saturating_add(opus_counts.refused_unknown_handle); + else if (queue_refused) + x2w_audio::saturating_add(opus_counts.refused_queue_full); + else if (refusal == DecodeRefusal::invalid_argument) + x2w_audio::saturating_add(opus_counts.refused_invalid_argument); + else if (refusal == DecodeRefusal::opus_error) + x2w_audio::saturating_add(opus_counts.refused_opus_error); + else if (refusal == DecodeRefusal::capacity) + x2w_audio::saturating_add(opus_counts.refused_capacity); + else if (refusal == DecodeRefusal::out_of_memory) + x2w_audio::saturating_add(opus_counts.refused_out_of_memory); + } +#endif + count_command(hr, reinterpret_cast<const void*>(rdx)); static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; @@ -379,6 +650,9 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 while (*slot && (*slot)->handle != rcx) slot = &(*slot)->next; Connection* conn = *slot; if (conn) *slot = conn->next; +#ifdef X2W_HAVE_OPUS + const bool last_connection = conn && !connections; +#endif if (conn && !connections && timer_active) { timeEndPeriod(1); timer_active = false; @@ -395,5 +669,31 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 delete[] conn->entries; delete conn; x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); +#ifdef X2W_HAVE_OPUS + if (last_connection) log_opus_summary(); +#endif return hr_ok; } + +// Experimental export for the source-built check (tests/startup_acphal_xma_activity.cpp): writes the line if one is +// due, as a counted call does, and the totals since start to out[0..18]: commands of classes 0..15, of larger classes, +// unreadable commands, calls with an unknown handle. With X2W_AUDIO_ACTIVITY off it writes zeros and returns FALSE. +extern "C" BOOL WINAPI x2w_xapu_command_counts(ULONGLONG* out) +{ + if (!out) return FALSE; + const bool on = activity_on(); + CommandCounts now{}; + char text[512]; + bool line = false; + if (on) { + AcquireSRWLockExclusive(&count_lock); + line = poll_locked(text); + now = command_counts; + ReleaseSRWLockExclusive(&count_lock); + } + if (line) x2w_local::logf("%s", text); + for (unsigned c = 0; c <= command_classes; ++c) out[c] = now.by_class[c]; + out[command_classes + 1] = now.unreadable; + out[command_classes + 2] = now.rejected; + return on; +} diff --git a/src/startup_stubs/xapu.def b/src/startup_stubs/xapu.def index 16136a6e78..548adb4c96 100644 --- a/src/startup_stubs/xapu.def +++ b/src/startup_stubs/xapu.def @@ -5,3 +5,4 @@ EXPORTS XApuDisconnect XApuEnqueueCommand XApuGetResultCount + x2w_xapu_command_counts diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 50d543a16e..7434b69ec4 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -10,6 +10,7 @@ #include "startup_stubs/trap.h" #include "startup_stubs/profile_zone.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/resident_pages.h" #include "startup_stubs/inflate.h" #include "startup_stubs/dstorage_error_record.h" #include "startup_stubs/dstorage_file_read.h" @@ -75,6 +76,24 @@ struct QueueObject : Object { HANDLE error_event = nullptr; }; +// Live stand-in objects by kind, and running queue workers. The lifetime fixture reads them through +// x2w_xcrdapi_live_objects and x2w_xcrdapi_live_workers to prove that a final Release frees the +// object and that the queue's worker has left (#2788). +LONG live_by_kind[4]; +LONG live_workers; + +// Test-only mutant (#2788): X2W_TEST_XCRDAPI_LIFETIME_MUTANT=naive deletes at final Release without +// stopping the worker or retaining the objects a queue entry uses. The fixture must reject it. +bool naive_lifetime_mutant() noexcept +{ + static const bool naive = [] { + char text[16]; + const DWORD length = GetEnvironmentVariableA("X2W_TEST_XCRDAPI_LIFETIME_MUTANT", text, sizeof(text)); + return length == 5 && std::memcmp(text, "naive", 5) == 0; + }(); + return naive; +} + // A queue entry as enqueued: a request (its 0x48 bytes copied, and a snapshot of its destination page // tokens), a status entry or a fence signal. Entries run in order on the queue's worker after Submit, // like DirectStorage; a destination page token that was 0 at enqueue is read again at the entry's turn @@ -91,6 +110,7 @@ struct Entry { std::unique_ptr<ULONG_PTR[]> tokens; std::size_t token_count = 0; Object* array; + Object* source; // request: the file the entry reads, retained while the entry is pending unsigned index; void* fence; u64 value; @@ -115,6 +135,10 @@ struct QueueWork { struct Unrecorded* deferred_head = nullptr; // snapshot of unrecorded entries, in order; guarded by mutex struct Unrecorded* deferred_tail = nullptr; bool completing = false; // a thread owns completion of snapshot entries, so they stay in order; guarded by mutex + bool stopping = false; // final Release asked the worker to leave; guarded by mutex + bool destroy_on_worker = false; // the final Release ran on the worker itself; guarded by mutex + HANDLE thread = nullptr; // kept for the join; closed by the releasing thread, guarded by the setup mutex + DWORD thread_id = 0; // guarded by the setup mutex std::condition_variable drained; // signaled when the worker finishes an entry u64 submitted_total = 0; // entries ever moved to `submitted`, guarded by mutex u64 finished_total = 0; // entries the worker has finished running, guarded by mutex @@ -153,29 +177,52 @@ static bool has_zlib_header(const unsigned char* bytes, std::size_t size) } // True when every byte of [destination, destination + bytes) is committed and writable, with no guard or -// no-access page in between. Walks the regions one VirtualQuery at a time, so a destination that spans -// regions of different protection is judged page by page. Nothing is written or touched. +// no-access page in between. Nothing is written or touched. Resident read-write pages are accepted from +// their working-set attributes; any other page (not resident, copy-on-write, guard, no access) sends the +// destination to the region walk (x2w_local::committed_writable), which judges it region by region. That walk +// is slow on the title's large regions: each query scans to the end of the region (#2684). Lazily mapped +// physical pages (X2W_XMEM_LAZY_COMMIT) are committed first. static bool destination_writable(const void* destination, std::size_t bytes) { if (bytes == 0) return true; - std::uintptr_t cursor = reinterpret_cast<std::uintptr_t>(destination); - if (!destination || bytes > UINTPTR_MAX - cursor) return false; - x2w_local::commit_lazy(destination, bytes); // lazily mapped physical pages (X2W_XMEM_LAZY_COMMIT) - const std::uintptr_t end = cursor + bytes; - while (cursor < end) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast<const void*>(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) - return false; - if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; - const DWORD protect = info.Protect & 0xFF; - if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && - protect != PAGE_EXECUTE_WRITECOPY) - return false; - const std::uintptr_t region_end = reinterpret_cast<std::uintptr_t>(info.BaseAddress) + info.RegionSize; - if (region_end <= cursor) return false; - cursor = region_end; + const auto start = reinterpret_cast<std::uintptr_t>(destination); + if (!destination || bytes > UINTPTR_MAX - start) return false; + x2w_local::commit_lazy(destination, bytes); + if (x2w_local::resident_read_write(start, start + bytes)) return true; + return x2w_local::committed_writable(destination, bytes); +} + +// Copies bytes of data into a plain-memory destination whose whole declared capacity must be writable. With +// xmem.dll loaded, x2w_xmem_copy_to_destination makes the check and the copy, under XMem's mapping mutex when +// either range overlaps one of its runs, so an XMem run break (the pages of a shared view unmapped and mapped again) +// can neither make a mapped destination look reserved nor take it away during the copy. Without xmem.dll the check +// and the copy run here. +// ERROR_SUCCESS; ERROR_NOACCESS when the destination is not writable (nothing written); ERROR_INVALID_ADDRESS when +// the copy faulted (part of the destination may be written); ERROR_INVALID_PARAMETER for an invalid request. +static DWORD copy_to_destination(void* destination, std::size_t capacity, const void* data, std::size_t bytes) +{ + using CopyToDestination = BOOL(WINAPI*)(void*, SIZE_T, const void*, SIZE_T); + static const CopyToDestination copy = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast<CopyToDestination>(GetProcAddress(xmem, "x2w_xmem_copy_to_destination")) : nullptr; + }(); + if (copy) return copy(destination, capacity, data, bytes) ? ERROR_SUCCESS : GetLastError(); + if (!destination_writable(destination, capacity)) return ERROR_NOACCESS; + std::memcpy(destination, data, bytes); + return ERROR_SUCCESS; +} + +// The outcome logged for a copy that copy_to_destination did not complete, by its error. text holds the last case. +static const char* copy_outcome(DWORD error, char (&text)[40]) +{ + switch (error) { + case ERROR_NOACCESS: return "destination not writable"; + case ERROR_INVALID_ADDRESS: return "copy faulted (part of the destination may be written)"; + case ERROR_INVALID_PARAMETER: return "invalid copy request"; + default: + std::snprintf(text, sizeof(text), "copy failed (error %lu)", static_cast<unsigned long>(error)); + return text; } - return true; } // Return the exact queued requests that continue this stream in this submission, in queue order. @@ -279,15 +326,23 @@ long __stdcall query_interface(Object* self, const GUID* riid, void** out) return S_OK; } unsigned long __stdcall add_ref(Object* self) { return static_cast<unsigned long>(InterlockedIncrement(&self->refs)); } + +void destroy_object(Object* self) noexcept; + +// Final Release of a queue: stop the worker, wait for it to leave, then drop the entries that never +// ran. Returns true when the worker owns the destruction (Release ran on the worker itself). +// Defined after the entry helpers below. +bool shutdown_queue(Object* self); + unsigned long __stdcall release(Object* self) { const auto refs = static_cast<unsigned long>(InterlockedDecrement(&self->refs)); - if (refs == 0 && self->kind == queue) { - auto& object = *static_cast<QueueObject*>(self); - const std::lock_guard guard(object.error_mutex); - if (object.error_event) CloseHandle(std::exchange(object.error_event, nullptr)); - } - return refs; + if (refs != 0) return refs; + // The factory is a process singleton: it stays alive for the life of the process (#2788). + if (self->kind == factory) return 0; + if (self->kind == queue && !naive_lifetime_mutant() && shutdown_queue(self)) return 0; + destroy_object(self); + return 0; } void** make_table(unsigned kind); @@ -302,9 +357,53 @@ Object* make(unsigned kind) object->kind = kind; object->refs = 1; object->handle = INVALID_HANDLE_VALUE; + InterlockedIncrement(&live_by_kind[kind / 0x20 - 1]); return object; } +void destroy_object(Object* self) noexcept +{ + const unsigned index = self->kind / 0x20 - 1; + if (self->kind == queue) { + auto* object = static_cast<QueueObject*>(self); + { + const std::lock_guard guard(object->error_mutex); + if (object->error_event) CloseHandle(std::exchange(object->error_event, nullptr)); + } + delete object; + } else if (self->kind == file) { + auto* object = static_cast<FileObject*>(self); + if (object->handle != INVALID_HANDLE_VALUE) CloseHandle(std::exchange(object->handle, INVALID_HANDLE_VALUE)); + delete object; + } else if (self->kind == status) { + delete[] self->results; + delete self; + } else { + return; // the factory singleton is never freed + } + InterlockedDecrement(&live_by_kind[index]); +} + +// The status array an entry completes and the file a request reads must outlive the guest's Release +// while the entry is pending: the entry owns one reference on each until it is consumed (#2788). +void retain_entry_object(Object* object) noexcept +{ + if (object && !naive_lifetime_mutant()) InterlockedIncrement(&object->refs); +} + +void release_entry_object(Object* object) noexcept +{ + if (object && !naive_lifetime_mutant()) release(object); +} + +void release_entry(Entry& entry) noexcept +{ + release_entry_object(entry.source); + entry.source = nullptr; + release_entry_object(entry.array); + entry.array = nullptr; +} + // Factory slot 4, PC IDStorageFactory::OpenFile(PCWSTR path, REFIID riid, void** ppv). long __stdcall factory_open_file(Object*, const wchar_t* path, const GUID* riid, void** out) { @@ -397,6 +496,8 @@ long __stdcall file_information(Object* self, BY_HANDLE_FILE_INFORMATION* info) // format, 1 seen), +0x08 destination pointer, +0x18 destination size (u32), +0x20 source (File object // or memory pointer), +0x28 source offset, +0x30 source size (u32). Uncompressed requests are executed // synchronously; compressed ones are logged and left undone. The first requests are logged in full. +// requests_done counts the uncompressed copies only (the "raw" count of the status lines); a compressed request +// is counted in requests_compressed ("inflated"), or in requests_bcpack_blank when its BCPack data was not decoded. LONG requests_done, requests_compressed, requests_failed, requests_bcpack_blank; // Failed requests by cause, for the heartbeat (#1198). Each failure site names its cause and @@ -492,6 +593,16 @@ LONG sample_failure_counts(StorageFailureCounts& counts) noexcept return static_cast<LONG>(total); } +// The counters of the status lines: "raw=R inflated=I failed=F bcpack-blank=B completed=C". "inflated=%ld +// failed=%ld" stays byte-for-byte what it was, because tools/startup/live_view.py parses it. completed is every +// request that wrote its destination and finished: raw + inflated + bcpack-blank (a failed request is not in it), so +// a run whose requests are all compressed still shows storage progressing. +int format_request_counts(char* out, std::size_t size, LONG raw, LONG inflated, LONG failed, LONG blank) noexcept +{ + return std::snprintf(out, size, "raw=%ld inflated=%ld failed=%ld bcpack-blank=%ld completed=%ld", raw, inflated, + failed, blank, raw + inflated + blank); +} + int format_failure_causes(char* out, std::size_t size, int second, const StorageFailureCounts& n) noexcept { return std::snprintf(out, size, @@ -656,6 +767,7 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR const unsigned page_offset = static_cast<unsigned>(*reinterpret_cast<const u64*>(request + 0x10) & 0xFFFF); const u64 known = 1 | (0xFull << 1) | (1ull << 21) | 0x400000; const char* outcome = "done"; + char copy_failure[40]; // copy_outcome's text for an error it does not name StorageFailure failure = StorageFailure::other; // the heartbeat's cause, if the request fails std::vector<unsigned char> packed, output; const unsigned char* input = nullptr; @@ -774,27 +886,18 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR if (input) { bool bcpack_decoded = false; if (data && bcpack) { - if (bcpack == 7 || bcpack == 1 || bcpack == 4 || bcpack == 5 || bcpack == 3) { - std::vector<unsigned char> decoded(destination_size); - std::size_t produced = 0; - if (x2w_bcpack::decode_bcpack(data, decode_length, bcpack, decoded.data(), decoded.size(), &produced)) { - output = std::move(decoded); - data = output.data(); - decode_length = produced; - outcome = zlib ? "inflated + bcpack decoded" : "bcpack decoded"; - bcpack_decoded = true; - } else { - outcome = "bcpack failed"; - failure = StorageFailure::bcpack; - data = nullptr; - } - } else { - // shortcut for formats not decoded yet: texels are left zero (a blank texture) so the - // title's loading continues. Counted as bcpack_blank. - output.assign(destination_size, 0); + std::vector<unsigned char> decoded(destination_size); + std::size_t produced = 0; + if (x2w_bcpack::decode_bcpack(data, decode_length, bcpack, decoded.data(), decoded.size(), &produced)) { + output = std::move(decoded); data = output.data(); - decode_length = destination_size; - outcome = "BCPack not decoded: zero-filled"; + decode_length = produced; + outcome = zlib ? "inflated + bcpack decoded" : "bcpack decoded"; + bcpack_decoded = true; + } else { + outcome = "bcpack failed"; + failure = StorageFailure::bcpack; + data = nullptr; } } if (data) { @@ -843,11 +946,10 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR // The title's destination can be smaller in memory than its declared capacity (#870: // a write fault inside this copy). Judge the whole declared capacity before the first // byte is written, so a refusal leaves every page untouched. - if (destination_writable(destination, destination_capacity)) { - std::memcpy(destination, data, decode_length); - } else { - outcome = "destination not writable"; - failure = StorageFailure::destination_not_writable; + const DWORD copied = copy_to_destination(destination, destination_capacity, data, decode_length); + if (copied != ERROR_SUCCESS) { + outcome = copy_outcome(copied, copy_failure); + failure = copied == ERROR_NOACCESS ? StorageFailure::destination_not_writable : StorageFailure::other; data = nullptr; written = false; } @@ -950,6 +1052,8 @@ void complete_deferred(Object* self, QueueWork* work); bool deferred_pending(const QueueWork& work); +void discard_entries(QueueWork* work) noexcept; + DWORD WINAPI queue_worker(void* parameter) { on_queue_worker = true; @@ -959,7 +1063,10 @@ DWORD WINAPI queue_worker(void* parameter) Entry entry; { std::unique_lock lock(work.mutex); - work.wake.wait(lock, [&] { return !work.submitted.empty() && !deferred_pending(work); }); + work.wake.wait(lock, [&] { + return work.stopping || (!work.submitted.empty() && !deferred_pending(work)); + }); + if (work.stopping) break; entry = std::move(work.submitted.front()); work.submitted.pop_front(); } @@ -983,6 +1090,7 @@ DWORD WINAPI queue_worker(void* parameter) copy_reason(reason, "unknown exception"); } if (failed) fail_entry(self, entry, reason); + release_entry(entry); { const std::lock_guard guard(work.mutex); if (work.submitted.empty()) { @@ -993,6 +1101,23 @@ DWORD WINAPI queue_worker(void* parameter) work.drained.notify_all(); complete_deferred(self, &work); } + bool destroy = false; + { + const std::lock_guard guard(work.mutex); + destroy = work.destroy_on_worker; + } + if (destroy) { + // The final Release ran on this worker (a fence callback released the queue). The worker cannot + // join itself: it drops the entries that never ran and frees the queue as it exits. + discard_entries(&work); + self->work = nullptr; + delete &work; + destroy_object(self); + InterlockedDecrement(&live_workers); + return 0; + } + InterlockedDecrement(&live_workers); + return 0; } // Guards queue setup: building a queue's work, starting its worker and the unrecorded list. @@ -1037,8 +1162,10 @@ bool start_worker(Object* self, QueueWork* work) return false; } work->worker_started = true; + work->thread = worker; + work->thread_id = GetThreadId(worker); + InterlockedIncrement(&live_workers); ResumeThread(worker); - CloseHandle(worker); return true; } @@ -1050,12 +1177,21 @@ struct Unrecorded { u64 after; Entry::Type type; Object* array; + Object* source; // request: the file the entry would read, retained until the node is dropped unsigned index; void* fence; u64 value; unsigned char bytes[sizeof(StorageRequest)]; }; +void release_unrecorded(Unrecorded& node) noexcept +{ + release_entry_object(node.source); + node.source = nullptr; + release_entry_object(node.array); + node.array = nullptr; +} + // True while snapshot entries of an earlier Submit are ready or being completed by some thread. The // worker starts no newer entry then, so a deferred completion and a normal one keep the same order. // The caller holds work.mutex. @@ -1106,13 +1242,25 @@ bool has_unrecorded(Object* self) return self->unrecorded_head != nullptr; } -void defer_unrecorded(Object* self, const Entry& entry) +void defer_unrecorded(Object* self, Entry& entry) { - auto* node = new (std::nothrow) Unrecorded{nullptr, 0, 0, entry.type, entry.array, entry.index, entry.fence, entry.value, {}}; + auto* node = new (std::nothrow) Unrecorded{}; if (!node) { fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.bytes); + release_entry(entry); return; } + node->next = nullptr; + node->submission_id = 0; + node->after = 0; + node->type = entry.type; + node->array = entry.array; + node->source = entry.source; + node->index = entry.index; + node->fence = entry.fence; + node->value = entry.value; + entry.array = nullptr; + entry.source = nullptr; // the node now owns the entry's references if (entry.type == Entry::request) std::memcpy(node->bytes, entry.bytes, sizeof node->bytes); const std::lock_guard guard(setup_mutex()); (self->unrecorded_tail ? self->unrecorded_tail->next : self->unrecorded_head) = node; @@ -1130,6 +1278,7 @@ void fail_unrecorded(Object* self) while (node) { Unrecorded* const next = node->next; fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value, node->bytes); + release_unrecorded(*node); delete node; node = next; } @@ -1147,6 +1296,7 @@ void fail_waiting(Object* self, QueueWork* work) work->waiting.pop_front(); } fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.bytes); + release_entry(entry); } } @@ -1275,13 +1425,60 @@ void complete_deferred(Object* self, QueueWork* work) } if (node) { fail_unstarted(self, node->type, node->array, node->index, node->fence, node->value, node->bytes); + release_unrecorded(*node); delete node; } else { fail_unstarted(self, entry.type, entry.array, entry.index, entry.fence, entry.value, entry.bytes); + release_entry(entry); } } } +// Drops every entry that will never run and releases the objects those entries held. Called after the +// worker has left, so no other thread touches the queue. +void discard_entries(QueueWork* work) noexcept +{ + for (Entry& entry : work->waiting) release_entry(entry); + work->waiting.clear(); + for (Entry& entry : work->submitted) release_entry(entry); + work->submitted.clear(); + for (Entry& entry : work->failing) release_entry(entry); + work->failing.clear(); + Unrecorded* node = work->deferred_head; + work->deferred_head = work->deferred_tail = nullptr; + while (node) { + Unrecorded* const next = node->next; + release_unrecorded(*node); + delete node; + node = next; + } + work->cached_streams.clear(); +} + +bool shutdown_queue(Object* self) +{ + QueueWork* work = self->work; + if (!work) return false; + bool on_worker; + { + const std::lock_guard guard(work->mutex); + work->stopping = true; + on_worker = work->worker_started && GetCurrentThreadId() == work->thread_id; + if (on_worker) work->destroy_on_worker = true; + } + work->wake.notify_all(); + if (on_worker) return true; // the worker frees the queue as it exits + if (work->thread) { + WaitForSingleObject(work->thread, INFINITE); + CloseHandle(work->thread); + work->thread = nullptr; + } + discard_entries(work); + self->work = nullptr; + delete work; + return false; +} + // Enqueue only records the entry, whether or not a worker runs; nothing completes before Submit. void push(Object* self, Entry&& entry) { @@ -1321,6 +1518,15 @@ void __stdcall queue_enqueue_request(Object* self, const unsigned char* request) entry.type = Entry::request; std::memcpy(entry.bytes, request, sizeof entry.bytes); const u64 options = *reinterpret_cast<const u64*>(request); + if (!(options & memory_source_option)) { + // The request keeps the file it reads alive until its turn: the guest may Release it after + // EnqueueRequest (#2788). + auto* source = *reinterpret_cast<Object* const*>(request + 0x20); + if (source && x2w_local::readable(source, sizeof(Object)) && source->kind == file) { + retain_entry_object(source); + entry.source = source; + } + } if (options & (1ull << 21)) { const auto* title = *reinterpret_cast<const ULONG_PTR* const*>(request + 0x08); const unsigned destination_size = *reinterpret_cast<const unsigned*>(request + 0x18); @@ -1348,13 +1554,18 @@ void __stdcall queue_enqueue_status(Object* self, Object* array, unsigned index) { const bool valid = array && array->kind == status && index < array->capacity; static LONG calls; - if (!valid || x2w_local::first_calls(calls, 8)) - log("x2w-dstorage Queue::EnqueueStatus array=%p index=%u%s (requests done=%ld inflated=%ld failed=%ld)", - static_cast<void*>(array), index, valid ? "" : " INVALID ARRAY", requests_done, requests_compressed, requests_failed); + if (!valid || x2w_local::first_calls(calls, 8)) { + char counts[128]; + format_request_counts(counts, sizeof(counts), requests_done, requests_compressed, requests_failed, + requests_bcpack_blank); + log("x2w-dstorage Queue::EnqueueStatus array=%p index=%u%s (requests %s)", static_cast<void*>(array), index, + valid ? "" : " INVALID ARRAY", counts); + } if (!valid) return; InterlockedExchange(&array->results[index], static_cast<LONG>(0x8000000A)); // E_PENDING until its turn Entry entry{}; entry.type = Entry::status_entry; + retain_entry_object(array); entry.array = array; entry.index = index; push(self, std::move(entry)); @@ -1521,6 +1732,23 @@ DWORD heartbeat_interval_ms() noexcept } // namespace +// Fixture-only probes (#2788): objects alive by kind (0 = every kind) and running queue workers. +extern "C" __declspec(dllexport) unsigned long x2w_xcrdapi_live_objects(unsigned kind) +{ + if (kind == 0) { + unsigned long total = 0; + for (LONG count : live_by_kind) total += static_cast<unsigned long>(count); + return total; + } + if (kind != factory && kind != file && kind != status && kind != queue) return 0; + return static_cast<unsigned long>(live_by_kind[kind / 0x20 - 1]); +} + +extern "C" __declspec(dllexport) unsigned long x2w_xcrdapi_live_workers() +{ + return static_cast<unsigned long>(live_workers); +} + extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) { char id[48]; @@ -1570,12 +1798,14 @@ extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) static_cast<unsigned long long>(sample.sections)); else std::snprintf(section_text, sizeof(section_text), "unknown"); - // Heartbeat preserves "inflated=%ld" format string for tools/startup/live_view.py; + // The counts keep "inflated=%ld failed=%ld" for tools/startup/live_view.py (format_request_counts); // requests_compressed counts all compressed streams (zlib and standalone/embedded BCPack). - log("x2w-dstorage heartbeat %d s: requests done=%ld inflated=%ld failed=%ld bcpack-blank=%ld; page tokens 0 at enqueue=%ld, " - "still 0 at run=%ld, replaced after enqueue=%ld; %s, live physical-page sections=%s", second, requests_done, requests_compressed, - failed, requests_bcpack_blank, zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue, memory, - section_text); + char counts[128]; + format_request_counts(counts, sizeof(counts), requests_done, requests_compressed, failed, + requests_bcpack_blank); + log("x2w-dstorage heartbeat %d s: requests %s; page tokens 0 at enqueue=%ld, " + "still 0 at run=%ld, replaced after enqueue=%ld; %s, live physical-page sections=%s", second, counts, + zero_tokens_at_enqueue, zero_tokens_at_run, tokens_replaced_after_enqueue, memory, section_text); char causes[384]; if (format_failure_causes(causes, sizeof(causes), second, failure_counts) > 0) log("%s", causes); char ends[384]; diff --git a/src/startup_stubs/xcrdapi.def b/src/startup_stubs/xcrdapi.def index 1d2bae195d..55b3df7ffc 100644 --- a/src/startup_stubs/xcrdapi.def +++ b/src/startup_stubs/xcrdapi.def @@ -1,3 +1,5 @@ LIBRARY XCRDAPI EXPORTS DStorageGetFactory + x2w_xcrdapi_live_objects + x2w_xcrdapi_live_workers diff --git a/src/startup_stubs/xg_xs.cpp b/src/startup_stubs/xg_xs.cpp index aa4ff39112..f593d2117d 100644 --- a/src/startup_stubs/xg_xs.cpp +++ b/src/startup_stubs/xg_xs.cpp @@ -81,6 +81,20 @@ struct Computer { constexpr std::size_t layout_header = 0x18, plane_bytes = 0x6c8, mip_base = 0x38, mip_bytes = 0x70; constexpr int max_mips = 15; +// Desktop D3D12 resolves MipLevels == 0 to the full mip chain for the resource's largest extent. +unsigned full_mips(const D3D12_RESOURCE_DESC& desc) +{ + UINT64 extent = desc.Width ? desc.Width : 1; + if (desc.Dimension >= D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Height > extent) extent = desc.Height; + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && desc.DepthOrArraySize > extent) extent = desc.DepthOrArraySize; + unsigned mips = 0; + while (extent) { + ++mips; + extent >>= 1; + } + return mips ? (std::min)(mips, static_cast<unsigned>(max_mips)) : 1u; +} + bool use_bc7_4k_s_layout(const D3D12_RESOURCE_DESC& desc) { return x2w_local::env_on("X2W_XG_BC7_4K_S_LAYOUT") && @@ -234,7 +248,7 @@ long __stdcall computer_layout(Computer* self, unsigned char* layout) const D3D12_RESOURCE_DESC desc = desktop_desc(self->desc); const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const unsigned slices = volume ? 1 : desc.DepthOrArraySize ? desc.DepthOrArraySize : 1; - unsigned mips = desc.MipLevels ? desc.MipLevels : 1; + unsigned mips = desc.MipLevels ? desc.MipLevels : full_mips(desc); if (mips > max_mips) mips = max_mips; const x2w_startup::SliceFootprints plan(device, desc, mips); const auto& footprints = plan.placed; @@ -385,7 +399,7 @@ long __stdcall computer_copy_into(Computer* self, unsigned char* base, unsigned const D3D12_RESOURCE_DESC desc = desktop_desc(self->desc); const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const unsigned slices = volume ? 1 : desc.DepthOrArraySize ? desc.DepthOrArraySize : 1; - unsigned mips = desc.MipLevels ? desc.MipLevels : 1; + unsigned mips = desc.MipLevels ? desc.MipLevels : full_mips(desc); if (mips > max_mips) mips = max_mips; const unsigned mip = subresource % mips, slice = subresource / mips; const x2w_startup::SliceFootprints plan(device, desc, mips); diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 7567418981..c4f202a7d4 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -10,13 +10,16 @@ #include <cstdio> #include <cstdlib> #include <cstring> +#include "startup_stubs/commit_state.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/resident_pages.h" #include "startup_stubs/profile_zone.h" #include <vector> #include <iterator> #include <limits> +#include <atomic> #include <map> #include <mutex> #include <new> @@ -56,7 +59,13 @@ struct PhysicalMemory { ULONG_PTR mirror_cpu = 0, mirror_gpu = 0; SIZE_T mirror_bytes = 0; std::set<ULONG_PTR> explicit_mirror_pages; - std::map<ULONG_PTR, SIZE_T> runs; // OS views: base -> bytes + // OS views: base -> bytes, and the id of the run break inside which the view was mapped (0: mapped outside any + // break). retry_remapped_page reads the id; it never expires while the view lasts. + struct Run { + SIZE_T bytes = 0; + ULONG64 stamp = 0; + }; + std::map<ULONG_PTR, Run> runs; // The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together // are adjacent slots again. x2w_xmem::SlabSlots<HANDLE> slots{era_physical::page_bytes}; @@ -71,7 +80,7 @@ struct PhysicalMemory { for (const auto& run : runs) UnmapViewOfFile(reinterpret_cast<void*>(run.first)); for (const HANDLE slab : slots.slabs()) - CloseHandle(slab); + if (slab) CloseHandle(slab); } }; @@ -100,12 +109,27 @@ const Backing* mirrored_backing(ULONG_PTR page) } // Caller holds memory.mutex. -void unpin_slot(const Slot& slot) +void collect_empty_slabs(std::vector<HANDLE>& closed) noexcept +{ + memory.slots.reclaim_empty_slabs([&](HANDLE slab) noexcept { + try { + closed.push_back(slab); + } catch (...) { + CloseHandle(slab); + } + }); +} + +// Caller holds memory.mutex. +void unpin_slot(const Slot& slot, std::vector<HANDLE>* closed = nullptr) { const auto found = memory.pins.find(slot); + if (found == memory.pins.end()) return; // not pinned: nothing to do if (--found->second.references) return; - if (found->second.retired) memory.slots.release(slot.first, slot.second); + const bool retired = found->second.retired; memory.pins.erase(found); + if (retired && memory.slots.release(slot.first, slot.second) && closed) + collect_empty_slabs(*closed); } BOOL physical_result(era_physical::Status status) noexcept @@ -247,6 +271,10 @@ const Backing* lease_backing(UINT version, ULONG_PTR page) return backing && backing->committed ? backing : nullptr; } +// Set while this thread holds memory.mutex to change mappings or to copy into mapped pages (MappingThread). The +// fault handlers pass such a thread's faults on: waiting for memory.mutex there would never return. +thread_local bool mapping_thread = false; + LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -281,6 +309,7 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) // A thread that raced another one to the same slot finds it committed: retry once, then pass the fault on. thread_local ULONG_PTR retried = 0; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); + if (mapping_thread) return EXCEPTION_CONTINUE_SEARCH; const std::lock_guard guard(memory.mutex); Backing* backing = backing_at(address); if (!backing) return EXCEPTION_CONTINUE_SEARCH; @@ -350,18 +379,60 @@ auto owned_reservation(ULONG_PTR address) return address - it->first < it->second ? it : memory.reservations.end(); } +// MapViewOfFile3 and placeholder-split attempts made by map_split (x2w_xmem_map_counts). +volatile LONG64 map_attempts, split_attempts; +#ifdef X2W_XMEM_TEST_CONTROLS +// Test build only (x2w_xmem_alias_counts): views install_alias_view could not map in place inside an owned +// reservation, split by whether alias_placeholders refused the range or a placeholder release was tried. +volatile LONG64 alias_refusals, alias_splits; +#endif + +// True when [target, target + bytes) is a whole reserved region of its own: a placeholder that +// MEM_REPLACE_PLACEHOLDER can take as it is, so no split is needed first. +bool exact_placeholder(void* target, SIZE_T bytes) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_RESERVE && + info.AllocationBase == target && info.BaseAddress == target && info.RegionSize == bytes; +} + // Only split a reservation owned by the shim. Caller-owned placeholders must already match the view. +// Inside an owned reservation the split comes first when the target is not already an exact placeholder: +// a map into the middle of a larger placeholder always fails, and under Wine every failed map is another +// server round trip whose cost grows with the number of views (one 64 KiB page per call at startup). +// The query and the split are not atomic, so if the split or the map after it fails, the map-first +// path below runs as before. Test build only (X2W_XMEM_TEST_CONTROLS): X2W_XMEM_TEST_MAP_FIRST=1 skips the +// split-first step; the deployed build ignores it. // Once a split succeeds, report the retry's result even if it fails for a different reason. template <class Map> bool map_split(void* target, SIZE_T bytes, Map map) { - if (map()) return true; - const DWORD error = GetLastError(); +#ifdef X2W_XMEM_TEST_CONTROLS + static const bool map_first = x2w_local::env_on("X2W_XMEM_TEST_MAP_FIRST"); +#else + constexpr bool map_first = false; +#endif const auto address = reinterpret_cast<ULONG_PTR>(target); const auto reservation = owned_reservation(address); - if (reservation != memory.reservations.end() && bytes <= reservation->second - (address - reservation->first) && - VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) - return map(); + const bool owned = reservation != memory.reservations.end() && + bytes <= reservation->second - (address - reservation->first); + if (owned && !map_first && !exact_placeholder(target, bytes)) { + InterlockedIncrement64(&split_attempts); + if (VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + InterlockedIncrement64(&map_attempts); + if (map()) return true; + } + } + InterlockedIncrement64(&map_attempts); + if (map()) return true; + const DWORD error = GetLastError(); + if (owned) { + InterlockedIncrement64(&split_attempts); + if (VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + InterlockedIncrement64(&map_attempts); + return map(); + } + } SetLastError(error); return false; } @@ -379,8 +450,8 @@ bool map_view(ULONG_PTR address, const Backing& backing) } // Maps bytes of one section at address as a single view; falls back to one view per page when the -// range is not inside a single placeholder. -bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, +// range is not inside a single placeholder. stamp: the run break in progress, or 0 (PhysicalMemory::Run). +bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, ULONG64 stamp, std::vector<std::pair<ULONG_PTR, SIZE_T>>& made, ULONG_PTR& failed_address) { auto* target = reinterpret_cast<void*>(address); @@ -389,7 +460,7 @@ bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; }; if (map_split(target, bytes, map)) { - memory.runs[address] = bytes; + memory.runs[address] = {bytes, stamp}; made.emplace_back(address, bytes); return true; } @@ -402,7 +473,7 @@ bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, failed_address = address + done; return false; } - memory.runs[address + done] = page_bytes; + memory.runs[address + done] = {page_bytes, stamp}; made.emplace_back(address + done, page_bytes); } return true; @@ -429,23 +500,33 @@ void coalesce_unused(const Pages& batch) } } -// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages). -// A thread that touches one of those pages in between faults. The break records the address -// ranges of the runs it takes apart and a generation that is odd while it is in progress. +// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages), and so do a +// cross-call merge (merge_with_previous) for the run it joins and a page batch (remap_alias_pages) for the runs it +// changes. A thread that touches one of those pages in between faults. Such a run break has a generation that is odd +// while it is in progress; the break's id is that odd value. Every view mapped inside a break records the id +// (PhysicalMemory::Run::stamp, under memory.mutex), so a fault handler that runs late, after any number of later +// breaks on other runs (a merge of the CPU view and then of its GPU mirror in one call, or the next calls), still +// finds the break that mapped the page again. struct RemapWindow { SRWLOCK lock = SRWLOCK_INIT; - std::vector<std::pair<ULONG_PTR, SIZE_T>> ranges; // the runs of the break in progress, or of the last one ULONG64 generation = 0; }; RemapWindow remap_window; +// Set once shared views are on (FaultRetry::ready). Breaks also begin without them (every unmap counts in the +// generation), but then a page has a view of its own and no break takes a neighbour away, so x2w_xmem_stable_call +// does not wait for them. +std::atomic<bool> shared_views_on{false}; +// Set once, with shared views, when X2W_XMEM_JOIN_CALLS=1 is set as well (FaultRetry::ready): only then does a run +// mapped by a call of its own join the recorded run that ends at its address (merge_with_previous). +std::atomic<bool> joins_on{false}; -void begin_break(const std::map<ULONG_PTR, SIZE_T>& broken) +// Caller holds memory.mutex. Returns the break's id, the stamp of the views mapped until end_break. +ULONG64 begin_break() { - std::vector<std::pair<ULONG_PTR, SIZE_T>> ranges(broken.begin(), broken.end()); AcquireSRWLockExclusive(&remap_window.lock); - remap_window.ranges.swap(ranges); - ++remap_window.generation; + const ULONG64 id = ++remap_window.generation; ReleaseSRWLockExclusive(&remap_window.lock); + return id; } void end_break() { @@ -456,12 +537,47 @@ void end_break() struct EndBreak { ~EndBreak() { end_break(); } }; -// Retries an access violation only when all of this holds: the address is inside a run that the -// break in progress, or the last finished one, took apart; after that break has finished (the -// mutex) the page is recorded and covered by a view; and this thread has not already retried this -// page for this break. Everything else is passed on, so a fault that is not the transient one is -// reported after at most one retry. -thread_local bool mapping_thread = false; +ULONG64 break_generation() +{ + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; +} + +// Test build only: X2W_XMEM_TEST_HOLD_RETRY=<name> holds the fault handler before it reads the break: it sets +// "<name>.faulted", then waits up to five seconds for "<name>.go", so that a test can end the break first. +#ifdef X2W_XMEM_TEST_CONTROLS +void hold_retry() +{ + char name[96]; + const DWORD length = GetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", name, sizeof(name) - 16); + if (!length || length >= sizeof(name) - 16) return; + char event_name[128]; + std::snprintf(event_name, sizeof(event_name), "%s.faulted", name); + HANDLE faulted = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.go", name); + HANDLE go = CreateEventA(nullptr, TRUE, FALSE, event_name); + if (faulted && go) { + SetEvent(faulted); + WaitForSingleObject(go, 5000); + } + if (faulted) CloseHandle(faulted); + if (go) CloseHandle(go); +} +#else +void hold_retry() {} +#endif + +// Retries an access violation only when all of this holds: after the break in progress, if any, has finished (the +// mutex), the page is recorded, covered by a view, and in a run mapped inside a break (a nonzero Run::stamp); and +// this thread has not already retried this page for that stamp. Everything else is passed on, so a fault that is not +// the transient one is reported after at most one retry per break that mapped the page again. +// Faults that cannot be the transient one do not wait for memory.mutex, which a mapping call holds for all of its +// work: when no break is in progress or begins or ends around a region query of the page (the generation is even +// before and unchanged after) and the query shows no mapped view there, the fault is passed on at once. Outside +// breaks only a break takes away a view mapped inside one, so the check below would pass it on as well. Faults on +// lazily committed memory and other faults outside the runs take that path. LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -469,26 +585,28 @@ LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) return EXCEPTION_CONTINUE_SEARCH; const ULONG_PTR address = record->ExceptionInformation[1]; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); - bool inside = false; - AcquireSRWLockShared(&remap_window.lock); - const ULONG64 seen = remap_window.generation; - for (const auto& [base, size] : remap_window.ranges) - inside |= address - base < size; - ReleaseSRWLockShared(&remap_window.lock); - if (!inside || seen == 0) return EXCEPTION_CONTINUE_SEARCH; - const ULONG64 break_id = seen | 1; // the break in progress, or the one that just finished - thread_local ULONG_PTR retried_page = 0; - thread_local ULONG64 retried_break = 0; - if (retried_page == page && retried_break == break_id) return EXCEPTION_CONTINUE_SEARCH; - bool mapped = false; + hold_retry(); + const ULONG64 before = break_generation(); + MEMORY_BASIC_INFORMATION info{}; + const bool mapped_now = VirtualQuery(reinterpret_cast<void*>(page), &info, sizeof(info)) == sizeof(info) && + info.State == MEM_COMMIT && info.Type == MEM_MAPPED; + if (!(before & 1) && break_generation() == before && !mapped_now) return EXCEPTION_CONTINUE_SEARCH; + // The break that last mapped the page's run, however many breaks on other runs came after it. A later break of + // the same run stamps it again, so a fault in that break is retried again. + ULONG64 stamp = 0; { const std::lock_guard guard(memory.mutex); // held by the mapping thread until its break is over - auto run = memory.runs.upper_bound(page); - mapped = memory.views.count(page) && run != memory.runs.begin() && page - std::prev(run)->first < std::prev(run)->second; + const auto run = memory.runs.upper_bound(page); + if (memory.views.count(page) && run != memory.runs.begin() && + page - std::prev(run)->first < std::prev(run)->second.bytes) + stamp = std::prev(run)->second.stamp; } - if (!mapped) return EXCEPTION_CONTINUE_SEARCH; + if (!stamp) return EXCEPTION_CONTINUE_SEARCH; + thread_local ULONG_PTR retried_page = 0; + thread_local ULONG64 retried_stamp = 0; + if (retried_page == page && retried_stamp == stamp) return EXCEPTION_CONTINUE_SEARCH; retried_page = page; - retried_break = break_id; + retried_stamp = stamp; return EXCEPTION_CONTINUE_EXECUTION; } struct MappingThread { @@ -498,7 +616,9 @@ struct MappingThread { // Shared views are opt-in: X2W_XMEM_SHARED_VIEWS=1, read once by the first mapping call. Without // it every page has a view of its own, as before: unmapping a page never takes a neighbour away, -// no handler is registered, and the module unloads like any DLL. +// no handler is registered, and the module unloads like any DLL. The switch is also read once when +// xmem.dll loads (virtual_query_ex_wrapped): with it set then, the main module's VirtualQueryEx imports +// are wrapped, and the module is pinned at load when one is. // // With it, the first mapping call registers the handler and pins the module. The handler is // process-wide and Windows offers no way to remove one that also waits for every dispatch already @@ -506,6 +626,9 @@ struct MappingThread { // place until the process ends, also across a host's FreeLibrary and LoadLibrary. Nothing is // waited for or torn down at DLL detach. If the handler cannot be registered or the module cannot // be pinned, the opt-in is refused and pages get a view each. +// +// X2W_XMEM_JOIN_CALLS=1 is read at the same time and only counts with shared views on: a mapping call may then join +// the run that ends at its address (merge_with_previous). Without it every call maps views of its own. struct FaultRetry { SRWLOCK lock = SRWLOCK_INIT; bool tried = false; @@ -520,6 +643,7 @@ struct FaultRetry { // Test build only: shared views without the handler, to show that a reader then faults. if (x2w_local::env_on("X2W_XMEM_NO_FAULT_RETRY")) { guaranteed = true; + joins_on.store(x2w_local::env_on("X2W_XMEM_JOIN_CALLS"), std::memory_order_release); ReleaseSRWLockExclusive(&lock); return true; } @@ -532,10 +656,15 @@ struct FaultRetry { AddVectoredExceptionHandler(1, retry_remapped_page)) { guaranteed = true; x2w_local::logf("x2w-xmem shared views are on (X2W_XMEM_SHARED_VIEWS): xmem.dll stays loaded until the process ends"); + if (x2w_local::env_on("X2W_XMEM_JOIN_CALLS")) { + joins_on.store(true, std::memory_order_release); + x2w_local::logf("x2w-xmem joins across mapping calls are on (X2W_XMEM_JOIN_CALLS)"); + } } else x2w_local::logf("x2w-xmem shared views are off: the fault handler could not be set up (error %lu)", GetLastError()); } const bool result = guaranteed; + if (result) shared_views_on.store(true, std::memory_order_release); ReleaseSRWLockExclusive(&lock); return result; } @@ -545,13 +674,15 @@ FaultRetry fault_retry; // Test build only (X2W_XMEM_TEST_CONTROLS; tests/xmem_page_runs_check.py): X2W_XMEM_TEST_FAULT=<stage>:<skip> makes one step of // the next unmap fail as if Windows had refused it, after skipping <skip> such steps. Stage 1 is // unmapping a run, stage 2 mapping surviving pages again, stage 3 both the unmap and the restore. +// Stages 4 and 5 are steps of a cross-call merge (merge_with_previous): 4 the map of the joined view, +// 5 joining the two placeholders. #ifdef X2W_XMEM_TEST_CONTROLS struct TestFault { unsigned stage = 0, skip = 0; TestFault() { char text[32]; - if (GetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", text, sizeof(text)) && text[0] >= '1' && text[0] <= '3' && text[1] == ':') { + if (GetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", text, sizeof(text)) && text[0] >= '1' && text[0] <= '5' && text[1] == ':') { stage = static_cast<unsigned>(text[0] - '0'); skip = static_cast<unsigned>(std::strtoul(text + 2, nullptr, 10)); } @@ -575,8 +706,8 @@ struct TestFault { }; #endif -// Test build only: X2W_XMEM_TEST_HOLD_WINDOW=<name> keeps an unmap in the window where the run is -// unmapped and not yet mapped again. It sets the event "<name>.unmapped", then waits up to +// Test build only: X2W_XMEM_TEST_HOLD_WINDOW=<name> keeps an unmap, or a cross-call merge (merge_with_previous), in the +// window where the run is unmapped and not yet mapped again. It sets the event "<name>.unmapped", then waits up to // five seconds for "<name>.release", so that a reader thread can reach the window every time. #ifdef X2W_XMEM_TEST_CONTROLS void hold_window() @@ -613,7 +744,7 @@ void forget_page(ULONG_PTR address) // Maps every recorded page of [base, base + size) that has no view: neighbours on adjacent slots // together, one page at a time when a group is refused. A page that cannot be mapped is forgotten -// and counted. fail is true when the test control refuses this range. +// and counted. fail is true when the test control refuses this range. stamp: the break in progress. struct MapFailure { const char* stage = nullptr; ULONG_PTR address = 0; @@ -635,7 +766,7 @@ struct MapFailure { } }; -ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failure) +ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, ULONG64 stamp, bool fail, MapFailure* failure) { ULONG_PTR lost = 0; ULONG_PTR at = base; @@ -655,14 +786,14 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu } std::vector<std::pair<ULONG_PTR, SIZE_T>> made; ULONG_PTR failed_address; - if (fail || !map_run(at, head, bytes, made, failed_address)) { + if (fail || !map_run(at, head, bytes, stamp, made, failed_address)) { // map_run may have mapped some pages one at a time before it stopped; keep those. for (SIZE_T done = 0; done < bytes; done += page_bytes) { if (memory.runs.count(at + done)) continue; Backing one = head; one.offset += done; if (!fail && map_view(at + done, one)) { - memory.runs[at + done] = page_bytes; + memory.runs[at + done] = {page_bytes, stamp}; } else { if (failure) failure->record("restore-view", at + done, memory.views.at(at + done), @@ -677,6 +808,83 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } +// Shared views with X2W_XMEM_JOIN_CALLS=1 only (joins_on). Startup maps nearly every page with a call of its own, +// and under Wine each map costs more the more views the process has. With the switch, a run mapped by a call of its +// own therefore joins the recorded run R that ends at its address, when its first page is the next slot of the +// section behind R's last page and R and the new pages lie in one reservation of the shim: the new pages' range is +// split to a placeholder of its own, R is unmapped, the two placeholders are joined and one view is mapped over +// both. R is taken apart as in an unmap (begin_break), so a thread that touches R in between is retried and +// x2w_xmem_stable_call readers wait. On a refused step before R is unmapped nothing changed; after it, R is mapped +// again as it was (map_recorded). Both return separate, and the caller maps the new pages on their own. lost: R +// could not be mapped again; the pages that have no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 +// turns the merge off (tests only). +// A joined run stops at max_merged_run_pages: a page that would make R longer starts a run of its own, which the +// next pages join. The cap bounds the runs that joining builds: the work of each join, and of a later break of such a +// run (an unmap inside a run takes the whole run apart and maps its other pages again). A run mapped by one call +// (map_run in map_pages_locked) is not capped, and neither are the survivors map_recorded maps again after an unmap +// inside such a run; both are as long as they were before the cap. +enum class Merge { joined, separate, lost }; + +constexpr SIZE_T max_merged_run_pages = 64; + +// Test build only: X2W_XMEM_TEST_MERGE_CAP=<pages> replaces the cap (xmem_cross_call_merge_check's timing mode). +SIZE_T merged_run_cap() +{ +#ifdef X2W_XMEM_TEST_CONTROLS + char text[24]; + if (GetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", text, sizeof(text))) + if (const auto pages = std::strtoull(text, nullptr, 10)) return static_cast<SIZE_T>(pages); +#endif + return max_merged_run_pages; +} + +Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, MapFailure* failure) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (x2w_local::env_on("X2W_XMEM_TEST_NO_MERGE")) return Merge::separate; +#endif + const auto next = memory.runs.lower_bound(address); + if (next == memory.runs.begin()) return Merge::separate; + const ULONG_PTR base = std::prev(next)->first; + const SIZE_T size = std::prev(next)->second.bytes; + if (base + size != address) return Merge::separate; + if ((size + bytes) / page_bytes > merged_run_cap()) return Merge::separate; + const auto tail = memory.views.find(address - page_bytes); + if (tail == memory.views.end()) return Merge::separate; + const Backing& previous = memory.backings.at(tail->second); + if (previous.section != head.section || previous.offset + page_bytes != head.offset) return Merge::separate; + const auto reservation = owned_reservation(base); + if (reservation == memory.reservations.end() || address + bytes > reservation->first + reservation->second) + return Merge::separate; + const Backing start = memory.backings.at(memory.views.at(base)); + auto* const target = reinterpret_cast<void*>(address); + if (!exact_placeholder(target, bytes)) { + InterlockedIncrement64(&split_attempts); + if (!VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return Merge::separate; + } + TestFault test; + const ULONG64 stamp = begin_break(); + const EndBreak end; + if (!unmap_view(base)) return Merge::separate; + memory.runs.erase(base); + hold_window(); + auto* const whole = reinterpret_cast<void*>(base); + if (!test.hit(5) && VirtualFree(whole, size + bytes, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) { + InterlockedIncrement64(&map_attempts); + if (!test.hit(4) && MapViewOfFile3(start.section, GetCurrentProcess(), whole, start.offset, size + bytes, + MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) { + memory.runs[base] = {size + bytes, stamp}; + return Merge::joined; + } + } + // map_recorded splits the joined placeholder back to R's size (map_split: the reservation is the shim's). + const ULONG_PTR lost = map_recorded(base, size, stamp, false, failure); + if (!lost) return Merge::separate; + x2w_local::logf("x2w-xmem merge of a run with the next mapping call failed: %llu page(s) of the run could not be " + "mapped again and were forgotten", static_cast<unsigned long long>(lost)); + return Merge::lost; +} + // Destinations must be caller-owned, page-sized Windows placeholders. Live views // are owned by this shim until it unmaps them. The caller must not replace them. template <typename AddressAt> @@ -721,8 +929,19 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& const Backing& b = memory.backings.at(last->second); if (last->first != first->first + bytes || b.section != head.section || b.offset != head.offset + bytes) break; } + // Only with X2W_XMEM_JOIN_CALLS, and only a run that is the whole batch joins an earlier one: a + // later run of the batch that fails unmaps everything in made, which a joined run is not. + const bool whole_batch = first == batch.begin() && last == batch.end(); + const Merge merge = share_views && joins_on.load(std::memory_order_acquire) && whole_batch + ? merge_with_previous(first->first, head, bytes, failure) + : Merge::separate; + if (merge == Merge::lost) { + coalesce_unused(batch); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } ULONG_PTR failed_address; - if (!map_run(first->first, head, bytes, made, failed_address)) { + if (merge == Merge::separate && !map_run(first->first, head, bytes, 0, made, failed_address)) { const DWORD error = GetLastError(); if (failure) failure->record("map-view", failed_address, batch.at(failed_address), error); for (const auto& [base, size] : made) { @@ -750,10 +969,10 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& auto run = memory.runs.upper_bound(address); if (run == memory.runs.begin()) continue; --run; - if (address - run->first < run->second) broken.insert(*run); + if (address - run->first < run->second.bytes) broken.emplace(run->first, run->second.bytes); } TestFault test; - begin_break(broken); + const ULONG64 stamp = begin_break(); const EndBreak end; DWORD error = ERROR_SUCCESS; std::vector<std::pair<ULONG_PTR, SIZE_T>> unmapped; @@ -777,7 +996,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& if (!refused && !unmapped.empty()) hold_window(); ULONG_PTR lost = 0; for (const auto& [base, size] : unmapped) - lost += map_recorded(base, size, refused ? test.stage == 3 && test.hit(3) : test.hit(2), failure); + lost += map_recorded(base, size, stamp, refused ? test.stage == 3 && test.hit(3) : test.hit(2), failure); if (!refused) coalesce_unused(batch); if (refused || lost) { x2w_local::logf("x2w-xmem unmap of %llu page(s) failed (error %lu): %s; %llu surviving page(s) could not be mapped " @@ -862,6 +1081,13 @@ void* local_virtual_alloc(void* address, SIZE_T bytes, DWORD type, ULONGLONG att if (result && !(type & MEM_RESERVE_PLACEHOLDER)) record_reservation(result, bytes); how = "placeholder reserve"; } +#if X2W_TRACY + if (result && (type & MEM_COMMIT)) { + // A plot, not a pool: the title releases these ranges with Win32 calls that are not seen here. + static std::atomic<long long> committed; + X2W_PLOT("XMemVirtualAlloc commits (bytes, cumulative)", static_cast<std::int64_t>(committed += bytes)); + } +#endif const DWORD error = result ? 0 : GetLastError(); x2w_local::logf("x2w-xmem XMemVirtualAlloc addr=%p size=0x%llx type=0x%lx attr=0x%llx prot=0x%lx -> %p (%s, err %lu)", address, static_cast<unsigned long long>(bytes), static_cast<unsigned long>(type), @@ -898,6 +1124,18 @@ void log_apply_failure(const char* what, const MapFailure& failure, ULONG_PTR co static_cast<unsigned long long>(failure.region.RegionSize), static_cast<unsigned long>(failure.region.State), static_cast<unsigned long>(failure.region.Protect), static_cast<unsigned long>(failure.region.Type)); + // A failed commit (1455 = system commit limit, 8 = not enough memory): say how full the system commit and the pool + // are. The caller holds memory.mutex. The first three failures are reported. + if (x2w_local::is_commit_failure(failure.error)) { + static volatile LONG reported = 0; + if (InterlockedIncrement(&reported) <= 3) { + char line[384]; + x2w_local::format_exhausted(line, sizeof(line), what, static_cast<unsigned long>(failure.error), + x2w_local::system_commit(), x2w_local::job_memory(), memory.backings.size(), + memory.slots.slab_count(), memory.slots.slots_in_use(), memory.slots.slots_free()); + x2w_local::logf("%s", line); + } + } } void log_failed_ranges(const char* what, const char* operation, const std::vector<ULONG_PTR>& addresses) @@ -1051,26 +1289,32 @@ BOOL free_pages(ULONG_PTR count, PULONG_PTR pages) { if (!pages || !count || count > era_physical::capacity_pages) return physical_result(era_physical::Status::invalid); - const std::lock_guard guard(memory.mutex); - for (ULONG_PTR i = 0; i < count; ++i) { - const auto backing = memory.backings.find(pages[i]); - if (backing != memory.backings.end() && backing->second.views) - return physical_result(era_physical::Status::invalid); - } - const auto status = era_physical::release(count, reinterpret_cast<const std::uint64_t*>(pages)); - if (status == era_physical::Status::ok) { + std::vector<HANDLE> closed; + era_physical::Status status; + { + const std::lock_guard guard(memory.mutex); for (ULONG_PTR i = 0; i < count; ++i) { const auto backing = memory.backings.find(pages[i]); - if (backing != memory.backings.end()) { - const Slot slot{backing->second.slab, backing->second.offset}; - if (const auto pin = memory.pins.find(slot); pin != memory.pins.end()) - pin->second.retired = true; - else - memory.slots.release(slot.first, slot.second); - memory.backings.erase(backing); + if (backing != memory.backings.end() && backing->second.views) + return physical_result(era_physical::Status::invalid); + } + status = era_physical::release(count, reinterpret_cast<const std::uint64_t*>(pages)); + if (status == era_physical::Status::ok) { + for (ULONG_PTR i = 0; i < count; ++i) { + const auto backing = memory.backings.find(pages[i]); + if (backing != memory.backings.end()) { + const Slot slot{backing->second.slab, backing->second.offset}; + if (const auto pin = memory.pins.find(slot); pin != memory.pins.end()) + pin->second.retired = true; + else + memory.slots.release(slot.first, slot.second); + memory.backings.erase(backing); + } } + collect_empty_slabs(closed); } } + for (const HANDLE slab : closed) CloseHandle(slab); return physical_result(status); } } // namespace @@ -1101,31 +1345,91 @@ struct AliasEdit { }; using AliasPlan = std::map<ULONG_PTR, AliasEdit>; -using ViewRuns = std::map<ULONG_PTR, SIZE_T>; +using ViewRuns = std::map<ULONG_PTR, PhysicalMemory::Run>; + +// The region query exposes the placeholder reservation flag in Flags even though the SDK does not name that bit. +constexpr ULONG placeholder_reservation = 0x100; + +// Measured once: whether the region query reports placeholder_reservation for a fresh placeholder, and, when it does +// not, whether VirtualFree(MEM_PRESERVE_PLACEHOLDER) refuses a plain reservation and leaves it whole. Windows reports +// the bit. Wine (Proton Experimental, 2026-11) leaves Flags 0 for placeholders but refuses the plain case with +// ERROR_INVALID_ADDRESS. Test build only (X2W_XMEM_TEST_CONTROLS): X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 skips the +// second probe; the deployed build ignores it. +bool placeholder_fallback() +{ + static const bool fallback = [] { +#ifdef X2W_XMEM_TEST_CONTROLS + const bool skip_probe = x2w_local::env_on("X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK"); +#else + constexpr bool skip_probe = false; +#endif + bool bit_reported = false, refuses_plain = false; + if (void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)) { + WIN32_MEMORY_REGION_INFORMATION info{}; + bit_reported = QueryVirtualMemoryInformation(GetCurrentProcess(), probe, MemoryRegionInfo, &info, + sizeof(info), nullptr) && + (info.Flags & placeholder_reservation); + VirtualFree(probe, 0, MEM_RELEASE); + } + if (!bit_reported && !skip_probe) { + if (auto* plain = static_cast<BYTE*>(VirtualAlloc(nullptr, 2 * page_bytes, MEM_RESERVE, PAGE_NOACCESS))) { + MEMORY_BASIC_INFORMATION after{}; + refuses_plain = !VirtualFree(plain + page_bytes, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) && + VirtualQuery(plain, &after, sizeof(after)) == sizeof(after) && + after.State == MEM_RESERVE && after.AllocationBase == plain && + after.RegionSize == 2 * page_bytes; + VirtualFree(plain, 0, MEM_RELEASE); + } + } + x2w_local::logf("x2w-xmem placeholder bit reported=%d, plain reservation kept by a placeholder release=%d", + bit_reported, refuses_plain); + return !bit_reported && refuses_plain; + }(); + return fallback; +} bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) { - // The region query exposes the placeholder reservation flag in Flags even though the - // SDK does not name that bit. VirtualQuery alone cannot distinguish a reserved private - // allocation from a placeholder. PRESERVE_PLACEHOLDER can silently release that allocation. - constexpr ULONG placeholder_reservation = 0x100; + // VirtualQuery alone cannot distinguish a reserved private allocation from a placeholder, and on Windows + // PRESERVE_PLACEHOLDER can silently release that allocation. Where the region query does not report the bit + // and the OS refuses that release for a reservation made by VirtualAlloc (placeholder_fallback), reserved + // regions may be offered. Every region the view covers must be reserved, not only the first one of each + // allocation: Wine (Proton Experimental, 2026-11) released a private allocation made in place of a placeholder + // (VirtualAlloc2 MEM_REPLACE_PLACEHOLDER) together with its committed second page, and the view then replaced + // that page (xmem_placeholder_split_partial). Limit: Wine does not refuse the release for that kind of + // allocation either, so its reserved pages are still offered, and releasing one cuts it out of the caller's + // allocation. + const bool fallback = placeholder_fallback(); const auto end = address + bytes; while (address < end) { WIN32_MEMORY_REGION_INFORMATION info{}; if (!QueryVirtualMemoryInformation(GetCurrentProcess(), reinterpret_cast<void*>(address), - MemoryRegionInfo, &info, sizeof(info), nullptr) || - !(info.Flags & placeholder_reservation)) + MemoryRegionInfo, &info, sizeof(info), nullptr)) return false; const auto base = reinterpret_cast<ULONG_PTR>(info.AllocationBase); if (address - base >= info.RegionSize) return false; - address += info.RegionSize - (address - base); + const auto allocation_end = base + info.RegionSize; + if (!(info.Flags & placeholder_reservation)) { + if (!fallback) return false; + const auto stop = end < allocation_end ? end : allocation_end; + for (auto at = address; at < stop;) { + MEMORY_BASIC_INFORMATION region{}; + if (VirtualQuery(reinterpret_cast<void*>(at), ®ion, sizeof(region)) != sizeof(region) || + region.State != MEM_RESERVE || !region.RegionSize) + return false; + at = reinterpret_cast<ULONG_PTR>(region.BaseAddress) + region.RegionSize; + } + } + address = allocation_end; } return true; } // Both maps have the same node type. The node for each possible run base was reserved before // unmapping anything, so recording a successful OS call cannot fail for lack of C++ heap memory. -bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, +// stamp: the page batch's break (PhysicalMemory::Run). +bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, ULONG64 stamp, ViewRuns& nodes, X2WPageBatchStats& stats) { auto* target = reinterpret_cast<void*>(address); @@ -1136,8 +1440,13 @@ bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, if (!map()) { const DWORD original_error = GetLastError(); const auto reservation = owned_reservation(address); - if (reservation == memory.reservations.end() || - bytes > reservation->second - (address - reservation->first) || !alias_placeholders(address, bytes)) { + const bool inside = reservation != memory.reservations.end() && + bytes <= reservation->second - (address - reservation->first); + const bool accepted = inside && alias_placeholders(address, bytes); +#ifdef X2W_XMEM_TEST_CONTROLS + if (inside) InterlockedIncrement64(accepted ? &alias_splits : &alias_refusals); +#endif + if (!accepted) { SetLastError(original_error); return false; } @@ -1151,13 +1460,13 @@ bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, if (!map()) return false; } auto node = nodes.extract(address); - node.mapped() = bytes; + node.mapped() = {bytes, stamp}; memory.runs.insert(std::move(node)); ++stats.mapCalls; return true; } -DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, bool restoring, +DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, bool restoring, ULONG64 stamp, std::vector<ULONG_PTR>& made, X2WPageBatchStats& stats) { DWORD error = ERROR_SUCCESS; @@ -1177,7 +1486,7 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo const auto& next = memory.backings.at(token(end->second)); if (next.section != head.section || next.offset != head.offset + bytes) break; } - if (install_alias_view(address, head, bytes, nodes, stats)) { + if (install_alias_view(address, head, bytes, stamp, nodes, stats)) { made.push_back(address); for (auto page = it; page != end; ++page) page->second.actual = token(page->second); @@ -1188,7 +1497,7 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo // A grouped view may cross placeholder boundaries. Retry each page once. for (auto page = it; page != end; ++page) { if (install_alias_view(page->first, memory.backings.at(token(page->second)), - page_bytes, nodes, stats)) { + page_bytes, stamp, nodes, stats)) { made.push_back(page->first); page->second.actual = token(page->second); } else { @@ -1204,13 +1513,13 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& stats) { - ViewRuns broken; + std::map<ULONG_PTR, SIZE_T> broken; for (const auto& [address, edit] : plan) { if (!edit.old) continue; const auto run = memory.runs.upper_bound(address); - if (run == memory.runs.begin() || address - std::prev(run)->first >= std::prev(run)->second) + if (run == memory.runs.begin() || address - std::prev(run)->first >= std::prev(run)->second.bytes) return E_UNEXPECTED; - broken.insert(*std::prev(run)); + broken.emplace(std::prev(run)->first, std::prev(run)->second.bytes); } for (const auto& [base, size] : broken) { // Surviving neighbours of a shared view are part of the transaction as well. @@ -1226,7 +1535,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& std::vector<ULONG_PTR> made; made.reserve(plan.size()); for (const auto& [address, edit] : plan) { - run_nodes.emplace(address, page_bytes); + run_nodes.emplace(address, PhysicalMemory::Run{page_bytes, 0}); view_nodes.emplace(address, 0); } auto clear_run = [&](ULONG_PTR address, SIZE_T size) { @@ -1235,7 +1544,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& it->second.actual = 0; }; - begin_break(broken); + const ULONG64 stamp = begin_break(); const EndBreak end; DWORD error = ERROR_SUCCESS; for (const auto& [base, size] : broken) { @@ -1247,7 +1556,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& clear_run(base, size); } if (!error) - error = install_alias_plan(plan, run_nodes, share_views, false, made, stats); + error = install_alias_plan(plan, run_nodes, share_views, false, stamp, made, stats); bool restore_failed = false; if (error) { for (const auto address : made) { @@ -1256,11 +1565,11 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& continue; } auto run = memory.runs.extract(address); - clear_run(address, run.mapped()); + clear_run(address, run.mapped().bytes); run_nodes.insert(std::move(run)); } made.clear(); - if (install_alias_plan(plan, run_nodes, share_views, true, made, stats)) + if (install_alias_plan(plan, run_nodes, share_views, true, stamp, made, stats)) restore_failed = true; } // Publish the OS state, including any views left over if Windows refused rollback. @@ -1452,11 +1761,15 @@ extern "C" BOOL WINAPI x2w_xmem_match_section(UINT version, ULONG64 lease, SIZE_ extern "C" BOOL WINAPI x2w_xmem_release_section(UINT version, ULONG64 lease) { - const std::lock_guard guard(memory.mutex); - const auto found = memory.leases.find(lease); - if (found == memory.leases.end() || found->second.version != version) return FALSE; - for (const auto& slot : found->second.slots) unpin_slot(slot); - memory.leases.erase(found); + std::vector<HANDLE> closed; + { + const std::lock_guard guard(memory.mutex); + const auto found = memory.leases.find(lease); + if (found == memory.leases.end() || found->second.version != version) return FALSE; + for (const auto& slot : found->second.slots) unpin_slot(slot, &closed); + memory.leases.erase(found); + } + for (const HANDLE slab : closed) CloseHandle(slab); return TRUE; } @@ -1471,9 +1784,73 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) return TRUE; } +// Runs fn(context) so that its answer does not come from inside a run break: the moment, under memory.mutex, +// when a run of shared views is unmapped and its surviving pages are mapped again (map_pages_locked, +// remap_alias_pages). A thread that touches such a page faults and retry_remapped_page retries it, but a region +// query (VirtualQuery) or a kernel copy (ReadProcessMemory) does not fault: inside the break it reports the pages +// as reserved, or fails. fn must be a query, or a copy into the caller's memory, that can simply run again, and +// must not take memory.mutex or call the mapping exports. +// Without shared views (X2W_XMEM_SHARED_VIEWS unset, or no mapping call yet) fn runs once, directly: every page has +// a view of its own, so no break takes a page away from a reader. With them fn runs once when no break begins or +// ends around it (the break generation is even before and unchanged after), which is nearly every call; otherwise +// it runs again under memory.mutex, so after the break. A thread that holds memory.mutex runs it directly. +extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context) +{ + if (!fn) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + if (mapping_thread || !shared_views_on.load(std::memory_order_acquire)) { + fn(context); + return TRUE; + } + const auto generation = [] { + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; + }; + const ULONG64 before = generation(); + if (!(before & 1)) { + fn(context); + if (generation() == before) return TRUE; + } + const MappingThread marker; + const std::lock_guard guard(memory.mutex); + fn(context); + return TRUE; +} + +// Test export: MapViewOfFile3 and placeholder-split attempts made by the physical-page map path so far. +extern "C" BOOL WINAPI x2w_xmem_map_counts(ULONGLONG* maps, ULONGLONG* splits) +{ + if (!maps || !splits) return FALSE; + *maps = static_cast<ULONGLONG>(map_attempts); + *splits = static_cast<ULONGLONG>(split_attempts); + return TRUE; +} + +// Test export, counted in the test-controls build only: views X2WMapPageBatch could not map in place inside an +// owned reservation whose range alias_placeholders refused, and those for which it tried a placeholder release. +// The deployed build returns FALSE with ERROR_NOT_SUPPORTED. +extern "C" BOOL WINAPI x2w_xmem_alias_counts(ULONGLONG* refusals, ULONGLONG* splits) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (!refusals || !splits) return FALSE; + *refusals = static_cast<ULONGLONG>(alias_refusals); + *splits = static_cast<ULONGLONG>(alias_splits); + return TRUE; +#else + (void)refusals; + (void)splits; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; +#endif +} + // Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free -// in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and it is closed only at process end, so -// a slot freed by a grant stays committed and these numbers do not show the commit held. +// in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs +// are closed when all of their slots are freed and unpinned. extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in_use, ULONGLONG* slots_free) { if (!slabs || !slots_in_use || !slots_free) return FALSE; @@ -1517,6 +1894,152 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) return TRUE; } +namespace { +// Keep the guarded copy out of functions that need unwinding (as read_alias_record). +bool copy_guarded(void* destination, const void* data, SIZE_T bytes) noexcept +{ + __try { + std::memcpy(destination, data, bytes); + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || + GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +// The longest hold of memory.mutex by a destination copy, and the largest copy, so far (under memory.mutex). +double copy_hold_max_ms = 0; +SIZE_T copy_bytes_max = 0; +#ifdef X2W_XMEM_TEST_CONTROLS +// Test build only (x2w_xmem_copy_counts): destination copies made under memory.mutex and without it. +volatile LONG64 locked_copies, unlocked_copies; +#endif + +// Whether [address, address + bytes) overlaps a recorded run. Caller holds memory.mutex. +bool overlaps_run(ULONG_PTR address, SIZE_T bytes) +{ + if (!bytes) return false; + const auto run = memory.runs.upper_bound(address); + if (run != memory.runs.begin() && address - std::prev(run)->first < std::prev(run)->second.bytes) return true; + return run != memory.runs.end() && run->first - address < bytes; +} + +// [destination, destination + capacity) committed and writable: resident read-write pages from their working-set +// attributes, any other page through the region walk (as XCRDAPI's destination check without xmem.dll). +bool destination_writable(void* destination, SIZE_T capacity) +{ + const auto start = reinterpret_cast<ULONG_PTR>(destination); + if (capacity && destination && capacity <= ~ULONG_PTR{0} - start && + x2w_local::resident_read_write(start, start + capacity)) + return true; + return x2w_local::committed_writable(destination, capacity); +} +} // namespace + +// The DirectStorage stand-in's copy into a plain-memory destination (XCRDAPI): the check that all of +// [destination, destination + capacity) is committed and writable, then the copy of bytes from data. Unmapping a page +// of a shared run takes the whole run away until its other pages are mapped again (map_pages_locked, +// remap_alias_pages, merge_with_previous), all under memory.mutex. With shared views on (shared_views_on), a short +// hold of that mutex first looks up whether either range overlaps a recorded run. If one does, the check and the +// copy run under the mutex, so neither can fall into that window and no such window can open while the copy runs. +// Otherwise, and always with shared views off (every page then has a view of its own, and no unmap takes a +// neighbour away), both run without the mutex, as in XCRDAPI without xmem.dll. A run can then appear over either +// range only through a mapping call on those addresses during the copy, which is the caller's race. Lazily mapped +// pages of both ranges are committed first, before any mutex: a fault under it is passed on (mapping_thread), not +// served. +// TRUE when the bytes were copied. FALSE with ERROR_NOACCESS when the destination is not writable (nothing is +// written), ERROR_INVALID_ADDRESS when the copy faulted (a source page not readable, or a destination page that +// stopped being writable during the copy; part of the destination may be written), or ERROR_INVALID_PARAMETER for +// more bytes than capacity or null data. +// Test build only: X2W_XMEM_TEST_COPY_ERROR=<code> fails every copy with that error before anything is written +// (startup_dstorage_break_window_check outcomes: XCRDAPI's logged outcome per error). +extern "C" BOOL WINAPI x2w_xmem_copy_to_destination(void* destination, SIZE_T capacity, const void* data, SIZE_T bytes) +{ + if (bytes > capacity || (bytes && !data)) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } +#ifdef X2W_XMEM_TEST_CONTROLS + char forced[16]; + if (GetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", forced, sizeof(forced)) && forced[0]) { + SetLastError(static_cast<DWORD>(std::strtoul(forced, nullptr, 10))); + return FALSE; + } +#endif + const auto start = reinterpret_cast<ULONG_PTR>(destination); + if (capacity && destination && capacity <= ~ULONG_PTR{0} - start) x2w_xmem_commit_range(destination, capacity); + if (bytes) x2w_xmem_commit_range(data, bytes); + DWORD error = ERROR_SUCCESS; + bool in_runs = false; + if (shared_views_on.load(std::memory_order_acquire)) { + const std::lock_guard guard(memory.mutex); + in_runs = overlaps_run(start, capacity) || overlaps_run(reinterpret_cast<ULONG_PTR>(data), bytes); + } + if (!in_runs) { +#ifdef X2W_XMEM_TEST_CONTROLS + InterlockedIncrement64(&unlocked_copies); +#endif + if (!destination_writable(destination, capacity)) + error = ERROR_NOACCESS; + else if (bytes && !copy_guarded(destination, data, bytes)) + error = ERROR_INVALID_ADDRESS; + SetLastError(error); + return error == ERROR_SUCCESS; + } + double held_ms = 0; + bool longest = false, largest = false; + { + const MappingThread marker; + const std::lock_guard guard(memory.mutex); +#ifdef X2W_XMEM_TEST_CONTROLS + InterlockedIncrement64(&locked_copies); +#endif + LARGE_INTEGER frequency{}, begin{}, end{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&begin); + if (!destination_writable(destination, capacity)) + error = ERROR_NOACCESS; + else if (bytes && !copy_guarded(destination, data, bytes)) + error = ERROR_INVALID_ADDRESS; + QueryPerformanceCounter(&end); + held_ms = frequency.QuadPart ? 1000.0 * static_cast<double>(end.QuadPart - begin.QuadPart) / frequency.QuadPart : 0; + if (held_ms > copy_hold_max_ms) { + copy_hold_max_ms = held_ms; + longest = true; + } + if (!error && bytes > copy_bytes_max) { + copy_bytes_max = bytes; + largest = true; + } + } + // A line per new maximum (about the logarithm of the number of copies), logged after the mutex is released. + static volatile LONG lines; + if ((longest || largest) && x2w_local::first_calls(lines, 64)) + x2w_local::logf("x2w-xmem destination copy: %s%s%.3f ms under the mapping mutex for 0x%llx bytes (capacity 0x%llx)", + longest ? "longest hold so far, " : "", largest ? "largest copy so far, " : "", held_ms, + static_cast<unsigned long long>(bytes), static_cast<unsigned long long>(capacity)); + SetLastError(error); + return error == ERROR_SUCCESS; +} + +// Test export, counted in the test-controls build only: destination copies (x2w_xmem_copy_to_destination) made under +// memory.mutex because a range overlapped a run, and those made without it. The deployed build returns FALSE with +// ERROR_NOT_SUPPORTED. +extern "C" BOOL WINAPI x2w_xmem_copy_counts(ULONGLONG* locked, ULONGLONG* unlocked) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (!locked || !unlocked) return FALSE; + *locked = static_cast<ULONGLONG>(locked_copies); + *unlocked = static_cast<ULONGLONG>(unlocked_copies); + return TRUE; +#else + (void)locked; + (void)unlocked; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; +#endif +} + // Experimental export (X2W_XMEM_LAZY_STARTUP): commits the whole lazy startup block holding address and stops // committing it lazily. A GPU heap opened on the block covers the committed run from its base and is reused for // later resources in the block, so the block is committed whole before the first one is placed. TRUE without the @@ -1624,11 +2147,139 @@ const bool lazy_commit_installed = [] { } return true; }(); + +// With X2W_XMEM_SHARED_VIEWS=1 the main module's VirtualQueryEx imports answer outside run breaks +// (x2w_xmem_stable_call): inside one, a page of the run being taken apart reads as reserved. A query of another +// process runs the same way; it only costs the retry. The module is pinned once an import points into it (a main +// module without the import leaves it unloadable, as before); if the pin is refused, the imports are restored. +using VirtualQueryExFn = SIZE_T(WINAPI*)(HANDLE, LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T); +VirtualQueryExFn real_virtual_query_ex; + +// The answer goes to a local buffer and is copied to the caller's after x2w_xmem_stable_call: on its mutex path the +// lazy-commit handler passes faults on (MappingThread), so a write into an uncommitted mapped slot would not be +// committed there. +SIZE_T WINAPI virtual_query_ex_stable(HANDLE process, LPCVOID address, PMEMORY_BASIC_INFORMATION info, SIZE_T bytes) +{ + if (!info || bytes < sizeof(MEMORY_BASIC_INFORMATION)) return real_virtual_query_ex(process, address, info, bytes); + struct Query { + HANDLE process; + LPCVOID address; + MEMORY_BASIC_INFORMATION info; + SIZE_T result; + DWORD error; + } query{process, address, {}, 0, ERROR_SUCCESS}; + x2w_xmem_stable_call([](void* context) { + auto& q = *static_cast<Query*>(context); + q.result = real_virtual_query_ex(q.process, q.address, &q.info, sizeof(q.info)); + q.error = GetLastError(); + }, &query); + if (query.result) std::memcpy(info, &query.info, query.result); + SetLastError(query.error); + return query.result; +} + +const int virtual_query_ex_wrapped = [] { + if (!x2w_local::env_on("X2W_XMEM_SHARED_VIEWS")) return 0; + real_virtual_query_ex = reinterpret_cast<VirtualQueryExFn>(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "VirtualQueryEx")); + if (!real_virtual_query_ex) return 0; + int queries = patch_main_import("VirtualQueryEx", reinterpret_cast<const void*>(&virtual_query_ex_stable)); + HMODULE self = nullptr; + if (queries && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast<LPCWSTR>(&virtual_query_ex_stable), &self)) { + const DWORD error = GetLastError(); + const int restored = patch_main_import("VirtualQueryEx", reinterpret_cast<const void*>(real_virtual_query_ex)); + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): xmem.dll could not be pinned (error %lu); " + "%d of %d VirtualQueryEx import(s) restored", static_cast<unsigned long>(error), restored, queries); + queries = 0; + } + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d VirtualQueryEx import(s) answer outside run breaks", + queries); + return queries; +}(); + +// With X2W_XMEM_SHARED_VIEWS=1 the main module's ReadFile and WriteFile imports also go around run breaks. Inside one, +// a kernel copy into or out of a page of the run being taken apart fails at once, with no fault to retry. Measured +// under Wine (tests/xmem_run_break_readers_check.cpp, ReadFile_import and WriteFile_import): ReadFile fails with +// ERROR_NOACCESS and leaves the file position where it was, WriteFile with ERROR_INVALID_USER_BUFFER. A synchronous +// call (no OVERLAPPED) on a disk file that fails with one of those while a break was in progress, or began or ended +// around it, and whose buffer lies in a run, waits for memory.mutex (the end of the break) and runs again, at most +// io_attempts times in all. A call that fails that way with no break around it, outside the runs, or on a handle that +// is not a disk file, fails at once as before: a pipe, socket or console may have consumed or sent data in the failed +// call, so running it again could lose or repeat that data. Under Wine a pipe read that fails this way leaves its data +// queued; whether Windows consumes it is unmeasured. GetFileType is asked only on that failure path. +// Not covered: overlapped I/O (the copy happens at completion, after the call has returned), a call that a break +// cuts short after part of the copy (a short count), and I/O from other modules or through GetProcAddress. +using WriteFileFn = BOOL(WINAPI*)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED); +ReadFileFn next_read_file; // read_file_committed with lazy commit, kernel32's ReadFile without +WriteFileFn kernel_write_file; +constexpr int io_attempts = 4; + +// Whether [buffer, buffer + bytes) holds a page of a run. Takes memory.mutex, so it returns after the break in progress. +bool in_a_run(const void* buffer, DWORD bytes) +{ + const std::lock_guard guard(memory.mutex); + return overlaps_run(reinterpret_cast<ULONG_PTR>(buffer), bytes); +} + +template <class Call> +BOOL io_outside_breaks(HANDLE file, const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, const Call& call) +{ + if (overlapped || !buffer || !bytes || mapping_thread || !shared_views_on.load(std::memory_order_acquire)) return call(); + for (int attempt = 1;; ++attempt) { + const ULONG64 before = break_generation(); + if (call()) return TRUE; + const DWORD error = GetLastError(); + const bool broken = (before & 1) || break_generation() != before; + if ((error != ERROR_NOACCESS && error != ERROR_INVALID_USER_BUFFER) || !broken || attempt == io_attempts || + GetFileType(file) != FILE_TYPE_DISK || !in_a_run(buffer, bytes)) { + SetLastError(error); + return FALSE; + } + } +} + +BOOL WINAPI read_file_stable(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) +{ + return io_outside_breaks(file, buffer, bytes, overlapped, [&] { return next_read_file(file, buffer, bytes, read, overlapped); }); +} + +BOOL WINAPI write_file_stable(HANDLE file, LPCVOID buffer, DWORD bytes, LPDWORD written, LPOVERLAPPED overlapped) +{ + return io_outside_breaks(file, buffer, bytes, overlapped, [&] { return kernel_write_file(file, buffer, bytes, written, overlapped); }); +} + +const int file_io_wrapped = [] { + if (!x2w_local::env_on("X2W_XMEM_SHARED_VIEWS")) return 0; + const HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); + const auto kernel_read_file = reinterpret_cast<ReadFileFn>(GetProcAddress(kernel32, "ReadFile")); + kernel_write_file = reinterpret_cast<WriteFileFn>(GetProcAddress(kernel32, "WriteFile")); + if (!kernel_read_file || !kernel_write_file) return 0; + // With lazy commit the ReadFile imports already point at read_file_committed, which stays the inner call. + next_read_file = lazy_commit_installed && real_read_file ? &read_file_committed : kernel_read_file; + int wrapped = patch_main_import("ReadFile", reinterpret_cast<const void*>(&read_file_stable)); + wrapped += patch_main_import("WriteFile", reinterpret_cast<const void*>(&write_file_stable)); + HMODULE self = nullptr; + if (wrapped && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast<LPCWSTR>(&read_file_stable), &self)) { + const DWORD error = GetLastError(); + const int restored = patch_main_import("ReadFile", reinterpret_cast<const void*>(next_read_file)) + + patch_main_import("WriteFile", reinterpret_cast<const void*>(kernel_write_file)); + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): xmem.dll could not be pinned (error %lu); " + "%d of %d ReadFile/WriteFile import(s) restored", static_cast<unsigned long>(error), restored, wrapped); + wrapped = 0; + } + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d ReadFile/WriteFile import(s) run again after a run " + "break that refused their buffer", wrapped); + return wrapped; +}(); } // namespace // Experimental export: writes bytes into physical pages named by the title's // page tokens (page number << 4, as XMemMapPhysicalPages takes them), starting offset bytes into the -// first page. DirectStorage requests can name such pages as their destination. +// first page. DirectStorage requests can name such pages as their destination. A token that names +// no granted page is refused like a mapping of it (ERROR_INVALID_PARAMETER): a section for a page +// nobody owns would stay until that page number is granted again, and that grant would map its +// bytes instead of zeros. extern "C" BOOL WINAPI x2w_xmem_write_physical(const ULONG_PTR* tokens, ULONG_PTR count, SIZE_T offset, const void* data, SIZE_T bytes) { X2W_ZONE("x2w_xmem_write_physical"); @@ -1641,6 +2292,7 @@ extern "C" BOOL WINAPI x2w_xmem_write_physical(const ULONG_PTR* tokens, ULONG_PT ULONG64 section_offset = 0; { const std::lock_guard guard(memory.mutex); + if (!era_physical::owns(tokens[index] >> 4)) return physical_result(era_physical::Status::invalid); section = section_for(tokens[index] >> 4); if (section) section_offset = memory.backings.at(tokens[index] >> 4).offset; } @@ -1777,7 +2429,7 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG } const bool below_40 = large_pages && attributes == 0x283 && x2w_local::env_on("X2W_XMEM_STARTUP_BELOW_40"); // X2W_XMEM_LAZY_STARTUP: a large block is reserved and committed on first touch (lazy_startup). - const bool lazy = lazy_startup() && bytes >= lazy_block_min && !below_40; + const bool lazy = lazy_startup() && bytes >= lazy_block_min; const DWORD type = lazy ? MEM_RESERVE : MEM_RESERVE | MEM_COMMIT; void* block = nullptr; if (!large_pages) { @@ -1792,7 +2444,7 @@ static void* commit_startup_block(SIZE_T bytes, DWORD allocation_type, ULONGLONG parameter.Type = MemExtendedParameterAddressRequirements; parameter.Pointer = &requirements; block = VirtualAlloc2(GetCurrentProcess(), nullptr, bytes, type, PAGE_READWRITE, ¶meter, 1); - if (below_40) return keep_startup_block_below_40(block, bytes, attributes, protection); + if (below_40) block = keep_startup_block_below_40(block, bytes, attributes, protection); } if (block && lazy) { bool listed = false; diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index a5b43f0f1d..61f64e716f 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -15,6 +15,7 @@ #include "era_title_gpu.h" #include "xmem_gpu_usage.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/profile_zone.h" #include <unordered_set> @@ -83,17 +84,19 @@ bool local_free(void* block) extern "C" void* XMemAlloc(SIZE_T bytes, ULONGLONG attributes) { void* allocation = era_heap::allocate(bytes, attributes); - if (!allocation && bytes && x2w_local::env_on("X2W_XMEM_PERMISSIVE")) return local_alloc(bytes, attributes); // Desktop policy: graphics memory types count as GPU-intended for XMemVirtualQuery. - if (allocation && is_graphics(attributes) && !era_title_gpu::track(allocation, bytes)) { + if (!allocation && bytes && x2w_local::env_on("X2W_XMEM_PERMISSIVE")) allocation = local_alloc(bytes, attributes); + else if (allocation && is_graphics(attributes) && !era_title_gpu::track(allocation, bytes)) { era_heap::release_with_attributes(allocation, attributes); return nullptr; } + if (allocation) X2W_ALLOC(allocation, bytes, "XMemAlloc"); return allocation; } extern "C" void XMemFree(void* allocation, ULONGLONG attributes) { + if (allocation) X2W_FREE(allocation, "XMemAlloc"); if (allocation && local_free(allocation)) return; if (allocation && is_graphics(attributes)) { era_title_gpu::untrack(allocation); @@ -101,9 +104,28 @@ extern "C" void XMemFree(void* allocation, ULONGLONG attributes) era_heap::release_with_attributes(allocation, attributes); } +extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context); + +// The answer for a page of a shared-view run is taken outside a run break (x2w_xmem_stable_call): inside one the +// page would read as reserved. era_query writes a local buffer, and on success its tail_offset + 1 bytes (the MBI and +// the tail byte, all that era_query writes) go to the caller's after the call: on stable_call's mutex path the +// lazy-commit handler passes faults on, so an uncommitted mapped slot is not written there. The caller's buffer is +// not read, and nothing is written to it on failure. extern "C" BOOL XMemVirtualQuery(HANDLE process, LPCVOID address, void* buffer) { - return era_query::query(process, address, buffer, query_buffer_bytes) != 0; + struct Query { + HANDLE process; + LPCVOID address; + unsigned char* buffer; + unsigned char copy[query_buffer_bytes]; + std::size_t result; + } query{process, address, static_cast<unsigned char*>(buffer), {}, 0}; + x2w_xmem_stable_call([](void* context) { + auto& q = *static_cast<Query*>(context); + q.result = era_query::query(q.process, q.address, q.buffer ? q.copy : nullptr, query_buffer_bytes); + }, &query); + if (query.buffer && query.result) std::memcpy(query.buffer, query.copy, era_query::tail_offset + 1); + return query.result != 0; } // Desktop policy (docs/experiments.md): writes only +8, with this process's GPU memory in bytes; diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 3776c7529f..5ff7b8500d 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -22,3 +22,8 @@ EXPORTS x2w_xmem_release_section @20 x2w_xmem_match_section @21 X2WMapPageBatch @22 + x2w_xmem_copy_to_destination @23 + x2w_xmem_copy_counts @24 + x2w_xmem_map_counts @25 + x2w_xmem_stable_call @26 + x2w_xmem_alias_counts @27 diff --git a/src/xmem_slab_slots.h b/src/xmem_slab_slots.h index 1b9095cc7c..5f060196be 100644 --- a/src/xmem_slab_slots.h +++ b/src/xmem_slab_slots.h @@ -5,8 +5,9 @@ // // A slab holds 4096 slots (256 MiB of 64 KiB pages). Slots are handed out in order from the newest slab; a // released slot goes back to an ordered set and is reused lowest first, so pages that are reused together -// are adjacent slots again. Slabs are never closed while the object lives. A slab is only reserved; its slots -// are committed by the caller on first use. This class reports how many slabs are open and how many slots are used. +// are adjacent slots again. Slabs are reclaimed explicitly via reclaim_empty_slabs() once all of their slots +// are released. A slab is only reserved; its slots are committed by the caller on first use. This class reports +// how many slabs are open and how many slots are used. #include <cstddef> #include <cstdint> #include <set> @@ -41,7 +42,11 @@ class SlabSlots { void take_lowest_free() { - if (!free_.empty()) free_.erase(free_.begin()); + if (free_.empty()) return; + const auto it = free_.begin(); + ++slab_used_[it->first]; + ++total_used_; + free_.erase(it); } // The next never-used slot of the newest slab. When there is none, make(Handle&) creates a slab; if it @@ -55,14 +60,20 @@ class SlabSlots { if (!make(slab)) return false; try { slabs_.push_back(slab); + slab_used_.push_back(0); } catch (...) { + if (slabs_.size() > slab_used_.size()) slabs_.pop_back(); discard(slab); throw; } + ++open_slabs_; fresh_used_ = 0; } - out = Slot{slabs_.back(), slabs_.size() - 1, fresh_used_ * slot_bytes_}; + const std::size_t index = slabs_.size() - 1; + out = Slot{slabs_[index], index, fresh_used_ * slot_bytes_}; ++fresh_used_; + ++slab_used_[index]; + ++total_used_; return true; } @@ -70,33 +81,63 @@ class SlabSlots { void unwind_fresh(const Slot& slot) { if (!slabs_.empty() && fresh_used_ && slot.slab_index == slabs_.size() - 1 && - slot.offset == (fresh_used_ - 1) * slot_bytes_) + slot.offset == (fresh_used_ - 1) * slot_bytes_) { --fresh_used_; + --slab_used_[slot.slab_index]; + --total_used_; + } } // Returns a slot. False, with nothing changed, for a slot that was never handed out or is already free. bool release(std::size_t slab_index, std::uint64_t offset) { - if (slab_index >= slabs_.size() || offset % slot_bytes_ || offset >= slab_bytes()) return false; + if (slab_index >= slabs_.size() || slabs_[slab_index] == Handle{} || offset % slot_bytes_ || + offset >= slab_bytes()) + return false; if (slab_index == slabs_.size() - 1 && offset / slot_bytes_ >= fresh_used_) return false; - return free_.emplace(slab_index, offset).second; + if (!free_.emplace(slab_index, offset).second) return false; + --slab_used_[slab_index]; + --total_used_; + return true; + } + + // Closes open slabs with zero used slots and drops their free entries. Non-trailing slabs become + // Handle{} tombstones to preserve existing slab indices; trailing empty slabs are popped. + template <class Close> + void reclaim_empty_slabs(Close&& close) + { + for (std::size_t i = 0; i < slabs_.size(); ++i) { + if (slabs_[i] == Handle{} || slab_used_[i] != 0) continue; + auto it = free_.lower_bound(std::make_pair(i, std::uint64_t{0})); + while (it != free_.end() && it->first == i) it = free_.erase(it); + const bool was_last = (i == slabs_.size() - 1); + Handle h = std::move(slabs_[i]); + slabs_[i] = Handle{}; + --open_slabs_; + if (was_last) { + while (!slabs_.empty() && slabs_.back() == Handle{}) { + slabs_.pop_back(); + slab_used_.pop_back(); + } + fresh_used_ = slabs_.empty() ? 0 : slots_per_slab; + } + close(h); + } } const std::vector<Handle>& slabs() const { return slabs_; } - std::uint64_t slab_count() const { return slabs_.size(); } + std::uint64_t slab_count() const { return open_slabs_; } // Slots handed out and not released. - std::uint64_t slots_in_use() const { return handed_out() - free_.size(); } + std::uint64_t slots_in_use() const { return total_used_; } // Slots of the open slabs that are not in use: released ones and those never handed out. - std::uint64_t slots_free() const { return slabs_.size() * slots_per_slab - slots_in_use(); } + std::uint64_t slots_free() const { return slab_count() * slots_per_slab - slots_in_use(); } private: - std::uint64_t handed_out() const - { - return slabs_.empty() ? 0 : (slabs_.size() - 1) * slots_per_slab + fresh_used_; - } - std::uint64_t slot_bytes_; std::vector<Handle> slabs_; + std::vector<std::uint16_t> slab_used_; + std::size_t open_slabs_ = 0; + std::uint64_t total_used_ = 0; std::uint64_t fresh_used_ = 0; // slots handed out from the newest slab std::set<std::pair<std::size_t, std::uint64_t>> free_; // (slab index, offset) }; diff --git a/tests/adapter_name_filter.h b/tests/adapter_name_filter.h new file mode 100644 index 0000000000..a82ebbe021 --- /dev/null +++ b/tests/adapter_name_filter.h @@ -0,0 +1,37 @@ +#pragma once + +#include <windows.h> +#include <cstdio> +#include <cwchar> +#include <iterator> + +// Hardware fixtures match XBOX2WINDOWS_ADAPTER against the DXGI description. +class AdapterNameFilter { +public: + bool read() + { + length = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + if (length < std::size(name)) return true; + std::fputs("XBOX2WINDOWS_ADAPTER is longer than 127 characters\n", stderr); + return false; + } + + bool matches(const wchar_t* description) const + { + if (!length) return true; + for (const wchar_t* p = description; *p; ++p) + if (_wcsnicmp(p, name, length) == 0) return true; + return false; + } + + int no_match() const + { + if (!length) return 77; + std::fprintf(stderr, "No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", name); + return 4; + } + +private: + wchar_t name[128]{}; + DWORD length = 0; +}; diff --git a/tests/bcpack_format_fixtures.h b/tests/bcpack_format_fixtures.h new file mode 100644 index 0000000000..2dbd7fab74 --- /dev/null +++ b/tests/bcpack_format_fixtures.h @@ -0,0 +1,85 @@ +// Synthetic lane inputs, independent of the decoder's predictor and rank tables. +// SPDX-License-Identifier: MIT +#pragma once +#include "bcpack_encoder.h" +#include <algorithm> + +namespace bcpack_fixture { +inline constexpr uint8_t AB[7][16] = { + {7,7,4,5,4,4,5,4,7,7,7,7}, + {3,3,3,3,3,3,3,3,3,3,4,5,4,7,7}, + {3,3,7,5,5,5,5,4,5,4,7,7}, + {7,7,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,5,5,5,5,5,5,5,5}, + {3,3,7,7,7,4,4,4,5,5,5,7,7,7,7,4}, + {3,3,7,7,7,7,7,6,6,4,5,7,7,7,7,4}, +}; +inline size_t lanes(unsigned fmt) { return fmt >= 6 ? 16 : fmt == 2 ? 15 : 12; } +inline size_t per(unsigned fmt) { return fmt == 1 || fmt == 4 ? 1 : 2; } +inline size_t block_bytes(unsigned fmt) { return 8 * per(fmt); } + +inline void byte_symbols(std::vector<uint16_t>& s, size_t at, unsigned value, size_t p) { + if (p == 1) { s[at] = static_cast<uint16_t>(value); return; } + for (unsigned h = 0; h < 2; ++h) { + s[at+h] = 0; + for (unsigned b = 0; b < 4; ++b) s[at+h] |= ((value >> (2*b+h)) & 1) << b; + } +} + +inline std::vector<uint16_t> reference_symbols(unsigned fmt, unsigned er, unsigned xr, unsigned mode) { + const size_t p = per(fmt); + std::vector<uint16_t> s(lanes(fmt)*p, 0); + const int delta = static_cast<int>((er-xr+128)&255)-128; + byte_symbols(s,0,delta >= 0 ? 2*delta : -2*delta-1,p); + byte_symbols(s,p,xr,p); + if (fmt == 6) { s[30] = static_cast<uint16_t>(mode); s[31] = er & 31; } + return s; +} + +inline std::vector<uint16_t> random_symbols(unsigned fmt, size_t blocks, uint64_t seed) { + const size_t target = per(fmt)*blocks; + std::vector<uint16_t> s(lanes(fmt)*target); + bcpack_test::Rng rng{seed}; + for (size_t l = 0; l < lanes(fmt); ++l) + for (size_t i = 0; i < target; ++i) s[l*target+i] = static_cast<uint16_t>(rng.below(1u << (AB[fmt-1][l]+1))); + if (fmt == 6) { + for (size_t i = 0; i < blocks; ++i) { + s[15*target+2*i] = static_cast<uint16_t>(i%14); + s[15*target+2*i+1] = static_cast<uint16_t>(i%32); + } + } else if (fmt == 7) { + // Choose all mapped controls; expected BC7 bytes still come from the oracle. + std::vector<unsigned> codes; + for (unsigned c = 0; c < 512; ++c) + if (x2w_bcpack::BC7_CONTROL_TABLE[c].valid) codes.push_back(c); + for (size_t i = 0; i < blocks; ++i) { + const unsigned code = codes[i%codes.size()]; + s[15*target+2*i] = code & 31; + s[15*target+2*i+1] = code >> 5; + } + } + return s; +} + +inline bool encode(unsigned fmt, const std::vector<uint16_t>& s, size_t blocks, std::vector<uint8_t>& stream) { + const size_t target = blocks*per(fmt), n = lanes(fmt); + if (!target || s.size() != n*target) return false; + std::vector<std::vector<uint8_t>> encoded(n); + for (size_t l = 0; l < n; ++l) { + for (size_t at = 0; at < target;) { + const size_t count = std::min(size_t(128),target-at); + bool ok = false; + for (uint8_t q = 0; q < 16 && !ok; ++q) { + std::vector<uint8_t> fragment; + if (bcpack_test::encode_fragment(AB[fmt-1][l],0,q,s.data()+l*target+at,count,true,fragment)) { + encoded[l].insert(encoded[l].end(),fragment.begin(),fragment.end()); + ok = true; + } + } + if (!ok) return false; + at += count; + } + } + return bcpack_test::interleave(encoded,AB[fmt-1],n,target,stream); +} +} // namespace bcpack_fixture diff --git a/tests/bcpack_formats_check.cpp b/tests/bcpack_formats_check.cpp new file mode 100644 index 0000000000..5f74f9dc71 --- /dev/null +++ b/tests/bcpack_formats_check.cpp @@ -0,0 +1,120 @@ +// Oracle-derived golden hashes of source-built synthetic streams. No SDK at test/run time. +// Optional --oracle ABSOLUTE_DLL_PATH regenerates hashes using an installed developer oracle. +// See docs/experiments/bcpack-standalone.md for provenance and commands. +// SPDX-License-Identifier: MIT +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> +#include "bcpack_format_fixtures.h" +#include "bcpack_formats_goldens.h" +#include <cstdio> +#include <string> + +namespace { +using Oracle = long (__cdecl*)(size_t,void*,size_t,const void*,size_t); +Oracle oracle = nullptr; +bool mutate = false; +size_t cases = 0; + +uint64_t hash(uint64_t h, const std::vector<uint8_t>& bytes) { + for (uint8_t b : bytes) { h ^= b; h *= 1099511628211ull; } + return h; +} + +bool check(unsigned fmt, const std::vector<uint16_t>& s, size_t blocks, uint64_t& h) { + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,blocks,packed)) return false; + const size_t size = blocks*bcpack_fixture::block_bytes(fmt); + std::vector<uint8_t> expected(size), guarded(size+32,0xa5); + if (oracle) { + if (oracle(fmt,expected.data(),size,packed.data(),packed.size()) < 0) return false; + } else { + bool first = true; + for (int path = 0; path < x2w_bcpack::LANE_PATH_COUNT; ++path) { + if (!x2w_bcpack::lane_path_supported(path)) continue; + x2w_bcpack::lane_path_override = path; + std::fill(guarded.begin(),guarded.end(),0xa5); + size_t produced = 123; + if (!x2w_bcpack::decode_bcpack(packed.data(),packed.size(),fmt,guarded.data()+16,size,&produced) || produced != size) + return false; + for (size_t i = 0; i < 16; ++i) + if (guarded[i] != 0xa5 || guarded[size+16+i] != 0xa5) return false; + if (first) { + std::copy(guarded.begin()+16,guarded.end()-16,expected.begin()); + first = false; + } else if (!std::equal(expected.begin(),expected.end(),guarded.begin()+16)) return false; + } + } + if (mutate && fmt == 2 && cases == 0) expected[0] ^= 1; + h = hash(h,expected); + ++cases; + return true; +} + +bool group(unsigned fmt, int mode, uint64_t expected) { + uint64_t h = 14695981039346656037ull; + cases = 0; + if (mode >= 0) { + for (unsigned r = 0; r < 256; ++r) { + const unsigned ep[] = {r,0,r}, ix[] = {0,r,(r*73+19)&255}; + for (unsigned k = 0; k < 3; ++k) + if (!check(fmt,bcpack_fixture::reference_symbols(fmt,ep[k],ix[k],mode),1,h)) return false; + } + } else { + for (size_t blocks : {size_t(2),size_t(17),size_t(255),size_t(256),size_t(257),size_t(1024)}) + if (!check(fmt,bcpack_fixture::random_symbols(fmt,blocks,0xbc9900+fmt+blocks),blocks,h)) return false; + } + std::printf("BC%u mode %d: %zu cases, %016llx%s\n",fmt,mode,cases, + static_cast<unsigned long long>(h), oracle || h == expected ? "" : " MISMATCH"); + return oracle || h == expected; +} + +bool failures() { + for (unsigned fmt = 1; fmt <= 7; ++fmt) { + auto s = bcpack_fixture::random_symbols(fmt,17,0x1122+fmt); + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,17,packed)) return false; + const size_t size = 17*bcpack_fixture::block_bytes(fmt); + std::vector<uint8_t> out(size+32,0xa5); + auto reject = [&](size_t input_size, size_t output_size, unsigned format) { + size_t produced = 123; + return !x2w_bcpack::decode_bcpack(packed.data(),input_size,format,out.data()+16,output_size,&produced) && produced == 0 && + std::all_of(out.begin(),out.end(),[](uint8_t b){return b == 0xa5;}); + }; + if (!reject(1,size,fmt) || !reject(packed.size(),size-1,fmt) || + !reject(packed.size(),size,0) || !reject(packed.size(),size,8)) return false; + packed.push_back(0xff); + if (!reject(packed.size(),size,fmt)) return false; + } + // A valid entropy stream can still contain an undefined BC6H mode. + std::vector<uint16_t> s(32,0); + s[30] = 14; + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(6,s,1,packed)) return false; + uint8_t out[16] = {}; size_t produced = 123; + return !x2w_bcpack::decode_bcpack(packed.data(),packed.size(),6,out,sizeof(out),&produced) && produced == 0; +} +} // namespace + +int main(int argc, char** argv) { + HMODULE library = nullptr; + if (argc == 3 && std::string(argv[1]) == "--oracle") { + library = LoadLibraryExA(argv[2],nullptr,LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!library) return 2; + oracle = reinterpret_cast<Oracle>(GetProcAddress(library,"BCPackDecompress")); + if (!oracle) { FreeLibrary(library); return 2; } + } else if (argc == 2 && std::string(argv[1]) == "--mutate") mutate = true; + else if (argc != 1) return 2; + bool ok = true; + for (unsigned fmt : {1u,2u,6u}) { + const unsigned modes = fmt == 6 ? 14 : 1; + for (unsigned mode = 0; mode < modes; ++mode) + ok = group(fmt,mode,BCPACK_REFERENCE_GOLDENS[fmt == 1 ? 0 : fmt == 2 ? 1 : mode+2]) && ok; + } + for (unsigned fmt = 1; fmt <= 7; ++fmt) + ok = group(fmt,-1,BCPACK_RANDOM_GOLDENS[fmt-1]) && ok; + if (!oracle) ok = failures() && ok; + if (library) FreeLibrary(library); + std::puts(ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/tests/bcpack_formats_goldens.h b/tests/bcpack_formats_goldens.h new file mode 100644 index 0000000000..dce02eb446 --- /dev/null +++ b/tests/bcpack_formats_goldens.h @@ -0,0 +1,32 @@ +// FNV-1a-64 of GDK 1.2603.3.0 output for source-built synthetic streams. +// Generated by bcpack_formats_check --oracle; see docs/experiments/bcpack-standalone.md. +// SPDX-License-Identifier: MIT +#pragma once +#include <cstdint> +inline constexpr uint64_t BCPACK_REFERENCE_GOLDENS[16] = { + 0x34c5c81aac38ab05ull, + 0x3fbe7d532c8a8ee5ull, + 0x3ad5c83091ad36c8ull, + 0xa166156f9d7c2584ull, + 0xf8dcf5a64a9bc914ull, + 0xc793a6b84f33d1f8ull, + 0x878c19433aad5528ull, + 0x323fe930ab1bbb34ull, + 0x7da68746bab3e824ull, + 0xdb039400e610986cull, + 0x057898faa1d59bf4ull, + 0x840acfcd001e5de0ull, + 0x0f6512b21bceaec9ull, + 0xb8a2e7bdf73cad4dull, + 0x48b0f9f1c4216b49ull, + 0x5dfb4aa715489a1dull, +}; +inline constexpr uint64_t BCPACK_RANDOM_GOLDENS[7] = { + 0x1b0b9d7ad64ed0ebull, + 0x80d855e20ab59f94ull, + 0x0c4a4d67b9bea24full, + 0x736c245fee5efa9aull, + 0xd75651737d36c49aull, + 0x8b25e69129e6d691ull, + 0xc498f7502500346dull, +}; diff --git a/tests/bcpack_oracle_bridge.cpp b/tests/bcpack_oracle_bridge.cpp new file mode 100644 index 0000000000..6683875f2d --- /dev/null +++ b/tests/bcpack_oracle_bridge.cpp @@ -0,0 +1,20 @@ +// Synthetic input bridge for the optional development-only constant recovery tool. +// SPDX-License-Identifier: MIT +#include "bcpack_format_fixtures.h" +#include <cstring> +extern "C" __declspec(dllexport) size_t encode_symbols(unsigned fmt, const uint16_t* symbols, + size_t target, uint8_t* output, size_t capacity) { + if (fmt < 1 || fmt > 7 || !symbols || !output || !target || target%bcpack_fixture::per(fmt)) return 0; + std::vector<uint16_t> s(symbols,symbols+target*bcpack_fixture::lanes(fmt)); + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,target/bcpack_fixture::per(fmt),packed) || packed.size() > capacity) return 0; + std::memcpy(output,packed.data(),packed.size()); + return packed.size(); +} +extern "C" __declspec(dllexport) size_t storage_symbols(unsigned fmt, uint16_t* output, size_t capacity) { + if ((fmt != 2 && fmt != 6) || !output) return 0; + auto s = bcpack_fixture::random_symbols(fmt,4,0x7700+fmt); + if (capacity < s.size()) return 0; + std::copy(s.begin(),s.end(),output); + return s.size(); +} diff --git a/tests/bcpack_storage_checks.inl b/tests/bcpack_storage_checks.inl new file mode 100644 index 0000000000..9df107ce77 --- /dev/null +++ b/tests/bcpack_storage_checks.inl @@ -0,0 +1,112 @@ +// Included by the source-built startup consumer after its queue/zlib helpers. +// SPDX-License-Identifier: MIT + +bool bcpack_storage_checks() { + _putenv("X2W_XMEM_PERMISSIVE=1"); + const auto library = LoadLibraryW(L"XCRDAPI.dll"); + if (!library) return false; + const auto get_factory = reinterpret_cast<DStorageGetFactoryFn>(GetProcAddress(library,"DStorageGetFactory")); + void* factory_ptr = nullptr; + if (!get_factory || get_factory(nullptr,&factory_ptr) != 0 || !factory_ptr) return false; + auto* factory = static_cast<Object*>(factory_ptr); + for (unsigned fmt : {2u,6u}) { + const auto s = bcpack_fixture::random_symbols(fmt,4,0x7700+fmt); + std::vector<uint8_t> packed; + if (!bcpack_fixture::encode(fmt,s,4,packed)) return false; + const auto zipped = make_stored_zlib(packed.data(),packed.size()); + const auto* expected = fmt == 2 ? BC2_STORAGE_EXPECTED : BC6_STORAGE_EXPECTED; + // Memory/file x raw/zlib, linear/page destinations; then failures followed by valid requests. + for (unsigned scenario = 0; scenario < (fmt == 6 ? 14u : 12u); ++scenario) { + const bool file = (scenario & 1) != 0; + const bool zlib = (scenario & 2) != 0; + const bool page = (scenario >= 4 && scenario < 10) || scenario == 13; + const bool invalid = scenario >= 8; + std::vector<uint8_t> damaged; + if (scenario >= 12) { + auto bad = s; + bad[15*8+6] = 14; // final block's undefined mode, after three valid blocks + if (!bcpack_fixture::encode(fmt,bad,4,damaged)) return false; + } + const auto& input = scenario >= 12 ? damaged : zlib ? zipped : packed; + void *queue_ptr = nullptr, *status_ptr = nullptr; + uint8_t desc[0x20] = {}; *reinterpret_cast<uint16_t*>(desc+8) = 16; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory,desc,nullptr,&queue_ptr) != 0 || !queue_ptr || + reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory,2,"BCPack",nullptr,&status_ptr) != 0 || !status_ptr) + return false; + auto* queue = static_cast<Object*>(queue_ptr); + auto* status = static_cast<Object*>(status_ptr); + std::vector<uint8_t> linear(96,0xa5), following(64,0xa5); + size_t page_count = 2; + u64 pages[2] = {}; + ULONG_PTR tokens[2] = {}; + void* view = nullptr; + if (page) { + if (!XMemAllocatePhysicalPages(0x20400000ull,&page_count,pages) || page_count != 2) return false; + tokens[0] = pages[0]; tokens[1] = pages[1]; + view = XMemVirtualAlloc(nullptr,131072,0x20402000,0x21,PAGE_READWRITE); + if (!view || XMemMapPhysicalPages(view,2,tokens) != view) return false; + std::memset(view,0xa5,131072); + if (scenario == 8 || scenario == 9) tokens[1] = 0; // missing second page: no partial publication + } + wchar_t temp_dir[MAX_PATH], temp_file[MAX_PATH] = {}; + Object* source_file = nullptr; + if (file) { + if (!GetTempPathW(MAX_PATH,temp_dir) || !GetTempFileNameW(temp_dir,L"bcp",0,temp_file)) return false; + const auto h = CreateFileW(temp_file,GENERIC_WRITE,0,nullptr,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + const uint8_t prefix[13] = {}; + DWORD written = 0; + const bool wrote = WriteFile(h,prefix,sizeof(prefix),&written,nullptr) && written == sizeof(prefix) && + WriteFile(h,input.data(),static_cast<DWORD>(input.size()),&written,nullptr) && written == input.size(); + CloseHandle(h); + void* ptr = nullptr; + if (!wrote || reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory,temp_file,nullptr,&ptr) != 0 || !ptr) return false; + source_file = static_cast<Object*>(ptr); + } + uint8_t requests[2][0x48] = {}; + for (unsigned k = 0; k < 2; ++k) { + auto* r = requests[k]; + const bool first = k == 0; + const bool use_file = first && file, use_zlib = first && zlib, use_pages = first && page; + const auto& src = first ? input : packed; + unsigned request_format = first && (scenario == 10 || scenario == 11) ? 8 : fmt; + *reinterpret_cast<u64*>(r) = (request_format << 1) | (use_zlib ? 1 : 0) | + (use_file ? 0 : 0x400000) | (use_pages ? 1ull<<21 : 0); + *reinterpret_cast<void**>(r+0x08) = use_pages ? static_cast<void*>(tokens) : + first ? static_cast<void*>(linear.data()+16) : static_cast<void*>(following.data()); + *reinterpret_cast<u64*>(r+0x10) = use_pages ? 65520 : 0; + *reinterpret_cast<unsigned*>(r+0x18) = 64; + *reinterpret_cast<const void**>(r+0x20) = use_file ? static_cast<const void*>(source_file) : src.data(); + *reinterpret_cast<u64*>(r+0x28) = use_file ? 13 : 0; + *reinterpret_cast<unsigned*>(r+0x30) = static_cast<unsigned>(src.size()); + *reinterpret_cast<unsigned*>(r+0x34) = static_cast<unsigned>(packed.size()); + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue,r); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue,status,k); + } + reinterpret_cast<SubmitFn>(queue->vtable[6])(queue); + for (int i = 0; i < 200 && !reinterpret_cast<IsCompleteFn>(status->vtable[3])(status,1); ++i) Sleep(10); + bool ok = reinterpret_cast<IsCompleteFn>(status->vtable[3])(status,1); + const long hr = reinterpret_cast<GetHResultFn>(status->vtable[4])(status,0); + ok = ok && (invalid ? hr != 0 : hr == 0) && + reinterpret_cast<GetHResultFn>(status->vtable[4])(status,1) == 0 && std::memcmp(following.data(),expected,64) == 0; + const auto* destination = page ? static_cast<const uint8_t*>(view) : linear.data(); + const size_t size = page ? 131072 : linear.size(), offset = page ? 65520 : 16; + for (size_t at = 0; at < size; ++at) { + const uint8_t wanted = !invalid && at >= offset && at < offset+64 ? expected[at-offset] : 0xa5; + if (destination[at] != wanted) ok = false; + } + if (source_file) { + reinterpret_cast<CloseFileFn>(source_file->vtable[3])(source_file); + DeleteFileW(temp_file); + } + if (view) { + XMemMapPhysicalPages(view,2,nullptr); + VirtualFree(view,0,MEM_RELEASE); + XMemFreePhysicalPages(2,pages); + } + std::printf("BC%u storage scenario %u: %s\n",fmt,scenario,ok ? "ok" : "FAIL"); + if (!ok) return false; + } + } + return true; +} diff --git a/tests/bcpack_storage_goldens.h b/tests/bcpack_storage_goldens.h new file mode 100644 index 0000000000..4f2f09b16e --- /dev/null +++ b/tests/bcpack_storage_goldens.h @@ -0,0 +1,15 @@ +// GDK 1.2603.3.0 golden BC blocks from random_symbols(fmt,4,0x7700+fmt). +// Entirely synthetic input, no SDK or title bytes. SPDX-License-Identifier: MIT +#pragma once +inline constexpr unsigned char BC2_STORAGE_EXPECTED[64] = { + 0x0a, 0x5a, 0xf0, 0x97, 0x8d, 0x91, 0x11, 0xbb, 0xff, 0xb9, 0x2f, 0x9e, 0xa6, 0x92, 0x7e, 0x8c, + 0x8f, 0x87, 0x8d, 0xb3, 0x65, 0x45, 0x15, 0x89, 0x44, 0x5f, 0x13, 0x7c, 0x57, 0x45, 0xaa, 0xde, + 0xed, 0x54, 0x81, 0xa6, 0x64, 0xcd, 0xd8, 0xbe, 0x91, 0x96, 0x07, 0x79, 0xf2, 0x16, 0xbd, 0xd0, + 0x12, 0x3c, 0xa4, 0x7c, 0xd7, 0x3a, 0xc8, 0x20, 0x92, 0xdc, 0x96, 0x5b, 0x41, 0x6a, 0x48, 0xc0, +}; +inline constexpr unsigned char BC6_STORAGE_EXPECTED[64] = { + 0x3c, 0xb0, 0x9e, 0x26, 0xae, 0xc9, 0x66, 0xae, 0x35, 0x0e, 0x60, 0xb7, 0xb5, 0x77, 0xc3, 0x32, + 0x49, 0x95, 0xfb, 0xad, 0x62, 0x12, 0xe7, 0x49, 0x02, 0x35, 0x44, 0xe2, 0xb5, 0xd3, 0xd9, 0x8d, + 0x02, 0xf3, 0x80, 0x2a, 0xb8, 0x95, 0xa1, 0x7b, 0x10, 0x5e, 0x64, 0x6d, 0x56, 0x72, 0x71, 0x05, + 0xe6, 0xe9, 0xcd, 0xd4, 0xc6, 0xc7, 0xe0, 0x59, 0xca, 0x7d, 0x30, 0x54, 0x5e, 0x09, 0xbc, 0xfe, +}; diff --git a/tests/bcpack_tables_check.py b/tests/bcpack_tables_check.py index 696d1ce81e..fd9f2a0a39 100644 --- a/tests/bcpack_tables_check.py +++ b/tests/bcpack_tables_check.py @@ -43,9 +43,9 @@ class BCPackTablesCheck(unittest.TestCase): @classmethod def setUpClass(cls): content = HEADER.read_text(encoding="utf-8") - inl = ROOT / "src" / "startup_stubs" / "bcpack_tables_bcn.inl" - if inl.exists() and '#include "bcpack_tables_bcn.inl"' in content: - content = content.replace('#include "bcpack_tables_bcn.inl"', inl.read_text(encoding="utf-8")) + for name in ("bcpack_tables_bcn.inl", "bcpack_tables_extra.inl"): + inl = HEADER.parent / name + content = content.replace(f'#include "{name}"', inl.read_text(encoding="utf-8")) cls.text = strip_comments(content) def test_rans_model_tables(self): @@ -96,22 +96,46 @@ def test_bc7_dictionary_structure(self): for b in row: self.assertIn(b, range(256)) - def test_bc1_window_structure(self): - window = extract_array(self.text, "BC1_WINDOW") - self.assertEqual(len(window), 256) - for row in window: - self.assertEqual(len(row), 6) - for b in row: - self.assertIn(b, range(256)) - - def test_bc1_quad_masks_structure(self): - quad_masks = extract_array(self.text, "BC1_QUAD_MASKS") - self.assertEqual(len(quad_masks), 4) - for row in quad_masks: - self.assertEqual(len(row), 256) - for mask in row: - self.assertGreaterEqual(mask, 0) - self.assertLessEqual(mask, 0xFFFFFFFF) + def test_bc1_bc2_exact_tables_structure(self): + for fmt in (1, 2): + ranks = extract_array(self.text, f"BC{fmt}_POSITION_RANK") + self.assertEqual(len(ranks), 256) + self.assertEqual({tuple(row) for row in ranks}, + {(a, b, c, d) for a in range(4) for b in range(4) + for c in range(4) for d in range(4)}) + dictionary = extract_array(self.text, f"BC{fmt}_FULL_DICTIONARY") + self.assertEqual(len(dictionary), 255) + for row in dictionary: + if fmt == 2: + alpha, ep, ix = row + self.assertEqual(len(alpha), 16) + self.assertTrue(all(v in range(16) for v in alpha)) + else: + ep, ix = row + self.assertEqual(len(ep), 6) + self.assertTrue(all(v in range(64 if i % 3 == 1 else 32) + for i, v in enumerate(ep))) + self.assertEqual(len(ix), 16) + self.assertTrue(all(v in range(4) for v in ix)) + + def test_bc6_tables_structure(self): + dictionary = extract_array(self.text, "BC6_DICTIONARY") + self.assertEqual(len(dictionary), 255) + for ep, ix in dictionary: + self.assertEqual(len(ep), 4) + for endpoint in ep: + self.assertEqual(len(endpoint), 3) + self.assertTrue(all(v in range(65536) for v in endpoint)) + self.assertEqual(len(ix), 16) + self.assertTrue(all(v in range(65536) for v in ix)) + wire = extract_array(self.text, "BC6_WIRE") + self.assertEqual(len(wire), 14) + for mode, row in enumerate(wire): + self.assertEqual(len(row), 82 if mode < 10 else 65) + for field, bit in row: + self.assertIn(field, range(14)) + self.assertIn(bit, range(16)) + self.assertEqual(len(extract_array(self.text, "BC6_ENDPOINT_BITS")), 15) def test_bc4_tables_structure(self): pairs = extract_array(self.text, "RANK_PAIR_BC4") @@ -202,10 +226,6 @@ def test_compare_with_reference_data_if_present(self): expected_dict.append([subsets, [ep[0:8], ep[8:16], ep[16:24]], [ix[0:16], ix[16:32]]]) self.assertEqual(extract_array(self.text, "BC7_DICTIONARY"), expected_dict) - window_json = json.loads((REF_DATA / "bc1_window.json").read_text(encoding="utf-8"))["slots"] - expected_window = [[0] * 6 if e is None else e["value"] for e in window_json] - self.assertEqual(extract_array(self.text, "BC1_WINDOW"), expected_window) - # BC4 checks bc4_json = json.loads((REF_DATA / "bc4.json").read_text(encoding="utf-8")) self.assertEqual(extract_array(self.text, "RANK_PAIR_BC4"), bc4_json["pairs"]) diff --git a/tests/bink_descriptors_aot_cli_check.py b/tests/bink_descriptors_aot_cli_check.py new file mode 100644 index 0000000000..fd72ae78cb --- /dev/null +++ b/tests/bink_descriptors_aot_cli_check.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python3 +"""Pure-Python synthetic PE32+ CLI, atomic-write, path-guard, and mutation suite for tools/bink_descriptors_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "bink_descriptors_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) + +import bink_descriptors_aot # noqa: E402 +from bink_descriptors_aot_check import build_image # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = bink_descriptors_aot.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkDescriptorsAotCliPositiveTests(unittest.TestCase): + def test_default_and_frame_planes_atomic_nested_outputs(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic_bink_desc.dll" + image.write_bytes(raw) + + # 1) Default mode (no --frame-planes) in nested directory, tracking atomic os.replace. + default_out = base / "nested" / "default" / "descriptors.cpp" + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.resolve(), dst_path.parent.resolve()) + self.assertTrue(src_path.name.endswith(".tmp")) + return real_replace(src, dst) + + with mock.patch.object(bink_descriptors_aot.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(image), str(default_out)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(seen_replaces), 1) + self.assertEqual([p.name for p in default_out.parent.iterdir()], ["descriptors.cpp"]) + default_text = default_out.read_text(encoding="ascii") + self.assertEqual(default_text, bink_descriptors_aot.generate(image, False, False)) + self.assertIn("group_init", default_text) + self.assertIn("group_append", default_text) + self.assertNotIn("frame_planes", default_text) + + # 2) --frame-planes mode atomically overwrites existing .cpp with 0 .tmp files left. + default_out.write_text("stale content", encoding="ascii") + code_fp, out_fp, err_fp = _run_main([str(image), str(default_out), "--frame-planes"]) + self.assertEqual(code_fp, 0, err_fp) + self.assertEqual(out_fp, "") + self.assertEqual(err_fp, "") + self.assertEqual([p.name for p in default_out.parent.iterdir()], ["descriptors.cpp"]) + fp_text = default_out.read_text(encoding="ascii") + self.assertEqual(fp_text, bink_descriptors_aot.generate(image, False, True)) + self.assertIn("frame_planes", fp_text) + self.assertIn("append_frame", fp_text) + + # 3) Subprocess end-to-end positive check. + sub_out = base / "sub_dir" / "cli_out.cpp" + proc = _run_subprocess(str(image), str(sub_out), "--frame-planes") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual([p.name for p in sub_out.parent.iterdir()], ["cli_out.cpp"]) + self.assertEqual(sub_out.read_text(encoding="ascii"), fp_text) + + def test_sys_argv_and_main_entrypoint(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "entry.dll" + image.write_bytes(raw) + out_cpp = base / "entry.cpp" + + with mock.patch.object(sys, "argv", [str(TOOL), str(image), str(out_cpp)]): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(out_cpp.read_text(encoding="ascii"), bink_descriptors_aot.generate(image, False, False)) + + out_cpp.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(image), str(out_cpp), "--frame-planes"]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(out_cpp.read_text(encoding="ascii"), bink_descriptors_aot.generate(image, False, True)) + + +class BinkDescriptorsAotCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "absent_dir" / "descriptors.cpp" + + with ( + mock.patch.object( + bink_descriptors_aot, + "generate", + side_effect=AssertionError("generate called for invalid image"), + ), + mock.patch.object( + bink_descriptors_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_corrupt_pe_rejected_cleanly_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + absent_out = base / "absent_dir" / "descriptors.cpp" + for name, payload in ( + ("empty.dll", b""), + ("not_pe.dll", b"not a valid PE32+"), + ("trunc_pe.dll", b"MZ" + b"\x00" * 58 + struct.pack("<I", 0x80)), + ): + with self.subTest(name=name): + bad_pe = base / name + bad_pe.write_bytes(payload) + self._assert_clean_failure([str(bad_pe), str(absent_out)], expected_code=1) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_rejected_before_generate_and_write(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(raw) + same_cpp = base / "same.cpp" + same_cpp.write_bytes(raw) + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_descriptors_aot, + "generate", + side_effect=AssertionError("generate called for invalid output"), + ), + mock.patch.object( + bink_descriptors_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "out.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "out.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), raw) + self.assertEqual(image.read_bytes(), raw) + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(raw) + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + has_symlinks = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + has_symlinks = False + + with ( + mock.patch.object( + bink_descriptors_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_descriptors_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + if has_symlinks: + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + else: + # Fallback when Windows account lacks SeCreateSymbolicLinkPrivilege (WinError 1314). + with mock.patch.object(Path, "is_symlink", autospec=True, side_effect=lambda p: p == real_target): + self._assert_clean_failure( + [str(image), str(real_target)], + expected_code=1, + fragments=("symlink",), + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + + def test_os_replace_and_staging_failures_preserve_target_and_leave_zero_tmp_files(self) -> None: + raw = build_image() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(raw) + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "descriptors.cpp" + out_cpp.write_text("original-target-bytes", encoding="ascii") + + # 1) os.replace fails on existing target -> target preserved, 0 .tmp files. + replace_calls: list[tuple[Path, Path]] = [] + + def fail_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + raise OSError("simulated replace failure") + + with mock.patch.object(bink_descriptors_aot.os, "replace", side_effect=fail_replace): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(len(replace_calls), 1) + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original-target-bytes") + self.assertEqual([p.name for p in out_dir.iterdir()], ["descriptors.cpp"]) + + # 2) os.replace fails on fresh nested path -> 0 output or .tmp files. + fresh_dir = base / "fresh_dir" + fresh_cpp = fresh_dir / "fresh.cpp" + with mock.patch.object(bink_descriptors_aot.os, "replace", side_effect=fail_replace): + self._assert_clean_failure( + [str(image), str(fresh_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(list(fresh_dir.iterdir()), []) + + # 3) Staging failure after .tmp creation -> os.replace not called, .tmp unlinked, target preserved. + real_ntf = bink_descriptors_aot.tempfile.NamedTemporaryFile + + class FailingWriteHandle: + def __init__(self, inner): + self._inner = inner + self.name = inner.name + + def __enter__(self): + self._inner.__enter__() + return self + + def __exit__(self, exc_type, exc, tb): + return self._inner.__exit__(exc_type, exc, tb) + + def write(self, _data): + raise OSError("simulated write failure") + + with ( + mock.patch.object(bink_descriptors_aot.os, "replace") as replace_mock, + mock.patch.object( + bink_descriptors_aot.tempfile, + "NamedTemporaryFile", + side_effect=lambda *a, **kw: FailingWriteHandle(real_ntf(*a, **kw)), + ), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated write failure",), + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original-target-bytes") + self.assertEqual([p.name for p in out_dir.iterdir()], ["descriptors.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "out.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/bink_frame_aot_cli_check.py b/tests/bink_frame_aot_cli_check.py new file mode 100644 index 0000000000..f49bbe9a0b --- /dev/null +++ b/tests/bink_frame_aot_cli_check.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and mutation suite for tools/bink_frame_aot.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "bink_frame_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +import bink_frame_aot # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include <cstdint>\n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) uint32_t frame_allocate(word, word, uint32_t) { return 0; }\n' +) + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkFrameAotCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_dirs_and_overwrite_with_zero_tmp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "frame_aot.cpp" + + real_replace = os.replace + replaced_pairs: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaced_pairs.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + with ( + mock.patch.object(bink_frame_aot, "generate", return_value=SYNTHETIC_CPP) as gen, + mock.patch.object(os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main(bink_frame_aot, [str(image), str(nested_out)]) + gen.assert_called_once_with(image) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["frame_aot.cpp"]) + self.assertEqual(len(replaced_pairs), 1) + self.assertEqual(replaced_pairs[0][1].resolve(), nested_out.resolve()) + + # Atomic overwrite preserves zero .tmp files. + updated_cpp = SYNTHETIC_CPP + "// updated\n" + with mock.patch.object(bink_frame_aot, "generate", return_value=updated_cpp): + code_ow, out_ow, err_ow = _run_main(bink_frame_aot, [str(image), str(nested_out)]) + self.assertEqual(code_ow, 0, err_ow) + self.assertEqual(out_ow, "") + self.assertEqual(err_ow, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), updated_cpp) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["frame_aot.cpp"]) + + # argv=None forwards sys.argv cleanly. + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(image), str(nested_out)]), + mock.patch.object(bink_frame_aot, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(bink_frame_aot, None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # __main__ entrypoint propagates SystemExit(1) cleanly on unmatched image. + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(image), str(base / "unused.cpp")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertTrue(stderr_m.getvalue().strip()) + + +class BinkFrameAotCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(bink_frame_aot, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_corrupt_and_unmatched_hash_image_rejected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "absent_dir" / "frame_aot.cpp" + + with ( + mock.patch.object( + bink_frame_aot, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + bink_frame_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + # Unmatched SHA-256 hash image fails cleanly without creating output parent. + unmatched = base / "unmatched.dll" + unmatched.write_bytes(b"not-the-pinned-bink-sha256") + self._assert_clean_failure( + [str(unmatched), str(absent_out)], + expected_code=1, + fragments=("version-query profile",), + ) + self.assertFalse(absent_out.parent.exists()) + + # Corrupt PE bytes (with patched SHA-256) fail cleanly without creating output parent. + import hashlib + + digest = hashlib.sha256(b"not a PE32+").hexdigest() + corrupt = base / "corrupt.dll" + corrupt.write_bytes(b"not a PE32+") + with mock.patch.object(bink_frame_aot, "BINK_SHA256", digest): + self._assert_clean_failure( + [str(corrupt), str(absent_out)], + expected_code=1, + check_subprocess=False, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_dir_file_parent_samefile_and_non_cpp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_frame_aot, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + bink_frame_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "frame_aot.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "frame_aot.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + bink_frame_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_frame_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_os_replace_failure_preserves_target_bytes_and_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "frame_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(bink_frame_aot, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(os, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["frame_aot.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(base / "frame_aot.cpp"), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + dir_image = base / "dir_image" + dir_image.mkdir() + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + file_parent = base / "file_parent.txt" + file_parent.write_text("keep", encoding="ascii") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "frame_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + # 1) Removing directory image check misses "image path is a directory". + # 2) Removing parent.is_file check drops "output parent is not a directory". + # 3) Removing samefile check allows hardlink collision past _validate_args. + # 4) Removing temp unlink leaves a .tmp file behind on os.replace failure. + for label, target, replacement, check_fn in ( + ( + "drop_image_is_dir_guard", + ' if args.image.is_dir():\n raise IsADirectoryError(f"image path is a directory: {args.image}")\n', + " pass\n", + lambda mod: self.assertNotIn( + "image path is a directory", + _run_main(mod, [str(dir_image), str(out_dir / "a.cpp")])[2].lower(), + ), + ), + ( + "drop_parent_is_file_guard", + ' if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()):\n' + ' raise NotADirectoryError(f"output parent is not a directory: {parent}")\n', + " pass\n", + lambda mod: self.assertNotIn( + "output parent is not a directory", + _run_main(mod, [str(image), str(file_parent / "frame_aot.cpp")])[2].lower(), + ), + ), + ( + "drop_samefile_guard", + " if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)):\n", + " if args.output.resolve() == args.image.resolve():\n", + lambda mod: self.assertNotIn( + "choose a distinct .cpp output", + _run_main(mod, [str(image), str(hardlink_cpp)])[2].lower(), + ), + ), + ( + "drop_tmp_unlink", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)\n", + " pass\n", + lambda mod: self._verify_tmp_leaked_on_replace_fail(mod, image, out_cpp, out_dir), + ), + ): + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"bink_frame_aot_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + with mock.patch.object(mod, "generate", return_value=SYNTHETIC_CPP): + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + def _verify_tmp_leaked_on_replace_fail(self, mod, image: Path, out_cpp: Path, out_dir: Path) -> None: + with mock.patch.object(os, "replace", side_effect=OSError("boom")): + code, _, _ = _run_main(mod, [str(image), str(out_cpp)]) + self.assertEqual(code, 1) + leaked = [p for p in out_dir.iterdir() if p.suffix == ".tmp"] + self.assertTrue(leaked, "expected unlinked .tmp file under mutation") + for p in leaked: + p.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/bink_heap_aot_cli_check.py b/tests/bink_heap_aot_cli_check.py new file mode 100644 index 0000000000..49bc5af446 --- /dev/null +++ b/tests/bink_heap_aot_cli_check.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and error-handling suite for tools/bink_heap_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "bink_heap_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) +import bink_heap_aot # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include <cstdint>\n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) void* heap_request(word bytes) { return nullptr; }\n' +) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = bink_heap_aot.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class BinkHeapAotCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_new_dir_and_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "heap_aot.cpp" + + # 1) Create missing parent directories and write atomically with 0 .tmp files. + with mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP) as gen: + code, out, err = _run_main([str(image), str(nested_out)]) + gen.assert_called_once_with(image, None, None) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["heap_aot.cpp"]) + + # 2) Forward --entries and --group-entry, and atomically overwrite existing file with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + entries_cpp = SYNTHETIC_CPP + "// entries-mode\n" + with mock.patch.object(bink_heap_aot, "generate", return_value=entries_cpp) as gen_entries: + code_ent, out_ent, err_ent = _run_main([ + str(image), + str(nested_out), + "--entries", + "0x1000", + "0x2000", + "--group-entry", + "heap_group", + ]) + gen_entries.assert_called_once_with(image, [0x1000, 0x2000], "heap_group") + self.assertEqual(code_ent, 0, err_ent) + self.assertEqual(out_ent, "") + self.assertEqual(err_ent, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), entries_cpp) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["heap_aot.cpp"]) + + # 3) Verify sys.argv forwarding when argv=None. + cli_argv = [str(TOOL), str(image), str(nested_out)] + with ( + mock.patch.object(sys, "argv", cli_argv), + mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) Verify __main__ entrypoint propagates SystemExit cleanly on invalid PE. + bad_pe = base / "bad_main.dll" + bad_pe.write_bytes(b"not a PE") + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(bad_pe), str(base / "unused.cpp")]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout.getvalue(), "") + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertTrue(stderr.getvalue().strip()) + + +class BinkHeapAotCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "should_not_exist" / "heap_aot.cpp" + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + def test_invalid_pe_bytes_exit_1_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + bad_pe = base / "bad.dll" + bad_pe.write_bytes(b"not a valid PE32+ image") + absent_out = base / "absent_dir" / "heap_aot.cpp" + + self._assert_clean_failure( + [str(bad_pe), str(absent_out)], + expected_code=1, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_negative_entries_and_empty_group_entry_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_cpp = base / "absent_dir" / "heap_aot.cpp" + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid entries/group-entry"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid entries/group-entry"), + ), + ): + for label, argv, frags in ( + ("neg_alloc_rva", [str(image), str(out_cpp), "--entries", "-1", "0x2000"], ("non-negative",)), + ("neg_free_rva", [str(image), str(out_cpp), "--entries", "0x1000", "-4"], ("non-negative",)), + ("both_neg_rva", [str(image), str(out_cpp), "--entries", "-1", "-4"], ("non-negative",)), + ("empty_group_entry", [str(image), str(out_cpp), "--group-entry", ""], ("--group-entry",)), + ("blank_group_entry", [str(image), str(out_cpp), "--group-entry", " "], ("--group-entry",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertFalse(out_cpp.parent.exists()) + + def test_output_guards_reject_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "heap_aot.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "heap_aot.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + bink_heap_aot, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + bink_heap_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_atomic_write_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "heap_aot.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(bink_heap_aot, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["heap_aot.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "heap_aot.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--entries", "0x1000"], ("expected 2 arguments",)), + ([str(image), str(out_cpp), "--entries", "bad", "0x2000"], ("invalid",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/call_evidence_cli_check.py b/tests/call_evidence_cli_check.py new file mode 100644 index 0000000000..cb606b759a --- /dev/null +++ b/tests/call_evidence_cli_check.py @@ -0,0 +1,690 @@ +#!/usr/bin/env python3 +"""Pure-Python synthetic PE32+ CLI, atomic-write, and path-guard suite for tools/call_evidence.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "call_evidence.py" +sys.path.insert(0, str(TOOLS_DIR)) +import call_evidence # noqa: E402 + + +IMAGE_BASE = 0x180000000 +SECTION_RVA = 0x1000 +RAW_OFFSET = 0x200 +RAW_SIZE = 0x1000 + + +def _make_dxbc_container() -> bytes: + """Build a minimal synthetic DXBC container with DXIL and RTS0 parts.""" + program = struct.pack("<II4sIII", 0, 8, b"DXIL", 0, 16, 4) + b"BC\xc0\xde" + bytes(4) + rts0 = struct.pack("<6I", 2, 3, 24, 1, 0, 0x10) + parts = [ + b"DXIL" + struct.pack("<I", len(program)) + program, + b"RTS0" + struct.pack("<I", len(rts0)) + rts0, + ] + cursor = 32 + 4 * len(parts) + offsets = [] + for part in parts: + offsets.append(cursor) + cursor += len(part) + body = b"".join(parts) + total = 32 + 4 * len(parts) + len(body) + return ( + b"DXBC" + + bytes(16) + + struct.pack("<III", 1, total, len(parts)) + + struct.pack(f"<{len(parts)}I", *offsets) + + body + ) + + +def _build_pe32_plus( + imports: list[tuple[bytes, bytes]] = (), + *, + containers: list[bytes] = (), +) -> tuple[bytes, dict[tuple[bytes, bytes], int], list[int]]: + """Build a minimal AMD64 PE32+ DLL with optional imports and mapped DXBC containers.""" + payload = bytearray(RAW_SIZE) + cursor = 0 + + def alloc(size: int, align: int) -> int: + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = SECTION_RVA + cursor + if cursor + size > len(payload): + raise AssertionError("synthetic section overflow") + cursor += size + return rva + + def put(rva: int, blob: bytes) -> None: + offset = rva - SECTION_RVA + payload[offset:offset + len(blob)] = blob + + grouped: dict[bytes, list[bytes]] = {} + for dll_bytes, sym in imports: + grouped.setdefault(dll_bytes, []).append(sym) + + dll_rvas = {} + for dll_bytes in grouped: + raw = dll_bytes + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + dll_rvas[dll_bytes] = rva + + hint_rvas = {} + for dll_bytes, syms in grouped.items(): + for sym in syms: + raw = struct.pack("<H", 0) + sym + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + hint_rvas[(dll_bytes, sym)] = rva + + iat_rvas: dict[tuple[bytes, bytes], int] = {} + descriptors = [] + for dll_bytes, syms in grouped.items(): + entries = [hint_rvas[(dll_bytes, sym)] for sym in syms] + table_blob = b"".join(struct.pack("<Q", value) for value in [*entries, 0]) + lookup_rva = alloc(len(table_blob), 8) + put(lookup_rva, table_blob) + iat_rva = alloc(len(table_blob), 8) + put(iat_rva, table_blob) + for idx, sym in enumerate(syms): + iat_rvas[(dll_bytes, sym)] = iat_rva + idx * 8 + descriptors.append((lookup_rva, dll_rvas[dll_bytes], iat_rva)) + + import_dir_rva = import_dir_size = 0 + if descriptors: + import_dir_size = 20 * (len(descriptors) + 1) + import_dir_rva = alloc(import_dir_size, 4) + for idx, (lookup_rva, dll_rva, iat_rva) in enumerate(descriptors): + put(import_dir_rva + idx * 20, struct.pack("<5I", lookup_rva, 0, 0, dll_rva, iat_rva)) + + container_rvas = [] + for blob in containers: + c_rva = alloc(len(blob), 16) + put(c_rva, blob) + container_rvas.append(c_rva) + + vsize = max(1, cursor) + size_of_image = SECTION_RVA + ((vsize + 0xFFF) // 0x1000) * 0x1000 + pe_off = 0x80 + buf = bytearray(RAW_OFFSET + RAW_SIZE) + buf[0:2] = b"MZ" + struct.pack_into("<I", buf, 60, pe_off) + buf[pe_off:pe_off + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_off + 4, 0x8664, 1, 0, 0, 0, 240, 0x2022) + opt = pe_off + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + 0x20B, 0, 0, 0, RAW_SIZE, 0, 0, SECTION_RVA, IMAGE_BASE, + 0x1000, 0x200, 6, 0, 0, 0, 6, 0, 0, size_of_image, RAW_OFFSET, + 0, 3, 0, 0, 0, 0, 0, 0, 16, + ) + sec = opt + 240 + struct.pack_into( + "<8sIIIIIIHHI", + buf, + sec, + b".rdata\0\0", vsize, SECTION_RVA, RAW_SIZE, RAW_OFFSET, 0, 0, 0, 0, 0x40000040, + ) + if import_dir_rva: + struct.pack_into("<II", buf, opt + 112 + 8, import_dir_rva, import_dir_size) + buf[RAW_OFFSET:RAW_OFFSET + RAW_SIZE] = payload + return bytes(buf), iat_rvas, container_rvas + + +def _format_disasm(lines: list[tuple[int, str]]) -> bytes: + body = "\n".join(f" {IMAGE_BASE + rva:016X}: {text}" for rva, text in lines) + return f"Dump of file fixture.dll\n\nFile Type: DLL\n\n{body}\n".encode("ascii") + + +def _populate_valid_build_dir(build_dir: Path) -> tuple[dict[str, bytes], dict[str, bytes]]: + pe0, iat0, _ = _build_pe32_plus(imports=[(b"xmem.dll", b"XMemAlloc")]) + pe1, iat1, c_rvas1 = _build_pe32_plus( + imports=[(b"d3d12_xs.dll", b"D3D12SerializeVersionedRootSignature")], + containers=[_make_dxbc_container()], + ) + pe2, _, _ = _build_pe32_plus() + images = { + call_evidence.NAMES[0]: pe0, + call_evidence.NAMES[1]: pe1, + call_evidence.NAMES[2]: pe2, + } + disasm = { + call_evidence.NAMES[0]: _format_disasm([ + (0x2100, f"call qword ptr [{IMAGE_BASE + iat0[(b'xmem.dll', b'XMemAlloc')]:016X}h]"), + ]), + call_evidence.NAMES[1]: _format_disasm([ + (0x2200, f"jmp qword ptr [{IMAGE_BASE + iat1[(b'd3d12_xs.dll', b'D3D12SerializeVersionedRootSignature')]:016X}h]"), + (0x2210, f"lea rcx, [{IMAGE_BASE + c_rvas1[0]:016X}h]"), + ]), + call_evidence.NAMES[2]: b"", + } + build_dir.mkdir(parents=True, exist_ok=True) + for name, blob in images.items(): + (build_dir / name).write_bytes(blob) + return images, disasm + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = call_evidence.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CallEvidenceCliPositiveTests(unittest.TestCase): + def test_atomic_write_creates_nested_dirs_replaces_stale_and_leaves_zero_tmp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + images, disasm = _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + expected_out = (base / "repo" / "out" / "calls" / "six-apis.json").resolve() + + def fake_dumpbin(cmd: list[str]) -> bytes: + return disasm[Path(cmd[-1]).name] + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + ): + code, out, err = _run_main([str(build_dir)]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(Path(out.strip()), expected_out) + self.assertEqual(sorted(p.name for p in expected_out.parent.iterdir()), ["six-apis.json"]) + + parsed = json.loads(expected_out.read_text(encoding="utf-8")) + self.assertEqual(list(parsed.keys()), list(call_evidence.NAMES)) + for name, blob in images.items(): + self.assertEqual(parsed[name]["sha256"], hashlib.sha256(blob).hexdigest()) + self.assertEqual(parsed[call_evidence.NAMES[0]]["calls"]["XMemAlloc"]["sites"][0]["rva"], "0x2100") + self.assertEqual(len(parsed[call_evidence.NAMES[1]]["containers"]), 1) + + # Seed stale bytes and verify atomic overwrite leaves 0 .tmp files. + expected_out.write_text("{stale", encoding="utf-8") + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + ): + code2, out2, err2 = _run_main([str(build_dir)]) + self.assertEqual(code2, 0, err2) + self.assertEqual(err2, "") + self.assertEqual(Path(out2.strip()), expected_out) + self.assertEqual(sorted(p.name for p in expected_out.parent.iterdir()), ["six-apis.json"]) + self.assertEqual(json.loads(expected_out.read_text(encoding="utf-8")), parsed) + + def test_sys_argv_none_and_main_entrypoint_system_exit(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _, disasm = _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + fake_tool.write_text(TOOL.read_text(encoding="utf-8"), encoding="utf-8") + expected_out = (base / "repo" / "out" / "calls" / "six-apis.json").resolve() + + def fake_dumpbin(cmd: list[str]) -> bytes: + return disasm[Path(cmd[-1]).name] + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(sys, "argv", [str(fake_tool), str(build_dir)]), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + ): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(Path(out.strip()), expected_out) + self.assertTrue(expected_out.is_file()) + + # Verify __main__ raises SystemExit(0) on success and SystemExit(1) on PE error. + expected_out.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(fake_tool), str(build_dir)]), + mock.patch("subprocess.check_output", side_effect=fake_dumpbin), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(fake_tool), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(Path(stdout.getvalue().strip()), expected_out) + self.assertTrue(expected_out.is_file()) + + (build_dir / call_evidence.NAMES[0]).write_bytes(b"corrupt") + stdout2, stderr2 = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(fake_tool), str(build_dir)]), + redirect_stdout(stdout2), + redirect_stderr(stderr2), + ): + with self.assertRaises(SystemExit) as exited_err: + runpy.run_path(str(fake_tool), run_name="__main__") + self.assertEqual(exited_err.exception.code, 1) + self.assertEqual(stdout2.getvalue(), "") + self.assertNotIn("Traceback", stderr2.getvalue()) + self.assertIn("call_evidence:", stderr2.getvalue()) + + +class CallEvidenceCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_non_dir_and_missing_dll_rejected_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + missing_dir = base / "missing_dir" + file_input = base / "regular.bin" + file_input.write_bytes(b"data") + empty_dir = base / "empty" + empty_dir.mkdir() + partial_dir = base / "partial" + partial_dir.mkdir() + pe, _, _ = _build_pe32_plus() + (partial_dir / call_evidence.NAMES[0]).write_bytes(pe) + (partial_dir / call_evidence.NAMES[1]).write_bytes(pe) + + with ( + mock.patch.object( + call_evidence, + "inspect", + side_effect=AssertionError("inspect called on invalid directory/inputs"), + ), + mock.patch.object( + call_evidence, + "_write_atomic", + side_effect=AssertionError("_write_atomic called on invalid directory/inputs"), + ), + ): + self._assert_clean_failure([str(missing_dir)], expected_code=2) + self._assert_clean_failure([str(file_input)], expected_code=2, fragments=("not a directory",)) + self._assert_clean_failure([str(empty_dir)], expected_code=2, fragments=("missing expected image",)) + self._assert_clean_failure( + [str(partial_dir)], + expected_code=2, + fragments=("missing expected image", call_evidence.NAMES[2]), + ) + + def test_dll_guards_reject_directory_unreadable_and_symlink_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_dir = base / "repo" / "out" + + # 1) Expected DLL path is a directory. + dll_dir = build_dir / call_evidence.NAMES[1] + dll_dir.unlink() + dll_dir.mkdir() + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "directory"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + # 2) Expected DLL path is unreadable (os.access false or open PermissionError). + dll_dir.rmdir() + pe_ok, _, _ = _build_pe32_plus() + dll_dir.write_bytes(pe_ok) + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + with mock.patch("call_evidence.os.access", return_value=False): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not readable"), + check_subprocess=False, + ) + with mock.patch.object(Path, "open", side_effect=PermissionError("denied")): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "denied"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + # 3) Expected DLL path is a live or dangling symlink. + target_dll = base / "real_target.dll" + target_dll.write_bytes(pe_ok) + dll_link = build_dir / call_evidence.NAMES[2] + dll_link.unlink() + try: + dll_link.symlink_to(target_dll) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + dll_link.unlink() + dll_link.symlink_to(base / "dangling_target.dll") + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + def test_output_guards_reject_inside_root_dir_and_file_parent_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + repo_dir = base / "repo" + fake_tool = repo_dir / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_file = repo_dir / "out" / "calls" / "six-apis.json" + + # 1) Output inside root (repo_dir has valid DLLs, and out/calls has valid DLLs). + _populate_valid_build_dir(repo_dir) + nested_calls = repo_dir / "out" / "calls" + _populate_valid_build_dir(nested_calls) + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + for overlapping in (repo_dir, nested_calls): + with self.subTest(overlapping=overlapping.name): + self._assert_clean_failure( + [str(overlapping)], + expected_code=2, + fragments=("separate from the report directory",), + check_subprocess=False, + ) + self.assertFalse(out_file.exists()) + shutil.rmtree(repo_dir / "out") + + # 2) Output path is an existing directory. + out_file.mkdir(parents=True) + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "directory"), + check_subprocess=False, + ) + out_file.rmdir() + + # 3) Output parent ('calls') is a regular file. + out_file.parent.rmdir() + out_file.parent.write_text("keep-calls", encoding="utf-8") + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not a directory"), + check_subprocess=False, + ) + self.assertEqual(out_file.parent.read_text(encoding="utf-8"), "keep-calls") + + # 4) Output ancestor ('out') is a regular file. + out_file.parent.unlink() + out_file.parent.parent.rmdir() + out_file.parent.parent.write_text("keep-out", encoding="utf-8") + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not a directory"), + check_subprocess=False, + ) + self.assertEqual(out_file.parent.parent.read_text(encoding="utf-8"), "keep-out") + + def test_output_symlink_and_symlink_parent_rejected_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + repo_dir = base / "repo" + fake_tool = repo_dir / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_file = repo_dir / "out" / "calls" / "six-apis.json" + out_file.parent.mkdir(parents=True) + real_target = base / "real_report.json" + real_target.write_text("untouched", encoding="utf-8") + + try: + out_file.symlink_to(real_target) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch.object(call_evidence, "inspect", side_effect=AssertionError("inspect called")), + mock.patch.object(call_evidence, "_write_atomic", side_effect=AssertionError("write called")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + out_file.unlink() + out_file.symlink_to(base / "missing_report.json") + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "symlink"), + check_subprocess=False, + ) + out_file.unlink() + out_file.parent.rmdir() + out_file.parent.symlink_to(base / "dangling_calls_dir") + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "not a directory"), + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + + def test_corrupt_pe_and_dumpbin_failures_exit_1_without_creating_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_dir = base / "repo" / "out" + + # 1) dumpbin SubprocessError and FileNotFoundError on valid synthetic PEs. + with mock.patch.object(call_evidence, "__file__", str(fake_tool)): + with mock.patch( + "call_evidence.subprocess.check_output", + side_effect=subprocess.CalledProcessError(1, ["dumpbin"]), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:",), + check_subprocess=False, + ) + with mock.patch( + "call_evidence.subprocess.check_output", + side_effect=FileNotFoundError("dumpbin missing"), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "dumpbin missing"), + check_subprocess=False, + ) + self.assertFalse(out_dir.exists()) + + # 2) Corrupt PE bytes (tested both in-process and via real subprocess). + (build_dir / call_evidence.NAMES[0]).write_bytes(b"not a valid PE32+ image") + with mock.patch.object(call_evidence, "__file__", str(fake_tool)): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:",), + ) + self.assertFalse(out_dir.exists()) + + def test_atomic_write_failures_leave_zero_tmp_files_and_preserve_existing_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + build_dir = base / "build" + _, disasm = _populate_valid_build_dir(build_dir) + fake_tool = base / "repo" / "tools" / "call_evidence.py" + fake_tool.parent.mkdir(parents=True) + out_file = base / "repo" / "out" / "calls" / "six-apis.json" + out_file.parent.mkdir(parents=True) + out_file.write_text("prior-report", encoding="utf-8") + + def fake_dumpbin(cmd: list[str]) -> bytes: + return disasm[Path(cmd[-1]).name] + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "simulated replace failure"), + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report") + self.assertEqual(sorted(p.name for p in out_file.parent.iterdir()), ["six-apis.json"]) + + with ( + mock.patch.object(call_evidence, "__file__", str(fake_tool)), + mock.patch("call_evidence.subprocess.check_output", side_effect=fake_dumpbin), + mock.patch("call_evidence.tempfile.NamedTemporaryFile", side_effect=OSError("disk full")), + ): + self._assert_clean_failure( + [str(build_dir)], + expected_code=1, + fragments=("call_evidence:", "disk full"), + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report") + self.assertEqual(sorted(p.name for p in out_file.parent.iterdir()), ["six-apis.json"]) + + def test_argparse_negative_controls_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + build_dir = Path(tmp) / "build" + _populate_valid_build_dir(build_dir) + for bad_argv in ( + [], + [str(build_dir), str(build_dir)], + [str(build_dir), "--unknown-flag"], + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure(bad_argv, expected_code=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/checks/README.md b/tests/checks/README.md new file mode 100644 index 0000000000..fc370f1e2e --- /dev/null +++ b/tests/checks/README.md @@ -0,0 +1,19 @@ +# CI check lists + +The inline lists in `.github/workflows/windows.yml` stay as they are. A new Python check can +instead go in a small text file here, so two pull requests that each add a check do not edit +the same lines. + +| Directory | Read by | One line holds | +|---|---|---| +| `python-linux/*.txt` | the `Run Python checks` step of the `python-linux` job | a script path, for example `tests/my_check.py` | +| `pixel-binary/*.txt` | the machine-code step of the `pixel-binary` job | a script path and its arguments, for example `tests/my_check.py binary llvm-mc-15` | + +Rules, enforced by `tools/run_checks_parallel.py`: + +- Use one file per topic or pull request, for example `python-linux/my_topic.txt`. +- Blank lines and lines starting with `#` are ignored. Files are read in name order. +- A script that does not exist, or a command listed twice across the files, fails the job. +- A command that is also in the inline list runs once. + +Windows jobs register their tests with CTest instead: see [tests/cmake](../cmake/README.md). diff --git a/tests/checks/pixel-binary/README.md b/tests/checks/pixel-binary/README.md new file mode 100644 index 0000000000..3c1493c482 --- /dev/null +++ b/tests/checks/pixel-binary/README.md @@ -0,0 +1,10 @@ +# pixel-binary check lists + +Put one `<topic>.txt` file here for a check that needs LLVM 15. Each line is a script path plus +its arguments, written out in full (the inline `COMMON_LLVM` shortcut is not available here): + +``` +tests/my_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 +``` + +See [the check list rules](../README.md). diff --git a/tests/checks/pixel-binary/mesh_bitcmp.txt b/tests/checks/pixel-binary/mesh_bitcmp.txt new file mode 100644 index 0000000000..a7b359904e --- /dev/null +++ b/tests/checks/pixel-binary/mesh_bitcmp.txt @@ -0,0 +1 @@ +tests/mesh_bitcmp_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/mesh_param_link.txt b/tests/checks/pixel-binary/mesh_param_link.txt new file mode 100644 index 0000000000..ed54c3ec86 --- /dev/null +++ b/tests/checks/pixel-binary/mesh_param_link.txt @@ -0,0 +1 @@ +tests/mesh_param_link_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/pixel_image_store.txt b/tests/checks/pixel-binary/pixel_image_store.txt new file mode 100644 index 0000000000..3b2f6c6523 --- /dev/null +++ b/tests/checks/pixel-binary/pixel_image_store.txt @@ -0,0 +1 @@ +tests/startup_pixel_image_store_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt b/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt new file mode 100644 index 0000000000..195cfc4b28 --- /dev/null +++ b/tests/checks/pixel-binary/startup_gfx2hlsl_image_store_3d1d.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_image_store_3d1d_check.py --llvm-mc llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_gfx2hlsl_pixel_first_lane.txt b/tests/checks/pixel-binary/startup_gfx2hlsl_pixel_first_lane.txt new file mode 100644 index 0000000000..f15e3caaaf --- /dev/null +++ b/tests/checks/pixel-binary/startup_gfx2hlsl_pixel_first_lane.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_pixel_first_lane_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_gfx2hlsl_wave_reduce.txt b/tests/checks/pixel-binary/startup_gfx2hlsl_wave_reduce.txt new file mode 100644 index 0000000000..b44566ab27 --- /dev/null +++ b/tests/checks/pixel-binary/startup_gfx2hlsl_wave_reduce.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_wave_reduce_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_image_cube.txt b/tests/checks/pixel-binary/startup_image_cube.txt new file mode 100644 index 0000000000..ea2f423737 --- /dev/null +++ b/tests/checks/pixel-binary/startup_image_cube.txt @@ -0,0 +1 @@ +tests/startup_image_cube_check.py binary llvm-mc-15 diff --git a/tests/checks/pixel-binary/startup_image_sample_l_join.txt b/tests/checks/pixel-binary/startup_image_sample_l_join.txt new file mode 100644 index 0000000000..a0c9ab69c3 --- /dev/null +++ b/tests/checks/pixel-binary/startup_image_sample_l_join.txt @@ -0,0 +1 @@ +tests/startup_image_sample_l_join_check.py binary llvm-mc-15 diff --git a/tests/checks/python-linux/bvh_node_model.txt b/tests/checks/python-linux/bvh_node_model.txt new file mode 100644 index 0000000000..4eff1e650c --- /dev/null +++ b/tests/checks/python-linux/bvh_node_model.txt @@ -0,0 +1,2 @@ +# Pure-Python witness set for the console BVH node formats (no GPU, no LLVM). +tests/gfx1030_bvh_box/check.py --model-only diff --git a/tests/checks/python-linux/cpu_call_aot_cli.txt b/tests/checks/python-linux/cpu_call_aot_cli.txt new file mode 100644 index 0000000000..be78837b70 --- /dev/null +++ b/tests/checks/python-linux/cpu_call_aot_cli.txt @@ -0,0 +1 @@ +tests/cpu_call_aot_cli_check.py diff --git a/tests/checks/python-linux/cpu_chained_aot_cli.txt b/tests/checks/python-linux/cpu_chained_aot_cli.txt new file mode 100644 index 0000000000..b793f004e1 --- /dev/null +++ b/tests/checks/python-linux/cpu_chained_aot_cli.txt @@ -0,0 +1 @@ +tests/cpu_chained_aot_cli_check.py diff --git a/tests/checks/python-linux/gdk_exports.txt b/tests/checks/python-linux/gdk_exports.txt new file mode 100644 index 0000000000..12598b2a55 --- /dev/null +++ b/tests/checks/python-linux/gdk_exports.txt @@ -0,0 +1 @@ +tests/gdk_exports_check.py diff --git a/tests/checks/python-linux/gdk_knowledge_report.txt b/tests/checks/python-linux/gdk_knowledge_report.txt new file mode 100644 index 0000000000..7917575364 --- /dev/null +++ b/tests/checks/python-linux/gdk_knowledge_report.txt @@ -0,0 +1 @@ +tests/gdk_knowledge_report_check.py diff --git a/tests/checks/python-linux/gdk_layouts.txt b/tests/checks/python-linux/gdk_layouts.txt new file mode 100644 index 0000000000..059002a3c5 --- /dev/null +++ b/tests/checks/python-linux/gdk_layouts.txt @@ -0,0 +1 @@ +tests/gdk_layouts_check.py diff --git a/tests/checks/python-linux/gdk_platform_profiles.txt b/tests/checks/python-linux/gdk_platform_profiles.txt new file mode 100644 index 0000000000..f83b228b84 --- /dev/null +++ b/tests/checks/python-linux/gdk_platform_profiles.txt @@ -0,0 +1 @@ +tests/gdk_platform_profiles_check.py diff --git a/tests/checks/python-linux/gdk_runtime_oracle.txt b/tests/checks/python-linux/gdk_runtime_oracle.txt new file mode 100644 index 0000000000..d4fdc274fe --- /dev/null +++ b/tests/checks/python-linux/gdk_runtime_oracle.txt @@ -0,0 +1 @@ +tests/gdk_runtime_oracle_check.py diff --git a/tests/checks/python-linux/gdk_shader_corpus.txt b/tests/checks/python-linux/gdk_shader_corpus.txt new file mode 100644 index 0000000000..2e522eda0a --- /dev/null +++ b/tests/checks/python-linux/gdk_shader_corpus.txt @@ -0,0 +1 @@ +tests/gdk_shader_corpus_check.py diff --git a/tests/checks/python-linux/mesh_bitcmp.txt b/tests/checks/python-linux/mesh_bitcmp.txt new file mode 100644 index 0000000000..b0b6ee9303 --- /dev/null +++ b/tests/checks/python-linux/mesh_bitcmp.txt @@ -0,0 +1 @@ +tests/mesh_bitcmp_check.py diff --git a/tests/checks/python-linux/mesh_param_link.txt b/tests/checks/python-linux/mesh_param_link.txt new file mode 100644 index 0000000000..3befbb80ed --- /dev/null +++ b/tests/checks/python-linux/mesh_param_link.txt @@ -0,0 +1 @@ +tests/mesh_param_link_check.py diff --git a/tests/checks/python-linux/native_f16_alu.txt b/tests/checks/python-linux/native_f16_alu.txt new file mode 100644 index 0000000000..511eae460c --- /dev/null +++ b/tests/checks/python-linux/native_f16_alu.txt @@ -0,0 +1 @@ +tests/native_f16_alu_check.py model diff --git a/tests/checks/python-linux/patch_manifest.txt b/tests/checks/python-linux/patch_manifest.txt new file mode 100644 index 0000000000..7fb241e0b2 --- /dev/null +++ b/tests/checks/python-linux/patch_manifest.txt @@ -0,0 +1,2 @@ +# Patch manifest schema, loader and hash gate (tools/patch_manifest.py). +tests/patch_manifest_check.py diff --git a/tests/checks/python-linux/pixel_image_store.txt b/tests/checks/python-linux/pixel_image_store.txt new file mode 100644 index 0000000000..2e7a8b4229 --- /dev/null +++ b/tests/checks/python-linux/pixel_image_store.txt @@ -0,0 +1 @@ +tests/startup_pixel_image_store_check.py diff --git a/tests/checks/python-linux/run_checks_fragments.txt b/tests/checks/python-linux/run_checks_fragments.txt new file mode 100644 index 0000000000..1d836f9de4 --- /dev/null +++ b/tests/checks/python-linux/run_checks_fragments.txt @@ -0,0 +1,2 @@ +# Read by `tools/run_checks_parallel.py --from-dir tests/checks/python-linux` (see README.md). +tests/run_checks_fragments_check.py diff --git a/tests/checks/python-linux/scene_color_report.txt b/tests/checks/python-linux/scene_color_report.txt new file mode 100644 index 0000000000..1c90868f22 --- /dev/null +++ b/tests/checks/python-linux/scene_color_report.txt @@ -0,0 +1 @@ +tests/startup_scene_color_report_check.py diff --git a/tests/checks/python-linux/shader_compile_lds_request_cli.txt b/tests/checks/python-linux/shader_compile_lds_request_cli.txt new file mode 100644 index 0000000000..76a947e366 --- /dev/null +++ b/tests/checks/python-linux/shader_compile_lds_request_cli.txt @@ -0,0 +1 @@ +tests/startup_compile_lds_request_cli_check.py diff --git a/tests/checks/python-linux/shader_import_gfx10_tables_cli.txt b/tests/checks/python-linux/shader_import_gfx10_tables_cli.txt new file mode 100644 index 0000000000..d667a54fe2 --- /dev/null +++ b/tests/checks/python-linux/shader_import_gfx10_tables_cli.txt @@ -0,0 +1 @@ +tests/startup_import_gfx10_tables_cli_check.py diff --git a/tests/checks/python-linux/startup_compute_packed_d16_x_uav.txt b/tests/checks/python-linux/startup_compute_packed_d16_x_uav.txt new file mode 100644 index 0000000000..97c50ccf60 --- /dev/null +++ b/tests/checks/python-linux/startup_compute_packed_d16_x_uav.txt @@ -0,0 +1 @@ +tests/startup_compute_packed_d16_x_uav_check.py diff --git a/tests/checks/python-linux/startup_compute_waterfall_heap.txt b/tests/checks/python-linux/startup_compute_waterfall_heap.txt new file mode 100644 index 0000000000..decf1dc693 --- /dev/null +++ b/tests/checks/python-linux/startup_compute_waterfall_heap.txt @@ -0,0 +1 @@ +tests/startup_compute_waterfall_heap_check.py diff --git a/tests/checks/python-linux/startup_exit_report.txt b/tests/checks/python-linux/startup_exit_report.txt new file mode 100644 index 0000000000..f8c299c41b --- /dev/null +++ b/tests/checks/python-linux/startup_exit_report.txt @@ -0,0 +1 @@ +tests/startup_exit_report_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt new file mode 100644 index 0000000000..26480c9d8e --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_bvh_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt b/tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt new file mode 100644 index 0000000000..ba93e995bf --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_bvh_triangle_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_cselect_descnum.txt b/tests/checks/python-linux/startup_gfx2hlsl_cselect_descnum.txt new file mode 100644 index 0000000000..e8d9138028 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_cselect_descnum.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_cselect_descnum_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt b/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt new file mode 100644 index 0000000000..156f018870 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_image_store_3d1d.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_image_store_3d1d_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_ldexp.txt b/tests/checks/python-linux/startup_gfx2hlsl_ldexp.txt new file mode 100644 index 0000000000..74acfe0204 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_ldexp.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_ldexp_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_lerp_u8.txt b/tests/checks/python-linux/startup_gfx2hlsl_lerp_u8.txt new file mode 100644 index 0000000000..1971e25dbb --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_lerp_u8.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_lerp_u8_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_load_desc.txt b/tests/checks/python-linux/startup_gfx2hlsl_load_desc.txt new file mode 100644 index 0000000000..390b287a5b --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_load_desc.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_load_desc_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_perm_b32.txt b/tests/checks/python-linux/startup_gfx2hlsl_perm_b32.txt new file mode 100644 index 0000000000..fa20b986ff --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_perm_b32.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_perm_b32_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_pixel_first_lane.txt b/tests/checks/python-linux/startup_gfx2hlsl_pixel_first_lane.txt new file mode 100644 index 0000000000..3807cfccb9 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_pixel_first_lane.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_pixel_first_lane_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_pk_minmax.txt b/tests/checks/python-linux/startup_gfx2hlsl_pk_minmax.txt new file mode 100644 index 0000000000..062f169387 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_pk_minmax.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_pk_minmax_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_bitcmp64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_bitcmp64.txt new file mode 100644 index 0000000000..cc4f3baebb --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_bitcmp64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_bitcmp64_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_bitreplicate.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_bitreplicate.txt new file mode 100644 index 0000000000..6202a3e19d --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_bitreplicate.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_bitreplicate_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_bitset64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_bitset64.txt new file mode 100644 index 0000000000..814b296124 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_bitset64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_bitset64_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_brev64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_brev64.txt new file mode 100644 index 0000000000..798c944dd3 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_brev64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_brev64_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_s_cmp64.txt b/tests/checks/python-linux/startup_gfx2hlsl_s_cmp64.txt new file mode 100644 index 0000000000..a1b938326e --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_s_cmp64.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_s_cmp64_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_add_sub_nc_i32.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_add_sub_nc_i32.txt new file mode 100644 index 0000000000..802ac7fdee --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_add_sub_nc_i32.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_dot2.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_dot2.txt new file mode 100644 index 0000000000..2a9dd9d5ff --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_dot2.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_dot2_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_dot4.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_dot4.txt new file mode 100644 index 0000000000..6f3a0a241d --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_dot4.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_dot4_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_dot8.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_dot8.txt new file mode 100644 index 0000000000..d2a2fc535c --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_dot8.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_dot8_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_mad_i32_i16.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_mad_i32_i16.txt new file mode 100644 index 0000000000..1e5c69f3b1 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_mad_i32_i16.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_mad_i32_i16_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_pk_add_sub_16.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_add_sub_16.txt new file mode 100644 index 0000000000..a84b1289d7 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_add_sub_16.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_pk_minmax_i16_u16.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_minmax_i16_u16.txt new file mode 100644 index 0000000000..cadd27d45f --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_minmax_i16_u16.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_pk_mul_mad_16.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_mul_mad_16.txt new file mode 100644 index 0000000000..2fcc156dd1 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_mul_mad_16.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_pk_shift16.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_shift16.txt new file mode 100644 index 0000000000..7bdd5d2d05 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_pk_shift16.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_pk_shift16_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_v_sat_pk_u8_i16.txt b/tests/checks/python-linux/startup_gfx2hlsl_v_sat_pk_u8_i16.txt new file mode 100644 index 0000000000..64bbf3486a --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_v_sat_pk_u8_i16.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_v_sat_pk_u8_i16_check.py diff --git a/tests/checks/python-linux/startup_gfx2hlsl_wave_reduce.txt b/tests/checks/python-linux/startup_gfx2hlsl_wave_reduce.txt new file mode 100644 index 0000000000..61056353c6 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_wave_reduce.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_wave_reduce_check.py diff --git a/tests/checks/python-linux/startup_image_cube.txt b/tests/checks/python-linux/startup_image_cube.txt new file mode 100644 index 0000000000..1ec2d8bd43 --- /dev/null +++ b/tests/checks/python-linux/startup_image_cube.txt @@ -0,0 +1 @@ +tests/startup_image_cube_check.py diff --git a/tests/checks/python-linux/startup_image_sample_l_join.txt b/tests/checks/python-linux/startup_image_sample_l_join.txt new file mode 100644 index 0000000000..db8c2fa17b --- /dev/null +++ b/tests/checks/python-linux/startup_image_sample_l_join.txt @@ -0,0 +1 @@ +tests/startup_image_sample_l_join_check.py diff --git a/tests/checks/python-linux/startup_ui_regression_matrix.txt b/tests/checks/python-linux/startup_ui_regression_matrix.txt new file mode 100644 index 0000000000..48d880d0c9 --- /dev/null +++ b/tests/checks/python-linux/startup_ui_regression_matrix.txt @@ -0,0 +1 @@ +tests/startup_ui_regression_matrix_check.py diff --git a/tests/cmake/README.md b/tests/cmake/README.md new file mode 100644 index 0000000000..4800fd9473 --- /dev/null +++ b/tests/cmake/README.md @@ -0,0 +1,9 @@ +# CTest registration fragments + +Every `tests/cmake/*.cmake` file is included by `CMakeLists.txt` after the existing test +registrations (in name order, and a new file triggers a re-configure). Put new `add_test` and +`set_tests_properties` calls for a family in `tests/cmake/<family>.cmake`, one file per family +or pull request, so two pull requests do not edit the same lines of `CMakeLists.txt`. A +fragment sees the targets, the `INTAKE_PYTHON` variable and the `add_test` wrapper defined above +it, and can set a `COST` property for a test that is not in `X2W_SLOW_TEST_COSTS`. Existing +registrations stay where they are. diff --git a/tests/cmake/bcpack_formats.cmake b/tests/cmake/bcpack_formats.cmake new file mode 100644 index 0000000000..aa1fe16d16 --- /dev/null +++ b/tests/cmake/bcpack_formats.cmake @@ -0,0 +1,15 @@ +add_executable(bcpack_formats_check tests/bcpack_formats_check.cpp) +target_compile_features(bcpack_formats_check PRIVATE cxx_std_17) +target_include_directories(bcpack_formats_check PRIVATE src) +target_compile_definitions(bcpack_formats_check PRIVATE X2W_BCPACK_LANE_TESTS) +add_test(NAME bcpack_all_formats COMMAND bcpack_formats_check) +add_test(NAME bcpack_all_formats_golden_control COMMAND bcpack_formats_check --mutate) +set_tests_properties(bcpack_all_formats bcpack_all_formats_golden_control PROPERTIES TIMEOUT 120) +set_tests_properties(bcpack_all_formats_golden_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_bcpack_storage COMMAND startup_stub_consumer bcpack-storage) +set_tests_properties(startup_bcpack_storage PROPERTIES TIMEOUT 60) + +# Explicit target only: normal builds and all runtime DLLs need no oracle bridge. +add_library(bcpack_oracle_bridge SHARED EXCLUDE_FROM_ALL tests/bcpack_oracle_bridge.cpp) +target_compile_features(bcpack_oracle_bridge PRIVATE cxx_std_17) +target_include_directories(bcpack_oracle_bridge PRIVATE src) diff --git a/tests/cmake/cpu_adx_aot.cmake b/tests/cmake/cpu_adx_aot.cmake new file mode 100644 index 0000000000..39effc66b2 --- /dev/null +++ b/tests/cmake/cpu_adx_aot.cmake @@ -0,0 +1,27 @@ +# Dedicated cpu_adx_aot lifter (32/64-bit ADCX and ADOX, reg + flat memory, dual-carry flags) +if(COMMAND cpu_asm_fixture AND COMMAND cpu_translation AND EXISTS "${INTAKE_PYTHON}") + set(cpu_adx_aot_exports + "op_adcx32_c0,op_adcx32_c1,op_adcx64_c0,op_adcx64_c1," + "op_adox32_o0,op_adox32_o1,op_adox64_o0,op_adox64_o1," + "op_adcx32_mem,op_adcx64_mem,op_adox32_mem,op_adox64_mem," + "op_adcx32_flags,op_adcx64_flags,op_adox32_flags,op_adox64_flags," + "op_adcx64_mem_flags,op_adox64_mem_flags," + "op_adx_dual64_adcx,op_adx_dual64_adox,op_adx_dst_alias,op_adx_discarded_read") + string(CONCAT cpu_adx_aot_exports ${cpu_adx_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_adx_aot_${variant} adx_aot) + cpu_translation(cpu_adx_aot_${variant} cpu_adx_aot "${cpu_adx_aot_exports}") + endforeach() + target_compile_definitions(cpu_adx_aot_altered PRIVATE ALTER_ADX) + add_test(NAME cpu_aot_adx_dedicated COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/adx_aot_check.py" + "$<TARGET_FILE:cpu_adx_aot_original>" + "$<TARGET_FILE:cpu_adx_aot_original_lifted>" + "$<TARGET_FILE:cpu_adx_aot_altered>" + "$<TARGET_FILE:cpu_adx_aot_altered_lifted>" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_adx_dedicated PROPERTIES + TIMEOUT 60 + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_adx_dedicated.txt") +endif() diff --git a/tests/cmake/cpu_call_aot_cli.cmake b/tests/cmake/cpu_call_aot_cli.cmake new file mode 100644 index 0000000000..8f85310f8c --- /dev/null +++ b/tests/cmake/cpu_call_aot_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME cpu_call_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu_call_aot_cli_check.py") + set_tests_properties(cpu_call_aot_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/cpu_chained_aot_cli.cmake b/tests/cmake/cpu_chained_aot_cli.cmake new file mode 100644 index 0000000000..00ad74010a --- /dev/null +++ b/tests/cmake/cpu_chained_aot_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME cpu_chained_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu_chained_aot_cli_check.py") + set_tests_properties(cpu_chained_aot_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/cpu_nt_store.cmake b/tests/cmake/cpu_nt_store.cmake new file mode 100644 index 0000000000..a1ba263740 --- /dev/null +++ b/tests/cmake/cpu_nt_store.cmake @@ -0,0 +1,16 @@ +# Legacy non-temporal stores in the shared lowering (MOVNTPS, MOVNTPD, MOVNTDQ, MOVNTI): each lowers to its +# streaming-store intrinsic, the XMM forms keep the 16-byte alignment fault, and the MMX, SSE4a and VEX +# neighbours stay refused. The fixture compares native bytes with the lowered C++ for stores, misaligned +# targets and a PAGE_NOACCESS target, with controls that remove the alignment test or the store. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME cpu_nt_store COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/nt_store_check.py") + add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/nt_store_fixture.cpp" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/nt_store_fixture.py" emit + "${CMAKE_CURRENT_BINARY_DIR}/nt_store_fixture.cpp" + DEPENDS tests/cpu/nt_store_fixture.py tools/ffx_version_query.py VERBATIM) + add_executable(cpu_nt_store_fixture "${CMAKE_CURRENT_BINARY_DIR}/nt_store_fixture.cpp") + target_compile_features(cpu_nt_store_fixture PRIVATE cxx_std_17) + add_test(NAME cpu_nt_store_fixture COMMAND cpu_nt_store_fixture) + set_tests_properties(cpu_nt_store_fixture PROPERTIES SKIP_RETURN_CODE 77) +endif() diff --git a/tests/cmake/cpu_ranges.cmake b/tests/cmake/cpu_ranges.cmake new file mode 100644 index 0000000000..9865ac25a3 --- /dev/null +++ b/tests/cmake/cpu_ranges.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME cpu_ranges_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu_ranges_check.py") + set_tests_properties(cpu_ranges_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/ffx_create_context_cli.cmake b/tests/cmake/ffx_create_context_cli.cmake new file mode 100644 index 0000000000..d8db528acc --- /dev/null +++ b/tests/cmake/ffx_create_context_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME ffx_create_context_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ffx_create_context_cli_check.py") + set_tests_properties(ffx_create_context_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/ffx_scratch_reference.cmake b/tests/cmake/ffx_scratch_reference.cmake new file mode 100644 index 0000000000..dd4e97a201 --- /dev/null +++ b/tests/cmake/ffx_scratch_reference.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME ffx_scratch_reference_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ffx_scratch_reference_check.py") + set_tests_properties(ffx_scratch_reference_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/gpu_record_gpu_cases_cli.cmake b/tests/cmake/gpu_record_gpu_cases_cli.cmake new file mode 100644 index 0000000000..edfba01bc5 --- /dev/null +++ b/tests/cmake/gpu_record_gpu_cases_cli.cmake @@ -0,0 +1,6 @@ +# Mocked CLI and mutation unit suite for tools/record_gpu_cases.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME gpu_record_gpu_cases_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/record_gpu_cases_cli_check.py") + set_tests_properties(gpu_record_gpu_cases_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/mesh_bitcmp.cmake b/tests/cmake/mesh_bitcmp.cmake new file mode 100644 index 0000000000..88ba3ecbff --- /dev/null +++ b/tests/cmake/mesh_bitcmp.cmake @@ -0,0 +1,10 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME mesh_bitcmp_cpu COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_bitcmp_check.py") + foreach(adapter IN ITEMS hardware warp) + add_test(NAME mesh_bitcmp_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_bitcmp_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(mesh_bitcmp_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/mesh_param_link.cmake b/tests/cmake/mesh_param_link.cmake new file mode 100644 index 0000000000..184128bd4e --- /dev/null +++ b/tests/cmake/mesh_param_link.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME mesh_param_link_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_param_link_check.py") + foreach(adapter IN ITEMS hardware warp) + # Mesh param0..param12 exports paired with gfx2hlsl MeshPixelStage (#2413 T4). + add_test(NAME mesh_param_link_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_param_link_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(mesh_param_link_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") + endforeach() +endif() diff --git a/tests/cmake/native_absdiff.cmake b/tests/cmake/native_absdiff.cmake new file mode 100644 index 0000000000..3fba5b0568 --- /dev/null +++ b/tests/cmake/native_absdiff.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: s_absdiff_i32. The controls compile and check the reference's mutants; the readback needs +# shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_absdiff_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_absdiff_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_absdiff_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_absdiff_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_absdiff_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_absdiff_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_add_sub_sat.cmake b/tests/cmake/native_add_sub_sat.cmake new file mode 100644 index 0000000000..4cbe684db0 --- /dev/null +++ b/tests/cmake/native_add_sub_sat.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_add_nc_i32, v_sub_nc_i32 and the clamp forms of the u32 adds (#3009). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_add_sub_sat_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_add_sub_sat_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_add_sub_sat_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_add_sub_sat_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_add_sub_sat_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_add_sub_sat_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_align_bfm.cmake b/tests/cmake/native_align_bfm.cmake new file mode 100644 index 0000000000..1cd0da59c2 --- /dev/null +++ b/tests/cmake/native_align_bfm.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32 (#2985). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_align_bfm_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_align_bfm_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_align_bfm_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_align_bfm_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_align_bfm_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_align_bfm_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_bitreplicate_exec.cmake b/tests/cmake/native_bitreplicate_exec.cmake new file mode 100644 index 0000000000..371e7a3483 --- /dev/null +++ b/tests/cmake/native_bitreplicate_exec.cmake @@ -0,0 +1,10 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_bitreplicate_exec_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_bitreplicate_exec_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_bitreplicate_exec_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_bitreplicate_exec_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_bitreplicate_exec_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_bitreplicate_exec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_bitscan.cmake b/tests/cmake/native_bitscan.cmake new file mode 100644 index 0000000000..b358fb78dc --- /dev/null +++ b/tests/cmake/native_bitscan.cmake @@ -0,0 +1,14 @@ +# Direct C++ compute: 32-bit bit counts and scans (s_bcnt0/1, s_ff0/1, s_flbit, v_ffbl, v_ffbh). The controls +# compile and check the reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports +# a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_bitscan_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_bitscan_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_bitscan_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_bitscan_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_bitscan_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_bitscan_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_bytewin_store.cmake b/tests/cmake/native_bytewin_store.cmake new file mode 100644 index 0000000000..f74d743cca --- /dev/null +++ b/tests/cmake/native_bytewin_store.cmake @@ -0,0 +1,19 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_bytewin_store_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_bytewin_store_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_bytewin_store_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_bytewin_store_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_bytewin_store_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_bytewin_store_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_raw_store_cache_bits_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_raw_store_cache_bits_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_raw_store_cache_bits_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_raw_store_cache_bits_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_raw_store_cache_bits_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_raw_store_cache_bits_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_carry_vcc_hi.cmake b/tests/cmake/native_carry_vcc_hi.cmake new file mode 100644 index 0000000000..e4b22273c7 --- /dev/null +++ b/tests/cmake/native_carry_vcc_hi.cmake @@ -0,0 +1,16 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxc.exe" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_carry_vcc_hi_check.py") + add_test(NAME native_carry_vcc_hi_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_carry_vcc_hi_controls PROPERTIES TIMEOUT 120) + if(TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_carry_vcc_hi_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" hardware "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_carry_vcc_hi_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + endif() + unset(checker) +endif() diff --git a/tests/cmake/native_compile_dxil_refusals.cmake b/tests/cmake/native_compile_dxil_refusals.cmake new file mode 100644 index 0000000000..8d41d03885 --- /dev/null +++ b/tests/cmake/native_compile_dxil_refusals.cmake @@ -0,0 +1,7 @@ +# Diagnostic .fail files and read-only --refusals census in compile_dxil (#2935). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_compile_dxil_refusals COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_refusals_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_compile_dxil_refusals PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_compile_dxil_rekey.cmake b/tests/cmake/native_compile_dxil_rekey.cmake new file mode 100644 index 0000000000..25559ea344 --- /dev/null +++ b/tests/cmake/native_compile_dxil_rekey.cmake @@ -0,0 +1,7 @@ +# Native cache re-keying (--rekey) in compile_dxil (#2935). +if(TARGET compile_dxil) + add_test(NAME native_compile_dxil_rekey COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_rekey_check.py" + "$<TARGET_FILE:compile_dxil>") + set_tests_properties(native_compile_dxil_rekey PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_compile_dxil_watch.cmake b/tests/cmake/native_compile_dxil_watch.cmake new file mode 100644 index 0000000000..04f2c20e40 --- /dev/null +++ b/tests/cmake/native_compile_dxil_watch.cmake @@ -0,0 +1,7 @@ +# Continuous and one-shot --watch mode for compile_dxil (#2935). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_compile_dxil_watch COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_watch_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_compile_dxil_watch PROPERTIES TIMEOUT 90) +endif() diff --git a/tests/cmake/native_compute_implicit_lod.cmake b/tests/cmake/native_compute_implicit_lod.cmake new file mode 100644 index 0000000000..2baf329e27 --- /dev/null +++ b/tests/cmake/native_compute_implicit_lod.cmake @@ -0,0 +1,15 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(implicit_lod_check "${CMAKE_SOURCE_DIR}/tests/native_compute_implicit_lod_check.py") + add_test(NAME native_compute_implicit_lod_controls COMMAND "${INTAKE_PYTHON}" -B + "${implicit_lod_check}" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_implicit_lod_controls PROPERTIES TIMEOUT 330) + if(TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_compute_implicit_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${implicit_lod_check}" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_compute_implicit_lod_${adapter} PROPERTIES TIMEOUT 540 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/native_compute_manifest_reasons.cmake b/tests/cmake/native_compute_manifest_reasons.cmake new file mode 100644 index 0000000000..a142534f0b --- /dev/null +++ b/tests/cmake/native_compute_manifest_reasons.cmake @@ -0,0 +1,15 @@ +# Named reasons for compute programs that compile but get no runtime manifest (#3224). +# native_compute_manifest_reasons calls the formatter once per reason; the _requests check runs one reachable +# reason through compile_dxil --requests, --refusals, --watch and triage_run.py. +if(TARGET compile_dxil) + add_executable(native_compute_manifest_reasons tests/native_compute_manifest_reasons.cpp) + target_link_libraries(native_compute_manifest_reasons PRIVATE x2w_shader_compiler) + set_property(TARGET native_compute_manifest_reasons PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + add_test(NAME native_compute_manifest_reasons COMMAND native_compute_manifest_reasons) + if(EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_compute_manifest_reasons_requests COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_compute_manifest_reasons_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_manifest_reasons_requests PROPERTIES TIMEOUT 60) + endif() +endif() diff --git a/tests/cmake/native_cvt_norm_f16.cmake b/tests/cmake/native_cvt_norm_f16.cmake new file mode 100644 index 0000000000..8c1717f4c5 --- /dev/null +++ b/tests/cmake/native_cvt_norm_f16.cmake @@ -0,0 +1,20 @@ +# Direct DXIL VOP1/VOP3 v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16. Compute replay needs SM 6.6 with wave32. +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_norm_f16_check.py") + add_test(NAME native_cvt_norm_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_cvt_norm_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_norm_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_norm_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_norm_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_norm_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_cvt_norm_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_cvt_norm_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_cvt_off_f32_i4.cmake b/tests/cmake/native_cvt_off_f32_i4.cmake new file mode 100644 index 0000000000..c69b88654c --- /dev/null +++ b/tests/cmake/native_cvt_off_f32_i4.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP1/VOP3A v_cvt_off_f32_i4. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_cvt_off_f32_i4_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_off_f32_i4_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_off_f32_i4_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_off_f32_i4_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_off_f32_i4_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_off_f32_i4_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_cvt_pk16.cmake b/tests/cmake/native_cvt_pk16.cmake new file mode 100644 index 0000000000..8a536d0bba --- /dev/null +++ b/tests/cmake/native_cvt_pk16.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 (#2995). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_cvt_pk16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pk16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_cvt_pk_u8.cmake b/tests/cmake/native_cvt_pk_u8.cmake new file mode 100644 index 0000000000..6b8b1fce2b --- /dev/null +++ b/tests/cmake/native_cvt_pk_u8.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_cvt_pk_u8_f32 (#2997). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_cvt_pk_u8_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk_u8_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk_u8_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pk_u8_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_cvt_pk_u8_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pk_u8_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_cvt_pknorm_f32.cmake b/tests/cmake/native_cvt_pknorm_f32.cmake new file mode 100644 index 0000000000..bd0bf75f74 --- /dev/null +++ b/tests/cmake/native_cvt_pknorm_f32.cmake @@ -0,0 +1,20 @@ +# Direct DXIL VOP3 v_cvt_pknorm_i16_f32 and v_cvt_pknorm_u16_f32. Compute replay needs SM 6.6 with wave32. +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_pknorm_f32_check.py") + add_test(NAME native_cvt_pknorm_f32_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_cvt_pknorm_f32_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pknorm_f32_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pknorm_f32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_pknorm_f32_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_pknorm_f32_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_cvt_pknorm_f32_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_cvt_pknorm_f32_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_dot4c.cmake b/tests/cmake/native_dot4c.cmake new file mode 100644 index 0000000000..fc6c1639f1 --- /dev/null +++ b/tests/cmake/native_dot4c.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP2 signed byte dot-accumulate. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dot4c_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dot4c_check.py" ir + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_dot4c_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_dot4c_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dot4c_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_dot4c_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dpp8.cmake b/tests/cmake/native_dpp8.cmake new file mode 100644 index 0000000000..08b341c016 --- /dev/null +++ b/tests/cmake/native_dpp8.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dpp8_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp8_check.py" + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp8_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dpp_quad.cmake b/tests/cmake/native_dpp_quad.cmake new file mode 100644 index 0000000000..e45b33e371 --- /dev/null +++ b/tests/cmake/native_dpp_quad.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dpp_quad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_quad_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_quad_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_dpp_quad_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_quad_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_quad_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dpp_row.cmake b/tests/cmake/native_dpp_row.cmake new file mode 100644 index 0000000000..6c350ed139 --- /dev/null +++ b/tests/cmake/native_dpp_row.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dpp_row_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_row_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_row_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_dpp_row_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dpp_row_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_dpp_row_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_dxil_llvm_ident.cmake b/tests/cmake/native_dxil_llvm_ident.cmake new file mode 100644 index 0000000000..280f74fdc4 --- /dev/null +++ b/tests/cmake/native_dxil_llvm_ident.cmake @@ -0,0 +1,13 @@ +# Direct DXIL !llvm.ident metadata check and WARP/hardware draw verification (#2915). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_dxil_llvm_ident_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dxil_llvm_ident_check.py" container + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_dxil_llvm_ident_controls PROPERTIES TIMEOUT 60) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_dxil_llvm_ident_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_dxil_llvm_ident_check.py" draw + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:offscreen_check>" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_dxil_llvm_ident_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() +endif() diff --git a/tests/cmake/native_exec_symbol_b64.cmake b/tests/cmake/native_exec_symbol_b64.cmake new file mode 100644 index 0000000000..c39593c996 --- /dev/null +++ b/tests/cmake/native_exec_symbol_b64.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_exec_symbol_b64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_exec_symbol_b64_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_exec_symbol_b64_controls PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_f16_alu.cmake b/tests/cmake/native_f16_alu.cmake new file mode 100644 index 0000000000..1e1e0944cd --- /dev/null +++ b/tests/cmake/native_f16_alu.cmake @@ -0,0 +1,12 @@ +# v_add_f16, v_sub_f16, v_subrev_f16 and v_mul_f16 in the direct C++ compute path. +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_compute_ir_dump tests/native_compute_ir_dump.cpp) + target_include_directories(native_compute_ir_dump PRIVATE src) + target_link_libraries(native_compute_ir_dump PRIVATE x2w_shader_compiler d3d12 dxgi) + set_property(TARGET native_compute_ir_dump PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + add_test(NAME native_f16_alu_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_f16_alu_check.py" ir "$<TARGET_FILE:native_compute_ir_dump>") + add_test(NAME native_f16_alu_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_f16_alu_check.py" gpu "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_f16_alu_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_fma_f16.cmake b/tests/cmake/native_fma_f16.cmake new file mode 100644 index 0000000000..12e85d19ec --- /dev/null +++ b/tests/cmake/native_fma_f16.cmake @@ -0,0 +1,19 @@ +# v_fma_f16, v_fmac_f16, v_fmamk_f16 and v_fmaak_f16 in the direct C++ compute path. +# Named to sort after native_f16_alu.cmake so native_compute_ir_dump is already defined. +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_fma_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_fma_f16_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_fma_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_fma_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_fma_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fma_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_fma_f16_opsel.cmake b/tests/cmake/native_fma_f16_opsel.cmake new file mode 100644 index 0000000000..56692ba2ea --- /dev/null +++ b/tests/cmake/native_fma_f16_opsel.cmake @@ -0,0 +1,14 @@ +# Sorts after native_f16_alu.cmake, which defines native_compute_ir_dump. +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_fma_f16_opsel_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_opsel_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_fma_f16_opsel_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_fma_f16_opsel_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fma_f16_opsel_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fma_f16_opsel_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_fract_f16.cmake b/tests/cmake/native_fract_f16.cmake new file mode 100644 index 0000000000..c0f9c9f869 --- /dev/null +++ b/tests/cmake/native_fract_f16.cmake @@ -0,0 +1,20 @@ +# Direct Compute and Pixel DXIL VOP1/VOP3 v_fract_f16 checks. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fract_f16_check.py") + add_test(NAME native_fract_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_fract_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_fract_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_fract_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_fract_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fract_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_fract_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_fract_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_fract_f32.cmake b/tests/cmake/native_fract_f32.cmake new file mode 100644 index 0000000000..3d24a542c4 --- /dev/null +++ b/tests/cmake/native_fract_f32.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_fract_f32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fract_f32_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + add_test(NAME native_fract_f32_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_fract_f32_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_fract_f32_controls PROPERTIES TIMEOUT 60) + set_tests_properties(native_fract_f32_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_frexp_f16.cmake b/tests/cmake/native_frexp_f16.cmake new file mode 100644 index 0000000000..4ab9311759 --- /dev/null +++ b/tests/cmake/native_frexp_f16.cmake @@ -0,0 +1,20 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_frexp_f16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_frexp_f16_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_frexp_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_frexp_f16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_frexp_f16_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_frexp_f16_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() +# No GPU and no DXC: evaluates the emitted IR (inline float sources). native_compute_ir_dump is +# defined in native_f16_alu.cmake, which is included before this file. +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_frexp_f16_ir + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_frexp_f16_check.py" + ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_frexp_f16_ir PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_frexp_f32.cmake b/tests/cmake/native_frexp_f32.cmake new file mode 100644 index 0000000000..357a4861a6 --- /dev/null +++ b/tests/cmake/native_frexp_f32.cmake @@ -0,0 +1,12 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_frexp_f32_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_frexp_f32_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_frexp_f32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_frexp_f32_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_frexp_f32_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_frexp_f32_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_gather_compare.cmake b/tests/cmake/native_gather_compare.cmake new file mode 100644 index 0000000000..358d73691a --- /dev/null +++ b/tests/cmake/native_gather_compare.cmake @@ -0,0 +1,9 @@ +# Direct C++ image path: image_gather4_c_lz as textureGatherCmp (#2969). Module and refusal checks, then a graphics +# pipeline created on WARP through native_recording_check --graphics-sampler. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET compile_dxil AND TARGET native_recording_check AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_gather_compare_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_gather_compare_check.py" "$<TARGET_FILE:compile_dxil>" + "${DXC_BIN_DIR}" "$<TARGET_FILE:native_recording_check>") + set_tests_properties(native_gather_compare_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_gather_lod.cmake b/tests/cmake/native_gather_lod.cmake new file mode 100644 index 0000000000..0a915da19d --- /dev/null +++ b/tests/cmake/native_gather_lod.cmake @@ -0,0 +1,15 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_gather_lod_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_gather_lod_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_gather_lod_controls PROPERTIES TIMEOUT 60) + foreach(stage IN ITEMS ps cs) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_gather_lod_${stage}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_gather_lod_check.py" ${stage} + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_gather_lod_${stage}_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + endforeach() +endif() diff --git a/tests/cmake/native_global_load.cmake b/tests/cmake/native_global_load.cmake new file mode 100644 index 0000000000..87698b78f5 --- /dev/null +++ b/tests/cmake/native_global_load.cmake @@ -0,0 +1,8 @@ +# Direct C++ compute: GLOBAL DWORD loads through a root SRV address. Refusals and the module's guards run +# everywhere; the dispatch readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(EXISTS "${INTAKE_PYTHON}" AND TARGET compile_dxil AND TARGET native_store_replay) + add_test(NAME native_global_load_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_global_load_check.py" "$<TARGET_FILE:compile_dxil>" + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_global_load_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_global_srv_heap_replay.cmake b/tests/cmake/native_global_srv_heap_replay.cmake new file mode 100644 index 0000000000..f2dbe64bc9 --- /dev/null +++ b/tests/cmake/native_global_srv_heap_replay.cmake @@ -0,0 +1,19 @@ +# GPU-selected global SRV heap slot: record and offline request replay with captured view types (issue #2908). +# The fixture runs the native recording path (NativeRecording and NativeDispatchStates) and the compile_dxil request +# replay on the same accepted and refused selections. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_global_srv_heap_replay tests/native_global_srv_heap_replay.cpp tests/desktop_gpu.cpp) + target_include_directories(native_global_srv_heap_replay PRIVATE src tests) + target_link_libraries(native_global_srv_heap_replay PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_global_srv_heap_replay PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_global_srv_heap_replay_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_global_srv_heap_replay_check.py" + "$<TARGET_FILE:native_global_srv_heap_replay>" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_global_srv_heap_replay_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() + add_test(NAME native_raw_load_cache_bits_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_raw_load_cache_bits_check.py" + "$<TARGET_FILE:native_global_srv_heap_replay>" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_raw_load_cache_bits_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_graphics_vertex_vcc_join.cmake b/tests/cmake/native_graphics_vertex_vcc_join.cmake new file mode 100644 index 0000000000..3ee4bfb290 --- /dev/null +++ b/tests/cmake/native_graphics_vertex_vcc_join.cmake @@ -0,0 +1,9 @@ +# A per-vertex VCC crosses a two-arm join in a translated vertex stage (#2906). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_graphics_vertex_vcc_join_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_graphics_vertex_vcc_join_check.py" "$<TARGET_FILE:compile_dxil>" + "$<TARGET_FILE:offscreen_check>" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_graphics_vertex_vcc_join_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() +endif() diff --git a/tests/cmake/native_graphics_wqm.cmake b/tests/cmake/native_graphics_wqm.cmake new file mode 100644 index 0000000000..aed792142b --- /dev/null +++ b/tests/cmake/native_graphics_wqm.cmake @@ -0,0 +1,11 @@ +# Cross-quad WQM/EXECZ in a native pixel draw (#2907). native_graphics_wqm_hardware stays in CMakeLists.txt. +# The WARP entry runs every case that one quad per wave can decide; the IR entry checks, without a GPU, that the +# vote's quad and wave operations are emitted before any branch. +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_graphics_wqm_warp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_graphics_wqm_check.py" "$<TARGET_FILE:compile_dxil>" + "$<TARGET_FILE:offscreen_check>" "${DXC_BIN_DIR}" warp) + set_tests_properties(native_graphics_wqm_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + add_test(NAME native_graphics_wqm_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_graphics_wqm_check.py" ir "$<TARGET_FILE:native_pixel_ir_dump>") +endif() diff --git a/tests/cmake/native_half_int_cvt.cmake b/tests/cmake/native_half_int_cvt.cmake new file mode 100644 index 0000000000..482b921b9d --- /dev/null +++ b/tests/cmake/native_half_int_cvt.cmake @@ -0,0 +1,19 @@ +# v_cvt_f16_u16, v_cvt_f16_i16, v_cvt_u16_f16 and v_cvt_i16_f16 in the direct C++ compute path. +# Named to sort after native_f16_alu.cmake so native_compute_ir_dump is already defined. +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_cvt_f16_i16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_f16_i16_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_cvt_f16_i16_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_cvt_f16_i16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_f16_i16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_f16_i16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_cvt_f16_i16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_cvt_f16_i16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_cvt_f16_i16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_heap_offset_add.cmake b/tests/cmake/native_heap_offset_add.cmake new file mode 100644 index 0000000000..f4ab8ffb76 --- /dev/null +++ b/tests/cmake/native_heap_offset_add.cmake @@ -0,0 +1,7 @@ +# A slot 67 resource-heap descriptor address formed by s_add_u32 with its carry (#3224). +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_heap_offset_add COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_heap_offset_add_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_heap_offset_add PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/native_image_atomic.cmake b/tests/cmake/native_image_atomic.cmake new file mode 100644 index 0000000000..1e40f5fe29 --- /dev/null +++ b/tests/cmake/native_image_atomic.cmake @@ -0,0 +1,20 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_image_atomic_check.py") + add_test(NAME native_image_atomic_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_image_atomic_controls PROPERTIES TIMEOUT 60) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_image_atomic_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" hardware "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_image_atomic_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + if(TARGET startup_stream_consumer) + add_test(NAME native_image_atomic_runtime_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" runtime "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" "$<TARGET_FILE:startup_stream_consumer>" hardware) + set_tests_properties(native_image_atomic_runtime_hardware PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endif() + unset(checker) +endif() diff --git a/tests/cmake/native_image_atomic_binops.cmake b/tests/cmake/native_image_atomic_binops.cmake new file mode 100644 index 0000000000..ee4658b799 --- /dev/null +++ b/tests/cmake/native_image_atomic_binops.cmake @@ -0,0 +1,14 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_image_atomic_binops_check.py") + add_test(NAME native_image_atomic_binops_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_image_atomic_binops_controls PROPERTIES TIMEOUT 120) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_image_atomic_binops_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" hardware "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_image_atomic_binops_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_image_cache_flags.cmake b/tests/cmake/native_image_cache_flags.cmake new file mode 100644 index 0000000000..003b7ddc2d --- /dev/null +++ b/tests/cmake/native_image_cache_flags.cmake @@ -0,0 +1,15 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_image_cache_flags_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_image_cache_flags_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_image_cache_flags_controls PROPERTIES TIMEOUT 60) + foreach(stage IN ITEMS ps cs) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_image_cache_flags_${stage}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_image_cache_flags_check.py" ${stage} + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_image_cache_flags_${stage}_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() + endforeach() +endif() diff --git a/tests/cmake/native_int16.cmake b/tests/cmake/native_int16.cmake new file mode 100644 index 0000000000..f762352546 --- /dev/null +++ b/tests/cmake/native_int16.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: non-packed 16-bit integer VOP3 operations (#669). The controls compile, check the op_sel +# refusal and the reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_int16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_int16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_int16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_int16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_int16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_int16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_int16_ternary.cmake b/tests/cmake/native_int16_ternary.cmake new file mode 100644 index 0000000000..ba1085911d --- /dev/null +++ b/tests/cmake/native_int16_ternary.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_mad_u16, v_mad_i16, v_min3_u16, v_min3_i16, v_max3_u16, v_max3_i16, v_med3_u16 and v_med3_i16 (#669). +# Controls verify compilation, refusals and mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_int16_ternary_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_int16_ternary_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_int16_ternary_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_int16_ternary_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_int16_ternary_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_int16_ternary_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_int32_minmax3.cmake b/tests/cmake/native_int32_minmax3.cmake new file mode 100644 index 0000000000..358f92211d --- /dev/null +++ b/tests/cmake/native_int32_minmax3.cmake @@ -0,0 +1,12 @@ +# Direct C++ compute 32-bit integer min3/max3/med3 regression. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_int32_minmax3_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_int32_minmax3_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_int32_minmax3_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_int32_minmax3_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_int32_minmax3_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_int32_minmax3_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_lane_access.cmake b/tests/cmake/native_lane_access.cmake new file mode 100644 index 0000000000..4bd29c4d0a --- /dev/null +++ b/tests/cmake/native_lane_access.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_lane_access_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_lane_access_check.py" "$<TARGET_FILE:compile_dxil>" + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_lane_access_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_lane_spill_descriptor.cmake b/tests/cmake/native_lane_spill_descriptor.cmake new file mode 100644 index 0000000000..113f84e2be --- /dev/null +++ b/tests/cmake/native_lane_spill_descriptor.cmake @@ -0,0 +1,9 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_lane_spill_descriptor_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_lane_spill_descriptor_check.py" "$<TARGET_FILE:compile_dxil>" + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}" "${adapter}") + set_tests_properties(native_lane_spill_descriptor_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endforeach() +endif() diff --git a/tests/cmake/native_ldexp.cmake b/tests/cmake/native_ldexp.cmake new file mode 100644 index 0000000000..081478b51e --- /dev/null +++ b/tests/cmake/native_ldexp.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_ldexp_f32 (#3013). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_ldexp_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_ldexp_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_ldexp_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_ldexp_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_ldexp_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_ldexp_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_ldexp_f16.cmake b/tests/cmake/native_ldexp_f16.cmake new file mode 100644 index 0000000000..abd675c284 --- /dev/null +++ b/tests/cmake/native_ldexp_f16.cmake @@ -0,0 +1,12 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_ldexp_f16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_ldexp_f16_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_ldexp_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_ldexp_f16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_ldexp_f16_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_ldexp_f16_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_lds_request.cmake b/tests/cmake/native_lds_request.cmake new file mode 100644 index 0000000000..933e9be4cb --- /dev/null +++ b/tests/cmake/native_lds_request.cmake @@ -0,0 +1,4 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_lds_request COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_lds_request_check.py" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") +endif() diff --git a/tests/cmake/native_m0.cmake b/tests/cmake/native_m0.cmake new file mode 100644 index 0000000000..68f63c57d4 --- /dev/null +++ b/tests/cmake/native_m0.cmake @@ -0,0 +1,12 @@ +# Defined numeric M0 register in direct compute; stock hardware capability skip remains 77. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_m0_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_m0_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_m0_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_m0_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_m0_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_m0_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_mad32.cmake b/tests/cmake/native_mad32.cmake new file mode 100644 index 0000000000..f3db9a9784 --- /dev/null +++ b/tests/cmake/native_mad32.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: the unfused v_mad_f32 and v_mac_f32 families (#3005). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_mad32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mad32_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_mad32_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mad32_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad32_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_mad32_k.cmake b/tests/cmake/native_mad32_k.cmake new file mode 100644 index 0000000000..efc50cf87a --- /dev/null +++ b/tests/cmake/native_mad32_k.cmake @@ -0,0 +1,19 @@ +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_mad32_k_check.py") + add_test(NAME native_mad32_k_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_mad32_k_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_mad32_k_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad32_k_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_mad32_k_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad32_k_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_mad32_k_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_mad32_k_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_mad64.cmake b/tests/cmake/native_mad64.cmake new file mode 100644 index 0000000000..328844cea9 --- /dev/null +++ b/tests/cmake/native_mad64.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_mad_u64_u32 and v_mad_i64_i32 (#3000). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_mad64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mad64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_mad64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mad64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_mad64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_mul24.cmake b/tests/cmake/native_mul24.cmake new file mode 100644 index 0000000000..88330db85c --- /dev/null +++ b/tests/cmake/native_mul24.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP2/VOP3A 24-bit integer multiplies. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_mul24_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mul24_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_mul24_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_mul24_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_mul24_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_mul24_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_or_saveexec.cmake b/tests/cmake/native_or_saveexec.cmake new file mode 100644 index 0000000000..84ae90a645 --- /dev/null +++ b/tests/cmake/native_or_saveexec.cmake @@ -0,0 +1,6 @@ +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_or_saveexec_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_or_saveexec_check.py" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_or_saveexec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_pack_b32_f16.cmake b/tests/cmake/native_pack_b32_f16.cmake new file mode 100644 index 0000000000..0a1d5b0be1 --- /dev/null +++ b/tests/cmake/native_pack_b32_f16.cmake @@ -0,0 +1,12 @@ +# v_pack_b32_f16 in the direct C++ DXIL path: an IR check on pixel containers (no GPU) and a compute readback. +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_pixel_ir_dump tests/native_pixel_ir_dump.cpp) + target_include_directories(native_pixel_ir_dump PRIVATE src) + target_link_libraries(native_pixel_ir_dump PRIVATE x2w_shader_compiler d3d12 dxgi) + set_property(TARGET native_pixel_ir_dump PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + add_test(NAME native_pack_b32_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pack_b32_f16_check.py" ir "$<TARGET_FILE:native_pixel_ir_dump>") + add_test(NAME native_pack_b32_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pack_b32_f16_check.py" gpu "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_pack_b32_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_packed_dot2.cmake b/tests/cmake/native_packed_dot2.cmake new file mode 100644 index 0000000000..126273ce94 --- /dev/null +++ b/tests/cmake/native_packed_dot2.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP3P halfword dot products. Replay needs SM 6.6 and wave32. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_packed_dot2_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_packed_dot2_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_packed_dot2_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_packed_dot2_f16.cmake b/tests/cmake/native_packed_dot2_f16.cmake new file mode 100644 index 0000000000..99f8fb3bbf --- /dev/null +++ b/tests/cmake/native_packed_dot2_f16.cmake @@ -0,0 +1,19 @@ +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_dot2_f32_f16_check.py") + add_test(NAME native_packed_dot2_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_dot2_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_dot2_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_dot2_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_dot2c_f16.cmake b/tests/cmake/native_packed_dot2c_f16.cmake new file mode 100644 index 0000000000..333c902f52 --- /dev/null +++ b/tests/cmake/native_packed_dot2c_f16.cmake @@ -0,0 +1,20 @@ +# Direct Compute and Pixel DXIL v_dot2c_f32_f16 (accumulate-in-place packed f16 dot product) checks. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_dot2c_f32_f16_check.py") + add_test(NAME native_packed_dot2c_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_dot2c_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2c_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2c_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot2c_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot2c_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_dot2c_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_dot2c_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_dot4.cmake b/tests/cmake/native_packed_dot4.cmake new file mode 100644 index 0000000000..ccbe9ba888 --- /dev/null +++ b/tests/cmake/native_packed_dot4.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP3P byte dots. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_packed_dot4_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_packed_dot4_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot4_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot4_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_packed_dot4_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot4_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_packed_dot8.cmake b/tests/cmake/native_packed_dot8.cmake new file mode 100644 index 0000000000..665627edc6 --- /dev/null +++ b/tests/cmake/native_packed_dot8.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP3P 4-bit nibble dots. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_packed_dot8_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_packed_dot8_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot8_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_dot8_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_packed_dot8_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_dot8_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_packed_f16.cmake b/tests/cmake/native_packed_f16.cmake new file mode 100644 index 0000000000..c2a6ce8939 --- /dev/null +++ b/tests/cmake/native_packed_f16.cmake @@ -0,0 +1,16 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_check.py") + add_test(NAME native_packed_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_f16_clamp.cmake b/tests/cmake/native_packed_f16_clamp.cmake new file mode 100644 index 0000000000..4e0855a52d --- /dev/null +++ b/tests/cmake/native_packed_f16_clamp.cmake @@ -0,0 +1,20 @@ +# Direct DXIL VOP3P clamp on v_pk_add_f16, v_pk_mul_f16, and v_pk_fma_f16. Compute replay needs SM 6.6 with wave32. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_clamp_check.py") + add_test(NAME native_packed_f16_clamp_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_f16_clamp_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_clamp_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_clamp_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_clamp_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_clamp_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_f16_clamp_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_f16_clamp_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_f16_inline.cmake b/tests/cmake/native_packed_f16_inline.cmake new file mode 100644 index 0000000000..7920cf2842 --- /dev/null +++ b/tests/cmake/native_packed_f16_inline.cmake @@ -0,0 +1,19 @@ +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_inline_check.py") + add_test(NAME native_packed_f16_inline_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_packed_f16_inline_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_inline_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_inline_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_f16_inline_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_f16_inline_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_f16_inline_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_f16_inline_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_packed_minmax.cmake b/tests/cmake/native_packed_minmax.cmake new file mode 100644 index 0000000000..814f173e1d --- /dev/null +++ b/tests/cmake/native_packed_minmax.cmake @@ -0,0 +1,16 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_SOURCE_DIR}/tests/native_packed_minmax_check.py") + add_test(NAME native_packed_minmax_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_minmax_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_packed_minmax_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_packed_minmax_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_packed_minmax_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_packed_minmax_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_perm_lerp.cmake b/tests/cmake/native_perm_lerp.cmake new file mode 100644 index 0000000000..e9a5caca71 --- /dev/null +++ b/tests/cmake/native_perm_lerp.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_perm_b32 and v_lerp_u8. The controls compile and check the reference's mutants; the +# readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_perm_lerp_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_perm_lerp_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_perm_lerp_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_perm_lerp_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_perm_lerp_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_perm_lerp_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_permlane.cmake b/tests/cmake/native_permlane.cmake new file mode 100644 index 0000000000..81ff175737 --- /dev/null +++ b/tests/cmake/native_permlane.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_permlane_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_permlane_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_permlane_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_permlane_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_permlane_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_permlane_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_pixel_atomic.cmake b/tests/cmake/native_pixel_atomic.cmake new file mode 100644 index 0000000000..92f8ef3bbf --- /dev/null +++ b/tests/cmake/native_pixel_atomic.cmake @@ -0,0 +1,10 @@ +# Native raw DWORD atomic add through the graphics runtime's published cache. +if(TARGET compile_dxil AND TARGET startup_stream_consumer + AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_pixel_atomic_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pixel_atomic_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_pixel_atomic_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() +endif() diff --git a/tests/cmake/native_pixel_raw_uav.cmake b/tests/cmake/native_pixel_raw_uav.cmake new file mode 100644 index 0000000000..5783309cd4 --- /dev/null +++ b/tests/cmake/native_pixel_raw_uav.cmake @@ -0,0 +1,14 @@ +# Source-built native pixel buffer writes through the runtime-published graphics cache. +add_executable(native_raw_buffer_view_check tests/native_raw_buffer_view_check.cpp) +target_include_directories(native_raw_buffer_view_check PRIVATE src) +target_compile_features(native_raw_buffer_view_check PRIVATE cxx_std_17) +add_test(NAME native_raw_buffer_view_controls COMMAND native_raw_buffer_view_check) +if(TARGET compile_dxil AND TARGET startup_stream_consumer + AND EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_pixel_raw_uav_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pixel_raw_uav_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_pixel_raw_uav_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endforeach() +endif() diff --git a/tests/cmake/native_pk_add_sub_16.cmake b/tests/cmake/native_pk_add_sub_16.cmake new file mode 100644 index 0000000000..76a368e617 --- /dev/null +++ b/tests/cmake/native_pk_add_sub_16.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP3P packed 16-bit add/sub. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_pk_add_sub_16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pk_add_sub_16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_add_sub_16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_add_sub_16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pk_add_sub_16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_add_sub_16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_pk_fmac_f16.cmake b/tests/cmake/native_pk_fmac_f16.cmake new file mode 100644 index 0000000000..332ae1eb54 --- /dev/null +++ b/tests/cmake/native_pk_fmac_f16.cmake @@ -0,0 +1,20 @@ +# Direct Compute and Pixel DXIL VOP2 v_pk_fmac_f16 checks. +if(TARGET native_compute_ir_dump AND TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_pk_fmac_f16_check.py") + add_test(NAME native_pk_fmac_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${checker}" ir "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_pk_fmac_f16_ir PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_fmac_f16_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_fmac_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_fmac_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_fmac_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_pk_fmac_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_pk_fmac_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_pk_mul_mad_16.cmake b/tests/cmake/native_pk_mul_mad_16.cmake new file mode 100644 index 0000000000..7da8cc89ad --- /dev/null +++ b/tests/cmake/native_pk_mul_mad_16.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP3P packed 16-bit multiply/mad. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_pk_mul_mad_16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pk_mul_mad_16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_mul_mad_16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_mul_mad_16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pk_mul_mad_16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_mul_mad_16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_pk_shift16.cmake b/tests/cmake/native_pk_shift16.cmake new file mode 100644 index 0000000000..6d198e2028 --- /dev/null +++ b/tests/cmake/native_pk_shift16.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP3P packed 16-bit shifts. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_pk_shift16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pk_shift16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_shift16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_pk_shift16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_pk_shift16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_pk_shift16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_rcp_iflag.cmake b/tests/cmake/native_rcp_iflag.cmake new file mode 100644 index 0000000000..08e8d49151 --- /dev/null +++ b/tests/cmake/native_rcp_iflag.cmake @@ -0,0 +1,16 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND + EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_rcp_iflag_check.py") + add_test(NAME native_rcp_iflag_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_rcp_iflag_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_rcp_iflag_compute_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_rcp_iflag_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_rcp_iflag_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_rcp_iflag_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() + unset(checker) +endif() diff --git a/tests/cmake/native_round_f16.cmake b/tests/cmake/native_round_f16.cmake new file mode 100644 index 0000000000..bb2126c1ee --- /dev/null +++ b/tests/cmake/native_round_f16.cmake @@ -0,0 +1,12 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_round_f16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_round_f16_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_round_f16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_round_f16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_round_f16_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_round_f16_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_rtv_variant.cmake b/tests/cmake/native_rtv_variant.cmake new file mode 100644 index 0000000000..bdc28db6b7 --- /dev/null +++ b/tests/cmake/native_rtv_variant.cmake @@ -0,0 +1,15 @@ +# RTV variant requests (req_<key>.rtv) resolved and cached by compile_dxil --requests (#2980). The controls need no +# device; the warp and hardware entries draw each variant through the stand-in and read the target back. +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${DXC_BIN_DIR}/dxc.exe") + add_test(NAME native_rtv_variant_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_rtv_variant_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_rtv_variant_controls PROPERTIES TIMEOUT 60) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_rtv_variant_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_rtv_variant_check.py" e2e + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_rtv_variant_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/native_s_lshl_add_u32.cmake b/tests/cmake/native_s_lshl_add_u32.cmake new file mode 100644 index 0000000000..14ba50755a --- /dev/null +++ b/tests/cmake/native_s_lshl_add_u32.cmake @@ -0,0 +1,12 @@ +# Direct compute SOP2 s_lshl{1,2,3,4}_add_u32. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_s_lshl_add_u32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_s_lshl_add_u32_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_lshl_add_u32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_s_lshl_add_u32_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_s_lshl_add_u32_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_lshl_add_u32_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_s_not_b64_exec.cmake b/tests/cmake/native_s_not_b64_exec.cmake new file mode 100644 index 0000000000..21a73092cf --- /dev/null +++ b/tests/cmake/native_s_not_b64_exec.cmake @@ -0,0 +1,12 @@ +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_s_not_b64_exec_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_s_not_b64_exec_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_not_b64_exec_controls PROPERTIES TIMEOUT 60) + if(TARGET native_store_replay) + add_test(NAME native_s_not_b64_exec_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_s_not_b64_exec_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_not_b64_exec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() +endif() diff --git a/tests/cmake/native_s_quadmask.cmake b/tests/cmake/native_s_quadmask.cmake new file mode 100644 index 0000000000..40a2cdae49 --- /dev/null +++ b/tests/cmake/native_s_quadmask.cmake @@ -0,0 +1,12 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_s_quadmask_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_s_quadmask_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_quadmask_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_s_quadmask_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_s_quadmask_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_quadmask_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_s_sext_i32.cmake b/tests/cmake/native_s_sext_i32.cmake new file mode 100644 index 0000000000..3205303966 --- /dev/null +++ b/tests/cmake/native_s_sext_i32.cmake @@ -0,0 +1,12 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_s_sext_i32_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_s_sext_i32_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_sext_i32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_s_sext_i32_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_s_sext_i32_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_s_sext_i32_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_sad.cmake b/tests/cmake/native_sad.cmake new file mode 100644 index 0000000000..e190caa325 --- /dev/null +++ b/tests/cmake/native_sad.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32 and v_msad_u8 (#2987). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_sad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sad_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_sad_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_sad_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sad_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_sad_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu64.cmake b/tests/cmake/native_salu64.cmake new file mode 100644 index 0000000000..68deac5350 --- /dev/null +++ b/tests/cmake/native_salu64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu_bfe64_brev64.cmake b/tests/cmake/native_salu_bfe64_brev64.cmake new file mode 100644 index 0000000000..21c2716664 --- /dev/null +++ b/tests/cmake/native_salu_bfe64_brev64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu_bfe64_brev64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_bfe64_brev64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_bfe64_brev64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu_bfe64_brev64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_bfe64_brev64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_bfe64_brev64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu_bitscan64.cmake b/tests/cmake/native_salu_bitscan64.cmake new file mode 100644 index 0000000000..8a4f674e34 --- /dev/null +++ b/tests/cmake/native_salu_bitscan64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu_bitscan64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_bitscan64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_bitscan64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu_bitscan64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_bitscan64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_bitscan64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu_cmov.cmake b/tests/cmake/native_salu_cmov.cmake new file mode 100644 index 0000000000..e067e1ea2c --- /dev/null +++ b/tests/cmake/native_salu_cmov.cmake @@ -0,0 +1,17 @@ +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_salu_cmov_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_salu_cmov_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_salu_cmov_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu_cmov_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_cmov_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_cmov_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu_cmov_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_cmov_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_cmov_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu_cmp64.cmake b/tests/cmake/native_salu_cmp64.cmake new file mode 100644 index 0000000000..2d71973e4c --- /dev/null +++ b/tests/cmake/native_salu_cmp64.cmake @@ -0,0 +1,17 @@ +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_salu_cmp64_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_salu_cmp64_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_salu_cmp64_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu_cmp64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_cmp64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_cmp64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu_cmp64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_cmp64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_cmp64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_salu_shift64.cmake b/tests/cmake/native_salu_shift64.cmake new file mode 100644 index 0000000000..83b8b4fac9 --- /dev/null +++ b/tests/cmake/native_salu_shift64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_salu_shift64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_shift64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_shift64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_salu_shift64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_salu_shift64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_salu_shift64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_sample_ssamp.cmake b/tests/cmake/native_sample_ssamp.cmake new file mode 100644 index 0000000000..abbd1a2183 --- /dev/null +++ b/tests/cmake/native_sample_ssamp.cmake @@ -0,0 +1,9 @@ +if(TARGET compile_dxil AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_sample_ssamp_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sample_ssamp_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(native_sample_ssamp_${adapter} PROPERTIES TIMEOUT 150 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/native_sampler_heap.cmake b/tests/cmake/native_sampler_heap.cmake new file mode 100644 index 0000000000..7f17283419 --- /dev/null +++ b/tests/cmake/native_sampler_heap.cmake @@ -0,0 +1,15 @@ +# Samplers read from the directly indexed sampler heap at a fixed index, translated natively (issue #3076). +# The fixture builds source-written compute requests, runs them on a sampler heap of decoys and compares with a CPU model; +# the check script also covers the compile refusals. _warp skips (77): WARP has no 32-lane waves. +if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll" AND EXISTS "${INTAKE_PYTHON}") + add_executable(native_sampler_heap tests/native_sampler_heap.cpp tests/desktop_gpu.cpp) + target_include_directories(native_sampler_heap PRIVATE src tests) + target_link_libraries(native_sampler_heap PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) + set_property(TARGET native_sampler_heap PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_sampler_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sampler_heap_check.py" + "$<TARGET_FILE:native_sampler_heap>" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(native_sampler_heap_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180) + endforeach() +endif() diff --git a/tests/cmake/native_sat_pk_u8_i16.cmake b/tests/cmake/native_sat_pk_u8_i16.cmake new file mode 100644 index 0000000000..eeaf792058 --- /dev/null +++ b/tests/cmake/native_sat_pk_u8_i16.cmake @@ -0,0 +1,12 @@ +# Direct compute VOP1/VOP3A v_sat_pk_u8_i16. Replay needs SM 6.6 with a physical wave32 adapter. +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_sat_pk_u8_i16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sat_pk_u8_i16_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_sat_pk_u8_i16_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_sat_pk_u8_i16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sat_pk_u8_i16_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_sat_pk_u8_i16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_saveexec_wrexec.cmake b/tests/cmake/native_saveexec_wrexec.cmake new file mode 100644 index 0000000000..9aee2ae897 --- /dev/null +++ b/tests/cmake/native_saveexec_wrexec.cmake @@ -0,0 +1,17 @@ +if(TARGET native_compute_ir_dump AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_saveexec_wrexec_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_saveexec_wrexec_check.py" ir + "$<TARGET_FILE:native_compute_ir_dump>") + set_tests_properties(native_saveexec_wrexec_ir PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_saveexec_wrexec_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_saveexec_wrexec_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_saveexec_wrexec_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_saveexec_wrexec_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_saveexec_wrexec_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_saveexec_wrexec_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_scalar_mask64.cmake b/tests/cmake/native_scalar_mask64.cmake new file mode 100644 index 0000000000..e75371335e --- /dev/null +++ b/tests/cmake/native_scalar_mask64.cmake @@ -0,0 +1,14 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxc.exe" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND + EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_scalar_mask64_check.py") + add_test(NAME native_scalar_mask64_controls COMMAND "${INTAKE_PYTHON}" -B + "${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_scalar_mask64_controls PROPERTIES TIMEOUT 120) + if(TARGET native_store_replay) + add_test(NAME native_scalar_mask64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${checker}" hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_scalar_mask64_hardware PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endif() + unset(checker) +endif() diff --git a/tests/cmake/native_sdwa_f16.cmake b/tests/cmake/native_sdwa_f16.cmake new file mode 100644 index 0000000000..a1258520bd --- /dev/null +++ b/tests/cmake/native_sdwa_f16.cmake @@ -0,0 +1,8 @@ +# SDWA binary16 arithmetic in the direct C++ compute path. +if(TARGET native_compute_ir_dump) + add_test(NAME native_sdwa_f16_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_check.py" ir "$<TARGET_FILE:native_compute_ir_dump>") + add_test(NAME native_sdwa_f16_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_check.py" gpu "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_sdwa_f16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_sdwa_f16_scalar.cmake b/tests/cmake/native_sdwa_f16_scalar.cmake new file mode 100644 index 0000000000..3cece43a8e --- /dev/null +++ b/tests/cmake/native_sdwa_f16_scalar.cmake @@ -0,0 +1,12 @@ +# Scalar sources in direct C++ binary16 SDWA arithmetic. +if(TARGET native_compute_ir_dump) + add_test(NAME native_sdwa_f16_scalar_ir COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_scalar_check.py" + ir "$<TARGET_FILE:native_compute_ir_dump>") +endif() +if(TARGET native_store_replay) + add_test(NAME native_sdwa_f16_scalar_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_scalar_check.py" + gpu "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_sdwa_f16_scalar_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_sdwa_vcc_hi.cmake b/tests/cmake/native_sdwa_vcc_hi.cmake new file mode 100644 index 0000000000..d1c10a6fcf --- /dev/null +++ b/tests/cmake/native_sdwa_vcc_hi.cmake @@ -0,0 +1,6 @@ +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_sdwa_vcc_hi_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_sdwa_vcc_hi_check.py" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_sdwa_vcc_hi_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_shift64.cmake b/tests/cmake/native_shift64.cmake new file mode 100644 index 0000000000..4d1956cb93 --- /dev/null +++ b/tests/cmake/native_shift64.cmake @@ -0,0 +1,11 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_shift64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_shift64_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_shift64_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_shift64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_shift64_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_shift64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_signed_forms.cmake b/tests/cmake/native_signed_forms.cmake new file mode 100644 index 0000000000..2866debfd8 --- /dev/null +++ b/tests/cmake/native_signed_forms.cmake @@ -0,0 +1,13 @@ +# Direct C++ compute: v_ashrrev_i64 and v_mad_i32_i24 (#2991). The controls compile and check the +# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77). +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_signed_forms_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_signed_forms_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_signed_forms_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_signed_forms_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_signed_forms_check.py" hardware + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_signed_forms_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_slot67_wave_size.cmake b/tests/cmake/native_slot67_wave_size.cmake new file mode 100644 index 0000000000..d9b4773a17 --- /dev/null +++ b/tests/cmake/native_slot67_wave_size.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_slot67_wave_size_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_slot67_wave_size_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_slot67_wave_size_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_smem_vcc.cmake b/tests/cmake/native_smem_vcc.cmake new file mode 100644 index 0000000000..3193811f5d --- /dev/null +++ b/tests/cmake/native_smem_vcc.cmake @@ -0,0 +1,6 @@ +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_smem_vcc_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_smem_vcc_check.py" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_smem_vcc_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_smem_vcc_wave64.cmake b/tests/cmake/native_smem_vcc_wave64.cmake new file mode 100644 index 0000000000..35004dffa2 --- /dev/null +++ b/tests/cmake/native_smem_vcc_wave64.cmake @@ -0,0 +1,14 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_smem_vcc_wave64_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_smem_vcc_wave64_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_smem_vcc_wave64_controls PROPERTIES TIMEOUT 60) +endif() + +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_smem_vcc_wave64_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_smem_vcc_wave64_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_smem_vcc_wave64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_smov_exec_hi.cmake b/tests/cmake/native_smov_exec_hi.cmake new file mode 100644 index 0000000000..dea0fb06ca --- /dev/null +++ b/tests/cmake/native_smov_exec_hi.cmake @@ -0,0 +1,10 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_smov_exec_hi_wave64 + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_smov_exec_hi_check.py" + wave64 "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_smov_exec_hi_wave64 PROPERTIES TIMEOUT 60) + add_test(NAME native_smov_exec_hi_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_smov_exec_hi_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_smov_exec_hi_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_startup_request_cache.cmake b/tests/cmake/native_startup_request_cache.cmake new file mode 100644 index 0000000000..1b88f24cfd --- /dev/null +++ b/tests/cmake/native_startup_request_cache.cmake @@ -0,0 +1,15 @@ +# Startup request consumption and runtime cache publication for compile_dxil (#2933). +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND TARGET offscreen_check + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_startup_request_cache_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_startup_request_cache_check.py" controls + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_startup_request_cache_controls PROPERTIES TIMEOUT 60) + foreach(backend IN ITEMS warp hardware) + add_test(NAME native_startup_request_cache_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_startup_request_cache_check.py" e2e + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" + "$<TARGET_FILE:offscreen_check>" "${DXC_BIN_DIR}" ${backend}) + set_tests_properties(native_startup_request_cache_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 90) + endforeach() +endif() diff --git a/tests/cmake/native_store_replay.cmake b/tests/cmake/native_store_replay.cmake new file mode 100644 index 0000000000..3a57f8f9ae --- /dev/null +++ b/tests/cmake/native_store_replay.cmake @@ -0,0 +1,6 @@ +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_store_replay_adapter_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_store_replay_adapter_check.py" + "$<TARGET_FILE:native_store_replay>") + set_tests_properties(native_store_replay_adapter_controls PROPERTIES TIMEOUT 30) +endif() diff --git a/tests/cmake/native_uav_slots.cmake b/tests/cmake/native_uav_slots.cmake new file mode 100644 index 0000000000..3a0a5d3d73 --- /dev/null +++ b/tests/cmake/native_uav_slots.cmake @@ -0,0 +1,6 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_uav_slots_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_uav_slots_check.py" "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_uav_slots_controls PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/cmake/native_v_xnor_b32.cmake b/tests/cmake/native_v_xnor_b32.cmake new file mode 100644 index 0000000000..a04977af9a --- /dev/null +++ b/tests/cmake/native_v_xnor_b32.cmake @@ -0,0 +1,12 @@ +if(X2W_HAVE_DXCAPI AND EXISTS "${INTAKE_PYTHON}") + add_test(NAME native_v_xnor_b32_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_v_xnor_b32_check.py" + controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_v_xnor_b32_controls PROPERTIES TIMEOUT 60) + add_test(NAME native_v_xnor_b32_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_v_xnor_b32_check.py" + hardware "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_v_xnor_b32_hardware PROPERTIES + SKIP_RETURN_CODE 77 + TIMEOUT 60) +endif() diff --git a/tests/cmake/native_vopc_cmp64.cmake b/tests/cmake/native_vopc_cmp64.cmake new file mode 100644 index 0000000000..5c290878fc --- /dev/null +++ b/tests/cmake/native_vopc_cmp64.cmake @@ -0,0 +1,7 @@ +if(TARGET native_store_replay AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_vopc_cmp64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_vopc_cmp64_check.py" + "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_vopc_cmp64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/cmake/native_wave64_exec_salu.cmake b/tests/cmake/native_wave64_exec_salu.cmake new file mode 100644 index 0000000000..53d343b15d --- /dev/null +++ b/tests/cmake/native_wave64_exec_salu.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wave64_exec_salu_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave64_exec_salu_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_wave64_exec_salu_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/native_wave_virtual_derivative.cmake b/tests/cmake/native_wave_virtual_derivative.cmake new file mode 100644 index 0000000000..aa3b68916c --- /dev/null +++ b/tests/cmake/native_wave_virtual_derivative.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wave_virtual_derivative_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_wave_virtual_derivative_check.py" + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(native_wave_virtual_derivative_controls PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/cmake/native_wrexec64.cmake b/tests/cmake/native_wrexec64.cmake new file mode 100644 index 0000000000..8f0f147d7a --- /dev/null +++ b/tests/cmake/native_wrexec64.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET native_store_replay AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_wrexec64_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_wrexec64_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}") + set_tests_properties(native_wrexec64_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +endif() diff --git a/tests/cmake/patch_manifest.cmake b/tests/cmake/patch_manifest.cmake new file mode 100644 index 0000000000..7702445aab --- /dev/null +++ b/tests/cmake/patch_manifest.cmake @@ -0,0 +1,7 @@ +# Patch manifest schema, loader and hash gate (tools/patch_manifest.py). +if(EXISTS "${INTAKE_PYTHON}") + add_test( + NAME patch_manifest_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/patch_manifest_check.py" + ) +endif() diff --git a/tests/cmake/pe_import_routing.cmake b/tests/cmake/pe_import_routing.cmake new file mode 100644 index 0000000000..955dc0486a --- /dev/null +++ b/tests/cmake/pe_import_routing.cmake @@ -0,0 +1,6 @@ +# Unit, boundary-validation, and temp-copy mutation checks for tools/import_routing.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME pe_import_routing_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/import_routing_check.py") + set_tests_properties(pe_import_routing_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/runtime_host_commit_unit.cmake b/tests/cmake/runtime_host_commit_unit.cmake new file mode 100644 index 0000000000..3261e3806d --- /dev/null +++ b/tests/cmake/runtime_host_commit_unit.cmake @@ -0,0 +1,6 @@ +# Pure-Python unit, boundary-validation, and temp-copy mutation checks for tools/host_commit.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME runtime_host_commit_unit_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/host_commit_unit_check.py") + set_tests_properties(runtime_host_commit_unit_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/shader_compile_lds_request_cli.cmake b/tests/cmake/shader_compile_lds_request_cli.cmake new file mode 100644 index 0000000000..b175d618d6 --- /dev/null +++ b/tests/cmake/shader_compile_lds_request_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME shader_compile_lds_request_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compile_lds_request_cli_check.py") + set_tests_properties(shader_compile_lds_request_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/shader_dxc_cache_unit.cmake b/tests/cmake/shader_dxc_cache_unit.cmake new file mode 100644 index 0000000000..d0a04c4762 --- /dev/null +++ b/tests/cmake/shader_dxc_cache_unit.cmake @@ -0,0 +1,8 @@ +# Unit and mutation suite for tools/dxc_cache.py (atomic restore, symlink/file-backed +# cache_dir fallback, -Fo dir/symlink refusal, multi-output -Fc/-Fd, corrupt cache miss, +# and -I/#include bypass). +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME shader_dxc_cache_unit_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/dxc_cache_unit_check.py") + set_tests_properties(shader_dxc_cache_unit_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/shader_import_gfx10_tables_cli.cmake b/tests/cmake/shader_import_gfx10_tables_cli.cmake new file mode 100644 index 0000000000..c644087712 --- /dev/null +++ b/tests/cmake/shader_import_gfx10_tables_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME shader_import_gfx10_tables_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_import_gfx10_tables_cli_check.py") + set_tests_properties(shader_import_gfx10_tables_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/shader_probe_root_devices_cli.cmake b/tests/cmake/shader_probe_root_devices_cli.cmake new file mode 100644 index 0000000000..27fa4df3de --- /dev/null +++ b/tests/cmake/shader_probe_root_devices_cli.cmake @@ -0,0 +1,6 @@ +# CLI, upfront path/symlink/hardlink guard, atomic output, and temp-copy mutation checks for tools/probe_root_devices.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME shader_probe_root_devices_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/probe_root_devices_cli_check.py") + set_tests_properties(shader_probe_root_devices_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/startup_compute_builder_gate.cmake b/tests/cmake/startup_compute_builder_gate.cmake new file mode 100644 index 0000000000..6370ce4dcb --- /dev/null +++ b/tests/cmake/startup_compute_builder_gate.cmake @@ -0,0 +1,39 @@ +# All-or-none gate for the console BVH builder's compute pipeline set +# (src/startup_stubs/compute_builder_gate.h), without a device or a title module. +add_executable(startup_compute_builder_gate_check tests/startup_compute_builder_gate_check.cpp) +target_include_directories(startup_compute_builder_gate_check PRIVATE src) +target_compile_features(startup_compute_builder_gate_check PRIVATE cxx_std_17) +add_test(NAME startup_compute_builder_gate COMMAND startup_compute_builder_gate_check) + +# A source-built module whose basename matches XboxBvhBuilder.dll, so the public slot 62 path can +# exercise the caller-module tag and the direct/indirect Dispatch gate. +add_library(startup_builder_module SHARED tests/startup_builder_module.cpp) +set_target_properties(startup_builder_module PROPERTIES OUTPUT_NAME XboxBvhBuilder) +target_compile_features(startup_builder_module PRIVATE cxx_std_17) +target_link_libraries(startup_builder_module PRIVATE d3d12) + +add_executable(startup_compute_builder_gate_runtime tests/startup_compute_builder_gate_runtime.cpp) +target_compile_features(startup_compute_builder_gate_runtime PRIVATE cxx_std_17) +target_link_libraries(startup_compute_builder_gate_runtime PRIVATE d3d12_xs_shim d3d12 dxgi) +set(startup_builder_gate_header "${CMAKE_CURRENT_BINARY_DIR}/startup_builder_gate_cs.h") +add_custom_command(OUTPUT "${startup_builder_gate_header}" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_0 -E main -Vn builder_gate_cs + -Fh "${startup_builder_gate_header}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_builder_gate.hlsl" + DEPENDS tests/startup_builder_gate.hlsl VERBATIM) +target_sources(startup_compute_builder_gate_runtime PRIVATE "${startup_builder_gate_header}") +target_include_directories(startup_compute_builder_gate_runtime PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_compute_builder_gate_runtime + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_builder_gate_runtime_check.py" + "$<TARGET_FILE:startup_compute_builder_gate_runtime>" "$<TARGET_FILE:startup_builder_module>") +endif() + +# Slot 67 request publication must keep its normal path with the gate enabled: slot 67 never +# carries the slot 62 builder tag. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + add_test(NAME startup_compute_builder_gate_request_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_check.py" + "$<TARGET_FILE:startup_stream_consumer>") + set_tests_properties(startup_compute_builder_gate_request_warp PROPERTIES + ENVIRONMENT "X2W_COMPUTE_BUILDER_GATE=1" TIMEOUT 180) +endif() diff --git a/tests/cmake/startup_compute_dispatch_array.cmake b/tests/cmake/startup_compute_dispatch_array.cmake new file mode 100644 index 0000000000..ad9b4f92b1 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_array.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_array_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_array_check.py" "$<TARGET_FILE:startup_stream_consumer>" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_array_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_dispatch_array_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_array_check.py" "$<TARGET_FILE:startup_stream_consumer>" + "${DXC_EXECUTABLE}" ${adapter} --d16) + set_tests_properties(startup_compute_dispatch_array_d16_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_dispatch_native.cmake b/tests/cmake/startup_compute_dispatch_native.cmake new file mode 100644 index 0000000000..cb7943b579 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_native.cmake @@ -0,0 +1,11 @@ +# A slot 67 request translated in-process by the C++ compiler (X2W_NATIVE_SHADERS) and dispatched through the +# stand-in. Without 32-lane waves the check verifies its refusals and exits 77. +if(TARGET x2w_shader_compiler AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_native_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_native_check.py" + "$<TARGET_FILE:startup_stream_consumer>" "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_dispatch_native_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_dispatch_output.cmake b/tests/cmake/startup_compute_dispatch_output.cmake new file mode 100644 index 0000000000..1460af0525 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_output.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_output_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_output_check.py" "$<TARGET_FILE:startup_stream_consumer>" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_output_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_dispatch_texture_dims.cmake b/tests/cmake/startup_compute_dispatch_texture_dims.cmake new file mode 100644 index 0000000000..e90a58bce4 --- /dev/null +++ b/tests/cmake/startup_compute_dispatch_texture_dims.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_dispatch_texture_dims_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_dims_check.py" "$<TARGET_FILE:startup_stream_consumer>" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_dispatch_texture_dims_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_half_buffer_uav.cmake b/tests/cmake/startup_compute_half_buffer_uav.cmake new file mode 100644 index 0000000000..591700ac8f --- /dev/null +++ b/tests/cmake/startup_compute_half_buffer_uav.cmake @@ -0,0 +1,17 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME startup_compute_half_buffer_uav_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_half_buffer_uav_check.py" compile + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(startup_compute_half_buffer_uav_controls PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_half_buffer_uav_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_half_buffer_uav_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" "$<TARGET_FILE:offscreen_check>" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_half_buffer_uav_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_packed_d16_x_uav.cmake b/tests/cmake/startup_compute_packed_d16_x_uav.cmake new file mode 100644 index 0000000000..e9fa0f6ccf --- /dev/null +++ b/tests/cmake/startup_compute_packed_d16_x_uav.cmake @@ -0,0 +1,22 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_compute_packed_d16_x_uav_reference COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_packed_d16_x_uav_check.py" reference) + set_tests_properties(startup_compute_packed_d16_x_uav_reference PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME startup_compute_packed_d16_x_uav_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_packed_d16_x_uav_check.py" compile + "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}") + set_tests_properties(startup_compute_packed_d16_x_uav_controls PROPERTIES TIMEOUT 60) +endif() +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND TARGET offscreen_check AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_packed_d16_x_uav_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_packed_d16_x_uav_check.py" + "$<TARGET_FILE:compile_dxil>" "$<TARGET_FILE:startup_stream_consumer>" "$<TARGET_FILE:offscreen_check>" + "${DXC_BIN_DIR}" ${adapter}) + set_tests_properties(startup_compute_packed_d16_x_uav_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_root_srv.cmake b/tests/cmake/startup_compute_root_srv.cmake new file mode 100644 index 0000000000..fa30001130 --- /dev/null +++ b/tests/cmake/startup_compute_root_srv.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_root_srv_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_root_srv_dispatch_check.py" + "$<TARGET_FILE:startup_stream_consumer>" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_root_srv_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_compute_waterfall_heap.cmake b/tests/cmake/startup_compute_waterfall_heap.cmake new file mode 100644 index 0000000000..a0ac246c9a --- /dev/null +++ b/tests/cmake/startup_compute_waterfall_heap.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_waterfall_heap_oracle_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_waterfall_heap_check.py" + --oracle "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_compute_waterfall_heap_oracle_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_waterfall_heap_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_waterfall_heap_check.py" + --dispatch "$<TARGET_FILE:startup_stream_consumer>" "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_compute_waterfall_heap_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_debug_launch_args.cmake b/tests/cmake/startup_debug_launch_args.cmake new file mode 100644 index 0000000000..7484ae950e --- /dev/null +++ b/tests/cmake/startup_debug_launch_args.cmake @@ -0,0 +1,7 @@ +# tools/startup/debug_launch.py rejects malformed --timeout, --memory-gib and --continue-asserts +# values with an "expected ..." message and exit code 2 before it launches anything. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_debug_launch_args COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_debug_launch_args_check.py") + set_tests_properties(startup_debug_launch_args PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) +endif() diff --git a/tests/cmake/startup_gameinput_trace.cmake b/tests/cmake/startup_gameinput_trace.cmake new file mode 100644 index 0000000000..9b89f4e0f6 --- /dev/null +++ b/tests/cmake/startup_gameinput_trace.cmake @@ -0,0 +1,8 @@ +# X2W_INPUT_TRACE=1 logs the resolved gamepad state and the script's marks and waits. The test runs +# the same script with the switch on and off; the control must not produce an x2w-input-trace line. +add_executable(startup_gameinput_trace tests/startup_gameinput_trace.cpp) +target_include_directories(startup_gameinput_trace PRIVATE src) +target_compile_features(startup_gameinput_trace PRIVATE cxx_std_17) +add_dependencies(startup_gameinput_trace startup_stub_gameinput) +add_test(NAME startup_gameinput_trace COMMAND startup_gameinput_trace "$<TARGET_FILE:startup_stub_gameinput>") +set_tests_properties(startup_gameinput_trace PROPERTIES RUN_SERIAL TRUE TIMEOUT 60 SKIP_RETURN_CODE 77) diff --git a/tests/cmake/startup_gather_implicit_mip.cmake b/tests/cmake/startup_gather_implicit_mip.cmake new file mode 100644 index 0000000000..f57abdd5c8 --- /dev/null +++ b/tests/cmake/startup_gather_implicit_mip.cmake @@ -0,0 +1,8 @@ +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gather_implicit_mip_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gather_implicit_mip_check.py" "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_gather_implicit_mip_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx10_linear.cmake b/tests/cmake/startup_gfx10_linear.cmake new file mode 100644 index 0000000000..e3ead6af1d --- /dev/null +++ b/tests/cmake/startup_gfx10_linear.cmake @@ -0,0 +1,21 @@ +# The console linear mode (0x100) in src/startup_stubs/gfx10_layout.h. The mutated run expects the largest +# mip first and is a negative control; the addrlib run compares every element address of several linear +# textures with addrlib's SW_LINEAR (Mesa 25.1.0, src/amd/addrlib, MIT) and skips (77) without addrlib. +add_test(NAME startup_gfx10_layout_linear_order_control COMMAND startup_gfx10_layout_check --mutate linear-largest-first) +set_tests_properties(startup_gfx10_layout_linear_order_control PROPERTIES WILL_FAIL TRUE) +if(XBOX2WINDOWS_ADDRLIB_DIR) + target_link_libraries(startup_gfx10_layout_check PRIVATE xbw_addrlib) + target_compile_definitions(startup_gfx10_layout_check PRIVATE XBOX2WINDOWS_HAVE_ADDRLIB) +endif() +add_test(NAME startup_gfx10_layout_linear_addrlib COMMAND startup_gfx10_layout_check --addrlib) +set_tests_properties(startup_gfx10_layout_linear_addrlib PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) +# The negative control for the linear cases of startup_address_console: a 2D texture and a 1D chain written +# without the 256-byte padding must not draw exactly. +if(STARTUP_FXC AND EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_address_console_linear_unpadded_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" + "$<TARGET_FILE:startup_stream_consumer>" "${backend}" linear-unpadded) + set_tests_properties(startup_address_console_linear_unpadded_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx10_volume.cmake b/tests/cmake/startup_gfx10_volume.cmake new file mode 100644 index 0000000000..988e462925 --- /dev/null +++ b/tests/cmake/startup_gfx10_volume.cmake @@ -0,0 +1,26 @@ +# Volumes in the 4 KiB standard console layout (0x105, with or without a mip chain, uncompressed or +# block-compressed; +# src/startup_stubs/gfx10_layout.h) and the slot-70 descriptions and views that use them +# (src/startup_stubs/address_texture.h), without a device: address equations against addrlib's +# GFX10_SW_4K_S3 rows (Mesa 25.1.0, src/amd/addrlib, MIT), block order, the mip chain and its tail, +# block-compressed volumes against the volume of their blocks, distinct addresses, round trips and +# refusals. The thin run lays each volume out as a 2D array of its layers, the tail run puts every tail +# mip at the start of the tail block, and the bc run sizes a block-compressed volume by its texel sides; +# all three are negative controls. The addrlib run compares every element address with addrlib +# and skips (77) without it. +add_executable(startup_gfx10_volume_check tests/startup_gfx10_volume_check.cpp) +target_compile_features(startup_gfx10_volume_check PRIVATE cxx_std_17) +target_include_directories(startup_gfx10_volume_check PRIVATE src) +if(XBOX2WINDOWS_ADDRLIB_DIR) + target_link_libraries(startup_gfx10_volume_check PRIVATE xbw_addrlib) + target_compile_definitions(startup_gfx10_volume_check PRIVATE XBOX2WINDOWS_HAVE_ADDRLIB) +endif() +add_test(NAME startup_gfx10_volume COMMAND startup_gfx10_volume_check) +add_test(NAME startup_gfx10_volume_thin_control COMMAND startup_gfx10_volume_check --mutate thin) +set_tests_properties(startup_gfx10_volume_thin_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_gfx10_volume_tail_control COMMAND startup_gfx10_volume_check --mutate tail) +set_tests_properties(startup_gfx10_volume_tail_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_gfx10_volume_bc_control COMMAND startup_gfx10_volume_check --mutate bc) +set_tests_properties(startup_gfx10_volume_bc_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_gfx10_volume_addrlib COMMAND startup_gfx10_volume_check --addrlib) +set_tests_properties(startup_gfx10_volume_addrlib PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) diff --git a/tests/cmake/startup_gfx2hlsl_bvh.cmake b/tests/cmake/startup_gfx2hlsl_bvh.cmake new file mode 100644 index 0000000000..aaf68adc60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh.cmake @@ -0,0 +1,14 @@ +# gfx2hlsl image_bvh_intersect_ray FP32 box-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py" dispatch "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake b/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake new file mode 100644 index 0000000000..db06bf7e60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake @@ -0,0 +1,15 @@ +# gfx2hlsl image_bvh_intersect_ray triangle-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh_triangle COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_triangle_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_triangle_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_triangle_check.py" dispatch "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_triangle_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() + diff --git a/tests/cmake/startup_gfx2hlsl_cselect_descnum.cmake b/tests/cmake/startup_gfx2hlsl_cselect_descnum.cmake new file mode 100644 index 0000000000..f4a1648b2a --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_cselect_descnum.cmake @@ -0,0 +1,13 @@ +# gfx2hlsl compute s_cselect_b32 on descriptor-derived data (#2618, the C500 rows): the select keeps both arms as an +# opaque symbol, every later use that needs its value is refused by name, and three mutated translators must fail; +# then case A of the compute check with the dead select is dispatched and all 320 words compared. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_cselect_descnum_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cselect_descnum_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cselect_descnum_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cselect_descnum_check.py" dispatch "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_gfx2hlsl_cselect_descnum_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_ldexp.cmake b/tests/cmake/startup_gfx2hlsl_ldexp.cmake new file mode 100644 index 0000000000..4dc81de4af --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_ldexp.cmake @@ -0,0 +1,6 @@ +# gfx2hlsl v_ldexp_f32 lowering (Refs #2618): +# validates that v_ldexp_f32 lowers to ldexp32 and refuses invalid modifiers. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_ldexp_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ldexp_check.py") +endif() diff --git a/tests/cmake/startup_gfx2hlsl_lerp_u8.cmake b/tests/cmake/startup_gfx2hlsl_lerp_u8.cmake new file mode 100644 index 0000000000..6899cb8813 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_lerp_u8.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_lerp_u8_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_lerp_u8_check.py") + if(DXC_EXECUTABLE AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_lerp_u8_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_lerp_u8_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" "${adapter}" "${STARTUP_FXC}") + set_tests_properties(startup_gfx2hlsl_lerp_u8_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_load_desc.cmake b/tests/cmake/startup_gfx2hlsl_load_desc.cmake new file mode 100644 index 0000000000..de7f6226d5 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_load_desc.cmake @@ -0,0 +1,6 @@ +# gfx2hlsl compute buffer load through a modified descriptor (#2901): +# validates that compute buffer loads through a modified or overwritten descriptor word are refused. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_load_desc_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_load_desc_check.py") +endif() diff --git a/tests/cmake/startup_gfx2hlsl_perm_b32.cmake b/tests/cmake/startup_gfx2hlsl_perm_b32.cmake new file mode 100644 index 0000000000..d119fc0bb7 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_perm_b32.cmake @@ -0,0 +1,12 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_perm_b32_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_perm_b32_check.py") + if(DXC_EXECUTABLE AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_perm_b32_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_perm_b32_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" "${adapter}" "${STARTUP_FXC}") + set_tests_properties(startup_gfx2hlsl_perm_b32_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_pixel_first_lane.cmake b/tests/cmake/startup_gfx2hlsl_pixel_first_lane.cmake new file mode 100644 index 0000000000..982ab7e6b9 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_pixel_first_lane.cmake @@ -0,0 +1,13 @@ +# gfx2hlsl first active lane of a pixel stage (#2618, the F rows): a 32-lane model of s_ff1_i32_b32 sD, exec_lo with +# v_readlane_b32 sX, vY, sD, refusals by name, then a triangle with partly covered quads compared per desktop wave with +# the input of the wave's lowest covered lane. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_pixel_first_lane_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pixel_first_lane_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pixel_first_lane_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pixel_first_lane_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_pixel_first_lane_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_pk_minmax.cmake b/tests/cmake/startup_gfx2hlsl_pk_minmax.cmake new file mode 100644 index 0000000000..d6b02452b7 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_pk_minmax.cmake @@ -0,0 +1,13 @@ +# Packed binary16 min/max translation controls and D3D12 readback (#2022). +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_pk_minmax_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pk_minmax_check.py") + if(TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pk_minmax_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pk_minmax_check.py" draw + "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_gfx2hlsl_pk_minmax_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_bitcmp64.cmake b/tests/cmake/startup_gfx2hlsl_s_bitcmp64.cmake new file mode 100644 index 0000000000..f61a24c82e --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_bitcmp64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar bit-compare (s_bitcmp0_b64, s_bitcmp1_b64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_bitcmp64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bitcmp64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp64_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bitcmp64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_bitreplicate.cmake b/tests/cmake/startup_gfx2hlsl_s_bitreplicate.cmake new file mode 100644 index 0000000000..fe97d9c367 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_bitreplicate.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar bit-replicate (s_bitreplicate_b64_b32) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_bitreplicate_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitreplicate_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bitreplicate_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitreplicate_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bitreplicate_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_bitset64.cmake b/tests/cmake/startup_gfx2hlsl_s_bitset64.cmake new file mode 100644 index 0000000000..f08344d82a --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_bitset64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar bit set/clear (s_bitset0_b64, s_bitset1_b64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_bitset64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_bitset64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitset64_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_bitset64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_brev64.cmake b/tests/cmake/startup_gfx2hlsl_s_brev64.cmake new file mode 100644 index 0000000000..29c279adcf --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_brev64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar bit-reverse (s_brev_b64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_brev64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_brev64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_brev64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_brev64_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_brev64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_s_cmp64.cmake b/tests/cmake/startup_gfx2hlsl_s_cmp64.cmake new file mode 100644 index 0000000000..8f24093378 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_s_cmp64.cmake @@ -0,0 +1,11 @@ +# 64-bit scalar equality comparisons (s_cmp_eq_u64, s_cmp_lg_u64) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_s_cmp64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_cmp64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_s_cmp64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_cmp64_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_s_cmp64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_add_sub_nc_i32.cmake b/tests/cmake/startup_gfx2hlsl_v_add_sub_nc_i32.cmake new file mode 100644 index 0000000000..badf54cdbe --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_add_sub_nc_i32.cmake @@ -0,0 +1,25 @@ +# Signed 32-bit add/sub (v_add_nc_i32, v_sub_nc_i32) lowering in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test( + NAME startup_gfx2hlsl_v_add_sub_nc_i32_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py" + ) + if(WIN32 AND DXC_EXECUTABLE AND TARGET offscreen_check) + set(_x2w_v_add_sub_nc_i32_fxc "") + if(FXC_EXECUTABLE) + set(_x2w_v_add_sub_nc_i32_fxc "${FXC_EXECUTABLE}") + endif() + add_test( + NAME startup_gfx2hlsl_v_add_sub_nc_i32_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" warp ${_x2w_v_add_sub_nc_i32_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_add_sub_nc_i32_warp PROPERTIES TIMEOUT 120) + add_test( + NAME startup_gfx2hlsl_v_add_sub_nc_i32_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" hardware ${_x2w_v_add_sub_nc_i32_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_add_sub_nc_i32_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_dot2.cmake b/tests/cmake/startup_gfx2hlsl_v_dot2.cmake new file mode 100644 index 0000000000..a7a152f797 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_dot2.cmake @@ -0,0 +1,11 @@ +# VOP3P 2-halfword integer dot products (v_dot2_i32_i16, v_dot2_u32_u16) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_v_dot2_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot2_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_v_dot2_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot2_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_v_dot2_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_dot4.cmake b/tests/cmake/startup_gfx2hlsl_v_dot4.cmake new file mode 100644 index 0000000000..0a15bcdd16 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_dot4.cmake @@ -0,0 +1,11 @@ +# VOP3P 4-byte integer dot products (v_dot4_i32_i8, v_dot4_u32_u8) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_v_dot4_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot4_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_v_dot4_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot4_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_v_dot4_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_dot8.cmake b/tests/cmake/startup_gfx2hlsl_v_dot8.cmake new file mode 100644 index 0000000000..b0c595f628 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_dot8.cmake @@ -0,0 +1,11 @@ +# VOP3P 8-nibble integer dot products (v_dot8_i32_i4, v_dot8_u32_u4) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_v_dot8_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot8_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_v_dot8_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_dot8_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_v_dot8_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_mad_i32_i16.cmake b/tests/cmake/startup_gfx2hlsl_v_mad_i32_i16.cmake new file mode 100644 index 0000000000..413d91547e --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_mad_i32_i16.cmake @@ -0,0 +1,11 @@ +# Signed 16x16+32 multiply-add (v_mad_i32_i16) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_v_mad_i32_i16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_mad_i32_i16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_v_mad_i32_i16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_mad_i32_i16_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_v_mad_i32_i16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_pk_add_sub_16.cmake b/tests/cmake/startup_gfx2hlsl_v_pk_add_sub_16.cmake new file mode 100644 index 0000000000..e6c99aa47e --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_pk_add_sub_16.cmake @@ -0,0 +1,25 @@ +# Packed 16-bit integer add/sub (v_pk_add/sub_i16, v_pk_add/sub_u16) lowering in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test( + NAME startup_gfx2hlsl_v_pk_add_sub_16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py" + ) + if(WIN32 AND DXC_EXECUTABLE AND TARGET offscreen_check) + set(_x2w_v_pk_add_sub_16_fxc "") + if(FXC_EXECUTABLE) + set(_x2w_v_pk_add_sub_16_fxc "${FXC_EXECUTABLE}") + endif() + add_test( + NAME startup_gfx2hlsl_v_pk_add_sub_16_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" warp ${_x2w_v_pk_add_sub_16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_add_sub_16_warp PROPERTIES TIMEOUT 120) + add_test( + NAME startup_gfx2hlsl_v_pk_add_sub_16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" hardware ${_x2w_v_pk_add_sub_16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_add_sub_16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_pk_minmax_i16_u16.cmake b/tests/cmake/startup_gfx2hlsl_v_pk_minmax_i16_u16.cmake new file mode 100644 index 0000000000..41981d1996 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_pk_minmax_i16_u16.cmake @@ -0,0 +1,25 @@ +# Packed 16-bit integer min/max (v_pk_min/max_i16, v_pk_min/max_u16) lowering in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test( + NAME startup_gfx2hlsl_v_pk_minmax_i16_u16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py" + ) + if(WIN32 AND DXC_EXECUTABLE AND TARGET offscreen_check) + set(_x2w_v_pk_minmax_i16_u16_fxc "") + if(FXC_EXECUTABLE) + set(_x2w_v_pk_minmax_i16_u16_fxc "${FXC_EXECUTABLE}") + endif() + add_test( + NAME startup_gfx2hlsl_v_pk_minmax_i16_u16_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" warp ${_x2w_v_pk_minmax_i16_u16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_minmax_i16_u16_warp PROPERTIES TIMEOUT 120) + add_test( + NAME startup_gfx2hlsl_v_pk_minmax_i16_u16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" hardware ${_x2w_v_pk_minmax_i16_u16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_minmax_i16_u16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_pk_mul_mad_16.cmake b/tests/cmake/startup_gfx2hlsl_v_pk_mul_mad_16.cmake new file mode 100644 index 0000000000..533f67c8dd --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_pk_mul_mad_16.cmake @@ -0,0 +1,25 @@ +# Packed 16-bit integer multiply/mad (v_pk_mul_lo_u16, v_pk_mad_u16, v_pk_mad_i16) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test( + NAME startup_gfx2hlsl_v_pk_mul_mad_16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py" + ) + if(WIN32 AND DXC_EXECUTABLE AND TARGET offscreen_check) + set(_x2w_v_pk_mul_mad_16_fxc "") + if(FXC_EXECUTABLE) + set(_x2w_v_pk_mul_mad_16_fxc "${FXC_EXECUTABLE}") + endif() + add_test( + NAME startup_gfx2hlsl_v_pk_mul_mad_16_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" warp ${_x2w_v_pk_mul_mad_16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_mul_mad_16_warp PROPERTIES TIMEOUT 120) + add_test( + NAME startup_gfx2hlsl_v_pk_mul_mad_16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" hardware ${_x2w_v_pk_mul_mad_16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_mul_mad_16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_pk_shift16.cmake b/tests/cmake/startup_gfx2hlsl_v_pk_shift16.cmake new file mode 100644 index 0000000000..cdb8d0455f --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_pk_shift16.cmake @@ -0,0 +1,25 @@ +# Packed 16-bit integer shifts (v_pk_lshlrev_b16, v_pk_lshrrev_b16, v_pk_ashrrev_i16) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}") + add_test( + NAME startup_gfx2hlsl_v_pk_shift16_controls + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_shift16_check.py" + ) + if(WIN32 AND DXC_EXECUTABLE AND TARGET offscreen_check) + set(_x2w_v_pk_shift16_fxc "") + if(FXC_EXECUTABLE) + set(_x2w_v_pk_shift16_fxc "${FXC_EXECUTABLE}") + endif() + add_test( + NAME startup_gfx2hlsl_v_pk_shift16_warp + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_shift16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" warp ${_x2w_v_pk_shift16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_shift16_warp PROPERTIES TIMEOUT 120) + add_test( + NAME startup_gfx2hlsl_v_pk_shift16_hardware + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_v_pk_shift16_check.py" + draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" hardware ${_x2w_v_pk_shift16_fxc} + ) + set_tests_properties(startup_gfx2hlsl_v_pk_shift16_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + endif() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_v_sat_pk_u8_i16.cmake b/tests/cmake/startup_gfx2hlsl_v_sat_pk_u8_i16.cmake new file mode 100644 index 0000000000..55b08e842e --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_v_sat_pk_u8_i16.cmake @@ -0,0 +1,11 @@ +# Saturating int16x2-to-uint8x2 pack (v_sat_pk_u8_i16) in tools/startup/gfx2hlsl.py. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_v_sat_pk_u8_i16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_sat_pk_u8_i16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_v_sat_pk_u8_i16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_v_sat_pk_u8_i16_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_v_sat_pk_u8_i16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_gfx2hlsl_wave_reduce.cmake b/tests/cmake/startup_gfx2hlsl_wave_reduce.cmake new file mode 100644 index 0000000000..376fba248a --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_wave_reduce.cmake @@ -0,0 +1,12 @@ +# gfx2hlsl whole-wave reductions (#2125 item D): a 32-lane model of the source chains, refusals by name, then a +# triangle with partly covered quads drawn per operation and compared with a CPU reference per desktop wave. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_gfx2hlsl_wave_reduce_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_wave_reduce_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_wave_reduce_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_wave_reduce_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_wave_reduce_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_image_cube.cmake b/tests/cmake/startup_image_cube.cmake new file mode 100644 index 0000000000..1c46cfb54d --- /dev/null +++ b/tests/cmake/startup_image_cube.cmake @@ -0,0 +1,12 @@ +# gfx2hlsl cube image sampling (#2943): translation controls, then a six-face TextureCube drawn from literal face +# addresses, translator mutants and the v_cube chain, compared with the address meaning and a desktop TextureCube draw. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_image_cube_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_cube_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_cube_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_cube_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_image_cube_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_image_sample_l_join.cmake b/tests/cmake/startup_image_sample_l_join.cmake new file mode 100644 index 0000000000..5cf16c9087 --- /dev/null +++ b/tests/cmake/startup_image_sample_l_join.cmake @@ -0,0 +1,10 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_image_sample_l_join_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_l_join_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_l_join_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_l_join_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_image_sample_l_join_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_manifest_retry.cmake b/tests/cmake/startup_manifest_retry.cmake new file mode 100644 index 0000000000..dfb9e53e57 --- /dev/null +++ b/tests/cmake/startup_manifest_retry.cmake @@ -0,0 +1,5 @@ +# The retry schedule for an absent shader cache manifest (startup_stubs/manifest_retry.h). +add_executable(startup_manifest_retry_check tests/startup_manifest_retry_check.cpp) +target_include_directories(startup_manifest_retry_check PRIVATE src) +target_compile_features(startup_manifest_retry_check PRIVATE cxx_std_17) +add_test(NAME startup_manifest_retry COMMAND startup_manifest_retry_check) diff --git a/tests/cmake/startup_pixel_history_draw.cmake b/tests/cmake/startup_pixel_history_draw.cmake new file mode 100644 index 0000000000..7f7de17426 --- /dev/null +++ b/tests/cmake/startup_pixel_history_draw.cmake @@ -0,0 +1,8 @@ +if(STARTUP_FXC AND EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_pixel_history_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_pixel_history_draw_check.py" + "$<TARGET_FILE:startup_stream_consumer>" "${backend}") + set_tests_properties(startup_pixel_history_draw_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_present_readback.cmake b/tests/cmake/startup_present_readback.cmake new file mode 100644 index 0000000000..86f59c6992 --- /dev/null +++ b/tests/cmake/startup_present_readback.cmake @@ -0,0 +1,4 @@ +add_executable(startup_present_readback_check tests/startup_present_readback_check.cpp) +target_compile_features(startup_present_readback_check PRIVATE cxx_std_17) +target_include_directories(startup_present_readback_check PRIVATE src) +add_test(NAME startup_present_readback COMMAND startup_present_readback_check) diff --git a/tests/cmake/startup_pso_recipe.cmake b/tests/cmake/startup_pso_recipe.cmake new file mode 100644 index 0000000000..67ebb03ff5 --- /dev/null +++ b/tests/cmake/startup_pso_recipe.cmake @@ -0,0 +1,6 @@ +# Device-free checks for the opt-in translated-PSO recipe format +# (src/startup_stubs/pso_recipe.h). +add_executable(startup_pso_recipe_check tests/startup_pso_recipe_check.cpp) +target_include_directories(startup_pso_recipe_check PRIVATE src) +target_compile_features(startup_pso_recipe_check PRIVATE cxx_std_17) +add_test(NAME startup_pso_recipe COMMAND startup_pso_recipe_check) diff --git a/tests/cmake/startup_rect_gap.cmake b/tests/cmake/startup_rect_gap.cmake new file mode 100644 index 0000000000..08a094566e --- /dev/null +++ b/tests/cmake/startup_rect_gap.cmake @@ -0,0 +1,12 @@ +# The eight-vertex quad-and-edge-ring draw with 12-byte vertex records (#3131): the shared indexed rectangle +# expansion with back-face culling on, and the same draw through the startup runtime entry. +add_test(NAME startup_rect_geometry_warp COMMAND startup_rect_geometry) +add_test(NAME startup_rect_geometry_hardware COMMAND startup_rect_geometry hardware) +set_tests_properties(startup_rect_geometry_hardware PROPERTIES SKIP_RETURN_CODE 77) + +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_rect_gap_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_rect_gap_check.py" + "$<TARGET_FILE:startup_stream_consumer>" "${backend}") + set_tests_properties(startup_rect_gap_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) +endforeach() diff --git a/tests/cmake/startup_root_srv_at_draw.cmake b/tests/cmake/startup_root_srv_at_draw.cmake new file mode 100644 index 0000000000..9bf9d83f15 --- /dev/null +++ b/tests/cmake/startup_root_srv_at_draw.cmake @@ -0,0 +1,12 @@ +# Graphics root SRV: no desktop copy that no draw reads (opt-in X2W_D3D12_ROOT_SRV_AT_DRAW=1). +# A translated draw reads a slot 44 root SRV whose title bytes change before the draw; it runs with the switch unset +# (slot 44 copies) and set (no copy). +target_sources(startup_stream_consumer PRIVATE tests/startup_root_srv_draw.cpp) +if(EXISTS "${INTAKE_PYTHON}") + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_root_srv_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_root_srv_draw_check.py" + "$<TARGET_FILE:startup_stream_consumer>" ${backend}) + set_tests_properties(startup_root_srv_draw_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_slot133_heap_cap.cmake b/tests/cmake/startup_slot133_heap_cap.cmake new file mode 100644 index 0000000000..c47f3f01b9 --- /dev/null +++ b/tests/cmake/startup_slot133_heap_cap.cmake @@ -0,0 +1,26 @@ +# Slot 133 existing-heap cap (opt-in X2W_D3D12_CAP_EXISTING_HEAP=1, <= 256 MiB), deferred +# commit_lazy_block, and incremental reserve_upload_ring growth (Refs #1199, Fixes #2765). +# The default cases exercise the aliased >256 MiB placement and its late-write fenced readback; +# the capped cases exercise the opt-in cap's copied fallback, the <= 256 MiB alias cases and the +# upload-ring growth. +add_executable(startup_slot133_heap_cap_check tests/startup_slot133_heap_cap_check.cpp) +target_include_directories(startup_slot133_heap_cap_check PRIVATE src) +target_compile_features(startup_slot133_heap_cap_check PRIVATE cxx_std_17) +target_link_libraries(startup_slot133_heap_cap_check PRIVATE d3d12 dxgi) +add_dependencies(startup_slot133_heap_cap_check xmem_shim d3d12_xs_shim) + +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(case startup_slot133_heap_cap_${backend}_debug${debug}) + add_test(NAME ${case} COMMAND startup_slot133_heap_cap_check ${backend}) + set_tests_properties(${case} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_DEBUG=${debug}") + endforeach() +endforeach() + +foreach(backend IN ITEMS warp hardware) + set(case startup_slot133_heap_cap_capped_${backend}) + add_test(NAME ${case} COMMAND startup_slot133_heap_cap_check ${backend} cap) + set_tests_properties(${case} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_DEBUG=0") +endforeach() diff --git a/tests/cmake/startup_slot70_cube.cmake b/tests/cmake/startup_slot70_cube.cmake new file mode 100644 index 0000000000..a08996ad58 --- /dev/null +++ b/tests/cmake/startup_slot70_cube.cmake @@ -0,0 +1,11 @@ +# Cube views of console-layout textures published by address (device slot 70). The cube draws run inside +# startup_address_console_{warp,hardware}; this is their negative control: the faces written in reverse slice +# order must not draw exactly. +if(STARTUP_FXC AND EXISTS "${INTAKE_PYTHON}" AND TARGET startup_stream_consumer) + foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_address_console_cube_order_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py" + "$<TARGET_FILE:startup_stream_consumer>" "${backend}" cube-order) + set_tests_properties(startup_address_console_cube_order_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/cmake/startup_view_alloc.cmake b/tests/cmake/startup_view_alloc.cmake new file mode 100644 index 0000000000..46e6da25b2 --- /dev/null +++ b/tests/cmake/startup_view_alloc.cmake @@ -0,0 +1,25 @@ +# #1199: when a view container cannot allocate, nothing is recorded, the destination slot is untracked and the process +# keeps running. One test per allocation site. `control` never arms the failure, so the fixture must print FAIL. +add_executable(startup_view_alloc tests/startup_view_alloc.cpp) +target_compile_features(startup_view_alloc PRIVATE cxx_std_17) +target_link_libraries(startup_view_alloc PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(site IN ITEMS records materialized ids) + foreach(mode IN ITEMS on control) + if(mode STREQUAL "on") + set(alloc_test startup_view_alloc_${site}_${backend}) + add_test(NAME ${alloc_test} COMMAND startup_view_alloc ${backend} ${site}) + else() + set(alloc_test startup_view_alloc_${site}_control_${backend}) + add_test(NAME ${alloc_test} COMMAND startup_view_alloc ${backend} ${site} control) + endif() + set(alloc_env "X2W_D3D12_BUDGET=1;X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_RENDER=1") + list(APPEND alloc_env "X2W_D3D12_DEBUG=0" "X2W_TRAP_LOG=${CMAKE_CURRENT_BINARY_DIR}/${alloc_test}.log") + set_tests_properties(${alloc_test} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "${alloc_env}") + if(mode STREQUAL "control") + set_tests_properties(${alloc_test} PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: a failed publication changed a view container") + endif() + endforeach() + endforeach() +endforeach() diff --git a/tests/cmake/textures_texture_blocks.cmake b/tests/cmake/textures_texture_blocks.cmake new file mode 100644 index 0000000000..5d34079431 --- /dev/null +++ b/tests/cmake/textures_texture_blocks.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME textures_texture_blocks_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/texture_blocks_check.py") + set_tests_properties(textures_texture_blocks_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/tooling_cpu_leaf_aot_cli.cmake b/tests/cmake/tooling_cpu_leaf_aot_cli.cmake new file mode 100644 index 0000000000..0f31950f4e --- /dev/null +++ b/tests/cmake/tooling_cpu_leaf_aot_cli.cmake @@ -0,0 +1,5 @@ +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME tooling_cpu_leaf_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu_leaf_aot_cli_check.py") + set_tests_properties(tooling_cpu_leaf_aot_cli_check PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake new file mode 100644 index 0000000000..fe8e94aa56 --- /dev/null +++ b/tests/cmake/xmem_page_runs.cmake @@ -0,0 +1,166 @@ +# XMem page-run fixtures (#2911): readers inside a run break, the cross-call merge of shared views, the slot 31 +# placeholder split, split-before-map inside a placeholder, and a DirectStorage destination inside a run break. +# Readers that do not fault, inside a run break held open by the test-controls build: x2w_xmem_stable_call, +# XMemVirtualQuery, the VirtualQueryEx import wrapper and the stand-in readers that go through +# x2w_local::outside_run_breaks must answer after the break. Control: a copy of local_log.h that asks xmem.dll for +# a missing export, so the stand-in readers run directly and answer inside the window. +foreach(variant check control) + add_executable(xmem_run_break_readers_${variant} tests/xmem_run_break_readers_check.cpp) + target_compile_features(xmem_run_break_readers_${variant} PRIVATE cxx_std_17) + add_dependencies(xmem_run_break_readers_${variant} xmem_shim_test_controls) +endforeach() +target_include_directories(xmem_run_break_readers_check PRIVATE src) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/local_log.h" local_log_text) +string(REPLACE "\"x2w_xmem_stable_call\"" "\"x2w_xmem_stable_call_control\"" local_log_control_text "${local_log_text}") +if(local_log_control_text STREQUAL local_log_text) + message(FATAL_ERROR "local_log.h lost the anchor used by xmem_run_break_readers_control") +endif() +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control/startup_stubs/local_log.h" "${local_log_control_text}") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/local_log.h) +target_include_directories(xmem_run_break_readers_control BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control") +target_include_directories(xmem_run_break_readers_control PRIVATE src) +add_test(NAME xmem_run_break_readers COMMAND xmem_run_break_readers_check "$<TARGET_FILE:xmem_shim_test_controls>") +add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_control + "$<TARGET_FILE:xmem_shim_test_controls>" control) +add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_readers_check + "$<TARGET_FILE:xmem_shim_test_controls>" next-break-control) +# Default mode (no X2W_XMEM_SHARED_VIEWS): readers that overlap an unmap answer inside it, as before. Lazy commit: +# the readers' output buffer in a mapped slot not yet committed. +add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$<TARGET_FILE:xmem_shim_test_controls>" default) +add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$<TARGET_FILE:xmem_shim_test_controls>" lazy) +# A fault handler that looks the page up after a later break on another run has begun: a second unmap on a disjoint +# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR; the program +# sets X2W_XMEM_JOIN_CALLS=1 for `mirror` only). +# stamps: a held fault whose break is followed by 63, 64 or 200 later breaks on another page is retried each time +# (the run keeps the stamp of the break that mapped it again); a fault that stays is passed on at once on a run no +# break mapped, and after one retry on a run a break mapped. +add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$<TARGET_FILE:xmem_shim_test_controls>" two-runs) +add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$<TARGET_FILE:xmem_shim_test_controls>" mirror) +add_test(NAME xmem_run_break_readers_stamps COMMAND xmem_run_break_readers_check "$<TARGET_FILE:xmem_shim_test_controls>" stamps) +set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control + xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs + xmem_run_break_readers_mirror xmem_run_break_readers_stamps PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_run_break_readers_default PROPERTIES + PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") +# Cross-call merge of shared views (merge_with_previous, X2W_XMEM_JOIN_CALLS=1 set by the program): single-page calls +# on consecutive slots join one view, and the steps around it (an unmap inside, slots out of order, a reader inside the +# held window, refused steps, two reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test +# build only); the deployed shim ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its +# own. no_join: the deployed shim with shared views and without X2W_XMEM_JOIN_CALLS keeps a view per call. +add_executable(xmem_cross_call_merge_check tests/xmem_cross_call_merge_check.cpp) +target_compile_features(xmem_cross_call_merge_check PRIVATE cxx_std_17) +add_dependencies(xmem_cross_call_merge_check xmem_shim xmem_shim_test_controls) +add_test(NAME xmem_cross_call_merge COMMAND xmem_cross_call_merge_check "$<TARGET_FILE:xmem_shim_test_controls>" check) +add_test(NAME xmem_cross_call_merge_control COMMAND xmem_cross_call_merge_check "$<TARGET_FILE:xmem_shim_test_controls>" control) +add_test(NAME xmem_cross_call_merge_deployed COMMAND xmem_cross_call_merge_check "$<TARGET_FILE:xmem_shim>" deployed) +add_test(NAME xmem_cross_call_merge_default COMMAND xmem_cross_call_merge_check "$<TARGET_FILE:xmem_shim>" default) +add_test(NAME xmem_cross_call_merge_no_join COMMAND xmem_cross_call_merge_check "$<TARGET_FILE:xmem_shim>" no-join) +set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed + xmem_cross_call_merge_default xmem_cross_call_merge_no_join PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_cross_call_merge_control PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_deployed PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "merge: 1 view of 32 pages" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_default PROPERTIES + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_no_join PROPERTIES + PASS_REGULAR_EXPRESSION "no-join: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +# Placed buffers at view boundaries (tests/xmem_page_runs_device_check.cpp, registered in CMakeLists.txt) with joins +# across mapping calls on: the order of the mapping calls keeps every boundary. +add_test(NAME xmem_page_runs_device_join_warp COMMAND xmem_page_runs_device_check warp join) +set_tests_properties(xmem_page_runs_device_join_warp PROPERTIES TIMEOUT 120) +# tests/xmem_page_runs_check.py expects one view per mapping call: an X2W_XMEM_JOIN_CALLS=1 inherited from the +# caller's environment must not reach it. +if(TEST xmem_shim_page_runs) + set_property(TEST xmem_shim_page_runs APPEND PROPERTY ENVIRONMENT "X2W_XMEM_JOIN_CALLS=") +endif() + +# Slot 31 placeholder split inside an XMem reservation. The control (test-controls build) disables the fallback used +# where the OS does not report placeholders (Wine), so the split fails there; where the OS reports them, the control +# skips (77). The check program sets each mode's test switch itself. +add_executable(xmem_placeholder_split_check tests/xmem_placeholder_split_check.cpp) +target_include_directories(xmem_placeholder_split_check PRIVATE src) +target_compile_features(xmem_placeholder_split_check PRIVATE cxx_std_17) +target_link_libraries(xmem_placeholder_split_check PRIVATE OneCore) +add_dependencies(xmem_placeholder_split_check xmem_shim xmem_shim_test_controls) +set(xmem_placeholder_env "X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") +add_test(NAME xmem_placeholder_split COMMAND xmem_placeholder_split_check "$<TARGET_FILE:xmem_shim>") +set_tests_properties(xmem_placeholder_split PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the split itself fails, not on an earlier setup failure. +add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check + "$<TARGET_FILE:xmem_shim_test_controls>" control) +set_tests_properties(xmem_placeholder_split_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" + PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) +# The deployed shim with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1: the switch is ignored and the split succeeds. +add_test(NAME xmem_placeholder_split_deployed COMMAND xmem_placeholder_split_check "$<TARGET_FILE:xmem_shim>" deployed) +set_tests_properties(xmem_placeholder_split_deployed PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" SKIP_RETURN_CODE 77 TIMEOUT 60) +# A two-page view over a reserved page and a committed page of one private allocation: the fallback checks every +# region of the view and refuses it (test-controls build: x2w_xmem_alias_counts), and the committed page keeps its +# bytes. The program turns shared views on for this mode. +add_test(NAME xmem_placeholder_split_partial COMMAND xmem_placeholder_split_check + "$<TARGET_FILE:xmem_shim_test_controls>" partial) +set_tests_properties(xmem_placeholder_split_partial PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" SKIP_RETURN_CODE 77 TIMEOUT 60) +add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) +target_include_directories(xmem_map_split_first_check PRIVATE src) +target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) +add_dependencies(xmem_map_split_first_check xmem_shim xmem_shim_test_controls) +add_test(NAME xmem_map_split_first COMMAND xmem_map_split_first_check "$<TARGET_FILE:xmem_shim>") +add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check + "$<TARGET_FILE:xmem_shim_test_controls>" control) +set_tests_properties(xmem_map_split_first PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control (test-controls build, X2W_XMEM_TEST_MAP_FIRST=1) passes only when the map-first order is measured +# (2 maps per page), not on a setup failure. +set_tests_properties(xmem_map_split_first_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" + PASS_REGULAR_EXPRESSION "map-first control: maps=2N" TIMEOUT 60) +# The deployed shim with X2W_XMEM_TEST_MAP_FIRST=1: the switch is ignored, so the split-first counts hold. +add_test(NAME xmem_map_split_first_deployed COMMAND xmem_map_split_first_check "$<TARGET_FILE:xmem_shim>" deployed) +set_tests_properties(xmem_map_split_first_deployed PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") + +# A request whose destination page an XMem run break holds unmapped (the xmem test-controls build's +# X2W_XMEM_TEST_HOLD_WINDOW) must not complete within the 1000 ms hold, then land after the release. +# Control: XCRDAPI without the x2w_xmem_copy_to_destination lookup judges the destination with its own VirtualQuery +# inside the window and refuses it. +add_executable(startup_dstorage_break_window_check tests/startup_dstorage_break_window_check.cpp) +target_compile_features(startup_dstorage_break_window_check PRIVATE cxx_std_17) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi xmem_shim_test_controls) +add_test(NAME startup_dstorage_break_window COMMAND startup_dstorage_break_window_check + "$<TARGET_FILE:xmem_shim_test_controls>" "$<TARGET_FILE:startup_stub_xcrdapi>") +set_tests_properties(startup_dstorage_break_window PROPERTIES TIMEOUT 60) +# Which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared views, a VirtualAlloc destination copies +# without it and one in a run with it (plain); with shared views off, an XMem page destination copies without it. +add_test(NAME startup_dstorage_break_window_plain COMMAND startup_dstorage_break_window_check + "$<TARGET_FILE:xmem_shim_test_controls>" "$<TARGET_FILE:startup_stub_xcrdapi>" plain) +add_test(NAME startup_dstorage_break_window_views_off COMMAND startup_dstorage_break_window_check + "$<TARGET_FILE:xmem_shim_test_controls>" "$<TARGET_FILE:startup_stub_xcrdapi>" views-off) +# XCRDAPI's logged outcome for each copy error, forced by the test-controls build (X2W_XMEM_TEST_COPY_ERROR). +add_test(NAME startup_dstorage_break_window_outcomes COMMAND startup_dstorage_break_window_check + "$<TARGET_FILE:xmem_shim_test_controls>" "$<TARGET_FILE:startup_stub_xcrdapi>" outcomes) +set_tests_properties(startup_dstorage_break_window_plain startup_dstorage_break_window_views_off + startup_dstorage_break_window_outcomes PROPERTIES TIMEOUT 60) +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) +string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text + "${xcrdapi_text}") +if(xcrdapi_control_text STREQUAL xcrdapi_text) + message(FATAL_ERROR "xcrdapi.cpp lost the anchor used by startup_dstorage_break_window_control") +endif() +set(xcrdapi_control "${CMAKE_CURRENT_BINARY_DIR}/xcrdapi_break_window_control/xcrdapi.cpp") +file(WRITE "${xcrdapi_control}" "${xcrdapi_control_text}") +add_library(startup_stub_xcrdapi_break_window_control SHARED "${xcrdapi_control}" src/startup_stubs/xcrdapi.def) +set_target_properties(startup_stub_xcrdapi_break_window_control PROPERTIES OUTPUT_NAME XCRDAPI + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") +target_include_directories(startup_stub_xcrdapi_break_window_control PRIVATE src) +target_compile_features(startup_stub_xcrdapi_break_window_control PRIVATE cxx_std_17) +target_link_libraries(startup_stub_xcrdapi_break_window_control PRIVATE psapi) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi_break_window_control) +add_test(NAME startup_dstorage_break_window_control COMMAND startup_dstorage_break_window_check + "$<TARGET_FILE:xmem_shim_test_controls>" "$<TARGET_FILE:startup_stub_xcrdapi_break_window_control>") +set_tests_properties(startup_dstorage_break_window_control PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "FAIL break window: refused while the run was broken") diff --git a/tests/compute_alu_bfm_check.py b/tests/compute_alu_bfm_check.py new file mode 100644 index 0000000000..5745b2f5fa --- /dev/null +++ b/tests/compute_alu_bfm_check.py @@ -0,0 +1,206 @@ +"""Check the compute lowering of v_bfm_b32 between a guarded read and its store (#1546). + +Modes: + controls translator output and rejections only + draw <dxc> <renderer> <adapter> also dispatch the fixture and compare the UAV with an independent reference +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import compute_store_check as base + +# v_bfm_b32 is VOP3 only on gfx10: D = ((1 << S0[4:0]) - 1) << S1[4:0], modulo 2^32. src0 is the width and +# src1 the offset. A width field of 0 gives an empty mask; a width of 32 cannot be encoded, so the widest mask is +# 0x7fffffff. Mask bits shifted past bit 31 are dropped, not rotated. +# +# The read-compute-write fixture of compute_store_check.py with its ALU lines replaced, by hand, in LLVM 15 gfx1013 +# spelling. With w = source word gid (byte offset gid * 4) and cap = params[0].y: +# a = bfm(w, w >> 5) VGPR sources; both fields come from words with higher bits set +# b = bfm(cap, 0x7b) SGPR width, literal offset 0x7b & 31 = 27 +# c = bfm(44, gid) inline width 44 & 31 = 12, offset from the dispatch index +# store a ^ b ^ c at element gid +# The low five bits of source_word(gid) are 17 * (gid + 1) mod 32, so lanes 0..31 see every width, 0 included. +READ_BFM = base.variant( + base.READ_COMPUTE, + ("v_and_b32_e32 v2, 0xffff, v1", ""), + ("v_lshrrev_b32_e32 v1, 16, v1", "v_lshrrev_b32_e32 v2, 5, v1"), + ("v_mad_u32_u24 v1, v2, v1, v0", "v_bfm_b32 v2, v1, v2\nv_bfm_b32 v3, s0, 0x7b\nv_bfm_b32 v4, 44, v0"), + ("v_min_u32_e32 v1, s0, v1", "v_xor_b32_e32 v2, v3, v2\nv_xor_b32_e32 v1, v4, v2"), +) +BFM_CASE = ("read_bfm", READ_BFM, 32, base.READ_BINDING) +# Width field 0x29 & 31 = 9 at offset 27: only bits 27..31 survive, b = 0xf8000000. +BFM_CAP = 0xc0de0029 +LOAD = base.READ_LOADS["read_copy"] +BFM_STORE = (" outputData.Store(tid.x * 4u + 0u, ((((1u << (0x0000002cu & 31u)) - 1u) << (tid.x & 31u)) ^ " + "((((1u << (params[0].y & 31u)) - 1u) << (0x0000007bu & 31u)) ^ (((1u << ({0} & 31u)) - 1u) << " + "(({0} >> (0x00000005u & 31u)) & 31u)))));").format(LOAD) +# Lanes worked out by hand from source_word(gid) = 0x8b02a7f1 + gid * 0x413b1 (gid: width, offset of a): +# 0: 17, 31 a = 0x80000000 c = 0x00000fff -> 0x78000fff +# 14: 31, 28 a = 0xf0000000 (widest field) c = 0x03ffc000 -> 0x0bffc000 +# 31: 0, 19 a = 0 (empty mask) c = 0x80000000 -> 0x78000000 +# 32: 17, 16 a = 0xffff0000 c = 0x00000fff -> 0x07ff0fff (c offset 32 & 31 = 0) +# 149: 22, 15 a = 0xffff8000 c = 0xffe00000 -> 0xf81f8000 +HAND_WORDS = {0: 0x78000fff, 14: 0x0bffc000, 31: 0x78000000, 32: 0x07ff0fff, 149: 0xf81f8000} + + +def bit_mask(width, offset, *, rotate=False): + """A mask built bit by bit: bits offset .. offset + width - 1, dropping (or, if rotate, wrapping) bits past 31.""" + bits = range(offset, offset + min(width, 32)) + return sum(1 << (bit % 32) for bit in bits) if rotate else sum(1 << bit for bit in bits if bit < 32) + + +def bfm_word(gid, *, swap=False, width_field=31, offset_field=31, zero_full=False, rotate=False): + """Independent CPU reference of read_bfm for one lane. The keywords select a wrong model of the instruction.""" + word = base.source_word(gid) + + def bfm(src0, src1): + width, offset = (src1, src0) if swap else (src0, src1) + width, offset = width & width_field, offset & offset_field + return bit_mask(32 if zero_full and width == 0 else width, offset, rotate=rotate) + + return bfm(word, word >> 5) ^ bfm(BFM_CAP, 0x7b) ^ bfm(44, gid) + + +def bfm_words(groups, bound, **reference): + words = [base.SENTINEL] * 320 + for gid in range(min(32 * groups, bound)): + words[gid] = bfm_word(gid, **reference) + return words + + +# Wrong models of the instruction; each must give other words for the largest dispatch and fail the readback. +WRONG = (("operands swapped", dict(swap=True)), ("6-bit width field", dict(width_field=63)), + ("6-bit offset field", dict(offset_field=63)), ("width 0 as 32", dict(zero_full=True)), + ("mask rotated", dict(rotate=True))) + + +def controls(): + """Translator output, the independent reference against hand-worked words, and the refused forms.""" + def bfm(*changes): + _, lines, width, binding = BFM_CASE + return base.aot.lower(base.variant(lines, *changes), width, **binding).splitlines() + + for gid, word in HAND_WORDS.items(): + assert bfm_word(gid) == word, (gid, hex(bfm_word(gid)), hex(word)) + widths = [base.source_word(gid) & 31 for gid in range(32)] + assert sorted(widths) == list(range(32)), widths + lines = bfm() + assert lines[-4:] == [base.GUARD_IF, BFM_STORE, " }", "}"], lines + # A copy of a result is the same program; exchanging the sources is another. + assert bfm(("v_bfm_b32 v4, 44, v0", "v_bfm_b32 v5, 44, v0\nv_mov_b32_e32 v4, v5")) == lines + assert bfm(("v_bfm_b32 v3, s0, 0x7b", "v_bfm_b32 v3, 0x7b, s0"))[-3] != lines[-3] + assert "(((1u << (0x0000007bu & 31u)) - 1u) << (params[0].y & 31u))" in bfm( + ("v_bfm_b32 v3, s0, 0x7b", "v_bfm_b32 v3, 0x7b, s0"))[-3] + # A negative inline constant is its 32-bit pattern: -1 & 31 = 31. + assert "(((1u << (0xffffffffu & 31u)) - 1u) << (tid.x & 31u))" in bfm(("44, v0", "-1, v0"))[-3] + bfm_a = "v_bfm_b32 v2, v1, v2" + unsupported, operand = "Unsupported compute instruction: ", "Unverified ALU operand" + for message, changes in ( + # Source modifiers: LLVM refuses them for this integer opcode, and so does the lowering. + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, |v1|, v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, -v1, v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, -v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, v2 clamp"),)), + # Operand spellings outside ALU_SOURCE: a register range, vcc_lo, exec_lo and a float inline constant. + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v[1:2], v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, vcc_lo, v2"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, exec_lo"),)), + (unsupported + "v_bfm_b32", ((bfm_a, "v_bfm_b32 v2, v1, 0.5"),)), + # Spellings and neighbours that are not this lowering: the _e64 suffix LLVM 15 does not print, the scalar + # and 64-bit forms, and the bitfield extract and insert opcodes. + (unsupported + "v_bfm_b32_e64", ((bfm_a, "v_bfm_b32_e64 v2, v1, v2"),)), + (unsupported + "s_bfm_b32", (("v_bfm_b32 v3, s0, 0x7b", "s_bfm_b32 s16, s0, 27\nv_mov_b32_e32 v3, s16"),)), + (unsupported + "s_bfm_b64", (("v_bfm_b32 v3, s0, 0x7b", "s_bfm_b64 s[16:17], s0, 27\nv_mov_b32_e32 v3, s16"),)), + (unsupported + "v_bfe_u32", ((bfm_a, "v_bfe_u32 v2, v1, v2, 5"),)), + (unsupported + "v_bfi_b32", ((bfm_a, "v_bfi_b32 v2, v1, v2, v0"),)), + # Sources that are not known words: an unwritten, a descriptor and the saved exec-mask SGPR, an unwritten + # VGPR, a literal wider than 32 bits and a constant word still waiting for its s_waitcnt. Also a + # destination past v255. + (operand, (("s0, 0x7b", "s20, 0x7b"),)), + (operand, (("s0, 0x7b", "s8, 0x7b"),)), + (operand, (("s0, 0x7b", "s2, 0x7b"),)), + (operand, ((bfm_a, "v_bfm_b32 v2, v1, v9"),)), + (operand, (("s0, 0x7b", "s0, 0x1ffffffff"),)), + (operand, (("s_buffer_load_dword s0, s[4:7], 0x4", ""), + ("v_lshrrev_b32_e32 v2, 5, v1", "s_buffer_load_dword s0, s[4:7], 0x4\nv_lshrrev_b32_e32 v2, 5, v1"))), + (operand, ((bfm_a, "v_bfm_b32 v256, v1, v2"),)), + ("Vector load result used or overwritten before s_waitcnt vmcnt(0)", (("s_waitcnt vmcnt(0)", ""),)), + # A result is data only: not an address and not a lane-guard operand, and a doubling chain is refused. + ("Unsupported store address", (("v1, v0, s[8:11]", "v0, v4, s[8:11]"),)), + ("Unverified lane guard compare", (("v_xor_b32_e32 v1, v4, v2", + "v_xor_b32_e32 v1, v4, v2\nv_cmp_gt_u32_e32 vcc_lo, s3, v4"),)), + ("ALU expression too large", (("v_xor_b32_e32 v1, v4, v2", + "v_xor_b32_e32 v1, v4, v2" + "\nv_bfm_b32 v1, v1, v1" * 4),)), + ): + base.rejects(message, bfm, *changes) + + +def draw(directory, compiler, renderer, backend): + """Dispatch read_bfm on the renderer and compare the UAV with bfm_words, with wrong references and mutants.""" + name, lines, width, binding = BFM_CASE + src, cso, case = [directory / x for x in ("store.hlsl", "store.cso", "store.case")] + src.write_text(base.aot.lower(lines, width, **binding), encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + cmd = [renderer, backend, "--compute-store-case", cso, case] + constants = [0x5eed0000 + i for i in range(16)] + constants[1] = BFM_CAP + + def write(groups, bound, words): + case.write_bytes(struct.pack("<337I", groups, *words, bound, *constants[1:])) + + for groups, bound in base.READ_RUNS: + write(groups, bound, bfm_words(groups, bound)) + result = subprocess.run(cmd) + if result.returncode: + return result.returncode + groups, bound = base.READ_RUNS[-1] + expected = bfm_words(groups, bound) + assert all(expected[gid] == word for gid, word in HAND_WORDS.items() if gid < bound), "hand-worked words" + fields = [(base.source_word(g) & 31, (base.source_word(g) >> 5) & 31) for g in range(bound)] + # The inputs must show an empty mask, the widest mask, masks cut at bit 31 and masks that fit. + assert any(w == 0 for w, _ in fields) and any(w == 31 for w, _ in fields), "width extremes" + assert any(w + o > 32 for w, o in fields) and any(0 < w and w + o <= 32 for w, o in fields), "cut and whole masks" + off = list(expected) + off[bound - 1] ^= 1 + wrong = [("one word off", off), ("lane past the bound", bfm_words(groups, bound + 1))] + wrong += [(label, bfm_words(groups, bound, **reference)) for label, reference in WRONG] + for label, reference in wrong: + assert reference != expected, f"{label} would go unseen" + word = next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) + write(groups, bound, reference) + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected=" not in bad.stderr: + raise AssertionError(f"{name}: reference '{label}' escaped detection\n{bad.stderr}") + write(groups, bound, expected) + source = src.read_text(encoding="ascii") + cap_term = "(((1u << (params[0].y & 31u)) - 1u) << (0x0000007bu & 31u))" + for label, old, new in (("mask without the minus one", " - 1u)", " - 0u)"), + ("inline width 43", "(0x0000002cu & 31u)", "(0x0000002bu & 31u)"), + ("cap term operands swapped", cap_term, + "(((1u << (0x0000007bu & 31u)) - 1u) << (params[0].y & 31u))"), + ("cap from another word", "params[0].y", "params[0].z")): + mutated = source.replace(old, new) + if mutated == source: + raise AssertionError(f"{name}: mutation '{label}' did not change the source") + mutant, mutant_cso = directory / "mutated.hlsl", directory / "mutated.cso" + mutant.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mutant_cso, mutant], check=True) + bad = subprocess.run([*cmd[:3], mutant_cso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"{name}: mutation '{label}' escaped detection") + return 0 + + +if __name__ == "__main__": + controls() + mode, *args = sys.argv[1:] + if mode == "controls" and not args: + sys.exit(0) + if mode != "draw" or len(args) != 3: + sys.exit(__doc__) + with tempfile.TemporaryDirectory() as tmp: + sys.exit(draw(Path(tmp), *args)) diff --git a/tests/compute_alu_negabs_check.py b/tests/compute_alu_negabs_check.py new file mode 100644 index 0000000000..ebb3d72c41 --- /dev/null +++ b/tests/compute_alu_negabs_check.py @@ -0,0 +1,273 @@ +"""Check -v, |v| and -|v| sources of the VOP3 binary32 forms in the compute store profile: exact lowering, refusals, +an LLVM 15 round trip and a WARP or GPU readback.""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import compute_store_check as base # noqa: E402 + +aot = base.aot +NAME = "read_f32_negabs" +# cap = params[0].y is the float -0.75, so -|s0| differs from -s0 and from |s0| on every lane. +CAP = 0xbf400000 +HALF_WAY = 0x3fe00000 # the float 1.75, a literal: it is not an inline constant +# Binary32 with VOP3 source modifiers, hand-edited in LLVM 15 spelling into the read-compute-write fixture. As in +# compute_store_check.READ_F32, the source word w gives x = 1.5 + (w & 0x3fffff) / 2^23 in [1.5, 2) and +# y = 3.0 + (w >> 10) / 2^22 in [3, 4). Then +# d = x - 1.75 in [-0.25, 0.25), negative on some lanes and positive on others +# z = 0 * d +0.0 where d > 0 and -0.0 where d < 0 +# a = |d| + y |v| on add, src0 +# b = -d * a -v on mul, src0 +# c = b - (-|d|) -|v| on sub, src1 +# e = (-c) - (-|cap|) -|v| on an SGPR and -v on src1 of subrev +# f = |z| * y |v| on a signed zero: +0.0 on every lane +# out = e ^ f bitwise, so a sign bit left on f reaches the readback +# Each modifier appears on two operations. Dropping an abs changes the lanes with d < 0 (and the cap); exchanging an +# abs for a negation changes the lanes with d > 0; dropping a negation changes every lane. The cap is negative, so its abs\n# and its negation each change every lane. +MODIFIED = ("v_add_f32_e64 v6, |v4|, v3", "v_mul_f32_e64 v7, -v4, v6", "v_sub_f32_e64 v8, v7, -|v4|", + "v_subrev_f32_e64 v9, -|s0|, -v8", "v_mul_f32_e64 v10, |v5|, v3") +LINES = base.variant( + base.READ_COMPUTE, + ("v_and_b32_e32 v2, 0xffff, v1", "v_and_b32_e32 v2, 0x3fffff, v1\nv_or_b32_e32 v2, 0x3fc00000, v2\n" + "v_lshrrev_b32_e32 v3, 10, v1\nv_or_b32_e32 v3, 0x40400000, v3"), + ("v_lshrrev_b32_e32 v1, 16, v1", f"v_subrev_f32_e32 v4, 0x{HALF_WAY:08x}, v2\nv_mul_f32_e32 v5, 0, v4\n" + + "\n".join(MODIFIED)), + ("v_mad_u32_u24 v1, v2, v1, v0", "v_xor_b32_e32 v1, v10, v9"), + ("v_min_u32_e32 v1, s0, v1", ""), +) +BINDING = base.READ_BINDING +# The modifier of each modified source, by name: a0 is src0 of a, c1 src1 of c, and so on. +SITES = {"a0": "|", "b0": "-", "c1": "-|", "e0": "-|", "e1": "-", "f0": "|"} +ABS, NEG = "& 0x7fffffffu)", " ^ 0x80000000u)" +# The expected store, built from the step names above: a modified source is its word with bit 31 cleared or flipped. +LOAD = base.READ_LOADS["read_copy"] +X = f"(0x3fc00000u | (0x003fffffu & {LOAD}))" +Y = f"(0x40400000u | ({LOAD} >> (0x0000000au & 31u)))" +D = f"f32_sub({X}, 0x{HALF_WAY:08x}u)" +Z = f"f32_mul(0x00000000u, {D})" +A = f"f32_add(({D} & 0x7fffffffu), {Y})" +B = f"f32_mul(({D} ^ 0x80000000u), {A})" +C = f"f32_sub({B}, (({D} & 0x7fffffffu) ^ 0x80000000u))" +E = f"f32_sub(({C} ^ 0x80000000u), ((params[0].y & 0x7fffffffu) ^ 0x80000000u))" +F = f"f32_mul(({Z} & 0x7fffffffu), {Y})" +STORE = f" outputData.Store(tid.x * 4u + 0u, ({F} ^ {E}));" + + +def modify(bits, modifier): + """VOP3 source modifiers on the 32-bit word: abs clears bit 31, then neg flips it.""" + if "|" in modifier: + bits &= 0x7fffffff + if "-" in modifier: + bits ^= 0x80000000 + return bits + + +def steps(gid, sites=SITES): + """Independent CPU model of one lane as binary32 bit patterns, every intermediate value; sites may change one.""" + value, bits = base.f32_value, base.f32_bits + + def op(fn, a, b): + return bits(base.f32_round(fn(value(a), value(b)))) + + word = base.source_word(gid) + x, y = 0x3fc00000 | word & 0x3fffff, 0x40400000 | word >> 10 + d = op(lambda p, q: p - q, x, HALF_WAY) + z = op(lambda p, q: p * q, 0, d) + a = op(lambda p, q: p + q, modify(d, sites["a0"]), y) + b = op(lambda p, q: p * q, modify(d, sites["b0"]), a) + c = op(lambda p, q: p - q, b, modify(d, sites["c1"])) + e = op(lambda p, q: p - q, modify(c, sites["e1"]), modify(CAP, sites["e0"])) + f = op(lambda p, q: p * q, modify(z, sites["f0"]), y) + return x, y, d, z, a, b, c, e, f, e ^ f + + +def negabs_words(groups, bound, **reference): + words = [base.SENTINEL] * 320 + for gid in range(min(32 * groups, bound)): + words[gid] = steps(gid, **reference)[-1] + return words + + +def wrong_sites(): + """One reference per modified source with its negation dropped, its abs dropped, or abs and negation exchanged.""" + for site, modifier in SITES.items(): + changes = {"-": ("neg dropped", "", "abs for neg", "|"), "|": ("abs dropped", "", "neg for abs", "-"), + "-|": ("neg dropped", "|", "abs dropped", "-")}[modifier] + for label, new in (changes[:2], changes[2:]): + yield f"{site} {label}", SITES | {site: new} + + +def lower(*changes, **binding): + return aot.lower(base.variant(LINES, *changes), 32, **(BINDING | binding)).splitlines() + + +def controls(): + """Exact modifier words, the sign-bit form on zeros and NaNs, then one rejection per form outside the subset.""" + lines = lower() + store = lines[-3] + assert lines[-4:] == [base.GUARD_IF, STORE, " }", "}"], lines + # Each modifier is an integer operation on the word, once per modified source, and never a float abs or negation. + assert store.count(ABS) == 4 and store.count(NEG) == 4, store + assert "abs(" not in "\n".join(lines) and "-asfloat" not in "\n".join(lines), lines + + # The sign-bit form keeps every other bit, also for signed zeros, infinities and NaN payloads, which the float + # forms abs() and unary minus need not do. The expression is evaluated here on the word. + vector = {2: ("alu", "W")} + forms = {token: aot.float_e64_source(token, {}, vector, set()) for token in ("-v2", "|v2|", "-|v2|")} + assert forms == {"-v2": "(W ^ 0x80000000u)", "|v2|": "(W & 0x7fffffffu)", "-|v2|": "((W & 0x7fffffffu) ^ 0x80000000u)"} + for word in (0x00000000, 0x80000000, 0x7fc12345, 0xffc00001, 0x7f800001, 0xff800000, 0xbf400000, 0x00000001): + for token, expression in forms.items(): + got = eval(re.sub(r"(0x[0-9a-f]+)u", r"\1", expression).replace("W", str(word))) + assert got == modify(word, token.replace("v2", "")), (token, hex(word), hex(got)) + + # A spelling of the same program: a source without modifier may stay plain in a modified _e64 form. + plain = "v_add_f32_e64 v6, |v4|, v3" + assert lower((plain, "v_add_f32_e64 v6, v3, |v4|"))[-3] != store + assert lower((plain, "v_add_f32_e64 v6, |v4|, s0"))[-3].count("params[0].y") == 2 + # A source modifier changes the program: each one dropped (as the _e32 form where that is all) differs. + assert lower(("v_mul_f32_e64 v7, -v4, v6", "v_mul_f32_e32 v7, v4, v6"))[-3] != store + assert lower(("v_sub_f32_e64 v8, v7, -|v4|", "v_sub_f32_e64 v8, v7, |v4|"))[-3] != store + assert lower(("v_sub_f32_e64 v8, v7, -|v4|", "v_sub_f32_e64 v8, v7, -v4"))[-3] != store + assert lower(("v_subrev_f32_e64 v9, -|s0|, -v8", "v_subrev_f32_e64 v9, |s0|, -v8"))[-3] != store + + unsupported, modifier = "Unsupported compute instruction: ", "Unsupported float source modifier" + output, operand = "Unsupported float output modifier", "Unverified float operand" + add = "v_add_f32_e64 v6, |v4|, v3" + for message, changes in ( + # The unmodified _e64 spelling stays refused, as does every opcode outside the four binary32 forms. + (unsupported + "v_add_f32_e64", ((add, "v_add_f32_e64 v6, v4, v3"),)), + (unsupported + "v_max_f32_e64", ((add, "v_max_f32_e64 v6, |v4|, v3"),)), + (unsupported + "v_fma_f32", ((add, "v_fma_f32 v6, |v4|, v3, v2"),)), + (unsupported + "v_add_f16_e64", ((add, "v_add_f16_e64 v6, |v4|, v3"),)), + # Modifiers on the VOP2 spelling, which has no modifier field. + (unsupported + "v_add_f32_e32", ((add, "v_add_f32_e32 v6, |v4|, v3"),)), + (unsupported + "v_add_f32_e32", ((add, "v_add_f32_e32 v6, -v4, v3"),)), + (unsupported + "v_add_f32_e32", ((add, "v_add_f32_e32 v6, -|v4|, v3"),)), + # Output modifiers, a third source and a register range. + (output, ((add, add + " clamp"),)), + (output, ((add, add + " mul:2"),)), + (output, ((add, add + " mul:4"),)), + (output, ((add, add + " div:2"),)), + (unsupported + "v_add_f32_e64", ((add, add + ", v2"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v[4:5]|, v3"),)), + # Spellings LLVM 15 does not print for a register, unbalanced bars, and modifiers on constants. + (modifier, ((add, "v_add_f32_e64 v6, abs(v4), v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, neg(v4), v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, --v4, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, |-v4|, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, -|v4, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, -v4|, v3"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, |1.0|"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, -|0.5|"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, neg(0x3f800000)"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, -0x3f800000"),)), + (modifier, ((add, "v_add_f32_e64 v6, |v4|, |0x3f800000|"),)), + # Sources that are not known words or not finite normal constants, with and without a modifier. + (operand, ((add, "v_add_f32_e64 v6, |v40|, v3"),)), + (operand, ((add, "v_add_f32_e64 v6, |v4|, v40"),)), + (operand, ((add, "v_add_f32_e64 v6, -|s20|, v3"),)), + (operand, ((add, "v_add_f32_e64 v6, -|s8|, v3"),)), + (operand, ((add, "s_mov_b32 s20, 0x7fc00000\nv_add_f32_e64 v6, |s20|, v3"),)), + (operand, ((add, "s_mov_b32 s20, 0x80000001\nv_add_f32_e64 v6, -s20, v3"),)), + (operand, ((add, "v_add_f32_e64 v6, |v4|, 0x7f800000"),)), + (operand, ((add, "v_add_f32_e64 v6, |v4|, -1"),)), + (operand, ((add, "v_add_f32_e64 v256, |v4|, v3"),)), + # A result is data only: not a store address and not a lane-guard operand, and a long chain is refused. + ("Unsupported store address", (("v1, v0, s[8:11]", "v0, v1, s[8:11]"),)), + ("Unverified lane guard compare", (("v_xor_b32_e32 v1, v10, v9", + "v_xor_b32_e32 v1, v10, v9\nv_cmp_gt_u32_e32 vcc_lo, s3, v6"),)), + ("ALU expression too large", (("v_xor_b32_e32 v1, v10, v9", + "v_mul_f32_e64 v9, -v9, v9\n" * 3 + "v_xor_b32_e32 v1, v10, v9"),)), + ): + base.rejects(message, lower, *changes) + + +def binary(directory, assembler, objcopy, library): + """Assemble the fixture with LLVM 15, disassemble it and require the same spelling and the same translation.""" + src, obj, raw = [directory / x for x in ("negabs.s", "negabs.o", "negabs.bin")] + src.write_text("\n".join(LINES) + "\n", encoding="ascii") + subprocess.run([assembler, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-filetype=obj", src, "-o", obj], check=True) + subprocess.run([objcopy, "-O", "binary", "--only-section=.text", obj, raw], check=True) + decoded = base.disassemble(raw.read_bytes(), library, offsets=True) + printed = [line for _, line in decoded] + missing = [line for line in MODIFIED if line not in printed] + assert not missing, (missing, printed) + assert aot.lower(aot.labelled(decoded), 32, **BINDING) == aot.lower(LINES, 32, **BINDING) + print(f"{NAME}: LLVM round trip prints the {len(MODIFIED)} modified forms and translates identically") + return 0 + + +def draw(directory, compiler, renderer, backend): + """Translate, compile and dispatch the fixture, then require wrong references and mutated sources to fail.""" + src, cso, case = [directory / x for x in ("store.hlsl", "store.cso", "store.case")] + source = aot.lower(LINES, 32, **BINDING) + src.write_text(source, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + cmd = [renderer, backend, "--compute-store-case", cso, case] + constants = [0x5eed0000 + i for i in range(16)] + constants[1] = CAP + groups, bound = base.READ_RUNS[-1] + + def write(run_groups, run_bound, words): + case.write_bytes(struct.pack("<337I", run_groups, *words, run_bound, *constants[1:])) + + # Every operand and result of an active lane is finite and normal, except z and f, which are signed zeros, and d + # takes both signs, so each modifier is observed. f is +0.0 on every lane, z is -0.0 on some lanes. + lanes = [steps(gid) for gid in range(bound)] + for gid, lane in enumerate(lanes): + x, y, d, z, a, b, c, e, f, _ = lane + for value in (x, y, d, a, b, c, e): + assert 0x00800000 <= value & 0x7fffffff < 0x7f800000, (gid, hex(value)) + assert z == d & 0x80000000 and f == 0, (gid, hex(z), hex(f)) + assert {lane[2] >> 31 for lane in lanes} == {0, 1}, "d has one sign on every lane" + for run_groups, run_bound in base.READ_RUNS: + write(run_groups, run_bound, negabs_words(run_groups, run_bound)) + result = subprocess.run(cmd) + if result.returncode: + return result.returncode + expected = negabs_words(groups, bound) + wrong = list(wrong_sites()) + for label, sites in wrong: + reference = negabs_words(groups, bound, sites=sites) + word = next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) + write(groups, bound, reference) + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected={reference[word]:08x}" not in bad.stderr: + raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{bad.stderr}") + write(groups, bound, expected) + # Each modifier occurrence in the HLSL, dropped alone or exchanged for the other modifier, must fail. + mutations = [] + for old, labels in ((ABS, (("abs dropped", "& 0xffffffffu)"),)), + (NEG, (("neg dropped", " ^ 0x00000000u)"), ("neg as abs", " & 0x7fffffffu)")))): + starts = [m.start() for m in re.finditer(re.escape(old), source)] + assert len(starts) == 4, (old, len(starts)) + for n, start in enumerate(starts): + for label, new in labels: + mutations.append((f"{label} at occurrence {n}", source[:start] + new + source[start + len(old):])) + for label, mutated in mutations: + bad_src, bad_cso = directory / "mutated.hlsl", directory / "mutated.cso" + bad_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", bad_cso, bad_src], check=True) + bad = subprocess.run([*cmd[:3], bad_cso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{bad.stderr}") + print(f"{NAME}: {len(base.READ_RUNS)} dispatches, {len(wrong)} wrong references and " + f"{len(mutations)} mutated sources checked") + return 0 + + +if __name__ == "__main__": + mode, *args = sys.argv[1:] + controls() + if mode == "controls": + sys.exit(0) + if mode not in ("draw", "binary") or len(args) != 3: + sys.exit("usage: compute_alu_negabs_check.py controls | draw <dxc> <renderer> <adapter>" + " | binary <llvm-mc> <llvm-objcopy> <libLLVM>") + with tempfile.TemporaryDirectory() as tmp: + sys.exit((draw if mode == "draw" else binary)(Path(tmp), *args)) diff --git a/tests/compute_alu_vop1_check.py b/tests/compute_alu_vop1_check.py new file mode 100644 index 0000000000..ab9853eb09 --- /dev/null +++ b/tests/compute_alu_vop1_check.py @@ -0,0 +1,292 @@ +"""Check the compute VOP1 bit forms v_bfrev_b32 and v_ffbh_i32 between a guarded read and its store. + +Modes: + controls translator only: exact output and rejections + draw <dxc> <renderer> <hardware|warp> translate, dispatch and compare the full UAV readback +""" +from pathlib import Path +from unittest.mock import patch +import os +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import compute_store_check as base # noqa: E402 + +aot = base.aot +MASK = 0xffffffff + +# The read-compute-write fixture of compute_store_check.py (READ_COMPUTE) with its four ALU lines replaced by the +# two VOP1 forms, written by hand in the LLVM 15 spelling, and a 16-byte element per lane. With w the source word: +# out[4 * gid + 0] = bfrev(w) +# out[4 * gid + 1] = ffbh_i32(w << (w & 31)) +# out[4 * gid + 2] = ffbh_i32(ashr(bfrev(w), (w >> 5) & 31)) +# out[4 * gid + 3] = ((bfrev(gid) ^ ffbh_i32(cap)) + ffbh_i32(-1)) ^ bfrev(0x12345678) +# The shifted words give both signs and leading runs of 1 to 30 bits (the cap gives 31), and the arithmetic shift +# also gives 0 and 0xffffffff. The sources cover a VGPR read from t0, a computed VGPR, the dispatch index, an SGPR (cap = +# params[0].y), an inline constant and a literal. +VOP1_CHAIN = ("v_bfrev_b32_e32 v2, v1\n" + "v_lshlrev_b32_e32 v3, v1, v1\nv_ffbh_i32_e32 v3, v3\n" + "v_lshrrev_b32_e32 v4, 5, v1\nv_ashrrev_i32_e32 v4, v4, v2\nv_ffbh_i32_e32 v4, v4\n" + "v_bfrev_b32_e32 v5, v0\nv_ffbh_i32_e32 v6, s0\nv_xor_b32_e32 v5, v6, v5\n" + "v_ffbh_i32_e32 v6, -1\nv_add_nc_u32_e32 v5, v6, v5\n" + "v_bfrev_b32_e32 v6, 0x12345678\nv_xor_b32_e32 v5, v6, v5") +READ_VOP1 = base.variant( + base.READ_COMPUTE, + ("v_and_b32_e32 v2, 0xffff, v1", VOP1_CHAIN), + ("v_lshrrev_b32_e32 v1, 16, v1", ""), + ("v_mad_u32_u24 v1, v2, v1, v0", ""), + ("v_min_u32_e32 v1, s0, v1", ""), + ("buffer_store_dword v1, v0, s[8:11], 0 idxen", "buffer_store_dwordx4 v[2:5], v0, s[8:11], 0 idxen"), +) +VOP1_BINDING = base.READ_BINDING | dict(stride=16) +LOAD = base.READ_LOADS["read_copy"] + + +def bfrev_text(x): + return f"reversebits({x})" + + +def ffbh_text(x): + return f"firstbitlow(reversebits({x} ^ asuint(asint({x}) >> 31u)))" + + +SHIFTED = f"({LOAD} << ({LOAD} & 31u))" +SPREAD = f"asuint(asint({bfrev_text(LOAD)}) >> (({LOAD} >> (0x00000005u & 31u)) & 31u))" + + +def vop1_store(index="tid.x", cap="params[0].y", inline="0xffffffffu"): + """The guarded store, with the sources of the three word-3 instructions that take a known word.""" + constant = f"({bfrev_text('0x12345678u')} ^ ({ffbh_text(inline)} + ({ffbh_text(cap)} ^ {bfrev_text(index)})))" + return (f" outputData.Store4(tid.x * 16u + 0u, uint4({bfrev_text(LOAD)}, {ffbh_text(SHIFTED)}, " + f"{ffbh_text(SPREAD)}, {constant}));") + + +def bfrev(x): + """Bit i of the result is bit 31 - i of x.""" + return int(f"{x:032b}"[::-1], 2) + + +def ffbh_i32(x): + """AMD RDNA 2 ISA, V_FFBH_I32: D = -1; for i in 1..31, the first i with S0[31 - i] != S0[31] is D.""" + for i in range(1, 32): + if (x >> (31 - i)) & 1 != x >> 31: + return i + return MASK + + +def ffbh_u32(x): + """V_FFBH_U32, the unsigned scan: the MSB-first index of the first set bit, -1 for zero.""" + return next((i for i in range(32) if (x >> (31 - i)) & 1), MASK) + + +def ashr(x, n): + return ((x - (1 << 32) if x >> 31 else x) >> (n & 31)) & MASK + + +# Wrong models of the two forms for the reference controls. Each must differ from the right one on the fixture. +WRONG_MODELS = { + "ffbh_u32 for ffbh_i32": dict(ffbh=ffbh_u32), + "ffbh counting after the sign bit": dict(ffbh=lambda x: ffbh_i32(x) - 1 if ffbh_i32(x) != MASK else MASK), + "ffbh as an LSB-first index": dict(ffbh=lambda x: 31 - ffbh_i32(x) if ffbh_i32(x) != MASK else MASK), + "ffbh 32 for 0 and -1": dict(ffbh=lambda x: 32 if ffbh_i32(x) == MASK else ffbh_i32(x)), + "bfrev as a copy": dict(reverse=lambda x: x), +} +VOP1_CAP = 0xfffffffe # ffbh_i32 = 31: only bit 0 differs from the sign bit +# (groups, bound): no lane passes, a split wave, and three groups with 70 active lanes, 280 of the 320 words. +VOP1_RUNS = ((1, 0), (1, 17), (3, 70)) + + +def lane_words(gid, *, reverse=bfrev, ffbh=ffbh_i32): + """Independent CPU reference of one lane's four words.""" + w = base.source_word(gid) + shifted = (w << (w & 31)) & MASK + spread = ashr(reverse(w), w >> 5) + constant = (((reverse(gid) ^ ffbh(VOP1_CAP)) + ffbh(MASK)) & MASK) ^ reverse(0x12345678) + return [reverse(w), ffbh(shifted), ffbh(spread), constant] + + +def vop1_words(groups, bound, **model): + words = [base.SENTINEL] * 320 + for gid in range(min(32 * groups, bound)): + words[4 * gid:4 * gid + 4] = lane_words(gid, **model) + return words + + +def reference_controls(): + """The CPU model against hand-worked ISA cases, and the fixture's coverage of them.""" + for x, expected in ((0, MASK), (MASK, MASK), (1, 31), (0xfffffffe, 31), (0x80000000, 1), (0x7fffffff, 1), + (0x40000000, 1), (0xbfffffff, 1), (0x3fffffff, 2), (0xc0000000, 2), (0x0000ffff, 16), + (0xffe0c0de, 11)): + assert ffbh_i32(x) == expected, (hex(x), ffbh_i32(x)) + for x, expected in ((0, 0), (1, 0x80000000), (0x80000000, 1), (0x12345678, 0x1e6a2c48), (0xf0000000, 0xf)): + assert bfrev(x) == expected, (hex(x), hex(bfrev(x))) + groups, bound = VOP1_RUNS[-1] + lanes = [base.source_word(gid) for gid in range(bound)] + inputs = [(w << (w & 31)) & MASK for w in lanes] + [ashr(bfrev(w), w >> 5) for w in lanes] + [VOP1_CAP] + # Both signs, both all-equal words, the shortest and the longest run. + assert {0, MASK} <= set(inputs) and any(x >> 31 and x != MASK for x in inputs) + assert any(0 < x < 1 << 31 for x in inputs) + assert {1, 31} <= {ffbh_i32(x) for x in inputs} + expected = vop1_words(groups, bound) + for label, model in WRONG_MODELS.items(): + assert vop1_words(groups, bound, **model) != expected, f"{label} would go unseen" + + +def controls(): + """Translator only: exact output, then one rejection per form or operand outside the subset.""" + reference_controls() + + def vop1(*changes, **binding): + return aot.lower(base.variant(READ_VOP1, *changes), 32, **(VOP1_BINDING | binding)).splitlines() + + lines = vop1() + assert lines[:3] == ["cbuffer Constants : register(b0) { uint4 params[4]; };", + "ByteAddressBuffer inputData : register(t0);", + "RWByteAddressBuffer outputData : register(u0);"], lines + assert lines[-4:] == [base.GUARD_IF, vop1_store(), " }", "}"], lines[-4:] + # A copy of a result is the same program. + assert vop1(("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v7, v1\nv_mov_b32_e32 v2, v7")) == lines + # Each source kind prints as its own word. + for source, word in (("s0", "params[0].y"), ("-16", "0xfffffff0u"), ("0x80000000", "0x80000000u"), + ("v0", "tid.x"), ("v1", LOAD)): + assert vop1(("v_ffbh_i32_e32 v6, -1", f"v_ffbh_i32_e32 v6, {source}"))[-3] == vop1_store(inline=word) + assert vop1(("v_ffbh_i32_e32 v6, s0", f"v_ffbh_i32_e32 v6, {source}"))[-3] == vop1_store(cap=word) + assert vop1(("v_bfrev_b32_e32 v5, v0", f"v_bfrev_b32_e32 v5, {source}"))[-3] == vop1_store(index=word) + unsupported, operand = "Unsupported compute instruction: ", "Unverified ALU operand" + for message, changes in ( + # The VOP3, SDWA and DPP encodings of both forms, source and output modifiers, and a register range. + (unsupported + "v_bfrev_b32_e64", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e64 v2, v1"),)), + (unsupported + "v_ffbh_i32_e64", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e64 v3, v3"),)), + (unsupported + "v_ffbh_i32_e64", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e64 v3, -v3"),)), + (unsupported + "v_bfrev_b32_sdwa", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_sdwa v2, v1 dst_sel:DWORD " + "dst_unused:UNUSED_PAD src0_sel:WORD_1"),)), + (unsupported + "v_ffbh_i32_sdwa", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_sdwa v3, v3 dst_sel:DWORD " + "dst_unused:UNUSED_PAD src0_sel:BYTE_0"),)), + (unsupported + "v_ffbh_i32_dpp", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_dpp v3, v3 quad_perm:[1,0,3,2] " + "row_mask:0xf bank_mask:0xf"),)), + (unsupported + "v_bfrev_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v2, -v1"),)), + (unsupported + "v_bfrev_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v2, |v1|"),)), + (unsupported + "v_ffbh_i32_e32", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e32 v3, v3 clamp"),)), + (unsupported + "v_bfrev_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v2, v[1:2]"),)), + # Neighbouring opcodes outside the family, and the scalar forms. + (unsupported + "v_ffbh_u32_e32", (("v_ffbh_i32_e32 v3, v3", "v_ffbh_u32_e32 v3, v3"),)), + (unsupported + "v_ffbl_b32_e32", (("v_ffbh_i32_e32 v3, v3", "v_ffbl_b32_e32 v3, v3"),)), + (unsupported + "v_not_b32_e32", (("v_bfrev_b32_e32 v2, v1", "v_not_b32_e32 v2, v1"),)), + (unsupported + "s_brev_b32", (("v_ffbh_i32_e32 v6, s0", "s_brev_b32 s16, s0\nv_ffbh_i32_e32 v6, s16"),)), + (unsupported + "s_flbit_i32", (("v_ffbh_i32_e32 v6, s0", "s_flbit_i32 s16, s0\nv_ffbh_i32_e32 v6, s16"),)), + # Sources that are not known words: an unknown VGPR, an unwritten, descriptor, saved exec-mask, pending or + # out-of-range SGPR, a literal wider than 32 bits and a byte offset. Also a destination past v255. + (operand, (("v_ffbh_i32_e32 v3, v3", "v_ffbh_i32_e32 v3, v9"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s20"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s8"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s2"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "s_buffer_load_dword s20, s[4:7], 0x8\nv_ffbh_i32_e32 v6, s20"),)), + (operand, (("v_ffbh_i32_e32 v6, s0", "v_ffbh_i32_e32 v6, s106"),)), + (operand, (("v_bfrev_b32_e32 v6, 0x12345678", "v_bfrev_b32_e32 v6, 0x112345678"),)), + (operand, (("v_bfrev_b32_e32 v5, v0", "v_lshlrev_b32_e32 v7, 2, v0\nv_bfrev_b32_e32 v5, v7"),)), + (operand, (("v_bfrev_b32_e32 v2, v1", "v_bfrev_b32_e32 v256, v1"),)), + ("Vector load result used or overwritten before s_waitcnt vmcnt(0)", (("s_waitcnt vmcnt(0)", ""),)), + # A result is data only: not a store or read address and not a lane-guard operand. + ("Unsupported store address", (("v[2:5], v0, s[8:11]", "v[2:5], v3, s[8:11]"),)), + ("Unsupported read address", (("buffer_store_dwordx4", "buffer_load_dword v7, v4, s[12:15], 0 offen\n" + "buffer_store_dwordx4"),)), + ("Unverified lane guard compare", (("buffer_store_dwordx4", "v_cmp_gt_u32_e32 vcc_lo, s3, v3\n" + "buffer_store_dwordx4"),)), + # ffbh_i32 names its source twice, so a chain of them is refused once it passes the limit. + ("ALU expression too large", (("v_ffbh_i32_e32 v4, v4", "v_ffbh_i32_e32 v4, v4" + + "\nv_ffbh_i32_e32 v4, v4" * 2),)), + ): + base.rejects(message, vop1, *changes) + # With the x8 descriptor load moved before the guard, a result computed under the guard is unknown after the + # restore, and one computed after it is known. + restored = (("s_load_dwordx8 s[8:15], s[0:1], 0x0", ""), + ("s_and_saveexec_b32 s2, vcc_lo", "s_load_dwordx8 s[8:15], s[0:1], 0x0\ns_waitcnt lgkmcnt(0)\n" + "s_and_saveexec_b32 s2, vcc_lo"), + ("s_cbranch_execz .LBB0_2", ""), (".LBB0_2:", ""), + ("buffer_store_dwordx4 v[2:5], v0, s[8:11], 0 idxen", + "buffer_store_dwordx3 v[2:4], v0, s[8:11], 0 idxen\ns_or_b32 exec_lo, exec_lo, s2\n" + "buffer_store_dword v5, v0, s[8:11], 0 idxen offset:12")) + base.rejects("Store data is not a known word", vop1, *restored) + after = vop1(*restored[:-1], (restored[-1][0], restored[-1][1].replace( + "\nbuffer_store_dword v5", "\nv_bfrev_b32_e32 v5, 1\nbuffer_store_dword v5"))) + assert after[-3:] == [" }", " outputData.Store(tid.x * 16u + 12u, reversebits(0x00000001u));", "}"], after + return 0 + + +# Translations that a wrong template would produce; each must fail on the GPU. +TEMPLATE_MUTATIONS = ( + ("bfrev as a copy", "v_bfrev_b32_e32", "({0})"), + ("bfrev as a complement", "v_bfrev_b32_e32", "(~{0})"), + ("ffbh_i32 as ffbh_u32", "v_ffbh_i32_e32", "firstbitlow(reversebits({0}))"), + ("logical sign fold", "v_ffbh_i32_e32", "firstbitlow(reversebits({0} ^ ({0} >> 31u)))"), + ("LSB-first index", "v_ffbh_i32_e32", "firstbithigh({0} ^ asuint(asint({0}) >> 31u))"), + ("32 for 0 and -1", "v_ffbh_i32_e32", "(31u - firstbithigh({0} ^ asuint(asint({0}) >> 31u)))"), + ("count after the sign bit", "v_ffbh_i32_e32", "(firstbitlow(reversebits({0} ^ asuint(asint({0}) >> 31u))) - 1u)"), +) + + +def draw(directory, compiler, renderer, backend): + controls() + src, cso, case = (directory / f"vop1.{ext}" for ext in ("hlsl", "cso", "case")) + compile_hlsl = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + run = [renderer, backend, "--compute-store-case", cso, case] + constants = [0x5eed0000 + i for i in range(16)] + constants[1] = VOP1_CAP + + def write(groups, bound, words): + case.write_bytes(struct.pack("<337I", groups, *words, bound, *constants[1:])) + + source = aot.lower(READ_VOP1, 32, **VOP1_BINDING) + src.write_text(source, encoding="ascii") + subprocess.run(compile_hlsl, check=True) + for groups, bound in VOP1_RUNS: + print(f"read_vop1: groups={groups} bound={bound}", flush=True) + write(groups, bound, vop1_words(groups, bound)) + result = subprocess.run(run) + if result.returncode: + return result.returncode + groups, bound = VOP1_RUNS[-1] + expected = vop1_words(groups, bound) + # Reference controls: one word off, the first lane past the bound writing, and each wrong model. + off = list(expected) + off[4 * bound - 1] ^= 1 + for label, reference in (("one word off", off), ("lane past the bound", vop1_words(groups, bound + 1)), + *((label, vop1_words(groups, bound, **model)) for label, model in WRONG_MODELS.items())): + word = next(i for i, (a, b) in enumerate(zip(expected, reference)) if a != b) + write(groups, bound, reference) + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or f"word={word} expected=" not in bad.stderr: + raise AssertionError(f"read_vop1: reference '{label}' escaped detection\n{bad.stdout}\n{bad.stderr}") + print(f"read_vop1: reference '{label}' fails at word {word}", flush=True) + write(groups, bound, expected) + mutated_src, mutated_cso = directory / "mutated.hlsl", directory / "mutated.cso" + for label, op, template in TEMPLATE_MUTATIONS: + with patch.dict(aot.VOP1_ALU, {op: template}): + mutated = aot.lower(READ_VOP1, 32, **VOP1_BINDING) + if mutated == source: + raise AssertionError(f"read_vop1: mutation '{label}' did not change the source") + mutated_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mutated_cso, mutated_src], check=True) + bad = subprocess.run([*run[:3], mutated_cso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"read_vop1: mutation '{label}' escaped detection\n{bad.stdout}\n{bad.stderr}") + print(f"read_vop1: mutation '{label}' fails", flush=True) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("v_bfrev_b32_e32\nv_ffbh_i32_e32\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + mode, *args = sys.argv[1:] + if mode == "controls" and not args: + sys.exit(controls()) + if mode == "draw" and len(args) == 3: + with tempfile.TemporaryDirectory() as tmp: + sys.exit(draw(Path(tmp), *args)) + sys.exit(f"usage: {Path(__file__).name} controls | draw <dxc> <renderer> <hardware|warp>") diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 4b6ada2a53..8d8eec6926 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -25,6 +25,9 @@ constexpr UINT uavs = 13, srvs = 21; // The image case header packs the dispatch count and a format/capability selector. The payload // carries raw texels, one word each for RGBA8 and scalar R32, or four for RGBA32. constexpr UINT texture_rgba8_flag = 1u << 24; +// Read-only image case selectors. The dispatch dimensions each fit in three bits. +constexpr UINT texture_mip_zero_sampler_flag = 1u << 22; +constexpr UINT texture_comparison_flag = 1u << 23; constexpr UINT texture_atomic_uint_flag = 1u << 25; constexpr UINT texture_atomic_sint_minmax_flag = 1u << 26; constexpr UINT texture_atomic_uint_minmax_flag = 1u << 27; @@ -250,8 +253,21 @@ struct StoreCase { } }; -static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE shader, - D3D12_SHADER_BYTECODE rootBytes, bool conversion_pair = false, +static ComputeReadbackProgram create_compute_program(ID3D12Device* device, D3D12_SHADER_BYTECODE shader, + D3D12_SHADER_BYTECODE rootBytes) +{ + ComputeReadbackProgram program; + check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&program.signature)), + "Create compute root signature"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = program.signature.Get(); + pso.CS = shader; + check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&program.pipeline)), "Create compute pipeline"); + return program; +} + +static void run_compute(ID3D12Device* device, bool tables, const ComputeReadbackProgram& program, + bool conversion_pair = false, const StoreCase* store = nullptr, const std::vector<UINT>* texels = nullptr, DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN, ID3D12Resource* rendered_texture = nullptr, bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0, @@ -259,14 +275,6 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE { if ((texels || rendered_texture) && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); if (uav_words == 0 || uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); - ComPtr<ID3D12RootSignature> signature; - check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&signature)), - "Create compute root signature"); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; - pso.pRootSignature = signature.Get(); - pso.CS = shader; - ComPtr<ID3D12PipelineState> pipeline; - check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline)), "Create compute pipeline"); auto input = make_buffer(device, constants_offset + 4 * alignment, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); auto output = make_buffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, @@ -275,14 +283,14 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr, store && store->has_initial ? &store->initial : nullptr, store ? &store->root_constants : nullptr); - ComputeCommands commands(device, pipeline.Get()); + ComputeCommands commands(device, program.pipeline.Get()); auto& list = commands.list; ComPtr<ID3D12Resource> texture_upload, texture; if (texels) texture = upload_texture(device, list.Get(), *texels, texture_format, texture_upload); transition(list.Get(), output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); list->CopyBufferRegion(output.Get(), 0, input.Get(), bytes, bytes); transition(list.Get(), output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list->SetComputeRootSignature(signature.Get()); + list->SetComputeRootSignature(program.signature.Get()); ComPtr<ID3D12DescriptorHeap> heap; if (tables) { // An image-load case binds its output at u0 and the source texture at t0; the table @@ -346,21 +354,18 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE store->axis(2), capacity, mismatches); else std::printf("layout=%s output_words=%u guard_words=%u mismatches=%u\n", tables ? "tables" : "root", active, capacity - active, mismatches); - if (mismatches) throw std::runtime_error("Compute readback differs from CPU reference"); + if (mismatches) throw ReadbackMismatch("Compute readback differs from CPU reference"); } void check_compute(ID3D12Device* device, bool tables) { const D3D12_SHADER_BYTECODE shader = tables ? D3D12_SHADER_BYTECODE{compute_tables, sizeof(compute_tables)} : D3D12_SHADER_BYTECODE{compute_root, sizeof(compute_root)}; - run_compute(device, tables, shader, shader); + run_compute(device, tables, create_compute_program(device, shader, shader)); } -void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, - bool dpp_case, bool sized_views, UINT uav_words) +static std::vector<char> read_compute_shader(const char* path) { - if (sized_views && uav_words > capacity) - throw std::runtime_error("Invalid compute UAV word count"); std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); const auto size = file.tellg(); @@ -369,70 +374,86 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ file.seekg(0); if (!file.read(bytes.data(), static_cast<std::streamsize>(bytes.size()))) throw std::runtime_error(std::string("Could not read compute shader: ") + path); - const D3D12_SHADER_BYTECODE shader{bytes.data(), bytes.size()}; - if (reference) { - StoreCase store{}; - std::ifstream file(reference, std::ios::binary); - file.read(reinterpret_cast<char*>(&store.groups), sizeof(store.groups)); - file.read(reinterpret_cast<char*>(store.expected.data()), sizeof(store.expected)); - // Bit 31 declares the trailing initial output segment; no other bit above the - // group counts is known, so an unflagged case keeps its historic bounds check. - constexpr UINT initial_data_flag = 1u << 31; - store.has_initial = (store.groups & initial_data_flag) != 0; - store.groups &= ~initial_data_flag; - if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || - store.axis(2) > 5) - throw std::runtime_error("Invalid compute store reference"); - if (dpp_case && store.groups != 1) - throw std::runtime_error("Invalid compute DPP reference dispatch"); - if (store.has_initial) { - file.read(reinterpret_cast<char*>(store.initial.data()), sizeof(store.initial)); - if (!file) - throw std::runtime_error("Invalid compute store initial words"); - } + return bytes; +} + +static StoreCase read_store_reference(const char* reference, bool dpp_case) +{ + StoreCase store{}; + std::ifstream file(reference, std::ios::binary); + file.read(reinterpret_cast<char*>(&store.groups), sizeof(store.groups)); + file.read(reinterpret_cast<char*>(store.expected.data()), sizeof(store.expected)); + // Bit 31 declares the trailing initial output segment; no other bit above the + // group counts is known, so an unflagged case keeps its historic bounds check. + constexpr UINT initial_data_flag = 1u << 31; + store.has_initial = (store.groups & initial_data_flag) != 0; + store.groups &= ~initial_data_flag; + if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || + store.axis(2) > 5) + throw std::runtime_error("Invalid compute store reference"); + if (dpp_case && store.groups != 1) + throw std::runtime_error("Invalid compute DPP reference dispatch"); + if (store.has_initial) { + file.read(reinterpret_cast<char*>(store.initial.data()), sizeof(store.initial)); + if (!file) + throw std::runtime_error("Invalid compute store initial words"); + } + if (file.peek() != std::char_traits<char>::eof()) { + file.read(reinterpret_cast<char*>(store.root_constants.data()), sizeof(store.root_constants)); + if (!file) + throw std::runtime_error("Invalid compute store constants"); if (file.peek() != std::char_traits<char>::eof()) { - file.read(reinterpret_cast<char*>(store.root_constants.data()), sizeof(store.root_constants)); - if (!file) - throw std::runtime_error("Invalid compute store constants"); - if (file.peek() != std::char_traits<char>::eof()) { - file.read(reinterpret_cast<char*>(store.source.data()), sizeof(store.source)); - if (!file || file.peek() != std::char_traits<char>::eof()) - throw std::runtime_error("Invalid compute store source words"); - store.has_source = true; - } + file.read(reinterpret_cast<char*>(store.source.data()), sizeof(store.source)); + if (!file || file.peek() != std::char_traits<char>::eof()) + throw std::runtime_error("Invalid compute store source words"); + store.has_source = true; } + } + return store; +} + +ComputeReadbackProgram load_compute_store_program(ID3D12Device* device, const char* shader) +{ + const auto code = read_compute_shader(shader); + return create_compute_program(device, {code.data(), code.size()}, {compute_root, sizeof(compute_root)}); +} + +void check_compute_store_reference(ID3D12Device* device, const ComputeReadbackProgram& program, const char* reference) +{ + const StoreCase store = read_store_reference(reference, false); + run_compute(device, false, program, false, &store); +} + +void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, + bool dpp_case, bool sized_views, UINT uav_words) +{ + if (sized_views && uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); + const auto bytes = read_compute_shader(path); + const D3D12_SHADER_BYTECODE shader{bytes.data(), bytes.size()}; + if (reference) { + const StoreCase store = read_store_reference(reference, dpp_case); if (sized_views) { const UINT effective_uav_words = uav_words ? uav_words : capacity; if (effective_uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); - run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, nullptr, + const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true, 0, effective_uav_words); } else { - run_compute(device, false, shader, {compute_root, sizeof(compute_root)}, false, &store, nullptr, + const auto program = create_compute_program(device, shader, {compute_root, sizeof(compute_root)}); + run_compute(device, false, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case); } } else { - run_compute(device, false, shader, shader, conversion_pair); + run_compute(device, false, create_compute_program(device, shader, shader), conversion_pair); } } -static std::vector<char> read_texture_shader(const char* path) -{ - std::ifstream file(path, std::ios::binary | std::ios::ate); - if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); - const auto size = file.tellg(); - if (size <= 0) throw std::runtime_error(std::string("Empty compute shader: ") + path); - std::vector<char> bytes(static_cast<std::size_t>(size)); - file.seekg(0); - if (!file.read(bytes.data(), static_cast<std::streamsize>(bytes.size()))) - throw std::runtime_error(std::string("Could not read compute shader: ") + path); - return bytes; -} - // The image load uses a descriptor-table signature. Its case file appends the source texels. void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference) { - const auto code = read_texture_shader(path); + const auto code = read_compute_shader(path); const D3D12_SHADER_BYTECODE shader{code.data(), code.size()}; StoreCase store{}; std::ifstream source(reference, std::ios::binary); @@ -442,8 +463,13 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch const bool rgba8 = (store.groups & texture_rgba8_flag) != 0; const bool rgba32_float = (store.groups & texture_rgba32_float_flag) != 0; const bool view_mip1 = (store.groups & texture_view_mip1_flag) != 0; - store.groups &= ~(texture_rgba8_flag | texture_rgba32_float_flag | texture_view_mip1_flag); - const UINT base_words = texture_width * texture_height * (rgba8 ? 1 : texture_channels); + const bool mip_zero = (store.groups & texture_mip_zero_sampler_flag) != 0; + const bool comparison = (store.groups & texture_comparison_flag) != 0; + store.groups &= ~(texture_rgba8_flag | texture_rgba32_float_flag | texture_view_mip1_flag | + texture_mip_zero_sampler_flag | texture_comparison_flag); + const auto format = comparison ? DXGI_FORMAT_R32_FLOAT : rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT + : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; + const UINT base_words = texture_width * texture_height * texture_words_per_texel(format); std::vector<UINT> texels(base_words); source.read(reinterpret_cast<char*>(texels.data()), static_cast<std::streamsize>(texels.size() * sizeof(UINT))); // Older cases stop after the base image. A mip case appends levels one and two. @@ -454,11 +480,35 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch } if (!source || source.peek() != std::char_traits<char>::eof() || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || store.axis(2) > 5 || (rgba8 && rgba32_float) || + (comparison && (rgba8 || rgba32_float || mip_zero)) || (view_mip1 && texels.size() == base_words)) throw std::runtime_error("Invalid compute image load reference"); - const auto format = rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT - : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; - run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, &texels, format, + D3D12_SHADER_BYTECODE root{compute_tables, sizeof(compute_tables)}; + ComPtr<ID3DBlob> case_root; + if (comparison || mip_zero) { + ComPtr<ID3D12VersionedRootSignatureDeserializer> embedded; + check(D3D12CreateVersionedRootSignatureDeserializer(root.pShaderBytecode, root.BytecodeLength, + IID_PPV_ARGS(&embedded)), "Read embedded compute table signature"); + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* original = nullptr; + check(embedded->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &original), + "Get v1.1 compute table signature"); + auto desc = *original; + if (desc.Desc_1_1.NumStaticSamplers != 1) + throw std::runtime_error("Expected one static sampler in the compute table signature"); + auto sampler = desc.Desc_1_1.pStaticSamplers[0]; + if (comparison) { + sampler.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT; + sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_LESS; + } else { + sampler.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; + sampler.MaxLOD = 0; + } + desc.Desc_1_1.pStaticSamplers = &sampler; + check(D3D12SerializeVersionedRootSignature(&desc, &case_root, nullptr), "Serialize compute case signature"); + root = {case_root->GetBufferPointer(), case_root->GetBufferSize()}; + } + const auto program = create_compute_program(device, shader, root); + run_compute(device, true, program, false, &store, &texels, format, nullptr, false, false, view_mip1 ? 1 : 0); } @@ -540,12 +590,12 @@ bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, con source.read(reinterpret_cast<char*>(store.expected.data()), sizeof(store.expected)); if (!source || source.peek() != std::char_traits<char>::eof() || store.groups != 1) throw std::runtime_error("Invalid compute MSAA load reference"); - const auto code = read_texture_shader(path); - const auto vs = read_texture_shader(vs_path), ps = read_texture_shader(ps_path); + const auto code = read_compute_shader(path); + const auto vs = read_compute_shader(vs_path), ps = read_compute_shader(ps_path); auto texture = render_msaa_texture(device, {vs.data(), vs.size()}, {ps.data(), ps.size()}); if (!texture) return false; - run_compute(device, true, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}, - false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); + const auto program = create_compute_program(device, {code.data(), code.size()}, {compute_tables, sizeof(compute_tables)}); + run_compute(device, true, program, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, texture.Get()); return true; } @@ -650,7 +700,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co return false; } - const auto code = read_texture_shader(path); + const auto code = read_compute_shader(path); ComPtr<ID3D12RootSignature> signature; check(device->CreateRootSignature(0, compute_tables, sizeof(compute_tables), IID_PPV_ARGS(&signature)), "Create image store root signature"); @@ -761,6 +811,137 @@ void check_bvh_root_roundtrip(ID3D12Device* device) if (roundtrip->GetBufferSize() != control->GetBufferSize() || std::memcmp(roundtrip->GetBufferPointer(), control->GetBufferPointer(), control->GetBufferSize()) != 0) throw std::runtime_error("Normalized signature differs from independent control serialization"); - run_compute(device, false, shader, {roundtrip->GetBufferPointer(), roundtrip->GetBufferSize()}); + const auto program = create_compute_program(device, shader, {roundtrip->GetBufferPointer(), roundtrip->GetBufferSize()}); + run_compute(device, false, program); std::puts("normalized_signature=matched_control root_creation=passed pipeline_creation=passed dispatch=passed"); } + +int check_compute_waterfall_oracle(ID3D12Device* device, const char* shader_path) +{ + const auto code = read_compute_shader(shader_path); + ComPtr<ID3D12RootSignature> root; + check(device->CreateRootSignature(0, code.data(), code.size(), IID_PPV_ARGS(&root)), "Create waterfall oracle root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.Get(); + pso_desc.CS = {code.data(), code.size()}; + ComPtr<ID3D12PipelineState> pso; + check(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso)), "Create waterfall oracle pipeline"); + + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; + heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + heap_desc.NumDescriptors = 4; + heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "Create oracle descriptor heap"); + const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + const auto buf_desc = [](UINT64 size, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = size; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + d.Flags = flags; + return d; + }; + const auto write_upload = [](ID3D12Resource* res, const void* data, UINT sz) { + void* mapped = nullptr; + const D3D12_RANGE none{}; + check(res->Map(0, &none, &mapped), "Map upload buffer"); + std::memcpy(mapped, data, sz); + res->Unmap(0, nullptr); + }; + + std::array<ComPtr<ID3D12Resource>, 4> sources; + auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + for (UINT rec = 0; rec < 4; ++rec) { + const std::array<UINT, 4> data{ + 1000u * (rec + 1u), 1000u * (rec + 1u) + 17u, 1000u * (rec + 1u) + 34u, 1000u * (rec + 1u) + 51u}; + sources[rec] = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + write_upload(sources[rec].Get(), data.data(), 16); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 4; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(sources[rec].Get(), &srv, handle); + handle.ptr += inc; + } + + auto keys_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto init_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto out_res = resource(device, buf_desc(16, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + auto rb_res = resource(device, buf_desc(16), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + constexpr std::array<UINT, 4> sentinels{0xc001cafeu, 0xc001cafeu, 0xc001cafeu, 0xc001cafeu}; + write_upload(init_res.Get(), sentinels.data(), 16); + + D3D12_COMMAND_QUEUE_DESC qdesc{}; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> alloc; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + check(device->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&queue)), "Create oracle queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc)), "Create oracle alloc"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list)), + "Create oracle list"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "Create oracle fence"); + check(list->Close(), "Close initial list"); + + const std::array<std::array<UINT, 4>, 5> inputs{{{0, 1, 2, 3}, {3, 2, 1, 0}, {2, 1, 2, 3}, {4, 9, 14, 19}, {7, 7, 7, 7}}}; + UINT matches = 0, mismatches = 0; + UINT64 fence_value = 0; + const auto barrier = [&](D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {out_res.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); + }; + + for (const auto& row : inputs) { + write_upload(keys_res.Get(), row.data(), 16); + for (UINT active = 0; active <= 4; ++active) { + check(alloc->Reset(), "Reset oracle alloc"); + check(list->Reset(alloc.Get(), pso.Get()), "Reset oracle list"); + barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(out_res.Get(), 0, init_res.Get(), 0, 16); + barrier(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.Get()); + list->SetComputeRootShaderResourceView(0, keys_res->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(1, heap->GetGPUDescriptorHandleForHeapStart()); + list->SetComputeRootUnorderedAccessView(2, out_res->GetGPUVirtualAddress()); + list->SetComputeRoot32BitConstant(3, active, 0); + list->Dispatch(1, 1, 1); + barrier(D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(rb_res.Get(), 0, out_res.Get(), 0, 16); + barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + check(list->Close(), "Close oracle list"); + ID3D12CommandList* cmd = list.Get(); + queue->ExecuteCommandLists(1, &cmd); + check(queue->Signal(fence.Get(), ++fence_value), "Signal oracle fence"); + while (fence->GetCompletedValue() < fence_value) Sleep(1); + + void* mapped = nullptr; + const D3D12_RANGE range{0, 16}; + const D3D12_RANGE no_writes{}; + check(rb_res->Map(0, &range, &mapped), "Map oracle readback"); + std::array<UINT, 4> got{}; + std::memcpy(got.data(), mapped, 16); + rb_res->Unmap(0, &no_writes); + + std::array<UINT, 4> expected{}; + for (UINT lane = 0; lane < 4; ++lane) + expected[lane] = lane < active ? 1000u * ((row[lane] & 3u) + 1u) + 17u * lane : 13u; + if (got == expected) ++matches; + else ++mismatches; + } + } + std::printf("dispatches=25 matches=%u mismatches=%u\n", matches, mismatches); + return 0; +} diff --git a/tests/compute_heap_store_check.py b/tests/compute_heap_store_check.py index 21e8906b7e..a95a87913e 100644 --- a/tests/compute_heap_store_check.py +++ b/tests/compute_heap_store_check.py @@ -5,6 +5,7 @@ import sys import tempfile +from compute_load_format_check import check_references import compute_store_check as base @@ -211,10 +212,12 @@ def compile_shader(text): default_payload = 0x42000001 if mode == "d16_xyz" else D16_X_PAYLOADS[0][1] - def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expected_y=0x40400000, - expected_z=0x33800000): + def write_case(path, slot, payload=default_payload, expected_x=D16_X, table_words=table, + expected_y=0x40400000, expected_z=0x33800000, written_offsets=None): result = [base.SENTINEL] * WORDS - for thread, start in enumerate(cases[slot][2]): + if written_offsets is None: + written_offsets = cases[slot][2] + for thread, start in enumerate(written_offsets): if mode == "d16_x": result[start] = expected_x[thread] elif mode == "d16_xy": @@ -226,49 +229,39 @@ def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expe result[start:start + 4] = [D16_X[thread], 0xc0000000, 0x33800000, 0x80000000] else: result[start:start + 4] = [thread, 0x12345678, 0x80000001, 0x3F800001] - case = directory / "store.case" - case.write_bytes(struct.pack("<321I", 1, *result) + struct.pack("<16I", slot, payload, *([0] * 14)) + path.write_bytes(struct.pack("<321I", 1, *result) + struct.pack("<16I", slot, payload, *([0] * 14)) + struct.pack("<320I", *table_words)) - return subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) + + references = [] + + def add(label, slot, **values): + path = directory / f"store_{len(references)}.case" + write_case(path, slot, **values) + references.append((path, label, None)) compile_shader(source) for slot, (label, _, _) in enumerate(cases): - result = run(slot) - if result.returncode == 77 and backend == "hardware": - return 77 - assert result.returncode == 0, (mode, label, result.stderr) - extra = 0 + add(f"slot {slot} {label}", slot) if mode == "d16_x": for label, payload, want in D16_X_PAYLOADS[1:]: - result = run(0, payload=payload, expected_x=want) - assert result.returncode == 0, (label, result.stderr) - extra += 1 + add(label, 0, payload=payload, expected_x=want) # A FLOAT4 format word must be refused just like UINT1 by store_heap_word_d16. wrong_float4 = list(table) wrong_float4[TABLE_BYTE // 4 + 3] = FLOAT4 - case = directory / "store.case" - case.write_bytes(struct.pack("<321I", 1, *([base.SENTINEL] * WORDS)) + struct.pack("<16I", 0, D16_X_PAYLOADS[0][1], *([0] * 14)) - + struct.pack("<320I", *wrong_float4)) - result = subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) - assert result.returncode == 0, ("wrong FLOAT4 format", result.stderr) - extra += 1 + add("wrong FLOAT4 format", 0, table_words=wrong_float4, written_offsets=()) if mode == "d16_xy": for payload, expected_y in ((0x80003c00, 0x80000000), (0x00013c00, 0x33800000), (0xc0003c00, 0xc0000000)): - result = run(0, payload=payload, expected_y=expected_y) - assert result.returncode == 0, (hex(payload), result.stderr) - extra += 1 + add(f"payload {payload:#x}", 0, payload=payload, expected_y=expected_y) elif mode == "d16_xyz": for payload, z in ((0x7e010001, 0x33800000), (0x3c008000, 0x80000000), (0x4200c000, 0xc0000000)): - result = run(0, payload=payload, expected_z=z) - assert result.returncode == 0, (hex(payload), result.stderr) - extra += 1 + add(f"payload {payload:#x}", 0, payload=payload, expected_z=z) mismatched_formats = {"d16_xy": (FLOAT4, base.aot.descriptor_format_word(62)), "d16_xyz": (FLOAT2, FLOAT4)} for wrong_format in mismatched_formats.get(mode, ()): wrong_view = table.copy() wrong_view[TABLE_BYTE // 4 + 5 * 8 + 3] = wrong_format - result = run(5, table_words=wrong_view) - assert result.returncode == 0, (hex(wrong_format), result.stderr) - extra += 1 + add(f"wrong format {wrong_format:#x}", 5, table_words=wrong_view) + if check_references(f"heap-store {mode}", renderer, backend, cso, references, allow_skip=backend == "hardware") == 77: + return 77 width_str = {"d16_x": "4u", "d16_xy": "8u", "d16_xyz": "12u"}.get(mode, "16u") format_guard = {"d16_x": f"{FLOAT1:#x}u", "d16_xy": f"{FLOAT2:#x}u", "d16_xyz": f"{FLOAT3:#x}u"}.get(mode, "formatWord") @@ -315,14 +308,16 @@ def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expe for old, new, slot, *first_mismatch in mutations: assert source.count(old) == 1, old compile_shader(source.replace(old, new)) - result = run(slot) + case = directory / "mutated.case" + write_case(case, slot) + result = subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) assert result.returncode == 1 and "Compute readback differs" in result.stderr, (old, result.stderr) if first_mismatch: words = [line for line in result.stderr.splitlines() if line.startswith("word=")] assert words[:1] == first_mismatch, (old, result.stderr) kind = {"uint4": "UINT4", "d16_xyzw": "D16-to-FLOAT4", "d16_x": "D16_X-to-FLOAT1", "d16_xy": "D16_XY-to-FLOAT2", "d16_xyz": "D16_XYZ-to-FLOAT3"}[mode] - print(f"{backend} {kind}: {len(cases) + extra} heap-store cases and {len(mutations)} shader mutations checked") + print(f"{backend} {kind}: {len(references)} heap-store cases and {len(mutations)} shader mutations checked") return 0 diff --git a/tests/compute_heap_view_check.py b/tests/compute_heap_view_check.py index 6555ec6802..68156df832 100644 --- a/tests/compute_heap_view_check.py +++ b/tests/compute_heap_view_check.py @@ -259,58 +259,56 @@ def draw(directory, compiler, renderer, backend): src.write_text(lower(suffix), encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) shaders[suffix] = cso - case = directory / "heap.case" - dispatches = 0 + sources = {suffix: source_words(views) for suffix, views in SUFFIXES.items()} + cases = {suffix: [] for suffix in SUFFIXES} - def write(suffix, slot, groups, reference): - words = source_words(SUFFIXES[suffix]) + def write(case, suffix, slot, groups, reference): case.write_bytes(struct.pack("<321I", groups, *reference) + struct.pack("<16I", *constants(slot)) - + struct.pack("<320I", *words)) - return words + + struct.pack("<320I", *sources[suffix])) + + def add(suffix, slot, groups, reference, label, actual=None): + diagnostic = None + if actual is not None: + word = next((i for i, (a, b) in enumerate(zip(reference, actual)) if a != b), None) + if word is None: + raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") + diagnostic = f"word={word} expected={reference[word]:08x} actual={actual[word]:08x}" + path = directory / f"heap_{suffix}_{len(cases[suffix])}.case" + write(path, suffix, slot, groups, reference) + cases[suffix].append((path, f"{suffix} slot {slot} {label} (groups={groups})", diagnostic)) for suffix, views in SUFFIXES.items(): for slot in range(len(views) + 1): - words = source_words(views) - for groups in (1, 2): - write(suffix, slot, groups, expected_words(suffix, slot, groups, words)) - if subprocess.run([*cmd, shaders[suffix], case]).returncode: - return 1 - dispatches += 1 label = views[slot]["label"] if slot < len(views) else "no record" - print(f"{NAME}: {suffix} slot {slot} {'refused' if slot in REFUSED[suffix] or slot >= len(views) else 'read'}" - f" ({label})", flush=True) + action = "refused" if slot in REFUSED[suffix] or slot >= len(views) else "read" + for groups in (1, 2): + add(suffix, slot, groups, expected_words(suffix, slot, groups, sources[suffix]), f"{action} ({label})") + dispatches = sum(map(len, cases.values())) # A refusal must stay distinguishable from a published zero read: zeros against a refused slot must fail. for suffix, slot in (("xy", 4), ("xy", 10), ("xy", 11), ("xyzw", 3)): - words = source_words(SUFFIXES[suffix]) - zeros = [0] * WORDS - write(suffix, slot, 2, zeros) - bad = subprocess.run([*cmd, shaders[suffix], case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: zeros published for {suffix} slot {slot} escaped detection\n{bad.stderr}") + add(suffix, slot, 2, [0] * WORDS, "zeros published", expected_words(suffix, slot, 2, sources[suffix])) for label, wrong, (suffix, slot) in WRONG: - words = source_words(SUFFIXES[suffix]) + words = sources[suffix] good = expected_words(suffix, slot, 2, words) wrong_words = expected_words(suffix, slot, 2, words, wrong=wrong) - if good == wrong_words: - raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - write(suffix, slot, 2, wrong_words) - bad = subprocess.run([*cmd, shaders[suffix], case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{bad.stderr}") + add(suffix, slot, 2, wrong_words, label, good) + for suffix, references in cases.items(): + fmt.check_references(NAME, renderer, backend, shaders[suffix], references) + wrong_count = sum(map(len, cases.values())) - dispatches original = {suffix: lower(suffix) for suffix in SUFFIXES} + case = directory / "mutated.case" for label, old, new, (suffix, slot) in MUTATIONS: mutated = original[suffix].replace(old, new, 1) if mutated == original[suffix]: raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - words = source_words(SUFFIXES[suffix]) - write(suffix, slot, 2, expected_words(suffix, slot, 2, words)) + write(case, suffix, slot, 2, expected_words(suffix, slot, 2, sources[suffix])) bad_src, bad_cso = directory / "mutated.hlsl", directory / "mutated.cso" bad_src.write_text(mutated, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", bad_cso, bad_src], check=True) bad = subprocess.run([*cmd, bad_cso, case], capture_output=True, text=True) if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{bad.stderr}") - print(f"{NAME}: {dispatches} dispatches, {3 + len(WRONG)} wrong references and " + print(f"{NAME}: {dispatches} dispatches, {wrong_count} wrong references and " f"{len(MUTATIONS)} mutated sources checked") return 0 diff --git a/tests/compute_image_atomics_gfx1013_check.py b/tests/compute_image_atomics_gfx1013_check.py index aee7656f7e..da7fca6a15 100644 --- a/tests/compute_image_atomics_gfx1013_check.py +++ b/tests/compute_image_atomics_gfx1013_check.py @@ -1,10 +1,11 @@ -"""Check gfx1013 image_atomic_add, umax and cmpswap on a 2D R32_UINT UAV. +"""Check gfx1013 image_atomic_add, umin, umax and cmpswap on a 2D R32_UINT UAV (M200-01 A). -gfx1013 takes the gfx1030 image atomic lowering for these three operations. The cases are the +gfx1013 takes the gfx1030 image atomic lowering for these four operations. The cases are the gfx1030 ones (tests/compute_store_check.py, mimg_atomic_cases) with the gfx1013 profile: the controls pin identical HLSL, the gfx1013 refusals and, with --binary, the gfx1013 machine words; --draw dispatches them on an adapter and compares every texel of a three-level texture with an -independent reference, including mutants that must mismatch. +independent reference, including mutants that must mismatch. The minmax operand is 0x80000011 so +unsigned umin/umax ordering differs from signed smin/smax on several texels. """ import argparse import os @@ -20,11 +21,12 @@ mimg_atomic_cases, mimg_atomic_reference, rejects, store_container, variant) HERE = Path(__file__).resolve().parent -ACCEPTED = ("add", "umax", "cmpswap") -SUITES = {"add": "integer", "umax": "minmax", "cmpswap": "exchange"} -FLAGS = {"add": MIMG_ATOMIC_UINT_FLAG, "umax": MIMG_ATOMIC_MINMAX_FLAGS["u"], "cmpswap": MIMG_ATOMIC_EXCHANGE_FLAG} +ACCEPTED = ("add", "umin", "umax", "cmpswap") +SUITES = {"add": "integer", "umin": "minmax", "umax": "minmax", "cmpswap": "exchange"} +FLAGS = {"add": MIMG_ATOMIC_UINT_FLAG, "umin": MIMG_ATOMIC_MINMAX_FLAGS["u"], + "umax": MIMG_ATOMIC_MINMAX_FLAGS["u"], "cmpswap": MIMG_ATOMIC_EXCHANGE_FLAG} # Every other integer image atomic the shared lowering knows, refused on gfx1013. -REFUSED_UINT = ("sub", "and", "or", "xor", "umin", "swap", "inc", "dec") +REFUSED_UINT = ("sub", "and", "or", "xor", "swap", "inc", "dec") def cases(): @@ -34,7 +36,7 @@ def cases(): for name, contended, lines, binding in mimg_atomic_cases(suite=SUITES[op]): if name.removesuffix("_contended") == op: found.append((name, op, contended, lines, binding | {"cpu": "gfx1013"})) - assert [name for name, *_ in found] == ["add", "add_contended", "umax", "cmpswap"], found + assert [name for name, *_ in found] == ["add", "add_contended", "umin", "umax", "cmpswap"], found return found @@ -52,23 +54,31 @@ def controls(): sources[name] = source value = f"{MIMG_ATOMIC_VALUE:#010x}u" assert f"InterlockedAdd(outputData[uint2(" in sources["add"] and f", {value});" in sources["add"] + assert "InterlockedMin(outputData[uint2(" in sources["umin"] and f", {value});" in sources["umin"] + assert "asint(" not in sources["umin"], "umin must stay unsigned" assert "InterlockedMax(outputData[uint2(" in sources["umax"] and f", {value});" in sources["umax"] assert "asint(" not in sources["umax"], "umax must stay unsigned" assert (f", {MIMG_ATOMIC_COMPARE:#010x}u, {MIMG_ATOMIC_REPLACEMENT:#010x}u);" in sources["cmpswap"] and sources["cmpswap"].count("InterlockedCompareStore(") == 1), sources["cmpswap"] + # High-bit unsigned ordering: the minmax operand has bit 31 set, so umin and smin differ. + assert MIMG_ATOMIC_VALUE >= 0x80000000 + _, umin_exp = mimg_atomic_reference("umin", False, 1) + _, smin_exp = mimg_atomic_reference("smin", False, 1) + assert umin_exp != smin_exp and sum(a != b for a, b in zip(umin_exp, smin_exp)) >= 1 + print("umin high-bit ordering differs from smin on the reference texture", flush=True) name, op, _, lines, binding = cases()[0] instruction = next(line for line in lines if line.startswith("image_atomic_")) for other in REFUSED_UINT: - rejects("gfx1013 image atomics require add, umax or cmpswap", lowered, + rejects("gfx1013 image atomics require add, umin, umax or cmpswap", lowered, variant(lines, ("image_atomic_add", f"image_atomic_{other}")), binding) # Signed and float formats are refused on gfx1013 before any instruction is read. - umax_lines, umax_binding = cases()[2][3], cases()[2][4] + umin_lines, umin_binding = next((lines, binding) for name, op, _, lines, binding in cases() if op == "umin") for change in ({"image_format": "R32_SINT"}, {"image_format": "R32_FLOAT", "image_float_domain": "finite-normal"}, {"image_uav_mip": 1}): - rejects("Invalid image UAV binding", lowered, umax_lines, umax_binding | change) - smin = variant(umax_lines, ("image_atomic_umax", "image_atomic_smin")) - rejects("Invalid image UAV binding", lowered, smin, umax_binding | {"image_format": "R32_SINT"}) + rejects("Invalid image UAV binding", lowered, umin_lines, umin_binding | change) + smin = variant(umin_lines, ("image_atomic_umin", "image_atomic_smin")) + rejects("Invalid image UAV binding", lowered, smin, umin_binding | {"image_format": "R32_SINT"}) for changed, diagnostic in ( (instruction + "\n" + instruction, "Unsupported image atomic target or binding"), (instruction.replace("IMG_2D", "IMG_2D_ARRAY"), "Unsupported compute instruction"), @@ -87,10 +97,10 @@ def controls(): return sources -# The two MIMG dwords of each atomic as LLVM 15 encodes them for gfx1013: opcode 17 (add), 23 (umax) -# or 16 (cmpswap) in bits 24:18, dmask in 11:8, unorm in bit 12, dim 1 (2D) in bits 5:3. +# The two MIMG dwords of each atomic as LLVM 15 encodes them for gfx1013: opcode 17 (add), 21 (umin), +# 23 (umax) or 16 (cmpswap) in bits 24:18, dmask in 11:8, unorm in bit 12, dim 1 (2D) in bits 5:3. ATOMIC_WORDS = {"add": "080144f0080e0600", "add_contended": "081144f0080e0600", - "umax": "08015cf0080e0600", "cmpswap": "081340f0080e0600"} + "umin": "080154f0080e0600", "umax": "08015cf0080e0600", "cmpswap": "081340f0080e0600"} def binary(directory, assembler, objcopy, library, sources): @@ -120,6 +130,9 @@ def mutants(op, source): if op == "add": assert source.count(f", {value});") == 1 return "subtracts instead of adds", source.replace(f", {value});", f", (0u - {value}));"), ("sub", None) + if op == "umin": + assert source.count("InterlockedMin(") == 1 + return "maximum instead of minimum", source.replace("InterlockedMin(", "InterlockedMax("), ("umax", None) if op == "umax": assert source.count("InterlockedMax(") == 1 return "minimum instead of maximum", source.replace("InterlockedMax(", "InterlockedMin("), ("umin", None) diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index bdaa9eca30..576b9cf1a0 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -2,11 +2,13 @@ The t0 format is V# word 3, read from a constant word at run time (--load-format-constant), as the descriptor-format stores read theirs. The case file supplies the t0 words, so each format sees chosen edge values. +Two suites share the t0 layout: binary32 results (draw) and d16 results packed two per word (draw-d16). """ from concurrent.futures import ThreadPoolExecutor from fractions import Fraction import os from pathlib import Path +import re import struct import subprocess import sys @@ -20,6 +22,7 @@ GROUP = (4, 1, 1) SOURCE_STRIDE = 80 OUTPUT_STRIDE = 120 +D16_STRIDE = 64 THREADS = 8 # opcode suffix, t0 byte offset, GFX10 format code, legacy word 3, u0 byte offset of the results. LOADS = ( @@ -38,7 +41,20 @@ ("x", 68, 20, False, 108), # 32_UINT ("xy", 72, 64, False, 112), # 32_32_FLOAT ) -# Format words that make one load invalid: load index, V# word 3. Each must leave every u0 word unwritten. +# The same t0 fields through the d16 opcodes. Every format with a d16 rule appears once. +D16_LOADS = ( + ("d16_xyzw", 0, 56, False, 0), # 8_8_8_8_UNORM + ("d16_xy", 4, 23, False, 8), # 16_16_UNORM + ("d16_xyzw", 8, 50, False, 12), # 2_10_10_10_UNORM + ("d16_xy", 12, 29, True, 20), # 16_16_FLOAT, legacy + ("d16_xyzw", 16, 71, False, 24), # 16_16_16_16_FLOAT + ("d16_x", 24, 7, False, 32), # 16_UNORM + ("d16_x", 28, 8, False, 36), # 16_SNORM + ("d16_x", 32, 11, False, 40), # 16_UINT + ("d16_x", 36, 12, False, 44), # 16_SINT + ("d16_x", 40, 13, False, 48), # 16_FLOAT +) +# Format words that make one load invalid: label, load index, V# word 3. Each must leave every u0 word unwritten. IDENTITY_32_UINT = aot.descriptor_format_word(20) INVALID = ( ("unknown format 8_SNORM", 0, aot.DESCRIPTOR_GFX10_FIXED | (2 << 12)), @@ -48,6 +64,11 @@ # 10_10_10_2_UNORM has a 2-bit x in bits 1:0; only the 2_10_10_10 layout is handled. ("10_10_10_2_UNORM", 2, aot.DESCRIPTOR_GFX10_FIXED | (44 << 12)), ) +D16_INVALID = ( + ("d16_xy on 32_32_FLOAT", 1, aot.descriptor_format_word(64)), + ("d16_x on 16_16_UNORM", 5, aot.descriptor_format_word(23)), + ("unknown format 8_SNORM", 0, aot.DESCRIPTOR_GFX10_FIXED | (2 << 12)), +) # Thread 0-3 t0 words: edge values per field. Threads 4-7 are pseudo-random. CURATED = ( (0x8001ff00, 0x0001ffff, 0xa00007ff, 0x80000001, 0xfc007c00, 0x7bff7e01, 0xdeadffff, 0x12348000, 0xabcdffff, @@ -78,6 +99,15 @@ def source_words(): return words + [base.SENTINEL] * (320 - len(words)) +def _exponent(value): + exponent = value.numerator.bit_length() - value.denominator.bit_length() + while value >= Fraction(2) ** exponent * 2: + exponent += 1 + while value < Fraction(2) ** exponent: + exponent -= 1 + return exponent + + def f32_bits(value): """binary32 bits of a Fraction or exact value, rounded to nearest even (no double rounding).""" value = Fraction(value) @@ -85,11 +115,7 @@ def f32_bits(value): return 0 sign = 0x80000000 if value < 0 else 0 value = abs(value) - exponent = value.numerator.bit_length() - value.denominator.bit_length() - while value >= Fraction(2) ** exponent * 2: - exponent += 1 - while value < Fraction(2) ** exponent: - exponent -= 1 + exponent = _exponent(value) assert -126 <= exponent < 128, value mantissa = round(value / Fraction(2) ** (exponent - 23)) if mantissa == 1 << 24: @@ -97,6 +123,25 @@ def f32_bits(value): return sign | ((exponent + 127) << 23) | (mantissa - (1 << 23)) +def f16_bits(value, *, truncate=False, flush=False): + """binary16 bits of a Fraction in [-1, 1], rounded to nearest even, denormals kept (IEEE 754 rounding).""" + value = Fraction(value) + if value == 0: + return 0 + sign = 0x8000 if value < 0 else 0 + value = abs(value) + exponent = _exponent(value) + rounding = (lambda q: int(q)) if truncate else round + if exponent < -14: + if flush: + return sign + return sign | rounding(value / Fraction(2) ** -24) # a carry to 0x400 is the smallest normal + mantissa = rounding(value / Fraction(2) ** (exponent - 10)) + if mantissa == 1 << 11: + mantissa, exponent = 1 << 10, exponent + 1 + return sign | ((exponent + 15) << 10) | (mantissa - (1 << 10)) + + def half_to_f32(half): """IEEE 754 widening of binary16: exact for numbers; a NaN keeps its payload (IEEE 754-2008 6.2.3).""" sign, exponent, mantissa = (half >> 15) & 1, (half >> 10) & 31, half & 0x3ff @@ -125,7 +170,7 @@ def snorm16(half, *, clamp=True): def load(code, words, channels, *, wrong=()): - """Independent reference for one load: the definition of each format, from the t0 words at its offset. + """Independent reference for one binary32 load: the definition of each format, from the t0 words at its offset. The profile handles an opcode that reads exactly the format's channels; anything else is a refusal. """ @@ -161,31 +206,82 @@ def load(code, words, channels, *, wrong=()): return result[:channels] -def expected_words(groups, *, wrong=(), source=None, placeholder=None): - """u0 after a valid dispatch. placeholder=(load index, words) publishes those words for that load instead.""" - source = source or source_words() - words = [base.SENTINEL] * 320 - for thread in range(GROUP[0] * groups): - index = thread + 1 if "neighbour element" in wrong else thread - element = source[index * SOURCE_STRIDE // 4:(index + 1) * SOURCE_STRIDE // 4] - for number, (suffix, src, code, legacy, dst) in enumerate(LOADS): - if placeholder and placeholder[0] == number: - values = placeholder[1](element[src // 4:]) - elif legacy and "legacy ignored" in wrong: - values = [0] * len(suffix) - else: - values = load(code, element[src // 4:], len(suffix), wrong=wrong) - start = (thread * OUTPUT_STRIDE + dst) // 4 - words[start:start + len(values)] = values - return words - +def load_d16(code, words, channels, *, wrong=()): + """Independent reference for one d16 load: binary16 for float-type formats, the 16-bit integer for UINT and + SINT, packed two per word with x low. An odd final half is stored masked to its low 16 bits.""" + _code, kind, format_channels = aot.decode_buffer_descriptor_format(aot.descriptor_format_word(code)) + assert channels == format_channels and kind != "raw32", (code, channels) + w = words[0] + rounding = dict(truncate="half truncated" in wrong, flush="flush halves" in wrong) -def constants(): - words = [aot.descriptor_format_word(code, legacy=legacy) for _s, _o, code, legacy, _d in LOADS] - return words + [0] * (16 - len(words)) + def ratio(x, d): + return f16_bits(Fraction(x, d), **rounding) + def snorm(h): + value = h - 0x10000 if h & 0x8000 else h + return 0xbc00 if value <= -32767 else f16_bits(Fraction(value, 32767), **rounding) -def program(): + if kind == "unorm8": + halves = [ratio((w >> (8 * i)) & 0xff, 255) for i in range(4)] + elif kind == "unorm16x2": + halves = [ratio(w & 0xffff, 65535), ratio(w >> 16, 65535)] + elif kind == "unorm10": + halves = [ratio((w >> (10 * i)) & 0x3ff, 1023) for i in range(3)] + [ratio(w >> 30, 3)] + elif kind == "f16x2": + halves = [w & 0xffff, w >> 16] + elif kind == "f16x4": + halves = [w & 0xffff, w >> 16, words[1] & 0xffff, words[1] >> 16] + elif kind == "unorm16": + halves = [ratio(w & 0xffff, 65535)] + elif kind == "snorm16": + halves = [snorm(w & 0xffff)] + elif kind == "uint16": + halves = [ratio(w & 0xffff, 65535) if "integer as unorm" in wrong else w & 0xffff] + elif kind == "sint16": + halves = [snorm(w & 0xffff) if "integer as snorm" in wrong else w & 0xffff] + else: + halves = [w & 0xffff] + if "pack high first" in wrong: + halves = [h for pair in zip(halves[1::2], halves[0::2]) for h in pair] + halves[len(halves) & ~1:] + return [halves[i] | ((halves[i + 1] if i + 1 < len(halves) else 0) << 16) for i in range(0, len(halves), 2)] + + +class Suite: + def __init__(self, name, loads, stride, model, invalid, wrong, mutations): + self.name, self.loads, self.stride, self.model = name, loads, stride, model + self.invalid, self.wrong, self.mutations = invalid, wrong, mutations + self.lines, self.binding = program(loads, stride) + + def expected(self, groups, *, wrong=(), placeholder=None): + """u0 after a valid dispatch. placeholder=(load index, function) publishes other words for that load.""" + source = source_words() + words = [base.SENTINEL] * 320 + for thread in range(GROUP[0] * groups): + index = thread + 1 if "neighbour element" in wrong else thread + element = source[index * SOURCE_STRIDE // 4:(index + 1) * SOURCE_STRIDE // 4] + for number, (suffix, src, code, legacy, dst) in enumerate(self.loads): + channels = len(suffix.removeprefix("d16_")) + if placeholder and placeholder[0] == number: + values = placeholder[1](element[src // 4:]) + elif legacy and "legacy ignored" in wrong: + values = [0] * registers(suffix) + else: + values = self.model(code, element[src // 4:], channels, wrong=wrong) + start = (thread * self.stride + dst) // 4 + words[start:start + len(values)] = values + return words + + def constants(self): + words = [aot.descriptor_format_word(code, legacy=legacy) for _s, _o, code, legacy, _d in self.loads] + return words + [0] * (16 - len(words)) + + +def registers(suffix): + channels = len(suffix.removeprefix("d16_")) + return (channels + 1) // 2 if suffix.startswith("d16_") else channels + + +def program(loads, stride): lines = [ "s_mov_b32 s12, s7", "s_mov_b32 s13, 0", "s_load_dwordx4 s[20:23], s[12:13], 0x30", @@ -199,36 +295,35 @@ def program(): "s_buffer_load_dwordx2 s[36:37], s[16:19], 0x30", "s_waitcnt lgkmcnt(0)", ] - reg, stores = 10, [] - for suffix, src, _code, _legacy, dst in LOADS: - n = len(suffix) + reg, masks, stores = 10, [], [] + for suffix, src, _code, _legacy, dst in loads: + n = registers(suffix) regs = f"v{reg}" if n == 1 else f"v[{reg}:{reg + n - 1}]" lines.append(f"buffer_load_format_{suffix} {regs}, v8, s[40:43], 0 idxen" + (f" offset:{src}" if src else "")) + if suffix.startswith("d16_") and len(suffix) % 2: + # An odd d16 count leaves the high half of the last word undefined; keep only the low half. + last = reg + n - 1 + masks.append(f"v_and_b32_e32 v{last}, 0xffff, v{last}") width = "" if n == 1 else f"x{n}" stores.append(f"buffer_store_dword{width} {regs}, v8, s[20:23], 0 idxen" + (f" offset:{dst}" if dst else "")) reg += n - lines += ["s_waitcnt vmcnt(0)", *stores, "s_endpgm"] + lines += ["s_waitcnt vmcnt(0)", *masks, *stores, "s_endpgm"] binding = dict(table_reg=7, descriptor_offset=0x30, constant_descriptor=0x40, source_descriptor=0x50, - source_stride=SOURCE_STRIDE, group_reg=11, stride=OUTPUT_STRIDE, cpu="gfx1013", - load_format_constant=tuple(range(len(LOADS)))) + source_stride=SOURCE_STRIDE, group_reg=11, stride=stride, cpu="gfx1013", + load_format_constant=tuple(range(len(loads)))) return lines, binding -LINES, BINDING = program() -FIRST_LOAD = (" bool format_valid_0;\n" - " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, format_valid_0);") -FIRST_STORE = (" outputData.Store4(tid.x * 120u + 0u, uint4(format_load_0.x, format_load_0.y, format_load_0.z, " - "format_load_0.w));") -LAST_LOAD = " uint4 format_load_13 = load_descriptor_format(params[3].y, tid.x * 80u + 72u, 2u, format_valid_13);" -REFUSE = " if (!(" + " && ".join(f"format_valid_{i}" for i in range(len(LOADS))) + ")) return;" -WRONG = (("UNORM divided by 2^n", ("unorm divisor",)), ("UNORM truncated", ("unorm truncated",)), - ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), - ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), - ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))) # Independent launches (the mutation ones also compile a mutated source); the Win2025 slots have 11 vCPUs. LAUNCH_THREADS = 6 FIXED = f"{aot.DESCRIPTOR_LEGACY_FIXED:#x}u" -# label, old, new, and the run it must fail: None for the valid two-group run, else an INVALID index. + + +def refuse_line(count): + return " if (!(" + " && ".join(f"format_valid_{i}" for i in range(count)) + ")) return;" + + +# label, old, new, and the run it must fail: None for the valid two-group run, else an invalid-run index. MUTATIONS = ( ("ratio never rounds up", " if ((bits & 1u) != 0u && (r != 0u || (result & 1u) != 0u)) ++result;\n", "", None), ("denormal halves flushed", " if (m == 0u) return sign;\n", " return sign;\n", None), @@ -238,166 +333,254 @@ def program(): ("SINT16 zero-extended", "(uint)((int)(raw.x << 16u) >> 16u)", "(raw.x & 0xffffu)", None), ("legacy fixed bits ignored", f"}} else if (fixedBits == {FIXED}) {{", "} else if (false) {", None), ("format word from params[0].y", "load_descriptor_format(params[0].x,", "load_descriptor_format(params[0].y,", None), - ("invalid loads still store", REFUSE, "", 0), + ("invalid loads still store", refuse_line(len(LOADS)), "", 0), ("narrower opcode accepted", "format == 77u) && channels == 4u)", "format == 77u) && channels <= 4u)", 1), ("wider opcode accepted", "format == 22u) && channels == 1u)", "format == 22u) && channels >= 1u)", 2), ("selectors ignored", f"uint fixedBits = formatWord & {aot.DESCRIPTOR_FIXED_MASK:#x}u;", f"uint fixedBits = formatWord & {aot.DESCRIPTOR_FIXED_MASK & ~0xfff:#x}u | 0xfacu;", 3), ) +D16_MUTATIONS = ( + ("binary16 ratio never rounds up", + " if (roundBit != 0u && (sticky || (result & 1u) != 0u)) ++result;\n", "", None), + ("binary16 denormals flushed", " : (f >> shift);\n", " : 0u;\n", None), + ("16_UINT converted like 16_UNORM", "(format == 11u) && channels == 1u) { h.x = raw.x & 0xffffu;", + "(format == 11u) && channels == 1u) { h.x = descriptor_ratio16(raw.x & 0xffffu, 65535u);", None), + ("16_SINT converted like 16_SNORM", "(format == 12u) && channels == 1u) { h.x = raw.x & 0xffffu;", + "(format == 12u) && channels == 1u) { h.x = descriptor_snorm16_half(raw.x & 0xffffu);", None), + ("halves packed high first", "r = uint4(h.x | (h.y << 16u), h.z | (h.w << 16u), 0u, 0u);", + "r = uint4(h.y | (h.x << 16u), h.w | (h.z << 16u), 0u, 0u);", None), + ("SNORM16 half sign dropped", "0x8000u | descriptor_ratio16(", "descriptor_ratio16(", None), + ("binary32 conversion under d16", "(d16 != 0u && (format == 23u)", "(d16 == 0u && (format == 23u)", None), + ("32-bit format accepted under d16", "(d16 == 0u && (format == 62u || format == 64u) && channels == 2u)", + "(true && (format == 62u || format == 64u) && channels == 2u)", 0), + ("invalid loads still store", refuse_line(len(D16_LOADS)), "", 2), +) +SUITES = { + "draw": Suite(NAME, LOADS, OUTPUT_STRIDE, load, INVALID, ( + ("UNORM divided by 2^n", ("unorm divisor",)), ("UNORM truncated", ("unorm truncated",)), + ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), + ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), + ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))), + MUTATIONS), + "draw-d16": Suite(NAME + "_d16", D16_LOADS, D16_STRIDE, load_d16, D16_INVALID, ( + ("binary16 truncated", ("half truncated",)), ("binary16 denormals flushed", ("flush halves",)), + ("16_UINT converted like 16_UNORM", ("integer as unorm",)), + ("16_SINT converted like 16_SNORM", ("integer as snorm",)), + ("halves packed high first", ("pack high first",)), ("legacy format ignored", ("legacy ignored",)), + ("neighbouring element", ("neighbour element",))), + D16_MUTATIONS), +} +LINES, BINDING = SUITES["draw"].lines, SUITES["draw"].binding +D16_LINES, D16_BINDING = SUITES["draw-d16"].lines, SUITES["draw-d16"].binding +FIRST_LOAD = (" bool format_valid_0;\n" + " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, 0u, format_valid_0);") +FIRST_STORE = (" outputData.Store4(tid.x * 120u + 0u, uint4(format_load_0.x, format_load_0.y, format_load_0.z, " + "format_load_0.w));") +LAST_LOAD = (" uint4 format_load_13 = load_descriptor_format(params[3].y, tid.x * 80u + 72u, 2u, 0u, " + "format_valid_13);") +D16_FIRST_LOAD = " uint4 format_load_0 = load_descriptor_format(params[0].x, tid.x * 80u + 0u, 4u, 1u, format_valid_0);" +D16_ODD_STORE = " outputData.Store(tid.x * 64u + 32u, (format_load_5.x & 0xffffu));" def lower(lines=None, **binding): return aot.lower(LINES if lines is None else lines, GROUP, **(BINDING | binding)) +def lower_d16(lines=None, **binding): + return aot.lower(D16_LINES if lines is None else lines, GROUP, **(D16_BINDING | binding)) + + def controls(): """Exact staged loads and stores, model checks, then one rejection per form outside the profile.""" assert f32_bits(Fraction(1, 255)) == 0x3b808081 and f32_bits(Fraction(128, 255)) == 0x3f008081 assert unorm(1, 16) == 0x37800080 and unorm(2, 2) == 0x3f2aaaab and snorm16(0x8000) == 0xbf800000 assert snorm16(0x8000, clamp=False) == 0xbf800100 and snorm16(0xffff) == 0xb8000100 assert half_to_f32(0x0001) == 0x33800000 and half_to_f32(0x03ff) == 0x387fc000 and half_to_f32(0x7e01) == 0x7fc02000 + # binary16: 100/1023 rounds up, 1/65535 and -1/32767 are denormals, and 1/3 rounds down. + assert f16_bits(Fraction(1, 255)) == 0x1c04 and f16_bits(Fraction(128, 255)) == 0x3804 + assert f16_bits(Fraction(1, 65535)) == 0x0100 and f16_bits(Fraction(1, 3)) == 0x3555 + assert f16_bits(Fraction(100, 1023)) == 0x2e42 and f16_bits(Fraction(100, 1023), truncate=True) == 0x2e41 + assert f16_bits(Fraction(-1, 32767)) == 0x8200 and f16_bits(Fraction(1, 65535), flush=True) == 0 source = lower() lines = source.splitlines() + refuse = refuse_line(len(LOADS)) assert source.count("= load_descriptor_format(") == len(LOADS) - assert FIRST_LOAD in source and LAST_LOAD in lines and FIRST_STORE in lines and REFUSE in lines, source + assert FIRST_LOAD in source and LAST_LOAD in lines and FIRST_STORE in lines and refuse in lines, source assert "outputData.Store(tid.x * 120u + 108u, format_load_12.x);" in source assert "outputData.Store2(tid.x * 120u + 112u, uint2(format_load_13.x, format_load_13.y));" in source # Every load and the refusal come before the first store. - assert lines.index(LAST_LOAD) < lines.index(REFUSE) < lines.index(FIRST_STORE) + assert lines.index(LAST_LOAD) < lines.index(refuse) < lines.index(FIRST_STORE) assert "&& channels == 4u) {" in source and "channels <=" not in source and "valid = false;" in source # Without the load constants the profile keeps the gfx1030 caller-format path and refuses gfx1013. base.rejects("Unsupported formatted buffer read target or address mode", lower, load_format_constant=None) for _name, old_lines, old_binding in base.mubuf_format_cases(): old = aot.lower(old_lines, 32, **old_binding) assert "load_descriptor_format(" not in old and "inputData.Load" in old and " return;" not in old + # d16: the flag reaches the helper, the odd final half is masked before a whole-word store, and no 32-bit + # format has a d16 arm. + d16 = lower_d16() + assert D16_FIRST_LOAD in d16 and D16_ODD_STORE in d16 and refuse_line(len(D16_LOADS)) in d16, d16 + assert "outputData.Store2(tid.x * 64u + 0u, uint2(format_load_0.x, format_load_0.y));" in d16 + assert "(d16 != 0u && (format == 20u" not in d16 and "(d16 != 0u && (format == 56u)" in d16 xyzw = LINES[12] assert xyzw == "buffer_load_format_xyzw v[10:13], v8, s[40:43], 0 idxen", xyzw + d16x = D16_LINES[17] + assert d16x == "buffer_load_format_d16_x v18, v8, s[40:43], 0 idxen offset:24", d16x + mask = "v_and_b32_e32 v18, 0xffff, v18" wait = LINES.index("s_waitcnt lgkmcnt(0)", 7) - for message, lines_, binding in ( - ("Descriptor-format d16 loads are not lowered", - base.variant(LINES, (xyzw, "buffer_load_format_d16_xyzw v[10:11], v8, s[40:43], 0 idxen")), {}), - ("Descriptor-format d16 loads are not lowered", - base.variant(LINES, (xyzw, "buffer_load_format_d16_x v10, v8, s[40:43], 0 idxen")), {}), - ("Unsupported formatted buffer read target or address mode", + for message, function, lines_, binding in ( + # The odd d16 half is low-16 only: stored or used without the mask, it is not a known word. + ("Store data is not a known word", lower_d16, base.variant(D16_LINES, (mask, "")), {}), + ("Unverified ALU operand", lower_d16, base.variant(D16_LINES, (mask, "v_xor_b32_e32 v18, 1, v18")), {}), + ("Unverified buffer read destination", lower_d16, base.variant(D16_LINES, (d16x, d16x.replace("v18,", "v[18:19],"))), {}), + ("Unsupported formatted buffer read target or address mode", lower, base.variant(LINES, (xyzw, xyzw.replace(" idxen", " offen"))), {}), - ("Unsupported formatted buffer read target or address mode", + ("Unsupported formatted buffer read target or address mode", lower, base.variant(LINES, (xyzw, xyzw.replace(" idxen", ""))), {}), - ("Unverified read offset", base.variant(LINES, (xyzw, xyzw + " offset:2")), {}), - ("Read leaves its source element", base.variant(LINES, (xyzw, xyzw + " offset:68")), {}), - ("Unsupported compute instruction", base.variant(LINES, (xyzw, xyzw + " glc")), {}), - ("Formatted buffer load is missing a format constant", None, dict(load_format_constant=(0,))), - ("Unused buffer load format constant", None, dict(load_format_constant=tuple(range(len(LOADS) + 1)))), - ("Formatted buffer load format constant is not ready", None, + ("Unverified read offset", lower, base.variant(LINES, (xyzw, xyzw + " offset:2")), {}), + ("Read leaves its source element", lower, base.variant(LINES, (xyzw, xyzw + " offset:68")), {}), + ("Unsupported compute instruction", lower, base.variant(LINES, (xyzw, xyzw + " glc")), {}), + ("Formatted buffer load is missing a format constant", lower, None, dict(load_format_constant=(0,))), + ("Unused buffer load format constant", lower, None, dict(load_format_constant=tuple(range(len(LOADS) + 1)))), + ("Formatted buffer load format constant is not ready", lower, None, dict(load_format_constant=(15,) + BINDING["load_format_constant"][1:])), - ("Formatted buffer load format constant is not ready", LINES[:wait] + LINES[wait + 1:], {}), - ("Invalid buffer load format constant", None, dict(cpu="gfx1030")), - ("Unsupported formatted source binding", None, dict(source_format="BUF_FMT_32_32_32_32_UINT")), - ("Invalid buffer load format constant", None, dict(cpu="gfx1030", source_format="BUF_FMT_32_32_32_32_UINT")), - ("Invalid buffer load format constant", None, dict(load_format_constant=(16,))), - ("Invalid buffer load format constant", None, dict(load_format_constant=())), - ("Invalid buffer load format constant", None, dict(constant_descriptor=None)), - ("Invalid buffer load format constant", None, dict(source_stride=None)), + ("Formatted buffer load format constant is not ready", lower, LINES[:wait] + LINES[wait + 1:], {}), + ("Invalid buffer load format constant", lower, None, dict(cpu="gfx1030")), + ("Unsupported formatted source binding", lower, None, dict(source_format="BUF_FMT_32_32_32_32_UINT")), + ("Invalid buffer load format constant", lower, None, + dict(cpu="gfx1030", source_format="BUF_FMT_32_32_32_32_UINT")), + ("Invalid buffer load format constant", lower, None, dict(load_format_constant=(16,))), + ("Invalid buffer load format constant", lower, None, dict(load_format_constant=())), + ("Invalid buffer load format constant", lower, None, dict(constant_descriptor=None)), + ("Invalid buffer load format constant", lower, None, dict(source_stride=None)), # A load result is data only. - ("Unsupported store address", base.variant(LINES, (", v8, s[20:23], 0 idxen offset:16", ", v10, s[20:23], 0 idxen offset:16")), {}), + ("Unsupported store address", lower, + base.variant(LINES, (", v8, s[20:23], 0 idxen offset:16", ", v10, s[20:23], 0 idxen offset:16")), {}), ): - base.rejects(message, lower, lines_, **binding) + base.rejects(message, function, lines_, **binding) def binary(directory, assembler, objcopy, library): - """LLVM 15 assembles the fixture; lower of the disassembly and the CLI both match lower of the source.""" + """LLVM 15 assembles both fixtures; lower of the disassembly and the CLI both match lower of the source.""" controls() - base.descriptor_store_round_trip(directory, LINES, BINDING, "mc", assembler, objcopy, library) - print(f"{NAME}: llvm15_round_trip=match") + for suite in SUITES.values(): + base.descriptor_store_round_trip(directory, suite.lines, suite.binding, "mc", assembler, objcopy, library) + print(f"{NAME}: llvm15_round_trip=match ({len(SUITES)} fixtures)") + return 0 + + +def check_references(name, renderer, backend, shader, cases, *, allow_skip=False): + paths = [path for path, _label, _diagnostic in cases] + result = subprocess.run([renderer, backend, "--compute-store-batch", shader, *paths], + capture_output=True, text=True) + if allow_skip and result.returncode == 77: + print(result.stdout, result.stderr) + return 77 + statuses = [line for line in result.stdout.splitlines() if line.startswith("case=")] + messages = re.split(r"(?=^case=\d+ path=)", result.stderr, flags=re.MULTILINE)[1:] + summaries = [line for line in result.stdout.splitlines() if line.startswith("groups=")] + for i, (path, label, diagnostic) in enumerate(cases): + status = "mismatch" if diagnostic else "pass" + if (i >= len(statuses) or statuses[i] != f"case={i} status={status}" + or i >= len(messages) or not messages[i].startswith(f"case={i} path={path}\n") + or (diagnostic and diagnostic not in messages[i])): + raise AssertionError(f"{name}: {label} expected {status}\n{result.stdout}{result.stderr}") + summary = summaries[i] if i < len(summaries) else "" + counts = re.fullmatch(r"groups=\d+ compared_words=320 mismatches=(\d+)", summary) + if not counts or (int(counts[1]) > 0) != bool(diagnostic): + raise AssertionError(f"{name}: {label} unexpected readback\n{result.stdout}{result.stderr}") + expected_exit = int(any(diagnostic for _, _, diagnostic in cases)) + if not (len(cases) == len(statuses) == len(messages) == len(summaries)) or result.returncode != expected_exit: + raise AssertionError(f"{name}: unexpected batch result ({result.returncode})\n{result.stdout}{result.stderr}") + labels = iter(label for _path, label, _diagnostic in cases) + for line in result.stdout.splitlines(): + if line.startswith("groups="): + print(f"{name}: {next(labels)}") + print(line) return 0 -def draw(directory, compiler, renderer, backend): +def draw(directory, compiler, renderer, backend, suite): """Dispatch with chosen t0 words; wrong references and mutated sources must fail. - Every case owns its case and cso files, so the launches run on a small thread pool. Results are - checked afterwards in the original order with the original messages. + The reference cases share one device and compute pipeline. Each independently compiled mutation keeps its own + renderer process so compilation and readback can overlap with the reference checks. """ src, cso = directory / "load.hlsl", directory / "load.cso" - source = lower() + source = aot.lower(suite.lines, GROUP, **suite.binding) src.write_text(source, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) words = source_words() - jobs = [] # (check, label, extra, case bytes, shader, mutated source or None) + references = [] + mutations = [] - def add(check, label, groups, reference, formats=None, extra=None, mutated=None): - data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) + def write_case(number, groups, reference, formats): + case = directory / f"case{number}.bin" + data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or suite.constants())) + struct.pack("<320I", *words)) - jobs.append((check, label, extra, data, mutated)) - - def run(number, job): - _check, _label, _extra, data, mutated = job - case, shader = directory / f"case{number}.bin", cso case.write_bytes(data) - if mutated is not None: - shader = directory / f"mutated{number}.cso" - bad_src = directory / f"mutated{number}.hlsl" - bad_src.write_text(mutated, encoding="ascii") - subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) - return subprocess.run([renderer, backend, "--compute-store-case", shader, case], - capture_output=True, text=True) + return case + + def add_reference(label, groups, reference, formats=None, diagnostic=None): + case = write_case(len(references), groups, reference, formats) + references.append((case, label, diagnostic)) + + def run_mutation(number, label, case, mutated): + shader = directory / f"mutated{number}.cso" + bad_src = directory / f"mutated{number}.hlsl" + bad_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) + result = subprocess.run([renderer, backend, "--compute-store-case", shader, case], + capture_output=True, text=True) + if result.returncode != 1 or "Compute readback differs" not in result.stderr: + raise AssertionError(f"{suite.name}: mutation '{label}' escaped detection\n{result.stderr}") for groups in (1, 2): - add("pass", "dispatch", groups, expected_words(groups)) + add_reference("dispatch", groups, suite.expected(groups)) def invalid_formats(number): - formats = constants() - formats[INVALID[number][1]] = INVALID[number][2] + formats = suite.constants() + formats[suite.invalid[number][1]] = suite.invalid[number][2] return formats # Each invalid format must leave all of u0 at the sentinel, and so fail a reference that publishes - # placeholder words for that load: zeros, or the D3D (0, 0, 0, 1) fill for the wider opcode. + # placeholder words for that load. unwritten = [base.SENTINEL] * 320 - zeros = (lambda channels: (lambda words: [0] * channels)) - for number, (label, index, _word) in enumerate(INVALID): - add("pass", f"refused {label}", 2, unwritten, invalid_formats(number)) - channels = len(LOADS[index][0]) - placeholders = [("published as zeros", zeros(channels))] - if number == 2: + for number, (label, index, _word) in enumerate(suite.invalid): + add_reference(f"refused {label}", 2, unwritten, invalid_formats(number)) + count = registers(suite.loads[index][0]) + placeholders = [("published as zeros", lambda words, count=count: [0] * count)] + if suite.loads is LOADS and number == 2: placeholders.append(("published with the (0, 0, 0, 1) fill", lambda words: [words[0], 0])) for what, values in placeholders: - published = expected_words(2, placeholder=(index, values)) - add("placeholder", f"{label} {what}", 2, published, invalid_formats(number), - extra=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") - expected = expected_words(2) - for label, wrong in WRONG: - reference = expected_words(2, wrong=wrong) + published = suite.expected(2, placeholder=(index, values)) + add_reference(f"{label} {what}", 2, published, invalid_formats(number), + diagnostic=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") + expected = suite.expected(2) + for label, wrong in suite.wrong: + reference = suite.expected(2, wrong=wrong) word = next((i for i, (a, b) in enumerate(zip(expected, reference)) if a != b), None) if word is None: - raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - add("wrong", label, 2, reference, extra=f"word={word} expected=") - for label, old, new, run_index in MUTATIONS: + raise AssertionError(f"{suite.name}: reference '{label}' matches the expected words") + add_reference(f"reference '{label}'", 2, reference, diagnostic=f"word={word} expected=") + for label, old, new, run_index in suite.mutations: mutated = source.replace(old, new, 1) if mutated == source: - raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - if run_index is None: - add("mutation", label, 2, expected, mutated=mutated) - else: - add("mutation", label, 2, unwritten, invalid_formats(run_index), mutated=mutated) + raise AssertionError(f"{suite.name}: mutation '{label}' did not change the source") + number = len(references) + len(mutations) + reference, formats = (expected, None) if run_index is None else (unwritten, invalid_formats(run_index)) + case = write_case(number, 2, reference, formats) + mutations.append((number, label, case, mutated)) with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: - results = list(pool.map(lambda item: run(*item), enumerate(jobs))) - for (check, label, extra, _data, _mutated), result in zip(jobs, results): - if check == "pass": - print(f"{NAME}: {label}", flush=True) - sys.stdout.write(result.stdout) - if result.returncode: - sys.stderr.write(result.stderr) - return 1 - elif check == "placeholder": - if result.returncode != 1 or extra not in result.stderr: - raise AssertionError(f"{NAME}: {label} escaped detection\n{result.stderr}") - elif check == "wrong": - if result.returncode != 1 or extra not in result.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{result.stderr}") - elif result.returncode != 1 or "Compute readback differs" not in result.stderr: - raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") - print(f"{NAME}: {2 + len(INVALID)} dispatches, {len(WRONG) + len(INVALID) + 1} wrong references and " - f"{len(MUTATIONS)} mutated sources checked") + batch = pool.submit(check_references, suite.name, renderer, backend, cso, references) + mutants = [pool.submit(run_mutation, *mutation) for mutation in mutations] + batch.result() + for future in mutants: + future.result() + count = len(suite.wrong) + len(suite.invalid) + (1 if suite.loads is LOADS else 0) + print(f"{suite.name}: {2 + len(suite.invalid)} dispatches, {count} wrong references and " + f"{len(suite.mutations)} mutated sources checked") return 0 @@ -409,7 +592,7 @@ def invalid_formats(number): with tempfile.TemporaryDirectory() as tmp: if mode == "binary" and len(args) == 3: sys.exit(binary(Path(tmp), *args)) - if mode == "draw" and len(args) == 3: - sys.exit(draw(Path(tmp), *args)) + if mode in SUITES and len(args) == 3: + sys.exit(draw(Path(tmp), *args, SUITES[mode])) sys.exit("usage: compute_load_format_check.py controls | binary <llvm-mc> <llvm-objcopy> <libLLVM> " - "| draw <dxc> <renderer> <adapter>") + "| draw | draw-d16 <dxc> <renderer> <adapter>") diff --git a/tests/compute_salu_bitset_check.py b/tests/compute_salu_bitset_check.py new file mode 100644 index 0000000000..cfc415dbe2 --- /dev/null +++ b/tests/compute_salu_bitset_check.py @@ -0,0 +1,216 @@ +"""Check the compute lowering of s_bitset0_b32 and s_bitset1_b32 on known scalar words.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import compute_store_check as base + +aot = base.aot + +# One invocation reads eight root constant words c0..c7 and stores eight words at u0 words 4..11. Each SOP1 bitset +# reads and writes its destination SGPR: it clears (bitset0) or sets (bitset1) bit src0[4:0] and keeps the rest. +# w4 = c0 with bit c1[4:0] set (runtime destination and index) +# w5 = c2 with bit c3[4:0] cleared +# w6 = c4 with bit c5[4:0] set (c5 is above 31 in both runs) +# w7 = w4 with bit 4 set again (a copy of a bitset result; bit 4 is already set) +# w8 = c6 with bit 31 cleared (inline 63: only bits [4:0] count) +# w9 = c7 with bit 31 set (inline -1, 0xffffffff) +# w10 = 0x0f0f0f0f, bit 1 cleared (literal 0xffffffe1), then bit c5[4:0] set +# w11 = c3 with bit c3[4:0] cleared (destination and source are one SGPR) +BITSET = [ + "s_mov_b32 s9, 0", + "s_load_dwordx4 s[12:15], s[8:9], null", + "s_load_dwordx4 s[16:19], s[8:9], 0x20", + "s_waitcnt lgkmcnt(0)", + "s_buffer_load_dwordx4 s[20:23], s[16:19], null", + "s_buffer_load_dwordx4 s[24:27], s[16:19], 0x10", + "s_waitcnt lgkmcnt(0)", + "s_bitset1_b32 s20, s21", + "s_bitset0_b32 s22, s23", + "s_bitset1_b32 s24, s25", + "s_mov_b32 s28, s20", + "s_bitset1_b32 s28, 4", + "s_bitset0_b32 s26, 63", + "s_bitset1_b32 s27, -1", + "s_mov_b32 s29, 0x0f0f0f0f", + "s_bitset0_b32 s29, 0xffffffe1", + "s_bitset1_b32 s29, s25", + "s_bitset0_b32 s23, s23", + "v_mov_b32_e32 v4, s20", "v_mov_b32_e32 v5, s22", "v_mov_b32_e32 v6, s24", "v_mov_b32_e32 v7, s28", + "v_mov_b32_e32 v8, s26", "v_mov_b32_e32 v9, s27", "v_mov_b32_e32 v10, s29", "v_mov_b32_e32 v11, s23", + "s_clause 0x1", + "buffer_store_dwordx4 v[4:7], off, s[12:15], 0 offset:16", + "buffer_store_dwordx4 v[8:11], off, s[12:15], 0 offset:32", + "s_endpgm", +] +BINDING = base.RUNTIME_BINDING +FIRST_STORED = 4 +# Two runs of root constants (c8..c15 are not read). In the first run c1 = 0 sets bit 0, c3 = 31 clears bit 31 and +# c5 = 0x47 (71) selects bit 7. In the second c1 = 0x20 (32) selects bit 0 again, already set, c3 = 0x3e selects bit +# 30, c5 = 0xffffffe3 selects bit 3, c6 already has bit 31 clear and c7 already has it set. +RUNS = ( + [0x12345670, 0x00000000, 0x8000ffff, 0x0000001f, 0x00000100, 0x00000047, 0xfedcba98, 0x00000001, + *(0x5eed0000 + i for i in range(8, 16))], + [0xffffffff, 0x00000020, 0xffffffff, 0x0000003e, 0x80000000, 0xffffffe3, 0x7fffffff, 0x80000000, + *(0x5eed0000 + i for i in range(8, 16))], +) +# Worked by hand from the ISA definition, D.u32[S0.u32[4:0]] = 0 or 1, for the two runs above. +HAND = ( + [0x12345671, 0x0000ffff, 0x00000180, 0x12345671, 0x7edcba98, 0x80000001, 0x0f0f0f8d, 0x0000001f], + [0xffffffff, 0xbfffffff, 0x80000008, 0xffffffff, 0x7fffffff, 0x80000000, 0x0f0f0f0d, 0x0000003e], +) + + +def bitset(word, index, value, *, mask=True): + """Independent reference: rewrite one entry of the word's bit list. Unmasked, an index past 31 changes nothing.""" + bits = [(word >> i) & 1 for i in range(32)] + if mask or index < 32: + bits[index % 32 if mask else index] = value + return sum(bit << i for i, bit in enumerate(bits)) + + +def reference(c, *, swap=False, mask=True, keep=True): + """Expected u0 words. swap exchanges set and clear, mask=False ignores src0[4:0], keep=False drops sD's old bits.""" + def op(word, index, value): + return bitset(word if keep else (0 if value else 0xffffffff), index & 0xffffffff, value ^ swap, mask=mask) + + w4 = op(c[0], c[1], 1) + w10 = op(op(0x0f0f0f0f, 0xffffffe1, 0), c[5], 1) + stored = [w4, op(c[2], c[3], 0), op(c[4], c[5], 1), op(w4, 4, 1), op(c[6], 63, 0), op(c[7], -1, 1), w10, + op(c[3], c[3], 0)] + words = [base.SENTINEL] * 320 + words[FIRST_STORED:FIRST_STORED + len(stored)] = stored + return words + + +def lowered(*changes): + return aot.lower(base.variant(BITSET, *changes), 1, **BINDING) + + +def controls(): + """Exact HLSL for each form, then one rejection per operand form outside the subset.""" + for constants, hand in zip(RUNS, HAND, strict=True): + stored = reference(constants)[FIRST_STORED:FIRST_STORED + len(hand)] + assert stored == hand, [hex(word) for word in stored] + # The reference controls the draw uses must each differ from the expected words. + for wrong in (dict(swap=True), dict(mask=False), dict(keep=False)): + assert reference(RUNS[0], **wrong) != reference(RUNS[0]), wrong + source = lowered() + w4 = "(params[0].x | (1u << (params[0].y & 31u)))" + for expression in ( + w4, + "(params[0].z & ~(1u << (params[0].w & 31u)))", + "(params[1].x | (1u << (params[1].y & 31u)))", + f"({w4} | (1u << (0x00000004u & 31u)))", + "(params[1].z & ~(1u << (0x0000003fu & 31u)))", + "(params[1].w | (1u << (0xffffffffu & 31u)))", + "((0x0f0f0f0fu & ~(1u << (0xffffffe1u & 31u))) | (1u << (params[1].y & 31u)))", + "(params[0].w & ~(1u << (params[0].w & 31u)))", + ): + assert expression in source, (expression, source) + # w4 appears in its own store and inside w7, the bitset of its copy in s28. + assert source.count(w4) == 2, source + # A bitset on the copy leaves s20 alone: storing s20 after it is still w4. + assert w4 + ")" not in source and w4 + ")" in lowered(("v_mov_b32_e32 v7, s28", "v_mov_b32_e32 v7, s20")) + unsupported, operand = "Unsupported compute instruction: ", "Unverified scalar ALU operand" + for message, changes in ( + # A destination that holds no known word: an unwritten SGPR, a descriptor SGPR, the table pointer and an SGPR + # whose load still waits for its s_waitcnt. + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s30, s21"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s12, s21"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s8, s21"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_buffer_load_dword s30, s[16:19], 0x20\ns_bitset1_b32 s30, 0"),)), + # A source that is not a known word: unwritten, descriptor, pending, or a literal wider than 32 bits. + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s20, s31"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s20, s13"),)), + (operand, (("s_bitset1_b32 s20, s21", "s_buffer_load_dword s30, s[16:19], 0x20\ns_bitset1_b32 s20, s30"),)), + (operand, (("s_bitset0_b32 s29, 0xffffffe1", "s_bitset0_b32 s29, 0x1ffffffe1"),)), + # A destination past s105. + (operand, (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s106, s21"),)), + # A fixture register used before its s_waitcnt lgkmcnt(0): its loaded word is not yet known. + (operand, (("s_buffer_load_dwordx4 s[24:27], s[16:19], 0x10", + "s_buffer_load_dwordx4 s[24:27], s[16:19], 0x10\ns_bitset1_b32 s24, 0"),)), + # A vector source, and the 64-bit forms. + (unsupported + "s_bitset1_b32", (("s_bitset1_b32 s20, s21", "s_bitset1_b32 s20, v4"),)), + (unsupported + "s_bitset0_b64", (("s_bitset0_b32 s22, s23", "s_bitset0_b64 s[22:23], s21"),)), + (unsupported + "s_bitset1_b64", (("s_bitset1_b32 s24, s25", "s_bitset1_b64 s[24:25], s21"),)), + # Each self-referencing bitset doubles the inline expression, so a long chain is rejected. + ("ALU expression too large", (("s_bitset0_b32 s23, s23", + "s_bitset0_b32 s23, s23" + "\ns_bitset1_b32 s23, s23" * 6),)), + # A bitset result is data only, not a store address. + ("Unsupported store address", (("v_mov_b32_e32 v4, s20", "v_mov_b32_e32 v4, s20\nv_mov_b32_e32 v12, s20"), + ("v[4:7], off, s[12:15], 0 offset:16", "v[4:7], v12, s[12:15], 0 offen"))), + ): + base.rejects(message, lowered, *changes) + # In the guarded read fixture, the group-ID SGPR and the saved exec mask are not known words either. + def guarded(*changes): + return aot.lower(base.variant(base.READ_SCALAR, *changes), 32, **base.READ_BINDING) + + guarded() + base.rejects(operand, guarded, ("s_mov_b32 s2, s1", "s_bitset1_b32 s1, 0\ns_mov_b32 s2, s1")) + base.rejects(operand, guarded, ("s_lshr_b32 s21, s20, 3", "s_lshr_b32 s21, s20, 3\ns_bitset0_b32 s2, 0")) + # Nor is the saved exec mask a known bit index. + base.rejects(operand, guarded, ("s_lshr_b32 s21, s20, 3", "s_lshr_b32 s21, s20, 3\ns_bitset1_b32 s21, s2")) + + +def run(cmd, case, constants, words, *, expect=None): + case.write_bytes(struct.pack("<337I", 1, *words, *constants)) + if expect is None: + return subprocess.run(cmd).returncode + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode != 1 or expect not in bad.stderr: + raise AssertionError(f"Expected '{expect}', got {bad.returncode}\n{bad.stdout}\n{bad.stderr}") + return 0 + + +def draw(directory, compiler, renderer, backend): + """Dispatch the fixture for both runs, then require wrong references and mutated translations to fail.""" + src, cso, case = [directory / x for x in ("bitset.hlsl", "bitset.cso", "bitset.case")] + source = lowered() + src.write_text(source, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) + cmd = [renderer, backend, "--compute-store-case", cso, case] + for constants in RUNS: + if result := run(cmd, case, constants, reference(constants)): + return result + # Wrong references: set and clear exchanged, src0[4:0] ignored, sD's other bits dropped, and the other run's + # words (a translation that folded the constants). + constants = RUNS[0] + expected = reference(constants) + for wrong in (reference(constants, swap=True), reference(constants, mask=False), + reference(constants, keep=False), reference(RUNS[1])): + word = next(i for i, (a, b) in enumerate(zip(expected, wrong)) if a != b) + run(cmd, case, constants, wrong, expect=f"word={word} expected=") + run(cmd, case, constants, expected) + w4 = "(params[0].x | (1u << (params[0].y & 31u)))" + for label, old, new in (("set for clear", "(params[0].z & ~(1u << ", "(params[0].z | (1u << "), + ("clear for set", w4, "(params[0].x & ~(1u << (params[0].y & 31u)))"), + ("destination dropped", w4, "(0x00000000u | (1u << (params[0].y & 31u)))"), + ("next bit", "(1u << (params[1].y & 31u))", "(2u << (params[1].y & 31u))"), + ("index from c1", "(params[1].x | (1u << (params[1].y", + "(params[1].x | (1u << (params[0].y")): + mutated = source.replace(old, new) + if mutated == source: + raise AssertionError(f"mutation '{label}' did not change the source") + msrc, mcso = directory / "mutated.hlsl", directory / "mutated.cso" + msrc.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mcso, msrc], check=True) + case.write_bytes(struct.pack("<337I", 1, *expected, *constants)) + bad = subprocess.run([*cmd[:3], mcso, case], capture_output=True, text=True) + if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: + raise AssertionError(f"mutation '{label}' escaped detection\n{bad.stdout}\n{bad.stderr}") + return 0 + + +if __name__ == "__main__": + controls() + mode, *args = sys.argv[1:] + if mode == "controls": + sys.exit(0) + if mode != "draw" or len(args) != 3: + sys.exit("usage: compute_salu_bitset_check.py controls | draw <dxc> <renderer> <adapter>") + with tempfile.TemporaryDirectory() as tmp: + sys.exit(draw(Path(tmp), *args)) diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index 964b2447fc..79faca44d3 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -3729,6 +3729,34 @@ def mac_f32_controls(): rejects("Unsupported compute instruction", aot.lower, variant(MAC_F32, ("v_mac_f32_e32 v10, 0x45800800, v5", bad_line)), 64, **MAC_F32_BINDING) + # The mad() fusion probe against a simulated renderer whose mutated shader reads back `readback`. + class Case: + def write_bytes(self, data): + self.words = list(struct.unpack("<321I", data)[1:]) + + def probe(readback, code=None): + case = Case() + + def run(): + diff = next((i for i, (a, b) in enumerate(zip(case.words, readback)) if a != b), None) + if code is not None or diff is None: + return subprocess.CompletedProcess([], code or 0, "", "") + return subprocess.CompletedProcess([], 1, "", f"word={diff} expected={case.words[diff]:08x} " + f"actual={readback[diff]:08x}\nCompute readback differs\n") + fusion = mac_f32_mad_fusion(run, case, expected) + assert case.words == expected + return fusion + expected, fused = mac_f32_words(), mac_f32_words(fused=True) + folded = [e if i % 4 == 0 else f for i, (e, f) in enumerate(zip(expected, fused))] + assert probe(expected) == "unfused" # no FMad fusion, as on an RX 5700 XT (#2730) + assert probe(folded) == "fused" # fused FMad, word 0 folded unfused by DXC, as on an RTX 4090 (#2883) + for readback, code, message in ((fused, None, "neither model alone"), (expected, 3, "failed (exit 3)")): + try: + probe(readback, code) + except AssertionError as error: + assert message in str(error), error + else: + raise AssertionError(f"mac_f32: mad() fusion probe accepted a readback that must fail: {message}") def mac_f32_binary(directory, assembler, objcopy, library): @@ -3739,6 +3767,40 @@ def mac_f32_binary(directory, assembler, objcopy, library): assert aot.lower(decoded, 64, **MAC_F32_BINDING) == aot.lower(MAC_F32, 64, **MAC_F32_BINDING) +def mac_f32_mad_fusion(run_mutated, case, expected): + """Whether this target fuses the `precise mad()` mutation: 'fused' or 'unfused' (#2730). + + The mutated shader is read back against the fused and the unfused model. Word 0, the cancellation + 4097 * 4097 - 16785408, has only constant operands, and DXC 1.9.2602.17 folds it at compile time to the + unfused +0, so a target that fuses FMad fuses only the thread-dependent words (#2883). The fused model + therefore keeps word 0 unfused and differs from the unfused model at words 2, 10, 18, ... Exactly one model + must match all 320 words; a compile, dispatch or readback failure, or any other readback, fails the test. + A DXC that leaves word 0 to the driver would read back neither model on a fusing target and fail here. + """ + fused = mac_f32_words(fused=True) + fused[0::4] = expected[0::4] + assert next(i for i, (a, b) in enumerate(zip(expected, fused)) if a != b) == 2 + matches, first = {}, {} + for name, model in (("fused", fused), ("unfused", expected)): + case.write_bytes(struct.pack("<321I", 1, *model)) + run = run_mutated() + if run.returncode == 0: + matches[name] = True + elif run.returncode == 1 and "Compute readback differs" in run.stderr: + matches[name] = False + first[name] = next((line for line in run.stderr.splitlines() if line.startswith("word=")), "") + else: + raise AssertionError(f"mac_f32: mad() fusion probe against the {name} model failed " + f"(exit {run.returncode})\n{run.stdout}{run.stderr}") + case.write_bytes(struct.pack("<321I", 1, *expected)) + if matches == {"fused": True, "unfused": False}: + return "fused" + if matches == {"fused": False, "unfused": True}: + return "unfused" + raise AssertionError(f"mac_f32: mad() fusion probe read back neither model alone: {matches}, " + f"first mismatch: {first}") + + def mac_f32_draw(directory, compiler, renderer, backend): src, cso, case = [directory / x for x in ("mac_f32.hlsl", "mac_f32.cso", "mac_f32.case")] source = aot.lower(MAC_F32, 64, **MAC_F32_BINDING) @@ -3779,7 +3841,17 @@ def mac_f32_draw(directory, compiler, renderer, backend): msrc, mcso = directory / "mutated.hlsl", directory / "mutated.cso" msrc.write_text(mutated, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", mcso, msrc], check=True) - bad = subprocess.run([*cmd[:3], mcso, case], capture_output=True, text=True) + run_mutated = lambda: subprocess.run([*cmd[:3], mcso, case], capture_output=True, text=True) + if label.startswith("fused mad()"): + # FMad may be fused or not (DXIL leaves it to the driver). Where it reads back the unfused model, + # as on an RX 5700 XT and an RX 9070 XT, this mutation equals the lowering and cannot be caught. + fusion = mac_f32_mad_fusion(run_mutated, case, expected) + print(f"mac_f32: mad() fusion probe ({backend}): {fusion}") + if fusion == "unfused": + print(f"mac_f32: mutation '{label}' is inapplicable on this adapter: " + "mad() reads back the unfused model on all 320 words") + continue + bad = run_mutated() if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: raise AssertionError(f"mac_f32: mutation '{label}' escaped detection") if record := os.environ.get("FORM_COVERAGE_RECORD"): @@ -5107,17 +5179,19 @@ def lds_controls(): lines[:i + 1] + lines[i + 2:], 32, **LDS_BINDING) -def gfx1030_binary(directory, assembler, objcopy, library, cases, prefix, group=32): +def gfx1030_binary(directory, assembler, objcopy, library, cases, prefix, group=32, *, cpu="gfx1030", + features=DS_FEATURES): dims = aot.checked_group(group) + attributes = [f"-mattr={features}"] if features else [] for name, lines, binding in cases: src, obj, raw = (directory / f"{name}.{ext}" for ext in ("s", "o", "bin")) src.write_text("\n".join(lines) + "\n", encoding="ascii") - subprocess.run([assembler, "-triple=amdgcn--amdpal", "-mcpu=gfx1030", f"-mattr={DS_FEATURES}", + subprocess.run([assembler, "-triple=amdgcn--amdpal", f"-mcpu={cpu}", *attributes, "-filetype=obj", src, "-o", obj], check=True) subprocess.run([objcopy, "-O", "binary", "--only-section=.text", obj, raw], check=True) code = raw.read_bytes() - decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=b"gfx1030", - features=DS_FEATURES.encode())) + decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=cpu.encode(), + features=(features or "").encode())) assert [line for line in decoded if line.startswith(prefix)] == [ line for line in lines if line.startswith(prefix)] expected = aot.lower(lines, dims, **binding) @@ -5417,6 +5491,243 @@ def ds_draw(directory, compiler, renderer, backend, *, private=False, cases=None return 0 +# Group-shared LDS on gfx1013 (issue #1541): one 64-thread group per program, LDS words written by one lane and +# read by another. Lane l of group g has tid = 64 * g + l; v5 = l * 4 is its word address, v8 its index. +SHARED_PREFIX = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", "s_load_dwordx4 s[20:23], s[12:13], 0x30", + "v_lshl_add_u32 v8, s11, 6, v0", "s_waitcnt lgkmcnt(0)", "v_lshlrev_b32_e32 v5, 2, v0"] +SHARED_BINDING = dict(table_reg=7, descriptor_offset=0x30, group_reg=11, stride=8, cpu="gfx1013", lds_bytes=1024, + wave_size=64) +# Without an allocation the wave64 statement is refused, so the no-LDS controls drop it. +SHARED_NO_LDS = {key: value for key, value in SHARED_BINDING.items() if key != "wave_size"} | {"lds_bytes": 0} +SHARED_WIDE_BINDING = SHARED_BINDING | {"stride": 16} +SHARED_MIRROR = "v_sub_nc_u32_e32 v9, 0xfc, v5" # (63 - l) * 4 +SHARED_DATA = ["v_add_nc_u32_e32 v6, 0x10000000, v8", "v_add_nc_u32_e32 v7, 0x20000000, v8"] +# The atomic operand: an odd multiplier spreads the lanes' bits over the word. +SHARED_MIX = 0x9e3779b1 +SHARED_PROGRAMS = { + # Own word, then the next lane's word and the mirrored lane's word. + "shared_exchange": (SHARED_BINDING, [ + "v_add_nc_u32_e32 v6, 0x12340000, v8", "ds_write_b32 v5, v6", "s_waitcnt lgkmcnt(0)", "s_barrier", + "v_add_nc_u32_e32 v7, 4, v5", "v_and_b32_e32 v7, 0xfc, v7", "ds_read_b32 v10, v7", "s_waitcnt lgkmcnt(0)", + SHARED_MIRROR, "ds_read_b32 v11, v9", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # Two words per lane, 64 words apart, written and read as pairs of the mirrored lane. + "shared_pair_b32": (SHARED_BINDING, [ + *SHARED_DATA, "ds_write2_b32 v5, v6, v7 offset1:64", "s_waitcnt lgkmcnt(0)", "s_barrier", + SHARED_MIRROR, "ds_read2_b32 v[10:11], v9 offset1:64", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # The same layout through st64: offset 1 is 64 elements. + "shared_pair_st64_b32": (SHARED_BINDING, [ + *SHARED_DATA, "ds_write2st64_b32 v5, v6, v7 offset1:1", "s_waitcnt lgkmcnt(0)", + SHARED_MIRROR, "ds_read2st64_b32 v[10:11], v9 offset1:1", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # A qword per lane at l * 8, read back from the mirrored lane. + "shared_b64": (SHARED_BINDING, [ + *SHARED_DATA, "v_lshlrev_b32_e32 v4, 3, v0", "ds_write_b64 v4, v[6:7]", "s_waitcnt lgkmcnt(0)", + "v_sub_nc_u32_e32 v9, 0x1f8, v4", "ds_read_b64 v[10:11], v9", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), + # Two qwords per lane 64 qwords apart, written with write2 and read with read2st64, and the other way round. + "shared_pair_b64": (SHARED_WIDE_BINDING, [ + *SHARED_DATA, "v_add_nc_u32_e32 v12, 0x30000000, v8", "v_add_nc_u32_e32 v13, 0x50000000, v8", + "v_lshlrev_b32_e32 v4, 3, v0", "ds_write2_b64 v4, v[6:7], v[12:13] offset1:64", "s_waitcnt lgkmcnt(0)", + "v_sub_nc_u32_e32 v9, 0x1f8, v4", "ds_read2st64_b64 v[14:17], v9 offset1:1", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx4 v[14:17], v8, s[20:23], 0 idxen"]), + "shared_pair_st64_b64": (SHARED_WIDE_BINDING, [ + *SHARED_DATA, "v_add_nc_u32_e32 v12, 0x30000000, v8", "v_add_nc_u32_e32 v13, 0x50000000, v8", + "v_lshlrev_b32_e32 v4, 3, v0", "ds_write2st64_b64 v4, v[6:7], v[12:13] offset1:1", "s_waitcnt lgkmcnt(0)", + "v_sub_nc_u32_e32 v9, 0x1f8, v4", "ds_read2_b64 v[14:17], v9 offset1:64", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx4 v[14:17], v8, s[20:23], 0 idxen"]), + # Four words per lane at l * 16, read back from the next lane. + "shared_b128": (SHARED_WIDE_BINDING, [ + "v_add_nc_u32_e32 v10, 0x10000000, v8", "v_add_nc_u32_e32 v11, 0x20000000, v8", + "v_add_nc_u32_e32 v12, 0x30000000, v8", "v_add_nc_u32_e32 v13, 0x50000000, v8", + "v_lshlrev_b32_e32 v4, 4, v0", "ds_write_b128 v4, v[10:13]", + "s_waitcnt lgkmcnt(0)", "v_add_nc_u32_e32 v9, 16, v4", "v_and_b32_e32 v9, 0x3f0, v9", + "ds_read_b128 v[14:17], v9", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx4 v[14:17], v8, s[20:23], 0 idxen"]), + # Every lane sets the seven counters (same values, so the overlapping writes agree), then updates them; lane l + # reports counters l & 7 and (l + 1) & 7, where counter 7 holds a constant. + "shared_atomics": (SHARED_BINDING, [ + "v_mov_b32_e32 v4, 0", "v_mov_b32_e32 v20, 0", "v_mov_b32_e32 v21, -1", "v_mov_b32_e32 v23, 0x5a5a5a5a", + "ds_write2_b32 v4, v20, v20 offset1:1", "s_waitcnt lgkmcnt(0)", + "ds_write2_b32 v4, v21, v20 offset0:2 offset1:3", "s_waitcnt lgkmcnt(0)", + "ds_write2_b32 v4, v20, v21 offset0:4 offset1:5", "s_waitcnt lgkmcnt(0)", + "ds_write2_b32 v4, v20, v23 offset0:6 offset1:7", "s_waitcnt lgkmcnt(0)", "s_barrier", + f"v_mul_lo_u32 v22, 0x{SHARED_MIX:08x}, v8", + "ds_add_u32 v4, v8", "s_waitcnt lgkmcnt(0)", "ds_sub_u32 v4, v8 offset:4", "s_waitcnt lgkmcnt(0)", + "ds_and_b32 v4, v22 offset:8", "s_waitcnt lgkmcnt(0)", "ds_or_b32 v4, v22 offset:12", "s_waitcnt lgkmcnt(0)", + "ds_xor_b32 v4, v22 offset:16", "s_waitcnt lgkmcnt(0)", "ds_min_u32 v4, v22 offset:20", "s_waitcnt lgkmcnt(0)", + "ds_max_u32 v4, v22 offset:24", "s_waitcnt lgkmcnt(0)", "s_barrier", + "v_and_b32_e32 v24, 28, v5", "ds_read_b32 v10, v24", "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32_e32 v25, 4, v5", "v_and_b32_e32 v25, 28, v25", "ds_read_b32 v11, v25", "s_waitcnt lgkmcnt(0)", + "buffer_store_dwordx2 v[10:11], v8, s[20:23], 0 idxen"]), +} +SHARED_CASES = [(name, SHARED_PREFIX + lines + ["s_endpgm"], binding) + for name, (binding, lines) in SHARED_PROGRAMS.items()] +SHARED_FORMS = {"ds_write_b32", "ds_read_b32", "ds_write_b64", "ds_read_b64", "ds_write_b128", "ds_read_b128", + "ds_write2_b32", "ds_read2_b32", "ds_write2st64_b32", "ds_read2st64_b32", "ds_write2_b64", + "ds_read2_b64", "ds_write2st64_b64", "ds_read2st64_b64", "ds_add_u32", "ds_sub_u32", "ds_and_b32", + "ds_or_b32", "ds_xor_b32", "ds_min_u32", "ds_max_u32", "s_barrier"} + + +def shared_counters(group): + tids = [64 * group + lane for lane in range(64)] + mixed = [tid * SHARED_MIX & 0xffffffff for tid in tids] + total = sum(tids) & 0xffffffff + a = mixed[0] + for value in mixed[1:]: + a &= value + o = x = 0 + for value in mixed: + o |= value + x ^= value + return [total, -total & 0xffffffff, a, o, x, min(mixed), max(mixed), 0x5a5a5a5a] + + +def shared_reference(name, groups): + words = [] + for group in range(groups): + def tid(lane): + return 64 * group + lane + counters = shared_counters(group) + for lane in range(64): + mirror = 63 - lane + if name == "shared_exchange": + words += [0x12340000 + tid((lane + 1) % 64), 0x12340000 + tid(mirror)] + elif name in ("shared_pair_b32", "shared_pair_st64_b32", "shared_b64"): + words += [0x10000000 + tid(mirror), 0x20000000 + tid(mirror)] + elif name in ("shared_pair_b64", "shared_pair_st64_b64"): + words += [base + tid(mirror) for base in (0x10000000, 0x20000000, 0x30000000, 0x50000000)] + elif name == "shared_b128": + words += [base + tid((lane + 1) % 64) for base in (0x10000000, 0x20000000, 0x30000000, 0x50000000)] + else: + words += [counters[lane & 7], counters[(lane + 1) & 7]] + return words + + +def shared_mutants(name, lines, binding): + """Assembly changes the reference must catch, with the first word they change.""" + if name == "shared_exchange": + # The next-but-one lane instead of the next one. + yield variant(lines, ("v_add_nc_u32_e32 v7, 4, v5", "v_add_nc_u32_e32 v7, 8, v5")), 0 + elif name == "shared_pair_st64_b32": + # offset1:1 as 4 bytes instead of 64 elements reads the next word, the mirrored lane's neighbour. + yield variant(lines, ("ds_read2st64_b32 v[10:11], v9 offset1:1", "ds_read2_b32 v[10:11], v9 offset1:1")), 1 + elif name == "shared_atomics": + # min in place of max: lane 5 reports counter 6 as its second word. + yield variant(lines, ("ds_max_u32 v4, v22 offset:24", "ds_min_u32 v4, v22 offset:24")), 11 + + +def shared_controls(): + for name, lines, binding in SHARED_CASES: + source = aot.lower(lines, 64, **binding) + assert f"groupshared uint lds[{binding['lds_bytes'] // 4}];" in source, name + # Every DS instruction is followed by one group barrier; s_barrier adds none after it. + steps = sum(line.startswith("ds_") for line in lines) + assert source.count("GroupMemoryBarrierWithGroupSync();") == steps, name + assert "uint3 local : SV_GroupThreadID" in source, name + # Out-of-range words are outside the input contract; every access stays guarded by the allocation size. + guard = f" < {binding['lds_bytes'] // 4}u" + assert all(guard in line for line in source.splitlines() if "lds[" in line and "groupshared" not in line), name + programs = {name: lines for name, lines, _ in SHARED_CASES} + atomics = aot.lower(programs["shared_atomics"], 64, **SHARED_BINDING) + for method in ("Add", "And", "Or", "Xor", "Min", "Max"): + assert f"Interlocked{method}(lds[" in atomics, method + # ds_sub_u32 is two additions, ~v then 1, on the same word. A single InterlockedAdd of a negated word on + # groupshared memory fails compute PSO creation on NVIDIA GeForce RTX 5080 (driver 32.0.16.2124). + sub = (" if (lds_a5 < 256u) InterlockedAdd(lds[lds_a5], ~(tid.x));\n" + " if (lds_a5 < 256u) InterlockedAdd(lds[lds_a5], 1u);\n") + assert sub in atomics, atomics + assert "0u - " not in atomics, atomics + lines = programs["shared_exchange"] + # A barrier with no DS instruction before it is kept. + assert aot.lower(SHARED_PREFIX + ["s_barrier"] + lines[len(SHARED_PREFIX):], 64, + **SHARED_BINDING).count("GroupMemoryBarrierWithGroupSync();") == 4 + write = "ds_write_b32 v5, v6" + for wrong, message in ( + ("ds_add_rtn_u32 v10, v5, v6", "Unsupported shared LDS instruction"), + ("ds_write_b96 v5, v[6:8]", "Unsupported shared LDS instruction"), + ("ds_write_b8 v5, v6", "Unsupported shared LDS instruction"), + ("ds_min_i32 v5, v6", "Unsupported shared LDS instruction"), + ("ds_write_b32 v5, v6 offset:65536", "Unverified shared LDS offset"), + ("ds_write_b32 v0, v6", "Unverified shared LDS address"), + ("ds_write_b32 v5, v0", "Shared LDS data is not a known word"), + ("ds_write_b64 v5, v[6:8]", "Unverified shared LDS register range"), + ("ds_write2_b32 v5, v6, v6 offset0:3 offset1:3", "Unverified shared LDS pair offsets"), + ("ds_write2_b32 v5, v6, v6 offset1:256", "Unverified shared LDS pair offsets")): + rejects(message, aot.lower, variant(lines, (write, wrong)), 64, **SHARED_BINDING) + # Barriers need uniform control flow: no DS instruction after a lane guard. + i = lines.index(write) + guarded = lines[:i] + ["v_cmp_gt_u32_e32 vcc_lo, 16, v8", "s_and_saveexec_b32 s5, vcc_lo"] + lines[i:] + rejects("Shared LDS access under a lane guard", aot.lower, guarded, 64, **SHARED_BINDING) + rejects("Expected immediate s_waitcnt lgkmcnt(0) after DS", aot.lower, + lines[:i + 1] + lines[i + 2:], 64, **SHARED_BINDING) + for size in (0x10004 // 2, 2, 6, 32772): + rejects("Invalid shared LDS allocation", aot.lower, lines, 64, **SHARED_BINDING | {"lds_bytes": size}) + # The profile is one guest wave. 32 threads are one wave at either width and need no statement; 64 threads + # need the wave64 statement, and are two waves under wave32; 128 threads are two wave64 waves. + unstated = {key: value for key, value in SHARED_BINDING.items() if key != "wave_size"} + half = variant(lines, ("v_lshl_add_u32 v8, s11, 6, v0", "v_lshl_add_u32 v8, s11, 5, v0")) + assert "groupshared uint lds[256];" in aot.lower(half, 32, **unstated) + for group, binding in ((64, unstated), (64, SHARED_BINDING | {"wave_size": 32}), (128, SHARED_BINDING), + ((32, 2, 1), SHARED_BINDING | {"wave_size": 32})): + rejects("Shared LDS requires a group of one guest wave", aot.lower, lines, group, **binding) + # wave64 is not a lane layout outside the shared LDS profile. + rejects("Unsupported wave size statement", aot.lower, lines, 64, **SHARED_NO_LDS | {"wave_size": 64}) + rejects("Unsupported wave size statement", aot.lower, lines, 64, **SHARED_BINDING | {"cpu": "gfx1030"}) + # Without an allocation gfx1013 keeps refusing the local-ID address, DS and s_barrier. + rejects("Unverified dispatch byte offset", aot.lower, lines, 64, **SHARED_NO_LDS) + rejects("Unverified private LDS write", aot.lower, SHARED_PREFIX[:5] + lines[len(SHARED_PREFIX):], 64, + **SHARED_NO_LDS) + rejects("Unsupported compute instruction: s_barrier", aot.lower, + SHARED_PREFIX[:5] + ["s_barrier", "buffer_store_dword v8, v8, s[20:23], 0 idxen", "s_endpgm"], 64, + **SHARED_NO_LDS | {"stride": 4}) + # The CPU references differ from the mutants'. + for name, lines, binding in SHARED_CASES: + for _, first in shared_mutants(name, lines, binding): + assert first < len(shared_reference(name, 1)), name + assert {line.split()[0] for _, lines, _ in SHARED_CASES for line in lines} >= SHARED_FORMS + + +def shared_draw(directory, compiler, renderer, backend): + shared_controls() + accepted = set() + for name, lines, binding in SHARED_CASES: + source = aot.lower(lines, 64, **binding) + src, cso, case = (directory / f"{name}.{ext}" for ext in ("hlsl", "cso", "case")) + src.write_text(source, encoding="ascii") + compile = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + subprocess.run(compile, check=True) + run = [renderer, backend, "--compute-store-case", cso, case] + # Two groups show that each group has its own LDS; four words per lane leave room for one. + for groups in (1,) if binding["stride"] == 16 else (1, 2): + words = shared_reference(name, groups) + case.write_bytes(struct.pack("<321I", groups, *(words + [SENTINEL] * (320 - len(words))))) + execution = subprocess.run(run) + if execution.returncode: + return execution.returncode + mutants = [(aot.lower(mutated, 64, **binding), word) for mutated, word in shared_mutants(name, lines, binding)] + if name == "shared_atomics": + # Without the second addition ds_sub_u32 adds ~v, so the difference read as lane 0's second word + # is 64 short, one for each lane. + dropped = source.replace(" if (lds_a5 < 256u) InterlockedAdd(lds[lds_a5], 1u);\n", "") + assert dropped != source + mutants.append((dropped, 1)) + for mutated, mismatched_word in mutants: + src.write_text(mutated, encoding="ascii") + subprocess.run(compile, check=True) + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or f"word={mismatched_word} expected=" not in bad.stderr: + raise AssertionError(f"{name}: shared LDS mutation escaped detection\n{bad.stderr}") + print(bad.stderr, end="") + accepted.update(line.split()[0] for line in lines) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(f"{op}\n" for op in sorted(accepted)), encoding="utf-8") + return 0 + + MUBUF_STORE_VALUE = 0x12345678 MUBUF_SUBWORD_STORES = { "buffer_store_byte": (1, 0, 5), @@ -6087,6 +6398,177 @@ def mubuf_float_draw(directory, compiler, renderer, backend): return 0 +# Only the four forms not already covered by mubuf_float_cases(). Low words differ +# even when the high words agree, so a truncated comparison or an exchanged pair fails. +MUBUF_FLOAT_EXTRA = ( + ("fcmpswap", False, 0xbf812345, 0x3f865432), + ("fcmpswap", True, 0xbff2345676543210, 0x3ff6543212345678), + ("fmin", True, 0xc000000012345678, 0xc000000087654321), + ("fmax", True, 0xc000000076543210, 0x4000000087654321), +) + + +def mubuf_float_extra_cases(): + for op, wide, initial, value in MUBUF_FLOAT_EXTRA: + name = f"buffer_atomic_{op}{'_x2' if wide else ''}" + width = 2 if wide else 1 + operands = (value, initial) if op == "fcmpswap" else (value,) + words = [operand >> (32 * i) & 0xffffffff for operand in operands for i in range(width)] + lines = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", + "s_load_dwordx4 s[20:23], s[12:13], 0x30", "s_waitcnt lgkmcnt(0)"] + lines += [f"v_mov_b32_e32 v{10 + i}, {word:#x}" for i, word in enumerate(words)] + lines += [f"{name} v[10:{9 + len(words)}], off, s[20:23], 0 offset:8", "s_endpgm"] + yield name, op, wide, initial, value, lines, { + k: v for k, v in DS_BINDING.items() if k != "stride" + } | {"buffer_float_domain": MUBUF_FLOAT_DOMAIN} + + +def mubuf_float_extra_reference(op, wide, initial, value, compare): + def number(bits): + integer, real = ("<Q", "<d") if wide else ("<I", "<f") + return struct.unpack(real, struct.pack(integer, bits))[0] + + old, candidate = number(initial), number(value) + if op == "fcmpswap": + return value if old == number(compare) else initial + return value if (candidate < old if op == "fmin" else candidate > old) else initial + + +def mubuf_float_extra_controls(): + for _, op, wide, initial, value, lines, binding in mubuf_float_extra_cases(): + atomic = lines[-2] + domain = "require a finite-normal domain and no glc" + rejects(domain, aot.lower, lines, 32, **(binding | {"buffer_float_domain": None})) + rejects(domain, aot.lower, variant(lines, (atomic, atomic + " glc")), 32, **binding) + rejects("Unsupported compute instruction", aot.lower, + variant(lines, (atomic, atomic.replace("off,", "v0,") + " offen")), 32, **binding) + rejects("Unverified atomic reduction address", aot.lower, + variant(lines, ("offset:8", "offset:4" if wide else "offset:2")), 32, **binding) + rejects("Unverified atomic reduction data range", aot.lower, + variant(lines, (atomic, atomic.replace(atomic.split()[1], "v10,"))), 32, **binding) + high_moves = [lines[5 if wide else 4]] + if op == "fcmpswap": + high_moves.append(lines[7 if wide else 5]) + for move in high_moves: + inf = 0x7ff00000 if wide else 0x7f800000 + sign = 0x80000000 + for word in ("0", "1", hex(sign), hex(inf), hex(inf | 0x80000)): + rejects("operands must be finite-normal constants", aot.lower, + variant(lines, (move, f"{move.split(',')[0]}, {word}")), 32, **binding) + dynamic = f"v_lshl_add_u32 v18, s11, 5, v0\n{move.split(',')[0]}, v18" + rejects("operands must be finite-normal constants", aot.lower, + variant(lines, (move, dynamic)), 32, **binding) + assert mubuf_float_extra_reference(op, wide, initial, value, initial) == value + if op == "fcmpswap": + miss = initial ^ 1 + assert mubuf_float_extra_reference(op, wide, miss, value, initial) == miss + wrong = (mubuf_float_extra_reference(op, wide, initial, initial, value) if op == "fcmpswap" else + mubuf_float_extra_reference("fmax" if op == "fmin" else "fmin", wide, initial, value, initial)) + assert wrong == initial + + +def mubuf_float_extra_binary_rejections(directory, assembler, objcopy, library): + cases = {name: (lines, binding) for name, _, _, _, _, lines, binding in mubuf_float_extra_cases()} + lines, binding = cases["buffer_atomic_fcmpswap"] + wide, wide_binding = cases["buffer_atomic_fcmpswap_x2"] + missing_domain = {key: value for key, value in binding.items() if key != "buffer_float_domain"} + domain = "Float buffer compare-swap and _x2 require a finite-normal domain and no glc" + for name, program, options, diagnostic in ( + ("missing-domain", lines, missing_domain, domain), + ("glc", variant(lines, (lines[-2], lines[-2] + " glc")), binding, domain), + ("fp64-compare-inf", variant(wide, (wide[7], "v_mov_b32_e32 v13, 0x7ff00000")), wide_binding, + "Float buffer atomic operands must be finite-normal constants"), + ("fp64-misaligned", variant(wide, ("offset:8", "offset:4")), wide_binding, + "Unverified atomic reduction address"), + ): + code = assemble(directory, assembler, objcopy, program, cpu="gfx1030", features=DS_FEATURES) + decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=b"gfx1030", + features=DS_FEATURES.encode())) + assert [line for line in decoded if line.startswith("buffer_atomic_")] == [program[-2]] + rejects(diagnostic, aot.lower, decoded, 32, **options) + archive, output = (directory / f"float-reject-{name}.{ext}" for ext in ("dxbc", "hlsl")) + archive.write_bytes(store_container(code, aot.checked_group(32))) + args = [part for key, value in options.items() for part in ("--" + key.replace("_", "-"), str(value))] + result = subprocess.run([sys.executable, "-B", aot.__file__, archive, "--output", output, + "--llvm", library, *args], capture_output=True, text=True) + assert result.returncode == 1 and result.stderr.splitlines()[-1] == f"ValueError: {diagnostic}", result + assert not output.exists(), output + print(f"assembled rejection {name}: {diagnostic}") + + +def mubuf_float_extra_binary(directory, assembler, objcopy, library): + mubuf_float_extra_controls() + gfx1030_binary(directory, assembler, objcopy, library, + [(name, lines, binding) for name, _, _, _, _, lines, binding in mubuf_float_extra_cases()], + "buffer_atomic_") + mubuf_float_extra_binary_rejections(directory, assembler, objcopy, library) + + +def mubuf_float_extra_draw(directory, compiler, renderer=None, backend=None, *, wide): + record = os.environ.get("FORM_COVERAGE_RECORD") if renderer else None + if record: + Path(record).unlink(missing_ok=True) + mubuf_float_extra_controls() + src, cso, case = (directory / f"mubuf-float-extra.{ext}" for ext in ("hlsl", "cso", "case")) + profile = "cs_6_6" if wide else "cs_6_0" + runner = "--compute-store-case-atomic64" if wide else "--compute-store-case" + run = [renderer, backend, runner, cso, case] + accepted = [] + for name, op, is_wide, initial, value, lines, binding in mubuf_float_extra_cases(): + if wide != is_wide: + continue + + def compile_source(program): + src.write_text(aot.lower(program, 32, **binding), encoding="ascii") + subprocess.run([compiler, "-T", profile, "-E", "main", "-Fo", cso, src], check=True) + + def output_words(bits): + words = [SENTINEL] * 320 + words[2] = bits & 0xffffffff + if wide: + words[3] = bits >> 32 + return words + + compile_source(lines) + # Flipping one low bit produces a distinct finite-normal seed and a compare miss. + if renderer: + for seed in (initial, initial ^ 1): + expected = mubuf_float_extra_reference(op, wide, seed, value, initial) + for groups in (1, 2): + case.write_bytes(mubuf_float_case_bytes(groups, output_words(expected), output_words(seed))) + result = subprocess.run(run) + if result.returncode: + return result.returncode + if op == "fcmpswap": + width = 2 if wide else 1 + moves = lines[4:4 + 2 * width] + mutant = [*lines[:4], *(f"v_mov_b32_e32 v{10 + i}, {move.split(', ')[1]}" + for i, move in enumerate(moves[width:] + moves[:width])), *lines[-2:]] + else: + opposite = "fmax" if op == "fmin" else "fmin" + mutant = variant(lines, (name, name.replace(op, opposite))) + compile_source(mutant) + before, after = output_words(initial), output_words(value) + first = next(i for i, (wanted, actual) in enumerate(zip(after, before)) if wanted != actual) + diagnostic = f"word={first} expected={after[first]:08x} actual={before[first]:08x}" + if renderer: + case.write_bytes(mubuf_float_case_bytes(2, before, before)) + result = subprocess.run(run) + if result.returncode: + return result.returncode + case.write_bytes(mubuf_float_case_bytes(2, after, before)) + bad = subprocess.run(run, capture_output=True, text=True) + if bad.returncode != 1 or diagnostic not in bad.stderr: + raise AssertionError(f"{name}: atomic mutation escaped detection\n{bad.stderr}") + accepted.append(name) + print(f"{name}: {'readback' if renderer else 'CPU predicted'} negative control {diagnostic}") + if record: + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(sorted(accepted)) + "\n", encoding="utf-8") + return 0 + + def scalar_alu_binary(directory, assembler, objcopy, library): """The assembled scalar chain decodes to the same program as its text.""" src, obj, raw = [directory / x for x in ("scalar.s", "scalar.o", "scalar.bin")] @@ -6168,6 +6650,7 @@ def binary(directory, assembler, objcopy, library): gfx1030_binary(directory, assembler, objcopy, library, [(name, lines, binding) for name, _, _, lines, binding in mubuf_float_cases()], "buffer_atomic_") + mubuf_float_extra_binary(directory, assembler, objcopy, library) mubuf_subword_controls() gfx1030_binary(directory, assembler, objcopy, library, mubuf_subword_cases(), "buffer_load_") mubuf_vector_controls() @@ -6197,6 +6680,8 @@ def binary(directory, assembler, objcopy, library): ds_controls() lds_controls() ds_binary(directory, assembler, objcopy, library) + shared_controls() + gfx1030_binary(directory, assembler, objcopy, library, SHARED_CASES, "ds_", 64, cpu="gfx1013", features=None) mtbuf_load_controls() mimg_load_binary(directory, assembler, objcopy, library) mimg_resinfo_controls() @@ -7805,16 +8290,16 @@ def mimg_atomic_controls(*, suite="integer"): msaa = "image_msaa_load v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm" rejects("requires an unguarded R32_UINT MSAA binding", aot.lower, variant(lines, (instruction, msaa)), MIMG_STORE_GROUP, **binding) - # gfx1013 shares this lowering for add, umax and cmpswap on R32_UINT only + # gfx1013 shares this lowering for add, umin, umax and cmpswap on R32_UINT only # (tests/compute_image_atomics_gfx1013_check.py); every other op and format stays refused there. for op, (case, case_binding) in cases.items(): gfx1013 = case_binding | {"cpu": "gfx1013"} if case_binding["image_format"] != "R32_UINT": rejects("Invalid image UAV binding", aot.lower, case, MIMG_STORE_GROUP, **gfx1013) - elif op.removesuffix("_contended") in ("add", "umax", "cmpswap"): + elif op.removesuffix("_contended") in ("add", "umin", "umax", "cmpswap"): assert aot.lower(case, MIMG_STORE_GROUP, **gfx1013) == aot.lower(case, MIMG_STORE_GROUP, **case_binding) else: - rejects("gfx1013 image atomics require add, umax or cmpswap", aot.lower, case, MIMG_STORE_GROUP, **gfx1013) + rejects("gfx1013 image atomics require add, umin, umax or cmpswap", aot.lower, case, MIMG_STORE_GROUP, **gfx1013) for case, case_binding in cases.values(): wrong_format = "R32_UINT" if case_binding["image_format"] == "R32_SINT" else "R32_SINT" rejects("Unsupported image atomic target or binding", aot.lower, case, MIMG_STORE_GROUP, @@ -9513,6 +9998,11 @@ def descriptor_store_draw(directory, compiler, renderer, backend): "draw-mubuf-reduction": mubuf_reduction_draw, "draw-mubuf-csub": lambda d, *a: mubuf_counter_draw(d, *a, csub=True), "draw-mubuf-float": mubuf_float_draw, + "binary-mubuf-float-extra": mubuf_float_extra_binary, + "compile-mubuf-float-cmpswap": lambda d, c: mubuf_float_extra_draw(d, c, wide=False), + "compile-mubuf-float-x2": lambda d, c: mubuf_float_extra_draw(d, c, wide=True), + "draw-mubuf-float-cmpswap": lambda d, *a: mubuf_float_extra_draw(d, *a, wide=False), + "draw-mubuf-float-x2": lambda d, *a: mubuf_float_extra_draw(d, *a, wide=True), "draw-mubuf-counter": mubuf_counter_draw, "draw-mubuf-counter-x2": lambda d, *a: mubuf_counter_draw(d, *a, wide=True), "draw-mubuf-exchange": mubuf_exchange_draw, @@ -9549,6 +10039,7 @@ def descriptor_store_draw(directory, compiler, renderer, backend): "draw-lds-wide-replacement": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_WIDE_REPLACEMENT_CASES), "draw-lds-f32": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_FLOAT_CASES), "draw-lds-private": lambda d, *a: ds_draw(d, *a, private=True), + "draw-lds-shared": shared_draw, "draw-lds-packed": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_PACKED_CASES), "draw-lds-arithmetic": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_ARITHMETIC_CASES), "draw-lds-replacement": lambda d, *a: ds_draw(d, *a, private=True, cases=LDS_REPLACEMENT_CASES), diff --git a/tests/coverage_svg_cli_check.py b/tests/coverage_svg_cli_check.py new file mode 100644 index 0000000000..149ad46284 --- /dev/null +++ b/tests/coverage_svg_cli_check.py @@ -0,0 +1,448 @@ +#!/usr/bin/env python3 +"""CLI, validation, collision, atomic-write, and mutation suite for tools/coverage_svg.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "coverage_svg.py" +sys.path.insert(0, str(ROOT / "tools")) + +import coverage_svg as cs # noqa: E402 + + +def _sample_coverage(): + return { + "x64_zen2": { + "covered": 4, + "total": 1007, + "blocked_by_skip": ["SSE movss"], + "groups": { + "Integer": {"covered": 3, "total": 1000}, + "SSE": {"covered": 1, "total": 6}, + "Tiny": {"covered": 0, "total": 1}, + "Zero": {"covered": 0, "total": 0}, + }, + }, + "gfx1013": { + "covered": 0, + "total": 0, + "blocked_by_skip": [], + "groups": { + "ZeroOnly": {"covered": 0, "total": 0}, + }, + }, + "gfx1030": { + "covered": 2, + "total": 5, + "blocked_by_skip": ["VOP3 v_add3_u32"], + "groups": { + "SOP1": {"covered": 2, "total": 3}, + "VOP3": {"covered": 0, "total": 2}, + }, + }, + } + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = cs.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CoverageSvgCliPositiveTests(unittest.TestCase): + def test_direct_main_writes_svg_creates_parents_and_leaves_zero_tmp(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "nested" / "sub" / "dashboard.svg" + self.assertFalse(out_svg.parent.exists()) + + code, out, err = _run_main([str(cov), str(out_svg), "--source", "test-commit, test-os, warp"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertTrue(out_svg.is_file()) + self.assertEqual( + out_svg.read_text(encoding="utf-8"), + cs.render(data, "test-commit, test-os, warp"), + ) + self.assertEqual([p.name for p in out_svg.parent.iterdir()], ["dashboard.svg"]) + + def test_sys_argv_and_script_entrypoint(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "out" / "entry.svg" + cli_argv = [str(TOOL), str(cov), str(out_svg), "--source", "entry-banner"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertIn("Measured on entry-banner.", out_svg.read_text(encoding="utf-8")) + + out_svg.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(out_svg.is_file()) + + def test_subprocess_end_to_end_positive(self): + data = _sample_coverage() + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "sub.svg" + + proc = _run_subprocess(str(cov), str(out_svg), "--source", "sub-banner") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(out_svg.read_text(encoding="utf-8"), cs.render(data, "sub-banner")) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + +class CoverageSvgCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_fragment, expected_code=1, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + if expected_code == 1: + self.assertIn("coverage_svg:", err) + else: + self.assertIn("usage:", err.lower()) + if expected_fragment: + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + if expected_code == 1: + self.assertIn("coverage_svg:", proc.stderr) + else: + self.assertIn("usage:", proc.stderr.lower()) + if expected_fragment: + self.assertIn(expected_fragment, proc.stderr) + + def test_empty_and_whitespace_source_rejected_upfront_and_in_render(self): + data = _sample_coverage() + for bad_source in ("", " ", "\t\n", None): + with self.subTest(bad_source=bad_source): + with self.assertRaisesRegex(ValueError, "source"): + cs.render(data, bad_source) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(data), encoding="utf-8") + out_svg = root / "never_created" / "out.svg" + + for bad_source in ("", " ", "\t\n"): + with self.subTest(cli_source=bad_source): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(out_svg), "--source", bad_source], + expected_fragment="--source must not be empty", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + def test_render_rejects_bool_negative_and_covered_gt_total_counts(self): + def _mutated(mutator): + sample = _sample_coverage() + mutator(sample) + return sample + + cases = ( + ("area_bool_covered", lambda d: d["x64_zen2"].__setitem__("covered", True), TypeError, "integers"), + ("area_bool_total", lambda d: d["x64_zen2"].__setitem__("total", False), TypeError, "integers"), + ("area_float_covered", lambda d: d["x64_zen2"].__setitem__("covered", 1.5), TypeError, "integers"), + ("area_neg_covered", lambda d: d["x64_zen2"].__setitem__("covered", -1), ValueError, "non-negative"), + ("area_neg_total", lambda d: d["x64_zen2"].__setitem__("total", -1), ValueError, "non-negative"), + ( + "area_covered_gt_total", + lambda d: d["x64_zen2"].__setitem__("covered", d["x64_zen2"]["total"] + 1), + ValueError, + "exceed total", + ), + ("group_bool_covered", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("covered", True), TypeError, "integers"), + ("group_bool_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", True), TypeError, "integers"), + ("group_float_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", 2.5), TypeError, "integers"), + ("group_neg_covered", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("covered", -1), ValueError, "non-negative"), + ("group_neg_total", lambda d: d["x64_zen2"]["groups"]["Integer"].__setitem__("total", -1), ValueError, "non-negative"), + ( + "group_covered_gt_total", + lambda d: d["x64_zen2"]["groups"]["SSE"].__setitem__("covered", 7), + ValueError, + "exceed total", + ), + ) + for name, mutator, exc_type, fragment in cases: + with self.subTest(case=name): + with self.assertRaisesRegex(exc_type, fragment): + cs.render(_mutated(mutator), "banner") + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_svg = root / "never" / "out.svg" + for name, mutator, _, fragment in cases: + with self.subTest(cli_case=name): + cov = root / f"{name}.json" + cov.write_text(json.dumps(_mutated(mutator)), encoding="utf-8") + self._assert_clean_failure( + [str(cov), str(out_svg), "--source", "banner"], + expected_fragment=fragment, + ) + self.assertFalse(out_svg.parent.exists()) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + def test_coverage_input_missing_dir_and_non_regular_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.json" + dir_in = root / "dir_in" + dir_in.mkdir() + reg_in = root / "coverage.json" + reg_in.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + out_svg = root / "never" / "out.svg" + + for path, frag in ( + (missing, "coverage file not found"), + (dir_in, "coverage path is a directory"), + ): + with self.subTest(path=path): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(path), str(out_svg), "--source", "banner"], + expected_fragment=frag, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + with ( + mock.patch.object(Path, "is_file", return_value=False), + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(reg_in), str(out_svg), "--source", "banner"], + expected_fragment="regular file", + check_subprocess=False, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertFalse(out_svg.parent.exists()) + + def test_output_dir_symlink_file_parent_and_samefile_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + cov_bytes = cov.read_bytes() + + # 1) Existing directory output rejected upfront. + out_dir = root / "existing_dir" + out_dir.mkdir() + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(out_dir), "--source", "banner"], + expected_fragment="existing directory", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(list(out_dir.iterdir()), []) + + # 2) Output symlink rejected upfront (real symlink if permitted, else mocked). + target = root / "keep_target.svg" + target.write_text("keep-target", encoding="utf-8") + sym_out = root / "link.svg" + try: + sym_out.symlink_to(target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + if created_real: + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(sym_out), "--source", "banner"], + expected_fragment="symbolic link", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + sym_out.unlink() + else: + with ( + mock.patch.object( + Path, + "is_symlink", + autospec=True, + side_effect=lambda p, expected=sym_out: p.resolve() == expected.resolve(), + ), + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(sym_out), "--source", "banner"], + expected_fragment="symbolic link", + check_subprocess=False, + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(target.read_text(encoding="utf-8"), "keep-target") + + # 3) File-parent output (direct and nested under regular file) rejected upfront. + file_parent = root / "regular_parent" + file_parent.write_text("keep-parent", encoding="utf-8") + for bad_out in (file_parent / "out.svg", file_parent / "nested" / "out.svg"): + with self.subTest(file_parent_out=bad_out): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(bad_out), "--source", "banner"], + expected_fragment="parent path is not a directory", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-parent") + + # 4) Output colliding with input via exact path, resolve() alias, and hardlink samefile(). + alias_out = sub / ".." / "coverage.json" + hardlink_out = sub / "hardlink.svg" + os.link(cov, hardlink_out) + self.assertNotEqual(cov.resolve(), hardlink_out.resolve()) + self.assertTrue(cov.samefile(hardlink_out)) + + for label, bad_out in (("exact", cov), ("alias", alias_out), ("samefile", hardlink_out)): + with self.subTest(collision=label): + with ( + mock.patch.object(cs, "render") as render_mock, + mock.patch.object(cs, "_write_atomic") as write_mock, + ): + self._assert_clean_failure( + [str(cov), str(bad_out), "--source", "banner"], + expected_fragment="must not match input", + ) + render_mock.assert_not_called() + write_mock.assert_not_called() + self.assertEqual(cov.read_bytes(), cov_bytes) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + self.assertFalse(any(p.name.endswith(".tmp") for p in sub.iterdir())) + + def test_bad_json_and_atomic_write_failure_leave_zero_tmp_files(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + bad_json = root / "bad.json" + bad_json.write_text("{not json", encoding="utf-8") + never_out = root / "never" / "out.svg" + self._assert_clean_failure( + [str(bad_json), str(never_out), "--source", "banner"], + expected_fragment="Expecting", + ) + self.assertFalse(never_out.parent.exists()) + self.assertFalse(any(p.name.endswith(".tmp") for p in root.iterdir())) + + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + sentinel_dir = root / "sentinel_dir" + sentinel_dir.mkdir() + sentinel = sentinel_dir / "keep.svg" + sentinel.write_text("prior-svg", encoding="utf-8") + + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(cov), str(sentinel), "--source", "banner"], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(sentinel.read_text(encoding="utf-8"), "prior-svg") + self.assertEqual([p.name for p in sentinel_dir.iterdir()], ["keep.svg"]) + + def test_argparse_errors_py314_compatible_exit_2_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + cov = root / "coverage.json" + cov.write_text(json.dumps(_sample_coverage()), encoding="utf-8") + out_svg = root / "out.svg" + + for bad_argv in ( + [], + [str(cov)], + [str(cov), str(out_svg)], + [str(cov), str(out_svg), "--source"], + [str(cov), str(out_svg), "--source", "ok", "--unknown-flag"], + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_fragment="", + expected_code=2, + ) + self.assertFalse(out_svg.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/cpu/adx_aot.asm b/tests/cpu/adx_aot.asm new file mode 100644 index 0000000000..6b5152d119 --- /dev/null +++ b/tests/cpu/adx_aot.asm @@ -0,0 +1,336 @@ +; coverage: record cpu_aot_adx_dedicated +; Source-built MASM fixture for ADX ADCX and ADOX from docs/coverage/x64_zen2.tsv +; group BMI/ADX in 32-bit and 64-bit register and flat [rcx|rdx|r8] memory forms, +; CF/OF-only isolation (preserving OF/CF/ZF/SF/PF), interleaved dual-carry chains, +; 32-bit zero-extension, destination aliasing, [r8] source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_OF_ZF_SF MACRO + setb r9b + seto r10b + sete r11b + sets byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 2 + or r9d, r11d + movzx r10d, byte ptr [r8] + shl r10d, 3 + or r9d, r10d + mov dword ptr [r8], r9d +ENDM + +; --- Register forms (32-bit & 64-bit; mov rax,rcx before 32-bit pins [63:32] zero-ext by ADCX/ADOX) --- + +op_adcx32_c0 PROC FRAME + .endprolog + xor r9d, r9d + mov rax, rcx +IFDEF ALTER_ADX + adox eax, edx +ELSE + adcx eax, edx +ENDIF + ret +op_adcx32_c0 ENDP + +op_adcx32_c1 PROC FRAME + .endprolog + xor r9d, r9d + stc + mov rax, -1 + mov eax, ecx +IFDEF ALTER_ADX + adox eax, edx +ELSE + adcx eax, edx +ENDIF + ret +op_adcx32_c1 ENDP + +op_adcx64_c0 PROC FRAME + .endprolog + xor r9d, r9d + mov rax, rcx +IFDEF ALTER_ADX + adox rax, rdx +ELSE + adcx rax, rdx +ENDIF + ret +op_adcx64_c0 ENDP + +op_adcx64_c1 PROC FRAME + .endprolog + xor r9d, r9d + stc + mov rax, rcx +IFDEF ALTER_ADX + adox rax, rdx +ELSE + adcx rax, rdx +ENDIF + ret +op_adcx64_c1 ENDP + +op_adox32_o0 PROC FRAME + .endprolog + xor r9d, r9d + mov rax, rcx +IFDEF ALTER_ADX + adcx eax, edx +ELSE + adox eax, edx +ENDIF + ret +op_adox32_o0 ENDP + +op_adox32_o1 PROC FRAME + .endprolog + mov r9d, 07fffffffh + add r9d, 1 ; OF=1, CF=0 + mov rax, -1 + mov eax, ecx +IFDEF ALTER_ADX + adcx eax, edx +ELSE + adox eax, edx +ENDIF + ret +op_adox32_o1 ENDP + +op_adox64_o0 PROC FRAME + .endprolog + xor r9d, r9d + mov rax, rcx +IFDEF ALTER_ADX + adcx rax, rdx +ELSE + adox rax, rdx +ENDIF + ret +op_adox64_o0 ENDP + +op_adox64_o1 PROC FRAME + .endprolog + mov r9d, 07fffffffh + add r9d, 1 ; OF=1, CF=0 + mov rax, rcx +IFDEF ALTER_ADX + adcx rax, rdx +ELSE + adox rax, rdx +ENDIF + ret +op_adox64_o1 ENDP + +; --- Flat [rcx|rdx|r8] m32 / m64 source forms (r8 carries 0/1 carry-in) --- + +op_adcx32_mem PROC FRAME + .endprolog + mov r9d, r8d + add r9d, 0ffffffffh ; CF = (r8d != 0), OF = 0 + mov rax, -1 + mov eax, ecx +IFDEF ALTER_ADX + adox eax, dword ptr [rdx] +ELSE + adcx eax, dword ptr [rdx] +ENDIF + ret +op_adcx32_mem ENDP + +op_adcx64_mem PROC FRAME + .endprolog + mov r9d, r8d + add r9d, 0ffffffffh + mov rax, rcx +IFDEF ALTER_ADX + adox rax, qword ptr [rdx] +ELSE + adcx rax, qword ptr [rdx] +ENDIF + ret +op_adcx64_mem ENDP + +op_adox32_mem PROC FRAME + .endprolog + mov r9d, r8d + add r9d, 07fffffffh ; OF = (r8d != 0), CF = 0 + mov rax, -1 + mov eax, ecx +IFDEF ALTER_ADX + adcx eax, dword ptr [rdx] +ELSE + adox eax, dword ptr [rdx] +ENDIF + ret +op_adox32_mem ENDP + +op_adox64_mem PROC FRAME + .endprolog + mov r9d, r8d + add r9d, 07fffffffh + mov rax, rcx +IFDEF ALTER_ADX + adcx rax, qword ptr [rdx] +ELSE + adox rax, qword ptr [rdx] +ENDIF + ret +op_adox64_mem ENDP + +; --- Flag isolation exports stored at [r8] --- + +; Seeds OF=1, CF=0, ZF=0, SF=1 (0x7fffffff + 1 = 0x80000000); ADCX updates ONLY CF. +op_adcx32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r11d, r11d + mov r10d, 07fffffffh + add r10d, 1 + mov rax, rcx + adcx eax, edx + PACK_CF_OF_ZF_SF + ret +op_adcx32_flags ENDP + +; Seeds OF=1, ZF=0, SF=1, then STC sets CF=1 preserving OF/ZF/SF; ADCX updates ONLY CF. +op_adcx64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r11d, r11d + mov r10d, 07fffffffh + add r10d, 1 + stc + mov rax, rcx + adcx rax, rdx + PACK_CF_OF_ZF_SF + ret +op_adcx64_flags ENDP + +; Seeds CF=1, OF=0, ZF=1, SF=0 (0xffffffff + 1 = 0); ADOX updates ONLY OF. +op_adox32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r11d, r11d + mov r10d, 0ffffffffh + add r10d, 1 + mov rax, rcx + adox eax, edx + PACK_CF_OF_ZF_SF + ret +op_adox32_flags ENDP + +; Seeds CF=1, OF=1, ZF=1, SF=0 (0x80000000 + 0x80000000 = 0); ADOX updates ONLY OF. +op_adox64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r11d, r11d + mov r10d, 080000000h + add r10d, r10d + mov rax, rcx + adox rax, rdx + PACK_CF_OF_ZF_SF + ret +op_adox64_flags ENDP + +; Reads [rcx] for ADCX, packs flags to [r8]. +op_adcx64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r11d, r11d + mov r10d, 07fffffffh + add r10d, 1 + mov rax, rdx + adcx rax, qword ptr [rcx] + PACK_CF_OF_ZF_SF + ret +op_adcx64_mem_flags ENDP + +; Reads [rcx] for ADOX, packs flags to [r8]. +op_adox64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r11d, r11d + mov r10d, 0ffffffffh + add r10d, 1 + mov rax, rdx + adox rax, qword ptr [rcx] + PACK_CF_OF_ZF_SF + ret +op_adox64_mem_flags ENDP + +; --- Interleaved dual-carry chain, [r8] source-then-store, dst aliasing, discarded m64 read --- + +; Reads c = [r8], runs interleaved adcx/adox chain, packs ((r11 << 2) | (OF << 1) | CF) at [r8], returns rax (adcx sum). +op_adx_dual64_adcx PROC FRAME + .endprolog + mov r9, qword ptr [r8] + mov r10d, 080000000h + add r10d, r10d ; CF=1, OF=1 + mov rax, rcx + mov r11, rdx + adcx rax, r9 + adox r11, r9 + adcx rax, rdx + adox r11, rcx + setb r9b + seto r10b + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + shl r11, 2 + or r9, r11 + mov qword ptr [r8], r9 + ret +op_adx_dual64_adcx ENDP + +; Same interleaved chain returning full 64-bit adox sum in rax and ((OF << 1) | CF) in dword [r8]. +op_adx_dual64_adox PROC FRAME + .endprolog + mov r9, qword ptr [r8] + mov r10d, 080000000h + add r10d, r10d ; CF=1, OF=1 + mov r11, rcx + mov rax, rdx + adcx r11, r9 + adox rax, r9 + adcx r11, rdx + adox rax, rcx + setb r9b + seto r10b + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + mov dword ptr [r8], r9d + ret +op_adx_dual64_adox ENDP + +op_adx_dst_alias PROC FRAME + .endprolog + xor r10d, r10d + stc ; CF=1, OF=0 + mov r9, rcx + mov r10, rdx + adcx r9, r9 + adox r10, r10 + mov rax, r9 + xor rax, r10 + ret +op_adx_dst_alias ENDP + +op_adx_discarded_read PROC FRAME + .endprolog + xor r9d, r9d + adcx r9, qword ptr [rdx] + mov rax, rcx + ret +op_adx_discarded_read ENDP + +END diff --git a/tests/cpu/adx_aot.def b/tests/cpu/adx_aot.def new file mode 100644 index 0000000000..ca0177916a --- /dev/null +++ b/tests/cpu/adx_aot.def @@ -0,0 +1,23 @@ +EXPORTS + op_adcx32_c0 + op_adcx32_c1 + op_adcx64_c0 + op_adcx64_c1 + op_adox32_o0 + op_adox32_o1 + op_adox64_o0 + op_adox64_o1 + op_adcx32_mem + op_adcx64_mem + op_adox32_mem + op_adox64_mem + op_adcx32_flags + op_adcx64_flags + op_adox32_flags + op_adox64_flags + op_adcx64_mem_flags + op_adox64_mem_flags + op_adx_dual64_adcx + op_adx_dual64_adox + op_adx_dst_alias + op_adx_discarded_read diff --git a/tests/cpu/adx_aot_check.py b/tests/cpu/adx_aot_check.py new file mode 100644 index 0000000000..140b5be74a --- /dev/null +++ b/tests/cpu/adx_aot_check.py @@ -0,0 +1,742 @@ +"""Differential, /O2, dual-carry flag-isolation, mutant, and rejection checks for cpu_adx_aot (ADCX, ADOX).""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_adx_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_adcx32_c0", "op_adcx32_c1", "op_adcx64_c0", "op_adcx64_c1", + "op_adox32_o0", "op_adox32_o1", "op_adox64_o0", "op_adox64_o1", + "op_adcx32_mem", "op_adcx64_mem", "op_adox32_mem", "op_adox64_mem", + "op_adcx32_flags", "op_adcx64_flags", "op_adox32_flags", "op_adox64_flags", + "op_adcx64_mem_flags", "op_adox64_mem_flags", + "op_adx_dual64_adcx", "op_adx_dual64_adox", + "op_adx_dst_alias", "op_adx_discarded_read", +) + +ALTERED_REG_EXPORTS = ( + "op_adcx32_c0", "op_adcx32_c1", "op_adcx64_c0", "op_adcx64_c1", + "op_adox32_o0", "op_adox32_o1", "op_adox64_o0", "op_adox64_o1", +) +ALTERED_MEM_EXPORTS = ( + "op_adcx32_mem", "op_adcx64_mem", "op_adox32_mem", "op_adox64_mem", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference model --- + +def ref_adx(op, a, b, cin, bits, *, init_cf=0, init_of=0, init_zf=0, init_sf=0, quirk=None): + """Return (dst, packed_flags) where packed_flags = (CF<<0)|(OF<<1)|(ZF<<2)|(SF<<3).""" + mask = MASK32 if bits == 32 else MASK64 + sa = a & mask + sb = b & mask + carry_in = cin & 1 + if quirk == "invert_cin": + carry_in ^= 1 + elif quirk == "drop_cin": + carry_in = 0 + total = sa + sb + carry_in + val = total & mask + cout = 1 if total > mask else 0 + if quirk == "invert_cout": + cout ^= 1 + + cf, of, zf, sf = init_cf, init_of, init_zf, init_sf + if op == "adcx": + cf = cout + if quirk == "clobber_of": + of = 0 + if quirk == "clobber_zf": + zf = int(val == 0) + if quirk == "clobber_sf": + sf = int((val >> (bits - 1)) & 1) + elif op == "adox": + of = cout + if quirk == "clobber_cf": + cf = 0 + if quirk == "clobber_zf": + zf = int(val == 0) + if quirk == "clobber_sf": + sf = int((val >> (bits - 1)) & 1) + else: + raise ValueError(op) + + if quirk == "no_zext32" and bits == 32: + val |= 0xFFFFFFFF00000000 + packed = (cf << 0) | (of << 1) | (zf << 2) | (sf << 3) + return val, packed + + +def test_pairs(): + singles = [ + 0x0000000000000000, + 0x0000000000000001, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x00000000FFFFFFFE, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF7FFFFFFF, + 0xDEADBEEF80000000, + 0xDEADBEEFFFFFFFFF, + 0x0000000100000000, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, + ] + pairs = [ + (0x0000000000000000, 0x0000000000000000), + (0x00000000FFFFFFFF, 0x0000000000000000), + (0x00000000FFFFFFFF, 0x0000000000000001), + (0x00000000FFFFFFFF, 0x00000000FFFFFFFF), + (0x000000007FFFFFFF, 0x0000000000000001), + (0x0000000080000000, 0x0000000080000000), + (0xFFFFFFFFFFFFFFFF, 0x0000000000000000), + (0xFFFFFFFFFFFFFFFF, 0x0000000000000001), + (0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF), + (0x7FFFFFFFFFFFFFFF, 0x0000000000000001), + (0x8000000000000000, 0x8000000000000000), + ] + for i, a in enumerate(singles): + pairs.append((a, singles[(i * 5 + 3) % len(singles)])) + rng = random.Random(0xAD70A07) + for _ in range(32): + pairs.append((rng.getrandbits(64), rng.getrandbits(64))) + return pairs + + +# --- Guarded memory & DLL helpers --- + +def alloc_guarded(payload): + raw = ctypes.create_string_buffer(GUARD_PRE + payload + GUARD_POST, len(GUARD_PRE) + len(payload) + len(GUARD_POST)) + base = ctypes.addressof(raw) + return raw, base + len(GUARD_PRE), len(GUARD_PRE), len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[:off] != GUARD_PRE or raw[off + length:] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_adx(lifted_lib): + if hasattr(lifted_lib, "host_has_adx"): + lifted_lib.host_has_adx.argtypes = [] + lifted_lib.host_has_adx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_adx()) + return False + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + xor_r9 = Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D) + stc = Instruction.create(Code.STC) + adcx_rax_rdx = Instruction.create_reg_reg(Code.ADCX_R64_RM64, R.RAX, R.RDX) + adox_rax_rdx = Instruction.create_reg_reg(Code.ADOX_R64_RM64, R.RAX, R.RDX) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("adcx32_r11_r8mem", (xor_r9, Instruction.create_reg_reg(Code.MOV_R32_RM32, R.R11D, R.EDX), + Instruction.create_reg_mem(Code.ADCX_R32_RM32, R.R11D, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "r11 = op_adcx32((r11 & 0xFFFFFFFFull), ld_"), + ("adox64_r10_rcxmem", (xor_r9, Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R10, R.RDX), + Instruction.create_reg_mem(Code.ADOX_R64_RM64, R.R10, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R10), ret), + "r10 = op_adox64(r10, ld_"), + ("adcx64_rax_rdx_r8", (stc, mov_rax_rcx, adcx_rax_rdx, ret), + "rax = op_adcx64(rax, rdx, flags);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r} in {src}") + + seg_adcx = Instruction.create_reg_mem(Code.ADCX_R64_RM64, R.RAX, MemoryOperand(R.RDX)) + seg_adcx.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # Undefined CF / OF reads + ("undef_cf_adcx_entry", (mov_rax_rcx, adcx_rax_rdx, ret), "undefined flag cf read"), + ("undef_of_adox_entry", (mov_rax_rcx, adox_rax_rdx, ret), "undefined flag of read"), + ("undef_of_after_stc", (stc, mov_rax_rcx, adox_rax_rdx, ret), "undefined flag of read"), + ("undef_of_after_shl2", (xor_r9, Instruction.create_reg_u32(Code.SHL_RM32_IMM8, R.R9D, 2), + mov_rax_rcx, adox_rax_rdx, ret), "undefined flag of read"), + ("undef_flags_seto_before", (mov_rax_rcx, Instruction.create_reg(Code.SETO_RM8, R.R9L), ret), + "undefined flag of read"), + # Unsupported instructions (ADC, SBB, MULX, BMI1, VEX/EVEX/XOP, LAHF/PUSHFQ) + ("adc_r64_r64", (xor_r9, mov_rax_rcx, Instruction.create_reg_reg(Code.ADC_R64_RM64, R.RAX, R.RDX), ret), + "unsupported instruction"), + ("sbb_r32_r32", (xor_r9, mov_rax_rcx, Instruction.create_reg_reg(Code.SBB_R32_RM32, R.EAX, R.EDX), ret), + "unsupported instruction"), + ("vex_mulx64", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.R9, R.RCX), ret), + "unsupported VEX instruction"), + ("vex_andn32", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr32", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + ("lahf_after_adcx", (xor_r9, mov_rax_rcx, adcx_rax_rdx, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("pushfq", (xor_r9, mov_rax_rcx, Instruction.create(Code.PUSHFQ), ret), "unsupported instruction"), + # Nonvolatile GPRs, arg GPR writes, high-byte GPRs, undefined GPRs + ("nonvol_rbx_dst", (xor_r9, Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RBX, R.RCX), + Instruction.create_reg_reg(Code.ADCX_R64_RM64, R.RBX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (xor_r9, mov_rax_rcx, Instruction.create_reg_reg(Code.ADOX_R64_RM64, R.RAX, R.RSI), ret), + "nonvolatile GPR"), + ("nonvol_r12_dst", (xor_r9, Instruction.create_reg_reg(Code.ADOX_R32_RM32, R.R12D, R.ECX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("write_arg_rcx", (xor_r9, Instruction.create_reg_reg(Code.ADCX_R64_RM64, R.RCX, R.RDX), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (xor_r9, Instruction.create_reg_reg(Code.ADOX_R32_RM32, R.EDX, R.ECX), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8", (xor_r9, Instruction.create_reg_reg(Code.ADCX_R64_RM64, R.R8, R.RCX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_u32(Code.MOV_R8_IMM8, R.AH, 1), ret), + "unsupported high-byte GPR"), + ("undef_gpr_r9_dst", (xor_r9, Instruction.create_reg_reg(Code.ADCX_R64_RM64, R.R10, R.RCX), mov_rax_rcx, ret), + "undefined GPR r10"), + ("undef_gpr_r11_src", (xor_r9, mov_rax_rcx, Instruction.create_reg_reg(Code.ADOX_R64_RM64, R.RAX, R.R11), ret), + "undefined GPR r11"), + ("undef_rax_ret", (xor_r9, Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RCX), ret), + "return with undefined RAX"), + # Displaced / indexed / RIP-relative / bad-base memory & stores outside [r8] + ("displaced_adcx_rcx", (xor_r9, mov_rax_rcx, Instruction.create_reg_mem( + Code.ADCX_R64_RM64, R.RAX, MemoryOperand(R.RCX, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_adox_rdx", (xor_r9, mov_rax_rcx, Instruction.create_reg_mem( + Code.ADOX_R32_RM32, R.EAX, MemoryOperand(R.RDX, displ=4, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_store_r8", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("indexed_adcx", (xor_r9, mov_rax_rcx, Instruction.create_reg_mem( + Code.ADCX_R64_RM64, R.RAX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("rip_rel_adox", (xor_r9, mov_rax_rcx, Instruction.create_reg_mem( + Code.ADOX_R64_RM64, R.RAX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (xor_r9, mov_rax_rcx, Instruction.create_reg_mem( + Code.ADCX_R64_RM64, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("non_r8_store_rcx", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("non_r8_store_setb", (xor_r9, mov_rax_rcx, Instruction.create_mem( + Code.SETB_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_adcx", (xor_r9, mov_rax_rcx, seg_adcx, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (xor_r9, mov_rax_rcx, adcx_rax_rdx), "missing terminal ret"), + ("trailing_after_ret", (mov_rax_rcx, ret, mov_rax_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_adx_dual64_adcx") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from("<I", records, i)[0] == entry) + pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) + max_len = struct.unpack_from("<I", records, rec_idx + 4)[0] - entry + + by_label = {label: (encode_seq(*seq), reason) for label, seq, reason in unit_cases} + pe_labels = ( + "undef_cf_adcx_entry", + "undef_of_adox_entry", + "adc_r64_r64", + "vex_mulx64", + "evex_vpaddd", + "xop_bextr32", + "nonvol_rbx_dst", + "write_arg_rcx", + "displaced_adcx_rcx", + "non_r8_store_rcx", + "branch_jmp", + "seg_prefix_adcx", + ) + lifter_script = Path(__file__).resolve().parents[2] / "tools" / "cpu_adx_aot.py" + with TemporaryDirectory() as folder: + tmp = Path(folder) + patched = tmp / "patched.dll" + out_cpp = tmp / "rejected.cpp" + for label in pe_labels: + patch, reason = by_label[label] + if len(patch) > max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("<I", damaged, pdata_end_off, entry + len(patch)) + patched.write_bytes(damaged) + try: + translate(patched, ["op_adx_dual64_adcx"]) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"pe_{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"pe_{label}: PE translate accepted rejected patch") + + proc = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(patched), "op_adx_dual64_adcx", str(out_cpp)], + capture_output=True, + text=True, + ) + if proc.returncode != 1 or "Traceback" in proc.stderr or "unsupported instruction prefix" not in proc.stderr: + raise AssertionError(f"CLI rejection unexpected: rc={proc.returncode}, stderr={proc.stderr!r}") + if out_cpp.exists() or list(tmp.glob("*.tmp")): + raise AssertionError("CLI failure left behind output or temp file") + + bad_dir = tmp / "dir_out" + bad_dir.mkdir() + proc_dir = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(original_path), "op_adcx32_c0", str(bad_dir)], + capture_output=True, + text=True, + ) + if proc_dir.returncode != 1 or "Traceback" in proc_dir.stderr or "directory" not in proc_dir.stderr: + raise AssertionError(f"CLI dir rejection unexpected: rc={proc_dir.returncode}, stderr={proc_dir.stderr!r}") + + print( + f"rejections passed: {len(alt_accept)} alt + {len(unit_cases)} IR + " + f"{len(raw_cases)} raw + {len(pe_labels)} PE-patched + CLI" + ) + + +# --- Positive, altered, mutant, and /O2 verification --- + +def _ref_dual64(a, b, c): + cf = 1 + of = 1 + t1 = a + c + cf + cf = 1 if t1 > MASK64 else 0 + rax = t1 & MASK64 + t2 = b + c + of + of = 1 if t2 > MASK64 else 0 + r11 = t2 & MASK64 + t3 = rax + b + cf + cf = 1 if t3 > MASK64 else 0 + rax = t3 & MASK64 + t4 = r11 + a + of + of = 1 if t4 > MASK64 else 0 + r11 = t4 & MASK64 + return rax, r11, (of << 1) | cf + + +def verify_suite(fns, label, pairs): + total = 0 + + # 1) Register forms (32-bit zero-ext + 64-bit, carry-in 0 and 1). + reg_specs = ( + ("op_adcx32_c0", "adcx", 32, 0), + ("op_adcx32_c1", "adcx", 32, 1), + ("op_adcx64_c0", "adcx", 64, 0), + ("op_adcx64_c1", "adcx", 64, 1), + ("op_adox32_o0", "adox", 32, 0), + ("op_adox32_o1", "adox", 32, 1), + ("op_adox64_o0", "adox", 64, 0), + ("op_adox64_o1", "adox", 64, 1), + ) + for name, op, bits, cin in reg_specs: + fn = fns[name] + for a, b in pairs: + want, _ = ref_adx(op, a, b, cin, bits) + got = fn(a, b, 0) + if got != want: + raise AssertionError(f"{label} {name}({a:#x}, {b:#x}): got {got:#x} != exp {want:#x}") + total += 1 + + # 2) Flat [rdx] m32 / m64 source forms with carry-in 0 and 1. + mem_specs = ( + ("op_adcx32_mem", "adcx", 32), + ("op_adcx64_mem", "adcx", 64), + ("op_adox32_mem", "adox", 32), + ("op_adox64_mem", "adox", 64), + ) + for name, op, bits in mem_specs: + fn = fns[name] + fmt = "<I" if bits == 32 else "<Q" + mask = MASK32 if bits == 32 else MASK64 + for a, b in pairs: + for cin in (0, 1): + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, b & mask)) + want, _ = ref_adx(op, a, b, cin, bits) + got = fn(a, ptr, cin) + read_guarded(buf, off, ln, name) + if got != want: + raise AssertionError(f"{label} {name}({a:#x}, {b:#x}, {cin}): got {got:#x} != exp {want:#x}") + total += 1 + + # 3) Flag-isolation exports: verify ONLY CF (for ADCX) or ONLY OF (for ADOX) updates, others preserved. + flag_specs = ( + ("op_adcx32_flags", "adcx", 32, 0, 1, 0, 1), # init: CF=0, OF=1, ZF=0, SF=1 + ("op_adcx64_flags", "adcx", 64, 1, 1, 0, 1), # init: CF=1, OF=1, ZF=0, SF=1 + ("op_adox32_flags", "adox", 32, 1, 0, 1, 0), # init: CF=1, OF=0, ZF=1, SF=0 + ("op_adox64_flags", "adox", 64, 1, 1, 1, 0), # init: CF=1, OF=1, ZF=1, SF=0 + ) + for name, op, bits, icf, iof, izf, isf in flag_specs: + fn = fns[name] + cin = icf if op == "adcx" else iof + for a, b in pairs: + want_val, want_flags = ref_adx(op, a, b, cin, bits, init_cf=icf, init_of=iof, init_zf=izf, init_sf=isf) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fn(a, b, po) + got_flags = struct.unpack("<I", read_guarded(bo, oo, lo, name))[0] + if got_val != want_val or got_flags != want_flags: + raise AssertionError( + f"{label} {name}({a:#x}, {b:#x}): val={got_val:#x}/{want_val:#x} flags={got_flags:#x}/{want_flags:#x}" + ) + total += 1 + + # [rcx] memory flag-isolation exports. + for name, op, icf, iof, izf, isf in ( + ("op_adcx64_mem_flags", "adcx", 0, 1, 0, 1), + ("op_adox64_mem_flags", "adox", 1, 0, 1, 0), + ): + fn = fns[name] + cin = icf if op == "adcx" else iof + for a, b in pairs: + want_val, want_flags = ref_adx(op, b, a, cin, 64, init_cf=icf, init_of=iof, init_zf=izf, init_sf=isf) + ba, pa, oa, la = alloc_guarded(struct.pack("<Q", a)) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fn(pa, b, po) + read_guarded(ba, oa, la, f"{name}_src") + got_flags = struct.unpack("<I", read_guarded(bo, oo, lo, f"{name}_out"))[0] + if got_val != want_val or got_flags != want_flags: + raise AssertionError( + f"{label} {name}({a:#x}, {b:#x}): val={got_val:#x}/{want_val:#x} flags={got_flags:#x}/{want_flags:#x}" + ) + total += 1 + + # 4) Interleaved dual-carry chains ([r8] source-then-store), dst aliasing, discarded faulting read. + for i in range(len(pairs) - 1): + a, b = pairs[i] + c, _ = pairs[i + 1] + want_adcx, want_adox, want_flags = _ref_dual64(a, b, c) + + br1, pr1, or1, lr1 = alloc_guarded(struct.pack("<Q", c)) + got_adcx = fns["op_adx_dual64_adcx"](a, b, pr1) + got_packed = struct.unpack("<Q", read_guarded(br1, or1, lr1, "dual64_adcx"))[0] + want_packed = ((want_adox << 2) & MASK64) | want_flags + if got_adcx != want_adcx or got_packed != want_packed: + raise AssertionError( + f"{label} op_adx_dual64_adcx({a:#x}, {b:#x}, {c:#x}): " + f"adcx={got_adcx:#x}/{want_adcx:#x} packed={got_packed:#x}/{want_packed:#x}" + ) + + br2, pr2, or2, lr2 = alloc_guarded(struct.pack("<Q", c)) + got_adox = fns["op_adx_dual64_adox"](a, b, pr2) + got_f = struct.unpack("<Q", read_guarded(br2, or2, lr2, "dual64_adox"))[0] & 0xFFFFFFFF + if got_adox != want_adox or got_f != want_flags: + raise AssertionError( + f"{label} op_adx_dual64_adox({a:#x}, {b:#x}, {c:#x}): " + f"adox={got_adox:#x}/{want_adox:#x} flags={got_f:#x}/{want_flags:#x}" + ) + total += 2 + + got_alias = fns["op_adx_dst_alias"](a, b, 0) + want_alias = ref_adx("adcx", a, a, 1, 64)[0] ^ ref_adx("adox", b, b, 0, 64)[0] + if got_alias != want_alias: + raise AssertionError(f"{label} op_adx_dst_alias({a:#x}, {b:#x}): got={got_alias:#x} exp={want_alias:#x}") + total += 1 + + bd, pd, od, ld = alloc_guarded(struct.pack("<Q", 0x123456789ABCDEF0)) + assert fns["op_adx_discarded_read"](0xCAFEBABE, pd, 0) == 0xCAFEBABE + read_guarded(bd, od, ld, "discarded_valid") + try: + fns["op_adx_discarded_read"](0xCAFEBABE, 0, 0) + except OSError as exc: + if "access violation reading" not in str(exc).lower(): + raise AssertionError(f"{label} discarded_read(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{label} op_adx_discarded_read(NULL) dropped faulting m64 read") + + return total + + +def _altered_expected(name, a, b, cin=0): + if name == "op_adcx32_c0": + return ref_adx("adox", a, b, 0, 32)[0] + if name == "op_adcx32_c1": + return ref_adx("adox", a, b, 0, 32)[0] + if name == "op_adcx64_c0": + return ref_adx("adox", a, b, 0, 64)[0] + if name == "op_adcx64_c1": + return ref_adx("adox", a, b, 0, 64)[0] + if name == "op_adox32_o0": + return ref_adx("adcx", a, b, 0, 32)[0] + if name == "op_adox32_o1": + return ref_adx("adcx", a, b, 0, 32)[0] + if name == "op_adox64_o0": + return ref_adx("adcx", a, b, 0, 64)[0] + if name == "op_adox64_o1": + return ref_adx("adcx", a, b, 0, 64)[0] + if name == "op_adcx32_mem": + return ref_adx("adox", a, b, 0, 32)[0] + if name == "op_adcx64_mem": + return ref_adx("adox", a, b, 0, 64)[0] + if name == "op_adox32_mem": + return ref_adx("adcx", a, b, 0, 32)[0] + if name == "op_adox64_mem": + return ref_adx("adcx", a, b, 0, 64)[0] + raise ValueError(name) + + +def check_altered_and_mutants(lifted_fns, alt_lifted_fns, pairs): + diverged = 0 + for name in ALTERED_REG_EXPORTS: + diffs = 0 + for a, b in pairs: + want_alt = _altered_expected(name, a, b) + got_al = alt_lifted_fns[name](a, b, 0) + if got_al != want_alt: + raise AssertionError(f"altered_lifted {name}({a:#x}, {b:#x}): {got_al:#x} != {want_alt:#x}") + diffs += got_al != lifted_fns[name](a, b, 0) + if name.endswith(("_c1", "_o1")) and not diffs: + raise AssertionError(f"ALTER_ADX failed to diverge on {name}") + diverged += 1 + + for name in ALTERED_MEM_EXPORTS: + bits = 32 if "32" in name else 64 + fmt = "<I" if bits == 32 else "<Q" + mask = MASK32 if bits == 32 else MASK64 + diffs = 0 + for a, b in pairs: + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, b & mask)) + want_alt = _altered_expected(name, a, b, 1) + got_al = alt_lifted_fns[name](a, ptr, 1) + got_ol = lifted_fns[name](a, ptr, 1) + read_guarded(buf, off, ln, name) + if got_al != want_alt: + raise AssertionError(f"altered_lifted {name}({a:#x}, {b:#x}): {got_al:#x} != {want_alt:#x}") + diffs += got_al != got_ol + if not diffs: + raise AssertionError(f"ALTER_ADX failed to diverge on {name}") + diverged += 1 + + mutant_specs = ( + ("adcx", 32, 0, 1, 0, 1, "invert_cin"), + ("adcx", 64, 1, 1, 0, 1, "drop_cin"), + ("adcx", 64, 1, 1, 0, 1, "invert_cout"), + ("adcx", 32, 0, 1, 0, 1, "clobber_of"), + ("adcx", 32, 0, 1, 0, 1, "clobber_zf"), + ("adcx", 64, 1, 1, 0, 1, "clobber_sf"), + ("adcx", 32, 0, 1, 0, 1, "no_zext32"), + ("adox", 32, 1, 0, 1, 0, "invert_cin"), + ("adox", 64, 1, 1, 1, 0, "drop_cin"), + ("adox", 64, 1, 1, 1, 0, "invert_cout"), + ("adox", 32, 1, 0, 1, 0, "clobber_cf"), + ("adox", 32, 1, 0, 1, 0, "clobber_zf"), + ("adox", 64, 1, 1, 1, 0, "clobber_sf"), + ("adox", 32, 1, 0, 1, 0, "no_zext32"), + ) + for op, bits, icf, iof, izf, isf, quirk in mutant_specs: + fn = lifted_fns[f"op_{op}{bits}_flags"] + cin = icf if op == "adcx" else iof + caught = 0 + for a, b in pairs: + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fn(a, b, po) + got_flags = struct.unpack("<I", read_guarded(bo, oo, lo, f"mut_{op}"))[0] + mut_val, mut_flags = ref_adx(op, a, b, cin, bits, init_cf=icf, init_of=iof, init_zf=izf, init_sf=isf, quirk=quirk) + if got_val != mut_val or got_flags != mut_flags: + caught += 1 + if not caught: + raise AssertionError(f"mutant {quirk} on {op}{bits} survived") + + return diverged, len(mutant_specs) + + +def compile_o2_and_verify(original_path, cxx_path, pairs): + source_text, _ = translate(original_path, list(EXPORTS)) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "adx_aot_o2.cpp" + dll_path = tmp / "adx_aot_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'adx_aot_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_suite(o2_fns, "lifted_o2", pairs) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + + # 1) Lift + rejections + portable lifted + mutants + /O2 run unconditionally BEFORE CPUID skip. + check_rejections(original_path) + + pairs = test_pairs() + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_suite(lifted_fns, "lifted", pairs) + diverged, mutants = check_altered_and_mutants(lifted_fns, alt_lifted_fns, pairs) + o2_cases = compile_o2_and_verify(original_path, cxx_path, pairs) + + if not host_has_adx(lifted_lib): + print( + f"portable lifted passed ({lifted_cases} lifted + {o2_cases} /O2 cases, " + f"{diverged} ALTER_ADX + {mutants} mutants); " + "Host lacks CPUID.07H.00H:EBX[19] (ADX), skipping native differential check" + ) + sys.exit(77) + + # 2) Native ADX hardware differential checks. + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + try: + native_cases = verify_suite(orig_fns, "native", pairs) + for name in ALTERED_REG_EXPORTS + ALTERED_MEM_EXPORTS: + is_mem = name.endswith("_mem") + bits = 32 if "32" in name else 64 + fmt = "<I" if bits == 32 else "<Q" + mask = MASK32 if bits == 32 else MASK64 + for a, b in pairs[:24]: + if is_mem: + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, b & mask)) + got_an = alt_fns[name](a, ptr, 1) + got_al = alt_lifted_fns[name](a, ptr, 1) + read_guarded(buf, off, ln, f"alt_{name}") + else: + got_an = alt_fns[name](a, b, 0) + got_al = alt_lifted_fns[name](a, b, 0) + if got_an != got_al: + raise AssertionError(f"altered native vs lifted {name}({a:#x}, {b:#x}): {got_an:#x} != {got_al:#x}") + finally: + orig_fns.clear() + alt_fns.clear() + unload_lib(orig_lib) + unload_lib(alt_lib) + finally: + lifted_fns.clear() + alt_lifted_fns.clear() + unload_lib(lifted_lib) + unload_lib(alt_lifted_lib) + + record_covered_forms(original_path) + print( + f"adx_aot passed: {native_cases} native + {lifted_cases} lifted + {o2_cases} /O2 cases " + f"across {len(EXPORTS)} exports; ALTER_ADX checked on {diverged} exports + {mutants} mutants caught" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/aes_pclmul_aot.asm b/tests/cpu/aes_pclmul_aot.asm new file mode 100644 index 0000000000..c9497881d5 --- /dev/null +++ b/tests/cpu/aes_pclmul_aot.asm @@ -0,0 +1,401 @@ +; coverage: record cpu_aot_aes_pclmul +; Source-built MASM fixture for legacy SSE and VEX.128 AES-NI and PCLMULQDQ +; instructions from docs/coverage/x64_zen2.tsv: register and flat [rcx|rdx|r8] +; m128 forms, YMM[255:128] preservation vs VEX.128 zeroing, vzeroupper, +; aliased source-before-dst overwrite, and discarded faulting m128 read. +.code + +; --- Legacy SSE register forms --- + +op_aesenc_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesenclast xmm0, xmm1 +ELSE + aesenc xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenc_reg ENDP + +op_aesenclast_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesenc xmm0, xmm1 +ELSE + aesenclast xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenclast_reg ENDP + +op_aesdec_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesdeclast xmm0, xmm1 +ELSE + aesdec xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdec_reg ENDP + +op_aesdeclast_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + aesdec xmm0, xmm1 +ELSE + aesdeclast xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdeclast_reg ENDP + +op_aesimc_reg PROC FRAME + .endprolog + movdqa xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + movdqa xmm0, xmm1 +ELSE + aesimc xmm0, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aesimc_reg ENDP + +op_aeskeygenassist_reg PROC FRAME + .endprolog + movdqa xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + aeskeygenassist xmm0, xmm1, 1Ch +ELSE + aeskeygenassist xmm0, xmm1, 1Bh +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_aeskeygenassist_reg ENDP + +op_pclmulqdq_00_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + pclmulqdq xmm0, xmm1, 11h +ELSE + pclmulqdq xmm0, xmm1, 00h +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_00_reg ENDP + +op_pclmulqdq_11_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + pclmulqdq xmm0, xmm1, 00h +ELSE + pclmulqdq xmm0, xmm1, 11h +ENDIF + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_11_reg ENDP + +op_pclmulqdq_ignore_bits_reg PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] + pclmulqdq xmm0, xmm1, 0EFh + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_ignore_bits_reg ENDP + +; --- Legacy SSE flat [rcx|rdx] m128 forms (16-byte aligned) --- + +op_aesenc_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesenc xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenc_mem ENDP + +op_aesenclast_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesenclast xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesenclast_mem ENDP + +op_aesdec_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesdec xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdec_mem ENDP + +op_aesdeclast_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + aesdeclast xmm0, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesdeclast_mem ENDP + +op_aesimc_mem PROC FRAME + .endprolog + aesimc xmm0, xmmword ptr [rcx] + movdqa xmmword ptr [r8], xmm0 + ret +op_aesimc_mem ENDP + +op_aeskeygenassist_mem PROC FRAME + .endprolog + aeskeygenassist xmm0, xmmword ptr [rcx], 80h + movdqa xmmword ptr [r8], xmm0 + ret +op_aeskeygenassist_mem ENDP + +op_pclmulqdq_01_mem PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + pclmulqdq xmm0, xmmword ptr [rdx], 01h + movdqa xmmword ptr [r8], xmm0 + ret +op_pclmulqdq_01_mem ENDP + +; --- VEX.128 register forms --- + +op_vaesenc_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesdec xmm0, xmm1, xmm2 +ELSE + vaesenc xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenc_reg ENDP + +op_vaesenclast_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesdeclast xmm0, xmm1, xmm2 +ELSE + vaesenclast xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenclast_reg ENDP + +op_vaesdec_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesenc xmm0, xmm1, xmm2 +ELSE + vaesdec xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdec_reg ENDP + +op_vaesdeclast_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesenclast xmm0, xmm1, xmm2 +ELSE + vaesdeclast xmm0, xmm1, xmm2 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdeclast_reg ENDP + +op_vaesimc_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vmovdqa xmm0, xmm1 +ELSE + vaesimc xmm0, xmm1 +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesimc_reg ENDP + +op_vaeskeygenassist_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vaeskeygenassist xmm0, xmm1, 37h +ELSE + vaeskeygenassist xmm0, xmm1, 36h +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaeskeygenassist_reg ENDP + +op_vpclmulqdq_10_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vpclmulqdq xmm0, xmm1, xmm2, 01h +ELSE + vpclmulqdq xmm0, xmm1, xmm2, 10h +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vpclmulqdq_10_reg ENDP + +op_vpclmulqdq_ignore_bits_reg PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vmovdqu xmm2, xmmword ptr [rdx] + vpclmulqdq xmm0, xmm1, xmm2, 0FCh + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vpclmulqdq_ignore_bits_reg ENDP + +; --- VEX.128 flat [rcx|rdx] m128 forms --- + +op_vaesenc_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vaesdec xmm0, xmm1, xmmword ptr [rdx] +ELSE + vaesenc xmm0, xmm1, xmmword ptr [rdx] +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenc_mem ENDP + +op_vaesenclast_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesenclast xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesenclast_mem ENDP + +op_vaesdec_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesdec xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdec_mem ENDP + +op_vaesdeclast_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesdeclast xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesdeclast_mem ENDP + +op_vaesimc_mem PROC FRAME + .endprolog + vaesimc xmm0, xmmword ptr [rcx] + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaesimc_mem ENDP + +op_vaeskeygenassist_mem PROC FRAME + .endprolog + vaeskeygenassist xmm0, xmmword ptr [rcx], 0FFh + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vaeskeygenassist_mem ENDP + +op_vpclmulqdq_11_mem PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] +IFDEF ALTER_AES_PCLMUL + vpclmulqdq xmm0, xmm1, xmmword ptr [rdx], 00h +ELSE + vpclmulqdq xmm0, xmm1, xmmword ptr [rdx], 11h +ENDIF + vmovdqu xmmword ptr [r8], xmm0 + ret +op_vpclmulqdq_11_mem ENDP + +; --- YMM[255:128] preservation vs VEX.128 zeroing, vzeroupper, aliasing, [r8] src, discarded read --- + +op_sse_preserves_ymm_hi PROC FRAME + .endprolog + vmovdqu ymm0, ymmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] +IFDEF ALTER_AES_PCLMUL + vaesenc xmm0, xmm0, xmm1 +ELSE + aesenc xmm0, xmm1 +ENDIF + vmovdqu ymmword ptr [r8], ymm0 + ret +op_sse_preserves_ymm_hi ENDP + +op_vex_zeroes_ymm_hi PROC FRAME + .endprolog + vmovdqu ymm0, ymmword ptr [rcx] + vmovdqu xmm1, xmmword ptr [rdx] + vaesenc xmm0, xmm0, xmm1 + vmovdqu ymmword ptr [r8], ymm0 + ret +op_vex_zeroes_ymm_hi ENDP + +op_vzeroupper_clears_ymm_hi PROC FRAME + .endprolog + vmovdqu ymm1, ymmword ptr [rcx] + vzeroupper + vmovdqu ymmword ptr [r8], ymm1 + ret +op_vzeroupper_clears_ymm_hi ENDP + +op_r8_source_then_store PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesenc xmm0, xmm1, xmmword ptr [r8] + vpclmulqdq xmm0, xmm0, xmmword ptr [rdx], 00h + vmovdqa xmmword ptr [r8], xmm0 + ret +op_r8_source_then_store ENDP + +op_dst_alias_src PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vaesenc xmm0, xmm0, xmm0 + aesimc xmm0, xmm0 + aeskeygenassist xmm0, xmm0, 01h + vpclmulqdq xmm0, xmm0, xmm0, 01h + movdqu xmmword ptr [r8], xmm0 + ret +op_dst_alias_src ENDP + +op_aes_pclmul_discarded_read PROC FRAME + .endprolog + vmovdqu xmm1, xmmword ptr [rcx] + vaesenc xmm0, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm1 + ret +op_aes_pclmul_discarded_read ENDP + +END diff --git a/tests/cpu/aes_pclmul_aot.def b/tests/cpu/aes_pclmul_aot.def new file mode 100644 index 0000000000..1df0227d24 --- /dev/null +++ b/tests/cpu/aes_pclmul_aot.def @@ -0,0 +1,38 @@ +EXPORTS + op_aesenc_reg + op_aesenclast_reg + op_aesdec_reg + op_aesdeclast_reg + op_aesimc_reg + op_aeskeygenassist_reg + op_pclmulqdq_00_reg + op_pclmulqdq_11_reg + op_pclmulqdq_ignore_bits_reg + op_aesenc_mem + op_aesenclast_mem + op_aesdec_mem + op_aesdeclast_mem + op_aesimc_mem + op_aeskeygenassist_mem + op_pclmulqdq_01_mem + op_vaesenc_reg + op_vaesenclast_reg + op_vaesdec_reg + op_vaesdeclast_reg + op_vaesimc_reg + op_vaeskeygenassist_reg + op_vpclmulqdq_10_reg + op_vpclmulqdq_ignore_bits_reg + op_vaesenc_mem + op_vaesenclast_mem + op_vaesdec_mem + op_vaesdeclast_mem + op_vaesimc_mem + op_vaeskeygenassist_mem + op_vpclmulqdq_11_mem + op_sse_preserves_ymm_hi + op_vex_zeroes_ymm_hi + op_vzeroupper_clears_ymm_hi + op_r8_source_then_store + op_dst_alias_src + op_aes_pclmul_discarded_read diff --git a/tests/cpu/aes_pclmul_aot_check.py b/tests/cpu/aes_pclmul_aot_check.py new file mode 100644 index 0000000000..64267bec97 --- /dev/null +++ b/tests/cpu/aes_pclmul_aot_check.py @@ -0,0 +1,817 @@ +"""Differential, FIPS-197, YMM[255:128], /O2, mutant, and rejection checks for cpu_aes_pclmul_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_aes_pclmul_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_aesenc_reg", "op_aesenclast_reg", "op_aesdec_reg", "op_aesdeclast_reg", + "op_aesimc_reg", "op_aeskeygenassist_reg", + "op_pclmulqdq_00_reg", "op_pclmulqdq_11_reg", "op_pclmulqdq_ignore_bits_reg", + "op_aesenc_mem", "op_aesenclast_mem", "op_aesdec_mem", "op_aesdeclast_mem", + "op_aesimc_mem", "op_aeskeygenassist_mem", "op_pclmulqdq_01_mem", + "op_vaesenc_reg", "op_vaesenclast_reg", "op_vaesdec_reg", "op_vaesdeclast_reg", + "op_vaesimc_reg", "op_vaeskeygenassist_reg", + "op_vpclmulqdq_10_reg", "op_vpclmulqdq_ignore_bits_reg", + "op_vaesenc_mem", "op_vaesenclast_mem", "op_vaesdec_mem", "op_vaesdeclast_mem", + "op_vaesimc_mem", "op_vaeskeygenassist_mem", "op_vpclmulqdq_11_mem", + "op_sse_preserves_ymm_hi", "op_vex_zeroes_ymm_hi", "op_vzeroupper_clears_ymm_hi", + "op_r8_source_then_store", "op_dst_alias_src", "op_aes_pclmul_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_aesenc_reg", "op_aesenclast_reg", "op_aesdec_reg", "op_aesdeclast_reg", + "op_aesimc_reg", "op_aeskeygenassist_reg", "op_pclmulqdq_00_reg", "op_pclmulqdq_11_reg", + "op_vaesenc_reg", "op_vaesenclast_reg", "op_vaesdec_reg", "op_vaesdeclast_reg", + "op_vaesimc_reg", "op_vaeskeygenassist_reg", "op_vpclmulqdq_10_reg", + "op_vaesenc_mem", "op_vpclmulqdq_11_mem", "op_sse_preserves_ymm_hi", +) + +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python GF(2^8) AES & GF(2) PCLMULQDQ reference model --- + +def _gf_mul(a, b): + p = 0 + for _ in range(8): + if b & 1: + p ^= a + hi = a & 0x80 + a = (a << 1) & 0xFF + if hi: + a ^= 0x1B + b >>= 1 + return p + + +def _gf_inv(a): + if a == 0: + return 0 + for x in range(1, 256): + if _gf_mul(a, x) == 1: + return x + raise ValueError(a) + + +def _rotl8(x, n): + return ((x << n) | (x >> (8 - n))) & 0xFF + + +SBOX = tuple(_gf_inv(i) ^ _rotl8(_gf_inv(i), 1) ^ _rotl8(_gf_inv(i), 2) ^ _rotl8(_gf_inv(i), 3) ^ _rotl8(_gf_inv(i), 4) ^ 0x63 for i in range(256)) +INV_SBOX = tuple(SBOX.index(i) for i in range(256)) + + +def _shift_rows(b, *, inv=False): + idx = (0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3) if inv else (0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11) + return bytes(b[i] for i in idx) + + +def _mix_columns(b, *, inv=False): + out = bytearray(16) + coeffs = (0x0E, 0x0B, 0x0D, 0x09) if inv else (2, 3, 1, 1) + for c in range(4): + col = b[c * 4:(c + 1) * 4] + for r in range(4): + val = 0 + for k in range(4): + coef = coeffs[(k - r) % 4] + val ^= _gf_mul(coef, col[k]) + out[c * 4 + r] = val + return bytes(out) + + +def _xor16(a, b): + return bytes(x ^ y for x, y in zip(a, b)) + + +def ref_aesenc(state, key, *, quirk=None): + if quirk == "aes_no_shiftrows": + sb = bytes(SBOX[x] for x in state) + return _xor16(_mix_columns(sb), key) + if quirk == "aes_no_mixcols": + return ref_aesenclast(state, key) + sr = _shift_rows(state) + sb = bytes(SBOX[x] for x in sr) + return _xor16(_mix_columns(sb), key) + + +def ref_aesenclast(state, key): + sb = bytes(SBOX[x] for x in _shift_rows(state)) + return _xor16(sb, key) + + +def ref_aesdec(state, key): + sb = bytes(INV_SBOX[x] for x in _shift_rows(state, inv=True)) + return _xor16(_mix_columns(sb, inv=True), key) + + +def ref_aesdeclast(state, key): + sb = bytes(INV_SBOX[x] for x in _shift_rows(state, inv=True)) + return _xor16(sb, key) + + +def ref_aesimc(src): + return _mix_columns(src, inv=True) + + +def ref_aeskeygenassist(src, imm8, *, quirk=None): + words = list(struct.unpack("<4I", src)) + def sub_w(w): + return (SBOX[w & 0xFF] | (SBOX[(w >> 8) & 0xFF] << 8) + | (SBOX[(w >> 16) & 0xFF] << 16) | (SBOX[(w >> 24) & 0xFF] << 24)) + def rot_w(w): + return ((w >> 8) | (w << 24)) & 0xFFFFFFFF + s1, s3 = sub_w(words[1]), sub_w(words[3]) + rcon = 0 if quirk == "keygen_drop_rcon" else (imm8 & 0xFF) + if quirk == "keygen_wrong_words": + s1, s3 = sub_w(words[0]), sub_w(words[2]) + return struct.pack("<4I", s1, rot_w(s1) ^ rcon, s3, rot_w(s3) ^ rcon) + + +def ref_pclmulqdq(src1, src2, imm8, *, quirk=None): + a0, a1 = struct.unpack("<2Q", src1) + b0, b1 = struct.unpack("<2Q", src2) + a = a1 if (imm8 & 0x01) else a0 + if quirk == "pclmul_wrong_op2_bit": + b = b1 if (imm8 & 0x02) else b0 + elif quirk == "pclmul_reject_other_bits": + b = 0 if (imm8 & 0xEE) else (b1 if (imm8 & 0x10) else b0) + else: + b = b1 if (imm8 & 0x10) else b0 + res = 0 + for i in range(64): + if (b >> i) & 1: + res ^= (a << i) + return struct.pack("<2Q", res & 0xFFFFFFFFFFFFFFFF, (res >> 64) & 0xFFFFFFFFFFFFFFFF) + + +# --- Guarded aligned memory & DLL helpers --- + +def alloc_guarded(payload, *, align=32): + total = len(GUARD_PRE) + len(payload) + len(GUARD_POST) + align + raw = ctypes.create_string_buffer(total) + base = ctypes.addressof(raw) + aligned_ptr = (base + len(GUARD_PRE) + align - 1) & ~(align - 1) + off = aligned_ptr - base + ctypes.memmove(aligned_ptr - len(GUARD_PRE), GUARD_PRE, len(GUARD_PRE)) + ctypes.memmove(aligned_ptr, payload, len(payload)) + ctypes.memmove(aligned_ptr + len(payload), GUARD_POST, len(GUARD_POST)) + return raw, aligned_ptr, off, len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[off - len(GUARD_PRE):off] != GUARD_PRE or raw[off + length:off + length + len(GUARD_POST)] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_aes_pclmul_avx(lifted_lib): + if hasattr(lifted_lib, "host_has_aes_pclmul_avx"): + lifted_lib.host_has_aes_pclmul_avx.argtypes = [] + lifted_lib.host_has_aes_pclmul_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_aes_pclmul_avx()) + return False + + +def test_vectors(): + fips_a = bytes.fromhex("3243f6a8885a308d313198a2e0370734") + fips_b = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c") + vectors = [ + (b"\x00" * 16, b"\x00" * 16), + (b"\xff" * 16, b"\xff" * 16), + (b"\x00" * 16, b"\xff" * 16), + (b"\xff" * 16, b"\x00" * 16), + (fips_a, fips_b), + (fips_b, fips_a), + (bytes(range(16)), bytes(range(16, 32))), + (struct.pack("<2Q", 0x8000000000000001, 0xFFFFFFFFFFFFFFFF), + struct.pack("<2Q", 0x8000000000000001, 0x0123456789ABCDEF)), + ] + rng = random.Random(0xAE59C1) + for _ in range(16): + vectors.append((rng.randbytes(16), rng.randbytes(16))) + return vectors + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + ld_xmm0 = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld_ymm0 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM0, MemoryOperand(R.RCX)) + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + st_xmm0 = Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("vaesenc_xmm5_xmm1_r8mem", (ld_xmm1, Instruction.create_reg_reg_mem( + Code.VEX_VAESENC_XMM_XMM_XMMM128, R.XMM5, R.XMM1, MemoryOperand(R.R8)), + Instruction.create_mem_reg(Code.VEX_VMOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM5), ret), + "ymm5 = zext256(op_aesenc(low128(ymm1), ld_1004_2));"), + ("aesimc_xmm3_xmm1", (ld_xmm1, Instruction.create_reg_reg(Code.AESIMC_XMM_XMMM128, R.XMM3, R.XMM1), + Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM3), ret), + "set_low128(ymm3, op_aesimc(low128(ymm1)));"), + ("vpclmulqdq_xmm4_xmm1_r8mem", (ld_xmm1, Instruction.create_reg_reg_mem_u32( + Code.VEX_VPCLMULQDQ_XMM_XMM_XMMM128_IMM8, R.XMM4, R.XMM1, MemoryOperand(R.R8), 0x11), + Instruction.create_mem_reg(Code.VEX_VMOVDQA_XMMM128_XMM, MemoryOperand(R.R8), R.XMM4), ret), + "ymm4 = zext256(op_pclmulqdq(low128(ymm1), ld_1004_2, 0x11u));"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_aes = Instruction.create_reg_mem(Code.AESENC_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX)) + seg_aes.segment_prefix = R.GS + evex_vaes = Instruction.create_reg_reg_reg(Code.EVEX_VAESENC_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2) + + unit_cases = [ + # VEX.256 compute rejections + ("vex256_vaesenc", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg( + Code.VEX_VAESENC_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported VEX.256 instruction"), + ("vex256_vaesdeclast", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg( + Code.VEX_VAESDECLAST_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported VEX.256 instruction"), + ("vex256_vpclmulqdq", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg_u32( + Code.VEX_VPCLMULQDQ_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0), ret), "unsupported VEX.256 instruction"), + ("vex256_vpaddq", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg( + Code.VEX_VPADDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported VEX.256 instruction"), + # EVEX / KeyLocker / out-of-scope + ("evex_vaesenc", (ld_xmm0, ld_xmm1, evex_vaes, ret), "unsupported EVEX instruction"), + ("aes128kl", (ld_xmm0, Instruction.create_reg_mem( + Code.AESENC128KL_XMM_M384, R.XMM0, MemoryOperand(R.RCX)), ret), "unsupported instruction"), + ("xop_vpcmov", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_reg_reg( + Code.XOP_VPCMOV_XMM_XMM_XMMM128_XMM, R.XMM0, R.XMM1, R.XMM1, R.XMM0), ret), "unsupported XOP instruction"), + # Nonvolatile XMM6..15 / YMM6..15 + ("nonvol_xmm6", (Instruction.create_reg_mem( + Code.MOVDQU_XMM_XMMM128, R.XMM6, MemoryOperand(R.RCX)), ret), "nonvolatile vector register"), + ("nonvol_ymm7", (Instruction.create_reg_mem( + Code.VEX_VMOVDQU_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret), "nonvolatile vector register"), + ("nonvol_xmm15_aes", (ld_xmm0, Instruction.create_reg_reg( + Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM15), ret), "nonvolatile vector register"), + # Undefined XMM / YMM reads + ("undef_xmm2_vaesenc", (ld_xmm1, Instruction.create_reg_reg_reg( + Code.VEX_VAESENC_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret), "undefined vector register xmm2"), + ("undef_xmm0_aesenc_dst", (ld_xmm1, Instruction.create_reg_reg( + Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM1), ret), "undefined vector register xmm0"), + ("undef_xmm0_pclmul_dst", (ld_xmm1, Instruction.create_reg_reg_u32( + Code.PCLMULQDQ_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), ret), "undefined vector register xmm0"), + ("undef_ymm0_hi_after_sse", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg( + Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM1), + Instruction.create_mem_reg(Code.VEX_VMOVDQU_YMMM256_YMM, MemoryOperand(R.R8), R.YMM0), ret), + "undefined vector register ymm0"), + # Bad memory operands & non-[r8] stores + ("displaced_aesenc_rdx", (ld_xmm0, Instruction.create_reg_mem( + Code.AESENC_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX, displ=16, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_store_r8", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8, displ=16, displ_size=1), R.XMM0), ret), + "displaced memory operand"), + ("indexed_vaesdec", (ld_xmm1, Instruction.create_reg_reg_mem( + Code.VEX_VAESDEC_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.RCX, R.RDX, 1)), ret), + "SIB index memory operand"), + ("rip_rel_aesimc", (Instruction.create_reg_mem( + Code.AESIMC_XMM_XMMM128, R.XMM0, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RBX)), ret), "nonvolatile GPR base"), + ("bad_base_r9", (Instruction.create_reg_mem( + Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.R9)), ret), "bad base register"), + ("non_r8_store_rcx", (ld_xmm0, Instruction.create_mem_reg( + Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.RCX), R.XMM0), ret), "non-r8 store memory operand"), + ("non_r8_store_ymm_rdx", (ld_ymm0, Instruction.create_mem_reg( + Code.VEX_VMOVDQU_YMMM256_YMM, MemoryOperand(R.RDX), R.YMM0), ret), "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_aesenc", (ld_xmm0, seg_aes, ret), "unsupported instruction prefix"), + ("branch_jmp", (ld_xmm0, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (ld_xmm0, st_xmm0), "missing terminal ret"), + ("trailing_after_ret", (ld_xmm0, st_xmm0, ret, ld_xmm1), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_dst_alias_src") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from("<I", records, i)[0] == entry) + pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) + max_len = struct.unpack_from("<I", records, rec_idx + 4)[0] - entry + + by_label = {label: (encode_seq(*seq), reason) for label, seq, reason in unit_cases} + pe_labels = ( + "vex256_vaesenc", + "vex256_vpclmulqdq", + "evex_vaesenc", + "nonvol_xmm6", + "undef_xmm2_vaesenc", + "displaced_aesenc_rdx", + "non_r8_store_rcx", + "branch_jmp", + "seg_prefix_aesenc", + ) + lifter_script = Path(__file__).resolve().parents[2] / "tools" / "cpu_aes_pclmul_aot.py" + with TemporaryDirectory() as folder: + tmp = Path(folder) + patched = tmp / "patched.dll" + out_cpp = tmp / "rejected.cpp" + for label in pe_labels: + patch, reason = by_label[label] + if len(patch) > max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("<I", damaged, pdata_end_off, entry + len(patch)) + patched.write_bytes(damaged) + try: + translate(patched, ["op_dst_alias_src"]) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"pe_{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"pe_{label}: PE translate accepted rejected patch") + + proc = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(patched), "op_dst_alias_src", str(out_cpp)], + capture_output=True, + text=True, + ) + if proc.returncode != 1 or "Traceback" in proc.stderr or "unsupported instruction prefix" not in proc.stderr: + raise AssertionError(f"CLI rejection unexpected: rc={proc.returncode}, stderr={proc.stderr!r}") + if out_cpp.exists() or list(tmp.glob("*.tmp")): + raise AssertionError("CLI failure left behind output or temp file") + + bad_dir = tmp / "dir_out" + bad_dir.mkdir() + proc_dir = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(original_path), "op_aesenc_reg", str(bad_dir)], + capture_output=True, + text=True, + ) + if proc_dir.returncode != 1 or "Traceback" in proc_dir.stderr or "directory" not in proc_dir.stderr: + raise AssertionError(f"CLI dir rejection unexpected: rc={proc_dir.returncode}, stderr={proc_dir.stderr!r}") + + print( + f"rejections passed: {len(alt_accept)} alt + {len(unit_cases)} IR + " + f"{len(raw_cases)} raw + {len(pe_labels)} PE-patched + CLI" + ) + + +# --- Positive, FIPS-197, YMM[255:128], altered, mutant, and /O2 verification --- + +def _expected_16(name, a, b, c=b"\x00" * 16): + if name in ("op_aesenc_reg", "op_aesenc_mem", "op_vaesenc_reg", "op_vaesenc_mem"): + return ref_aesenc(a, b) + if name in ("op_aesenclast_reg", "op_aesenclast_mem", "op_vaesenclast_reg", "op_vaesenclast_mem"): + return ref_aesenclast(a, b) + if name in ("op_aesdec_reg", "op_aesdec_mem", "op_vaesdec_reg", "op_vaesdec_mem"): + return ref_aesdec(a, b) + if name in ("op_aesdeclast_reg", "op_aesdeclast_mem", "op_vaesdeclast_reg", "op_vaesdeclast_mem"): + return ref_aesdeclast(a, b) + if name in ("op_aesimc_reg", "op_aesimc_mem", "op_vaesimc_reg", "op_vaesimc_mem"): + return ref_aesimc(a) + if name == "op_aeskeygenassist_reg": + return ref_aeskeygenassist(a, 0x1B) + if name == "op_aeskeygenassist_mem": + return ref_aeskeygenassist(a, 0x80) + if name == "op_vaeskeygenassist_reg": + return ref_aeskeygenassist(a, 0x36) + if name == "op_vaeskeygenassist_mem": + return ref_aeskeygenassist(a, 0xFF) + if name == "op_pclmulqdq_00_reg": + return ref_pclmulqdq(a, b, 0x00) + if name in ("op_pclmulqdq_11_reg", "op_vpclmulqdq_11_mem"): + return ref_pclmulqdq(a, b, 0x11) + if name in ("op_pclmulqdq_ignore_bits_reg", "op_pclmulqdq_01_mem"): + return ref_pclmulqdq(a, b, 0x01) + if name in ("op_vpclmulqdq_10_reg", "op_vpclmulqdq_ignore_bits_reg"): + return ref_pclmulqdq(a, b, 0x10) + if name == "op_r8_source_then_store": + x0 = ref_aesenc(a, c) + return ref_pclmulqdq(x0, b, 0x00) + if name == "op_dst_alias_src": + x0 = ref_aesenc(a, a) + x0 = ref_aesimc(x0) + x0 = ref_aeskeygenassist(x0, 0x01) + return ref_pclmulqdq(x0, x0, 0x01) + raise KeyError(name) + + +def verify_suite(fns, label, vectors): + total = 0 + + # 1) All 16-byte AES-NI & PCLMULQDQ register and memory forms. + ops_16 = ( + "op_aesenc_reg", "op_aesenclast_reg", "op_aesdec_reg", "op_aesdeclast_reg", + "op_aesimc_reg", "op_aeskeygenassist_reg", + "op_pclmulqdq_00_reg", "op_pclmulqdq_11_reg", "op_pclmulqdq_ignore_bits_reg", + "op_aesenc_mem", "op_aesenclast_mem", "op_aesdec_mem", "op_aesdeclast_mem", + "op_aesimc_mem", "op_aeskeygenassist_mem", "op_pclmulqdq_01_mem", + "op_vaesenc_reg", "op_vaesenclast_reg", "op_vaesdec_reg", "op_vaesdeclast_reg", + "op_vaesimc_reg", "op_vaeskeygenassist_reg", + "op_vpclmulqdq_10_reg", "op_vpclmulqdq_ignore_bits_reg", + "op_vaesenc_mem", "op_vaesenclast_mem", "op_vaesdec_mem", "op_vaesdeclast_mem", + "op_vaesimc_mem", "op_vaeskeygenassist_mem", "op_vpclmulqdq_11_mem", + "op_dst_alias_src", + ) + for name in ops_16: + fn = fns[name] + for a, b in vectors: + ba, pa, oa, la = alloc_guarded(a) + bb, pb, ob, lb = alloc_guarded(b) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 16) + fn(pa, pb, po) + read_guarded(ba, oa, la, f"{name}_a") + read_guarded(bb, ob, lb, f"{name}_b") + got = read_guarded(bo, oo, lo, f"{name}_out") + want = _expected_16(name, a, b) + if got != want: + raise AssertionError(f"{label} {name}: got={got.hex()} != want={want.hex()}") + total += 1 + + # 2) FIPS-197 Appendix B full AES-128 cipher & inverse cipher round check. + fips_pt = bytes.fromhex("3243f6a8885a308d313198a2e0370734") + fips_rk0 = bytes.fromhex("2b7e151628aed2a6abf7158809cf4f3c") + fips_ct = bytes.fromhex("3925841d02dc09fbdc118597196a0b32") + rcons = (0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36) + rks = [fips_rk0] + for rcon in rcons: + prev = list(struct.unpack("<4I", rks[-1])) + kg = struct.unpack("<4I", ref_aeskeygenassist(rks[-1], rcon))[3] + k0 = prev[0] ^ kg + k1 = prev[1] ^ k0 + k2 = prev[2] ^ k1 + k3 = prev[3] ^ k2 + rks.append(struct.pack("<4I", k0, k1, k2, k3)) + state = _xor16(fips_pt, rks[0]) + for r in range(1, 10): + ba, pa, oa, la = alloc_guarded(state) + bb, pb, ob, lb = alloc_guarded(rks[r]) + bo, po, oo, lo = alloc_guarded(b"\x00" * 16) + fns["op_vaesenc_reg"](pa, pb, po) + state = read_guarded(bo, oo, lo, f"fips_enc_{r}") + ba, pa, oa, la = alloc_guarded(state) + bb, pb, ob, lb = alloc_guarded(rks[10]) + bo, po, oo, lo = alloc_guarded(b"\x00" * 16) + fns["op_vaesenclast_reg"](pa, pb, po) + ct = read_guarded(bo, oo, lo, "fips_enclast") + if ct != fips_ct: + raise AssertionError(f"{label} FIPS-197 encrypt mismatch: {ct.hex()} != {fips_ct.hex()}") + total += 1 + + # Inverse cipher round-trip using AESIMC + VAESDEC + VAESDECLAST. + dec_state = _xor16(ct, rks[10]) + for r in range(9, 0, -1): + bi, pi, oi, li = alloc_guarded(rks[r]) + bik, pik, oik, lik = alloc_guarded(b"\x00" * 16) + fns["op_vaesimc_reg"](pi, 0, pik) + inv_rk = read_guarded(bik, oik, lik, f"fips_imc_{r}") + ba, pa, oa, la = alloc_guarded(dec_state) + bb, pb, ob, lb = alloc_guarded(inv_rk) + bo, po, oo, lo = alloc_guarded(b"\x00" * 16) + fns["op_vaesdec_reg"](pa, pb, po) + dec_state = read_guarded(bo, oo, lo, f"fips_dec_{r}") + ba, pa, oa, la = alloc_guarded(dec_state) + bb, pb, ob, lb = alloc_guarded(rks[0]) + bo, po, oo, lo = alloc_guarded(b"\x00" * 16) + fns["op_vaesdeclast_reg"](pa, pb, po) + pt = read_guarded(bo, oo, lo, "fips_declast") + if pt != fips_pt: + raise AssertionError(f"{label} FIPS-197 decrypt mismatch: {pt.hex()} != {fips_pt.hex()}") + total += 1 + + # 3) YMM[255:128] preservation (SSE), zeroing (VEX.128), and vzeroupper. + hi_sentinel = bytes(range(0x10, 0x20)) + for a, b in vectors[:12]: + ymm_in = a + hi_sentinel + ba, pa, oa, la = alloc_guarded(ymm_in) + bb, pb, ob, lb = alloc_guarded(b) + bo1, po1, oo1, lo1 = alloc_guarded(b"\x5a" * 32) + fns["op_sse_preserves_ymm_hi"](pa, pb, po1) + read_guarded(ba, oa, la, "sse_hi_a") + read_guarded(bb, ob, lb, "sse_hi_b") + got_sse = read_guarded(bo1, oo1, lo1, "sse_hi_out") + want_sse = ref_aesenc(a, b) + hi_sentinel + if got_sse != want_sse: + raise AssertionError(f"{label} op_sse_preserves_ymm_hi: {got_sse.hex()} != {want_sse.hex()}") + total += 1 + + bo2, po2, oo2, lo2 = alloc_guarded(b"\x5a" * 32) + fns["op_vex_zeroes_ymm_hi"](pa, pb, po2) + got_vex = read_guarded(bo2, oo2, lo2, "vex_hi_out") + want_vex = ref_aesenc(a, b) + (b"\x00" * 16) + if got_vex != want_vex: + raise AssertionError(f"{label} op_vex_zeroes_ymm_hi: {got_vex.hex()} != {want_vex.hex()}") + total += 1 + + bo3, po3, oo3, lo3 = alloc_guarded(b"\x5a" * 32) + fns["op_vzeroupper_clears_ymm_hi"](pa, 0, po3) + got_vz = read_guarded(bo3, oo3, lo3, "vzeroupper_out") + want_vz = a + (b"\x00" * 16) + if got_vz != want_vz: + raise AssertionError(f"{label} op_vzeroupper_clears_ymm_hi: {got_vz.hex()} != {want_vz.hex()}") + total += 1 + + # 4) [r8] source-then-store. + for i in range(len(vectors)): + a, b = vectors[i] + c = vectors[(i + 5) % len(vectors)][0] + ba, pa, oa, la = alloc_guarded(a) + bb, pb, ob, lb = alloc_guarded(b) + br, pr, or_, lr = alloc_guarded(c) + fns["op_r8_source_then_store"](pa, pb, pr) + read_guarded(ba, oa, la, "r8_src_a") + read_guarded(bb, ob, lb, "r8_src_b") + got_mem = read_guarded(br, or_, lr, "r8_src_out") + want = _expected_16("op_r8_source_then_store", a, b, c) + if got_mem != want: + raise AssertionError(f"{label} op_r8_source_then_store: got={got_mem.hex()} != exp={want.hex()}") + total += 1 + + # 5) Discarded faulting m128 read must fault on NULL rdx even under /O2. + a0, _ = vectors[0] + ba, pa, oa, la = alloc_guarded(a0) + bd, pd, od, ld = alloc_guarded(vectors[1][0]) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 16) + fns["op_aes_pclmul_discarded_read"](pa, pd, po) + read_guarded(bd, od, ld, "discarded_valid") + assert read_guarded(bo, oo, lo, "discarded_out") == a0 + try: + fns["op_aes_pclmul_discarded_read"](pa, 0, po) + except OSError as exc: + if "access violation reading" not in str(exc).lower(): + raise AssertionError(f"{label} discarded_read(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{label} op_aes_pclmul_discarded_read(NULL) dropped faulting m128 read") + + return total + + +def _altered_expected(name, a, b): + if name in ("op_aesenc_reg", "op_vaesenclast_reg"): + return ref_aesenclast(a, b) if name == "op_aesenc_reg" else ref_aesdeclast(a, b) + if name == "op_aesenclast_reg": + return ref_aesenc(a, b) + if name == "op_aesdec_reg": + return ref_aesdeclast(a, b) + if name == "op_aesdeclast_reg": + return ref_aesdec(a, b) + if name in ("op_aesimc_reg", "op_vaesimc_reg"): + return a + if name == "op_aeskeygenassist_reg": + return ref_aeskeygenassist(a, 0x1C) + if name == "op_pclmulqdq_00_reg": + return ref_pclmulqdq(a, b, 0x11) + if name == "op_pclmulqdq_11_reg": + return ref_pclmulqdq(a, b, 0x00) + if name in ("op_vaesenc_reg", "op_vaesenc_mem"): + return ref_aesdec(a, b) + if name == "op_vaesdec_reg": + return ref_aesenc(a, b) + if name == "op_vaesdeclast_reg": + return ref_aesenclast(a, b) + if name == "op_vaeskeygenassist_reg": + return ref_aeskeygenassist(a, 0x37) + if name == "op_vpclmulqdq_10_reg": + return ref_pclmulqdq(a, b, 0x01) + if name == "op_vpclmulqdq_11_mem": + return ref_pclmulqdq(a, b, 0x00) + if name == "op_sse_preserves_ymm_hi": + return ref_aesenc(a, b) + (b"\x00" * 16) + raise KeyError(name) + + +def check_altered_and_mutants(lifted_fns, alt_lifted_fns, vectors): + diverged = 0 + hi_sentinel = bytes(range(0x10, 0x20)) + for name in ALTERED_EXPORTS: + is_ymm = name == "op_sse_preserves_ymm_hi" + diffs = 0 + for a, b in vectors[:8]: + buf_a = (a + hi_sentinel) if is_ymm else a + ba, pa, oa, la = alloc_guarded(buf_a) + bb, pb, ob, lb = alloc_guarded(b) + out_len = 32 if is_ymm else 16 + bo_a, po_a, oo_a, lo_a = alloc_guarded(b"\x5a" * out_len) + bo_o, po_o, oo_o, lo_o = alloc_guarded(b"\x5a" * out_len) + alt_lifted_fns[name](pa, pb, po_a) + lifted_fns[name](pa, pb, po_o) + got_al = read_guarded(bo_a, oo_a, lo_a, f"alt_{name}") + got_ol = read_guarded(bo_o, oo_o, lo_o, f"orig_{name}") + want_alt = _altered_expected(name, a, b) + if got_al != want_alt: + raise AssertionError(f"altered_lifted {name}: {got_al.hex()} != {want_alt.hex()}") + diffs += got_al != got_ol + if not diffs: + raise AssertionError(f"ALTER_AES_PCLMUL failed to diverge on {name}") + diverged += 1 + + # Mutant models targeting critical AES/PCLMUL SDM details. + mutant_specs = ( + ("op_aesenc_reg", lambda a, b: ref_aesenc(a, b, quirk="aes_no_shiftrows")), + ("op_aesenc_reg", lambda a, b: ref_aesenc(a, b, quirk="aes_no_mixcols")), + ("op_aeskeygenassist_reg", lambda a, b: ref_aeskeygenassist(a, 0x1B, quirk="keygen_drop_rcon")), + ("op_aeskeygenassist_reg", lambda a, b: ref_aeskeygenassist(a, 0x1B, quirk="keygen_wrong_words")), + ("op_vpclmulqdq_ignore_bits_reg", lambda a, b: ref_pclmulqdq(a, b, 0xFC, quirk="pclmul_wrong_op2_bit")), + ("op_pclmulqdq_ignore_bits_reg", lambda a, b: ref_pclmulqdq(a, b, 0xEF, quirk="pclmul_reject_other_bits")), + ) + for name, mut_fn in mutant_specs: + fn = lifted_fns[name] + caught = 0 + for a, b in vectors[:8]: + ba, pa, oa, la = alloc_guarded(a) + bb, pb, ob, lb = alloc_guarded(b) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 16) + fn(pa, pb, po) + got = read_guarded(bo, oo, lo, f"mut_{name}") + if got != mut_fn(a, b): + caught += 1 + if not caught: + raise AssertionError(f"mutant on {name} survived") + + return diverged, len(mutant_specs) + + +def compile_o2_and_verify(original_path, cxx_path, vectors): + source_text, _ = translate(original_path, list(EXPORTS)) + if "<wmmintrin.h>" in source_text or "_mm_aes" in source_text or "_mm_clmul" in source_text: + raise AssertionError("translated C++ must be pure portable C++ without AES/PCLMUL intrinsics") + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "aes_pclmul_aot_o2.cpp" + dll_path = tmp / "aes_pclmul_aot_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'aes_pclmul_aot_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_suite(o2_fns, "lifted_o2", vectors) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + + # 1) Lift + rejections + portable lifted + mutants + /O2 run unconditionally BEFORE CPUID skip. + check_rejections(original_path) + + vectors = test_vectors() + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_suite(lifted_fns, "lifted", vectors) + diverged, mutants = check_altered_and_mutants(lifted_fns, alt_lifted_fns, vectors) + o2_cases = compile_o2_and_verify(original_path, cxx_path, vectors) + + if not host_has_aes_pclmul_avx(lifted_lib): + print( + f"portable lifted passed ({lifted_cases} lifted + {o2_cases} /O2 cases, " + f"{diverged} ALTER_AES_PCLMUL + {mutants} mutants); " + "Host lacks CPUID.01H:ECX[1,25,27,28]/XGETBV[2:1] (PCLMULQDQ+AES+AVX), skipping native differential check" + ) + sys.exit(77) + + # 2) Native AES-NI + PCLMULQDQ + AVX hardware differential checks. + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + try: + native_cases = verify_suite(orig_fns, "native", vectors) + hi_sentinel = bytes(range(0x10, 0x20)) + for name in ALTERED_EXPORTS: + is_ymm = name == "op_sse_preserves_ymm_hi" + out_len = 32 if is_ymm else 16 + for a, b in vectors[:8]: + buf_a = (a + hi_sentinel) if is_ymm else a + ba, pa, oa, la = alloc_guarded(buf_a) + bb, pb, ob, lb = alloc_guarded(b) + bn, pn, on, ln = alloc_guarded(b"\x5a" * out_len) + bl, pl, ol, ll = alloc_guarded(b"\x5a" * out_len) + alt_fns[name](pa, pb, pn) + alt_lifted_fns[name](pa, pb, pl) + got_an = read_guarded(bn, on, ln, f"alt_nat_{name}") + got_al = read_guarded(bl, ol, ll, f"alt_lift_{name}") + if got_an != got_al: + raise AssertionError(f"altered native vs lifted {name}: {got_an.hex()} != {got_al.hex()}") + finally: + orig_fns.clear() + alt_fns.clear() + unload_lib(orig_lib) + unload_lib(alt_lib) + finally: + lifted_fns.clear() + alt_lifted_fns.clear() + unload_lib(lifted_lib) + unload_lib(alt_lifted_lib) + + record_covered_forms(original_path) + print( + f"aes_pclmul_aot passed: {native_cases} native + {lifted_cases} lifted + {o2_cases} /O2 cases " + f"across {len(EXPORTS)} exports; ALTER_AES_PCLMUL diverged on {diverged} exports + {mutants} mutants caught" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/amd_monitor_rdpru_aot.asm b/tests/cpu/amd_monitor_rdpru_aot.asm new file mode 100644 index 0000000000..13927f4c6d --- /dev/null +++ b/tests/cpu/amd_monitor_rdpru_aot.asm @@ -0,0 +1,303 @@ +; coverage: record cpu_aot_amd_monitor_rdpru +; Source-owned differential fixture for AMD Zen 2 user-mode MONITORX, MWAITX, and RDPRU. +; RCX = uint64_t input_a (preset value or caller-owned buffer pointer) +; RDX = uint64_t input_b (preset value or caller-owned buffer pointer) +; R8 = void* output (64-byte caller-owned output buffer) +; RAX = uint64_t return value +; Note: ML64 emits MONITORX (0F 01 FA), MWAITX (0F 01 FB), and RDPRU (0F 01 FD) via +; exact opcode bytes where older MASM lacks mnemonics, decoded natively by iced-x86. +.code + +; RDPRU with ECX=0 (MPERF): zero-extends EAX->RAX & EDX->RDX, preserves RCX and RFLAGS. +; Output [r8]: +0=RAX, +8=RDX, +16=RCX, +24=CF|(ZF<<1)|(SF<<2)|(OF<<3). Returns (RDX<<32)|RAX. +op_rdpru_mperf PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + mov rax, -1 + mov rdx, -1 +IFDEF ALTER_AMD_EXT + mov rcx, 1 +ELSE + mov rcx, 0 +ENDIF + add r9, r10 + db 0fh, 01h, 0fdh ; rdpru + mov qword ptr [r8], rax + mov qword ptr [r8+8], rdx + mov qword ptr [r8+16], rcx + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+24], rcx + shl rdx, 32 + or rax, rdx + ret +op_rdpru_mperf ENDP + +; RDPRU with ECX=1 (APERF): same ABI and flag/register preservation checks. +op_rdpru_aperf PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + mov rax, -1 + mov rdx, -1 +IFDEF ALTER_AMD_EXT + mov rcx, 0 +ELSE + mov rcx, 1 +ENDIF + cmp r9, r10 + db 0fh, 01h, 0fdh ; rdpru + mov qword ptr [r8], rax + mov qword ptr [r8+8], rdx + mov qword ptr [r8+16], rcx + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+24], rcx + shl rdx, 32 + or rax, rdx + ret +op_rdpru_aperf ENDP + +; Two consecutive RDPRU reads: verifies monotonicity and prevents /O2 CSE merging. +; Output [r8]: +0=first_rax, +8=first_rdx, +16=second_rax, +24=second_rdx, +32=rcx. +op_rdpru_twice PROC FRAME + .endprolog + xor ecx, ecx + db 0fh, 01h, 0fdh ; rdpru (1) + mov qword ptr [r8], rax + mov qword ptr [r8+8], rdx +IFDEF ALTER_AMD_EXT + mov ecx, 1 +ENDIF + db 0fh, 01h, 0fdh ; rdpru (2) + mov qword ptr [r8+16], rax + mov qword ptr [r8+24], rdx + mov qword ptr [r8+32], rcx + shl rdx, 32 + or rax, rdx + ret +op_rdpru_twice ENDP + +; Overwritten RDPRU read: prevents /O2 DCE of the counter read while returning constant 7. +op_rdpru_unused PROC FRAME + .endprolog + xor ecx, ecx + db 0fh, 01h, 0fdh ; rdpru +IFDEF ALTER_AMD_EXT + mov eax, 42 +ELSE + mov eax, 7 +ENDIF + xor edx, edx + ret +op_rdpru_unused ENDP + +; MONITORX on [r8] + triggering store + MWAITX (ECX=0, EAX=0): preserves GPRs, RFLAGS, and stores. +; Output [r8]: +0=rcx, +8=rdx, +16=rax_hint, +24=flags_mask, +32=ecx_ext. +op_monitorx_mwaitx_r8 PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + lea rax, [r8] + xor ecx, ecx + xor edx, edx + db 0fh, 01h, 0fah ; monitorx (arms [r8], ECX=0, EDX=0) + mov qword ptr [r8], r9 ; observable store (also wakes monitored line on AMD hardware) + mov eax, 0 + mov ecx, 0 + cmp r9, r10 ; preset CF/ZF/SF/OF before MWAITX + db 0fh, 01h, 0fbh ; mwaitx (hints=0, ext=0; preserves GPRs & RFLAGS) +IFDEF ALTER_AMD_EXT + mov qword ptr [r8+8], r9 +ELSE + mov qword ptr [r8+8], r10 +ENDIF + mov qword ptr [r8+16], rax + mov qword ptr [r8+32], rcx + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+24], rcx + mov rax, rcx + ret +op_monitorx_mwaitx_r8 ENDP + +; MONITORX + MWAITX with C1 hint (EAX=0x10) and interrupt-break extension (ECX=1, no timer bit). +op_monitorx_mwaitx_intbrk PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + lea rax, [r8] + mov ecx, 0 + mov edx, 0 + db 0fh, 01h, 0fah ; monitorx + mov qword ptr [r8], r9 +IFDEF ALTER_AMD_EXT + mov eax, 20h +ELSE + mov eax, 10h +ENDIF + mov ecx, 1 ; ECX[0]=1 interrupt-break (ECX[1]=0 no timer/EBX) + add r9, r10 + db 0fh, 01h, 0fbh ; mwaitx + mov qword ptr [r8+8], rax + mov qword ptr [r8+16], rcx + mov qword ptr [r8+24], rdx + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+32], rcx + mov rax, rcx + ret +op_monitorx_mwaitx_intbrk ENDP + +; MONITORX on flat [rcx] and [rdx] pointers; verifies pre/post store ordering and NULL fault ordering. +op_monitorx_rcx_rdx PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + mov qword ptr [r8], r10 ; pre-MONITORX store + lea rax, [rcx] + mov ecx, 0 + mov edx, 0 + cmp r9, r10 + db 0fh, 01h, 0fah ; monitorx on [rcx] (faults if rcx == NULL) + mov qword ptr [r8+8], rax + mov rax, r10 ; flat pointer copy of original [rdx] + db 0fh, 01h, 0fah ; monitorx on [rdx] (faults if rdx == NULL) + mov qword ptr [r8+16], rax + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+24], rcx + mov rax, rcx + ret +op_monitorx_rcx_rdx ENDP + +; 32-bit ADD flag path preserved across RDPRU (ECX=0); upper 32 bits of inputs ignored. +op_add32_rdpru PROC FRAME + .endprolog + mov r9d, ecx + mov r10d, edx + mov rax, -1 + mov rdx, -1 + mov ecx, 0 + add r9d, r10d + db 0fh, 01h, 0fdh ; rdpru + mov qword ptr [r8], rax + mov qword ptr [r8+8], rdx + mov qword ptr [r8+16], rcx + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+24], rcx + shl rdx, 32 + or rax, rdx + ret +op_add32_rdpru ENDP + +; 32-bit CMP flag path preserved across MONITORX/MWAITX; upper 32 bits of inputs ignored. +op_cmp32_mwaitx PROC FRAME + .endprolog + mov r9d, ecx + mov r10d, edx + lea rax, [r8] + xor ecx, ecx + xor edx, edx + db 0fh, 01h, 0fah ; monitorx + mov qword ptr [r8], r9 + mov eax, 0 + mov ecx, 0 + cmp r9d, r10d + db 0fh, 01h, 0fbh ; mwaitx + mov qword ptr [r8+8], rax + mov qword ptr [r8+16], rcx + mov ecx, 0 + mov r9d, 0 + mov r10d, 0 + mov r11d, 0 + setb cl + sete r9b + sets r10b + seto r11b + shl r9d, 1 + or ecx, r9d + shl r10d, 2 + or ecx, r10d + shl r11d, 3 + or ecx, r11d + mov qword ptr [r8+24], rcx + mov rax, rcx + ret +op_cmp32_mwaitx ENDP + +END diff --git a/tests/cpu/amd_monitor_rdpru_aot.def b/tests/cpu/amd_monitor_rdpru_aot.def new file mode 100644 index 0000000000..d49aaae6aa --- /dev/null +++ b/tests/cpu/amd_monitor_rdpru_aot.def @@ -0,0 +1,10 @@ +EXPORTS + op_rdpru_mperf + op_rdpru_aperf + op_rdpru_twice + op_rdpru_unused + op_monitorx_mwaitx_r8 + op_monitorx_mwaitx_intbrk + op_monitorx_rcx_rdx + op_add32_rdpru + op_cmp32_mwaitx diff --git a/tests/cpu/amd_monitor_rdpru_aot_check.py b/tests/cpu/amd_monitor_rdpru_aot_check.py new file mode 100644 index 0000000000..2ced3ef8e4 --- /dev/null +++ b/tests/cpu/amd_monitor_rdpru_aot_check.py @@ -0,0 +1,655 @@ +"""Differential, /O2-barrier, fault-ordering, mutation, rejection, and AMD CPUID checks +for AMD MONITORX, MWAITX, and RDPRU AOT lifting (`tools/cpu_amd_monitor_rdpru_aot.py`). + +Unconditional checks (translator acceptance/rejections, Debug & /O2 lifted execution, +/O2 disassembly anti-CSE/anti-DCE verification, NULL-pointer MONITORX fault ordering, +ALTER_AMD_EXT altered-lifted checks, and mutant controls) run on every host BEFORE +checking AMD CPUID Fn8000_0001:ECX[29] (MWAITX) and Fn8000_0008:EBX[4] (RDPRU). +On non-AMD or pre-Zen2 hosts lacking either feature, the script exits 77 without +writing FORM_COVERAGE_RECORD (matching repository form_coverage conventions). +""" + +import ctypes +import os +from pathlib import Path +import struct +import sys + +from iced_x86 import ( + Code, + Decoder, + Encoder, + FlowControl, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +import cpu_amd_monitor_rdpru_aot # noqa: E402 +from cpu_amd_monitor_rdpru_aot import lift_code # noqa: E402 + +EXPORTS = ( + "op_rdpru_mperf", + "op_rdpru_aperf", + "op_rdpru_twice", + "op_rdpru_unused", + "op_monitorx_mwaitx_r8", + "op_monitorx_mwaitx_intbrk", + "op_monitorx_rcx_rdx", + "op_add32_rdpru", + "op_cmp32_mwaitx", +) + +ALTERED_EXPORTS = ( + "op_rdpru_mperf", + "op_rdpru_aperf", + "op_rdpru_twice", + "op_rdpru_unused", + "op_monitorx_mwaitx_r8", + "op_monitorx_mwaitx_intbrk", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) +OUT_BYTES = 64 +SENTINEL64 = 0x5A5A5A5A5A5A5A5A + +# Pairs exercising all CF/ZF/SF/OF combinations under both ADD and CMP. +FLAG_PAIRS = ( + (0, 0), + (1, 1), + (5, 9), + (9, 5), + (0x7FFFFFFFFFFFFFFF, 1), + (0x8000000000000000, 0x8000000000000000), + (0xFFFFFFFFFFFFFFFF, 1), + (0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF), + (0x8000000000000000, 1), + (1, 0x8000000000000000), +) + +FLAG_PAIRS_32 = ( + (0, 0), + (1, 1), + (5, 9), + (9, 5), + (0x7FFFFFFF, 1), + (0x80000000, 0x80000000), + (0xFFFFFFFF, 1), + (0xFFFFFFFF, 0xFFFFFFFF), + (0x80000000, 1), + (1, 0x80000000), + (0x100000005, 0x200000009), + (0x900000009, 0x100000005), +) + + +def add32_flags(a, b): + a &= MASK32 + b &= MASK32 + r = (a + b) & MASK32 + cf = 1 if (a + b) > MASK32 else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r >> 31) else 0 + of = 1 if (((~(a ^ b)) & (a ^ r)) >> 31) & 1 else 0 + return cf | (zf << 1) | (sf << 2) | (of << 3) + + +def cmp32_flags(a, b): + a &= MASK32 + b &= MASK32 + r = (a - b) & MASK32 + cf = 1 if a < b else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r >> 31) else 0 + of = 1 if (((a ^ b) & (a ^ r)) >> 31) & 1 else 0 + return cf | (zf << 1) | (sf << 2) | (of << 3) + + +def add64_flags(a, b): + a &= MASK64 + b &= MASK64 + r = (a + b) & MASK64 + cf = 1 if (a + b) > MASK64 else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r >> 63) else 0 + of = 1 if (((~(a ^ b)) & (a ^ r)) >> 63) & 1 else 0 + return cf | (zf << 1) | (sf << 2) | (of << 3) + + +def cmp64_flags(a, b): + a &= MASK64 + b &= MASK64 + r = (a - b) & MASK64 + cf = 1 if a < b else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r >> 63) else 0 + of = 1 if (((a ^ b) & (a ^ r)) >> 63) & 1 else 0 + return cf | (zf << 1) | (sf << 2) | (of << 3) + + +def alloc_guarded(payload): + size = 32 + len(GUARD_PRE) + len(payload) + len(GUARD_POST) + raw = ctypes.create_string_buffer(size) + base = ctypes.addressof(raw) + data_addr = (base + len(GUARD_PRE) + 15) & ~15 + pre_off = (data_addr - len(GUARD_PRE)) - base + data_off = data_addr - base + post_off = data_off + len(payload) + raw[pre_off:data_off] = GUARD_PRE + raw[data_off:post_off] = payload + raw[post_off:post_off + len(GUARD_POST)] = GUARD_POST + return raw, pre_off, data_off, post_off, data_addr + + +def call_export(fn, a_u64, b_u64): + raw, pre, off, post, addr = alloc_guarded(b"\x5a" * OUT_BYTES) + ret = fn(a_u64, b_u64, addr) + assert raw.raw[pre:off] == GUARD_PRE and raw.raw[post:post + 16] == GUARD_POST, "output guards corrupted" + slots = struct.unpack("<8Q", raw.raw[off:off + OUT_BYTES]) + return ret, slots + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def pin_current_thread(): + """Pin current thread to one logical CPU so TSC brackets are strictly monotonic.""" + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.GetCurrentThread.restype = ctypes.c_void_p + kernel32.GetProcessAffinityMask.argtypes = [ + ctypes.c_void_p, ctypes.POINTER(ctypes.c_size_t), ctypes.POINTER(ctypes.c_size_t), + ] + kernel32.SetThreadAffinityMask.argtypes = [ctypes.c_void_p, ctypes.c_size_t] + kernel32.SetThreadAffinityMask.restype = ctypes.c_size_t + proc_mask, sys_mask = ctypes.c_size_t(), ctypes.c_size_t() + if kernel32.GetProcessAffinityMask(kernel32.GetCurrentProcess(), ctypes.byref(proc_mask), ctypes.byref(sys_mask)): + bit = proc_mask.value & -proc_mask.value + if bit: + kernel32.SetThreadAffinityMask(kernel32.GetCurrentThread(), bit) + + +# --- Translator positive and negative controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += enc.encode(ins, rip) + return enc.take_buffer() + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + rdpru = Instruction.create(Code.RDPRU) + monitorx = Instruction.create(Code.MONITORXQ) + mwaitx = Instruction.create(Code.MWAITX) + xor_ecx = Instruction.create_reg_reg(Code.XOR_R32_RM32, R.ECX, R.ECX) + xor_edx = Instruction.create_reg_reg(Code.XOR_R32_RM32, R.EDX, R.EDX) + mov_ecx_0 = Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.ECX, 0) + mov_ecx_1 = Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.ECX, 1) + mov_ecx_2 = Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.ECX, 2) + mov_eax_0 = Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.EAX, 0) + lea_rax_rcx = Instruction.create_reg_mem(Code.LEA_R64_M, R.RAX, MemoryOperand(R.RCX)) + lea_rax_rdx = Instruction.create_reg_mem(Code.LEA_R64_M, R.RAX, MemoryOperand(R.RDX)) + lea_rax_r8 = Instruction.create_reg_mem(Code.LEA_R64_M, R.RAX, MemoryOperand(R.R8)) + st_r8_rax = Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.RAX) + + # Positive acceptance checks. + positive = [ + ("rdpru_0", (xor_ecx, rdpru, st_r8_rax, ret), "op_rdpru_read(0u)"), + ("rdpru_1", (mov_ecx_1, rdpru, st_r8_rax, ret), "op_rdpru_read(1u)"), + ("monitorx_rcx", (lea_rax_rcx, xor_ecx, xor_edx, monitorx, ret), "op_monitorx(rax);"), + ("monitorx_rdx", (lea_rax_rdx, xor_ecx, xor_edx, monitorx, ret), "op_monitorx(rax);"), + ("monitorx_r8_mwaitx_0", (lea_rax_r8, xor_ecx, xor_edx, monitorx, mov_eax_0, mov_ecx_0, mwaitx, ret), "op_mwaitx("), + ("mwaitx_intbrk_1", (mov_eax_0, mov_ecx_1, mwaitx, ret), "op_mwaitx(static_cast<std::uint32_t>(rax), 1u);"), + ] + for label, seq, needle in positive: + src, _ = lift_code(label, 0x1000, encode_seq(*seq)) + assert needle in src, f"{label}: missing {needle!r}" + + # Negative rejection controls. + rep_ret = Instruction.create(Code.RETNQ) + rep_ret.has_rep_prefix = True + fs_store = Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.RAX) + fs_store.segment_prefix = R.FS + + rejections = [ + ("legacy_monitor", (lea_rax_rcx, xor_ecx, xor_edx, Instruction.create(Code.MONITORQ), ret), + "unsupported legacy monitor/mwait/rdtsc instruction"), + ("legacy_mwait", (mov_eax_0, mov_ecx_0, Instruction.create(Code.MWAIT), ret), + "unsupported legacy monitor/mwait/rdtsc instruction"), + ("legacy_rdtsc", (Instruction.create(Code.RDTSC), ret), + "unsupported legacy monitor/mwait/rdtsc instruction"), + ("legacy_rdtscp", (Instruction.create(Code.RDTSCP), ret), + "unsupported legacy monitor/mwait/rdtsc instruction"), + ("monitorx_addr32", (lea_rax_rcx, xor_ecx, xor_edx, Instruction.create(Code.MONITORXD), ret), + "unsupported non-64-bit monitorx address size"), + ("vex_vmovdqu", (Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), mov_eax_0, ret), + "unsupported VEX encoding"), + ("evex_vmovdqu32", (Instruction.create_reg_mem(Code.EVEX_VMOVDQU32_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), mov_eax_0, ret), + "unsupported EVEX encoding"), + ("sse_movaps", (Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), mov_eax_0, ret), + "unsupported instruction"), + ("nonvol_rbx", (Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.EBX, 0), mov_eax_0, ret), + "nonvolatile GPR"), + ("nonvol_r12", (Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R12), ret), + "nonvolatile GPR"), + ("nonvol_mem_rbx", (mov_eax_0, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RBX), R.RAX), ret), + "nonvolatile GPR base"), + ("rdpru_unproven_ecx", (rdpru, ret), + "non-constant/unproven ECX for rdpru"), + ("rdpru_oor_ecx_2", (mov_ecx_2, rdpru, ret), + "out-of-range ECX=0x2 for rdpru"), + ("rdpru_oor_ecx_neg1", (Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.ECX, 0xFFFFFFFF), rdpru, ret), + "out-of-range ECX=0xffffffff for rdpru"), + ("monitorx_undef_rax", (xor_ecx, xor_edx, monitorx, mov_eax_0, ret), + "non-flat or unowned RAX address for monitorx"), + ("monitorx_const_rax", (Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.EAX, 0x1000), xor_ecx, xor_edx, monitorx, ret), + "non-flat or unowned RAX address for monitorx"), + ("monitorx_arith_rax", (lea_rax_rcx, Instruction.create_reg_i32(Code.ADD_RM64_IMM8, R.RAX, 1), xor_ecx, xor_edx, monitorx, ret), + "non-flat or unowned RAX address for monitorx"), + ("monitorx_nonzero_ecx", (lea_rax_rcx, mov_ecx_1, xor_edx, monitorx, ret), + "undefined or non-zero ECX for monitorx"), + ("monitorx_unproven_ecx", (lea_rax_rcx, xor_edx, monitorx, ret), + "undefined or non-zero ECX for monitorx"), + ("monitorx_nonzero_edx", (lea_rax_rcx, xor_ecx, Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.EDX, 1), monitorx, ret), + "undefined or non-zero EDX for monitorx"), + ("monitorx_unproven_edx", (lea_rax_rcx, xor_ecx, monitorx, ret), + "undefined or non-zero EDX for monitorx"), + ("mwaitx_undef_rax", (mov_ecx_0, mwaitx, mov_eax_0, ret), + "undefined RAX hints for mwaitx"), + ("mwaitx_unproven_ecx", (mov_eax_0, mwaitx, ret), + "undefined or non-constant ECX extensions for mwaitx"), + ("mwaitx_timer_ecx_2", (mov_eax_0, mov_ecx_2, mwaitx, ret), + "unsupported MWAITX timer extension ECX[1]"), + ("mwaitx_timer_ecx_3", (mov_eax_0, Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.ECX, 3), mwaitx, ret), + "unsupported MWAITX timer extension ECX[1]"), + ("mwaitx_reserved_ecx_4", (mov_eax_0, Instruction.create_reg_u32(Code.MOV_R32_IMM32, R.ECX, 4), mwaitx, ret), + "unsupported reserved MWAITX extension bits"), + ("undef_gpr_read", (Instruction.create_reg_reg(Code.ADD_R64_RM64, R.R9, R.RCX), mov_eax_0, ret), + "undefined register r9"), + ("undef_ret_rax", (xor_ecx, ret), + "undefined return register rax"), + ("undef_flag_setb", (mov_eax_0, Instruction.create_reg(Code.SETB_RM8, R.AL), ret), + "undefined flag cf read"), + ("undef_flag_seto_after_shl2", (mov_eax_0, Instruction.create_reg_u32(Code.SHL_RM64_IMM8, R.RAX, 2), + Instruction.create_reg(Code.SETO_RM8, R.AL), ret), + "undefined flag of read"), + ("store_outside_r8_rcx", (mov_eax_0, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "store outside output buffer r8"), + ("store_outside_r8_rdx", (mov_eax_0, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RDX), R.RAX), ret), + "store outside output buffer r8"), + ("store_oob_r8_disp64", (mov_eax_0, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=64, displ_size=1), R.RAX), ret), + "out-of-buffer store displacement"), + ("store_indexed", (mov_eax_0, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8, index=R.RCX), R.RAX), ret), + "unsupported memory operand"), + ("lea_displaced", (Instruction.create_reg_mem(Code.LEA_R64_M, R.RAX, MemoryOperand(R.RCX, displ=8, displ_size=1)), ret), + "unsupported displaced lea operand"), + ("lea_indexed", (Instruction.create_reg_mem(Code.LEA_R64_M, R.RAX, MemoryOperand(R.RCX, index=R.RDX)), ret), + "unsupported lea memory operand"), + ("prefix_fs", (mov_eax_0, fs_store, ret), + "unsupported instruction prefix"), + ("prefix_rep_ret", (mov_eax_0, rep_ret), + "unsupported instruction prefix"), + ("branch_jmp", (mov_eax_0, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "unsupported control-flow instruction"), + ("missing_ret", (xor_ecx, rdpru), + "missing terminal ret"), + ("trailing_after_ret", (mov_eax_0, ret, mov_eax_0), + "unreachable instruction after ret"), + ] + for label, seq, reason in rejections: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected sequence") + return len(positive), len(rejections) + + +# --- /O2 binary anti-CSE / anti-DCE inspection --- + +def walk_export_codes(dll_path, symbol): + """Collect reachable instruction Codes from a compiled export without relying on .pdata.""" + with pefile.PE(str(dll_path), fast_load=True) as pe: + base = pe.OPTIONAL_HEADER.ImageBase + image = pe.get_memory_mapped_image() + pending = [base + export_rva(pe, symbol)] + seen = set() + found = {} + while pending: + ip = pending.pop() + while ip not in seen: + seen.add(ip) + assert base <= ip < base + len(image), f"{symbol}: branch left image at {ip:#x}" + ins = Decoder(64, image[ip - base:ip - base + 15], ip=ip).decode() + found[ip] = ins.code + flow = ins.flow_control + if flow == FlowControl.RETURN: + break + if flow in (FlowControl.CONDITIONAL_BRANCH, FlowControl.UNCONDITIONAL_BRANCH): + pending.append(ins.near_branch_target) + if flow == FlowControl.UNCONDITIONAL_BRANCH: + break + ip = ins.next_ip + return [found[ip] for ip in sorted(found)] + + +def check_o2_barriers(o2_path): + """Verify /O2 did not CSE consecutive RDPRU reads, DCE overwritten RDPRU, or elide MWAITX.""" + expected_rdtsc = { + "lifted_op_rdpru_mperf": 1, + "lifted_op_rdpru_aperf": 1, + "lifted_op_rdpru_twice": 2, + "lifted_op_rdpru_unused": 1, + } + for sym, want in expected_rdtsc.items(): + codes = walk_export_codes(o2_path, sym) + got = codes.count(Code.RDTSC) + if got != want: + raise AssertionError(f"/O2 {sym}: expected {want} RDTSC instruction(s), found {got}") + for sym in ("lifted_op_monitorx_mwaitx_r8", "lifted_op_monitorx_mwaitx_intbrk"): + codes = walk_export_codes(o2_path, sym) + if codes.count(Code.PAUSE) < 1: + raise AssertionError(f"/O2 {sym}: expected PAUSE barrier from MWAITX, found 0") + + +# --- Execution checks (run on Debug lifted, /O2 lifted, and optionally native AMD) --- + +def check_runtime_suite(label, funcs, serial_tsc, *, check_tsc_bracket, check_null_fault): + total = 0 + # 1. RDPRU MPERF (ECX=0) and APERF (ECX=1) + for name, want_ecx, flag_fn in ( + ("op_rdpru_mperf", 0, add64_flags), + ("op_rdpru_aperf", 1, cmp64_flags), + ): + for a, b in FLAG_PAIRS: + before = serial_tsc() if check_tsc_bracket else 0 + ret, slots = call_export(funcs[name], a, b) + after = serial_tsc() if check_tsc_bracket else MASK64 + lo, hi, ecx_out, flags_out = slots[0], slots[1], slots[2], slots[3] + assert lo <= MASK32 and hi <= MASK32, f"{label} {name}: upper 32 bits not zeroed ({lo:#x}, {hi:#x})" + assert ret == ((hi << 32) | lo), f"{label} {name}: return mismatch" + if check_tsc_bracket: + assert before <= ret <= after, f"{label} {name}: {ret:#x} outside TSC bracket {before:#x}..{after:#x}" + assert ecx_out == want_ecx, f"{label} {name}: RCX clobbered ({ecx_out:#x} != {want_ecx:#x})" + want_flags = flag_fn(a, b) + assert flags_out == want_flags, f"{label} {name} ({a:#x},{b:#x}): flags {flags_out:#x} != {want_flags:#x}" + total += 1 + + # 2. Consecutive RDPRU monotonicity (op_rdpru_twice) + advanced = False + for _ in range(512): + ret, slots = call_export(funcs["op_rdpru_twice"], 0, 0) + lo1, hi1, lo2, hi2, ecx_out = slots[0], slots[1], slots[2], slots[3], slots[4] + assert max(lo1, hi1, lo2, hi2) <= MASK32, f"{label} op_rdpru_twice: upper 32 bits not zeroed" + t1, t2 = (hi1 << 32) | lo1, (hi2 << 32) | lo2 + assert t2 >= t1, f"{label} op_rdpru_twice went backwards: {t1:#x} -> {t2:#x}" + assert ret == t2 and ecx_out == 0 + advanced |= (t2 > t1) + total += 1 + assert advanced, f"{label} op_rdpru_twice never observed counter advancement in 512 rounds" + + # 3. Overwritten RDPRU (op_rdpru_unused) + ret, _ = call_export(funcs["op_rdpru_unused"], 0x1111, 0x2222) + assert ret == 7, f"{label} op_rdpru_unused returned {ret}, expected 7" + total += 1 + + # 4. MONITORX + triggering store + MWAITX (ECX=0 and ECX=1 interrupt-break) + for a, b in FLAG_PAIRS: + ret, slots = call_export(funcs["op_monitorx_mwaitx_r8"], a, b) + want_flags = cmp64_flags(a, b) + assert slots[0] == a and slots[1] == b and slots[2] == 0 and slots[3] == want_flags and slots[4] == 0 + assert ret == want_flags + ret2, slots2 = call_export(funcs["op_monitorx_mwaitx_intbrk"], a, b) + want_flags2 = add64_flags(a, b) + assert slots2[0] == a and slots2[1] == 0x10 and slots2[2] == 1 and slots2[3] == 0 and slots2[4] == want_flags2 + assert ret2 == want_flags2 + total += 2 + + # 5. MONITORX on flat [rcx] and [rdx] pointers + NULL fault ordering + buf_a, a_pre, a_off, a_post, a_addr = alloc_guarded(b"\x11" * 16) + buf_b, b_pre, b_off, b_post, b_addr = alloc_guarded(b"\x22" * 16) + ret, slots = call_export(funcs["op_monitorx_rcx_rdx"], a_addr, b_addr) + want_flags = cmp64_flags(a_addr, b_addr) + assert slots[0] == b_addr and slots[1] == a_addr and slots[2] == b_addr and slots[3] == want_flags + assert ret == want_flags + assert buf_a.raw[a_pre:a_off] == GUARD_PRE and buf_a.raw[a_post:a_post + 16] == GUARD_POST + assert buf_b.raw[b_pre:b_off] == GUARD_PRE and buf_b.raw[b_post:b_post + 16] == GUARD_POST + total += 1 + + if check_null_fault: + out_raw, o_pre, o_off, o_post, o_addr = alloc_guarded(b"\x5a" * OUT_BYTES) + try: + funcs["op_monitorx_rcx_rdx"](0, b_addr, o_addr) + except OSError as exc: + assert "access violation" in str(exc).lower(), (label, exc) + else: + raise AssertionError(f"{label} op_monitorx_rcx_rdx did not fault on NULL rcx") + assert out_raw.raw[o_pre:o_off] == GUARD_PRE and out_raw.raw[o_post:o_post + 16] == GUARD_POST + fault_slots = struct.unpack("<8Q", out_raw.raw[o_off:o_off + OUT_BYTES]) + assert fault_slots[0] == b_addr, f"{label}: pre-MONITORX store was elided/sunk across fault" + assert fault_slots[1] == SENTINEL64, f"{label}: post-MONITORX store hoisted before fault" + total += 1 + + # 6. 32-bit ADD and CMP flag paths across RDPRU and MONITORX/MWAITX + for a, b in FLAG_PAIRS_32: + before = serial_tsc() if check_tsc_bracket else 0 + ret, slots = call_export(funcs["op_add32_rdpru"], a, b) + after = serial_tsc() if check_tsc_bracket else MASK64 + lo, hi, ecx_out, flags_out = slots[0], slots[1], slots[2], slots[3] + assert lo <= MASK32 and hi <= MASK32 + assert ret == ((hi << 32) | lo) + if check_tsc_bracket: + assert before <= ret <= after + assert ecx_out == 0 and flags_out == add32_flags(a, b) + + ret_c, slots_c = call_export(funcs["op_cmp32_mwaitx"], a, b) + want_c = cmp32_flags(a, b) + assert slots_c[0] == (a & MASK32) and slots_c[1] == 0 and slots_c[2] == 0 and slots_c[3] == want_c + assert ret_c == want_c + total += 2 + + return total + + +MUTANT_SPECS = ( + ("mut_rdpru_no_zext", "op_rdpru_mperf", "rax = static_cast<std::uint32_t>(pru); rdx = pru >> 32;", + "rax = pru | 0x100000000ull; rdx = (pru >> 32) | 0x100000000ull;"), + ("mut_rdpru_swap_halves", "op_rdpru_mperf", "rax = static_cast<std::uint32_t>(pru); rdx = pru >> 32;", + "rax = pru >> 32; rdx = static_cast<std::uint32_t>(pru);"), + ("mut_rdpru_clobber_flags", "op_rdpru_mperf", "rdx = pru >> 32; }", + "rdx = pru >> 32; cf = false; zf = false; sf = false; of = false; }"), + ("mut_mwaitx_clobber_flags", "op_monitorx_mwaitx_r8", "op_mwaitx(static_cast<std::uint32_t>(rax), 0u);", + "op_mwaitx(static_cast<std::uint32_t>(rax), 0u); cf = false; zf = false; sf = false; of = false;"), + ("mut_mwaitx_drop_hint_ext", "op_monitorx_mwaitx_intbrk", "op_mwaitx(static_cast<std::uint32_t>(rax), 1u);", + "op_mwaitx(static_cast<std::uint32_t>(rax), 1u); rax = 0ull; rcx = 0ull;"), + ("mut_cmp32_flip_cf", "op_cmp32_mwaitx", "op_cmp32(r9, r10, cf, zf, sf, of);", + "op_cmp32(r9, r10, cf, zf, sf, of); cf = static_cast<std::uint32_t>(r9) > static_cast<std::uint32_t>(r10);"), +) + + +def emit_mutants(original_path, out_cpp): + """Emit compiled C++ mutation controls from translated functions.""" + unique_exports = [] + for _, src_name, _, _ in MUTANT_SPECS: + if src_name not in unique_exports: + unique_exports.append(src_name) + base_src, _ = cpu_amd_monitor_rdpru_aot.translate(original_path, unique_exports) + chunks = [base_src] + with pefile.PE(str(original_path), fast_load=True) as pe: + by_name = {} + for name in unique_exports: + entry = export_rva(pe, name) + fn_src, _ = lift_code(name, entry, bounded_code(pe, entry)) + by_name[name] = fn_src + for mut_name, src_name, needle, repl in MUTANT_SPECS: + src = by_name[src_name] + if needle not in src: + raise AssertionError(f"mutant {mut_name}: needle {needle!r} not found in {src_name}") + mutated = src.replace(f"lifted_{src_name}", mut_name, 1).replace(needle, repl, 1) + chunks.append(mutated) + out_cpp.parent.mkdir(parents=True, exist_ok=True) + out_cpp.write_text("\n".join(chunks) + "\n", encoding="utf-8") + + +def check_altered_and_mutants(lifted, altered_lifted, mutants_path=None, serial_tsc=None): + # Altered-lifted build must diverge on every altered export. + _, s_orig_m = call_export(lifted["op_rdpru_mperf"], 5, 9) + _, s_alt_m = call_export(altered_lifted["op_rdpru_mperf"], 5, 9) + assert s_orig_m[2] == 0 and s_alt_m[2] == 1 + + _, s_orig_a = call_export(lifted["op_rdpru_aperf"], 5, 9) + _, s_alt_a = call_export(altered_lifted["op_rdpru_aperf"], 5, 9) + assert s_orig_a[2] == 1 and s_alt_a[2] == 0 + + _, s_orig_t = call_export(lifted["op_rdpru_twice"], 0, 0) + _, s_alt_t = call_export(altered_lifted["op_rdpru_twice"], 0, 0) + assert s_orig_t[4] == 0 and s_alt_t[4] == 1 + + r_orig_u, _ = call_export(lifted["op_rdpru_unused"], 0, 0) + r_alt_u, _ = call_export(altered_lifted["op_rdpru_unused"], 0, 0) + assert r_orig_u == 7 and r_alt_u == 42 + + _, s_orig_mw = call_export(lifted["op_monitorx_mwaitx_r8"], 0x1234, 0x5678) + _, s_alt_mw = call_export(altered_lifted["op_monitorx_mwaitx_r8"], 0x1234, 0x5678) + assert s_orig_mw[1] == 0x5678 and s_alt_mw[1] == 0x1234 + + _, s_orig_ib = call_export(lifted["op_monitorx_mwaitx_intbrk"], 1, 2) + _, s_alt_ib = call_export(altered_lifted["op_monitorx_mwaitx_intbrk"], 1, 2) + assert s_orig_ib[1] == 0x10 and s_alt_ib[1] == 0x20 + + mutants = 0 + if mutants_path is not None: + mut_lib = ctypes.CDLL(str(Path(mutants_path).resolve())) + mut = {} + for mut_name, _, _, _ in MUTANT_SPECS: + fn = getattr(mut_lib, mut_name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + mut[mut_name] = fn + + # 1. Missing 32->64 zero extension on RAX/RDX after RDPRU + _, sm1 = call_export(mut["mut_rdpru_no_zext"], 1, 2) + assert (sm1[0] >> 32) != 0 and (sm1[1] >> 32) != 0 + mutants += 1 + # 2. Swapped RAX/RDX halves in returned 64-bit counter + before = serial_tsc() + rm2, sm2 = call_export(mut["mut_rdpru_swap_halves"], 1, 2) + after = serial_tsc() + unswapped = (sm2[0] << 32) | sm2[1] + assert sm2[0] != sm2[1] and before <= unswapped <= after and not (before <= rm2 <= after) + mutants += 1 + # 3. Clobbering RFLAGS on RDPRU + _, sm3 = call_export(mut["mut_rdpru_clobber_flags"], 0x7FFFFFFFFFFFFFFF, 1) + assert sm3[3] != add64_flags(0x7FFFFFFFFFFFFFFF, 1) + mutants += 1 + # 4. Clobbering RFLAGS on MWAITX + _, sm4 = call_export(mut["mut_mwaitx_clobber_flags"], 5, 9) + assert sm4[3] != cmp64_flags(5, 9) + mutants += 1 + # 5. Dropping MWAITX EAX hint and ECX=1 extension + _, sm5 = call_export(mut["mut_mwaitx_drop_hint_ext"], 1, 2) + assert sm5[1] != 0x10 or sm5[2] != 1 + mutants += 1 + # 6. Flipping CF in op_cmp32 (a < b -> a > b) + rc6, _ = call_export(mut["mut_cmp32_flip_cf"], 5, 9) + assert rc6 != cmp32_flags(5, 9) + mutants += 1 + return len(ALTERED_EXPORTS), mutants + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if len(sys.argv) >= 4 and sys.argv[1] == "emit-mutants": + emit_mutants(Path(sys.argv[2]), Path(sys.argv[3])) + return + + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, lifted_o2_path, altered_path, altered_lifted_path, mutants_path = ( + Path(p) for p in sys.argv[1:7] + ) + + accepted, rejected = check_translator() + print(f"{accepted} AMD MONITORX/MWAITX/RDPRU sequences accepted; {rejected} rejection controls passed") + + check_o2_barriers(lifted_o2_path) + print("/O2 disassembly verified: RDPRU anti-CSE (2 reads in twice), anti-DCE (1 read in unused), MWAITX PAUSE barriers kept") + + pin_current_thread() + lifted_lib, lifted = bind(lifted_path, "lifted_") + _, lifted_o2 = bind(lifted_o2_path, "lifted_") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + + serial_tsc = lifted_lib.host_serial_tsc + serial_tsc.argtypes, serial_tsc.restype = [], ctypes.c_uint64 + has_mwaitx_fn = lifted_lib.host_has_mwaitx + has_mwaitx_fn.argtypes, has_mwaitx_fn.restype = [], ctypes.c_uint32 + has_rdpru_fn = lifted_lib.host_has_rdpru + has_rdpru_fn.argtypes, has_rdpru_fn.restype = [], ctypes.c_uint32 + + dbg_total = check_runtime_suite("lifted", lifted, serial_tsc, check_tsc_bracket=True, check_null_fault=True) + o2_total = check_runtime_suite("lifted_o2", lifted_o2, serial_tsc, check_tsc_bracket=True, check_null_fault=True) + alt_count, mut_count = check_altered_and_mutants(lifted, altered_lifted, mutants_path, serial_tsc) + print( + f"lifted Debug ({dbg_total} checks) + /O2 ({o2_total} checks) + NULL fault-ordering passed; " + f"{alt_count} altered-build + {mut_count} compiled C++ mutant controls caught" + ) + + has_mwaitx = bool(has_mwaitx_fn()) + has_rdpru = bool(has_rdpru_fn()) + if not (has_mwaitx and has_rdpru): + print( + f"Host lacks AMD MWAITX (CPUID Fn8000_0001:ECX[29]={int(has_mwaitx)}) and/or " + f"RDPRU (CPUID Fn8000_0008:EBX[4]={int(has_rdpru)}); skipping native differential check" + ) + sys.exit(77) + + _, native = bind(original_path, "") + _, altered = bind(altered_path, "") + nat_total = check_runtime_suite("native", native, serial_tsc, check_tsc_bracket=False, check_null_fault=True) + alt_nat_count, _ = check_altered_and_mutants(native, altered) + print(f"native AMD hardware differential passed ({nat_total} checks, {alt_nat_count} altered-native controls caught)") + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/avx_cmp_aot.asm b/tests/cpu/avx_cmp_aot.asm new file mode 100644 index 0000000000..fb7295d955 --- /dev/null +++ b/tests/cpu/avx_cmp_aot.asm @@ -0,0 +1,502 @@ +; coverage: record cpu_aot_avx_cmp +; Source-owned MASM fixture for VEX.128 and VEX.256 AVX FP compare instructions +; (vcmpps, vcmppd, vcmpss, vcmpsd) across all 32 5-bit predicates (0x00..0x1F), +; flat [rcx|rdx|r8] memory sources, scalar upper-lane preservation, and glue moves. +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +MK_VCMPPS_YMM MACRO name, pred +name PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vcmpps ymm0, ymm1, ymm2, pred + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +MK_VCMPPD_YMM MACRO name, pred +name PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vcmppd ymm0, ymm1, ymm2, pred + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +MK_VCMPSS MACRO name, pred +name PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vcmpss xmm0, xmm1, xmm2, pred + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +MK_VCMPSD MACRO name, pred +name PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vcmpsd xmm0, xmm1, xmm2, pred + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +name ENDP +ENDM + +; --- VCMPPS YMM predicates 0x00..0x1F --- +op_vcmpps_ymm_p00 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmpps ymm0, ymm1, ymm2, 04h +ELSE + vcmpps ymm0, ymm1, ymm2, 00h +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_p00 ENDP + +MK_VCMPPS_YMM op_vcmpps_ymm_p01, 01h +MK_VCMPPS_YMM op_vcmpps_ymm_p02, 02h +MK_VCMPPS_YMM op_vcmpps_ymm_p03, 03h +MK_VCMPPS_YMM op_vcmpps_ymm_p04, 04h +MK_VCMPPS_YMM op_vcmpps_ymm_p05, 05h +MK_VCMPPS_YMM op_vcmpps_ymm_p06, 06h +MK_VCMPPS_YMM op_vcmpps_ymm_p07, 07h +MK_VCMPPS_YMM op_vcmpps_ymm_p08, 08h +MK_VCMPPS_YMM op_vcmpps_ymm_p09, 09h +MK_VCMPPS_YMM op_vcmpps_ymm_p0a, 0Ah +MK_VCMPPS_YMM op_vcmpps_ymm_p0b, 0Bh +MK_VCMPPS_YMM op_vcmpps_ymm_p0c, 0Ch +MK_VCMPPS_YMM op_vcmpps_ymm_p0d, 0Dh +MK_VCMPPS_YMM op_vcmpps_ymm_p0e, 0Eh +MK_VCMPPS_YMM op_vcmpps_ymm_p0f, 0Fh +MK_VCMPPS_YMM op_vcmpps_ymm_p10, 10h +MK_VCMPPS_YMM op_vcmpps_ymm_p11, 11h +MK_VCMPPS_YMM op_vcmpps_ymm_p12, 12h +MK_VCMPPS_YMM op_vcmpps_ymm_p13, 13h +MK_VCMPPS_YMM op_vcmpps_ymm_p14, 14h +MK_VCMPPS_YMM op_vcmpps_ymm_p15, 15h +MK_VCMPPS_YMM op_vcmpps_ymm_p16, 16h +MK_VCMPPS_YMM op_vcmpps_ymm_p17, 17h +MK_VCMPPS_YMM op_vcmpps_ymm_p18, 18h +MK_VCMPPS_YMM op_vcmpps_ymm_p19, 19h +MK_VCMPPS_YMM op_vcmpps_ymm_p1a, 1Ah +MK_VCMPPS_YMM op_vcmpps_ymm_p1b, 1Bh +MK_VCMPPS_YMM op_vcmpps_ymm_p1c, 1Ch +MK_VCMPPS_YMM op_vcmpps_ymm_p1d, 1Dh +MK_VCMPPS_YMM op_vcmpps_ymm_p1e, 1Eh +MK_VCMPPS_YMM op_vcmpps_ymm_p1f, 1Fh + +; --- VCMPPD YMM predicates 0x00..0x1F --- +MK_VCMPPD_YMM op_vcmppd_ymm_p00, 00h +op_vcmppd_ymm_p01 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmppd ymm0, ymm1, ymm2, 05h +ELSE + vcmppd ymm0, ymm1, ymm2, 01h +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_p01 ENDP + +MK_VCMPPD_YMM op_vcmppd_ymm_p02, 02h +MK_VCMPPD_YMM op_vcmppd_ymm_p03, 03h +MK_VCMPPD_YMM op_vcmppd_ymm_p04, 04h +MK_VCMPPD_YMM op_vcmppd_ymm_p05, 05h +MK_VCMPPD_YMM op_vcmppd_ymm_p06, 06h +MK_VCMPPD_YMM op_vcmppd_ymm_p07, 07h +MK_VCMPPD_YMM op_vcmppd_ymm_p08, 08h +MK_VCMPPD_YMM op_vcmppd_ymm_p09, 09h +MK_VCMPPD_YMM op_vcmppd_ymm_p0a, 0Ah +MK_VCMPPD_YMM op_vcmppd_ymm_p0b, 0Bh +MK_VCMPPD_YMM op_vcmppd_ymm_p0c, 0Ch +MK_VCMPPD_YMM op_vcmppd_ymm_p0d, 0Dh +MK_VCMPPD_YMM op_vcmppd_ymm_p0e, 0Eh +MK_VCMPPD_YMM op_vcmppd_ymm_p0f, 0Fh +MK_VCMPPD_YMM op_vcmppd_ymm_p10, 10h +MK_VCMPPD_YMM op_vcmppd_ymm_p11, 11h +MK_VCMPPD_YMM op_vcmppd_ymm_p12, 12h +MK_VCMPPD_YMM op_vcmppd_ymm_p13, 13h +MK_VCMPPD_YMM op_vcmppd_ymm_p14, 14h +MK_VCMPPD_YMM op_vcmppd_ymm_p15, 15h +MK_VCMPPD_YMM op_vcmppd_ymm_p16, 16h +MK_VCMPPD_YMM op_vcmppd_ymm_p17, 17h +MK_VCMPPD_YMM op_vcmppd_ymm_p18, 18h +MK_VCMPPD_YMM op_vcmppd_ymm_p19, 19h +MK_VCMPPD_YMM op_vcmppd_ymm_p1a, 1Ah +MK_VCMPPD_YMM op_vcmppd_ymm_p1b, 1Bh +MK_VCMPPD_YMM op_vcmppd_ymm_p1c, 1Ch +MK_VCMPPD_YMM op_vcmppd_ymm_p1d, 1Dh +MK_VCMPPD_YMM op_vcmppd_ymm_p1e, 1Eh +MK_VCMPPD_YMM op_vcmppd_ymm_p1f, 1Fh + +; --- VCMPSS predicates 0x00..0x1F --- +MK_VCMPSS op_vcmpss_p00, 00h +MK_VCMPSS op_vcmpss_p01, 01h +op_vcmpss_p02 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmpss xmm0, xmm2, xmm1, 02h +ELSE + vcmpss xmm0, xmm1, xmm2, 02h +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_p02 ENDP + +MK_VCMPSS op_vcmpss_p03, 03h +MK_VCMPSS op_vcmpss_p04, 04h +MK_VCMPSS op_vcmpss_p05, 05h +MK_VCMPSS op_vcmpss_p06, 06h +MK_VCMPSS op_vcmpss_p07, 07h +MK_VCMPSS op_vcmpss_p08, 08h +MK_VCMPSS op_vcmpss_p09, 09h +MK_VCMPSS op_vcmpss_p0a, 0Ah +MK_VCMPSS op_vcmpss_p0b, 0Bh +MK_VCMPSS op_vcmpss_p0c, 0Ch +MK_VCMPSS op_vcmpss_p0d, 0Dh +MK_VCMPSS op_vcmpss_p0e, 0Eh +MK_VCMPSS op_vcmpss_p0f, 0Fh +MK_VCMPSS op_vcmpss_p10, 10h +MK_VCMPSS op_vcmpss_p11, 11h +MK_VCMPSS op_vcmpss_p12, 12h +MK_VCMPSS op_vcmpss_p13, 13h +MK_VCMPSS op_vcmpss_p14, 14h +MK_VCMPSS op_vcmpss_p15, 15h +MK_VCMPSS op_vcmpss_p16, 16h +MK_VCMPSS op_vcmpss_p17, 17h +MK_VCMPSS op_vcmpss_p18, 18h +MK_VCMPSS op_vcmpss_p19, 19h +MK_VCMPSS op_vcmpss_p1a, 1Ah +MK_VCMPSS op_vcmpss_p1b, 1Bh +MK_VCMPSS op_vcmpss_p1c, 1Ch +MK_VCMPSS op_vcmpss_p1d, 1Dh +MK_VCMPSS op_vcmpss_p1e, 1Eh +MK_VCMPSS op_vcmpss_p1f, 1Fh + +; --- VCMPSD predicates 0x00..0x1F --- +MK_VCMPSD op_vcmpsd_p00, 00h +MK_VCMPSD op_vcmpsd_p01, 01h +MK_VCMPSD op_vcmpsd_p02, 02h +MK_VCMPSD op_vcmpsd_p03, 03h +MK_VCMPSD op_vcmpsd_p04, 04h +MK_VCMPSD op_vcmpsd_p05, 05h +MK_VCMPSD op_vcmpsd_p06, 06h +MK_VCMPSD op_vcmpsd_p07, 07h +MK_VCMPSD op_vcmpsd_p08, 08h +MK_VCMPSD op_vcmpsd_p09, 09h +MK_VCMPSD op_vcmpsd_p0a, 0Ah +MK_VCMPSD op_vcmpsd_p0b, 0Bh +MK_VCMPSD op_vcmpsd_p0c, 0Ch +MK_VCMPSD op_vcmpsd_p0d, 0Dh +MK_VCMPSD op_vcmpsd_p0e, 0Eh +MK_VCMPSD op_vcmpsd_p0f, 0Fh +MK_VCMPSD op_vcmpsd_p10, 10h +MK_VCMPSD op_vcmpsd_p11, 11h +MK_VCMPSD op_vcmpsd_p12, 12h +MK_VCMPSD op_vcmpsd_p13, 13h +MK_VCMPSD op_vcmpsd_p14, 14h +MK_VCMPSD op_vcmpsd_p15, 15h +MK_VCMPSD op_vcmpsd_p16, 16h +MK_VCMPSD op_vcmpsd_p17, 17h +MK_VCMPSD op_vcmpsd_p18, 18h +MK_VCMPSD op_vcmpsd_p19, 19h +MK_VCMPSD op_vcmpsd_p1a, 1Ah +MK_VCMPSD op_vcmpsd_p1b, 1Bh +MK_VCMPSD op_vcmpsd_p1c, 1Ch +MK_VCMPSD op_vcmpsd_p1d, 1Dh +MK_VCMPSD op_vcmpsd_p1e, 1Eh +MK_VCMPSD op_vcmpsd_p1f, 1Fh + +; --- VEX.128 packed & upper-zeroing checks --- +op_vcmpps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_CMP + vcmpps ymm0, ymm1, ymm2, 00h +ELSE + vcmpps xmm0, xmm1, xmm2, 00h +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_xmm_reg ENDP + +op_vcmppd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vcmppd xmm0, xmm1, xmm2, 0Ch + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_xmm_reg ENDP + +op_vcmpps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps xmm0, xmm1, XMMWORD PTR [rdx], 02h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_xmm_mem ENDP + +op_vcmppd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vcmppd xmm0, xmm1, XMMWORD PTR [rdx], 11h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_xmm_mem ENDP + +; --- Flat [rcx|rdx|r8] memory-source forms --- +op_vcmpps_ymm_mem_rcx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rdx] + vcmpps ymm0, ymm1, YMMWORD PTR [rcx], 01h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_mem_rcx ENDP + +op_vcmpps_ymm_mem_rdx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps ymm0, ymm1, YMMWORD PTR [rdx], 0Eh + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_mem_rdx ENDP + +op_vcmpps_ymm_mem_r8 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps ymm0, ymm1, YMMWORD PTR [r8], 12h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_ymm_mem_r8 ENDP + +op_vcmppd_ymm_mem_rcx PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rdx] + vcmppd ymm0, ymm1, YMMWORD PTR [rcx], 0Dh + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_mem_rcx ENDP + +op_vcmppd_ymm_mem_rdx PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vcmppd ymm0, ymm1, YMMWORD PTR [rdx], 15h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_mem_rdx ENDP + +op_vcmppd_ymm_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vcmppd ymm0, ymm1, YMMWORD PTR [r8], 1Eh + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_ymm_mem_r8 ENDP + +op_vcmpss_mem_rcx PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rdx] + vcmpss xmm0, xmm1, DWORD PTR [rcx], 01h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_mem_rcx ENDP + +op_vcmpss_mem_rdx PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vcmpss xmm0, xmm1, DWORD PTR [rdx], 11h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_mem_rdx ENDP + +op_vcmpss_mem_r8 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpss xmm0, xmm1, DWORD PTR [r8], 0Ch + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpss_mem_r8 ENDP + +op_vcmpsd_mem_rcx PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rdx] + vcmpsd xmm0, xmm1, QWORD PTR [rcx], 02h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_mem_rcx ENDP + +op_vcmpsd_mem_rdx PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_AVX_CMP + vcmpsd xmm0, xmm1, QWORD PTR [rdx], 0Ah +ELSE + vcmpsd xmm0, xmm1, QWORD PTR [rdx], 0Eh +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_mem_rdx ENDP + +op_vcmpsd_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vcmpsd xmm0, xmm1, QWORD PTR [r8], 1Dh + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_mem_r8 ENDP + +; --- High imm8 bits [7:5] ignored (0xE5 & 0x1F == 0x05) --- +op_vcmpps_imm_highbits PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vcmpps ymm0, ymm1, ymm2, 0E5h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_imm_highbits ENDP + +; --- Register aliasing & scalar/packed glue moves --- +op_vcmpps_alias_dst_src1 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vmovups ymm1, YMMWORD PTR [rdx] + vcmpps ymm0, ymm0, ymm1, 04h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_alias_dst_src1 ENDP + +op_vcmppd_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vcmppd ymm0, ymm1, ymm0, 06h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmppd_alias_dst_src2 ENDP + +op_vcmpps_alias_src1_src2 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vcmpps ymm0, ymm1, ymm1, 03h + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpps_alias_src1_src2 ENDP + +op_vcmpsd_alias_all PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [rcx] + vcmpsd xmm0, xmm0, xmm0, 00h + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vcmpsd_alias_all ENDP + +op_vmovss_mem_glue PROC FRAME + .endprolog + vmovss xmm0, DWORD PTR [rcx] + vmovss xmm1, DWORD PTR [rdx] + vcmpss xmm0, xmm0, xmm1, 01h + vmovss DWORD PTR [r8], xmm0 + vzeroupper + ret +op_vmovss_mem_glue ENDP + +op_vmovsd_mem_glue PROC FRAME + .endprolog + vmovsd xmm0, QWORD PTR [rcx] + vmovsd xmm1, QWORD PTR [rdx] + vcmpsd xmm0, xmm0, xmm1, 01h + vmovsd QWORD PTR [r8], xmm0 + vzeroupper + ret +op_vmovsd_mem_glue ENDP + +op_vmovss_reg_merge_glue PROC FRAME + .endprolog + vmovaps ymm0, YMMWORD PTR [r8] + vmovaps xmm1, XMMWORD PTR [rcx] + vmovaps xmm2, XMMWORD PTR [rdx] + vmovss xmm0, xmm1, xmm2 + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vmovss_reg_merge_glue ENDP + +op_vmovsd_reg_merge_glue PROC FRAME + .endprolog + vmovapd ymm0, YMMWORD PTR [r8] + vmovapd xmm1, XMMWORD PTR [rcx] + vmovapd xmm2, XMMWORD PTR [rdx] + vmovsd xmm0, xmm1, xmm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vmovsd_reg_merge_glue ENDP + +op_vmov_aligned_glue PROC FRAME + .endprolog + vmovaps ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vmovaps ymm3, ymm1 + vmovapd ymm4, ymm2 + vcmpps ymm0, ymm3, ymm4, 0Ch + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vmov_aligned_glue ENDP + +END diff --git a/tests/cpu/avx_cmp_aot.def b/tests/cpu/avx_cmp_aot.def new file mode 100644 index 0000000000..f92943cb97 --- /dev/null +++ b/tests/cpu/avx_cmp_aot.def @@ -0,0 +1,155 @@ +EXPORTS + op_vcmpps_ymm_p00 + op_vcmpps_ymm_p01 + op_vcmpps_ymm_p02 + op_vcmpps_ymm_p03 + op_vcmpps_ymm_p04 + op_vcmpps_ymm_p05 + op_vcmpps_ymm_p06 + op_vcmpps_ymm_p07 + op_vcmpps_ymm_p08 + op_vcmpps_ymm_p09 + op_vcmpps_ymm_p0a + op_vcmpps_ymm_p0b + op_vcmpps_ymm_p0c + op_vcmpps_ymm_p0d + op_vcmpps_ymm_p0e + op_vcmpps_ymm_p0f + op_vcmpps_ymm_p10 + op_vcmpps_ymm_p11 + op_vcmpps_ymm_p12 + op_vcmpps_ymm_p13 + op_vcmpps_ymm_p14 + op_vcmpps_ymm_p15 + op_vcmpps_ymm_p16 + op_vcmpps_ymm_p17 + op_vcmpps_ymm_p18 + op_vcmpps_ymm_p19 + op_vcmpps_ymm_p1a + op_vcmpps_ymm_p1b + op_vcmpps_ymm_p1c + op_vcmpps_ymm_p1d + op_vcmpps_ymm_p1e + op_vcmpps_ymm_p1f + op_vcmppd_ymm_p00 + op_vcmppd_ymm_p01 + op_vcmppd_ymm_p02 + op_vcmppd_ymm_p03 + op_vcmppd_ymm_p04 + op_vcmppd_ymm_p05 + op_vcmppd_ymm_p06 + op_vcmppd_ymm_p07 + op_vcmppd_ymm_p08 + op_vcmppd_ymm_p09 + op_vcmppd_ymm_p0a + op_vcmppd_ymm_p0b + op_vcmppd_ymm_p0c + op_vcmppd_ymm_p0d + op_vcmppd_ymm_p0e + op_vcmppd_ymm_p0f + op_vcmppd_ymm_p10 + op_vcmppd_ymm_p11 + op_vcmppd_ymm_p12 + op_vcmppd_ymm_p13 + op_vcmppd_ymm_p14 + op_vcmppd_ymm_p15 + op_vcmppd_ymm_p16 + op_vcmppd_ymm_p17 + op_vcmppd_ymm_p18 + op_vcmppd_ymm_p19 + op_vcmppd_ymm_p1a + op_vcmppd_ymm_p1b + op_vcmppd_ymm_p1c + op_vcmppd_ymm_p1d + op_vcmppd_ymm_p1e + op_vcmppd_ymm_p1f + op_vcmpss_p00 + op_vcmpss_p01 + op_vcmpss_p02 + op_vcmpss_p03 + op_vcmpss_p04 + op_vcmpss_p05 + op_vcmpss_p06 + op_vcmpss_p07 + op_vcmpss_p08 + op_vcmpss_p09 + op_vcmpss_p0a + op_vcmpss_p0b + op_vcmpss_p0c + op_vcmpss_p0d + op_vcmpss_p0e + op_vcmpss_p0f + op_vcmpss_p10 + op_vcmpss_p11 + op_vcmpss_p12 + op_vcmpss_p13 + op_vcmpss_p14 + op_vcmpss_p15 + op_vcmpss_p16 + op_vcmpss_p17 + op_vcmpss_p18 + op_vcmpss_p19 + op_vcmpss_p1a + op_vcmpss_p1b + op_vcmpss_p1c + op_vcmpss_p1d + op_vcmpss_p1e + op_vcmpss_p1f + op_vcmpsd_p00 + op_vcmpsd_p01 + op_vcmpsd_p02 + op_vcmpsd_p03 + op_vcmpsd_p04 + op_vcmpsd_p05 + op_vcmpsd_p06 + op_vcmpsd_p07 + op_vcmpsd_p08 + op_vcmpsd_p09 + op_vcmpsd_p0a + op_vcmpsd_p0b + op_vcmpsd_p0c + op_vcmpsd_p0d + op_vcmpsd_p0e + op_vcmpsd_p0f + op_vcmpsd_p10 + op_vcmpsd_p11 + op_vcmpsd_p12 + op_vcmpsd_p13 + op_vcmpsd_p14 + op_vcmpsd_p15 + op_vcmpsd_p16 + op_vcmpsd_p17 + op_vcmpsd_p18 + op_vcmpsd_p19 + op_vcmpsd_p1a + op_vcmpsd_p1b + op_vcmpsd_p1c + op_vcmpsd_p1d + op_vcmpsd_p1e + op_vcmpsd_p1f + op_vcmpps_xmm_reg + op_vcmppd_xmm_reg + op_vcmpps_xmm_mem + op_vcmppd_xmm_mem + op_vcmpps_ymm_mem_rcx + op_vcmpps_ymm_mem_rdx + op_vcmpps_ymm_mem_r8 + op_vcmppd_ymm_mem_rcx + op_vcmppd_ymm_mem_rdx + op_vcmppd_ymm_mem_r8 + op_vcmpss_mem_rcx + op_vcmpss_mem_rdx + op_vcmpss_mem_r8 + op_vcmpsd_mem_rcx + op_vcmpsd_mem_rdx + op_vcmpsd_mem_r8 + op_vcmpps_imm_highbits + op_vcmpps_alias_dst_src1 + op_vcmppd_alias_dst_src2 + op_vcmpps_alias_src1_src2 + op_vcmpsd_alias_all + op_vmovss_mem_glue + op_vmovsd_mem_glue + op_vmovss_reg_merge_glue + op_vmovsd_reg_merge_glue + op_vmov_aligned_glue diff --git a/tests/cpu/avx_cmp_aot_check.py b/tests/cpu/avx_cmp_aot_check.py new file mode 100644 index 0000000000..83a14fbd65 --- /dev/null +++ b/tests/cpu/avx_cmp_aot_check.py @@ -0,0 +1,652 @@ +"""Differential, edge-case, MXCSR, refusal, CLI, and coverage checks for AVX VEX FP compare AOT.""" + +import ctypes +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Instruction, + MemoryOperand, + Mnemonic, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from avx_horiz_fp import _guarded_buf # noqa: E402 +from cpu_avx_cmp_aot import lift_code, main as tool_main, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + + +VCMPPS_PRED_EXPORTS = tuple(f"op_vcmpps_ymm_p{p:02x}" for p in range(32)) +VCMPPD_PRED_EXPORTS = tuple(f"op_vcmppd_ymm_p{p:02x}" for p in range(32)) +VCMPSS_PRED_EXPORTS = tuple(f"op_vcmpss_p{p:02x}" for p in range(32)) +VCMPSD_PRED_EXPORTS = tuple(f"op_vcmpsd_p{p:02x}" for p in range(32)) + +EXTRA_EXPORTS = ( + "op_vcmpps_xmm_reg", + "op_vcmppd_xmm_reg", + "op_vcmpps_xmm_mem", + "op_vcmppd_xmm_mem", + "op_vcmpps_ymm_mem_rcx", + "op_vcmpps_ymm_mem_rdx", + "op_vcmpps_ymm_mem_r8", + "op_vcmppd_ymm_mem_rcx", + "op_vcmppd_ymm_mem_rdx", + "op_vcmppd_ymm_mem_r8", + "op_vcmpss_mem_rcx", + "op_vcmpss_mem_rdx", + "op_vcmpss_mem_r8", + "op_vcmpsd_mem_rcx", + "op_vcmpsd_mem_rdx", + "op_vcmpsd_mem_r8", + "op_vcmpps_imm_highbits", + "op_vcmpps_alias_dst_src1", + "op_vcmppd_alias_dst_src2", + "op_vcmpps_alias_src1_src2", + "op_vcmpsd_alias_all", + "op_vmovss_mem_glue", + "op_vmovsd_mem_glue", + "op_vmovss_reg_merge_glue", + "op_vmovsd_reg_merge_glue", + "op_vmov_aligned_glue", +) + +EXPORTS = ( + VCMPPS_PRED_EXPORTS + + VCMPPD_PRED_EXPORTS + + VCMPSS_PRED_EXPORTS + + VCMPSD_PRED_EXPORTS + + EXTRA_EXPORTS +) + +# (export_name, ref_export_override_or_None) +ALTERED_CASES = ( + ("op_vcmpps_ymm_p00", "op_vcmpps_ymm_p04"), + ("op_vcmppd_ymm_p01", "op_vcmppd_ymm_p05"), + ("op_vcmpss_p02", None), + ("op_vcmpsd_mem_rdx", None), + ("op_vcmpps_xmm_reg", "op_vcmpps_ymm_p00"), +) + +SEED = bytes(0xA0 + (i % 16) for i in range(32)) +MXCSR_DEFAULT = 0x1F80 +MXCSR_DAZ = 0x1FC0 + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _is_nan_f32(bits: int) -> bool: + return (bits & 0x7FFFFFFF) > 0x7F800000 + + +def _is_nan_f64(bits: int) -> bool: + return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000 + + +def _is_subnormal_f32(bits: int) -> bool: + return 0 < (bits & 0x7FFFFFFF) < 0x00800000 + + +def _is_subnormal_f64(bits: int) -> bool: + return 0 < (bits & 0x7FFFFFFFFFFFFFFF) < 0x0010000000000000 + + +def _daz_f32(bits: int, daz: bool) -> float: + if daz and _is_subnormal_f32(bits): + bits &= 0x80000000 + return struct.unpack("<f", struct.pack("<I", bits & 0xFFFFFFFF))[0] + + +def _daz_f64(bits: int, daz: bool) -> float: + if daz and _is_subnormal_f64(bits): + bits &= 0x8000000000000000 + return struct.unpack("<d", struct.pack("<Q", bits & 0xFFFFFFFFFFFFFFFF))[0] + + +def cmp_pred_bool(x: float, y: float, unord: bool, pred: int) -> bool: + """Exact boolean semantics for all 32 5-bit AVX FP compare predicates (imm8 & 0x1F).""" + p = pred & 0x0F + if p == 0x00: + return not unord and x == y + if p == 0x01: + return not unord and x < y + if p == 0x02: + return not unord and x <= y + if p == 0x03: + return unord + if p == 0x04: + return unord or x != y + if p == 0x05: + return unord or not (x < y) + if p == 0x06: + return unord or not (x <= y) + if p == 0x07: + return not unord + if p == 0x08: + return unord or x == y + if p == 0x09: + return unord or x < y + if p == 0x0A: + return unord or x <= y + if p == 0x0B: + return False + if p == 0x0C: + return not unord and x != y + if p == 0x0D: + return not unord and x >= y + if p == 0x0E: + return not unord and x > y + return True + + +def ref_vcmpps(a: bytes, b: bytes, pred: int, wide: bool, daz: bool = False) -> bytes: + count = 8 if wide else 4 + xa = struct.unpack("<8I", a) + xb = struct.unpack("<8I", b) + masks = [] + for i in range(count): + unord = _is_nan_f32(xa[i]) or _is_nan_f32(xb[i]) + fx, fy = _daz_f32(xa[i], daz), _daz_f32(xb[i], daz) + masks.append(0xFFFFFFFF if cmp_pred_bool(fx, fy, unord, pred) else 0) + if not wide: + masks.extend([0, 0, 0, 0]) + return struct.pack("<8I", *masks) + + +def ref_vcmppd(a: bytes, b: bytes, pred: int, wide: bool, daz: bool = False) -> bytes: + count = 4 if wide else 2 + xa = struct.unpack("<4Q", a) + xb = struct.unpack("<4Q", b) + masks = [] + for i in range(count): + unord = _is_nan_f64(xa[i]) or _is_nan_f64(xb[i]) + dx, dy = _daz_f64(xa[i], daz), _daz_f64(xb[i], daz) + masks.append(0xFFFFFFFFFFFFFFFF if cmp_pred_bool(dx, dy, unord, pred) else 0) + if not wide: + masks.extend([0, 0]) + return struct.pack("<4Q", *masks) + + +def ref_vcmpss(a: bytes, b: bytes, pred: int, daz: bool = False) -> bytes: + xa = list(struct.unpack("<4I", a[:16])) + xb0 = struct.unpack("<I", b[:4])[0] + unord = _is_nan_f32(xa[0]) or _is_nan_f32(xb0) + xa[0] = 0xFFFFFFFF if cmp_pred_bool(_daz_f32(xa[0], daz), _daz_f32(xb0, daz), unord, pred) else 0 + return struct.pack("<4I", *xa) + b"\x00" * 16 + + +def ref_vcmpsd(a: bytes, b: bytes, pred: int, daz: bool = False) -> bytes: + xa = list(struct.unpack("<2Q", a[:16])) + xb0 = struct.unpack("<Q", b[:8])[0] + unord = _is_nan_f64(xa[0]) or _is_nan_f64(xb0) + xa[0] = 0xFFFFFFFFFFFFFFFF if cmp_pred_bool(_daz_f64(xa[0], daz), _daz_f64(xb0, daz), unord, pred) else 0 + return struct.pack("<2Q", *xa) + b"\x00" * 16 + + +def ref_export(name: str, a: bytes, b: bytes, seed: bytes, daz: bool = False) -> bytes: + if name.startswith("op_vcmpps_ymm_p"): + return ref_vcmpps(a, b, int(name[-2:], 16), wide=True, daz=daz) + if name.startswith("op_vcmppd_ymm_p"): + return ref_vcmppd(a, b, int(name[-2:], 16), wide=True, daz=daz) + if name.startswith("op_vcmpss_p"): + return ref_vcmpss(a, b, int(name[-2:], 16), daz=daz) + if name.startswith("op_vcmpsd_p"): + return ref_vcmpsd(a, b, int(name[-2:], 16), daz=daz) + if name == "op_vcmpps_xmm_reg": + return ref_vcmpps(a, b, 0x00, wide=False, daz=daz) + if name == "op_vcmppd_xmm_reg": + return ref_vcmppd(a, b, 0x0C, wide=False, daz=daz) + if name == "op_vcmpps_xmm_mem": + return ref_vcmpps(a, b, 0x02, wide=False, daz=daz) + if name == "op_vcmppd_xmm_mem": + return ref_vcmppd(a, b, 0x11, wide=False, daz=daz) + if name == "op_vcmpps_ymm_mem_rcx": + return ref_vcmpps(b, a, 0x01, wide=True, daz=daz) + if name == "op_vcmpps_ymm_mem_rdx": + return ref_vcmpps(a, b, 0x0E, wide=True, daz=daz) + if name == "op_vcmpps_ymm_mem_r8": + return ref_vcmpps(a, seed, 0x12, wide=True, daz=daz) + if name == "op_vcmppd_ymm_mem_rcx": + return ref_vcmppd(b, a, 0x0D, wide=True, daz=daz) + if name == "op_vcmppd_ymm_mem_rdx": + return ref_vcmppd(a, b, 0x15, wide=True, daz=daz) + if name == "op_vcmppd_ymm_mem_r8": + return ref_vcmppd(a, seed, 0x1E, wide=True, daz=daz) + if name == "op_vcmpss_mem_rcx": + return ref_vcmpss(b, a, 0x01, daz=daz) + if name == "op_vcmpss_mem_rdx": + return ref_vcmpss(a, b, 0x11, daz=daz) + if name == "op_vcmpss_mem_r8": + return ref_vcmpss(a, seed, 0x0C, daz=daz) + if name == "op_vcmpsd_mem_rcx": + return ref_vcmpsd(b, a, 0x02, daz=daz) + if name == "op_vcmpsd_mem_rdx": + return ref_vcmpsd(a, b, 0x0E, daz=daz) + if name == "op_vcmpsd_mem_r8": + return ref_vcmpsd(a, seed, 0x1D, daz=daz) + if name == "op_vcmpps_imm_highbits": + return ref_vcmpps(a, b, 0x05, wide=True, daz=daz) + if name == "op_vcmpps_alias_dst_src1": + return ref_vcmpps(a, b, 0x04, wide=True, daz=daz) + if name == "op_vcmppd_alias_dst_src2": + return ref_vcmppd(a, b, 0x06, wide=True, daz=daz) + if name == "op_vcmpps_alias_src1_src2": + return ref_vcmpps(a, a, 0x03, wide=True, daz=daz) + if name == "op_vcmpsd_alias_all": + return ref_vcmpsd(a, a, 0x00, daz=daz) + if name == "op_vmovss_mem_glue": + res = ref_vcmpss(a[:4] + b"\x00" * 12, b[:4] + b"\x00" * 12, 0x01, daz=daz) + return res[:4] + seed[4:] + if name == "op_vmovsd_mem_glue": + res = ref_vcmpsd(a[:8] + b"\x00" * 8, b[:8] + b"\x00" * 8, 0x01, daz=daz) + return res[:8] + seed[8:] + if name == "op_vmovss_reg_merge_glue": + return b[:4] + a[4:16] + b"\x00" * 16 + if name == "op_vmovsd_reg_merge_glue": + return b[:8] + a[8:16] + b"\x00" * 16 + if name == "op_vmov_aligned_glue": + return ref_vcmpps(a, b, 0x0C, wide=True, daz=daz) + raise KeyError(name) + + +def check_translator(original_path: Path) -> None: + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_avx" in source_cpp, len(meta) + assert "<immintrin.h>" not in source_cpp + + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPD_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)) + ld_xmm2 = Instruction.create_reg_mem(Code.VEX_VMOVAPD_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)) + ld_xmm4 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM4, MemoryOperand(R.RCX)) + ld_xmm5 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM5, MemoryOperand(R.RDX)) + ld_ymm4 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM4, MemoryOperand(R.RCX)) + ld_ymm5 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM5, MemoryOperand(R.RDX)) + st_xmm0 = Instruction.create_mem_reg(Code.VEX_VMOVUPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + st_ymm0 = Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8), R.YMM0) + vzero = Instruction.create(Code.VEX_VZEROUPPER) + ret_ins = Instruction.create(Code.RETNQ) + + # Positive lift checks across all 6 VCMP Codes, reg & [rcx|rdx|r8] mem-src, and alternate encodings. + accepted = 0 + for code, wide, helper, is_scalar, is_double in ( + (Code.VEX_VCMPPS_XMM_XMM_XMMM128_IMM8, False, "op_vcmpps", False, False), + (Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, True, "op_vcmpps", False, False), + (Code.VEX_VCMPPD_XMM_XMM_XMMM128_IMM8, False, "op_vcmppd", False, True), + (Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8, True, "op_vcmppd", False, True), + (Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8, False, "op_vcmpss", True, False), + (Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8, False, "op_vcmpsd", True, True), + ): + dst, s1, s2 = (R.YMM4, R.YMM4, R.YMM5) if wide else (R.XMM4, R.XMM4, R.XMM5) + loads = (ld_ymm4, ld_ymm5) if wide else (ld_xmm4, ld_xmm5) + st_code = Code.VEX_VMOVUPS_YMMM256_YMM if wide else Code.VEX_VMOVUPS_XMMM128_XMM + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_reg_u32(code, dst, s1, s2, 0x3F), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + vzero, + ret_ins, + ), + ) + assert f"{helper}(" in reg_src and "0x1fu" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + loads[0], + Instruction.create_reg_reg_mem_u32(code, dst, s1, MemoryOperand(base), 0x11), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + ret_ins, + ), + ) + loader = ( + ("load64" if is_double else "load32") + if is_scalar + else ("load256" if wide else "load128") + ) + assert f"{loader}(" in mem_src, mem_src + accepted += 1 + + # Alternate VMOVSS/VMOVSD 0F11 encodings. + for alt_code, helper in ( + (Code.VEX_VMOVSS_XMM_XMM_XMM_0F11, "op_vmovss_reg"), + (Code.VEX_VMOVSD_XMM_XMM_XMM_0F11, "op_vmovsd_reg"), + ): + alt_src, _ = lift_code( + f"alt_{helper}", + 0x1000, + encode_seq( + ld_xmm4, + ld_xmm5, + Instruction.create_reg_reg_reg(alt_code, R.XMM0, R.XMM4, R.XMM5), + st_xmm0, + ret_ins, + ), + ) + assert f"{helper}(ymm4," in alt_src, alt_src + accepted += 1 + + evex_ps = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPPS_KR_K1_XMM_XMMM128B32_IMM8, R.K1, R.XMM0, R.XMM1, 0 + ) + evex_pd = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPPD_KR_K1_YMM_YMMM256B64_IMM8, R.K1, R.YMM1, R.YMM2, 0 + ) + evex_ss = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPSS_KR_K1_XMM_XMMM32_IMM8_SAE, R.K1, R.XMM1, R.XMM2, 0 + ) + evex_sd = Instruction.create_reg_reg_reg_u32( + Code.EVEX_VCMPSD_KR_K1_XMM_XMMM64_IMM8_SAE, R.K1, R.XMM1, R.XMM2, 0 + ) + evex_mov = Instruction.create_reg_mem( + Code.EVEX_VMOVAPS_YMM_K1Z_YMMM256, R.YMM0, MemoryOperand(R.RCX) + ) + seg_ins = Instruction.create_reg_reg_mem_u32( + Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RDX), 0 + ) + seg_ins.segment_prefix = R.FS + + rejects = [ + ("evex_vcmpps", (ld_xmm1, evex_ps, ret_ins), "unsupported EVEX instruction"), + ("evex_vcmppd", (ld_ymm1, ld_ymm2, evex_pd, ret_ins), "unsupported EVEX instruction"), + ("evex_vcmpss", (ld_xmm1, ld_xmm2, evex_ss, ret_ins), "unsupported EVEX instruction"), + ("evex_vcmpsd", (ld_xmm1, ld_xmm2, evex_sd, ret_ins), "unsupported EVEX instruction"), + ("evex_vmovaps", (evex_mov, ret_ins), "unsupported EVEX instruction"), + ("legacy_cmpps", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPPS_XMM_XMMM128_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_cmppd", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPPD_XMM_XMMM128_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_cmpss", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPSS_XMM_XMMM32_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_cmpsd", (ld_xmm1, ld_xmm2, Instruction.create_reg_reg_u32(Code.CMPSD_XMM_XMMM64_IMM8, R.XMM1, R.XMM2, 0), ret_ins), "unsupported legacy SSE instruction"), + ("legacy_movaps", (Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)), ret_ins), "unsupported legacy SSE instruction"), + ("other_insn_vaddps", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret_ins), "unsupported instruction"), + ("nonvol_ymm6_dst", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM6, R.YMM1, R.YMM2, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_src2", (ld_xmm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, R.XMM15, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_ymm7_mov", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm8_movss", (Instruction.create_reg_mem(Code.VEX_VMOVSS_XMM_M32, R.XMM8, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("undef_vcmpps_src1", (ld_ymm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM3, R.YMM2, 0), ret_ins), "undefined vector register ymm3"), + ("undef_vcmppd_src2", (ld_ymm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM4, 0), ret_ins), "undefined vector register ymm4"), + ("undef_vcmpss_alias", (ld_xmm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8, R.XMM0, R.XMM0, R.XMM2, 0), ret_ins), "undefined vector register ymm0"), + ("undef_store", (Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8), R.YMM0), ret_ins), "undefined vector register ymm0"), + ("disp_mem_rcx", (ld_ymm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RCX, displ=32, displ_size=1), 0), ret_ins), "unsupported memory operand"), + ("disp_store_r8", (ld_ymm1, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8, displ=32, displ_size=1), R.YMM1), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_ymm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RDX, R.RCX, 4), 0), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_xmm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8, R.XMM0, R.XMM1, MemoryOperand(R.RIP, displ=0x1040, displ_size=4), 0), ret_ins), "unsupported memory operand"), + ("non_arg_base_rax", (ld_ymm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, MemoryOperand(R.RAX), 0), ret_ins), "unsupported memory operand"), + ("nonvol_base_rbx", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM0, MemoryOperand(R.RBX)), ret_ins), "unsupported memory operand"), + ("addr32_ecx", (ld_xmm1, Instruction.create_reg_reg_mem_u32(Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, MemoryOperand(R.ECX), 0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rcx", (ld_ymm1, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.RCX), R.YMM1), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_rdx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVSS_M32_XMM, MemoryOperand(R.RDX), R.XMM1), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_sd_rcx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVSD_M64_XMM, MemoryOperand(R.RCX), R.XMM1), ret_ins), "non-r8 store memory operand"), + ("seg_prefix", (ld_ymm1, seg_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg_u32(Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0), st_ymm0), "missing terminal ret"), + ("after_ret", (ld_ymm1, ret_ins, st_ymm0), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + raw_rejects = [ + ("invalid_bytes", b"\xFF\xFE\xC3", "invalid instruction"), + ("empty_stream", b"", "truncated instruction stream"), + ] + for label, raw, reason in raw_rejects: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: raw stream unexpectedly accepted") + + # CLI failure exit code 1 without traceback and zero leftover temp files. + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + out_dir = root / "out_dir" + out_dir.mkdir() + in_dir = root / "in_dir" + in_dir.mkdir() + for argv, label in ( + ([str(root / "missing.dll"), "op_vcmpps_ymm_p00", str(out_cpp)], "missing_dll"), + ([str(in_dir), "op_vcmpps_ymm_p00", str(out_cpp)], "input_dir"), + ([str(original_path), ",", str(out_cpp)], "empty_exports"), + ([str(original_path), "missing_export_xyz", str(out_cpp)], "missing_export"), + ([str(original_path), "op_vcmpps_ymm_p00", str(out_dir)], "output_dir"), + ): + try: + tool_main(argv) + except SystemExit as exc: + assert exc.code == 1, (label, exc.code) + else: + raise AssertionError(f"{label}: CLI did not exit") + assert not out_cpp.exists() + assert sorted(p.name for p in root.iterdir()) == ["in_dir", "out_dir"] + + print( + f"translator validated: {accepted} forms accepted, " + f"{len(rejects) + len(raw_rejects)} refusal controls and 5 CLI negative checks passed" + ) + + +def host_has_avx(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_avx"): + lifted_lib.host_has_avx.argtypes = [] + lifted_lib.host_has_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_avx()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack("<I", struct.pack("<f", v))[0] for v in vals] + return struct.pack("<8I", *words) + + def _f64(*vals): + words = [v if isinstance(v, int) else struct.unpack("<Q", struct.pack("<d", v))[0] for v in vals] + return struct.pack("<4Q", *words) + + f32_qnan_pos, f32_qnan_neg = 0x7FC01234, 0xFFC05678 + f32_snan_pos, f32_snan_neg = 0x7F800042, 0xFFA00099 + f32_sub_pos, f32_sub_neg = 0x00400001, 0x80400001 + + f32_pairs = ( + (_f32(0x00000000, 0x80000000, 1.5, -2.25, 0x7F800000, 0xFF800000, f32_sub_pos, 0x3F800000), + _f32(0x80000000, 0x00000000, 1.5, 0.75, 0x7F800000, 0x7F800000, 0x00000000, -1.0)), + (_f32(f32_qnan_pos, 1.0, f32_snan_pos, f32_qnan_neg, 2.5, -3.5, f32_sub_neg, 0x7F7FFFFF), + _f32(1.0, f32_qnan_neg, f32_snan_neg, f32_qnan_pos, -4.5, -3.5, 0x80000000, 0xFF7FFFFF)), + # Scalar lane 0 normal/zero/Inf/NaN + distinct upper src1/src2 lanes (lane 1 has sNaN in src1!) + (_f32(1.25, f32_snan_pos, 0x3F800000, 0x40000000, 9.0, 8.0, 7.0, 6.0), + _f32(2.50, 0x11223344, 0x55667788, 0x99AABBCC, -1.0, -2.0, -3.0, -4.0)), + (_f32(f32_qnan_pos, 0x12345678, 0x9ABCDEF0, 0x0F0E0D0C, 3.0, 4.0, 5.0, 6.0), + _f32(f32_qnan_neg, 0xAABBCCDD, 0xEEFF0011, 0x22334455, 7.0, 8.0, 9.0, 10.0)), + ) + + f64_qnan_pos, f64_qnan_neg = 0x7FF8000012345678, 0xFFF8000087654321 + f64_snan_pos, f64_snan_neg = 0x7FF0000000000042, 0xFFF4000000000099 + f64_sub_pos, f64_sub_neg = 0x0008000000000001, 0x8008000000000001 + + f64_pairs = ( + (_f64(0x0000000000000000, 0x8000000000000000, 1.5, -2.25), + _f64(0x8000000000000000, 0x0000000000000000, 1.5, 0.75)), + (_f64(0x7FF0000000000000, 0xFFF0000000000000, f64_sub_pos, f64_sub_neg), + _f64(0x7FF0000000000000, 0x7FF0000000000000, 0x0000000000000000, 0x8000000000000000)), + (_f64(f64_qnan_pos, f64_snan_pos, 2.5, f64_qnan_neg), + _f64(1.0, f64_snan_neg, 2.5, f64_qnan_pos)), + # Scalar lane 0 normal/qNaN + distinct upper src1/src2 lanes (lane 1 has sNaN in src1!) + (_f64(1.25, f64_snan_pos, 3.0, 4.0), + _f64(2.50, 0x1122334455667788, -3.0, -4.0)), + ) + + def invoke(dll, prefix: str, name: str, a_bytes: bytes, b_bytes: bytes, mxcsr: int, align: int = 0): + is_rcx_mem = name.endswith("_mem_rcx") + is_r8_mem = name.endswith("_mem_r8") + _ra, pa = _guarded_buf(a_bytes, align if is_rcx_mem else 0) + _rb, pb = _guarded_buf(b_bytes, 0 if (is_rcx_mem or is_r8_mem) else align) + _rc, pc = _guarded_buf(SEED, align if is_r8_mem else 0) + fn = getattr(dll, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = None + previous = exchange(mxcsr) + try: + fn(pa, pb, pc) + finally: + status = exchange(previous) + return ctypes.string_at(pc, 32), status & 0x3F + + cases = 0 + for name in EXPORTS: + is_pd = ("pd_" in name or "vcmpsd" in name or "vmovsd" in name) + pairs = f64_pairs if is_pd else f32_pairs + for mxcsr, daz in ((MXCSR_DEFAULT, False), (MXCSR_DAZ, True)): + for a_bytes, b_bytes in pairs: + want = ref_export(name, a_bytes, b_bytes, SEED, daz=daz) + got_n, _ = invoke(native, "", name, a_bytes, b_bytes, mxcsr, 0) + got_l, _ = invoke(lifted, "lifted_", name, a_bytes, b_bytes, mxcsr, 0) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} mxcsr={mxcsr:#x}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + if "_mem" in name: + a_bytes, b_bytes = pairs[0] + for off in (1, 3, 7): + want = ref_export(name, a_bytes, b_bytes, SEED, daz=False) + got_n, _ = invoke(native, "", name, a_bytes, b_bytes, MXCSR_DEFAULT, off) + got_l, _ = invoke(lifted, "lifted_", name, a_bytes, b_bytes, MXCSR_DEFAULT, off) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} align={off}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + + # Verify MXCSR.IE quiet vs signaling distinction on qNaN (pair 3 has lane0 qNaN without sNaN). + qnan_ps_a, qnan_ps_b = f32_pairs[3] + qnan_pd_a = _f64(f64_qnan_pos, 1.0, 2.0, 3.0) + qnan_pd_b = _f64(f64_qnan_neg, 4.0, 5.0, 6.0) + quiet_sig_checks = ( + ("op_vcmpps_ymm_p00", qnan_ps_a, qnan_ps_b, 0), # EQ_OQ -> quiet + ("op_vcmpps_ymm_p10", qnan_ps_a, qnan_ps_b, 1), # EQ_OS -> signaling + ("op_vcmpps_ymm_p11", qnan_ps_a, qnan_ps_b, 0), # LT_OQ -> quiet + ("op_vcmpps_ymm_p01", qnan_ps_a, qnan_ps_b, 1), # LT_OS -> signaling + ("op_vcmpps_ymm_p0f", qnan_ps_a, qnan_ps_b, 0), # TRUE_UQ -> quiet + ("op_vcmpps_ymm_p1f", qnan_ps_a, qnan_ps_b, 1), # TRUE_US -> signaling + ("op_vcmppd_ymm_p11", qnan_pd_a, qnan_pd_b, 0), # LT_OQ -> quiet + ("op_vcmppd_ymm_p01", qnan_pd_a, qnan_pd_b, 1), # LT_OS -> signaling + ("op_vcmpss_p11", qnan_ps_a, qnan_ps_b, 0), # scalar LT_OQ -> quiet (ignores lane1!) + ("op_vcmpss_p01", qnan_ps_a, qnan_ps_b, 1), # scalar LT_OS -> signaling + ("op_vcmpsd_p11", qnan_pd_a, qnan_pd_b, 0), # scalar LT_OQ -> quiet + ("op_vcmpsd_p01", qnan_pd_a, qnan_pd_b, 1), # scalar LT_OS -> signaling + ) + for name, a_bytes, b_bytes, want_ie in quiet_sig_checks: + _, st_n = invoke(native, "", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + _, st_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + if (st_n & 1) != want_ie or (st_l & 1) != want_ie: + raise AssertionError( + f"{name} MXCSR.IE mismatch: want={want_ie} native={st_n:#x} lifted={st_l:#x}" + ) + # Scalar sNaN in upper lane 1 must NOT trigger IE on lane 0 non-NaN operands. + _, st_scalar_n = invoke(native, "", "op_vcmpss_p01", f32_pairs[2][0], f32_pairs[2][1], MXCSR_DEFAULT, 0) + _, st_scalar_l = invoke(lifted, "lifted_", "op_vcmpss_p01", f32_pairs[2][0], f32_pairs[2][1], MXCSR_DEFAULT, 0) + assert (st_scalar_n & 1) == 0 and (st_scalar_l & 1) == 0, (st_scalar_n, st_scalar_l) + + # Altered controls must diverge from original and match altered native DLL. + for name, alt_ref_name in ALTERED_CASES: + is_pd = "pd_" in name or "vcmpsd" in name + a_bytes, b_bytes = (f64_pairs if is_pd else f32_pairs)[0] + if name == "op_vcmpss_p02": + a_bytes, b_bytes = f32_pairs[2] + want_orig = ref_export(name, a_bytes, b_bytes, SEED) + want_alt = ref_vcmpss(b_bytes, a_bytes, 0x02) + elif name == "op_vcmpsd_mem_rdx": + want_orig = ref_export(name, a_bytes, b_bytes, SEED) + want_alt = ref_vcmpsd(a_bytes, b_bytes, 0x0A) + else: + want_orig = ref_export(name, a_bytes, b_bytes, SEED) + want_alt = ref_export(alt_ref_name, a_bytes, b_bytes, SEED) + got_alt_n, _ = invoke(altered_native, "", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + got_alt_l, _ = invoke(altered_lifted, "lifted_", name, a_bytes, b_bytes, MXCSR_DEFAULT, 0) + assert got_alt_n == want_alt and got_alt_l == want_alt, ( + name, got_alt_n.hex(), got_alt_l.hex(), want_alt.hex() + ) + assert got_alt_l != want_orig, f"altered {name} failed to diverge from original" + + print( + f"{cases} AVX VEX FP compare cases across {len(EXPORTS)} exports, 32 predicates, " + f"DAZ/IE modes matched native DLL and IEEE-754 reference; {len(ALTERED_CASES)} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + mnemonic_names = { + val: key.lower() + for key, val in vars(Mnemonic).items() + if not key.startswith("_") and isinstance(val, int) + } + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(mnemonic_names[ins.mnemonic]) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_avx(lifted_lib): + print("Host lacks CPUID.01H:ECX[27:28] + XGETBV[2:1]; skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/avx_horiz_fp_aot.asm b/tests/cpu/avx_horiz_fp_aot.asm new file mode 100644 index 0000000000..7678a4a821 --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot.asm @@ -0,0 +1,329 @@ +; coverage: record cpu_aot_avx_horiz_fp_dedicated +; Source-owned MASM fixture for VEX.128 and VEX.256 AVX horizontal and alternating +; floating-point add/sub ops (vhaddps, vhaddpd, vhsubps, vhsubpd, vaddsubps, vaddsubpd). +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +op_vhaddps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vhaddps xmm0, xmm1, xmm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_xmm_reg ENDP + +op_vhaddpd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhaddpd ymm0, ymm1, ymm2 +ELSE + vhaddpd xmm0, xmm1, xmm2 +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_xmm_reg ENDP + +op_vhsubps_xmm_reg PROC FRAME + .endprolog + vmovaps ymm0, YMMWORD PTR [r8] + vmovaps ymm1, YMMWORD PTR [rcx] + vmovaps ymm2, YMMWORD PTR [rdx] + vhsubps xmm0, xmm1, xmm2 + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_xmm_reg ENDP + +op_vhsubpd_xmm_reg PROC FRAME + .endprolog + vmovapd ymm0, YMMWORD PTR [r8] + vmovapd ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vhsubpd xmm0, xmm1, xmm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_xmm_reg ENDP + +op_vaddsubps_xmm_reg PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vaddsubps xmm0, xmm1, xmm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_xmm_reg ENDP + +op_vaddsubpd_xmm_reg PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vaddsubpd xmm0, xmm1, xmm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_reg ENDP + +op_vhaddps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vhaddps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_xmm_mem ENDP + +op_vhaddpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vhaddpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_xmm_mem ENDP + +op_vhsubps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_xmm_mem ENDP + +op_vhsubpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vhsubpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_xmm_mem ENDP + +op_vaddsubps_xmm_mem PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [r8] + vmovups ymm1, YMMWORD PTR [rcx] + vaddsubps xmm0, xmm1, XMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_xmm_mem ENDP + +op_vaddsubpd_xmm_mem PROC FRAME + .endprolog + vmovupd ymm0, YMMWORD PTR [r8] + vmovupd ymm1, YMMWORD PTR [rcx] + vaddsubpd xmm0, xmm1, XMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_mem ENDP + +op_vhaddps_ymm_reg PROC FRAME + .endprolog + vmovaps ymm1, YMMWORD PTR [rcx] + vmovaps ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhsubps ymm0, ymm1, ymm2 +ELSE + vhaddps ymm0, ymm1, ymm2 +ENDIF + vmovaps YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_reg ENDP + +op_vhaddpd_ymm_reg PROC FRAME + .endprolog + vmovapd ymm1, YMMWORD PTR [rcx] + vmovapd ymm2, YMMWORD PTR [rdx] + vhaddpd ymm0, ymm1, ymm2 + vmovapd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_reg ENDP + +op_vhsubps_ymm_reg PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] + vhsubps ymm0, ymm1, ymm2 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_reg ENDP + +op_vhsubpd_ymm_reg PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vhsubpd ymm0, ymm1, ymm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_ymm_reg ENDP + +op_vaddsubps_ymm_reg PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vmovups ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_AVX_HORIZ_FP + vhaddps ymm0, ymm1, ymm2 +ELSE + vaddsubps ymm0, ymm1, ymm2 +ENDIF + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_reg ENDP + +op_vaddsubpd_ymm_reg PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm2, YMMWORD PTR [rdx] + vaddsubpd ymm0, ymm1, ymm2 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_reg ENDP + +op_vhaddps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhaddps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_mem ENDP + +op_vhaddpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vhaddpd ymm0, ymm1, YMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_mem ENDP + +op_vhsubps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_mem ENDP + +op_vhsubpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vhsubpd ymm0, ymm1, YMMWORD PTR [rdx] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubpd_ymm_mem ENDP + +op_vaddsubps_ymm_mem PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vaddsubps ymm0, ymm1, YMMWORD PTR [rdx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_mem ENDP + +op_vaddsubpd_ymm_mem PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_AVX_HORIZ_FP + vhsubpd ymm0, ymm1, YMMWORD PTR [rdx] +ELSE + vaddsubpd ymm0, ymm1, YMMWORD PTR [rdx] +ENDIF + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_mem ENDP + +op_vhaddps_ymm_mem_rcx PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rdx] + vhaddps ymm0, ymm1, YMMWORD PTR [rcx] + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_mem_rcx ENDP + +op_vaddsubpd_ymm_mem_r8 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vaddsubpd ymm0, ymm1, YMMWORD PTR [r8] + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_ymm_mem_r8 ENDP + +op_vhaddps_ymm_alias_dst_src1 PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vmovups ymm1, YMMWORD PTR [rdx] + vhaddps ymm0, ymm0, ymm1 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddps_ymm_alias_dst_src1 ENDP + +op_vhaddpd_ymm_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vhaddpd ymm0, ymm1, ymm0 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhaddpd_ymm_alias_dst_src2 ENDP + +op_vhsubps_ymm_alias_src1_src2 PROC FRAME + .endprolog + vmovups ymm1, YMMWORD PTR [rcx] + vhsubps ymm0, ymm1, ymm1 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vhsubps_ymm_alias_src1_src2 ENDP + +op_vaddsubps_ymm_alias_all PROC FRAME + .endprolog + vmovups ymm0, YMMWORD PTR [rcx] + vaddsubps ymm0, ymm0, ymm0 + vmovups YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubps_ymm_alias_all ENDP + +op_vaddsubpd_xmm_alias_dst_src2 PROC FRAME + .endprolog + vmovupd ymm1, YMMWORD PTR [rcx] + vmovupd ymm0, YMMWORD PTR [rdx] + vaddsubpd xmm0, xmm1, xmm0 + vmovupd YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vaddsubpd_xmm_alias_dst_src2 ENDP + +END diff --git a/tests/cpu/avx_horiz_fp_aot.def b/tests/cpu/avx_horiz_fp_aot.def new file mode 100644 index 0000000000..b0a2748a62 --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot.def @@ -0,0 +1,32 @@ +EXPORTS + op_vhaddps_xmm_reg + op_vhaddpd_xmm_reg + op_vhsubps_xmm_reg + op_vhsubpd_xmm_reg + op_vaddsubps_xmm_reg + op_vaddsubpd_xmm_reg + op_vhaddps_xmm_mem + op_vhaddpd_xmm_mem + op_vhsubps_xmm_mem + op_vhsubpd_xmm_mem + op_vaddsubps_xmm_mem + op_vaddsubpd_xmm_mem + op_vhaddps_ymm_reg + op_vhaddpd_ymm_reg + op_vhsubps_ymm_reg + op_vhsubpd_ymm_reg + op_vaddsubps_ymm_reg + op_vaddsubpd_ymm_reg + op_vhaddps_ymm_mem + op_vhaddpd_ymm_mem + op_vhsubps_ymm_mem + op_vhsubpd_ymm_mem + op_vaddsubps_ymm_mem + op_vaddsubpd_ymm_mem + op_vhaddps_ymm_mem_rcx + op_vaddsubpd_ymm_mem_r8 + op_vhaddps_ymm_alias_dst_src1 + op_vhaddpd_ymm_alias_dst_src2 + op_vhsubps_ymm_alias_src1_src2 + op_vaddsubps_ymm_alias_all + op_vaddsubpd_xmm_alias_dst_src2 diff --git a/tests/cpu/avx_horiz_fp_aot_check.py b/tests/cpu/avx_horiz_fp_aot_check.py new file mode 100644 index 0000000000..bbfa86d5df --- /dev/null +++ b/tests/cpu/avx_horiz_fp_aot_check.py @@ -0,0 +1,419 @@ +"""Differential, boundary, mutation, refusal, and coverage-record checks for dedicated AVX horizontal/addsub FP AOT.""" + +import ctypes +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from avx_horiz_fp import F32, F64, _guarded_buf # noqa: E402 +from cpu_avx_horiz_fp_aot import lift_code, main as tool_main, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + + +EXPORTS = ( + "op_vhaddps_xmm_reg", + "op_vhaddpd_xmm_reg", + "op_vhsubps_xmm_reg", + "op_vhsubpd_xmm_reg", + "op_vaddsubps_xmm_reg", + "op_vaddsubpd_xmm_reg", + "op_vhaddps_xmm_mem", + "op_vhaddpd_xmm_mem", + "op_vhsubps_xmm_mem", + "op_vhsubpd_xmm_mem", + "op_vaddsubps_xmm_mem", + "op_vaddsubpd_xmm_mem", + "op_vhaddps_ymm_reg", + "op_vhaddpd_ymm_reg", + "op_vhsubps_ymm_reg", + "op_vhsubpd_ymm_reg", + "op_vaddsubps_ymm_reg", + "op_vaddsubpd_ymm_reg", + "op_vhaddps_ymm_mem", + "op_vhaddpd_ymm_mem", + "op_vhsubps_ymm_mem", + "op_vhsubpd_ymm_mem", + "op_vaddsubps_ymm_mem", + "op_vaddsubpd_ymm_mem", + "op_vhaddps_ymm_mem_rcx", + "op_vaddsubpd_ymm_mem_r8", + "op_vhaddps_ymm_alias_dst_src1", + "op_vhaddpd_ymm_alias_dst_src2", + "op_vhsubps_ymm_alias_src1_src2", + "op_vaddsubps_ymm_alias_all", + "op_vaddsubpd_xmm_alias_dst_src2", +) + +ALTERED_CASES = ( + ("op_vhaddps_ymm_reg", "op_vhsubps_ymm_reg"), + ("op_vaddsubps_ymm_reg", "op_vhaddps_ymm_reg"), + ("op_vaddsubpd_ymm_mem", "op_vhsubpd_ymm_mem"), +) + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _lane_ps(kind: str, lane_a: bytes, lane_b: bytes, mxcsr: int) -> bytes: + xa = struct.unpack("<4I", lane_a) + xb = struct.unpack("<4I", lane_b) + if kind == "vhadd": + vals = ( + F32.add(xa[0], xa[1], mxcsr), + F32.add(xa[2], xa[3], mxcsr), + F32.add(xb[0], xb[1], mxcsr), + F32.add(xb[2], xb[3], mxcsr), + ) + elif kind == "vhsub": + vals = ( + F32.sub(xa[0], xa[1], mxcsr), + F32.sub(xa[2], xa[3], mxcsr), + F32.sub(xb[0], xb[1], mxcsr), + F32.sub(xb[2], xb[3], mxcsr), + ) + elif kind == "vaddsub": + vals = ( + F32.sub(xa[0], xb[0], mxcsr), + F32.add(xa[1], xb[1], mxcsr), + F32.sub(xa[2], xb[2], mxcsr), + F32.add(xa[3], xb[3], mxcsr), + ) + else: + raise ValueError(kind) + return struct.pack("<4I", *vals) + + +def _lane_pd(kind: str, lane_a: bytes, lane_b: bytes, mxcsr: int) -> bytes: + xa = struct.unpack("<2Q", lane_a) + xb = struct.unpack("<2Q", lane_b) + if kind == "vhadd": + vals = (F64.add(xa[0], xa[1], mxcsr), F64.add(xb[0], xb[1], mxcsr)) + elif kind == "vhsub": + vals = (F64.sub(xa[0], xa[1], mxcsr), F64.sub(xb[0], xb[1], mxcsr)) + elif kind == "vaddsub": + vals = (F64.sub(xa[0], xb[0], mxcsr), F64.add(xa[1], xb[1], mxcsr)) + else: + raise ValueError(kind) + return struct.pack("<2Q", *vals) + + +def ref_op(name: str, a: bytes, b: bytes, mxcsr: int) -> bytes: + if name == "op_vhaddps_ymm_mem_rcx": + a, b = b, a + elif name in ("op_vhsubps_ymm_alias_src1_src2", "op_vaddsubps_ymm_alias_all"): + b = a + is_xmm = "_xmm_" in name + is_pd = "pd_" in name + if "vhadd" in name: + kind = "vhadd" + elif "vhsub" in name: + kind = "vhsub" + elif "vaddsub" in name: + kind = "vaddsub" + else: + raise KeyError(name) + lane_fn = _lane_pd if is_pd else _lane_ps + lo = lane_fn(kind, a[0:16], b[0:16], mxcsr) + if is_xmm: + return lo + b"\x00" * 16 + return lo + lane_fn(kind, a[16:32], b[16:32], mxcsr) + + +def check_translator(original_path: Path): + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_avx" in source_cpp, meta + + ld_ymm0 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_YMM_YMMM256, R.YMM0, MemoryOperand(R.RCX)) + ld_ymm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM1, MemoryOperand(R.RCX)) + ld_ymm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPD_YMM_YMMM256, R.YMM2, MemoryOperand(R.RDX)) + ld_xmm1 = Instruction.create_reg_mem(Code.VEX_VMOVAPD_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)) + ld_xmm2 = Instruction.create_reg_mem(Code.VEX_VMOVUPS_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)) + ret_ins = Instruction.create(Code.RETNQ) + vzero = Instruction.create(Code.VEX_VZEROUPPER) + + # All 12 horizontal/addsub codes (6 mnemonics x XMM/YMM) in reg & flat [rcx|rdx|r8] mem-src forms. + accepted = 0 + for code, is_ymm, helper in ( + (Code.VEX_VHADDPS_XMM_XMM_XMMM128, False, "op_vhaddps"), + (Code.VEX_VHADDPS_YMM_YMM_YMMM256, True, "op_vhaddps"), + (Code.VEX_VHADDPD_XMM_XMM_XMMM128, False, "op_vhaddpd"), + (Code.VEX_VHADDPD_YMM_YMM_YMMM256, True, "op_vhaddpd"), + (Code.VEX_VHSUBPS_XMM_XMM_XMMM128, False, "op_vhsubps"), + (Code.VEX_VHSUBPS_YMM_YMM_YMMM256, True, "op_vhsubps"), + (Code.VEX_VHSUBPD_XMM_XMM_XMMM128, False, "op_vhsubpd"), + (Code.VEX_VHSUBPD_YMM_YMM_YMMM256, True, "op_vhsubpd"), + (Code.VEX_VADDSUBPS_XMM_XMM_XMMM128, False, "op_vaddsubps"), + (Code.VEX_VADDSUBPS_YMM_YMM_YMMM256, True, "op_vaddsubps"), + (Code.VEX_VADDSUBPD_XMM_XMM_XMMM128, False, "op_vaddsubpd"), + (Code.VEX_VADDSUBPD_YMM_YMM_YMMM256, True, "op_vaddsubpd"), + ): + dst, s1, s2 = (R.YMM0, R.YMM1, R.YMM2) if is_ymm else (R.XMM0, R.XMM1, R.XMM2) + loads = (ld_ymm1, ld_ymm2) if is_ymm else (ld_xmm1, ld_xmm2) + st_code = Code.VEX_VMOVUPS_YMMM256_YMM if is_ymm else Code.VEX_VMOVUPS_XMMM128_XMM + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_reg(code, dst, s1, s2), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + vzero, + ret_ins, + ), + ) + assert f"{helper}(ymm1, ymm2, {'true' if is_ymm else 'false'})" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + loads[0], + Instruction.create_reg_reg_mem(code, dst, s1, MemoryOperand(base)), + Instruction.create_mem_reg(st_code, MemoryOperand(R.R8), dst), + ret_ins, + ), + ) + loader = "load256" if is_ymm else "load128" + assert f"{helper}(ymm1, {loader}(" in mem_src, mem_src + accepted += 1 + + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VADDPS_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2) + evex_ins.op_mask = R.K1 + seg_mem = MemoryOperand(R.RDX) + seg_prefix_ins = Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, seg_mem) + seg_prefix_ins.segment_prefix = R.FS + + rejects = [ + ("evex", (ld_ymm1, ld_ymm2, evex_ins, ret_ins), "unsupported EVEX instruction"), + ("legacy_sse", (ld_xmm1, ld_xmm2, Instruction.create_reg_mem(Code.HADDPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX)), ret_ins), "unsupported instruction"), + ("nonvol_ymm6_dst", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM6, R.YMM1, R.YMM2), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_src", (ld_xmm1, Instruction.create_reg_reg_reg(Code.VEX_VHSUBPD_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM15), ret_ins), "nonvolatile vector register"), + ("nonvol_ymm7_move", (Instruction.create_reg_mem(Code.VEX_VMOVAPS_YMM_YMMM256, R.YMM7, MemoryOperand(R.RCX)), ret_ins), "nonvolatile vector register"), + ("undef_ymm3", (ld_ymm1, Instruction.create_reg_reg_reg(Code.VEX_VHADDPD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret_ins), "undefined vector register ymm3"), + ("undef_alias_dst", (ld_ymm1, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM0, R.YMM1), ret_ins), "undefined vector register ymm0"), + ("disp_mem_rcx", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RCX, displ=32, displ_size=1)), ret_ins), "unsupported memory operand"), + ("disp_mem_rdx", (ld_xmm1, Instruction.create_reg_reg_mem(Code.VEX_VADDSUBPS_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.RDX, displ=16, displ_size=1)), ret_ins), "unsupported memory operand"), + ("disp_store_r8", (ld_ymm0, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.R8, displ=32, displ_size=1), R.YMM0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rcx", (ld_ymm0, Instruction.create_mem_reg(Code.VEX_VMOVUPS_YMMM256_YMM, MemoryOperand(R.RCX), R.YMM0), ret_ins), "unsupported memory operand"), + ("non_r8_store_rdx", (ld_xmm1, Instruction.create_mem_reg(Code.VEX_VMOVAPD_XMMM128_XMM, MemoryOperand(R.RDX), R.XMM1), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHSUBPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RDX, R.RCX, 1)), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VADDSUBPD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RIP, displ=0x1040, displ_size=4)), ret_ins), "unsupported memory operand"), + ("non_arg_base_rax", (ld_ymm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, MemoryOperand(R.RAX)), ret_ins), "unsupported memory operand"), + ("addr32_ecx", (ld_xmm1, Instruction.create_reg_reg_mem(Code.VEX_VHADDPS_XMM_XMM_XMMM128, R.XMM0, R.XMM1, MemoryOperand(R.ECX)), ret_ins), "unsupported memory operand"), + ("seg_prefix", (ld_ymm1, seg_prefix_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_ymm1, ld_ymm2, Instruction.create_reg_reg_reg(Code.VEX_VHADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), "missing terminal ret"), + ("after_ret", (ld_ymm1, ret_ins, ld_ymm2), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + # Verify CLI failure exit code 1 without traceback and zero temp files. + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + try: + tool_main([str(root / "missing.dll"), "op_vhaddps_ymm_reg", str(out_cpp)]) + except SystemExit as exc: + assert exc.code == 1, exc.code + else: + raise AssertionError("missing DLL did not exit") + assert not out_cpp.exists() and list(root.iterdir()) == [] + + print(f"translator validated: {accepted} forms accepted, {len(rejects)} refusal controls passed") + + +def host_has_avx(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_avx"): + lifted_lib.host_has_avx.argtypes = [] + lifted_lib.host_has_avx.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_avx()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack("<I", struct.pack("<f", v))[0] for v in vals] + return struct.pack("<8I", *words) + + def _f64(*vals): + words = [v if isinstance(v, int) else struct.unpack("<Q", struct.pack("<d", v))[0] for v in vals] + return struct.pack("<4Q", *words) + + f32_qnan_pos, f32_qnan_neg = 0x7FC01234, 0xFFC05678 + f32_snan_pos, f32_snan_neg = 0x7F800042, 0xFFA00099 + f32_sub_pos, f32_sub_neg = 0x00400001, 0x80400001 + f32_min_norm = 0x00800000 + f32_one_half_min_norm = 0x00C00000 + f32_max_fin = 0x7F7FFFFF + + f32_pairs = ( + (_f32(1.5, -2.25, 1.0, 2.0 ** -24, 3.5, 0.125, -1.0, -(2.0 ** -24)), + _f32(4.25, 0.75, f32_min_norm, f32_sub_neg, -7.5, 2.5, f32_sub_pos, f32_sub_pos)), + (_f32(0x00000000, 0x00000000, 0x80000000, 0x80000000, f32_one_half_min_norm, f32_min_norm | 0x80000000, 1.5, -1.5), + _f32(0x00000000, 0x80000000, 0x00000000, 0x80000000, f32_one_half_min_norm | 0x80000000, f32_min_norm, 2.5, 2.5)), + (_f32(0x7F800000, 0x7F800000, 0x7F800000, 0xFF800000, f32_max_fin, f32_max_fin, f32_sub_pos, f32_sub_pos), + _f32(0x7F800000, 1.0, 0xFF800000, 0xFF800000, f32_max_fin | 0x80000000, f32_max_fin | 0x80000000, f32_min_norm, f32_min_norm | 0x80000000)), + (_f32(f32_qnan_pos, 1.0, 2.0, f32_snan_pos, f32_qnan_pos, f32_qnan_neg, f32_snan_pos, f32_snan_neg), + _f32(f32_snan_neg, f32_qnan_neg, f32_qnan_neg, 3.0, f32_snan_neg, f32_qnan_pos, f32_qnan_pos, f32_snan_pos)), + ) + + f64_qnan_pos, f64_qnan_neg = 0x7FF8000012345678, 0xFFF8000087654321 + f64_snan_pos, f64_snan_neg = 0x7FF0000000000042, 0xFFF4000000000099 + f64_sub_pos, f64_sub_neg = 0x0008000000000001, 0x8008000000000001 + f64_min_norm = 0x0010000000000000 + f64_one_half_min_norm = 0x0018000000000000 + f64_max_fin = 0x7FEFFFFFFFFFFFFF + + f64_pairs = ( + (_f64(1.5, 2.0 ** -53, -3.5, -(2.0 ** -53)), + _f64(f64_min_norm, f64_sub_neg, f64_sub_pos, f64_sub_pos)), + (_f64(0x0000000000000000, 0x8000000000000000, f64_one_half_min_norm, f64_min_norm | 0x8000000000000000), + _f64(2.25, -2.25, 0x0000000000000000, 0x8000000000000000)), + (_f64(0x7FF0000000000000, 0xFFF0000000000000, f64_max_fin, f64_max_fin), + _f64(0x7FF0000000000000, 0x7FF0000000000000, f64_max_fin | 0x8000000000000000, f64_max_fin | 0x8000000000000000)), + (_f64(f64_qnan_pos, 1.0, f64_snan_pos, f64_qnan_neg), + _f64(f64_snan_neg, f64_qnan_neg, 2.0, f64_snan_pos)), + ) + + mxcsr_modes = (0x1F80, 0x3F80, 0x5F80, 0x7F80, 0x1FC0, 0x9F80, 0x9FC0) + cases = 0 + + def invoke(dll, prefix: str, name: str, a_bytes: bytes, b_bytes: bytes, mxcsr: int, align: int = 0) -> bytes: + _ra, pa = _guarded_buf(a_bytes, align if name == "op_vhaddps_ymm_mem_rcx" else 0) + _rb, pb = _guarded_buf(b_bytes, 0 if name in ("op_vhaddps_ymm_mem_rcx", "op_vaddsubpd_ymm_mem_r8") else align) + seed = b_bytes if name == "op_vaddsubpd_ymm_mem_r8" else b"\xCC" * 32 + _rc, pc = _guarded_buf(seed, align if name == "op_vaddsubpd_ymm_mem_r8" else 0) + fn = getattr(dll, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = None + previous = exchange(mxcsr) + try: + fn(pa, pb, pc) + finally: + exchange(previous) + return ctypes.string_at(pc, 32) + + for name in EXPORTS: + pairs = f64_pairs if "pd_" in name else f32_pairs + for mxcsr in mxcsr_modes: + for a_bytes, b_bytes in pairs: + want = ref_op(name, a_bytes, b_bytes, mxcsr) + got_n = invoke(native, "", name, a_bytes, b_bytes, mxcsr, 0) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, mxcsr, 0) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} mxcsr={mxcsr:#x}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + if "_mem" in name: + a_bytes, b_bytes = pairs[0] + for off in (1, 3, 7): + want = ref_op(name, a_bytes, b_bytes, 0x1F80) + got_n = invoke(native, "", name, a_bytes, b_bytes, 0x1F80, off) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, off) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} align={off}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + + # Altered controls must diverge from original and match altered native DLL. + for name, alt_ref_name in ALTERED_CASES: + pairs = f64_pairs if "pd_" in name else f32_pairs + a_bytes, b_bytes = pairs[0] + want_orig = ref_op(name, a_bytes, b_bytes, 0x1F80) + want_alt = ref_op(alt_ref_name, a_bytes, b_bytes, 0x1F80) + got_alt_n = invoke(altered_native, "", name, a_bytes, b_bytes, 0x1F80, 0) + got_alt_l = invoke(altered_lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, 0) + assert got_alt_n == want_alt and got_alt_l == want_alt, (name, got_alt_n.hex(), got_alt_l.hex(), want_alt.hex()) + assert got_alt_l != want_orig, f"altered {name} failed to diverge from original" + + # Altered XMM zeroing control: vhaddpd ymm0 instead of xmm0 leaves bits [255:128] non-zero. + a64, b64 = f64_pairs[0] + want_xmm_orig = ref_op("op_vhaddpd_xmm_reg", a64, b64, 0x1F80) + got_xmm_alt_n = invoke(altered_native, "", "op_vhaddpd_xmm_reg", a64, b64, 0x1F80, 0) + got_xmm_alt_l = invoke(altered_lifted, "lifted_", "op_vhaddpd_xmm_reg", a64, b64, 0x1F80, 0) + assert got_xmm_alt_n == got_xmm_alt_l, (got_xmm_alt_n.hex(), got_xmm_alt_l.hex()) + assert got_xmm_alt_l[:16] == want_xmm_orig[:16] and got_xmm_alt_l[16:] != b"\x00" * 16, got_xmm_alt_l.hex() + + print( + f"{cases} AVX horizontal/addsub FP cases across {len(EXPORTS)} exports and {len(mxcsr_modes)} MXCSR modes " + f"matched native DLL and IEEE-754 reference; {len(ALTERED_CASES) + 1} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_avx(lifted_lib): + print("Host lacks CPUID.01H:ECX[27:28] + XGETBV[2:1]; skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/avx_int_regs_check.py b/tests/cpu/avx_int_regs_check.py index c683c53ab5..3a0d0d0980 100644 --- a/tests/cpu/avx_int_regs_check.py +++ b/tests/cpu/avx_int_regs_check.py @@ -707,21 +707,22 @@ def check_rejections(original_path): # 1) VEX.L=1 (256-bit) packed-integer encodings of surviving forms must be rejected explicitly (AVX2, not AVX1). # The 256-bit add, subtract, saturating add and subtract, compare, minimum, maximum, absolute value, - # sign, word shuffle, horizontal, and pack forms are lowered and are covered by avx_int_ymm_addsub_check.py, - # avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, avx_int_ymm_abs_sign_shuf_check.py, - # avx_int_ymm_horizontal_check.py, and avx_int_ymm_pack_check.py. + # sign, word shuffle, horizontal, pack, cross-lane extend, and dword/qword unpack forms are lowered and + # covered by avx_int_ymm_addsub_check.py, avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, + # avx_int_ymm_abs_sign_shuf_check.py, avx_int_ymm_horizontal_check.py, avx_int_ymm_pack_check.py, + # and avx_int_ymm_widen_unpack_check.py. vex256_int_cases = [ ("vpmulhuw_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULHUW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), - ("vpunpckhdq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpsrld_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSRLD_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), ("vpalignr_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPALIGNR_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 4)), ("vpblendvb_ymm", Instruction.create_reg_reg_reg_reg(Code.VEX_VPBLENDVB_YMM_YMM_YMMM256_YMM, R.YMM0, R.YMM1, R.YMM2, R.YMM3)), ("vpblendw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPBLENDW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0xAA)), ("vpmaddwd_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMADDWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vpmulld_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULLD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vmpsadbw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VMPSADBW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0)), - ("vpmovsxbw_ymm", Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM1)), - ("vpmovzxdq_ymm", Instruction.create_reg_reg(Code.VEX_VPMOVZXDQ_YMM_XMMM128, R.YMM0, R.XMM1)), - ("vpunpckldq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpsrld_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSRLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), + ("vpsllq_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSLLQ_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), + ("vpsrlq_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSRLQ_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), ("vpslld_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSLLD_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), ("vpslld_ymm_xmm", Instruction.create_reg_reg_reg(Code.VEX_VPSLLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2)), ("vpsrlq_ymm_imm", Instruction.create_reg_reg_u32(Code.VEX_VPSRLQ_YMM_YMM_IMM8, R.YMM0, R.YMM1, 4)), diff --git a/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py b/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py index 07ae0dc61e..f69a5589e7 100644 --- a/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py +++ b/tests/cpu/avx_int_ymm_abs_sign_shuf_check.py @@ -243,8 +243,8 @@ def check_translator(): "unsupported EVEX instruction"), ("vpshufhw_evex", (loads[0], Instruction.create_reg_reg_u32( Code.EVEX_VPSHUFHW_YMM_K1Z_YMMM256_IMM8, R.YMM0, R.YMM1, 0x1B), ret), "unsupported EVEX instruction"), - ("vpmovsxbw_ymm_xmm_source", (loads[0], Instruction.create_reg_reg( - Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM1), ret), "unsupported VEX.256 (L=1) packed-integer encoding"), + ("vpsrld_ymm_xmm_source", (*loads, Instruction.create_reg_reg_reg( + Code.VEX_VPSRLD_YMM_YMM_XMMM128, R.YMM0, R.YMM1, R.XMM2), ret), "unsupported VEX.256 (L=1) packed-integer encoding"), ("vpshufb_ymm_other_form", (*loads, Instruction.create_reg_reg_reg( Code.VEX_VPSHUFB_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), "unsupported instruction"), ("vpalignr_ymm_other_form", (*loads, Instruction.create_reg_reg_reg_u32( diff --git a/tests/cpu/avx_int_ymm_widen_unpack.asm b/tests/cpu/avx_int_ymm_widen_unpack.asm new file mode 100644 index 0000000000..6a4404912d --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack.asm @@ -0,0 +1,301 @@ +; coverage: source cpu_aot_avx_int_ymm_widen_unpack +; Source-owned differential fixture for 256-bit (VEX.L=1, AVX2) packed-integer +; cross-lane extend moves (VPMOVSX*/VPMOVZX*) and in-lane unpacks (VPUNPCK{L,H}{DQ,QDQ}). +; RCX = const void* input_a (32 bytes) +; RDX = const void* input_b (32 bytes) +; R8 = void* output (32 bytes) +.code + +op_vpmovsxbw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbw ymm0, xmm1 +ELSE + vpmovsxbw ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbw_ymm ENDP + +op_vpmovsxbd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbd ymm0, xmm1 +ELSE + vpmovsxbd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbd_ymm ENDP + +op_vpmovsxbq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxbq ymm0, xmm1 +ELSE + vpmovsxbq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbq_ymm ENDP + +op_vpmovsxwd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxwd ymm0, xmm1 +ELSE + vpmovsxwd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwd_ymm ENDP + +op_vpmovsxwq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxwq ymm0, xmm1 +ELSE + vpmovsxwq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwq_ymm ENDP + +op_vpmovsxdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovzxdq ymm0, xmm1 +ELSE + vpmovsxdq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxdq_ymm ENDP + +op_vpmovzxbw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbw ymm0, xmm1 +ELSE + vpmovzxbw ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbw_ymm ENDP + +op_vpmovzxbd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbd ymm0, xmm1 +ELSE + vpmovzxbd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbd_ymm ENDP + +op_vpmovzxbq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxbq ymm0, xmm1 +ELSE + vpmovzxbq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxbq_ymm ENDP + +op_vpmovzxwd_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxwd ymm0, xmm1 +ELSE + vpmovzxwd ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxwd_ymm ENDP + +op_vpmovzxwq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxwq ymm0, xmm1 +ELSE + vpmovzxwq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxwq_ymm ENDP + +op_vpmovzxdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] +IFDEF ALTER_YMM + vpmovsxdq ymm0, xmm1 +ELSE + vpmovzxdq ymm0, xmm1 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovzxdq_ymm ENDP + +op_vpunpckldq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckhdq ymm0, ymm1, ymm2 +ELSE + vpunpckldq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckldq_ymm ENDP + +op_vpunpckhdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckldq ymm0, ymm1, ymm2 +ELSE + vpunpckhdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckhdq_ymm ENDP + +op_vpunpcklqdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpckhqdq ymm0, ymm1, ymm2 +ELSE + vpunpcklqdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpcklqdq_ymm ENDP + +op_vpunpckhqdq_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpunpcklqdq ymm0, ymm1, ymm2 +ELSE + vpunpckhqdq ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpunpckhqdq_ymm ENDP + +op_vpmovsxbd_ymm_stale_dst PROC FRAME + .endprolog + vmovdqu ymm0, YMMWORD PTR [rdx] + vmovdqu ymm1, YMMWORD PTR [rcx] + vpmovsxbd ymm0, xmm1 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxbd_ymm_stale_dst ENDP + +op_vpmovsxbw_ymm_alias PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vpmovsxbw ymm1, xmm1 + vmovdqu YMMWORD PTR [r8], ymm1 + vzeroupper + ret +op_vpmovsxbw_ymm_alias ENDP + +op_vpmovzxdq_ymm_alias PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpmovzxdq ymm2, xmm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpmovzxdq_ymm_alias ENDP + +op_vpunpckldq_ymm_dst_src1 PROC FRAME + .endprolog + vmovdqu ymm3, YMMWORD PTR [rcx] + vmovdqu ymm4, YMMWORD PTR [rdx] + vpunpckldq ymm3, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm3 + vzeroupper + ret +op_vpunpckldq_ymm_dst_src1 ENDP + +op_vpunpckhqdq_ymm_dst_src2 PROC FRAME + .endprolog + vmovdqu ymm4, YMMWORD PTR [rcx] + vmovdqu ymm5, YMMWORD PTR [rdx] + vpunpckhqdq ymm5, ymm4, ymm5 + vmovdqu YMMWORD PTR [r8], ymm5 + vzeroupper + ret +op_vpunpckhqdq_ymm_dst_src2 ENDP + +op_vpunpckhdq_ymm_all PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpunpckhdq ymm2, ymm2, ymm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpunpckhdq_ymm_all ENDP + +op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpmovsxwd ymm0, xmm1 + vpunpcklqdq xmm0, xmm0, xmm2 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq ENDP + +op_chain_ymm_widen_unpack PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpmovsxwd ymm3, xmm1 + vpmovzxbd ymm4, xmm2 + vpunpckldq ymm0, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_chain_ymm_widen_unpack ENDP + +END diff --git a/tests/cpu/avx_int_ymm_widen_unpack.def b/tests/cpu/avx_int_ymm_widen_unpack.def new file mode 100644 index 0000000000..3935ba5a44 --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack.def @@ -0,0 +1,25 @@ +EXPORTS + op_vpmovsxbw_ymm + op_vpmovsxbd_ymm + op_vpmovsxbq_ymm + op_vpmovsxwd_ymm + op_vpmovsxwq_ymm + op_vpmovsxdq_ymm + op_vpmovzxbw_ymm + op_vpmovzxbd_ymm + op_vpmovzxbq_ymm + op_vpmovzxwd_ymm + op_vpmovzxwq_ymm + op_vpmovzxdq_ymm + op_vpunpckldq_ymm + op_vpunpckhdq_ymm + op_vpunpcklqdq_ymm + op_vpunpckhqdq_ymm + op_vpmovsxbd_ymm_stale_dst + op_vpmovsxbw_ymm_alias + op_vpmovzxdq_ymm_alias + op_vpunpckldq_ymm_dst_src1 + op_vpunpckhqdq_ymm_dst_src2 + op_vpunpckhdq_ymm_all + op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq + op_chain_ymm_widen_unpack diff --git a/tests/cpu/avx_int_ymm_widen_unpack_check.py b/tests/cpu/avx_int_ymm_widen_unpack_check.py new file mode 100644 index 0000000000..e1d10328ac --- /dev/null +++ b/tests/cpu/avx_int_ymm_widen_unpack_check.py @@ -0,0 +1,383 @@ +"""Differential, boundary, mutation, and rejection checks for 256-bit AVX2 extend and unpack ops.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import sys + +from iced_x86 import Code, Decoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from avx_int_ymm_minmax_check import encode_seq, first_bad_word, invoke, load # noqa: E402 +from avx_int_ymm_pack_check import host_has_avx2 # noqa: E402 +from cpu_avx_int_aot import lift_code # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXTEND_SPECS = { + # export: (signed, src_width_bytes, dst_width_bytes) + "op_vpmovsxbw_ymm": (True, 1, 2), + "op_vpmovsxbd_ymm": (True, 1, 4), + "op_vpmovsxbq_ymm": (True, 1, 8), + "op_vpmovsxwd_ymm": (True, 2, 4), + "op_vpmovsxwq_ymm": (True, 2, 8), + "op_vpmovsxdq_ymm": (True, 4, 8), + "op_vpmovzxbw_ymm": (False, 1, 2), + "op_vpmovzxbd_ymm": (False, 1, 4), + "op_vpmovzxbq_ymm": (False, 1, 8), + "op_vpmovzxwd_ymm": (False, 2, 4), + "op_vpmovzxwq_ymm": (False, 2, 8), + "op_vpmovzxdq_ymm": (False, 4, 8), +} +UNPACK_EXPORTS = ( + "op_vpunpckldq_ymm", + "op_vpunpckhdq_ymm", + "op_vpunpcklqdq_ymm", + "op_vpunpckhqdq_ymm", +) +BASE_EXPORTS = tuple(EXTEND_SPECS) + UNPACK_EXPORTS +SPECIAL_EXPORTS = ( + "op_vpmovsxbd_ymm_stale_dst", + "op_vpmovsxbw_ymm_alias", + "op_vpmovzxdq_ymm_alias", + "op_vpunpckldq_ymm_dst_src1", + "op_vpunpckhqdq_ymm_dst_src2", + "op_vpunpckhdq_ymm_all", + "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", + "op_chain_ymm_widen_unpack", +) +EXPORTS = BASE_EXPORTS + SPECIAL_EXPORTS + +_FMT_SIGNED = {1: "b", 2: "h", 4: "i", 8: "q"} +_FMT_UNSIGNED = {1: "B", 2: "H", 4: "I", 8: "Q"} + + +# --- Independent Python reference: cross-lane XMM->YMM extend & per-128-bit-lane unpack --- + +def _ref_extend(is_signed, src_w, dst_w, a): + count = 32 // dst_w + in_fmt = (_FMT_SIGNED if is_signed else _FMT_UNSIGNED)[src_w] + out_fmt = (_FMT_SIGNED if is_signed else _FMT_UNSIGNED)[dst_w] + vals = struct.unpack(f"<{count}{in_fmt}", a[:count * src_w]) + return struct.pack(f"<{count}{out_fmt}", *vals) + + +def _unpack_half(kind, a16, b16): + if kind in ("ldq", "hdq"): + xs = struct.unpack("<4I", a16) + ys = struct.unpack("<4I", b16) + off = 0 if kind == "ldq" else 2 + return struct.pack("<4I", xs[off], ys[off], xs[off + 1], ys[off + 1]) + if kind in ("lqdq", "hqdq"): + xs = struct.unpack("<2Q", a16) + ys = struct.unpack("<2Q", b16) + idx = 0 if kind == "lqdq" else 1 + return struct.pack("<2Q", xs[idx], ys[idx]) + raise ValueError(kind) + + +def _ref_unpack(kind, a, b): + return _unpack_half(kind, a[:16], b[:16]) + _unpack_half(kind, a[16:32], b[16:32]) + + +def reference(name, a, b): + if name in EXTEND_SPECS: + return _ref_extend(*EXTEND_SPECS[name], a) + if name == "op_vpmovsxbd_ymm_stale_dst": + return _ref_extend(True, 1, 4, a) + if name == "op_vpmovsxbw_ymm_alias": + return _ref_extend(True, 1, 2, a) + if name == "op_vpmovzxdq_ymm_alias": + return _ref_extend(False, 4, 8, a) + if name in ("op_vpunpckldq_ymm", "op_vpunpckldq_ymm_dst_src1"): + return _ref_unpack("ldq", a, b) + if name == "op_vpunpckhdq_ymm": + return _ref_unpack("hdq", a, b) + if name == "op_vpunpckhdq_ymm_all": + return _ref_unpack("hdq", a, a) + if name == "op_vpunpcklqdq_ymm": + return _ref_unpack("lqdq", a, b) + if name in ("op_vpunpckhqdq_ymm", "op_vpunpckhqdq_ymm_dst_src2"): + return _ref_unpack("hqdq", a, b) + if name == "op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq": + t = _ref_extend(True, 2, 4, a) + return _unpack_half("lqdq", t[:16], b[:16]) + b"\x00" * 16 + if name == "op_chain_ymm_widen_unpack": + t3 = _ref_extend(True, 2, 4, a) + t4 = _ref_extend(False, 1, 4, b) + return _ref_unpack("ldq", t3, t4) + raise KeyError(name) + + +def all_pairs(): + """Construct sign-boundary vectors with non-zero ignored XMM/YMM upper bytes plus random.""" + pairs = [] + b_edges = (0x00, 0x01, 0x7F, 0x80, 0x81, 0xFE, 0xFF) + w_edges = (0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF) + d_edges = (0x00000000, 0x00000001, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFE, 0xFFFFFFFF) + + for shift in range(len(b_edges)): + a = bytes(b_edges[(i + shift) % len(b_edges)] for i in range(32)) + b = bytes(b_edges[(3 * i + shift + 1) % len(b_edges)] for i in range(32)) + pairs.append((a, b)) + for shift in range(len(w_edges)): + a = struct.pack("<16H", *(w_edges[(i + shift) % len(w_edges)] for i in range(16))) + b = struct.pack("<16H", *(w_edges[(3 * i + shift + 2) % len(w_edges)] for i in range(16))) + pairs.append((a, b)) + for shift in range(len(d_edges)): + a = struct.pack("<8I", *(d_edges[(i + shift) % len(d_edges)] for i in range(8))) + b = struct.pack("<8I", *(d_edges[(3 * i + shift + 2) % len(d_edges)] for i in range(8))) + pairs.append((a, b)) + + # Distinct non-zero high bytes in xmm (bytes 4..15) and upper ymm lane (bytes 16..31). + pairs.append((bytes(range(0x10, 0x30)), bytes(range(0xA0, 0xC0)))) + pairs.append((bytes(0x80 + i for i in range(32)), bytes(0x7F - i for i in range(32)))) + pairs.append((bytes(32), bytes(32))) + pairs.append((b"\xff" * 32, b"\xff" * 32)) + pairs.append((b"\x80" * 16 + b"\x55" * 16, b"\x7f" * 16 + b"\xaa" * 16)) + + rng = random.Random(0x57DE9) + pairs += [(rng.randbytes(32), rng.randbytes(32)) for _ in range(160)] + return pairs + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + ymm_loads = (load(R.YMM1, R.RCX), load(R.YMM2, R.RDX)) + xmm_loads = ( + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)), + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)), + ) + + extend_codes = { + "VPMOVSXBW": Code.VEX_VPMOVSXBW_YMM_XMMM128, + "VPMOVSXBD": Code.VEX_VPMOVSXBD_YMM_XMMM64, + "VPMOVSXBQ": Code.VEX_VPMOVSXBQ_YMM_XMMM32, + "VPMOVSXWD": Code.VEX_VPMOVSXWD_YMM_XMMM128, + "VPMOVSXWQ": Code.VEX_VPMOVSXWQ_YMM_XMMM64, + "VPMOVSXDQ": Code.VEX_VPMOVSXDQ_YMM_XMMM128, + "VPMOVZXBW": Code.VEX_VPMOVZXBW_YMM_XMMM128, + "VPMOVZXBD": Code.VEX_VPMOVZXBD_YMM_XMMM64, + "VPMOVZXBQ": Code.VEX_VPMOVZXBQ_YMM_XMMM32, + "VPMOVZXWD": Code.VEX_VPMOVZXWD_YMM_XMMM128, + "VPMOVZXWQ": Code.VEX_VPMOVZXWQ_YMM_XMMM64, + "VPMOVZXDQ": Code.VEX_VPMOVZXDQ_YMM_XMMM128, + } + accepted = 0 + for name, code in extend_codes.items(): + source, _ = lift_code( + name, 0x1000, encode_seq(xmm_loads[0], Instruction.create_reg_reg(code, R.YMM0, R.XMM1), ret)) + assert f"ymm0 = op_{name.lower()}_ymm(ymm1);" in source, name + # Aliased dst == src with YMM source loaded must also lift cleanly. + alias_src, _ = lift_code( + f"{name}_alias", 0x1000, encode_seq(ymm_loads[0], Instruction.create_reg_reg(code, R.YMM1, R.XMM1), ret)) + assert f"ymm1 = op_{name.lower()}_ymm(ymm1);" in alias_src, name + accepted += 1 + + for name in ("VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ"): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + source, _ = lift_code( + name, 0x1000, encode_seq(*ymm_loads, Instruction.create_reg_reg_reg(code, R.YMM0, R.YMM1, R.YMM2), ret)) + assert f"wide128(op_{name.lower()}, ymm1, ymm2)" in source, name + accepted += 1 + + # 128-bit forms keep their 128-bit single-helper path. + src_ext128, _ = lift_code( + "xmm_vpmovsxbw", 0x1000, + encode_seq(xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_XMM_XMMM64, R.XMM0, R.XMM1), ret)) + assert "ymm0 = op_vpmovsxbw(ymm1);" in src_ext128 and "_ymm" not in src_ext128 + src_unpck128, _ = lift_code( + "xmm_vpunpckldq", 0x1000, + encode_seq(*xmm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret)) + assert "ymm0 = op_vpunpckldq(ymm1, ymm2);" in src_unpck128 and "wide128" not in src_unpck128 + + mem_err = "unsupported memory operand for register-domain AVX integer instruction" + mem = MemoryOperand(R.RDX) + cases = [] + for name, code in extend_codes.items(): + cases.append((f"{name.lower()}_mem", (Instruction.create_reg_mem(code, R.YMM0, mem), ret), mem_err)) + for name in ("VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ"): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + cases.append((f"{name.lower()}_mem", (ymm_loads[0], Instruction.create_reg_reg_mem(code, R.YMM0, R.YMM1, mem), ret), mem_err)) + + cases += [ + # EVEX variants + ("vpmovsxbw_evex", (xmm_loads[0], Instruction.create_reg_reg(Code.EVEX_VPMOVSXBW_YMM_K1Z_XMMM128, R.YMM0, R.XMM1), ret), + "unsupported EVEX instruction"), + ("vpmovzxdq_evex", (xmm_loads[0], Instruction.create_reg_reg(Code.EVEX_VPMOVZXDQ_YMM_K1Z_XMMM128, R.YMM0, R.XMM1), ret), + "unsupported EVEX instruction"), + ("vpunpckldq_evex", (*ymm_loads, Instruction.create_reg_reg_reg(Code.EVEX_VPUNPCKLDQ_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + ("vpunpckhqdq_evex", (*ymm_loads, Instruction.create_reg_reg_reg(Code.EVEX_VPUNPCKHQDQ_YMM_K1Z_YMM_YMMM256B64, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + # Nonvolatile YMM6..15 / XMM6..15 + ("vpmovsxbd_nonvol_dst", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVSXBD_YMM_XMMM64, R.YMM6, R.XMM1), ret), + "nonvolatile vector register"), + ("vpmovzxwq_nonvol_src", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVZXWQ_YMM_XMMM64, R.YMM0, R.XMM7), ret), + "nonvolatile vector register"), + ("vpunpckldq_nonvol_dst", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLDQ_YMM_YMM_YMMM256, R.YMM8, R.YMM1, R.YMM2), ret), + "nonvolatile vector register"), + ("vpunpcklqdq_nonvol_src2", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLQDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM15), ret), + "nonvolatile vector register"), + # Unlowered YMM unpack forms whose 128-bit encodings are carved out to cpu_vex_aot.py + ("vpunpcklbw_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLBW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpckhbw_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHBW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpcklwd_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKLWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + ("vpunpckhwd_ymm", (*ymm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHWD_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + # Undefined sources + ("vpmovsxbw_undef_src", (Instruction.create_reg_reg(Code.VEX_VPMOVSXBW_YMM_XMMM128, R.YMM0, R.XMM3), ret), + "undefined vector register ymm3"), + ("vpunpckhdq_undef_src2", (ymm_loads[0], Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret), + "undefined vector register ymm3"), + # Missing terminal ret + ("vpmovzxdq_missing_ret", (xmm_loads[0], Instruction.create_reg_reg(Code.VEX_VPMOVZXDQ_YMM_XMMM128, R.YMM0, R.XMM1)), + "missing terminal ret"), + ] + for label, seq, reason in cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted a rejected control") + return accepted, len(cases) + + +def check_differential(native, lifted, altered, altered_lifted): + pairs = all_pairs() + total = 0 + for name in EXPORTS: + for index, (a, b) in enumerate(pairs): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b) + if got != want: + raise AssertionError( + f"{label} {name} case {index} word {first_bad_word(got, want)}: " + f"got {got.hex()} expected {want.hex()}") + total += 1 + + # Unaligned input and output buffers; guard bytes must remain intact. + a, b = pairs[len(pairs) // 2] + for name in EXPORTS: + for a_offset, out_offset in ((1, 0), (0, 3), (7, 5)): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b, a_offset, out_offset) + if got != want: + raise AssertionError(f"{label} {name} offsets {a_offset}/{out_offset}") + total += 1 + + # Altered build checks: swapped ops match altered native and diverge from original. + for name in BASE_EXPORTS: + changed = 0 + for a, b in pairs: + alt_nat = invoke(altered[name], a, b) + alt_lif = invoke(altered_lifted[name], a, b) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted differs from native") + changed += alt_nat != invoke(native[name], a, b) + if not changed: + raise AssertionError(f"altered build did not diverge on {name}") + + # Mutant Python models: must fail against lifted in the expected 64-bit words. + zero16 = b"\x00" * 16 + mutants = [ + # Upper 128-bit half dropped on extend and unpack + ("op_vpmovsxbw_ymm", lambda x, _y: reference("op_vpmovsxbw_ymm", x, _y)[:16] + zero16, {2, 3}), + ("op_vpunpckldq_ymm", lambda x, y: reference("op_vpunpckldq_ymm", x, y)[:16] + zero16, {2, 3}), + # Lower 128-bit extend duplicated into upper 128-bit lane instead of cross-lane slicing + ("op_vpmovsxbw_ymm", lambda x, _y: reference("op_vpmovsxbw_ymm", x, _y)[:16] * 2, {2, 3}), + ("op_vpmovzxbd_ymm", lambda x, _y: reference("op_vpmovzxbd_ymm", x, _y)[:16] * 2, {2, 3}), + ("op_vpmovsxdq_ymm", lambda x, _y: reference("op_vpmovsxdq_ymm", x, _y)[:16] * 2, {2, 3}), + # Stale upper YMM bits (bytes 16..31) erroneously read for upper half + ("op_vpmovsxbw_ymm", lambda x, _y: _ref_extend(True, 1, 2, x)[:16] + _ref_extend(True, 1, 2, x[16:])[:16], {2, 3}), + # Wrong sign/zero extension + ("op_vpmovsxbd_ymm", lambda x, y: reference("op_vpmovzxbd_ymm", x, y), {0, 1, 2, 3}), + ("op_vpmovzxwq_ymm", lambda x, y: reference("op_vpmovsxwq_ymm", x, y), {0, 1, 2, 3}), + # Ignored upper XMM bytes (bytes 8..15) erroneously read for *BD + ("op_vpmovsxbd_ymm", lambda x, _y: _ref_extend(True, 1, 4, x[8:]), {0, 1, 2, 3}), + # Cross-lane or swapped unpacks + ("op_vpunpckldq_ymm", lambda x, y: reference("op_vpunpckhdq_ymm", x, y), {0, 1, 2, 3}), + ("op_vpunpcklqdq_ymm", lambda x, y: reference("op_vpunpckhqdq_ymm", x, y), {0, 1, 2, 3}), + ("op_vpunpckldq_ymm", + lambda x, y: _unpack_half("ldq", x[:16], y[:16]) + _unpack_half("ldq", x[:16], y[:16]), {2, 3}), + # Missing VEX.128 upper-half zeroing after YMM extend + ("op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", + lambda x, y: reference("op_vpmovsxwd_ymm_then_xmm_vpunpcklqdq", x, y)[:16] + _ref_extend(True, 2, 4, x)[16:], + {2, 3}), + ] + for name, wrong, allowed_words in mutants: + bad_words = set() + for x, y in pairs: + w = first_bad_word(invoke(lifted[name], x, y), wrong(x, y)) + if w is not None: + bad_words.add(w) + if not bad_words or not bad_words <= allowed_words: + raise AssertionError( + f"mutant on {name}: bad words {sorted(bad_words)}, expected subset of {sorted(allowed_words)}") + + return total, len(mutants), len(BASE_EXPORTS) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + + accepted, rejected = check_translator() + print(f"{accepted} 256-bit extend/unpack forms accepted; {rejected} rejection controls passed") + + lifted_lib, lifted = bind(lifted_path, "lifted_") + if not host_has_avx2(lifted_lib): + print("Host lacks CPUID.01H:ECX[28] + XGETBV + CPUID.07H:EBX[5] AVX2; skipping native differential check") + sys.exit(77) + + _, native = bind(original_path, "") + _, altered = bind(altered_path, "") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + total, caught, altered_count = check_differential(native, lifted, altered, altered_lifted) + print(f"{total} native/lifted/reference cases across {len(EXPORTS)} exports matched bit for bit; " + f"{caught} mutant controls + {altered_count} altered-build controls caught") + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/bmi1_logic_aot.asm b/tests/cpu/bmi1_logic_aot.asm new file mode 100644 index 0000000000..fd13c6902a --- /dev/null +++ b/tests/cpu/bmi1_logic_aot.asm @@ -0,0 +1,296 @@ +; coverage: record cpu_aot_bmi1_logic +; Source-built MASM fixture for BMI1 ANDN, BEXTR, and TZCNT from +; docs/coverage/x64_zen2.tsv group BMI/ADX in 32-bit and 64-bit register and +; flat [rcx|rdx|r8] memory forms, plus SDM flag-packing, 32-bit zero-extension, +; destination aliasing, [r8] source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 2 + or r9d, r11d + movzx r10d, byte ptr [r8] + shl r10d, 3 + or r9d, r10d + mov dword ptr [r8], r9d +ENDM + +PACK_CF_ZF_OF MACRO + setb r9b + sete r10b + seto r11b + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 3 + or r9d, r11d + mov dword ptr [r8], r9d +ENDM + +PACK_CF_ZF MACRO + setb r9b + sete r10b + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + mov dword ptr [r8], r9d +ENDM + +; --- Register forms (32-bit & 64-bit; mov rax,-1 before 32-bit tests [63:32] zero-ext) --- + +op_andn32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + andn eax, edx, ecx +ELSE + andn eax, ecx, edx +ENDIF + ret +op_andn32 ENDP + +op_andn64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + andn rax, rdx, rcx +ELSE + andn rax, rcx, rdx +ENDIF + ret +op_andn64 ENDP + +op_bextr32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, edx, ecx +ELSE + bextr eax, ecx, edx +ENDIF + ret +op_bextr32 ENDP + +op_bextr64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, rdx, rcx +ELSE + bextr rax, rcx, rdx +ENDIF + ret +op_bextr64 ENDP + +op_tzcnt32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, ecx, ecx +ELSE + tzcnt eax, ecx +ENDIF + ret +op_tzcnt32 ENDP + +op_tzcnt64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, rcx, rcx +ELSE + tzcnt rax, rcx +ENDIF + ret +op_tzcnt64 ENDP + +; --- Flat [rcx|rdx] m32 / m64 source forms --- + +op_andn32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, dword ptr [rcx], edx +ELSE + andn eax, edx, dword ptr [rcx] +ENDIF + ret +op_andn32_mem ENDP + +op_andn64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, qword ptr [rcx], rdx +ELSE + andn rax, rdx, qword ptr [rcx] +ENDIF + ret +op_andn64_mem ENDP + +op_bextr32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + andn eax, edx, dword ptr [rcx] +ELSE + bextr eax, dword ptr [rcx], edx +ENDIF + ret +op_bextr32_mem ENDP + +op_bextr64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + andn rax, rdx, qword ptr [rcx] +ELSE + bextr rax, qword ptr [rcx], rdx +ENDIF + ret +op_bextr64_mem ENDP + +op_tzcnt32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1_LOGIC + bextr eax, dword ptr [rdx], ecx +ELSE + tzcnt eax, dword ptr [rdx] +ENDIF + ret +op_tzcnt32_mem ENDP + +op_tzcnt64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1_LOGIC + bextr rax, qword ptr [rdx], rcx +ELSE + tzcnt rax, qword ptr [rdx] +ENDIF + ret +op_tzcnt64_mem ENDP + +; --- Flag-packing exports stored at [r8] --- + +op_andn32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + andn eax, ecx, edx + PACK_CF_ZF_SF_OF + ret +op_andn32_flags ENDP + +op_andn64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + andn rax, rcx, rdx + PACK_CF_ZF_SF_OF + ret +op_andn64_flags ENDP + +op_bextr32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + bextr eax, ecx, edx + PACK_CF_ZF_OF + ret +op_bextr32_flags ENDP + +op_bextr64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bextr rax, rcx, rdx + PACK_CF_ZF_OF + ret +op_bextr64_flags ENDP + +op_tzcnt32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + mov rax, -1 + tzcnt eax, ecx + PACK_CF_ZF + ret +op_tzcnt32_flags ENDP + +op_tzcnt64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + tzcnt rax, rcx + PACK_CF_ZF + ret +op_tzcnt64_flags ENDP + +op_bextr64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bextr rax, qword ptr [rcx], rdx + PACK_CF_ZF_OF + ret +op_bextr64_mem_flags ENDP + +op_tzcnt64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + tzcnt rax, qword ptr [rcx] + PACK_CF_ZF + ret +op_tzcnt64_mem_flags ENDP + +; --- [r8] source-then-store, dst aliasing src, and discarded faulting m64 read --- + +op_r8_source_then_store PROC FRAME + .endprolog + mov r11, qword ptr [rdx] + andn r9, r11, qword ptr [r8] + bextr r10, qword ptr [rcx], r11 + tzcnt r11, qword ptr [rdx] + or r9, r10 + xor r9, r11 + mov qword ptr [r8], r9 + mov rax, r9 + ret +op_r8_source_then_store ENDP + +op_dst_alias_src PROC FRAME + .endprolog + mov r9, rcx + mov r10, rdx + andn r9, r9, r10 + bextr r10, r10, r9 + tzcnt r10, r10 + or r9, r10 + mov rax, r9 + ret +op_dst_alias_src ENDP + +op_bmi1_logic_discarded_read PROC FRAME + .endprolog + tzcnt r9, qword ptr [rdx] + mov rax, rcx + ret +op_bmi1_logic_discarded_read ENDP + +END diff --git a/tests/cpu/bmi1_logic_aot.def b/tests/cpu/bmi1_logic_aot.def new file mode 100644 index 0000000000..8bde8d32f5 --- /dev/null +++ b/tests/cpu/bmi1_logic_aot.def @@ -0,0 +1,24 @@ +EXPORTS + op_andn32 + op_andn64 + op_bextr32 + op_bextr64 + op_tzcnt32 + op_tzcnt64 + op_andn32_mem + op_andn64_mem + op_bextr32_mem + op_bextr64_mem + op_tzcnt32_mem + op_tzcnt64_mem + op_andn32_flags + op_andn64_flags + op_bextr32_flags + op_bextr64_flags + op_tzcnt32_flags + op_tzcnt64_flags + op_bextr64_mem_flags + op_tzcnt64_mem_flags + op_r8_source_then_store + op_dst_alias_src + op_bmi1_logic_discarded_read diff --git a/tests/cpu/bmi1_logic_aot_check.py b/tests/cpu/bmi1_logic_aot_check.py new file mode 100644 index 0000000000..3ca4e07505 --- /dev/null +++ b/tests/cpu/bmi1_logic_aot_check.py @@ -0,0 +1,803 @@ +"""Differential, /O2, flag-modeling, mutant, and rejection checks for cpu_bmi1_logic_aot (ANDN, BEXTR, TZCNT).""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi1_logic_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_andn32", "op_andn64", + "op_bextr32", "op_bextr64", + "op_tzcnt32", "op_tzcnt64", + "op_andn32_mem", "op_andn64_mem", + "op_bextr32_mem", "op_bextr64_mem", + "op_tzcnt32_mem", "op_tzcnt64_mem", + "op_andn32_flags", "op_andn64_flags", + "op_bextr32_flags", "op_bextr64_flags", + "op_tzcnt32_flags", "op_tzcnt64_flags", + "op_bextr64_mem_flags", + "op_tzcnt64_mem_flags", + "op_r8_source_then_store", + "op_dst_alias_src", + "op_bmi1_logic_discarded_read", +) + +ALTERED_REG_EXPORTS = ( + "op_andn32", "op_andn64", + "op_bextr32", "op_bextr64", + "op_tzcnt32", "op_tzcnt64", +) +ALTERED_MEM_EXPORTS = ( + "op_andn32_mem", "op_andn64_mem", + "op_bextr32_mem", "op_bextr64_mem", + "op_tzcnt32_mem", "op_tzcnt64_mem", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference model --- + +def ref_bmi1_logic(op, a, b, bits, *, quirk=None): + """Return (dst, packed_flags) matching SDM flags per instruction.""" + mask = MASK32 if bits == 32 else MASK64 + sign = 1 << (bits - 1) + s1 = a & mask + s2 = b & mask + + if op == "andn": + if quirk == "andn_swap": + d = ((~s2) & s1) & mask + elif quirk == "andn_plain_and": + d = (s1 & s2) & mask + else: + d = ((~s1) & s2) & mask + cf = True if quirk == "set_cf" else False + of = True if quirk == "set_of" else False + zf = (d == 0) + sf = False if quirk == "drop_sf" else ((d & sign) != 0) + elif op == "bextr": + if quirk == "bextr_swap_start_len": + start = (s2 >> 8) & 0xFF + length = s2 & 0xFF + else: + start = s2 & 0xFF + length = (s2 >> 8) & 0xFF + if quirk == "bextr_mask_start_bits": + start &= (bits - 1) + if quirk == "bextr_len_zero_all" and length == 0: + length = bits + if length == 0 or start >= bits: + d = 0 + else: + bit_mask = mask if length >= bits else ((1 << length) - 1) + d = ((s1 >> start) & bit_mask) & mask + cf = True if quirk == "set_cf" else False + of = True if quirk == "set_of" else False + zf = False if quirk == "bextr_zf_false" else (d == 0) + sf = False + elif op == "tzcnt": + if s1 == 0: + if quirk == "tzcnt_zero_0": + d = 0 + elif quirk == "tzcnt_zero_width_m1": + d = bits - 1 + else: + d = bits + cf = False if quirk == "tzcnt_invert_cf" else True + else: + d = (s1 & -s1).bit_length() - 1 + cf = True if quirk == "tzcnt_invert_cf" else False + zf = (s1 == 0) if quirk == "tzcnt_zf_from_src" else (d == 0) + sf = False + of = False + else: + raise ValueError(op) + + if quirk == "no_zext32" and bits == 32: + d |= 0xFFFFFFFF00000000 + packed = (int(cf) << 0) | (int(zf) << 1) | (int(sf) << 2) | (int(of) << 3) + return d, packed + + +def test_pairs(): + singles = [ + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000002, + 0x0000000000000010, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x0000000080000001, + 0x00000000FFFFFFFE, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF80000000, + 0x0000000100000000, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0x8000000000000001, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, + ] + singles.extend(1 << b for b in range(64)) + bextr_ctrls = [ + 0x0000000000000000, # start=0, len=0 + 0x0000000000000005, # start=5, len=0 + 0x0000000000000100, # start=0, len=1 + 0x000000000000011F, # start=31, len=1 + 0x0000000000000120, # start=32, len=1 (out of 32b range, valid in 64b) + 0x000000000000013F, # start=63, len=1 + 0x0000000000000140, # start=64, len=1 (out of 64b range) + 0x0000000000001418, # start=24, len=20 (crosses 32b boundary) + 0x0000000000002000, # start=0, len=32 + 0x0000000000002010, # start=16, len=32 + 0x0000000000004000, # start=0, len=64 + 0x0000000000004020, # start=32, len=64 (crosses 64b boundary) + 0x000000000000FF00, # start=0, len=255 + 0x000000000000FF1F, # start=31, len=255 + 0x000000000000FF3F, # start=63, len=255 + 0x000000000000FFFF, # start=255, len=255 + 0xABCD123400000804, # dirty upper bits [31:16]/[63:16] + 0xCAFE000000002018, # dirty upper bits + ] + pairs = [ + (0x0000000000000000, 0x0000000080000000), + (0x0000000000000000, 0x8000000000000000), + (0x0000000080000000, 0x00000000FFFFFFFF), + (0x8000000000000000, 0xFFFFFFFFFFFFFFFF), + ] + for idx, a in enumerate(singles): + b = bextr_ctrls[idx % len(bextr_ctrls)] if idx < len(bextr_ctrls) * 2 else singles[(idx * 7 + 3) % len(singles)] + pairs.append((a, b)) + for ctrl in bextr_ctrls: + pairs.append((0xF0E1D2C3B4A59687, ctrl)) + pairs.append((0x8000000080000001, ctrl)) + rng = random.Random(0xB11101C) + for _ in range(32): + pairs.append((rng.getrandbits(64), rng.getrandbits(64))) + return pairs + + +# --- Guarded memory & DLL helpers --- + +def alloc_guarded(payload): + raw = ctypes.create_string_buffer(GUARD_PRE + payload + GUARD_POST, len(GUARD_PRE) + len(payload) + len(GUARD_POST)) + base = ctypes.addressof(raw) + return raw, base + len(GUARD_PRE), len(GUARD_PRE), len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[:off] != GUARD_PRE or raw[off + length:] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_bmi1(lifted_lib): + if hasattr(lifted_lib, "host_has_bmi1"): + lifted_lib.host_has_bmi1.argtypes = [] + lifted_lib.host_has_bmi1.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_bmi1()) + return False + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + xor_r9 = Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D) + andn_eax_ecx_edx = Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX) + bextr_rax_rcx_rdx = Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RCX, R.RDX) + tzcnt_rax_rcx = Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.RAX, R.RCX) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("andn32_r11_rdx_r8mem", (Instruction.create_reg_reg_mem(Code.VEX_ANDN_R32_R32_RM32, R.R11D, R.EDX, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "r11 = op_andn32((rdx & 0xFFFFFFFFull), ld_1000_2, flags);"), + ("bextr64_r10_rdxmem_rcx", (Instruction.create_reg_mem_reg(Code.VEX_BEXTR_R64_RM64_R64, R.R10, MemoryOperand(R.RDX), R.RCX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R10), ret), + "r10 = op_bextr64(ld_1000_1, rcx, flags);"), + ("tzcnt32_r9_r8d", (Instruction.create_reg_reg(Code.TZCNT_R32_RM32, R.R9D, R.R8D), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), ret), + "r9 = op_tzcnt32((r8 & 0xFFFFFFFFull), flags);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_andn = Instruction.create_reg_reg_mem(Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RDX)) + seg_andn.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # Other BMI1 instructions (BLSI / BLSMSK / BLSR) & 16-bit TZCNT & BSF/LZCNT + ("bmi1_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_blsmsk", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R32_RM32, R.EAX, R.ECX), ret), + "unsupported VEX instruction"), + ("bmi1_blsr", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("tzcnt_16bit", (Instruction.create_reg_reg(Code.TZCNT_R16_RM16, R.AX, R.CX), mov_rax_rcx, ret), + "unsupported instruction"), + ("bsf_32bit", (Instruction.create_reg_reg(Code.BSF_R32_RM32, R.EAX, R.ECX), ret), + "unsupported instruction"), + ("lzcnt_64bit", (Instruction.create_reg_reg(Code.LZCNT_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + # BMI2 rejections + ("bmi2_rorx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.RCX, 5), ret), + "unsupported VEX instruction"), + ("bmi2_sarx", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_shlx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_bzhi", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr32", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + ("xop_bextr64", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R64_RM64_IMM32, R.RAX, R.RCX, 0x0804), ret), + "unsupported XOP instruction"), + # Undefined flag reads per instruction (including after prior XOR defining all flags!) + ("undef_pf_after_andn", (xor_r9, andn_eax_ecx_edx, Instruction.create_reg(Code.SETP_RM8, R.R9L), ret), + "undefined flag pf read"), + ("undef_sf_after_bextr", (xor_r9, bextr_rax_rcx_rdx, Instruction.create_reg(Code.SETS_RM8, R.R9L), ret), + "undefined flag sf read"), + ("undef_pf_after_bextr", (xor_r9, bextr_rax_rcx_rdx, Instruction.create_mem(Code.SETNP_RM8, MemoryOperand(R.R8)), ret), + "undefined flag pf read"), + ("undef_sf_after_tzcnt", (xor_r9, tzcnt_rax_rcx, Instruction.create_reg(Code.SETNS_RM8, R.R9L), ret), + "undefined flag sf read"), + ("undef_of_after_tzcnt", (xor_r9, tzcnt_rax_rcx, Instruction.create_mem(Code.SETO_RM8, MemoryOperand(R.R8)), ret), + "undefined flag of read"), + ("undef_pf_after_tzcnt", (xor_r9, tzcnt_rax_rcx, Instruction.create_reg(Code.SETP_RM8, R.R9L), ret), + "undefined flag pf read"), + ("undef_af_lahf_after_andn", (andn_eax_ecx_edx, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("undef_flags_pushfq", (tzcnt_rax_rcx, Instruction.create(Code.PUSHFQ), ret), + "unsupported instruction"), + ("undef_flags_before_op", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flag cf read"), + # Nonvolatile GPRs, arg GPR writes, high-byte GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RBX, R.RCX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RSI, R.RDX), ret), + "nonvolatile GPR"), + ("nonvol_r12_dst", (Instruction.create_reg_reg(Code.TZCNT_R32_RM32, R.R12D, R.ECX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("write_arg_rcx", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RCX, R.RDX, R.R8), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R32_RM32_R32, R.EDX, R.ECX, R.R8D), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.R8, R.RCX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_u32(Code.MOV_R8_IMM8, R.AH, 1), ret), + "unsupported high-byte GPR"), + # Undefined GPRs + ("undef_gpr_r9_src", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.R9, R.RCX), ret), + "undefined GPR r9"), + ("undef_gpr_r10_bextr_ctrl", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RCX, R.R10), ret), + "undefined GPR r10"), + ("undef_rax_ret", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.R9, R.RCX), ret), + "return with undefined RAX"), + # Displaced / indexed / non-flat memory & non-r8 stores + ("displaced_andn_rcx", (Instruction.create_reg_reg_mem( + Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RDX, MemoryOperand(R.RCX, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_bextr_rdx", (Instruction.create_reg_mem_reg( + Code.VEX_BEXTR_R32_RM32_R32, R.EAX, MemoryOperand(R.RDX, displ=4, displ_size=1), R.ECX), ret), + "displaced memory operand"), + ("displaced_store_r8", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("indexed_tzcnt", (Instruction.create_reg_mem( + Code.TZCNT_R64_RM64, R.RAX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("rip_rel_andn", (Instruction.create_reg_reg_mem( + Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem(Code.TZCNT_R64_RM64, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem_reg( + Code.VEX_BEXTR_R32_RM32_R32, R.EAX, MemoryOperand(R.RSP), R.ECX), ret), + "bad base register in memory operand"), + ("non_r8_store_rcx", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), "non-r8 store memory operand"), + ("non_r8_store_setb", (tzcnt_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_andn", (seg_andn, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (andn_eax_ecx_edx,), "missing terminal ret"), + ("trailing_after_ret", (tzcnt_rax_rcx, ret, mov_rax_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("repne_bsf", bytes.fromhex("f20fbcc1") + encode_seq(ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_andn64_flags") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from("<I", records, i)[0] == entry) + pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) + max_len = struct.unpack_from("<I", records, rec_idx + 4)[0] - entry + + by_label = {label: (encode_seq(*seq), reason) for label, seq, reason in unit_cases} + pe_labels = ( + "bmi1_blsi", + "bmi2_rorx", + "xop_bextr32", + "evex_vpaddd", + "undef_sf_after_bextr", + "undef_of_after_tzcnt", + "nonvol_rbx_dst", + "write_arg_rcx", + "displaced_andn_rcx", + "non_r8_store_rcx", + "branch_jmp", + "seg_prefix_andn", + ) + lifter_script = Path(__file__).resolve().parents[2] / "tools" / "cpu_bmi1_logic_aot.py" + with TemporaryDirectory() as folder: + tmp = Path(folder) + patched = tmp / "patched.dll" + out_cpp = tmp / "rejected.cpp" + for label in pe_labels: + patch, reason = by_label[label] + if len(patch) > max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("<I", damaged, pdata_end_off, entry + len(patch)) + patched.write_bytes(damaged) + try: + translate(patched, ["op_andn64_flags"]) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"pe_{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"pe_{label}: PE translate accepted rejected patch") + + proc = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(patched), "op_andn64_flags", str(out_cpp)], + capture_output=True, + text=True, + ) + if proc.returncode != 1 or "Traceback" in proc.stderr or "unsupported instruction prefix" not in proc.stderr: + raise AssertionError(f"CLI rejection unexpected: rc={proc.returncode}, stderr={proc.stderr!r}") + if out_cpp.exists() or list(tmp.glob("*.tmp")): + raise AssertionError("CLI failure left behind output or temp file") + + bad_dir = tmp / "dir_out" + bad_dir.mkdir() + proc_dir = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(original_path), "op_andn32", str(bad_dir)], + capture_output=True, + text=True, + ) + if proc_dir.returncode != 1 or "Traceback" in proc_dir.stderr or "directory" not in proc_dir.stderr: + raise AssertionError(f"CLI dir rejection unexpected: rc={proc_dir.returncode}, stderr={proc_dir.stderr!r}") + + print( + f"rejections passed: {len(alt_accept)} alt + {len(unit_cases)} IR + " + f"{len(raw_cases)} raw + {len(pe_labels)} PE-patched + CLI" + ) + + +# --- Positive, altered, mutant, and /O2 verification --- + +def verify_suite(fns, label, pairs): + total = 0 + + # 1) Register forms (32-bit zero-ext + 64-bit). + for op in ("andn", "bextr", "tzcnt"): + for bits in (32, 64): + fn = fns[f"op_{op}{bits}"] + for a, b in pairs: + want, _ = ref_bmi1_logic(op, a, b, bits) + got = fn(a, b, 0) + if got != want: + raise AssertionError(f"{label} op_{op}{bits}({a:#x}, {b:#x}): got {got:#x} != exp {want:#x}") + total += 1 + + # 2) Flat [rcx|rdx] memory forms. + mem_specs = ( + ("op_andn32_mem", "andn", 32, "rcx"), + ("op_andn64_mem", "andn", 64, "rcx"), + ("op_bextr32_mem", "bextr", 32, "rcx"), + ("op_bextr64_mem", "bextr", 64, "rcx"), + ("op_tzcnt32_mem", "tzcnt", 32, "rdx"), + ("op_tzcnt64_mem", "tzcnt", 64, "rdx"), + ) + for name, op, bits, mem_reg in mem_specs: + fn = fns[name] + fmt = "<I" if bits == 32 else "<Q" + mask = MASK32 if bits == 32 else MASK64 + for a, b in pairs: + if op == "andn": + # andn dst, rdx, [rcx] -> src1=rdx (b), src2=[rcx] (a) + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want, _ = ref_bmi1_logic(op, b, a, bits) + got = fn(ptr, b, 0) + elif op == "bextr": + # bextr dst, [rcx], rdx -> src1=[rcx] (a), src2=rdx (b) + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want, _ = ref_bmi1_logic(op, a, b, bits) + got = fn(ptr, b, 0) + else: + # tzcnt dst, [rdx] -> src=[rdx] (a) + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want, _ = ref_bmi1_logic(op, a, 0, bits) + got = fn(0, ptr, 0) if mem_reg == "rdx" else fn(ptr, 0, 0) + read_guarded(buf, off, ln, name) + if got != want: + raise AssertionError(f"{label} {name}({a:#x}, {b:#x}): got {got:#x} != exp {want:#x}") + total += 1 + + # 3) Flag-packing exports. + for op in ("andn", "bextr", "tzcnt"): + for bits in (32, 64): + name = f"op_{op}{bits}_flags" + fn = fns[name] + for a, b in pairs: + want_val, want_flags = ref_bmi1_logic(op, a, b, bits) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fn(a, b, po) + got_flags = struct.unpack("<I", read_guarded(bo, oo, lo, name))[0] + if got_val != want_val or got_flags != want_flags: + raise AssertionError( + f"{label} {name}({a:#x}, {b:#x}): val={got_val:#x}/{want_val:#x} flags={got_flags:#x}/{want_flags:#x}" + ) + total += 1 + + # Memory flag-packing exports: op_bextr64_mem_flags & op_tzcnt64_mem_flags. + for a, b in pairs: + want_val, want_flags = ref_bmi1_logic("bextr", a, b, 64) + ba, pa, oa, la = alloc_guarded(struct.pack("<Q", a)) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fns["op_bextr64_mem_flags"](pa, b, po) + read_guarded(ba, oa, la, "op_bextr64_mem_flags_a") + got_flags = struct.unpack("<I", read_guarded(bo, oo, lo, "op_bextr64_mem_flags_out"))[0] + if got_val != want_val or got_flags != want_flags: + raise AssertionError( + f"{label} op_bextr64_mem_flags({a:#x}, {b:#x}): val={got_val:#x}/{want_val:#x} flags={got_flags:#x}/{want_flags:#x}" + ) + total += 1 + + want_val_t, want_flags_t = ref_bmi1_logic("tzcnt", a, 0, 64) + bt, pt, ot, lt = alloc_guarded(struct.pack("<Q", a)) + bo2, po2, oo2, lo2 = alloc_guarded(b"\x5a" * 4) + got_val_t = fns["op_tzcnt64_mem_flags"](pt, 0, po2) + read_guarded(bt, ot, lt, "op_tzcnt64_mem_flags_a") + got_flags_t = struct.unpack("<I", read_guarded(bo2, oo2, lo2, "op_tzcnt64_mem_flags_out"))[0] + if got_val_t != want_val_t or got_flags_t != want_flags_t: + raise AssertionError( + f"{label} op_tzcnt64_mem_flags({a:#x}): val={got_val_t:#x}/{want_val_t:#x} flags={got_flags_t:#x}/{want_flags_t:#x}" + ) + total += 1 + + # 4) [r8] source-then-store and dst aliasing src. + for i in range(len(pairs) - 1): + a, b = pairs[i] + c, _ = pairs[i + 1] + ba, pa, oa, la = alloc_guarded(struct.pack("<Q", a)) + bb, pb, ob, lb = alloc_guarded(struct.pack("<Q", b)) + br, pr, or_, lr = alloc_guarded(struct.pack("<Q", c)) + got_rax = fns["op_r8_source_then_store"](pa, pb, pr) + read_guarded(ba, oa, la, "r8_src_a") + read_guarded(bb, ob, lb, "r8_src_b") + got_mem = struct.unpack("<Q", read_guarded(br, or_, lr, "r8_src_out"))[0] + v_andn = ref_bmi1_logic("andn", b, c, 64)[0] + v_bextr = ref_bmi1_logic("bextr", a, b, 64)[0] + v_tzcnt = ref_bmi1_logic("tzcnt", b, 0, 64)[0] + want = (v_andn | v_bextr) ^ v_tzcnt + if got_rax != want or got_mem != want: + raise AssertionError(f"{label} op_r8_source_then_store: rax={got_rax:#x} mem={got_mem:#x} exp={want:#x}") + total += 1 + + got_alias = fns["op_dst_alias_src"](a, b, 0) + r9 = ref_bmi1_logic("andn", a, b, 64)[0] + r10 = ref_bmi1_logic("bextr", b, r9, 64)[0] + r10 = ref_bmi1_logic("tzcnt", r10, 0, 64)[0] + want_alias = r9 | r10 + if got_alias != want_alias: + raise AssertionError(f"{label} op_dst_alias_src({a:#x}, {b:#x}): got={got_alias:#x} exp={want_alias:#x}") + total += 1 + + # 5) Discarded faulting m64 read must fault on NULL rdx even under /O2. + bd, pd, od, ld = alloc_guarded(struct.pack("<Q", 0x123456789ABCDEF0)) + assert fns["op_bmi1_logic_discarded_read"](0xCAFEBABE, pd, 0) == 0xCAFEBABE + read_guarded(bd, od, ld, "discarded_valid") + try: + fns["op_bmi1_logic_discarded_read"](0xCAFEBABE, 0, 0) + except OSError as exc: + if "access violation reading" not in str(exc).lower(): + raise AssertionError(f"{label} discarded_read(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{label} op_bmi1_logic_discarded_read(NULL) dropped faulting m64 read") + + return total + + +def _altered_reg_expected(name, a, b): + if name == "op_andn32": + return ref_bmi1_logic("andn", b, a, 32)[0] + if name == "op_andn64": + return ref_bmi1_logic("andn", b, a, 64)[0] + if name == "op_bextr32": + return ref_bmi1_logic("bextr", b, a, 32)[0] + if name == "op_bextr64": + return ref_bmi1_logic("bextr", b, a, 64)[0] + if name == "op_tzcnt32": + return ref_bmi1_logic("bextr", a, a, 32)[0] + if name == "op_tzcnt64": + return ref_bmi1_logic("bextr", a, a, 64)[0] + raise ValueError(name) + + +def _altered_mem_expected(name, a, b): + if name == "op_andn32_mem": + return ref_bmi1_logic("bextr", a, b, 32)[0] + if name == "op_andn64_mem": + return ref_bmi1_logic("bextr", a, b, 64)[0] + if name == "op_bextr32_mem": + return ref_bmi1_logic("andn", b, a, 32)[0] + if name == "op_bextr64_mem": + return ref_bmi1_logic("andn", b, a, 64)[0] + if name == "op_tzcnt32_mem": + return ref_bmi1_logic("bextr", a, b, 32)[0] + if name == "op_tzcnt64_mem": + return ref_bmi1_logic("bextr", a, b, 64)[0] + raise ValueError(name) + + +def check_altered_and_mutants(lifted_fns, alt_lifted_fns, pairs): + diverged = 0 + sample = pairs + for name in ALTERED_REG_EXPORTS: + diffs = 0 + for a, b in sample: + want_alt = _altered_reg_expected(name, a, b) + got_al = alt_lifted_fns[name](a, b, 0) + if got_al != want_alt: + raise AssertionError(f"altered_lifted {name}({a:#x}, {b:#x}): {got_al:#x} != {want_alt:#x}") + diffs += got_al != lifted_fns[name](a, b, 0) + if not diffs: + raise AssertionError(f"ALTER_BMI1_LOGIC failed to diverge on {name}") + diverged += 1 + + for name in ALTERED_MEM_EXPORTS: + bits = 32 if "32" in name else 64 + fmt = "<I" if bits == 32 else "<Q" + mask = MASK32 if bits == 32 else MASK64 + is_tz = name.startswith("op_tzcnt") + diffs = 0 + for a, b in sample: + buf, ptr, off, ln = alloc_guarded(struct.pack(fmt, a & mask)) + want_alt = _altered_mem_expected(name, a, b) + if is_tz: + got_al = alt_lifted_fns[name](b, ptr, 0) + got_ol = lifted_fns[name](b, ptr, 0) + else: + got_al = alt_lifted_fns[name](ptr, b, 0) + got_ol = lifted_fns[name](ptr, b, 0) + read_guarded(buf, off, ln, name) + if got_al != want_alt: + raise AssertionError(f"altered_lifted {name}({a:#x}, {b:#x}): {got_al:#x} != {want_alt:#x}") + diffs += got_al != got_ol + if not diffs: + raise AssertionError(f"ALTER_BMI1_LOGIC failed to diverge on {name}") + diverged += 1 + + # Mutant models targeting SDM edge cases across ANDN, BEXTR, TZCNT. + mutant_specs = ( + ("andn", 32, "andn_swap"), + ("andn", 64, "andn_plain_and"), + ("andn", 32, "drop_sf"), + ("andn", 64, "set_of"), + ("andn", 64, "set_cf"), + ("andn", 32, "no_zext32"), + ("bextr", 32, "bextr_swap_start_len"), + ("bextr", 32, "bextr_mask_start_bits"), + ("bextr", 64, "bextr_len_zero_all"), + ("bextr", 64, "bextr_zf_false"), + ("bextr", 64, "set_cf"), + ("bextr", 32, "no_zext32"), + ("tzcnt", 32, "tzcnt_zero_0"), + ("tzcnt", 64, "tzcnt_zero_width_m1"), + ("tzcnt", 64, "tzcnt_invert_cf"), + ("tzcnt", 32, "tzcnt_zf_from_src"), + ("tzcnt", 32, "no_zext32"), + ) + for op, bits, quirk in mutant_specs: + fn = lifted_fns[f"op_{op}{bits}_flags"] + caught = 0 + for a, b in sample: + bo, po, oo, lo = alloc_guarded(b"\x5a" * 4) + got_val = fn(a, b, po) + got_flags = struct.unpack("<I", read_guarded(bo, oo, lo, f"mut_{op}"))[0] + mut_val, mut_flags = ref_bmi1_logic(op, a, b, bits, quirk=quirk) + if got_val != mut_val or got_flags != mut_flags: + caught += 1 + if not caught: + raise AssertionError(f"mutant {quirk} on {op}{bits} survived") + + return diverged, len(mutant_specs) + + +def compile_o2_and_verify(original_path, cxx_path, pairs): + source_text, _ = translate(original_path, list(EXPORTS)) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "bmi1_logic_aot_o2.cpp" + dll_path = tmp / "bmi1_logic_aot_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'bmi1_logic_aot_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_suite(o2_fns, "lifted_o2", pairs) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + + # 1) Lift + rejections + portable lifted + mutants + /O2 run unconditionally BEFORE CPUID skip. + check_rejections(original_path) + + pairs = test_pairs() + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_suite(lifted_fns, "lifted", pairs) + diverged, mutants = check_altered_and_mutants(lifted_fns, alt_lifted_fns, pairs) + o2_cases = compile_o2_and_verify(original_path, cxx_path, pairs) + + if not host_has_bmi1(lifted_lib): + print( + f"portable lifted passed ({lifted_cases} lifted + {o2_cases} /O2 cases, " + f"{diverged} ALTER_BMI1_LOGIC + {mutants} mutants); " + "Host lacks CPUID.07H.00H:EBX[3] (BMI1), skipping native differential check" + ) + sys.exit(77) + + # 2) Native BMI1 hardware differential checks. + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + try: + native_cases = verify_suite(orig_fns, "native", pairs) + for name in ALTERED_REG_EXPORTS: + for a, b in pairs[:32]: + got_an = alt_fns[name](a, b, 0) + got_al = alt_lifted_fns[name](a, b, 0) + if got_an != got_al: + raise AssertionError(f"altered native vs lifted {name}({a:#x}, {b:#x}): {got_an:#x} != {got_al:#x}") + finally: + orig_fns.clear() + alt_fns.clear() + unload_lib(orig_lib) + unload_lib(alt_lib) + finally: + lifted_fns.clear() + alt_lifted_fns.clear() + unload_lib(lifted_lib) + unload_lib(alt_lifted_lib) + + record_covered_forms(original_path) + print( + f"bmi1_logic_aot passed: {native_cases} native + {lifted_cases} lifted + {o2_cases} /O2 cases " + f"across {len(EXPORTS)} exports; ALTER_BMI1_LOGIC diverged on {diverged} exports + {mutants} mutants caught" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/bmi2_bit_aot.asm b/tests/cpu/bmi2_bit_aot.asm new file mode 100644 index 0000000000..6c6ab04a4a --- /dev/null +++ b/tests/cpu/bmi2_bit_aot.asm @@ -0,0 +1,303 @@ +; coverage: record cpu_aot_bmi2_bit +; Source-built MASM fixture for the four BMI2 bit-manipulation forms from +; docs/coverage/x64_zen2.tsv group BMI/ADX: BZHI, MULX, PDEP, and PEXT in 32-bit +; and 64-bit register and flat zero-displacement [rcx|rdx|r8] memory forms, plus +; BZHI CF/ZF/SF/OF flag checks, CMP -> PDEP/PEXT/MULX -> SETcc flag preservation +; (CF, ZF, SF, OF, PF), MULX op0==op1 aliasing, 32-bit zero-extension, [r8] +; source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + mov eax, 2 + pdep r10d, r10d, eax + or r9d, r10d + movzx r11d, r11b + mov eax, 4 + pdep r11d, r11d, eax + or r9d, r11d + movzx r10d, byte ptr [r8] + mov eax, 8 + pdep r10d, r10d, eax + or r9d, r10d + mov eax, r9d + mov dword ptr [r8], eax +ENDM + +; --- Register forms (mov rax,-1 / r9,-1 / r10,-1 before 32-bit ops checks [63:32] zero-ext) --- + +op_bzhi32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pext eax, ecx, edx +ELSE + bzhi eax, ecx, edx +ENDIF + ret +op_bzhi32 ENDP + +op_bzhi64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pext rax, rcx, rdx +ELSE + bzhi rax, rcx, rdx +ENDIF + ret +op_bzhi64 ENDP + +op_mulx32 PROC FRAME + .endprolog + mov r9, -1 + mov r10, -1 +IFDEF ALTER_BMI2_BIT + mulx r10d, r9d, ecx +ELSE + mulx r9d, r10d, ecx +ENDIF + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx32 ENDP + +op_mulx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + mulx r10, r9, rcx +ELSE + mulx r9, r10, rcx +ENDIF + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx64 ENDP + +op_mulx32_alias PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + mulx r9d, eax, ecx +ELSE + mulx eax, eax, ecx +ENDIF + ret +op_mulx32_alias ENDP + +op_mulx64_alias PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + mulx r9, rax, rcx +ELSE + mulx rax, rax, rcx +ENDIF + ret +op_mulx64_alias ENDP + +op_pdep32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pext eax, ecx, edx +ELSE + pdep eax, ecx, edx +ENDIF + ret +op_pdep32 ENDP + +op_pdep64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pext rax, rcx, rdx +ELSE + pdep rax, rcx, rdx +ENDIF + ret +op_pdep64 ENDP + +op_pext32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_BIT + pdep eax, ecx, edx +ELSE + pext eax, ecx, edx +ENDIF + ret +op_pext32 ENDP + +op_pext64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_BIT + pdep rax, rcx, rdx +ELSE + pext rax, rcx, rdx +ENDIF + ret +op_pext64 ENDP + +; --- Flat zero-displacement [rcx|rdx] m32 / m64 source forms --- + +op_bzhi32_mem PROC FRAME + .endprolog + mov rax, -1 + mov r9d, dword ptr [rdx] + bzhi eax, dword ptr [rcx], r9d + ret +op_bzhi32_mem ENDP + +op_bzhi64_mem PROC FRAME + .endprolog + mov r9, qword ptr [rdx] + bzhi rax, qword ptr [rcx], r9 + ret +op_bzhi64_mem ENDP + +op_mulx32_mem PROC FRAME + .endprolog + mov r9, -1 + mov r10, -1 + mulx r9d, r10d, dword ptr [rcx] + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx32_mem ENDP + +op_mulx64_mem PROC FRAME + .endprolog + mulx r9, r10, qword ptr [rcx] + mov qword ptr [r8], r10 + mov rax, r9 + ret +op_mulx64_mem ENDP + +op_pdep32_mem PROC FRAME + .endprolog + mov rax, -1 + pdep eax, ecx, dword ptr [rdx] + ret +op_pdep32_mem ENDP + +op_pdep64_mem PROC FRAME + .endprolog + pdep rax, rcx, qword ptr [rdx] + ret +op_pdep64_mem ENDP + +op_pext32_mem PROC FRAME + .endprolog + mov rax, -1 + pext eax, ecx, dword ptr [rdx] + ret +op_pext32_mem ENDP + +op_pext64_mem PROC FRAME + .endprolog + pext rax, rcx, qword ptr [rdx] + ret +op_pext64_mem ENDP + +; --- [r8] source-then-store and program order --- + +op_mem_r8_source PROC FRAME + .endprolog + mov r9, qword ptr [rcx] + pdep r10, r9, qword ptr [r8] + pext r11, r10, qword ptr [rdx] + mulx r9, rax, qword ptr [r8] + xor rax, r11 + mov qword ptr [r8], r10 + ret +op_mem_r8_source ENDP + +; --- BZHI flags: (CF << 0) | (ZF << 1) | (SF << 2) | (OF << 3) --- + +op_bzhi32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + bzhi eax, ecx, edx + PACK_CF_ZF_SF_OF + ret +op_bzhi32_flags ENDP + +op_bzhi64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + bzhi rax, rcx, rdx + PACK_CF_ZF_SF_OF + ret +op_bzhi64_flags ENDP + +; --- Flag preservation across CMP -> PDEP/PEXT/MULX -> SETcc (CF/ZF/SF/OF and PF) --- + +op_flags_preserve32 PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + cmp ecx, edx + pdep r9d, ecx, edx + pext r10d, r9d, edx + mulx r11d, eax, ecx + PACK_CF_ZF_SF_OF + ret +op_flags_preserve32 ENDP + +op_flags_preserve64 PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + cmp rcx, rdx + pdep r9, rcx, rdx + pext r10, r9, rdx + mulx r11, rax, rcx + PACK_CF_ZF_SF_OF + ret +op_flags_preserve64 ENDP + +op_flags_preserve_pf PROC FRAME + .endprolog + cmp rcx, rdx + pdep r9, rcx, rdx + pext r10, r9, rdx + mulx r11, rax, rcx + setp byte ptr [r8] + ret +op_flags_preserve_pf ENDP + +op_flags_preserve_mem PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov r9, qword ptr [rcx] + mov r10, qword ptr [rdx] + cmp r9, r10 + pdep r11, r9, qword ptr [rdx] + pext r9, r11, qword ptr [rcx] + mulx r10, rax, qword ptr [rcx] + PACK_CF_ZF_SF_OF + ret +op_flags_preserve_mem ENDP + +; --- Discarded memory read must still fault on NULL rdx even under /O2 --- + +op_bmi2_bit_discarded_read PROC FRAME + .endprolog + pext r9, rcx, qword ptr [rdx] + mov rax, rcx + ret +op_bmi2_bit_discarded_read ENDP + +END diff --git a/tests/cpu/bmi2_bit_aot.def b/tests/cpu/bmi2_bit_aot.def new file mode 100644 index 0000000000..a8e7c10605 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot.def @@ -0,0 +1,27 @@ +EXPORTS + op_bzhi32 + op_bzhi64 + op_mulx32 + op_mulx64 + op_mulx32_alias + op_mulx64_alias + op_pdep32 + op_pdep64 + op_pext32 + op_pext64 + op_bzhi32_mem + op_bzhi64_mem + op_mulx32_mem + op_mulx64_mem + op_pdep32_mem + op_pdep64_mem + op_pext32_mem + op_pext64_mem + op_mem_r8_source + op_bzhi32_flags + op_bzhi64_flags + op_flags_preserve32 + op_flags_preserve64 + op_flags_preserve_pf + op_flags_preserve_mem + op_bmi2_bit_discarded_read diff --git a/tests/cpu/bmi2_bit_aot_check.py b/tests/cpu/bmi2_bit_aot_check.py new file mode 100644 index 0000000000..cf2f0ae675 --- /dev/null +++ b/tests/cpu/bmi2_bit_aot_check.py @@ -0,0 +1,854 @@ +"""Differential, /O2, flag-preservation, mutant, and rejection checks for cpu_bmi2_bit_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi2_bit_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_bzhi32", + "op_bzhi64", + "op_mulx32", + "op_mulx64", + "op_mulx32_alias", + "op_mulx64_alias", + "op_pdep32", + "op_pdep64", + "op_pext32", + "op_pext64", + "op_bzhi32_mem", + "op_bzhi64_mem", + "op_mulx32_mem", + "op_mulx64_mem", + "op_pdep32_mem", + "op_pdep64_mem", + "op_pext32_mem", + "op_pext64_mem", + "op_mem_r8_source", + "op_bzhi32_flags", + "op_bzhi64_flags", + "op_flags_preserve32", + "op_flags_preserve64", + "op_flags_preserve_pf", + "op_flags_preserve_mem", + "op_bmi2_bit_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_bzhi32", + "op_bzhi64", + "op_mulx32", + "op_mulx64", + "op_mulx32_alias", + "op_mulx64_alias", + "op_pdep32", + "op_pdep64", + "op_pext32", + "op_pext64", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) +OUT_FILL = b"\x5A" * 16 + + +# --- Independent Python reference model --- + +def ref_bzhi(val, idx, bits, *, bad_mask=False): + mask = (1 << bits) - 1 + s = val & mask + n = (idx & (bits - 1)) if bad_mask else (idx & 0xFF) + if n >= bits: + d = s + cf = 1 + else: + d = s & ((1 << n) - 1) + cf = 0 + zf = 1 if d == 0 else 0 + sf = 1 if (d & (1 << (bits - 1))) else 0 + of = 0 + packed = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) + return d, packed + + +def ref_mulx(src1, src2, bits): + mask = (1 << bits) - 1 + prod = (src1 & mask) * (src2 & mask) + lo = prod & mask + hi = (prod >> bits) & mask + return hi, lo + + +def ref_pdep(src, msk, bits): + mask = (1 << bits) - 1 + s = src & mask + m = msk & mask + d = 0 + k = 0 + for i in range(bits): + if (m >> i) & 1: + if (s >> k) & 1: + d |= 1 << i + k += 1 + return d + + +def ref_pext(src, msk, bits): + mask = (1 << bits) - 1 + s = src & mask + m = msk & mask + d = 0 + k = 0 + for i in range(bits): + if (m >> i) & 1: + if (s >> i) & 1: + d |= 1 << k + k += 1 + return d + + +def ref_cmp_flags(a, b, bits): + mask = (1 << bits) - 1 + sign = 1 << (bits - 1) + ua, ub = a & mask, b & mask + r = (ua - ub) & mask + cf = 1 if ua < ub else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r & sign) else 0 + of = 1 if (((ua ^ ub) & (ua ^ r)) & sign) else 0 + pf = 1 if (bin(r & 0xFF).count("1") % 2 == 0) else 0 + packed4 = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) + return (cf, zf, sf, of, pf), packed4 + + +VALUES = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000003, + 0x0000000055AA55AA, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x0000000080000001, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF80000001, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0x8000000000000001, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, +) +BZHI_INDICES = ( + 0, 1, 7, 15, 31, 32, 33, 63, 64, 65, 255, + 0x100, 0x101, 0x120, 0x13F, 0x140, 0xFFFFFFFF, 0x8000000000000000, +) +BIT_MASKS = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000080000000, + 0x0000000055555555, + 0x00000000AAAAAAAA, + 0x00000000FFFFFFFF, + 0x8000000000000001, + 0x0F0F0F0F0F0F0F0F, + 0x5555555555555555, + 0xAAAAAAAAAAAAAAAA, + 0xFFFFFFFFFFFFFFFF, +) + + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + """Verify shifts, BMI1, EVEX/XOP, ABI, addressing, PF/AF, prefix, and state rejections.""" + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + mov_r9_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RCX) + cmp_rcx_rdx = Instruction.create_reg_reg(Code.CMP_R64_RM64, R.RCX, R.RDX) + bzhi_rax = Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.RDX) + + alt_accept = [ + ("bzhi64_r11_r8_rcx", ( + Instruction.create_reg_mem_reg(Code.VEX_BZHI_R64_RM64_R64, R.R11, MemoryOperand(R.R8), R.RCX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), + ret, + ), "r11 = op_bzhi64(ld_1000_1, rcx, flags);"), + ("bzhi32_self_alias", ( + mov_r9_rcx, + Instruction.create_reg_reg_reg(Code.VEX_BZHI_R32_RM32_R32, R.R9D, R.R9D, R.EDX), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), + ret, + ), "r9 = op_bzhi32((r9 & 0xFFFFFFFFull), (rdx & 0xFFFFFFFFull), flags);"), + ("mulx64_alias_mem", ( + Instruction.create_reg_reg_mem(Code.VEX_MULX_R64_R64_RM64, R.R9, R.R9, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), + ret, + ), "r9 = mulx_hi_1000;"), + ("pdep64_r9_r10_rcx", ( + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R10, R.RDX), + Instruction.create_reg_reg_mem(Code.VEX_PDEP_R64_R64_RM64, R.R9, R.R10, MemoryOperand(R.RCX)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), + ret, + ), "r9 = op_pdep64(r10, ld_1003_2);"), + ("pext32_r11_r9_r8", ( + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.R9D, R.ECX), + Instruction.create_reg_reg_mem(Code.VEX_PEXT_R32_R32_RM32, R.R11D, R.R9D, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R11D), + ret, + ), "r11 = op_pext32((r9 & 0xFFFFFFFFull), ld_1003_2);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r} in:\n{src}") + + seg_pext = Instruction.create_reg_reg_mem(Code.VEX_PEXT_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RDX)) + seg_pext.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + # BMI2 shifts & legacy shifts (ALL shifts refused) + ("bmi2_rorx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.RCX, 5), ret), + "unsupported VEX instruction"), + ("bmi2_shlx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_shrx", (Instruction.create_reg_reg_reg(Code.VEX_SHRX_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_sarx", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("legacy_shl_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM32_IMM8, R.EAX, 1), ret), + "unsupported instruction"), + ("legacy_shl_1", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM64_1, R.RAX, 1), ret), + "unsupported instruction"), + ("legacy_shr_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHR_RM32_IMM8, R.EAX, 3), ret), + "unsupported instruction"), + ("legacy_sar_cl", (mov_rax_rcx, Instruction.create_reg_reg(Code.SAR_RM32_CL, R.EAX, R.CL), ret), + "unsupported instruction"), + ("legacy_ror_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.ROR_RM32_IMM8, R.EAX, 2), ret), + "unsupported instruction"), + # BMI1 instructions + ("bmi1_andn", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_bextr", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R32_RM32, R.EAX, R.ECX), ret), + "unsupported VEX instruction"), + ("bmi1_blsmsk", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_blsr", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("bmi1_tzcnt", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + # Nonvolatile GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RBX, R.RCX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RSI, R.RDX), ret), + "nonvolatile GPR"), + ("nonvol_r12_idx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.R12), ret), + "nonvolatile GPR"), + ("nonvol_rsp_lo", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.RSP, R.RCX), ret), + "nonvolatile GPR"), + # Writes to argument GPRs (rcx/rdx/r8) including MULX op0 & op1 + ("write_arg_rcx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RCX, R.RDX, R.R8), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_mulx_hi_edx", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R32_R32_RM32, R.EDX, R.EAX, R.ECX), ret), + "cannot write argument GPR rdx"), + ("write_arg_mulx_lo_r8", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R64_R64_RM64, R.RAX, R.R8, R.RCX), ret), + "cannot write argument GPR r8"), + ("write_arg_pext_r8", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R64_R64_RM64, R.R8, R.RCX, R.RDX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + # High-byte GPRs + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_reg(Code.MOV_R8_RM8, R.AL, R.AH), ret), + "unsupported high-byte GPR"), + ("high_byte_ch_dst", (Instruction.create_reg_reg(Code.MOV_R8_RM8, R.CH, R.DL), mov_rax_rcx, ret), + "unsupported high-byte GPR"), + # Displaced memory operands (must be refused!) + ("disp_mem_bzhi", (Instruction.create_reg_mem_reg( + Code.VEX_BZHI_R64_RM64_R64, R.RAX, MemoryOperand(R.RCX, displ=8, displ_size=1), R.RDX), ret), + "displaced memory operand"), + ("disp_mem_mulx", (Instruction.create_reg_reg_mem( + Code.VEX_MULX_R32_R32_RM32, R.R9D, R.EAX, MemoryOperand(R.RDX, displ=4, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_pdep", (Instruction.create_reg_reg_mem( + Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.R8, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_pext", (Instruction.create_reg_reg_mem( + Code.VEX_PEXT_R32_R32_RM32, R.EAX, R.ECX, MemoryOperand(R.RCX, displ=-4, displ_size=1)), ret), + "displaced memory operand"), + ("disp_mem_store_mov", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("disp_mem_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem( + Code.SETB_RM8, MemoryOperand(R.R8, displ=1, displ_size=1)), ret), + "displaced memory operand"), + # RIP-relative, SIB-indexed, bad base, non-[r8] stores + ("rip_rel_pdep", (Instruction.create_reg_reg_mem( + Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("sib_idx_pext", (Instruction.create_reg_reg_mem( + Code.VEX_PEXT_R64_R64_RM64, R.RAX, R.RCX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("bad_base_rbx", (Instruction.create_reg_reg_mem( + Code.VEX_MULX_R64_R64_RM64, R.R9, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem_reg( + Code.VEX_BZHI_R32_RM32_R32, R.EAX, MemoryOperand(R.RSP), R.EDX), ret), + "bad base register in memory operand"), + ("non_r8_store_mov", (mov_rax_rcx, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("non_r8_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Undefined GPR / undefined flag / PF & AF readers after BZHI + ("undef_gpr_src", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.R9, R.RDX), ret), + "undefined GPR r9"), + ("undef_gpr_idx", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.R10), ret), + "undefined GPR r10"), + ("undef_rax_ret", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R64_R64_RM64, R.R9, R.RCX, R.RDX), ret), + "return with undefined RAX"), + ("undef_flags_setb", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_flags_after_pdep", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R64_R64_RM64, R.RAX, R.RCX, R.RDX), + Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.R8)), ret), "undefined flags read"), + ("undef_pf_setp_after_bzhi", (cmp_rcx_rdx, bzhi_rax, Instruction.create_mem(Code.SETP_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_pf_setnp_after_bzhi", (cmp_rcx_rdx, bzhi_rax, Instruction.create_mem(Code.SETNP_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("af_reader_lahf_after_bzhi", (bzhi_rax, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("af_reader_pushfq_after_bzhi", (bzhi_rax, Instruction.create(Code.PUSHFQ), ret), + "unsupported instruction"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_pext", (seg_pext, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (mov_rax_rcx,), "missing terminal ret"), + ("after_ret", (mov_rax_rcx, ret, mov_r9_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE patching and CLI non-traceback rejection controls. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_flags_preserve64") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from("<I", records, i)[0] == entry) + pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) + max_len = struct.unpack_from("<I", records, rec_idx + 4)[0] - entry + + by_label = {lbl: (seq, reason) for lbl, seq, reason in unit_cases} + pe_labels = ( + "evex_vpaddd", "bmi2_rorx", "legacy_shl_imm", "bmi1_blsi", "nonvol_rbx_dst", + "write_arg_mulx_lo_r8", "disp_mem_bzhi", "undef_pf_setp_after_bzhi", + "non_r8_store_setcc", "seg_prefix_pext", + ) + lifter_script = Path(__file__).resolve().parents[2] / "tools" / "cpu_bmi2_bit_aot.py" + with TemporaryDirectory() as folder: + tmp = Path(folder) + patched_path = tmp / "patched.dll" + out_cpp = tmp / "rejected.cpp" + for label in pe_labels: + seq, reason = by_label[label] + patch = encode_seq(*seq) + if len(patch) > max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off : file_off + len(patch)] = patch + struct.pack_into("<I", damaged, pdata_end_off, entry + len(patch)) + patched_path.write_bytes(damaged) + try: + translate(patched_path, ["op_flags_preserve64"]) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"pe_{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"pe_{label}: PE translate accepted rejected patch") + + proc = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(patched_path), "op_flags_preserve64", str(out_cpp)], + capture_output=True, + text=True, + ) + if proc.returncode != 1 or "Traceback" in proc.stderr or "unsupported instruction prefix" not in proc.stderr: + raise AssertionError(f"CLI rejection unexpected: rc={proc.returncode}, stderr={proc.stderr!r}") + if out_cpp.exists(): + raise AssertionError("CLI failure left behind output file") + + print( + f"rejections passed: {len(alt_accept)} alt + {len(unit_cases)} unit + {len(raw_cases)} raw + " + f"{len(pe_labels)} PE-patched + CLI" + ) + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_bmi2(lifted_lib): + if hasattr(lifted_lib, "host_has_bmi2"): + lifted_lib.host_has_bmi2.argtypes = [] + lifted_lib.host_has_bmi2.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_bmi2()) + try: + return " bmi2" in Path("/proc/cpuinfo").read_text(encoding="ascii", errors="replace") + except OSError: + return False + + +def alloc_guarded(payload, offset=0): + data = GUARD_PRE + b"\x77" * offset + payload + b"\x77" * (8 - offset) + GUARD_POST + buf = ctypes.create_string_buffer(data, len(data)) + ptr = ctypes.addressof(buf) + len(GUARD_PRE) + offset + return buf, ptr, offset, len(payload) + + +def read_guarded(buf, offset, length, label): + raw = buf.raw + if raw[:16] != GUARD_PRE or raw[-16:] != GUARD_POST: + raise AssertionError(f"guard corrupted around {label}") + if raw[16 : 16 + offset] != b"\x77" * offset or raw[16 + offset + length : -16] != b"\x77" * (8 - offset): + raise AssertionError(f"padding corrupted around {label}") + return raw[16 + offset : 16 + offset + length] + + +def check_discarded_read(fns, label): + buf = ctypes.create_string_buffer(struct.pack("<Q", 0x0123456789ABCDEF)) + got = fns["op_bmi2_bit_discarded_read"](0xCAFEBABE12345678, ctypes.addressof(buf), 0) + if got != 0xCAFEBABE12345678: + raise AssertionError(f"{label} op_bmi2_bit_discarded_read(valid) = {got:#x}") + try: + fns["op_bmi2_bit_discarded_read"](0xCAFEBABE12345678, 0, 0) + except OSError as exc: + if "access violation reading" not in str(exc).lower(): + raise AssertionError(f"{label} op_bmi2_bit_discarded_read(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{label} op_bmi2_bit_discarded_read(NULL) dropped faulting m64 read") + + +def verify_positive_suite(native_fns, target_fns, label): + cases = 0 + + # 1) Register forms: BZHI, MULX (normal + op0==op1 alias), PDEP, PEXT + for bits, bzhi_name in ((32, "op_bzhi32"), (64, "op_bzhi64")): + for a in VALUES: + for idx in BZHI_INDICES: + want, _ = ref_bzhi(a, idx, bits) + got_n = native_fns[bzhi_name](a, idx, 0) + got_t = target_fns[bzhi_name](a, idx, 0) + if got_n != want or got_t != want: + raise AssertionError(f"{label} {bzhi_name}({a:#x}, {idx:#x}): n={got_n:#x} t={got_t:#x} exp={want:#x}") + cases += 1 + + for bits, mulx_name, alias_name in ( + (32, "op_mulx32", "op_mulx32_alias"), + (64, "op_mulx64", "op_mulx64_alias"), + ): + for s2 in VALUES: + for s1 in VALUES: + want_hi, want_lo = ref_mulx(s1, s2, bits) + exp_out = struct.pack("<Q", want_lo) + OUT_FILL[8:] + bo_n, po_n, oo_n, lo_n = alloc_guarded(OUT_FILL) + bo_t, po_t, oo_t, lo_t = alloc_guarded(OUT_FILL) + got_n = native_fns[mulx_name](s2, s1, po_n) + got_t = target_fns[mulx_name](s2, s1, po_t) + out_n = read_guarded(bo_n, oo_n, lo_n, f"{mulx_name}_n") + out_t = read_guarded(bo_t, oo_t, lo_t, f"{mulx_name}_t") + if got_n != want_hi or got_t != want_hi or out_n != exp_out or out_t != exp_out: + raise AssertionError( + f"{label} {mulx_name}({s2:#x}, {s1:#x}): hi n={got_n:#x} t={got_t:#x} exp={want_hi:#x}" + ) + got_an = native_fns[alias_name](s2, s1, 0) + got_at = target_fns[alias_name](s2, s1, 0) + if got_an != want_hi or got_at != want_hi: + raise AssertionError( + f"{label} {alias_name}({s2:#x}, {s1:#x}): n={got_an:#x} t={got_at:#x} exp={want_hi:#x}" + ) + cases += 2 + + for bits, name, ref_fn in ( + (32, "op_pdep32", ref_pdep), + (64, "op_pdep64", ref_pdep), + (32, "op_pext32", ref_pext), + (64, "op_pext64", ref_pext), + ): + for s in VALUES: + for m in BIT_MASKS: + want = ref_fn(s, m, bits) + got_n = native_fns[name](s, m, 0) + got_t = target_fns[name](s, m, 0) + if got_n != want or got_t != want: + raise AssertionError(f"{label} {name}({s:#x}, {m:#x}): n={got_n:#x} t={got_t:#x} exp={want:#x}") + cases += 1 + + # 2) Flat zero-displacement [rcx|rdx|r8] memory forms (aligned and misaligned buffers) + rng = random.Random(0xB2B17A07) + mem_inputs = [ + (0x800000017FFFFFFF, 0x0000000000000020, 0x0F0F0F0F0F0F0F0F), + (0xFFFFFFFF80000000, 0x0000000000000100, 0x55555555AAAAAAAA), + (0x0123456789ABCDEF, 0xFFFFFFFFFFFFFFFF, 0x8000000000000001), + ] + [(rng.getrandbits(64), rng.getrandbits(64), rng.getrandbits(64)) for _ in range(16)] + + for a_val, b_val, r8_val in mem_inputs: + a_bytes = struct.pack("<Q", a_val) + b_bytes = struct.pack("<Q", b_val) + r8_init = struct.pack("<Q", r8_val) + OUT_FILL[8:] + for mis in (0, 3): + ba, pa, oa, la = alloc_guarded(a_bytes, mis) + bb, pb, ob, lb = alloc_guarded(b_bytes, mis) + + for bits, name in ((32, "op_bzhi32_mem"), (64, "op_bzhi64_mem")): + want, _ = ref_bzhi(a_val, b_val, bits) + got_n = native_fns[name](pa, pb, 0) + got_t = target_fns[name](pa, pb, 0) + if got_n != want or got_t != want: + raise AssertionError(f"{label} {name} mis={mis}: n={got_n:#x} t={got_t:#x} exp={want:#x}") + cases += 1 + + for bits, name in ((32, "op_mulx32_mem"), (64, "op_mulx64_mem")): + want_hi, want_lo = ref_mulx(b_val, a_val, bits) + exp_out = struct.pack("<Q", want_lo) + OUT_FILL[8:] + bo_n, po_n, oo_n, lo_n = alloc_guarded(OUT_FILL, mis) + bo_t, po_t, oo_t, lo_t = alloc_guarded(OUT_FILL, mis) + got_n = native_fns[name](pa, b_val, po_n) + got_t = target_fns[name](pa, b_val, po_t) + out_n = read_guarded(bo_n, oo_n, lo_n, f"{name}_n") + out_t = read_guarded(bo_t, oo_t, lo_t, f"{name}_t") + if got_n != want_hi or got_t != want_hi or out_n != exp_out or out_t != exp_out: + raise AssertionError(f"{label} {name} mis={mis} mismatch") + cases += 1 + + for bits, name, ref_fn in ( + (32, "op_pdep32_mem", ref_pdep), + (64, "op_pdep64_mem", ref_pdep), + (32, "op_pext32_mem", ref_pext), + (64, "op_pext64_mem", ref_pext), + ): + want = ref_fn(a_val, b_val, bits) + got_n = native_fns[name](a_val, pb, 0) + got_t = target_fns[name](a_val, pb, 0) + if got_n != want or got_t != want: + raise AssertionError(f"{label} {name} mis={mis}: n={got_n:#x} t={got_t:#x} exp={want:#x}") + cases += 1 + + # op_mem_r8_source: reads [rcx], [rdx], [r8] BEFORE storing r10 to [r8] (mulx uses rdx=pb). + r10 = ref_pdep(a_val, r8_val, 64) + r11 = ref_pext(r10, b_val, 64) + _, mul_lo = ref_mulx(pb, r8_val, 64) + want_rax = mul_lo ^ r11 + exp_r8 = struct.pack("<Q", r10) + OUT_FILL[8:] + bo_n, po_n, oo_n, lo_n = alloc_guarded(r8_init, mis) + bo_t, po_t, oo_t, lo_t = alloc_guarded(r8_init, mis) + got_n = native_fns["op_mem_r8_source"](pa, pb, po_n) + got_t = target_fns["op_mem_r8_source"](pa, pb, po_t) + out_n = read_guarded(bo_n, oo_n, lo_n, "r8_src_n") + out_t = read_guarded(bo_t, oo_t, lo_t, "r8_src_t") + if got_n != want_rax or got_t != want_rax or out_n != exp_r8 or out_t != exp_r8: + raise AssertionError(f"{label} op_mem_r8_source mis={mis} mismatch") + assert read_guarded(ba, oa, la, "a") == a_bytes and read_guarded(bb, ob, lb, "b") == b_bytes + cases += 1 + + # 3) BZHI flag definitions (CF, ZF, SF, OF=0) + bzhi_flag_pairs = [ + (0x0000000000000000, 0), + (0x0000000000000000, 32), + (0x0000000000000000, 64), + (0xFFFFFFFF80000000, 0), + (0xFFFFFFFF80000000, 31), + (0xFFFFFFFF80000000, 32), + (0x8000000000000000, 63), + (0x8000000000000000, 64), + (0x0000000080000001, 0x100), + (0x8000000080000001, 0x120), + (0x8000000080000001, 0x140), + (0x0123456789ABCDEF, 17), + ] + for bits, name in ((32, "op_bzhi32_flags"), (64, "op_bzhi64_flags")): + seen_bzhi = set() + for a, idx in bzhi_flag_pairs: + _, packed = ref_bzhi(a, idx, bits) + seen_bzhi.add(packed) + exp_buf = struct.pack("<I", packed) + OUT_FILL[4:] + bo_n, po_n, oo_n, lo_n = alloc_guarded(OUT_FILL) + bo_t, po_t, oo_t, lo_t = alloc_guarded(OUT_FILL) + got_n = native_fns[name](a, idx, po_n) + got_t = target_fns[name](a, idx, po_t) + buf_n = read_guarded(bo_n, oo_n, lo_n, f"{name}_n") + buf_t = read_guarded(bo_t, oo_t, lo_t, f"{name}_t") + if got_n != packed or got_t != packed or buf_n != exp_buf or buf_t != exp_buf: + raise AssertionError(f"{label} {name}({a:#x}, {idx:#x}): n={got_n:#x} t={got_t:#x} exp={packed:#x}") + cases += 1 + for bit_idx, fname in ((0, "CF"), (1, "ZF"), (2, "SF")): + if {(p >> bit_idx) & 1 for p in seen_bzhi} != {0, 1}: + raise AssertionError(f"{name} did not exercise both 0 and 1 for {fname}") + if {(p >> 3) & 1 for p in seen_bzhi} != {0}: + raise AssertionError(f"{name} observed non-zero OF") + + # 4) Flag preservation across CMP -> PDEP/PEXT/MULX -> SETcc (CF, ZF, SF, OF, PF) + flag_pairs = [ + (0x0000000000000000, 0x0000000000000000), + (0x0000000000000000, 0x0000000000000001), + (0x0000000000000003, 0x0000000000000002), + (0x0000000080000000, 0x0000000000000001), + (0x000000007FFFFFFF, 0x00000000FFFFFFFF), + (0x8000000000000000, 0x0000000000000001), + (0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF), + ] + [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(24)] + + for bits, name in ((32, "op_flags_preserve32"), (64, "op_flags_preserve64")): + seen = set() + for a, b in flag_pairs: + f_tuple, packed4 = ref_cmp_flags(a, b, bits) + seen.add(f_tuple[:4]) + exp_buf = struct.pack("<I", packed4) + OUT_FILL[4:] + bo_n, po_n, oo_n, lo_n = alloc_guarded(OUT_FILL) + bo_t, po_t, oo_t, lo_t = alloc_guarded(OUT_FILL) + got_n = native_fns[name](a, b, po_n) + got_t = target_fns[name](a, b, po_t) + buf_n = read_guarded(bo_n, oo_n, lo_n, f"{name}_n") + buf_t = read_guarded(bo_t, oo_t, lo_t, f"{name}_t") + if got_n != packed4 or got_t != packed4 or buf_n != exp_buf or buf_t != exp_buf: + raise AssertionError(f"{label} {name}({a:#x}, {b:#x}): n={got_n:#x} t={got_t:#x} exp={packed4:#x}") + cases += 1 + for idx, fname in enumerate(("CF", "ZF", "SF", "OF")): + if {t[idx] for t in seen} != {0, 1}: + raise AssertionError(f"{name} did not exercise both 0 and 1 for {fname}") + + seen_pf = set() + for a, b in flag_pairs: + f_tuple, packed4 = ref_cmp_flags(a, b, 64) + pf = f_tuple[4] + seen_pf.add(pf) + _, want_rax = ref_mulx(b, a, 64) + exp_buf = bytes((pf,)) + OUT_FILL[1:] + bo_n, po_n, oo_n, lo_n = alloc_guarded(OUT_FILL) + bo_t, po_t, oo_t, lo_t = alloc_guarded(OUT_FILL) + got_n = native_fns["op_flags_preserve_pf"](a, b, po_n) + got_t = target_fns["op_flags_preserve_pf"](a, b, po_t) + buf_n = read_guarded(bo_n, oo_n, lo_n, "flags_pf_n") + buf_t = read_guarded(bo_t, oo_t, lo_t, "flags_pf_t") + if got_n != want_rax or got_t != want_rax or buf_n != exp_buf or buf_t != exp_buf: + raise AssertionError(f"{label} op_flags_preserve_pf({a:#x}, {b:#x}) mismatch") + + ba, pa, _, _ = alloc_guarded(struct.pack("<Q", a)) + bb, pb, _, _ = alloc_guarded(struct.pack("<Q", b)) + exp_mbuf = struct.pack("<I", packed4) + OUT_FILL[4:] + bo_mn, po_mn, oo_mn, lo_mn = alloc_guarded(OUT_FILL) + bo_mt, po_mt, oo_mt, lo_mt = alloc_guarded(OUT_FILL) + got_mn = native_fns["op_flags_preserve_mem"](pa, pb, po_mn) + got_mt = target_fns["op_flags_preserve_mem"](pa, pb, po_mt) + buf_mn = read_guarded(bo_mn, oo_mn, lo_mn, "flags_mem_n") + buf_mt = read_guarded(bo_mt, oo_mt, lo_mt, "flags_mem_t") + if got_mn != packed4 or got_mt != packed4 or buf_mn != exp_mbuf or buf_mt != exp_mbuf: + raise AssertionError(f"{label} op_flags_preserve_mem({a:#x}, {b:#x}) mismatch") + cases += 2 + if seen_pf != {0, 1}: + raise AssertionError(f"op_flags_preserve_pf did not exercise both 0 and 1 for PF: {seen_pf}") + + check_discarded_read(native_fns, "native") + check_discarded_read(target_fns, label) + return cases + + +def check_altered_and_mutants(lifted_fns, alt_native_fns, alt_lifted_fns): + diverged = {} + for name in ALTERED_EXPORTS: + diffs = 0 + for a in VALUES[:8]: + for b in VALUES[:8]: + bo_n, po_n, _, _ = alloc_guarded(OUT_FILL) + bo_l, po_l, _, _ = alloc_guarded(OUT_FILL) + bo_o, po_o, _, _ = alloc_guarded(OUT_FILL) + got_an = alt_native_fns[name](a, b, po_n) + got_al = alt_lifted_fns[name](a, b, po_l) + if got_an != got_al or bo_n.raw != bo_l.raw: + raise AssertionError(f"altered {name}({a:#x}, {b:#x}) native/lifted mismatch") + got_orig = lifted_fns[name](a, b, po_o) + if got_orig != got_al or bo_o.raw != bo_l.raw: + diffs += 1 + if diffs == 0: + raise AssertionError(f"ALTER_BMI2_BIT failed to diverge on {name}") + diverged[name] = diffs + + # Mutant 1: BZHI index masking to 5/6 bits instead of [7:0] (index=32/64 or 0x100). + if lifted_fns["op_bzhi32"](0x12345678, 32, 0) != 0x12345678: + raise AssertionError("mutant bzhi32(32) failed to preserve src") + if lifted_fns["op_bzhi32"](0x12345678, 0x100, 0) != 0: + raise AssertionError("mutant bzhi32(0x100) failed to return 0") + if lifted_fns["op_bzhi64"](0x123456789ABCDEF0, 64, 0) != 0x123456789ABCDEF0: + raise AssertionError("mutant bzhi64(64) failed to preserve src") + if lifted_fns["op_bzhi64"](0x123456789ABCDEF0, 0x100, 0) != 0: + raise AssertionError("mutant bzhi64(0x100) failed to return 0") + # Check CF=1 when index==32 (32-bit) vs CF=0 when index==0x100. + bo1, po1, _, _ = alloc_guarded(OUT_FILL) + bo2, po2, _, _ = alloc_guarded(OUT_FILL) + if (lifted_fns["op_bzhi32_flags"](0x12345678, 32, po1) & 1) != 1: + raise AssertionError("mutant bzhi32_flags(32) CF!=1") + if (lifted_fns["op_bzhi32_flags"](0x12345678, 0x100, po2) & 1) != 0: + raise AssertionError("mutant bzhi32_flags(0x100) CF!=0") + del bo1, bo2 + + # Mutant 2: MULX op0 == op1 must yield high half, not low half. + if lifted_fns["op_mulx32_alias"](0x80000000, 4, 0) != 2: + raise AssertionError("mutant mulx32_alias returned low half instead of high half") + if lifted_fns["op_mulx64_alias"](0x8000000000000000, 4, 0) != 2: + raise AssertionError("mutant mulx64_alias returned low half instead of high half") + + # Mutant 3: PDEP/PEXT/MULX must preserve flags (e.g. CF=1, ZF=0, PF=0 from cmp(1, 20)). + bo_f, po_f, oo_f, lo_f = alloc_guarded(OUT_FILL) + packed = lifted_fns["op_flags_preserve32"](1, 20, po_f) + if packed != 0b0101: # CF=1, ZF=0, SF=1, OF=0 + raise AssertionError(f"flag-preservation witness failed: got {packed:#b}") + assert read_guarded(bo_f, oo_f, lo_f, "flag_mutant")[:4] == struct.pack("<I", 0b0101) + return diverged + + +def compile_o2_and_verify(original_path, native_fns, cxx_path): + source_text, _ = translate(original_path, list(EXPORTS)) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "bmi2_bit_o2.cpp" + dll_path = tmp / "bmi2_bit_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'bmi2_bit_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_positive_suite(native_fns, o2_fns, "lifted_o2") + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + check_rejections(original_path) + + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + if not host_has_bmi2(lifted_lib): + lifted_fns.clear() + unload_lib(lifted_lib) + print("Host lacks BMI2 (CPUID leaf 7 subleaf 0 EBX bit 8); skipping native differential check") + sys.exit(77) + + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_positive_suite(orig_fns, lifted_fns, "lifted") + diverged = check_altered_and_mutants(lifted_fns, alt_fns, alt_lifted_fns) + o2_cases = compile_o2_and_verify(original_path, orig_fns, cxx_path) + finally: + for fn_map, lib in ( + (orig_fns, orig_lib), + (lifted_fns, lifted_lib), + (alt_fns, alt_lib), + (alt_lifted_fns, alt_lifted_lib), + ): + fn_map.clear() + unload_lib(lib) + + record_covered_forms(original_path) + print( + f"bmi2_bit_aot passed: {lifted_cases} lifted + {o2_cases} /O2 cases across {len(EXPORTS)} exports; " + f"ALTER_BMI2_BIT diverged on {diverged}" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/hint_nop_check.py b/tests/cpu/hint_nop_check.py index 2bc720dfe1..39251f70a9 100644 --- a/tests/cpu/hint_nop_check.py +++ b/tests/cpu/hint_nop_check.py @@ -2,9 +2,8 @@ """Control for the reserved/hint NOP space in the shared lowering (tools/ffx_version_query.py, #1476). The AMD APM documents `0F 19 /r`, `0F 1D /r`, `0F 1E /r` (unprefixed) and `0F 1F /r` as reserved hint NOPs -that take a ModRM but access no memory. CET-instrumented code puts `endbr64` at function entries and this -target has no CET, but ENDBR is deliberately out of this slice: it is listed as a refusal here so widening -the accepted set later is a visible change rather than a silent one. +that take a ModRM but access no memory. CET-instrumented code puts `endbr64`/`endbr32` (`F3 0F 1E FA/FB`) at +indirect-branch targets; both have no register, flag, or memory side effects and execute as NOPs on `x64_zen2`. What is checked, all on exact byte patterns: @@ -12,8 +11,9 @@ already-accepted NOP. Identical bodies are the proof that the instruction evaluates nothing: no address computation, no load, no register or flag write. Block labels are normalised because they are numbered by instruction count, not by effect. - refused - encodings in the same space that iced decodes as another mnemonic stay refused: - ENDBR64/ENDBR32, CLDEMOTE, RDSSPD/RDSSPQ. A widened accepted set would show up here. + refused - encodings in the same space that iced decodes as another mnemonic or unaccepted reserved NOP + stay refused: CLDEMOTE, RDSSPD/RDSSPQ, 0F 0D, 0F 18, 0F 1A-0F 1C. A widened accepted set would + show up here. The memory-form cases include a ModRM whose address would fault if evaluated (a non-canonical pointer in RAX) and a RIP-relative displacement: identical lifted bodies mean neither can be touched. @@ -39,6 +39,8 @@ "660f1e00": "reserved nop 0F 1E [rax], 16-bit operand size", "480f1900": "reserved nop 0F 19 [rax], 64-bit operand size", "480f1e00": "reserved nop 0F 1E [rax], 64-bit operand size", + "f30f1efa": "endbr64", + "f30f1efb": "endbr32", } # Encodings in the same space that iced also decodes as RESERVEDNOP but that are not part of this slice, plus @@ -50,10 +52,9 @@ "0f1a00": "0F 1A", "0f1b00": "0F 1B", "0f1c08": "0F 1C /1", - "f30f1efa": "endbr64", - "f30f1efb": "endbr32", "0f1c00": "cldemote [rax]", "f30f1ec8": "rdsspd eax", + "f3480f1ec8": "rdsspq rax", } LABEL = re.compile(r"block_\d+") diff --git a/tests/cpu/hint_nop_fixture.py b/tests/cpu/hint_nop_fixture.py index b947a28879..1056d36580 100644 --- a/tests/cpu/hint_nop_fixture.py +++ b/tests/cpu/hint_nop_fixture.py @@ -42,6 +42,8 @@ ("hn_0f1e_16", "66 0F 1E [rax], 16-bit operand size", bytes.fromhex("660f1e00"), True), ("hn_0f19_64", "48 0F 19 [rax], 64-bit operand size", bytes.fromhex("480f1900"), True), ("hn_0f1e_64", "48 0F 1E [rax], 64-bit operand size", bytes.fromhex("480f1e00"), True), + ("hn_endbr64", "F3 0F 1E FA (endbr64)", bytes.fromhex("f30f1efa"), False), + ("hn_endbr32", "F3 0F 1E FB (endbr32)", bytes.fromhex("f30f1efb"), False), ] TEST_MAIN = r""" diff --git a/tests/cpu/movbe_aot.asm b/tests/cpu/movbe_aot.asm new file mode 100644 index 0000000000..0c7eaa2cea --- /dev/null +++ b/tests/cpu/movbe_aot.asm @@ -0,0 +1,227 @@ +; coverage: record cpu_aot_movbe_dedicated +; Source-built MASM fixture for all 6 MOVBE forms (16/32/64-bit loads and stores) +; from docs/coverage/x64_zen2.tsv group MOVBE: [rcx|rdx|r8 (+small_disp)] loads, +; [r8 (+disp)] stores, 16-bit upper-bit preservation, 32-bit zero-extension, +; zero flag modification, [r8] source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF_PF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8+16] + setp byte ptr [r8+20] + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 2 + or r9d, r11d + movzx r10d, byte ptr [r8+16] + shl r10d, 3 + or r9d, r10d + movzx r10d, byte ptr [r8+20] + shl r10d, 4 + or r9d, r10d + mov dword ptr [r8+16], r9d +ENDM + +; --- Loads (16-bit preserves [63:16], 32-bit zero-extends [63:32], 64-bit full) --- + +op_movbe_load16 PROC FRAME + .endprolog + mov rax, rdx +IFDEF ALTER_MOVBE + mov ax, word ptr [rcx] +ELSE + movbe ax, word ptr [rcx] +ENDIF + ret +op_movbe_load16 ENDP + +op_movbe_load16_disp PROC FRAME + .endprolog + mov r9, rdx +IFDEF ALTER_MOVBE + movbe r9w, word ptr [rcx+1] +ELSE + movbe r9w, word ptr [rcx+3] +ENDIF + mov rax, r9 + ret +op_movbe_load16_disp ENDP + +op_movbe_load32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_MOVBE + mov eax, dword ptr [rcx] +ELSE + movbe eax, dword ptr [rcx] +ENDIF + ret +op_movbe_load32 ENDP + +op_movbe_load32_disp PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_MOVBE + movbe r10d, dword ptr [rdx+1] +ELSE + movbe r10d, dword ptr [rdx+5] +ENDIF + mov rax, r10 + ret +op_movbe_load32_disp ENDP + +op_movbe_load64 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov rax, qword ptr [rcx] +ELSE + movbe rax, qword ptr [rcx] +ENDIF + ret +op_movbe_load64 ENDP + +op_movbe_load64_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe r11, qword ptr [rdx+4] +ELSE + movbe r11, qword ptr [rdx+8] +ENDIF + mov rax, r11 + ret +op_movbe_load64_disp ENDP + +; --- Stores strictly to [r8] or [r8+disp] --- + +op_movbe_store16 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov word ptr [r8], dx +ELSE + movbe word ptr [r8], dx +ENDIF + mov rax, rdx + ret +op_movbe_store16 ENDP + +op_movbe_store16_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe word ptr [r8+4], dx +ELSE + movbe word ptr [r8+2], dx +ENDIF + mov rax, rdx + ret +op_movbe_store16_disp ENDP + +op_movbe_store32 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov dword ptr [r8], edx +ELSE + movbe dword ptr [r8], edx +ENDIF + mov eax, edx + ret +op_movbe_store32 ENDP + +op_movbe_store32_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe dword ptr [r8+8], edx +ELSE + movbe dword ptr [r8+4], edx +ENDIF + mov eax, edx + ret +op_movbe_store32_disp ENDP + +op_movbe_store64 PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + mov qword ptr [r8], rdx +ELSE + movbe qword ptr [r8], rdx +ENDIF + mov rax, rdx + ret +op_movbe_store64 ENDP + +op_movbe_store64_disp PROC FRAME + .endprolog +IFDEF ALTER_MOVBE + movbe qword ptr [r8+16], rdx +ELSE + movbe qword ptr [r8+8], rdx +ENDIF + mov rax, rdx + ret +op_movbe_store64_disp ENDP + +; --- Flag preservation checks (PACK_CF_ZF_SF_OF_PF -> dword ptr [r8+16]) --- + +op_movbe_flags_cf_zf_of_pf PROC FRAME + .endprolog + mov r9d, 80000000h + shl r9d, 1 + movbe eax, dword ptr [rcx] + movbe dword ptr [r8], eax + mov r10d, 0 + mov r11d, 0 + PACK_CF_ZF_SF_OF_PF + ret +op_movbe_flags_cf_zf_of_pf ENDP + +op_movbe_flags_sf_of_pf PROC FRAME + .endprolog + mov r9d, 40000000h + shl r9d, 1 + movbe rax, qword ptr [rcx] + movbe qword ptr [r8+8], rax + mov r10d, 0 + mov r11d, 0 + PACK_CF_ZF_SF_OF_PF + ret +op_movbe_flags_sf_of_pf ENDP + +op_movbe_flags_all_clear PROC FRAME + .endprolog + mov r9d, 0 + or r9d, 1 + mov rax, -1 + movbe ax, word ptr [rcx] + movbe word ptr [r8], ax + mov r10d, 0 + mov r11d, 0 + PACK_CF_ZF_SF_OF_PF + ret +op_movbe_flags_all_clear ENDP + +; --- [r8] source-then-store and discarded faulting m64 read --- + +op_r8_source_then_store PROC FRAME + .endprolog + mov r11, rdx + movbe r9, qword ptr [r8] + movbe r10d, dword ptr [rcx] + movbe r11w, word ptr [rdx] + movbe qword ptr [r8+8], r9 + movbe dword ptr [r8], r10d + mov rax, r11 + ret +op_r8_source_then_store ENDP + +op_movbe_discarded_read PROC FRAME + .endprolog + movbe r9, qword ptr [rdx] + mov rax, rcx + ret +op_movbe_discarded_read ENDP + +END diff --git a/tests/cpu/movbe_aot.def b/tests/cpu/movbe_aot.def new file mode 100644 index 0000000000..4dc37d6e87 --- /dev/null +++ b/tests/cpu/movbe_aot.def @@ -0,0 +1,18 @@ +EXPORTS + op_movbe_load16 + op_movbe_load16_disp + op_movbe_load32 + op_movbe_load32_disp + op_movbe_load64 + op_movbe_load64_disp + op_movbe_store16 + op_movbe_store16_disp + op_movbe_store32 + op_movbe_store32_disp + op_movbe_store64 + op_movbe_store64_disp + op_movbe_flags_cf_zf_of_pf + op_movbe_flags_sf_of_pf + op_movbe_flags_all_clear + op_r8_source_then_store + op_movbe_discarded_read diff --git a/tests/cpu/movbe_aot_check.py b/tests/cpu/movbe_aot_check.py new file mode 100644 index 0000000000..d62d31edc1 --- /dev/null +++ b/tests/cpu/movbe_aot_check.py @@ -0,0 +1,643 @@ +"""Differential, /O2, flag-preservation, mutant, and rejection checks for cpu_movbe_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_movbe_aot import lift_code, translate # noqa: E402 + +EXPORTS = ( + "op_movbe_load16", "op_movbe_load16_disp", + "op_movbe_load32", "op_movbe_load32_disp", + "op_movbe_load64", "op_movbe_load64_disp", + "op_movbe_store16", "op_movbe_store16_disp", + "op_movbe_store32", "op_movbe_store32_disp", + "op_movbe_store64", "op_movbe_store64_disp", + "op_movbe_flags_cf_zf_of_pf", + "op_movbe_flags_sf_of_pf", + "op_movbe_flags_all_clear", + "op_r8_source_then_store", + "op_movbe_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_movbe_load16", "op_movbe_load16_disp", + "op_movbe_load32", "op_movbe_load32_disp", + "op_movbe_load64", "op_movbe_load64_disp", + "op_movbe_store16", "op_movbe_store16_disp", + "op_movbe_store32", "op_movbe_store32_disp", + "op_movbe_store64", "op_movbe_store64_disp", +) + +MASK16 = 0xFFFF +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference model --- + +def ref_movbe_load(buf, offset, width, prior_reg, *, quirk=None): + raw = buf[offset:offset + width // 8] + val = int.from_bytes(raw, "little" if quirk == "noswap" else "big") + if width == 16: + if quirk == "clear16": + return val + return (prior_reg & ~MASK16) | val + if width == 32: + if quirk == "no_zext32": + return val | 0xFFFFFFFF00000000 + return val + return val + + +def ref_movbe_store(val, width, *, quirk=None): + mask = (1 << width) - 1 + return (val & mask).to_bytes(width // 8, "little" if quirk == "noswap" else "big") + + +def test_inputs(): + mem_blocks = [ + bytes(range(0x10, 0x30)), + b"\x00" * 32, + b"\xff" * 32, + bytes((0x11 * k + 0x5A) & 0xFF for k in range(32)), + struct.pack("<4Q", 0x0102030405060708, 0x8000000000000001, 0xDEADBEEFCAFEF00D, 0x00FF00FF00FF00FF), + ] + regs = [ + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0xDEADBEEF12345678, + 0x0102030405060708, + 0x8000000000000001, + 0x00000000CAFEBABE, + ] + rng = random.Random(0x40DBE07) + for _ in range(8): + mem_blocks.append(rng.randbytes(32)) + regs.append(rng.getrandbits(64)) + return mem_blocks, regs + + +# --- Guarded memory & DLL helpers --- + +def alloc_guarded(payload): + raw = ctypes.create_string_buffer(GUARD_PRE + payload + GUARD_POST, len(GUARD_PRE) + len(payload) + len(GUARD_POST)) + base = ctypes.addressof(raw) + return raw, base + len(GUARD_PRE), len(GUARD_PRE), len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[:off] != GUARD_PRE or raw[off + length:] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_movbe(lifted_lib): + if hasattr(lifted_lib, "host_has_movbe"): + lifted_lib.host_has_movbe.argtypes = [] + lifted_lib.host_has_movbe.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_movbe()) + return False + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + mov_r9_rdx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RDX) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("movbe_r11w_r8_disp12", (Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R11, R.RDX), + Instruction.create_reg_mem(Code.MOVBE_R16_M16, R.R11W, MemoryOperand(R.R8, displ=12, displ_size=1)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "const word ld_1003_1 = static_cast<word>(bswap16(load_always<std::uint16_t>((r8 + 0xcull))));"), + ("movbe_m32_r10d_disp16", (Instruction.create_reg_reg(Code.MOV_R32_RM32, R.R10D, R.ECX), + Instruction.create_mem_reg(Code.MOVBE_M32_R32, MemoryOperand(R.R8, displ=16, displ_size=1), R.R10D), + mov_rax_rcx, ret), + "store_always<std::uint32_t>((r8 + 0x10ull), bswap32(static_cast<std::uint32_t>((r10 & 0xFFFFFFFFull))));"), + ("movbe_r9_rdx_disp64", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.R9, MemoryOperand(R.RDX, displ=64, displ_size=1)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R9), ret), + "const word ld_1000_1 = static_cast<word>(bswap64(load_always<std::uint64_t>((rdx + 0x40ull))));"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_movbe = Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RCX)) + seg_movbe.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # Stores outside [r8] + ("store_rcx_movbe16", (Instruction.create_mem_reg(Code.MOVBE_M16_R16, MemoryOperand(R.RCX), R.DX), mov_rax_rcx, ret), + "non-r8 store memory operand"), + ("store_rdx_movbe32", (Instruction.create_mem_reg(Code.MOVBE_M32_R32, MemoryOperand(R.RDX, displ=4, displ_size=1), R.ECX), mov_rax_rcx, ret), + "non-r8 store memory operand"), + ("store_rcx_movbe64", (Instruction.create_mem_reg(Code.MOVBE_M64_R64, MemoryOperand(R.RCX), R.RDX), mov_rax_rcx, ret), + "non-r8 store memory operand"), + ("store_rcx_mov64", (mov_rax_rcx, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("store_rdx_setb", (Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D), + Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.RDX)), mov_rax_rcx, ret), + "non-r8 store memory operand"), + # Indexed / scaled / RIP-relative / bad base / out-of-range displacement + ("indexed_movbe64", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RCX, R.RDX, 4)), ret), + "SIB index memory operand"), + ("scaled_store_movbe", (Instruction.create_mem_reg( + Code.MOVBE_M32_R32, MemoryOperand(R.R8, R.RCX, 2), R.EDX), mov_rax_rcx, ret), + "SIB index memory operand"), + ("rip_rel_movbe", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem(Code.MOVBE_R32_M32, R.EAX, MemoryOperand(R.RSP)), ret), + "bad base register in memory operand"), + ("neg_disp_movbe", (Instruction.create_reg_mem( + Code.MOVBE_R32_M32, R.EAX, MemoryOperand(R.RCX, displ=-4, displ_size=1)), ret), + "out-of-range displaced memory operand"), + ("large_disp_movbe", (Instruction.create_reg_mem( + Code.MOVBE_R64_M64, R.RAX, MemoryOperand(R.RCX, displ=128, displ_size=8)), ret), + "out-of-range displaced memory operand"), + ("large_disp_store", (Instruction.create_mem_reg( + Code.MOVBE_M64_R64, MemoryOperand(R.R8, displ=65, displ_size=1), R.RDX), mov_rax_rcx, ret), + "out-of-range displaced memory operand"), + # Nonvolatile GPRs, arg GPR writes, high-byte GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RBX, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_mem_reg(Code.MOVBE_M64_R64, MemoryOperand(R.R8), R.RSI), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_r12_dst", (Instruction.create_reg_mem(Code.MOVBE_R32_M32, R.R12D, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("write_arg_rcx", (Instruction.create_reg_mem(Code.MOVBE_R64_M64, R.RCX, MemoryOperand(R.RDX)), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (Instruction.create_reg_mem(Code.MOVBE_R32_M32, R.EDX, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8w", (Instruction.create_reg_mem(Code.MOVBE_R16_M16, R.R8W, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_u32(Code.MOV_R8_IMM8, R.AH, 1), ret), + "unsupported high-byte GPR"), + # Undefined GPRs / flags + ("undef_r9_movbe16_dst", (Instruction.create_reg_mem(Code.MOVBE_R16_M16, R.R9W, MemoryOperand(R.RCX)), mov_rax_rcx, ret), + "undefined GPR r9"), + ("undef_r10_movbe_store", (Instruction.create_mem_reg(Code.MOVBE_M64_R64, MemoryOperand(R.R8), R.R10), mov_rax_rcx, ret), + "undefined GPR r10"), + ("undef_rax_ret", (mov_r9_rdx, ret), "return with undefined RAX"), + ("undef_flags_setb", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flag cf read"), + # Out-of-scope / VEX / EVEX / XOP / prefixes / branches / ret + ("bswap_rejected", (mov_rax_rcx, Instruction.create_reg(Code.BSWAP_R64, R.RAX), ret), + "unsupported instruction"), + ("cmovbe_rejected", (Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D), + Instruction.create_reg_reg(Code.CMOVBE_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + ("vex_blsi", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RAX, R.RCX), ret), + "unsupported VEX instruction"), + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_blsic", (Instruction.create_reg_reg(Code.XOP_BLSIC_R64_RM64, R.RAX, R.RCX), ret), + "unsupported XOP instruction"), + ("seg_prefix_movbe", (seg_movbe, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (mov_rax_rcx,), "missing terminal ret"), + ("trailing_after_ret", (mov_rax_rcx, ret, mov_r9_rdx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("movbe_reg_reg_ud", bytes.fromhex("0f38f0c1") + encode_seq(ret), "invalid instruction"), + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback / temp-cleanup rejections. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_movbe_flags_cf_zf_of_pf") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from("<I", records, i)[0] == entry) + pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) + max_len = struct.unpack_from("<I", records, rec_idx + 4)[0] - entry + + by_label = {label: (encode_seq(*seq), reason) for label, seq, reason in unit_cases} + pe_labels = ( + "store_rcx_movbe16", + "store_rcx_movbe64", + "indexed_movbe64", + "rip_rel_movbe", + "neg_disp_movbe", + "large_disp_movbe", + "nonvol_rbx_dst", + "write_arg_rcx", + "bswap_rejected", + "branch_jmp", + "seg_prefix_movbe", + ) + lifter_script = Path(__file__).resolve().parents[2] / "tools" / "cpu_movbe_aot.py" + with TemporaryDirectory() as folder: + tmp = Path(folder) + patched = tmp / "patched.dll" + out_cpp = tmp / "rejected.cpp" + for label in pe_labels: + patch, reason = by_label[label] + if len(patch) > max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("<I", damaged, pdata_end_off, entry + len(patch)) + patched.write_bytes(damaged) + try: + translate(patched, ["op_movbe_flags_cf_zf_of_pf"]) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"pe_{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"pe_{label}: PE translate accepted rejected patch") + + proc = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(patched), "op_movbe_flags_cf_zf_of_pf", str(out_cpp)], + capture_output=True, + text=True, + ) + if proc.returncode != 1 or "Traceback" in proc.stderr or "unsupported instruction prefix" not in proc.stderr: + raise AssertionError(f"CLI rejection unexpected: rc={proc.returncode}, stderr={proc.stderr!r}") + if out_cpp.exists() or list(tmp.glob("*.tmp")): + raise AssertionError("CLI failure left behind output or temp file") + + bad_dir = tmp / "dir_out" + bad_dir.mkdir() + proc_dir = subprocess.run( + [sys.executable, "-B", str(lifter_script), str(original_path), "op_movbe_load64", str(bad_dir)], + capture_output=True, + text=True, + ) + if proc_dir.returncode != 1 or "Traceback" in proc_dir.stderr or "directory" not in proc_dir.stderr: + raise AssertionError(f"CLI dir rejection unexpected: rc={proc_dir.returncode}, stderr={proc_dir.stderr!r}") + + print( + f"rejections passed: {len(alt_accept)} alt + {len(unit_cases)} IR + " + f"{len(raw_cases)} raw + {len(pe_labels)} PE-patched + CLI" + ) + + +# --- Positive, altered, mutant, and /O2 verification --- + +def verify_suite(fns, label, mem_blocks, regs): + total = 0 + + # 1) Load forms (16-bit preserves [63:16], 32-bit zero-extends, 64-bit full, + disp). + load_specs = ( + ("op_movbe_load16", 16, 0, "rcx"), + ("op_movbe_load16_disp", 16, 3, "rcx"), + ("op_movbe_load32", 32, 0, "rcx"), + ("op_movbe_load32_disp", 32, 5, "rdx"), + ("op_movbe_load64", 64, 0, "rcx"), + ("op_movbe_load64_disp", 64, 8, "rdx"), + ) + for name, width, disp, reg in load_specs: + fn = fns[name] + for blk in mem_blocks: + for r in regs: + buf, ptr, off, ln = alloc_guarded(blk) + got = fn(ptr, r, 0) if reg == "rcx" else fn(r, ptr, 0) + read_guarded(buf, off, ln, name) + want = ref_movbe_load(blk, disp, width, r) + if got != want: + raise AssertionError(f"{label} {name}: got={got:#x} != exp={want:#x}") + total += 1 + + # 2) Store forms strictly to [r8] / [r8+disp]. + store_specs = ( + ("op_movbe_store16", 16, 0), + ("op_movbe_store16_disp", 16, 2), + ("op_movbe_store32", 32, 0), + ("op_movbe_store32_disp", 32, 4), + ("op_movbe_store64", 64, 0), + ("op_movbe_store64_disp", 64, 8), + ) + for name, width, disp in store_specs: + fn = fns[name] + nbytes = width // 8 + for r in regs: + fill = b"\x5a" * 32 + bo, po, oo, lo = alloc_guarded(fill) + got_rax = fn(0, r, po) + out_mem = read_guarded(bo, oo, lo, name) + want_rax = (r & MASK32) if width == 32 else r + want_bytes = ref_movbe_store(r, width) + expected_buf = fill[:disp] + want_bytes + fill[disp + nbytes:] + if got_rax != want_rax or out_mem != expected_buf: + raise AssertionError(f"{label} {name}({r:#x}): rax={got_rax:#x}/{want_rax:#x} mem={out_mem.hex()}") + total += 1 + + # 3) Flag preservation checks (CF, ZF, SF, OF, PF untouched by MOVBE). + flag_specs = ( + ("op_movbe_flags_cf_zf_of_pf", 32, 0, (1 << 0) | (1 << 1) | (1 << 3) | (1 << 4)), + ("op_movbe_flags_sf_of_pf", 64, 8, (1 << 2) | (1 << 3) | (1 << 4)), + ("op_movbe_flags_all_clear", 16, 0, 0), + ) + for name, width, disp, want_flags in flag_specs: + fn = fns[name] + nbytes = width // 8 + for blk in mem_blocks[:5]: + ba, pa, oa, la = alloc_guarded(blk) + bo, po, oo, lo = alloc_guarded(b"\x5a" * 24) + got_rax = fn(pa, 0, po) + read_guarded(ba, oa, la, f"{name}_in") + out_mem = read_guarded(bo, oo, lo, f"{name}_out") + got_flags = struct.unpack_from("<I", out_mem, 16)[0] + want_rax = ref_movbe_load(blk, 0, width, MASK64) + if got_rax != want_rax or got_flags != want_flags or out_mem[disp:disp + nbytes] != blk[:nbytes]: + raise AssertionError( + f"{label} {name}: rax={got_rax:#x}/{want_rax:#x} flags={got_flags:#x}/{want_flags:#x}" + ) + total += 1 + + # 4) [r8] source-then-store. + for i in range(len(mem_blocks) - 1): + a = mem_blocks[i] + b = mem_blocks[i + 1] + c = mem_blocks[(i + 2) % len(mem_blocks)] + ba, pa, oa, la = alloc_guarded(a) + bb, pb, ob, lb = alloc_guarded(b) + br, pr, or_, lr = alloc_guarded(c) + got_rax = fns["op_r8_source_then_store"](pa, pb, pr) + read_guarded(ba, oa, la, "r8_src_a") + read_guarded(bb, ob, lb, "r8_src_b") + out_r8 = read_guarded(br, or_, lr, "r8_src_out") + want_rax = ref_movbe_load(b, 0, 16, pb) + if got_rax != want_rax or out_r8[0:4] != a[0:4] or out_r8[8:16] != c[0:8]: + raise AssertionError(f"{label} op_r8_source_then_store mismatch") + total += 1 + + # 5) Discarded faulting m64 read must fault on NULL rdx even under /O2. + bd, pd, od, ld = alloc_guarded(mem_blocks[0]) + assert fns["op_movbe_discarded_read"](0xCAFEBABE, pd, 0) == 0xCAFEBABE + read_guarded(bd, od, ld, "discarded_valid") + try: + fns["op_movbe_discarded_read"](0xCAFEBABE, 0, 0) + except OSError as exc: + if "access violation reading" not in str(exc).lower(): + raise AssertionError(f"{label} discarded_read(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{label} op_movbe_discarded_read(NULL) dropped faulting m64 read") + + return total + + +def _altered_load_expected(name, blk, r): + if name == "op_movbe_load16": + return ref_movbe_load(blk, 0, 16, r, quirk="noswap") + if name == "op_movbe_load16_disp": + return ref_movbe_load(blk, 1, 16, r) + if name == "op_movbe_load32": + return ref_movbe_load(blk, 0, 32, r, quirk="noswap") + if name == "op_movbe_load32_disp": + return ref_movbe_load(blk, 1, 32, r) + if name == "op_movbe_load64": + return ref_movbe_load(blk, 0, 64, r, quirk="noswap") + if name == "op_movbe_load64_disp": + return ref_movbe_load(blk, 4, 64, r) + raise KeyError(name) + + +def check_altered_and_mutants(lifted_fns, alt_lifted_fns, mem_blocks, regs): + diverged = 0 + for name in ALTERED_EXPORTS: + diffs = 0 + if "load" in name: + is_rdx = name in ("op_movbe_load32_disp", "op_movbe_load64_disp") + for blk in mem_blocks[:4]: + for r in regs[:4]: + buf, ptr, off, ln = alloc_guarded(blk) + got_al = alt_lifted_fns[name](r if is_rdx else ptr, ptr if is_rdx else r, 0) + got_ol = lifted_fns[name](r if is_rdx else ptr, ptr if is_rdx else r, 0) + read_guarded(buf, off, ln, name) + want_alt = _altered_load_expected(name, blk, r) + if got_al != want_alt: + raise AssertionError(f"altered_lifted {name}: {got_al:#x} != {want_alt:#x}") + diffs += got_al != got_ol + else: + width = 16 if "16" in name else (32 if "32" in name else 64) + disp = {"op_movbe_store16": 0, "op_movbe_store16_disp": 4, + "op_movbe_store32": 0, "op_movbe_store32_disp": 8, + "op_movbe_store64": 0, "op_movbe_store64_disp": 16}[name] + quirk = None if "disp" in name else "noswap" + for r in regs[:6]: + fill = b"\x5a" * 32 + bo_a, po_a, oo_a, lo_a = alloc_guarded(fill) + bo_o, po_o, oo_o, lo_o = alloc_guarded(fill) + alt_lifted_fns[name](0, r, po_a) + lifted_fns[name](0, r, po_o) + mem_a = read_guarded(bo_a, oo_a, lo_a, f"alt_{name}") + mem_o = read_guarded(bo_o, oo_o, lo_o, f"orig_{name}") + want_bytes = ref_movbe_store(r, width, quirk=quirk) + expected = fill[:disp] + want_bytes + fill[disp + width // 8:] + if mem_a != expected: + raise AssertionError(f"altered_lifted {name}: {mem_a.hex()} != {expected.hex()}") + diffs += mem_a != mem_o + if not diffs: + raise AssertionError(f"ALTER_MOVBE failed to diverge on {name}") + diverged += 1 + + # Mutant models (noswap, clear16, drop_zext32, clobber_flags). + mutants = 0 + blk0 = mem_blocks[0] + ba, pa, oa, la = alloc_guarded(blk0) + assert lifted_fns["op_movbe_load16"](pa, 0xDEADBEEF12345678, 0) != ref_movbe_load(blk0, 0, 16, 0xDEADBEEF12345678, quirk="noswap") + mutants += 1 + assert lifted_fns["op_movbe_load16"](pa, 0xDEADBEEF12345678, 0) != ref_movbe_load(blk0, 0, 16, 0xDEADBEEF12345678, quirk="clear16") + mutants += 1 + assert lifted_fns["op_movbe_load32"](pa, 0, 0) != ref_movbe_load(blk0, 0, 32, 0, quirk="no_zext32") + mutants += 1 + bo, po, oo, lo = alloc_guarded(b"\x5a" * 24) + lifted_fns["op_movbe_flags_cf_zf_of_pf"](pa, 0, po) + got_flags = struct.unpack_from("<I", read_guarded(bo, oo, lo, "mut_flags"), 16)[0] + if got_flags == 0: + raise AssertionError("mutant clobber_flags survived") + mutants += 1 + + return diverged, mutants + + +def compile_o2_and_verify(original_path, cxx_path, mem_blocks, regs): + source_text, _ = translate(original_path, list(EXPORTS)) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "movbe_aot_o2.cpp" + dll_path = tmp / "movbe_aot_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'movbe_aot_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_suite(o2_fns, "lifted_o2", mem_blocks, regs) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + + # 1) Lift + rejections + portable lifted + mutants + /O2 run unconditionally BEFORE CPUID skip. + check_rejections(original_path) + + mem_blocks, regs = test_inputs() + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_suite(lifted_fns, "lifted", mem_blocks, regs) + diverged, mutants = check_altered_and_mutants(lifted_fns, alt_lifted_fns, mem_blocks, regs) + o2_cases = compile_o2_and_verify(original_path, cxx_path, mem_blocks, regs) + + if not host_has_movbe(lifted_lib): + print( + f"portable lifted passed ({lifted_cases} lifted + {o2_cases} /O2 cases, " + f"{diverged} ALTER_MOVBE + {mutants} mutants); " + "Host lacks CPUID.01H:ECX[22] (MOVBE), skipping native differential check" + ) + sys.exit(77) + + # 2) Native MOVBE hardware differential checks. + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + try: + native_cases = verify_suite(orig_fns, "native", mem_blocks, regs) + for name in ALTERED_EXPORTS: + if "load" in name: + is_rdx = name in ("op_movbe_load32_disp", "op_movbe_load64_disp") + for blk in mem_blocks[:4]: + for r in regs[:4]: + buf, ptr, off, ln = alloc_guarded(blk) + got_an = alt_fns[name](r if is_rdx else ptr, ptr if is_rdx else r, 0) + got_al = alt_lifted_fns[name](r if is_rdx else ptr, ptr if is_rdx else r, 0) + read_guarded(buf, off, ln, f"alt_nat_{name}") + if got_an != got_al: + raise AssertionError(f"altered native vs lifted {name}: {got_an:#x} != {got_al:#x}") + else: + for r in regs[:4]: + bn, pn, on, ln = alloc_guarded(b"\x5a" * 32) + bl, pl, ol, ll = alloc_guarded(b"\x5a" * 32) + alt_fns[name](0, r, pn) + alt_lifted_fns[name](0, r, pl) + if read_guarded(bn, on, ln, f"alt_nat_{name}") != read_guarded(bl, ol, ll, f"alt_lift_{name}"): + raise AssertionError(f"altered native vs lifted store {name}") + finally: + orig_fns.clear() + alt_fns.clear() + unload_lib(orig_lib) + unload_lib(alt_lib) + finally: + lifted_fns.clear() + alt_lifted_fns.clear() + unload_lib(lifted_lib) + unload_lib(alt_lifted_lib) + + record_covered_forms(original_path) + print( + f"movbe_aot passed: {native_cases} native + {lifted_cases} lifted + {o2_cases} /O2 cases " + f"across {len(EXPORTS)} exports; ALTER_MOVBE diverged on {diverged} exports + {mutants} mutants caught" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/nt_store_check.py b/tests/cpu/nt_store_check.py new file mode 100644 index 0000000000..72c8cb077e --- /dev/null +++ b/tests/cpu/nt_store_check.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Control for the legacy non-temporal stores in the shared lowering (tools/ffx_version_query.py). + +MOVNTPS, MOVNTPD and MOVNTDQ (`0F 2B /r`, `66 0F 2B /r`, `66 0F E7 /r`) store a whole XMM register; like +MOVAPS they raise #GP(0) when the target is not 16-byte aligned. MOVNTI (`0F C3 /r`) stores a 32- or 64-bit +register with no alignment requirement. None of them changes a flag. The non-temporal hint and the weak +ordering of the store are kept by lowering each one to the matching streaming-store intrinsic. + +What is checked, all on exact byte patterns: + + accepted - the encoding lowers to the streaming intrinsic of its width. The XMM forms test the target + against 15 and raise the aligned-operand fault before the store; MOVNTI does not. + refused - the neighbours that are not part of this slice stay refused: an XMM register above XMM2 (the + register set MOVAPS has here), the MMX MOVNTQ, the SSE4a scalar MOVNTSS and MOVNTSD, the VEX + VMOVNTPS/VMOVNTPD/VMOVNTDQ, and the MOVNTDQA load. A widened accepted set would show up here. + +The native-versus-lifted comparison is tests/cpu/nt_store_fixture.py. +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from iced_x86 import Decoder +from ffx_version_query import lower + +ALIGN = "if (target & 15u) raise_aligned_m128_fault();" + +# encoding -> (description, intrinsic the body must call, whether the body checks 16-byte alignment) +ACCEPTED = { + "0f2b01": ("movntps [rcx], xmm0", "_mm_stream_si128", True), + "660f2b01": ("movntpd [rcx], xmm0", "_mm_stream_si128", True), + "660fe701": ("movntdq [rcx], xmm0", "_mm_stream_si128", True), + "0f2b5110": ("movntps [rcx+16], xmm2", "_mm_stream_si128", True), + "660fe70424": ("movntdq [rsp], xmm0", "_mm_stream_si128", True), + "0fc301": ("movnti [rcx], eax", "_mm_stream_si32", False), + "480fc301": ("movnti [rcx], rax", "_mm_stream_si64", False), + "4c0fc34103": ("movnti [rcx+3], r8", "_mm_stream_si64", False), +} + +REFUSED = { + "0f2b19": "movntps [rcx], xmm3 (the shared lowering models XMM0-XMM2, as for MOVAPS)", + "0fe701": "movntq [rcx], mm0 (MMX)", + "f30f2b01": "movntss [rcx], xmm0 (SSE4a)", + "f20f2b01": "movntsd [rcx], xmm0 (SSE4a)", + "c5f82b01": "vmovntps [rcx], xmm0 (VEX)", + "c5f92b01": "vmovntpd [rcx], xmm0 (VEX)", + "c5f9e701": "vmovntdq [rcx], xmm0 (VEX)", + "660f382a01": "movntdqa xmm0, [rcx] (non-temporal load)", +} + + +def body(hex_bytes: str) -> str: + return lower(list(Decoder(64, bytes.fromhex(hex_bytes + "c3"))), [], {}, {}, {}) + + +def main() -> int: + failures = [] + + def check(label, condition, detail=""): + print(f"{label}: {'ok' if condition else 'MISMATCH'}{(' (' + detail + ')') if detail and not condition else ''}") + if not condition: + failures.append(label) + + for encoding, (description, intrinsic, aligned) in ACCEPTED.items(): + try: + lifted = body(encoding) + except ValueError as error: + check(f"accepted {encoding} ({description})", False, str(error)) + continue + check(f"accepted {encoding} ({description})", True) + check(f" {encoding} stores with {intrinsic}", lifted.count(intrinsic + "(") == 1) + check(f" {encoding} {'checks' if aligned else 'does not check'} 16-byte alignment", + (ALIGN in lifted) == aligned) + if aligned: + check(f" {encoding} raises the fault before the store", lifted.find(ALIGN) < lifted.find(intrinsic)) + + for encoding, description in REFUSED.items(): + try: + body(encoding) + except ValueError: + check(f"refused {encoding} ({description})", True) + continue + check(f"refused {encoding} ({description})", False, "lowering accepted it") + + if failures: + print(f"FAIL: {len(failures)} case(s)") + return 1 + print(f"PASS: {len(ACCEPTED)} non-temporal stores lowered, {len(REFUSED)} neighbours still refused") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/cpu/nt_store_fixture.py b/tests/cpu/nt_store_fixture.py new file mode 100644 index 0000000000..463713f78d --- /dev/null +++ b/tests/cpu/nt_store_fixture.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Emit the non-temporal store differential fixture (MOVNTPS, MOVNTPD, MOVNTDQ, MOVNTI). + +For the same inputs, compare what the host executes for each store against what the shared lowering +(tools/ffx_version_query.lower()) produces for it: + + native - the exact bytes in an executable section, called directly. + lifted - the same instructions lowered to C++ and compiled alongside. + +Each case is called as f(target, source, value). The XMM cases load XMM0 or XMM2 from `source` with MOVDQU +and store it to `target`; the MOVNTI cases store the low 32 or 64 bits of `value`. Every case ends with SFENCE +and returns RAX. The native and lifted calls write into two separate 64-byte buffers that start filled with a +sentinel, so the check compares the whole buffer, not only the stored bytes, and an independent reference +(the source bytes or the value at the target offset, the sentinel elsewhere) is checked as well. + +The fault cases run under a guard that records the exception code and its two parameters: + - an XMM store to a target that is not 16-byte aligned raises #GP(0), which Windows reports as an access + violation at address -1; nothing may be written; + - a store to a PAGE_NOACCESS page raises an access violation for a write at that address; + - MOVNTI to an odd address is not a fault. + +Controls that must break a rule, so the cases above are informative: + - `noalign`: the lifted MOVNTPS with its alignment test removed and a plain store in place of the streaming + one must store where the native one faults (the streaming intrinsic is MOVNTDQ and faults by itself); + - `nostore`: the native bytes with the store replaced by a NOP must leave the reference unmatched; + - a plain MOVUPS to the same misaligned target must not fault natively, so the fault above comes from the + alignment rule and not from the mapping. + +usage: nt_store_fixture.py emit <output.cpp> +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from iced_x86 import Decoder +from ffx_version_query import INTEGER_HEADER, lower + +LOAD_XMM0 = bytes.fromhex("f30f6f02") # movdqu xmm0, [rdx] +LOAD_XMM2 = bytes.fromhex("f30f6f12") # movdqu xmm2, [rdx] +VALUE_RAX = bytes.fromhex("4c89c0") # mov rax, r8 +EPILOGUE = bytes.fromhex("0faef8c3") # sfence ; ret +ALIGN = "if (target & 15u) raise_aligned_m128_fault();" + +PAGE = "page" # the target is the PAGE_NOACCESS page + +# (name, description, prologue, store bytes, offset of RCX in the 64-byte buffer or PAGE, stored width, +# expected fault: None, "gp" (aligned-operand #GP) or "write"[, displacement of the store from RCX]) +CASES = [ + ("nt_movntps", "movntps [rcx], xmm0", LOAD_XMM0, bytes.fromhex("0f2b01"), 16, 16, None), + ("nt_movntpd", "movntpd [rcx], xmm0", LOAD_XMM0, bytes.fromhex("660f2b01"), 32, 16, None), + ("nt_movntdq", "movntdq [rcx], xmm0", LOAD_XMM0, bytes.fromhex("660fe701"), 0, 16, None), + ("nt_movntps_disp", "movntps [rcx+16], xmm2", LOAD_XMM2, bytes.fromhex("0f2b5110"), 0, 16, None, 16), + ("nt_movnti32", "movnti [rcx], eax", VALUE_RAX, bytes.fromhex("0fc301"), 8, 4, None), + ("nt_movnti64", "movnti [rcx], rax", VALUE_RAX, bytes.fromhex("480fc301"), 24, 8, None), + ("nt_movnti32_odd", "movnti [rcx], eax at an odd address", VALUE_RAX, bytes.fromhex("0fc301"), 3, 4, None), + ("nt_movnti64_odd", "movnti [rcx], rax at an odd address", VALUE_RAX, bytes.fromhex("480fc301"), 41, 8, None), + ("nt_movntps_misaligned", "movntps [rcx], xmm0 at +8", LOAD_XMM0, bytes.fromhex("0f2b01"), 8, 16, "gp"), + ("nt_movntpd_misaligned", "movntpd [rcx], xmm0 at +4", LOAD_XMM0, bytes.fromhex("660f2b01"), 4, 16, "gp"), + ("nt_movntdq_misaligned", "movntdq [rcx], xmm0 at +1", LOAD_XMM0, bytes.fromhex("660fe701"), 1, 16, "gp"), + ("nt_movntps_noaccess", "movntps to PAGE_NOACCESS", LOAD_XMM0, bytes.fromhex("0f2b01"), PAGE, 16, "write"), + ("nt_movntdq_noaccess", "movntdq to PAGE_NOACCESS", LOAD_XMM0, bytes.fromhex("660fe701"), PAGE, 16, "write"), + ("nt_movnti64_noaccess", "movnti [rcx], rax to PAGE_NOACCESS", VALUE_RAX, bytes.fromhex("480fc301"), PAGE, 8, + "write"), +] + +TEST_MAIN = r""" +using Fn = word (*)(word, word, word); + +enum Expect { NONE, GP, WRITE }; + +struct Case { + const char* name; + const char* description; + const unsigned char* native_bytes; + Fn lifted; + int offset; // of RCX in the buffer; -1: the PAGE_NOACCESS page + int disp; // of the store from RCX + int width; + Expect expect; +}; + +struct Fault { + unsigned long code = 0; + unsigned long long info0 = 0, info1 = 0; + bool raised = false; +}; + +static int capture(EXCEPTION_POINTERS* pointers, Fault* fault) +{ + const EXCEPTION_RECORD* record = pointers->ExceptionRecord; + fault->raised = true; + fault->code = record->ExceptionCode; + fault->info0 = record->NumberParameters > 0 ? record->ExceptionInformation[0] : ~0ull; + fault->info1 = record->NumberParameters > 1 ? record->ExceptionInformation[1] : ~0ull; + return EXCEPTION_EXECUTE_HANDLER; +} + +static Fault call(Fn fn, word target, word source, word value) +{ + Fault fault; + __try { + (void)fn(target, source, value); + } __except (capture(GetExceptionInformation(), &fault)) { + } + return fault; +} + +static const Case cases[] = { +/*CASES*/ +}; + +static const unsigned char SENTINEL = 0xA5; +static const unsigned long long VALUE = 0x0123456789ABCDEFull; + +int main() +{ + // Page 0: the two 64-byte buffers (native at 0, lifted at 128) and the 16 source bytes at 256. + // Page 1: PAGE_NOACCESS. + unsigned char* base = + static_cast<unsigned char*>(VirtualAlloc(nullptr, 8192, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + DWORD old = 0; + if (!base || !VirtualProtect(base + 4096, 4096, PAGE_NOACCESS, &old)) { + std::printf("skip: VirtualAlloc/VirtualProtect failed\n"); + return 77; + } + unsigned char* native_buf = base; + unsigned char* lifted_buf = base + 128; + unsigned char* source = base + 256; + unsigned char* page = base + 4096; + for (int k = 0; k < 16; ++k) source[k] = static_cast<unsigned char>(0x10 + 7 * k); + + int failures = 0; + for (const Case& test : cases) { + memset(native_buf, SENTINEL, 64); + memset(lifted_buf, SENTINEL, 64); + const Fn native = reinterpret_cast<Fn>(const_cast<unsigned char*>(test.native_bytes)); + const word native_target = reinterpret_cast<word>(test.offset < 0 ? page : native_buf + test.offset); + const word lifted_target = reinterpret_cast<word>(test.offset < 0 ? page : lifted_buf + test.offset); + const Fault nf = call(native, native_target, reinterpret_cast<word>(source), VALUE); + const Fault lf = call(test.lifted, lifted_target, reinterpret_cast<word>(source), VALUE); + + // The reference: the stored bytes at the offset when the case does not fault, the sentinel elsewhere. + unsigned char reference[64]; + memset(reference, SENTINEL, 64); + if (test.expect == NONE) + memcpy(reference + test.offset + test.disp, test.width == 16 ? source : reinterpret_cast<const unsigned char*>(&VALUE), + test.width); + bool expected_fault = false; + if (test.expect == NONE) expected_fault = !nf.raised; + if (test.expect == GP) + expected_fault = nf.raised && nf.code == 0xC0000005ul && nf.info0 == 0 && nf.info1 == ~0ull; + if (test.expect == WRITE) + expected_fault = nf.raised && nf.code == 0xC0000005ul && nf.info0 == 1 && + nf.info1 >= reinterpret_cast<word>(page) && nf.info1 < reinterpret_cast<word>(page) + 16; + const bool same_fault = nf.raised == lf.raised && nf.code == lf.code && nf.info0 == lf.info0 && + (test.expect == WRITE ? lf.info1 == nf.info1 : lf.info1 == nf.info1); + const bool native_ref = memcmp(native_buf, reference, 64) == 0; + const bool lifted_ref = memcmp(lifted_buf, reference, 64) == 0; + const bool ok = expected_fault && same_fault && native_ref && lifted_ref; + std::printf("%s (%s): native fault=%d code=0x%08lx info=%llu,0x%llx lifted fault=%d code=0x%08lx " + "info=%llu,0x%llx buffers native=%s lifted=%s %s\n", + test.name, test.description, nf.raised ? 1 : 0, nf.code, nf.info0, nf.info1, lf.raised ? 1 : 0, + lf.code, lf.info0, lf.info1, native_ref ? "ref" : "DIFF", lifted_ref ? "ref" : "DIFF", + ok ? "ok" : "MISMATCH"); + if (!ok) ++failures; + } + + // Control `noalign`: without its alignment test the lifted MOVNTPS stores at +8, where the native one faults. + { + memset(lifted_buf, SENTINEL, 64); + const Fault f = call(lifted_control_noalign, reinterpret_cast<word>(lifted_buf + 8), + reinterpret_cast<word>(source), VALUE); + const bool broke = !f.raised && memcmp(lifted_buf + 8, source, 16) == 0; + std::printf("control noalign: fault=%d %s\n", f.raised ? 1 : 0, + broke ? "ok (differs from native)" : "MISMATCH (the misaligned cases do not test the check)"); + if (!broke) ++failures; + } + // Control `nostore`: with the store replaced by a NOP the reference must not match. + { + memset(native_buf, SENTINEL, 64); + const Fault f = call(reinterpret_cast<Fn>(const_cast<unsigned char*>(nat_control_nostore)), + reinterpret_cast<word>(native_buf + 16), reinterpret_cast<word>(source), VALUE); + const bool broke = !f.raised && memcmp(native_buf + 16, source, 16) != 0; + std::printf("control nostore: %s\n", broke ? "ok (reference unmatched)" : "MISMATCH (reference cannot see a store)"); + if (!broke) ++failures; + } + // Control: a plain MOVUPS to the same misaligned target does not fault. + { + memset(native_buf, SENTINEL, 64); + const Fault f = call(reinterpret_cast<Fn>(const_cast<unsigned char*>(nat_control_movups)), + reinterpret_cast<word>(native_buf + 8), reinterpret_cast<word>(source), VALUE); + const bool ok = !f.raised && memcmp(native_buf + 8, source, 16) == 0; + std::printf("control movups at +8: fault=%d %s\n", f.raised ? 1 : 0, ok ? "ok" : "MISMATCH"); + if (!ok) ++failures; + } + + if (failures) { + std::printf("FAIL: %d case(s)\n", failures); + return 1; + } + std::printf("PASS: every non-temporal store matched native, including the alignment and access faults\n"); + return 0; +} +""" + + +def lifted(name: str, code: bytes, mutate=None) -> str: + text = lower(list(Decoder(64, code)), ["rcx = a; rdx = b; r8 = c;"], {}, {}, {}) + if mutate: + text = mutate(text) + return f'extern "C" __declspec(dllexport) word lifted_{name}(word a, word b, word c) {{\n{text}\n}}' + + +def native(name: str, code: bytes) -> str: + emitted = ", ".join("0x%02x" % byte for byte in code) + return f'#pragma section(".text")\n__declspec(allocate(".text")) const unsigned char nat_{name}[] = {{{emitted}}};' + + +def main() -> int: + if len(sys.argv) != 3 or sys.argv[1] != "emit": + print(__doc__) + return 2 + output = Path(sys.argv[2]) + + parts = [INTEGER_HEADER, "#include <windows.h>\n#include <cstdio>\n#include <cstring>\n"] + rows = [] + for name, description, prologue, store, offset, width, fault, *disp in CASES: + code = prologue + store + EPILOGUE + parts.append(native(name, code)) + parts.append(lifted(name, code)) + expect = {None: "NONE", "gp": "GP", "write": "WRITE"}[fault] + rows.append(f' {{"{name}", "{description}", nat_{name}, lifted_{name}, ' + f'{-1 if offset == PAGE else offset}, {disp[0] if disp else 0}, {width}, {expect}}},') + + movntps = LOAD_XMM0 + bytes.fromhex("0f2b01") + EPILOGUE + + def drop_align(text: str) -> str: + # The streaming intrinsic compiles to MOVNTDQ, which faults on its own, so the control also turns it + # into a plain store: a lowering that ignores the alignment rule. + stream = "_mm_stream_si128(reinterpret_cast<__m128i*>(target), value);" + if text.count(ALIGN) != 1 or text.count(stream) != 1: + raise SystemExit("noalign control: the lifted MOVNTPS has no single alignment test and store to replace") + return text.replace(ALIGN, "").replace(stream, "memcpy(reinterpret_cast<void*>(target), &value, 16);") + + parts.append(lifted("control_noalign", movntps, drop_align)) + parts.append(native("control_nostore", LOAD_XMM0 + bytes.fromhex("0f1f00") + EPILOGUE)) # nop dword [rax] + parts.append(native("control_movups", LOAD_XMM0 + bytes.fromhex("0f1101") + EPILOGUE)) # movups [rcx], xmm0 + parts.append(TEST_MAIN.replace("/*CASES*/", "\n".join(rows))) + output.write_text("\n".join(parts) + "\n", encoding="utf-8") + print(f"emitted {len(CASES)} non-temporal store cases into {output}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/cpu/sse41_fp_aot.asm b/tests/cpu/sse41_fp_aot.asm new file mode 100644 index 0000000000..02d7d0f215 --- /dev/null +++ b/tests/cpu/sse41_fp_aot.asm @@ -0,0 +1,527 @@ +; coverage: record cpu_aot_sse41_fp +; Source-owned MASM fixture for legacy SSE4.1 floating-point instructions +; (roundps, roundpd, roundss, roundsd, dpps, dppd, insertps, extractps) +; across register and flat [rcx|rdx|r8] memory-source forms plus glue moves. +; ABI: void fn(const void* rcx, const void* rdx, void* r8). +.code + +; --- ROUNDPS (reg imm 0,1,2,3,4,8 & flat [rcx|rdx|r8] mem) --- +op_roundps_reg_0 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 00h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_0 ENDP + +op_roundps_reg_1 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] +IFDEF ALTER_SSE41_FP + roundps xmm0, xmm1, 02h +ELSE + roundps xmm0, xmm1, 01h +ENDIF + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_1 ENDP + +op_roundps_reg_2 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 02h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_2 ENDP + +op_roundps_reg_3 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 03h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_3 ENDP + +op_roundps_reg_4 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 04h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_4 ENDP + +op_roundps_reg_8 PROC FRAME + .endprolog + movaps xmm1, XMMWORD PTR [rcx] + roundps xmm0, xmm1, 08h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_reg_8 ENDP + +op_roundps_mem_rcx PROC FRAME + .endprolog + roundps xmm0, XMMWORD PTR [rcx], 01h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_mem_rcx ENDP + +op_roundps_mem_rdx PROC FRAME + .endprolog + roundps xmm0, XMMWORD PTR [rdx], 02h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_mem_rdx ENDP + +op_roundps_mem_r8 PROC FRAME + .endprolog + roundps xmm0, XMMWORD PTR [r8], 03h + movaps XMMWORD PTR [r8], xmm0 + ret +op_roundps_mem_r8 ENDP + +; --- ROUNDPD (reg imm 0,1,2,3,4 & flat [rcx|rdx|r8] mem) --- +op_roundpd_reg_0 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 00h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_0 ENDP + +op_roundpd_reg_1 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 01h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_1 ENDP + +op_roundpd_reg_2 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] +IFDEF ALTER_SSE41_FP + roundpd xmm0, xmm1, 01h +ELSE + roundpd xmm0, xmm1, 02h +ENDIF + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_2 ENDP + +op_roundpd_reg_3 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 03h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_3 ENDP + +op_roundpd_reg_4 PROC FRAME + .endprolog + movapd xmm1, XMMWORD PTR [rcx] + roundpd xmm0, xmm1, 04h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_reg_4 ENDP + +op_roundpd_mem_rcx PROC FRAME + .endprolog + roundpd xmm0, XMMWORD PTR [rcx], 00h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_mem_rcx ENDP + +op_roundpd_mem_rdx PROC FRAME + .endprolog + roundpd xmm0, XMMWORD PTR [rdx], 01h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_mem_rdx ENDP + +op_roundpd_mem_r8 PROC FRAME + .endprolog + roundpd xmm0, XMMWORD PTR [r8], 02h + movapd XMMWORD PTR [r8], xmm0 + ret +op_roundpd_mem_r8 ENDP + +; --- ROUNDSS (preserves dst[127:32], reg & flat [rcx|rdx|r8] m32) --- +op_roundss_reg_0 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + roundss xmm0, xmm1, 03h +ELSE + roundss xmm0, xmm1, 00h +ENDIF + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_0 ENDP + +op_roundss_reg_1 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 01h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_1 ENDP + +op_roundss_reg_2 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 02h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_2 ENDP + +op_roundss_reg_3 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 03h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_3 ENDP + +op_roundss_reg_4 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + roundss xmm0, xmm1, 04h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_reg_4 ENDP + +op_roundss_mem_rcx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rdx] + roundss xmm0, DWORD PTR [rcx], 01h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_mem_rcx ENDP + +op_roundss_mem_rdx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + roundss xmm0, DWORD PTR [rdx], 02h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_mem_rdx ENDP + +op_roundss_mem_r8 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + roundss xmm0, DWORD PTR [r8], 03h + movups XMMWORD PTR [r8], xmm0 + ret +op_roundss_mem_r8 ENDP + +; --- ROUNDSD (preserves dst[127:64], reg & flat [rcx|rdx|r8] m64) --- +op_roundsd_reg_0 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 00h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_0 ENDP + +op_roundsd_reg_1 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 01h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_1 ENDP + +op_roundsd_reg_2 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 02h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_2 ENDP + +op_roundsd_reg_3 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + roundsd xmm0, xmm1, 02h +ELSE + roundsd xmm0, xmm1, 03h +ENDIF + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_3 ENDP + +op_roundsd_reg_4 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + movupd xmm1, XMMWORD PTR [rdx] + roundsd xmm0, xmm1, 04h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_reg_4 ENDP + +op_roundsd_mem_rcx PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rdx] + roundsd xmm0, QWORD PTR [rcx], 01h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_mem_rcx ENDP + +op_roundsd_mem_rdx PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + roundsd xmm0, QWORD PTR [rdx], 02h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_mem_rdx ENDP + +op_roundsd_mem_r8 PROC FRAME + .endprolog + movupd xmm0, XMMWORD PTR [rcx] + roundsd xmm0, QWORD PTR [r8], 03h + movupd XMMWORD PTR [r8], xmm0 + ret +op_roundsd_mem_r8 ENDP + +; --- DPPS (reg & flat [rcx|rdx|r8] mem) --- +op_dpps_reg_f1 PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + dpps xmm0, xmm1, 0F1h + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_f1 ENDP + +op_dpps_reg_ff PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + dpps xmm0, xmm1, 055h +ELSE + dpps xmm0, xmm1, 0FFh +ENDIF + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_ff ENDP + +op_dpps_reg_5a PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + dpps xmm0, xmm1, 05Ah + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_5a ENDP + +op_dpps_reg_0f PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + movaps xmm1, XMMWORD PTR [rdx] + dpps xmm0, xmm1, 00Fh + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_reg_0f ENDP + +op_dpps_mem_rcx PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rdx] + dpps xmm0, XMMWORD PTR [rcx], 0F3h + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_mem_rcx ENDP + +op_dpps_mem_rdx PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + dpps xmm0, XMMWORD PTR [rdx], 0C5h + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_mem_rdx ENDP + +op_dpps_mem_r8 PROC FRAME + .endprolog + movaps xmm0, XMMWORD PTR [rcx] + dpps xmm0, XMMWORD PTR [r8], 0AAh + movaps XMMWORD PTR [r8], xmm0 + ret +op_dpps_mem_r8 ENDP + +; --- DPPD (reg & flat [rcx|rdx|r8] mem) --- +op_dppd_reg_33 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + dppd xmm0, xmm1, 011h +ELSE + dppd xmm0, xmm1, 033h +ENDIF + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_33 ENDP + +op_dppd_reg_11 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] + dppd xmm0, xmm1, 011h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_11 ENDP + +op_dppd_reg_22 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] + dppd xmm0, xmm1, 022h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_22 ENDP + +op_dppd_reg_03 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + movapd xmm1, XMMWORD PTR [rdx] + dppd xmm0, xmm1, 003h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_reg_03 ENDP + +op_dppd_mem_rcx PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rdx] + dppd xmm0, XMMWORD PTR [rcx], 031h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_mem_rcx ENDP + +op_dppd_mem_rdx PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + dppd xmm0, XMMWORD PTR [rdx], 032h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_mem_rdx ENDP + +op_dppd_mem_r8 PROC FRAME + .endprolog + movapd xmm0, XMMWORD PTR [rcx] + dppd xmm0, XMMWORD PTR [r8], 023h + movapd XMMWORD PTR [r8], xmm0 + ret +op_dppd_mem_r8 ENDP + +; --- INSERTPS (reg count_s/count_d/zmask & flat [rcx|rdx|r8] m32) --- +op_insertps_reg_s1_d2_z5 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + insertps xmm0, xmm1, 060h +ELSE + insertps xmm0, xmm1, 065h +ENDIF + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_reg_s1_d2_z5 ENDP + +op_insertps_reg_s3_d0_z0 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + insertps xmm0, xmm1, 0C0h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_reg_s3_d0_z0 ENDP + +op_insertps_reg_s0_d3_z8 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + movups xmm1, XMMWORD PTR [rdx] + insertps xmm0, xmm1, 038h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_reg_s0_d3_z8 ENDP + +op_insertps_mem_rcx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rdx] + insertps xmm0, DWORD PTR [rcx], 0D2h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_mem_rcx ENDP + +op_insertps_mem_rdx PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + insertps xmm0, DWORD PTR [rdx], 0E4h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_mem_rdx ENDP + +op_insertps_mem_r8 PROC FRAME + .endprolog + movups xmm0, XMMWORD PTR [rcx] + insertps xmm0, DWORD PTR [r8], 091h + movups XMMWORD PTR [r8], xmm0 + ret +op_insertps_mem_r8 ENDP + +; --- EXTRACTPS (r32 zero-extend, r64 zero-extend, and m32 [r8]) --- +op_extractps_r32_lane2 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + mov rax, QWORD PTR [rdx] +IFDEF ALTER_SSE41_FP + extractps eax, xmm0, 01h +ELSE + extractps eax, xmm0, 02h +ENDIF + mov QWORD PTR [r8], rax + ret +op_extractps_r32_lane2 ENDP + +op_extractps_r64_lane3 PROC FRAME + .endprolog + movdqa xmm0, XMMWORD PTR [rcx] + mov r9, QWORD PTR [rdx] + db 66h, 49h, 0Fh, 3Ah, 17h, 0C1h, 03h ; extractps r9, xmm0, 03h (REX.W) + mov QWORD PTR [r8], r9 + ret +op_extractps_r64_lane3 ENDP + +op_extractps_mem_lane1 PROC FRAME + .endprolog + movdqu xmm0, XMMWORD PTR [rcx] + extractps DWORD PTR [r8], xmm0, 01h + ret +op_extractps_mem_lane1 ENDP + +; --- Glue transport pipeline --- +op_sse41_glue_pipeline PROC FRAME + .endprolog + movss xmm0, DWORD PTR [rcx] + movsd xmm1, QWORD PTR [rdx] + movdqa xmm2, XMMWORD PTR [rcx] + movdqu xmm3, XMMWORD PTR [rdx] + movss xmm2, xmm1 + movsd xmm3, xmm0 + roundps xmm4, xmm2, 01h + insertps xmm4, xmm3, 052h + movupd XMMWORD PTR [r8], xmm4 + ret +op_sse41_glue_pipeline ENDP + +END diff --git a/tests/cpu/sse41_fp_aot.def b/tests/cpu/sse41_fp_aot.def new file mode 100644 index 0000000000..0a8c0d6743 --- /dev/null +++ b/tests/cpu/sse41_fp_aot.def @@ -0,0 +1,58 @@ +EXPORTS + op_roundps_reg_0 + op_roundps_reg_1 + op_roundps_reg_2 + op_roundps_reg_3 + op_roundps_reg_4 + op_roundps_reg_8 + op_roundps_mem_rcx + op_roundps_mem_rdx + op_roundps_mem_r8 + op_roundpd_reg_0 + op_roundpd_reg_1 + op_roundpd_reg_2 + op_roundpd_reg_3 + op_roundpd_reg_4 + op_roundpd_mem_rcx + op_roundpd_mem_rdx + op_roundpd_mem_r8 + op_roundss_reg_0 + op_roundss_reg_1 + op_roundss_reg_2 + op_roundss_reg_3 + op_roundss_reg_4 + op_roundss_mem_rcx + op_roundss_mem_rdx + op_roundss_mem_r8 + op_roundsd_reg_0 + op_roundsd_reg_1 + op_roundsd_reg_2 + op_roundsd_reg_3 + op_roundsd_reg_4 + op_roundsd_mem_rcx + op_roundsd_mem_rdx + op_roundsd_mem_r8 + op_dpps_reg_f1 + op_dpps_reg_ff + op_dpps_reg_5a + op_dpps_reg_0f + op_dpps_mem_rcx + op_dpps_mem_rdx + op_dpps_mem_r8 + op_dppd_reg_33 + op_dppd_reg_11 + op_dppd_reg_22 + op_dppd_reg_03 + op_dppd_mem_rcx + op_dppd_mem_rdx + op_dppd_mem_r8 + op_insertps_reg_s1_d2_z5 + op_insertps_reg_s3_d0_z0 + op_insertps_reg_s0_d3_z8 + op_insertps_mem_rcx + op_insertps_mem_rdx + op_insertps_mem_r8 + op_extractps_r32_lane2 + op_extractps_r64_lane3 + op_extractps_mem_lane1 + op_sse41_glue_pipeline diff --git a/tests/cpu/sse41_fp_aot_check.py b/tests/cpu/sse41_fp_aot_check.py new file mode 100644 index 0000000000..4fbf408e05 --- /dev/null +++ b/tests/cpu/sse41_fp_aot_check.py @@ -0,0 +1,549 @@ +"""Differential, MXCSR, refusal, CLI, and coverage checks for legacy SSE4.1 FP AOT.""" + +import ctypes +from fractions import Fraction +import math +import os +from pathlib import Path +import struct +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Instruction, + MemoryOperand, + Mnemonic, + Register as R, +) +import pefile + +THIS_DIR = Path(__file__).resolve().parent +TOOLS_DIR = THIS_DIR.parents[1] / "tools" +sys.path.insert(0, str(THIS_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) + +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_sse41_fp_aot import lift_code, main as tool_main, translate # noqa: E402 +from sse34_fp import F32, F64, _dp_allowed, _guarded_buf, _round_nearest_even # noqa: E402 + + +EXPORTS = ( + "op_roundps_reg_0", "op_roundps_reg_1", "op_roundps_reg_2", "op_roundps_reg_3", + "op_roundps_reg_4", "op_roundps_reg_8", + "op_roundps_mem_rcx", "op_roundps_mem_rdx", "op_roundps_mem_r8", + "op_roundpd_reg_0", "op_roundpd_reg_1", "op_roundpd_reg_2", "op_roundpd_reg_3", + "op_roundpd_reg_4", + "op_roundpd_mem_rcx", "op_roundpd_mem_rdx", "op_roundpd_mem_r8", + "op_roundss_reg_0", "op_roundss_reg_1", "op_roundss_reg_2", "op_roundss_reg_3", + "op_roundss_reg_4", + "op_roundss_mem_rcx", "op_roundss_mem_rdx", "op_roundss_mem_r8", + "op_roundsd_reg_0", "op_roundsd_reg_1", "op_roundsd_reg_2", "op_roundsd_reg_3", + "op_roundsd_reg_4", + "op_roundsd_mem_rcx", "op_roundsd_mem_rdx", "op_roundsd_mem_r8", + "op_dpps_reg_f1", "op_dpps_reg_ff", "op_dpps_reg_5a", "op_dpps_reg_0f", + "op_dpps_mem_rcx", "op_dpps_mem_rdx", "op_dpps_mem_r8", + "op_dppd_reg_33", "op_dppd_reg_11", "op_dppd_reg_22", "op_dppd_reg_03", + "op_dppd_mem_rcx", "op_dppd_mem_rdx", "op_dppd_mem_r8", + "op_insertps_reg_s1_d2_z5", "op_insertps_reg_s3_d0_z0", "op_insertps_reg_s0_d3_z8", + "op_insertps_mem_rcx", "op_insertps_mem_rdx", "op_insertps_mem_r8", + "op_extractps_r32_lane2", "op_extractps_r64_lane3", "op_extractps_mem_lane1", + "op_sse41_glue_pipeline", +) + +ALTERED_EXPORTS = ( + "op_roundps_reg_1", + "op_roundpd_reg_2", + "op_roundss_reg_0", + "op_roundsd_reg_3", + "op_dpps_reg_ff", + "op_dppd_reg_33", + "op_insertps_reg_s1_d2_z5", + "op_extractps_r32_lane2", +) + +SEED = bytes(0xB0 + (i % 16) for i in range(16)) +MXCSR_MODES = (0x1F80, 0x3F80, 0x5F80, 0x7F80, 0x1FC0, 0x9F80, 0x9FC0) + + +def encode_seq(*instructions): + encoder = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += encoder.encode(ins, rip) + return encoder.take_buffer() + + +def _u32s(buf: bytes) -> tuple[int, ...]: + return struct.unpack("<4I", buf[:16]) + + +def _u64s(buf: bytes) -> tuple[int, ...]: + return struct.unpack("<2Q", buf[:16]) + + +def _p32s(vals) -> bytes: + return struct.pack("<4I", *vals) + + +def _p64s(vals) -> bytes: + return struct.pack("<2Q", *vals) + + +def _round_ref(fmt, raw: int, imm: int, mxcsr: int) -> int: + if fmt.is_nan(raw): + return fmt.quiet(raw) + if fmt.is_inf(raw) or fmt.is_zero(raw): + return raw + sa, exp, _ = fmt.unpack(raw) + daz = bool(mxcsr & 0x0040) + if daz and exp == 0: + return fmt.sign_mask if sa else 0 + mode = ((mxcsr >> 13) & 3) if (imm & 4) else (imm & 3) + f = fmt.to_fraction(raw) + if mode == 0: + n = _round_nearest_even(f) + elif mode == 1: + n = math.floor(f) + elif mode == 2: + n = math.ceil(f) + else: + n = int(f) + return fmt.from_fraction(Fraction(n, 1), zero_sign=sa) + + +def _insertps_ref(dst_bytes: bytes, src_bytes: bytes, imm: int, *, mem: bool) -> bytes: + xa = list(_u32s(dst_bytes)) + val = _u32s(src_bytes)[0 if mem else ((imm >> 6) & 3)] + xa[(imm >> 4) & 3] = val + for k in range(4): + if (imm >> k) & 1: + xa[k] = 0 + return _p32s(xa) + + +def ref_export(name: str, a: bytes, b: bytes, seed: bytes, mxcsr: int, *, altered: bool = False) -> bytes: + if name.startswith("op_roundps_"): + if name == "op_roundps_mem_rcx": + src, imm = a, 1 + elif name == "op_roundps_mem_rdx": + src, imm = b, 2 + elif name == "op_roundps_mem_r8": + src, imm = seed, 3 + else: + imm = 2 if (altered and name == "op_roundps_reg_1") else int(name.split("_")[-1]) + src = a + return _p32s(_round_ref(F32, x, imm, mxcsr) for x in _u32s(src)) + + if name.startswith("op_roundpd_"): + if name == "op_roundpd_mem_rcx": + src, imm = a, 0 + elif name == "op_roundpd_mem_rdx": + src, imm = b, 1 + elif name == "op_roundpd_mem_r8": + src, imm = seed, 2 + else: + imm = 1 if (altered and name == "op_roundpd_reg_2") else int(name.split("_")[-1]) + src = a + return _p64s(_round_ref(F64, x, imm, mxcsr) for x in _u64s(src)) + + if name.startswith("op_roundss_"): + if name == "op_roundss_mem_rcx": + dst, src, imm = b, a, 1 + elif name == "op_roundss_mem_rdx": + dst, src, imm = a, b, 2 + elif name == "op_roundss_mem_r8": + dst, src, imm = a, seed, 3 + else: + imm = 3 if (altered and name == "op_roundss_reg_0") else int(name.split("_")[-1]) + dst, src = a, b + out = list(_u32s(dst)) + out[0] = _round_ref(F32, _u32s(src)[0], imm, mxcsr) + return _p32s(out) + + if name.startswith("op_roundsd_"): + if name == "op_roundsd_mem_rcx": + dst, src, imm = b, a, 1 + elif name == "op_roundsd_mem_rdx": + dst, src, imm = a, b, 2 + elif name == "op_roundsd_mem_r8": + dst, src, imm = a, seed, 3 + else: + imm = 2 if (altered and name == "op_roundsd_reg_3") else int(name.split("_")[-1]) + dst, src = a, b + out = list(_u64s(dst)) + out[0] = _round_ref(F64, _u64s(src)[0], imm, mxcsr) + return _p64s(out) + + if name.startswith("op_insertps_"): + imms = { + "op_insertps_reg_s1_d2_z5": (a, b, 0x60 if altered else 0x65, False), + "op_insertps_reg_s3_d0_z0": (a, b, 0xC0, False), + "op_insertps_reg_s0_d3_z8": (a, b, 0x38, False), + "op_insertps_mem_rcx": (b, a, 0xD2, True), + "op_insertps_mem_rdx": (a, b, 0xE4, True), + "op_insertps_mem_r8": (a, seed, 0x91, True), + } + dst, src, imm, is_mem = imms[name] + return _insertps_ref(dst, src, imm, mem=is_mem) + + if name == "op_extractps_r32_lane2": + lane = 1 if altered else 2 + return struct.pack("<QQ", _u32s(a)[lane], _u64s(seed)[1]) + if name == "op_extractps_r64_lane3": + return struct.pack("<QQ", _u32s(a)[3], _u64s(seed)[1]) + if name == "op_extractps_mem_lane1": + return struct.pack("<I", _u32s(a)[1]) + seed[4:16] + + if name == "op_sse41_glue_pipeline": + xmm2 = _p32s((_u32s(b)[0], *_u32s(a)[1:])) + xmm3 = _p64s((_u64s(a)[0], _u64s(b)[1])) + xmm4 = _p32s(_round_ref(F32, x, 1, mxcsr) for x in _u32s(xmm2)) + return _insertps_ref(xmm4, xmm3, 0x52, mem=False) + + raise KeyError(name) + + +def check_dp_result(name: str, a: bytes, b: bytes, seed: bytes, mxcsr: int, got_n: bytes, got_l: bytes, *, altered: bool = False) -> None: + imms = { + "op_dpps_reg_f1": (a, b, 0xF1), + "op_dpps_reg_ff": (a, b, 0x55 if altered else 0xFF), + "op_dpps_reg_5a": (a, b, 0x5A), + "op_dpps_reg_0f": (a, b, 0x0F), + "op_dpps_mem_rcx": (b, a, 0xF3), + "op_dpps_mem_rdx": (a, b, 0xC5), + "op_dpps_mem_r8": (a, seed, 0xAA), + "op_dppd_reg_33": (a, b, 0x11 if altered else 0x33), + "op_dppd_reg_11": (a, b, 0x11), + "op_dppd_reg_22": (a, b, 0x22), + "op_dppd_reg_03": (a, b, 0x03), + "op_dppd_mem_rcx": (b, a, 0x31), + "op_dppd_mem_rdx": (a, b, 0x32), + "op_dppd_mem_r8": (a, seed, 0x23), + } + x, y, imm = imms[name] + is_pd = name.startswith("op_dppd_") + fmt, unpack, lanes = (F64, _u64s, 2) if is_pd else (F32, _u32s, 4) + allowed = _dp_allowed(fmt, unpack(x), unpack(y), imm) + for label, got in (("native", got_n), ("lifted", got_l)): + words = unpack(got) + for k in range(lanes): + if not ((imm >> k) & 1) and words[k] != 0: + raise AssertionError(f"{name} ({label}): disabled lane {k} is {words[k]:#x}, expected +0.0") + enabled = {words[k] for k in range(lanes) if (imm >> k) & 1} + if mxcsr == 0x1F80 and not enabled <= allowed: + raise AssertionError(f"{name} ({label}): {enabled} not in {sorted(allowed)}") + # Where the architectural reduction set has a single value (including single-NaN, +/-Inf, + # signed zero, normal, and non-associative finite cancellation), require bit-for-bit equality. + if len(allowed) == 1 and got_n != got_l: + raise AssertionError(f"{name} mxcsr={mxcsr:#x}: native={got_n.hex()} != lifted={got_l.hex()}") + + +def check_translator(original_path: Path) -> None: + source_cpp, meta = translate(original_path, EXPORTS) + assert len(meta) == len(EXPORTS) and "host_has_sse41" in source_cpp, len(meta) + assert "<smmintrin.h>" not in source_cpp and "<immintrin.h>" not in source_cpp + + ld_xmm0 = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld_xmm1 = Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld_xmm4 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM4, MemoryOperand(R.RCX)) + ld_xmm5 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM5, MemoryOperand(R.RDX)) + st_xmm0 = Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + st_xmm4 = Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.R8), R.XMM4) + ret_ins = Instruction.create(Code.RETNQ) + + accepted = 0 + for code, helper, needs_dst, mem_size in ( + (Code.ROUNDPS_XMM_XMMM128_IMM8, "op_roundps", False, 16), + (Code.ROUNDPD_XMM_XMMM128_IMM8, "op_roundpd", False, 16), + (Code.ROUNDSS_XMM_XMMM32_IMM8, "op_roundss", True, 4), + (Code.ROUNDSD_XMM_XMMM64_IMM8, "op_roundsd", True, 8), + (Code.DPPS_XMM_XMMM128_IMM8, "op_dpps", True, 16), + (Code.DPPD_XMM_XMMM128_IMM8, "op_dppd", True, 16), + (Code.INSERTPS_XMM_XMMM32_IMM8, "op_insertps", True, 4), + ): + loads = (ld_xmm4, ld_xmm5) if needs_dst else (ld_xmm5,) + reg_src, _ = lift_code( + f"{helper}_reg", + 0x1000, + encode_seq( + *loads, + Instruction.create_reg_reg_u32(code, R.XMM4, R.XMM5, 0x54), + st_xmm4, + ret_ins, + ), + ) + assert f"{helper}(" in reg_src, reg_src + accepted += 1 + + for base in (R.RCX, R.RDX, R.R8): + mem_loads = (ld_xmm4,) if needs_dst else () + mem_src, _ = lift_code( + f"{helper}_mem_{base}", + 0x1000, + encode_seq( + *mem_loads, + Instruction.create_reg_mem_u32(code, R.XMM4, MemoryOperand(base), 0x11), + st_xmm4, + ret_ins, + ), + ) + loader = {4: "load32", 8: "load64", 16: "load128"}[mem_size] + assert f"{loader}(" in mem_src, mem_src + accepted += 1 + + # Alternate EXTRACTPS (r32/r64/m32) and MOVSS/MOVSD 0F11 encodings. + for label, seq, frag in ( + ("ext_r32", (ld_xmm4, Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.R10D, R.XMM4, 2), Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.R10), ret_ins), "r10 = static_cast<word>(lane32(xmm4, 2u));"), + ("ext_r64", (ld_xmm4, Instruction.create_reg_reg_u32(Code.EXTRACTPS_R64M32_XMM_IMM8, R.R11, R.XMM4, 3), Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.R11), ret_ins), "r11 = static_cast<word>(lane32(xmm4, 3u));"), + ("ext_m32", (ld_xmm4, Instruction.create_mem_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, MemoryOperand(R.R8), R.XMM4, 1), ret_ins), "store32(r8, lane32(xmm4, 1u));"), + ("movss_0f11", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg(Code.MOVSS_XMMM32_XMM, R.XMM4, R.XMM5), st_xmm4, ret_ins), "set_lane32(xmm4, 0u, lane32(xmm5, 0u));"), + ("movsd_0f11", (ld_xmm4, ld_xmm5, Instruction.create_reg_reg(Code.MOVSD_XMMM64_XMM, R.XMM4, R.XMM5), st_xmm4, ret_ins), "xmm4.q[0] = xmm5.q[0];"), + ): + src, _ = lift_code(label, 0x1000, encode_seq(*seq)) + assert frag in src, src + accepted += 1 + + seg_ins = Instruction.create_reg_mem_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RCX), 0) + seg_ins.segment_prefix = R.GS + + rejects = [ + ("vex_vroundps", (ld_xmm1, Instruction.create_reg_reg_u32(Code.VEX_VROUNDPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), ret_ins), "non-legacy encoding"), + ("vex_vdpps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VDPPS_XMM_XMM_XMMM128_IMM8, R.XMM0, R.XMM0, R.XMM1, 0xFF), ret_ins), "non-legacy encoding"), + ("vex_vinsertps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_reg_u32(Code.VEX_VINSERTPS_XMM_XMM_XMMM32_IMM8, R.XMM0, R.XMM0, R.XMM1, 0), ret_ins), "non-legacy encoding"), + ("vex_vextractps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.VEX_VEXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM0, 0), ret_ins), "non-legacy encoding"), + ("evex_vmovaps", (Instruction.create_reg_mem(Code.EVEX_VMOVAPS_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins), "non-legacy encoding"), + ("unsupported_addps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.ADDPS_XMM_XMMM128, R.XMM0, R.XMM1), ret_ins), "unsupported instruction"), + ("unsupported_blendps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32(Code.BLENDPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 1), ret_ins), "unsupported instruction"), + ("nonvol_xmm6_roundps", (ld_xmm1, Instruction.create_reg_reg_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM6, R.XMM1, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm15_dpps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.DPPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM15, 0xFF), ret_ins), "nonvolatile vector register"), + ("nonvol_xmm8_extractps", (Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM8, 0), ret_ins), "nonvolatile vector register"), + ("nonvol_rbx_extractps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.EXTRACTPS_R64M32_XMM_IMM8, R.RBX, R.XMM0, 0), ret_ins), "nonvolatile GPR"), + ("arg_write_rcx_extractps", (ld_xmm0, Instruction.create_reg_reg_u32(Code.EXTRACTPS_R64M32_XMM_IMM8, R.RCX, R.XMM0, 0), ret_ins), "write to argument GPR"), + ("arg_write_rdx_mov", (Instruction.create_reg_mem(Code.MOV_R64_RM64, R.RDX, MemoryOperand(R.RCX)), ret_ins), "write to argument GPR"), + ("undef_roundss_dst", (ld_xmm1, Instruction.create_reg_reg_u32(Code.ROUNDSS_XMM_XMMM32_IMM8, R.XMM0, R.XMM1, 0), ret_ins), "undefined vector register xmm0"), + ("undef_roundsd_dst", (ld_xmm1, Instruction.create_reg_reg_u32(Code.ROUNDSD_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, 0), ret_ins), "undefined vector register xmm0"), + ("undef_dpps_dst", (ld_xmm1, Instruction.create_reg_reg_u32(Code.DPPS_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0xFF), ret_ins), "undefined vector register xmm0"), + ("undef_insertps_src", (ld_xmm0, Instruction.create_reg_reg_u32(Code.INSERTPS_XMM_XMMM32_IMM8, R.XMM0, R.XMM3, 0), ret_ins), "undefined vector register xmm3"), + ("undef_extractps_src", (Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM2, 0), ret_ins), "undefined vector register xmm2"), + ("undef_gpr_store", (Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.R8), R.RAX), ret_ins), "undefined GPR rax"), + ("disp_mem_rcx", (Instruction.create_reg_mem_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RCX, displ=16, displ_size=1), 0), ret_ins), "unsupported memory operand"), + ("indexed_mem", (ld_xmm0, Instruction.create_reg_mem_u32(Code.DPPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RDX, R.RCX, 4), 0xFF), ret_ins), "unsupported memory operand"), + ("rip_rel_mem", (ld_xmm0, Instruction.create_reg_mem_u32(Code.INSERTPS_XMM_XMMM32_IMM8, R.XMM0, MemoryOperand(R.RIP, displ=0x1040, displ_size=4), 0), ret_ins), "unsupported memory operand"), + ("nonvol_base_rbx", (Instruction.create_reg_mem_u32(Code.ROUNDPD_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RBX), 0), ret_ins), "nonvolatile GPR base"), + ("non_arg_base_rax", (Instruction.create_reg_mem_u32(Code.ROUNDPS_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RAX), 0), ret_ins), "unsupported memory base"), + ("addr32_ecx", (ld_xmm0, Instruction.create_reg_mem_u32(Code.ROUNDSS_XMM_XMMM32_IMM8, R.XMM0, MemoryOperand(R.ECX), 0), ret_ins), "unsupported memory operand"), + ("non_r8_store_extractps", (ld_xmm0, Instruction.create_mem_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, MemoryOperand(R.RDX), R.XMM0, 0), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_movaps", (ld_xmm0, Instruction.create_mem_reg(Code.MOVAPS_XMMM128_XMM, MemoryOperand(R.RCX), R.XMM0), ret_ins), "non-r8 store memory operand"), + ("non_r8_store_gpr", (ld_xmm0, Instruction.create_reg_reg_u32(Code.EXTRACTPS_RM32_XMM_IMM8, R.EAX, R.XMM0, 0), Instruction.create_mem_reg(Code.MOV_RM32_R32, MemoryOperand(R.RDX), R.EAX), ret_ins), "non-r8 store memory operand"), + ("seg_prefix", (seg_ins, ret_ins), "unsupported instruction prefix"), + ("missing_ret", (ld_xmm0, st_xmm0), "missing terminal ret"), + ("after_ret", (ld_xmm0, ret_ins, st_xmm0), "unreachable instruction after ret"), + ] + for label, seq, reason in rejects: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted invalid sequence") + + for label, raw, reason in ( + ("invalid_bytes", b"\xFF\xFE\xC3", "invalid instruction"), + ("empty_stream", b"", "truncated instruction stream"), + ): + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: raw stream unexpectedly accepted") + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_cpp = root / "out.cpp" + out_dir = root / "out_dir" + out_dir.mkdir() + in_dir = root / "in_dir" + in_dir.mkdir() + for argv in ( + [str(root / "missing.dll"), "op_roundps_reg_0", str(out_cpp)], + [str(in_dir), "op_roundps_reg_0", str(out_cpp)], + [str(original_path), ",", str(out_cpp)], + [str(original_path), "missing_export_xyz", str(out_cpp)], + [str(original_path), "op_roundps_reg_0", str(out_dir)], + ): + try: + tool_main(argv) + except SystemExit as exc: + assert exc.code == 1, (argv, exc.code) + else: + raise AssertionError(f"CLI did not exit for {argv}") + assert not out_cpp.exists() and sorted(p.name for p in root.iterdir()) == ["in_dir", "out_dir"] + + print( + f"translator validated: {accepted} forms accepted, " + f"{len(rejects) + 2} refusal controls and 5 CLI negative checks passed" + ) + + +def host_has_sse41(lifted_lib) -> bool: + if hasattr(lifted_lib, "host_has_sse41"): + lifted_lib.host_has_sse41.argtypes = [] + lifted_lib.host_has_sse41.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_sse41()) + return False + + +def check_differential(native_path: Path, lifted_path: Path, altered_path: Path, altered_lifted_path: Path) -> None: + native = ctypes.CDLL(str(native_path.resolve())) + lifted = ctypes.CDLL(str(lifted_path.resolve())) + altered_native = ctypes.CDLL(str(altered_path.resolve())) + altered_lifted = ctypes.CDLL(str(altered_lifted_path.resolve())) + + exchange = lifted.host_exchange_mxcsr + exchange.argtypes, exchange.restype = [ctypes.c_uint32], ctypes.c_uint32 + + def _f32(*vals): + words = [v if isinstance(v, int) else struct.unpack("<I", struct.pack("<f", v))[0] for v in vals] + return struct.pack("<4I", *words) + + def _f64(*vals): + words = [v if isinstance(v, int) else struct.unpack("<Q", struct.pack("<d", v))[0] for v in vals] + return struct.pack("<2Q", *words) + + f32_pairs = ( + (_f32(-3.5, -2.5, -0.25, 0.5), _f32(2.5, 3.5, 0.25, -0.5)), + (_f32(0x00000000, 0x80000000, 0x00000001, 0x80000001), _f32(0x80000000, 0x00000000, 0x00400001, 0x80400001)), + (_f32(0x7FC12345, 0x7F800123, 0x7F800000, 0xFF800000), _f32(0xFFC54321, 0xFF800456, 1.5, -2.5)), + (_f32(0x7FC12345, 1.5, 2.0, -3.0), _f32(1.0, 2.0, -0.5, 0.25)), + (_f32(16777215.0, -16777215.0, 1.9999999, -1.9999999), _f32(3.5, -0.5, 2.0, -3.0)), + # Non-associative DPPS + poison upper qword for extractps. + (_f32(1.0e20, -1.0e20, 1.0, 2.0), _f32(0xCAFEBABE, 0xFEEDFACE, 1.5, -0.25)), + ) + + f64_pairs = ( + (_f64(-3.5, -2.5), _f64(0.25, 0.5)), + (_f64(0x0000000000000000, 0x8000000000000000), _f64(0x0000000000000001, 0x8000000000000001)), + (_f64(0x7FF8000000012345, 0x7FF0000000000123), _f64(0xFFF8000000054321, 0xFFF0000000000456)), + (_f64(0x7FF8000000012345, 1.5), _f64(1.0, -2.5)), + (_f64(0x7FF0000000000000, 0xFFF0000000000000), _f64(2.5, -1.5)), + ) + + def invoke(dll, prefix: str, name: str, a_bytes: bytes, b_bytes: bytes, mxcsr: int, align: int = 0): + is_rcx_mem = name.endswith("_mem_rcx") + is_r8_mem = name.endswith("_mem_r8") + _ra, pa, _ = _guarded_buf(a_bytes, align if is_rcx_mem else 0) + _rb, pb, _ = _guarded_buf(b_bytes, 0 if (is_rcx_mem or is_r8_mem) else align) + _rc, pc, _ = _guarded_buf(SEED, align if is_r8_mem else 0) + fn = getattr(dll, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64] + fn.restype = None + previous = exchange(mxcsr) + try: + fn(pa, pb, pc) + finally: + exchange(previous) + return ctypes.string_at(pc, 16) + + cases = 0 + for name in EXPORTS: + is_pd = ("pd_" in name or "roundsd_" in name) + pairs = f64_pairs if is_pd else f32_pairs + is_dp = name.startswith(("op_dpps_", "op_dppd_")) + is_aligned_only = ( + name.startswith(("op_roundps_", "op_roundpd_", "op_dpps_", "op_dppd_")) + and "_mem_" in name + ) + for mxcsr in MXCSR_MODES: + for a_bytes, b_bytes in pairs: + got_n = invoke(native, "", name, a_bytes, b_bytes, mxcsr, 0) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, mxcsr, 0) + if is_dp: + check_dp_result(name, a_bytes, b_bytes, SEED, mxcsr, got_n, got_l) + else: + want = ref_export(name, a_bytes, b_bytes, SEED, mxcsr) + if got_n != want or got_l != want: + raise AssertionError( + f"{name} mxcsr={mxcsr:#x}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}" + ) + cases += 1 + if "_mem_" in name and not is_aligned_only: + a_bytes, b_bytes = pairs[0] + for off in (1, 3, 7): + got_n = invoke(native, "", name, a_bytes, b_bytes, 0x1F80, off) + got_l = invoke(lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, off) + want = ref_export(name, a_bytes, b_bytes, SEED, 0x1F80) + if got_n != want or got_l != want: + raise AssertionError(f"{name} off={off}: want={want.hex()} native={got_n.hex()} lifted={got_l.hex()}") + cases += 1 + + # Altered controls must match altered native and diverge from original on at least one input pair. + for name in ALTERED_EXPORTS: + is_pd = ("pd_" in name or "roundsd_" in name) + pairs = f64_pairs if is_pd else f32_pairs + diffs = 0 + for a_bytes, b_bytes in pairs: + got_alt_n = invoke(altered_native, "", name, a_bytes, b_bytes, 0x1F80, 0) + got_alt_l = invoke(altered_lifted, "lifted_", name, a_bytes, b_bytes, 0x1F80, 0) + got_orig = invoke(native, "", name, a_bytes, b_bytes, 0x1F80, 0) + if name.startswith(("op_dpps_", "op_dppd_")): + check_dp_result(name, a_bytes, b_bytes, SEED, 0x1F80, got_alt_n, got_alt_l, altered=True) + else: + want_alt = ref_export(name, a_bytes, b_bytes, SEED, 0x1F80, altered=True) + assert got_alt_n == want_alt and got_alt_l == want_alt, ( + name, got_alt_n.hex(), got_alt_l.hex(), want_alt.hex() + ) + if got_alt_l != got_orig: + diffs += 1 + assert diffs > 0, f"altered {name} failed to diverge" + + print( + f"{cases} legacy SSE4.1 FP cases across {len(EXPORTS)} exports and {len(MXCSR_MODES)} MXCSR modes " + f"matched native DLL and IEEE-754 reference; {len(ALTERED_EXPORTS)} altered controls diverged" + ) + + +def record_covered_forms(original_path: Path) -> None: + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + mnemonic_names = { + val: key.lower() + for key, val in vars(Mnemonic).items() + if not key.startswith("_") and isinstance(val, int) + } + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(mnemonic_names[ins.mnemonic]) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main() -> None: + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + check_translator(original_path) + + lifted_lib = ctypes.CDLL(str(lifted_path.resolve())) + if not host_has_sse41(lifted_lib): + print("Host lacks CPUID.01H:ECX[19] (SSE4.1); skipping native differential check") + sys.exit(77) + + check_differential(original_path, lifted_path, altered_path, altered_lifted_path) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tests/cpu/sse_fp_pd_check.py b/tests/cpu/sse_fp_pd_check.py index 6984681255..3cc7310b60 100644 --- a/tests/cpu/sse_fp_pd_check.py +++ b/tests/cpu/sse_fp_pd_check.py @@ -4,7 +4,10 @@ through the translator in the default control word and under all sixteen combinations of MXCSR rounding mode, DAZ and FTZ, each against the exact reference in sse_fp_pd_ref.py. CMPPD (predicates 0..7, xmm and aligned m128 sources) gets the same treatment against the predicate rules of that reference. The packed -single checks in sse_fp_check.py provide the buffer, driver and encoding helpers.""" +single checks in sse_fp_check.py provide the buffer, driver and encoding helpers. + +CTest runs the parts (differential, modes, cmp_differential, cmp_modes, rejections) as separate cases in +parallel. Passing no part name after the four paths still runs all of them serially, for a direct run.""" from pathlib import Path import random @@ -481,9 +484,17 @@ def cmppd(dst, src, imm): if __name__ == "__main__": - native_dll, lifted_dll, altered_dll, harness_dll = sys.argv[1:5] - check_differential(native_dll, lifted_dll, altered_dll) - check_modes(native_dll, lifted_dll, harness_dll) - check_cmp_differential(native_dll, lifted_dll, altered_dll) - check_cmp_modes(native_dll, lifted_dll, harness_dll) - check_rejections(native_dll) + native_dll, lifted_dll, altered_dll, harness_dll, *selected = sys.argv[1:] + # CTest runs the parts as separate cases; no part runs them all in the original order. + parts = { + "differential": lambda: check_differential(native_dll, lifted_dll, altered_dll), + "modes": lambda: check_modes(native_dll, lifted_dll, harness_dll), + "cmp_differential": lambda: check_cmp_differential(native_dll, lifted_dll, altered_dll), + "cmp_modes": lambda: check_cmp_modes(native_dll, lifted_dll, harness_dll), + "rejections": lambda: check_rejections(native_dll), + } + unknown = [name for name in selected if name not in parts] + if unknown: + raise ValueError(f"unknown part {unknown}; choose from {sorted(parts)}") + for name in selected or parts: + parts[name]() diff --git a/tests/cpu/x87_fprem.py b/tests/cpu/x87_fprem.py index 98ae594df5..0d2a120adf 100644 --- a/tests/cpu/x87_fprem.py +++ b/tests/cpu/x87_fprem.py @@ -5,6 +5,8 @@ python tests/cpu/x87_fprem.py emit <dll> <cpp> [control] translate (and optionally mutate) the fixture python tests/cpu/x87_fprem.py check <harness> <native> <lifted> [controls...] +CTest runs the check-* parts as separate cases in parallel; `check` runs every part serially for a direct run. + Each export loads ST(1) from offset 16 and ST(0) from offset 0 of its input block, takes the partial remainder, and stores the result, the divisor and records of the status word in its output block. The translation is lower(..., x87=Checked(REJECT)) inside a checked entry, uint32_t name(word input, @@ -455,8 +457,23 @@ def is_nan(raw): def check(harness_path, native_path, lifted_path, *control_paths): + check_light() + expected = build_expected() + check_lifted(harness_path, lifted_path, expected) + check_native(harness_path, native_path, expected) + check_controls(harness_path, expected, control_paths) + + +def check_light(): print(f"the model agreed with {check_model()} remainders worked by hand") - expected = [(name, data, run(name, data)) for name, data in cases()] + check_rejections() + + +def build_expected(): + return [(name, data, run(name, data)) for name, data in cases()] + + +def check_lifted(harness_path, lifted_path, expected): lifted = CheckedRunner(harness_path, lifted_path) statuses = dict.fromkeys(STATUS.values(), 0) bad = 0 @@ -473,6 +490,9 @@ def check(harness_path, native_path, lifted_path, *control_paths): print(f"{len(expected)} cases over {len(SEQUENCES)} exports matched the model in the checked translation (status, " "output block and guards, and *result, which only status 0 writes)") print("translated statuses: " + ", ".join(f"{name} {statuses[code]}" for name, code in STATUS.items())) + + +def check_native(harness_path, native_path, expected): native = base.Runner(harness_path, native_path) compared = partial_records = nan_results = looped = skipped = 0 for name, data, model in expected: @@ -509,6 +529,9 @@ def check(harness_path, native_path, lifted_path, *control_paths): f"was a NaN in the {nan_results} single-step cases with a NaN model result, and the loops reduced partially " f"and iterated in {looped} cases; {skipped} loop cases with a NaN result ran only translated") print(f"processor: {platform.processor()}") + + +def check_controls(harness_path, expected, control_paths): for path in control_paths: control = Path(path).stem.rsplit("_", 1)[-1] run_control = CheckedRunner(harness_path, path) @@ -516,7 +539,6 @@ def check(harness_path, native_path, lifted_path, *control_paths): print(f"control {control}: {bad}/{len(expected)} mismatches") if not bad: raise AssertionError(f"control {control} matched every case") - check_rejections() def check_rejections(): @@ -567,12 +589,22 @@ def pair(middle, end=clear): # two values loaded, middle, both popped if __name__ == "__main__": - mode, first, second, *rest = sys.argv[1:] + mode, *args = sys.argv[1:] # check-light takes no paths + first, second = (args + [None, None])[:2] + rest = args[2:] if mode == "asm": write_asm(first, second) elif mode == "emit": emit(Path(first), Path(second), *rest) elif mode == "check": check(first, second, *rest) + elif mode == "check-light": # the hand-worked model and the rejections; no fixture needed + check_light() + elif mode == "check-lifted": + check_lifted(first, second, build_expected()) + elif mode == "check-native": + check_native(first, second, build_expected()) + elif mode == "check-controls": # args: harness, unused, then the control DLLs + check_controls(first, build_expected(), rest) else: raise ValueError(mode) diff --git a/tests/cpu/x87_scale.py b/tests/cpu/x87_scale.py index 5120b5f7fc..57d1864857 100644 --- a/tests/cpu/x87_scale.py +++ b/tests/cpu/x87_scale.py @@ -5,6 +5,8 @@ python tests/cpu/x87_scale.py emit <dll> <cpp> [control] translate (and optionally mutate) the fixture python tests/cpu/x87_scale.py check <harness> <native> <lifted> [controls...] +CTest runs the check-* parts as separate cases in parallel; `check` runs every part serially for a direct run. + The exports, harness and guards follow tests/cpu/x87_add.py, and the other steps use the format of tests/cpu/x87_moves.py. emit checks that every decoded x87 instruction is the form its sequence names. The model scales with Fraction arithmetic and is independent of tools/x87_soft.h. @@ -257,36 +259,40 @@ def cases(): # ---- Check ----------------------------------------------------------------------------------------- -def check(harness_path, native_path, lifted_path, *control_paths): - expected = [(name, data, reference(name, data)) for name, data in cases()] - for label, path in (("native", native_path), ("lifted", lifted_path)): - run = base.Runner(harness_path, path) - bad = 0 - for name, data, want in expected: - got, state = run(name, data) - if not base.entry_state_ok(state): - raise AssertionError(f"{label} {name} left state {state:#014x}; the profile requires control " - "0x027f and an empty stack at TOP 0") - if got != want: - if bad < 3: - print(f"{label} mismatch: {name}(input {data[:48].hex()})\n got {got[:48].hex()}\n" - f" expected {want[:48].hex()}") - bad += 1 - if bad: - raise AssertionError(f"{label}: {bad}/{len(expected)} mismatches") - print(f"{len(expected)} cases over {len(SEQUENCES)} exports (output block and guards) matched the reference " - "in native and translated DLLs; each export returned with control 0x027f and an empty stack") +def build_expected(): + return [(name, data, reference(name, data)) for name, data in cases()] + + +def check_target(label, harness_path, path, expected): + """Every case, then the x87_call caller-state check, against one DLL (native or translated).""" + run = base.Runner(harness_path, path) + bad = 0 + for name, data, want in expected: + got, state = run(name, data) + if not base.entry_state_ok(state): + raise AssertionError(f"{label} {name} left state {state:#014x}; the profile requires control " + "0x027f and an empty stack at TOP 0") + if got != want: + if bad < 3: + print(f"{label} mismatch: {name}(input {data[:48].hex()})\n got {got[:48].hex()}\n" + f" expected {want[:48].hex()}") + bad += 1 + if bad: + raise AssertionError(f"{label}: {bad}/{len(expected)} mismatches") + print(f"{label}: {len(expected)} cases over {len(SEQUENCES)} exports (output block and guards) matched the " + "reference; each export returned with control 0x027f and an empty stack") print(f"processor: {platform.processor()}") first = {} for name, data, want in expected: first.setdefault(name, (data, want)) - for label, path in (("native", native_path), ("lifted", lifted_path)): - run = base.Runner(harness_path, path) - failed = [name for name, (data, want) in first.items() if not base.preserved(run, "x87_call", name, data, want)] - if failed: - raise AssertionError(f"x87_call lost a live caller value or control word around {label} {failed}") - print(f"x87_call kept a live caller ST(0) value and control word around all {len(first)} native and " - "translated exports") + run = base.Runner(harness_path, path) + failed = [name for name, (data, want) in first.items() if not base.preserved(run, "x87_call", name, data, want)] + if failed: + raise AssertionError(f"x87_call lost a live caller value or control word around {label} {failed}") + print(f"x87_call kept a live caller ST(0) value and control word around all {len(first)} {label} exports") + + +def check_controls(harness_path, expected, control_paths): for path in control_paths: control = Path(path).stem.rsplit("_", 1)[-1] run = base.Runner(harness_path, path) @@ -294,6 +300,13 @@ def check(harness_path, native_path, lifted_path, *control_paths): print(f"control {control}: {bad}/{len(expected)} mismatches") if not bad: raise AssertionError(f"control {control} matched every case") + + +def check(harness_path, native_path, lifted_path, *control_paths): + expected = build_expected() + check_target("native", harness_path, native_path, expected) + check_target("lifted", harness_path, lifted_path, expected) + check_controls(harness_path, expected, control_paths) check_rejections() @@ -324,12 +337,22 @@ def attempt(hex_bytes): if __name__ == "__main__": - mode, first, second, *rest = sys.argv[1:] + mode, *args = sys.argv[1:] # check-rejections takes no paths + first, second = (args + [None, None])[:2] + rest = args[2:] if mode == "asm": write_asm(first, second) elif mode == "emit": emit(Path(first), Path(second), *rest) elif mode == "check": check(first, second, *rest) + elif mode == "check-rejections": # no fixture needed + check_rejections() + elif mode == "check-native": # args: harness, native DLL + check_target("native", first, second, build_expected()) + elif mode == "check-lifted": # args: harness, lifted DLL + check_target("lifted", first, second, build_expected()) + elif mode == "check-controls": # args: harness, unused, then the control DLLs + check_controls(first, build_expected(), rest) else: raise ValueError(mode) diff --git a/tests/cpu/xchg.py b/tests/cpu/xchg.py index 87739375d6..ba09c13aae 100644 --- a/tests/cpu/xchg.py +++ b/tests/cpu/xchg.py @@ -1,4 +1,8 @@ -"""Compare native and translated XCHG, and check that the memory form stays atomic under contention.""" +"""Compare native and translated XCHG, and check that the memory form stays atomic under contention. + +CTest runs the parts as separate cases (check-native, check-lifted, check-controls, in parallel) and keeps +check-rejections on the aggregate. The `check` mode still runs every part serially for a direct run; the +parts above are not the only coverage of that mode, they are the same checks split up.""" from collections import Counter import ctypes import os @@ -167,18 +171,20 @@ def token_errors(lib, rounds): return threads, worst -def check(native_path, lifted_path, *control_paths): - for label, path in (("native", native_path), ("lifted", lifted_path)): - lib = load_lib(path) - cases, bad = value_mismatches(lib) - if bad: - name, x, y, want, got = bad[0] - raise AssertionError(f"{label}: {len(bad)} mismatches; first {name}({x:#x}, {y:#x}) = {got}, expected {want}") - threads, errors = token_errors(lib, rounds=3) - if any(errors.values()): - raise AssertionError(f"{label}: token exchange lost or duplicated values: {errors}") - print(f"{label}: {cases} value cases matched; {threads} threads x 100000 tokens x 3 rounds, " - f"lost or duplicated tokens {errors}") +def check_library(label, path): + lib = load_lib(path) + cases, bad = value_mismatches(lib) + if bad: + name, x, y, want, got = bad[0] + raise AssertionError(f"{label}: {len(bad)} mismatches; first {name}({x:#x}, {y:#x}) = {got}, expected {want}") + threads, errors = token_errors(lib, rounds=3) + if any(errors.values()): + raise AssertionError(f"{label}: token exchange lost or duplicated values: {errors}") + print(f"{label}: {cases} value cases matched; {threads} threads x 100000 tokens x 3 rounds, " + f"lost or duplicated tokens {errors}") + + +def check_controls(control_paths): for path in control_paths: control = Path(path).stem.rsplit("_", 1)[-1] lib = load_lib(path) @@ -189,6 +195,12 @@ def check(native_path, lifted_path, *control_paths): raise AssertionError(f"control {control} matched every case") +def check(native_path, lifted_path, *control_paths): + check_library("native", native_path) + check_library("lifted", lifted_path) + check_controls(control_paths) + + def check_rejections(): # An explicit LOCK on XCHG is redundant but still goes through the prefix rejection. try: @@ -208,11 +220,19 @@ def check_rejections(): if __name__ == "__main__": - mode, native, other, *rest = sys.argv[1:] + mode, *args = sys.argv[1:] if mode == "emit": - emit(Path(native), Path(other), *rest) + emit(Path(args[0]), Path(args[1]), *args[2:]) elif mode == "check": - check(native, other, *rest) + check(*args) + check_rejections() + elif mode == "check-native": + check_library("native", *args) + elif mode == "check-lifted": + check_library("lifted", *args) + elif mode == "check-controls": + check_controls(args) + elif mode == "check-rejections": # no fixture needed check_rejections() else: raise ValueError(mode) diff --git a/tests/cpu_call_aot_cli_check.py b/tests/cpu_call_aot_cli_check.py new file mode 100644 index 0000000000..eec0739e8a --- /dev/null +++ b/tests/cpu_call_aot_cli_check.py @@ -0,0 +1,882 @@ +#!/usr/bin/env python3 +"""Standalone pure-Python synthetic PE32+ unit, CLI, path-guard, atomic-write, and mutation suite for tools/cpu_call_aot.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +import pefile + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "cpu_call_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) + +import cpu_call_aot # noqa: E402 + + +SECTION_ALIGN = 0x1000 +FILE_ALIGN = 0x200 +TEXT_RVA = 0x1000 +RDATA_RVA = 0x2000 +PDATA_RVA = 0x3000 + +CALLER_PROLOGUE = bytes.fromhex("53 56 48 83 ec 28") +CALLER_EPILOGUE = bytes.fromhex("48 83 c4 28 5e 5b c3") +CALLEE_PROLOGUE = bytes.fromhex("53 56 48 83 ec 08") +CALLEE_EPILOGUE = bytes.fromhex("48 83 c4 08 5e 5b c3") + + +def build_synthetic_pe( + *, + functions: list[tuple[str | None, int, bytes]], + exports: list[tuple[str | None, int, int]] | None = None, + imports: list[tuple[str, list[tuple[str | None, int | None, int]]]] | None = None, + text_executable: bool = True, + directories: int = 16, + overlapping_pdata: bool = False, +) -> bytes: + """Build a synthetic AMD64 PE32+ DLL with multiple functions, exports, .pdata, and optional IAT imports.""" + text = bytearray() + fn_spans: list[tuple[int, int]] = [] + for _name, rel_off, code in functions: + if len(text) < rel_off: + text.extend(b"\xcc" * (rel_off - len(text))) + begin = TEXT_RVA + rel_off + text[rel_off:rel_off + len(code)] = code + fn_spans.append((begin, begin + len(code))) + + rdata = bytearray() + unwind_rva = RDATA_RVA + rdata += bytes([1, 0, 0, 0]) # UNWIND_INFO v1, no prolog, no codes + + def align_rdata(align: int = 8) -> int: + while len(rdata) % align: + rdata.append(0) + return RDATA_RVA + len(rdata) + + # Export directory + if exports is None: + exports = [(name, idx + 1, TEXT_RVA + rel_off) + for idx, (name, rel_off, _code) in enumerate(functions) if name is not None] + + exports_rva = 0 + exports_size = 0 + if exports: + exports_rva = align_rdata(4) + base_ord = min(ord_num for _n, ord_num, _rva in exports) + max_ord = max(ord_num for _n, ord_num, _rva in exports) + num_funcs = max_ord - base_ord + 1 + named = sorted([(n, ord_num) for n, ord_num, _rva in exports if n is not None], key=lambda item: item[0]) + eat_off = len(rdata) + 40 + npt_off = eat_off + 4 * num_funcs + eot_off = npt_off + 4 * len(named) + str_off = eot_off + 2 * len(named) + dll_name = b"synth.dll\0" + rdata.extend(b"\x00" * (str_off - len(rdata))) + dll_name_rva = RDATA_RVA + len(rdata) + rdata.extend(dll_name) + name_rvas: list[tuple[int, int]] = [] + for sym_name, ord_num in named: + name_rvas.append((RDATA_RVA + len(rdata), ord_num - base_ord)) + rdata.extend(sym_name.encode("ascii") + b"\0") + struct.pack_into( + "<IIHHIIIIIII", + rdata, + exports_rva - RDATA_RVA, + 0, 0, 0, 0, dll_name_rva, base_ord, num_funcs, len(named), + RDATA_RVA + eat_off, RDATA_RVA + npt_off, RDATA_RVA + eot_off, + ) + for _n, ord_num, rva in exports: + struct.pack_into("<I", rdata, eat_off + 4 * (ord_num - base_ord), rva) + for idx, (nrva, ord_idx) in enumerate(name_rvas): + struct.pack_into("<I", rdata, npt_off + 4 * idx, nrva) + struct.pack_into("<H", rdata, eot_off + 2 * idx, ord_idx) + exports_size = (RDATA_RVA + len(rdata)) - exports_rva + + # Import directory + ILT + IAT + imports_rva = 0 + imports_size = 0 + if imports: + # Place IAT slots first at known RVAs requested by callers. + for _dll, items in imports: + for _imp_name, _imp_ord, slot_rva in items: + needed = (slot_rva - RDATA_RVA) + 16 + if len(rdata) < needed: + rdata.extend(b"\x00" * (needed - len(rdata))) + + desc_rva = align_rdata(4) + imports_rva = desc_rva + desc_count = len(imports) + 1 + rdata.extend(b"\x00" * (20 * desc_count)) + imports_size = 20 * desc_count + + for idx, (dll_name, items) in enumerate(imports): + dll_rva = RDATA_RVA + len(rdata) + rdata.extend(dll_name.encode("ascii") + b"\0") + ilt_rva = align_rdata(8) + rdata.extend(b"\x00" * (8 * (len(items) + 1))) + first_slot_rva = items[0][2] + for j, (imp_name, imp_ord, slot_rva) in enumerate(items): + assert slot_rva == first_slot_rva + 8 * j + if imp_ord is not None: + entry_val = (1 << 63) | imp_ord + else: + ibn_rva = align_rdata(2) + rdata.extend(b"\x00\x00" + imp_name.encode("ascii") + b"\0") + entry_val = ibn_rva + struct.pack_into("<Q", rdata, (ilt_rva - RDATA_RVA) + 8 * j, entry_val) + struct.pack_into("<Q", rdata, (slot_rva - RDATA_RVA), entry_val) + struct.pack_into( + "<IIIII", + rdata, + (desc_rva - RDATA_RVA) + 20 * idx, + ilt_rva, 0, 0, dll_rva, first_slot_rva, + ) + + pdata = bytearray() + spans = sorted(fn_spans) + for idx, (begin, end) in enumerate(spans): + if overlapping_pdata and idx == 0 and len(spans) > 1: + end = spans[1][0] + 4 + pdata.extend(struct.pack("<III", begin, end, unwind_rva)) + + text_flags = 0x60000020 if text_executable else 0x40000040 + sections = ( + (b".text", TEXT_RVA, bytes(text), text_flags), + (b".rdata", RDATA_RVA, bytes(rdata), 0x40000040), + (b".pdata", PDATA_RVA, bytes(pdata), 0x40000040), + ) + + entries = [(0, 0)] * 16 + if exports_size: + entries[0] = (exports_rva, exports_size) + if imports_size: + entries[1] = (imports_rva, imports_size) + entries[3] = (PDATA_RVA, len(pdata)) + + optional = struct.pack( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + 0x20B, 14, 0, len(text), 0, 0, TEXT_RVA, TEXT_RVA, + 0x140000000, SECTION_ALIGN, FILE_ALIGN, 6, 0, 0, 0, 6, 0, 0, + 0x4000, FILE_ALIGN, 0, 3, 0x8160, + 0x100000, SECTION_ALIGN, 0x100000, SECTION_ALIGN, 0, directories, + ) + optional += b"".join(struct.pack("<II", *entry) for entry in entries[:directories]) + + headers = b"" + body = b"" + offset = FILE_ALIGN + for name, va, data, flags in sections: + raw_size = max(FILE_ALIGN, -(-len(data) // FILE_ALIGN) * FILE_ALIGN) + headers += name.ljust(8, b"\0") + struct.pack( + "<IIIIIIHHI", len(data), va, raw_size, offset + len(body), 0, 0, 0, 0, flags, + ) + body += data.ljust(raw_size, b"\0") + + coff = struct.pack("<HHIIIHH", 0x8664, len(sections), 0, 0, 0, len(optional), 0x2022) + image = b"MZ" + bytes(58) + struct.pack("<I", 0x40) + b"PE\0\0" + coff + optional + headers + return image.ljust(FILE_ALIGN, b"\0") + body + + +def _make_direct_caller_and_callees() -> bytes: + """Build a caller invoking two distinct callees at 0x1080 and 0x10c0 (caller at 0x1000).""" + callee1_body = bytes.fromhex( + "49 89 08" # mov [r8], rcx + "49 89 50 08" # mov [r8+8], rdx + "48 89 c8" # mov rax, rcx + "48 29 d0" # sub rax, rdx + "48 83 c0 0b" # add rax, 11 + "49 89 40 10" # mov [r8+16], rax + ) + callee2_body = bytes.fromhex( + "48 89 c8" # mov rax, rcx + "48 31 d0" # xor rax, rdx + "48 83 c0 1d" # add rax, 29 + "49 89 40 10" # mov [r8+16], rax + ) + # Build caller with rel32 calls to 0x1080 and 0x10c0. + part1 = bytes.fromhex( + "48 89 cb" # mov rbx, rcx + "4c 89 c6" # mov rsi, r8 + "48 83 c1 07" # add rcx, 7 + "48 83 ea 03" # sub rdx, 3 + ) + call1_rva = TEXT_RVA + len(CALLER_PROLOGUE) + len(part1) + call1 = b"\xe8" + struct.pack("<i", (TEXT_RVA + 0x80) - (call1_rva + 5)) + part2 = bytes.fromhex( + "48 89 c1" # mov rcx, rax + "48 01 d9" # add rcx, rbx + "48 89 da" # mov rdx, rbx + "49 89 f0" # mov r8, rsi + ) + call2_rva = call1_rva + 5 + len(part2) + call2 = b"\xe8" + struct.pack("<i", (TEXT_RVA + 0xc0) - (call2_rva + 5)) + part3 = bytes.fromhex("48 01 d8") # add rax, rbx + caller = CALLER_PROLOGUE + part1 + call1 + part2 + call2 + part3 + CALLER_EPILOGUE + return build_synthetic_pe( + functions=[ + ("call_pair", 0x00, caller), + ("mix_args", 0x80, CALLEE_PROLOGUE + callee1_body + CALLEE_EPILOGUE), + ("mix_other", 0xc0, CALLEE_PROLOGUE + callee2_body + CALLEE_EPILOGUE), + ], + ) + + +def _make_provider_dll(*, export_name: str | None = "mix_args", ordinal: int = 1, executable: bool = True) -> bytes: + callee_body = bytes.fromhex("48 89 c8 48 83 c0 01") # mov rax, rcx; add rax, 1 + code = CALLEE_PROLOGUE + callee_body + CALLEE_EPILOGUE + return build_synthetic_pe( + functions=[(export_name, 0x00, code)], + exports=[(export_name, ordinal, TEXT_RVA)], + text_executable=executable, + ) + + +def _make_iat_caller_dll(*, dll_name: str, imp_name: str | None, imp_ord: int | None) -> tuple[bytes, int]: + slot_rva = RDATA_RVA + 0x200 + part1 = bytes.fromhex("48 89 cb 4c 89 c6") # mov rbx, rcx; mov rsi, r8 + call1_rva = TEXT_RVA + len(CALLER_PROLOGUE) + len(part1) + call1 = b"\xff\x15" + struct.pack("<i", slot_rva - (call1_rva + 6)) + part2 = bytes.fromhex("48 89 c1 48 89 da 49 89 f0") # mov rcx, rax; mov rdx, rbx; mov r8, rsi + call2_rva = call1_rva + 6 + len(part2) + call2 = b"\xff\x15" + struct.pack("<i", slot_rva - (call2_rva + 6)) + caller = CALLER_PROLOGUE + part1 + call1 + part2 + call2 + CALLER_EPILOGUE + raw = build_synthetic_pe( + functions=[("call_mix", 0x00, caller)], + imports=[(dll_name, [(imp_name, imp_ord, slot_rva)])], + ) + return raw, slot_rva + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CpuCallAotPositiveTests(unittest.TestCase): + def test_direct_calls_concrete_cpp_and_atomic_cli(self) -> None: + raw = _make_direct_caller_and_callees() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "caller.dll" + dll.write_bytes(raw) + expected = cpu_call_aot.translate(dll, "call_pair") + + self.assertIn("#include <cstdint>", expected) + self.assertIn("using word = std::uint64_t;", expected) + self.assertIn('extern "C" __declspec(dllexport) __declspec(noinline) word lifted_callee(', expected) + self.assertIn('extern "C" __declspec(dllexport) __declspec(noinline) word lifted_callee2(', expected) + self.assertIn('extern "C" __declspec(dllexport) __declspec(noinline) word lifted(', expected) + self.assertIn("rax = lifted_callee(rcx, rdx, r8);", expected) + self.assertIn("rax = lifted_callee2(rcx, rdx, r8);", expected) + self.assertIn("r8[2] = rax;", expected) + + nested_out = base / "nested" / "sub" / "lifted.cpp" + self.assertFalse(nested_out.parent.exists()) + + real_replace = os.replace + replaced: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaced.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + self.assertEqual(src_p.suffix, ".tmp") + return real_replace(src, dst) + + with mock.patch.object(cpu_call_aot.os, "replace", side_effect=tracking_replace): + rc, out, err = _run_main(cpu_call_aot, [str(dll), "call_pair", str(nested_out)]) + + self.assertIs(type(rc), int) + self.assertEqual(rc, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="utf-8"), expected) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["lifted.cpp"]) + self.assertEqual(len(replaced), 1) + self.assertEqual(replaced[0][1].resolve(), nested_out.resolve()) + + # Atomic overwrite via subprocess and argv=None forwarding. + nested_out.write_text("// stale\n", encoding="utf-8") + proc = _run_subprocess(str(dll), "call_pair", str(nested_out)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(nested_out.read_text(encoding="utf-8"), expected) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["lifted.cpp"]) + + nested_out.write_text("// stale-2\n", encoding="utf-8") + with mock.patch.object(sys, "argv", [str(TOOL), str(dll), "call_pair", str(nested_out)]): + rc_none, out_none, err_none = _run_main(cpu_call_aot, None) + self.assertEqual(rc_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="utf-8"), expected) + + def test_named_and_ordinal_iat_bindings_and_entrypoint(self) -> None: + named_raw, _ = _make_iat_caller_dll(dll_name="prov.dll", imp_name="mix_args", imp_ord=None) + ord_raw, _ = _make_iat_caller_dll(dll_name="ws2_32.dll", imp_name=None, imp_ord=77) + prov_named = _make_provider_dll(export_name="mix_args", ordinal=1) + prov_ord = _make_provider_dll(export_name=None, ordinal=77) + + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + caller_named = base / "caller_named.dll" + caller_named.write_bytes(named_raw) + prov_named_dll = base / "PROV.DLL" + prov_named_dll.write_bytes(prov_named) + out_named = base / "named.cpp" + + rc, out, err = _run_main( + cpu_call_aot, + [str(caller_named), "call_mix", str(out_named), "--bind", str(prov_named_dll), "mix_args"], + ) + self.assertEqual(rc, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + cpp_named = out_named.read_text(encoding="utf-8") + self.assertIn('extern "C" __declspec(dllimport) word mix_args(word, word, word*);', cpp_named) + self.assertIn("rax = ::mix_args(rcx, rdx, r8);", cpp_named) + + # System ordinal (#77 on ws2_32.dll) with --link-name keeps stored ordinal instead of pefile table name. + caller_ord = base / "caller_ord.dll" + caller_ord.write_bytes(ord_raw) + prov_ord_dll = base / "ws2_32.dll" + prov_ord_dll.write_bytes(prov_ord) + out_ord = base / "ord.cpp" + + proc = _run_subprocess( + str(caller_ord), "call_mix", str(out_ord), + "--bind", str(prov_ord_dll), "#77", "--link-name", "mix_args", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + cpp_ord = out_ord.read_text(encoding="utf-8") + self.assertIn('extern "C" __declspec(dllimport) word mix_args(word, word, word*);', cpp_ord) + self.assertIn("rax = ::mix_args(rcx, rdx, r8);", cpp_ord) + self.assertEqual([p.name for p in base.iterdir() if p.suffix == ".tmp"], []) + + # __main__ entrypoint raises SystemExit(0) and SystemExit(1) cleanly. + for argv, expected_exit, err_frag in ( + ([str(TOOL), str(caller_named), "call_mix", str(out_named), "--bind", str(prov_named_dll), "mix_args"], 0, ""), + ([str(TOOL), str(caller_named), "missing", str(out_named)], 1, "expected one local export"), + ): + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", argv), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, expected_exit) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + if err_frag: + self.assertIn(err_frag, stderr_m.getvalue()) + + +class CpuCallAotNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(cpu_call_aot, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_upfront_path_bind_and_link_name_guards(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "caller.dll" + image.write_bytes(b"synthetic-caller") + provider = base / "prov.dll" + provider.write_bytes(b"synthetic-provider") + provider_cpp = base / "prov.cpp" + provider_cpp.write_bytes(b"synthetic-provider-cpp") + dir_path = base / "dir_path" + dir_path.mkdir() + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp") + hardlink_image = base / "hardlink_img.cpp" + hardlink_image.hardlink_to(image) + hardlink_prov = base / "hardlink_prov.cpp" + hardlink_prov.hardlink_to(provider) + sub_dir = base / "sub" + sub_dir.mkdir() + out_dir = base / "dir_out.cpp" + out_dir.mkdir() + file_parent = base / "file_parent.txt" + file_parent.write_text("keep", encoding="utf-8") + absent_out = base / "absent_dir" / "lifted.cpp" + + with ( + mock.patch.object( + cpu_call_aot, + "translate", + side_effect=AssertionError("translate called past upfront validation"), + ), + mock.patch.object( + cpu_call_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called past upfront validation"), + ), + ): + for label, argv, frags in ( + ("missing_image", [str(base / "missing.dll"), "call_mix", str(absent_out)], ("image file not found",)), + ("dir_image", [str(dir_path), "call_mix", str(absent_out)], ("image path is a directory",)), + ("empty_image", ["", "call_mix", str(absent_out)], ("image path is a directory",)), + ("empty_export", [str(image), "", str(absent_out)], ("export name must not be empty",)), + ("blank_export", [str(image), " ", str(absent_out)], ("export name must not be empty",)), + ("non_cpp_suffix", [str(image), "call_mix", str(base / "out.txt")], (".cpp suffix",)), + ("empty_output", [str(image), "call_mix", ""], (".cpp suffix",)), + ("dot_cpp_only", [str(image), "call_mix", str(base / ".cpp")], (".cpp suffix",)), + ("output_is_dir", [str(image), "call_mix", str(out_dir)], ("output path is a directory",)), + ("parent_is_file", [str(image), "call_mix", str(file_parent / "lifted.cpp")], ("output parent is not a directory",)), + ("ancestor_is_file", [str(image), "call_mix", str(file_parent / "sub" / "lifted.cpp")], ("output parent is not a directory",)), + ("same_as_image", [str(same_cpp), "call_mix", str(same_cpp)], ("must not match input path",)), + ("resolve_as_image", [str(same_cpp), "call_mix", str(sub_dir / ".." / "same.cpp")], ("must not match input path",)), + ("hardlink_image", [str(image), "call_mix", str(hardlink_image)], ("must not match input path",)), + ("same_as_bind", [str(image), "call_mix", str(provider_cpp), "--bind", str(provider_cpp), "fn"], ("must not match input path",)), + ("resolve_as_bind", [str(image), "call_mix", str(sub_dir / ".." / "prov.cpp"), "--bind", str(provider_cpp), "fn"], ("must not match input path",)), + ("hardlink_bind", [str(image), "call_mix", str(hardlink_prov), "--bind", str(provider), "fn"], ("must not match input path",)), + ("missing_provider", [str(image), "call_mix", str(absent_out), "--bind", str(base / "missing_prov.dll"), "fn"], ("missing provider for missing_prov.dll!fn",)), + ("dir_provider", [str(image), "call_mix", str(absent_out), "--bind", str(dir_path), "fn"], ("missing provider for dir_path!fn",)), + ("empty_bind_provider", [str(image), "call_mix", str(absent_out), "--bind", "", "fn"], ("provider path and symbol must not be empty",)), + ("empty_bind_symbol", [str(image), "call_mix", str(absent_out), "--bind", str(provider), " "], ("provider path and symbol must not be empty",)), + ("link_name_no_bind", [str(image), "call_mix", str(absent_out), "--link-name", "mix_args"], ("link name requires a provider binding",)), + ("empty_link_name", [str(image), "call_mix", str(absent_out), "--bind", str(provider), "#77", "--link-name", ""], ("link name must not be empty",)), + ("blank_link_name", [str(image), "call_mix", str(absent_out), "--bind", str(provider), "#77", "--link-name", " "], ("link name must not be empty",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp") + self.assertEqual(image.read_bytes(), b"synthetic-caller") + self.assertEqual(provider.read_bytes(), b"synthetic-provider") + self.assertEqual(provider_cpp.read_bytes(), b"synthetic-provider-cpp") + + def test_output_symlink_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "caller.dll" + image.write_bytes(b"synthetic-caller") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="utf-8") + + with ( + mock.patch.object(Path, "is_symlink", return_value=True), + mock.patch.object( + cpu_call_aot, + "translate", + side_effect=AssertionError("translate called for symlink output"), + ), + mock.patch.object( + cpu_call_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + self._assert_clean_failure( + [str(image), "call_mix", str(out_dir / "mock_link.cpp")], + expected_code=1, + fragments=("output path must not be a symlink",), + check_subprocess=False, + ) + + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + cpu_call_aot, + "translate", + side_effect=AssertionError("translate called for symlink output"), + ), + mock.patch.object( + cpu_call_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), "call_mix", str(link)], + expected_code=1, + fragments=("output path must not be a symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + + def test_semantic_refusals_mixed_overlapping_non_pointer_r8_out_of_trace_and_non_exec(self) -> None: + # 1) Mixed direct + import calls and two distinct IAT slots in lift_body. + direct = b"\xe8\x00\x01\x00\x00" + imp1 = b"\xff\x15\x00\x02\x00\x00" + imp2 = b"\xff\x15\x08\x02\x00\x00" + for body, needle in ( + (direct + imp1, "mixed import and direct calls"), + (imp1 + direct, "mixed import and direct calls"), + (imp1 + imp2, "call to a second IAT slot"), + ): + with self.subTest(needle=needle): + with self.assertRaisesRegex(ValueError, needle): + cpu_call_aot.lift_body(0x1000, CALLER_PROLOGUE + body + CALLER_EPILOGUE, + caller=True, bind_import=lambda _slot: "mix_args") + + # 2) Reloading R8 from a non-pointer GPR (RBX overwritten by mov rbx, rcx). + bad_r8_code = CALLER_PROLOGUE + bytes.fromhex("48 89 cb 49 89 d8") + direct + CALLER_EPILOGUE + with self.assertRaisesRegex(ValueError, "R8 reloaded without the output pointer"): + cpu_call_aot.lift_body(0x1000, bad_r8_code, caller=True) + + # 3) Store outside trace ([r8+24]). + out_of_trace = CALLER_PROLOGUE + direct + bytes.fromhex("49 89 40 18") + CALLER_EPILOGUE + with self.assertRaisesRegex(ValueError, "store outside trace"): + cpu_call_aot.lift_body(0x1000, out_of_trace, caller=True) + + # 4) PE-backed refusals via CLI & direct API. + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + absent_out = base / "never_created" / "lifted.cpp" + + # Overlapping call target (call into caller itself). + call_self = b"\xe8" + struct.pack("<i", -5 - len(CALLER_PROLOGUE)) + overlap_dll = base / "overlap.dll" + overlap_dll.write_bytes(build_synthetic_pe( + functions=[("call_pair", 0x00, CALLER_PROLOGUE + call_self + CALLER_EPILOGUE)], + )) + self._assert_clean_failure( + [str(overlap_dll), "call_pair", str(absent_out)], + fragments=("overlapping call target",), + ) + + # Overlapping runtime-function intervals in .pdata. + pdata_overlap_dll = base / "pdata_overlap.dll" + pdata_overlap_dll.write_bytes(build_synthetic_pe( + functions=[ + ("call_pair", 0x00, CALLER_PROLOGUE + b"\xe8\x75\x00\x00\x00" + CALLER_EPILOGUE), + ("mix_args", 0x80, CALLEE_PROLOGUE + b"\x48\x89\xc8" + CALLEE_EPILOGUE), + ], + overlapping_pdata=True, + )) + self._assert_clean_failure( + [str(pdata_overlap_dll), "call_pair", str(absent_out)], + fragments=("invalid runtime-function interval",), + ) + + # Non-executable .text section in caller. + non_exec_caller = base / "non_exec_caller.dll" + non_exec_caller.write_bytes(build_synthetic_pe( + functions=[("call_pair", 0x00, CALLER_PROLOGUE + direct + CALLER_EPILOGUE)], + text_executable=False, + )) + self._assert_clean_failure( + [str(non_exec_caller), "call_pair", str(absent_out)], + fragments=("invalid file-backed range",), + ) + + # Direct call supplied with --bind. + direct_dll = base / "direct.dll" + direct_dll.write_bytes(_make_direct_caller_and_callees()) + prov_dll = base / "prov.dll" + prov_dll.write_bytes(_make_provider_dll()) + self._assert_clean_failure( + [str(direct_dll), "call_pair", str(absent_out), "--bind", str(prov_dll), "mix_args"], + fragments=("provider binding supplied for a direct call",), + ) + + # Non-executable provider export. + non_exec_prov = base / "non_exec_prov.dll" + non_exec_prov.write_bytes(_make_provider_dll(executable=False)) + iat_raw, slot_rva = _make_iat_caller_dll(dll_name="non_exec_prov.dll", imp_name="mix_args", imp_ord=None) + iat_dll = base / "iat_non_exec.dll" + iat_dll.write_bytes(iat_raw) + self._assert_clean_failure( + [str(iat_dll), "call_mix", str(absent_out), "--bind", str(non_exec_prov), "mix_args"], + fragments=("non-executable export for non_exec_prov.dll!mix_args",), + ) + + # Direct resolve_import() & translate() guards for empty link_name and non-file provider. + dir_prov = base / "dir_prov_sub" / "non_exec_prov.dll" + dir_prov.mkdir(parents=True) + with pefile.PE(str(iat_dll), fast_load=True) as pe: + for bad_link in ("", " "): + with self.assertRaisesRegex(ValueError, "link name must not be empty"): + cpu_call_aot.resolve_import(pe, slot_rva, non_exec_prov, "mix_args", link_name=bad_link) + with self.assertRaisesRegex(ValueError, "missing provider for"): + cpu_call_aot.resolve_import(pe, slot_rva, dir_prov, "mix_args") + + with self.assertRaisesRegex(ValueError, "link name must not be empty"): + cpu_call_aot.translate(iat_dll, "call_mix", binding=(str(prov_dll), "#77"), link_name=" ") + with self.assertRaisesRegex(ValueError, "missing provider for"): + cpu_call_aot.translate(iat_dll, "call_mix", binding=(str(base), "mix_args")) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual([p for p in base.iterdir() if p.suffix == ".tmp"], []) + + def test_atomic_write_failure_paths_and_argparse_errors(self) -> None: + raw = _make_direct_caller_and_callees() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "caller.dll" + dll.write_bytes(raw) + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "lifted.cpp" + out_cpp.write_text("original", encoding="utf-8") + + with mock.patch.object(cpu_call_aot.os, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(dll), "call_pair", str(out_cpp)], + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["lifted.cpp"]) + + with mock.patch.object(cpu_call_aot, "translate", return_value="bad-surrogate-\ud800"): + self._assert_clean_failure( + [str(dll), "call_pair", str(out_cpp)], + fragments=("surrogates not allowed",), + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["lifted.cpp"]) + + with mock.patch.object(cpu_call_aot.tempfile, "NamedTemporaryFile", side_effect=OSError("disk full")): + self._assert_clean_failure( + [str(dll), "call_pair", str(out_cpp)], + fragments=("disk full",), + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["lifted.cpp"]) + + for argv, frags in ( + ([], ("required",)), + ([str(dll)], ("required",)), + ([str(dll), "call_pair"], ("required",)), + ([str(dll), "call_pair", str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + raw = _make_direct_caller_and_callees() + prov_raw = _make_provider_dll() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "caller.dll" + dll.write_bytes(raw) + prov = base / "prov.dll" + prov.write_bytes(prov_raw) + dir_image = base / "dir_image" + dir_image.mkdir() + hardlink_prov = base / "hardlink_prov.cpp" + hardlink_prov.hardlink_to(prov) + file_parent = base / "file_parent.txt" + file_parent.write_text("keep", encoding="utf-8") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "lifted.cpp" + out_cpp.write_text("original", encoding="utf-8") + + iat_raw, slot_rva = _make_iat_caller_dll(dll_name="prov.dll", imp_name="mix_args", imp_ord=None) + iat_dll = base / "iat.dll" + iat_dll.write_bytes(iat_raw) + + def _check_drop_image_dir(mod) -> None: + _, _, err = _run_main(mod, [str(dir_image), "call_pair", str(out_dir / "a.cpp")]) + self.assertNotIn("image path is a directory", err.lower()) + + def _check_drop_image_file(mod) -> None: + with mock.patch.object(mod, "translate", side_effect=RuntimeError("reached_translate")): + with self.assertRaisesRegex(RuntimeError, "reached_translate"): + _run_main(mod, [str(base / "missing.dll"), "call_pair", str(out_dir / "a.cpp")]) + + def _check_drop_export(mod) -> None: + with mock.patch.object(mod, "translate", side_effect=RuntimeError("reached_translate")): + with self.assertRaisesRegex(RuntimeError, "reached_translate"): + _run_main(mod, [str(dll), " ", str(out_dir / "a.cpp")]) + + def _check_drop_cpp_suffix(mod) -> None: + code, _, err = _run_main(mod, [str(dll), "call_pair", str(base / "a.txt")]) + self.assertEqual(code, 0, err) + + def _check_drop_symlink(mod) -> None: + with mock.patch.object(Path, "is_symlink", return_value=True): + _, _, err = _run_main(mod, [str(dll), "call_pair", str(out_dir / "sym.cpp")]) + self.assertNotIn("output path must not be a symlink", err.lower()) + + def _check_drop_parent_file(mod) -> None: + _, _, err = _run_main(mod, [str(dll), "call_pair", str(file_parent / "lifted.cpp")]) + self.assertNotIn("output parent is not a directory", err.lower()) + + def _check_drop_samefile(mod) -> None: + with mock.patch.object(mod, "translate", side_effect=RuntimeError("reached_translate")): + with self.assertRaisesRegex(RuntimeError, "reached_translate"): + _run_main(mod, [str(dll), "call_pair", str(hardlink_prov), "--bind", str(prov), "mix_args"]) + + def _check_drop_empty_link_name(mod) -> None: + with pefile.PE(str(iat_dll), fast_load=True) as pe: + with self.assertRaisesRegex(ValueError, "unexpected link name"): + mod.resolve_import(pe, slot_rva, prov, "mix_args", link_name="") + + def _check_drop_tmp_unlink(mod) -> None: + with mock.patch.object(mod.os, "replace", side_effect=OSError("boom")): + code, _, _ = _run_main(mod, [str(dll), "call_pair", str(out_cpp)]) + self.assertEqual(code, 1) + leaked = [p for p in out_dir.iterdir() if p.suffix == ".tmp"] + self.assertTrue(leaked, "expected leaked .tmp file under mutation") + for p in leaked: + p.unlink(missing_ok=True) + + def _check_drop_r8_ptr(mod) -> None: + bad_r8_code = CALLER_PROLOGUE + bytes.fromhex("48 89 cb 49 89 d8 e8 00 01 00 00") + CALLER_EPILOGUE + text_out, _ = mod.lift_body(0x1000, bad_r8_code, caller=True) + self.assertIn("r8 = reinterpret_cast<word*>(rbx);", text_out) + + mutations = ( + ( + "drop_image_is_dir_guard", + ' if image.is_dir():\n raise IsADirectoryError(f"image path is a directory: {image}")\n', + " pass\n", + _check_drop_image_dir, + ), + ( + "drop_image_is_file_guard", + ' if not image.is_file():\n raise FileNotFoundError(f"image file not found: {image}")\n', + " pass\n", + _check_drop_image_file, + ), + ( + "drop_export_non_empty_guard", + ' if not isinstance(export, str) or not export.strip():\n raise ValueError("export name must not be empty")\n', + " pass\n", + _check_drop_export, + ), + ( + "drop_cpp_suffix_guard", + ' if output.suffix.lower() != ".cpp":\n raise ValueError(f"output path must have .cpp suffix: {output}")\n', + " pass\n", + _check_drop_cpp_suffix, + ), + ( + "drop_output_is_symlink_guard", + ' if output.is_symlink():\n raise ValueError(f"output path must not be a symlink: {output}")\n', + " pass\n", + _check_drop_symlink, + ), + ( + "drop_parent_is_file_guard", + ' if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()):\n' + ' raise NotADirectoryError(f"output parent is not a directory: {parent}")\n', + " pass\n", + _check_drop_parent_file, + ), + ( + "drop_samefile_guard", + " if out_resolved == input_path.resolve() or (output.exists() and input_path.samefile(output)):\n", + " if out_resolved == input_path.resolve():\n", + _check_drop_samefile, + ), + ( + "drop_empty_link_name_guard", + ' if link_name is not None and (not isinstance(link_name, str) or not link_name.strip()):\n raise ValueError("link name must not be empty")\n', + " pass\n", + _check_drop_empty_link_name, + ), + ( + "drop_tmp_unlink", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)\n", + " pass\n", + _check_drop_tmp_unlink, + ), + ( + "drop_r8_pointer_guard", + ' if r8_move and write == "r8" and source not in pointer:\n raise ValueError(f"R8 reloaded without the output pointer at RVA {rva:#x}")\n', + " pass\n", + _check_drop_r8_ptr, + ), + ) + + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"cpu_call_aot_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/cpu_chained_aot_cli_check.py b/tests/cpu_chained_aot_cli_check.py new file mode 100644 index 0000000000..f30dd1c4c2 --- /dev/null +++ b/tests/cpu_chained_aot_cli_check.py @@ -0,0 +1,459 @@ +"""Unit, CLI, path-guard, atomic-write, and mutation suite for tools/cpu_chained_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "cpu_chained_aot.py" +sys.path.insert(0, str(ROOT / "tools")) + +import cpu_chained_aot as tool # noqa: E402 + + +IMAGE_BASE = 0x140000000 +FILE_ALIGN = 0x200 +SECTION_ALIGN = 0x1000 +TEXT_RVA = 0x1000 +RDATA_RVA = 0x2000 +PDATA_RVA = 0x3000 +SECTION_SIZE = 0x1000 + + +def _rel32(next_ip: int, target: int) -> bytes: + return struct.pack("<i", target - next_ip) + + +def build_chained_pe(mode: str = "chained", *, export_name: str = "chained_fn", directories: int = 16, + callback_disp: int = 8) -> bytes: + """Build a minimal synthetic AMD64 PE32+ DLL exercising chained unwind ranges.""" + text = bytearray(SECTION_SIZE) + rdata = bytearray(SECTION_SIZE) + rdata_cursor = 0 + + def alloc_rdata(size: int, align: int = 4) -> int: + nonlocal rdata_cursor + rdata_cursor = (rdata_cursor + align - 1) & ~(align - 1) + rva = RDATA_RVA + rdata_cursor + rdata_cursor += size + return rva + + def put_rdata(rva: int, blob: bytes) -> None: + offset = rva - RDATA_RVA + rdata[offset:offset + len(blob)] = blob + + import_rva = 0 + import_size = 0 + free_slot_rva = 0 + if mode == "ffx_destroy": + dll_name = b"api-ms-win-crt-heap-l1-1-0.dll\0" + dll_rva = alloc_rdata(len(dll_name), 2) + put_rdata(dll_rva, dll_name) + hint_rva = alloc_rdata(2 + len(b"free\0"), 2) + put_rdata(hint_rva, b"\0\0free\0") + table = struct.pack("<QQ", hint_rva, 0) + ilt_rva = alloc_rdata(len(table), 8) + put_rdata(ilt_rva, table) + iat_rva = alloc_rdata(len(table), 8) + put_rdata(iat_rva, table) + free_slot_rva = iat_rva + import_size = 40 + import_rva = alloc_rdata(import_size, 4) + put_rdata(import_rva, struct.pack("<5I", ilt_rva, 0, 0, dll_rva, iat_rva)) + + if mode == "chained": + # Primary [0x1000..0x100d): test rcx, rcx; je 0x1020; mov rax, [rcx]; ret + # Child [0x1020..0x1023): xor eax, eax; ret + primary = bytearray.fromhex("48 85 C9 0F 84 17 00 00 00 48 8B 01 C3") + child = bytearray.fromhex("31 C0 C3") + text[0:len(primary)] = primary + text[0x20:0x20 + len(child)] = child + prim_begin, prim_end = TEXT_RVA, TEXT_RVA + len(primary) + child_begin, child_end = TEXT_RVA + 0x20, TEXT_RVA + 0x20 + len(child) + unwind_prim = alloc_rdata(4, 4) + put_rdata(unwind_prim, bytes([1, 0, 0, 0])) + unwind_child = alloc_rdata(16, 4) + put_rdata(unwind_child, bytes([(4 << 3) | 1, 0, 0, 0]) + struct.pack("<III", prim_begin, prim_end, unwind_prim)) + pdata = struct.pack("<IIIIII", prim_begin, prim_end, unwind_prim, child_begin, child_end, unwind_child) + elif mode == "partial": + # test rcx, rcx; je 0x1020; call qword ptr [rcx+8]; mov eax, 1; ret + primary = bytearray.fromhex("48 85 C9 0F 84 19 00 00 00 FF 51 08 B8 01 00 00 00 C3") + child = bytearray.fromhex("31 C0 C3") + text[0:len(primary)] = primary + text[0x22:0x22 + len(child)] = child + prim_begin, prim_end = TEXT_RVA, TEXT_RVA + len(primary) + child_begin, child_end = TEXT_RVA + 0x22, TEXT_RVA + 0x22 + len(child) + unwind_prim = alloc_rdata(4, 4) + put_rdata(unwind_prim, bytes([1, 0, 0, 0])) + unwind_child = alloc_rdata(16, 4) + put_rdata(unwind_child, bytes([(4 << 3) | 1, 0, 0, 0]) + struct.pack("<III", prim_begin, prim_end, unwind_prim)) + pdata = struct.pack("<IIIIII", prim_begin, prim_end, unwind_prim, child_begin, child_end, unwind_child) + elif mode == "callback": + # sub rsp, 28h; call qword ptr [rcx+disp]; add rsp, 28h; ret + primary = bytearray.fromhex("48 83 EC 28 FF 51") + bytes([callback_disp]) + bytearray.fromhex("48 83 C4 28 C3") + text[0:len(primary)] = primary + prim_begin, prim_end = TEXT_RVA, TEXT_RVA + len(primary) + unwind_prim = alloc_rdata(4, 4) + put_rdata(unwind_prim, bytes([1, 0, 0, 0])) + pdata = struct.pack("<III", prim_begin, prim_end, unwind_prim) + elif mode == "ffx_destroy": + # push rsi; push rdi; sub rsp, 28h; mov rsi, rdx; mov rdi, rcx; mov rax, [rcx]; call [rax+8]; + # mov [rsp+20h], rax; mov rcx, rdi; test rsi, rsi; je free_path; mov rdx, rsi; call [rsi+10h]; jmp done; + # free_path: call [rip+free_slot]; done: mov rax, [rsp+20h]; add rsp, 28h; pop rdi; pop rsi; ret + code = bytearray.fromhex( + "56 57 48 83 EC 28 " + "48 89 D6 48 89 CF 48 8B 01 FF 50 08 " + "48 89 44 24 20 48 89 F9 48 85 F6 " + "74 08 48 89 F2 FF 56 10 EB 06 " + ) + call_ip = TEXT_RVA + len(code) + code += b"\xFF\x15" + _rel32(call_ip + 6, free_slot_rva) + code += bytearray.fromhex("48 8B 44 24 20 48 83 C4 28 5F 5E C3") + text[0:len(code)] = code + prim_begin, prim_end = TEXT_RVA, TEXT_RVA + len(code) + unwind_prim = alloc_rdata(4, 4) + put_rdata(unwind_prim, bytes([1, 0, 0, 0])) + pdata = struct.pack("<III", prim_begin, prim_end, unwind_prim) + else: + raise ValueError(f"unknown mode {mode!r}") + + exp_dll_rva = alloc_rdata(len(b"chained_test.dll\0"), 2) + put_rdata(exp_dll_rva, b"chained_test.dll\0") + exp_name_bytes = export_name.encode("ascii") + b"\0" + exp_name_rva = alloc_rdata(len(exp_name_bytes), 2) + put_rdata(exp_name_rva, exp_name_bytes) + eat_rva = alloc_rdata(4, 4) + put_rdata(eat_rva, struct.pack("<I", TEXT_RVA)) + ent_rva = alloc_rdata(4, 4) + put_rdata(ent_rva, struct.pack("<I", exp_name_rva)) + eot_rva = alloc_rdata(2, 2) + put_rdata(eot_rva, struct.pack("<H", 0)) + export_size = 40 + export_rva = alloc_rdata(export_size, 4) + put_rdata( + export_rva, + struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, exp_dll_rva, 1, 1, 1, eat_rva, ent_rva, eot_rva), + ) + + pdata_sec = bytearray(SECTION_SIZE) + pdata_sec[0:len(pdata)] = pdata + + buf = bytearray(FILE_ALIGN + SECTION_SIZE * 3) + buf[0:2] = b"MZ" + pe_off = 0x80 + struct.pack_into("<I", buf, 60, pe_off) + buf[pe_off:pe_off + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_off + 4, 0x8664, 3, 0, 0, 0, 0xF0, 0x2022) + opt = pe_off + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, opt, + 0x20B, 14, 0, SECTION_SIZE, SECTION_SIZE * 2, 0, TEXT_RVA, TEXT_RVA, IMAGE_BASE, + SECTION_ALIGN, FILE_ALIGN, 6, 0, 0, 0, 6, 0, 0, 0x4000, FILE_ALIGN, 0, 3, 0x8160, + 0x100000, 0x1000, 0x100000, 0x1000, 0, directories, + ) + dd = opt + 112 + if directories > 0: + struct.pack_into("<II", buf, dd + 0 * 8, export_rva, export_size) + if directories > 1 and import_size: + struct.pack_into("<II", buf, dd + 1 * 8, import_rva, import_size) + if directories > 3: + struct.pack_into("<II", buf, dd + 3 * 8, PDATA_RVA, len(pdata)) + + sections_off = opt + 0xF0 + for idx, (sec_name, va, roff, chars) in enumerate(( + (b".text\0\0\0", TEXT_RVA, FILE_ALIGN, 0x60000020), + (b".rdata\0\0", RDATA_RVA, FILE_ALIGN + SECTION_SIZE, 0x40000040), + (b".pdata\0\0", PDATA_RVA, FILE_ALIGN + SECTION_SIZE * 2, 0x40000040), + )): + struct.pack_into( + "<8sIIIIIIHHI", buf, sections_off + idx * 40, + sec_name, SECTION_SIZE, va, SECTION_SIZE, roff, 0, 0, 0, 0, chars, + ) + + buf[FILE_ALIGN:FILE_ALIGN + SECTION_SIZE] = text + buf[FILE_ALIGN + SECTION_SIZE:FILE_ALIGN + SECTION_SIZE * 2] = rdata + buf[FILE_ALIGN + SECTION_SIZE * 2:FILE_ALIGN + SECTION_SIZE * 3] = pdata_sec + return bytes(buf) + + +def _run_main(argv): + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = tool.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *map(str, args)], + capture_output=True, + text=True, + timeout=30, + ) + + +class ChainedAotCliPositiveTests(unittest.TestCase): + def test_default_partial_callback_and_ffx_destroy(self): + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + img = root / "chained.dll" + img.write_bytes(build_chained_pe("chained")) + out = root / "nested" / "dir" / "out.cpp" + + code, stdout, stderr = _run_main([str(img), "chained_fn", str(out)]) + self.assertEqual(code, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn("2 owned ranges, 2 return paths, indirect stops: []", stdout) + cpp = out.read_text(encoding="utf-8") + self.assertIn("extern \"C\" __declspec(dllexport) word try_lifted(", cpp) + self.assertIn("load_always<word>((first + 0ull))", cpp) + + partial_img = root / "partial.dll" + partial_img.write_bytes(build_chained_pe("partial")) + partial_out = root / "partial.cpp" + proc = _run_subprocess(partial_img, "chained_fn", partial_out, "--partial") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("2 owned ranges, 1 return paths, indirect stops: [4105]", proc.stdout) + self.assertIn("return 0;", partial_out.read_text(encoding="utf-8")) + + cb_img = root / "callback.dll" + cb_img.write_bytes(build_chained_pe("callback", callback_disp=16)) + cb_out = root / "callback.cpp" + code, stdout, stderr = _run_main([str(cb_img), "chained_fn", str(cb_out), "--callback-offset", "0x10"]) + self.assertEqual(code, 0, stderr) + self.assertIn("try_lifted_callback(", cb_out.read_text(encoding="utf-8")) + self.assertIn("read_word(binding->table + 16ull)", cb_out.read_text(encoding="utf-8")) + + ffx_img = root / "ffx.dll" + ffx_img.write_bytes(build_chained_pe("ffx_destroy")) + ffx_out = root / "ffx.cpp" + code, stdout, stderr = _run_main([str(ffx_img), "chained_fn", str(ffx_out), "--ffx-destroy"]) + self.assertEqual(code, 0, stderr) + ffx_cpp = ffx_out.read_text(encoding="utf-8") + self.assertIn("try_destroy(", ffx_cpp) + self.assertIn("known->dealloc(", ffx_cpp) + self.assertIn("known->release(", ffx_cpp) + + +class ChainedAotCliRefusalAndAtomicTests(unittest.TestCase): + def _assert_clean_exit(self, argv, expected_code, fragment="", *, check_subprocess=True): + code, stdout, stderr = _run_main(argv) + self.assertEqual(code, expected_code, f"stdout={stdout!r} stderr={stderr!r}") + self.assertEqual(stdout, "") + self.assertNotIn("Traceback", stderr) + if fragment: + self.assertIn(fragment, stderr) + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + if fragment: + self.assertIn(fragment, proc.stderr) + + def test_translate_callback_offset_and_contract_guards(self): + with TemporaryDirectory() as tmp: + img = Path(tmp) / "chained.dll" + img.write_bytes(build_chained_pe("chained")) + for bad_offset in (False, True, -8, 4, 0x80000000, "8"): + with self.subTest(bad_offset=bad_offset): + with self.assertRaisesRegex(ValueError, "callback slot"): + tool.translate(img, "chained_fn", callback_offset=bad_offset) + with self.assertRaisesRegex(ValueError, "destroy contract"): + tool.translate(img, "chained_fn", partial=True, ffx_destroy=True) + with self.assertRaisesRegex(ValueError, "destroy contract"): + tool.translate(img, "chained_fn", callback_offset=8, ffx_destroy=True) + for bad_export in ("", " ", None): + with self.subTest(bad_export=bad_export): + with self.assertRaisesRegex(ValueError, "export name"): + tool.translate(img, bad_export) + + def test_hostile_cli_paths_and_refusals(self): + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + img = root / "chained.dll" + img.write_bytes(build_chained_pe("chained")) + img_dir = root / "img_dir" + img_dir.mkdir() + out_cpp = root / "out.cpp" + + self._assert_clean_exit([str(root / "missing.dll"), str(out_cpp), str(out_cpp)], 1, "not an existing file") + self._assert_clean_exit([str(img_dir), "chained_fn", str(out_cpp)], 1, "not an existing file") + self._assert_clean_exit([str(img), "", str(out_cpp)], 1, "export name") + self._assert_clean_exit([str(img), " ", str(out_cpp)], 1, "export name") + self._assert_clean_exit([str(img), "chained_fn", str(root / "bad.txt")], 1, ".cpp suffix") + self._assert_clean_exit([str(img), "chained_fn", str(root / "noext")], 1, ".cpp suffix") + + out_dir = root / "out_dir.cpp" + out_dir.mkdir() + self._assert_clean_exit([str(img), "chained_fn", str(out_dir)], 1, "is a directory") + + parent_file = root / "parent_file" + parent_file.write_bytes(b"keep-me") + self._assert_clean_exit([str(img), "chained_fn", str(parent_file / "child.cpp")], 1, "parent is not a directory") + self.assertEqual(parent_file.read_bytes(), b"keep-me") + + # Samefile / resolve collision directly and via hardlink + code, stdout, stderr = _run_main([str(img), "chained_fn", str(img.with_suffix(".cpp"))]) + self.assertEqual((code, stderr), (0, "")) + self.assertIn("2 owned ranges", stdout) + cpp_input = root / "input_alias.cpp" + cpp_input.write_bytes(build_chained_pe("chained")) + self._assert_clean_exit([str(cpp_input), "chained_fn", str(cpp_input)], 1, "collide with input image") + + hardlink_out = root / "hardlink.cpp" + hardlink_out.hardlink_to(img) + self._assert_clean_exit([str(img), "chained_fn", str(hardlink_out)], 1, "collide with input image") + + # Symlink output guard (real symlink if permitted + mock fallback) + real_target = root / "real_target.cpp" + real_target.write_text("do-not-overwrite\n", encoding="utf-8") + sym_out = root / "sym.cpp" + try: + sym_out.symlink_to(real_target) + created_sym = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_sym = False + if created_sym: + self._assert_clean_exit([str(img), "chained_fn", str(sym_out)], 1, "symbolic link") + else: + with mock.patch.object(Path, "is_symlink", autospec=True, + side_effect=lambda p: p.resolve() == sym_out.resolve()): + self._assert_clean_exit( + [str(img), "chained_fn", str(sym_out)], + 1, + "symbolic link", + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "do-not-overwrite\n") + + # Bad CLI callback-offset values + self._assert_clean_exit([str(img), "chained_fn", str(out_cpp), "--callback-offset", "-8"], 1, "callback slot") + self._assert_clean_exit([str(img), "chained_fn", str(out_cpp), "--callback-offset", "4"], 1, "callback slot") + self._assert_clean_exit([str(img), "chained_fn", str(out_cpp), "--callback-offset", "0x80000000"], 1, "callback slot") + self._assert_clean_exit([str(img), "chained_fn", str(out_cpp), "--callback-offset", "nope"], 2, "invalid") + + # Short directory PE refusal + short_img = root / "short.dll" + short_img.write_bytes(build_chained_pe("chained", directories=3)) + self._assert_clean_exit([str(short_img), "chained_fn", str(out_cpp)], 1, "runtime-function") + + def test_atomic_write_failures_preserve_prior_and_unlink_temps(self): + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + img = root / "chained.dll" + img.write_bytes(build_chained_pe("chained")) + out_dir = root / "atomic" + out_dir.mkdir() + out_cpp = out_dir / "lifted.cpp" + out_cpp.write_text("prior-contents\n", encoding="utf-8") + + with mock.patch.object(tool.os, "replace", side_effect=OSError("simulated replace fail")): + self._assert_clean_exit( + [str(img), "chained_fn", str(out_cpp)], + 1, + "simulated replace fail", + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "prior-contents\n") + self.assertEqual(list(out_dir.iterdir()), [out_cpp]) + + with mock.patch.object(tool.os, "fdopen", side_effect=OSError("simulated fdopen fail")): + self._assert_clean_exit( + [str(img), "chained_fn", str(out_cpp)], + 1, + "simulated fdopen fail", + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "prior-contents\n") + self.assertEqual(list(out_dir.iterdir()), [out_cpp]) + + +class ChainedAotCliMutationTests(unittest.TestCase): + def test_fast_self_mutations_are_killed(self): + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + img = root / "chained.dll" + img.write_bytes(build_chained_pe("chained")) + orig_translate = tool.translate + orig_validate = tool._validate_cli_inputs + mutants = [] + + def run_case(test_cls, method_name): + res = unittest.TestResult() + test_cls(method_name).run(res) + return res.wasSuccessful() + + # Mutant A: allow bool callback_offset + def mut_a(image, name, partial=False, callback_offset=None, ffx_destroy=False): + if isinstance(callback_offset, bool): + callback_offset = int(callback_offset) + return orig_translate(image, name, partial, callback_offset, ffx_destroy) + + with mock.patch.object(tool, "translate", side_effect=mut_a): + mutants.append(("allow_bool_callback_offset", + run_case(ChainedAotCliRefusalAndAtomicTests, + "test_translate_callback_offset_and_contract_guards"))) + + # Mutant B: skip .cpp suffix check + def mut_b(image, export, output): + if output.suffix.lower() != ".cpp": + return orig_validate(image, export, output.with_suffix(".cpp")) + return orig_validate(image, export, output) + + with mock.patch.object(tool, "_validate_cli_inputs", side_effect=mut_b): + mutants.append(("skip_cpp_suffix_guard", + run_case(ChainedAotCliRefusalAndAtomicTests, "test_hostile_cli_paths_and_refusals"))) + + # Mutant C: leave temp file behind on os.replace failure + def mut_c(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tool.tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent)) + with tool.os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + tool.os.replace(Path(tmp_name), path) + + with mock.patch.object(tool, "_write_atomic", side_effect=mut_c): + mutants.append(("leak_temp_on_replace_fail", + run_case(ChainedAotCliRefusalAndAtomicTests, + "test_atomic_write_failures_preserve_prior_and_unlink_temps"))) + + # Mutant D: skip samefile/collision guard + def mut_d(image, export, output): + if output.suffix.lower() == ".cpp" and output.exists() and output.samefile(image): + return + return orig_validate(image, export, output) + + with mock.patch.object(tool, "_validate_cli_inputs", side_effect=mut_d): + mutants.append(("skip_collision_guard", + run_case(ChainedAotCliRefusalAndAtomicTests, "test_hostile_cli_paths_and_refusals"))) + + # Mutant E: skip symlink guard + def mut_e(image, export, output): + if output.is_symlink(): + return + return orig_validate(image, export, output) + + with mock.patch.object(tool, "_validate_cli_inputs", side_effect=mut_e): + mutants.append(("skip_symlink_guard", + run_case(ChainedAotCliRefusalAndAtomicTests, "test_hostile_cli_paths_and_refusals"))) + + for name, passed in mutants: + self.assertFalse(passed, f"mutant {name} unexpectedly survived") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/cpu_leaf_aot_cli_check.py b/tests/cpu_leaf_aot_cli_check.py new file mode 100644 index 0000000000..54f4421c36 --- /dev/null +++ b/tests/cpu_leaf_aot_cli_check.py @@ -0,0 +1,691 @@ +#!/usr/bin/env python3 +"""Standalone pure-Python synthetic PE32+ unit, CLI, path-guard, atomic-write, and mutation suite for tools/cpu_leaf_aot.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +import pefile + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "cpu_leaf_aot.py" +sys.path.insert(0, str(TOOLS_DIR)) + +import cpu_leaf_aot # noqa: E402 + + +SECTION_ALIGN = 0x1000 +FILE_ALIGN = 0x200 +TEXT_RVA = 0x1000 +RDATA_RVA = 0x2000 +PDATA_RVA = 0x3000 + +# Exercises mov eax, ecx (89 c8), unsigned cmp imm8 + jb, signed cmp imm32 + jle, +# add/sub imm8/imm32, jmp short, mov [rdx], eax, and ret. +RICH_LEAF_CODE = bytes.fromhex( + "89 c8" # mov eax, ecx + "83 f8 05 72 05" # cmp eax, 5; jb +5 -> sub + "83 c0 03" # add eax, 3 + "eb 03" # jmp short +3 -> cmp imm32 + "83 e8 07" # sub eax, 7 + "3d 9c ff ff ff" # cmp eax, -100 + "7e 07" # jle +7 -> add imm32 + "2d 04 01 00 00" # sub eax, 260 + "eb 05" # jmp short +5 -> store + "05 00 02 00 00" # add eax, 512 + "89 02" # mov [rdx], eax + "c3" # ret +) + +SIMPLE_LEAF_CODE = bytes.fromhex("8b c1 83 c0 01 89 02 c3") + + +def build_synthetic_leaf_dll( + *, + code: bytes = SIMPLE_LEAF_CODE, + export: str = "leaf", + machine: int = 0x8664, + magic: int = 0x20B, + directories: int = 16, + duplicate_export: bool = False, + forwarder: bytes | None = None, + executable_text: bool = True, +) -> bytes: + """Build a minimal synthetic PE32+ (or deliberately malformed) DLL image in memory.""" + rdata = bytearray() + rdata += bytes([1, 0, 0, 0]) # UNWIND_INFO v1, no prolog, no codes + exports_rva = RDATA_RVA + len(rdata) + + if forwarder is not None: + fwd_rva = RDATA_RVA + len(rdata) + 40 + 4 + 4 + 2 + names_rva = fwd_rva + len(forwarder) + 1 + dll_name_rva = names_rva + len(export) + 1 + rdata += struct.pack( + "<IIHHIIIIIII", + 0, 0, 0, 0, dll_name_rva, 1, 1, 1, + exports_rva + 40, exports_rva + 44, exports_rva + 48, + ) + rdata += struct.pack("<IIH", fwd_rva, names_rva, 0) + rdata += forwarder + b"\0" + export.encode("ascii") + b"\0x.dll\0" + elif duplicate_export: + names_rva = RDATA_RVA + len(rdata) + 40 + 8 + 8 + 4 + name_bytes = export.encode("ascii") + b"\0" + dll_name_rva = names_rva + len(name_bytes) + rdata += struct.pack( + "<IIHHIIIIIII", + 0, 0, 0, 0, dll_name_rva, 1, 2, 2, + exports_rva + 40, exports_rva + 48, exports_rva + 56, + ) + rdata += struct.pack("<II", TEXT_RVA, TEXT_RVA) + rdata += struct.pack("<II", names_rva, names_rva) + rdata += struct.pack("<HH", 0, 1) + rdata += name_bytes + b"x.dll\0" + else: + names_rva = RDATA_RVA + len(rdata) + 40 + 4 + 4 + 2 + dll_name_rva = names_rva + len(export) + 1 + rdata += struct.pack( + "<IIHHIIIIIII", + 0, 0, 0, 0, dll_name_rva, 1, 1, 1, + exports_rva + 40, exports_rva + 44, exports_rva + 48, + ) + rdata += struct.pack("<IIH", TEXT_RVA, names_rva, 0) + rdata += export.encode("ascii") + b"\0x.dll\0" + + pdata = struct.pack("<III", TEXT_RVA, TEXT_RVA + len(code), RDATA_RVA) + text_chars = 0x60000020 if executable_text else 0x40000040 + sections = ( + (b".text", TEXT_RVA, code, text_chars), + (b".rdata", RDATA_RVA, bytes(rdata), 0x40000040), + (b".pdata", PDATA_RVA, pdata, 0x40000040), + ) + + entries = [(0, 0)] * 16 + entries[0] = (exports_rva, len(rdata) - 4) + entries[3] = (PDATA_RVA, len(pdata)) + + optional = struct.pack( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + magic, 14, 0, len(code), 0, 0, TEXT_RVA, TEXT_RVA, + 0x140000000, SECTION_ALIGN, FILE_ALIGN, 6, 0, 0, 0, 6, 0, 0, + 0x4000, FILE_ALIGN, 0, 3, 0x8160, + 0x100000, SECTION_ALIGN, 0x100000, SECTION_ALIGN, 0, directories, + ) + optional += b"".join(struct.pack("<II", *entry) for entry in entries[:directories]) + + headers = b"" + body = b"" + offset = FILE_ALIGN + for name, va, data, flags in sections: + raw_size = -(-len(data) // FILE_ALIGN) * FILE_ALIGN + headers += name.ljust(8, b"\0") + struct.pack( + "<IIIIIIHHI", len(data), va, raw_size, offset + len(body), 0, 0, 0, 0, flags, + ) + body += data.ljust(raw_size, b"\0") + + coff = struct.pack("<HHIIIHH", machine, len(sections), 0, 0, 0, len(optional), 0x2022) + image = b"MZ" + bytes(58) + struct.pack("<I", 0x40) + b"PE\0\0" + coff + optional + headers + return image.ljust(FILE_ALIGN, b"\0") + body + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class CpuLeafAotPositiveTests(unittest.TestCase): + def test_translate_semantics_and_bytes_like_inputs(self) -> None: + expected = "\n".join([ + "#include <cstdint>", + 'extern "C" __declspec(dllexport) std::uint32_t lifted(std::uint32_t input, std::uint32_t* output) {', + " std::uint32_t eax = input;", + " if (eax < 5u) goto loc_c;", + " eax += 3u;", + " goto loc_f;", + "loc_c:", + " eax -= 7u;", + "loc_f:", + " if (static_cast<std::int32_t>(eax) <= static_cast<std::int32_t>(4294967196u)) goto loc_1d;", + " eax -= 260u;", + " goto loc_22;", + "loc_1d:", + " eax += 512u;", + "loc_22:", + " *output = eax;", + " return eax;", + "}", + "", + ]) + for payload in (RICH_LEAF_CODE, bytearray(RICH_LEAF_CODE), memoryview(RICH_LEAF_CODE)): + with self.subTest(payload_type=type(payload).__name__): + self.assertEqual(cpu_leaf_aot.translate(0x1000, payload), expected) + + simple_cpp = cpu_leaf_aot.translate(0, SIMPLE_LEAF_CODE) + self.assertIn("eax += 1u;", simple_cpp) + self.assertIn("*output = eax;", simple_cpp) + self.assertIn("return eax;", simple_cpp) + + def test_pe_helpers_atomic_cli_nested_dirs_and_entrypoint(self) -> None: + raw = build_synthetic_leaf_dll(code=RICH_LEAF_CODE, export="branch_leaf") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "leaf.dll" + dll.write_bytes(raw) + + rva, code = cpu_leaf_aot.function_bytes(dll, "branch_leaf") + self.assertEqual(rva, TEXT_RVA) + self.assertEqual(code, RICH_LEAF_CODE) + with pefile.PE(str(dll), fast_load=True) as pe: + self.assertEqual(cpu_leaf_aot.export_rva(pe, "branch_leaf"), TEXT_RVA) + self.assertEqual(cpu_leaf_aot.export_rva(pe, 1), TEXT_RVA) + self.assertEqual(cpu_leaf_aot.bounded_code(pe, TEXT_RVA), RICH_LEAF_CODE) + + expected_cpp = cpu_leaf_aot.translate(rva, code) + nested_out = base / "nested" / "dir" / "lifted.cpp" + self.assertFalse(nested_out.parent.exists()) + + real_replace = os.replace + replaced: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaced.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + self.assertEqual(src_p.suffix, ".tmp") + return real_replace(src, dst) + + with mock.patch.object(cpu_leaf_aot.os, "replace", side_effect=tracking_replace): + code_rc, out, err = _run_main(cpu_leaf_aot, [str(dll), "branch_leaf", str(nested_out)]) + + self.assertIs(type(code_rc), int) + self.assertEqual(code_rc, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="utf-8"), expected_cpp) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["lifted.cpp"]) + self.assertEqual(len(replaced), 1) + self.assertEqual(replaced[0][1].resolve(), nested_out.resolve()) + + # Atomic overwrite replaces stale output with 0 leftover .tmp files. + nested_out.write_text("// stale\n", encoding="utf-8") + proc = _run_subprocess(str(dll), "branch_leaf", str(nested_out)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(nested_out.read_text(encoding="utf-8"), expected_cpp) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["lifted.cpp"]) + + # argv=None forwards sys.argv cleanly. + nested_out.write_text("// stale-again\n", encoding="utf-8") + with mock.patch.object(sys, "argv", [str(TOOL), str(dll), "branch_leaf", str(nested_out)]): + rc_none, out_none, err_none = _run_main(cpu_leaf_aot, None) + self.assertEqual(rc_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="utf-8"), expected_cpp) + + # __main__ entrypoint raises SystemExit(0) on success and SystemExit(1) cleanly on failure. + for argv, expected_exit, err_frag in ( + ([str(TOOL), str(dll), "branch_leaf", str(nested_out)], 0, ""), + ([str(TOOL), str(dll), "missing_export", str(nested_out)], 1, "expected one local export"), + ): + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", argv), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, expected_exit) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + if err_frag: + self.assertIn(err_frag, stderr_m.getvalue()) + + +class CpuLeafAotNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(cpu_leaf_aot, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_upfront_path_and_export_guards(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "leaf.dll" + image.write_bytes(b"synthetic-image") + dir_image = base / "dir_image" + dir_image.mkdir() + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + sub_dir = base / "sub" + sub_dir.mkdir() + out_dir = base / "dir_out.cpp" + out_dir.mkdir() + file_parent = base / "file_parent.txt" + file_parent.write_text("keep-parent", encoding="utf-8") + absent_out = base / "absent_dir" / "lifted.cpp" + + with ( + mock.patch.object( + cpu_leaf_aot, + "function_bytes", + side_effect=AssertionError("function_bytes called past upfront validation"), + ), + mock.patch.object( + cpu_leaf_aot, + "translate", + side_effect=AssertionError("translate called past upfront validation"), + ), + mock.patch.object( + cpu_leaf_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called past upfront validation"), + ), + ): + for label, argv, frags in ( + ("missing_image", [str(base / "missing.dll"), "leaf", str(absent_out)], ("image file not found",)), + ("dir_image", [str(dir_image), "leaf", str(absent_out)], ("image path is a directory",)), + ("empty_image", ["", "leaf", str(absent_out)], ("image path is a directory",)), + ("empty_export", [str(image), "", str(absent_out)], ("export name must not be empty",)), + ("blank_export", [str(image), " ", str(absent_out)], ("export name must not be empty",)), + ("non_cpp_suffix", [str(image), "leaf", str(base / "out.txt")], (".cpp suffix",)), + ("empty_output", [str(image), "leaf", ""], (".cpp suffix",)), + ("dot_cpp_only", [str(image), "leaf", str(base / ".cpp")], (".cpp suffix",)), + ("output_is_dir", [str(image), "leaf", str(out_dir)], ("output path is a directory",)), + ("parent_is_file", [str(image), "leaf", str(file_parent / "lifted.cpp")], ("output parent is not a directory",)), + ("ancestor_is_file", [str(image), "leaf", str(file_parent / "sub" / "lifted.cpp")], ("output parent is not a directory",)), + ("same_path", [str(same_cpp), "leaf", str(same_cpp)], ("must not match input image",)), + ("resolve_alias", [str(same_cpp), "leaf", str(sub_dir / ".." / "same.cpp")], ("must not match input image",)), + ("hardlink_samefile", [str(image), "leaf", str(hardlink_cpp)], ("must not match input image",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp") + self.assertEqual(image.read_bytes(), b"synthetic-image") + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-parent") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "leaf.dll" + image.write_bytes(b"synthetic-image") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="utf-8") + + with ( + mock.patch.object(Path, "is_symlink", return_value=True), + mock.patch.object( + cpu_leaf_aot, + "function_bytes", + side_effect=AssertionError("function_bytes called for symlink output"), + ), + mock.patch.object( + cpu_leaf_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + self._assert_clean_failure( + [str(image), "leaf", str(out_dir / "mock_link.cpp")], + expected_code=1, + fragments=("output path must not be a symlink",), + check_subprocess=False, + ) + + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + cpu_leaf_aot, + "function_bytes", + side_effect=AssertionError("function_bytes called for symlink output"), + ), + mock.patch.object( + cpu_leaf_aot, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), "leaf", str(link)], + expected_code=1, + fragments=("output path must not be a symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_pe_and_translation_cli_errors_create_no_dirs_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + absent_out = base / "never_created" / "lifted.cpp" + + cases = ( + ("corrupt_pe", b"not a PE32+ image", "leaf", ("dos header",)), + ("x86_pe32", build_synthetic_leaf_dll(machine=0x014C, magic=0x10B), "leaf", ("expected amd64 pe32+",)), + ("missing_pdata", build_synthetic_leaf_dll(directories=3), "leaf", ("no runtime-function directory",)), + ("missing_export", build_synthetic_leaf_dll(), "other", ("expected one local export for other",)), + ("duplicate_export", build_synthetic_leaf_dll(duplicate_export=True), "leaf", ("expected one local export for leaf",)), + ("forwarder_export", build_synthetic_leaf_dll(forwarder=b"other.fn"), "leaf", ("expected one local export for leaf",)), + ("non_exec_section", build_synthetic_leaf_dll(executable_text=False), "leaf", ("invalid file-backed range",)), + ("bad_prologue", build_synthetic_leaf_dll(code=b"\x90\xc3"), "leaf", ("expected mov eax, ecx",)), + ) + + for label, payload, export_name, frags in cases: + with self.subTest(case=label): + dll = base / f"{label}.dll" + dll.write_bytes(payload) + self._assert_clean_failure( + [str(dll), export_name, str(absent_out)], + expected_code=1, + fragments=frags, + ) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual([p for p in base.iterdir() if p.suffix == ".tmp"], []) + + def test_atomic_write_failure_paths_leave_zero_tmp_files(self) -> None: + raw = build_synthetic_leaf_dll() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "leaf.dll" + dll.write_bytes(raw) + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "lifted.cpp" + out_cpp.write_text("original", encoding="utf-8") + + # 1) os.replace failure preserves original file and unlinks sibling temp. + with mock.patch.object(cpu_leaf_aot.os, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(dll), "leaf", str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["lifted.cpp"]) + + # 2) UTF-8 encoding failure (lone surrogate) unlinks sibling temp and preserves original. + with mock.patch.object(cpu_leaf_aot, "translate", return_value="bad-surrogate-\ud800"): + self._assert_clean_failure( + [str(dll), "leaf", str(out_cpp)], + expected_code=1, + fragments=("surrogates not allowed",), + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["lifted.cpp"]) + + # 3) Write-time OSError inside handle unlinks sibling temp and preserves original. + with mock.patch.object(cpu_leaf_aot.tempfile, "NamedTemporaryFile", side_effect=OSError("disk full")): + self._assert_clean_failure( + [str(dll), "leaf", str(out_cpp)], + expected_code=1, + fragments=("disk full",), + check_subprocess=False, + ) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["lifted.cpp"]) + + def test_translate_input_validation_and_argparse_errors(self) -> None: + for bad_start in (True, False, -1, -0x1000, 1.5, "0x1000", None): + with self.subTest(bad_start=bad_start): + with self.assertRaisesRegex(ValueError, "start RVA"): + cpu_leaf_aot.translate(bad_start, SIMPLE_LEAF_CODE) + + for bad_code in ("8bc1c3", None, 123, [0x8B, 0xC1, 0xC3]): + with self.subTest(bad_code=bad_code): + with self.assertRaisesRegex(ValueError, "bytes-like code"): + cpu_leaf_aot.translate(0x1000, bad_code) + + for body, msg in ( + ("90 c3", "unsupported or incomplete instruction at RVA 0x1002"), + ("eb 01 83 c0 05 c3", "branch into an instruction at RVA 0x1005"), + ("eb 7f c3", "expected forward in-function branch at RVA 0x1002"), + ("89 02", "missing terminal return at RVA 0x1004"), + ): + with self.subTest(body=body): + with self.assertRaisesRegex(ValueError, msg): + cpu_leaf_aot.translate(0x1000, bytes.fromhex("8b c1 " + body)) + + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "leaf.dll" + dll.write_bytes(b"synthetic") + for argv, frags in ( + ([], ("required",)), + ([str(dll)], ("required",)), + ([str(dll), "leaf"], ("required",)), + ([str(dll), "leaf", str(base / "out.cpp"), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + raw = build_synthetic_leaf_dll() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dll = base / "leaf.dll" + dll.write_bytes(raw) + dir_image = base / "dir_image" + dir_image.mkdir() + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(dll) + file_parent = base / "file_parent.txt" + file_parent.write_text("keep", encoding="utf-8") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "lifted.cpp" + out_cpp.write_text("original", encoding="utf-8") + + def _check_drop_dir_image(mod) -> None: + _, _, err = _run_main(mod, [str(dir_image), "leaf", str(out_dir / "a.cpp")]) + self.assertNotIn("image path is a directory", err.lower()) + + def _check_drop_image_is_file(mod) -> None: + with mock.patch.object(mod, "function_bytes", side_effect=RuntimeError("reached_function_bytes")): + with self.assertRaisesRegex(RuntimeError, "reached_function_bytes"): + _run_main(mod, [str(base / "missing.dll"), "leaf", str(out_dir / "a.cpp")]) + + def _check_drop_export_guard(mod) -> None: + with mock.patch.object(mod, "function_bytes", side_effect=RuntimeError("reached_function_bytes")): + with self.assertRaisesRegex(RuntimeError, "reached_function_bytes"): + _run_main(mod, [str(dll), " ", str(out_dir / "a.cpp")]) + + def _check_drop_cpp_suffix(mod) -> None: + code, _, err = _run_main(mod, [str(dll), "leaf", str(out_dir / "a.txt")]) + self.assertEqual(code, 0, err) + + def _check_drop_symlink_guard(mod) -> None: + with mock.patch.object(Path, "is_symlink", return_value=True): + _, _, err = _run_main(mod, [str(dll), "leaf", str(out_dir / "sym.cpp")]) + self.assertNotIn("output path must not be a symlink", err.lower()) + + def _check_drop_parent_file_guard(mod) -> None: + _, _, err = _run_main(mod, [str(dll), "leaf", str(file_parent / "lifted.cpp")]) + self.assertNotIn("output parent is not a directory", err.lower()) + + def _check_drop_samefile_guard(mod) -> None: + with mock.patch.object(mod, "function_bytes", side_effect=RuntimeError("reached_function_bytes")): + with self.assertRaisesRegex(RuntimeError, "reached_function_bytes"): + _run_main(mod, [str(dll), "leaf", str(hardlink_cpp)]) + + def _check_drop_tmp_unlink(mod) -> None: + with mock.patch.object(mod.os, "replace", side_effect=OSError("boom")): + code, _, _ = _run_main(mod, [str(dll), "leaf", str(out_cpp)]) + self.assertEqual(code, 1) + leaked = [p for p in out_dir.iterdir() if p.suffix == ".tmp"] + self.assertTrue(leaked, "expected leaked .tmp file under mutation") + for p in leaked: + p.unlink(missing_ok=True) + + def _check_drop_bool_start_guard(mod) -> None: + self.assertIn("return eax;", mod.translate(True, SIMPLE_LEAF_CODE)) + + def _check_drop_bytes_like_guard(mod) -> None: + with self.assertRaises(AttributeError): + mod.translate(0x1000, memoryview(SIMPLE_LEAF_CODE)) + + mutations = ( + ( + "drop_image_is_dir_guard", + ' if image.is_dir():\n raise IsADirectoryError(f"image path is a directory: {image}")\n', + " pass\n", + _check_drop_dir_image, + ), + ( + "drop_image_is_file_guard", + ' if not image.is_file():\n raise FileNotFoundError(f"image file not found: {image}")\n', + " pass\n", + _check_drop_image_is_file, + ), + ( + "drop_export_non_empty_guard", + ' if not isinstance(export, str) or not export.strip():\n raise ValueError("export name must not be empty")\n', + " pass\n", + _check_drop_export_guard, + ), + ( + "drop_cpp_suffix_guard", + ' if output.suffix.lower() != ".cpp":\n raise ValueError(f"output path must have .cpp suffix: {output}")\n', + " pass\n", + _check_drop_cpp_suffix, + ), + ( + "drop_output_is_symlink_guard", + ' if output.is_symlink():\n raise ValueError(f"output path must not be a symlink: {output}")\n', + " pass\n", + _check_drop_symlink_guard, + ), + ( + "drop_parent_is_file_guard", + ' if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()):\n' + ' raise NotADirectoryError(f"output parent is not a directory: {parent}")\n', + " pass\n", + _check_drop_parent_file_guard, + ), + ( + "drop_samefile_guard", + " if output.resolve() == image.resolve() or (output.exists() and image.samefile(output)):\n", + " if output.resolve() == image.resolve():\n", + _check_drop_samefile_guard, + ), + ( + "drop_tmp_unlink", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)\n", + " pass\n", + _check_drop_tmp_unlink, + ), + ( + "drop_bool_start_guard", + " if isinstance(start, bool) or not isinstance(start, int):\n", + " if not isinstance(start, int):\n", + _check_drop_bool_start_guard, + ), + ( + "drop_bytes_like_guard", + " if not isinstance(code, bytes):\n" + " try:\n" + " code = memoryview(code).tobytes()\n" + " except TypeError as exc:\n" + ' raise ValueError(f"expected bytes-like code, got {type(code).__name__}") from exc\n', + " pass\n", + _check_drop_bytes_like_guard, + ), + ) + + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"cpu_leaf_aot_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/cpu_ranges_check.py b/tests/cpu_ranges_check.py new file mode 100644 index 0000000000..773b0c96d6 --- /dev/null +++ b/tests/cpu_ranges_check.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Standalone synthetic PE32+ unit, bounds, unwind-chain, and mutation suite for tools/cpu_ranges.py.""" + +from __future__ import annotations + +from pathlib import Path +import struct +import sys +import types +import unittest +from unittest import mock + +import pefile + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "cpu_ranges.py" +sys.path.insert(0, str(ROOT / "tools")) + +import cpu_ranges # noqa: E402 + + +IMAGE_BASE = 0x180000000 +RAW_OFFSET = 0x200 +SECTION_ALIGN = 0x1000 +TEXT_RVA = 0x1000 +RDATA_RVA = 0x2000 +SECTION_SIZE = 0x1000 + + +def build_pe( + *, + text_bytes: bytes | None = None, + text_vsize: int = SECTION_SIZE, + text_rsize: int = SECTION_SIZE, + pdata_records: list[tuple[int, int, int]] | None = None, + rdata_blobs: dict[int, bytes] | None = None, + pdata_rva_override: int | None = None, + pdata_size_override: int | None = None, + num_data_dirs: int = 16, +) -> pefile.PE: + """Construct an in-memory AMD64 PE32+ object for cpu_ranges unit tests.""" + text = bytearray(SECTION_SIZE) + if text_bytes: + text[:len(text_bytes)] = text_bytes + rdata = bytearray(SECTION_SIZE) + + rdata_cursor = 0 + + def alloc_rdata(size: int, align: int = 4) -> int: + nonlocal rdata_cursor + rdata_cursor = (rdata_cursor + align - 1) & ~(align - 1) + rva = RDATA_RVA + rdata_cursor + rdata_cursor += size + return rva + + def put_rdata(rva: int, blob: bytes) -> None: + offset = rva - RDATA_RVA + rdata[offset:offset + len(blob)] = blob + + if rdata_blobs: + for rva, blob in rdata_blobs.items(): + put_rdata(rva, blob) + rdata_cursor = max(rdata_cursor, (rva - RDATA_RVA) + len(blob)) + + pdata_rva = 0 + pdata_size = 0 + if pdata_records is not None: + pdata_size = 12 * len(pdata_records) + pdata_rva = alloc_rdata(max(pdata_size, 4), 4) + for idx, (begin, end, info) in enumerate(pdata_records): + put_rdata(pdata_rva + idx * 12, struct.pack("<III", begin, end, info)) + + if pdata_rva_override is not None: + pdata_rva = pdata_rva_override + if pdata_size_override is not None: + pdata_size = pdata_size_override + + buf = bytearray(RAW_OFFSET + SECTION_SIZE * 2) + buf[0:2] = b"MZ" + pe_off = 0x80 + struct.pack_into("<I", buf, 60, pe_off) + buf[pe_off:pe_off + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_off + 4, 0x8664, 2, 0, 0, 0, 0xF0, 0x2022) + opt = pe_off + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + 0x20B, 14, 0, SECTION_SIZE, SECTION_SIZE, 0, TEXT_RVA, TEXT_RVA, + IMAGE_BASE, SECTION_ALIGN, 0x200, 6, 0, 0, 0, 6, 0, 0, + 0x3000, RAW_OFFSET, 0, 3, 0x160, + 0x100000, 0x1000, 0x100000, 0x1000, 0, num_data_dirs, + ) + dd = opt + 112 + if num_data_dirs >= 4 and (pdata_rva or pdata_size): + struct.pack_into("<II", buf, dd + 3 * 8, pdata_rva, pdata_size) + + sections_off = opt + 0xF0 + sections = [ + (b".text\0\0\0", text_vsize, TEXT_RVA, text_rsize, RAW_OFFSET, 0x60000020), + (b".rdata\0\0", SECTION_SIZE, RDATA_RVA, SECTION_SIZE, RAW_OFFSET + SECTION_SIZE, 0x40000040), + ] + for idx, (name, vsize, va, rsize, roff, chars) in enumerate(sections): + struct.pack_into( + "<8sIIIIIIHHI", + buf, + sections_off + idx * 40, + name, vsize, va, rsize, roff, 0, 0, 0, 0, chars, + ) + + buf[RAW_OFFSET:RAW_OFFSET + SECTION_SIZE] = text + buf[RAW_OFFSET + SECTION_SIZE:RAW_OFFSET + SECTION_SIZE * 2] = rdata + return pefile.PE(data=bytes(buf), fast_load=True) + + +def _chained_blob(version: int, code_count: int, parent: tuple[int, int, int]) -> bytes: + header = bytes([version | (4 << 3), 0, code_count, 0]) + slots = ((code_count + 1) & ~1) * 2 + return header + (b"\x00" * slots) + struct.pack("<III", *parent) + + +class CpuRangesPositiveTests(unittest.TestCase): + def test_image_bytes_exec_and_non_exec_sections(self) -> None: + text_pattern = bytes((i * 11 + 3) & 0xFF for i in range(64)) + rdata_pattern = b"CONST-DATA-12345" + with build_pe(text_bytes=text_pattern, rdata_blobs={RDATA_RVA + 0x40: rdata_pattern}) as pe: + self.assertEqual(cpu_ranges.image_bytes(pe, TEXT_RVA, 32, executable=True), text_pattern[:32]) + self.assertEqual(cpu_ranges.image_bytes(pe, TEXT_RVA + 8, 16, executable=False), text_pattern[8:24]) + self.assertEqual(cpu_ranges.image_bytes(pe, RDATA_RVA + 0x40, len(rdata_pattern)), rdata_pattern) + + def test_single_range_and_chained_unwind_v1_v2_odd_even_sorting(self) -> None: + primary_info = RDATA_RVA + 0x00 + chain_v1_odd = RDATA_RVA + 0x10 + chain_v2_even = RDATA_RVA + 0x30 + chain_v1_even0 = RDATA_RVA + 0x50 + chain_v2_odd3 = RDATA_RVA + 0x70 + + primary = (0x1200, 0x1240, primary_info) + frag_before = (0x1050, 0x1070, chain_v1_odd) + frag_after = (0x1300, 0x1320, chain_v2_even) + frag_grandchild = (0x1400, 0x1410, chain_v2_odd3) + other_fn = (0x1100, 0x1120, primary_info) + other_child = (0x1150, 0x1160, chain_v1_even0) + + blobs = { + primary_info: b"\x01\x00\x00\x00", + # v1, odd CountOfUnwindCodes=1 -> 4 bytes of codes -> trailer at +8 + chain_v1_odd: _chained_blob(1, 1, primary), + # v2, even CountOfUnwindCodes=2 -> 4 bytes of codes -> trailer at +8 + chain_v2_even: _chained_blob(2, 2, primary), + # v1, even CountOfUnwindCodes=0 -> 0 bytes of codes -> trailer at +4 + chain_v1_even0: _chained_blob(1, 0, other_fn), + # v2, odd CountOfUnwindCodes=3 -> 8 bytes of codes -> trailer at +12 (2-hop chain) + chain_v2_odd3: _chained_blob(2, 3, frag_before), + } + records = sorted([frag_before, other_fn, other_child, primary, frag_after, frag_grandchild]) + with build_pe(pdata_records=records, rdata_blobs=blobs) as pe: + self.assertEqual( + cpu_ranges.function_ranges(pe, 0x1200), + [(0x1050, 0x1070), (0x1200, 0x1240), (0x1300, 0x1320), (0x1400, 0x1410)], + ) + self.assertEqual( + cpu_ranges.function_ranges(pe, 0x1100), + [(0x1100, 0x1120), (0x1150, 0x1160)], + ) + + +class CpuRangesNegativeAndMutationTests(unittest.TestCase): + def test_image_bytes_refusals_exec_bounds_and_types(self) -> None: + with build_pe(text_vsize=0x200, text_rsize=0x100, rdata_blobs={RDATA_RVA: b"DATA"}) as pe: + # Non-executable section refused when executable=True. + with self.assertRaisesRegex(ValueError, "invalid file-backed range"): + cpu_ranges.image_bytes(pe, RDATA_RVA, 4, executable=True) + + # Out-of-bounds beyond min(Misc_VirtualSize, SizeOfRawData) and unmapped RVA. + with self.assertRaisesRegex(ValueError, "invalid file-backed range"): + cpu_ranges.image_bytes(pe, TEXT_RVA, 0x101, executable=True) + with self.assertRaisesRegex(ValueError, "invalid file-backed range"): + cpu_ranges.image_bytes(pe, 0x5000, 4) + + # Bool, non-int, negative RVA, and non-positive size refused. + for bad_rva in (True, False, -1, -0x1000, 1.5, "0x1000", None): + with self.subTest(bad_rva=bad_rva): + with self.assertRaises(ValueError): + cpu_ranges.image_bytes(pe, bad_rva, 4) + for bad_size in (True, False, 0, -1, -16, 1.5, "4", None): + with self.subTest(bad_size=bad_size): + with self.assertRaises(ValueError): + cpu_ranges.image_bytes(pe, TEXT_RVA, bad_size) + + # rva < section.VirtualAddress refused even if get_section_by_rva returns a section. + fake_sec = types.SimpleNamespace( + VirtualAddress=0x2000, + Characteristics=0x60000020, + Misc_VirtualSize=0x1000, + SizeOfRawData=0x1000, + get_data=lambda _rva, length: b"\x90" * length, + ) + with mock.patch.object(pe, "get_section_by_rva", return_value=fake_sec): + with self.assertRaisesRegex(ValueError, "invalid file-backed range"): + cpu_ranges.image_bytes(pe, 0x1000, 4) + + def test_function_ranges_refusals(self) -> None: + # 1) Invalid entry types / negative entry / missing runtime-function directory. + with build_pe(pdata_records=None) as pe_no_pdata: + for bad_entry in (True, False, -1, -0x100, 1.5, "0x1000", None): + with self.subTest(bad_entry=bad_entry): + with self.assertRaises(ValueError): + cpu_ranges.function_ranges(pe_no_pdata, bad_entry) + with self.assertRaisesRegex(ValueError, "no runtime-function directory"): + cpu_ranges.function_ranges(pe_no_pdata, TEXT_RVA) + + with build_pe(pdata_records=None, pdata_rva_override=RDATA_RVA, pdata_size_override=0) as pe_zero_size: + with self.assertRaisesRegex(ValueError, "no runtime-function directory"): + cpu_ranges.function_ranges(pe_zero_size, TEXT_RVA) + + with build_pe(pdata_records=None, num_data_dirs=3) as pe_short_dd: + with self.assertRaisesRegex(ValueError, "no runtime-function directory"): + cpu_ranges.function_ranges(pe_short_dd, TEXT_RVA) + + # 2) Truncated (.pdata Size % 12 != 0), out-of-order, overlapping, inverted, unaligned info. + with build_pe(pdata_records=[(0x1000, 0x1010, RDATA_RVA)], rdata_blobs={RDATA_RVA: b"\x01\x00\x00\x00"}, + pdata_size_override=10) as pe_trunc: + with self.assertRaisesRegex(ValueError, "incomplete runtime-function record"): + cpu_ranges.function_ranges(pe_trunc, 0x1000) + + for label, bad_records in ( + ("overlapping", [(0x1000, 0x1020, RDATA_RVA), (0x1010, 0x1030, RDATA_RVA)]), + ("out_of_order", [(0x1020, 0x1030, RDATA_RVA), (0x1000, 0x1010, RDATA_RVA)]), + ("empty_interval", [(0x1000, 0x1000, RDATA_RVA)]), + ("unaligned_info", [(0x1000, 0x1010, RDATA_RVA + 2)]), + ): + with self.subTest(case=label): + with build_pe(pdata_records=bad_records, rdata_blobs={RDATA_RVA: b"\x01\x00\x00\x00"}) as pe: + with self.assertRaisesRegex(ValueError, "invalid runtime-function interval"): + cpu_ranges.function_ranges(pe, 0x1000) + + # 3) Unsupported unwind header / truncated trailer / dangling parent / cyclic unwind chain / missing entry. + with build_pe(pdata_records=[(0x1000, 0x1010, RDATA_RVA)], + rdata_blobs={RDATA_RVA: bytes([3 | (4 << 3), 0, 0, 0]) + bytes(12)}) as pe_bad_ver: + with self.assertRaisesRegex(ValueError, "unsupported chained unwind header"): + cpu_ranges.function_ranges(pe_bad_ver, 0x1000) + + with build_pe(pdata_records=[(0x1000, 0x1010, RDATA_RVA)], + rdata_blobs={RDATA_RVA: bytes([1 | (5 << 3), 0, 0, 0]) + bytes(12)}) as pe_bad_flags: + with self.assertRaisesRegex(ValueError, "unsupported chained unwind header"): + cpu_ranges.function_ranges(pe_bad_flags, 0x1000) + + # Truncated chained trailer right at end of .rdata section. + trunc_info = RDATA_RVA + SECTION_SIZE - 8 + with build_pe(pdata_records=[(0x1000, 0x1010, trunc_info)], + rdata_blobs={trunc_info: bytes([1 | (4 << 3), 0, 0, 0])}) as pe_trunc_trailer: + with self.assertRaisesRegex(ValueError, "invalid file-backed range"): + cpu_ranges.function_ranges(pe_trunc_trailer, 0x1000) + + # Dangling parent not in .pdata. + with build_pe(pdata_records=[(0x1000, 0x1010, RDATA_RVA)], + rdata_blobs={RDATA_RVA: _chained_blob(1, 0, (0x1500, 0x1510, RDATA_RVA))}) as pe_dangling: + with self.assertRaisesRegex(ValueError, "invalid unwind chain"): + cpu_ranges.function_ranges(pe_dangling, 0x1000) + + # Cyclic unwind chain (A -> B -> A). + info_a = RDATA_RVA + 0x00 + info_b = RDATA_RVA + 0x20 + rec_a = (0x1000, 0x1010, info_a) + rec_b = (0x1020, 0x1030, info_b) + with build_pe(pdata_records=[rec_a, rec_b], + rdata_blobs={info_a: _chained_blob(1, 0, rec_b), + info_b: _chained_blob(1, 0, rec_a)}) as pe_cycle: + with self.assertRaisesRegex(ValueError, "invalid unwind chain"): + cpu_ranges.function_ranges(pe_cycle, 0x1000) + + # Missing entry in valid .pdata. + with build_pe(pdata_records=[(0x1000, 0x1010, RDATA_RVA)], + rdata_blobs={RDATA_RVA: b"\x01\x00\x00\x00"}) as pe_valid: + with self.assertRaisesRegex(ValueError, "no unique function interval"): + cpu_ranges.function_ranges(pe_valid, 0x1100) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + + with build_pe( + pdata_records=[(0x1050, 0x1070, RDATA_RVA + 0x10), (0x1100, 0x1120, RDATA_RVA), (0x1200, 0x1240, RDATA_RVA)], + rdata_blobs={ + RDATA_RVA: b"\x01\x00\x00\x00", + RDATA_RVA + 0x10: _chained_blob(1, 1, (0x1200, 0x1240, RDATA_RVA)), + }, + ) as pe_valid, build_pe( + pdata_records=[(0x1000, 0x1020, RDATA_RVA), (0x1010, 0x1030, RDATA_RVA)], + rdata_blobs={RDATA_RVA: b"\x01\x00\x00\x00"}, + ) as pe_overlap: + def _check_bool_mut(mod) -> None: + self.assertEqual(len(mod.image_bytes(pe_valid, TEXT_RVA, True)), 1) + + def _check_rva_lt_va_mut(mod) -> None: + fake_sec = types.SimpleNamespace( + VirtualAddress=0x2000, + Characteristics=0x60000020, + Misc_VirtualSize=0x2000, + SizeOfRawData=0x2000, + get_data=lambda _rva, length: b"\x90" * length, + ) + with mock.patch.object(pe_valid, "get_section_by_rva", return_value=fake_sec): + self.assertEqual(len(mod.image_bytes(pe_valid, 0x1000, 4)), 4) + + def _check_exec_mut(mod) -> None: + self.assertEqual(len(mod.image_bytes(pe_valid, RDATA_RVA, 4, executable=True)), 4) + + def _check_odd_align_mut(mod) -> None: + with self.assertRaisesRegex(ValueError, "invalid unwind chain"): + mod.function_ranges(pe_valid, 0x1200) + + def _check_overlap_mut(mod) -> None: + self.assertEqual(mod.function_ranges(pe_overlap, 0x1000), [(0x1000, 0x1020)]) + + mutations = ( + ( + "drop_bool_guard", + " if isinstance(value, bool) or not isinstance(value, int):\n", + " if not isinstance(value, int):\n", + _check_bool_mut, + ), + ( + "drop_rva_lt_section_va_guard", + " if (not section or rva < section.VirtualAddress\n", + " if (not section\n", + _check_rva_lt_va_mut, + ), + ( + "drop_executable_guard", + " or (executable and not section.Characteristics & 0x20000000)\n", + " or False\n", + _check_exec_mut, + ), + ( + "drop_odd_unwind_align", + " trailer = info + 4 + ((header[2] + 1) & ~1) * 2\n", + " trailer = info + 4 + header[2] * 2\n", + _check_odd_align_mut, + ), + ( + "drop_overlap_guard", + " if begin < previous or end <= begin or info % 4:\n", + " if end <= begin or info % 4:\n", + _check_overlap_mut, + ), + ) + + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"cpu_ranges_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 84ff8c3f52..d57366ae69 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -26,15 +26,18 @@ float check_startup_sampler_heap(ID3D12Device* device, const char* vertex_path, void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array = false, UINT levels = 1, bool one_dimensional = false, bool two_dimensional = false, - UINT first_mip = 0, UINT view_levels = 0); + UINT first_mip = 0, UINT view_levels = 0, UINT mip_base = 4, bool cube = false); void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, bool depth16, std::uint32_t words[64], bool array = false); int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, - const std::uint32_t expected[4]); + const std::uint32_t expected[4], unsigned coverage = 1); +// Queries colour formats and returns "typed_uav_load_refused" when one has no typed UAV load, before any draw. +// Returns nullptr only when the refusal helper itself accepts a cleared UAV_TYPED_LOAD bit. +const char* check_startup_image_store_typed_load(ID3D12Device* device); void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, std::uint32_t* words, UINT width = 1, UINT height = 1, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE, - UINT vertices = 3); + UINT vertices = 3, const std::uint32_t* constants = nullptr); void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path, const std::uint32_t* entry, UINT entry_count, std::uint32_t* words, UINT width = 1, UINT height = 1); @@ -46,6 +49,13 @@ void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); +int check_compute_waterfall_oracle(ID3D12Device* device, const char* shader_path); +struct ComputeReadbackProgram { + Microsoft::WRL::ComPtr<ID3D12RootSignature> signature; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pipeline; +}; +ComputeReadbackProgram load_compute_store_program(ID3D12Device* device, const char* shader); +void check_compute_store_reference(ID3D12Device* device, const ComputeReadbackProgram& program, const char* reference); void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference); bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, const char* vs_path, const char* ps_path); @@ -72,6 +82,7 @@ bool check_mesh_entry_draw(ID3D12Device*, const char*, const char*, const char*, const char* amplification = nullptr); bool check_mesh_amplified_draw(ID3D12Device*, const char* amplification, const char* mesh, const char* pixel, const char* fixture); +bool check_mesh_shader_pipeline(ID3D12Device* device, bool force_fallback); bool check_mesh_heap_sampler_draw(ID3D12Device*, const char* mesh, const char* pixel, const char* fixture); void check_mesh_fallback_draw(ID3D12Device* device, const char* compute, const char* vertex, const char* pixel, const char* fixture, MeshDrawMode mode = MeshDrawMode::color, @@ -80,8 +91,11 @@ void check_texture_mips(ID3D12Device* device); void check_depth_mask_draw(ID3D12Device*, const char*, const char*, const char*, bool); void check_sampled_coverage(ID3D12Device*, const char*, const char*); void check_dual_pixel(ID3D12Device*, const char*, const char*, bool); -struct PixelMismatch : std::runtime_error { - PixelMismatch() : std::runtime_error("AOT color export differs from CPU reference") {} +struct ReadbackMismatch : std::runtime_error { + using std::runtime_error::runtime_error; +}; +struct PixelMismatch : ReadbackMismatch { + PixelMismatch() : ReadbackMismatch("AOT color export differs from CPU reference") {} }; void check_translated_pixel(ID3D12Device* device, const char* path, bool swapRB, const char* reference = nullptr, @@ -93,7 +107,7 @@ void check_pixel_quad_lod(ID3D12Device* device, const char* shader, const char* bool allowUpperRawLodStep = false); void check_pixel_mip_clamp(ID3D12Device* device, const char* shader, unsigned expectedLevel); void check_pixel_mip_blend(ID3D12Device* device, const char* shader, float clamp, float tolerance); -void check_pixel_compare(ID3D12Device* device, const char* shader, const char* reference); +void check_pixel_compare(ID3D12Device* device, const char* shader, const char* reference, bool twoMips = false); void check_pixel_gather(ID3D12Device* device, const char* shader, const char* reference); void check_pixel_compare_gather(ID3D12Device* device, const char* shader, const char* reference, const char* sampler_line, const char* vsPath = nullptr); diff --git a/tests/dxc_cache_check.py b/tests/dxc_cache_check.py index 8ec04d0dea..f867c0c7d3 100644 --- a/tests/dxc_cache_check.py +++ b/tests/dxc_cache_check.py @@ -33,9 +33,17 @@ class Rig: def __init__(self, root): self.root = Path(root) self.cache = str(self.root / "cache") - self.compiler = str(self.root / "fakedxc") - Path(self.compiler).write_text(FAKE) - os.chmod(self.compiler, os.stat(self.compiler).st_mode | stat.S_IEXEC) + if os.name == "nt": + # Windows cannot execute a shebang script: the compiler is a .cmd wrapper + # that runs the fake script with this interpreter. + script = self.root / "fakedxc_impl.py" + script.write_text(FAKE) + self.compiler = str(self.root / "fakedxc.cmd") + Path(self.compiler).write_text('@"%s" "%s" %%*\n' % (sys.executable, script)) + else: + self.compiler = str(self.root / "fakedxc") + Path(self.compiler).write_text(FAKE) + os.chmod(self.compiler, os.stat(self.compiler).st_mode | stat.S_IEXEC) self.n = 0 def compile(self, source, extra=(), cache=True, check=False, out=None): diff --git a/tests/dxc_cache_unit_check.py b/tests/dxc_cache_unit_check.py new file mode 100644 index 0000000000..de5a1b7107 --- /dev/null +++ b/tests/dxc_cache_unit_check.py @@ -0,0 +1,413 @@ +"""Unit and temp-copy mutation suite for tools/dxc_cache.py.""" +import importlib.util +import json +import os +import stat +import subprocess +import sys +import tempfile +from pathlib import Path +from unittest import mock + +TOOLS_DIR = Path(__file__).resolve().parents[1] / "tools" +DXC_CACHE_PATH = TOOLS_DIR / "dxc_cache.py" + +FAKE_DXC = """#!/usr/bin/env python3 +import sys +args = sys.argv[1:] +fo = args[args.index("-Fo") + 1] +with open(fo + ".calls", "a", encoding="utf-8") as handle: + handle.write("x") +src = open(args[-1], "rb").read() +if b"BROKEN" in src: + sys.stderr.write("error in " + args[-1] + "\\n") + sys.exit(3) +with open(fo, "wb") as handle: + handle.write(b"FO:" + src + b":" + fo.encode()) +if "-Fc" in args: + fc = args[args.index("-Fc") + 1] + with open(fc, "wb") as handle: + handle.write(b"FC:" + src + b":" + fc.encode()) + sys.stdout.write("asm " + fc + "\\n") +if "-Fd" in args: + fd = args[args.index("-Fd") + 1] + with open(fd, "wb") as handle: + handle.write(b"FD:" + src) + sys.stdout.write("pdb " + fd + "\\n") +sys.stdout.write("compiled " + args[-1] + " -> " + fo + "\\n") +""" + + +def _load_module(path, name="dxc_cache_sut"): + spec = importlib.util.spec_from_file_location(name, str(path)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _make_rig(root): + root = Path(root) + if os.name == "nt": + impl = root / "fake_dxc_impl.py" + impl.write_text(FAKE_DXC, encoding="utf-8") + compiler = root / "fake_dxc.cmd" + compiler.write_text(f'@"{sys.executable}" "{impl}" %*\n', encoding="utf-8") + else: + compiler = root / "fake_dxc" + compiler.write_text(FAKE_DXC, encoding="utf-8") + os.chmod(compiler, os.stat(compiler).st_mode | stat.S_IEXEC) + return str(compiler) + + +def _calls(root): + return sum(len(p.read_text(encoding="utf-8")) for p in Path(root).glob("*.calls")) + + +def _tmp_files(directory): + return [p for p in Path(directory).iterdir() if p.name.startswith(".tmp-") or p.name.endswith(".tmp")] + + +def _make_symlink(target, link_path): + try: + os.symlink(target, link_path) + return True + except (OSError, NotImplementedError): + return False + + +def _test_atomic_restore_and_zero_temps(mod, root, compiler): + cache_dir = Path(root) / "cache_atomic" + src = Path(root) / "shader.hlsl" + src.write_bytes(b"float4 main() : SV_Target { return 1; }") + out1 = Path(root) / "out1.cso" + out2 = Path(root) / "out2.cso" + out2.write_bytes(b"STALE_OUT2") + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + res1 = mod.run_dxc(compiler, ["-T", "ps_6_0", "-Fo", str(out1), str(src)], + capture_output=True, text=True, check=True) + res2 = mod.run_dxc(compiler, ["-T", "ps_6_0", "-Fo", str(out2), str(src)], + capture_output=True, text=True, check=True) + assert res1.returncode == 0 and res2.returncode == 0 + assert _calls(root) == 1, f"expected 1 real compile, got {_calls(root)}" + assert out2.read_bytes().startswith(b"FO:") + assert b"STALE_OUT2" not in out2.read_bytes() + assert str(out2) in res2.stdout + assert not _tmp_files(root), f"leftover temp files in output dir: {_tmp_files(root)}" + assert not _tmp_files(cache_dir), f"leftover temp files in cache dir: {_tmp_files(cache_dir)}" + + +def _test_replace_fail_preserves_output_and_cleans_temps(mod, root, compiler): + cache_dir = Path(root) / "cache_replace_fail" + src = Path(root) / "replace.hlsl" + src.write_bytes(b"void main(){}") + warm = Path(root) / "warm.cso" + target = Path(root) / "preserve.cso" + target.write_bytes(b"ORIGINAL_BYTES") + + # Direct _write_file failure via os.replace. + with mock.patch.object(mod.os, "replace", side_effect=OSError("boom")): + try: + mod._write_file(str(target), b"NEW_BYTES") + except OSError: + pass + else: + raise AssertionError("_write_file did not propagate os.replace OSError") + assert target.read_bytes() == b"ORIGINAL_BYTES", "prior output corrupted on os.replace failure" + assert not _tmp_files(root), f"leftover temp files after os.replace failure: {_tmp_files(root)}" + + # Direct _write_file failure via write TypeError. + try: + mod._write_file(str(target), "not-bytes") + except TypeError: + pass + else: + raise AssertionError("_write_file did not reject non-bytes write") + assert target.read_bytes() == b"ORIGINAL_BYTES" + assert not _tmp_files(root), f"leftover temp files after write failure: {_tmp_files(root)}" + + # Cache-hit path through run_dxc when os.replace fails. + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(warm), str(src)], capture_output=True, check=True) + with mock.patch.object(mod.os, "replace", side_effect=OSError("disk full")): + try: + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(target), str(src)], capture_output=True, check=True) + except OSError: + pass + else: + raise AssertionError("cache-hit run_dxc did not propagate os.replace OSError") + assert target.read_bytes() == b"ORIGINAL_BYTES", "cache-hit os.replace fail altered prior output" + assert not _tmp_files(root), f"leftover temp files after cache-hit replace failure: {_tmp_files(root)}" + + +def _test_fo_dir_and_symlink_refusal(mod, root, compiler): + out_dir = Path(root) / "dir_target" + out_dir.mkdir() + try: + mod._write_file(str(out_dir), b"data") + except OSError: + pass + else: + raise AssertionError("_write_file must refuse directory target") + assert not _tmp_files(root) + + victim = Path(root) / "victim.cso" + victim.write_bytes(b"VICTIM_INTACT") + link_out = Path(root) / "link_out.cso" + real_symlink = _make_symlink(str(victim), str(link_out)) + if real_symlink: + try: + mod._write_file(str(link_out), b"OVERWRITE") + except OSError: + pass + else: + raise AssertionError("_write_file must refuse symlink target") + assert victim.read_bytes() == b"VICTIM_INTACT", "symlink target file was modified" + assert not _tmp_files(root) + else: + with mock.patch.object(mod.os.path, "islink", side_effect=lambda p: os.fspath(p) == str(link_out)): + try: + mod._write_file(str(link_out), b"OVERWRITE") + except OSError: + pass + else: + raise AssertionError("_write_file must refuse symlink target (mocked)") + assert not _tmp_files(root) + + # Cache-hit run_dxc with -Fo pointing at symlink must refuse and preserve victim. + cache_dir = Path(root) / "cache_link_fo" + src = Path(root) / "link_fo.hlsl" + src.write_bytes(b"void main(){}") + warm = Path(root) / "warm_fo.cso" + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(warm), str(src)], capture_output=True, check=True) + if real_symlink: + try: + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(link_out), str(src)], + capture_output=True, check=True) + except OSError: + pass + else: + raise AssertionError("cache-hit run_dxc must refuse symlink -Fo") + assert victim.read_bytes() == b"VICTIM_INTACT" + assert not _tmp_files(root) + # -Fo pointing to directory bypasses cache via _plan and fails in compiler. + before = _calls(root) + res_dir = mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(out_dir), str(src)], capture_output=True) + assert res_dir.returncode != 0 + assert _calls(root) == before + 1, "-Fo directory must bypass cache to compiler" + assert len(list(cache_dir.glob("*.json"))) == 1 + + +def _test_symlink_and_file_cache_dir_fallback(mod, root, compiler): + src = Path(root) / "fallback.hlsl" + src.write_bytes(b"void main(){}") + + # 1. File-backed cache_dir (and nested child under file) -> uncached fallback without crashing. + file_cache = Path(root) / "file_cache" + file_cache.write_bytes(b"NOT_A_DIR") + for cache_val in (str(file_cache), str(file_cache / "nested")): + before = _calls(root) + with mock.patch.dict(os.environ, {mod.ENV_VAR: cache_val}): + r1 = mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "fb1.cso"), str(src)], + capture_output=True, check=True) + r2 = mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "fb2.cso"), str(src)], + capture_output=True, check=True) + assert r1.returncode == 0 and r2.returncode == 0 + assert _calls(root) == before + 2, f"file-backed cache_dir {cache_val} must run uncached" + assert file_cache.read_bytes() == b"NOT_A_DIR" + + # 2. Symlink-backed cache_dir -> uncached fallback, real target stays empty. + real_cache = Path(root) / "real_cache_target" + real_cache.mkdir() + link_cache = Path(root) / "link_cache" + if _make_symlink(str(real_cache), str(link_cache)): + before = _calls(root) + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(link_cache)}): + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "sl1.cso"), str(src)], + capture_output=True, check=True) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "sl2.cso"), str(src)], + capture_output=True, check=True) + assert _calls(root) == before + 2, "symlink cache_dir must run uncached" + assert list(real_cache.iterdir()) == [], "symlink cache_dir wrote to target" + + # Trailing slash on symlink cache_dir must still be rejected. + before = _calls(root) + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(link_cache) + os.sep}): + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "sl3.cso"), str(src)], + capture_output=True, check=True) + assert _calls(root) == before + 1 + assert list(real_cache.iterdir()) == [] + else: + before = _calls(root) + with mock.patch.object(mod.os.path, "islink", side_effect=lambda p: os.fspath(p) == str(link_cache)): + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(link_cache)}): + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "sl1.cso"), str(src)], + capture_output=True, check=True) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "sl2.cso"), str(src)], + capture_output=True, check=True) + assert _calls(root) == before + 2 + + +def _test_multi_output_fc_fd(mod, root, compiler): + cache_dir = Path(root) / "cache_multi" + src = Path(root) / "multi.hlsl" + src.write_bytes(b"float4 main() : SV_Target { return 0; }") + fo1, fc1, fd1 = Path(root) / "m1.cso", Path(root) / "m1.asm", Path(root) / "m1.pdb" + fo2, fc2, fd2 = Path(root) / "m2.cso", Path(root) / "m2.asm", Path(root) / "m2.pdb" + before = _calls(root) + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + r1 = mod.run_dxc(compiler, ["-T", "ps_6_0", "-Fo", str(fo1), "-Fc", str(fc1), "-Fd", str(fd1), str(src)], + capture_output=True, text=True, check=True) + r2 = mod.run_dxc(compiler, ["-T", "ps_6_0", "-Fo", str(fo2), "-Fc", str(fc2), "-Fd", str(fd2), str(src)], + capture_output=True, text=True, check=True) + assert _calls(root) == before + 1, "multi-output -Fc/-Fd missed cache" + assert fo2.read_bytes().startswith(b"FO:") + assert fc2.read_bytes().startswith(b"FC:") + assert fd2.read_bytes().startswith(b"FD:") + assert str(fc2) in r2.stdout and str(fd2) in r2.stdout and str(fo2) in r2.stdout + assert str(fo1) not in r2.stdout and str(fc1) not in r2.stdout + assert r1.returncode == r2.returncode == 0 + assert not _tmp_files(root) + + +def _test_corrupt_cache_miss(mod, root, compiler): + cache_dir = Path(root) / "cache_corrupt" + src = Path(root) / "corrupt.hlsl" + src.write_bytes(b"void main(){ /*corrupt*/ }") + out1 = Path(root) / "c1.cso" + out2 = Path(root) / "c2.cso" + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(out1), str(src)], capture_output=True, check=True) + entries = list(cache_dir.glob("*.json")) + assert len(entries) == 1 + entry = entries[0] + # Invalid JSON -> treated as cache miss and overwritten with valid entry. + entry.write_text("{not-json", encoding="utf-8") + before = _calls(root) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(out2), str(src)], capture_output=True, check=True) + assert _calls(root) == before + 1 + assert out2.read_bytes().startswith(b"FO:") + # Bad hex payload -> treated as cache miss. + rec = json.loads(entry.read_text(encoding="utf-8")) + rec["files"]["-Fo"] = "zzzz" + entry.write_text(json.dumps(rec), encoding="utf-8") + before = _calls(root) + out3 = Path(root) / "c3.cso" + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(out3), str(src)], capture_output=True, check=True) + assert _calls(root) == before + 1 + assert out3.read_bytes().startswith(b"FO:") + + +def _test_include_and_i_bypass(mod, root, compiler): + cache_dir = Path(root) / "cache_bypass" + inc_src = Path(root) / "inc.hlsl" + inc_src.write_bytes(b'#include "defs.hlsli"\nvoid main(){}') + plain_src = Path(root) / "plain.hlsl" + plain_src.write_bytes(b"void main(){}") + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + before = _calls(root) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "i1.cso"), str(inc_src)], capture_output=True) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-Fo", str(Path(root) / "i2.cso"), str(inc_src)], capture_output=True) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-I", str(root), "-Fo", str(Path(root) / "d1.cso"), str(plain_src)], + capture_output=True) + mod.run_dxc(compiler, ["-T", "cs_6_0", "-I", str(root), "-Fo", str(Path(root) / "d2.cso"), str(plain_src)], + capture_output=True) + assert _calls(root) == before + 4, "#include or -I must bypass cache every time" + assert not cache_dir.exists() or list(cache_dir.glob("*.json")) == [] + + +def _test_proxy(mod, root, compiler): + cache_dir = Path(root) / "cache_proxy" + src = Path(root) / "proxy.hlsl" + src.write_bytes(b"void main(){}") + proxy = mod.with_dxc_cache(subprocess) + with mock.patch.dict(os.environ, {mod.ENV_VAR: str(cache_dir)}): + before = _calls(root) + proxy.run([compiler, "-T", "cs_6_0", "-Fo", str(Path(root) / "p1.cso"), str(src)], capture_output=True) + proxy.run([compiler, "-T", "cs_6_0", "-Fo", str(Path(root) / "p2.cso"), str(src)], capture_output=True) + assert _calls(root) == before + 1 + sentinel = subprocess.CompletedProcess(["other"], 0) + with mock.patch.object(subprocess, "run", return_value=sentinel) as patched: + got = proxy.run(["other", "--version"]) + assert got is sentinel and patched.call_count == 1 + + +def run_suite(mod): + tests = [ + _test_atomic_restore_and_zero_temps, + _test_replace_fail_preserves_output_and_cleans_temps, + _test_fo_dir_and_symlink_refusal, + _test_symlink_and_file_cache_dir_fallback, + _test_multi_output_fc_fd, + _test_corrupt_cache_miss, + _test_include_and_i_bypass, + _test_proxy, + ] + for fn in tests: + with tempfile.TemporaryDirectory() as root: + compiler = _make_rig(root) + fn(mod, root, compiler) + return len(tests) + + +def _run_mutations(): + source = DXC_CACHE_PATH.read_text(encoding="utf-8") + mutants = [ + ( + "drop_symlink_target_guard", + " if os.path.islink(target) or os.path.islink(stripped):\n" + " raise OSError(errno.ELOOP, \"refusing symlink target\", target)\n", + " if False:\n pass\n", + _test_fo_dir_and_symlink_refusal, + ), + ( + "non_atomic_write_file", + " os.replace(temp, target)", + " with open(target, 'wb') as direct: direct.write(data)\n os.unlink(temp)", + _test_replace_fail_preserves_output_and_cleans_temps, + ), + ( + "drop_tmp_cleanup", + " if not closed:\n os.close(handle)\n" + " if os.path.exists(temp):\n os.unlink(temp)", + " if not closed:\n os.close(handle)", + _test_replace_fail_preserves_output_and_cleans_temps, + ), + ( + "drop_cache_dir_symlink_and_file_guard", + " if _valid_cache_dir(cache_dir) and not extra:", + " if cache_dir and not extra:", + _test_symlink_and_file_cache_dir_fallback, + ), + ( + "drop_include_bypass", + " if INCLUDE_RE.search(source_bytes):", + " if False:", + _test_include_and_i_bypass, + ), + ] + with tempfile.TemporaryDirectory() as mut_dir: + for idx, (name, needle, repl, probe) in enumerate(mutants): + assert source.count(needle) == 1, f"mutant needle not unique: {name}" + mut_path = Path(mut_dir) / f"dxc_cache_mut_{idx}.py" + mut_path.write_text(source.replace(needle, repl, 1), encoding="utf-8") + mod = _load_module(mut_path, f"dxc_cache_mut_{idx}") + with tempfile.TemporaryDirectory() as root: + compiler = _make_rig(root) + try: + probe(mod, root, compiler) + except (AssertionError, OSError, SystemExit): + continue + raise SystemExit(f"dxc_cache_unit_check: mutant {name} survived!") + return len(mutants) + + +def main(): + mod = _load_module(DXC_CACHE_PATH, "dxc_cache") + passed = run_suite(mod) + killed = _run_mutations() + print(f"dxc_cache_unit_check: {passed}/{passed} unit checks passed, {killed}/{killed} mutants killed") + + +if __name__ == "__main__": + main() diff --git a/tests/dxc_compile_time_cli_check.py b/tests/dxc_compile_time_cli_check.py index 0f7e894154..5e4e057546 100644 --- a/tests/dxc_compile_time_cli_check.py +++ b/tests/dxc_compile_time_cli_check.py @@ -290,6 +290,10 @@ def test_argparse_and_cli_parameter_errors_exit_nonzero_cleanly(self): cases = [ (["--dxc", str(fake_dxc)], "--timeout"), (["--dxc", str(fake_dxc), "--timeout", "0"], "positive"), + (["--dxc", str(fake_dxc), "--timeout", "nan"], "finite positive"), + (["--dxc", str(fake_dxc), "--timeout", "inf"], "finite positive"), + (["--dxc", str(fake_dxc), "--timeout=-inf"], "finite positive"), + (["--dxc", str(fake_dxc), "--timeout", "1e999"], "finite positive"), (["--dxc", str(fake_dxc), "--timeout", "10", "--repeat", "0"], "--repeat"), (["--timeout", "10"], "--dxc"), (["--dxc", str(missing_dxc), "--timeout", "10"], "DXC executable not found"), diff --git a/tests/era_heap_check.cpp b/tests/era_heap_check.cpp index 79e66e7bc1..20a2e5c961 100644 --- a/tests/era_heap_check.cpp +++ b/tests/era_heap_check.cpp @@ -85,22 +85,27 @@ bool allocation_checks() bool failure_checks() { - // Mix each reserved bit with a valid heap alignment and with the AMD graphics word. - for (unsigned bit = 33; bit < 64; ++bit) { + // Mix each of the 30 reserved bits with a valid heap alignment and with the AMD graphics word. + for (unsigned bit = 34; bit < 64; ++bit) { const auto reserved = std::uint64_t{1} << bit; if (!rejects(257, reserved | (std::uint64_t{6} << 24)) || !rejects(512, reserved | amd_word)) { return false; } } + // The address-below-4-GiB bit is valid but this allocator does not provide such an address. + if (!rejects(257, (std::uint64_t{1} << 33) | (std::uint64_t{6} << 24)) || + !rejects(512, (std::uint64_t{1} << 33) | amd_word)) { + return false; + } // Physical memory types 7-9 are not modeled. Types 10-15 are undefined. for (std::uint64_t type = 7; type < 16; ++type) { if (!rejects(512, (amd_word & ~memory_type_mask) | (type << 29))) return false; } - // Graphics memory with 4 MB pages or a 128 KiB alignment exceeds the desktop + // Graphics memory with 2 MB pages or a 128 KiB alignment exceeds the desktop // allocation granularity. The undefined page size value 3 fails for every type. - const auto four_mb_pages = (amd_word & ~(std::uint64_t{3} << 14)) | (std::uint64_t{2} << 14); + const auto two_mb_pages = (amd_word & ~(std::uint64_t{3} << 14)) | (std::uint64_t{2} << 14); const auto wide_alignment = (amd_word & ~(std::uint64_t{31} << 24)) | (std::uint64_t{17} << 24); - if ((allocation_granularity() < (std::size_t{4} << 20) && !rejects(512, four_mb_pages)) || + if ((allocation_granularity() < (std::size_t{2} << 20) && !rejects(512, two_mb_pages)) || (allocation_granularity() < (std::size_t{1} << 17) && !rejects(512, wide_alignment)) || !rejects(512, amd_word | (std::uint64_t{3} << 14)) || !rejects(64, bink_word | (std::uint64_t{3} << 14))) { @@ -117,9 +122,9 @@ bool observed_word_checks() const auto bink = era_heap::decode(bink_word); const auto amd = era_heap::decode(amd_word); if (bink.object_type != 0 || bink.page_size != 0 || bink.allocator_id != 0xe5 || - bink.alignment != 5 || bink.memory_type != 0 || bink.reserved != 0 || + bink.alignment != 5 || bink.memory_type != 0 || bink.reserved != 0 || bink.address_below_4gib != 0 || amd.object_type != 0 || amd.page_size != 1 || amd.allocator_id != 0 || - amd.alignment != 8 || amd.memory_type != 5 || amd.reserved != 0) { + amd.alignment != 8 || amd.memory_type != 5 || amd.reserved != 0 || amd.address_below_4gib != 0) { return false; } @@ -404,8 +409,9 @@ bool concurrency_checks() return ok.load(); } -// Every field of the ERA attribute layout (objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, -// reserved:31) at its widest value alone, all at once, and one word with a distinct value in each field. The +// Every field of the XALLOC_ATTRIBUTES layout (objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, +// address-below-4-GiB:1, reserved:30) at its widest value alone, all at once, and one word with a distinct value +// in each field. The // observed words leave the object type and the reserved bits at 0, so a narrowed mask or a shifted field boundary // would decode them unchanged. narrow_object_type expects a 13-bit object type and is the negative control. bool decode_field_checks(bool narrow_object_type) @@ -416,16 +422,17 @@ bool decode_field_checks(bool narrow_object_type) era_heap::Fields fields; }; constexpr std::uint64_t mixed = 0x2a5cull | 2ull << 14 | 0xb7ull << 16 | 0x13ull << 24 | 9ull << 29 | - 0x5a5a5a5ull << 33; + 1ull << 33 | 0x2a5a5a5ull << 34; const Case cases[] = { - {"object type", 0x3fff, {0x3fff, 0, 0, 0, 0, 0}}, - {"page size", 3ull << 14, {0, 3, 0, 0, 0, 0}}, - {"allocator", 0xffull << 16, {0, 0, 0xff, 0, 0, 0}}, - {"alignment", 0x1full << 24, {0, 0, 0, 0x1f, 0, 0}}, - {"memory type", 0xfull << 29, {0, 0, 0, 0, 0xf, 0}}, - {"reserved", 0x7fffffffull << 33, {0, 0, 0, 0, 0, 0x7fffffff}}, - {"all ones", ~0ull, {0x3fff, 3, 0xff, 0x1f, 0xf, 0x7fffffff}}, - {"mixed", mixed, {0x2a5c, 2, 0xb7, 0x13, 9, 0x5a5a5a5}}, + {"object type", 0x3fff, {0x3fff, 0, 0, 0, 0, 0, 0}}, + {"page size", 3ull << 14, {0, 3, 0, 0, 0, 0, 0}}, + {"allocator", 0xffull << 16, {0, 0, 0xff, 0, 0, 0, 0}}, + {"alignment", 0x1full << 24, {0, 0, 0, 0x1f, 0, 0, 0}}, + {"memory type", 0xfull << 29, {0, 0, 0, 0, 0xf, 0, 0}}, + {"address 32-bit mapping", 1ull << 33, {0, 0, 0, 0, 0, 1, 0}}, + {"reserved", 0x3fffffffull << 34, {0, 0, 0, 0, 0, 0, 0x3fffffff}}, + {"all ones", ~0ull, {0x3fff, 3, 0xff, 0x1f, 0xf, 1, 0x3fffffff}}, + {"mixed", mixed, {0x2a5c, 2, 0xb7, 0x13, 9, 1, 0x2a5a5a5}}, }; bool ok = true; for (const auto& c : cases) { @@ -436,10 +443,11 @@ bool decode_field_checks(bool narrow_object_type) const auto got = era_heap::decode(c.word); if (got.object_type != want.object_type || got.page_size != want.page_size || got.allocator_id != want.allocator_id || got.alignment != want.alignment || - got.memory_type != want.memory_type || got.reserved != want.reserved) { - std::printf("FAIL: decode %s: %x %u %x %u %u %llx\n", c.name, got.object_type, got.page_size, + got.memory_type != want.memory_type || got.reserved != want.reserved || + got.address_below_4gib != want.address_below_4gib) { + std::printf("FAIL: decode %s: %x %u %x %u %u %x %u\n", c.name, got.object_type, got.page_size, got.allocator_id, got.alignment, got.memory_type, - static_cast<unsigned long long>(got.reserved)); + got.reserved, got.address_below_4gib); ok = false; } } diff --git a/tests/f16_exp_midpoints.py b/tests/f16_exp_midpoints.py new file mode 100644 index 0000000000..24eab4f008 --- /dev/null +++ b/tests/f16_exp_midpoints.py @@ -0,0 +1,58 @@ +"""Generate the non-tie binary16 exp2 corrections for an 8 f32 ULP window.""" +import re +import struct +from decimal import Decimal, localcontext +from fractions import Fraction +from functools import cache +from pathlib import Path + + +def floor_log2(value): + exponent = value.numerator.bit_length() - value.denominator.bit_length() + return exponent - (value < Fraction(2) ** exponent) + + +@cache +def exp_f16_midpoints(): + entries = {} + with localcontext() as context: + context.prec = 90 + ln2 = Decimal(2).ln() + for bits in range(0x10000): + if bits & 0x7fff >= 0x7c00: + continue + operand = struct.unpack('<e', struct.pack('<H', bits))[0] + # Beyond these limits the half result is fixed with ample error margin. + if operand < -25 or operand > 16: + continue + power = Fraction(operand) + integer = power.numerator // power.denominator + fractional = power - integer + exponent = Decimal(fractional.numerator) / Decimal(fractional.denominator) + value = Fraction(2) ** integer * Fraction((exponent * ln2).exp()) + binade = floor_log2(value) + half_ulp = Fraction(2) ** (max(binade, -14) - 10) + lower = int(value / half_ulp) * half_ulp + midpoint = lower + half_ulp / 2 + distance = abs(value - midpoint) + if distance == 0: + assert bits == 0xce40 # The emitter handles exp2(-25) explicitly. + elif distance < 8 * Fraction(2) ** (binade - 23): + rounded = lower if value < midpoint else lower + half_ulp + result = struct.unpack('<H', struct.pack('<e', float(rounded)))[0] + entries[bits] = result + return entries + + +def check_cpp_table(): + source = Path(__file__).resolve().parents[1] / 'src' / 'gfx1013_direct_compute.inl' + array = re.search(r'exp_f16_midpoints\[\]\s*\{(.*?)\};', + source.read_text(encoding='utf-8'), re.DOTALL) + assert array, 'missing C++ exp_f16_midpoints array' + pairs = re.findall(r'\{\s*(0x[0-9a-f]+),\s*(0x[0-9a-f]+)\s*\}', array[1]) + parsed = [(int(source, 16), int(result, 16)) for source, result in pairs] + assert len(parsed) == 70 and parsed == list(exp_f16_midpoints().items()), parsed + + +if __name__ == '__main__': + check_cpp_table() diff --git a/tests/f16_packed_model.py b/tests/f16_packed_model.py new file mode 100644 index 0000000000..e25ba0866f --- /dev/null +++ b/tests/f16_packed_model.py @@ -0,0 +1,189 @@ +"""Independent CPU model of v_pk_mul_f16 / v_pk_add_f16 / v_pk_fma_f16 (Part of #1723). Pure Python, no GPU. + +Per RDNA 2 VOP3P: result low half = op(source i half op_sel[i], ...), result high half = op(source i half +op_sel_hi[i], ...); absent modifiers mean op_sel [0,..] and op_sel_hi [1,..]. Each half is an IEEE binary16 +operation rounded once to nearest even. Finite operands use exact rational arithmetic; infinities and NaNs use +float64 (exact for those cases). Any NaN result is reported as the canonical quiet NaN 0x7e00 (its class is what +is compared: the payload of a generated NaN is not fixed by the format). +""" +import math +import random +import struct +from fractions import Fraction + +# 0, -0, smallest denormal, largest denormal, 1, -1, 65504, -65504, inf, -inf, quiet NaN, signalling NaN, NaN with payload +GRID = [0x0000, 0x8000, 0x0001, 0x03ff, 0x3c00, 0xbc00, 0x7bff, 0xfbff, 0x7c00, 0xfc00, 0x7e00, 0x7d00, 0x7e01] +# Extra finite words: 1/3, a tie between two binary16 values (1 + 2^-11 + 1 ulp pattern), 0.1, -2.5, 65519.9 region, min normal +EXTRA = [0x3555, 0x3c01, 0x2e66, 0xc100, 0x7bfe, 0x0400, 0x8400, 0x1400, 0x4900, 0x5640] + + +def h2f(bits): + return struct.unpack('<e', struct.pack('<H', bits & 0xffff))[0] + + +def is_nan(bits): + return (bits & 0x7c00) == 0x7c00 and (bits & 0x3ff) != 0 + + +def is_inf(bits): + return (bits & 0x7fff) == 0x7c00 + + +def sign(bits): + return bits >> 15 & 1 + + +def round_exact(x): + """Binary16 encoding of a nonzero rational, nearest even, overflow to infinity (exact, no intermediate float).""" + neg = 0x8000 if x < 0 else 0 + x = abs(x) + e = max(x.numerator.bit_length() - x.denominator.bit_length() - 1, -14) + while Fraction(2) ** (e + 1) <= x: + e += 1 + while Fraction(2) ** e > x and e > -14: + e -= 1 + q = x / Fraction(2) ** (e - 10) + n = int(q) + if q - n > Fraction(1, 2) or (q - n == Fraction(1, 2) and n & 1): + n += 1 + if n == 0: + return neg + if n == 0x800: + n, e = 0x400, e + 1 + if e > 15: + return neg | 0x7c00 + return neg | (n if e == -14 and n < 0x400 else ((e + 15) << 10) | (n & 0x3ff)) + + +def half_unary_value(op, x): + """Evaluate binary16 unary operations in float64, including special values.""" + if op == 'rcp': + return math.copysign(math.inf, x) if x == 0 else 1.0 / x + if op == 'sqrt': + return math.nan if x < 0 else math.sqrt(x) + if op == 'rsq': + if x == 0: + return math.copysign(math.inf, x) + return math.nan if x < 0 else 1.0 / math.sqrt(x) + assert op == 'exp' + return math.inf if x >= 128 else math.exp2(x) + + +def rsq_rounding(bits): + """Return the exact RNE result and any alternate allowed by the f32 midpoint window.""" + if not 0 < bits < 0x7c00: + value = half_unary_value('rsq', h2f(bits)) + result = 0x7e00 if math.isnan(value) else struct.unpack('<H', struct.pack('<e', value))[0] + return result, None + + source = Fraction(h2f(bits)) + + def below_rsq(value): + return source * value * value < 1 + + # The reciprocal square root of every positive finite half is a normal half + # or falls between two normal half encodings. 0x6c00 is the largest result. + lo, hi = 0x0400, 0x6c01 + while hi - lo > 1: + mid = (lo + hi) // 2 + if below_rsq(Fraction(h2f(mid))): + lo = mid + else: + hi = mid + lower, upper = Fraction(h2f(lo)), Fraction(h2f(hi)) + if source * upper * upper == 1: + return hi, None + midpoint = (lower + upper) / 2 + if source * midpoint * midpoint == 1: + rounded = lo if lo % 2 == 0 else hi + else: + rounded = hi if below_rsq(midpoint) else lo + # The result and midpoint share the lower encoding's binade. Compare + # the exact reciprocal square root to each endpoint by squaring. + radius = Fraction(2) ** ((lo >> 10) - 15 - 20) + near = below_rsq(midpoint - radius) and source * (midpoint + radius) ** 2 > 1 + return rounded, (lo if rounded == hi else hi) if near else None + + +def half_op(op, a, b=0, c=0): + """Round one binary16 operation, including unary rcp, sqrt, rsq and exp2.""" + if op == 'rsq': + return rsq_rounding(a)[0] + if op in ('rcp', 'sqrt', 'exp'): + x = h2f(a) + if op == 'rcp' and math.isfinite(x) and x != 0: + return round_exact(1 / Fraction(x)) + value = half_unary_value(op, x) + if math.isnan(value): + return 0x7e00 + if value == 0 or math.isinf(value): + return struct.unpack('<H', struct.pack('<e', value))[0] + return round_exact(Fraction(value)) + words = (a, b, c) if op == 'fma' else (a, b) + if any(is_nan(w) for w in words): + return 0x7e00 + if any(is_inf(w) for w in words): + x, y = h2f(a), h2f(b) + with_nan = (op == 'mul' and (math.isinf(x) or math.isinf(y)) and (x == 0 or y == 0)) + v = x * y if op != 'add' else x + y + if op == 'fma': + if (x == 0 and math.isinf(y)) or (y == 0 and math.isinf(x)): + with_nan = True + v = x * y + h2f(c) if not with_nan else math.nan + if with_nan or math.isnan(v): + return 0x7e00 + return 0x7c00 if v > 0 else 0xfc00 + fa, fb, fc = Fraction(h2f(a)), Fraction(h2f(b)), Fraction(h2f(c)) + exact = fa * fb if op == 'mul' else fa + fb if op == 'add' else fa * fb + fc + if exact != 0: + return round_exact(exact) + # An exact zero: the sign rules of IEEE 754 round-to-nearest. + if op == 'mul': + return (sign(a) ^ sign(b)) << 15 + if op == 'add': + return 0x8000 if (a == 0x8000 and b == 0x8000) else 0 + product_zero = fa * fb == 0 + psign = sign(a) ^ sign(b) + return 0x8000 if product_zero and fc == 0 and psign and sign(c) else 0 + + +def pick(word, high): + return (word >> 16 if high else word) & 0xffff + + +def packed(op, words, op_sel, op_sel_hi): + """Result word of v_pk_<op>_f16 over 32-bit source words.""" + n = len(words) + lo = half_op(op, *[pick(words[i], op_sel[i]) for i in range(n)]) + hi = half_op(op, *[pick(words[i], op_sel_hi[i]) for i in range(n)]) + return (hi << 16) | lo + + +def same(a, b): + """Word equality where every NaN half of one equals every NaN half of the other.""" + return all(x == y or (is_nan(x) and is_nan(y)) for x, y in ((a & 0xffff, b & 0xffff), (a >> 16, b >> 16))) + + +def combos(arity): + """(op_sel, op_sel_hi) selector pairs: all of them for two sources, a covering sample of 16 of the 64 for three.""" + def bits(v): + return [v >> i & 1 for i in range(arity)] + if arity == 2: + return [(bits(s), bits(h)) for s in range(4) for h in range(4)] + return [(bits(s), bits(h)) for s, h in + [(s, (5 * s + 3) % 8) for s in range(8)] + [((3 * s + 1) % 8, s) for s in range(8)]] + + +def all_combos(arity): + def bits(v): + return [v >> i & 1 for i in range(arity)] + return [(bits(s), bits(h)) for s in range(1 << arity) for h in range(1 << arity)] + + +def sample(seed, count, arity): + """count tuples of arity 32-bit words whose halves come from the grid, the finite extras and random words.""" + rng = random.Random(seed) + pool = GRID + EXTRA + def half(): + return rng.choice(pool) if rng.random() < 0.8 else rng.randrange(0x10000) + return [tuple(half() | half() << 16 for _ in range(arity)) for _ in range(count)] diff --git a/tests/ffx_create_context_cli_check.py b/tests/ffx_create_context_cli_check.py new file mode 100644 index 0000000000..fea9123e9d --- /dev/null +++ b/tests/ffx_create_context_cli_check.py @@ -0,0 +1,492 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and mutation suite for tools/ffx_create_context.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "ffx_create_context.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) +import ffx_create_context # noqa: E402 +from ffx_create_context_check import build_synthetic_loader # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include <cstdint>\n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) uint32_t create_context(void** output, const void* desc, ' + 'const void* allocator, const void* host) { return 0; }\n' +) + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FfxCreateContextCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_dirs_and_overwrite_with_zero_tmp(self) -> None: + raw = build_synthetic_loader() + digest = hashlib.sha256(raw).hexdigest() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + loader = base / "synthetic_loader.dll" + loader.write_bytes(raw) + nested_out = base / "nested" / "sub" / "create_context.cpp" + self.assertFalse(nested_out.parent.exists()) + + real_replace = os.replace + replaced_pairs: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaced_pairs.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + self.assertEqual(src_p.suffix, ".tmp") + return real_replace(src, dst) + + # 1) Create missing parent directories and write real lowered C++ atomically with 0 .tmp files. + with ( + mock.patch.object(ffx_create_context, "LOADER", digest), + mock.patch.object(ffx_create_context.os, "replace", side_effect=tracking_replace), + ): + expected_cpp = ffx_create_context.generate(loader) + code, out, err = _run_main(ffx_create_context, [str(loader), str(nested_out)]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), expected_cpp) + self.assertIn('extern "C" __declspec(dllexport) uint32_t create_context', expected_cpp) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["create_context.cpp"]) + self.assertEqual(len(replaced_pairs), 1) + self.assertEqual(replaced_pairs[0][1].resolve(), nested_out.resolve()) + + # 2) Atomic overwrite replaces stale content with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + updated_cpp = SYNTHETIC_CPP + "// updated\n" + with mock.patch.object(ffx_create_context, "generate", return_value=updated_cpp): + code_ow, out_ow, err_ow = _run_main(ffx_create_context, [str(loader), str(nested_out)]) + self.assertEqual(code_ow, 0, err_ow) + self.assertEqual(out_ow, "") + self.assertEqual(err_ow, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), updated_cpp) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["create_context.cpp"]) + + # 3) argv=None forwards sys.argv cleanly. + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(loader), str(nested_out)]), + mock.patch.object(ffx_create_context, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(ffx_create_context, None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) __main__ entrypoint propagates SystemExit(1) cleanly on unmatched loader. + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(loader), str(base / "unused.cpp")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("version-query profile", stderr_m.getvalue()) + + +class FfxCreateContextCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(ffx_create_context, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_corrupt_and_hash_mismatch_loader_rejected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_loader = base / "dir_loader" + dir_loader.mkdir() + absent_out = base / "absent_dir" / "create_context.cpp" + + with ( + mock.patch.object( + ffx_create_context, + "generate", + side_effect=AssertionError("generate called for invalid loader path"), + ), + mock.patch.object( + ffx_create_context, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid loader path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("loader file not found",), + ) + self._assert_clean_failure( + [str(dir_loader), str(absent_out)], + expected_code=1, + fragments=("loader path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + # Unmatched SHA-256 hash fails cleanly with 0 temps and 0 created dirs. + raw = build_synthetic_loader() + unmatched = base / "unmatched.dll" + unmatched.write_bytes(raw) + self._assert_clean_failure( + [str(unmatched), str(absent_out)], + expected_code=1, + fragments=("version-query profile",), + ) + self.assertFalse(absent_out.parent.exists()) + + # Corrupt PE bytes (with matching SHA-256) fail cleanly without creating output parent. + corrupt_payload = b"not a PE32+ image" + corrupt_digest = hashlib.sha256(corrupt_payload).hexdigest() + corrupt = base / "corrupt.dll" + corrupt.write_bytes(corrupt_payload) + with mock.patch.object(ffx_create_context, "LOADER", corrupt_digest): + self._assert_clean_failure( + [str(corrupt), str(absent_out)], + expected_code=1, + fragments=("dos header",), + check_subprocess=False, + ) + self.assertFalse(absent_out.parent.exists()) + self.assertEqual([p.name for p in base.iterdir() if p.suffix == ".tmp"], []) + + def test_output_guards_dir_file_parent_samefile_and_non_cpp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + loader = base / "loader.dll" + loader.write_bytes(b"synthetic-loader-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(loader) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + sub_dir = base / "sub" + sub_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + ffx_create_context, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + ffx_create_context, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(loader), str(base / "out.txt")], 2, ("separate .cpp output",)), + ("empty_output", [str(loader), ""], 2, ("separate .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("separate .cpp output",)), + ("resolve_alias", [str(same_cpp), str(sub_dir / ".." / "same.cpp")], 2, ("separate .cpp output",)), + ("hardlink_samefile", [str(loader), str(hardlink_cpp)], 2, ("separate .cpp output",)), + ("output_is_dir", [str(loader), str(out_dir)], 1, ("output path is a directory",)), + ("parent_is_file", [str(loader), str(file_parent / "create_context.cpp")], 1, ("not a directory",)), + ( + "ancestor_is_file", + [str(loader), str(file_parent / "sub" / "create_context.cpp")], + 1, + ("not a directory",), + ), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(loader.read_bytes(), b"synthetic-loader-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + loader = base / "loader.dll" + loader.write_bytes(b"synthetic-loader-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + + # Unconditional unit check for output.is_symlink() guard even if OS lacks symlink privilege. + with ( + mock.patch.object(Path, "is_symlink", return_value=True), + mock.patch.object( + ffx_create_context, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + ffx_create_context, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + self._assert_clean_failure( + [str(loader), str(out_dir / "mock_link.cpp")], + expected_code=1, + fragments=("output path must not be a symlink",), + check_subprocess=False, + ) + + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + ffx_create_context, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + ffx_create_context, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(loader), str(link)], + expected_code=1, + fragments=("output path must not be a symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_os_replace_and_write_failures_preserve_output_and_leave_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + loader = base / "loader.dll" + loader.write_bytes(b"synthetic-loader-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "create_context.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(ffx_create_context, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(ffx_create_context.os, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(loader), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["create_context.cpp"]) + + # Non-ASCII payload fails during temp write; temp file is still unlinked and original preserved. + with mock.patch.object(ffx_create_context, "generate", return_value="non-ascii-\u00e9"): + self._assert_clean_failure( + [str(loader), str(out_cpp)], + expected_code=1, + fragments=("ascii",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual([p.name for p in out_dir.iterdir()], ["create_context.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + loader = base / "loader.dll" + loader.write_bytes(b"synthetic") + + for argv, frags in ( + ([], ("required",)), + ([str(loader)], ("required",)), + ([str(loader), str(base / "create_context.cpp"), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + loader = base / "loader.dll" + loader.write_bytes(b"synthetic-loader-bytes") + dir_loader = base / "dir_loader" + dir_loader.mkdir() + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(loader) + file_parent = base / "file_parent.txt" + file_parent.write_text("keep", encoding="ascii") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "create_context.cpp" + out_cpp.write_text("original", encoding="ascii") + + def check_symlink_mutation(mod): + with mock.patch.object(Path, "is_symlink", return_value=True): + _, _, err = _run_main(mod, [str(loader), str(out_dir / "sym.cpp")]) + self.assertNotIn("output path must not be a symlink", err.lower()) + + # 1) Dropping loader.is_dir() guard misses "loader path is a directory". + # 2) Dropping output.is_symlink() guard misses "output path must not be a symlink". + # 3) Dropping parent.is_file() guard misses "output parent is not a directory". + # 4) Dropping samefile() guard allows hardlink collision past _validate_paths. + # 5) Dropping tmp_path.unlink() leaks a .tmp file on os.replace failure. + for label, target, replacement, check_fn in ( + ( + "drop_loader_is_dir_guard", + ' if loader.is_dir():\n raise IsADirectoryError(f"loader path is a directory: {loader}")\n', + " pass\n", + lambda mod: self.assertNotIn( + "loader path is a directory", + _run_main(mod, [str(dir_loader), str(out_dir / "a.cpp")])[2].lower(), + ), + ), + ( + "drop_output_is_symlink_guard", + ' if output.is_symlink():\n raise ValueError(f"output path must not be a symlink: {output}")\n', + " pass\n", + check_symlink_mutation, + ), + ( + "drop_parent_is_file_guard", + ' if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()):\n' + ' raise NotADirectoryError(f"output parent is not a directory: {parent}")\n', + " pass\n", + lambda mod: self.assertNotIn( + "output parent is not a directory", + _run_main(mod, [str(loader), str(file_parent / "create_context.cpp")])[2].lower(), + ), + ), + ( + "drop_samefile_guard", + " if output.resolve() == loader.resolve() or (output.exists() and loader.samefile(output)):\n", + " if output.resolve() == loader.resolve():\n", + lambda mod: self.assertNotIn( + "separate .cpp output", + _run_main(mod, [str(loader), str(hardlink_cpp)])[2].lower(), + ), + ), + ( + "drop_tmp_unlink", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)\n", + " pass\n", + lambda mod: self._verify_tmp_leaked_on_replace_fail(mod, loader, out_cpp, out_dir), + ), + ): + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"ffx_create_context_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + with mock.patch.object(mod, "generate", return_value=SYNTHETIC_CPP): + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + def _verify_tmp_leaked_on_replace_fail(self, mod, loader: Path, out_cpp: Path, out_dir: Path) -> None: + with mock.patch.object(mod.os, "replace", side_effect=OSError("boom")): + code, _, _ = _run_main(mod, [str(loader), str(out_cpp)]) + self.assertEqual(code, 1) + leaked = [p for p in out_dir.iterdir() if p.suffix == ".tmp"] + self.assertTrue(leaked, "expected unlinked .tmp file under mutation") + for p in leaked: + p.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/ffx_scratch_reference_check.py b/tests/ffx_scratch_reference_check.py new file mode 100644 index 0000000000..2852217894 --- /dev/null +++ b/tests/ffx_scratch_reference_check.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""Standalone unit, bounds-validation, and mutation suite for tools/ffx_scratch_reference.py.""" + +from __future__ import annotations + +from pathlib import Path +import re +import struct +import sys +import types +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "ffx_scratch_reference.py" +sys.path.insert(0, str(ROOT / "tools")) + +import ffx_scratch_reference # noqa: E402 + + +def _build_initializer() -> bytes: + # 128 bytes = 32 dwords; offset 0x00 and offset 0x40 are valid 64-byte windows. + dwords = [ + 0x01020304, 0xFFFDFCFB, 0x3F800000, 0x40000000, + 0x11223344, 0x80000001, 0x00000005, 0x00000007, + 0x7F800000, 0x42FE0000, 0x43800000, 0xC1200000, + 0x00000001, 0x00000002, 0x00000003, 0x00000004, + *[(0x01010101 * (i + 1)) & 0xFFFFFFFF for i in range(16)], + ] + return struct.pack("<32I", *dwords) + + +def _synthetic_pass24() -> list[tuple[int, str]]: + return [ + (0x00, "s_buffer_load_dwordx16 s[0:15], s[16:19], 0x0"), + (0x08, "buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + (0x10, "s_movk_i32 s20, 0xffff"), + (0x14, "s_addk_i32 s20, 3"), + (0x18, "s_mulk_i32 s20, -2"), + (0x1C, "s_brev_b32 s21, s0"), + (0x20, "v_xor_b32 v0, v0, s20"), + (0x24, "v_add_f32 v1, v1, 1.5"), + (0x28, "v_min_f32 v2, v2, 127.0"), + (0x2C, "v_cvt_pk_u8_f32 v3, 127.0, 0, v3"), + (0x30, "buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + ] + + +def _synthetic_producer() -> list[tuple[int, str]]: + return [ + (0x0000, "s_buffer_load_dwordx16 s[0:15], s[16:19], 0x40"), + (0x0010, "buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + # Skipped under stage=26: [0x2414, 0x26dc) and [0x2a40, 0x3c48). + (0x2414, "v_mov_b32 v0, 0"), + (0x2800, "s_mov_b32 s20, 0"), + (0x2810, "v_dot4_i32_i8 v10, v0, s0, 0 op_sel:[0,1,0]"), + (0x2880, "v_dot4c_i32_i8 v10, v1, s1"), + (0x2A40, "v_mov_b32 v10, 0"), + (0x4370, "v_dot4_i32_i8 v11, v2, s2, -5 op_sel:[0,1,1]"), + (0x4AC0, "v_xor_b32 v12, v3, s3"), + (0x51EC, "v_mov_b32_e32 v13, v10"), + ] + + +class FfxScratchReferencePositiveTests(unittest.TestCase): + def test_simm16_and_bit_helpers_preserve_exact_semantics(self) -> None: + self.assertEqual(ffx_scratch_reference.simm16("0"), 0) + self.assertEqual(ffx_scratch_reference.simm16("0x7fff"), 0x7FFF) + self.assertEqual(ffx_scratch_reference.simm16("0x8000"), 0xFFFF8000) + self.assertEqual(ffx_scratch_reference.simm16("0xffff"), 0xFFFFFFFF) + self.assertEqual(ffx_scratch_reference.simm16("-1"), 0xFFFFFFFF) + self.assertEqual(ffx_scratch_reference.simm16("-32768"), 0xFFFF8000) + self.assertEqual(ffx_scratch_reference.simm16("-0x8000"), 0xFFFF8000) + self.assertEqual(ffx_scratch_reference.simm16(" 42 "), 42) + + self.assertEqual(ffx_scratch_reference.bits(1.5), 0x3FC00000) + self.assertEqual(ffx_scratch_reference.real(0x3FC00000), 1.5) + self.assertEqual(ffx_scratch_reference.signed(0x7FFFFFFF), 0x7FFFFFFF) + self.assertEqual(ffx_scratch_reference.signed(0x80000000), -0x80000000) + self.assertEqual(ffx_scratch_reference.signed(0xFFFFFFFF), -1) + + def test_network_stage_24_and_26_and_deterministic_make_reference(self) -> None: + init = _build_initializer() + pass24 = _synthetic_pass24() + producer = _synthetic_producer() + taps = [[ffx_scratch_reference.seed(x, y, c) for c in range(4)] for y in range(3) for x in range(3)] + + out24 = ffx_scratch_reference.network(pass24, taps, init, 24) + self.assertEqual(len(out24), 4) + self.assertEqual(out24, ffx_scratch_reference.network(pass24, taps, init, 24)) + + out26 = ffx_scratch_reference.network(producer, taps, init, 26) + self.assertEqual(len(out26), 4) + self.assertEqual(out26, ffx_scratch_reference.network(producer, taps, init, 26)) + self.assertTrue(all(isinstance(x, int) and not isinstance(x, bool) for x in out26)) + + programs = {"pass24": pass24, "producer": producer} + cpp_a = ffx_scratch_reference.make_reference(programs, init) + cpp_b = ffx_scratch_reference.make_reference(programs, init) + self.assertEqual(cpp_a, cpp_b) + + lines = cpp_a.splitlines() + self.assertEqual(len(lines), 2) + m_rows = re.fullmatch(r"static constexpr uint32_t before_padding\[\] = \{([^}]+)\};", lines[0]) + m_gates = re.fullmatch(r"static constexpr int history_logits\[\] = \{([^}]+)\};", lines[1]) + self.assertIsNotNone(m_rows) + self.assertIsNotNone(m_gates) + row_tokens = m_rows.group(1).split(",") + gate_tokens = m_gates.group(1).split(",") + self.assertEqual(len(row_tokens), 3 * 24 * 4) # 3 modes * 6x4 * 4 words = 288 + self.assertTrue(all(tok.startswith("0x") and tok.endswith("u") for tok in row_tokens)) + self.assertEqual(len(gate_tokens), 3 * 32) # 3 modes * 32 logits = 96 + # Mode 0 has all-zero before_padding rows. + self.assertTrue(all(tok == "0x0u" for tok in row_tokens[:96])) + # Modes 1 and 2 must differ. + self.assertNotEqual(row_tokens[96:192], row_tokens[192:]) + self.assertNotEqual(gate_tokens[32:64], gate_tokens[64:]) + + +class FfxScratchReferenceNegativeAndMutationTests(unittest.TestCase): + def test_simm16_rejects_non_str_bool_and_out_of_range(self) -> None: + for bad in (True, False, 0, -1, 1.5, None, b"0", "", " ", "bad", "0x10000", "65536", "-0x8001", "-32769"): + with self.subTest(bad=bad): + with self.assertRaises(ValueError): + ffx_scratch_reference.simm16(bad) + + def test_network_rejects_invalid_stage_and_bad_cbuf_offsets(self) -> None: + init = _build_initializer() + pass24 = _synthetic_pass24() + taps = [[0, 0, 0, 0]] * 9 + + for bad_stage in (0, 1, 25, 27, -24, True, False, 24.0, "24", None): + with self.subTest(bad_stage=bad_stage): + with self.assertRaises(ValueError): + ffx_scratch_reference.network(pass24, taps, init, bad_stage) + + for bad_offset in ("-4", "2", "6", str(len(init) - 60), str(len(init)), "0x1000"): + with self.subTest(bad_offset=bad_offset): + prog = [ + (0x0, f"s_buffer_load_dwordx16 s[0:15], s[16:19], {bad_offset}"), + (0x4, "buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + ] + with self.assertRaises(ValueError): + ffx_scratch_reference.network(prog, taps, init, 24) + + # Empty initializer triggers ValueError (not struct.error) even at offset 0. + with self.assertRaises(ValueError): + ffx_scratch_reference.network(pass24, taps, b"", 24) + + def test_make_reference_rejects_missing_keys_and_undifferentiated_fixture(self) -> None: + init = _build_initializer() + pass24 = _synthetic_pass24() + producer = _synthetic_producer() + + for bad_programs in ({}, {"pass24": pass24}, {"producer": producer}, [], None): + with self.subTest(bad_programs=bad_programs): + with self.assertRaises(ValueError): + ffx_scratch_reference.make_reference(bad_programs, init) + + # Constant pass24 + constant producer fails undifferentiated fixture guard. + const_pass24 = [ + (0x0, "v_mov_b32 v0, 1"), + (0x4, "v_mov_b32 v1, 2"), + (0x8, "v_mov_b32 v2, 3"), + (0xC, "v_mov_b32 v3, 4"), + (0x10, "buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + ] + const_producer = [ + (0x2880, "v_mov_b32 v10, 1"), + (0x4370, "v_mov_b32 v11, 2"), + (0x4AC0, "v_mov_b32 v12, 3"), + (0x51EC, "v_mov_b32 v13, 4"), + ] + with self.assertRaisesRegex(ValueError, "does not distinguish"): + ffx_scratch_reference.make_reference({"pass24": const_pass24, "producer": const_producer}, init) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + init = _build_initializer() + pass24 = _synthetic_pass24() + producer = _synthetic_producer() + taps = [[1, 2, 3, 4]] * 9 + + def _check_simm16_str_mut(mod) -> None: + with self.assertRaises(TypeError): + mod.simm16(True) + + def _check_simm16_range_mut(mod) -> None: + self.assertEqual(mod.simm16("0x10000"), 0x10000) + + def _check_stage_mut(mod) -> None: + with self.assertRaisesRegex(ValueError, "Incomplete tensor reference"): + mod.network(pass24, taps, init, 25) + + def _check_cbuf_bounds_mut(mod) -> None: + prog_unaligned = [ + (0x0, "s_buffer_load_dwordx16 s[0:15], s[16:19], 2"), + (0x4, "buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + (0x8, "v_mov_b32 v0, s0"), + (0xC, "buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + ] + res = mod.network(prog_unaligned, taps, init, 24) + self.assertEqual(len(res), 4) + prog_oob = [ + (0x0, f"s_buffer_load_dwordx16 s[0:15], s[16:19], {len(init)}"), + (0x4, "buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + ] + with self.assertRaises(struct.error): + mod.network(prog_oob, taps, init, 24) + + def _check_programs_keys_mut(mod) -> None: + with self.assertRaises(KeyError): + mod.make_reference({}, init) + + def _check_undiff_mut(mod) -> None: + const_pass24 = [ + (0x0, "v_mov_b32 v0, 1"), + (0x4, "v_mov_b32 v1, 2"), + (0x8, "v_mov_b32 v2, 3"), + (0xC, "v_mov_b32 v3, 4"), + (0x10, "buffer_store_dwordx4 v[0:3], v4, s[8:11], 0 offen"), + ] + const_producer = [ + (0x2880, "v_mov_b32 v10, 1"), + (0x4370, "v_mov_b32 v11, 2"), + (0x4AC0, "v_mov_b32 v12, 3"), + (0x51EC, "v_mov_b32 v13, 4"), + ] + out = mod.make_reference({"pass24": const_pass24, "producer": const_producer}, init) + self.assertIn("before_padding", out) + + mutations = ( + ( + "drop_simm16_str_guard", + ' if not isinstance(token, str):\n raise ValueError(f"Invalid 16-bit signed immediate: {token!r}")\n', + " pass\n", + _check_simm16_str_mut, + ), + ( + "drop_simm16_upper_bound", + " if 0 <= value <= 0xffff:\n", + " if 0 <= value <= 0x1ffff:\n", + _check_simm16_range_mut, + ), + ( + "drop_stage_guard", + ' if isinstance(stage, bool) or not isinstance(stage, int) or stage not in (24, 26):\n' + ' raise ValueError(f"Expected network stage 24 or 26, got {stage!r}")\n', + " pass\n", + _check_stage_mut, + ), + ( + "drop_cbuf_bounds_guard", + ' if offset < 0 or offset % 4 != 0 or offset + 64 > len(initializer):\n' + ' raise ValueError(\n' + ' f"Constant-buffer offset {offset} out of bounds for {len(initializer)}-byte initializer"\n' + ' )\n', + " pass\n", + _check_cbuf_bounds_mut, + ), + ( + "drop_programs_keys_guard", + ' if not isinstance(programs, Mapping) or "pass24" not in programs or "producer" not in programs:\n' + ' raise ValueError("Expected programs mapping with \'pass24\' and \'producer\'")\n', + " pass\n", + _check_programs_keys_mut, + ), + ( + "drop_undifferentiated_guard", + ' if rows[96:192] == rows[192:] or gates[32:64] == gates[64:]:\n' + ' raise ValueError("Fixture does not distinguish the two upstream inputs")\n', + " pass\n", + _check_undiff_mut, + ), + ) + + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"ffx_scratch_reference_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/ffx_working_set_delta_cli_check.py b/tests/ffx_working_set_delta_cli_check.py new file mode 100644 index 0000000000..d076e34ead --- /dev/null +++ b/tests/ffx_working_set_delta_cli_check.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path-guard, and error-handling suite for tools/ffx_working_set_delta.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "ffx_working_set_delta.py" +sys.path.insert(0, str(TOOLS_DIR)) +import ffx_working_set_delta # noqa: E402 + + +SYNTHETIC_CPP = ( + '#include <cstdint>\n' + 'using word = uint64_t;\n' + 'extern "C" __declspec(dllexport) word create_delta(word input, word counters) { return input + counters; }\n' +) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = ffx_working_set_delta.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FfxWorkingSetDeltaCliPositiveTests(unittest.TestCase): + def test_atomic_cpp_output_in_nested_new_dir_and_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"synthetic-image-placeholder") + nested_out = base / "nested" / "sub" / "delta.cpp" + + # 1) Create missing parent directories and write atomically with 0 .tmp files. + with mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP) as gen: + code, out, err = _run_main([str(image), str(nested_out)]) + gen.assert_called_once_with(image, False) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["delta.cpp"]) + + # 2) Forward --package flag and atomically replace pre-existing file with 0 .tmp files. + nested_out.write_text("stale content", encoding="ascii") + pkg_cpp = SYNTHETIC_CPP + "// package-mode\n" + with mock.patch.object(ffx_working_set_delta, "generate", return_value=pkg_cpp) as gen_pkg: + code_pkg, out_pkg, err_pkg = _run_main([str(image), str(nested_out), "--package"]) + gen_pkg.assert_called_once_with(image, True) + self.assertEqual(code_pkg, 0, err_pkg) + self.assertEqual(out_pkg, "") + self.assertEqual(err_pkg, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), pkg_cpp) + self.assertEqual(sorted(p.name for p in nested_out.parent.iterdir()), ["delta.cpp"]) + + # 3) Verify sys.argv forwarding when argv=None. + cli_argv = [str(TOOL), str(image), str(nested_out)] + with ( + mock.patch.object(sys, "argv", cli_argv), + mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP), + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_text(encoding="ascii"), SYNTHETIC_CPP) + + # 4) Verify __main__ entrypoint propagates SystemExit cleanly. + bad_pe = base / "bad_main.dll" + bad_pe.write_bytes(b"not a PE") + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(bad_pe), str(base / "unused.cpp")]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout.getvalue(), "") + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertTrue(stderr.getvalue().strip()) + + +class FfxWorkingSetDeltaCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_directory_image_rejected_before_generate(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + dir_image = base / "dir_image" + dir_image.mkdir() + absent_out = base / "should_not_exist" / "delta.cpp" + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for invalid image path"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid image path"), + ), + ): + self._assert_clean_failure( + [str(base / "missing.dll"), str(absent_out)], + expected_code=1, + fragments=("image file not found",), + ) + self._assert_clean_failure( + [str(dir_image), str(absent_out)], + expected_code=1, + fragments=("image path is a directory",), + ) + + self.assertFalse(absent_out.parent.exists()) + + def test_invalid_pe_bytes_exit_1_without_creating_output_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + bad_pe = base / "bad.dll" + bad_pe.write_bytes(b"not a valid PE32+ image") + absent_out = base / "absent_dir" / "delta.cpp" + + self._assert_clean_failure( + [str(bad_pe), str(absent_out)], + expected_code=1, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_reject_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + same_cpp = base / "same.cpp" + same_cpp.write_bytes(b"synthetic-cpp-bytes") + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + out_dir = base / "existing_dir.cpp" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("keep-me", encoding="ascii") + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for invalid output path"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid output path"), + ), + ): + for label, argv, code, frags in ( + ("non_cpp_suffix", [str(image), str(base / "out.txt")], 2, ("distinct .cpp output",)), + ("empty_output", [str(image), ""], 2, ("distinct .cpp output",)), + ("same_path", [str(same_cpp), str(same_cpp)], 2, ("distinct .cpp output",)), + ("hardlink_samefile", [str(image), str(hardlink_cpp)], 2, ("distinct .cpp output",)), + ("output_is_dir", [str(image), str(out_dir)], 1, ("directory",)), + ("parent_is_file", [str(image), str(file_parent / "delta.cpp")], 1, ("not a directory",)), + ("ancestor_is_file", [str(image), str(file_parent / "sub" / "delta.cpp")], 1, ("not a directory",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=code, fragments=frags) + + self.assertEqual(same_cpp.read_bytes(), b"synthetic-cpp-bytes") + self.assertEqual(image.read_bytes(), b"synthetic-image-bytes") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_text(encoding="ascii"), "keep-me") + self.assertFalse((base / "out.txt").exists()) + + def test_output_symlink_rejected_before_generate_and_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.cpp" + real_target.write_text("untouched", encoding="ascii") + live_link = out_dir / "live_link.cpp" + dangling_link = out_dir / "dangling_link.cpp" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with ( + mock.patch.object( + ffx_working_set_delta, + "generate", + side_effect=AssertionError("generate called for symlink output"), + ), + mock.patch.object( + ffx_working_set_delta, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for symlink output"), + ), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(image), str(link)], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_text(encoding="ascii"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.cpp", "live_link.cpp", "real.cpp"], + ) + + def test_atomic_write_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic-image-bytes") + out_dir = base / "out_dir" + out_dir.mkdir() + out_cpp = out_dir / "delta.cpp" + out_cpp.write_text("original", encoding="ascii") + + with ( + mock.patch.object(ffx_working_set_delta, "generate", return_value=SYNTHETIC_CPP), + mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(image), str(out_cpp)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + + self.assertEqual(out_cpp.read_text(encoding="ascii"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["delta.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"synthetic") + out_cpp = base / "delta.cpp" + + for argv, frags in ( + ([], ("required",)), + ([str(image)], ("required",)), + ([str(image), str(out_cpp), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/fixtures/tracy_fake/tracy/Tracy.hpp b/tests/fixtures/tracy_fake/tracy/Tracy.hpp new file mode 100644 index 0000000000..fb8c4c4f2c --- /dev/null +++ b/tests/fixtures/tracy_fake/tracy/Tracy.hpp @@ -0,0 +1,28 @@ +// Test double for Tracy's memory macros: records every pool event so tracy_new_check can assert on them. +// Used only by tracy_new_check; the real Tracy is never fetched for it. +#pragma once + +#include <cstddef> + +struct TracyFakeEvent { + bool alloc; + const void* pointer; + std::size_t bytes; + const char* pool; +}; + +constexpr std::size_t kTracyFakeMax = 16; +inline TracyFakeEvent g_tracy_events[kTracyFakeMax]; +inline std::size_t g_tracy_event_count = 0; + +inline void tracy_fake_record(bool alloc, const void* pointer, std::size_t bytes, const char* pool) +{ + if (g_tracy_event_count < kTracyFakeMax) + g_tracy_events[g_tracy_event_count++] = {alloc, pointer, bytes, pool}; +} + +#define TracyAllocN(pointer, bytes, pool) tracy_fake_record(true, (pointer), (bytes), (pool)) +#define TracyFreeN(pointer, pool) tracy_fake_record(false, (pointer), 0, (pool)) +#define TracyPlot(name, value) ((void)0) +#define ZoneScopedN(name) ((void)0) +#define FrameMark ((void)0) diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 6fb84217d3..e46a275565 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -516,7 +516,7 @@ def check_shader_records(): for group in ("DPP16", "DPP8") for form in ("v_cvt_flr_i32_f32_dpp", "v_cvt_rpi_i32_f32_dpp", "v_cvt_pkrtz_f16_f32_dpp") } - cvt_f32_excluded = {"v_cvt_norm_i16_f16_sdwa", "v_cvt_norm_u16_f16_sdwa"} + cvt_f32_excluded = {"v_rcp_f16_sdwa", "v_rsq_f16_sdwa"} for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) assert cvt_f32_int | cvt_dpp_forms <= reference, name @@ -1598,8 +1598,8 @@ def check_f16_exact_extra_forms(): neighbours = { ("VOP1", "v_rcp_f16"), ("VOP3", "v_rcp_f16_e64"), ("DPP16", "v_rcp_f16_dpp"), ("DPP8", "v_rcp_f16_dpp"), ("SDWA", "v_rcp_f16_sdwa"), - ("DPP16", "v_cvt_norm_i16_f16_dpp"), ("DPP8", "v_cvt_norm_i16_f16_dpp"), - ("SDWA", "v_cvt_norm_i16_f16_sdwa"), + ("DPP16", "v_rsq_f16_dpp"), ("DPP8", "v_rsq_f16_dpp"), + ("SDWA", "v_rsq_f16_sdwa"), } for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) @@ -1638,8 +1638,8 @@ def check_sdwa_cvt_forms(): assert len(forms) == 13 neighbours = { ("SDWA", "v_cndmask_b32_sdwa"), ("SDWA", "v_rcp_f16_sdwa"), - ("SDWA", "v_sqrt_f16_sdwa"), ("SDWA", "v_cvt_norm_i16_f16_sdwa"), - ("SDWA", "v_cvt_norm_u16_f16_sdwa"), + ("SDWA", "v_sqrt_f16_sdwa"), ("SDWA", "v_rsq_f16_sdwa"), + ("SDWA", "v_sin_f16_sdwa"), } for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) @@ -1655,6 +1655,43 @@ def check_sdwa_cvt_forms(): pixel.ACCEPTED.update(saved) +def check_f16_cvt_norm_forms(): + """The 10 binary16 normalized conversion forms (v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16 across + VOP1, VOP3, DPP16, DPP8, SDWA) count as covered once the translator accepts their fixtures.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for body in pixel.F16_CVT_NORM_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + ops = ("v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16") + forms = { + *{("VOP1", op) for op in ops}, + *{("VOP3", f"{op}_e64") for op in ops}, + *{(group, f"{op}_dpp") for group in ("DPP16", "DPP8") for op in ops}, + *{("SDWA", f"{op}_sdwa") for op in ops}, + } + assert len(forms) == 10 + neighbours = { + ("VOP1", "v_rcp_f16"), ("VOP3", "v_rcp_f16_e64"), + ("DPP16", "v_rcp_f16_dpp"), ("DPP8", "v_rcp_f16_dpp"), ("SDWA", "v_rcp_f16_sdwa"), + ("VOP1", "v_rsq_f16"), ("DPP16", "v_rsq_f16_dpp"), ("SDWA", "v_rsq_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not (neighbours & covered), (name, sorted(neighbours & covered)) + stripped = pixel.ACCEPTED - {"v_cvt_norm_i16_f16_dpp"} + assert not {("DPP16", "v_cvt_norm_i16_f16_dpp"), ("DPP8", "v_cvt_norm_i16_f16_dpp")} & fc.gfx_forms( + stripped, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + if __name__ == "__main__": check_denominators() check_example() @@ -1681,6 +1718,7 @@ def check_sdwa_cvt_forms(): check_sdwa_int_extra_forms() check_f16_exact_extra_forms() check_sdwa_cvt_forms() + check_f16_cvt_norm_forms() check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() diff --git a/tests/form_reference_cli_check.py b/tests/form_reference_cli_check.py new file mode 100644 index 0000000000..9ae521fac5 --- /dev/null +++ b/tests/form_reference_cli_check.py @@ -0,0 +1,450 @@ +"""Pure-Python CLI, atomic-write, path-guard, and mutation suite for tools/form_reference.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "form_reference.py" +sys.path.insert(0, str(TOOLS_DIR)) + +import form_reference # noqa: E402 + + +SYNTHETIC_RST = { + "AMDGPUAsmGFX10.rst": ( + "SOPP\n----\n\n.. parsed-literal::\n\n s_endpgm\n\n" + "EXP\n---\n\n exp\n" + ), + "AMDGPUAsmGFX1011.rst": ( + "SOPK\n----\n\n s_addk_i32 sdst, simm16\n" + ), + "AMDGPUAsmGFX1013.rst": ( + "SMEM\n----\n\n s_atomic_add sdata, sbase, offset\n\n" + "VOP1\n----\n\n v_mov_b32_e32 vdst, src0\n" + ), + "AMDGPUAsmGFX1030.rst": ( + "SOPP\n----\n\n s_endpgm\n\n" + "VOP3\n----\n\n v_fmac_f32_e64 vdst, src0, src1\n\n" + ".. toctree::\n :hidden:\n\n gfx1030_ignored_entry\n" + ), +} + + +def _populate_docs_dir(docs_dir: Path, *, skip: str | None = None) -> None: + docs_dir.mkdir(parents=True, exist_ok=True) + for name, text in SYNTHETIC_RST.items(): + if name == skip: + continue + (docs_dir / name).write_text(text, encoding="utf-8") + + +def _run_main(argv: list[str] | None, *, module=form_reference) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, script: Path = TOOL) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(script), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FormReferenceCliPositiveTests(unittest.TestCase): + def test_synthetic_rst_and_nested_out_dir_atomic_generation(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "llvm_docs" + _populate_docs_dir(docs) + out_dir = root / "nested" / "coverage" + self.assertFalse(out_dir.exists()) + + replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaces.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + with mock.patch.object(form_reference.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(docs), "--out-dir", str(out_dir)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(replaces), 3) + self.assertIn("gfx1013.tsv 5", out) + self.assertIn("rdna2.tsv 2", out) + self.assertIn("x64_zen2.tsv", out) + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + + gfx_lines = (out_dir / "gfx1013.tsv").read_text(encoding="utf-8").splitlines() + self.assertTrue(gfx_lines[0].startswith("# 5 forms. Source: "), gfx_lines[0]) + self.assertEqual( + gfx_lines[1:], + [ + "EXP\texp", + "SMEM\ts_atomic_add", + "SOPK\ts_addk_i32", + "SOPP\ts_endpgm", + "VOP1\tv_mov_b32_e32", + ], + ) + rdna_lines = (out_dir / "rdna2.tsv").read_text(encoding="utf-8").splitlines() + self.assertTrue(rdna_lines[0].startswith("# 2 forms. Source: "), rdna_lines[0]) + self.assertEqual(rdna_lines[1:], ["SOPP\ts_endpgm", "VOP3\tv_fmac_f32_e64"]) + x64_lines = (out_dir / "x64_zen2.tsv").read_text(encoding="utf-8").splitlines() + expected_x64 = form_reference.x64_forms() + self.assertTrue(x64_lines[0].startswith(f"# {len(expected_x64)} forms. Source: ")) + self.assertEqual(len(x64_lines) - 1, len(expected_x64)) + + def test_atomic_overwrite_sys_argv_and_main_entrypoint(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + out_dir = root / "out" + out_dir.mkdir() + for name in form_reference.OUTPUT_TSV_NAMES: + (out_dir / name).write_text("stale\n", encoding="utf-8") + + proc = _run_subprocess(str(docs), "--out-dir", str(out_dir)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + self.assertTrue( + (out_dir / "rdna2.tsv").read_text(encoding="utf-8").startswith("# 2 forms.") + ) + + # Verify argv=None forwarding and __main__ entrypoint. + out_entry = root / "entry_out" + cli_argv = [str(TOOL), str(docs), "--out-dir", str(out_entry)] + with mock.patch.object(sys, "argv", cli_argv): + code, _, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertTrue((out_entry / "gfx1013.tsv").is_file()) + + out_runpy = root / "runpy_out" + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(docs), "--out-dir", str(out_runpy)]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual( + sorted(p.name for p in out_runpy.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + + +@unittest.skipUnless(os.name == "posix", "POSIX permission modes only") +class FormReferencePermissionModeTests(unittest.TestCase): + def test_child_umask_modes_preserved_by_cli_rewrite(self) -> None: + with_mode = {"gfx1013.tsv": 0o600, "rdna2.tsv": 0o664, "x64_zen2.tsv": 0o644} + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + + fresh_dir = root / "fresh" + replaced_dir = root / "replaced" + replaced_dir.mkdir() + for name, mode in with_mode.items(): + stale = replaced_dir / name + stale.write_text("stale\n", encoding="utf-8") + stale.chmod(mode) + for out_dir in (fresh_dir, replaced_dir): + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(docs), "--out-dir", str(out_dir)], + capture_output=True, + text=True, + timeout=30, + umask=0o027, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + + self.assertEqual( + {p.name: p.stat().st_mode & 0o777 for p in fresh_dir.iterdir()}, + {name: 0o640 for name in form_reference.OUTPUT_TSV_NAMES}, + ) + self.assertEqual( + {p.name: p.stat().st_mode & 0o777 for p in replaced_dir.iterdir()}, + with_mode, + ) + for name in form_reference.OUTPUT_TSV_NAMES: + fresh = (fresh_dir / name).read_bytes() + self.assertTrue(fresh.startswith(b"# ")) + self.assertEqual((replaced_dir / name).read_bytes(), fresh) + + +class FormReferenceCliNegativeTests(unittest.TestCase): + def _assert_exit_1_clean(self, argv: list[str], *, fragment: str, check_subproc: bool = True) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, 1, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("form_reference:", err) + self.assertIn(fragment, err) + + if check_subproc: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("form_reference:", proc.stderr) + self.assertIn(fragment, proc.stderr) + + def test_missing_and_non_directory_docs_dir_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_dir = root / "never_created" + reg_file = root / "not_a_dir.txt" + reg_file.write_text("file", encoding="utf-8") + + with ( + mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")), + mock.patch.object(form_reference, "x64_forms", side_effect=AssertionError("x64")), + ): + for bad_docs, frag in ( + (str(root / "missing_docs"), "not a directory"), + (str(reg_file), "not a directory"), + ("", "must not be empty"), + (" ", "must not be empty"), + ): + with self.subTest(bad_docs=bad_docs): + self._assert_exit_1_clean( + [bad_docs, "--out-dir", str(out_dir)], + fragment=frag, + check_subproc=False, + ) + self.assertFalse(out_dir.exists()) + + proc = _run_subprocess(str(root / "missing_docs"), "--out-dir", str(out_dir)) + self.assertEqual(proc.returncode, 1) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("not a directory", proc.stderr) + self.assertFalse(out_dir.exists()) + + def test_missing_or_directory_rst_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_dir = root / "never_created" + + for missing_name in SYNTHETIC_RST: + docs = root / f"missing_{missing_name}" + _populate_docs_dir(docs, skip=missing_name) + with ( + mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")), + mock.patch.object(form_reference, "x64_forms", side_effect=AssertionError("x64")), + ): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_dir)], + fragment=missing_name, + check_subproc=False, + ) + self.assertFalse(out_dir.exists()) + + dir_rst_docs = root / "dir_rst_docs" + _populate_docs_dir(dir_rst_docs, skip="AMDGPUAsmGFX1030.rst") + (dir_rst_docs / "AMDGPUAsmGFX1030.rst").mkdir() + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(dir_rst_docs), "--out-dir", str(out_dir)], + fragment="AMDGPUAsmGFX1030.rst", + check_subproc=True, + ) + self.assertFalse(out_dir.exists()) + + def test_output_dir_file_parent_and_empty_out_dir_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + + # 1) Output file path is an existing directory. + out_with_dir = root / "out_with_dir" + out_with_dir.mkdir() + (out_with_dir / "gfx1013.tsv").mkdir() + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_with_dir)], + fragment="must not be a directory", + ) + self.assertEqual([p.name for p in out_with_dir.iterdir()], ["gfx1013.tsv"]) + + # 2) --out-dir itself is an existing regular file. + out_is_file = root / "file_out" + out_is_file.write_text("keep-me", encoding="utf-8") + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_is_file)], + fragment="not a directory", + ) + self.assertEqual(out_is_file.read_text(encoding="utf-8"), "keep-me") + + # 3) Parent ancestor of --out-dir is a regular file. + nested_under_file = out_is_file / "sub" + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(nested_under_file)], + fragment="output parent is not a directory", + ) + self.assertEqual(out_is_file.read_text(encoding="utf-8"), "keep-me") + + # 4) Empty --out-dir. + self._assert_exit_1_clean([str(docs), "--out-dir", " "], fragment="--out-dir must not be empty") + + def test_output_symlink_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + out_dir = root / "out" + out_dir.mkdir() + real_target = root / "real_target.tsv" + real_target.write_text("untouched\n", encoding="utf-8") + link_target = out_dir / "x64_zen2.tsv" + try: + link_target.symlink_to(real_target) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with mock.patch.object(form_reference, "llvm_forms", side_effect=AssertionError("parsed")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_dir)], + fragment="symlink", + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched\n") + self.assertEqual([p.name for p in out_dir.iterdir()], ["x64_zen2.tsv"]) + + def test_os_replace_failure_leaves_zero_tmp_and_preserves_existing_tsv(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + docs = root / "docs" + _populate_docs_dir(docs) + out_dir = root / "out" + out_dir.mkdir() + for name in form_reference.OUTPUT_TSV_NAMES: + (out_dir / name).write_text(f"prior-{name}\n", encoding="utf-8") + + with mock.patch.object(form_reference.os, "replace", side_effect=OSError("simulated replace fail")): + self._assert_exit_1_clean( + [str(docs), "--out-dir", str(out_dir)], + fragment="simulated replace fail", + check_subproc=False, + ) + + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv"], + ) + for name in form_reference.OUTPUT_TSV_NAMES: + self.assertEqual((out_dir / name).read_text(encoding="utf-8"), f"prior-{name}\n") + + def test_argparse_errors_py314_safe(self) -> None: + with TemporaryDirectory() as tmp: + docs = Path(tmp) / "docs" + _populate_docs_dir(docs) + for argv, frag in ( + ([], "required"), + ([str(docs), "--bogus-flag"], "unrecognized"), + ([str(docs), "--out-dir"], "expected one argument"), + ): + with self.subTest(argv=argv): + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("usage:", proc.stderr.lower()) + self.assertIn(frag, proc.stderr) + + def test_fast_temp_mutations_killed(self) -> None: + """Verify mutated copies of form_reference.py fail targeted guard assertions.""" + original_src = TOOL.read_text(encoding="utf-8") + mutations = ( + ( + "drop_docs_is_dir", + " if not docs.is_dir():", + " if False:", + lambda m_docs, m_out: [str(m_docs / "not_a_dir"), "--out-dir", str(m_out)], + "not a directory", + ), + ( + "drop_rst_is_file", + " if not rst.is_file():", + " if False:", + lambda m_docs, m_out: [str(m_docs / "missing_rst"), "--out-dir", str(m_out)], + "missing or non-regular", + ), + ( + "drop_out_dir_check", + " if path.exists() and path.is_dir():", + " if False:", + lambda m_docs, m_out: [str(m_docs / "valid"), "--out-dir", str(m_out / "dir_collision")], + "output path must not be a directory", + ), + ) + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_docs = root / "valid" + _populate_docs_dir(valid_docs) + (root / "not_a_dir").write_text("file", encoding="utf-8") + _populate_docs_dir(root / "missing_rst", skip="AMDGPUAsmGFX1030.rst") + out_base = root / "out" + out_base.mkdir() + (out_base / "dir_collision").mkdir() + (out_base / "dir_collision" / "gfx1013.tsv").mkdir() + + for label, old, new, argv_fn, expected_msg in mutations: + mutated_src = original_src.replace(old, new, 1) + self.assertNotEqual(mutated_src, original_src, label) + mutated_tool = root / f"mut_{label}.py" + mutated_tool.write_text(mutated_src, encoding="utf-8") + argv = argv_fn(root, out_base) + proc = _run_subprocess(*argv, script=mutated_tool) + self.assertNotIn(expected_msg, proc.stderr, label) + + # Mutating temp-file cleanup must leak a .tmp file on replace failure. + no_cleanup_src = original_src.replace("tmp_path.unlink(missing_ok=True)", "pass", 1) + self.assertNotEqual(no_cleanup_src, original_src) + mut_ns: dict[str, object] = {"__file__": str(TOOL)} + exec(compile(no_cleanup_src, str(root / "mut_cleanup.py"), "exec"), mut_ns) + leak_dir = root / "leak_out" + leak_dir.mkdir() + with mock.patch.object(mut_ns["os"], "replace", side_effect=OSError("boom")): + with self.assertRaises(OSError): + mut_ns["_write_atomic"](leak_dir / "gfx1013.tsv", "content") + self.assertTrue(any(p.suffix == ".tmp" for p in leak_dir.iterdir())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/fuzz_cpu_cli_check.py b/tests/fuzz_cpu_cli_check.py new file mode 100644 index 0000000000..4f26ca1853 --- /dev/null +++ b/tests/fuzz_cpu_cli_check.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, path/count guard, and mutation suite for tools/fuzz_cpu.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "fuzz_cpu.py" +sys.path.insert(0, str(TOOLS_DIR)) + +import fuzz_cpu # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = fuzz_cpu.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FuzzCpuCliPositiveTests(unittest.TestCase): + def test_emit_multi_area_atomic_nested_outputs_and_zero_tmp_files(self) -> None: + areas_to_check = ("leaf", "frames", "calls", "switches", "scalar_fp", "x87", "bits") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + real_replace = os.replace + + for idx, area in enumerate(areas_to_check): + with self.subTest(area=area): + out_dir = base / f"nested_{idx}" / area + asm_path = out_dir / f"{area}.asm" + def_path = out_dir / f"{area}.def" + seen_replaces: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.resolve(), dst_path.parent.resolve()) + self.assertTrue(src_path.name.endswith(".tmp")) + return real_replace(src, dst) + + with mock.patch.object(fuzz_cpu.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([ + "emit", + "0xA902", + "4", + str(asm_path), + str(def_path), + "--area", + area, + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(seen_replaces), 2) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), sorted([asm_path.name, def_path.name])) + asm_text = asm_path.read_text(encoding="utf-8") + def_text = def_path.read_text(encoding="utf-8") + self.assertIn(".code", asm_text) + self.assertTrue(asm_text.endswith("END\n")) + expected_lib = fuzz_cpu.AREAS[area][1] + self.assertTrue(def_text.startswith(f"LIBRARY {expected_lib}\nEXPORTS\n")) + + # End-to-end subprocess check with overwrite on existing files. + sub_dir = base / "sub_emit" + sub_asm = sub_dir / "out.asm" + sub_def = sub_dir / "out.def" + sub_dir.mkdir() + sub_asm.write_text("stale asm", encoding="utf-8") + sub_def.write_text("stale def", encoding="utf-8") + proc = _run_subprocess("emit", "0x1234", "2", str(sub_asm), str(sub_def), "--area", "loops") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertEqual(proc.stderr, "") + self.assertEqual(sorted(p.name for p in sub_dir.iterdir()), ["out.asm", "out.def"]) + self.assertIn("LIBRARY cpu_fuzz_loops", sub_def.read_text(encoding="utf-8")) + + def test_translate_atomic_write_and_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "synthetic.dll" + image.write_bytes(b"MZ-synthetic-placeholder") + out_cpp = base / "nested" / "lifted.cpp" + translated_calls: list[tuple[Path, list[str]]] = [] + + def fake_translate(img: Path, names: list[str]) -> tuple[str, dict]: + translated_calls.append((img, list(names))) + return "// lifted\nint ok = 1;\n", {} + + fake_mod = types.SimpleNamespace(translate=fake_translate) + with mock.patch.object(fuzz_cpu, "translator_module", return_value=fake_mod): + code, out, err = _run_main(["translate", "0xA902", "2", str(image), str(out_cpp)]) + + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(translated_calls), 1) + self.assertEqual(translated_calls[0][0], image) + self.assertEqual(translated_calls[0][1], ["fuzz_0", "fuzz_1"]) + self.assertEqual(out_cpp.read_text(encoding="utf-8"), "// lifted\nint ok = 1;\n") + self.assertEqual([p.name for p in out_cpp.parent.iterdir()], ["lifted.cpp"]) + + # sys.argv forwarding (argv=None) and __main__ entrypoint via runpy. + asm_entry = base / "entry.asm" + def_entry = base / "entry.def" + cli_argv = [str(TOOL), "emit", "0x55", "1", str(asm_entry), str(def_entry)] + with mock.patch.object(sys, "argv", cli_argv): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertTrue(asm_entry.is_file() and def_entry.is_file()) + + asm_entry.unlink() + def_entry.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(asm_entry.is_file() and def_entry.is_file()) + + +class FuzzCpuCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_non_positive_count_rejected_upfront_in_emit_translate_and_check(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "image.dll" + lifted = base / "lifted.dll" + o2 = base / "o2.dll" + for dll in (image, lifted, o2): + dll.write_bytes(b"MZ-placeholder") + absent_asm = base / "absent_emit" / "out.asm" + absent_def = base / "absent_emit" / "out.def" + absent_cpp = base / "absent_trans" / "out.cpp" + + for bad_count in ("0", "-3"): + with self.subTest(bad_count=bad_count): + with ( + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + mock.patch.object(fuzz_cpu.ctypes, "CDLL", side_effect=AssertionError("should not load DLL")), + ): + self._assert_clean_failure( + ["emit", "1", bad_count, str(absent_asm), str(absent_def)], + fragments=("count must be >= 1",), + ) + self._assert_clean_failure( + ["translate", "1", bad_count, str(image), str(absent_cpp)], + fragments=("count must be >= 1",), + ) + self._assert_clean_failure( + ["check", "1", bad_count, str(image), str(lifted), str(o2)], + fragments=("count must be >= 1",), + ) + + self.assertFalse(absent_asm.parent.exists()) + self.assertFalse(absent_cpp.parent.exists()) + + def test_missing_and_directory_pe_rejected_upfront_in_translate_and_check(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + valid_dll = base / "valid.dll" + valid_dll.write_bytes(b"MZ-placeholder") + dir_dll = base / "dir_dll" + dir_dll.mkdir() + missing_dll = base / "missing.dll" + absent_cpp = base / "never_created" / "out.cpp" + + with ( + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + ): + self._assert_clean_failure( + ["translate", "1", "2", str(missing_dll), str(absent_cpp)], + fragments=("image file not found",), + ) + self._assert_clean_failure( + ["translate", "1", "2", str(dir_dll), str(absent_cpp)], + fragments=("image path is a directory",), + ) + self.assertFalse(absent_cpp.parent.exists()) + + with mock.patch.object(fuzz_cpu.ctypes, "CDLL", side_effect=AssertionError("should not load DLL")): + for label, argv, frag in ( + ("missing_native", ["check", "1", "2", str(missing_dll), str(valid_dll), str(valid_dll)], "native file not found"), + ("dir_native", ["check", "1", "2", str(dir_dll), str(valid_dll), str(valid_dll)], "native path is a directory"), + ("missing_lifted", ["check", "1", "2", str(valid_dll), str(missing_dll), str(valid_dll)], "lifted file not found"), + ("dir_lifted", ["check", "1", "2", str(valid_dll), str(dir_dll), str(valid_dll)], "lifted path is a directory"), + ("missing_o2", ["check", "1", "2", str(valid_dll), str(valid_dll), str(missing_dll)], "o2 file not found"), + ("dir_o2", ["check", "1", "2", str(valid_dll), str(valid_dll), str(dir_dll)], "o2 path is a directory"), + ( + "missing_mutant", + ["check", "1", "2", str(valid_dll), str(valid_dll), str(valid_dll), "--area", "frames", "--mutant", str(missing_dll)], + "mutant file not found", + ), + ( + "dir_mutant", + ["check", "1", "2", str(valid_dll), str(valid_dll), str(valid_dll), "--area", "frames", "--mutant", str(dir_dll)], + "mutant path is a directory", + ), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, fragments=(frag,)) + + def test_corrupt_pe_translate_exits_cleanly_without_traceback(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + corrupt = base / "corrupt.dll" + corrupt.write_bytes(b"not a PE image") + out_cpp = base / "absent" / "lifted.cpp" + self._assert_clean_failure(["translate", "0xA902", "1", str(corrupt), str(out_cpp)]) + self.assertFalse(out_cpp.parent.exists()) + + def test_output_dir_file_parent_and_collision_guards(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"MZ-input") + existing_dir = base / "out_dir" + existing_dir.mkdir() + file_parent = base / "file_parent.txt" + file_parent.write_text("keep-parent", encoding="utf-8") + existing_asm = base / "existing.asm" + existing_asm.write_text("keep-asm", encoding="utf-8") + hardlink_def = base / "hardlink.def" + hardlink_def.hardlink_to(existing_asm) + hardlink_cpp = base / "hardlink.cpp" + hardlink_cpp.hardlink_to(image) + + with ( + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + ): + for label, argv, frag in ( + ("emit_asm_dir", ["emit", "1", "1", str(existing_dir), str(base / "ok.def")], "directory"), + ("emit_def_dir", ["emit", "1", "1", str(base / "ok.asm"), str(existing_dir)], "directory"), + ("emit_asm_file_parent", ["emit", "1", "1", str(file_parent / "a.asm"), str(base / "ok.def")], "not a directory"), + ("emit_def_ancestor_file", ["emit", "1", "1", str(base / "ok.asm"), str(file_parent / "sub" / "a.def")], "not a directory"), + ("emit_same_path", ["emit", "1", "1", str(base / "same.asm"), str(base / "same.asm")], "distinct"), + ("emit_alias_path", ["emit", "1", "1", str(base / "same.asm"), str(existing_dir / ".." / "same.asm")], "distinct"), + ("emit_hardlink_asm_def", ["emit", "1", "1", str(existing_asm), str(hardlink_def)], "distinct"), + ("translate_out_dir", ["translate", "1", "1", str(image), str(existing_dir)], "directory"), + ("translate_file_parent", ["translate", "1", "1", str(image), str(file_parent / "out.cpp")], "not a directory"), + ("translate_same_image", ["translate", "1", "1", str(image), str(image)], "distinct"), + ("translate_hardlink_image", ["translate", "1", "1", str(image), str(hardlink_cpp)], "distinct"), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, fragments=(frag,)) + + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-parent") + self.assertEqual(existing_asm.read_text(encoding="utf-8"), "keep-asm") + self.assertEqual(image.read_bytes(), b"MZ-input") + self.assertFalse((base / "ok.asm").exists()) + self.assertFalse((base / "ok.def").exists()) + + def test_output_symlink_rejected_before_write(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + image = base / "input.dll" + image.write_bytes(b"MZ-input") + out_dir = base / "out" + out_dir.mkdir() + real_target = out_dir / "real.txt" + real_target.write_text("untouched", encoding="utf-8") + live_link = out_dir / "live_link.asm" + dangling_link = out_dir / "dangling_link.cpp" + + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.cpp") + has_symlinks = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + has_symlinks = False + + with ( + mock.patch.object(fuzz_cpu, "_write_atomic", side_effect=AssertionError("should not write")), + mock.patch.object(fuzz_cpu, "translator_module", side_effect=AssertionError("should not lift")), + ): + if has_symlinks: + self._assert_clean_failure( + ["emit", "1", "1", str(live_link), str(out_dir / "ok.def")], + fragments=("symlink",), + ) + self._assert_clean_failure( + ["translate", "1", "1", str(image), str(dangling_link)], + fragments=("symlink",), + ) + else: + with mock.patch.object(Path, "is_symlink", autospec=True, side_effect=lambda p: p == real_target): + self._assert_clean_failure( + ["emit", "1", "1", str(real_target), str(out_dir / "ok.def")], + fragments=("symlink",), + check_subprocess=False, + ) + self._assert_clean_failure( + ["translate", "1", "1", str(image), str(real_target)], + fragments=("symlink",), + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + + def test_os_replace_and_staging_failures_preserve_target_and_leave_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + out_dir = base / "out_dir" + out_dir.mkdir() + asm_path = out_dir / "fuzz.asm" + def_path = out_dir / "fuzz.def" + asm_path.write_text("prior-asm", encoding="utf-8") + def_path.write_text("prior-def", encoding="utf-8") + + # 1) os.replace fails on existing target -> target preserved, 0 .tmp files. + def fail_replace(src, _dst): + self.assertTrue(Path(src).is_file()) + raise OSError("simulated replace failure") + + with mock.patch.object(fuzz_cpu.os, "replace", side_effect=fail_replace): + self._assert_clean_failure( + ["emit", "0xA902", "2", str(asm_path), str(def_path)], + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(asm_path.read_text(encoding="utf-8"), "prior-asm") + self.assertEqual(def_path.read_text(encoding="utf-8"), "prior-def") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["fuzz.asm", "fuzz.def"]) + + # 2) os.replace fails on translate -> prior .cpp preserved, 0 .tmp files. + image = base / "input.dll" + image.write_bytes(b"MZ-input") + cpp_path = out_dir / "lifted.cpp" + cpp_path.write_text("prior-cpp", encoding="utf-8") + fake_mod = types.SimpleNamespace(translate=lambda _img, _names: ("// new\n", {})) + with ( + mock.patch.object(fuzz_cpu, "translator_module", return_value=fake_mod), + mock.patch.object(fuzz_cpu.os, "replace", side_effect=fail_replace), + ): + self._assert_clean_failure( + ["translate", "0xA902", "2", str(image), str(cpp_path)], + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(cpp_path.read_text(encoding="utf-8"), "prior-cpp") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["fuzz.asm", "fuzz.def", "lifted.cpp"]) + + # 3) Staging failure after .tmp creation -> .tmp unlinked, os.replace not called, target preserved. + real_ntf = fuzz_cpu.tempfile.NamedTemporaryFile + + class FailingWriteHandle: + def __init__(self, inner): + self._inner = inner + self.name = inner.name + + def __enter__(self): + self._inner.__enter__() + return self + + def __exit__(self, exc_type, exc, tb): + return self._inner.__exit__(exc_type, exc, tb) + + def write(self, _data): + raise OSError("simulated staging write failure") + + with ( + mock.patch.object(fuzz_cpu.os, "replace") as replace_mock, + mock.patch.object( + fuzz_cpu.tempfile, + "NamedTemporaryFile", + side_effect=lambda *a, **kw: FailingWriteHandle(real_ntf(*a, **kw)), + ), + ): + self._assert_clean_failure( + ["emit", "0xA902", "2", str(asm_path), str(def_path)], + fragments=("simulated staging write failure",), + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(asm_path.read_text(encoding="utf-8"), "prior-asm") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["fuzz.asm", "fuzz.def", "lifted.cpp"]) + + def test_argparse_errors_py314_safe(self) -> None: + for argv, frags in ( + ([], ("required",)), + (["emit"], ("required",)), + (["emit", "0x1", "2", "a.asm", "a.def", "--area", "bogus"], ("invalid choice",)), + (["translate", "bad_seed", "1", "a.dll", "a.cpp"], ("invalid",)), + (["check", "1", "1", "n.dll", "l.dll", "o.dll", "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/gdk/runtime_families_probe.cpp b/tests/gdk/runtime_families_probe.cpp new file mode 100644 index 0000000000..609766ec4d --- /dev/null +++ b/tests/gdk/runtime_families_probe.cpp @@ -0,0 +1,95 @@ +// Original fixture for tools/gdk_runtime_oracle.py. It prints only public +// observations from the desktop GDK runtime; it never prints package contents. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> +#include <cstddef> +#include <cstdint> +#include <cstdio> +#include <vector> +#include <XGameRuntime.h> + +static void hr(const char* name, HRESULT value) +{ + std::printf("%s=0x%08X\n", name, static_cast<unsigned>(value)); +} + +int main() +{ +#ifndef X2W_SHIM + hr("init", XGameRuntimeInitialize()); +#endif + + std::printf("device=%u\n", static_cast<unsigned>(XSystemGetDeviceType())); + + char console_id[128]{}; + std::size_t console_used = 0; + hr("console_id", XSystemGetConsoleId(sizeof(console_id), console_id, &console_used)); + std::printf("console_used=%zu console_value=%s\n", console_used, console_id); + + std::uint32_t title_id = 0; + hr("title_id", XGameGetXboxTitleId(&title_id)); + std::printf("title_value=0x%08X\n", static_cast<unsigned>(title_id)); + + std::size_t path_size = 0; + hr("pls_path_size", XPersistentLocalStorageGetPathSize(&path_size)); + std::printf("pls_path_size_value=%zu\n", path_size); + if (path_size > 0) + { + std::vector<char> path(path_size + 1, 0); + std::size_t used = 0; + hr("pls_path", XPersistentLocalStorageGetPath(path.size(), path.data(), &used)); + std::printf("pls_path_used=%zu pls_path_value=%s\n", used, path.data()); + } + + XPersistentLocalStorageSpaceInfo space{}; + hr("pls_space", XPersistentLocalStorageGetSpaceInfo(&space)); + std::printf("pls_space_available=%llu total_free=%llu used=%llu total=%llu\n", + static_cast<unsigned long long>(space.availableFreeBytes), + static_cast<unsigned long long>(space.totalFreeBytes), + static_cast<unsigned long long>(space.usedBytes), + static_cast<unsigned long long>(space.totalBytes)); + + XPackageMountHandle mount = nullptr; + hr("xpackage_mount_missing", XPackageMount("x2w-nonexistent-package", &mount)); + std::printf("xpackage_mount_handle=%p\n", static_cast<void*>(mount)); + if (mount) + { + std::size_t mount_size = 0; + hr("xpackage_path_size", XPackageGetMountPathSize(mount, &mount_size)); + std::printf("xpackage_path_size_value=%zu\n", mount_size); + if (mount_size > 0) + { + std::vector<char> path(mount_size + 1, 0); + hr("xpackage_path", XPackageGetMountPath(mount, path.size(), path.data())); + std::printf("xpackage_path_value=%s\n", path.data()); + } + XPackageCloseMountHandle(mount); + std::printf("xpackage_closed=1\n"); + } + + XTaskQueueHandle queue = nullptr; + hr("queue_create", XTaskQueueCreate(XTaskQueueDispatchMode::Manual, + XTaskQueueDispatchMode::Manual, &queue)); + std::printf("queue_handle=%p\n", static_cast<void*>(queue)); + if (queue) + { + std::printf("queue_dispatch=%u\n", + XTaskQueueDispatch(queue, XTaskQueuePort::Completion, 0) ? 1u : 0u); + XTaskQueueCloseHandle(queue); + std::printf("queue_closed=1\n"); + } + +#ifndef X2W_SHIM + char sandbox[64]{}; + std::size_t sandbox_used = 0; + hr("sandbox", XSystemGetXboxLiveSandboxId(sizeof(sandbox), sandbox, &sandbox_used)); + std::printf("sandbox_used=%zu sandbox_value=%s\n", sandbox_used, sandbox); + XGameRuntimeUninitialize(); +#endif + return 0; +} diff --git a/tests/gdk/shaders/cases.json b/tests/gdk/shaders/cases.json new file mode 100644 index 0000000000..1ea3a520b1 --- /dev/null +++ b/tests/gdk/shaders/cases.json @@ -0,0 +1,40 @@ +{ + "cases": [ + { + "name": "wave64_ballot_ps", + "source": "wave64_ballot_ps.hlsl", + "profile": "ps_6_0", + "entry": "main" + }, + { + "name": "root_constants_vs", + "source": "root_constants_vs.hlsl", + "profile": "vs_6_0", + "entry": "main" + }, + { + "name": "image_sample_c_lz_ps", + "source": "image_sample_c_lz_ps.hlsl", + "profile": "ps_6_0", + "entry": "main" + }, + { + "name": "packed_types_cs", + "source": "packed_types_cs.hlsl", + "profile": "cs_6_0", + "entry": "main" + }, + { + "name": "derivatives_ps", + "source": "derivatives_ps.hlsl", + "profile": "ps_6_0", + "entry": "main" + }, + { + "name": "mesh_ngg_ms", + "source": "mesh_ngg_ms.hlsl", + "profile": "ms_6_5", + "entry": "main" + } + ] +} diff --git a/tests/gdk/shaders/derivatives_ps.hlsl b/tests/gdk/shaders/derivatives_ps.hlsl new file mode 100644 index 0000000000..930a7cb0ad --- /dev/null +++ b/tests/gdk/shaders/derivatives_ps.hlsl @@ -0,0 +1,8 @@ +// Original corpus case: implicit derivatives and fwidth in a pixel stage. +float4 main(float2 uv : TEXCOORD0) : SV_Target +{ + float2 dx = ddx(uv); + float2 dy = ddy(uv); + float width = fwidth(uv.x + uv.y); + return float4(dx, dy.x + dy.y, width); +} diff --git a/tests/gdk/shaders/image_sample_c_lz_ps.hlsl b/tests/gdk/shaders/image_sample_c_lz_ps.hlsl new file mode 100644 index 0000000000..f37212cb0d --- /dev/null +++ b/tests/gdk/shaders/image_sample_c_lz_ps.hlsl @@ -0,0 +1,8 @@ +// Original corpus case: comparison sample at an explicit level. +Texture2D<float4> Depth : register(t0); +SamplerComparisonState Shadow : register(s0); + +float4 main(float2 uv : TEXCOORD0) : SV_Target +{ + return Depth.SampleCmpLevelZero(Shadow, uv, 0.5); +} diff --git a/tests/gdk/shaders/mesh_ngg_ms.hlsl b/tests/gdk/shaders/mesh_ngg_ms.hlsl new file mode 100644 index 0000000000..4a24fe7c6a --- /dev/null +++ b/tests/gdk/shaders/mesh_ngg_ms.hlsl @@ -0,0 +1,16 @@ +// Original corpus case: a fixed three-vertex mesh shader. +struct Vertex +{ + float4 position : SV_Position; +}; + +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void main(out vertices Vertex verts[3], out indices uint3 tris[1]) +{ + SetMeshOutputCounts(3, 1); + verts[0].position = float4(-1.0, -1.0, 0.0, 1.0); + verts[1].position = float4(1.0, -1.0, 0.0, 1.0); + verts[2].position = float4(0.0, 1.0, 0.0, 1.0); + tris[0] = uint3(0, 1, 2); +} diff --git a/tests/gdk/shaders/packed_types_cs.hlsl b/tests/gdk/shaders/packed_types_cs.hlsl new file mode 100644 index 0000000000..959f02b262 --- /dev/null +++ b/tests/gdk/shaders/packed_types_cs.hlsl @@ -0,0 +1,11 @@ +// Original corpus case: packed 16-bit fields in a compute stage. +RWStructuredBuffer<uint> Output : register(u0); + +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) +{ + uint packed = (id.x & 0xffffu) | ((id.y & 0xffffu) << 16); + uint low = packed & 0xffffu; + uint high = packed >> 16; + Output[id.x] = low + high + WaveActiveCountBits(low != 0u); +} diff --git a/tests/gdk/shaders/root_constants_vs.hlsl b/tests/gdk/shaders/root_constants_vs.hlsl new file mode 100644 index 0000000000..333e6eca17 --- /dev/null +++ b/tests/gdk/shaders/root_constants_vs.hlsl @@ -0,0 +1,13 @@ +// Original corpus case: a root signature with one constant buffer. +cbuffer Constants : register(b0) +{ + float4x4 Transform; + float4 Tint; +}; + +[RootSignature("RootFlags(0), CBV(b0)")] +float4 main(uint id : SV_VertexID) : SV_Position +{ + float4 position = float4(id & 1u, (id >> 1) & 1u, 0.0, 1.0); + return mul(Transform, position) + Tint; +} diff --git a/tests/gdk/shaders/wave64_ballot_ps.hlsl b/tests/gdk/shaders/wave64_ballot_ps.hlsl new file mode 100644 index 0000000000..6e2ffbbe15 --- /dev/null +++ b/tests/gdk/shaders/wave64_ballot_ps.hlsl @@ -0,0 +1,11 @@ +// Original corpus case: wave ballot and lane index in a pixel stage. +Texture2D<float4> Color : register(t0); +SamplerState Linear : register(s0); + +float4 main(float2 uv : TEXCOORD0) : SV_Target +{ + uint4 ballot = WaveActiveBallot(uv.x > 0.5); + uint count = WaveActiveCountBits(uv.y > 0.5); + float4 color = Color.Sample(Linear, uv); + return color + float4(ballot.x & 1u, count & 1u, WaveGetLaneIndex() & 1u, 0.0); +} diff --git a/tests/gdk_exports_check.py b/tests/gdk_exports_check.py new file mode 100644 index 0000000000..3af413d3f4 --- /dev/null +++ b/tests/gdk_exports_check.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_exports.py and tools/gdk_shim_coverage.py. + +Uses synthetic dumpbin text and synthetic .def files. It needs neither Windows +nor the GDK; the PE scanner is a thin wrapper over pefile and is exercised by +the real inventory outside the repository. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_exports as exports # noqa: E402 +import gdk_shim_coverage as coverage # noqa: E402 + + +DLL_TEXT = """Microsoft (R) COFF/PE Dumper Version 14.44.35207.0 + +Dump of file xg_xs.dll + +File Type: DLL + + Exports + + ordinal hint RVA name + + 1 0 00001000 XGComputeBufferLayout + 2 1 00001200 XGComputeTexture2DLayout + 3 2 00001400 IID_IXGThing +""" + +LIB_TEXT = """Dump of file xmem.lib + +File Type: LIBRARY + +Exports + + ordinal name + + 1 XMemAlloc + XMemFree + ?XMemInternal@@YAXXZ +""" + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_parse(): + dll = exports.parse_dumpbin_text(DLL_TEXT) + check(dll == [ + {"ordinal": 1, "name": "XGComputeBufferLayout", "rva": "0x1000"}, + {"ordinal": 2, "name": "XGComputeTexture2DLayout", "rva": "0x1200"}, + {"ordinal": 3, "name": "IID_IXGThing", "rva": "0x1400"}, + ], f"DLL parse {dll}") + lib = exports.parse_dumpbin_text(LIB_TEXT) + check(lib == [ + {"ordinal": 1, "name": "XMemAlloc", "rva": None}, + {"ordinal": None, "name": "XMemFree", "rva": None}, + {"ordinal": None, "name": "?XMemInternal@@YAXXZ", "rva": None}, + ], f"LIB parse {lib}") + + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + source = directory / "xg_xs.txt" + source.write_text(DLL_TEXT, encoding="utf-8") + output = directory / "exports.json" + code = exports.main([ + "parse-dumpbin", str(source), "--json", str(output), "--kind", "dll", "--sdk", "999" + ]) + check(code == 0, f"parse-dumpbin exit {code}") + document = json.loads(output.read_text(encoding="utf-8")) + check(document["count"] == 3, f"count {document['count']}") + check(document["sdk"] == "999", f"sdk {document['sdk']}") + check(document["modules"][0]["module"] == "xg_xs", f"module {document['modules'][0]['module']}") + check(document["modules"][0]["sdk"] == "999", f"module sdk {document['modules'][0]['sdk']}") + check(len(document["modules"][0]["sha256"]) == 64, "sha256") + print("exports: DLL, LIB, ordinal and CLI parsing passed") + + +def check_coverage(): + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + inventory = { + "sdk": "261000", + "modules": [ + { + "file": "xg_xs.dll", + "exports": [ + {"ordinal": 1, "name": "XGComputeBufferLayout", "rva": "0x1000"}, + {"ordinal": 2, "name": "XGComputeTexture2DLayout", "rva": "0x1200"}, + {"ordinal": 3, "name": "IID_IXGThing", "rva": "0x1400"}, + ], + }, + { + "file": "xmem.lib", + "exports": [ + {"ordinal": None, "name": "XMemAlloc", "rva": None}, + {"ordinal": None, "name": "XMemFree", "rva": None}, + ], + }, + ], + } + inventory_path = directory / "exports.json" + inventory_path.write_text(json.dumps(inventory), encoding="utf-8") + xg_def = directory / "xg_xs.def" + xg_def.write_text( + "LIBRARY xg_xs\nEXPORTS\nXGComputeBufferLayout\nIID_IXGThing DATA\nx2w_local\n", + encoding="utf-8", + ) + xmem_def = directory / "xmem.def" + xmem_def.write_text( + "LIBRARY xmem\nEXPORTS\nXMemAlloc @1\nXMemFree\n?XMemInternal@@YAXXZ\n", + encoding="utf-8", + ) + output_json = directory / "coverage.json" + output_md = directory / "coverage.md" + code = coverage.main([ + "--exports", str(inventory_path), + "--def", "xg_xs=" + str(xg_def), + "--def", "xmem=" + str(xmem_def), + "--json", str(output_json), + "--markdown", str(output_md), + ]) + check(code == 0, f"coverage exit {code}") + rows = {row["module"]: row for row in json.loads(output_json.read_text(encoding="utf-8"))} + xg = rows["xg_xs"] + check(xg["gdk_functions"] == 2, f"xg functions {xg['gdk_functions']}") + check(xg["shim_functions"] == 2, f"xg shim functions {xg['shim_functions']}") + check(xg["covered_functions"] == 1, f"xg covered {xg['covered_functions']}") + check(xg["missing_functions"] == ["XGComputeTexture2DLayout"], f"xg missing {xg['missing_functions']}") + check(xg["covered_data"] == 1, f"xg data {xg['covered_data']}") + check(xg["extra"] == ["x2w_local"], f"xg extra {xg['extra']}") + check(xg["ordinals"] == { + "IID_IXGThing": 3, "XGComputeBufferLayout": 1, "XGComputeTexture2DLayout": 2 + }, f"xg ordinals {xg['ordinals']}") + check(rows["xmem"]["def_ordinals"] == {"XMemAlloc": 1}, f"xmem def ordinals {rows['xmem']['def_ordinals']}") + check("?XMemInternal@@YAXXZ" in rows["xmem"]["extra"], f"decorated name {rows['xmem']['extra']}") + check("| xg_xs | 2 | 2 | 1 | 1 |" in output_md.read_text(encoding="utf-8"), "markdown table") + check(coverage.main([ + "--exports", str(inventory_path), + "--def", "xg_xs=" + str(xg_def), + "--fail-on-missing", + ]) == 1, "fail-on-missing exit") + print("coverage: functions, data, extras, ordinals and exit codes passed") + + +def check_merge(): + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + inventory = { + "modules": [ + { + "module": "d3d12_xs", + "file": "d3d12_xs.lib.txt", + "exports": [ + {"ordinal": 1, "name": "D3D12XLibOnly", "rva": None}, + {"ordinal": None, "name": "Shared", "rva": None}, + ], + }, + { + "module": "d3d12_xs", + "file": "d3d12_xs.dll.txt", + "exports": [ + {"ordinal": 2, "name": "Shared", "rva": "0x1000"}, + {"ordinal": 3, "name": "D3D12XDllOnly", "rva": "0x2000"}, + ], + }, + ], + } + merged = coverage.load_exports(inventory) + check(set(merged) == {"d3d12_xs"}, f"merged keys {set(merged)}") + check( + {item["name"] for item in merged["d3d12_xs"]["exports"]} + == {"D3D12XLibOnly", "Shared", "D3D12XDllOnly"}, + f"merged exports {merged['d3d12_xs']['exports']}", + ) + inventory_path = directory / "exports.json" + inventory_path.write_text(json.dumps(inventory), encoding="utf-8") + def_path = directory / "d3d12_xs.def" + def_path.write_text( + "LIBRARY d3d12_xs\nEXPORTS\nShared\nD3D12XLibOnly\n", encoding="utf-8" + ) + output = directory / "coverage.json" + check(coverage.main([ + "--exports", str(inventory_path), + "--def", "d3d12_xs=" + str(def_path), + "--json", str(output), + ]) == 0, "merge coverage exit") + row = json.loads(output.read_text(encoding="utf-8"))[0] + check(row["gdk_functions"] == 3, f"merge functions {row['gdk_functions']}") + check(row["covered_functions"] == 2, f"merge covered {row['covered_functions']}") + check(row["missing_functions"] == ["D3D12XDllOnly"], f"merge missing {row['missing_functions']}") + print("exports: LIB+DLL merge and module-name key passed") + + +def check_unmeasured(): + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + empty_capture = directory / "empty.txt" + empty_capture.write_text("not a dumpbin export capture\n", encoding="utf-8") + collected = exports.collect_dumpbin(empty_capture, "dll") + check(collected[0].get("error") == "no exports parsed", f"empty capture {collected}") + + inventory = { + "modules": [ + {"module": "empty", "file": "empty.txt", "exports": [], "error": "no exports parsed"} + ] + } + inventory_path = directory / "exports.json" + inventory_path.write_text(json.dumps(inventory), encoding="utf-8") + empty_def = directory / "empty.def" + empty_def.write_text("LIBRARY empty\nEXPORTS\nAnything\n", encoding="utf-8") + absent_def = directory / "absent.def" + absent_def.write_text("LIBRARY absent\nEXPORTS\nAnything\n", encoding="utf-8") + output = directory / "coverage.json" + markdown = directory / "coverage.md" + check(coverage.main([ + "--exports", str(inventory_path), + "--def", "empty=" + str(empty_def), + "--def", "absent=" + str(absent_def), + "--json", str(output), + "--markdown", str(markdown), + "--fail-on-missing", + ]) == 1, "unmeasured fail-on-missing exit") + rows = { + row["module"]: row + for row in json.loads(output.read_text(encoding="utf-8")) + } + check(rows["empty"]["unmeasured"] == "no exports parsed", f"empty row {rows['empty']}") + check(rows["absent"]["unmeasured"] == "no inventory entry", f"absent row {rows['absent']}") + check("Unmeasured: no inventory entry" in markdown.read_text(encoding="utf-8"), "markdown status") + print("exports: empty, absent and fail-on-missing rows passed") + + +def main(): + check_parse() + check_coverage() + check_merge() + check_unmeasured() + print("gdk_exports_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_knowledge_report_check.py b/tests/gdk_knowledge_report_check.py new file mode 100644 index 0000000000..0e49b43a51 --- /dev/null +++ b/tests/gdk_knowledge_report_check.py @@ -0,0 +1,467 @@ +"""Synthetic controls for the GDK knowledge merge and coverage report.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "gdk_knowledge_report.py" +FACT_FIELDS = {"module", "kind", "name", "value", "source", "confidence", "targets"} + + +def write_json(path, data): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + + +def write_text(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def make_report_tree(root): + write_json( + root / "layouts" / "alpha.json", + { + "module": "alpha", + "classes": [ + {"name": "Shared", "size": 16, "members": [{"offset": 0, "text": "x"}]}, + {"name": "OnlyA", "size": 8, "members": []}, + {"name": "Cross", "size": 8, "members": []}, + ], + }, + ) + write_json( + root / "layouts" / "beta.json", + {"module": "beta", "classes": [{"name": "Cross", "size": 16, "members": []}]}, + ) + write_json( + root / "abi" / "alpha.json", + { + "module": "alpha", + "facts": [ + {"kind": "sizeof", "name": "Shared", "value": 32}, + {"kind": "struct", "name": "AbiOnly", "value": {"size": 4}}, + {"kind": "enum", "name": "Color", "value": 1}, + {"kind": "constant", "name": "Magic", "value": 1}, + ], + }, + ) + write_json( + root / "abi" / "alpha-more.json", + { + "module": "alpha", + "facts": [ + {"kind": "enum", "name": "Color", "value": 2}, + {"kind": "constant", "name": "Magic", "value": 2}, + ], + }, + ) + write_json( + root / "exports" / "alpha-a.json", + { + "module": "alpha", + "exports": [ + {"name": "Foo", "ordinal": 1, "rva": "0x10"}, + {"name": "Bar", "ordinal": 3, "rva": "0x20"}, + ], + }, + ) + write_json( + root / "exports" / "alpha-b.json", + { + "module": "alpha", + "exports": [ + {"name": "Foo", "ordinal": 2, "rva": "0x30"}, + {"name": "Bar", "ordinal": 3, "rva": "0x20"}, + ], + }, + ) + write_json( + root / "behavior" / "alpha.json", + { + "module": "alpha", + "observations": [ + {"kind": "value", "name": "Bar", "value": 42}, + {"kind": "behavior", "name": "OnlyA", "value": "ok"}, + ], + }, + ) + write_json( + root / "platform" / "windows.json", + { + "platform": "windows-x64", + "defines": ["ALPHA=1"], + "includes": ["alpha.h"], + "libs": ["alpha.lib"], + "flags": ["/W4"], + }, + ) + write_json( + root / "shaders" / "corpus.json", + { + "module": "alpha", + "cases": [ + {"name": "ps-case", "stage": "pixel"}, + {"name": "cs-case", "stage": "compute"}, + ], + }, + ) + write_text( + root / "defs" / "alpha.def", + "LIBRARY alpha\n" + "EXPORTS\n" + " Bar @3\n" + " MissingThing @4\n" + " XMemAllocDefault=Bar @5\n" + " x2w_internal_helper @6\n", + ) + write_json( + root / "defs-map.json", + {"alpha": ["Bar", "MappingOnly", "x2w_mapping_internal"]}, + ) + + +def run_report(root, output, *, defs=None, require=None, check=False, markdown=None): + json_path = Path(output) / "coverage.json" + markdown_path = Path(markdown) if markdown else Path(output) / "report.md" + command = [ + sys.executable, + "-B", + str(TOOL), + "report", + "--root", + str(root), + "--json", + str(json_path), + "--markdown", + str(markdown_path), + ] + if defs is not None: + command.extend(["--defs", str(defs)]) + if require is not None: + command.extend(["--require", require]) + if check: + command.append("--check") + process = subprocess.run(command, capture_output=True, text=True) + return process, json_path, markdown_path + + +def check_report(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "knowledge" + make_report_tree(root) + + process, json_path, markdown_path = run_report( + root, base / "out", defs=root / "defs" + ) + assert process.returncode == 0, process.stderr + report = json.loads(json_path.read_text(encoding="utf-8")) + markdown = markdown_path.read_text(encoding="utf-8") + + assert report["schema"] == "xbox2windows.gdk_knowledge/1" + assert report["generated_by"] == { + "tool": "gdk_knowledge_report", + "version": 1, + } + assert set(report["categories"]) == { + "layouts", + "abi", + "exports", + "behavior", + "platform", + "shaders", + } + assert all(info["present"] for info in report["categories"].values()) + assert report["missing"] == [] + assert report["required"] == [] + assert report["required_missing"] == [] + + summary = report["summary"] + assert summary["modules"] == 3 + assert summary["types"] == 5 + assert summary["classes_types"] == 5 + assert summary["exports"] == 2 + assert summary["export_rows"] == 4 + assert summary["runtime_facts"] == 2 + assert summary["shader_facts"] == 2 + assert summary["platforms"] == 1 + assert summary["facts"] == 19 + assert summary["conflicts"] == 5 + assert summary["shims"] == 3 + assert summary["shims_without_fact"] == 1 + assert report["categories"]["layouts"]["facts"] == 4 + assert report["categories"]["abi"]["facts"] == 6 + assert report["categories"]["exports"]["facts"] == 4 + + assert len(report["facts"]) == 19 + for fact in report["facts"]: + assert set(fact) == FACT_FIELDS + assert fact["module"] + assert fact["kind"] + assert fact["name"] + assert isinstance(fact["confidence"], str) + assert isinstance(fact["targets"], list) + assert not str(fact["source"]).startswith(str(base)) + assert report["facts"] == sorted( + report["facts"], + key=lambda fact: ( + fact["module"].casefold(), + fact["module"], + fact["kind"].casefold(), + fact["kind"], + fact["name"].casefold(), + fact["name"], + json.dumps( + fact["value"], sort_keys=True, ensure_ascii=False, separators=(",", ":") + ), + json.dumps( + fact["source"], sort_keys=True, ensure_ascii=False, separators=(",", ":") + ), + ), + ) + + shared = next( + fact + for fact in report["facts"] + if fact["module"] == "alpha" + and fact["kind"] == "layout" + and fact["name"] == "Shared" + ) + assert shared["value"] == { + "size": 16, + "members": [{"offset": 0, "text": "x"}], + } + assert shared["source"] == "layouts/alpha.json" + assert shared["confidence"] == "header" + + behavior = next( + fact + for fact in report["facts"] + if fact["name"] == "Bar" and fact["kind"] == "behavior" + ) + assert behavior["value"] == 42 + assert behavior["confidence"] == "runtime" + + kinds = [conflict["kind"] for conflict in report["conflicts"]] + assert kinds == ["value", "size", "ordinal", "enum", "type-size"], kinds + by_kind = {conflict["kind"]: conflict for conflict in report["conflicts"]} + assert by_kind["size"]["module"] == "alpha" + assert by_kind["size"]["name"] == "Shared" + assert {item["value"] for item in by_kind["size"]["values"]} == {16, 32} + assert by_kind["ordinal"]["module"] == "alpha" + assert by_kind["ordinal"]["name"] == "Foo" + assert [item["value"] for item in by_kind["ordinal"]["values"]] == [1, 2] + assert by_kind["enum"]["name"] == "Color" + assert {item["value"] for item in by_kind["enum"]["values"]} == {1, 2} + assert by_kind["type-size"]["name"] == "Cross" + assert by_kind["type-size"]["modules"] == ["alpha", "beta"] + assert {item["module"] for item in by_kind["type-size"]["values"]} == {"alpha", "beta"} + assert by_kind["value"]["name"] == "Magic" + for conflict in report["conflicts"]: + assert conflict["message"] + assert conflict["sources"] == sorted(set(conflict["sources"])) + + shims = report["shims"] + assert shims["exports"] == 3 + assert shims["covered"] == 2 + assert shims["internal"] == 1 + assert [ + (item["module"], item["name"], item["alias"]) + for item in shims["without_fact"] + ] == [("alpha", "MissingThing", None)] + + modules = {module["module"]: module for module in report["modules"]} + assert set(modules) == {"alpha", "beta", "windows-x64"} + assert modules["alpha"]["types"] == 4 + assert modules["alpha"]["exports"] == 2 + assert modules["alpha"]["runtime_facts"] == 2 + assert modules["alpha"]["shader_facts"] == 2 + assert modules["windows-x64"]["platform_facts"] == 1 + + assert markdown.startswith("# GDK knowledge coverage\n") + assert "| Modules | 3 |" in markdown + assert "| Classes/types | 5 |" in markdown + assert "| Runtime facts | 2 |" in markdown + assert "| Conflicts | 5 |" in markdown + assert "| ordinal | alpha | Foo |" in markdown + assert "MissingThing" in markdown + assert "A header fact does not prove the runtime." in markdown + assert markdown.endswith("\n") and not markdown.endswith("\n\n") + + second_process, second_json, second_markdown = run_report( + root, base / "out-again", defs=root / "defs" + ) + assert second_process.returncode == 0, second_process.stderr + assert json_path.read_bytes() == second_json.read_bytes() + assert markdown_path.read_bytes() == second_markdown.read_bytes() + + mapping_process, mapping_json, _ = run_report( + root, base / "out-mapping", defs=root / "defs-map.json" + ) + assert mapping_process.returncode == 0, mapping_process.stderr + mapping_report = json.loads(mapping_json.read_text(encoding="utf-8")) + assert mapping_report["summary"]["shims"] == 2 + assert mapping_report["summary"]["shims_without_fact"] == 1 + assert [ + (item["module"], item["name"]) + for item in mapping_report["shims"]["without_fact"] + ] == [("alpha", "MappingOnly")] + assert mapping_report["shims"]["internal"] == 1 + + checked, checked_json, checked_markdown = run_report( + root, base / "out-check", defs=root / "defs", check=True + ) + assert checked.returncode == 1 + assert checked_json.is_file() + assert checked_markdown.is_file() + assert "conflict" in checked.stderr + + +def check_require(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "clean" + write_json( + root / "layouts" / "one.json", + {"module": "one", "classes": [{"name": "Only", "size": 4, "members": []}]}, + ) + + passed, passed_json, _ = run_report( + root, base / "out-pass", require="layouts", check=True + ) + assert passed.returncode == 0, passed.stderr + passed_report = json.loads(passed_json.read_text(encoding="utf-8")) + assert passed_report["required"] == ["layouts"] + assert passed_report["required_missing"] == [] + assert passed_report["missing"] == ["abi", "exports", "behavior", "platform", "shaders"] + + failed, failed_json, failed_markdown = run_report( + root, base / "out-fail", require="layouts,exports", check=True + ) + assert failed.returncode == 1 + assert "exports" in failed.stderr + failed_report = json.loads(failed_json.read_text(encoding="utf-8")) + assert failed_report["required"] == ["layouts", "exports"] + assert failed_report["required_missing"] == ["exports"] + assert "Required categories missing: exports." in failed_markdown.read_text( + encoding="utf-8" + ) + + warned, warned_json, warned_markdown = run_report( + root, base / "out-warn", require="exports" + ) + assert warned.returncode == 0, warned.stderr + warned_report = json.loads(warned_json.read_text(encoding="utf-8")) + assert warned_report["required_missing"] == ["exports"] + assert "Required categories missing: exports." in warned_markdown.read_text( + encoding="utf-8" + ) + + +def check_module_case(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "case" + write_json( + root / "layouts" / "one.json", + {"module": "Alpha", "classes": [{"name": "One", "size": 4, "members": []}]}, + ) + write_json( + root / "layouts" / "two.json", + {"module": "alpha", "classes": [{"name": "Two", "size": 8, "members": []}]}, + ) + process, json_path, _ = run_report(root, base / "out") + assert process.returncode == 0, process.stderr + report = json.loads(json_path.read_text(encoding="utf-8")) + assert [module["module"] for module in report["modules"]] == ["alpha"] + assert report["modules"][0]["types"] == 2 + assert report["summary"]["modules"] == 1 + + +def check_errors(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + + missing_root, _, _ = run_report(base / "absent", base / "out-absent") + assert missing_root.returncode == 2 + assert "does not exist" in missing_root.stderr + + malformed = base / "malformed" + write_text(malformed / "layouts" / "bad.json", "{") + malformed_process, _, _ = run_report(malformed, base / "out-malformed") + assert malformed_process.returncode == 2 + assert "invalid JSON" in malformed_process.stderr + + wrong_shape = base / "wrong-shape" + write_json(wrong_shape / "layouts" / "bad.json", {"classes": {}}) + wrong_process, _, _ = run_report(wrong_shape, base / "out-wrong") + assert wrong_process.returncode == 2 + assert "classes" in wrong_process.stderr + + valid = base / "valid" + write_json( + valid / "layouts" / "one.json", + {"module": "one", "classes": [{"name": "Only", "size": 4, "members": []}]}, + ) + unknown_require, _, _ = run_report( + valid, base / "out-unknown", require="layouts,unknown" + ) + assert unknown_require.returncode == 2 + assert "unknown category" in unknown_require.stderr + + absent_defs, _, _ = run_report( + valid, base / "out-defs", defs=base / "absent-defs" + ) + assert absent_defs.returncode == 2 + assert "does not exist" in absent_defs.stderr + + bad_mapping = base / "bad-mapping.json" + write_text(bad_mapping, "[") + bad_mapping_process, _, _ = run_report( + valid, base / "out-map", defs=bad_mapping + ) + assert bad_mapping_process.returncode == 2 + assert "invalid JSON" in bad_mapping_process.stderr + + same_path = base / "same.md" + same_process, _, _ = run_report( + valid, base / "out-same", markdown=same_path + ) + assert same_process.returncode == 0, same_process.stderr + + json_path = base / "collision.json" + collision = subprocess.run( + [ + sys.executable, + "-B", + str(TOOL), + "report", + "--root", + str(valid), + "--json", + str(json_path), + "--markdown", + str(json_path), + ], + capture_output=True, + text=True, + ) + assert collision.returncode == 2 + assert "different paths" in collision.stderr + + +def main(): + check_report() + check_require() + check_module_case() + check_errors() + print("gdk_knowledge_report_check: ok") + + +if __name__ == "__main__": + main() diff --git a/tests/gdk_layouts_check.py b/tests/gdk_layouts_check.py new file mode 100644 index 0000000000..3d584e2771 --- /dev/null +++ b/tests/gdk_layouts_check.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_layouts.py and tools/gdk_abi_probe.py. + +The synthetic log covers the MSVC constructs the knowledge parser needs: +nested classes, a base class, a vftable, bitfields, arrays and an alignment +member. No Windows or GDK is required. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_abi_probe as abi # noqa: E402 +import gdk_layouts as layouts # noqa: E402 + + +SYNTHETIC_LOG = """class Base\tsize(8): +\t+--- + 0\t| {vfptr} +\t+--- + +class Outer\tsize(24): +\t+--- + 0\t| +--- (base class Base) + 0\t| | {vfptr} +\t+--- + 8\t| UINT Width +12\t| UINT Flags : 3 +16\t| UCHAR Data[4] + \t| <alignment member> (size=4) +\t+--- + +class Outer::Inner\tsize(4): +\t+--- + 0\t| UINT Value +\t+--- + +class Single\tsize(4): +\t+--- + 0\t| Value +\t+--- +""" + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_parser(): + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "layout.log" + log.write_text(SYNTHETIC_LOG, encoding="utf-8") + classes = layouts.parse_log(log) + by_name = {item["name"]: item for item in classes} + check(set(by_name) == {"Base", "Outer", "Outer::Inner", "Single"}, f"classes {set(by_name)}") + outer = by_name["Outer"] + check(outer["size"] == 24, f"Outer size {outer['size']}") + check(outer["bases"] == [{"offset": 0, "name": "Base"}], f"bases {outer['bases']}") + check(outer["alignment"] == 4, f"alignment {outer['alignment']}") + members = {item["name"]: item for item in outer["members"] if item["name"]} + check(members["{vfptr}"]["kind"] == "vftable", "vftable kind") + check(members["Width"]["offset"] == 8, "Width offset") + check(members["Width"]["type"] == "UINT", "typed member") + check(members["Flags"]["bits"] == 3, "bitfield width") + check(members["Data"]["array"] == 4, "array count") + check(members["<alignment>"]["kind"] == "alignment", "alignment member") + check(by_name["Outer::Inner"]["nested_in"] == "Outer", "nested_in") + check(by_name["Single"]["members"][0]["type"] == "unknown", "single-token member type") + check(by_name["Single"]["members"][0]["name"] == "Value", "single-token member name") + print("parser: base, vftable, bitfield, array and alignment passed") + + +def write_layouts(path, classes): + path.write_text( + json.dumps({"module": "synthetic", "classes": classes}, indent=2) + "\n", + encoding="utf-8", + ) + + +def check_compare(): + left = [ + {"name": "A", "size": 16, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "X", "bits": None, "kind": "field"}, + {"offset": 8, "type": "UINT", "name": "Y", "bits": None, "kind": "field"}, + ]}, + {"name": "OnlyLeft", "size": 4, "bases": [], "members": []}, + ] + right = [ + {"name": "A", "size": 24, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "X", "bits": None, "kind": "field"}, + {"offset": 12, "type": "UINT", "name": "Y", "bits": None, "kind": "field"}, + {"offset": 20, "type": "UINT", "name": "Z", "bits": None, "kind": "field"}, + ]}, + {"name": "OnlyRight", "size": 8, "bases": [], "members": []}, + ] + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + left_path = directory / "left.json" + right_path = directory / "right.json" + write_layouts(left_path, left) + write_layouts(right_path, right) + code = layouts.main(["compare", str(left_path), str(right_path), "--json", str(directory / "diff.json")]) + check(code == 1, f"compare exit {code}") + changes = json.loads((directory / "diff.json").read_text(encoding="utf-8")) + kinds = {(item["class"], item.get("kind")) for item in changes} + check(("A", "size") in kinds, f"size change {kinds}") + check(("A", "offset") in kinds, f"offset change {kinds}") + check(("OnlyLeft", "removed") in kinds and ("OnlyRight", "added") in kinds, f"add/remove {kinds}") + check(layouts.main(["compare", str(left_path), str(left_path)]) == 0, "identical exit") + print("compare: size, offset, add and remove changes passed") + + +def check_probe(): + classes = [ + {"name": "Simple", "size": 12, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "A", "bits": None, "kind": "field"}, + {"offset": 4, "type": "UINT", "name": "Flags", "bits": 3, "kind": "field"}, + {"offset": 8, "type": "UINT", "name": "B", "bits": None, "kind": "field"}, + ]}, + {"name": "Derived", "size": 16, "bases": [{"offset": 0, "name": "Simple"}], "members": [ + {"offset": 0, "type": "void*", "name": "{vfptr}", "bits": None, "kind": "vftable"}, + {"offset": 12, "type": "UINT", "name": "C", "bits": None, "kind": "field"}, + ]}, + ] + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + layout_path = directory / "layout.json" + write_layouts(layout_path, classes) + source = directory / "probe.cpp" + code = abi.main([ + "generate", "--layouts", str(layout_path), "--out", str(source), + "--include", "synthetic.h", "--offsetof", "--print", + ]) + check(code == 0, f"generate exit {code}") + text = source.read_text(encoding="utf-8") + check("#include <synthetic.h>" in text, "include") + check('static_assert(sizeof(Simple) == 12, "sizeof(Simple)");' in text, "sizeof Simple") + check('static_assert(offsetof(Simple, A) == 0, "offsetof(Simple, A)");' in text, "offsetof A") + check("offsetof(Simple, Flags)" not in text, "bitfield offset emitted") + check("offsetof(Derived, C)" not in text, "base-class offset emitted") + check('std::printf("offsetof(Simple, B)=%zu\\n", offsetof(Simple, B));' in text, "print B") + + size_only = directory / "size-only.cpp" + private_classes = classes + [ + {"name": "PrivateField", "size": 4, "bases": [], "members": [ + {"offset": 0, "type": "int", "name": "hidden", "bits": None, "kind": "field"}, + ]}, + ] + private_layout = directory / "private.json" + write_layouts(private_layout, private_classes) + code = abi.main([ + "generate", "--layouts", str(private_layout), "--out", str(size_only), + "--include", "synthetic.h", "--print", + ]) + check(code == 0, f"size-only generate exit {code}") + size_text = size_only.read_text(encoding="utf-8") + check('std::printf("sizeof(PrivateField)=%zu\\n"' in size_text, "size-only sizeof") + check("offsetof(PrivateField, hidden)" not in size_text, "print-only emitted offsetof") + check('std::printf("offsetof(Simple, B)=%zu\\n"' not in size_text, "print-only emitted a public offsetof") + + log = directory / "probe.log" + log.write_text("sizeof(Simple)=12\noffsetof(Simple, A)=0\n", encoding="utf-8") + parsed = directory / "parsed.json" + check(abi.main(["parse", str(log), "--json", str(parsed)]) == 0, "parse exit") + facts = json.loads(parsed.read_text(encoding="utf-8"))["facts"] + check(facts == {"sizeof(Simple)": 12, "offsetof(Simple, A)": 0}, f"facts {facts}") + + changed = directory / "changed.json" + changed.write_text( + json.dumps({"facts": {"sizeof(Simple)": 16, "offsetof(Simple, A)": 0}}), + encoding="utf-8", + ) + check(abi.main(["diff", str(parsed), str(changed)]) == 1, "diff exit") + check(abi.main(["diff", str(parsed), str(parsed)]) == 0, "same diff exit") + print("probe: generation, offsetof rules, parse and diff passed") + + +def main(): + check_parser() + check_compare() + check_probe() + print("gdk_layouts_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_platform_profiles_check.py b/tests/gdk_platform_profiles_check.py new file mode 100644 index 0000000000..1049b3e3d9 --- /dev/null +++ b/tests/gdk_platform_profiles_check.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_platform_profiles.py. + +Builds a small MSBuild platform tree in a temporary directory. No GDK or +Windows is required. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_platform_profiles as profiles # noqa: E402 + + +NAMESPACE = 'xmlns="http://schemas.microsoft.com/developer/msbuild/2003"' + + +def write(path, body): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + f"<Project {NAMESPACE}>\n{body}\n</Project>\n", encoding="utf-8" + ) + + +def make_tree(root): + platform = ( + root + / "VS2022" + / "flatDeployment" + / "MSBuild" + / "Microsoft" + / "VC" + / "v170" + / "Platforms" + / "Gaming.Xbox.Scarlett.x64" + ) + write( + platform / "261000" / "Platform.Common.props", + """ <PropertyGroup> + <UseDebugLibraries Condition="'$(Configuration)'=='Debug'">true</UseDebugLibraries> + <CharacterSet>Unicode</CharacterSet> + </PropertyGroup> + <ItemDefinitionGroup> + <ClCompile> + <PreprocessorDefinitions>_GAMING_XBOX;_GAMING_XBOX_SCARLETT;%(PreprocessorDefinitions)</PreprocessorDefinitions> + <AdditionalIncludeDirectories>$(XdkEditionRootVS2022)Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> + <AdditionalOptions>/favor:AMD64 %(AdditionalOptions)</AdditionalOptions> + <FloatingPointModel>Fast</FloatingPointModel> + </ClCompile> + <Link> + <AdditionalDependencies>xgameplatform.lib</AdditionalDependencies> + <TargetMachine>MachineX64</TargetMachine> + </Link> + </ItemDefinitionGroup>""", + ) + write( + platform / "Platform.props", + """ <PropertyGroup> + <XdkEditionRootVS2022>D:\\gdk\\</XdkEditionRootVS2022> + </PropertyGroup>""", + ) + write(platform / "Platform.targets", " <PropertyGroup><XdkEdition>261000</XdkEdition></PropertyGroup>") + write( + platform / "PlatformToolsets" / "v143" / "Toolset.props", + """ <ItemDefinitionGroup> + <ClCompile> + <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> + </ClCompile> + </ItemDefinitionGroup>""", + ) + write( + platform / "999999" / "Platform.Common.props", + """ <ItemDefinitionGroup> + <ClCompile> + <PreprocessorDefinitions>PROFILE_999999</PreprocessorDefinitions> + </ClCompile> + </ItemDefinitionGroup>""", + ) + return platform + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def main(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + make_tree(root) + + found = profiles.choose(root, "Gaming.Xbox.Scarlett.x64", "v170", "261000") + check(found is not None, "platform not found") + check(found.name == "Gaming.Xbox.Scarlett.x64", f"platform {found.name}") + + listed = profiles.main(["list", "--root", str(root)]) + check(listed == 0, f"list exit {listed}") + + output = root / "profile.json" + code = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--json", str(output), + ]) + check(code == 0, f"scan exit {code}") + document = json.loads(output.read_text(encoding="utf-8")) + check(document["platform"] == "Gaming.Xbox.Scarlett.x64", "platform name") + check(document["defines"] == ["_GAMING_XBOX", "_GAMING_XBOX_SCARLETT"], f"defines {document['defines']}") + check(document["includes"] == ["D:\\gdk\\Include"], f"includes {document['includes']}") + check(document["dependencies"] == ["xgameplatform.lib"], f"deps {document['dependencies']}") + check(document["flags"]["floating_point_model"] == "Fast", "floating point") + check(document["flags"]["runtime_library"] == "MultiThreadedDLL", "runtime library") + check(document["flags"]["target_machine"] == "MachineX64", "target machine") + check(document["flags"]["character_set"] == "Unicode", "character set") + conditions = document["properties"]["UseDebugLibraries"] + check(conditions[0]["condition"] == "'$(Configuration)'=='Debug'", f"condition {conditions}") + check(len(document["sources"]) == 4, f"sources {len(document['sources'])}") + + other_output = root / "profile-999999.json" + other = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--sdk", "999999", "--json", str(other_output), + ]) + check(other == 0, f"999999 scan exit {other}") + other_document = json.loads(other_output.read_text(encoding="utf-8")) + check(other_document["sdk"] == "999999", f"sdk {other_document['sdk']}") + check(other_document["defines"] == ["PROFILE_999999"], f"defines {other_document['defines']}") + source_paths = [item["path"] for item in other_document["sources"]] + check(any("999999" in path and "Platform.Common.props" in path for path in source_paths), + f"999999 source {source_paths}") + check(not any("261000" in path for path in source_paths), f"261000 leaked {source_paths}") + + unsupported_output = root / "profile-unsupported.json" + unsupported = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--sdk", "888888", "--json", str(unsupported_output), + ]) + check(unsupported == 2, f"unsupported SDK exit {unsupported}") + check(not unsupported_output.exists(), "unsupported SDK wrote output") + + missing = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Desktop.x64", + "--json", str(root / "missing.json"), + ]) + check(missing == 2, f"missing platform exit {missing}") + print("gdk_platform_profiles_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_runtime_oracle_check.py b/tests/gdk_runtime_oracle_check.py new file mode 100644 index 0000000000..fb1d70ac3d --- /dev/null +++ b/tests/gdk_runtime_oracle_check.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_runtime_oracle.py. + +Without a GDK, this covers normalization, the unified diff and the skip path +when cl.exe is absent. It does not claim a desktop runtime was measured. +""" + +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_runtime_oracle as oracle # noqa: E402 + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_normalization(): + cases = { + "queue_handle=0000026D29CDFD60": "queue_handle=<handle>", + "xpackage_mount_handle=00007FFFEA53C588": "xpackage_mount_handle=<handle>", + "console_value=58325731.00000000.00000000.00000000.01": "console_value=<console-id>", + "pls_path_value=C:\\Users\\ROLAND~1\\AppData\\Local\\Temp\\xbox-recomp-pls\\x2w-synthetic-title-0001": + "pls_path_value=<localappdata>\\Temp\\xbox-recomp-pls\\x2w-synthetic-title-0001", + "xpackage_path_value=C:\\Users\\ROLAND~1\\AppData\\Local\\Temp\\xbox-recomp-packages\\x2w-nonexistent-package": + "xpackage_path_value=<localappdata>\\Temp\\xbox-recomp-packages\\x2w-nonexistent-package", + "title_id=0x80070490": "title_id=0x80070490", + "queue_dispatch=0": "queue_dispatch=0", + } + for line, expected in cases.items(): + actual = oracle.normalize_line(line) + check(actual == expected, f"{line!r}: {actual!r} != {expected!r}") + print(f"normalization: {len(cases)} cases passed") + + +def check_diff(): + reference = ["init=0x00000000", "device=1", "queue_dispatch=0"] + candidate = ["init=0x00000000", "device=1", "queue_dispatch=1"] + difference = oracle.diff_lines(reference, candidate) + check(difference[0] == "--- reference", f"header {difference[0]!r}") + check(difference[1] == "+++ candidate", f"header {difference[1]!r}") + check("-queue_dispatch=0" in difference, f"removed line {difference}") + check("+queue_dispatch=1" in difference, f"added line {difference}") + check(oracle.diff_lines(reference, reference) == [], "identical logs differ") + + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + (directory / "reference.txt").write_text("\n".join(reference) + "\n", encoding="utf-8") + (directory / "candidate.txt").write_text("\n".join(candidate) + "\n", encoding="utf-8") + code = oracle.main(["diff", str(directory / "reference.txt"), str(directory / "candidate.txt")]) + check(code == 1, f"diff exit {code}") + (directory / "candidate.txt").write_text("\n".join(reference) + "\n", encoding="utf-8") + code = oracle.main(["diff", str(directory / "reference.txt"), str(directory / "candidate.txt")]) + check(code == 0, f"identical exit {code}") + print("diff: headers, changed line and exit codes passed") + + +def check_skip(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + gdk = root / "grdk" + (gdk / "GameKit" / "Include").mkdir(parents=True) + (gdk / "GameKit" / "Lib" / "amd64").mkdir(parents=True) + shim = root / "shim" + shim.mkdir() + fixture = root / "fixture.cpp" + fixture.write_text("int main() { return 0; }\n", encoding="utf-8") + code = oracle.main([ + "run", + "--gdk-root", str(gdk), + "--shim-dir", str(shim), + "--fixture", str(fixture), + "--out", str(root / "out"), + "--cl", str(root / "missing-cl.exe"), + ]) + check(code == oracle.SKIP, f"missing cl exit {code}") + print("run: missing cl reports 77") + + +def check_version_parser(): + with tempfile.TemporaryDirectory() as directory: + include = Path(directory) + (include / "GRDK.h").write_text( + "#define _GRDKVER_PRODUCTBUILDVER_FULL 10.0.26100.9661\n", encoding="utf-8" + ) + check(oracle.grdk_version(include) == "10.0.26100.9661", "GRDK version") + check(oracle.grdk_version(Path(directory) / "missing") == "unknown", "missing GRDK version") + print("version parser: present and missing headers passed") + + +def main(): + check_normalization() + check_diff() + check_skip() + check_version_parser() + print("gdk_runtime_oracle_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gdk_shader_corpus_check.py b/tests/gdk_shader_corpus_check.py new file mode 100644 index 0000000000..632a9bfb2c --- /dev/null +++ b/tests/gdk_shader_corpus_check.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_shader_corpus.py without the GDK. + +The real compilation is covered by the corpus build in docs/experiments/ +gdk-shader-corpus.md. This check covers case loading, hashing, manifest +verification, triple checks and the missing-dxc skip. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_shader_corpus as corpus # noqa: E402 + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def write_corpus(root, duplicate=False): + (root / "case.hlsl").write_text("float4 main() : SV_Target { return 0; }\n", encoding="utf-8") + cases = [{"name": "case", "source": "case.hlsl", "profile": "ps_6_0", "entry": "main"}] + if duplicate: + cases.append(dict(cases[0])) + (root / "cases.json").write_text(json.dumps({"cases": cases}), encoding="utf-8") + + +def check_loading(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + write_corpus(root) + cases = corpus.load_cases(root) + check(cases[0]["name"] == "case", f"cases {cases}") + write_corpus(root, duplicate=True) + try: + corpus.load_cases(root) + except ValueError as error: + check("duplicate" in str(error), str(error)) + else: + raise AssertionError("duplicate case accepted") + (root / "case.hlsl").unlink() + try: + corpus.load_cases(root) + except ValueError as error: + check("missing" in str(error), str(error)) + else: + raise AssertionError("missing source accepted") + print("loading: case, duplicate and missing source passed") + + +def check_build_skip(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + write_corpus(root) + out = root / "out" + code = corpus.main([ + "build", "--gdk-root", str(root), "--corpus", str(root), "--out", str(out), + "--dxc", str(root / "missing-dxc.exe"), + ]) + check(code == corpus.SKIP, f"missing dxc exit {code}") + code = corpus.main([ + "build", "--gdk-root", str(root), "--corpus", str(root), "--out", str(out), + "--dxc", str(root / "missing-dxc.exe"), "--require", + ]) + check(code == 2, f"required dxc exit {code}") + print("build: missing dxc reports 77 and --require reports 2") + + +def check_verify(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "xbox.cso").write_bytes(b"xbox") + (root / "desktop.cso").write_bytes(b"desktop") + manifest = { + "sdk": "261000", + "cases": [ + { + "name": "case", + "source": "case.hlsl", + "source_sha256": "0" * 64, + "profile": "ps_6_0", + "entry": "main", + "args": [], + "xbox": { + "file": "xbox.cso", + "bytes": 4, + "sha256": corpus.sha256(root / "xbox.cso"), + }, + "desktop": { + "file": "desktop.cso", + "bytes": 7, + "sha256": corpus.sha256(root / "desktop.cso"), + }, + "dxil": { + "original_triple": "dxil-ms-xb2", + "target_triple": "dxil-ms-dx", + "removed_named_metadata": ["xbox.compiler.options"], + }, + } + ], + } + path = root / "corpus.json" + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 0, "valid manifest") + + manifest["cases"][0]["xbox"]["sha256"] = "1" * 64 + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 1, "hash mismatch") + + manifest["cases"][0]["xbox"]["sha256"] = corpus.sha256(root / "xbox.cso") + manifest["cases"][0]["dxil"]["target_triple"] = "dxil-ms-xb2" + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 1, "triple mismatch") + + manifest["cases"][0]["dxil"]["target_triple"] = "dxil-ms-dx" + (root / "xbox.cso").unlink() + path.write_text(json.dumps(manifest), encoding="utf-8") + check(corpus.main(["verify", "--manifest", str(path)]) == 1, "missing file") + print("verify: hashes, sizes, triples and missing files passed") + + +def main(): + check_loading() + check_build_skip() + check_verify() + print("gdk_shader_corpus_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/gfx1030_bvh_box/bvh_model.py b/tests/gfx1030_bvh_box/bvh_model.py new file mode 100644 index 0000000000..da0b588e5c --- /dev/null +++ b/tests/gfx1030_bvh_box/bvh_model.py @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: MIT +"""CPU model of the console BVH node test. + +This models one ``image_bvh_intersect_ray`` / ``image_bvh64_intersect_ray`` +call: a ray and a node pointer in, four result DWORDs out. Node traversal, +the stack and instance transforms belong to the calling shader and are not +part of this module. + +The node formats and the box test follow the public software emulation in +Mesa's RADV driver (MIT). The triangle test is the watertight formulation +from Woop, Benthin and Wald, JCGT 2013, as RADV uses it. The result layout +is the 40-bit ray-tracing descriptor's triangle return mode 1: +``{t_num, t_denom, I_num, J_num}``. Arithmetic is binary32 at every step, +rounding to nearest even; scalar Python floats only carry the values. +""" + +import math +import struct + + +MASK32 = (1 << 32) - 1 +MASK48 = (1 << 48) - 1 +MASK64 = (1 << 64) - 1 +INVALID = 0xffffffff + +NODE_BOX16 = 4 +NODE_BOX32 = 5 +SORT_ENABLE = 1 << 31 +RETURN_BARYCENTRICS = 1 << 24 + +TRIANGLE_VERTICES = ((0, 1, 2), (1, 3, 2), (2, 3, 4), (2, 4, 0)) +MISS = (math.inf, 1.0, 0.0, 0.0) +FLT_MAX = struct.unpack("<f", struct.pack("<I", 0x7f7fffff))[0] + + +def f32(value): + """Round a Python float to binary32, nearest even.""" + if math.isnan(value) or math.isinf(value): + return value + try: + return struct.unpack("<f", struct.pack("<f", value))[0] + except OverflowError: + return math.inf if value > 0.0 else -math.inf + + +def f32_bits(value): + return struct.unpack("<I", struct.pack("<f", f32(value)))[0] + + +def bits_f32(word): + return struct.unpack("<f", struct.pack("<I", word & MASK32))[0] + + +def fadd(a, b): + return f32(a + b) + + +def fsub(a, b): + return f32(a - b) + + +def fmul(a, b): + return f32(a * b) + + +def fmin(a, b): + # IEEE minNum: the non-NaN operand when one is NaN. + if math.isnan(a): + return b + if math.isnan(b): + return a + return a if a <= b else b + + +def fmax(a, b): + # IEEE maxNum: the non-NaN operand when one is NaN. + if math.isnan(a): + return b + if math.isnan(b): + return a + return a if a >= b else b + + +def node_address(descriptor, pointer, wide=False): + """Return ``(kind, byte address)`` for a node pointer. + + The low three bits are the node kind. The rest addresses a 64-byte + node: ``(pointer >> 3) << 6``. The 32-bit form adds that offset to a + 40-bit base held in descriptor DWORD 0 and the low byte of DWORD 1, in + 256-byte units. The 64-bit form uses the absolute pointer. + """ + kind = pointer & 7 + if wide: + return kind, ((pointer >> 3) << 6) & MASK64 + base = (((descriptor[1] & 0xff) << 32) | (descriptor[0] & MASK32)) << 8 + return kind, (base + ((pointer >> 3) << 6)) & MASK48 + + +def descriptor(base=0, *, sort=True, return_barycentrics=True, size=0x3ffffffffff): + """Build the four descriptor DWORDs a node test reads. + + The base argument is a 256-byte aligned byte address. The DWORDs hold + it in 256-byte units, as the instruction's resource does. + """ + assert base & 0xff == 0, "the descriptor base is 256-byte aligned" + units = base >> 8 + return ( + units & MASK32, + ((units >> 32) & 0xff) | (SORT_ENABLE if sort else 0), + size & MASK32, + ((size >> 32) & 0x3fffff) + | (RETURN_BARYCENTRICS if return_barycentrics else 0) + | (8 << 28), + ) + + +def _load_box(data, offset, kind, index): + if kind == NODE_BOX32: + start = offset + 16 + 24 * index + return struct.unpack_from("<6f", data, start) + start = offset + 16 + 12 * index + return struct.unpack_from("<6e", data, start) + + +def _box_entry(lo, hi, origin, inverse, extent): + # RADV removes infinities so an origin exactly on a face does not turn + # zero times infinity into NaN. max then min is the order its NIR uses. + inv = [fmin(fmax(inverse[i], -FLT_MAX), FLT_MAX) for i in range(3)] + low = [fmul(fsub(lo[i], origin[i]), inv[i]) for i in range(3)] + high = [fmul(fsub(hi[i], origin[i]), inv[i]) for i in range(3)] + enter = fmax(fmax(fmin(low[0], high[0]), fmin(low[1], high[1])), fmin(low[2], high[2])) + leave = fmin(fmin(fmax(low[0], high[0]), fmax(low[1], high[1])), fmax(low[2], high[2])) + # min.x is the inactive-slot marker. Other NaN components are outside + # the defined input; fmin/fmax above use the non-NaN operand. + if math.isnan(lo[0]): + return None + if leave >= fmax(0.0, enter) and enter < extent: + return enter + return None + + +def _boxes(data, offset, kind, origin, inverse, extent, sort): + children = struct.unpack_from("<4I", data, offset) + indices = [INVALID] * 4 + distances = [math.inf] * 4 + for i in range(4): + if children[i] == INVALID: + continue + coords = _load_box(data, offset, kind, i) + enter = _box_entry(coords[:3], coords[3:], origin, inverse, extent) + if enter is not None: + indices[i] = children[i] + distances[i] = enter + if sort: + # RADV's five-comparator network. A strict comparison leaves equal + # entries in child order. + for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + if distances[b] < distances[a]: + distances[a], distances[b] = distances[b], distances[a] + indices[a], indices[b] = indices[b], indices[a] + return indices + + +def _node_vertex(data, offset, index): + return struct.unpack_from("<3f", data, offset + 12 * index) + + +def _triangle(data, offset, kind, origin, direction, inverse): + id_dword = struct.unpack_from("<I", data, offset + 60)[0] + id_byte = (id_dword >> (8 * (kind & 3))) & 0xff + i = id_byte & 3 + j = (id_byte >> 2) & 3 + first = (3 - i - j) & 3 + # The fourth map nibble is zero in the node format; a malformed ID that + # names it reads the node's first vertex, as the arithmetic lands. + mapped = TRIANGLE_VERTICES[kind & 3] + (0,) + a, b, c = (_node_vertex(data, offset, mapped[n]) for n in (first, i, j)) + + size = (abs(direction[0]), abs(direction[1]), abs(direction[2])) + if size[0] >= size[1]: + kz = 0 if size[0] >= size[2] else 2 + elif size[1] >= size[2]: + kz = 1 + else: + kz = 2 + kx = (kz + 1) % 3 + ky = (kx + 1) % 3 + if direction[kz] < 0.0: + kx, ky = ky, kx + + sz = inverse[kz] + sx = fmul(direction[kx], sz) + sy = fmul(direction[ky], sz) + + def shear(vertex): + rel = [fsub(vertex[n], origin[n]) for n in range(3)] + return ( + fsub(rel[kx], fmul(sx, rel[kz])), + fsub(rel[ky], fmul(sy, rel[kz])), + fmul(sz, rel[kz]), + ) + + ax, ay, az = shear(a) + bx, by, bz = shear(b) + cx, cy, cz = shear(c) + u = fsub(fmul(cx, by), fmul(cy, bx)) + v = fsub(fmul(ax, cy), fmul(ay, cx)) + w = fsub(fmul(bx, ay), fmul(by, ax)) + + behind = u < 0.0 or v < 0.0 or w < 0.0 + before = u > 0.0 or v > 0.0 or w > 0.0 + det = fadd(u, fadd(v, w)) + t = fadd(fadd(fmul(u, az), fmul(v, bz)), fmul(w, cz)) + ahead = (det > 0.0 and t >= 0.0) or (det < 0.0 and t <= 0.0) + if (behind and before) or not ahead: + return MISS + # The instruction does not test the ray extent for triangles. + return f32(t), f32(det), f32(v), f32(w) + + +def intersect(data, descriptor_words, pointer, *, origin, direction, inverse, extent, + wide=False): + """Return the four result DWORDs for one node and one ray.""" + kind, address = node_address(descriptor_words, pointer, wide) + sort = bool(descriptor_words[1] & SORT_ENABLE) + if kind == NODE_BOX32 or kind == NODE_BOX16: + return _boxes(data, address, kind, origin, inverse, extent, sort) + if kind <= 3: + if not descriptor_words[3] & RETURN_BARYCENTRICS: + raise ValueError("triangle return mode 0 is not modeled") + # The instruction does not test the ray extent for triangles. + values = _triangle(data, address, kind, origin, direction, inverse) + return [f32_bits(value) for value in values] + # Instance and procedural nodes are not read by this instruction. + return [f32_bits(value) for value in MISS] diff --git a/tests/gfx1030_bvh_box/check.py b/tests/gfx1030_bvh_box/check.py index 3153ff5f90..66b69bca6c 100644 --- a/tests/gfx1030_bvh_box/check.py +++ b/tests/gfx1030_bvh_box/check.py @@ -3,9 +3,16 @@ import argparse import ctypes as ct import hashlib +import math import os from pathlib import Path import struct +import sys +from collections import namedtuple + + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import bvh_model ROOT = Path(__file__).resolve().parents[2] @@ -17,6 +24,9 @@ TRANSFER_TO_DEVICE = 1 TRANSFER_TO_HOST = 2 MASK32 = (1 << 32) - 1 +inf = math.inf +D_SORT = bvh_model.descriptor(0, sort=True) +D_NOSORT = bvh_model.descriptor(0, sort=False) def box(child, depth, x=-8): @@ -80,6 +90,910 @@ def model_check(): print("all_miss zero-fill control word=0 expected=ffffffff actual=00000000") +Witness = namedtuple("Witness", "name image descriptor pointer ray expected wide") +PointerWitness = namedtuple("PointerWitness", "name descriptor pointer wide expected") + + +def C(name, image, descriptor, pointer, ray, expected, wide=False): + return Witness(name, image, descriptor, pointer, ray, expected, wide) + + +def P(name, descriptor, pointer, wide, expected): + return PointerWitness(name, descriptor, pointer, wide, expected) + + +def witness_check(): + failures = 0 + for case in WITNESSES: + origin, direction, inverse, extent = case.ray + actual = tuple(bvh_model.intersect(case.image, case.descriptor, case.pointer, + origin=origin, direction=direction, inverse=inverse, + extent=extent, wide=case.wide)) + difference = first_difference(case.expected, actual) + if difference: + index, wanted, got = difference + print(f"witness {case.name} word={index} expected={wanted:08x} actual={got:08x}") + failures += 1 + for case in POINTER_WITNESSES: + actual = bvh_model.node_address(case.descriptor, case.pointer, case.wide) + if actual != case.expected: + print(f"pointer witness {case.name} expected={case.expected} actual={actual}") + failures += 1 + print(f"model_witness_cases={len(WITNESSES) + len(POINTER_WITNESSES)} " + f"node={len(WITNESSES)} pointer={len(POINTER_WITNESSES)} mismatches={failures}") + return failures + + +# box32/four-sorted +NODE_0 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/tie-sorted +NODE_1 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f00002041000080bf000080bf000030410000803f0000803f" + "00002041000080bf000080bf000030410000803f0000803f00002041000080bf" + "000080bf000030410000803f0000803f00000000000000000000000000000000" +) +# box32/tie-two-then-far +NODE_2 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f00002041000080bf000080bf000030410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/mixed-sorted +NODE_3 = bytes.fromhex( + "05010000ffffffff04030000ffffffff00002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/zero-child-sorted +NODE_4 = bytes.fromhex( + "0000000005010000000000000403000000002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/overlap-sorted +NODE_5 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf0000f041" + "0000803f0000803f0000a041000080bf000080bf0000c8410000803f0000803f" + "00002042000080bf000080bf000024420000803f0000803f0000a040000080bf" + "000080bf0000c0400000803f0000803f00000000000000000000000000000000" +) +# box32/3d-0.5-0.5 +NODE_6 = bytes.fromhex( + "050100000c020000040300000004000000002041000000000000000000003041" + "0000803f0000803f00002041000000400000000000003041000040400000803f" + "000020410000000000000040000030410000803f000040400000204100000040" + "0000004000003041000040400000404000000000000000000000000000000000" +) +# box32/behind-0-e1e+09 +NODE_7 = bytes.fromhex( + "050100000c02000004030000000400000000a0c1000080bf000080bf000020c1" + "0000803f0000803f000020c1000080bf000080bf000020410000803f0000803f" + "00000000000080bf000080bf000020410000803f0000803f00002041000080bf" + "000080bf0000a0410000803f0000803f00000000000000000000000000000000" +) +# box32/zerodir-10.5-0 +NODE_8 = bytes.fromhex( + "050100000c02000004030000000400000000204100002041000080bf00003041" + "000030410000803f0000a04100002041000080bf0000a841000030410000803f" + "0000f04100002041000080bf0000f841000030410000803f0000204200002041" + "000080bf00002442000030410000803f00000000000000000000000000000000" +) +# box32/inverted +NODE_9 = bytes.fromhex( + "050100000c020000040300000004000000003041000080bf000080bf00002041" + "0000803f0000803f00000000000080bf000080bf0000a0410000803f0000803f" + "0000f041000080bf000080bf0000c8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/infinite-bounds +NODE_10 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf0000807f" + "0000803f0000803f000080ff000080bf000080bf0000a0410000803f0000803f" + "000080ff000080bf000080bf0000807f0000803f0000803f00002041000080bf" + "000080bf000020410000803f0000803f00000000000000000000000000000000" +) +# box32/nan-min-disabled +NODE_11 = bytes.fromhex( + "050100000c02000004030000000400000000c07f000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box32/nan-max-convention +NODE_12 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf0000c07f" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f00002042000080bf" + "000080bf000024420000803f0000803f00000000000000000000000000000000" +) +# box16/four-sorted +NODE_13 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/tie-sorted +NODE_14 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc8049003c003c004900bc" + "00bc8049003c003c004900bc00bc8049003c003c004900bc00bc8049003c003c" +) +# box16/mixed-sorted +NODE_15 = bytes.fromhex( + "05010000ffffffff04030000ffffffff004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/zero-child-sorted +NODE_16 = bytes.fromhex( + "00000000050100000000000004030000004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/round-low-e0 +NODE_17 = bytes.fromhex( + "050100000c0200000403000000040000662e00bc00bc003c003c003c662e00bc" + "00bc003c003c003c662e00bc00bc003c003c003c662e00bc00bc003c003c003c" +) +# box16/round-high-neg +NODE_18 = bytes.fromhex( + "050100000c0200000403000000040000000000bc00bc3340003c003c000000bc" + "00bc3340003c003c000000bc00bc3340003c003c000000bc00bc3340003c003c" +) +# box16/subnormal-e1 +NODE_19 = bytes.fromhex( + "050100000c0200000403000000040000010000bc00bc0200003c003c000400bc" + "00bc0008003c003c003c00bc00bc0040003c003c000000bc00bc0038003c003c" +) +# box16/65504-e10 +NODE_20 = bytes.fromhex( + "050100000c0200000403000000040000ff7b00bc00bcff7b003c003cff7b00bc" + "00bcff7b003c003cff7b00bc00bcff7b003c003cff7b00bc00bcff7b003c003c" +) +# box16/infinite-bounds +NODE_21 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc007c003c003c00fc00bc" + "00bc004d003c003c00fc00bc00bc007c003c003c004900bc00bc0049003c003c" +) +# box16/nan-min-disabled +NODE_22 = bytes.fromhex( + "050100000c0200000403000000040000007e00bc00bc8049003c003c004d00bc" + "00bc404d003c003c804f00bc00bcc04f003c003c005100bc00bc2051003c003c" +) +# box16/negzero-0.0 +NODE_23 = bytes.fromhex( + "050100000c0200000403000000040000008000bc00bc0000003c003c008000bc" + "00bc0000003c003c008000bc00bc0000003c003c008000bc00bc0000003c003c" +) +# box32/scramble-sorted +NODE_24 = bytes.fromhex( + "050100000c020000040300000004000000002042000080bf000080bf00002442" + "0000803f0000803f00002041000080bf000080bf000030410000803f0000803f" + "0000f041000080bf000080bf0000f8410000803f0000803f0000a041000080bf" + "000080bf0000a8410000803f0000803f00000000000000000000000000000000" +) +# box16/scramble-sorted +NODE_25 = bytes.fromhex( + "050100000c0200000403000000040000005100bc00bc2051003c003c004900bc" + "00bc8049003c003c804f00bc00bcc04f003c003c004d00bc00bc404d003c003c" +) +# box32/pairs-sorted +NODE_26 = bytes.fromhex( + "050100000c02000004030000000400000000a041000080bf000080bf0000a841" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "00002041000080bf000080bf000030410000803f0000803f00002041000080bf" + "000080bf000030410000803f0000803f00000000000000000000000000000000" +) +# box16/pairs-sorted +NODE_27 = bytes.fromhex( + "050100000c0200000403000000040000004d00bc00bc404d003c003c004d00bc" + "00bc404d003c003c004900bc00bc8049003c003c004900bc00bc8049003c003c" +) +# box32/interleaved-sorted +NODE_28 = bytes.fromhex( + "050100000c020000040300000004000000002041000080bf000080bf00003041" + "0000803f0000803f0000a041000080bf000080bf0000a8410000803f0000803f" + "00002041000080bf000080bf000030410000803f0000803f0000a041000080bf" + "000080bf0000a8410000803f0000803f00000000000000000000000000000000" +) +# box16/interleaved-sorted +NODE_29 = bytes.fromhex( + "050100000c0200000403000000040000004900bc00bc8049003c003c004d00bc" + "00bc404d003c003c004900bc00bc8049003c003c004d00bc00bc404d003c003c" +) +# box16/3d-0.5-0.5 +NODE_30 = bytes.fromhex( + "050100000c02000004030000000400000049000000008049003c003c00490040" + "000080490042003c0049000000408049003c0042004900400040804900420042" +) +# box16/inverted +NODE_31 = bytes.fromhex( + "050100000c0200000403000000040000804900bc00bc0049003c003c000000bc" + "00bc004d003c003c804f00bc00bc404e003c003c005100bc00bc2051003c003c" +) +# tri/kind0-center +NODE_32 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090909" +) +# tri/kind0-id09 +NODE_33 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09000000" +) +# tri/kind0-id09-hi +NODE_34 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f59000000" +) +# tri/kind0-id06 +NODE_35 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f06000000" +) +# tri/kind0-id06-hi +NODE_36 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f56000000" +) +# tri/kind0-id08 +NODE_37 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f08000000" +) +# tri/kind0-id08-hi +NODE_38 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f58000000" +) +# tri/kind0-id02 +NODE_39 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f02000000" +) +# tri/kind0-id02-hi +NODE_40 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f52000000" +) +# tri/kind0-id04 +NODE_41 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f04000000" +) +# tri/kind0-id04-hi +NODE_42 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f54000000" +) +# tri/kind0-id01 +NODE_43 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f01000000" +) +# tri/kind0-id01-hi +NODE_44 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f51000000" +) +# tri/kind1-id09 +NODE_45 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00090000" +) +# tri/kind1-id09-hi +NODE_46 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00590000" +) +# tri/kind1-id06 +NODE_47 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00060000" +) +# tri/kind1-id06-hi +NODE_48 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00560000" +) +# tri/kind1-id08 +NODE_49 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00080000" +) +# tri/kind1-id08-hi +NODE_50 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00580000" +) +# tri/kind1-id02 +NODE_51 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00020000" +) +# tri/kind1-id02-hi +NODE_52 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00520000" +) +# tri/kind1-id04 +NODE_53 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00040000" +) +# tri/kind1-id04-hi +NODE_54 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00540000" +) +# tri/kind1-id01 +NODE_55 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00010000" +) +# tri/kind1-id01-hi +NODE_56 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00510000" +) +# tri/kind2-id09 +NODE_57 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000900" +) +# tri/kind2-id09-hi +NODE_58 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005900" +) +# tri/kind2-id06 +NODE_59 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000600" +) +# tri/kind2-id06-hi +NODE_60 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005600" +) +# tri/kind2-id08 +NODE_61 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000800" +) +# tri/kind2-id08-hi +NODE_62 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005800" +) +# tri/kind2-id02 +NODE_63 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000200" +) +# tri/kind2-id02-hi +NODE_64 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005200" +) +# tri/kind2-id04 +NODE_65 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000400" +) +# tri/kind2-id04-hi +NODE_66 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005400" +) +# tri/kind2-id01 +NODE_67 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000100" +) +# tri/kind2-id01-hi +NODE_68 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00005100" +) +# tri/kind3-id09 +NODE_69 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000009" +) +# tri/kind3-id09-hi +NODE_70 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000059" +) +# tri/kind3-id06 +NODE_71 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000006" +) +# tri/kind3-id06-hi +NODE_72 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000056" +) +# tri/kind3-id08 +NODE_73 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000008" +) +# tri/kind3-id08-hi +NODE_74 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000058" +) +# tri/kind3-id02 +NODE_75 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000002" +) +# tri/kind3-id02-hi +NODE_76 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000052" +) +# tri/kind3-id04 +NODE_77 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000004" +) +# tri/kind3-id04-hi +NODE_78 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000054" +) +# tri/kind3-id01 +NODE_79 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000001" +) +# tri/kind3-id01-hi +NODE_80 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000051" +) +# tri/kind0-hibits10 +NODE_81 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f19090909" +) +# tri/kind0-hibits80 +NODE_82 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f89090909" +) +# tri/kind0-hibitsf0 +NODE_83 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803ff9090909" +) +# tri/kind1-hibits10 +NODE_84 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09190909" +) +# tri/kind1-hibits80 +NODE_85 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09890909" +) +# tri/kind1-hibitsf0 +NODE_86 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09f90909" +) +# tri/kind2-hibits10 +NODE_87 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09091909" +) +# tri/kind2-hibits80 +NODE_88 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09098909" +) +# tri/kind2-hibitsf0 +NODE_89 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f0909f909" +) +# tri/kind3-hibits10 +NODE_90 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090919" +) +# tri/kind3-hibits80 +NODE_91 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090989" +) +# tri/kind3-hibitsf0 +NODE_92 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f090909f9" +) +# tri/kind0-mal00 +NODE_93 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00000000" +) +# tri/kind0-malff +NODE_94 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803fff000000" +) +# tri/kind1-malff +NODE_95 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f00ff0000" +) +# tri/kind2-malff +NODE_96 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f0000ff00" +) +# tri/kind3-malff +NODE_97 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f000000ff" +) +# tri/kind0-nan +NODE_98 = bytes.fromhex( + "00000000000000000000803f00008040000000000000803f0000c07f00000000" + "0000803f00008040000080400000803f00000041000000000000803f09090909" +) +# tri/kind0-negzero-vertex +NODE_99 = bytes.fromhex( + "00000080000000000000803f00008040000000000000803f0000000000008040" + "0000803f00008040000080400000803f00000041000000000000803f09090909" +) +# tri/kind0-x1024 +NODE_100 = bytes.fromhex( + "0000000000000000000080440000804500000000000080440000000000008045" + "0000804400008045000080450000804400000046000000000000804409090909" +) +# tri/kind0-div1024 +NODE_101 = bytes.fromhex( + "00000000000000000000803a0000803b000000000000803a000000000000803b" + "0000803a0000803b0000803b0000803a0000003c000000000000803a09090909" +) +# tri/kind0-degenerate +NODE_102 = bytes.fromhex( + "00000000000000000000803f0000803f000000000000803f0000004000000000" + "0000803f00004040000000000000803f00008040000000000000803f09090909" +) + +WITNESSES = [ + C("box32/four-sorted", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/reverse-sorted", NODE_0, D_SORT, 5, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000400, 0x00000304, 0x0000020c, 0x00000105,)), + C("box32/four-nosort", NODE_0, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/reverse-nosort", NODE_0, D_NOSORT, 5, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/extent-45", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 45.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/extent-35", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 35.0,), (0x00000105, 0x0000020c, 0x00000304, 0xffffffff,)), + C("box32/extent-25", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 25.0,), (0x00000105, 0x0000020c, 0xffffffff, 0xffffffff,)), + C("box32/extent-20", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 20.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent-19.999998", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 19.999998,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent-5", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent-0", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/extent--1", NODE_0, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), -1.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-10.5-0-e1e+09", NODE_0, D_SORT, 5, ((10.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/origin-10.5-0-e0.1", NODE_0, D_SORT, 5, ((10.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-10.5-0-e0", NODE_0, D_SORT, 5, ((10.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-12.5-0-e1e+09", NODE_0, D_SORT, 5, ((12.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/origin-12.5-0-e0.1", NODE_0, D_SORT, 5, ((12.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-12.5-0-e0", NODE_0, D_SORT, 5, ((12.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-35.5-0-e1e+09", NODE_0, D_SORT, 5, ((35.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-35.5-0-e0.1", NODE_0, D_SORT, 5, ((35.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-35.5-0-e0", NODE_0, D_SORT, 5, ((35.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0-1-e1e+09", NODE_0, D_SORT, 5, ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0-1-e0.1", NODE_0, D_SORT, 5, ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0-1-e0", NODE_0, D_SORT, 5, ((0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0--1-e1e+09", NODE_0, D_SORT, 5, ((0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/origin-0--1-e0.1", NODE_0, D_SORT, 5, ((0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.1,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/origin-0--1-e0", NODE_0, D_SORT, 5, ((0.0, -1.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/tie-sorted", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/tie-nosort", NODE_1, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/tie-two-then-far", NODE_2, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/mixed-sorted", NODE_3, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/mixed-nosort", NODE_3, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0x00000304, 0xffffffff,)), + C("box32/zero-child-sorted", NODE_4, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box32/zero-child-nosort", NODE_4, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box32/overlap-sorted", NODE_5, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0x00000105, 0x0000020c, 0x00000304,)), + C("box32/overlap-nosort", NODE_5, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/3d-0.5-0.5", NODE_6, D_SORT, 5, ((0.0, 0.5, 0.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/3d-2.5-2.5", NODE_6, D_SORT, 5, ((0.0, 2.5, 2.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/3d-1.5-1.5", NODE_6, D_SORT, 5, ((0.0, 1.5, 1.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/behind-0-e1e+09", NODE_7, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/behind-0-e0", NODE_7, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x0000020c, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/behind-0-e5", NODE_7, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0x0000020c, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/behind-5-e1e+09", NODE_7, D_SORT, 5, ((5.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/behind-5-e0", NODE_7, D_SORT, 5, ((5.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x0000020c, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/behind-5-e5", NODE_7, D_SORT, 5, ((5.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0x0000020c, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box32/behind--15-e1e+09", NODE_7, D_SORT, 5, ((-15.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/behind--15-e0", NODE_7, D_SORT, 5, ((-15.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/behind--15-e5", NODE_7, D_SORT, 5, ((-15.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/zerodir-10.5-0", NODE_8, D_SORT, 5, ((10.5, 0.0, 0.0), (0.0, 1.0, 0.0), (inf, 1.0, inf), 100.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/zerodir-0-10.5", NODE_8, D_SORT, 5, ((0.0, 10.5, 0.0), (0.0, 1.0, 0.0), (inf, 1.0, inf), 100.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/zerodir-50-10.5", NODE_8, D_SORT, 5, ((50.0, 10.5, 0.0), (0.0, 1.0, 0.0), (inf, 1.0, inf), 100.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box32/negzero-y", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, -0.0, 0.0), (1.0, -inf, inf), 100.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/negzero-z", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, -0.0), (1.0, inf, -inf), 100.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/inverted", NODE_9, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000105, 0x00000304, 0x00000400,)), + C("box32/infinite-bounds", NODE_10, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000105, 0x00000400,)), + C("box32/infinite-bounds-nosort", NODE_10, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/nan-min-disabled", NODE_11, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box32/nan-max-convention", NODE_12, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/four-sorted", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/reverse-sorted", NODE_13, D_SORT, 4, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000400, 0x00000304, 0x0000020c, 0x00000105,)), + C("box16/four-nosort", NODE_13, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/reverse-nosort", NODE_13, D_NOSORT, 4, ((50.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/extent-45", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 45.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/extent-25", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 25.0,), (0x00000105, 0x0000020c, 0xffffffff, 0xffffffff,)), + C("box16/extent-20", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 20.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/extent-19.999998", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 19.999998,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/extent-5", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 5.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/extent-0", NODE_13, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/tie-sorted", NODE_14, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/tie-nosort", NODE_14, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/mixed-sorted", NODE_15, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0xffffffff, 0xffffffff,)), + C("box16/mixed-nosort", NODE_15, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0x00000304, 0xffffffff,)), + C("box16/zero-child-sorted", NODE_16, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box16/zero-child-nosort", NODE_16, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000000, 0x00000105, 0x00000000, 0x00000304,)), + C("box16/round-low-e0", NODE_17, D_SORT, 4, ((0.09999000281095505, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/round-low-e0.001", NODE_17, D_SORT, 4, ((0.09999000281095505, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.001,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/round-low-e1", NODE_17, D_SORT, 4, ((0.09999000281095505, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/round-high-neg", NODE_18, D_SORT, 4, ((2.0998001098632812, 0.0, 0.0), (-1.0, 0.0, 0.0), (-1.0, -inf, -inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/round-high-pos", NODE_18, D_SORT, 4, ((2.0998001098632812, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/subnormal-e1", NODE_19, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1.0,), (0x00000400, 0x00000105, 0x0000020c, 0xffffffff,)), + C("box16/subnormal-e0.00012207", NODE_19, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0001220703125,), (0x00000400, 0x00000105, 0x0000020c, 0xffffffff,)), + C("box16/subnormal-e0", NODE_19, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 0.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/65504-e10", NODE_20, D_SORT, 4, ((65500.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/65504-e4", NODE_20, D_SORT, 4, ((65500.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 4.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/65504-e3.9999998", NODE_20, D_SORT, 4, ((65500.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 3.9999998,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/infinite-bounds", NODE_21, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000105, 0x00000400,)), + C("box16/infinite-bounds-nosort", NODE_21, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/nan-min-disabled", NODE_22, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000304, 0x00000400, 0xffffffff,)), + C("box16/negzero-0.0", NODE_23, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/negzero--0.0", NODE_23, D_SORT, 4, ((-0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/negzero-0.5", NODE_23, D_SORT, 4, ((0.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/negzero--1.0", NODE_23, D_SORT, 4, ((-1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 10.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/scramble-sorted", NODE_24, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000400, 0x00000304, 0x00000105,)), + C("box32/scramble-nosort", NODE_24, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/scramble-sorted", NODE_25, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000400, 0x00000304, 0x00000105,)), + C("box16/scramble-nosort", NODE_25, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/pairs-sorted", NODE_26, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000304, 0x00000400, 0x00000105, 0x0000020c,)), + C("box32/pairs-nosort", NODE_26, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/pairs-sorted", NODE_27, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000304, 0x00000400, 0x00000105, 0x0000020c,)), + C("box16/pairs-nosort", NODE_27, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/interleaved-sorted", NODE_28, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0x0000020c, 0x00000400,)), + C("box32/interleaved-nosort", NODE_28, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/interleaved-sorted", NODE_29, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x00000304, 0x0000020c, 0x00000400,)), + C("box16/interleaved-nosort", NODE_29, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/all-tie-sorted", NODE_1, D_SORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box32/all-tie-nosort", NODE_1, D_NOSORT, 5, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/all-tie-sorted", NODE_14, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/all-tie-nosort", NODE_14, D_NOSORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0x0000020c, 0x00000304, 0x00000400,)), + C("box16/3d-0.5-0.5", NODE_30, D_SORT, 4, ((0.0, 0.5, 0.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000105, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/3d-2.5-2.5", NODE_30, D_SORT, 4, ((0.0, 2.5, 2.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x00000400, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/3d-1.5-1.5", NODE_30, D_SORT, 4, ((0.0, 1.5, 1.5), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,)), + C("box16/inverted", NODE_31, D_SORT, 4, ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, inf, inf), 1000000000.0,), (0x0000020c, 0x00000105, 0x00000304, 0x00000400,)), + C("tri/kind0-center", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-center", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-center", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-center", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-edge-ac", NODE_32, D_SORT, 0, ((0.0, 2.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0x00000000, 0xc1000000,)), + C("tri/kind3-edge-ac", NODE_32, D_SORT, 3, ((0.0, 2.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x80000000, 0x41800000,)), + C("tri/kind0-vertex-a", NODE_32, D_SORT, 0, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0x00000000, 0x00000000,)), + C("tri/kind3-vertex-a", NODE_32, D_SORT, 3, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x00000000, 0x42000000,)), + C("tri/kind2-edge-ce", NODE_32, D_SORT, 2, ((4.0, 2.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x00000000, 0x41000000,)), + C("tri/kind0-outside", NODE_32, D_SORT, 0, ((5.0, 5.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-outside", NODE_32, D_SORT, 1, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-outside", NODE_32, D_SORT, 2, ((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-outside", NODE_32, D_SORT, 3, ((4.0, 4.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-id09", NODE_33, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-id09-hi", NODE_34, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-id06", NODE_35, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind0-id06-hi", NODE_36, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind0-id08", NODE_37, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind0-id08-hi", NODE_38, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind0-id02", NODE_39, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind0-id02-hi", NODE_40, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind0-id04", NODE_41, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind0-id04-hi", NODE_42, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind0-id01", NODE_43, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind0-id01-hi", NODE_44, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind1-id09", NODE_45, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-id09-hi", NODE_46, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-id06", NODE_47, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind1-id06-hi", NODE_48, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind1-id08", NODE_49, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind1-id08-hi", NODE_50, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind1-id02", NODE_51, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-id02-hi", NODE_52, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-id04", NODE_53, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind1-id04-hi", NODE_54, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind1-id01", NODE_55, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind1-id01-hi", NODE_56, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-id09", NODE_57, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-id09-hi", NODE_58, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-id06", NODE_59, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind2-id06-hi", NODE_60, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc1000000,)), + C("tri/kind2-id08", NODE_61, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind2-id08-hi", NODE_62, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind2-id02", NODE_63, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind2-id02-hi", NODE_64, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x40800000,)), + C("tri/kind2-id04", NODE_65, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind2-id04-hi", NODE_66, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x40800000, 0x41000000,)), + C("tri/kind2-id01", NODE_67, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-id01-hi", NODE_68, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind3-id09", NODE_69, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-id09-hi", NODE_70, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-id06", NODE_71, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1a00000, 0xc0800000,)), + C("tri/kind3-id06-hi", NODE_72, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1a00000, 0xc0800000,)), + C("tri/kind3-id08", NODE_73, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1000000, 0xc1a00000,)), + C("tri/kind3-id08-hi", NODE_74, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc1000000, 0xc1a00000,)), + C("tri/kind3-id02", NODE_75, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41a00000, 0x41000000,)), + C("tri/kind3-id02-hi", NODE_76, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41a00000, 0x41000000,)), + C("tri/kind3-id04", NODE_77, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41000000, 0x40800000,)), + C("tri/kind3-id04-hi", NODE_78, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x41000000, 0x40800000,)), + C("tri/kind3-id01", NODE_79, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc0800000, 0xc1000000,)), + C("tri/kind3-id01-hi", NODE_80, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc2000000, 0xc2000000, 0xc0800000, 0xc1000000,)), + C("tri/kind0-hibits10", NODE_81, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-hibits80", NODE_82, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind0-hibitsf0", NODE_83, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-hibits10", NODE_84, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-hibits80", NODE_85, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind1-hibitsf0", NODE_86, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-hibits10", NODE_87, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-hibits80", NODE_88, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind2-hibitsf0", NODE_89, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-hibits10", NODE_90, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-hibits80", NODE_91, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind3-hibitsf0", NODE_92, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-mal00", NODE_93, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-malff", NODE_94, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-mal00", NODE_93, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-malff", NODE_95, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-mal00", NODE_93, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-malff", NODE_96, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-mal00", NODE_93, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-malff", NODE_97, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-nan", NODE_98, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-nan", NODE_98, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-nan", NODE_98, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-nan", NODE_98, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-negzero-vertex", NODE_99, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind3-negzero-vertex", NODE_99, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-zerodir", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-zerodir", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-zerodir", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-zerodir", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 0.0), (inf, inf, inf), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-negzero-dir", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, -0.0, 1.0), (0.0, -inf, 1.0), 1000000000.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind3-negzero-dir", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, -0.0, 1.0), (0.0, -inf, 1.0), 1000000000.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-behind", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-behind", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-behind", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-behind", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, -1.0), (0.0, 0.0, -1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind0-t0", NODE_32, D_SORT, 0, ((1.0, 1.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x80000000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-t0", NODE_32, D_SORT, 1, ((3.0, 3.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x80000000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-t0", NODE_32, D_SORT, 2, ((4.0, 3.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x00000000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-t0", NODE_32, D_SORT, 3, ((1.0, 1.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x00000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-extent0", NODE_32, D_SORT, 0, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0xc1800000, 0xc1800000, 0xc0800000, 0xc0800000,)), + C("tri/kind1-extent0", NODE_32, D_SORT, 1, ((3.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0xc1800000, 0xc1800000, 0xc1000000, 0xc0800000,)), + C("tri/kind2-extent0", NODE_32, D_SORT, 2, ((4.0, 3.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0x41800000, 0x41800000, 0x41000000, 0x40800000,)), + C("tri/kind3-extent0", NODE_32, D_SORT, 3, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 0.0,), (0x42000000, 0x42000000, 0x40800000, 0x41a00000,)), + C("tri/kind0-x1024", NODE_100, D_SORT, 0, ((1024.0, 1024.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0xcb800000, 0xcb800000, 0xca800000, 0xca800000,)), + C("tri/kind1-x1024", NODE_100, D_SORT, 1, ((3072.0, 3072.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0xcb800000, 0xcb800000, 0xcb000000, 0xca800000,)), + C("tri/kind2-x1024", NODE_100, D_SORT, 2, ((4096.0, 3072.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0x4b800000, 0x4b800000, 0x4b000000, 0x4a800000,)), + C("tri/kind3-x1024", NODE_100, D_SORT, 3, ((1024.0, 1024.0, 0.0), (0.0, 0.0, 1024.0), (0.0, 0.0, 0.0009765625), 1000000000.0,), (0x4c000000, 0x4c000000, 0x4a800000, 0x4ba00000,)), + C("tri/kind0-div1024", NODE_101, D_SORT, 0, ((0.0009765625, 0.0009765625, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0xb7800000, 0xb7800000, 0xb6800000, 0xb6800000,)), + C("tri/kind1-div1024", NODE_101, D_SORT, 1, ((0.0029296875, 0.0029296875, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0xb7800000, 0xb7800000, 0xb7000000, 0xb6800000,)), + C("tri/kind2-div1024", NODE_101, D_SORT, 2, ((0.00390625, 0.0029296875, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0x37800000, 0x37800000, 0x37000000, 0x36800000,)), + C("tri/kind3-div1024", NODE_101, D_SORT, 3, ((0.0009765625, 0.0009765625, 0.0), (0.0, 0.0, 0.0009765625), (0.0, 0.0, 1024.0), 1000000000.0,), (0x38000000, 0x38000000, 0x36800000, 0x37a00000,)), + C("tri/kind0-degenerate", NODE_102, D_SORT, 0, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind1-degenerate", NODE_102, D_SORT, 1, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind2-degenerate", NODE_102, D_SORT, 2, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind3-degenerate", NODE_102, D_SORT, 3, ((0.5, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind6-notriangle", NODE_32, D_SORT, 6, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), + C("tri/kind7-notriangle", NODE_32, D_SORT, 7, ((1.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), 1000000000.0,), (0x7f800000, 0x3f800000, 0x00000000, 0x00000000,)), +] + +POINTER_WITNESSES = [ + P("ptr/base0-0-k0", bvh_model.descriptor(0x0), 0x0, False, (0, 0x0)), + P("ptr/base0-0-k1", bvh_model.descriptor(0x0), 0x1, False, (1, 0x0)), + P("ptr/base0-0-k2", bvh_model.descriptor(0x0), 0x2, False, (2, 0x0)), + P("ptr/base0-0-k3", bvh_model.descriptor(0x0), 0x3, False, (3, 0x0)), + P("ptr/base0-0-k4", bvh_model.descriptor(0x0), 0x4, False, (4, 0x0)), + P("ptr/base0-0-k5", bvh_model.descriptor(0x0), 0x5, False, (5, 0x0)), + P("ptr/base0-0-k6", bvh_model.descriptor(0x0), 0x6, False, (6, 0x0)), + P("ptr/base0-0-k7", bvh_model.descriptor(0x0), 0x7, False, (7, 0x0)), + P("ptr/base0-64-k0", bvh_model.descriptor(0x0), 0x8, False, (0, 0x40)), + P("ptr/base0-64-k1", bvh_model.descriptor(0x0), 0x9, False, (1, 0x40)), + P("ptr/base0-64-k2", bvh_model.descriptor(0x0), 0xa, False, (2, 0x40)), + P("ptr/base0-64-k3", bvh_model.descriptor(0x0), 0xb, False, (3, 0x40)), + P("ptr/base0-64-k4", bvh_model.descriptor(0x0), 0xc, False, (4, 0x40)), + P("ptr/base0-64-k5", bvh_model.descriptor(0x0), 0xd, False, (5, 0x40)), + P("ptr/base0-64-k6", bvh_model.descriptor(0x0), 0xe, False, (6, 0x40)), + P("ptr/base0-64-k7", bvh_model.descriptor(0x0), 0xf, False, (7, 0x40)), + P("ptr/base0-128-k0", bvh_model.descriptor(0x0), 0x10, False, (0, 0x80)), + P("ptr/base0-128-k1", bvh_model.descriptor(0x0), 0x11, False, (1, 0x80)), + P("ptr/base0-128-k2", bvh_model.descriptor(0x0), 0x12, False, (2, 0x80)), + P("ptr/base0-128-k3", bvh_model.descriptor(0x0), 0x13, False, (3, 0x80)), + P("ptr/base0-128-k4", bvh_model.descriptor(0x0), 0x14, False, (4, 0x80)), + P("ptr/base0-128-k5", bvh_model.descriptor(0x0), 0x15, False, (5, 0x80)), + P("ptr/base0-128-k6", bvh_model.descriptor(0x0), 0x16, False, (6, 0x80)), + P("ptr/base0-128-k7", bvh_model.descriptor(0x0), 0x17, False, (7, 0x80)), + P("ptr/base0-192-k0", bvh_model.descriptor(0x0), 0x18, False, (0, 0xc0)), + P("ptr/base0-192-k1", bvh_model.descriptor(0x0), 0x19, False, (1, 0xc0)), + P("ptr/base0-192-k2", bvh_model.descriptor(0x0), 0x1a, False, (2, 0xc0)), + P("ptr/base0-192-k3", bvh_model.descriptor(0x0), 0x1b, False, (3, 0xc0)), + P("ptr/base0-192-k4", bvh_model.descriptor(0x0), 0x1c, False, (4, 0xc0)), + P("ptr/base0-192-k5", bvh_model.descriptor(0x0), 0x1d, False, (5, 0xc0)), + P("ptr/base0-192-k6", bvh_model.descriptor(0x0), 0x1e, False, (6, 0xc0)), + P("ptr/base0-192-k7", bvh_model.descriptor(0x0), 0x1f, False, (7, 0xc0)), + P("ptr/base0-256-k0", bvh_model.descriptor(0x0), 0x20, False, (0, 0x100)), + P("ptr/base0-256-k1", bvh_model.descriptor(0x0), 0x21, False, (1, 0x100)), + P("ptr/base0-256-k2", bvh_model.descriptor(0x0), 0x22, False, (2, 0x100)), + P("ptr/base0-256-k3", bvh_model.descriptor(0x0), 0x23, False, (3, 0x100)), + P("ptr/base0-256-k4", bvh_model.descriptor(0x0), 0x24, False, (4, 0x100)), + P("ptr/base0-256-k5", bvh_model.descriptor(0x0), 0x25, False, (5, 0x100)), + P("ptr/base0-256-k6", bvh_model.descriptor(0x0), 0x26, False, (6, 0x100)), + P("ptr/base0-256-k7", bvh_model.descriptor(0x0), 0x27, False, (7, 0x100)), + P("ptr/base0-448-k0", bvh_model.descriptor(0x0), 0x38, False, (0, 0x1c0)), + P("ptr/base0-448-k1", bvh_model.descriptor(0x0), 0x39, False, (1, 0x1c0)), + P("ptr/base0-448-k2", bvh_model.descriptor(0x0), 0x3a, False, (2, 0x1c0)), + P("ptr/base0-448-k3", bvh_model.descriptor(0x0), 0x3b, False, (3, 0x1c0)), + P("ptr/base0-448-k4", bvh_model.descriptor(0x0), 0x3c, False, (4, 0x1c0)), + P("ptr/base0-448-k5", bvh_model.descriptor(0x0), 0x3d, False, (5, 0x1c0)), + P("ptr/base0-448-k6", bvh_model.descriptor(0x0), 0x3e, False, (6, 0x1c0)), + P("ptr/base0-448-k7", bvh_model.descriptor(0x0), 0x3f, False, (7, 0x1c0)), + P("ptr/base40-0-k0", bvh_model.descriptor(0x4000), 0x0, False, (0, 0x4000)), + P("ptr/base40-0-k5", bvh_model.descriptor(0x4000), 0x5, False, (5, 0x4000)), + P("ptr/base40-0-k7", bvh_model.descriptor(0x4000), 0x7, False, (7, 0x4000)), + P("ptr/base40-64-k0", bvh_model.descriptor(0x4000), 0x8, False, (0, 0x4040)), + P("ptr/base40-64-k5", bvh_model.descriptor(0x4000), 0xd, False, (5, 0x4040)), + P("ptr/base40-64-k7", bvh_model.descriptor(0x4000), 0xf, False, (7, 0x4040)), + P("ptr/base40-256-k0", bvh_model.descriptor(0x4000), 0x20, False, (0, 0x4100)), + P("ptr/base40-256-k5", bvh_model.descriptor(0x4000), 0x25, False, (5, 0x4100)), + P("ptr/base40-256-k7", bvh_model.descriptor(0x4000), 0x27, False, (7, 0x4100)), + P("ptr/highbase-0-k0", bvh_model.descriptor(0x1234567800), 0x0, False, (0, 0x1234567800)), + P("ptr/highbase-0-k4", bvh_model.descriptor(0x1234567800), 0x4, False, (4, 0x1234567800)), + P("ptr/highbase-0-k5", bvh_model.descriptor(0x1234567800), 0x5, False, (5, 0x1234567800)), + P("ptr/highbase-64-k0", bvh_model.descriptor(0x1234567800), 0x8, False, (0, 0x1234567840)), + P("ptr/highbase-64-k4", bvh_model.descriptor(0x1234567800), 0xc, False, (4, 0x1234567840)), + P("ptr/highbase-64-k5", bvh_model.descriptor(0x1234567800), 0xd, False, (5, 0x1234567840)), + P("ptr/highbase-4096-k0", bvh_model.descriptor(0x1234567800), 0x200, False, (0, 0x1234568800)), + P("ptr/highbase-4096-k4", bvh_model.descriptor(0x1234567800), 0x204, False, (4, 0x1234568800)), + P("ptr/highbase-4096-k5", bvh_model.descriptor(0x1234567800), 0x205, False, (5, 0x1234568800)), + P("ptr/wrap-100", bvh_model.descriptor(0xffffffffff00), 0x25, False, (5, 0x0)), + P("ptr/wrap-80", bvh_model.descriptor(0xffffffffff00), 0x14, False, (4, 0xffffffffff80)), + P("ptr/wide-0-k0", bvh_model.descriptor(0x0), 0x0, True, (0, 0x0)), + P("ptr/wide-0-k5", bvh_model.descriptor(0x0), 0x5, True, (5, 0x0)), + P("ptr/wide-0-k7", bvh_model.descriptor(0x0), 0x7, True, (7, 0x0)), + P("ptr/wide-40-k0", bvh_model.descriptor(0x0), 0x8, True, (0, 0x40)), + P("ptr/wide-40-k5", bvh_model.descriptor(0x0), 0xd, True, (5, 0x40)), + P("ptr/wide-40-k7", bvh_model.descriptor(0x0), 0xf, True, (7, 0x40)), + P("ptr/wide-1000-k0", bvh_model.descriptor(0x0), 0x200, True, (0, 0x1000)), + P("ptr/wide-1000-k5", bvh_model.descriptor(0x0), 0x205, True, (5, 0x1000)), + P("ptr/wide-1000-k7", bvh_model.descriptor(0x0), 0x207, True, (7, 0x1000)), + P("ptr/wide-1234567800-k0", bvh_model.descriptor(0x0), 0x2468acf00, True, (0, 0x1234567800)), + P("ptr/wide-1234567800-k5", bvh_model.descriptor(0x0), 0x2468acf05, True, (5, 0x1234567800)), + P("ptr/wide-1234567800-k7", bvh_model.descriptor(0x0), 0x2468acf07, True, (7, 0x1234567800)), + P("ptr/wide-ffffffffffffffc0-k0", bvh_model.descriptor(0x0), 0x1ffffffffffffff8, True, (0, 0xffffffffffffffc0)), + P("ptr/wide-ffffffffffffffc0-k5", bvh_model.descriptor(0x0), 0x1ffffffffffffffd, True, (5, 0xffffffffffffffc0)), + P("ptr/wide-ffffffffffffffc0-k7", bvh_model.descriptor(0x0), 0x1fffffffffffffff, True, (7, 0xffffffffffffffc0)), + P("ptr/wide-ignores-base", bvh_model.descriptor(0x1234567800), 0x205, True, (5, 0x1000)), +] + + def descriptor_for(base, wide): # Absolute typed pointers use base zero and the full 42-bit node-count field. # Relative pointers are constructed only for the two nodes in this allocation. @@ -193,13 +1107,14 @@ def main(): parser.add_argument("--model-only", action="store_true") args = parser.parse_args() model_check() + failures = witness_check() if args.model_only: - return 0 + return int(failures != 0) if any(key.startswith("HSA_OVERRIDE_GFX_VERSION") for key in os.environ): parser.error("Unset HSA_OVERRIDE_GFX_VERSION before measuring native behavior") if not OBJECT.is_file(): parser.error("Build the gfx1030 code object with sh tests/gfx1030_bvh_box/build.sh") - return run(args.library, args.device) + return int(run(args.library, args.device) + failures != 0) if __name__ == "__main__": diff --git a/tests/gpu_case_recorder_check.py b/tests/gpu_case_recorder_check.py new file mode 100644 index 0000000000..f5f0768799 --- /dev/null +++ b/tests/gpu_case_recorder_check.py @@ -0,0 +1,45 @@ +"""tools/record_gpu_cases.py writes what the GPU check package replays: python gpu_case_recorder_check.py [dxc].""" +import shutil +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT / 'tools'), str(ROOT / 'tests')] +import record_gpu_cases as recorder # noqa: E402 +import startup_gfx2hlsl_compute_check as check # noqa: E402 + + +def main(dxc): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) + rows = recorder.record(dxc, out) + assert [r[0] for r in rows if r[2] == 'pass'] == ['gfx2hlsl_compute/' + n for n in check.CASES], rows + controls = {r[0]: r for r in rows if r[2] == 'fail'} + assert sorted(controls) == sorted('gfx2hlsl_compute/control-' + m for m in check.CONTROLS), sorted(controls) + manifest = [line.split('\t') for line in (out / 'manifest.tsv').read_text(encoding='ascii').splitlines()] + assert manifest == [list(r) for r in rows], 'manifest rows differ from the recorded cases' + for ident, compiler, expect, mismatch in manifest: + assert compiler == 'dxc' and expect in ('pass', 'fail'), ident + cso, case = (out / ('%s.%s' % (ident, ext)) for ext in ('cso', 'case')) + assert cso.read_bytes()[:4] == b'DXBC', ident + # group counts, WORDS expected words, 16 root constants, then any formatted input + assert len(case.read_bytes()) >= 4 + 4 * check.WORDS + 64, ident + for mutation, (name, _, _) in check.CONTROLS.items(): + base = out / ('gfx2hlsl_compute/%s.cso' % name) + ctrl = out / ('gfx2hlsl_compute/control-%s.cso' % mutation) + assert base.read_bytes() != ctrl.read_bytes(), 'control %s compiled to the unmutated shader' % mutation + pinned = controls['gfx2hlsl_compute/control-' + mutation][3] + assert pinned == check.CONTROL_MISMATCH.get(mutation, ''), mutation + print('recorded %d gfx2hlsl compute cases and %d controls' % (len(check.CASES), len(check.CONTROLS))) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) > 2: + sys.exit(__doc__) + found = sys.argv[1] if len(sys.argv) == 2 else shutil.which('dxc') + if not found: + print('skip: no dxc on PATH and none given') + sys.exit(77) + sys.exit(main(found)) diff --git a/tests/gpu_case_runner.py b/tests/gpu_case_runner.py new file mode 100644 index 0000000000..289e5ef089 --- /dev/null +++ b/tests/gpu_case_runner.py @@ -0,0 +1,227 @@ +"""Shared by the GPU checks: one D3D12 device per test instead of one offscreen_check process per case (issue #448). + +run(renderer, adapter, args) + The same as subprocess.run([renderer, adapter, *args], capture_output=True, text=True), but the case goes to a long-lived + `offscreen_check <adapter> --serve` process of this test (one device for all its cases). The returned + subprocess.CompletedProcess has the one-shot meaning: returncode 0 pass, 1 failure, 77 skip, 2 bad arguments. Its stdout + and stderr are the text the one-shot call would print, adapter banner included for EVERY case (so a check that looks for + "debug_layer=enabled" and "debug_errors=0 debug_warnings=0" sees them in each case, as it does in a one-shot call). + + Only a server that cannot start falls back to the one-shot call (an older offscreen_check without `--serve`, no adapter, + X2W_FLAT_SERVER=0): no case has been sent yet, so the one-shot call gives the verdict. Once a case has been sent, a + renderer that dies, hangs past CASE_TIMEOUT_S, or answers with the wrong case number gives a FAILED verdict (returncode 1, + the reason on stderr) for that case; it is never run again, so a crash cannot turn into a pass. The next case starts a + new server. +""" +import atexit +import os +import queue +import signal +import subprocess +import threading +import time + +CASE_TIMEOUT_S = 300 +SERVER_OFF = os.environ.get('X2W_FLAT_SERVER') == '0' +DEVICE_REMOVED = 'device removed during case' +_servers = {} + + +def _command(renderer): + """The renderer as a command prefix: a path, or a list such as an interpreter plus its script (a launcher in between would + keep the pipes open after the renderer is killed).""" + return [str(part) for part in renderer] if isinstance(renderer, (list, tuple)) else [str(renderer)] + + +class _Lost(Exception): + """The server did not answer the case it was sent.""" + + +class _Server: + def __init__(self, renderer, adapter): + self.out, self.err = queue.Queue(), queue.Queue() + self.proc = subprocess.Popen([*_command(renderer), adapter, '--serve'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, bufsize=1, + start_new_session=os.name == 'posix') # own process group: a launcher's children die with it + self.banner, self.banner_err, self.ready, self.returncode, self.stderr_text = '', '', False, None, '' + self.next_case, self.lost_out, self.lost_err = 0, '', '' + self.threads = [threading.Thread(target=self._pump, args=(self.proc.stdout, self.out, 'X2WCASE '), daemon=True), + threading.Thread(target=self._pump, args=(self.proc.stderr, self.err, 'X2WEND '), daemon=True)] + for thread in self.threads: + thread.start() + deadline = time.monotonic() + CASE_TIMEOUT_S + first = self._get(self.out, deadline) # the banner, closed by the marker pair of case -1 + banner_err = self._get(self.err, deadline) + if first is None or first[1] != -1 or first[2] != 0 or banner_err is None or banner_err[1] != -1: + self.proc.kill() # closed first (skip 77, an unknown mode, a crash) or a hang + self.proc.wait() + self.returncode = self.proc.returncode + self.stderr_text = ''.join(self._drain(self.err)) + self.banner = first[0] if first else '' + self._release() + return + self.banner, self.banner_err, self.ready = first[0], banner_err[0], True + + @staticmethod + def _pump(stream, sink, marker): + """Split a stream into per-case chunks at its marker line "<marker><case index> [exit code]".""" + chunk = [] + for line in stream: + parts = line.split() + if line.startswith(marker) and len(parts) == (3 if marker == 'X2WCASE ' else 2): + try: + index = int(parts[1]) + code = int(parts[2]) if marker == 'X2WCASE ' else 0 + except ValueError: + chunk.append(line) + continue + sink.put((''.join(chunk), index, code)) + chunk = [] + else: + chunk.append(line) + if chunk: + sink.put((''.join(chunk), None, None)) + sink.put(None) + + @staticmethod + def _get(q, deadline): + """The next (text, case index, exit code) of a stream, or None at its end or the deadline.""" + try: + item = q.get(timeout=max(0.0, deadline - time.monotonic())) + except queue.Empty: + return None + return item # None at the end of the stream; an unmarked tail has index None + + @staticmethod + def _drain(q): + items = [] + while True: + try: + item = q.get(timeout=2) + except queue.Empty: + return items + if item is None: + return items + items.append(item[0]) + + @staticmethod + def _drain_now(q): + """The text still queued, without waiting (the pumps have ended).""" + items = [] + while True: + try: + item = q.get_nowait() + except queue.Empty: + return items + if item is not None: + items.append(item[0]) + + def case(self, args): + """Send one case; the reply must carry exactly this case's number on both streams, else _Lost.""" + index, self.next_case = self.next_case, self.next_case + 1 + deadline = time.monotonic() + CASE_TIMEOUT_S + try: + self.proc.stdin.write('\t'.join(args) + '\n') + self.proc.stdin.flush() + except OSError as error: + raise _Lost('could not send the case: %s' % error) + out, err = self._get(self.out, deadline), self._get(self.err, deadline) + self.lost_out = out[0] if out else '' # what the renderer printed for this case, kept for a FAILED verdict + self.lost_err = err[0] if err else '' + if out is None or err is None or out[1] is None or err[1] is None: + try: # a dying process closes its pipes a moment before it can be reaped + self.proc.wait(timeout=max(0.0, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + pass + state = 'timed out after %d s' % CASE_TIMEOUT_S if self.proc.poll() is None else 'exited (code %s)' % self.proc.poll() + raise _Lost('the renderer %s during the case' % state) + if out[1] != index or err[1] != index: + raise _Lost('the renderer answered case %s/%s to case %d' % (out[1], err[1], index)) + return subprocess.CompletedProcess(self.proc.args, out[2], self.banner + out[0], self.banner_err + err[0]) + + def _kill_tree(self): + """Kill the renderer and everything it started (a Wine or shell launcher leaves a child that keeps the pipes open).""" + try: + if os.name == 'posix': + os.killpg(self.proc.pid, signal.SIGKILL) + else: + subprocess.run(['taskkill', '/F', '/T', '/PID', str(self.proc.pid)], capture_output=True) + except OSError: + pass + self.proc.kill() + + def _release(self): + """Wait for the process, end its group, join the pump threads and close the pipes, so nothing is left behind.""" + self.proc.wait() + self._kill_tree() + for thread in self.threads: # the pumps end at the end of the pipes + thread.join(timeout=5) + for stream, thread in ((self.proc.stdin, None), (self.proc.stdout, self.threads[0]), (self.proc.stderr, self.threads[1])): + if thread is None or not thread.is_alive(): # closing a pipe a pump is still reading would block + try: + stream.close() + except (OSError, ValueError): + pass + + def kill(self): + self._kill_tree() + self._release() + + def close(self): + try: + self.proc.stdin.write('--end\n') # explicit: a launcher in between may not pass the end of stdin on + self.proc.stdin.close() + self.proc.wait(timeout=30) + except (OSError, ValueError, subprocess.TimeoutExpired): # already closed, or it does not end + self._kill_tree() + self._release() + + +def _close_all(): + for server in _servers.values(): + if server: + server.close() + + +atexit.register(_close_all) + + +def _failed(server, reason): + """The FAILED verdict of a case whose server did not answer it.""" + server.kill() # ends the pumps, so everything the renderer printed is in the queues + out = server.banner + server.lost_out + ''.join(server._drain_now(server.out)) + err = server.banner_err + server.lost_err + ''.join(server._drain_now(server.err)) + return subprocess.CompletedProcess(server.proc.args, 1, out, 'gpu_case_runner: %s\n%s' % (reason, err)) + + +def run(renderer, adapter, args): + args = [str(a) for a in args] + key = (tuple(_command(renderer)), adapter) + if not SERVER_OFF and '\t' not in ''.join(args) and '\n' not in ''.join(args): + for _ in range(2): # a second start only when the first server was already gone before the case + server = _servers.get(key) + if server is None: + server = _servers[key] = _Server(renderer, adapter) + if not server.ready: # nothing was sent: the one-shot call gives the verdict + _servers[key] = False + if server.returncode == 77: # no adapter: the skip the one-shot call reports + return subprocess.CompletedProcess(server.proc.args, 77, server.banner, server.stderr_text) + break + elif server is False: + break + if server.proc.poll() is not None: # it ended after its last answer (device removed): start a new one + server.kill() + _servers[key] = None + continue + try: + result = server.case(args) + except _Lost as lost: + _servers[key] = None + return _failed(server, str(lost)) + if DEVICE_REMOVED in result.stderr: + server.close() + _servers[key] = None + return result + else: + _servers[key] = False + return subprocess.run([*_command(renderer), adapter, *args], capture_output=True, text=True) diff --git a/tests/gpu_case_runner_check.py b/tests/gpu_case_runner_check.py new file mode 100644 index 0000000000..271f68f57e --- /dev/null +++ b/tests/gpu_case_runner_check.py @@ -0,0 +1,243 @@ +"""tests/gpu_case_runner.py: the served cases answer like one-shot calls, and every failure of the server falls back to one. + +The renderer here is a fake offscreen_check (a Python script behind a one-line launcher) that speaks the `--serve` protocol of +tests/offscreen_check.cpp: a banner closed by the marker pair of case -1, then per case the case text, "X2WEND <i>" on stderr and +"X2WCASE <i> <exit code>" on stdout. Its one-shot mode prints the same text, so the two paths can be compared. +""" +import os +import subprocess +import sys +import tempfile +import time +import unittest +import unittest.mock +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import gpu_case_runner as R # noqa: E402 + +FAKE = r''' +import os, sys +mode = sys.argv[1].split("=", 1)[1] +adapter, args = sys.argv[2], sys.argv[3:] + +def one(args): + """The text and exit code of one case, as the real tool prints them.""" + op = args[0] + with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "cases.log"), "a") as log: + log.write(" ".join(args) + "\n") + if op == "--pass": + return "ok %s\ndebug_errors=0 debug_warnings=0\n" % args[1], "", 0 + if op == "--warn": + return "ok %s\ndebug_errors=0 debug_warnings=1\n" % args[1], "", 0 + if op == "--mismatch": + return "", "startup_flat_param mismatch %s\n" % args[1], 1 + if op == "--skip": + return "skip: nothing\n", "", 77 + return "", "Unknown GPU operation or invalid arguments: %s\n" % op, 2 + +if mode == "grandchild": # a launcher child that keeps the pipes open after the renderer is gone + import subprocess + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) + with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "grandchild.pid"), "w") as pid_file: + pid_file.write(str(child.pid)) +banner = "backend=%s debug_layer=enabled\nadapter=Fake\n" % adapter +if args and args[0] == "--serve": + if mode == "no-serve": + sys.stderr.write("Unknown GPU operation or invalid arguments: --serve\n") + sys.exit(2) + if mode == "no-adapter": + print("No D3D12-capable hardware adapter visible") + sys.exit(77) + sys.stdout.write(banner) + sys.stderr.write("XBOX2WINDOWS_ADAPTER: skipping Other\n") + sys.stderr.write("X2WEND -1\n") + print("X2WCASE -1 0", flush=True) + for index, line in enumerate(sys.stdin): + if line == "--end\n": + sys.exit(0) + out, err, code = one(line.rstrip("\n").split("\t")) + if mode == "die-at-%d" % index: + os._exit(3) + if mode == "noisy-die-at-%d" % index: + sys.stdout.write("partial output %d\n" % index) + sys.stdout.flush() + sys.stderr.write("renderer diagnostic %d\n" % index) + sys.stderr.flush() + os._exit(3) + if mode == "hang-at-%d" % index: + sys.stderr.write("hang diagnostic %d\n" % index) + sys.stderr.flush() + import time + time.sleep(60) + if mode == "skew-at-%d" % index: + sys.stderr.write("X2WEND %d\n" % (index + 5)) + print("X2WCASE %d 0" % index, flush=True) + continue + sys.stdout.write(out) + sys.stderr.write(err) + sys.stderr.write("X2WEND %d\n" % index) + print("X2WCASE %d %d" % (index, code), flush=True) + sys.exit(0) +out, err, code = one(args) +sys.stdout.write("ONESHOT " + banner + out) +sys.stderr.write(err) +sys.exit(code) +''' + + +def launcher(directory, name, mode): + """The renderer as an interpreter plus script, a direct child of the runner: killing it releases its pipes at once (a + .cmd or shell launcher in between would leave a sleeping grandchild holding them).""" + fake = directory / 'fake_offscreen.py' + fake.write_text(FAKE) + return [sys.executable, str(fake), '--mode=' + mode] + + +def running(pid): + """True while the process runs: a killed child nobody reaped (PID 1 of a container) stays a zombie, which is not running.""" + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + try: + with open('/proc/%d/stat' % pid) as stat: + return stat.read().rsplit(')', 1)[1].split()[0] != 'Z' + except (OSError, IndexError): + return True + + +class RunnerChecks(unittest.TestCase): + def setUp(self): + R._servers.clear() + self.addCleanup(R._servers.clear) + self.addCleanup(R._close_all) # runs first: the servers of the test are closed before the table is emptied + patch = unittest.mock.patch.object(R, 'SERVER_OFF', False) # X2W_FLAT_SERVER=0 in the environment must not turn served tests into one-shot calls + patch.start() + self.addCleanup(patch.stop) + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + + def run_case(self, renderer, *args): + return R.run(renderer, 'warp', args) + + def test_served_cases_carry_their_own_text_and_exit_code(self): + renderer = launcher(self.dir, 'fake', 'serve') + first = self.run_case(renderer, '--pass', 'a') + second = self.run_case(renderer, '--mismatch', 'b') + third = self.run_case(renderer, '--pass', 'c') + self.assertEqual((first.returncode, second.returncode, third.returncode), (0, 1, 0)) + self.assertEqual(first.stdout, 'backend=warp debug_layer=enabled\nadapter=Fake\nok a\ndebug_errors=0 debug_warnings=0\n') + self.assertEqual(first.stderr, 'XBOX2WINDOWS_ADAPTER: skipping Other\n') + self.assertEqual(second.stderr, 'XBOX2WINDOWS_ADAPTER: skipping Other\nstartup_flat_param mismatch b\n') + self.assertEqual(third.stdout, 'backend=warp debug_layer=enabled\nadapter=Fake\nok c\ndebug_errors=0 debug_warnings=0\n') # banner on every case + self.assertEqual(third.stderr, 'XBOX2WINDOWS_ADAPTER: skipping Other\n') + self.assertEqual(self.run_case(renderer, '--bogus').returncode, 2) + + def test_skip_and_missing_adapter_keep_their_exit_code(self): + self.assertEqual(self.run_case(launcher(self.dir, 'skip', 'serve'), '--skip').returncode, 77) + none = self.run_case(launcher(self.dir, 'none', 'no-adapter'), '--pass', 'x') + self.assertEqual(none.returncode, 77) + self.assertIn('No D3D12-capable hardware adapter visible', none.stdout) + + def test_a_renderer_without_serve_falls_back_to_one_shot_calls(self): + renderer = launcher(self.dir, 'old', 'no-serve') + result = self.run_case(renderer, '--mismatch', 'z') + self.assertEqual(result.returncode, 1) + self.assertTrue(result.stdout.startswith('ONESHOT ')) + self.assertEqual(self.run_case(renderer, '--pass', 'q').returncode, 0) + + def executed(self): + log = self.dir / 'cases.log' + return log.read_text().splitlines() if log.exists() else [] + + def test_a_crash_after_the_handshake_is_a_failed_verdict_and_the_case_is_not_run_again(self): + renderer = launcher(self.dir, 'dies', 'die-at-1') + self.assertEqual(self.run_case(renderer, '--pass', 'a').returncode, 0) + lost = self.run_case(renderer, '--pass', 'b') # the renderer dies on this case, which would pass if re-run + self.assertEqual(lost.returncode, 1) + self.assertIn('exited (code 3)', lost.stderr) + self.assertEqual(self.executed(), ['--pass a', '--pass b']) # fake logs the case before dying; never a second time + self.assertEqual(self.run_case(renderer, '--pass', 'c').returncode, 0) # the next case gets a new server + + def test_a_silent_renderer_fails_the_case_after_one_deadline(self): + renderer = launcher(self.dir, 'hangs', 'hang-at-0') + self.addCleanup(setattr, R, 'CASE_TIMEOUT_S', R.CASE_TIMEOUT_S) + R.CASE_TIMEOUT_S = 2 + started = time.monotonic() + lost = self.run_case(renderer, '--pass', 'a') + self.assertEqual(lost.returncode, 1) + self.assertIn('timed out after 2 s', lost.stderr) + self.assertLess(time.monotonic() - started, 4) # one deadline for both streams, not one each + self.assertIn('hang diagnostic 0', lost.stderr) # what it printed before hanging survives + self.assertIn('debug_layer=enabled', lost.stdout) # and so does the adapter banner + + def test_a_crash_keeps_the_diagnostics_and_the_banner(self): + lost = self.run_case(launcher(self.dir, 'noisy', 'noisy-die-at-0'), '--pass', 'a') + self.assertEqual(lost.returncode, 1) + self.assertIn('exited (code 3)', lost.stderr) + self.assertIn('renderer diagnostic 0', lost.stderr) + self.assertIn('partial output 0', lost.stdout) + self.assertTrue(lost.stdout.startswith('backend=warp debug_layer=enabled\nadapter=Fake\n')) + + def test_a_reply_with_the_wrong_case_number_fails_the_case(self): + lost = self.run_case(launcher(self.dir, 'skew', 'skew-at-1'), '--pass', 'a') + self.assertEqual(lost.returncode, 0) + lost = self.run_case(launcher(self.dir, 'skew', 'skew-at-1'), '--pass', 'b') + self.assertEqual(lost.returncode, 1) + self.assertIn('answered case', lost.stderr) + + def test_a_debug_warning_of_a_later_case_is_visible_to_the_check(self): + renderer = launcher(self.dir, 'fake', 'serve') + self.run_case(renderer, '--pass', 'a') + later = self.run_case(renderer, '--warn', 'b') + self.assertIn('debug_layer=enabled', later.stdout) # the check looks for the status in every case + self.assertIn('debug_errors=0 debug_warnings=1', later.stdout) + + def test_every_exit_leaves_no_process_and_no_open_pipe(self): + made = [] + real = R._Server + + def record(*args): + made.append(real(*args)) + return made[-1] + + with unittest.mock.patch.object(R, '_Server', record): + self.run_case(launcher(self.dir, 'old', 'no-serve'), '--pass', 'a') # failed handshake, then the one-shot call + self.run_case(launcher(self.dir, 'none', 'no-adapter'), '--pass', 'a') # skip 77 at the handshake + dies = launcher(self.dir, 'dies', 'die-at-1') + self.run_case(dies, '--pass', 'a') + self.run_case(dies, '--mismatch', 'b') # dead server: failed verdict + self.run_case(dies, '--pass', 'c') # next case, new server + R._close_all() # that server, at exit + self.assertEqual(len(made), 4) + for server in made: + self.assertIsNotNone(server.proc.poll()) + self.assertTrue(all(s.closed for s in (server.proc.stdin, server.proc.stdout, server.proc.stderr))) + + @unittest.skipUnless(os.name == 'posix', 'process groups') + def test_a_launcher_child_holding_the_pipes_does_not_block_the_end_of_the_test(self): + renderer = launcher(self.dir, 'grand', 'grandchild') + self.assertEqual(self.run_case(renderer, '--pass', 'a').returncode, 0) + pid = int((self.dir / 'grandchild.pid').read_text()) + started = time.monotonic() + R._close_all() # the renderer is gone but its child holds stdout and stderr + self.assertLess(time.monotonic() - started, 20) + for _ in range(50): # the child was killed with the group + if not running(pid): + break + time.sleep(0.1) + else: + self.fail('the launcher child is still alive') + + def test_x2w_flat_server_zero_uses_one_shot_calls(self): + renderer = launcher(self.dir, 'off', 'serve') + patch = unittest.mock.patch.object(R, 'SERVER_OFF', True) + patch.start() + self.addCleanup(patch.stop) + self.assertTrue(self.run_case(renderer, '--pass', 'a').stdout.startswith('ONESHOT ')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/hardware_adapter_filter_check.py b/tests/hardware_adapter_filter_check.py new file mode 100644 index 0000000000..2196c24f1d --- /dev/null +++ b/tests/hardware_adapter_filter_check.py @@ -0,0 +1,21 @@ +"""Check failure diagnostics for hardware adapter selectors in a GPU test executable.""" +import os +import subprocess +import sys + + +def check(args, env, allow_missing_factory=False): + missing = "x2w-no-such-hardware-adapter" + for selector, message in (("x" * 128, "XBOX2WINDOWS_ADAPTER is longer than 127 characters"), + (missing, f"No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER={missing}")): + run = subprocess.run(args, env=dict(env, XBOX2WINDOWS_ADAPTER=selector), capture_output=True, text=True) + if allow_missing_factory and selector == missing and run.returncode == 77: + return 77 + if run.returncode != 4 or message not in run.stderr: + raise RuntimeError(f"expected {message!r}, got exit {run.returncode}\n{run.stdout}{run.stderr}") + print("overlong and unmatched hardware adapter filters rejected") + return 0 + + +if __name__ == "__main__": + sys.exit(check(sys.argv[1:], os.environ)) diff --git a/tests/hardware_reports_check.py b/tests/hardware_reports_check.py index 1727eb5cca..baabffa4d9 100644 --- a/tests/hardware_reports_check.py +++ b/tests/hardware_reports_check.py @@ -45,7 +45,8 @@ def table_row(*cells): def report(adapter="Example GPU 100", device="1111", driver="1.0", backend="hardware", lanes=32, - lane_range="32..32", model="0x66", wave64="SKIP", tier=11, bvh="PASS", debug="unavailable"): + lane_range="32..32", model="0x66", wave64="SKIP", tier=11, bvh="PASS", debug="unavailable", + shaders=None): """Return a report in the layout that tools/gpu-check/Run-GpuCheck.ps1 writes.""" head = [f"backend={backend} debug_layer={debug}", f"adapter={adapter} vendor=10de device={device}", f"driver={driver}"] @@ -60,6 +61,14 @@ def report(adapter="Example GPU 100", device="1111", driver="1.0", backend="hard ("bvh_wave64", wave64, head + w64), ("bvh_differential", bvh, head + diff), ] + if shaders: + # The replayed shader cases are one section; the runner lists every case in its block. + verdict = "1 fail" if shaders == "FAIL" else "0 fail" + cases.append(("gfx2hlsl_shaders", shaders, [ + "translated compute shaders replayed from the package (compiler, case, result)", + f"cases: 2 pass, {verdict}, 0 skip of 2", + "dxc gfx2hlsl_compute/A PASS", + "dxc gfx2hlsl_compute/control-dropped-store " + ("FAIL: control not rejected: exit 0" if shaders == "FAIL" else "PASS: control rejected")])) lines = ["## Xbox2Windows GPU report", "", f"Source commit: {COMMIT}", "Windows build: 26100.1000", f"Backend: {backend}", "", "### Summary", "", f"- Adapter: {adapter} (vendor=10de device={device})", f"- Driver: {driver}", @@ -172,6 +181,18 @@ def test_matches_rows_by_device_and_the_software_adapter(self): row = hardware_reports.matching_row(only_report(body), rows) self.assertEqual(row.adapter if row else None, expected) + def test_replayed_shader_cases_are_one_section_that_can_fail(self): + """The shader section changes the pass and failure counts and nothing else in the report cells.""" + plain = hardware_reports.summarize([comment(410, report())], README) + passing = hardware_reports.summarize([comment(411, report(shaders="PASS"))], README) + failing = hardware_reports.summarize([comment(412, report(shaders="FAIL"))], README) + entry = lambda summary: summary["unrecorded"][0] + cells = lambda summary: {k: v for k, v in entry(summary)["cells"].items() if k != "evidence"} + self.assertEqual(entry(passing)["passed"], entry(plain)["passed"] + 1) + self.assertEqual(cells(passing), cells(plain)) + self.assertEqual(entry(failing)["failed"], ["gfx2hlsl_shaders"]) + self.assertEqual(cells(failing), cells(plain)) + def test_markdown_lists_failed_and_skipped_separately(self): """A skipped test is not a failed one, and both are named on the one Tests line. diff --git a/tests/hardware_reports_cli_check.py b/tests/hardware_reports_cli_check.py new file mode 100644 index 0000000000..5ec4655865 --- /dev/null +++ b/tests/hardware_reports_cli_check.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI validation, comment-ID guard, and mutation suite for tools/hardware_reports.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "hardware_reports.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) + +import hardware_reports as hr # noqa: E402 +from hardware_reports_check import README, comment, report # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = hr.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + encoding="utf-8", + env={**os.environ, "PYTHONIOENCODING": "utf-8"}, + timeout=30, + ) + + +class HardwareReportsCliPositiveTests(unittest.TestCase): + def test_markdown_json_after_filtering_and_boundary_id_zero(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + + c0 = comment(0, report(adapter="Example GPU 000", device="0001", driver="0.9")) + c101 = comment(101, report()) + c202 = comment(202, report(adapter="Example GPU 300", device="3333", driver="3.0")) + c205 = comment(205, report(adapter="Example GPU 400", device="4444", driver="4.0")) + + page1 = base / "page1.json" + page2 = base / "page2.json" + page1.write_text(json.dumps([c0, c101]), encoding="utf-8") + page2.write_text(json.dumps([c202]) + "\n" + json.dumps([c205]), encoding="utf-16") + + # 1) Markdown output across multiple comment files, including id=0. + code, out, err = _run_main([str(page1), str(page2), "--readme", str(readme)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("Read 4 comments. 4 reports use the generated layout; README.md links 1 of them.", out) + self.assertIn("## 1. Example GPU 000 (new row)", out) + self.assertIn("## 2. Example GPU 300 (new row)", out) + self.assertIn("## 3. Example GPU 400 (new row)", out) + + # 2) --json with --after 0 includes positive IDs (and excludes id=0). + code_a0, out_a0, err_a0 = _run_main( + [str(page1), str(page2), "--readme", str(readme), "--after", "0", "--json"] + ) + self.assertEqual(code_a0, 0, err_a0) + self.assertEqual(err_a0, "") + data_a0 = json.loads(out_a0) + self.assertEqual(data_a0["after"], 0) + self.assertEqual([item["comment_id"] for item in data_a0["unrecorded"]], [202, 205]) + + # 3) --json with --after 202 filters to > 202. + code_a202, out_a202, err_a202 = _run_main( + [str(page1), str(page2), "--readme", str(readme), "--after", "202", "--json"] + ) + self.assertEqual(code_a202, 0, err_a202) + data_a202 = json.loads(out_a202) + self.assertEqual(data_a202["after"], 202) + self.assertEqual([item["comment_id"] for item in data_a202["unrecorded"]], [205]) + + # 4) Subprocess end-to-end positive check. + proc = _run_subprocess(str(page1), str(page2), "--readme", str(readme), "--after", "202", "--json") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), data_a202) + + def test_sys_argv_and_script_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + comments_file = base / "comments.json" + comments_file.write_text( + json.dumps([comment(202, report(adapter="Example GPU 300", device="3333", driver="3.0"))]), + encoding="utf-8", + ) + cli_argv = [str(TOOL), str(comments_file), "--readme", str(readme), "--json"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual([item["comment_id"] for item in json.loads(out)["unrecorded"]], [202]) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual([item["comment_id"] for item in json.loads(stdout.getvalue())["unrecorded"]], [202]) + + +class HardwareReportsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 2, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_upfront_paths_and_negative_after_rejected_before_reading(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + valid_comments = base / "valid.json" + valid_comments.write_text("[]", encoding="utf-8") + missing_comments = base / "missing.json" + missing_readme = base / "missing_readme.md" + a_dir = base / "a_dir" + a_dir.mkdir() + + with ( + mock.patch.object(hr, "load_comments", side_effect=AssertionError("load_comments called upfront")), + mock.patch.object(hr, "summarize", side_effect=AssertionError("summarize called upfront")), + ): + for label, argv, frag in ( + ("missing_comments", [str(missing_comments), "--readme", str(readme)], "comments file not found"), + ( + "second_missing_comments", + [str(valid_comments), str(missing_comments), "--readme", str(readme)], + "comments file not found", + ), + ("dir_comments", [str(a_dir), "--readme", str(readme)], "comments path is a directory"), + ( + "second_dir_comments", + [str(valid_comments), str(a_dir), "--readme", str(readme)], + "comments path is a directory", + ), + ("missing_readme", [str(valid_comments), "--readme", str(missing_readme)], "--readme file not found"), + ("dir_readme", [str(valid_comments), "--readme", str(a_dir)], "--readme path is a directory"), + ("neg_after_1", [str(valid_comments), "--readme", str(readme), "--after", "-1"], "non-negative"), + ("neg_after_99", [str(valid_comments), "--readme", str(readme), "--after", "-99"], "non-negative"), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=2, fragments=(frag,)) + + def test_load_comments_rejects_bool_negative_non_int_ids_and_bad_json(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + readme = base / "README.md" + readme.write_text(README, encoding="utf-8") + + for label, bad_id in ( + ("bool_true", True), + ("bool_false", False), + ("neg_one", -1), + ("neg_large", -100), + ("str_id", "101"), + ("float_id", 10.5), + ("none_id", None), + ): + with self.subTest(case=label, bad_id=bad_id): + bad_file = base / f"{label}.json" + bad_file.write_text( + json.dumps([{"id": bad_id, "body": "x"}]), + encoding="utf-8", + ) + with self.assertRaises(ValueError) as ctx: + hr.load_comments([bad_file]) + self.assertIn("non-negative integer id", str(ctx.exception)) + self._assert_clean_failure( + [str(bad_file), "--readme", str(readme)], + expected_code=2, + fragments=("non-negative integer id",), + ) + + # Missing body / non-dict item / malformed JSON / bad UTF-8 / bad README table. + missing_body = base / "missing_body.json" + missing_body.write_text(json.dumps([{"id": 1}]), encoding="utf-8") + self._assert_clean_failure( + [str(missing_body), "--readme", str(readme)], + expected_code=2, + fragments=("expected github issue comment objects",), + ) + + non_dict = base / "non_dict.json" + non_dict.write_text(json.dumps([123]), encoding="utf-8") + self._assert_clean_failure( + [str(non_dict), "--readme", str(readme)], + expected_code=2, + fragments=("expected github issue comment objects",), + ) + + malformed = base / "malformed.json" + malformed.write_text('[{"id": 1, "body": ', encoding="utf-8") + self._assert_clean_failure([str(malformed), "--readme", str(readme)], expected_code=2) + + bad_utf8 = base / "bad_utf8.json" + bad_utf8.write_bytes(b"\xff\xfe\x00") + self._assert_clean_failure([str(bad_utf8), "--readme", str(readme)], expected_code=2) + + valid_comments = base / "valid.json" + valid_comments.write_text("[]", encoding="utf-8") + bad_readme = base / "bad_readme.md" + bad_readme.write_text("# No coverage table here\n", encoding="utf-8") + self._assert_clean_failure( + [str(valid_comments), "--readme", str(bad_readme)], + expected_code=2, + fragments=("no hardware coverage table header",), + ) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + comments = base / "comments.json" + comments.write_text("[]", encoding="utf-8") + + for argv, frags in ( + ([], ("required",)), + ([str(comments), "--bogus-flag"], ("unrecognized",)), + ([str(comments), "--after", "not_int"], ("invalid",)), + ([str(comments), "--readme"], ("expected one argument",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/host_commit_unit_check.py b/tests/host_commit_unit_check.py new file mode 100644 index 0000000000..2de69aa701 --- /dev/null +++ b/tests/host_commit_unit_check.py @@ -0,0 +1,239 @@ +"""Pure-Python unit, boundary, mocked WinAPI, and temp-copy mutation suite for tools/host_commit.py.""" + +import ctypes +import importlib.util +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +from types import MappingProxyType +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +MODULE_PATH = ROOT / "tools" / "host_commit.py" +sys.path.insert(0, str(ROOT / "tools")) + +import host_commit # noqa: E402 + + +MUTATIONS = ( + ( + "drop_is_int_bool_guard", + " return isinstance(value, int) and not isinstance(value, bool)\n", + " return isinstance(value, int)\n", + ), + ( + "drop_used_pages_nonneg_guard", + " if not _is_int(used_pages) or used_pages < 0:\n", + " if False:\n", + ), + ( + "drop_snapshot_mapping_guard", + " if not isinstance(snapshot, Mapping):\n", + " if False:\n", + ), + ( + "drop_snapshot_field_validation", + " for key in _SNAPSHOT_KEYS:\n", + " for key in ():\n", + ), + ( + "drop_free_bytes_clamp", + " free_bytes = max(limit_bytes - used_bytes, 0)\n", + " free_bytes = limit_bytes - used_bytes\n", + ), + ( + "drop_winmode_800", + ' psapi = C.WinDLL("psapi.dll", winmode=0x800, use_last_error=True)\n', + ' psapi = C.WinDLL("psapi.dll", use_last_error=True)\n', + ), +) + + +class _FakeGetPerformanceInfo: + def __init__(self, *, limit=1024, used=256, page_size=65536, success=True): + self.limit = limit + self.used = used + self.page_size = page_size + self.success = success + self.argtypes = None + self.restype = None + self.calls = [] + + def __call__(self, ptr, cb_size, struct_cls): + info = ctypes.cast(ptr, ctypes.POINTER(struct_cls)).contents + self.calls.append((info.cb, cb_size)) + if self.success: + info.CommitLimit = self.limit + info.CommitTotal = self.used + info.PageSize = self.page_size + return int(self.success) + + +def _load_temp_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise AssertionError(f"could not create module spec for {path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + try: + spec.loader.exec_module(mod) + except Exception: + sys.modules.pop(name, None) + raise + return mod + + +class HostCommitUnitTests(unittest.TestCase): + def _verify_module_contract(self, mod) -> None: + mib = mod.MIB + self.assertEqual(mib, 1 << 20) + + # Exact MiB math and 0-used floor. + self.assertEqual( + mod.snapshot_from_pages(64, 0, mib), + {"limit_mib": 64, "used_mib": 0, "available_mib": 64, "available_bytes": 64 * mib}, + ) + self.assertEqual( + mod.snapshot_from_pages(256, 128, 4096), + {"limit_mib": 1, "used_mib": 0, "available_mib": 0, "available_bytes": 128 * 4096}, + ) + self.assertEqual( + mod.snapshot_from_pages(100, 100, 65536), + {"limit_mib": (100 * 65536) // mib, "used_mib": (100 * 65536) // mib, + "available_mib": 0, "available_bytes": 0}, + ) + + # Clamping when used_pages > limit_pages. + clamped = mod.snapshot_from_pages(2, 5, mib) + self.assertEqual( + clamped, + {"limit_mib": 2, "used_mib": 5, "available_mib": 0, "available_bytes": 0}, + ) + + # Bool / non-int / negative / zero refusals in snapshot_from_pages. + for bad_args in ( + (True, 0, 4096), + (False, 0, 4096), + (10, True, 4096), + (10, False, 4096), + (10, 0, True), + (10, 0, False), + (0, 0, 4096), + (-1, 0, 4096), + (10, 0, 0), + (10, 0, -4096), + (10, -1, 4096), + ("10", 0, 4096), + (10.0, 0, 4096), + (10, 0.5, 4096), + (10, 0, 4096.0), + (None, 0, 4096), + ): + with self.assertRaises(ValueError, msg=f"args={bad_args!r}"): + mod.snapshot_from_pages(*bad_args) + + # Budget boundary checks (exact pass, 1-byte-short fail, max cap). + snap = mod.snapshot_from_pages(10, 4, mib) + self.assertEqual( + mod.require_commit_budget(6, snap), + {"limit_mib": 10, "used_mib": 4, "available_mib": 6, + "minimum_mib": 6, "meets_minimum": True}, + ) + self.assertEqual(mod.require_commit_budget(0, MappingProxyType(snap))["meets_minimum"], True) + + one_short = dict(snap, available_bytes=6 * mib - 1) + with self.assertRaises(ValueError): + mod.require_commit_budget(6, one_short) + + huge = mod.snapshot_from_pages((1 << 20) + 1, 0, mib) + self.assertEqual(mod.require_commit_budget(1 << 20, huge)["minimum_mib"], 1 << 20) + with self.assertRaises(ValueError): + mod.require_commit_budget((1 << 20) + 1, huge) + + # Reject bool/non-int/out-of-range minimum_mib. + for bad_min in (True, False, -1, (1 << 20) + 1, "6", 6.0, None): + with self.assertRaises(ValueError, msg=f"minimum_mib={bad_min!r}"): + mod.require_commit_budget(bad_min, snap) + + # Reject non-Mapping snapshot, missing keys, and bool/non-int/negative fields. + for bad_snap in (None, [], (), "snapshot", 42, [0, 0, 0, 0]): + with self.assertRaises(ValueError, msg=f"snapshot={bad_snap!r}"): + mod.require_commit_budget(0, bad_snap) + + required = ("available_bytes", "limit_mib", "used_mib", "available_mib") + for missing_key in required: + partial = {k: v for k, v in snap.items() if k != missing_key} + with self.assertRaises(ValueError, msg=f"missing={missing_key}"): + mod.require_commit_budget(0, partial) + + for key in required: + for bad_val in (True, False, -1, "1", 1.5, None): + bad_row = dict(snap) + bad_row[key] = bad_val + with self.assertRaises(ValueError, msg=f"{key}={bad_val!r}"): + mod.require_commit_budget(0, bad_row) + + # Mocked read_host_commit success, GetPerformanceInfo==0, and non-win32 OSError. + fake = _FakeGetPerformanceInfo(limit=512, used=128, page_size=65536, success=True) + + def call_success(ptr, cb_size): + return fake(ptr, cb_size, mod.PerformanceInformation) + + with patch.object(mod.sys, "platform", "win32"), \ + patch.object(mod.C, "WinDLL", create=True) as win_dll: + win_dll.return_value.GetPerformanceInfo = call_success + got = mod.read_host_commit() + win_dll.assert_called_once_with("psapi.dll", winmode=0x800, use_last_error=True) + expected_cb = ctypes.sizeof(mod.PerformanceInformation) + self.assertEqual(fake.calls, [(expected_cb, expected_cb)]) + self.assertEqual( + got, + {"limit_mib": (512 * 65536) // mib, "used_mib": (128 * 65536) // mib, + "available_mib": (384 * 65536) // mib, "available_bytes": 384 * 65536}, + ) + + fake_fail = _FakeGetPerformanceInfo(success=False) + + def call_fail(ptr, cb_size): + return fake_fail(ptr, cb_size, mod.PerformanceInformation) + + with patch.object(mod.sys, "platform", "win32"), \ + patch.object(mod.C, "WinDLL", create=True) as win_dll, \ + patch.object(mod.C, "get_last_error", create=True, return_value=87): + win_dll.return_value.GetPerformanceInfo = call_fail + with self.assertRaises(OSError) as raised: + mod.read_host_commit() + self.assertEqual(raised.exception.errno, 87) + + for non_win in ("linux", "darwin"): + with patch.object(mod.sys, "platform", non_win): + with self.assertRaises(OSError): + mod.read_host_commit() + + def test_contract_and_boundaries(self) -> None: + self._verify_module_contract(host_commit) + + def test_fast_temp_copy_mutations(self) -> None: + source = MODULE_PATH.read_text(encoding="utf-8") + with TemporaryDirectory() as tmp: + tmp_dir = Path(tmp) + for label, target, replacement in MUTATIONS: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mut_path = tmp_dir / f"host_commit_{label}.py" + mut_path.write_text(source.replace(target, replacement, 1), encoding="utf-8") + mod_name = f"host_commit_mut_{label}" + mod = _load_temp_module(mut_path, mod_name) + try: + with self.assertRaises( + (AssertionError, AttributeError, KeyError, TypeError), + msg=f"mutation {label} escaped detection", + ): + self._verify_module_contract(mod) + finally: + sys.modules.pop(mod_name, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/import_routing_check.py b/tests/import_routing_check.py new file mode 100644 index 0000000000..c945f8b35a --- /dev/null +++ b/tests/import_routing_check.py @@ -0,0 +1,245 @@ +"""Unit, boundary-validation, and temp-copy mutation suite for tools/import_routing.py.""" + +from collections import UserDict +import importlib.util +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +from types import MappingProxyType +import unittest + +ROOT = Path(__file__).resolve().parents[1] +MODULE_PATH = ROOT / "tools" / "import_routing.py" +sys.path.insert(0, str(ROOT / "tools")) + +import import_routing # noqa: E402 + + +MUTATIONS = ( + ( + "drop_non_str_guard", + ' if not isinstance(module, str):\n' + ' raise ValueError(f"module name must be a str, got {type(module).__name__}")\n', + ' if False:\n' + ' raise ValueError(f"module name must be a str, got {type(module).__name__}")\n', + ), + ( + "drop_empty_whitespace_control_guard", + ' if not module or any(ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in module):\n' + ' raise ValueError(f"invalid module name: {module!r}")\n', + ' if False:\n' + ' raise ValueError(f"invalid module name: {module!r}")\n', + ), + ( + "drop_mutable_mapping_guard", + ' if not isinstance(row, MutableMapping):\n' + ' raise TypeError(f"row must be a MutableMapping, got {type(row).__name__}")\n', + ' if False:\n' + ' raise TypeError(f"row must be a MutableMapping, got {type(row).__name__}")\n', + ), + ( + "drop_lower_normalization", + " name = module.lower()\n", + " name = module\n", + ), + ( + "substring_api_set_prefix", + " if name.startswith(prefix):\n", + " if prefix in name:\n", + ), + ( + "lowercase_candidate_provider", + ' "candidate_provider": module if route == "hle" else None,\n', + ' "candidate_provider": module.lower() if route == "hle" else None,\n', + ), +) + + +def _load_temp_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise AssertionError(f"could not create module spec for {path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + try: + spec.loader.exec_module(mod) + except Exception: + sys.modules.pop(name, None) + raise + return mod + + +class ImportRoutingTests(unittest.TestCase): + def _verify_module_contract(self, mod) -> None: + self.assertEqual(mod.POLICY_VERSION, 2) + self.assertEqual(mod.ROUTE_KIND, "candidate") + self.assertEqual(mod.RESOLUTION, "not_checked") + self.assertEqual(mod.ROUTES, ("hle", "windows", "stub", "unsupported")) + + # All 4 policy routes and mixed-case normalization. + for name, expected_route in ( + ("xmem.dll", "hle"), + ("XMem.DLL", "hle"), + ("d3d12_xs.dll", "hle"), + ("D3D12_Xs.Dll", "hle"), + ("xgameruntime.dll", "stub"), + ("XGameRuntime.DLL", "stub"), + ("xg_xs.dll", "stub"), + ("XG_XS.dll", "stub"), + ("kernel32.dll", "windows"), + ("Kernel32.DLL", "windows"), + ("ntdll.dll", "windows"), + ("xaudio2_8.dll", "windows"), + ("XAudio2_9.DLL", "windows"), + ("gameinput.dll", "windows"), + ("mystery.dll", "unsupported"), + ("Mystery.DLL", "unsupported"), + ("winhttp2.dll", "unsupported"), + ("my-api-ms-win-core.dll", "unsupported"), + ("not-ext-ms-core.dll", "unsupported"), + ): + route, reason = mod.classify(name) + self.assertEqual(route, expected_route, name) + self.assertIsInstance(reason, str) + self.assertTrue(reason) + + # Prefix routes preserve contract reason across mixed case. + for prefix_name in ( + "api-ms-win-core-file-l1-1-0.dll", + "API-MS-WIN-CORE-SYNCH-L1-2-0.DLL", + "ext-ms-win-ntuser-window-l1-1-0.dll", + "EXT-MS-ONECORE-TEST-L1-1-0.DLL", + ): + self.assertEqual( + mod.classify(prefix_name), + ("windows", "Windows API-set contract"), + prefix_name, + ) + + # Invalid module names must raise ValueError (never AttributeError or 'unsupported'). + for bad_module in ( + None, + 123, + True, + b"xmem.dll", + bytearray(b"xmem.dll"), + ["xmem.dll"], + {"module": "xmem.dll"}, + "", + " ", + "\t\n\r", + "\u00a0", + " xmem.dll", + "xmem.dll ", + "x mem.dll", + "kernel32\t.dll", + "\x00", + "xmem\x00.dll", + "xmem\x1f.dll", + "xmem\x7f.dll", + "xmem\x85.dll", + "xmem\x9f.dll", + ): + with self.assertRaises(ValueError, msg=f"module={bad_module!r}"): + mod.classify(bad_module) + + # annotate() requires a MutableMapping containing module_key before mutating. + for bad_row, key in ( + (None, "module"), + (123, "module"), + ("xmem.dll", "module"), + (["xmem.dll"], 0), + (("xmem.dll",), 0), + (MappingProxyType({"module": "xmem.dll"}), "module"), + ): + with self.assertRaises(TypeError, msg=f"row={bad_row!r}"): + mod.annotate(bad_row, module_key=key) + + missing_row = {"dll": "xmem.dll", "caller": "app.exe"} + with self.assertRaises(KeyError): + mod.annotate(missing_row) + self.assertEqual(missing_row, {"dll": "xmem.dll", "caller": "app.exe"}) + + for invalid_val in ("", None, " bad.dll", "bad\x00.dll"): + untouched = {"module": invalid_val, "caller": "app.exe", "symbol": "Sym"} + snapshot = dict(untouched) + with self.assertRaises(ValueError): + mod.annotate(untouched) + self.assertEqual(untouched, snapshot) + + # annotate() preserves caller keys, return schema, and original casing for HLE candidate_provider. + hle_row = {"image": "app.exe", "kind": "normal", "dll": "XMem.DLL", "symbol": "XMemAlloc", "extra": 42} + ret = mod.annotate(hle_row, module_key="dll") + self.assertIs(ret, hle_row) + self.assertEqual( + hle_row, + { + "image": "app.exe", + "kind": "normal", + "dll": "XMem.DLL", + "symbol": "XMemAlloc", + "extra": 42, + "route": "hle", + "reason": mod.POLICY["hle"]["xmem.dll"], + "route_kind": mod.ROUTE_KIND, + "resolution": mod.RESOLUTION, + "provider": None, + "stub": False, + "candidate_provider": "XMem.DLL", + }, + ) + + stub_row = UserDict({"module": "XGameRuntime.DLL", "symbol": "XUserGetId"}) + ret_stub = mod.annotate(stub_row) + self.assertIs(ret_stub, stub_row) + self.assertEqual(stub_row["route"], "stub") + self.assertTrue(stub_row["stub"]) + self.assertIsNone(stub_row["candidate_provider"]) + self.assertIsNone(stub_row["provider"]) + self.assertEqual(stub_row["symbol"], "XUserGetId") + + win_row = {"module": "API-MS-WIN-CORE-FILE-L1-1-0.DLL", "caller": "app.exe"} + mod.annotate(win_row) + self.assertEqual(win_row["route"], "windows") + self.assertFalse(win_row["stub"]) + self.assertIsNone(win_row["candidate_provider"]) + + unsup_row = {"module": "Mystery.DLL", "caller": "app.exe"} + mod.annotate(unsup_row) + self.assertEqual(unsup_row["route"], "unsupported") + self.assertFalse(unsup_row["stub"]) + self.assertIsNone(unsup_row["candidate_provider"]) + + def test_contract_and_policy_coverage(self) -> None: + self._verify_module_contract(import_routing) + + for mod_name, reason in import_routing.POLICY["hle"].items(): + self.assertEqual(import_routing.classify(mod_name), ("hle", reason)) + for mod_name, reason in import_routing.POLICY["stub"].items(): + self.assertEqual(import_routing.classify(mod_name), ("stub", reason)) + for mod_name in import_routing.POLICY["windows"]: + self.assertEqual(import_routing.classify(mod_name), ("windows", "Windows system DLL")) + + def test_fast_temp_copy_mutations(self) -> None: + source = MODULE_PATH.read_text(encoding="utf-8") + with TemporaryDirectory() as tmp: + tmp_dir = Path(tmp) + for label, target, replacement in MUTATIONS: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mut_path = tmp_dir / f"import_routing_{label}.py" + mut_path.write_text(source.replace(target, replacement, 1), encoding="utf-8") + mod_name = f"import_routing_mut_{label}" + mod = _load_temp_module(mut_path, mod_name) + try: + with self.assertRaises( + (AssertionError, AttributeError, KeyError, TypeError), + msg=f"mutation {label} escaped detection", + ): + self._verify_module_contract(mod) + finally: + sys.modules.pop(mod_name, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/intake_exe_cli_check.py b/tests/intake_exe_cli_check.py new file mode 100644 index 0000000000..0f97c248d6 --- /dev/null +++ b/tests/intake_exe_cli_check.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI validation, atomic-report, and mutation suite for tools/intake_exe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_DIR / "intake_exe.py" +sys.path.insert(0, str(TOOLS_DIR)) +sys.path.insert(0, str(TESTS_DIR)) + +import intake_exe # noqa: E402 +from intake_exe_check import _build_pe, _fake_scan_for, _synthetic_package # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = intake_exe.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class IntakeExeCliPositiveTests(unittest.TestCase): + def test_inspected_awaiting_error_json_and_require_routing_with_zero_tmp(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + + # 1) awaiting_executable -> exit 3, 0 .tmp files. + pkg_wait, base_w, int_w = _synthetic_package(base / "wait", write_candidate=False) + rep_wait = base / "wait" / "nested" / "reports" + code_w, out_w, err_w = _run_main([ + "--build", str(pkg_wait), + "--baseline", str(base_w), + "--integrity", str(int_w), + "--reports", str(rep_wait), + ]) + self.assertIs(type(code_w), int) + self.assertEqual(code_w, 3, (out_w, err_w)) + self.assertEqual(err_w, "") + self.assertIn("awaiting_executable |", out_w) + wait_files = list(rep_wait.iterdir()) + self.assertEqual(len(wait_files), 1) + self.assertTrue(wait_files[0].name.endswith(".awaiting_executable.json")) + self.assertEqual(json.loads(wait_files[0].read_text(encoding="utf-8"))["status"], "awaiting_executable") + + # 2) inspected with explicit PE candidate -> exit 0, 0 .tmp files. + pe_ok = _build_pe(imports=[("normal", "xmem.dll", "XMemAlloc")]) + pkg_ok, base_ok, int_ok = _synthetic_package(base / "ok", write_candidate=False) + cand_ok = base / "ok" / "candidate.exe" + cand_ok.write_bytes(pe_ok) + rep_ok = base / "ok" / "reports" + with mock.patch.object(intake_exe, "scan", _fake_scan_for(pkg_ok, pe_ok)): + code_ok, out_ok, err_ok = _run_main([ + str(cand_ok), + "--build", str(pkg_ok), + "--baseline", str(base_ok), + "--integrity", str(int_ok), + "--reports", str(rep_ok), + "--require-routing", + ]) + self.assertEqual(code_ok, 0, (out_ok, err_ok)) + self.assertEqual(err_ok, "") + self.assertIn("inspected |", out_ok) + ok_files = list(rep_ok.iterdir()) + self.assertEqual(len(ok_files), 1) + self.assertTrue(ok_files[0].name.endswith(".inspected.json")) + ok_payload = json.loads(ok_files[0].read_text(encoding="utf-8")) + self.assertEqual(ok_payload["status"], "inspected") + self.assertEqual(ok_payload["pe"]["machine"], "AMD64") + + # 3) --require-routing failure -> exit 1, stderr names unsupported import, JSON written w/ 0 .tmp. + pe_bad_route = _build_pe( + imports=[("normal", "xmem.dll", "XMemAlloc"), ("normal", "mystery.dll", "MissingExport")] + ) + cand_bad = base / "ok" / "bad_route.exe" + cand_bad.write_bytes(pe_bad_route) + rep_route = base / "ok" / "reports_route" + with mock.patch.object(intake_exe, "scan", _fake_scan_for(pkg_ok, pe_bad_route)): + code_rt, out_rt, err_rt = _run_main([ + str(cand_bad), + "--build", str(pkg_ok), + "--baseline", str(base_ok), + "--integrity", str(int_ok), + "--reports", str(rep_route), + "--require-routing", + ]) + self.assertEqual(code_rt, 1, (out_rt, err_rt)) + self.assertIn("unsupported: main.exe -> mystery.dll!MissingExport", err_rt) + self.assertIn("inspected |", out_rt) + rt_files = list(rep_route.iterdir()) + self.assertEqual(len(rt_files), 1) + self.assertTrue(rt_files[0].name.endswith(".inspected.json")) + + # 4) error JSON (malformed MicrosoftGame.Config) -> exit 2, 0 .tmp files. + (pkg_ok / "MicrosoftGame.Config").write_text("<broken", encoding="utf-8") + rep_err = base / "ok" / "reports_err" + code_err, out_err, err_err = _run_main([ + "--build", str(pkg_ok), + "--baseline", str(base_ok), + "--integrity", str(int_ok), + "--reports", str(rep_err), + ]) + self.assertEqual(code_err, 2, (out_err, err_err)) + self.assertNotIn("Traceback", err_err) + self.assertIn("error |", out_err) + err_files = list(rep_err.iterdir()) + self.assertEqual(len(err_files), 1) + self.assertTrue(err_files[0].name.endswith(".error.json")) + self.assertEqual(json.loads(err_files[0].read_text(encoding="utf-8"))["status"], "error") + + def test_sys_argv_and_script_entrypoint_and_subprocess(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "entry", write_candidate=False) + rep = base / "entry" / "reports" + cli_argv = [ + str(TOOL), + "--build", str(pkg), + "--baseline", str(baseline), + "--integrity", str(integrity), + "--reports", str(rep), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 3, (out, err)) + self.assertEqual(err, "") + self.assertIn("awaiting_executable |", out) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 3) + self.assertEqual(stderr.getvalue(), "") + self.assertIn("awaiting_executable |", stdout.getvalue()) + + proc = _run_subprocess(*cli_argv[1:]) + self.assertEqual(proc.returncode, 3, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("awaiting_executable |", proc.stdout) + + +class IntakeExeCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_upfront_build_candidate_baseline_integrity_guards_before_collect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "pkg", write_candidate=False) + rep_absent = base / "never_created_reports" + regular_file = base / "regular.txt" + regular_file.write_text("keep", encoding="utf-8") + a_dir = base / "a_dir" + a_dir.mkdir() + missing = base / "missing.json" + + with mock.patch.object(intake_exe, "collect", side_effect=AssertionError("collect called upfront")): + for label, argv, frag in ( + ("missing_build", ["--build", str(base / "no_pkg"), "--reports", str(rep_absent)], "directory not found"), + ("file_build", ["--build", str(regular_file), "--reports", str(rep_absent)], "not a directory"), + ( + "dir_candidate", + [str(a_dir), "--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_absent)], + "candidate path is not a regular file", + ), + ( + "missing_baseline", + ["--build", str(pkg), "--baseline", str(missing), "--integrity", str(integrity), "--reports", str(rep_absent)], + "--baseline file not found", + ), + ( + "dir_baseline", + ["--build", str(pkg), "--baseline", str(a_dir), "--integrity", str(integrity), "--reports", str(rep_absent)], + "--baseline path is a directory", + ), + ( + "missing_integrity", + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(missing), "--reports", str(rep_absent)], + "--integrity file not found", + ), + ( + "dir_integrity", + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(a_dir), "--reports", str(rep_absent)], + "--integrity path is a directory", + ), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=(frag,)) + + self.assertFalse(rep_absent.exists()) + self.assertEqual(regular_file.read_text(encoding="utf-8"), "keep") + + def test_reports_file_symlink_parent_file_and_inside_build_rejected_before_collect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "pkg", write_candidate=False) + rep_file = base / "rep_file.txt" + rep_file.write_text("keep-rep", encoding="utf-8") + real_dir = base / "real_dir" + real_dir.mkdir() + symlink_rep = base / "symlink_rep" + + try: + symlink_rep.symlink_to(real_dir, target_is_directory=True) + has_symlinks = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + has_symlinks = False + + with mock.patch.object(intake_exe, "collect", side_effect=AssertionError("collect called for bad --reports")): + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_file)], + expected_code=1, + fragments=("failed to write report", "regular file"), + ) + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_file / "sub" / "out")], + expected_code=1, + fragments=("failed to write report", "not a directory"), + ) + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(pkg / "inside")], + expected_code=2, + fragments=("outside game files",), + ) + if has_symlinks: + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(symlink_rep)], + expected_code=1, + fragments=("failed to write report", "symlink"), + ) + else: + with mock.patch.object(Path, "is_symlink", autospec=True, side_effect=lambda p: p == real_dir): + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(real_dir)], + expected_code=1, + fragments=("failed to write report", "symlink"), + check_subprocess=False, + ) + self.assertEqual(rep_file.read_text(encoding="utf-8"), "keep-rep") + self.assertEqual(list(real_dir.iterdir()), []) + + def test_report_replace_failure_leaves_zero_tmp_files(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg, baseline, integrity = _synthetic_package(base / "pkg", write_candidate=False) + rep_dir = base / "rep_dir" + rep_dir.mkdir() + (rep_dir / "existing.txt").write_text("keep", encoding="utf-8") + + with mock.patch.object(intake_exe.os, "replace", side_effect=OSError("simulated replace fail")): + self._assert_clean_failure( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(rep_dir)], + expected_code=1, + fragments=("failed to write report", "simulated replace fail"), + check_subprocess=False, + ) + self.assertEqual([p.name for p in rep_dir.iterdir()], ["existing.txt"]) + + def test_argparse_errors_py314_safe(self) -> None: + for argv, frags in ( + (["--bogus-flag"], ("unrecognized",)), + (["--build"], ("expected one argument",)), + (["--baseline"], ("expected one argument",)), + (["--integrity"], ("expected one argument",)), + (["--reports"], ("expected one argument",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index a735c1ef8d..cadc63aace 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -345,7 +345,7 @@ struct Pool { write(previous.cpu, 0, D, alloc_pages * page / 4); return release(previous); } - bool map(Memory& out, unsigned pages) + bool map(Memory& out, unsigned pages, bool split_last_page = false) { out.cpu = base + cursor; if (cursor + pages * page > bytes) return false; @@ -353,8 +353,14 @@ struct Pool { if (!xmem) return true; out.tokens.assign(pages, 0); ULONG_PTR got = pages; - return XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) && got == pages && - XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + if (!XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) || got != pages) return false; + if (!split_last_page) return XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + + // Map the upper page first so that, with X2W_XMEM_JOIN_CALLS=1, neither call can join across the boundary + // inside the buffer. + auto* const last_page = out.cpu + (pages - 1) * page; + return XMemMapPhysicalPages(last_page, 1, &out.tokens.back()) == last_page && + XMemMapPhysicalPages(out.cpu, pages - 1, out.tokens.data()) == out.cpu; } // One allocation in the case layout: neighbour pages, then the buffer filled with `fill`. bool allocate(Memory& out, Tag fill, bool* zero = nullptr) @@ -370,11 +376,7 @@ struct Pool { // Two pages of the buffer in two mapping calls (two views): the buffer crosses a view boundary. bool allocate_split(Memory& out, Tag fill) { - Memory first, second; - if (!xmem || !map(first, alloc_pages - 1) || !map(second, 1)) return false; - out.cpu = first.cpu; - out.tokens = first.tokens; - out.tokens.insert(out.tokens.end(), second.tokens.begin(), second.tokens.end()); + if (!xmem || !map(out, alloc_pages, true)) return false; write(out.cpu, 0, neighbour, buffer_offset / 4); write(out.buffer(), 0, fill, buffer_bytes / 4); return true; @@ -1766,6 +1768,7 @@ int main(int argc, char** argv) SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", nullptr); // no joins across mapping calls (the default) SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention || path == Path::lease ? L"copy" : L"1"); diff --git a/tests/mesh_bitcmp_check.py b/tests/mesh_bitcmp_check.py new file mode 100644 index 0000000000..cd3a8b7deb --- /dev/null +++ b/tests/mesh_bitcmp_check.py @@ -0,0 +1,357 @@ +"""Check s_bitcmp0/1_b32 and s_bitcmp0/1_b64 in the bounded mesh lowerers (#2413).""" + +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / "tools")) +sys.path.insert(0, str(HERE)) + +from disasm_rdna2 import decode_instruction +from mesh_dynamic_aot import Geometry, RuntimeWave, enumerate_variants +from mesh_dynamic_aot import lower as lower_dynamic +from mesh_dynamic_aot_check import insert_scalar +from mesh_dynamic_geometry_check import CODE, MESH_LIMITS, SECOND, decode +from mesh_entry_aot import UNDEF, U32, WAVE, Wave +from mesh_entry_aot import lower as lower_static +from mesh_entry_check import PROGRAM, TRIANGLE, draw, enumerate_pcs + + +SOPC_CASES = ( + ("s_bitcmp0_b32 s15, 0", bytes.fromhex("0f800cbf")), + ("s_bitcmp1_b32 s15, 12", bytes.fromhex("0f8c0dbf")), + ("s_bitcmp0_b64 exec, 37", bytes.fromhex("7ea50ebf")), + ("s_bitcmp1_b64 s[4:5], s6", bytes.fromhex("04060fbf")), + ("s_bitcmp0_b32 s15, 0xffffffe5", bytes.fromhex("0fff0cbfe5ffffff")), + ("s_bitcmp1_b64 s[4:5], 0x45", bytes.fromhex("04ff0fbf45000000")), +) + +WORDS_32 = (0x00000000, 0xFFFFFFFF, 0x80000001, 0x00010020, 0x55555555, 0xAAAAAAAA, 0x0000001F, 0x00000020) +INDEXES_32 = (0, 1, 5, 16, 31, 32, 33, 37, 0xFFFFFFE5) +WORDS_64 = ( + 0x00000000_00000000, + 0xFFFFFFFF_FFFFFFFF, + 0x00000001_00000000, + 0x80000020_00010001, + 0xAAAAAAAA_55555555, + 0x00000000_00000001, +) +INDEXES_64 = (0, 1, 31, 32, 37, 63, 64, 65, 101, 0xFFFFFFC5) + +POINT, MATRIX = "0x60", "0x80" + + +def expect_error(fn, message): + try: + fn() + except ValueError as error: + assert message in str(error), f"Expected {message!r}, got {error!r}" + return + raise AssertionError(f"Expected refusal: {message}") + + +def check_wave_model(): + for op, want in (("s_bitcmp0_b32", 0), ("s_bitcmp1_b32", 1)): + for word in WORDS_32: + for idx in INDEXES_32: + expected = (((word & U32) >> (idx & 31)) & 1) == want + wave = Wave(0, []) + wave.s[4] = word + wave.s[6] = idx + wave.written.update((4, 6)) + wave.scalar_op(op, ["s4", str(idx) if 0 <= idx <= 64 else hex(idx)]) + assert wave.scc is expected and wave.s[4] == word + wave.scc = None + wave.scalar_op(op, ["s4", "s6"]) + assert wave.scc is expected and wave.s[4] == word and wave.s[6] == idx + + for op, want in (("s_bitcmp0_b64", 0), ("s_bitcmp1_b64", 1)): + for word in WORDS_64: + for idx in INDEXES_64: + expected = (((word & WAVE) >> (idx & 63)) & 1) == want + wave = Wave(0, []) + wave.s[4] = word & U32 + wave.s[5] = (word >> 32) & U32 + wave.s[6] = idx + wave.exec = word + wave.vcc = word ^ WAVE + wave.written.update((4, 5, 6)) + wave.scalar_op(op, ["s[4:5]", "s6"]) + assert wave.scc is expected + wave.scalar_op(op, ["exec", "s6"]) + assert wave.scc is expected + wave.scalar_op(op, ["vcc", "s6"]) + assert wave.scc is (not expected) + if 0 <= idx <= 64: + wave.scalar_op(op, ["s[4:5]", str(idx)]) + assert wave.scc is expected + + # Inline -1 sign-extends to all 64 bits. + wave = Wave(0, []) + wave.scalar_op(op, ["-1", "37"]) + assert wave.scc is (want == 1) + + +def check_decode_and_specialization(): + for expected_asm, raw in SOPC_CASES: + size, op, asm, _ = decode_instruction(raw, 0) + assert (size, asm) == (len(raw), expected_asm), (size, op, asm) + + # Guard wave 0 in static PROGRAM using s_bitcmp0_b32 s3, 24 and 64-bit high-bit s_bitcmp1_b64 exec, 37. + base_decoded = enumerate_pcs(PROGRAM) + assert lower_static(concrete_wave_program(), [0x1003], (3, 1)) == lower_static(base_decoded, [0x1003], (3, 1)) + + # Flipping s_bitcmp0_b32 -> s_bitcmp1_b32 makes wave 1 run alloc instead of wave 0 and fails Unverified allocation. + wrong = [ + (pc, line.replace("s_bitcmp0_b32 s3, 24", "s_bitcmp1_b32 s3, 24")) + for pc, line in concrete_wave_program() + ] + expect_error(lambda: lower_static(wrong, [0x1003], (3, 1)), "Unverified allocation") + + # Also prove 64-bit exec high bit test on entry EXEC = 0xFFFFFFFFFFFFFFFF. + exec_guarded = enumerate_pcs( + PROGRAM[:2] + ["s_bitcmp1_b64 exec, 37", "s_cbranch_scc0 0"] + PROGRAM[2:] + ) + assert lower_static(exec_guarded, [0x1003], (3, 1)) == lower_static(base_decoded, [0x1003], (3, 1)) + + # Splice a concrete bit-compare sequence into CODE after s_sendmsg (outside the skip branch). + body = decode(CODE) + after_alloc = next(pc for pc, op in body if op.startswith("s_sendmsg ")) + extra = decode(bytes.fromhex("0f8c0dbf") + bytes.fromhex("7ea50ebf")) + assert [line for _, line in extra] == ["s_bitcmp1_b32 s15, 12", "s_bitcmp0_b64 exec, 37"] + spliced = insert_scalar(body, after_alloc, ["s_bitcmp1_b32 s15, 12", "s_bitcmp0_b64 exec, 37"]) + # Adding a pure compare before an instruction that doesn't read SCC preserves dynamic variants and HLSL. + assert enumerate_variants(spliced, 2, MESH_LIMITS) == enumerate_variants(body, 2, MESH_LIMITS) + assert lower_dynamic(spliced, 2, MESH_LIMITS) == lower_dynamic(body, 2, MESH_LIMITS) + + +def concrete_wave_program(): + # Replace the inner allocation guard (`s_cbranch_execz 1` at PROGRAM[19]) with s_bitcmp0_b32 s3, 24 + # plus a 64-bit high-word bit test s_bitcmp1_b64 s[4:5], 37. + idx = PROGRAM.index("s_sendmsg sendmsg(MSG_GS_ALLOC_REQ)") + assert PROGRAM[idx - 1] == "s_cbranch_execz 1" + # Update outer s_cbranch_execz 2 (at idx - 4) to jump over our 4 instructions + s_sendmsg? No: outer branch + # is before s_mov s7/m0, so keep its skip target at idx - 1 and guard s_sendmsg cleanly. + lines = ( + PROGRAM[: idx - 1] + + [ + "s_mov_b32 s4, 0", + "s_mov_b32 s5, 0x20", + "s_bitcmp1_b64 s[4:5], 37", + "s_cbranch_scc0 3", + "s_bitcmp0_b32 s3, 24", + "s_cbranch_scc0 1", + ] + + PROGRAM[idx:] + ) + # Fix outer `s_cbranch_execz 2` (right before `s_mov_b32 s7, s15`) so wave 1 skips s_mov s7/m0 -> hits s_mov s4. + assert lines[idx - 4] == "s_cbranch_execz 2" + return enumerate_pcs(lines) + + +def join_program(bit_compare, branch_op, dynamic_bit=False): + """Splice a dynamic bit-compare + uniform if/else choosing POINT vs MATRIX into PROGRAM.""" + table_arm = lambda off: [f"s_load_dwordx4 s[36:39], s[10:11], {off}", "s_waitcnt lgkmcnt(0)"] + arm_true = table_arm(POINT) + arm_false = table_arm(MATRIX) + first = arm_true + [f"s_branch {len(arm_false)}"] + loads = [ + "s_buffer_load_dword s14, s[16:19], null", + *(["s_buffer_load_dword s13, s[16:19], 0x8"] if dynamic_bit else []), + "s_waitcnt lgkmcnt(0)", + bit_compare, + f"{branch_op} {len(first)}", + ] + lines = ( + PROGRAM[:7] + + loads + + first + + arm_false + + [ + "s_buffer_load_dword s30, s[36:39], 0x4", + "s_buffer_load_dword s31, s[20:23], 0xc", + "s_waitcnt lgkmcnt(0)", + ] + + PROGRAM[10:] + ) + return enumerate_pcs(lines) + + +def check_dynamic_joins(): + hlsl0 = lower_static(join_program("s_bitcmp0_b32 s14, 5", "s_cbranch_scc0"), [0x1003], (3, 1)) + assert "((asuint(pointData[0].x) & (1u << 5u)) == 0u)" in hlsl0, hlsl0 + + hlsl1 = lower_static(join_program("s_bitcmp1_b32 s14, 5", "s_cbranch_scc1"), [0x1003], (3, 1)) + assert "((asuint(pointData[0].x) & (1u << 5u)) != 0u) ? matrixData[0].y : pointData[0].y" in hlsl1, hlsl1 + + hlsl_dyn = lower_static(join_program("s_bitcmp1_b32 s14, s13", "s_cbranch_scc1", dynamic_bit=True), + [0x1003], (3, 1)) + assert "((asuint(pointData[0].x) & (1u << (asuint(pointData[0].z) & 31u))) != 0u) ? matrixData[0].y : pointData[0].y" in hlsl_dyn, hlsl_dyn + + +def check_refusals(): + # Unwritten SGPR must not be hidden by steps()'s written scan. + expect_error( + lambda: lower_static(enumerate_pcs(["s_bitcmp0_b32 s99, 0", "s_endpgm"]), [0x1003], (3, 1)), + "Scalar register s99 used before it is written", + ) + + # Skipped-range UNDEF scalar leaves SCC None; a dead compare passes, a branch consuming it refuses. + body = decode(CODE) + skipped = insert_scalar(body, 160, ["s_mov_b32 s32, 1"], skip_pc=156) + dead = insert_scalar(skipped, 172, ["s_bitcmp0_b32 s32, 5"]) + lower_dynamic(dead, 2, MESH_LIMITS) + consumed = insert_scalar(skipped, 172, ["s_bitcmp0_b32 s32, 5", "s_cbranch_scc0 0"]) + expect_error(lambda: lower_dynamic(consumed, 2, MESH_LIMITS), "Undefined branch predicate") + + # Pending scalar load before s_waitcnt lgkmcnt(0). + expect_error( + lambda: lower_static( + enumerate_pcs(PROGRAM[:7] + ["s_bitcmp0_b32 s15, 0", "s_endpgm"]), + [0x1003], + (3, 1), + ), + "Scalar load used before wait", + ) + + # Width and operand-shape refusals. + for line, msg in ( + ("s_bitcmp0_b64 s4, 37", "Expected a 64-bit scalar operand"), + ("s_bitcmp0_b64 exec_lo, 5", "Expected a 64-bit scalar operand"), + ("s_bitcmp0_b32 s[4:5], 5", "Expected a 32-bit scalar operand"), + ("s_bitcmp0_b32 exec, 5", "Expected a 32-bit scalar operand"), + ("s_bitcmp0_b32 s4, s[6:7]", "Expected a 32-bit bit-index operand"), + ("s_bitcmp0_b64 s[4:5], exec", "Expected a 32-bit bit-index operand"), + ("s_bitcmp0_b32 s4", "Expected two operands"), + ): + wave = Wave(0, []) + wave.s.update({4: 1, 5: 2, 6: 3, 7: 4}) + op, _, tail = line.partition(" ") + expect_error(lambda w=wave, o=op, a=tail.split(", "): w.scalar_op(o, a), msg) + + # 64-bit dynamic string operand refused. + wave = Wave(0, []) + wave.s.update({4: "pointData[0].x", 5: 0}) + expect_error(lambda: wave.scalar_op("s_bitcmp0_b64", ["s[4:5]", "5"]), "Scalar pair requires concrete words") + + # Unproven RuntimeWord in RuntimeWave refused. + rt = RuntimeWave(0, Geometry(2, ())) + rt.s[15] = rt.geometry[0] + expect_error(lambda: rt.scalar_op("s_bitcmp0_b32", ["s15", "0"]), "Unproven runtime geometry word") + + # Sampler-heap base/word in either operand refused in RuntimeWave. + rt_heap = RuntimeWave(0, Geometry(2, (), sampler_heap_sgpr=28)) + rt_heap.s[29] = 0 + rt_heap.descriptor_scalar_op("s_load_dwordx4", ["s[36:39]", "s[28:29]", "0x10"]) + rt_heap.pending.clear() + expect_error(lambda: rt_heap.scalar_op("s_bitcmp0_b32", ["s28", "0"]), "Sampler heap") + expect_error(lambda: rt_heap.scalar_op("s_bitcmp1_b32", ["s36", "0"]), "Sampler heap") + rt_heap.s[40] = 1 + expect_error(lambda: rt_heap.scalar_op("s_bitcmp1_b32", ["s40", "s36"]), "Sampler heap") + + +def check_controls(): + check_wave_model() + check_decode_and_specialization() + check_dynamic_joins() + check_refusals() + print("mesh s_bitcmp controls passed") + + +def check_binary(llvm_mc): + source = "\n".join(asm for asm, _ in SOPC_CASES) + "\n" + run = subprocess.run( + [llvm_mc, "-triple=amdgcn--", "-mcpu=gfx1013", "-mattr=-wavefrontsize32,+wavefrontsize64", "-show-encoding"], + input=source, + capture_output=True, + text=True, + check=True, + ) + encoded = bytearray() + for line in run.stdout.splitlines(): + m = re.search(r"encoding: \[([^\]]*)\]", line) + if m: + encoded += bytes(int(b, 16) for b in m.group(1).split(",")) + expected = b"".join(raw for _, raw in SOPC_CASES) + assert bytes(encoded) == expected, f"encoded {encoded.hex()} != {expected.hex()}" + pc = 0 + for expected_asm, raw in SOPC_CASES: + size, _, asm, _ = decode_instruction(encoded, pc) + assert (size, asm) == (len(raw), expected_asm), (size, asm, expected_asm) + pc += size + print("mesh s_bitcmp binary encodings match llvm-mc") + + +def constants(selector_bits, depth_point, depth_matrix, matrix_w, bit_index=0): + data = bytearray(1024) + struct.pack_into("<IfI", data, 0, selector_bits, depth_point, bit_index) + struct.pack_into("<f", data, 512 + 4, depth_matrix) + struct.pack_into("<f", data, 512 + 12, matrix_w) + return data + + +def join_cases(): + def triangle(z): + return [(x, y, z, w) for x, y, _, w in TRIANGLE] + + # Bit 5 == 0 with non-zero low bits (0x1f) selects POINT (-0.625 + 0.375 = -0.25 -> clipped); + # Bit 5 == 1 (0x20) selects MATRIX (0.25 + 0.375 = 0.625 -> visible). + # Dynamic bit index 37 tests (37 & 31) == 5. + return [ + (constants(0x0000001F, -0.625, 0.25, 0.375, bit_index=37), triangle(-0.25), False), + (constants(0x00000020, -0.625, 0.25, 0.375, bit_index=37), triangle(0.625), True), + ] + + +def check_draw(dxc, renderer, adapter): + configs = ( + lower_static(concrete_wave_program(), [0x1003], (3, 1)), + lower_static(join_program("s_bitcmp0_b32 s14, 5", "s_cbranch_scc0"), [0x1003], (3, 1)), + lower_static(join_program("s_bitcmp1_b32 s14, 5", "s_cbranch_scc1"), [0x1003], (3, 1)), + lower_static(join_program("s_bitcmp1_b32 s14, s13", "s_cbranch_scc1", dynamic_bit=True), [0x1003], (3, 1)), + ) + with tempfile.TemporaryDirectory() as directory: + tmp = Path(directory) + rc = draw(dxc, renderer, adapter, tmp, configs[0], [(constants(0, 0.125, 0.25, 0.375), + [(x, y, 0.5, w) for x, y, _, w in TRIANGLE], True)]) + if rc == 77: + return 77 + cases = join_cases() + for source in configs[1:]: + rc = draw(dxc, renderer, adapter, tmp, source, cases) + if rc == 77: + return 77 + + # Negative control: invert s_bitcmp0_b32 -> s_bitcmp1_b32 so arms flip and draw mismatches. + inverted = lower_static(join_program("s_bitcmp1_b32 s14, 5", "s_cbranch_scc0"), [0x1003], (3, 1)) + bad_dir = tmp / "neg" + bad_dir.mkdir() + try: + neg_rc = draw(dxc, renderer, adapter, bad_dir, inverted, cases) + except subprocess.CalledProcessError: + neg_rc = 1 + assert neg_rc != 0, "Inverted s_bitcmp passed GPU draw" + print("mesh s_bitcmp draw: ok") + return 0 + + +def main(): + if len(sys.argv) == 1: + check_controls() + return 0 + if sys.argv[1] == "binary" and len(sys.argv) == 3: + check_controls() + check_binary(sys.argv[2]) + return 0 + if sys.argv[1] == "draw" and len(sys.argv) == 5: + check_controls() + return check_draw(*sys.argv[2:]) + raise SystemExit("Usage: mesh_bitcmp_check.py [binary <llvm-mc> | draw <dxc> <offscreen_check> <adapter>]") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/mesh_param_link_check.py b/tests/mesh_param_link_check.py new file mode 100644 index 0000000000..cb2f65b0c0 --- /dev/null +++ b/tests/mesh_param_link_check.py @@ -0,0 +1,444 @@ +"""Parameter exports up to param12 and pixel-input pairing in mesh/startup translators (#2413 T4). + + (no arguments) pure-Python linkage controls, refusals and guard mutations + binary <llvm-mc> reassemble wave64 mesh and wave32 pixel fixtures with llvm-mc + draw <dxc> <offscreen_check> <adapter> compile ms_6_5 + ps_6_0 pairs, draw on D3D12, and check pixel readback + plus negative controls +""" + +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(ROOT / "tests")) + +import gfx2hlsl as G # noqa: E402 +import mesh_dynamic_aot # noqa: E402 +import mesh_entry_aot # noqa: E402 +import mesh_param_link # noqa: E402 +from mesh_dynamic_aot_draw_check import compile_shader # noqa: E402 +from mesh_dynamic_geometry_check import CODE as BASE_CODE, MESH_LIMITS, SECOND, decode # noqa: E402 +from startup_flat_param_check import root_blob # noqa: E402 +from startup_gfx2hlsl_interp_f16_check import P1LL_SRC2_MASK # noqa: E402 + +WAVE64 = "+wavefrontsize64,-wavefrontsize32" +SIDE = 32 + +# Insert extra parameter exports right after `exp param0 v5, v6, v7, v4` in tests/mesh_dynamic_geometry.s. +# All branches in BASE_CODE precede that block, so instruction PCs after the insertion stay branch-free. +PARAM0_ANCHOR = bytes.fromhex("0f0200f805060704") +ASSERT_ANCHOR = BASE_CODE.count(PARAM0_ANCHOR) == 1 + + +def encode_exp(target, vs, *, done=False, vm=False): + w0 = 0xF8000000 | (int(vm) << 12) | (int(done) << 11) | (target << 4) | 0xF + w1 = vs[0] | (vs[1] << 8) | (vs[2] << 16) | (vs[3] << 24) + return struct.pack("<II", w0, w1) + + +def encode_v_mov_lit(vdst, literal): + return struct.pack("<II", 0x7E0002FF | ((vdst & 0xFF) << 17), literal & 0xFFFFFFFF) + + +def encode_vintrp(op, vdst, attr, chan, vsrc): + return struct.pack("<I", 0xC8000000 | ((vdst & 0xFF) << 18) | (op << 16) | ((attr & 0x3F) << 10) + | ((chan & 3) << 8) | (vsrc & 0xFF)) + + +def encode_interp_f16(op, vdst, src1, attr, chan, high=0, src2=0): + w0 = (0b110101 << 26) | (op << 16) | (vdst & 0xFF) + attribute = ((high & 1) << 8) | ((chan & 3) << 6) | (attr & 0x3F) + w1 = attribute | ((src1 & 0x1FF) << 9) | ((src2 & 0x1FF) << 18) + return struct.pack("<II", w0, w1) + + +def encode_cvt_f32_f16(vdst, vsrc): + return struct.pack("<I", 0x7E000000 | ((vdst & 0xFF) << 17) | (0x0B << 9) | (0x100 + (vsrc & 0xFF))) + + +def with_mesh_exports(extra_bytes): + assert ASSERT_ANCHOR + return BASE_CODE.replace(PARAM0_ANCHOR, PARAM0_ANCHOR + extra_bytes) + + +# Mesh variant 1: exports param0 (u, v, 0.5, 1.0), param5 (0.25, 0, 1.0, 1.0), and param12 (v, u, 0, 1.0). +MESH_PARAM12_EXTRA = ( + encode_v_mov_lit(8, 0x3E800000) # v8 = 0.25f + + encode_exp(32 + 5, (8, 3, 4, 4)) # exp param5 v8, v3, v4, v4 + + encode_exp(32 + 12, (6, 5, 3, 4)) # exp param12 v6, v5, v3, v4 +) +MESH_PARAM12_CODE = with_mesh_exports(MESH_PARAM12_EXTRA) +MESH_PARAM12_ASM = ( + "v_mov_b32_e32 v8, 0x3e800000\n" + "exp param5 v8, v3, v4, v4\n" + "exp param12 v6, v5, v3, v4\n" +) + +# Mesh variant 2: exports param0 and param12 holding packed binary16 pairs (0.25, 1.0) and (0.125, 0.75). +MESH_F16_EXTRA = ( + encode_v_mov_lit(8, 0x3C003400) # v8 = pack_f16(0.25, 1.0) + + encode_v_mov_lit(12, 0x3A003000) # v12 = pack_f16(0.125, 0.75) + + encode_exp(32 + 12, (8, 12, 3, 4)) # exp param12 v8, v12, v3, v4 +) +MESH_F16_CODE = with_mesh_exports(MESH_F16_EXTRA) +MESH_F16_ASM = ( + "v_mov_b32_e32 v8, 0x3c003400\n" + "v_mov_b32_e32 v12, 0x3a003000\n" + "exp param12 v8, v12, v3, v4\n" +) + +# Negative-control mesh variant with unsupported param13 export. +MESH_PARAM13_CODE = with_mesh_exports(encode_exp(32 + 13, (5, 6, 7, 4))) + +# Pixel shader 1: linear attr0.x (R), linear attr12.x (G), flat attr5.x (B), linear attr12.w (A). +PS_LINEAR_FLAT_ASM = ( + "s_mov_b32 m0, s2\n" + "v_interp_p1_f32 v2, v0, attr0.x\n" + "v_interp_p2_f32 v2, v1, attr0.x\n" + "v_interp_p1_f32 v3, v0, attr12.x\n" + "v_interp_p2_f32 v3, v1, attr12.x\n" + "v_interp_mov_f32 v4, p0, attr5.x\n" + "v_interp_p1_f32 v5, v0, attr12.w\n" + "v_interp_p2_f32 v5, v1, attr12.w\n" + "exp mrt0 v2, v3, v4, v5 done vm\n" + "s_endpgm\n" +) +PS_LINEAR_FLAT_WORDS = b"".join(( + bytes.fromhex("0203fcbe"), + encode_vintrp(0, 2, 0, 0, 0), + encode_vintrp(1, 2, 0, 0, 1), + encode_vintrp(0, 3, 12, 0, 0), + encode_vintrp(1, 3, 12, 0, 1), + encode_vintrp(2, 4, 5, 0, 2), + encode_vintrp(0, 5, 12, 3, 0), + encode_vintrp(1, 5, 12, 3, 1), + encode_exp(0, (2, 3, 4, 5), done=True, vm=True), + bytes.fromhex("000081bf"), +)) + +# Pixel shader 2: reads both halves of attr12.x and attr12.y via v_interp_p1ll_f16 / v_interp_p2_f16. +PS_F16_ASM = ( + "s_mov_b32 m0, s2\n" + "v_interp_p1ll_f16 v4, v0, attr12.x\n" + "v_interp_p2_f16 v4, v1, attr12.x, v4\n" + "v_interp_p1ll_f16 v5, v0, attr12.x high\n" + "v_interp_p2_f16 v5, v1, attr12.x, v5 high\n" + "v_interp_p1ll_f16 v6, v0, attr12.y\n" + "v_interp_p2_f16 v6, v1, attr12.y, v6\n" + "v_interp_p1ll_f16 v7, v0, attr12.y high\n" + "v_interp_p2_f16 v7, v1, attr12.y, v7 high\n" + "v_cvt_f32_f16 v4, v4\n" + "v_cvt_f32_f16 v5, v5\n" + "v_cvt_f32_f16 v6, v6\n" + "v_cvt_f32_f16 v7, v7\n" + "exp mrt0 v4, v5, v6, v7 done vm\n" + "s_endpgm\n" +) +PS_F16_WORDS = b"".join(( + bytes.fromhex("0203fcbe"), + encode_interp_f16(0x342, 4, 0x100, 12, 0, high=0, src2=0), + encode_interp_f16(0x35A, 4, 0x101, 12, 0, high=0, src2=0x104), + encode_interp_f16(0x342, 5, 0x100, 12, 0, high=1, src2=0), + encode_interp_f16(0x35A, 5, 0x101, 12, 0, high=1, src2=0x105), + encode_interp_f16(0x342, 6, 0x100, 12, 1, high=0, src2=0), + encode_interp_f16(0x35A, 6, 0x101, 12, 1, high=0, src2=0x106), + encode_interp_f16(0x342, 7, 0x100, 12, 1, high=1, src2=0), + encode_interp_f16(0x35A, 7, 0x101, 12, 1, high=1, src2=0x107), + encode_cvt_f32_f16(4, 4), + encode_cvt_f32_f16(5, 5), + encode_cvt_f32_f16(6, 6), + encode_cvt_f32_f16(7, 7), + encode_exp(0, (4, 5, 6, 7), done=True, vm=True), + bytes.fromhex("000081bf"), +)) + +# Depth-only pixel shader (no attribute reads, mrtz depth export). +PS_DEPTH_ONLY_WORDS = bytes.fromhex("8002007e" "810800f800000000" "000081bf") + + +def assemble_mc(llvm_mc, source, mattr=None): + cmd = [llvm_mc, "-arch=amdgcn", "-mcpu=gfx1013"] + if mattr: + cmd.append(f"-mattr={mattr}") + cmd.append("-show-encoding") + run = subprocess.run(cmd, input=source, capture_output=True, text=True, check=True) + words = bytearray() + for line in run.stdout.splitlines(): + m = re.search(r"encoding: \[([^\]]*)\]", line) + if m: + words += bytes(int(b, 16) for b in m.group(1).split(",")) + return bytes(words) + + +def normalise_p1ll(words): + out = bytearray(words) + off = 0 + for _, size, name, _ in G.decode(words): + if name.startswith("v_interp_p1ll_f16"): + w1 = struct.unpack_from("<I", out, off + 4)[0] & ~P1LL_SRC2_MASK + struct.pack_into("<I", out, off + 4, w1) + off += size + return bytes(out) + + +def expect_error(exc_type, needle, fn, *args, **kwargs): + try: + fn(*args, **kwargs) + except exc_type as error: + assert needle in str(error), (needle, str(error)) + return + raise AssertionError(f"Expected {exc_type.__name__}({needle!r})") + + +def expected_pixels(counts, mode): + """Independent CPU rasterizer for 32x32 target (triangle=0x1003, quad=0x2004).""" + assert counts in (0x1003, 0x2004), hex(counts) + quad = counts == 0x2004 + pixels = bytearray() + for y in range(SIDE): + for x in range(SIDE): + inside = quad or y > x + if not inside: + pixels.extend((0, 0, 0, 255)) + elif mode == "linear_flat": + r = round((x + 0.5) / SIDE * 255) + g = round((SIDE - y - 0.5) / SIDE * 255) + pixels.extend((r, g, 64, 255)) + elif mode == "f16": + pixels.extend((64, 255, 32, 191)) + else: + raise ValueError(mode) + return bytes(pixels) + + +def fixture(counts, geometry, pixels): + data = bytearray(1536) + struct.pack_into("<II", data, 1024, counts, geometry) + data.extend(b"\xcd" * 80) + data.extend(pixels) + return bytes(data) + + +def controls(): + # 0. Verify all newly assembled instruction bytes decode to the exact expected assembly. + for raw, asm_text in ( + (MESH_PARAM12_EXTRA, MESH_PARAM12_ASM), + (MESH_F16_EXTRA, MESH_F16_ASM), + (PS_LINEAR_FLAT_WORDS, PS_LINEAR_FLAT_ASM), + (PS_F16_WORDS, PS_F16_ASM), + ): + decoded_lines = "\n".join(asm.replace("_e32", "") for _, _, _, asm in G.decode(raw)) + "\n" + want_lines = "\n".join(l.replace("_e32", "") for l in asm_text.splitlines()) + "\n" + assert decoded_lines == want_lines, (decoded_lines, want_lines) + + # 1. Static + dynamic mesh paired with MeshPixelStage (param0, flat param5, linear param12). + ps_stage = G.MeshPixelStage((0, 5, 12), PS_LINEAR_FLAT_WORDS, root_blob()) + linkage = ps_stage.linkage() + assert linkage.params == (0, 5, 12) + assert linkage.flat == (5,) + assert linkage.f16_plain == () + assert linkage.pixel_attrs == (0, 5, 12) + ps_hlsl = ps_stage.hlsl_ps() + assert "float4 param12 : PARAM12;" in ps_hlsl and "nointerpolation uint4 fparam5 : FPARAM5;" in ps_hlsl + assert "cbuffer entry" not in ps_hlsl + + decoded_m12 = decode(MESH_PARAM12_CODE) + static_hlsl = mesh_entry_aot.lower(decoded_m12, [0x2004, SECOND], MESH_LIMITS, param_linkage=linkage) + dynamic_hlsl = mesh_dynamic_aot.lower(decoded_m12, 2, MESH_LIMITS, param_linkage=linkage) + for text in (static_hlsl, dynamic_hlsl): + for token in ("float4 param0 : PARAM0;", "float4 param12 : PARAM12;", "nointerpolation uint4 fparam5 : FPARAM5;", + ".param1 = float4(0.0f, 0.0f, 0.0f, 0.0f);", ".fparam5 = asuint(p5);"): + assert token in text, (token, text) + + # 2. Static + dynamic mesh paired with MeshPixelStage reading binary16 halves from param12. + ps_f16_stage = G.MeshPixelStage((0, 12), PS_F16_WORDS, root_blob()) + f16_link = ps_f16_stage.linkage() + assert f16_link.f16_plain == (12,) + assert "float4 hparam12_lo : HPARAML12;" in ps_f16_stage.hlsl_ps() + decoded_f16 = decode(MESH_F16_CODE) + static_f16 = mesh_entry_aot.lower(decoded_f16, [0x2004, SECOND], MESH_LIMITS, param_linkage=f16_link) + dynamic_f16 = mesh_dynamic_aot.lower(decoded_f16, 2, MESH_LIMITS, param_linkage=f16_link) + for text in (static_f16, dynamic_f16): + assert "float4 hparam12_lo : HPARAML12;" in text and "float4 hparam12_hi : HPARAMH12;" in text, text + assert ".hparam12_lo = f16tof32(h12);" in text and ".hparam12_hi = f16tof32(h12 >> 16);" in text, text + + # 3. Depth-only pairing (empty mesh_params and no pixel attribute reads) and legacy TEXCOORD0 default. + depth_ps = G.MeshPixelStage((), PS_DEPTH_ONLY_WORDS, root_blob()) + assert depth_ps.linkage().params == () + assert "PARAM0" not in depth_ps.hlsl_ps() + legacy_hlsl = mesh_entry_aot.lower(decode(BASE_CODE), [0x1003, SECOND], MESH_LIMITS) + assert "float4 attr : TEXCOORD0;" in legacy_hlsl and "PARAM0" not in legacy_hlsl, legacy_hlsl + + # 4. Refusals: param13+, off component, compr, duplicate, incomplete vertex export, variant signature mismatch, + # missing pixel attr, compute fallback with param12, and D3D12 32-vector signature limit. + expect_error(ValueError, "Unsupported mesh export", mesh_entry_aot.lower, + decode(MESH_PARAM13_CODE), [0x1003, SECOND], MESH_LIMITS) + expect_error(ValueError, "Unsupported live export", mesh_entry_aot.lower, + [(0, "s_mov_b32 s15, 0x1003"), *decode(with_mesh_exports(encode_exp(32 + 12, (6, 5, 3, 4))))[:-1], + (900, "exp param12 v6, v5, off, v4"), (908, "s_endpgm")], + [0x1003, SECOND], MESH_LIMITS) + expect_error(ValueError, "Duplicate vertex parameter param12", mesh_entry_aot.lower, + decode(with_mesh_exports(MESH_PARAM12_EXTRA + encode_exp(32 + 12, (6, 5, 3, 4)))), + [0x1003, SECOND], MESH_LIMITS) + incomplete = [(pc, text.replace("exp param12 v6, v5, v3, v4", "exp param12 v6, v5, v3, v4") if pc else text) + for pc, text in decoded_m12] + # Emit param12 only for vertex 0 (skip vertices 1 and 2 via v_cmpx_eq_u32). + split_incomplete = [] + for pc, text in decoded_m12: + if text == "exp param12 v6, v5, v3, v4": + split_incomplete.extend([ + (pc, "v_cmpx_eq_u32_e32 0, v0"), + (pc + 1, "exp param12 v6, v5, v3, v4"), + (pc + 2, "s_mov_b64 exec, s[22:23]"), + (pc + 3, "v_cmpx_gt_u32_e32 s16, v0"), + ]) + else: + split_incomplete.append((pc, text)) + expect_error(ValueError, "Incomplete vertex parameter param12", + mesh_entry_aot.lower, split_incomplete, [0x1003, SECOND], MESH_LIMITS) + + # Dynamic branch mismatch: only one runtime branch exports param12. + mismatch_dyn = [] + shift = 0 + for pc, text in decode(BASE_CODE): + if text == "exp param0 v5, v6, v7, v4": + mismatch_dyn.extend([ + (pc, text), + (pc + 8, "s_cmp_eq_u32 s15, 0x2004"), + (pc + 12, "s_cbranch_scc0 2"), + (pc + 16, "exp param12 v6, v5, v3, v4"), + ]) + shift = 16 + else: + mismatch_dyn.append((pc + shift, text)) + expect_error(ValueError, "disagree on the vertex signature", + mesh_dynamic_aot.lower, mismatch_dyn, 2, MESH_LIMITS) + + expect_error(G.Unsupported, "does not export", G.MeshPixelStage, (0, 5), PS_LINEAR_FLAT_WORDS, root_blob()) + expect_error(G.Unsupported, "does not export", G.MeshPixelStage, (0, 12), PS_LINEAR_FLAT_WORDS, root_blob()) + expect_error(ValueError, "compute fallback translates only param0", + mesh_entry_aot.lower, decoded_m12, [0x1003, SECOND], MESH_LIMITS, compute_fallback=True) + expect_error(ValueError, "exceeding D3D12 limit", mesh_param_link.validate_linkage, + tuple(range(13)), flat=tuple(range(13)), f16_plain=(0, 1, 2, 3)) + expect_error(ValueError, "must be an integer in 0..12", mesh_param_link.validate_linkage, (0, 13)) + expect_error(G.Unsupported, "outside 0..12", G.MeshPixelStage, (0, 13), PS_DEPTH_ONLY_WORDS, root_blob()) + + # 5. Guard mutation controls: weakening any check must be caught. + with patch.object(mesh_param_link, "MAX_VERTEX_VECTORS", 64): + expect_error(AssertionError, "Expected ValueError", expect_error, ValueError, "exceeding D3D12 limit", + mesh_param_link.validate_linkage, tuple(range(13)), flat=tuple(range(13)), f16_plain=(0, 1, 2, 3)) + with patch.object(mesh_param_link, "MAX_PARAM", 15): + mesh_param_link.validate_linkage((0, 13)) + with patch.object(mesh_entry_aot, "hlsl_param_writes", lambda *a, **k: []): + no_writes = mesh_entry_aot.lower(decoded_m12, [0x2004, SECOND], MESH_LIMITS, param_linkage=linkage) + assert ".param12" not in no_writes + + print("mesh param0..param12 linkage controls passed") + + +def check_binary(llvm_mc): + for label, src, raw in ( + ("mesh_param12_extra", MESH_PARAM12_ASM, MESH_PARAM12_EXTRA), + ("mesh_f16_extra", MESH_F16_ASM, MESH_F16_EXTRA), + ): + built = assemble_mc(llvm_mc, src, mattr=WAVE64) + if built != raw: + raise AssertionError(f"{label}: assembled {built.hex()}, recorded {raw.hex()}") + for label, src, raw, norm in ( + ("ps_linear_flat", PS_LINEAR_FLAT_ASM, PS_LINEAR_FLAT_WORDS, False), + ("ps_f16", PS_F16_ASM, PS_F16_WORDS, True), + ): + built = assemble_mc(llvm_mc, src) + if norm: + built = normalise_p1ll(built) + if built != raw: + raise AssertionError(f"{label}: assembled {built.hex()}, recorded {raw.hex()}") + print("mesh param0..param12 fixture words match llvm-mc") + + +def check_draw(dxc, renderer, adapter): + controls() + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + ps_lf_stage = G.MeshPixelStage((0, 5, 12), PS_LINEAR_FLAT_WORDS, root_blob()) + ps_lf_dxil = compile_shader(dxc, directory, "ps_lf", ps_lf_stage.hlsl_ps(), "ps_6_0") + lf_link = ps_lf_stage.linkage() + decoded_m12 = decode(MESH_PARAM12_CODE) + dyn_lf_hlsl = mesh_dynamic_aot.lower(decoded_m12, 2, MESH_LIMITS, param_linkage=lf_link) + dyn_lf_dxil = compile_shader(dxc, directory, "ms_dyn_lf", dyn_lf_hlsl, "ms_6_5") + stat_lf_hlsl = mesh_entry_aot.lower(decoded_m12, [0x2004, SECOND], MESH_LIMITS, param_linkage=lf_link) + stat_lf_dxil = compile_shader(dxc, directory, "ms_stat_lf", stat_lf_hlsl, "ms_6_5") + + ps_f16_stage = G.MeshPixelStage((0, 12), PS_F16_WORDS, root_blob()) + ps_f16_dxil = compile_shader(dxc, directory, "ps_f16", ps_f16_stage.hlsl_ps(), "ps_6_0") + f16_link = ps_f16_stage.linkage() + decoded_f16 = decode(MESH_F16_CODE) + dyn_f16_dxil = compile_shader( + dxc, directory, "ms_dyn_f16", + mesh_dynamic_aot.lower(decoded_f16, 2, MESH_LIMITS, param_linkage=f16_link), "ms_6_5") + stat_f16_dxil = compile_shader( + dxc, directory, "ms_stat_f16", + mesh_entry_aot.lower(decoded_f16, [0x2004, SECOND], MESH_LIMITS, param_linkage=f16_link), "ms_6_5") + + draws = ( + ("dynamic_lf_triangle", dyn_lf_dxil, ps_lf_dxil, 0x1003, expected_pixels(0x1003, "linear_flat")), + ("dynamic_lf_quad", dyn_lf_dxil, ps_lf_dxil, 0x2004, expected_pixels(0x2004, "linear_flat")), + ("static_lf_quad", stat_lf_dxil, ps_lf_dxil, 0x2004, expected_pixels(0x2004, "linear_flat")), + ("dynamic_f16_quad", dyn_f16_dxil, ps_f16_dxil, 0x2004, expected_pixels(0x2004, "f16")), + ("static_f16_quad", stat_f16_dxil, ps_f16_dxil, 0x2004, expected_pixels(0x2004, "f16")), + ) + for name, ms, ps, counts, pixels in draws: + case = directory / f"{name}.bin" + case.write_bytes(fixture(counts, SECOND, pixels)) + run = subprocess.run([renderer, adapter, "--mesh-indexed", ms, ps, case], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout, run.stderr) + return 77 + if run.returncode: + raise AssertionError(f"{name}:\n{run.stdout}\n{run.stderr}") + print(f"{adapter} {name}: pass ({[l for l in run.stdout.splitlines() if 'mismatches=' in l][0]})", + flush=True) + + # GPU negative controls: swapping param0<->param12 or corrupting fparam5 must fail readback. + quad_case = directory / "dynamic_lf_quad.bin" + swapped = dyn_lf_hlsl.replace(".param0 = ", ".paramX = ").replace(".param12 = ", ".param0 = ").replace( + ".paramX = ", ".param12 = ") + assert swapped != dyn_lf_hlsl + bad_flat = dyn_lf_hlsl.replace(".fparam5 = asuint(p5);", ".fparam5 = uint4(0, 0, 0, 0);") + assert bad_flat != dyn_lf_hlsl + for label, bad_hlsl, want_mismatches in ( + ("swapped_param0_param12", swapped, "pixels=1024 mismatches=992"), + ("zeroed_flat_fparam5", bad_flat, "pixels=1024 mismatches=1024"), + ): + bad_ms = compile_shader(dxc, directory, label, bad_hlsl, "ms_6_5") + wrong = subprocess.run([renderer, adapter, "--mesh-indexed", bad_ms, ps_lf_dxil, quad_case], + capture_output=True, text=True) + if wrong.returncode != 1 or want_mismatches not in wrong.stdout.splitlines() or "Draw reference mismatch" not in wrong.stderr: + raise AssertionError(f"{label} did not fail as expected:\n{wrong.stdout}\n{wrong.stderr}") + print(f"{adapter} control {label}: fails as expected ({want_mismatches})", flush=True) + return 0 + + +def main(): + if len(sys.argv) == 1: + controls() + return 0 + mode, *args = sys.argv[1:] + if mode == "binary": + check_binary(*args) + return 0 + if mode == "draw": + return check_draw(*args) + raise SystemExit(__doc__) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/mesh_shader_pipeline_draw.cpp b/tests/mesh_shader_pipeline_draw.cpp new file mode 100644 index 0000000000..66efe49b5a --- /dev/null +++ b/tests/mesh_shader_pipeline_draw.cpp @@ -0,0 +1,281 @@ +#include "desktop_gpu.h" +#include "mesh_shader_pipeline.h" +#include "meshlet_builder.h" + +#include "meshlet_pipeline_as.h" +#include "meshlet_pipeline_ms.h" +#include "meshlet_pipeline_ps.h" +#include "meshlet_pipeline_vs.h" + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <stdexcept> +#include <vector> + +namespace { + +using Microsoft::WRL::ComPtr; +using x2w::meshlet::MeshShaderBytecode; +using x2w::meshlet::MeshShaderCapabilities; +using x2w::meshlet::MeshShaderPipeline; +using x2w::meshlet::MeshShaderPipelineMode; +using x2w::meshlet::MeshletBufferData; +using x2w::meshlet::MeshletGpuResources; +using x2w::meshlet::SceneConstantsGPU; + +constexpr UINT kSide = 64; + +struct RenderResult { + std::vector<std::uint8_t> rgba; + std::array<std::uint32_t, 4> cull_stats{}; + MeshShaderCapabilities caps{}; + bool used_mesh_shaders = false; +}; + +SceneConstantsGPU make_scene_constants(std::uint32_t meshlet_count) { + SceneConstantsGPU cb{}; + // Identity view-projection matrix (row-major). + cb.view_proj[0] = 1.0f; + cb.view_proj[5] = 1.0f; + cb.view_proj[10] = 1.0f; + cb.view_proj[15] = 1.0f; + + // 6 NDC frustum planes for D3D12 depth [0, 1]. + const float planes[6][4]{ + { 1.0f, 0.0f, 0.0f, 1.0f}, // Left + {-1.0f, 0.0f, 0.0f, 1.0f}, // Right + { 0.0f, 1.0f, 0.0f, 1.0f}, // Bottom + { 0.0f, -1.0f, 0.0f, 1.0f}, // Top + { 0.0f, 0.0f, 1.0f, 0.0f}, // Near + { 0.0f, 0.0f, -1.0f, 1.0f}, // Far + }; + std::memcpy(cb.frustum_planes, planes, sizeof(planes)); + + cb.camera_pos[0] = 0.0f; + cb.camera_pos[1] = 0.0f; + cb.camera_pos[2] = -2.0f; + cb.camera_pos[3] = 1.0f; // Enable AS culling + cb.meshlet_count = meshlet_count; + return cb; +} + +RenderResult render_scene(ID3D12Device* device, const MeshletBufferData& scene, MeshShaderPipelineMode mode) { + MeshShaderBytecode shaders{}; + shaders.as = {meshlet_pipeline_as, sizeof(meshlet_pipeline_as)}; + shaders.ms = {meshlet_pipeline_ms, sizeof(meshlet_pipeline_ms)}; + shaders.vs = {meshlet_pipeline_vs, sizeof(meshlet_pipeline_vs)}; + shaders.ps = {meshlet_pipeline_ps, sizeof(meshlet_pipeline_ps)}; + + MeshShaderPipeline pipeline; + if (!pipeline.initialize(device, shaders, mode, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_D32_FLOAT)) { + throw std::runtime_error("MeshShaderPipeline::initialize unexpectedly returned false"); + } + + if (pipeline.using_mesh_shaders()) { + using namespace x2w::meshlet; + const auto expect_refusal = [&](const std::vector<MeshletVertex>& vertices, const std::vector<std::uint32_t>& indices) { + const auto oversized = build_meshlets(vertices, indices, kHardwareMaxMeshletVertices, kHardwareMaxMeshletPrimitives); + try { + pipeline.create_gpu_resources(device, oversized); + } catch (const std::invalid_argument&) { + return; + } + throw std::runtime_error("Meshlet exceeding the shader output capacity was accepted"); + }; + + std::vector<MeshletVertex> vertices(kMaxMeshletVertices + 1, scene.vertices.front()); + std::vector<std::uint32_t> indices; + for (std::uint32_t i = 0; i < vertices.size(); ++i) indices.push_back(i); + indices.push_back(0); + expect_refusal(vertices, indices); + indices.clear(); + for (std::uint32_t i = 0; i <= kMaxMeshletPrimitives; ++i) + indices.insert(indices.end(), {0, 1, 2}); + expect_refusal(scene.vertices, indices); + } + const MeshletGpuResources res = pipeline.create_gpu_resources(device, scene); + const SceneConstantsGPU cb_data = make_scene_constants(res.meshlet_count); + + auto cb_upload = make_buffer(device, sizeof(SceneConstantsGPU), D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + const D3D12_RANGE empty{0, 0}; + check(cb_upload->Map(0, &empty, &mapped), "Map scene constants"); + std::memcpy(mapped, &cb_data, sizeof(cb_data)); + cb_upload->Unmap(0, nullptr); + + constexpr UINT64 kStatsBytes = 16; + auto stats_zero = make_buffer(device, kStatsBytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(stats_zero->Map(0, &empty, &mapped), "Map stats zero upload"); + std::memset(mapped, 0, kStatsBytes); + stats_zero->Unmap(0, nullptr); + + auto stats_uav = make_buffer(device, kStatsBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto stats_readback = make_buffer(device, kStatsBytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + + D3D12_RESOURCE_DESC rtv_desc{}; + rtv_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rtv_desc.Width = kSide; + rtv_desc.Height = kSide; + rtv_desc.DepthOrArraySize = 1; + rtv_desc.MipLevels = 1; + rtv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rtv_desc.SampleDesc.Count = 1; + rtv_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const float clear_color[4]{0.0f, 0.0f, 0.0f, 1.0f}; + D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.0f, 0.0f, 0.0f, 1.0f}}; + auto target = resource(device, rtv_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &rtv_clear); + + D3D12_RESOURCE_DESC dsv_desc = rtv_desc; + dsv_desc.Format = DXGI_FORMAT_D32_FLOAT; + dsv_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE dsv_clear{}; + dsv_clear.Format = DXGI_FORMAT_D32_FLOAT; + dsv_clear.DepthStencil.Depth = 1.0f; + auto depth = resource(device, dsv_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_DEPTH_WRITE, &dsv_clear); + + ComPtr<ID3D12DescriptorHeap> rtv_heap; + D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + check(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap)), "Create RTV heap"); + const auto rtv_handle = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv_handle); + + ComPtr<ID3D12DescriptorHeap> dsv_heap; + D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + check(device->CreateDescriptorHeap(&dsv_heap_desc, IID_PPV_ARGS(&dsv_heap)), "Create DSV heap"); + const auto dsv_handle = dsv_heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateDepthStencilView(depth.Get(), nullptr, dsv_handle); + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 readback_bytes = 0; + device->GetCopyableFootprints(&rtv_desc, 0, 1, 0, &footprint, nullptr, nullptr, &readback_bytes); + auto pixel_readback = make_buffer(device, readback_bytes, D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_STATE_COPY_DEST); + + ComputeCommands commands(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + auto* list = commands.list.Get(); + + list->CopyBufferRegion(stats_uav.Get(), 0, stats_zero.Get(), 0, kStatsBytes); + transition(list, stats_uav.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + const D3D12_VIEWPORT viewport{0.0f, 0.0f, static_cast<float>(kSide), static_cast<float>(kSide), 0.0f, 1.0f}; + const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSide), static_cast<LONG>(kSide)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv_handle, FALSE, &dsv_handle); + list->ClearRenderTargetView(rtv_handle, clear_color, 0, nullptr); + list->ClearDepthStencilView(dsv_handle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + + pipeline.record_draw(list, cb_upload->GetGPUVirtualAddress(), stats_uav->GetGPUVirtualAddress(), res); + + transition(list, stats_uav.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(stats_readback.Get(), 0, stats_uav.Get(), 0, kStatsBytes); + + transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.Get(); + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = pixel_readback.Get(); + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = footprint; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + + commands.submit_and_wait(device); + + RenderResult result; + result.caps = pipeline.capabilities(); + result.used_mesh_shaders = pipeline.using_mesh_shaders(); + result.rgba.resize(static_cast<std::size_t>(kSide) * kSide * 4); + + const D3D12_RANGE stats_range{0, kStatsBytes}; + check(stats_readback->Map(0, &stats_range, &mapped), "Map cull stats readback"); + std::memcpy(result.cull_stats.data(), mapped, kStatsBytes); + stats_readback->Unmap(0, &empty); + + const D3D12_RANGE pixel_range{0, static_cast<SIZE_T>(readback_bytes)}; + check(pixel_readback->Map(0, &pixel_range, &mapped), "Map rendered pixels"); + const auto* base = static_cast<const std::uint8_t*>(mapped); + for (UINT y = 0; y < kSide; ++y) { + std::memcpy(&result.rgba[static_cast<std::size_t>(y) * kSide * 4], + base + footprint.Offset + static_cast<std::size_t>(y) * footprint.Footprint.RowPitch, + kSide * 4); + } + pixel_readback->Unmap(0, &empty); + return result; +} + +void verify_rendered_image(const std::vector<std::uint8_t>& rgba, const char* label) { + auto pixel_at = [&](UINT x, UINT y) -> std::array<std::uint8_t, 4> { + const std::size_t idx = (static_cast<std::size_t>(y) * kSide + x) * 4; + return {rgba[idx + 0], rgba[idx + 1], rgba[idx + 2], rgba[idx + 3]}; + }; + const std::array<std::uint8_t, 4> green{0, 255, 0, 255}; + const std::array<std::uint8_t, 4> blue{0, 0, 255, 255}; + const std::array<std::uint8_t, 4> black{0, 0, 0, 255}; + + if (pixel_at(16, 32) != green) { + std::fprintf(stderr, "%s: expected green at (16,32)\n", label); + throw std::runtime_error("Left visible meshlet pixel mismatch"); + } + if (pixel_at(48, 32) != blue) { + std::fprintf(stderr, "%s: expected blue at (48,32)\n", label); + throw std::runtime_error("Right visible meshlet pixel mismatch"); + } + if (pixel_at(32, 32) != black) { + std::fprintf(stderr, "%s: expected black at (32,32) (backface-culled meshlet leaked)\n", label); + throw std::runtime_error("Backface-culled meshlet was not culled"); + } + + for (UINT y = 0; y < kSide; ++y) { + for (UINT x = 0; x < kSide; ++x) { + const auto p = pixel_at(x, y); + if (p[0] > 0) { + std::fprintf(stderr, "%s: unexpected red channel %u at (%u,%u)\n", label, p[0], x, y); + throw std::runtime_error("Culled red/yellow meshlet rendered a pixel"); + } + } + } +} + +} // namespace + +bool check_mesh_shader_pipeline(ID3D12Device* device, bool force_fallback) { + const MeshletBufferData scene = x2w::meshlet::build_culling_test_scene(); + + if (force_fallback) { + const RenderResult fallback = render_scene(device, scene, MeshShaderPipelineMode::ForceVertexFallback); + std::printf("mesh_shader_tier=%u mode=vertex_fallback\n", + static_cast<unsigned>(fallback.caps.mesh_shader_tier)); + verify_rendered_image(fallback.rgba, "vertex_fallback"); + return true; + } + + const RenderResult auto_result = render_scene(device, scene, MeshShaderPipelineMode::Auto); + std::printf("mesh_shader_tier=%u shader_model=0x%x mode=%s\n", + static_cast<unsigned>(auto_result.caps.mesh_shader_tier), + static_cast<unsigned>(auto_result.caps.highest_shader_model), + auto_result.used_mesh_shaders ? "mesh" : "vertex_fallback"); + + verify_rendered_image(auto_result.rgba, auto_result.used_mesh_shaders ? "mesh_shader" : "vertex_fallback"); + + if (auto_result.used_mesh_shaders) { + std::printf("cull_stats tested=%u frustum_culled=%u backface_culled=%u dispatched=%u\n", + auto_result.cull_stats[0], auto_result.cull_stats[1], + auto_result.cull_stats[2], auto_result.cull_stats[3]); + if (auto_result.cull_stats != std::array<std::uint32_t, 4>{4, 1, 1, 2}) { + throw std::runtime_error("Unexpected amplification shader cull statistics"); + } + + const RenderResult fallback = render_scene(device, scene, MeshShaderPipelineMode::ForceVertexFallback); + if (auto_result.rgba != fallback.rgba) { + throw std::runtime_error("Mesh shader output differs from classic vertex fallback output"); + } + std::puts("fallback_parity=exact"); + } + + return true; +} diff --git a/tests/meshlet_builder_check.cpp b/tests/meshlet_builder_check.cpp new file mode 100644 index 0000000000..1dd1e83ce2 --- /dev/null +++ b/tests/meshlet_builder_check.cpp @@ -0,0 +1,280 @@ +#include "meshlet_builder.h" + +#include <cmath> +#include <cstdio> +#include <set> +#include <stdexcept> +#include <tuple> +#include <vector> + +namespace { + +using x2w::meshlet::MeshletBounds; +using x2w::meshlet::MeshletBufferData; +using x2w::meshlet::MeshletVertex; + +void require(bool cond, const char* what) { + if (!cond) { + std::fprintf(stderr, "meshlet_builder_check failed: %s\n", what); + throw std::runtime_error(what); + } +} + +MeshletVertex make_vertex(float x, float y, float z, float nz = -1.0f) { + return MeshletVertex{{x, y, z}, 0.0f, {0.0f, 0.0f, nz}, 0.0f, {0.2f, 0.4f, 0.6f, 1.0f}}; +} + +bool is_backface_culled(const MeshletBounds& b, float cam_x, float cam_y, float cam_z) { + if (b.cone_cutoff >= 1.5f) return false; + const float dx = b.cone_apex[0] - cam_x; + const float dy = b.cone_apex[1] - cam_y; + const float dz = b.cone_apex[2] - cam_z; + const float len_sq = dx * dx + dy * dy + dz * dz; + if (len_sq <= 1e-12f) return false; + const float inv_len = 1.0f / std::sqrt(len_sq); + const float d = (dx * b.cone_axis[0] + dy * b.cone_axis[1] + dz * b.cone_axis[2]) * inv_len; + return d >= b.cone_cutoff; +} + +void test_single_triangle() { + const std::vector<MeshletVertex> verts{ + make_vertex(-0.5f, -0.5f, 0.5f), + make_vertex(0.0f, 0.5f, 0.5f), + make_vertex(0.5f, -0.5f, 0.5f), + }; + const std::vector<std::uint32_t> indices{0, 1, 2}; + const MeshletBufferData data = x2w::meshlet::build_meshlets(verts, indices); + + require(data.meshlets.size() == 1, "single triangle produces 1 meshlet"); + require(data.bounds.size() == 1, "single triangle produces 1 bounds entry"); + require(data.meshlets[0].vertex_count == 3, "single triangle vertex_count == 3"); + require(data.meshlets[0].primitive_count == 1, "single triangle primitive_count == 1"); + require(data.unique_vertex_indices.size() == 3, "unique_vertex_indices size == 3"); + require(data.packed_primitives.size() == 1, "packed_primitives size == 1"); + require(data.packed_primitives[0] == 0x00020100u, "packed primitive indices match (0,1,2)"); + require(!is_backface_culled(data.bounds[0], 0.0f, 0.0f, -2.0f), "CW triangle is front-facing from z=-2"); + require(is_backface_culled(data.bounds[0], 0.0f, 0.0f, 2.0f), "CW triangle is back-facing from z=+2"); +} + +void test_grid_partitioning() { + // 10x10 grid = 121 vertices, 200 triangles: exceeds both kMaxMeshletVertices (64) and kMaxMeshletPrimitives (126). + constexpr int grid = 10; + std::vector<MeshletVertex> verts; + std::vector<std::uint32_t> indices; + for (int y = 0; y <= grid; ++y) { + for (int x = 0; x <= grid; ++x) { + verts.push_back(make_vertex(static_cast<float>(x), static_cast<float>(y), 0.0f)); + } + } + for (int y = 0; y < grid; ++y) { + for (int x = 0; x < grid; ++x) { + const std::uint32_t v0 = static_cast<std::uint32_t>(y * (grid + 1) + x); + const std::uint32_t v1 = v0 + (grid + 1); + const std::uint32_t v2 = v1 + 1; + const std::uint32_t v3 = v0 + 1; + indices.insert(indices.end(), {v0, v1, v2, v0, v2, v3}); + } + } + + const MeshletBufferData data = x2w::meshlet::build_meshlets(verts, indices); + require(data.meshlets.size() >= 2, "grid splits into multiple meshlets"); + require(data.meshlets.size() == data.bounds.size(), "meshlets and bounds counts match"); + + std::vector<std::tuple<std::uint32_t, std::uint32_t, std::uint32_t>> reconstructed; + for (std::size_t m = 0; m < data.meshlets.size(); ++m) { + const auto& d = data.meshlets[m]; + const auto& b = data.bounds[m]; + require(d.vertex_count > 0 && d.vertex_count <= x2w::meshlet::kMaxMeshletVertices, + "meshlet vertex count within limit"); + require(d.primitive_count > 0 && d.primitive_count <= x2w::meshlet::kMaxMeshletPrimitives, + "meshlet primitive count within limit"); + require(d.vertex_offset + d.vertex_count <= data.unique_vertex_indices.size(), + "meshlet vertex range in bounds"); + require(d.primitive_offset + d.primitive_count <= data.packed_primitives.size(), + "meshlet primitive range in bounds"); + + std::set<std::uint32_t> seen_vertices; + for (std::uint32_t v = 0; v < d.vertex_count; ++v) { + const std::uint32_t global_idx = data.unique_vertex_indices[d.vertex_offset + v]; + require(global_idx < verts.size(), "unique vertex index in bounds"); + require(seen_vertices.insert(global_idx).second, "meshlet vertices are deduplicated"); + const float dx = verts[global_idx].position[0] - b.center[0]; + const float dy = verts[global_idx].position[1] - b.center[1]; + const float dz = verts[global_idx].position[2] - b.center[2]; + const float dist = std::sqrt(dx * dx + dy * dy + dz * dz); + require(dist <= b.radius + 1e-4f, "bounding sphere encloses all meshlet vertices"); + } + + for (std::uint32_t p = 0; p < d.primitive_count; ++p) { + const std::uint32_t packed = data.packed_primitives[d.primitive_offset + p]; + const std::uint32_t l0 = packed & 0xFFu; + const std::uint32_t l1 = (packed >> 8) & 0xFFu; + const std::uint32_t l2 = (packed >> 16) & 0xFFu; + require(l0 < d.vertex_count && l1 < d.vertex_count && l2 < d.vertex_count, + "packed primitive local indices in bounds"); + reconstructed.emplace_back( + data.unique_vertex_indices[d.vertex_offset + l0], + data.unique_vertex_indices[d.vertex_offset + l1], + data.unique_vertex_indices[d.vertex_offset + l2]); + } + } + + require(reconstructed.size() == indices.size() / 3, "all triangles preserved"); + for (std::size_t t = 0; t < reconstructed.size(); ++t) { + const auto expected = std::make_tuple(indices[t * 3 + 0], indices[t * 3 + 1], indices[t * 3 + 2]); + require(reconstructed[t] == expected, "triangle order and indices match input"); + } +} + +void test_double_sided_disables_culling() { + const std::vector<MeshletVertex> verts{ + make_vertex(-0.5f, -0.5f, 0.5f), + make_vertex(-0.5f, 0.5f, 0.5f), + make_vertex(0.5f, 0.5f, 0.5f), + }; + const std::vector<std::uint32_t> indices{0, 1, 2, 0, 2, 1}; + const MeshletBufferData data = x2w::meshlet::build_meshlets(verts, indices); + require(data.bounds.size() == 1, "double-sided triangles in 1 meshlet"); + require(data.bounds[0].cone_cutoff > 1.0f, "opposing normals disable normal cone culling"); + require(!is_backface_culled(data.bounds[0], 0.0f, 0.0f, -2.0f), "double-sided meshlet not culled from front"); + require(!is_backface_culled(data.bounds[0], 0.0f, 0.0f, 2.0f), "double-sided meshlet not culled from back"); +} + +void test_culling_scene() { + const MeshletBufferData scene = x2w::meshlet::build_culling_test_scene(); + require(scene.meshlets.size() == 4, "culling test scene has 4 meshlets"); + require(!is_backface_culled(scene.bounds[0], 0.0f, 0.0f, -2.0f), "meshlet 0 is front-facing"); + require(!is_backface_culled(scene.bounds[1], 0.0f, 0.0f, -2.0f), "meshlet 1 is front-facing"); + require(is_backface_culled(scene.bounds[2], 0.0f, 0.0f, -2.0f), "meshlet 2 is back-facing"); + require(!is_backface_culled(scene.bounds[3], 0.0f, 0.0f, -2.0f), "meshlet 3 is front-facing"); +} + +// Two triangles whose normals are tilted by +/- half_angle around Y, so the cone axis is +Z and +// min_dot == cos(half_angle). Appends 6 vertices at x offset `x0`. +std::vector<MeshletVertex> tilted_pair(float half_angle) { + const float c = std::cos(half_angle); + const float s = std::sin(half_angle); + std::vector<MeshletVertex> v; + // normal (s,0,c): tangent (c,0,-s) x (0,1,0) + v.push_back(make_vertex(0.0f, 0.0f, 0.0f)); + v.push_back(make_vertex(c, 0.0f, -s)); + v.push_back(make_vertex(0.0f, 1.0f, 0.0f)); + // normal (-s,0,c): tangent (c,0,s) x (0,1,0) + v.push_back(make_vertex(5.0f, 0.0f, 0.0f)); + v.push_back(make_vertex(5.0f + c, 0.0f, s)); + v.push_back(make_vertex(5.0f, 1.0f, 0.0f)); + return v; +} + +void test_cone_width_threshold() { + constexpr float kDeg = 3.14159265f / 180.0f; + const std::vector<std::uint32_t> indices{0, 1, 2, 3, 4, 5}; + + // Moderate cone (min_dot = cos 60 = 0.5): kept, cutoff = sin(60 deg). + const MeshletBufferData moderate = x2w::meshlet::build_meshlets(tilted_pair(60.0f * kDeg), indices); + require(moderate.bounds.size() == 1, "moderate cone is one meshlet"); + require(std::fabs(moderate.bounds[0].cone_cutoff - std::sin(60.0f * kDeg)) < 1e-3f, + "moderate cone keeps cutoff = sin(half angle)"); + require(std::fabs(moderate.bounds[0].cone_axis[2] - 1.0f) < 1e-3f, "moderate cone axis is +Z"); + + // Wide cone (min_dot = cos 87 = 0.052, inside (-0.1, 0.1]): too wide to cull, culling disabled. + const MeshletBufferData wide = x2w::meshlet::build_meshlets(tilted_pair(87.0f * kDeg), indices); + require(wide.bounds.size() == 1, "wide cone is one meshlet"); + require(wide.bounds[0].cone_cutoff > 1.0f, "cone wider than the threshold disables culling"); + + // Just inside the accepted side (min_dot = cos 80 = 0.17 > 0.1): still culls. + const MeshletBufferData edge = x2w::meshlet::build_meshlets(tilted_pair(80.0f * kDeg), indices); + require(edge.bounds[0].cone_cutoff < 1.0f, "cone just under the threshold still culls"); +} + +void test_degenerate_triangle_ignored_for_cone() { + // One real +Z triangle plus a sliver (cross product ~1e-8, squared ~1e-16) wound the other way. + // The sliver must not enter the cone; otherwise the opposing normals cancel and culling is lost. + const float e = 1e-4f; + const std::vector<MeshletVertex> verts{ + make_vertex(0.0f, 0.0f, 0.0f), make_vertex(1.0f, 0.0f, 0.0f), make_vertex(0.0f, 1.0f, 0.0f), + make_vertex(5.0f, 0.0f, 0.0f), make_vertex(5.0f, e, 0.0f), make_vertex(5.0f + e, 0.0f, 0.0f), + }; + const MeshletBufferData data = x2w::meshlet::build_meshlets(verts, {0, 1, 2, 3, 4, 5}); + require(data.bounds.size() == 1, "sliver case is one meshlet"); + require(data.bounds[0].cone_cutoff < 0.01f, "sliver triangle is ignored by the cone"); + require(data.bounds[0].cone_axis[2] > 0.99f, "cone axis follows the real triangle"); +} + +void require_within_limits(const MeshletBufferData& data, std::uint32_t max_vertices, std::uint32_t max_primitives, + std::size_t triangles) { + std::size_t total = 0; + for (const auto& d : data.meshlets) { + require(d.vertex_count > 0 && d.vertex_count <= max_vertices, "meshlet vertex count within requested limit"); + require(d.primitive_count > 0 && d.primitive_count <= max_primitives, + "meshlet primitive count within requested limit"); + total += d.primitive_count; + } + require(total == triangles, "all triangles preserved under small limits"); +} + +void test_small_limits() { + const int grid = 6; + std::vector<MeshletVertex> verts; + for (int y = 0; y <= grid; ++y) + for (int x = 0; x <= grid; ++x) verts.push_back(make_vertex(float(x), float(y), 0.0f)); + std::vector<std::uint32_t> indices; + for (int y = 0; y < grid; ++y) { + for (int x = 0; x < grid; ++x) { + const std::uint32_t v0 = static_cast<std::uint32_t>(y * (grid + 1) + x); + const std::uint32_t v1 = v0 + (grid + 1); + indices.insert(indices.end(), {v0, v1, v1 + 1, v0, v1 + 1, v0 + 1}); + } + } + const std::size_t tris = indices.size() / 3; + require_within_limits(x2w::meshlet::build_meshlets(verts, indices, 3, 126), 3, 126, tris); + require_within_limits(x2w::meshlet::build_meshlets(verts, indices, 64, 1), 64, 1, tris); + require_within_limits(x2w::meshlet::build_meshlets(verts, indices, 4, 2), 4, 2, tris); + require_within_limits(x2w::meshlet::build_meshlets(verts, indices, 256, 256), 256, 256, tris); + require_within_limits(x2w::meshlet::build_meshlets(verts, indices), x2w::meshlet::kMaxMeshletVertices, + x2w::meshlet::kMaxMeshletPrimitives, tris); + + // Triangles that repeat a vertex need fewer slots but must still respect the limit. + const std::vector<std::uint32_t> degenerate{0, 0, 1, 2, 2, 2, 3, 4, 5, 1, 1, 1}; + require_within_limits(x2w::meshlet::build_meshlets(verts, degenerate, 3, 126), 3, 126, degenerate.size() / 3); +} + +void test_negative_controls() { + const std::vector<MeshletVertex> verts{make_vertex(0, 0, 0), make_vertex(0, 1, 0), make_vertex(1, 0, 0)}; + auto expect_throw = [](auto&& fn, const char* what) { + bool threw = false; + try { + fn(); + } catch (const std::invalid_argument&) { + threw = true; + } + require(threw, what); + }; + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1}); }, "non-multiple-of-3 indices rejected"); + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1, 3}); }, "out-of-range vertex index rejected"); + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1, 2}, 0, 10); }, "max_vertices=0 rejected"); + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1, 2}, 1, 10); }, "max_vertices=1 rejected"); + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1, 2}, 2, 10); }, "max_vertices=2 rejected"); + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1, 2}, 257, 10); }, "max_vertices>256 rejected"); + expect_throw([&] { x2w::meshlet::build_meshlets(verts, {0, 1, 2}, 64, 257); }, "max_primitives>256 rejected"); +} + +} // namespace + +int main() { + try { + test_single_triangle(); + test_grid_partitioning(); + test_double_sided_disables_culling(); + test_culling_scene(); + test_cone_width_threshold(); + test_degenerate_triangle_ignored_for_cone(); + test_small_limits(); + test_negative_controls(); + std::puts("meshlet_builder_check: PASS"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "meshlet_builder_check error: %s\n", e.what()); + return 1; + } +} diff --git a/tests/native_absdiff_check.py b/tests/native_absdiff_check.py new file mode 100644 index 0000000000..64e9b31872 --- /dev/null +++ b/tests/native_absdiff_check.py @@ -0,0 +1,175 @@ +"""s_absdiff_i32 in the direct compute path. + + native_absdiff_check.py controls <compile_dxil> <sdk bin dir> + native_absdiff_check.py hardware <native_store_replay> <sdk bin dir> + +RDNA 2 ISA: D = S0 - S1 as a 32-bit signed difference; if D < 0 then D = -D; SCC = D != 0. The difference wraps, +and negating 0x80000000 gives 0x80000000. gfx2hlsl.py and tools/pixel_aot.py lower it the same way. + +The words are encoded with the helpers of the other native fixtures and decode with tools/disasm_rdna2.py. + +The dispatch has two groups of 32 lanes. s24 = group * 0x01000193, so group 0 sees the pairs below as written +and group 1 sees both operands of the register cases XORed with 0x01000193 (equal pairs stay equal). For each +case the program stores the result and SCC (through s_cselect_b32). The operands come from registers set at run +time, except the last two cases, whose S1 is a literal and the inline constant -1. +Before the equal pair, SCC is 1 (the s_xor_b32 before it leaves a non-zero value), so a lowering that kept the +old SCC would show there. + +Each of these mutated references must differ from the expected words: +- a difference that does not wrap (exact integers, then the low 32 bits); +- the unsigned distance max(S0, S1) - min(S0, S1); +- 0x80000000 saturated to 0x7fffffff; +- the difference without the absolute value; +- SCC left unchanged. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +STRIDE = 16 +MASK = 0xFFFFFFFF +LITERAL, ZERO, ONE, MINUS_ONE = 255, 128, 129, 193 +GROUP_XOR = 0x01000193 +# SOP1 and SOP2 opcodes +S_MOV = 3 +S_CSELECT, S_XOR, S_LSHL, S_MUL, S_ABSDIFF = 10, 18, 30, 38, 44 +# VOP2 opcodes +V_LSHLREV, V_ADD = 0x1A, 0x25 +# Register pairs (S0, S1): ordinary, swapped, the wrap at 0x80000000 and the equal pair. +PAIRS = [(5, 3), (3, 5), (0x80000000, 0), (0x7FFFFFFF, 0xFFFFFFFF), (0x80000000, 1), (7, 7)] +# Constant S1: a literal and the inline constant -1. +LITERAL_CASE = (0x00000010, 0xFFFFFFF0) +INLINE_CASE = 0x7FFFFFFE + + +def mubuf_store(data, offset): + # buffer_store_dword v<data>, v8, s[32:35], 0 offen offset:<offset> + return [0xE0701000 | offset, 0x80080008 | data << 8] + + +def program(): + words = [sop1(S_MOV, 20, 4), sop1(S_MOV, 21, ZERO), # s[20:21] = the table pointer + 0xF4080000 | 32 << 6 | 10, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(S_LSHL, 7, 5, 139), # s7 = group * 2048 bytes + vop2(V_LSHLREV, 8, 134, 0), # v8 = lane * 64 bytes + vop2(V_ADD, 8, 7, 8), # v8 += s7 + scalar(S_MUL, 24, 5, LITERAL), GROUP_XOR] # s24 = group * 0x01000193 + out = 10 + for a, b in PAIRS: + words += [scalar(S_XOR, 9, LITERAL, 24), a, # s9 = a ^ s24 + scalar(S_XOR, 10, LITERAL, 24), b, # s10 = b ^ s24 + scalar(S_ABSDIFF, 11, 9, 10), + scalar(S_CSELECT, 12, ONE, ZERO), + vmove(out, 11), vmove(out + 1, 12)] + out += 2 + words += [scalar(S_XOR, 9, LITERAL, 24), LITERAL_CASE[0], + scalar(S_ABSDIFF, 11, 9, LITERAL), LITERAL_CASE[1], + scalar(S_CSELECT, 12, ONE, ZERO), + vmove(out, 11), vmove(out + 1, 12), + scalar(S_XOR, 9, LITERAL, 24), INLINE_CASE, + scalar(S_ABSDIFF, 11, 9, MINUS_ONE), + scalar(S_CSELECT, 12, ONE, ZERO), + vmove(out + 2, 11), vmove(out + 3, 12)] + words.append(0xBF8CC07F) # s_waitcnt lgkmcnt(0) + for k in range(STRIDE): + words += mubuf_store(10 + k, 4 * k) + return words + [0xBF810000] # s_endpgm + + +def signed(v): + return v - (1 << 32) if v & 0x80000000 else v + + +def absdiff(a, b, mutation=None): + if mutation == 'no wrap': + return abs(signed(a) - signed(b)) & MASK + if mutation == 'unsigned': + return max(a, b) - min(a, b) + d = (a - b) & MASK + if mutation == 'no abs': + return d + d = (-d) & MASK if d & 0x80000000 else d + if mutation == 'saturated' and d == 0x80000000: + return 0x7FFFFFFF + return d + + +def operands(group): + key = group * GROUP_XOR + cases = [(a ^ key, b ^ key) for a, b in PAIRS] + return cases + [(LITERAL_CASE[0] ^ key, LITERAL_CASE[1]), (INLINE_CASE ^ key, MASK)] + + +def group_words(group, mutation=None): + words = [] + for a, b in operands(group): + d = absdiff(a, b, mutation) + words += [d, 1 if mutation == 'SCC unchanged' else int(d != 0)] + return words + + +def reference(mutation=None): + expected = [SENTINEL] * OUTPUT_WORDS + for n in range(64): + base = GUARD_WORDS + n * STRIDE + expected[base:base + STRIDE] = group_words(n // 32, mutation) + return expected + + +def compile_words(cli, sdk, work, root, words): + marker = request(work, root, words) + output = marker.with_suffix('.cso') + return subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True), output + + +def controls(cli, sdk, work, root): + result, output = compile_words(cli, sdk, work, root, program()) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + for group in (0, 1): + words = group_words(group) + assert 0x80000000 in words[::2] and 0x7FFFFFFF in words[::2], 'both wrap results must be present' + assert words[11] == 0 and words[10] == 0, 'the equal pair must give 0 and SCC 0' + expected = reference() + for label in ('no wrap', 'unsigned', 'saturated', 'no abs', 'SCC unchanged'): + assert reference(label) != expected, label + print('compiled; the unwrapped, unsigned, saturated, signed-difference and SCC-unchanged references each differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print(f's_absdiff_i32: {64 * STRIDE} words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_add_sub_sat_check.py b/tests/native_add_sub_sat_check.py new file mode 100644 index 0000000000..7ab26985c7 --- /dev/null +++ b/tests/native_add_sub_sat_check.py @@ -0,0 +1,143 @@ +"""v_add_nc_i32, v_sub_nc_i32 and the clamp forms of v_add_nc_u32, v_sub_nc_u32 and v_subrev_nc_u32 in the direct +compute path (#3009). + + native_add_sub_sat_check.py controls <compile_dxil> <sdk bin dir> + native_add_sub_sat_check.py hardware <native_store_replay> <sdk bin dir> + +The signed forms wrap like the unsigned ones; clamp saturates, signed for v_*_nc_i32 and unsigned for v_*_nc_u32. +LLVM 15.0.7 selects exactly these clamp forms for llvm.sadd.sat, llvm.ssub.sat, llvm.uadd.sat and llvm.usub.sat +(clang -nogpulib -target amdgcn-- -mcpu=gfx1013 -O2 -S). The VOP3 words were assembled with LLVM 15.0.7 +(clang -cc1as, gfx1013); the first prologue words follow native_dpp_quad_check.py, with v8 = 128 * lane and s7 = 4096 * group (32 words +per lane), and the store words follow native_lane_access_check.py. + +Each case sets S0 and S1 by v_mov literals and stores seven results; every lane of two groups stores all cases. +Unclamped, sign-swapped (unsigned saturation for the signed forms and the reverse), saturate-toward-S1 and +unswapped-subrev references must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +CASES = [ + (0x7FFFFFFF, 0x00000001), + (0x80000000, 0x00000001), + (0xFFFFFFFF, 0x80000000), + (0x7FFFFFFF, 0xFFFFFFFF), +] +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] +# v_add_nc_i32 v4 / v_add_nc_i32 v5 clamp / v_sub_nc_i32 v6 / v_sub_nc_i32 v7 clamp / v_add_nc_u32_e64 v9 clamp / +# v_sub_nc_u32_e64 v10 clamp / v_subrev_nc_u32_e64 v11 clamp, each with S0 = v1 and S1 = v2. +OPS = [('add_i32', 0xD77F0004, 4), ('add_i32 clamp', 0xD77F8005, 5), ('sub_i32', 0xD7760006, 6), + ('sub_i32 clamp', 0xD7768007, 7), ('add_u32 clamp', 0xD5258009, 9), ('sub_u32 clamp', 0xD526800A, 10), + ('subrev_u32 clamp', 0xD527800B, 11)] +SOURCES = 0x00020501 +NEG_SOURCES = 0x20020501 # the same operands with neg on S0 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK = 0xFFFFFFFF + + +def program(sources=SOURCES): + code = list(PROLOGUE) + for index, (a, b) in enumerate(CASES): + code += [0x7E0202FF, a, 0x7E0402FF, b] + for _, word, _ in OPS: + code += [word, sources] + for slot, (_, _, vgpr) in enumerate(OPS): + code += [0xE0701000 | (32 * index + 4 * slot), 0x80080008 | vgpr << 8] + return code + [0xBF810000] + + +def signed(x): + return x - (1 << 32) if x & 0x80000000 else x + + +def op(name, a, b, clamp=True, swap_sign=False, toward_b=False, subrev_swap=True): + sat = name.endswith('clamp') and clamp + is_signed = name.endswith('i32') or name.endswith('i32 clamp') + if swap_sign: + is_signed = not is_signed + if name.startswith('subrev') and subrev_swap: + a, b = b, a + if is_signed: + x, y = signed(a), signed(b) + true = x + y if name.startswith('add') else x - y + if sat and not -(1 << 31) <= true < (1 << 31): + sign = (b if toward_b else a) & 0x80000000 + return 0x80000000 if sign else 0x7FFFFFFF + return true & MASK + true = a + b if name.startswith('add') else a - b + if sat and true > MASK: + return MASK + if sat and true < 0: + return 0 + return true & MASK + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(64): + base = GUARD_WORDS + lane * 32 + for index, (a, b) in enumerate(CASES): + for slot, (name, _, _) in enumerate(OPS): + expected[base + 8 * index + slot] = op(name, a, b, **mutation) + return expected + + +def compile_program(cli, sdk, work, root, code, name): + marker = request(work, root, code) + output = marker.with_suffix(name) + return subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True), output + + +def controls(cli, sdk, work, root): + result, output = compile_program(cli, sdk, work, root, program(), '.cso') + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'add i32' in dump and 'sub i32' in dump and 'select i1' in dump, dump + result, _ = compile_program(cli, sdk, work, root, program(NEG_SOURCES), '.neg.cso') + assert result.returncode != 0 and 'v_add_nc_i32 operand modifiers' in result.stdout + result.stderr, ( + result.stdout, result.stderr) + expected = reference() + for label, mutation in (('unclamped', {'clamp': False}), ('signedness swapped', {'swap_sign': True}), + ('saturated toward S1', {'toward_b': True}), + ('subrev without the swap', {'subrev_swap': False})): + assert reference(**mutation) != expected, label + print('compiled seven add/sub forms with saturating selects; a neg modifier is refused; the unclamped, ' + 'signedness-swapped, saturate-toward-S1 and unswapped-subrev references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print('seven add/sub forms: all 2064 words matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_adjacent_srv_check.py b/tests/native_adjacent_srv_check.py new file mode 100644 index 0000000000..12e1708db3 --- /dev/null +++ b/tests/native_adjacent_srv_check.py @@ -0,0 +1,55 @@ +"""Check dynamic SRVs spanning adjacent ranges in a serialized guest root signature.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + # s4 and s5 are the two root tables. s6 holds group.x. The + # candidate span starts at slot 1, group 1 selects slot 2. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), + scalar(0xe, 11, 6, 129), scalar(0x1e, 11, 11, 133), + 0xf408040a, 0x16000020, 0xf408080b, 0xfa000000, + scalar(0x1e, 12, 6, 130), vmove(8, 12), sop1(3, 126, 129), vmove(3, 130), + 0xe0002000, 0x80040103, 0xe0701000, 0x80080108, 0xbf810000] + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 6 << 1) + for name, second, reason in ( + ("append", "SRV(t18, space=2)", ""), + ("null", "SRV(t18, space=2)", ""), + ("reversed", "SRV(t18, space=2, offset=2)", ""), + ("hole", "SRV(t18, space=2, offset=3)", "exceeds its declared root range"), + ("uav", "UAV(u18, space=2, offset=2)", "overlaps a non-SRV root range")): + first = "SRV(t7, offset=1)" + ranges = second + "," + first if name == "reversed" else first + "," + second + src, root = work / "root.hlsl", work / "root.bin" + src.write_text(f'#define SIG "DescriptorTable({ranges}),DescriptorTable(UAV(u0))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + marker = write_request(work, words, root.read_bytes(), sa) + dest = work / (name + ".bin") + mode = "--direct-null-srv" if name == "null" else "--direct" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, mode], + capture_output=True, text=True) + if result.returncode == 77: + sys.exit(77) + if reason: + assert result.returncode and reason in result.stderr and not dest.exists(), result.stderr + continue + assert not result.returncode, (result.stdout, result.stderr) + expected = [0x69696969] * 2064 + expected[8:10] = [0x3f800000 + 256 * slot + 8 for slot in (1, 2)] + if name == "null": + expected[9] = 0 + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Both layouts selected distinct SRVs, a recorded null returned zero, and hole/UAV controls were refused.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_align_bfm_check.py b/tests/native_align_bfm_check.py new file mode 100644 index 0000000000..1dad65de7a --- /dev/null +++ b/tests/native_align_bfm_check.py @@ -0,0 +1,109 @@ +"""v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32 in the direct compute path (#2985). + + native_align_bfm_check.py controls <compile_dxil> <sdk bin dir> + native_align_bfm_check.py hardware <native_store_replay> <sdk bin dir> + +The semantics are those of the gfx2hlsl.py VOP3 table: v_alignbit_b32 returns bits [k + 31 : k] of {S0, S1} with +k = S2[4:0], v_alignbyte_b32 the same with k = 8 * S2[1:0], and both return S1 for k = 0; v_bfm_b32 returns +((1 << S0[4:0]) - 1) << S1[4:0]. All words below were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The dispatch has two groups of 32 lanes. Lane L of group g uses S0 = 0x89abcdef, S1 = 0x01234567 and +S2 = L + 32g, so every shift 0..31 and every byte count appears, and group 1 repeats them with bit 5 set, which +the five-bit field must ignore. v_bfm_b32 takes S0 = S2 and S1 = S2 ^ 0x15. Each lane stores the three results. +References with the zero shift not special-cased, with S0 and S1 exchanged, and with the field not masked must +each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 9 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 4, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v3, s8, v0 / +# v_mov_b32 v1, 0x89abcdef / v_mov_b32 v2, 0x1234567 / v_alignbit_b32 v4, v1, v2, v3 / +# v_alignbyte_b32 v5, v1, v2, v3 / v_xor_b32 v6, 0x15, v3 / v_bfm_b32 v7, v3, v6 / s_waitcnt lgkmcnt(0) / +# buffer_store_dword v4, v5, v7 at v8 + 0, 4, 8 through s[32:35] / s_endpgm +HEX = ('040394be 800395be 0a0808f4200000fa 0589078f 0585088f 84001034 0710104a 0800064a ff02027eefcdab89 ' + 'ff02047e67452301 04004ed501050e04 05004fd501050e04 95060c3a 070063d7030d0200 7fc08cbf ' + '001070e008040880 041070e008050880 081070e008070880 000081bf') +S0, S1 = 0x89ABCDEF, 0x01234567 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def align(high, low, k, zero_special=True): + """Bits [k + 31 : k] of {high, low}. Without the zero special case, a five-bit-masked 32 - k turns k = 0 into + low | high, the result of an unguarded lowering.""" + if k == 0 and not zero_special: + return low | high + return (((high << 32) | low) >> k) & 0xFFFFFFFF + + +def reference(zero_special=True, swapped=False, unmasked=False): + expected = [SENTINEL] * OUTPUT_WORDS + high, low = (S1, S0) if swapped else (S0, S1) + field = 63 if unmasked else 31 + for group in range(2): + for lane in range(32): + s2 = lane + 32 * group + bit = align(high, low, s2 & field, zero_special) + byte = align(high, low, 8 * (s2 & (7 if unmasked else 3)) % 64, zero_special) + bfm = (((1 << (s2 & field)) - 1) << ((s2 ^ 0x15) & field)) & 0xFFFFFFFF + base = GUARD_WORDS + (group * 32 + lane) * 4 + expected[base:base + 3] = [bit, byte, bfm] + return expected + + +def controls(cli, sdk, work, root): + marker = request(work, root, words(HEX)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + expected = reference() + for label, mutant in (('zero shift not special-cased', reference(zero_special=False)), + ('S0 and S1 exchanged', reference(swapped=True)), + ('field not masked to five bits', reference(unmasked=True))): + assert mutant != expected, label + print('compiled; the zero-shift, exchanged-source and unmasked references each differ from the expected words') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not diff, diff[:10] + print('v_alignbit_b32, v_alignbyte_b32 and v_bfm_b32: 192 words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_bitreplicate_exec_check.py b/tests/native_bitreplicate_exec_check.py new file mode 100644 index 0000000000..2adc28ee62 --- /dev/null +++ b/tests/native_bitreplicate_exec_check.py @@ -0,0 +1,109 @@ +"""Direct compute wave32 EXEC bitreplicate readback.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +BITREPLICATE = 0x3B +MOV_B32 = 3 +EXEC_LO, EXEC_HI = 126, 127 +LITERAL = 255 +THREADS = 32 +LANES = 2 * THREADS +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 +CASES = ( + (0xFF00FF00, LITERAL), + (0x0000FFFF, LITERAL), + (5, 128 + 5), + (0xF0F0F0F0, LITERAL), +) + + +def program(value, source, dst=EXEC_LO): + # Table pointer s4, group.x s5. v8 addresses one dword per dispatch lane. + words = [ + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, 128), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[8:11], s[20:21], 32 + scalar(0x1E, 7, 5, 135), # group.x * 128 + vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8), # v8 = group base + local.x * 4 + 0xBF8CC07F, + 0xBF068180, # s_cmp_eq_u32 0, 1 (SCC = 0) + sop1(BITREPLICATE, dst, source), + ] + if source == LITERAL: + words.append(value) + words += [ + 0xE0701000, 0x80080008, # store local.x from v0 under replicated EXEC + sop1(MOV_B32, 6, EXEC_LO), + sop1(MOV_B32, 12, EXEC_HI), + sop1(MOV_B32, EXEC_LO, 193), # restore all 32 lanes + ] + for plane, reg in enumerate((6, 12, 253), start=1): + # Store the saved low word, saved high word and incoming SCC on every lane. + offset = plane * LANES * 4 + words += [vmove(4, reg), 0xE0701000 | offset, 0x80080408] + return words + [0xBF810000] + + +def request(work, root, words): + sa = struct.pack("<7I", 0, 0, 0, THREADS | (1 << 16), 1 | (1 << 20), 0, 0x8A) + return write_request(work, words, root, sa) + + +def reference(value): + lo, hi = (sum(3 << (2 * bit) for bit in range(16) if value & (1 << (bit + start))) + for start in (0, 16)) + masked = tuple(lane if lo & (1 << lane) else SENTINEL for lane in range(THREADS)) + return ((SENTINEL,) * GUARD_WORDS + masked * 2 + (lo,) * LANES + (hi,) * LANES + + (0,) * LANES + (SENTINEL,) * (OUTPUT_WORDS - GUARD_WORDS - 4 * LANES)) + + +def controls(cli, sdk, work, root): + value, source = CASES[0] + marker = request(work, root, program(value, source, dst=9)) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode != 0 and "bitreplicate requires an aligned general scalar pair" in result.stderr, ( + result.stdout, result.stderr) + assert not output.exists(), output + return 0 + + +def hardware(replay, sdk, work, root): + for value, source in CASES: + marker = request(work, root, program(value, source)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = reference(value) + for word, (got, want) in enumerate(zip(actual, expected)): + assert got == want, f"{value:#010x}, word {word}: got {got:#010x}, expected {want:#010x}" + print(f"{value:#010x}: lane stores, saved EXEC, SCC and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_bitscan_check.py b/tests/native_bitscan_check.py new file mode 100644 index 0000000000..e10323cd64 --- /dev/null +++ b/tests/native_bitscan_check.py @@ -0,0 +1,204 @@ +"""32-bit bit counts and bit scans in the direct compute path. + + native_bitscan_check.py controls <compile_dxil> <sdk bin dir> + native_bitscan_check.py hardware <native_store_replay> <sdk bin dir> + +The operations follow the RDNA 2 ISA: +- s_bcnt0_i32_b32 and s_bcnt1_i32_b32 count the zero or one bits of S0 and set SCC to D != 0. +- s_ff0_i32_b32, s_ff1_i32_b32 and v_ffbl_b32 return the index of the first zero or one bit from bit 0. +- s_flbit_i32_b32 and v_ffbh_u32 return the number of bits above the first one bit, counted from bit 31. +- s_flbit_i32 and v_ffbh_i32 do the same for the first bit that differs from the sign bit. +- Every scan returns 0xffffffff when no bit qualifies (so for 0, and for 0xffffffff in the signed and ff0 forms). +- No scan writes SCC. + +The words are encoded with the helpers of the other native fixtures and decode with tools/disasm_rdna2.py to +the listing below. + +The dispatch has two groups of 32 lanes. Lane L of group g holds x = (0x80000000 >> g) >> L (arithmetic) and +z = x ^ mul_u32_u24(L + 32g, 0x9e3779). So group 0 holds negative values down to 0xffffffff, and group 1 holds +single bits down to 0. The scalar inputs are s9 = g * 0xff0f0010 (0 in group 0) and s10 = ~s9. +Each lane stores 16 words: +- the three vector scans of x; +- the three vector scans of z; +- the six scalar results for s9; +- SCC after s_bcnt1 s9 with an s_ff1 in between, so a scan that wrote SCC would show; +- SCC after s_bcnt0 s9; +- s_flbit_i32 s10 and s_ff0 s10. + +Each of these mutated references must differ from the expected words: +- scans that count from the wrong end; +- an unsigned scan in place of the signed one; +- a scan of 0 that returns 32; +- a bit count that leaves SCC alone; +- a scan that writes SCC. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +STRIDE = 16 +MASK = 0xFFFFFFFF +LITERAL, ZERO, ONE = 255, 128, 129 +# SOP1 opcodes +S_MOV, S_NOT, S_BCNT0, S_BCNT1, S_FF0, S_FF1, S_FLBIT, S_FLBIT_I32 = 3, 7, 13, 15, 17, 19, 21, 23 +# SOP2 opcodes +S_CSELECT, S_LSHL, S_LSHR, S_MUL = 10, 30, 32, 38 +# VOP1 opcodes +V_FFBH_U32, V_FFBL, V_FFBH_I32 = 0x39, 0x3A, 0x3B +# VOP2 opcodes +V_MUL_U24, V_LSHLREV, V_ASHRREV, V_XOR, V_ADD = 0x0B, 0x1A, 0x18, 0x1D, 0x25 +VECTOR_SCANS = (V_FFBH_U32, V_FFBL, V_FFBH_I32) + + +def vop1(op, dst, src): + return 0x7E000000 | dst << 17 | op << 9 | src + + +def mubuf_store(data, offset): + # buffer_store_dword v<data>, v8, s[32:35], 0 offen offset:<offset> + return [0xE0701000 | offset, 0x80080008 | data << 8] + + +def program(mutant=None): + words = [sop1(S_MOV, 20, 4), sop1(S_MOV, 21, ZERO), # s[20:21] = the table pointer + 0xF4080000 | 32 << 6 | 10, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(S_LSHL, 7, 5, 139), # s7 = group * 2048 bytes + scalar(S_LSHL, 8, 5, 133), # s8 = group * 32 + vop2(V_LSHLREV, 8, 134, 0), # v8 = lane * 64 bytes + vop2(V_ADD, 8, 7, 8), # v8 += s7 + vop2(V_ADD, 9, 8, 0), # v9 = n = lane + 32 * group + scalar(S_LSHR, 10, LITERAL, 5), 0x80000000, # s10 = 0x80000000 >> group + vmove(2, 10), # v2 = s10 + vop2(V_ASHRREV, 1, 256, 2), # v1 = x = v2 >> lane (arithmetic) + vop2(V_MUL_U24, 3, LITERAL, 9), 0x009E3779, # v3 = mul_u32_u24(n, 0x9e3779) + vop2(V_XOR, 3, 257, 3)] # v3 = z = x ^ v3 + words += [vop1(op, 10 + k, 257) for k, op in enumerate(VECTOR_SCANS)] + words += [vop1(op, 13 + k, 259) for k, op in enumerate(VECTOR_SCANS)] + words += [scalar(S_MUL, 9, 5, LITERAL), 0xFF0F0010, # s9 = group * 0xff0f0010 + sop1(S_NOT, 10, 9), # s10 = ~s9 + sop1(S_BCNT0, 11, 9), + scalar(S_CSELECT, 16, ONE, ZERO), # s16 = SCC after s_bcnt0 + sop1(S_BCNT1, 12, 9), + sop1(S_FF1, 13, 9), # must leave SCC from s_bcnt1 + scalar(S_CSELECT, 17, ONE, ZERO), + sop1(S_FF0, 14, 9), sop1(S_FLBIT, 15, 9), sop1(S_FLBIT_I32, 18, 9), + sop1(S_FLBIT_I32, 19, 10), sop1(S_FF0, 22, 10)] + scalars = (11, 12, 14, 13, 15, 18, 17, 16, 19, 22) + words += [vmove(16 + k, s) for k, s in enumerate(scalars)] + if mutant == 'clamp': + # v_ffbl_b32 v11, v1 clamp: the VOP3 form (opcode 0x180 + the VOP1 opcode) with bit 15 set. + at = words.index(vop1(V_FFBL, 11, 257)) + words[at:at + 1] = [0xD4000000 | (0x180 + V_FFBL) << 16 | 0x8000 | 11, 257] + words.append(0xBF8CC07F) # s_waitcnt lgkmcnt(0) + for k in range(STRIDE): + words += mubuf_store(10 + k, 4 * k) + return words + [0xBF810000] # s_endpgm + + +def first_low(v): + return (v & -v).bit_length() - 1 if v else MASK + + +def first_high(v): + return 32 - v.bit_length() if v else MASK + + +def first_high_signed(v): + return first_high(v ^ MASK if v & 0x80000000 else v) + + +def lane_words(n, mutation=None): + group, lane = divmod(n, 32) + base = 0x80000000 >> group + x = ((base - (1 << 32) if base & 0x80000000 else base) >> lane) & MASK + z = x ^ ((n * 0x9E3779) & MASK) + low, high, signed = first_low, first_high, first_high_signed + if mutation == 'wrong end': + low, high = (lambda v: 31 - first_low(v) if v else MASK), (lambda v: 31 - first_high(v) if v else MASK) + signed = lambda v: 31 - first_high_signed(v) if first_high_signed(v) != MASK else MASK + elif mutation == 'unsigned': + signed = first_high + elif mutation == 'zero is 32': + low, high = (lambda v: first_low(v) if v else 32), (lambda v: first_high(v) if v else 32) + s9 = (group * 0xFF0F0010) & MASK + s10 = s9 ^ MASK + bcnt0, bcnt1 = 32 - bin(s9).count('1'), bin(s9).count('1') + ff1 = low(s9) + scc_bcnt1 = int(bcnt1 != 0) + if mutation == 'scan writes SCC': + scc_bcnt1 = int(ff1 != 0) + scc_bcnt0 = int(bcnt0 != 0) + if mutation == 'count leaves SCC': + scc_bcnt0 = scc_bcnt1 = 0 + return [high(x), low(x), signed(x), high(z), low(z), signed(z), + bcnt0, bcnt1, low(s9 ^ MASK), ff1, high(s9), signed(s9), scc_bcnt1, scc_bcnt0, + signed(s10), low(s10 ^ MASK)] + + +def reference(mutation=None): + expected = [SENTINEL] * OUTPUT_WORDS + for n in range(64): + base = GUARD_WORDS + n * STRIDE + expected[base:base + STRIDE] = lane_words(n, mutation) + return expected + + +def compile_words(cli, sdk, work, root, words): + marker = request(work, root, words) + output = marker.with_suffix('.cso') + return subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True), output + + +def controls(cli, sdk, work, root): + result, output = compile_words(cli, sdk, work, root, program()) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + # The VOP3 form of v_ffbl_b32 with the clamp bit is refused, like the other integer VOP3 modifiers. + result, _ = compile_words(cli, sdk, work, root, program('clamp')) + assert result.returncode and 'direct ALU operand modifiers' in result.stderr, (result.stdout, result.stderr) + xs = [lane_words(n)[:3] for n in range(64)] + assert any(w[0] == MASK for w in xs) and any(w[2] == MASK for w in xs), 'a lane must scan 0 and 0xffffffff' + expected = reference() + for label in ('wrong end', 'unsigned', 'zero is 32', 'count leaves SCC', 'scan writes SCC'): + assert reference(label) != expected, label + print('compiled; clamp refused; the wrong-end, unsigned, zero-is-32, SCC-dropped and SCC-written references ' + 'each differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print(f'bit counts and scans: {64 * STRIDE} words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_buffered_vertex_gpu.cpp b/tests/native_buffered_vertex_gpu.cpp new file mode 100644 index 0000000000..f2b126a69c --- /dev/null +++ b/tests/native_buffered_vertex_gpu.cpp @@ -0,0 +1,250 @@ +#include "desktop_gpu.h" +#include "gfx1013_vertex_id.h" +#include "shader_dxil_compiler.h" +#include "xmem_test_device.h" +#include <algorithm> +#include <array> +#include <chrono> +#include <cmath> +#include <cstring> +#include <fstream> +#include <iterator> + +using Microsoft::WRL::ComPtr; +using Position = std::array<float, 4>; +using Bytes = std::vector<unsigned char>; +using Word = std::uint32_t; +namespace fs = std::filesystem; + +namespace { +template <class T> Bytes bytes_of(const std::vector<T> &input) { + auto begin = reinterpret_cast<const unsigned char *>(input.data()); + return {begin, begin + input.size() * sizeof(T)}; +} +struct Case { + std::string program, bindings; + std::array<Word, 4> entry{}; + std::vector<Bytes> buffers; + Bytes indices; + std::vector<Position> expected; +}; +Case fixture(bool overwrite_descriptor = false) { + Case data; + // Different SGPRs, VB descriptor position, root-table number and byte offset + // from the buffered draw. Use a nonzero base vertex and a vertex byte offset. + std::vector<Word> words{0xbe980308, + 0xbe990380, // s24 = table0, s25 = 0 + 0xbe9a0400, + 0x939bff1b, + 0x00080000, // vertex table s[26:27], mask high + 0xf4080000u | (32u << 6) | 12u, + 0xfa000040, + 0xf4080000u | (40u << 6) | 13u, + 0xfa000000, + 0x4a000002, // v0 += s2 + 0xe03c2004, + 0x800a0600, // x/y/z at stride*id + 4 + 0xf4280000u | (32u << 6) | 16u, + 0xfa000010, // replace descriptor with 4 values + 0xd5030009, + 32u | (262u << 9), // x + constant.x + 0xd54b000a, + 242u | (263u << 9) | (33u << 18) | (1u << 31), // y - constant.y + 0x7e1602f2, // w = 1 + 0xf80008cf, + 0x0b080a09, + 0xf8000201, + 0x80808009, + 0xbf810000}; + if (overwrite_descriptor) { + // Overwrite word 2 of the vertex descriptor before the first vertex load. + const auto load = std::find(words.begin(), words.end(), Word{0xe03c2004}); + words.insert(load, 0xbeaa0380); + } + data.program.assign(reinterpret_cast<const char *>(words.data()), words.size() * sizeof(Word)); + data.entry = {0, 1, 0, 16}; + data.buffers = {bytes_of(std::vector<float>{99, 99, 99, 99, 7, 1, 2, 3, 7, 4, 5, 6, 7, 7, 8, 9}), + bytes_of(std::vector<float>{0, 0, 0, 0, .5f, 1.5f, 2, 1})}; + data.indices = bytes_of(std::vector<std::uint16_t>{1, 0, 2, 2, 0, 1}); + data.expected = {{4.5f, 3.5f, 6, 1}, {1.5f, .5f, 3, 1}, {7.5f, 6.5f, 9, 1}, + {7.5f, 6.5f, 9, 1}, {1.5f, .5f, 3, 1}, {4.5f, 3.5f, 6, 1}}; + data.bindings = "srv 0 buf vb 0\nsrv 1 buf table 0 64\n"; + return data; +} +Bytes read_file(const fs::path &path) { + std::ifstream file(path, std::ios::binary); + if (!file) throw std::runtime_error("missing replay input: " + path.filename().string()); + return {std::istreambuf_iterator<char>(file), {}}; +} +Case load(const fs::path &dir) { + Case data; + auto program = read_file(dir / "program.bin"), bindings = read_file(dir / "bindings.txt"); + data.program.assign(program.begin(), program.end()); + data.bindings.assign(bindings.begin(), bindings.end()); + data.indices = read_file(dir / "indices.bin"); + auto entry = read_file(dir / "entry.bin"), expected = read_file(dir / "positions.bin"); + if (entry.size() != sizeof(data.entry) || expected.empty() || expected.size() % sizeof(Position) || + expected.size() / sizeof(Position) * 2 != data.indices.size()) + throw std::runtime_error("invalid replay dimensions"); + std::memcpy(data.entry.data(), entry.data(), entry.size()); + data.expected.resize(expected.size() / sizeof(Position)); + std::memcpy(data.expected.data(), expected.data(), expected.size()); + for (unsigned i = 0; i < 32; ++i) { + auto path = dir / ("t" + std::to_string(i) + ".bin"); + if (!fs::exists(path)) break; + data.buffers.push_back(read_file(path)); + } + return data; +} +ComPtr<ID3D12Resource> upload(ID3D12Device *device, const Bytes &bytes) { + auto obj = make_buffer(device, bytes.size(), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(obj->Map(0, nullptr, &mapped), "map upload"); + std::memcpy(mapped, bytes.data(), bytes.size()); + obj->Unmap(0, nullptr); + return obj; +} +void verify(ID3D12Device *dev, const Bytes &vs, const Case &data) { + if (data.buffers.empty() || data.buffers.size() > 32) throw std::runtime_error("invalid descriptor count"); + const UINT count = static_cast<UINT>(data.buffers.size()); + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, count, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants.Num32BitValues = 4; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + D3D12_ROOT_SIGNATURE_DESC root_desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT}; + ComPtr<ID3DBlob> serialized; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr), + "serialize SO root"); + ComPtr<ID3D12RootSignature> root; + check(dev->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), + IID_PPV_ARGS(&root)), + "SO root"); + D3D12_SO_DECLARATION_ENTRY output{0, "SV_Position", 0, 0, 4, 0}; + const UINT stride = sizeof(Position); + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.VS = {vs.data(), vs.size()}; + pso.StreamOutput = {&output, 1, &stride, 1, D3D12_SO_NO_RASTERIZED_STREAM}; + pso.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso.RasterizerState.DepthClipEnable = TRUE; + pso.SampleMask = UINT_MAX; + pso.SampleDesc.Count = 1; + pso.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + ComPtr<ID3D12PipelineState> pipeline; + const auto pso_start = std::chrono::steady_clock::now(); + check(dev->CreateGraphicsPipelineState(&pso, IID_PPV_ARGS(&pipeline)), "SO graphics pipeline"); + const auto pso_time = std::chrono::steady_clock::now() - pso_start; + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + check(dev->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "SRV heap"); + auto dest = heap->GetCPUDescriptorHandleForHeapStart(); + std::vector<ComPtr<ID3D12Resource>> buffers; + for (const auto &bytes : data.buffers) { + if (bytes.empty() || bytes.size() % 4) throw std::runtime_error("invalid raw SRV length"); + buffers.push_back(upload(dev, bytes)); + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Buffer.NumElements = static_cast<UINT>(bytes.size() / 4); + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + dev->CreateShaderResourceView(buffers.back().Get(), &view, dest); + dest.ptr += dev->GetDescriptorHandleIncrementSize(heap_desc.Type); + } + auto ib = upload(dev, data.indices), zero = upload(dev, Bytes(16)); + D3D12_INDEX_BUFFER_VIEW index{ib->GetGPUVirtualAddress(), static_cast<UINT>(data.indices.size()), + DXGI_FORMAT_R16_UINT}; + const UINT64 payload = data.expected.size() * sizeof(Position); + auto out = make_buffer(dev, 16 + payload, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + auto readback = make_buffer(dev, 16 + payload, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands commands(dev, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto *list = commands.list.Get(); + D3D12_QUERY_HEAP_DESC queries{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2, 0}; + ComPtr<ID3D12QueryHeap> timestamps; + check(dev->CreateQueryHeap(&queries, IID_PPV_ARGS(×tamps)), "draw timestamps"); + auto timing = make_buffer(dev, 2 * sizeof(UINT64), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + UINT64 frequency = 0; + check(commands.queue->GetTimestampFrequency(&frequency), "timestamp frequency"); + list->CopyBufferRegion(out.Get(), 0, zero.Get(), 0, 16); + transition(list, out.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_STREAM_OUT); + D3D12_STREAM_OUTPUT_BUFFER_VIEW so{out->GetGPUVirtualAddress() + 16, payload, out->GetGPUVirtualAddress()}; + list->SOSetTargets(0, 1, &so); + list->SetGraphicsRootSignature(root.Get()); + ID3D12DescriptorHeap *heaps[]{heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetGraphicsRoot32BitConstants(0, 4, data.entry.data(), 0); + list->SetGraphicsRootDescriptorTable(1, heap->GetGPUDescriptorHandleForHeapStart()); + list->IASetIndexBuffer(&index); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->EndQuery(timestamps.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0); + list->DrawIndexedInstanced(static_cast<UINT>(data.indices.size() / 2), 1, 0, 0, 0); + list->EndQuery(timestamps.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 1); + list->ResolveQueryData(timestamps.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, timing.Get(), 0); + transition(list, out.Get(), D3D12_RESOURCE_STATE_STREAM_OUT, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(), out.Get()); + commands.submit_and_wait(dev); + void *memory = nullptr; + D3D12_RANGE read{0, static_cast<SIZE_T>(16 + payload)}; + check(readback->Map(0, &read, &memory), "map SO result"); + UINT64 written = 0; + std::memcpy(&written, memory, sizeof(written)); + if (written != payload) throw std::runtime_error("wrong output vertex count"); + const auto *actual = reinterpret_cast<const Position *>(static_cast<const char *>(memory) + 16); + double max_error = 0; + unsigned identical = 0; + for (size_t v = 0; v < data.expected.size(); ++v) + for (unsigned c = 0; c < 4; ++c) { + const float a = actual[v][c], e = data.expected[v][c]; + if (!std::isfinite(a) || !std::isfinite(e) || std::abs(a - e) > 1.e-5f * (std::max)(std::abs(e), 1.0f)) + throw std::runtime_error("position mismatch at vertex " + std::to_string(v) + " component " + + std::to_string(c) + " actual=" + std::to_string(a) + + " expected=" + std::to_string(e)); + identical += !std::memcmp(&a, &e, sizeof(a)); + max_error = (std::max)(max_error, std::abs(double(a) - e)); + } + D3D12_RANGE none{}; + readback->Unmap(0, &none); + D3D12_RANGE time_range{0, 2 * sizeof(UINT64)}; + check(timing->Map(0, &time_range, &memory), "read timestamps"); + const auto *ticks = static_cast<const UINT64 *>(memory); + if (!frequency || ticks[1] < ticks[0]) throw std::runtime_error("invalid GPU timestamps"); + std::printf("pso_ms=%.6f draw_gpu_us=%.6f\n", std::chrono::duration<double, std::milli>(pso_time).count(), + 1e6 * double(ticks[1] - ticks[0]) / frequency); + timing->Unmap(0, &none); + std::printf("%zu indexed vertices, %u/%zu identical components, max absolute error %.9g\n", + data.expected.size(), identical, data.expected.size() * 4, max_error); +} +} // namespace +int wmain(int argc, wchar_t **argv) { + if (argc != 4 && argc != 5) return 2; + try { + bool unmatched = false; + const auto dev = create_device(std::wstring_view(argv[1]) == L"warp", unmatched); + if (!dev) return unmatched ? 1 : 77; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_0}; + if (FAILED(dev->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_0) + return 77; + auto data = argc == 5 ? load(argv[4]) : fixture(); + if (argc == 4) { + bool refused = false; + try { + x2w::translate_gfx1013_buffered_vertex(fixture(true).program); + } catch (const std::runtime_error &error) { + refused = std::strstr(error.what(), "overwritten buffer descriptor") != nullptr; + } + if (!refused) throw std::runtime_error("accepted overwritten vertex descriptor or wrong diagnostic"); + } + const auto program = x2w::translate_gfx1013_buffered_vertex(data.program); + if (program.bindings != data.bindings) throw std::runtime_error("vertex resource manifest mismatch"); + x2w::ShaderDxilCompiler compiler(argv[2]); + verify(dev.Get(), compiler.compile(program.hlsl, L"vs_6_0", argv[3]).dxil, data); + } catch (const std::exception &error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/tests/native_bytewin_store_check.py b/tests/native_bytewin_store_check.py new file mode 100644 index 0000000000..79d82b8974 --- /dev/null +++ b/tests/native_bytewin_store_check.py @@ -0,0 +1,153 @@ +"""Read back direct compute byte-window stores and atomics, and check descriptor refusals.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +LANES = 64 +LANE_BYTES = 16 +PLANE_BYTES = LANES * LANE_BYTES +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 +STORE_OPS = (0xE0701000, 0xE0741000, 0xE07C1000, 0xE0781000) +ATOMIC_ADD = 0xE0C80000 +ATOMIC_ADD_X2 = 0xE1480000 +ATOMIC_UMIN = 0xE0D80000 +ATOMIC_CMPSWAP = 0xE0C40000 +OFFEN, IDXEN, GLC = 0x1000, 0x2000, 0x4000 + + +def request(work, root, program): + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | 1 << 20, 0, 0x8A) + return write_request(work, program, root, sa) + + +def compute_program(*, constant_stride=False, foreign_word=False, oob=0x30000000, ops=STORE_OPS): + # Root table 0 is in s4. Load slot 1 into s[8:11] through s[20:21]. + program = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF4080000 | 8 << 6 | 10, 0xFA000020] + count_word = 10 + stride_word = 9 + if foreign_word: + # Give word 2 a valid byte_count proof, but from slot 2. + program += [0xF4080000 | 12 << 6 | 10, 0xFA000040] + count_word = 14 + stride_word = 13 + program += [ + scalar(0x27, 18, stride_word, 255), 0xE0010, # s_bfe_u32: extract the stride + scalar(0x09, 18, 18, 129), # s_max_u32: clamp the stride to 1 + scalar(0x0E, 9, 9, 255), 0xC000FFFF, # s_and_b32: clear the stride + ] + if constant_stride: + program += [sop1(3, 22, 132)] # Plain SGPR constant 4. + program += [ + scalar(0x26, 10, count_word, 22 if constant_stride else 18), # s_mul_i32 + scalar(0x10, 11, 11, 255), oob, # s_or_b32 + ] + + # v8 = 512 * group.x + 16 * lane.x. The replay view begins after its leading guard. + program += [scalar(0x1E, 7, 5, 137), vop2(0x1A, 8, 132, 0), vop2(0x25, 8, 7, 8)] + for component in range(4): + program.append(vop2(0x25, 2 + component, 129 + component, 8)) + # One 1024-byte plane per width. The last immediate is 3072, within 12 bits. + for plane, opcode in enumerate(ops): + program += [opcode | plane * PLANE_BYTES, 0x80020208] + return program + [0xBF810000] + + +def atomic_program(): + # Each plane uses the same raw UAV for the atomic and its VGPR readback. + program = compute_program(ops=())[:-1] + for plane, opcode in enumerate((ATOMIC_ADD | GLC, ATOMIC_ADD, ATOMIC_UMIN | GLC, ATOMIC_CMPSWAP | GLC)): + offset = plane * PLANE_BYTES + program += [vop2(0x25, 2, 129, 8)] # v2 = lane byte offset + 1 + if plane == 3: + program += [vmove(3, 255), SENTINEL] # v3 is the compare operand. + program += [opcode | OFFEN | offset, 0x80020208, + 0xE0701000 | (offset + 4), 0x80020208] + if plane == 3: + # Retry with a different replacement and the same now-stale compare. + program += [vmove(2, 128), opcode | OFFEN | offset, 0x80020208, + 0xE0701000 | (offset + 8), 0x80020208] + return program + [0xBF810000] + + +def atomic_reference(): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(LANES): + value = LANE_BYTES * lane + 1 + results = ((SENTINEL + value, SENTINEL), + (SENTINEL + value, value), + (min(SENTINEL, value), SENTINEL), + (value, SENTINEL, value)) + for plane, words in enumerate(results): + start = GUARD_WORDS + (plane * PLANE_BYTES + lane * LANE_BYTES) // 4 + expected[start:start + len(words)] = words + return expected + + +def controls(cli, sdk, work, root): + # Manual mutants that must fail: dropping the clamped-stride proof must + # accept the constant; ignoring descriptor identity must accept the foreign word. + for name, program, errors in ( + ("constant stride", compute_program(constant_stride=True), + ("unbound numeric SGPR s10", "non-contiguous resource descriptor")), + ("foreign word 2", compute_program(foreign_word=True), ("non-contiguous resource descriptor",)), + ("wrong OOB bits", compute_program(oob=0x20000000), + ("unbound numeric SGPR s11", "non-contiguous resource descriptor")), + ("indexed atomic through byte window", compute_program(ops=(ATOMIC_ADD | IDXEN,)), + ("non-contiguous resource descriptor",)), + ("64-bit atomic through byte window", compute_program(ops=(ATOMIC_ADD_X2 | OFFEN,)), + ("unsupported buffer atomic width or operation",))): + marker = request(work, root, program) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode and any(error in result.stderr for error in errors), (name, result.stderr) + assert not output.exists(), output + print(f"{name}: refused") + return 0 + + +def hardware(replay, sdk, work, root): + store_expected = [SENTINEL] * OUTPUT_WORDS + for plane, width in enumerate(range(1, 5)): + for lane in range(LANES): + start = GUARD_WORDS + (plane * PLANE_BYTES + lane * LANE_BYTES) // 4 + store_expected[start:start + width] = [LANE_BYTES * lane + j + 1 for j in range(width)] + for name, program, expected in (("stores", compute_program(), store_expected), + ("atomics", atomic_program(), atomic_reference())): + marker = request(work, root, program) + output = work / f"{name}.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for word, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (name, word, hex(got), hex(want)) + print(f"{name}: updated words, untouched words and guards matched") + return 0 + + +def main(mode, tool, sdk, *, checks=None): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + if checks is None: + checks = {"controls": controls, "hardware": hardware} + return checks[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_carry_vcc_hi_check.py b/tests/native_carry_vcc_hi_check.py new file mode 100644 index 0000000000..b507910da6 --- /dev/null +++ b/tests/native_carry_vcc_hi_check.py @@ -0,0 +1,164 @@ +"""Direct compute wave32 carry-out to vcc_hi, with an independent vcc_lo seed.""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import compute, words +from native_image_atomic_check import render + + +SEED = 0x13579BDF +ODD_LANES = 0xAAAAAAAA +END = 0xBF810000 +DIAGNOSTIC = 'unsupported carry mask destination' + + +def vop2(op, dst, src0, src1): + return op << 25 | dst << 17 | src1 << 9 | src0 + + +def vop3b(op, dst, sdst, src0, src1, src2=0): + return [0xD4000000 | op << 16 | sdst << 8 | dst, src0 | src1 << 9 | src2 << 18] + + +def carry_in(sdst): + # v_add_co_ci_u32_e64 v16, sdst, 0, v16, s105 + return vop3b(0x128, 16, sdst, 128, 256 + 16, 105) + + +def program(): + return [ + # s[0:1] is the table. Load the u0 descriptor into s[8:11]. + 0xBE810380, 0xF4080200, 0xFA000000, 0xBF8CC07F, + 0xBE8003FF | 106 << 16, SEED, # s_mov_b32 vcc_lo, seed + vop2(0x1C, 16, 194, 0), # v_or_b32 v16, -2, v0 + *vop3b(0x30F, 17, 105, 129, 256 + 16), # v_add_co_u32 v17, s105, 1, v16 + *carry_in(107), + 0x7E000200 | 18 << 17 | 107, # v_mov_b32 v18, vcc_hi + 0x7E000200 | 19 << 17 | 106, # v_mov_b32 v19, vcc_lo + 0xD5010000 | 20, 128 | 129 << 9 | 107 << 18, # v_cndmask_b32_e64 v20, 0, 1, vcc_hi + *vop3b(0x128, 20, 104, 128, 256 + 20, 107), # v_add_co_ci_u32_e64 v20, s104, 0, v20, vcc_hi + vop2(0x1A, 8, 132, 0), # v_lshlrev_b32 v8, 4, v0 + # buffer_store_dword, offen, s[8:11], offsets 0, 4, and 8. + 0xE0701000, 0x80020008 | 16 << 8, + 0xE0701004, 0x80020008 | 18 << 8, + 0xE0701008, 0x80020008 | 19 << 8, + 0xE070100C, 0x80020008 | 20 << 8, + END, + ] + + +def compile_shader(cli, sdk, work, source, profile): + shader = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', profile, source, shader], + capture_output=True, text=True, timeout=30) + return shader, run + + +def compile_positive(cli, sdk, work): + source = work / 'carry.cs' + source.write_bytes(compute(words(*program()), table=True)) + shader, run = compile_shader(cli, sdk, work, source, 'gfx1013-container-cs') + assert run.returncode == 0 and shader.is_file(), (run.stdout, run.stderr) + return shader + + +def check_shape(dump): + # Follow SSA dependencies through the direct emitter's register loads and stores. + # Treat each ballot result as a distinct source, independent of its predicate. + ballots, extracts, outputs = [], [], [] + values, slots = {}, {} + for line in dump.splitlines(): + # DXC appends a "; ..." comment to intrinsic calls. + line = line.split(";", 1)[0].strip() + store = re.fullmatch(r'store i32 (\S+), i32\* (\S+), align 4', line) + if store: + value, slot = store.groups() + slots[slot] = values.get(value, {value}) + raw = re.fullmatch(r'call void @dx\.op\.rawBufferStore\.i32\(i32 140, %dx\.types\.Handle \S+, ' + r'i32 \S+, i32 undef, i32 (\S+), i32 undef, i32 undef, i32 undef, i8 1, i32 4\)' + r'(?: #\d+)?', line) + if raw: + value = raw[1] + outputs.append(values.get(value, {value})) + assign = re.fullmatch(r'(%[\w.]+) = (.+)', line) + if not assign: + continue + name, rhs = assign.groups() + load = re.fullmatch(r'load i32, i32\* (\S+), align 4', rhs) + ballot = re.fullmatch(r'call %dx\.types\.fouri32 @dx\.op\.waveActiveBallot\(i32 116, i1 (\S+)\)' + r'(?: #\d+)?', rhs) + extract = re.fullmatch(r'extractvalue %dx\.types\.fouri32 (\S+), (\d+)', rhs) + if load: + values[name] = slots.get(load[1], set()) + elif ballot: + ballots.append((name, ballot[1])) + values[name] = {name} + else: + if extract: + extracts.append(extract.groups()) + values[name] = set().union(*(values.get(token, set()) for token in re.findall(r'%[\w.]+', rhs))) + + assert len(ballots) == 4 and len(outputs) == 4, (ballots, outputs, dump) + exec_mask, carry_in_mask, carry_out_mask = [name for name, _ in ballots[:3]] + assert extracts == [(name, '0') for name, _ in ballots], extracts + # The last ballot is the carry-out of the add whose carry-in is vcc_hi. + assert carry_out_mask in values[ballots[3][1]], ballots + assert ballots[0][1] == 'true' and all(pred.startswith('%') for _, pred in ballots[1:]), ballots + assert exec_mask in values[ballots[1][1]], ballots + assert {exec_mask, carry_in_mask} <= values[ballots[2][1]], ballots + assert {carry_in_mask, exec_mask} <= outputs[0] and carry_out_mask not in outputs[0], outputs + assert carry_out_mask in outputs[1] and carry_in_mask not in outputs[1], outputs + assert outputs[2].isdisjoint({carry_in_mask, carry_out_mask}), outputs + assert carry_out_mask in outputs[3] and carry_in_mask not in outputs[3], outputs + assert str(SEED) in outputs[2], outputs + assert 'icmp ult i32' in dump and 'or i1' in dump and 'zext i1' in dump, dump + assert '@waveExchange' not in dump, dump + + +def controls(cli, sdk, work): + shader = compile_positive(cli, sdk, work) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', shader], check=True, + capture_output=True, text=True, timeout=30).stdout + check_shape(dump) + + # Raw requests exercise the narrow wave64 model. FSSM wave64 always selects + # the full model, even with a group of 32 threads. + signature, root = work / 'root.hlsl', work / 'root.bin' + signature.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"\n') + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, signature], + check=True, timeout=30) + for label, threads, wave32, dst in (('full wave64', 64, False, 107), ('narrow wave64', 32, False, 107), + ('m0', 32, True, 124), ('ttmp0', 32, True, 108)): + state = words(0, 0, 0, threads | 1 << 16, 1 | (int(wave32) << 20), 0, 0x8A) + # Make the carry input and VGPR numeric so the narrow-model mutation can lower. + code = [0xBE800380 | 105 << 16, 0x7E0002C1 | 16 << 17, *carry_in(dst), END] + marker = write_request(work, code, root.read_bytes(), state) + output, run = compile_shader(cli, sdk, work, marker, 'gfx1013-direct-cs@0') + assert run.returncode and not output.exists(), (label, run.stdout, run.stderr) + assert f'native compute +0x8: {DIAGNOSTIC}' in run.stderr.splitlines(), (label, run.stderr) + print('wave32 vcc_hi ballot and vcc_lo seed DXIL matched, and all four controls refused') + + +def hardware(cli, sdk, work, renderer, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, (wave.stdout, wave.stderr) + shader = compile_positive(cli, sdk, work) + expected = [0xC5C5C5C5] * 320 + for lane in range(32): + expected[4 * lane:4 * lane + 4] = [0 if lane & 1 else 0xFFFFFFFE, ODD_LANES, SEED, 2 * (lane & 1)] + case = work / 'carry.bin' + case.write_bytes(words(1, *expected)) + run = render(renderer, adapter, '--compute-store-sized-case', shader, case) + assert run.returncode == 0, (run.stdout, run.stderr) + print(run.stdout, end='') + + +if __name__ == '__main__': + mode, cli, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + {'controls': controls, 'hardware': hardware}[mode](cli, sdk, Path(temp), *args) diff --git a/tests/native_compile_dxil_refusals_check.py b/tests/native_compile_dxil_refusals_check.py new file mode 100644 index 0000000000..97f0e6c9e6 --- /dev/null +++ b/tests/native_compile_dxil_refusals_check.py @@ -0,0 +1,297 @@ +"""Diagnostic .fail lifecycle and read-only --refusals summary checks for compile_dxil (#2935). + +usage: + native_compile_dxil_refusals_check.py <compile_dxil> <sdk> +""" +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "tools" / "startup")) + +import gfx2hlsl as G # noqa: E402 +import triage_run # noqa: E402 +from native_rtv_variant_check import FLOAT32, UINT16, UNORM8, pixel_stage, put_variant # noqa: E402 +from native_startup_request_cache_check import ( # noqa: E402 + COMPUTE_GROUP, + COMPUTE_RSRC2, + DECOY_MASKS, + TARGET_MASKS, + VS_WORDS, + compile_compute_root, + compile_graphics_table_root, + compute_program_words, + ps_words, + put_compute_request, + put_graphics_request, + stream_vertex_container, +) +from startup_compute_translate_check import state_a # noqa: E402 + + +def snapshot_tree(root: Path) -> dict[str, tuple[int, int]]: + snap: dict[str, tuple[int, int]] = {} + for p in sorted(root.rglob("*")): + st = p.stat() + snap[p.relative_to(root).as_posix()] = (st.st_size, st.st_mtime_ns) + return snap + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + raise SystemExit(__doc__) + cli = Path(argv[0]) + sdk = Path(argv[1]) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + g_root = compile_graphics_table_root(sdk, work) + c_root = compile_compute_root(sdk, work) + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + + # 1. Batch --requests writes <key>.fail on refusal and removes stale <key>.fail on subsequent success. + cache = work / "batch_cache" + cache.mkdir() + valid_gfx = put_graphics_request(cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + bad_vgpr2 = put_graphics_request(cache, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + bad_decode_gfx = put_graphics_request( + cache, VS_WORDS, struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS + ) + # Pre-seed a stale .fail beside a valid request to verify --requests deletes it upon success. + stale_fail = cache / f"{valid_gfx:016x}.fail" + stale_fail.write_text("stale failure\n", encoding="utf-8") + + g_res = subprocess.run( + [cli, sdk, frontend, "--jobs", "2", "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, + text=True, + ) + assert g_res.returncode != 0 and "requests=3 compiled=1 refused=2" in g_res.stdout, ( + g_res.returncode, g_res.stdout, g_res.stderr + ) + assert (cache / f"{valid_gfx:016x}.txt").is_file() + assert not stale_fail.exists(), "stale .fail survived successful compilation" + for bad_key in (bad_vgpr2, bad_decode_gfx): + fail_file = cache / f"{bad_key:016x}.fail" + assert fail_file.is_file(), f"missing .fail for refused graphics request {bad_key:016x}" + fail_text = fail_file.read_text(encoding="utf-8") + assert fail_text.endswith("\n") and len(fail_text.splitlines()) == 1 and fail_text.strip(), repr(fail_text) + assert not (cache / f"{bad_key:016x}.txt").exists() + assert not (cache / f"{bad_key:016x}.vs.cso").exists() + assert not (cache / f"{bad_key:016x}.ps.cso").exists() + + valid_cs = put_compute_request(cache, c_code, c_root, c_sa) + bad_cs_decode = put_compute_request( + cache, c_code[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), c_root, c_sa + ) + stale_cs_fail = cache / f"{valid_cs:016x}.fail" + stale_cs_fail.write_text("stale compute failure\n", encoding="utf-8") + + c_res = subprocess.run( + [cli, sdk, frontend, "--jobs", "2", "gfx1013-direct-cs@0", "--requests", cache, cache], + capture_output=True, + text=True, + ) + assert c_res.returncode != 0 and "requests=2 compiled=1 refused=1" in c_res.stdout, ( + c_res.returncode, c_res.stdout, c_res.stderr + ) + assert (cache / f"{valid_cs:016x}.txt").is_file() + assert not stale_cs_fail.exists(), "stale compute .fail survived successful compilation" + cs_fail = cache / f"{bad_cs_decode:016x}.fail" + assert cs_fail.is_file() + assert "unknown gfx1013 instruction format" in cs_fail.read_text(encoding="utf-8") + assert not (cache / f"{bad_cs_decode:016x}.txt").exists() + assert not (cache / f"{bad_cs_decode:016x}.cs.cso").exists() + + # Verify triage_run.py ingests and classifies the native .fail files cleanly. + log_dir = work / "logs" + log_dir.mkdir() + (log_dir / "stderr.txt").write_text("", encoding="utf-8") + triage_report = triage_run.triage_run(log_dir, shader_cache=cache) + assert "`X2W_SHADER_CACHE` `.fail` shaders: `3`" in triage_report, triage_report + assert "| 1 | `unsupported pixel entry VGPR` |" in triage_report, triage_report + assert "| 1 | `undecodable word` |" in triage_report, triage_report + assert "| 1 | `compute: undecodable word` |" in triage_report, triage_report + + # Mutate the valid graphics request into a key mismatch and re-run: old .txt must vanish and .fail appear. + (cache / f"req_{valid_gfx:016x}.b").write_bytes(ps_words(2)) + stale_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, + text=True, + ) + assert stale_run.returncode != 0 + assert not (cache / f"{valid_gfx:016x}.txt").exists(), "refused re-run kept stale manifest" + assert "stale pixel input description" in (cache / f"{valid_gfx:016x}.fail").read_text(encoding="utf-8") + + # 2. Read-only --refusals summary across graphics (.a) and slot-67 compute (.c67) requests. + req_dir = work / "refusals_dir" + req_dir.mkdir() + g_ok = put_graphics_request(req_dir, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + # Two distinct VGPR-disabled failures (VGPR 2 and VGPR 4) should normalize and group together. + g_vgpr2 = put_graphics_request(req_dir, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + g_vgpr4 = put_graphics_request(req_dir, VS_WORDS, ps_words(4), g_root, (0x0002, 0x8006)) + # Two undecodable graphics failures at different byte offsets (0 and 4) should group together. + g_dec0 = put_graphics_request(req_dir, VS_WORDS, struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS) + g_dec4 = put_graphics_request( + req_dir, VS_WORDS, struct.pack("<3I", 0xBF800000, 0xFFFFFFFF, 0xBF810000), g_root, DECOY_MASKS + ) + # Unsupported instruction with a distinct hex encoding (s_trap 0x1234 -> 0xbf921234). + g_trap = put_graphics_request( + req_dir, VS_WORDS, struct.pack("<3I", 0xBF921234, 0xF800180F, 0x04040404), g_root, TARGET_MASKS + ) + + c_ok = put_compute_request(req_dir, c_code, c_root, c_sa) + c_dec = put_compute_request( + req_dir, c_code[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000), c_root, c_sa + ) + c_key_bad = put_compute_request(req_dir, c_code, c_root, c_sa, override_key=c_ok ^ 1) + + before_snap = snapshot_tree(req_dir) + r1 = subprocess.run( + [cli, "--refusals", req_dir, "--json"], + capture_output=True, + text=True, + check=True, + ) + r2 = subprocess.run( + [cli, "--refusals", req_dir, "--jobs", "3", "--json"], + capture_output=True, + text=True, + check=True, + ) + r_text = subprocess.run( + [cli, "--refusals", req_dir, "--jobs", "2"], + capture_output=True, + text=True, + check=True, + ) + after_snap = snapshot_tree(req_dir) + assert before_snap == after_snap, "read-only --refusals modified the request directory" + + assert r1.stdout == r2.stdout, (r1.stdout, r2.stdout) + parsed = json.loads(r1.stdout) + assert parsed["graphics"]["examined"] == 6, parsed + assert parsed["graphics"]["no_refusal"] == 1, parsed + assert parsed["graphics"]["refused"] == 5, parsed + gfx_reasons = {row["reason"]: row["count"] for row in parsed["graphics"]["reasons"]} + assert gfx_reasons.get("unsupported pixel entry VGPR N") == 2, gfx_reasons + assert gfx_reasons.get("unknown gfx1013 instruction format at byte N") == 2, gfx_reasons + assert len(gfx_reasons) == 3 and sum(gfx_reasons.values()) == 5, gfx_reasons + + assert parsed["compute"]["examined"] == 3, parsed + assert parsed["compute"]["no_refusal"] == 1, parsed + assert parsed["compute"]["refused"] == 2, parsed + cs_reasons = {row["reason"]: row["count"] for row in parsed["compute"]["reasons"]} + assert cs_reasons == { + "compute request key mismatch": 1, + "unknown gfx1013 instruction format at byte N": 1, + }, cs_reasons + + # Negative control: hex words, PCs, and request keys must not appear in the census output. + for forbidden in ( + f"{g_ok:016x}", + f"{g_vgpr2:016x}", + f"{g_vgpr4:016x}", + f"{g_dec0:016x}", + f"{g_dec4:016x}", + f"{g_trap:016x}", + f"{c_dec:016x}", + f"{c_key_bad:016x}", + "bf921234", + "1234", + "+0x", + ): + assert forbidden not in r1.stdout.lower() and forbidden not in r_text.stdout.lower(), ( + forbidden, r1.stdout, r_text.stdout + ) + + for expected_line in ( + "Graphics requests", + "Requests examined: 6", + "No refusal recorded (not compiled): 1", + "Refused: 5", + "2\tunsupported pixel entry VGPR N", + "2\tunknown gfx1013 instruction format at byte N", + "Compute requests (device slot 67)", + "Compute requests examined: 3", + "No refusal recorded (not compiled): 1", + "Refused: 2", + "1\tcompute request key mismatch", + ): + assert expected_line in r_text.stdout, (expected_line, r_text.stdout) + + # Empty directory is valid and reports 0 examined. + empty_dir = work / "empty" + empty_dir.mkdir() + r_empty = subprocess.run([cli, "--refusals", empty_dir, "--json"], capture_output=True, text=True, check=True) + empty_json = json.loads(r_empty.stdout) + assert empty_json == { + "graphics": {"examined": 0, "no_refusal": 0, "refused": 0, "reasons": []}, + "compute": {"examined": 0, "no_refusal": 0, "refused": 0, "reasons": []}, + }, empty_json + + # RTV variant requests (.rtv): valid + refused variants, read-only guarantee, and same-key dedup. + rtv_dir = work / "rtv_refusals" + rtv_dir.mkdir() + rtv_base = put_graphics_request(rtv_dir, stream_vertex_container(), pixel_stage(), g_root) + rtv_u16, _ = put_variant(rtv_dir, rtv_base, (UINT16, UNORM8)) + rtv_f32, _ = put_variant(rtv_dir, rtv_base, (FLOAT32,)) + rtv_forged, _ = put_variant(rtv_dir, rtv_base, (UINT16,), name_key=0x1111222233334444) + rtv_missing, _ = put_variant(rtv_dir, 0x9999888877776666, (UINT16,)) + rtv_bad_fmt, _ = put_variant(rtv_dir, rtv_base, (7,)) + + rtv_before = snapshot_tree(rtv_dir) + r_rtv1 = subprocess.run([cli, "--refusals", rtv_dir, "--json"], capture_output=True, text=True, check=True) + r_rtv2 = subprocess.run( + [cli, "--refusals", rtv_dir, "--jobs", "2", "--json"], capture_output=True, text=True, check=True + ) + assert snapshot_tree(rtv_dir) == rtv_before, "--refusals modified RTV request directory" + assert r_rtv1.stdout == r_rtv2.stdout, (r_rtv1.stdout, r_rtv2.stdout) + rtv_json = json.loads(r_rtv1.stdout) + assert rtv_json["graphics"]["examined"] == 6, rtv_json + assert rtv_json["graphics"]["no_refusal"] == 3, rtv_json + assert rtv_json["graphics"]["refused"] == 3, rtv_json + for variant_key in (rtv_base, rtv_u16, rtv_f32, rtv_forged, rtv_missing, rtv_bad_fmt): + assert f"{variant_key:016x}" not in r_rtv1.stdout.lower(), (variant_key, r_rtv1.stdout) + + dedupe_dir = work / "rtv_dedupe" + dedupe_dir.mkdir() + dedupe_key = put_graphics_request(dedupe_dir, stream_vertex_container(), pixel_stage(), g_root) + put_variant(dedupe_dir, dedupe_key, (UINT16,), name_key=dedupe_key) + r_dedupe = subprocess.run([cli, "--refusals", dedupe_dir, "--json"], capture_output=True, text=True, check=True) + dedupe_json = json.loads(r_dedupe.stdout) + assert dedupe_json["graphics"] == { + "examined": 1, + "no_refusal": 0, + "refused": 1, + "reasons": [{"reason": "invalid RTV variant request", "count": 1}], + }, dedupe_json + + # 3. Negative controls for invalid --refusals CLI invocations. + bad_file = work / "not_a_dir.txt" + bad_file.write_text("x", encoding="utf-8") + for bad_args in ( + ["--refusals"], + ["--refusals", work / "missing_dir"], + ["--refusals", bad_file], + ["--refusals", req_dir, "--jobs", "0"], + ["--refusals", req_dir, "--jobs", "65"], + ["--refusals", req_dir, "--bogus"], + ): + res = subprocess.run([cli, *bad_args], capture_output=True, text=True) + assert res.returncode != 0 and res.stderr.strip(), (bad_args, res.returncode, res.stdout, res.stderr) + + print("native_compile_dxil_refusals checks: PASS (.fail lifecycle, triage_run classification, and read-only --refusals summary)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_compile_dxil_rekey_check.py b/tests/native_compile_dxil_rekey_check.py new file mode 100644 index 0000000000..390540d99d --- /dev/null +++ b/tests/native_compile_dxil_rekey_check.py @@ -0,0 +1,262 @@ +"""Tests for `compile_dxil --rekey` parity with `tools/startup/shader_cache_rekey.py`.""" +import hashlib +import importlib.util +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +STARTUP = ROOT / 'tools' / 'startup' +REKEY_PY = STARTUP / 'shader_cache_rekey.py' +sys.path.insert(0, str(STARTUP)) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(name, ok, detail=''): + print('%s: %s%s' % ('ok' if ok else 'FAIL', name, (' (%s)' % detail) if detail and not ok else '')) + if not ok: + failures.append(name) + + +def older_revision_module(): + text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + literal = re.compile(r"b'x2w-startup-shader-([0-9]+)(cs)?'") + found = literal.findall(text) + assert sorted(suffix for _, suffix in found) == ['', 'cs'] and len({n for n, _ in found}) == 1 + number = int(found[0][0]) - 1 + module = importlib.util.module_from_spec(importlib.util.spec_from_loader('gfx2hlsl_%d' % number, loader=None)) + module.__file__ = str(STARTUP / 'gfx2hlsl.py') + exec(compile(literal.sub(lambda m: "b'x2w-startup-shader-%d%s'" % (number, m.group(2) or ''), text), + module.__file__, 'exec'), module.__dict__) + return module + + +def graphics(index, layout=b''): + vs = struct.pack('<4I', 0x7e000280 + index, 0x01020304, index, 0xbf810000) + ps = struct.pack('<3I', 0x7e020281, index * 7, 0xbf810000) + parts = {'.b': ps, '.root': b'RTS0 synthetic root %d' % index, '.a': vs} + if layout: + parts['.ia'] = layout + return parts + + +def gkey(module, parts, ps_inputs=None): + return module.pipeline_key(parts['.a'], parts['.b'], parts['.root'], parts.get('.ia', b''), ps_inputs) + + +COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, + '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', + '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} +MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'} +MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root', + '.m57': b'another synthetic mesh'} + + +def write_request(directory, key, parts): + for ext, data in parts.items(): + (directory / ('req_%016x%s' % (key, ext))).write_bytes(data) + + +def write_rtv(directory, base): + text = ('rtv1 %d 28 87' % base).encode('ascii') + key = G.fnv(text) + (directory / ('req_%016x.rtv' % key)).write_bytes(text) + return key + + +def snapshot(directory): + return {p.name: (hashlib.sha256(p.read_bytes()).hexdigest(), p.stat().st_mtime_ns) + for p in sorted(directory.iterdir())} + + +def contents(directory): + return {p.name: p.read_bytes() for p in sorted(directory.iterdir())} + + +def run_cpp(exe, *args): + return subprocess.run([str(exe), '--rekey', *[str(a) for a in args]], + capture_output=True, text=True, timeout=60) + + +def check_revision_strings(): + cpp_req = (ROOT / 'src' / 'shader_compute_request.cpp').read_text(encoding='utf-8') + draw_inl = (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') + py_text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-3'): + ok = (token in cpp_req) and (token in draw_inl) and (token in py_text) + check('revision string %s matches across C++ and Python' % token, ok) + + +def main(): + if len(sys.argv) != 2: + print('usage: native_compile_dxil_rekey_check.py <path-to-compile_dxil>', file=sys.stderr) + return 2 + exe = Path(sys.argv[1]) + check('compile_dxil executable exists', exe.is_file(), str(exe)) + check_revision_strings() + + older = older_revision_module() + g1 = graphics(1) + g2 = graphics(2, b'synthetic layout POSITION 0 R32G32B32_FLOAT') + g3 = graphics(3) + psin_masks = (0x0003, 0x000f) + + with tempfile.TemporaryDirectory(prefix='x2w-native-rekey-') as tmp: + tmp = Path(tmp) + src = tmp / 'old_cache' + src.mkdir() + + k1_old = gkey(older, g1) + k2_old = gkey(older, g2) + k3_old = gkey(older, g3, psin_masks) + k1_cur = gkey(G, g1) + k2_cur = gkey(G, g2) + k3_cur = gkey(G, g3, psin_masks) + c_old = older.compute_key(COMPUTE['.c67'], COMPUTE['.data'], COMPUTE['.root'], + COMPUTE['.desc'], COMPUTE['.sa'], COMPUTE['.sb']) + c_cur = G.compute_key(COMPUTE['.c67'], COMPUTE['.data'], COMPUTE['.root'], + COMPUTE['.desc'], COMPUTE['.sa'], COMPUTE['.sb']) + m_old_key = G.mesh57_key(MESH_OLD['.m57'], MESH_OLD['.ps57'], MESH_OLD['.root']) ^ 1 + m_old_cur = G.mesh57_key(MESH_OLD['.m57'], MESH_OLD['.ps57'], MESH_OLD['.root']) + m_cur_key = G.mesh57_key(MESH_CURRENT['.m57'], MESH_CURRENT['.ps57'], MESH_CURRENT['.root']) + + write_request(src, k1_old, g1) + write_request(src, k2_old, g2) + g3_old_parts = dict(g3) + g3_old_parts['.psin'] = ('psin1 %016x ena=0x%04x addr=0x%04x\n' % (k3_old, *psin_masks)).encode('ascii') + write_request(src, k3_old, g3_old_parts) + write_request(src, k1_cur, g1) # duplicate current copy of g1 + write_request(src, c_old, COMPUTE) + write_request(src, m_old_key, MESH_OLD) + write_request(src, m_cur_key, MESH_CURRENT) + old_rtv = write_rtv(src, k1_old) + write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86'}) + + # Non-request outputs and diagnostics that must never be copied. + (src / ('%016x.txt' % k1_old)).write_bytes(b'synthetic manifest\n') + (src / ('%016x.fail' % k2_old)).write_bytes(b'synthetic refusal\n') + (src / ('%016x.vs.cso' % k1_old)).write_bytes(b'DXBC...') + (src / ('%016x.psdep' % k3_old)).write_bytes(b'psin1 ...\n') + + before_src = snapshot(src) + + dst_cpp = tmp / 'dst_cpp' + dst_py = tmp / 'dst_py' + res_cpp = run_cpp(exe, src, dst_cpp, '--jobs', '2') + res_py = subprocess.run([sys.executable, '-B', str(REKEY_PY), str(src), str(dst_py)], + capture_output=True, text=True, timeout=60) + + check('compile_dxil --rekey exits 0', res_cpp.returncode == 0, res_cpp.stdout + res_cpp.stderr) + check('shader_cache_rekey.py exits 0', res_py.returncode == 0, res_py.stdout + res_py.stderr) + check('byte-for-byte parity with shader_cache_rekey.py', + dst_cpp.is_dir() and contents(dst_cpp) == contents(dst_py)) + check('only req_* files copied (no .txt/.fail/.cso/.psdep)', + all(name.startswith('req_') for name in contents(dst_cpp))) + + rtv_cur = G.fnv(('rtv1 %d 28 87' % k1_cur).encode('ascii')) + check('rewritten .psin names new key with preserved masks', + (dst_cpp / ('req_%016x.psin' % k3_cur)).read_bytes() == + ('psin1 %016x ena=0x%04x addr=0x%04x\n' % (k3_cur, *psin_masks)).encode('ascii')) + check('rewritten .rtv names new base key', + rtv_cur != old_rtv and + (dst_cpp / ('req_%016x.rtv' % rtv_cur)).read_bytes() == ('rtv1 %d 28 87' % k1_cur).encode('ascii')) + + check('summary graphics line', + 'graphics: 4 requests, 1 already current -> 3 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary compute line', + 'compute: 1 requests, 0 already current -> 1 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary m57 line', + 'm57: 2 requests, 1 already current -> 2 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary rtv line', + 'rtv variants: 1 requests -> 1 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary m86 line', + 'not re-keyed (own key strings): m86 1' in res_cpp.stdout, res_cpp.stdout) + + expected_pending = sorted({k1_cur, k2_cur, k3_cur, c_cur, m_old_cur, m_cur_key, rtv_cur}) + check('gfx2hlsl.pending_keys recognizes re-keyed cache', + G.pending_keys(str(dst_cpp), False) == expected_pending, + str(G.pending_keys(str(dst_cpp), False))) + + # --jobs 1 matches --jobs 2 + dst_j1 = tmp / 'dst_j1' + res_j1 = run_cpp(exe, src, dst_j1, '--jobs', '1') + check('--jobs 1 produces identical contents to --jobs 2', + res_j1.returncode == 0 and contents(dst_j1) == contents(dst_cpp), res_j1.stderr) + + # Idempotency (second run writes 0 files and touches nothing) + snap_dst = snapshot(dst_cpp) + second = run_cpp(exe, src, dst_cpp) + total_files = len(snap_dst) + check('second run is idempotent (0 written)', + second.returncode == 0 and ('files: 0 written, %d already present' % total_files) in second.stdout, + second.stdout + second.stderr) + check('second run leaves mtimes and contents unchanged', snapshot(dst_cpp) == snap_dst) + + # Re-keying an already current cache preserves every name and reports all current + dst_again = tmp / 'dst_again' + third = run_cpp(exe, dst_cpp, dst_again) + check('re-keying current cache preserves names and reports all current', + third.returncode == 0 and contents(dst_again) == contents(dst_cpp) + and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout + and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, + third.stdout + third.stderr) + + # Incomplete/malformed negative controls (exit 1, write nothing, dst not created) + bad_cases = [ + ('graphics missing .root', 8, lambda d: (d / ('req_%016x.root' % k2_old)).unlink()), + ('graphics psin wrong key', 8, + lambda d: (d / ('req_%016x.psin' % k3_old)).write_bytes( + ('psin1 %016x ena=0x0003 addr=0x000f\n' % (k3_old ^ 1)).encode('ascii'))), + ('graphics psin contradictory masks', 8, + lambda d: (d / ('req_%016x.psin' % k3_old)).write_bytes( + ('psin1 %016x ena=0x0010 addr=0x0001\n' % k3_old).encode('ascii'))), + ('compute missing .sa', 8, lambda d: (d / ('req_%016x.sa' % c_old)).unlink()), + ('mesh57 missing .ps57', 8, lambda d: (d / ('req_%016x.ps57' % m_old_key)).unlink()), + ('truncated .rtv', 8, + lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes(b'rtv1 123')), + ('missing .rtv base', 7, lambda d: (d / ('req_%016x.a' % k1_old)).unlink()), + ] + for label, expected_total, damage in bad_cases: + bad_src = tmp / ('bad_' + label.replace(' ', '_').replace('.', '')) + bad_dst = tmp / ('out_' + label.replace(' ', '_').replace('.', '')) + shutil.copytree(src, bad_src) + damage(bad_src) + res = run_cpp(exe, bad_src, bad_dst) + check('%s exits 1' % label, res.returncode == 1, '%d %s' % (res.returncode, res.stderr)) + check('%s reports failure count without writing' % label, + ('error: 1 of %d requests are incomplete or unreadable; nothing written' % expected_total) in res.stderr + and not bad_dst.exists(), + res.stderr) + + # CLI negative controls (exit 2) + reg_file = tmp / 'regular_file.txt' + reg_file.write_bytes(b'not a dir') + cli_cases = [ + ('src == dst', [src, src]), + ('missing args', [src]), + ('extra args', [src, tmp / 'x', tmp / 'y']), + ('unknown flag', [src, tmp / 'x', '--bogus']), + ('missing src dir', [tmp / 'does_not_exist', tmp / 'x']), + ('dst is regular file', [src, reg_file]), + ('jobs 0', [src, tmp / 'x', '--jobs', '0']), + ('jobs 65', [src, tmp / 'x', '--jobs', '65']), + ] + for label, cli_args in cli_cases: + res = run_cpp(exe, *cli_args) + check('CLI %s exits 2' % label, res.returncode == 2, '%d %s' % (res.returncode, res.stderr)) + + check('old cache completely unchanged', snapshot(src) == before_src) + + print('%d failed' % len(failures) if failures else 'all checks passed') + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/native_compile_dxil_watch_check.py b/tests/native_compile_dxil_watch_check.py new file mode 100644 index 0000000000..a8bbbbb973 --- /dev/null +++ b/tests/native_compile_dxil_watch_check.py @@ -0,0 +1,439 @@ +"""Continuous and one-shot --watch mode checks for compile_dxil (#2935). + +usage: + native_compile_dxil_watch_check.py <compile_dxil> <sdk> +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import time + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "tools" / "startup")) + +import gfx2hlsl as G # noqa: E402 +from native_direct_container_check import patched_pixel, publish as publish_raw, vertex as container_vertex, words as raw_words # noqa: E402 +from native_rtv_variant_check import FLOAT32, UINT16, UNORM8, put_variant # noqa: E402 +from native_startup_request_cache_check import ( # noqa: E402 + COMPUTE_GROUP, + COMPUTE_RSRC2, + DECOY_MASKS, + TARGET_MASKS, + VS_WORDS, + compile_compute_root, + compile_graphics_table_root, + compute_program_words, + describe_psin, + ps_words, + put_compute_request, + put_graphics_request, +) +from startup_compute_translate_check import state_a # noqa: E402 + + +def touch(path: Path, data: bytes | None = None, mtime: float | None = None) -> None: + if data is not None: + path.write_bytes(data) + if mtime is not None: + os.utime(path, (mtime, mtime)) + + +def wait_for(predicate, timeout: float = 20.0) -> bool: + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.05) + return predicate() + + +def run_once(cli: Path, sdk: Path, frontend: Path, req_dir: Path, jobs: int = 1) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [cli, "--watch", sdk, frontend, req_dir, "--jobs", str(jobs), "--once"], + capture_output=True, + text=True, + timeout=60, + ) + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + raise SystemExit(__doc__) + cli = Path(argv[0]) + sdk = Path(argv[1]) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + g_root = compile_graphics_table_root(sdk, work) + c_root = compile_compute_root(sdk, work) + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + + # Part 1: --once pending, skip, resume, .psin/.psdep recheck, and parallel equivalence. + d1 = work / "once_serial" + d1.mkdir() + # Incomplete marker without .a / .c67 must be ignored. + (d1 / "req_00000000000000aa.b").write_bytes(ps_words(4)) + (d1 / "req_00000000000000aa.root").write_bytes(g_root) + (d1 / "req_00000000000000bb.data").write_bytes(b"\0" * 16) + + g_key = put_graphics_request(d1, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + g_bad_key = put_graphics_request(d1, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + c_key = put_compute_request(d1, c_code, c_root, c_sa) + + r1 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r1.returncode == 0, (r1.returncode, r1.stdout, r1.stderr) + assert f"{g_key:016x}: compiled graphics" in r1.stdout, r1.stdout + assert f"{c_key:016x}: compiled compute" in r1.stdout, r1.stdout + assert f"{g_bad_key:016x}: refused:" in r1.stdout, r1.stdout + assert "00000000000000aa" not in r1.stdout and "00000000000000bb" not in r1.stdout, r1.stdout + assert not (d1 / "00000000000000aa.fail").exists() + assert (d1 / f"{g_key:016x}.txt").is_file() + assert (d1 / f"{g_key:016x}.psdep").is_file() + assert (d1 / f"{c_key:016x}.txt").is_file() + assert (d1 / f"{g_bad_key:016x}.fail").is_file() + + # Re-running --once retries the .fail (first-pass semantics of --once) and skips complete entries. + txt_mtime = (d1 / f"{g_key:016x}.txt").stat().st_mtime_ns + cs_mtime = (d1 / f"{c_key:016x}.txt").stat().st_mtime_ns + r2 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r2.returncode == 0, (r2.returncode, r2.stdout, r2.stderr) + assert f"{g_key:016x}:" not in r2.stdout and f"{c_key:016x}:" not in r2.stdout, r2.stdout + assert f"{g_bad_key:016x}: refused:" in r2.stdout, r2.stdout + assert (d1 / f"{g_key:016x}.txt").stat().st_mtime_ns == txt_mtime + assert (d1 / f"{c_key:016x}.txt").stat().st_mtime_ns == cs_mtime + + # Seed outputs that satisfy the old watcher's completeness check. + cs_manifest = d1 / f"{c_key:016x}.txt" + cs_cso = d1 / f"{c_key:016x}.cs.cso" + cs_hlsl = d1 / f"{c_key:016x}.cs.hlsl" + current_manifest = cs_manifest.read_bytes() + old_manifest = b"".join(line for line in current_manifest.splitlines(keepends=True) + if not line.startswith(b"native ")) + assert current_manifest.splitlines().count(b"native 1") == 1 + assert not cs_hlsl.exists() + dummy_cso = b"DXBC" + b"\0" * 20 + struct.pack("<III", 36, 1, 0) + for stale_manifest in (old_manifest, old_manifest + b"native 0\n"): + cs_cso.write_bytes(dummy_cso) + cs_manifest.write_bytes(stale_manifest) + refreshed = run_once(cli, sdk, frontend, d1) + assert refreshed.returncode == 0, (refreshed.stdout, refreshed.stderr) + assert f"{c_key:016x}: compiled compute" in refreshed.stdout, refreshed.stdout + assert cs_manifest.read_bytes() == current_manifest + assert cs_cso.read_bytes().startswith(b"DXBC") and cs_cso.read_bytes() != dummy_cso + assert not cs_hlsl.exists() + + cs_hlsl.write_bytes(b"// Python output\n") + cs_cso.write_bytes(dummy_cso) + cs_manifest.write_bytes(old_manifest) + python_outputs = (cs_hlsl, cs_cso, cs_manifest) + before = [(path.read_bytes(), path.stat().st_mtime_ns) for path in python_outputs] + skipped = run_once(cli, sdk, frontend, d1) + assert skipped.returncode == 0, (skipped.stdout, skipped.stderr) + assert f"{c_key:016x}:" not in skipped.stdout, skipped.stdout + assert [(path.read_bytes(), path.stat().st_mtime_ns) for path in python_outputs] == before + + # A Python output with incomplete bytecode is still pending. The native rebuild removes its sidecar, so + # the stand-in no longer reads the new unmarked-looking pair as a Python output. + cs_cso.write_bytes(dummy_cso[:16]) + rebuilt = run_once(cli, sdk, frontend, d1) + assert rebuilt.returncode == 0, (rebuilt.stdout, rebuilt.stderr) + assert f"{c_key:016x}: compiled compute" in rebuilt.stdout, rebuilt.stdout + assert cs_manifest.read_bytes() == current_manifest + assert not cs_hlsl.exists() + + # Corrupting/truncating a stage .cso triggers resume and restores valid DXBC. + vs_cso = d1 / f"{g_key:016x}.vs.cso" + orig_vs = vs_cso.read_bytes() + vs_cso.write_bytes(orig_vs[:16]) + r3 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r3.returncode == 0 and f"{g_key:016x}: compiled graphics" in r3.stdout, (r3.stdout, r3.stderr) + assert vs_cso.read_bytes() == orig_vs + + # Updating .psin mtime newer than .txt (with mismatched .b) rechecks, withdraws .txt, and writes .fail. + (d1 / f"req_{g_key:016x}.b").write_bytes(ps_words(2)) + future = time.time() + 2.0 + touch(d1 / f"req_{g_key:016x}.psin", mtime=future) + r4 = run_once(cli, sdk, frontend, d1, jobs=1) + assert r4.returncode == 0 and f"{g_key:016x}: refused:" in r4.stdout, (r4.stdout, r4.stderr) + assert not (d1 / f"{g_key:016x}.txt").exists() + assert (d1 / f"{g_key:016x}.fail").is_file() + + # Removing .psin when .psdep exists ('lost') forces recheck and withdraws .txt. + d_lost = work / "lost_psin" + d_lost.mkdir() + lost_key = put_graphics_request(d_lost, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, d_lost, jobs=1).returncode == 0 + assert (d_lost / f"{lost_key:016x}.txt").is_file() and (d_lost / f"{lost_key:016x}.psdep").is_file() + (d_lost / f"req_{lost_key:016x}.psin").unlink() + r_lost = run_once(cli, sdk, frontend, d_lost, jobs=1) + assert r_lost.returncode == 0 and f"{lost_key:016x}: refused:" in r_lost.stdout, (r_lost.stdout, r_lost.stderr) + assert not (d_lost / f"{lost_key:016x}.txt").exists() + assert (d_lost / f"{lost_key:016x}.fail").is_file() + + # A 0-byte <key>.psdep next to a published manifest + valid .psin triggers retranslation and restores .psdep. + zero_psdep = d_lost / "zero_psdep" + zero_psdep.mkdir() + z_key = put_graphics_request(zero_psdep, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, zero_psdep, jobs=1).returncode == 0 + z_psdep = zero_psdep / f"{z_key:016x}.psdep" + orig_dep = z_psdep.read_bytes() + assert orig_dep + z_psdep.write_bytes(b"") + r_zero = run_once(cli, sdk, frontend, zero_psdep, jobs=1) + assert r_zero.returncode == 0 and f"{z_key:016x}: compiled graphics" in r_zero.stdout, (r_zero.stdout, r_zero.stderr) + assert z_psdep.read_bytes() == orig_dep + + # A copied slot-57 sidecar can be older than the published stream manifest. + conflict_dir = work / "copied_pixel_sidecar" + conflict_dir.mkdir() + conflict_key = put_graphics_request(conflict_dir, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, conflict_dir, jobs=1).returncode == 0 + conflict_manifest = conflict_dir / f"{conflict_key:016x}.txt" + assert conflict_manifest.is_file() + packed = conflict_dir / f"req_{conflict_key:016x}.ps57in" + packed.write_bytes(b"PSI1" + bytes(8)) + touch(packed, mtime=conflict_manifest.stat().st_mtime - 10) + conflict = run_once(cli, sdk, frontend, conflict_dir, jobs=1) + assert "conflicting stream and slot-57 pixel entry records" in conflict.stdout, conflict.stdout + assert not conflict_manifest.exists() + + # Parallel --once --jobs 2 matches serial --once --jobs 1. + d_serial = work / "cmp_serial" + d_parallel = work / "cmp_parallel" + for d in (d_serial, d_parallel): + d.mkdir() + put_graphics_request(d, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + put_graphics_request(d, VS_WORDS, ps_words(2), g_root, DECOY_MASKS) + put_graphics_request(d, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + put_compute_request(d, c_code, c_root, c_sa) + put_compute_request(d, c_code, c_root, c_sa, override_key=c_key ^ 1) + rs = run_once(cli, sdk, frontend, d_serial, jobs=1) + rp = run_once(cli, sdk, frontend, d_parallel, jobs=2) + assert rs.returncode == 0 and rp.returncode == 0 + assert rs.stdout == rp.stdout, (rs.stdout, rp.stdout) + assert G.pending_keys(str(d_parallel), skip_failed=True) == [] + + # RTV variants in --once: compile base + variants, publish rtv1 manifest + .psdep, and recheck on base .psin update. + d_rtv = work / "once_rtv" + d_rtv.mkdir() + rtv_base = put_graphics_request(d_rtv, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + rtv_u16, rtv_u16_line = put_variant(d_rtv, rtv_base, (UINT16, UNORM8)) + rtv_f32, rtv_f32_line = put_variant(d_rtv, rtv_base, (FLOAT32,)) + rtv_bad, _ = put_variant(d_rtv, rtv_base, (7,)) + r_rtv = run_once(cli, sdk, frontend, d_rtv, jobs=2) + assert r_rtv.returncode == 0, (r_rtv.returncode, r_rtv.stdout, r_rtv.stderr) + for vkey, vline in ((rtv_u16, rtv_u16_line), (rtv_f32, rtv_f32_line)): + assert f"{vkey:016x}: compiled graphics" in r_rtv.stdout, r_rtv.stdout + vtxt = (d_rtv / f"{vkey:016x}.txt").read_text(encoding="ascii") + assert vtxt.splitlines()[-1] == vline, vtxt + assert (d_rtv / f"{vkey:016x}.psdep").is_file() + assert not (d_rtv / f"{vkey:016x}.fail").exists() + assert f"{rtv_bad:016x}: refused:" in r_rtv.stdout and (d_rtv / f"{rtv_bad:016x}.fail").is_file() + assert G.pending_keys(str(d_rtv), skip_failed=True) == [] + + # Updating the base request's .psin (with mismatched .b) rechecks both the base and its .rtv variants. + (d_rtv / f"req_{rtv_base:016x}.b").write_bytes(ps_words(2)) + touch(d_rtv / f"req_{rtv_base:016x}.psin", mtime=time.time() + 2.0) + r_rtv_recheck = run_once(cli, sdk, frontend, d_rtv, jobs=2) + assert r_rtv_recheck.returncode == 0, (r_rtv_recheck.returncode, r_rtv_recheck.stdout, r_rtv_recheck.stderr) + for key in (rtv_base, rtv_u16, rtv_f32): + assert f"{key:016x}: refused:" in r_rtv_recheck.stdout, r_rtv_recheck.stdout + assert not (d_rtv / f"{key:016x}.txt").exists() + assert (d_rtv / f"{key:016x}.fail").is_file() + + # Issue #3133: sidecar content changes or contradictory .ps57in with preserved/older mtimes must invalidate. + # Contradictory .ps57in appearing with older mtime vs newer mtime must withdraw stale .txt identically. + outcomes_ps57 = [] + for label, offset in (("older", -60.0), ("newer", 10.0)): + d_cmp = work / f"ps57_contradict_{label}" + d_cmp.mkdir() + s_key = put_graphics_request(d_cmp, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + r_pub = run_once(cli, sdk, frontend, d_cmp, jobs=1) + assert r_pub.returncode == 0 and f"{s_key:016x}: compiled graphics" in r_pub.stdout, r_pub.stdout + txt_path = d_cmp / f"{s_key:016x}.txt" + fail_path = d_cmp / f"{s_key:016x}.fail" + assert txt_path.is_file() and (d_cmp / f"{s_key:016x}.psdep").is_file() + # Unchanged-input cache-hit control before adding contradictory .ps57in. + txt_ns = txt_path.stat().st_mtime_ns + r_hit = run_once(cli, sdk, frontend, d_cmp, jobs=1) + assert r_hit.returncode == 0 and f"{s_key:016x}:" not in r_hit.stdout and txt_path.stat().st_mtime_ns == txt_ns + touch( + d_cmp / f"req_{s_key:016x}.ps57in", + b"PSI1" + struct.pack("<II", *DECOY_MASKS), + mtime=txt_path.stat().st_mtime + offset, + ) + r_bad = run_once(cli, sdk, frontend, d_cmp, jobs=1) + assert r_bad.returncode == 0 and not txt_path.exists() and fail_path.is_file(), (label, r_bad.stdout, r_bad.stderr) + assert f"{s_key:016x}: refused: conflicting stream and slot-57 pixel entry records" in r_bad.stdout, r_bad.stdout + outcomes_ps57.append((r_bad.stdout, fail_path.read_text(encoding="utf-8"))) + assert outcomes_ps57[0] == outcomes_ps57[1], outcomes_ps57 + + # Changed .psin content preserving an older mtime must withdraw stale .txt and report conflict/mismatch. + d_psin_mtime = work / "psin_preserved_mtime" + d_psin_mtime.mkdir() + pm_key = put_graphics_request(d_psin_mtime, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + assert run_once(cli, sdk, frontend, d_psin_mtime, jobs=1).returncode == 0 + pm_txt = d_psin_mtime / f"{pm_key:016x}.txt" + older_t = pm_txt.stat().st_mtime - 60.0 + touch( + d_psin_mtime / f"req_{pm_key:016x}.psin", + describe_psin(pm_key, DECOY_MASKS).encode("ascii"), + mtime=older_t, + ) + r_pm = run_once(cli, sdk, frontend, d_psin_mtime, jobs=1) + assert r_pm.returncode == 0 and not pm_txt.exists() and (d_psin_mtime / f"{pm_key:016x}.fail").is_file() + assert f"{pm_key:016x}: refused: stale pixel input description: graphics request key mismatch" in r_pm.stdout, r_pm.stdout + + # Slot-57 .ps57in-only unchanged cache-hit control and changed-content preserved-mtime regression. + d_s57 = work / "ps57_preserved_mtime" + idx57 = work / "index57" + frontend57 = work / "frontend57" + idx57.mkdir() + vp57 = [0x7E0002F2, 0xF80008CF, 0, 0xF800020F, 0, 0xF800021F, 0, 0xBF810000] + (idx57 / "varying.cdxil").write_bytes(container_vertex(program=vp57)) + interp57 = lambda attr, ch, op, dst, src: 0xC8000000 | dst << 18 | op << 16 | attr << 10 | ch << 8 | src + prefix57 = [0xD5800000, 255, 17, 0xD5800000, 255, 23] + tmpl57 = prefix57 + [interp57(0, 0, 0, 4, 0), interp57(0, 0, 1, 4, 1)] + attrs57 = [(6, row, 15, row, 0, 0, row, 2) for row in range(2)] + (idx57 / "smooth.cdxil").write_bytes(patched_pixel(len(tmpl57), tmpl57, input_address=2, attributes=attrs57)) + subprocess.run([cli, "--index-graphics-interfaces", idx57, frontend57], check=True, capture_output=True) + root57 = b"DXBC" + bytes(16) + raw_words(1, 68, 1, 36) + b"RTS0" + raw_words(24, 2, 0, 24, 0, 24, 0) + code57 = raw_words(*tmpl57, interp57(0, 1, 2, 5, 2), 0xF800180F, 0x05040504, 0xBF810000) + k57 = publish_raw(d_s57, code57, raw_words(*vp57), root57, slot57_inputs=(2, 1)) + ps57_bytes = b"PSI1" + struct.pack("<II", 2, 1) + assert run_once(cli, sdk, frontend57, d_s57, jobs=1).returncode == 0 + txt57 = d_s57 / f"{k57}.txt" + assert txt57.is_file() and (d_s57 / f"{k57}.psdep").read_bytes() == ps57_bytes + txt57_ns = txt57.stat().st_mtime_ns + r57_hit = run_once(cli, sdk, frontend57, d_s57, jobs=1) + assert r57_hit.returncode == 0 and f"{k57}:" not in r57_hit.stdout and txt57.stat().st_mtime_ns == txt57_ns + touch( + d_s57 / f"req_{k57}.ps57in", + b"PSI1" + struct.pack("<II", 2, 2), + mtime=txt57.stat().st_mtime - 60.0, + ) + r57_bad = run_once(cli, sdk, frontend57, d_s57, jobs=1) + assert r57_bad.returncode == 0 and not txt57.exists() and (d_s57 / f"{k57}.fail").is_file() + assert f"{k57}: refused: stale pixel input description: graphics request key mismatch" in r57_bad.stdout, r57_bad.stdout + + # RTV variant must also withdraw when base gains contradictory .ps57in with older mtime. + d_rtv57 = work / "rtv_ps57_older" + d_rtv57.mkdir() + b57 = put_graphics_request(d_rtv57, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + v57, _ = put_variant(d_rtv57, b57, (UINT16, UNORM8)) + assert run_once(cli, sdk, frontend, d_rtv57, jobs=2).returncode == 0 + min_txt_mtime = min((d_rtv57 / f"{k:016x}.txt").stat().st_mtime for k in (b57, v57)) + touch(d_rtv57 / f"req_{b57:016x}.ps57in", b"PSI1" + struct.pack("<II", *DECOY_MASKS), mtime=min_txt_mtime - 60.0) + r_rtv57 = run_once(cli, sdk, frontend, d_rtv57, jobs=2) + assert r_rtv57.returncode == 0 + for key in (b57, v57): + assert not (d_rtv57 / f"{key:016x}.txt").exists() and (d_rtv57 / f"{key:016x}.fail").is_file() + assert f"{key:016x}: refused:" in r_rtv57.stdout and "conflicting stream and slot-57 pixel entry records" in r_rtv57.stdout, r_rtv57.stdout + + # Part 2: Live background --watch process retries pre-existing .fail once, skips unchanged .fail, + # translates newly written graphics/compute requests, and clears .fail when fixed. + wdir = work / "live_watch" + wdir.mkdir() + now = time.time() + stale_key = put_graphics_request(wdir, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)) + touch(wdir / f"req_{stale_key:016x}.a", mtime=now - 20.0) + stale_fail = wdir / f"{stale_key:016x}.fail" + touch(stale_fail, b"stale reason\n", mtime=now - 10.0) + + watch = subprocess.Popen( + [cli, "--watch", sdk, frontend, wdir, "--jobs", "2", "--interval", "50"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + assert wait_for( + lambda: stale_fail.exists() and "unsupported pixel entry VGPR 2" in stale_fail.read_text(encoding="utf-8") + ), "watcher did not retry pre-existing .fail on first pass" + + # Write a new graphics request (initially tampered .b so it refuses, then fixed to the same key). + mut_key = G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS) + stem = wdir / f"req_{mut_key:016x}" + stem.with_suffix(".b").write_bytes(ps_words(2)) + stem.with_suffix(".root").write_bytes(g_root) + stem.with_suffix(".psin").write_bytes(describe_psin(mut_key, TARGET_MASKS).encode("ascii")) + stem.with_suffix(".a").write_bytes(VS_WORDS) + + mut_fail = wdir / f"{mut_key:016x}.fail" + assert wait_for(lambda: mut_fail.exists()), "watcher did not emit .fail for newly written refused request" + first_fail_ns = mut_fail.stat().st_mtime_ns + stale_fail_ns = stale_fail.stat().st_mtime_ns + time.sleep(0.35) + assert mut_fail.stat().st_mtime_ns == first_fail_ns, "watcher rewrote unchanged .fail on subsequent pass" + assert stale_fail.stat().st_mtime_ns == stale_fail_ns, "watcher rewrote stale .fail on subsequent pass" + + # Fix the refused request with newer mtime: watcher must compile it and remove .fail. + future2 = time.time() + 2.0 + touch(stem.with_suffix(".b"), ps_words(4), mtime=future2) + touch(stem.with_suffix(".a"), VS_WORDS, mtime=future2) + mut_txt = wdir / f"{mut_key:016x}.txt" + assert wait_for(lambda: mut_txt.exists() and not mut_fail.exists()), ( + "watcher did not recover fixed request or remove .fail" + ) + assert (wdir / f"{mut_key:016x}.vs.cso").read_bytes().startswith(b"DXBC") + assert (wdir / f"{mut_key:016x}.ps.cso").read_bytes().startswith(b"DXBC") + + # Write a valid .rtv variant and an invalid .rtv variant while the watcher is running. + live_rtv, live_rtv_line = put_variant(wdir, mut_key, (UINT16, UNORM8)) + live_rtv_bad, _ = put_variant(wdir, mut_key, (7,)) + live_rtv_txt = wdir / f"{live_rtv:016x}.txt" + live_rtv_fail = wdir / f"{live_rtv_bad:016x}.fail" + assert wait_for(lambda: live_rtv_txt.exists() and live_rtv_fail.exists()), ( + "watcher did not process newly written .rtv variants" + ) + assert live_rtv_txt.read_text(encoding="ascii").splitlines()[-1] == live_rtv_line + assert (wdir / f"{live_rtv:016x}.vs.cso").read_bytes().startswith(b"DXBC") + assert (wdir / f"{live_rtv:016x}.ps.cso").read_bytes().startswith(b"DXBC") + + # Write a new compute request while the watcher is running. + live_cs = put_compute_request(wdir, c_code, c_root, c_sa) + live_cs_txt = wdir / f"{live_cs:016x}.txt" + assert wait_for(lambda: live_cs_txt.exists()), "watcher did not compile newly written compute request" + assert (wdir / f"{live_cs:016x}.cs.cso").read_bytes().startswith(b"DXBC") + assert not (wdir / f"{live_cs:016x}.fail").exists() + assert watch.poll() is None, "watcher exited unexpectedly" + finally: + watch.kill() + out, err = watch.communicate(timeout=20) + + assert not err.strip(), f"unexpected watcher stderr: {err!r}" + assert f"{stale_key:016x}: refused:" in out, out + assert f"{mut_key:016x}: refused:" in out and f"{mut_key:016x}: compiled graphics" in out, out + assert f"{live_cs:016x}: compiled compute" in out, out + + # Part 3: CLI negative controls. + bad_file = work / "not_a_dir" + bad_file.write_text("x", encoding="utf-8") + for bad_args in ( + ["--watch"], + ["--watch", sdk, frontend], + ["--watch", work / "missing_sdk", frontend, wdir, "--once"], + ["--watch", sdk, frontend, work / "missing_req", "--once"], + ["--watch", sdk, frontend, bad_file, "--once"], + ["--watch", sdk, frontend, wdir, "--interval", "5", "--once"], + ["--watch", sdk, frontend, wdir, "--interval", "60001", "--once"], + ["--watch", sdk, frontend, wdir, "--interval", "abc", "--once"], + ["--watch", sdk, frontend, wdir, "--jobs", "0", "--once"], + ["--watch", sdk, frontend, wdir, "--jobs", "65", "--once"], + ["--watch", sdk, frontend, wdir, "--bogus", "--once"], + ): + res = subprocess.run([cli, *bad_args], capture_output=True, text=True) + assert res.returncode != 0 and res.stderr.strip(), (bad_args, res.returncode, res.stdout, res.stderr) + + print("native_compile_dxil_watch checks: PASS (--once controls, resume/recheck, live --watch retry/skip/recovery, and CLI negative controls)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_compute_clear_check.py b/tests/native_compute_clear_check.py new file mode 100644 index 0000000000..9d1215608d --- /dev/null +++ b/tests/native_compute_clear_check.py @@ -0,0 +1,69 @@ +"""Build a two-table compute request with source-generated instructions and an SDK root signature.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + + +def write_request(work, words, root, sa=None): + code = struct.pack(f"<{len(words)}I", *words) + data = b"synthetic" + if sa is None: + sa = struct.pack("<7I", 0, 0, 0, 32 | (8 << 16), 1 | (1 << 20), 0, (6 << 1) | (1 << 10)) + desc = struct.pack("<12Q", 0, 0, len(sa), 0, 0, 0, len(code), 0, len(data), 0, 0, 0) + parts = {".c67":code, ".data":data, ".root":root, ".desc":desc, ".sa":sa, ".sb":b""} + payload = b"x2w-startup-shader-28cs" + b"".join(struct.pack("<Q", len(p))+p for p in parts.values()) + key = 1469598103934665603 + for byte in payload: + key = (key ^ byte)*1099511628211 & 0xffffffffffffffff + marker = work/f"req_{key:016x}.c67" + for suffix, part in parts.items(): + marker.with_suffix(suffix).write_bytes(part) + return marker + + +def main(exe, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + root_src = work/"root.hlsl" + root_src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8)),DescriptorTable(UAV(u8,numDescriptors=8))"') + root_file = work/"root.bin" + subprocess.run([Path(sdk)/"dxc.exe","-T","rootsig_1_1","-E","SIG","-Fo",root_file,root_src],check=True) + root = root_file.read_bytes() + # s20:21 is table 0. Load two descriptors into s32:35 and s36:39. + mov = lambda dst, src: 0xbe800300 | dst<<16 | src + descriptor = lambda dst, off: [0xf4080000 | dst<<6 | 10, 0xfa000000 | off] + store = lambda dst: [0xe2102000, 0x80000000 | (dst//4)<<16 | 10<<8 | 8] + words = [mov(20,4), mov(21,128), *descriptor(32,96), *descriptor(36,32), + 0x8718ff06,0xfc0, 0xd700000a,0x10080, 0xd7650007,193|(24<<9), + 0xd7660008,193|((256+7)<<9),0xbf8cc07f,*store(32),*store(36),0xbf810000] + + def run(marker, name, expected=0): + p=subprocess.run([exe,sdk,work/"cache","gfx1013-group-clear@0",marker,work/name], + text=True,capture_output=True) + if p.returncode != expected: raise AssertionError((p.stdout,p.stderr)) + return p.stdout+p.stderr + + marker=write_request(work,words,root) + cold=run(marker,"clear.cso") + assert "u0 parameter=0 byte_offset=32" in cold and "u1 parameter=0 byte_offset=96" in cold + assert "cache_hit_ms" in run(marker,"warm.cso") + assert (work/"clear.cso").read_bytes()==(work/"warm.cso").read_bytes() + marker.with_suffix(".data").write_bytes(b"corrupted") + assert "key mismatch" in run(marker,"damaged.cso",1) + # A partial SGPR write breaks the second descriptor. The first store must + # not cause publication of a partial shader. + broken=words[:-3]+[mov(37,128)]+words[-3:] + assert "unsupported" in run(write_request(work,broken,root),"partial.cso",1) + assert not (work/"partial.cso").exists() + # A correctly keyed request whose state block A is short must fail the shape check with its + # existing diagnostic. The wave-size bit is read only once 28 bytes are proved (#3241). + short=write_request(work,words,root,sa=struct.pack("<6I",0,0,0,32|(8<<16),1|(1<<20),0)) + assert "compute state block A is not 28 bytes" in run(short,"short.cso",1) + assert not (work/"short.cso").exists() + print("two-table request, register renaming, store order, cache, tamper and partial descriptor passed") + + +if __name__=="__main__": + main(*sys.argv[1:]) diff --git a/tests/native_compute_grid.cpp b/tests/native_compute_grid.cpp new file mode 100644 index 0000000000..9b2b0e2e2a --- /dev/null +++ b/tests/native_compute_grid.cpp @@ -0,0 +1,288 @@ +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include "startup_stubs/native_buffer_stride.h" +#include <array> +#include <chrono> +#include <cmath> +#include <cstdio> +#include <cstring> + +using Microsoft::WRL::ComPtr; +using Clock = std::chrono::steady_clock; +namespace { +constexpr UINT width = 64, height = 32, pixels = width * height; +constexpr UINT raw_words = pixels * 2 + 16; +UINT raw_word(UINT i) { + // Every even word is another valid pair's byte address; odd words identify the pair. + return i % 2 ? 0x1234u + 11 * (i / 2) : 8 * ((i / 2 + 1) % pixels); +} +using Pixel = std::array<float, 4>; +Pixel pattern(UINT x, UINT y) { + return {float(1 + x + 128 * y), float(2000 + 2 * x + y), float(3 + x * y), float(10000 - x - 2 * y)}; +} +std::array<UINT, 2> sdwa_inputs(UINT x) { + return {0x93ac38e7u ^ (x * 0x0305070bu), 0x5ad2419bu ^ (x * 0x09010305u)}; +} +Pixel sdwa_expected(UINT x, const std::wstring &mode) { + auto [a, b] = sdwa_inputs(x); + UINT first, second; + if (mode == L"sdwa-class") { + first = b; + second = ((b >> 24) & 32u) ? a : b; + } else if (mode == L"sdwa-alias") { + first = (a >> 16) ^ a; + second = ((b >> 16) & 255u) ^ ((a >> 8) & 255u); + } else { + // Sign-extended source byte XOR a 32-bit operand. Then place the low byte + // of a separate XOR in byte 1, retaining or sign-filling unused bits. + first = UINT(int32_t(int8_t(a >> 16))) ^ b; + const UINT byte = ((a >> 16) ^ b) & 255u; + second = mode == L"sdwa-preserve" ? ((b & 0xffff00ffu) | (byte << 8)) + : UINT(int32_t(int8_t(byte))) << 8; + } + return {float(first & 65535), float(first >> 16), float(second & 65535), float(second >> 16)}; +} +} // namespace +int check_native_compute_grid(ID3D12Device *device, x2w::ShaderDxilCompiler &compiler, const wchar_t *marker, + const wchar_t *cache, const std::wstring &mode) { + const bool sdwa = mode == L"sdwa-alias" || mode == L"sdwa-preserve" || mode == L"sdwa-sext" || mode == L"sdwa-class"; + const bool typed = mode == L"typed" || sdwa; + const bool global_stride = mode == L"global-stride"; + const bool indexed = mode == L"indexed"; + const bool raw = global_stride || indexed || mode == L"raw-offset" || mode == L"raw-edge" || mode == L"raw-three" || + mode == L"raw-four" || mode == L"raw-math"; + const bool row = mode == L"row"; + if (!typed && !raw && !row && mode != L"copy" && mode != L"red" && mode != L"xyxx" && mode != L"negative") + return 2; + auto req = x2w::read_compute_request(marker); + UINT shape = 0; + std::memcpy(&shape, req.sa.data() + 12, sizeof(shape)); + const UINT gx = shape & 65535, gy = shape >> 16; + if (!gx || !gy || width % gx || height % gy) + return 2; + auto pipeline = x2w::create_native_compute_pipeline(device, compiler, marker, typed || raw ? 0 : 36, cache); + if (pipeline.srv_count != (row || indexed || global_stride ? 2u : 1u) || pipeline.uav_count != 1) + return 2; + auto kind = global_stride ? x2w::ComputeViewKind::buffer_srv : raw ? x2w::ComputeViewKind::raw_vector_srv : + typed ? x2w::ComputeViewKind::typed_buffer_srv : x2w::ComputeViewKind::texture_srv; + if ((row ? pipeline.bindings[1] : pipeline.bindings.front()).kind != kind) + return 2; + std::vector<UINT> constants(pipeline.constant_words, 0); + if (typed || raw) { + if (constants.size() != 4 || pipeline.constants[0].root_parameter != 2 || + pipeline.bindings[0].byte_offset != 64 || pipeline.bindings[indexed || global_stride ? 2 : 1].byte_offset != 224) + return 2; + if (indexed && (pipeline.bindings[0].root_parameter != 0 || pipeline.bindings[0].array_count != 2 || + pipeline.bindings[1].root_parameter != 0 || pipeline.bindings[1].byte_offset != 96 || + pipeline.bindings[1].array_position != 1 || pipeline.bindings[2].root_parameter != 1)) + return 2; + if (global_stride && (pipeline.bindings[1].kind != x2w::ComputeViewKind::heap_stride_srv || + pipeline.bindings[1].root_parameter != x2w::compute_resource_heap)) + return 2; + constants[0] = 3; + constants[1] = 5; + } + constexpr unsigned copied_columns = 47, source_row = 13; + if (row) { + if (constants.size() != 2 || pipeline.bindings.front().kind != x2w::ComputeViewKind::buffer_srv || + pipeline.bindings[0].byte_offset != 0 || pipeline.bindings[1].byte_offset != 32 || + pipeline.bindings[2].byte_offset != 64) + return 2; + constants[0] = copied_columns; + constants[1] = 1; + } + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, pipeline.srv_count + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)), "grid heap"); + UINT step = device->GetDescriptorHandleIncrementSize(hd.Type); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + ComputeCommands cmd(device, pipeline.state.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = width; + td.Height = height; + td.DepthOrArraySize = td.MipLevels = td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + UINT64 bytes; + device->GetCopyableFootprints(&td, 0, 1, 0, &fp, nullptr, nullptr, &bytes); + auto upload = make_buffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped; + check(upload->Map(0, nullptr, &mapped), "grid upload"); + ComPtr<ID3D12Resource> input; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (raw) { + constexpr UINT first = 8; + for (UINT i = 0; i < first + raw_words + 1; ++i) + static_cast<UINT*>(mapped)[i] = i < first ? 0x654321u : raw_word(i - first); + if (global_stride) { + static_cast<UINT*>(mapped)[first + 3] = 4; + static_cast<UINT*>(mapped)[first + 11] = 9; + } + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.FirstElement = first; + srv.Buffer.NumElements = raw_words; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + input = upload; + } else if (typed) { + for (UINT i = 0; i < width; ++i) { + const auto values = sdwa ? sdwa_inputs(i) : std::array<UINT, 2>{33 * i + 7, 5 * i + 2}; + std::memcpy(static_cast<UINT *>(mapped) + 2 * i, values.data(), sizeof(values)); + } + srv.Format = DXGI_FORMAT_R32G32_UINT; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Buffer.NumElements = width; + input = upload; + } else { + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + std::memcpy(static_cast<char *>(mapped) + y * fp.Footprint.RowPitch + x * sizeof(Pixel), + pattern(x, y).data(), sizeof(Pixel)); + srv.Format = td.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Texture2D.MipLevels = 1; + input = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, + dst{input.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = fp; + cmd.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + transition(cmd.list.Get(), input.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + upload->Unmap(0, nullptr); + ComPtr<ID3D12Resource> parameters; + if (row) { + constexpr unsigned words = 130; + parameters = make_buffer(device, words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(parameters->Map(0, nullptr, &mapped), "row parameters"); + std::memset(mapped, 0, words * 4); + static_cast<UINT *>(mapped)[129] = source_row << 8; + parameters->Unmap(0, nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC raw{}; + raw.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + raw.Format = DXGI_FORMAT_R32_TYPELESS; + raw.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + raw.Buffer.NumElements = words; + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(parameters.Get(), &raw, cpu); + cpu.ptr += step; + } + device->CreateShaderResourceView(input.Get(), &srv, cpu); + ComPtr<ID3D12Resource> second; + if (indexed || global_stride) { + second = make_buffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(second->Map(0, nullptr, &mapped), "second indexed SRV"); + for (UINT i = 0; i < raw_words; ++i) + static_cast<UINT*>(mapped)[srv.Buffer.FirstElement + i] = 100000 + raw_word(i); + if (global_stride) { + auto *strides = static_cast<UINT*>(mapped) + srv.Buffer.FirstElement; + // Supply the metadata for a typed float3 SRV and an eleven-word structured UAV + // using the same decoder used for materialized guest slots at dispatch. + D3D12_SHADER_RESOURCE_VIEW_DESC typed_view{}; + typed_view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + typed_view.Format = DXGI_FORMAT_R32G32B32_FLOAT; + D3D12_UNORDERED_ACCESS_VIEW_DESC structured{}; + structured.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + structured.Buffer.StructureByteStride = 44; + if (!x2w_startup::native_view_stride(18, &typed_view, sizeof(typed_view), strides[4]) || + !x2w_startup::native_view_stride(19, &structured, sizeof(structured), strides[9])) + return 2; + } + second->Unmap(0, nullptr); + cpu.ptr += step; + device->CreateShaderResourceView(second.Get(), &srv, cpu); + } + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + auto output = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if (row) { + transition(cmd.list.Get(), output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + D3D12_TEXTURE_COPY_LOCATION dst{output.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = fp; + cmd.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + transition(cmd.list.Get(), output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + cpu.ptr += step; + device->CreateUnorderedAccessView(output.Get(), nullptr, nullptr, cpu); + auto rb = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + auto ticks = make_buffer(device, 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_QUERY_HEAP_DESC qd{D3D12_QUERY_HEAP_TYPE_TIMESTAMP, 2}; + ComPtr<ID3D12QueryHeap> query; + check(device->CreateQueryHeap(&qd, IID_PPV_ARGS(&query)), "grid timestamps"); + pipeline.bind(cmd.list.Get(), heap.Get(), heap->GetGPUDescriptorHandleForHeapStart(), step, constants.data()); + cmd.list->EndQuery(query.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0); + cmd.list->Dispatch(width / gx, row ? 1u : height / gy, 1); + cmd.list->EndQuery(query.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 1); + cmd.list->ResolveQueryData(query.Get(), D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, ticks.Get(), 0); + transition(cmd.list.Get(), output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{output.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}, + dst{rb.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = fp; + cmd.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + check(cmd.list->Close(), "close"); + ID3D12CommandList *lists[]{cmd.list.Get()}; + auto start = Clock::now(); + cmd.queue->ExecuteCommandLists(1, lists); + double submit_us = std::chrono::duration<double, std::micro>(Clock::now() - start).count(); + ComPtr<ID3D12Fence> fence; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + check(cmd.queue->Signal(fence.Get(), 1), "signal"); + check(fence->SetEventOnCompletion(1, nullptr), "await grid"); + check(device->GetDeviceRemovedReason(), "grid completion"); + check(ticks->Map(0, nullptr, &mapped), "read times"); + UINT64 t[2], hz; + std::memcpy(t, mapped, 16); + ticks->Unmap(0, nullptr); + check(cmd.queue->GetTimestampFrequency(&hz), "frequency"); + check(rb->Map(0, nullptr, &mapped), "read pixels"); + unsigned differences = 0; + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + Pixel expected = pattern(x, y); + if (raw) { + const UINT lane = y * width + x; + const UINT pair = mode == L"raw-edge" ? raw_words - 1 : 2 * lane; + expected = {float(raw_word(2 * lane + 13)), float(raw_word(pair)), + pair + 1 < raw_words ? float(raw_word(pair + 1)) : 0.f, float(lane)}; + if (mode == L"raw-three" || mode == L"raw-four") + expected = {float(raw_word(pair)), float(raw_word(pair + 1)), float(raw_word(pair + 2)), + mode == L"raw-four" ? float(raw_word(pair + 3)) : float(raw_word(pair + 13))}; + if (indexed && x >= gx) + for (unsigned component = 0; component < 3; ++component) + expected[component] += 100000; + if (mode == L"raw-math") { + constexpr float cosine[]{1.f, 0.f, -1.f, 0.f}; + expected[0] = cosine[lane % 4]; + const UINT bits = raw_word(pair), exponent = bits >> 10, fraction = bits & 1023; + expected[3] = exponent ? std::ldexp(float(1024 + fraction), int(exponent) - 25) + : std::ldexp(float(fraction), -24); + } + } + if (global_stride) expected.fill(x < gx ? 12.f : 44.f); + if (typed) + expected = {float(33 * x + 7), float(16*(y*3+5)+1+5*x+2), float(x+(x<32?3:9)), float(y/2+((y&3)==3))}; + if (sdwa) + expected = sdwa_expected(x, mode); + if (row && y == 0 && x < copied_columns) + expected = pattern(x, source_row); + if (mode == L"red") + expected.fill(expected[0]); + if (mode == L"xyxx") + expected[2] = expected[3] = expected[0]; + if (mode == L"negative") + expected[0] += 1; + auto *actual = + reinterpret_cast<const float *>(static_cast<const char *>(mapped) + y * fp.Footprint.RowPitch) + 4 * x; + for (UINT i = 0; i < 4; ++i) + differences += actual[i] != expected[i]; + } + rb->Unmap(0, nullptr); + std::printf("pixels=%u differing_components=%u cache_hit=%d frontend_ms=%.4f backend_ms=%.4f pso_ms=%.4f " + "cpu_submit_us=%.3f gpu_dispatch_us=%.3f\n", + pixels, differences, pipeline.cache_hit, pipeline.frontend_ms, pipeline.backend_ms, + pipeline.pipeline_ms, submit_us, double(t[1] - t[0]) * 1e6 / hz); + return differences ? 1 : 0; +} diff --git a/tests/native_compute_implicit_lod_check.py b/tests/native_compute_implicit_lod_check.py new file mode 100644 index 0000000000..441575253c --- /dev/null +++ b/tests/native_compute_implicit_lod_check.py @@ -0,0 +1,247 @@ +"""Check that direct DXIL sampling uses the guest's consecutive-lane quads.""" + +import math +from pathlib import Path +import subprocess +import sys +import tempfile + +from compute_gather4_l_check import FLOAT_TEXTURE_FLAG, HEIGHT, SENTINEL, WIDTH, bits, texels +from native_direct_container_check import compute, words +from native_gather_lod_check import render +from startup_compute_gather_l_check import reference as gather_reference +from startup_image_sample_c_check import LESS, POINT + + +CASES = ( + ((4, 1, 1), True), + ((12, 1, 1), True), + ((32, 1, 1), True), + ((64, 1, 1), False), + ((96, 1, 1), True), + ((128, 1, 1), False), + ((8, 4, 1), True), + ((8, 4, 2), False), +) +MIP_COLORS = tuple(bits(value) for value in (1.0, 2.0, 4.0)) +MIP_ZERO_FLAG = 1 << 22 # tests/compute_check.cpp texture_mip_zero_sampler_flag +DEPTH_FLAG = 1 << 23 # tests/compute_check.cpp texture_comparison_flag +POINT_MIP_SAMPLER = (0x12, 0xFFF000, 0x04500000, 0) + + +def vop2(op, dst, src0, src1): + return (op << 25) | (dst << 17) | (src1 << 9) | src0 + + +def setup(wave32, sampler): + # One group at ID (0,0,0), with guest local IDs in v0/v1/v2. + # The texture descriptor is at table + 0 and output at table + 0x20. + code = [ + 0xBEFE03C1 if wave32 else 0xBEFE04C1, # s_mov_b32 exec_lo, -1 / s_mov_b64 exec, -1 + 0xBE810380, 0xF40C0200, 0xFA000000, + 0xF4080800, 0xFA000020, + ] + for reg, value in enumerate(sampler, start=4): + code += [0xBE8003FF | reg << 16, value] + return code + + +def program(group, wave32, implicit): + code = setup(wave32, POINT_MIP_SAMPLER) + _, y, z = group + if z > 1: + code += [ + vop2(26, 2, 133, 2), # v2 = z << 5 + vop2(28, 0, 258, 0), # v0 |= v2 + ] + if y > 1: + code += [ + vop2(26, 1, 131, 1), # v1 = y << 3 + vop2(28, 0, 257, 0), # v0 |= v1, completing the linear index + ] + code += [ + vop2(26, 5, 130, 0), # v5 = linear index * 4, the output byte offset + ] + if y > 1: + # Use a vertical-only ramp. Consecutive quads step two indices in ddy + # (0.75 texels) and have zero ddx. Spatial 2D quads step eight indices + # in ddy (three texels), so they sample above mip zero. + code += [ + 0x7E0202F0, # v_mov_b32 v1, 0.5 (U) + vop2(27, 2, 142, 0), # v2 = linear index & 14 + 0x7E040D02, # v_cvt_f32_u32 v2, v2 + vop2(8, 2, 255, 2), bits(3 / (8 * HEIGHT)), # V + 0x7E060280, # v_mov_b32 v3, 0 (explicit LOD) + ] + else: + code += [ + vop2(22, 3, 130, 0), # v3 = linear index >> 2 + vop2(27, 3, 131, 3), # v3 &= 3 + vop2(19, 3, 130, 3), # v3 = min(v3, 2), the expected mip + vop2(26, 4, 151, 3), # v4 = mip << 23 + vop2(37, 4, 255, 4), bits(1 / WIDTH), # v4 = bits for (1 / WIDTH) * 2**mip + vop2(27, 1, 129, 0), # v1 = linear index & 1 + 0x7E020D01, # v_cvt_f32_u32 v1, v1 + vop2(8, 1, 260, 1), # v1 = U, giving each quad ddx(U) = 2**mip / WIDTH + vop2(27, 4, 136, 0), # v4 = linear index & 8 + 0x7E080D04, # v_cvt_f32_u32 v4, v4 + vop2(8, 4, 255, 4), bits(0.0625), # v4 = 0.5 when bit 3 of the index is set + vop2(3, 1, 260, 1), # Add an offset constant within each quad. + 0x7E0402F0, # v_mov_b32 v2, 0.5 (V) + 0x7E060D03, # v_cvt_f32_u32 v3, v3 (explicit LOD) + ] + code += [ + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + 0xF0000108 | ((32 if implicit else 36) << 18), 0x00220401, + 0xBF8C3F70, # s_waitcnt vmcnt(0) + 0xE0701000, 0x80080405, # buffer_store_dword v4, v5, s[32:35], 0 offen + 0xBF810000, + ] + return compute(words(*code), table=True, wave32=wave32, group=group) + + +def compile_shader(cli, sdk, work, group, wave32, implicit): + name = '-'.join(map(str, (*group, int(wave32), int(implicit)))) + return compile_program(cli, sdk, work, name, program(group, wave32, implicit)) + + +def compile_program(cli, sdk, work, name, binary): + source = work / f'{name}.c67' + source.write_bytes(binary) + shader = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, run + + +def compile_pair(cli, sdk, work, group, wave32): + for implicit in (True, False): + shader, run = compile_shader(cli, sdk, work, group, wave32, implicit) + assert run.returncode == 0 and shader.is_file(), (group, wave32, implicit, run.stdout, run.stderr) + yield shader + + +def mip_payload(colors, channels=4): + return [color for mip, color in enumerate(colors) + for _ in range((WIDTH >> mip) * (HEIGHT >> mip) * channels)] + + +def write_case(path, expected, payload, flags=FLOAT_TEXTURE_FLAG): + expected = [*expected, *([SENTINEL] * (320 - len(expected)))] + path.write_bytes(words(flags | 1, *expected, *payload)) + + +def write_reference(path, group): + threads = math.prod(group) + if group[1] > 1: + expected = [MIP_COLORS[0]] * threads + else: + expected = [MIP_COLORS[min((lane // 4) % 4, 2)] for lane in range(threads)] + write_case(path, expected, mip_payload(MIP_COLORS)) + + +def operation_program(op, *, step=2 / WIDTH, operand=0.0, mask=1, components=1, + sampler=POINT_MIP_SAMPLER): + code = setup(True, sampler) + code += [ + vop2(26, 8, {1: 130, 2: 131, 4: 132}[components], 0), # byte offset + vop2(27, 7, 129, 0), # lane & 1 + 0x7E0E0D07, # convert v7 to float + vop2(8, 1, 255, 7), bits(step), + vop2(3, 1, 240, 1), # U = 0.5 + step * (lane & 1) + 0x7E0402F0, # V = 0.5 + 0x7E0002FF, bits(operand), + ] + address = 0 if op in (37, 40) else 1 + if op == 40: + # Comparison reference before U and V, as in startup_image_sample_c_check. + code += [vop2(8, 0, 255, 7), bits(0.25), vop2(3, 0, 240, 0)] + if op in (36, 68): + code += [0x7E060300] # v_mov_b32 v3, v0: explicit LOD after U and V + code += [ + 0xBF8CC07F, + 0xF0000008 | op << 18 | mask << 8, 0x00220400 | address, + 0xBF8C3F70, + {1: 0xE0701000, 2: 0xE0741000, 4: 0xE0781000}[components], 0x80080408, + 0xBF810000, + ] + return compute(words(*code), wave32=True, group=(4, 1, 1), table=True) + + +def operation_cases(): + colors = mip_payload(MIP_COLORS) + yield 'bias-base', operation_program(32), [MIP_COLORS[1]] * 4, colors, FLOAT_TEXTURE_FLAG + yield 'bias-plus-one', operation_program(37, operand=1.0), [MIP_COLORS[2]] * 4, colors, FLOAT_TEXTURE_FLAG + yield 'bias-explicit', operation_program(36, operand=2.0), [MIP_COLORS[2]] * 4, colors, FLOAT_TEXTURE_FLAG + + comparison = (POINT | LESS, 0xFFF000, 0x04000000, 0) + depth = mip_payload(tuple(map(bits, (0.25, 0.625, 1.0))), channels=1) + yield 'compare', operation_program(40, sampler=comparison), [bits(1.0), bits(0.0)] * 2, depth, DEPTH_FLAG + + mip_zero = (0x12, 0, 0x04500000, 0) + query = operation_program(96, step=4 / WIDTH, mask=3, components=2, sampler=mip_zero) + yield 'get-lod', query, [bits(0.0), bits(2.0)] * 4, colors, FLOAT_TEXTURE_FLAG | MIP_ZERO_FLAG + + step = 1 / (4 * WIDTH) + taps = gather_reference(0, 0, (0.5, 0.5))[:4] + assert taps == gather_reference(0, 0, (0.5 + step, 0.5))[:4] + for name, op in (('gather', 64), ('gather-explicit', 68)): + binary = operation_program(op, step=step, components=4, sampler=mip_zero) + yield name, binary, taps * 4, texels(), FLOAT_TEXTURE_FLAG | MIP_ZERO_FLAG + + +def check_readback(renderer, adapter, shader, reference): + result = render(renderer, adapter, '--compute-texture-case', shader, reference) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + shader.name, result.stdout, result.stderr) + + +def main(cli, sdk, *render_args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if not render_args: + dxc = Path(sdk) / 'dxc.exe' + for group, wave32 in CASES: + shaders = compile_pair(cli, sdk, work, group, wave32) + for shader, dimensions in zip(shaders, ((math.prod(group), 1, 1), group)): + dump = subprocess.check_output([dxc, '-dumpbin', shader], text=True, timeout=30) + expected = '; NumThreads=(' + ','.join(map(str, dimensions)) + ')' + actual = next((line for line in dump.splitlines() if line.startswith('; NumThreads=')), '') + assert actual == expected, (shader.name, expected, actual) + for group, reason in ( + ((36, 1, 1), 'partial final wave in multi-wave group'), + ((6, 1, 1), 'implicit derivatives require a pixel stage'), + ): + _, run = compile_shader(cli, sdk, work, group, True, True) + assert run.returncode != 0 and reason in run.stderr, (group, run.stdout, run.stderr) + _, run = compile_program(cli, sdk, work, 'gather-unsupported-sampler', + operation_program(64, components=4)) + assert run.returncode != 0 and 'implicit gather requires a sampler fixed to mip zero' in run.stderr, ( + run.stdout, run.stderr) + group = (6, 1, 1) + shader, run = compile_shader(cli, sdk, work, group, True, False) + assert run.returncode == 0 and shader.is_file(), run.stdout + run.stderr + for name, binary, _, _, _ in operation_cases(): + shader, run = compile_program(cli, sdk, work, name, binary) + assert run.returncode == 0 and shader.is_file(), (name, run.stdout, run.stderr) + return + + renderer, adapter = render_args + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + reference = work / 'expected.bin' + for group, wave32 in CASES: + write_reference(reference, group) + for shader in compile_pair(cli, sdk, work, group, wave32): + check_readback(renderer, adapter, shader, reference) + print(f'{group} wave{32 if wave32 else 64}: implicit and explicit LOD matched guest readback') + for name, binary, expected, payload, flags in operation_cases(): + shader, run = compile_program(cli, sdk, work, name, binary) + assert run.returncode == 0 and shader.is_file(), (name, run.stdout, run.stderr) + write_case(reference, expected, payload, flags) + check_readback(renderer, adapter, shader, reference) + print(f'{name}: exact readback') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_compute_ir_dump.cpp b/tests/native_compute_ir_dump.cpp new file mode 100644 index 0000000000..2c01a51f20 --- /dev/null +++ b/tests/native_compute_ir_dump.cpp @@ -0,0 +1,22 @@ +// Print the DXIL-text IR that the direct C++ frontend builds for a compute container. +// Used by native_f16_alu_check.py. Exit 1 and the diagnostic on stderr when the program is refused. +// usage: native_compute_ir_dump CONTAINER +#include "gfx1013_compute_native.h" +#include <fstream> +#include <iostream> +#include <iterator> +#include <string> + +int main(int argc, char **argv) { + if (argc != 2) + return 2; + std::ifstream file(argv[1], std::ios::binary); + const std::string bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); + try { + std::cout << x2w::translate_compute_container({bytes, {}}).dxil_ir; + } catch (const std::exception &error) { + std::cerr << error.what() << "\n"; + return 1; + } + return 0; +} diff --git a/tests/native_compute_manifest_reasons.cpp b/tests/native_compute_manifest_reasons.cpp new file mode 100644 index 0000000000..92d7147f14 --- /dev/null +++ b/tests/native_compute_manifest_reasons.cpp @@ -0,0 +1,122 @@ +// Every refusal of format_compute_runtime_manifest names its reason, and an accepted program's manifest is unchanged. +#include "direct_compute_cache.h" +#include "native_compute_output.h" + +#include <cstdio> +#include <cstring> +#include <functional> +#include <string> + +using namespace x2w; + +static ComputeViewBinding view(ComputeViewKind kind, unsigned reg, unsigned root = 1, unsigned offset = 0) { + ComputeViewBinding b{}; + b.kind = kind; + b.root_parameter = root; + b.byte_offset = offset; + b.shader_register = reg; + return b; +} + +static NativeComputeShader base() { + NativeComputeShader p{}; + p.group = {8, 4, 1}; + p.constants.push_back({0, 0, 2}); + p.bindings.push_back(view(ComputeViewKind::buffer_srv, 0, 1, 64)); + p.bindings.push_back(view(ComputeViewKind::raw_buffer_uav, 0, 1, 32)); + return p; +} + +int main() { + int failures = 0; + std::string reason = "unset"; + const auto accepted = format_compute_runtime_manifest(base(), &reason); + const std::string expected = "x2w-manifest 2\nstage cs\ngroup 8 4 1\nud 2\nudsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\nsrv 0 buf table 1 64\nuav 0 table 1 32\nnative " + + std::to_string(native_compute_output_revision) + "\n"; + if (!accepted || *accepted != expected || reason != "unset") { + std::printf("FAIL accepted program: manifest %s, reason \"%s\"\n", accepted ? accepted->c_str() : "(none)", + reason.c_str()); + ++failures; + } + + using K = ComputeViewKind; + const struct { + const char *expected; + std::function<void(NativeComputeShader &)> change; + } cases[] = { + {"group size has a zero dimension", [](auto &p) { p.group[2] = 0; }}, + {"root constants above root parameter 15", [](auto &p) { p.constants[0].root_parameter = 16; }}, + {"more than 8 root constants in one root parameter", [](auto &p) { p.constants[0].count = 9; }}, + {"more than 32 user data words", [](auto &p) { + p.constants.assign(4, {0, 0, 8}); + p.bindings[0].kind = K::raw_vector_srv; + p.stride_srvs = {0}; + }}, + {"resource heap view", [](auto &p) { p.bindings.push_back(view(K::heap_buffer_srv, 1, compute_resource_heap)); }}, + {"sampler heap", [](auto &p) { p.bindings.push_back(view(K::heap_sampler, 1, compute_sampler_heap)); }}, + {"view above root parameter 15", [](auto &p) { p.bindings[1].root_parameter = 16; }}, + {"SRV registers not contiguous", [](auto &p) { p.bindings[0].shader_register = 1; }}, + {"UAV registers not contiguous", [](auto &p) { p.bindings[1].shader_register = 1; }}, + {"SRV kind root_buffer_srv", [](auto &p) { p.bindings[0].kind = K::root_buffer_srv; }}, + {"SRV kind texture_srv cube", [](auto &p) { + p.bindings[0].kind = K::texture_srv; + p.bindings[0].image_dimension = 3; + }}, + {"SRV kind texture_srv 2d array", [](auto &p) { + p.bindings[0].kind = K::texture_srv; + p.bindings[0].array_count = 4; + }}, + {"UAV kind typed_buffer_uav", [](auto &p) { p.bindings[1].kind = K::typed_buffer_uav; }}, + {"UAV kind texture_uav cube", [](auto &p) { + p.bindings[1].kind = K::texture_uav; + p.bindings[1].image_dimension = 3; + }}, + {"more than 32 SRVs", [](auto &p) { + for (unsigned r = 1; r < 33; ++r) + p.bindings.push_back(view(K::buffer_srv, r, 1, 64 + 32 * r)); + }}, + {"more than 8 UAVs", [](auto &p) { + for (unsigned r = 1; r < 9; ++r) + p.bindings.push_back(view(K::raw_buffer_uav, r, 2, 32 * r)); + }}, + {"comparison sampler", [](auto &p) { p.samplers.push_back({{0, 0, 0, 0}, true, true}); }}, + {"stride words from a view that is not one raw vector SRV", [](auto &p) { p.stride_srvs = {0}; }}, + }; + for (const auto &c : cases) { + auto program = base(); + c.change(program); + reason.clear(); + const auto manifest = format_compute_runtime_manifest(program, &reason); + const bool ok = !manifest && reason == c.expected; + std::printf("%s %s%s%s\n", ok ? "ok " : "FAIL", c.expected, ok ? "" : " | got: ", + ok ? "" : manifest ? "a manifest" : reason.c_str()); + failures += !ok; + } + // A texture SRV is published under the name of its dimension: the line the runtime's reader takes. + const struct { + unsigned image_dimension; + const char *line; + } published[] = { + {0, "srv 0 tex1d table 1 64\n"}, + {1, "srv 0 tex2d table 1 64\n"}, + {2, "srv 0 tex3d table 1 64\n"}, + {5, "srv 0 tex2da table 1 64\n"}, + }; + for (const auto &c : published) { + auto program = base(); + program.bindings[0].kind = K::texture_srv; + program.bindings[0].image_dimension = c.image_dimension; + reason = "unset"; + const auto manifest = format_compute_runtime_manifest(program, &reason); + std::string wanted = expected; + wanted.replace(wanted.find("srv 0 buf table 1 64\n"), std::strlen("srv 0 buf table 1 64\n"), c.line); + const bool ok = manifest && *manifest == wanted && reason == "unset"; + std::printf("%s publishes %s", ok ? "ok " : "FAIL", c.line); + if (!ok) + std::printf(" | got: %s\n", manifest ? manifest->c_str() : reason.c_str()); + failures += !ok; + } + std::printf("%d of %zu manifest reasons wrong\n", failures, std::size(cases) + std::size(published) + 1); + return failures ? 1 : 0; +} diff --git a/tests/native_compute_manifest_reasons_check.py b/tests/native_compute_manifest_reasons_check.py new file mode 100644 index 0000000000..201d0c6bac --- /dev/null +++ b/tests/native_compute_manifest_reasons_check.py @@ -0,0 +1,104 @@ +"""A compute program that compiles but gets no runtime manifest names the reason (#3224). + +The program reads a root CBV and a root SRV (the raw-root fixture), so it translates to DXIL but the +compute manifest has no line for a root descriptor. A table-bound control still publishes its manifest. +--requests reports the reason on stdout and leaves no .fail, so watchers keep retrying the key; --watch, +which refuses the key, writes the reason to its .fail. + +usage: + native_compute_manifest_reasons_check.py <compile_dxil> <sdk> +""" +import json +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "tools" / "startup")) + +import gfx2hlsl as G # noqa: E402 +import triage_run # noqa: E402 +from native_compute_clear_check import write_request # noqa: E402 +from native_startup_request_cache_check import ( # noqa: E402 + COMPUTE_GROUP, + COMPUTE_RSRC2, + compile_compute_root, + compute_program_words, + put_compute_request, +) +from startup_compute_translate_check import state_a # noqa: E402 + +# s_load_dwordx4 from the root CBV at s[6:7]; copy the root SRV address s[8:9] to s[2:3]; load from it; s_endpgm. +ROOT_CODE = [0xF40C0403, 0xFA000010, 0xBE820408, 0xF40C0601, 0xFA000030, 0xBF810000] +ROOT_SA = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 10 << 1) +REASON = "unsupported startup runtime manifest bindings: SRV kind root_buffer_srv" + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + raise SystemExit(__doc__) + cli, sdk = Path(argv[0]).resolve(), Path(argv[1]) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "root.hlsl" + src.write_text('#define RS "RootConstants(num32BitConstants=2,b1),CBV(b0),SRV(t0)"', encoding="ascii") + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", work / "root.bin", src], check=True) + requests = work / "requests" + requests.mkdir() + key = write_request(requests, ROOT_CODE, (work / "root.bin").read_bytes(), ROOT_SA).stem[4:] + control = "%016x" % put_compute_request( + requests, compute_program_words(), compile_compute_root(sdk, work), state_a(COMPUTE_GROUP, COMPUTE_RSRC2)) + watched = work / "watched" + shutil.copytree(requests, watched) + + # 1. --requests in a live cache: the DXIL is published, the reason goes to stdout, and no .fail is left. + # A genuine refusal beside it keeps its .fail. The Python watcher's two selections tell them apart. + live = work / "live" + shutil.copytree(requests, live) + broken = compute_program_words()[:-4] + struct.pack("<2I", 0xFFFFFFFF, 0xBF810000) + refused = "%016x" % put_compute_request( + live, broken, compile_compute_root(sdk, work), state_a(COMPUTE_GROUP, COMPUTE_RSRC2)) + (live / f"{key}.fail").write_text("stale failure\n", encoding="ascii") + run = subprocess.run([cli, sdk, work / "frontend", "--jobs", "2", "gfx1013-direct-cs@0", "--requests", + live, live], capture_output=True, text=True) + assert run.returncode == 1 and "requests=3 compiled=2 refused=1" in run.stdout, (run.stdout, run.stderr) + retry_all = sorted(int(k, 16) for k in (key, refused)) + assert G.pending_keys(str(live), False) == retry_all, G.pending_keys(str(live), False) + assert G.pending_keys(str(live), True) == [int(key, 16)], G.pending_keys(str(live), True) + assert f"no_manifest input=req_{key}.c67 {REASON}\n" in run.stdout, run.stdout + assert run.stdout.count("no_manifest ") == 1, run.stdout + assert (live / f"{key}.cs.cso").read_bytes().startswith(b"DXBC") + assert not (live / f"{key}.txt").exists() and not (live / f"{key}.fail").exists() + assert (live / f"{control}.txt").is_file() and not (live / f"{control}.fail").exists() + assert (live / f"{refused}.fail").is_file() and not (live / f"{refused}.cs.cso").exists() + + # 2. --refusals counts it with the same text. + summary = json.loads(subprocess.run([cli, "--refusals", requests, "--json"], capture_output=True, + text=True, check=True).stdout)["compute"] + assert summary["examined"] == 2 and summary["no_refusal"] == 1 and summary["refused"] == 1, summary + assert summary["reasons"] == [{"reason": REASON, "count": 1}], summary + + # 3. --watch writes the same line, and triage_run.py reports it as a fixed category without the key. + watch = subprocess.run([cli, "--watch", sdk, work / "watch_cache", watched, "--once"], + capture_output=True, text=True) + assert watch.returncode == 0 and f"{key}: refused: {REASON}" in watch.stdout, (watch.stdout, watch.stderr) + assert f"{control}: compiled compute" in watch.stdout, watch.stdout + assert (watched / f"{key}.fail").read_text(encoding="ascii") == REASON + "\n" + # A watcher refusal is a genuine failure: skipped by the repeated pass, retried by the first. + assert G.pending_keys(str(watched), True) == [] and G.pending_keys(str(watched), False) == [int(key, 16)] + logs = work / "logs" + logs.mkdir() + (logs / "stderr.txt").write_text("", encoding="utf-8") + report = triage_run.triage_run(logs, shader_cache=watched) + assert "| 1 | `compute: runtime manifest: SRV kind root_buffer_srv` |" in report, report + assert key not in report and control not in report + print("compute manifest reasons: ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/native_compute_pack_check.cpp b/tests/native_compute_pack_check.cpp new file mode 100644 index 0000000000..7e731d65db --- /dev/null +++ b/tests/native_compute_pack_check.cpp @@ -0,0 +1,96 @@ +#include "direct_compute_cache.h" +#include "shader_dxil_compiler.h" +#include <algorithm> +#include <chrono> +#include <fstream> +#include <iostream> +#include <stdexcept> +#include <vector> + +using namespace x2w; +namespace fs = std::filesystem; +using Clock = std::chrono::steady_clock; +static double elapsed(Clock::time_point since) { + return std::chrono::duration<double, std::milli>(Clock::now() - since).count(); +} +static void check(bool ok, const char *reason) { + if (!ok) throw std::runtime_error(reason); +} +int main(int argc, char **argv) { + try { + if (argc < 3 || argc > 4) return 2; + const fs::path input = argv[1], file = argv[2]; + std::vector<fs::path> markers; + for (auto &it : fs::directory_iterator(input)) + if (it.path().extension() == ".c67") markers.push_back(it.path()); + std::sort(markers.begin(), markers.end()); + auto start = Clock::now(); + auto pack = ComputeFrontendPack::load(file, 0); + const auto load_ms = elapsed(start); + std::ofstream report; + if (argc == 4) { + report.open(argv[3]); + report.exceptions(std::ios::failbit | std::ios::badbit); + report << "key\tstatus\tcold_ms\tlookup_ms\tir_sha256_or_diagnostic\tmanifest_sha256\n"; + } + size_t success = 0, refused = 0, other = 0; + double live_total = 0, warm_total = 0; + bool tested_success = false, tested_refused = false; + for (const auto &marker : markers) { + auto r = read_compute_request(marker); + NativeComputeShader warm, cold; + std::string warm_error, cold_error; + start = Clock::now(); + const auto hit = pack.lookup(r, 0, warm, warm_error); + const double warm_ms = elapsed(start); + start = Clock::now(); + ComputePackResult expected = ComputePackResult::prepared; + try { cold = translate_compute(r, 0, true); } + catch (const UnsupportedComputeShader &e) { expected = ComputePackResult::unsupported; cold_error = e.what(); } + catch (const std::runtime_error &e) { expected = ComputePackResult::miss; cold_error = e.what(); } + const double live_ms = elapsed(start); + live_total += live_ms; + warm_total += warm_ms; + check(hit == expected, "result class differs from direct frontend"); + const char *status; + std::string identity, manifest_digest; + if (hit == ComputePackResult::prepared) { + auto manifest = format_compute_runtime_manifest(cold); + check(warm.dxil_ir == cold.dxil_ir && warm.group == cold.group && + warm.instruction_count == cold.instruction_count && format_compute_runtime_manifest(warm) == manifest, + "IR, layout or manifest differs"); + status = "prepared"; + identity = shader_digest(cold.dxil_ir); + if (manifest) manifest_digest = shader_digest(*manifest); + ++success; + } else if (hit == ComputePackResult::unsupported) { + check(warm_error == cold_error, "refusal differs"); + status = "unsupported"; + identity = cold_error; + ++refused; + } else { + status = "other"; + identity = cold_error; + ++other; + } + if ((hit == ComputePackResult::prepared && !tested_success) || + (hit == ComputePackResult::unsupported && !tested_refused)) { + for (auto *part : {&r.code, &r.data, &r.root, &r.description, &r.sa, &r.sb}) { + part->push_back(0); + check(pack.lookup(r, 0, warm, warm_error) == ComputePackResult::miss, "stale input accepted"); + part->pop_back(); + } + check(pack.lookup(r, 4, warm, warm_error) == ComputePackResult::miss, "stale entry accepted"); + if (hit == ComputePackResult::prepared) tested_success = true; + else tested_refused = true; + } + if (report.is_open()) + report << marker.stem().string() << '\t' << status << '\t' << live_ms << '\t' << warm_ms << '\t' + << identity << '\t' << manifest_digest << '\n'; + } + check(tested_success && tested_refused && pack.size() == success + refused, "missing test coverage"); + std::cout << "prepared=" << success << " unsupported=" << refused << " other=" << other + << " load_ms=" << load_ms << " cold_ms=" << live_total << " lookup_ms=" << warm_total << '\n'; + return 0; + } catch (const std::exception &e) { std::cerr << e.what() << '\n'; return 1; } +} diff --git a/tests/native_compute_pack_check.py b/tests/native_compute_pack_check.py new file mode 100644 index 0000000000..7925f419c4 --- /dev/null +++ b/tests/native_compute_pack_check.py @@ -0,0 +1,109 @@ +"""Replay source-built frontend pack and check version, input identity and integrity.""" +from pathlib import Path +import os +import subprocess +import sys +import tempfile + +from native_startup_request_cache_check import (compile_compute_root, compute_program_words, + put_compute_request, state_a, COMPUTE_GROUP, COMPUTE_RSRC2) + + +def run(cli, checker, sdk): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + inputs = base / "requests" + inputs.mkdir() + root = compile_compute_root(sdk, base) + code = compute_program_words() + state = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + put_compute_request(inputs, code, root, state) + put_compute_request(inputs, bytes.fromhex("0000f8d8 00000000 000081bf"), root, state) + build = [cli, "--prepare-compute-pack", inputs, base / "cache", "0"] + result = subprocess.run(build, capture_output=True, text=True) + assert result.returncode == 0 and "prepared=1 unsupported=1 errors=0" in result.stdout, result + pack = base / "cache" / "compute-0.pack" + subprocess.run([checker, inputs, pack], check=True) + original = pack.read_bytes() + for position in (0, 64, len(original) - 1): + damaged = bytearray(original) + damaged[position] ^= 1 + pack.write_bytes(damaged) + rejected = subprocess.run([checker, inputs, pack], capture_output=True, text=True) + assert rejected.returncode and "damaged compute pack" in rejected.stderr, rejected + pack.write_bytes(original) + # Invalid source remains retryable. Other valid records still publish. + (inputs / "req_0000000000000000.c67").write_bytes(code) + result = subprocess.run(build, capture_output=True, text=True) + assert result.returncode == 1 and "prepared=1 unsupported=1 errors=1" in result.stdout, result + assert pack.read_bytes() == original + + +def hardware(cli, consumer, sdk): + import startup_gfx2hlsl_compute_check as C + from startup_compute_dispatch_check import dispatch, lines, prepare_case + from startup_compute_dispatch_native_check import LOAD_X8, LOADS_X4 + from startup_stream_check import gfx2hlsl as G + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + cache, env = prepare_case(work, "hardware") + env.pop("X2W_NATIVE_COMPUTE_PACK", None) + env["X2W_NATIVE_SHADERS"] = str(sdk) + code_file = work / "program" + original = code_file.read_bytes() + assert original.count(LOAD_X8) == 1 + words, refused = dispatch(work, str(consumer), env, "dispatch") + assert words == [C.SENTINEL] * C.WORDS and lines(refused, "unaligned descriptor table entry"), refused.stderr + code_file.write_bytes(original.replace(LOAD_X8, LOADS_X4)) + words, result = dispatch(work, str(consumer), env, "dispatch-records32") + print(result.stdout, end="") + if lines(result, "the adapter has no 32-lane waves"): + print("SKIP: native compute requires a 32-lane wave") + sys.exit(77) + assert words == C.expected("A") and lines(result, "outputs (frontend live)"), result.stderr + build = subprocess.run([cli, "--prepare-compute-pack", cache, work / "pack", "0"], check=True, + capture_output=True, text=True) + assert "prepared=1 unsupported=1 errors=0" in build.stdout, build.stdout + env["X2W_NATIVE_COMPUTE_PACK"] = str(work / "pack" / "compute-0.pack") + words, result = dispatch(work, str(consumer), env, "dispatch-records32") + assert words == C.expected("A") and lines(result, "outputs (frontend prepared)"), result.stderr + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + layer = lines(result, "x2w-d3d12 debug layer: ") + print("Debug layer:", "enabled" if layer and "0x00000000" in layer[0] else "unavailable") + words, result = dispatch(work, str(consumer), env, "dispatch") + assert words == [C.SENTINEL] * C.WORDS and lines(result, "refused:"), result.stderr + env["X2W_D3D12_COMPUTE_OUTPUT_TRACE"] = "1" + for mode in ("raw", "structured", "typed", "wrong-slot", "copied"): + words, result = dispatch(work, str(consumer), env, f"dispatch-uav-token-{mode}") + expected = [C.SENTINEL] * C.WORDS + if mode in ("raw", "structured", "typed"): + expected[4:-4] = C.expected("A")[:-8] + assert lines(result, "offset=16 bytes=1248 result=bound"), result.stderr + elif mode == "wrong-slot": + assert lines(result, "does not identify a slot-19 UAV"), result.stderr + else: + assert lines(result, "does not uniquely alias its guest byte interval"), result.stderr + assert lines(result, "use=copy-source-attempt") and not lines(result, "use=copy-read-recorded"), result.stderr + assert lines(result, "use=map-guest-read-request") and lines(result, "x2w-compute-output-submit"), result.stderr + assert words == expected, (mode, words[:16], expected[:16], result.stderr) + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + print(f"slot-19 {mode}: all {len(words)} readback words match") + # Publish the reference artifact offline. A native refusal must still try the published shader. + subprocess.run([sys.executable, "-B", G.__file__, "--pending", cache], check=True, capture_output=True, + env=dict(os.environ, X2W_DXC=str(sdk / "dxc.exe"))) + code_file.write_bytes(original) + words, result = dispatch(work, str(consumer), env, "dispatch") + assert words == C.expected("A") and lines(result, "unaligned descriptor table entry"), result.stderr + assert lines(result, "Dispatch(3, 2, 2) translated"), result.stderr + print(f"Direct and prepared dispatch matched {C.WORDS} words. Invalid binding preserved every sentinel.") + print(f"Prepared refusal followed by published translation matched {C.WORDS} words.") + + +if __name__ == "__main__": + if sys.argv[1] == "hardware": + hardware(*(Path(a).resolve() for a in sys.argv[2:])) + else: + run(*(Path(a).resolve() for a in sys.argv[1:])) diff --git a/tests/native_compute_raw_root_check.py b/tests/native_compute_raw_root_check.py new file mode 100644 index 0000000000..d7809b2885 --- /dev/null +++ b/tests/native_compute_raw_root_check.py @@ -0,0 +1,84 @@ +"""Exercise packed CBV/SRV address pairs in the raw compute entry ABI.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import compute, words + + +def main(exe, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + + def signature(text): + src = work / "root.hlsl" + src.write_text(f'#define RS "{text}"') + binary = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", + "-Fo", binary, src], check=True) + return binary.read_bytes() + + def compile_case(code, root, user=10, error=None): + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, user << 1) + marker = write_request(work, code, root, sa) + result = subprocess.run([exe, sdk, work / "cache", "gfx1013-direct-cs@0", + marker, marker.with_suffix(".cso")], text=True, capture_output=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + assert not marker.with_suffix(".cso").exists() + else: + assert result.returncode == 0, result.stderr + return result.stdout + + prefix = "RootConstants(num32BitConstants=2,b1)," + root = signature(prefix + "CBV(b0),SRV(t0)") + end = 0xbf810000 + # s[6:7] and s[8:9] belong to different root parameters. + # Copy the second address to s[2:3] before reading at byte 48. + read_cbv = [0xf40c0403, 0xfa000010] + copy_srv = 0xbe820408 + read_srv = [0xf40c0601, 0xfa000030] + code = [*read_cbv, copy_srv, *read_srv, end] + cold = compile_case(code, root) + assert "t0 root=1 bytes=0 min_size=48" in cold, cold + assert "t1 root=2 bytes=0 min_size=80" in cold, cold + assert "frontend_cache_hit=1" in compile_case(code, root) + compile_case([*read_cbv, copy_srv, 0xbe830380, *read_srv, end], root, + error="mismatched root address high half") + compile_case(code, root, user=9, error="root descriptor pair exceeds user SGPRs") + for wrong in ("UAV(u0)", "CBV(b0,visibility=SHADER_VISIBILITY_VERTEX)"): + compile_case(code, signature(prefix + wrong + ",SRV(t0)"), + error="compute root descriptor type or visibility") + + # The first table range occupies slot zero. Its appended range at slot + # one is either CBV or SRV, although both shaders perform the same SMEM load. + read_table = [0xbe850380, 0xf4080202, 0xfa000020, 0xf42000c4, 0xfa000000, end] + for declaration, expected in (("CBV(b1)", "declared-cbv"), ("SRV(t1)", "srv")): + table = signature("DescriptorTable(SRV(t0)," + declaration + ")") + assert "table_view=" + expected in compile_case(read_table, table, user=5) + + container_code = words(0xbe810380, 0xf4080200, 0xfa000020, 0xf42000c4, 0xfa000000, end) + for name, kind, width, sgpr, error in ( + ("cbv", 2, 4, 0, ""), ("srv", 0, 4, 0, ""), + ("uav", 3, 4, 0, "disagrees with reflected table record"), + ("image", 0, 8, 0, "disagrees with reflected table record"), + ("sgpr", 2, 4, 1, "no matching user SGPR")): + marker = work / (name + ".cdx") + record = (0x300 | kind, 8, 0, 0, width | sgpr << 8) + marker.write_bytes(compute(container_code, table=True, uses=[record])) + args = [exe, sdk, work / "cache", "gfx1013-container-cs", marker, marker.with_suffix(".cso")] + result = subprocess.run(args, capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + else: + expected = "table_view=" + ("reflected-cbv" if kind == 2 else "srv") + assert result.returncode == 0 and expected in result.stdout, (result.stdout, result.stderr) + warm = subprocess.run(args, check=True, capture_output=True, text=True).stdout + assert "frontend_cache_hit=1" in warm and expected in warm, warm + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_cvt_f16_i16_check.py b/tests/native_cvt_f16_i16_check.py new file mode 100644 index 0000000000..e92cc74afb --- /dev/null +++ b/tests/native_cvt_f16_i16_check.py @@ -0,0 +1,398 @@ +"""Direct compute binary16 <-> 16-bit integer conversions (v_cvt_f16_u16, v_cvt_f16_i16, v_cvt_u16_f16, v_cvt_i16_f16).""" +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_direct_container_check import words as pack_words +import native_f16_alu_check as F +from native_scalar_lds_check import scalar, sop1 + + +OPS = { + 'v_cvt_f16_u16': (0x50, 0x1D0, False, True), + 'v_cvt_f16_i16': (0x51, 0x1D1, True, True), + 'v_cvt_u16_f16': (0x52, 0x1D2, False, False), + 'v_cvt_i16_f16': (0x53, 0x1D3, True, False), +} +HI_DST = 0xABCD0000 +HI_SRC = 0xBEEF0000 +DST_SEED = HI_DST | 0x5555 + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_unary(op, vdst, src0, *, abs0=0, neg0=0, clamp=0, omod=0, op_sel=0, src1=0): + w0 = (0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | + ((op_sel & 0xF) << 11) | ((abs0 & 7) << 8) | (vdst & 0xFF)) + w1 = ((neg0 & 7) << 29) | ((omod & 3) << 27) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def v_mov_lit(vdst, val): + return [0x7E0002FF | ((vdst & 0xFF) << 17), val & 0xFFFFFFFF] + + +def half_bits_to_f32(bits): + return struct.unpack('<e', struct.pack('<H', bits & 0xFFFF))[0] + + +def ref_cvt_f16_int(signed, raw, *, clamp=False, rne=True): + """Exact binary16 encoding of low 16-bit integer (round to nearest even).""" + val = raw & 0xFFFF + if signed and (val & 0x8000): + val -= 0x10000 + f = float(val) + if rne: + try: + out = struct.unpack('<H', struct.pack('<e', f))[0] + except OverflowError: + out = 0xFC00 if f < 0.0 else 0x7C00 + else: + # Broken mutant: round toward zero via f16 mantissa truncation. + fbits = struct.unpack('<I', struct.pack('<f', f))[0] + sign = (fbits >> 16) & 0x8000 + mag = fbits & 0x7FFFFFFF + exp = mag >> 23 + frac = mag & 0x7FFFFF + if mag == 0: + out = sign + elif exp > 142: + out = sign | 0x7C00 + elif exp <= 112: + out = sign | ((0x800000 | frac) >> (126 - exp)) if exp >= 102 else sign + else: + out = sign | (((exp - 112) << 10) | (frac >> 13)) + if clamp: + if (out & 0x7FFF) > 0x7C00 or (out & 0x8000): + out = 0 + elif out > 0x3BFF: + out = 0x3C00 + return out + + +def ref_cvt_int_f16(signed, raw, *, abs0=0, neg0=0, nan_check=True): + """Truncate toward zero and saturate binary16 to 16-bit int; NaN gives 0.""" + bits = raw & 0xFFFF + if abs0: + bits &= 0x7FFF + if neg0: + bits ^= 0x8000 + f = half_bits_to_f32(bits) + if math.isnan(f): + return 0 if nan_check else (0x8000 if signed else 0) + lo, hi = (-32768, 32767) if signed else (0, 65535) + if f <= lo: + return lo & 0xFFFF + if f >= hi: + return hi & 0xFFFF + return int(math.trunc(f)) & 0xFFFF + + +def cases(): + items = [] + + def add(op, kind, src_val, *, src_code=257, abs0=0, neg0=0, clamp=0, wide=False, want=None): + vop1_op, vop3_op, signed, to_f16 = OPS[op] + if want is None: + raw = F.INLINE_F16[src_code] if kind == 'inline_float' else src_val + want = (ref_cvt_f16_int(signed, raw, clamp=bool(clamp)) if to_f16 + else ref_cvt_int_f16(signed, raw, abs0=abs0, neg0=neg0)) + items.append((op, vop1_op, vop3_op, signed, to_f16, kind, src_val, src_code, abs0, neg0, clamp, wide, want)) + + # v_cvt_f16_u16 (RNE rounding + overflow at 65520 + clamp + source kinds) + for v in (0, 1, 2048, 2049, 2051, 32768, 65504, 65519, 65520, 65535): + add('v_cvt_f16_u16', 'vgpr', HI_SRC | v) + add('v_cvt_f16_u16', 'sgpr', HI_SRC | 2051) + add('v_cvt_f16_u16', 'lit', 0xBEEF0803) # 2051 -> 2052 (0x6804) + add('v_cvt_f16_u16', 'inline_int', 0, src_code=128) + add('v_cvt_f16_u16', 'inline_int', 64, src_code=192) + add('v_cvt_f16_u16', 'inline_int', 0xFFFF, src_code=193) # -1 low 16 bits = 65535 -> +inf + add('v_cvt_f16_u16', 'inline_float', 0x3C00, src_code=242) # 1.0 bits (15360) -> 15360.0 (0x7380) + add('v_cvt_f16_u16', 'vop3', HI_SRC | 2051, wide=True) + for v in (0, 1, 65535): + add('v_cvt_f16_u16', 'vop3', v, clamp=1, wide=True) + + # v_cvt_f16_i16 (signed boundaries, RNE ties, clamp, source kinds) + for v in (0, 1, 0xFFFF, 0xFFFD, 2049, (-2049) & 0xFFFF, (-2051) & 0xFFFF, 0x7FFF, 0x8000): + add('v_cvt_f16_i16', 'vgpr', HI_SRC | v) + add('v_cvt_f16_i16', 'sgpr', HI_SRC | 0xFFFD) # -3.0 + add('v_cvt_f16_i16', 'lit', 0xCAFE8000) + add('v_cvt_f16_i16', 'inline_int', 0xFFFF, src_code=193) # -1.0 (0xBC00) + add('v_cvt_f16_i16', 'inline_int', (-16) & 0xFFFF, src_code=208) # -16.0 + add('v_cvt_f16_i16', 'inline_float', 0x3C00, src_code=242) + for v in (0xFFFD, 0, 1, 0x7FFF): + add('v_cvt_f16_i16', 'vop3', v, clamp=1, wide=True) + + # v_cvt_u16_f16 (truncation, clamping at 0..65535, NaN->0, abs/neg, source kinds) + for h in (0x0000, 0x8000, 0x0001, 0x8001, 0x3800, 0xB800, 0x4180, 0xC180, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE01): + add('v_cvt_u16_f16', 'vgpr', HI_SRC | h) + add('v_cvt_u16_f16', 'sgpr', HI_SRC | 0x4180) + add('v_cvt_u16_f16', 'lit', 0x12344580) # 5.5 -> 5 + add('v_cvt_u16_f16', 'inline_float', 0x4400, src_code=246) # 4.0 -> 4 + add('v_cvt_u16_f16', 'inline_float', 0xBC00, src_code=243) # -1.0 -> 0 + add('v_cvt_u16_f16', 'vop3', HI_SRC | 0xC180, abs0=1, wide=True) # |-2.75| -> 2 + add('v_cvt_u16_f16', 'vop3', HI_SRC | 0xC180, neg0=1, wide=True) # -(-2.75) -> 2 + add('v_cvt_u16_f16', 'vop3', HI_SRC | 0x4180, abs0=1, neg0=1, wide=True) # -|2.75| -> 0 + + # v_cvt_i16_f16 (truncation, clamping at -32768..32767, NaN->0, abs/neg, source kinds) + for h in (0x0000, 0x8000, 0x0001, 0x8001, 0x3800, 0xB800, 0x4180, 0xC180, + 0x77FF, 0x7800, 0x7BFF, 0xF800, 0xF801, 0xFBFF, 0x7C00, 0xFC00, 0x7E00, 0xFE01): + add('v_cvt_i16_f16', 'vgpr', HI_SRC | h) + add('v_cvt_i16_f16', 'sgpr', HI_SRC | 0xC180) + add('v_cvt_i16_f16', 'lit', 0xABCD7800) # 32768.0 -> 32767 + add('v_cvt_i16_f16', 'inline_float', 0xC400, src_code=247) # -4.0 -> -4 (0xFFFC) + add('v_cvt_i16_f16', 'vop3', HI_SRC | 0xF800, abs0=1, wide=True) # |-32768.0| -> 32767 + add('v_cvt_i16_f16', 'vop3', HI_SRC | 0xF800, neg0=1, wide=True) # -(-32768.0) -> 32767 + add('v_cvt_i16_f16', 'vop3', HI_SRC | 0x7800, abs0=1, neg0=1, wide=True) # -|32768.0| -> -32768 + + assert len(items) < F.STRIDE + return items + + +def emit_program(items): + code = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 128 + F.SHIFT), F.vmove(8, 7), sop1(3, 126, 129), + 0xBFA40000, 0xBFA5000F, 0xBA800881, 0] + want = [] + for index, (op, vop1_op, vop3_op, _, _, kind, src_val, src_code, abs0, neg0, clamp, wide, expected) in enumerate(items): + code += v_mov_lit(3, DST_SEED) + if kind == 'vgpr': + code += v_mov_lit(1, src_val) + [vop1(vop1_op, 3, 257)] + elif kind == 'sgpr': + code += [sop1(3, 10, 255), src_val, vop1(vop1_op, 3, 10)] + elif kind == 'lit': + code += [vop1(vop1_op, 3, 255), src_val] + elif kind in ('inline_int', 'inline_float'): + code += [vop1(vop1_op, 3, src_code)] + elif kind == 'vop3': + assert wide + code += v_mov_lit(1, src_val) + vop3_unary(vop3_op, 3, 257, abs0=abs0, neg0=neg0, clamp=clamp) + else: + raise AssertionError((op, kind)) + code += F.store(4 * index, 3) + want.append(HI_DST | expected) + code.append(0xBF810000) + return code, want + + +def check_mutants(items): + def match(got, expected): + return got == (HI_DST | expected) + + for op, _, _, signed, to_f16, _, _, _, _, _, clamp, _, expected in items: + assert match(HI_DST | expected, expected) + + # Zeroed upper half must fail. + assert any(not match(expected, expected) for _, _, _, _, _, _, _, _, _, _, _, _, expected in items) + + # Round-toward-zero instead of RNE on f16<-int must fail (2051 / 65519 / 32767). + assert any( + ref_cvt_f16_int(signed, F.INLINE_F16[sc] if kind == 'inline_float' else sv, clamp=bool(cl), rne=False) != exp + for _, _, _, signed, to_f16, kind, sv, sc, _, _, cl, _, exp in items if to_f16 + ) + + # Skipping NaN->0 on int<-f16 must fail. + assert any( + ref_cvt_int_f16(signed, F.INLINE_F16[sc] if kind == 'inline_float' else sv, abs0=a0, neg0=n0, nan_check=False) != exp + for _, _, _, signed, to_f16, kind, sv, sc, a0, n0, _, _, exp in items if not to_f16 + ) + + +def refusal_programs(): + programs = [] + for op, (vop1_op, vop3_op, _, to_f16) in OPS.items(): + programs.append(([vop1(vop1_op, 3, 250), 0xFF00B101, 0xBF810000], 'unsupported DPP arithmetic')) + programs.append(([vop1(vop1_op, 3, 249), 0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile')) + programs.append((vop3_unary(vop3_op, 3, 257, omod=1) + [0xBF810000], f'unsupported {op} clamp or omod')) + programs.append((vop3_unary(vop3_op, 3, 257, op_sel=1) + [0xBF810000], f'unsupported {op} high-half op_sel')) + programs.append((vop3_unary(vop3_op, 3, 257, op_sel=8) + [0xBF810000], f'unsupported {op} high-half op_sel')) + programs.append((vop3_unary(vop3_op, 3, 257, src1=1) + [0xBF810000], f'unsupported {op} operand modifiers')) + if to_f16: + programs.append((vop3_unary(vop3_op, 3, 257, abs0=1) + [0xBF810000], f'unsupported {op} operand modifiers')) + programs.append((vop3_unary(vop3_op, 3, 257, neg0=1) + [0xBF810000], f'unsupported {op} operand modifiers')) + else: + programs.append((vop3_unary(vop3_op, 3, 257, clamp=1) + [0xBF810000], f'unsupported {op} clamp or omod')) + + for op in ('v_cvt_f16_i16', 'v_cvt_i16_f16'): + insn = vop1(OPS[op][0], 3, 257) + programs.append(([0xBFA4000C, insn, 0xBF810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xBFA50000, insn, 0xBF810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xBA8005C1, 1, insn, 0xBF810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xB98005C1, insn, 0xBF810000], 'unsupported binary16 rounding or denormal mode')) + return programs + + +def _float_val(token, values): + if token.startswith('%'): + kind, bits = values[token] + assert kind == 'float', (token, kind) + return F._f32(bits) + return float(token) + + +def _fcmp(pred, a, b): + if pred == 'ord': + return not (math.isnan(a) or math.isnan(b)) + if pred == 'oge': + return a >= b + if pred == 'olt': + return a < b + if pred == 'ogt': + return a > b + raise AssertionError((pred, a, b)) + + +def _fptoi(signed, f): + val = int(math.trunc(f)) + return (val & 0xFFFFFFFF) + + +def interpret_cvt(ir_text): + """Evaluate lane 0 of the lowered DXIL IR, handling int<->float conversions and fcmp.""" + body = ir_text.split('define void @main()', 1)[1].split('\n}', 1)[0] + blocks, label, buf = {}, None, [] + for raw in body.splitlines(): + line = raw.strip() + if not line or line == '{': + continue + if line.endswith(':') and ' ' not in line: + if label is not None: + blocks[label] = buf + label, buf = line[:-1], [] + continue + if label is None: + raise AssertionError(line) + buf.append(line) + if label is not None: + blocks[label] = buf + values, memory, stores = {}, {}, [] + label, steps = 'entry', 0 + while steps < 200000: + steps += 1 + followed = False + for line in blocks[label]: + if line.startswith('br '): + label = F._branch(line, values) + followed = True + break + if line == 'ret void': + return sorted(stores) + m = re.fullmatch(r'(%\w+) = (.+)', line) + if m: + name, rhs = m.group(1), m.group(2) + if rhs.startswith(('sitofp i32 ', 'uitofp i32 ')): + parts = re.fullmatch(r'(sitofp|uitofp) i32 (\S+) to float', rhs) + raw = F._i32(parts.group(2), values) + val = float(F._signed(raw) if parts.group(1) == 'sitofp' else raw) + values[name] = ('float', struct.unpack('<I', struct.pack('<f', val))[0]) + continue + if rhs.startswith(('fptosi float ', 'fptoui float ')): + parts = re.fullmatch(r'(fptosi|fptoui) float (\S+) to i32', rhs) + val = _float_val(parts.group(2), values) + values[name] = ('i32', _fptoi(parts.group(1) == 'fptosi', val)) + continue + if rhs.startswith('fcmp '): + parts = re.fullmatch(r'fcmp (\w+) float (\S+), (\S+)', rhs) + ok = _fcmp(parts.group(1), _float_val(parts.group(2), values), _float_val(parts.group(3), values)) + values[name] = ('i1', int(ok)) + continue + if rhs.startswith('select i1 ') and ', float ' in rhs: + parts = re.fullmatch(r'select i1 (\S+), float (\S+), float (\S+)', rhs) + cond = F._i1(parts.group(1), values) + fval = _float_val(parts.group(2) if cond else parts.group(3), values) + values[name] = ('float', struct.unpack('<I', struct.pack('<f', fval))[0]) + continue + F._exec(line, values, memory, stores) + if not followed: + raise AssertionError('block fell through: ' + label) + raise AssertionError('step limit') + + +def ir(dumper): + items = cases() + check_mutants(items) + code, want = emit_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'cvt') + assert run.returncode == 0, run.stderr + stores = interpret_cvt(run.stdout) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i][0], hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (why, r.returncode, r.stderr) + print(f'native_cvt_f16_i16 IR: {len(want)} conversions match exact reference; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = cases() + check_mutants(items) + code, want = emit_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'legacyF32ToF16' not in dump, dump + + refusals = refusal_programs() + for n, (prog_words, why) in enumerate(refusals): + m = request(work, root, prog_words) + o = m.with_suffix(f'.refused{n}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_cvt_f16_i16 controls: compiled {len(want)} conversions to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = cases() + check_mutants(items) + code, want = emit_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + for group in range(F.GROUPS): + head = F.BASE + group * F.STRIDE + got = words_out[head:head + len(want)] + assert got == want, (group, [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(got, want)) if a != b][:8]) + words_out[F.BASE:F.BASE + len(want)] = [0] * len(want) + words_out[F.BASE + F.STRIDE:F.BASE + F.STRIDE + len(want)] = [0] * len(want) + assert all(w == F.SENTINEL for w in words_out if w != 0), 'guard overwritten' + print(f'native_cvt_f16_i16 hardware: {len(want)} conversions matched across {F.GROUPS} groups') + return 0 + + +def main(mode, tool, sdk=None): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_norm_f16_check.py b/tests/native_cvt_norm_f16_check.py new file mode 100644 index 0000000000..d468aafcfe --- /dev/null +++ b/tests/native_cvt_norm_f16_check.py @@ -0,0 +1,317 @@ +"""Direct DXIL VOP1/VOP3 v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +VOP1_OPS = {'i16': 0x63, 'u16': 0x64} +VOP3_OPS = {'i16': 0x1E3, 'u16': 0x1E4} +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + + +def vop1_cvt_norm(kind, dst, src0): + return [0x7E000000 | ((dst & 0xFF) << 17) | (VOP1_OPS[kind] << 9) | (src0 & 0x1FF)] + + +def vop3_cvt_norm(kind, dst, src0, *, abs_=0, neg=0, op_sel=0, clamp=0, omod=0, s1=0, s2=0): + w0 = (0xD4000000 | (VOP3_OPS[kind] << 16) | ((clamp & 1) << 15) | ((op_sel & 15) << 11) | + ((abs_ & 7) << 8) | (dst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def eval_cvt_norm(kind, raw_word, *, abs_=0, neg=0, op_sel=0, dst_init=DST_INIT): + signed = kind == 'i16' + bits = (raw_word >> (16 if (op_sel & 1) else 0)) & 0xFFFF + if abs_ & 1: + bits &= 0x7FFF + if neg & 1: + bits ^= 0x8000 + sign = bits & 0x8000 + mag = bits & 0x7FFF + if mag > 0x7C00 or mag == 0: + res = 0 + elif not signed: + if sign: + res = 0 + elif mag >= 0x3C00: + res = 0xFFFF + else: + exp = mag >> 10 + mant = mag if exp == 0 else (0x400 | (mag & 0x3FF)) + shift = 24 if exp == 0 else (25 - exp) + prod = mant * 65535 + q = prod >> shift + mid = 1 << (shift - 1) + rem = prod & ((1 << shift) - 1) + if rem > mid or (rem == mid and (q & 1)): + q += 1 + res = q + else: + if mag >= 0x3C00: + q = 32767 + else: + exp = mag >> 10 + mant = mag if exp == 0 else (0x400 | (mag & 0x3FF)) + shift = 24 if exp == 0 else (25 - exp) + prod = mant * 32767 + q = prod >> shift + mid = 1 << (shift - 1) + rem = prod & ((1 << shift) - 1) + if rem > mid or (rem == mid and (q & 1)): + q += 1 + res = ((-q) & 0xFFFF) if sign else q + if op_sel & 8: + return ((res & 0xFFFF) << 16) | (dst_init & 0xFFFF) + return (dst_init & 0xFFFF0000) | (res & 0xFFFF) + + +@dataclass(frozen=True) +class Case: + name: str + kind: str + src0: int + val0: int + wide: bool = False + abs_: int = 0 + neg: int = 0 + op_sel: int = 0 + exec_mask: int = ALL_EXEC + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + raw = self.val0 & 0xFFFFFFFF if (self.src0 < 128 or self.src0 >= 255) else inline_word(self.src0) + return eval_cvt_norm(self.kind, raw, abs_=self.abs_, neg=self.neg, op_sel=self.op_sel) + + +def all_cases(): + return [ + # 1. Signed zero, unity, saturation (>1 / <-1 / +/-Inf), and NaN -> 0 for i16 & u16. + Case('i16_neg_zero', 'i16', 257, 0x8000), + Case('u16_neg_zero', 'u16', 257, 0x8000), + Case('i16_pos_one_and_over', 'i16', 257, 0x7BFF3C00), # 1.0 -> 32767 (hi=65504 ignored) + Case('i16_neg_two_sat', 'i16', 257, 0xC000), # -2.0 -> -32767 (0x8001) + Case('u16_neg_clamp_zero', 'u16', 257, 0xBC00), # -1.0 -> 0 + Case('u16_pos_inf_sat', 'u16', 257, 0x7C00), # +Inf -> 65535 (0xffff) + Case('i16_neg_inf_sat', 'i16', 257, 0xFC00), # -Inf -> -32767 (0x8001) + Case('u16_neg_inf_zero', 'u16', 257, 0xFC00), # -Inf -> 0 + Case('i16_nan_zero', 'i16', 257, 0x7E01), # NaN -> 0 + Case('u16_neg_nan_zero', 'u16', 257, 0xFC01), # -NaN -> 0 + # 2. Exact halfway ties and binary32 double-rounding / subnormal discriminators. + Case('i16_half_tie_even', 'i16', 257, 0x3800), # 0.5 * 32767 = 16383.5 -> 16384 (even) + Case('u16_half_tie_even', 'u16', 257, 0x3800), # 0.5 * 65535 = 32767.5 -> 32768 (even) + Case('i16_neg_half_tie_even', 'i16', 257, 0xB800), # -0.5 -> -16384 (0xc000) + Case('i16_dbl_round_3801', 'i16', 257, 0x3801), # 1025/2048 * 32767 = 16399.4997 -> 16399 + Case('u16_dbl_round_3801', 'u16', 257, 0x3801), # 1025/2048 * 65535 = 32799.4995 -> 32799 + Case('i16_dbl_round_b802', 'i16', 257, 0xB802), # -1026/2048 * 32767 -> -16415 + Case('u16_max_subnormal', 'u16', 257, 0x03FF), # 0x03ff * 65535 / 2^24 -> 4 + Case('i16_neg_max_subnormal', 'i16', 257, 0x83FF), # -0x03ff * 32767 / 2^24 -> -2 (0xfffe) + Case('u16_lt_one_3bff', 'u16', 257, 0x3BFF), # (1 - 2^-11) * 65535 = 65503.0005 -> 65503 + # 3. VOP3 modifiers: separate abs, neg, and high-half op_sel[0]/op_sel[3]. + Case('i16_vop3_abs', 'i16', 257, 0x7BFFB800, wide=True, abs_=1), + Case('u16_vop3_neg', 'u16', 257, 0x7BFFB800, wide=True, neg=1), + Case('i16_vop3_opsel_hi_src', 'i16', 257, 0x38000000, wide=True, op_sel=0b0001), + Case('u16_vop3_opsel_hi_dst', 'u16', 257, 0x00003800, wide=True, op_sel=0b1000), + Case('i16_vop3_opsel_hi_rw', 'i16', 257, 0xB800BEEF, wide=True, op_sel=0b1001), + # 4. SGPR, literal (255), inline f16 float (240/248), inline int (129/193), and partial EXEC_LO. + Case('u16_sgpr_src0', 'u16', 10, 0x3800), + Case('i16_literal_src0', 'i16', 255, 0x3802), + Case('u16_inline_f16_248', 'u16', 248, 0), + Case('i16_inline_int_129', 'i16', 129, 0), + Case('i16_inline_int_193_nan', 'i16', 193, 0), + Case('u16_partial_exec', 'u16', 257, 0x7BFF3800, exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + if c.src0 >= 256: + code += F.mov(c.src0 - 256, c.val0) + elif c.src0 <= 105: + code += F.smov(c.src0, c.val0) + elif c.src0 == 255: + lit_tail = [c.val0] + if c.wide: + code += vop3_cvt_norm(c.kind, 4, c.src0, abs_=c.abs_, neg=c.neg, op_sel=c.op_sel) + else: + code += vop1_cvt_norm(c.kind, 4, c.src0) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = vop1_cvt_norm('i16', 4, 257) + [0xBF810000] + return [ + # Clamp and omod refused on both forms. + (vop3_cvt_norm('i16', 4, 257, clamp=1) + [0xBF810000], 'unsupported v_cvt_norm_i16_f16 clamp or omod'), + (vop3_cvt_norm('u16', 4, 257, omod=1) + [0xBF810000], 'unsupported v_cvt_norm_u16_f16 clamp or omod'), + # Unused VOP3 operand modifier / op_sel bits. + (vop3_cvt_norm('u16', 4, 257, op_sel=0b0010) + [0xBF810000], 'unsupported v_cvt_norm_u16_f16 operand modifiers'), + (vop3_cvt_norm('i16', 4, 257, s1=258) + [0xBF810000], 'unsupported v_cvt_norm_i16_f16 operand modifiers'), + # High-half op_sel on non-VGPR source. + (vop3_cvt_norm('u16', 4, 10, op_sel=0b0001) + [0xBF810000], + 'unsupported v_cvt_norm_u16_f16 high-half op_sel on non-VGPR source'), + # DPP16 and SDWA forms. + (vop1_cvt_norm('i16', 4, 250) + [0xFF00E401, 0xBF810000], 'unsupported DPP arithmetic'), + (vop1_cvt_norm('u16', 4, 249) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar source (vcc_lo). + (vop1_cvt_norm('i16', 4, 106) + [0xBF810000], 'unsupported v_cvt_norm_i16_f16 source'), + # Unsupported binary16 rounding/denorm modes and dynamic conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'cvt-norm-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_cvt_norm_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert '32767' in dump and '65535' in dump and 'lshr i32' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_cvt_norm_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_cvt_norm_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'cvt-norm-f16-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_cvt_norm_f16 pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_off_f32_i4_check.py b/tests/native_cvt_off_f32_i4_check.py new file mode 100644 index 0000000000..4620e010e9 --- /dev/null +++ b/tests/native_cvt_off_f32_i4_check.py @@ -0,0 +1,158 @@ +"""Direct compute VOP1/VOP3A v_cvt_off_f32_i4 (signed 4-bit offset [-8..+7] / 16.0 to binary32).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF + +# Eight input words whose low nibbles span 0..7 and 8..15 (with non-zero upper 28 bits that must be ignored). +CASES = ( + 0xDEAD0000, # 0 -> 0.0 + 0xBEEF0001, # +1 -> +0.0625 + 0xCAFE0004, # +4 -> +0.25 + 0xBABE0007, # +7 -> +0.4375 + 0x12340008, # -8 -> -0.5 + 0x5678000C, # -4 -> -0.25 + 0x9ABC000F, # -1 -> -0.0625 + 0xFFFFFFF2, # +2 -> +0.125 +) +# (wide, omod, clamp) +FORMS = ( + (False, 0, 0), # VOP1 v_cvt_off_f32_i4_e32 + (True, 0, 0), # VOP3A v_cvt_off_f32_i4_e64 + (True, 1, 0), # VOP3A mul:2 + (True, 0, 1), # VOP3A clamp [0.0, 1.0] +) + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3a(op, vdst, src0, src1=0, src2=0, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | (clamp << 15) | ((op_sel & 0xF) << 11) | ((abs_bits & 7) << 8) | (vdst & 0xFF) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((src2 & 0x1FF) << 18) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def program(*, sparse=False, drop_clamp=False, first_modifier=0, second_modifier=0): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, val in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), val] # v_xor_b32 v1, val, v0 (exercises all 16 nibble values across lanes) + for mode, (wide, omod, clamp) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + if wide: + w0, w1 = vop3a(0x18E, 4, 257, omod=omod, clamp=1 if (clamp and not drop_clamp) else 0) + if (first_modifier or second_modifier) and case == 0 and mode == 1: + w0 ^= first_modifier + w1 ^= second_modifier + code += [w0, w1] + else: + code += [vop1(0x0E, 4, 257)] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def cvt_off_f32_i4(word, omod, clamp): + nib = word & 0xF + s4 = nib - 16 if nib >= 8 else nib + val = s4 * 0.0625 + if omod == 1: + val *= 2.0 + elif omod == 2: + val *= 4.0 + elif omod == 3: + val *= 0.5 + if clamp: + val = max(0.0, min(1.0, val)) + return struct.unpack('<I', struct.pack('<f', val))[0] + + +def reference(sparse=False, ignore_clamp=False): + words = [SENTINEL] * 8 + for lane in range(64): + for val in CASES: + for _wide, omod, clamp in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + cvt_off_f32_i4(val ^ (lane % 32), omod, clamp and not ignore_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + # Valid encoding + 5 refused VOP3A encodings: + # abs (w0[8]), neg (w1[29]), op_sel (w0[11]), nonzero src1 (w1[9]), nonzero src2 (w1[18]). + refusal_cases = ( + (0, 0, ''), + (1 << 8, 0, 'integer conversion source modifier'), + (0, 1 << 29, 'integer conversion source modifier'), + (1 << 11, 0, 'op_sel'), + (0, 1 << 9, 'unused src1/src2'), + (0, 1 << 18, 'unused src1/src2'), + ) + for first, second, needle in refusal_cases: + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and needle in result.stderr, (first, second, result.stderr) + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'ashr i32 ' in dump and ', 28' in dump and 'sitofp i32 ' in dump, dump + assert reference() != reference(ignore_clamp=True) + assert reference() != reference(sparse=True) + print('v_cvt_off_f32_i4 DXIL verified; five VOP3A modifier/unused-src encodings refused; clamp and EXEC differ') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse, drop_clamp in ((False, False), (True, False), (False, True)): + marker = request(work, root, program(sparse=sparse, drop_clamp=drop_clamp)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse, ignore_clamp=drop_clamp) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} drop_clamp={drop_clamp} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + if drop_clamp: + changed = sum(a != b for a, b in zip(actual, reference())) + assert changed > 0, 'dropping clamp did not change the readback' + print(f'no-clamp control: {changed} words differed from the clamped reference') + else: + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_cvt_off_f32_i4_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_pk16_check.py b/tests/native_cvt_pk16_check.py new file mode 100644 index 0000000000..c4f8e8eae9 --- /dev/null +++ b/tests/native_cvt_pk16_check.py @@ -0,0 +1,113 @@ +"""v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 in the direct compute path (#2995). + + native_cvt_pk16_check.py controls <compile_dxil> <sdk bin dir> + native_cvt_pk16_check.py hardware <native_store_replay> <sdk bin dir> + +Both saturate S0 and S1 to 16 bits and pack S0 into the low and S1 into the high half (gfx2hlsl.py's VOP3 table): +v_cvt_pk_u16_u32 takes min(S, 0xffff) of the unsigned values, v_cvt_pk_i16_i32 clamps the signed values to +[-32768, 32767]. A nonzero unused SRC2 field and op_sel are refused (gfx2hlsl.py refuses the SRC2 field). The VOP3 words were assembled with +LLVM 15.0.7 (clang -cc1as, gfx1013); the v_mov and store words follow the encodings of native_align_bfm_check.py. + +Each operand pair below is set by v_mov literals and converted by both instructions; every lane of two groups of +32 stores the sixteen results. The pairs cross both bounds of both forms. References that truncate instead of +saturating and that apply the unsigned bound to the signed form must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +PAIRS = [(0, 0xFFFF), (0x10000, 0xFFFFFFFF), (0xFFFF8000, 0xFFFF7FFF), (0x7FFF, 0x8000), + (0x12345, 0x7FFFFFFF), (0x80000000, 5), (0xFFFFFFFE, 0xFFFE), (1, 0x00010001)] +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 11 / +# v_lshlrev_b32 v8, 6, v0 / v_add_nc_u32 v8, s7, v8: 64 bytes per lane, 2048 per group of 32 +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078B05, 0x34100086, 0x4A101007] +CVT_U16, CVT_I16 = (0xD76A0004, 0x00020501), (0xD76B0005, 0x00020501) # v4 / v5 from v1, v2 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def program(src2=0): + code = PROLOGUE + [0xBF8CC07F] # s_waitcnt lgkmcnt(0) before the stores use s[32:35] + for index, (x, y) in enumerate(PAIRS): + code += [0x7E0202FF, x, 0x7E0402FF, y, + CVT_U16[0], CVT_U16[1] | src2 << 18, CVT_I16[0], CVT_I16[1] | src2 << 18] + for slot, vgpr in enumerate((4, 5)): + code += [0xE0701000 | (8 * index + 4 * slot), 0x80080008 | vgpr << 8] # buffer_store_dword v, v8, s[32:35] + return code + [0xBF810000] + + +def signed(x): + return x - (1 << 32) if x & 0x80000000 else x + + +def pack(x, y, truncate=False, unsigned_bound=False): + if truncate: + return (x & 0xFFFF) | ((y & 0xFFFF) << 16), (x & 0xFFFF) | ((y & 0xFFFF) << 16) + u = min(x, 0xFFFF) | (min(y, 0xFFFF) << 16) + clamp = (lambda v: min(v, 0x7FFF)) if unsigned_bound else (lambda v: max(-32768, min(32767, signed(v)))) + i = (clamp(x) & 0xFFFF) | ((clamp(y) & 0xFFFF) << 16) + return u, i + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(64): + base = GUARD_WORDS + lane * 16 + for index, (x, y) in enumerate(PAIRS): + expected[base + 2 * index:base + 2 * index + 2] = pack(x, y, **mutation) + return expected + + +def compile_program(cli, sdk, work, root, code): + marker = request(work, root, code) + return marker, subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + +def controls(cli, sdk, work, root): + marker, result = compile_program(cli, sdk, work, root, program()) + assert result.returncode == 0 and marker.with_suffix('.cso').is_file(), (result.stdout, result.stderr) + _, result = compile_program(cli, sdk, work, root, program(src2=3)) + assert result.returncode and 'with unused src2 field set' in result.stderr, (result.stdout, result.stderr) + code = program() + code[code.index(CVT_U16[0])] |= 1 << 11 # op_sel bit of src0 + _, result = compile_program(cli, sdk, work, root, code) + assert result.returncode and 'with op_sel' in result.stderr, (result.stdout, result.stderr) + expected = reference() + for label, mutant in (('truncated', reference(truncate=True)), ('unsigned bound', reference(unsigned_bound=True))): + assert mutant != expected, label + print('compiled; a nonzero src2 field and op_sel refused; the truncating and unsigned-bound references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, reference())) if x != y] + assert not diff, diff[:10] + print('v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32: all 2064 words matched (1024 results, guards and sentinels)') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_pk_u8_check.py b/tests/native_cvt_pk_u8_check.py new file mode 100644 index 0000000000..606b5dc4e5 --- /dev/null +++ b/tests/native_cvt_pk_u8_check.py @@ -0,0 +1,150 @@ +"""v_cvt_pk_u8_f32 in the direct compute path (#2997). + + native_cvt_pk_u8_check.py controls <compile_dxil> <sdk bin dir> + native_cvt_pk_u8_check.py hardware <native_store_replay> <sdk bin dir> + +D = (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]). The conversion is the one gfx2hlsl.py +measured on RDNA 2 hardware (see docs/experiments.md): round to nearest even, saturated to [0, 255], with NaN, both +zeros and every negative value giving 0 and +inf giving 255. The VOP3 word (opcode 0x15e) was assembled with LLVM +15.0.7 (clang -cc1as, gfx1013); the other words were checked with tools/disasm_rdna2.py --hex. + +One dispatch sets S0 from literals. Another derives every integer from 0 to 255, the halfway value above +it, and both adjacent binary32 values from the lane and group. Both check the packed byte and the untouched bytes. +""" +from pathlib import Path +import math +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_dpp_mirror_check import vop2 + +REST = 0xA5A5A5A5 +F = lambda value: struct.unpack('<I', struct.pack('<f', value))[0] # noqa: E731 +CASES = [(F(0.5), 0), (F(1.5), 1), (F(2.5), 2), (F(254.5), 3), (F(255.5), 0), (F(1e30), 1), (0x7F800000, 2), + (0x80000000, 3), (F(-1.0), 0), (0x7FC00000, 1), (0x00000001, 2), (F(127.4999), 3), (F(3.0), 6), + (0xFF800000, 0), (F(0.0), 1), (F(255.0), 2)] +LANES = 64 +CASES_PER_LANE = 16 +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078B05, 0x34100086, 0x4A101007, 0xBF8CC07F] +CVT = (0xD55E0004, 0x040E0501) # v_cvt_pk_u8_f32 v4, v1, v2, v3 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def pack_and_store(index, select, modifier=0): + return [0x7E0402FF, select, CVT[0], CVT[1] | modifier, + 0xE0701000 | 4 * index, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + + +def program(modifier=0): + code = PROLOGUE + [0x7E0602FF, REST] # v_mov_b32 v3, 0xa5a5a5a5 + for index, (value, select) in enumerate(CASES): + code += [0x7E0202FF, value] + pack_and_store(index, select, modifier) + return code + [0xBF810000] + + +def lane_program(): + # v8 is the byte address of this lane's 16-word output row. + code = PROLOGUE + [0x7E0602FF, REST, vop2(0x16, 10, 134, 8)] # v10 = v8 >> 6 + for batch in range(4): + code += [vop2(0x25, 9, 255, 10), batch * LANES, # v_add_nc_u32 v9, literal, v10 + 0x7E120D09, # v_cvt_f32_u32 v9, v9 + vop2(0x03, 11, 240, 9)] # v_add_f32 v11, 0.5, v9 + base = batch * 4 + code += [0x7E020309] + pack_and_store(base, batch) # v_mov_b32 v1, v9 + for slot, delta in enumerate((193, 128, 129), start=1): # inline -1, 0, and 1 + code += [vop2(0x25, 1, delta, 11)] + pack_and_store(base + slot, (batch + slot) & 3) + return code + [0xBF810000] + + +def lane_cases(lane): + for batch in range(4): + integer = batch * LANES + lane + halfway = F(integer + 0.5) + yield F(integer), batch + for slot, delta in enumerate((-1, 0, 1), start=1): + yield halfway + delta, (batch + slot) & 3 + + +def to_u8(bits, half_up=False, truncate=False, lax=False): + value = struct.unpack('<f', struct.pack('<I', bits))[0] + if math.isnan(value) or value <= 0: + if not lax or math.isnan(value): + return 0 + return int(max(-128, value)) & 0xFF # a lowering that forgets the zero test + value = min(value, 255.0) + if truncate: + return int(value) + if half_up: + return int(math.floor(value + 0.5)) + return round(value) # Python rounds half to even + + +def reference(dynamic=False, **mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(LANES): + base = GUARD_WORDS + lane * CASES_PER_LANE + for index, (value, select) in enumerate(lane_cases(lane) if dynamic else CASES): + shift = 8 * (select & 3) + expected[base + index] = (REST & ~(0xFF << shift) & 0xFFFFFFFF) | (to_u8(value, **mutation) << shift) + return expected + + +def compile_program(cli, sdk, work, root, code): + marker = request(work, root, code) + return marker, subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + +def controls(cli, sdk, work, root): + # Keep the conversion out of the driver's floating-point rounding path for both input sources. + for code in (program(), lane_program()): + marker, result = compile_program(cli, sdk, work, root, code) + compiled = marker.with_suffix('.cso') + assert result.returncode == 0 and compiled.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', compiled], capture_output=True, + text=True, check=True).stdout + assert '@dx.op.unary.f32(i32 26,' not in dump and 'fptoui' not in dump, dump + _, result = compile_program(cli, sdk, work, root, program(modifier=1 << 29)) # neg on S0 + assert result.returncode and 'direct ALU operand modifiers' in result.stderr, (result.stdout, result.stderr) + expected = reference() + for label, mutation in (('half up', {'half_up': True}), ('truncated', {'truncate': True}), + ('negatives let through', {'lax': True})): + assert reference(**mutation) != expected, label + assert reference(dynamic=True, half_up=True) != reference(dynamic=True) + print('literal and lane-derived programs compiled without Round_ne or fptoui; negated source refused; ' + 'half-up, truncating and negative-passing references differ') + return 0 + + +def hardware(replay, sdk, work, root): + for label, code, dynamic in (('literal', program(), False), ('lane-derived', lane_program(), True)): + marker = request(work, root, code) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes()) + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, reference(dynamic))) if x != y] + assert not diff, (label, diff[:10]) + print(f'v_cvt_pk_u8_f32 {label}: all 2064 words matched (1024 results, guards and sentinels)') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_cvt_pknorm_f32_check.py b/tests/native_cvt_pknorm_f32_check.py new file mode 100644 index 0000000000..ab4788e317 --- /dev/null +++ b/tests/native_cvt_pknorm_f32_check.py @@ -0,0 +1,350 @@ +"""Direct DXIL VOP3 v_cvt_pknorm_i16_f32 and v_cvt_pknorm_u16_f32 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from fractions import Fraction +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OPS = {'i16': 0x368, 'u16': 0x369} +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + +INLINE_F32_WORDS = { + 240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000, + 248: 0x3E22F983, +} + + +def inline_f32_word(enc): + if enc in INLINE_F32_WORDS: + return INLINE_F32_WORDS[enc] + if 128 <= enc <= 192: + return enc - 128 + if 193 <= enc <= 208: + return (192 - enc) & 0xFFFFFFFF + raise ValueError(enc) + + +def vop3_pknorm(kind, dst, srcs, *, abs_=0, neg=0, op_sel=0, clamp=0, omod=0, s2=0): + s0, s1 = srcs + w0 = (0xD4000000 | (OPS[kind] << 16) | ((clamp & 1) << 15) | ((op_sel & 15) << 11) | + ((abs_ & 7) << 8) | (dst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def cvt_norm_f32_half(kind, bits): + bits &= 0xFFFFFFFF + if (bits & 0x7FFFFFFF) > 0x7F800000: + return 0 + val = struct.unpack('<f', struct.pack('<I', bits))[0] + if kind == 'u16': + if math.isnan(val) or val <= 0.0: + return 0 + if val >= 1.0: + return 0xFFFF + scaled = Fraction(val) * 65535 + else: + if val == 0.0: + return 0 + if val >= 1.0: + return 32767 + if val <= -1.0: + return (-32767) & 0xFFFF + scaled = Fraction(val) * 32767 + neg_sign = scaled < 0 + mag = abs(scaled) + q = int(mag) + rem = mag - q + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (q & 1)): + q += 1 + return ((-q) & 0xFFFF) if neg_sign else (q & 0xFFFF) + + +def eval_pknorm(kind, raw0, raw1, *, abs_=0, neg=0): + words = [] + for j, w in enumerate((raw0, raw1)): + bits = w & 0xFFFFFFFF + if (abs_ >> j) & 1: + bits &= 0x7FFFFFFF + if (neg >> j) & 1: + bits ^= 0x80000000 + words.append(cvt_norm_f32_half(kind, bits)) + return words[0] | (words[1] << 16) + + +@dataclass(frozen=True) +class Case: + name: str + kind: str + srcs: tuple + vals: tuple + abs_: int = 0 + neg: int = 0 + exec_mask: int = ALL_EXEC + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + raw = [v & 0xFFFFFFFF if (s < 128 or s >= 255) else inline_f32_word(s) + for s, v in zip(self.srcs, self.vals)] + return eval_pknorm(self.kind, raw[0], raw[1], abs_=self.abs_, neg=self.neg) + + +def all_cases(): + return [ + # 1. Zeros, subnormals, 2^-17 boundary, unity, saturation (>1, <-1, +/-Inf), and NaNs. + Case('i16_signed_zeros', 'i16', (257, 258), (0x00000000, 0x80000000)), + Case('u16_neg_and_pos_zero', 'u16', (257, 258), (0x80000000, 0x00000000)), + Case('i16_subnormals', 'i16', (257, 258), (0x00000001, 0x807FFFFF)), + Case('u16_2m17_boundary', 'u16', (257, 258), (0x37000000, 0x37000100)), # 0.5-eps -> 0, 0.5+eps -> 1 + Case('i16_2m17_neg_subone', 'i16', (257, 258), (0xB7000000, 0x3F7FFFFF)), # -> 0, 32767 + Case('u16_tiny_and_almost_one', 'u16', (257, 258), (0x34000000, 0x3F7FFFFF)), # -> 0, 65535 + Case('i16_unity_sat', 'i16', (257, 258), (0x3F800000, 0xBF800000)), # -> +32767, -32767 + Case('u16_unity_neg_sat', 'u16', (257, 258), (0x3F800000, 0xBF800000)), # -> 65535, 0 + Case('i16_over_under_sat', 'i16', (257, 258), (0x40000000, 0xC0000000)), # 2.0, -2.0 -> 32767, -32767 + Case('u16_over_under_sat', 'u16', (257, 258), (0x60000000, 0xC0000000)), # large, -2.0 -> 65535, 0 + Case('i16_infs', 'i16', (257, 258), (0x7F800000, 0xFF800000)), + Case('u16_infs', 'u16', (257, 258), (0x7F800000, 0xFF800000)), + Case('i16_nans', 'i16', (257, 258), (0x7FC00001, 0xFF800001)), + Case('u16_nans', 'u16', (257, 258), (0x7F800001, 0xFFC00001)), + # 2. Exact halfway RNE ties and p_lo != 0 carry-over tie-break witnesses. + Case('i16_half_ties', 'i16', (257, 258), (0x3F000000, 0xBF000000)), # 0.5 -> 16384, -0.5 -> -16384 + Case('u16_half_and_quarter', 'u16', (257, 258), (0x3F000000, 0x3E800000)), # 0.5 -> 32768, 0.25 -> 16384 + Case('i16_neg_quarter', 'i16', (257, 258), (0xBE800000, 0x3E800000)), # -0.25 -> -8192, 0.25 -> 8192 + Case('u16_p_lo_tie_witness', 'u16', (257, 258), (0x3F000101, 0xBF000101)), # 32768.50389 -> 32769 (kills drop p_lo) + Case('i16_p_lo_tie_witness', 'i16', (257, 258), (0x3F000201, 0xBF000201)), # +-16384.50192 -> +-16385 + # Single-rounding exact product vs binary32-multiply-then-RNE witnesses: + Case('i16_single_round_sep', 'i16', (257, 258), (0x3F000400, 0x38400180)), # 16385 vs 16386, 1 vs 2 + Case('u16_single_round_sep', 'u16', (257, 258), (0x3F000200, 0x37C000C0)), # 32769 vs 32770, 1 vs 2 + # 3. VOP3 abs[1:0] and neg[1:0] across both operands. + Case('i16_abs_both', 'i16', (257, 258), (0xBF000000, 0xBE800000), abs_=0b11), + Case('i16_neg_both', 'i16', (257, 258), (0x3F000000, 0x3F800000), neg=0b11), + Case('u16_abs_neg_mix', 'u16', (257, 258), (0xBF000000, 0xBF000000), abs_=0b01, neg=0b10), + # 4. SGPR, literal (255), inline f32 (240/241/242/248), inline int (128), and partial EXEC_LO. + Case('u16_sgpr_literal', 'u16', (10, 255), (0x3F000000, 0x3F000101)), + Case('i16_inline_f32', 'i16', (240, 243), (0, 0)), + Case('u16_inline_248_128', 'u16', (248, 128), (0, 0)), + Case('i16_partial_exec', 'i16', (257, 258), (0x3F800000, 0xBF000000), exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + for s, v in zip(c.srcs, c.vals): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3_pknorm(c.kind, 4, c.srcs, abs_=c.abs_, neg=c.neg) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + return [ + # clamp and omod refused. + (vop3_pknorm('i16', 4, (257, 258), clamp=1) + [0xBF810000], 'unsupported v_cvt_pknorm_i16_f32 clamp or omod'), + (vop3_pknorm('u16', 4, (257, 258), omod=1) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 clamp or omod'), + # op_sel, third-operand abs/neg, and nonzero src2 refused. + (vop3_pknorm('u16', 4, (257, 258), op_sel=1) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 operand modifiers'), + (vop3_pknorm('i16', 4, (257, 258), op_sel=8) + [0xBF810000], 'unsupported v_cvt_pknorm_i16_f32 operand modifiers'), + (vop3_pknorm('i16', 4, (257, 258), abs_=4) + [0xBF810000], 'unsupported v_cvt_pknorm_i16_f32 operand modifiers'), + (vop3_pknorm('u16', 4, (257, 258), neg=4) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 operand modifiers'), + (vop3_pknorm('u16', 4, (257, 258), s2=259) + [0xBF810000], 'unsupported v_cvt_pknorm_u16_f32 operand modifiers'), + # Unsupported special operand encoding (e.g. 254). + (vop3_pknorm('i16', 4, (254, 258)) + [0xBF810000], 'direct DXIL operand encoding'), + ] + + +def cvt_norm_f32_half_mul_f32_oracle(kind, bits): + """Alternative binary32-multiply-then-RNE oracle (separated by *_single_round_sep).""" + bits &= 0xFFFFFFFF + if (bits & 0x7FFFFFFF) > 0x7F800000: + return 0 + val = struct.unpack('<f', struct.pack('<I', bits))[0] + if kind == 'u16': + if math.isnan(val) or val <= 0.0: + return 0 + if val >= 1.0: + return 0xFFFF + scaled = Fraction(struct.unpack('<f', struct.pack('<f', val * 65535.0))[0]) + else: + if val == 0.0: + return 0 + if val >= 1.0: + return 32767 + if val <= -1.0: + return (-32767) & 0xFFFF + scaled = Fraction(struct.unpack('<f', struct.pack('<f', val * 32767.0))[0]) + neg_sign = scaled < 0 + mag = abs(scaled) + q = int(mag) + rem = mag - q + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (q & 1)): + q += 1 + return ((-q) & 0xFFFF) if neg_sign else (q & 0xFFFF) + + +def check_oracle_separation(): + assert cvt_norm_f32_half('i16', 0x3F000400) == 16385 and cvt_norm_f32_half_mul_f32_oracle('i16', 0x3F000400) == 16386 + assert cvt_norm_f32_half('i16', 0x38400180) == 1 and cvt_norm_f32_half_mul_f32_oracle('i16', 0x38400180) == 2 + assert cvt_norm_f32_half('u16', 0x3F000200) == 32769 and cvt_norm_f32_half_mul_f32_oracle('u16', 0x3F000200) == 32770 + assert cvt_norm_f32_half('u16', 0x37C000C0) == 1 and cvt_norm_f32_half_mul_f32_oracle('u16', 0x37C000C0) == 2 + + +def ir(dumper): + check_oracle_separation() + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'cvt-pknorm-f32') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_cvt_pknorm_f32 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + check_oracle_separation() + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert '32767' in dump and '65535' in dump and 'lshr i32' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_cvt_pknorm_f32 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_cvt_pknorm_f32 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'cvt-pknorm-f32-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_cvt_pknorm_f32 pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_descriptor_scc_check.py b/tests/native_descriptor_scc_check.py new file mode 100644 index 0000000000..8ee3457143 --- /dev/null +++ b/tests/native_descriptor_scc_check.py @@ -0,0 +1,154 @@ +"""Observe the SCC of a buffer stride extraction and both MAX operand orders.""" + +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import KEY, SENTINEL, TGID_X, TGID_Y, TGID_Z, USER7, WORDS + + +def program(*, runtime=False): + offset = 0 if runtime else 32 + table, constant = (6, 4) if runtime else (4, 5) + words = [sop1(3, 20, table), sop1(3, 21, 128), + 0xf408040a, 0xfa000000 | offset, # input SRV in s[16:19] + 0xf408080a, 0xfa000000 | (offset + 32), # output UAV in s[32:35] + 0xbf8cc07f, + scalar(0x27, 25, 17, 255), 0xe0010, # s_bfe_u32: 14-bit stride + sop1(3, 26, 253), + scalar(9, 27, 25, 129), sop1(3, 28, 253), + scalar(9, 29, 129, 25), sop1(3, 30, 253)] + if runtime: + # Flatten the 3x2x2 Dispatch so each group owns four output words. + words += [scalar(0x26, 8, 8, 131), scalar(0x26, 9, 9, 134), + scalar(0, 6, 7, 8), scalar(0, 6, 6, 9)] + words += [scalar(0x1e, 7, 6, 132), vmove(8, 7), sop1(3, 126, 129)] + for i, reg in enumerate((26, 28, 30, constant)): + words += [vmove(10, reg), 0xe0701000 | (4 * i), 0x80080a08] + return words + [0xbf810000] + + +def main(compile_dxil, replay, sdk, backend): + with TemporaryDirectory() as directory: + work = Path(directory) + dxc = Path(sdk) / "dxc.exe" + source, root = work / "root.hlsl", work / "root.bin" + requests = work / "requests" + requests.mkdir() + # s5 is one root constant and s6 is the X group ID. Exercise b0 with + # the descriptor metadata appended to a regular root constant. + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x80 | 6 << 1) + + def root_bytes(srv_count): + source.write_text(f'#define RS "DescriptorTable(SRV(t0,numDescriptors={srv_count}),' + f'UAV(u0,numDescriptors={3 - srv_count},offset={srv_count})),' + 'RootConstants(num32BitConstants=1,b0)"\n', encoding="ascii") + subprocess.run([dxc, "-T", "rootsig_1_1", "-E", "RS", source, "-Fo", root], check=True) + return root.read_bytes() + + marker = write_request(requests, program(), root_bytes(2), sa) + prefix = [compile_dxil, sdk, work / "cache", "gfx1013-direct-cs@0"] + for hit in (0, 1): + published = work / f"published-{hit}" + result = subprocess.run([*prefix, "--requests", requests, published], + capture_output=True, text=True) + assert result.returncode == 0 and f"frontend_cache_hit={hit}" in result.stdout, result.stdout + result.stderr + [manifest] = published.glob("*.txt") + # The native output revision line (#3006) is checked separately; the binding lines stay exact. + lines = manifest.read_text().splitlines() + assert sum(line.startswith("native ") for line in lines) == 1, manifest.read_text() + assert [line for line in lines if not line.startswith("native ")] == [ + "x2w-manifest 2", "stage cs", "group 32 1 1", "ud 2", + "udsrc 0 rootconst 1 0", "udsrc 1 stride 0", + "srv 0 buf table 0 32", "uav 0 table 0 64", + ], manifest.read_text() + print("cold and warm manifests both bind the stride of SRV 0 after the root constant") + + negative = work / "negative" + negative.mkdir() + bad = write_request(negative, program(), root_bytes(1), sa) + result = subprocess.run([*prefix, bad, work / "bad.cso"], capture_output=True, text=True) + assert result.returncode and "numeric SCC from a symbolic descriptor field" in result.stderr, result.stderr + print("the same descriptor load from a UAV range is refused") + + mode = "--direct-warp" if backend == "warp" else "--direct" + readback, metadata = work / "readback.bin", work / "stride.txt" + for value in (0, 1, 4, 16, 0x4000, 0x7fff): + metadata.write_text(str(value), encoding="ascii") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, mode, metadata], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stderr.strip()) + return 77 + assert result.returncode == 0, result.stdout + result.stderr + stride = value & 0x3fff + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + group * 4 + expected[start:start + 4] = [int(stride != 0), int(stride > 1), int(1 > stride), 3] + actual = list(struct.unpack("<2064I", readback.read_bytes())) + assert actual == expected, next((i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b) + print(f"stride word {value}: two groups match {expected[8:12]} and all guards") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", readback, mode], + capture_output=True, text=True) + assert result.returncode == 1 and "compute descriptor stride metadata missing" in result.stderr, result.stderr + print("missing stride metadata is rejected before dispatch") + return 0 + + +def runtime_main(compile_dxil, consumer, sdk, backend): + with TemporaryDirectory() as directory: + work = Path(directory) + cache, env = prepare_case(work, backend) + env.pop("X2W_NATIVE_SHADERS", None) + env.pop("X2W_NATIVE_SHADERS_ONLY", None) + env["X2W_TEST_DISPATCH_FIELDS"] = str(work / "descriptor.bin") + fields = Path(env["X2W_TEST_DISPATCH_FIELDS"]) + fields.write_bytes(struct.pack("<6I", 4, 64, 0, 4, WORDS, 0)) + code = program(runtime=True) + (work / "program").write_bytes(struct.pack(f"<{len(code)}I", *code)) + (work / "state").write_bytes(state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z)) + got, result = dispatch(work, consumer, env, "dispatch-records32", probe=True) + assert got == [SENTINEL] * WORDS and lines(result, "refused: no translation"), result.stderr + [marker] = cache.glob("req_*.c67") + + for route in ("native", "published"): + selected = dict(env) + if route == "native": + selected["X2W_NATIVE_SHADERS"] = sdk + else: + subprocess.run([compile_dxil, sdk, work / "frontend", "gfx1013-direct-cs@0", + "--requests", cache, cache], check=True) + manifest = cache / (marker.stem.removeprefix("req_") + ".txt") + assert "udsrc 2 stride 0\n" in manifest.read_text(), manifest.read_text() + for stride in (0, 1, 4, 16): + fields.write_bytes(struct.pack("<6I", stride, 64, 0, 4, WORDS, 0)) + got, result = dispatch(work, consumer, selected, "dispatch-records32") + if lines(result, "the adapter has no 32-lane waves"): + assert got == [SENTINEL] * WORDS + print("skip: runtime adapter has no wave32") + return 77 + expected = [int(stride != 0), int(stride > 1), int(1 > stride), KEY] * 12 + expected += [SENTINEL] * (WORDS - len(expected)) + assert got == expected, ( + next((i, a, b) for i, (a, b) in enumerate(zip(got, expected)) if a != b), result.stderr[-3000:] + ) + assert bool(lines(result, "translated natively: 3 entry values, 1 inputs, 1 outputs")) == ( + route == "native" + ), result.stderr[-3000:] + assert lines(result, "Dispatch(3, 2, 2) translated") and not lines(result, "refused: "), result.stderr + assert not [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + print(f"{route}: stride {stride}, 12 groups match {expected[:4]} and all guards") + return 0 + + +if __name__ == "__main__": + if sys.argv[1] == "runtime": + sys.exit(runtime_main(*sys.argv[2:])) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py new file mode 100644 index 0000000000..22b41cf886 --- /dev/null +++ b/tests/native_direct_container_check.py @@ -0,0 +1,1355 @@ +"""Source-built containers exercise direct DXIL assembly and rejection paths.""" +import pathlib +import hashlib +import re +import struct +import subprocess +import sys +import tempfile +import zlib + + +def words(*values): + return struct.pack(f"<{len(values)}I", *values) + + +def compute(code, threads=32, table=False, root_descriptor=False, wave32=True, uses=(), *, group=None): + body = bytearray(256) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into("<Q", body, 96, record) + if table or root_descriptor: + struct.pack_into("<Q",body, record+40, len(body)) + struct.pack_into("<I",body, record+56, 1) + body.extend(words(1,0,2,0,0) if root_descriptor else words(3,0,1,0,0)) + if uses: + struct.pack_into("<Q", body, record+48, len(body)) + struct.pack_into("<I", body, record+60, len(uses)) + for use in uses: + body.extend(words(*use)) + struct.pack_into("<QQ", body, record, len(body), len(code)) + struct.pack_into("<I", body, record+20, 32 if wave32 else 0) + struct.pack_into("<II", body, record+76, 512, 4) + user_flags = 4 if root_descriptor else (0x1002 if table else 0) + group = (threads, 1, 1) if group is None else group + struct.pack_into("<IIII", body, record+120, 0x8400 | user_flags, *group) + body.extend(code) + return pack(body) + + +def pack(body, extra=()): + raw = b"FSSM" + struct.pack("<IQ", 0x101, len(body)) + body + compressed = zlib.compress(raw) + blob = b"XBCH" + struct.pack("<IQQ", 3, len(compressed), len(raw)) + compressed + part = bytes(24) + b"XDAT" + words(1, 0, 13, 48, len(blob)) + blob + chunks = [(b"DXIL", part), *extra] + table = [] + data = b"" + for name, payload in chunks: + table.append(32+4*len(chunks)+len(data)) + data += name+words(len(payload))+payload + data += bytes(-len(data)%4) + return b"DXBC"+bytes(16)+words(1, 32+4*len(chunks)+len(data), len(chunks), *table)+data + +def signature_rows(rows): + records, names = bytearray(), bytearray() + for semantic, system, component, row, mask in rows: + name_at = 8 + 32*len(rows) + len(names) + records.extend(words(0,name_at,0,system,component,row,mask*257,0)) + names.extend(semantic+b"\0") + return words(len(rows),8)+records+names + + +def signature(semantic, system=0, component=3, row=0, mask=15): + return signature_rows([(semantic,system,component,row,mask)]) + + +def add_root_input(body, record, parameter, count, kind=0): + struct.pack_into("<Q", body, record+40, len(body)) + struct.pack_into("<I", body, record+56, 1) + body.extend(words(kind, 0, count, 0, parameter << 8)) + + +def vertex(fetch=False, constants=None, program=None, extra=(), varying=False, table=False, uses=()): + record=112 + body=bytearray(record+84+0x18c) + struct.pack_into("<Q",body,0,6) + for index in (8,16,24,32,48,72,96): + struct.pack_into("<Q",body,index,0xdeadbeefdeadbeef) + struct.pack_into("<Q",body,40,record) + # Convert incoming vertex ID before a full position export. + code=words(0x7e020b00,0xf80008cf,0x01010101,0xbf810000) + if fetch: + io = record + 84 + struct.pack_into("<I", body, io+0xc4, 1) + body[io+0x24:io+0x29] = bytes((6, 0, 15, 1, 3)) + code = words(0xbe842104, 0xf80008cf, 0x04030201, 0xbf810000) + if constants: + add_root_input(body, record, *constants) + code = words(0x7e000200, 0xf80008cf, 0, 0xbf810000) + if table: + add_root_input(body, record, 0, 1, kind=3) + if uses: + struct.pack_into("<Q", body, record+48, len(body)) + struct.pack_into("<I", body, record+60, len(uses)) + for use in uses: + body.extend(words(*use)) + if program is not None: + code = words(*program) + if varying: + io=record+84 + struct.pack_into("<I", body,io+0x188,1) + body[io+0xc8:io+0xce]=bytes((6,0,0,0,0,0)) + struct.pack_into("<QQ",body,record,len(body),len(code)) + body.extend(code) + return pack(body, (((b"ISG1", signature(b"POSITION")),) if fetch else ()) + extra) + +def patched_pixel(where=1, prefix=None, table=False, input_address=0, input_signature=(), constants=None, + export=(0xf800180f, 0), root_inputs=(), wave32=False, tail=(), attributes=(), uses=()): + record = 112 + io = record + 84 + body = bytearray(io + 0x14c + 8 * 404) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 72, 96): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + struct.pack_into("<Q", body, 48, record) + struct.pack_into("<I", body, record+20, 32 if wave32 else 0) + struct.pack_into("<I", body, io+0x134, input_address) + struct.pack_into("<I", body, io+0x124, len(attributes)) + for index, attribute in enumerate(attributes): + struct.pack_into("<8B", body, io+0x24+index*8, *attribute) + if table: + struct.pack_into("<Q", body, record+40, len(body)) + struct.pack_into("<I", body, record+56, 1) + body.extend(words(3,0,1,0,0)) + if prefix is None: + prefix = [0x7e0002f2] + if constants: + add_root_input(body, record, *constants) + if root_inputs: + struct.pack_into("<Q", body, record+40, len(body)) + struct.pack_into("<I", body, record+56, len(root_inputs)) + for record_words in root_inputs: + body.extend(words(*record_words)) + if uses: + struct.pack_into("<Q", body, record+48, len(body)) + struct.pack_into("<I", body, record+60, len(uses)) + for use in uses: + body.extend(words(*use)) + code = words(*prefix, 0xffffffff, 0xffffffff, 0xbf810000, *tail) + struct.pack_into("<QQ", body, record, len(body), len(code)) + struct.pack_into("<I", body, io+0x148, 2) + for mrt in range(8): + struct.pack_into("<I", body, io+0x14c+404*mrt, where if mrt == 0 else 0xffffffff) + struct.pack_into("<II", body, io+0x14c+364, *export) + body.extend(code) + return pack(body, input_signature) + +def interpolated_pixel(mismatched=False): + record=112 + io=record+84 + body=bytearray(io+0x14c+8*404) + struct.pack_into("<Q",body,0,6) + for offset in (8,16,24,32,40,72,96): + struct.pack_into("<Q",body,offset,0xdeadbeefdeadbeef) + struct.pack_into("<Q",body,48,record) + struct.pack_into("<I",body,io+0x124,1) + body[io+0x24:io+0x28]=bytes([6,0,15,0]) + struct.pack_into("<I",body,io+0x134,2) + for t in range(8): + struct.pack_into("<I",body,io+0x14c+404*t,0xffffffff) + p1=0xc8000000 | 4<<18 | 2<<8 + p2=p1 | (1<<16) | 1 + code=words(p1,p2^(0x100 if mismatched else 0),0xf800180f,0x04040404,0xbf810000) + struct.pack_into("<QQ",body,record,len(body),len(code)) + body.extend(code) + return pack(body,[(b"ISG1",signature(b"TEXCOORD"))]) + +def publish(directory, *stages, ps_inputs=None, slot57_inputs=None): + directory.mkdir(exist_ok=True) + key = 1469598103934665603 + tail = b"" if ps_inputs is None else b"psin1" + struct.pack("<II", *ps_inputs) + if slot57_inputs is not None: + assert ps_inputs is None + tail = b"PSI1" + struct.pack("<II", *slot57_inputs) + for byte in b"x2w-startup-shader-28" + b"".join(stages) + tail: + key = ((key ^ byte) * 1099511628211) & ((1 << 64) - 1) + hex_key = f"{key:016x}" + stem = f"req_{hex_key}" + for suffix, data in zip((".a", ".b", ".root", ".ia"), stages): + (directory / (stem + suffix)).write_bytes(data) + if ps_inputs is not None: + (directory / (stem + ".psin")).write_bytes( + f"psin1 {hex_key} ena=0x{ps_inputs[0]:04x} addr=0x{ps_inputs[1]:04x}\n".encode("ascii") + ) + if slot57_inputs is not None: + (directory / (stem + ".ps57in")).write_bytes(tail) + return hex_key + + +def comparison_program(op=47, dim=1, sampler=0x08001012): + # Clamp X/Y, point with TRUNC_COORD, LESS, nonzero maximum LOD. + setup = [0xbe810380, 0xf40c0200, 0xfa000000, 0xbe8403ff, sampler, + 0xbe8503ff, 0x00fff000, 0xbe8603ff, 0x04000000, 0xbe870380, + 0x7e0002f0, 0x7e0202f2, 0x7e0402f4, 0x7e060280] + return [*setup, 0xf0000100 | (dim << 3) | op << 18, 0x00220400] + + +# Scalar ops whose direct lowering writes SCC. The byte-window field refuses when +# the next instruction still looks like an SCC reader, so these have to sit in +# uses_scc_after's overwrite list next to s_max_u32. +SCC_WRITERS = ("s_absdiff_i32", "s_min_u32", "s_min_i32", "s_max_i32") + + +def scc_overwrite_names(source): + start = source.index("const bool overwrites = ") + end = source.index("const bool preserves_pair", start) + return set(re.findall(r'n == "([^"]+)"', source[start:end])) + + +def symbolic_field_scc_live(program, writers): + """Same backward walk as uses_scc_after, for a straight-line program. + + Returns whether SCC is live at the instruction after program[0]. + """ + preserves = {"s_mov_b32", "s_mov_b64", "s_ff1_i32_b64", "s_brev_b32"} + readers = {"s_cselect_b32"} + live = [False] * len(program) + previous = [[] for _ in program] + pending = [] + for index, name in enumerate(program): + scalar = name.startswith("s_") and name != "s_endpgm" + reads = name in readers + uncertain = scalar and not reads and name not in writers and name not in preserves + if reads or uncertain: + live[index] = True + pending.append(index) + continue + if name in writers or name == "s_endpgm": + continue + previous[index + 1].append(index) + while pending: + index = pending.pop() + for pred in previous[index]: + if live[pred]: + continue + live[pred] = True + pending.append(pred) + return live[1] + + +def check_scc_writer_mutant(): + source = pathlib.Path(__file__).resolve().parents[1].joinpath( + "src", "gfx1013_direct_compute.inl").read_text(encoding="utf-8") + start = source.index("const bool overwrites = ") + end = source.index("const bool preserves_pair", start) + block = source[start:end] + writers = scc_overwrite_names(source) + assert "s_and_b32" in writers and "s_max_u32" in writers + for name in SCC_WRITERS: + assert block.count(f'n == "{name}"') == 1, name + killed = ["s_and_b32", "s_mov_b32", "s_mov_b32", "s_absdiff_i32", "s_cselect_b32", + "v_mov_b32", "s_endpgm"] + select = ["s_and_b32", "s_mov_b32", "s_mov_b32", "s_ff1_i32_b64", "s_cselect_b32", "s_endpgm"] + assert symbolic_field_scc_live(select, writers) + assert not symbolic_field_scc_live(killed, writers) + mutant = block + for name in SCC_WRITERS: + mutant = mutant.replace(f'n == "{name}"', 'n == "s_endpgm"', 1) + dropped = set(re.findall(r'n == "([^"]+)"', mutant)) - {"s_endpgm"} + for name in SCC_WRITERS: + program = ["s_and_b32", "s_mov_b32", "s_mov_b32", name, "v_mov_b32", "s_endpgm"] + assert not symbolic_field_scc_live(program, writers), name + assert symbolic_field_scc_live(program, dropped), name + assert symbolic_field_scc_live(killed, dropped) + print("scc writer mutant: each new case is live once its overwrite entry is removed") + + +def main(): + check_scc_writer_mutant() + if len(sys.argv) == 4 and sys.argv[1] in ("--sampler-pso", "--graphics-sampler-pso"): + sdk, probe = sys.argv[2:] + with tempfile.TemporaryDirectory() as tmp: + folder = pathlib.Path(tmp) + # Keep both comparison and regular uses of identical sampler words. + code = [*comparison_program(), 0xf09c0108, 0x00220500, 0x06000b04] + if sys.argv[1] == "--graphics-sampler-pso": + vs, ps, root = (folder/name for name in ("vertex", "pixel", "root.bin")) + vs_code = [0xbe810380, 0xf40c0200, 0xfa000040, 0x7e020280, 0x7e040280, + 0xf0200108, 0x80020201, 0x7e020b00, 0xf80008cf, 0x01010101, 0xbf810000] + vs.write_bytes(vertex(program=vs_code, table=True)) + # Reload the next descriptor in the same table as a writable image. + code += [0xf40c0200, 0xfa000020, 0xf0200108, 0x80020400] + ps.write_bytes(patched_pixel(len(code), code, True)) + source = folder/"root.hlsl" + source.write_text('#define RS "DescriptorTable(SRV(t0), UAV(u0, numDescriptors=2))"\n') + subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "RS", source, "-Fo", root], check=True) + raise SystemExit(subprocess.run([probe, "--graphics-sampler", sdk, vs, ps, root, folder/"cache"]).returncode) + marker = folder / "sample.cdx" + marker.write_bytes(compute(words(*code, 0xbf810000), table=True)) + raise SystemExit(subprocess.run([probe, "--sampler", sdk, marker, folder/"cache"]).returncode) + if len(sys.argv) in (5, 6) and sys.argv[1]=="--rect-pso": + exe,sdk,probe=sys.argv[2:5] + rect_geometry=sys.argv[5] if len(sys.argv)==6 else None + with tempfile.TemporaryDirectory() as tmp: + folder=pathlib.Path(tmp) + source=folder/"inputs" + out=folder/"compiled" + vs=vertex(program=[0x7e020b00,0xf80000cf,0x01010101,0xf8000a0f,0x01010101,0xbf810000], + varying=True, extra=((b"OSG1",signature_rows([(b"TEXCOORD",0,3,0,15), + (b"SV_Position",1,3,1,15)])),)) + root=b"DXBC"+bytes(16)+words(1,68,1,36)+b"RTS0"+words(24,2,0,24,0,24,0) + stem=publish(source,vs,interpolated_pixel(),root) + subprocess.run([exe,sdk,folder/"cache","gfx1013-container-rect","--requests",source,out],check=True) + result=subprocess.run([probe,*(out/f"{stem}.{stage}.cso" for stage in ("vs","gs","ps"))]) + if result.returncode or not rect_geometry: + raise SystemExit(result.returncode) + # A second pair exports only SV_Position, matching the standalone geometry fixture's HLSL + # VS/PS. Draw the same rotated scenes through that native GS instead of the HLSL stage. + native_source=folder/"native-inputs" + native_out=folder/"native-compiled" + from startup_stream_draw_check import vop1 + native_ps=patched_pixel(2,[vop1(1,0,128),vop1(1,1,242)],export=(0xf800180f,0x01000001)) + native_stem=publish(native_source,vertex(fetch=True),native_ps,root, + b"ia1 1\nPOSITION 0 6 0 4 0 0\n") + subprocess.run([exe,sdk,folder/"cache","gfx1013-container-rect","--requests",native_source,native_out],check=True) + native_stages=[str(native_out/f"{native_stem}.{stage}.cso") for stage in ("vs","ps","gs")] + raise SystemExit(subprocess.run([rect_geometry,"--native-vs",native_stages[0], + "--native-ps",native_stages[1],"--native-gs",native_stages[2]]).returncode) + exe, sdk = sys.argv[1:] + with tempfile.TemporaryDirectory() as tmp: + folder = pathlib.Path(tmp) + def check(name, profile, data, expected=""): + source = folder / name + source.write_bytes(data) + binary = source.with_suffix(".cso") + result = subprocess.run([exe, sdk, folder/"cache", profile, source, binary], + capture_output=True, text=True) + if expected: + assert result.returncode and expected in result.stderr and not binary.exists(), result.stderr + else: + assert result.returncode == 0, result.stderr + assert binary.read_bytes().startswith(b"DXBC") + return result.stdout + cs = "gfx1013-container-cs" + end = 0xbf810000 + # Direct reads of the I/J VGPRs export the y/z weights. Include a + # preceding (unused) pull-model triple to distinguish VGPR allocation + # from the two DXIL system-value elements used by the shader. + for label, mask, first, second in ( + ("center", 2, 0, 0), ("centroid", 4, 0, 0), ("sample", 1, 0, 0), + ("linear-center", 32, 0, 0), ("linear-centroid", 64, 0, 0), + ("linear-sample", 16, 0, 0), ("two-pairs", 2 | 8 | 32, 0, 5)): + reads = [0x7e080300 | first, 0x7e0a0300 | (second + 1)] + shader = patched_pixel(len(reads), reads, input_address=mask, export=(0xf800180f, 0x05040504)) + name = "bary-" + label + for timing in ("cold_compile_and_publish_ms=", "cache_hit_ms="): + assert timing in check(name, "gfx1013-container-ps", shader) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(name+".cso")], + check=True, capture_output=True, text=True).stdout + loads = re.findall(r"call float @dx\.op\.loadInput\.f32\(i32 4, i32 (\d+), i32 0, i8 (\d+)", dump) + assert loads == [("0", "1"), ("1" if first != second else "0", "2")], (name, loads) + binary = (folder/(name+".cso")).read_bytes() + offsets = struct.unpack_from(f"<{struct.unpack_from('<I', binary, 28)[0]}I", binary, 32) + psv = next(off for off in offsets if binary[off:off+4] == b"PSV0") + assert binary[psv+13] == bool(mask & 0x11), name # PSVRuntimeInfo0.PS.SampleFrequency + for mask in (2 | 4, 32 | 64): + reads = [0x7e080300, 0x7e0a0303] + check("bary-conflict", "gfx1013-container-ps", + patched_pixel(2, reads, input_address=mask, export=(0xf800180f, 0x05040504)), + "two barycentric locations in the same perspective mode") + check("bary-pull", "gfx1013-container-ps", patched_pixel(1, [0x7e000300], input_address=8), + "unsupported pixel entry VGPR") + # Exact EXEC in odd s13 survives an unrelated write to s12 in wave32. + wqm = [0xbe8d037e, 0xbefe097e, 0xbe8c0380, 0x7e0002f2, 0xbefe030d] + check("wave32-save-exact", "gfx1013-container-ps", patched_pixel(len(wqm), wqm, wave32=True)) + check("wave64-low-only-wqm", "gfx1013-container-ps", + patched_pixel(2, [0xbefe097e, 0x7e0002f2]), "only half of the guest EXEC") + # Both successors are valid, including the block beyond the first return. + branch = compute(words(0xbf880001, end, end)) + assert "frontend_cache_hit=0" in check("branches", cs, branch) + assert "frontend_cache_hit=1" in check("branches", cs, branch) + [cached] = (folder/"cache").glob("*.csir") + data = bytearray(cached.read_bytes()) + data[-1] ^= 1 + cached.write_bytes(data) + assert "frontend_cache_hit=0" in check("branches", cs, branch) + # The read target aliases its byte-address source. Include a group barrier. + ds = words(0xd8340000, 0, 0xbf8a0000, 0xd8d80000, 0, end) + for n in (32, 64, 96): + check(f"lds{n}", cs, compute(ds, n)) + # A split wave ballots both halves and restores EXEC from an SGPR pair. + mask_program = words(0x7c0400f2, 0xbe84246a, 0x7e0c0500, 0xd7650002, 128 << 9 | 193, + 0xd7660003, 258 << 9 | 193, 0xbefe0404, end) + check("split-wave64", cs, compute(mask_program, 64, wave32=False)) + check("two-wave64", cs, compute(mask_program, 128, wave32=False)) + check("multi-wave64-local-branch", cs, compute(words(0xbf880001, end, end), 128, wave32=False)) + check("multi-wave64-exchange-branch", cs, compute(words(0xbf880001, 0x7c0400f2, end), 128, wave32=False), + "converged group control flow") + check("partial-wave64", cs, compute(mask_program, 32, wave32=False), "complete guest waves") + # Wide-carry destination and source are aligned SGPR pairs in a + # guest wave64. Both host halves must participate in the ballot. + carry = [0xbe9e04c1, 0xd5281e00, 128 | 256 << 9 | 30 << 18] + check("wave64-vector-carry", cs, compute(words(*carry, end), 64, wave32=False)) + check("wave64-odd-carry", cs, + compute(words(carry[0], carry[1] | 0x100, carry[2], end), 64, wave32=False), + "unsupported carry mask destination") + check("wave64-divergent-carry", cs, + compute(words(carry[0], 0xbf880002, *carry[1:], end), 128, wave32=False), + "multi-wave64 exchange requires converged group control flow") + split_ir = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"split-wave64.cso"], + check=True, capture_output=True, text=True).stdout + assert "waveExchange" in split_ir and "waveReadLaneAt" in split_ir and "waveActiveBallot" in split_ir, split_ir + # A descriptor's stride is symbolic. Its SCC may be discarded + # only if no path can consume it before a concrete definition. + stride_field = [0xbe810380, 0xf4080500, 0xfa000000, 0x9391ff15, 0xe0010] + shift = 0x901a8381 # s_lshr_b32 s26, 1, 3 + read_scc = 0xbe9903fd # s_mov_b32 s25, src_scc + check("stride-scc-jump", cs, compute(words(*stride_field, 0xbf820001, read_scc, shift, end), table=True)) + check("stride-scc-join", cs, compute(words(*stride_field, 0xbf880001, shift, read_scc, end), table=True), + "numeric SCC from a symbolic descriptor field") + address_field = [0xbe810380, 0xf4080500, 0xfa000000, 0x8715ff15, 0xc000ffff] + saveexec = 0xbe983c81 # s_and_saveexec_b32 s24, 1 + check("descriptor-saveexec-kill", cs, compute(words(*address_field, saveexec, read_scc, end), table=True)) + check("descriptor-saveexec-bypass", cs, + compute(words(*address_field, 0xbf880001, saveexec, read_scc, end), table=True), + "numeric SCC from a symbolic descriptor field") + pair_zero = [0xbe960380, 0xbe970380] # s_mov_b32 s22, 0 / s23, 0 (both preserve SCC) + ff1_pair = 0xbe8e1416 # s_ff1_i32_b64 s14, s[22:23] + brev = 0xbe8f0b0e # s_brev_b32 s15, s14 + use_scan = 0x7e00020f # v_mov_b32 v0, s15 + select_scc = 0x85198e80 # s_cselect_b32 s25, 0, s14 + check("descriptor-sop1-preserves-scc", cs, + compute(words(*address_field, *pair_zero, ff1_pair, brev, use_scan, end), table=True)) + check("descriptor-sop1-before-scc-read", cs, + compute(words(*address_field, *pair_zero, ff1_pair, select_scc, end), table=True), + "numeric SCC from a symbolic descriptor field") + # s_min_i32 / s_min_u32 / s_max_i32 / s_absdiff_i32 write SCC, same as s_max_u32. + # After the address-field rewrite they kill that symbolic SCC. s_cselect with + # no such writer in between stays refused above. The source mutant in + # check_scc_writer_mutant drops each overwrite entry and the same shape is live. + use_diff = 0x7e00021a # v_mov_b32 v0, s26 + for name, word in ( + ("s_min_i32", 0x831a1716), # s_min_i32 s26, s22, s23 + ("s_min_u32", 0x839a1716), + ("s_max_i32", 0x841a1716), + ("s_absdiff_i32", 0x961a1716)): + check("descriptor-" + name + "-kills-scc", cs, + compute(words(*address_field, *pair_zero, word, use_diff, end), table=True)) + check("descriptor-absdiff-then-cselect", cs, + compute(words(*address_field, *pair_zero, 0x961a1716, 0x85191716, use_diff, end), + table=True)) + or_saveexec = 0xbe983dc1 # s_or_saveexec_b32 s24, -1 + check("descriptor-or-saveexec-kill", cs, compute(words(*address_field, or_saveexec, read_scc, end), table=True)) + check("or-saveexec-exec-destination", cs, compute(words(0xbefe3dc1, end)), + "unsupported wave32 SAVEEXEC destination") + # The previous symbolic SCC is dead at WQM. Reading it before WQM + # must still refuse. The nonzero high word supplies the new SCC. + numeric_wqm = [0xbe9a0380, 0xbe9b0381, 0xbe980a1a] # s[24:25] = WQM(s[26:27]) + for early in (False, True): + seq = [*stride_field, *([read_scc] if early else []), *numeric_wqm, + 0xbf840001, 0xbf800000, 0x7e000218] + check("pixel-stride-scc-"+("read" if early else "overwritten"), "gfx1013-container-ps", + patched_pixel(len(seq),seq,table=True), + *(["numeric SCC from a symbolic descriptor field"] if early else [])) + check("sdwa-class-float-byte", cs, compute(words(0x7d100af9, 0x03908e80, end)), + "unsupported floating class operand selection") + # A real FSSM root table feeds eight descriptor words. The image + # dimension changes both the emitted handle and the operand count. + for dim in (0,1,2,4,5,6,7): + image = 0xf0000100 | dim << 3 + stream = words(0xbe810380, 0xf40c0200, 0xfa000000, + image, 0x00020400, end) + check(f"image{dim}", cs, compute(stream, table=True)) + check("bad-target", cs, compute(words(0xbf820010, end)), "branch outside") + # Exercise every 32-bit raw UAV atomic, including GLC's old-value + # writeback to the VGPR also used as the address. + atomics = [] + for op in (0x30, 0x31, 0x32, 0x33, *range(0x35, 0x3c)): + atomics.extend((0xe0005000 | op << 18, 0x80020000)) + def atomic_program(instructions): + return compute(words(0xbe810380, 0xf4080200, 0xfa000000, + *instructions, end), table=True) + check("raw-atomics", cs, atomic_program(atomics)) + # gfx1013 VOP3 forms for signed BFE, min3/median, high products + # and mixed three-source logic. V0 is both source and destination. + vec = [] + for op in (329, 339, 344, 362, 364, 837, 877, 882): + vec.extend((0xd4000000 | op << 16, 256 | 129 << 9 | 130 << 18)) + check("integer-vector", cs, compute(words(*vec, end))) + # SDWA byte/word extraction, signed extension, preservation of the + # untouched destination, plus scalar or vector source selection. + sdwa = [0x3a0000f9, 0x06091100, 0x060000f9, 0x06162600] + for opcode in (17, 18, 19, 20, 32, 33, 34): + sdwa.extend((0x7e0000f9 | opcode << 9, 0x00060600)) + check("subword-alu", cs, compute(words(*sdwa, end))) + # Read a V# from the table, clear stride, set byte-address bounds and + # preserve its extent as num_records * max(1,stride). The subsequent + # vector access still selects this table and byte window. + byte_view = [0xbe810380, 0xf4080700, 0xfa000000, 0x939bff1d, 0xe0010, 0x849b811b, + 0x871dff1d, 0xc000ffff, 0x871fff1f, 0xcfffffff, 0x931e1b1e, 0x881fff1f, 0x30000000, + 0x7e0a0280, 0xe0381000, 0x80070805] + check("byte-count-rewrite", "gfx1013-container-ps", + patched_pixel(len(byte_view), byte_view, table=True, export=(0xf800180f, 0x0b0a0908))) + broken = byte_view.copy() + broken[10] = 0xbf800000 # Leave NUM_RECORDS in elements instead of bytes. + check("byte-count-missing-product", "gfx1013-container-ps", + patched_pixel(len(broken), broken, table=True), "non-contiguous resource descriptor") + # Convert v11 to a half in the high word of v6, retaining v6.low. + # Widen the selected high word back from a scalar source into v7. + halves = [0x7e0c02ff, 0xa5a53600, 0x7e1602ff, 0x3f801000, 0x7e0c14f9, 0x06150b, + 0xbe8e03ff, 0x40003c00, 0x7e0e16f9, 0x85060e] + check("sdwa-half-pair", "gfx1013-container-ps", + patched_pixel(len(halves), halves, export=(0xf800180f, 0x07060706))) + half_ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"sdwa-half-pair.cso"], + text=True) + assert "@dx.op.legacyF16ToF32" in half_ir and "65535" in half_ir, half_ir + invalid = halves.copy() + invalid[-1] |= 1 << 19 + check("sdwa-half-signextend", "gfx1013-container-ps", patched_pixel(len(invalid), invalid), + "invalid SDWA source modifier") + check("invalid-subword", cs, compute(words(0x3a0000f9, 0x06071700, end)), + "unsupported SDWA destination modifier") + for bad in (0x2000, 0x4000, 0x100): + check("half-mad-mod-" + str(bad), cs, + compute(words(0xd7730000 | bad, 257 | 258 << 9 | 259 << 18, end)), + "unsupported halfword MAD operand modifiers") + # Compare different subwords into VCC, then select and preserve + # the other bytes of the destination. CMPX must write EXEC. + cmp_sdwa = (0x7c000000 | (2 << 17) | 249, 0x06010000) + choose_byte = (1 << 25 | 249, 0x06021100) + check("compare-select-subword", cs, compute(words(*cmp_sdwa, *choose_byte, end))) + check("cmpx-explicit-destination", cs, compute(words(cmp_sdwa[0] | (0x10 << 17), + cmp_sdwa[1] | 0x8000, end)), "invalid SDWA compare destination") + for name, opcode, ext, error in ( + ("class", 0x7d100af9, 0x0396eb80, "invalid SDWA class modifiers or mask destination"), + ("ne", 0x7d0a0cf9, 0x0086eb6b, "invalid SDWA compare destination"), + ): + check(f"sdwa-{name}-vcc-hi-wave64", cs, compute(words(opcode, ext, end), 64, wave32=False), error) + check(f"sdwa-{name}-sdst-108", cs, compute(words(opcode, (ext & ~0x7f00) | (108 << 8), end)), error) + check("sdwa-cmpx-vcc-hi", cs, compute(words(0x7d2a0cf9, 0x0086eb6b, end)), + "invalid SDWA compare destination") + check("atomic-x2", cs, atomic_program((0xe1445000, 0x80020000)), + "unsupported buffer atomic width") + check("bad-container", cs, compute(ds)[:-1], "invalid DXBC length") + check("vertex", "gfx1013-container-vs", vertex()) + fetch_body = [0xbe842104, 0xf80008cf, 0x04030201, end] + check("prefixed-fetch", "gfx1013-container-vs", + vertex(fetch=True, program=[0x7e000080, *fetch_body])) + check("late-fetch", "gfx1013-container-vs", + vertex(fetch=True, program=[0x7e000080, 0x7e0002f2, *fetch_body]), "outside the entry") + # Copy a root address into s[2:3], read 8 dwords at byte 48, + # then use the last word in an observable vertex position export. + # Overwriting only the high SGPR must invalidate the pointer. + root_load = [0xbe820400, 0xf40c0201, 0xfa000030] + root_vs = vertex(constants=(0,2,1), program=[*root_load, 0x7e00020f, 0xf80008cf, 0, end]) + check("address-vs", "gfx1013-container-vs", root_vs) + check("address-cs", cs, compute(words(*root_load, end), root_descriptor=True)) + check("wave64-smem-symbolic-vcc-dst", cs, + compute(words(0xbe810380, 0xf4080000 | 104 << 6, 125 << 25, end), + threads=64, table=True, wave32=False), + "symbolic scalar memory destination overlaps wave64 VCC") + check("wave32-smem-cross-vcc", cs, + compute(words(0xf40c0000 | 104 << 6, 125 << 25, end), root_descriptor=True), + "unsupported scalar memory destination range") + # A descriptor into s[104:107] must tag both VCC words as nonnumeric. + for offset in (106, 107): + check(f"wave32-smem-symbolic-offset-{offset}", cs, + compute(words(0xbe810380, 0xf4080000 | 104 << 6, 125 << 25, + 0xf4080200, offset << 25, end), table=True), + f"unbound numeric SGPR s{offset}") + wrong_high = [root_load[0], 0xbe830380, *root_load[1:], end] + check("bad-address-cs", cs, compute(words(*wrong_high), root_descriptor=True), "mismatched root address high half") + # Build a zero-stride byte-address descriptor in s[4:7]. The x8 + # load starts at 96 and ends exactly at the 128-byte view bound. + def built_load(bound=128, control=0x31016fac, high=0xbe850301): + return [0xbe840300, high, 0xbe8603ff, bound, 0xbe8703ff, control, 0xf42c0202, 0xfa000060] + check("built-root-cs", cs, compute(words(*built_load(), end), root_descriptor=True)) + # Build the same byte range from a root address with stride one. + unit_stride = [0xbe840300, 0x8805ff01, 0x10000, *built_load(control=0x11014fac)[2:]] + check("built-root-unit-stride", cs, compute(words(*unit_stride, end), root_descriptor=True)) + wrong_control = unit_stride.copy() + wrong_control[-3] = 0x31016fac + check("built-root-unit-stride-control", cs, compute(words(*wrong_control, end), root_descriptor=True), + "unsupported synthesized scalar buffer descriptor fields") + check("built-root-range", cs, compute(words(*built_load(bound=127), end), root_descriptor=True), + "exceeds synthesized descriptor byte bound") + check("built-root-fields", cs, compute(words(*built_load(control=0x01016fac), end), root_descriptor=True), + "unsupported synthesized scalar buffer descriptor fields") + check("built-root-pair", cs, compute(words(*built_load(high=0xbe850380), end), root_descriptor=True), + "mismatched root address high half") + check("built-root-vs", "gfx1013-container-vs", vertex(constants=(0,2,1), + program=[*built_load(), 0x7e00020f, 0xf80008cf, 0, end])) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"built-root-vs.cso"], + check=True, capture_output=True, text=True).stdout + assert "@dx.op.rawBufferLoad.i32(i32 139" in dump and ", i32 112," in dump, dump + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"address-vs.cso"], + check=True, capture_output=True, text=True).stdout + assert "@dx.op.rawBufferLoad.i32(i32 139" in dump and ", i32 64," in dump, dump + check("smooth", "gfx1013-container-ps", interpolated_pixel()) + check("mismatch", "gfx1013-container-ps", interpolated_pixel(True), "unmatched interpolation pair") + check("patched", "gfx1013-container-ps", patched_pixel()) + check("null-export", "gfx1013-container-ps", patched_pixel(export=(0xf8001890,0))) + clip_sig=signature_rows([(b"SV_Position",1,3,0,15),(b"SV_ClipDistance",2,3,1,3), + (b"SV_CullDistance",3,3,1,4)]) + clip=[0x7e0002f2,0xf80000cf,0,0xf80008d7,0,end] + check("clip-cull","gfx1013-container-vs",vertex(program=clip,extra=((b"OSG1",clip_sig),))) + check("clip-unmapped","gfx1013-container-vs",vertex(program=clip),"unmapped position export") + diamond = [0xbf008180, 0xbf850002, 0x7e0002f2, 0xbf820001, 0x7e0002f4] + check("pixel-branch", "gfx1013-container-ps", patched_pixel(len(diamond), diamond)) + # Carry the position input through an SCC-controlled two-iteration loop. + loop = [0xb0000002, 0x7e020300, 0x06020300, 0xb780ffff, 0xbf078000, + 0xbf85fffc, 0x7e000301] + position_input = ((b"ISG1", signature(b"SV_Position", 1)),) + check("pixel-loop", "gfx1013-container-ps", + patched_pixel(len(loop), loop, input_address=1 << 8, input_signature=position_input)) + uninitialized = loop.copy() + uninitialized[1] = 0xbf800000 + check("pixel-loop-undefined", "gfx1013-container-ps", + patched_pixel(len(loop), uninitialized, input_address=1 << 8, input_signature=position_input), + "unsupported pixel entry VGPR") + missing = diamond.copy() + missing[-1] = 0xbf800000 + check("undefined-at-join", "gfx1013-container-ps", patched_pixel(len(missing), missing), + "undefined on an incoming path") + check("position-preserved-at-join", "gfx1013-container-ps", + patched_pixel(len(missing), missing, input_address=1 << 8, input_signature=position_input)) + lanes = [0x7e0002f2, 0x7c0400f2, 0x02000080] + check("lane-select", "gfx1013-container-ps", patched_pixel(len(lanes), lanes)) + # Guest SRC0 is an sNaN bit pattern and V0 is the integer class mask. + # Do not convert SRC0 to host float before distinguishing sNaN/qNaN. + for name, word, snan, quiet_bit in (("f16", 0x7d1e00ff, 0x7c01, 512), + ("f32", 0x7d1000ff, 0x7f800001, 4194304)): + ops = [0x7e000281, word, snan, 0x02000080] + check("class-"+name, "gfx1013-container-ps", patched_pixel(len(ops), ops)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/f"class-{name}.cso"], text=True) + fraction = re.search(rf"(%\w+) = and i32 {snan}, {2*quiet_bit-1}\b", ir) + assert fraction and f"and i32 {fraction[1]}, {quiet_bit}" in ir and "@dx.op.legacyF16ToF32" not in ir + vcc_diamond = [*lanes[:2], 0xbf870002, *diamond[2:]] + check("uniform-vcc-join", "gfx1013-container-ps", patched_pixel(len(vcc_diamond), vcc_diamond)) + varying_vcc = vcc_diamond[1:] + check("varying-vcc-join", "gfx1013-container-ps", patched_pixel(len(varying_vcc), varying_vcc, + input_address=1 << 8, input_signature=position_input), "condition depends on a varying input") + masked = [0x7c0400f2, 0xbe84246a, 0xbf880001, 0x7e0002f4, 0xbefe0404] + check("masked-pixel", "gfx1013-container-ps", patched_pixel(len(masked), masked, + input_address=1 << 8, input_signature=position_input)) + two_arms = [0x7c0400f2, 0xbe84047e, 0x87fe7e6a, 0xbf880001, 0x7e0002f4, + 0x8afe7e04, 0xbf880001, 0x7e0002f2, 0xbefe0404] + # VertexID chooses a mask. A uniform branch inside THEN skips the + # write to v4; ELSE covers its complement. Both paths reach POS0. + vertex_arms = [0x7e0802f2, 0x7d040080, 0xbe88246a, 0xbf880006, + 0xbf008080, 0xbf840002, 0x7e0802f4, 0xbf800000, + 0x7e0a0304, 0x7e080305, 0x8afe7e08, 0xbf880002, + 0x7e080281, 0xbf800000, 0xbefe0408, 0xf80008cf, 0x04040404, end] + check("vertex-mask-branch", "gfx1013-container-vs", vertex(program=vertex_arms)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"vertex-mask-branch.cso"], text=True) + assert ir.count("br i1") == 3 and "phi i32" in ir, ir + # v4 has only constant data operands, but VertexID selected the arm. + # The resulting VCC cannot drive a wave-uniform scalar branch. + varying_join = vertex_arms[:15] + [0x7d040880, 0xbf870001, 0xbf800000] + vertex_arms[15:] + check("vertex-mask-phi-dependency", "gfx1013-container-vs", vertex(program=varying_join), + "condition depends on a varying input") + # The outer THEN contains an independently saved inner mask. Its ELSE + # must only change v4 for lanes which entered that outer THEN. + nested = [0x7e0802f2, 0x7d040080, 0xbe88246a, 0xbf880009, + 0x7d040081, 0xbe8a246a, 0xbf880002, 0x7e0802f4, 0xbf800000, + 0x8afe7e0a, 0xbf880001, 0x7e080281, 0xbefe040a, 0xbefe0408, + 0xf80008cf, 0x04040404, end] + check("vertex-nested-mask", "gfx1013-container-vs", vertex(program=nested)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"vertex-nested-mask.cso"], text=True) + assert "br i1" in ir and "select i1" in ir and "phi i32" in ir, ir + # Capture VCC & EXEC at the CMPX join. The next compare intersects + # that captured bit before narrowing EXEC for the second region. + captured_vs = [0x7e0802f2, 0xbe98047e, 0x7d2a0080, 0xbf880002, + 0x7e0802f4, 0x7d0a0081, 0x87887e6a, 0x8afe7e18, + 0xbf880001, 0x7e080281, 0xbefe0418, 0x7d0a0082, + 0x8788086a, 0x87fe7e08, 0xbf880002, 0x7e080284, + 0xbf800000, 0x8afe7e18, 0xbf880001, 0x7e080285, + 0xbefe0418, 0xf80008cf, 0x04040404, end] + check("vertex-cmpx-intersection", "gfx1013-container-vs", vertex(program=captured_vs)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"vertex-cmpx-intersection.cso"], text=True) + assert "phi i32 [ 0," in ir or ", [ 0," in ir, ir + assert "and i32" in ir and ir.count("br i1") == 4 and "@dx.op.wave" not in ir, ir + numeric_mask = captured_vs.copy() + numeric_mask[9] = 0x7e080208 # No numeric s8 exists on the empty edge. + check("vertex-cmpx-numeric-wave-mask", "gfx1013-container-vs", vertex(program=numeric_mask), + "undefined on an incoming path") + changed_exec = captured_vs.copy() + changed_exec[4] = 0x7d2a0083 + check("vertex-cmpx-changed-exec", "gfx1013-container-vs", vertex(program=changed_exec), + "reaching CMPX mask on every path") + mask_scc = [0x7e0802f2, 0x7d0a0081, 0xd485001a, 0x00020080, + 0x879a1a6a, 0xbe9a241a, 0xbf880007, + 0xd40d002a, 0x000100f2, 0x87aa7e2a, 0xbf840001, + 0x7e080284, 0xbf800000, 0xbf800000, 0xbefe041a, + 0xf80008cf, 0x04040404, end] + check("vertex-active-uniform-scc", "gfx1013-container-vs", vertex(program=mask_scc)) + varying_scc = mask_scc.copy() + varying_scc[8] = 0x00020081 # Other lanes can disagree on this SCC. + check("vertex-active-varying-scc", "gfx1013-container-vs", vertex(program=varying_scc), + "native compute +0x24: unbound numeric SGPR s42") + # Both arms load t0's first dword after their lane-local v4 writes. + # Its result is read after restoring EXEC, including for an empty ELSE. + scalar_tail = [0xbe98047e, 0x7d0a0080, 0x87fe7e6a, 0xbf880002, + 0xbe9a0381, 0x7e0802f4, 0x8afe7e18, 0x7e0802f2, + 0xf4000200, 0xfa000000, 0xbefe0418, 0x06080808, + 0xf80008cf, 0x04040404, end] + check("vertex-shared-scalar-tail", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=scalar_tail)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"vertex-shared-scalar-tail.cso"], text=True) + assert "phi i32" in ir and ir.count("call %dx.types.ResRet.i32 @dx.op.rawBufferLoad") == 1, ir + unsafe_tail = scalar_tail.copy() + unsafe_tail[7] = 0x7e08021a + check("vertex-scalar-tail-escaping-sgpr", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=unsafe_tail), "unbound numeric SGPR s26") + # SGPR -> f32 -> reciprocal -> scaled integer is uniform at every + # step. Replacing the first conversion's input with VertexID is not. + uniform_vs = [0xf4000200, 0xfa000000, 0x7e020c08, 0x7e025501, + 0x100202ff, 0x41800000, 0x7e020f01, 0x7e120501, + 0x7e080c09, 0xf80008cf, 0x04040404, end] + check("vertex-uniform-readfirst-chain", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=uniform_vs)) + varying_vs = uniform_vs.copy() + varying_vs[2] = 0x7e020d00 + check("vertex-varying-readfirst-chain", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=varying_vs), "requires a wave-uniform reaching value") + # The first ALU overwrites its input VGPR and outputs a separate + # s[20:21] mask. CNDMASK still sees the original VCC. The next ALU + # consumes s[20:21], writes VCC and exposes that carry via v6. + vertex_carry = [0x7d0a0080, 0x7e020300, 0xd5281401, 195 | (257<<9) | (106<<18), + 0x7e0a02f4, 0x02000000 | (2<<17) | (5<<9) | 242, + 0xd5286a03, 128 | (193<<9) | (20<<18), 0x02000000 | (6<<17) | (5<<9) | 242, + 0x7e020b01, 0x7e060b03, 0xf80008cf, 0x06030201, end] + for op in range(3): + chain = vertex_carry.copy() + chain[2] += op<<16 + check("vertex-carry-chain-"+str(op), "gfx1013-container-vs", vertex(program=chain)) + replaced = vertex_carry[:6] + [0xbe950380] + vertex_carry[6:] + check("vertex-carry-high-overwrite", "gfx1013-container-vs", vertex(program=replaced), + "unproven vertex carry-in mask") + numeric = vertex_carry.copy() + numeric[5] = 0x7e040214 + check("vertex-carry-numeric-sgpr", "gfx1013-container-vs", vertex(program=numeric), + "unbound numeric SGPR s20") + # Match the decoder's DWORD input (+0.0), BYTE_3 class mask and + # s[40:41] destination. A second compare defines s[26:27]; both can + # still select a result while VCC retains the original vertex test. + class_select = [0x7d0a0080, 0x3446009e, 0x7d1046f9, 0x0386a880, + 0x7e0a02f4, 0xd5010004, 242 | (261<<9) | (40<<18), + 0x020c0af2, 0xd485001a, 130 | (256<<9), + 0xd5010007, 242 | (261<<9) | (26<<18), + 0xd5010008, 261 | (242<<9) | (40<<18), + 0xf80008cf, 0x08070604, end] + check("vertex-class-mask-select", "gfx1013-container-vs", vertex(program=class_select)) + pixel_class = [0x7e000281, *class_select[:-3]] + check("pixel-class-mask-select", "gfx1013-container-ps", patched_pixel(len(pixel_class),pixel_class, + export=(0xf800180f,0x08070604))) + changed_high = class_select[:5] + [0xbea90380] + class_select[5:] + check("vertex-class-mask-high-overwrite", "gfx1013-container-vs", vertex(program=changed_high), + "unproven graphics CNDMASK source") + bad_class = class_select.copy() + bad_class[3] |= 1<<16 + check("vertex-class-reserved-selection", "gfx1013-container-vs", vertex(program=bad_class), + "invalid or unsupported integer SDWA modifiers") + # s8 is a uniform root-buffer read. Bit 0 chooses identical high + # and low scalar words and the corresponding CNDMASK bit. + scalar_select = [0xf4000200,0xfa000000,0xbf0d8008,0x85a480c1, + 0x7e0a02f4,0xd5010004,242 | (261<<9) | (36<<18), + 0x7e0c0a24,0x7e0e0a25,0xf80008cf,0x04070604,end] + check("vertex-scalar-full-mask", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=scalar_select)) + no_scalar_scc = scalar_select.copy() + no_scalar_scc[2] = 0x7d0a0080 # VOPC writes this lane's VCC, not SCC. + check("vertex-no-scalar-mask-proof", "gfx1013-container-vs", + vertex(constants=(0,2,1), program=no_scalar_scc), "requires a reaching scalar SCC comparison") + outside = [0xbf840006, *vertex_arms] # Jump into THEN before saving its mask. + check("vertex-mask-entry", "gfx1013-container-vs", vertex(program=outside), + "branch enters or crosses a masked vertex arm") + store = vertex_arms.copy() + store[6:8] = [0xe0701000,0x80020100] + check("vertex-mask-store", "gfx1013-container-vs", vertex(program=store), + "masked vertex arm has an unsupported exit or memory effect") + overwritten = vertex_arms.copy() + overwritten[7] = 0xbe880380 + check("vertex-mask-clobber", "gfx1013-container-vs", vertex(program=overwritten), + "masked vertex arm overwrites its saved EXEC") + escaping_scalar = vertex_arms.copy() + escaping_scalar[7] = 0xbe9a0381 # THEN writes s26; ELSE must not see a per-lane surrogate. + escaping_scalar[12] = 0x7e08021a + source = folder/"vertex-mask-scalar" + source.write_bytes(vertex(program=escaping_scalar)) + rejected = subprocess.run([exe, sdk, folder/"cache", "gfx1013-container-vs", source, source.with_suffix(".cso")], + capture_output=True, text=True) + assert rejected.returncode and ("unbound numeric SGPR s26" in rejected.stderr or + "undefined on an incoming path: 26" in rejected.stderr), rejected.stderr + # A PS selects one of two read-only scalar records. Only the VGPR + # written by the selected arm is defined after EXEC is restored. + record_select=[0xbe810380, 0xf4080200,0xfa000000, + 0x7c0800ff,0x40800000, 0xbe9a246a,0xbf880004, + 0x80118080,0xf4200804,17<<25,0x7e040220, + 0x8afe7e1a,0xbf880004, + 0x80118480,0xf4200804,17<<25,0x7e040220, + 0xbefe041a,0x7e000302] + def record_pixel(seq): + return patched_pixel(len(seq),seq,table=True,input_address=1<<8,input_signature=position_input) + check("pixel-mask-record-choice","gfx1013-container-ps",record_pixel(record_select)) + record_ir=subprocess.check_output([pathlib.Path(sdk)/"dxc.exe","-dumpbin",folder/"pixel-mask-record-choice.cso"],text=True) + assert record_ir.count("call %dx.types.ResRet.i32 @dx.op.rawBufferLoad")==2,record_ir + # The next lookup re-filters the restored EXEC with the same VCC. It + # has no second SAVEEXEC and its ELSE names the earlier saved pair. + twice = record_select[:-1] + [0x87fe7e6a] + record_select[6:] + check("pixel-mask-record-refilter","gfx1013-container-ps",record_pixel(twice)) + wrong_parent = twice.copy() + wrong_parent[len(record_select)-1+6]=0x8afe7e1c + check("pixel-mask-record-wrong-parent","gfx1013-container-ps",record_pixel(wrong_parent),"wave mask") + invalid = record_select.copy() + invalid[-1]=0x7e000220 # Read s32 after a possibly empty arm. + check("pixel-mask-record-escaping","gfx1013-container-ps",record_pixel(invalid),"unbound numeric SGPR") + # A mesh pixel shader uses floor(SV_Position.x)&1 to pick a texture. + # The two forms compare the slot itself or its 32-byte heap offset. + waterfall_root=folder/"waterfall-root.hlsl" + waterfall_root.write_text('#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)"\n') + subprocess.run([pathlib.Path(sdk)/"dxc.exe","-T","rootsig_1_1","-E","RS",waterfall_root, + "-Fo",folder/"waterfall.root"],check=True) + (folder/"waterfall.pslayout").write_text("meshps1 256 256 64 guest_root\n") + def waterfall_pixel(byte_key=False,modifier=None): + code=[0x7e000f00,0x362e0081,0x7e040280,0x7e060280,0x7e080280, + 0xbebc047e,0xbeb4047e] # two distinct copies of entering EXEC + if byte_key: code.append(0x342e2e85) + if modifier=="unbounded": code[1]=0x7e2e0300 + if modifier=="wrong-mask": code[6]=0xbeb4046a # seed remaining lanes from VCC + head=len(code) + code.extend([0x7e1e0517,0x7d242e0f]) + if modifier=="wrong-key": code[-1]+=1 + if not byte_key: code.append(0x8f0f850f) + code.extend([0xf40c1004,15<<25,0xf0000108,0x00100002,0xbeb43a34]) + if modifier=="effect": code.append(0x7e0a0281) + code.append((0xbf890000 if byte_key else 0xbf850000) | ((head-len(code)-1)&65535)) + code.extend([0xbefe043c,0xf800180f,0,0xbf810000]) + if modifier=="last-scalar": code.insert(-3,0x7e00020f) + return words(*code) + for byte_key in (False,True): + check("waterfall","gfx1013-raw-mesh-ps",waterfall_pixel(byte_key)) + dump=subprocess.check_output([pathlib.Path(sdk)/"dxc.exe","-dumpbin",folder/"waterfall.cso"],text=True) + assert re.search(r"call %dx.types.Handle @dx.op.createHandleFromHeap\([^\n]+i1 false, i1 true\)",dump),dump + assert dump.count("call %dx.types.ResRet.f32 @dx.op.textureLoad")==1,dump + for reason in ("wrong-key","wrong-mask","effect","unbounded","last-scalar"): + source=folder/"waterfall" + source.write_bytes(waterfall_pixel(modifier=reason)) + destination=folder/(reason+".dxil") + result=subprocess.run([exe,sdk,folder/"cache","gfx1013-raw-mesh-ps",source,destination], + capture_output=True,text=True) + assert result.returncode and not destination.exists(),(reason,result.stderr) + if reason=="unbounded": assert "bounded aligned material index" in result.stderr,result.stderr + # Address bits 1, 11 and 15 allocate I/J, position W and packed XY. + # Reading v2 must use SV_Position.w, and v3 still uses screen XY. + position_entry = words(0x7e000302, 0x7e020303, 0xf800180f, 0x01010000, 0xbf810000) + (folder/"mesh-entry-w-xy.pslayout").write_text("meshps2 34818 64\n") + check("mesh-entry-w-xy", "gfx1013-raw-mesh-ps", position_entry) + w_xy = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", + folder/"mesh-entry-w-xy.cso"], text=True) + for channel in (0, 1, 3): + assert re.search(r"@dx.op.loadInput.f32\(i32 4, i32 \d+, i32 0, i8 " + str(channel) + r",", w_xy), w_xy + (folder/"mesh-entry-w-disabled.pslayout").write_text("meshps1 2 34818 64\n") + check("mesh-entry-w-disabled", "gfx1013-raw-mesh-ps", position_entry, "unsupported pixel entry VGPR 2") + check("split-mask-two-arms", "gfx1013-container-ps", patched_pixel(len(two_arms), two_arms, + input_address=1 << 8, input_signature=position_input)) + cmpx = [0xbefe0a7e, 0xbe8a047e, 0x7c2800f4, 0x7e0002f2, + 0x8afe7e0a, 0x7e0002f0, 0xbefe040a] + check("cmpx-partition", "gfx1013-container-ps", patched_pixel(len(cmpx), cmpx, + input_address=1 << 8, input_signature=position_input)) + unproven = cmpx.copy() + unproven[1] = 0xbf800000 + check("cmpx-wrong-parent", "gfx1013-container-ps", patched_pixel(len(unproven), unproven, + input_address=1 << 8, input_signature=position_input), "unproven enclosing whole-quad EXEC") + first = [0xd557000e, (240 << 18) | (128 << 9) | 242, 0x7e28050e, 0x7e000214] + check("readfirstlane-uniform-median", "gfx1013-container-ps", patched_pixel(len(first), first)) + varying = [0x7e280500, 0x7e000214] + check("readfirstlane-varying-position", "gfx1013-container-ps", patched_pixel(len(varying), varying, + input_address=1 << 8, input_signature=position_input), "wave-uniform reaching value") + partition = [0xbe8c047e, 0xbefe0a7e, 0xbe8a047e, 0x7c0400f2, + 0xd4010016, 0x000200f2, 0x8896166a, 0x87fe7e16, + 0xbf880001, 0x7e0002f4, 0x8afe7e0a, 0xbf880003, + 0xbe96240c, 0x7e0002f2, 0xbe9e2516, 0xbefe040a] + check("compare-union-exec-arms", "gfx1013-container-ps", patched_pixel(len(partition), partition, + input_address=1 << 8, input_signature=position_input)) + foreign_mask = partition.copy() + foreign_mask[12] = 0xbe962408 + check("unproven-inner-coverage", "gfx1013-container-ps", patched_pixel(len(foreign_mask), foreign_mask, + input_address=1 << 8, input_signature=position_input), "inner EXEC requires saved entry coverage") + unsafe = masked.copy() + unsafe[3] = 0xb0000002 # scalar state changes for the whole guest wave + check("masked-scalar", "gfx1013-container-ps", patched_pixel(len(unsafe), unsafe, + input_address=1 << 8, input_signature=position_input), "lane-local vector arithmetic") + full_mask = lanes + [0xbe80036a] + check("full-mask", "gfx1013-container-ps", patched_pixel(len(full_mask), full_mask), + "consumes a full wave mask") + # Two barycentric registers, three pull-model registers, one line + # stipple register, then position.y in V6 (position.x disabled). + position = [0x7e000306] + mask = (1 << 1) | (1 << 3) | (1 << 7) | (1 << 9) + check("pixel-position", "gfx1013-container-ps", patched_pixel(1, position, input_address=mask, + input_signature=((b"ISG1", signature(b"SV_Position", 1)),))) + # Export the numeric I,J,J,I registers. DXIL orders the three + # weights by vertex, so I/J must select components 1/2. + ij = patched_pixel(prefix=[0xbf800000], input_address=2, export=(0xf800180f,0x00010100)) + check("center-weights", "gfx1013-container-ps", ij) + ij_ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe","-dumpbin",folder/"center-weights.cso"],text=True) + assert "SV_Barycentrics" in ij_ir and all( + f"@dx.op.loadInput.f32(i32 4, i32 0, i32 0, i8 {col}," in ij_ir for col in (1,2)), ij_ir + # Covered lanes replace I with 1/4. A subsequent horizontal quad + # shuffle must still see original I on the other side of an edge. + edge = [0xbe8c047e,0xbefe0a7e,0xbe8a047e,0xbefe040c,0x7e0002ff,0x3e800000, + 0xbefe040a,0x060000fa,0xff00b100] + check("masked-ij-quad-edge", "gfx1013-container-ps", patched_pixel(len(edge),edge,input_address=2)) + check("pull-weights", "gfx1013-container-ps", + patched_pixel(prefix=[0xbf800000], input_address=8, export=(0xf800180f,0x00010100)), + "unsupported pixel entry VGPR") + for semantic,system,component,channel in ( + (b"SV_Depth",65,3,0), (b"SV_DepthLessEqual",68,3,0), + (b"SV_DepthGreaterEqual",67,3,0), (b"SV_StencilRef",69,1,1), + (b"SV_Coverage",66,1,2)): + output=((b"OSG1",signature(semantic,system,component,0xffffffff,1)),) + data=patched_pixel(input_signature=output, export=(0xf8001880 | (1<<channel),0)) + check(semantic.decode(), "gfx1013-container-ps", data) + check("missing-depth", "gfx1013-container-ps", patched_pixel(export=(0xf8001881,0)), "unmapped depth") + face=((b"ISG1",signature(b"SV_IsFrontFace",9,1,0,1)),(b"OSG1",signature(b"SV_Target",64,1))) + check("face", "gfx1013-container-ps", + patched_pixel(prefix=[0x7e000300],input_address=1<<12,input_signature=face)) + # Use the same VGPR for the shuffled operand, unshuffled operand and result. + for control in (0xaa,0xb1,0x4e,0x1b,0xf5): + quad=[0xbefe0a7e,0x060000fa,0xff000000 | control<<8] + check(f"quad-{control}", "gfx1013-container-ps", patched_pixel(len(quad), quad, + input_address=1<<8,input_signature=position_input)) + # In WQM every source of a quad-local broadcast or swap is active. + for perm in (0, 0xb1): + lanes = [(perm >> (2 * n)) & 3 for n in range(4)] + dpp8 = sum((lanes[n % 4] + (n & 4)) << (8 + 3 * n) for n in range(8)) + variants = [(0x060000fa, 0xff0c0000 | perm << 8), (0x060000e9, dpp8), (0x060000ea, dpp8)] + for n, (op, control) in enumerate(variants): + label = f"quad-fi-{perm}-{n}" + args = [0xbefe0a7e, op, control] + check(label, "gfx1013-container-ps", patched_pixel(len(args), args, input_address=2)) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], text=True) + assert ("@dx.op.quadReadLaneAt.i32(" if not perm else "@dx.op.quadOp.i32(") in ir + check("quad-dpp8-cross"+str(perm), "gfx1013-container-ps", + patched_pixel(3, [0xbefe0a7e, 0x060000ea, dpp8 ^ (4 << 8)], input_address=2), + "repeating quad-local selections") + check("quad-fi-exact", "gfx1013-container-ps", + patched_pixel(2, [0x060000fa, 0xff0c0000], input_address=2), "requires a proven whole quad") + check("quad-half-row-mirror", "gfx1013-container-ps", + patched_pixel(3, [0xbefe0a7e, 0x060000fa, 0xff054100], input_address=2), + "half-row mirror requires a proven eight-lane pixel layout") + full = [0xbebe25c1,0x7e2202fa,0xff054100,0xbefe043e] + check("mirror-unknown-pixel-lanes","gfx1013-container-ps", + patched_pixel(len(full),full,input_address=2),"needs an unobserved source lane") + full[-1] += 2 + check("mirror-unmatched-exec","gfx1013-container-ps", + patched_pixel(len(full),full,input_address=2),"matching restore in the same block") + quad[0]=0xbf800000 + check("quad-no-wqm","gfx1013-container-ps",patched_pixel(len(quad),quad), + "without whole-quad entry") + quad[-1]^=1<<28 + check("quad-partial-mask","gfx1013-container-ps",patched_pixel(len(quad),quad), + "full-row, full-bank") + check("missing-position", "gfx1013-container-ps", patched_pixel(1, position, input_address=mask), + "position absent from pixel input signature") + for op in (32, 37): + prefix = [0xbe810380, 0xf40c0200, 0xfa000000, + 0xbe840380, 0xbe8503ff, 0x00fff000, 0xbe8603ff, 0x04000000, 0xbe870380, + 0x7e0002f0, 0x7e0202f2, 0x7e0402f4, 0xf0000108 | op << 18, 0x00220000] + check(f"sample{op}", "gfx1013-container-ps", patched_pixel(len(prefix), prefix, True)) + # Six threads do not form complete compute quads, so implicit derivatives stay refused. + check(f"derivative{op}", cs, compute(words(*prefix, end), threads=6, table=True), + "implicit derivatives require a pixel stage") + image_setup = prefix[:-2] + # Reread v0 as the input record index before the instruction overwrites it. + descriptor = [0xbe810380, 0xf4080200, 0xfa000000] + indexed = [*descriptor, 0x7e000281, 0xe0302004, 0x80020000] + for stride, expected in [(16, ""), (4, "outside a verified"), (0, "outside a verified")]: + check(f"indexed-pixel-record-{stride}", "gfx1013-container-ps", + patched_pixel(len(indexed), indexed, table=True, uses=[(0x300, 0, 0, stride, 4)]), expected) + raw_immediate = [*descriptor, 0xe0300134, 0x80020000] + check("raw-pixel-immediate-offset", "gfx1013-container-ps", + patched_pixel(len(raw_immediate), raw_immediate, table=True)) + for op in (32, 34, 36, 37, 39): + coords = [0x7e060280, 0x7e080280, 0x7e0a0280] + sample = [*image_setup, *coords, 0xf0000e08 | (op << 18), 0x80220400] + name = f"packed-sample-{op}" + check(name, "gfx1013-container-ps", + patched_pixel(len(sample), sample, table=True, export=(0xf800180f, 0x05040504))) + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(name+".cso")], text=True) + components = re.findall(r"extractvalue %dx.types.ResRet.f32 %\w+, (\d)", ir) + assert components == ["1", "2", "3"] and "shl i32" in ir, (name, components) + invalid = [*image_setup, 0xf09c0e18, 0x80220400] # Cube needs a separate view contract. + check("packed-sample-cube", "gfx1013-container-ps", patched_pixel(len(invalid),invalid,table=True), + "unsupported image dimension or D16") + # The derivative sample executes with its quad intact. Coverage masks + # the writeback to v0; a helper must keep the pre-sample coordinate. + window = [0xbe95037e, 0xbefe097e, 0xbe97037e, *image_setup, 0xbf820000, + 0xbefe0315, 0xf0800108, 0x00220000, 0xbefe0317, 0x060000fa, 0xff00b100, 0xbefe0315] + check("wave32-exact-sample", "gfx1013-container-ps", + patched_pixel(len(window), window, table=True, wave32=True)) + sample_ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", + folder/"wave32-exact-sample.cso"], text=True) + assert all(op in sample_ir for op in ("@dx.op.sample.f32", "@dx.op.isHelperLane.i1", "select i1", + "@dx.op.quadOp.i32")) + assert re.search(r"select i1 %\w+, float %\w+, float %\w+", sample_ir), sample_ir + clobbered = window.copy() + clobbered.insert(3, 0xbe950380) # Overwrite the exact coverage mask in s21. + check("wave32-clobbered-exec", "gfx1013-container-ps", + patched_pixel(len(clobbered), clobbered, table=True, wave32=True), + "unproven EXEC for a conditional sample") + for name, inst, intrinsic in (("raw", 0xe0701000, "rawBufferStore.i32"), + ("typed", 0xe0102000, "bufferStore.i32")): + store = [*image_setup, inst, 0x80020100] + check("pixel-buffer-" + name, "gfx1013-container-ps", patched_pixel(len(store), store, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/("pixel-buffer-" + name + ".cso")], + check=True, capture_output=True, text=True).stdout + assert "@dx.op." + intrinsic + "(" in dump, dump + for channels in (1, 2, 4): + # Two distinguishable binary16 values in each VGPR. + mask = (1 << channels) - 1 + store = 0xf0200008 | mask << 8 + code = [*image_setup, 0x7e0802ff, 0x40003c00, 0x7e0a02ff, 0xc000bc00, store, 0x80020400, end] + label = f"d16-store-{channels}" + check(label, cs, compute(words(*code), table=True)) + check("pixel-" + label, "gfx1013-container-ps", patched_pixel(len(code)-1, code[:-1], True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], + check=True, capture_output=True, text=True).stdout + assert dump.count("call float @dx.op.legacyF16ToF32(") == channels and "@dx.op.textureStore.f32(" in dump, dump + vs_store = [*code[:-1], 0xf80008cf, 0, end] + check("vertex-uav", "gfx1013-container-vs", vertex(program=vs_store, table=True)) + code[-2] = 0x8002ff00 + check("d16-store-overflow", cs, compute(words(*code), table=True), "image data overflow") + code[-3], code[-2] = 0xf0200508, 0x80020400 + check("d16-store-holes", cs, compute(words(*code), table=True), "image opcode or descriptor modifiers") + for op, profile, dim, method in ((40, "gfx1013-container-ps", 1, "sampleCmp"), + (47, cs, 5, "sampleCmpLevelZero")): + code = comparison_program(op, dim) + label = f"comparison-{op}" + source = compute(words(*code, end), table=True) if profile == cs else patched_pixel(len(code), code, True) + check(label, profile, source) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], + check=True, capture_output=True, text=True).stdout + assert f"@dx.op.{method}.f32(" in dump and "i32 32782" in dump, dump + cube_cmp = comparison_program(dim=3) + check("cube-array-compare", "gfx1013-container-ps", patched_pixel(len(cube_cmp), cube_cmp, True)) + code = comparison_program(sampler=0x1012) # point without coordinate truncation + check("comparison-invalid", cs, compute(words(*code, end), table=True), "unsupported comparison sampler fields") + for op in (32, 39): + code = [*image_setup, 0xf0000508 | op << 18, 0x40220002] + check(f"packed-{op}", "gfx1013-container-ps", patched_pixel(len(code), code, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/f"packed-{op}.cso"], + check=True, capture_output=True, text=True).stdout + assert dump.count("call float @dx.op.legacyF16ToF32(") == 2, dump + # Lower all four cube ALU operations, then use face coordinates in a sample. + cube = list(image_setup) + for op in range(0x144, 0x148): + cube.extend((0xd4000000 | op << 16 | (4 + op - 0x144), 256 | 257 << 9 | 258 << 18)) + cube.extend((0xf09c011a, 0x00220005, 0x00000406)) # S=V5, T=V6, face=V4 + check("cube", "gfx1013-container-ps", patched_pixel(len(cube), cube, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"cube.cso"], + check=True, capture_output=True, text=True).stdout + assert "@dx.op.sampleLevel.f32(" in dump and "fcmp oge float" in dump and "fptosi float" in dump and "cubearray" in dump.lower(), dump + code = [*image_setup, 0xf0000118, 0x00020000] + check("cube-load", "gfx1013-container-ps", patched_pixel(len(code), code, True), "unsupported cube") + for label, op, dim, mask, flags, nsa, expected_ir in ( + ("gradient", 34, 1, 1, 0, [0x00020100, 1], "sampleGrad.f32"), + ("gradient-cube-array", 34, 3, 1, 0, [0x00020100, 0x0201], "sampleGrad.f32"), + ("gradient-array", 34, 5, 1, 0, [0x00020100, 0x0201], "sampleGrad.f32"), + ("lod-query", 96, 1, 3, 0x1000, [], "calculateLOD.f32"), + ("cube-array-lod", 96, 3, 3, 0, [], "calculateLOD.f32"), + ("cube-array-gather", 71, 3, 2, 0, [], "textureGather.f32"), + ("gather-green", 64, 1, 2, 0, [], "textureGather.f32"), + ("gather-blue-lz", 71, 1, 4, 0, [], "textureGather.f32"), + ("mip-size", 14, 1, 15, 0, [], "getDimensions")): + instruction = 0xf0000000 | op << 18 | dim << 3 | mask << 8 | flags | len(nsa) << 1 + code = [*image_setup, instruction, 0x00220000, *nsa] + if op == 64: + check(label+"-mips", "gfx1013-container-ps", patched_pixel(len(code), code, True), + "implicit gather requires a sampler fixed to mip zero") + code[image_setup.index(0x00fff000)] = 0 + check(label, "gfx1013-container-ps", patched_pixel(len(code), code, True)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/(label+".cso")], + check=True, capture_output=True, text=True).stdout + assert f"@dx.op.{expected_ir}(" in dump, dump + if op == 96 and dim == 1: + assert "i1 true)" in dump and "i1 false)" in dump and "fdiv float" in dump, dump + if op == 34: + wrong = [*image_setup, instruction - 2, 0x00220000, nsa[0]] + check(label+"-short", "gfx1013-container-ps", patched_pixel(len(wrong), wrong, True), + "incomplete image NSA address list") + pair=[exe,sdk,folder/"cache","gfx1013-container-pair", + folder/"vertex",folder/"linked.vs.cso",folder/"patched",folder/"linked.ps.cso"] + for expected in (0, 1): + result = subprocess.run(pair, check=True, capture_output=True, text=True) + assert f"graphics_pair frontend_cache_hit={expected}" in result.stdout + assert (folder/"linked.vs.cso").read_bytes()==(folder/"vertex.cso").read_bytes() + assert (folder/"linked.ps.cso").read_bytes()==(folder/"patched.cso").read_bytes() + pair[-2] = folder/"bary-two-pairs" + for warm in (0, 1): + result = subprocess.run(pair, check=True, capture_output=True, text=True) + assert f"graphics_pair frontend_cache_hit={warm}" in result.stdout + pair[-2]=folder/"smooth" + mismatch=subprocess.run(pair,capture_output=True,text=True) + assert mismatch.returncode and "stages disagree" in mismatch.stderr + # VS reads root 4, PS reads root 1. The linked b0 puts root 4 after + # four PS words although both stages load the guest value from s0. + check("root-vs", "gfx1013-container-vs", vertex(constants=(4, 1))) + check("root-ps", "gfx1013-container-ps", patched_pixel(prefix=[0x7e000200], constants=(1, 4))) + pair[-4], pair[-2] = folder/"root-vs", folder/"root-ps" + for warm in range(2): + result = subprocess.run(pair, check=True, capture_output=True, text=True) + assert f"frontend_cache_hit={warm}" in result.stdout + for output, col in (("linked.vs.cso", 1), ("linked.ps.cso", 0)): + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/output], + check=True, capture_output=True, text=True).stdout + assert any("@dx.op.cbufferLoadLegacy.i32(i32 59" in line and f", i32 {col})" in line + for line in dump.splitlines()), dump + (folder/"root-ps").write_bytes(patched_pixel(prefix=[0x7e000200], constants=(1, 32))) + overflow = subprocess.run(pair, capture_output=True, text=True) + assert overflow.returncode and "exceeds 32 words" in overflow.stderr, overflow.stderr + # Directory mode consumes the runtime's last-published .a marker and + # matches the FNV key over both containers, the root, and optional IA. + capture = folder / "requests" + capture.mkdir() + root = b"DXBC" + bytes(16) + words(1, 68, 1, 36) + b"RTS0" + words(24, 2, 0, 24, 0, 24, 0) + stem = publish(capture, vertex(), patched_pixel(), root) + batch = [exe, sdk, folder/"cache", "--jobs", "2", "gfx1013-container-pair", + "--requests", capture, folder/"warm"] + raw_vs = words(0x7e020b00, 0xf80008cf, 0x01010101, end) + raw_ps = words(0x7e0002f2, 0xf8001c0f, 0, end) + # A recorded logical table can contain scalar buffers outside the + # serialized desktop range. Both stage identities and each used + # record are checked, including when a warm cache already exists. + rs = folder/"short-root.hlsl" + rs.write_text('#define RS "DescriptorTable(CBV(b27,space=1))"\n') + short = folder/"short-root.bin" + subprocess.run([pathlib.Path(sdk)/"dxc.exe","-T","rootsig_1_1","-E","RS",rs,"-Fo",short],check=True) + interfaces = folder/"reviewed-cache"/"interfaces" + interfaces.mkdir(parents=True) + def install(raw, container): + (interfaces/(hashlib.sha256(raw).hexdigest()+".cdxil")).write_bytes(container) + ps_id = [0xd5800000,255,0x789,0xd5800000,255,0xabc] + ps = words(*ps_id) + raw_ps + install(ps, patched_pixel(7,[*ps_id,0x7e0002f2])) + for slot in (2,5): + vs_id = [0xd5800000,255,0x123,0xd5800000,255,slot] + op = [*vs_id,0xbe890380,0xf4080204,0xfa000000+32*slot, + 0xf42000c4,0xfa000000,0x7e000203,0xf80008cf,0,end] + raw = words(*op) + fixture_dir = folder/f"reflected-slot-{slot}" + publish(fixture_dir, ps, raw, short.read_bytes(), ps_inputs=(0x8080, 0x8080)) + job = [exe,sdk,interfaces.parent,"gfx1013-container-pair","--requests",fixture_dir,folder/"warm"] + missing_record = f"missing reflected resource: VS root 0 offset {32*slot} kind 0 user SGPR 8" + for offset,error in ((8*slot,None),(8*slot+8,missing_record)): + install(raw, vertex(program=op, uses=[(0x302,offset,0,0,4 | 8<<8)])) + result = subprocess.run(job, capture_output=True,text=True) + if error: + assert result.returncode and error in result.stderr,result.stderr + else: + assert result.returncode == 0,result.stderr + install(raw, patched_pixel(len(vs_id),vs_id)) + install(ps, vertex(program=[*ps_id, *struct.unpack("<4I",raw_vs)])) + result = subprocess.run(job,capture_output=True,text=True) + assert result.returncode and "raw exports disagree with reflected stage" in result.stderr,result.stderr + for label, fragment, diagnostic in ( + ("raw-export", raw_ps, ""), + ("raw-branch", words(0xbf820000) + raw_ps, "verified stage interface or wave state")): + raw_dir = folder / label + raw_key = publish(raw_dir, fragment, raw_vs, root) + raw_job = batch.copy() + raw_job[-2] = raw_dir + result = subprocess.run(raw_job, capture_output=True, text=True) + if diagnostic: + assert result.returncode and diagnostic in result.stderr, result.stderr + else: + assert result.returncode == 0, result.stderr + for stage in ("ps", "vs"): + assert (folder/"warm"/f"{raw_key}.{stage}.cso").read_bytes().startswith(b"DXBC") + # One scalar entry precedes the packed screen coordinate. A different + # mask moves that entry and must change the request and compilation. + packed_ps = words(0x7e000cf9, 0x00040601, 0xf800180f, 0, end) + # Two independent comparisons kill fragment lanes before their color + # export. Empty waves branch to EXP_NULL beyond the first endpgm. + kill = [0xbe90047e, 0xbefe0410, 0x7e1002f2, 0x7e0a0280, + 0xd4010008, 0x21100, 0x7d040a80, 0x8888086a, 0x8afe087e, 0xbf880003, + 0xf800180f, 0, end, 0xf8001890, 0x80808080, end] + for name, clobber in (("terminal-discard", False), ("terminal-discard-clobber", True)): + sequence = kill.copy() + if clobber: + sequence.insert(6, 0xbe880380) + fixture = folder/name + key = publish(fixture, words(*sequence), raw_vs, root, ps_inputs=(2, 2)) + job = batch.copy() + job[-2] = fixture + result = subprocess.run(job, capture_output=True, text=True) + if clobber: + assert result.returncode and "discard mask has no reaching lane comparison" in result.stderr + else: + assert result.returncode == 0, result.stderr + ir = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", + folder/"warm"/f"{key}.ps.cso"], text=True) + assert "call void @dx.op.discard(i32 82, i1 %" in ir + for name, entry, ps, vs, ok in ( + ("packed-input", (0x8080, 0x8080), packed_ps, raw_vs, True), + ("packed-absent", (0, 0), packed_ps, raw_vs, False), + ("center-position-zw", (0x0c02, 0x0c02), + words(0xf800180f, 0x03020302, end), raw_vs, True), + ("center-position-zw-packed", (0x8c02, 0x8c02), + words(0xf800180f, 0x04040302, end), raw_vs, True), + ("center-position-missing-w", (0x0402, 0x0402), + words(0xf800180f, 0x03020302, end), raw_vs, False), + ("whole-quad-second-param", (2, 2), + words(0xbe8c047e, 0xbefe0a7e, 0xc8100400, 0xc8110401, + 0xbefe040c, 0xf800180f, 0x04040404, end), + words(0xbe8c0400, 0x938dff0d, 0x80000, 0xf4080406, 0xfa000000, + 0x4a000002, 0xbf8cc07f, 0xe03c2000, 0x80040100, + 0xe0342010, 0x80040400, 0xe9c3200c, 0x80040800, + 0xf80008cf, 0x08030201, 0xf8000211, 0x04040404, end), True), + ("whole-quad-param", (0x8002, 0x8002), + words(0xbe8c047e, 0xbefe0a7e, 0xbe8a047e, 0xc8100000, 0xc8140100, + 0xc8110001, 0xc8150101, 0xbefe040c, 0xf800180f, 0x05040504, end), + words(0x7e020b00,0xf80008cf,0x01010101,0xf800020f,0x01010101,end), True)): + fixture = folder / name + key = publish(fixture, ps, vs, root, ps_inputs=entry) + job = batch.copy() + job[-2] = fixture + result = subprocess.run(job, capture_output=True, text=True) + assert (result.returncode == 0) == ok, (name, result.stderr) + if not ok: + assert "pixel entry VGPR" in result.stderr, result.stderr + elif name.startswith("center-position-"): + binary = folder/"warm"/f"{key}.ps.cso" + dump = subprocess.check_output([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", binary], text=True) + channels = re.findall(r"call float @dx\.op\.loadInput\.f32\(i32 4, i32 0, i32 0, i8 (\d+)", dump) + assert set(channels) == set("0123" if name.endswith("packed") else "23"), (name, channels) + # A UNORM byte at offset 7 and a pair at offset 4 feed distinct VS outputs. + # Keep both conversions and byte offsets on cold and decoded-IR cache paths. + for label, pair_offset in (("fixed-unorm", 4), ("fixed-unaligned-pair", 5)): + vertex_program = words(0xbe8c0400, 0x938dff0d, 0x80000, 0xf4080406, 0xfa000000, + 0x4a000002, 0xbf8cc07f, 0xe8082007, 0x80040100, + 0xe8712000 | pair_offset, 0x80040200, + 0xf80008cf, 0x01030201, end) + fixture = folder / label + key = publish(fixture, raw_ps, vertex_program, root, ps_inputs=(2, 2)) + job = batch.copy() + job[-2] = fixture + for run in range(2): + result = subprocess.run(job, capture_output=True, text=True) + if pair_offset == 5: + assert result.returncode and not (folder/"warm"/f"{key}.txt").exists(), result.stderr + break + assert result.returncode == 0, result.stderr + manifest = (folder/"warm"/f"{key}.txt").read_text().splitlines() + assert "x2w-manifest 3" in manifest and {"fixedvb 7 61", "fixedvb 4 49"} <= set(manifest), manifest + # All attributes use the entry vertex index. An x4 fetch may overwrite + # that VGPR after the byte selector has been fetched, but not before. + for label, overlap_early in (("fixed-uint4-byte", False), ("fixed-clobbered-index", True)): + prologue = [0xbe8c0400, 0x938dff0d, 0x80000, 0xf4080406, 0xfa000000, + 0x4a000002, 0xbf8cc07f] + wide = [0xe0382004, 0x80040000] + selector = [0xe8282014, 0x80040400] + fetch = wide + selector if overlap_early else selector + wide + vertex_program = words(*prologue, *fetch, 0xf80008cf, 0x04020100, end) + fixture = folder / label + key = publish(fixture, raw_ps, vertex_program, root, ps_inputs=(2, 2)) + job = batch.copy() + job[-2] = fixture + result = subprocess.run(job, capture_output=True, text=True) + if overlap_early: + assert result.returncode and not (folder/"warm"/f"{key}.txt").exists(), result.stderr + else: + assert result.returncode == 0, result.stderr + manifest = (folder/"warm"/f"{key}.txt").read_text().splitlines() + assert {"fixedvb 4 3", "fixedvb 20 62"} <= set(manifest), manifest + # Mask a real PS root constant to select table byte offset 0 or 32. + # Reading through the resulting descriptor must require two SRV slots. + indexed = [0xbe810380, 0x8702a002, 0xf4080200, 2 << 25, + 0xf42000c4, 0xfa000000, 0x7e000203] + indexed_ps = patched_pixel(len(indexed), indexed, + root_inputs=((3,0,1,0,0), (0,0,1,0,0x102))) + # s4 supplies the byte offset and is also the first of eight destinations. + # The second raw load still consumes the address computed at entry. + load8 = [0x8704a002, 0xf40c0100, (4 << 25) + 16, 0x7e00020b] + descriptor_inputs = ((1,0,2,0,0), (0,0,1,0,0x102)) + check("root-index", "gfx1013-container-ps", + patched_pixel(len(load8), load8, root_inputs=descriptor_inputs)) + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"root-index.cso"], + check=True, capture_output=True, text=True).stdout + first, second = re.findall(r"call .*?@dx\.op\.rawBufferLoad\.i32\(i32 139, [^,]+, i32 (%\w+),", dump) + assert f"{second} = add i32 {first}, 16" in dump, dump + unknown8 = [*load8[1:]] + unknown8[1] = (2 << 25) + 16 + check("root-index-range", "gfx1013-container-ps", + patched_pixel(len(unknown8), unknown8, root_inputs=descriptor_inputs), + "unbounded or unaligned root descriptor index") + for label, declaration, error in ( + ("cbv", "CBV(b0)", ""), + ("srv", "SRV(t0, visibility=SHADER_VISIBILITY_VERTEX)", ""), + ("uav", "UAV(u0)", "requires a root CBV or SRV"), + ("hidden", "SRV(t0, visibility=SHADER_VISIBILITY_PIXEL)", "visibility mismatch"), + ("array2", "DescriptorTable(SRV(t0,numDescriptors=2)),RootConstants(num32BitConstants=1,b0)", ""), + ("array1", "DescriptorTable(SRV(t0)),RootConstants(num32BitConstants=1,b0)", "exceeds its declared root range")): + rs = folder/"root.hlsl" + rs.write_text(f'#define RS "{declaration}"\n') + compiled_root = folder/"root.bin" + subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "RS", + rs, "-Fo", compiled_root], check=True) + source = folder/("descriptor-" + label) + vs, ps = (vertex(), indexed_ps) if label.startswith("array") else (root_vs, patched_pixel()) + descriptor_stem = publish(source, vs, ps, compiled_root.read_bytes()) + job = batch.copy() + job[-2] = source + for warm in range(1 if error else 2): + result = subprocess.run(job, capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + else: + assert result.returncode == 0 and f"frontend_cache_hit={warm}" in result.stdout, result.stderr + if label == "array2": + dump = subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-dumpbin", folder/"warm"/f"{descriptor_stem}.ps.cso"], + check=True, capture_output=True, text=True).stdout + assert "i32 0, i32 1, i32 0, i8 0 }" in dump and "i1 true)" in dump, dump + for expected in (0, 1): + result = subprocess.run(batch, capture_output=True, text=True) + assert result.returncode == 0, result.stderr + assert f"graphics_pair frontend_cache_hit={expected}" in result.stdout + assert "requests=1 compiled=1 refused=0" in result.stdout + for stage, reference in (("vs", "vertex"), ("ps", "patched")): + assert (folder/"warm"/f"{stem}.{stage}.cso").read_bytes() == (folder/f"{reference}.cso").read_bytes() + rect=batch.copy() + rect[5]="gfx1013-container-rect" + for _ in range(2): + result=subprocess.run(rect,capture_output=True,text=True) + assert result.returncode==0, result.stderr + gs=folder/"warm"/f"{stem}.gs.cso" + dump=subprocess.run([pathlib.Path(sdk)/"dxc.exe","-dumpbin",gs],capture_output=True,text=True,check=True).stdout + assert dump.count("call void @dx.op.emitStream(")==6 and dump.count("call void @dx.op.cutStream(")==2 + (capture / f"req_{stem}.root").write_bytes(root + b"!") + result = subprocess.run(batch, capture_output=True, text=True) + assert result.returncode and "graphics request key mismatch" in result.stderr + for case, element, error in ( + ("stream", b"position 0 2 3 4294967295 0 0", ""), + ("instanced", b"POSITION 0 2 5 16 1 2", ""), + ("semantic", b"COLOR 0 2 0 0 0 0", "missing vertex input"), + ("component", b"POSITION 0 3 0 0 0 0", "vertex format disagrees")): + folder_input = folder/case + publish(folder_input, vertex(True), patched_pixel(), root, b"ia1 1\n"+element+b"\n") + batch[-2] = folder_input + for warm in range(1 if error else 2): + result = subprocess.run(batch, capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, result.stderr + else: + assert result.returncode == 0, result.stderr + assert f"frontend_cache_hit={warm}" in result.stdout + check("patch-range", "gfx1013-container-ps", patched_pixel(3), "record outside") + check("pixel", "gfx1013-direct-constant-ps", words(0x7e0002f2, 0xf800180f, 0, end)) + + +if __name__ == "__main__": + main() diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py new file mode 100644 index 0000000000..e2cb289df7 --- /dev/null +++ b/tests/native_direct_mesh_check.py @@ -0,0 +1,197 @@ +"""Source-built mesh ISA, direct DXIL validation and fail-closed controls.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + + +def triangle(): + return [ + 0xbefc03ff, 0x1003, 0xbf900009, # m0 = (1 primitive << 12) | 3 vertices; GS_ALLOC_REQ + 0xd7650000, 0x100c1, # v0 = mbcnt_lo(-1, 0) + 0x36020081, 0x2c040081, # v1 = v0 & 1; v2 = v0 >> 1 + 0x7e020d01, 0x7e040d02, # convert to f32 + 0x7e060280, 0x7e0802f2, # z = 0; w = 1 + 0xf80008cf, 0x04030201, # POS0 + 0x7e0a02ff, 0x200400, # triangle indices 0,1,2 + 0xf8000941, 0x80808005, 0xbf810000, + ] + + +def checked_pixel_entry(folder, compiler, sdk): + from mesh57_pixel_entry import pixel_entry + from gfx2hlsl import fnv, mesh57_key + + # One source-built v_mov/EXP pixel program. Only a reviewed version 2 + # profile with all six exact spans may supply its entry to the offline compiler. + ms = struct.pack("<%dI" % len(triangle()), *triangle()) + ps = struct.pack("<8I", *([0x7e0002f2] * 5), 0xf800180f, 0, 0xbf810000) + root_source = folder / "checked-root.hlsl" + root_source.write_text('#define RS "RootFlags(0)"') + root_file = folder / "checked-root.bin" + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", root_file, root_source], check=True) + root, state_a, state_b = root_file.read_bytes(), b"abcd", b"efgh" + key = mesh57_key(ms, ps, root) + request = folder / f"req_{key:016x}.ps57" + for ext, part in ((".m57", ms), (".ps57", ps), (".root", root)): + request.with_suffix(ext).write_bytes(part) + desc = bytearray(0x300) + for word, length in ((2, len(state_a)), (4, len(state_b)), (6, len(ps)), (14, len(ms))): + struct.pack_into("<Q", desc, 8 * word, length) + fixed = [desc, state_a, state_b] + variant = key + for part in fixed: + variant = fnv(part, fnv(struct.pack("<Q", len(part)), variant)) + archive = folder / f"req_{variant:016x}.s57" + archive.write_bytes(struct.pack("<Q3I", key, *map(len, fixed)) + b"".join(fixed)) + parts = fixed + [root, ms, ps] + header = bytearray(532) + struct.pack_into("<8s6I", header, 0, b"X2WM572", *map(len, parts)) + profile = folder / f"{variant:016x}.mesh57-state" + blob = header + struct.pack("<3I", 0, 0, 64) + b"".join(parts) + profile.write_bytes(blob) + layout = pixel_entry(request, archive, profile) + assert layout == "meshps1 0 0 64" + request.with_suffix(".pslayout").write_text(layout) + out = folder / "checked-pixel.dxil" + subprocess.run([compiler, sdk, folder / "cache", "gfx1013-raw-mesh-ps", request, out], check=True) + assert out.read_bytes()[:4] == b"DXBC" + # The v6 profile has the same exact-span requirement and enables the captured guest root. + header[:8] = b"X2WM576\0" + extra = struct.pack("<8I", 12, 4, 1, 1, 16, 0, 0, 47) + profile.write_bytes(header + struct.pack("<3I", 0, 0, 64) + extra + b"".join(parts)) + assert pixel_entry(request, archive, profile) == "meshps1 0 0 64 guest_root" + # The first 24 stage bytes and profile filename still match, but the hardware variant differs. + blob[-1] ^= 1 + profile.write_bytes(blob) + try: + pixel_entry(request, archive, profile) + except ValueError as error: + assert "bytes differ" in str(error) + else: + raise AssertionError("accepted another hardware variant") + + +def main(): + compiler, sdk = map(Path, sys.argv[1:]) + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup")) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + checked_pixel_entry(root, compiler, sdk) + raw = root / 'fixture.m57' + layout = raw.with_suffix('.mslayout') + layout.write_text('mesh1 128 3 1 2 128 64') + def run(name, words, expected=None): + raw.write_bytes(struct.pack('<%dI' % len(words), *words)) + out = root / (name + '.dxil') + result = subprocess.run([compiler, sdk, root/'cache', 'gfx1013-raw-ms', raw, out], + capture_output=True, text=True) + if expected is not None: + assert result.returncode and expected in result.stderr and not out.exists(), (result.stdout,result.stderr) + return '' + assert result.returncode == 0, result.stderr + return subprocess.check_output([sdk/'dxc.exe','-dumpbin',out], text=True) + + program = triangle() + text = run('triangle',program) + for marker in ('MeshOutputTopology=triangle','setMeshOutputCounts(i32 168, i32 3, i32 1)', + 'storeVertexOutput.f32','emitIndices','flattenedThreadIdInGroup'): + assert marker in text, marker + # A per-vertex raw PARAM0.xy must have the same semantic/channel + # indices as the corresponding fixed PS reads. + varying = program[:13] + [0xf8000203,0x00000201] + program[13:] + text = run('varyings',varying) + assert 'TEXCOORD' in text and 'storeVertexOutput.f32(i32 171, i32 2' in text + # Runtime root constants select an actual scalar diamond. Each path + # defines s20, consumed by a vertex export after the join. + rs = root / 'fixture.hlsl' + rs.write_text('#define RS "RootConstants(num32BitConstants=1,b0),DescriptorTable(SRV(t0))"') + subprocess.run([sdk/'dxc.exe','-T','rootsig_1_1','-E','RS','-Fo',raw.with_suffix('.root'),rs], check=True) + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\ntable 16 1') + controlled = program.copy() + controlled[7] = 0x7e020c14 # read joined s20 + # Clear the high address. Read the four-word V# at table byte + # offset zero, then fetch a word from that SRV only on the else arm. + words = [0xbe910380,0xf4080608,0xfa000000, + 0xbf0c8015,0xbf840002,0xbe940381,0xbf820002, + 0xf420050c,0xfa000000] + text = run('root-branch',words+controlled) + for marker in ('cbufferLoadLegacy','rawBufferLoad','phi i32','storeVertexOutput'): + assert marker in text, marker + typed = [0xbe9e0317,0xbe9f0380, # copy the heap base; zero high address + 0x8715ff15,31,0x8f158515, # (root0[0] & 31) * descriptor size + 0xf408080f,0x2a000000, # load V# into s32:s35 + 0x7e020280,0xe0002000,0x80080a01] # v10 = formatted element v1 (index zero) + exported = program.copy() + exported[7] = 0x7e020d0a # v_cvt_f32_u32 v1,v10 + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1\nresource_heap 23') + run('unknown-heap-view',typed+exported,'selected GPU slot') + with layout.open('a') as meta: + meta.write('\nvalidate_uint_heap_reads') + text=run('typed-heap',typed+exported) + for marker in ('createHandleFromHeap', 'bufferLoad.i32', 'i32 261'): + assert marker in text, marker + overwritten = typed[:7] + [0xbea10380] + typed[7:] + run('overwritten-heap-word',overwritten+exported,'overwritten mesh heap descriptor') + # Three incoming scalar edges share one join. Distinct reaching + # values of s20 must all be linked to the post-join mesh position. + layout.write_text('mesh1 128 3 1 2 128 64\nconstants 21 0 1') + nested = [0xbf0c8015,0xbf840006,0xbf0c8115,0xbf840002, + 0xbe940381,0xbf820003,0xbe940382,0xbf820001,0xbe940383] + text=run('multi-edge',nested+controlled) + assert text.count('phi i32')>=2 + # Count active lanes in both halves of a guest wave using the + # logical workgroup index. The unsigned root parameter is the bound. + # Use source-built encodings for the group index and range test. + masks=[0x9380ff03 | (22<<16),0x40018,0x8f008616 | (28<<16), + 0xd7650000,0x000038c1,0xd7660000,0x000200c1, + 0x7da80015,0xbea8047e,0xbefe04c1,0xbe941028] + text=run('mesh-range-mask',masks+controlled) + assert 'unaryBits.i32' in text + # Two guest waves share their output counts in LDS. s34 and s35 + # are bounded by source masks on the dynamic root input. Lane 0 + # writes both LDS slots; wave 1 reads the same pair after rendezvous. + count_setup=[0x9380ff03|(22<<16),0x40018,0xbe880381,0xbe890380, + 0x87228315,0x87238115] + def movv(v,s): return 0x7e000200|(v<<17)|s + p_reg,v_reg=35,34 + allocate=[0xbf8a0000,0xbf008016,0xbf840010,0xbefe0408,0xbf880007, + movv(2,p_reg),movv(3,128),movv(4,v_reg),0xd8340000,0x0203, + 0xd8340004,0x0403,0xbefe04c1,0xbfa3ffe3,0xbf8a0000, + 0x8f088c00|p_reg,0x887c0008|(v_reg<<8),0xbf900009,0xbf82000d, + 0xbf8a0000,0xbefe0408,0xbf880009,movv(6,128),0xd8d80000, + (7<<24)|6,0xd8d80004,(6<<24)|6,0xbf8cc17f, + 0x7e000500|(p_reg<<17)|7,0xbf8cc07f,0x7e000500|(v_reg<<17)|6,0xbefe04c1] + text=run('group-counts',count_setup+allocate+program[3:]) + assert '@meshCounts' in text and 'setMeshOutputCounts(i32 168, i32 %' in text + bad_slot=allocate.copy() + bad_slot[25]=0xd8d80008 + run('wrong-count-slot',count_setup+bad_slot+program[3:],'unsupported mesh instruction') + overflow=count_setup.copy() + overflow[-1]=0x87238315 + run('too-many-primitives',overflow+allocate+program[3:],'exceeds declared range') + layout.write_text('mesh1 128 3 1 2 128 64\ntable 16 0') + run('mistyped-root',words+controlled,'root parameter kind') + layout.write_text('mesh1 128 3 1 2 128 64') + # A second allocation request/invalid maxima and unknown descriptors never emit partial bytecode. + run('second-allocation', program[:3]+[0xbf900009]+program[3:], 'requires one uniform') + run('over-limit', [program[0],0x1004]+program[2:], 'exceeds declared') + run('unknown-root', [0xf4080308,0xfa000b20]+program, 'verified guest root') + + # Lane zero of wave zero stores its group identifier, then both + # waves rendezvous before the other wave reads the word. + exchange = [0xbefe0481,0xbe88047e,0x870aff03,0x0f000000,0xbf850007,0x2c0a0a87, + 0x7e000280,0xd8340008,0x500,0xbfa3ffe3,0xbf8a0000,0xbf820004, + 0xbf8a0000,0x7e000280,0xd8d80008,0x05000000,0xbefe04c1,0x7e240505] + reads_group = program.copy() + reads_group[7] = 0x7e020c12 # v_cvt_f32_u32 v1,s18 uses the readfirstlane result + assert 'call i32 @dx.op.groupId.i32' in run('group',exchange+reads_group) + broken = exchange.copy() + broken[12] = 0xbf800000 # missing rendezvous on the reading wave + run('mismatched-barriers',broken+reads_group,'unsupported mesh instruction') + print('mesh allocation, indexed outputs, group exchange and negative controls passed') + + +if __name__ == '__main__': + main() diff --git a/tests/native_dot2_f32_f16_check.py b/tests/native_dot2_f32_f16_check.py new file mode 100644 index 0000000000..2c4847f517 --- /dev/null +++ b/tests/native_dot2_f32_f16_check.py @@ -0,0 +1,350 @@ +"""Direct DXIL v_dot2_f32_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import INLINE_F16_WORDS, PROLOGUE, inline_word +from native_scalar_lds_check import vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_DOT2_F32_F16 = 0x13 + + +def vop3p_dot2(dst, srcs, *, op_sel=0, op_sel_hi=0, neg_lo=0, neg_hi=0, clamp=0, op_sel_hi2=0): + s0, s1, s2 = srcs + w0 = (0xCC000000 | (OP_DOT2_F32_F16 << 16) | ((clamp & 1) << 15) | ((op_sel_hi2 & 1) << 14) | + ((op_sel & 7) << 11) | ((neg_hi & 7) << 8) | (dst & 0xFF)) + w1 = ((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def f32_to_bits(val): + return struct.unpack('<I', struct.pack('<f', val))[0] + + +def bits_to_f32(bits): + return struct.unpack('<f', struct.pack('<I', bits & 0xFFFFFFFF))[0] + + +def widen_f16(half_bits): + return struct.unpack('<e', struct.pack('<H', half_bits & 0xFFFF))[0] + + +def f32_inline_bits(enc): + f32_inline = { + 240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000, + 248: 0x3E22F983, + } + if enc in f32_inline: + return f32_inline[enc] + if 128 <= enc <= 192: + return enc - 128 + if 193 <= enc <= 208: + return (192 - enc) & 0xFFFFFFFF + raise ValueError(enc) + + +def is_nan_f32(bits): + return (bits & 0x7FFFFFFF) > 0x7F800000 + + +def same_f32(got, want): + if is_nan_f32(want): + return is_nan_f32(got) + return got == want + + +def eval_dot2(raw_words, *, op_sel=0, op_sel_hi=0, neg_lo=0, neg_hi=0, clamp=0): + def term(word, selector, neg): + half = (word >> 16) if selector else (word & 0xFFFF) + if neg: + half ^= 0x8000 + return widen_f16(half) + + a0 = term(raw_words[0], op_sel & 1, bool(neg_lo & 1)) + b0 = term(raw_words[1], (op_sel >> 1) & 1, bool(neg_lo & 2)) + a1 = term(raw_words[0], op_sel_hi & 1, bool(neg_hi & 1)) + b1 = term(raw_words[1], (op_sel_hi >> 1) & 1, bool(neg_hi & 2)) + c_bits = raw_words[2] ^ (0x80000000 if (neg_lo & 4) else 0) + c = bits_to_f32(c_bits) + + p0 = bits_to_f32(f32_to_bits(a0 * b0)) + p1 = bits_to_f32(f32_to_bits(a1 * b1)) + s01 = bits_to_f32(f32_to_bits(p0 + p1)) + res = bits_to_f32(f32_to_bits(s01 + c)) + if clamp: + res = 0.0 if (math.isnan(res) or res <= 0.0) else (1.0 if res >= 1.0 else res) + return f32_to_bits(res) + + +@dataclass(frozen=True) +class Case: + name: str + srcs: tuple + vals: tuple + op_sel: int = 0 + op_sel_hi: int = 3 + neg_lo: int = 0 + neg_hi: int = 0 + clamp: int = 0 + op_sel_hi2: int = 0 + pixel_safe: bool = True + + def raw_words(self): + words = [] + for idx, (s, v) in enumerate(zip(self.srcs, self.vals)): + if s < 128 or s >= 255: + words.append(v & 0xFFFFFFFF) + elif idx < 2: + words.append(inline_word(s)) + else: + words.append(f32_inline_bits(s)) + return tuple(words) + + def expected(self): + return eval_dot2(self.raw_words(), op_sel=self.op_sel, op_sel_hi=self.op_sel_hi, + neg_lo=self.neg_lo, neg_hi=self.neg_hi, clamp=self.clamp) + + +def p16(lo, hi): + return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) + + +def all_cases(): + return [ + # 1. Basic VGPR dot product with packed halves and binary32 accumulator. + Case('basic_vgpr', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(0.5))), + # 2. All op_sel / op_sel_hi cross-lane combinations + LLVM-style op_sel_hi[2]=1. + Case('opsel_swap', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(1.25)), + op_sel=0b10, op_sel_hi=0b01, op_sel_hi2=1), + Case('opsel_broadcast_lo', (257, 258, 259), (p16(0x3C00, 0x7E00), p16(0x4200, 0x7E00), f32_to_bits(2.0)), + op_sel=0b00, op_sel_hi=0b00), + Case('opsel_broadcast_hi', (257, 258, 259), (p16(0x7E00, 0x3C00), p16(0x7E00, 0x4000), f32_to_bits(-0.5)), + op_sel=0b11, op_sel_hi=0b11), + # 3. Negate modifiers: neg_lo[0], neg_lo[1], neg_lo[2] (f32 src2), neg_hi[0], neg_hi[1]. + Case('neg_pair0', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(10.0)), + neg_lo=0b001), + Case('neg_pair0_both_and_c', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(10.0)), + neg_lo=0b111), + Case('neg_pair1_hi0_hi1', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(1.0)), + neg_hi=0b10), + Case('neg_all_five', (257, 258, 259), (p16(0x3C00, 0x4000), p16(0x4200, 0x4400), f32_to_bits(3.0)), + neg_lo=0b111, neg_hi=0b11), + # 4. Clamp / saturate: < 0 -> +0.0, interior (0, 1), > 1 -> 1.0, exact boundary 0.0 / 1.0. + Case('clamp_negative', (257, 258, 259), (p16(0xBC00, 0x3C00), p16(0x4000, 0x3800), f32_to_bits(-2.0)), + clamp=1), + Case('clamp_above_one', (257, 258, 259), (p16(0x4000, 0x4000), p16(0x4000, 0x4000), f32_to_bits(0.5)), + clamp=1), + Case('clamp_interior', (257, 258, 259), (p16(0x3800, 0x3400), p16(0x3800, 0x3C00), f32_to_bits(0.125)), + clamp=1), + Case('clamp_nan_to_zero', (257, 258, 259), (p16(0x7E00, 0x3C00), p16(0x3C00, 0x3C00), f32_to_bits(0.5)), + clamp=1, pixel_safe=False), + # 5. Inline binary16 float constants on src0/src1 (including zero high half 242, 245, 248) and f32 src2 inline. + Case('inline_f16_lo_242_hi_zero', (242, 258, 240), (0, p16(0x4000, 0x4400), 0)), + Case('inline_f16_245_248', (245, 248, 259), (0, 0, f32_to_bits(1.0)), op_sel=0b00, op_sel_hi=0b11), + Case('inline_src2_243_neg_c', (257, 258, 243), (p16(0x3C00, 0x3C00), p16(0x3C00, 0x4000), 0), neg_lo=0b100), + # 6. Inline integer constants on src0/src1 (129=subnormal 2^-24, 192=64 subnormal) & src2 (128=+0, 129=2^-149). + Case('inline_int_129_192_128', (129, 192, 128), (0, 0, 0)), + Case('inline_int_src2_128_zero', (257, 258, 128), (p16(0x3C00, 0x3C00), p16(0x4000, 0x3800), 0)), + Case('inline_int_src2_129', (257, 258, 129), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0)), + Case('vgpr_src2_subnormal_pos', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x00000001)), + Case('vgpr_src2_subnormal_neg', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x80400000)), + Case('vgpr_src2_subnormal_clamp_pos', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x00000001), clamp=1), + Case('vgpr_src2_subnormal_clamp_neg', (257, 258, 259), (p16(0x0000, 0x0000), p16(0x0000, 0x0000), 0x80400000), clamp=1), + # 7. SGPR and 32-bit literal sources. + Case('sgpr_sources', (10, 11, 12), (p16(0x3C00, 0xC000), p16(0x4200, 0x3800), f32_to_bits(0.75))), + Case('literal_src0', (255, 258, 259), (p16(0x4000, 0x3C00), p16(0x3800, 0x4200), f32_to_bits(-1.0))), + Case('literal_src2', (257, 258, 255), (p16(0x3C00, 0x3800), p16(0x3C00, 0x4000), f32_to_bits(3.25))), + # 8. Binary16 subnormals, signed zeros, infinity, max finite, and NaN propagation. + Case('subnormal_f16_exact', (257, 258, 259), (p16(0x0001, 0x03FF), p16(0x0001, 0x7BFF), f32_to_bits(0.0))), + Case('signed_zero_keep', (257, 258, 259), (p16(0x8000, 0x8000), p16(0x3C00, 0x3C00), f32_to_bits(-0.0)), + pixel_safe=False), + Case('signed_zero_cancel_pos', (257, 258, 259), (p16(0x3C00, 0x3C00), p16(0xBC00, 0x3C00), f32_to_bits(-0.0)), + pixel_safe=False), + Case('inf_propagation', (257, 258, 259), (p16(0x7C00, 0x3C00), p16(0x3C00, 0x3C00), f32_to_bits(-4.0)), + pixel_safe=False), + Case('nan_propagation', (257, 258, 259), (p16(0x7E01, 0x3C00), p16(0x3C00, 0x3C00), f32_to_bits(1.0)), + pixel_safe=False), + ] + + +def emit_case(c: Case): + code = [] + lit_tail = [] + for idx, (s, v) in enumerate(zip(c.srcs, c.vals)): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3p_dot2(4, c.srcs, op_sel=c.op_sel, op_sel_hi=c.op_sel_hi, + neg_lo=c.neg_lo, neg_hi=c.neg_hi, clamp=c.clamp, op_sel_hi2=c.op_sel_hi2) + code += lit_tail + return code + + +def compute_program(cases): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + # Conditional branch + s_denorm_mode makes half_mode_known == false for v_dot2_f32_f16. + cond_mode = [0xBF840001, 0xBFA5000F, 0xBF810000] # s_cbranch_scc0 +1; s_denorm_mode 15 + return [ + # Reserved OP_SEL[2] and NEG_HI[2] bits on v_dot2_f32_f16. + (vop3p_dot2(4, (257, 258, 259), op_sel=0b100) + [0xBF810000], 'unsupported v_dot2_f32_f16 encoding'), + (vop3p_dot2(4, (257, 258, 259), neg_hi=0b100) + [0xBF810000], 'unsupported v_dot2_f32_f16 encoding'), + # Special scalar sources refused on src0, src1, src2. + (vop3p_dot2(4, (106, 258, 259)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + (vop3p_dot2(4, (257, 124, 259)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + (vop3p_dot2(4, (257, 258, 126)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + (vop3p_dot2(4, (257, 258, 253)) + [0xBF810000], 'unsupported v_dot2_f32_f16 source'), + # Unsupported binary16 denormal flush (s_denorm_mode 3) or rounding mode (s_round_mode 4). + ([0xBFA50003] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported binary16 rounding or denormal mode'), + ([0xBFA40004] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported binary16 rounding or denormal mode'), + # Unsupported binary32 denormal flush (s_denorm_mode 0xC) refused via mode gate. + ([0xBFA5000C] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported compute control instruction s_denorm_mode'), + # Dynamic conditional mode change makes half_mode_known false via half_binary tracking. + (cond_mode[:-1] + vop3p_dot2(4, (257, 258, 259)) + [0xBF810000], + 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code, want = compute_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'dot2-f32-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_f32(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_dot2_f32_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'fmul float' in dump and 'fadd float' in dump and 'unary.f32(i32 7,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_dot2_f32_f16 controls: compiled {len(want)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, w in enumerate(want): + expected[head + idx] = w + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same_f32(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_dot2_f32_f16 compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'dot2-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected() for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_dot2_f32_f16 pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dot2c_f32_f16_check.py b/tests/native_dot2c_f32_f16_check.py new file mode 100644 index 0000000000..3c0160a2f5 --- /dev/null +++ b/tests/native_dot2c_f32_f16_check.py @@ -0,0 +1,283 @@ +"""Direct DXIL VOP2 v_dot2c_f32_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dot2_f32_f16_check import bits_to_f32, f32_to_bits, p16, same_f32, widen_f16 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1, vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_DOT2C_F32_F16 = 0x02 +ALL_EXEC = 0xFFFFFFFF + + +def vop2_dot2c(dst, src0, vsrc1): + assert 256 <= vsrc1 < 512, vsrc1 + return ((OP_DOT2C_F32_F16 << 25) | ((dst & 0xFF) << 17) | (((vsrc1 - 256) & 0xFF) << 9) | (src0 & 0x1FF)) + + +def vop3_dot2c_e64(dst, src0, vsrc1, *, clamp=0): + return [ + 0xD5020000 | ((clamp & 1) << 15) | (dst & 0xFF), + ((vsrc1 & 0x1FF) << 9) | (src0 & 0x1FF), + ] + + +def eval_dot2c(s0_word, s1_word, acc_bits): + a0 = widen_f16(s0_word & 0xFFFF) + b0 = widen_f16(s1_word & 0xFFFF) + a1 = widen_f16((s0_word >> 16) & 0xFFFF) + b1 = widen_f16((s1_word >> 16) & 0xFFFF) + p0 = bits_to_f32(f32_to_bits(a0 * b0)) + p1 = bits_to_f32(f32_to_bits(a1 * b1)) + s01 = bits_to_f32(f32_to_bits(p0 + p1)) + c = bits_to_f32(acc_bits) + return f32_to_bits(s01 + c) + + +@dataclass(frozen=True) +class Case: + name: str + steps: tuple + acc: int + exec_mask: int = ALL_EXEC + alias: str = 'none' + pixel_safe: bool = True + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return self.acc & 0xFFFFFFFF + cur = self.acc & 0xFFFFFFFF + for s0, v0, v1 in self.steps: + if self.alias == 'src0': + w0 = cur + elif s0 < 128 or s0 >= 255: + w0 = v0 & 0xFFFFFFFF + else: + w0 = inline_word(s0) + w1 = cur if self.alias == 'src1' else (v1 & 0xFFFFFFFF) + cur = eval_dot2c(w0, w1, cur) + return cur + + +def all_cases(): + return [ + # 1. Basic VGPR accumulate with distinct low/high products. + Case('vgpr_basic', ((262, p16(0x3C00, 0x4000), p16(0x4200, 0x4400)),), f32_to_bits(0.5)), + # 2. Opposite products cancel to +0.0, preserving binary32 accumulator. + Case('vgpr_cancel_to_acc', ((262, p16(0x3C00, 0x4000), p16(0xC000, 0x3C00)),), f32_to_bits(1.25)), + # 3. Back-to-back accumulation in the same destination VGPR. + Case('multi_accumulate', + ((262, p16(0x3C00, 0x3800), p16(0x4000, 0x4000)), + (262, p16(0xBC00, 0x4000), p16(0x3C00, 0x4200))), + f32_to_bits(0.25)), + # 4. Destination VGPR aliased with src0 or vsrc1 (read both as f16x2 input and f32 acc). + Case('vgpr_dst_alias_src0', ((260, 0, p16(0x4000, 0x4200)),), p16(0x0000, 0x3C00), alias='src0'), + Case('vgpr_dst_alias_src1', ((262, p16(0x4200, 0x3C00), 0),), p16(0x3800, 0x4000), alias='src1'), + # 5. SGPR and 32-bit literal src0 encodings. + Case('sgpr_src0', ((10, p16(0x3C00, 0xC000), p16(0x4200, 0x3800)),), f32_to_bits(0.75)), + Case('literal_src0', ((255, p16(0x4000, 0x3C00), p16(0x3800, 0x4200)),), f32_to_bits(-1.0)), + # 6. Inline binary16 float constants (0.5, 1.0, -1.0) and inline integer 0. + Case('inline_f16_240', ((240, 0, p16(0x4000, 0x4400)),), f32_to_bits(1.5)), + Case('inline_f16_242', ((242, 0, p16(0x4000, 0x4400)),), f32_to_bits(2.0)), + Case('inline_f16_243', ((243, 0, p16(0x3C00, 0x4000)),), f32_to_bits(3.0)), + Case('inline_int_128', ((128, 0, p16(0x4000, 0x4400)),), f32_to_bits(-2.5)), + # 7. Binary16 subnormal operands (2^-24 and max subnormal). + Case('half_subnormal_src0', ((262, p16(0x0001, 0x03FF), p16(0x0001, 0x7BFF)),), f32_to_bits(0.0)), + # 8. Binary32 subnormal accumulators: preserved when sum == 0, flushed/rounded under nonzero sum. + Case('f32_subnormal_acc_pos', ((262, p16(0x0000, 0x0000), p16(0x0000, 0x0000)),), 0x00000001), + Case('f32_subnormal_acc_neg', ((262, p16(0x0000, 0x0000), p16(0x0000, 0x0000)),), 0x80400000), + Case('f32_subnormal_acc_nonzero_dot', ((262, p16(0x3C00, 0x0000), p16(0x3C00, 0x0000)),), 0x00000001), + # 9. Partial EXEC mask: odd lanes update vdst, even lanes preserve pre-existing vdst accumulator. + Case('partial_exec_odd', ((262, p16(0x3C00, 0x4000), p16(0x4000, 0x4200)),), + 0x40A00000, exec_mask=0xAAAAAAAA, pixel_safe=False), + # 10. Signed zero, infinity, and NaN propagation. + Case('signed_zero_keep', ((262, p16(0x8000, 0x8000), p16(0x3C00, 0x3C00)),), + f32_to_bits(-0.0), pixel_safe=False), + Case('inf_propagation', ((262, p16(0x7C00, 0x3C00), p16(0x3C00, 0x3C00)),), + f32_to_bits(-4.0), pixel_safe=False), + Case('nan_propagation', ((262, p16(0x7E01, 0x3C00), p16(0x3C00, 0x3C00)),), + f32_to_bits(1.0), pixel_safe=False), + ] + + +def emit_case(c: Case): + code = F.mov(4, c.acc) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + for s0, v0, v1 in c.steps: + lit_tail = [] + vsrc1 = 260 if c.alias == 'src1' else 261 + if c.alias != 'src1': + code += F.mov(vsrc1 - 256, v1) + src0 = 260 if c.alias == 'src0' else s0 + if c.alias != 'src0': + if src0 >= 256: + code += F.mov(src0 - 256, v0) + elif src0 <= 105: + code += F.smov(src0, v0) + elif src0 == 255: + lit_tail = [v0] + code.append(vop2_dot2c(4, src0, vsrc1)) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = [vop2_dot2c(4, 262, 261), 0xBF810000] + return [ + # VOP3 _e64 form of v_dot2c_f32_f16. + (vop3_dot2c_e64(4, 262, 261) + [0xBF810000], 'unsupported v_dot2c_f32_f16 encoding'), + # DPP16, DPP8, and SDWA forms. + ([vop2_dot2c(4, 250, 261), 0xFF00E406, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_dot2c(4, 233, 261), 0xC6886806, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_dot2c(4, 249, 261), 0x06060606, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar sources refused on src0 (vcc_lo). + ([vop2_dot2c(4, 106, 261), 0xBF810000], 'unsupported v_dot2c_f32_f16 source'), + # Unsupported binary16 rounding/denorm, binary32 denorm flush, and conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA5000C] + plain, 'unsupported compute control instruction s_denorm_mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'dot2c-f32-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_f32(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_dot2c_f32_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'fmul float' in dump and 'fadd float' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_dot2c_f32_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same_f32(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_dot2c_f32_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'dot2c-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected(lane=0) for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_dot2c_f32_f16 pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dot4c_check.py b/tests/native_dot4c_check.py new file mode 100644 index 0000000000..da68910efa --- /dev/null +++ b/tests/native_dot4c_check.py @@ -0,0 +1,109 @@ +"""Direct compute VOP2 signed byte dot-accumulate lowering and replay.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + + +DOT4C = 0x0D +ALL = 0xFFFFFFFF +EVEN = 0x55555555 +SENTINEL = 0x69696969 +CASES = ( + # Name, encoded src0, extension words, packed src1, accumulator base, dot, EXEC + ("literal", 255, (0xFBF201F7,), 0x04030201, 100, -69, ALL), + ("sgpr", 10, (), 0x80808080, 0x7FFFFFF0, 65536, EVEN), + ("inline", 193, (), 0x01020304, 64, -10, ALL), + ("vgpr_dst_alias", 259, (), 0x7F000000, 0x80000000, -16256, ALL), +) + + +def program(case, *, modifier=None): + name, src0, extension, b, base, _, active = case + # Group IDs (0,0,0) and (1,0,0), 32 lanes each. UAV u0 starts with + # eight guard words, then one consecutive 32-word row per group. + code = [ + sop1(3, 126, 193), # EXEC_LO = all lanes + sop1(3, 20, 4), sop1(3, 21, 128), # s[20:21] = resource table base + 0xF408080A, 0xFA000020, # load s[32:35] for u0 + scalar(0x1E, 7, 5, 135), # s7 = group_id.x * 128 bytes + vop2(0x1A, 8, 130, 0), # v8 = local lane * 4 bytes + vop2(0x25, 8, 7, 8), # v8 += s7 + vmove(2, 255), b, + vop2(0x25, 3, 255, 0), base, # v3 = accumulator base + local lane + 0xBF8CC07F, # wait for descriptor load + ] + if name == "sgpr": + code += [sop1(3, 10, 255), 0x80808080] + code += [sop1(3, 126, 255), active] + if modifier == "dpp": + src0, extension = 250, (0xFF00E403,) # v3, identity quad_perm, full masks + elif modifier == "sdwa": + src0, extension = 249, (0x06060603,) # v3, DWORD selectors + return code + [ + vop2(DOT4C, 3, src0, 2), *extension, + sop1(3, 126, 193), # restore EXEC before readback + 0xE0701000, 0x80080308, # buffer_store_dword v3, v8, s[32:35], 0 offen + 0xBF810000, + ] + + +def ir(cli, sdk, work, root): + for case, modifier, error in ( + *((case, None, None) for case in CASES), + (CASES[-1], "dpp", "unsupported DPP arithmetic"), + (CASES[-1], "sdwa", "unimplemented direct SDWA operand profile"), + ): + marker = request(work, root, program(case, modifier=modifier)) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr, (modifier, result.stdout, result.stderr) + assert not output.exists(), output + else: + assert result.returncode == 0 and output.is_file(), (case[0], result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, + text=True, check=True).stdout + assert dump.count("@dx.op.dot4AddPacked.i32(i32 163,") == 1, (case[0], dump) + print("signed VOP2 dot-accumulate DXIL verified for four source encodings; DPP and SDWA refused") + return 0 + + +def hardware(replay, sdk, work, root): + for case in CASES: + name, _, _, _, base, dot, active = case + marker = request(work, root, program(case)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + row = tuple((base + lane + (dot if (active >> lane) & 1 else 0)) & ALL + for lane in range(32)) + expected = (SENTINEL,) * 8 + row * 2 + (SENTINEL,) * (2064 - 72) + actual = struct.unpack("<2064I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, f"{name} word {index}: got {got:08x}, expected {want:08x}" + print(f"{name}: 64 results and all guards matched") + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"ir": ir, "hardware": hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp8_check.py b/tests/native_dpp8_check.py new file mode 100644 index 0000000000..d3679ab26c --- /dev/null +++ b/tests/native_dpp8_check.py @@ -0,0 +1,97 @@ +"""Wave32 hardware readback for direct compute DPP8.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +ADD, MIN, MAX = 0x03, 0x0F, 0x10 +SWAP = (4, 5, 6, 7, 0, 1, 2, 3) +ASYMMETRIC = (7, 0, 3, 1, 6, 2, 5, 4) +ALL = 0xFFFFFFFF +SPARSE = 0x55555555 +SENTINEL = 0x69696969 + + +def program(op, selectors, active, fi): + # Each workgroup writes 32 words, starting after eight guard words. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 135), vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8), + vop2(0x25, 9, 145, 0), 0x7E000000 | 9 << 17 | 6 << 9 | 265] + # Seed v9 under full EXEC and alias both inputs with the destination. + # Restore full EXEC before storing so disabled destinations are visible. + src0 = 234 if fi else 233 + instruction = vmove(9, src0) if op is None else vop2(op, 9, src0, 9) + control = 9 | sum(peer << (8 + 3 * lane) for lane, peer in enumerate(selectors)) + return words + [sop1(3, 126, 255), active, instruction, control, + sop1(3, 126, 193), 0xE0701000, 0x80080908, 0xBF810000] + + +def reference(op, selectors, active, fi): + initial = list(range(17, 49)) + result = initial.copy() + for start in range(0, 32, 8): + for offset, selection in enumerate(selectors): + lane, peer = start + offset, start + selection + if not active & (1 << lane): + continue + source = initial[peer] if fi or active & (1 << peer) else 0 + if op == ADD: + result[lane] = source + initial[lane] + elif op == MIN: + result[lane] = min(source, initial[lane]) + elif op == MAX: + result[lane] = max(source, initial[lane]) + else: + result[lane] = source + return struct.unpack("<32I", struct.pack("<32f", *result)) + + +def hardware(replay, sdk, work, root): + # Unique values in all four octets expose a wrong group base. In each + # sparse case lane 0 selects disabled lane 7, exposing ignored FI. + cases = ( + ("min swap", MIN, SWAP, ALL, False), + ("add swap", ADD, SWAP, ALL, False), + ("max swap", MAX, SWAP, ALL, False), + ("mov asymmetric", None, ASYMMETRIC, ALL, False), + ("add sparse without FI", ADD, ASYMMETRIC, SPARSE, False), + # min(0, x) differs from the old destination, so it separates "zero" from "keep". + ("min sparse without FI", MIN, ASYMMETRIC, SPARSE, False), + ("add sparse with FI", ADD, ASYMMETRIC, SPARSE, True), + ) + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x8A) + for name, op, selectors, active, fi in cases: + marker = write_request(work, program(op, selectors, active, fi), root, sa) + output = work / "out.bin" + run = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if run.returncode == 77: + return 77 + run.check_returncode() + lanes = reference(op, selectors, active, fi) + expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 72) + actual = struct.unpack("<2064I", output.read_bytes()) + for index, (observed, wanted) in enumerate(zip(actual, expected)): + assert observed == wanted, (name, index, hex(observed), hex(wanted)) + print(f"{name}: 64 results and guards matched") + return 0 + + +def main(replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return hardware(replay, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp_mirror_check.py b/tests/native_dpp_mirror_check.py new file mode 100644 index 0000000000..f009c67489 --- /dev/null +++ b/tests/native_dpp_mirror_check.py @@ -0,0 +1,149 @@ +"""GPU differential for source-built, direct-DXIL guest row mirrors.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import patched_pixel, vertex +from native_scalar_lds_check import scalar, sop1, vmove + + +def vop2(op, dst, src0, src1): + return op << 25 | dst << 17 | src1 << 9 | src0 + + +def compute_program(control, active): + # v1 holds a unique value even after guest EXEC is narrowed. The DPP + # src0 aliases the destination. A distinct local src1 distinguishes + # suppress-write from adding zero when the mirror points outside EXEC. + return [sop1(3,20,4), sop1(3,21,128), 0xf4080000 | 32 << 6 | 10, 0xfa000020, + scalar(0x1e,7,5,135), vop2(0x1a,8,130,0), vop2(0x25,8,7,8), + vop2(0x25,1,145,0), vop2(0x25,2,148,0), sop1(3,126,255), active, + vop2(0x25,1,250,2), 0xff000001 | control, sop1(3,126,193), + 0xe0701000, 0x80080108, 0xbf810000] + + +def pixel_program(start, half, control): + # Explicitly populate a guest register array even when the rasterizer + # schedules fewer than eight pixels. Read back four individual guest lanes. + program = [sop1(0x25,62,193), vmove(17,128)] + for lane in range(16): + program += [0xd7610011, (129+lane) | ((128+start+lane) << 9)] + program += [vmove(17,250), 0xff040011 | control << 8] + for col in range(4): + program += [0xd7600000 | col, 273 | ((128+start+4*half+col) << 9)] + program += [sop1(4,126,62)] + program += [0x7e000c00 | col << 17 | col for col in range(4)] + return patched_pixel(len(program), program, export=(0xf800180f,0x03020100)) + + +def reduction_program(): + # Seed two guest wave64 halves differently, including unsigned values + # above INT_MAX. Inspect both the intermediate 32-lane extrema and + # the 64-lane extrema after the readlane/broadcast step. + program = [sop1(0x25,62,193), vmove(17,144)] + for lane, value in ((12,1),(19,27),(33,3),(60,39)): + program += [0xd7610011, (128+value) | ((128+lane) << 9)] + program += [0xd7610011, 193 | (155 << 9)] # lane 27 holds UINT_MAX + for output, op in enumerate((0x13,0x14)): + program += [vmove(18,273)] + for control in (0xb1,0x4e,0x141,0x140): + program += [vop2(op,18,250,18), 0xff040012 | (control << 8)] + program += [0xd7780013,274 | 128 << 9 | 128 << 18, vop2(op,18,274,19), + 0xd7600000 | output,274 | 191 << 9, + 0xd7600004,274 | 128 << 9,vop2(op,18,4,18), + 0xd7600002 | output,274 | 191 << 9] + # Keep the low byte of each result so the uint max is observable as 255. + program += [sop1(4,126,62)] + for col in range(4): + program += [vmove(col,col),vop2(0x1b,col,255,col),255,0x7e000c00 | col << 17 | (256+col)] + return patched_pixel(len(program),program,export=(0xf800180f,0x03020100)) + + +def vertex_program(last_id, branchless=False): + program = [vmove(1,243),vmove(2,243),vmove(3,128),vmove(4,242)] + # Start at (-1,-1). Separate masked arms move vertices 1 and 2 to + # (3,-1) and (-1,3). Each contains a scalar branch over the literal move. + for reg, vertex_id in ((1,1),(2,last_id)): + if branchless: + program += [sop1(4,8,126),0xbf8cc07f,0x7d240080 | vertex_id, + vmove(reg,255),0x40400000,0x8afe7e08,vmove(reg,243),sop1(4,126,8)] + else: + program += [0x7d040080 | vertex_id, 0xbe88246a, 0xbf880004, + 0xbf008080,0xbf840002,vmove(reg,255),0x40400000,0xbefe0408] + return vertex(program=program+[0xf80008cf,0x04030201,0xbf810000]) + + +def main(cli, replay, raster, sdk): + reverse = (7,6,5,4,3,2,1,0) + sentinel = 0x69696969 + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + shader = work/"fixture.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"\n' + 'float4 vs(uint id:SV_VertexID):SV_Position {' + 'return float4(id==1?3:-1,id==2?3:-1,0,1);}') + dxc = Path(sdk)/"dxc.exe" + root, vs = work/"root", work/"vs.cso" + subprocess.run([dxc,"-T","rootsig_1_1","-E","SIG","-Fo",root,shader],check=True) + subprocess.run([dxc,"-T","vs_6_6","-E","vs","-Fo",vs,shader],check=True) + sa = struct.pack("<7I",0,0,0,32 | 1 << 16,1 | (1 << 20),0,0x8a) + sparse = 0x955ad3b6 + for mask, active, fi, zero in ((7,0xffffffff,1,0), (15,0xffffffff,1,0), + (7,sparse,1,0), (7,sparse,0,0), (7,sparse,0,1)): + ctrl = ((0x141 if mask == 7 else 0x140) << 8) | fi << 18 | zero << 19 + marker = write_request(work,compute_program(ctrl, active),root.read_bytes(),sa) + dest = work/"out.bin" + result = subprocess.run([replay,sdk,marker,work/"cache","0",dest,"--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = [sentinel]*2064 + for lane in range(32): + peer = lane // (mask+1) * (mask+1) + mask - lane % (mask+1) + own, value = lane+20, lane+17 + if active & (1 << lane): + if fi or active & (1 << peer): value = own + peer + 17 + elif zero: value = own + for group in range(2): + expected[8+group*32+lane] = value + actual = struct.unpack("<2064I",dest.read_bytes()) + assert list(actual) == expected, (mask, fi, zero, actual[8:40], expected[8:40]) + print(f"CS xor={mask} EXEC={active:08x} FI={fi} BC={zero}: 64 results and guards matched") + for start, half, ctrl in ((0,0,0x141),(0,1,0x141),(32,0,0x141),(32,1,0x141),(0,0,0x140)): + src, ps = work/"pixel.fssm", work/"pixel.cso" + src.write_bytes(pixel_program(start,half,ctrl)) + subprocess.run([cli,sdk,work/"cache","gfx1013-container-ps",src,ps],check=True) + expected = [1 + x for x in reverse[4*half:4*half+4]] + reference = work/"pixels.bin" + reference.write_bytes(struct.pack("<4f",*expected)*8) + result = subprocess.run([raster,"hardware","--startup-pixel-words",vs,ps,"4","2",reference], + capture_output=True,text=True) + if result.returncode == 77: + return 77 + if ctrl == 0x140: + assert result.returncode == 1 and "8 of 8 pixels differ" in result.stderr, result.stderr + elif result.returncode: + raise AssertionError(result.stderr) + print(f"PS guest lanes {start+4*half}..{start+4*half+3}: " + + (f"matched {expected}" if ctrl == 0x141 else "wrong full-row control differed at all 8 pixels")) + src.write_bytes(reduction_program()) + subprocess.run([cli,sdk,work/"cache","gfx1013-container-ps",src,ps],check=True) + reference.write_bytes(struct.pack("<4f",3,39,1,255)*8) + subprocess.run([raster,"hardware","--startup-pixel-words",vs,ps,"4","2",reference],check=True) + print("PS unsigned min/max, two 32-lane halves and final wave64 reduction matched [3,39,1,255]") + for branchless,last_id in ((False,2),(False,1),(True,2),(True,1)): + src.write_bytes(vertex_program(last_id,branchless)) + subprocess.run([cli,sdk,work/"cache","gfx1013-container-vs",src,vs],check=True) + result = subprocess.run([raster,"hardware","--startup-pixel-words",vs,ps,"4","2",reference], + capture_output=True,text=True) + if last_id == 2: result.check_returncode() + else: assert result.returncode == 1 and "8 of 8 pixels differ" in result.stderr, result.stderr + print("Translated masked VS and reduction PS matched 8 pixels; collapsed triangle lost all 8") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp_quad_check.py b/tests/native_dpp_quad_check.py new file mode 100644 index 0000000000..8f5ec48551 --- /dev/null +++ b/tests/native_dpp_quad_check.py @@ -0,0 +1,132 @@ +"""Direct compute DPP16 quad_perm readback and compile-only refusals.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +OR, ADD, SUBREV = 0x1C, 0x03, 0x05 +SWAP = (1, 0, 3, 2) +ALL = 0xFFFFFFFF +SPARSE = ALL ^ (1 << 1) +SENTINEL = 0x69696969 + + +def compute_program(op, pattern, active=ALL, fi=False, bound_zero=False): + control = 0xFF000001 | pattern << 8 | fi << 18 | bound_zero << 19 + # Reuse the mirror fixture's table load and addressing ABI. Two groups + # write 32 consecutive words each, after eight guard words. + program = [sop1(3, 20, 4), sop1(3, 21, 128), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1e, 7, 5, 135), vop2(0x1a, 8, 130, 0), vop2(0x25, 8, 7, 8), + vop2(0x25, 1, 145, 0)] + if op == OR: + program += [vmove(2, 192)] # inline integer 64 + else: + program += [vop2(0x25, 2, 148, 0), + 0x7E000000 | 1 << 17 | 6 << 9 | 257, # v_cvt_f32_u32 v1, v1 + 0x7E000000 | 2 << 17 | 6 << 9 | 258] # v_cvt_f32_u32 v2, v2 + # Seed both registers under full EXEC, alias src0 with dst, and restore + # EXEC before storing so suppressed writes are visible in the readback. + return program + [sop1(3, 126, 255), active, + vop2(op, 1, 250, 2), control, sop1(3, 126, 193), + 0xE0701000, 0x80080108, 0xBF810000] + + +def reference(op, selection, active, fi, bound_zero): + initial = list(range(17, 49)) + enabled = [(active >> lane) & 1 for lane in range(32)] + result = initial.copy() + for base in range(0, 32, 4): + for offset, source in enumerate(selection): + lane, peer = base + offset, base + source + if not enabled[lane]: + continue + if fi or enabled[peer]: + src0 = initial[peer] + elif bound_zero: + src0 = 0 + else: + continue + if op == OR: + result[lane] = src0 | 64 + elif op == ADD: + result[lane] = src0 + (lane + 20) + else: + result[lane] = (lane + 20) - src0 + if op != OR: + return struct.unpack("<32I", struct.pack("<32f", *result)) + return tuple(result) + + +def request(work, root, program, threads=32): + sa = struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1 | (1 << 20), 0, 0x8A) + return write_request(work, program, root, sa) + + +def controls(cli, sdk, work, root): + for pattern, threads, error in ( + (0xB1, 32, None), + (0x150, 32, "unsupported DPP lane selection"), # row_share:0 + (0xB1, 30, "DPP quad_perm needs a thread count divisible by four")): + marker = request(work, root, compute_program(OR, pattern), threads) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error is None: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + else: + assert result.returncode and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + print(error) + return 0 + + +def hardware(replay, sdk, work, root): + # Manual mutants that must fail: read the permutation in reversed lane + # order (rotation), or ignore BOUND_CTRL (sparse EXEC add with BC=1). + cases = ( + ("or swap", OR, SWAP, ALL, False, False), + ("add swap", ADD, SWAP, ALL, False, False), + ("subrev broadcast", SUBREV, (0, 0, 0, 0), ALL, False, False), + ("or identity", OR, (0, 1, 2, 3), ALL, False, False), + ("or rotation", OR, (1, 2, 3, 0), ALL, False, False), + ("add disabled source, zero", ADD, SWAP, SPARSE, False, True), + ("add disabled source, preserve", ADD, SWAP, SPARSE, False, False), + ("add disabled source, fetch", ADD, SWAP, SPARSE, True, False), + ) + for name, op, selection, active, fi, bound_zero in cases: + pattern = sum(source << (2 * lane) for lane, source in enumerate(selection)) + marker = request(work, root, compute_program(op, pattern, active, fi, bound_zero)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + lanes = reference(op, selection, active, fi, bound_zero) + expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 72) + actual = struct.unpack("<2064I", output.read_bytes()) + mismatch = next((i for i, pair in enumerate(zip(actual, expected)) if pair[0] != pair[1]), None) + assert mismatch is None, (name, mismatch, actual[mismatch], expected[mismatch]) + print(f"{name}: 64 results and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dpp_row_check.py b/tests/native_dpp_row_check.py new file mode 100644 index 0000000000..ac8084ef71 --- /dev/null +++ b/tests/native_dpp_row_check.py @@ -0,0 +1,147 @@ +"""Direct compute DPP16 row shifts and rotates with sparse guest EXEC.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1 + + +SENTINEL = 0x69696969 +ACTIVE = 0xFFFFFEFD # Disable physical lanes 1 and 8 in each wave32. + +# VOP1/VOP2 src0=250. DPP word: VGPR 7:0, DPP_CTRL 16:8, FI 18, +# BOUND_CTRL 19, bank mask 27:24, row mask 31:28. +# Keep the CPU model's parameters separate from these hand-encoded words. +CASES = ( + ("mov", "shl", 1, False, False, 0x7E0202FA, 0xFF010101), # v_mov_b32_dpp row_shl:1 + ("mov", "shl", 1, False, True, 0x7E0202FA, 0xFF090101), # v_mov_b32_dpp row_shl:1 BC + ("mov", "shl", 15, False, False, 0x7E0202FA, 0xFF010F01), # v_mov_b32_dpp row_shl:15 + ("mov", "shl", 15, False, True, 0x7E0202FA, 0xFF090F01), # v_mov_b32_dpp row_shl:15 BC + ("mov", "shr", 1, False, False, 0x7E0202FA, 0xFF011101), # v_mov_b32_dpp row_shr:1 + ("mov", "shr", 1, False, True, 0x7E0202FA, 0xFF091101), # v_mov_b32_dpp row_shr:1 BC + ("mov", "shr", 15, False, False, 0x7E0202FA, 0xFF011F01), # v_mov_b32_dpp row_shr:15 + ("mov", "shr", 15, False, True, 0x7E0202FA, 0xFF091F01), # v_mov_b32_dpp row_shr:15 BC + ("mov", "ror", 1, False, False, 0x7E0202FA, 0xFF012101), # v_mov_b32_dpp row_ror:1 + ("mov", "ror", 1, False, True, 0x7E0202FA, 0xFF092101), # v_mov_b32_dpp row_ror:1 BC + ("mov", "ror", 15, False, False, 0x7E0202FA, 0xFF012F01), # v_mov_b32_dpp row_ror:15 + ("mov", "ror", 15, False, True, 0x7E0202FA, 0xFF092F01), # v_mov_b32_dpp row_ror:15 BC + ("add_u", "shr", 1, True, False, 0x4A0204FA, 0xFF051101), # v_add_nc_u32_dpp row_shr:1 FI + ("mov", "shr", 1, True, True, 0x7E0202FA, 0xFF0D1101), # v_mov_b32_dpp row_shr:1 FI BC + ("add_f", "ror", 8, False, True, 0x060204FA, 0xFF092801), # v_add_f32_dpp row_ror:8 BC + ("min_f", "ror", 8, False, True, 0x1E0204FA, 0xFF092801), # v_min_f32_dpp row_ror:8 BC +) + + +def program(op, instruction, control): + # Each group writes 64 words starting after eight guard words. + # Seed v1 (also the destination) and v2 under full EXEC. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8), + vop2(0x25, 1, 145, 0), vop2(0x25, 2, 148, 0)] + if op in ("add_f", "min_f"): + words += [0x7E020D01, 0x7E040D02] # v_cvt_f32_u32 v1, v1 and v2, v2 + # Restore EXEC before the store so suppressed writes can be checked. + return words + [sop1(3, 126, 255), ACTIVE, instruction, control, + sop1(3, 126, 193), 0xE0701000, 0x80080108, 0xBF810000] + + +def reference(op, direction, amount, fi, bound_zero): + initial = list(range(17, 81)) + result = initial.copy() + enabled = [bool(ACTIVE & (1 << (lane % 32))) for lane in range(64)] + for start in range(0, 64, 16): + row = initial[start:start + 16] + if direction == "shl": + peers = list(range(amount, 16)) + [None] * amount + elif direction == "shr": + peers = [None] * amount + list(range(16 - amount)) + else: + peers = list(range(16 - amount, 16)) + list(range(16 - amount)) + for offset, peer in enumerate(peers): + lane = start + offset + if not enabled[lane]: + continue + if peer is not None and (fi or enabled[start + peer]): + source = row[peer] + elif bound_zero: + source = 0 + else: + continue + own = lane + 20 + if op == "mov": + result[lane] = source + elif op == "min_f": + result[lane] = min(source, own) + else: + result[lane] = source + own + if op in ("add_f", "min_f"): + return struct.unpack("<64I", struct.pack("<64f", *result)) + return tuple(result) + + +def request(work, root, op, instruction, control, threads=64): + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1 | (1 << 20), 0, 0x8A) + return write_request(work, program(op, instruction, control), root, sa) + + +def controls(cli, sdk, work, root): + requests = work / "requests" + requests.mkdir() + good = request(requests, root, "mov", 0x7E0202FA, 0xFF010101) # row_shl:1 + refused = {} + for control, threads, error in ( + (0xFF015001, 64, "unsupported DPP lane selection"), # row_share:0 + (0xFF014201, 64, "unsupported DPP lane selection"), # control 0x142 + (0x7F010101, 64, "DPP requires a full-row, full-bank"), # row_shl:1, row_mask:7 + (0xFF010101, 24, "thread count divisible by 16")): # row_shl:1, partial row + marker = request(requests, root, "mov", 0x7E0202FA, control, threads) + refused[marker] = error + result = subprocess.run( + [cli, sdk, work / "cache", "gfx1013-direct-cs@0", "--requests", requests, requests], + capture_output=True, text=True) + assert result.returncode and "requests=5 compiled=1 refused=4" in result.stdout, ( + result.stdout, result.stderr) + good_key = good.stem.removeprefix("req_") + assert (requests / f"{good_key}.cs.cso").is_file() + for marker, error in refused.items(): + key = marker.stem.removeprefix("req_") + reason = (requests / f"{key}.fail").read_text(encoding="utf-8") + assert error in reason, (marker, reason) + assert not (requests / f"{key}.cs.cso").exists() + return 0 + + +def hardware(replay, sdk, work, root): + for op, direction, amount, fi, bound_zero, instruction, control in CASES: + marker = request(work, root, op, instruction, control) + output = marker.with_suffix(".bin") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + lanes = reference(op, direction, amount, fi, bound_zero) + expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 136) + actual = struct.unpack("<2064I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (op, hex(control), index, hex(got), hex(want)) + print(f"{op} {hex(control)}: 128 results and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_dxil_llvm_ident_check.py b/tests/native_dxil_llvm_ident_check.py new file mode 100644 index 0000000000..89e453e5a8 --- /dev/null +++ b/tests/native_dxil_llvm_ident_check.py @@ -0,0 +1,273 @@ +"""Verify direct DXIL !llvm.ident emission and D3D12 draw execution (#2915).""" +import ctypes +from ctypes import POINTER, Structure, byref, c_char_p, c_int32, c_size_t, c_uint32, c_void_p +from pathlib import Path +import re +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import uuid + +from native_direct_container_check import ( + compute, + interpolated_pixel, + patched_pixel, + publish, + signature, + signature_rows, + vertex, + words, +) + + +class _GUID(Structure): + _fields_ = [ + ("Data1", c_uint32), + ("Data2", ctypes.c_uint16), + ("Data3", ctypes.c_uint16), + ("Data4", ctypes.c_ubyte * 8), + ] + + @classmethod + def parse(cls, text: str) -> "_GUID": + return cls.from_buffer_copy(uuid.UUID(text).bytes_le) + + +_CLSID_DXC_UTILS = _GUID.parse("6245d6af-66e0-48fd-80b4-4d271796748c") +_IID_IDXC_UTILS = _GUID.parse("4605c4cb-2019-492a-ada4-65f20bb7d67f") +_CLSID_DXC_ASSEMBLER = _GUID.parse("d728db68-f903-4f80-94cd-dccf76ec7151") +_IID_IDXC_ASSEMBLER = _GUID.parse("091f7a26-1c1f-4948-904b-e6e3a8a771d5") +_CLSID_DXC_VALIDATOR = _GUID.parse("8ca3e215-f728-4cf3-8cdd-88af917587a1") +_IID_IDXC_VALIDATOR = _GUID.parse("a6e82bd2-1fd7-4826-9811-2857e797f49a") + + +def _vfn(obj, index: int, restype, *argtypes): + vtbl = ctypes.cast(ctypes.cast(obj, POINTER(c_void_p))[0], POINTER(c_void_p)) + return ctypes.WINFUNCTYPE(restype, c_void_p, *argtypes)(vtbl[index]) + + +def _blob_bytes(blob: c_void_p) -> bytes: + ptr = _vfn(blob, 3, c_void_p)(blob) + size = _vfn(blob, 4, c_size_t)(blob) + return ctypes.string_at(ptr, size) + + +def _take_result(op_result: c_void_p) -> tuple[bytes, c_void_p]: + status = c_int32() + assert _vfn(op_result, 3, c_int32, POINTER(c_int32))(op_result, byref(status)) == 0 + if status.value < 0: + err = c_void_p() + _vfn(op_result, 5, c_int32, POINTER(c_void_p))(op_result, byref(err)) + detail = _blob_bytes(err).decode("utf-8", "replace") if err.value else f"{status.value:#x}" + raise RuntimeError(f"DXIL assembly/validation failed: {detail}") + blob = c_void_p() + assert _vfn(op_result, 4, c_int32, POINTER(c_void_p))(op_result, byref(blob)) == 0 + return _blob_bytes(blob), blob + + +def assemble_and_validate(sdk: Path, ir_text: str) -> bytes: + dxc_dll = ctypes.WinDLL(str(sdk / "dxcompiler.dll")) + dxil_dll = ctypes.WinDLL(str(sdk / "dxil.dll")) + for dll in (dxc_dll, dxil_dll): + dll.DxcCreateInstance.argtypes = [POINTER(_GUID), POINTER(_GUID), POINTER(c_void_p)] + dll.DxcCreateInstance.restype = c_int32 + + utils, assembler, validator = c_void_p(), c_void_p(), c_void_p() + assert dxc_dll.DxcCreateInstance(byref(_CLSID_DXC_UTILS), byref(_IID_IDXC_UTILS), byref(utils)) == 0 + assert dxc_dll.DxcCreateInstance(byref(_CLSID_DXC_ASSEMBLER), byref(_IID_IDXC_ASSEMBLER), byref(assembler)) == 0 + assert dxil_dll.DxcCreateInstance(byref(_CLSID_DXC_VALIDATOR), byref(_IID_IDXC_VALIDATOR), byref(validator)) == 0 + + encoded = ir_text.encode("utf-8") + source_blob = c_void_p() + assert _vfn(utils, 6, c_int32, c_char_p, c_uint32, c_uint32, POINTER(c_void_p))( + utils, encoded, len(encoded), 65001, byref(source_blob) + ) == 0 + assembled = c_void_p() + assert _vfn(assembler, 3, c_int32, c_void_p, POINTER(c_void_p))(assembler, source_blob, byref(assembled)) == 0 + _, container_blob = _take_result(assembled) + validated = c_void_p() + assert _vfn(validator, 3, c_int32, c_void_p, c_uint32, POINTER(c_void_p))( + validator, container_blob, 1, byref(validated) + ) == 0 + cso_bytes, _ = _take_result(validated) + return cso_bytes + + +def has_llvm_ident(disassembly: str, expected: str = "x2w") -> bool: + match = re.search(r"^!llvm\.ident\s*=\s*!\{!(\d+)\}\s*$", disassembly, re.MULTILINE) + if not match: + return False + node_id = match.group(1) + node = re.search(rf"^!{node_id}\s*=\s*!\{{!\"([^\"]*)\"\}}\s*$", disassembly, re.MULTILINE) + return bool(node and node.group(1) == expected) + + +def fullscreen_triangle_vs() -> bytes: + # Fullscreen triangle (-1, -1), (4, -1), (-1, 4) from SV_VertexID in v0. + program = [ + 0x7E0C02F6, # v_mov_b32_e32 v6, 4.0 + 0x7D040081, # v_cmp_eq_i32_e32 vcc, 1, v0 + 0x02020CF3, # v_cndmask_b32_e32 v1, -1.0, v6, vcc + 0x7D040082, # v_cmp_eq_i32_e32 vcc, 2, v0 + 0x02040CF3, # v_cndmask_b32_e32 v2, -1.0, v6, vcc + 0x7E060280, # v_mov_b32_e32 v3, 0 + 0x7E0E02F2, # v_mov_b32_e32 v7, 1.0 + 0xF80008CF, 0x07030201, # exp pos0 v1, v2, v3, v7 done + 0xBF810000, # s_endpgm + ] + return vertex(program=program) + + +def check_containers(cli: Path, sdk: Path) -> None: + dxc = sdk / "dxc.exe" + with TemporaryDirectory() as tmp: + work = Path(tmp) + cache = work / "cache" + + def compile_and_dump(name: str, profile: str, payload: bytes) -> tuple[Path, str]: + src = work / f"{name}.in" + cso = work / f"{name}.cso" + src.write_bytes(payload) + run = subprocess.run([cli, sdk, cache, profile, src, cso], capture_output=True, text=True) + assert run.returncode == 0, (name, profile, run.stdout, run.stderr) + dump = subprocess.check_output([dxc, "-dumpbin", cso], text=True) + assert has_llvm_ident(dump), f"{name} ({profile}) missing !llvm.ident:\n{dump}" + return cso, dump + + cs_code = words(0x7E000280, 0xBF810000) + compile_and_dump("compute", "gfx1013-container-cs", compute(cs_code)) + compile_and_dump("vertex", "gfx1013-container-vs", fullscreen_triangle_vs()) + _, ps_dump = compile_and_dump( + "pixel", + "gfx1013-container-ps", + patched_pixel(1, [0x7E0002F2], input_signature=((b"OSG1", signature(b"SV_Target", 64)),)), + ) + const_words = struct.pack("<8I", 0x7E0002F2, 0x7E0202F0, 0x7E0402FF, 0x3E800000, 0x7E0602F4, 0xF800180F, 0x03020100, 0xBF810000) + _, const_ps_dump = compile_and_dump("direct_const_ps", "gfx1013-direct-constant-ps", const_words) + + # Rectangle geometry expansion emits VS, GS and PS through DxilModule. + inputs_dir, rect_out = work / "rect_in", work / "rect_out" + vs_rect = vertex( + program=[0x7E020B00, 0xF80000CF, 0x01010101, 0xF8000A0F, 0x01010101, 0xBF810000], + varying=True, + extra=((b"OSG1", signature_rows([(b"TEXCOORD", 0, 3, 0, 15), (b"SV_Position", 1, 3, 1, 15)])),), + ) + root = b"DXBC" + bytes(16) + words(1, 68, 1, 36) + b"RTS0" + words(24, 2, 0, 24, 0, 24, 0) + stem = publish(inputs_dir, vs_rect, interpolated_pixel(), root) + subprocess.run([cli, sdk, cache, "gfx1013-container-rect", "--requests", inputs_dir, rect_out], check=True) + for stage in ("vs", "gs", "ps"): + stage_dump = subprocess.check_output([dxc, "-dumpbin", rect_out / f"{stem}.{stage}.cso"], text=True) + assert has_llvm_ident(stage_dump), f"rect.{stage} missing !llvm.ident" + + # Negative control: SDK validation accepts a module without !llvm.ident, + # and has_llvm_ident rejects the stripped container across both direct emitters. + for label, dump in (("container_ps", ps_dump), ("direct_const_ps", const_ps_dump)): + ir_text = "\n".join( + line for line in dump.splitlines() if not line.startswith(";") and not line.startswith("!llvm.ident") + ) + "\n" + stripped_cso = work / f"{label}_stripped.cso" + stripped_cso.write_bytes(assemble_and_validate(sdk, ir_text)) + stripped_dump = subprocess.check_output([dxc, "-dumpbin", stripped_cso], text=True) + assert not has_llvm_ident(stripped_dump), f"{label} negative control kept !llvm.ident" + + print("direct DXIL !llvm.ident container and negative controls passed (cs, vs, gs, ps, direct-constant-ps)") + + +def check_draws(cli: Path, raster: Path, sdk: Path, backend: str) -> None: + with TemporaryDirectory() as tmp: + work = Path(tmp) + cache = work / "cache" + vs_in, vs_cso = work / "vs.in", work / "vs.cso" + vs_in.write_bytes(fullscreen_triangle_vs()) + subprocess.run([cli, sdk, cache, "gfx1013-container-vs", vs_in, vs_cso], check=True) + + # Case 1: gfx1013-direct-constant-ps -> (1.0, 0.5, 0.25, 2.0) + const_in, const_cso = work / "const_ps.in", work / "const_ps.cso" + const_words = [0x7E0002F2, 0x7E0202F0, 0x7E0402FF, 0x3E800000, 0x7E0602F4, 0xF800180F, 0x03020100, 0xBF810000] + const_in.write_bytes(struct.pack("<8I", *const_words)) + subprocess.run([cli, sdk, cache, "gfx1013-direct-constant-ps", const_in, const_cso], check=True) + + expected = work / "expected.bin" + expected.write_bytes(struct.pack("<4f", 1.0, 0.5, 0.25, 2.0) * 16) + run = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, const_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, (run.stdout, run.stderr) + if "debug_layer=enabled" in run.stdout: + assert "debug_errors=0 debug_warnings=0" in run.stdout, run.stdout + + # Negative control 1: change alpha 2.0 -> 4.0 in gfx1013-direct-constant-ps; readback must fail. + bad_words = list(const_words) + bad_words[4] = 0x7E0602F6 # v3 = 4.0f + bad_in, bad_cso = work / "bad_const_ps.in", work / "bad_const_ps.cso" + bad_in.write_bytes(struct.pack("<8I", *bad_words)) + subprocess.run([cli, sdk, cache, "gfx1013-direct-constant-ps", bad_in, bad_cso], check=True) + bad_run = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, bad_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + assert bad_run.returncode != 0, "mutated gfx1013-direct-constant-ps unexpectedly matched" + + # Case 2: gfx1013-container-ps exporting distinct constants -> (0.5, 2.0, 1.0, 4.0) + ps_in, ps_cso = work / "container_ps.in", work / "container_ps.cso" + ps_seq = [0x7E0002F0, 0x7E0202F4, 0x7E0402F2, 0x7E0602F6] + ps_in.write_bytes( + patched_pixel( + len(ps_seq), + ps_seq, + export=(0xF800180F, 0x03020100), + input_signature=((b"OSG1", signature(b"SV_Target", 64)),), + ) + ) + subprocess.run([cli, sdk, cache, "gfx1013-container-ps", ps_in, ps_cso], check=True) + expected.write_bytes(struct.pack("<4f", 0.5, 2.0, 1.0, 4.0) * 16) + run2 = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, ps_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + assert run2.returncode == 0, (run2.stdout, run2.stderr) + if "debug_layer=enabled" in run2.stdout: + assert "debug_errors=0 debug_warnings=0" in run2.stdout, run2.stdout + + # Negative control 2: swap exported channels in gfx1013-container-ps; readback must fail. + bad_ps_in, bad_ps_cso = work / "bad_container_ps.in", work / "bad_container_ps.cso" + bad_ps_in.write_bytes( + patched_pixel( + len(ps_seq), + ps_seq, + export=(0xF800180F, 0x03020001), + input_signature=((b"OSG1", signature(b"SV_Target", 64)),), + ) + ) + subprocess.run([cli, sdk, cache, "gfx1013-container-ps", bad_ps_in, bad_ps_cso], check=True) + bad_run2 = subprocess.run( + [raster, backend, "--startup-pixel-words", vs_cso, bad_ps_cso, "8", "2", expected], + capture_output=True, + text=True, + ) + assert bad_run2.returncode != 0, "mutated gfx1013-container-ps unexpectedly matched" + + print(run2.stdout.strip()) + + +def main() -> None: + mode = sys.argv[1] + if mode == "container": + _, _, cli, sdk = sys.argv + check_containers(Path(cli), Path(sdk)) + elif mode == "draw": + _, _, cli, raster, sdk, backend = sys.argv + check_draws(Path(cli), Path(raster), Path(sdk), backend) + else: + raise ValueError(f"unknown mode: {mode}") + + +if __name__ == "__main__": + main() diff --git a/tests/native_exec_symbol_b64_check.py b/tests/native_exec_symbol_b64_check.py new file mode 100644 index 0000000000..a6349abdad --- /dev/null +++ b/tests/native_exec_symbol_b64_check.py @@ -0,0 +1,47 @@ +"""Reject a sampler word copied from EXEC after a 64-bit implicit write.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from native_direct_container_check import comparison_program, compute, words + + +def program(exec_op=None): + code = comparison_program(dim=5) + sampler_address = code[4] + code[3:5] = [ + 0x7e2c0500, # v_readfirstlane_b32 s22, v0 + 0xbe970380, # s_mov_b32 s23, 0 + 0xbefe04ff, sampler_address, # s_mov_b64 exec, comparison sampler word + *(() if exec_op is None else (exec_op,)), + 0xbe84037e, # s_mov_b32 s4, exec_lo + ] + return compute(words(*code, 0xbf810000), threads=64, table=True, wave32=False) + + +def controls(cli, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for name, exec_op in ( + ("constant-exec", None), + ("saveexec", 0xbe982416), # s_and_saveexec_b64 s[24:25], s[22:23] + ("wrexec", 0xbe983a16), # s_andn2_wrexec_b64 s[24:25], s[22:23] + ): + source = work / (name + ".cdx") + output = source.with_suffix(".cso") + source.write_bytes(program(exec_op)) + result = subprocess.run( + [cli, sdk, work / "cache", "gfx1013-container-cs", source, output], + capture_output=True, text=True, + ) + if exec_op is None: + assert result.returncode == 0 and output.read_bytes().startswith(b"DXBC"), (name, result.stderr) + else: + assert result.returncode != 0 and "nonconstant sampler" in result.stderr, (name, result.stderr) + assert not output.exists(), output + + +if __name__ == "__main__": + mode, cli, sdk = sys.argv[1:] + {"controls": controls}[mode](cli, sdk) diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py new file mode 100644 index 0000000000..c04181fc34 --- /dev/null +++ b/tests/native_f16_alu_check.py @@ -0,0 +1,753 @@ +"""Binary16 binary and unary ALU in the direct C++ compute path. + +Each source contributes its low 16 bits. abs clears bit 15 of that half, then neg toggles it. +The operation runs in f32 and rounds to binary16 the way v_cvt_f16_f32 does. The result is the low +16 bits and the destination's high half keeps its value (LLVM GCNSubtarget::zeroesHigh16BitsOfDest: +"On gfx10, all 16-bit instructions preserve the high bits"). Every destination holds HI_A in its high +half before the operation, so each stored word is HI_A | result. The reference is half_op in f16_packed_model.py (sub is an add of +the negated second source, subrev swaps the sources). Exp2 matches exact bits. +Rsq permits the other encoding only within 8 f32 ULP of a binary16 midpoint. +For the other operations NaNs match by class. + + native_f16_alu_check.py model + no dumper and no GPU: the case table, the f32 rounding cross-check, and the two mutants + native_f16_alu_check.py ir DUMPER + build one compute container, dump its DXIL text, evaluate it, and require the named refusals + native_f16_alu_check.py gpu STORE_REPLAY SDK + compute readback of the same words and the DPP16 cases (exit 77 without wave32) +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import f16_packed_model as M +from f16_exp_midpoints import check_cpp_table, exp_f16_midpoints +from native_compute_clear_check import write_request +from native_direct_container_check import pack, words +from native_scalar_lds_check import scalar, sop1, vmove + +GROUPS = 2 +WORDS = 2064 +SENTINEL = 0x69696969 # native_store_replay fills untouched words with 0x69 +BASE = 8 +STRIDE = 512 +SHIFT = 11 +assert 4 * STRIDE == 1 << SHIFT + +OPS = ('add', 'sub', 'subrev', 'mul') +OP_CODE = {'add': 0x32, 'sub': 0x33, 'subrev': 0x34, 'mul': 0x35} +UNARY_CODE = {'rcp': 0x54, 'sqrt': 0x55, 'exp': 0x58, 'rsq': 0x56} +UNARY_INPUTS = M.GRID + [0x8001, 0x0400, 0x3800, 0x4000, 0x4400, 0x3555, + 0x4bff, 0x4c00, 0x4c40, 0xce00, 0xce40, 0xce80] +# Binary16 rounding of the nine inline float encodings, in encoding order. +INLINE_F16 = { + 240: 0x3800, 241: 0xb800, 242: 0x3c00, 243: 0xbc00, 244: 0x4000, + 245: 0xc000, 246: 0x4400, 247: 0xc400, 248: 0x3118, +} +PAIRS = [ + (0x3c00, 0x4000), (0x0000, 0x8000), (0x8000, 0x8000), (0x0001, 0x0000), + (0x0001, 0x0001), (0x7c00, 0x3c00), (0x7c00, 0xfc00), (0x7e00, 0x3c00), + (0x7bff, 0x7bff), (0x3c00, 0x1000), (0x3c01, 0x1000), (0x7c01, 0x0001), +] +HI_A = 0xABCD0000 +HI_B = 0x789A0000 +DPP_EXEC = 0xFFFFFEFD # Lanes 1 and 8 are inactive during the DPP instructions. +DPP_OLD = HI_A | 0x3555 +DPP_CASES = ( + # op, DPP_CTRL, FI, BOUND_CTRL, row mask, bank mask, src1 low half + ('add', 0xB1, True, False, 0xF, 0xF, 0x1000), # quad_perm:[1,0,3,2], ties to even + ('mul', 0x111, False, False, 0xF, 0xF, 0x3C01), # row_shr:1, preserve at row edges + ('sub', 0xB1, True, False, 0x5, 0xF, 0x3C01), + ('subrev', 0xB1, False, True, 0xF, 0x5, 0x3C01), +) + + +def binary16(op, a, b): + """Low 16 bits of one RDNA 2 operation. sub negates the second source; subrev swaps.""" + a &= 0xffff + b &= 0xffff + if op == 'sub': + return M.half_op('add', a, b ^ 0x8000) + if op == 'subrev': + return M.half_op('add', b, a ^ 0x8000) + if op == 'exp' and a in exp_f16_midpoints(): + return exp_f16_midpoints()[a] + return M.half_op(op, a, b) + + +def modified(bits, abs_mask, neg, index): + if abs_mask & (1 << index): + bits &= 0x7fff + if neg & (1 << index): + bits ^= 0x8000 + return bits & 0xffff + + +def same_binary16(got, want): + """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN.""" + if got >> 16 or want >> 16: + return False + if M.is_nan(got) or M.is_nan(want): + return M.is_nan(got) and M.is_nan(want) + return got == want + + +def same_alu_result(got, want, op, alternate): + if op == 'exp': + return got == want + return same_binary16(got, want) or got == alternate + + +def same_half(got, want, case=None): + """Check the preserved HI_A and compare the low half with the reference.""" + if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): + return False + return same_alu_result(got & 0xffff, want & 0xffff, + case.op if case else None, case.alternate if case else None) + + +def _u32(value): + return value & 0xffffffff + + +def packed_half_rne(bits): + """The integer round used by packed_half_rne in the direct compute lowering.""" + bits = _u32(bits) + sign = (bits >> 16) & 32768 + mag = bits & 0x7fffffff + exp = mag >> 23 + frac = mag & 0x7fffff + + def round_shift(value, shift, half): + odd = _u32(value >> shift) & 1 + bias = _u32(_u32(half - 1) + odd) + return _u32(_u32(value + bias) >> shift) + + normal = round_shift(_u32(mag - 939524096), 13, 4096) + sub_range = 102 <= exp <= 112 + shift = _u32(126 - exp) if sub_range else 14 + half = _u32(1 << _u32(shift - 1)) + sub = round_shift(frac | 8388608, shift, half) + if exp <= 112: + result = sub if sub_range else 0 + else: + result = normal + if exp > 142: + result = 31744 + if mag > 2139095040: + result = (frac >> 13) | 32256 + return (result | sign) & 65535 + + +def f32_half(op, a, b): + """f32 operation on exact f16 inputs, then the integer binary16 round.""" + left, right = M.h2f(a), M.h2f(b) + if op in UNARY_CODE: + value = M.half_unary_value(op, left) + else: + value = {'add': left + right, 'sub': left - right, 'subrev': right - left, 'mul': left * right}[op] + if op == 'exp': + if M.is_nan(a): + return 0x7e00 + if a == 0xce40: + return 0 + if a in exp_f16_midpoints(): + return exp_f16_midpoints()[a] + bits = struct.unpack('<I', struct.pack('<f', value))[0] + return packed_half_rne(bits) + + +def vop2(op, dst, src0, src1): + return [(op << 25) | ((dst & 255) << 17) | ((src1 & 255) << 9) | (src0 & 511)] + + +def vop1(op, dst, src0): + return [0x7e000000 | ((dst & 255) << 17) | (op << 9) | (src0 & 511)] + + +def vop3(op, dst, src0, src1, abs_mask=0, neg=0, clamp=0, omod=0, opsel=0, unary=False): + base = 0x180 if unary else 0x100 + word = (0xd4000000 | ((base + op) << 16) | ((abs_mask & 7) << 8) | ((opsel & 15) << 11) | + ((clamp & 1) << 15) | (dst & 255)) + other = (src0 & 511) | ((src1 & 511) << 9) | ((omod & 3) << 27) | ((neg & 7) << 29) + return [word, other] + + +def mov(reg, value): + return [0x7e0002ff | (reg << 17), value & 0xffffffff] + + +def smov(reg, value): + return [0xbe8003ff | (reg << 16), value & 0xffffffff] + + +def store(byte_off, data): + return [0xe0701000 | (byte_off & 4095), 0x80080008 | ((data & 255) << 8)] + + +class Case: + def __init__(self, op, a, b, kind='vop2', abs_mask=0, neg=0, inline_src=242): + self.op = op + self.kind = kind + self.abs_mask = abs_mask + self.neg = neg + self.inline_src = inline_src + self.dest = 3 + if kind == 'inline': + a = INLINE_F16[inline_src] + elif kind == 'inline_int': + a = (192 - 193) & 0xffff + self.a = a & 0xffff + self.b = b & 0xffff + left = modified(self.a, abs_mask, neg, 0) + if op == 'rsq': + self.want, self.alternate = M.rsq_rounding(left) + else: + self.want = binary16(op, left, modified(self.b, abs_mask, neg, 1)) + self.alternate = None + + def emit(self): + a_word, b_word = HI_A | self.a, HI_B | self.b + if self.op in UNARY_CODE: + op = UNARY_CODE[self.op] + instruction = (vop3(op, 3, 257, 0, self.abs_mask, self.neg, unary=True) + if self.kind == 'vop3' else vop1(op, 3, 257)) + return mov(1, a_word) + mov(3, HI_A) + instruction + op = OP_CODE[self.op] + if self.kind == 'overlap': + self.dest = 1 + return mov(1, a_word) + mov(2, b_word) + vop2(op, 1, 257, 2) + if self.kind == 'issue': + self.dest = 0 + word = vop2(0x32, 0, 257, 2) + assert word == [0x64000501] + return mov(1, a_word) + mov(2, b_word) + mov(0, HI_A) + word + if self.kind == 'literal': + return mov(2, b_word) + mov(3, HI_A) + vop2(op, 3, 255, 2) + [a_word] + if self.kind == 'inline': + return mov(2, b_word) + mov(3, HI_A) + vop2(op, 3, self.inline_src, 2) + if self.kind == 'inline_int': + return mov(2, b_word) + mov(3, HI_A) + vop2(op, 3, 193, 2) + if self.kind == 'sgpr': + return mov(2, b_word) + mov(3, HI_A) + smov(8, a_word) + vop2(op, 3, 8, 2) + if self.kind == 'vop3': + return mov(1, a_word) + mov(2, b_word) + mov(3, HI_A) + vop3(op, 3, 257, 258, self.abs_mask, self.neg) + return mov(1, a_word) + mov(2, b_word) + mov(3, HI_A) + vop2(op, 3, 257, 2) + + +def all_cases(): + items = [Case(op, a, b) for a, b in PAIRS for op in OPS] + for abs_mask, neg in ((1, 0), (0, 2), (3, 1), (3, 3)): + items.extend(Case(op, 0xbc00, 0x4000, 'vop3', abs_mask, neg) for op in OPS) + items.append(Case('add', 0x3c00, 0x4000, 'vop3', abs_mask=4)) + for op in OPS: + items.append(Case(op, 0, 0x4000, 'inline')) + items.append(Case(op, 0x3c01, 0x3c00, 'literal')) + items.append(Case(op, 0x3c00, 0x4000, 'sgpr')) + items.append(Case('add', 0, 0x3c00, 'inline', inline_src=248)) + items.append(Case('add', 0, 0, 'inline_int')) + items.append(Case('add', 0x3c00, 0x4000, 'overlap')) + items.append(Case('subrev', 0x3c00, 0x4000, 'overlap')) + items.append(Case('add', 0x3c00, 0x4000, 'issue')) + for op in UNARY_CODE: + items.extend(Case(op, a, 0, kind) for kind in ('vop1', 'vop3') for a in UNARY_INPUTS) + items.append(Case(op, 0xc000, 0, 'vop3', abs_mask=1)) + items.append(Case(op, 0x4000, 0, 'vop3', neg=1)) + for kind in ('vop1', 'vop3'): + items.extend(Case('exp', a, 0, kind) for a in exp_f16_midpoints()) + items.append(Case('rsq', 0x3bfe, 0, kind)) + items += [ + Case('exp', 0x91c5, 0, 'vop3', abs_mask=1), + Case('exp', 0x11c5, 0, 'vop3', neg=1), + Case('exp', 0x91c5, 0, 'vop3', neg=1), + ] + assert len(items) < STRIDE + return items + + +def preamble(): + """s4 is the descriptor table and s5 is the group id.""" + return [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 128 + SHIFT), vmove(8, 7), sop1(3, 126, 129), + 0xbfa40000, 0xbfa40010, 0xbfa5000f, 0xba800881, 0] + + +def program(items): + code = preamble() + want = [] + for case in items: + code += case.emit() + code += store(4 * len(want), case.dest) + want.append(case.want) + code.append(0xbf810000) + return code, want + + +def dpp_program(): + assert 32 * len(DPP_CASES) <= STRIDE # 4 words per lane, inside one group + code = preamble() + code += [sop1(3, 126, 193)] # the preamble leaves EXEC at lane 0; set up every lane + code += vop2(0x1A, 8, 132, 0) + vop2(0x25, 8, 7, 8) # 16 * lane + group byte base + code += mov(1, HI_B | 0x3c00) + vop2(0x1C, 1, 256, 1) # lane-distinct src0 + for slot, (op, pattern, fi, bound_zero, rows, banks, src1) in enumerate(DPP_CASES): + control = 1 | pattern << 8 | fi << 18 | bound_zero << 19 | banks << 24 | rows << 28 + code += mov(2, HI_B | src1) + mov(3, DPP_OLD) + code += [sop1(3, 126, 255), DPP_EXEC, *vop2(OP_CODE[op], 3, 250, 2), control] + # Store under full EXEC to observe both lane masks and preserved destinations. + code += [sop1(3, 126, 193), *store(4 * slot, 3)] + return code + [0xbf810000] + + +def dpp_reference(): + results = [] + for lane in range(32): + for op, _, fi, bound_zero, rows, banks, src1 in DPP_CASES: + peer = lane - 1 if op == 'mul' else lane ^ 1 + in_row = peer // 16 == lane // 16 + usable = in_row and (fi or DPP_EXEC & (1 << peer)) + row, bank = lane // 16, lane // 4 % 4 + enabled = DPP_EXEC & (1 << lane) and rows & (1 << row) and banks & (1 << bank) + if enabled and (usable or bound_zero): + results.append(HI_A | binary16(op, 0x3c00 + peer if usable else 0, src1)) + else: + results.append(DPP_OLD) + return results + + +def swapped_want(case): + if case.op in UNARY_CODE: + return case.want + op = {'sub': 'subrev', 'subrev': 'sub'}.get(case.op, case.op) + return binary16(op, modified(case.a, case.abs_mask, case.neg, 0), modified(case.b, case.abs_mask, case.neg, 1)) + + +def reject_mutants(items): + """The comparator must fail a sub/subrev swap and a result whose high half was zeroed.""" + wants = [case.want for case in items] + swapped = [swapped_want(case) for case in items] + assert any(left != right for left, right in zip(wants, swapped)) + assert not all(same_half(HI_A | got, want) for got, want in zip(swapped, wants)) + assert not any(same_half(got, want) for got, want in zip(wants, wants)) + + +def check_model(items): + check_cpp_table() + assert binary16('add', 0x3c00, 0x1000) == 0x3c00 + assert binary16('add', 0x3c01, 0x1000) == 0x3c02 + assert binary16('add', 0x7bff, 0x7bff) == 0x7c00 + assert binary16('add', 0x8000, 0x8000) == 0x8000 + assert binary16('add', 0x8000, 0x0000) == 0x0000 + assert binary16('add', 0x0001, 0x0001) == 0x0002 + assert binary16('mul', 0x0001, 0x8001) == 0x8000 + assert binary16('sub', 0x4200, 0x3c00) == 0x4000 + assert binary16('subrev', 0x3c00, 0x4200) == 0x4000 + assert binary16('sub', 0x3c00, 0x4000) != binary16('subrev', 0x3c00, 0x4000) + assert M.half_op('rcp', 0x8000) == 0xfc00 + assert M.half_op('rcp', 0xfc00) == 0x8000 + assert M.half_op('sqrt', 0x8000) == 0x8000 + assert M.half_op('sqrt', 0x4400) == 0x4000 + assert M.is_nan(M.half_op('sqrt', 0xbc00)) + assert M.half_op('exp', 0x8000) == 0x3c00 + assert M.half_op('exp', 0x4c00) == 0x7c00 # 2**16 overflows binary16. + assert M.half_op('exp', 0xce00) == 0x0001 # 2**-24 is the least subnormal. + assert M.half_op('exp', 0xce40) == 0x0000 # 2**-25 ties to zero. + for source, rsq in ((0x0000, 0x7c00), (0x8000, 0xfc00), (0x7c00, 0x0000), + (0x3c00, 0x3c00), (0x0001, 0x6c00), (0x4400, 0x3800)): + assert M.half_op('rsq', source) == rsq + for source in (0xbc00, 0x8001, 0xfc00, 0x7e01): + assert M.is_nan(M.half_op('rsq', source)) + assert M.rsq_rounding(0x3bfe) == (0x3c01, 0x3c00) + assert M.rsq_rounding(0x3c00) == (0x3c00, None) + assert not same_alu_result(0x3c00, 0x3c01, 'exp', None) + assert not same_alu_result(0x7e01, 0x7e00, 'exp', None) + for case in items: + left = modified(case.a, case.abs_mask, case.neg, 0) + right = modified(case.b, case.abs_mask, case.neg, 1) + got = f32_half(case.op, left, right) + assert same_half(HI_A | got, case.want, case), (case.op, case.kind, hex(left), hex(right), hex(got), hex(case.want)) + wants = [case.want for case in items] + assert 0x8000 in wants and 0x0000 in wants and 0x7c00 in wants and 0x3c00 in wants and 0x3c02 in wants + assert any(M.is_nan(value) for value in wants) + assert any(0 < (value & 0x7fff) < 0x0400 for value in wants) + reject_mutants(items) + + +def refusal_programs(): + add = vop2(0x32, 3, 257, 2) + programs = [] + programs.append((vop2(0x32, 3, 233, 2) + [0xfac68801, 0xbf810000], 'unsupported v_add_f16 DPP form')) # DPP8 stays refused on binary16 + # Clamp needs a wide encoding. A VOP3 with clamp and the DPP16 source selector is invalid. + programs.append((vop3(0x32, 3, 250, 258, clamp=1) + [0xbf810000], 'unsupported v_add_f16 clamp or omod')) + programs.append((vop3(0x35, 3, 257, 258, clamp=1) + [0xbf810000], 'unsupported v_mul_f16 clamp or omod')) + programs.append((vop3(0x33, 3, 257, 258, omod=1) + [0xbf810000], 'unsupported v_sub_f16 clamp or omod')) + programs.append((vop3(0x34, 3, 257, 258, opsel=1) + [0xbf810000], 'unsupported v_subrev_f16 high-half op_sel')) + programs.append((vop3(0x32, 3, 257, 258, opsel=8) + [0xbf810000], 'unsupported v_add_f16 high-half op_sel')) + programs.append(([0xbfa4000c] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xbfa50000] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xba8005c1, 1] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xb98005c1] + add + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) + programs.append(([0xbfa40001] + add + [0xbf810000], 'unsupported compute control instruction s_round_mode')) + programs.append(([0xbfa5000c] + add + [0xbf810000], 'unsupported compute control instruction s_denorm_mode')) + programs.append((vop2(0x3a, 3, 257, 2) + [0xbf810000], 'direct DXIL lowering for v_min_f16')) + for name, op in UNARY_CODE.items(): + programs.append((vop1(op, 3, 250) + [0, 0xbf810000], 'unsupported v_%s_f16 DPP form' % name)) + programs.append((vop3(op, 3, 257, 0, clamp=1, unary=True) + [0xbf810000], + 'unsupported v_%s_f16 clamp or omod' % name)) + programs.append((vop3(op, 3, 257, 0, omod=1, unary=True) + [0xbf810000], + 'unsupported v_%s_f16 clamp or omod' % name)) + programs.append((vop3(op, 3, 257, 0, opsel=1, unary=True) + [0xbf810000], + 'unsupported v_%s_f16 high-half op_sel' % name)) + for mode in (0xbfa4000c, 0xbfa50000): + programs.append(([mode] + vop1(op, 3, 257) + [0xbf810000], + 'unsupported binary16 rounding or denormal mode')) + for instruction in (vop1(0x57, 3, 257), vop3(0x57, 3, 257, 0, unary=True)): + programs.append((instruction + [0xbf810000], 'direct DXIL lowering for v_log_f16')) + return programs + + +def compute_container(code_bytes): + """One compute stage. The descriptor table is s4 and the group id is s5, matching the .c67 preamble.""" + body = bytearray(256) + struct.pack_into('<Q', body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into('<Q', body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into('<Q', body, 96, record) + struct.pack_into('<Q', body, record + 40, len(body)) + struct.pack_into('<I', body, record + 56, 1) + body.extend(words(3, 0, 1, 0, 4)) + struct.pack_into('<QQ', body, record, len(body), len(code_bytes)) + struct.pack_into('<I', body, record + 20, 32) + struct.pack_into('<II', body, record + 76, 512, 4) + struct.pack_into('<IIII', body, record + 120, 0x8a, 32, 1, 1) + body.extend(code_bytes) + return pack(body) + + +def _i32(token, values): + if token.startswith('%'): + kind, bits = values[token] + if kind != 'i32': + raise AssertionError((token, kind, bits)) + return bits & 0xffffffff + if token == 'undef': + return 0 + return int(token, 0) & 0xffffffff + + +def _i1(token, values): + if token == 'true': + return 1 + if token == 'false': + return 0 + kind, bits = values[token] + if kind != 'i1': + raise AssertionError((token, kind)) + return bits + + +def _signed(bits): + return bits - 0x100000000 if bits & 0x80000000 else bits + + +def _icmp(pred, left, right): + sl, sr = _signed(left), _signed(right) + return { + 'eq': left == right, 'ne': left != right, + 'ugt': left > right, 'uge': left >= right, 'ult': left < right, 'ule': left <= right, + 'sgt': sl > sr, 'sge': sl >= sr, 'slt': sl < sr, 'sle': sl <= sr, + }[pred] + + +def _f32(bits): + return struct.unpack('<f', struct.pack('<I', bits & 0xffffffff))[0] + + +def _fbin(op, left, right): + if op == 'fdiv': + assert left == 0x3f800000 + value = M.half_unary_value('rcp', _f32(right)) + else: + value = {'fadd': _f32(left) + _f32(right), 'fsub': _f32(left) - _f32(right), + 'fmul': _f32(left) * _f32(right)}[op] + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def _widen(bits): + return struct.unpack('<I', struct.pack('<f', struct.unpack('<e', struct.pack('<H', bits & 0xffff))[0]))[0] + + +def _branch(line, values): + match = re.fullmatch(r'br label %(\S+)', line) + if match: + return match.group(1) + match = re.fullmatch(r'br i1 (\S+), label %(\S+), label %(\S+)', line) + if not match: + raise AssertionError(line) + return match.group(2) if _i1(match.group(1), values) else match.group(3) + + +def _exec(line, values, memory, stores): + if line.startswith('store '): + match = re.fullmatch(r'store i32 (\S+), i32\* (\S+), align 4', line) + if not match: + raise AssertionError(line) + memory[match.group(2)] = _i32(match.group(1), values) + return + if 'rawBufferStore.i32' in line: + match = re.search(r'rawBufferStore\.i32\(i32 140, %dx\.types\.Handle \S+, i32 (\S+), i32 \S+, i32 (\S+),', line) + if not match: + raise AssertionError(line) + stores.append((_i32(match.group(1), values), _i32(match.group(2), values))) + return + if line.startswith('call '): + raise AssertionError(line) + match = re.fullmatch(r'(%\w+) = (.+)', line) + if not match: + raise AssertionError(line) + name, rhs = match.group(1), match.group(2) + if rhs.startswith('alloca '): + memory[name] = None + values[name] = ('ptr', 0) + return + loaded = re.fullmatch(r'load i32, i32\* (%\w+), align 4', rhs) + if loaded: + # A destination keeps its previous bits on an inactive lane. Lane 0 is active + # for every store in this fixture, so an unread register contributes nothing. + values[name] = ('i32', 0 if memory.get(loaded.group(1)) is None else memory[loaded.group(1)]) + return + compared = re.fullmatch(r'icmp (\w+) i32 (\S+), (\S+)', rhs) + if compared: + values[name] = ('i1', int(_icmp(compared.group(1), _i32(compared.group(2), values), _i32(compared.group(3), values)))) + return + selected = re.fullmatch(r'select i1 (\S+), i32 (\S+), i32 (\S+)', rhs) + if selected: + taken = _i32(selected.group(2), values) if _i1(selected.group(1), values) else _i32(selected.group(3), values) + values[name] = ('i32', taken) + return + binary = re.fullmatch(r'(add|sub|mul|and|or|xor|shl|lshr|ashr|urem|udiv) i32 (\S+), (\S+)', rhs) + if binary: + op, left, right = binary.group(1), _i32(binary.group(2), values), _i32(binary.group(3), values) + if op == 'shl': + result = left << (right & 31) + elif op == 'lshr': + result = left >> (right & 31) + elif op == 'ashr': + result = _signed(left) >> (right & 31) + elif op in ('urem', 'udiv'): + result = 0 if right == 0 else (left % right if op == 'urem' else left // right) + else: + result = {'add': left + right, 'sub': left - right, 'mul': left * right, + 'and': left & right, 'or': left | right, 'xor': left ^ right}[op] + values[name] = ('i32', result & 0xffffffff) + return + logic = re.fullmatch(r'(and|or|xor) i1 (\S+), (\S+)', rhs) + if logic: + left, right = _i1(logic.group(2), values), _i1(logic.group(3), values) + result = {'and': left & right, 'or': left | right, 'xor': left ^ right}[logic.group(1)] + values[name] = ('i1', result) + return + extended = re.fullmatch(r'zext i1 (\S+) to i32', rhs) + if extended: + values[name] = ('i32', _i1(extended.group(1), values)) + return + if rhs.startswith('bitcast i32 '): + token = rhs.removeprefix('bitcast i32 ').removesuffix(' to float') + values[name] = ('float', _i32(token, values)) + return + if rhs.startswith('bitcast float '): + token = rhs.removeprefix('bitcast float ').removesuffix(' to i32') + kind, bits = values[token] + if kind != 'float': + raise AssertionError(rhs) + values[name] = ('i32', bits) + return + floated = re.fullmatch(r'(fadd|fsub|fmul|fdiv) float (\S+), (\S+)', rhs) + if floated: + def bits_of(token): + if token.startswith('%'): + kind, bits = values[token] + if kind != 'float': + raise AssertionError(rhs) + return bits + return struct.unpack('<I', struct.pack('<f', float(token)))[0] + values[name] = ('float', _fbin(floated.group(1), bits_of(floated.group(2)), bits_of(floated.group(3)))) + return + extracted = re.fullmatch(r'extractvalue %dx\.types\.fouri32 (\S+), (\d+)', rhs) + if extracted: + kind, _ = values[extracted.group(1)] + if kind != 'ballot' or extracted.group(2) != '0': + raise AssertionError(rhs) + values[name] = ('i32', 0xffffffff) + return + if rhs.startswith('call '): + if 'waveGetLaneIndex' in rhs or 'groupId.i32' in rhs or 'flattenedThreadIdInGroup' in rhs: + values[name] = ('i32', 0) + elif 'waveActiveBallot' in rhs: + values[name] = ('ballot', 0) + elif 'legacyF16ToF32' in rhs: + argument = re.search(r'i32 (\S+)\)$', rhs) + values[name] = ('float', _widen(_i32(argument.group(1), values))) + elif 'unaryBits.i32(i32 33,' in rhs: + argument = re.search(r'i32 33,\s*i32 ([^,\s\)]+)\)', rhs) + x = _i32(argument.group(1), values) & 0xffffffff + values[name] = ('i32', (32 - x.bit_length()) if x else 0xffffffff) + elif 'unary.f32(i32 7,' in rhs: + argument = re.search(r'i32 7,\s*float ([^,\s\)]+)\)', rhs) + token = argument.group(1) + if token.startswith('%'): + kind, bits = values[token] + if kind != 'float': + raise AssertionError(rhs) + else: + bits = struct.unpack('<I', struct.pack('<f', float(token)))[0] + val = _f32(bits) + clamped = 0.0 if (math.isnan(val) or val <= 0.0) else (1.0 if val >= 1.0 else val) + values[name] = ('float', struct.unpack('<I', struct.pack('<f', clamped))[0]) + elif 'unary.f32' in rhs: + call = re.fullmatch(r'call float @dx\.op\.unary\.f32\(i32 (21|24|25), float (%\w+)\)', rhs) + assert call, rhs + op = {'21': 'exp', '24': 'sqrt', '25': 'rsq'}[call.group(1)] + kind, bits = values[call.group(2)] + assert kind == 'float', rhs + # Exercise the guest sign fix even with a host Rsqrt that treats -0 as +0. + value = M.half_unary_value(op, 0.0 if op == 'rsq' and bits == 0x80000000 else _f32(bits)) + values[name] = ('float', struct.unpack('<I', struct.pack('<f', value))[0]) + elif 'createHandleFromBinding' in rhs or 'annotateHandle' in rhs: + values[name] = ('handle', 0) + else: + raise AssertionError(rhs) + return + raise AssertionError(line) + + +def interpret(ir): + """Lane 0 of a straight-line compute module. Returns (byte address, stored word) pairs.""" + body = ir.split('define void @main()', 1)[1].split('\n}', 1)[0] + blocks, label, buf = {}, None, [] + for raw in body.splitlines(): + line = raw.strip() + if not line or line == '{': + continue + if line.endswith(':') and ' ' not in line: + if label is not None: + blocks[label] = buf + label, buf = line[:-1], [] + continue + if label is None: + raise AssertionError(line) + buf.append(line) + if label is not None: + blocks[label] = buf + values, memory, stores = {}, {}, [] + label, steps = 'entry', 0 + while steps < 200000: + steps += 1 + followed = False + for line in blocks[label]: + if line.startswith('br '): + label = _branch(line, values) + followed = True + break + if line == 'ret void': + return stores + _exec(line, values, memory, stores) + if not followed: + raise AssertionError('block fell through: ' + label) + raise AssertionError('step limit') + + +def dump(dumper, work, code, name): + path = work / (name + '.cdx') + path.write_bytes(compute_container(words(*code))) + return subprocess.run([dumper, str(path)], capture_output=True, text=True) + + +def run_model(): + items = all_cases() + check_model(items) + code, want = program(items) + assert vop2(0x32, 0, 257, 2) == [0x64000501] + assert len(want) == len(items) and len(code) > len(want) + print('native_f16_alu model: %d results match f32-then-round; ' + 'a sub/subrev swap and a zeroed upper half are rejected' % len(items)) + + +def run_ir(dumper): + items = all_cases() + check_model(items) + code, want = program(items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = dump(dumper, work, code, 'alu') + assert run.returncode == 0, run.stderr + text = run.stdout + assert 'legacyF16ToF32' in text and 'legacyF32ToF16' not in text, 'rounding opcode' + assert 'fadd float' in text and 'fsub float' in text and 'fmul float' in text + assert 'fdiv float' in text and all(f'@dx.op.unary.f32(i32 {op},' in text for op in (21, 24, 25)) + assert '939524096' in text, 'integer nearest-even rounding' + stores = sorted(interpret(text)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, hex(got), hex(expected)) for i, ((_, got), expected) in enumerate(zip(stores, want)) + if not same_half(got, expected, items[i])] + assert not bad, bad[:8] + run = dump(dumper, work, dpp_program(), 'dpp') + assert run.returncode == 0 and 'waveReadLaneAt.i32' in run.stdout, (run.stdout, run.stderr) + for refused, why in refusal_programs(): + run = dump(dumper, work, refused, 'refused') + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print('native_f16_alu IR: %d results match the model; %d refusals carry the named diagnostic' % + (len(want), len(refusal_programs()))) + + +def group_offsets(count): + offsets = [[BASE + group * STRIDE + i for i in range(count)] for group in range(GROUPS)] + flat = [index for group in offsets for index in group] + assert len(set(flat)) == len(flat) + assert 0 <= min(flat) and max(flat) < WORDS + return offsets + + +def run_gpu(gpu, sdk): + items = all_cases() + code, want = program(items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1)) + for name, instructions, reference, cases in (('alu', code, want, items), + ('dpp', dpp_program(), dpp_reference(), None)): + marker = write_request(work, instructions, root.read_bytes(), sa) + dest = work / (name + '-readback.bin') + run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + results = {slot: (value, cases[n] if cases else None) for offsets in group_offsets(len(reference)) + for n, (slot, value) in enumerate(zip(offsets, reference))} + actual = struct.unpack('<2064I', dest.read_bytes()) + bad = [] + for index, got in enumerate(actual): + model, case = results.get(index, (SENTINEL, None)) + ok = same_half(got, model, case) if index in results else got == model + if not ok: + bad.append((index, hex(got), hex(model))) + assert not bad, (name, bad[:10]) + print('native_f16_alu GPU %s: %d words matched the model, high half kept' % (name, len(results))) + + +if __name__ == '__main__': + if len(sys.argv) == 2 and sys.argv[1] == 'model': + run_model() + elif len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2]) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(sys.argv[2], sys.argv[3]) + else: + sys.exit(__doc__) diff --git a/tests/native_fma_f16_check.py b/tests/native_fma_f16_check.py new file mode 100644 index 0000000000..7eb4c24b53 --- /dev/null +++ b/tests/native_fma_f16_check.py @@ -0,0 +1,298 @@ +"""Direct compute binary16 FMA (v_fma_f16, v_fmac_f16, v_fmamk_f16, v_fmaak_f16).""" +from fractions import Fraction +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_scalar_lds_check import scalar, sop1 + + +HI_DST = 0xABCD0000 +HI_A = 0xBEEF0000 +HI_B = 0x789A0000 +HI_C = 0x13570000 + +OP_FMAC, OP_FMAMK, OP_FMAAK = 0x36, 0x37, 0x38 +OP_FMA_VOP3 = 0x34B +OP_FMAC_VOP3 = 0x136 + + +def vop3_tern(op, vdst, s0, s1, s2, *, abs_mask=0, neg=0, clamp=0, omod=0, op_sel=0): + w0 = (0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | + ((op_sel & 0xF) << 11) | ((abs_mask & 7) << 8) | (vdst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def half_to_fraction(bits): + bits &= 0xFFFF + sign = -1 if (bits & 0x8000) else 1 + exp = (bits >> 10) & 0x1F + mant = bits & 0x3FF + if exp == 0x1F: + return None + if exp == 0: + return Fraction(sign * mant, 1 << 24) + return Fraction(sign * (1024 + mant), 1 << (25 - exp)) if exp < 25 else Fraction(sign * (1024 + mant) * (1 << (exp - 25)), 1) + + +def round_fraction_f16(q, neg_zero=False): + if q == 0: + return 0x8000 if neg_zero else 0x0000 + sign = 0x8000 if q < 0 else 0x0000 + aq = abs(q) + # Overflow boundary: 65520 = 65504 + 16 -> +inf + if aq >= Fraction(65520, 1): + return sign | 0x7C00 + # Find largest e >= -24 such that 2^e <= aq, or subnormal grid 2^-24. + if aq < Fraction(1, 1 << 14): + scaled = aq * (1 << 24) + n = scaled.numerator // scaled.denominator + rem = scaled - n + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): + n += 1 + return sign | n + # Normal range: 2^e <= aq < 2^(e+1) + num, den = aq.numerator, aq.denominator + e = num.bit_length() - den.bit_length() + if aq < (Fraction(1 << e, 1) if e >= 0 else Fraction(1, 1 << (-e))): + e -= 1 + elif aq >= (Fraction(1 << (e + 1), 1) if e + 1 >= 0 else Fraction(1, 1 << (-(e + 1)))): + e += 1 + shift = e - 10 + step = Fraction(1 << shift, 1) if shift >= 0 else Fraction(1, 1 << (-shift)) + scaled = aq / step + n = scaled.numerator // scaled.denominator + rem = scaled - n + if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): + n += 1 + if n == 2048: + n = 1024 + e += 1 + if e > 15: + return sign | 0x7C00 + return sign | ((e + 15) << 10) | (n & 0x3FF) + + +def ref_fma16(a_bits, b_bits, c_bits, *, abs_mask=0, neg=0, clamp=False): + a = F.modified(a_bits, abs_mask, neg, 0) + b = F.modified(b_bits, abs_mask, neg, 1) + c = F.modified(c_bits, abs_mask, neg, 2) + + def cls(h): + e, f = (h >> 10) & 0x1F, h & 0x3FF + return e == 0x1F and f != 0, e == 0x1F and f == 0, (h & 0x7FFF) == 0, (h >> 15) & 1 + + an, ai, az, sa = cls(a) + bn, bi, bz, sb = cls(b) + cn, ci, cz, sc = cls(c) + sp = sa ^ sb + if an or bn or cn or (ai and bz) or (bi and az) or ((ai or bi) and ci and sp != sc): + out = 0x7E00 + elif ai or bi: + out = (sp << 15) | 0x7C00 + elif ci: + out = (sc << 15) | 0x7C00 + else: + exact = half_to_fraction(a) * half_to_fraction(b) + half_to_fraction(c) + out = round_fraction_f16(exact, neg_zero=(az or bz) and cz and sp == 1 and sc == 1) + if clamp: + if (out & 0x7FFF) > 0x7C00 or (out & 0x8000): + out = 0 + elif out > 0x3BFF: + out = 0x3C00 + return out + + +# #2073 double-rounding tie witnesses: f32 a*b+c rounded to f16 disagrees with exact single-rounded FMA. +TIE_WITNESSES_2073 = ( + (0x4A54, 0x1EF4, 0x4E2D, 0x4E33), + (0x51EA, 0xBF3E, 0x1D5F, 0xD55B), + (0x2BD5, 0xBE83, 0x4528, 0x450F), + (0x3915, 0x387A, 0x4B71, 0x4B9F), +) + + +def cases(): + items = [] + + def add(name, code, want, dst=3): + items.append((name, code, want, dst)) + + # 1. All four #2073 single-rounding witnesses across v_fma_f16, v_fmac_f16, v_fmamk_f16, v_fmaak_f16. + for a, b, c, want in TIE_WITNESSES_2073: + assert ref_fma16(a, b, c) == want + assert F.packed_half_rne( + struct.unpack('<I', struct.pack('<f', F.M.h2f(a) * F.M.h2f(b) + F.M.h2f(c)))[0] + ) != want + add(f'fma2073 {hex(a)}', + F.mov(1, HI_A | a) + F.mov(2, HI_B | b) + F.mov(4, HI_C | c) + F.mov(3, HI_DST | 0x1111) + + vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260), want) + add(f'fmac2073 {hex(a)}', + F.mov(1, HI_A | a) + F.mov(2, HI_B | b) + F.mov(3, HI_DST | c) + F.vop2(OP_FMAC, 3, 257, 2), want) + add(f'fmamk2073 {hex(a)}', + F.mov(1, HI_A | a) + F.mov(2, HI_B | c) + F.mov(3, HI_DST | 0x2222) + F.vop2(OP_FMAMK, 3, 257, 2) + [0xDEAD0000 | b], want) + add(f'fmaak2073 {hex(a)}', + F.mov(1, HI_A | a) + F.mov(2, HI_B | b) + F.mov(3, HI_DST | 0x3333) + F.vop2(OP_FMAAK, 3, 257, 2) + [0xCAFE0000 | c], want) + + # 2. v_fmac_f16 source kinds & VOP3 modifiers + destination overlap. + add('fmac sgpr', F.smov(10, HI_A | 0x4000) + F.mov(2, HI_B | 0x4200) + F.mov(3, HI_DST | 0x3C00) + F.vop2(OP_FMAC, 3, 10, 2), ref_fma16(0x4000, 0x4200, 0x3C00)) + add('fmac inline_float', F.mov(2, HI_B | 0x4000) + F.mov(3, HI_DST | 0x3C00) + F.vop2(OP_FMAC, 3, 242, 2), ref_fma16(0x3C00, 0x4000, 0x3C00)) + add('fmac inv2pi', F.mov(2, HI_B | 0x4400) + F.mov(3, HI_DST | 0x3800) + F.vop2(OP_FMAC, 3, 248, 2), ref_fma16(0x3118, 0x4400, 0x3800)) + add('fmac inline_int', F.mov(2, HI_B | 0x4000) + F.mov(3, HI_DST | 0x3C00) + F.vop2(OP_FMAC, 3, 193, 2), ref_fma16(0xFFFF, 0x4000, 0x3C00)) + add('fmac e64 neg abs', F.mov(1, HI_A | 0xC000) + F.mov(2, HI_B | 0xC200) + F.mov(3, HI_DST | 0x3C00) + vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, abs_mask=1, neg=2), ref_fma16(0xC000, 0xC200, 0x3C00, abs_mask=1, neg=2)) + add('fmac overlap dst=src0', F.mov(1, HI_DST | 0x4000) + F.mov(2, HI_B | 0x4200) + F.vop2(OP_FMAC, 1, 257, 2), ref_fma16(0x4000, 0x4200, 0x4000), dst=1) + + # 3. v_fma_f16 edge cases: abs/neg on all 3 sources, clamp, signed zero, cancellation, subnormals, overflow, Inf/NaN. + edges = [ + ('neg0*-0 + -0', 0x8000, 0x0000, 0x8000, 0, 0, False), + ('-0*-0 + -0', 0x8000, 0x8000, 0x8000, 0, 0, False), + ('exact cancel 2*3-6', 0x4000, 0x4200, 0xC600, 0, 0, False), + ('subnormal prod+subnormal', 0x0400, 0x0400, 0x0001, 0, 0, False), + ('sticky diff>=30 midpoint', 0x4200, 0x5156, 0x0001, 0, 0, False), # 128.0625 + 2^-24 -> 0x5801 (drop sticky -> 0x5800) + ('subnormal tie to even', 0x0001, 0x3800, 0x0000, 0, 0, False), # 2^-24 * 0.5 = 2^-25 -> 0 + ('subnormal above half', 0x0003, 0x3800, 0x0000, 0, 0, False), # 3 * 2^-25 -> 0x0001 + ('overflow +inf', 0x7BFF, 0x4000, 0x3C00, 0, 0, False), + ('overflow -inf', 0xFBFF, 0x4000, 0x3C00, 0, 0, False), + ('clamp negative', 0xC000, 0x4000, 0x3C00, 0, 0, True), + ('clamp >1.0', 0x4000, 0x4000, 0x3C00, 0, 0, True), + ('clamp 0.5', 0x3800, 0x3C00, 0x0000, 0, 0, True), + ('clamp +inf', 0x7C00, 0x3C00, 0x0000, 0, 0, True), + ('clamp qNaN', 0x7E00, 0x3C00, 0x0000, 0, 0, True), + ('0 * inf -> qNaN', 0x0000, 0x7C00, 0x3C00, 0, 0, False), + ('+inf + -inf -> qNaN', 0x7C00, 0x3C00, 0xFC00, 0, 0, False), + ('+inf + 1 -> +inf', 0x7C00, 0x3C00, 0x3C00, 0, 0, False), + ('-inf + 1 -> -inf', 0xFC00, 0x3C00, 0x3C00, 0, 0, False), + ('abs/neg all 3', 0xC000, 0xC200, 0x3C00, 5, 6, False), + ] + for label, a, b, c, absm, negm, cl in edges: + add(label, + F.mov(1, HI_A | a) + F.mov(2, HI_B | b) + F.mov(4, HI_C | c) + F.mov(3, HI_DST | 0x4444) + + vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, abs_mask=absm, neg=negm, clamp=int(cl)), + ref_fma16(a, b, c, abs_mask=absm, neg=negm, clamp=cl)) + + assert len(items) < F.STRIDE + return items + + +def emit_program(items): + code = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 128 + F.SHIFT), F.vmove(8, 7), sop1(3, 126, 129), + 0xBFA40000, 0xBFA5000F, 0xBA800881, 0] + want = [] + for index, (_, snippet, expected, dst) in enumerate(items): + code += snippet + F.store(4 * index, dst) + want.append(HI_DST | expected) + code.append(0xBF810000) + return code, want + + +def same_word(got, want): + if (got >> 16) != (HI_DST >> 16): + return False + return F.same_binary16(got & 0xFFFF, want & 0xFFFF) + + +def refusal_programs(): + fma = vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260) + fmac = F.vop2(OP_FMAC, 3, 257, 2) + return [ + (F.vop2(OP_FMAC, 3, 250, 2) + [0xFF00B101, 0xBF810000], 'unsupported DPP arithmetic'), + (F.vop2(OP_FMAC, 3, 249, 2) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + (vop3_tern(OP_FMA_VOP3, 3, 257, 258, 260, omod=1) + [0xBF810000], 'unsupported v_fma_f16 omod'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, omod=1) + [0xBF810000], 'unsupported v_fmac_f16 omod'), + (vop3_tern(OP_FMA_VOP3, 3, 244, 258, 260, op_sel=1) + [0xBF810000], 'unsupported v_fma_f16 high-half op_sel on non-VGPR source'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, op_sel=8) + [0xBF810000], 'unsupported v_fmac_f16 high-half op_sel'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 0, neg=4) + [0xBF810000], 'unsupported v_fmac_f16 third-source modifier'), + (vop3_tern(OP_FMAC_VOP3, 3, 257, 258, 260) + [0xBF810000], 'unsupported v_fmac_f16 third-source modifier'), + ([0xBFA4000C] + fma + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50000] + fmac + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xBA8005C1, 1] + fma + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ([0xB98005C1] + fmac + [0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = cases() + code, want = emit_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'fma-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i][0], hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_word(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (why, r.returncode, r.stderr) + print(f'native_fma_f16 IR: {len(want)} single-rounded conversions match Fraction reference; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = cases() + code, want = emit_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF32ToF16' not in dump, dump + + refusals = refusal_programs() + for n, (prog_words, why) in enumerate(refusals): + m = request(work, root, prog_words) + o = m.with_suffix(f'.refused{n}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_fma_f16 controls: compiled {len(want)} FMA cases cleanly to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = cases() + code, want = emit_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + for group in range(F.GROUPS): + head = F.BASE + group * F.STRIDE + got = words_out[head:head + len(want)] + bad = [(i, items[i][0], hex(a), hex(b)) for i, (a, b) in enumerate(zip(got, want)) if not same_word(a, b)] + assert not bad, (group, bad[:8]) + words_out[F.BASE:F.BASE + len(want)] = [0] * len(want) + words_out[F.BASE + F.STRIDE:F.BASE + F.STRIDE + len(want)] = [0] * len(want) + assert all(w == F.SENTINEL for w in words_out if w != 0), 'guard overwritten' + print(f'native_fma_f16 hardware: {len(want)} FMA cases matched across {F.GROUPS} groups') + return 0 + + +def main(mode, tool, sdk=None): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_fma_f16_opsel_check.py b/tests/native_fma_f16_opsel_check.py new file mode 100644 index 0000000000..83e9b5f4ba --- /dev/null +++ b/tests/native_fma_f16_opsel_check.py @@ -0,0 +1,98 @@ +"""Direct VOP3 v_fma_f16 source and destination half selection.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import f16_packed_model as model +from native_compute_clear_check import write_request +import native_f16_alu_check as F +from native_fma_f16_check import OP_FMA_VOP3, OP_FMAC, vop3_tern + + +SOURCES = (0x40003C00, 0x44004200, 0x4C004500) # (high, low): (2, 1), (4, 3), (16, 5) +DST = 0xABCD1234 +END = 0xBF810000 + + +def fma(srcs, op_sel, *, clamp=0): + return vop3_tern(OP_FMA_VOP3, 3, *srcs, op_sel=op_sel, clamp=clamp) + + +def program(): + # s5 supplies the group X ID (0 or 1). Lane 0 alone writes each dword. + # Case i in group g stores at byte 512*g + 4*i relative to the UAV window, + # which starts at readback word 8, so the file word index is 8 + 128*g + i. + # The preamble sets EXEC to 1 before the per-lane VGPR initialization. + code = F.preamble() + F.mov(1, SOURCES[0]) + F.mov(2, SOURCES[1]) + F.mov(4, SOURCES[2]) + want = [] + for op_sel in (1, 2, 3, 15, 14, 12, 8): + srcs = (257, 258, 260) + words = SOURCES + if op_sel == 8: + srcs = (244, 258, 243) # inline binary16 2.0 and -1.0 + words = (0x4000, SOURCES[1], 0xBC00) + halves = [model.pick(word, op_sel & (1 << j)) for j, word in enumerate(words)] + result = model.half_op('fma', *halves) + code += F.mov(3, DST) + fma(srcs, op_sel) + F.store(4 * len(want), 3) + want.append(((result << 16) | (DST & 0xFFFF)) if op_sel & 8 else ((DST & 0xFFFF0000) | result)) + assert want == [0xABCD4980, 0xABCD4880, 0xABCD4A80, 0x4E001234, 0x4D001234, 0x4CC01234, 0x45001234] + return code + [END], want + + +def refusals(): + return ( + (F.smov(10, SOURCES[0]) + fma((10, 258, 260), 1), + 'unsupported v_fma_f16 high-half op_sel on non-VGPR source'), + (F.vop2(OP_FMAC, 3, 250, 2) + [0xFF00B101], 'unsupported DPP arithmetic'), + (fma((257, 258, 260), 8, clamp=1), 'unsupported v_fma_f16 high-half op_sel'), + ) + + +def ir(dumper, work, code, want): + run = F.dump(dumper, work, code, 'fma-f16-opsel') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert stores == [(4 * i, word) for i, word in enumerate(want)], stores + for i, (snippet, why) in enumerate(refusals()): + run = F.dump(dumper, work, F.preamble() + snippet + [END], f'refused-{i}') + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print(f'native_fma_f16_opsel IR matched {len(want)} cases and {len(refusals())} refusals') + return 0 + + +def hardware(replay, sdk, work, code, want): + shader, root = work / 'root.hlsl', work / 'root.bin' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + # .sa dword 4, bit 20 requests wave32. + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x8A) + marker = write_request(work, code, root.read_bytes(), sa) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + got = struct.unpack(f'<{F.WORDS}I', output.read_bytes()) + expected = {slot: value for slots in F.group_offsets(len(want)) + for slot, value in zip(slots, want)} + bad = [(i, hex(word), hex(expected.get(i, F.SENTINEL))) + for i, word in enumerate(got) if word != expected.get(i, F.SENTINEL)] + assert not bad, bad[:8] + print(f'native_fma_f16_opsel hardware matched {len(want)} cases across {F.GROUPS} groups') + return 0 + + +def main(mode, tool, sdk=None): + code, want = program() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'ir': + return ir(tool, work, code, want) + assert mode == 'hardware' and sdk is not None + return hardware(tool, sdk, work, code, want) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_fract_f16_check.py b/tests/native_fract_f16_check.py new file mode 100644 index 0000000000..1fe6fa96e5 --- /dev/null +++ b/tests/native_fract_f16_check.py @@ -0,0 +1,318 @@ +"""Direct DXIL VOP1/VOP3 v_fract_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from fractions import Fraction +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile +from unittest import mock + +from f16_packed_model import h2f, round_exact +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_VOP1_FRACT_F16 = 0x5F +OP_VOP3_FRACT_F16 = 0x1DF +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + + +def vop1_fract_f16(dst, src0): + return [0x7E000000 | ((dst & 0xFF) << 17) | (OP_VOP1_FRACT_F16 << 9) | (src0 & 0x1FF)] + + +def vop3_fract_f16(dst, src0, *, abs_=0, neg=0, op_sel=0, clamp=0, omod=0, s1=0, s2=0): + w0 = (0xD4000000 | (OP_VOP3_FRACT_F16 << 16) | ((clamp & 1) << 15) | ((op_sel & 15) << 11) | + ((abs_ & 7) << 8) | (dst & 0xFF)) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def eval_fract_f16(raw_word, *, abs_=0, neg=0, op_sel=0, clamp=0, dst_init=DST_INIT): + bits = (raw_word >> (16 if (op_sel & 1) else 0)) & 0xFFFF + if abs_ & 1: + bits &= 0x7FFF + if neg & 1: + bits ^= 0x8000 + if (bits & 0x7FFF) >= 0x7C00: + res = 0x0000 if clamp else 0x7E00 + else: + x = Fraction(h2f(bits)) + diff = x - math.floor(x) + res = 0x0000 if diff == 0 else min(round_exact(diff), 0x3BFF) + if op_sel & 8: + return ((res & 0xFFFF) << 16) | (dst_init & 0xFFFF) + return (dst_init & 0xFFFF0000) | (res & 0xFFFF) + + +@dataclass(frozen=True) +class Case: + name: str + src0: int + val0: int + wide: bool = False + abs_: int = 0 + neg: int = 0 + op_sel: int = 0 + clamp: int = 0 + exec_mask: int = ALL_EXEC + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + raw = self.val0 & 0xFFFFFFFF if (self.src0 < 128 or self.src0 >= 255) else inline_word(self.src0) + return eval_fract_f16(raw, abs_=self.abs_, neg=self.neg, op_sel=self.op_sel, clamp=self.clamp) + + +def all_cases(): + return [ + # 1. Positive fractions and exact positive integers (with nonzero unused high halves on op_sel[0]=0 VGPR reads). + Case('pos_zero', 257, 0x0000), + Case('pos_frac_mixed', 257, 0x7BFF3D00), # 1.25 -> 0.25 (hi=65504 ignored) + Case('pos_exact_one', 257, 0x3C00), # 1.0 -> +0.0 + Case('pos_exact_max', 257, 0x7BFF), # 65504 -> +0.0 + # 2. Negative fractions and exact negative integers (-0.0, -1.0, -65504). + Case('neg_zero', 257, 0x8000), # -0.0 -> +0.0 + Case('neg_quarter', 257, 0x7BFFB400), # -0.25 -> 0.75 (hi=65504 ignored) + Case('neg_1_75', 257, 0xBF00), # -1.75 -> 0.25 + Case('neg_exact_one', 257, 0xBC00), # -1.0 -> +0.0 + Case('neg_exact_max', 257, 0xFBFF), # -65504 -> +0.0 + # 3. Tiny negatives: x - floor(x) near 1.0 (0x3bff clamp + RNE-vs-truncation discriminators). + Case('tiny_neg_2_m11', 257, 0x9000), # -2^-11 -> 0x3bff exact + Case('tiny_neg_2_m12', 257, 0x8C00), # -2^-12 (rounds to 1.0 without clamp) -> 0x3bff + Case('tiny_neg_5_m12', 257, 0x9500), # -5*2^-12 (halfway tie -> 0x3bfe under RNE vs 0x3bfd trunc) + Case('tiny_neg_9_m13', 257, 0x9480), # -9*2^-13 (rounds to 0x3bfe under RNE vs 0x3bfd trunc) + Case('tiny_neg_min_subnormal', 257, 0x8001), # -2^-24 -> 0x3bff + # 4. Positive binary16 subnormal preserved as exact fraction. + Case('pos_min_subnormal', 257, 0x0001), + # 5. Non-finite inputs (+Inf, -Inf, NaN -> 0x7e00 or +0.0 with clamp) and finite clamp=1 preservation. + Case('pos_inf', 257, 0x7C00), + Case('neg_inf', 257, 0xFC00), + Case('nan_payload', 257, 0x7E01), + Case('vop3_clamp_inf_and_neg', 257, 0xFC00, wide=True, clamp=1), + Case('vop3_clamp_nan', 257, 0x7E01, wide=True, clamp=1), + Case('vop3_clamp_pos', 257, 0x7BFF3D00, wide=True, clamp=1), + Case('vop3_clamp_neg', 257, 0x7BFFB400, wide=True, clamp=1), + # 6. VOP3 modifiers: separate abs, neg, and high-half op_sel[0]/op_sel[3] preserving D[15:0]. + Case('vop3_abs', 257, 0x7BFFB400, wide=True, abs_=1), # abs(-0.25) = 0.25 -> 0.25 + Case('vop3_neg', 257, 0x7BFF3400, wide=True, neg=1), # neg(0.25) = -0.25 -> 0.75 + Case('vop3_opsel_hi_src', 257, 0x3D003C00, wide=True, op_sel=0b0001), + Case('vop3_opsel_hi_dst', 257, 0x3C003D00, wide=True, op_sel=0b1000), + Case('vop3_opsel_hi_rw', 257, 0x3D00BEEF, wide=True, op_sel=0b1001), + # 7. SGPR, literal (255), inline binary16 float (248=0x3118) and inline integer subnormal (129=0x0001). + Case('sgpr_src0', 10, 0xB400), + Case('literal_src0', 255, 0x8C00), + Case('inline_f16_248', 248, 0), + Case('inline_int_129', 129, 0), + # 8. Partial EXEC_LO mask: inactive lanes keep DST_INIT. + Case('partial_exec', 257, 0x7BFF3D00, exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + if c.src0 >= 256: + code += F.mov(c.src0 - 256, c.val0) + elif c.src0 <= 105: + code += F.smov(c.src0, c.val0) + elif c.src0 == 255: + lit_tail = [c.val0] + if c.wide: + code += vop3_fract_f16(4, c.src0, abs_=c.abs_, neg=c.neg, op_sel=c.op_sel, clamp=c.clamp) + else: + code += vop1_fract_f16(4, c.src0) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = vop1_fract_f16(4, 257) + [0xBF810000] + return [ + # VOP3 output modifier omod != 0. + (vop3_fract_f16(4, 257, omod=1) + [0xBF810000], 'unsupported v_fract_f16 omod'), + # Unused VOP3 operand modifier/op_sel bits. + (vop3_fract_f16(4, 257, op_sel=0b0010) + [0xBF810000], 'unsupported v_fract_f16 operand modifiers'), + (vop3_fract_f16(4, 257, s1=258) + [0xBF810000], 'unsupported v_fract_f16 operand modifiers'), + # High-half op_sel on non-VGPR source. + (vop3_fract_f16(4, 10, op_sel=0b0001) + [0xBF810000], + 'unsupported v_fract_f16 high-half op_sel on non-VGPR source'), + # DPP16 and SDWA forms. + (vop1_fract_f16(4, 250) + [0xFF00E401, 0xBF810000], 'unsupported DPP arithmetic'), + (vop1_fract_f16(4, 249) + [0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar source (vcc_lo). + (vop1_fract_f16(4, 106) + [0xBF810000], 'unsupported v_fract_f16 source'), + # Unsupported binary16 rounding/denorm modes and dynamic conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def _exec_with_floor(orig_exec): + def wrapped(line, values, memory, stores): + if 'unary.f32(i32 27,' in line: + name, rhs = [part.strip() for part in line.split('=', 1)] + token = re.search(r'i32 27,\s*float ([^,\s\)]+)\)', rhs).group(1) + if token.startswith('%'): + kind, bits = values[token] + assert kind == 'float', line + else: + bits = struct.unpack('<I', struct.pack('<f', float(token)))[0] + val = struct.unpack('<f', struct.pack('<I', bits))[0] + if not (math.isnan(val) or math.isinf(val) or val == 0.0): + bits = struct.unpack('<I', struct.pack('<f', float(math.floor(val))))[0] + values[name] = ('float', bits) + return + orig_exec(line, values, memory, stores) + return wrapped + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'fract-f16') + assert run.returncode == 0, run.stderr + with mock.patch.object(F, '_exec', _exec_with_floor(F._exec)): + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_fract_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'legacyF16ToF32' in dump and 'fsub float' in dump and 'unary.f32(i32 27,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_fract_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_fract_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'fract-f16-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_fract_f16 pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_fract_f32_check.py b/tests/native_fract_f32_check.py new file mode 100644 index 0000000000..305f41afd0 --- /dev/null +++ b/tests/native_fract_f32_check.py @@ -0,0 +1,124 @@ +"""Direct DXIL fract's strict upper bound, NaNs and output modifier order. + +The source-built VOP1 and VOP3 instructions write 32 words per lane in two +wave32 groups. Tiny negative values make a host Frc round to 1.0; gfx1013 +instead returns the greatest binary32 below 1.0. A NaN must stay a NaN. +""" +import math +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_dpp_quad_check import request +from native_frexp_f32_check import v_mov_lit, vop1, vop3_unary +from native_mad32_check import PROLOGUE + +INPUTS = (0xb0800000, 0xb1800000, 0x3e800000, 0xbe800000, + 0, 0x80000000, 0x7fc12345, 0xc0400000) +CAP = 0x3f7fffff +SENTINEL = 0x69696969 +WORDS = 2064 + + +def bits(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def value(word): + return struct.unpack('<f', struct.pack('<I', word))[0] + + +def fract(word, *, cap=True, nan_to_cap=False): + x = value(word) + if math.isnan(x): + return CAP if nan_to_cap else 0x7fc00000 + result = bits(x - math.floor(x)) + if not result & 0x7fffffff: + result = 0 # floor retains -0, so subtracting that same zero yields +0. + return CAP if cap and value(result) >= 1.0 else result + + +def expected_row(word, **mutation): + plain = fract(word, **mutation) + negated = fract(word ^ 0x80000000, **mutation) + clamped = bits(0.0 if math.isnan(value(plain)) else value(plain)) + scaled = bits(value(plain) * 2.0) + return plain, negated, clamped, scaled + + +def reference(**mutation): + row = [v for word in INPUTS for v in expected_row(word, **mutation)] + return [SENTINEL] * 8 + row * 64 + [SENTINEL] * 8 + + +def program(): + code = list(PROLOGUE) + for ci, word in enumerate(INPUTS): + code += v_mov_lit(1, word) + forms = ([vop1(0x20, 3, 257)], + vop3_unary(0x1a0, 3, 257, neg0=1), + vop3_unary(0x1a0, 3, 257, clamp=1), + vop3_unary(0x1a0, 3, 257, omod=1)) + for fi, form in enumerate(forms): + code += form + [0xe0701000 | (4 * (4 * ci + fi)), 0x80080308] + return code + [0xbf810000] + + +def is_nan(word): + return (word & 0x7fffffff) > 0x7f800000 + + +def matches(actual, expected): + return len(actual) == len(expected) and all( + a == e or (is_nan(a) and is_nan(e)) for a, e in zip(actual, expected)) + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = work / 'fract.cso' + subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], check=True) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], + capture_output=True, text=True, check=True).stdout + assert 'Frc(value)' in dump, dump + # Ordered comparison preserves NaN. The cap precedes the output scale + # and clamp, which the hardware mode checks through the stored words. + assert 'fcmp oge float' in dump and '1065353215 to float' in dump, 'missing ordered upper bound' + expected = reference() + assert not matches(reference(cap=False), expected), 'uncapped Frc escaped' + assert not matches(reference(nan_to_cap=True), expected), 'NaN-losing minimum escaped' + print('fract DXIL validates; uncapped and NaN-losing references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'readback.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{WORDS}I', output.read_bytes()) + expected = reference() + if not matches(actual, expected): + bad = [(i, f'{a:08x}', f'{e:08x}') for i, (a, e) in enumerate(zip(actual, expected)) + if a != e and not (is_nan(a) and is_nan(e))] + raise AssertionError(f'{len(bad)}/{WORDS} words differ: {bad[:12]}') + print('fract e32/e64: 2048 words and 16 guards matched (NaN by class)') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_fract_f32_') as temp: + work = Path(temp) + source = work / 'root.hlsl' + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', + '-Fo', root, source], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(*sys.argv[1:])) diff --git a/tests/native_frexp_f16_check.py b/tests/native_frexp_f16_check.py new file mode 100644 index 0000000000..1fd2d45f1d --- /dev/null +++ b/tests/native_frexp_f16_check.py @@ -0,0 +1,194 @@ +"""Direct compute v_frexp_mant_f16 and v_frexp_exp_i16_f16 (VOP1 and VOP3A, high-half preserving).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +HIGH_SEED = 0xBEEF0000 + +CASES = ( + 0xCAFE0000, # +0.0h (with high junk in src0) + 0x12348000, # -0.0h + 0x00003C00, # +1.0h -> mant=0.5h (0x3800), exp=1 + 0x5555C200, # -3.0h -> mant=-0.75h (0xBA00), exp=2 + 0x00000400, # smallest normal 2^-14 -> mant=0.5h, exp=-13 + 0x00000200, # largest subnormal 2^-15 -> mant=0.5h, exp=-14 + 0x00008001, # smallest negative subnormal -2^-24 -> mant=-0.5h (0xB800), exp=-23 + 0x00007C00, # +Inf -> mant=+Inf (clamped to 1.0h = 0x3C00), exp=0 +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_unary(op, vdst, src0, *, abs0=0, neg0=0, clamp=0, omod=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | ((abs0 & 1) << 8) | (vdst & 0xFF) + w1 = ((neg0 & 1) << 29) | ((omod & 3) << 27) | (src0 & 0x1FF) + return [w0, w1] + + +def program(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, bits in enumerate(CASES): + code += v_mov_lit(2, bits) + # 0: VOP1 v_frexp_exp_i16_f16 v4, v2 (pre-seed v4 high half) + code += v_mov_lit(4, HIGH_SEED | 0x1111) + [vop1(0x5A, 4, 258), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + # 1: VOP1 v_frexp_mant_f16 v4, v2 + code += v_mov_lit(4, HIGH_SEED | 0x2222) + [vop1(0x59, 4, 258), 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + # 2: VOP3A v_frexp_exp_i16_f16 v4, -v2 + code += v_mov_lit(4, HIGH_SEED | 0x3333) + vop3_unary(0x1DA, 4, 258, neg0=1) + [0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + # 3: VOP3A v_frexp_mant_f16 v4, |v2| clamp + code += v_mov_lit(4, HIGH_SEED | 0x4444) + vop3_unary(0x1D9, 4, 258, abs0=1, clamp=1) + [0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def frexp_f16(bits, *, flush_denormals=False, clamp=False): + bits &= 0xFFFF + sign = bits & 0x8000 + exp = (bits >> 10) & 0x1F + mant = bits & 0x3FF + if exp == 0x1F or (bits & 0x7FFF) == 0: + out_exp, out_mant = 0, bits + elif exp == 0: + if flush_denormals: + out_exp, out_mant = 0, sign + else: + steps = 0 + x = mant + while (x & 0x400) == 0: + x <<= 1 + steps += 1 + out_exp = (1 - steps - 14) & 0xFFFF + out_mant = sign | 0x3800 | (x & 0x3FF) + else: + out_exp = (exp - 14) & 0xFFFF + out_mant = sign | 0x3800 | mant + if clamp: + abs_m = out_mant & 0x7FFF + if abs_m > 0x7C00 or (out_mant & 0x8000): + out_mant = 0 + elif out_mant > 0x3BFF: + out_mant = 0x3C00 + return out_exp, out_mant + + +def reference(*, flush_denormals=False, no_clamp=False, zero_high=False): + hi = 0 if zero_high else HIGH_SEED + words = [SENTINEL] * 8 + for _lane in range(64): + for bits in CASES: + e0, m0 = frexp_f16(bits, flush_denormals=flush_denormals) + e_neg, _ = frexp_f16((bits & 0xFFFF) ^ 0x8000, flush_denormals=flush_denormals) + _, m_abs_clamp = frexp_f16(bits & 0x7FFF, flush_denormals=flush_denormals, clamp=not no_clamp) + words.extend((hi | e0, hi | m0, hi | e_neg, hi | m_abs_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump, dump + for tag, bad, msg in ( + ('exp_clamp', vop3_unary(0x1DA, 4, 258, clamp=1) + [0xBF810000], 'unsupported v_frexp_exp_i16_f16 operand modifiers'), + ('mant_omod', vop3_unary(0x1D9, 4, 258, omod=1) + [0xBF810000], 'unsupported v_frexp_mant_f16 operand modifiers'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), (tag, bad_res.stdout, bad_res.stderr) + assert reference() != reference(flush_denormals=True) + assert reference() != reference(no_clamp=True) + assert reference() != reference(zero_high=True) + print('v_frexp_mant_f16/exp_i16_f16 DXIL verified; invalid modifiers refused; denormal, clamp and high-half controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print('v_frexp_mant_f16/exp_i16_f16: 2048 result words (high halves kept) and 16 guards matched') + return 0 + + +def ir(dumper): + """No GPU and no DXC: evaluate lane 0 of the module the direct frontend builds. + + An inline float source (240-248) is a binary16 operand here, so it must read the binary16 value + of the constant (as v_add_f16 does), not the low half of its f32 pattern. + """ + from native_direct_container_check import words + from native_f16_alu_check import INLINE_F16, SHIFT, compute_container, interpret, store + from native_scalar_lds_check import scalar, sop1, vmove + + # Pinned rows, independent of the lowering: 1.0 = 0.5 * 2^1 and 1/(2pi) = 0x3118 = 0.6367 * 2^-2. + assert frexp_f16(0x3C00) == (1, 0x3800) and frexp_f16(0x3118) == (0xFFFE, 0x3918) + cases = [] + for src, half in INLINE_F16.items(): + cases.append(([vop1(0x59, 3, src)], frexp_f16(half)[1])) + cases.append(([vop1(0x5A, 3, src)], frexp_f16(half)[0])) + cases.append((vop3_unary(0x1D9, 3, 245, abs0=1, clamp=1), frexp_f16(0x4000, clamp=True)[1])) # |-2.0| clamp + cases.append((vop3_unary(0x1D9, 3, 242, neg0=1), frexp_f16(0xBC00)[1])) # -1.0 + cases.append((vop3_unary(0x1DA, 3, 248, neg0=1), frexp_f16(0xB118)[0])) # -1/(2pi) + cases.append((v_mov_lit(1, 0x12343C00) + [vop1(0x59, 3, 257)], 0x3800)) # VGPR source + code = [sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 128 + SHIFT), vmove(8, 7), sop1(3, 126, 129)] + want = [] + for k, (op, result) in enumerate(cases): + code += v_mov_lit(3, HIGH_SEED | (0x1000 + k)) + op + store(4 * k, 3) + want.append(HIGH_SEED | result) + code.append(0xBF810000) + with tempfile.TemporaryDirectory(prefix='x2w_native_frexp_f16_ir_') as temp: + path = Path(temp) / 'frexp.cdx' + path.write_bytes(compute_container(words(*code))) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, run.stderr + stores = sorted(interpret(run.stdout)) + assert [address for address, _ in stores] == [4 * k for k in range(len(want))], stores[:4] + bad = [(k, f'{got:08x}', f'{expected:08x}') for k, ((_, got), expected) in enumerate(zip(stores, want)) + if got != expected] + assert not bad, bad + print(f'v_frexp_mant_f16/exp_i16_f16 IR: {len(want)} results matched, inline floats read as binary16') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_frexp_f16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + raise SystemExit(ir(sys.argv[2])) + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_frexp_f32_check.py b/tests/native_frexp_f32_check.py new file mode 100644 index 0000000000..c6e6e0bfc1 --- /dev/null +++ b/tests/native_frexp_f32_check.py @@ -0,0 +1,147 @@ +"""Direct compute v_frexp_exp_i32_f32 and v_frexp_mant_f32 (VOP1 and VOP3A).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 + +CASES = ( + 0x00000000, # +0.0 + 0x80000000, # -0.0 + 0x3F800000, # +1.0 -> mant=0.5, exp=1 + 0xC0400000, # -3.0 -> mant=-0.75, exp=2 + 0x00800000, # smallest normal 2^-126 -> mant=0.5, exp=-125 + 0x00400000, # largest subnormal 2^-127 -> mant=0.5, exp=-126 + 0x80000001, # smallest negative subnormal -2^-149 -> mant=-0.5, exp=-148 + 0x7F800000, # +Inf -> mant=+Inf (clamped to 1.0), exp=0 +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_unary(op, vdst, src0, *, abs0=0, neg0=0, clamp=0, omod=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | ((abs0 & 1) << 8) | (vdst & 0xFF) + w1 = ((neg0 & 1) << 29) | ((omod & 3) << 27) | (src0 & 0x1FF) + return [w0, w1] + + +def program(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, bits in enumerate(CASES): + code += v_mov_lit(2, bits) + # 0: VOP1 v_frexp_exp_i32_f32 v4, v2 + code += [vop1(0x3F, 4, 258), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + # 1: VOP1 v_frexp_mant_f32 v4, v2 + code += [vop1(0x40, 4, 258), 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + # 2: VOP3A v_frexp_exp_i32_f32 v4, -v2 (negated input) + code += vop3_unary(0x1BF, 4, 258, neg0=1) + [0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + # 3: VOP3A v_frexp_mant_f32 v4, |v2| clamp + code += vop3_unary(0x1C0, 4, 258, abs0=1, clamp=1) + [0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def frexp_f32(bits, *, flush_denormals=False, clamp=False): + sign = bits & 0x80000000 + exp = (bits >> 23) & 0xFF + mant = bits & 0x7FFFFF + if exp == 0xFF or (bits & 0x7FFFFFFF) == 0: + out_exp, out_mant = 0, bits + elif exp == 0: + if flush_denormals: + out_exp, out_mant = 0, sign + else: + steps = 0 + x = mant + while (x & 0x800000) == 0: + x <<= 1 + steps += 1 + out_exp = (1 - steps - 126) & MASK + out_mant = sign | 0x3F000000 | (x & 0x7FFFFF) + else: + out_exp = (exp - 126) & MASK + out_mant = sign | 0x3F000000 | mant + if clamp: + abs_m = out_mant & 0x7FFFFFFF + if abs_m > 0x7F800000 or (out_mant & 0x80000000): + out_mant = 0 + elif out_mant > 0x3F7FFFFF: + out_mant = 0x3F800000 + return out_exp, out_mant + + +def reference(*, flush_denormals=False, no_clamp=False): + words = [SENTINEL] * 8 + for _lane in range(64): + for bits in CASES: + e0, m0 = frexp_f32(bits, flush_denormals=flush_denormals) + e_neg, _ = frexp_f32(bits ^ 0x80000000, flush_denormals=flush_denormals) + _, m_abs_clamp = frexp_f32(bits & 0x7FFFFFFF, flush_denormals=flush_denormals, clamp=not no_clamp) + words.extend((e0, m0, e_neg, m_abs_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump, dump + for tag, bad, msg in ( + ('exp_clamp', vop3_unary(0x1BF, 4, 258, clamp=1) + [0xBF810000], 'unsupported v_frexp_exp_i32_f32 operand modifiers'), + ('mant_omod', vop3_unary(0x1C0, 4, 258, omod=1) + [0xBF810000], 'unsupported v_frexp_mant_f32 operand modifiers'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), (tag, bad_res.stdout, bad_res.stderr) + assert reference() != reference(flush_denormals=True) + assert reference() != reference(no_clamp=True) + print('v_frexp_exp_i32_f32/mant_f32 DXIL verified; invalid modifiers refused; denormal and clamp controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print('v_frexp_exp_i32_f32/mant_f32: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_frexp_f32_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_frozen_request_check.cpp b/tests/native_frozen_request_check.cpp new file mode 100644 index 0000000000..7a86aa7b3f --- /dev/null +++ b/tests/native_frozen_request_check.cpp @@ -0,0 +1,54 @@ +#include "frozen_compute_requests.h" +#include <cstring> +#include <iostream> +#include <stdexcept> + +namespace { +x2w::ComputeRequest fixture(uint64_t key) { + x2w::ComputeRequest r{"code", "data", "root", std::string(96, 0), std::string(28, 0), {}, key}; + const auto length = [&](size_t offset, uint64_t n) { std::memcpy(r.description.data() + offset, &n, sizeof(n)); }; + length(48, r.code.size()); + length(64, r.data.size()); + length(16, r.sa.size()); + return r; +} +void require(bool ok, const char *reason) { + if (!ok) throw std::runtime_error(reason); +} +} + +int main() { + try { + x2w::FrozenComputeRequests pool(4096, 2); + auto first = fixture(1); + pool.put(first); + first.code[0] = 'x'; + auto saved = pool.take(1); + require(saved && saved->code == "code", "snapshot changed with caller"); + x2w::validate_compute_request_shape(*saved); + require(!pool.take(1), "consumed snapshot still present"); + pool.put(first); + pool.put(fixture(2)); + pool.put(fixture(2)); + pool.put(fixture(3)); + require(!pool.take(1) && pool.take(2) && pool.take(3), "FIFO eviction or duplicate key failed"); + auto stats = pool.stats(); + require(stats.hits == 3 && stats.misses == 2 && stats.evicted == 1 && !stats.bytes && !stats.entries, + "handoff accounting mismatch"); + x2w::FrozenComputeRequests tiny(32), disabled(0); + tiny.put(first); + disabled.put(first); + require(!tiny.take(1) && !disabled.enabled() && !disabled.take(1), "byte budget exceeded"); + auto broken = *saved; + broken.description[48] ^= 1; + try { + x2w::validate_compute_request_shape(broken); + } catch (const std::runtime_error &) { + return 0; + } + throw std::runtime_error("inconsistent description accepted"); + } catch (const std::exception &e) { + std::cerr << e.what() << '\n'; + return 1; + } +} diff --git a/tests/native_gather_compare_check.py b/tests/native_gather_compare_check.py new file mode 100644 index 0000000000..e60de81db9 --- /dev/null +++ b/tests/native_gather_compare_check.py @@ -0,0 +1,94 @@ +"""image_gather4_c_lz in the direct C++ image path (#2969). + + native_gather_compare_check.py <compile_dxil> <sdk bin dir> <native_recording_check> + +image_gather4_c_lz compares the red component of the four texels of a gather footprint at the view's first mip +against a reference, the first address dword, and returns the four results. The direct frontend lowers +it to DXIL textureGatherCmp (opcode 74) with channel 0, the comparison sampler under the existing comparison field +checks and the base-level sampler fix of image_gather4_lz, on 2D and 2D-array images with dmask 0x1. The programs +reuse comparison_program() of native_direct_container_check.py (clamp X/Y, point with TRUNC_COORD, LESS). + +Checks: a compute container compiles and its module calls textureGatherCmp with channel 0, u and v from v1 and v2 +and the reference v0 as compare value (the same program with image_sample_c_lz compiles as a control); refusals by +message for dmask 0x2, a cube and a 3D image, d16, image_gather4_c (implicit LOD), _c_l and _c_b; and, +through native_recording_check --graphics-sampler, WARP creates the graphics pipeline of the program of +native_graphics_comparison_pso_warp with the comparison sample replaced by this gather. +""" +import pathlib +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import comparison_program, compute, patched_pixel, vertex, words + +REFUSED = 'direct image opcode or descriptor modifiers' + + +def main(compiler, sdk, probe): + sdk = pathlib.Path(sdk) + with tempfile.TemporaryDirectory() as tmp: + folder = pathlib.Path(tmp) + + def compile_cs(label, code): + marker = folder / (label + '.cdx') + marker.write_bytes(compute(words(*code, 0x7e0a0300, 0xbf810000), table=True)) + run = subprocess.run([compiler, sdk, folder / 'cache', 'gfx1013-container-cs', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + return marker.with_suffix('.cso'), run + + cso, run = compile_cs('gather', comparison_program(op=79)) + assert run.returncode == 0, run.stderr + dump = subprocess.run([sdk / 'dxc.exe', '-dumpbin', cso], capture_output=True, text=True, check=True).stdout + calls = [line for line in dump.splitlines() if '@dx.op.textureGatherCmp.f32(i32 74' in line] + assert len(calls) == 1, dump + # The module keeps VGPRs in allocas %r256 (v0) and up. Each float argument must be a bitcast of a load of the + # matching register: u = v1, v = v2, two undef components, then zero offsets, channel 0 and the reference v0. + casts = dict(re.findall(r'(%[\w.]+) = bitcast i32 (%[\w.]+) to float', dump)) + loads = dict(re.findall(r'(%[\w.]+) = load i32, i32\* %r(\d+),', dump)) + args = re.search(r'textureGatherCmp\.f32\(i32 74, ([^)]*)\)', calls[0]).group(1).split(', ') + floats = [a.split(' ', 1)[1] for a in args if a.startswith('float ')] + sources = ['v%d' % (int(loads[casts[f]]) - 256) if f in casts else f for f in floats] + assert sources == ['v1', 'v2', 'undef', 'undef', 'v0'], (sources, calls[0]) + assert args[-4:-1] == ['i32 0', 'i32 0', 'i32 0'], args + assert 'textureGather.f32' not in dump and 'sampleCmp' not in dump, dump + _, run = compile_cs('sample_c_lz', comparison_program(op=47)) + assert run.returncode == 0, run.stderr + print('module: one textureGatherCmp with channel 0') + + base = comparison_program(op=79) + image = base[-2] + cases = [('dmask 0x2', image & ~0xf00 | 0x200, base[-1], REFUSED), + ('cube', image & ~0x38 | 3 << 3, base[-1], REFUSED), + ('3D', image & ~0x38 | 2 << 3, base[-1], REFUSED), + ('d16', image, base[-1] | 0x80000000, 'unsupported image dimension or D16')] # refused at decode + cases += [(name, image & ~(0x7f << 18) | op << 18, base[-1], REFUSED) + for name, op in (('image_gather4_c', 72), ('image_gather4_c_l', 76), ('image_gather4_c_b', 77))] + for label, word, second, message in cases: + _, run = compile_cs(label.replace(' ', '_'), [*base[:-2], word, second]) + assert run.returncode and message in run.stderr, (label, run.stdout, run.stderr) + _, run = compile_cs('array', [*base[:-2], image & ~0x38 | 5 << 3, base[-1]]) + assert run.returncode == 0, run.stderr + print('refused: dmask 0x2, cube, 3D, d16, image_gather4_c, _c_l and _c_b; a 2D array compiles') + + # The program of native_graphics_comparison_pso_warp, with image_sample_c_lz (47) replaced by the gather. + code = [*comparison_program(op=79), 0xf09c0108, 0x00220500, 0x06000b04] + vs, ps, root = (folder / name for name in ('vertex', 'pixel', 'root.bin')) + vs_code = [0xbe810380, 0xf40c0200, 0xfa000040, 0x7e020280, 0x7e040280, + 0xf0200108, 0x80020201, 0x7e020b00, 0xf80008cf, 0x01010101, 0xbf810000] + vs.write_bytes(vertex(program=vs_code, table=True)) + code += [0xf40c0200, 0xfa000020, 0xf0200108, 0x80020400] + ps.write_bytes(patched_pixel(len(code), code, True)) + source = folder / 'root.hlsl' + source.write_text('#define RS "DescriptorTable(SRV(t0), UAV(u0, numDescriptors=2))"\n') + subprocess.run([sdk / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', source, '-Fo', root], check=True) + run = subprocess.run([probe, '--graphics-sampler', sdk, vs, ps, root, folder / 'cache'], + capture_output=True, text=True) + print(run.stdout.strip()) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, (run.returncode, run.stdout, run.stderr) + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_gather_lod_check.py b/tests/native_gather_lod_check.py new file mode 100644 index 0000000000..bcf5e97591 --- /dev/null +++ b/tests/native_gather_lod_check.py @@ -0,0 +1,185 @@ +"""Compare direct DXIL 2D image_gather4_l against independent mip/tap references.""" +from dataclasses import dataclass +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import compute_gather4_l_check as compute_data +from native_direct_container_check import compute, patched_pixel, words +from pixel_gather_check import SIDE, texel, write_case +from startup_compute_gather_l_check import reference as compute_reference + + +@dataclass(frozen=True) +class Case: + name: str + lod: float + relative: int + channel: int + first: int = 1 + uv: tuple[float, float] = (0.546875, 0.546875) + max_lod: int = 512 # unsigned 4.8 + + +CASES = ( + Case('view_first', 0.0, 0, 0), + Case('view_next', 1.0, 1, 1), + Case('view_last', 7.0, 1, 2, max_lod=0xFFF), + Case('half_up', 0.5, 1, 3), + Case('below_half', 0.499, 0, 1), + Case('negative_lod', -1.0, 0, 2), + Case('sampler_limit', 1.0, 0, 3, max_lod=127), + Case('outside_uv', 0.0, 0, 0, uv=(-1.0e30, 1.25)), + Case('nonfinite_uv', 0.0, 0, 1, uv=(float('nan'), 0.546875)), + Case('nonfinite_lod', float('inf'), 0, 2), + Case('full_view', 2.0, 2, 0, first=0), +) +ORDER = ((0, 1), (1, 1), (1, 0), (0, 0)) + + +def float_bits(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def program(case, stage, *, dim=1, mask=None, flags=0, sampler=0x12, filter_word=0x04500000, + override_descriptor=False, dynamic=False): + code = [0xBE810380, 0xF40C0200, 0xFA000000] # read the texture descriptor into s[8:15] + if stage == 'cs': + code += [0xF4080800, 0xFA000020] # output descriptor s[32:35] + # Save the lane's byte offset and LOD before overwriting v0 with U. + code += [0x34060084, 0x7E040D00] if dynamic else [0x7E060280] + if override_descriptor: + code.append(0xBE8E0380) # clobber s14 without changing the descriptor base + for reg, value in enumerate((sampler, case.max_lod << 12, filter_word, 0), start=4): + code += [0xBE8003FF | reg << 16, value] + for reg, value in enumerate(case.uv if dynamic else (*case.uv, case.lod)): + code += [0x7E0002FF | reg << 17, float_bits(value)] + mask = 1 << case.channel if mask is None else mask + code += [0xBF8CC07F, 0xF0000000 | 68 << 18 | dim << 3 | mask << 8 | flags, 0x00220400, 0xBF8C3F70] + if stage == 'cs': + return compute(words(*code, 0xE0781000, 0x80080403, 0xBF810000), threads=4 if dynamic else 1, table=True) + return patched_pixel(len(code), code, table=True, export=(0xF800180F, 0x07060504)) + + +def compile_shader(cli, sdk, work, case, stage, **overrides): + source = work / f'{case.name}-{stage}' + source.write_bytes(program(case, stage, **overrides)) + cso = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', f'gfx1013-container-{stage}', source, cso], + capture_output=True, text=True, timeout=30) + return cso, run + + +def controls(cli, sdk, work): + for stage in ('ps', 'cs'): + shader, run = compile_shader(cli, sdk, work, CASES[1], stage) + assert run.returncode == 0 and shader.is_file(), run.stdout + run.stderr + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', shader], check=True, + capture_output=True, text=True).stdout + assert dump.count('call %dx.types.ResRet.f32 @dx.op.textureLoad.f32(') == 4, dump + assert dump.count('call %dx.types.Dimensions @dx.op.getDimensions(') == 2, dump + assert '@dx.op.textureGather' not in dump, dump + for overrides, reason in ( + ({'dim': 5}, 'explicit 2D gather operands'), + ({'mask': 3}, 'explicit 2D gather operands'), + ({'flags': 0x1000}, 'explicit 2D gather operands'), + ({'sampler': 0x13}, 'explicit 2D gather sampler'), + ({'filter_word': 0x08500000}, 'explicit 2D gather sampler'), + ({'filter_word': 0x14500000}, 'explicit 2D gather sampler'), + ({'override_descriptor': True}, 'non-contiguous resource descriptor'), + ): + _, run = compile_shader(cli, sdk, work, CASES[1], stage, **overrides) + assert run.returncode and reason in run.stderr, (stage, overrides, run.stderr) + print('both stages emitted four loads and rejected seven unsupported cases') + + +def taps(case): + if not all(map(math.isfinite, (*case.uv, case.lod))): + return (0.0,) * 4 + # The pixel helper loads the first payload into MostDetailedMip. + # Payload dimensions and texel tags therefore start at relative mip zero. + level = case.relative + extent = SIDE >> level + x, y = (math.floor(value * extent - 0.5) for value in case.uv) + return tuple(texel(level, min(max(x + dx, 0), extent - 1), min(max(y + dy, 0), extent - 1), case.channel) + for dx, dy in ORDER) + + +def render(renderer, adapter, operation, *args): + run = subprocess.run([renderer, adapter, operation, *args], capture_output=True, text=True, timeout=30) + if run.returncode == 77: + print(run.stdout + run.stderr, end='') + raise SystemExit(77) + return run + + +def render_compute(renderer, adapter, shader, reference, first, expected): + flags = compute_data.FLOAT_TEXTURE_FLAG | (compute_data.VIEW_MIP1_FLAG if first else 0) + reference.write_bytes(words(compute_data.GROUPS | flags, *expected, *compute_data.texels())) + return render(renderer, adapter, '--compute-texture-case', shader, reference) + + +def draw(cli, sdk, renderer, adapter, stage, work): + if stage == 'cs': + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + for case in CASES: + shader, run = compile_shader(cli, sdk, work, case, stage) + assert run.returncode == 0, (case.name, run.stdout, run.stderr) + reference = work / 'expected.bin' + if stage == 'ps': + write_case(reference, 3 - case.first, case.first, [taps(case)] * (SIDE ** 2)) + result = render(renderer, adapter, '--check-pixel-gather', shader, reference) + assert result.returncode == 0 and 'pixels=64 channels=256 max_absolute_error=0' in result.stdout, ( + case.name, result.stdout, result.stderr) + else: + finite = all(map(math.isfinite, (*case.uv, case.lod))) + expected = (compute_reference(case.first + case.relative, case.channel, case.uv) + if finite else [0] * 4 + [compute_data.SENTINEL] * 316) + result = render_compute(renderer, adapter, shader, reference, case.first, expected) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + case.name, result.stdout, result.stderr) + if 'debug_layer=enabled' in result.stdout: + assert 'debug_errors=0 debug_warnings=0' in result.stdout, result.stdout + print(f'{stage} {case.name}: exact readback') + if stage == 'cs': + case = Case('dynamic_lod', 0.0, 0, 1) + shader, run = compile_shader(cli, sdk, work, case, stage, dynamic=True) + assert run.returncode == 0, run.stdout + run.stderr + expected = [tap for level in (1, 2, 2, 2) for tap in compute_reference(level, case.channel, case.uv)[:4]] + expected += [compute_data.SENTINEL] * 304 + result = render_compute(renderer, adapter, shader, reference, case.first, expected) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + result.stdout, result.stderr) + print('cs dynamic LOD: four lanes selected resource mips 1, 2, 2, 2') + # Keep the mip-1 expectation and force the shader to use view-relative mip zero. + case = CASES[1] + forced = Case('forced_mip_zero', 0.0, 0, case.channel) + shader, run = compile_shader(cli, sdk, work, forced, stage) + assert run.returncode == 0, run.stdout + run.stderr + if stage == 'ps': + write_case(reference, 2, case.first, [taps(case)] * (SIDE ** 2)) + result = render(renderer, adapter, '--check-pixel-gather', shader, reference) + assert result.returncode == 1 and 'pixel_mismatch x=0 y=0' in result.stderr, (result.stdout, result.stderr) + else: + expected = compute_reference(case.first + case.relative, case.channel, case.uv) + result = render_compute(renderer, adapter, shader, reference, case.first, expected) + assert result.returncode == 1 and 'compared_words=320 mismatches=4' in result.stdout, ( + result.stdout, result.stderr) + print(f'{stage} forced mip zero: readback rejected') + + +def main(mode, cli, sdk, *args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'controls': + controls(cli, sdk, work) + else: + draw(cli, sdk, *args, mode, work) + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_global_load_check.py b/tests/native_global_load_check.py new file mode 100644 index 0000000000..2c989f023e --- /dev/null +++ b/tests/native_global_load_check.py @@ -0,0 +1,205 @@ +"""global_load_dword through a root SRV address in the direct C++ compute path (#2962). + + native_global_load_check.py <compile_dxil> <native_store_replay> <sdk bin dir> + +The saddr form reads ADDR = SADDR + zext(VADDR) + sext(OFFSET[11:0]) (RDNA 2 ISA, FLAT/GLOBAL addressing). The +direct frontend accepts SADDR only as the unadvanced root address of a root SRV, the binding its scalar root loads +already use, guards the 32-bit byte offset against wrapping, and drops the low two address bits like +buffer_load_dword in this path. All words below were assembled with LLVM 15 (clang -cc1as, gfx1013). + +The dispatch (two groups of 32 lanes) reads the root SRV that native_store_replay fills with 0x51aa0000 + dword +index. An s_load_dword at byte 252 sizes the view to 64 dwords. Each lane L stores five words: + A v1 = 4L -> word L + B v1, offset:16 -> word L + 4 + C v1, offset:-8 -> word L - 2, or 0 for L < 2 (the byte offset would be negative) + D v2 = 0xfffffff0 | 4(L & 3), +16 -> 0: zext(v2) + 16 is at least 2^32 (unguarded it would wrap in bounds) + E v3 = 4L + 1 -> word L (low address bits dropped) +References with the offset dropped or the wrap guard dropped must each differ from the readback. The lower guard +of C is not observable here: a wrapped negative offset lies near 2^32, outside any view below 4 GiB, and reads 0 +either way. Refusals are checked by message, and the module's loads and guards are counted before the +GPU run, which needs shader model 6.6 with wave32 (native_store_replay returns 77 otherwise). +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import sop1, vmove + + +def words(hexes): + out = [] + for h in hexes.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +ROOT = 'SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))' +SA = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 7 << 1) +# s_mov_b32 s20, s6 / s_mov_b32 s21, 0 / s_load_dwordx4 s[40:43], s[20:21], 0x20 / s_load_dword s30, s[4:5], 0xfc / +# s_lshl_b32 s12, s7, 10 / v_lshlrev_b32 v8, 5, v0 / v_add_nc_u32 v8, s12, v8 / v_lshlrev_b32 v1, 2, v0 / +# v_and_b32 v2, 3, v0 / v_lshlrev_b32 v2, 2, v2 / v_or_b32 v2, -16, v2 / v_add_nc_u32 v3, 1, v1 +PROLOGUE = words('060394be 800395be 0a0a08f4200000fa 820700f4fc0000fa 078a0c8f 85001034 0c10104a 82000234 ' + '83000436 82040434 d0040438 8102064a') +LOADS = { + 'A': '008030dc01000414', # global_load_dword v20, v1, s[4:5] + 'B': '108030dc01000415', # global_load_dword v21, v1, s[4:5] offset:16 + 'C': 'f88f30dc01000416', # global_load_dword v22, v1, s[4:5] offset:-8 + 'D': '108030dc02000417', # global_load_dword v23, v2, s[4:5] offset:16 + 'E': '008030dc03000418', # global_load_dword v24, v3, s[4:5] +} +# s_waitcnt vmcnt(0) lgkmcnt(0), five buffer_store_dword v20..v24, v8, s[40:43], 0 offen offset:0..16, s_endpgm +EPILOGUE = words('70008cbf 001070e008140a80 041070e008150a80 081070e008160a80 0c1070e008170a80 ' + '101070e008180a80 000081bf') +REFUSALS = [ + ('008030dc01007d14', 'DWORD loads with a scalar address pair'), # v[1:2], off + ('008030dc01001414', 'global load base is not a root buffer address'), # s[20:21], a table pointer + ('028030dc01000414', 'global load at an unaligned immediate offset'), # offset:2 + ('008034dc010004ff', 'global load destination register range'), # x2 beginning at v255 + ('00803cdc010004fe', 'global load destination register range'), # x3 beginning at v254 + ('008038dc010004fd', 'global load destination register range'), # x4 beginning at v253 + ('008070dc01140400', 'DWORD loads with a scalar address pair'), # global_store_dword + ('800385be 008030dc01000414', 'global load base is an advanced or mismatched root address'), # s_mov_b32 s5, 0 + ('04900480 008030dc01000414', 'unbound numeric SGPR s4'), # s_add_u32 s4, s4, 16 on the root address + ('00a030dc01000414', 'DWORD loads with a scalar address pair'), # the lds bit + ('000030dc01007d14', 'DWORD loads with a scalar address pair'), # flat_load_dword (segment 0) + ('004030dc01007d14', 'DWORD loads with a scalar address pair'), # scratch_load_dword (segment 1) + ('0080c8dc01140400', 'DWORD loads with a scalar address pair'), # global_atomic_add +] +POLICY = '009033dc01000414' # global_load_dword v20, v1, s[4:5] glc slc dlc: accepted +INACTIVE = 0x13579bdf +WIDE_OPS = {2: 13, 3: 15, 4: 14} + + +def reference(drop_offset=False, drop_wrap_guard=False): + expected = [0x69696969] * 2064 + for group in range(2): + for lane in range(32): + base = 8 + (group * 32 + lane) * 8 + + def word(byte): + return 0x51aa0000 + byte // 4 if 0 <= byte < 256 else 0 + b = word(4 * lane + (0 if drop_offset else 16)) + c_byte = 4 * lane - 8 + c = word(c_byte) if c_byte >= 0 else 0 + d_byte = 0xfffffff0 | 4 * (lane & 3) + d = word((d_byte + 16) & 0xffffffff) if drop_wrap_guard else 0 + expected[base:base + 5] = [word(4 * lane), b, c, d, word(4 * lane)] + return expected + + +def wide_program(width, case, *, reverse=False): + code = PROLOGUE.copy() + dst, coord, offset = 20, 1, 0 + if case == 'alias': + dst, offset = 1, 16 + elif case == 'tail': + code += [vop2(0x25, 1, 255, 1), 244] + elif case == 'sparse': + offset = -4 + for j in range(width): + code += [vmove(dst + j, 255), INACTIVE] + code += [sop1(3, 126, 255), 0x55555555] + elif case == 'wrap': + coord, offset = 2, 16 + elif case == 'extent': + offset = 2044 + else: + raise ValueError(case) + code += [0xdc008000 | WIDE_OPS[width] << 18 | (offset & 0xfff), dst << 24 | 4 << 16 | coord] + code.append(0xbf8c0070) # s_waitcnt vmcnt(0) lgkmcnt(0) + if case == 'sparse': + code.append(sop1(3, 126, 193)) + for j in range(width): + source = dst + (width - 1 - j if reverse else j) + code += [0xe0701000 | (j * 4), 0x800a0008 | source << 8] + return code + [0xbf810000] + + +def wide_reference(width, case): + expected = [0x69696969] * 2064 + for lane in range(64): + local = lane % 32 + if case == 'sparse' and local % 2: + values = [INACTIVE] * width + else: + start = {'alias': local + 4, 'tail': local + 61, 'sparse': local - 1, 'wrap': 1 << 30}[case] + values = [0x51aa0000 + start + j if start >= 0 and start + j < 64 else 0 for j in range(width)] + base = 8 + lane * 8 + expected[base:base + width] = values + return expected + + +def main(compiler, replay, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + source, root = work / 'root.hlsl', work / 'root.bin' + source.write_text('#define SIG "%s"' % ROOT) + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, source], check=True) + + def compile_words(code): + marker = write_request(work, code, root.read_bytes(), SA) + return marker, subprocess.run([compiler, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + for code, message in REFUSALS: + _, run = compile_words(PROLOGUE + words(code) + EPILOGUE) + assert run.returncode and message in run.stderr, (code, message, run.stdout, run.stderr) + _, run = compile_words(PROLOGUE + words(POLICY) + EPILOGUE) + assert run.returncode == 0, run.stderr + print('refused: off, a table pointer, offset:2, VGPR overflows, store, a replaced high half, an advanced pointer, ' + 'lds, flat and scratch segments, an atomic; glc slc dlc accepted') + + code = PROLOGUE + words(' '.join(LOADS.values())) + EPILOGUE + marker, run = compile_words(code) + assert run.returncode == 0, run.stderr + assert 't0 root=0 bytes=0 min_size=256' in run.stdout, run.stdout + # The module, before the GPU run: five global loads plus the scalar root load, the two upper-bound guards + # (B and D) and the lower-bound guard (C), each a select on a raw buffer load. + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', marker.with_suffix('.cso')], + capture_output=True, text=True, check=True).stdout + counts = [dump.count(t) for t in ('rawBufferLoad.i32(i32 139', 'icmp ule i32', 'icmp uge i32')] + assert counts == [6, 2, 1], counts + print('module: 6 raw buffer loads, 2 upper-bound and 1 lower-bound guards') + def replay_words(request): + dest = work / 'readback.bin' + result = subprocess.run([replay, sdk, request, work / 'cache', '0', dest, '--direct'], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout + result.stderr) + sys.exit(77) + assert result.returncode == 0, (result.stdout, result.stderr) + return list(struct.unpack('<2064I', dest.read_bytes())) + + actual = replay_words(marker) + expected = reference() + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not diff, diff[:10] + for label, mutant in (('offset dropped', reference(drop_offset=True)), + ('wrap guard dropped', reference(drop_wrap_guard=True))): + assert mutant != expected and actual != mutant, label + print('global_load_dword: 320 words of two groups matched (offsets 0, 16, -8, the 2^32 guard and an ' + 'unaligned address); the offset-dropped and wrap-guard-dropped references differ') + for width in WIDE_OPS: + for case in ('alias', 'tail', 'sparse', 'wrap'): + marker, run = compile_words(wide_program(width, case)) + assert run.returncode == 0, (width, case, run.stdout, run.stderr) + got, expected = replay_words(marker), wide_reference(width, case) + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(got, expected, strict=True)) if a != b] + assert not diff, (width, case, diff[:10]) + _, extent = compile_words(wide_program(width, 'extent')) + assert extent.returncode == 0 and f't0 root=0 bytes=0 min_size={2044 + width * 4}' in extent.stdout, ( + width, extent.stdout, extent.stderr) + marker, run = compile_words(wide_program(width, 'alias', reverse=True)) + assert run.returncode == 0, run.stderr + wrong = replay_words(marker) + changed = sum(a != b for a, b in zip(wrong, wide_reference(width, 'alias'), strict=True)) + assert changed == 64 * (width - (width % 2)), (width, changed) + print(f'global_load_dwordx{width}: alias, tail, sparse EXEC and wrap match; reversing results changes {changed} words') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_global_srv_heap_replay.cpp b/tests/native_global_srv_heap_replay.cpp new file mode 100644 index 0000000000..fb26837747 --- /dev/null +++ b/tests/native_global_srv_heap_replay.cpp @@ -0,0 +1,461 @@ +// Native compute fixture whose shader picks a global (descriptor heap) SRV slot from a GPU input. +// +// root OUT.root writes the root signature the request container carries. +// record SDK CACHE REQ.cdx ADAPTER SELECTOR EXPECT [--no-guard] +// Native recording path: reads the GPU selector back before the dispatch, captures {select, view types} +// into REQ.views, refuses a slot of another view type before the shader runs, otherwise records the +// dispatch with x2w_startup::NativeRecording and NativeDispatchStates and compares the fenced output. +// replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER EXPECT REFERENCE_SLOT [EXPECTED_WORDS] +// Offline request replay: decodes VIEWS, refuses before the dispatch or runs the compiled.cso shader on a +// heap rebuilt from the captured slot types and compares with the reference slot data. +// EXPECT is "ok" or "refused". Exit 0: outcome as expected. 1: output mismatch for an expected-ok case. 3: the +// outcome differs from the expectation. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include "startup_stubs/native_dispatch_states.h" +#include "startup_stubs/native_global_srv.h" +#include "startup_stubs/native_recording.h" +#include <dxgi1_4.h> +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <fstream> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; +using x2w_startup::GlobalSrvType; +using x2w_startup::GlobalSrvView; +namespace fs = std::filesystem; + +namespace { +constexpr unsigned slot_count = 4, slot_words = 64, selector_page_slot = 4, output_page_slot = 5; +constexpr unsigned output_words = 72; +constexpr std::uint32_t sentinel = 0x69696969u; + +// Backing data of a raw buffer slot, deterministic from the slot index. +std::uint32_t slot_word(unsigned slot, unsigned index) { return 0xA0000000u + slot * 0x10000000u + index; } + +struct Rig { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + x2w_startup::NativeRecording recording; + x2w_startup::NativeDescriptorTable page; + ComPtr<ID3D12Resource> selector, output; + std::vector<ComPtr<ID3D12Resource>> slots{slot_count}; // keeps the backing resources of the heap alive + std::vector<ComPtr<ID3D12Resource>> upload_keep; + + ~Rig() { + if (event) CloseHandle(event); + } + + // Returns 77 when the adapter cannot run the fixture; 0 when the rig is ready. + int open(const std::wstring &adapter) { + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr<IDXGIAdapter1> candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + // The descriptor page of one native recording: slots 0..3 are selectable, 4 is t0, 5 is u0. + page = recording.allocate(device.Get(), 6); + return 0; + } + + D3D12_CPU_DESCRIPTOR_HANDLE cpu(unsigned index) const { + auto handle = page.cpu; + handle.ptr += SIZE_T(index) * page.increment; + return handle; + } + D3D12_GPU_DESCRIPTOR_HANDLE first_gpu() const { + auto handle = page.gpu; + handle.ptr += UINT64(selector_page_slot) * page.increment; + return handle; + } + + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + // Records `body` on the one list and waits for its fence. + template<class Body> void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + } + // A command list with no commands: what a refused request submits instead of the dispatch. + void run_empty() { + run([](ID3D12GraphicsCommandList *) {}); + } + void fill(ID3D12Resource *destination, const std::vector<std::uint32_t> &words) { + const UINT64 bytes = words.size() * 4; + auto upload = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + D3D12_RANGE none{}; + check(upload->Map(0, &none, &mapped), "upload map"); + std::memcpy(mapped, words.data(), bytes); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { l->CopyBufferRegion(destination, 0, upload.Get(), 0, bytes); }); + } + std::vector<std::uint32_t> read(ID3D12Resource *source, unsigned words) { + auto readback = make_buffer(device.Get(), UINT64(words) * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + run([&](ID3D12GraphicsCommandList *l) { l->CopyBufferRegion(readback.Get(), 0, source, 0, UINT64(words) * 4); }); + std::vector<std::uint32_t> out(words); + void *mapped = nullptr; + D3D12_RANGE range{0, UINT64(words) * 4}; + check(readback->Map(0, &range, &mapped), "readback map"); + std::memcpy(out.data(), mapped, out.size() * 4); + D3D12_RANGE written{}; + readback->Unmap(0, &written); + return out; + } + + // t0 (the selector, a raw buffer) and u0 (72 words of output) in their page slots. + void create_io() { + selector = make_buffer(device.Get(), 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + output = make_buffer(device.Get(), output_words * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 1; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(selector.Get(), &srv, cpu(selector_page_slot)); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R32_TYPELESS; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = output_words; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(output.Get(), nullptr, &uav, cpu(output_page_slot)); + } + void fill_sentinel() { fill(output.Get(), std::vector<std::uint32_t>(output_words, sentinel)); } + bool sentinels_intact() { + for (auto word : read(output.Get(), output_words)) + if (word != sentinel) return false; + return true; + } + + // Creates the backing resource and the SRV of one selectable slot. Returns the captured view: the class is + // classified from the exact description passed to CreateShaderResourceView, the size from the resource. + GlobalSrvView add_slot(unsigned slot, GlobalSrvType type, std::uint64_t bytes) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (type == GlobalSrvType::texture) { + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 8; + texture.DepthOrArraySize = texture.MipLevels = 1; + texture.Format = DXGI_FORMAT_R32_UINT; + texture.SampleDesc.Count = 1; + slots[slot] = resource(device.Get(), texture, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + desc.Format = DXGI_FORMAT_R32_UINT; + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipLevels = 1; + } else if (type == GlobalSrvType::raw_buffer || type == GlobalSrvType::typed_buffer) { + if (!bytes || bytes % 4 || bytes > (1u << 20)) + throw std::runtime_error("slot " + std::to_string(slot) + " has an unusable buffer size"); + slots[slot] = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + std::vector<std::uint32_t> data(bytes / 4); + for (unsigned i = 0; i < data.size(); ++i) data[i] = slot_word(slot, i); + fill(slots[slot].Get(), data); + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Buffer.NumElements = static_cast<UINT>(bytes / 4); + if (type == GlobalSrvType::raw_buffer) { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + } else { + desc.Format = DXGI_FORMAT_R32_UINT; + } + } else { + throw std::runtime_error(std::string("view type ") + x2w_startup::global_srv_type_name(type) + + " cannot be rebuilt by this fixture"); + } + device->CreateShaderResourceView(slots[slot].Get(), &desc, cpu(slot)); + GlobalSrvView view; + if (!x2w_startup::classify_global_srv_view(slot, &desc, sizeof desc, view)) + throw std::runtime_error("slot view could not be classified"); + if (view.type != type) throw std::runtime_error("slot view classified as another type"); + view.bytes = type == GlobalSrvType::texture ? 0 : slots[slot]->GetDesc().Width; + return view; + } + + unsigned read_selector(unsigned value) { + fill(selector.Get(), {value}); + return read(selector.Get(), 1)[0]; + } + + // Barriers from the views of the dispatch (NativeDispatchStates), the dispatch, the barriers back, the fence. + // `state` is the pipeline-state object to run (null: the one bind() set). + void dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12PipelineState *state, ID3D12Resource *selected) { + struct View { + ComPtr<ID3D12Resource> resource; + bool write = false; + x2w_startup::NativeTextureWindow texture{}; + struct { bool upload = false; } buffer; + }; + std::vector<View> views; + views.push_back({selector, false, {}, {}}); + views.push_back({output, true, {}, {}}); + views.push_back({selected, false, {}, {}}); + x2w_startup::NativeDispatchStates states(views); + std::vector<D3D12_RESOURCE_BARRIER> before, after; + states.whole_states([&](ID3D12Resource *resource, D3D12_RESOURCE_STATES target) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, target}; + before.push_back(b); + std::swap(b.Transition.StateBefore, b.Transition.StateAfter); + after.push_back(b); + }); + run([&](ID3D12GraphicsCommandList *l) { + l->ResourceBarrier(UINT(before.size()), before.data()); + pipeline.bind(l, page.heap, first_gpu(), page.increment); + if (state) l->SetPipelineState(state); + l->Dispatch(1, 1, 1); + l->ResourceBarrier(UINT(after.size()), after.data()); + }); + } +}; + +std::vector<std::uint32_t> reference_output(unsigned slot) { + std::vector<std::uint32_t> words(output_words, sentinel); + for (unsigned i = 0; i < slot_words; ++i) words[i] = slot_word(slot, i); + return words; +} + +// 0: the 72 words equal the reference; 1 prints the first mismatch. +int compare_output(Rig &rig, unsigned reference_slot, const fs::path &reference_path = {}) { + auto expected = reference_output(reference_slot); + if (!reference_path.empty()) { + std::ifstream input(reference_path, std::ios::binary); + if (!input.read(reinterpret_cast<char *>(expected.data()), output_words * sizeof(expected[0])) || + input.peek() != std::char_traits<char>::eof()) + throw std::runtime_error("expected output file must contain exactly 72 dwords"); + } + const auto actual = rig.read(rig.output.Get(), output_words); + for (unsigned i = 0; i < output_words; ++i) + if (actual[i] != expected[i]) { + std::printf("mismatch word %u: got 0x%08x expected 0x%08x (reference slot %u)\n", i, actual[i], expected[i], + reference_slot); + return 1; + } + if (reference_path.empty()) + std::printf("output matches slot %u data (%u words) and the %u sentinel words are intact\n", reference_slot, + slot_words, output_words - slot_words); + else + std::printf("output matches CPU reference (%u words)\n", output_words); + return 0; +} + +// The refused path of both modes: no dispatch is recorded, and the output must be untouched. +int refused_path(Rig &rig, bool expect_ok) { + rig.run_empty(); + const bool intact = rig.sentinels_intact(); + std::printf("no dispatch submitted; u0 sentinels %s\n", intact ? "intact" : "CHANGED"); + return (!expect_ok && intact) ? 0 : 3; +} + +int write_root(const fs::path &destination) { + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + ranges[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + ranges[0].NumDescriptors = 1; + ranges[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + ranges[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; + ranges[1].NumDescriptors = 1; + ranges[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {2, ranges}; + D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> blob, error; + if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &error))) + throw std::runtime_error("root signature serialization failed"); + std::ofstream file(destination, std::ios::binary); + file.write(static_cast<const char *>(blob->GetBufferPointer()), static_cast<std::streamsize>(blob->GetBufferSize())); + file.close(); + if (!file) throw std::runtime_error("could not write the root signature"); + return 0; +} + +// The pipeline must read t0 and u0 through the tables and the selected slot through the heap. +void check_pipeline_shape(const x2w::NativeComputePipeline &pipeline) { + if (!pipeline.heap_indexed || pipeline.srv_count != 1 || pipeline.uav_count != 1 || pipeline.constant_words) + throw std::runtime_error("native pipeline has an unexpected binding layout"); +} + +int record(int argc, wchar_t **argv) { + if (argc != 8 && argc != 9) return 2; + const std::wstring expect = argv[7]; + const bool guard = !(argc == 9 && std::wstring_view(argv[8]) == L"--no-guard"); + if ((argc == 9 && guard) || (expect != L"ok" && expect != L"refused")) return 2; + const unsigned selector = static_cast<unsigned>(std::stoul(argv[6])); + const fs::path cdx = argv[4]; + Rig rig; + if (int skip = rig.open(argv[5])) return skip; + try { + x2w::ShaderDxilCompiler compiler(argv[2]); + auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, + x2w::HeapViewContract::raw_buffer); + check_pipeline_shape(pipeline); + rig.create_io(); + x2w_startup::GlobalSrvRequest request; + request.needed = GlobalSrvType::raw_buffer; + request.views.push_back(rig.add_slot(0, GlobalSrvType::raw_buffer, slot_words * 4)); + request.views.push_back(rig.add_slot(1, GlobalSrvType::raw_buffer, slot_words * 4)); + request.views.push_back(rig.add_slot(2, GlobalSrvType::texture, 0)); + request.views.push_back(rig.add_slot(3, GlobalSrvType::typed_buffer, slot_words * 4)); + rig.fill_sentinel(); + // The selector is GPU data: it is read back (one CPU/GPU sync) before the dispatch is recorded. + request.selected = rig.read_selector(selector); + request.has_selected = true; + auto views_path = cdx; + views_path.replace_extension(L".views"); + std::ofstream(views_path, std::ios::binary) << x2w_startup::encode_global_srv_request(request); + std::printf("captured select=%u need=raw_buffer views=%s\n", request.selected, views_path.string().c_str()); + const auto diagnostic = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (!diagnostic.empty() && guard) { + std::printf("refused select=%u: %s\n", request.selected, diagnostic.c_str()); + return refused_path(rig, expect == L"ok"); + } + if (request.selected >= slot_count || request.views[request.selected].type != GlobalSrvType::raw_buffer) + throw std::runtime_error("--no-guard only dispatches a raw buffer slot"); + rig.dispatch(pipeline, nullptr, rig.slots[request.selected].Get()); + if (expect == L"refused") { + // Discrimination control: without the guard the shader ran, so the output must have changed. + const bool intact = rig.sentinels_intact(); + std::printf("dispatch ran (%s); %s\n", guard ? "no refusal" : "guard disabled", + intact ? "sentinels intact" : "sentinels changed"); + return 3; + } + return compare_output(rig, request.selected); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} + +int replay(int argc, wchar_t **argv) { + if (argc != 10 && argc != 11) return 2; + const std::wstring expect = argv[8]; + if (expect != L"ok" && expect != L"refused") return 2; + const fs::path cdx = argv[4], cso = argv[5], views_path = argv[6]; + const unsigned reference_slot = static_cast<unsigned>(std::stoul(argv[9])); + Rig rig; + if (int skip = rig.open(argv[7])) return skip; + try { + rig.create_io(); + rig.fill_sentinel(); + std::string text, error; + x2w_startup::GlobalSrvRequest request; + std::ifstream file(views_path, std::ios::binary); + if (!file) { + error = "global SRV view metadata file missing: " + views_path.string(); + } else { + text.assign(std::istreambuf_iterator<char>(file), {}); + x2w_startup::decode_global_srv_request(text, request, error); + } + if (error.empty()) + error = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (error.empty() && request.needed != GlobalSrvType::raw_buffer) + error = std::string("GPU-selected heap slot view type ") + x2w_startup::global_srv_type_name(request.needed) + + " is not raw_buffer; only raw buffer heap reads are translated"; + if (!error.empty()) { + std::printf("refused: %s\n", error.c_str()); + return refused_path(rig, expect == L"ok"); + } + x2w::ShaderDxilCompiler compiler(argv[2]); + auto pipeline = x2w::create_native_compute_pipeline(rig.device.Get(), compiler, cdx, 0, argv[3], true, + x2w::HeapViewContract::raw_buffer); + check_pipeline_shape(pipeline); + std::ifstream shader(cso, std::ios::binary); + if (!shader) throw std::runtime_error("missing compiled shader " + cso.string()); + const std::string dxil((std::istreambuf_iterator<char>(shader)), {}); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = pipeline.root.Get(); + pso.CS = {dxil.data(), dxil.size()}; + ComPtr<ID3D12PipelineState> compiled; + check(rig.device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&compiled)), "compiled shader pipeline"); + for (const auto &view : request.views) { + if (view.slot >= slot_count) throw std::runtime_error("captured slot outside the fixture heap page"); + rig.add_slot(view.slot, view.type, view.bytes); + } + rig.read_selector(request.selected); + rig.dispatch(pipeline, compiled.Get(), rig.slots[request.selected].Get()); + const int result = compare_output(rig, reference_slot, argc == 11 ? fs::path(argv[10]) : fs::path{}); + if (expect == L"refused") return 3; // ran when a refusal was expected + return result; + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + try { + if (argc >= 2 && std::wstring_view(argv[1]) == L"root" && argc == 3) return write_root(argv[2]); + if (argc >= 2 && std::wstring_view(argv[1]) == L"record") return record(argc, argv); + if (argc >= 2 && std::wstring_view(argv[1]) == L"replay") return replay(argc, argv); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } + std::fputs("usage: native_global_srv_heap_replay root OUT.root | record SDK CACHE REQ.cdx ADAPTER SELECTOR ok|refused " + "[--no-guard] | replay SDK CACHE REQ.cdx COMPILED.cso VIEWS ADAPTER ok|refused REFERENCE_SLOT " + "[EXPECTED_WORDS]\n", stderr); + return 2; +} diff --git a/tests/native_global_srv_heap_replay_check.py b/tests/native_global_srv_heap_replay_check.py new file mode 100644 index 0000000000..fba18e6179 --- /dev/null +++ b/tests/native_global_srv_heap_replay_check.py @@ -0,0 +1,457 @@ +"""GPU-selected global SRV heap slot: native recording and offline request replay (issue #2908). + +usage: native_global_srv_heap_replay_check.py FIXTURE COMPILE_DXIL SDK ADAPTER + +A source-built compute container picks a descriptor heap slot from a GPU buffer (t0), reads 64 words through +ResourceDescriptorHeap[slot] and stores them to u0. Slots 0 and 1 are raw buffers with different data, slot 2 is a +texture, slot 3 a typed buffer. The fixture's `record` mode captures the GPU selector and the slot view types into a +req_<key>.views file and refuses the incompatible slots before the dispatch; `compile_dxil` and the fixture's `replay` +mode consume the same file offline. Section 11 forms the heap descriptor address by adding the byte offset to the heap +base (s_add_u32, carry into the high word) instead of the SGPR offset of the load. Exit 77 when the fixture reports a +capability skip. +""" +import pathlib +import shutil +import struct +import subprocess +import sys +import tempfile +import zlib + +fixture, compile_dxil, sdk, adapter = sys.argv[1:5] +RAW = "global SRV slot {n} has view type {t}, the shader needs raw_buffer" +HEAP_REFUSAL = "direct resource-heap load requires the selected GPU slot and its view type" + + +def words(*values): + return struct.pack(f"<{len(values)}I", *values) + + +def pack(body, extra=()): + raw = b"FSSM" + struct.pack("<IQ", 0x101, len(body)) + body + compressed = zlib.compress(raw) + blob = b"XBCH" + struct.pack("<IQQ", 3, len(compressed), len(raw)) + compressed + part = bytes(24) + b"XDAT" + words(1, 0, 13, 48, len(blob)) + blob + chunks = [(b"DXIL", part), *extra] + table = [] + data = b"" + for name, payload in chunks: + table.append(32 + 4 * len(chunks) + len(data)) + data += name + words(len(payload)) + payload + data += bytes(-len(data) % 4) + return b"DXBC" + bytes(16) + words(1, 32 + 4 * len(chunks) + len(data), len(chunks), *table) + data + + +def compute_two_inputs(code, threads=64, *, vgprs=4, sa4=0): + """compute() of native_direct_container_check.py with both root inputs in one list: an SRV/UAV descriptor table + in s[0:1] (type 3) and the descriptor heap in s[2:3] (type 5). Four user SGPRs: rsrc2 0x8400 | 0x1008.""" + body = bytearray(256) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into("<Q", body, 96, record) + struct.pack_into("<Q", body, record + 40, len(body)) + struct.pack_into("<I", body, record + 56, 2) + body.extend(struct.pack("<IIIIBBH", 3, 0, 1, 0, 0, 0, 0)) # A: table of root parameter 0 at user SGPR 0 + body.extend(struct.pack("<IIIIBBH", 5, 0, 1, 0, 2, 0, 0)) # B: descriptor heap at user SGPR 2 + struct.pack_into("<QQ", body, record, len(body), len(code)) + struct.pack_into("<I", body, record + 16, sa4) + struct.pack_into("<I", body, record + 20, 32) + struct.pack_into("<II", body, record + 76, 512, vgprs) + struct.pack_into("<IIII", body, record + 120, 0x8400 | 0x1008, threads, 1, 1) + body.extend(code) + return pack(body) + + +# Assembled with LLVM 15: clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 -show-encoding. +PROGRAM = words( + 0xbe810380, # s_mov_b32 s1, 0 + 0xbe830380, # s_mov_b32 s3, 0 + 0xf4080200, 0xfa000000, # s_load_dwordx4 s[8:11], s[0:1], 0x0 (t0: the selector) + 0xf4080300, 0xfa000020, # s_load_dwordx4 s[12:15], s[0:1], 0x20 (u0: the output) + 0xf4200404, 0xfa000000, # s_buffer_load_dword s16, s[8:11], 0x0 (the selected slot) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x8f118510, # s_lshl_b32 s17, s16, 5 + 0xf4080501, 0x22000000, # s_load_dwordx4 s[20:23], s[2:3], s17 (heap descriptor of the slot) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x34020082, # v_lshlrev_b32_e32 v1, 2, v0 + 0xe0301000, 0x80050201, # buffer_load_dword v2, v1, s[20:23], 0 offen + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xe0701000, 0x80030201, # buffer_store_dword v2, v1, s[12:15], 0 offen + 0xbf810000, # s_endpgm +) + + +def key_of(root, cdx): + """FNV-1a 64 as read_compute_container (src/shader_compute_request.cpp).""" + key = 1469598103934665603 + for byte in b"native-container-1" + struct.pack("<Q", len(root)) + root + cdx: + key = ((key ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF + return key + + +def run(command): + result = subprocess.run([str(part) for part in command], capture_output=True, timeout=100) + out = result.stdout.decode("utf-8", "replace") + err = result.stderr.decode("utf-8", "replace") + print("$ " + " ".join(pathlib.Path(str(c)).name if i == 0 else str(c) for i, c in enumerate(command))) + for text in (out, err): + for line in text.strip().splitlines(): + print(" " + line) + print(f" -> exit {result.returncode}") + if result.returncode == 77 and str(command[0]) == fixture: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + +def require(condition, message): + if not condition: + print("FAIL: " + message) + sys.exit(1) + print("ok: " + message) + + +with tempfile.TemporaryDirectory(prefix="x2w_global_srv_") as scratch: + base = pathlib.Path(scratch) + cache = base / "cache" + cache.mkdir() + + # Fixture root signature, container, key (B6). + root_path = base / "fixture.root" + code, out, err = run([fixture, "root", root_path]) + require(code == 0 and root_path.stat().st_size > 0, "fixture wrote the root signature") + root = root_path.read_bytes() + cdx = compute_two_inputs(PROGRAM) + stem = "req_%016x" % key_of(root, cdx) + + def request_dir(name): + directory = base / name + directory.mkdir() + (directory / (stem + ".cdx")).write_bytes(cdx) + (directory / (stem + ".root")).write_bytes(root) + return directory + + def compile_directory(directory): + out_dir = base / (directory.name + "_out") + result = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + # compile_dxil --requests publishes <key>.cs.cso (the req_ prefix stripped) for a compute request. + return result, out_dir / (stem[len("req_"):] + ".cs.cso") + + selections = [request_dir(f"sel{n}") for n in range(4)] + nometa = request_dir("nometa") + + # 1. Missing metadata, offline: a heap shader without .views is refused before any output exists. + (code, out, err), cso = compile_directory(nometa) + require(code == 1 and HEAP_REFUSAL in err, "compile_dxil without .views refuses the heap read with the slot/type text") + require(not cso.exists(), "no .cso is published for the request without .views") + + # 2. Native recording path: accepted and refused selections. + for n in (0, 1): + views = selections[n] / (stem + ".views") + code, out, err = run([fixture, "record", sdk, cache, selections[n] / (stem + ".cdx"), adapter, n, "ok"]) + require(code == 0, f"record select {n}: fenced output equals the slot {n} data and u0 sentinels are intact") + require("output matches slot %d data" % n in out, f"record select {n} compared 64 words with the CPU reference") + text = views.read_text() + require(text.startswith("x2w-global-srv-views 2\nselect %d\nneed raw_buffer\n" % n), + f"record select {n} captured the GPU selector and the view type") + for line in ("slot 0 raw_buffer 1 256", "slot 1 raw_buffer 1 256", "slot 2 texture 0 0", "slot 3 typed_buffer 4 256"): + require(line + "\n" in text, f"captured view line '{line}'") + for n, type_name in ((2, "texture"), (3, "typed_buffer")): + code, out, err = run([fixture, "record", sdk, cache, selections[n] / (stem + ".cdx"), adapter, n, "refused"]) + require(code == 0, f"record select {n}: refused with unchanged u0 sentinels") + require(RAW.format(n=n, t=type_name) in out, f"record select {n}: slot/type diagnostic before the dispatch") + require("no dispatch submitted" in out and "sentinels intact" in out, f"record select {n}: nothing was dispatched") + + # 3. Discrimination control: without the guard a valid slot runs and changes u0, which the check must see. + code, out, err = run([fixture, "record", sdk, cache, selections[0] / (stem + ".cdx"), adapter, 0, "refused", "--no-guard"]) + require(code == 3 and "sentinels changed" in out, "record --no-guard expecting a refusal sees the changed sentinels (exit 3)") + + # 4. Offline replay compilation of the captured requests. + outputs = {} + for n in range(4): + (code, out, err), cso = compile_directory(selections[n]) + outputs[n] = cso + if n < 2: + require(code == 0 and "requests=1 compiled=1 refused=0" in out, f"compile_dxil select {n}: compiled") + require("global_srv select=%d need=raw_buffer" % n in out, f"compile_dxil select {n}: reports the captured selection") + require(cso.exists(), f"compile_dxil select {n}: published a .cso") + else: + type_name = "texture" if n == 2 else "typed_buffer" + require(code == 1 and "refused=1" in out, f"compile_dxil select {n}: refused") + require(RAW.format(n=n, t=type_name) in err, f"compile_dxil select {n}: slot/type diagnostic") + require(not cso.exists(), f"compile_dxil select {n}: no .cso") + + # 5. Fixture replay of the compiled shader and of the refusals. + def replay(directory, cso, views, expect, reference): + return run([fixture, "replay", sdk, cache, directory / (stem + ".cdx"), cso, views, adapter, expect, reference]) + + for n in (0, 1): + code, out, err = replay(selections[n], outputs[n], selections[n] / (stem + ".views"), "ok", n) + require(code == 0 and "output matches slot %d data" % n in out, f"replay select {n}: compiled shader output equals slot {n} data") + for n, type_name in ((2, "texture"), (3, "typed_buffer")): + code, out, err = replay(selections[0], outputs[0], selections[n] / (stem + ".views"), "refused", 0) + require(code == 0 and RAW.format(n=n, t=type_name) in out and "sentinels intact" in out, + f"replay select {n}: refused with the slot/type diagnostic, u0 sentinels intact") + + # 6. Mutation control: the slot 1 data is not the slot 0 reference. + code, out, err = replay(selections[0], outputs[0], selections[0] / (stem + ".views"), "ok", 1) + require(code == 1 and "mismatch word 0" in out, "replay select 0 compared with slot 1 data reports a mismatch (exit 1)") + + # 7. Negative controls on both paths: metadata that cannot reconstruct the binding. + good = (selections[0] / (stem + ".views")).read_text() + lines = good.splitlines() + + def variant(name, text, expected): + directory = request_dir("neg_" + name) + views = directory / (stem + ".views") + views.write_text(text, newline="\n") + (code, out, err), cso = compile_directory(directory) + require(code == 1 and expected in err, f"compile_dxil '{name}': refused with '{expected}'") + require(not cso.exists() and not any(cso.parent.glob("*.cso")), f"compile_dxil '{name}': no .cso") + code, out, err = replay(selections[0], outputs[0], views, "refused", 0) + require(code == 0 and expected in out and "sentinels intact" in out, + f"replay '{name}': refused with the same diagnostic, u0 sentinels intact") + + def without(prefix): + kept = [line for line in lines if not line.startswith(prefix)] + require(len(kept) == len(lines) - 1, f"control input drops exactly one '{prefix}' line") + return "\n".join(kept) + "\n" + + variant("mismatched_type", good.replace("slot 0 raw_buffer 1 256", "slot 0 texture 0 0"), RAW.format(n=0, t="texture")) + require("slot 0 texture 0 0" in (base / "neg_mismatched_type" / (stem + ".views")).read_text(), "mismatch input rewrote slot 0") + variant("no_need", without("need "), "global SRV view metadata lacks the needed view type") + variant("no_select", without("select "), "global SRV view metadata lacks the selected slot") + variant("no_slot_line", without("slot 0 "), "global SRV slot 0 has no captured view type") + variant("select_7", good.replace("select 0", "select 7"), "global SRV slot 7 has no captured view type") + + # 8. Shader shapes whose heap read could address another slot than the captured selection, use the slot's stride + # as a number, or rewrite the heap descriptor in a way the raw slot view cannot stand for: refused by + # compile_dxil even with valid metadata, no .cso. + words_list = list(struct.unpack(f"<{len(PROGRAM) // 4}I", PROGRAM)) + lshl = words_list.index(0x8f118510) + heap_load = words_list.index(0xf4080501) + after_wait = heap_load + 3 # the s_waitcnt after the heap descriptor load + # The byte-address rewrite of the heap descriptor s[20:23] into s[24:27] (LLVM 15 encodings, as above). + rewrite = [ + 0x939cff15, 0x000e0010, # s_bfe_u32 s28, s21, 0xe0010 (stride) + 0x849c811c, # s_max_u32 s28, s28, 1 + 0x931a1c16, # s_mul_i32 s26, s22, s28 (byte count) + 0x8719ff15, 0xc000ffff, # s_and_b32 s25, s21, 0xc000ffff (stride cleared) + 0x871bff17, 0xcfffffff, # s_and_b32 s27, s23, 0xcfffffff + 0x881bff1b, 0x30000000, # s_or_b32 s27, s27, 0x30000000 (raw out-of-bounds mode) + 0xbe980314, # s_mov_b32 s24, s20 + ] + load = words_list.index(0xe0301000) # buffer_load_dword v2, v1, s[20:23], 0 offen + store = words_list.index(0xe0701000) # buffer_store_dword v2, v1, s[12:15], 0 offen + + def window(rewritten=rewrite, prefix=(), store_word=0x80030201): + """PROGRAM with the rewrite after the heap load and the load through s[24:27].""" + program = list(words_list) + program[load + 1] = 0x80060201 # buffer_load_dword v2, v1, s[24:27], 0 offen + program[store + 1] = store_word + return program[:after_wait] + list(prefix) + list(rewritten) + program[after_wait:] + + WINDOW = window() + second_load = window([0xbe980320 if w == 0xbe980314 else w for w in rewrite]) + second_load[after_wait - 1:after_wait - 1] = [0xf4080801, 0x22000000] # before the s_waitcnt + # The branch word sits at after_wait + 1; its target is next pc + 4 * simm16, here the s_lshl_b32 at word lshl. + loop_around_load = window(prefix=(0xbf071010, 0xbf850000 | ((lshl - (after_wait + 2)) & 0xFFFF))) + shapes = { + # s_mov_b32 s17, 64 instead of the GPU-derived s_lshl_b32 s17, s16, 5 + "constant_index": (words_list[:lshl] + [0xbe9103c0] + words_list[lshl + 1:], + "heap descriptor index is a constant; the captured selection must come from GPU data"), + # s_load_dwordx4 s[20:23], s[2:3], s17 offset:0x20 + "immediate_offset": (words_list[:heap_load] + [0xf4080501, 0x22000020] + words_list[heap_load + 2:], + "heap descriptor load with an immediate offset addresses another slot than the captured selection"), + # s_bfe_u32 s24, s21, 0xe0010 after the heap descriptor load (stride field of the selected slot), then + # v_mov_b32 v3, s24: the stride is used as a number + "stride_read": (words_list[:after_wait] + [0x9398ff15, 0x000e0010, 0x7e060218] + words_list[after_wait:], + "unbound numeric SGPR s24"), + # s_and_b32 s25, s21, 0xc000fffe: not the mask that clears the stride + "window_wrong_mask": (window([0xc000fffe if w == 0xc000ffff else w for w in rewrite]), "unbound numeric SGPR s21"), + # a second heap load s_load_dwordx4 s[32:35], s[2:3], s17 and word 0 from it (s_mov_b32 s24, s32) + "window_second_load": (second_load, "non-contiguous resource descriptor"), + # buffer_store_dword v2, v1, s[24:27], 0 offen: a store through the window + "window_store": (window(store_word=0x80060201), "a GPU-selected heap slot is read as a raw buffer SRV only"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 back to the s_lshl_b32 before the heap load (never taken): the + # loop contains the heap load, which would run again for another selection + "window_loop": (loop_around_load, "heap byte window loaded inside a loop"), + } + for name, (program, expected) in shapes.items(): + directory = base / ("shape_" + name) + directory.mkdir() + shape_cdx = compute_two_inputs(words(*program)) + shape_stem = "req_%016x" % key_of(root, shape_cdx) + (directory / (shape_stem + ".cdx")).write_bytes(shape_cdx) + (directory / (shape_stem + ".root")).write_bytes(root) + (directory / (shape_stem + ".views")).write_text(good, newline="\n") + out_dir = base / (directory.name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 1 and expected in err, f"compile_dxil shape '{name}': refused with '{expected}'") + require(not any(out_dir.glob("*.cso")), f"compile_dxil shape '{name}': no .cso") + + # 9. The byte-address rewrite of the selected heap descriptor (stride, max 1, byte count, stride cleared, raw + # out-of-bounds mode) reads the selected raw slot: recorded, compiled offline and replayed like PROGRAM. A stride + # read that nothing uses compiles too. The descriptor words stay symbolic, so a stride > 1 is not exercised. + def shader_request(name, program, **stage): + directory = base / name + directory.mkdir() + cdx_bytes = compute_two_inputs(words(*program), **stage) + window_stem = "req_%016x" % key_of(root, cdx_bytes) + (directory / (window_stem + ".cdx")).write_bytes(cdx_bytes) + (directory / (window_stem + ".root")).write_bytes(root) + return directory, window_stem + + compiled_shapes = { + "stride_unused": (words_list[:after_wait] + [0x9398ff15, 0x000e0010] + words_list[after_wait:], + "an unused stride read compiles and publishes a .cso"), + # s_cmp_lg_u32 s16, s16 and s_cbranch_scc1 -2 (back to the compare, never taken) after the heap load: the loop + # does not contain the load, which runs once + "window_loop_after_load": (window(prefix=(0xbf071010, 0xbf85fffe)), + "a loop after the heap load does not refuse the window, a .cso is published"), + } + for name, (program, message) in compiled_shapes.items(): + directory, window_stem = shader_request(name, program) + (directory / (window_stem + ".views")).write_text(good, newline="\n") + out_dir = base / (name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and + (out_dir / (window_stem[len("req_"):] + ".cs.cso")).exists(), "compile_dxil: " + message) + window_outputs = {} + for n in (0, 1): + directory, window_stem = shader_request(f"window{n}", WINDOW) + code, out, err = run([fixture, "record", sdk, cache, directory / (window_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record window select {n}: u0 equals the slot {n} data read through the rewritten descriptor") + out_dir = base / f"window{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (window_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil window select {n}: compiled and published a .cso") + window_outputs[n] = (directory, window_stem, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, f"replay window select {n}: output equals slot {n} data") + directory, window_stem, cso = window_outputs[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (window_stem + ".cdx"), cso, + directory / (window_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, "replay window select 0 compared with slot 1 data reports a mismatch") + + missing = base / "missing" / (stem + ".views") + code, out, err = replay(selections[0], outputs[0], missing, "refused", 0) + require(code == 0 and "global SRV view metadata file missing: " + str(missing) in out and "sentinels intact" in out, + "replay with a missing .views path refuses with the file diagnostic, u0 sentinels intact") + + # 10. Raw load address forms. Eight active lanes each write one 16-byte output slot. + def raw_load_request(name, width=1, *, offen=False, soffset=18, imm=0, flags=0, flags2=0): + opcode_delta = {1: 0, 2: 1, 3: 3, 4: 2}[width] << 18 + program = words_list[:load - 1] + [ + 0x34020084, # v_lshlrev_b32_e32 v1, 4, v0 + 0xbe92038c, # s_mov_b32 s18, 12 + 0xbefe03ff, 0x000000ff, # s_mov_b32 exec_lo, 0xff + 0xe0300000 | opcode_delta | (int(offen) << 12) | imm | flags, + (soffset << 24) | 0x00050201 | flags2, # s[20:23], vdata at v2, VADDR field v1 + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xe0701000 | opcode_delta, 0x80030201, # buffer_store_dword[xN] v2..., v1, s[12:15], 0 offen + 0xbf810000, # s_endpgm + ] + directory, key = shader_request(name, program, threads=32, vgprs=6, sa4=1 << 20) + views = directory / (key + ".views") + views.write_text(good, newline="\n") + out_dir = base / (name + "_out") + result = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + return result, directory, key, views, out_dir / (key[len("req_"):] + ".cs.cso") + + cases = [(f"off_sgpr_x{width}", width, 12, {}) for width in (1, 2, 3, 4)] + cases += [ + ("off_sgpr_imm", 1, 12, {"imm": 8}), + ("offen_sgpr", 1, 12, {"offen": True}), + ("off_inline", 1, 20, {"soffset": 128 + 20}), + ("off_inline_zero", 1, 0, {"soffset": 128}), + ] + for name, width, scalar_bytes, addressing in cases: + (code, out, err), directory, key, views, cso = raw_load_request(name, width, **addressing) + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), f"{name}: compiled") + expected = [0x69696969] * 72 + for lane in range(8): + addr = scalar_bytes + addressing.get("imm", 0) + (16 * lane if addressing.get("offen") else 0) + expected[4 * lane:4 * lane + width] = [0xA0000000 + addr // 4 + k for k in range(width)] + reference = directory / "expected.bin" + reference.write_bytes(words(*expected)) + code, out, err = run([fixture, "replay", sdk, cache, directory / (key + ".cdx"), cso, + views, adapter, "ok", 0, reference]) + require(code == 0 and "output matches CPU reference (72 words)" in out, f"{name}: CPU reference") + + modifiers = "raw buffer load needs a linear byte offset and no modifiers" + for name, diagnostic, addressing in ( + ("raw_idxen", modifiers, {"flags": 1 << 13}), + ("raw_descriptor_soffset", "unbound numeric SGPR s20", {"soffset": 20}), + ("raw_literal_soffset", "raw buffer load scalar offset needs an SGPR or inline integer", {"soffset": 255}), + ): + (code, out, err), _, _, _, cso = raw_load_request(name, **addressing) + require(code == 1 and diagnostic in err and not cso.exists(), f"{name}: refused with '{diagnostic}'") + + # 11. The heap descriptor address formed by adding the byte offset to the heap base, as a waterfall loop over a + # lane-selected slot does, instead of the SGPR offset of the load (encodings checked with tools/disasm_rdna2.py): + # s_add_u32 s24, s2, s17 ; s_add_u32 s25, 0, src_scc ; s_load_dwordx4 s[20:23], s[24:25], 0x0 + # It reads the same slot: recorded, compiled offline and replayed like PROGRAM. + ADD_LO, ADD_HI, ADDED_LOAD = 0x80181102, 0x8019fd80, [0xf408050c, 0xfa000000] + + def added(lo=ADD_LO, between=(), hi=ADD_HI, load_words=ADDED_LOAD): + return words_list[:heap_load] + [lo, *between, hi, *load_words] + words_list[heap_load + 2:] + + ADDED = added() + directory, added_stem = shader_request("added_nometa", ADDED) + out_dir = base / "added_nometa_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + require(code == 1 and HEAP_REFUSAL in err and not any(out_dir.glob("*.cso")), + "compile_dxil added address without .views refuses the heap read with the slot/type text") + added_outputs = {} + for n in (0, 1): + directory, added_stem = shader_request(f"added{n}", ADDED) + code, out, err = run([fixture, "record", sdk, cache, directory / (added_stem + ".cdx"), adapter, n, "ok"]) + require(code == 0 and "output matches slot %d data" % n in out, + f"record added select {n}: u0 equals the slot {n} data read through the added address") + out_dir = base / f"added{n}_out" + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + cso = out_dir / (added_stem[len("req_"):] + ".cs.cso") + require(code == 0 and "requests=1 compiled=1 refused=0" in out and cso.exists(), + f"compile_dxil added select {n}: compiled and published a .cso") + added_outputs[n] = (directory, cso) + code, out, err = run([fixture, "replay", sdk, cache, directory / (added_stem + ".cdx"), cso, + directory / (added_stem + ".views"), adapter, "ok", n]) + require(code == 0 and "output matches slot %d data" % n in out, f"replay added select {n}: output equals slot {n} data") + directory, cso = added_outputs[0] + code, out, err = run([fixture, "replay", sdk, cache, directory / (added_stem + ".cdx"), cso, + directory / (added_stem + ".views"), adapter, "ok", 1]) + require(code == 1 and "mismatch word 0" in out, "replay added select 0 compared with slot 1 data reports a mismatch") + + high_word = "heap descriptor address high word is not the carry of its offset add" + added_shapes = { + # s_add_u32 s24, s17, s2 and s_addc_u32 s25, 0, 0: the other operand order and carry form + "added_swapped_addc": (added(lo=0x80180211, hi=0x82198080), None), + # s_add_u32 s24, s2, 0x40: a constant offset names a slot that is not the captured GPU selection + "added_constant": (added(lo=0x8018ff02, between=(0x00000040,)), "unbound numeric SGPR s2"), + # s_mov_b32 s25, 0: the high word drops the carry of the offset add + "added_mov_high": (added(hi=0xbe990380), high_word), + # s_cmp_lg_u32 s16, s16 between the adds: SCC is no longer the carry + "added_scc_clobbered": (added(between=(0xbf071010,)), high_word), + # s_load_dwordx4 s[20:23], s[24:25], 0x20 + "added_immediate": (added(load_words=[0xf408050c, 0xfa000020]), + "heap descriptor load with an immediate offset addresses another slot than the captured selection"), + } + for name, (program, expected) in added_shapes.items(): + directory, shape_stem = shader_request("shape_" + name, program) + (directory / (shape_stem + ".views")).write_text(good, newline="\n") + out_dir = base / ("shape_" + name + "_out") + code, out, err = run([compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir]) + if expected is None: + require(code == 0 and "requests=1 compiled=1 refused=0" in out and any(out_dir.glob("*.cso")), + f"compile_dxil shape '{name}': compiled") + else: + require(code == 1 and expected in err and not any(out_dir.glob("*.cso")), + f"compile_dxil shape '{name}': refused with '{expected}'") + +print("native_global_srv_heap_replay: all checks passed") diff --git a/tests/native_graphics_interface_library_check.py b/tests/native_graphics_interface_library_check.py new file mode 100644 index 0000000000..d5475858ca --- /dev/null +++ b/tests/native_graphics_interface_library_check.py @@ -0,0 +1,131 @@ +"""Index source-built native containers and replay their raw runtime form.""" +import pathlib +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel, publish, vertex, words + + +def main(compiler, sdk): + def run(*args, expected=None): + result = subprocess.run([compiler, *args], capture_output=True, text=True) + if expected is None: + assert result.returncode == 0, result.stderr + else: + assert result.returncode and expected in result.stderr, result.stderr + return result.stdout + + with tempfile.TemporaryDirectory() as tmp: + base = pathlib.Path(tmp) + library, cache, requests = (base / s for s in ("library", "cache", "requests")) + library.mkdir() + # The old raw reader has no PS state for this scalar branch. Exact + # native programs recover the full stage ABI from the catalog. + branch = [0xbf008180, 0xbf850002, 0x7e0002f2, 0xbf820001, 0x7e0002f4] + prefix = [0xd5800000, 255, 17, 0xd5800000, 255, 23] + program = prefix + branch + end = 0xbf810000 + vs = words(0x7e020b00, 0xf80008cf, 0x01010101, end) + ps = words(*program, 0xf800180f, 0, end) + pixel_file = library / "pixel.cdxil" + pixel_file.write_bytes(patched_pixel(len(program), program)) + vertex_file = library / "vertex.cdxil" + vertex_file.write_bytes(vertex()) + root = b"DXBC" + bytes(16) + words(1,68,1,36) + b"RTS0" + words(24,2,0,24,0,24,0) + stem = publish(requests, ps, vs, root) + def batch(folder, output, **kwargs): + return run(sdk, cache, "gfx1013-container-pair", "--requests", folder, output, **kwargs) + batch(requests, base / "bare", expected="verified stage interface") + install = ("--index-graphics-interfaces", library, cache) + run(*install) + for name, hit in (("cold",0), ("warm",1)): + assert f"frontend_cache_hit={hit}" in batch(requests, base / name) + run(sdk,cache,"gfx1013-container-pair",vertex_file,base/"vertex.cso",pixel_file,base/"pixel.cso") + for stage, name in (("vs","vertex"),("ps","pixel")): + binary = (base / (name+".cso")).read_bytes() + assert all((base / mode / (stem+"."+stage+".cso")).read_bytes() == binary for mode in ("cold","warm")) + # A second implementation shares the embedded ID. Exact matches + # still work, while a third unmatched implementation cannot pick one. + alternate = prefix + [0xbf800000] + branch + (library/"alternate.cdxil").write_bytes(patched_pixel(len(alternate),alternate)) + run(*install) + batch(requests,base/"exact") + other = base/"other" + publish(other, words(*prefix,0xbf800000,0xbf800000,*branch,0xf800180f,0,end),vs,root) + batch(other,base/"ambiguous",expected="ambiguous reviewed graphics interfaces") + # A failed rebuild must leave the published generation usable. + (library/"broken.cdxil").write_bytes(b"bad") + assert subprocess.run([compiler,*install],capture_output=True).returncode + batch(requests,base/"retained") + + # Two reflected parameter rows. The fixed PS uses P1/P2 for x + # and MOV P0 for y of row zero; hardware only allocates that row. + fixed = base / "fixed" + fixed.mkdir() + vp = [0x7e0002f2, 0xf80008cf, 0, 0xf800020f, 0, 0xf800021f, 0, end] + (fixed / "varying.cdxil").write_bytes(vertex(program=vp)) + def interpolate(attr, channel, op, dst, src): + return 0xc8000000 | dst << 18 | op << 16 | attr << 10 | channel << 8 | src + template = prefix + [interpolate(0, 0, 0, 4, 0), interpolate(0, 0, 1, 4, 1)] + attributes = [(6, row, 15, row, 0, 0, row, 2) for row in range(2)] + (fixed / "smooth.cdxil").write_bytes(patched_pixel( + len(template), template, input_address=2, attributes=attributes)) + run("--index-graphics-interfaces", fixed, cache) + for attr, count, error in ((0, 1, None), (1, 2, None), + (1, 1, "interpolation inputs disagree"), + (0, 3, "captured interpolation count")): + code = words(*template, interpolate(attr, 1, 2, 5, 2), 0xf800180f, 0x05040504, end) + folder = base / f"fixed-{attr}-{count}" + publish(folder, code, words(*vp), root, slot57_inputs=(2, count)) + batch(folder, base / f"linked-{attr}-{count}", expected=error) + + # The library PS consumes x only. A fixed variant also reads y, + # which is valid only when the actual VS exports that channel. + narrow = [(6, row, 1, row, 0, 0, row, 2) for row in range(2)] + (fixed / "smooth.cdxil").write_bytes(patched_pixel( + len(template), template, input_address=2, attributes=narrow)) + code = words(*template, interpolate(0, 1, 0, 5, 0), interpolate(0, 1, 1, 5, 1), + 0xf800180f, 0x05040504, end) + for mask in (15, 1): + producer = vp.copy() + producer[3] = (producer[3] & ~15) | mask + (fixed / "varying.cdxil").write_bytes(vertex(program=producer)) + run("--index-graphics-interfaces", fixed, cache) + folder = base / f"raw-channels-{mask}" + publish(folder, code, words(*producer), root, slot57_inputs=(2, 1)) + batch(folder, base / f"raw-linked-{mask}", expected=None if mask == 15 else "graphics stages disagree") + + # An exact VS writes a four-component image through the second + # guest slot. The serialized root covers just the first slot. + # The FSSM offset, descriptor width, class and SGPR establish the + # binding used by the C++ linker and copied to the runtime cache. + images = base / "images" + images.mkdir() + (images / "pixel.cdxil").write_bytes(pixel_file.read_bytes()) + vs_file = images / "store.cdxil" + op = [0xbe810380, 0xf40c0200, 0xfa000020, + 0x7e000280, 0x7e020280, 0x7e0802f2, 0x7e0a02f2, + 0xf0200f08, 0x80020400, 0xf80008cf, 0, end] + root_src, root_bin = base / "uav.hlsl", base / "uav.bin" + root_src.write_text('#define RS "DescriptorTable(UAV(u0))"') + subprocess.run([pathlib.Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "RS", + root_src, "-Fo", root_bin], check=True) + job = base / "image-request" + publish(job, ps, words(*op), root_bin.read_bytes()) + for kind, width, sgpr, error in ( + (3, 8, 0, None), (0, 8, 0, "disagrees with reflected table record"), + (3, 4, 0, "disagrees with reflected table record"), + (3, 8, 1, "no matching user SGPR")): + vs_file.write_bytes(vertex(program=op, table=True, uses=[(0x300 | kind, 8, 0, 0, width | sgpr << 8)])) + run("--index-graphics-interfaces", images, cache) + output = base / f"store-{kind}-{width}-{sgpr}" + batch(job, output, expected=error) + if error: + assert not list(output.glob("*.cso")) + else: + assert "frontend_cache_hit=1" in batch(job, base / "warm-store") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_graphics_sampler_heap_check.py b/tests/native_graphics_sampler_heap_check.py new file mode 100644 index 0000000000..37f063c659 --- /dev/null +++ b/tests/native_graphics_sampler_heap_check.py @@ -0,0 +1,68 @@ +"""Read back slots in the C++ raw graphics sampler-table lowering.""" +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import publish +from startup_sampler_heap_check import CONST_WORDS, FULLSCREEN_VS, MIXED_WORDS, PS_WORDS, VS_WORDS + + +def move(dst, src): + return struct.pack("<I", 0xbe800300 | (dst << 16) | src) + + +def program(body, dropped=False): + # Root table at s8, constants at s9:s10, sampler heap at s11. The + # existing draw harness puts the varying byte offset in constant word 1. + prefix = (move(10, 9) if dropped else b"") + move(12, 11) + move(13, 128) + move(9, 128) + body = body.replace(bytes.fromhex("050608f400000012"), bytes.fromhex("060608f400000014")) + return prefix + body.replace(bytes.fromhex("050608f4100000fa"), bytes.fromhex("060608f4100000fa")) + + +def main(frontend, renderer, sdk, adapter): + with TemporaryDirectory() as temp: + folder = Path(temp) + root = folder / "root.bin" + source = folder / "fixture.hlsl" + source.write_text('#define RS "RootFlags(SAMPLER_HEAP_DIRECTLY_INDEXED),' + 'DescriptorTable(SRV(t0)),RootConstants(num32BitConstants=2,b0)"', encoding="ascii") + dxc = Path(sdk) / "dxc.exe" + subprocess.run([dxc, "-T", "rootsig_1_1", "-E", "RS", "-Fo", root, source], check=True) + vs = folder / "fullscreen.cso" + source.write_text(FULLSCREEN_VS, encoding="ascii") + subprocess.run([dxc, "-T", "vs_6_0", "-Fo", vs, source], check=True) + + for case, words, reason in (("dynamic", PS_WORDS, ""), ("dropped", PS_WORDS, ""), + ("constant", CONST_WORDS, "constant sampler heap offset"), + ("mixed", MIXED_WORDS, "mixed sampler heap descriptor words")): + directory, output = folder / case, folder / (case + "-out") + key = publish(directory, VS_WORDS, program(words, case == "dropped"), root.read_bytes()) + cmd = [frontend, sdk, folder / "cache", "gfx1013-container-pair", "--requests", directory, output] + result = subprocess.run(cmd, capture_output=True, text=True) + if reason: + assert result.returncode and reason in result.stderr, result.stderr + continue + assert result.returncode == 0, result.stderr + warm = subprocess.run(cmd, capture_output=True, text=True, check=True) + assert "frontend_cache_hit=1" in warm.stdout, warm.stdout + manifest = output / (key + ".txt") + assert "smpheap 2048 1 fallback 2047" in manifest.read_text() + cases = ((0, "3e800000"), (16, "3f400000"), (32, "00000000"), (8, "3f000000"), + (2047 * 16, "3f000000"), (0xfffffff0, "3f000000")) + for offset, expected in (cases if case == "dynamic" else ((16, "3f400000"),)): + draw = subprocess.run([renderer, adapter, "--startup-sampler-heap", vs, output / (key + ".ps.cso"), + str(offset), expected, manifest], capture_output=True, text=True) + print(draw.stdout, end="") + if draw.returncode == 77: + return 77 + if case == "dropped": + assert draw.returncode == 1 and "expected=3f400000 actual=3e800000" in draw.stderr, draw.stderr + else: + assert draw.returncode == 0, draw.stderr + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_graphics_vertex_vcc_join_check.py b/tests/native_graphics_vertex_vcc_join_check.py new file mode 100644 index 0000000000..0d0215afa8 --- /dev/null +++ b/tests/native_graphics_vertex_vcc_join_check.py @@ -0,0 +1,130 @@ +"""Draw source-built guest VS programs whose per-vertex VCC crosses a two-arm join.""" +import re +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import signature_rows, vertex +from native_scalar_lds_check import sop1, vmove + +NOP = 0xbf800000 +ARM_WORD = 8 +ARM_B_COMPARE = 15 +JOIN = 17 +LANE_JOIN = 17 + + +def cndmask(dst, taken, other): + # dst = VCC ? v[taken] : other + return 0x02000000 | dst << 17 | taken << 9 | other + + +def program(arm_b): + # Fullscreen triangle (-1,-1), (4,-1), (-1,4) from SV_VertexID in v0. + seq = [vmove(6, 246), + 0x7d040081, cndmask(1, 6, 243), # x = id == 1 ? 4 : -1 + 0x7d040082, cndmask(2, 6, 243), # y = id == 2 ? 4 : -1 + vmove(3, 128), vmove(7, 242), + # The harness supplies zero in b0, so the arm is chosen at draw time. + sop1(3, 4, 255), int(arm_b), 0x89040004, 0xbf008004, + 0xbf840003, # s4 != 0: arm B + 0x7d040081, vmove(4, 244), 0xbf820002, # A: VCC = id == 1, v4 = 2 + 0x7d0a0082, vmove(4, 246), # B: VCC = id != 2, v4 = 4 + vmove(5, 240), cndmask(5, 4, 261), # after the join: VCC ? v4 : 0.5 + 0xf80000cf, 0x07030201, 0xf8000a0f, 0x05050405, 0xbf810000] + assert seq[ARM_WORD] == arm_b and seq[ARM_B_COMPARE] == 0x7d0a0082 and seq[JOIN] == vmove(5, 240) + return seq + + +def lane_program(): + # The compare itself splits the wave: vertex 1 runs THEN, the others ELSE. + # VCC is written once, before the region, and read after EXEC is restored. + # The frontend lowers these arms to per-vertex selects in one block. + seq = program(False)[:7] + # A masked write keeps the previous v4 on the other lanes. + seq += [vmove(4, 242), + 0x7d040081, 0xbe88246a, 0xbf880002, # VCC = id == 1; save EXEC; skip THEN + vmove(4, 244), NOP, # THEN: v4 = 2 + 0x8afe7e08, 0xbf880001, vmove(4, 246), # ELSE: v4 = 4 + 0xbefe0408, + 0x101008f3, cndmask(5, 4, 264), # v8 = -v4; VCC ? v4 : v8 + 0xf80000cf, 0x07030201, 0xf8000a0f, 0x05050405, 0xbf810000] + assert seq[LANE_JOIN] == 0x101008f3 + return seq + + +def container(seq): + outputs = signature_rows([(b"TEXCOORD", 0, 3, 0, 15), (b"SV_Position", 1, 3, 1, 15)]) + return vertex(constants=(0, 1), program=seq, varying=True, extra=((b"OSG1", outputs),)) + + +def reference(arm_b): + """Per-vertex CPU model: three selected values, then the arm's own value.""" + arm = 4.0 if arm_b else 2.0 + vcc = [(vid != 2) if arm_b else (vid == 1) for vid in range(3)] + return [arm if bit else 0.5 for bit in vcc] + [arm] + + +def main(cli, raster, sdk, backend): + with TemporaryDirectory() as tmp: + work = Path(tmp) + source, vs, ps, expected = work/"source", work/"vs.cso", work/"ps.cso", work/"expected.bin" + # Every pixel reports the unblended value of each of the three vertices. + source.write_text("float4 main(nointerpolation float4 v:TEXCOORD, float4 p:SV_Position):SV_Target {" + "return float4(GetAttributeAtVertex(v,0).x,GetAttributeAtVertex(v,1).x," + "GetAttributeAtVertex(v,2).x,GetAttributeAtVertex(v,0).y);}") + subprocess.run([Path(sdk)/"dxc.exe", "-T", "ps_6_6", "-Fo", ps, source], check=True) + + def draw(seq, words): + source.write_bytes(container(seq)) + subprocess.run([cli, sdk, work/"cache", "gfx1013-container-vs", source, vs], check=True) + expected.write_bytes(struct.pack("<4f", *words)*8) + result = subprocess.run([raster, backend, "--startup-pixel-words", vs, ps, "4", "2", expected], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, result.stderr) + sys.exit(77) + return result + + def differs(result): + assert result.returncode == 1 and "8 of 8 pixels differ" in result.stderr, (result.stdout, result.stderr) + return result.stderr.splitlines()[0] + + for arm_b in (False, True): + result = draw(program(arm_b), reference(arm_b)) + assert result.returncode == 0, (result.stdout, result.stderr) + ir = subprocess.check_output([Path(sdk)/"dxc.exe", "-dumpbin", vs], text=True) + # Each arm supplies its own compare to the mask the select reads. + joined = re.search(r"(%\w+) = phi i32 \[ (%\w+), %g\d+ \], \[ (%\w+), %g\d+ \]\n", ir) + assert joined and joined[2] != joined[3] and "@dx.op.wave" not in ir, ir + mask = re.search(rf"(%\w+) = icmp ne i32 {joined[1]}, 0\n", ir) + assert mask and f"select i1 {mask[1]}," in ir, ir + print(*(line for line in result.stdout.splitlines() + if line.startswith(("backend=", "adapter=", "driver=", "debug_"))), sep="\n") + print(f"arm {'AB'[arm_b]}: vertices 0..2 and arm value matched {reference(arm_b)}") + # Vertex 0 supplies the fourth word, so it is the ELSE value. + lane = [-4.0, 2.0, -4.0, 4.0] + result = draw(lane_program(), lane) + assert result.returncode == 0, (result.stdout, result.stderr) + print(f"per-vertex arms: THEN on vertex 1, ELSE on vertices 0 and 2 matched {lane}") + uniform = lane_program() + uniform.insert(LANE_JOIN, 0x7d040100) + print("uniform mask after the per-vertex arms:", differs(draw(uniform, lane))) + # Control: arm B no longer contributes its own compare. The join + # then receives the stale id == 2 mask on that edge only. + dropped = program(True) + dropped[ARM_B_COMPARE] = NOP + print("dropped arm B contribution:", differs(draw(dropped, reference(True)))) + dropped[ARM_WORD] = 0 + assert draw(dropped, reference(False)).returncode == 0 + # Control: a uniform v0 == v0 replaces the joined mask. + for arm_b in (False, True): + uniform = program(arm_b) + uniform.insert(JOIN, 0x7d040100) + print(f"uniform mask after the join, arm {'AB'[arm_b]}:", differs(draw(uniform, reference(arm_b)))) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_graphics_wqm_check.py b/tests/native_graphics_wqm_check.py new file mode 100644 index 0000000000..61cc0da93c --- /dev/null +++ b/tests/native_graphics_wqm_check.py @@ -0,0 +1,399 @@ +"""Check whole-wave zero and pixel coverage using source-built guest shaders.""" +import re +import struct +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +from native_direct_container_check import patched_pixel, signature +from native_scalar_lds_check import sop1, vmove + + +def packed(lo, hi, narrow=False): + move = 3 if narrow else 4 + wqm = 9 if narrow else 10 + # Both paths are scalar until the original coverage is restored. + # Observe the actual expanded words and which direction EXECZ took. + # The harness supplies zero in b0. The front end and DXIL optimizer + # must still evaluate both words from runtime data at draw time. + def xor_root_word(dst, root): + return 0x80000000 | (0x12 << 23) | (dst << 16) | (root << 8) | dst + seq = [sop1(move,20,126), sop1(3,4,255),lo, sop1(3,5,255),hi, + xor_root_word(4,0), xor_root_word(5,1), + sop1(3,10,128), sop1(3,11,128), sop1(3,12,129), + sop1(wqm,126,4),0xbf880002,sop1(move,10,126),sop1(3,12,130), + sop1(move,126,20)] + # Byte-sized values remain exactly representable in the float target. + seq += [vmove(0,10),vmove(1,11),vmove(2,12),vmove(3,10)] + for v in (0,1,3): + seq += [(0x16<<25) | (v<<17) | (v<<9) | (152 if v==3 else 128), + (0x1b<<25) | (v<<17) | (v<<9) | 255,255] + for v in range(4): + seq += [0x7e000c00 | (v<<17) | (256+v)] + return patched_pixel(len(seq),seq,constants=(0,2),wave32=narrow,export=(0xf800180f,0x03020100), + input_signature=((b"OSG1",signature(b"SV_Target",64)),)) + + +def raster_program(limit=None, *, lower=None, cross=False): + # Drop coverage where limit < SV_Position.x. In a surviving quad + # the horizontal peer's coordinate must remain available, even if its + # own coverage was dropped. An empty quad branches to EXP_NULL. + seq=[sop1(4,12,126), sop1(10,126,126)] + attributes=() + if limit is None: + # Perspective-center P1/P2 of attr3.z, followed by 0 > v5. + p1=0xc8000000 | (5<<18) | (3<<10) | (2<<8) + seq += [p1, p1 | (1<<16) | 1, 0x7c080000 | (5<<9) | 128] + attributes=((6,0,15,3,0,0,0,0),) + inputs, input_address, value = signature(b"TEXCOORD"), 2, 5 + else: + threshold=struct.unpack("<I",struct.pack("<f",limit))[0] + seq += [0x7c0200ff,threshold] + inputs, input_address, value = signature(b"SV_Position",1), 1<<8, 0 + branches=[] + def filter_and_test(): + seq.extend([0x8a8c6a0c, sop1(10,126,12)]) + branches.append(len(seq)) + seq.append(0) + filter_and_test() + if lower is not None: + assert limit is not None + seq += [0x7c0800ff,struct.unpack("<I",struct.pack("<f",lower))[0]] + filter_and_test() + seq += [vmove(2,250), 0xff040000 | ((0x141 if cross else 0xb1)<<8) | value,sop1(4,126,12)] + if limit is None: + # The interpolator may round the fractional input by one ULP. Move + # it onto a coarser float grid before the bit-exact color comparison. + seq += [(3<<25) | (2<<17) | (2<<9) | 255, 0x41800000] + for branch in branches: + seq[branch] = 0xbf880000 | (len(seq)+3-(branch+1)) # after color export and END + return patched_pixel(len(seq),seq,input_address=input_address,attributes=attributes, + input_signature=((b"ISG1",inputs),(b"OSG1",signature(b"SV_Target",64))), + export=(0xf800180f,0x02020202),tail=(0xf8001890,0x80808080,0xbf810000)) + + +def quad_mask(word): + return sum(15<<shift for shift in range(0,32,4) if word & (15<<shift)) + + +def check_packed_and_exact_exec(draw, compile_guest): + target = (b"OSG1", signature(b"SV_Target", 64)) + position = (b"ISG1", signature(b"SV_Position", 1)) + + def packed_color(code, **kwargs): + return patched_pixel(len(code), code, export=(0xf8001c0f, 0x05050505), **kwargs) + + def fma(op, src): + # Destination v5, operands (src, inline 1.0, inline 0). + return [op | 5, src | (242 << 9) | (128 << 18)] + + low, high = fma(0xcc210000, 242), fma(0xcc220000, 244) + def interleaved(src): + return [0xd54b000c, src | (242 << 9) | (128 << 18)] # v_fma_f32 v12,src,1,0 + + expected = [(1.0, 2.0, 1.0, 2.0)] * 16 + for code in (low + high, high + low, low + interleaved(242) + high): + draw(packed_color(code, input_signature=(target,)), expected) + for code in (low, low + low, low + interleaved(261) + high, low + fma(0xcc220000, 261)): + result = compile_guest(packed_color(code, input_signature=(target,))) + assert result.returncode and "entry VGPR 5" in result.stderr, result.stderr + + # WQM -> exact -> WQM: the exact write to unallocated v4 has no old + # helper value. Packed arithmetic observes only the eventual color. + prefix = [sop1(4, 10, 126), sop1(10, 126, 126), sop1(4, 12, 126), + sop1(4, 126, 10), vmove(4, 242), sop1(4, 126, 12)] + tail = fma(0xcc210000, 260) + high + [sop1(4, 126, 10)] + kwargs = dict(input_address=1 << 8, input_signature=(position, target)) + draw(packed_color(prefix + tail, **kwargs), expected) + quad_read = [vmove(2, 250), 0xff04b104] # DPP reads v4 from another quad lane + result = compile_guest(packed_color(prefix + quad_read + tail, **kwargs)) + assert result.returncode and "entry VGPR 4" in result.stderr, result.stderr + + # CMPX compares 4.0 < SV_Position.x. Its read-only arm updates v2 + # only on the right half of the draw; all pixels export after restore. + def cmpx(body): + code = [vmove(2, 242), sop1(4, 10, 126), 0x7c2200f6, + 0xbf880000 | len(body), *body, sop1(4, 126, 10)] + return patched_pixel(len(code), code, export=(0xf800180f, 0x02020202), **kwargs) + + draw(cmpx([vmove(2, 244)]), [(1.0 + (lane % 8 >= 4),) * 4 for lane in range(16)]) + result = compile_guest(cmpx(quad_read)) + assert result.returncode and "graphics branch on a wave mask" in result.stderr, result.stderr + + +# Cross-quad EXECZ (#2907). A region term (axis, "le"|"ge", value) keeps the lanes with +# SV_Position.axis <= value or >= value; the compare sets VCC for the lanes it removes. +def term_compare(axis, op, value): + return [(0x7c020000 if op=="le" else 0x7c080000) | ({"x":0,"y":1}[axis]<<9) | 255, + struct.unpack("<I",struct.pack("<f",value))[0]] + + +def cross_quad_program(limit, terms, *, base="survivors", region=(sop1(3,14,130),)): + # Exact coverage drops pixels where limit < x. The EXECZ region runs under + # WQM of a mask taken from the survivors or from the whole-quad EXEC and + # narrowed by the terms, and writes only a scalar. After exact coverage is + # restored every survivor exports that scalar, so a quad with no bit in the + # mask still observes whether the wave took the branch. + seq=[sop1(4,12,126), sop1(10,126,126), *term_compare("x","le",limit), 0x8a8c6a0c, # s[12:13] = survivors + sop1(3,14,129)] # s14 = 1 + for k,term in enumerate(terms): + source=16 if k else (12 if base=="survivors" else 126) + seq += [*term_compare(*term), 0x8a906a00 | source] # s[16:17] = source & ~VCC + seq += [sop1(10,126,16)] # exec = WQM(s[16:17]) + branch=len(seq) + seq += [0, *region] # s_cbranch_execz to the restore; s14 = 2 + seq[branch] = 0xbf880000 | (len(seq)-(branch+1)) + seq += [sop1(4,126,12), vmove(1,14), 0x7e000c00 | (1<<17) | 257] + return patched_pixel(len(seq),seq,input_address=3<<8, + input_signature=((b"ISG1",signature(b"SV_Position",1)),(b"OSG1",signature(b"SV_Target",64))), + export=(0xf800180f,0x01010000)) + + +def position(lane): + return (lane%8+0.5, lane//8+0.5) + + +def cross_quad_reference(limit, terms, quads, vote, *, base="survivors"): + """Pixels of cross_quad_program: (x, x, s14, s14) for survivors, the clear value elsewhere. + + `quads` holds the measured desktop quads of the draw: (wave, ((lane, helper), ...)). vote="wave" is the + lowering: EXEC at the branch is the WQM expansion of the mask, so a quad votes when any of its lanes, helpers + included, holds a mask bit, and the branch is taken once per measured wave. The negative controls: + vote="plain" sees only non-helper lanes (a wave vote without the quad OR), vote="survivors" only surviving + pixels, and vote="quad" lets each quad decide alone.""" + keep=lambda lane: all((position(lane)[a=="y"]<=v) if op=="le" else (position(lane)[a=="y"]>=v) + for a,op,v in terms) + survives=lambda lane, helper: not helper and position(lane)[0]<=limit + def bit(lane, helper): + if base=="survivors" and not survives(lane,helper): + return False + if vote=="plain" and helper or vote=="survivors" and not survives(lane,helper): + return False + return keep(lane) + voted={(w if vote!="quad" else (w,lanes)) for w,lanes in quads if any(bit(*l) for l in lanes)} + pixels=[(-1.0,)*4]*16 + for w,lanes in quads: + flag=2.0 if (w if vote!="quad" else (w,lanes)) in voted else 1.0 + for lane,helper in lanes: + if survives(lane,helper): + pixels[lane]=(position(lane)[0],position(lane)[0],flag,flag) + return pixels + + +def desktop_quads(work, raster, sdk, backend, vs): + """Measure the quads and waves of the 8x2 draw with HLSL pixel stages on the same draw. + + Wave operations leave helper lanes out, so each covered pixel reports its wave (the smallest covered id in + it), the ids of its three quad peers and whether each peer is a helper (IsHelperLane, SM 6.6).""" + reads={"ids": ("ps_6_0","float4(WaveActiveMin(id),QuadReadAcrossX(id),QuadReadAcrossY(id)," + "QuadReadAcrossDiagonal(id))"), + "helpers": ("ps_6_6","float4(WaveGetLaneCount(),QuadReadAcrossX(h),QuadReadAcrossY(h)," + "QuadReadAcrossDiagonal(h))")} + data={} + for key,(profile,value) in reads.items(): + source, ps, out = work/f"{key}.hlsl", work/f"{key}.cso", work/f"{key}.bin" + source.write_text("float4 main(float4 p:SV_Position):SV_Target {uint id=uint(p.y)*8u+uint(p.x);" + f"uint h=IsHelperLane()?1u:0u; return {value};}}" if profile=="ps_6_6" else + "float4 main(float4 p:SV_Position):SV_Target {uint id=uint(p.y)*8u+uint(p.x);" + f"return {value};}}") + subprocess.run([Path(sdk)/"dxc.exe","-T",profile,"-Fo",ps,source],check=True) + result=subprocess.run([raster,backend,"--startup-pixel-dump",vs,ps,"8","2",out],capture_output=True,text=True) + if result.returncode==77: sys.exit(77) + assert result.returncode==0,(result.stdout,result.stderr) + values=struct.unpack("<64f",out.read_bytes()) + data[key]=[values[4*i:4*i+4] for i in range(16)] + quads, widths = {}, set() + for lane in range(16): + if data["ids"][lane]==(-1.0,)*4: + continue # not covered: the clear value + wave,*peers=(int(v) for v in data["ids"][lane]) + width,*helpers=(int(v) for v in data["helpers"][lane]) + widths.add(width) + members=((lane,False),*((p,bool(h)) for p,h in zip(peers,helpers))) + assert len({m[0] for m in members})==4 and all(position(p)[0]//2==position(lane)[0]//2 and + position(p)[1]//2==position(lane)[1]//2 for p,_ in members),\ + ("a desktop quad is not the aligned 2x2 block",lane,members) + quads.setdefault((wave,frozenset(members)),set()).add(lane) + assert len(widths)==1,widths + for (wave,members),lanes in quads.items(): + # Every covered lane of a quad reports the same quad, and its smallest covered lane names a wave. + assert lanes=={l for l,h in members if not h},(wave,members,lanes) + return [(w,tuple(sorted(m))) for w,m in quads], widths.pop() + + +VERTEX={"full": "float4 main(uint i:SV_VertexID):SV_Position {return float4(i==1?3:-1,i==2?3:-1,0,1);}", + # Covers the pixels with x + y < 5.5, so the quad at x = 4..5 has one covered lane, (4,0). + "diagonal": "float4 main(uint i:SV_VertexID):SV_Position {" + "return float4(i==0?-0.25:(i==1?0.5:-5),i==0?-1.5:(i==1?1.5:0),0,1);}"} +# (vertex, limit, terms, base): one quad's survivors hold the mask; a wider mask; an empty wave; a mask in +# covered quads without survivors (WQM before the filter); the same from the survivors; and masks that only +# the diagonal, horizontal or vertical helper of the one covered lane (4,0) holds. +CASES=(("full",6.5,(("x","le",1.0),),"survivors"), ("full",9,(("x","le",4.5),),"survivors"), + ("full",6.5,(("x","le",-1.0),),"survivors"), ("full",3.5,(("x","ge",4.5),),"wqm"), + ("full",3.5,(("x","ge",4.5),),"survivors"), + ("diagonal",4.5,(("x","ge",5.0),("y","ge",1.0)),"wqm"), + ("diagonal",4.5,(("x","ge",5.0),("y","le",1.0)),"wqm"), + ("diagonal",4.5,(("x","ge",4.0),("x","le",5.0),("y","ge",1.0)),"wqm")) + + +def ir_main(dump): + """Without a GPU: the vote's three quad reads and the wave vote come before any conditional branch, where + every lane of the quad, helpers included, still runs them (quad operations need quad-uniform control flow). + + The patterns follow the frontend's current text form (immediate i8 operands, attributes written inline on + the declaration); a change to that form, for example attribute groups, needs these patterns updated.""" + with TemporaryDirectory() as tmp: + blob=Path(tmp)/"cross.bin" + blob.write_bytes(cross_quad_program(6.5,(("x","le",1.0),))) + result=subprocess.run([dump,blob],capture_output=True,text=True) + assert result.returncode==0,result.stderr + body=result.stdout[result.stdout.index("define void @main"):] + first_branch=body.index("\n br i1 ") # the first conditional branch: the vote's own + quad=[m.group(1) for m in re.finditer(r"@dx\.op\.quadOp\.i32\(i32 123, i32 %\w+, i8 (\d)\)",body)] + vote=[m.start() for m in re.finditer(r"@dx\.op\.waveAnyTrue\(i32 113, i1 %\w+\)",body)] + assert sorted(quad)==["0","1","2"] and len(vote)==1,(quad,vote) + assert all(m.start()<first_branch for m in re.finditer(r"call \w+ @dx\.op\.(quadOp|waveAnyTrue)",body)),body + # The same attributes as DXC gives the HLSL intrinsics. + for declaration in ("declare i32 @dx.op.quadOp.i32(i32, i32, i8) nounwind\n", + "declare i1 @dx.op.waveAnyTrue(i32, i1) nounwind\n"): + assert declaration in result.stdout,(declaration,result.stdout) + print("cross-quad EXECZ IR: QuadReadAcrossX/Y/Diagonal and WaveActiveAnyTrue before the first branch") + + +def main(cli, raster, sdk, backend="hardware"): + with TemporaryDirectory() as tmp: + work=Path(tmp) + source, vs, ps = work/"source", work/"vs.cso", work/"ps.cso" + def vertex(kind): + source.write_text(VERTEX[kind]) + subprocess.run([Path(sdk)/"dxc.exe","-T","vs_6_6","-Fo",vs,source],check=True) + vertex("full") + def compile_guest(blob): + source.write_bytes(blob) + return subprocess.run([cli,sdk,work/"cache","gfx1013-container-ps",source,ps], + capture_output=True,text=True) + def run(blob, pixels): + result=compile_guest(blob) + assert not result.returncode,result.stderr + expected=work/"expected.bin" + expected.write_bytes(b"".join(struct.pack("<4f",*pixel) for pixel in pixels)) + result=subprocess.run([raster,backend,"--startup-pixel-words",vs,ps,"8","2",expected], + capture_output=True,text=True) + if result.returncode==77: sys.exit(77) + return result + def draw(blob, pixels): + result=run(blob,pixels) + assert result.returncode==0,(result.stdout,result.stderr) + print(result.stdout.strip()) + # On a 2x2 quad, compare the vertical neighbor with the negated + # current value. The equal case on column two checks ordered GT. + cmp_code=[sop1(10,126,126),0x06220300,0x062222ff,0xc0600000, # v17 = x+y-3.5 + 0x7c0822fa,0xff4c4e11,0x7e0402f2,0x02000480] + def quad_compare(code): + return patched_pixel(len(code),code,input_address=0x300, + input_signature=((b"ISG1",signature(b"SV_Position",1)),)) + expected=[(float(x>=3),)*4 for y in range(2) for x in range(8)] + draw(quad_compare(cmp_code),expected) + # The high word of v54 contains floor(x). Its low word is zero. + # -1 as 32-bit raw bits is qNaN (class bit 1), while 0x7c01 is + # binary16 sNaN (bit 0). Both arms write v0, on complementary EXEC. + for half in (False,True): + selector=[0x7d1e6cf9,0x0586b40f] if half else [0x7d106cf9,0x0586b4c1] + seq=[0x7e6c0f00,0x346c6c90,0xbe8f03ff,0x7c01,0xbebc047e, + *selector,0xbeb40834,0x87fe7e34,0xbf880001,0x7e0002f2, + 0x8afe7e3c,0x7e0002f0,0xbefe043c] + flags=1 if half else 2 + reference=[(0.5 if x & flags else 1.0,)*4 for y in range(2) for x in range(8)] + draw(quad_compare(seq),reference) + for control in (0xff4ce411,0xff0c4e11): # Identity permutation or unnegated src1. + wrong=cmp_code.copy() + wrong[5]=control + failed=run(quad_compare(wrong),expected) + assert failed.returncode==1 and "pixels differ" in failed.stderr,failed.stderr + check_packed_and_exact_exec(draw, compile_guest) + for lo,hi,narrow in ((0,0,False),(0,1,False),(0x80000000,0,False), + (0x80000021,0x42,False),(0,1,True),(0x22,0,True)): + a,b=quad_mask(lo),0 if narrow else quad_mask(hi) + pixel=(a&255,b&255,2 if a or b else 1,a>>24) + draw(packed(lo,hi,narrow),[pixel]*16) + print(f"wave{32 if narrow else 64} {hi:08x}:{lo:08x} -> {pixel}") + for limit in (0,0.5,2.5,9): + values=[(float((x^1)+0.5) if x+0.5<=limit else -1.0,)*4 for y in range(2) for x in range(8)] + draw(raster_program(limit),values) + print(f"filtered coverage limit={limit}: {sum(x[0]!=-1.0 for x in values)}/16 pixels survived") + for lower in (1.5,4.5): + values=[(float((x^1)+0.5) if lower<=x+0.5<=2.5 else -1.0,)*4 for y in range(2) for x in range(8)] + draw(raster_program(2.5,lower=lower),values) + print(f"two coverage filters [{lower},2.5]: {sum(x[0]!=-1.0 for x in values)}/16 pixels survived") + rejected=compile_guest(raster_program(2.5,cross=True)) + assert rejected.returncode and "complete guest vote or a quad-local continuation" in rejected.stderr,rejected.stderr + # Cross-quad EXECZ: the CPU reference comes from the measured desktop quads and waves of each draw. + controls, cross_controls, measured = {}, 0, {} + for kind,limit,terms,base in CASES: + vertex(kind) + if kind not in measured: + measured[kind]=desktop_quads(work,raster,sdk,backend,vs) + quads,width=measured[kind] + waves={w for w,_ in quads} + print(f"{kind} draw: {width} lanes, {len(quads)} quads in {len(waves)} waves, " + f"{sum(1 for w in waves if sum(1 for q,_ in quads if q==w)>1)} waves with more than one quad, " + f"{sum(h for _,lanes in quads for _,h in lanes)} helper lanes") + quads,_=measured[kind] + blob=cross_quad_program(limit,terms,base=base) + reference=lambda vote: cross_quad_reference(limit,terms,quads,vote,base=base) + whole=reference("wave") + draw(blob,whole) + label=f"{kind} limit={limit} {base} {terms}" + print(f"cross-quad {label}: {sum(p[0]!=-1.0 for p in whole)}/16 survive, " + f"s14 {sorted({p[2] for p in whole if p[0]!=-1.0})}") + for vote in ("quad","plain","survivors"): + other=reference(vote) + if other==whole: + continue + result=run(blob,other) + assert result.returncode==1 and "pixels differ" in result.stderr,(vote,label,result.stderr) + print(f" {vote} vote reference: {next(l for l in result.stderr.splitlines() if 'pixels differ' in l)}") + controls[vote]=controls.get(vote,0)+1 + cross_controls+=vote=="quad" + assert cross_quad_reference(6.5,(("x","le",-1.0),),measured["full"][0],"wave")== \ + cross_quad_reference(6.5,(("x","le",-1.0),),measured["full"][0],"quad") + assert controls.get("plain",0)>=3,controls # the three single-helper masks are decided by the quad OR + vertex("full") + # Lane reads, vector writes, branches and EXEC changes inside the region keep a named refusal. + for label,region,reason in ( + ("DPP inside the region",(0x7e0402fa,0xff04b100),"may only write scalars"), + ("VGPR write inside the region",(vmove(1,14),),"may only write scalars"), + ("EXEC read inside the region",(sop1(4,20,126),),"may only write scalars"), + ("branch inside the region",(0xbf820000,),"region contains a branch"), + ("EXEC rewritten inside the region",(sop1(4,126,16),),"must branch to the exact coverage restore"), + ("s_setreg_b32 inside the region",(0xb98e0801,),"hardware register"), + ("s_getreg_b32 inside the region",(0xb9140801,),"hardware register")): + rejected=compile_guest(cross_quad_program(6.5,(("x","le",1.0),),region=region)) + assert rejected.returncode and reason in rejected.stderr,(label,rejected.stderr) + print(f"refused: {label}: ok") + # The pixel program now consumes an interpolated value produced by + # the VS, including a negative coordinate from a WQM helper. + source.write_text("struct Out { float4 tc:TEXCOORD; float4 pos:SV_Position; };" + "Out main(uint i:SV_VertexID) { Out o;" + "o.pos=float4(i==1?3:-1,i==2?3:-1,0,1);" + "o.tc=float4(0,0,3.25-(o.pos.x+1)*4,0); return o; }") + subprocess.run([Path(sdk)/"dxc.exe","-T","vs_6_6","-Fo",vs,source],check=True) + values=[(16+3.25-((x^1)+0.5) if x+0.5<=3.25 else -1.0,)*4 for y in range(2) for x in range(8)] + draw(raster_program(),values) + print("attr3.z perspective interpolation, VCC filter and WQM/EXECZ: all 16 pixels matched") + print(f"cross-quad EXECZ negative controls that differ from the readback: {controls}") + if not cross_controls: + reason=f"no desktop wave holds two quads ({measured['full'][1]} lanes)" + if backend=="hardware": + # Every other check passed; the cross-quad decision itself was not exercised. + print(f"skip: the cross-quad quad-local control needs two quads in one wave: {reason}") + sys.exit(77) + print(f"SKIPPED cross-quad quad-local control: {reason}") + + +if __name__=="__main__": + if sys.argv[1]=="ir": + ir_main(sys.argv[2]) + else: + main(*sys.argv[1:]) diff --git a/tests/native_half_grid.cpp b/tests/native_half_grid.cpp new file mode 100644 index 0000000000..af7d08c93c --- /dev/null +++ b/tests/native_half_grid.cpp @@ -0,0 +1,176 @@ +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include <array> +#include <cstdio> +#include <cstring> +#include <map> +#include <vector> + +using Microsoft::WRL::ComPtr; +namespace { +constexpr UINT width = 40, height = 54; +struct Surface { + ComPtr<ID3D12Resource> texture, upload, readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 size{}; + bool half{}, writable{}; +}; +Surface make_surface(ID3D12Device *device, ID3D12GraphicsCommandList *list, bool writable, bool half, bool bit_input, bool prefix) { + Surface s; + s.writable = writable; + s.half = half; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Format = half ? DXGI_FORMAT_R16_FLOAT : DXGI_FORMAT_R32G32B32A32_FLOAT; + desc.Flags = writable ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE; + s.texture = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + device->GetCopyableFootprints(&desc, 0, 1, 0, &s.footprint, nullptr, nullptr, &s.size); + s.upload = make_buffer(device, s.size, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped; + check(s.upload->Map(0, nullptr, &mapped), "upload"); + for (UINT y = 0; y < height; ++y) { + auto row = static_cast<char*>(mapped) + y * s.footprint.Footprint.RowPitch; + for (UINT x = 0; x < width; ++x) { + if (half) { + reinterpret_cast<uint16_t*>(row)[x] = 0x5400; // +64 sentinel + } else { + auto pixel = reinterpret_cast<float*>(row) + 4*x; + for (UINT k = 0; k < 4; ++k) + pixel[k] = writable ? 64.f : float(1+x+16*y+k); + if (!writable && prefix) + pixel[0] = x == 1+y ? 2.f : x == 9-y ? -2.f : x == 14 ? float(y+1) : 0.f; + if (!writable && bit_input && ((x+y)&1)) { + UINT bits; + std::memcpy(&bits, pixel, 4); + bits |= 2; + std::memcpy(pixel, &bits, 4); + } + } + } + } + s.upload->Unmap(0, nullptr); + D3D12_TEXTURE_COPY_LOCATION src{s.upload.Get(),D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + D3D12_TEXTURE_COPY_LOCATION dst{s.texture.Get(),D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = s.footprint; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + transition(list, s.texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, writable ? + D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + if (writable) + s.readback = make_buffer(device, s.size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + return s; +} +} + +int check_half_grid(ID3D12Device *device, x2w::ShaderDxilCompiler &compiler, const wchar_t *marker, + const wchar_t *cache, const std::wstring &mode) { + const bool shift = mode == L"half-shift", bits = mode == L"half-bit", offset = mode == L"half-offset"; + const bool fixture = mode == L"half-value" || mode == L"half-mutant"; + if (!shift && !bits && !offset && !fixture && mode != L"half-clear" && mode != L"half-dual") + return 2; + auto request = x2w::read_compute_request(marker); + UINT shape; + std::memcpy(&shape, request.sa.data()+12, 4); + const UINT gx = shape & 65535, gy = shape >> 16; + auto p = x2w::create_native_compute_pipeline(device, compiler, marker, fixture ? 0 : 36, cache); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, UINT(p.bindings.size()), + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&heap)), "half heap"); + UINT step = device->GetDescriptorHandleIncrementSize(hd.Type); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + ComputeCommands cmd(device,p.state.Get(),D3D12_COMMAND_LIST_TYPE_DIRECT); + // Multiple desktop views of one guest slot must see the same underlying storage. + using Slot = std::pair<UINT,UINT>; + std::map<Slot, Surface> surfaces; + ComPtr<ID3D12Resource> params; + for (const auto &b : p.bindings) { + const bool write = x2w::compute_uav(b.kind); + Slot slot{b.root_parameter,b.byte_offset}; + if (b.kind == x2w::ComputeViewKind::buffer_srv && offset && slot.second == 32) { + params = make_buffer(device, 24, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const UINT words[]{91,98,87,77,3,5}; + void *data; + check(params->Map(0,nullptr,&data),"offset buffer"); + std::memcpy(data, words,sizeof(words)); + params->Unmap(0,nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Buffer.NumElements = 6; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(params.Get(),&srv,cpu); + } else { + bool half = b.kind == x2w::ComputeViewKind::half_scalar_uav || (shift && slot.second == 64); + if (!surfaces.count(slot)) + surfaces.emplace(slot,make_surface(device,cmd.list.Get(),write,half,bits,shift)); + auto &s = surfaces.at(slot); + if (write) + device->CreateUnorderedAccessView(s.texture.Get(),nullptr,nullptr,cpu); + else + device->CreateShaderResourceView(s.texture.Get(),nullptr,cpu); + } + cpu.ptr += step; + } + if (surfaces.size() != (shift || bits ? 3u : mode == L"half-dual" ? 2u : 1u)) + return 2; + const UINT groups_x = shift ? 1 : 2, groups_y = 3; + std::vector<UINT> constants(p.constant_words,0); + p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,constants.data()); + cmd.list->Dispatch(groups_x,groups_y,1); + for (auto &[slot,s] : surfaces) { + if (!s.writable) continue; + transition(cmd.list.Get(),s.texture.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{s.texture.Get(),D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{s.readback.Get(),D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = s.footprint; + cmd.list->CopyTextureRegion(&dst,0,0,0,&src,nullptr); + } + cmd.submit_and_wait(device); + check(device->GetDeviceRemovedReason(),"half completion"); + UINT differences = 0, checked = 0; + for (auto &[slot,s] : surfaces) { + if (!s.writable) continue; + void *mapped; + check(s.readback->Map(0,nullptr,&mapped),"half readback"); + for (UINT y = 0; y < height; ++y) { + auto row = static_cast<const char*>(mapped) + y*s.footprint.Footprint.RowPitch; + for (UINT x = 0; x < width; ++x) { + UINT ox = offset ? 3 : 0, oy = offset ? 5 : 0; + bool covered = x >= ox && y >= oy && x-ox < gx*groups_x && y-oy < gy*groups_y; + if (s.half) { + UINT expected = covered ? (fixture ? 0xc100u : 0u) : 0x5400u; + if (shift) { + expected = 0x5400; + if (x < 16 && y < groups_y) { + // Exclusive u32 prefix of the bit patterns for +2 and -2. + // Their modulo-2^32 sum is zero. The last source value is y+1. + constexpr uint16_t tail[]{0x3c00, 0x4000, 0x4200}; + expected = x == 15 ? tail[y] : x > 1+y && x <= 9-y ? 0x4000 : 0; + } + } + differences += reinterpret_cast<const uint16_t*>(row)[x] != expected; + ++checked; + } else { + float expected = 64.f; + if (shift && y == 0 && x < groups_y) expected = float(x+1); + if (bits && covered) { + UINT value = ((x+y)&1) * 2; + std::memcpy(&expected,&value,4); + } + for (UINT k = 0; k < 4; ++k) { + differences += std::memcmp(row+(4*x+k)*4,&expected,4) != 0; + ++checked; + } + } + } + } + s.readback->Unmap(0,nullptr); + } + std::printf("components=%u differing_components=%u cache_hit=%d frontend_ms=%.4f backend_ms=%.4f pso_ms=%.4f\n", + checked,differences,p.cache_hit,p.frontend_ms,p.backend_ms,p.pipeline_ms); + return differences ? 1 : 0; +} diff --git a/tests/native_heap_handle_probe.cpp b/tests/native_heap_handle_probe.cpp new file mode 100644 index 0000000000..6fb745d5db --- /dev/null +++ b/tests/native_heap_handle_probe.cpp @@ -0,0 +1,292 @@ +// Cycle 1 of the global SRV work: can a native compute module read through ResourceDescriptorHeap[index]? +// +// Two shaders select a heap slot from a GPU word and copy that slot's raw buffer to a UAV: one is HLSL compiled by DXC +// (the reference), the other is the textual DXIL module the native compiler builds (dx.op.createHandleFromHeap, opcode +// 218). Both run on the same pipeline shape (root flag CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) with two different selector +// words: the readbacks must be the distinct data of slot A and slot B, and a UAV guard word past the copied range must +// stay intact. Usage: native_heap_handle_probe ADAPTER SDK_DIRECTORY WORK_DIRECTORY SHADER_FLAGS +// ADAPTER is warp or hardware. Exit 77 when the adapter lacks shader model 6.6 or resource binding tier 3. +#include "dxil_module.h" +#include "shader_dxil_compiler.h" +#include <d3d12.h> +#include <dxgi1_4.h> +#include <wrl/client.h> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <filesystem> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT words = 64; +constexpr UINT guard_word = 0xC0FFEE11u; +constexpr UINT sentinel = 0xCAFEF00Du; + +UINT slot_word(UINT slot, UINT i) { return (slot == 0 ? 0x1000u : 0x9000u) + i * (slot == 0 ? 7u : 13u); } + +ComPtr<ID3D12Resource> make_buffer(ID3D12Device *device, UINT64 bytes, D3D12_HEAP_TYPE type, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_HEAP_PROPERTIES heap{type}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + ComPtr<ID3D12Resource> resource; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&resource)))) + return {}; + return resource; +} + +struct Gpu { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + UINT64 value = 0; + bool open(ID3D12Device *d) { + device = d; + D3D12_COMMAND_QUEUE_DESC q{D3D12_COMMAND_LIST_TYPE_DIRECT}; + return SUCCEEDED(d->CreateCommandQueue(&q, IID_PPV_ARGS(&queue))) && + SUCCEEDED(d->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(d->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(list->Close()) && SUCCEEDED(d->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + template <class Record> bool run(Record &&record) { + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.Get(), nullptr))) return false; + record(list.Get()); + if (FAILED(list->Close())) return false; + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), ++value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + fence->SetEventOnCompletion(value, event); + WaitForSingleObject(event, 30000); + CloseHandle(event); + return fence->GetCompletedValue() >= value; + } +}; + +void transition(ID3D12GraphicsCommandList *list, ID3D12Resource *r, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &b); +} + +// The dxil module of the native compiler: output[tid] = ResourceDescriptorHeap[selection[0]][tid]. +std::string native_module(unsigned shader_flags) { + x2w::DxilModule m; + m.features = shader_flags | 16; + const auto selection = m.handle({0, 0, 11, 0, 0, 0}); + const auto output = m.handle({1, 0, 11, 0, 0, 0}); + const auto thread = m.invoke("i32", "threadId.i32", 93, {{"i32", "0"}}, "nounwind readnone"); + const auto address = m.binary("shl", thread, "2"); + const auto word = m.invoke("%dx.types.ResRet.i32", "rawBufferLoad.i32", 139, + {{"%dx.types.Handle", selection}, {"i32", "0"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind readonly"); + const auto slot = m.value("extractvalue %dx.types.ResRet.i32 " + word + ", 0"); + const auto data = m.heap_handle(slot, 11, 0); + const auto loaded = m.invoke("%dx.types.ResRet.i32", "rawBufferLoad.i32", 139, + {{"%dx.types.Handle", data}, {"i32", address}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind readonly"); + const auto value = m.value("extractvalue %dx.types.ResRet.i32 " + loaded + ", 0"); + m.invoke("void", "rawBufferStore.i32", 140, + {{"%dx.types.Handle", output}, {"i32", address}, {"i32", "undef"}, {"i32", value}, {"i32", "undef"}, + {"i32", "undef"}, {"i32", "undef"}, {"i8", "1"}, {"i32", "4"}}, + "nounwind"); + m.body << " ret void\n"; + return m.finish_compute(words, 1, 1); +} + +const char *reference_hlsl = + "ByteAddressBuffer selection : register(t0);\n" + "RWByteAddressBuffer output : register(u0);\n" + "[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) {\n" + " ByteAddressBuffer data = ResourceDescriptorHeap[selection.Load(0)];\n" + " output.Store(id.x * 4, data.Load(id.x * 4));\n" + "}\n"; +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 5) { + std::fputs("usage: native_heap_handle_probe ADAPTER SDK WORK SHADER_FLAGS\n", stderr); + return 2; + } + const std::wstring adapter = argv[1]; + const unsigned shader_flags = static_cast<unsigned>(std::stoull(argv[4])); + const std::filesystem::path work = argv[3]; + std::filesystem::create_directories(work); + + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> chosen; + ComPtr<ID3D12Device> device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr<IDXGIAdapter1> candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { chosen = candidate; break; } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { std::puts("no device"); return 77; } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot create it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + try { + x2w::ShaderDxilCompiler compiler(argv[2]); + const auto module = native_module(shader_flags); + std::ofstream(work / "native_module.ll") << module; + x2w::CompiledShader reference, native; + reference = compiler.compile(reference_hlsl, L"cs_6_6", work); + try { + native = compiler.compile(module, L"cs_6_6", work, x2w::ShaderSourceFormat::dxil_ir); + } catch (const std::exception &error) { + std::printf("FAIL: the native module was refused by the compiler or validator: %s\n", error.what()); + return 3; + } + + // Both containers go to the work directory so the check script can print how they differ. + for (const auto &[name, shader] : {std::pair<const char *, const x2w::CompiledShader *>{"reference.dxil", &reference}, + std::pair<const char *, const x2w::CompiledShader *>{"native.dxil", &native}}) + std::ofstream(work / name, std::ios::binary) + .write(reinterpret_cast<const char *>(shader->dxil.data()), static_cast<std::streamsize>(shader->dxil.size())); + + // Root signature: root SRV t0 (selector), root UAV u0 (output), and the heap indexed directly. + D3D12_ROOT_PARAMETER1 parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC versioned{}; + versioned.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; + versioned.Desc_1_1.NumParameters = 2; + versioned.Desc_1_1.pParameters = parameters; + versioned.Desc_1_1.Flags = static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(0x400); // CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + ComPtr<ID3DBlob> blob, error; + ComPtr<ID3D12RootSignature> root; + if (FAILED(D3D12SerializeVersionedRootSignature(&versioned, &blob, &error)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)))) { + std::puts("FAIL: root signature with the heap-indexed flag"); + return 4; + } + ComPtr<ID3D12PipelineState> states[2]; + const x2w::CompiledShader *shaders[2]{&reference, &native}; + for (int k = 0; k < 2; ++k) { + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {shaders[k]->dxil.data(), shaders[k]->dxil.size()}; + if (FAILED(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&states[k])))) { + std::printf("FAIL: pipeline state of the %s shader\n", k ? "native" : "reference"); + return 5; + } + } + + // Heap slots 0 and 1: two raw buffers with different data. Slot 2: a buffer of another size, never selected. + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 6; + const UINT step = device->GetDescriptorHandleIncrementSize(heap_desc.Type); + ComPtr<ID3D12Resource> data[2], decoy; + void *mapped = nullptr; + for (UINT s = 0; s < 2; ++s) { + data[s] = make_buffer(device.Get(), words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + if (!data[s] || FAILED(data[s]->Map(0, nullptr, &mapped))) return 6; + for (UINT i = 0; i < words; ++i) static_cast<UINT *>(mapped)[i] = slot_word(s, i); + data[s]->Unmap(0, nullptr); + } + decoy = make_buffer(device.Get(), words * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = words; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + for (ID3D12Resource *r : {data[0].Get(), data[1].Get(), decoy.Get()}) { + device->CreateShaderResourceView(r, &srv, cpu); + cpu.ptr += step; + } + + auto selection = make_buffer(device.Get(), 256, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto output = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto seed = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + auto readback = make_buffer(device.Get(), (words + 1) * 4, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + if (!selection || !output || !seed || !readback) return 6; + Gpu gpu; + if (!gpu.open(device.Get())) return 6; + int failures = 0; + for (int k = 0; k < 2; ++k) { + const char *name = k ? "native" : "reference"; + std::vector<UINT> seen[2]; + for (UINT selected = 0; selected < 2; ++selected) { + seed->Map(0, nullptr, &mapped); + for (UINT i = 0; i < words; ++i) static_cast<UINT *>(mapped)[i] = sentinel; + static_cast<UINT *>(mapped)[words] = guard_word; + seed->Unmap(0, nullptr); + selection->Map(0, nullptr, &mapped); + static_cast<UINT *>(mapped)[0] = selected; + selection->Unmap(0, nullptr); + const bool ok = gpu.run([&](ID3D12GraphicsCommandList *list) { + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyResource(output.Get(), seed.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap *heaps[]{heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(states[k].Get()); + list->SetComputeRootShaderResourceView(0, selection->GetGPUVirtualAddress()); + list->SetComputeRootUnorderedAccessView(1, output->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(), output.Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + }); + if (!ok || FAILED(device->GetDeviceRemovedReason())) { + std::printf("FAIL: %s dispatch selecting slot %u did not complete\n", name, selected); + return 7; + } + readback->Map(0, nullptr, &mapped); + seen[selected].assign(static_cast<UINT *>(mapped), static_cast<UINT *>(mapped) + words + 1); + readback->Unmap(0, nullptr); + bool match = true; + for (UINT i = 0; i < words; ++i) match &= seen[selected][i] == slot_word(selected, i); + const bool guard = seen[selected][words] == guard_word; + std::printf("%s selector %u: data %s, guard %s\n", name, selected, match ? "matches the CPU reference" : "DIFFERS", + guard ? "intact" : "OVERWRITTEN"); + failures += !match || !guard; + } + if (seen[0] == seen[1]) { + std::printf("FAIL: %s read the same data for both selectors\n", name); + ++failures; + } + } + std::puts(failures ? "native_heap_handle_probe: FAIL" : "native_heap_handle_probe: PASS"); + return failures ? 1 : 0; + } catch (const std::exception &error) { + std::printf("FAIL: %s\n", error.what()); + return 8; + } +} diff --git a/tests/native_heap_handle_probe_check.py b/tests/native_heap_handle_probe_check.py new file mode 100644 index 0000000000..eb9fa22c1a --- /dev/null +++ b/tests/native_heap_handle_probe_check.py @@ -0,0 +1,58 @@ +"""Cycle 1 of the global SRV work: compile a reference ResourceDescriptorHeap shader with DXC, show how DXC spells the heap handle and +its shader flags, then run the native heap-handle probe with those flags (exit 77 from the probe is a skip).""" +import re +import subprocess +import sys +import tempfile +from pathlib import Path + + +REFERENCE = """ByteAddressBuffer selection : register(t0); +RWByteAddressBuffer output : register(u0); +[numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { + ByteAddressBuffer data = ResourceDescriptorHeap[selection.Load(0)]; + output.Store(id.x * 4, data.Load(id.x * 4)); +} +""" + + +def main(probe, sdk, adapter): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source = work / "reference.hlsl" + source.write_text(REFERENCE) + listing = work / "reference.ll" + subprocess.run([str(Path(sdk) / "dxc.exe"), "-T", "cs_6_6", "-E", "main", "-Fc", str(listing), str(source)], check=True, + capture_output=True) + text = listing.read_text() + flags = re.search(r"!\{i32 0, i64 (\d+)", text) + if not flags: + raise AssertionError("the reference listing has no shader flags tag") + for line in text.splitlines(): + if "createHandleFromHeap" in line or "annotateHandle(i32 216" in line and "ResourceProperties { i32 11" in line: + print("reference:", line.strip()) + print("reference shader flags:", flags.group(1)) + result = subprocess.run([probe, adapter, sdk, str(work / "probe"), flags.group(1)], capture_output=True, text=True) + print(result.stdout, end="") + print(result.stderr, end="") + if result.returncode not in (0, 77): + # Show how the two containers differ (module, shader flags, pipeline state validation data). + import difflib + listings = {} + for name in ("reference", "native"): + container = work / "probe" / f"{name}.dxil" + if container.exists(): + listings[name] = subprocess.run([str(Path(sdk) / "dxc.exe"), "-dumpbin", str(container)], + capture_output=True, text=True).stdout.splitlines() + if len(listings) == 2: + diff = list(difflib.unified_diff(listings["reference"], listings["native"], "reference", "native", lineterm="", n=1)) + print("\n".join(diff[:160])) + if result.returncode == 77: + return 77 + assert result.returncode == 0, f"probe exit {result.returncode}" + assert "native_heap_handle_probe: PASS" in result.stdout + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:4])) diff --git a/tests/native_heap_offset_add_check.py b/tests/native_heap_offset_add_check.py new file mode 100644 index 0000000000..4d5f8978b2 --- /dev/null +++ b/tests/native_heap_offset_add_check.py @@ -0,0 +1,84 @@ +"""A slot 67 request that forms its resource-heap descriptor address by adding a byte offset (issue #3224). + +usage: native_heap_offset_add_check.py COMPILE_DXIL SDK + +A waterfall loop over a lane-selected heap slot adds the slot's byte offset to the heap base and carries into the high +word instead of passing the offset as the SGPR offset of the load: + + s_add_u32 s10, s5, s8 ; s_add_u32 s11, 0, src_scc ; s_load_dwordx4 s[12:15], s[10:11], 0x0 + +The requests are written from source with the entry layout of the start-up shaders that do this: user SGPRs s4 (a +descriptor table), s5 (the resource heap) and s6 (the sampler heap) under both directly indexed heap flags, wave32. Such a +load is the same GPU-selected heap read as the SGPR-offset form, so both now stop at the heap view contract, which a +.c67 request has no metadata for. Before this change the add was refused as a numeric use of the heap table. The +controls keep their refusals: a high word that is not the carry of the add, SCC clobbered between the adds, and a +constant offset. The GPU readback of the same address form is in native_global_srv_heap_replay_check.py (section 11). +Encodings were checked with tools/disasm_rdna2.py; the test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + +ROOT = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +HEAP_CONTRACT = "direct resource-heap load requires the selected GPU slot and its view type" +HIGH_WORD = "heap descriptor address high word is not the carry of its offset add" +SELECT = [0x7E100500, 0x8F088508] # v_readfirstlane_b32 s8, v0 ; s_lshl_b32 s8, s8, 5 +ADD_LO, ADD_HI = 0x800A0805, 0x800BFD80 # s_add_u32 s10, s5, s8 ; s_add_u32 s11, 0, src_scc +LOAD = [0xF4080305, 0xFA000000] # s_load_dwordx4 s[12:15], s[10:11], 0x0 +END = [0xBF8CC07F, 0xBF810000] # s_waitcnt lgkmcnt(0) ; s_endpgm +PROGRAMS = { + "added": (SELECT + [ADD_LO, ADD_HI] + LOAD + END, HEAP_CONTRACT), + # s_mov_b32 s10, s5 ; s_mov_b32 s11, 0 ; s_load_dwordx4 s[12:15], s[10:11], s8: the SGPR-offset form + "sgpr_offset": (SELECT + [0xBE8A0305, 0xBE8B0380, 0xF4080305, 0x10000000] + END, HEAP_CONTRACT), + # s_mov_b32 s11, 0 instead of the carry + "mov_high": (SELECT + [ADD_LO, 0xBE8B0380] + LOAD + END, HIGH_WORD), + # s_cmp_lg_u32 s8, s8 between the adds + "scc_clobbered": (SELECT + [ADD_LO, 0xBF070808, ADD_HI] + LOAD + END, HIGH_WORD), + # s_add_u32 s10, s5, 0x40: a constant offset is not a GPU selection; the heap table is used as a number + "constant": (SELECT + [0x800AFF05, 0x40, ADD_HI] + LOAD + END, "unbound numeric SGPR s5"), + # Wave64, s_load_dwordx4 s[104:107], s[10:11], 0x0: the slot index would be written into VCC, which the wave64 + # model keeps as mask data, so the overlap refusal comes before the heap contract. + "wave64_vcc_dst": (SELECT + [ADD_LO, ADD_HI, 0xF4081A05, 0xFA000000] + END, + "symbolic scalar memory destination overlaps wave64 VCC", 64), +} + + +def main(compile_dxil, sdk): + failures = 0 + with tempfile.TemporaryDirectory(prefix="x2w_heap_offset_add_") as scratch: + base = pathlib.Path(scratch) + source = base / "root.hlsl" + source.write_text(f'#define RS "{ROOT}"') + binary = base / "root.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + root = binary.read_bytes() + for name, (program, expected, *wave) in PROGRAMS.items(): + # Group 32x1x1 in wave32 (bit 20 of dword 4), or 64x1x1 in wave64, 7 user SGPRs. + threads = wave[0] if wave else 32 + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1 | (0 if wave else 1 << 20), 0, 7 << 1) + folder = base / name + folder.mkdir() + marker = write_request(folder, program, root, sa) + output = marker.with_suffix(".cso") + result = subprocess.run([compile_dxil, sdk, base / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True, timeout=60) + ok = result.returncode != 0 and expected in result.stderr and not output.exists() + print(("ok: " if ok else "FAIL: ") + f"{name}: refused with '{expected}' and no .cso") + if not ok: + print(result.stdout + result.stderr) + failures += 1 + if failures: + return 1 + print("native_heap_offset_add: all checks passed") + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 3: + raise SystemExit(__doc__) + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_image_atomic_binops_check.py b/tests/native_image_atomic_binops_check.py new file mode 100644 index 0000000000..f8ce9f287b --- /dev/null +++ b/tests/native_image_atomic_binops_check.py @@ -0,0 +1,110 @@ +"""Check new direct DXIL integer atomics on the typed 2D uint UAV.""" +from pathlib import Path +import operator +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, words +from native_image_atomic_check import ( + OPERAND, TEXELS, UINT_MASK, WIDTH, image_atomic, program_words, reference, render, +) + + +OPS = { + 'swap': (0x0f, 8, 1 << 28, lambda old, operand: operand), + 'umin': (0x15, 6, 1 << 27, min), + 'and': (0x18, 1, 1 << 25, operator.and_), + 'or': (0x19, 2, 1 << 25, operator.or_), + 'xor': (0x1a, 3, 1 << 25, operator.xor), +} +REFUSED = {'sub': 0x12, 'smin': 0x14, 'smax': 0x16, 'inc': 0x1b, 'dec': 0x1c, + 'fcmpswap': 0x1d, 'fmin': 0x1e, 'fmax': 0x1f} +OPERAND_DIAGNOSTIC = 'unsupported typed 2D image atomic operands' + + +def compile_shader(cli, sdk, work, opcode, *, glc=True, sparse=False, contend=False, **encoding): + # Retain the fixture's coordinates, EXEC mask, wait, and old-value probe. + # With GLC clear the probe observes the original data VGPR instead. + code = program_words('add', returning=True, drop_glc=not glc, sparse=sparse, + contend=contend, **encoding) + flags = encoding.get('flags', 0) | (0x2000 if glc else 0) + atomic_word, _ = image_atomic('add', flags=flags, mask=encoding.get('mask'), dim=encoding.get('dim', 1)) + index = code.index(atomic_word) + code[index] = (atomic_word & ~(0x7f << 18)) | (opcode << 18) + if contend: + # The original fixture uses 1 for contended add. Exercise the same + # high-bit operand as the distinct-texel case here. + code[code.index(0x7e1c02ff) + 1] = OPERAND + source = work / 'binop.cs' + shader = source.with_suffix('.cso') + shader.unlink(missing_ok=True) + source.write_bytes(compute(words(*code), table=True)) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, result + + +def controls(cli, sdk, work): + for name, (opcode, dxil, _, _) in OPS.items(): + shader, run = compile_shader(cli, sdk, work, opcode) + assert run.returncode == 0, ( + f'{name}: valid typed image atomic refused (operand diagnostic: {OPERAND_DIAGNOSTIC})', + run.stdout, run.stderr, + ) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', shader], + capture_output=True, text=True, timeout=30, check=True).stdout + # The second atomic is the existing add probe and must have code 0. + codes = re.findall(r'@dx\.op\.atomicBinOp\.i32\(i32 78, %dx\.types\.Handle [^,]+, i32 (\d+),', dump) + assert codes == [str(dxil), '0'] and '2d' in dump, (name, dump) + for encoding in ({'dim': 5}, {'mask': 15}, {'coord': 255}, {'flags': 0x80}, + {'addr_flags': 0x40000000}, {'addr_flags': 0x200000}): + _, run = compile_shader(cli, sdk, work, opcode, **encoding) + assert run.returncode and OPERAND_DIAGNOSTIC in run.stderr, (name, encoding, run.stdout, run.stderr) + for name, opcode in REFUSED.items(): + _, run = compile_shader(cli, sdk, work, opcode) + assert run.returncode and 'direct image opcode or descriptor modifiers' in run.stderr, ( + name, run.stdout, run.stderr, + ) + print('Typed image binary atomic DXIL codes and refusal diagnostics matched') + + +def expected_texels(update, *, glc, contend): + initial, _ = reference('add') + expected = initial.copy() + for lane in range(0, 32, 2): + x, y = (5, 6) if contend else (2 + lane % 8, 1 + lane // 8) + index = y * WIDTH + x + previous = expected[index] + expected[index] = update(previous, OPERAND) + # Contending lanes use the same operand, so the aggregate of returned + # values depends only on the number of updates, regardless of order. + probe = index + 12 + expected[probe] = (expected[probe] + (previous if glc else OPERAND)) & UINT_MASK + return initial, expected + + +def hardware(cli, sdk, work, renderer, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, (wave.stdout, wave.stderr) + print(wave.stdout, end='') + for name, (opcode, _, format_selector, update) in OPS.items(): + for contend in (False, True): + for glc in (False, True): + shader, run = compile_shader(cli, sdk, work, opcode, glc=glc, sparse=True, contend=contend) + assert run.returncode == 0, (name, glc, contend, run.stdout, run.stderr) + initial, expected = expected_texels(update, glc=glc, contend=contend) + payload = work / 'texture.bin' + payload.write_bytes(words(1 | format_selector, 0, *initial, *expected)) + run = render(renderer, adapter, '--compute-texture-store-case', shader, payload) + assert run.returncode == 0, (name, glc, contend, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{name} GLC={glc} contended={contend}: {TEXELS} texture words matched') + + +if __name__ == '__main__': + mode, cli, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + {'controls': controls, 'hardware': hardware}[mode](cli, sdk, Path(temp), *args) diff --git a/tests/native_image_atomic_check.py b/tests/native_image_atomic_check.py new file mode 100644 index 0000000000..69365503a3 --- /dev/null +++ b/tests/native_image_atomic_check.py @@ -0,0 +1,192 @@ +"""Exercise typed 2D image atomics generated by the native DXIL compiler.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, words +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import sop1 +from startup_compute_dispatch_check import lines +from startup_compute_dispatch_texture_check import clean, run as run_consumer +from startup_compute_image_store_d16_check import RSRC2 +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import root_blob + + +OPS = {'add': 17, 'umax': 23, 'cmpswap': 16} +OPERAND = 0x80000011 +COMPARE = 0x00000020 +UINT_MASK = 0xffffffff +WIDTH = 32 +TEXELS = 336 # 32x8, 16x4, and 8x2 in the shared texture-store runner. +FORMATS = {'add': 1 << 25, 'umax': 1 << 27, 'cmpswap': 1 << 29} + + +def image_atomic(op, *, coord=8, data=14, resource=8, flags=0, mask=None, dim=1, addr_flags=0): + mask = (3 if op == 'cmpswap' else 1) if mask is None else mask + return [0xF0000000 | OPS[op] << 18 | flags | mask << 8 | dim << 3, + (resource // 4) << 16 | data << 8 | coord | addr_flags] + + +def program_words(op, *, returning=False, drop_glc=False, sparse=False, contend=False, resource=8, **encoding): + # s[0:1] points to a table. Read one complete image descriptor into s[8:15]. + code = [0xBE810380, 0xF40C0200, 0xFA000000, 0xBF8CC07F] + if contend: + code += [0x7E100285, 0x7E120286] + else: + code += [vop2(0x1b, 8, 135, 0), vop2(0x16, 9, 131, 0), + vop2(0x25, 8, 130, 8), vop2(0x25, 9, 129, 9)] + code += [0x7E1C02FF, 1 if contend else OPERAND] + if op == 'cmpswap': + code += [0x7E1E02FF, COMPARE] + if sparse: + code += [sop1(3, 126, 255), 0x55555555] + flags = encoding.pop('flags', 0) | (0x2000 if returning and not drop_glc else 0) + code += image_atomic(op, flags=flags, resource=resource, **encoding) + if returning: + # Use the returned old value as the data of a second write. Its + # destination is disjoint from the first, so each lane has an oracle. + code += [0xBF8C3F70, vop2(0x25, 8, 140, 8), *image_atomic('add', resource=resource)] + code += [0xBBFD0000, 0xBF810000] + return code + + +def compile_shader(cli, sdk, work, op, **options): + source = work / f'{op}.cs' + shader = source.with_suffix('.cso') + shader.unlink(missing_ok=True) + source.write_bytes(compute(words(*program_words(op, **options)), table=True)) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, result + + +def controls(cli, sdk, work): + for op in OPS: + shader, run = compile_shader(cli, sdk, work, op, returning=True) + assert run.returncode == 0, (op, run.stdout, run.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', shader], + capture_output=True, text=True, timeout=30, check=True).stdout + operation = ('@dx.op.atomicCompareExchange.i32(i32 79,' if op == 'cmpswap' + else '@dx.op.atomicBinOp.i32(i32 78,') + assert operation in dump and '2d' in dump, dump + for options in ({'dim': 5}, {'mask': 15}, {'coord': 255}, {'flags': 0x80}, + {'addr_flags': 0x40000000}, {'addr_flags': 0x200000}, + *(({'data': 255},) if op == 'cmpswap' else ())): + _, run = compile_shader(cli, sdk, work, op, **options) + assert run.returncode and 'unsupported typed 2D image atomic operands' in run.stderr, ( + op, options, run.stdout, run.stderr) + print('Typed image atomics compiled and unsupported dimensions, operands and modifiers were refused') + + +def reference(op, *, returning=False, sparse=False, contend=False): + initial = [0x10f00000 + i for i in range(TEXELS)] + for lane in range(32): + x, y = 2 + lane % 8, 1 + lane // 8 + initial[y * WIDTH + x] = (COMPARE, 0x7ffffff0, 0xfffffff0, OPERAND)[lane % 4] + expected = initial.copy() + for lane in range(32): + if sparse and lane % 2: + continue + x, y = (5, 6) if contend else (2 + lane % 8, 1 + lane // 8) + index = y * WIDTH + x + previous = expected[index] + if op == 'add': + expected[index] = (previous + (1 if contend else OPERAND)) & UINT_MASK + elif op == 'umax': + expected[index] = max(previous, OPERAND) + elif previous == COMPARE: + expected[index] = OPERAND + if returning: + probe = index + 12 + expected[probe] = (initial[probe] + previous) & UINT_MASK + return initial, expected + + +def render(renderer, adapter, *args): + run = subprocess.run([renderer, adapter, *args], capture_output=True, text=True, timeout=30) + if run.returncode == 77: + print(run.stdout + run.stderr, end='') + raise SystemExit(77) + return run + + +def hardware(cli, sdk, work, renderer, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, (wave.stdout, wave.stderr) + print(wave.stdout, end='') + for op, cases in ( + ('add', ({}, {'sparse': True, 'contend': True}, {'returning': True})), + ('umax', ({}, {'returning': True, 'sparse': True})), + ('cmpswap', ({}, {'returning': True, 'sparse': True})), + ): + for options in cases: + shader, run = compile_shader(cli, sdk, work, op, **options) + assert run.returncode == 0, (op, options, run.stdout, run.stderr) + initial, expected = reference(op, **options) + payload = work / 'texture.bin' + payload.write_bytes(words(1 | FORMATS[op], 0, *initial, *expected)) + run = render(renderer, adapter, '--compute-texture-store-case', shader, payload) + assert run.returncode == 0, (op, options, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{op} {options}: {TEXELS} texture words matched') + if options.get('returning'): + # Same guest instruction without GLC cannot produce the old word. + mutant, result = compile_shader(cli, sdk, work, op, drop_glc=True, **options) + assert result.returncode == 0, (result.stdout, result.stderr) + rejected = render(renderer, adapter, '--compute-texture-store-case', mutant, payload) + assert rejected.returncode == 1 and 'mip=0' in rejected.stderr, ( + op, options, rejected.stdout, rejected.stderr) + print(f'{op} with GLC cleared: {rejected.stderr.strip()}') + + +def runtime(cli, sdk, work, renderer, consumer, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, (wave.stdout, wave.stderr) + print(wave.stdout, end='') + cache, env = prepare(work) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1', X2W_TEST_DISPATCH_HARDWARE='1') + env.pop('X2W_NATIVE_SHADERS', None) + root = work / 'compute_root' + root.write_bytes(root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(root) + code = program_words('add', sparse=True, contend=True, resource=24) + # Slot 67 supplies the table at s7. The consumer writes the texture view + # at table byte 64, following the three root constants. + code[:3] = [0xBE8C0307, 0xBE8D0380, 0xF40C0606, 0xFA000040] + (work / 'program').write_bytes(words(*code)) + (work / 'data').write_bytes(DATA) + (work / 'state').write_bytes(state_a((32, 1, 1), RSRC2)) + + initial = [0x10f00000 + i for i in range(WIDTH * 8)] + expected = initial.copy() + expected[6 * WIDTH + 5] += 32 # 16 active lanes per group, two groups. + got, result = run_consumer(work, consumer, env, 'texture-store-atomic', '<256I') + assert got == initial and lines(result, 'refused: no translation'), result.stderr[-3000:] + requests = lines(result, 'x2w-draw compute request') + assert len(requests) == 1, result.stderr[-3000:] + key = requests[0].split()[3] + + compiled = subprocess.run([cli, sdk, work / 'compiler-cache', 'gfx1013-direct-cs@0', + '--requests', cache, cache], capture_output=True, text=True, timeout=30) + manifest = cache / f'{key}.txt' + assert compiled.returncode == 0 and manifest.is_file(), (compiled.stdout, compiled.stderr) + assert 'uav 0 tex2d uint table 1 64 channels 1' in manifest.read_text().splitlines() + got, result = run_consumer(work, consumer, env, 'texture-store-atomic', '<256I') + wrong = next((i for i, pair in enumerate(zip(got, expected, strict=True)) if pair[0] != pair[1]), None) + assert wrong is None, (wrong, got[wrong], expected[wrong], result.stderr[-3000:]) + assert lines(result, 'Dispatch(2, 1, 1) translated'), result.stderr[-3000:] + layer = clean(result) + got, result = run_consumer(work, consumer, env, 'texture-store', '<1024H') + assert got == [0x5000 + i for i in range(1024)], result.stderr[-3000:] + assert lines(result, 'refused: an image atomic requires an R32_UINT UAV'), result.stderr[-3000:] + print(f'Published DXIL matched all 256 words and the float UAV stayed unchanged; debug layer {layer}') + + +if __name__ == '__main__': + mode, cli, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + {'controls': controls, 'hardware': hardware, 'runtime': runtime}[mode](cli, sdk, Path(temp), *args) diff --git a/tests/native_image_cache_flags_check.py b/tests/native_image_cache_flags_check.py new file mode 100644 index 0000000000..4fd7df93c9 --- /dev/null +++ b/tests/native_image_cache_flags_check.py @@ -0,0 +1,136 @@ +"""Verify GLC and DLC cache-policy flags on direct read-only image ops (#3242).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, patched_pixel, words +import native_gather_lod_check as G + +GLC = 0x2000 +DLC = 0x0080 +SLC = 0x02000000 +ALL_CACHE = GLC | DLC | SLC +REFUSED = 'direct image opcode or descriptor modifiers' + + +def ro_program(op, stage, *, flags=0, w1_flags=0): + code = [0xBE810380, 0xF40C0200, 0xFA000000] # s[8:15] texture descriptor + if stage == 'cs': + code += [0xF4080800, 0xFA000020, 0x7E060280] # s[32:35] UAV, v3 = 0 + for reg, value in enumerate((0x12, 512 << 12, 0x04500000, 0), start=4): + code += [0xBE8003FF | (reg << 16), value] + coords = (0.5, 0.5, 0.0) if op >= 32 else (0, 0, 0) + for reg, value in enumerate(coords): + encoded = struct.unpack('<I', struct.pack('<f', value))[0] if op >= 32 else value + code += [0x7E0002FF | (reg << 17), encoded] + sampler_field = (1 << 21) if op >= 32 else 0 + dmask = 1 if op in (68, 71) else 0xF + code += [0xBF8CC07F, 0xF0000008 | (op << 18) | (dmask << 8) | flags, 0x00020400 | sampler_field | w1_flags, 0xBF8C3F70] + if stage == 'cs': + return compute(words(*code, 0xE0781000, 0x80080403, 0xBF810000), threads=1, table=True) + return patched_pixel(len(code), code, table=True, export=(0xF800180F, 0x07060504)) + + +def store_program(stage, *, flags=0): + code = [0xBE810380, 0xF40C0200, 0xFA000000, 0xBF8CC07F, + 0x7E000280, 0x7E020280, + 0xF0000F08 | (8 << 18) | flags, 0x00020400, 0xBF810000] + if stage == 'cs': + return compute(words(*code), threads=1, table=True) + return patched_pixel(len(code), code, table=True, export=(0xF800180F, 0x07060504)) + + +def compile_bytes(cli, sdk, work, label, stage, blob): + src = work / f'{label}.{stage}' + src.write_bytes(blob) + cso = src.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', f'gfx1013-container-{stage}', src, cso], + capture_output=True, text=True, timeout=30) + return cso, run + + +def controls(cli, sdk, work): + ops = ( + ('image_load', 0, '@dx.op.textureLoad.f32'), + ('image_load_mip', 1, '@dx.op.textureLoad.f32'), + ('image_getresinfo', 14, '@dx.op.getDimensions'), + ('image_sample_lz', 39, '@dx.op.sampleLevel.f32'), + ('image_gather4_lz', 71, '@dx.op.textureGather.f32'), + ('image_gather4_l', 68, '@dx.op.textureLoad.f32'), + ) + accepted = 0 + for stage in ('cs', 'ps'): + for name, op, expected_dxil in ops: + base_cso, base_run = compile_bytes(cli, sdk, work, f'{name}-base', stage, ro_program(op, stage)) + assert base_run.returncode == 0 and base_cso.is_file(), (stage, name, base_run.stdout, base_run.stderr) + base_dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', base_cso], + capture_output=True, text=True, check=True).stdout + assert expected_dxil in base_dump, (stage, name, expected_dxil, base_dump) + for tag, fl in (('glc', GLC), ('dlc', DLC), ('slc', SLC), ('all', ALL_CACHE)): + cso, run = compile_bytes(cli, sdk, work, f'{name}-{tag}', stage, ro_program(op, stage, flags=fl)) + assert run.returncode == 0 and cso.is_file(), (stage, name, tag, run.stdout, run.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', cso], + capture_output=True, text=True, check=True).stdout + assert dump == base_dump, (stage, name, tag) + accepted += 1 + + refusals = ( + ('store_glc', lambda st: store_program(st, flags=GLC)), + ('store_dlc', lambda st: store_program(st, flags=DLC)), + ('sample_r128', lambda st: ro_program(39, st, flags=0x8000)), + ('sample_tfe', lambda st: ro_program(39, st, flags=0x10000)), + ('sample_lwe', lambda st: ro_program(39, st, flags=0x20000)), + ('sample_res_bit6', lambda st: ro_program(39, st, flags=0x0040)), + ('sample_res_bit14', lambda st: ro_program(39, st, flags=0x4000)), + ('sample_res_w1_bit26', lambda st: ro_program(39, st, w1_flags=1 << 26)), + ) + refused = 0 + for stage in ('cs', 'ps'): + for rname, builder in refusals: + _, run = compile_bytes(cli, sdk, work, f'ref-{rname}', stage, builder(stage)) + assert run.returncode != 0 and REFUSED in run.stderr, (stage, rname, run.returncode, run.stderr) + refused += 1 + + print(f'native_image_cache_flags controls: {accepted} flagged DXIL modules matched plain baselines; {refused} refusals matched') + return 0 + + +def execute(cli, sdk, renderer, adapter, stage, work): + if stage == 'cs': + wave = G.render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + cases = (G.CASES[0], G.CASES[1], G.CASES[3], G.CASES[7]) + flag_sets = (('glc', GLC), ('dlc', DLC), ('glc_dlc_slc', ALL_CACHE)) + for case in cases: + for tag, flags in flag_sets: + cso, run = G.compile_shader(cli, sdk, work, case, stage, flags=flags) + assert run.returncode == 0, (stage, case.name, tag, run.stdout, run.stderr) + reference = work / 'expected.bin' + if stage == 'ps': + G.write_case(reference, 3 - case.first, case.first, [G.taps(case)] * (G.SIDE ** 2)) + res = G.render(renderer, adapter, '--check-pixel-gather', cso, reference) + assert res.returncode == 0 and 'pixels=64 channels=256 max_absolute_error=0' in res.stdout, ( + stage, case.name, tag, res.stdout, res.stderr) + else: + expected = G.compute_reference(case.first + case.relative, case.channel, case.uv) + res = G.render_compute(renderer, adapter, cso, reference, case.first, expected) + assert res.returncode == 0 and 'compared_words=320 mismatches=0' in res.stdout, ( + stage, case.name, tag, res.stdout, res.stderr) + if 'debug_layer=enabled' in res.stdout: + assert 'debug_errors=0 debug_warnings=0' in res.stdout, res.stdout + print(f'native_image_cache_flags {stage} ({adapter}): {len(cases) * len(flag_sets)} cached-flag cases matched') + return 0 + + +def main(mode, cli, sdk, *args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'controls': + return controls(cli, sdk, work) + return execute(cli, sdk, args[0], args[1], mode, work) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_image_store_exact_width_check.py b/tests/native_image_store_exact_width_check.py new file mode 100644 index 0000000000..b5b4ba620c --- /dev/null +++ b/tests/native_image_store_exact_width_check.py @@ -0,0 +1,116 @@ +"""Compile source-built gfx1013 image stores and exercise the startup Dispatch binder.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from native_direct_container_check import words +from startup_compute_dispatch_check import lines +from startup_compute_dispatch_texture_check import clean, run +from startup_compute_image_store_check import ARRAY_END, ARRAY_PROLOGUE, ARRAY_SLICE, RSRC2 +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import root_blob + + +CASES = { + "r": (1, 1, "tex2d", 1), + "rg": (3, 1, "tex2d", 2), + "rgb": (7, 1, "tex2d", 1), + "array": (7, 5, "tex2da", 1), + "volume": (7, 2, "tex3d", 1), + "rgba": (7, 1, "tex2d", 1), + "sparse": (9, 1, "tex2d", 1), +} +OPCODE_REFUSAL = "direct image opcode or descriptor modifiers" +CHANNEL_REFUSAL = "an exact-width image store requires a matching output texture channel count" + + +def program(mask, dimension): + # ARRAY_PROLOGUE loads the image descriptor from table 1 + 64 into s[24:31]. + # v8 = 4 * group_id.x + local_id.x, v9 = 2 * group_id.y + local_id.y. + # v10 = 1 for array/volume. EXEC explicitly selects the even lanes of each 4x2 group. + values = (0x3F800000, 0x40000000, 0x40800000) + data = [] + for i in range(mask.bit_count()): + data.extend((0x7E1C02FF + (i << 17), values[i])) # v_mov_b32 v14+i, literal + store = words(0xF0201000 | (mask << 8) | (dimension << 3), 0x00060E08) + return (ARRAY_PROLOGUE + ARRAY_SLICE[1] + words(0xBF8CC07F) + words(*data) + + words(0xBEFE03FF, 0x55) + store + ARRAY_END) + + +def check(directory, cli, sdk, consumer, adapter, case): + mask, dimension, view, texel_words = CASES[case] + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1", + X2W_TEST_COMPUTE_ROOT=str(directory / "compute_root")) + env.pop("X2W_NATIVE_SHADERS", None) + env.pop("X2W_TEST_DISPATCH_HARDWARE", None) + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(root_blob(3, table_range=True)) + (directory / "program").write_bytes(program(mask, dimension)) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a((4, 2, 1), RSRC2)) + + # Each mip under test is 32x8. Array/volume use six slices and a view starting + # at slice 1, so the shader's relative coordinate 1 writes physical slice 2. + layers = 6 if dimension != 1 else 1 + initial = [0x30000000 + i for i in range(layers * 32 * 8 * texel_words)] + mode = "texture-exact-" + ("rgba" if case == "sparse" else case) + layout = f"<{len(initial)}I" + got, result = run(directory, consumer, env, mode, layout) + assert got == initial and lines(result, "Dispatch(2, 1, 1) refused: no translation"), result.stderr + key = lines(result, "x2w-draw compute request")[0].split()[3] + compiled = subprocess.run([cli, sdk, directory / "compiler-cache", "gfx1013-direct-cs@0", + "--requests", cache, cache], capture_output=True, text=True, timeout=30) + diagnostic = compiled.stdout + compiled.stderr + manifest = cache / f"{key}.txt" + if case == "sparse": + assert compiled.returncode and OPCODE_REFUSAL in diagnostic and not manifest.exists(), diagnostic + print(diagnostic, end="") + return 0 + assert compiled.returncode == 0 and manifest.is_file(), diagnostic + assert f"uav 0 {view} float table 1 64 channels {mask.bit_count()}" in manifest.read_text().splitlines() + + expected = initial.copy() + if case != "rgba": + # Packed unsigned floats for (1, 2, 4), with 6/6/5 mantissa bits. + packed = 0x3C0 | (0x400 << 11) | (0x220 << 22) + values = {"r": [0x3F800000], "rg": [0x3F800000, 0x40000000]}.get(case, [packed]) + for y in range(2): + for x in (0, 2, 4, 6): # two X groups, local lanes 0, 2, 4 and 6 in each group + i = (((2 if layers > 1 else 0) * 8 + y) * 32 + x) * texel_words + expected[i:i + texel_words] = values + + # Native translation first with the published manifest removed (no fallback), so an + # adapter without 32-lane waves reports the capability skip before any PSO is made; + # then bind solely from the restored manifest. + published = manifest.read_bytes() + for native in (True, False): + if native: + manifest.unlink() + env["X2W_NATIVE_SHADERS"] = sdk + else: + manifest.write_bytes(published) + env.pop("X2W_NATIVE_SHADERS", None) + got, result = run(directory, consumer, env, mode, layout) + if native and lines(result, "not translated natively: the adapter has no 32-lane waves"): + assert got == initial, result.stderr + return 77 + assert got == expected, (case, native, result.stderr, + next(i for i, (actual, want) in enumerate(zip(got, expected)) if actual != want)) + if native: + assert lines(result, "translated natively:"), result.stderr + if case == "rgba": + assert lines(result, f"Dispatch(2, 1, 1) refused: {CHANNEL_REFUSAL}"), result.stderr + else: + assert lines(result, "Dispatch(2, 1, 1) translated"), result.stderr + clean(result) + print(f"{adapter} {case}: checked all {len(initial)} words through both binders") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/native_indexed_atomic_check.py b/tests/native_indexed_atomic_check.py new file mode 100644 index 0000000000..a1bcdf3061 --- /dev/null +++ b/tests/native_indexed_atomic_check.py @@ -0,0 +1,100 @@ +"""Check indexed atomics against recorded structured, raw and typed UAV windows.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request +from native_scalar_lds_check import sop1, scalar, vmove + + +def program(mutant): + # s4 is the table, s5 is group.x. Only lane zero may perform each atomic. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 126, 129), + scalar(0x1e, 7, 5, 132), scalar(0, 7, 7, 132), scalar(0x1e, 8, 5, 135), vmove(8, 8)] + for j in range(5): + words += [0xf4080000 | ((32 + 4*j) << 6) | 10, 0xfa000000 | (32 + 32*j)] + for j in range(4): + slot, first = (8 + j) << 16, 10 + 3*j + # Aliased vaddr/vdata. GLC returns the original value. Without GLC + # the source stays unchanged. The huge unsigned index must never wrap. + words += [vmove(1, 7), 0xe0c86000, 0x80000101 | slot, vmove(first, 257), + vmove(1, 7), vmove(2, 132 if mutant else 131), 0xe0c82000, 0x80000201 | slot, + vmove(first+1, 258), vmove(1, 193), 0xe0c86000, 0x80000201 | slot, vmove(first+2, 258)] + for j in range(12): + words += [0xe0701000 | (4*j), 0x800c0008 | (10+j) << 8] + # Only group zero touches each window's last complete dword. Group one + # keeps a different pre-existing VGPR value while EXEC is empty. + for j in range(4): + slot = (8 + j) << 16 + last = 8188 if j == 3 else 2047 + words += [vmove(2, 137), vmove(3, 137), vmove(1, 255), last, vmove(4, 255), last + 1, + 0xbf068005, scalar(0x0a, 126, 129, 128), + 0xe0c86000, 0x80000201 | slot, 0xe0c86000, 0x80000304 | slot, sop1(3, 126, 129), + 0xe0701000 | (48 + 8*j), 0x800c0208, 0xe0701000 | (52 + 8*j), 0x800c0308] + return words + [0xbf810000] + + +def check_output(blob, layout, mutant): + rest = memoryview(blob) + for _, offset, _, stride, write in layout: + assert write == 1 + words = (2048 + 16) * stride // 4 + data = struct.unpack_from(f"<{words}I", rest) + rest = rest[4 * words:] + expected = [0x69696969] * words + for group in range(2): + index = 4 + 16*group + increment = 4 if mutant else 3 + if offset == 160: + window = 8 + group*32 + expected[window:window+12] = [0x69696969, increment, 0] * 4 + expected[window+12:window+20] = ([9, 9] if group else [0x69696969, 0]) * 4 + else: + assert offset in (32, 64, 96, 128) + start = 8 * stride // 4 + word = index//4 if offset == 128 else index*stride//4 + expected[start + word] += index + increment + if not group: + last = 2047 if offset == 128 else 2047 * stride // 4 + expected[start + last] += 9 + assert data == tuple(expected), (offset, [(j, a, b) for j,(a,b) in enumerate(zip(data,expected)) if a!=b][:8]) + assert not rest and len(layout) == 5 + + +def main(cli, gpu, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work/"root.hlsl", work/"root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + sa = struct.pack("<7I",0,0,0,32 | 1<<16,1 | (1 << 20),0,0x8a) + previous = None + for mutant in (False, True): + words = program(mutant) + marker = write_request(work, words, root.read_bytes(), sa) + dest = work/"result.bin" + run = subprocess.run([gpu, sdk, marker, work/"cache", "0", dest, "--direct"], capture_output=True,text=True) + if run.returncode == 77: + print(run.stderr); sys.exit(77) + assert run.returncode == 0, run.stderr + data = dest.read_bytes() + check_output(data, [tuple(map(int,line.split())) for line in run.stdout.splitlines()], mutant) + if previous is not None: + diff = sum(a != b for a,b in zip(struct.iter_unpack("<I",previous),struct.iter_unpack("<I",data))) + assert diff == 16, diff + previous = data + slot = words.index(0xe0c86000) + for extra in (4, 0x1000, 0x8000): + invalid = words.copy() + invalid[slot] |= extra + marker = write_request(work,invalid,root.read_bytes(),sa) + r = subprocess.run([cli,sdk,work/"cache","gfx1013-direct-cs@0",marker,work/"bad.cso"], + capture_output=True,text=True) + assert r.returncode and not (work/"bad.cso").exists() and "atomic" in r.stderr, r.stderr + print("Four bound UAV shapes, old values, inactive lanes, unsigned OOB, window guards and 16-word mutation matched.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_indexed_pixel_texture_check.py b/tests/native_indexed_pixel_texture_check.py new file mode 100644 index 0000000000..68382ebd74 --- /dev/null +++ b/tests/native_indexed_pixel_texture_check.py @@ -0,0 +1,93 @@ +"""Verify bounded eight-DWORD PS texture lookups in the linked native path.""" +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_direct_container_check import patched_pixel, publish, vertex, words + + +def texture_program(original, mask, opposite, base_offset=32): + # Adapt the existing MRT draw. t0 holds one runtime byte offset and the UV + # offset. t1 and t2 have different colors and different spatial patterns. + source = list(struct.unpack(f"<{len(original) // 4}I", original)) + start = source.index(0xf4100000 | (16 << 6) | 10) + assert source[start + 1] == 0xfa000020 and source[start + 3] == 0xfa000038 + + # Move the table base to s[48:49] before reading s[16:23] and s[24:31]. + source[0:2] = [0xbe800300 | (48 << 16) | 8, 0xbe800380 | (49 << 16)] + source[start - 2] = (source[start - 2] & ~63) | 24 + offset_load = source[start + 2:start + 4] + + # Explicit words of the fixture's point sampler (2 bits set at bit 54). + sampler = [0xbeac0380, 0xbead03ff, 0x00c00000, 0xbeae0380, 0xbeaf0380] + # Interleave a different destination between the two writes defining v80. + # Only v47 and v81 need initial upper halves for their partial exports. + initial = [0x7e000280 | (dst << 17) for dst in (47, 81)] + lo = source.index(0xcc214000 | 80) + high, other_low = source[lo+2:lo+4], source[lo+4:lo+6] + assert high[0] == 0xcc224000 | 80 and other_low[0] == 0xcc214000 | 81 + source[lo+2:lo+6] = other_low + high + + def and_mask(dst, src): + return 0x87000000 | (dst << 16) | ((128 + mask) << 8) | src + + # s40 = s12 & mask; s41 = (s12 ^ toggle) & mask. Select each + # descriptor from the same base byte offset in the same bound root table. + toggle = 32 if opposite else 0 + lookups = [*offset_load, and_mask(40, 12), + 0xf40c0000 | (16 << 6) | 24, (40 << 25) | base_offset, + 0x89000000 | (41 << 16) | ((128 + toggle) << 8) | 12, + and_mask(41, 41), 0xf40c0000 | (24 << 6) | 24, (41 << 25) | base_offset] + return words(*initial, *source[:start], *lookups, *sampler, *source[start + 7:]) + + +def run(work, writer, compiler, sdk, adapter): + subprocess.run([writer, "--write-fixture", work], check=True) + vs, ps, root = [(work / name).read_bytes() for name in ("vertex.bin", "pixel.bin", "root.bin")] + cache, output = work / "cache", work / "objects" + for name, mask, offset, refusal in ( + ("distinct", 32, 32, ""), ("same", 32, 32, ""), + ("unaligned", 31, 32, "32-byte-aligned SRV offset"), + ("short-table", 32, 96, "exceeds its declared root range"), + ): + program = texture_program(ps, mask, name != "same", offset) + key = publish(work / name, program, vs, root, ps_inputs=(2, 2)) + result = subprocess.run([compiler, sdk, cache, "gfx1013-container-pair", + "--requests", work / name, output], capture_output=True, text=True) + if refusal: + assert result.returncode and refusal in result.stderr, result.stderr + print(name, refusal) + continue + assert result.returncode == 0, result.stderr + manifest = (output / f"{key}.txt").read_text().splitlines() + assert {"srv 1 tex2d table 0 32", "srv 2 tex2d table 0 64"} <= set(manifest), manifest + result = subprocess.run([writer, adapter, sdk, cache, output / f"{key}.ps.cso", output / f"{key}.vs.cso"], + text=True, capture_output=True) + print(name, result.returncode, result.stdout.strip(), result.stderr.strip()) + if result.returncode == 77: + return 77 + if name == "distinct": + assert result.returncode == 0, result.stderr + else: + assert result.returncode and "sampled MRT mismatch" in result.stderr, result.stderr + + # Type 5 denotes the global resource heap. A real table at root 0 exists, + # but a load via this unrelated ABI input must never resolve to that table. + heap = [0xbe810380, 0x8702a002, 0xf40c0200, 2 << 25, 0x7e000280, 0x7e020280, + 0xf0000108, 0x00020000] + pixel = patched_pixel(len(heap), heap, root_inputs=((5, 0, 1, 0, 0), (0, 0, 1, 0, 0x102))) + request = work / "global-heap" + key = publish(request, vertex(), pixel, root) + result = subprocess.run([compiler, sdk, cache, "gfx1013-container-pair", + "--requests", request, output], capture_output=True, text=True) + assert result.returncode and not (output / f"{key}.txt").exists(), result.stderr + assert "direct descriptor address outside bound table" in result.stderr, result.stderr + print("global-heap", result.stderr.strip()) + return 0 + + +if __name__ == "__main__": + with TemporaryDirectory() as folder: + sys.exit(run(Path(folder), *sys.argv[1:])) diff --git a/tests/native_int16_check.py b/tests/native_int16_check.py new file mode 100644 index 0000000000..1d0ca0cf7d --- /dev/null +++ b/tests/native_int16_check.py @@ -0,0 +1,141 @@ +"""Non-packed 16-bit integer VOP3 operations in the direct compute path (#669). + + native_int16_check.py controls <compile_dxil> <sdk bin dir> + native_int16_check.py hardware <native_store_replay> <sdk bin dir> + +v_add_nc_u16, v_sub_nc_u16, v_add_nc_i16, v_sub_nc_i16, v_mul_lo_u16, v_lshlrev_b16, v_lshrrev_b16, v_ashrrev_i16, +v_min_u16, v_max_u16, v_min_i16 and v_max_i16 write D[15:0] from S0[15:0] and S1[15:0] and keep D[31:16], as #669 +records for RDNA 2: an inline-assembly measurement on RDNA 2 silicon, and LLVM's GCNSubtarget::zeroesHigh16BitsOfDest +("On gfx10, all 16-bit instructions preserve the high bits"). The shifts take S1 shifted by S0[3:0]. The words were +assembled with LLVM 15 (llvm-mc -mcpu=gfx1013). + +Two groups of 32 lanes; G = L + 32g. S0 = G * 0x9e3779b9 and S1 = (G * 0x7f4a7c15) ^ 0x5bd1e995, so both high halves +are nonzero, the shift counts cover 0..15 and bit 4 of S0 varies. Each destination is set to 0xcafebabe first, and +the twelve results are stored per lane. References with a zeroed high half, a five-bit shift count, signed and +unsigned order exchanged, or a logical shift for v_ashrrev_i16 must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_align_bfm_check import words +from native_dpp_quad_check import request + +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 11 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 6, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v3, s8, v0 / +# v_mul_lo_u32 v1, v3, 0x9e3779b9 / v_mul_lo_u32 v2, v3, 0x7f4a7c15 / v_xor_b32 v2, 0x5bd1e995, v2 / +# for each op k in OPS: v_mov_b32 v[10+k], 0xcafebabe / <op> v[10+k], v1, v2 / +# s_waitcnt lgkmcnt(0) / buffer_store_dword v[10+k] at v8 + 4k / s_endpgm +HEX = ('040394be 800395be 0a0808f4200000fa 058b078f 0585088f 86001034 0710104a 0800064a 010069d503ff0100b979379e ' + '020069d503ff0100157c4a7f ff04043a95e9d15b ff02147ebebafeca 0a0003d701050200 ff02167ebebafeca 0b0004d701050200 ' + 'ff02187ebebafeca 0c000dd701050200 ff021a7ebebafeca 0d000ed701050200 ff021c7ebebafeca 0e0005d701050200 ' + 'ff021e7ebebafeca 0f0014d701050200 ff02207ebebafeca 100007d701050200 ff02227ebebafeca 110008d701050200 ' + 'ff02247ebebafeca 12000bd701050200 ff02267ebebafeca 130009d701050200 ff02287ebebafeca 14000cd701050200 ' + 'ff022a7ebebafeca 15000ad701050200 7fc08cbf 001070e0080a0880 041070e0080b0880 081070e0080c0880 ' + '0c1070e0080d0880 101070e0080e0880 141070e0080f0880 181070e008100880 1c1070e008110880 201070e008120880 ' + '241070e008130880 281070e008140880 2c1070e008150880 000081bf') +OPS = ("v_add_nc_u16", "v_sub_nc_u16", "v_add_nc_i16", "v_sub_nc_i16", "v_mul_lo_u16", "v_lshlrev_b16", + "v_lshrrev_b16", "v_ashrrev_i16", "v_min_u16", "v_max_u16", "v_min_i16", "v_max_i16") +PRESET = 0xCAFEBABE +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK = 0xFFFFFFFF + + +def sext16(x): + x &= 0xFFFF + return x - 0x10000 if x & 0x8000 else x + + +def op16(name, s0, s1, shift_bits=4, swap_order=False, logical_ashr=False): + a, b = s0 & 0xFFFF, s1 & 0xFFFF + count = s0 & ((1 << shift_bits) - 1) + signed = name.endswith("i16") != swap_order + if name in ("v_add_nc_u16", "v_add_nc_i16"): + r = a + b + elif name in ("v_sub_nc_u16", "v_sub_nc_i16"): + r = a - b + elif name == "v_mul_lo_u16": + r = a * b + elif name == "v_lshlrev_b16": + r = b << count + elif name == "v_lshrrev_b16" or (name == "v_ashrrev_i16" and logical_ashr): + r = b >> count + elif name == "v_ashrrev_i16": + r = sext16(b) >> count + else: + x, y = (sext16(a), sext16(b)) if signed else (a, b) + r = min(x, y) if "_min_" in name else max(x, y) + return r & 0xFFFF + + +def reference(zero_high=False, **wrong): + expected = [SENTINEL] * OUTPUT_WORDS + for g in range(64): + s0 = (g * 0x9E3779B9) & MASK + s1 = ((g * 0x7F4A7C15) & MASK) ^ 0x5BD1E995 + high = 0 if zero_high else PRESET & 0xFFFF0000 + base = GUARD_WORDS + g * 16 + expected[base:base + len(OPS)] = [high | op16(name, s0, s1, **wrong) for name in OPS] + return expected + + +def controls(cli, sdk, work, root): + marker = request(work, root, words(HEX)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + # Spot values of the definitions. + assert op16("v_sub_nc_u16", 0x10001, 0x20002) == 0xFFFF and op16("v_ashrrev_i16", 0x1F, 0x8000) == 0xFFFF + assert op16("v_lshrrev_b16", 0x1F, 0x8000) == 1 and op16("v_min_i16", 0x8000, 0x7FFF) == 0x8000 + assert op16("v_min_u16", 0x8000, 0x7FFF) == 0x7FFF and op16("v_lshlrev_b16", 0x11, 0xC001) == 0x8002 + # op_sel (VOP3 word 0 bits 11..14) selects other halves and stays refused. + program = words(HEX) + at = program.index(0xD703000A) + program[at] |= 1 << 14 + marker = request(work, root, program) + refused = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, marker.with_suffix('.cso')], + capture_output=True, text=True) + assert refused.returncode and "v_add_nc_u16 op_sel" in refused.stderr, (refused.stdout, refused.stderr) + expected = reference() + for label, mutant in (('high half zeroed', reference(zero_high=True)), + ('five-bit shift count', reference(shift_bits=5)), + ('signed and unsigned order exchanged', reference(swap_order=True)), + ('logical shift for v_ashrrev_i16', reference(logical_ashr=True))): + assert mutant != expected, label + print('compiled; op_sel refused; the zeroed-high, five-bit-shift, exchanged-order and logical-shift references ' + 'each differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not diff, diff[:10] + print('16-bit integer VOP3: 768 words of two groups and the guards matched, high halves kept') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_int16_ternary_check.py b/tests/native_int16_ternary_check.py new file mode 100644 index 0000000000..b11bfc0c37 --- /dev/null +++ b/tests/native_int16_ternary_check.py @@ -0,0 +1,190 @@ +"""Three-source 16-bit integer VOP3 operations in the direct compute path (#669). + + native_int16_ternary_check.py controls <compile_dxil> <sdk bin dir> + native_int16_ternary_check.py hardware <native_store_replay> <sdk bin dir> + +Lowers the eight three-source 16-bit integer VOP3 operations: +- v_mad_u16, v_mad_i16 +- v_min3_u16, v_min3_i16 +- v_max3_u16, v_max3_i16 +- v_med3_u16, v_med3_i16 + +Each operation computes D[15:0] from S0[15:0], S1[15:0] and S2[15:0], and D[31:16] preserves its previous value +(measured on RDNA 2 silicon; LLVM GCNSubtarget::zeroesHigh16BitsOfDest: "On gfx10, all 16-bit instructions preserve +the high bits"). Modifiers (clamp, scale, neg, abs) and op_sel are refused. + +The dispatch has two groups of 32 lanes (64 lanes total). S0, S1 and S2 have nonzero high halves, cross the +signed 16-bit sign boundary, wrap mad modulo 2^16, and cover permutations of signed and unsigned orders. +Prior to each operation, destination registers are initialized to 0xcafebabe, so preserving D[31:16] leaves +0xcafe in the upper half. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +HEX = ('040394be 800395be 0a0808f4 200000fa 058a078f 0585088f 85001034 0710104a 0800124a ff120216 d1f30500 ' + 'ff02023a 000080a5 ff120416 71030000 ff04043a debc9a7f ff120616 01100000 ff06063a ff7f0080 ff02147e ' + 'bebafeca ff02167e bebafeca ff02187e bebafeca ff021a7e bebafeca ff021c7e bebafeca ff021e7e bebafeca ' + 'ff02207e bebafeca ff02227e bebafeca 0a0040d7 01050e04 0b005ed7 01050e04 0c0053d7 01050e04 0d0052d7 ' + '01050e04 0e0056d7 01050e04 0f0055d7 01050e04 100059d7 01050e04 110058d7 01050e04 7fc08cbf 001070e0 ' + '080a0880 041070e0 080b0880 081070e0 080c0880 0c1070e0 080d0880 101070e0 080e0880 141070e0 080f0880 ' + '181070e0 08100880 1c1070e0 08110880 000081bf') + +PRESET = 0xCAFEBABE +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK32 = 0xFFFFFFFF + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & MASK32 + + +def operands(g): + s0 = mul24(g, 0x05F3D1) ^ 0xA5800000 + s1 = mul24(g, 0x000371) ^ 0x7F9ABCDE + s2 = mul24(g, 0x001001) ^ 0x80007FFF + return s0, s1, s2 + + +def sext16(x): + x &= 0xFFFF + return x - 0x10000 if x & 0x8000 else x + + +def results(s0, s1, s2, zero_high=False, signed_as_unsigned=False, med_as_min=False, + mad_no_add=False, mad_high_half=False): + high = 0 if zero_high else (PRESET & 0xFFFF0000) + a, b, c = s0 & 0xFFFF, s1 & 0xFFFF, s2 & 0xFFFF + sa, sb, sc = sext16(s0), sext16(s1), sext16(s2) + + # mad + if mad_no_add: + r_mad_u = (a * b) & 0xFFFF + r_mad_i = (sa * sb) & 0xFFFF + elif mad_high_half: + r_mad_u = ((s0 >> 16) * b + c) & 0xFFFF + r_mad_i = ((s0 >> 16) * b + c) & 0xFFFF + else: + r_mad_u = (a * b + c) & 0xFFFF + r_mad_i = (sa * sb + sc) & 0xFFFF + + # min3, max3, med3 + u_ordered = sorted([a, b, c]) + s_ordered = sorted([a, b, c]) if signed_as_unsigned else sorted([a, b, c], key=sext16) + + r_min_u = u_ordered[0] + r_min_i = s_ordered[0] + r_max_u = u_ordered[2] + r_max_i = s_ordered[2] + r_med_u = u_ordered[0 if med_as_min else 1] + r_med_i = s_ordered[0 if med_as_min else 1] + + return [high | r_mad_u, + high | r_mad_i, + high | r_min_u, + high | r_min_i, + high | r_max_u, + high | r_max_i, + high | r_med_u, + high | r_med_i] + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(32): + g = group * 32 + lane + base = GUARD_WORDS + g * 8 + expected[base:base + 8] = results(*operands(g), **mutation) + return expected + + +def controls(cli, sdk, work, root): + prog = words(HEX) + marker = request(work, root, prog) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + + # op_sel on v_mad_u16 (bit 14 of word 0) must be refused + op_sel_prog = list(prog) + at = op_sel_prog.index(0xD740000A) + op_sel_prog[at] |= (1 << 14) + marker_op_sel = request(work, root, op_sel_prog) + refused = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker_op_sel, + marker_op_sel.with_suffix('.cso')], capture_output=True, text=True) + assert refused.returncode and "v_mad_u16 op_sel" in refused.stderr, (refused.stdout, refused.stderr) + + # clamp on v_mad_u16 (bit 15 of word 0) must be refused + clamped_prog = list(prog) + clamped_prog[at] |= (1 << 15) + marker_clamp = request(work, root, clamped_prog) + refused_clamp = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker_clamp, + marker_clamp.with_suffix('.cso')], capture_output=True, text=True) + assert refused_clamp.returncode and "direct ALU operand modifiers" in refused_clamp.stderr, (refused_clamp.stdout, refused_clamp.stderr) + + # Spot checks of definitions + assert results(0x10002, 0x20003, 0x30004)[:2] == [PRESET & 0xFFFF0000 | 10, PRESET & 0xFFFF0000 | 10] + # 0x8001 is -32767 signed, 32769 unsigned; 0x0001 is 1; 0x7FFF is 32767 + s0, s1, s2 = 0x8001, 0x0001, 0x7FFF + res = results(s0, s1, s2) + assert res[2] & 0xFFFF == 0x0001 # unsigned min3 is 1 + assert res[3] & 0xFFFF == 0x8001 # signed min3 is -32767 + assert res[4] & 0xFFFF == 0x8001 # unsigned max3 is 32769 + assert res[5] & 0xFFFF == 0x7FFF # signed max3 is 32767 + assert res[6] & 0xFFFF == 0x7FFF # unsigned med3 is 32767 + assert res[7] & 0xFFFF == 0x0001 # signed med3 is 1 + + expected = reference() + for label, mutant in (('high half zeroed', reference(zero_high=True)), + ('signed as unsigned', reference(signed_as_unsigned=True)), + ('median as minimum', reference(med_as_min=True)), + ('mad without addend', reference(mad_no_add=True)), + ('mad source from high half', reference(mad_high_half=True))): + assert mutant != expected, f"Mutant failed to differ: {label}" + + print('compiled; op_sel and clamp refused; definitions spot-checked; all mutants differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, f"First diffs: {diff[:10]}" + print('eight 16-bit ternary operations: 512 words of two groups and the guards matched, high halves kept') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_int32_minmax3_check.py b/tests/native_int32_minmax3_check.py new file mode 100644 index 0000000000..fa90b2d929 --- /dev/null +++ b/tests/native_int32_minmax3_check.py @@ -0,0 +1,127 @@ +"""Direct DXIL regression for signed/unsigned three-source 32-bit integer min/max/median. + +The generic lowering predates this fixture (4036577). Earlier Python paths +are covered by #1992, #1574, #1577 and #308. Exercise all six VOP3 encodings +through the native compiler, not the Python translator. + +Two full 32-thread groups write six words per lane. Sparse guest EXEC +suppresses the ALU writes, not the final stores: inactive lanes must keep +the old destination (including an S0/destination alias for signed median). +Full physical waves avoid the WARP 1.0.22 partial-wave ballot issue (#3160). +""" +from itertools import permutations +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + +OPS = (("v_min3_u32", 0x153, 0, False), ("v_max3_u32", 0x156, 2, False), + ("v_med3_u32", 0x159, 1, False), ("v_min3_i32", 0x152, 0, True), + ("v_max3_i32", 0x155, 2, True), ("v_med3_i32", 0x158, 1, True)) +ALL = 0xffffffff +SPARSE = 0xa55aa55a +SEED = 0x13579bdf +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +CASES = [(t, ALL) for t in permutations((0x80000000, 0x7fffffff, 0xffffffff))] +CASES += [((0, 0, 0xffffffff), ALL), ((1, 0, 1), ALL), + ((0x80000000, 0x80000000, 0x80000000), ALL), + ((0xffffffff, 0x7fffffff, 0x80000000), SPARSE), + ((0, 1, 0xffffffff), SPARSE)] + + +def program(triple, active=ALL, ops=OPS, clamp=False): + # Root table s4, group.x in s5, 1024 bytes/group, 32 bytes/lane. + p = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 138), vop2(0x1a, 8, 133, 0), vop2(0x25, 8, 7, 8)] + for dst, value in enumerate(triple, 1): + p += [vmove(dst, 255), value] + for dst in range(10, 15): + p += [vmove(dst, 255), SEED] + p += [sop1(3, 126, 255), active] + destinations = [] + for j, (_, opcode, _, _) in enumerate(ops): + # Last op aliases S0; all other destinations are disjoint. + dst = 1 if j == len(ops) - 1 else 10 + j + destinations.append(dst) + p += [0xd4000000 | opcode << 16 | dst | (0x8000 if clamp else 0), + 257 | 258 << 9 | 259 << 18] + p += [sop1(3, 126, 193), 0xbf8cc07f] + for j, dst in enumerate(destinations): + p += [0xe0701000 | 4*j, 0x80080008 | dst << 8] + return p + [0xbf810000] + + +def reference(triple, active, wrong_sign=False, drop_third=False, ignore_exec=False, wrong_rank=False): + expected = [SENTINEL] * OUTPUT_WORDS + operands = triple[:2] + triple[1:2] if drop_third else triple + results = [] + for _, _, rank, signed in OPS: + order = sorted(operands, key=lambda v: v - (1 << 32) if (signed != wrong_sign) and v & 0x80000000 else v) + results.append(order[(rank + 1) % 3 if wrong_rank else rank]) + for n in range(64): + base = GUARD_WORDS + n * 8 + enabled = ignore_exec or (active >> (n % 32)) & 1 + expected[base:base+6] = results if enabled else [SEED]*5 + [triple[0]] + return expected + + +def compile_case(cli, sdk, work, root, p): + marker = request(work, root, p) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + return result, output + + +def controls(cli, sdk, work, root): + for op in OPS: + r, out = compile_case(cli, sdk, work, root, program(CASES[0][0], ops=(op,))) + assert r.returncode == 0 and out.is_file(), (op, r.stdout, r.stderr) + r, out = compile_case(cli, sdk, work, root, program(CASES[0][0], ops=(op,), clamp=True)) + assert r.returncode and "direct ALU operand modifiers" in r.stderr and not out.exists(), (op, r.stdout, r.stderr) + for mutation in ("wrong_sign", "drop_third", "ignore_exec", "wrong_rank"): + assert any(reference(t, a) != reference(t, a, **{mutation: True}) for t, a in CASES), mutation + # Ensure every opcode independently detects swapped signedness. + for j in range(len(OPS)): + assert any(reference(t, a)[GUARD_WORDS+j] != reference(t, a, wrong_sign=True)[GUARD_WORDS+j] + for t, a in CASES if a == ALL), OPS[j][0] + print("six canonical forms compile; six clamp controls refused; four incorrect references differ") + return 0 + + +def hardware(replay, sdk, work, root): + for triple, active in CASES: + marker = request(work, root, program(triple, active)) + output = work / "out.bin" + r = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if r.returncode == 77: + return 77 + r.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = reference(triple, active) + bad = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not bad, (triple, hex(active), bad[:10]) + print("triple", *(f"{v:08x}" for v in triple), "EXEC", f"{active:08x}", f"{len(actual)} words match", flush=True) + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src = work / "root.hlsl" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + rootfile = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", rootfile, src], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, rootfile.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_lane_access_check.py b/tests/native_lane_access_check.py new file mode 100644 index 0000000000..eaf974be0d --- /dev/null +++ b/tests/native_lane_access_check.py @@ -0,0 +1,147 @@ +"""Compare source-built direct DXIL lane accesses with a CPU wave model.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def vop2(op, dst, src0, src1): + return op << 25 | dst << 17 | src1 << 9 | src0 + + +def readlane(dst, vgpr, selector): + return [0xd7600000 | dst, (256 + vgpr) | selector << 9] + + +def writelane(dst, source, selector): + return [0xd7610000 | dst, source | selector << 9] + + +def readfirstlane(dst, vgpr): + return 0x7e000400 | dst << 17 | (256 + vgpr) + + +def launch(threads): + return struct.pack("<7I", 0, 0, 0, threads | 1 << 16, 1 | (1 << 20), 0, 0x8a) + + +def program(): + # v8 = byte address of a 16-word record per lane in each workgroup. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 139), vop2(0x1a, 8, 134, 0), vop2(0x25, 8, 7, 8), + vmove(1, 256)] + for slot, (lane, value) in enumerate(((0, 11), (5, 22), (31, 33))): + words += [sop1(3, 10 + slot, 128 + value), *writelane(1, 10 + slot, 128 + lane)] + for slot, lane in enumerate((0, 5, 63)): + words += readlane(14 + slot, 1, 128 + lane) + + # The group ID changes the SGPR selector. Bit 5 must be ignored on wave32. + words += [scalar(1, 13, 169, 5), *writelane(1, 170, 13), *readlane(17, 1, 13)] + # A manual mutant that lets v_writelane honour EXEC must lose the value 59. + # A manual mutant that reads lane ^ 1 must return the neighbouring lane's value. + words += [sop1(3, 126, 129), vmove(1, 175), *writelane(1, 187, 151), + *readlane(18, 1, 151), sop1(3, 126, 193)] + words += [sop1(3, 19, 255), 0xa5a5a5a5, *writelane(1, 19, 142), *readlane(106, 1, 142), + vmove(16, 137), vop2(1, 9, 133, 16), + readfirstlane(106, 1), vmove(10, 106)] + # A manual mutant that treats vcc_hi as constant 0 in wave32 must fail, and so must one that + # reads the high word of a wave32 VCC pair as 0: the pair is s106:s107 on hardware. + words += [*readlane(107, 1, 133), vmove(12, 107), + readfirstlane(107, 1), vmove(13, 107), + sop1(3, 107, 255), 0x89abcdef, vmove(14, 107), + sop1(4, 24, 106), vmove(15, 25)] + for slot, (kind, reg) in enumerate((("s", 14), ("s", 15), ("s", 16), ("s", 17), + ("s", 18), ("v", 9), ("v", 1), ("v", 10), + ("v", 12), ("v", 13), ("v", 14), ("v", 15))): + if kind == "s": + words.append(vmove(11, reg)) + reg = 11 + words += [0xe0701000 | 4 * slot, 0x80080008 | reg << 8] + return words + [0xbf810000] + + +def reference(): + expected = [0x69696969] * 2064 + for group in range(2): + lanes = list(range(32)) + for lane, value in ((0, 11), (5, 22), (31, 33)): + lanes[lane] = value + refill = [lanes[lane] for lane in (0, 5, 31)] + selected = (41 - group) % len(lanes) + lanes[selected] = 42 + dynamic = lanes[selected] + exec_mask = 1 + for lane in range(len(lanes)): + if exec_mask & (1 << lane): + lanes[lane] = 47 + lanes[23] = 59 # Lane write ignores EXEC. + narrowed = lanes[23] + lanes[14] = 0xa5a5a5a5 + vcc = lanes[14] + exec_mask = 0xffffffff + first = next(lane for lane in range(len(lanes)) if exec_mask & (1 << lane)) + for lane, value in enumerate(lanes): + base = 8 + 16 * (32 * group + lane) + expected[base:base + 12] = [*refill, dynamic, narrowed, 9 if (vcc >> lane) & 1 else 5, + value, lanes[first], lanes[5], lanes[first], 0x89abcdef, 0x89abcdef] + return expected + + +def check_refusals(cli, sdk, work, root): + direct = "gfx1013-direct-cs@0" + hlsl = "gfx1013-compute-wave32@0" + partial = "lane read/write needs full waves" + invalid = "invalid scalar lane read destination" + cases = [ + (direct, 30, readlane(14, 1, 13), partial), + (direct, 30, writelane(1, 129, 159), partial), + (direct, 62, readlane(14, 1, 13), partial), + (direct, 32, readlane(14, 1, 257), "lane read/write needs a constant or SGPR lane"), + (direct, 32, [0xd7610811, 129 | 128 << 9], "lane read/write encoding or operand modifiers"), + (direct, 32, readlane(108, 1, 128), invalid), + (direct, 32, [readfirstlane(108, 1)], invalid), + (hlsl, 32, readlane(106, 1, 128), invalid), + (hlsl, 32, [readfirstlane(106, 1)], invalid), + (hlsl, 32, readlane(107, 1, 128), invalid), + (hlsl, 32, [readfirstlane(107, 1)], invalid), + ] + for profile, threads, operation, diagnostic in cases: + words = [vmove(1, 128), sop1(3, 13, 129), *operation, 0xbf810000] + marker = write_request(work, words, root, launch(threads)) + dest = work / "refused.cso" + result = subprocess.run([cli, sdk, work / "cache", profile, marker, dest], + capture_output=True, text=True) + assert result.returncode != 0 and diagnostic in result.stdout + result.stderr, ( + profile, threads, operation, result.stdout, result.stderr) + assert not dest.exists() + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source, root_file = work / "root.hlsl", work / "root.bin" + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, source], check=True) + root = root_file.read_bytes() + check_refusals(cli, sdk, work, root) + marker = write_request(work, program(), root, launch(32)) + dest = work / "result.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + expected = reference() + mismatches = [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not mismatches, mismatches[:12] + print("Two workgroups matched 768 lane-access words and all guards.") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_lane_spill_descriptor_check.py b/tests/native_lane_spill_descriptor_check.py new file mode 100644 index 0000000000..b90cbc5ab1 --- /dev/null +++ b/tests/native_lane_spill_descriptor_check.py @@ -0,0 +1,105 @@ +"""Exercise symbolic descriptor spills and numeric spills in the same VGPR.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_lane_access_check import readlane, vop2, writelane +from native_scalar_lds_check import scalar, sop1, vmove + + +LAUNCH = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1, 0, 0x8c) +SPILL = 1 +ROOT = "DescriptorTable(SRV(t0,numDescriptors=8)),DescriptorTable(UAV(u0,numDescriptors=8))" + + +def load_descriptor(dst, table_pair, byte_offset): + return [0xf4080000 | dst << 6 | table_pair // 2, 0xfa000000 | byte_offset] + + +def spill_descriptor(first): + return [word for lane in range(4) for word in writelane(SPILL, first + lane, 128 + lane)] + + +def program(control=""): + # s20:21 and s22:23 are the table pointers. s6 is the workgroup ID. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), + *load_descriptor(32, 20, 32), *load_descriptor(36, 22, 32), 0xbf8cc07f, + vmove(SPILL, 128), scalar(0x1e, 7, 6, 137), + vop2(0x1a, 8, 132, 0), vop2(0x25, 8, 7, 8), vop2(0x1a, 2, 130, 0)] + if control == "join": + left, right = spill_descriptor(32), spill_descriptor(44) + words += [*load_descriptor(44, 20, 64), 0xbf8cc07f, + 0xbf840000 | (len(left) + 1), *left, 0xbf820000 | len(right), *right] + else: + words += spill_descriptor(32) + words += [*writelane(SPILL, 139, 132), *writelane(SPILL, 150, 133)] + words += [sop1(3, reg, 128) for reg in range(32, 36)] + if control == "overwrite": + words += [vmove(SPILL, 128)] + if control == "valu": + words += [vmove(3, 256 + SPILL)] + if control == "sgpr_selector": + words += [sop1(3, 10, 128), *readlane(32, SPILL, 10)] + for lane in range(4): + selector = 256 + 2 if control == "vgpr_selector" and lane == 0 else 128 + lane + words += readlane(32 + lane, SPILL, selector) + words += [*readlane(10, SPILL, 132), *readlane(11, SPILL, 133), + 0xe0301000, 0x80080902, 0xbf8c0f70, vmove(10, 10), vmove(11, 11)] + for slot, vgpr in enumerate((9, 10, 11)): + words += [0xe0701000 | 4 * slot, 0x80090008 | vgpr << 8] + return words + [0xbf810000] + + +def reference(): + source = [0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5] + expected = [0x69696969] * 2064 + for group in range(2): + for lane in range(32): + base = 8 + 4 * (32 * group + lane) + expected[base:base + 3] = [source[lane % len(source)], 11, 22] + return expected + + +def main(cli, replay, sdk, adapter): + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + source, root_file = work / "root.hlsl", work / "root.bin" + source.write_text(f'#define SIG "{ROOT}"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, source], check=True) + root = root_file.read_bytes() + cache = work / "cache" + controls = { + "vgpr_selector": "lane read/write needs a constant or SGPR lane", + "sgpr_selector": "needs a constant lane", + "overwrite": "write to a VGPR holding symbolic lanes", + "join": "symbolic VGPR lane read has conflicting incoming values", + "valu": "symbolic VGPR lane read of v1", + } + for control, diagnostic in controls.items(): + marker = write_request(work, program(control), root, LAUNCH) + dest = work / f"{control}.cso" + run = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, dest], + capture_output=True, text=True) + assert run.returncode and diagnostic in run.stdout + run.stderr, (control, run.stdout, run.stderr) + assert not dest.exists(), control + + marker = write_request(work, program(), root, LAUNCH) + dest = work / "readback.bin" + mode = "--direct-warp" if adapter == "warp" else "--direct" + run = subprocess.run([replay, sdk, marker, cache, "0", dest, mode]) + if run.returncode == 77: + return 77 + run.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + mismatches = [(i, a, e) for i, (a, e) in enumerate(zip(actual, reference())) if a != e] + assert not mismatches, mismatches[:12] + print("Two workgroups matched 192 descriptor-spill and numeric-spill words and all guards.") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_ldexp_check.py b/tests/native_ldexp_check.py new file mode 100644 index 0000000000..42b9bd31d5 --- /dev/null +++ b/tests/native_ldexp_check.py @@ -0,0 +1,176 @@ +"""v_ldexp_f32 in the direct compute path (#3013). + + native_ldexp_check.py controls <compile_dxil> <sdk bin dir> + native_ldexp_check.py hardware <native_store_replay> <sdk bin dir> + +The semantics are tools/pixel_aot.py's ldexp32: exact binary32 scaling of S0 by 2^S1, with zero, Inf and NaN passed +unchanged, a denormal S0 normalized rather than flushed, a denormal result rounded to nearest even, S1 a signed +integer clamped to [-512, 512]. clamp saturates with integer tests: NaN and negative values (also -0) give +0, +values from 1.0 give 1.0 and a denormal stays, so nothing depends on a float denormal mode. The VOP3 words were assembled with LLVM 15.0.7 (clang -cc1as, +gfx1013). The prologue has the instructions of native_dpp_quad_check.py with the shift amounts 7 and 12, so +v8 = 128 * lane and s7 = 4096 * group (32 words per lane), and the store words follow native_lane_access_check.py. + +Each case sets S0 and S1 by v_mov literals and stores v_ldexp_f32 of S0, of -|S0| and with clamp; every lane of two +groups stores all cases. References that flush denormals, truncate or round half away from zero, or add the exponent +without clamping S1 (so it wraps) must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +CASES = [ + (0x3F800000, 3), # 1.0 * 2^3 + (0x00000001, 23), # a denormal input, normalized: 2^-126 + (0x3FC00000, -149), # 1.5 * 2^-149: half way between 1 and 2 ulp, rounds to even 2 (also clamped) + (0x3F800000, -150), # 2^-150: half way between 0 and 1 ulp, rounds to even 0 + (0x7FC00001, 5), # NaN with a payload passes unchanged + (0x80000000, 0x7FFFFFFF), # -0 passes unchanged; clamp gives +0 + (0x3F400000, 1), # 0.75 * 2 = 1.5, saturated to 1.0 + (0xC0400000, 0x7FFFFFFF), # -3 * 2^huge: -Inf +] +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] +# v_ldexp_f32 v4, v1, v2 / v_ldexp_f32 v5, -|v1|, v2 / v_ldexp_f32 v6, v1, v2 clamp +OPS = [(0xD7620004, 0x00020501, 4), (0xD7620105, 0x20020501, 5), (0xD7628006, 0x00020501, 6)] +# Refused: neg on S1 (word 1 bit 30), omod mul:2 (word 1 bits 28:27), abs on S1 (word 0 bit 9), op_sel bit 11 and +# a nonzero src2 field (word 1 bits 26:18, here v1). +REFUSED = [('neg on S1', (0xD7620004, 0x40020501)), ('omod', (0xD7620004, 0x08020501)), + ('abs on S1', (0xD7620204, 0x00020501)), ('op_sel', (0xD7620804, 0x00020501)), + ('src2 field', (0xD7620004, 0x04060501))] +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def program(ops=OPS): + code = list(PROLOGUE) + for index, (a, b) in enumerate(CASES): + code += [0x7E0202FF, a, 0x7E0402FF, b & 0xFFFFFFFF] + for w0, w1, _ in ops: + code += [w0, w1] + for slot, (_, _, vgpr) in enumerate(ops): + code += [0xE0701000 | (16 * index + 4 * slot), 0x80080008 | vgpr << 8] + return code + [0xBF810000] + + +def signed(x): + x &= 0xFFFFFFFF + return x - (1 << 32) if x & 0x80000000 else x + + +def ldexp32(bits, delta, flush=False, rounding='even', clamp_delta=True): + sign, exp, mant = bits & 0x80000000, (bits >> 23) & 0xFF, bits & 0x7FFFFF + if exp == 0xFF or (exp == 0 and mant == 0): + return bits + if exp == 0: + if flush: + return sign + shift = 23 - (mant.bit_length() - 1) + mant, e = (mant << shift) & 0x7FFFFF, 1 - shift + else: + e = exp + delta = signed(delta) + if clamp_delta: + e += max(-512, min(512, delta)) + else: + e = signed(e + delta) + if e >= 255: + return sign | 0x7F800000 + if e <= 0: + if flush or e < -23: + return sign + full, shift = mant | 0x800000, 1 - e + half, rest, q = 1 << (shift - 1), full & ((1 << shift) - 1), full >> shift + if rounding == 'even': + q += rest > half or (rest == half and q & 1) + elif rounding == 'away': + q += rest >= half + return sign | q + return sign | (e << 23) | mant + + +def saturate(bits, float_clamp=False): + """NaN and negative values (also -0) give +0, values from 1.0 give 1.0, others (also denormals) stay.""" + if float_clamp: # a float clamp that flushes denormals and keeps -0 + if (bits & 0x7F800000) == 0x7F800000 and bits & 0x7FFFFF: + return 0 + if (bits & 0x7F800000) == 0: + return bits & 0x80000000 + value = struct.unpack('<f', struct.pack('<I', bits))[0] + return struct.unpack('<I', struct.pack('<f', min(max(value, 0.0), 1.0)))[0] + if (bits & 0x7FFFFFFF) > 0x7F800000 or bits & 0x80000000: + return 0 + return min(bits, 0x3F800000) + + +def results(a, b, float_clamp=False, **mutation): + return [ldexp32(a, b, **mutation), ldexp32(a | 0x80000000, b, **mutation), + saturate(ldexp32(a, b, **mutation), float_clamp)] + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(64): + base = GUARD_WORDS + lane * 32 + for index, (a, b) in enumerate(CASES): + expected[base + 4 * index:base + 4 * index + 3] = results(a, b, **mutation) + return expected + + +def compile_program(cli, sdk, work, root, code, suffix): + marker = request(work, root, code) + output = marker.with_suffix(suffix) + return subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True), output + + +def controls(cli, sdk, work, root): + result, output = compile_program(cli, sdk, work, root, program(), '.cso') + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + # Integer bit operations only: no float multiply and no DXIL unary float operation (such as Saturate). + assert 'fmul' not in dump and '@dx.op.unary.f32(' not in dump and 'shl i32' in dump, dump + for n, (label, words) in enumerate(REFUSED): + result, _ = compile_program(cli, sdk, work, root, program([words + (4,)]), f'.refused{n}.cso') + assert result.returncode != 0 and 'v_ldexp_f32 operand modifiers' in result.stdout + result.stderr, ( + label, result.stdout, result.stderr) + expected = reference() + for label, mutation in (('flushed denormals', {'flush': True}), ('truncated', {'rounding': 'down'}), + ('half away from zero', {'rounding': 'away'}), ('S1 not clamped', {'clamp_delta': False}), + ('float clamp', {'float_clamp': True})): + assert reference(**mutation) != expected, label + print('compiled three v_ldexp_f32 forms with integer operations only; five modifier forms are refused; the ' + 'flushing, truncating, half-away, unclamped-exponent and float-clamp references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print('v_ldexp_f32: all 2064 words matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_ldexp_f16_check.py b/tests/native_ldexp_f16_check.py new file mode 100644 index 0000000000..ea5416ef0f --- /dev/null +++ b/tests/native_ldexp_f16_check.py @@ -0,0 +1,216 @@ +"""Direct compute v_ldexp_f16 (VOP2 and VOP3A, exact integer binary16 scaling, high-half preserving).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +HIGH_SEED = 0xBEEF0000 + +# Two 8-case batches covering normals, denormals, subnormal ties, ±0, ±Inf, qNaN, and large/min deltas. +BATCHES = ( + ( + (0xCAFE3C00, 0x00000002), # 1.0h * 2^2 = 4.0h + (0x1234C200, 0xABCDFFFE), # -3.0h * 2^-2 = -0.75h (delta = -2) + (0x00000001, 0x0000000A), # smallest subnormal 2^-24 * 2^10 = smallest normal 2^-14 + (0x00000400, 0x0000FFFF), # smallest normal 2^-14 * 2^-1 = largest subnormal 2^-15 + (0x00000403, 0x0000FFFE), # subnormal round-up (rest > half) + (0x00000402, 0x0000FFFE), # subnormal tie-to-even (even q stays) + (0x00000406, 0x0000FFFE), # subnormal tie-to-even (odd q rounds up) + (0x00007BFF, 0x00000001), # max finite overflow -> +Inf (clamped to 1.0h) + ), + ( + (0x00000000, 0x00000005), # +0.0h pass-through + (0x00008000, 0x0000FFFB), # -0.0h pass-through + (0x00007C00, 0x0000FFF0), # +Inf pass-through (clamped to 1.0h) + (0x0000FC00, 0x00000010), # -Inf pass-through (clamped to 0.0h) + (0x00007E01, 0x00000003), # qNaN pass-through (clamped to 0.0h) + (0x00003C00, 0x00000064), # 1.0h * 2^100 -> +Inf (clamped delta +100 -> +64) + (0x00003C00, 0x0000FF9C), # 1.0h * 2^-100 -> +0.0h (clamped delta -100 -> -64) + (0x00003C00, 0x00008000), # 1.0h * 2^-32768 -> +0.0h (INT16_MIN delta) + ), +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop2(op, vdst, src0, vsrc1): + return ((op & 0x3F) << 25) | ((vdst & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_binary(op, vdst, src0, src1, *, abs_m=0, neg_m=0, clamp=0, omod=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | ((abs_m & 7) << 8) | (vdst & 0xFF) + w1 = ((neg_m & 7) << 29) | ((omod & 3) << 27) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def program(batch_idx): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, (s0, s1) in enumerate(BATCHES[batch_idx]): + code += v_mov_lit(2, s0) + v_mov_lit(3, s1) + # 0: VOP2 v_ldexp_f16 v4, v2, v3 + code += v_mov_lit(4, HIGH_SEED | 0x1111) + [vop2(0x3B, 4, 258, 3), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + # 1: batch 0 -> VOP3A v_ldexp_f16 v4, v2, v3; batch 1 -> VOP2 inline float constant 1.0 (src0=242 -> 0x3C00) + if batch_idx == 0: + code += v_mov_lit(4, HIGH_SEED | 0x2222) + vop3_binary(0x13B, 4, 258, 259) + [ + 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + else: + code += v_mov_lit(4, HIGH_SEED | 0x2222) + [vop2(0x3B, 4, 242, 3), + 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + # 2: VOP3A v_ldexp_f16 v4, -v2, v3 + code += v_mov_lit(4, HIGH_SEED | 0x3333) + vop3_binary(0x13B, 4, 258, 259, neg_m=1) + [ + 0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + # 3: VOP3A v_ldexp_f16 v4, |v2|, v3 clamp + code += v_mov_lit(4, HIGH_SEED | 0x4444) + vop3_binary(0x13B, 4, 258, 259, abs_m=1, clamp=1) + [ + 0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def sext16(v): + v &= 0xFFFF + return v - 0x10000 if (v & 0x8000) else v + + +def ldexp_f16(bits, delta_raw, *, flush_denormals=False, truncate_subnormal=False, drop_keep=False, clamp=False): + bits &= 0xFFFF + delta = max(-64, min(64, sext16(delta_raw))) + sign = bits & 0x8000 + exp = (bits >> 10) & 0x1F + mant = bits & 0x3FF + if not drop_keep and (exp == 0x1F or (bits & 0x7FFF) == 0): + res = bits + else: + if exp == 0: + if flush_denormals: + res = sign + exp = None + else: + steps = 0 + x = mant + while x and (x & 0x400) == 0: + x <<= 1 + steps += 1 + mant = x & 0x3FF + e = 1 - steps + delta + else: + e = exp + delta + if exp is not None: + if e > 30: + res = sign | 0x7C00 + elif e > 0: + res = sign | (e << 10) | mant + elif e < -10: + res = sign + else: + full = 0x400 | mant + amt = 1 - e + half = 1 << (amt - 1) + rest = full & ((1 << amt) - 1) + q = full >> amt + up = 0 if truncate_subnormal else int(rest > half or (rest == half and (q & 1) != 0)) + res = sign | (q + up) + if clamp: + abs_r = res & 0x7FFF + if abs_r > 0x7C00 or (res & 0x8000): + res = 0 + elif res > 0x3BFF: + res = 0x3C00 + return res & 0xFFFF + + +def reference(batch_idx, *, flush_denormals=False, truncate_subnormal=False, drop_keep=False, + inline_as_zero=False, no_clamp=False, zero_high=False): + hi = 0 if zero_high else HIGH_SEED + words = [SENTINEL] * 8 + for _lane in range(64): + for s0, s1 in BATCHES[batch_idx]: + r0 = ldexp_f16(s0, s1, flush_denormals=flush_denormals, truncate_subnormal=truncate_subnormal, + drop_keep=drop_keep) + if batch_idx == 0: + r1 = r0 + else: + r1 = ldexp_f16(0x0000 if inline_as_zero else 0x3C00, s1, + flush_denormals=flush_denormals, truncate_subnormal=truncate_subnormal, + drop_keep=drop_keep) + r_neg = ldexp_f16((s0 & 0xFFFF) ^ 0x8000, s1, flush_denormals=flush_denormals, + truncate_subnormal=truncate_subnormal, drop_keep=drop_keep) + r_abs_clamp = ldexp_f16(s0 & 0x7FFF, s1, flush_denormals=flush_denormals, + truncate_subnormal=truncate_subnormal, drop_keep=drop_keep, clamp=not no_clamp) + words.extend((hi | r0, hi | r1, hi | r_neg, hi | r_abs_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for bi in range(len(BATCHES)): + sub = work / f'b{bi}' + sub.mkdir(exist_ok=True) + marker = request(sub, root, program(bi)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (bi, result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump, dump + if bi == 1: + assert '15360' in dump, 'inline float 1.0 must lower to 0x3c00 (15360)' + for tag, bad, msg in ( + ('omod', vop3_binary(0x13B, 4, 258, 259, omod=1) + [0xBF810000], 'unsupported v_ldexp_f16 operand modifiers'), + ('neg_src1', vop3_binary(0x13B, 4, 258, 259, neg_m=2) + [0xBF810000], 'unsupported v_ldexp_f16 operand modifiers'), + ('bad_mode', [0xBFA4000C, vop2(0x3B, 4, 258, 3), 0xBF810000], 'unsupported binary16 rounding or denormal mode'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), ( + tag, bad_res.stdout, bad_res.stderr) + assert reference(0) != reference(0, flush_denormals=True) + assert reference(0) != reference(0, truncate_subnormal=True) + assert reference(0) != reference(0, no_clamp=True) + assert reference(0) != reference(0, zero_high=True) + assert reference(1) != reference(1, drop_keep=True) + assert reference(1) != reference(1, inline_as_zero=True) + print('v_ldexp_f16 DXIL verified; invalid modifiers/mode refused; all negative controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for bi in range(len(BATCHES)): + sub = work / f'hw{bi}' + sub.mkdir(exist_ok=True) + marker = request(sub, root, program(bi)) + output = work / f'out_{bi}.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(bi) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'batch={bi} word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print(f'batch={bi}: 2048 result words (high halves kept) and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_ldexp_f16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_lds_control_flow_check.py b/tests/native_lds_control_flow_check.py new file mode 100644 index 0000000000..da00c508cb --- /dev/null +++ b/tests/native_lds_control_flow_check.py @@ -0,0 +1,51 @@ +"""Exercise the shared-memory frontend's reconvergence and rejection paths.""" +from pathlib import Path +import struct +import sys +from types import SimpleNamespace + +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/"tools/startup")) +from compile_lds_request import ComputeStage +from gfx2hlsl import Unsupported + + +barrier = "GroupMemoryBarrierWithGroupSync();" +blocks = [(0,[],("branch","(exec & 1) == 0",16)), (8,["v1 = 2;"],None), + (16,[barrier],("end",))] +source = "\n".join(ComputeStage.body(SimpleNamespace(blocks=blocks))) +assert "!WaveActiveAnyTrue((exec&1u)!=0u)" in source +assert "}\n"+barrier+"\nif(pc==" in source + +for invalid, expected in [ + ([(0,[],("branch","scc",16)),(8,[barrier],None),(16,[],("end",))],"conditional"), + ([(0,[barrier],("jump",0))],"forward"), +]: + try: + ComputeStage.body(SimpleNamespace(blocks=invalid)) + except Unsupported as error: + assert expected in str(error), error + else: + raise AssertionError("accepted invalid compute control flow") +print("uniform barrier and wave-level EXEC branch passed; divergent barrier and back edge rejected") + +# A returning atomic replaces the entire destination, including a previous +# partial d16 result. Its address must still be readable when the registers alias. +def atomic_with_partial_register(address): + stage = ComputeStage.__new__(ComputeStage) + stage.pipe = SimpleNamespace(lds_words=128) + stage.exec_known = True + stage.used_v, stage.low16_only_v, stage.lines = set(), set(), [] + stage.pc = 0 + stage.code = struct.pack('<II', 0xd8800000, (7 << 24) | (6 << 8) | address) + stage.set_v(7, '0u', low16_only=True) + stage.lower('ds_add_rtn_u32', '', ['v7', f'v{address}', 'v6'], []) + return stage.u('v7') + + +assert atomic_with_partial_register(1) == 'v7' +try: + atomic_with_partial_register(7) +except Unsupported as error: + assert 'whole-word read of v7' in str(error), error +else: + raise AssertionError('accepted an undefined upper half in the atomic address') diff --git a/tests/native_lds_gpu.cpp b/tests/native_lds_gpu.cpp new file mode 100644 index 0000000000..43f1ef6c7c --- /dev/null +++ b/tests/native_lds_gpu.cpp @@ -0,0 +1,91 @@ +#include "desktop_gpu.h" +#include "shader_dxil_compiler.h" +#include <dxgi1_4.h> +#include <array> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> + +using Microsoft::WRL::ComPtr; +int wmain(int argc,wchar_t** argv) { + if(argc!=5) return 2; + try { + std::ifstream input(argv[3],std::ios::binary); + if(!input) return 2; + std::string source{std::istreambuf_iterator<char>(input),{}}; + x2w::ShaderDxilCompiler compiler(argv[2]); + auto shader=compiler.compile(source,L"cs_6_0",argv[4]); + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> adapter; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)),"factory"); + const bool warp=std::wstring(argv[1])==L"warp"; + if(warp) check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)),"warp"); + else { + ComPtr<IDXGIAdapter1> candidate; + for(UINT i=0;factory->EnumAdapters1(i,candidate.ReleaseAndGetAddressOf())==S_OK;++i) { + DXGI_ADAPTER_DESC1 description{}; + check(candidate->GetDesc1(&description),"adapter description"); + if(!(description.Flags&DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(),D3D_FEATURE_LEVEL_11_0,__uuidof(ID3D12Device),nullptr))) { + adapter=candidate; + break; + } + } + if(!adapter) { std::puts("no D3D12 hardware adapter"); return 77; } + } + ComPtr<ID3D12Device> device; + check(D3D12CreateDevice(adapter.Get(),D3D_FEATURE_LEVEL_11_0,IID_PPV_ARGS(&device)),"device"); + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_0}; + if(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL,&model,sizeof(model))) || + model.HighestShaderModel<D3D_SHADER_MODEL_6_0) { std::puts("requires shader model 6"); return 77; } + D3D12_ROOT_PARAMETER param{}; + param.ParameterType=D3D12_ROOT_PARAMETER_TYPE_UAV; + D3D12_ROOT_SIGNATURE_DESC layout{1,¶m}; + ComPtr<ID3DBlob> serialized; + check(D3D12SerializeRootSignature(&layout,D3D_ROOT_SIGNATURE_VERSION_1,&serialized,nullptr),"serialize"); + ComPtr<ID3D12RootSignature> root; + check(device->CreateRootSignature(0,serialized->GetBufferPointer(),serialized->GetBufferSize(),IID_PPV_ARGS(&root)),"root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature=root.Get(); + desc.CS={shader.dxil.data(),shader.dxil.size()}; + ComPtr<ID3D12PipelineState> pipeline; + check(device->CreateComputePipelineState(&desc,IID_PPV_ARGS(&pipeline)),"pipeline"); + ComputeCommands cmd(device.Get(),pipeline.Get()); + constexpr unsigned words=29; + constexpr size_t bytes=32*words*sizeof(unsigned); + auto output=make_buffer(device.Get(),bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto readback=make_buffer(device.Get(),bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + cmd.list->SetComputeRootSignature(root.Get()); + cmd.list->SetComputeRootUnorderedAccessView(0,output->GetGPUVirtualAddress()); + cmd.list->Dispatch(1,1,1); + transition(cmd.list.Get(),output.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd.list->CopyResource(readback.Get(),output.Get()); + cmd.submit_and_wait(device.Get()); + void* data=nullptr; + D3D12_RANGE range{0,bytes}; + check(readback->Map(0,&range,&data),"readback"); + for(unsigned lane=0;lane<32;++lane) { + unsigned other=(lane+1)%32; + auto bits=[](float f){ unsigned u; std::memcpy(&u,&f,sizeof(u)); return u; }; + float a=static_cast<float>(lane+1); + std::array<unsigned,words> expected{100+other,200+other,300+other,400+other,100,231,500+other,600+other, + 700+other,800+other,900+other,bits(a+2),bits(a-2),bits(2-a),bits(2*a), + lane*3,lane*2,(0x80000000u+lane)-1,lane+11,700+other,800+other,900+other,1000+other, + 303+other,404+other,101+other,202+other,lane+100,99}; + for(unsigned i=0;i<words;++i) { + auto actual=static_cast<const unsigned*>(data)[words*lane+i]; + if(actual!=expected[i]) { + std::fprintf(stderr,"lane %u component %u expected %u got %u\n",lane,i,expected[i],actual); + return 1; + } + } + } + D3D12_RANGE empty{}; + readback->Unmap(0,&empty); + std::printf("%u LDS and vector ALU readback words matched\n",32*words); + } catch(const std::exception& e) { + std::fprintf(stderr,"%s\n",e.what()); + return 1; + } +} diff --git a/tests/native_lds_gpu.hlsl b/tests/native_lds_gpu.hlsl new file mode 100644 index 0000000000..9ba59ed621 --- /dev/null +++ b/tests/native_lds_gpu.hlsl @@ -0,0 +1,78 @@ +RWByteAddressBuffer output : register(u0); +groupshared uint lds[1024]; + +[numthreads(32,1,1)] +void main(uint lane : SV_GroupIndex) { + uint exec=1, v0=4*lane, v1=100+lane, v2=200+lane, v3=0, v4=0; + uint v5=0, v6=0, v7=0, v8=0; + lds[320+lane]=300+lane; + lds[448+lane]=400+lane; + lds[128+lane]=500+lane; + lds[160+lane]=600+lane; + if(lane==0) { lds[512]=0xffffffff; lds[513]=0; } + GroupMemoryBarrierWithGroupSync(); + // stride-64 write, then atomic min and max on two shared words + #pragma x2w_lds d83c0301 00020100 + v3=2048; + #pragma x2w_lds d81c0000 00000103 + #pragma x2w_lds d8200004 00000203 + v3=4*(640+3*lane); + v5=700+lane; v6=800+lane; v7=900+lane; + #pragma x2w_lds db780000 00000503 + v3=4*(736+4*lane); + v8=1000+lane; + #pragma x2w_lds db7c0000 00000503 + exec=0; + v8=0; + #pragma x2w_lds db7c0000 00000503 + exec=1; + GroupMemoryBarrierWithGroupSync(); + uint other=(lane+1)%32; + uint base=116*lane; + uint wide=736+4*other; + output.Store4(base+76,uint4(lds[wide],lds[wide+1],lds[wide+2],lds[wide+3])); + output.Store2(base,uint2(lds[64+other],lds[192+other])); + v4=4*other; + // The first read overwrites the incoming address register. + #pragma x2w_lds d8e00705 04000004 + output.Store4(base+8,uint4(v4,v5,lds[512],lds[513])); + // One inactive store cannot disturb the initialized value. + exec=0; + #pragma x2w_lds d8340200 00000100 + exec=1; + v6=4*other; + #pragma x2w_lds d8dca080 07000006 + output.Store2(base+24,uint2(v7,v8)); + v4=4*(640+3*other); + #pragma x2w_lds d9d80000 04000004 + output.Store3(base+32,uint3(v4,v5,lds[642+3*other])); + v1=asuint(float(lane+1)); v2=asuint(2.0f); + #pragma x2w_vop2 06060501 + #pragma x2w_vop2 08080501 + #pragma x2w_vop2 0a0a0501 + #pragma x2w_vop2 100c0501 + output.Store4(base+44,uint4(v3,v4,v5,v6)); + v1=0xff000003; v2=0x80000000|lane; + #pragma x2w_vop2 16060501 + #pragma x2w_vop2 340804ff 00000021 + #pragma x2w_vop2 4a0a04c1 + #pragma x2w_vop2 4a0c04ff 8000000b + exec=0; + #pragma x2w_vop2 4a0c0481 + output.Store4(base+60,uint4(v3,v4,v5,v6)); + exec=1; + v0=4*(864+4*lane); + v1=101+lane; v2=202+lane; v5=303+lane; v6=404+lane; + // Each offset is measured in 64-bit elements. Reverse them for the read. + #pragma x2w_lds d9380100 00050100 + v0=4*(864+4*other); + GroupMemoryBarrierWithGroupSync(); + #pragma x2w_lds d9dc0001 00000000 + output.Store4(base+92,uint4(v0,v1,v2,v3)); + // Each lane atomically subtracts from its own word. Alias DATA0 with VDST. + v0=4*(992+lane); + lds[992+lane]=lane+100; + v1=lane+1; + #pragma x2w_lds d8840000 01000100 + output.Store2(base+108,uint2(v1,lds[992+lane])); +} diff --git a/tests/native_lds_request_check.py b/tests/native_lds_request_check.py new file mode 100644 index 0000000000..585b93e987 --- /dev/null +++ b/tests/native_lds_request_check.py @@ -0,0 +1,37 @@ +"""Compile a source-built slot 67 request through the LDS replay CLI.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +from startup_compute_translate_check import state_a, write_request +from startup_gfx2hlsl_compute_check import CASES + + +def main(compiler, sdk): + script = Path(__file__).resolve().parents[1] / 'tools/startup/compile_lds_request.py' + _, code, rsrc2, group, _ = CASES['F'] + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + key = write_request(work, code, state_a(group, rsrc2)) + marker = work / f'req_{key:016x}.c67' + command = [sys.executable, '-B', script, marker, work / 'output', + '--compiler', compiler, '--sdk', sdk, '--cache', work / 'cache', + '--rw-image', '0', '0', '--wave-size', '32'] + subprocess.run(command, check=True) + bundle, = (work / 'output').iterdir() + source = (bundle / f'{key:016x}.cs.hlsl').read_text() + assert '#pragma x2w_lds ' in source and '#pragma x2w_vop2 ' in source + assert 'GroupMemoryBarrierWithGroupSync();' in source + assert (bundle / f'{key:016x}.cs.cso').read_bytes().startswith(b'DXBC') + assert 'group 64 1 1' in (bundle / f'{key:016x}.txt').read_text().splitlines() + + data = marker.with_suffix('.data') + data.write_bytes(bytes(b ^ 1 for b in data.read_bytes())) + refused = subprocess.run(command, capture_output=True, text=True) + assert refused.returncode and 'do not match the key' in refused.stderr, refused.stderr + assert list((work / 'output').iterdir()) == [bundle] + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_m0_check.py b/tests/native_m0_check.py new file mode 100644 index 0000000000..c89950a153 --- /dev/null +++ b/tests/native_m0_check.py @@ -0,0 +1,106 @@ +"""Numeric M0 in the direct compute path (RDNA2 scalar encoding 124). + +The per-wave value must survive overwrites, SCC control flow, CFG joins and +loops. Two complete physical wave32 groups use one guest lane for stores. +M0 memory addressing is deliberately separate from #3172. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + +M0 = 124 +SENTINEL = 0x69696969 +WORDS = 2064 +PREFIX = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 134), vmove(8, 7), sop1(3, 126, 129)] + +def mov(dst, src): + return sop1(3, dst, src) + +def stores(regs): + p = [0xbf8cc07f] + for j, reg in enumerate(regs): + p += [0xe0701000 | (4*j), 0x80080008 | (reg << 8)] + return p + [0xbf810000] + +def program(): + p = PREFIX + [ + mov(M0, 132), vmove(1, M0), + mov(M0, 5), scalar(0, M0, M0, 136), vmove(2, M0), + mov(M0, 193), scalar(0, M0, M0, 129), vmove(3, M0), + scalar(0x0a, 10, 129, 128), vmove(4, 10), + 0xb0000000 | M0 << 16 | 0xfffe, vmove(5, M0), + 0xbf068005, # s_cmp_eq_u32 s5, 0 + 0xbf850002, # SCC1 skips the other branch's write + jump + mov(M0, 162), 0xbf820001, mov(M0, 145), + vmove(6, M0), mov(11, M0), vmove(7, 11), + scalar(0x0a, M0, M0, 176), vmove(9, M0), + mov(M0, 128), + scalar(0, M0, M0, 129), 0xbf0a837c, 0xbf85fffd, + vmove(10, M0), + mov(126, 128), mov(M0, 137), mov(126, 129), vmove(11, M0), + ] + return p + stores((1,2,3,4,5,6,7,9,10,11)) + +def reference(): + expected = [SENTINEL]*WORDS + for group in range(2): + start = 8 + group*16 + branch = 17 if group == 0 else 34 + expected[start:start+10] = [4, 8+group, 0, 1, 0xfffffffe, branch, + branch, 17 if group == 0 else 48, 3, 9] + return expected + +def controls(cli, sdk, work, root): + def run(label, p, refusal=None): + marker = request(work, root, p) + output = work / (label+".cso") + r = subprocess.run([cli,sdk,work/"cache","gfx1013-direct-cs@0",marker,output], + capture_output=True,text=True) + if refusal is None: + assert r.returncode == 0 and output.is_file(), (label,r.stdout,r.stderr) + else: + assert r.returncode and refusal in r.stderr and not output.exists(), (label,r.stdout,r.stderr) + print(label, "accepted" if refusal is None else r.stderr.strip(), flush=True) + run("numeric", program()) + run("undefined", PREFIX+[vmove(1,M0)]+stores((1,)), "unbound numeric M0") + run("partial_join", PREFIX+[0xbf068005,0xbf850001,mov(M0,132),vmove(1,M0)]+stores((1,)), + "unbound numeric M0") + run("descriptor", PREFIX+[mov(M0,32),vmove(1,M0)]+stores((1,)), "descriptor used as mask") + run("pair_source", PREFIX+[mov(M0,132),sop1(4,10,M0),vmove(1,10)]+stores((1,)), + "unsupported wave64 scalar pair") + run("pair_destination", PREFIX+[sop1(4,M0,128),vmove(1,M0)]+stores((1,)), + "direct scalar move destination") + run("memory_offset", PREFIX+[mov(M0,132),vmove(1,129),0xe0701000,0x7c080108,0xbf810000], + "direct DXIL operand encoding") + return 0 + +def hardware(replay,sdk,work,root): + marker = request(work,root,program()) + out = work/"out.bin" + r = subprocess.run([replay,sdk,marker,work/"cache","0",out,"--direct"]) + if r.returncode == 77: + return 77 + r.check_returncode() + actual = struct.unpack(f"<{WORDS}I",out.read_bytes()) + expected = reference() + assert list(actual) == expected, [(i,hex(a),hex(b)) for i,(a,b) in enumerate(zip(actual,expected)) if a!=b][:16] + print("M0: two groups, 20 value words and all 2044 guard/untouched words match",flush=True) + return 0 + +def main(mode,tool,sdk): + with tempfile.TemporaryDirectory() as temp: + work=Path(temp) + src=work/"root.hlsl" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root=work/"root.bin" + subprocess.run([Path(sdk)/"dxc.exe","-T","rootsig_1_1","-E","SIG","-Fo",root,src],check=True) + return {"controls":controls,"hardware":hardware}[mode](tool,sdk,work,root.read_bytes()) + +if __name__=="__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_mad32_check.py b/tests/native_mad32_check.py new file mode 100644 index 0000000000..38bab453f9 --- /dev/null +++ b/tests/native_mad32_check.py @@ -0,0 +1,167 @@ +"""v_mad_f32, v_mad_legacy_f32, v_mac_f32 and v_mac_legacy_f32 in the direct compute path (#3005). + + native_mad32_check.py controls <compile_dxil> <sdk bin dir> + native_mad32_check.py hardware <native_store_replay> <sdk bin dir> + +The semantics are gfx2hlsl.py's mad32 (and pixel_aot's): flush denormal inputs to signed zero, round the product on +its own (the legacy forms make 0 * anything +0), add the flushed addend and flush the sum. v_mac_* add the +destination. The VOP3 and VOP2 words were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013); the v_mov and store +words follow native_lane_access_check.py, with 32 words per lane. + +Each case sets S0, S1 and S2 by v_mov literals and stores the four results; every lane of two groups stores all +cases. The cases need a separately rounded product ((1 + 2^-12)^2 - 1), flush a denormal input and a denormal sum, +take 0 * inf and signed zeros. References that fuse, skip the flush, or treat the legacy forms like the plain ones +must each differ from the expected words. +""" +from pathlib import Path +import math +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + + +def bits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def value(b): + return struct.unpack('<f', struct.pack('<I', b))[0] + + +CASES = [ + (0x3F800800, 0x3F800800, bits(-1.0)), # product needs 25 bits: fused and unfused differ + (0x00000001, 0x7E800000, bits(1.0)), # a denormal input: flushed, so the product is 0 + (bits(0.0), 0x7F800000, bits(2.0)), # 0 * inf: NaN, or +0 for the legacy forms + (0x80000000, bits(1.0), 0x80000000), # -0 * 1 + -0: -0, or +0 + -0 = +0 for the legacy forms + (bits(1.5 * 2.0 ** -63), bits(2.0 ** -63), 0x80800000), # 1.5 * 2^-126 - 2^-126: a denormal sum, flushed + (bits(3.0), bits(-2.5), bits(0.25)), # an ordinary value +] +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] +BODY = [0xD5410004, 0x040E0501, 0xD5400005, 0x040E0501, 0x7E0C0303, 0x3E0C0501, 0x7E0E0303, 0x0C0E0501] +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def program(): + code = list(PROLOGUE) + for index, (a, b, c) in enumerate(CASES): + code += [0x7E0202FF, a, 0x7E0402FF, b, 0x7E0602FF, c] + BODY + for slot, vgpr in enumerate((4, 5, 6, 7)): + code += [0xE0701000 | (16 * index + 4 * slot), 0x80080008 | vgpr << 8] + return code + [0xBF810000] + + +def f32(x): + if math.isnan(x): + return 0x7FC00000 + return bits(x) + + +def ftz(b): + return b & 0x80000000 if (b & 0x7FFFFFFF) < 0x00800000 else b + + +def mad(a, b, c, legacy, fused=False, flush=True): + if flush: + a, b, c = ftz(a), ftz(b), ftz(c) + x, y, z = value(a), value(b), value(c) + if legacy and (x == 0 or y == 0): + product = 0.0 + else: + product = x * y if not (math.isinf(x) or math.isinf(y)) or (x != 0 and y != 0) else math.nan + if fused: + total = product + z if not math.isnan(product) else math.nan + out = f32(total) if not math.isnan(total) else 0x7FC00000 + else: + p = f32(product) if not math.isnan(product) else 0x7FC00000 + if flush: + p = ftz(p) + q = value(p) + total = q + z if not math.isnan(q) else math.nan + out = f32(total) if not math.isnan(total) else 0x7FC00000 + return ftz(out) if flush else out + + +def results(a, b, c, same_legacy=False, **mutation): + plain, legacy = mad(a, b, c, False, **mutation), mad(a, b, c, True, **mutation) + if same_legacy: + legacy = plain + return [plain, legacy, plain, legacy] + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for lane in range(64): + base = GUARD_WORDS + lane * 32 + for index, case in enumerate(CASES): + expected[base + 4 * index:base + 4 * index + 4] = results(*case, **mutation) + return expected + + +def nan_equal(actual, expected): + """A NaN result compares by class: any quiet or signalling NaN pattern matches an expected NaN.""" + def is_nan(x): + return (x & 0x7F800000) == 0x7F800000 and x & 0x007FFFFF + return all(a == e or (is_nan(a) and is_nan(e)) for a, e in zip(actual, expected)) + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + # Four unfused multiply-adds per case: a separate fmul and fadd each, and no FMad (DXIL tertiary opcode 46). + assert dump.count('fmul') >= 4 * len(CASES) and dump.count('fadd') >= 4 * len(CASES), dump + assert '@dx.op.tertiary.f32(i32 46,' not in dump, dump + assert ' fast ' not in dump and 'contract' not in dump, dump + # v_mac_f32_e64 v6, v1, v2 with the neg bit of the accumulator (src2) set: refused, not dropped. + negated = program() + at = negated.index(0x3E0C0501) + negated[at:at + 1] = [0xD51F0006, 0x841A0501] + marker = request(work, root, negated) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, marker.with_suffix('.neg.cso')], + capture_output=True, text=True) + assert result.returncode != 0 and 'accumulator modifier' in result.stdout + result.stderr, (result.stdout, + result.stderr) + expected = reference() + for label, mutation in (('fused', {'fused': True}), ('no flush', {'flush': False}), + ('legacy like plain', {'same_legacy': True})): + assert reference(**mutation) != expected, label + print('compiled with separate fmul and fadd and no FMad or fast-math flags; the fused, unflushed and ' + 'legacy-as-plain references differ; an accumulator neg is refused') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + assert nan_equal(actual, expected), [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) + if x != y][:10] + print('the four unfused multiply-adds: all 2064 words matched (NaN by class)') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_mad32_k_check.py b/tests/native_mad32_k_check.py new file mode 100644 index 0000000000..68dfc0849a --- /dev/null +++ b/tests/native_mad32_k_check.py @@ -0,0 +1,289 @@ +"""v_madmk_f32 and v_madak_f32 in the direct C++ Compute and Pixel DXIL paths.""" +from dataclasses import dataclass +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE +from native_scalar_lds_check import vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_CODE = {'madmk': 0x20, 'madak': 0x21} + + +def fbits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def fval(b): + return struct.unpack('<f', struct.pack('<I', b & 0xFFFFFFFF))[0] + + +def ftz(b): + b &= 0xFFFFFFFF + return b & 0x80000000 if (b & 0x7FFFFFFF) < 0x00800000 else b + + +def mad_ftz(a, b, c, *, fused=False, flush=True): + if flush: + a, b, c = ftz(a), ftz(b), ftz(c) + x, y, z = fval(a), fval(b), fval(c) + if (math.isinf(x) and y == 0.0) or (math.isinf(y) and x == 0.0) or math.isnan(x) or math.isnan(y): + product = math.nan + else: + product = x * y + if fused: + total = product + z if not math.isnan(product) else math.nan + out = 0x7FC00000 if math.isnan(total) else fbits(total) + else: + p = 0x7FC00000 if math.isnan(product) else (ftz(fbits(product)) if flush else fbits(product)) + q = fval(p) + total = q + z if not math.isnan(q) else math.nan + out = 0x7FC00000 if math.isnan(total) else fbits(total) + return ftz(out) if flush else out + + +def is_nan_f32(b): + return (b & 0x7F800000) == 0x7F800000 and (b & 0x007FFFFF) != 0 + + +def same_f32(got, want): + if is_nan_f32(want): + return is_nan_f32(got) + return got == want + + +def vop2_k(op, dst, src0, vsrc1, lit): + w0 = (OP_CODE[op] << 25) | ((dst & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF) + return [w0, lit & 0xFFFFFFFF] + + +def f32_inline(enc): + inline_f = { + 240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000, + } + if enc in inline_f: + return inline_f[enc] + if 128 <= enc <= 192: + return enc - 128 + raise ValueError(enc) + + +@dataclass(frozen=True) +class Case: + name: str + op: str + src0_enc: int + src0_val: int + vsrc1_val: int + k_val: int + pixel_safe: bool = True + + def operands(self): + a = f32_inline(self.src0_enc) if 128 <= self.src0_enc < 255 else self.src0_val + if self.op == 'madmk': + return a, self.k_val, self.vsrc1_val + return a, self.vsrc1_val, self.k_val + + def expected(self, **mutation): + return mad_ftz(*self.operands(), **mutation) + + +def all_cases(): + return [ + # 1. Distinct K vs S1 argument positions. + Case('madmk_asymmetric', 'madmk', 257, fbits(3.0), fbits(1.25), fbits(-2.5)), + Case('madak_asymmetric', 'madak', 257, fbits(3.0), fbits(-2.5), fbits(1.25)), + # 2. Unfused product rounding ties: fused FMA differs by 1 ULP. + Case('madmk_unfused_tie_sub', 'madmk', 257, 0x3F800800, fbits(-1.0), 0x3F800800), + Case('madak_unfused_tie_add', 'madak', 257, 0x3F800001, 0x3F800001, 0x3F800003), + # 3. Denormal input flushes (src0, literal K multiplier in madmk, literal K addend in madak). + Case('madmk_ftz_src0', 'madmk', 257, 0x00000001, fbits(1.0), 0x7E800000), + Case('madmk_ftz_lit_k', 'madmk', 257, 0x7E800000, fbits(2.0), 0x80400000), + Case('madak_ftz_lit_k', 'madak', 257, 0x00800000, fbits(1.0), 0x00400000), + # 4. Denormal product flush and denormal sum flush. + Case('madmk_ftz_product', 'madmk', 257, 0x00800000, 0x00800000, fbits(0.5)), + Case('madak_ftz_sum', 'madak', 257, fbits(1.5 * 2.0 ** -63), fbits(2.0 ** -63), 0x80800000, pixel_safe=False), + # 5. SGPR src0 and inline float src0 (242=1.0, 240=0.5). + Case('madmk_sgpr_src0', 'madmk', 10, fbits(2.5), fbits(-0.75), fbits(4.0)), + Case('madak_inline_242', 'madak', 242, 0, fbits(3.5), fbits(-1.5)), + Case('madmk_inline_240', 'madmk', 240, 0, fbits(0.25), fbits(5.0)), + # 6. Inf/zero -> NaN and negative-zero preservation. + Case('madmk_zero_inf_nan', 'madmk', 257, fbits(0.0), fbits(2.0), 0x7F800000, pixel_safe=False), + Case('madak_neg_zero', 'madak', 257, 0x80000000, fbits(1.0), 0x80000000, pixel_safe=False), + ] + + +def emit_case(c: Case): + code = [] + if c.src0_enc >= 256: + code += F.mov(c.src0_enc - 256, c.src0_val) + elif c.src0_enc <= 105: + code += F.smov(c.src0_enc, c.src0_val) + code += F.mov(2, c.vsrc1_val) + code += vop2_k(c.op, 4, c.src0_enc, 2, c.k_val) + return code + + +def compute_program(cases): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + return [ + # Non-VOP2 (VOP3 e64) forms of v_madmk_f32 / v_madak_f32 refused. + ([0xD5200004, 0x00020501, 0xBF810000], 'unsupported v_madmk_f32 encoding'), + ([0xD5210004, 0x00020501, 0xBF810000], 'unsupported v_madak_f32 encoding'), + # SDWA and DPP forms remain refused. + ([0x400804F9, 0x06060601, 0xBF810000], 'unimplemented direct SDWA operand profile'), + ([0x420804FA, 0xFF001B01, 0xBF810000], 'SDWA or DPP vector operands'), + ] + + +def check_reference_mutations(items): + baseline = [c.expected() for c in items] + for label, mutation in (('fused', {'fused': True}), ('no_flush', {'flush': False})): + mutated = [c.expected(**mutation) for c in items] + assert mutated != baseline, label + swapped = [mad_ftz(c.operands()[0], c.operands()[2], c.operands()[1]) for c in items] + assert swapped != baseline, 'swapped_k_s1' + + +def ir(dumper): + items = all_cases() + check_reference_mutations(items) + code, want = compute_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'mad32-k') + assert run.returncode == 0, run.stderr + assert '@dx.op.tertiary.f32(i32 46,' not in run.stdout, run.stdout + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same_f32(got, exp)] + assert not bad, bad[:8] + for idx, (prog, why) in enumerate(refusals): + r = F.dump(dumper, work, prog, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_mad32_k IR: {len(want)} cases matched unfused FTZ model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + check_reference_mutations(items) + code, want = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert dump.count('fmul') >= len(items) and dump.count('fadd') >= len(items), dump + assert '@dx.op.tertiary.f32(i32 46,' not in dump, dump + assert ' fast ' not in dump and 'contract' not in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_mad32_k controls: compiled {len(want)} cases with separate fmul/fadd; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, w in enumerate(want): + expected[head + idx] = w + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same_f32(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_mad32_k compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'madk-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected() for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_mad32_k pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_mad64_check.py b/tests/native_mad64_check.py new file mode 100644 index 0000000000..72dab0db6f --- /dev/null +++ b/tests/native_mad64_check.py @@ -0,0 +1,133 @@ +"""v_mad_u64_u32 and v_mad_i64_i32 in the direct compute path (#3000). + + native_mad64_check.py controls <compile_dxil> <sdk bin dir> + native_mad64_check.py hardware <native_store_replay> <sdk bin dir> + +D = S0 * S1 + S2 modulo 2^64, with 32-bit factors (zero- or sign-extended) and a 64-bit S2 (gfx2hlsl.py mad64). The +unsigned form writes the carry-out of the 64-bit add to its SDST as a lane mask; the signed form is lowered only with +the null SDST, as in gfx2hlsl.py. All words were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The dispatch has two groups of 32 lanes. With n = lane + 32 * group, S0 = mul_u32_u24(n, 0x0f0f0f) ^ 0xffff0000, +S1 = mul_u32_u24(n, 0x123457) ^ 0xfff00000 and S2 = {((n & 1) << 31) | 0x10, mul_u32_u24(n, 0x777777) ^ 0x89abcdef}, +so the products lie just below 2^64 and the unsigned sum carries exactly for the odd lanes. Each lane stores the unsigned and signed results and +the carry mask in s30 (v_mov_b32 v12, s30), which must equal the ballot of its group. References that drop the +high word, zero-extend the signed factors or report no carry must each differ. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +# See the docstring; the program ends with buffer_store_dword v4, v5, v10, v11, v12 at v8 + 0..16 and s_endpgm. +HEX = ('040394be 800395be 0a0808f4200000fa 058a078f 0585088f 85001034 0710104a 0800124a ff1202160f0f0f00 ' + 'ff02023a0000ffff ff12041657341200 ff04043a0000f0ff ff120c1677777700 ff0c0c3aefcdab89 81120e36 9f0e0e34 900e0e38 ' + '041e76d501051a04 0a7d77d501051a04 1e02187e 7fc08cbf 001070e008040880 041070e008050880 081070e0080a0880 ' + '0c1070e0080b0880 101070e0080c0880 000081bf') +SIGNED_WITH_SDST = '0a1e77d501051a04' # v_mad_i64_i32 v[10:11], s30, v1, v2, v[6:7]: refused +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +M32, M64 = 0xFFFFFFFF, (1 << 64) - 1 + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & M32 + + +def s32(x): + return x - (1 << 32) if x & 0x80000000 else x + + +def operands(n): + a, b = mul24(n, 0x0F0F0F) ^ 0xFFFF0000, mul24(n, 0x123457) ^ 0xFFF00000 + c = ((((n & 1) << 31) | 0x10) << 32) | (mul24(n, 0x777777) ^ 0x89ABCDEF) + return a, b, c + + +def reference(drop_high=False, zero_extend_signed=False, no_carry=False): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + mask = 0 + rows = [] + for lane in range(32): + a, b, c = operands(lane + 32 * group) + total = a * b + c + mask |= (0 if no_carry else int(total > M64)) << lane + signed = ((a * b if zero_extend_signed else s32(a) * s32(b)) + c) & M64 + unsigned = total & M64 + rows.append([unsigned & M32, 0 if drop_high else unsigned >> 32, signed & M32, signed >> 32]) + for lane, row in enumerate(rows): + base = GUARD_WORDS + (group * 32 + lane) * 8 + expected[base:base + 5] = row + [mask] + return expected + + +def compile_program(cli, sdk, work, root, code): + marker = request(work, root, code) + return marker, subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, + marker.with_suffix('.cso')], capture_output=True, text=True) + + +def controls(cli, sdk, work, root): + marker, result = compile_program(cli, sdk, work, root, words(HEX)) + assert result.returncode == 0 and marker.with_suffix('.cso').is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', marker.with_suffix('.cso')], capture_output=True, + text=True, check=True).stdout + assert dump.count('mul i64') == 2 and 'sext i32' in dump and 'icmp ult i64' in dump, dump + signed_sdst = HEX.replace('0a7d77d501051a04', SIGNED_WITH_SDST) + _, result = compile_program(cli, sdk, work, root, words(signed_sdst)) + assert result.returncode and 'v_mad_i64_i32 carry-out destination' in result.stderr, (result.stdout, result.stderr) + # The unsigned form with the null SDST is refused by the symbolic transfer, as gfx2hlsl.py refuses it, and an + # inline float factor is refused like in gfx2hlsl.py. + for code, message in ((HEX.replace('041e76d501051a04', '047d76d501051a04'), 'unsupported carry mask destination'), + (HEX.replace('041e76d501051a04', '041e76d5f2041a04'), 'with an inline float factor')): + _, result = compile_program(cli, sdk, work, root, words(code)) + assert result.returncode and message in result.stderr, (message, result.stdout, result.stderr) + expected = reference() + masks = {expected[GUARD_WORDS + g * 32 * 8 + 4] for g in range(2)} + assert all(0 < m < M32 for m in masks), [hex(m) for m in masks] # some lanes carry, some do not + for label, mutation in (('high word dropped', {'drop_high': True}), + ('signed factors zero-extended', {'zero_extend_signed': True}), + ('no carry', {'no_carry': True})): + assert reference(**mutation) != expected, label + print('compiled with two 64-bit multiplies and an unsigned carry compare; the signed form with an SGPR ' + 'carry-out, the unsigned form with null and an inline float factor refused; both groups have mixed carries; the three mutated references differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, reference())) if x != y] + assert not diff, diff[:10] + print('v_mad_u64_u32 and v_mad_i64_i32: results, carry masks, guards and sentinels matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_mtbuf_check.py b/tests/native_mtbuf_check.py new file mode 100644 index 0000000000..fe3a740291 --- /dev/null +++ b/tests/native_mtbuf_check.py @@ -0,0 +1,124 @@ +"""Decode explicit MTBUF formats through the runtime's direct C++ compute backend.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +# format, channels actually requested, immediate byte displacement (plus group.x) +CASES = [(24, 2, 0), (24, 2, 4), (56, 4, 3), (60, 4, 7), (13, 1, 12), + (71, 4, 12), (75, 4, 4), (2, 1, 7), (12, 1, 7), (25, 2, 3), (24, 2, 8188)] +CASES += [(fmt, 4, 1) for fmt in range(44, 56)] +PACKED = struct.pack("<6I", 0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5) + + +def program(unsigned): + # Load a raw SRV and UAV from separate table parameters. One writer per group. + words = [sop1(3, 20, 4), sop1(3, 21, 128), sop1(3, 22, 5), sop1(3, 23, 128), + 0xf4080000 | 32 << 6 | 10, 0xfa000020, 0xf4080000 | 36 << 6 | 11, 0xfa000020, + scalar(0x1e, 7, 6, 137), vmove(8, 7), sop1(3, 126, 129)] + pos = 0 + for index, (fmt, channels, disp) in enumerate(CASES): + if unsigned and index == 0: + fmt = 23 + if disp > 4095: + words += [scalar(0, 9, 6, 255), disp, vmove(10, 9)] + disp = 0 + else: + words += [vmove(10, 6)] + words += [0xe8001000 | fmt << 19 | (channels - 1) << 16 | disp, + 0x80080a0a] # v10 is both byte offset and first output + for component in range(channels): + words += [0xe0701000 | 4 * pos, 0x80090008 | (10 + component) << 8] + pos += 1 + return words + [0xbf810000] + + +def fbits(value): + return struct.unpack("<I", struct.pack("<f", value))[0] + + +def expected(group): + result = [] + data = (PACKED * 342)[:8192] + for fmt, count, disp in CASES: + if 44 <= fmt <= 55: + fields = (2, 10, 10, 10) if fmt < 50 else (10, 10, 10, 2) + number = (fmt - 44) % 6 + bits = int.from_bytes(data[disp + group:disp + group + 4], "little") + for width in fields[:count]: + value = bits & ((1 << width) - 1) + bits >>= width + if number in (1, 3, 5) and value >> (width - 1): + value -= 1 << width + if number == 0: + value = fbits(value / ((1 << width) - 1)) + elif number == 1: + value = fbits(max(-1, value / ((1 << (width - 1)) - 1))) + elif number in (2, 3): + value = fbits(value) + result.append(value & 0xffffffff) + continue + width = 4 if fmt == 75 else 1 if fmt in (2, 56, 60) else 2 + if disp + group + width * count > len(data): + result.extend([0] * count) + continue + for c in range(count): + at = disp + group + c * width + v = int.from_bytes(data[at:at + width], "little", signed=fmt in (2, 12, 24)) + if fmt in (13, 71): + v = fbits(struct.unpack_from("<e", data, at)[0]) + elif fmt in (2, 24): + v = fbits(max(-1, v / ((1 << (width * 8 - 1)) - 1))) + elif fmt == 56: + v = fbits(v / 255) + elif fmt == 25: + v = fbits(v) + result.append(v & 0xffffffff) + return result + + +def main(cli, gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src, root = work / "root.hlsl", work / "root.bin" + src.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=8)),DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk)/"dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x8c) + reference = [0x69696969] * 2064 + for group in range(2): + start = 8 + 128 * group + row = expected(group) + reference[start:start + len(row)] = row + for unsigned in (False, True): + words = program(unsigned) + marker = write_request(work, words, root.read_bytes(), sa) + dest = work / "result.bin" + run = subprocess.run([gpu, sdk, marker, work/"cache", "0", dest, "--direct"]) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + differences = [i for i, (a, b) in enumerate(zip(actual, reference)) if a != b] + if unsigned: + assert differences and set(differences) <= {8, 9, 136, 137}, differences + else: + assert not differences, [(i, hex(actual[i]), hex(reference[i])) for i in differences] + insn = next(i for i, w in enumerate(words) if w >> 26 == 0x3a) + for op, error in ((words[insn] | (1 << 13), "without index"), + (0xe8001000 | 24 << 19 | 3 << 16, "absent component")): + bad = words.copy() + bad[insn] = op + marker = write_request(work, bad, root.read_bytes(), sa) + reject = subprocess.run([cli, sdk, work/"cache", "gfx1013-direct-cs@0", marker, work/"bad.cso"], + capture_output=True, text=True) + assert reject.returncode and error in reject.stderr and not (work/"bad.cso").exists(), reject.stderr + print(f"MTBUF matched {2 * len(row)} result words and all guards; changed format, index and component controls passed.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_mul24_check.py b/tests/native_mul24_check.py new file mode 100644 index 0000000000..6b38426bfd --- /dev/null +++ b/tests/native_mul24_check.py @@ -0,0 +1,146 @@ +"""Direct compute VOP2/VOP3A 24-bit integer multiplies (v_mul_i32_i24, v_mul_hi_i32_i24, v_mul_hi_u32_u24).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF + +# Eight pairs covering upper-byte noise (must be ignored), +/-2^23 boundaries, max 24-bit, and sign combinations. +CASES = ( + (0xDE000003, 0xBE000007), + (0xFF7FFFFF, 0xAA7FFFFF), # (+8388607) * (+8388607) + (0x00800000, 0x00800000), # (-8388608) * (-8388608) = +2^46 -> hi = +0x4000 + (0x12800000, 0x347FFFFF), # (-8388608) * (+8388607) -> negative hi + (0x56FFFFFF, 0x78FFFFFF), # (-1)*(-1)=+1 signed; (2^24-1)^2 unsigned -> hi = 0xFFFE + (0x9AFFFFFF, 0xBC000002), # (-1)*(+2)=-2 -> hi = 0xFFFFFFFF signed; hi = 0x0001 unsigned + (0xAB123456, 0xCD654321), # general positive/unsigned product + (0xEF800001, 0x10FFFFFE), # near-min * -2 +) +# (vop2_op, wide) -> covers all 3 opcodes across both VOP2 (_e32) and VOP3A (_e64) encodings. +FORMS = ( + (0x09, False), # v_mul_i32_i24_e32 + (0x0A, False), # v_mul_hi_i32_i24_e32 + (0x0C, False), # v_mul_hi_u32_u24_e32 + (0x0A, True), # v_mul_hi_i32_i24_e64 +) + + +def vop3a(op, vdst, src0, src1, src2=0, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | (clamp << 15) | ((op_sel & 0xF) << 11) | ((abs_bits & 7) << 8) | (vdst & 0xFF) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((src2 & 0x1FF) << 18) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def program(*, sparse=False, first_modifier=0, second_modifier=0): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, (a, b) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), a, # v_xor_b32 v1, a, v0 + 0x7E0402FF, b] # v_mov_b32 v2, b + for mode, (op2, wide) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + if wide: + w0, w1 = vop3a(0x100 + op2, 4, 257, 258) + if (first_modifier or second_modifier) and case == 0: + w0 ^= first_modifier + w1 ^= second_modifier + code += [w0, w1] + else: + code += [vop2(op2, 4, 257, 2)] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def sext24(v): + v &= 0xFFFFFF + return v - 0x1000000 if v >= 0x800000 else v + + +def eval_mul24(op2, a, b): + if op2 == 0x09: + return (sext24(a) * sext24(b)) & MASK + if op2 == 0x0A: + return ((sext24(a) * sext24(b)) >> 32) & MASK + return (((a & 0xFFFFFF) * (b & 0xFFFFFF)) >> 32) & MASK + + +def reference(sparse=False): + words = [SENTINEL] * 8 + for lane in range(64): + for a, b in CASES: + for op2, _wide in FORMS: + words.append(INACTIVE if sparse and lane % 2 else eval_mul24(op2, a ^ (lane % 32), b)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + # Valid encoding + 5 refused VOP3A encodings: + # clamp (w0[15]), op_sel (w0[11]), abs (w0[8]), neg (w1[29]), nonzero src2 (w1[18]). + refusal_cases = ( + (0, 0, ''), + (1 << 15, 0, 'modifier'), + (1 << 11, 0, 'op_sel'), + (1 << 8, 0, 'modifier'), + (0, 1 << 29, 'modifier'), + (0, 1 << 18, 'unused src2'), + ) + for first, second, needle in refusal_cases: + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and needle in result.stderr, (first, second, result.stderr) + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'ashr i32 ' in dump and ', 20' in dump and 'and i32 ' in dump and ', 4095' in dump, dump + assert reference() != reference(sparse=True) + print('mul24 DXIL verified; five VOP3A modifier/unused-src2 encodings refused; EXEC control differs') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse in (False, True): + marker = request(work, root, program(sparse=sparse)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_mul24_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_or_saveexec_check.py b/tests/native_or_saveexec_check.py new file mode 100644 index 0000000000..8f9b4cd133 --- /dev/null +++ b/tests/native_or_saveexec_check.py @@ -0,0 +1,79 @@ +"""Direct wave32 s_or_saveexec_b32: saved EXEC, the OR result, SCC and a restore, in full and partial waves.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def or_saveexec_readback(work, gpu, sdk): + full = 0xffffffff + root = (work / "root.bin").read_bytes() + for width in (8, 32): + entry = (1 << width) - 1 + sa = struct.pack("<7I", 0, 0, 0, width | 1 << 16, 1, 0, 0x80 | 5 << 1) + for name, old, src, mask in ( + ("all", 0x25, 193, full), + ("sgpr", 0x25, 10, 0x80000092), # Source aliases the saved EXEC destination. + ("literal", 0x25, 255, 0x80000018), + ("vcc", 0x25, 106, 0x80000042), + ("empty", 0, 128, 0), + ("past-end", 0, 255, 0x80000000), + ): + updated = old | mask # EXEC is stored as computed, including bits past the group + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 137), 0x34000000 | 8 << 17 | 132, + 0x4a000000 | 8 << 17 | 8 << 9 | 7, + sop1(0x3c, 24, 255), old] + if src in (10, 106): + words += [sop1(3, src, 255), mask] + if name == "all": + words.append(sop1(3, 10, 32)) # Replace symbolic descriptor provenance with numeric EXEC. + if name == "vcc": + # Derive the same partial EXEC through S_ANDN2_WREXEC_B32. + words += [sop1(3, 126, 255), entry ^ old, sop1(0x47, 25, 24)] + # Set the incoming SCC opposite to the expected new SCC. + words += [0xbf068180 if updated else 0xbf068080, sop1(0x3d, 10, src)] + if src == 255: + words.append(mask) + words += [scalar(0xa, 11, 129, 128), vmove(9, 10), vmove(10, 126), + 0xe0701000, 0x80080908, 0xe0701004, 0x80080a08, + sop1(3, 126, 10), vmove(9, 177), 0xe0701008, 0x80080908, + sop1(3, 126, 24), vmove(9, 11), 0xe070100c, 0x80080908, + 0xbf810000] + expected = [0x69696969] * 2064 + for group in range(2): + for lane in range(width): + pos = 8 + group * 128 + lane * 4 + if updated & (1 << lane): + expected[pos:pos + 2] = [old, updated] + if old & (1 << lane): + expected[pos + 2] = 49 + expected[pos + 3] = int(bool(updated)) + marker = write_request(work, words, root, sa) + dest = work / "or-saveexec.bin" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + sys.exit(77) + result.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, (width, name, [ + (i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b + ][:10]) + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src, root = work / "root.hlsl", work / "root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + or_saveexec_readback(work, gpu, sdk) + print("s_or_saveexec_b32 matched six sources in 8- and 32-thread groups, with SCC, restore and guards.") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_pack_b32_f16_check.py b/tests/native_pack_b32_f16_check.py new file mode 100644 index 0000000000..679c5be908 --- /dev/null +++ b/tests/native_pack_b32_f16_check.py @@ -0,0 +1,210 @@ +"""v_pack_b32_f16 (VOP3 0x311) in the direct C++ DXIL path. + +D[15:0] = S0.f16 and D[31:16] = S1.f16. Per source, op_sel picks the high or low half, abs clears bit 15 of the +half, then neg toggles it. Only integer bit operations are allowed, so signed zero and NaN payloads are kept. +The reference is `ref` of startup_gfx2hlsl_pack_b32_f16_check.py, the model of the Python translator. + + native_pack_b32_f16_check.py ir DUMPER no GPU: build pixel containers, dump the emitted IR with + native_pixel_ir_dump, evaluate it and compare with the model + native_pack_b32_f16_check.py gpu STORE_REPLAY SDK compute readback of the packed bits (exit 77: no adapter) + +Refused forms (explicit diagnostics): clamp, omod, a destination op_sel bit, op_sel[2], abs/neg on source 2, inline +constants and a literal source. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_direct_container_check import patched_pixel +from startup_gfx2hlsl_pack_b32_f16_check import ref +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + +GROUPS = 2 +WORDS = 2064 +BASE = 8 # words before group 0's results (as in half_mad_readback) +STRIDE = 128 # words per group: 512 bytes, so the 66 results of one group never reach the next +SHIFT = 9 # s_lshl_b32 amount giving the per-group byte base +assert 4 * STRIDE == 1 << SHIFT + +PAIRS = [(0x3c00bc00, 0x80017fff), (0xfc007e00, 0x7d557c01), (0x12345678, 0xffff0001), (0x00008000, 0x80000000)] + + +def pack(dst, s0, s1, opsel=0, absm=0, neg=0, clamp=0, omod=0): + return [0xd7110000 | clamp << 15 | opsel << 11 | absm << 8 | dst, s0 | s1 << 9 | omod << 27 | neg << 29] + + +def mov(reg, value): + return [0x7e0002ff | reg << 17, value] + + +def mov_s(reg, value): + return [0xbe8003ff | reg << 16, value] + + +def container(code, outputs=(4, 5, 6, 7)): + return patched_pixel(len(code), code, export=(0xf800180f, sum(r << 8 * i for i, r in enumerate(outputs)))) + + +def evaluate(ir): + """Evaluate the straight-line integer IR; return the four exported words. Anything else is an error.""" + values, out = {}, {} + + def val(token): + return values[token] if token.startswith('%') else int(token) & 0xffffffff + + for line in ir.splitlines(): + line = line.strip() + m = re.fullmatch(r'(%\w+) = (and|or|xor|shl|lshr|add|sub) i32 (\S+), (\S+)', line) + if m: + a, b = val(m.group(3)), val(m.group(4)) + values[m.group(1)] = {'and': a & b, 'or': a | b, 'xor': a ^ b, 'shl': a << b, 'lshr': a >> b, + 'add': a + b, 'sub': a - b}[m.group(2)] & 0xffffffff + continue + m = re.fullmatch(r'(%\w+) = bitcast i32 (\S+) to float', line) + if m: + values[m.group(1)] = val(m.group(2)) + continue + m = re.fullmatch(r'call void @dx\.op\.storeOutput\.f32\(i32 5, i32 0, i32 0, i8 (\d), float (\S+)\)', line) + if m: + out[int(m.group(1))] = val(m.group(2)) + continue + # Any float operation, conversion call or select would break the bit-exactness requirement. + assert not re.search(r'\b(fadd|fmul|fcmp|fptrunc|fpext|select|legacy|call float)', line), line + return [out[c] for c in range(4)] + + +def dump(dumper, work, code, name='case'): + path = work / (name + '.cdxil') + path.write_bytes(container(code)) + run = subprocess.run([dumper, path], capture_output=True, text=True) + return run + + +def run_ir(dumper): + cases = 0 + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + # Every op_sel x abs x neg form, four value pairs per container (v1/v2 in, v4..v7 out). + for sel in range(4): + for absm in range(4): + for neg in range(4): + code, want = [], [] + for k, (a, b) in enumerate(PAIRS): + code += mov(1, a) + mov(2, b) + pack(4 + k, 257, 258, sel, absm, neg) + want.append(ref(a, b, sel, absm, neg)) + run = dump(dumper, work, code) + assert run.returncode == 0, (sel, absm, neg, run.stderr) + got = evaluate(run.stdout) + assert got == want, (sel, absm, neg, [hex(g) for g in got], [hex(w) for w in want]) + cases += len(want) + # Controls: the order of abs and neg, and the half order, must be observable by this check. + if absm & neg: + assert got != [ref(a, b, sel, absm, neg, neg_first=True) for a, b in PAIRS], (sel, absm, neg) + if sel == 1 and not absm and not neg: + swapped = [(w & 0xffff) << 16 | w >> 16 for w in want] + assert got != swapped + # The issue reproduction: v4 = 0x77883344 and v5 is untouched. Without the pack both are 0x55667788. + issue = [0x7e0802ff, 0x11223344, 0x7e0a02ff, 0x55667788, 0xd7110004, 0x00020b04] + path = work / 'issue.cdxil' + path.write_bytes(patched_pixel(len(issue), issue, export=(0xf800180f, 0x05040504))) + run = subprocess.run([dumper, path], capture_output=True, text=True) + assert run.returncode == 0, run.stderr + assert evaluate(run.stdout) == [0x77883344, 0x55667788, 0x77883344, 0x55667788], run.stdout + control = patched_pixel(4, issue[:4], export=(0xf800180f, 0x05040504)) + path.write_bytes(control) + run = subprocess.run([dumper, path], capture_output=True, text=True) + assert run.returncode == 0 and evaluate(run.stdout) == [0x11223344, 0x55667788] * 2, run.stderr + # Destination overlap, SGPR sources (including a high half) and one source used twice. + a, b = 0x80017e55, 0xfc00bc01 + shapes = [ + (mov(4, a) + mov(5, b) + pack(4, 260, 261, 1, 1, 2), a, b, 1, 1, 2), # dst = src0 + (mov(4, a) + mov(5, b) + pack(5, 260, 261, 2, 0, 1), a, b, 2, 0, 1), # dst = src1 + (mov(4, a) + pack(4, 260, 260, 1, 3, 3), a, a, 1, 3, 3), # one reg twice + (mov_s(5, a) + mov(5, b) + pack(4, 5, 261, 1, 1, 0), a, b, 1, 1, 0), # SGPR src0 + (mov_s(5, b) + mov(4, a) + pack(4, 260, 5, 2, 2, 3), a, b, 2, 2, 3), # SGPR src1 + ] + # The SGPR shapes reuse number 5 for an unrelated VGPR; keep each case independent. + for code, x, y, sel, absm, neg in shapes: + run = dump(dumper, work, sum((mov(r, 0) for r in range(4, 8)), []) + code) + assert run.returncode == 0, (code, run.stderr) + dst = code[-2] & 255 if code[-2] >> 16 == 0xd711 else 4 + assert evaluate(run.stdout)[dst - 4] == ref(x, y, sel, absm, neg), (hex(evaluate(run.stdout)[dst - 4]), code) + cases += 1 + # Unsupported forms are refused with a named diagnostic and no IR. + base = mov(1, a) + mov(2, b) + for words, why in [(pack(4, 257, 258, clamp=1), 'clamp or omod'), (pack(4, 257, 258, omod=1), 'clamp or omod'), + (pack(4, 257, 258, opsel=4), 'destination or third-source'), + (pack(4, 257, 258, opsel=8), 'destination or third-source'), + (pack(4, 257, 258, absm=4), 'destination or third-source'), + (pack(4, 257, 258, neg=4), 'destination or third-source'), + (pack(4, 242, 258), 'constant source'), (pack(4, 129, 258), 'constant source'), + (pack(4, 257, 255) + [0x3c00], 'constant source')]: + run = dump(dumper, work, base + words, 'refused') + assert run.returncode != 0 and 'v_pack_b32_f16' in run.stderr and why in run.stderr, (why, run.stderr) + print('pack_b32_f16 IR: %d results match the model; issue reproduction, control, overlap, SGPR and refusals ' + 'pass; swapped-half and neg-before-abs variants differ from the emitted bits' % cases) + + +def group_offsets(count): + """Word indices written by each workgroup; they must be disjoint and inside the result buffer.""" + offsets = [[BASE + group * STRIDE + i for i in range(count)] for group in range(GROUPS)] + flat = [i for group in offsets for i in group] + assert len(set(flat)) == len(flat), 'two workgroups write the same word' + assert 0 <= min(flat) and max(flat) < WORDS, 'a store falls outside the result buffer' + return offsets + + +def run_gpu(gpu, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1) + checked = 0 + for a, b in PAIRS: + # Same preamble as half_mad_readback in native_scalar_lds_check.py: s20:21 table, v8 = group * 512 bytes (STRIDE words). + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 128 + SHIFT), vmove(8, 7), sop1(3, 126, 129)] + words += mov(1, a) + mov(2, b) + want = [] + for sel in range(4): + for absm in range(4): + for neg in range(4): + # v3 is both the destination and (through the preceding move) a pre-existing value. + words += mov(3, 0x69696969) + pack(3, 257, 258, sel, absm, neg) + words += [0xe0701000 | 4 * len(want), 0x80080308] + want.append(ref(a, b, sel, absm, neg)) + # SGPR source and destination overlapping a source. + words += mov_s(9, a) + pack(3, 9, 258, 1, 1, 1) + [0xe0701000 | 4 * len(want), 0x80080308] + want.append(ref(a, b, 1, 1, 1)) + words += mov(3, a) + pack(3, 259, 258, 2, 2, 1) + [0xe0701000 | 4 * len(want), 0x80080308] + want.append(ref(a, b, 2, 2, 1)) + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + dest = work / 'pack-readback.bin' + run = subprocess.run([gpu, sdk, marker, work / 'cache', '0', dest, '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + offsets = group_offsets(len(want)) + expected = [0x69696969] * WORDS + for group in range(GROUPS): + expected[offsets[group][0]:offsets[group][-1] + 1] = want + actual = struct.unpack('<2064I', dest.read_bytes()) + bad = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y][:10] + assert not bad, (hex(a), hex(b), bad) + checked += GROUPS * len(want) + print('pack_b32_f16 GPU: %d packed words matched the model bit for bit' % checked) + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2]) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/native_packed_dot2_check.py b/tests/native_packed_dot2_check.py new file mode 100644 index 0000000000..96d9a838b9 --- /dev/null +++ b/tests/native_packed_dot2_check.py @@ -0,0 +1,136 @@ +"""Read back gfx1013 signed and unsigned 16-bit dot products in direct compute.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +INT_MIN, INT_MAX = -(1 << 31), (1 << 31) - 1 +SENTINEL, INACTIVE = 0x69696969, 0x13579BDF +CASES = ( + (0xFFFF0002, 0x0003FFFC, 13), + (0x80008000, 0x80008000, 0x80000000), # intermediate signed overflow cancels + (0x80008000, 0x80008000, 0x7FFFFFFF), # final signed positive overflow + (0x80008000, 0x7FFF7FFF, 0x80000000), # final signed negative overflow + (MASK, MASK, MASK), # unsigned total carries twice + (0x80000000, 0x80000000, 0x3FFFFFFF), # exact INT_MAX + (0x80000000, 0x7FFF0000, 0xBFFF8000), # exact INT_MIN + (0xFFFF0000, 0xFFFF0000, 0x0001FFFE), # exact UINT_MAX +) +FORMS = ((True, False), (True, True), (False, False), (False, True)) + + +def program(*, sparse=False, drop_clamp=False, low_modifier=0, high_modifier=0): + # v8 is the byte offset of this lane's 32-word output row. + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, (a, b, acc) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), a, # v_xor_b32 v1, a, v0 + 0x7E0402FF, b, 0x7E0602FF, acc] # v_mov_b32 v2, b; v_mov_b32 v3, acc + for form, (signed, clamp) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + opcode = 0x14 if signed else 0x15 + word = 0xCC004004 | (opcode << 16) | ((clamp and not drop_clamp) << 15) + operands = 0x1C000000 | (259 << 18) | (258 << 9) | 257 + code += [word ^ low_modifier, operands ^ high_modifier] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + form) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def signed_word(value, width): + return value - (1 << width) if value >> (width - 1) else value + + +def dot(a, b, acc, signed, clamp, *, early_clamp=False): + lo, hi = (INT_MIN, INT_MAX) if signed else (0, MASK) + x = (a & 65535, a >> 16) + y = (b & 65535, b >> 16) + if signed: + x = tuple(signed_word(value, 16) for value in x) + y = tuple(signed_word(value, 16) for value in y) + acc = signed_word(acc, 32) + product = x[0] * y[0] + x[1] * y[1] + if clamp and early_clamp: + product = max(lo, min(hi, product)) + total = product + acc + if clamp: + total = max(lo, min(hi, total)) + return total & MASK + + +def reference(sparse=False, drop_clamp=False): + words = [SENTINEL] * 8 + for lane in range(64): + for a, b, acc in CASES: + for signed, clamp in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + dot(a ^ (lane % 32), b, acc, signed, clamp and not drop_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for low, high in ((0, 0), (1 << 11, 0), (1 << 14, 0), (0, 1 << 27), + (1 << 8, 0), (0, 1 << 29)): + marker = request(work, root, program(low_modifier=low, high_modifier=high)) + output = marker.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if low or high: + assert run.returncode and 'packed halfword dot operand modifiers' in run.stderr, run.stderr + assert not output.exists() + else: + assert run.returncode == 0 and output.is_file(), (run.stdout, run.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'mul i32' in dump and 'add i64' not in dump, dump + assert dot(*CASES[1], True, True) == 0 + assert dot(*CASES[1], True, True, early_clamp=True) == MASK + assert (2 * 65535 ** 2 + MASK) >> 32 == 2 + print('32-bit DXIL verified; five modifier encodings refused; the exact cancellation catches early clamp') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse, drop_clamp in ((False, False), (True, False), (False, True)): + marker = request(work, root, program(sparse=sparse, drop_clamp=drop_clamp)) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + expected = reference(sparse, drop_clamp) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + for i, (word, wanted) in enumerate(zip(actual, expected)): + if word != wanted: + raise AssertionError(f'sparse={sparse} drop_clamp={drop_clamp} word {i}: ' + f'got {word:08x}, expected {wanted:08x}') + if drop_clamp: + changed = sum(word != clamped for word, clamped in zip(actual, reference())) + assert changed > 0, 'dropping clamp did not change the readback' + print(f'no-clamp control: {changed} words differed from the clamped reference') + else: + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_dot4_check.py b/tests/native_packed_dot4_check.py new file mode 100644 index 0000000000..1a48a09d46 --- /dev/null +++ b/tests/native_packed_dot4_check.py @@ -0,0 +1,130 @@ +"""Direct compute signed/unsigned VOP3P byte dot products and accumulator saturation.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF +CASES = ( + (0x01020304, 0x02050813, 29), + (0x80808080, 0x80808080, 0x7FFFFFF0), # signed positive overflow + (0x80808080, 0x7F7F7F7F, 0x80000010), # signed negative overflow + (MASK, MASK, 0xFFFFFFF0), # unsigned carry + (0xFF80FE7F, 0x7F1002FE, 0x80010001), + (0x80000000, 0x80000000, 0x7FFFBFFF), # exact signed upper boundary at lane 0 + (0x80000000, 0x7F000000, 0x80003F80), # exact signed lower boundary at lane 0 + (0x00000080, 0xFFFFFF00, MASK), # exact unsigned upper boundary +) +FORMS = ((True, False), (True, True), (False, False), (False, True)) + + +def program(*, sparse=False, drop_clamp=False, first_modifier=0, second_modifier=0): + # Group index and local lane identify a 32-word row. + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, (a, b, acc) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), a, # v_xor_b32 v1, a, v0 + 0x7E0402FF, b, 0x7E0602FF, acc] # v_mov_b32 v2, b; v_mov_b32 v3, acc + for mode, (signed, clamp) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + opcode = 0x16 if signed else 0x17 + word = 0xCC004004 | (opcode << 16) | ((clamp and not drop_clamp) << 15) + operands = 0x1C000000 | (259 << 18) | (258 << 9) | 257 + code += [word ^ first_modifier, operands ^ second_modifier] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def as_signed(value, width): + return value - (1 << width) if value >> (width - 1) else value + + +def dot(a, b, acc, signed, clamp): + total = as_signed(acc, 32) if signed else acc + for shift in range(0, 32, 8): + x, y = (a >> shift) & 255, (b >> shift) & 255 + total += as_signed(x, 8) * as_signed(y, 8) if signed else x * y + if clamp: + lo, hi = (-(1 << 31), (1 << 31) - 1) if signed else (0, MASK) + total = max(lo, min(hi, total)) + return total & MASK + + +def reference(sparse=False, ignore_clamp=False): + words = [SENTINEL] * 8 + for lane in range(64): + for a, b, acc in CASES: + for signed, clamp in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + dot(a ^ (lane % 32), b, acc, signed, clamp and not ignore_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for first, second in ((0, 0), (1 << 11, 0), (1 << 14, 0), (0, 1 << 27), + (1 << 8, 0), (0, 1 << 29)): + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and 'packed byte dot operand modifiers' in result.stderr, result.stderr + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + for opcode in (163, 164): + assert dump.count(f'@dx.op.dot4AddPacked.i32(i32 {opcode},') == 2 * len(CASES), dump + assert reference() != reference(ignore_clamp=True) + assert reference() != reference(sparse=True) + print('signed/unsigned dot4 DXIL verified; five modifier encodings refused; clamp and EXEC controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse, drop_clamp in ((False, False), (True, False), (False, True)): + marker = request(work, root, program(sparse=sparse, drop_clamp=drop_clamp)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse, ignore_clamp=drop_clamp) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} drop_clamp={drop_clamp} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + if drop_clamp: + changed = sum(a != b for a, b in zip(actual, reference())) + assert changed > 0, 'dropping clamp did not change the readback' + print(f'no-clamp control: {changed} words differed from the clamped reference') + else: + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_dot8_check.py b/tests/native_packed_dot8_check.py new file mode 100644 index 0000000000..cae6a1f63f --- /dev/null +++ b/tests/native_packed_dot8_check.py @@ -0,0 +1,130 @@ +"""Direct compute signed/unsigned VOP3P 4-bit nibble dot products and accumulator saturation.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF +CASES = ( + (0x01234567, 0x01234567, 29), + (0x88888888, 0x88888888, 0x7FFFFF00), # signed positive overflow (+512) + (0x88888888, 0x77777777, 0x80000100), # signed negative overflow (-448) + (MASK, MASK, 0xFFFFFF00), # unsigned carry (+1800) + (0xF8E7D6C5, 0x7102F384, 0x80010001), + (0x80000000, 0x80000000, 0x7FFFFFBF), # exact signed upper boundary at lane 0 + (0x80000000, 0x70000000, 0x80000038), # exact signed lower boundary at lane 0 + (0x00000008, 0xFFFFFFF0, MASK), # exact unsigned upper boundary +) +FORMS = ((True, False), (True, True), (False, False), (False, True)) + + +def program(*, sparse=False, drop_clamp=False, first_modifier=0, second_modifier=0): + # Group index and local lane identify a 32-word row. + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, (a, b, acc) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), a, # v_xor_b32 v1, a, v0 + 0x7E0402FF, b, 0x7E0602FF, acc] # v_mov_b32 v2, b; v_mov_b32 v3, acc + for mode, (signed, clamp) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + opcode = 0x18 if signed else 0x19 + word = 0xCC004004 | (opcode << 16) | ((clamp and not drop_clamp) << 15) + operands = 0x1C000000 | (259 << 18) | (258 << 9) | 257 + code += [word ^ first_modifier, operands ^ second_modifier] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def as_signed(value, width): + return value - (1 << width) if value >> (width - 1) else value + + +def dot(a, b, acc, signed, clamp): + total = as_signed(acc, 32) if signed else acc + for shift in range(0, 32, 4): + x, y = (a >> shift) & 15, (b >> shift) & 15 + total += as_signed(x, 4) * as_signed(y, 4) if signed else x * y + if clamp: + lo, hi = (-(1 << 31), (1 << 31) - 1) if signed else (0, MASK) + total = max(lo, min(hi, total)) + return total & MASK + + +def reference(sparse=False, ignore_clamp=False): + words = [SENTINEL] * 8 + for lane in range(64): + for a, b, acc in CASES: + for signed, clamp in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + dot(a ^ (lane % 32), b, acc, signed, clamp and not ignore_clamp)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for first, second in ((0, 0), (1 << 11, 0), (1 << 14, 0), (0, 1 << 27), + (1 << 8, 0), (0, 1 << 29)): + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and 'packed nibble dot operand modifiers' in result.stderr, result.stderr + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'ashr i32 ' in dump and ', 28' in dump, dump + assert 'and i32 ' in dump and ', 15' in dump, dump + assert reference() != reference(ignore_clamp=True) + assert reference() != reference(sparse=True) + print('signed/unsigned dot8 DXIL verified; five modifier encodings refused; clamp and EXEC controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse, drop_clamp in ((False, False), (True, False), (False, True)): + marker = request(work, root, program(sparse=sparse, drop_clamp=drop_clamp)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse, ignore_clamp=drop_clamp) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} drop_clamp={drop_clamp} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + if drop_clamp: + changed = sum(a != b for a, b in zip(actual, reference())) + assert changed > 0, 'dropping clamp did not change the readback' + print(f'no-clamp control: {changed} words differed from the clamped reference') + else: + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_dot8_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_f16_check.py b/tests/native_packed_f16_check.py new file mode 100644 index 0000000000..4bfd8e1a7d --- /dev/null +++ b/tests/native_packed_f16_check.py @@ -0,0 +1,216 @@ +"""Run direct packed binary16 arithmetic against an exact-rational reference.""" +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import h2f, half_op, round_exact +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OPS = {'add': 0x0f, 'mul': 0x10, 'fma': 0x0e} +GUARD = 0x69696969 +INACTIVE = 0x13579bdf +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + + +@dataclass(frozen=True) +class Case: + a: int + b: int + c: int + low: int = 0 + high: int = 7 + neg_lo: int = 0 + neg_hi: int = 0 + + @property + def inputs(self): + return self.a, self.b, self.c + + +CASES = ( + # Both products are binary16 midpoints. A minimum subnormal addend + # changes the exact rounded result but vanishes on a binary32 tie. + Case(0x3c033c01, 0x3e003e00, 0x00018001), + Case(0x6001bc01, 0x3e003e00, 0x80010001), + Case(0x04000001, 0x38003800, 0x03ff0000), + Case(0x7bfffbff, 0x40004000, 0x80000000), + Case(0xbc003c00, 0x3c003c00, 0x3c00bc00), + Case(0x80008000, 0xbc003c00, 0x80008000), + Case(0x7c00fc00, 0x00003c00, 0x3c007c00), + Case(0x7d017e01, 0x3c003c00, 0x3c003c00), + Case(0x42003c00, 0xc4004000, 0x4400c000, low=5, high=2, neg_lo=1, neg_hi=6), + Case(0x00018001, 0x35553c00, 0x7bff83ff, low=3, high=4, neg_lo=2, neg_hi=1), +) + + +def packed_instruction(name, dst, case, bad=0): + active = 7 if name == 'fma' else 3 + # Set the conventional high selector for the unused third source. + high = case.high if name == 'fma' else case.high | 4 + word0 = (0xcc000000 | OPS[name] << 16 | dst | (case.low & active) << 11 | + (high & 4) << 12 | (case.neg_hi & active) << 8 | bad) + last = 259 if name == 'fma' else 0 + word1 = 257 | 258 << 9 | last << 18 | (high & 3) << 27 | (case.neg_lo & active) << 29 + return [word0, word1] + + +def moves(case): + return [word for index, value in enumerate(case.inputs, 1) for word in (0x7e0002ff | index << 17, value)] + + +def compute_program(cases, *, sparse=False, bad=0, mode=()): + code = PROLOGUE + list(mode) + for slot, case in enumerate(cases): + code += moves(case) + for j, op in enumerate(OPS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + code += packed_instruction(op, 4, case, bad) + if sparse: + code.append(sop1(3, 126, 193)) + code += [0xE0701000 | (slot * len(OPS) + j) * 4, 0x80080408] + return code + [0xBF810000] + + +def root_signature(sdk, work): + hlsl = work / 'root.hlsl' + hlsl.write_text('#define RS "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', root, hlsl], check=True) + return root.read_bytes() + + +def compile_shader(cli, sdk, work, profile, source): + output = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', profile, source, output], + capture_output=True, text=True, timeout=30) + return output, run + + +def controls(cli, sdk, work): + root = root_signature(sdk, work) + source = request(work, root, compute_program(CASES[:1])) + output, run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', source) + assert run.returncode == 0 and output.is_file(), run.stdout + run.stderr + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], check=True, + capture_output=True, text=True).stdout + assert 'fadd float' in dump and 'fmul float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + clamped_source = request(work, root, compute_program(CASES[:1], bad=0x8000)) + clamped_output, clamped_run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', clamped_source) + assert clamped_run.returncode == 0 and clamped_output.is_file(), clamped_run.stdout + clamped_run.stderr + for options, message in ( + ({'bad': 0x0400}, 'packed binary16 arithmetic encoding'), + ({'bad': 0x2000}, 'packed binary16 arithmetic encoding'), + ({'mode': (0xBFA50003,)}, 'binary16 rounding or denormal mode'), + ({'mode': (0xBFA40004,)}, 'binary16 rounding or denormal mode'), + ): + source = request(work, root, compute_program(CASES[:1], **options)) + _, run = compile_shader(cli, sdk, work, 'gfx1013-direct-cs@0', source) + assert run.returncode and message in run.stderr, (options, run.stderr) + print('ADD/MUL and integer FMA compiled (including clamp); unsupported modifiers and modes were refused') + + +def operands(case, high): + selected = case.high if high else case.low + neg = case.neg_hi if high else case.neg_lo + return tuple(((word >> (16 * ((selected >> i) & 1))) & 0xffff) ^ (((neg >> i) & 1) << 15) + for i, word in enumerate(case.inputs)) + + +def expected(case, op): + low, high = (half_op(op, *operands(case, h)) for h in (False, True)) + return low | high << 16 + + +def double_rounded(case): + def lane(high): + a, b, c = map(h2f, operands(case, high)) + rounded_f32, = struct.unpack('<f', struct.pack('<f', a * b + c)) + return round_exact(Fraction(rounded_f32)) + return lane(False) | lane(True) << 16 + + +def replay(tool, sdk, work, root, cases, sparse=False): + source = request(work, root, compute_program(cases, sparse=sparse)) + output = work / 'readback.bin' + run = subprocess.run([tool, sdk, source, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + raise SystemExit(77) + run.check_returncode() + return struct.unpack('<2064I', output.read_bytes()) + + +def verify_compute(tool, sdk, work, root, cases=CASES, sparse=False): + values = [expected(case, op) for case in cases for op in OPS] + unused = [GUARD] * (32 - len(values)) + inactive = [INACTIVE] * len(values) if sparse else values + pair = values + unused + inactive + unused + want = (GUARD,) * 8 + tuple(pair * 32) + (GUARD,) * 8 + actual = replay(tool, sdk, work, root, cases, sparse) + mismatch = next((i for i, (x, y) in enumerate(zip(actual, want, strict=True)) if x != y), None) + assert mismatch is None, (mismatch, hex(actual[mismatch]), hex(want[mismatch])) + return actual + + +def draw_compute(tool, sdk, work): + root = root_signature(sdk, work) + values = verify_compute(tool, sdk, work, root) + verify_compute(tool, sdk, work, root, sparse=True) + for i in (0, 1): + offset = 8 + i * 3 + 2 + assert values[offset] == expected(CASES[i], 'fma') and values[offset] != double_rounded(CASES[i]) + print(f'FMA case {i}: exact {values[offset]:08x}, binary32 intermediate {double_rounded(CASES[i]):08x}') + print('2064 words matched in each full and sparse EXEC dispatch') + + +def pixel_program(case, other_op): + code = moves(case) + for i, op in enumerate(('fma', other_op)): + result, low, high = 4 + i, 8 + 2 * i, 9 + 2 * i + code += packed_instruction(op, result, case) + code += [vop2(0x1b, low, 255, result), 65535, vop2(0x16, high, 144, result)] + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (low, high)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def draw_pixel(tool, sdk, renderer, adapter, work): + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + for index, case in enumerate(CASES): + other_op = 'add' if index % 2 == 0 else 'mul' + shader = work / f'packed-{index}.ps' + shader.write_bytes(pixel_program(case, other_op)) + cso, build = compile_shader(tool, sdk, work, 'gfx1013-container-ps', shader) + assert build.returncode == 0, build.stdout + build.stderr + fused, other = expected(case, 'fma'), expected(case, other_op) + reference = work / 'expected.bin' + reference.write_bytes(struct.pack('<4f', fused & 0xffff, fused >> 16, other & 0xffff, other >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', reference], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + raise SystemExit(77) + assert run.returncode == 0, (index, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{len(CASES)} Pixel readbacks matched, including both exact FMA tie cases') + + +if __name__ == '__main__': + mode, tool, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + if mode == 'controls': + controls(tool, sdk, work) + elif mode == 'compute': + draw_compute(tool, sdk, work) + elif mode == 'pixel': + draw_pixel(tool, sdk, *args, work) + else: + raise ValueError(mode) diff --git a/tests/native_packed_f16_clamp_check.py b/tests/native_packed_f16_clamp_check.py new file mode 100644 index 0000000000..70663247cc --- /dev/null +++ b/tests/native_packed_f16_clamp_check.py @@ -0,0 +1,292 @@ +"""Direct DXIL VOP3P clamp on v_pk_add_f16, v_pk_mul_f16, and v_pk_fma_f16 in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import half_op +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word, vop3p +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +ALL_EXEC = 0xFFFFFFFF +DST_INIT = 0xDEADCAFE + + +def clamp_f16(bits): + bits &= 0xFFFF + if (bits & 0x7FFF) > 0x7C00 or (bits & 0x8000): + return 0x0000 + return 0x3C00 if bits > 0x3BFF else bits + + +def eval_clamp_case(op_name, raw_words, op_sel, op_sel_hi, neg_lo, neg_hi, clamp): + arity = 3 if op_name == 'fma' else 2 + + def lane_eval(high): + sel = op_sel_hi if high else op_sel + neg = neg_hi if high else neg_lo + ops = [] + for j in range(arity): + half = (raw_words[j] >> (16 if ((sel >> j) & 1) else 0)) & 0xFFFF + if (neg >> j) & 1: + half ^= 0x8000 + ops.append(half) + res = half_op(op_name, *ops) + return clamp_f16(res) if clamp else res + + return lane_eval(False) | (lane_eval(True) << 16) + + +@dataclass(frozen=True) +class Case: + name: str + op: str + srcs: tuple + vals: tuple + op_sel: int = 0 + op_sel_hi: int = 7 + neg_lo: int = 0 + neg_hi: int = 0 + clamp: int = 1 + exec_mask: int = ALL_EXEC + + def raw_words(self): + return tuple(v & 0xFFFFFFFF if (s < 128 or s >= 255) else inline_word(s) + for s, v in zip(self.srcs, self.vals)) + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return DST_INIT + return eval_clamp_case(self.op, self.raw_words(), self.op_sel, self.op_sel_hi, + self.neg_lo, self.neg_hi, self.clamp) + + +def all_cases(): + return [ + # 1. v_pk_add_f16: negative finite, -0.0, subnormals, interior (0,1), >= 1.0, +/-Inf, NaN, and unclamped contrast. + Case('add_neg_and_over_one', 'add', (257, 258), ((0x4000 << 16) | 0xBC00, (0x3800 << 16) | 0xB800)), + Case('add_neg_zero_and_lt_one', 'add', (257, 258), ((0x3BFF << 16) | 0x8000, (0x0000 << 16) | 0x8000)), + Case('add_subnormals_exact_one', 'add', (257, 258), ((0x3800 << 16) | 0x0001, (0x3800 << 16) | 0x0000)), + Case('add_pos_inf_and_nan', 'add', (257, 258), ((0x7C00 << 16) | 0x7E01, (0x3C00 << 16) | 0x3C00)), + Case('add_neg_inf_and_inf_minus_inf', 'add', (257, 258), ((0xFC00 << 16) | 0x7C00, (0x3C00 << 16) | 0xFC00)), + Case('add_unclamped_contrast', 'add', (257, 258), ((0x7C00 << 16) | 0xBC00, (0x3C00 << 16) | 0xB800), clamp=0), + # 2. v_pk_mul_f16: subnormal normal-product, -0.0, interior, overflow/+Inf -> 1.0, -Inf/Inf*0 NaN -> +0.0. + Case('mul_subnormal_and_neg_zero', 'mul', (257, 258), ((0x0400 << 16) | 0x8000, (0x3800 << 16) | 0x3C00)), + Case('mul_overflow_and_interior', 'mul', (257, 258), ((0x7BFF << 16) | 0x3800, (0x4000 << 16) | 0x3800)), + Case('mul_neg_inf_and_inf_times_zero', 'mul', (257, 258), ((0xFC00 << 16) | 0x7C00, (0x3C00 << 16) | 0x0000)), + Case('mul_neg_finite_and_max_subnormal', 'mul', (257, 258), ((0xBC00 << 16) | 0x03FF, (0x3800 << 16) | 0x3C00)), + # 3. v_pk_fma_f16: negative/-0, subnormals, exact 1.0, 0x3BFF edge, overflow avoidance, +/-Inf, Inf*0 NaN. + Case('fma_neg_and_over_one', 'fma', (257, 258, 259), + ((0x4000 << 16) | 0xBC00, (0x4000 << 16) | 0x3C00, (0x0000 << 16) | 0x3800)), + Case('fma_subnormal_and_exact_one', 'fma', (257, 258, 259), + ((0x3800 << 16) | 0x3800, (0x0400 << 16) | 0x3800, (0x0001 << 16) | 0x3A00)), + Case('fma_near_one_and_overflow_avoid', 'fma', (257, 258, 259), + ((0x7BFF << 16) | 0x3800, (0x4000 << 16) | 0x4000, (0xFBFF << 16) | 0x9000)), + Case('fma_nan_and_inf_zero', 'fma', (257, 258, 259), + ((0x7E01 << 16) | 0x7C00, (0x3C00 << 16) | 0x0000, (0x3C00 << 16) | 0x3C00)), + Case('fma_neg_zero_and_neg_inf', 'fma', (257, 258, 259), + ((0x8000 << 16) | 0xFC00, (0x3C00 << 16) | 0x3C00, (0x8000 << 16) | 0x0000)), + # 4. VOP3P selectors (op_sel / op_sel_hi) + neg_lo / neg_hi combined with clamp. + Case('add_opsel_neg_clamp', 'add', (257, 258), + ((0x3800 << 16) | 0x4000, (0x3C00 << 16) | 0xBC00), op_sel=0b01, op_sel_hi=0b10, neg_lo=0b10, neg_hi=0b01), + Case('mul_opsel_neg_clamp', 'mul', (257, 258), + ((0x3800 << 16) | 0xC000, (0x4000 << 16) | 0x3C00), op_sel=0b10, op_sel_hi=0b01, neg_lo=0b01, neg_hi=0b10), + Case('fma_opsel_neg_clamp', 'fma', (257, 258, 259), + ((0x3800 << 16) | 0x4000, (0x4000 << 16) | 0x3800, (0xBC00 << 16) | 0x3400), + op_sel=0b101, op_sel_hi=0b010, neg_lo=0b100, neg_hi=0b011), + # 5. SGPR, literal (255), inline f16 float (242/243/240), inline int (193 NaN -> +0.0 under clamp). + Case('add_sgpr_literal_clamp', 'add', (10, 255), ((0x4000 << 16) | 0xBC00, (0x3800 << 16) | 0x3800)), + Case('mul_inline_242_243_clamp', 'mul', (257, 243), ((0x3800 << 16) | 0xBC00, 0), + op_sel=0, op_sel_hi=0b101, neg_lo=0b10), + Case('fma_inline_int_193_nan_clamp', 'fma', (257, 240, 193), ((0x4000 << 16) | 0x3C00, 0, 0), + op_sel=0, op_sel_hi=0b101), + # 6. Partial EXEC_LO mask: inactive lanes keep DST_INIT. + Case('fma_partial_exec_clamp', 'fma', (257, 258, 259), + ((0x4000 << 16) | 0xBC00, (0x3C00 << 16) | 0x3C00, (0x0000 << 16) | 0x0000), + exec_mask=0xAAAAAAAA), + ] + + +def emit_case(c: Case): + code = F.mov(4, DST_INIT) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + lit_tail = [] + for s, v in zip(c.srcs, c.vals): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3p(c.op, 4, c.srcs, op_sel=c.op_sel, op_sel_hi=c.op_sel_hi, + neg_lo=c.neg_lo, neg_hi=c.neg_hi, clamp=c.clamp) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + assert len(cases) <= 32, len(cases) + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + clamped_add = vop3p('add', 4, (257, 258), clamp=1) + [0xBF810000] + add_bad_src2 = vop3p('add', 4, (257, 258), clamp=1) + add_bad_src2[1] |= 259 << 18 + fmac_e64_clamp = [0xD53C8004, (258 << 9) | 257] # VOP3 e64 v_pk_fmac_f16 with clamp=1 + return [ + # Unused third-operand fields and VOP3 e64 v_pk_fmac_f16 clamp refused. + (add_bad_src2 + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (fmac_e64_clamp + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (vop3p('mul', 4, (257, 258), op_sel=4, clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (vop3p('add', 4, (257, 258), neg_lo=4, clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + (vop3p('mul', 4, (257, 258), neg_hi=4, clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + # Special scalar source refused. + (vop3p('fma', 4, (257, 106, 259), clamp=1) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + # Unsupported binary16 rounding/denormal modes and dynamic conditional MODE write. + ([0xBFA40004] + clamped_add, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + clamped_add, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + clamped_add, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'packed-f16-clamp') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_packed_f16_clamp IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'fadd float' in dump and 'fmul float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_packed_f16_clamp controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if got != expected[i]: + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_packed_f16_clamp compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(pair): + code = [] + for idx, c in enumerate(pair): + code += emit_case(c) + lo_reg, hi_reg = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo_reg, 255, 4), 65535, vop2(0x16, hi_reg, 144, 4)] + # Each 16-bit half is exactly representable in binary32 as an integer in 0..65535. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo_reg, hi_reg)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.exec_mask == ALL_EXEC] + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [items[i:i + 2] for i in range(0, len(items), 2)] + for idx, pair in enumerate(pairs): + shader = work / f'packed-f16-clamp-{idx}.ps' + shader.write_bytes(pixel_program(pair)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in pair], build.stdout, build.stderr) + w0, w1 = pair[0].expected(), pair[1].expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', w0 & 0xFFFF, w0 >> 16, w1 & 0xFFFF, w1 >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in pair], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_packed_f16_clamp pixel ({adapter}): {len(pairs)} pixel draws ({len(items)} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_f16_inline_check.py b/tests/native_packed_f16_inline_check.py new file mode 100644 index 0000000000..df66932ff7 --- /dev/null +++ b/tests/native_packed_f16_inline_check.py @@ -0,0 +1,328 @@ +"""Direct DXIL packed binary16 arithmetic and min/max with inline constant sources.""" +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import half_op +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + + +OPS_3SRC = {'fma': 0x0e} +OPS_2SRC = {'add': 0x0f, 'mul': 0x10, 'min_f16': 0x11, 'max_f16': 0x12, 'min_u16': 0x0d, 'max_i16': 0x07} +OPS = {**OPS_3SRC, **OPS_2SRC} + +INLINE_F16_WORDS = { + 240: 0x3800, 241: 0xB800, 242: 0x3C00, 243: 0xBC00, + 244: 0x4000, 245: 0xC000, 246: 0x4400, 247: 0xC400, + 248: 0x3118, +} + +GUARD = 0x69696969 +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + + +def inline_word(enc): + if enc in INLINE_F16_WORDS: + return INLINE_F16_WORDS[enc] + if 128 <= enc <= 192: + return enc - 128 + if 193 <= enc <= 208: + return (192 - enc) & 0xFFFFFFFF + raise ValueError(enc) + + +def vop3p(op_name, dst, srcs, *, op_sel=0, op_sel_hi=7, neg_lo=0, neg_hi=0, clamp=0): + arity = 3 if op_name in OPS_3SRC else 2 + s0, s1 = srcs[0], srcs[1] + s2 = srcs[2] if arity == 3 else 0 + # Default op_sel_hi[2]=1 for 2-src instructions (LLVM MC convention). + hi2 = (op_sel_hi >> 2) & 1 if arity == 3 else 1 + w0 = (0xCC000000 | (OPS[op_name] << 16) | ((clamp & 1) << 15) | + (hi2 << 14) | ((op_sel & 7) << 11) | ((neg_hi & 7) << 8) | (dst & 0xFF)) + w1 = ((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) | ((s2 & 0x1FF) << 18) | ((s1 & 0x1FF) << 9) | (s0 & 0x1FF) + return [w0, w1] + + +def f16_key(bits): + bits &= 0xFFFF + return (bits ^ 0xFFFF) if (bits & 0x8000) else (bits ^ 0x8000) + + +def f16_minmax(a, b, is_max): + a &= 0xFFFF + b &= 0xFFFF + a_nan = (a & 0x7FFF) > 0x7C00 + b_nan = (b & 0x7FFF) > 0x7C00 + if a_nan and b_nan: + return 0x7E00 + if a_nan: + return b + if b_nan: + return a + ka, kb = f16_key(a), f16_key(b) + return (a if ka > kb else b) if is_max else (a if ka < kb else b) + + +def int16_minmax(a, b, is_max, signed): + a &= 0xFFFF + b &= 0xFFFF + if signed: + sa = a - 0x10000 if (a & 0x8000) else a + sb = b - 0x10000 if (b & 0x8000) else b + return (a if sa > sb else b) if is_max else (a if sa < sb else b) + return (a if a > b else b) if is_max else (a if a < b else b) + + +def eval_case(op_name, raw_words, op_sel, op_sel_hi, neg_lo, neg_hi): + arity = 3 if op_name in OPS_3SRC else 2 + + def lane_eval(high): + sel = op_sel_hi if high else op_sel + neg = neg_hi if high else neg_lo + ops = [] + for j in range(arity): + half = (raw_words[j] >> (16 if ((sel >> j) & 1) else 0)) & 0xFFFF + if (neg >> j) & 1: + half ^= 0x8000 + ops.append(half) + if op_name in ('add', 'mul', 'fma'): + return half_op(op_name, *ops) + if op_name == 'min_f16': + return f16_minmax(ops[0], ops[1], False) + if op_name == 'max_f16': + return f16_minmax(ops[0], ops[1], True) + if op_name == 'min_u16': + return int16_minmax(ops[0], ops[1], False, False) + if op_name == 'max_i16': + return int16_minmax(ops[0], ops[1], True, True) + raise ValueError(op_name) + + return lane_eval(False) | (lane_eval(True) << 16) + + +@dataclass(frozen=True) +class Case: + name: str + op: str + srcs: tuple # encoding per operand (>=256 for VGPR v[idx-256], <=105 for SGPR, 128..208/240..248 inline, 255 literal) + vals: tuple # 32-bit raw value per operand (ignored for inline; used for VGPR/SGPR/literal) + op_sel: int = 0 + op_sel_hi: int = 7 + neg_lo: int = 0 + neg_hi: int = 0 + + def raw_words(self): + return tuple(inline_word(s) if 128 <= s < 255 else v for s, v in zip(self.srcs, self.vals)) + + def expected(self): + return eval_case(self.op, self.raw_words(), self.op_sel, self.op_sel_hi, self.neg_lo, self.neg_hi) + + +def all_cases(): + items = [] + # 1. All 9 inline binary16 float constants (240..248) broadcast to both lanes via op_sel=0, op_sel_hi=0. + base_vec = (0x4200 << 16) | 0x3E00 # hi=3.0, lo=1.5 + for enc in range(240, 249): + items.append(Case(f'mul_inline_{enc}_broadcast', 'mul', (257, enc), (base_vec, 0), op_sel=0, op_sel_hi=0b101)) + # 2. gfx1013 high-half zeroing on inline float constants (op_sel_hi selects bit 1 -> reads +0.0 = 0x0000). + items.append(Case('add_inline_242_hi_zero', 'add', (257, 242), ((0x4000 << 16) | 0x3C00, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('mul_inline_244_lo_hi_zero', 'mul', (244, 257), (0, (0x4200 << 16) | 0x3C00), op_sel=0b001, op_sel_hi=0b111)) + # 3. neg_lo and neg_hi on inline float constants (including negating zeroed high half -> -0.0 = 0x8000). + items.append(Case('add_inline_242_neg_hi_zero', 'add', (257, 242), ((0x8000 << 16) | 0x3C00, 0), + op_sel=0, op_sel_hi=0b111, neg_lo=0b10, neg_hi=0b10)) + items.append(Case('mul_inline_240_neg_broadcast', 'mul', (257, 240), ((0x4400 << 16) | 0x4000, 0), + op_sel=0, op_sel_hi=0b101, neg_lo=0b10, neg_hi=0b10)) + # 4. Single-rounding FMA tie witness with inline float 240 (0.5) and inline int 129 (0x0001 = 2^-24). + # Low lane: (1 + 2^-10) * 0.5 + 2^-24 -> 0x3801 (double-rounded f32 product would give 0x3800). + # High lane: (1 + 3*2^-10) * 0.5 + 0 -> 0x3802. + items.append(Case('fma_inline_tie_pos', 'fma', (257, 240, 129), ((0x3C03 << 16) | 0x3C01, 0, 0), + op_sel=0, op_sel_hi=0b101)) + # Negative tie witness using neg_lo/neg_hi on inline 240 and inline 129 in src2 + SGPR src0. + items.append(Case('fma_inline_src0_242_src2_241', 'fma', (242, 257, 241), (0, (0x4000 << 16) | 0x3C00, 0), + op_sel=0, op_sel_hi=0b010)) + # 5. Inline integer constants: 128 (0), 129 (1=0x00000001), 192 (64=0x00000040), + # 193 (-1=0xffffffff -> NaN in both halves), 208 (-16=0xfffffff0 -> NaN hi, fff0=NaN lo). + items.append(Case('add_inline_int_192', 'add', (257, 192), ((0x4000 << 16) | 0x3C00, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('fma_inline_int_193_nan', 'fma', (257, 242, 193), ((0x4000 << 16) | 0x3C00, 0, 0), + op_sel=0, op_sel_hi=0b101)) + items.append(Case('add_inline_int_208_nan', 'add', (257, 208), ((0x4000 << 16) | 0x3C00, 0), op_sel=0, op_sel_hi=0b111)) + # 6. Packed f16 min/max with inline float constants (242, 243, 244, high-half zeroing, and 193 NaN selecting numeric). + items.append(Case('min_f16_inline_242_broadcast', 'min_f16', (257, 242), ((0x4000 << 16) | 0x3800, 0), op_sel=0, op_sel_hi=0b101)) + items.append(Case('max_f16_inline_243_hi_zero', 'max_f16', (257, 243), ((0x8000 << 16) | 0xBC00, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('min_f16_inline_193_nan', 'min_f16', (193, 257), (0, (0x4000 << 16) | 0x3C00), op_sel=0, op_sel_hi=0b111)) + items.append(Case('max_f16_inline_248_sgpr', 'max_f16', (10, 248), ((0x3400 << 16) | 0x3000, 0), op_sel=0, op_sel_hi=0b101)) + # 7. Packed integer min/max with inline integers (128, 129, 192, 193=-1, 208=-16). + items.append(Case('min_u16_inline_192', 'min_u16', (257, 192), ((0x0010 << 16) | 0x0050, 0), op_sel=0, op_sel_hi=0b111)) + items.append(Case('max_i16_inline_193_208', 'max_i16', (193, 208), (0, 0), op_sel=0, op_sel_hi=0b111)) + return items + + +def emit_case(c: Case): + code = [] + lit_tail = [] + for idx, (s, v) in enumerate(zip(c.srcs, c.vals)): + if s >= 256: + code += F.mov(s - 256, v) + elif s <= 105: + code += F.smov(s, v) + elif s == 255: + lit_tail = [v] + code += vop3p(c.op, 4, c.srcs, op_sel=c.op_sel, op_sel_hi=c.op_sel_hi, neg_lo=c.neg_lo, neg_hi=c.neg_hi) + code += lit_tail + return code + + +def compute_program(cases): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + return [ + # Special scalar sources refused in packed_f16_alu + (vop3p('add', 4, (257, 106)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + (vop3p('mul', 4, (124, 257)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + (vop3p('fma', 4, (257, 242, 126)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + (vop3p('fma', 4, (257, 242, 253)) + [0xBF810000], 'unsupported packed binary16 arithmetic source'), + # Special scalar sources refused in packed_minmax + (vop3p('min_f16', 4, (257, 106)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + (vop3p('max_f16', 4, (124, 257)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + (vop3p('min_f16', 4, (257, 253)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + # Float inline constants refused on integer packed min/max + (vop3p('min_u16', 4, (257, 242)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + (vop3p('max_i16', 4, (240, 257)) + [0xBF810000], 'unsupported packed 16-bit min/max source'), + # Unused third-source modifier refused on 2-source VOP3P add + (vop3p('add', 4, (257, 242), neg_lo=4) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + ] + + +def ir(dumper): + items = all_cases() + code, want = compute_program(items) + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'packed-f16-inline') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if got != exp] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_packed_f16_inline IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'fmul float' in dump and 'fadd float' in dump and '@dx.op.unaryBits.i32(i32 33,' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_packed_f16_inline controls: compiled {len(want)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = [F.SENTINEL] * F.WORDS + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + expected[head:head + len(want)] = want + mismatch = next((i for i, (a, b) in enumerate(zip(words_out, expected, strict=True)) if a != b), None) + assert mismatch is None, (mismatch, hex(words_out[mismatch]), hex(expected[mismatch])) + print(f'native_packed_f16_inline compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(case_a: Case, case_b: Case): + code = [] + for idx, c in enumerate((case_a, case_b)): + code += emit_case(c) + lo, hi = 8 + 2 * idx, 9 + 2 * idx + code += [vop2(0x1B, lo, 255, 4), 65535, vop2(0x16, hi, 144, 4)] + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (lo, hi)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = all_cases() + if len(items) % 2: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + pairs = [(items[i], items[i + 1]) for i in range(0, len(items), 2)] + for idx, (ca, cb) in enumerate(pairs): + shader = work / f'inline-{idx}.ps' + shader.write_bytes(pixel_program(ca, cb)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, (ca.name, cb.name, build.stdout, build.stderr) + ea, eb = ca.expected(), cb.expected() + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4f', ea & 0xFFFF, ea >> 16, eb & 0xFFFF, eb >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, ca.name, cb.name, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_packed_f16_inline pixel ({adapter}): {len(pairs)} paired draws ({len(all_cases())} cases) matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_packed_minmax_check.py b/tests/native_packed_minmax_check.py new file mode 100644 index 0000000000..cc4607e44c --- /dev/null +++ b/tests/native_packed_minmax_check.py @@ -0,0 +1,258 @@ +"""Source-built direct DXIL checks for the six packed 16-bit min/max opcodes.""" +import math +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OPS = {'i16': (8, 7), 'u16': (13, 12), 'f16': (17, 18)} +CASES = ( + (0x00008000, 0x80000000, 0, 3), + (0x8000FFFF, 0x7FFF0001, 1, 2), + (0x7E013C00, 0x4000FE00, 0, 3), + (0x7C010001, 0xFE7F8001, 0, 3), + (0xFC007C00, 0x7BFFFBFF, 3, 0), + (0x80010000, 0x00017C00, 2, 1), + (0xFFFF0000, 0x0000FFFF, 0, 3), + (0x4400C000, 0x3C003800, 1, 1), + (0x00000000, 0x00018000, 3, 2), +) +MOD_CASES = ( + # a, b, op_sel, op_sel_hi, neg_lo, neg_hi, clamp + (0x38004000, 0x3C00BC00, 0, 3, 1, 2, 0), # neg_lo[0] vs neg_hi[1] asymmetric + (0xC0000001, 0x80003C00, 1, 2, 2, 1, 0), # neg_lo[1] vs neg_hi[0] cross-lane + (0x00008000, 0x80000000, 0, 3, 3, 0, 0), # neg_lo both (+/-0) without neg_hi + (0x7C007E01, 0xFC003800, 0, 3, 0, 3, 0), # neg_hi both (+/-Inf, NaN payload) + (0x8000C000, 0x3C000000, 0, 3, 0, 0, 1), # clamp -2.0 -> +0.0 and -0.0 -> +0.0 + (0x00013800, 0x3C000000, 0, 3, 0, 0, 1), # clamp preserves positive subnormal 0x0001 and 0.5..1.0 + (0x7C004000, 0xFC000000, 0, 3, 0, 0, 1), # clamp >1.0 / +Inf -> 1.0, -Inf -> +0.0 + (0x7E013800, 0x7E027BFF, 0, 3, 0, 0, 1), # clamp both-NaN -> +0.0, one-NaN picks numeric -> clamp + (0x3800B800, 0xC0004000, 0, 3, 3, 2, 1), # combined neg_lo + neg_hi + clamp +) +SENTINEL = 0x69696969 +INACTIVE = 0x13579bdf +PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + + +def packed(op, dst, lo, hi, *, first=257, second=258, bad=0, neg_lo=0, neg_hi=0, clamp=0): + w0 = 0xCC004000 | (op << 16) | ((clamp & 1) << 15) | (lo << 11) | ((neg_hi & 7) << 8) | dst | bad + w1 = ((neg_lo & 7) << 29) | (hi << 27) | (second << 9) | first + return [w0, w1] + + +def compute_program(kind, *, bad=0, swap=False, flush=False, sparse=False, neg_lo=0, neg_hi=0, clamp=0, mods=False): + code = list(PROLOGUE) + if flush: + code.append(0xBFA50003) # s_denorm_mode: keep f32 denormals and flush f16 + rows = MOD_CASES if mods else CASES + for slot, row in enumerate(rows): + if mods: + a, b, lo, hi, m_lo, m_hi, m_clamp = row + else: + a, b, lo, hi = row + m_lo, m_hi, m_clamp = neg_lo, neg_hi, clamp + source = {1: 23, 2: 255, 8: 128}.get(slot, 257) if not mods else {2: 23, 4: 255}.get(slot, 257) + if source == 23: + code += [0xBE9703FF, a] # s_mov_b32 s23, literal + elif source == 257: + code += [0x7E0202FF, a] + code += [0x7E0402FF, b] + for j, op in enumerate(OPS[kind]): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + code += packed(op, 4, hi if swap else lo, lo if swap else hi, first=source, bad=bad, + neg_lo=m_lo, neg_hi=m_hi, clamp=m_clamp) + if source == 255: + code.append(a) + if sparse: + code.append(sop1(3, 126, 193)) + code += [0xE0701000 | (slot * 2 + j) * 4, 0x80080408] + return code + [0xBF810000] + + +def compile_compute(cli, sdk, work, root, kind, **options): + source = request(work, root, compute_program(kind, **options)) + output = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', source, output], + capture_output=True, text=True, timeout=30) + return output, run + + +def root_signature(sdk, work): + hlsl = work / 'root.hlsl' + hlsl.write_text('#define RS "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'RS', '-Fo', root, hlsl], check=True) + return root.read_bytes() + + +def controls(cli, sdk, work, root, baseline=False): + for kind in OPS: + _, run = compile_compute(cli, sdk, work, root, kind) + if baseline: + assert run.returncode, (kind, run.stdout) + print(kind, run.stderr.strip()) + continue + assert run.returncode == 0, run.stdout + run.stderr + if kind == 'f16': + _, run = compile_compute(cli, sdk, work, root, kind, mods=True) + assert run.returncode == 0, run.stdout + run.stderr + _, run = compile_compute(cli, sdk, work, root, kind, neg_lo=3, neg_hi=3, clamp=1) + assert run.returncode == 0, run.stdout + run.stderr + for bad_kwargs in ({'bad': 1 << 10}, {'bad': 1 << 13}, {'neg_lo': 4}): + _, run = compile_compute(cli, sdk, work, root, kind, **bad_kwargs) + assert run.returncode and 'packed 16-bit min/max encoding' in run.stderr, (kind, bad_kwargs, run.stderr) + else: + for bad in (1 << 15, 1 << 8, 1 << 13): + _, run = compile_compute(cli, sdk, work, root, kind, bad=bad) + assert run.returncode and 'packed 16-bit min/max encoding' in run.stderr, (kind, run.stderr) + if not baseline: + _, run = compile_compute(cli, sdk, work, root, 'f16', flush=True) + assert run.returncode and 'denormal mode' in run.stderr, run.stderr + print('six opcodes compiled (f16 with neg_lo/neg_hi/clamp); reserved/integer mods and f16 flush mode refused') + + +def half_result(kind, maximum, a, b, *, neg_a=False, neg_b=False, clamp=False): + if kind == 'f16': + if neg_a: + a ^= 0x8000 + if neg_b: + b ^= 0x8000 + x, y = (struct.unpack('<e', struct.pack('<H', v))[0] for v in (a, b)) + if math.isnan(x): + res = 0x7e00 if math.isnan(y) else b + elif math.isnan(y): + res = a + elif x == y == 0: + res = a & b if maximum else a | b + else: + res = a if (x > y if maximum else x < y) else b + if clamp: + if (res & 0x7fff) > 0x7c00 or (res & 0x8000): + return 0x0000 + if res > 0x3bff: + return 0x3c00 + return res + elif kind == 'i16': + x, y = (struct.unpack('<h', struct.pack('<H', v))[0] for v in (a, b)) + else: + x, y = a, b + return a if (x > y if maximum else x < y) else b + + +def expected(kind, case, maximum, *, swap=False): + if len(case) == 7: + a, b, lo, hi, neg_lo, neg_hi, clamp = case + else: + a, b, lo, hi = case + neg_lo, neg_hi, clamp = 0, 0, 0 + halves = [] + pairs = ((hi, neg_hi), (lo, neg_lo)) if swap else ((lo, neg_lo), (hi, neg_hi)) + for select, neg in pairs: + x, y = (a >> (16 * (select & 1))) & 0xffff, (b >> (16 * (select >> 1))) & 0xffff + halves.append(half_result(kind, maximum, x, y, neg_a=bool(neg & 1), neg_b=bool(neg & 2), clamp=bool(clamp))) + return halves[0] | halves[1] << 16 + + +def compute_replay(replay, sdk, work, root, kind, **options): + source = request(work, root, compute_program(kind, **options)) + output = work / 'readback.bin' + run = subprocess.run([replay, sdk, source, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + raise SystemExit(77) + run.check_returncode() + return struct.unpack('<2064I', output.read_bytes()) + + +def expected_buffer(kind, *, swap=False, sparse=False, mods=False): + rows = MOD_CASES if mods else CASES + lane_words = [expected(kind, case, maximum, swap=swap) for case in rows for maximum in (False, True)] + unused = [SENTINEL] * (32 - len(lane_words)) + inactive = [INACTIVE] * len(lane_words) if sparse else lane_words + pair = lane_words + unused + inactive + unused + return (SENTINEL,) * 8 + tuple(pair * 32) + (SENTINEL,) * 8 + + +def draw_compute(replay, sdk, work, root): + for kind in OPS: + actual = compute_replay(replay, sdk, work, root, kind) + reference = expected_buffer(kind) + for index, (word, want) in enumerate(zip(actual, reference, strict=True)): + assert word == want, (kind, index, hex(word), hex(want)) + print(f'{kind}: 2064 Compute readback words matched') + actual = compute_replay(replay, sdk, work, root, 'f16', mods=True) + reference = expected_buffer('f16', mods=True) + for index, (word, want) in enumerate(zip(actual, reference, strict=True)): + assert word == want, ('f16_mods', index, hex(word), hex(want)) + print(f'f16 neg_lo/neg_hi/clamp: {len(MOD_CASES)}x2 Compute readback cases matched across 2064 words') + actual = compute_replay(replay, sdk, work, root, 'f16', swap=True) + assert actual == expected_buffer('f16', swap=True) + count = sum(a != b for a, b in zip(actual, expected_buffer('f16'), strict=True)) + assert count > 0 + print(f'Compute swapped selectors: {count} readback words differ from the original reference') + actual = compute_replay(replay, sdk, work, root, 'f16', sparse=True) + assert actual == expected_buffer('f16', sparse=True) + print('Compute sparse EXEC: inactive lanes kept their original packed word') + + +def pixel_program(kind, case): + if len(case) == 7: + a, b, lo, hi, neg_lo, neg_hi, clamp = case + else: + a, b, lo, hi = case + neg_lo, neg_hi, clamp = 0, 0, 0 + code = [0x7E0202FF, a, 0x7E0402FF, b] + for j, op in enumerate(OPS[kind]): + src, low, high = 4 + j, 8 + 2 * j, 9 + 2 * j + code += packed(op, src, lo, hi, neg_lo=neg_lo, neg_hi=neg_hi, clamp=clamp) + code += [vop2(0x1b, low, 255, src), 65535, vop2(0x16, high, 144, src)] + # Each unsigned halfword is exactly representable as binary32, even + # if the packed result as a whole would encode a float NaN. + code += [0x7E000C00 | reg << 17 | (256 + reg) for reg in (low, high)] + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def draw_pixel(cli, sdk, renderer, adapter, work): + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + for kind in OPS: + indices = (0, 1, 3, 7) + cases = [(f'{kind}-{index}', CASES[index]) for index in indices] + if kind == 'f16': + cases += [(f'f16-mod-{index}', case) for index, case in enumerate(MOD_CASES)] + for label, case in cases: + shader = work / f'{label}.ps' + shader.write_bytes(pixel_program(kind, case)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, (label, build.stdout + build.stderr) + minimum, maximum = (expected(kind, case, flag) for flag in (False, True)) + reference = work / 'expected.bin' + reference.write_bytes(struct.pack('<4f', minimum & 0xffff, minimum >> 16, maximum & 0xffff, maximum >> 16)) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', reference], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + raise SystemExit(77) + assert run.returncode == 0, (label, run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'{kind}: {len(cases)} Pixel cases matched for both packed results') + + +if __name__ == '__main__': + mode, tool, sdk, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + if mode == 'pixel': + draw_pixel(tool, sdk, *args, work) + elif mode == 'compute': + draw_compute(tool, sdk, work, root_signature(sdk, work)) + else: + controls(tool, sdk, work, root_signature(sdk, work), baseline=mode == 'baseline') diff --git a/tests/native_perm_lerp_check.py b/tests/native_perm_lerp_check.py new file mode 100644 index 0000000000..cb1b5be84a --- /dev/null +++ b/tests/native_perm_lerp_check.py @@ -0,0 +1,130 @@ +"""v_perm_b32 and v_lerp_u8 in the direct compute path. + + native_perm_lerp_check.py controls <compile_dxil> <sdk bin dir> + native_perm_lerp_check.py hardware <native_store_replay> <sdk bin dir> + +The semantics are those of the RDNA 2 ISA, as the gfx2hlsl.py lowerings (#2875, #2873) state them. v_perm_b32: each +result byte i takes selector s = S2[8i+7:8i]; s 0..7 picks byte s of the 64-bit value {S0, S1} (S1 is bytes 0..3), +s 8..11 gives 0xff or 0x00 from bit 15 of S1, bit 31 of S1, bit 15 of S0 or bit 31 of S0, s 12 gives 0x00 and +s 13..255 give 0xff. v_lerp_u8: each byte is (S0 + S1 + S2[8i]) >> 1. The words were assembled with LLVM 15 +(llvm-mc -mcpu=gfx1013). + +Two groups of 32 lanes; G = L + 32g is the lane's global index. v_perm_b32 uses S0 = 0x1b6c9e37, S1 = 0x80f07ad5 +and S2 bytes 4G .. 4G+3, so the 64 lanes cover all 256 selectors once; a second v_perm_b32 exchanges S0 and S1. The +two words have different bits 15 and 31, and bits 7 and 23 differ from bits 15 and 31. v_lerp_u8 uses +S1 = G * 0x9e3779b9, S0 = S1 ^ 0xff80017f and S2 = G * 0x01030507. References with the sources exchanged, the sign +read from bit 7 instead of bit 15, selector 12 as 0xff, and the lerp rounding bit dropped or taken from every bit of +the S2 byte must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_align_bfm_check import words +from native_dpp_quad_check import request + +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 9 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 4, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v3, s8, v0 / +# v_mov_b32 v1, 0x1b6c9e37 / v_mov_b32 v2, 0x80f07ad5 / v_mul_lo_u32 v9, v3, 0x4040404 / +# v_add_nc_u32 v9, 0x3020100, v9 / v_perm_b32 v4, v1, v2, v9 / v_mul_lo_u32 v10, v3, 0x9e3779b9 / +# v_mul_lo_u32 v11, v3, 0x1030507 / v_xor_b32 v12, 0xff80017f, v10 / v_lerp_u8 v5, v12, v10, v11 / +# v_perm_b32 v7, v2, v1, v9 / s_waitcnt lgkmcnt(0) / buffer_store_dword v4, v5, v7 at v8 + 0, 4, 8 / s_endpgm +HEX = ('040394be 800395be 0a0808f4200000fa 0589078f 0585088f 84001034 0710104a 0800064a ff02027e379e6c1b ' + 'ff02047ed57af080 090069d503ff010004040404 ff12124a00010203 040044d701052604 0a0069d503ff0100b979379e ' + '0b0069d503ff010007050301 ff14183a7f0180ff 05004dd50c152e04 070044d702032604 7fc08cbf ' + '001070e008040880 041070e008050880 081070e008070880 000081bf') +S0, S1 = 0x1B6C9E37, 0x80F07AD5 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK = 0xFFFFFFFF + + +def perm(s0, s1, s2, sign_bits=(15, 31), twelve=0x00): + pair = (s0 << 32) | s1 + out = 0 + for i in range(4): + sel = (s2 >> (8 * i)) & 255 + if sel < 8: + value = (pair >> (8 * sel)) & 255 + elif sel < 12: + bit = (32 if sel >= 10 else 0) + sign_bits[sel & 1] + value = 255 if (pair >> bit) & 1 else 0 + else: + value = twelve if sel == 12 else 255 + out |= value << (8 * i) + return out + + +def lerp(s0, s1, s2, rounding='bit0'): + out = 0 + for i in range(4): + a, b, c = ((x >> (8 * i)) & 255 for x in (s0, s1, s2)) + r = {'bit0': c & 1, 'none': 0, 'byte': c}[rounding] + out |= (((a + b + r) >> 1) & 255) << (8 * i) + return out + + +def reference(swapped=False, sign_bits=(15, 31), twelve=0x00, rounding='bit0'): + expected = [SENTINEL] * OUTPUT_WORDS + hi, lo = (S1, S0) if swapped else (S0, S1) + for g in range(64): + selectors = sum((4 * g + i) << (8 * i) for i in range(4)) + b = (g * 0x9E3779B9) & MASK + a, c = b ^ 0xFF80017F, (g * 0x01030507) & MASK + base = GUARD_WORDS + g * 4 + expected[base:base + 3] = [perm(hi, lo, selectors, sign_bits, twelve), lerp(a, b, c, rounding), + perm(lo, hi, selectors, sign_bits, twelve)] + return expected + + +def controls(cli, sdk, work, root): + marker = request(work, root, words(HEX)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + # Spot values of the definition: selectors 0..7 read {S0, S1} bytes, 8..11 the four sign bits, 12 is zero. + assert perm(S0, S1, 0x03020100) == S1 and perm(S0, S1, 0x07060504) == S0 + assert perm(S0, S1, 0x0B0A0908) == 0x00FFFF00 and perm(S0, S1, 0xFF0D0C0C) == 0xFFFF0000 + assert lerp(0xFF00FF01, 0xFF01FF00, 0x01010101) == 0xFF01FF01 and lerp(0xFF00FF01, 0xFF01FF00, 0) == 0xFF00FF00 + expected = reference() + for label, mutant in (('S0 and S1 exchanged', reference(swapped=True)), + ('sign read from bit 7 and 23', reference(sign_bits=(7, 23))), + ('selector 12 as 0xff', reference(twelve=0xFF)), + ('lerp rounding bit dropped', reference(rounding='none')), + ('lerp rounding from the whole S2 byte', reference(rounding='byte'))): + assert mutant != expected, label + print('compiled; the exchanged, sign-bit, selector-12 and both lerp-rounding references each differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert not diff, diff[:10] + print('v_perm_b32 and v_lerp_u8: 192 words of two groups, all 256 selectors and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_permlane_check.py b/tests/native_permlane_check.py new file mode 100644 index 0000000000..9976e58d68 --- /dev/null +++ b/tests/native_permlane_check.py @@ -0,0 +1,146 @@ +"""Direct compute permlane with sparse guest EXEC.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import compute +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1 + + +SENTINEL = 0x69696969 +ACTIVE = 0xFFFFFEFD # Disable physical lanes 1 and 8 in each wave32. +SELECTORS = (1, 8, 3, 0, 15, 2, 9, 4, 8, 1, 14, 5, 2, 11, 6, 7) + +# VOP3A word 0: opcode 25:16 (377/378), FI 11, BOUND_CTRL 12, v1 destination. +# Word 1: S0 8:0 (258 = v2), S1 17:9, S2 26:18. A selector of 255 +# references the shared third word. Keep the CPU model separate from the machine words. +CASES = ( + ("cross-literal-bound", True, False, True, SELECTORS, + (0xD7781001, 0x0035FF02, 0x492F0381)), # x16 BC, v2/literal/s13 + ("cross-sgprs-fi", True, True, False, SELECTORS, + (0xD7780801, 0x00341902)), # x16 FI, v2/s12/s13 + ("cross-inline-zero", True, False, False, (0,) * 16, + (0xD7780001, 0x02010102)), # x16, v2/inline 0/inline 0 + ("same-literal-bound", False, False, True, SELECTORS, + (0xD7771001, 0x0035FF02, 0x492F0381)), # permlane16 BC, v2/literal/s13 + ("same-sgprs", False, False, False, SELECTORS, + (0xD7770001, 0x00341902)), # permlane16, v2/s12/s13 + ("cross-s2-literal", True, False, False, SELECTORS, + (0xD7780001, 0x03FC1902, 0x76B25E18)), # x16, v2/s12/literal + ("cross-shared-literal", True, False, False, (1, 8, 3, 0, 15, 2, 9, 4) * 2, + (0xD7780001, 0x03FDFF02, 0x492F0381)), # x16, v2/literal/literal +) + + +def program(instruction): + # Each group writes 64 words starting after eight guards. + # Initialize the destination and a distinct source while EXEC is full. + return [ + sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8), + vop2(0x25, 1, 145, 0), vop2(0x25, 2, 148, 0), + sop1(3, 12, 255), 0x492F0381, sop1(3, 13, 255), 0x76B25E18, + sop1(3, 126, 255), ACTIVE, *instruction, + # Restore EXEC so the store observes preserved destinations too. + sop1(3, 126, 193), 0xE0701000, 0x80080108, 0xBF810000, + ] + + +def reference(cross_row, fi, bound_zero, selectors): + result = list(range(17, 81)) + enabled = [bool(ACTIVE & (1 << (lane % 32))) for lane in range(64)] + for half in (0, 32): + rows = (half, half + 16) + source_rows = rows[::-1] if cross_row else rows + for destination, source in zip(rows, source_rows): + for offset, peer in enumerate(selectors): + lane = destination + offset + if enabled[lane]: + if fi or enabled[source + peer]: + result[lane] = 20 + source + peer + elif bound_zero: + result[lane] = 0 + return tuple(result) + + +def request(work, root, instruction, threads=64): + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1 | (1 << 20), 0, 0x8A) # bit 20: wave32 (#2999) + return write_request(work, program(instruction), root, sa) + + +def controls(cli, sdk, work, root): + requests = work / "requests" + requests.mkdir() + good = request(requests, root, CASES[0][-1]) + refused = {} + for instruction, threads, error in ( + ((0xD7782001, 0x00341902), 64, "unsupported permlane modifier or op_sel"), # x16 op_sel[2] + ((0xD7788001, 0x00341902), 64, "unsupported permlane modifier or op_sel"), # x16 clamp + ((0xD7780001, 0x00360702), 64, "permlane selectors must be uniform"), # v2/v3/s13 + ((0xD7780001, 0x00341902), 16, "thread count divisible by 32"), # x16 partial pair + ((0xD7770001, 0x00341902), 8, "thread count divisible by 16"), # permlane16 partial row + ((0xD7780001, 0x00341880), 64, "S0 must be a VGPR")): # inline 0/s12/s13 + refused[request(requests, root, instruction, threads)] = error + result = subprocess.run( + [cli, sdk, work / "cache", "gfx1013-direct-cs@0", "--requests", requests, requests], + capture_output=True, text=True) + assert result.returncode and "requests=7 compiled=1 refused=6" in result.stdout, ( + result.stdout, result.stderr) + good_key = good.stem.removeprefix("req_") + assert (requests / f"{good_key}.cs.cso").is_file() + for marker, error in refused.items(): + key = marker.stem.removeprefix("req_") + reason = (requests / f"{key}.fail").read_text(encoding="utf-8") + assert error in reason, (marker, reason) + assert not (requests / f"{key}.cs.cso").exists() + + # Compile a container without its wave32 flag to exercise split guest wave64. + # Give EXEC halves distinct values, then restore both after the permutation. + shader = work / "wave64.cdx" + output = shader.with_suffix(".cso") + words = [vop2(0x25, 1, 145, 0), vop2(0x25, 2, 148, 0), + sop1(3, 13, 255), 0x76B25E18, + sop1(3, 126, 255), ACTIVE, sop1(3, 127, 255), 0xFFFFFF7B, + *CASES[0][-1], sop1(4, 126, 193), 0xBF810000] + shader.write_bytes(compute(struct.pack(f"<{len(words)}I", *words), 64, wave32=False)) + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-container-cs", shader, output], + capture_output=True, text=True) + assert result.returncode == 0, (result.stdout, result.stderr) + assert output.read_bytes().startswith(b"DXBC") + return 0 + + +def hardware(replay, sdk, work, root): + for name, cross_row, fi, bound_zero, selectors, instruction in CASES: + marker = request(work, root, instruction) + output = marker.with_suffix(".bin") + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + lanes = reference(cross_row, fi, bound_zero, selectors) + expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 136) + actual = struct.unpack("<2064I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (name, index, hex(got), hex(want)) + print(f"{name}: 128 results and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_pixel_atomic_check.py b/tests/native_pixel_atomic_check.py new file mode 100644 index 0000000000..990413b011 --- /dev/null +++ b/tests/native_pixel_atomic_check.py @@ -0,0 +1,194 @@ +"""Native pixel atomics through offline publication and the real draw path.""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +from types import SimpleNamespace + +from native_direct_container_check import patched_pixel, signature +from native_startup_request_cache_check import stream_vertex_container +from startup_pixel_uav_check import run_case, DRAWN_LINE, CLEAR + +MASK = 0xffffffff +RED = bytes((255, 0, 0, 255)) + + +def shader(stride, glc=True, threshold=None, offset=0, delta=1, wqm=False, bad=None, dynamic=False): + vop1 = lambda op, dst, src: 0x7e000000 | dst << 17 | op << 9 | src + vop2 = lambda op, dst, src0, src1: op << 25 | dst << 17 | src1 << 9 | src0 + code = [0xbe810380, 0xf40c0200, 0xfa000000 | stride] + if wqm or bad == "wqm": + code += [0xbe98047e, 0xbefe0a7e] # Save exact EXEC, enter WQM. + # v0 = x, v1 = y. Per-pixel output address = 4*(4*y+x+1). + code += [vop1(7, 0, 256), vop1(7, 1, 257), vop1(1, 4, 255), delta, + vop1(1, 2, 242), vop1(1, 3, 128)] + if dynamic: + # Two contended counters at the last two DWORDs of the view. + code += [vop2(0x1b, 5, 129, 0), vop2(0x1a, 5, 130, 5)] + if bad == "branch": + code += [0xbf820000] # Unflattened guest CFG edge. + if threshold is not None: + code += [0x7d080080 | threshold, 0xbe84246a, 0xbf880002] + if wqm: + # Horizontal quad swap of integer SV_Position.x. At x=2 on the + # odd edge this consumes the helper at x=3, not a constant. + code += [0x7e0802fa, 0xff0cb100] # v4 = quadSwapX(v0). + if glc: + # Preserve v0/v1 for the quad read; form the private output offset + # in WQM before restoring exact EXEC. v6 = 4*(4*y+x). + code += [vop2(0x1a, 1, 130, 1), vop2(0x1c, 6, 257, 0), + vop2(0x1a, 6, 130, 6)] + code += [0xbefe0418] # Restore exact EXEC. + op = 0xe0c80000 | (0x4000 if glc else 0) | offset + if bad == "other": + op = 0xe0cc0000 + if bad == "indexed": + op |= 0x2000 + if dynamic: + op |= 0x1000 + code += [op, 0x80020405 if dynamic else 0x80020400] # v4 is both addend and GLC destination. + if threshold is not None: + code += [0xbefe0404] # Restore the proven original EXEC. + if wqm and glc: + # A second already-supported exact atomic add records the returned old + # value into a disjoint lane slot; no extra exact-mask ALU/store allowed. + code += [0xe0c81004, 0x80020406] + elif not wqm and bad != "wqm": + # Store returned VGPR (or unchanged addend) after reconvergence. + code += [vop2(0x1a, 1, 130, 1), vop2(0x1c, 0, 257, 0), + vop2(0x1a, 0, 130, 0), 0xe0701004, 0x80020400] + return patched_pixel(len(code), code, table=True, input_address=3 << 8, + input_signature=((b"ISG1", signature(b"SV_Position", 1)),), + export=(0xf800180f, 0x02030302)) + + +def main(cli, consumer, sdk, backend): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + vs = folder / "vs" + vs.write_bytes(stream_vertex_container()) + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", + X2W_D3D12_RENDER="1", X2W_D3D12_DEVICE_NOOP="1", + X2W_TEST_DEBUG_LAYER="1", X2W_D3D12_DEBUG="0") + # The guest descriptor increment differs between AMD and app-local WARP. + probe = folder / "probe" + probe.mkdir() + ps = probe / "ps" + root = probe / "root" + ps.write_bytes(shader(32)) + publish = dict(env, X2W_SHADER_CACHE=str(probe), X2W_TEST_PIXEL_UAV="raw-atomic") + publish.pop("X2W_TEST_DEBUG_LAYER") + if backend == "hardware": + publish["X2W_TEST_DISPATCH_HARDWARE"] = "1" + r = subprocess.run([consumer, vs, ps, root], env=publish, capture_output=True, text=True) + if r.returncode == 77: + return 77 + assert r.returncode == 0, r.stderr + stride = int(re.search(r"raw descriptor stride: (\d+)", r.stdout)[1]) + print(f"descriptor stride={stride}", flush=True) + + def case(name, *, glc=True, threshold=None, offset=0, delta=1, edge=False, wqm=False, dynamic=False): + work = folder / name + work.mkdir() + cache = work / "cache" + cache.mkdir() + ps, root = work / "ps", work / "root" + ps.write_bytes(shader(stride, glc, threshold, offset, delta, wqm, dynamic=dynamic)) + mode = "raw-atomic-edge" if edge else "raw-atomic" + p = dict(publish, X2W_SHADER_CACHE=str(cache), X2W_TEST_PIXEL_UAV=mode) + r = subprocess.run([consumer, vs, ps, root], env=p, capture_output=True, text=True) + assert r.returncode == 0, r.stderr + r = subprocess.run([cli, sdk, folder/"frontend", "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, text=True) + assert r.returncode == 0, (name, r.stdout, r.stderr) + stage, = cache.glob("*.ps.cso") + manifest = stage.with_name(stage.name.replace(".ps.cso", ".txt")) + assert f"uav 0 raw table 0 {stride}" in manifest.read_text() + ir = subprocess.check_output([Path(sdk)/"dxc.exe", "-dumpbin", stage], text=True) + assert "@dx.op.atomicBinOp.i32" in ir and "@dx.op.isHelperLane.i1" in ir, ir + if wqm: + assert "@dx.op.quadOp.i32" in ir, ir + program = SimpleNamespace(directory=work, cache=cache, consumer=consumer, vs=vs, ps=ps, root=root) + rc, out, log, pixels, words = run_case(program, mode, env, backend) + if rc == 77: + sys.exit(77) + assert rc == 0 and "device removed reason: 0x00000000" in out, (name, rc, out, log) + assert DRAWN_LINE in log, (name, log) + if "debug layer: on" in out: + assert "debug layer: on, errors: 0" in out, out + coverage = [(x,y) for y in range(3 if edge else 4) for x in range(3 if edge else 4)] + active = [(x,y) for x,y in coverage if threshold is None or x < threshold] + want_pixels = b"".join(RED if (x,y) in coverage else CLEAR for y in range(4) for x in range(8)) + assert pixels == want_pixels, (name, pixels.hex(), want_pixels.hex()) + expected = [0xabcd0000 + i for i in range(64)] + base = 36 + for group in range(2 if dynamic else 1): + lanes = [(x,y) for x,y in active if not dynamic or x%2 == group] + target = base + offset//4 + group + in_view = offset//4 + group < 20 + seed = expected[target] if in_view else 0 + if in_view: + increment = sum(x ^ 1 for x,y in lanes) if wqm else delta*len(lanes) + expected[target] = (seed + increment) & MASK + if not wqm or glc: + returned = [] + for x,y in coverage: + if dynamic and x%2 != group: + continue + pos = base + 1 + 4*y+x + if glc and (x,y) in lanes: + returned.append((words[pos]-expected[pos]) & MASK if wqm else words[pos]) + expected[pos] = words[pos] # Compare the full old-value multiset independently. + else: + expected[pos] = (x ^ 1) if wqm else delta + want_old = sorted(((seed + delta*j) & MASK) if in_view else 0 for j in range(len(lanes))) + if wqm and glc and in_view: + # Validate a serialization, including zero increments, without imposing GPU lane order. + from functools import lru_cache + from collections import Counter + edges = Counter((old, x ^ 1) for old,(x,y) in zip(returned, lanes)) + pairs = tuple(edges) + @lru_cache(None) + def chain(value, counts): + if not any(counts): + return value == expected[target] + return any(n and old == value and chain((value+add)&MASK, + counts[:i]+(n-1,)+counts[i+1:]) + for i, ((old,add),n) in enumerate(zip(pairs,counts))) + assert chain(seed, tuple(edges.values())), (name, edges, seed, expected[target]) + else: + assert sorted(returned) == (want_old if glc else []), (name, returned, want_old) + assert words == expected, (name, [(i,hex(a),hex(b)) for i,(a,b) in enumerate(zip(words,expected)) if a!=b], len(words)) + print(name, f"{len(coverage)} covered, {len(active)} active; 64 DWORDs and 32 pixels exact", + next((l for l in out.splitlines() if l.startswith("adapter=")), ""), flush=True) + + case("contention-return") + case("contention-no-return", glc=False) + case("half-exec", threshold=2) + case("empty-exec", threshold=0) + case("all-exec", threshold=4) + case("wrap", delta=0x60000001) + case("last-dword", offset=76) + case("out-of-view", offset=80) + case("dynamic-two-counters", offset=72, dynamic=True) + case("odd-edge", edge=True) + case("wqm-restore-edge-helper-read", glc=False, edge=True, wqm=True) + case("wqm-glc-edge-helper-read", edge=True, wqm=True) + case("wqm-glc-out-of-view", offset=80, edge=True, wqm=True) + for bad, reason in (("other", "graphics buffer atomic"), ("indexed", "indexed compute atomic"), + ("wqm", "pixel atomic requires exact coverage"), ("branch", "straight-line pixel raw DWORD add")): + source = folder / (bad+".ps") + dest = folder / (bad+".cso") + source.write_bytes(shader(stride, bad=bad)) + r = subprocess.run([cli,sdk,folder/"frontend","gfx1013-container-ps",source,dest], + capture_output=True,text=True) + assert r.returncode != 0 and not dest.exists() and reason in r.stderr, (bad,r.stderr) + print(bad, r.stderr.strip(), flush=True) + print(backend, "13 actual draws and 4 refusal controls passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_pixel_dxil_check.py b/tests/native_pixel_dxil_check.py new file mode 100644 index 0000000000..5909e44a1a --- /dev/null +++ b/tests/native_pixel_dxil_check.py @@ -0,0 +1,68 @@ +"""Compare a source-built gfx1013 packet with independently written HLSL.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + + +def main(exe, sdk): + with tempfile.TemporaryDirectory() as folder: + work = Path(folder) + def compile_one(profile, source, output, success=True): + p = subprocess.run([exe, sdk, work/"cache", profile, work/source, work/output], + capture_output=True, text=True) + if (p.returncode == 0) != success: + raise AssertionError((p.stdout, p.stderr)) + return p.stdout if success else p.stderr + + words = [0x7e0002f2,0x7e0202f0,0x7e040280,0x7e0602ff,0x3e800000, + 0xf800180f,0x03020100,0xbf810000] + (work/"pixel.bin").write_bytes(struct.pack("<8I", *words)) + (work/"pixel.hlsl").write_text("float4 main() : SV_Target0 { return float4(1,0.5,0,0.25); }") + mode = "gfx1013-constant-ps" + assert "cold_compile" in compile_one(mode,"pixel.bin","native.cso") + assert "cache_hit" in compile_one(mode,"pixel.bin","warm.cso") + cached, = (work/"cache").glob("*.bin") + damaged = bytearray(cached.read_bytes()) + damaged[-1] ^= 1 + cached.write_bytes(damaged) + assert "cold_compile" in compile_one(mode,"pixel.bin","recovered.cso") + compile_one("ps_6_0","pixel.hlsl","ref.cso") + expected=(work/"ref.cso").read_bytes() + assert all((work/name).read_bytes() == expected for name in ("native.cso","warm.cso","recovered.cso")) + words[2]=0xbf800000 # s_nop is outside the supported instruction family + (work/"pixel.bin").write_bytes(struct.pack("<8I", *words)) + assert "instruction at 8" in compile_one(mode,"pixel.bin","invalid.cso",False) + assert not (work/"invalid.cso").exists() + sources=[work/f"batch{i}.hlsl" for i in range(4)] + for i,path in enumerate(sources): + path.write_text(f"float4 main() : SV_Target0 {{ return {i+1}; }}") + args=[exe,sdk,work/"parallel-cache","--jobs","3","ps_6_0"] + pairs=[str(arg) for path in sources for arg in (path,path.with_suffix(".cso"))] + cold=subprocess.run(args+pairs,capture_output=True,text=True,check=True) + warm=subprocess.run(args+pairs,capture_output=True,text=True,check=True) + assert cold.stdout.count("cold_compile")==4 and warm.stdout.count("cache_hit")==4 + for path in sources: + compile_one("ps_6_0",path.name,"serial.cso") + assert path.with_suffix(".cso").read_bytes()==(work/"serial.cso").read_bytes() + bad=pairs.copy() + bad[-1]=pairs[1].upper() + assert "distinct" in subprocess.run(args+bad,capture_output=True,text=True).stderr + # One failed input keeps its previous output. Other jobs still finish. + previous=sources[0].with_suffix(".cso").read_bytes() + sources[0].write_text("invalid HLSL") + result=subprocess.run(args+pairs,capture_output=True,text=True) + assert result.returncode==1 and "job=1" in result.stderr and result.stdout.count("cache_hit")==3 + assert sources[0].with_suffix(".cso").read_bytes()==previous + for pragma,error in [("x2w_vop2 340804ff","literal length"), + ("x2w_vop2 02060501","unsupported VOP2 opcode"), + ("x2w_vop3 00000000","unknown native compute pragma")]: + (work/"bad-ir.hlsl").write_text(f"#pragma {pragma}\n[numthreads(1,1,1)] void main() {{}}") + assert error in compile_one("cs_6_0","bad-ir.hlsl","invalid-ir.cso",False) + assert not (work/"invalid-ir.cso").exists() + print("native pixel DXIL, independent reference, persistent hit, cache repair and refusal passed") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_pixel_ir_dump.cpp b/tests/native_pixel_ir_dump.cpp new file mode 100644 index 0000000000..f09d9a6e9b --- /dev/null +++ b/tests/native_pixel_ir_dump.cpp @@ -0,0 +1,21 @@ +// Print the DXIL-text IR that the direct C++ frontend builds for a pixel container. +// Used by native_pack_b32_f16_check.py to evaluate the emitted operations without a GPU. +// usage: native_pixel_ir_dump CONTAINER (exit 1 and the diagnostic on stderr if refused) +#include "gfx1013_compute_native.h" +#include <fstream> +#include <iostream> +#include <iterator> +#include <string> + +int main(int argc, char **argv) { + if (argc != 2) return 2; + std::ifstream file(argv[1], std::ios::binary); + const std::string bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); + try { + std::cout << x2w::translate_graphics_container(bytes, true).dxil_ir; + } catch (const std::exception &error) { + std::cerr << error.what() << "\n"; + return 1; + } + return 0; +} diff --git a/tests/native_pixel_raw_uav_check.py b/tests/native_pixel_raw_uav_check.py new file mode 100644 index 0000000000..396dada5a9 --- /dev/null +++ b/tests/native_pixel_raw_uav_check.py @@ -0,0 +1,127 @@ +"""Source-built native pixel buffer store through the actual graphics cache and draw.""" +import os +import re +from pathlib import Path +import subprocess +import sys +import tempfile +from types import SimpleNamespace + +from native_direct_container_check import patched_pixel, signature +from native_startup_request_cache_check import stream_vertex_container +from startup_pixel_uav_check import run_case, DRAWN_LINE, CLEAR + +VALUE = 0x11223344 + + +def shader(stride): + vop1 = lambda op, dst, src: 0x7e000000 | dst << 17 | op << 9 | src + vop2 = lambda op, dst, src0, src1: op << 25 | dst << 17 | src1 << 9 | src0 + # Load the second guest descriptor. Pixel (x,y) writes DWORD 4*y+x + # relative to that view; the triangle covers x=0..3, y=0..3. + code = [0xbe810380, 0xf40c0200, 0xfa000000 | stride, + vop1(7, 0, 256), vop1(7, 1, 257), + vop2(0x1a, 1, 130, 1), vop2(0x1c, 0, 257, 0), + vop2(0x1a, 0, 130, 0), vop1(1, 4, 255), VALUE, + 0xe0701000, 0x80020400, vop1(1, 2, 242), vop1(1, 3, 128)] + return patched_pixel(len(code), code, table=True, input_address=3 << 8, + input_signature=((b"ISG1", signature(b"SV_Position", 1)),), + export=(0xf800180f, 0x02030302)) + + +def main(cli, consumer, sdk, backend, baseline=False): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + cache = folder / "cache" + cache.mkdir() + vs, ps, root = (folder / n for n in ("vs", "ps", "root")) + vs.write_bytes(stream_vertex_container()) + ps.write_bytes(shader(32)) + env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_D3D12_PERMISSIVE="1", + X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_D3D12_DEVICE_NOOP="1", + X2W_TEST_PIXEL_UAV="raw-ok", X2W_TEST_DEBUG_LAYER="1", X2W_D3D12_DEBUG="0") + publish = dict(env) + publish.pop("X2W_TEST_DEBUG_LAYER") + if backend == "hardware": + publish["X2W_TEST_DISPATCH_HARDWARE"] = "1" + probe = subprocess.run([consumer, vs, ps, root], env=publish, capture_output=True, text=True) + if probe.returncode == 77: + sys.exit(77) + assert probe.returncode == 0, probe.stderr + stride = int(re.search(r"raw descriptor stride: (\d+)", probe.stdout)[1]) + assert stride >= 32 + print(f"guest descriptor stride: {stride}") + if stride != 32: + for entry in cache.iterdir(): + entry.unlink() + ps.write_bytes(shader(stride)) + subprocess.run([consumer, vs, ps, root], env=publish, check=True, capture_output=True) + line = f"uav 0 raw table 0 {stride}" + result = subprocess.run([cli, sdk, folder/"frontend", "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, text=True) + print(result.stdout, result.stderr, flush=True) + assert result.returncode == 0, result.stderr + stage, = cache.glob("*.ps.cso") + manifest = stage.with_name(stage.name.replace(".ps.cso", ".txt")) + if baseline: + assert not manifest.exists(), "baseline unexpectedly published raw UAV" + # Pair compilation succeeds on baseline; supply only the missing manifest + # to isolate the real runtime's independent refusal. + manifest.write_text("x2w-manifest 2\nud 1\nudsrc 0 rect\n" + line + "\nparams 0\ntargets 0\n") + text = manifest.read_text() + assert line in text.splitlines(), text + program = SimpleNamespace(directory=folder, cache=cache, consumer=consumer, vs=vs, ps=ps, root=root) + + def check(name, start=None, count=16, reason=None, decoy=False): + rc, out, log, pixels, words = run_case(program, name, env, backend) + if rc == 77: + print(out) + sys.exit(77) + assert rc == 0, (name, rc, out, log) + assert "device removed reason: 0x00000000" in out, out + if "debug layer: on" in out: + assert "debug layer: on, errors: 0" in out, out + expected = [0xabcd0000 + i for i in range(64)] + if start is not None: + base = (0 if decoy else 32) + start + expected[base:base+count] = [VALUE]*count + assert words == expected, (name, [(i, hex(a), hex(b)) for i,(a,b) in enumerate(zip(words,expected)) if a!=b], len(words), out, log) + assert (DRAWN_LINE in log) == (start is not None), (name, log) + if reason: + assert reason in log, (name, log) + red = bytes((255,0,0,255)) + assert pixels == ((red*4 + CLEAR*4)*4 if start is not None else CLEAR*32), (name, pixels.hex(), log) + print(name, "64 DWORDs + 32 pixels exact;", next((l for l in out.splitlines() if l.startswith("adapter=")), ""), next((l for l in out.splitlines() if l.startswith("debug layer:")), ""), flush=True) + + if baseline: + check("raw-ok", reason="buffer view (raw uav) is not bound") + return + check("raw-ok", 4) + check("raw-short", 4, 8) + check("raw-last", 16) + for name, reason in ( + ("raw-typed", "incompatible raw buffer UAV"), + ("raw-structured", "incompatible raw buffer UAV"), + ("raw-no-ua", "resource lacks ALLOW_UNORDERED_ACCESS"), + ("raw-missing", "table entry holds no view"), + ("raw-srv", "table entry is not an unordered-access view"), + ("raw-no-table", "no descriptor table at the parameter"), + ): + check(name, reason=reason) + # A different live descriptor at offset zero must change the written buffer. + manifest.write_text(text.replace(line, "uav 0 raw table 0 0")) + check("raw-ok.decoy", 4, decoy=True) + manifest.write_text(text.replace(line, "uav 0 raw table 0 4096")) + check("raw-ok.out-of-table", reason="table entry outside the bound table") + manifest.write_text(text.replace(line, "uav 0 raw table 0 1")) + check("raw-ok.unaligned", reason="raw view requires an aligned table record without typedload") + manifest.write_text(text.replace(line, line + " typedload")) + check("raw-ok.typedload", reason="raw view requires an aligned table record without typedload") + if stride > 32: + manifest.write_text(text.replace(line, "uav 0 raw table 0 32")) + check("raw-ok.wrong-stride", reason="raw UAV offset is not a descriptor boundary") + print(backend, f"{13 + (stride > 32)} raw UAV cases passed") + + +if __name__ == "__main__": + main(*sys.argv[1:5], baseline=len(sys.argv) == 6 and sys.argv[5] == "baseline") diff --git a/tests/native_pk_add_sub_16_check.py b/tests/native_pk_add_sub_16_check.py new file mode 100644 index 0000000000..624a0026e4 --- /dev/null +++ b/tests/native_pk_add_sub_16_check.py @@ -0,0 +1,158 @@ +"""Direct compute VOP3P packed 16-bit add/sub (v_pk_add/sub_i16, v_pk_add/sub_u16) with and without clamp.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF + +CASES = ( + (0x7FFF8000, 0x0001FFFF), # signed hi overflow (+32767+1), lo underflow (-32768-1) + (0x4000C000, 0x4000C000), # signed hi/lo saturation both directions + (0x00008000, 0x00018000), # 0 - (-32768) -> +32767 saturation; unsigned underflow -> 0 + (0xFFFF8000, 0x00018000), # unsigned wrap & saturation to 0xFFFF + (0x00010005, 0x00020003), # unsigned sub clamp to 0 vs exact diff + (0x7FFF8000, 0x80007FFF), # opposite-sign cancellation + (0x0003FFFD, 0x00050002), # small positive/negative without saturation + (0xDEADBEEF, 0x11112222), # general bit patterns +) +# (opcode, clamp, op_sel, op_sel_hi) +FORMS = ( + (0x02, True, 0, 3), # v_pk_add_i16 clamp default + (0x03, True, 1, 2), # v_pk_sub_i16 clamp swizzled op_sel:[1,0] op_sel_hi:[0,1] + (0x0A, True, 0, 3), # v_pk_add_u16 clamp default + (0x0B, True, 0, 0), # v_pk_sub_u16 clamp broadcast low halves op_sel:[0,0] op_sel_hi:[0,0] +) + + +def vop3p(opcode, vdst, src0, src1, *, op_sel=0, op_sel_hi=3, clamp=0, neg_lo=0, neg_hi=0, src2=0): + w0 = (0xCC004000 | ((opcode & 0x7F) << 16) | (clamp << 15) | ((op_sel & 7) << 11) + | ((neg_hi & 7) << 8) | (vdst & 0xFF)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1FF) << 18) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF)) + return [w0, w1] + + +def program(*, sparse=False, drop_clamp=False, first_modifier=0, second_modifier=0): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, (a, b) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), a, # v_xor_b32 v1, a, v0 + 0x7E0402FF, b] # v_mov_b32 v2, b + for mode, (opcode, clamp, op_sel, op_sel_hi) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + w0, w1 = vop3p(opcode, 4, 257, 258, op_sel=op_sel, op_sel_hi=op_sel_hi, + clamp=1 if (clamp and not drop_clamp) else 0) + code += [w0 ^ first_modifier, w1 ^ second_modifier] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def sext16(v): + v &= 0xFFFF + return v - 0x10000 if v >= 0x8000 else v + + +def eval_add_sub(opcode, a, b, clamp, op_sel, op_sel_hi): + signed = opcode in (0x02, 0x03) + sub = opcode in (0x03, 0x0B) + + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xFFFF + + def lane(sel): + x = pick(a, sel & 1) + y = pick(b, (sel >> 1) & 1) + if signed: + xv, yv = sext16(x), sext16(y) + r = xv - yv if sub else xv + yv + if clamp: + r = max(-32768, min(32767, r)) + return r & 0xFFFF + r = x - y if sub else x + y + if clamp: + r = max(0, min(0xFFFF, r)) + return r & 0xFFFF + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def reference(sparse=False, ignore_clamp=False): + words = [SENTINEL] * 8 + for lane in range(64): + for a, b in CASES: + for opcode, clamp, op_sel, op_sel_hi in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + eval_add_sub(opcode, a ^ (lane % 32), b, clamp and not ignore_clamp, op_sel, op_sel_hi)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + # Valid encoding + 4 refused modifier/reserved-bit encodings: + # op_sel[2] (w0[13]), neg_hi (w0[8]), neg_lo (w1[29]), nonzero src2 (w1[18]). + for first, second in ((0, 0), (1 << 13, 0), (1 << 8, 0), (0, 1 << 29), (0, 1 << 18)): + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and 'packed 16-bit add/sub operand modifiers' in result.stderr, result.stderr + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'icmp sgt i32 ' in dump and '32767' in dump, dump + assert 'icmp ugt i32 ' in dump and '65535' in dump, dump + assert reference() != reference(ignore_clamp=True) + assert reference() != reference(sparse=True) + print('v_pk_add/sub_16 DXIL verified; four modifier encodings refused; clamp and EXEC controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse, drop_clamp in ((False, False), (True, False), (False, True)): + marker = request(work, root, program(sparse=sparse, drop_clamp=drop_clamp)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse, ignore_clamp=drop_clamp) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} drop_clamp={drop_clamp} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + if drop_clamp: + changed = sum(a != b for a, b in zip(actual, reference())) + assert changed > 0, 'dropping clamp did not change the readback' + print(f'no-clamp control: {changed} words differed from the clamped reference') + else: + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_pk_add_sub_16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_pk_fmac_f16_check.py b/tests/native_pk_fmac_f16_check.py new file mode 100644 index 0000000000..a9301c94ad --- /dev/null +++ b/tests/native_pk_fmac_f16_check.py @@ -0,0 +1,275 @@ +"""Direct DXIL VOP2 v_pk_fmac_f16 lowering in Compute and Pixel shaders.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from f16_packed_model import half_op, same +from native_direct_container_check import patched_pixel +from native_dot2_f32_f16_check import p16 +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE, inline_word +from native_scalar_lds_check import sop1, vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + +OP_PK_FMAC_F16 = 0x3C +ALL_EXEC = 0xFFFFFFFF + + +def vop2_pk_fmac(dst, src0, vsrc1): + assert 256 <= vsrc1 < 512, vsrc1 + return ((OP_PK_FMAC_F16 << 25) | ((dst & 0xFF) << 17) | (((vsrc1 - 256) & 0xFF) << 9) | (src0 & 0x1FF)) + + +def vop3_pk_fmac_e64(dst, src0, vsrc1, *, clamp=0): + return [ + 0xD53C0000 | ((clamp & 1) << 15) | (dst & 0xFF), + ((vsrc1 & 0x1FF) << 9) | (src0 & 0x1FF), + ] + + +def eval_pk_fmac(s0_word, s1_word, acc_word): + lo = half_op('fma', s0_word & 0xFFFF, s1_word & 0xFFFF, acc_word & 0xFFFF) + hi = half_op('fma', (s0_word >> 16) & 0xFFFF, (s1_word >> 16) & 0xFFFF, (acc_word >> 16) & 0xFFFF) + return (hi << 16) | lo + + +@dataclass(frozen=True) +class Case: + name: str + steps: tuple + acc: int + exec_mask: int = ALL_EXEC + alias: str = 'none' + pixel_safe: bool = True + + def expected(self, lane=0): + if ((self.exec_mask >> lane) & 1) == 0: + return self.acc & 0xFFFFFFFF + cur = self.acc & 0xFFFFFFFF + for s0, v0, v1 in self.steps: + if self.alias == 'src0': + w0 = cur + elif s0 < 128 or s0 >= 255: + w0 = v0 & 0xFFFFFFFF + else: + w0 = inline_word(s0) + w1 = cur if self.alias == 'src1' else (v1 & 0xFFFFFFFF) + cur = eval_pk_fmac(w0, w1, cur) + return cur + + +def all_cases(): + return [ + # 1. Distinct low and high half FMA values. + Case('vgpr_basic', ((262, p16(0x3C00, 0x4000), p16(0x4200, 0x3800)),), p16(0x3800, 0xC000)), + # 2. Fused cancellation: (1 + 2^-6)^2 - 1 = 2^-5 + 2^-12 (0x2808), whereas unfused mul+add gives 2^-5 (0x2800). + Case('fused_cancellation', ((262, p16(0x3C10, 0xBC10), p16(0x3C10, 0x3C10)),), p16(0xBC00, 0xBC00)), + # 3. Back-to-back accumulation into vdst. + Case('multi_accumulate', + ((262, p16(0x3C00, 0x3800), p16(0x4000, 0x4000)), + (262, p16(0xBC00, 0x4000), p16(0x3C00, 0x4200))), + p16(0x3400, 0x3C00)), + # 4. Destination VGPR aliased with src0 or vsrc1. + Case('vgpr_dst_alias_src0', ((260, 0, p16(0x4000, 0x4200)),), p16(0x3C00, 0x3800), alias='src0'), + Case('vgpr_dst_alias_src1', ((262, p16(0x4200, 0x3C00), 0),), p16(0x3800, 0x4000), alias='src1'), + # 5. SGPR and 32-bit literal src0 encodings. + Case('sgpr_src0', ((10, p16(0x3C00, 0xC000), p16(0x4200, 0x3800)),), p16(0x3800, 0x4000)), + Case('literal_src0', ((255, p16(0x4000, 0x3C00), p16(0x3800, 0x4200)),), p16(0xBC00, 0x3400)), + # 6. Inline binary16 float constants (0.5, 1.0, -1.0) and inline integer 0 / subnormal 1. + Case('inline_f16_240', ((240, 0, p16(0x4000, 0x4400)),), p16(0x3C00, 0x3C00)), + Case('inline_f16_242', ((242, 0, p16(0x4000, 0x4400)),), p16(0x3800, 0x4000)), + Case('inline_f16_243', ((243, 0, p16(0x3C00, 0x4000)),), p16(0x4000, 0x4200)), + Case('inline_int_128', ((128, 0, p16(0x4000, 0x4400)),), p16(0xC200, 0x3C00)), + Case('inline_int_129', ((129, 0, p16(0x3C00, 0x3C00)),), p16(0x0002, 0x0001)), + # 7. Binary16 subnormal operands and subnormal outputs preserved cleanly. + Case('subnormal_io', ((262, p16(0x0001, 0x03FF), p16(0x3800, 0x3C00)),), p16(0x0001, 0x0001)), + # 8. Overflow from finite operands to +/-Inf. + Case('overflow_to_inf', ((262, p16(0x7BFF, 0xFBFF), p16(0x4000, 0x4000)),), + p16(0x3C00, 0xBC00), pixel_safe=False), + # 9. Partial EXEC mask: odd lanes update vdst, even lanes preserve pre-existing vdst. + Case('partial_exec_odd', ((262, p16(0x3C00, 0x4000), p16(0x4000, 0x4200)),), + p16(0x4500, 0xC100), exec_mask=0xAAAAAAAA, pixel_safe=False), + # 10. Signed zero, infinity, and NaN propagation. + Case('signed_zero_keep', ((262, p16(0x8000, 0x0000), p16(0x3C00, 0x8000)),), + p16(0x8000, 0x8000), pixel_safe=False), + Case('inf_and_nan', ((262, p16(0x7C00, 0x7E01), p16(0x3C00, 0x3C00)),), + p16(0xBC00, 0x3C00), pixel_safe=False), + ] + + +def emit_case(c: Case): + code = F.mov(4, c.acc) + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 255), c.exec_mask] + for s0, v0, v1 in c.steps: + lit_tail = [] + vsrc1 = 260 if c.alias == 'src1' else 261 + if c.alias != 'src1': + code += F.mov(vsrc1 - 256, v1) + src0 = 260 if c.alias == 'src0' else s0 + if c.alias != 'src0': + if src0 >= 256: + code += F.mov(src0 - 256, v0) + elif src0 <= 105: + code += F.smov(src0, v0) + elif src0 == 255: + lit_tail = [v0] + code.append(vop2_pk_fmac(4, src0, vsrc1)) + code += lit_tail + if c.exec_mask != ALL_EXEC: + code += [sop1(3, 126, 193)] + return code + + +def compute_program(cases): + code = list(PROLOGUE) + for slot, c in enumerate(cases): + code += emit_case(c) + F.store(slot * 4, 4) + return code + [0xBF810000] + + +def refusal_programs(): + cond_mode = [0xBF840001, 0xBFA5000F] # s_cbranch_scc0 +1; s_denorm_mode 15 + plain = [vop2_pk_fmac(4, 262, 261), 0xBF810000] + return [ + # VOP3 _e64 form of v_pk_fmac_f16. + (vop3_pk_fmac_e64(4, 262, 261) + [0xBF810000], 'unsupported packed binary16 arithmetic encoding'), + # DPP16, DPP8, and SDWA forms. + ([vop2_pk_fmac(4, 250, 261), 0xFF00E406, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_pk_fmac(4, 233, 261), 0xC6886806, 0xBF810000], 'unsupported DPP arithmetic'), + ([vop2_pk_fmac(4, 249, 261), 0x06060606, 0xBF810000], 'unimplemented direct SDWA operand profile'), + # Special scalar source refused on src0 (vcc_lo). + ([vop2_pk_fmac(4, 106, 261), 0xBF810000], 'unsupported packed binary16 arithmetic source'), + # Unsupported binary16 rounding/denorm and conditional MODE write. + ([0xBFA40004] + plain, 'unsupported binary16 rounding or denormal mode'), + ([0xBFA50003] + plain, 'unsupported binary16 rounding or denormal mode'), + (cond_mode + plain, 'unsupported binary16 rounding or denormal mode'), + ] + + +def ir(dumper): + items = all_cases() + code = compute_program(items) + want = [c.expected(lane=0) for c in items] + refusals = refusal_programs() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = F.dump(dumper, work, code, 'pk-fmac-f16') + assert run.returncode == 0, run.stderr + stores = sorted(F.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(want))], stores[:4] + bad = [(i, items[i].name, hex(got), hex(exp)) + for i, ((_, got), exp) in enumerate(zip(stores, want)) if not same(got, exp)] + assert not bad, bad[:8] + for idx, (refused, why) in enumerate(refusals): + r = F.dump(dumper, work, refused, f'refused-{idx}') + assert r.returncode != 0 and why in r.stderr, (idx, why, r.returncode, r.stderr) + print(f'native_pk_fmac_f16 IR: {len(want)} cases matched exact model; {len(refusals)} refusals matched') + return 0 + + +def controls(cli, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert '@dx.op.unaryBits.i32(i32 33,' in dump and 'mul i32' in dump, dump + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = m.with_suffix(f'.refused{idx}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_pk_fmac_f16 controls: compiled {len(items)} cases to DXIL; verified {len(refusals)} refusals') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = {} + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + for idx, c in enumerate(items): + expected[head + idx] = c.expected(lane=lane) + bad = [] + for i, got in enumerate(words_out): + if i in expected: + if not same(got, expected[i]): + bad.append((i, hex(got), hex(expected[i]))) + elif got != F.SENTINEL: + bad.append((i, hex(got), hex(F.SENTINEL))) + assert not bad, bad[:10] + print(f'native_pk_fmac_f16 compute hardware: {len(items)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'pk-fmac-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected(lane=0) for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_pk_fmac_f16 pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_pk_mul_mad_16_check.py b/tests/native_pk_mul_mad_16_check.py new file mode 100644 index 0000000000..51a01a219e --- /dev/null +++ b/tests/native_pk_mul_mad_16_check.py @@ -0,0 +1,172 @@ +"""Direct compute VOP3P packed 16-bit multiply/mad (v_pk_mul_lo_u16, v_pk_mad_u16, v_pk_mad_i16).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF + +CASES = ( + (0x00030005, 0x0007000B, 0x00010002), # small positive products & sums + (0x01000003, 0x01000005, 0x00010007), # unsigned overflow 0x10001 -> 0xFFFF clamp vs 1 wrap + (0xFFFF8000, 0xFFFF0002, 0xFFFF0000), # max u16 * max u16 + max u16 = 0xFFFF0000 (no u32 overflow) + (0x80007FFF, 0x00028000, 0x7FFF0001), # signed (-32768)*(-32768) -> +32767 saturation + (0x80008000, 0x7FFF7FFF, 0x80008000), # signed (-32768)*(+32767)-32768 -> -32768 saturation + (0x0003FFFD, 0x00050002, 0x0001FFFE), # signed negative product without saturation + (0x00FF0000, 0x0100FFFF, 0x00FF0001), # exact unsigned boundary 255*256+255 = 0xFFFF + (0xABCD0100, 0x00040100, 0xDEADBEEF), # general wrapping patterns +) +# (opcode, clamp, op_sel, op_sel_hi) +FORMS = ( + (0x01, False, 0, 3), # v_pk_mul_lo_u16 default + (0x01, False, 1, 2), # v_pk_mul_lo_u16 swizzled op_sel:[1,0] op_sel_hi:[0,1] + (0x09, True, 0, 7), # v_pk_mad_u16 clamp default + (0x00, True, 5, 2), # v_pk_mad_i16 clamp swizzled op_sel:[1,0,1] op_sel_hi:[0,1,0] +) + + +def vop3p(opcode, vdst, src0, src1, src2=0, *, op_sel=0, op_sel_hi=7, clamp=0, neg_lo=0, neg_hi=0): + w0 = (0xCC000000 | ((opcode & 0x7F) << 16) | (clamp << 15) | (((op_sel_hi >> 2) & 1) << 14) + | ((op_sel & 7) << 11) | ((neg_hi & 7) << 8) | (vdst & 0xFF)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1FF) << 18) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF)) + return [w0, w1] + + +def program(*, sparse=False, drop_clamp=False, first_modifier=0, second_modifier=0, mod_opcode=0x01): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, (a, b, c) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), a, # v_xor_b32 v1, a, v0 + 0x7E0402FF, b, 0x7E0602FF, c] # v_mov_b32 v2, b; v_mov_b32 v3, c + for mode, (opcode, clamp, op_sel, op_sel_hi) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + is_mad = opcode != 0x01 + w0, w1 = vop3p(opcode, 4, 257, 258, 259 if is_mad else 0, + op_sel=op_sel, op_sel_hi=op_sel_hi if is_mad else (op_sel_hi | 4), + clamp=1 if (clamp and not drop_clamp) else 0) + if (first_modifier or second_modifier) and opcode == mod_opcode and case == 0: + w0 ^= first_modifier + w1 ^= second_modifier + code += [w0, w1] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def sext16(v): + v &= 0xFFFF + return v - 0x10000 if v >= 0x8000 else v + + +def eval_mul_mad(opcode, a, b, c, clamp, op_sel, op_sel_hi): + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xFFFF + + def lane(sel): + x = pick(a, sel & 1) + y = pick(b, (sel >> 1) & 1) + if opcode == 0x01: + return (x * y) & 0xFFFF + z = pick(c, (sel >> 2) & 1) + if opcode == 0x00: + r = sext16(x) * sext16(y) + sext16(z) + if clamp: + r = max(-32768, min(32767, r)) + return r & 0xFFFF + r = x * y + z + if clamp: + r = min(0xFFFF, r) + return r & 0xFFFF + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def reference(sparse=False, ignore_clamp=False): + words = [SENTINEL] * 8 + for lane in range(64): + for a, b, c in CASES: + for opcode, clamp, op_sel, op_sel_hi in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + eval_mul_mad(opcode, a ^ (lane % 32), b, c, + clamp and not ignore_clamp, op_sel, op_sel_hi)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + # Valid encoding + 5 refused modifier/reserved-bit encodings: + # mul_lo: clamp (w0[15]), op_sel[2] (w0[13]), nonzero src2 (w1[18]); + # mad_i16: neg_hi (w0[8]), neg_lo (w1[29]). + cases = ( + (0x01, 0, 0), + (0x01, 1 << 15, 0), + (0x01, 1 << 13, 0), + (0x01, 0, 1 << 18), + (0x00, 1 << 8, 0), + (0x00, 0, 1 << 29), + ) + for mod_op, first, second in cases: + marker = request(work, root, program(first_modifier=first, second_modifier=second, mod_opcode=mod_op)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and 'packed 16-bit mul/mad operand modifiers' in result.stderr, result.stderr + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'mul i32 ' in dump and 'icmp sgt i32 ' in dump and '32767' in dump, dump + assert 'icmp ugt i32 ' in dump and '65535' in dump, dump + assert reference() != reference(ignore_clamp=True) + assert reference() != reference(sparse=True) + print('v_pk_mul_lo_u16/mad_16 DXIL verified; five modifier encodings refused; clamp and EXEC controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse, drop_clamp in ((False, False), (True, False), (False, True)): + marker = request(work, root, program(sparse=sparse, drop_clamp=drop_clamp)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse, ignore_clamp=drop_clamp) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} drop_clamp={drop_clamp} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + if drop_clamp: + changed = sum(a != b for a, b in zip(actual, reference())) + assert changed > 0, 'dropping clamp did not change the readback' + print(f'no-clamp control: {changed} words differed from the clamped reference') + else: + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_pk_mul_mad_16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_pk_shift16_check.py b/tests/native_pk_shift16_check.py new file mode 100644 index 0000000000..1aee3f34be --- /dev/null +++ b/tests/native_pk_shift16_check.py @@ -0,0 +1,147 @@ +"""Direct compute VOP3P packed 16-bit shifts (v_pk_lshlrev_b16, v_pk_lshrrev_b16, v_pk_ashrrev_i16).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF + +# (shift_word, value_word) covering counts 0..15, >15 masking, sign bit 0x8000, and lane-bleed hazards. +CASES = ( + (0x00040001, 0x00018001), + (0x000F0010, 0x80007FFF), + (0x001F0008, 0xFFFF1234), + (0x0007000C, 0xDEADBEEF), + (0x00000001, 0x80017FFE), + (0x00140004, 0xFF0000F0), + (0x00000000, 0x7FFF8000), + (0x000F000F, 0x80007FFF), +) +# (opcode, op_sel, op_sel_hi) +FORMS = ( + (0x04, 0, 3), # v_pk_lshlrev_b16 default + (0x05, 1, 2), # v_pk_lshrrev_b16 swizzled op_sel:[1,0] op_sel_hi:[0,1] + (0x06, 0, 3), # v_pk_ashrrev_i16 default + (0x06, 0, 0), # v_pk_ashrrev_i16 broadcast low halves op_sel:[0,0] op_sel_hi:[0,0] +) + + +def vop3p(opcode, vdst, src0, src1, *, op_sel=0, op_sel_hi=3, clamp=0, neg_lo=0, neg_hi=0, src2=0): + w0 = (0xCC004000 | ((opcode & 0x7F) << 16) | (clamp << 15) | ((op_sel & 7) << 11) + | ((neg_hi & 7) << 8) | (vdst & 0xFF)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1FF) << 18) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF)) + return [w0, w1] + + +def program(*, sparse=False, first_modifier=0, second_modifier=0): + # Group index and local lane identify a 24-word row (6 cases * 4 forms). + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + # Multiply row index by 24/32? Actually native_store_replay allocates 32 dwords per lane (64*32 = 2048 words). + # Keep stride 32 dwords per lane (offset < 128 bytes) to match native_store_replay's buffer layout. + for case, (amt_w, val_w) in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), amt_w, # v_xor_b32 v1, amt_w, v0 (varies shift counts per lane) + 0x7E0402FF, val_w] # v_mov_b32 v2, val_w + for mode, (opcode, op_sel, op_sel_hi) in enumerate(FORMS): + if sparse: + code += [0x7E0802FF, INACTIVE, sop1(3, 126, 255), 0x55555555] + w0, w1 = vop3p(opcode, 4, 257, 258, op_sel=op_sel, op_sel_hi=op_sel_hi) + code += [w0 ^ first_modifier, w1 ^ second_modifier] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * len(FORMS) + mode) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + # Fill remaining 8 dwords of the 32-word row with 0? Only 24 dwords written per lane; write last 8 on case==0. + return code + [0xBF810000] + + +def sext16(v): + v &= 0xFFFF + return v - 0x10000 if v >= 0x8000 else v + + +def eval_shift(opcode, a, b, op_sel, op_sel_hi): + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xFFFF + + def lane(sel): + amt = pick(a, sel & 1) & 15 + val = pick(b, (sel >> 1) & 1) + if opcode == 0x04: + return (val << amt) & 0xFFFF + if opcode == 0x05: + return (val >> amt) & 0xFFFF + return (sext16(val) >> amt) & 0xFFFF + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def reference(sparse=False): + words = [SENTINEL] * 8 + for lane in range(64): + for amt_w, val_w in CASES: + for opcode, op_sel, op_sel_hi in FORMS: + words.append(INACTIVE if sparse and lane % 2 else + eval_shift(opcode, amt_w ^ (lane % 32), val_w, op_sel, op_sel_hi)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + # Test valid encoding + 5 refused modifier/reserved-bit encodings: + # clamp (w0[15]), op_sel[2] (w0[13]), neg_hi (w0[8]), neg_lo (w1[29]), nonzero src2 (w1[18]). + for first, second in ((0, 0), (1 << 15, 0), (1 << 13, 0), (1 << 8, 0), (0, 1 << 29), (0, 1 << 18)): + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and 'packed 16-bit shift operand modifiers' in result.stderr, result.stderr + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump and 'ashr i32 ' in dump, dump + assert reference() != reference(sparse=True) + print('v_pk_shift16 DXIL verified; five modifier encodings refused; EXEC control differs') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse in (False, True): + marker = request(work, root, program(sparse=sparse)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_pk_shift16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_raw_buffer_view_check.cpp b/tests/native_raw_buffer_view_check.cpp new file mode 100644 index 0000000000..a8238bb36c --- /dev/null +++ b/tests/native_raw_buffer_view_check.cpp @@ -0,0 +1,44 @@ +#include "native_buffer_store_view.h" +#include <cstdio> +#include <limits> + +int main() +{ + const x2w::ComputeViewBinding binding{x2w::ComputeViewKind::raw_buffer_uav, 0, 32, 0, 4}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R32_TYPELESS, D3D12_UAV_DIMENSION_BUFFER}; + view.Buffer.FirstElement = 4; + view.Buffer.NumElements = 16; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + const auto valid = [&](D3D12_UNORDERED_ACCESS_VIEW_DESC v, UINT64 bytes) { + return x2w::native_buffer_store_view(binding, v, bytes); + }; + if (!valid(view, 128) || valid(view, 79)) return 1; + auto last = view; + last.Buffer.FirstElement = 16; + if (!valid(last, 128) || valid(last, 127)) return 2; + auto invalid = view; + invalid.Buffer.FirstElement = 5; + if (valid(invalid, 128)) return 3; + invalid = view; + invalid.Buffer.FirstElement = (std::numeric_limits<UINT64>::max)() - 3; + if (valid(invalid, 128)) return 4; + invalid = view; + invalid.Buffer.NumElements = 0; + if (valid(invalid, 128)) return 5; + invalid.Buffer.NumElements = 29; + if (valid(invalid, 128)) return 6; + invalid = view; + invalid.Buffer.CounterOffsetInBytes = 4096; + if (valid(invalid, 128)) return 7; + invalid = view; + invalid.Buffer.StructureByteStride = 4; + if (valid(invalid, 128)) return 8; + invalid = view; + invalid.Format = DXGI_FORMAT_R32_UINT; + if (valid(invalid, 128)) return 9; + invalid = view; + invalid.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + if (valid(invalid, 128)) return 10; + std::puts("raw buffer view: aligned and exact-end accepted; truncated, unaligned, overflowing, empty, counter, stride, format and flags refused"); + return 0; +} diff --git a/tests/native_raw_load_cache_bits_check.py b/tests/native_raw_load_cache_bits_check.py new file mode 100644 index 0000000000..ac87d76d5d --- /dev/null +++ b/tests/native_raw_load_cache_bits_check.py @@ -0,0 +1,136 @@ +"""Compile raw MUBUF loads with cache hints and compare hardware UAV readback.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import pack, words + + +GLC_DLC = (1 << 14) | (1 << 15) +SLC = 1 << 22 +REFUSAL = "raw buffer load needs a linear byte offset and no modifiers" +VIEWS = """x2w-global-srv-views 2 +select 0 +need raw_buffer +slot 0 raw_buffer 1 256 +slot 1 raw_buffer 1 256 +slot 2 texture 0 0 +slot 3 typed_buffer 4 256 +""" + + +def container(offen, cache_flags, extra_flags): + # Dispatch(1, 1, 1) runs group (0,0,0), with one wave32 and local IDs in v0. + # EXEC enables lanes 0..7. Each lane writes the first dword of a 16-byte u0 slot. + soffset = 128 if offen else 18 + code = words( + 0xbe810380, # s_mov_b32 s1, 0 + 0xbe830380, # s_mov_b32 s3, 0 + 0xf4080200, 0xfa000000, # s_load_dwordx4 s[8:11], s[0:1], 0 (selector t0) + 0xf4080300, 0xfa000020, # s_load_dwordx4 s[12:15], s[0:1], 32 (output u0) + 0xf4200404, 0xfa000000, # s_buffer_load_dword s16, s[8:11], 0 + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x8f118510, # s_lshl_b32 s17, s16, 5 + 0xf4080501, 0x22000000, # s_load_dwordx4 s[20:23], s[2:3], s17 (selected heap SRV) + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0x34020084, # v_lshlrev_b32_e32 v1, 4, v0 + 0xbe92038c, # s_mov_b32 s18, 12 + 0xbefe03ff, 0x000000ff, # s_mov_b32 exec_lo, 0xff + 0xbeff0380, # s_mov_b32 exec_hi, 0 + 0xe0300000 | (int(offen) << 12) | cache_flags, + (soffset << 24) | 0x00050200 | int(offen) | extra_flags, # v2, v1/off, s[20:23] + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xe0701000, 0x80030201, # buffer_store_dword v2, v1, s[12:15], 0 offen + 0xbf810000, # s_endpgm + ) + + # Same two root inputs as native_global_srv_heap_replay_check.py. + body = bytearray(256) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into("<Q", body, 96, record) + struct.pack_into("<Q", body, record + 40, len(body)) + struct.pack_into("<I", body, record + 56, 2) + body.extend(struct.pack("<IIIIBBH", 3, 0, 1, 0, 0, 0, 0)) + body.extend(struct.pack("<IIIIBBH", 5, 0, 1, 0, 2, 0, 0)) + struct.pack_into("<QQII", body, record, len(body), len(code), 1 << 20, 32) + struct.pack_into("<II", body, record + 76, 512, 6) + struct.pack_into("<IIII", body, record + 120, 0x8400 | 0x1008, 32, 1, 1) + body.extend(code) + return pack(body) + + +def request_key(root, cdx): + key = 1469598103934665603 + for byte in b"native-container-1" + struct.pack("<Q", len(root)) + root + cdx: + key = ((key ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF + return f"{key:016x}" + + +def run(*command): + return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", timeout=100) + + +def main(fixture, compile_dxil, sdk): + with tempfile.TemporaryDirectory(prefix="x2w_raw_load_cache_") as scratch: + base = Path(scratch) + cache = base / "cache" + cache.mkdir() + root_path = base / "fixture.root" + result = run(fixture, "root", root_path) + if result.returncode != 0: + raise AssertionError((result.stdout, result.stderr)) + root = root_path.read_bytes() + + replays = [] + for name, offen, cache_flags, extra_flags, refused in ( + ("offen_glc_dlc", True, GLC_DLC, 0, False), + ("soffset_glc_dlc", False, GLC_DLC, 0, False), + ("offen_slc", True, 0, SLC, False), + ("offen_lds", True, GLC_DLC | (1 << 16), 0, True), + ("soffset_tfe", False, GLC_DLC, 1 << 23, True), + ): + directory = base / name + directory.mkdir() + cdx = container(offen, cache_flags, extra_flags) + key = request_key(root, cdx) + request = directory / f"req_{key}.cdx" + views = request.with_suffix(".views") + request.write_bytes(cdx) + request.with_suffix(".root").write_bytes(root) + views.write_text(VIEWS, encoding="ascii", newline="\n") + out_dir = base / f"{name}_out" + cso = out_dir / f"{key}.cs.cso" + result = run(compile_dxil, sdk, cache, "gfx1013-container-cs", "--requests", directory, out_dir) + if refused: + if result.returncode != 1 or REFUSAL not in result.stderr or cso.exists(): + raise AssertionError((name, result.stdout, result.stderr)) + continue + if result.returncode != 0 or "compiled=1 refused=0" not in result.stdout or not cso.exists(): + raise AssertionError((name, result.stdout, result.stderr)) + # Slot 0 starts at 0xA0000000 and increases by one per dword. + # OFFEN reads source word 4*lane. SOFFSET reads source word 3 in every lane. + expected = [0x69696969] * 72 + for lane in range(8): + expected[4 * lane] = 0xA0000000 + (4 * lane if offen else 3) + reference = directory / "expected.bin" + reference.write_bytes(words(*expected)) + replays.append((name, request, cso, views, reference)) + + for name, request, cso, views, reference in replays: + result = run(fixture, "replay", sdk, cache, request, cso, views, "hardware", "ok", "0", reference) + if result.returncode == 77: + print(result.stdout, result.stderr) + return 77 + if result.returncode != 0 or "output matches CPU reference (72 words)" not in result.stdout: + raise AssertionError((name, result.stdout, result.stderr)) + print(f"{name} matched the 72-word hardware readback") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_raw_store_cache_bits_check.py b/tests/native_raw_store_cache_bits_check.py new file mode 100644 index 0000000000..be08df7d50 --- /dev/null +++ b/tests/native_raw_store_cache_bits_check.py @@ -0,0 +1,68 @@ +"""Read back direct raw stores with cache hints and check modifier refusals.""" +import struct +import subprocess +import sys + +from native_bytewin_store_check import ( + GLC, GUARD_WORDS, IDXEN, LANE_BYTES, LANES, OUTPUT_WORDS, PLANE_BYTES, SENTINEL, + STORE_OPS, compute_program, main, request, sop1, +) + + +DLC = 1 << 15 +LDS = 1 << 16 +SLC = 1 << 22 +TFE = 1 << 23 +DWORD = STORE_OPS[0] +DWORDX4 = STORE_OPS[3] +REFUSAL = "raw store needs a linear byte offset" + + +def program(stores): + code = compute_program(ops=())[:-1] + # Groups (0,0,0) and (1,0,0) each run one wave32. + # Enable local lanes 0..7 in each group after initializing the data VGPRs. + code += [sop1(3, 126, 255), 0xff, sop1(3, 127, 128)] + for plane, (opcode, word1_flags) in enumerate(stores): + # One 1024-byte plane per store, 16 bytes per lane, including inactive lanes. + code += [opcode | plane * PLANE_BYTES, 0x80020208 | word1_flags] + return code + [0xBF810000] + + +def controls(cli, sdk, work, root): + for name, opcode, word1_flags in (("idxen", DWORD | GLC | IDXEN, 0), + ("lds", DWORD | GLC | LDS, 0), + ("tfe", DWORDX4 | GLC, TFE)): + marker = request(work, root, program(((opcode, word1_flags),))) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode and REFUSAL in result.stderr and not output.exists(), (name, result.stderr) + print(f"{name}: refused") + return 0 + + +def hardware(replay, sdk, work, root): + stores = ((DWORD | GLC, 0), (DWORDX4 | GLC, 0), (DWORD | DLC, 0), (DWORDX4, SLC)) + marker = request(work, root, program(stores)) + output = work / "stores.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + + expected = [SENTINEL] * OUTPUT_WORDS + for plane, width in enumerate((1, 4, 1, 4)): + for lane in range(LANES): + if lane % 32 < 8: + start = GUARD_WORDS + (plane * PLANE_BYTES + lane * LANE_BYTES) // 4 + expected[start:start + width] = [LANE_BYTES * lane + j + 1 for j in range(width)] + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for word, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (word, hex(got), hex(want)) + print("cache-hinted stores: updated words, untouched words and guards matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:], checks={"controls": controls, "hardware": hardware})) diff --git a/tests/native_rcp_iflag_check.py b/tests/native_rcp_iflag_check.py new file mode 100644 index 0000000000..0f4faf7907 --- /dev/null +++ b/tests/native_rcp_iflag_check.py @@ -0,0 +1,265 @@ +"""v_rcp_iflag_f32 (VOP1, VOP3, SDWA, DPP16) in direct Compute and Pixel DXIL.""" +from dataclasses import dataclass +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_direct_container_check import patched_pixel +from native_dpp_quad_check import request +import native_f16_alu_check as F +from native_packed_f16_inline_check import PROLOGUE +from native_scalar_lds_check import vmove +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl + + +def fbits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def fval(b): + return struct.unpack('<f', struct.pack('<I', b & 0xFFFFFFFF))[0] + + +def vop1(op, dst, src0): + return [0x7E000000 | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF)] + + +def vop3(op, dst, src0, *, abs_bit=0, neg_bit=0, clamp=0, omod=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | ((abs_bit & 1) << 8) | (dst & 0xFF) + w1 = ((neg_bit & 1) << 29) | ((omod & 3) << 27) | (src0 & 0x1FF) + return [w0, w1] + + +def sdwa(op, dst, src_reg, *, src_scalar=0, abs_bit=0, neg_bit=0, clamp=0, omod=0, + src_sel=6, dst_sel=6, dst_unused=0): + w0 = 0x7E000000 | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | 249 + ext = (((src_scalar & 1) << 23) | ((abs_bit & 1) << 21) | ((neg_bit & 1) << 20) | + ((src_sel & 7) << 16) | ((omod & 3) << 14) | ((clamp & 1) << 13) | + ((dst_unused & 3) << 11) | ((dst_sel & 7) << 8) | (src_reg & 0xFF)) + return [w0, ext] + + +def dpp(op, dst, src_vgpr, *, pattern=0xB1, row_mask=0xF, bank_mask=0xF): + w0 = 0x7E000000 | ((dst & 0xFF) << 17) | ((op & 0xFF) << 9) | 250 + ctrl = ((row_mask & 0xF) << 28) | ((bank_mask & 0xF) << 24) | ((pattern & 0x1FF) << 8) | (src_vgpr & 0xFF) + return [w0, ctrl] + + +def f32_inline(enc): + return {240: 0x3F000000, 241: 0xBF000000, 242: 0x3F800000, 243: 0xBF800000, + 244: 0x40000000, 245: 0xC0000000, 246: 0x40800000, 247: 0xC0800000}[enc] + + +@dataclass(frozen=True) +class Case: + name: str + form: str + src: int + val: int + abs_bit: int = 0 + neg_bit: int = 0 + clamp: int = 0 + omod: int = 0 + pixel_safe: bool = True + + def expected(self): + raw = f32_inline(self.src) if 240 <= self.src <= 248 else self.val + if self.abs_bit: + raw &= 0x7FFFFFFF + if self.neg_bit: + raw ^= 0x80000000 + r = 1.0 / fval(raw) + if self.omod == 1: + r *= 2.0 + elif self.omod == 2: + r *= 4.0 + elif self.omod == 3: + r *= 0.5 + if self.clamp: + r = 0.0 if r <= 0.0 else (1.0 if r >= 1.0 else r) + return fbits(r) + + +def all_cases(): + return [ + # VOP1: VGPR, SGPR, inline floats, literal. + Case('vop1_vgpr_two', 'vop1', 257, fbits(2.0)), + Case('vop1_vgpr_neg_four', 'vop1', 257, fbits(-4.0)), + Case('vop1_sgpr_eight', 'vop1', 10, fbits(8.0)), + Case('vop1_inline_240', 'vop1', 240, 0), + Case('vop1_inline_245', 'vop1', 245, 0), + Case('vop1_literal_eighth', 'vop1', 255, fbits(0.125)), + # VOP3: abs, neg, clamp, omod (*2, *4, *0.5). + Case('vop3_abs', 'vop3', 257, fbits(-2.0), abs_bit=1), + Case('vop3_neg', 'vop3', 257, fbits(4.0), neg_bit=1), + Case('vop3_clamp_hi', 'vop3', 257, fbits(0.25), clamp=1), + Case('vop3_clamp_lo', 'vop3', 257, fbits(-2.0), clamp=1), + Case('vop3_omod_2x', 'vop3', 257, fbits(4.0), omod=1), + Case('vop3_omod_4x', 'vop3', 257, fbits(8.0), omod=2), + Case('vop3_omod_half', 'vop3', 257, fbits(0.5), omod=3), + # SDWA: VGPR & SGPR DWORD with abs/neg/clamp. + Case('sdwa_vgpr_abs_neg', 'sdwa', 257, fbits(2.0), abs_bit=1, neg_bit=1), + Case('sdwa_sgpr_clamp', 'sdwa', 10, fbits(0.5), clamp=1), + # DPP16: quad_perm:[1,0,3,2] (lane 0 reads lane 1 = 0.25 -> 4.0) across compute lanes. + Case('dpp_quad_perm', 'dpp', 257, fbits(0.25), pixel_safe=False), + ] + + +def emit_case(c: Case, *, use_plain_rcp=False): + op_vop1 = 0x2A if use_plain_rcp else 0x2B + op_vop3 = 0x1AA if use_plain_rcp else 0x1AB + code = [] + if c.form == 'dpp': + code += F.mov(1, c.val) + code += dpp(op_vop1, 4, 1) + return code + if c.src >= 256: + code += F.mov(c.src - 256, c.val) + elif c.src <= 105: + code += F.smov(c.src, c.val) + if c.form == 'vop1': + code += vop1(op_vop1, 4, c.src) + if c.src == 255: + code.append(c.val) + elif c.form == 'vop3': + code += vop3(op_vop3, 4, c.src, abs_bit=c.abs_bit, neg_bit=c.neg_bit, clamp=c.clamp, omod=c.omod) + elif c.form == 'sdwa': + scalar = 1 if c.src <= 105 else 0 + reg = c.src if scalar else (c.src - 256) + code += sdwa(op_vop1, 4, reg, src_scalar=scalar, abs_bit=c.abs_bit, neg_bit=c.neg_bit, clamp=c.clamp) + else: + raise ValueError(c.form) + return code + + +def compute_program(cases, *, use_plain_rcp=False): + code = list(PROLOGUE) + want = [] + for slot, c in enumerate(cases): + code += emit_case(c, use_plain_rcp=use_plain_rcp) + F.store(slot * 4, 4) + want.append(c.expected()) + return code + [0xBF810000], want + + +def refusal_programs(): + return [ + # SDWA invalid dst_select=7 refused by SDWA profile validation. + (sdwa(0x2B, 4, 1, dst_sel=7) + [0xBF810000], 'unsupported SDWA destination modifier'), + # DPP16 partial row mask refused. + (dpp(0x2B, 4, 1, row_mask=0x5) + [0xBF810000], 'DPP requires a full-row, full-bank mask'), + ] + + +def controls(cli, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + ctrl_code, _ = compute_program(items, use_plain_rcp=True) + m_iflag = request(work, root, code) + m_plain = request(work, root, ctrl_code) + o_iflag = work / 'iflag.cso' + o_plain = work / 'plain.cso' + for m, o in ((m_iflag, o_iflag), (m_plain, o_plain)): + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode == 0 and o.is_file(), (r.stdout, r.stderr) + d_iflag = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', o_iflag], capture_output=True, text=True, check=True).stdout + d_plain = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', o_plain], capture_output=True, text=True, check=True).stdout + assert 'fdiv float 1.000000e+00,' in d_iflag and d_iflag == d_plain, 'v_rcp_iflag_f32 DXIL mismatch vs v_rcp_f32' + + # Also verify Pixel stage compilation equivalence. + ps_items = [c for c in items if c.pixel_safe][:4] + ps_iflag = work / 'ps_iflag.ps' + ps_plain = work / 'ps_plain.ps' + ps_iflag.write_bytes(pixel_program(ps_items, use_plain_rcp=False)) + ps_plain.write_bytes(pixel_program(ps_items, use_plain_rcp=True)) + for src, cso in ((ps_iflag, ps_iflag.with_suffix('.cso')), (ps_plain, ps_plain.with_suffix('.cso'))): + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', src, cso], capture_output=True, text=True) + assert r.returncode == 0 and cso.is_file(), (r.stdout, r.stderr) + dp_iflag = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', ps_iflag.with_suffix('.cso')], + capture_output=True, text=True, check=True).stdout + dp_plain = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', ps_plain.with_suffix('.cso')], + capture_output=True, text=True, check=True).stdout + assert dp_iflag == dp_plain, 'Pixel DXIL mismatch vs v_rcp_f32' + + refusals = refusal_programs() + for idx, (prog, why) in enumerate(refusals): + m = request(work, root, prog) + o = work / f'refused-{idx}.cso' + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], capture_output=True, text=True) + assert r.returncode != 0 and why in r.stderr, (idx, why, r.stdout, r.stderr) + assert not o.exists(), o + + print(f'native_rcp_iflag controls: {len(want)} Compute + {len(ps_items)} Pixel cases matched v_rcp_f32 DXIL; {len(refusals)} refusals matched') + return 0 + + +def hardware(replay, sdk, work, root): + items = all_cases() + code, want = compute_program(items) + marker = request(work, root, code) + output = work / 'out.bin' + run = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if run.returncode == 77: + return 77 + run.check_returncode() + words_out = list(struct.unpack(f'<{F.WORDS}I', output.read_bytes())) + expected = [F.SENTINEL] * F.WORDS + for group in range(F.GROUPS): + for lane in range(32): + head = F.BASE + group * 1024 + lane * 32 + expected[head:head + len(want)] = want + mismatch = next((i for i, (a, b) in enumerate(zip(words_out, expected, strict=True)) if a != b), None) + assert mismatch is None, (mismatch, hex(words_out[mismatch]), hex(expected[mismatch])) + print(f'native_rcp_iflag compute hardware: {len(want)} cases matched across {F.GROUPS}x32 lanes and guards') + return 0 + + +def pixel_program(quad, *, use_plain_rcp=False): + code = [] + for idx, c in enumerate(quad): + code += emit_case(c, use_plain_rcp=use_plain_rcp) + code.append(vmove(8 + idx, 256 + 4)) + return patched_pixel(len(code), code, export=(0xF800180F, 0x0B0A0908)) + + +def pixel(cli, sdk, renderer, adapter, work): + items = [c for c in all_cases() if c.pixel_safe] + while len(items) % 4: + items.append(items[-1]) + vs = compile_hlsl(str(Path(sdk) / 'dxc.exe'), 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + quads = [items[i:i + 4] for i in range(0, len(items), 4)] + for idx, quad in enumerate(quads): + shader = work / f'rcp-{idx}.ps' + shader.write_bytes(pixel_program(quad)) + cso = shader.with_suffix('.cso') + build = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-ps', shader, cso], + capture_output=True, text=True, timeout=30) + assert build.returncode == 0, ([c.name for c in quad], build.stdout, build.stderr) + ref = work / 'expected.bin' + ref.write_bytes(struct.pack('<4I', *(c.expected() for c in quad))) + run = subprocess.run([renderer, adapter, '--startup-pixel-words', vs, cso, '1', '1', ref], + capture_output=True, text=True, timeout=30) + if run.returncode == 77: + return 77 + assert run.returncode == 0, (idx, [c.name for c in quad], run.stdout, run.stderr) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, run.stdout + print(f'native_rcp_iflag pixel ({adapter}): {len(quads)} quad draws matched') + return 0 + + +def main(mode, tool, sdk=None, *args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if mode == 'pixel': + return pixel(tool, sdk, args[0], args[1], work) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'compute': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_recording_check.cpp b/tests/native_recording_check.cpp new file mode 100644 index 0000000000..602aba393a --- /dev/null +++ b/tests/native_recording_check.cpp @@ -0,0 +1,228 @@ +#include "startup_stubs/native_recording.h" +#include "native_compute_pipeline.h" +#include "direct_compute_cache.h" +#include "native_graphics_bindings.h" +#include "native_texture_store_view.h" +#include "startup_stubs/native_dispatch_states.h" +#include <dxgi1_4.h> +#include <cstdio> +#include <memory> +#include <filesystem> +#include <fstream> +#include <vector> + +static int graphics_pso(ID3D12Device *device, ID3D12RootSignature *root, D3D12_SHADER_BYTECODE vs, + D3D12_SHADER_BYTECODE gs, D3D12_SHADER_BYTECODE ps) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC p{}; + p.VS = vs; + p.GS = gs; + p.PS = ps; + p.pRootSignature = root; + p.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + p.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + p.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + p.RasterizerState.DepthClipEnable = TRUE; + p.BlendState.RenderTarget[0] = {FALSE, + FALSE, + D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, + D3D12_BLEND_ONE, + D3D12_BLEND_ZERO, + D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, + D3D12_COLOR_WRITE_ENABLE_ALL}; + p.NumRenderTargets = 1; + p.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + p.SampleDesc.Count = 1; + p.SampleMask = UINT_MAX; + Microsoft::WRL::ComPtr<ID3D12PipelineState> pipeline; + const HRESULT hr = device->CreateGraphicsPipelineState(&p, IID_PPV_ARGS(&pipeline)); + if (FAILED(hr)) { + std::fprintf(stderr, "graphics PSO failed: 0x%08lx\n", static_cast<unsigned long>(hr)); + return 10; + } + return 0; +} + +static std::string file_bytes(const std::filesystem::path &path) { + std::ifstream file(path, std::ios::binary); + if (!file) throw std::runtime_error("missing shader fixture"); + return {std::istreambuf_iterator<char>(file), {}}; +} + +static int dispatch_states(ID3D12Device *device) { + using x2w_startup::NativeDispatchStates; + const auto rg = x2w::native_half_store_format(x2w::ComputeViewKind::half2_texture_uav); + if (!rg.accepts(DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_TYPELESS) || + !rg.accepts(DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_FLOAT) || + rg.accepts(DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_TYPELESS) || + rg.accepts(DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16B16A16_TYPELESS)) return 22; + struct View { + Microsoft::WRL::ComPtr<ID3D12Resource> resource; + bool write{}; + x2w_startup::NativeTextureWindow texture{}; + struct { bool upload = false; } buffer; + }; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = desc.Height = 8; + desc.DepthOrArraySize = 6; + desc.MipLevels = 3; + desc.Format = DXGI_FORMAT_R32_FLOAT; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Microsoft::WRL::ComPtr<ID3D12Resource> texture; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&texture)))) return 15; + // Read mips 0 and 1 on all six faces; write mip 2. Two duplicate SRVs + // exercise the merge. The read-only plan does not expand the face range. + View read{texture, false, {0,2,0,6}}, write{texture, true, {2,1,0,6}}; + NativeDispatchStates reads(std::vector<View>{read, read}); + unsigned whole = 0; + reads.whole_states([&](auto *r, auto state) { + if (r == texture.Get() && state == D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE) ++whole; + }); + if (whole != 1 || !reads.split().empty() || !reads.writes().empty()) return 16; + NativeDispatchStates mixed(std::vector<View>{read, write, read, write}); + if (!mixed.mixed(texture.Get()) || mixed.split().size() != 18 || + mixed.writes().size() != 1 || mixed.writes()[0].UAV.pResource != texture.Get()) return 17; + for (unsigned sub = 0; sub < 18; ++sub) { + const auto &t = mixed.split()[sub].Transition; + if (t.Subresource != sub || t.StateBefore != D3D12_RESOURCE_STATE_COMMON || + t.StateAfter != (sub % 3 == 2 ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) return 18; + } + mixed.reverse(); + if (mixed.split()[17].Transition.StateAfter != D3D12_RESOURCE_STATE_COMMON) return 19; + // All mips of faces 0-3 vs all mips of faces 4-5 are adjacent. + read.texture = {0,3,0,4}; + write.texture = {0,3,4,2}; + if (NativeDispatchStates(std::vector<View>{write,read}).split().size() != 18) return 20; + write.texture = {1,1,3,1}; + try { NativeDispatchStates invalid(std::vector<View>{write, read}); } + catch (const std::runtime_error &e) { + if (std::string(e.what()) == "overlapping compute SRV and UAV subresource 10") return 0; + } + return 21; +} + +// Allocation and lifetime smoke. No command list or GPU workload is required. +int wmain(int argc, wchar_t **argv) { + using Microsoft::WRL::ComPtr; + using x2w_startup::NativeRecording; + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> warp; + ComPtr<ID3D12Device> device; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp))) || + FAILED(D3D12CreateDevice(warp.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("WARP device unavailable"); + return 77; + } + try { + if (argc == 2 && std::wstring_view(argv[1]) == L"--subresources") + return dispatch_states(device.Get()); + if (argc > 1) { + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6) + return 77; + } + if (argc == 7 && std::wstring_view(argv[1]) == L"--graphics-sampler") { + const auto a = file_bytes(argv[3]), b = file_bytes(argv[4]), guest_root = file_bytes(argv[5]); + x2w::ShaderDxilCompiler compiler(argv[2]); + for (bool warm : {false, true}) { + bool hit = false; + auto pair = x2w::prepare_direct_graphics(a, b, argv[6], hit, guest_root); + x2w::NativeGraphicsBindings bindings(pair); + auto statics = x2w_startup::decode_statics(bindings.samplers); + if (hit != warm || bindings.srv_count != 2 || bindings.views.size() != 4 || statics.size() != 2 || + bindings.views[2].kind != x2w::ComputeViewKind::half_scalar_uav || bindings.views[2].shader_register != 0 || + bindings.views[2].byte_offset != 64 || bindings.views[3].byte_offset != 32 || + bindings.views[3].shader_register != 1 || + bindings.views[0].kind != x2w::ComputeViewKind::comparison_texture_srv || + statics[0].Filter != D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT || + statics[0].ComparisonFunc != D3D12_COMPARISON_FUNC_LESS || + statics[1].Filter != D3D12_FILTER_MIN_MAG_MIP_POINT) + return 13; + ComPtr<ID3D12RootSignature> root; + if (FAILED(x2w_startup::create_translated_root(device.Get(), 1, bindings.srv_count, bindings.samplers, &root, 2))) + return 8; + auto vs = compiler.compile(pair.vertex.dxil_ir, L"vs_6_6", argv[6], x2w::ShaderSourceFormat::dxil_ir); + auto ps = compiler.compile(pair.pixel.dxil_ir, L"ps_6_6", argv[6], x2w::ShaderSourceFormat::dxil_ir); + if (vs.cache_hit != warm || ps.cache_hit != warm) return 14; + int result = graphics_pso(device.Get(), root.Get(), {vs.dxil.data(), vs.dxil.size()}, {}, + {ps.dxil.data(), ps.dxil.size()}); + if (result) return result; + } + std::puts("WARP created cold and cached graphics pipelines with regular/comparison samples and vertex/pixel UAVs"); + return 0; + } + if (argc == 5 && std::wstring_view(argv[1]) == L"--sampler") { + D3D12_FEATURE_DATA_D3D12_OPTIONS1 options{}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options, sizeof options)) || + !options.WaveOps || options.WaveLaneCountMin > 32 || options.WaveLaneCountMax < 32) { + std::printf("compute requires wave32: WaveOps=%u range=%u..%u\n", options.WaveOps, + options.WaveLaneCountMin, options.WaveLaneCountMax); + return 77; + } + x2w::ShaderDxilCompiler compiler(argv[2]); + for (bool warm : {false, true}) { + auto pipeline = x2w::create_native_compute_pipeline(device.Get(), compiler, argv[3], 0, argv[4], true); + if (!pipeline.state || pipeline.frontend_cache_hit != warm || pipeline.cache_hit != warm || + pipeline.srv_count != 2 || pipeline.bindings[0].kind != x2w::ComputeViewKind::comparison_texture_srv) + return 11; + bool hit = false; + const auto shader = x2w::prepare_direct_compute(argv[3], 0, true, argv[4], hit); + if (!hit || shader.samplers.size() != 2 || !shader.samplers[0].comparison || + shader.samplers[1].comparison || shader.samplers[0].words != shader.samplers[1].words) + return 12; + } + std::puts("WARP created cold and cached comparison-sampling compute pipelines"); + return 0; + } + if (argc == 4) { + D3D12_ROOT_SIGNATURE_DESC empty{}; + ComPtr<ID3DBlob> blob; + ComPtr<ID3D12RootSignature> root; + if (FAILED(D3D12SerializeRootSignature(&empty, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)))) + return 8; + const auto vs = file_bytes(argv[1]), gs = file_bytes(argv[2]), ps = file_bytes(argv[3]); + return graphics_pso(device.Get(), root.Get(), {vs.data(), vs.size()}, {gs.data(), gs.size()}, {ps.data(), ps.size()}); + } + if (argc != 1) + return 1; + auto recording = std::make_shared<NativeRecording>(); + if (recording->allocate(device.Get(), 0).heap) + return 1; + const auto first = recording->allocate(device.Get(), 1); + const UINT page_size = first.heap->GetDesc().NumDescriptors; + const auto rest = recording->allocate(device.Get(), page_size - 1); + if (rest.heap != first.heap || !first.increment || rest.gpu.ptr != first.gpu.ptr + first.increment || + rest.cpu.ptr != first.cpu.ptr + first.increment) + return 2; + const auto next = recording->allocate(device.Get(), 1); + if (next.heap == first.heap) + return 3; + recording->retain(first.heap); + if (recording->objects.size() != 2) + return 4; + + auto submit1 = recording, submit2 = recording; + std::weak_ptr<NativeRecording> previous = recording; + recording = std::make_shared<NativeRecording>(); + auto fresh = recording->allocate(device.Get(), 1); + submit1.reset(); + if (fresh.heap == first.heap || first.heap->GetDesc().NumDescriptors != page_size || previous.expired()) + return 5; + submit2.reset(); + if (!previous.expired()) + return 6; + std::puts("WARP descriptor ranges, rollover, reset and repeated submission ownership passed"); + } catch (const std::exception &error) { + std::fprintf(stderr, "%s\n", error.what()); + return 7; + } +} diff --git a/tests/native_round_f16_check.py b/tests/native_round_f16_check.py new file mode 100644 index 0000000000..5d18910284 --- /dev/null +++ b/tests/native_round_f16_check.py @@ -0,0 +1,204 @@ +"""Direct compute v_floor_f16, v_ceil_f16, v_trunc_f16 and v_rndne_f16 (VOP1/VOP3A, inline f16, high-half preserving).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +HIGH_SEED = 0xBEEF0000 + +CASES = ( + 0xCAFE8000, # -0.0h (with high junk in src0) + 0x00000001, # +min_sub (2^-24) + 0x00008001, # -min_sub (-2^-24) + 0x00003800, # +0.5h (rndne ties to +0.0h) + 0x00003E00, # +1.5h (rndne ties to +2.0h) + 0x00004100, # +2.5h (rndne ties to +2.0h) + 0x0000BE00, # -1.5h (floor=-2, ceil=-1, trunc=-1, rndne=-2) + 0x000063FF, # +1023.5h (ceil/rndne carry into exponent -> 1024.0h = 0x6400) +) + +# Inline float constants: 0.5, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, 1/(2*pi) (0x3118). +INLINE_CASES = ( + (240, 0x3800), + (241, 0xB800), + (242, 0x3C00), + (243, 0xBC00), + (244, 0x4000), + (245, 0xC000), + (246, 0x4400), + (248, 0x3118), +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_unary(op, vdst, src0, *, abs0=0, neg0=0, clamp=0, omod=0, op_sel=0): + w0 = (0xD4000000 | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) | + ((op_sel & 0xF) << 11) | ((abs0 & 1) << 8) | (vdst & 0xFF)) + w1 = ((neg0 & 1) << 29) | ((omod & 3) << 27) | (src0 & 0x1FF) + return [w0, w1] + + +def program_main(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, bits in enumerate(CASES): + code += v_mov_lit(2, bits) + code += v_mov_lit(4, HIGH_SEED | 0x1111) + [vop1(0x5B, 4, 258), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + code += v_mov_lit(4, HIGH_SEED | 0x2222) + [vop1(0x5C, 4, 258), 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + code += v_mov_lit(4, HIGH_SEED | 0x3333) + vop3_unary(0x1DD, 4, 258) + [0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + code += v_mov_lit(4, HIGH_SEED | 0x4444) + vop3_unary(0x1DE, 4, 258) + [0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def program_inline(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, (src0, _f16) in enumerate(INLINE_CASES): + code += v_mov_lit(4, HIGH_SEED | 0x1111) + [vop1(0x5B, 4, src0), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + code += v_mov_lit(4, HIGH_SEED | 0x2222) + [vop1(0x5C, 4, src0), 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + code += v_mov_lit(4, HIGH_SEED | 0x3333) + vop3_unary(0x1DD, 4, src0) + [0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + code += v_mov_lit(4, HIGH_SEED | 0x4444) + vop3_unary(0x1DE, 4, src0) + [0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def round_f16(bits, mode, *, ties_away=False, lose_neg_zero=False): + bits &= 0xFFFF + sign = 0 if lose_neg_zero else (bits & 0x8000) + neg = (bits & 0x8000) != 0 + mag = bits & 0x7FFF + exp = (bits >> 10) & 0x1F + if exp >= 25: + return bits + if exp < 15: + if mode == 'trunc': + return sign + if mode == 'floor': + return 0xBC00 if (mag != 0 and neg) else sign + if mode == 'ceil': + return 0x3C00 if (mag != 0 and not neg) else sign + if ties_away: + return (bits & 0x8000) | 0x3C00 if mag >= 0x3800 else sign + return (bits & 0x8000) | 0x3C00 if mag > 0x3800 else sign + frac_bits = 25 - exp + unit = 1 << frac_bits + mask = unit - 1 + half = unit >> 1 + frac = bits & mask + base = bits & (~mask & 0xFFFF) + if mode == 'trunc': + return base + if mode == 'floor': + return (base + unit) & 0xFFFF if (neg and frac != 0) else base + if mode == 'ceil': + return (base + unit) & 0xFFFF if ((not neg) and frac != 0) else base + if ties_away: + inc = frac >= half + else: + inc = frac > half or (frac == half and (base & unit) != 0) + return (base + unit) & 0xFFFF if inc else base + + +def reference_main(*, ties_away=False, lose_neg_zero=False, zero_high=False): + hi = 0 if zero_high else HIGH_SEED + words = [SENTINEL] * 8 + for _lane in range(64): + for bits in CASES: + words.extend(( + hi | round_f16(bits, 'floor', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + hi | round_f16(bits, 'ceil', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + hi | round_f16(bits, 'trunc', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + hi | round_f16(bits, 'rndne', ties_away=ties_away, lose_neg_zero=lose_neg_zero), + )) + return words + [SENTINEL] * 8 + + +def reference_inline(*, inline_as_zero=False, zero_high=False): + hi = 0 if zero_high else HIGH_SEED + words = [SENTINEL] * 8 + for _lane in range(64): + for _src0, f16 in INLINE_CASES: + bits = 0x0000 if inline_as_zero else f16 + words.extend(( + hi | round_f16(bits, 'floor'), + hi | round_f16(bits, 'ceil'), + hi | round_f16(bits, 'trunc'), + hi | round_f16(bits, 'rndne'), + )) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for tag, prog in (('main', program_main()), ('inline', program_inline())): + sub = work / tag + sub.mkdir(exist_ok=True) + marker = request(sub, root, prog) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (tag, result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'lshr i32 ' in dump, dump + if tag == 'inline': + assert '14336' in dump and '12568' in dump, 'inline f16 0.5 (0x3800) and 1/(2*pi) (0x3118) must appear in DXIL' + for tag, bad, msg in ( + ('omod', vop3_unary(0x1DB, 4, 258, omod=1) + [0xBF810000], 'unsupported v_floor_f16 operand modifiers'), + ('op_sel', vop3_unary(0x1DE, 4, 258, op_sel=1) + [0xBF810000], 'unsupported v_rndne_f16 operand modifiers'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), (tag, bad_res.stdout, bad_res.stderr) + assert reference_main() != reference_main(ties_away=True) + assert reference_main() != reference_main(lose_neg_zero=True) + assert reference_main() != reference_main(zero_high=True) + assert reference_inline() != reference_inline(inline_as_zero=True) + print('v_floor/ceil/trunc/rndne_f16 DXIL verified; invalid modifiers refused; tie, -0, inline and high-half controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + for tag, prog, expected in (('main', program_main(), reference_main()), + ('inline', program_inline(), reference_inline())): + sub = work / f'hw_{tag}' + sub.mkdir(exist_ok=True) + marker = request(sub, root, prog) + output = work / f'out_{tag}.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'{tag} word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print(f'{tag}: 2048 result words (high halves kept) and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_round_f16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_rtv_variant_check.py b/tests/native_rtv_variant_check.py new file mode 100644 index 0000000000..58980d090a --- /dev/null +++ b/tests/native_rtv_variant_check.py @@ -0,0 +1,327 @@ +"""RTV variant requests (req_<key>.rtv) resolved, compiled and cached by compile_dxil --requests (#2980). + +usage: + native_rtv_variant_check.py controls <compile_dxil> <DXC directory> + native_rtv_variant_check.py e2e <compile_dxil> <startup_stream_consumer> <DXC directory> <warp|hardware> + +The pair is source-built: the vertex container of native_startup_request_cache_check.py, which covers the viewport +from the vertex index, and a pixel container that moves four literal words into v0..v3 and exports them to MRT0. +A variant request is the ASCII text "rtv1 <base key> <format> ...", in a file named by the FNV-1a hash of that text +(tools/startup/gfx2hlsl.py request_source). The reader checks it and the base parts it names, the formats type the +pixel stage's color targets, and the variant is published as <variant key>.{vs.cso,ps.cso,txt} with the request as +the manifest's last line, which is what the runtime matches. + +controls (no device): +1. One directory holds the base request and four variants of it: R16G16B16A16_UINT, R16G16B16A16_SINT and + R16G16_UINT, each with an R8G8B8A8_UNORM second target, and R32G32B32A32_FLOAT. With an empty compiler cache + the tool compiles all five with four parallel workers; the two UINT variants have the same target types and + share one frontend cache entry. Each variant's manifest is the base manifest plus its request line, the report + names the target types (u32, i32, f32), the compiled pixel stages declare SV_Target0 as uint, int and float, + and the base manifest and stages are those of the base alone. A second run hits the frontend and bytecode + caches for every request and publishes the same bytes. gfx2hlsl.pending_keys then finds nothing left to do. +2. Refusals, each in a fresh directory with only <key>.fail and its reason under the variant key: a forged variant key, base + content that no longer matches the base key, no format, nine formats, a format above 32 bits, a trailing + newline, a missing base, the two integer formats without a verified readback (7 and 8) in the exported slot, + and a forged variant file under the base's own key. Wherever the base request is intact it still compiles. + Format 7 in a slot the pixel stage does not export to is accepted, and refused again when it is moved to the + exported slot although the frontend entry of those target types is then cached. A base with an input layout + publishes its stages without a manifest, as before; its variant is refused for having none, and again when + the layout no longer matches the base key. +3. A published variant whose base then changes is refused on the next run, and every manifest of the directory + is withdrawn. +4. A pixel container whose own output signature says uint: the UINT variant compiles, the FLOAT variant is + refused by name, and the base pair publishes no manifest (as before this change). + +e2e: the consumer creates the pair through device slot 86 and draws one pixel into a target of each format, which +makes the stand-in publish the base request and the three variant requests. The tool compiles the directory with +an empty compiler cache and again with the populated one. The consumer then draws each format in a new process: +the stand-in loads <variant key>.txt, creates the desktop pipeline with the bound formats and the target is read +back after the fence. Expected, for the exported words ffff7ffe, 15, eb, 68: UINT 16 clamps to ffff 0015 00eb 0068, +SINT 16 clamps to 8000 0015 00eb 0068, FLOAT 32 keeps all four words bit for bit (the first is a NaN with a +payload), and the untyped RGBA8 base draw stores 00000000 over the blue clear. Exit 77 without the adapter. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_startup_request_cache_check import compile_graphics_table_root, put_graphics_request, stream_vertex_container +from native_direct_container_check import patched_pixel, publish, signature, vertex +from startup_stream_draw_check import vop1 +import gfx2hlsl as G + +WORDS = (0xffff7ffe, 0x15, 0xeb, 0x68) +UINT16, SINT16, FLOAT32, UNORM8, UINT16_RG = 12, 14, 2, 28, 36 +# request formats, report types, SV_Target0 type, MRT0 bytes, bytes of the second (RGBA8, cleared) target +VARIANTS = ( + (UINT16, (UINT16, UNORM8), 'u32,f32', 'uint', 'ffff1500eb006800', '0000ffff'), + (SINT16, (SINT16, UNORM8), 'i32,f32', 'int', '00801500eb006800', '0000ffff'), + (FLOAT32, (FLOAT32,), 'f32', 'float', struct.pack('<4I', *WORDS).hex(), ''), +) + + +def pixel_stage(words=WORDS, parts=()): + prefix = [] + for register, value in enumerate(words): + prefix += [vop1(1, register, 255), value] + return patched_pixel(len(prefix), prefix, export=(0xf800180f, 0x03020100), input_signature=parts) + + +def put_variant(cache, base, formats, name_key=None, text=None): + line = text if text is not None else 'rtv1 ' + ' '.join(map(str, (base, *formats))) + key = G.fnv(line.encode('ascii')) if name_key is None else name_key + (cache / f'req_{key:016x}.rtv').write_bytes(line.encode('ascii')) + return key, line + + +def run_tool(cli, sdk, frontend, cache, jobs=()): + return subprocess.run([cli, sdk, frontend, *jobs, 'gfx1013-container-pair', '--requests', cache, cache], + capture_output=True, text=True) + + +def target_types(sdk, blob): + listing = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', blob], capture_output=True, text=True, check=True).stdout + found = re.findall(r'^\s*;\s+SV_Target\s+(\d+)\s+\S+\s+\d+\s+\S+\s+(float|uint|int)\b', listing, re.M) + assert found, listing[:2000] + return dict(found) + + +def published(cache, key): + return sorted(p.name for p in cache.glob(f'{key:016x}.*')) + + +def only_failure(cache, key, reason): + """A refused request leaves <key>.fail with its reason, and no stage or manifest.""" + assert published(cache, key) == [f'{key:016x}.fail'], published(cache, key) + assert reason in (cache / f'{key:016x}.fail').read_text(encoding='ascii'), (cache / f'{key:016x}.fail').read_text() + + +def check_published(cli, sdk, frontend, cache, base, variants, jobs=(), shared=0): + """variants: (key, line, report types, SV_Target0 type). Cold run, checks, warm run. Returns the cold report. + + shared: how many variants have the target types of another one. Such a pair has one frontend cache entry, so + with parallel jobs the later one may already hit it in the cold run.""" + cold = run_tool(cli, sdk, frontend, cache, jobs) + count = len(variants) + 1 + assert cold.returncode == 0 and f'requests={count} compiled={count} refused=0' in cold.stdout, (cold.stdout, cold.stderr) + # Every pair is linked anew. The stage bytecode cache already hits within this run: the requests share one vertex + # stage, and a pixel stage with float targets is the base's. + assert count - shared <= cold.stdout.count('graphics_pair frontend_cache_hit=0') <= count, cold.stdout + # One vertex stage and one pixel stage per distinct set of target types; parallel workers can compile one twice. + stages = 1 + len({types for _, _, types, _ in variants} | {'f32'}) + compiled = cold.stdout.count('cold_compile_and_publish_ms=') + assert compiled >= stages if jobs else compiled == stages, cold.stdout + base_manifest = (cache / f'{base:016x}.txt').read_text(encoding='ascii') + assert 'rtv1' not in base_manifest and base_manifest.startswith('x2w-manifest 1\n'), base_manifest + assert target_types(sdk, cache / f'{base:016x}.ps.cso') == {'0': 'float'} + for key, line, types, target in variants: + assert published(cache, key) == [f'{key:016x}.ps.cso', f'{key:016x}.txt', f'{key:016x}.vs.cso'], published(cache, key) + manifest = cache / f'{key:016x}.txt' + assert manifest.read_text(encoding='ascii') == base_manifest + line + '\n', manifest.read_text(encoding='ascii') + assert f'rtv_variant {line} types={types}\n' in cold.stdout, cold.stdout + assert target_types(sdk, cache / f'{key:016x}.ps.cso') == {'0': target}, (line, target) + assert manifest.stat().st_mtime_ns >= max((cache / f'{key:016x}{e}').stat().st_mtime_ns for e in ('.vs.cso', '.ps.cso')) + before = {p.name: p.read_bytes() for p in cache.iterdir() if not p.name.startswith('req_')} + warm = run_tool(cli, sdk, frontend, cache, jobs) + assert warm.returncode == 0 and f'requests={count} compiled={count} refused=0' in warm.stdout, (warm.stdout, warm.stderr) + assert warm.stdout.count('graphics_pair frontend_cache_hit=1') == count, warm.stdout + assert warm.stdout.count('cache_hit_ms=') == 2 * count and 'cold_compile_and_publish_ms=' not in warm.stdout, warm.stdout + assert {p.name: p.read_bytes() for p in cache.iterdir() if not p.name.startswith('req_')} == before + assert G.pending_keys(str(cache), skip_failed=False) == [], 'published entries are not recognised as complete' + return cold + + +def check_controls(cli, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / 'frontend' + root = compile_graphics_table_root(Path(sdk), work) + vs, ps = stream_vertex_container(), pixel_stage() + + cache = work / 'cache' + cache.mkdir() + base = put_graphics_request(cache, vs, ps, root) + variants = [put_variant(cache, base, formats) + (types, target) for _, formats, types, target, _, _ in VARIANTS] + # R16G16_UINT has the target types of the first variant, so the two share a frontend cache entry. Four + # workers compile the five requests side by side. + variants.append(put_variant(cache, base, (UINT16_RG, UNORM8)) + ('u32,f32', 'uint')) + check_published(cli, sdk, frontend, cache, base, variants, jobs=('--jobs', '4'), shared=1) + + # 3. The base changes under a published variant: the next run refuses it and withdraws its manifest. + (cache / f'req_{base:016x}.b').write_bytes(pixel_stage((1, 2, 3, 4))) + stale = run_tool(cli, sdk, frontend, cache) + assert stale.returncode != 0 and 'requests=5 compiled=0 refused=5' in stale.stdout, (stale.stdout, stale.stderr) + assert stale.stderr.count('RTV variant source: graphics request key mismatch') == len(variants), stale.stderr + assert not list(cache.glob('*.txt')), 'a request with a changed base kept a loadable manifest' + + refusals = 0 + + def refuse(label, expected, setup, base_intact=True): + nonlocal refusals + folder = work / label + folder.mkdir() + base_key = put_graphics_request(folder, vs, ps, root) + key = setup(folder, base_key) + result = run_tool(cli, sdk, frontend, folder) + assert result.returncode != 0 and expected in result.stderr, (label, result.returncode, result.stderr) + only_failure(folder, key, expected) + if base_intact: + assert 'compiled=1 refused=1' in result.stdout, (label, result.stdout) + assert (folder / f'{base_key:016x}.txt').is_file(), f'{label}: the base pair no longer compiles' + refusals += 1 + + def remove_base(folder, base_key): + for extension in ('.a', '.b', '.root'): + (folder / f'req_{base_key:016x}{extension}').unlink() + return put_variant(folder, base_key, (UINT16, UNORM8))[0] + + def change_base(folder, base_key): + key = put_variant(folder, base_key, (UINT16, UNORM8))[0] + (folder / f'req_{base_key:016x}.b').write_bytes(pixel_stage((1, 2, 3, 4))) + return key + + invalid = 'invalid RTV variant request' + refuse('forged-key', invalid, + lambda d, b: put_variant(d, b, (UINT16, UNORM8), name_key=G.fnv(f'rtv1 {b} 12 28'.encode()) ^ 1)[0]) + refuse('base-changed', 'RTV variant source: graphics request key mismatch', change_base, base_intact=False) + refuse('no-format', invalid, lambda d, b: put_variant(d, b, ())[0]) + refuse('nine-formats', invalid, lambda d, b: put_variant(d, b, (UNORM8,) * 9)[0]) + refuse('wide-format', 'invalid RTV variant values', lambda d, b: put_variant(d, b, (1 << 32,))[0]) + refuse('trailing-newline', invalid, lambda d, b: put_variant(d, b, (), text=f'rtv1 {b} 12 28\n')[0]) + refuse('missing-base', 'RTV variant source: missing or oversized .a', remove_base, base_intact=False) + refuse('unverified-uint', 'unverified UINT RTV format 7', lambda d, b: put_variant(d, b, (7, UNORM8))[0]) + refuse('unverified-sint', 'unverified SINT RTV format 8', lambda d, b: put_variant(d, b, (8, UNORM8))[0]) + # Both markers under one key are one request, the variant: a forged one refuses that key and nothing else runs + # under it. + refuse('forged-base-key', invalid, lambda d, b: put_variant(d, b, (UINT16, UNORM8), name_key=b)[0], base_intact=False) + + # As in gfx2hlsl.py, an unverified format in a slot the pixel stage does not export to is not refused. The + # frontend entry of these target types is cached by the first request, so the second is refused on a hit. + unwritten = work / 'unwritten' + unwritten.mkdir() + slot_base = put_graphics_request(unwritten, vs, ps, root) + accepted, line = put_variant(unwritten, slot_base, (UINT16, 7)) + result = run_tool(cli, sdk, frontend, unwritten) + assert result.returncode == 0 and f'rtv_variant {line} types=u32,u32\n' in result.stdout, (result.stdout, result.stderr) + assert (unwritten / f'{accepted:016x}.txt').is_file() + (unwritten / f'req_{accepted:016x}.rtv').unlink() + rejected, _ = put_variant(unwritten, slot_base, (7, UINT16)) + result = run_tool(cli, sdk, frontend, unwritten) + assert result.returncode != 0 and 'unverified UINT RTV format 7' in result.stderr, (result.stdout, result.stderr) + only_failure(unwritten, rejected, 'unverified UINT RTV format 7') + refusals += 1 + + # A base with an input layout: the layout is read and checked with the base key, the base publishes its + # stages without a manifest (as before), and its variant is refused because it would have none either. + fetched = work / 'layout' + layout_base = int(publish(fetched, vertex(True), ps, root, b'ia1 1\nposition 0 2 3 4294967295 0 0\n'), 16) + layout_variant, _ = put_variant(fetched, layout_base, (UINT16, UNORM8)) + result = run_tool(cli, sdk, frontend, fetched) + assert result.returncode != 0 and 'requests=2 compiled=1 refused=1' in result.stdout, (result.stdout, result.stderr) + assert 'RTV variant has no runtime manifest' in result.stderr, result.stderr + assert published(fetched, layout_base) == [f'{layout_base:016x}.ps.cso', f'{layout_base:016x}.vs.cso'] + only_failure(fetched, layout_variant, 'RTV variant has no runtime manifest') + (fetched / f'req_{layout_base:016x}.ia').write_bytes(b'ia1 1\nposition 0 2 3 0 0 0\n') + result = run_tool(cli, sdk, frontend, fetched) + assert 'RTV variant source: graphics request key mismatch' in result.stderr, result.stderr + only_failure(fetched, layout_variant, 'RTV variant source: graphics request key mismatch') + refusals += 2 + + # 4. A container whose own signature types the target: the format has to agree with it. + typed = work / 'signature' + typed.mkdir() + uint_ps = pixel_stage(parts=[(b'OSG1', signature(b'SV_Target', system=64, component=1))]) + typed_base = put_graphics_request(typed, vs, uint_ps, root) + agree, _ = put_variant(typed, typed_base, (UINT16, UNORM8)) + disagree, _ = put_variant(typed, typed_base, (FLOAT32,)) + result = run_tool(cli, sdk, frontend, typed) + assert result.returncode != 0 and 'requests=3 compiled=2 refused=1' in result.stdout, (result.stdout, result.stderr) + assert 'RTV variant format disagrees with the pixel signature of target 0' in result.stderr, result.stderr + assert (typed / f'{agree:016x}.txt').is_file() and target_types(sdk, typed / f'{agree:016x}.ps.cso') == {'0': 'uint'} + only_failure(typed, disagree, 'RTV variant format disagrees with the pixel signature of target 0') + assert not (typed / f'{typed_base:016x}.txt').exists(), 'a base pair with an integer target published a manifest' + + print(f'native_rtv_variant controls: the base and 4 variants (uint, int, float SV_Target0) compiled cold and warm ' + f'by 4 workers with identical bytes; {refusals} refusals left only a .fail; a changed base withdrew every manifest; ' + f'a signature that disagrees with the format is refused') + return 0 + + +def check_e2e(cli, consumer, sdk, backend): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + cache = work / 'cache' + cache.mkdir() + vs, ps, root, pixels = (work / name for name in ('vs', 'ps', 'root', 'pixels')) + vs.write_bytes(stream_vertex_container()) + ps.write_bytes(pixel_stage()) + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache)) + env.pop('X2W_NATIVE_SHADERS', None) + + def draw(fmt=None): + pixels.unlink(missing_ok=True) + result = subprocess.run([consumer, vs, ps, root, backend, pixels] + ([str(fmt)] if fmt else []), + env=env, capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout + result.stderr[-2000:], end='') + print(f'native_rtv_variant e2e: SKIP on {backend}: the adapter is not available') + sys.exit(77) + assert result.returncode == 0, f'consumer exit {result.returncode}\n{result.stderr[-3000:]}' + errors = [line for line in result.stderr.splitlines() if 'x2w-d3d12-debug ' in line and (' sev=0 ' in line or ' sev=1 ' in line)] + assert not errors, errors[0] + return pixels.read_bytes(), result + + # The stand-in publishes the requests: no translation exists, so nothing is drawn. + cleared = {} + for fmt, *_ in VARIANTS: + cleared[fmt], result = draw(fmt) + assert '-> drawn;' not in result.stderr and 'no RTV translation' in result.stderr, result.stderr[-3000:] + print(result.stdout, end='') + base = G.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) + variants = [] + for fmt, formats, types, target, _, _ in VARIANTS: + line = 'rtv1 ' + ' '.join(map(str, (base, *formats))) + key = G.fnv(line.encode('ascii')) + assert (cache / f'req_{key:016x}.rtv').read_bytes() == line.encode('ascii'), line + variants.append((key, line, types, target)) + # The first request also writes the stand-in's revision.txt; it is not a request. + assert sorted(p.name for p in cache.iterdir() if p.name != 'revision.txt') == sorted( + [f'req_{base:016x}{e}' for e in ('.a', '.b', '.root')] + [f'req_{key:016x}.rtv' for key, *_ in variants]) + + check_published(cli, sdk, work / 'frontend', cache, base, variants) + + for (fmt, _, _, _, first, second), (key, line, _, _) in zip(VARIANTS, variants): + image, result = draw(fmt) + log = result.stderr + assert image.hex() == first + second, f'format {fmt}: {image.hex()} expected {first + second}\n{log[-3000:]}' + assert image != cleared[fmt], f'format {fmt}: the expected value equals the cleared target' + targets = 2 if second else 1 + assert f'desktop pipeline for {key:016x}, {targets} targets (format {fmt}) -> 0x00000000' in log, log[-3000:] + assert f'pipeline {key:016x} topology 0x4 -> drawn;' in log, log[-3000:] + print(f'{backend} format {fmt} variant {key:016x}: MRT0={first}' + (f' MRT1={second}' if second else '')) + image, result = draw() + assert image == (bytes(4) * 4 + bytes((0, 0, 255, 255)) * 4) * 4, image.hex() + assert f'pipeline {base:016x} topology 0x4 -> drawn;' in result.stderr, result.stderr[-3000:] + layer = [line for line in result.stderr.splitlines() if 'x2w-d3d12 debug layer: ' in line] + assert layer, result.stderr[-3000:] + print('debug layer: ' + ('enabled, no error message' if '0x00000000' in layer[0] else 'unavailable')) + + print(f'native_rtv_variant e2e: PASS on {backend} (3 runtime-published variants of one base compiled cold and warm; ' + f'UINT16, SINT16 and FLOAT32 readbacks match; the base pair draws)') + return 0 + + +def main(argv): + if len(argv) == 3 and argv[0] == 'controls': + return check_controls(*argv[1:]) + if len(argv) == 5 and argv[0] == 'e2e' and argv[4] in ('warp', 'hardware'): + return check_e2e(*argv[1:]) + raise SystemExit(__doc__) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_s_lshl_add_u32_check.py b/tests/native_s_lshl_add_u32_check.py new file mode 100644 index 0000000000..444bc3c72d --- /dev/null +++ b/tests/native_s_lshl_add_u32_check.py @@ -0,0 +1,116 @@ +"""Direct compute SOP2 s_lshl{1,2,3,4}_add_u32 (D = (S0 << k) + S1, SCC = 64-bit unsigned overflow).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 + +# (s0, s1) covering no-carry, add-carry-only, shift-out-overflow-only (s1=0), and exact 2^32-1 / 2^32 boundaries. +CASES = ( + (0x00000005, 0x00000003), # small positive, no carry + (0x80000000, 0x00000000), # shift-out overflow only (k=1..4 -> SCC=1, D=0) + (0x40000000, 0x00000000), # k=1 -> SCC=0; k=2..4 -> shift-out overflow SCC=1 + (0x10000000, 0x00000000), # k=1..3 -> SCC=0; k=4 -> shift-out overflow SCC=1 + (0x0FFFFFFF, 0x0000000F), # k=4: (0x0FFFFFFF<<4)+15 = 0xFFFFFFFF (exact max, SCC=0) + (0x0FFFFFFF, 0x00000010), # k=4: (0x0FFFFFFF<<4)+16 = 0x100000000 (add carry, SCC=1, D=0) + (0x01234567, 0xF0000000), # add carry for k=2..4, no carry for k=1 + (0xFFFFFFFF, 0xFFFFFFFF), # both shift-out and add carry +) +# SOP2 opcodes 0x2e..0x31 -> k = 1..4 +SHIFTS = ((0x2E, 1), (0x2F, 2), (0x30, 3), (0x31, 4)) + + +def sop2(op, sdst, src0, src1): + return 0x80000000 | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16) | ((src1 & 0xFF) << 8) | (src0 & 0xFF) + + +def program_batch(batch): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, (s0, s1) in enumerate(batch): + code += [sop1(3, 6, 255), s0, # s_mov_b32 s6, s0 + sop1(3, 7, 255), s1] # s_mov_b32 s7, s1 + for si, (op, _k) in enumerate(SHIFTS): + code += [ + sop2(op, 8, 6, 7), # s_lshl{k}_add_u32 s8, s6, s7 + sop1(3, 9, 253), # s_mov_b32 s9, src_scc + 0x7E080208, # v_mov_b32 v4, s8 + 0xE0701000 | (4 * (ci * 8 + si * 2)), 0x80080408, + 0x7E080209, # v_mov_b32 v4, s9 (SCC) + 0xE0701000 | (4 * (ci * 8 + si * 2 + 1)), 0x80080408, + ] + return code + [0xBF810000] + + +def ref_op(s0, s1, k, ignore_shift_overflow=False): + full = ((s0 & MASK) << k) + (s1 & MASK) + d = full & MASK + if ignore_shift_overflow: + shifted = ((s0 & MASK) << k) & MASK + scc = int(((shifted + (s1 & MASK)) & MASK) < shifted) + else: + scc = int(full >= (1 << 32)) + return d, scc + + +def reference(batch, ignore_shift_overflow=False): + words = [SENTINEL] * 8 + for _lane in range(64): + for s0, s1 in batch: + for _op, k in SHIFTS: + d, scc = ref_op(s0, s1, k, ignore_shift_overflow=ignore_shift_overflow) + words.extend((d, scc)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + for bi, batch in enumerate((CASES[:4], CASES[4:])): + marker = request(work, root, program_batch(batch)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (bi, result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'shl i32 ' in dump and 'icmp ult i32 ' in dump, dump + assert reference(CASES[:4]) != reference(CASES[:4], ignore_shift_overflow=True) + print('s_lshl1..4_add_u32 DXIL verified; shift-out overflow SCC control differs') + return 0 + + +def hardware(replay, sdk, work, root): + for bi, batch in enumerate((CASES[:4], CASES[4:])): + marker = request(work, root, program_batch(batch)) + output = work / f'out_{bi}.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(batch) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'batch={bi} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + print(f'batch={bi}: 2048 result/SCC words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_s_lshl_add_u32_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_s_not_b64_exec_check.py b/tests/native_s_not_b64_exec_check.py new file mode 100644 index 0000000000..e3763bec27 --- /dev/null +++ b/tests/native_s_not_b64_exec_check.py @@ -0,0 +1,143 @@ +"""Compile and replay 64-bit NOT and CSELECT with the compute mask registers.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_scalar_lds_check import scalar, sop1, vmove +from native_wave64_exec_salu_check import ( + END, EXEC, GROUP_STRIDE_WORDS, GUARD_WORDS, NEG_ONE, OUTPUT_WORDS, + SENTINEL, VCC, ZERO, compile_request, request, +) + + +NOT_B64, CSELECT_B64 = 0x08, 0x0B +MOV_B32, MOV_B64, LITERAL = 3, 4, 255 +M0, RESULT = 124, 24 +MASK32, MASK64 = (1 << 32) - 1, (1 << 64) - 1 +EXEC_MASK = 0xA5600FF00F0FF00F +VCC_MASK = 0x3150C4D2FFFFFFFF +PLANE_WORDS = 2 * GROUP_STRIDE_WORDS +CASES = ("not_exec", "not_vcc", "not_vcc_all_ones", "select_scc0", "select_scc1", "not_into_exec") + + +def move_pair(dst, bits): + return [sop1(MOV_B32, dst, LITERAL), bits & MASK32, + sop1(MOV_B32, dst + 1, LITERAL), bits >> 32] + + +def set_scc(value): + # s_cmp_eq_u32 0, 0 (SCC = 1) or s_cmp_eq_u32 0, 1 (SCC = 0). + return 0xBF060000 | (ZERO + (1 - value)) << 8 | ZERO + + +def store(vgpr, plane): + return [0xE0701000 | (4 * PLANE_WORDS * plane), 0x80080008 | vgpr << 8] + + +def program(case): + # Prepare every lane's address before narrowing EXEC. The shader uses + # the same two-group UAV layout as the wave64 EXEC SALU fixture. + words = [ + sop1(MOV_B64, EXEC, NEG_ONE), + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(0x1E, 7, 5, ZERO + 9), # s_lshl_b32 s7, s5, 9 + 0x34100082, # v_lshlrev_b32 v8, 2, v0 + 0x4A101007, # v_add_nc_u32 v8, s7, v8 + ] + words += move_pair(EXEC, EXEC_MASK) + words += move_pair(VCC, MASK64 if case == "not_vcc_all_ones" else VCC_MASK) + if case.startswith("select"): + words += [set_scc(int(case[-1])), scalar(CSELECT_B64, RESULT, EXEC, VCC)] + elif case == "not_into_exec": + words += [set_scc(0), sop1(NOT_B64, EXEC, EXEC), *store(0, 0)] + # Save both new EXEC words before restoring all lanes for readback. + words.append(sop1(MOV_B64, RESULT, EXEC)) + else: + source = EXEC if case == "not_exec" else VCC + words += [set_scc(int(case == "not_vcc_all_ones")), sop1(NOT_B64, RESULT, source)] + + words += [sop1(MOV_B64, EXEC, NEG_ONE), scalar(0x0A, RESULT + 2, ZERO + 1, ZERO)] + for plane, src in enumerate((RESULT, RESULT + 1, RESULT + 2), start=1): + words += [vmove(1, src), *store(1, plane)] + return words + [END] + + +def expected_words(wave_size, case): + if case.startswith("select"): + scc = int(case[-1]) + result = EXEC_MASK if scc else VCC_MASK + else: + source = {"not_exec": EXEC_MASK, "not_vcc": VCC_MASK, + "not_vcc_all_ones": MASK64, "not_into_exec": EXEC_MASK}[case] + result = source ^ MASK64 + scc = int(result != 0) + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(wave_size): + index = GUARD_WORDS + group * GROUP_STRIDE_WORDS + lane + if case == "not_into_exec" and result & (1 << lane): + expected[index] = lane + for plane, value in enumerate((result & MASK32, result >> 32, scc), start=1): + expected[index + plane * PLANE_WORDS] = value + return expected + + +def controls(cli, sdk, work, root): + cache = work / "cache" + failures = [] + for wave_size in (32, 64): + for case in CASES: + marker = request(work, root, wave_size, wave_size, program(case)) + output, result = compile_request(cli, sdk, cache, marker) + if result.returncode or not output.is_file(): + failures.append((wave_size, case, result.stdout, result.stderr)) + assert not failures, failures + + prefix = [sop1(MOV_B32, 23, ZERO), sop1(MOV_B32, M0, ZERO), set_scc(1)] + refusals = [ + (sop1(NOT_B64, RESULT, src), "invalid s_not_b64 source") + for src in (23, M0) + ] + [ + (scalar(CSELECT_B64, RESULT, a, b), "invalid s_cselect_b64 source") + for src in (23, M0) for a, b in ((src, ZERO), (ZERO, src)) + ] + [(scalar(CSELECT_B64, EXEC, ZERO, ZERO), "invalid s_cselect_b64 destination")] + for instruction, error in refusals: + marker = request(work, root, 64, 64, prefix + [instruction, END]) + output, result = compile_request(cli, sdk, cache, marker) + assert result.returncode and error in result.stderr, (error, result.stdout, result.stderr) + assert not output.exists(), output + print("Wave32 and wave64 compile controls and invalid operand refusals passed") + return 0 + + +def hardware(replay, sdk, work, root): + for wave_size in (32, 64): + for case in CASES: + marker = request(work, root, wave_size, wave_size, program(case)) + output = work / f"wave{wave_size}_{case}.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected_words(wave_size, case))): + assert got == want, (wave_size, case, index, hex(got), hex(want)) + print(f"wave{wave_size} {case}: both groups and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root_file = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root_file.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_s_quadmask_check.py b/tests/native_s_quadmask_check.py new file mode 100644 index 0000000000..86941abb4d --- /dev/null +++ b/tests/native_s_quadmask_check.py @@ -0,0 +1,142 @@ +"""Direct compute SOP1 s_quadmask_b32 and s_quadmask_b64.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +SENTINEL = 0x69696969 + +CASES_32 = ( + 0x00000000, # all zero -> 0x00, SCC=0 + 0x00000001, # nibble 0 bit 0 -> 0x01, SCC=1 + 0x00000008, # nibble 0 bit 3 -> 0x01, SCC=1 + 0x80000000, # nibble 7 bit 3 -> 0x80, SCC=1 + 0x0F00F00F, # nibbles 0, 3, 6 -> 0x49, SCC=1 + 0x10204080, # odd nibbles 1, 3, 5, 7 -> 0xAA, SCC=1 + 0x01020408, # even nibbles 0, 2, 4, 6 -> 0x55, SCC=1 + 0xFFFFFFFF, # all nibbles -> 0xFF, SCC=1 +) + +CASES_64 = ( + (0x00000000, 0x00000000), # zero -> (0x0000, 0, SCC=0) + (0x00000000, 0x00000001), # hi-only non-zero -> (0x0100, 0, SCC=1) + (0x80000001, 0x10204080), # mixed lo and hi -> (0xAA81, 0, SCC=1) + (0x01020408, 0xFFFFFFFF), # all hi + even lo -> (0xFF55, 0, SCC=1) +) + + +def program(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + # Words 0..15: 8 x s_quadmask_b32 (D, SCC) + for ci, x in enumerate(CASES_32): + code += [ + sop1(3, 6, 255), x, # s_mov_b32 s6, x + sop1(0x2C, 8, 6), # s_quadmask_b32 s8, s6 + sop1(3, 9, 253), # s_mov_b32 s9, src_scc + 0x7E080208, # v_mov_b32 v4, s8 + 0xE0701000 | (4 * (ci * 2 + 0)), 0x80080408, + 0x7E080209, # v_mov_b32 v4, s9 (SCC) + 0xE0701000 | (4 * (ci * 2 + 1)), 0x80080408, + ] + # Words 16..31: 4 x s_quadmask_b64 (D.lo, D.hi, SCC, aliased-in-place D.lo) + for ci, (lo, hi) in enumerate(CASES_64): + base = 16 + ci * 4 + code += [ + sop1(3, 6, 255), lo, # s_mov_b32 s6, lo + sop1(3, 7, 255), hi, # s_mov_b32 s7, hi + sop1(0x2D, 8, 6), # s_quadmask_b64 s[8:9], s[6:7] + sop1(3, 10, 253), # s_mov_b32 s10, src_scc + sop1(0x2D, 6, 6), # s_quadmask_b64 s[6:7], s[6:7] (aliased dst==src) + 0x7E080208, # v_mov_b32 v4, s8 (D.lo) + 0xE0701000 | (4 * (base + 0)), 0x80080408, + 0x7E080209, # v_mov_b32 v4, s9 (D.hi, must be 0) + 0xE0701000 | (4 * (base + 1)), 0x80080408, + 0x7E08020A, # v_mov_b32 v4, s10 (SCC) + 0xE0701000 | (4 * (base + 2)), 0x80080408, + 0x7E080206, # v_mov_b32 v4, s6 (aliased D.lo) + 0xE0701000 | (4 * (base + 3)), 0x80080408, + ] + return code + [0xBF810000] + + +def quadmask32(x, all_bits=False): + out = 0 + for q in range(8): + nib = (x >> (4 * q)) & 0xF + if (nib == 0xF) if all_bits else (nib != 0): + out |= 1 << q + return out + + +def reference(all_bits=False, ignore_hi=False): + words = [SENTINEL] * 8 + for _lane in range(64): + for x in CASES_32: + q = quadmask32(x, all_bits=all_bits) + words.extend((q, int(q != 0))) + for lo, hi in CASES_64: + qlo = quadmask32(lo, all_bits=all_bits) + qhi = 0 if ignore_hi else quadmask32(hi, all_bits=all_bits) + out_lo = qlo | (qhi << 8) + words.extend((out_lo, 0, int(out_lo != 0), out_lo)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'and i32 ' in dump and '286331153' in dump, dump + for tag, bad, msg in ( + ('odd_dst', [sop1(0x2D, 7, 6), 0xBF810000], 'invalid s_quadmask_b64 destination'), + ('odd_src', [sop1(0x2D, 8, 7), 0xBF810000], 'invalid s_quadmask_b64 source'), + ): + sub = work / tag + sub.mkdir(exist_ok=True) + bad_marker = request(sub, root, bad) + bad_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', bad_marker, + bad_marker.with_suffix('.cso')], capture_output=True, text=True) + assert bad_res.returncode != 0 and msg in (bad_res.stdout + bad_res.stderr), (tag, bad_res.stdout, bad_res.stderr) + assert reference() != reference(all_bits=True) + assert reference() != reference(ignore_hi=True) + print('s_quadmask_b32/b64 DXIL verified; odd dst/src refused; all-bits and ignore-hi controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print('s_quadmask_b32/b64: 2048 result/SCC words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_s_quadmask_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_s_sext_i32_check.py b/tests/native_s_sext_i32_check.py new file mode 100644 index 0000000000..961e6394db --- /dev/null +++ b/tests/native_s_sext_i32_check.py @@ -0,0 +1,123 @@ +"""Direct compute SOP1 s_sext_i32_i8 and s_sext_i32_i16 (sign extension preserving SCC).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 + +# (value, incoming_scc_for_i8, incoming_scc_for_i16) +CASES = ( + (0x00000000, 1, 0), # zero result must preserve SCC=1; zero must preserve SCC=0 + (0x0000007F, 0, 1), # max positive i8, positive i16 + (0x00000080, 0, 1), # min negative i8 (0xFFFFFF80), positive i16 (0x00000080) + (0x123456FF, 1, 0), # upper junk + -1 i8, positive i16 + (0x12347FFF, 0, 1), # max positive i16, -1 i8 + (0x12348000, 1, 0), # min negative i16 (0xFFFF8000), 0 i8 (preserve SCC=1 and SCC=0) + (0x8765807F, 0, 1), # negative i16, positive i8 + (0xFFFFFFFF, 0, 0), # all ones (-1 for both) while preserving SCC=0 +) + + +def sopc_set_scc(val): + # s_cmp_eq_i32 0, 0 -> SCC=1; s_cmp_eq_i32 0, 1 -> SCC=0 + return 0xBF008080 if val else 0xBF008180 + + +def program(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, (val, scc8, scc16) in enumerate(CASES): + code += [sop1(3, 6, 255), val] # s_mov_b32 s6, val + # s_sext_i32_i8 (SOP1 0x19) preserving incoming SCC + code += [ + sopc_set_scc(scc8), + sop1(0x19, 8, 6), # s_sext_i32_i8 s8, s6 + sop1(3, 9, 253), # s_mov_b32 s9, src_scc + 0x7E080208, # v_mov_b32 v4, s8 + 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408, + 0x7E080209, # v_mov_b32 v4, s9 (SCC) + 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408, + ] + # s_sext_i32_i16 (SOP1 0x1a) preserving incoming SCC + code += [ + sopc_set_scc(scc16), + sop1(0x1A, 8, 6), # s_sext_i32_i16 s8, s6 + sop1(3, 9, 253), # s_mov_b32 s9, src_scc + 0x7E080208, # v_mov_b32 v4, s8 + 0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408, + 0x7E080209, # v_mov_b32 v4, s9 (SCC) + 0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408, + ] + return code + [0xBF810000] + + +def sext(val, bits, zero_extend=False): + m = (1 << bits) - 1 + v = val & m + if zero_extend: + return v + sign = 1 << (bits - 1) + return (v - (1 << bits)) & MASK if (v & sign) else v + + +def reference(zero_extend=False, clobber_scc=False): + words = [SENTINEL] * 8 + for _lane in range(64): + for val, scc8, scc16 in CASES: + r8 = sext(val, 8, zero_extend=zero_extend) + r16 = sext(val, 16, zero_extend=zero_extend) + s8 = int(r8 != 0) if clobber_scc else scc8 + s16 = int(r16 != 0) if clobber_scc else scc16 + words.extend((r8, s8, r16, s16)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'ashr i32 ' in dump and 'shl i32 ' in dump, dump + assert reference() != reference(zero_extend=True) + assert reference() != reference(clobber_scc=True) + print('s_sext_i32_i8/i16 DXIL verified; zero-extend and clobber-SCC controls differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print('s_sext_i32_i8/i16: 2048 result/SCC words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_s_sext_i32_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_sad_check.py b/tests/native_sad_check.py new file mode 100644 index 0000000000..76fcdac131 --- /dev/null +++ b/tests/native_sad_check.py @@ -0,0 +1,136 @@ +"""v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32 and v_msad_u8 in the direct compute path (#2987). + + native_sad_check.py controls <compile_dxil> <sdk bin dir> + native_sad_check.py hardware <native_store_replay> <sdk bin dir> + +Each operation sums unsigned absolute differences of S0 and S1 (four bytes, two halfwords or one dword) and adds +S2, modulo 2^32, as gfx2hlsl.py's sad_u8, sad4_u8, sad_u16 and sad_u32 helpers and tools/pixel_aot.py do. +v_msad_u8 skips each byte whose S1 byte is zero, and v_sad_hi_u8 shifts the byte sum left by 16. All words below +were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The dispatch has two groups of 32 lanes. With n = lane + 32 * group, S0 = mul_u32_u24(n, 0x050311) ^ 0x80f00a33, +S1 = mul_u32_u24(n, 0x010203) & 0xffff00ff (byte 1 is always zero, byte 0 is zero for n = 0) and +S2 = mul_u32_u24(n, 0x1001). Bytes of S0 below and above those of S1 both occur. Each lane stores the five +results. References with signed byte differences, msad without its mask, sad_hi without its shift and S2 dropped +must each differ from the expected words. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 10 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 5, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v9, s8, v0 / +# v_mul_u32_u24 v1, 0x50311, v9 / v_xor_b32 v1, 0x80f00a33, v1 / v_mul_u32_u24 v2, 0x10203, v9 / +# v_and_b32 v2, 0xffff00ff, v2 / v_mul_u32_u24 v3, 0x1001, v9 / v_sad_u8 v10, v_sad_hi_u8 v11, v_sad_u16 v12, +# v_sad_u32 v13, v_msad_u8 v14 (each v1, v2, v3) / s_waitcnt lgkmcnt(0) / buffer_store_dword v10..v14 at +# v8 + 0..16 through s[32:35] / s_endpgm +HEX = ('040394be 800395be 0a0808f4200000fa 058a078f 0585088f 85001034 0710104a 0800124a ff12021611030500 ' + 'ff02023a330af080 ff12041603020100 ff040436ff00ffff ff12061601100000 0a005ad501050e04 0b005bd501050e04 ' + '0c005cd501050e04 0d005dd501050e04 0e0071d501050e04 7fc08cbf 001070e0080a0880 041070e0080b0880 ' + '081070e0080c0880 0c1070e0080d0880 101070e0080e0880 000081bf') +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +MASK = 0xFFFFFFFF + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & MASK + + +def operands(n): + return mul24(n, 0x050311) ^ 0x80F00A33, mul24(n, 0x010203) & 0xFFFF00FF, mul24(n, 0x1001) + + +def parts(x, width): + return [(x >> at) & ((1 << width) - 1) for at in range(0, 32, width)] + + +def signed8(x): + return x - 256 if x & 0x80 else x + + +def results(a, b, c, signed=False, unmasked=False, no_shift=False, no_add=False): + def diff(x, y): + return abs(signed8(x) - signed8(y)) if signed else abs(x - y) + add = 0 if no_add else c + bytes_sum = sum(diff(x, y) for x, y in zip(parts(a, 8), parts(b, 8))) + masked = sum(diff(x, y) for x, y in zip(parts(a, 8), parts(b, 8)) if unmasked or y) + return [(bytes_sum + add) & MASK, + ((bytes_sum << (0 if no_shift else 16)) + add) & MASK, + (sum(abs(x - y) for x, y in zip(parts(a, 16), parts(b, 16))) + add) & MASK, + (abs(a - b) + add) & MASK, + (masked + add) & MASK] + + +def reference(**mutation): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(32): + base = GUARD_WORDS + (group * 32 + lane) * 8 + expected[base:base + 5] = results(*operands(lane + 32 * group), **mutation) + return expected + + +def controls(cli, sdk, work, root): + marker = request(work, root, words(HEX)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + # The same v_sad_u8 with a clamp bit is refused, as source and output modifiers are on integer VOP3 here. + clamped = words(HEX) + clamped[clamped.index(0xD55A000A)] |= 0x8000 + marker = request(work, root, clamped) + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, marker.with_suffix('.cso')], + capture_output=True, text=True) + assert result.returncode and 'direct ALU operand modifiers' in result.stderr, (result.stdout, result.stderr) + expected = reference() + a, b, _ = zip(*(operands(n) for n in range(64))) + assert any(x > y for v, w in zip(a, b) for x, y in zip(parts(v, 8), parts(w, 8))) + assert any(x < y for v, w in zip(a, b) for x, y in zip(parts(v, 8), parts(w, 8))) + for label, mutation in (('signed byte differences', {'signed': True}), ('msad without its mask', {'unmasked': True}), + ('sad_hi without its shift', {'no_shift': True}), ('S2 dropped', {'no_add': True})): + assert reference(**mutation) != expected, label + print('compiled; clamp refused; the signed, unmasked, unshifted and S2-dropped references each differ') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, words(HEX)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + expected = reference() + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, expected)) if x != y] + assert not diff, diff[:10] + print('five SAD operations: 320 words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu64_check.py b/tests/native_salu64_check.py new file mode 100644 index 0000000000..41a94d07c4 --- /dev/null +++ b/tests/native_salu64_check.py @@ -0,0 +1,119 @@ +"""Direct compute 64-bit SALU readback and EXEC destination refusal.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + + +BFM, CSELECT, CSELECT32, NOT = 0x25, 0x0B, 0x0A, 0x08 +ZERO, ONE, NEG_ONE, LITERAL = 128, 129, 193, 255 +PAIR = (0x89ABCDEF, 0x01234567) +LITERAL_VALUE = 0x80000001 +MASK32 = (1 << 32) - 1 +LANES = 64 +PLANE_BYTES = LANES * 8 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def set_pair(words): + return [sop1(3, 22, LITERAL), words[0], sop1(3, 23, LITERAL), words[1]] + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | (ZERO if value else ONE) << 8 + + +def compute_program(instructions, dst): + # Two 32-lane groups, with 8 bytes per lane and 256 bytes per group in each plane. + program = [sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 131, 0), vop2(0x25, 8, 7, 8)] + program += instructions + # One pair per lane in each of two planes. A ninth plane would set OFFEN + # because the store's immediate offset is only 12 bits. + program += [vmove(2, dst), vmove(3, dst + 1), 0xE0741000, 0x80080208, + scalar(CSELECT32, 26, ONE, ZERO), vmove(2, 26), vmove(3, ZERO), + 0xE0741000 | PLANE_BYTES, 0x80080208, 0xBF810000] + return program + + +def controls(cli, sdk, work, root): + for words, error in (([scalar(CSELECT, 126, NEG_ONE, ZERO), 0xBF810000], "invalid s_cselect_b64 destination"), + ([sop1(NOT, 24, 127), 0xBF810000], "invalid s_not_b64 source")): + marker = request(work, root, words) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + assert result.returncode and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + print(error) + return 0 + + +def cases(): + # Manual mutants that must fail: 32-bit s_bfm_b64 with a zero high word, + # zero-extending -1 in s_cselect_b64, and s_not_b64 SCC from the low word only. + for width, offset in ((0, 0), (1, 0), (31, 1), (32, 32), (33, 0), (63, 1), (64, 0)): + bits = ((1 << (width & 63)) - 1) << (offset & 63) + scc = int(bits == 0) + # Use odd SGPR s23 for the width and s22 for the offset in the measured case. + if (width, offset) == (32, 32): + code = [sop1(3, 23, ZERO + width), sop1(3, 22, ZERO + offset), + set_scc(scc), scalar(BFM, 24, 23, 22)] + else: + code = [set_scc(scc), scalar(BFM, 24, ZERO + width, ZERO + offset)] + yield f"bfm {width},{offset}", code, 24, (bits & MASK32, (bits >> 32) & MASK32), scc + + for scc in (0, 1): + yield (f"cselect pair,-1 SCC={scc}", + set_pair(PAIR) + [set_scc(scc), scalar(CSELECT, 24, 22, NEG_ONE)], + 24, PAIR if scc else (MASK32, MASK32), scc) + yield (f"cselect literal,pair SCC={scc}", + set_pair(PAIR) + [set_scc(scc), scalar(CSELECT, 106, LITERAL, 22), LITERAL_VALUE], + 106, (LITERAL_VALUE, 0) if scc else PAIR, scc) + + for source in (PAIR, (0, 0), (MASK32, MASK32), (MASK32, 0)): + words = tuple(word ^ MASK32 for word in source) + scc = int(any(words)) + yield (f"not {source}", set_pair(source) + [set_scc(1 - scc), sop1(NOT, 106, 22)], + 106, words, scc) + + +def hardware(replay, sdk, work, root): + for name, code, dst, words, scc in cases(): + marker = request(work, root, compute_program(code, dst)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, name + assert actual[GUARD_WORDS:end] == words * LANES + (scc, 0) * LANES, (name, words, scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), name + print(f"{name}: result words, SCC and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu_bfe64_brev64_check.py b/tests/native_salu_bfe64_brev64_check.py new file mode 100644 index 0000000000..4216c597f0 --- /dev/null +++ b/tests/native_salu_bfe64_brev64_check.py @@ -0,0 +1,251 @@ +"""Direct compute s_bfe_u64, s_bfe_i64 and s_brev_b64 checks (#3086).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_salu64_check import GUARD_WORDS, LANES, LITERAL, LITERAL_VALUE, MASK32, NEG_ONE, OUTPUT_WORDS, SENTINEL, ZERO, compute_program, set_pair, set_scc +from native_scalar_lds_check import scalar, sop1 + + +S_BREV_B64 = 0x0C +S_BFE_U64, S_BFE_I64 = 0x29, 0x2A +NULL, VCC_LO, EXEC_LO, INLINE_FLOAT_ONE = 125, 106, 126, 242 +PAIR = (0x89ABCDEF, 0x01234567) +MASK64 = (1 << 64) - 1 + + +def rev32(w): + return int(f"{w & MASK32:032b}"[::-1], 2) + + +def bfe64_oracle(x, ctrl, signed): + off = ctrl & 63 + wd = min((ctrl >> 16) & 127, 64 - off) + field = (x >> off) & ((1 << wd) - 1) + if signed and 0 < wd < 64 and ((field >> (wd - 1)) & 1): + field |= MASK64 ^ ((1 << wd) - 1) + return 0 if (signed and wd == 0) else field + + +def _src64(kind, spec, signed_lit=False): + if kind == "pair": + return spec + if kind == "null": + return (0, 0) + if kind == "inline": + val = (spec - 128) if spec <= 192 else (192 - spec) + return (val & MASK32, MASK32 if spec >= 193 else 0) + return (spec, MASK32 if (signed_lit and (spec & 0x80000000)) else 0) + + +def cases(): + # s_brev_b64: preserves SCC and swaps+reverses 32-bit halves. + for label, kind, spec, scc in ( + ("brev pair scc=0", "pair", PAIR, 0), + ("brev pair scc=1", "pair", PAIR, 1), + ("brev bit0 -> bit63", "pair", (1, 0), 1), + ("brev -1", "inline", NEG_ONE, 0), + ("brev literal 0x80000001", "lit", LITERAL_VALUE, 1), + ("brev null", "null", 0, 1), + ): + s0_words = _src64(kind, spec) + expected = (rev32(s0_words[1]), rev32(s0_words[0])) + dst = 22 if label == "brev bit0 -> bit63" else 24 # verify in-place s[22:23] on one case + code = [] + if kind == "pair": + code += set_pair(spec) + a_enc = 22 + elif kind == "inline": + a_enc = spec + elif kind == "null": + a_enc = NULL + else: + a_enc = LITERAL + code.append(set_scc(scc)) + code.append(sop1(S_BREV_B64, dst, a_enc)) + if a_enc == LITERAL: + code.append(spec) + yield label, code, dst, expected, scc, ("brev", kind, s0_words, 0) + + # s_bfe_u64 and s_bfe_i64: ctrl = (width << 16) | offset + bfe_specs = [ + ("bfe_u64 width=0", S_BFE_U64, "pair", PAIR, 0x00000004, 1), + ("bfe_i64 width=0", S_BFE_I64, "pair", PAIR, 0x00000024, 1), + ("bfe_u64 full 64", S_BFE_U64, "pair", PAIR, 0x00400000, 0), + ("bfe_i64 width=127 clamp", S_BFE_I64, "pair", (0x12345678, 0x80000001), 0x007F0000, 0), + ("bfe_u64 cross-word off=28 wd=8", S_BFE_U64, "pair", (0xA0000000, 0x0000000B), (8 << 16) | 28, 0), + ("bfe_i64 cross-word neg off=28 wd=8", S_BFE_I64, "pair", (0x80000000, 0x00000008), (8 << 16) | 28, 0), + ("bfe_i64 past-MSB neg off=40 wd=32", S_BFE_I64, "pair", (0, 0x80000000), (32 << 16) | 40, 0), + ("bfe_i64 past-MSB pos off=40 wd=32", S_BFE_I64, "pair", (0, 0x00800000), (32 << 16) | 40, 0), + ("bfe_u64 hi-only nonzero scc", S_BFE_U64, "pair", (0x00000000, 0x00000010), (40 << 16) | 0, 0), + ("bfe_u64 zero extract clears scc", S_BFE_U64, "pair", (0xFFFFFFFF, 0xFFFFFFFF), (0 << 16) | 12, 1), + ("bfe_i64 -1 off=32 wd=8", S_BFE_I64, "inline", NEG_ONE, (8 << 16) | 32, 0), + ("bfe_u64 lit off=32 wd=8 (zext=0)", S_BFE_U64, "lit", LITERAL_VALUE, (8 << 16) | 32, 1), + ("bfe_i64 lit off=32 wd=8 (sext=-1)", S_BFE_I64, "lit", LITERAL_VALUE, (8 << 16) | 32, 0), + ("bfe_u64 null", S_BFE_U64, "null", 0, (16 << 16) | 8, 1), + ] + for label, op, kind, spec, ctrl, init_scc in bfe_specs: + signed = op == S_BFE_I64 + s0_words = _src64(kind, spec, signed_lit=signed) + val64 = s0_words[0] | (s0_words[1] << 32) + out64 = bfe64_oracle(val64, ctrl, signed) + expected = (out64 & MASK32, (out64 >> 32) & MASK32) + scc = int(out64 != 0) + code = [sop1(3, 26, LITERAL), ctrl] + if kind == "pair": + code += set_pair(spec) + a_enc = 22 + elif kind == "inline": + a_enc = spec + elif kind == "null": + a_enc = NULL + else: + a_enc = LITERAL + code.append(set_scc(init_scc)) + code.append(scalar(op, 24, a_enc, 26)) + if a_enc == LITERAL: + code.append(spec) + yield label, code, 24, expected, scc, (op, kind, s0_words, ctrl) + + # Overlapping destination+ctrl+source: s_bfe_u64 s[22:23], s[22:23], s22 + ctrl_overlap = (12 << 16) | 16 + pair_overlap = (ctrl_overlap, 0x00AB0000) + out_overlap = bfe64_oracle(pair_overlap[0] | (pair_overlap[1] << 32), ctrl_overlap, False) + yield ("bfe_u64 overlapping dst/s0/s1", + set_pair(pair_overlap) + [set_scc(0), scalar(S_BFE_U64, 22, 22, 22)], + 22, (out_overlap & MASK32, (out_overlap >> 32) & MASK32), int(out_overlap != 0), + (S_BFE_U64, "pair", pair_overlap, ctrl_overlap)) + + +def _mutant_result(mutant, meta): + op, kind, s0_words, ctrl = meta + if op == "brev": + if mutant == "brev_no_word_swap": + return ((rev32(s0_words[0]), rev32(s0_words[1])), None) + return ((rev32(s0_words[1]), rev32(s0_words[0])), None) + signed = op == S_BFE_I64 + if mutant == "bfe_unsigned_for_signed": + signed = False + if mutant == "bfe_no_sign_ext_lit_i64" and op == S_BFE_I64 and kind == "lit": + s0_words = (s0_words[0], 0) + eff_ctrl = ctrl + if mutant == "bfe_ignore_offset_bit5": + eff_ctrl = (ctrl & ~0x3F) | (ctrl & 0x1F) + val64 = s0_words[0] | (s0_words[1] << 32) + wd = (eff_ctrl >> 16) & 127 + if mutant == "bfe_width_zero_passthrough" and wd == 0: + out64 = val64 + else: + out64 = bfe64_oracle(val64, eff_ctrl, signed) + out_words = (out64 & MASK32, (out64 >> 32) & MASK32) + scc = int(out_words[0] != 0) if mutant == "bfe_scc_low_word_only" else int(out64 != 0) + return (out_words, scc) + + +def _compile_and_dis(cli, sdk, work, root, code, name): + marker = request(work, root, code) + cso = work / f"{name}.cso" + cso.unlink(missing_ok=True) + res = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, cso], + capture_output=True, text=True) + return res, cso + + +def controls(cli, sdk, work, root): + # 1. Standalone s_brev_b64 uses unary.i32(30) and zero i64 ops. + brev_code = set_pair(PAIR) + [sop1(S_BREV_B64, 24, 22)] + res, cso = _compile_and_dis(cli, sdk, work, root, compute_program(brev_code, 24), "brev_only") + assert res.returncode == 0 and cso.is_file(), (res.stdout, res.stderr) + dis_brev = subprocess.run([Path(sdk) / "dxc.exe", "-dumpbin", cso], + capture_output=True, text=True, check=True).stdout + assert "@dx.op.unary.i32(i32 30," in dis_brev, dis_brev + for forbidden in ("64-bit integer", "zext i32", "shl i64", "lshr i64", "ashr i64", "trunc i64"): + assert forbidden not in dis_brev, (forbidden, dis_brev) + + # 2. Combined program with all cases compiles and emits expected DXIL ops. + combined = [] + for _, code, _, _, _, _ in cases(): + combined += code + res, cso_all = _compile_and_dis(cli, sdk, work, root, compute_program(combined, 24), "all_cases") + assert res.returncode == 0 and cso_all.is_file(), (res.stdout, res.stderr) + dis_all = subprocess.run([Path(sdk) / "dxc.exe", "-dumpbin", cso_all], + capture_output=True, text=True, check=True).stdout + for required in ("@dx.op.unary.i32(i32 30,", "lshr i64", "ashr i64", "shl i64"): + assert required in dis_all, f"missing {required} in combined DXIL disassembly" + print("compiled s_brev_b64 (pure 32-bit DXIL) and all 21 s_brev/s_bfe cases cleanly") + + # 3. Symbolic transfer() _u64 check: s_bfe_u64 overwriting descriptor s[32:33] must clear s33 too. + overwrite_desc = (set_pair(PAIR) + + [sop1(3, 26, ZERO + 16), + scalar(S_BFE_U64, 32, 22, 26), + 0xE0741000, 0x80080208, # buffer_store_dwordx2 using modified s[32:35] + 0xBF810000]) + res_desc, cso_desc = _compile_and_dis(cli, sdk, work, root, overwrite_desc, "overwrite_desc") + assert res_desc.returncode != 0 and not cso_desc.exists(), (res_desc.stdout, res_desc.stderr) + print(f"symbolic transfer _u64 descriptor clobber refused: {res_desc.stderr.strip()}") + + # 4. Negative operand/destination refusal controls (with s[22:27] initialized). + init = set_pair((0, 0)) + [sop1(3, 24, ZERO), sop1(3, 25, ZERO), sop1(3, 26, ZERO), sop1(3, 27, ZERO)] + refusals = [ + (init + [sop1(S_BREV_B64, 23, 22), 0xBF810000], "invalid s_brev_b64 destination"), + (init + [sop1(S_BREV_B64, VCC_LO, 22), 0xBF810000], "invalid s_brev_b64 destination"), + (init + [sop1(S_BREV_B64, EXEC_LO, 22), 0xBF810000], "invalid s_brev_b64 destination"), + (init + [sop1(S_BREV_B64, 24, 23), 0xBF810000], "invalid s_brev_b64 source"), + (init + [sop1(S_BREV_B64, 24, INLINE_FLOAT_ONE), 0xBF810000], "invalid s_brev_b64 source"), + (init + [scalar(S_BFE_U64, VCC_LO, 22, 26), 0xBF810000], "invalid s_bfe_u64 destination"), + (init + [scalar(S_BFE_U64, 24, 23, 26), 0xBF810000], "invalid s_bfe_u64 source"), + (init + [scalar(S_BFE_U64, 24, 22, INLINE_FLOAT_ONE), 0xBF810000], "invalid s_bfe_u64 source"), + (init + [scalar(S_BFE_I64, 24, EXEC_LO, 26), 0xBF810000], "invalid s_bfe_i64 source"), + ] + for idx, (words, err) in enumerate(refusals): + r, bad_cso = _compile_and_dis(cli, sdk, work, root, words, f"bad_{idx}") + assert r.returncode and err in r.stderr and not bad_cso.exists(), (idx, err, r.stdout, r.stderr) + print(f"refused: {err}") + + # 5. Oracle mutant checks. + expected = [(label, words, scc, meta) for label, _, _, words, scc, meta in cases()] + for mutant in ("brev_no_word_swap", "bfe_unsigned_for_signed", "bfe_width_zero_passthrough", + "bfe_no_sign_ext_lit_i64", "bfe_scc_low_word_only", "bfe_ignore_offset_bit5"): + caught = 0 + for label, words, scc, meta in expected: + m_words, m_scc = _mutant_result(mutant, meta) + if m_words != words or (m_scc is not None and m_scc != scc): + caught += 1 + assert caught > 0, f"mutant {mutant} agreed on every case" + print(f"mutant {mutant} caught on {caught} case(s)") + return 0 + + +def hardware(replay, sdk, work, root): + for label, code, dst, words, scc, _ in cases(): + marker = request(work, root, compute_program(code, dst)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, label + assert actual[GUARD_WORDS:end] == words * LANES + (scc, 0) * LANES, (label, words, scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), label + print(f"{label}: result words, SCC and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu_bitscan64_check.py b/tests/native_salu_bitscan64_check.py new file mode 100644 index 0000000000..a4cc011eea --- /dev/null +++ b/tests/native_salu_bitscan64_check.py @@ -0,0 +1,242 @@ +"""Direct compute 64-bit scalar bit counts and bit scans (#3072).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + + +BCNT0_64, BCNT1_64, FF0_64, FF1_64, FLBIT_B64, FLBIT_I64 = 0x0E, 0x10, 0x12, 0x14, 0x16, 0x18 +CSELECT32 = 0x0A +ZERO, ONE, NEG_ONE, VCC, EXEC, FLOAT_ONE, LITERAL = 128, 129, 193, 106, 126, 242, 255 +OLD_PAIR = (0xCAFEBABE, 0xDEADBEEF) +LITERAL_VALUE = 0x80000001 +MASK32 = (1 << 32) - 1 +MASK64 = (1 << 64) - 1 +LANES = 64 +PLANE_BYTES = LANES * 8 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def set_pair(base, words): + return [sop1(3, base, LITERAL), words[0], sop1(3, base + 1, LITERAL), words[1]] + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | (ZERO if value else ONE) << 8 + + +def compute_program(instructions, dst): + # Two 32-lane groups, with 8 bytes per lane and 256 bytes per group in each plane. + program = [sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 131, 0), vop2(0x25, 8, 7, 8)] + program += instructions + program += [vmove(2, dst), vmove(3, dst + 1), 0xE0741000, 0x80080208, + scalar(CSELECT32, 26, ONE, ZERO), vmove(2, 26), vmove(3, ZERO), + 0xE0741000 | PLANE_BYTES, 0x80080208, 0xBF810000] + return program + + +def eval_bitscan(op, lo, hi, src_kind, primed_scc, *, no_hi_offset_ff=False, no_lo_offset_flbit=False, + unsigned_flbit=False, zero_ext_lit=False, scan_writes_scc=False, zero_is_64=False): + if src_kind == 'neg_inline': + hi_word = MASK32 + elif src_kind == 'literal': + hi_word = 0 if (zero_ext_lit or op != FLBIT_I64 or not (lo >> 31)) else MASK32 + else: + hi_word = hi + val = (hi_word << 32) | (lo & MASK32) + + def ff1(v): + if not v: + return 64 if zero_is_64 else MASK32 + if no_hi_offset_ff and not (v & MASK32): + return ((v >> 32) & -(v >> 32)).bit_length() - 1 + return (v & -v).bit_length() - 1 + + def flbit_u(v): + if not v: + return 64 if zero_is_64 else MASK32 + if no_lo_offset_flbit and not (v >> 32): + return 32 - (v & MASK32).bit_length() + return 64 - v.bit_length() + + if op == BCNT0_64: + res = 64 - bin(val).count('1') + scc = int(res != 0) + elif op == BCNT1_64: + res = bin(val).count('1') + scc = int(res != 0) + elif op == FF0_64: + res = ff1(val ^ MASK64) + scc = int(res != 0) if scan_writes_scc else primed_scc + elif op == FF1_64: + res = ff1(val) + scc = int(res != 0) if scan_writes_scc else primed_scc + elif op == FLBIT_B64 or (op == FLBIT_I64 and unsigned_flbit): + res = flbit_u(val) + scc = int(res != 0) if scan_writes_scc else primed_scc + else: + res = flbit_u((val ^ MASK64) if (val >> 63) else val) + scc = int(res != 0) if scan_writes_scc else primed_scc + return res, scc + + +def cases(): + pair_inputs = ( + ('zero', (0, 0)), + ('all_ones', (MASK32, MASK32)), + ('bit32', (0, 1)), + ('bit31', (0x80000000, 0)), + ('neg2', (0xFFFFFFFE, MASK32)), + ('int64_min', (0, 0x80000000)), + ('bit0', (1, 0)), + ) + ops = ( + (BCNT0_64, 'bcnt0'), + (BCNT1_64, 'bcnt1'), + (FF0_64, 'ff0'), + (FF1_64, 'ff1'), + (FLBIT_B64, 'flbit_b64'), + (FLBIT_I64, 'flbit_i64'), + ) + for label, pair in pair_inputs: + for op, opname in ops: + primed = 1 if op in (FF0_64, FLBIT_B64) else 0 + # Prime SCC opposite to counts or arbitrary for scans; keep s25 = OLD_PAIR[1]. + if op in (BCNT0_64, BCNT1_64): + bits = bin((pair[1] << 32) | pair[0]).count('1') + expected_cnt = (64 - bits) if op == BCNT0_64 else bits + primed = 1 - int(expected_cnt != 0) + code = set_pair(24, OLD_PAIR) + set_pair(22, pair) + [set_scc(primed), sop1(op, 24, 22)] + yield (f'{opname} {label}', code, 24, OLD_PAIR[1], op, pair[0], pair[1], 'pair', primed) + + # Inline -1 (sign-extended to all ones) and 32-bit literal 0x80000001 (zero-ext for _b64, sign-ext for _i64). + yield ('bcnt1 neg1', set_pair(24, OLD_PAIR) + [set_scc(0), sop1(BCNT1_64, 24, NEG_ONE)], + 24, OLD_PAIR[1], BCNT1_64, MASK32, MASK32, 'neg_inline', 0) + yield ('flbit_i64 neg1', set_pair(24, OLD_PAIR) + [set_scc(1), sop1(FLBIT_I64, 24, NEG_ONE)], + 24, OLD_PAIR[1], FLBIT_I64, MASK32, MASK32, 'neg_inline', 1) + yield ('bcnt1 lit', set_pair(24, OLD_PAIR) + [set_scc(0), sop1(BCNT1_64, 24, LITERAL), LITERAL_VALUE], + 24, OLD_PAIR[1], BCNT1_64, LITERAL_VALUE, 0, 'literal', 0) + yield ('flbit_i64 lit', set_pair(24, OLD_PAIR) + [set_scc(0), sop1(FLBIT_I64, 24, LITERAL), LITERAL_VALUE], + 24, OLD_PAIR[1], FLBIT_I64, LITERAL_VALUE, 0, 'literal', 0) + + # Explicit SCC preservation across count -> scan sequence. + yield ('scc0 preserved by ff1', + set_pair(24, OLD_PAIR) + set_pair(22, (0, 1)) + [sop1(BCNT1_64, 24, ZERO), sop1(FF1_64, 24, 22)], + 24, OLD_PAIR[1], FF1_64, 0, 1, 'pair', 0) + yield ('scc1 preserved by flbit_b64', + set_pair(24, OLD_PAIR) + set_pair(22, (0, 0)) + [sop1(BCNT1_64, 24, ONE), sop1(FLBIT_B64, 24, 22)], + 24, OLD_PAIR[1], FLBIT_B64, 0, 0, 'pair', 1) + + # Overlapping destination: s22 = ff1(s[22:23]), s23 stays 0x01234567. + yield ('ff1 overlap s22', + set_pair(22, (0, 0x01234567)) + [set_scc(0), sop1(FF1_64, 22, 22)], + 22, 0x01234567, FF1_64, 0, 0x01234567, 'pair', 0) + + +def full_reference(**mutant_flags): + return [eval_bitscan(op, lo, hi, src_kind, primed, **mutant_flags) + for _, _, _, _, op, lo, hi, src_kind, primed in cases()] + + +def controls(cli, sdk, work, root): + combined = compute_program( + set_pair(24, OLD_PAIR) + set_pair(22, (0x80000001, 0x00000010)) + [ + sop1(BCNT0_64, 24, 22), + sop1(BCNT1_64, 24, 22), + sop1(FF0_64, 24, 22), + sop1(FF1_64, 24, 22), + sop1(FLBIT_B64, 24, 22), + sop1(FLBIT_I64, 24, 22), + ], 24) + marker = request(work, root, combined) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + for op_id in (31, 32, 33): + assert f'@dx.op.unaryBits.i32(i32 {op_id}' in dump, (op_id, dump) + assert 'shl i64' not in dump, dump + + # Adjacent descriptor preservation regression: s_ff1_i32_b64 writes 32-bit s31 right below s[32:35]; + # transfer() must not clear s32 as a 64-bit destination pair. + adj_prog = compute_program(set_pair(24, OLD_PAIR) + set_pair(22, (0, 1)) + [sop1(FF1_64, 31, 22)], 24) + adj_marker = request(work, root, adj_prog) + adj_out = adj_marker.with_suffix('.adj.cso') + adj_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', adj_marker, adj_out], + capture_output=True, text=True) + assert adj_res.returncode == 0 and adj_out.is_file(), (adj_res.stdout, adj_res.stderr) + + refused = ( + ([sop1(BCNT1_64, VCC, 22), 0xBF810000], 'invalid s_bcnt1_i32_b64 destination'), + ([sop1(FF1_64, EXEC, 22), 0xBF810000], 'invalid s_ff1_i32_b64 destination'), + ([sop1(FF0_64, 24, 23), 0xBF810000], 'invalid s_ff0_i32_b64 source'), + ([sop1(FLBIT_B64, 24, VCC), 0xBF810000], 'invalid s_flbit_i32_b64 source'), + ([sop1(BCNT0_64, 24, EXEC + 1), 0xBF810000], 'invalid s_bcnt0_i32_b64 source'), + ([sop1(FLBIT_I64, 24, FLOAT_ONE), 0xBF810000], 'invalid s_flbit_i32_i64 source'), + ) + for n, (words, error) in enumerate(refused): + m = request(work, root, words) + o = m.with_suffix(f'.refused{n}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], + capture_output=True, text=True) + assert r.returncode and error in r.stderr, (error, r.stdout, r.stderr) + assert not o.exists(), o + + baseline = full_reference() + for label, flags in ( + ('missing +32 in high ff0/ff1', {'no_hi_offset_ff': True}), + ('missing +32 in low flbit', {'no_lo_offset_flbit': True}), + ('unsigned flbit_i64', {'unsigned_flbit': True}), + ('zero-extended negative literal in flbit_i64', {'zero_ext_lit': True}), + ('scan writes SCC', {'scan_writes_scc': True}), + ('zero returns 64 instead of 0xffffffff', {'zero_is_64': True}), + ): + assert full_reference(**flags) != baseline, label + + print('compiled 64-bit scalar counts and scans (adjacent s32 descriptor preserved); ' + '6 invalid forms refused; 6 reference mutants differ') + return 0 + + +def hardware(replay, sdk, work, root): + for name, code, dst, neighbor, op, lo, hi, src_kind, primed in cases(): + res, scc = eval_bitscan(op, lo, hi, src_kind, primed) + marker = request(work, root, compute_program(code, dst)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, name + assert actual[GUARD_WORDS:end] == (res, neighbor) * LANES + (scc, 0) * LANES, (name, res, neighbor, scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), name + print(f'{name}: result, neighbor, SCC and guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', + '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu_cmov_check.py b/tests/native_salu_cmov_check.py new file mode 100644 index 0000000000..9deffb019a --- /dev/null +++ b/tests/native_salu_cmov_check.py @@ -0,0 +1,313 @@ +"""Direct compute scalar conditional moves (s_cmov_b32, s_cmov_b64, s_cmovk_i32) (#3070).""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_direct_container_check import words as pack_words +from native_f16_alu_check import _branch, _exec, _i32, compute_container +from native_scalar_lds_check import scalar, sop1, vmove + + +CMOV32, CMOV64, CMOVK, CSELECT32 = 0x05, 0x06, 0x02, 0x0A +ZERO, ONE, NEG_ONE, VCC, VCC_HI, EXEC, FLOAT_ONE, LITERAL = 128, 129, 193, 106, 107, 126, 242, 255 +OLD_PAIR = (0xCAFEBABE, 0xDEADBEEF) +SRC_PAIR = (0x89ABCDEF, 0x01234567) +LITERAL32 = 0x12345678 +LITERAL64_LO = 0x80000001 +FLOAT_ONE_BITS = 0x3F800000 +MASK32 = (1 << 32) - 1 +LANES = 64 +PLANE_BYTES = LANES * 8 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def sopk(op, dst, simm16): + return 0xB0000000 | (op << 23) | (dst << 16) | (simm16 & 0xFFFF) + + +def set_pair(base, pair): + return [sop1(3, base, LITERAL), pair[0], sop1(3, base + 1, LITERAL), pair[1]] + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | (ZERO if value else ONE) << 8 + + +def compute_program(instructions, dst): + # Two 32-lane groups, with 8 bytes per lane and 256 bytes per group in each plane. + program = [sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 131, 0), vop2(0x25, 8, 7, 8)] + program += instructions + program += [vmove(2, dst), vmove(3, dst + 1), 0xE0741000, 0x80080208, + scalar(CSELECT32, 26, ONE, ZERO), vmove(2, 26), vmove(3, ZERO), + 0xE0741000 | PLANE_BYTES, 0x80080208, 0xBF810000] + return program + + +def cases(): + # Each tuple: (name, instructions, dst, is_pair, is_cmovk, new_words, expected_scc). + for scc in (0, 1): + # s_cmov_b32: SGPR, 32-bit literal, inline float, wave32 vcc_hi dst/src; neighbor word stays OLD_PAIR. + yield (f'cmov32 sgpr SCC={scc}', + set_pair(24, OLD_PAIR) + set_pair(22, SRC_PAIR) + [set_scc(scc), sop1(CMOV32, 24, 22)], + 24, False, False, (SRC_PAIR[0], OLD_PAIR[1]), scc) + yield (f'cmov32 lit SCC={scc}', + set_pair(24, OLD_PAIR) + [set_scc(scc), sop1(CMOV32, 24, LITERAL), LITERAL32], + 24, False, False, (LITERAL32, OLD_PAIR[1]), scc) + yield (f'cmov32 float SCC={scc}', + set_pair(24, OLD_PAIR) + [set_scc(scc), sop1(CMOV32, 24, FLOAT_ONE)], + 24, False, False, (FLOAT_ONE_BITS, OLD_PAIR[1]), scc) + yield (f'cmov32 vcc_hi dst SCC={scc}', + set_pair(VCC, OLD_PAIR) + set_pair(22, SRC_PAIR) + [set_scc(scc), sop1(CMOV32, VCC_HI, 22)], + VCC, False, False, (OLD_PAIR[0], SRC_PAIR[0]), scc) + yield (f'cmov32 vcc_hi src SCC={scc}', + set_pair(24, OLD_PAIR) + set_pair(VCC, SRC_PAIR) + [set_scc(scc), sop1(CMOV32, 24, VCC_HI)], + 24, False, False, (SRC_PAIR[1], OLD_PAIR[1]), scc) + + # s_cmovk_i32: negative, positive, and wave32 vcc_hi dst; neighbor word untouched. + yield (f'cmovk neg SCC={scc}', + set_pair(24, OLD_PAIR) + [set_scc(scc), sopk(CMOVK, 24, -1234)], + 24, False, True, ((-1234) & MASK32, OLD_PAIR[1]), scc) + yield (f'cmovk pos SCC={scc}', + set_pair(24, OLD_PAIR) + [set_scc(scc), sopk(CMOVK, 24, 0x7FFF)], + 24, False, True, (0x7FFF, OLD_PAIR[1]), scc) + yield (f'cmovk vcc_hi dst SCC={scc}', + set_pair(VCC, OLD_PAIR) + [set_scc(scc), sopk(CMOVK, VCC_HI, -1234)], + VCC, False, True, (OLD_PAIR[0], (-1234) & MASK32), scc) + + # s_cmov_b64: SGPR pair, inline -1 (sign-extended), 32-bit literal (zero-extended), and vcc dst. + yield (f'cmov64 pair SCC={scc}', + set_pair(24, OLD_PAIR) + set_pair(22, SRC_PAIR) + [set_scc(scc), sop1(CMOV64, 24, 22)], + 24, True, False, SRC_PAIR, scc) + yield (f'cmov64 neg1 SCC={scc}', + set_pair(24, OLD_PAIR) + [set_scc(scc), sop1(CMOV64, 24, NEG_ONE)], + 24, True, False, (MASK32, MASK32), scc) + yield (f'cmov64 lit SCC={scc}', + set_pair(24, OLD_PAIR) + [set_scc(scc), sop1(CMOV64, 24, LITERAL), LITERAL64_LO], + 24, True, False, (LITERAL64_LO, 0), scc) + yield (f'cmov64 vcc SCC={scc}', + set_pair(VCC, OLD_PAIR) + set_pair(22, SRC_PAIR) + [set_scc(scc), sop1(CMOV64, VCC, 22)], + VCC, True, False, SRC_PAIR, scc) + + +def eval_case(is_pair, is_cmovk, new_words, scc, *, inverted=False, unconditional=False, + zero_ext_cmovk=False, zero_ext_b64=False, clobber_scc=False): + cond = (1 - scc) if inverted else (1 if unconditional else scc) + if cond: + lo, hi = new_words + if zero_ext_cmovk and is_cmovk: + if lo != OLD_PAIR[0] and (lo >> 15): + lo &= 0xFFFF + if hi != OLD_PAIR[1] and (hi >> 15): + hi &= 0xFFFF + if zero_ext_b64 and is_pair and new_words == (MASK32, MASK32): + hi = 0 + result_words = (lo, hi) + else: + result_words = OLD_PAIR + out_scc = (1 - scc) if clobber_scc else scc + return result_words, out_scc + + +def full_reference(**mutant_flags): + return [eval_case(is_pair, is_cmovk, new_words, scc, **mutant_flags) + for _, _, _, is_pair, is_cmovk, new_words, scc in cases()] + + +TRANSFER_BASELINE = [sop1(3, 20, 4), sop1(3, 21, ZERO), 0xF4080000 | 32 << 6 | 10, 0xFA000020, 0xBF810000] + + +def refused_programs(): + programs = [ + ([sop1(CMOV32, EXEC, 22), 0xBF810000], 'invalid s_cmov_b32 destination'), + ([sopk(CMOVK, EXEC, 1), 0xBF810000], 'invalid s_cmovk_i32 destination'), + ([sop1(CMOV64, EXEC, 22), 0xBF810000], 'invalid s_cmov_b64 destination'), + ([sop1(CMOV64, 25, 22), 0xBF810000], 'invalid s_cmov_b64 destination'), + ([sop1(CMOV32, 24, EXEC), 0xBF810000], 'invalid s_cmov_b32 source'), + ([sop1(CMOV64, 24, 23), 0xBF810000], 'invalid s_cmov_b64 source'), + ([sop1(CMOV64, 24, VCC), 0xBF810000], 'invalid s_cmov_b64 source'), + ([sop1(CMOV64, 24, FLOAT_ONE), 0xBF810000], 'invalid s_cmov_b64 source'), + ] + # Omit the store epilogue so only the s_cmov* at +0x20 reads the symbolic descriptor s24. + sym_prefix = [sop1(3, 20, 4), sop1(3, 21, ZERO), 0xF4040000 | 24 << 6 | 10, 0xFA000020] + set_pair(22, SRC_PAIR) + for cmov in (sop1(CMOV64, 24, 22), sop1(CMOV32, 24, 22), sopk(CMOVK, 24, 1)): + programs.append((sym_prefix + [cmov, 0xBF810000], 'native compute +0x20: unbound numeric SGPR s24')) + # transfer() must clear s21 constant state on s_cmovk_i32 before s_load_dwordx4 at +0x10. + programs.append(( + [sop1(3, 20, 4), sop1(3, 21, ZERO), set_scc(0), sopk(CMOVK, 21, 1), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, 0xBF810000], + 'native compute +0x10: direct descriptor address outside bound table', + )) + return programs + + +def interpret_pair_stores(ir_text): + """Lane 0 of a straight-line compute module; returns sorted (byte address, lo, hi) stores.""" + body = ir_text.split('define void @main()', 1)[1].split('\n}', 1)[0] + blocks, label, buf = {}, None, [] + for raw in body.splitlines(): + line = raw.strip() + if not line or line == '{': + continue + if line.endswith(':') and ' ' not in line: + if label is not None: + blocks[label] = buf + label, buf = line[:-1], [] + continue + if label is None: + raise AssertionError(line) + buf.append(line) + if label is not None: + blocks[label] = buf + values, memory, raw_stores = {}, {}, [] + label, steps = 'entry', 0 + while steps < 200000: + steps += 1 + followed = False + for line in blocks[label]: + if line.startswith('br '): + label = _branch(line, values) + followed = True + break + if line == 'ret void': + return sorted(raw_stores) + if 'rawBufferStore.i32' in line: + match = re.search( + r'rawBufferStore\.i32\(i32 140, %dx\.types\.Handle \S+, i32 (\S+), i32 \S+, i32 (\S+), i32 (\S+),', + line, + ) + assert match, line + raw_stores.append(( + _i32(match.group(1), values), + _i32(match.group(2), values), + _i32(match.group(3), values), + )) + else: + _exec(line, values, memory, []) + if not followed: + raise AssertionError('block fell through: ' + label) + raise AssertionError('step limit') + + +def check_mutants(): + baseline = full_reference() + for label, flags in ( + ('inverted SCC', {'inverted': True}), + ('unconditional move', {'unconditional': True}), + ('zero-extended cmovk immediate', {'zero_ext_cmovk': True}), + ('zero-extended s_cmov_b64 -1', {'zero_ext_b64': True}), + ('clobbered SCC', {'clobber_scc': True}), + ): + assert full_reference(**flags) != baseline, label + + +def ir(dumper): + all_cases = list(cases()) + refusals = refused_programs() + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for index, (name, code, dst, is_pair, is_cmovk, new_words, scc) in enumerate(all_cases): + path = work / f'case{index}.cdx' + path.write_bytes(compute_container(pack_words(*compute_program(code, dst)))) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, (name, run.stderr) + text = run.stdout + if name == 'cmovk neg SCC=1': + assert '4294966062' in text and '64302' not in text, (name, text) + stores = interpret_pair_stores(text) + assert len(stores) == 2 and stores[0][0] == 0 and stores[1][0] == PLANE_BYTES, (name, stores) + expected_words, out_scc = eval_case(is_pair, is_cmovk, new_words, scc) + assert (stores[0][1], stores[0][2]) == expected_words, (name, stores[0], expected_words) + assert (stores[1][1], stores[1][2]) == (out_scc, 0), (name, stores[1], out_scc) + + base_path = work / 'transfer_base.cdx' + base_path.write_bytes(compute_container(pack_words(*TRANSFER_BASELINE))) + base_run = subprocess.run([dumper, str(base_path)], capture_output=True, text=True) + assert base_run.returncode == 0, base_run.stderr + + for index, (prog_words, error) in enumerate(refusals): + path = work / f'refused{index}.cdx' + path.write_bytes(compute_container(pack_words(*prog_words))) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode != 0 and error in run.stderr, (error, run.returncode, run.stderr) + + check_mutants() + print(f'evaluated DXIL IR for {len(all_cases)} s_cmov cases, verified {len(refusals)} exact-pc/diagnostic ' + 'refusals + transfer() baseline, and confirmed 5 reference mutants differ') + return 0 + + +def controls(cli, sdk, work, root): + accepted = [case for case in cases() if case[-1] == 1] + for index, (name, code, dst, _, _, _, _) in enumerate(accepted): + marker = request(work, root, compute_program(code, dst)) + output = marker.with_suffix(f'.ok{index}.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (name, result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + assert 'select i1' in dump, (name, dump) + + base_marker = request(work, root, TRANSFER_BASELINE) + base_out = base_marker.with_suffix('.transfer.cso') + base_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', base_marker, base_out], + capture_output=True, text=True) + assert base_res.returncode == 0 and base_out.is_file(), (base_res.stdout, base_res.stderr) + + refusals = refused_programs() + for n, (prog_words, error) in enumerate(refusals): + m = request(work, root, prog_words) + o = m.with_suffix(f'.refused{n}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], + capture_output=True, text=True) + assert r.returncode and error in r.stderr, (error, r.stdout, r.stderr) + assert not o.exists(), o + + check_mutants() + print(f'compiled all {len(accepted)} accepted s_cmov forms; verified {len(refusals)} exact-pc/diagnostic ' + 'refusals + transfer() baseline; 5 reference mutants differ') + return 0 + + +def hardware(replay, sdk, work, root): + for name, code, dst, is_pair, is_cmovk, new_words, scc in cases(): + result_words, out_scc = eval_case(is_pair, is_cmovk, new_words, scc) + marker = request(work, root, compute_program(code, dst)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, name + assert actual[GUARD_WORDS:end] == result_words * LANES + (out_scc, 0) * LANES, (name, result_words, out_scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), name + print(f'{name}: result words, preserved SCC and guards matched') + return 0 + + +def main(mode, tool, sdk=None): + if mode == 'ir': + return ir(tool) + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', + '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu_cmp64_check.py b/tests/native_salu_cmp64_check.py new file mode 100644 index 0000000000..136ebd2feb --- /dev/null +++ b/tests/native_salu_cmp64_check.py @@ -0,0 +1,329 @@ +"""Direct compute 64-bit SOPC comparison and bit-test checks.""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request +from native_direct_container_check import words as pack_words +from native_f16_alu_check import _branch, _exec, _i32, compute_container +from native_salu64_check import ( + GUARD_WORDS, LANES, LITERAL, LITERAL_VALUE, MASK32, NEG_ONE, OUTPUT_WORDS, + PLANE_BYTES, SENTINEL, ZERO, compute_program, set_pair, set_scc, +) +from native_scalar_lds_check import sop1 + + +S_BITCMP0_B64, S_BITCMP1_B64, S_CMP_EQ_U64, S_CMP_LG_U64 = 0x0E, 0x0F, 0x12, 0x13 +NULL = 125 +VCC_LO, EXEC_LO, INLINE_FLOAT_ONE = 106, 126, 242 +PAIR = (0x89ABCDEF, 0x01234567) + + +def sopc(op, a, b): + return 0xBF000000 | (op << 16) | (b << 8) | a + + +def _src64(kind, spec): + if kind == "pair": + return spec + if kind == "null": + return (0, 0) + if kind == "inline": + val = (spec - 128) if spec <= 192 else (192 - spec) + return (val & MASK32, MASK32 if spec >= 193 else 0) + return (spec, 0) + + +def cases(): + # (label, op, s0_kind, s0_spec, s1_kind, s1_spec, reg_pair) + cmp_specs = [ + ("eq equal pairs", S_CMP_EQ_U64, "pair", PAIR, "pair", PAIR), + ("eq hi differs", S_CMP_EQ_U64, "pair", PAIR, "pair", (PAIR[0], PAIR[1] ^ 1)), + ("eq lo differs", S_CMP_EQ_U64, "pair", PAIR, "pair", (PAIR[0] ^ 1, PAIR[1])), + ("lg hi differs", S_CMP_LG_U64, "pair", PAIR, "pair", (PAIR[0], PAIR[1] ^ 0x80000000)), + ("lg equal pairs", S_CMP_LG_U64, "pair", PAIR, "pair", PAIR), + ("eq -1 vs all ones", S_CMP_EQ_U64, "pair", (MASK32, MASK32), "inline", NEG_ONE), + ("eq -1 vs lo-only 0xffffffff", S_CMP_EQ_U64, "pair", (MASK32, 0), "inline", NEG_ONE), + ("eq lit 0x80000001 vs zext", S_CMP_EQ_U64, "pair", (LITERAL_VALUE, 0), "lit", LITERAL_VALUE), + ("lg lit 0x80000001 vs sext", S_CMP_LG_U64, "pair", (LITERAL_VALUE, MASK32), "lit", LITERAL_VALUE), + ("eq null vs (0,0)", S_CMP_EQ_U64, "null", 0, "pair", (0, 0)), + ("eq null vs (0,1)", S_CMP_EQ_U64, "null", 0, "pair", (0, 1)), + ] + for label, op, k0, s0, k1, s1 in cmp_specs: + code = [] + a_enc = 22 + b_enc = 24 + if k0 == "pair": + code += set_pair(s0) + elif k0 == "null": + a_enc = NULL + elif k0 == "inline": + a_enc = s0 + else: + a_enc = LITERAL + if k1 == "pair": + # Also preload s[22:23] with PAIR so compute_program(dst=22) verifies SOPC preserves SGPRs. + if k0 != "pair": + code += set_pair(PAIR) + code += [sop1(3, 24, LITERAL), s1[0], sop1(3, 25, LITERAL), s1[1]] + elif k1 == "inline": + b_enc = s1 + elif k1 == "null": + b_enc = NULL + else: + b_enc = LITERAL + expected_pair = s0 if k0 == "pair" else PAIR + if k0 != "pair" and k1 != "pair": + code += set_pair(PAIR) + v0, v1 = _src64(k0, s0), _src64(k1, s1) + scc = int(v0 == v1) if op == S_CMP_EQ_U64 else int(v0 != v1) + inst = [sopc(op, a_enc, b_enc)] + if a_enc == LITERAL: + inst.append(s0) + if b_enc == LITERAL: + inst.append(s1) + code += [set_scc(1 - scc)] + inst + yield label, code, 22, expected_pair, scc, (op, k0, v0, k1, v1) + + bit_specs = [ + ("bitcmp1 bit 0 set", S_BITCMP1_B64, "pair", (1, 0), "imm", 0), + ("bitcmp1 bit 31 set", S_BITCMP1_B64, "pair", (0x80000000, 0), "imm", 31), + ("bitcmp1 bit 32 set", S_BITCMP1_B64, "pair", (0, 1), "imm", 32), + ("bitcmp0 bit 32 clear", S_BITCMP0_B64, "pair", (1, 0), "imm", 32), + ("bitcmp1 bit 63 set", S_BITCMP1_B64, "pair", (0, 0x80000000), "imm", 63), + ("bitcmp1 wrapped bit 65 (odd sgpr)", S_BITCMP1_B64, "pair", (2, 0), "sgpr27", 65), + ("bitcmp0 wrapped bit 96 (sgpr)", S_BITCMP0_B64, "pair", (0, 0), "sgpr27", 96), + ("bitcmp1 -1 bit 63", S_BITCMP1_B64, "inline", NEG_ONE, "imm", 63), + ("bitcmp1 lit 0x80000001 bit 31", S_BITCMP1_B64, "lit", LITERAL_VALUE, "imm", 31), + ("bitcmp0 lit 0x80000001 bit 32", S_BITCMP0_B64, "lit", LITERAL_VALUE, "imm", 32), + ("bitcmp0 null bit 0", S_BITCMP0_B64, "null", 0, "imm", 0), + ] + for label, op, k0, s0, k1, bit_idx in bit_specs: + code = set_pair(s0 if k0 == "pair" else PAIR) + expected_pair = s0 if k0 == "pair" else PAIR + if k0 == "pair": + a_enc = 22 + elif k0 == "inline": + a_enc = s0 + elif k0 == "null": + a_enc = NULL + else: + a_enc = LITERAL + if k1 == "imm": + b_enc = ZERO + bit_idx + else: + code += [sop1(3, 27, LITERAL), bit_idx] + b_enc = 27 + v0 = _src64(k0, s0) + val64 = v0[0] | (v0[1] << 32) + bit = (val64 >> (bit_idx & 63)) & 1 + scc = int(bit == 0) if op == S_BITCMP0_B64 else int(bit == 1) + inst = [sopc(op, a_enc, b_enc)] + if a_enc == LITERAL: + inst.append(s0) + code += [set_scc(1 - scc)] + inst + yield label, code, 22, expected_pair, scc, (op, k0, v0, "bit", bit_idx) + + +def _mutant_scc(mutant, meta): + op, k0, v0, k1, v1 = meta + if op in (S_CMP_EQ_U64, S_CMP_LG_U64): + a0, a1 = v0 + b0, b1 = v1 + if mutant == "zero_ext_neg_inline": + if k0 == "inline": + a1 = 0 + if k1 == "inline": + b1 = 0 + elif mutant == "sign_ext_lit": + if k0 == "lit" and (a0 & 0x80000000): + a1 = MASK32 + if k1 == "lit" and (b0 & 0x80000000): + b1 = MASK32 + if mutant == "low_word_only_cmp": + eq = (a0 == b0) + elif mutant == "high_word_only_cmp": + eq = (a1 == b1) + else: + eq = (a0, a1) == (b0, b1) + return int(eq) if op == S_CMP_EQ_U64 else int(not eq) + # bitcmp + a0, a1 = v0 + idx = v1 + if mutant == "sign_ext_lit" and k0 == "lit" and (a0 & 0x80000000): + a1 = MASK32 + val64 = a0 | (a1 << 32) + eff = (idx & 31) if mutant == "ignore_bit5_bitcmp" else (idx & 63) + bit = (val64 >> eff) & 1 + if mutant == "inverted_bitcmp": + return int(bit == 1) if op == S_BITCMP0_B64 else int(bit == 0) + return int(bit == 0) if op == S_BITCMP0_B64 else int(bit == 1) + + +def refused_programs(): + init = set_pair((0, 0)) + [sop1(3, 24, ZERO), sop1(3, 25, ZERO)] + return [ + (init + [sopc(S_CMP_EQ_U64, 23, 24), 0xBF810000], "unaligned scalar mask pair"), + (init + [sopc(S_CMP_EQ_U64, VCC_LO, 24), 0xBF810000], "invalid s_cmp_eq_u64 source"), + (init + [sopc(S_CMP_LG_U64, 22, EXEC_LO), 0xBF810000], "invalid s_cmp_lg_u64 source"), + (init + [sopc(S_CMP_EQ_U64, 22, INLINE_FLOAT_ONE), 0xBF810000], "unsupported wave64 scalar pair"), + (init + [sopc(S_BITCMP0_B64, 23, ZERO), 0xBF810000], "unaligned scalar mask pair"), + (init + [sopc(S_BITCMP1_B64, 22, INLINE_FLOAT_ONE), 0xBF810000], "invalid s_bitcmp1_b64 bit index"), + (init + [sopc(S_BITCMP0_B64, 22, VCC_LO), 0xBF810000], "invalid s_bitcmp0_b64 bit index"), + ] + + +def interpret_pair_stores(ir_text): + """Lane 0 of a straight-line compute module; returns sorted (byte address, lo, hi) stores.""" + body = ir_text.split("define void @main()", 1)[1].split("\n}", 1)[0] + blocks, label, buf = {}, None, [] + for raw in body.splitlines(): + line = raw.strip() + if not line or line == "{": + continue + if line.endswith(":") and " " not in line: + if label is not None: + blocks[label] = buf + label, buf = line[:-1], [] + continue + if label is None: + raise AssertionError(line) + buf.append(line) + if label is not None: + blocks[label] = buf + values, memory, raw_stores = {}, {}, [] + label, steps = "entry", 0 + while steps < 200000: + steps += 1 + followed = False + for line in blocks[label]: + if line.startswith("br "): + label = _branch(line, values) + followed = True + break + if line == "ret void": + return sorted(raw_stores) + if "rawBufferStore.i32" in line: + match = re.search( + r"rawBufferStore\.i32\(i32 140, %dx\.types\.Handle \S+, i32 (\S+), i32 \S+, i32 (\S+), i32 (\S+),", + line, + ) + assert match, line + raw_stores.append(( + _i32(match.group(1), values), + _i32(match.group(2), values), + _i32(match.group(3), values), + )) + else: + _exec(line, values, memory, []) + if not followed: + raise AssertionError("block fell through: " + label) + raise AssertionError("step limit") + + +def check_mutants(): + expected = [(label, scc, meta) for label, _, _, _, scc, meta in cases()] + for mutant in ("low_word_only_cmp", "high_word_only_cmp", "zero_ext_neg_inline", + "sign_ext_lit", "ignore_bit5_bitcmp", "inverted_bitcmp"): + mismatches = [label for label, scc, meta in expected if _mutant_scc(mutant, meta) != scc] + assert mismatches, f"mutant {mutant} agreed on every case" + print(f"mutant {mutant} caught on {len(mismatches)} case(s)") + + +def ir(dumper): + all_cases = list(cases()) + refusals = refused_programs() + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for index, (label, code, dst, expected_pair, scc, _) in enumerate(all_cases): + path = work / f"case{index}.cdx" + path.write_bytes(compute_container(pack_words(*compute_program(code, dst)))) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, (label, run.stderr) + text = run.stdout + for forbidden in ("icmp eq i64", "icmp ne i64", "lshr i64", "shl i64"): + assert forbidden not in text, f"unexpected 64-bit IR op {forbidden} in {label}:\n{text}" + stores = interpret_pair_stores(text) + assert len(stores) == 2 and stores[0][0] == 0 and stores[1][0] == PLANE_BYTES, (label, stores) + assert (stores[0][1], stores[0][2]) == expected_pair, (label, stores[0], expected_pair) + assert (stores[1][1], stores[1][2]) == (scc, 0), (label, stores[1], scc) + + for index, (prog_words, expected_error) in enumerate(refusals): + path = work / f"refused{index}.cdx" + path.write_bytes(compute_container(pack_words(*prog_words))) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode != 0 and expected_error in run.stderr, (expected_error, run.returncode, run.stderr) + + check_mutants() + print(f"evaluated DXIL IR for {len(all_cases)} 64-bit SOPC cases (pure 32-bit IR) and verified {len(refusals)} refusals") + return 0 + + +def controls(cli, sdk, work, root): + # 1. Compile all cases together and check pure 32-bit DXIL IR (no i64 instructions). + combined = [] + for _, code, _, _, _, _ in cases(): + combined += code + marker = request(work, root, compute_program(combined, 22)) + cso = work / "combined.cso" + subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, cso], check=True) + dis = subprocess.run([Path(sdk) / "dxc.exe", "-dumpbin", cso], + capture_output=True, text=True, check=True).stdout + for forbidden in ("icmp eq i64", "icmp ne i64", "lshr i64", "shl i64"): + assert forbidden not in dis, f"unexpected 64-bit IR op {forbidden} in:\n{dis}" + for required in ("icmp eq i32", "icmp ne i32", "lshr i32"): + assert required in dis, f"missing {required} in DXIL disassembly" + print("compiled all 22 64-bit SOPC cases cleanly with pure 32-bit DXIL IR") + + # 2. Negative operand refusal controls (initialize s[22:25] so only the invalid operand triggers refusal). + refusals = refused_programs() + for prog_words, expected_error in refusals: + bad = request(work, root, prog_words) + bad_cso = work / "bad.cso" + bad_cso.unlink(missing_ok=True) + res = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", bad, bad_cso], + capture_output=True, text=True) + assert res.returncode and expected_error in res.stderr, (prog_words, res.stdout, res.stderr) + assert not bad_cso.exists() + print(f"refused: {expected_error}") + + # 3. Mutant controls over expected SCC oracle. + check_mutants() + return 0 + + +def hardware(replay, sdk, work, root): + for label, code, dst, expected_pair, scc, _ in cases(): + marker = request(work, root, compute_program(code, dst)) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, label + assert actual[GUARD_WORDS:end] == expected_pair * LANES + (scc, 0) * LANES, (label, expected_pair, scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), label + print(f"{label}: preserved pair, SCC and guards matched") + return 0 + + +def main(mode, tool, sdk=None): + if mode == "ir": + return ir(tool) + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_salu_shift64_check.py b/tests/native_salu_shift64_check.py new file mode 100644 index 0000000000..ec48454b9a --- /dev/null +++ b/tests/native_salu_shift64_check.py @@ -0,0 +1,209 @@ +"""Direct compute 64-bit scalar shift (s_lshl_b64, s_lshr_b64, s_ashr_i64) controls and readback (#3062).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1, vmove + + +LSHL64, LSHR64, ASHR64, CSELECT32 = 0x1F, 0x21, 0x23, 0x0A +ZERO, ONE, NEG_ONE, NEG_SIXTEEN, SIXTY_FOUR, VCC, EXEC, FLOAT_ONE, LITERAL = 128, 129, 193, 208, 192, 106, 126, 242, 255 +PAIR = (0x89ABCDEF, 0x81234567) +LITERAL_VALUE = 0x80000001 +MASK32 = (1 << 32) - 1 +MASK64 = (1 << 64) - 1 +LANES = 64 +PLANE_BYTES = LANES * 8 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def set_pair(words): + return [sop1(3, 22, LITERAL), words[0], sop1(3, 23, LITERAL), words[1]] + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | (ZERO if value else ONE) << 8 + + +def compute_program(instructions, dst): + # Two 32-lane groups, with 8 bytes per lane and 256 bytes per group in each plane. + program = [sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 131, 0), vop2(0x25, 8, 7, 8)] + program += instructions + program += [vmove(2, dst), vmove(3, dst + 1), 0xE0741000, 0x80080208, + scalar(CSELECT32, 26, ONE, ZERO), vmove(2, 26), vmove(3, ZERO), + 0xE0741000 | PLANE_BYTES, 0x80080208, 0xBF810000] + return program + + +def eval_shift(op, lo, hi, src_kind, amount, *, logical_ashr=False, zero_ext_neg=False, + zero_ext_lit=False, sign_ext_lit=False, mask_amount=True): + shift = amount & 63 if mask_amount else amount + if src_kind == 'neg_inline': + hi_word = 0 if zero_ext_neg else MASK32 + elif src_kind == 'pos_inline': + hi_word = 0 + elif src_kind == 'literal': + if zero_ext_lit: + hi_word = 0 + elif (op == ASHR64 or sign_ext_lit) and (lo >> 31): + hi_word = MASK32 + else: + hi_word = 0 + else: + hi_word = hi + val = (hi_word << 32) | (lo & MASK32) + if op == LSHL64: + res = (val << shift) & MASK64 + elif op == LSHR64 or logical_ashr: + res = val >> shift + else: + signed_val = val - (1 << 64) if (val >> 63) else val + res = (signed_val >> shift) & MASK64 + return (res & MASK32, (res >> 32) & MASK32) + + +def cases(): + # SGPR pair across boundary amounts and odd SGPR wrapped shift amount (65 & 63 == 1). + for op, opname in ((LSHL64, 'lshl'), (LSHR64, 'lshr'), (ASHR64, 'ashr')): + for amount in (0, 1, 31, 32, 33, 63): + code = set_pair(PAIR) + [set_scc(0), scalar(op, 24, 22, ZERO + amount)] + yield (f'{opname} pair,{amount}', code, 24, op, PAIR[0], PAIR[1], 'pair', amount) + code = set_pair(PAIR) + [sop1(3, 27, LITERAL), 65, set_scc(0), scalar(op, 24, 22, 27)] + yield (f'{opname} pair,s27(65)', code, 24, op, PAIR[0], PAIR[1], 'pair', 65) + + # Inline integers: negative (-1, -16) and positive (1, 64). + for op, opname in ((LSHL64, 'lshl'), (LSHR64, 'lshr'), (ASHR64, 'ashr')): + for label, enc, lo, hi, src_kind in (('neg1', NEG_ONE, MASK32, MASK32, 'neg_inline'), + ('neg16', NEG_SIXTEEN, 0xFFFFFFF0, MASK32, 'neg_inline'), + ('pos1', ONE, 1, 0, 'pos_inline'), + ('pos64', SIXTY_FOUR, 64, 0, 'pos_inline')): + code = [set_scc(0), scalar(op, 24, enc, ZERO + 5)] + yield (f'{opname} {label},5', code, 24, op, lo, hi, src_kind, 5) + + # 32-bit literal 0x80000001: zero-extended for logical shifts, sign-extended for s_ashr_i64. + for op, opname in ((LSHR64, 'lshr'), (ASHR64, 'ashr')): + code = [set_scc(0), scalar(op, 24, LITERAL, ZERO + 4), LITERAL_VALUE] + yield (f'{opname} lit,4', code, 24, op, LITERAL_VALUE, 0, 'literal', 4) + + # Overlapping in-place destinations: s[22:23] written after reading s[22:23] and s22/s23. + code = set_pair((0x12345678, 0x9ABCDEF0)) + [set_scc(0), scalar(LSHR64, 22, 22, 22)] + yield ('lshr overlap s22', code, 22, LSHR64, 0x12345678, 0x9ABCDEF0, 'pair', 0x12345678) + code = set_pair((0x12345678, 0x9ABCDEF0)) + [set_scc(0), scalar(LSHL64, 22, 22, 23)] + yield ('lshl overlap s23', code, 22, LSHL64, 0x12345678, 0x9ABCDEF0, 'pair', 0x9ABCDEF0) + + # High-word-only nonzero into VCC (SCC=1), and zero result clearing primed SCC=1. + yield ('lshl vcc high only', [set_scc(0), scalar(LSHL64, VCC, ONE, ZERO + 32)], VCC, LSHL64, 1, 0, 'pos_inline', 32) + yield ('lshr zero clears scc', [set_scc(1), scalar(LSHR64, 24, ONE, ONE)], 24, LSHR64, 1, 0, 'pos_inline', 1) + + +def full_reference(*, scc_low_only=False, **mutant_flags): + out = [] + for _, _, _, op, lo, hi, src_kind, amount in cases(): + words = eval_shift(op, lo, hi, src_kind, amount, **mutant_flags) + scc = int(words[0] != 0) if scc_low_only else int(any(words)) + out.append((words, scc)) + return out + + +def controls(cli, sdk, work, root): + # Compile representative program covering all three opcodes and verify DXIL 64-bit shifts. + ir_program = compute_program( + set_pair(PAIR) + [ + scalar(LSHL64, 24, 22, ZERO + 5), + scalar(LSHR64, 24, 24, ONE), + scalar(ASHR64, 24, 24, ONE), + ], 24) + marker = request(work, root, ir_program) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, check=True).stdout + for insn in ('shl i64', 'lshr i64', 'ashr i64'): + assert insn in dump, (insn, dump) + + # Symbolic-descriptor overwrite regression for s_ashr_i64: s_load_dwordx2 s[24:25], s[20:21], 0x20 + # tags both s24 and s25 as descriptor; s_ashr_i64 must clear both symbolic tags so vmove(3, 25) succeeds. + sym_prog = compute_program([0xF4040000 | 24 << 6 | 10, 0xFA000020, scalar(ASHR64, 24, NEG_ONE, ONE)], 24) + sym_marker = request(work, root, sym_prog) + sym_out = sym_marker.with_suffix('.sym.cso') + sym_res = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', sym_marker, sym_out], + capture_output=True, text=True) + assert sym_res.returncode == 0 and sym_out.is_file(), (sym_res.stdout, sym_res.stderr) + + # Refused operand/destination controls. + refused = ( + ([scalar(LSHL64, EXEC, 22, ONE), 0xBF810000], 'invalid s_lshl_b64 destination'), + ([scalar(LSHR64, 25, 22, ONE), 0xBF810000], 'invalid s_lshr_b64 destination'), + ([scalar(ASHR64, 24, 23, ONE), 0xBF810000], 'invalid s_ashr_i64 source'), + ([scalar(LSHL64, 24, VCC, ONE), 0xBF810000], 'invalid s_lshl_b64 source'), + ([scalar(LSHR64, 24, FLOAT_ONE, ONE), 0xBF810000], 'invalid s_lshr_b64 source'), + ([scalar(ASHR64, 24, 22, FLOAT_ONE), 0xBF810000], 'invalid s_ashr_i64 source'), + ([scalar(LSHL64, 24, 22, VCC), 0xBF810000], 'invalid s_lshl_b64 source'), + ) + for n, (words, error) in enumerate(refused): + m = request(work, root, words) + o = m.with_suffix(f'.refused{n}.cso') + r = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', m, o], + capture_output=True, text=True) + assert r.returncode and error in r.stderr, (error, r.stdout, r.stderr) + assert not o.exists(), o + + # Mutants must each alter the reference expectations. + baseline = full_reference() + for label, flags in ( + ('logical ashr', {'logical_ashr': True}), + ('zero-extended negative inline', {'zero_ext_neg': True}), + ('zero-extended literal for ashr', {'zero_ext_lit': True}), + ('sign-extended literal for lshr', {'sign_ext_lit': True}), + ('SCC from low word only', {'scc_low_only': True}), + ('unmasked shift amount', {'mask_amount': False}), + ): + assert full_reference(**flags) != baseline, label + + print('compiled s_lshl_b64, s_lshr_b64 and s_ashr_i64 (including descriptor overwrite); ' + '7 invalid operand/destination forms refused; 6 reference mutants differ') + return 0 + + +def hardware(replay, sdk, work, root): + for name, code, dst, op, lo, hi, src_kind, amount in cases(): + words = eval_shift(op, lo, hi, src_kind, amount) + scc = int(any(words)) + marker = request(work, root, compute_program(code, dst)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes()) + end = GUARD_WORDS + LANES * 4 + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS, name + assert actual[GUARD_WORDS:end] == words * LANES + (scc, 0) * LANES, (name, words, scc) + assert actual[end:] == (SENTINEL,) * (OUTPUT_WORDS - end), name + print(f'{name}: result words, SCC and guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', + '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_sample_ssamp_check.py b/tests/native_sample_ssamp_check.py new file mode 100644 index 0000000000..b9171daa6e --- /dev/null +++ b/tests/native_sample_ssamp_check.py @@ -0,0 +1,58 @@ +"""Check that direct 2D image_sample_lz accepts all five sampler index bits.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +import compute_gather4_l_check as texture +from native_direct_container_check import compute, words +from native_gather_lod_check import render, render_compute + + +def program(sampler_base, reserved_bits): + code = [ + 0xBE810380, 0xF40C0200, 0xFA000000, # texture descriptor into s[8:15] + 0xF4080800, 0xFA000020, # output descriptor into s[32:35] + 0x7E060280, # v3 = output byte offset 0 + ] + for reg, value in enumerate(texture.SAMPLER, start=sampler_base): + code.extend((0xBE8003FF | reg << 16, value)) + code.extend(( + 0x7E0002FF, 0x3C800000, # v0 = 0.5 / 32 + 0x7E0202FF, 0x3D800000, # v1 = 0.5 / 8 + 0xBF8CC07F, + # image_sample_lz v[4:7], v[0:1], s[8:15], s[sampler_base:sampler_base+3] + 0xF09C0F08, ((sampler_base // 4) << 21) | 0x00020400 | reserved_bits, + 0xBF8C3F70, + 0xE0781000, 0x80080403, # buffer_store_dwordx4 v[4:7] + 0xBF810000, + )) + return compute(words(*code), threads=1, table=True) + + +def main(cli, sdk, renderer, adapter): + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + # The bilinear sample is centered on texel (0, 0) of mip 0. + expected = [texture.texel(0, 0, 0, channel) for channel in range(4)] + [texture.SENTINEL] * 316 + for name, base, reserved_bits in (('low', 4, 0), ('high', 68, 0), ('reserved', 68, 1 << 26)): + source = work / name + source.write_bytes(program(base, reserved_bits)) + shader = source.with_suffix('.cso') + compiled = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + if reserved_bits: + assert compiled.returncode != 0 and 'direct image opcode or descriptor modifiers' in compiled.stderr, ( + compiled.stdout, compiled.stderr) + continue + assert compiled.returncode == 0, (name, compiled.stdout, compiled.stderr) + result = render_compute(renderer, adapter, shader, work / 'expected.bin', 0, expected) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + name, result.stdout, result.stderr) + print('Both sampler quads matched the CPU reference. Reserved bit 26 was refused.') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_sampled_pixel_gpu.cpp b/tests/native_sampled_pixel_gpu.cpp new file mode 100644 index 0000000000..df1f808fd3 --- /dev/null +++ b/tests/native_sampled_pixel_gpu.cpp @@ -0,0 +1,270 @@ +#include "desktop_gpu.h" +#include "gfx1013_sampled_pixel.h" +#include "gfx1013_vertex_id.h" +#include "shader_dxil_compiler.h" +#include "xmem_test_device.h" +#include <d3d12sdklayers.h> +#include <array> +#include <chrono> +#include <cstring> +#include <fstream> +#include <iterator> + +using Microsoft::WRL::ComPtr; +namespace { +using Color=std::array<float,4>; +constexpr unsigned width=8,height=4; +constexpr Color left{0.125f,1,2,1},right{2,0.5f,1,1}; +constexpr Color first{0.25f,0,0,1},last{4,0,0,1}; +constexpr Color sentinel{8,8,8,8}; +constexpr DXGI_FORMAT formats[]{DXGI_FORMAT_R32G32B32A32_FLOAT,DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R11G11B10_FLOAT,DXGI_FORMAT_R16_FLOAT}; + +// Two independently sampled inputs. Coordinates include a runtime offset. +// Rename registers and use table 0 to exercise decoded operands and bindings. +std::string packet(unsigned color_mask=7, bool implicit=false, unsigned sampler_word2=0) { + std::vector<unsigned> w; + auto emit=[&](std::initializer_list<unsigned> a){w.insert(w.end(),a);}; + auto mov=[&](unsigned d,unsigned s){emit({0xbe800300u|d<<16|s});}; + auto interp=[&](unsigned d,unsigned c){for(unsigned i=0;i<2;++i)emit({0xc8000000u|d<<18|i<<16|c<<8|i});}; + auto sample=[&](unsigned d,unsigned mask,unsigned tex){ + emit({(implicit ? 0xf0800008u : 0xf09c0008u)|mask<<8,6u|d<<8|(tex/4)<<16|(44u/4)<<21}); + }; + auto mix=[&](unsigned d,unsigned src,bool high){ + emit({(high?0xcc224000u:0xcc214000u)|d,0x82000000u|(256+src)<<9|(256+84)}); + }; + mov(20,8);mov(21,128); + emit({0xf4080000u|32u<<6|10,0xfa000060u,0xf4100000u|16u<<6|10,0xfa000020u}); + emit({0xf4240000u|12u<<6|16,0xfa000038u}); // offsets into t0 + emit({0x92800000u|44u<<16|182u<<8|130u}); // s_bfm_b64 s[44:45], 2, 54 + emit({0xbe800400u|46u<<16|255u,sampler_word2}); // s_mov_b64 with a 32-bit literal + mov(124,10);interp(4,0);interp(5,1); + emit({0x06000000u|6u<<17|4u<<9|12u,0x06000000u|7u<<17|5u<<9|13u}); + sample(32,color_mask,16);sample(12,1,24); + // Two VOP3 sources share a single trailing literal. The next dword is an opcode. + emit({0xd54b0000u|84u,255u|(255u<<9)|(128u<<18),0x3f800000u}); + mix(80,32,false);mix(80,33,true);mix(81,34,false);mix(47,12,false); + emit({0xf800040fu,0x80800000u|81u<<8|80u,0xf8001c13u,0x80808000u|47u,0xbf810000u}); + return {reinterpret_cast<const char*>(w.data()),w.size()*4}; +} + +std::string vertex_packet() { + const auto vop2=[](unsigned op,unsigned dst,unsigned a,unsigned b) { + return op<<25 | dst<<17 | b<<9 | a; + }; + const auto vop1=[](unsigned op,unsigned dst,unsigned src) { + return 0x7e000000u | dst<<17 | op<<9 | src; + }; + const auto args=[](unsigned a,unsigned b,unsigned c){ return a | b<<9 | c<<18; }; + const unsigned words[]{ + vop2(26,7,129,0), vop2(27,6,130,0), vop2(27,7,130,7), + vop1(5,7,263), vop1(5,6,262), vop1(1,10,128), vop1(1,11,242), + 0xd54b0008u,args(244,263,243), 0xd54b0009u,args(245,262,242), + 0xf80008cfu,0x0b0a0908u, 0xf8000203u,0x80800607u, 0xbf810000u + }; + return {reinterpret_cast<const char*>(words),sizeof(words)}; +} + +void write_fixture(const std::filesystem::path& folder) { + const auto write=[&](const char* name,const std::string& bytes) { + std::ofstream out(folder/name,std::ios::binary); + out.exceptions(std::ios::failbit|std::ios::badbit); + out.write(bytes.data(),bytes.size()); + }; + write("vertex.bin",vertex_packet()); + write("pixel.bin",packet()); + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + D3D12_ROOT_PARAMETER tables[2]{}; + for(unsigned i=0;i<2;++i) { + ranges[i]={D3D12_DESCRIPTOR_RANGE_TYPE_SRV,4,0,i,0}; + tables[i].ParameterType=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + tables[i].DescriptorTable={1,&ranges[i]}; + } + D3D12_ROOT_SIGNATURE_DESC desc{2,tables,0,nullptr,D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + ComPtr<ID3DBlob> root; + check(D3D12SerializeRootSignature(&desc,D3D_ROOT_SIGNATURE_VERSION_1,&root,nullptr),"fixture root"); + write("root.bin",{static_cast<const char*>(root->GetBufferPointer()),root->GetBufferSize()}); +} + +ComPtr<ID3D12DescriptorHeap> heap(ID3D12Device* dev,D3D12_DESCRIPTOR_HEAP_TYPE type,unsigned count,bool visible) { + D3D12_DESCRIPTOR_HEAP_DESC d{type,count,visible?D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE:D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + ComPtr<ID3D12DescriptorHeap> h;check(dev->CreateDescriptorHeap(&d,IID_PPV_ARGS(&h)),"descriptor heap");return h; +} +ComPtr<ID3D12RootSignature> signature(ID3D12Device* dev,bool graphics) { + D3D12_DESCRIPTOR_RANGE ranges[]{{D3D12_DESCRIPTOR_RANGE_TYPE_SRV,graphics?3u:2u,0,0,0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_UAV,1,0,0,2}}; + D3D12_ROOT_PARAMETER p[2]{};p[0].ParameterType=D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p[0].DescriptorTable={graphics?1u:2u,ranges}; + p[1].ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p[1].Constants.Num32BitValues=3; + p[1].ShaderVisibility=D3D12_SHADER_VISIBILITY_VERTEX; + D3D12_STATIC_SAMPLER_DESC s{};s.Filter=D3D12_FILTER_MIN_MAG_MIP_POINT; + s.AddressU=s.AddressV=s.AddressW=D3D12_TEXTURE_ADDRESS_MODE_CLAMP;s.MaxLOD=D3D12_FLOAT32_MAX; + s.MaxAnisotropy=1;s.ComparisonFunc=D3D12_COMPARISON_FUNC_ALWAYS; + D3D12_ROOT_SIGNATURE_DESC d{graphics?2u:1u,p,graphics?1u:0u,graphics?&s:nullptr}; + ComPtr<ID3DBlob> blob;check(D3D12SerializeRootSignature(&d,D3D_ROOT_SIGNATURE_VERSION_1,&blob,nullptr),"root serialization"); + ComPtr<ID3D12RootSignature> root; + check(dev->CreateRootSignature(0,blob->GetBufferPointer(),blob->GetBufferSize(),IID_PPV_ARGS(&root)),"root"); + return root; +} + +void run(ID3D12Device* dev,x2w::ShaderDxilCompiler& compiler,const wchar_t* cache, + const std::vector<unsigned char>& vs,const std::vector<unsigned char>& ps) { + auto graphics=signature(dev,true),compute=signature(dev,false); + auto cs=compiler.compile(R"( +Texture2D<float3> a:register(t0);Texture2D<float> b:register(t1);RWByteAddressBuffer dst:register(u0); +[numthreads(8,4,1)]void main(uint3 id:SV_DispatchThreadID){ +dst.Store4(16*(id.y*8+id.x),asuint(float4(a.Load(int3(id.xy,0)),b.Load(int3(id.xy,0)))));})",L"cs_6_0",cache); + D3D12_GRAPHICS_PIPELINE_STATE_DESC g{};g.pRootSignature=graphics.Get(); + g.VS={vs.data(),vs.size()};g.PS={ps.data(),ps.size()};g.SampleMask=UINT_MAX; + g.BlendState.RenderTarget[0].RenderTargetWriteMask=D3D12_COLOR_WRITE_ENABLE_ALL; + g.RasterizerState.FillMode=D3D12_FILL_MODE_SOLID;g.RasterizerState.CullMode=D3D12_CULL_MODE_NONE; + g.RasterizerState.DepthClipEnable=TRUE;g.PrimitiveTopologyType=D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + g.NumRenderTargets=2;g.RTVFormats[0]=formats[2];g.RTVFormats[1]=formats[3];g.SampleDesc.Count=1; + ComPtr<ID3D12PipelineState> gp,cp; + const auto start=std::chrono::steady_clock::now(); + auto hr=dev->CreateGraphicsPipelineState(&g,IID_PPV_ARGS(&gp)); + const auto pso_ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count(); + if(FAILED(hr)){ + ComPtr<ID3D12InfoQueue> queue; + if(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&queue)))){ + for(UINT64 i=0;i<queue->GetNumStoredMessages();++i){ + SIZE_T size=0;queue->GetMessage(i,nullptr,&size); + std::vector<unsigned char> bytes(size); + auto* msg=reinterpret_cast<D3D12_MESSAGE*>(bytes.data()); + if(SUCCEEDED(queue->GetMessage(i,msg,&size)))std::fprintf(stderr,"%s\n",msg->pDescription); + } + } + } + check(hr,"graphics PSO"); + D3D12_COMPUTE_PIPELINE_STATE_DESC c{};c.pRootSignature=compute.Get();c.CS={cs.dxil.data(),cs.dxil.size()}; + check(dev->CreateComputePipelineState(&c,IID_PPV_ARGS(&cp)),"compute PSO"); + auto rtvs=heap(dev,D3D12_DESCRIPTOR_HEAP_TYPE_RTV,4,false); + auto views=heap(dev,D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,6,true); + auto cpu=[&](ID3D12DescriptorHeap* h,unsigned i){auto v=h->GetCPUDescriptorHandleForHeapStart(); + v.ptr+=SIZE_T(i)*dev->GetDescriptorHandleIncrementSize(h->GetDesc().Type);return v;}; + auto gpu=[&](unsigned i){auto v=views->GetGPUDescriptorHandleForHeapStart(); + v.ptr+=UINT64(i)*dev->GetDescriptorHandleIncrementSize(views->GetDesc().Type);return v;}; + auto constants=make_buffer(dev,64,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ); + void* data{};check(constants->Map(0,nullptr,&data),"map offsets");std::memset(data,0,64);constants->Unmap(0,nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC buf{};buf.Format=DXGI_FORMAT_R32_TYPELESS;buf.ViewDimension=D3D12_SRV_DIMENSION_BUFFER; + buf.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;buf.Buffer.NumElements=16;buf.Buffer.Flags=D3D12_BUFFER_SRV_FLAG_RAW; + dev->CreateShaderResourceView(constants.Get(),&buf,cpu(views.Get(),0)); + std::array<ComPtr<ID3D12Resource>,4> surfaces; + for(unsigned i=0;i<4;++i){ + D3D12_RESOURCE_DESC d{};d.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;d.Width=i<2?2*width:width; + d.Height=i<2?2*height:height;d.DepthOrArraySize=d.MipLevels=d.SampleDesc.Count=1; + d.Format=formats[i];d.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + surfaces[i]=resource(dev,d,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_RENDER_TARGET); + dev->CreateRenderTargetView(surfaces[i].Get(),nullptr,cpu(rtvs.Get(),i)); + dev->CreateShaderResourceView(surfaces[i].Get(),nullptr,cpu(views.Get(),1+i)); + } + constexpr unsigned bytes=width*height*sizeof(Color); + auto dest=make_buffer(dev,bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + auto readback=make_buffer(dev,bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_UNORDERED_ACCESS_VIEW_DESC u{};u.Format=DXGI_FORMAT_R32_TYPELESS;u.ViewDimension=D3D12_UAV_DIMENSION_BUFFER; + u.Buffer.NumElements=bytes/4;u.Buffer.Flags=D3D12_BUFFER_UAV_FLAG_RAW; + dev->CreateUnorderedAccessView(dest.Get(),nullptr,&u,cpu(views.Get(),5)); + ComputeCommands cmd(dev,gp.Get(),D3D12_COMMAND_LIST_TYPE_DIRECT); + UINT64 frequency=0; + check(cmd.queue->GetTimestampFrequency(&frequency),"timestamp frequency"); + D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_TIMESTAMP,2,0}; + ComPtr<ID3D12QueryHeap> timestamps; + check(dev->CreateQueryHeap(&query_desc,IID_PPV_ARGS(×tamps)),"timestamp heap"); + auto timing=make_buffer(dev,2*sizeof(UINT64),D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + auto* list=cmd.list.Get();ID3D12DescriptorHeap* heaps[]{views.Get()};list->SetDescriptorHeaps(1,heaps); + D3D12_RECT right_half{width,0,2*width,2*height},bottom_half{0,height,2*width,2*height}; + list->ClearRenderTargetView(cpu(rtvs.Get(),0),left.data(),0,nullptr); + list->ClearRenderTargetView(cpu(rtvs.Get(),0),right.data(),1,&right_half); + list->ClearRenderTargetView(cpu(rtvs.Get(),1),first.data(),0,nullptr); + list->ClearRenderTargetView(cpu(rtvs.Get(),1),last.data(),1,&bottom_half); + for(unsigned i=0;i<2;++i){ + transition(list,surfaces[i].Get(),D3D12_RESOURCE_STATE_RENDER_TARGET,D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + list->ClearRenderTargetView(cpu(rtvs.Get(),2+i),sentinel.data(),0,nullptr); + } + const auto targets=cpu(rtvs.Get(),2);list->OMSetRenderTargets(2,&targets,TRUE,nullptr); + D3D12_VIEWPORT viewport{0,0,width,height,0,1};D3D12_RECT scissor{0,0,width-1,height}; + list->RSSetViewports(1,&viewport);list->RSSetScissorRects(1,&scissor);list->SetGraphicsRootSignature(graphics.Get()); + list->SetGraphicsRootDescriptorTable(0,gpu(0));list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->SetGraphicsRoot32BitConstant(1,0,0); + list->EndQuery(timestamps.Get(),D3D12_QUERY_TYPE_TIMESTAMP,0); + list->DrawInstanced(3,1,0,0); + list->EndQuery(timestamps.Get(),D3D12_QUERY_TYPE_TIMESTAMP,1); + list->ResolveQueryData(timestamps.Get(),D3D12_QUERY_TYPE_TIMESTAMP,0,2,timing.Get(),0); + for(unsigned i=2;i<4;++i)transition(list,surfaces[i].Get(),D3D12_RESOURCE_STATE_RENDER_TARGET,D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->SetPipelineState(cp.Get());list->SetComputeRootSignature(compute.Get());list->SetComputeRootDescriptorTable(0,gpu(3)); + list->Dispatch(1,1,1); + transition(list,dest.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyResource(readback.Get(),dest.Get());cmd.submit_and_wait(dev); + D3D12_RANGE range{0,bytes};check(readback->Map(0,&range,&data),"map compute result"); + for(unsigned y=0;y<height;++y)for(unsigned x=0;x<width;++x){ + Color expected=x<width/2?left:right;expected[3]=y<height/2?first[0]:last[0]; + if(x==width-1)expected=sentinel; + auto actual=static_cast<const Color*>(data)[y*width+x]; + if(actual!=expected)throw std::runtime_error("sampled MRT mismatch at "+std::to_string(x)+","+std::to_string(y)); + } + D3D12_RANGE empty{};readback->Unmap(0,&empty); + D3D12_RANGE time_range{0,2*sizeof(UINT64)}; + check(timing->Map(0,&time_range,&data),"read timestamps"); + const auto* ticks=static_cast<const UINT64*>(data); + if(!frequency || ticks[1]<ticks[0]) throw std::runtime_error("invalid GPU timestamps"); + std::printf("pso_ms=%.6f draw_gpu_us=%.6f\n",pso_ms,1e6*(ticks[1]-ticks[0])/frequency); + timing->Unmap(0,&empty); +} +} + +int wmain(int argc,wchar_t** argv) { + try { + if(argc==3 && std::wstring_view(argv[1])==L"--write-fixture") { + write_fixture(argv[2]); + return 0; + } + if(argc<4 || argc>6)return 2; + if(GetEnvironmentVariableW(L"X2W_TEST_DEBUG_LAYER",nullptr,0)){ + ComPtr<ID3D12Debug> debug; + check(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)),"debug layer");debug->EnableDebugLayer(); + } + bool unmatched=false; + auto device=create_device(std::wstring_view(argv[1])==L"warp",unmatched); + if(!device)return unmatched?1:77; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_0}; + if(FAILED(device->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL,&model,sizeof(model))) || + model.HighestShaderModel<D3D_SHADER_MODEL_6_0)return 77; + auto code=packet(); + auto shader=x2w::translate_gfx1013_sampled_pixel(code); + if(shader.bindings!="srv 0 buf table 0 96\nsrv 1 tex2d table 0 32\nsampler 0 0 12582912 0 0\nsrv 2 tex2d table 0 64\n") + throw std::runtime_error("unexpected bindings"); + const auto require_refusal=[](const std::string& bad,const char* diagnostic) { + try { x2w::translate_gfx1013_sampled_pixel(bad); } + catch(const std::runtime_error& e) { + if(std::strstr(e.what(),diagnostic))return; + throw; + } + throw std::runtime_error("accepted invalid sampled program"); + }; + require_refusal(code.substr(0,code.size()-4),"missing endpgm"); + require_refusal(packet(0),"invalid image_sample_lz"); + require_refusal(packet(3),"undefined float VGPR"); + require_refusal(packet(7,true,0x04004000),"secondary sampler bias"); + require_refusal(packet(7,true,0x04001000),"primary sampler bias"); + require_refusal(packet(7,false,0x04003f80),"primary sampler bias"); + x2w::ShaderDxilCompiler compiler(argv[2]); + auto object=[&](int index,const std::string& hlsl,const wchar_t* profile){ + if(argc<=index)return compiler.compile(hlsl,profile,argv[3]).dxil; + std::ifstream input(argv[index],std::ios::binary); + if(!input)throw std::runtime_error("external stage file missing"); + return std::vector<unsigned char>(std::istreambuf_iterator<char>(input),{}); + }; + auto pixel=object(4,shader.hlsl,L"ps_6_0"); + auto vertex=object(5,x2w::translate_gfx1013_vertex_id(vertex_packet()),L"vs_6_0"); + run(device.Get(),compiler,argv[3],vertex,pixel); + if(argc==4) { + const auto biased=x2w::translate_gfx1013_sampled_pixel(packet(7,true,0x04003f80)); + if(biased.hlsl.find("-128.0/256.0") == std::string::npos || + biased.bindings.find("sampler 0 0 12582912 67108864 0") == std::string::npos) + throw std::runtime_error("implicit sampler bias or normalized manifest differs"); + run(device.Get(),compiler,argv[3],vertex,compiler.compile(biased.hlsl,L"ps_6_0",argv[3]).dxil); + } + std::puts("112 covered components and 16 uncovered sentinel components matched after compute read"); + } catch(const std::exception& e){std::fprintf(stderr,"%s\n",e.what());return 1;} +} diff --git a/tests/native_sampled_replay_check.py b/tests/native_sampled_replay_check.py new file mode 100644 index 0000000000..47f06a5d7f --- /dev/null +++ b/tests/native_sampled_replay_check.py @@ -0,0 +1,50 @@ +"""Replay a source-built VS/PS pair, then damage each published identity in turn.""" +import hashlib +import json +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools/startup')) +from compile_sampled_pixel_request import build +from gfx2hlsl import fnv, pipeline_key + + +def main(writer, compiler, sdk): + with TemporaryDirectory() as folder: + work = Path(folder) + subprocess.run([writer, '--write-fixture', work], check=True) + # Device slot order can differ from shader stage order. + stages = [(work / name).read_bytes() for name in ('pixel.bin', 'vertex.bin', 'root.bin')] + base = pipeline_key(*stages) + for ext, data in zip(('.a', '.b', '.root'), stages): + (work / f'req_{base:016x}{ext}').write_bytes(data) + request = f'rtv1 {base} 26 54'.encode() + marker = work / f'req_{fnv(request):016x}.rtv' + marker.write_bytes(request) + args = (marker, work / 'bundles', compiler, sdk, work / 'cache') + output = build(*args) + assert build(*args) == output + meta = json.loads((output / 'replay.json').read_bytes()) + assert meta['pixel_bytes'] == len(stages[0]) and meta['vertex_bytes'] == len(stages[1]) + for name, digest in meta['sha256'].items(): + assert hashlib.sha256((output / name).read_bytes()).hexdigest() == digest + def refuse(message): + try: + build(*args) + except ValueError as exc: + assert message in str(exc), exc + else: + raise AssertionError('accepted damaged replay input') + next(output.glob('*.vs.cso')).write_bytes(b'damaged') + refuse('damaged replay bundle') + (work / f'req_{base:016x}.b').write_bytes(stages[0]) + refuse('key mismatch') + marker.write_bytes(f'rtv1 {base} 54 26'.encode()) + refuse('matching R11G11B10_FLOAT') + print('Matched two-stage cold/warm replay and three refusal controls passed') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_sampler_heap.cpp b/tests/native_sampler_heap.cpp new file mode 100644 index 0000000000..17c480717b --- /dev/null +++ b/tests/native_sampler_heap.cpp @@ -0,0 +1,479 @@ +// Native compute fixture: samplers read from the directly indexed sampler heap at a fixed index (issue #3076). +// +// usage: native_sampler_heap SDK CACHE REQ.c67 ADAPTER MODE +// REQ.c67 a source-built compute request (tests/native_sampler_heap_check.py) whose root has +// CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED and one SRV+UAV table. +// CACHE a fresh frontend cache directory: the fixture asserts a miss, then a hit on the same request. +// ADAPTER warp | hardware +// MODE sample one s_load_dwordx4 at 0x430 (entry 67), image_sample_lz at a coordinate outside [0, 1] +// two one s_load_dwordx8 at 0x430, two samples with entries 67 and 68 +// lod image_sample_l at LOD 1 of a two-mip texture; MaxLOD of the entry decides the mip +// mixed one literal static sampler and heap entry 67 in one program +// unbound bind() without a sampler heap throws +// The sampler heap has 128 entries, every one but the entries under test a decoy; each decoy is dispatched in place of +// the entry under test and must change the result. Entries are made with dynamic_sampler(), as the runtime does. +// Exit 0: every assertion held. 1: a result differs. 4: setup error. 77: capability skip. +#include "desktop_gpu.h" +#include "direct_compute_cache.h" +#include "native_compute_pipeline.h" +#include "startup_stubs/translated_sampler_bindings.h" +#include <dxgi1_4.h> +#include <algorithm> +#include <array> +#include <cmath> +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <map> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; +using x2w_startup::SamplerWords; + +namespace { +constexpr unsigned lanes = 32, heap_entries = 128; +constexpr float u_coordinate = 1.375f, v_coordinate = -0.375f; +constexpr std::uint32_t sentinel = 0x69696969u; +using Texel = std::array<float, 4>; + +// A 4x4 first mip and a 2x2 second mip with a distinct value in every texel and channel. +Texel texel(unsigned level, int x, int y) { + if (level == 0) return {10.f * x + 1, 10.f * y + 2, 100.f + x + 4 * y, 1000.f}; + return {500.f + x, 600.f + y, 700.f + x + 2 * y, 2000.f}; +} + +enum Address : unsigned { wrap = 0, mirror = 1, clamp = 2, border = 6 }; +// Title SQ_IMG_SAMP words in the encoding decode_sampler reads: clamp modes in word 0, MAX_LOD in word 1 (4.8 fixed +// point), filters and mip filter in word 2 (mip filter 1 = point), border colour type in word 3 (2 = opaque white). +SamplerWords title_sampler(Address address, bool bilinear, unsigned max_lod, bool white_border = false) { + const unsigned a = address, filter = bilinear ? 1u : 0u; + return {a | a << 3 | a << 6, (max_lod * 256u) << 12, filter << 20 | filter << 22 | 1u << 26, + white_border ? 2u << 30 : 0u}; +} + +// CPU model of a point-filtered sample at (u_coordinate, v_coordinate): the texel the address mode picks at the level the +// requested LOD gives after the sampler's MAX_LOD clamp. +Texel model(const SamplerWords &words, unsigned requested_lod) { + const unsigned level = (std::min)(requested_lod, (words[1] >> 12 & 0xfffu) / 256u); + const int n = 4 >> level; + int index[2]{int(std::floor(u_coordinate * n)), int(std::floor(v_coordinate * n))}; + bool outside = false; + for (int &i : index) { + switch (words[0] & 7u) { + case wrap: i = ((i % n) + n) % n; break; + case mirror: { + const int m = ((i % (2 * n)) + 2 * n) % (2 * n); + i = m < n ? m : 2 * n - 1 - m; + break; + } + case clamp: i = (std::max)(0, (std::min)(i, n - 1)); break; + default: outside |= i < 0 || i >= n; break; + } + } + if (outside) { + const float white = (words[3] >> 30) == 2 ? 1.f : 0.f; + return {white, white, white, white}; + } + return texel(level, index[0], index[1]); +} + +// One heap entry under test: the float4 of `result` must equal `expected` and a decoy in its place must change it. +struct Probe { + unsigned entry, result; + SamplerWords words; + unsigned lod; +}; +struct Mode { + std::vector<Probe> probes; + std::vector<SamplerWords> decoys; + unsigned results = 1, statics = 0; + std::map<unsigned, Texel> fixed; // results that do not come from the heap (the static sampler) + unsigned highest_entry = 0; +}; + +Mode make_mode(const std::wstring &name) { + Mode mode; + const auto wrap_point = title_sampler(wrap, false, 0), clamp_point = title_sampler(clamp, false, 0), + mirror_point = title_sampler(mirror, false, 0), border_clear = title_sampler(border, false, 0), + border_white = title_sampler(border, true, 0, true); + if (name == L"sample") { + mode.probes = {{67, 0, wrap_point, 0}}; + mode.decoys = {clamp_point, mirror_point, border_clear, border_white}; + } else if (name == L"two") { + mode.results = 2; + mode.probes = {{67, 0, wrap_point, 0}, {68, 1, clamp_point, 0}}; + mode.decoys = {mirror_point, border_clear, border_white}; + } else if (name == L"lod") { + mode.probes = {{67, 0, title_sampler(wrap, false, 1), 1}}; + // MaxLOD 0 with a bilinear and a point filter (the LOD clamp must matter), and a wrong address mode at MaxLOD 1. + mode.decoys = {title_sampler(wrap, true, 0), title_sampler(wrap, false, 0), title_sampler(clamp, false, 1)}; + } else if (name == L"mixed") { + mode.results = 2; + mode.statics = 1; + mode.probes = {{67, 1, wrap_point, 0}}; + mode.decoys = {clamp_point, mirror_point, border_clear}; + mode.fixed[0] = model(SamplerWords{0x92u, 0, 0, 0}, 0); // the literal static sampler: clamp, point + } + for (const auto &probe : mode.probes) mode.highest_entry = (std::max)(mode.highest_entry, probe.entry); + return mode; +} + +struct Gpu { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + HANDLE event = nullptr; + UINT64 fence_value = 0; + ComPtr<ID3D12DescriptorHeap> views; + ComPtr<ID3D12Resource> texture, output, readback, clear; + UINT view_increment = 0, sampler_increment = 0; + UINT output_bytes = 0; + + ~Gpu() { + if (event) CloseHandle(event); + } + + // Returns 77 when the adapter cannot run the fixture; 0 when ready. + int open(const std::wstring &adapter) { + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> chosen; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77; + if (adapter == L"warp") { + if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&chosen)))) return 77; + } else { + for (UINT i = 0; i < 8; ++i) { + ComPtr<IDXGIAdapter1> candidate; + if (factory->EnumAdapters1(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; + DXGI_ADAPTER_DESC1 desc{}; + candidate->GetDesc1(&desc); + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { + chosen = candidate; + std::printf("adapter=%ls\n", desc.Description); + break; + } + } + if (!chosen) { std::puts("no hardware adapter"); return 77; } + } + if (FAILED(D3D12CreateDevice(chosen.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { + std::puts("no device"); + return 77; + } + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof model)) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof options)) || + options.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) { + std::printf("adapter lacks shader model 6.6 or resource binding tier 3 (tier %d)\n", + int(options.ResourceBindingTier)); + return 77; + } + // The native module declares WaveSize=32 (the guest wave), so an adapter without 32-lane waves cannot run it. + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof waves)) || !waves.WaveOps || + waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::printf("adapter has no 32-lane waves (%u..%u)\n", waves.WaveLaneCountMin, waves.WaveLaneCountMax); + return 77; + } + // An older runtime refuses roots with the heap-indexing flags (E_INVALIDARG): a capability skip, not a failure. + { + D3D12_ROOT_SIGNATURE_DESC probe{0, nullptr, 0, nullptr, static_cast<D3D12_ROOT_SIGNATURE_FLAGS>(0xc00)}; + ComPtr<ID3DBlob> blob; + ComPtr<ID3D12RootSignature> root; + if (FAILED(D3D12SerializeRootSignature(&probe, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&root)))) { + std::puts("adapter refuses a root with the heap-indexing flags 0xc00"); + return 77; + } + } + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "queue"); + check(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + check(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + check(list->Close(), "close"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "fence"); + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) throw std::runtime_error("event"); + view_increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + sampler_increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + return 0; + } + + void wait() { + check(queue->Signal(fence.Get(), ++fence_value), "signal"); + check(fence->SetEventOnCompletion(fence_value, event), "fence event"); + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) throw std::runtime_error("fence wait timed out"); + } + template<class Body> void run(Body body) { + check(allocator->Reset(), "allocator reset"); + check(list->Reset(allocator.Get(), nullptr), "list reset"); + body(list.Get()); + check(list->Close(), "list close"); + ID3D12CommandList *lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + wait(); + check(device->GetDeviceRemovedReason(), "device removed"); + } + static D3D12_RESOURCE_BARRIER barrier(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; + } + + // t0 of the guest table: a 4x4 two-mip texture; u0: one float4 per result and lane, as a raw buffer. + void create_resources(unsigned results) { + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = 4; + td.DepthOrArraySize = 1; + td.MipLevels = 2; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.SampleDesc.Count = 1; + texture = resource(device.Get(), td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[2]{}; + UINT64 total = 0; + device->GetCopyableFootprints(&td, 0, 2, 0, footprints, nullptr, nullptr, &total); + auto upload = make_buffer(device.Get(), total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped = nullptr; + check(upload->Map(0, nullptr, &mapped), "texture upload map"); + for (unsigned level = 0; level < 2; ++level) + for (int y = 0; y < (4 >> level); ++y) + for (int x = 0; x < (4 >> level); ++x) + std::memcpy(static_cast<char *>(mapped) + footprints[level].Offset + + y * footprints[level].Footprint.RowPitch + x * sizeof(Texel), + texel(level, x, y).data(), sizeof(Texel)); + upload->Unmap(0, nullptr); + run([&](ID3D12GraphicsCommandList *l) { + for (UINT level = 0; level < 2; ++level) { + D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, + dst{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.PlacedFootprint = footprints[level]; + dst.SubresourceIndex = level; + l->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + auto to_read = barrier(texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + l->ResourceBarrier(1, &to_read); + }); + output_bytes = lanes * results * sizeof(Texel); + output = make_buffer(device.Get(), output_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + readback = make_buffer(device.Get(), output_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + clear = make_buffer(device.Get(), output_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(clear->Map(0, nullptr, &mapped), "sentinel map"); + for (unsigned i = 0; i < output_bytes / 4; ++i) static_cast<std::uint32_t *>(mapped)[i] = sentinel; + clear->Unmap(0, nullptr); + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)), "view heap"); + auto cpu = views->GetCPUDescriptorHandleForHeapStart(); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = td.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 2; + device->CreateShaderResourceView(texture.Get(), &srv, cpu); + cpu.ptr += view_increment; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R32_TYPELESS; + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = output_bytes / 4; + uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + device->CreateUnorderedAccessView(output.Get(), nullptr, &uav, cpu); + } + + // The sampler heap of the run: every entry a decoy (cycling through `decoys`), `entries` replaced. + ComPtr<ID3D12DescriptorHeap> sampler_heap(const std::vector<SamplerWords> &decoys, + const std::map<unsigned, SamplerWords> &entries) { + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, heap_entries, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)), "sampler heap"); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + for (unsigned i = 0; i < heap_entries; ++i) { + auto found = entries.find(i); + const auto desc = x2w_startup::dynamic_sampler(found != entries.end() ? found->second : decoys[i % decoys.size()]); + device->CreateSampler(&desc, cpu); + cpu.ptr += sampler_increment; + } + return heap; + } + + // Fills u0 with a sentinel, dispatches one group of 32 lanes, reads u0 back as floats. + std::vector<float> dispatch(const x2w::NativeComputePipeline &pipeline, ID3D12DescriptorHeap *samplers) { + run([&](ID3D12GraphicsCommandList *l) { + auto to_copy = barrier(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + l->ResourceBarrier(1, &to_copy); + l->CopyBufferRegion(output.Get(), 0, clear.Get(), 0, output_bytes); + auto to_uav = barrier(output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + l->ResourceBarrier(1, &to_uav); + pipeline.bind(l, views.Get(), views->GetGPUDescriptorHandleForHeapStart(), view_increment, nullptr, {}, + samplers); + l->Dispatch(1, 1, 1); + auto to_source = barrier(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + l->ResourceBarrier(1, &to_source); + l->CopyBufferRegion(readback.Get(), 0, output.Get(), 0, output_bytes); + auto back = barrier(output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + l->ResourceBarrier(1, &back); + }); + std::vector<float> out(output_bytes / 4); + void *mapped = nullptr; + D3D12_RANGE range{0, output_bytes}; + check(readback->Map(0, &range, &mapped), "readback map"); + std::memcpy(out.data(), mapped, output_bytes); + D3D12_RANGE written{}; + readback->Unmap(0, &written); + return out; + } +}; + +bool equal(const Texel &a, const Texel &b) { return std::memcmp(a.data(), b.data(), sizeof a) == 0; } +const char *texel_text(const Texel &t, char (&buffer)[96]) { + std::snprintf(buffer, sizeof buffer, "(%g, %g, %g, %g)", t[0], t[1], t[2], t[3]); + return buffer; +} + +// 0: every lane holds `expected` in float4 `result`. Otherwise the first mismatch is printed. +bool lanes_hold(const std::vector<float> &values, unsigned results, unsigned result, const Texel &expected, + const char *what) { + for (unsigned lane = 0; lane < lanes; ++lane) { + Texel got; + std::memcpy(got.data(), &values[(lane * results + result) * 4], sizeof got); + if (!equal(got, expected)) { + char a[96], b[96]; + std::printf("FAIL: %s: lane %u result %u is %s, expected %s\n", what, lane, result, texel_text(got, a), + texel_text(expected, b)); + return false; + } + } + return true; +} +// Every lane must hold a result other than `expected`, and not the untouched output sentinel (the dispatch ran). +bool lanes_differ(const std::vector<float> &values, unsigned results, unsigned result, const Texel &expected) { + for (unsigned lane = 0; lane < lanes; ++lane) { + Texel got; + std::memcpy(got.data(), &values[(lane * results + result) * 4], sizeof got); + std::uint32_t bits[4]; + std::memcpy(bits, got.data(), sizeof bits); + if (equal(got, expected) || (bits[0] == sentinel && bits[1] == sentinel && bits[2] == sentinel && + bits[3] == sentinel)) + return false; + } + return true; +} + +int run_mode(const std::wstring &sdk, const std::wstring &cache, const std::filesystem::path &marker, Gpu &gpu, + const std::wstring &name) { + const bool unbound = name == L"unbound"; + const Mode mode = make_mode(unbound ? L"sample" : name); + if (mode.probes.empty()) { + std::puts("unknown mode"); + return 2; + } + // Frontend cache: a miss on the fresh directory, then a hit with the same binding record. + bool first_hit = true, second_hit = false; + const auto first = x2w::prepare_direct_compute(marker, 0, false, cache, first_hit); + const auto second = x2w::prepare_direct_compute(marker, 0, false, cache, second_hit); + if (first_hit || !second_hit) { + std::printf("FAIL: frontend cache first call hit=%d second call hit=%d\n", int(first_hit), int(second_hit)); + return 1; + } + std::puts("pass: prepare_direct_compute misses on a fresh cache and hits on the second call"); + for (const auto *program : {&first, &second}) { + unsigned count = 0; + for (const auto &b : program->bindings) { + if (b.kind != x2w::ComputeViewKind::heap_sampler) continue; + ++count; + if (b.root_parameter != x2w::compute_sampler_heap || b.byte_offset != 0 || b.shader_register != 0 || + b.required_bytes != 16 * (mode.highest_entry + 1) || b.array_count != 1 || b.array_position != 0 || + b.image_dimension != 1 || b.scalar_table != x2w::ComputeViewBinding::ScalarTable::unknown) { + std::printf("FAIL: heap_sampler binding root=%u offset=%u register=%u bytes=%u\n", b.root_parameter, + b.byte_offset, b.shader_register, b.required_bytes); + return 1; + } + } + if (count != 1 || program->samplers.size() != mode.statics) { + std::printf("FAIL: %u heap_sampler bindings, %zu static samplers\n", count, program->samplers.size()); + return 1; + } + } + std::printf("pass: one heap_sampler binding {compute_sampler_heap, 0, 0, %u bytes} in the computed and the cached " + "program, %u static samplers\n", 16 * (mode.highest_entry + 1), mode.statics); + + x2w::ShaderDxilCompiler compiler(sdk); + auto pipeline = x2w::create_native_compute_pipeline(gpu.device.Get(), compiler, marker, 0, cache, true); + if (!pipeline.sampler_heap_indexed || pipeline.heap_indexed || pipeline.srv_count != 1 || pipeline.uav_count != 1 || + !pipeline.frontend_cache_hit) { + std::printf("FAIL: pipeline shape sampler_heap_indexed=%d heap_indexed=%d srv=%u uav=%u frontend_hit=%d\n", + int(pipeline.sampler_heap_indexed), int(pipeline.heap_indexed), pipeline.srv_count, + pipeline.uav_count, int(pipeline.frontend_cache_hit)); + return 1; + } + std::puts("pass: pipeline has sampler_heap_indexed, no resource-heap indexing, one SRV and one UAV"); + gpu.create_resources(mode.results); + + if (unbound) { + // bind() without a sampler heap must throw before anything is recorded for it. + bool threw = false; + try { + gpu.run([&](ID3D12GraphicsCommandList *l) { + pipeline.bind(l, gpu.views.Get(), gpu.views->GetGPUDescriptorHandleForHeapStart(), gpu.view_increment); + }); + } catch (const std::runtime_error &error) { + threw = std::string(error.what()) == "a sampler heap is needed"; + std::printf("bind without a sampler heap: %s\n", error.what()); + } + if (!threw) { + std::puts("FAIL: bind without a sampler heap did not throw"); + return 1; + } + std::puts("pass: bind without a sampler heap throws \"a sampler heap is needed\""); + return 0; + } + + std::map<unsigned, SamplerWords> entries; + for (const auto &probe : mode.probes) entries[probe.entry] = probe.words; + const auto values = gpu.dispatch(pipeline, gpu.sampler_heap(mode.decoys, entries).Get()); + for (const auto &[result, expected] : mode.fixed) + if (!lanes_hold(values, mode.results, result, expected, "static sampler")) return 1; + if (!mode.fixed.empty()) std::puts("pass: the literal static sampler result matches the CPU model"); + for (const auto &probe : mode.probes) { + const Texel expected = model(probe.words, probe.lod); + if (!lanes_hold(values, mode.results, probe.result, expected, "heap entry")) return 1; + std::printf("pass: entry %u (result %u) equals the CPU model in all %u lanes\n", probe.entry, probe.result, lanes); + // The same program with a decoy in place of the entry under test must give another result. + for (size_t d = 0; d < mode.decoys.size(); ++d) { + auto swapped = entries; + swapped[probe.entry] = mode.decoys[d]; + const auto other = gpu.dispatch(pipeline, gpu.sampler_heap(mode.decoys, swapped).Get()); + if (!lanes_differ(other, mode.results, probe.result, expected)) { + std::printf("FAIL: decoy %zu in place of entry %u leaves result %u unchanged\n", d, probe.entry, + probe.result); + return 1; + } + std::printf("pass: decoy %zu in place of entry %u changes result %u\n", d, probe.entry, probe.result); + } + } + return 0; +} +} // namespace + +int wmain(int argc, wchar_t **argv) { + if (argc != 6) { + std::fputs("usage: native_sampler_heap SDK CACHE REQ.c67 ADAPTER sample|two|lod|mixed|unbound\n", stderr); + return 2; + } + Gpu gpu; + try { + if (int skip = gpu.open(argv[4])) return skip; + return run_mode(argv[1], argv[2], argv[3], gpu, argv[5]); + } catch (const std::exception &error) { + std::printf("setup error: %s\n", error.what()); + return 4; + } +} diff --git a/tests/native_sampler_heap_check.py b/tests/native_sampler_heap_check.py new file mode 100644 index 0000000000..2d20e2aa8f --- /dev/null +++ b/tests/native_sampler_heap_check.py @@ -0,0 +1,365 @@ +"""Samplers read from the directly indexed sampler heap at a fixed index, translated natively (issue #3076). + +usage: native_sampler_heap_check.py FIXTURE COMPILE_DXIL SDK ADAPTER + +Compute requests are written from source: user SGPRs s4 (the SRV+UAV descriptor table), s5 (the resource heap) and s6 (the +sampler heap) under RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED). The programs copy s6 +into an even SGPR pair with a constant-zero high word, load one sampler (s_load_dwordx4) or two (s_load_dwordx8) at a +16-byte aligned immediate offset (0x430 is entry 67) and sample a two-mip texture at a coordinate outside [0, 1]: + + SAMPLE image_sample_lz with entry 67 TWO entries 67 and 68 from one s_load_dwordx8 + LOD image_sample_l at LOD 1, MaxLOD decides MIXED one literal static sampler and entry 67 + +The `native_sampler_heap` fixture runs them with a sampler heap of decoys, compares every lane with a CPU model, puts each +decoy in place of the entry under test (the result must change), checks the frontend cache round trip and the binding +record, and shows that bind() without a sampler heap throws. This script also compiles the refusal shapes and checks each +refusal text (and that no .cso is written), each with a control that compiles. Exit 77 when the fixture reports a +capability skip (WARP has no 32-lane waves). + +Instruction words were assembled once with LLVM 15 (clang -cc1as -triple amdgcn-amd-amdhsa -target-cpu gfx1013 +-filetype asm -show-encoding); the comment on each line is the assembler source. The test needs no LLVM. +""" +import pathlib +import struct +import subprocess +import sys +import tempfile + +# Same helper as native_compute_raw_root_check.py: writes req_<key>.c67 and its parts. +from native_compute_clear_check import write_request + +ROOT_RW = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" +ROOT_VIEWS_ONLY = "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t0), UAV(u0))" + +REFUSALS = { + "buffer": "scalar buffer load from the sampler heap is not translated", + "sgpr": "sampler heap load with an SGPR offset (a GPU-selected sampler) is not translated", + "shape": "sampler heap load must read one or two samplers", + "align": "sampler heap offset is not a multiple of 16", + "bound": "sampler heap index beyond 2046 (2047 is the runtime fallback entry)", + "hlsl": "sampler heap reads need the direct DXIL path", + "resource": "a sampler heap descriptor is read as a resource", + "gather": "gather through the sampler heap is not translated", + "compare": "comparison sampler from the sampler heap is not translated", + "implicit": "sampler from the sampler heap needs image_sample_l or image_sample_lz", + "mixed": "nonconstant sampler", + "table": "direct descriptor address outside bound table", +} + +# --- instruction blocks ------------------------------------------------------------------------------------------- +BASES = [ + 0xbe880304, # s_mov_b32 s8, s4 (s[8:9]: the table pointer, high word constant 0) + 0xbe890380, # s_mov_b32 s9, 0 + 0xbe8a0306, # s_mov_b32 s10, s6 (s[10:11]: the sampler heap base, high word constant 0) + 0xbe8b0380, # s_mov_b32 s11, 0 +] +TABLE_LOADS = [ + 0xf40c0404, 0xfa000000, # s_load_dwordx8 s[16:23], s[8:9], 0x0 (t0: the texture) + 0xf4080604, 0xfa000020, # s_load_dwordx4 s[24:27], s[8:9], 0x20 (u0: the output buffer) +] +SAMPLER_X4 = [ + 0xf4080305, 0xfa000430, # s_load_dwordx4 s[12:15], s[10:11], 0x430 (entry 67) +] +COORDINATES = [ + 0x7e0202ff, 0x3fb00000, # v_mov_b32_e32 v1, 0x3fb00000 (u = 1.375) + 0x7e0402ff, 0xbec00000, # v_mov_b32_e32 v2, 0xbec00000 (v = -0.375) +] +LOD_ONE = [ + 0x7e0602f2, # v_mov_b32_e32 v3, 1.0 (LOD 1) +] +WAIT_SCALAR = [ + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) +] +WAIT_VECTOR = [ + 0xbf8c3f70, # s_waitcnt vmcnt(0) +] +END = [ + 0xbf810000, # s_endpgm +] +LITERAL_STATIC = [ + 0xbea803ff, 0x00000092, # s_mov_b32 s40, 0x92 (static sampler: clamp x, y and z, point) + 0xbea90380, # s_mov_b32 s41, 0 + 0xbeaa0380, # s_mov_b32 s42, 0 + 0xbeab0380, # s_mov_b32 s43, 0 +] +STORE_ONE = [ + 0x34100084, # v_lshlrev_b32_e32 v8, 4, v0 + 0xe0781000, 0x80060408, # buffer_store_dwordx4 v[4:7], v8, s[24:27], 0 offen +] +STORE_TWO = [ + 0x34100085, # v_lshlrev_b32_e32 v8, 5, v0 + 0xe0781000, 0x80060408, # buffer_store_dwordx4 v[4:7], v8, s[24:27], 0 offen + 0xe0781010, 0x80060c08, # buffer_store_dwordx4 v[12:15], v8, s[24:27], 0 offen offset:16 +] +SAMPLE_LZ_HEAP = [ + 0xf09c0f08, 0x00640401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D +] +# Operands for the refusal and control shapes: four coordinates after u and v, a sampler built from literals. +FILL_V3_V6 = [ + 0x7e0602f2, # v_mov_b32_e32 v3, 1.0 + 0x7e0802f2, # v_mov_b32_e32 v4, 1.0 + 0x7e0a02f2, # v_mov_b32_e32 v5, 1.0 + 0x7e0c02f2, # v_mov_b32_e32 v6, 1.0 +] +SAMPLER_LITERAL = [ + 0xbe8c03ff, 0x08001012, # s_mov_b32 s12, 0x8001012 (comparison_program of native_direct_container_check.py) + 0xbe8d03ff, 0x00fff000, # s_mov_b32 s13, 0xfff000 + 0xbe8e03ff, 0x04000000, # s_mov_b32 s14, 0x4000000 + 0xbe8f0380, # s_mov_b32 s15, 0 +] + + +def operation(op_words): + return [*BASES, *TABLE_LOADS, "SAMPLER", *COORDINATES, *FILL_V3_V6, *WAIT_SCALAR, *op_words, *END] + + +OPERATIONS = { + "gather4_lz": [0xf11c0108, 0x00640801], # image_gather4_lz v[8:11], v[1:2], s[16:23], s[12:15] dmask:0x1 dim:SQ_RSRC_IMG_2D + "gather4_c_lz": [0xf13c0108, 0x00640801], # image_gather4_c_lz v[8:11], v[1:3], s[16:23], s[12:15] dmask:0x1 dim:SQ_RSRC_IMG_2D + "sample_c_lz": [0xf0bc0108, 0x00640801], # image_sample_c_lz v8, v[1:3], s[16:23], s[12:15] dmask:0x1 dim:SQ_RSRC_IMG_2D + "sample_d": [0xf0880f08, 0x00640801], # image_sample_d v[8:11], v[1:6], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D +} + + +def with_sampler(program, sampler): + out = [] + for word in program: + out.extend(sampler if word == "SAMPLER" else [word]) + return out + + +PROGRAMS = { + "sample": [*BASES, *TABLE_LOADS, *SAMPLER_X4, *COORDINATES, *WAIT_SCALAR, *SAMPLE_LZ_HEAP, *WAIT_VECTOR, *STORE_ONE, *END], + "two": [ + *BASES, *TABLE_LOADS, + 0xf40c0805, 0xfa000430, # s_load_dwordx8 s[32:39], s[10:11], 0x430 (entries 67 and 68) + *COORDINATES, *WAIT_SCALAR, + 0xf09c0f08, 0x01040401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[32:35] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf09c0f08, 0x01240c01, # image_sample_lz v[12:15], v[1:2], s[16:23], s[36:39] dmask:0xf dim:SQ_RSRC_IMG_2D + *WAIT_VECTOR, *STORE_TWO, *END], + "lod": [ + *BASES, *TABLE_LOADS, *SAMPLER_X4, *COORDINATES, *LOD_ONE, *WAIT_SCALAR, + 0xf0900f08, 0x00640401, # image_sample_l v[4:7], v[1:3], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D + *WAIT_VECTOR, *STORE_ONE, *END], + "mixed": [ + *BASES, *TABLE_LOADS, *SAMPLER_X4, *LITERAL_STATIC, *COORDINATES, *WAIT_SCALAR, + 0xf09c0f08, 0x01440401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xf09c0f08, 0x00640c01, # image_sample_lz v[12:15], v[1:2], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D + *WAIT_VECTOR, *STORE_TWO, *END], + # Refusal shapes. Each one stops at the instruction under test. + "dx2": [*BASES, + 0xf4040305, 0xfa000430, # s_load_dwordx2 s[12:13], s[10:11], 0x430 + *END], + "dx16": [*BASES, + 0xf4100405, 0xfa000400, # s_load_dwordx16 s[16:31], s[10:11], 0x400 + *END], + "off438": [*BASES, + 0xf4080305, 0xfa000438, # s_load_dwordx4 s[12:15], s[10:11], 0x438 + *END], + "idx2047": [*BASES, + 0xf4080305, 0xfa007ff0, # s_load_dwordx4 s[12:15], s[10:11], 0x7ff0 + *END], + "bound2": [*BASES, + 0xf40c0405, 0xfa007fe0, # s_load_dwordx8 s[16:23], s[10:11], 0x7fe0 (entries 2046 and 2047) + *END], + "sgpr_offset": [*BASES, + 0xbe9403ff, 0x00000430, # s_mov_b32 s20, 0x430 + 0xf4080305, 0x28000000, # s_load_dwordx4 s[12:15], s[10:11], s20 + *END], + "bufload": [ + 0xbe880306, # s_mov_b32 s8, s6 + 0xbe890380, # s_mov_b32 s9, 0 + 0xf4200304, 0xfa000000, # s_buffer_load_dword s12, s[8:11], 0x0 + *END], + "asres": [ + *BASES, + 0xf40c0405, 0xfa000400, # s_load_dwordx8 s[16:23], s[10:11], 0x400 (a sampler heap entry as the image descriptor) + *LITERAL_STATIC, *COORDINATES, *WAIT_SCALAR, + 0xf09c0f08, 0x01440401, # image_sample_lz v[4:7], v[1:2], s[16:23], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D + *END], + "mixed_words": [ + *BASES, *TABLE_LOADS, *SAMPLER_X4, + 0xbe8c03ff, 0x00000092, # s_mov_b32 s12, 0x92 (word 0 of the sampler becomes a literal; words 1 to 3 stay heap words) + *COORDINATES, *WAIT_SCALAR, *SAMPLE_LZ_HEAP, *END], + "join": [ + *BASES, + 0xbe940381, # s_mov_b32 s20, 1 + 0xbf068014, # s_cmp_eq_u32 s20, 0 + 0xbf850001, # s_cbranch_scc1 1 (skips the next instruction) + 0xbe8a0380, # s_mov_b32 s10, 0 (one path replaces the copied heap base) + 0xf4080305, 0xfa000430, # s_load_dwordx4 s[12:15], s[10:11], 0x430 + *END], + # Controls: the same shapes with the one change that makes them valid. + "join_control": [ + *BASES, + 0xbe940381, # s_mov_b32 s20, 1 + 0xbf068014, # s_cmp_eq_u32 s20, 0 + 0xbf850001, # s_cbranch_scc1 1 + 0xbe950380, # s_mov_b32 s21, 0 (the skipped instruction leaves the heap base alone) + 0xf4080305, 0xfa000430, # s_load_dwordx4 s[12:15], s[10:11], 0x430 + *END], + "edge2046": [*BASES, + 0xf4080305, 0xfa007fe0, # s_load_dwordx4 s[12:15], s[10:11], 0x7fe0 (entry 2046, the last one) + *END], + "x8_edge": [*BASES, + 0xf40c0405, 0xfa007fd0, # s_load_dwordx8 s[16:23], s[10:11], 0x7fd0 (entries 2045 and 2046) + *END], +} +for op_name, op_words in OPERATIONS.items(): + PROGRAMS["heap_" + op_name] = with_sampler(operation(op_words), SAMPLER_X4) + PROGRAMS["literal_" + op_name] = with_sampler(operation(op_words), SAMPLER_LITERAL) + + +def main(): + fixture, compile_dxil, sdk, adapter = sys.argv[1:5] + ok_lines = 0 + + def require(condition, message): + nonlocal ok_lines + if not condition: + print("FAIL: " + message) + sys.exit(1) + ok_lines += 1 + print("ok: " + message) + + def run(command, expect_skip=False): + result = subprocess.run([str(part) for part in command], capture_output=True, timeout=150) + out = result.stdout.decode("utf-8", "replace") + err = result.stderr.decode("utf-8", "replace") + print("$ " + " ".join(pathlib.Path(str(c)).name if i == 0 else str(c) for i, c in enumerate(command))) + for text in (out, err): + for line in text.strip().splitlines(): + print(" " + line) + print(f" -> exit {result.returncode}") + if result.returncode == 77 and expect_skip: + print("fixture capability skip (77)") + sys.exit(77) + return result.returncode, out, err + + with tempfile.TemporaryDirectory(prefix="x2w_sampler_heap_") as scratch: + base = pathlib.Path(scratch) + # Sampler heap content, texture and expectations are in the fixture; the requests are written here. + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1, 0, 7 << 1) # group 32x1x1, 7 user SGPRs + roots = {} + + def root(text): + if text not in roots: + source = base / f"root{len(roots)}.hlsl" + source.write_text(f'#define RS "{text}"') + binary = base / f"root{len(roots)}.bin" + subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", binary, source], + check=True, capture_output=True) + roots[text] = binary.read_bytes() + return roots[text] + + counter = 0 + + def request(name, root_text=ROOT_RW): + nonlocal counter + counter += 1 + folder = base / f"req_{counter}_{name}" + folder.mkdir() + return write_request(folder, PROGRAMS[name], root(root_text), sa) + + def compile_request(marker, profile="gfx1013-direct-cs@0", cache=None): + output = marker.with_suffix(".cso") + code, out, err = run([compile_dxil, sdk, cache or marker.parent / "cache", profile, marker, output]) + return code, out, err, output + + def refused(name, key, root_text=ROOT_RW, profile="gfx1013-direct-cs@0"): + marker = request(name, root_text) + code, out, err, output = compile_request(marker, profile) + require(code != 0 and REFUSALS[key] in err and not output.exists(), + f"{name}: refused with \"{REFUSALS[key]}\" and no .cso") + + def accepted(name, message): + marker = request(name) + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists() and "sampler_heap span" not in out, message) + return out + + # 1. Fixture runs. A fresh frontend cache per run: the fixture asserts a miss and then a hit. + expected_lines = { + "sample": ["entry 67 (result 0) equals the CPU model in all 32 lanes", + *[f"decoy {n} in place of entry 67 changes result 0" for n in range(4)], + "{compute_sampler_heap, 0, 0, 1088 bytes}"], + "two": ["entry 67 (result 0) equals the CPU model", "entry 68 (result 1) equals the CPU model", + *[f"decoy {n} in place of entry {e} changes result {e - 67}" for e in (67, 68) for n in range(3)], + "{compute_sampler_heap, 0, 0, 1104 bytes}"], + "lod": ["entry 67 (result 0) equals the CPU model", + *[f"decoy {n} in place of entry 67 changes result 0" for n in range(3)], + "{compute_sampler_heap, 0, 0, 1088 bytes}"], + "mixed": ["the literal static sampler result matches the CPU model", "entry 67 (result 1) equals the CPU model", + *[f"decoy {n} in place of entry 67 changes result 1" for n in range(3)], + "1088 bytes}"], + } + for mode, lines in expected_lines.items(): + marker = request(mode) + cache = base / f"cache_{mode}" + cache.mkdir() + code, out, err = run([fixture, sdk, cache, marker, adapter, mode], expect_skip=True) + require(code == 0, f"fixture mode {mode} exits 0") + for line in lines: + require(line in out, f"{mode}: {line}") + require("pass: prepare_direct_compute misses on a fresh cache and hits on the second call" in out, + f"{mode}: frontend cache round trip (miss, then hit)") + require("pass: pipeline has sampler_heap_indexed" in out, f"{mode}: pipeline asks for the sampler heap flag only") + code, out, err = run([fixture, sdk, base / "cache_unbound", request("sample"), adapter, "unbound"], expect_skip=True) + require(code == 0 and "bind without a sampler heap throws" in out, "bind without a sampler heap throws") + + # 2. compile_dxil: the module reads the sampler from the heap and the binding record is reported. + marker = request("sample") + code, out, err, output = compile_request(marker) + require(code == 0 and output.exists(), "compile_dxil compiles SAMPLE") + require("sampler_heap span=1088" in out, "compile_dxil reports sampler_heap span=1088 for entry 67") + code2, out2, err2, _ = compile_request(marker) + require(code2 == 0 and "frontend_cache_hit=1" in out2, "the second compile hits the frontend cache") + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, text=True).stdout + require("@dx.op.createHandleFromHeap(i32 218, i32 67, i1 true, i1 false)" in listing, + "the module creates the sampler with createHandleFromHeap(218, index 67, sampler heap, uniform)") + require(listing.count("@dx.op.createHandleFromBinding(") >= 2, + "the texture and the output buffer stay table bindings (createHandleFromBinding)") + marker = request("two") + code, out, err, output = compile_request(marker) + listing = subprocess.run([pathlib.Path(sdk) / "dxc.exe", "-dumpbin", output], capture_output=True, text=True).stdout + require(code == 0 and "sampler_heap span=1104" in out and + "createHandleFromHeap(i32 218, i32 67, i1 true, i1 false)" in listing and + "createHandleFromHeap(i32 218, i32 68, i1 true, i1 false)" in listing, + "TWO: one s_load_dwordx8 gives sampler heap handles 67 and 68") + marker = request("sample") + requests = marker.parent + out_dir = base / "requests_out" + code, out, err = run([compile_dxil, sdk, base / "cache_requests", "gfx1013-direct-cs@0", "--requests", requests, out_dir]) + stem = marker.stem[len("req_"):] + require(code == 0 and (out_dir / (stem + ".cs.cso")).exists() and not (out_dir / (stem + ".txt")).exists(), + "--requests publishes .cs.cso and no runtime manifest (.txt) for a sampler heap program") + + # 3. Refusals, each with its text, and controls that compile. + refused("off438", "align") + refused("idx2047", "bound") + refused("bound2", "bound") + refused("dx2", "shape") + refused("dx16", "shape") + refused("sgpr_offset", "sgpr") + refused("bufload", "buffer") + refused("asres", "resource") + refused("mixed_words", "mixed") + refused("join", "table") + refused("heap_gather4_lz", "gather") + refused("heap_gather4_c_lz", "gather") + refused("heap_sample_c_lz", "compare") + refused("heap_sample_d", "implicit") + accepted("edge2046", "control: entry 2046 (offset 0x7fe0) compiles") + accepted("x8_edge", "control: s_load_dwordx8 at entries 2045 and 2046 compiles") + accepted("join_control", "control: the same branch without the overwrite compiles") + for op_name in OPERATIONS: + accepted("literal_" + op_name, f"control: {op_name} with a literal sampler compiles") + # The HLSL path has no sampler heap handle; a root with only the views flag has no sampler heap base. + refused("sample", "hlsl", profile="gfx1013-compute-wave32@0") + refused("sample", "table", root_text=ROOT_VIEWS_ONLY) + + print(f"{ok_lines} assertions held") + + +if __name__ == "__main__": + main() diff --git a/tests/native_sat_pk_u8_i16_check.py b/tests/native_sat_pk_u8_i16_check.py new file mode 100644 index 0000000000..b7ed790406 --- /dev/null +++ b/tests/native_sat_pk_u8_i16_check.py @@ -0,0 +1,151 @@ +"""Direct compute VOP1/VOP3A v_sat_pk_u8_i16 (pack two signed 16-bit halves saturated to u8, zero high half).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import sop1 + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 +INACTIVE = 0x13579BDF + +# 16 input words covering negative (-32768, -1), boundary (0, 1, 255, 256), and large positive (+32767) in both halves. +CASES = ( + 0x00000000, + 0x00FF0001, + 0x010000FF, + 0x7FFF8000, + 0x80007FFF, + 0xFFFF0000, + 0x0000FFFF, + 0xFF000080, + 0x0080FF00, + 0x00FE0002, + 0x0101FFFE, + 0x12345678, + 0x80017FFE, + 0x007F0080, + 0x00FF0100, + 0xDEADBEEF, +) + + +def vop1(op, vdst, src0): + return 0x7E000000 | ((vdst & 0xFF) << 17) | ((op & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3a(op, vdst, src0, src1=0, src2=0, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0): + w0 = 0xD4000000 | ((op & 0x3FF) << 16) | (clamp << 15) | ((op_sel & 0xF) << 11) | ((abs_bits & 7) << 8) | (vdst & 0xFF) + w1 = ((neg & 7) << 29) | ((omod & 3) << 27) | ((src2 & 0x1FF) << 18) | ((src1 & 0x1FF) << 9) | (src0 & 0x1FF) + return [w0, w1] + + +def program(*, sparse=False, first_modifier=0, second_modifier=0): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for case, val in enumerate(CASES): + code += [vop2(0x1D, 1, 255, 0), val] # v_xor_b32 v1, val, v0 + for wide in (False, True): + # Preload v4 with 0xABCD0000 so we prove D[31:16] is zeroed (or preserved when inactive). + code += [0x7E0802FF, INACTIVE if sparse else 0xABCD0000] + if sparse: + code += [sop1(3, 126, 255), 0x55555555] + if wide: + w0, w1 = vop3a(0x1E2, 4, 257) + if (first_modifier or second_modifier) and case == 0: + w0 ^= first_modifier + w1 ^= second_modifier + code += [w0, w1] + else: + code += [vop1(0x62, 4, 257)] + if sparse: + code += [sop1(3, 126, 193)] # restore EXEC before storing + offset = 4 * (case * 2 + int(wide)) + code += [0xE0701000 | offset, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen + return code + [0xBF810000] + + +def sext16(v): + v &= 0xFFFF + return v - 0x10000 if v >= 0x8000 else v + + +def sat_pk_u8_i16(word): + lo = max(0, min(255, sext16(word))) + hi = max(0, min(255, sext16(word >> 16))) + return lo | (hi << 8) + + +def reference(sparse=False): + words = [SENTINEL] * 8 + for lane in range(64): + for val in CASES: + for _wide in (False, True): + words.append(INACTIVE if sparse and lane % 2 else sat_pk_u8_i16(val ^ (lane % 32))) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + # Valid encoding + 6 refused VOP3A modifier/reserved-bit encodings: + # clamp (w0[15]), op_sel (w0[11]), abs (w0[8]), neg (w1[29]), nonzero src1 (w1[9]), nonzero src2 (w1[18]). + refusal_cases = ( + (0, 0, ''), + (1 << 15, 0, 'modifier'), + (1 << 11, 0, 'op_sel'), + (1 << 8, 0, 'modifier'), + (0, 1 << 29, 'modifier'), + (0, 1 << 9, 'unused src1/src2'), + (0, 1 << 18, 'unused src1/src2'), + ) + for first, second, needle in refusal_cases: + marker = request(work, root, program(first_modifier=first, second_modifier=second)) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + if first or second: + assert result.returncode and needle in result.stderr, (first, second, result.stderr) + assert not output.exists() + else: + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'icmp slt i32 ' in dump and 'icmp sgt i32 ' in dump and '255' in dump, dump + assert reference() != reference(sparse=True) + print('v_sat_pk_u8_i16 DXIL verified; six VOP3A modifier/unused-src encodings refused; EXEC control differs') + return 0 + + +def hardware(replay, sdk, work, root): + for sparse in (False, True): + marker = request(work, root, program(sparse=sparse)) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference(sparse) + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'sparse={sparse} word {mismatch}: got {actual[mismatch]:08x}, ' + f'expected {expected[mismatch]:08x}') + print(f'sparse={sparse}: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_sat_pk_u8_i16_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_saveexec_wrexec_check.py b/tests/native_saveexec_wrexec_check.py new file mode 100644 index 0000000000..46708c6a31 --- /dev/null +++ b/tests/native_saveexec_wrexec_check.py @@ -0,0 +1,459 @@ +"""Direct Compute DXIL checks for all remaining SOP1 *_saveexec_* and *_wrexec_* ops (#3296, Refs #2935).""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_f16_alu_check import _branch, _exec, _i32, pack, words as pack_words +from native_scalar_lds_check import scalar, sop1, vmove + + +MOV_B32, MOV_B64 = 3, 4 +ZERO, ONE, NEG_ONE, M0, LITERAL = 128, 129, 193, 124, 255 +VCC_LO, EXEC_LO, EXEC_HI = 106, 126, 127 +MASK32, MASK64 = 0xFFFFFFFF, (1 << 64) - 1 +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +GROUP_WORDS, PLANE_WORDS = 128, 256 +PLANE_BYTES = PLANE_WORDS * 4 +SENTINEL = 0x69696969 +END = 0xBF810000 +ACTIVE_SENTINEL = 0x11110000 + +# Remaining 9 wave32 SOP1 ops (0x3e..0x46) and 3 wave64 SOP1 ops (0x37..0x39). +WAVE32_OPS = ( + ("s_xor_saveexec_b32", 0x3E, True), + ("s_andn2_saveexec_b32", 0x3F, True), + ("s_orn2_saveexec_b32", 0x40, True), + ("s_nand_saveexec_b32", 0x41, True), + ("s_nor_saveexec_b32", 0x42, True), + ("s_xnor_saveexec_b32", 0x43, True), + ("s_andn1_saveexec_b32", 0x44, True), + ("s_orn1_saveexec_b32", 0x45, True), + ("s_andn1_wrexec_b32", 0x46, False), +) +WAVE64_OPS = ( + ("s_andn1_saveexec_b64", 0x37, True), + ("s_orn1_saveexec_b64", 0x38, True), + ("s_andn1_wrexec_b64", 0x39, False), +) + + +def op_kind(name): + return name.split("_")[1] + + +def combine_bits(op, a, b, width): + mask = (1 << width) - 1 + if op == "and": + return a & b + if op == "or": + return a | b + if op == "xor": + return a ^ b + if op == "andn2": + return a & (b ^ mask) + if op == "orn2": + return (a | (b ^ mask)) & mask + if op == "andn1": + return (a ^ mask) & b + if op == "orn1": + return ((a ^ mask) | b) & mask + if op == "nand": + return (a & b) ^ mask + if op == "nor": + return (a | b) ^ mask + if op == "xnor": + return (a ^ b) ^ mask + raise ValueError(op) + + +def set_scc(value): + # s_cmp_eq_u32 0, (0 for true, 1 for false) + return 0xBF060080 | ((ZERO if value else ONE) << 8) + + +def store(vgpr, plane): + return [0xE0701000 | (plane * PLANE_BYTES), 0x80080008 | (vgpr << 8)] + + +def compute_container(code_bytes, wave32=True, threads=None): + """Build a .cdx container compatible with native_compute_ir_dump (table=s4, group=s5).""" + if threads is None: + threads = 32 if wave32 else 64 + body = bytearray(256) + struct.pack_into("<Q", body, 0, 6) + for offset in (8, 16, 24, 32, 40, 48, 72): + struct.pack_into("<Q", body, offset, 0xDEADBEEFDEADBEEF) + record = 112 + struct.pack_into("<Q", body, 96, record) + struct.pack_into("<Q", body, record + 40, len(body)) + struct.pack_into("<I", body, record + 56, 1) + body.extend(pack_words(3, 0, 1, 0, 4)) + struct.pack_into("<QQ", body, record, len(body), len(code_bytes)) + struct.pack_into("<I", body, record + 20, 32 if wave32 else 0) + struct.pack_into("<II", body, record + 76, 512, 4) + struct.pack_into("<IIII", body, record + 120, 0x8A, threads, 1, 1) + body.extend(code_bytes) + return pack(body) + + +def request(work, root, wave_size, threads, prog_words): + z = 1 | (1 << 20 if wave_size == 32 else 0) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), z, 0, 0x8A) + return write_request(work, prog_words, root, sa) + + +def wave32_cases(): + # (label, name, opcode, save, threads, old_exec, dst, src_reg, src_val, seed_reg) + return [ + # Non-zero cases (SCC=1, incoming SCC=0), asymmetric inputs to distinguish every op and operand order. + ("w32_xor_nz", "s_xor_saveexec_b32", 0x3E, True, 32, 0xA5A50003, 24, 22, 0x0F0F00F2, None), + ("w32_andn2_nz", "s_andn2_saveexec_b32", 0x3F, True, 32, 0x0F0F00F2, 24, 22, 0xA5A50003, None), + ("w32_orn2_nz", "s_orn2_saveexec_b32", 0x40, True, 32, 0xF0F0FF0C, 24, 22, 0x12340001, None), + ("w32_nand_nz", "s_nand_saveexec_b32", 0x41, True, 32, 0xA5A50003, 24, 22, 0xFFFF0002, None), + ("w32_nor_nz", "s_nor_saveexec_b32", 0x42, True, 32, 0x0F0F00F2, 24, 22, 0xF0F00004, None), + ("w32_xnor_nz", "s_xnor_saveexec_b32", 0x43, True, 32, 0xA5A50003, 24, 22, 0x5A5A00F2, None), + ("w32_andn1_nz", "s_andn1_saveexec_b32", 0x44, True, 32, 0xA5A50003, 24, 22, 0x0F0F0002, None), + ("w32_orn1_nz", "s_orn1_saveexec_b32", 0x45, True, 32, 0x00000011, 24, 22, 0xFFFF00FE, None), + ("w32_wr1_nz", "s_andn1_wrexec_b32", 0x46, False, 32, 0xA5A50003, 24, 22, 0x0F0F0002, None), + # Zero-result cases (SCC=0, incoming SCC=1), covering aliasing, inline, literal, VCC, EXEC_LO, partial wave. + ("w32_xor_z", "s_xor_saveexec_b32", 0x3E, True, 32, 0x12345678, 22, 22, 0x12345678, None), # dst == src + ("w32_andn2_z", "s_andn2_saveexec_b32", 0x3F, True, 32, 0xFFFFFFFF, 106, 22, 0x12345678, None), # dst=vcc_lo + ("w32_orn2_z", "s_orn2_saveexec_b32", 0x40, True, 32, 0xFFFFFFFF, 24, ZERO, 0, None), # inline 0 + ("w32_nand_z", "s_nand_saveexec_b32", 0x41, True, 32, 0xFFFFFFFF, 24, NEG_ONE, 0xFFFFFFFF, None), # inline -1 + ("w32_nor_z", "s_nor_saveexec_b32", 0x42, True, 32, 0xF0F0F0F0, 24, LITERAL, 0x0F0F0F0F, None), # literal + ("w32_xnor_z", "s_xnor_saveexec_b32", 0x43, True, 32, 0x55AA33CC, 24, 106, 0xAA55CC33, 106), # src=vcc_lo + ("w32_andn1_z", "s_andn1_saveexec_b32", 0x44, True, 8, 0x000000A5, 24, NEG_ONE, 0xFFFFFFFF, None), # partial + ("w32_orn1_z", "s_orn1_saveexec_b32", 0x45, True, 32, 0x00000000, 24, NEG_ONE, 0xFFFFFFFF, None), + ("w32_wr1_z", "s_andn1_wrexec_b32", 0x46, False, 32, 0x12345679, 22, 22, 0xFFFFFFFF, None), # dst == src + ("w32_xor_exec", "s_xor_saveexec_b32", 0x3E, True, 32, 0x000000FF, 24, EXEC_LO, 0x000000FF, None), # src=exec_lo + ] + + +def wave64_cases(): + # (label, name, opcode, save, threads, old_exec, dst, src_reg, src_val) + return [ + # Non-zero with bit 0 set (low & high both exercised). + ("w64_andn1_nz", "s_andn1_saveexec_b64", 0x37, True, 64, (0x80000013, 0x40000021), 24, 22, (0x00000012, 0x40000000)), + ("w64_orn1_nz", "s_orn1_saveexec_b64", 0x38, True, 64, (0x00000001, 0x40000000), 24, 22, (0xFFFFFF0E, 0xBFFFFF0F)), + ("w64_wr1_nz", "s_andn1_wrexec_b64", 0x39, False, 128, (0x80000013, 0x40000021), 22, 22, (0x00000012, 0x40000000)), # dst == src + # High-word-only non-zero (lo == 0, hi != 0 -> verifies SCC combines hi word, bit 0 == 0). + ("w64_andn1_hi", "s_andn1_saveexec_b64", 0x37, True, 64, (0x000000FF, 0x80000010), 24, 22, (0x000000FF, 0x0000000F)), + ("w64_orn1_hi", "s_orn1_saveexec_b64", 0x38, True, 64, (0x00000000, 0x00000001), 24, 22, (0xFFFFFFFF, 0xFFFFFFFE)), + ("w64_wr1_hi", "s_andn1_wrexec_b64", 0x39, False, 64, (0x000000FF, 0x80000010), 24, 22, (0x000000FF, 0x0000000F)), + # Zero-result cases (SCC=0, incoming SCC=1). + ("w64_andn1_z", "s_andn1_saveexec_b64", 0x37, True, 64, (0x80000012, 0x40000009), 24, NEG_ONE, (MASK32, MASK32)), + ("w64_orn1_z", "s_orn1_saveexec_b64", 0x38, True, 64, (0x00000000, 0x00000000), 24, NEG_ONE, (MASK32, MASK32)), + ("w64_wr1_z", "s_andn1_wrexec_b64", 0x39, False, 64, (0x80000012, 0x40000009), 24, 22, (MASK32, MASK32)), + ] + + +def build_wave32_program(case): + _, name, opcode, save, _, old_exec, dst, src_reg, src_val, seed_reg = case + new_exec = combine_bits(op_kind(name), src_val, old_exec, 32) + dst_val = old_exec if save else new_exec + scc = int(new_exec != 0) + # v8 = 512 * group.x + 4 * local.x; v1 = 0x11110000 + local.x + prog = [ + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(0x1E, 7, 5, ZERO + 9), # s_lshl_b32 s7, s5, 9 + vop2(0x1A, 8, ZERO + 2, 0), # v_lshlrev_b32 v8, 2, v0 + vop2(0x25, 8, 7, 8), # v_add_nc_u32 v8, s7, v8 + vop2(0x25, 1, LITERAL, 0), ACTIVE_SENTINEL, # v_add_nc_u32 v1, ACTIVE_SENTINEL, v0 + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + sop1(MOV_B32, EXEC_LO, LITERAL), old_exec, + ] + if seed_reg is not None: + prog += [sop1(MOV_B32, seed_reg, LITERAL), src_val] + elif src_reg < 106: + prog += [sop1(MOV_B32, src_reg, LITERAL), src_val] + prog.append(set_scc(1 - scc)) + prog.append(sop1(opcode, dst, src_reg)) + if src_reg == LITERAL: + prog.append(src_val) + prog += [ + *store(1, 0), # active-lane write under new EXEC + scalar(0x0A, 26, ONE, ZERO), # s_cselect_b32 s26, 1, 0 (captures SCC) + sop1(MOV_B32, 27, EXEC_LO), # capture new EXEC + sop1(MOV_B32, EXEC_LO, NEG_ONE), + ] + for plane, reg in ((1, dst), (2, 27), (3, 26)): + prog += [vmove(2, reg), *store(2, plane)] + prog.append(END) + return prog, new_exec, dst_val, scc + + +def build_wave64_program(case): + _, name, opcode, save, _, old_exec, dst, src_reg, src_val = case + old64 = old_exec[0] | (old_exec[1] << 32) + src64 = src_val[0] | (src_val[1] << 32) + new64 = combine_bits(op_kind(name), src64, old64, 64) + new_exec = (new64 & MASK32, new64 >> 32) + dst_val = old_exec if save else new_exec + scc = int(new64 != 0) + prog = [ + sop1(MOV_B64, 126, NEG_ONE), + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, ZERO + 9), + vop2(0x1A, 8, ZERO + 2, 0), + vop2(0x25, 8, 7, 8), + vop2(0x25, 1, LITERAL, 0), ACTIVE_SENTINEL, + 0xBF8CC07F, + sop1(MOV_B32, EXEC_LO, LITERAL), old_exec[0], + sop1(MOV_B32, EXEC_HI, LITERAL), old_exec[1], + ] + if src_reg < 106: + prog += [ + sop1(MOV_B32, src_reg, LITERAL), src_val[0], + sop1(MOV_B32, src_reg + 1, LITERAL), src_val[1], + ] + prog += [ + set_scc(1 - scc), + sop1(opcode, dst, src_reg), + *store(1, 0), # plane 0: active lanes under new EXEC + scalar(0x0A, 26, ONE, ZERO), # s26 = SCC + sop1(MOV_B64, 28, EXEC_LO), # s[28:29] = new EXEC + sop1(MOV_B64, EXEC_LO, NEG_ONE), + ] + for plane, reg in ((1, dst), (2, dst + 1), (3, 26)): + prog += [vmove(2, reg), *store(2, plane)] + # Advance v8 by 4096 so planes 4 and 5 stay within the 12-bit MUBUF offset field. + prog += [0x4A1010FF, 0x1000] + for plane, reg in ((0, 28), (1, 29)): + prog += [vmove(2, reg), *store(2, plane)] + prog.append(END) + return prog, new_exec, dst_val, scc + + +def interpret(ir_text): + """Evaluate lane 0 of a straight-line DXIL compute module.""" + body = ir_text.split("define void @main()", 1)[1].split("\n}", 1)[0] + blocks, label, buf = {}, None, [] + for raw in body.splitlines(): + line = raw.strip() + if not line or line == "{": + continue + if line.endswith(":") and " " not in line: + if label is not None: + blocks[label] = buf + label, buf = line[:-1], [] + continue + buf.append(line) + if label is not None: + blocks[label] = buf + values, memory, shared_mem, stores = {}, {}, {}, [] + label, prev_label, steps = "entry", None, 0 + while steps < 200000: + steps += 1 + followed = False + for line in blocks[label]: + if line.startswith("br "): + prev_label, label = label, _branch(line, values) + followed = True + break + if line == "ret void": + return sorted(stores) + if (m := re.fullmatch(r"(%\w+) = call i32 @dx\.op\.waveActiveOp\.i32\(.+\)", line)): + values[m.group(1)] = ("i32", 0) + elif line.startswith("call void @dx.op.barrier("): + continue + elif (m := re.fullmatch(r"(%\w+) = getelementptr .+, i32 (\S+)$", line)): + values[m.group(1)] = ("sptr", _i32(m.group(2), values)) + elif (m := re.fullmatch(r"store i32 (\S+), i32 addrspace\(3\)\* (%\w+), align 4", line)): + shared_mem[values[m.group(2)][1]] = _i32(m.group(1), values) + elif (m := re.fullmatch(r"(%\w+) = load i32, i32 addrspace\(3\)\* (%\w+), align 4", line)): + values[m.group(1)] = ("i32", shared_mem.get(values[m.group(2)][1], 0)) + elif (m := re.fullmatch(r"(%\w+) = phi i32 (.+)", line)): + chosen = None + for val_tok, pred in re.findall(r"\[([^,\]]+), %([^\]]+)\]", m.group(2)): + if pred == prev_label: + chosen = _i32(val_tok.strip(), values) + break + assert chosen is not None, (line, prev_label) + values[m.group(1)] = ("i32", chosen) + else: + _exec(line, values, memory, stores) + if not followed: + raise AssertionError("block fell through: " + label) + raise AssertionError("step limit") + + +def refusal_programs(): + init64 = [sop1(MOV_B64, 22, NEG_ONE), sop1(MOV_B64, VCC_LO, NEG_ONE)] + return [ + (True, 32, [sop1(0x3E, EXEC_LO, NEG_ONE), END], "unsupported wave32 SAVEEXEC destination"), + (True, 32, [sop1(0x46, EXEC_LO, NEG_ONE), END], "unsupported wave32 SAVEEXEC destination"), + (True, 32, [sop1(0x44, M0, NEG_ONE), END], "unsupported wave32 SAVEEXEC destination"), + (False, 64, [sop1(0x3E, 24, NEG_ONE), END], "direct DXIL lowering for s_xor_saveexec_b32"), + (False, 64, [sop1(0x46, 24, NEG_ONE), END], "direct DXIL lowering for s_andn1_wrexec_b32"), + (False, 64, [*init64, sop1(0x39, 24, VCC_LO), END], "unsupported wave64 scalar operation"), + (False, 64, [*init64, sop1(0x39, 25, 22), END], "unsupported wave64 scalar operation"), + (False, 64, [*init64, sop1(0x37, 25, 22), END], "unsupported wave64 scalar operation"), + ] + + +def check_oracles(): + # Ensure mutant references (swapped n1/n2, dropped ~ on nand/nor/xnor, save-vs-wrexec swap) differ cleanly. + for op in ("andn1", "orn1"): + for a, b in ((0x0F0F0002, 0xA5A50003),): + assert combine_bits(op, a, b, 32) != combine_bits(op.replace("n1", "n2"), a, b, 32) + for op, alt in (("nand", "and"), ("nor", "or"), ("xnor", "xor")): + assert combine_bits(op, 0x0F0F00F2, 0xA5A50003, 32) != combine_bits(alt, 0x0F0F00F2, 0xA5A50003, 32) + + +def ir(dumper): + check_oracles() + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for case in wave32_cases(): + label = case[0] + prog, new_exec, dst_val, scc = build_wave32_program(case) + path = work / f"{label}.cdx" + path.write_bytes(compute_container(pack_words(*prog), wave32=True, threads=case[4])) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, (label, run.stderr) + stores = dict(interpret(run.stdout)) + if new_exec & 1: + assert stores.get(0) == ACTIVE_SENTINEL, (label, stores) + else: + assert 0 not in stores, (label, stores) + assert stores.get(1 * PLANE_BYTES) == dst_val, (label, hex(stores.get(PLANE_BYTES, -1)), hex(dst_val)) + assert stores.get(2 * PLANE_BYTES) == new_exec, (label, hex(stores.get(2 * PLANE_BYTES, -1)), hex(new_exec)) + assert stores.get(3 * PLANE_BYTES) == scc, (label, stores.get(3 * PLANE_BYTES), scc) + + for case in wave64_cases(): + label = case[0] + prog, new_exec, dst_val, scc = build_wave64_program(case) + path = work / f"{label}.cdx" + path.write_bytes(compute_container(pack_words(*prog), wave32=False, threads=case[4])) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode == 0, (label, run.stderr) + stores = dict(interpret(run.stdout)) + if new_exec[0] & 1: + assert stores.get(0) == ACTIVE_SENTINEL, (label, stores) + else: + assert 0 not in stores, (label, stores) + assert stores.get(1 * PLANE_BYTES) == dst_val[0], (label, stores, dst_val) + assert stores.get(2 * PLANE_BYTES) == dst_val[1], (label, stores, dst_val) + assert stores.get(3 * PLANE_BYTES) == scc, (label, stores, scc) + assert stores.get(4 * PLANE_BYTES) == new_exec[0], (label, stores, new_exec) + assert stores.get(5 * PLANE_BYTES) == new_exec[1], (label, stores, new_exec) + + for idx, (wave32, threads, bad_prog, err) in enumerate(refusal_programs()): + path = work / f"refuse{idx}.cdx" + path.write_bytes(compute_container(pack_words(*bad_prog), wave32=wave32, threads=threads)) + run = subprocess.run([dumper, str(path)], capture_output=True, text=True) + assert run.returncode != 0 and err in run.stderr, (idx, err, run.returncode, run.stderr) + + print(f"evaluated IR for {len(wave32_cases())} wave32 and {len(wave64_cases())} wave64 cases, " + f"plus {len(refusal_programs())} refusals") + return 0 + + +def controls(cli, sdk, work, root): + check_oracles() + cache = work / "cache" + compiled = 0 + for wave_size, builder, items in ((32, build_wave32_program, wave32_cases()), + (64, build_wave64_program, wave64_cases())): + for case in items: + label = case[0] + prog, _, _, _ = builder(case) + marker = request(work, root, wave_size, case[4], prog) + cso = marker.with_suffix(".cso") + cso.unlink(missing_ok=True) + res = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, cso], + capture_output=True, text=True) + assert res.returncode == 0 and cso.is_file(), (label, res.stdout, res.stderr) + compiled += 1 + + refusals = refusal_programs() + for idx, (wave32, threads, bad_prog, err) in enumerate(refusals): + marker = request(work, root, 32 if wave32 else 64, threads, bad_prog) + cso = marker.with_suffix(".cso") + cso.unlink(missing_ok=True) + res = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, cso], + capture_output=True, text=True) + assert res.returncode != 0 and err in res.stderr, (idx, err, res.stdout, res.stderr) + assert not cso.exists(), cso + + print(f"compiled {compiled} wave32/wave64 cases cleanly and verified {len(refusals)} refusals") + return 0 + + +def hardware(replay, sdk, work, root): + cache = work / "cache" + for case in wave32_cases(): + label, _, _, _, threads, _, _, _, _, _ = case + prog, new_exec, dst_val, scc = build_wave32_program(case) + marker = request(work, root, 32, threads, prog) + out = work / f"{label}.bin" + run = subprocess.run([replay, sdk, marker, cache, "0", out, "--direct"]) + if run.returncode == 77: + return 77 + run.check_returncode() + actual = list(struct.unpack(f"<{OUTPUT_WORDS}I", out.read_bytes())) + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(threads): + pos = GUARD_WORDS + group * GROUP_WORDS + lane + if new_exec & (1 << lane): + expected[pos] = ACTIVE_SENTINEL | lane + expected[pos + 1 * PLANE_WORDS] = dst_val + expected[pos + 2 * PLANE_WORDS] = new_exec + expected[pos + 3 * PLANE_WORDS] = scc + assert actual == expected, (label, [ + (i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b + ][:10]) + + for case in wave64_cases(): + label, _, _, _, threads, _, _, _, _ = case + prog, new_exec, dst_val, scc = build_wave64_program(case) + marker = request(work, root, 64, threads, prog) + out = work / f"{label}.bin" + run = subprocess.run([replay, sdk, marker, cache, "0", out, "--direct"]) + if run.returncode == 77: + return 77 + run.check_returncode() + actual = list(struct.unpack(f"<{OUTPUT_WORDS}I", out.read_bytes())) + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for local in range(threads): + lane = local % 64 + pos = GUARD_WORDS + group * GROUP_WORDS + local + if new_exec[lane // 32] & (1 << (lane % 32)): + expected[pos] = ACTIVE_SENTINEL | local + expected[pos + 1 * PLANE_WORDS] = dst_val[0] + expected[pos + 2 * PLANE_WORDS] = dst_val[1] + expected[pos + 3 * PLANE_WORDS] = scc + expected[pos + 4 * PLANE_WORDS] = new_exec[0] + expected[pos + 5 * PLANE_WORDS] = new_exec[1] + assert actual == expected, (label, [ + (i, hex(a), hex(b)) for i, (a, b) in enumerate(zip(actual, expected)) if a != b + ][:10]) + + print(f"replayed {len(wave32_cases())} wave32 and {len(wave64_cases())} wave64 cases on GPU with guards") + return 0 + + +def main(mode, tool, sdk=None): + if mode == "ir": + return ir(tool) + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_scalar_lds_check.py b/tests/native_scalar_lds_check.py new file mode 100644 index 0000000000..4f4a9280c5 --- /dev/null +++ b/tests/native_scalar_lds_check.py @@ -0,0 +1,261 @@ +"""Run the shared C++ direct-DXIL frontend on a source-built scalar/LDS request.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + + +def scalar(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def sop1(op, dst, src): + return 0xbe800000 | dst << 16 | op << 8 | src + + +def vmove(dst, src): + return 0x7e000200 | dst << 17 | src + + +def ds(op, addr, data0=0, data1=0, dst=0, offset=0): + return [0xd8000000 | op << 18 | offset, dst << 24 | data1 << 16 | data0 << 8 | addr] + + +def program(mutant): + # Root table s4, group.x in s5, 64 bytes per group. Keep lane zero active. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf4080000 | 32 << 6 | 10, 0xfa000020, + scalar(0x1e, 7, 5, 134), vmove(8, 7), sop1(3, 126, 129)] + # src = 0x81234567 ^ group.x. High signed/unsigned multiplication and bitset + # must preserve zero SCC. Make both the bit position and destination s11. + words += [scalar(0x12, 16, 5, 255), 0x81234567, 0xbf068180, + scalar(0x36 if mutant else 0x35, 10, 16, 193), vmove(1, 10), + scalar(0x36, 10, 16, 193), vmove(2, 10), + sop1(3, 11, 255), 0x8000001f, sop1(0x1b, 11, 11), vmove(3, 11), + sop1(0x3b, 16, 16), sop1(0x1d, 16, 134), sop1(0x1c, 16, 191), + sop1(0x1e, 16, 190), vmove(4, 16), vmove(5, 17), + # A nonempty mask (7 ones shifted by 3) must preserve SCC=0. + scalar(0x24, 24, 135, 131), vmove(16, 24), + scalar(0x0a, 10, 129, 128), vmove(6, 10), + sop1(0x34, 10, 255), 0x80000000, vmove(7, 10), + scalar(0x0a, 10, 129, 128), vmove(9, 10)] + # Use distinct b64 tuples, reverse offset order on read and alias the + # first result with the read's address. Returning subtract aliases data0. + words += [vmove(10, 128), vmove(11, 129), vmove(12, 130), vmove(13, 131), vmove(14, 132), + *ds(0x4e, 10, 11, 13, offset=0x0301), *ds(0x77, 10, dst=10, offset=0x0103), + vmove(14, 128), vmove(15, 129), *ds(0x21, 14, 15, dst=15, offset=8), 0xbfa3ffe3, + *ds(0x36, 14, dst=14, offset=8)] + for index, vgpr in enumerate([1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 14, 16]): + words += [0xe0701000 | 4 * index, 0x80080008 | vgpr << 8] + return words + [0xbbfd0000, 0xbf8a0000, 0xbf810000] # drain stores, then group barrier + + +def reference(group): + a = 0x81234567 ^ group + replicated = sum(3 << (2 * i) for i in range(32) if a & (1 << i)) + replicated = (replicated | 1 << 6 | 1 << 62) & ~(1 << 63) + return [a * 0xffffffff >> 32, 0, 31, replicated & 0xffffffff, replicated >> 32, + 0, 0x80000000, 1, 3, 4, 1, 2, 1, 0, 127 << 3] + + +def built_root_readback(work, gpu, sdk): + source, root = work / "built.hlsl", work / "built.root" + source.write_text('#define SIG "SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 7 << 1) + for offset in (96, 92): + # Build the byte-address V# in s16:19 from root SRV s4:5. Each + # group selects an aligned index. Group 1 ends at the view limit. + words = [sop1(4, 16, 4), sop1(3, 18, 255), 132, sop1(3, 19, 255), 0x31016fac, + sop1(3, 20, 6), sop1(3, 21, 128), 0xf4080000 | 40 << 6 | 10, 0xfa000020, + scalar(0x1e, 11, 7, 130), scalar(0xe, 11, 11, 132), + 0xf42c0808, 11 << 25 | offset, scalar(0x1e, 12, 7, 133), vmove(8, 12), + sop1(3, 126, 129)] + for j in range(8): + words += [vmove(9, 32 + j), 0xe0701000 | 4 * j, 0x800a0908] + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + dest = work / "built-readback.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + for group in range(2): + for j in range(8): + expected[8 + 8 * group + j] = 0x51aa0000 + offset // 4 + group + j + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Root-built scalar x8 matched 16 words and all guards at each offset; shifting by one dword changed all 16.") + + + # The byte address in v8 overlaps the first destination of the x3 load. + # Select a different source window in each group and keep all guard words. + words = [sop1(3, 16, 4), scalar(0x10, 17, 5, 255), 0x10000, + sop1(3, 18, 193), sop1(3, 19, 255), 0x11014fac, + sop1(3, 20, 6), sop1(3, 21, 128), 0xf4080000 | 40 << 6 | 10, 0xfa000020, + scalar(0x1e, 12, 7, 132), vmove(8, 12), vmove(11, 12), + # The replay fixture creates the smallest raw SRV requested by the + # program. A scalar load at byte 24 provisions the seven-word view. + 0xf4200000 | (25 << 6) | 8, 0xfa000018, + 0xe03c1000, 0x80040808, sop1(3, 126, 129)] + for j in range(3): + words.extend([0xe0701000 | 4*j, 0x800a000b | (8+j) << 8]) + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + for group in range(2): + for j in range(3): + expected[8 + group * 4 + j] = 0x51aa0000 + group * 4 + j + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i,a,b) for i,(a,b) in enumerate(zip(actual,expected)) if a!=b][:10] + print("Root descriptor with byte stride one: x3 load matches both source windows and all guards.") + + +def vector_carry_readback(work, gpu, sdk): + def vop2(op, dst, a, b): + return op << 25 | dst << 17 | b << 9 | a + + forms = [(op, wide) for op in (0x128, 0x129, 0x12a) for wide in (False, True)] + forms += [(op, True) for op in (0x30f, 0x310, 0x319)] + full = (1 << 32) - 1 + active = 0xdedebdbd + cin = 0x5a3c96e1 + # Each lane owns 128 bytes. Generate (a,b) of (0,0), (~0,0), + # (0,1), (~0,1) repeating, covering carry on either addition step. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 140), vop2(0x1a, 8, 135, 0), vop2(0x25, 8, 7, 8), + vop2(0x1a, 1, 159, 0), vop2(0x18, 1, 159, 1), vop2(0x16, 2, 129, 0), + vop2(0x1b, 2, 129, 2)] + expected = [0x69696969] * 2064 + for idx, (op, wide) in enumerate(forms): + ci = op in (0x128, 0x129, 0x12a) + add = op in (0x128, 0x30f) + reverse = op in (0x12a, 0x319) + mask = 30 if wide else 106 + words += [vmove(10, 257), sop1(3, mask, 255), cin, sop1(3, 126, 255), active] + if wide: + words += [0xd4000000 | op << 16 | mask << 8 | 10, 266 | 258 << 9 | (mask if ci else 0) << 18] + else: + words.append(vop2(op - 0x100, 10, 266, 2)) + words += [sop1(3, 126, 193), vmove(11, mask), 0xe0701000 | 8 * idx, 0x80080a08, + 0xe0701004 | 8 * idx, 0x80080b08] + ballot = 0 + for lane in range(32): + a, b = full * (lane & 1), (lane >> 1) & 1 + bit = int(ci) * ((cin >> lane) & 1) + exact = a + b + bit if add else (b - a if reverse else a - b) - bit + enabled = (active >> lane) & 1 + ballot |= int(enabled and (exact < 0 or exact > full)) << lane + for group in range(2): + pos = 8 + 32 * (group * 32 + lane) + 2 * idx + expected[pos] = exact & full if enabled else a + for lane in range(64): + expected[8 + 32 * lane + 2 * idx + 1] = ballot + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1) + marker = write_request(work, words + [0xbf810000], (work / "root.bin").read_bytes(), sa) + dest = work / "carry-readback.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Nine carry/borrow encodings matched 1152 result and ballot words plus all guards.") + + +def half_mad_readback(work, gpu, sdk): + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 136), vmove(8, 7), sop1(3, 126, 129)] + a, b = 0x80007fff, 0xfffe0003 + words += [vmove(1, 255), a, vmove(2, 255), b] + values = [] + for signed in (False, True): + for addend in (0x80000010, 0x7ffffff0, 0xfffffffe): + for clamp in (False, True): + for halves in range(4): + # Alias the dword addend and the result VGPR. + inst = 0xd4000000 | (0x375 if signed else 0x373) << 16 | clamp << 15 | halves << 11 | 3 + offset = 4 * len(values) + words += [vmove(3, 255), addend, inst, 257 | 258 << 9 | 259 << 18, + 0xe0701000 | offset, 0x80080308] + x = (a >> (16 * (halves & 1))) & 65535 + y = (b >> (16 * (halves >> 1))) & 65535 + z = addend + if signed: + x -= (x >> 15) << 16 + y -= (y >> 15) << 16 + z -= (z >> 31) << 32 + exact = x * y + z + if clamp: + low, high = (-2**31, 2**31-1) if signed else (0, 2**32-1) + exact = min(high, max(low, exact)) + values.append(exact & 0xffffffff) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1) + marker = write_request(work, words + [0xbf810000], (work / "root.bin").read_bytes(), sa) + dest = work / "half-mad-readback.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + group * 64 + expected[start:start + len(values)] = values + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Halfword MAD matched 96 signed/unsigned results across half-selects, wrap, saturation and aliasing.") + + +def descriptor_scc_readback(work, gpu, sdk): + # Use the table only as provenance for s[16:19]. Its guest address bits + # are unavailable in the shader. OOB_SELECT=3 always sets SCC, whereas + # the masked address's SCC must be dead at SAVEEXEC. + words = [sop1(3, 20, 4), sop1(3, 21, 128), + 0xf408040a, 0xfa000000, 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 132), vmove(8, 7), + scalar(0xe, 23, 19, 255), 0xcfffffff, 0xbf068180, + scalar(0x10, 23, 23, 255), 0x30000000, sop1(3, 25, 253), + scalar(0xe, 17, 17, 255), 0xc000ffff, sop1(0x3c, 24, 5), + sop1(3, 26, 253), sop1(3, 126, 129), + vmove(9, 25), vmove(10, 26), 0xe0701000, 0x80080908, 0xe0701004, 0x80080a08, + # -0 has class bit 5. BYTE_3 selects this bit only in group 1, + # BYTE_0 selects it in both. Only lane zero contributes. + scalar(0x1e, 11, 5, 157), scalar(0x10, 11, 11, 160), vmove(5, 11), + 0x7d100af9, 0x03968e80, vmove(9, 14), 0xe0701008, 0x80080908, + 0x7d100af9, 0x00968e80, vmove(9, 14), 0xe070100c, 0x80080908, + 0xbf810000] + marker = write_request(work, words, (work / "root.bin").read_bytes(), + struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x80 | 5 << 1)) + dest = work / "descriptor-scc.bin" + subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"], check=True) + expected = [0x69696969] * 2064 + expected[8:12] = [1, 0, 0, 1] + expected[12:16] = [1, 1, 1, 1] + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Descriptor OOB OR / SAVEEXEC SCC and both -0 SDWA class-mask selections matched eight words and all guards.") + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src, root = work / "root.hlsl", work / "root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | (1 << 20), 0, 0x808a) + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + 16 * group + expected[start:start + 15] = reference(group) + for mutant in (False, True): + marker = write_request(work, program(mutant), root.read_bytes(), sa) + dest = work / "result.bin" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + sys.exit(77) + result.check_returncode() + actual = struct.unpack("<2064I", dest.read_bytes()) + mismatches = [i for i, (a, b) in enumerate(zip(actual, expected)) if a != b] + assert mismatches == ([8, 24] if mutant else []), [(i, actual[i], expected[i]) for i in mismatches[:10]] + print("Two direct-DXIL workgroups matched 30 result words and all guards; the signed-multiply control differed twice.") + built_root_readback(work, gpu, sdk) + vector_carry_readback(work, gpu, sdk) + half_mad_readback(work, gpu, sdk) + descriptor_scc_readback(work, gpu, sdk) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_scalar_mask64_check.py b/tests/native_scalar_mask64_check.py new file mode 100644 index 0000000000..4b72c7ab49 --- /dev/null +++ b/tests/native_scalar_mask64_check.py @@ -0,0 +1,128 @@ +"""Check s_andn2_wrexec_b64 in a wave64 request of at most 32 threads.""" +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from native_scalar_lds_check import sop1 +from native_wrexec64_check import ( + ANDN2_WREXEC_B64, EXEC_HI, LITERAL, MOV_B32, OLD_EXEC, OUTPUT_WORDS, + expected_output, program, request, +) + + +BCNT1_I32_B64, VCC_LO, END = 0x10, 106, 0xBF810000 +SOURCE = (0x96, 0x40000001) +REGISTER = r"%[-\w.]+" + + +def wrexec_program(dst=28, *, high="initial"): + code = program(SOURCE, dst, 0) + code[code.index(sop1(ANDN2_WREXEC_B64, dst, 22))] = sop1(ANDN2_WREXEC_B64, dst, 28) + for src, dst_reg in ((22, 28), (23, 29)): + code[code.index(sop1(MOV_B32, src, LITERAL))] = sop1(MOV_B32, dst_reg, LITERAL) + if high == "initial": + index = code.index(sop1(MOV_B32, EXEC_HI, LITERAL)) + del code[index:index + 2] + elif high == "cmpx": + index = code.index(sop1(ANDN2_WREXEC_B64, dst, 28)) + code.insert(index, 0x7DA40080) # v_cmpx_eq_u32 0, v0 (lane 0 disabled) + return code + + +def count_program(src=VCC_LO): + return [sop1(MOV_B32, VCC_LO, LITERAL), 0x80000003, + sop1(MOV_B32, VCC_LO + 1, LITERAL), 0x40000050, + sop1(BCNT1_I32_B64, 16, src), END] + + +def compile_case(cli, sdk, work, marker, diagnostic=None): + output = marker.with_suffix(".cso") + run = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True, timeout=30) + if diagnostic: + assert run.returncode and not output.exists(), (run.stdout, run.stderr) + assert any(line.endswith(": " + diagnostic) for line in run.stderr.splitlines()), run.stderr + return "" + assert run.returncode == 0 and output.is_file(), (run.stdout, run.stderr) + return subprocess.run([Path(sdk) / "dxc.exe", "-dumpbin", output], + capture_output=True, text=True, timeout=30, check=True).stdout + + +def definitions(dump): + return {name: rhs.strip() for name, rhs in + re.findall(rf"^\s*({REGISTER}) = ([^\n;]+)", dump, re.MULTILINE)} + + +def stored(dump, reg): + return re.findall(rf"^\s*store i32 (\S+), i32\* %r{reg}, align 4", dump, re.MULTILINE) + + +def check_scc(defs, value, result): + check = re.fullmatch(rf"zext i1 ({REGISTER}) to i32", defs[value]) + assert check and defs[check[1]] == f"icmp ne i32 {result}, 0", defs + + +def check_wrexec(dump, old_high): + defs = definitions(dump) + low, high = (stored(dump, reg)[-1] for reg in (28, 29)) + for result, src, exec_reg in ((low, 28, 126), (high, 29, 127)): + operands = re.fullmatch(rf"and i32 ({REGISTER}), ({REGISTER})", defs[result]) + assert operands and defs[operands[1]] == f"load i32, i32* %r{src}, align 4", dump + inv = re.fullmatch(rf"xor i32 ({REGISTER}), -1", defs[operands[2]]) + assert inv and defs[inv[1]] == f"load i32, i32* %r{exec_reg}, align 4", dump + assert stored(dump, exec_reg)[-2] == result, dump # followed by fixture restore + assert int(stored(dump, EXEC_HI)[-3]) == old_high, dump + scc = stored(dump, 128)[-1] + merged, = [name for name, rhs in defs.items() if rhs == f"or i32 {low}, {high}"] + check_scc(defs, scc, merged) + + +def controls(cli, sdk, work, root): + for high in ("initial", "scalar", "cmpx"): + marker = request(work, root, 32, wrexec_program(high=high)) + check_wrexec(compile_case(cli, sdk, work, marker), OLD_EXEC[1] if high == "scalar" else 0) + for code, threads, diagnostic in ( + (wrexec_program(dst=29), 32, "unsupported wave64 scalar operation"), + (count_program(src=107), 64, "invalid s_bcnt1_i32_b64 source"), + # VCC stays refused as a 64-bit count source. + (count_program(), 64, "invalid s_bcnt1_i32_b64 source"), + (count_program(), 32, "invalid s_bcnt1_i32_b64 source"), + ): + compile_case(cli, sdk, work, request(work, root, threads, code), diagnostic) + print("64-bit scalar mask DXIL and refusal diagnostics matched") + return 0 + + +def hardware(replay, sdk, work, root): + for high in ("initial", "scalar", "cmpx"): + marker = request(work, root, 32, wrexec_program(high=high)) + output = marker.with_suffix(".bin") + run = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"], timeout=30) + if run.returncode == 77: + return 77 + run.check_returncode() + old_low = 0 if high == "cmpx" else OLD_EXEC[0] + old_high = OLD_EXEC[1] if high == "scalar" else 0 + mask = (SOURCE[0] & ~old_low, SOURCE[1] & ~old_high) + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = expected_output(32, mask, int(any(mask))) + assert list(actual) == expected, (high, actual, expected) + print("32-thread wave64 WREXEC lane stores, destination words and SCC matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source, root = work / "root.hlsl", work / "root.bin" + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True, timeout=30) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_sdwa_f16_check.py b/tests/native_sdwa_f16_check.py new file mode 100644 index 0000000000..a992c50621 --- /dev/null +++ b/tests/native_sdwa_f16_check.py @@ -0,0 +1,266 @@ +"""Direct compute SDWA arithmetic and conversion. Use ir DUMPER or gpu STORE_REPLAY SDK.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import f16_packed_model as model +import native_f16_alu_check as fixture +from native_compute_clear_check import write_request + +BYTE_1, WORD_0, WORD_1, DWORD = 1, 4, 5, 6 +PAD, SEXT, PRESERVE = 0, 1, 2 +NEG, ABS, SCALAR = 0x10, 0x20, 0x80 +CLAMP = 1 << 13 +OLD = 0xa55a1357 +GUARD = 0x69696969 +ADD_CO_CI, PKRTZ = 0x28, 0x2f +LANE_STRIDE = fixture.STRIDE // 2 +LANE_BYTE_SHIFT = fixture.SHIFT - 1 + + +def sdwa(opcode, dst, unused, src0, src1=0, reg0=1, reg1=2, dst_mod=0, unary=False): + ext = (reg0 | (dst << 8) | (unused << 11) | dst_mod | + (src0 << 16) | (src1 << 24)) + instruction = fixture.vop1(opcode, 3, 249) if unary else fixture.vop2(opcode, 3, 249, reg1) + return instruction + [ext] + + +def cvt_sdwa(src0, dst_mod=CLAMP): + # VOP1 opcode 0x0b, v3 destination, SDWA escape, then v1 with DWORD/PAD. + return [0x7e000000 | (3 << 17) | (0x0b << 9) | 249, + 1 | (DWORD << 8) | dst_mod | (src0 << 16)] + + +class ClampCase: + op = 'v_cvt_f32_f16 clamp' + dest = 3 + + def __init__(self, half, selector): + self.selector = selector + # Put a distinct in-range value in the other half to expose a wrong selector. + other = 0x3400 + self.word = (half << 16) | other if selector == WORD_1 else (other << 16) | half + value = struct.unpack('<e', struct.pack('<H', half))[0] + # An ordered > comparison maps NaN, negative values and -0.0 to +0.0. + result = min(value, 1.0) if value > 0.0 else 0.0 + self.want = struct.unpack('<I', struct.pack('<f', result))[0] + + def emit(self): + return fixture.mov(1, self.word) + fixture.mov(self.dest, OLD) + cvt_sdwa(self.selector) + + def matches(self, got): + return got == self.want + + +class Case: + dest = 3 + + def __init__(self, op, a, b, dst, unused, src0, src1): + self.op, self.a, self.b = op, a, b + self.dst, self.unused = dst, unused + self.src0, self.src1 = src0, src1 + self.shift = 16 if dst == WORD_1 else 0 + self.mask = 0xffff << self.shift + self.alternate = model.rsq_rounding(self.read(a, src0))[1] if op == 'rsq' else None + self.want = self.expected(src0, src1, unused) + + @staticmethod + def read(value, control): + picked = model.pick(value, (control & 7) == WORD_1) + return fixture.modified(picked, bool(control & ABS), bool(control & NEG), 0) + + def expected(self, src0, src1, unused): + result = fixture.binary16(self.op, self.read(self.a, src0), self.read(self.b, src1)) + other = OLD & ~self.mask if unused == PRESERVE else 0 + return (result << self.shift) | other + + def emit(self): + if self.op in fixture.UNARY_CODE: + return (fixture.mov(1, self.a) + fixture.mov(self.dest, OLD) + + sdwa(fixture.UNARY_CODE[self.op], self.dst, self.unused, self.src0, unary=True)) + return (fixture.mov(1, self.a) + fixture.mov(2, self.b) + fixture.mov(self.dest, OLD) + + sdwa(fixture.OP_CODE[self.op], self.dst, self.unused, self.src0, self.src1)) + + def matches(self, got): + return (got & ~self.mask == self.want & ~self.mask and + fixture.same_alu_result((got & self.mask) >> self.shift, + (self.want & self.mask) >> self.shift, self.op, self.alternate)) + + +def cases(): + shapes = [ + (0x3c004400, 0x45004000, WORD_0, PRESERVE, WORD_1, DWORD), + (0x44004200, 0x45003c00, WORD_0, PAD, DWORD, WORD_0), + (0x4400bc00, 0x40004500, WORD_1, PRESERVE, WORD_0 | ABS | NEG, WORD_1), + ] + items = [Case(op, *shape) for shape in shapes for op in fixture.OPS] + items += [ + Case('add', 0x3c014400, 0x45001000, WORD_0, PRESERVE, WORD_1, DWORD), + Case('mul', 0x44000003, 0x45003800, WORD_0, PAD, DWORD, WORD_0), + Case('mul', 0x44007bff, 0x40004500, WORD_1, PAD, WORD_0, WORD_1), + Case('add', 0x7e014400, 0x45003c00, WORD_0, PRESERVE, WORD_1, DWORD), + # neg on one source and abs on the other: -(1.0) + |-2.0| = 1.0; dropping either modifier changes the sum. + Case('add', 0x44003c00, 0xc0004500, WORD_1, PAD, WORD_0 | NEG, WORD_1 | ABS), + ] + for op in fixture.UNARY_CODE: + items.append(Case(op, 0xc4003800, 0, WORD_1, PRESERVE, WORD_1 | ABS, 0)) + items.append(Case(op, 0x44004000, 0, WORD_0, PAD, DWORD | NEG, 0)) + items += [ + Case('rsq', 0x44000000, 0, WORD_1, PAD, WORD_0 | NEG, 0), + Case('rsq', 0x3bfe4400, 0, WORD_1, PRESERVE, WORD_1, 0), + Case('exp', 0x91c54400, 0, WORD_1, PRESERVE, WORD_1 | ABS, 0), + ] + assert len(items) < fixture.STRIDE + return items + + +def clamp_cases(): + # -1, 2, quiet NaN, -0, smallest positive subnormal, 0.5, and 1. + halves = (0xbc00, 0x4000, 0x7e01, 0x8000, 0x0001, 0x3800, 0x3c00) + return [ClampCase(half, selector) for selector in (WORD_0, WORD_1) for half in halves] + + +def check_mutants(items): + # Manual lowering mutants that must fail: swap WORD_0/WORD_1 on either + # source, or ignore UNUSED_PRESERVE by zeroing the other destination half. + def swap(control): + return control ^ 1 if (control & 7) in (WORD_0, WORD_1) else control + + # Without this, a comparator that rejects every word would pass the mutant checks below. + assert all(case.matches(case.want) for case in items) + assert any(not case.matches(case.expected(swap(case.src0), case.src1, case.unused)) for case in items) + assert any(not case.matches(case.expected(case.src0, swap(case.src1), case.unused)) for case in items) + assert any(not case.matches(case.expected(case.src0, case.src1, PAD)) for case in items) + + +def refusals(): + add = fixture.OP_CODE['add'] + dest_error = 'unsupported SDWA destination modifier' + src_error = 'invalid SDWA source modifier' + return [ + (sdwa(add, DWORD, PAD, WORD_0, WORD_0), dest_error), + (sdwa(add, WORD_0, PAD, BYTE_1, WORD_0), src_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | 8), src_error), + (sdwa(add, WORD_0, SEXT, WORD_0, WORD_0), dest_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 13), dest_error), + (sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 14), dest_error), + (cvt_sdwa(WORD_0, 1 << 14), dest_error), + (cvt_sdwa(WORD_1, CLAMP | (1 << 14)), dest_error), + (sdwa(0x39, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # max + (sdwa(0x3a, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # min + (sdwa(0x55, WORD_0, PAD, DWORD, dst_mod=1 << 13, unary=True), dest_error), + (sdwa(0x57, WORD_0, PAD, WORD_0, unary=True), 'unimplemented direct SDWA operand profile'), + ] + [ + (sdwa(op, WORD_0, PAD, DWORD, DWORD, dst_mod=1 << modifier), dest_error) + for op in (PKRTZ, ADD_CO_CI) for modifier in (13, 14) + ] + + +def run_ir(dumper, items, code): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + run = fixture.dump(dumper, work, code, 'sdwa-f16') + assert run.returncode == 0, run.stderr + stores = sorted(fixture.interpret(run.stdout)) + assert [addr for addr, _ in stores] == [4 * i for i in range(len(items))] + for (addr, got), case in zip(stores, items): + assert case.matches(got), (addr, case.op, hex(got), hex(case.want)) + for index, (instruction, why) in enumerate(refusals()): + run = fixture.dump(dumper, work, instruction + [0xbf810000], 'refused-%d' % index) + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print('native_sdwa_f16 IR: %d results and %d refusals' % (len(items), len(refusals()))) + + +def extend_gpu_program(code, items): + code = code[:-1] # Append cases just before s_endpgm. + expected = {(0, slot): (case.want, None) for slot, case in enumerate(items)} + slot = len(items) + # The expected half is the RTZ conversion of the first source after abs/neg. + for a, dst, unused, src0, half in ( + (0x3f801800, WORD_0, PAD, DWORD, 0x3c00), + (0xbf801800, WORD_1, PRESERVE, DWORD | ABS, 0x3c00), + (0x7f800000, WORD_0, PAD, DWORD | NEG, 0xfc00), + (0x7fc00001, WORD_1, PRESERVE, DWORD, 0x7e00)): + code += fixture.mov(1, a) + fixture.mov(3, OLD) + code += sdwa(PKRTZ, dst, unused, src0, DWORD | SCALAR, reg1=128) + code += fixture.store(4 * slot, 3) + shift = 16 if dst == WORD_1 else 0 + expected[0, slot] = ((half << shift) | (OLD & 0xffff if unused == PRESERVE else 0), shift) + slot += 1 + + # Enable lanes 0 and 1. v8 is the group base and v0 is the local thread ID. + code += [fixture.sop1(3, 126, 131)] + code += fixture.vop2(0x1a, 7, 128 + LANE_BYTE_SHIFT, 0) + code += fixture.vop2(0x25, 8, 256 + 7, 8) + carry_in = 0b10 + for a, b, dst, src0, src1 in ( + (0xffffffff, 0, WORD_1, DWORD, DWORD), + (0xffffffff, 0x1235, WORD_1, DWORD, DWORD), + (0xfffffffe, 0xffff0001, WORD_1, WORD_0, DWORD), + (0xaaaa1234, 0xbeefffff, DWORD, WORD_0, WORD_1)): + code += fixture.mov(1, a) + fixture.mov(2, b) + fixture.mov(4, 1) + code += [fixture.sop1(3, 106, 128 + carry_in)] + code += sdwa(ADD_CO_CI, dst, PAD, src0, src1) + code += fixture.vop2(0x01, 4, 128, 4) # v_cndmask_b32 v4, 0, v4, vcc_lo + code += fixture.store(4 * slot, 3) + fixture.store(4 * (slot + 1), 4) + left = a if src0 == DWORD else a & 0xffff + right = b if src1 == DWORD else b >> 16 + for lane in range(2): + total = left + right + ((carry_in >> lane) & 1) + result = (total & 0xffff) << 16 if dst == WORD_1 else total & 0xffffffff + expected[lane, slot] = (result, None) + expected[lane, slot + 1] = (total >> 32, None) + slot += 2 + assert slot <= LANE_STRIDE + return code + [0xbf810000], expected + + +def run_gpu(gpu, sdk, items, code): + code, expected = extend_gpu_program(code, items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1)) + marker = write_request(work, code, root.read_bytes(), sa) + dest = work / 'sdwa-f16-readback.bin' + run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + stores = {base + lane * LANE_STRIDE + slot: (slot, want, shift) + for (base,) in fixture.group_offsets(1) + for (lane, slot), (want, shift) in expected.items()} + actual = struct.unpack(f'<{fixture.WORDS}I', dest.read_bytes()) + for index, got in enumerate(actual): + if index in stores: + slot, want, shift = stores[index] + if slot < len(items): + matches = items[slot].matches(got) + elif shift is not None: + mask = 0xffff << shift + matches = (got & ~mask == want & ~mask and + fixture.same_binary16((got & mask) >> shift, (want & mask) >> shift)) + else: + matches = got == want + assert matches, (index, slot, hex(got), hex(want)) + else: + assert got == GUARD, (index, hex(got), hex(GUARD)) + print('native_sdwa_f16 GPU: %d results and %d guards' % (len(stores), fixture.WORDS - len(stores))) + + +if __name__ == '__main__': + items = cases() + check_mutants(items) + items += clamp_cases() + assert len(items) < fixture.STRIDE + code, _ = fixture.program(items) + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2], items, code) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(sys.argv[2], sys.argv[3], items, code) + else: + sys.exit(__doc__) diff --git a/tests/native_sdwa_f16_scalar_check.py b/tests/native_sdwa_f16_scalar_check.py new file mode 100644 index 0000000000..b2af56513a --- /dev/null +++ b/tests/native_sdwa_f16_scalar_check.py @@ -0,0 +1,113 @@ +"""Direct compute binary16 SDWA scalar sources. Use ir DUMPER or gpu STORE_REPLAY SDK.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import f16_packed_model as model +import native_f16_alu_check as fixture +from native_compute_clear_check import write_request +from native_sdwa_f16_check import DWORD, OLD, PAD, PRESERVE, SCALAR, WORD_0, WORD_1, sdwa + +SGPR = 9 +WORDS = {SGPR: 0x44004000, 256 + 1: 0x48003c00, 256 + 2: 0x45004200} +SOURCE_WORDS = {**WORDS, **fixture.INLINE_F16, 128: 0} + + +def instruction(op, unused, left, left_sel, right, right_sel): + def control(source, selector): + return selector | (SCALAR if source < 256 else 0) + + return sdwa(op, WORD_0, unused, control(left, left_sel), control(right, right_sel), + reg0=left & 255, reg1=right & 255) + + +class Case: + dest = 3 + + def __init__(self, op, unused, left, left_sel, right, right_sel): + self.instruction = instruction(fixture.OP_CODE[op], unused, left, left_sel, right, right_sel) + + def half(source, selector): + return model.pick(SOURCE_WORDS[source], selector == WORD_1) + + result = fixture.binary16(op, half(left, left_sel), half(right, right_sel)) + self.want = (OLD & 0xffff0000 if unused == PRESERVE else 0) | result + + def emit(self): + return (fixture.smov(SGPR, WORDS[SGPR]) + + fixture.mov(1, WORDS[257]) + fixture.mov(2, WORDS[258]) + + fixture.mov(self.dest, OLD) + self.instruction) + + +def cases(): + return [ + Case('add', PAD, SGPR, DWORD, 258, WORD_0), + Case('add', PRESERVE, 242, WORD_0, 128, DWORD), + Case('mul', PRESERVE, 257, WORD_0, SGPR, WORD_1), + Case('sub', PAD, 257, WORD_1, SGPR, DWORD), + Case('subrev', PAD, 257, WORD_1, SGPR, WORD_0), + ] + + +def refusals(): + add = fixture.OP_CODE['add'] + return [ + (instruction(add, PAD, 255, WORD_0, 258, WORD_0), 'literal is unavailable in SDWA'), + (instruction(add, PAD, 257, WORD_0, SGPR, WORD_1 | 8), 'invalid SDWA source modifier'), + (instruction(add, PAD, 258, WORD_0, 242, WORD_1), 'unsupported SDWA binary16 inline constant selection'), + # These captured min/max forms also need an arithmetic lowering. + (instruction(0x39, PRESERVE, SGPR, DWORD, 258, WORD_1), 'unimplemented direct SDWA operand profile'), + (instruction(0x3a, PAD, 257, WORD_0, 258, WORD_0), 'unimplemented direct SDWA operand profile'), + ] + + +def run_ir(dumper, items): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + # Isolate each shape so one decode refusal cannot hide another. + for index, case in enumerate(items): + code, _ = fixture.program([case]) + run = fixture.dump(dumper, work, code, f'case-{index}') + assert run.returncode == 0, (index, run.stderr) + stores = fixture.interpret(run.stdout) + assert stores == [(0, case.want)], (index, stores, hex(case.want)) + for index, (words, why) in enumerate(refusals()): + run = fixture.dump(dumper, work, words + [0xbf810000], f'refused-{index}') + assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr) + print(f'native_sdwa_f16_scalar IR: {len(items)} results and {len(refusals())} refusals') + + +def run_gpu(gpu, sdk, items): + code, expected = fixture.program(items) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src, root = work / 'root.hlsl', work / 'root.bin' + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True) + sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1)) + marker = write_request(work, code, root.read_bytes(), sa) + dest = work / 'sdwa-f16-scalar-readback.bin' + run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct']) + if run.returncode == 77: + sys.exit(77) + run.check_returncode() + # The preamble sets EXEC_LO=1. Group IDs 0 and 1 in s5 select + # wave32 records at DWORDs 8 and 136, with contiguous lane-0 results. + stores = {slot: want for offsets in fixture.group_offsets(len(items)) + for slot, want in zip(offsets, expected)} + actual = struct.unpack(f'<{fixture.WORDS}I', dest.read_bytes()) + for index, got in enumerate(actual): + want = stores.get(index, fixture.SENTINEL) + assert got == want, (index, hex(got), hex(want)) + print(f'native_sdwa_f16_scalar GPU: {len(stores)} results and {fixture.WORDS - len(stores)} guards') + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'ir': + run_ir(sys.argv[2], cases()) + elif len(sys.argv) == 4 and sys.argv[1] == 'gpu': + run_gpu(sys.argv[2], sys.argv[3], cases()) + else: + sys.exit(__doc__) diff --git a/tests/native_sdwa_vcc_hi_check.py b/tests/native_sdwa_vcc_hi_check.py new file mode 100644 index 0000000000..4ddb51ce72 --- /dev/null +++ b/tests/native_sdwa_vcc_hi_check.py @@ -0,0 +1,52 @@ +"""Direct wave32 SDWA VOPC compares that write their lane mask to vcc_hi and read it back as a scalar source.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def sdwa_vcc_hi_readback(work, gpu, sdk): + # Each lane owns two dwords. The negated zero class bit is present only in lane zero. + words = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020, + scalar(0x1e, 7, 5, 136), # group byte offset = group.x << 8 + 0x1a << 25 | 8 << 17 | 131, # v8 = local.x << 3 + 0x25 << 25 | 8 << 17 | 8 << 9 | 7, # v8 += group byte offset + vmove(5, 255), 0x20000000, + 0x16 << 25 | 5 << 17 | 5 << 9 | 256, # v5 >>= local.x + 0x7d100af9, 0x0396eb80, # class(-0, BYTE_3(v5)) -> vcc_hi + sop1(3, 14, 107), vmove(9, 14), 0xe0701000, 0x80080908, + 0x1c << 25 | 6 << 17 | 255, 0x100, # v6 = local.x | 0x100 + 0x7d0a0cf9, 0x0086eb6b, # ne(vcc_hi, BYTE_0(v6)) -> vcc_hi + sop1(3, 14, 107), vmove(9, 14), 0xe0701004, 0x80080908, + 0xbf810000] + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | 1 << 20, 0, 0x80 | 5 << 1) # bit 20: wave32 (#2999) + marker = write_request(work, words, (work / "root.bin").read_bytes(), sa) + dest = work / "sdwa-vcc-hi.bin" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + sys.exit(77) + result.check_returncode() + class_mask = sum(1 << lane for lane in range(32) if ((0x20000000 >> lane) >> 24) & (1 << 5)) + ne_mask = sum(1 << lane for lane in range(32) if class_mask != ((lane | 0x100) & 0xff)) + expected = [0x69696969] * 2064 + expected[8:136] = [class_mask, ne_mask] * 64 + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Both wave32 SDWA vcc_hi masks matched in every lane and all guards held.") + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + src, root = work / "root.hlsl", work / "root.bin" + src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, src], check=True) + sdwa_vcc_hi_readback(work, gpu, sdk) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_shift64_check.py b/tests/native_shift64_check.py new file mode 100644 index 0000000000..5fd0eacde7 --- /dev/null +++ b/tests/native_shift64_check.py @@ -0,0 +1,104 @@ +"""Direct compute logical 64-bit shift readback and inline-float refusal.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_mirror_check import vop2 +from native_dpp_quad_check import request +from native_scalar_lds_check import scalar, sop1 + + +AMOUNTS = (0, 1, 31, 32, 33, 63) +SGPR_LOW, SGPR_HIGH = 0x89ABCDEF, 0x01234567 +LITERAL = 0x80000001 +SOURCES = ( + ("inline -1", 193, -1), + ("inline -16", 208, -16), + ("inline 64", 192, 64), + ("inline 1", 129, 1), + ("literal", 255, LITERAL), + ("SGPR pair", 22, (SGPR_HIGH << 32) | SGPR_LOW), +) +SHIFTS = (("right", 0xD7000002), ("left", 0xD6FF0002)) +MASK64 = (1 << 64) - 1 +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +LANES = 64 +OUTPUT_WORDS = 2064 + + +def compute_program(amount, sources=SOURCES): + # Use the quad fixture's descriptor setup and group index. v8 holds the + # byte offset of a lane's two words within a plane of 64 result pairs: 8 bytes per lane, 256 per group. + program = [sop1(3, 20, 4), sop1(3, 21, 128), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1e, 7, 5, 136), vop2(0x1a, 8, 131, 0), vop2(0x25, 8, 7, 8), + sop1(3, 22, 255), SGPR_LOW, sop1(3, 23, 255), SGPR_HIGH] + # Replay's UAV view already starts after the leading guard words. + offset = 0 + for _, source, _ in sources: + for _, opcode in SHIFTS: + program += [opcode, (128 + amount) | (source << 9)] + if source == 255: + program.append(LITERAL) + # buffer_store_dwordx2 v[2:3], v8, s[32:35], 0 offen + program += [0xE0741000 | offset, 0x80080208] + offset += LANES * 8 + return program + [0xBF810000] + + +def controls(cli, sdk, work, root): + marker = request(work, root, compute_program(1, (("inline float", 242, None),))) + output = marker.with_suffix(".cso") + result = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + error = "direct 64-bit shift operand" + assert result.returncode and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + print(error) + return 0 + + +def hardware(replay, sdk, work, root): + # Manual mutants that must fail: zero-extend the negative inline values, + # sign-extend the literal, or swap the SGPR pair's words. + # One source per dispatch: the store's immediate offset is 12 bits. All twelve planes in one dispatch + # would not fit: the ninth starts at 4096, which is the OFFEN bit. + for amount in AMOUNTS: + for source in SOURCES: + marker = request(work, root, compute_program(amount, (source,))) + output = work / "out.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + assert actual[:GUARD_WORDS] == (SENTINEL,) * GUARD_WORDS + start = GUARD_WORDS + name, _, value = source + bits = value & MASK64 + for (direction, _), expected in zip(SHIFTS, (bits >> amount, (bits << amount) & MASK64)): + words = (expected & 0xFFFFFFFF, expected >> 32) + end = start + LANES * 2 + assert actual[start:end] == words * LANES, (name, direction, amount, words, actual[start:end]) + start = end + assert actual[start:] == (SENTINEL,) * (OUTPUT_WORDS - start) + print(f"Shift by {amount}: all 6 sources, both directions and guards matched") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / "root.hlsl" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_signed_forms_check.py b/tests/native_signed_forms_check.py new file mode 100644 index 0000000000..2f5f53b752 --- /dev/null +++ b/tests/native_signed_forms_check.py @@ -0,0 +1,167 @@ +"""v_ashrrev_i64 and v_mad_i32_i24 in the direct compute path (#2991). + + native_signed_forms_check.py controls <compile_dxil> <sdk bin dir> + native_signed_forms_check.py hardware <native_store_replay> <sdk bin dir> + +v_ashrrev_i64 shifts the 64-bit value S1 right arithmetically by S0[5:0]. Its shifted-value rules are those of the +logical 64-bit shifts (tests/native_shift64_check.py), with one difference that gfx2hlsl.py's +i64_words(signed=True) makes: a 32-bit literal is sign-extended, not zero-extended. v_mad_i32_i24 is +sext(S0[23:0]) * sext(S1[23:0]) + S2 modulo 2^32. All words were assembled with LLVM 15.0.7 (clang -cc1as, gfx1013). + +The shift dispatches reuse native_shift64_check.compute_program with the VOP3 opcode of v_ashrrev_i64 (0x301), a +negative SGPR pair (0x89abcdef:01234567), inline -1, -16, 64 and 1 and the literal 0x80000001, for shift amounts +0, 1, 31, 32, 33 and 63. Zero-extended-literal and logical-shift references must differ from the expected words. +The multiply-add dispatch uses, with n = lane + 32 * group, S0 = mul_u32_u24(n, 0x05f3d1) ^ 0xa5800000, +S1 = mul_u32_u24(n, 0x0371) ^ 0x7f9abcde and S2 = mul_u32_u24(n, 0x1001), so bit 23 is set in many factors and +bits above it are not zero. Unsigned and unmasked references must differ. +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import native_shift64_check as S64 +from native_dpp_quad_check import request + +S64.SHIFTS = (('arithmetic', 0xD7010002),) # v_ashrrev_i64 v[2:3], amount, source +S64.SGPR_LOW, S64.SGPR_HIGH = 0x01234567, 0x89ABCDEF +SOURCES = ( + ('inline -1', 193, -1), + ('inline -16', 208, -16), + ('inline 64', 192, 64), + ('inline 1', 129, 1), + ('literal', 255, 0x80000001), + ('SGPR pair', 22, (0x89ABCDEF << 32) | 0x01234567), +) +AMOUNTS = (0, 1, 31, 32, 33, 63) +MASK64 = (1 << 64) - 1 +# s_mov_b32 s20, s4 / s_mov_b32 s21, 0 / s_load_dwordx4 s[32:35], s[20:21], 0x20 / s_lshl_b32 s7, s5, 9 / +# s_lshl_b32 s8, s5, 5 / v_lshlrev_b32 v8, 4, v0 / v_add_nc_u32 v8, s7, v8 / v_add_nc_u32 v9, s8, v0 / +# v_mul_u32_u24 v1, 0x5f3d1, v9 / v_xor_b32 v1, 0xa5800000, v1 / v_mul_u32_u24 v2, 0x371, v9 / +# v_xor_b32 v2, 0x7f9abcde, v2 / v_mul_u32_u24 v3, 0x1001, v9 / v_mad_i32_i24 v4, v1, v2, v3 / +# s_waitcnt lgkmcnt(0) / buffer_store_dword v4, v8, s[32:35], 0 offen / s_endpgm +MAD = ('040394be 800395be 0a0808f4200000fa 0589078f 0585088f 84001034 0710104a 0800124a ff120216d1f30500 ' + 'ff02023a000080a5 ff12041671030000 ff04043adebc9a7f ff12061601100000 040042d501050e04 7fc08cbf ' + '001070e008040880 000081bf') +SENTINEL = 0x69696969 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 + + +def words(text): + out = [] + for h in text.split(): + out += [int.from_bytes(bytes.fromhex(h[i:i + 8]), 'little') for i in range(0, len(h), 8)] + return out + + +def shifted(source, amount, zero_extend_literal=False, logical=False): + name, _, value = source + if name == 'literal' and not zero_extend_literal: + value = value - (1 << 32) if value & 0x80000000 else value + bits = value & MASK64 + signed = bits - (1 << 64) if bits >> 63 else bits + return (bits >> amount if logical else signed >> amount) & MASK64 + + +def mul24(x, y): + return ((x & 0xFFFFFF) * (y & 0xFFFFFF)) & 0xFFFFFFFF + + +def sext24(x): + x &= 0xFFFFFF + return x - (1 << 24) if x & 0x800000 else x + + +def mad_reference(unsigned=False, unmasked=False): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for lane in range(32): + n = lane + 32 * group + a, b, c = mul24(n, 0x05F3D1) ^ 0xA5800000, mul24(n, 0x0371) ^ 0x7F9ABCDE, mul24(n, 0x1001) + if unmasked: + x, y = a, b + elif unsigned: + x, y = a & 0xFFFFFF, b & 0xFFFFFF + else: + x, y = sext24(a), sext24(b) + expected[GUARD_WORDS + (group * 32 + lane) * 4] = (x * y + c) & 0xFFFFFFFF + return expected + + +def compile_ok(cli, sdk, work, root, program): + marker = request(work, root, program) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + return subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, text=True, + check=True).stdout + + +def controls(cli, sdk, work, root): + # The modules, before the GPU run: an arithmetic 64-bit shift (no logical one), and for the multiply-add a + # 24-bit sign extension of each factor, a shift left by 8 followed by an arithmetic shift right by 8. + for source in SOURCES: + dump = compile_ok(cli, sdk, work, root, S64.compute_program(1, (source,))) + assert 'ashr i64' in dump and 'lshr i64 %' in dump and dump.count('ashr i64') == 1, (source[0], dump) + dump = compile_ok(cli, sdk, work, root, words(MAD)) + assert dump.count(', 8') >= 4 and 'ashr i32' in dump and 'mul i32' in dump, dump + changed = {label: any(shifted(s, k, **kw) != shifted(s, k) for s in SOURCES for k in AMOUNTS) + for label, kw in (('zero-extended literal', {'zero_extend_literal': True}), + ('logical shift', {'logical': True}))} + assert all(changed.values()), changed + for label, mutant in (('unsigned factors', mad_reference(unsigned=True)), + ('factors not masked to 24 bits', mad_reference(unmasked=True))): + assert mutant != mad_reference(), label + print('compiled six v_ashrrev_i64 sources and v_mad_i32_i24; the zero-extended-literal, logical, unsigned ' + 'and unmasked references each differ') + return 0 + + +def readback(replay, sdk, work, root, program): + marker = request(work, root, program) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return None + result.check_returncode() + return list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes())) + + +def hardware(replay, sdk, work, root): + for amount in AMOUNTS: + for source in SOURCES: + actual = readback(replay, sdk, work, root, S64.compute_program(amount, (source,))) + if actual is None: + return 77 + expected = shifted(source, amount) + words_ = (expected & 0xFFFFFFFF, expected >> 32) + start = GUARD_WORDS + end = start + S64.LANES * 2 + assert actual[:start] == [SENTINEL] * start + assert actual[start:end] == list(words_) * S64.LANES, (source[0], amount, words_, actual[start:end][:4]) + assert actual[end:] == [SENTINEL] * (OUTPUT_WORDS - end) + print(f'v_ashrrev_i64 by {amount}: all 6 sources and guards matched') + actual = readback(replay, sdk, work, root, words(MAD)) + if actual is None: + return 77 + diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, mad_reference())) if x != y] + assert not diff, diff[:10] + print('v_mad_i32_i24: 64 words of two groups and the guards matched') + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_slot67_wave_size_check.py b/tests/native_slot67_wave_size_check.py new file mode 100644 index 0000000000..d6e3ce1a96 --- /dev/null +++ b/tests/native_slot67_wave_size_check.py @@ -0,0 +1,69 @@ +"""Compare slot 67 wave64 and wave32 lane counts for the same source-built program.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request + + +PROGRAM = ( + 0xBE940304, 0xBE950380, # s[20:21] = UAV table address from s4 + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + 0x8F078805, # s_lshl_b32 s7, s5, 8 (group byte offset) + 0x34100082, # v_lshlrev_b32 v8, 2, v0 (local byte offset) + 0x4A101007, # v_add_nc_u32 v8, s7, v8 + 0xD7650001, 0x000100C1, # v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD7660001, 0x000202C1, # v_mbcnt_hi_u32_b32 v1, -1, v1 + 0xE0701000, 0x80080108, # buffer_store_dword v1, v8, s[32:35], 0 offen + 0xBF810000, # s_endpgm +) +THREADS = 64 +DISPATCH_THREADS = 2 * THREADS # native_store_replay dispatches two groups +GUARD = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, shader], check=True) + # (wave size, threads per group): a wave64 request with a 32-thread group has one guest wave of lanes 0..31. + cases = ((64, 64), (32, 64), (64, 32)) + markers = {} + for wave_size, threads in cases: + z = 1 | (1 << 20 if wave_size == 32 else 0) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), z, 0, 0x8A) + markers[wave_size, threads] = write_request(work, PROGRAM, root.read_bytes(), sa) + + cache, batch = work / "cache", work / "batch" + subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", "--requests", work, batch], + check=True) + for marker in markers.values(): + assert (batch / f"{marker.stem[4:]}.cs.cso").is_file(), marker + + for (wave_size, threads), marker in markers.items(): + output = work / f"wave{wave_size}_{threads}.bin" + result = subprocess.run([replay, sdk, marker, cache, "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = [SENTINEL] * OUTPUT_WORDS + # Each group stores its lane indices at a 256-byte group offset (s_lshl_b32 s7, s5, 8). + for group in range(2): + for tid in range(threads): + expected[GUARD + group * THREADS + tid] = tid % min(wave_size, threads) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (wave_size, index, got, want) + print(f"wave{wave_size}, {threads}-thread groups: {2 * threads} lane indices and buffer guards matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_smem_vcc_check.py b/tests/native_smem_vcc_check.py new file mode 100644 index 0000000000..e32c4ea61a --- /dev/null +++ b/tests/native_smem_vcc_check.py @@ -0,0 +1,50 @@ +"""Direct wave32 SMEM loads with vcc_lo / vcc_hi as the scalar offset and vcc_hi as a destination.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +def vcc_smem_readback(work, gpu, sdk): + source, root = work / "built.hlsl", work / "built.root" + source.write_text('#define SIG "SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + # The raw .sa capture sets bit 20 of dword 4 for wave32. + sa = struct.pack("<7I", 0, 0, 0, 32 | 1 << 16, 1 | 1 << 20, 0, 0x80 | 7 << 1) + words = [sop1(4, 16, 4), sop1(3, 18, 255), 132, sop1(3, 19, 255), 0x31016fac, + sop1(3, 20, 6), sop1(3, 21, 128), 0xf4080000 | 40 << 6 | 10, 0xfa000020, + scalar(0x1e, 106, 7, 130), scalar(0xe, 106, 106, 132), sop1(3, 107, 136), + 0xf4200008 | 30 << 6, 106 << 25 | 4, # s_buffer_load_dword s30, s[16:19], vcc_lo + 0xf4240008 | 32 << 6, 107 << 25 | 20, # s_buffer_load_dwordx2 s[32:33], s[16:19], vcc_hi + 0xf40c0002 | 48 << 6, 107 << 25 | 80, # s_load_dwordx8 s[48:55], s[4:5], vcc_hi + 0xf4200008 | 107 << 6, 107 << 25 | 40, # s_buffer_load_dword vcc_hi, s[16:19], vcc_hi + 0xbf8cc07f, scalar(0x1e, 12, 7, 134), vmove(8, 12), sop1(3, 126, 129)] + for j, sgpr in enumerate((30, 32, 33, *range(48, 56), 107)): + words += [vmove(9, sgpr), 0xe0701000 | 4 * j, 0x800a0908] + marker = write_request(work, words + [0xbf810000], root.read_bytes(), sa) + dest = work / "vcc-smem-readback.bin" + result = subprocess.run([gpu, sdk, marker, work / "cache", "0", dest, "--direct"]) + if result.returncode == 77: + sys.exit(77) + result.check_returncode() + expected = [0x69696969] * 2064 + for group in range(2): + start = 8 + 16 * group + indices = (1 + group, 7, 8, *range(22, 30), 12) + expected[start:start + len(indices)] = [0x51aa0000 + index for index in indices] + actual = struct.unpack("<2064I", dest.read_bytes()) + assert list(actual) == expected, [(i, a, b) for i, (a, b) in enumerate(zip(actual, expected)) if a != b][:10] + print("Wave32 SMEM VCC offsets and destination matched 24 result words and all guards.") + + +def main(gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + vcc_smem_readback(Path(temp), gpu, sdk) + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/tests/native_smem_vcc_wave64_check.py b/tests/native_smem_vcc_wave64_check.py new file mode 100644 index 0000000000..061db04b09 --- /dev/null +++ b/tests/native_smem_vcc_wave64_check.py @@ -0,0 +1,121 @@ +"""Compile and replay direct wave64 scalar loads that use VCC as scalar data.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +THREADS = 64 +LANE_WORDS = 16 +GUARD_WORDS = 8 +OUTPUT_WORDS = 2064 +SENTINEL = 0x69696969 +INPUT_BASE = 0x51AA0000 +EXEC_LO, EXEC_HI = 0x5A5AA5A5, 0xA5A55A5A + + +def program(first_dst=104): + # Use the same root SRV, synthesized byte descriptor and UAV slot as the wave32 fixture. + words = [ + sop1(4, 126, 193), # s_mov_b64 exec, -1 + sop1(4, 16, 4), sop1(3, 18, 255), 132, sop1(3, 19, 255), 0x31016FAC, + sop1(3, 20, 6), sop1(3, 21, 128), 0xF4080000 | 40 << 6 | 10, 0xFA000020, + 0xF4280008 | first_dst << 6, 0xFA000000, # s_buffer_load_dwordx4 s[104:107], s[16:19], 0 + 0xBF8CC07F, + scalar(0x1E, 12, 7, 140), # group.x * 4096 bytes + vop2(0x1A, 8, 134, 0), vop2(0x25, 8, 12, 8), # group byte base + local.x * 64 + sop1(3, 30, 106), # s_mov_b32 s30, vcc_lo + ] + + def store(reg, slot): + return [vmove(9, reg), 0xE0701000 | slot * 4, 0x800A0908] + + for slot, reg in enumerate((104, 105, 30, 107)): + words += store(reg, slot) + words += [ + 0xF40C0002 | 100 << 6, 0xFA000050, # s_load_dwordx8 s[100:107], s[4:5], 80 + 0xBF8CC07F, sop1(3, 30, 107), # s_mov_b32 s30, vcc_hi + ] + for slot, reg in enumerate((*range(100, 107), 30), start=4): + words += store(reg, slot) + words += [ + sop1(3, 106, 132), sop1(3, 107, 136), # scalar byte offsets 4 and 8 + 0xF4200008 | 30 << 6, 106 << 25 | 24, # s_buffer_load_dword s30, s[16:19], vcc_lo + 24 + 0xF4000002 | 31 << 6, 107 << 25 | 32, # s_load_dword s31, s[4:5], vcc_hi + 32 + 0xBF8CC07F, + *store(30, 12), *store(31, 13), + sop1(3, 126, 255), EXEC_LO, sop1(3, 127, 255), EXEC_HI, + 0xF4040002 | 106 << 6, 0xFA000014, # s_load_dwordx2 vcc, s[4:5], 20 + 0xBF8CC07F, + vmove(1, 129), vop2(1, 9, 128, 1), # v_cndmask_b32 v9, 0, v1, vcc + 0xE0701000 | 14 * 4, 0x800A0908, # EXEC-inactive lanes retain the sentinel + 0xBF810000, + ] + return words + + +def request(work, root, first_dst): + # .sa dword 4 bit 20 is clear, so each 64-thread group is one guest wave64. + sa = struct.pack("<7I", 0, 0, 0, THREADS | 1 << 16, 1, 0, 0x80 | 7 << 1) + return write_request(work, program(first_dst), root, sa) + + +def reference(): + expected = [SENTINEL] * OUTPUT_WORDS + vcc = (INPUT_BASE + 5) | ((INPUT_BASE + 6) << 32) + exec_mask = EXEC_LO | (EXEC_HI << 32) + loaded = [INPUT_BASE + index for index in (*range(4), *range(20, 28), 7, 10)] + for group in range(2): + for lane in range(THREADS): + pos = GUARD_WORDS + (group * THREADS + lane) * LANE_WORDS + expected[pos:pos + len(loaded)] = loaded + if exec_mask & (1 << lane): + expected[pos + 14] = (vcc >> lane) & 1 + return expected + + +def controls(tool, sdk, work, root): + for dst, error in ((104, ""), (105, "unsupported scalar memory destination range")): + marker = request(work, root, dst) + output = marker.with_suffix(".cso") + result = subprocess.run([tool, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + if error: + assert result.returncode != 0 and error in result.stderr, (result.stdout, result.stderr) + assert not output.exists(), output + else: + assert result.returncode == 0 and output.exists(), (result.stdout, result.stderr) + return 0 + + +def hardware(tool, sdk, work, root): + marker = request(work, root, 104) + output = work / "out.bin" + result = subprocess.run([tool, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for word, (got, want) in enumerate(zip(actual, reference())): + assert got == want, f"word {word}: got {got:#010x}, expected {want:#010x}" + print("Wave64 SMEM scalar data, both VCC mask halves, and all guards matched.") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source, root = work / "built.hlsl", work / "built.root" + source.write_text('#define SIG "SRV(t0),DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True) + return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes()) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_smov_exec_hi_check.py b/tests/native_smov_exec_hi_check.py new file mode 100644 index 0000000000..9d449d41fd --- /dev/null +++ b/tests/native_smov_exec_hi_check.py @@ -0,0 +1,89 @@ +"""Exercise EXEC_HI scalar moves in the direct compute frontend.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_direct_container_check import compute, words +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +EXEC_LO, EXEC_HI = 126, 127 +END = 0xBF810000 +THREADS = 32 +LANES = 2 * THREADS +LOW_MASK = 0x9 +VALUES = (0x550055, 5, 0x80000002) +GUARD = 0x69696969 +OUTPUT_WORDS = 2064 + + +def mov(dst, src): + return sop1(3, dst, src) + + +def program(): + # Load the output UAV from the table in s4. v8 addresses one dword per lane. + code = [ + mov(20, 4), mov(21, 128), 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, 135), # group.x * 128 + vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8), + mov(EXEC_LO, 128 + LOW_MASK), + mov(EXEC_HI, 255), VALUES[0], mov(12, EXEC_HI), + 0xE0701000, 0x80080008, # store local.x under the narrowed EXEC + mov(EXEC_HI, 128 + VALUES[1]), mov(13, EXEC_HI), + mov(14, 255), VALUES[2], mov(EXEC_HI, 14), mov(15, EXEC_HI), + mov(EXEC_LO, 193), # restore all wave32 lanes for the readbacks + ] + for plane, reg in enumerate((12, 13, 15), start=1): + code.extend((vmove(4, reg), 0xE0701000 | (4 * LANES * plane), 0x80080408)) + return code + [END] + + +def reference(): + masked = tuple(lane if LOW_MASK & (1 << lane) else GUARD for lane in range(THREADS)) + readbacks = tuple(value for value in VALUES for _ in range(LANES)) + return (GUARD,) * 8 + masked * 2 + readbacks + (GUARD,) * (OUTPUT_WORDS - 8 - 4 * LANES) + + +def hardware(replay, sdk, work): + source = work / "root.hlsl" + root = work / "root.bin" + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, THREADS | (1 << 16), 1 | (1 << 20), 0, 0x8A) + marker = write_request(work, program(), root.read_bytes(), sa) + output = work / "readback.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, reference())): + assert got == want, f"word {index}: got {got:#010x}, expected {want:#010x}" + return 0 + + +def wave64(cli, sdk, work): + source = work / "wave64" + output = work / "wave64.cso" + code = words(mov(EXEC_LO, 129), mov(EXEC_HI, 255), VALUES[0], mov(12, EXEC_HI), + mov(EXEC_HI, 128 + VALUES[1]), mov(13, EXEC_HI), + mov(14, 255), VALUES[2], mov(EXEC_HI, 14), mov(15, EXEC_HI), vmove(4, 15), END) + source.write_bytes(compute(code, threads=64, wave32=False)) + subprocess.run([cli, sdk, work / "cache", "gfx1013-container-cs", source, output], check=True) + assert output.read_bytes().startswith(b"DXBC") + return 0 + + +def main(mode, tool, sdk): + with tempfile.TemporaryDirectory() as temp: + return {"hardware": hardware, "wave64": wave64}[mode](tool, sdk, Path(temp)) + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py new file mode 100644 index 0000000000..ad2c8b0d43 --- /dev/null +++ b/tests/native_startup_request_cache_check.py @@ -0,0 +1,489 @@ +"""Startup request consumption and runtime cache publication for compile_dxil (#2933). + +usage: + native_startup_request_cache_check.py controls <compile_dxil> <sdk> + native_startup_request_cache_check.py e2e <compile_dxil> <startup_stream_consumer> <offscreen_check> <sdk> <warp|hardware> +""" +import hashlib +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / "tools" / "startup")) + +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +from native_direct_container_check import patched_pixel, vertex as container_vertex # noqa: E402 +from startup_compute_request_check import DATA, STATE_B, prepare # noqa: E402 +from startup_compute_translate_check import state_a # noqa: E402 +from startup_image_3d_check import root_blob as graphics_const_root_blob # noqa: E402 + +TARGET_MASKS = (0x8002, 0x8003) # PERSP_SAMPLE allocated (v0..v1), PERSP_CENTER (v2..v3), POS_FIXED_PT (v4) +DECOY_MASKS = (0x8002, 0x8002) # PERSP_CENTER (v0..v1), POS_FIXED_PT (v2) +COMPUTE_GROUP = (2, 3, 4) +COMPUTE_RSRC2 = C.USER7 | C.TGID_X | C.TGID_Y | C.TGID_Z | C.tidig(3) + + +def fullscreen_vs_words() -> bytes: + vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src + vop2 = lambda op, dst, src0, vsrc1: op << 25 | dst << 17 | vsrc1 << 9 | src0 + words = [vop2(0x1A, 1, 129, 0), vop2(0x1B, 1, 130, 1), vop2(0x1B, 2, 130, 0)] + for v in (1, 2): + words.extend([vop1(6, v, 256 + v), vop2(8, v, 244, v), vop2(3, v, 243, v)]) + words.extend([vop1(1, 3, 128), vop1(1, 4, 242), 0xF80008CF, 0x04030201, 0xBF810000]) + return struct.pack(f"<{len(words)}I", *words) + + +VS_WORDS = fullscreen_vs_words() + + +def stream_vertex_container() -> bytes: + words = list(struct.unpack(f"<{len(VS_WORDS) // 4}I", VS_WORDS)) + return container_vertex(program=words) + + +def stream_pixel_container(green: bool) -> bytes: + vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src + prefix = [vop1(1, 0, 128), vop1(1, 1, 242)] + channels = 0x01000100 if green else 0x01000001 + return patched_pixel(where=len(prefix), prefix=prefix, export=(0xF800180F, channels)) + + +def ps_words(reg: int) -> bytes: + return struct.pack("<3I", 0xF800180F, reg * 0x01010101, 0xBF810000) + + +def compile_graphics_table_root(sdk: Path, work: Path) -> bytes: + hlsl = work / "graphics_table_root.hlsl" + out = work / "graphics_table_root.bin" + hlsl.write_text('#define RS "DescriptorTable(SRV(t0))"\n', encoding="ascii") + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", out, hlsl], check=True) + return out.read_bytes() + + +def describe_psin(key: int, masks: tuple[int, int]) -> str: + return f"psin1 {key:016x} ena=0x{masks[0]:04x} addr=0x{masks[1]:04x}\n" + + +def put_graphics_request(cache: Path, vs: bytes, ps: bytes, root: bytes, + masks: tuple[int, int] | None = None, + psin_text: str | None = None, + override_key: int | None = None) -> int: + key = G.pipeline_key(vs, ps, root, ps_inputs=masks) if override_key is None else override_key + stem = cache / f"req_{key:016x}" + for ext, blob in ((".b", ps), (".root", root), (".a", vs)): + stem.with_suffix(ext).write_bytes(blob) + text = psin_text if psin_text is not None else (describe_psin(key, masks) if masks is not None else None) + if text is not None: + stem.with_suffix(".psin").write_bytes(text.encode("ascii")) + return key + + +def compute_program_words() -> bytes: + # Same arithmetic and buffer load/store body as Case A (2x3x4 group, 3x2x2 groups), + # reading the placed input SRV from table 1 byte 64 and the placed output UAV from table 1 byte 32. + loads = struct.pack( + "<6I", + 0xBE8A0306, # s_mov_b32 s10, s6 + 0xBE8B0380, # s_mov_b32 s11, 0 + 0xF4080305, 0xFA000040, # s_load_dwordx4 s[12:15], s[10:11], 0x40 + 0xF4080405, 0xFA000020, # s_load_dwordx4 s[16:19], s[10:11], 0x20 + ) + return loads + C.WORDS_A[16:] + + +def compile_compute_root(sdk: Path, work: Path) -> bytes: + hlsl = work / "compute_root.hlsl" + out = work / "compute_root.bin" + hlsl.write_text( + '#define RS "RootConstants(num32BitConstants=2, b0), ' + 'DescriptorTable(SRV(t0, numDescriptors=4), UAV(u0, numDescriptors=4, offset=0))"\n', + encoding="ascii", + ) + subprocess.run([sdk / "dxc.exe", "-T", "rootsig_1_1", "-E", "RS", "-Fo", out, hlsl], check=True) + return out.read_bytes() + + +def put_compute_request(cache: Path, code: bytes, root: bytes, sa: bytes, + override_key: int | None = None) -> int: + desc = struct.pack("<12Q", 0, 0, len(sa), 0, len(STATE_B), 0, len(code), 0, len(DATA), 0, 0, 11) + key = G.compute_key(code, DATA, root, desc, sa, STATE_B) if override_key is None else override_key + for ext, part in ((".desc", desc), (".sa", sa), (".sb", STATE_B), (".data", DATA), (".root", root), (".c67", code)): + (cache / f"req_{key:016x}{ext}").write_bytes(part) + return key + + +def check_controls(cli: Path, sdk: Path) -> int: + repo = HERE.parent + reader_text = (repo / "src" / "shader_compute_request.cpp").read_text(encoding="utf-8") + runtime_text = (repo / "src" / "startup_stubs" / "d3d12_draw.inl").read_text(encoding="utf-8") + reader_revs = re.findall(r'constexpr char revision\[\] = "(x2w-startup-shader-\d+(?:cs)?)";', reader_text) + runtime_gfx = re.search(r'constexpr char revision\[\] = "(x2w-startup-shader-\d+)";', runtime_text) + runtime_cs = re.search(r'constexpr char compute_revision\[\] = "(x2w-startup-shader-\d+cs)";', runtime_text) + assert runtime_gfx and runtime_cs and reader_revs == [runtime_gfx.group(1), runtime_cs.group(1)], ( + reader_revs, runtime_gfx and runtime_gfx.group(1), runtime_cs and runtime_cs.group(1) + ) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + frontend = work / "frontend" + g_root = compile_graphics_table_root(sdk, work) + g_const_root = graphics_const_root_blob() + c_root = compile_compute_root(sdk, work) + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + + # 1. Valid graphics (.psin) and compute (.c67) startup requests publish runtime cache entries in place. + cache = work / "cache" + cache.mkdir() + target_key = put_graphics_request(cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + decoy_key = put_graphics_request(cache, VS_WORDS, ps_words(2), g_const_root, DECOY_MASKS) + cs_key = put_compute_request(cache, c_code, c_root, c_sa) + + g_run = subprocess.run( + [cli, sdk, frontend, "--jobs", "2", "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, text=True, + ) + assert g_run.returncode == 0, (g_run.stdout, g_run.stderr) + assert "requests=2 compiled=2 refused=0" in g_run.stdout, g_run.stdout + + c_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-direct-cs@0", "--requests", cache, cache], + capture_output=True, text=True, + ) + assert c_run.returncode == 0, (c_run.stdout, c_run.stderr) + assert "requests=1 compiled=1 refused=0" in c_run.stdout, c_run.stdout + + for key, masks, expected_ud in ( + (target_key, TARGET_MASKS, "x2w-manifest 1\nud 1\nudsrc 0 rect\n"), + (decoy_key, DECOY_MASKS, "x2w-manifest 1\nud 1\nudsrc 0 rootconst 1 0\n"), + ): + vs_cso = cache / f"{key:016x}.vs.cso" + ps_cso = cache / f"{key:016x}.ps.cso" + psdep = cache / f"{key:016x}.psdep" + manifest = cache / f"{key:016x}.txt" + assert vs_cso.read_bytes().startswith(b"DXBC") + assert ps_cso.read_bytes().startswith(b"DXBC") + assert psdep.read_text(encoding="ascii") == describe_psin(key, masks) + assert manifest.read_text(encoding="ascii").startswith(expected_ud), manifest.read_text(encoding="ascii") + assert manifest.stat().st_mtime_ns >= max(vs_cso.stat().st_mtime_ns, ps_cso.stat().st_mtime_ns) + assert not (cache / f"req_{key:016x}.vs.cso").exists() + assert not (cache / f"req_{key:016x}.ps.cso").exists() + + cs_cso = cache / f"{cs_key:016x}.cs.cso" + cs_manifest = cache / f"{cs_key:016x}.txt" + assert cs_cso.read_bytes().startswith(b"DXBC") + assert cs_manifest.stat().st_mtime_ns >= cs_cso.stat().st_mtime_ns + assert not (cache / f"{cs_key:016x}.cs.hlsl").exists() + assert not (cache / f"req_{cs_key:016x}.cso").exists() + assert cs_manifest.read_text(encoding="ascii") == ( + "x2w-manifest 2\n" + "stage cs\n" + "group 2 3 4\n" + "ud 2\n" + "udsrc 0 rootconst 0 0\n" + "udsrc 1 rootconst 0 1\n" + "srv 0 buf table 1 64\n" + "uav 0 table 1 32\n" + "native 1\n" + ) + assert G.pending_keys(str(cache), skip_failed=False) == [], "published entries not recognised as complete" + + archive = work / "archive" + archive.mkdir() + ps = ps_words(4) + legacy_graphics_key = G.fnv(b"x2w-startup-shader-28") + for part in (VS_WORDS, ps, g_root, b"psin1" + struct.pack("<II", *TARGET_MASKS)): + legacy_graphics_key = G.fnv(part, legacy_graphics_key) + put_graphics_request(archive, VS_WORDS, ps, g_root, TARGET_MASKS, override_key=legacy_graphics_key) + legacy_desc = struct.pack("<12Q", 0, 0, len(c_sa), 0, len(STATE_B), 0, len(c_code), 0, len(DATA), 0, 0, 11) + legacy_compute_key = G.fnv(b"x2w-startup-shader-28cs") + for part in (c_code, DATA, c_root, legacy_desc, c_sa, STATE_B): + legacy_compute_key = G.fnv(part, G.fnv(struct.pack("<Q", len(part)), legacy_compute_key)) + put_compute_request(archive, c_code, c_root, c_sa, override_key=legacy_compute_key) + for profile, key, current_key in ( + ("gfx1013-container-pair", legacy_graphics_key, target_key), + ("gfx1013-direct-cs@0", legacy_compute_key, cs_key), + ): + result = subprocess.run( + [cli, sdk, frontend, profile, "--requests", archive, archive], + capture_output=True, text=True, + ) + assert result.returncode == 0, (profile, result.stdout, result.stderr) + assert "requests=1 compiled=1 refused=0" in result.stdout, result.stdout + assert (archive / f"{key:016x}.txt").read_bytes() == (cache / f"{current_key:016x}.txt").read_bytes() + + # 2. Stale stage change on an already-published .psin entry refuses with diagnostic and withdraws <key>.txt. + (cache / f"req_{target_key:016x}.b").write_bytes(ps_words(2)) + stale_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", cache, cache], + capture_output=True, text=True, + ) + assert stale_run.returncode != 0 and "stale pixel input description" in stale_run.stderr, stale_run.stderr + assert not (cache / f"{target_key:016x}.txt").exists(), "stale .psin kept a loadable manifest" + assert (cache / f"{decoy_key:016x}.txt").is_file(), "unrelated valid entry was disturbed" + + # 3. Fresh-directory negative controls: mismatched keys and malformed/stale/contradictory .psin files. + def expect_graphics_refusal(label: str, setup, expected_stderr: str) -> None: + case_dir = work / label + case_dir.mkdir() + bad_key = setup(case_dir) + res = subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", case_dir, case_dir], + capture_output=True, text=True, + ) + assert res.returncode != 0 and expected_stderr in res.stderr, (label, res.returncode, res.stderr) + assert not list(case_dir.glob("*.txt")), (label, list(case_dir.iterdir())) + assert not (case_dir / f"{bad_key:016x}.vs.cso").exists(), label + assert not (case_dir / f"{bad_key:016x}.ps.cso").exists(), label + + expect_graphics_refusal( + "graphics-key-mismatch", + lambda d: put_graphics_request(d, VS_WORDS, ps_words(0), g_root, override_key=0x0123456789ABCDEF), + "graphics request key mismatch", + ) + expect_graphics_refusal( + "psin-other-pipeline", + lambda d: put_graphics_request( + d, VS_WORDS, ps_words(4), g_root, TARGET_MASKS, psin_text=describe_psin(decoy_key, DECOY_MASKS) + ), + "pixel input description names another pipeline", + ) + expect_graphics_refusal( + "psin-missing-addr", + lambda d: ( + lambda k: put_graphics_request(d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} ena=0x8002\n", override_key=k) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS)), + "pixel input address mask missing from the stream description", + ) + expect_graphics_refusal( + "psin-missing-ena", + lambda d: ( + lambda k: put_graphics_request(d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} addr=0x8003\n", override_key=k) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS)), + "pixel input enable mask missing from the stream description", + ) + expect_graphics_refusal( + "psin-contradictory", + lambda d: ( + lambda k: put_graphics_request( + d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} ena=0x8003 addr=0x8002\n", override_key=k + ) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=(0x8003, 0x8002))), + "contradictory pixel input enable/address masks", + ) + expect_graphics_refusal( + "psin-malformed", + lambda d: ( + lambda k: put_graphics_request( + d, VS_WORDS, ps_words(4), g_root, psin_text=f"psin1 {k:016x} ena=8002 addr=8003\n", override_key=k + ) + )(G.pipeline_key(VS_WORDS, ps_words(4), g_root, ps_inputs=TARGET_MASKS)), + "invalid pixel input description", + ) + expect_graphics_refusal( + "psin-allocated-disabled", + lambda d: put_graphics_request(d, VS_WORDS, ps_words(2), g_root, (0x0002, 0x8002)), + "unsupported pixel entry VGPR 2", + ) + + bad_cs_dir = work / "compute-key-mismatch" + bad_cs_dir.mkdir() + bad_cs_key = put_compute_request(bad_cs_dir, c_code, c_root, c_sa, override_key=cs_key ^ 1) + bad_cs_run = subprocess.run( + [cli, sdk, frontend, "gfx1013-direct-cs@0", "--requests", bad_cs_dir, bad_cs_dir], + capture_output=True, text=True, + ) + assert bad_cs_run.returncode != 0 and "compute request key mismatch" in bad_cs_run.stderr, bad_cs_run.stderr + assert not (bad_cs_dir / f"{bad_cs_key:016x}.txt").exists() + assert not (bad_cs_dir / f"{bad_cs_key:016x}.cs.cso").exists() + + print("native_startup_request_cache controls: current and archived graphics (.psin) + compute (.c67) cache entries and 8 refusal controls passed") + return 0 + + +def fixed_vertex_draw(work: Path, consumer: Path, sdk: Path, backend: str): + from native_direct_container_check import words + cache = work / "fixed-vertex" + interfaces = cache / "interfaces" + interfaces.mkdir(parents=True) + vs_id = [0xd5800000, 255, 0x123, 0xd5800000, 255, 0x456] + ps_id = [0xd5800000, 255, 0x789, 0xd5800000, 255, 0xabc] + # xyz at slot-zero offset 0; export it as position with W=1, and export Z as a varying. + vs = words(*vs_id, 0xbe8c0400, 0x938dff0d, 0x80000, 0xf4080406, 0xfa000000, + 0x4a000002, 0xbf8cc07f, 0xe03c2000, 0x80040100, 0x7e0802f2, + 0xf80008cf, 0x04030201, 0xf8000201, 0x03030303, 0xbf810000) + ps = words(*ps_id, 0xc8100000, 0xc8110001, 0xf800180f, 0x04040404, 0xbf810000) + for name, raw, interface in ( + ("vs", vs, container_vertex(program=vs_id+[0xbf810000], varying=True)), + ("ps", ps, patched_pixel(7, ps_id+[0x7e0002f2], input_address=2, attributes=[(6,0,1,0,0,0,0,2)]))): + (cache/name).write_bytes(raw) + (interfaces/(hashlib.sha256(raw).hexdigest()+".cdxil")).write_bytes(interface) + for rectangle in (False, True): + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=str(sdk), + X2W_TEST_VERTEX_FETCH="1", X2W_TEST_FIXED_COLOR="1") + env.pop("X2W_TEST_FIXED_RECT", None) + if rectangle: + env["X2W_TEST_FIXED_RECT"] = "1" + result = subprocess.run([consumer, cache/"vs", cache/"ps", cache/"root", backend, cache/"pixels", + "slot57", "58:2,5c:1"], env=env, capture_output=True, text=True) + if result.returncode == 77: + return 77 + assert result.returncode == 0 and "ready=1" in result.stderr and "-> drawn;" in result.stderr, result.stderr + assert not re.search(r"x2w-d3d12-debug .* sev=[01] ", result.stderr), result.stderr + if rectangle: + assert "not aliased" in result.stderr and "topology 0x11 -> drawn" in result.stderr, result.stderr + # The rectangle draws four pixels. The indexed call in the list case adds (3,3). + expected = {(x, 0) for x in range(4)} + if not rectangle: + expected.add((3, 3)) + assert (cache/"pixels").read_bytes() == b"".join( + bytes((64,)*4) if (x,y) in expected else bytes((0,0,255,255)) for y in range(4) for x in range(8)) + return 0 + + +def check_e2e(cli: Path, consumer: Path, offscreen: Path, sdk: Path, backend: str) -> int: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if fixed_vertex_draw(work, consumer, sdk, backend) == 77: + return 77 + frontend = work / "frontend" + + # Part 1: .psin VS/PS requests compiled by compile_dxil --requests and executed on GPU. + psin_cache = work / "psin_cache" + psin_cache.mkdir() + g_root = compile_graphics_table_root(sdk, work) + target_key = put_graphics_request(psin_cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + decoy_key = put_graphics_request(psin_cache, VS_WORDS, ps_words(2), g_root, DECOY_MASKS) + wrong_key = put_graphics_request(psin_cache, VS_WORDS, ps_words(2), g_root, (0x8003, 0x8003)) + subprocess.run( + [cli, sdk, frontend, "--jobs", "3", "gfx1013-container-pair", "--requests", psin_cache, psin_cache], + check=True, capture_output=True, text=True, + ) + for label, key, should_match in (("target-v4", target_key, True), ("decoy-v2", decoy_key, True), ("wrong-v2", wrong_key, False)): + vs_cso = psin_cache / f"{key:016x}.vs.cso" + ps_cso = psin_cache / f"{key:016x}.ps.cso" + draw_res = subprocess.run( + [offscreen, backend, "--startup-packed-position", vs_cso, ps_cso], + capture_output=True, text=True, + ) + if draw_res.returncode == 77: + print(draw_res.stdout + draw_res.stderr, end="") + return 77 + if should_match: + assert draw_res.returncode == 0 and "all 91 packed positions matched" in draw_res.stdout, ( + label, draw_res.stdout, draw_res.stderr + ) + else: + assert draw_res.returncode != 0, f"{label} negative control unexpectedly matched" + + # Part 2: Runtime-published graphics request -> compile_dxil --requests -> runtime cache loader draw. + draw_dir = work / "runtime_draw" + draw_cache = draw_dir / "cache" + draw_cache.mkdir(parents=True) + vs_path, ps_path, root_path, pixels_path = (draw_dir / n for n in ("vs", "ps", "root", "pixels")) + vs_path.write_bytes(stream_vertex_container()) + draw_env = dict( + os.environ, + X2W_D3D12_PERMISSIVE="1", + X2W_D3D12_LIST_NOOP="1", + X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="1", + X2W_SHADER_CACHE=str(draw_cache), + ) + drawn_images = [] + for green in (False, True): + ps_path.write_bytes(stream_pixel_container(green)) + subprocess.run([consumer, vs_path, ps_path, root_path], env=draw_env, check=True, capture_output=True, text=True) + subprocess.run( + [cli, sdk, frontend, "gfx1013-container-pair", "--requests", draw_cache, draw_cache], + check=True, capture_output=True, text=True, + ) + res = subprocess.run([consumer, vs_path, ps_path, root_path, backend, pixels_path], + env=draw_env, capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr, end="") + return 77 + assert res.returncode == 0 and "-> drawn;" in res.stderr, (res.returncode, res.stderr[-2000:]) + debug_errors = [ln for ln in res.stderr.splitlines() if "x2w-d3d12-debug " in ln and (" sev=0 " in ln or " sev=1 " in ln)] + assert not debug_errors, debug_errors[0] + color = bytes((0, 255, 0, 255) if green else (255, 0, 0, 255)) + clear = bytes((0, 0, 255, 255)) + expected_pixels = (color * 4 + clear * 4) * 4 + actual_pixels = pixels_path.read_bytes() + assert actual_pixels == expected_pixels, (actual_pixels.hex(), expected_pixels.hex()) + drawn_images.append(actual_pixels) + assert sum(drawn_images[0][i:i + 4] != drawn_images[1][i:i + 4] for i in range(0, 128, 4)) == 16 + + # Part 3: Runtime-published .c67 compute request -> compile_dxil --requests -> runtime cache loader dispatch. + cs_dir = work / "runtime_compute" + cs_cache, cs_env = prepare(cs_dir) + cs_env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1" if backend == "hardware" else "0") + if backend == "hardware": + cs_env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + else: + cs_env.pop("X2W_TEST_DISPATCH_HARDWARE", None) + c_root = compile_compute_root(sdk, work) + (cs_dir / "compute_root").write_bytes(c_root) + cs_env["X2W_TEST_COMPUTE_ROOT"] = str(cs_dir / "compute_root") + c_code = compute_program_words() + c_sa = state_a(COMPUTE_GROUP, COMPUTE_RSRC2) + (cs_dir / "program").write_bytes(c_code) + (cs_dir / "data").write_bytes(DATA) + (cs_dir / "state").write_bytes(c_sa) + out_bin = cs_dir / "out.bin" + + def run_dispatch() -> tuple[list[int], subprocess.CompletedProcess[str]]: + out_bin.unlink(missing_ok=True) + args = [consumer, cs_dir / "vertex", cs_dir / "pixel", cs_dir / "root", "slot67", + cs_dir / "program", cs_dir / "data", cs_dir / "state", "dispatch-heap"] + res = subprocess.run(args, env=dict(cs_env, X2W_TEST_DISPATCH_OUT=str(out_bin)), capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr, end="") + sys.exit(77) + assert res.returncode == 0, (res.returncode, res.stderr[-2500:]) + return list(struct.unpack(f"<{C.WORDS}I", out_bin.read_bytes())), res + + before_words, before_res = run_dispatch() + assert before_words == [C.SENTINEL] * C.WORDS, "dispatch ran before compile_dxil published cache entry" + assert "Dispatch(3, 2, 2) refused: no translation" in before_res.stderr, before_res.stderr[-2000:] + + subprocess.run( + [cli, sdk, frontend, "gfx1013-direct-cs@0", "--requests", cs_cache, cs_cache], + check=True, capture_output=True, text=True, + ) + assert G.pending_keys(str(cs_cache), skip_failed=False) == [] + + after_words, after_res = run_dispatch() + if backend == "hardware" or "Dispatch(3, 2, 2) translated:" in after_res.stderr: + debug_errors = [ + ln for ln in after_res.stderr.splitlines() if "x2w-d3d12-debug " in ln and (" sev=0 " in ln or " sev=1 " in ln) + ] + assert not debug_errors, debug_errors[0] + assert "Dispatch(3, 2, 2) translated:" in after_res.stderr, after_res.stderr[-2000:] + assert after_words == C.expected("A"), "compute dispatch output mismatch" + else: + # Wave-4 WARP builds validate the manifest, load <key>.cs.cso, build tr.root, and stop at [WaveSize(32)] PSO creation. + assert "not translated: pipeline creation failed" in after_res.stderr, after_res.stderr[-2000:] + + print(f"native_startup_request_cache e2e: PASS on {backend} (.psin 91-pixel draws, runtime graphics cache draw, runtime .c67 compute dispatch of {C.WORDS} words)") + return 0 + + +def main(argv: list[str]) -> int: + if len(argv) == 3 and argv[0] == "controls": + return check_controls(Path(argv[1]), Path(argv[2])) + if len(argv) == 6 and argv[0] == "e2e" and argv[5] in ("warp", "hardware"): + return check_e2e(Path(argv[1]), Path(argv[2]), Path(argv[3]), Path(argv[4]), argv[5]) + raise SystemExit(__doc__) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/native_store_replay.cpp b/tests/native_store_replay.cpp new file mode 100644 index 0000000000..e6eb4f1846 --- /dev/null +++ b/tests/native_store_replay.cpp @@ -0,0 +1,259 @@ +#include "desktop_gpu.h" +#include "native_buffer_store_view.h" +#include "native_compute_pipeline.h" +#include "xmem_test_device.h" +#include <chrono> +#include <cstdio> +#include <cstring> +#include <dxgi1_4.h> +#include <filesystem> +#include <fstream> +#include <string_view> +#include <vector> + +using Microsoft::WRL::ComPtr; +namespace fs = std::filesystem; +using namespace x2w; +namespace { +constexpr UINT elements = 2048, guard = 8; +struct Window { + ComPtr<ID3D12Resource> resource, upload, readback; + UINT bytes = 0; + bool write = false; +}; +UINT constant(UINT index) { + constexpr UINT words[]{3,9,37,5}; + return words[index % 4]; +} +UINT format_width(ComputeViewKind kind, UINT bytes) { + if (kind == ComputeViewKind::typed_buffer_srv) return 16; + if (kind == ComputeViewKind::buffer_srv || kind == ComputeViewKind::root_buffer_srv || + kind == ComputeViewKind::raw_buffer_uav) return 4; + return bytes; +} +DXGI_FORMAT typed_format(unsigned bytes, bool half, bool reference) { + const DXGI_FORMAT uints[]{DXGI_FORMAT_R32_UINT,DXGI_FORMAT_R32G32_UINT,DXGI_FORMAT_R32G32B32_UINT,DXGI_FORMAT_R32G32B32A32_UINT}; + const DXGI_FORMAT floats[]{DXGI_FORMAT_R32_FLOAT,DXGI_FORMAT_R32G32_FLOAT,DXGI_FORMAT_R32G32B32_FLOAT,DXGI_FORMAT_R32G32B32A32_FLOAT}; + if (half) return bytes == 2 ? DXGI_FORMAT_R16_FLOAT : bytes == 4 ? DXGI_FORMAT_R16G16_FLOAT : DXGI_FORMAT_R16G16B16A16_FLOAT; + return (reference ? floats : uints)[bytes/4-1]; +} +void report_adapter(ID3D12Device* device) { + const LUID luid = device->GetAdapterLuid(); + std::fprintf(stderr, "adapter_luid=%08lx:%08lx\n", static_cast<unsigned long>(luid.HighPart), luid.LowPart); + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter1> adapter; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || + FAILED(factory->EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter))) || + FAILED(adapter->GetDesc1(&desc))) { + std::fputs("adapter=unavailable via DXGI\n", stderr); + return; + } + std::fprintf(stderr, "adapter=%ls vendor=%04x device=%04x\n", desc.Description, desc.VendorId, desc.DeviceId); + LARGE_INTEGER driver{}; + if (SUCCEEDED(adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver))) + std::fprintf(stderr, "driver=%u.%u.%u.%u\n", HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart)); + else + std::fputs("driver=unavailable via DXGI\n", stderr); +} +} + +// A reference directory supplies independently compiled DXIL and its user-data layout. +// --direct exercises the same direct DXIL frontend used by the runtime. +int wmain(int argc, wchar_t **argv) { + if (argc < 6 || argc > 8) return 2; + try { + const auto mode = argc >= 7 ? std::wstring_view(argv[6]) : std::wstring_view{}; + const bool warp = mode == L"--direct-warp"; + ComPtr<IDXGIAdapter> adapter; + if (warp) { + ComPtr<IDXGIFactory4> factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "DXGI factory"); + const auto warp_hr = factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + if (warp_hr == DXGI_ERROR_NOT_FOUND || warp_hr == DXGI_ERROR_UNSUPPORTED) return 77; + check(warp_hr, "WARP adapter"); + } + ComPtr<ID3D12Device> device; + if (warp) { + // --direct-warp: the WARP adapter chosen above. + const auto device_hr = D3D12CreateDevice(adapter.Get(),D3D_FEATURE_LEVEL_12_0,IID_PPV_ARGS(&device)); + if (device_hr == DXGI_ERROR_UNSUPPORTED) return 77; + check(device_hr, "device"); + } else { + if (GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", nullptr, 0)) { + bool unmatched = false; + device = create_device(false, unmatched, [](IUnknown* adapter, REFIID iid, void** result) { + return D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, iid, result); + }, stderr); + if (!device) { + if (!unmatched) + std::fputs("Unable to enumerate D3D12 hardware adapters\n", stderr); + return 2; + } + } else { + const auto device_hr = D3D12CreateDevice(nullptr,D3D_FEATURE_LEVEL_12_0,IID_PPV_ARGS(&device)); + if (device_hr == DXGI_ERROR_UNSUPPORTED) return 77; + check(device_hr, "device"); + } + report_adapter(device.Get()); + } + ShaderDxilCompiler compiler(argv[1]); + fs::path marker=argv[2], dest=argv[5]; + const bool null_array = mode == L"--direct-null-srv"; + const bool direct = null_array || warp || mode == L"--direct"; + if (argc == 8 && !direct) return 2; + if (direct) { + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(device.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(device.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) || + !waves.WaveOps || waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) { + std::fprintf(stderr, "requires shader model 6.6 with wave32\n"); + return 77; + } + } + const bool reference = argc == 7 && !direct; + auto p=create_native_compute_pipeline(device.Get(),compiler,marker,std::stoul(argv[4]),argv[3],direct); + std::vector<UINT> args(p.constant_words); + UINT index=0; + for (auto &block:p.constants) + for (unsigned j=0;j<block.count;++j) args[index++]=constant(j); + std::vector<unsigned> strides; + if (argc == 8) { + std::ifstream input{fs::path(argv[7])}; + unsigned stride; + while (input >> stride) strides.push_back(stride); + if (!input.eof()) throw std::runtime_error("invalid descriptor stride metadata"); + } + UINT roots[64]{}; + if (reference) { + fs::path base=fs::path(argv[6])/marker.stem().wstring().substr(4); + std::ifstream input(base.wstring()+L".dxil",std::ios::binary); + std::vector<char> dxil{std::istreambuf_iterator<char>(input),{}}; + std::ifstream layout(base.wstring()+L".roots"); + UINT addr, slot, dword; std::string type; + while (layout>>addr>>slot>>type>>dword) { + if (addr>=64 || slot>=16 || (type!="Table" && type!="Constants")) return 2; + roots[addr]= type=="Table" ? slot*256*32 : constant(dword); + } + D3D12_ROOT_PARAMETER param{}; + param.ParameterType=D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues=64; + D3D12_ROOT_SIGNATURE_DESC rd{1,¶m,0,nullptr,D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED}; + ComPtr<ID3DBlob> blob; + check(D3D12SerializeRootSignature(&rd,D3D_ROOT_SIGNATURE_VERSION_1,&blob,nullptr),"reference root"); + p.root.Reset();p.state.Reset(); + check(device->CreateRootSignature(0,blob->GetBufferPointer(),blob->GetBufferSize(),IID_PPV_ARGS(&p.root)),"reference root"); + D3D12_COMPUTE_PIPELINE_STATE_DESC sd{};sd.pRootSignature=p.root.Get();sd.CS={dxil.data(),dxil.size()}; + check(device->CreateComputePipelineState(&sd,IID_PPV_ARGS(&p.state)),"reference PSO"); + } + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,reference?4096u:UINT(p.bindings.size()),D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&heap)),"heap"); + const UINT step=device->GetDescriptorHandleIncrementSize(hd.Type); + ComputeCommands cmd(device.Get(),p.state.Get(),D3D12_COMMAND_LIST_TYPE_DIRECT); + std::vector<Window> windows; + std::vector<IndexedAtomicView> atomic; + for (const auto &b:p.bindings) { + const UINT position=reference?b.root_parameter*256+b.byte_offset/32:UINT(windows.size()); + if (position>=hd.NumDescriptors) return 2; + auto cpu=heap->GetCPUDescriptorHandleForHeapStart();cpu.ptr+=UINT64(position)*step; + Window w;w.write=compute_buffer_uav(b.kind); + const bool vector_bytes = b.kind == ComputeViewKind::raw_vector_srv; + const bool root_bytes = b.kind == ComputeViewKind::root_buffer_srv; + if (!w.write && b.kind!=ComputeViewKind::typed_buffer_srv && b.kind!=ComputeViewKind::buffer_srv && !vector_bytes && !root_bytes) return 2; + const bool raw=root_bytes || vector_bytes || b.kind==ComputeViewKind::buffer_srv || b.kind==ComputeViewKind::raw_buffer_uav; + const bool indexed = b.kind == ComputeViewKind::indexed_atomic_uav; + const UINT stride = indexed && b.byte_offset == 32 ? 16 : + indexed && b.byte_offset == 64 ? 12 : format_width(b.kind,b.required_bytes); + w.bytes=(elements+2*guard)*stride; + w.upload=make_buffer(device.Get(),w.bytes,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ); + void *mapped; + check(w.upload->Map(0,nullptr,&mapped),"seed"); + std::memset(mapped,0x69,w.bytes); + if (!w.write) { + auto *words=reinterpret_cast<UINT*>(static_cast<char*>(mapped)+guard*stride); + constexpr UINT packed[]{0x7fff8000, 0x40008001, 0x007fff81, 0xfc003c00, 0x0001bc00, 0x42987ec5}; + for (UINT j=0;j<elements*stride/4;++j) + words[j]=root_bytes ? 0x51aa0000u+j : vector_bytes ? packed[j%6] : raw ? constant(j) : 0x3f800000u+(b.byte_offset/32)*256+j; + } + w.upload->Unmap(0,nullptr); + if (w.write) { + auto desc=w.upload->GetDesc();desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + w.resource=resource(device.Get(),desc,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_COPY_DEST); + cmd.list->CopyResource(w.resource.Get(),w.upload.Get()); + transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + D3D12_UNORDERED_ACCESS_VIEW_DESC v{}; + v.ViewDimension=D3D12_UAV_DIMENSION_BUFFER;v.Buffer.FirstElement=guard;v.Buffer.NumElements=elements; + v.Format=raw?DXGI_FORMAT_R32_TYPELESS:typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav || + b.kind==ComputeViewKind::packed_d16_x_uav,false); + if(raw)v.Buffer.Flags=D3D12_BUFFER_UAV_FLAG_RAW; + if (indexed) { + if (stride > 4) { + v.Format = DXGI_FORMAT_UNKNOWN; + v.Buffer.StructureByteStride = stride; + } else if (b.byte_offset == 128) { + v.Format = DXGI_FORMAT_R32_TYPELESS; + v.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } + } + auto truncated = v; + IndexedAtomicView shape; + if(!native_buffer_store_view(b,v,w.bytes,&shape) || + native_buffer_store_view(b,truncated,w.bytes-guard*stride-1,&shape)) return 2; + if (indexed) atomic.push_back(shape); + if(reference&&!raw)v.Format=typed_format(stride,b.kind==ComputeViewKind::half_buffer_uav || + b.kind==ComputeViewKind::packed_d16_x_uav,true); + device->CreateUnorderedAccessView(w.resource.Get(),nullptr,&v,cpu); + w.readback=make_buffer(device.Get(),w.bytes,D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + } else { + w.resource=w.upload; + D3D12_SHADER_RESOURCE_VIEW_DESC v{};v.ViewDimension=D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping=D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Format=raw?DXGI_FORMAT_R32_TYPELESS:typed_format(16,false,reference);v.Buffer.FirstElement=guard;v.Buffer.NumElements=elements; + if (root_bytes) { + if (b.required_bytes % 4 || b.required_bytes > elements * 4) return 2; + v.Buffer.NumElements = b.required_bytes / 4; + } + if(raw)v.Buffer.Flags=D3D12_BUFFER_SRV_FLAG_RAW; + auto *source = w.resource.Get(); + if (null_array && b.kind == ComputeViewKind::typed_buffer_srv && b.array_position == 1) { + auto guest = v; + guest.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + auto bad = guest; + bad.Format = DXGI_FORMAT_R8G8B8A8_UINT; + if (x2w_startup::native_null_typed_array_srv(0,0,&guest,sizeof(guest),b.required_bytes,v) || + x2w_startup::native_null_typed_array_srv(18,1,&guest,sizeof(guest),b.required_bytes,v) || + x2w_startup::native_null_typed_array_srv(18,0,&bad,sizeof(bad),b.required_bytes,v) || + x2w_startup::native_null_typed_array_srv(18,0,&guest,sizeof(guest)-1,b.required_bytes,v) || + !x2w_startup::native_null_typed_array_srv(18,0,&guest,sizeof(guest),b.required_bytes,v) || + v.Format != DXGI_FORMAT_R32G32B32A32_UINT || v.Buffer.FirstElement != guard || + v.Buffer.NumElements != elements) return 2; + source = nullptr; + } + device->CreateShaderResourceView(source,&v,cpu); + } + std::printf("%u %u %u %u %u\n", b.root_parameter,b.byte_offset,unsigned(b.kind),stride,w.write); + windows.push_back(std::move(w)); + } + if(reference){ + ID3D12DescriptorHeap* h=heap.Get();cmd.list->SetDescriptorHeaps(1,&h);cmd.list->SetComputeRootSignature(p.root.Get()); + cmd.list->SetComputeRoot32BitConstants(0,64,roots,0); + } else p.bind(cmd.list.Get(),heap.Get(),heap->GetGPUDescriptorHandleForHeapStart(),step,args.data(),atomic, + nullptr,strides); + cmd.list->Dispatch(2,1,1); + for(auto &w:windows) if(w.write) { + transition(cmd.list.Get(),w.resource.Get(),D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE); + cmd.list->CopyResource(w.readback.Get(),w.resource.Get()); + } + cmd.submit_and_wait(device.Get());check(device->GetDeviceRemovedReason(),"completion"); + std::ofstream out(dest,std::ios::binary); + for(auto &w:windows)if(w.write){ + void *mapped;check(w.readback->Map(0,nullptr,&mapped),"readback"); + out.write(static_cast<const char*>(mapped),w.bytes);w.readback->Unmap(0,nullptr); + } + return out.good()?0:1; + } catch(const std::exception &e){std::fprintf(stderr,"%s\n",e.what());return 1;} +} diff --git a/tests/native_store_replay_adapter_check.py b/tests/native_store_replay_adapter_check.py new file mode 100644 index 0000000000..3a985ea092 --- /dev/null +++ b/tests/native_store_replay_adapter_check.py @@ -0,0 +1,23 @@ +"""Verify that explicit hardware adapter filters cannot fall back to the default.""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + output = work / 'readback.bin' + for wanted, diagnostic in ( + ('no adapter has this name', 'No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER='), + ('x' * 128, 'XBOX2WINDOWS_ADAPTER is longer than 127 characters'), + ): + env = dict(os.environ, XBOX2WINDOWS_ADAPTER=wanted) + # The runner must reject the filter before touching any shader inputs. + run = subprocess.run([sys.argv[1], work / 'sdk', work / 'request', work / 'cache', + '0', output, '--direct'], env=env, capture_output=True, text=True, timeout=10) + assert run.returncode == 2 and diagnostic in run.stderr, (run.returncode, run.stdout, run.stderr) + assert not run.stdout and not output.exists(), run.stdout +print('Unmatched and overlong adapter filters were rejected before replay') diff --git a/tests/native_uav_slots_check.py b/tests/native_uav_slots_check.py new file mode 100644 index 0000000000..f4598c602c --- /dev/null +++ b/tests/native_uav_slots_check.py @@ -0,0 +1,51 @@ +"""Check the DXIL shader flag for more than 8 UAV slots in direct compute. + +DXC sets flag 0x8000 when a module declares more than 8 UAV slots, and the validator +refuses a module whose declared flags differ ("Flags must match usage"). Each program +stores to N buffer descriptors read from one table, so the module declares N UAVs. +8 UAVs must compile without the flag (the negative control); 9 must compile with it. +""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from native_direct_container_check import compute, words + + +def program(uavs): + code = [0xBEFE03C1, 0xBE810380] # s_mov_b32 exec_lo, -1; s_mov_b32 s1, 0 + for k in range(uavs): + # s_load_dwordx4 s[4+4k:7+4k], s[0:1], 32*k (table entries are 32-byte aligned) + code += [0xF4080000 | (4 + 4 * k) << 6, 0xFA000000 | 32 * k] + code += [ + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + (26 << 25) | (5 << 17) | 130, # v_lshlrev_b32 v5, 2, v0 + ] + for k in range(uavs): + # buffer_store_dword v0, v5, s[4+4k:7+4k], 0 offen + code += [0xE0701000, 0x80000005 | (1 + k) << 16] + code.append(0xBF810000) # s_endpgm + return compute(words(*code), table=True) + + +def main(cli, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + for uavs in (8, 9): + source = work / f'uav{uavs}.c67' + source.write_bytes(program(uavs)) + shader = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=60) + declared = len(re.findall(r'^u\d+ ', run.stdout, re.M)) + assert run.returncode == 0 and shader.is_file(), (uavs, run.stdout, run.stderr) + assert declared == uavs, (uavs, declared, run.stdout) + print(f'{uavs} UAVs: compiled and validated') + + +if __name__ == '__main__': + if len(sys.argv) != 3: + sys.exit('usage: native_uav_slots_check.py COMPILE_DXIL DXC_BIN_DIR') + main(*sys.argv[1:]) diff --git a/tests/native_v_xnor_b32_check.py b/tests/native_v_xnor_b32_check.py new file mode 100644 index 0000000000..37cbe91b44 --- /dev/null +++ b/tests/native_v_xnor_b32_check.py @@ -0,0 +1,120 @@ +"""Direct compute v_xnor_b32 (VOP2, VOP2 literal, VOP3A, and VOP2 SDWA).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_dpp_quad_check import request + +MASK = 0xFFFFFFFF +SENTINEL = 0x69696969 + +CASES = ( + (0x00000000, 0x00000000), # identical zeros -> 0xFFFFFFFF + (0xFFFFFFFF, 0xFFFFFFFF), # identical ones -> 0xFFFFFFFF + (0xFFFFFFFF, 0x00000000), # complementary -> 0x00000000 + (0xAAAAAAAA, 0x55555555), # alternating complements -> 0x00000000 + (0x12345678, 0x9ABCDEF0), # general 32-bit pattern (byte0=0x78 positive) + (0x12345680, 0x8000FF7F), # byte0=0x80 sign-extends to 0xFFFFFF80 in SDWA + (0x00FF00FF, 0xF0F0F0F0), # byte0=0xFF sign-extends to 0xFFFFFFFF in SDWA + (0x76543210, 0x76543210), # identical non-trivial -> 0xFFFFFFFF (VOP2/VOP3A) +) + + +def v_mov_lit(vdst, lit): + return [0x7E0002FF | ((vdst & 0xFF) << 17), lit & MASK] + + +def vop2_xnor(vdst, src0, vsrc1): + return (0x1E << 25) | ((vdst & 0xFF) << 17) | ((vsrc1 & 0xFF) << 9) | (src0 & 0x1FF) + + +def vop3_xnor(vdst, src0, src1): + return [0xD4000000 | (0x11E << 16) | (vdst & 0xFF), (src0 & 0x1FF) | ((src1 & 0x1FF) << 9)] + + +def vop2_xnor_sdwa(vdst, vsrc0, vsrc1, dst_sel=6, dst_unused=0, src0_ctrl=0x08, src1_ctrl=0x04): + ext = ((vsrc0 & 0xFF) | ((dst_sel & 7) << 8) | ((dst_unused & 3) << 11) | + ((src0_ctrl & 0xFF) << 16) | ((src1_ctrl & 0xFF) << 24)) + return [vop2_xnor(vdst, 249, vsrc1), ext] + + +def program(): + code = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, + 0x8F078C05, 0x34100087, 0x4A101007, 0xBF8CC07F] + for ci, (a, b) in enumerate(CASES): + code += v_mov_lit(2, a) + v_mov_lit(3, b) + # 0: VOP2 VGPR + VGPR + code += [vop2_xnor(4, 258, 3), 0xE0701000 | (4 * (ci * 4 + 0)), 0x80080408] + # 1: VOP2 literal + VGPR + code += [vop2_xnor(4, 255, 3), a, 0xE0701000 | (4 * (ci * 4 + 1)), 0x80080408] + # 2: VOP3A VGPR + VGPR + code += vop3_xnor(4, 258, 259) + [0xE0701000 | (4 * (ci * 4 + 2)), 0x80080408] + # 3: VOP2 SDWA (src0=SEXT(BYTE_0), src1=WORD_0, dst=DWORD) + code += vop2_xnor_sdwa(4, 2, 3) + [0xE0701000 | (4 * (ci * 4 + 3)), 0x80080408] + return code + [0xBF810000] + + +def xnor32(a, b, omit_invert=False): + x = (a ^ b) & MASK + return x if omit_invert else (~x) & MASK + + +def sext8(v): + b = v & 0xFF + return (b - 0x100) & MASK if (b & 0x80) else b + + +def reference(omit_invert=False): + words = [SENTINEL] * 8 + for _lane in range(64): + for a, b in CASES: + plain = xnor32(a, b, omit_invert=omit_invert) + sdwa = xnor32(sext8(a), b & 0xFFFF, omit_invert=omit_invert) + words.extend((plain, plain, plain, sdwa)) + return words + [SENTINEL] * 8 + + +def controls(cli, sdk, work, root): + marker = request(work, root, program()) + output = marker.with_suffix('.cso') + result = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker, output], + capture_output=True, text=True) + assert result.returncode == 0 and output.is_file(), (result.stdout, result.stderr) + dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', output], capture_output=True, + text=True, check=True).stdout + assert 'xor i32 ' in dump and ('-1' in dump or '4294967295' in dump), dump + assert reference() != reference(omit_invert=True) + print('v_xnor_b32 DXIL verified; xor-without-invert control differs') + return 0 + + +def hardware(replay, sdk, work, root): + marker = request(work, root, program()) + output = work / 'out.bin' + result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct']) + if result.returncode == 77: + return 77 + result.check_returncode() + expected = reference() + actual = struct.unpack(f'<{len(expected)}I', output.read_bytes()) + mismatch = next((i for i, (a, e) in enumerate(zip(actual, expected)) if a != e), None) + if mismatch is not None: + raise AssertionError(f'word {mismatch}: got {actual[mismatch]:08x}, expected {expected[mismatch]:08x}') + print('v_xnor_b32: 2048 result words and 16 guards matched') + return 0 + + +def main(mode, executable, sdk): + with tempfile.TemporaryDirectory(prefix='x2w_native_v_xnor_b32_') as temp: + work = Path(temp) + shader = work / 'root.hlsl' + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + root = work / 'root.bin' + subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True) + return (controls if mode == 'controls' else hardware)(executable, sdk, work, root.read_bytes()) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/tests/native_vopc_cmp64_check.py b/tests/native_vopc_cmp64_check.py new file mode 100644 index 0000000000..318086a234 --- /dev/null +++ b/tests/native_vopc_cmp64_check.py @@ -0,0 +1,158 @@ +"""Wave32 readback of direct compute 64-bit integer comparisons.""" +import operator +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +ZERO, LITERAL, NEG_ONE = 128, 255, 193 +VCC_LO, EXEC_LO, SDST = 106, 126, 14 +LANES, GROUPS, GUARD_WORDS, OUTPUT_WORDS = 32, 2, 8, 2064 +MASK32, SENTINEL, OLD_VCC = 0xFFFFFFFF, 0x69696969, 0xAAAAAAAA +PREDICATES = { + "lt": (1, operator.lt), "eq": (2, operator.eq), "le": (3, operator.le), + "gt": (4, operator.gt), "ne": (5, operator.ne), "ge": (6, operator.ge), +} + +# Every case must fail on main at the measured compare with "direct comparison width". +CASES = ( + ("ne", True, "e32", "pair"), + ("eq", True, "e32", "pair"), + ("lt", True, "e32", "sign"), + ("lt", False, "e32", "sign"), + ("eq", True, "e32", "inline"), + ("eq", False, "e64", "inline"), + ("le", True, "e64", "pair"), + ("gt", False, "e64", "sign"), + ("ge", False, "e64", "pair"), + ("ne", True, "cmpx", "pair"), +) + + +def vopc(op, src0, vgpr): + return 0x7C000000 | op << 17 | vgpr << 9 | src0 + + +def program(predicate, signed, form, inputs): + # group.x is s5 (IDs 0 and 1), and local.x is v0 (IDs 0 through 31). + # Byte address = 32 + 16 * (32 * group.x + local.x). + # Readback word index = byte address / 4, including the 8-word guard. + words = [ + sop1(3, EXEC_LO, NEG_ONE), + sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF4080000 | 32 << 6 | 10, 0xFA000020, + scalar(0x1E, 7, 5, 137), vop2(0x1A, 8, 132, 0), vop2(0x25, 8, 7, 8), + scalar(0, 10, 5, 135), vmove(6, 256), # s10 = group.x + 7, v6 = local.x + ] + src0, literal = 10, None + if inputs == "pair": + words += [scalar(0, 11, 5, 129), vmove(7, 11)] + elif inputs == "sign": + words += [sop1(3, 11, ZERO), scalar(0x1E, 12, 5, 159), vmove(7, 12)] + else: + src0 = NEG_ONE if inputs == "inline" else LITERAL + low = MASK32 if inputs == "inline" else 0x80000001 + literal = low if inputs == "literal" else None + words += [ + vmove(6, LITERAL), low, vmove(9, NEG_ONE), + vopc(0xC4, 10, 0), # vcc = group.x + 7 > local.x + vop2(1, 7, ZERO, 9), # high word = 0xffffffff on selected lanes + ] + + words += [sop1(3, VCC_LO, LITERAL), OLD_VCC] + opcode = (0xA0 if signed else 0xE0) + PREDICATES[predicate][0] + if form == "e64": + words += [0xD4000000 | opcode << 16 | SDST, src0 | (256 + 6) << 9] + else: + words.append(vopc(opcode + (0x10 if form == "cmpx" else 0), src0, 6)) + if literal is not None: + words.append(literal) + + if form == "cmpx": + words += [sop1(3, SDST, EXEC_LO), sop1(3, EXEC_LO, NEG_ONE)] + dst = VCC_LO if form == "e32" else SDST + words += [ + vmove(2, dst), vmove(9, 170), + vop2(1, 4, 145, 9), # select on VCC before copying an explicit result + ] + if dst != VCC_LO: + words.append(sop1(3, VCC_LO, dst)) + words += [ + vop2(1, 3, 145, 9), vop2(0x16, 5, 132, 8), + 0xE0781000, 0x80080208, 0xBF810000, + ] + return words + + +def reference(predicate, signed, form, inputs): + def integer(bits): + return bits - (1 << 64) if signed and bits >> 63 else bits + + expected = [SENTINEL] * OUTPUT_WORDS + compare = PREDICATES[predicate][1] + for group in range(GROUPS): + pivot = group + 7 + conditions = [] + for lane in range(LANES): + if inputs == "pair": + high = (group + 1) << 32 + lhs, rhs = high | pivot, high | lane + elif inputs == "sign": + lhs, rhs = pivot, (group << 63) | lane + else: + low = MASK32 if inputs == "inline" else 0x80000001 + # An inline constant is sign-extended to 64 bits for both i64 and u64. + lhs = (MASK32 << 32) | low + rhs = (MASK32 << 32 if lane < pivot else 0) | low + conditions.append(compare(integer(lhs), integer(rhs))) + mask = sum(bit << lane for lane, bit in enumerate(conditions)) + for lane, bit in enumerate(conditions): + item = group * LANES + lane + index = GUARD_WORDS + 4 * item + old_bit = bit if form == "e32" else (OLD_VCC >> lane) & 1 + expected[index:index + 4] = [mask, 42 if bit else 17, 42 if old_bit else 17, item] + return tuple(expected) + + +def main(replay, sdk): + # The request selects wave32 with .sa dword 4 bit 20. + sa = struct.pack("<7I", 0, 0, 0, LANES | 1 << 16, 1 | 1 << 20, 0, 0x8A) + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source, root = work / "root.hlsl", work / "root.bin" + source.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True) + for case in CASES: + marker = write_request(work, program(*case), root.read_bytes(), sa) + output = work / "readback.bin" + result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"], + capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, result.stderr) + return 77 + assert result.returncode == 0, (case, result.stdout, result.stderr) + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = reference(*case) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (case, index, hex(got), hex(want)) + print(f"{case}: masks, lane selects, addresses and guards matched") + # A 32-bit literal on a 64-bit integer compare stays refused. + for signed in (True, False): + marker = write_request(work, program("eq", signed, "e32", "literal"), root.read_bytes(), sa) + result = subprocess.run([replay, sdk, marker, work / "cache", "0", work / "refused.bin", "--direct"], + capture_output=True, text=True) + assert result.returncode != 0 and "direct 64-bit integer comparison operand" in result.stdout + result.stderr, ( + result.stdout, result.stderr) + print("literal sources refused") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wave64_exec_salu_check.py b/tests/native_wave64_exec_salu_check.py new file mode 100644 index 0000000000..854e520b09 --- /dev/null +++ b/tests/native_wave64_exec_salu_check.py @@ -0,0 +1,127 @@ +"""Compile and replay slot 67 scalar EXEC operands in both wave models.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_scalar_lds_check import scalar, sop1, vmove + + +BCNT1_B64, BFM_B64 = 0x10, 0x25 +VCC, EXEC, ZERO, NEG_ONE = 106, 126, 128, 193 +COUNT_ERROR = "invalid s_bcnt1_i32_b64 source" +BFM_ERROR = "invalid s_bfm_b64 destination" +GROUP_STRIDE_WORDS = 128 +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +SENTINEL = 0x69696969 +END = 0xBF810000 + + +def request(work, root, wave_size, threads, words): + z = 1 | (1 << 20 if wave_size == 32 else 0) + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), z, 0, 0x8A) + return write_request(work, words, root, sa) + + +def program(wave_size, operation): + # s4 is the UAV table and s5 is group.x. v0 is local.x. + # Replay dispatches groups 0 and 1. The byte address is 512 * group.x + 4 * local.x. + if wave_size == 64: + words = [sop1(4, EXEC, NEG_ONE)] + else: + # Explicitly enable all 32 lanes and seed the tracked upper word. + words = [sop1(3, EXEC, NEG_ONE), sop1(3, EXEC + 1, ZERO + 1)] + words += [ + sop1(3, 20, 4), sop1(3, 21, ZERO), + 0xF408080A, 0xFA000020, # s_load_dwordx4 s[32:35], s[20:21], 0x20 + scalar(0x1E, 7, 5, ZERO + 9), # s_lshl_b32 s7, s5, 9 + 0x34100082, # v_lshlrev_b32 v8, 2, v0 + 0x4A101007, # v_add_nc_u32 v8, s7, v8 + ] + if operation == "count": + words += [ + 0x36040083, # v_and_b32 v2, 3, v0 + 0x7DA40480, # v_cmpx_eq_u32 0, v2 + 0x7DAA00A0, # v_cmpx_ne_u32 32, v0 + sop1(BCNT1_B64, 24, EXEC), + vmove(1, 24), + ] + data = 1 + else: + width, offset = (16, 0) if operation == "lower" else (32, 32) + words.append(scalar(BFM_B64, EXEC, ZERO + width, ZERO + offset)) + data = 0 + return words + [0xE0701000, 0x80080008 | data << 8, END] + + +def expected_words(wave_size, threads, operation): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for local in range(threads): + lane = local % wave_size + word = GUARD_WORDS + group * GROUP_STRIDE_WORDS + local + if operation == "count" and local % 4 == 0 and local != 32: + # Wave64 loses lane 32 in the first guest wave only. Wave32 + # counts eight lower bits and the explicitly set EXEC_HI bit. + expected[word] = 9 if wave_size == 32 else 15 if local < 64 else 16 + elif operation == "lower" and lane < 16: + expected[word] = local + elif operation == "upper" and lane >= 32: + expected[word] = local + return expected + + +def compile_request(cli, sdk, cache, marker): + output = marker.with_suffix(".cs.cso") + result = subprocess.run([cli, sdk, cache, "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True) + return output, result + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root_file = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, shader], check=True) + root = root_file.read_bytes() + cache = work / "cache" + cases = [(64, threads, op) for threads in (64, 128) for op in ("count", "lower", "upper")] + cases.append((32, 32, "count")) + positives = [] + for wave_size, threads, op in cases: + marker = request(work, root, wave_size, threads, program(wave_size, op)) + output, result = compile_request(cli, sdk, cache, marker) + assert result.returncode == 0 and output.is_file(), ( + wave_size, threads, op, result.stdout, result.stderr) + positives.append((wave_size, threads, op, marker)) + + for instruction, error in ( + (sop1(BCNT1_B64, 24, VCC), COUNT_ERROR), + (scalar(BFM_B64, VCC, ZERO + 16, ZERO), BFM_ERROR), + (sop1(BCNT1_B64, 24, 23), COUNT_ERROR), + ): + marker = request(work, root, 64, 64, [instruction, END]) + output, result = compile_request(cli, sdk, cache, marker) + assert result.returncode and error in result.stderr, (error, result.stdout, result.stderr) + assert not output.exists(), output + + for wave_size, threads, op, marker in positives: + output = work / f"wave{wave_size}_{threads}_{op}.bin" + result = subprocess.run([replay, sdk, marker, cache, "0", output, "--direct"]) + if result.returncode == 77: + return 77 + result.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + expected = expected_words(wave_size, threads, op) + for index, (got, want) in enumerate(zip(actual, expected)): + assert got == want, (wave_size, threads, op, index, hex(got), hex(want)) + print(f"wave{wave_size}, {threads} threads, {op}: both groups and guards matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wave_request_check.py b/tests/native_wave_request_check.py new file mode 100644 index 0000000000..cdab046316 --- /dev/null +++ b/tests/native_wave_request_check.py @@ -0,0 +1,258 @@ +"""Exercise the C++ frontend with a source-assembled two-wave request.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request + + +def sdwa_fixtures(cli_args, gpu, sdk, work, root, sa): + def xor(dst, lhs, rhs, sel0, sel1, dest=6, unused=0, sext0=False): + return [(0x1d << 25) | (dst << 17) | (rhs << 9) | 249, + lhs | (dest << 8) | (unused << 11) | (sel0 << 16) | (int(sext0) << 19) | (sel1 << 24)] + + setup = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0xd7460008, 12 | (133 << 9) | (256 << 18), 0x7e12020d, + 0xe0042000, 0x80080208, # load v2, v3 from element x + 0x7e000200 | (20 << 17) | 258, 0x7e000200 | (21 << 17) | 259, + ] + finish = [] + for reg, low in [(20, 2), (21, 4)]: + # Store both halves exactly as floats, including NaN-shaped integer results. + finish += [(0x1b << 25) | (low << 17) | (reg << 9) | 255, 65535, + (0x16 << 25) | ((low + 1) << 17) | (reg << 9) | 144] + for reg in range(2, 6): + finish.append(0x7e000000 | (reg << 17) | (6 << 9) | (256 + reg)) + finish += [0xf0200f08, (10 << 16) | (2 << 8) | 8, 0xbf810000] + cases = [ + ("sdwa-alias", xor(20, 20, 20, 5, 6) + xor(21, 3, 2, 2, 1), False), + ("sdwa-preserve", xor(20, 2, 3, 2, 6, sext0=True) + xor(21, 2, 21, 5, 6, 1, 2), False), + ("sdwa-sext", xor(20, 2, 3, 2, 6, sext0=True) + xor(21, 2, 21, 5, 6, 1, 1), False), + ("sdwa-alias", xor(20, 20, 20, 4, 6) + xor(21, 3, 2, 2, 1), True), + ("sdwa-preserve", xor(20, 2, 3, 2, 6, sext0=True) + xor(21, 2, 21, 5, 6, 1, 0), True), + ("sdwa-class", [ + 0x7e000000 | (20 << 17) | (0x65 << 9) | 277, # swap v20 and v21 + 0x7c000000 | (0x88 << 17) | (3 << 9) | 249, 0x03968e80, # class(-0, byte3(v3)) -> s14 + 0xbeea030e, # vcc_lo = s14 + (1 << 25) | (21 << 17) | (21 << 9) | 276, # choose swapped v20 or v21 + ], False), + ] + for mode, operations, mutant in cases: + marker = write_request(work, setup + operations + finish, root, sa) + result = subprocess.run([gpu, sdk, marker, work / "cache", mode], text=True, capture_output=True) + print(mode, "mutant" if mutant else "reference", result.stdout.strip(), flush=True) + assert result.returncode == int(mutant), (result.stdout, result.stderr) + assert ("differing_components=0 " in result.stdout) != mutant + invalid = write_request(work, setup + xor(20, 2, 3, 7, 6) + finish, root, sa) + rejected = subprocess.run([*cli_args, invalid, work / "invalid.cso"], capture_output=True, text=True) + assert rejected.returncode and "SDWA modifiers" in rejected.stderr and not (work / "invalid.cso").exists() + + +def raw_offset_fixtures(cli_args, gpu, sdk, work, root, sa): + def move(dst, src): + return 0x7e000200 | (dst << 17) | src + + def load(op, dst, addr, offset=0): + return [0xe0001000 | (op << 18) | offset, 0x80080000 | (dst << 8) | addr] + + setup = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0xd7460008, 12 | (133 << 9) | (256 << 18), move(9, 13), + 0xd746000a, 13 | (134 << 9) | (264 << 18), # i = group.y * 64 + x + (0x1a << 25) | (20 << 17) | (10 << 9) | 131, # byte offset = i << 3 + ] + finish = [0x7e000000 | (dst << 17) | (6 << 9) | (256 + src) + for dst, src in zip(range(2, 6), (20, 24, 25, 10))] + finish += [0xf0200f08, (10 << 16) | (2 << 8) | 8, 0xbf810000] + cases = [ + ("raw-offset", [move(24, 276)], load(0x0d, 24, 24), 52, False), + ("raw-offset", [move(25, 276)], load(0x0d, 24, 25), 52, False), + ("raw-edge", [move(24, 255), (2 * 2048 + 15) * 4], load(0x0d, 24, 24), 52, False), + # First word overwrites v24; a second instruction now uses the wrong pair's in-bounds address. + ("raw-offset", [move(24, 276)], load(0x0c, 24, 24) + load(0x0c, 25, 24, 4), 52, True), + ("raw-offset", [move(24, 276)], load(0x0d, 24, 24), 0, True), + ("raw-three", [move(26, 276)], load(0x0f, 24, 26), 52, False), + ("raw-four", [move(27, 276)], load(0x0e, 24, 27), 52, False), + ("raw-math", [move(24, 276)], load(0x0d, 24, 24), 52, False), + # Dword accesses ignore the low two bits after adding the immediate. + ("raw-offset", [(0x25 << 25) | (20 << 17) | (20 << 9) | 131, move(24, 276)], + load(0x0d, 24, 24), 52, False), + ] + for mode, addr, pair, offset, mutant in cases: + tail = finish + if mode in ("raw-three", "raw-four"): + registers = (24, 25, 26, 27 if mode == "raw-four" else 20) + tail = [0x7e000000 | (dst << 17) | (6 << 9) | (256 + src) + for dst, src in zip(range(2, 6), registers)] + finish[4:] + elif mode == "raw-math": + tail = finish[:4] + [(8 << 25) | (2 << 17) | (5 << 9) | 255, 0x3e800000, + 0x7e000000 | (2 << 17) | (0x36 << 9) | 258, + 0x7e000000 | (5 << 17) | (0x0b << 9) | 280] + finish[4:] + words = setup + addr + load(0x0c, 20, 20, offset) + pair + tail + marker = write_request(work, words, root, sa) + run = subprocess.run([gpu, sdk, marker, work / "cache", mode], capture_output=True, text=True) + print(mode, "mutant" if mutant else "reference", run.stdout.strip(), flush=True) + assert run.returncode == int(mutant), (run.stdout, run.stderr) + expected = 2048 if mutant else 0 + assert f"differing_components={expected} " in run.stdout + # Select a different 32-byte descriptor for each of the two X workgroups. + # Both vector loads share the descriptor. Clobber its source index before either load. + def scalar(op, dst, a, b): + return 0x80000000 | (op << 23) | (dst << 16) | (b << 8) | a + + table_load = 0xf4080000 | (32 << 6) | 10 + for flip in (0, 1): + selector = [scalar(0, 28, 12, 128 + flip), scalar(0x0e, 28, 28, 129), scalar(0x1e, 28, 28, 133)] + words = (setup[:4] + selector + [table_load, (28 << 25) | 64, 0xbe9c0380] + setup[6:] + + [move(24, 276)] + load(0x0c, 20, 20, 52) + load(0x0d, 24, 24) + finish) + marker = write_request(work, words, root, sa) + run = subprocess.run([gpu, sdk, marker, work / "cache", "indexed"], capture_output=True, text=True) + print("indexed", "flipped" if flip else "reference", run.stdout.strip(), flush=True) + assert run.returncode == flip and f"differing_components={6144 * flip} " in run.stdout, (run.stdout, run.stderr) + for change, value in ((0, 0xbe94030a), (8, (28 << 25) | 512)): + invalid_words = words.copy() + invalid_words[change] = value + marker = write_request(work, invalid_words, root, sa) + run = subprocess.run([*cli_args, marker, work / "invalid-span.cso"], text=True, capture_output=True) + assert run.returncode and not (work / "invalid-span.cso").exists(), run.stdout + invalid = write_request(work, setup + load(0x0d, 255, 20) + finish, root, sa) + result = subprocess.run([*cli_args, invalid, work / "invalid-pair.cso"], capture_output=True, text=True) + assert result.returncode and "destination overflow" in result.stderr and not (work / "invalid-pair.cso").exists() + indexed = load(0x0d, 24, 20) + indexed[0] |= 1 << 13 + invalid = write_request(work, setup + indexed + finish, root, sa) + result = subprocess.run([*cli_args, invalid, work / "indexed.cso"], capture_output=True, text=True) + assert result.returncode and "needs offen" in result.stderr and not (work / "indexed.cso").exists() + + +def global_stride_fixtures(gpu, sdk, work, root, source, sa): + source.write_text('#define SIG "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | SAMPLER_HEAP_DIRECTLY_INDEXED),' + 'DescriptorTable(SRV(t0,numDescriptors=16)),DescriptorTable(UAV(u0,numDescriptors=16)),' + 'RootConstants(num32BitConstants=4,b0)"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + # GPU input s[40:47] feeds s43. Select a heap slot, then extract descriptor word 1 bits 16..29. + # The table index is deliberately unbounded at compile time, and is overwritten before the extract. + for selector_offset in (0, 4): + words = [0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (24 << 6) | 10, 0xfa000040, + 0xf40c0000 | (56 << 6) | 11, 0xfa0000e0, + 0x80000000 | (0x1e << 23) | (20 << 16) | (133 << 8) | 12, + 0xf42c0000 | (40 << 6) | 12, (20 << 25) | selector_offset, + 0xbe9e030a, 0xbe9f0380, 0x80000000 | (0x1e << 23) | (43 << 16) | (133 << 8) | 43, + 0xf4080000 | (48 << 6) | 15, 43 << 25, 0xbeab0380, + 0x93800000 | (28 << 16) | (255 << 8) | 49, 0x000e0010, + 0xd7460008, 12 | (133 << 9) | (256 << 18), 0x7e12020d] + words += [0x7e000000 | (v << 17) | (6 << 9) | 28 for v in range(2, 6)] + words += [0xf0200f08, (14 << 16) | (2 << 8) | 8, 0xbf810000] + marker = write_request(work, words, root.read_bytes(), sa) + result = subprocess.run([gpu, sdk, marker, work / "cache", "global-stride"], capture_output=True, text=True) + print("global-stride", selector_offset, result.stdout.strip(), flush=True) + assert result.returncode == int(bool(selector_offset)), (result.stdout, result.stderr) + assert f"differing_components={8192 if selector_offset else 0} " in result.stdout + + +def main(cli, gpu, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + source = work / "root.hlsl" + source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=16)),DescriptorTable(UAV(u0,numDescriptors=16))"') + root = work / "root.bin" + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, 8 | (8 << 16), 1 | (1 << 20), 0, 0x8d8c) + # s4 and s5 are the two guest tables. The byte offsets deliberately differ + # from the desktop registers that the translator assigns to them. + words = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, # descriptor s32:35, table 0 +64 + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, # descriptor s40:47, table 1 +224 + 0xbe8b0384, # s11 = byte offset 4 + 0xf4240000 | (11 << 6) | 16, 11 << 25, # s[11:12] = buffer[s11], mask in second word + 0x938dff08, 0x00050014, # wave in group from TG_SIZE_EN -> s13 + 0x938eff08, 0x00060000, # number of waves -> s14 + 0xd7650002, (128 << 9) | 193, # v2 = mbcnt(-1, 0) + 0xd7650003, (128 << 9) | 12, # v3 = mbcnt(s12, 0) + ] + for dst, src in [(2,258),(3,259),(4,13),(5,14)]: + words.append(0x7e000000 | (dst << 17) | (6 << 9) | src) # v_cvt_f32_u32 + words.extend([0xf0200f08, (10 << 16) | (2 << 8), 0xbf810000]) + marker = write_request(work, words, root.read_bytes(), sa) + args = [cli, sdk, work / "cache", "gfx1013-compute-wave32@0"] + result = subprocess.run([*args, marker, work / "good.cso"], capture_output=True, text=True, check=True) + assert "t0 root=0 bytes=64 min_size=4" in result.stdout and "u0 root=1 bytes=224" in result.stdout + rejected = write_request(work, [*words[:-1], 0xffffffff, words[-1]], root.read_bytes(), sa) + result = subprocess.run([*args, rejected, work / "bad.cso"], capture_output=True, text=True) + # 0xffffffff is not a gfx1013 encoding, so the decoder refuses it before any lowering. + assert result.returncode and "unknown gfx1013 instruction format at byte" in result.stderr, result.stderr + assert not (work / "bad.cso").exists() + batch_dir = work / "batch-output" + batch = subprocess.run([cli, sdk, work / "cache", "--jobs", "2", "gfx1013-compute-wave32@0", + "--requests", work, batch_dir], capture_output=True, text=True) + assert batch.returncode == 1 and "requests=2 compiled=1 refused=1" in batch.stdout + assert (batch_dir / f"{marker.stem[4:]}.cs.cso").read_bytes() == (work / "good.cso").read_bytes() + assert (batch_dir / f"{marker.stem[4:]}.txt").is_file() + assert not (batch_dir / f"{rejected.stem[4:]}.cs.cso").exists() + assert not (batch_dir / f"{rejected.stem[4:]}.txt").exists() + first = subprocess.run([gpu, sdk, marker, work / "cache"]) + if first.returncode: + return first.returncode + + source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=16)),' + 'DescriptorTable(UAV(u0,numDescriptors=16)),RootConstants(num32BitConstants=4,b0)"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", "-Fo", root, source], check=True) + sa = struct.pack("<7I", 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x198) + # One 32-lane group per tile. s6/s7 are root constants and s12/s13 are the group IDs. + code = [ + 0xbe940304, 0xbe950380, 0xbe960305, 0xbe970380, + 0xf4080000 | (32 << 6) | 10, 0xfa000040, + 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0x930f060d, 0x800f070f, # s15 = group.y * root[0] + root[1] + 0xd7460008, 12 | (133 << 9) | (256 << 18), # v8 = (group.x << 5) + local.x + 0x80000000 | (0x31 << 23) | (15 << 16) | (129 << 8) | 15, # (s15 << 4) + 1 + 0x7c000000 | (0xc1 << 17) | (8 << 9) | 159, # wave mask for 31 < x + 0xbe910383, 0xbf860001, 0xbe910389, # s17 = 3 in tile 0, 9 in tile 1 + 0x4a000000 | (10 << 17) | (8 << 9) | 17, # v10 = x + s17 + 0x7e12020d, # v9 = group.y + 0xe0042000, 0x80080208, # v[2:3] = formatted[v8].xy + 0x4a06060f, # v3 = v3 + s15 + ] + for dst, src in [(2, 258), (3, 259), (4, 266), (5, 13)]: + code.append(0x7e000000 | (dst << 17) | (6 << 9) | src) + # Convert y/2 with ties-to-even, then round-trip through unsigned integer. + code.extend([0x10000000 | (5 << 17) | (5 << 9) | 240, + 0x7e000000 | (5 << 17) | (0x23 << 9) | 261, + 0x7e000000 | (5 << 17) | (7 << 9) | 261, + 0x7e000000 | (5 << 17) | (6 << 9) | 261]) + code.extend([0xf0200f08, (10 << 16) | (2 << 8) | 8, 0xbf810000]) + typed = write_request(work, code, root.read_bytes(), sa) + subprocess.run([*args, typed, work / "typed.cso"], check=True) + unbound = write_request(work, [*code[:-1], 0x800f000f, code[-1]], root.read_bytes(), sa) + rejection = subprocess.run([*args, unbound, work / "unbound.cso"], capture_output=True, text=True) + assert rejection.returncode and "unbound numeric SGPR s0" in rejection.stderr + assert not (work / "unbound.cso").exists() + subprocess.run([gpu, sdk, typed, work / "cache", "typed"], check=True) + # Only the low 16 bits are stored. Distinct high bits expose an accidental high-half selection. + for half, mode in ((0xc100, "half-value"), (0x4100, "half-mutant")): + words = [0xbe960305, 0xbe970380, 0xf40c0000 | (40 << 6) | 11, 0xfa0000e0, + 0xd7460008, 12 | (133 << 9) | (256 << 18), 0x7e12020d, + 0x7e0402ff, 0x45000000 | half, + 0xf0200108, 0x80000000 | (10 << 16) | (2 << 8) | 8, 0xbf810000] + marker = write_request(work, words, root.read_bytes(), sa) + result = subprocess.run([gpu, sdk, marker, work / "cache", mode], capture_output=True, text=True) + mutant = mode == "half-mutant" + assert result.returncode == int(mutant), (result.stdout, result.stderr) + print(mode, result.stdout.strip(), flush=True) + sdwa_fixtures(args, gpu, sdk, work, root.read_bytes(), sa) + raw_offset_fixtures(args, gpu, sdk, work, root.read_bytes(), sa) + global_stride_fixtures(gpu, sdk, work, root, source, sa) + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wave_request_gpu.cpp b/tests/native_wave_request_gpu.cpp new file mode 100644 index 0000000000..fe60f81cde --- /dev/null +++ b/tests/native_wave_request_gpu.cpp @@ -0,0 +1,104 @@ +#include "desktop_gpu.h" +#include "native_compute_pipeline.h" +#include <cstdio> +#include <cstring> +#include <dxgi1_4.h> + +using Microsoft::WRL::ComPtr; +int check_native_compute_grid(ID3D12Device*, x2w::ShaderDxilCompiler&, const wchar_t*, const wchar_t*, const std::wstring&); +int check_half_grid(ID3D12Device*, x2w::ShaderDxilCompiler&, const wchar_t*, const wchar_t*, const std::wstring&); +int wmain(int argc, wchar_t **argv) { + if (argc != 4 && argc != 5) + return 2; + try { + ComPtr<IDXGIFactory4> factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "factory"); + ComPtr<ID3D12Device> device; + for (UINT i = 0; !device; ++i) { + ComPtr<IDXGIAdapter1> adapter; + if (factory->EnumAdapters1(i, &adapter) != S_OK) + return 77; + DXGI_ADAPTER_DESC1 description{}; + check(adapter->GetDesc1(&description), "adapter description"); + if (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) + continue; + ComPtr<ID3D12Device> candidate; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&candidate)))) + continue; + D3D12_FEATURE_DATA_SHADER_MODEL model{D3D_SHADER_MODEL_6_6}; + D3D12_FEATURE_DATA_D3D12_OPTIONS1 waves{}; + if (FAILED(check_feature(candidate.Get(), D3D12_FEATURE_SHADER_MODEL, &model, sizeof(model))) || + model.HighestShaderModel < D3D_SHADER_MODEL_6_6 || + FAILED(check_feature(candidate.Get(), D3D12_FEATURE_D3D12_OPTIONS1, &waves, sizeof(waves))) || + !waves.WaveOps || waves.WaveLaneCountMin > 32 || waves.WaveLaneCountMax < 32) + continue; + device = candidate; + } + x2w::ShaderDxilCompiler compiler(argv[1]); + if (argc == 5 && std::wstring(argv[4]).find(L"half-") == 0) + return check_half_grid(device.Get(), compiler, argv[2], argv[3], argv[4]); + if(argc==5)return check_native_compute_grid(device.Get(),compiler,argv[2],argv[3],argv[4]); + auto pipeline = x2w::create_native_compute_pipeline(device.Get(), compiler, argv[2], 0, argv[3]); + if (!pipeline.cache_hit || pipeline.srv_count != 1 || pipeline.bindings.size() != 2) + return 1; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr<ID3D12DescriptorHeap> heap; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap)), "descriptor heap"); + UINT step = device->GetDescriptorHandleIncrementSize(hd.Type); + auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); + auto input = make_buffer(device.Get(), 12, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const unsigned words[]{0, 0x10000, 0x55555555}; + void *mapped; + check(input->Map(0, nullptr, &mapped), "map input"); + std::memcpy(mapped, words, sizeof(words)); + input->Unmap(0, nullptr); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.Buffer.NumElements = 3; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(input.Get(), &srv, cpu); + cpu.ptr += step; + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = td.Height = 8; + td.DepthOrArraySize = td.MipLevels = td.SampleDesc.Count = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + auto texture = resource(device.Get(), td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + device->CreateUnorderedAccessView(texture.Get(), nullptr, nullptr, cpu); + ComputeCommands commands(device.Get(), pipeline.state.Get()); + pipeline.bind(commands.list.Get(), heap.Get(), heap->GetGPUDescriptorHandleForHeapStart(), step); + commands.list->Dispatch(1, 1, 1); + transition(commands.list.Get(), texture.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes; + device->GetCopyableFootprints(&td, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + auto readback = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION src{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = footprint; + commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + commands.submit_and_wait(device.Get()); + check(readback->Map(0, nullptr, &mapped), "read pixels"); + for (unsigned i = 0; i < 64; ++i) { + auto pixel = reinterpret_cast<const float *>(static_cast<const char *>(mapped) + + (i / 8) * footprint.Footprint.RowPitch) + + (i % 8) * 4; + unsigned lane = i % 32; + if (pixel[0] != lane || pixel[1] != (lane + 1) / 2 || pixel[2] != i / 32 || pixel[3] != 2) { + std::fprintf(stderr, "lane %u: %g %g %g %g\n", i, pixel[0], pixel[1], pixel[2], pixel[3]); + return 1; + } + } + readback->Unmap(0, nullptr); + std::puts("64 lanes, two wave32 groups, masked prefix counts and offline-to-runtime cache match"); + return 0; + } catch (const std::exception &error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; + } +} diff --git a/tests/native_wave_virtual_derivative_check.py b/tests/native_wave_virtual_derivative_check.py new file mode 100644 index 0000000000..17dfacfa3c --- /dev/null +++ b/tests/native_wave_virtual_derivative_check.py @@ -0,0 +1,93 @@ +"""Packed slot-67 control for implicit derivatives in a virtual wave64 group. + +The virtual-wave scheduler needs the packed state, more than one guest wave64, +and a conditional branch plus a synchronizing instruction. The container +fixture does not enter that path. This source-built request keeps the explicit +LOD and ordinary implicit cases compiling, and requires the combination to be +refused at the image opcode instead of producing a shader with no scheduler +readback. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_compute_clear_check import write_request + + +WIDTH = 8 +SAMPLER = (0x12, 0xFFF000, 0x04500000, 0) + + +def bits(value): + return struct.unpack("<I", struct.pack("<f", value))[0] + + +def vop2(op, dst, src0, src1): + return (op << 25) | (dst << 17) | (src1 << 9) | src0 + + +def setup(): + # One guest table at s4: the texture descriptor is loaded from it before + # s4:7 is reused for the sampler constants the image op consumes. + code = [ + 0xBEFE04C1, # s_mov_b64 exec, -1 (wave64) + 0xBE850380, # s5 = 0, the high half of the table address + 0xF40C0202, 0xFA000000, # s_load_dwordx8 s[8:15], s[4:5], 0 + ] + for reg, value in enumerate(SAMPLER, start=4): + code += [0xBE8003FF | (reg << 16), value] + return code + + +def program(implicit, control): + code = setup() + code += [ + vop2(22, 3, 130, 0), vop2(27, 3, 131, 3), vop2(19, 3, 130, 3), + vop2(26, 4, 151, 3), vop2(37, 4, 255, 4), bits(1 / WIDTH), + vop2(27, 1, 129, 0), 0x7E020D01, vop2(8, 1, 260, 1), + vop2(27, 4, 136, 0), 0x7E080D04, vop2(8, 4, 255, 4), bits(0.0625), + vop2(3, 1, 260, 1), 0x7E0402F0, 0x7E060D03, + ] + if control: + code += [0xBF880004, 0xBF8A0000] # s_cbranch_execz +4; s_barrier + code += [0xBF8CC07F, 0xF0000108 | ((32 if implicit else 36) << 18), 0x00220401] + code.append(0xBF810000) + return code + + +def main(cli, sdk): + with tempfile.TemporaryDirectory() as temporary: + work = Path(temporary) + source, root = work / "root.hlsl", work / "root.bin" + source.write_text('#define SIG "DescriptorTable(SRV(t0,numDescriptors=8)),' + 'DescriptorTable(UAV(u0,numDescriptors=8))"', encoding="ascii") + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root, source], check=True) + # Tagged slot-67 state: dword 0 and dword 1 select the packed ABI, dword 3 + # is X|Y<<16, dword 4 holds Z and the wave size, and dword 6 is RSRC2. + sa = struct.pack("<7I", 0x4005cf00, 0x6c090102, 0, 128 | (1 << 16), 1, 0, 0x8d8c) + cases = ( + ("implicit", True, False, 0, None), + ("explicit", False, True, 0, None), + ("implicit-virtual", True, True, 1, "implicit derivatives with virtual wave64 groups"), + ) + for name, implicit, control, expected, diagnostic in cases: + marker = write_request(work, program(implicit, control), root.read_bytes(), sa) + output = work / f"{name}.cso" + run = subprocess.run([cli, sdk, work / "cache", "gfx1013-direct-cs@0", marker, output], + capture_output=True, text=True, timeout=60) + assert run.returncode == expected, (name, run.stdout, run.stderr) + if diagnostic: + assert diagnostic in run.stderr and not output.exists(), (name, run.stderr) + print(f"{name}: refused at the image opcode: {diagnostic}") + else: + assert output.is_file(), (name, run.stdout, run.stderr) + print(f"{name}: packed slot-67 request compiled") + print("virtual-wave derivative control passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/native_wrexec64_check.py b/tests/native_wrexec64_check.py new file mode 100644 index 0000000000..c88b11456f --- /dev/null +++ b/tests/native_wrexec64_check.py @@ -0,0 +1,112 @@ +"""Check slot 67 wave64 WREXEC lane stores, destination words and SCC.""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from native_compute_clear_check import write_request +from native_dpp_mirror_check import vop2 +from native_scalar_lds_check import scalar, sop1, vmove + + +MOV_B32, ANDN2_WREXEC_B64 = 3, 0x3A +ZERO, ONE, NEG_ONE, LITERAL = 128, 129, 193, 255 +EXEC_LO, EXEC_HI = 126, 127 +OLD_EXEC = (0x80000012, 0x40000009) +GUARD_WORDS, OUTPUT_WORDS = 8, 2064 +GROUP_WORDS, PLANE_WORDS = 128, 256 +SENTINEL = 0x69696969 +CASES = ( + # X, source words, destination, incoming SCC, expected result, expected SCC + (64, (0x80000084, 0xC0000021), 24, 0, (0x84, 0x80000020), 1), + (128, (0x80000084, 0xC0000021), 24, 0, (0x84, 0x80000020), 1), + (128, (0x80000002, 0xC0000021), 22, 0, (0, 0x80000020), 1), + (64, OLD_EXEC, 24, 1, (0, 0), 0), +) + + +def program(source, dst, incoming_scc, src=22): + # s4 holds the table, s5 holds group.x and v0 holds local.x. + # v8 = 512 * group.x + 4 * local.x, calculated before narrowing EXEC. + words = [ + sop1(MOV_B32, 20, 4), sop1(MOV_B32, 21, ZERO), + 0xF408080A, 0xFA000020, + scalar(0x1E, 7, 5, ZERO + 9), + vop2(0x1A, 8, ZERO + 2, 0), vop2(0x25, 8, 7, 8), + 0xBF8CC07F, + sop1(MOV_B32, EXEC_LO, LITERAL), OLD_EXEC[0], + sop1(MOV_B32, EXEC_HI, LITERAL), OLD_EXEC[1], + sop1(MOV_B32, 22, LITERAL), source[0], + sop1(MOV_B32, 23, LITERAL), source[1], + 0xBF060080 | (ZERO if incoming_scc else ONE) << 8, # s_cmp_eq_u32 + sop1(ANDN2_WREXEC_B64, dst, src), + 0xE0701000, 0x80080008, # store v0 under the new EXEC + scalar(0x0A, 26, ONE, ZERO), # s_cselect_b32 captures SCC + sop1(MOV_B32, EXEC_LO, NEG_ONE), sop1(MOV_B32, EXEC_HI, NEG_ONE), + ] + for plane, reg in enumerate((dst, dst + 1, 26), start=1): + words += [vmove(4, reg), 0xE0701000 | (plane * PLANE_WORDS * 4), 0x80080408] + return words + [0xBF810000] + + +def request(work, root, threads, words): + # .sa dword 4 bit 20 is clear, selecting the wave64 model. + sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1, 0, 0x8A) + return write_request(work, words, root, sa) + + +def expected_output(threads, result, scc): + expected = [SENTINEL] * OUTPUT_WORDS + for group in range(2): + for local in range(threads): + index = GUARD_WORDS + group * GROUP_WORDS + local + lane = local % 64 + if result[lane // 32] & (1 << (lane % 32)): + expected[index] = local + for plane, value in enumerate((*result, scc), start=1): + expected[index + plane * PLANE_WORDS] = value + return expected + + +def main(cli, replay, sdk): + with tempfile.TemporaryDirectory() as temp: + work = Path(temp) + shader, root_file = work / "root.hlsl", work / "root.bin" + shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"') + subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG", + "-Fo", root_file, shader], check=True) + root = root_file.read_bytes() + cache = work / "cache" + compile_cmd = [cli, sdk, cache, "gfx1013-direct-cs@0"] + replay_cases = [] + for threads, source, dst, incoming_scc, result, scc in CASES: + marker = request(work, root, threads, program(source, dst, incoming_scc)) + output = marker.with_suffix(".cso") + compiled = subprocess.run([*compile_cmd, marker, output], capture_output=True, text=True) + assert compiled.returncode == 0 and output.is_file(), (compiled.stdout, compiled.stderr) + replay_cases.append((threads, result, scc, marker)) + + for src, dst in ((106, 24), (23, 24), (22, 25)): + marker = request(work, root, 64, program(CASES[0][1], dst, 0, src)) + output = marker.with_suffix(".cso") + compiled = subprocess.run([*compile_cmd, marker, output], capture_output=True, text=True) + assert compiled.returncode != 0 and "unsupported wave64 scalar operation" in compiled.stderr, ( + src, dst, compiled.stdout, compiled.stderr) + assert not output.exists(), output + + for threads, result, scc, marker in replay_cases: + output = marker.with_suffix(".bin") + replayed = subprocess.run([replay, sdk, marker, cache, "0", output, "--direct"]) + if replayed.returncode == 77: + return 77 + replayed.check_returncode() + actual = struct.unpack(f"<{OUTPUT_WORDS}I", output.read_bytes()) + for index, (got, want) in enumerate(zip(actual, expected_output(threads, result, scc))): + assert got == want, (threads, result, index, hex(got), hex(want)) + print(f"wave64 X={threads}, EXEC={result[1]:08x}:{result[0]:08x}, SCC={scc} matched") + return 0 + + +if __name__ == "__main__": + sys.exit(main(*sys.argv[1:])) diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index d3973cdd18..3d53da367c 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -459,11 +459,14 @@ bool validate_compute_mesh_texture_fallback_args(int argc, char** argv) (argc != 10 || std::string_view(argv[9]) == "--stale"); } -template<class AfterDraw> -OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_draw) +template<class AfterCase> +OperationResult run_readback_batch(const OperationContext& ctx, AfterCase after_case) { - const bool pairs = std::string_view(ctx.argv[2]) == "--check-pixel-pairs"; + const std::string_view operation(ctx.argv[2]); + const bool pairs = operation == "--check-pixel-pairs"; + const bool compute = operation == "--compute-store-batch"; const int stride = pairs ? 2 : 1; + ComputeReadbackProgram program; bool failed = false; for (int i = 4, index = 0; i < ctx.argc; i += stride, ++index) { const char* shader = ctx.argv[pairs ? i - 1 : 3]; @@ -471,10 +474,15 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra std::fprintf(stderr, "case=%d path=%s\n", index, ctx.argv[i]); if (pairs) std::fprintf(stderr, "shader=%s\n", shader); try { - check(ctx.device->GetDeviceRemovedReason(), "Pixel batch device"); - check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); - after_draw(index); - } catch (const PixelMismatch& e) { + check(ctx.device->GetDeviceRemovedReason(), compute ? "Compute batch device" : "Pixel batch device"); + if (compute) { + if (!program.pipeline) program = load_compute_store_program(ctx.device, shader); + check_compute_store_reference(ctx.device, program, ctx.argv[i]); + } else { + check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); + } + after_case(index); + } catch (const ReadbackMismatch& e) { std::fprintf(stderr, "%s\n", e.what()); status = "mismatch"; } catch (const std::exception& e) { @@ -490,15 +498,15 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra return failed ? OperationResult{OutcomeKind::fail, nullptr} : OperationResult{OutcomeKind::pass, nullptr}; } -OperationResult run_check_pixel_batch(const OperationContext& ctx) +OperationResult run_check_batch(const OperationContext& ctx) { - return run_pixel_batch(ctx, [](int) {}); + return run_readback_batch(ctx, [](int) {}); } OperationResult run_pixel_batch_debug_control(const OperationContext& ctx) { if (!ctx.messages) return {OutcomeKind::skip, "skip: pixel batch control requires the D3D12 debug layer"}; - return run_pixel_batch(ctx, [&](int index) { + return run_readback_batch(ctx, [&](int index) { if (index == 1) check(ctx.messages->AddApplicationMessage(D3D12_MESSAGE_SEVERITY_ERROR, "pixel batch control error"), "Add pixel batch control message"); @@ -511,7 +519,7 @@ OperationResult run_pixel_batch_removal_control(const OperationContext& ctx) const HRESULT hr = ctx.device->QueryInterface(IID_PPV_ARGS(&device)); if (hr == E_NOINTERFACE) return {OutcomeKind::skip, "skip: pixel batch control requires ID3D12Device5"}; check(hr, "Query pixel batch control device"); - return run_pixel_batch(ctx, [&](int index) { + return run_readback_batch(ctx, [&](int index) { if (index == 1) device->RemoveDevice(); }); } @@ -786,6 +794,35 @@ OperationResult run_sampled_coverage(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_check_pixel_compare_mips(const OperationContext& ctx) +{ +// Windows SDK 10.0.22621 does not declare the SM 6.8 capability query. +#if defined(__ID3D12Device14_INTERFACE_DEFINED__) + const bool level = std::strcmp(ctx.argv[2], "--check-pixel-compare-level") == 0; + const D3D_SHADER_MODEL required = level ? D3D_SHADER_MODEL_6_7 : D3D_SHADER_MODEL_6_8; + D3D12_FEATURE_DATA_SHADER_MODEL shaderModel{required}; + if (FAILED(check_feature(ctx.device, D3D12_FEATURE_SHADER_MODEL, &shaderModel, sizeof(shaderModel))) || + shaderModel.HighestShaderModel < required) + return {OutcomeKind::skip, level ? "Comparison LOD requires SM 6.7" : "Comparison bias/gradient requires SM 6.8"}; + if (!level) { + D3D12_FEATURE_DATA_D3D12_OPTIONS21 options{}; + if (FAILED(check_feature(ctx.device, D3D12_FEATURE_D3D12_OPTIONS21, &options, sizeof(options))) || + !options.SampleCmpGradientAndBiasSupported) + return {OutcomeKind::skip, "Comparison bias/gradient requires SampleCmpGradientAndBiasSupported"}; + } else { + D3D12_FEATURE_DATA_D3D12_OPTIONS14 options{}; + if (FAILED(check_feature(ctx.device, D3D12_FEATURE_D3D12_OPTIONS14, &options, sizeof(options))) || + !options.AdvancedTextureOpsSupported) + return {OutcomeKind::skip, "Comparison LOD requires AdvancedTextureOpsSupported"}; + } + check_pixel_compare(ctx.device, ctx.argv[3], ctx.argv[4], true); + return {OutcomeKind::pass, nullptr}; +#else + (void)ctx; + return {OutcomeKind::skip, "Comparison mip fixture requires Windows SDK 10.0.26100 headers"}; +#endif +} + OperationResult run_check_pixel_compare(const OperationContext& ctx) { check_pixel_compare(ctx.device, ctx.argv[3], ctx.argv[4]); @@ -910,6 +947,16 @@ OperationResult run_mesh_amplified(const OperationContext& ctx) ctx.argv[6])); } +OperationResult run_mesh_shader_pipeline(const OperationContext& ctx) +{ + return skip_if_false(check_mesh_shader_pipeline(ctx.device, false)); +} + +OperationResult run_mesh_shader_pipeline_fallback(const OperationContext& ctx) +{ + return skip_if_false(check_mesh_shader_pipeline(ctx.device, true)); +} + OperationResult run_mesh_heap_sampler(const OperationContext& ctx) { return skip_if_false(check_mesh_heap_sampler_draw(ctx.device, ctx.argv[3], ctx.argv[4], ctx.argv[5])); @@ -994,6 +1041,12 @@ OperationResult run_bvh_root_roundtrip(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +OperationResult run_compute_waterfall_oracle(const OperationContext& ctx) +{ + check_compute_waterfall_oracle(ctx.device, ctx.argv[3]); + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_bvh_differential(const OperationContext& ctx) { return skip_if_false(check_bvh_differential(ctx.device, false)); @@ -1282,12 +1335,16 @@ OperationResult run_startup_sampler_heap(const OperationContext& ctx) // The expected value is four comma-separated hex words. Omit the sampler line for point wrap. // --startup-image-2d-array takes the same arguments: the texels are two slices of a 2D array and the // third coordinate is the slice. --startup-image-2d-array-mips uses a 4x4 array of two slices with three -// mip levels whose cells all differ (tests/startup_image_3d.cpp). +// mip levels whose cells all differ (tests/startup_image_3d.cpp). --startup-image-cube binds six 4x4 faces as a +// TextureCube whose 96 texels all differ (#2943); z is passed through as for the other modes. OperationResult run_startup_image_3d(const OperationContext& ctx) { - const bool mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; - const bool array = mips || std::strcmp(ctx.argv[2], "--startup-image-2d-array") == 0; + const bool array_mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; + const bool one_dimensional_mips = std::strcmp(ctx.argv[2], "--startup-image-1d-mips") == 0; + const bool array = array_mips || std::strcmp(ctx.argv[2], "--startup-image-2d-array") == 0; + const bool one_dimensional = one_dimensional_mips || std::strcmp(ctx.argv[2], "--startup-image-1d") == 0; const bool two_dimensional = std::strcmp(ctx.argv[2], "--startup-image-2d") == 0; + const bool cube = std::strcmp(ctx.argv[2], "--startup-image-cube") == 0; float z = 0.0f; if (two_dimensional && ctx.argv[5][0] == '0' && (ctx.argv[5][1] == 'x' || ctx.argv[5][1] == 'X')) { char* end = nullptr; @@ -1303,8 +1360,8 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) return {OutcomeKind::fail, "expected value is not four hex words"}; float color[4]{}; const char* sampler = ctx.argc == 8 ? ctx.argv[7] : "smp 0 0x0 0x0 0x0 0x0"; - check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], z, color, sampler, array, mips ? 3 : 1, - std::strcmp(ctx.argv[2], "--startup-image-1d") == 0, two_dimensional); + check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], z, color, sampler, array, + array_mips || one_dimensional_mips ? 3 : 1, one_dimensional, two_dimensional, 0, 0, 4, cube); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); if (std::memcmp(bits, expected, sizeof(bits)) != 0) { @@ -1315,16 +1372,32 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// --startup-image-2d-view <vs.cso> <ps.cso> <sampler manifest line> <first/count> prints one RGBA32F pixel. +// --startup-image-2d-view <vs.cso> <ps.cso> <sampler manifest> <first/count> [0|1] [8] prints one RGBA32F pixel. +// The optional selector is forwarded as the second root constant. The final 8 requests an 8x8 mip base. +// --startup-image-2d-array-view uses the two-slice renderer with the default 4x4 base. OperationResult run_startup_image_2d_view(const OperationContext& ctx) { const std::string_view window = ctx.argv[6]; if (window.size() != 3 || window[1] != '/' || window[0] < '0' || window[0] > '2' || window[2] < '1' || window[2] > '3') return {OutcomeKind::fail, "expected a first/count mip window on a three-mip texture"}; + const bool array = std::strcmp(ctx.argv[2], "--startup-image-2d-array-view") == 0; + float selector = 0.0f; + if (ctx.argc >= 8) { + if (std::strcmp(ctx.argv[7], "1") == 0) + selector = 1.0f; + else if (std::strcmp(ctx.argv[7], "0") != 0) + return {OutcomeKind::fail, "view selector must be 0 or 1"}; + } + UINT mip_base = 4; + if (ctx.argc == 9) { + if (std::strcmp(ctx.argv[8], "8") != 0) + return {OutcomeKind::fail, "2D mip base must be 8"}; + mip_base = 8; + } float color[4]{}; - check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], 0, color, ctx.argv[5], false, 3, false, true, - UINT(window[0] - '0'), UINT(window[2] - '0')); + check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], selector, color, ctx.argv[5], array, 3, false, !array, + UINT(window[0] - '0'), UINT(window[2] - '0'), mip_base); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); std::printf("view_rgba=%08x,%08x,%08x,%08x\n", bits[0], bits[1], bits[2], bits[3]); @@ -1367,20 +1440,31 @@ OperationResult run_startup_image_load_d16(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// --startup-image-store <vs.cso> <ps.cso> <x,y> <expected rgba bits>: the translated pixel stage stores to -// u0 (tests/startup_image_store.cpp); texel (x, y) must hold the four hex words and every other texel -1.0. +// --startup-image-store <vs.cso> <ps.cso> <x,y> <expected rgba bits> [coverage]: the translated pixel +// stage stores to u0 (tests/startup_image_store.cpp); texel (x, y) must hold the four hex words and +// every other texel -1.0. Coverage is 1 (one pixel) or 2 (two pixels in one draw). OperationResult run_startup_image_store(const OperationContext& ctx) { - unsigned x = 0, y = 0; + unsigned x = 0, y = 0, coverage = 1; std::uint32_t expected[4]{}; if (std::sscanf(ctx.argv[5], "%u,%u", &x, &y) != 2) return {OutcomeKind::fail, "texel is not x,y"}; if (std::sscanf(ctx.argv[6], "%8x,%8x,%8x,%8x", &expected[0], &expected[1], &expected[2], &expected[3]) != 4) return {OutcomeKind::fail, "expected value is not four hex words"}; - if (check_startup_image_store(ctx.device, ctx.argv[3], ctx.argv[4], x, y, expected)) + if (ctx.argc == 8 && (std::sscanf(ctx.argv[7], "%u", &coverage) != 1 || (coverage != 1 && coverage != 2))) + return {OutcomeKind::fail, "coverage is not 1 or 2"}; + if (check_startup_image_store(ctx.device, ctx.argv[3], ctx.argv[4], x, y, expected, coverage)) return {OutcomeKind::fail, "image store readback differs"}; return {OutcomeKind::pass, nullptr}; } +// --startup-image-store-reject-load: a colour format without typed UAV load is refused before any draw. +OperationResult run_startup_image_store_reject_load(const OperationContext& ctx) +{ + if (const char* reason = check_startup_image_store_typed_load(ctx.device)) + return {OutcomeKind::fail, reason}; + return {OutcomeKind::fail, "typed UAV load negative control found no refusal"}; +} + const char* check_startup_sharedexp_target(ID3D12Device* device, ID3D12InfoQueue* messages); OperationResult run_startup_sharedexp_target(const OperationContext& ctx) @@ -1472,16 +1556,39 @@ OperationResult run_startup_pixel_words(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +// --startup-pixel-dump <vs.cso> <ps.cso> <width> <height> <out.bin>: the draw of --startup-pixel-words, but the +// readback is written to the file (width * height * 4 little-endian words, row by row) for the caller to check. +// Gated on wave operations: the caller's pixel stage reads its own lane and wave (tests that need a reference +// per desktop wave, which only the readback can tell). +OperationResult run_startup_pixel_dump(const OperationContext& ctx) +{ + const unsigned long width = pixel_extent(ctx.argv[5]), height = pixel_extent(ctx.argv[6]); + std::vector<std::uint32_t> pixels(size_t(width) * height * 4); + check_startup_flat_param(ctx.device, ctx.argv[3], ctx.argv[4], pixels.data(), UINT(width), UINT(height)); + std::ofstream file(ctx.argv[7], std::ios::binary); + file.write(reinterpret_cast<const char*>(pixels.data()), std::streamsize(pixels.size() * sizeof(std::uint32_t))); + if (!file) + return {OutcomeKind::fail, "cannot write the readback file"}; + std::printf("wrote %lu pixels\n", width * height); + return {OutcomeKind::pass, nullptr}; +} + // --startup-flat-param <vs.cso> <ps.cso> <expected words>: draws one pixel with a gfx2hlsl vertex and // pixel stage pair (tests/startup_flat_param.cpp). The expected value is four 8-digit hex words, -// comma separated. +// comma separated. An optional fourth argument sets the four entry constants (ud0..ud3) as four hex words; +// without it they are all 0. OperationResult run_startup_flat_param(const OperationContext& ctx) { std::uint32_t expected[4]{}; if (std::sscanf(ctx.argv[5], "%8x,%8x,%8x,%8x", &expected[0], &expected[1], &expected[2], &expected[3]) != 4) return {OutcomeKind::fail, "expected value is not four hex words"}; std::uint32_t words[4]{}; - check_startup_flat_param(ctx.device, ctx.argv[3], ctx.argv[4], words); + std::uint32_t constants[4]{}; + if (ctx.argc == 7 && std::sscanf(ctx.argv[6], "%8x,%8x,%8x,%8x", &constants[0], &constants[1], &constants[2], + &constants[3]) != 4) + return {OutcomeKind::fail, "entry constants are not four hex words"}; + check_startup_flat_param(ctx.device, ctx.argv[3], ctx.argv[4], words, 1, 1, + D3D12_CULL_MODE_NONE, FALSE, 3, ctx.argc == 7 ? constants : nullptr); if (std::memcmp(words, expected, sizeof(words)) != 0) { std::fprintf(stderr, "startup_flat_param mismatch expected=%08x,%08x,%08x,%08x actual=%08x,%08x,%08x,%08x\n", expected[0], expected[1], expected[2], expected[3], words[0], words[1], words[2], words[3]); @@ -1619,9 +1726,12 @@ constexpr CapabilityGate kGateSm66MinLod{ // Static argument shapes and unconditional adapter prerequisites for every named operation. // Scenario-dependent capability checks (such as DXR tier, mesh tier, or existing-heap support) // remain inside the handlers and report OutcomeKind::skip. +OperationResult run_serve(const OperationContext& ctx); + const OperationSpec kOperations[] = { - {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_pixel_batch}, - {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_pixel_batch}, + {"--serve", 3, 3, nullptr, kNoGate, run_serve}, + {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_batch}, + {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_batch}, {"--pixel-batch-debug-control", 7, 7, nullptr, kNoGate, run_pixel_batch_debug_control}, {"--pixel-batch-removal-control", 7, 7, nullptr, kNoGate, run_pixel_batch_removal_control}, {"--compute-root", 3, 3, nullptr, kNoGate, run_compute_root}, @@ -1629,6 +1739,7 @@ const OperationSpec kOperations[] = { {"--compute-root-file", 4, 4, nullptr, kNoGate, run_compute_root_file}, {"--ffx-immediate-conversion", 4, 4, nullptr, kNoGate, run_ffx_immediate_conversion}, {"--compute-store-case", 5, 5, nullptr, kNoGate, run_compute_store_case}, + {"--compute-store-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_batch}, {"--compute-store-sized-case", 5, 6, nullptr, kNoGate, run_compute_store_sized_case}, {"--compute-store-dpp-case", 5, 5, nullptr, kGateShaderWave, run_compute_store_dpp_case}, {"--compute-store-case-atomic64", 5, 5, nullptr, kGateComputeAtomic64, run_compute_store_case}, @@ -1642,19 +1753,24 @@ const OperationSpec kOperations[] = { {"--sampler-index-control", 3, 3, nullptr, kGateSm60SamplerIndexControl, run_sampler_index_control}, {"--startup-sampler-heap", 7, 9, nullptr, kNoGate, run_startup_sampler_heap}, {"--startup-image-1d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-1d-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, - {"--startup-image-2d-view", 7, 7, nullptr, kNoGate, run_startup_image_2d_view}, + {"--startup-image-2d-view", 7, 9, nullptr, kNoGate, run_startup_image_2d_view}, + {"--startup-image-2d-array-view", 7, 8, nullptr, kNoGate, run_startup_image_2d_view}, {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, - {"--startup-image-store", 7, 7, nullptr, kNoGate, run_startup_image_store}, + {"--startup-image-store", 7, 8, nullptr, kNoGate, run_startup_image_store}, + {"--startup-image-store-reject-load", 3, 3, nullptr, kNoGate, run_startup_image_store_reject_load}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-cube", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, - {"--startup-flat-param", 6, 6, nullptr, kNoGate, run_startup_flat_param}, + {"--startup-flat-param", 6, 7, nullptr, kNoGate, run_startup_flat_param}, {"--startup-entry-words", 7, 7, nullptr, kNoGate, run_startup_entry_words}, {"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words}, {"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words}, + {"--startup-pixel-dump", 8, 8, validate_pixel_words_args, kGateShaderWave, run_startup_pixel_dump}, // <cso> <groups 1|2> <UAV bytes> <out.bin>: whole raw UAV after one dispatch (#775 GVN parity). {"--raw-uav-dump", 7, 7, nullptr, kGateSm60RawUavDump, run_raw_uav_dump}, {"--raw-uav-dump-sm62", 7, 7, nullptr, kGateSm62RawUavDump, run_raw_uav_dump}, @@ -1688,6 +1804,9 @@ const OperationSpec kOperations[] = { {"--dual-pixel-swapped", 5, 5, nullptr, kNoGate, run_dual_pixel_swapped}, {"--sampled-coverage", 5, 5, nullptr, kNoGate, run_sampled_coverage}, {"--check-pixel-compare", 5, 5, nullptr, kNoGate, run_check_pixel_compare}, + {"--check-pixel-compare-level", 5, 5, nullptr, kNoGate, run_check_pixel_compare_mips}, + {"--check-pixel-compare-bias", 5, 5, nullptr, kNoGate, run_check_pixel_compare_mips}, + {"--check-pixel-compare-grad", 5, 5, nullptr, kNoGate, run_check_pixel_compare_mips}, {"--check-pixel-gather", 5, 5, nullptr, kNoGate, run_check_pixel_gather}, {"--check-pixel-compare-gather", 6, 7, nullptr, kNoGate, run_check_pixel_compare_gather}, {"--check-pixel-case", 5, 6, nullptr, kNoGate, run_check_pixel_case}, @@ -1707,6 +1826,8 @@ const OperationSpec kOperations[] = { {"--depth-mask-swapped", 6, 6, nullptr, kNoGate, run_depth_mask_swapped}, {"--mesh-entry", 6, 7, validate_mesh_entry_args, kNoGate, run_mesh_entry}, {"--mesh-amplified", 7, 7, nullptr, kNoGate, run_mesh_amplified}, + {"--mesh-shader-pipeline", 3, 3, nullptr, kNoGate, run_mesh_shader_pipeline}, + {"--mesh-shader-pipeline-fallback", 3, 3, nullptr, kNoGate, run_mesh_shader_pipeline_fallback}, {"--mesh-indexed", 6, 6, nullptr, kNoGate, run_mesh_indexed}, {"--mesh-multi", 6, 6, nullptr, kNoGate, run_mesh_multi}, {"--mesh-heap-sampler", 6, 6, nullptr, kNoGate, run_mesh_heap_sampler}, @@ -1721,6 +1842,7 @@ const OperationSpec kOperations[] = { {"--mesh-depth-pair-fallback", 7, 7, nullptr, kGateSm60MeshFallback, run_mesh_depth_pair_fallback}, {"--mesh-shadow", 7, 8, validate_mesh_shadow_args, kNoGate, run_mesh_shadow}, {"--bvh-root-roundtrip", 3, 3, nullptr, kNoGate, run_bvh_root_roundtrip}, + {"--compute-waterfall-oracle", 4, 4, nullptr, kNoGate, run_compute_waterfall_oracle}, {"--bvh-differential", 3, 3, nullptr, kNoGate, run_bvh_differential}, {"--bvh-differential-pipeline", 3, 3, nullptr, kNoGate, run_bvh_differential_pipeline}, {"--bvh-hits", 3, 3, nullptr, kGateSm65, run_bvh_hits}, @@ -1894,6 +2016,60 @@ int run_operation_spec(const OperationSpec& spec, const OperationContext& ctx, D return 1; } +// --serve: any other operation, case after case, on this one device. A test that checks hundreds of shader pairs starts one +// process and creates the D3D12 device once instead of once per case. After the banner it prints the marker pair for case -1 (the banner text), then +// reads one case per stdin line: the operation and its operands separated by tabs, exactly the arguments that follow the +// adapter name in a one-shot call. Each case runs through the same argument validation, capability gate, debug-layer check +// and exit-code mapping as a one-shot call (0 pass, 1 failure, 77 skip, 2 bad arguments); its stdout and stderr text is +// whatever the one-shot call prints. Both streams end the case with a marker line ("X2WEND <index>" on stderr, then +// "X2WCASE <index> <exit code>" on stdout) so the client can split the text per case. The line "--end" or closing stdin ends the loop; a removed +// device ends it with exit code 1 after answering, and the client starts a new process. +OperationResult run_serve(const OperationContext& ctx) +{ + std::setvbuf(stderr, nullptr, _IONBF, 0); + std::fprintf(stderr, "X2WEND -1\n"); // the banner printed so far; the client repeats it in front of every case, as a one-shot call prints it + std::printf("X2WCASE -1 0\n"); + std::fflush(stdout); + std::vector<char> buffer(65536); + for (int index = 0; std::fgets(buffer.data(), int(buffer.size()), stdin); ++index) { + std::string line(buffer.data()); + while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) line.pop_back(); + if (line == "--end") break; // an explicit end: not every launcher (a Wine wrapper) passes the end of stdin on + std::vector<std::string> field{ctx.argv[0], std::string(ctx.mode)}; + for (std::size_t start = 0;;) { + const auto tab = line.find('\t', start); + field.push_back(line.substr(start, tab == std::string::npos ? std::string::npos : tab - start)); + if (tab == std::string::npos) break; + start = tab + 1; + } + std::vector<char*> argv; + for (auto& f : field) argv.push_back(f.data()); + int code = 2; + const bool nested = field.size() >= 3 && field[2] != "--serve"; + if (nested) { + const CliResolution cli = resolve_cli(int(argv.size()), argv.data()); + if (cli.action == CliAction::operation) { + const OperationContext inner{ctx.device, ctx.messages, ctx.caps, ctx.mode, int(argv.size()), argv.data(), nullptr}; + code = run_operation_spec(*cli.spec, inner); + } + } else { + std::fprintf(stderr, "--serve takes an operation and its operands, one case per line\n"); + } + if (ctx.messages) ctx.messages->ClearStoredMessages(); + const bool removed = FAILED(ctx.device->GetDeviceRemovedReason()); + if (removed) { + std::fprintf(stderr, "device removed during case %d\n", index); + code = 1; + } + std::fflush(stdout); + std::fprintf(stderr, "X2WEND %d\n", index); + std::printf("X2WCASE %d %d\n", index, code); + std::fflush(stdout); + if (removed) return {OutcomeKind::fail, "device removed"}; + } + return {OutcomeKind::pass, nullptr}; +} + int run_self_test() { auto require = [](bool condition, const char* what) { diff --git a/tests/paged_resource_check.py b/tests/paged_resource_check.py new file mode 100644 index 0000000000..45ea582166 --- /dev/null +++ b/tests/paged_resource_check.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Pure-Python unit, edge-case, and mutation suite for tools/paged_resource.py.""" + +from __future__ import annotations + +import io +import os +from pathlib import Path +import sys +import types +from types import SimpleNamespace +import unittest +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "paged_resource.py" +sys.path.insert(0, str(TOOLS_DIR)) +import paged_resource as pr # noqa: E402 + + +class _ShortReadStream: + """Seekable stream returning at most max_chunk bytes per read() and optionally truncating EOF.""" + + def __init__(self, data: bytes, *, max_chunk: int = 3, reported_size: int | None = None) -> None: + self._data = data + self._max_chunk = max_chunk + self._reported_size = len(data) if reported_size is None else reported_size + self._pos = 0 + + def seek(self, offset: int, whence: int = os.SEEK_SET) -> int: + if whence == os.SEEK_END: + self._pos = self._reported_size + offset + elif whence == os.SEEK_CUR: + self._pos += offset + else: + self._pos = offset + return self._pos + + def read(self, size: int = -1) -> bytes: + if self._pos >= len(self._data): + return b"" + if size < 0: + take = len(self._data) - self._pos + else: + take = min(size, self._max_chunk, len(self._data) - self._pos) + chunk = self._data[self._pos : self._pos + take] + self._pos += len(chunk) + return chunk + + +def _build_multi_segment_archive() -> tuple[bytes, list[pr.Segment], bytes]: + raw0 = b"RAW_HEAD_0" # 10 bytes + dec1 = b"ZLIB_PAYLOAD_SEG_ONE" * 2 # 40 bytes + cmp1 = zlib.compress(dec1) + raw2 = b"MIDDLE_RAW_BYTES" # 16 bytes + dec3 = b"TAIL_ZLIB_DATA!" * 3 # 45 bytes + cmp3 = zlib.compress(dec3) + + buf = bytearray(b"\xaa" * 4) + off0 = len(buf) + buf.extend(raw0) + buf.extend(b"\xbb" * 6) # physical alignment padding + off1 = len(buf) + buf.extend(cmp1) + buf.extend(b"\xcc" * 5) + off2 = len(buf) + buf.extend(raw2) + buf.extend(b"\xdd" * 3) + off3 = len(buf) + buf.extend(cmp3) + buf.extend(b"\xee" * 4) + + segments = [ + pr.Segment(off0, len(raw0), len(raw0), "raw"), + pr.Segment(off1, len(cmp1), len(dec1), "zlib"), + pr.Segment(off2, len(raw2), len(raw2), "raw"), + pr.Segment(off3, len(cmp3), len(dec3), "zlib"), + ] + logical = raw0 + dec1 + raw2 + dec3 + return bytes(buf), segments, logical + + +class PagedResourcePositiveTests(unittest.TestCase): + def test_multi_segment_raw_and_zlib_spanning_boundaries(self) -> None: + blob, segments, logical = _build_multi_segment_archive() + resource = pr.PagedResource(io.BytesIO(blob), segments) + + self.assertEqual(resource.size, len(logical)) + self.assertEqual(resource.starts, (0, 10, 50, 66)) + self.assertEqual(resource.read(0, len(logical)), logical) + + # Cross-boundary spans across raw -> zlib -> raw -> zlib. + for offset, length in ( + (0, 10), + (5, 20), + (10, 40), + (45, 25), + (0, 0), + (resource.size, 0), + (0, 0), + (len(logical) - 12, 12), + ): + with self.subTest(offset=offset, length=length): + self.assertEqual(resource.read(offset, length), logical[offset : offset + length]) + + self.assertEqual(resource.read(0, 0, limit=0), b"") + + # Empty segment table is valid with size 0. + empty = pr.PagedResource(io.BytesIO(b"unused"), []) + self.assertEqual(empty.size, 0) + self.assertEqual(empty.starts, ()) + self.assertEqual(empty.read(0, 0), b"") + + def test_short_read_reassembly(self) -> None: + blob, segments, logical = _build_multi_segment_archive() + stream = _ShortReadStream(blob, max_chunk=3) + resource = pr.PagedResource(stream, segments) + + self.assertEqual(resource._read_at(segments[0].offset, segments[0].stored), logical[:10]) + self.assertEqual(resource.read(0, len(logical)), logical) + self.assertEqual(resource.read(7, 65), logical[7:72]) + + +class PagedResourceNegativeTests(unittest.TestCase): + def test_segment_and_init_type_and_layout_rejections(self) -> None: + stream = io.BytesIO(b"\x00" * 64) + + # Bool / non-int Segment fields rejected at construction and in PagedResource.__init__. + for kwargs in ( + {"offset": True, "stored": 4, "size": 4, "codec": "raw"}, + {"offset": 0, "stored": False, "size": 4, "codec": "raw"}, + {"offset": 0, "stored": 4, "size": True, "codec": "raw"}, + {"offset": 1.5, "stored": 4, "size": 4, "codec": "raw"}, + {"offset": 0, "stored": "4", "size": 4, "codec": "raw"}, + {"offset": 0, "stored": 4, "size": None, "codec": "raw"}, + ): + with self.subTest(bad_segment=kwargs): + with self.assertRaisesRegex(ValueError, "must be an integer"): + pr.Segment(**kwargs) + with self.assertRaisesRegex(ValueError, "must be an integer"): + pr.PagedResource(stream, [SimpleNamespace(**kwargs)]) + + # Overlapping, descending, negative, empty segments. + bad_layout = ( + ("negative_offset", [pr.Segment(-1, 4, 4, "raw")]), + ("empty_stored", [pr.Segment(0, 0, 4, "raw")]), + ("empty_size", [pr.Segment(0, 4, 0, "raw")]), + ("negative_stored", [pr.Segment(0, -4, 4, "raw")]), + ("negative_size", [pr.Segment(0, 4, -4, "raw")]), + ("overlapping", [pr.Segment(0, 10, 10, "raw"), pr.Segment(9, 4, 4, "raw")]), + ("descending", [pr.Segment(16, 4, 4, "raw"), pr.Segment(8, 4, 4, "raw")]), + ) + for label, segs in bad_layout: + with self.subTest(case=label): + with self.assertRaisesRegex(ValueError, "Overlapping, descending or empty segment"): + pr.PagedResource(stream, segs) + + # Oversized and mismatched raw segments. + bad_extents = ( + ("past_eof", [pr.Segment(60, 8, 8, "raw")]), + ("raw_stored_gt_size", [pr.Segment(0, 8, 4, "raw")]), + ("raw_stored_lt_size", [pr.Segment(0, 4, 8, "raw")]), + ) + for label, segs in bad_extents: + with self.subTest(case=label): + with self.assertRaisesRegex(ValueError, "Segment extent disagrees"): + pr.PagedResource(stream, segs) + + # Non-str / empty codecs are rejected upfront in PagedResource.__init__. + for bad_codec in (None, 123, b"raw", ""): + with self.subTest(codec=bad_codec): + seg = pr.Segment(0, 4, 4, bad_codec) # type: ignore[arg-type] + with self.assertRaisesRegex(ValueError, "Unsupported segment codec"): + pr.PagedResource(stream, [seg]) + + # Unknown string codecs stay deferred to read() so later segments remain addressable. + for unknown_codec in ("other", "lz4", "zstd"): + with self.subTest(unknown_codec=unknown_codec): + mixed = pr.PagedResource( + io.BytesIO(b"abcdef"), + [ + pr.Segment(0, 2, 2, "raw"), + pr.Segment(2, 2, 2, unknown_codec), + pr.Segment(4, 2, 2, "raw"), + ], + ) + self.assertEqual(mixed.read(0, 2), b"ab") + self.assertEqual(mixed.read(4, 2), b"ef") + with self.assertRaisesRegex(ValueError, f"Unsupported segment codec {unknown_codec}"): + mixed.read(1, 2) + + def test_zlib_error_and_limit_cases(self) -> None: + payload = b"ABCD" * 8 # 32 bytes + compressed = zlib.compress(payload) + + cases = ( + ("corrupt_zlib", b"\x78\x9c" + b"\xff" * 16, len(payload)), + ("truncated_zlib", compressed[:-3], len(payload)), + ("trailing_data", compressed + b"\x00", len(payload)), + ("decoded_smaller_than_declared", compressed, len(payload) + 1), + ("decoded_larger_than_declared", compressed, len(payload) - 1), + ) + for label, data, declared_size in cases: + with self.subTest(case=label): + res = pr.PagedResource(io.BytesIO(data), [pr.Segment(0, len(data), declared_size, "zlib")]) + with self.assertRaisesRegex(ValueError, "Invalid compressed segment"): + res.read(0, 4) + + # Over-limit zlib (both decoded size > limit and stored size > limit). + over_dec = pr.PagedResource(io.BytesIO(compressed), [pr.Segment(0, len(compressed), len(payload), "zlib")]) + with self.assertRaisesRegex(ValueError, "Compressed segment exceeds read budget"): + over_dec.read(0, 4, limit=len(payload) - 1) + + incompressible = os.urandom(32) if False else bytes((i * 37) & 0xFF for i in range(32)) + big_cmp = zlib.compress(incompressible) + self.assertGreater(len(big_cmp), len(incompressible)) + over_stored = pr.PagedResource(io.BytesIO(big_cmp), [pr.Segment(0, len(big_cmp), len(incompressible), "zlib")]) + with self.assertRaisesRegex(ValueError, "Compressed segment exceeds read budget"): + over_stored.read(0, 4, limit=len(big_cmp) - 1) + + # Truncated physical read detected cleanly. + trunc_raw = pr.PagedResource(_ShortReadStream(b"AB", reported_size=8), [pr.Segment(0, 8, 8, "raw")]) + with self.assertRaisesRegex(ValueError, "Truncated segment"): + trunc_raw.read(0, 8) + + trunc_zlib = pr.PagedResource( + _ShortReadStream(compressed[:4], reported_size=len(compressed)), + [pr.Segment(0, len(compressed), len(payload), "zlib")], + ) + with self.assertRaisesRegex(ValueError, "Invalid compressed segment"): + trunc_zlib.read(0, 4) + + def test_read_bounds_and_type_rejections(self) -> None: + res = pr.PagedResource(io.BytesIO(b"0123456789"), [pr.Segment(0, 10, 10, "raw")]) + + for args, kwargs in ( + ((-1, 1), {}), + ((0, -1), {}), + ((0, 0), {"limit": -1}), + ((0, 5), {"limit": 4}), + ((8, 3), {}), + ((11, 0), {}), + ): + with self.subTest(args=args, kwargs=kwargs): + with self.assertRaisesRegex(ValueError, "Logical range outside resource or read budget"): + res.read(*args, **kwargs) + + for args, kwargs in ( + ((True, 1), {}), + ((0, False), {}), + ((0, 1), {"limit": True}), + ((0.0, 1), {}), + ((0, "1"), {}), + ((0, 1), {"limit": None}), + ): + with self.subTest(bad_types=(args, kwargs)): + with self.assertRaisesRegex(ValueError, "must be an integer"): + res.read(*args, **kwargs) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + payload = b"MUTATION_TEST_DATA" + cmp_plus_trail = zlib.compress(payload) + b"\x00" + + mutations = ( + ( + "allow_bool_segment_offset", + " if isinstance(value, bool) or not isinstance(value, int):\n", + " if not isinstance(value, int):\n", + lambda mod: mod.Segment(True, 1, 1, "raw"), + ), + ( + "skip_upfront_codec_type_check", + ' if not isinstance(segment.codec, str) or not segment.codec:\n' + ' raise ValueError(f"Unsupported segment codec {segment.codec!r}")\n', + " pass\n", + lambda mod: mod.PagedResource(io.BytesIO(b"abcd"), [mod.Segment(0, 4, 4, "")]), + ), + ( + "allow_negative_limit", + " if limit < 0 or offset < 0 or length < 0 or length > limit or offset + length > self.size:\n", + " if offset < 0 or length < 0 or (limit >= 0 and length > limit) or offset + length > self.size:\n", + lambda mod: mod.PagedResource(io.BytesIO(b"abcd"), [mod.Segment(0, 4, 4, "raw")]).read( + 0, 0, limit=-1 + ), + ), + ( + "ignore_trailing_zlib_data", + " if (len(data) != segment.stored or not decoder.eof or decoder.unused_data\n", + " if (len(data) != segment.stored or not decoder.eof\n", + lambda mod: mod.PagedResource( + io.BytesIO(cmp_plus_trail), + [mod.Segment(0, len(cmp_plus_trail), len(payload), "zlib")], + ).read(0, len(payload)), + ), + ( + "ignore_raw_size_mismatch", + ' if physical_end > file_size or (segment.codec == "raw" and stored != size):\n', + " if physical_end > file_size:\n", + lambda mod: mod.PagedResource(io.BytesIO(b"abcd"), [mod.Segment(0, 4, 2, "raw")]), + ), + ) + + for label, target, replacement, trigger in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mod = types.ModuleType(f"paged_resource_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + trigger(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py new file mode 100644 index 0000000000..75708a40bb --- /dev/null +++ b/tests/patch_manifest_check.py @@ -0,0 +1,342 @@ +"""Schema, loader and hash-gate controls for tools/patch_manifest.py on a synthetic PE32+.""" + +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import tomllib +import unittest + +import pefile + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "patch_manifest.py" +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) +import patch_manifest # noqa: E402 +from call_evidence_check import SECTION_RVA, build_pe32_plus # noqa: E402 + +REPLACEMENT = "90c3" +# Revisions of each pipeline's form, not the runtime's current ones: the loader checks the form only. +REVISION = {"graphics": "x2w-startup-shader-12", "compute": "x2w-startup-shader-12cs", + "mesh86": "x2w-startup-mesh-86-4"} + + +def manifest_text(input_sha256, original, patches=None): + if patches is None: + patches = f""" +[[patch]] +id = "p001" +kind = "memory" +why = "synthetic fixture" +remove_when = "never; this is a test" +rva = {SECTION_RVA:#x} +expect_sha256 = "{hashlib.sha256(original).hexdigest()}" +bytes = "{REPLACEMENT}" +""" + return f'[target]\ninput_sha256 = "{input_sha256}"\n{patches}' + + +def memory_patch(pid, rva, replacement=REPLACEMENT): + """One [[patch]] of kind memory; parse checks the shape of expect_sha256, not the bytes it hashes.""" + return f""" +[[patch]] +id = "{pid}" +kind = "memory" +why = "synthetic fixture" +remove_when = "never; this is a test" +rva = {rva:#x} +expect_sha256 = "{hashlib.sha256(pid.encode()).hexdigest()}" +bytes = "{replacement}" +""" + + +def shader_patch(pid="s001", key="00c0ffee0badf00d", pipeline="compute", revision=None, exts=None): + """One [[patch]] of kind shader; its files are named after the patch and hashed from their names.""" + revision = revision or REVISION[pipeline] + exts = patch_manifest.PIPELINES[pipeline][2] if exts is None else exts + files = ", ".join(f'{{ ext = "{ext}", file = "{pid}{ext}", ' + f'sha256 = "{hashlib.sha256((pid + ext).encode()).hexdigest()}" }}' for ext in exts) + return f""" +[[patch]] +id = "{pid}" +kind = "shader" +why = "synthetic fixture" +remove_when = "never; this is a test" +key = "{key}" +pipeline = "{pipeline}" +revision = "{revision}" +files = [{files}] +""" + + +class PatchManifest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + tmp = Path(self.tmp.name) + image, _, _ = build_pe32_plus() + self.original = pefile.PE(data=image).get_data(SECTION_RVA, len(REPLACEMENT) // 2) + self.input = tmp / "input.bin" + self.input.write_bytes(image) + self.other = tmp / "other.bin" + self.other.write_bytes(image[:-1] + bytes([image[-1] ^ 1])) + self.digest = hashlib.sha256(image).hexdigest() + self.manifest = tmp / "manifest.toml" + self.manifest.write_text(manifest_text(self.digest, self.original), encoding="utf-8", newline="\n") + + def cli(self, input_path): + return subprocess.run([sys.executable, "-B", str(TOOL), str(self.manifest), str(input_path)], + capture_output=True, text=True, check=False) + + def test_bound_input_loads(self): + plan = patch_manifest.load(self.manifest, self.input) + self.assertEqual(plan["manifest_sha256"], hashlib.sha256(self.manifest.read_bytes()).hexdigest()) + self.assertEqual(plan["input_sha256"], self.digest) + [patch] = plan["patches"] + self.assertEqual(patch, {"id": "p001", "kind": "memory", "why": "synthetic fixture", + "remove_when": "never; this is a test", "rva": SECTION_RVA, + "expect_sha256": hashlib.sha256(self.original).hexdigest(), + "bytes": bytes.fromhex(REPLACEMENT)}) + result = self.cli(self.input) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('"p001"', result.stdout) + + def test_wrong_input_is_refused(self): + result = self.cli(self.other) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn("manifest is for another input", result.stderr) + self.assertEqual(result.stdout, "") + # An input that cannot be opened is a diagnostic too, not a traceback. + result = self.cli(self.input.with_name("absent.bin")) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn("patch manifest: [Errno", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(result.stdout, "") + + def test_memory_patches_side_by_side(self): + # Adjacent spans do not overlap, the order of the [[patch]] tables does not matter, and RVA 0 is in range. + # The ids follow neither the addresses nor their reverse, so spans sorted by id either way refuse this case. + text = manifest_text(self.digest, self.original, patches="".join( + memory_patch(pid, rva) for pid, rva in (("p001", SECTION_RVA + 4), ("p003", SECTION_RVA + 2), + ("p000", SECTION_RVA), ("p002", 0)))) + _, patches = patch_manifest.parse(text) + self.assertEqual([(p["id"], p["rva"]) for p in patches], + [("p001", SECTION_RVA + 4), ("p003", SECTION_RVA + 2), ("p000", SECTION_RVA), ("p002", 0)]) + # One shared byte is an overlap, in either order. + for first, second in ((SECTION_RVA, SECTION_RVA + 1), (SECTION_RVA + 1, SECTION_RVA)): + with self.subTest(first=first, second=second): + text = manifest_text(self.digest, self.original, + patches=memory_patch("p001", first) + memory_patch("p002", second)) + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(text) + self.assertRegex(str(caught.exception), r"patches p00[12] and p00[12] overlap") + + def test_malformed_manifests_are_refused(self): + sha = self.digest + ok = manifest_text(sha, self.original) + second = ok.split("[target]", 1)[1].split("\n", 2)[2].replace('"p001"', '"p002"') + cases = { + "unknown keys: expect_sha265": ok.replace("expect_sha256 =", "expect_sha265 ="), + "kind 'hook' is not supported": ok.replace('"memory"', '"hook"'), + "kind ['memory'] is not supported": ok.replace('"memory"', '["memory"]'), + "kind {'a': 1} is not supported": ok.replace('"memory"', "{a = 1}"), + "span [0xffffffff, 0x100000001) does not fit": ok.replace(f"rva = {SECTION_RVA:#x}", "rva = 0xffffffff"), + "missing: why": ok.replace('why = "synthetic fixture"\n', ""), + "remove_when must be a non-empty": ok.replace('"never; this is a test"', '" "'), + "duplicate patch id: p001": ok + ok.split("[target]", 1)[1].split("\n", 2)[2], + "patches p001 and p002 overlap": ok + second, + "bytes must be": ok.replace(REPLACEMENT, "90c"), + "p001 bytes must be a non-empty": ok.replace(f'bytes = "{REPLACEMENT}"', 'bytes = ""'), + "rva must be": ok.replace(f"rva = {SECTION_RVA:#x}", "rva = true"), + "input_sha256 must be": ok.replace(sha, sha.upper()), + # A hash or key with trailing text is malformed, not a hash of another input. + "input_sha256 must be 64 lowercase hex digits": ok.replace(sha, sha + "0"), + "p001 expect_sha256 must be 64": ok.replace(hashlib.sha256(self.original).hexdigest(), + hashlib.sha256(self.original).hexdigest() + "x"), + "at least one [[patch]]": "patch = []\n" + manifest_text(sha, self.original, patches=""), + } + for message, text in cases.items(): + with self.subTest(message): + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(text) + self.assertIn(message, str(caught.exception)) + with self.assertRaises(tomllib.TOMLDecodeError): # the wording differs between Python versions + patch_manifest.parse(ok.replace("[target]", "[target")) + # Shape control for the span check: one byte at the last RVA ends exactly at 2^32. + last = ok.replace(f"rva = {SECTION_RVA:#x}", "rva = 0xffffffff").replace(REPLACEMENT, "90") + [patch] = patch_manifest.parse(last)[1] + self.assertEqual((patch["rva"], patch["bytes"]), (0xFFFFFFFF, b"\x90")) + # A wrong-type kind must reach the CLI as a diagnostic, not a traceback. + self.manifest.write_text(ok.replace('"memory"', '["memory"]'), encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertIn("patch manifest: [[patch]] 0: kind ['memory'] is not supported", result.stderr) + self.assertNotIn("Traceback", result.stderr) + + def test_load_data_gates_the_bytes_given(self): + image, other = self.input.read_bytes(), self.other.read_bytes() + self.assertEqual(patch_manifest.load_data(self.manifest, image), patch_manifest.load(self.manifest, self.input)) + with self.assertRaises(ValueError) as caught: + patch_manifest.load_data(self.manifest, other) + self.assertIn("manifest is for another input", str(caught.exception)) + # The bytes in hand decide, not the file they came from: the input file now holds the other image. + self.input.write_bytes(other) + self.assertEqual(patch_manifest.load_data(self.manifest, bytearray(image))["input_sha256"], self.digest) + with self.assertRaises(ValueError): + patch_manifest.load(self.manifest, self.input) + + def test_shader_patches(self): + sha = self.digest + ok = manifest_text(sha, self.original) + # Each pipeline loads both its base files and the optional stage or source. + text = (ok + shader_patch("s001") + shader_patch("s002", "0123456789abcdef", "graphics") + + shader_patch("s003", "fedcba9876543210", "mesh86") + + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso")) + + shader_patch("s005", "0000000000000002", "compute", exts=(".txt", ".cs.cso", ".cs.hlsl")) + + shader_patch("s006", "0000000000000003", "graphics", exts=(".txt", ".vs.cso", ".ps.cso", ".gs.cso"))) + target, patches = patch_manifest.parse(text) + self.assertEqual([(p["id"], p["kind"]) for p in patches], [("p001", "memory")] + [ + (pid, "shader") for pid in ("s001", "s002", "s003", "s004", "s005", "s006")]) + s001 = patches[1] + self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), + ("00c0ffee0badf00d", "compute", "x2w-startup-shader-12cs")) + self.assertEqual(s001["files"], [ + {"ext": ".txt", "file": "s001.txt", "sha256": hashlib.sha256(b"s001.txt").hexdigest()}, + {"ext": ".cs.cso", "file": "s001.cs.cso", "sha256": hashlib.sha256(b"s001.cs.cso").hexdigest()}]) + self.assertEqual([f["ext"] for f in patches[4]["files"]], [".mesh86.txt", ".ms.cso", ".ps.cso"]) + self.assertEqual([f["ext"] for f in patches[5]["files"]], [".txt", ".cs.cso", ".cs.hlsl"]) + self.assertEqual([f["ext"] for f in patches[6]["files"]], [".txt", ".vs.cso", ".ps.cso", ".gs.cso"]) + # The CLI lists shader ids with the memory ones. + self.manifest.write_text(text, encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004", "s005", "s006"]) + good = shader_patch() + cases = { + "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), + "s001 key must be 16 lowercase hex": ok + shader_patch(key="00C0FFEE0BADF00D"), + "patch s001 key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00d0"), + "pipeline must be one of: graphics, compute, mesh86": ok + shader_patch().replace('"compute"', '"vertex"'), + "revision 'x2w-startup-shader-12' is not a compute key revision (x2w-startup-shader-<n>cs)": + ok + shader_patch(revision="x2w-startup-shader-12"), + "s002 revision 'x2w-startup-shader-12cs' is not a graphics key revision (x2w-startup-shader-<n>)": + ok + shader_patch("s002", pipeline="graphics", revision="x2w-startup-shader-12cs"), + "revision 'x2w-startup-mesh-57-3' is not a mesh86 key revision (x2w-startup-mesh-86-<n>)": + ok + shader_patch(pipeline="mesh86", revision="x2w-startup-mesh-57-3"), + "revision 'x2w-startup-shader-cs' is not a compute": ok + shader_patch(revision="x2w-startup-shader-cs"), + "revision 'x2w-startup-shader-012cs' is not a compute": + ok + shader_patch(revision="x2w-startup-shader-012cs"), + "revision 29 is not a compute": ok + shader_patch().replace('"x2w-startup-shader-12cs"', "29"), + "files must be a non-empty array": ok + good.replace(good[good.index("files = "):], "files = []\n"), + "files[0] has unknown keys: size": ok + good.replace('{ ext = ".txt",', '{ size = 1, ext = ".txt",'), + "files[1] is missing: sha256": ok + good.replace( + f', sha256 = "{hashlib.sha256(b"s001.cs.cso").hexdigest()}"', ""), + "files[1] ext '.vs.cso' is not a compute translation file (.txt, .cs.cso, .cs.hlsl)": + ok + shader_patch(exts=(".txt", ".vs.cso")), + "s001 lists .txt twice": ok + shader_patch(exts=(".txt", ".cs.cso", ".txt")), + "s001 compute override is missing: .cs.cso": ok + shader_patch(exts=(".txt",)), + "s002 graphics override is missing: .vs.cso, .ps.cso": + ok + shader_patch("s002", pipeline="graphics", exts=(".txt", ".gs.cso")), + "files[0] file must be a non-empty string": ok + good.replace('file = "s001.txt"', 'file = ""'), + **{f"files[0] file {name!r} must be a bare file name": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("sub/s001.txt", "sub\\s001.txt", "/s001.txt", "C:s001.txt", "..", ".")}, + # The runtime that reads these files runs on Windows: names it can't hold, shortens or opens as a device. + **{f"files[0] file {name!r} has a character a Windows file name cannot hold": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("a*b", "a?b", "a<b", "a>b", "a|b", 'a"b', "a\tb")}, + "files[0] file 'a\\x01b' has a character": ok + good.replace('file = "s001.txt"', 'file = "a\\u0001b"'), + **{f"files[0] file {name!r} ends in a dot or a space, which Windows drops": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") for name in ("s001.txt.", "s001.txt ")}, + **{f"files[0] file {name!r} is a Windows device name": + ok + good.replace('file = "s001.txt"', f"file = '{name}'") + for name in ("NUL", "CON.txt", "Com1", "nul .txt", "CONIN$", "conout$.txt", + "COM\u00b9", "lpt\u00b3.cso")}, + "files[0] sha256 must be 64 lowercase hex digits": ok + good.replace( + hashlib.sha256(b"s001.txt").hexdigest(), hashlib.sha256(b"s001.txt").hexdigest().upper()), + "patches s001 and s002 override the same key 00c0ffee0badf00d": ok + good + shader_patch("s002"), + "has unknown keys: rva": ok + good.replace('key = "', 'rva = 0x1000\nkey = "'), + "[[patch]] 1 is missing: files": ok + good[:good.index("files = ")], + "kind 'shaders' is not supported": ok + good.replace('"shader"', '"shaders"'), + } + for message, case in cases.items(): + with self.subTest(message): + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(case) + self.assertIn(message, str(caught.exception)) + # A device name only as a prefix, a space inside a name and a leading dot are still file names. + for name in ("console.txt", "nulls.cso", "a b.txt", "com10.txt", "conin.txt", ".s001.txt"): + with self.subTest(name): + _, patches = patch_manifest.parse(ok + good.replace('file = "s001.txt"', f"file = '{name}'")) + self.assertEqual(patches[-1]["files"][0]["file"], name) + + def test_shader_revision_forms_match_the_runtime(self): + # The runtime's current revision of each pipeline has the loader's form, so a bump (a new <n>) still loads. + # Whether a manifest names the current revision is for a later consumer to check against the runtime. + draw = (ROOT / "src/startup_stubs/d3d12_draw.inl").read_text(encoding="utf-8") + mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") + found = { + "graphics": re.findall(r'constexpr char revision\[\] = "(x2w-startup-shader-[^"]*)";', draw), + "compute": re.findall(r'constexpr char compute_revision\[\] = "([^"]*)";', draw), + "mesh86": re.findall(r'constexpr char revision\[\] = "([^"]*)";', mesh86), + } + self.assertEqual(set(found), set(patch_manifest.PIPELINES)) + for pipeline, revisions in found.items(): + with self.subTest(pipeline): + self.assertEqual(len(revisions), 1, revisions) + self.assertTrue(patch_manifest.REVISIONS[pipeline].fullmatch(revisions[0]), revisions[0]) + + def test_shader_files_match_the_runtime(self): + # The translation files each pipeline's loader in the runtime reads for one key: cache_path(..., L"", key, ext) + # and mesh86's load_stage(ext, ...). The fixed rectangle geometry stage, mesh86 pixel stage + # and Python compute source are optional. + reads = re.compile(r'(?:cache_path\(\w+, L"", [\w.]+, |load_stage\()L"(\.[a-z0-9.]+)"') + sources = {"graphics": "d3d12_draw.inl", "compute": "d3d12_compute_dispatch.inl", "mesh86": "mesh86_cache.inl"} + self.assertEqual(set(sources), set(patch_manifest.PIPELINES)) + for pipeline, name in sources.items(): + text = (ROOT / "src/startup_stubs" / name).read_text(encoding="utf-8") + with self.subTest(pipeline): + self.assertEqual(set(reads.findall(text)), set(patch_manifest.PIPELINES[pipeline][1])) + graphics = (ROOT / "src/startup_stubs/d3d12_draw.inl").read_text(encoding="utf-8") + self.assertIn("else if (tr.fixed_rectangle_on_disk) {", graphics) + self.assertEqual(set(patch_manifest.PIPELINES["graphics"][1]) - set(patch_manifest.PIPELINES["graphics"][2]), + {".gs.cso"}) + mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") + self.assertIn('(!request.ps.empty() && !load_stage(L".ps.cso", ps))', mesh86) + self.assertEqual(set(patch_manifest.PIPELINES["mesh86"][1]) - set(patch_manifest.PIPELINES["mesh86"][2]), + {".ps.cso"}) + compute = (ROOT / "src/startup_stubs/d3d12_compute_dispatch.inl").read_text(encoding="utf-8") + self.assertIn("if (output == x2w::NativeComputeOutput::unmarked) {", compute) + self.assertEqual(set(patch_manifest.PIPELINES["compute"][1]) - set(patch_manifest.PIPELINES["compute"][2]), + {".cs.hlsl"}) + + def test_deep_nesting_is_refused(self): + def nested(depth): + return "x = " + "[" * depth + "]" * depth + "\n" + manifest_text(self.digest, self.original) + + # Shape control: a shallow array gets past tomllib and is refused only for its unknown key. + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(nested(50)) + self.assertIn("manifest has unknown keys: x", str(caught.exception)) + # Twice the recursion limit, set here so a runner that raised it cannot parse the array: refused, not a + # RecursionError. The CLI runs in a new interpreter, whose limit is the default 1000. + limit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, limit) + sys.setrecursionlimit(1000) + with self.assertRaises(ValueError) as caught: + patch_manifest.parse(nested(2000)) + self.assertIn("manifest is nested too deeply to parse", str(caught.exception)) + self.manifest.write_text(nested(2000), encoding="utf-8", newline="\n") + result = self.cli(self.input) + self.assertEqual(result.returncode, 1, result.stdout) + self.assertEqual(result.stdout, "") + self.assertIn("patch manifest: manifest is nested too deeply to parse", result.stderr) + self.assertNotIn("Traceback", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pe_package_preflight_cli_check.py b/tests/pe_package_preflight_cli_check.py new file mode 100644 index 0000000000..18f488a2c7 --- /dev/null +++ b/tests/pe_package_preflight_cli_check.py @@ -0,0 +1,582 @@ +#!/usr/bin/env python3 +"""Synthetic PE32+ CLI, deterministic scan, and error-handling suite for tools/pe_package_preflight.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "pe_package_preflight.py" +sys.path.insert(0, str(TOOLS_DIR)) +import pe_package_preflight # noqa: E402 + + +IMAGE_BASE = 0x180000000 +RAW_OFFSET = 0x200 +SECTION_RVA = 0x1000 +SECTION_SIZE = 0x1000 + + +def _build_pe32_plus( + *, + imports: tuple[tuple[str, str, str | int], ...] = (), + exports: tuple[tuple[str | None, str | None], ...] = (), + machine: int = 0x8664, +) -> bytes: + """Build a minimal synthetic PE32+ image with optional exports and normal/delay imports.""" + rdata = bytearray(SECTION_SIZE) + cursor = 0 + + def alloc(size: int, align: int = 4) -> int: + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = SECTION_RVA + cursor + if cursor + size > len(rdata): + raise AssertionError("synthetic .rdata overflow") + cursor += size + return rva + + def put(rva: int, blob: bytes) -> None: + offset = rva - SECTION_RVA + rdata[offset:offset + len(blob)] = blob + + export_rva = export_size = 0 + if exports: + code_rva = alloc(4, 4) + put(code_rva, b"\xC3\x90\x90\x90") + functions = [] + named_entries = [] + for idx, (symbol, forwarder) in enumerate(exports): + if forwarder is not None: + fwd_blob = forwarder.encode("ascii") + b"\0" + fwd_rva = alloc(len(fwd_blob), 2) + put(fwd_rva, fwd_blob) + functions.append(fwd_rva) + else: + functions.append(code_rva) + if symbol is not None: + name_blob = symbol.encode("ascii") + b"\0" + name_rva = alloc(len(name_blob), 2) + put(name_rva, name_blob) + named_entries.append((symbol, idx, name_rva)) + named_entries.sort(key=lambda item: item[0]) + + eat_rva = alloc(4 * len(functions), 4) + put(eat_rva, b"".join(struct.pack("<I", rva) for rva in functions)) + names_rva = alloc(max(4, 4 * len(named_entries)), 4) + ordinals_rva = alloc(max(2, 2 * len(named_entries)), 2) + if named_entries: + put(names_rva, b"".join(struct.pack("<I", item[2]) for item in named_entries)) + put(ordinals_rva, b"".join(struct.pack("<H", item[1]) for item in named_entries)) + + dll_name_rva = alloc(16, 2) + put(dll_name_rva, b"synthetic.dll\0") + export_rva = alloc(40, 4) + put( + export_rva, + struct.pack( + "<2I2H7I", + 0, 0, 0, 0, dll_name_rva, 1, + len(functions), len(named_entries), + eat_rva, names_rva, ordinals_rva, + ), + ) + export_size = 40 + + module_rvas = {} + for module in sorted({module for _, module, _ in imports}): + raw = module.encode("ascii") + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + module_rvas[module] = rva + + hint_rvas = {} + for kind, module, symbol in imports: + if isinstance(symbol, int): + continue + raw = struct.pack("<H", 0) + symbol.encode("ascii") + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + hint_rvas[(kind, module, symbol)] = rva + + groups: dict[tuple[str, str], list[str | int]] = {} + for kind, module, symbol in imports: + groups.setdefault((kind, module), []).append(symbol) + + tables = {} + for key in sorted(groups): + values = [] + for sym in groups[key]: + if isinstance(sym, int): + values.append((1 << 63) | sym) + else: + values.append(hint_rvas[(key[0], key[1], sym)]) + blob = b"".join(struct.pack("<Q", v) for v in [*values, 0]) + lookup = alloc(len(blob), 8) + put(lookup, blob) + iat = alloc(len(blob), 8) + put(iat, blob) + tables[key] = (lookup, iat) + + normal_groups = sorted(k for k in groups if k[0] == "normal") + delay_groups = sorted(k for k in groups if k[0] == "delay") + normal_rva = normal_size = delay_rva = delay_size = 0 + + if normal_groups: + normal_size = 20 * (len(normal_groups) + 1) + normal_rva = alloc(normal_size, 4) + for idx, key in enumerate(normal_groups): + lookup, iat = tables[key] + put(normal_rva + idx * 20, struct.pack("<5I", lookup, 0, 0, module_rvas[key[1]], iat)) + + if delay_groups: + delay_size = 32 * (len(delay_groups) + 1) + delay_rva = alloc(delay_size, 4) + for idx, key in enumerate(delay_groups): + lookup, iat = tables[key] + put(delay_rva + idx * 32, struct.pack("<8I", 1, module_rvas[key[1]], 0, iat, lookup, 0, 0, 0)) + + pe_off = 0x80 + buf = bytearray(RAW_OFFSET + SECTION_SIZE) + buf[0:2] = b"MZ" + struct.pack_into("<I", buf, 60, pe_off) + buf[pe_off:pe_off + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_off + 4, machine, 1, 0, 0, 0, 0xF0, 0x2022) + opt = pe_off + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + 0x20B, 14, 0, 0, SECTION_SIZE, 0, 0, SECTION_RVA, IMAGE_BASE, + 0x1000, 0x200, 6, 0, 0, 0, 6, 0, 0, 0x2000, RAW_OFFSET, + 0, 3, 0, 0x100000, 0x1000, 0x100000, 0x1000, 0, 16, + ) + dd = opt + 112 + if export_rva: + struct.pack_into("<II", buf, dd + 0 * 8, export_rva, export_size) + if normal_groups: + struct.pack_into("<II", buf, dd + 1 * 8, normal_rva, normal_size) + if delay_groups: + struct.pack_into("<II", buf, dd + 13 * 8, delay_rva, delay_size) + + sec_off = opt + 0xF0 + struct.pack_into( + "<8sIIIIIIHHI", + buf, + sec_off, + b".rdata\0\0", SECTION_SIZE, SECTION_RVA, SECTION_SIZE, RAW_OFFSET, 0, 0, 0, 0, 0x40000040, + ) + buf[RAW_OFFSET:RAW_OFFSET + SECTION_SIZE] = rdata + return bytes(buf) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = pe_package_preflight.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _make_synthetic_package(pkg: Path) -> None: + sub = pkg / "sub" + sub.mkdir() + (pkg / "app.exe").write_bytes( + _build_pe32_plus( + imports=( + ("normal", "helper.dll", "HelperInit"), + ("delay", "helper.dll", 2), + ("normal", "kernel32.dll", "ExitProcess"), + ) + ) + ) + (sub / "helper.dll").write_bytes( + _build_pe32_plus( + imports=(("normal", "core.dll", "CoreTick"),), + exports=(("HelperInit", None), (None, None)), + ) + ) + (sub / "core.dll").write_bytes( + _build_pe32_plus(exports=(("CoreTick", None),)) + ) + + +class PePackagePreflightCliPositiveTests(unittest.TestCase): + def test_stdout_and_atomic_output_with_zero_leftover_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + # 1) Stdout mode (in-process + subprocess). + code, out, err = _run_main([str(pkg), "app.exe"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + report = json.loads(out) + self.assertEqual(report["schema"], 1) + self.assertEqual(report["entry"], "app.exe") + self.assertEqual(report["summary"]["images_scanned"], 3) + self.assertEqual(report["summary"]["images_reachable"], 3) + self.assertEqual(report["summary"]["static_imports"], 4) + self.assertEqual(report["summary"]["bundled_failures"], 0) + self.assertEqual(report["summary"]["external_unverified"], 1) + self.assertEqual(report["ignored_images"], []) + self.assertFalse(report["reachable"]["sub/helper.dll"]["conditional"]) + self.assertEqual( + report["reachable"]["sub/core.dll"]["path"], + ["app.exe", "sub/helper.dll", "sub/core.dll"], + ) + + proc = _run_subprocess(str(pkg), "app.exe") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), report) + + # 2) Atomic --output creation into nested non-existent directory, 0 leftover temps. + nested_out = base / "reports" / "nested" / "preflight.json" + proc_out = _run_subprocess(str(pkg), "app.exe", "--output", str(nested_out)) + self.assertEqual(proc_out.returncode, 0, proc_out.stderr) + self.assertEqual(proc_out.stdout, "") + self.assertEqual(proc_out.stderr, "") + self.assertEqual(json.loads(nested_out.read_text(encoding="utf-8")), report) + self.assertEqual( + sorted(p.name for p in nested_out.parent.iterdir()), + ["preflight.json"], + ) + + # 3) Atomic replacement of pre-existing output file, 0 leftover temps. + nested_out.write_text("stale content", encoding="utf-8") + code_rep, out_rep, err_rep = _run_main([str(pkg), "app.exe", "--output", str(nested_out)]) + self.assertEqual(code_rep, 0, err_rep) + self.assertEqual(out_rep, "") + self.assertEqual(err_rep, "") + self.assertEqual(json.loads(nested_out.read_text(encoding="utf-8")), report) + self.assertEqual( + sorted(p.name for p in nested_out.parent.iterdir()), + ["preflight.json"], + ) + + # 4) sys.argv forwarding when argv=None and __main__ entrypoint. + cli_argv = [str(TOOL), str(pkg), "app.exe"] + with mock.patch.object(sys, "argv", cli_argv): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(json.loads(out_none), report) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue()), report) + + def test_unsorted_rglob_deterministic_order_and_cutoff(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + a_dir = root / "a_dir" + b_dir = root / "B_dir" + a_dir.mkdir() + b_dir.mkdir() + + entry = a_dir / "first.exe" + second = a_dir / "second.dll" + huge = b_dir / "huge.dll" + entry.write_bytes(b"a" * 100) + second.write_bytes(b"b" * 100) + huge.write_bytes(b"z" * 500) + + # Unsorted rglob puts B_dir/huge.dll first (and ASCII sort puts 'B' < 'a'); + # deterministic casefold sort visits a_dir/first.exe, a_dir/second.dll before B_dir/huge.dll. + unsorted_paths = [huge, second, entry] + with ( + mock.patch.object(Path, "rglob", return_value=iter(unsorted_paths)), + mock.patch.object(pe_package_preflight, "MAX_IMAGE_BYTES", 300), + mock.patch.object(pe_package_preflight, "MAX_IMAGES", 1), + ): + with self.assertRaisesRegex(ValueError, "1024 PE image inspection limit"): + pe_package_preflight._paths(root.resolve()) + + with ( + mock.patch.object(Path, "rglob", return_value=iter(unsorted_paths)), + mock.patch.object(pe_package_preflight, "MAX_IMAGE_BYTES", 300), + mock.patch.object(pe_package_preflight, "MAX_TOTAL_BYTES", 150), + ): + with self.assertRaisesRegex(ValueError, "2 GiB PE inspection limit"): + pe_package_preflight._paths(root.resolve()) + + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) + _make_synthetic_package(pkg) + forward = [pkg / "app.exe", pkg / "sub" / "core.dll", pkg / "sub" / "helper.dll"] + reversed_order = list(reversed(forward)) + with mock.patch.object(Path, "rglob", return_value=iter(forward)): + code_a, out_a, err_a = _run_main([str(pkg), "app.exe"]) + with mock.patch.object(Path, "rglob", return_value=iter(reversed_order)): + code_b, out_b, err_b = _run_main([str(pkg), "app.exe"]) + self.assertEqual(code_a, 0, err_a) + self.assertEqual(code_b, 0, err_b) + self.assertEqual(out_a, out_b) + + +class PePackagePreflightCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_root_is_dir_and_non_empty_entry_validated_before_inspect(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + not_a_dir = base / "regular.txt" + not_a_dir.write_text("not a directory", encoding="utf-8") + + with mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError("inspect called for invalid package/entry"), + ): + self._assert_clean_failure( + [str(base / "missing_pkg"), "app.exe"], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self._assert_clean_failure( + [str(not_a_dir), "app.exe"], + expected_code=1, + fragments=("pe_package_preflight:", "Package root must be a directory"), + ) + for blank_entry in ("", " "): + with self.subTest(entry=blank_entry): + self._assert_clean_failure( + [str(pkg), blank_entry], + expected_code=1, + fragments=("pe_package_preflight:", "Entry must be"), + ) + + for blank_entry in ("", " "): + with self.subTest(direct_entry=blank_entry): + with self.assertRaisesRegex(ValueError, "Entry must be"): + pe_package_preflight.inspect(pkg, blank_entry) + + def test_output_collision_dir_inside_pkg_rejected_before_temp_staging(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + file_parent = base / "collision.txt" + file_parent.write_text("keep-me", encoding="utf-8") + out_dir = base / "existing_dir" + out_dir.mkdir() + + cases = ( + ("parent_regular_file", file_parent / "report.json", ("not a directory",)), + ("ancestor_regular_file", file_parent / "nested" / "report.json", ("not a directory",)), + ("output_is_dir", out_dir, ("directory",)), + ("output_empty_string", Path(""), ("directory",)), + ("output_inside_pkg_root", pkg, ("outside the inspected package",)), + ("output_inside_pkg_file", pkg / "report.json", ("outside the inspected package",)), + ("output_inside_pkg_nested", pkg / "new_sub" / "report.json", ("outside the inspected package",)), + ) + for label, target, frags in cases: + with self.subTest(case=label): + with ( + mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError(f"inspect called for {label}"), + ), + mock.patch.object( + pe_package_preflight.tempfile, + "TemporaryDirectory", + side_effect=AssertionError(f"temp staging called for {label}"), + ), + ): + argv = [str(pkg), "app.exe", "--output", "" if label == "output_empty_string" else str(target)] + self._assert_clean_failure( + argv, + expected_code=1, + fragments=("pe_package_preflight:", *frags), + ) + + self.assertEqual(file_parent.read_text(encoding="utf-8"), "keep-me") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertFalse((pkg / "report.json").exists()) + self.assertFalse((pkg / "new_sub").exists()) + + def test_output_symlink_rejected_before_temp_staging(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + out_dir = base / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.json" + real_target.write_text("untouched", encoding="utf-8") + live_link = out_dir / "live_link.json" + dangling_link = out_dir / "dangling_link.json" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "nonexistent.json") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + for label, target in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + with ( + mock.patch.object( + pe_package_preflight, + "inspect", + side_effect=AssertionError(f"inspect called for {label}"), + ), + mock.patch.object( + pe_package_preflight.tempfile, + "TemporaryDirectory", + side_effect=AssertionError(f"temp staging called for {label}"), + ), + ): + self._assert_clean_failure( + [str(pkg), "app.exe", "--output", str(target)], + expected_code=1, + fragments=("pe_package_preflight:", "symlink"), + ) + + self.assertEqual(real_target.read_text(encoding="utf-8"), "untouched") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.json", "live_link.json", "real.json"], + ) + + def test_temp_staging_replace_failure_leaves_zero_leftover_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + _make_synthetic_package(pkg) + + out_dir = base / "out_dir" + out_dir.mkdir() + out_file = out_dir / "report.json" + out_file.write_text("original", encoding="utf-8") + + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(pkg), "app.exe", "--output", str(out_file)], + expected_code=1, + fragments=("pe_package_preflight:", "simulated replace failure"), + check_subprocess=False, + ) + + self.assertEqual(out_file.read_text(encoding="utf-8"), "original") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json"]) + + def test_invalid_pe_and_missing_entry_do_not_create_output_dir_or_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + (pkg / "bad.exe").write_bytes(b"not a valid PE") + absent_out = base / "should_not_exist" / "report.json" + + self._assert_clean_failure( + [str(pkg), "bad.exe", "--output", str(absent_out)], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self.assertFalse(absent_out.parent.exists()) + + _make_synthetic_package(pkg) + self._assert_clean_failure( + [str(pkg), "missing.exe", "--output", str(absent_out)], + expected_code=1, + fragments=("pe_package_preflight:",), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) + _make_synthetic_package(pkg) + cases = ( + ([], ("required",)), + ([str(pkg)], ("required",)), + ([str(pkg), "app.exe", "--bogus-flag"], ("unrecognized",)), + ([str(pkg), "app.exe", "--output"], ("expected one argument",)), + ) + for argv, frags in cases: + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/pe_run_package_cli_check.py b/tests/pe_run_package_cli_check.py index f5658890c8..caf1b2e5c5 100644 --- a/tests/pe_run_package_cli_check.py +++ b/tests/pe_run_package_cli_check.py @@ -79,7 +79,94 @@ def _run_cli(argv: list[str]) -> tuple[int, str, str]: return rc, stdout.getvalue(), stderr.getvalue() +SEM_FAILCRITICALERRORS = 0x0001 + + +def _thread_error_mode() -> int: + kernel = pe_run_package.C.WinDLL("kernel32") + get_mode = kernel.GetThreadErrorMode + get_mode.argtypes, get_mode.restype = [], pe_run_package.W.DWORD + return get_mode() + + +def _set_thread_error_mode(mode: int) -> int: + """Set the calling thread's error mode and return the previous one.""" + kernel = pe_run_package.C.WinDLL("kernel32", use_last_error=True) + set_mode = kernel.SetThreadErrorMode + set_mode.argtypes = [pe_run_package.W.DWORD, pe_run_package.C.POINTER(pe_run_package.W.DWORD)] + set_mode.restype = pe_run_package.W.BOOL + previous = pe_run_package.W.DWORD() + if not set_mode(mode, pe_run_package.C.byref(previous)): + raise OSError(pe_run_package.C.get_last_error(), "SetThreadErrorMode failed") + return previous.value + + +class _RecordingKernel: + """kernel32 for pe_run_package.run whose LoadLibraryExW records the thread error mode of each call.""" + + def __init__(self, real, modes): + self._real = real + self._modes = modes + + def __getattr__(self, name): + function = getattr(self._real, name) + if name != "LoadLibraryExW": + return function + modes = self._modes + + class Recorder: + argtypes = restype = None + + def __call__(self, *args): + function.argtypes, function.restype = self.argtypes, self.restype + modes.append((args[0], _thread_error_mode())) + return function(*args) + + return Recorder() + + class PeRunPackageCliTests(unittest.TestCase): + def test_provider_load_has_no_critical_error_dialog(self): + # A provider that is not a loadable image (here a 0-byte file) raises a critical error inside + # LoadLibraryExW. Without SEM_FAILCRITICALERRORS Windows shows a modal "Bad Image" dialog and the + # load blocks until someone closes it. The flag must be set for the provider load only: the + # thread's previous mode is back once the run returns, so the guest keeps the host's setting. + # The thread starts the run with mode 0: a host that already set the flag (as some CI runners + # do) would otherwise make the restore check pass whether or not the runner restores the mode. + real_win_dll = pe_run_package.C.WinDLL + modes = [] + + def win_dll(name, *args, **kwargs): + library = real_win_dll(name, *args, **kwargs) + return _RecordingKernel(library, modes) if name == "kernel32" else library + + system_kernel = Path(pe_run_package.os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "kernel32.dll" + with tempfile.TemporaryDirectory() as tmp: + pkg = Path(tmp) / "package" + pkg.mkdir() + (pkg / "app.exe").write_bytes(_minimal_pe32_plus()) + mapper = Path(tmp) / "mapper.dll" + mapper.write_bytes(b"") + original = _set_thread_error_mode(0) + try: + before = _thread_error_mode() + with mock.patch.object(pe_run_package.C, "WinDLL", win_dll): + rc, stdout, stderr = _run_cli([ + str(mapper), str(pkg), "app.exe", "--preflight-only", + "--shim", "kernel32.dll", str(system_kernel), + ]) + after = _thread_error_mode() + finally: + _set_thread_error_mode(original) + self.assertEqual(before, 0, "the thread error mode could not be cleared before the run") + self.assertEqual(rc, 0, stderr) + self.assertEqual(json.loads(stdout)["missing"], []) + self.assertEqual([Path(path).name.casefold() for path, _ in modes], ["kernel32.dll"]) + for path, mode in modes: + self.assertTrue(mode & SEM_FAILCRITICALERRORS, + f"LoadLibraryExW({path}) ran with thread error mode {mode:#x}") + self.assertEqual(after, before, "the thread error mode was not restored after the run") + def test_positive_preflight_in_process_and_subprocess(self): with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 2c10983562..e5cc0628c3 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -355,11 +355,11 @@ def expect_unbound_operand(function, program, bank, register, index, offset, ins "-fvk-s-shift", "32", "0", "-fvk-u-shift", "48", "0"] -def compile_shader(compiler, source, shader, *, listing=None, mode=F32_DENORM_MODE, ieee=True): +def compile_shader(compiler, source, shader, *, listing=None, mode=F32_DENORM_MODE, ieee=True, unoptimized=False): """Run DXC on one translated shader under an explicit binary32 denormal mode.""" # DXC accepts -denorm only at shader model 6.2 and above; ps_6_2 is the minimum target. - command = [compiler, *(["-Gis"] if ieee else []), "-denorm", mode, - "-T", "ps_6_2", "-E", "main", "-Fo", shader] + command = [compiler, *(["-Gis"] if ieee else []), *(["-Od"] if unoptimized else []), + "-denorm", mode, "-T", "ps_6_2", "-E", "main", "-Fo", shader] if listing is not None: command += ["-Fc", listing] if SPIRV_ARGS is not None: @@ -8764,7 +8764,8 @@ def check_literal_fma_draw(directory, compiler, renderer, backend): def check_scalar_pair_reads() -> None: program = with_scalar_pair_reads() source = translate(program) - for field in ("(params[0].w * sample", "max(params[15].z, ", "(params[1].x + sample", "(params[1].y - sample", + for field in ("(params[0].w * sample", "minmax_zero32(params[15].z, alu22, true)", + "(params[1].x + sample", "(params[1].y - sample", "= params[1].z;", "(params[15].w * alu"): assert field in source, field @@ -9816,9 +9817,11 @@ def three_way_case(directory, low, high, cap, middle, *, name="three_way.case"): def check_three_way_templates(): """The HLSL forms must pick the expected operand for every operand order, NaN operands included.""" names = {"min": min_num, "max": max_num, "asuint": lambda x: struct.unpack("<I", struct.pack("<f", x))[0]} + names.update(minmax_zero32=lambda a, b, maximum: (max_num if maximum else min_num)(a, b), + true=True, false=False) # Evaluate the med3_32 helper of the preamble: its NaN test on the encoding, then the selected form. helper = (r"^float med3_32\(float a, float b, float c\) \{\n uint top = (.+);\n" - r" return top > (0x[0-9a-f]+)u \? (.+) : (.+);\n\}") + r" return top > (0x[0-9a-f]+)u\n \? (.+)\n : (.+);\n\}") for top, limit, nan_form, finite_form in re.findall(helper, pixel_aot.PREAMBLE, re.M): top = re.sub(r"(0x[0-9a-f]+)u\b", r"\1", top) names["med3_32"] = lambda a, b, c: eval( @@ -9955,7 +9958,7 @@ def check_dpp_cvt_refusals(): "DPP operand v255 is read before it is written"), ("v_cvt_pkrtz_f16_f32_dpp v16, v12, v13 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf bound_ctrl:1", "Unsupported DPP16 modifier"), - ("v_cvt_norm_i16_f16_dpp v55, v12 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + ("v_rcp_f16_dpp v55, v12 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "Unsupported instruction"), ("v_cvt_f32_i32_dpp v12, v255 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "DPP operand v255 is read before it is written"), @@ -10462,7 +10465,7 @@ def check_dpp_f16_contract_controls(): ("v_cvt_f16_f32_dpp v23, -v20 dpp8:[1,2,3,0,5,6,7,4]", "Source modifiers are not allowed on -v20"), (f"v_cvt_f16_f32_dpp v23, v70 {identity}", "DPP operand v70 is read before it is written"), (f"v_cvt_f16_f32_dpp v256, v20 {identity}", "Invalid f16 DPP operation"), - (f"v_cvt_norm_i16_f16_dpp v23, v20 {identity}", "Unsupported instruction"), + (f"v_rsq_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_rcp_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_exp_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_log_f16_dpp v23, v20 {identity}", "Unsupported instruction"), @@ -11022,8 +11025,8 @@ def check_sdwa_f16_controls(): (proven_pair, f"v_log_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_sqrt_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_rcp_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), - (proven_pair, f"v_cvt_norm_i16_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), - (proven_pair, f"v_cvt_norm_u16_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_rsq_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_sin_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), ): expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) # Scheduling: pending scalar load, outstanding sample, and non-entry EXEC mask must refuse. @@ -11267,6 +11270,10 @@ def check_sdwa_int_extra_controls(): elif name == "mul24": for helper in ("mul24_u32(", "mul24_i32(", "mul24_hi_u32(", "mul24_hi_i32("): assert helper in hlsl, (helper, hlsl) + elif name == "co_ci": + add = next(i for i, line in enumerate(prog) if line.startswith("v_add_co_ci_u32_sdwa ")) + sub = next(i for i, line in enumerate(prog) if line.startswith("v_sub_co_ci_u32_sdwa ")) + assert f"uint co{sub} = cmp{add} ? ~(sb{sub} - sa{sub}) : cp{sub};" in hlsl for old, new in SDWA_INT_EXTRA_MUTATIONS[name]: mutated = [line.replace(old, new) for line in prog] assert mutated != prog, (name, old) @@ -11591,6 +11598,300 @@ def check_f16_exact_extra_draw(directory, compiler, renderer, backend): return 0 +# Binary16 normalized integer conversion fixtures covering 10 forms (v_cvt_norm_i16_f16 and +# v_cvt_norm_u16_f16 across VOP1, VOP3, DPP16, DPP8, and SDWA) under the static finite-proof contract (#839). +F16_CVT_NORM_PROGRAMS = { + "plain_e32": [ + "v_mov_b32_e32 v20, 0x3800", # +0.5 (exact tie: 16383.5 -> 16384, 32767.5 -> 32768) + "v_mov_b32_e32 v21, 0xb800", # -0.5 (exact tie: -16383.5 -> -16384, u16 clamps to 0) + "v_mov_b32_e32 v22, 0x3801", # +0.50048828125 (double-rounding discriminator: 16399, 32799) + "v_mov_b32_e32 v23, 0x03ff", # largest positive subnormal (+6.097555e-5 -> +2, 4) + "v_cvt_norm_i16_f16_e32 v25, v20", + "v_cvt_norm_u16_f16_e32 v26, v20", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e32 v27, v21", + "v_cvt_norm_u16_f16_e32 v28, v21", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e32 v29, v22", + "v_cvt_norm_u16_f16_e32 v30, v22", + "v_mov_b32_sdwa v14, v29 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v30 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e32 v31, v23", + "v_cvt_norm_u16_f16_e32 v32, v23", + "v_mov_b32_sdwa v15, v31 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v32 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], + "plain_e64": [ + "s_mov_b32 s60, 0xbc00", # -1.0 (i16 -> -32767 = 0x8001, u16 -> 0) + "s_mov_b32 s61, 0x4000", # +2.0 (clamps to +32767 = 0x7fff, 65535 = 0xffff) + "v_mov_b32_e32 v20, 0xb801", # -0.50048828125 (double-rounding discriminator: -16399 = 0xbff1) + "v_mov_b32_e32 v21, 0x0100", # +2^-16 subnormal (i16 -> 0, u16 -> 1) + "v_cvt_norm_i16_f16_e64 v25, s60", + "v_cvt_norm_u16_f16_e64 v26, s60", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e64 v27, s61", + "v_cvt_norm_u16_f16_e64 v28, s61", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e64 v29, v20", + "v_cvt_norm_u16_f16_e64 v30, 0.5", + "v_mov_b32_sdwa v14, v29 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v30 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_e64 v31, v21", + "v_cvt_norm_u16_f16_e64 v32, v21", + "v_mov_b32_sdwa v15, v31 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v32 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], + "dpp16": [ + "v_mov_b32_e32 v20, 0xb801", # -0.50048828125 + "v_mov_b32_e32 v21, 0x83ff", # -0x03ff subnormal + "v_mov_b32_e32 v22, 0x3800", # +0.5 + "v_mov_b32_e32 v23, 0xbc00", # -1.0 + "v_cvt_norm_i16_f16_dpp v25, |v20| quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_cvt_norm_u16_f16_dpp v26, |v20| quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_dpp v27, -v22 quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "v_cvt_norm_u16_f16_dpp v28, -v23 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_dpp v29, v21 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_cvt_norm_u16_f16_dpp v30, |v21| quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v14, v29 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v30 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_dpp v31, v23 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_cvt_norm_u16_f16_dpp v32, v22 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v15, v31 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v32 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], + "dpp8": [ + "v_mov_b32_e32 v20, 0x3800", # +0.5 + "v_mov_b32_e32 v21, 0xb800", # -0.5 + "v_mov_b32_e32 v22, 0x3802", # +0.5009765625 (double-rounding discriminator: 16415, 32831) + "v_mov_b32_e32 v23, 0xc000", # -2.0 + "v_cvt_norm_i16_f16_dpp v25, v20 dpp8:[1,2,3,0,5,6,7,4]", + "v_cvt_norm_u16_f16_dpp v26, v20 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_dpp v27, v21 dpp8:[1,2,3,0,5,6,7,4]", + "v_cvt_norm_u16_f16_dpp v28, v21 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_dpp v29, v22 dpp8:[1,2,3,0,5,6,7,4]", + "v_cvt_norm_u16_f16_dpp v30, v22 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v14, v29 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v30 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_dpp v31, v23 dpp8:[1,2,3,0,5,6,7,4]", + "v_cvt_norm_u16_f16_dpp v32, v23 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v15, v31 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v32 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], + "sdwa": [ + "v_mov_b32_e32 v20, 0x3801b800", # WORD_0=-0.5, WORD_1=+0.50048828125 + "v_mov_b32_e32 v21, 0x03ffbc00", # WORD_0=-1.0, WORD_1=+0x03ff subnormal + "s_mov_b32 s60, 0x40000100", # WORD_0=+2^-16 subnormal, WORD_1=+2.0 + "v_cvt_norm_i16_f16_sdwa v12, v20 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_u16_f16_sdwa v12, |v20| dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_cvt_norm_i16_f16_sdwa v13, v20 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_norm_u16_f16_sdwa v13, v20 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_cvt_norm_i16_f16_sdwa v14, -v21 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_norm_u16_f16_sdwa v14, v21 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_cvt_norm_i16_f16_sdwa v24, s60 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_mov_b32_sdwa v15, v24 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_u16_f16_sdwa v15, s60 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], +} +F16_CVT_NORM_EXPECTED = { + "plain_e32": (0x80004000, 0x0000c000, 0x801f400f, 0x00040002), + "plain_e64": (0x00008001, 0xffff7fff, 0x8000bff1, 0x00010000), + "dpp16": (0x801f400f, 0xffffc000, 0x0004fffe, 0x80008001), + "dpp8": (0x80004000, 0x0000c000, 0x803f401f, 0x00008001), + "sdwa": (0x8000c000, 0x801f400f, 0x0004fffe, 0x00017fff), +} +F16_CVT_NORM_MUTATIONS = { + "plain_e32": ( + ("v_cvt_norm_i16_f16_e32 v25, v20", "v_cvt_norm_u16_f16_e32 v25, v20"), + ("v_cvt_norm_u16_f16_e32 v28, v21", "v_cvt_norm_i16_f16_e32 v28, v21"), + ("v_cvt_norm_i16_f16_e32 v29, v22", "v_cvt_norm_i16_f16_e32 v29, v20"), + ("v_cvt_norm_u16_f16_e32 v32, v23", "v_cvt_norm_i16_f16_e32 v32, v23"), + ), + "plain_e64": ( + ("v_cvt_norm_i16_f16_e64 v25, s60", "v_cvt_norm_u16_f16_e64 v25, s60"), + ("v_cvt_norm_u16_f16_e64 v28, s61", "v_cvt_norm_i16_f16_e64 v28, s61"), + ("v_cvt_norm_i16_f16_e64 v29, v20", "v_cvt_norm_i16_f16_e64 v29, s60"), + ("v_cvt_norm_u16_f16_e64 v32, v21", "v_cvt_norm_i16_f16_e64 v32, v21"), + ), + "dpp16": ( + ("v_cvt_norm_i16_f16_dpp v25, |v20|", "v_cvt_norm_i16_f16_dpp v25, v20"), + ("v_cvt_norm_u16_f16_dpp v28, -v23", "v_cvt_norm_u16_f16_dpp v28, v23"), + ("v_cvt_norm_u16_f16_dpp v30, |v21|", "v_cvt_norm_u16_f16_dpp v30, v21"), + ("v_cvt_norm_i16_f16_dpp v31, v23", "v_cvt_norm_u16_f16_dpp v31, v23"), + ), + "dpp8": ( + ("v_cvt_norm_i16_f16_dpp v25, v20", "v_cvt_norm_u16_f16_dpp v25, v20"), + ("v_cvt_norm_u16_f16_dpp v28, v21", "v_cvt_norm_i16_f16_dpp v28, v21"), + ("v_cvt_norm_i16_f16_dpp v29, v22", "v_cvt_norm_i16_f16_dpp v29, v20"), + ("v_cvt_norm_i16_f16_dpp v31, v23", "v_cvt_norm_u16_f16_dpp v31, v23"), + ), + "sdwa": ( + ("v_cvt_norm_u16_f16_sdwa v12, |v20| dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_cvt_norm_u16_f16_sdwa v12, |v20| dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ("v_cvt_norm_u16_f16_sdwa v12, |v20|", "v_cvt_norm_u16_f16_sdwa v12, v20"), + ("v_cvt_norm_i16_f16_sdwa v14, -v21", "v_cvt_norm_i16_f16_sdwa v14, v21"), + ("v_cvt_norm_u16_f16_sdwa v15, s60 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_cvt_norm_u16_f16_sdwa v15, s60 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), +} + + +def f16_cvt_norm_reference(signed, bits): + """Independent exact rational reference for v_cvt_norm_{i16,u16}_f16 using fractions.Fraction.""" + from fractions import Fraction + x = struct.unpack("<e", struct.pack("<H", bits & 0xffff))[0] + fx = Fraction(x) + lo, hi, scale = (Fraction(-1), Fraction(1), 32767) if signed else (Fraction(0), Fraction(1), 65535) + p = max(lo, min(hi, fx)) * scale + n, d = p.numerator, p.denominator + neg = n < 0 + an = -n if neg else n + q, r = divmod(an, d) + if 2 * r > d or (2 * r == d and (q & 1)): + q += 1 + return ((-q) if neg else q) & 0xffff + + +def check_f16_cvt_norm_controls(): + """Positive, exhaustive-reference, and negative controls for all 10 v_cvt_norm_{i16,u16}_f16 forms.""" + identity = "quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf" + sdwa1 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0" + # Exhaustive check of translator's integer model against independent Fraction reference over all 63,488 finite f16s. + for bits in range(0x10000): + if ((bits >> 10) & 0x1f) == 0x1f: + continue + for signed in (True, False): + assert pixel_aot.f16_cvt_norm_result(signed, bits) == f16_cvt_norm_reference(signed, bits), (signed, hex(bits)) + for name, body in F16_CVT_NORM_PROGRAMS.items(): + prog = uncompressed_export(body) + hlsl = translate_f16(prog) + for helper in ("cvt_norm_i16_f16(", "cvt_norm_u16_f16("): + assert helper in hlsl, (name, helper) + for old, new in F16_CVT_NORM_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + assert translate_f16(mutated) != hlsl, (name, old, new) + # Pin the exact DPP16/DPP8 permutation -> HLSL quad-intrinsic mapping on single-instruction + # cvt_norm programs (catches ignore, rotation, X<->Y swap, and lane-order transpositions). + src = ["v_mov_b32_e32 v20, 0x3800"] + for op in ("v_cvt_norm_i16_f16_dpp", "v_cvt_norm_u16_f16_dpp"): + for dpp_spec, expected_counts, lane_order in ( + ("quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", (0, 0, 0, 0), None), + ("quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", (1, 0, 0, 0), None), + ("quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", (0, 1, 0, 0), None), + ("quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", (0, 0, 1, 0), None), + ("quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf", (0, 0, 0, 1), (2,)), + ("quad_perm:[0,2,1,3] row_mask:0xf bank_mask:0xf", (0, 0, 0, 4), (0, 2, 1, 3)), + ("dpp8:[1,2,3,0,5,6,7,4]", (0, 0, 0, 4), (1, 2, 3, 0)), + ): + hlsl = translate_f16(uncompressed_export([*src, f"{op} v24, v20 {dpp_spec}"])) + counts = tuple( + hlsl.count(name) + for name in ("QuadReadAcrossX(", "QuadReadAcrossY(", "QuadReadAcrossDiagonal(", "QuadReadLaneAt(") + ) + assert counts == expected_counts, (op, dpp_spec, counts, expected_counts) + if lane_order is not None and len(lane_order) == 1: + assert f", {lane_order[0]});" in hlsl, (op, dpp_spec, hlsl) + elif lane_order is not None: + p0, p1, p2, p3 = lane_order + pat = ( + rf"\(\(\(dpp\d+_l{p0} & dpp\d+_even\) \| \(dpp\d+_l{p1} & ~dpp\d+_even\)\) & dpp\d+_top\) \| " + rf"\(\(\(dpp\d+_l{p2} & dpp\d+_even\) \| \(dpp\d+_l{p3} & ~dpp\d+_even\)\) & ~dpp\d+_top\)" + ) + assert re.search(pat, hlsl), (op, dpp_spec, lane_order, hlsl) + # Bare and _e32 spellings lower identically. + for bare, e32 in ( + ("v_cvt_norm_i16_f16 v24, v20", "v_cvt_norm_i16_f16_e32 v24, v20"), + ("v_cvt_norm_u16_f16 v24, v20", "v_cvt_norm_u16_f16_e32 v24, v20"), + ): + assert translate_f16(uncompressed_export([*src, bare])) == translate_f16(uncompressed_export([*src, e32])) + # Entry profile (half_denorm="preserve") and HALF_RTZ controls across all 5 encodings. + for inst, op in ( + ("v_cvt_norm_i16_f16_e32 v24, v20", "v_cvt_norm_i16_f16_e32"), + ("v_cvt_norm_u16_f16_e64 v24, 0.5", "v_cvt_norm_u16_f16_e64"), + (f"v_cvt_norm_i16_f16_dpp v24, v20 {identity}", "v_cvt_norm_i16_f16_dpp"), + ("v_cvt_norm_u16_f16_dpp v24, v20 dpp8:[1,2,3,0,5,6,7,4]", "v_cvt_norm_u16_f16_dpp"), + (f"v_cvt_norm_i16_f16_sdwa v24, v20 {sdwa1}", "v_cvt_norm_i16_f16_sdwa"), + (f"v_cvt_norm_u16_f16_sdwa v24, v20 {sdwa1}", "v_cvt_norm_u16_f16_sdwa"), + ): + prog = uncompressed_export([*src, inst, f"v_mov_b32_sdwa v12, v24 {sdwa1}"]) + expect_value_error(translate_int, prog, "binary16 denormal mode unknown at entry") + expect_value_error(translate_f16, [HALF_RTZ, *prog], f"under round toward zero: {op}") + # Chaining: low16 output feeds audited 16-bit integer readers; binary16 and high-half readers refuse it. + translate_f16(uncompressed_export([*src, "v_cvt_norm_i16_f16_e32 v24, v20", "v_cvt_f16_i16_e32 v25, v24"])) + translate_f16(uncompressed_export([*src, "v_cvt_norm_u16_f16_e64 v24, v20", "v_add_nc_u16 v25, v24, 1"])) + for prefix, bad, message in ( + ([], "v_cvt_norm_i16_f16_e64 v24, s44", "binary16 operand lacks a finite proof: s44"), + (["v_mov_b32_e32 v20, 0x7c00"], "v_cvt_norm_i16_f16_e32 v24, v20", "binary16 operand is not finite: v20"), + (["v_mov_b32_e32 v20, 0x7e00"], f"v_cvt_norm_u16_f16_sdwa v24, v20 {sdwa1}", "binary16 operand is not finite: v20"), + (["v_mov_b32_e32 v20, 0xfc00"], f"v_cvt_norm_i16_f16_dpp v24, v20 {identity}", "binary16 operand is not finite: v20"), + (src, "v_cvt_norm_i16_f16_e64 v24, -v20", "Unsupported binary16 source modifier -v20"), + (src, "v_cvt_norm_u16_f16_e64 v24, v20 clamp", "Unsupported instruction"), + (src, "v_cvt_norm_i16_f16_e64 v24, v20 mul:2", "Unsupported instruction"), + (src, "v_cvt_norm_i16_f16_dpp v24, -v20 dpp8:[1,2,3,0,5,6,7,4]", "Source modifiers are not allowed on -v20"), + (src, "v_cvt_norm_u16_f16_dpp v24, |v20| dpp8:[1,2,3,0,5,6,7,4]", "Source modifiers are not allowed on |v20|"), + (src, f"v_cvt_norm_i16_f16_sdwa v24, sext(v20) {sdwa1}", "Unsupported binary16 SDWA source modifier: sext(v20)"), + (src, "v_cvt_norm_u16_f16_sdwa v24, v20 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0", + "UNUSED_SEXT is not lowered"), + (src, "v_cvt_norm_i16_f16_sdwa v24, v20 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", + "Unsupported binary16 SDWA source selection: BYTE_0"), + (src, "v_cvt_norm_u16_f16_sdwa v24, v20 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "Unsupported 16-bit SDWA destination selection: BYTE_0"), + ([*src, "v_cvt_norm_i16_f16_e32 v24, v20"], "v_cvt_f32_f16_e32 v12, v24", "Expected a numeric register"), + ([*src, "v_cvt_norm_u16_f16_e32 v24, v20"], + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "Reads the undefined high half of a 16-bit result"), + ): + expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) + # Scheduling: pending load, sample overlap, and non-entry EXEC mask must refuse. + base = uncompressed_export([]) + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(translate_f16, base[:sample + 1] + ["v_cvt_norm_i16_f16_e64 v12, 0.5"] + base[sample + 1:], + "Write overlaps an outstanding sample") + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(translate_f16, base[:masked] + ["v_cvt_norm_u16_f16_e64 v24, 0.5"] + base[masked:], + "Invalid binary16 to integer conversion operation") + + +def check_f16_cvt_norm_draw(directory, compiler, renderer, backend): + check_f16_cvt_norm_controls() + for name, body in F16_CVT_NORM_PROGRAMS.items(): + prog = uncompressed_export(body) + expected = F16_CVT_NORM_EXPECTED[name] + src_path = directory / f"f16_cvt_norm_{name}.hlsl" + cso_path = directory / f"f16_cvt_norm_{name}.cso" + pass_case = directory / f"f16_cvt_norm_{name}_pass.case" + pass_case.write_bytes(bytes(256) + struct.pack("<4I", *expected) * 64 + b"\x01") + src_path.write_text(translate_f16(prog), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + # Compile unoptimized (-Od) under -denorm ftz as well so DXC keeps the integer conversion + # arithmetic in DXIL instead of constant-folding the statically proven operands to immediates. + compile_shader(compiler, src_path, cso_path, mode="ftz", unoptimized=True) + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + for old, new in F16_CVT_NORM_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + src_path.write_text(translate_f16(mutated), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cso_path, [pass_case]) + print(f"f16_cvt_norm {name} mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"f16_cvt_norm {name} mutation {old!r} -> {new!r} escaped detection") + return 0 + + # SDWA binary32 conversion, frexp_exp, and packed-RTZ fixtures covering 13 SDWA forms: # f32->int32 (cvt_{i32,u32,flr_i32,rpi_i32}_f32_sdwa, frexp_exp_i32_f32_sdwa), # int->f32 (cvt_f32_{i32,u32,ubyte0..3}_sdwa, cvt_off_f32_i4_sdwa), and v_cvt_pkrtz_f16_f32_sdwa. @@ -17728,10 +18029,10 @@ def refuse(line, message, translator=translate_f16): for line in ("v_cvt_f16_i16_e64 v24, v18 clamp", "v_cvt_f16_u16_e64 v24, v18 clamp", "v_cvt_f16_i16_e64 v24, v18 mul:2", "v_cvt_f16_u16_e64 v24, v18 div:2", "v_cvt_f16_i16_e64 v24, v18 op_sel:[0,1]", "v_cvt_f16_i16_e64 v24, -v18 clamp", "v_cvt_f16_i16_e32 v24, v18 clamp", "v_cvt_f16_u16_e32 v24, 1 clamp", - "v_cvt_norm_i16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_cvt_norm_u16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", - "v_cvt_norm_i16_f16_e32 v24, v18", "v_cvt_norm_u16_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", + "v_rcp_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -18091,10 +18392,10 @@ def refuse(line, message, translator=translate_f16): for line in ("v_cvt_i16_f16_e64 v24, v18 clamp", "v_cvt_u16_f16_e64 v24, v18 clamp", "v_cvt_i16_f16_e64 v24, v18 mul:2", "v_cvt_u16_f16_e64 v24, v18 div:2", "v_cvt_i16_f16_e64 v24, v18 mul:4", "v_cvt_i16_f16_e64 v24, v18 op_sel:[0,1]", "v_cvt_i16_f16_e64 v24, -v18 clamp", "v_cvt_i16_f16_e32 v24, v18 clamp", "v_cvt_u16_f16_e32 v24, 1.0 clamp", - "v_cvt_norm_i16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_cvt_norm_u16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", - "v_cvt_norm_i16_f16_e32 v24, v18", "v_cvt_norm_u16_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): + "v_rcp_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") # Entry profile: unknown or an unsupported declaration refuses every spelling of both kinds. for kind in ("i16", "u16"): @@ -18904,9 +19205,9 @@ def _check_controls_inline(directory): must_reject(translate, [line.replace(old, new) for line in shaping()]) source = translate(three_way()) for expected in ("med3_32(params[1].z, sample16.y, sample16.x)", - "max(max(sample16.x, sample16.z), sample16.y)", + "minmax_zero32(minmax_zero32(sample16.x, sample16.z, true), sample16.y, true)", "med3_32(sample16.x, params[0].w, params[1].x)", - "min(min(abs(params[1].y), sample16.y), alu"): + "minmax_zero32(minmax_zero32(abs(params[1].y), sample16.y, false), alu22, false)"): assert expected in source, expected for old, new in (("v_med3_f32 v12, v12, s44, s45", "v_med3_f32 v12, v12, s44"), ("v_med3_f32 v15, s47", "v_med3_i32 v15, |s47|"), @@ -20191,6 +20492,7 @@ def _check_controls_inline(directory): "check_sdwa_f16_controls", "check_sdwa_int_extra_controls", "check_f16_exact_extra_controls", + "check_f16_cvt_norm_controls", "check_sdwa_cvt_controls", "check_smem_pointer_controls", "check_masked_controls", @@ -20846,6 +21148,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append((uncompressed_export(SDWA_F16_CVT_F32_BODY), translate_f16)) fixtures.extend((uncompressed_export(body), translate_int) for body in SDWA_INT_EXTRA_PROGRAMS.values()) fixtures.extend((uncompressed_export(body), translate_f16) for body in F16_EXACT_EXTRA_PROGRAMS.values()) + fixtures.extend((uncompressed_export(body), translate_f16) for body in F16_CVT_NORM_PROGRAMS.values()) fixtures.extend((uncompressed_export(body), translate_int) for body in SDWA_CVT_PROGRAMS.values()) fixtures.append((sdwa_pkrtz_program(), translate)) fixtures.extend((bit_program(op), translate) for op in BIT_OPERATIONS) @@ -24162,7 +24465,7 @@ def check_three_way_draw(directory, compiler, renderer, backend): run_pixel_batch(renderer, backend, shader, cases) # Desktop min and max alone skip a NaN operand instead of taking V_MIN3_F32 of the rest. text = source.read_text(encoding="ascii") - nan_ignored = text.replace("? min(min(a, b), c) :", "? max(min(a, b), min(max(a, b), c)) :") + nan_ignored = text.replace("return top > 0x7f800000u", "return false") assert nan_ignored != text source.write_text(nan_ignored, encoding="ascii") compile_shader(compiler, source, shader) @@ -27594,7 +27897,7 @@ def main(): "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", - "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): + "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-f16-cvt-norm", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, "draw-dpp-cvt": check_dpp_cvt_draw, @@ -27660,6 +27963,7 @@ def main(): "draw-sdwa-f16": check_sdwa_f16_draw, "draw-sdwa-int-extra": check_sdwa_int_extra_draw, "draw-f16-exact-extra": check_f16_exact_extra_draw, + "draw-f16-cvt-norm": check_f16_cvt_norm_draw, "draw-sdwa-cvt": check_sdwa_cvt_draw}[mode] return draw(directory, *args) except subprocess.CalledProcessError as error: diff --git a/tests/pixel_compare_grad_check.py b/tests/pixel_compare_grad_check.py new file mode 100644 index 0000000000..4858ebabfb --- /dev/null +++ b/tests/pixel_compare_grad_check.py @@ -0,0 +1,256 @@ +"""Check gfx1030 2D depth comparisons with explicit FP32 or G16 gradients.""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, write_record +from pixel_compare_check import pixel_aot, prefix, sampler_moves, sampler_words, tail, translate +from pixel_compare_lod_check import ( + OFFSET, first_mismatch, probe_shader_profile, reference_rows, run_draw, sampler, write_case, +) +from pixel_compare_sample_check import must_reject +from pixel_sample_gradient_check import WAVE64 + + +FORMS = { + "image_sample_c_d": 3, + "image_sample_c_d_o": 2, + "image_sample_c_d_g16": 5, + "image_sample_c_d_o_g16": 4, +} +DISTINCT = (0.125, -0.25, 0.5, 1.0) +ZERO = (0.0, 0.0, 0.0, 0.0) +DRAWS = ((8, (0.0, -0.25, 0.0, 0.0)), (16, (0.0, 0.0, 0.25, 0.0))) + + +def has_offset(op): + return op.removesuffix("_g16").endswith("_o") + + +def program(op, slopes, *, scale=1, packed="0x3e01", compare="s60", words=None): + words = sampler() if words is None else words + first = FORMS[op] + g16 = op.endswith("_g16") + if g16: + slopes = struct.unpack("<2I", struct.pack("<4e", *slopes)) + else: + slopes = struct.unpack("<4I", struct.pack("<4f", *slopes)) + reference = first + has_offset(op) + lines = prefix() + if scale == 2: + lines = ["s_mov_b64 s[50:51], exec", "s_wqm_b64 exec, exec", *lines, + "v_add_f32_e32 v8, v8, v8", "v_add_f32_e32 v9, v9, v9", + "s_and_b64 exec, exec, s[50:51]"] + lines += sampler_moves(words) + if has_offset(op): + lines.append(f"v_mov_b32_e32 v{first}, {packed}") + lines.append(f"v_mov_b32_e32 v{reference}, {compare}") + inline = {0: "0", 0x3f000000: "0.5", 0x3f800000: "1.0"} + lines.extend(f"v_mov_b32_e32 v{reg}, {inline.get(value, hex(value))}" + for reg, value in enumerate(slopes, reference + 1)) + return [*lines, f"{op} v12, v[{first}:9], s[28:35], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D", + *tail(reference=f"v{reference}")] + + +def controls(): + def lower(lines, words): + return pixel_aot.lower(lines, 20, 24, words, constant_descriptor=64) + + words = sampler() + for op, first in FORMS.items(): + lines = program(op, DISTINCT) + hlsl = lower(lines, words) + assert "tex.SampleCmpGrad(samp, float2(uv.x, uv.y)," in hlsl, op + assert (", int2(1, -2))" in hlsl) == has_offset(op), op + assert ("widen16(asuint(" in next(line for line in hlsl.splitlines() + if "tex.SampleCmpGrad(" in line)) == op.endswith("_g16"), op + nsa = "[" + ", ".join(f"v{reg}" for reg in range(first, 10)) + "]" + for old, new, diagnostic in ( + (f"v[{first}:9]", f"v[{first}:8]", "Descriptor or vector width mismatch"), + (f"v[{first}:9]", nsa, "Unsupported instruction"), + ("dmask:0x1", "dmask:0x2", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D a16", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D d16", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_3D", "Unsupported instruction"), + ): + must_reject(lambda: lower([line.replace(old, new) for line in lines], words), diagnostic) + for state, diagnostic in ( + (sampler_words("LESS", "point"), "MAX_LOD 1"), + (sampler_words("LESS", "point", w1=0x100000, w2=2 << 26), "point mip"), + (sampler_words("LESS", "bilinear", w1=0x100000, w2=1 << 26), "point XY"), + ): + must_reject(lambda: lower(program(op, DISTINCT, words=state), state), diagnostic) + grad = first + has_offset(op) + 1 + for value, diagnostic in ( + ("s61", "must be statically known"), + ("0x7c007c00" if op.endswith("_g16") else "0x7f800000", "must be normal or zero"), + ("0x00010000" if op.endswith("_g16") else "0x00000001", "must be normal or zero"), + ): + bad = [f"v_mov_b32_e32 v{grad}, {value}" if line.startswith(f"v_mov_b32_e32 v{grad},") else line + for line in lines] + must_reject(lambda: lower(bad, words), diagnostic) + image = next(i for i, line in enumerate(lines) if line.startswith(f"{op} ")) + lines.insert(image, f"image_sample_c_lz v{grad}, v[7:9], s[28:35], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D") + # Copy the ready comparison reference to the address of the first sample. + lines.insert(image, f"v_mov_b32_e32 v7, v{first + has_offset(op)}") + must_reject(lambda: lower(lines, words), "Comparison gradient used before vmcnt wait") + if has_offset(op): + must_reject(lambda: lower(program(op, DISTINCT, packed="8"), words), "[-8, 7]") + + +def check_llvm_codegen(directory, llc, op): + g16 = op.endswith("_g16") + suffix = ".o" if has_offset(op) else "" + precision = "f16" if g16 else "f32" + intrinsic = f"llvm.amdgcn.image.sample.c.d{suffix}.2d.f32.{precision}.f32" + slope_type = "half" if g16 else "float" + offset_decl = "i32, " if has_offset(op) else "" + offset_arg = "i32 15873, " if has_offset(op) else "" + slopes = ("half 0xH3000, half 0xHB400, half 0xH3800, half 0xH3C00" if g16 else + "float 0.125, float -0.25, float 0.5, float 1.0") + ir = directory / "gradient-order.ll" + ir.write_text(f'''target triple = "amdgcn-amd-amdpal" + declare float @{intrinsic}(i32 immarg, {offset_decl}float, {', '.join([slope_type] * 4)}, + float, float, <8 x i32>, <4 x i32>, i1 immarg, i32 immarg, i32 immarg) + define amdgpu_ps float @gradient_order(<8 x i32> inreg %r, <4 x i32> inreg %s, float %u, float %v) {{ + %value = call float @{intrinsic}(i32 1, {offset_arg}float 0.375, {slopes}, float %u, float %v, + <8 x i32> %r, <4 x i32> %s, i1 false, i32 0, i32 0) + ret float %value + }} + ''', encoding="ascii") + asm = subprocess.run([llc, "-mcpu=gfx1030", f"-mattr={WAVE64},-nsa-encoding", "-o", "-", ir], + check=True, capture_output=True, text=True).stdout + match = re.search(rf"\b{op} v\d+, v\[(\d+):(\d+)\].*dim:SQ_RSRC_IMG_2D[^\r\n]*", asm) + assert match and " a16" not in match[0], asm + first, last = map(int, match.groups()) + expected = [0x3e01] if has_offset(op) else [] + expected += [0x3ec00000] # Compare reference precedes both gradient vectors. + expected += ([0xb4003000, 0x3c003800] if g16 else list(struct.unpack("<4I", struct.pack("<4f", *DISTINCT)))) + assert last - first + 1 == len(expected) + 2, match[0] + for reg, bits in enumerate(expected, first): + literal = re.search(rf"v_mov_b32_e32 v{reg}, (\S+)", asm) + assert literal, asm + value = literal[1] + actual = int(value, 0) if value.startswith("0x") else struct.unpack("<I", struct.pack("<f", float(value)))[0] + assert actual == bits, (reg, bits, actual, asm) + + +def check_binary(directory, assembler, objcopy, library, llc): + words = sampler() + for op, first in FORMS.items(): + check_llvm_codegen(directory, llc, op) + lines = program(op, DISTINCT) + # LLVM MC uses an eight-VGPR tuple for the six/seven-word encoding. + assembly = [line.replace(f"v[{first}:9]", f"v[{first}:{first + 7}]") + if line.startswith(f"{op} ") and first in (3, 4) else line for line in lines] + code = assemble(directory, assembler, objcopy, assembly, cpu="gfx1030", features=WAVE64) + decoded = pixel_aot.disassemble(code, library, cpu=b"gfx1030", features=WAVE64.encode(), offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [ + line for line in lines if line.startswith("image_")] + expected = translate(lines, words) + assert translate(decoded, words) == expected + archive, output = directory / "fixture.bin", directory / "fixture.hlsl" + archive.write_bytes(envelope(code)) + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", "--constant-descriptor", "0x40", + "--sampler-words", *(hex(word) for word in words), "--output", output], check=True) + assert output.read_text(encoding="utf-8") == expected + + +def check_glsl(directory, glslang, validator, disassembler): + """Cross-check the source-level compare/Grad/ConstOffset contract in SPIR-V.""" + source, binary = directory / "gradient.frag", directory / "gradient.spv" + source.write_text('''#version 450 +layout(set=0, binding=0) uniform sampler2DShadow depth_tex; +layout(location=0) in vec2 uv; +layout(location=0) out vec2 depth; +void main() { + vec3 coord = vec3(uv, 0.375); + vec2 dx = vec2(0.125, -0.25), dy = vec2(0.5, 1.0); + depth = vec2(textureGrad(depth_tex, coord, dx, dy), + textureGradOffset(depth_tex, coord, dx, dy, ivec2(1, -2))); +} +''', encoding="ascii") + subprocess.run([glslang, "-V", "-Os", "-o", binary, source], check=True) + subprocess.run([validator, binary], check=True) + asm = subprocess.run([disassembler, binary], check=True, capture_output=True, text=True).stdout + samples = re.findall(r"OpImageSampleDrefExplicitLod \S+ \S+ \S+ (.+)", asm) + assert len(samples) == 2, asm + plain, offset = [sample.split() for sample in samples] + assert plain[1] == "Grad" and offset[1] == "Grad|ConstOffset", asm + assert plain[0] == offset[0] and plain[2:] == offset[2:4] and len(offset) == 5, asm + constants = dict(re.findall(r"(%\S+) = OpConstant \S+ (\S+)", asm)) + vectors = {name: (lo, hi) for name, lo, hi in + re.findall(r"(%\S+) = OpConstantComposite \S+ (%\S+) (%\S+)\s*\n", asm)} + assert float(constants[plain[0]]) == 0.375, asm + assert tuple(float(constants[component]) for vector in plain[2:] for component in vectors[vector]) == DISTINCT, asm + assert tuple(int(constants[component]) for component in vectors[offset[4]]) == OFFSET, asm + + +def check_dxil_order(directory, args, op): + source, shader, assembly = (directory / name for name in ("order.hlsl", "order.cso", "order.ll")) + source.write_text(translate(program(op, DISTINCT, compare="0.375"), sampler()), encoding="ascii") + subprocess.run([*args, "-Fo", shader, "-Fc", assembly, source], check=True) + text = assembly.read_text(encoding="utf-8") + call = re.search(r"call .* @dx\.op\.sampleCmpGrad\.f32\(([^)]+)\)", text) + assert call, text + operands = call[1].split(", ") + if has_offset(op): + assert operands[7:9] == ["i32 1", "i32 -2"], call[0] + assert float(operands[10].split()[1]) == 0.375, call[0] + assert tuple(float(operands[i].split()[1]) for i in (11, 12, 14, 15)) == DISTINCT, call[0] + + +def whole_mip(slopes): + # These cases use one nonzero component. Its footprint is exactly two mip-zero texels. + squared = [sum((8 * component)**2 for component in axis) for axis in (slopes[:2], slopes[2:])] + return {0: 0, 4: 1}[max(squared)] + + +def check_shader(directory, compiler, renderer=None, adapter=None): + args = probe_shader_profile(directory, compiler, "ps_6_8") + source, shader, case, mutation = (directory / name for name in ("grad.hlsl", "grad.cso", "grad.case", "mutation.case")) + for op in FORMS: + check_dxil_order(directory, args, op) + displacement = OFFSET if has_offset(op) else (0, 0) + for size, slopes in DRAWS: + scale = size // 8 + baseline = reference_rows(size, scale, whole_mip(slopes), displacement) + write_case(case, size, baseline) + variants = [("original", slopes, displacement), ("gradient-zero", ZERO, displacement)] + if has_offset(op): + variants.append(("offset-zero", slopes, (0, 0))) + for variant, gradients, offset in variants: + packed = "0x3e01" if offset != (0, 0) else "0" + source.write_text(translate(program(op, gradients, scale=scale, packed=packed), sampler()), + encoding="ascii") + subprocess.run([*args, "-Fo", shader, source], check=True) + if variant == "original": + if renderer: + run_draw(renderer, adapter, "grad", shader, case) + continue + mutated = reference_rows(size, scale, whole_mip(gradients), offset) + mismatch = first_mismatch(size, baseline, mutated) + if renderer: + write_case(mutation, size, mutated) + run_draw(renderer, adapter, "grad", shader, mutation) + run_draw(renderer, adapter, "grad", shader, case, mismatch) + print(f"{op} {size} {variant} {'readback' if renderer else 'CPU prediction'} {mismatch}") + if renderer: + write_record(os.environ.get("FORM_COVERAGE_RECORD")) + + +if __name__ == "__main__": + controls() + if len(sys.argv) > 1: + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compare-grad-", dir=out) as directory: + {"binary": check_binary, "compile": check_shader, "draw": check_shader, "glsl": check_glsl}[sys.argv[1]]( + Path(directory), *sys.argv[2:]) + print("gfx1030 depth-comparison gradient checks passed") diff --git a/tests/pixel_compare_lod_check.py b/tests/pixel_compare_lod_check.py new file mode 100644 index 0000000000..604f8a15d4 --- /dev/null +++ b/tests/pixel_compare_lod_check.py @@ -0,0 +1,209 @@ +"""Compare gfx1030 explicit LOD and biased depth samples on two depth mips.""" +from fractions import Fraction +import math +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, write_record +from pixel_compare_check import ( + CONSTANT_REFERENCE, D3D12_FILTER, DEPTHS, pixel_aot, prefix, sampler_moves, sampler_words, tail, translate, +) +from pixel_compare_sample_check import must_reject + +FORMS = {"level": ("image_sample_c_l", "image_sample_c_l_o"), + "bias": ("image_sample_c_b", "image_sample_c_b_o")} +FEATURES = "+wavefrontsize64,-wavefrontsize32" +OFFSET = (1, -2) +MIPS = (DEPTHS, [((x * 5 + y * 9 + 8) % 16 * 4 + 1) / 64 for y in range(4) for x in range(4)]) + + +def sampler(): + return sampler_words("LESS", "point", w1=0x100000, w2=1 << 26) + + +def program(op, *, operand="1.0", scale=1, packed="0x3e01", quad=True, words=None): + words = sampler() if words is None else words + lines = prefix() + if quad: + lines = ["s_mov_b64 s[50:51], exec", "s_wqm_b64 exec, exec", *lines] + if scale == 2: + lines += ["v_add_f32_e32 v8, v8, v8", "v_add_f32_e32 v9, v9, v9"] + lines.append("s_and_b64 exec, exec, s[50:51]") + bias = "_b" in op + first, last = (6, 9) if bias else (7, 10) + lines += [*sampler_moves(words), "v_mov_b32_e32 v7, s60", + f"v_mov_b32_e32 v{6 if bias else 10}, {operand}"] + if op.endswith("_o"): + first -= 1 + lines.append(f"v_mov_b32_e32 v{first}, {packed}") + return [*lines, f"{op} v12, v[{first}:{last}], s[28:35], s[40:43] dmask:0x1 dim:SQ_RSRC_IMG_2D", + *tail(reference="v7")] + + +def controls(): + def lower(lines, words): + return pixel_aot.lower(lines, 20, 24, words, constant_descriptor=64) + + words = sampler() + for mode, forms in FORMS.items(): + for op in forms: + hlsl = lower(program(op), words) + method = "SampleCmpBias" if mode == "bias" else "SampleCmpLevel" + assert f"tex.{method}(samp" in hlsl + assert (", int2(1, -2))" in hlsl) == op.endswith("_o") + for operand in ("s61", "0.5", "-1.0"): + must_reject(lambda: lower(program(op, operand=operand), words), "statically 0 or 1") + for state, diagnostic in ( + (sampler_words("LESS", "point"), "MAX_LOD 1"), + (sampler_words("LESS", "point", w1=0x100000, w2=2 << 26), "point mip"), + (sampler_words("LESS", "bilinear", w1=0x100000, w2=1 << 26), "point XY"), + ): + must_reject(lambda: lower(program(op, words=state), state), diagnostic) + for old, new, diagnostic in ( + ("dmask:0x1", "dmask:0x2", "Unsupported instruction"), + ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D a16", "Unsupported instruction"), + ("s_waitcnt vmcnt(0)", "v_add_f32_e32 v12, 0, v12", "outstanding sample"), + ): + lines = [line.replace(old, new) for line in program(op)] + must_reject(lambda: lower(lines, words), diagnostic) + if mode == "bias": + must_reject(lambda: lower(program(op, quad=False), words), "quad provenance") + else: + lower(program(op, quad=False), words) + if op.endswith("_o"): + must_reject(lambda: lower(program(op, packed="8"), words), "[-8, 7]") + + +def binary(directory, assembler, objcopy, library): + words = sampler() + for forms in FORMS.values(): + for op in forms: + lines = program(op, scale=2) + code = assemble(directory, assembler, objcopy, lines, cpu="gfx1030", features=FEATURES) + decoded = pixel_aot.disassemble(code, library, cpu=b"gfx1030", features=FEATURES.encode(), offsets=True) + assert [line for _, line in decoded if line.startswith("image_")] == [ + line for line in lines if line.startswith("image_") + ] + expected = translate(lines, words) + assert translate(decoded, words) == expected + archive, output = directory / "fixture.bin", directory / "fixture.hlsl" + archive.write_bytes(envelope(code)) + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", *(hex(w) for w in words), "--constant-descriptor", "0x40", + "--output", output], check=True) + assert output.read_text(encoding="utf-8") == expected + + +def reference_rows(size, scale, mip, displacement): + width = 8 >> mip + rows = [] + for y in range(size): + for x in range(size): + u = Fraction(width * scale * (2 * x + 1), 2 * size) + displacement[0] + v = Fraction(width * scale * (2 * y + 1), 2 * size) + displacement[1] + tx = min(width - 1, max(0, math.floor(u))) + ty = min(width - 1, max(0, math.floor(v))) + red = float(CONSTANT_REFERENCE < MIPS[mip][ty * width + tx]) + rows.append((red, CONSTANT_REFERENCE, 0.5, 1.0)) + return rows + + +def first_mismatch(size, expected, actual): + for i, (wanted, observed) in enumerate(zip(expected, actual, strict=True)): + if wanted != observed: + want = ",".join(f"{channel:.9g}" for channel in wanted) + got = ",".join(f"{channel:.9g}" for channel in observed) + return f"pixel_mismatch x={i % size} y={i // size} expected={want} actual={got}" + raise AssertionError("Negative control does not distinguish the CPU references") + + +def write_case(path, size, rows): + data = bytearray(struct.pack("<6I", D3D12_FILTER["point"], 2, 8, 8, size, size)) + data.extend(struct.pack("<64f", CONSTANT_REFERENCE, *([0.0] * 63))) + data.extend(struct.pack("<80f", *MIPS[0], *MIPS[1])) + for row in rows: + data.extend(struct.pack("<4f", *row)) + path.write_bytes(data) + + +def probe_shader_profile(directory, compiler, target): + probe = directory / "probe.hlsl" + probe.write_text("float4 main() : SV_Target { return 0; }\n", encoding="ascii") + args = [compiler, "-T", target, "-E", "main"] + result = subprocess.run([*args, "-Fo", directory / "probe.cso", probe], capture_output=True, text=True) + if result.returncode: + diagnostic = result.stdout + result.stderr + if "invalid profile" in diagnostic.lower() or "unable to parse shader model" in diagnostic.lower(): + print(f"skip: DXC does not support {target}: {diagnostic.strip()}") + raise SystemExit(77) + raise AssertionError(diagnostic) + + return args + + +def run_draw(renderer, adapter, mode, shader, case, expected_mismatch=None): + run = subprocess.run([renderer, adapter, f"--check-pixel-compare-{mode}", shader, case], + capture_output=True, text=True) + print(run.stdout, end="") + if run.returncode == 77: + print(run.stderr, end="", file=sys.stderr) + raise SystemExit(77) + if expected_mismatch is None: + assert run.returncode == 0, (run.stdout, run.stderr) + else: + observed = next((line for line in run.stderr.splitlines() if line.startswith("pixel_mismatch ")), None) + assert run.returncode == 1 and observed == expected_mismatch, ( + expected_mismatch, run.stdout, run.stderr) + + +def check_shader(directory, mode, compiler, renderer=None, adapter=None): + target = "ps_6_8" if mode == "bias" else "ps_6_7" + args = probe_shader_profile(directory, compiler, target) + + source = directory / "sample.hlsl" + shader, case = source.with_suffix(".cso"), source.with_suffix(".case") + mutated_case = directory / "mutated.case" + for op in FORMS[mode]: + displacement = OFFSET if op.endswith("_o") else (0, 0) + for size in (8, 16): + # Mip-zero footprint is one texel per pixel, so implicit LOD is zero. + scale = size // 8 + baseline = reference_rows(size, scale, 1, displacement) + write_case(case, size, baseline) + variants = [("original", 1, displacement), ("operand-zero", 0, displacement)] + if op.endswith("_o"): + variants.append(("offset-zero", 1, (0, 0))) + for variant, mip, offset in variants: + lines = program(op, scale=scale, operand=f"{mip}.0", packed="0x3e01" if offset != (0, 0) else "0") + source.write_text(translate(lines, sampler()), encoding="ascii") + subprocess.run([*args, "-Fo", shader, source], check=True) + if variant == "original": + if renderer: + run_draw(renderer, adapter, mode, shader, case) + continue + mutated = reference_rows(size, scale, mip, offset) + mismatch = first_mismatch(size, baseline, mutated) + if renderer: + write_case(mutated_case, size, mutated) + run_draw(renderer, adapter, mode, shader, mutated_case) + run_draw(renderer, adapter, mode, shader, case, mismatch) + print(f"{op} {size} {variant} {'readback' if renderer else 'CPU prediction'} {mismatch}") + if renderer: + write_record(os.environ.get("FORM_COVERAGE_RECORD")) + + +if __name__ == "__main__": + controls() + if len(sys.argv) > 1: + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compare-lod-", dir=out) as directory: + {"binary": binary, "draw": check_shader, "compile": check_shader}[sys.argv[1]]( + Path(directory), *sys.argv[2:]) + print("gfx1030 depth-comparison LOD/bias checks passed") diff --git a/tests/pixel_compare_render.cpp b/tests/pixel_compare_render.cpp index ba0e719a6a..5d82a5cca2 100644 --- a/tests/pixel_compare_render.cpp +++ b/tests/pixel_compare_render.cpp @@ -20,7 +20,7 @@ struct CompareCase { std::vector<std::array<float, 4>> expected; }; -CompareCase read_case(const char* path) +CompareCase read_case(const char* path, UINT mipLevels) { std::ifstream file(path, std::ios::binary); if (!file) throw std::runtime_error("Cannot open comparison case"); @@ -40,7 +40,11 @@ CompareCase read_case(const char* path) c.filter != D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT)) throw std::runtime_error("Invalid comparison case header"); file.read(reinterpret_cast<char*>(c.constants.data()), sizeof(c.constants)); - c.depths.resize(size_t(c.texWidth) * c.texHeight); + if (mipLevels == 2 && (c.texWidth < 2 || c.texHeight < 2)) + throw std::runtime_error("Two-mip comparison case needs both texture dimensions at least 2"); + size_t texels = size_t(c.texWidth) * c.texHeight; + if (mipLevels == 2) texels += size_t(c.texWidth / 2) * (c.texHeight / 2); + c.depths.resize(texels); file.read(reinterpret_cast<char*>(c.depths.data()), std::streamsize(c.depths.size() * sizeof(float))); c.expected.resize(size_t(c.width) * c.height); file.read(reinterpret_cast<char*>(c.expected.data()), std::streamsize(c.expected.size() * 16)); @@ -61,9 +65,10 @@ ComPtr<ID3D12Resource> upload_bytes(ID3D12Device* device, const void* data, UINT } } -void check_pixel_compare(ID3D12Device* device, const char* shader, const char* casePath) +void check_pixel_compare(ID3D12Device* device, const char* shader, const char* casePath, bool twoMips) { - const auto c = read_case(casePath); + const UINT mipLevels = twoMips ? 2 : 1; + const auto c = read_case(casePath, mipLevels); std::ifstream stream(shader, std::ios::binary); std::vector<char> ps{std::istreambuf_iterator<char>(stream), {}}; if (ps.empty()) throw std::runtime_error("Cannot read compiled pixel shader"); @@ -113,16 +118,25 @@ void check_pixel_compare(ID3D12Device* device, const char* shader, const char* c texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; texDesc.Width = c.texWidth; texDesc.Height = c.texHeight; - texDesc.DepthOrArraySize = texDesc.MipLevels = texDesc.SampleDesc.Count = 1; + texDesc.DepthOrArraySize = texDesc.SampleDesc.Count = 1; + texDesc.MipLevels = static_cast<UINT16>(mipLevels); texDesc.Format = DXGI_FORMAT_R32_FLOAT; auto texture = resource(device, texDesc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); - D3D12_PLACED_SUBRESOURCE_FOOTPRINT texLayout{}; + std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, 2> texLayouts{}; UINT64 texBytes = 0; - device->GetCopyableFootprints(&texDesc, 0, 1, 0, &texLayout, nullptr, nullptr, &texBytes); + device->GetCopyableFootprints(&texDesc, 0, mipLevels, 0, texLayouts.data(), nullptr, nullptr, &texBytes); std::vector<char> staged(static_cast<size_t>(texBytes)); - for (UINT y = 0; y < c.texHeight; ++y) - std::memcpy(staged.data() + texLayout.Offset + size_t(y) * texLayout.Footprint.RowPitch, - c.depths.data() + size_t(y) * c.texWidth, c.texWidth * sizeof(float)); + size_t texelOffset = 0; + for (UINT mip = 0; mip < mipLevels; ++mip) { + const auto& layout = texLayouts[mip]; + const UINT width = c.texWidth >> mip; + const UINT height = c.texHeight >> mip; + for (UINT y = 0; y < height; ++y) { + std::memcpy(staged.data() + layout.Offset + size_t(y) * layout.Footprint.RowPitch, + c.depths.data() + texelOffset + size_t(y) * width, width * sizeof(float)); + } + texelOffset += size_t(width) * height; + } auto staging = upload_bytes(device, staged.data(), texBytes); auto constants = upload_bytes(device, c.constants.data(), sizeof(c.constants)); @@ -138,7 +152,7 @@ void check_pixel_compare(ID3D12Device* device, const char* shader, const char* c sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; sampler.MaxAnisotropy = 1; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC(c.func); - sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.MaxLOD = twoMips ? 1.0f : D3D12_FLOAT32_MAX; device->CreateSampler(&sampler, samplers->GetCPUDescriptorHandleForHeapStart()); heapDesc = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; check(device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&rtvs)), "Comparison target heap"); @@ -162,10 +176,13 @@ void check_pixel_compare(ID3D12Device* device, const char* shader, const char* c D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; src.pResource = staging.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = texLayout; dst.pResource = texture.Get(); dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + for (UINT mip = 0; mip < mipLevels; ++mip) { + src.PlacedFootprint = texLayouts[mip]; + dst.SubresourceIndex = mip; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } transition(list, texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); ID3D12DescriptorHeap* heaps[]{views.Get(), samplers.Get()}; list->SetDescriptorHeaps(2, heaps); diff --git a/tests/pixel_sample_clamp_check.py b/tests/pixel_sample_clamp_check.py new file mode 100644 index 0000000000..4a6763e418 --- /dev/null +++ b/tests/pixel_sample_clamp_check.py @@ -0,0 +1,275 @@ +"""Verify the bounded gfx1030 2D per-instruction minimum LOD profile.""" +import math +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import assemble +from pixel_aot_check import envelope, pixel_aot +from pixel_sample_lod_check import base_prefix, compile_ps, export_tail +from pixel_sample_offset_check import draw + + +# Clamp addressing, zero sampler LOD floor and bias, max LOD 2, point XY and mip. +SAMPLER = (0x12, 0x200000, 0x04000000, 0) +FEATURES = "+wavefrontsize64,-wavefrontsize32" +FORMS = { + "image_sample_cl": (0x21, 8), + "image_sample_cl_o": (0x31, 7), + "image_sample_b_cl": (0x26, 7), + "image_sample_b_cl_o": (0x36, 6), +} +SIDE, MIPS = 8, 3 + + +def program(op, *, floor="1.0", bias="0.0", offset="0x3f01", scale=1, runtime=False, sampler=SAMPLER): + _, first = FORMS[op] + prefix = base_prefix(quad_scale=runtime) + if scale != 1: + prefix.insert(prefix.index("s_and_b64 exec, exec, s[50:51]"), f"v_fma_f32 v8, {scale}.0, v8, 0") + body = ["v_mov_b32_e32 v10, " + floor] + if "_b_" in op: + body.append(f"v_mov_b32_e32 v7, {bias}") + if op.endswith("_o"): + body.append(f"v_mov_b32_e32 v{first}, {offset}") + body.append(f"{op} v[12:15], v[{first}:10], s[28:35], s[40:43] dmask:0xf dim:SQ_RSRC_IMG_2D") + for index, value in enumerate(sampler, 40): + prefix[prefix.index(f"s_mov_b32 s{index}, {index - 39}")] = f"s_mov_b32 s{index}, 0x{value:x}" + return prefix + body + export_tail() + + +def translate(lines, *, sampler=SAMPLER, **kwargs): + profile = dict(cpu="gfx1030", sample_clamp_mips=MIPS, constant_descriptor=0x40) | kwargs + return pixel_aot.lower(lines, 20, 24, sampler, **profile) + + +def rejects(lines, message, **kwargs): + try: + translate(lines, **kwargs) + except ValueError as exc: + assert message in str(exc), (message, str(exc)) + else: + raise AssertionError(f"Expected rejection with {message!r}") + + +def check_lowering(): + for op in FORMS: + lines = program(op) + offset = "int2(1, -1)" if op.endswith("_o") else "int2(0, 0)" + method = "SampleBias(samp, float2(uv.x, uv.y), 0.0f" if "_b_" in op else "Sample(samp, float2(uv.x, uv.y)" + assert f"tex.{method}, {offset}, 1.0f);" in translate(lines), op + rejects(lines, "requires --sample-clamp-mips", sample_clamp_mips=None) + rejects(lines, "gfx1030", cpu="gfx1013") + for floor in ("-1.0", "3.0", "0x7f800000", "0x7fc00000"): + rejects(program(op, floor=floor), "known minimum LOD inside the view") + rejects(program(op, floor="s60", runtime=True), "known minimum LOD inside the view") + first = FORMS[op][1] + nsa = "[" + ", ".join(f"v{i}" for i in range(first, 11)) + "]" + rejects([line.replace(f"v[{first}:10]", nsa) for line in lines], "Unsupported instruction") + for old, new, diagnostic in ( + ("dmask:0xf", "dmask:0x7", "requires dmask:0xf"), + ("IMG_2D", "IMG_2D a16", "Unsupported instruction"), + ("IMG_2D", "IMG_2D d16", "Unsupported instruction"), + ("IMG_2D", "IMG_3D", "Unsupported instruction"), + (":10]", ":9]", "width mismatch"), + ("s[40:43]", "s[44:47]", "Unsupported image or sampler binding"), + ): + rejects([line.replace(old, new) for line in lines], diagnostic) + rejects([line for line in lines if line != "s_waitcnt vmcnt(0)"], "Unsupported pack operand") + op = "image_sample_b_cl_o" + for bias in ("-17.0", "16.0", "0x7fc00000"): + rejects(program(op, bias=bias), "known LOD bias") + rejects(program(op, bias="s60", runtime=True), "known LOD bias") + rejects(program(op, offset="0x08"), "outside the DXIL immediate range") + rejects(program(op, offset="0x10000"), "canonical 2D offset word") + assert "int2(-8, 7), 0.75f" in translate(program(op, floor="0.75", offset="0x738")) + for sampler in ((0x13, *SAMPLER[1:]), (0x12, 0x200001, *SAMPLER[2:]), + (0x12, 0x100000, *SAMPLER[2:]), (*SAMPLER[:2], 0x04500000, 0), + (*SAMPLER[:2], 0x04000001, 0)): + rejects(program(op, sampler=sampler), "requires a normalized clamp sampler", sampler=sampler) + + +def texel(mip, x, y): + # Exactly representable as binary16, with independent mip, X and Y channels. + return ((mip + 1) / 4, (x + 1) / 16, (y + 1) / 16, (mip + x + 2 * y + 1) / 32) + + +def mip_for(scale, bias, floor): + lod = max(math.log2(scale) + bias, floor) + return min(MIPS - 1, math.floor(lod + 0.5)) + + +def reference(mip, scale, offset): + size = SIDE >> mip + def point(coord, slope, shift): + return max(0, min(size - 1, math.floor((coord + 0.5) * slope * size / SIDE) + shift)) + return [texel(mip, point(x, scale, offset[0]), point(y, 1, offset[1])) + for y in range(SIDE) for x in range(SIDE)] + + +def case_data(expected): + colors = [texel(m, x, y) for m in range(MIPS) for y in range(SIDE >> m) for x in range(SIDE >> m)] + return struct.pack("<2I", 0, MIPS) + b"".join(struct.pack("<4f", *color) for color in colors + expected) + + +def cases(op): + # Bias-before-floor needs a negative bias and a nonzero floor. A separate + # positive-bias case ensures that bias can also select a mip above the floor. + if "_b_" in op: + yield "raised", 2, -1.0, 2.0, 2 + yield "higher", 1, 2.0, 1.0, 2 + else: + yield "raised", 1, 0.0, 1.0, 1 + yield "higher", 4, 0.0, 1.0, 2 + + +def wrong_cases(op, name, scale, bias, floor): + offset = (1, -1) if op.endswith("_o") else (0, 0) + if name == "raised": + yield "drop_floor", mip_for(scale, bias, 0.0), offset + if "_b_" in op: + yield "floor_before_bias", math.floor(max(math.log2(scale), floor) + bias + 0.5), offset + if offset != (0, 0): + yield "drop_offset", mip_for(scale, bias, floor), (0, 0) + elif "_b_" in op: + yield "drop_bias", mip_for(scale, 0, floor), offset + else: + yield "force_floor", int(floor), offset + + +def check_reference(): + for op in FORMS: + offset = (1, -1) if op.endswith("_o") else (0, 0) + for name, scale, bias, floor, mip in cases(op): + assert mip_for(scale, bias, floor) == mip + correct = reference(mip, scale, offset) + assert len(correct) == 64 and correct[0] == texel(mip, offset[0], 0) + for kind, wrong_mip, wrong_offset in wrong_cases(op, name, scale, bias, floor): + wrong = reference(wrong_mip, scale, wrong_offset) + assert correct[0] != wrong[0], (op, name, kind) + print(f"CPU {op}/{kind} (0,0) expected={correct[0]} actual={wrong[0]}") + + +def check_intrinsic_order(directory, llc): + # Use distinct non-inline literals to observe their assigned VGPRs. Mesa's + # AMD LLVM backend maps NIR min_lod to the final float on these intrinsics. + for op in FORMS: + has_offset, has_bias = op.endswith("_o"), "_b_" in op + mods = op.removeprefix("image_sample").replace("_", ".") + intrinsic = f"llvm.amdgcn.image.sample{mods}.2d.v4f32.f32" + (".f32" if has_bias else "") + operands = [("float", "0.125", 0x3E000000), ("float", "0.375", 0x3EC00000), ("float", "1.25", 0x3FA00000)] + if has_bias: + operands.insert(0, ("float", "-0.75", 0xBF400000)) + if has_offset: + operands.insert(0, ("i32", "16129", 0x3F01)) + types = ", ".join(kind for kind, _, _ in operands) + args = ", ".join(f"{kind} {value}" for kind, value, _ in operands) + ir = directory / f"{op}.ll" + ir.write_text(f'''target triple = "amdgcn-amd-amdpal" +declare <4 x float> @{intrinsic}(i32 immarg, {types}, <8 x i32>, <4 x i32>, i1 immarg, i32 immarg, i32 immarg) +define amdgpu_ps <4 x float> @order(<8 x i32> inreg %rsrc, <4 x i32> inreg %sampler) {{ + %value = call <4 x float> @{intrinsic}(i32 15, {args}, <8 x i32> %rsrc, <4 x i32> %sampler, i1 false, i32 0, i32 0) + ret <4 x float> %value +}} +''', encoding="ascii") + asm = subprocess.run([llc, "-mcpu=gfx1030", f"-mattr={FEATURES},-nsa-encoding", "-o", "-", ir], + check=True, capture_output=True, text=True).stdout + match = re.search(rf"{op} v\[\d+:\d+\], v\[(\d+):(\d+)\].*dim:SQ_RSRC_IMG_2D", asm) + assert match and " a16" not in match[0], asm + first, last = map(int, match.groups()) + assert last - first + 1 == len(operands), match[0] + for reg, (_, _, bits) in enumerate(operands, first): + assert re.search(rf"v_mov_b32_e32 v{reg}, 0x{bits:x}\b", asm), asm + print(f"{op} LLVM intrinsic address order: " + ", ".join(f"0x{bits:08x}" for _, _, bits in operands)) + + +def check_binary(directory, assembler, objcopy, library, llc): + check_intrinsic_order(directory, llc) + for op, (opcode, first) in FORMS.items(): + lines = program(op, bias="-1.0") + # LLVM MC requires the padded sequential tuple for a five-word address. + assembly = [line.replace(f"v[{first}:10]", f"v[{first}:{first + 7}]") + if line.startswith(op + " ") and first == 6 else line for line in lines] + data = assemble(directory, assembler, objcopy, assembly, cpu="gfx1030", features=FEATURES) + decoded = pixel_aot.disassemble(data, library, cpu=b"gfx1030", features=FEATURES.encode(), offsets=True) + image = [(pc, text) for pc, text in decoded if text.startswith("image_")] + assert len(image) == 1 and image[0][1] == next(line for line in lines if line.startswith(op + " ")), image + pc, _ = image[0] + w0, w1 = struct.unpack_from("<2I", data, pc) + assert ((w0 >> 18) & 0x7f, w1 & 0xff, w0 & 0x6) == (opcode, first, 0), (op, hex(w0), hex(w1)) + print(f"{op}: {data[pc:pc + 8].hex(' ')}") + expected = translate(lines) + assert translate(decoded) == expected + archive, output = directory / "fixture.bin", directory / "fixture.hlsl" + archive.write_bytes(envelope(data)) + subprocess.run([sys.executable, "-B", pixel_aot.__file__, archive, "fixture", "--llvm", library, + "--cpu", "gfx1030", "--texture-sgpr", "20", "--interp-sgpr", "24", + "--sampler-words", *(hex(word) for word in SAMPLER), "--sample-clamp-mips", str(MIPS), + "--constant-descriptor", "0x40", + "--output", output], check=True) + assert output.read_text() == expected + + +def direct_hlsl(scale, mip, offset): + return f"""Texture2D<float4> tex : register(t0); +SamplerState samp : register(s0); +float4 main(float4 uv : TEXCOORD0) : SV_Target0 {{ + return tex.SampleLevel(samp, float2(uv.x * {scale}.0f, uv.y), {mip}.0f, int2{offset}); +}} +""" + + +def check_draw(directory, compiler, renderer=None, adapter=None): + case = directory / "sample-clamp.case" + for op in FORMS: + offset = (1, -1) if op.endswith("_o") else (0, 0) + for name, scale, bias, floor, mip in cases(op): + stem = f"{op}_{name}" + source = translate(program(op, scale=scale, bias=str(bias), floor=str(floor))) + shader = compile_ps(compiler, source, directory, stem) + dxil = subprocess.run([compiler, "-dumpbin", shader], check=True, capture_output=True, text=True).stdout + dxop = "sampleBias" if "_b_" in op else "sample" + call = re.search(rf"call .* @dx\.op\.{dxop}\.f32\(([^)\n]+)\)", dxil) + assert call, dxil + args = call[1].split(", ") + assert float(args[-1].removeprefix("float ")) == floor, call[0] + if "_b_" in op: + assert float(args[-2].removeprefix("float ")) == bias, call[0] + if offset != (0, 0): + assert args[7:9] == [f"i32 {component}" for component in offset], call[0] + direct = compile_ps(compiler, direct_hlsl(scale, mip, offset), directory, stem + "_direct") + case.write_bytes(case_data(reference(mip, scale, offset))) + if renderer is not None: + if op == "image_sample_cl" and name == "raised": + draw(renderer, adapter, "--check-pixel-mip-exact", shader, "1") + draw(renderer, adapter, "--check-pixel-gather", shader, case) + draw(renderer, adapter, "--check-pixel-gather", direct, case) + for kind, wrong_mip, wrong_offset in wrong_cases(op, name, scale, bias, floor): + if kind == "drop_floor": + marker = f", {floor}f);" + assert source.count(marker) == 1 + wrong = source.replace(marker, ", 0.0f);") + elif kind == "drop_bias": + wrong = translate(program(op, scale=scale, bias="0.0", floor=str(floor))) + elif kind == "drop_offset": + wrong = translate(program(op, scale=scale, bias=str(bias), floor=str(floor), offset="0")) + else: + wrong = direct_hlsl(scale, wrong_mip, wrong_offset) + mutated = compile_ps(compiler, wrong, directory, f"{stem}_{kind}") + if renderer is not None: + draw(renderer, adapter, "--check-pixel-gather", mutated, case, mismatch=True) + + +if __name__ == "__main__": + check_reference() + check_lowering() + if len(sys.argv) > 1: + mode, *args = sys.argv[1:] + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="sample-clamp-", dir=out) as tmp: + {"binary": check_binary, "compile": check_draw, "draw": check_draw}[mode](Path(tmp), *args) + print("Four 2D minimum-LOD sample forms checked") diff --git a/tests/pixel_sample_gradient_check.py b/tests/pixel_sample_gradient_check.py index 7564a71be5..2d7085759e 100644 --- a/tests/pixel_sample_gradient_check.py +++ b/tests/pixel_sample_gradient_check.py @@ -103,7 +103,7 @@ def check_lowering(): ("SQ_RSRC_IMG_2D", "SQ_RSRC_IMG_2D d16", "Unsupported instruction"), ("image_sample_d ", "image_sample_cd ", "requires gfx1030"), ("image_sample_d ", "image_sample_d_cl ", "Unsupported instruction"), - ("image_sample_d ", "image_sample_c_d ", "Unsupported instruction"), + ("image_sample_d ", "image_sample_c_d_cl ", "Unsupported instruction"), ): reject([line.replace(old, new) for line in lines], diagnostic) undefined = [line for line in lines if not line.startswith("v_mov_b32_e32 v5,")] diff --git a/tests/probe_root_devices_cli_check.py b/tests/probe_root_devices_cli_check.py new file mode 100644 index 0000000000..bc80aa06cf --- /dev/null +++ b/tests/probe_root_devices_cli_check.py @@ -0,0 +1,575 @@ +"""CLI, path-guard, symlink, atomic-replace, and temp-copy mutation suite for tools/probe_root_devices.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import importlib.util +import io +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "probe_root_devices.py" +sys.path.insert(0, str(ROOT / "tools")) + +import probe_root_devices # noqa: E402 + + +IMAGE_BASE = 0x180000000 +SECTION_RVA = 0x1000 +RAW_OFFSET = 0x200 +RAW_SIZE = 0x1000 + +MUTATIONS = ( + ( + "drop_bin_is_dir_guard", + " if not args.bin.is_dir():\n" + ' raise NotADirectoryError(f"--bin path is not a directory: {args.bin}")\n', + " if False:\n" + ' raise NotADirectoryError(f"--bin path is not a directory: {args.bin}")\n', + ), + ( + "drop_control_cso_is_file_guard", + " if not control_path.is_file():\n" + ' raise FileNotFoundError(f"Control shader is missing or not a file: {control_path}")\n', + " if False:\n" + ' raise FileNotFoundError(f"Control shader is missing or not a file: {control_path}")\n', + ), + ( + "drop_dest_is_dir_guard", + " if dest.is_dir():\n" + ' raise IsADirectoryError(f"Output path is a directory: {dest}")\n', + " if False:\n" + ' raise IsADirectoryError(f"Output path is a directory: {dest}")\n', + ), + ( + "drop_dest_inside_build_guard", + " if dest.resolve().is_relative_to(args.build.resolve()):\n" + ' parser.error("Choose an input directory separate from the report directory")\n', + " if False:\n" + ' parser.error("Choose an input directory separate from the report directory")\n', + ), + ( + "drop_tmp_unlink_cleanup", + " if temporary is not None:\n" + " temporary.unlink(missing_ok=True)\n", + " if False:\n" + " temporary.unlink(missing_ok=True)\n", + ), +) + + +def _make_dxbc_rts0(rts0: bytes) -> bytes: + program = struct.pack("<II4sIII", 0, 8, b"DXIL", 0, 16, 4) + b"BC\xc0\xde\x00\x00\x00\x00" + parts = [ + b"DXIL" + struct.pack("<I", len(program)) + program, + b"RTS0" + struct.pack("<I", len(rts0)) + rts0, + ] + table_end = 32 + 4 * len(parts) + offsets = [] + cursor = table_end + for part in parts: + offsets.append(cursor) + cursor += len(part) + body = b"".join(parts) + return ( + b"DXBC" + + bytes(16) + + struct.pack("<III", 1, table_end + len(body), len(parts)) + + struct.pack(f"<{len(parts)}I", *offsets) + + body + ) + + +def _build_pe32_plus(containers: list[bytes]) -> tuple[bytes, list[tuple[int, int]]]: + payload = bytearray(RAW_SIZE) + cursor = 0 + layout = [] + for blob in containers: + cursor = (cursor + 15) & ~15 + rva = SECTION_RVA + cursor + payload[cursor:cursor + len(blob)] = blob + cursor += len(blob) + layout.append((rva, len(blob))) + vsize = max(1, cursor) + size_of_image = SECTION_RVA + ((vsize + 0xFFF) // 0x1000) * 0x1000 + pe_offset = 0x80 + buf = bytearray(RAW_OFFSET + RAW_SIZE) + buf[0:2] = b"MZ" + struct.pack_into("<I", buf, 60, pe_offset) + buf[pe_offset:pe_offset + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_offset + 4, 0x8664, 1, 0, 0, 0, 240, 0x2022) + opt = pe_offset + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + 0x20B, 0, 0, 0, RAW_SIZE, 0, 0, SECTION_RVA, IMAGE_BASE, + 0x1000, 0x200, 6, 0, 0, 0, 6, 0, 0, size_of_image, RAW_OFFSET, + 0, 3, 0, 0, 0, 0, 0, 0, 16, + ) + sec = opt + 240 + struct.pack_into( + "<8sIIIIIIHHI", + buf, + sec, + b".rdata\0\0", vsize, SECTION_RVA, RAW_SIZE, RAW_OFFSET, + 0, 0, 0, 0, 0x40000040, + ) + buf[RAW_OFFSET:RAW_OFFSET + RAW_SIZE] = payload + return bytes(buf), layout + + +def _setup_bin(bin_dir: Path) -> None: + bin_dir.mkdir(parents=True, exist_ok=True) + (bin_dir / "compute_root.cso").write_bytes(b"CTRL_ROOT") + (bin_dir / "compute_tables.cso").write_bytes(b"CTRL_TABLES") + + +def _fake_probe_ok(cmd, *, input, stdout, check, timeout): + warp_only = "--warp-only" in cmd + row = {"cleared": 0, "remaining_flags": 0, "serialize": "0x00000000", "warp": "0x00000000"} + if not warp_only: + row["hardware"] = "0x00000000" + return subprocess.CompletedProcess(cmd, 0, (json.dumps(row) + "\n").encode("utf-8")) + + +def _run_main(mod, argv: list[str], repo: Path, fake_run=_fake_probe_ok) -> tuple[int, str, str]: + out = io.StringIO() + err = io.StringIO() + with ( + mock.patch.object(mod, "PROJECT", repo), + mock.patch.object(mod.subprocess, "run", side_effect=fake_run), + redirect_stdout(out), + redirect_stderr(err), + ): + try: + code = mod.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, out.getvalue(), err.getvalue() + + +def _load_temp_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise AssertionError(f"could not create module spec for {path}") + mod = importlib.util.module_from_spec(spec) + sys.modules[name] = mod + try: + spec.loader.exec_module(mod) + except Exception: + sys.modules.pop(name, None) + raise + return mod + + +class ProbeRootDevicesCliTests(unittest.TestCase): + def _create_fixture(self, base: Path) -> tuple[Path, Path, Path, Path]: + repo = base / "repo" + calls = repo / "out" / "calls" + calls.mkdir(parents=True) + build_dir = base / "build" + build_dir.mkdir() + bin_dir = base / "bin" + _setup_bin(bin_dir) + + rts0 = struct.pack("<6I", 2, 1, 24, 0, 0, 0) + pe_bytes, layout = _build_pe32_plus([_make_dxbc_rts0(rts0)]) + names = probe_root_devices.NAMES + (build_dir / names[0]).write_bytes(pe_bytes) + inventory = { + names[0]: { + "sha256": hashlib.sha256(pe_bytes).hexdigest(), + "containers": [{"rva": hex(layout[0][0]), "bytes": layout[0][1]}], + }, + names[1]: {"sha256": "0" * 64, "containers": []}, + names[2]: {"sha256": "0" * 64, "containers": []}, + } + (calls / "six-apis.json").write_text(json.dumps(inventory), encoding="utf-8") + return repo, calls, build_dir, bin_dir + + def test_atomic_json_write_and_zero_leftover_temps(self) -> None: + for warp_only in (True, False): + with self.subTest(warp_only=warp_only), TemporaryDirectory() as tmp: + repo, calls, build_dir, bin_dir = self._create_fixture(Path(tmp)) + argv = [str(build_dir), "--bin", str(bin_dir)] + if warp_only: + argv.append("--warp-only") + code, out, err = _run_main(probe_root_devices, argv, repo) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + dest_name = "root-devices-warp.json" if warp_only else "root-devices.json" + dest = calls / dest_name + self.assertTrue(dest.is_file()) + self.assertIn(str(dest), out) + self.assertEqual(sorted(p.name for p in calls.iterdir()), sorted([dest_name, "six-apis.json"])) + report = json.loads(dest.read_text(encoding="utf-8")) + self.assertIn(probe_root_devices.NAMES[0], report["images"]) + + def test_upfront_bin_control_build_inventory_and_image_guards(self) -> None: + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + file_bin = base / "bin_as_file" + file_bin.write_text("not a dir", encoding="ascii") + file_build = base / "build_as_file" + file_build.write_text("not a dir", encoding="ascii") + + # Non-dir --bin (missing or file) exits 1 before invoking subprocess.run. + for bad_bin in (base / "missing_bin", file_bin): + code, _, err = _run_main( + probe_root_devices, + ["--warp-only", "--bin", str(bad_bin)], + repo, + fake_run=mock.Mock(side_effect=AssertionError("subprocess called for bad --bin")), + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("--bin path is not a directory", err) + + # Missing or directory control .cso exits 1 before invoking subprocess.run. + bad_cso_bin = base / "bad_cso_bin" + bad_cso_bin.mkdir() + (bad_cso_bin / "compute_root.cso").mkdir() + (bad_cso_bin / "compute_tables.cso").write_bytes(b"ok") + code, _, err = _run_main( + probe_root_devices, + ["--warp-only", "--bin", str(bad_cso_bin)], + repo, + fake_run=mock.Mock(side_effect=AssertionError("subprocess called for dir .cso")), + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Control shader is missing or not a file", err) + + # Non-dir --build exits 1 cleanly. + for bad_build in (base / "missing_build", file_build): + code, _, err = _run_main( + probe_root_devices, + [str(bad_build), "--warp-only", "--bin", str(bin_dir)], + repo, + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Build directory is not a directory", err) + + # Missing or directory six-apis.json exits 1 cleanly. + inv = calls / "six-apis.json" + saved_inv = inv.read_text(encoding="utf-8") + inv.unlink() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Inventory file is missing or not a file", err) + + inv.mkdir() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Inventory file is missing or not a file", err) + inv.rmdir() + inv.write_text(saved_inv, encoding="utf-8") + + # Directory where PE image is expected exits 1 cleanly. + img = build_dir / probe_root_devices.NAMES[0] + saved_img = img.read_bytes() + img.unlink() + img.mkdir() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Build image is missing or not a file", err) + img.rmdir() + img.write_bytes(saved_img) + + # Real missing root_device_probe.exe (unmocked subprocess.run) exits 1 cleanly. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), "--warp-only", "--bin", str(bin_dir)], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("probe_root_devices:", proc.stderr) + + def test_dest_dir_file_parent_and_inside_build_guards(self) -> None: + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + dest = calls / "root-devices-warp.json" + + # dest is a directory + dest.mkdir() + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Output path is a directory", err) + dest.rmdir() + + # dest inside args.build exits 2 + code, _, err = _run_main( + probe_root_devices, [str(repo), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 2) + self.assertNotIn("Traceback", err) + self.assertIn("separate from the report directory", err) + + # dest.parent is a regular file + repo2 = base / "repo_file_parent" + (repo2 / "out").mkdir(parents=True) + (repo2 / "out" / "calls").write_text("keep-parent-file", encoding="ascii") + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo2 + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Output parent is not a directory", err) + self.assertEqual((repo2 / "out" / "calls").read_text(encoding="ascii"), "keep-parent-file") + + def test_atomic_replace_allows_symlink_and_hardlink_dest(self) -> None: + # Restored main behaviour: temporary.replace(dest) renames over the + # directory entry, so it never writes through a symlink or hardlink. + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + dest = calls / "root-devices-warp.json" + inv = calls / "six-apis.json" + inv_text = inv.read_text(encoding="utf-8") + + # dest hardlinked to six-apis.json: report written, inventory unchanged. + dest.hardlink_to(inv) + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 0, err) + self.assertTrue(dest.is_file()) + self.assertFalse(dest.is_symlink()) + self.assertEqual(inv.read_text(encoding="utf-8"), inv_text) + self.assertIn(probe_root_devices.NAMES[0], json.loads(dest.read_text(encoding="utf-8"))["images"]) + + # dest a symlink to six-apis.json: the link is replaced by the report. + dest.unlink() + dest.symlink_to(inv) + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 0, err) + self.assertTrue(dest.is_file()) + self.assertFalse(dest.is_symlink()) + self.assertEqual(inv.read_text(encoding="utf-8"), inv_text) + + # dest.parent a directory symlink to another folder: report lands there. + target = base / "target_calls" + target.mkdir() + (target / "six-apis.json").write_text(inv_text, encoding="utf-8") + repo2 = base / "repo_parent_link" + (repo2 / "out").mkdir(parents=True) + (repo2 / "out" / "calls").symlink_to(target, target_is_directory=True) + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo2 + ) + self.assertEqual(code, 0, err) + self.assertTrue((target / "root-devices-warp.json").is_file()) + self.assertEqual((target / "six-apis.json").read_text(encoding="utf-8"), inv_text) + + def test_guards_fail_before_reading_or_measuring(self) -> None: + # Behavioural pins for the remaining guards (M1-M4): each guard must + # fail before the guarded read/measure is attempted, not merely with a + # different message. A deleted guard lets the guarded operation run, + # which the mocks below turn into a test error. + with TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + real_read_bytes = Path.read_bytes + + def _no_read(name): + def _guarded(path_self, *args, **kwargs): + if path_self.name == name: + raise AssertionError(f"read attempted for {name} despite guard") + return real_read_bytes(path_self, *args, **kwargs) + + return _guarded + + def _no_image_measure(cmd, *, input, stdout, check, timeout): + if input not in (b"CTRL_ROOT", b"CTRL_TABLES"): + raise AssertionError("image probe called despite guard") + return _fake_probe_ok(cmd, input=input, stdout=stdout, check=check, timeout=timeout) + + # M1: missing build fails before the inventory is read, and wins + # over a missing inventory (guard ordering, not just wording). + (calls / "six-apis.json").unlink() + with mock.patch.object(Path, "read_bytes", _no_read("six-apis.json")): + code, _, err = _run_main( + probe_root_devices, + [str(base / "missing_build"), "--warp-only", "--bin", str(bin_dir)], + repo, + ) + self.assertEqual(code, 1) + self.assertIn("Build directory is not a directory", err) + (calls / "six-apis.json").write_text( + json.dumps( + { + probe_root_devices.NAMES[0]: { + "sha256": "0" * 64, + "containers": [], + }, + probe_root_devices.NAMES[1]: {"sha256": "0" * 64, "containers": []}, + probe_root_devices.NAMES[2]: {"sha256": "0" * 64, "containers": []}, + } + ), + encoding="utf-8", + ) + + # M2: dest.parent is a file fails before any image probe runs. + repo2 = base / "repo_file_parent" + (repo2 / "out").mkdir(parents=True) + (repo2 / "out" / "calls").write_text("keep-parent-file", encoding="ascii") + code, _, err = _run_main( + probe_root_devices, + [str(build_dir), "--warp-only", "--bin", str(bin_dir)], + repo2, + fake_run=_no_image_measure, + ) + self.assertEqual(code, 1) + self.assertIn("Output parent is not a directory", err) + + # M3: missing inventory fails before the inventory is read. + (calls / "six-apis.json").unlink() + with mock.patch.object(Path, "read_bytes", _no_read("six-apis.json")): + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertIn("Inventory file is missing or not a file", err) + # Restore the fixture inventory for the M4 case below. + repo3, calls3, build_dir3, bin_dir3 = self._create_fixture(base / "fixture2") + repo, calls, build_dir, bin_dir = repo3, calls3, build_dir3, bin_dir3 + + # M4: missing build image fails before the image is read. + img = build_dir / probe_root_devices.NAMES[0] + img.unlink() + with mock.patch.object(Path, "read_bytes", _no_read(probe_root_devices.NAMES[0])): + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertIn("Build image is missing or not a file", err) + + def test_os_replace_failure_preserves_bytes_and_zero_temps(self) -> None: + with TemporaryDirectory() as tmp: + repo, calls, build_dir, bin_dir = self._create_fixture(Path(tmp)) + dest = calls / "root-devices-warp.json" + dest.write_text("existing-report\n", encoding="utf-8") + with mock.patch.object(os, "replace", side_effect=OSError("simulated replace failure")): + code, _, err = _run_main( + probe_root_devices, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated replace failure", err) + self.assertEqual(dest.read_text(encoding="utf-8"), "existing-report\n") + self.assertEqual(sorted(p.name for p in calls.iterdir()), ["root-devices-warp.json", "six-apis.json"]) + + def test_argparse_py314_safe(self) -> None: + with TemporaryDirectory() as tmp: + repo = Path(tmp) / "repo" + code_help, out_help, err_help = _run_main(probe_root_devices, ["--help"], repo) + self.assertEqual(code_help, 0) + self.assertEqual(err_help, "") + self.assertIn("usage:", out_help.lower()) + + for bad_argv in (["--bogus-flag"], ["build_one", "extra_arg"]): + with self.subTest(argv=bad_argv): + code, _, err = _run_main(probe_root_devices, bad_argv, repo) + self.assertNotEqual(code, 0) + self.assertNotIn("Traceback", err) + self.assertIn("unrecognized", err.lower()) + + def test_fast_temp_copy_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + for label, target, replacement in MUTATIONS: + with self.subTest(mutation=label), TemporaryDirectory() as tmp: + base = Path(tmp) + repo, calls, build_dir, bin_dir = self._create_fixture(base) + file_bin = base / "file_bin" + file_bin.write_text("not dir", encoding="ascii") + bad_cso_bin = base / "bad_cso_bin" + bad_cso_bin.mkdir() + (bad_cso_bin / "compute_root.cso").mkdir() + (bad_cso_bin / "compute_tables.cso").write_bytes(b"ok") + dest = calls / "root-devices-warp.json" + + checks = { + "drop_bin_is_dir_guard": lambda mod: self.assertIn( + "--bin path is not a directory", + _run_main(mod, ["--warp-only", "--bin", str(file_bin)], repo)[2], + ), + "drop_control_cso_is_file_guard": lambda mod: self.assertIn( + "Control shader is missing or not a file", + _run_main(mod, ["--warp-only", "--bin", str(bad_cso_bin)], repo)[2], + ), + "drop_dest_is_dir_guard": lambda mod: self._assert_dir_guard_fires( + mod, build_dir, bin_dir, repo, dest + ), + "drop_dest_inside_build_guard": lambda mod: self.assertEqual( + _run_main(mod, [str(repo), "--warp-only", "--bin", str(bin_dir)], repo)[0], + 2, + ), + "drop_tmp_unlink_cleanup": lambda mod: self._assert_replace_leaves_zero_temps( + mod, build_dir, bin_dir, repo, calls, dest + ), + } + + self.assertEqual(source.count(target), 1, target) + mut_path = base / f"probe_root_devices_{label}.py" + mut_path.write_text(source.replace(target, replacement, 1), encoding="utf-8") + mod_name = f"probe_root_devices_mut_{label}" + mod = _load_temp_module(mut_path, mod_name) + try: + with self.assertRaises(AssertionError, msg=f"mutation {label} escaped detection"): + checks[label](mod) + finally: + sys.modules.pop(mod_name, None) + + def _assert_dir_guard_fires(self, mod, build_dir: Path, bin_dir: Path, repo: Path, dest: Path) -> None: + dest.mkdir() + try: + _, _, err = _run_main(mod, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo) + finally: + if dest.is_dir(): + dest.rmdir() + self.assertIn("Output path is a directory", err) + + def _assert_replace_leaves_zero_temps( + self, mod, build_dir: Path, bin_dir: Path, repo: Path, calls: Path, dest: Path + ) -> None: + dest.write_text("keep", encoding="utf-8") + try: + with mock.patch.object(os, "replace", side_effect=OSError("boom")): + _run_main(mod, [str(build_dir), "--warp-only", "--bin", str(bin_dir)], repo) + self.assertEqual(sorted(p.name for p in calls.iterdir()), ["root-devices-warp.json", "six-apis.json"]) + finally: + for extra in list(calls.iterdir()): + if extra.name not in ("six-apis.json", "root-devices-warp.json"): + extra.unlink(missing_ok=True) + dest.unlink(missing_ok=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index 1b197796d4..b1c5060a2d 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -2608,6 +2608,92 @@ def build_fma_mix_shader(swap_modifiers=False): with self.assertRaises(ValueError): lower(bad_shader_asm, 20, 24, None, constant_descriptor=0) + def test_vop3p_fma_mix_half_select_per_source_position(self): + """Each v_fma_mix* source position reads op_sel_hi as binary16 and op_sel as the high half on its own.""" + refusal = "High-half selection requires an f16 operand" + prologue = [ + "s_mov_b32 s21, 0", + "s_load_dwordx4 s[28:31], s[20:21], 0x0", + "s_waitcnt lgkmcnt(0)", + "s_buffer_load_dwordx4 s[28:31], s[28:31], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32_e32 v8, s29", + "v_mov_b32_e32 v9, s30", + "v_mov_b32_e32 v10, s31", + ] + epilogue = [ + "v_cvt_pkrtz_f16_f32_e32 v16, v8, v8", + "exp mrt0 v16, v16, v16, v16 done compr vm", + "s_endpgm", + ] + # v8, v9 and v10 lower to alu5, alu6 and alu7, so a source read at the wrong position is visible. + sources = ("alu5", "alu6", "alu7") + + def widened(position, high): + """Sources with only `position` widened as binary16; `high` picks its upper half.""" + shift = " >> 16" if high else "" + return [f"widen16(asuint({name}){shift})" if k == position else name for k, name in enumerate(sources)] + + def lowered_mad(op, selectors): + # v_fma_mixlo_f16 keeps the other half of its destination, so it writes the initialized v8. + dst = "v12" if op == "v_fma_mix_f32" else "v8" + asm = prologue + [f"{op} {dst}, v8, v9, v10{selectors}"] + epilogue + found = [line for line in lower(asm, 20, 24, None, constant_descriptor=0).splitlines() if " = mad(" in line] + self.assertEqual(len(found), 1, found) + return found[0].split(" = ", 1)[1] + + def mad(args): + return f"mad({', '.join(args)});" + + def bits(position): + return ",".join("1" if k == position else "0" for k in range(3)) + + for op in ("v_fma_mix_f32", "v_fma_mixlo_f16"): + self.assertEqual(lowered_mad(op, ""), mad(sources), op) + lowered = {} + for pos in range(3): + one = bits(pos) + low_sel = f" op_sel_hi:[{one}]" + high_sel = f" op_sel:[{one}] op_sel_hi:[{one}]" + # The parsed fields must name the same position the lowering reads. + zero = [0, 0, 0] + marked = [int(k == pos) for k in range(3)] + self.assertEqual(parse_fma_mix(f"v8, v9, v10{low_sel}")[1:3], (zero, marked)) + self.assertEqual(parse_fma_mix(f"v8, v9, v10{high_sel}")[1:3], (marked, marked)) + + with self.subTest(op=op, position=pos, case="low half"): + # (a) op_sel_hi alone widens the low half of this source and leaves the others binary32. + lowered[pos, "low"] = lowered_mad(op, low_sel) + self.assertEqual(lowered[pos, "low"], mad(widened(pos, False))) + with self.subTest(op=op, position=pos, case="high half"): + # (b) op_sel with op_sel_hi on this source picks the high half of that source only. + lowered[pos, "high"] = lowered_mad(op, high_sel) + self.assertEqual(lowered[pos, "high"], mad(widened(pos, True))) + with self.subTest(op=op, position=pos, case="high half among binary16 sources"): + # All three sources are binary16 and op_sel marks one: it must not move to a neighbour. + expected = [f"widen16(asuint({name}){' >> 16' if k == pos else ''})" for k, name in enumerate(sources)] + self.assertEqual(lowered_mad(op, f" op_sel:[{one}] op_sel_hi:[1,1,1]"), mad(expected)) + with self.subTest(op=op, position=pos, case="op_sel alone"): + # (c) op_sel on a binary32 source is refused, at the parser and through lower(). + with self.assertRaisesRegex(ValueError, refusal): + parse_fma_mix(f"v8, v9, v10 op_sel:[{one}]") + with self.assertRaisesRegex(ValueError, refusal): + lowered_mad(op, f" op_sel:[{one}]") + # The refusal tracks the position: op_sel_hi on a different source does not excuse it. + other_hi = bits((pos + 1) % 3) + with self.assertRaisesRegex(ValueError, refusal): + parse_fma_mix(f"v8, v9, v10 op_sel:[{one}] op_sel_hi:[{other_hi}]") + with self.assertRaisesRegex(ValueError, refusal): + lowered_mad(op, f" op_sel:[{one}] op_sel_hi:[{other_hi}]") + + # (d) Swapped-source control: the same modifier on another position gives different text. + for pos in range(3): + self.assertNotEqual(lowered[pos, "low"], lowered[pos, "high"], (op, pos)) + for other in range(3): + if other != pos: + for half in ("low", "high"): + self.assertNotEqual(lowered[pos, half], lowered[other, half], (op, pos, other, half)) + def test_mubuf_opcode_table_synthetic_forms(self): """Every GFX1013 MUBUF opcode must decode with exact width, scanner recognition, and 8-byte alignment.""" from disasm_rdna2 import MUBUF_OPS @@ -4309,6 +4395,54 @@ def test_decoded_scalar_control_forms_are_recognized(self): ) self.assertEqual(missing, []) + def test_permlane_cross_lane_census_preserves_lowering_refusal(self): + # gfx1013 VOP3 bytes use the same valid VGPR/SGPR operands in all three forms. + encodings = ( + ("000077d701050c00", "v_permlane16_b32", "VALU (Cross-lane)"), + ("000078d701050c00", "v_permlanex16_b32", "VALU (Cross-lane)"), + ("000044d701050c00", "v_perm_b32", "VALU (Vector ALU)"), + ) + results = [] + for wave_size in (32, 64): + for encoding, opcode, category in encodings: + with self.subTest(wave_size=wave_size, opcode=opcode): + instruction = disasm_rdna2(bytes.fromhex(encoding))[0]["assembly"] + self.assertEqual(instruction, f"{opcode} v0, v1, s2, s3") + shader = [ + "v_mov_b32_e32 v1, 1", + "s_mov_b32 s2, 0", + "s_mov_b32 s3, 0", + instruction, + "v_cvt_pkrtz_f16_f32_e32 v16, v0, v0", + "exp mrt0 v16, v16, v16, v16 done compr vm", + "s_endpgm", + ] + record = analyze_shader_instructions( + f"ps_{opcode}_wave{wave_size}", shader, wave_size=wave_size + ) + self.assertTrue(record["opcodes_recognized"]) + self.assertFalse(record["translator_accepted"]) + self.assertEqual(record["compatibility_category"], "opcode_recognized_translator_rejected") + self.assertEqual(record["lower_error_kind"], "translator_rejection") + self.assertEqual(record["lower_error"], f"Unsupported instruction 3: {instruction}") + self.assertEqual(record["unsupported_details"], [ + {"line_number": 4, "raw": instruction, "opcode": opcode, "category": category}, + ]) + results.append(record) + + with tempfile.TemporaryDirectory() as tmp: + json_file, _ = generate_progress_dashboard(results, Path(tmp)) + report = json.loads(json_file.read_text(encoding="utf-8")) + cross_lane = report["subsystems"]["VALU (Cross-lane)"] + self.assertEqual(cross_lane["total_instructions"], 4) + self.assertEqual(cross_lane["distinct_opcodes"], 2) + self.assertCountEqual(cross_lane["top_opcodes"], ["v_permlane16_b32", "v_permlanex16_b32"]) + missing = {row["opcode"]: row for row in report["missing_opcodes_ranked"]} + for _, opcode, category in encodings: + self.assertEqual(missing[opcode]["category"], category) + self.assertEqual(missing[opcode]["occurrences"], 2) + + def test_accepted_full_shader(self): """Canonical straight-line pixel shader accepted by pixel_aot translator.""" canonical_shader = [ @@ -6110,10 +6244,10 @@ def test_shift64_scanner_support(self): """Issue #928: the 64-bit VOP3 shifts are supported with at most one SGPR or literal source.""" for line in ("v_lshlrev_b64 v[12:13], v20, v[18:19]", "v_lshrrev_b64 v[2:3], s46, v[4:5]", "v_ashrrev_i64 v[2:3], 0x41, v[4:5]", "v_lshlrev_b64 v[2:3], v1, s[4:5]", - "v_ashrrev_i64 v[2:3], 3, -1", "v_lshlrev_b64_e64 v[2:3], v1, v[4:5]"): + "v_ashrrev_i64 v[2:3], 3, -1", "v_lshlrev_b64 v[2:3], v1, 0x41", "v_lshlrev_b64_e64 v[2:3], v1, v[4:5]"): self.assertTrue(is_instruction_supported(line), line) for line in ("v_lshlrev_b64 v[2:3], s4, s[4:5]", "v_lshlrev_b64 v[2:3], 0x41, s[4:5]", - "v_lshlrev_b64 v[2:3], v1, 0x41", "v_lshlrev_b64 v[2:3], v1, v[4:5] clamp", + "v_lshlrev_b64 v[2:3], s4, 0x41", "v_lshlrev_b64 v[2:3], v1, v[4:5] clamp", "v_lshlrev_b64_e32 v[2:3], v1, v[4:5]", "v_lshlrev_b64 v[2:3], -v1, v[4:5]"): self.assertFalse(is_instruction_supported(line), line) diff --git a/tests/rdna_cvt_pk_u8_cli_check.py b/tests/rdna_cvt_pk_u8_cli_check.py new file mode 100644 index 0000000000..8194c9f356 --- /dev/null +++ b/tests/rdna_cvt_pk_u8_cli_check.py @@ -0,0 +1,505 @@ +"""Pure-Python CLI, atomic-write, path-collision, error-guard, and mutation suite for tools/rdna_cvt_pk_u8.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "rdna_cvt_pk_u8.py" +MEASURED_TSV = ROOT / "tests" / "data" / "rdna_cvt_pk_u8_measured.tsv" +sys.path.insert(0, str(ROOT / "tools")) + +import rdna_cvt_pk_u8 # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = rdna_cvt_pk_u8.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + cwd=str(cwd) if cwd is not None else None, + timeout=30, + ) + + +class _FakeHip: + device = 0 + + def __init__(self) -> None: + self.calls: list[tuple[str, int]] = [] + + def count(self) -> int: + return 2 + + def arch(self, device: int | None = None) -> str: + idx = self.device if device is None else device + return "gfx1030:sramecc-:xnack-" if idx == 0 else "gfx1036" + + def run_kernel(self, hsaco: bytes, kname: str, words: list[tuple[int, int]]) -> list[int]: + self.calls.append((kname, len(words))) + model = "trunc_sat_nan0" if kname.endswith("_rtz") else "rne_sat_nan0" + return [rdna_cvt_pk_u8.model_word(model, b, s) for b, s in words] + + +def _fake_build(arch: str, variant: str, workdir: str, args) -> tuple[bytes, str]: + out = Path(workdir) / f"{variant}_{arch}.hsaco" + out.write_bytes(b"HSACO_" + variant.encode("ascii")) + return out.read_bytes(), str(out) + + +class RdnaCvtPkU8CliPositiveTests(unittest.TestCase): + def test_self_test_direct_argv_and_subprocess(self) -> None: + code, out, err = _run_main(["--self-test"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("self-test OK", out) + + with mock.patch.object(sys, "argv", [str(TOOL), "--self-test"]): + code_default, out_default, err_default = _run_main(None) + self.assertIs(type(code_default), int) + self.assertEqual(code_default, 0, err_default) + self.assertIn("self-test OK", out_default) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), "--self-test"]), + redirect_stdout(stdout), + redirect_stderr(stderr), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertIn("self-test OK", stdout.getvalue()) + self.assertEqual(stderr.getvalue(), "") + + proc = _run_subprocess("--self-test") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("self-test OK", proc.stdout) + + def test_mocked_hip_writes_tsv_and_json_atomically_and_matches_measured(self) -> None: + expected_rows = [ + line.rstrip("\n") + for line in MEASURED_TSV.read_text(encoding="utf-8").splitlines() + if not line.startswith("#") + ] + self.assertEqual(len(expected_rows), 5432) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_tsv = root / "tsv_dir" / "rdna_cvt_pk_u8.tsv" + out_json = root / "json_dir" / "rdna_cvt_pk_u8.json" + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + created_workdirs: list[Path] = [] + real_mkdtemp = rdna_cvt_pk_u8.tempfile.mkdtemp + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + seen_replaces.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + return real_replace(src, dst) + + def tracking_mkdtemp(**kwargs): + d = Path(real_mkdtemp(**kwargs)) + created_workdirs.append(d) + return str(d) + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=tracking_replace), + mock.patch.object(rdna_cvt_pk_u8.tempfile, "mkdtemp", side_effect=tracking_mkdtemp), + ): + code, out, err = _run_main([ + "--out", str(out_tsv), + "--json", str(out_json), + "--show", "0", + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("HIP device 0: gfx1030:sramecc-:xnack- <- used", out) + self.assertIn("HIP device 1: gfx1036", out) + self.assertIn("rows identical to", out) + self.assertIn("results written to", out) + self.assertIn("verbose JSON written to", out) + + self.assertEqual(len(created_workdirs), 1) + self.assertFalse(created_workdirs[0].exists()) + + self.assertEqual(len(seen_replaces), 2) + self.assertEqual( + {dst.resolve() for _, dst in seen_replaces}, + {out_tsv.resolve(), out_json.resolve()}, + ) + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], [out_tsv.name]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], [out_json.name]) + + tsv_lines = out_tsv.read_text(encoding="utf-8").splitlines() + self.assertIn("# device gfx1030", tsv_lines) + tsv_rows = [line for line in tsv_lines if not line.startswith("#")] + self.assertEqual(tsv_rows, expected_rows) + + doc = json.loads(out_json.read_text(encoding="utf-8")) + self.assertEqual(doc["arch"], "gfx1030") + self.assertEqual(doc["sentinel"], rdna_cvt_pk_u8.SENTINEL) + self.assertEqual(len(doc["rows"]), 5432) + self.assertEqual(doc["summary"]["default"]["matching_models"], ["rne_sat_nan0"]) + self.assertEqual(doc["summary"]["rtz"]["matching_models"], ["trunc_sat_nan0"]) + self.assertEqual(doc["summary"]["flush"]["matching_models"], ["rne_sat_nan0"]) + + def test_asm_only_with_keep_and_compare_diff_report(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + keep_dir = root / "keep_artifacts" + with mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build): + code, out, err = _run_main(["--asm-only", "--arch", "gfx1030", "--keep", str(keep_dir)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("built default", out) + self.assertTrue((keep_dir / "default_gfx1030.hsaco").is_file()) + + # Compare with a modified TSV triggers the DIFFER summary line without failing. + ref_lines = MEASURED_TSV.read_text(encoding="utf-8").splitlines() + for idx, line in enumerate(ref_lines): + if not line.startswith("#"): + parts = line.split("\t") + parts[3] = "00000000" + ref_lines[idx] = "\t".join(parts) + break + diff_ref = root / "diff_ref.tsv" + diff_ref.write_text("\n".join(ref_lines) + "\n", encoding="utf-8") + out_tsv = root / "out.tsv" + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + code2, out2, err2 = _run_main([ + "--out", str(out_tsv), + "--compare", str(diff_ref), + ]) + self.assertEqual(code2, 0, err2) + self.assertEqual(err2, "") + self.assertIn("rows DIFFER from", out2) + self.assertIn("(1 of 5432 rows)", out2) + + +class RdnaCvtPkU8CliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + allow_stdout: bool = False, + cwd: Path | None = None, + ) -> str: + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, expected_code, err) + if not allow_stdout: + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv, cwd=cwd) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + if not allow_stdout: + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + return err + + def test_asm_only_needs_arch_and_hip_runtime_errors(self) -> None: + # --asm-only without --arch -> stderr + return 2 (not SystemExit). + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")): + self._assert_clean_failure( + ["--asm-only"], + expected_code=2, + expected_fragments=("error: --asm-only needs --arch",), + ) + + with TemporaryDirectory() as tmp: + out_tsv = Path(tmp) / "out.tsv" + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=RuntimeError("no HIP dll")): + self._assert_clean_failure( + ["--out", str(out_tsv)], + expected_code=2, + expected_fragments=("error: no HIP dll",), + check_subprocess=False, + ) + + class _FailingKernelHip(_FakeHip): + def run_kernel(self, hsaco, kname, words): + raise RuntimeError("kernel launch failed") + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FailingKernelHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + self._assert_clean_failure( + ["--out", str(out_tsv)], + expected_code=3, + expected_fragments=("error: kernel launch failed",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertFalse(out_tsv.exists()) + + def test_flag_and_path_type_validation_guards(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + reg_file = root / "regular.txt" + reg_file.write_text("keep-me", encoding="utf-8") + existing_dir = root / "existing_dir" + existing_dir.mkdir() + valid_out = root / "ok.tsv" + + cases = [ + (["--show", "-1", "--out", str(valid_out)], "--show must be >= 0", True), + (["--keep", "", "--out", str(valid_out)], "--keep path must not be empty", True), + (["--keep", str(reg_file), "--out", str(valid_out)], "--keep path is not a directory", True), + (["--keep", str(reg_file / "sub"), "--out", str(valid_out)], "--keep parent path is not a directory", True), + (["--compare", str(existing_dir), "--out", str(valid_out)], "--compare path is a directory", True), + (["--out", ""], "--out path must not be empty", True), + (["--out", str(existing_dir) + os.sep], "--out path is a directory path", True), + (["--out", str(existing_dir)], "--out path is a directory", True), + (["--out", str(reg_file / "child.tsv")], "--out parent path is not a directory", True), + (["--out", str(reg_file / "sub" / "child.tsv")], "--out parent path is not a directory", True), + (["--out", str(valid_out), "--json", ""], "--json path must not be empty", True), + (["--out", str(valid_out), "--json", str(existing_dir) + "/"], "--json path is a directory path", True), + (["--out", str(valid_out), "--json", str(existing_dir)], "--json path is a directory", True), + (["--out", str(valid_out), "--json", str(reg_file / "child.json")], "--json parent path is not a directory", True), + ] + for argv, fragment, subproc in cases: + with self.subTest(argv=argv): + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=AssertionError("build() must not run")), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", fragment), + check_subprocess=subproc, + ) + self.assertEqual(reg_file.read_text(encoding="utf-8"), "keep-me") + self.assertEqual(list(existing_dir.iterdir()), []) + + def test_symlink_output_guards_kill_mutations(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + target = root / "target.txt" + target.write_text("do-not-clobber", encoding="utf-8") + valid_out = root / "valid.tsv" + + for flag, name in (("--out", "out_link.tsv"), ("--json", "json_link.json")): + link = root / name + try: + link.symlink_to(target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + argv = [flag, str(link)] if flag == "--out" else ["--out", str(valid_out), flag, str(link)] + if created_real: + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", f"{flag} path must not be a symlink"), + ) + link.unlink() + else: + with ( + mock.patch.object( + Path, + "is_symlink", + autospec=True, + side_effect=lambda p, expected=link: os.path.normcase(str(p.resolve())) + == os.path.normcase(str(expected.resolve())), + ), + mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", f"{flag} path must not be a symlink"), + check_subprocess=False, + ) + self.assertEqual(target.read_text(encoding="utf-8"), "do-not-clobber") + + def test_collision_guards_alias_nonexistent_and_hardlink(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + ref = root / "ref.tsv" + ref.write_text("# ref\n", encoding="utf-8") + ref_hardlink = root / "ref_hardlink.tsv" + os.link(ref, ref_hardlink) + self.assertNotEqual(ref.resolve(), ref_hardlink.resolve()) + self.assertTrue(ref.samefile(ref_hardlink)) + + ghost_a = root / "ghost.txt" + ghost_b = sub / ".." / "ghost.txt" + other_out = root / "other_out.tsv" + + collision_cases = [ + (["--out", str(ref), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(sub / ".." / "ref.tsv"), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(ref_hardlink), "--compare", str(ref)], "--out path collides with --compare"), + (["--out", str(ghost_a), "--compare", str(ghost_b)], "--out path collides with --compare"), + (["--out", str(other_out), "--json", str(ref), "--compare", str(ref)], "--json path collides with --compare"), + (["--out", str(other_out), "--json", str(ref_hardlink), "--compare", str(ref)], "--json path collides with --compare"), + (["--out", str(ghost_a), "--json", str(ghost_b)], "--out and --json paths must not collide"), + (["--out", str(ref), "--json", str(ref_hardlink)], "--out and --json paths must not collide"), + (["--keep", str(ghost_a), "--out", str(ghost_b)], "--keep and --out paths must not collide"), + ] + for argv, fragment in collision_cases: + with self.subTest(argv=argv): + with mock.patch.object(rdna_cvt_pk_u8, "Hip", side_effect=AssertionError("Hip() must not run")): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragments=("error:", fragment), + ) + self.assertEqual(ref.read_text(encoding="utf-8"), "# ref\n") + + def test_atomic_write_and_compare_failures_leave_zero_temps(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + out_tsv = root / "out_dir" / "res.tsv" + out_json = root / "json_dir" / "res.json" + out_tsv.parent.mkdir() + out_json.parent.mkdir() + out_tsv.write_text("PRIOR_TSV", encoding="utf-8") + out_json.write_text("PRIOR_JSON", encoding="utf-8") + + # 1) os.replace fails on --out: prior files preserved, zero sibling .tmp leftovers. + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=OSError("simulated tsv replace fail")), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error: simulated tsv replace fail",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertEqual(out_tsv.read_text(encoding="utf-8"), "PRIOR_TSV") + self.assertEqual(out_json.read_text(encoding="utf-8"), "PRIOR_JSON") + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], ["res.tsv"]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], ["res.json"]) + + # 2) os.replace fails on --json after --out: prior --json preserved, zero sibling .tmp leftovers. + real_replace = os.replace + calls = [] + + def fail_second_replace(src, dst): + calls.append(Path(dst)) + if len(calls) == 2: + raise OSError("simulated json replace fail") + return real_replace(src, dst) + + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object(rdna_cvt_pk_u8.os, "replace", side_effect=fail_second_replace), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error: simulated json replace fail",), + check_subprocess=False, + allow_stdout=True, + ) + self.assertEqual(out_json.read_text(encoding="utf-8"), "PRIOR_JSON") + self.assertEqual([p.name for p in out_tsv.parent.iterdir()], ["res.tsv"]) + self.assertEqual([p.name for p in out_json.parent.iterdir()], ["res.json"]) + + # 3) Corrupt UTF-8 --compare file -> ValueError/UnicodeDecodeError caught -> clean exit 1. + bad_cmp = root / "bad_utf8.tsv" + bad_cmp.write_bytes(b"\xff\xfe\xfd") + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--compare", str(bad_cmp)], + expected_code=1, + expected_fragments=("error:",), + check_subprocess=False, + allow_stdout=True, + ) + + # 4) json.JSONDecodeError caught cleanly if raised during main flow. + with ( + mock.patch.object(rdna_cvt_pk_u8, "Hip", _FakeHip), + mock.patch.object(rdna_cvt_pk_u8, "build", side_effect=_fake_build), + mock.patch.object( + rdna_cvt_pk_u8.json, + "dumps", + side_effect=json.JSONDecodeError("bad json", "x", 0), + ), + ): + self._assert_clean_failure( + ["--out", str(out_tsv), "--json", str(out_json)], + expected_code=1, + expected_fragments=("error:", "bad json"), + check_subprocess=False, + allow_stdout=True, + ) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + for bad_argv, fragment in ( + (["--unknown-flag"], "--unknown-flag"), + (["--arch"], "--arch"), + (["--show", "not-an-int"], "--show"), + (["--cov", "9"], "--cov"), + (["--build", "bogus"], "--build"), + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragments=("usage:", fragment), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/record_gpu_cases_cli_check.py b/tests/record_gpu_cases_cli_check.py new file mode 100644 index 0000000000..3bcafa96b4 --- /dev/null +++ b/tests/record_gpu_cases_cli_check.py @@ -0,0 +1,284 @@ +"""Mocked CLI and temp-copy mutation unit suite for tools/record_gpu_cases.py.""" +import contextlib +import importlib.util +import io +import os +import sys +import tempfile +from pathlib import Path +from unittest import mock + +TOOLS_DIR = Path(__file__).resolve().parents[1] / "tools" +RECORDER_PATH = TOOLS_DIR / "record_gpu_cases.py" + + +def _load_module(path, name="record_gpu_cases_sut"): + spec = importlib.util.spec_from_file_location(name, str(path)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _fake_dxc(root): + dxc = Path(root) / "fake_dxc.exe" + dxc.write_bytes(b"DXC") + return dxc + + +def _fake_run_case(name, dxc, runner, adapter, folder, mutation=None): + assert Path(dxc).is_file(), f"run_case received non-file dxc: {dxc}" + tag = (mutation or "base").encode("ascii") + (folder / f"{name}.cso").write_bytes(b"DXBC" + tag) + (folder / f"{name}.case").write_bytes(b"CASE:" + name.encode("ascii") + b":" + tag) + + +def _tmp_files(directory): + return [p for p in Path(directory).iterdir() if p.name.endswith(".tmp") or p.name.startswith(".manifest.tsv.")] + + +def _make_symlink(target, link_path): + try: + os.symlink(target, link_path) + return True + except (OSError, NotImplementedError): + return False + + +def _test_atomic_manifest_and_zero_temps(mod, root): + dxc = _fake_dxc(root) + out = Path(root) / "out" + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + stdout = io.StringIO() + stderr = io.StringIO() + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(out)]) + assert rc == 0, f"expected rc=0, got {rc} stderr={stderr.getvalue()!r}" + assert stderr.getvalue() == "" + manifest = out / "manifest.tsv" + assert manifest.is_file() + lines = manifest.read_text(encoding="ascii").splitlines() + assert len(lines) == len(mod.check.CASES) + len(mod.check.CONTROLS) + for line in lines: + fields = line.split("\t") + assert len(fields) == 4 + ident, compiler, expect, _ = fields + assert compiler == "dxc" and expect in ("pass", "fail") + assert (out / f"{ident}.cso").is_file() + assert (out / f"{ident}.case").is_file() + assert not _tmp_files(out), f"leftover temp files: {_tmp_files(out)}" + + # Resolving dxc by name via shutil.which. + out_which = Path(root) / "out_which" + with mock.patch.object(mod.shutil, "which", return_value=str(dxc)): + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + rows = mod.record("fake_dxc.exe", out_which, cases=(next(iter(mod.check.CASES)),), controls=()) + assert len(rows) == 1 + assert (out_which / "manifest.tsv").is_file() + assert not _tmp_files(out_which) + + +def _test_dxc_validation(mod, root): + out = Path(root) / "out" + missing = Path(root) / "missing_dxc.exe" + dxc_dir = Path(root) / "dxc_dir" + dxc_dir.mkdir() + for bad_dxc in (missing, dxc_dir): + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(bad_dxc), str(out)]) + assert rc == 1, f"expected rc=1 for bad dxc {bad_dxc}, got {rc}" + assert "Traceback" not in stderr.getvalue() and stderr.getvalue().strip() + assert not (out / "manifest.tsv").exists() + + +def _test_output_validation(mod, root): + dxc = _fake_dxc(root) + + # 1. Existing regular file output. + file_out = Path(root) / "out_file" + file_out.write_bytes(b"KEEP_FILE") + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + try: + mod.record(str(dxc), str(file_out)) + except ValueError: + pass + else: + raise AssertionError("record() did not raise ValueError for file output") + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(file_out)]) + assert rc == 1 and "Traceback" not in stderr.getvalue() + assert file_out.read_bytes() == b"KEEP_FILE" + + # 2. File-backed parent. + sub_out = file_out / "child" + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + try: + mod.record(str(dxc), str(sub_out)) + except ValueError: + pass + else: + raise AssertionError("record() did not raise ValueError for file-backed parent") + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(sub_out)]) + assert rc == 1 and "Traceback" not in stderr.getvalue() + assert file_out.read_bytes() == b"KEEP_FILE" + + # 3. samefile output == dxc (direct and mocked os.path.samefile for a directory/alias). + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(dxc)]) + assert rc == 1 and "Traceback" not in stderr.getvalue() + assert dxc.read_bytes() == b"DXC" + alias_out = Path(root) / "alias_out" + alias_out.mkdir() + with mock.patch.object(mod.os.path, "samefile", return_value=True): + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + try: + mod.record(str(dxc), str(alias_out)) + except ValueError: + pass + else: + raise AssertionError("record() did not raise ValueError on samefile match") + + # 4. Symlink output. + real_dir = Path(root) / "real_dir" + real_dir.mkdir() + link_out = Path(root) / "link_out" + if _make_symlink(str(real_dir), str(link_out)): + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(link_out)]) + assert rc == 1 and "Traceback" not in stderr.getvalue() + assert list(real_dir.iterdir()) == [] + else: + with mock.patch.object(mod.Path, "is_symlink", autospec=True, side_effect=lambda p: p == link_out): + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(link_out)]) + assert rc == 1 and "Traceback" not in stderr.getvalue() + + +def _test_replace_fail_preserves_manifest_and_cleans_temps(mod, root): + dxc = _fake_dxc(root) + out = Path(root) / "out_replace" + out.mkdir() + manifest = out / "manifest.tsv" + manifest.write_text("OLD\tdxc\tpass\t\n", encoding="ascii") + + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=_fake_run_case): + with mock.patch.object(mod.os, "replace", side_effect=OSError("replace failed")): + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(out)]) + assert rc == 1, f"expected rc=1 on os.replace failure, got {rc}" + assert "Traceback" not in stderr.getvalue() and "replace failed" in stderr.getvalue() + assert manifest.read_text(encoding="ascii") == "OLD\tdxc\tpass\t\n" + assert not _tmp_files(out), f"leftover temp files after os.replace failure: {_tmp_files(out)}" + + +def _test_runtime_error_and_argparse(mod, root): + dxc = _fake_dxc(root) + out = Path(root) / "out_err" + stderr = io.StringIO() + with mock.patch.object(mod.check, "run_case", side_effect=RuntimeError("boom")): + with contextlib.redirect_stderr(stderr): + rc = mod.main([str(dxc), str(out)]) + assert rc == 1 and "Traceback" not in stderr.getvalue() and "boom" in stderr.getvalue() + assert not (out / "manifest.tsv").exists() + + help_out = io.StringIO() + try: + with contextlib.redirect_stdout(help_out): + mod.main(["--help"]) + except SystemExit as exc: + assert exc.code == 0 + else: + raise AssertionError("--help did not exit") + assert "dxc" in help_out.getvalue() and "output" in help_out.getvalue() + + +def run_suite(mod): + tests = [ + _test_atomic_manifest_and_zero_temps, + _test_dxc_validation, + _test_output_validation, + _test_replace_fail_preserves_manifest_and_cleans_temps, + _test_runtime_error_and_argparse, + ] + for fn in tests: + with tempfile.TemporaryDirectory() as root: + fn(mod, root) + return len(tests) + + +def _run_mutations(): + source = RECORDER_PATH.read_text(encoding="utf-8") + mutants = [ + ( + "drop_dxc_is_file_guard", + " if candidate.is_file():\n return candidate", + " if True:\n return candidate", + _test_dxc_validation, + ), + ( + "drop_output_is_file_guard", + " if out.is_file() or (out.exists() and not out.is_dir()):\n" + " raise ValueError(f\"output path is not a directory: {out}\")", + " if False:\n pass", + _test_output_validation, + ), + ( + "drop_output_is_symlink_guard", + " if out.is_symlink():\n raise ValueError(f\"output path cannot be a symlink: {out}\")", + " if False:\n pass", + _test_output_validation, + ), + ( + "drop_samefile_guard", + " if _samefile(out, dxc_path):\n raise ValueError(f\"output path matches dxc executable: {out}\")", + " if False:\n pass", + _test_output_validation, + ), + ( + "non_atomic_manifest_write", + " os.replace(tmp_path, path)", + " path.write_text(text, encoding='ascii')\n tmp_path.unlink(missing_ok=True)", + _test_replace_fail_preserves_manifest_and_cleans_temps, + ), + ( + "drop_tmp_unlink_cleanup", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)", + " pass", + _test_replace_fail_preserves_manifest_and_cleans_temps, + ), + ] + with tempfile.TemporaryDirectory() as mut_dir: + for idx, (name, needle, repl, probe) in enumerate(mutants): + assert source.count(needle) == 1, f"mutant needle not unique: {name}" + mut_path = Path(mut_dir) / f"record_gpu_cases_mut_{idx}.py" + mut_path.write_text(source.replace(needle, repl, 1), encoding="utf-8") + mod = _load_module(mut_path, f"record_gpu_cases_mut_{idx}") + with tempfile.TemporaryDirectory() as root: + try: + probe(mod, root) + except (AssertionError, OSError, SystemExit): + continue + raise SystemExit(f"record_gpu_cases_cli_check: mutant {name} survived!") + return len(mutants) + + +def main(): + mod = _load_module(RECORDER_PATH, "record_gpu_cases") + passed = run_suite(mod) + killed = _run_mutations() + print(f"record_gpu_cases_cli_check: {passed}/{passed} unit checks passed, {killed}/{killed} mutants killed") + + +if __name__ == "__main__": + main() diff --git a/tests/rectlist_draw_check.cpp b/tests/rectlist_draw_check.cpp index 75fd169f90..9466765257 100644 --- a/tests/rectlist_draw_check.cpp +++ b/tests/rectlist_draw_check.cpp @@ -121,7 +121,7 @@ void execute_draw( const D3D12_VERTEX_BUFFER_VIEW vbv{ upload_vb->GetGPUVirtualAddress(), - sizeof(Vertex) * vertex_count, + static_cast<UINT>(sizeof(Vertex) * vertex_count), sizeof(Vertex) }; list->IASetVertexBuffers(0, 1, &vbv); diff --git a/tests/run_checks_fragments_check.py b/tests/run_checks_fragments_check.py new file mode 100644 index 0000000000..4eaf4af25f --- /dev/null +++ b/tests/run_checks_fragments_check.py @@ -0,0 +1,129 @@ +"""The parallel check runner also runs the checks listed in a directory of text files.""" +import os +import runpy +import subprocess +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RUNNER = os.path.join(ROOT, "tools", "run_checks_parallel.py") + + +def run(*args): + return subprocess.run([sys.executable, "-B", RUNNER, "-j", "2", *args], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + + +def q(path): + """Quote a path for a listing line so a directory with spaces stays one word.""" + return '"' + path + '"' + + +def write(path, text): + with open(path, "w", encoding="utf-8") as handle: + handle.write(text) + + +with tempfile.TemporaryDirectory(prefix="x2w frag ") as tmp: + echo = os.path.join(tmp, "echo.py") + write(echo, "import sys\nprint('echo ran', *sys.argv[1:])\n") + lists = os.path.join(tmp, "lists") + os.mkdir(lists) + + # Files are read in name order; comments, blank lines and README files are ignored; a line may + # carry arguments; a command also given on the command line runs once. + write(os.path.join(lists, "b.txt"), f"# note\n\n{q(echo)} second\n") + write(os.path.join(lists, "a.txt"), f"{q(echo)} first\n{q(echo)}\n") + write(os.path.join(lists, "README.md"), f"{q(echo)} never\n") + ok = run("--from-dir", lists, echo) + assert ok.returncode == 0, ok.stdout + assert "all 3 checks passed" in ok.stdout, ok.stdout + assert ok.stdout.index("echo ran first") < ok.stdout.index("echo ran second"), ok.stdout + assert "never" not in ok.stdout, ok.stdout + + # The directory alone is enough, and an empty directory is a plain empty run. + only = run("--from-dir", lists) + assert only.returncode == 0 and "all 3 checks passed" in only.stdout, only.stdout + empty = os.path.join(tmp, "empty") + os.mkdir(empty) + assert run("--from-dir", empty).returncode == 0 + + # A listed failure fails the run like an inline one. + bad = os.path.join(tmp, "bad.py") + write(bad, "import sys\nsys.exit(3)\n") + bad_dir = os.path.join(tmp, "bad_dir") + os.mkdir(bad_dir) + write(os.path.join(bad_dir, "x.txt"), q(bad) + "\n") + failed = run("--from-dir", bad_dir) + assert failed.returncode == 1 and "FAILED: " + bad in failed.stdout, failed.stdout + + # Loud refusals: missing directory, missing script, duplicate, bad quoting, nothing to run. + missing_dir = run("--from-dir", os.path.join(tmp, "nope")) + assert missing_dir.returncode == 1 and "does not exist" in missing_dir.stdout, missing_dir.stdout + for name, body, needle in ( + ("missing", q(os.path.join(tmp, "gone.py")) + "\n", "x.txt:1"), + ("dup", f"{q(echo)} a\n{q(echo)} a\n", "duplicate of"), + ("quote", f"{q(echo)} 'a\n", "x.txt:1"), + ): + bad_list = os.path.join(tmp, "case_" + name) + os.mkdir(bad_list) + write(os.path.join(bad_list, "x.txt"), body) + refused = run("--from-dir", bad_list) + assert refused.returncode == 1 and needle in refused.stdout, (name, refused.stdout) + assert "echo ran" not in refused.stdout, (name, refused.stdout) + # The same command in two files is a duplicate too, even with different path spellings. + two = os.path.join(tmp, "case_two") + os.mkdir(two) + write(os.path.join(two, "a.txt"), f"{q(echo)}\n") + write(os.path.join(two, "b.txt"), f"{q(echo)}\n") + twice = run("--from-dir", two) + assert twice.returncode == 1 and "b.txt:1" in twice.stdout and "duplicate" in twice.stdout, twice.stdout + dot_two = os.path.join(tmp, "case_dot_two") + os.mkdir(dot_two) + dot_echo = os.path.join(tmp, ".", os.path.basename(echo)) + write(os.path.join(dot_two, "a.txt"), f"{q(echo)}\n") + write(os.path.join(dot_two, "b.txt"), f"{q(dot_echo)}\n") + dot_twice = run("--from-dir", dot_two) + assert dot_twice.returncode == 1 and "b.txt:1" in dot_twice.stdout and "duplicate" in dot_twice.stdout, dot_twice.stdout + dedup = run("--from-dir", lists, dot_echo) + assert dedup.returncode == 0 and "all 3 checks passed" in dedup.stdout, dedup.stdout + assert run().returncode == 2 + + # A listing saved with a UTF-8 byte-order mark (Notepad, Windows PowerShell 5.1 Set-Content + # -Encoding UTF8) behaves like the same listing without one, also when line 1 is a comment or + # blank. The mark is written as explicit bytes so the result does not depend on the platform. + bom = b"\xef\xbb\xbf" + for name, body in ( + ("path", q(echo) + " bomarg\n"), + ("comment", "# note\n" + q(echo) + " bomarg\n"), + ("blank", "\n" + q(echo) + " bomarg\n"), + ): + results = [] + for mark in (b"", bom): + listing = os.path.join(tmp, f"case_bom_{name}_{'bom' if mark else 'plain'}") + os.mkdir(listing) + with open(os.path.join(listing, "x.txt"), "wb") as handle: + handle.write(mark + body.encode("utf-8")) + results.append(run("--from-dir", listing)) + for result in results: + assert result.returncode == 0 and "echo ran bomarg" in result.stdout \ + and "all 1 checks passed" in result.stdout, (name, result.stdout) + +# On Windows a listed path keeps its backslashes and quoted words lose their quotes; POSIX +# splitting would eat the backslashes (`C:\x2w\a.py` -> `C:x2wa.py`). +split = runpy.run_path(RUNNER)["split_command"] +assert split(r'C:\x2w\tests\a.py "b c" d', windows=True) == [r"C:\x2w\tests\a.py", "b c", "d"] +assert split(r'a.py --llvm="C:\Program Files\LLVM\x.dll" ""', windows=True) == [ + "a.py", r"--llvm=C:\Program Files\LLVM\x.dll", ""] +assert split('a.py --llvm="/opt/my llvm/x.so"', windows=False) == ["a.py", "--llvm=/opt/my llvm/x.so"] +assert split("tests/a.py 'b c' d", windows=False) == ["tests/a.py", "b c", "d"] + +# The lists committed to the repository only name scripts that exist, so CI cannot lose one. +for sub in ("python-linux", "pixel-binary"): + found = subprocess.run([sys.executable, "-B", "-c", + "import runpy,sys;r=runpy.run_path(sys.argv[1]);" + "print(len(r['read_check_files'](sys.argv[2])))", + RUNNER, os.path.join(ROOT, "tests", "checks", sub)], + cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + assert found.returncode == 0, found.stdout +print("run_checks_fragments_check ok") diff --git a/tests/run_checks_parallel_check.py b/tests/run_checks_parallel_check.py index 2d04e5cbbd..7484751def 100644 --- a/tests/run_checks_parallel_check.py +++ b/tests/run_checks_parallel_check.py @@ -34,9 +34,18 @@ def group(out, script, status): with open(fail, "w") as f: # An uncaught assertion exits 1 and writes its traceback to stderr, the usual way a check fails. f.write("assert False, 'fail ran'\n") - ok = run(good, good) + also_good = os.path.join(tmp, "also_good.py") + with open(also_good, "w") as f: + f.write("print('good ran')\n") + ok = run(good, also_good) assert ok.returncode == 0 and ok.stdout.count("good ran") == 2, ok.stdout assert "all 2 checks passed" in ok.stdout, ok.stdout + # The same script twice on the command line fails like a command listed twice across the + # tests/checks files: one error line, status 1, and nothing runs. + twice = run(good, bad, good) + assert twice.returncode == 1, twice.stdout + assert twice.stdout.strip() == "duplicate command-line script: " + good, twice.stdout + assert "good ran" not in twice.stdout and "::group::" not in twice.stdout, twice.stdout mixed = run(bad, good) assert mixed.returncode == 1, mixed.stdout assert "bad ran" in mixed.stdout and "good ran" in mixed.stdout and "FAILED: " + bad in mixed.stdout, mixed.stdout @@ -64,6 +73,12 @@ def group(out, script, status): assert both.returncode == 1, both.stdout assert "FAILED: " + bad + "\n" in both.stdout, both.stdout assert "SKIPPED: " + skip + "\n" in both.stdout, both.stdout + # Equivalent script path spellings on the command line (e.g. a.py vs ./a.py) count as duplicates. + dot_good = os.path.join(tmp, ".", "good.py") + spelled_twice = run(good, dot_good) + assert spelled_twice.returncode == 1, spelled_twice.stdout + assert spelled_twice.stdout.strip() == "duplicate command-line script: " + dot_good, spelled_twice.stdout + assert "good ran" not in spelled_twice.stdout and "::group::" not in spelled_twice.stdout, spelled_twice.stdout # -j 0 is clamped to one worker instead of reaching ThreadPoolExecutor(max_workers=0). serial = run(good, jobs="0") assert serial.returncode == 0 and "all 1 checks passed" in serial.stdout, serial.stdout diff --git a/tests/script_state_probe_cli_check.py b/tests/script_state_probe_cli_check.py new file mode 100644 index 0000000000..b0e3a75bff --- /dev/null +++ b/tests/script_state_probe_cli_check.py @@ -0,0 +1,377 @@ +"""Pure-Python CLI and synthetic RPF9 validation suite for tools/script_state_probe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import mmap +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "script_state_probe.py" +sys.path.insert(0, str(ROOT / "tools")) + +import script_state_probe as probe # noqa: E402 + + +def _attr(name: str, spelling: str, raw: int, kind: int) -> bytes: + return struct.pack("<IIIBBH", probe.joaat(name), probe.joaat(spelling), raw, kind, 1, 0) + + +def _camera_rows(priority: int) -> list[bytes]: + return [ + _attr("priority", str(priority), priority, 3), + _attr("blendduration", "25", 25, 3), + _attr("orbitdistance", "2.500000", 0x40200000, 2), + _attr("pitchlimits", "-0.500000,0.500000,0.000000", 0, 1), + _attr("headinglimits", "-1.500000,1.500000,0.000000", 1, 1), + ] + + +def _synth_record( + *, + priorities: tuple[int, ...] = (7,), + state_label: str = "cli_synthetic_state", + truncate_schema_by: int = 0, + corrupt_zlib: bool = False, + truncate_zlib: bool = False, +) -> bytes: + """Build one zlib-compressed PSIN/LSCH/LENM/LSNS/LGID/LRSC/CHKS record payload.""" + attrs = bytearray() + nodes = bytearray() + + def add_node(name: str, parent: int, row_list: list[bytes]) -> int: + idx = len(nodes) // 16 + nodes.extend( + struct.pack( + "<I5H2B", + probe.joaat(name), + parent, + 0, + 0, + 0, + len(attrs) // 16, + len(row_list), + 1, + ) + ) + attrs.extend(b"".join(row_list)) + return idx + + root_parent = 65535 + if len(priorities) > 1: + root_parent = add_node("root", root_parent, []) + for prio in priorities: + state_idx = add_node("state", root_parent, [_attr("id", state_label, 0, 5)]) + add_node("camera", state_idx, _camera_rows(prio)) + + vecs = struct.pack("<6f", -0.5, 0.5, 0.0, -1.5, 1.5, 0.0) + arrays = ((len(attrs) // 16, 2), (0, 0), (2, 4), (0, 0), (len(nodes) // 16, 3)) + root_blob = b"".join(struct.pack("<IIQ", n, n, ref) for n, ref in arrays) + blocks = (root_blob, bytes(attrs), bytes(nodes), vecs) + + instances = bytearray() + for kind, blob in enumerate(blocks, 1): + instances.extend(struct.pack("<IIQ", kind, len(blob), 0xAAAAAAAAAAAAAAAA)) + for blob in blocks: + instances.extend(bytes(-(len(instances) + 8) % 16)) + instances.extend(blob) + + definitions = ( + (80, (("attributes", 0, 0x5C),)), + (16, (("name", 0, 0x4A), ("valueHash", 4, 0x4A))), + (16, (("name", 0, 0x4A), ("parentIndex", 4, 0x13), ("attributeCount", 14, 0x11))), + (12, tuple((axis, i * 4, 0x14) for i, axis in enumerate("xyz"))), + ) + schema = bytearray() + for kind, (size, fields) in enumerate(definitions, 1): + schema.extend(struct.pack("<IIIIQIHH", kind, 0, 0, 0, 0, size, 0, len(fields))) + for _, fields in definitions: + for field_name, off, code in fields: + schema.extend(struct.pack("<IIBBHI", probe.joaat(field_name), off, code, 0, 0, 0)) + if truncate_schema_by: + del schema[-truncate_schema_by:] + + header = bytearray(80) + header[:5] = b"0DRPz" + struct.pack_into("<I", header, 16, 1) + struct.pack_into("<3H", header, 56, 4, 0, 4) + + body = bytearray() + for tag, part in ( + (b"PSIN", instances), + (b"LSCH", schema), + (b"LENM", b""), + (b"LSNS", b""), + (b"LGID", b""), + (b"LRSC", header), + ): + body.extend(struct.pack(">4sI", tag, len(part) + 8)) + body.extend(part) + + chks_size = 20 + total_len = len(body) + chks_size + body.extend(struct.pack(">4sIIQ", b"CHKS", chks_size, total_len, 0)) + + compressed = zlib.compress(bytes(body)) + if corrupt_zlib: + return compressed[:4] + b"\xff\x00\xff\x00" + compressed[8:] + if truncate_zlib: + return compressed[:6] + return compressed + + +def _build_rpf9(*payloads: bytes) -> bytes: + archive = bytearray(b"9FPR") + for payload in payloads: + archive.extend(bytes(-len(archive) % 16)) + archive.extend(payload) + return bytes(archive) + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = probe.main(argv) + except SystemExit as exc: + rc = exc.code if isinstance(exc.code, int) else 2 + return rc, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + env = dict(os.environ, PYTHONUTF8="1") + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + encoding="utf-8", + env=env, + timeout=30, + ) + + +class ScriptStateProbeCliPositiveTests(unittest.TestCase): + def test_direct_main_default_and_state_schema(self): + single_bytes = _build_rpf9(_synth_record(priorities=(7,), state_label="orbit_one")) + ambig_bytes = _build_rpf9(_synth_record(priorities=(7, 11), state_label="orbit_dup")) + with TemporaryDirectory() as tmp: + root = Path(tmp) + single = root / "single.rpf" + single.write_bytes(single_bytes) + ambig = root / "ambig.rpf" + ambig.write_bytes(ambig_bytes) + + # Default mode without --state. + rc, out, err = _run_main([str(single)]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + default_json = json.loads(out) + self.assertEqual( + set(default_json), + {"counts", "requested_state", "first_verified_example"}, + ) + self.assertIsNone(default_json["requested_state"]) + self.assertIsNone(default_json["first_verified_example"]) + self.assertEqual( + default_json["counts"], + { + "section_records": 1, + "node_trees": 1, + "state_nodes": 1, + "camera_parameter_sets": 1, + "all_five_literals_verified": 1, + }, + ) + self.assertEqual(single.read_bytes(), single_bytes) + + # Matching --state mode. + rc, out, err = _run_main([str(single), "--state", "orbit_one"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + matched_json = json.loads(out) + self.assertEqual(matched_json["requested_state"], "orbit_one") + self.assertEqual( + matched_json["first_verified_example"], + { + "priority": "7", + "blendduration": "25", + "orbitdistance": "2.500000", + "pitchlimits": "-0.500000,0.500000,0.000000", + "headinglimits": "-1.500000,1.500000,0.000000", + }, + ) + self.assertNotIn("ambiguous_state_candidates", matched_json) + + # Unmatched --state mode. + rc, out, err = _run_main([str(single), "--state", "absent_state"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + missed_json = json.loads(out) + self.assertEqual(missed_json["requested_state"], "absent_state") + self.assertIsNone(missed_json["first_verified_example"]) + + # Ambiguous --state mode. + rc, out, err = _run_main([str(ambig), "--state", "orbit_dup"]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + ambig_json = json.loads(out) + self.assertIsNone(ambig_json["first_verified_example"]) + self.assertEqual( + [c["node_path"] for c in ambig_json["ambiguous_state_candidates"]], + [[0, 1], [0, 3]], + ) + + # Subprocess parity and sys.argv/runpy entrypoint. + proc = _run_subprocess(str(single), "--state", "orbit_one") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), matched_json) + + with mock.patch.object(sys, "argv", [str(TOOL), str(single), "--state", "orbit_one"]): + rc_none, out_none, err_none = _run_main(None) + self.assertEqual(rc_none, 0, err_none) + self.assertEqual(json.loads(out_none), matched_json) + + out_runpy, err_runpy = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(single)]), + redirect_stdout(out_runpy), + redirect_stderr(err_runpy), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(err_runpy.getvalue(), "") + self.assertEqual(json.loads(out_runpy.getvalue()), default_json) + + def test_corrupt_or_truncated_zlib_yields_zero_node_trees_without_crash(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, kw in ( + ("corrupt_zlib", {"corrupt_zlib": True}), + ("truncated_zlib", {"truncate_zlib": True}), + ): + with self.subTest(case=label): + archive = root / f"{label}.rpf" + archive.write_bytes(_build_rpf9(_synth_record(**kw))) + rc, out, err = _run_main([str(archive)]) + self.assertEqual(rc, 0, err) + self.assertEqual(err, "") + payload = json.loads(out) + self.assertEqual(payload["counts"].get("node_trees", 0), 0) + self.assertEqual(payload["counts"], {}) + + +class ScriptStateProbeCliNegativeTests(unittest.TestCase): + def _assert_cli_failure( + self, + argv: list[str], + *, + expected_code: int, + fragment: str, + check_subprocess: bool = True, + ) -> None: + rc, out, err = _run_main(argv) + self.assertEqual(rc, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(fragment, proc.stderr) + + def test_upfront_is_file_and_archive_validation_controls(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.rpf" + folder = root / "dir_archive" + folder.mkdir() + empty = root / "empty.rpf" + empty.write_bytes(b"") + short_header = root / "short.rpf" + short_header.write_bytes(b"9FP") + bad_magic = root / "bad_magic.rpf" + bad_magic.write_bytes(b"NOPE" + b"\x00" * 16) + truncated_schema = root / "truncated_schema.rpf" + truncated_schema.write_bytes(_build_rpf9(_synth_record(truncate_schema_by=8))) + + # Missing and directory must reject upfront before open/mmap. + with ( + mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")), + mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")), + ): + with self.assertRaises(FileNotFoundError): + probe.inspect(missing) + with self.assertRaisesRegex(ValueError, "directory"): + probe.inspect(folder) + + self._assert_cli_failure([str(missing)], expected_code=1, fragment="not found") + self._assert_cli_failure([str(folder)], expected_code=1, fragment="directory") + + # 0-byte archive must fail cleanly before mmap.mmap. + with mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")): + with self.assertRaisesRegex(ValueError, "Empty archive"): + probe.inspect(empty) + self._assert_cli_failure([str(empty)], expected_code=1, fragment="Empty archive") + + # Truncated header, bad magic, and truncated inner schema. + self._assert_cli_failure([str(short_header)], expected_code=1, fragment="Expected an RPF9 archive") + self._assert_cli_failure([str(bad_magic)], expected_code=1, fragment="Expected an RPF9 archive") + self._assert_cli_failure([str(truncated_schema)], expected_code=1, fragment="Truncated schema members") + + def test_empty_and_non_ascii_state_validation(self): + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(_build_rpf9(_synth_record())) + + # Upfront state validation rejects before open/mmap. + with ( + mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")), + mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run")), + ): + with self.assertRaisesRegex(ValueError, "non-empty ASCII"): + probe.inspect(archive, "") + with self.assertRaisesRegex(ValueError, "ASCII"): + probe.inspect(archive, "café") + with self.assertRaisesRegex(ValueError, "non-empty ASCII"): + probe.joaat("", allow_empty=False) + + # Empty and non-ASCII --state via main(argv) and subprocess. + self._assert_cli_failure([str(archive), "--state", ""], expected_code=1, fragment="non-empty ASCII") + self._assert_cli_failure([str(archive), "--state", "café"], expected_code=1, fragment="ASCII") + + def test_argparse_errors_and_help_py314_compatible(self): + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(_build_rpf9(_synth_record())) + + for argv, fragment in ( + ([], "usage:"), + ([str(archive), "--unknown-flag"], "unrecognized"), + ([str(archive), "--state"], "--state"), + ): + with self.subTest(argv=argv): + self._assert_cli_failure(argv, expected_code=2, fragment=fragment) + + rc, out, err = _run_main(["--help"]) + self.assertEqual(rc, 0) + self.assertIn("usage:", out) + self.assertEqual(err, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/sgd5_effects_cli_check.py b/tests/sgd5_effects_cli_check.py new file mode 100644 index 0000000000..903bbb7cbf --- /dev/null +++ b/tests/sgd5_effects_cli_check.py @@ -0,0 +1,448 @@ +"""CLI, path-guard, short-read, error-handling, and mutation suite for tools/sgd5_effects.py.""" + +import argparse +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "sgd5_effects.py" +sys.path.insert(0, str(ROOT / "tools")) + +import sgd5_effects # noqa: E402 + + +def _word(value: int) -> bytes: + return struct.pack("<I", value) + + +def _len_name(text: str) -> bytes: + encoded = text.encode("ascii") + b"\0" + return bytes([len(encoded)]) + encoded + + +def _deflate_raw(blob: bytes, mode: int = zlib.Z_FINISH) -> bytes: + compressor = zlib.compressobj(wbits=-15) + return compressor.compress(blob) + compressor.flush(mode) + + +def _program_record(label: str, kind: int, identity: int, *, pack=_deflate_raw) -> tuple[bytes, str]: + dxil = struct.pack("<HHI4sIII4sI", 0x60, kind, 8, b"DXIL", 0x100, 16, 8, b"BC\xc0\xde", identity) + blob = b"DXBC" + bytes(16) + struct.pack("<4I", 1, 44 + len(dxil), 1, 36) + b"DXIL" + _word(len(dxil)) + dxil + packed = pack(blob) + size = 12 + len(packed) + wrapped = struct.pack("<3I", 0xddce7, size, len(blob)) + packed + reflection = _word(9) + struct.pack("<4H", 0, 0, 0, 9) + b"\0" + record = _len_name(label) + b"\x20" + _word(size) + wrapped + bytes(152) + reflection + return record, hashlib.sha256(blob).hexdigest() + + +def _effect_record(label: str, vs: list[int], ps: list[int]) -> bytes: + lists = b"".join(_word(len(group)) + b"".join(map(_word, group)) for group in (vs, ps, [], [], [], [])) + strings = b"\0entry\0" + return _len_name(label) + _word(0) + lists + b"\xff\xff" + _word(len(strings)) + strings + + +def _build_archive(prefix_len: int = 0) -> tuple[bytes, int, int, int, int, int, str, str]: + vs0, vs_digest = _program_record("vs_main", 1, 101) + ps0, ps_digest = _program_record("ps_main", 0, 202) + arrays = _word(1) + vs0 + _word(1) + ps0 + _word(0) * 4 + first = _effect_record("idle", [], []) + second = _effect_record("draw", [0], [0]) + header = bytes(prefix_len) + b"SGD5" + bytes(28) + arrays_start = len(header) + first_start = arrays_start + len(arrays) + 4 + second_start = first_start + len(first) + archive = header + arrays + _word(2) + first + second + return archive, prefix_len, len(archive), arrays_start, second_start, len(archive), vs_digest, ps_digest + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = sgd5_effects.main(argv) + except SystemExit as exc: + raw = exc.code + code = 0 if raw is None else (int(raw) if isinstance(raw, int) else 2) + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class Sgd5EffectsCliPositiveTests(unittest.TestCase): + def test_cli_zero_and_hex_offsets_exact_json_schema(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, prefix_len, fmt_offset in ( + ("zero_group_start", 0, str), + ("hex_offsets", 16, hex), + ): + with self.subTest(label=label): + data, grp_start, grp_end, arrays, rec_start, rec_end, vs_digest, ps_digest = _build_archive( + prefix_len + ) + archive = root / f"{label}.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + fmt_offset(grp_start), + fmt_offset(grp_end), + "--arrays", + fmt_offset(arrays), + "--record", + fmt_offset(rec_start), + fmt_offset(rec_end), + ] + expected = { + "effect": "draw", + "candidates": [ + { + "group": "VS", + "index": 0, + "name": "vs_main", + "dxil_kind": 1, + "container_sha256": vs_digest, + }, + { + "group": "PS", + "index": 0, + "name": "ps_main", + "dxil_kind": 0, + "container_sha256": ps_digest, + }, + ], + } + + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(set(doc), {"effect", "candidates"}) + self.assertEqual(doc, expected) + for item in doc["candidates"]: + self.assertEqual(set(item), {"group", "index", "name", "dxil_kind", "container_sha256"}) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), expected) + + self.assertEqual(sorted(p.name for p in root.iterdir()), ["hex_offsets.bin", "zero_group_start.bin"]) + + def test_main_sys_argv_and_script_entrypoint(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "entry.bin" + archive.write_bytes(data) + cli_argv = [ + str(TOOL), + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(json.loads(out)["candidates"]), 2) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(len(json.loads(stdout.getvalue())["candidates"]), 2) + + +class Sgd5EffectsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragment: str, + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment.lower(), proc.stderr.lower()) + + def test_py314_safe_argparse_errors_exit_nonzero_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "valid.bin" + archive.write_bytes(data) + base_argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + for label, argv, frag in ( + ("missing_all_args", [], "usage:"), + ("missing_required_flags", [str(archive), "draw"], "required"), + ("non_integer_arrays", [str(archive), "draw", "--group", "0", "1", "--arrays", "bad", "--record", "0", "1"], "invalid"), + ("unknown_flag", [*base_argv, "--unknown-flag"], "unrecognized"), + ): + with self.subTest(case=label): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + sgd5_effects.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_clean_failure(argv, expected_code=2, expected_fragment=frag) + + def test_negative_offsets_rejected_by_offset_parser_before_opening_archive(self) -> None: + self.assertEqual(sgd5_effects.offset("0"), 0) + self.assertEqual(sgd5_effects.offset("0x20"), 32) + for raw in ("-1", "-0x1", "-16"): + with self.subTest(raw=raw): + with self.assertRaises(argparse.ArgumentTypeError): + sgd5_effects.offset(raw) + + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + existing = Path(tmp) / "existing.bin" + existing.write_bytes(data) + missing = Path(tmp) / "missing.bin" + + for archive in (existing, missing): + for label, bad_argv in ( + ("neg_group_start", [str(archive), "draw", "--group", "-1", str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), + ("neg_group_end", [str(archive), "draw", "--group", str(grp_start), "-1", "--arrays", str(arrays), "--record", str(rec_start), str(rec_end)]), + ("neg_arrays", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays=-0x1", "--record", str(rec_start), str(rec_end)]), + ("neg_record_start", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", "-1", str(rec_end)]), + # Older argparse versions treat a separate negative hex token as an option, not as an offset. + ("neg_record_end", [str(archive), "draw", "--group", str(grp_start), str(grp_end), "--arrays", str(arrays), "--record", str(rec_start), "-16"]), + ): + with self.subTest(archive=archive.name, case=label): + with mock.patch.object( + sgd5_effects, + "candidates", + side_effect=AssertionError("candidates called for negative offset"), + ): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragment="non-negative", + ) + + def test_non_file_and_missing_archive_rejected_upfront_before_candidates(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dir_path = root / "archive_dir" + dir_path.mkdir() + missing_path = root / "missing.bin" + + for label, bad_archive in ( + ("directory", str(dir_path)), + ("empty_cwd_dir", ""), + ("missing_file", str(missing_path)), + ): + with self.subTest(case=label): + argv = [ + bad_archive, + "draw", + "--group", + "0", + "64", + "--arrays", + "32", + "--record", + "48", + "64", + ] + with mock.patch.object( + sgd5_effects, + "candidates", + side_effect=AssertionError(f"candidates called for invalid archive {label}"), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment="regular file", + check_subprocess=bool(bad_archive), + ) + + def test_cursor_short_and_overlong_reads_and_negative_skip_rejected(self) -> None: + class _FakeView: + def __init__(self, payload: bytes) -> None: + self._payload = payload + + def read(self, offset: int, length: int) -> bytes: + return self._payload + + for label, payload, request in ( + ("empty_short_read", b"", 4), + ("partial_short_read", b"abc", 4), + ("overlong_read", b"abcde", 4), + ): + with self.subTest(case=label): + cursor = sgd5_effects.Cursor(_FakeView(payload), 0, 16) + with self.assertRaisesRegex(ValueError, "Truncated"): + cursor.read(request) + + neg_cursor = sgd5_effects.Cursor(_FakeView(b"abcd"), 4, 16) + with self.assertRaisesRegex(ValueError, "Negative"): + neg_cursor.skip(-1) + self.assertEqual(neg_cursor.pos, 4) + + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "short_read.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + with mock.patch.object(sgd5_effects.PagedResource, "read", side_effect=[b"SGD5", b"SG"]): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment="Truncated", + check_subprocess=False, + ) + + def test_os_value_struct_and_zlib_errors_caught_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + data, grp_start, grp_end, arrays, rec_start, rec_end, _, _ = _build_archive(0) + archive = Path(tmp) / "probe.bin" + archive.write_bytes(data) + argv = [ + str(archive), + "draw", + "--group", + str(grp_start), + str(grp_end), + "--arrays", + str(arrays), + "--record", + str(rec_start), + str(rec_end), + ] + + # Real corrupt archive checks via both in-process main() and subprocess. + bad_magic = bytearray(data) + bad_magic[0:4] = b"BAD!" + bad_magic_path = Path(tmp) / "bad_magic.bin" + bad_magic_path.write_bytes(bad_magic) + self._assert_clean_failure( + [str(bad_magic_path), *argv[1:]], + expected_code=1, + expected_fragment="Missing SGD5 group header", + ) + + vs_bad, _ = _program_record("vs_main", 1, 101, pack=lambda blob: b"\xff" * len(_deflate_raw(blob))) + ps0, _ = _program_record("ps_main", 0, 202) + bad_arrays = _word(1) + vs_bad + _word(1) + ps0 + _word(0) * 4 + draw_effect = _effect_record("draw", [0], [0]) + bad_zlib_bytes = ( + b"SGD5" + + bytes(28) + + bad_arrays + + _word(2) + + _effect_record("idle", [], []) + + draw_effect + ) + bad_zlib_path = Path(tmp) / "bad_zlib.bin" + bad_zlib_path.write_bytes(bad_zlib_bytes) + self._assert_clean_failure( + [ + str(bad_zlib_path), + "draw", + "--group", + "0", + str(len(bad_zlib_bytes)), + "--arrays", + "32", + "--record", + str(len(bad_zlib_bytes) - len(draw_effect)), + str(len(bad_zlib_bytes)), + ], + expected_code=1, + expected_fragment="Invalid compressed SGD5 candidate", + ) + + # Direct error-tuple mutation controls for (OSError, ValueError, struct.error, zlib.error). + for exc in ( + OSError("simulated read error"), + ValueError("simulated validation error"), + struct.error("unpack requires a buffer of 12 bytes"), + zlib.error("Error -3 while decompressing data"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(sgd5_effects, "candidates", side_effect=exc): + self._assert_clean_failure( + argv, + expected_code=1, + expected_fragment=str(exc), + check_subprocess=False, + ) + + self.assertEqual( + sorted(p.name for p in Path(tmp).iterdir()), + ["bad_magic.bin", "bad_zlib.bin", "probe.bin"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/shader_census_cli_check.py b/tests/shader_census_cli_check.py new file mode 100644 index 0000000000..d02e8fbd46 --- /dev/null +++ b/tests/shader_census_cli_check.py @@ -0,0 +1,296 @@ +"""Pure-Python CLI, boundary, error-guard, and mutation suite for tools/shader_census.py.""" +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "shader_census.py" +sys.path.insert(0, str(ROOT / "tools")) + +import shader_census as sc # noqa: E402 + + +def _make_dxbc(digest_byte: int, word: int, stage: int = 0) -> bytes: + program = struct.pack("<II4sIII", (stage << 16) | 0x60, 7, b"DXIL", 0x100, 16, 4) + struct.pack("<I", word) + return ( + b"DXBC" + + bytes([digest_byte]) * 16 + + struct.pack("<4I", 1, 44 + len(program), 1, 36) + + b"DXIL" + + struct.pack("<I", len(program)) + + program + ) + + +def _make_record(blob: bytes, name: str = "owned_shader") -> bytes: + encoder = zlib.compressobj(wbits=-15) + payload = encoder.compress(blob) + encoder.flush() + return ( + name.encode("ascii") + + b"\0\0" + + struct.pack("<4I", len(payload), 0, len(payload), len(blob)) + + payload + ) + + +def _make_archive() -> bytes: + a = _make_dxbc(1, 17, stage=0) + b = _make_dxbc(1, 18, stage=0) + c = _make_dxbc(2, 19, stage=5) + return _make_record(a) + _make_record(a) + _make_record(b) + _make_record(c) + + +def _make_ps9_cache(entries: list[tuple[int, int]] | None = None) -> tuple[bytes, int]: + entries = entries if entries is not None else [(0, 16), (16, 16), (0, 16), (32, 32)] + index_start = 128 + 0x70 + 2 * 0x18 + 3 * 8 + code_base = index_start + len(entries) * 8 + data = bytearray(code_base + 96) + data[:4] = b"PS\x00\x09" + struct.pack_into("<4I", data, 80, 1, 2, 3, len(entries)) + for i, (offset, size) in enumerate(entries): + struct.pack_into("<2I", data, index_start + i * 8, offset, size) + return bytes(data), code_base + + +class ShaderCensusCliTests(unittest.TestCase): + def _run_main(self, argv: list[str]) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + code = 0 + with redirect_stdout(out), redirect_stderr(err): + try: + ret = sc.main(argv) + code = 0 if ret is None else ret + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, out.getvalue(), err.getvalue() + + def _assert_main_fails(self, argv: list[str], *, expected_code: int, fragment: str | tuple[str, ...]) -> str: + code, stdout, stderr = self._run_main(argv) + self.assertEqual(code, expected_code, f"argv={argv!r} stderr={stderr!r}") + self.assertEqual(stdout, "") + self.assertNotIn("Traceback", stderr) + fragments = (fragment,) if isinstance(fragment, str) else fragment + self.assertTrue( + any(f in stderr for f in fragments), + f"none of {fragments!r} found in {stderr!r}", + ) + return stderr + + def test_main_argv_forwarding_and_json_schema(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + cache_bytes, base = _make_ps9_cache() + cache.write_bytes(cache_bytes) + + # Mutating sys.argv ensures main(argv) forwards its explicit argv parameter. + with mock.patch.object(sys, "argv", ["shader_census.py", "--bogus-global-flag"]): + for base_arg in (str(base), hex(base)): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + rc = sc.main([str(archive), "--cache-blob", str(cache), "--code-base", base_arg]) + self.assertEqual(rc, 0) + self.assertEqual(err.getvalue(), "") + doc = json.loads(out.getvalue()) + self.assertEqual( + set(doc), + { + "archive_records", + "dxbc_header_digests", + "classification_cache", + "cache_index", + "candidate_rejections", + }, + ) + self.assertEqual(doc["archive_records"]["count"], 4) + self.assertEqual(doc["archive_records"]["stages"], {"pixel": 3, "compute": 1}) + self.assertTrue(doc["archive_records"]["coverage_denominator"]) + self.assertEqual(doc["dxbc_header_digests"]["count"], 2) + self.assertFalse(doc["dxbc_header_digests"]["integrity_verified"]) + self.assertEqual(doc["classification_cache"]["count"], 3) + self.assertEqual(doc["cache_index"]["count"], 4) + self.assertEqual(doc["cache_index"]["distinct_spans"], 3) + self.assertEqual(doc["cache_index"]["aliased_entries"], 1) + self.assertEqual(doc["cache_index"]["code_base"], base) + self.assertEqual(doc["cache_index"]["index_offset"], 312) + self.assertEqual(doc["cache_index"]["program_validation"], "not performed") + + # Archive-only subprocess CLI check. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive)], + capture_output=True, + text=True, + check=True, + ) + sub_doc = json.loads(proc.stdout) + self.assertEqual(sub_doc["archive_records"]["count"], 4) + self.assertIsNone(sub_doc["cache_index"]) + + def test_zero_byte_archive_and_cache_blob(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + empty_archive = root / "empty.archive" + empty_cache = root / "empty.cache" + empty_archive.write_bytes(b"") + empty_cache.write_bytes(b"") + + # 0-byte archive succeeds cleanly without mmap ValueError. + code, out, err = self._run_main([str(empty_archive)]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(doc["archive_records"]["count"], 0) + self.assertIsNone(doc["cache_index"]) + + # 0-byte --cache-blob exits 1 with 'Shader census:' (never mmap ValueError traceback). + stderr = self._assert_main_fails( + [str(empty_archive), "--cache-blob", str(empty_cache), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + self.assertIn("128-byte header", stderr) + + def test_directory_and_missing_path_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + archive.write_bytes(_make_archive()) + subdir = root / "a_dir" + subdir.mkdir() + + # Directory passed as archive -> exit 1 with 'Shader census:' and 'directory'. + err_arch = self._assert_main_fails([str(subdir)], expected_code=1, fragment="Shader census:") + self.assertIn("directory", err_arch.lower()) + + # Directory passed as --cache-blob -> exit 1 with 'Shader census:' and 'directory'. + err_blob = self._assert_main_fails( + [str(archive), "--cache-blob", str(subdir), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + self.assertIn("directory", err_blob.lower()) + + # Missing archive and missing --cache-blob -> exit 1 with 'Shader census:'. + self._assert_main_fails([str(root / "missing.archive")], expected_code=1, fragment="Shader census:") + self._assert_main_fails( + [str(archive), "--cache-blob", str(root / "missing.cache"), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + + def test_mismatched_and_negative_code_base_exit_2(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + cache_bytes, base = _make_ps9_cache() + cache.write_bytes(cache_bytes) + + # Mismatched --cache-blob / --code-base -> argparse exit 2. + self._assert_main_fails([str(archive), "--cache-blob", str(cache)], expected_code=2, fragment="supplied together") + self._assert_main_fails([str(archive), "--code-base", hex(base)], expected_code=2, fragment="supplied together") + + # Negative --code-base (decimal and hex) -> parser.error exit 2. + for args_extra in (["--code-base", "-1"], ["--code-base=-1"], ["--code-base=-0x10"]): + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), *args_extra], + expected_code=2, + fragment="non-negative", + ) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "-0x10"], + expected_code=2, + fragment=("expected one argument", "non-negative"), + ) + + # Non-integer --code-base -> exit 2. + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "not_an_int"], + expected_code=2, + fragment="invalid", + ) + + def test_malformed_truncated_inputs_and_struct_zlib_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "owned.archive" + cache = root / "decoded.cache" + archive.write_bytes(_make_archive()) + + # Truncated PS/9 cache (<128 bytes) -> exit 1 with 'Shader census:'. + cache.write_bytes(b"PS\x00\x09" + b"\x00" * 123) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", "128"], + expected_code=1, + fragment="Shader census:", + ) + + # Out-of-bounds code_base or overlapping allocations -> exit 1 with 'Shader census:'. + bad_cache, bad_base = _make_ps9_cache([(0, 32), (16, 16)]) + cache.write_bytes(bad_cache) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(bad_base)], + expected_code=1, + fragment="Shader census:", + ) + good_cache, good_base = _make_ps9_cache() + cache.write_bytes(good_cache) + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(len(good_cache) + 1)], + expected_code=1, + fragment="Shader census:", + ) + + # Corrupt deflate payload and truncated span in archive -> cleanly counted in candidate_rejections. + corrupt_deflate = b"bad_rec\0\0" + struct.pack("<4I", 20, 0, 20, 64) + b"\xff" * 20 + truncated_span = b"trunc_rec\0\0" + struct.pack("<4I", 64, 0, 64, 64) + b"\x00" * 8 + archive.write_bytes(_make_archive() + corrupt_deflate + truncated_span) + code, out, err = self._run_main([str(archive)]) + self.assertEqual(code, 0, err) + doc = json.loads(out) + self.assertEqual(doc["archive_records"]["count"], 4) + self.assertEqual(doc["candidate_rejections"]["deflate_error"], 1) + self.assertEqual(doc["candidate_rejections"]["truncated_span"], 1) + + # Direct struct.error and zlib.error propagation -> guarded to exit 1 with 'Shader census:'. + archive.write_bytes(_make_archive()) + for err_obj in (struct.error("truncated header"), zlib.error("corrupt deflate stream")): + with mock.patch.object(sc, "scene_records", side_effect=err_obj): + self._assert_main_fails( + [str(archive)], + expected_code=1, + fragment=f"Shader census: {err_obj}", + ) + with mock.patch.object(sc, "cache_index", side_effect=err_obj): + self._assert_main_fails( + [str(archive), "--cache-blob", str(cache), "--code-base", str(good_base)], + expected_code=1, + fragment=f"Shader census: {err_obj}", + ) + + # Subprocess end-to-end negative check verifying zero raw traceback on stderr. + sub_fail = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive), "--cache-blob", str(cache), "--code-base=-4"], + capture_output=True, + text=True, + ) + self.assertEqual(sub_fail.returncode, 2) + self.assertNotIn("Traceback", sub_fail.stderr) + self.assertIn("non-negative", sub_fail.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/shader_signed_zero_minmax_check.py b/tests/shader_signed_zero_minmax_check.py new file mode 100644 index 0000000000..035bc91fd5 --- /dev/null +++ b/tests/shader_signed_zero_minmax_check.py @@ -0,0 +1,276 @@ +"""Source-built gfx1013 min/max translation and pixel checks. + +No arguments checks the emitted HLSL. Binary mode verifies the encodings with +llvm-mc. The before, draw, plain and invert modes take DXC, offscreen_check, +the adapter name and optionally FXC. +""" + +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from startup_gfx2hlsl_bit_alu_check import G, POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, vs_source, vs_words +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob + +import pixel_aot + +NEG_ZERO, POS_ZERO = 0x80000000, 0 +NEG_ONE, TWO, NAN = 0xbf800000, 0x40000000, 0x7fc01234 +CASE_TEXELS = 8 * 8 +DRAW_TEXELS = 64 * 64 +OPS = { + "min": ("v_min_f32_e32", 2), "max": ("v_max_f32_e32", 2), + "min-e64": ("v_min_f32_e64", 2), "max-e64": ("v_max_f32_e64", 2), + "min3": ("v_min3_f32", 3), "max3": ("v_max3_f32", 3), "med3": ("v_med3_f32", 3), + "min-sdwa": ("v_min_f32_sdwa", 2), "max-sdwa": ("v_max_f32_sdwa", 2), + "min-dpp": ("v_min_f32_dpp", 2), "max-dpp": ("v_max_f32_dpp", 2), + "min-pack": ("v_pk_min_f16", 2), "max-pack": ("v_pk_max_f16", 2), +} +STARTUP_OPS = ("min", "max", "min-e64", "max-e64", "min3", "max3", "med3") +BODY_WORDS = { + "min": "0009181e010b1a1e020d1c1e030f1e1e", + "max": "00091820010b1a20020d1c20030f1e20", + "min-e64": "0c000fd5000902000d000fd5010b02000e000fd5020d02000f000fd5030f0200", + "max-e64": "0c0010d5000902000d0010d5010b02000e0010d5020d02000f0010d5030f0200", + "min3": "0c0051d5000922040d0051d5010b26040e0051d5020d2a040f0051d5030f2e04", + "max3": "0c0054d5000922040d0054d5010b26040e0054d5020d2a040f0054d5030f2e04", + "med3": "0c0057d5000922040d0057d5010b26040e0057d5020d2a040f0057d5030f2e04", + "min-sdwa": "f908181e00060606f90a1a1e01060606f90c1c1e02060606f90e1e1e03060606", + "max-sdwa": "f908182000060606f90a1a2001060606f90c1c2002060606f90e1e2003060606", + "min-dpp": "fa08181e00e400fffa0a1a1e01e400fffa0c1c1e02e400fffa0e1e1e03e400ff", + "max-dpp": "fa08182000e400fffa0a1a2001e400fffa0c1c2002e400fffa0e1e2003e400ff", + "min-pack": "0c4011cc000902180d4011cc010b02180e4011cc020d02180f4011cc030f0218", + "max-pack": "0c4012cc000902180d4012cc010b02180e4012cc020d02180f4012cc030f0218", +} + +PIXEL_PREFIX = """s_mov_b32 s21, 0 +s_load_dwordx4 s[44:47], s[20:21], 0x40 +s_waitcnt lgkmcnt(0) +s_buffer_load_dwordx4 s[48:51], s[44:47], 0xc +s_buffer_load_dwordx4 s[52:55], s[44:47], 0x1c +s_buffer_load_dwordx4 s[56:59], s[44:47], 0x2c +s_waitcnt lgkmcnt(0) +""" + "".join(f"v_mov_b32_e32 v{i}, s{48 + i}\n" for i in range(12)) +PIXEL_PREFIX_WORDS = ( + "800395be0a0b08f4400000fa7fc08cbf160c28f40c0000fa160d28f41c0000fa" + "160e28f42c0000fa7fc08cbf3002007e3102027e3202047e3302067e3402087e" + "35020a7e36020c7e37020e7e3802107e3902127e3a02147e3b02167e" +) + + +def body_source(op): + mnemonic, arity = OPS[op] + mods = "" + if op.endswith("-sdwa"): + mods = " dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD" + if op.endswith("-dpp"): + mods = " quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf" + return "".join(f"{mnemonic} v{12 + lane}, " + + ", ".join(f"v{lane + 4 * arg}" for arg in range(arity)) + mods + "\n" + for lane in range(4)) + + +def draw_cases(op): + nz, pz = NEG_ZERO, POS_ZERO + if op.endswith("-pack"): + # Each word has distinct low and high halves. The first two lanes swap the packed operands. + return (((0x00008000, 0x80000000, 0), (0x80000000, 0x00008000, 0), + (0x80000000, 0x80000000, 0), (0x00008000, 0x00008000, 0)), + ((0x7e003c00, 0x4000fe00, 0), (0x4000fe00, 0x7e003c00, 0), + (0x3c00bc00, 0x40004000, 0), (0x40004000, 0x3c00bc00, 0))) + if OPS[op][1] == 2: + return (((nz, pz, 0), (pz, nz, 0), (nz, nz, 0), (pz, pz, 0)), + ((NAN, NEG_ONE, 0), (NEG_ONE, NAN, 0), (NAN, TWO, 0), (NEG_ONE, TWO, 0))) + return (((nz, pz, NEG_ONE), (pz, nz, NEG_ONE), (nz, pz, TWO), (pz, nz, TWO)), + ((nz, nz, pz), (pz, pz, nz), (nz, pz, pz), (pz, nz, nz)), + ((NAN, NEG_ONE, TWO), (NEG_ONE, NAN, TWO), (NEG_ONE, TWO, NAN), (NEG_ONE, pz, TWO))) + + +def value(bits, size): + return struct.unpack("<e" if size == 16 else "<f", bits.to_bytes(size // 8, "little"))[0] + + +def ordered(word, size): + # Sort zeros by their sign after comparing numerical values. + return value(word, size), word != 1 << (size - 1) + + +def reference(op, words, kind): + if op.endswith("-pack"): + def lane(shift): + selected = [(word >> shift) & 0xffff for word in words[:2]] + return reference_word(op, selected, 16, kind) + return lane(0) | (lane(16) << 16) + return reference_word(op, words[:OPS[op][1]], 32, kind) + + +def reference_word(op, words, size, kind): + numeric = [word for word in words if not math.isnan(value(word, size))] + ordered_words = sorted(numeric, key=lambda word: ordered(word, size)) + if op.startswith("min"): + return ordered_words[0] + if op.startswith("max"): + return ordered_words[-1] + # A NaN source makes V_MED3_F32 return V_MIN3_F32 of the three: the smallest number (#2095). + if len(numeric) < len(words): + return ordered_words[0] + return ordered_words[1] + + +def pixel_hlsl(op): + code = bytes.fromhex(PIXEL_PREFIX_WORDS + BODY_WORDS[op]) + POST_WORDS + asm = [line for _, _, _, line in G.decode(code)] + return pixel_aot.lower(asm, 20, 24, None, constant_descriptor=64, integer_export=True) + + +def startup_pipeline(op, rows): + ps = PRE_WORDS + bytes.fromhex(BODY_WORDS[op]) + POST_WORDS + return G.Pipeline(vs_words(rows), ps, root_blob()) + + +def check_binary(llvm_mc): + assert assemble(llvm_mc, PIXEL_PREFIX).hex() == PIXEL_PREFIX_WORDS, "pixel constant-load prologue" + for op in OPS: + assert assemble(llvm_mc, body_source(op)).hex() == BODY_WORDS[op], op + if op in STARTUP_OPS: + for rows in draw_cases(op): + assert assemble(llvm_mc, vs_source(rows)) == vs_words(rows), op + assert assemble(llvm_mc, PRE_SOURCE + body_source(op) + POST_SOURCE) == ( + PRE_WORDS + bytes.fromhex(BODY_WORDS[op]) + POST_WORDS), op + print("All signed-zero fixtures match llvm-mc") + + +def check_lowering(kind, op, source): + assert "uint a_bits = asuint(a), b_bits = asuint(b);" in source + assert "uint either = a_bits | b_bits;" in source + assert "uint zero = maximum ? (a_bits & b_bits) : either;" in source + assert "return asfloat((either & 0x7fffffffu) == 0u ? zero :" in source + body = source[source.index(" main("):] + polarity = "true" if op.startswith("max") else "false" + if op.endswith("-pack"): + assert "isnan(a) ? b : (isnan(b) ? a : minmax_zero32(a, b, maximum))" in source + assert body.count("minmax16_num(") == body.count(", " + polarity + ")") == 8, (op, body) + elif op == "med3": + name = "med3_32" + assert body.count(name + "(") == 4, (kind, body) + start = source.index("float " + name + "(") + helper = source[start:source.index("\n}", start)] + assert helper.count("minmax_zero32(") == 6, helper + else: + count = 8 if OPS[op][1] == 3 else 4 + assert body.count("minmax_zero32(") == body.count(", " + polarity + ")") == count, (op, body) + + +def mutate(source, mode): + start = source.index("float minmax_zero32(") + end = source.index("\n}", start) + helper = source[start:end] + if mode == "plain": + replacement = helper.splitlines()[0] + "\n return maximum ? max(a, b) : min(a, b);" + else: + replacement = helper.replace("maximum ? (a_bits & b_bits) : either", + "maximum ? either : (a_bits & b_bits)") + assert replacement != helper + return source[:start] + replacement + source[end:] + + +def check_translation(): + for kind, ops in (("pixel", OPS), ("startup", STARTUP_OPS)): + for op in ops: + source = pixel_hlsl(op) if kind == "pixel" else startup_pipeline(op, draw_cases(op)[0]).hlsl_ps() + check_lowering(kind, op, source) + for mode in ("plain", "invert"): + try: + check_lowering(kind, op, mutate(source, mode)) + except AssertionError: + continue + raise AssertionError(f"{kind} {op} accepted the {mode} control") + print("20 signed-zero lowering checks reject both helper mutations") + + +def pixel_readback(renderer, backend, directory, shader, rows, expect): + # Existing integer-target case format, with three runtime uint4 operands from b0. + constants = [0] * 64 + for arg in range(3): + constants[3 + 4 * arg:7 + 4 * arg] = [row[arg] for row in rows] + case, raw = (directory / name for name in ("minmax.case", "minmax.bin")) + case.write_bytes(struct.pack("<64I", *constants) + struct.pack("<4I", *expect) * CASE_TEXELS + b"\x01") + raw.unlink(missing_ok=True) + run = subprocess.run([renderer, backend, "--check-pixel-case", str(shader), str(case), str(raw)], + capture_output=True, text=True) + return run, tuple(struct.iter_unpack("<4I", raw.read_bytes())) if raw.exists() else () + + +def startup_readback(renderer, backend, vs, ps, expect): + run = draw(renderer, backend, vs, ps, ",".join(f"{word:08x}" for word in expect)) + match = re.search(r"startup_flat_param words=([0-9a-f,]+)", run.stdout) + return run, (tuple(int(word, 16) for word in match[1].split(",")),) if match else () + + +def check_draw(mode, dxc, renderer, backend, fxc=None): + renderer = str(Path(renderer).resolve()) + sites = [("pixel", dxc, "dxc", "ps_6_2"), ("startup", dxc, "dxc", "ps_6_0")] + if fxc: + sites.append(("startup", fxc, "fxc", "ps_5_1")) + out = Path(__file__).resolve().parents[1] / "out" + out.mkdir(exist_ok=True) + mismatches = total = 0 + with tempfile.TemporaryDirectory(dir=out) as tmp: + directory = Path(tmp) + for kind, compiler, tool, profile in sites: + for op in OPS if kind == "pixel" else STARTUP_OPS: + cases = draw_cases(op) + source = pixel_hlsl(op) if kind == "pixel" else startup_pipeline(op, cases[0]).hlsl_ps() + if mode in ("plain", "invert"): + source = mutate(source, mode) + if kind == "pixel": + hlsl, shader = (directory / name for name in ("pixel.hlsl", "pixel.cso")) + hlsl.write_text(source, encoding="ascii") + subprocess.run([dxc, "-Gis", "-T", profile, "-E", "main", "-Fo", str(shader), str(hlsl)], + check=True) + else: + shader = compile_hlsl(compiler, tool, source, "pixel", profile, directory) + for index, rows in enumerate(cases): + expected = tuple(reference(op, row, kind) for row in rows) + if kind == "pixel": + run, raw = pixel_readback(renderer, backend, directory, shader, rows, expected) + else: + pipeline = startup_pipeline(op, rows) + vs = compile_hlsl(compiler, tool, pipeline.hlsl_vs(), "vertex", profile.replace("ps", "vs"), directory) + run, raw = startup_readback(renderer, backend, vs, shader, expected) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + pixel_count = DRAW_TEXELS if kind == "pixel" else 1 + if len(raw) != pixel_count: + raise AssertionError(f"{kind} {op}: expected {pixel_count} readback pixels, got {len(raw)}\n" + f"{run.stdout}\n{run.stderr}") + if (any(row != raw[0] for row in raw) or run.returncode not in (0, 1) + or ("debug_layer=enabled" in run.stdout and "debug_errors=0 debug_warnings=0" not in run.stdout)): + raise AssertionError(f"{kind} {op}: {run.stdout}\n{run.stderr}") + got = ",".join(f"{word:08x}" for word in raw[0]) + want = ",".join(f"{word:08x}" for word in expected) + print(f"{backend} {kind} {profile} {op} row {index}: {got} (expected {want})") + if bool(run.returncode) != (raw[0] != expected): + raise AssertionError(f"{kind} {op}: {run.stdout}\n{run.stderr}") + mismatches += sum(got != want for got, want in zip(raw[0], expected)) + total += len(expected) + print(f"{backend} {mode}: {mismatches}/{total} result words differ") + if mode == "invert" and not mismatches: + raise AssertionError("The inverted sign rule escaped detection") + return int(mode != "before" and mismatches != 0) + + +if __name__ == "__main__": + if len(sys.argv) == 3 and sys.argv[1] == "binary": + check_binary(sys.argv[2]) + elif len(sys.argv) in (5, 6) and sys.argv[1] in ("before", "draw", "plain", "invert"): + sys.exit(check_draw(*sys.argv[1:])) + elif len(sys.argv) == 1: + check_translation() + else: + sys.exit(__doc__) diff --git a/tests/spirv_address_window_cli_check.py b/tests/spirv_address_window_cli_check.py new file mode 100644 index 0000000000..cf3e9905eb --- /dev/null +++ b/tests/spirv_address_window_cli_check.py @@ -0,0 +1,433 @@ +#!/usr/bin/env python3 +"""Pure-Python mocked-subprocess CLI, atomic-write, path-guard, and cleanup suite for tools/spirv_address_window.py.""" + +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +import os +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "spirv_address_window.py" +FIXTURES = ROOT / "tests" / "spirv_window" +sys.path.insert(0, str(TOOLS_DIR)) +import spirv_address_window as saw # noqa: E402 + + +SUBTRACT_ASM = (FIXTURES / "subtract.spvasm").read_text(encoding="utf-8") +_REAL_SUBPROCESS_RUN = subprocess.run + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + import io + + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = saw.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return _REAL_SUBPROCESS_RUN( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class SpirvAddressWindowCliPositiveTests(unittest.TestCase): + def test_atomic_spv_in_nested_dir_overwrite_and_zero_temp_dirs(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + nested_out = work / "nested" / "deep" / "window.spv" + + calls: list[list[str]] = [] + seen_asm: dict[str, str] = {} + created_tempdirs: list[Path] = [] + replaced_pairs: list[tuple[Path, Path]] = [] + real_tempdir = tempfile.TemporaryDirectory + real_replace = Path.replace + payload_counter = [0] + + class TrackingTempDir(real_tempdir): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + created_tempdirs.append(Path(self.name)) + + def tracking_replace(self_path: Path, target: Path): + replaced_pairs.append((self_path, Path(target))) + self.assertEqual(self_path.parent.parent.resolve(), Path(target).parent.resolve()) + return real_replace(self_path, target) + + def fake_run(cmd, check=False, **_kwargs): + self.assertTrue(check) + calls.append([str(part) for part in cmd]) + if cmd[0] == "mock-as": + asm_path = Path(cmd[3]) + seen_asm[asm_path.name] = asm_path.read_text(encoding="utf-8") + out_idx = cmd.index("-o") + 1 + payload_counter[0] += 1 + Path(cmd[out_idx]).write_bytes(f"SPV_V{payload_counter[0]}".encode("ascii")) + return subprocess.CompletedProcess(cmd, 0) + + with ( + mock.patch.object(saw.subprocess, "run", side_effect=fake_run), + mock.patch.object(saw.tempfile, "TemporaryDirectory", TrackingTempDir), + mock.patch.object(Path, "replace", tracking_replace), + ): + # 1) Nested missing parent directories, atomic replace, 0 leftover temp dirs. + code, out, err = _run_main([ + str(src), + str(nested_out), + "--assembler", + " mock-as ", + "--validator", + " mock-val ", + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(nested_out.read_bytes(), b"SPV_V2") + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["window.spv"]) + self.assertEqual(len(created_tempdirs), 1) + self.assertFalse(created_tempdirs[0].exists()) + self.assertEqual(len(replaced_pairs), 1) + self.assertEqual(replaced_pairs[0][1].resolve(), nested_out.resolve()) + + self.assertEqual(len(calls), 4) + self.assertEqual(calls[0][:3], ["mock-as", "--target-env", "vulkan1.2"]) + self.assertEqual(Path(calls[0][3]).name, "original.spvasm") + self.assertEqual(calls[1][:3], ["mock-val", "--target-env", "vulkan1.2"]) + self.assertEqual(calls[2][:3], ["mock-as", "--target-env", "vulkan1.2"]) + self.assertEqual(Path(calls[2][3]).name, "logical.spvasm") + self.assertEqual(calls[3][:3], ["mock-val", "--target-env", "vulkan1.2"]) + self.assertEqual(seen_asm["original.spvasm"], SUBTRACT_ASM) + self.assertIn("OpMemoryModel Logical GLSL450", seen_asm["logical.spvasm"]) + self.assertNotIn("PhysicalStorageBuffer", seen_asm["logical.spvasm"]) + + # 2) Atomic overwrite on existing file leaves 0 temp dirs. + calls.clear() + code_ow, out_ow, err_ow = _run_main([ + str(src), + str(nested_out), + "--assembler", + "mock-as", + "--validator", + "mock-val", + ]) + self.assertEqual(code_ow, 0, err_ow) + self.assertEqual(out_ow, "") + self.assertEqual(err_ow, "") + self.assertEqual(nested_out.read_bytes(), b"SPV_V4") + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["window.spv"]) + self.assertEqual(len(created_tempdirs), 2) + self.assertFalse(created_tempdirs[1].exists()) + + # 3) argv=None forwards sys.argv cleanly. + with mock.patch.object( + sys, + "argv", + [str(TOOL), str(src), str(nested_out), "--assembler", "mock-as", "--validator", "mock-val"], + ): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(out_none, "") + self.assertEqual(err_none, "") + self.assertEqual(nested_out.read_bytes(), b"SPV_V6") + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["window.spv"]) + self.assertFalse(created_tempdirs[2].exists()) + + # 4) __main__ entrypoint exits cleanly on invalid source without raw traceback. + import io + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(work / "absent.spvasm"), str(work / "out.spv")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("source file not found", stderr_m.getvalue().lower()) + + +class SpirvAddressWindowCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_dir_and_bad_utf8_source_rejected_without_creating_parent(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + dir_src = work / "dir_source" + dir_src.mkdir() + bad_utf8 = work / "bad_utf8.spvasm" + bad_utf8.write_bytes(b"\xff\xfe\x00\x80") + absent_out = work / "never_created" / "window.spv" + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for invalid source"), + ): + for label, src, frags in ( + ("missing_source", work / "missing.spvasm", ("source file not found",)), + ("directory_source", dir_src, ("directory",)), + ("bad_utf8_source", bad_utf8, ("decode",)), + ): + with self.subTest(case=label): + self._assert_clean_failure( + [str(src), str(absent_out), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=frags, + ) + self.assertFalse(absent_out.parent.exists()) + + def test_output_guards_dir_file_parent_and_samefile(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + out_dir = work / "existing_dir.spv" + out_dir.mkdir() + file_parent = work / "file_parent" + file_parent.write_bytes(b"keep-parent-bytes") + hardlink = work / "subtract_hardlink.spv" + hardlink.hardlink_to(src) + missing_src = work / "missing.spvasm" + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for invalid output"), + ): + for label, argv, frags in ( + ("output_is_dir", [str(src), str(out_dir)], ("directory",)), + ("parent_is_file", [str(src), str(file_parent / "window.spv")], ("not a directory",)), + ("ancestor_is_file", [str(src), str(file_parent / "sub" / "window.spv")], ("not a directory",)), + ("same_exact_path", [str(src), str(src)], ("separate input assembly and output binary",)), + ( + "same_unnormalized_path", + [str(src), str(work / "nested" / ".." / "subtract.spvasm")], + ("separate input assembly and output binary",), + ), + ( + "same_missing_alias", + [str(missing_src), str(work / "nested" / ".." / "missing.spvasm")], + ("separate input assembly and output binary",), + ), + ("hardlink_samefile", [str(src), str(hardlink)], ("separate input assembly and output binary",)), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags) + + self.assertEqual(src.read_text(encoding="utf-8"), SUBTRACT_ASM) + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(file_parent.read_bytes(), b"keep-parent-bytes") + + def test_output_symlink_rejected_before_subprocess(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + out_dir = work / "out_dir" + out_dir.mkdir() + real_target = out_dir / "real.spv" + real_target.write_bytes(b"UNTOUCHED") + live_link = out_dir / "live_link.spv" + dangling_link = out_dir / "dangling_link.spv" + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.spv") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + self.skipTest("this Windows account cannot create symlinks (WinError 1314)") + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for symlink output"), + ): + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(src), str(link), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=("symlink",), + ) + + self.assertEqual(real_target.read_bytes(), b"UNTOUCHED") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["dangling_link.spv", "live_link.spv", "real.spv"], + ) + + def test_empty_and_whitespace_assembler_and_validator_rejected(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + absent_out = work / "absent_dir" / "window.spv" + + with mock.patch.object( + saw.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for empty tool flag"), + ): + for label, flag, val in ( + ("empty_assembler", "--assembler", ""), + ("blank_assembler", "--assembler", " \t "), + ("empty_validator", "--validator", ""), + ("blank_validator", "--validator", " \n "), + ): + with self.subTest(case=label): + self._assert_clean_failure( + [str(src), str(absent_out), flag, val], + expected_code=1, + fragments=(flag, "non-empty"), + ) + self.assertFalse(absent_out.parent.exists()) + + def test_subprocess_and_replace_failures_clean_up_temp_dirs_and_preserve_output(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + target_dir = work / "target_dir" + target_dir.mkdir() + protected = target_dir / "kept.spv" + sentinel = b"SENTINEL_KEEP_BYTES" + protected.write_bytes(sentinel) + + created_tempdirs: list[Path] = [] + real_tempdir = tempfile.TemporaryDirectory + calls: list[list[str]] = [] + fail_on_call: dict[int, BaseException] = {} + + class TrackingTempDir(real_tempdir): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + created_tempdirs.append(Path(self.name)) + + def fake_run(cmd, check=False, **_kwargs): + calls.append([str(part) for part in cmd]) + idx = len(calls) + if idx in fail_on_call: + raise fail_on_call[idx] + if cmd[0] == "mock-as": + out_idx = cmd.index("-o") + 1 + Path(cmd[out_idx]).write_bytes(b"MOCK_SPV") + return subprocess.CompletedProcess(cmd, 0) + + with ( + mock.patch.object(saw.subprocess, "run", side_effect=fake_run), + mock.patch.object(saw.tempfile, "TemporaryDirectory", TrackingTempDir), + ): + failure_cases = ( + ("orig_as_called_process_error", 1, subprocess.CalledProcessError(1, ["mock-as"]), ("returned non-zero",)), + ("orig_val_called_process_error", 2, subprocess.CalledProcessError(1, ["mock-val"]), ("returned non-zero",)), + ("lower_as_called_process_error", 3, subprocess.CalledProcessError(1, ["mock-as"]), ("returned non-zero",)), + ("lower_val_called_process_error", 4, subprocess.CalledProcessError(1, ["mock-val"]), ("returned non-zero",)), + ("missing_tool_file_not_found", 1, FileNotFoundError("no mock-as binary"), ("no mock-as binary",)), + ("validator_timeout", 2, subprocess.TimeoutExpired(["mock-val"], 5), ("timed out",)), + ) + for label, call_idx, exc, frags in failure_cases: + with self.subTest(case=label): + calls.clear() + fail_on_call.clear() + fail_on_call[call_idx] = exc + self._assert_clean_failure( + [str(src), str(protected), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=frags, + check_subprocess=False, + ) + self.assertEqual(protected.read_bytes(), sentinel) + self.assertEqual([p.name for p in target_dir.iterdir()], ["kept.spv"]) + self.assertFalse(created_tempdirs[-1].exists()) + + fail_on_call.clear() + with mock.patch.object(Path, "replace", side_effect=OSError("simulated replace failure")): + self._assert_clean_failure( + [str(src), str(protected), "--assembler", "mock-as", "--validator", "mock-val"], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + ) + self.assertEqual(protected.read_bytes(), sentinel) + self.assertEqual([p.name for p in target_dir.iterdir()], ["kept.spv"]) + self.assertFalse(created_tempdirs[-1].exists()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + src = work / "subtract.spvasm" + src.write_text(SUBTRACT_ASM, encoding="utf-8") + out = work / "out.spv" + + for argv, frags in ( + ([], ("required",)), + ([str(src)], ("required",)), + ([str(src), str(out), "--assembler"], ("expected one argument",)), + ([str(src), str(out), "--validator"], ("expected one argument",)), + ([str(src), str(out), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/spirv_ballot_extract_check.py b/tests/spirv_ballot_extract_check.py new file mode 100644 index 0000000000..6ef84046ae --- /dev/null +++ b/tests/spirv_ballot_extract_check.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Pure-Python unit and mutation suite for tools/spirv_ballot_extract.py.""" + +import importlib.util +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +import unittest + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / "tools" / "spirv_ballot_extract.py" +BALLOT_SPVASM = ROOT / "tests" / "spirv_window" / "ballot.spvasm" +sys.path.insert(0, str(ROOT / "tools")) +import spirv_ballot_extract as sbe # noqa: E402 + + +EXTRACT_MODULE = BALLOT_SPVASM.read_text(encoding="utf-8") + +FIND_MODULE = """OpCapability Shader +OpCapability GroupNonUniformBallot +OpMemoryModel Logical GLSL450 +%uint = OpTypeInt 32 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%scope = OpConstant %uint 0x3 +%workgroup = OpConstant %uint 2 +%main = OpFunction %void None %fn +%entry = OpLabel +%lsb = OpGroupNonUniformBallotFindLSB %uint %scope %mask +OpReturn +OpFunctionEnd +""" + +COMBINED_MODULE = """OpCapability Shader +OpCapability GroupNonUniformBallot +OpMemoryModel Logical GLSL450 +%uint = OpTypeInt 32 0 +%bool = OpTypeBool +%void = OpTypeVoid +%fn = OpTypeFunction %void +%scope = OpConstant %uint 3 +%main = OpFunction %void None %fn +%entry = OpLabel +%bit = OpGroupNonUniformBallotBitExtract %bool %scope %mask %lane ; trailing comment +%lsb = OpGroupNonUniformBallotFindLSB %uint %scope %mask +OpReturn +OpFunctionEnd +""" + + +def _load_module(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class SpirvBallotExtractTest(unittest.TestCase): + def test_passthrough_preserves_input_verbatim(self) -> None: + plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n%main = OpFunction %void None %fn\n" + for sample in ("", plain, "%x2w_ballot_unused = OpConstant %uint 0\n"): + self.assertEqual(sbe.lower_ballot_extract(sample), sample) + + # Unmatched FindLSB signatures (e.g. wrong result type) pass through untouched. + wrong_find = FIND_MODULE.replace( + "%lsb = OpGroupNonUniformBallotFindLSB %uint %scope %mask", + "%lsb = OpGroupNonUniformBallotFindLSB %bool %scope %mask", + ) + self.assertEqual(sbe.lower_ballot_extract(wrong_find), wrong_find) + + def test_ballot_bit_extract_lowering(self) -> None: + lowered = sbe.lower_ballot_extract(EXTRACT_MODULE) + lines = lowered.splitlines() + self.assertNotIn("OpGroupNonUniformBallotBitExtract", lowered) + self.assertNotIn("OpExtInstImport", lowered) + for c in (0, 1, 5, 31): + self.assertIn(f"%x2w_ballot_c{c} = OpConstant %uint {c}", lines) + for c in (32, 64, 96): + self.assertNotIn(f"%x2w_ballot_c{c}", lowered) + fn_idx = lines.index("%main = OpFunction %void None %fn") + self.assertEqual( + lines[fn_idx - 4:fn_idx], + [f"%x2w_ballot_c{c} = OpConstant %uint {c}" for c in (0, 1, 5, 31)], + ) + self.assertIn("%x2w_ballot_bit_word_index = OpShiftRightLogical %uint %i %x2w_ballot_c5", lines) + self.assertIn("%x2w_ballot_bit_word = OpVectorExtractDynamic %uint %mask %x2w_ballot_bit_word_index", lines) + self.assertIn("%x2w_ballot_bit_bit = OpBitwiseAnd %uint %i %x2w_ballot_c31", lines) + self.assertIn("%x2w_ballot_bit_shifted = OpShiftRightLogical %uint %x2w_ballot_bit_word %x2w_ballot_bit_bit", lines) + self.assertIn("%x2w_ballot_bit_low = OpBitwiseAnd %uint %x2w_ballot_bit_shifted %x2w_ballot_c1", lines) + self.assertIn("%bit = OpINotEqual %bool %x2w_ballot_bit_low %x2w_ballot_c0", lines) + + def test_ballot_find_lsb_injects_glsl_import(self) -> None: + lowered = sbe.lower_ballot_extract(FIND_MODULE) + lines = lowered.splitlines() + self.assertNotIn("OpGroupNonUniformBallotFindLSB", lowered) + self.assertEqual(lines.count('%x2w_ballot_glsl = OpExtInstImport "GLSL.std.450"'), 1) + mm_idx = lines.index("OpMemoryModel Logical GLSL450") + self.assertEqual(lines[mm_idx - 1], '%x2w_ballot_glsl = OpExtInstImport "GLSL.std.450"') + for c in (31, 32, 64, 96): + self.assertIn(f"%x2w_ballot_c{c} = OpConstant %uint {c}", lines) + for c in (0, 1, 5): + self.assertNotIn(f"%x2w_ballot_c{c} = OpConstant", lowered) + self.assertIn("%x2w_ballot_lsb_w0 = OpCompositeExtract %uint %mask 0", lines) + self.assertIn("%x2w_ballot_lsb_c0 = OpExtInst %uint %x2w_ballot_glsl FindILsb %x2w_ballot_lsb_w0", lines) + self.assertIn("%x2w_ballot_lsb_m3 = OpShiftRightArithmetic %uint %x2w_ballot_lsb_l3 %x2w_ballot_c31", lines) + self.assertIn("%x2w_ballot_lsb_a3 = OpIAdd %uint %x2w_ballot_lsb_l3 %x2w_ballot_c96", lines) + self.assertIn("%lsb = OpExtInst %uint %x2w_ballot_glsl UMin %x2w_ballot_lsb_c0 %x2w_ballot_lsb_u1", lines) + + def test_ballot_find_lsb_reuses_existing_glsl_import(self) -> None: + with_import = FIND_MODULE.replace( + "OpMemoryModel Logical GLSL450\n", + '%existing_glsl = OpExtInstImport "GLSL.std.450"\n', + ) + lowered = sbe.lower_ballot_extract(with_import) + lines = lowered.splitlines() + self.assertEqual(lowered.count("OpExtInstImport"), 1) + self.assertNotIn("%x2w_ballot_glsl", lowered) + self.assertIn("%x2w_ballot_lsb_c0 = OpExtInst %uint %existing_glsl FindILsb %x2w_ballot_lsb_w0", lines) + self.assertIn("%lsb = OpExtInst %uint %existing_glsl UMin %x2w_ballot_lsb_c0 %x2w_ballot_lsb_u1", lines) + + def test_combined_extract_and_find_lsb(self) -> None: + lowered = sbe.lower_ballot_extract(COMBINED_MODULE) + lines = lowered.splitlines() + self.assertNotIn("OpGroupNonUniformBallotBitExtract", lowered) + self.assertNotIn("OpGroupNonUniformBallotFindLSB", lowered) + fn_idx = lines.index("%main = OpFunction %void None %fn") + self.assertEqual( + lines[fn_idx - 7:fn_idx], + [f"%x2w_ballot_c{c} = OpConstant %uint {c}" for c in (0, 1, 5, 31, 32, 64, 96)], + ) + self.assertIn("%bit = OpINotEqual %bool %x2w_ballot_bit_low %x2w_ballot_c0", lines) + self.assertIn("%lsb = OpExtInst %uint %x2w_ballot_glsl UMin %x2w_ballot_lsb_c0 %x2w_ballot_lsb_u1", lines) + + def test_negative_controls(self) -> None: + for bad in (None, b"OpCapability Shader", 42, ["OpMemoryModel Logical GLSL450"]): + with self.subTest(bad=bad): + with self.assertRaisesRegex(TypeError, "assembly must be a str"): + sbe.lower_ballot_extract(bad) + + reserved = EXTRACT_MODULE.replace("%one", "%x2w_ballot_taken") + with self.assertRaisesRegex(ValueError, "Reserved ballot lowering ID already in use"): + sbe.lower_ballot_extract(reserved) + + for bad_scope in ("%workgroup", "%missing", "%main"): + with self.subTest(bad_scope=bad_scope): + probe = FIND_MODULE.replace("%scope %mask", f"{bad_scope} %mask") + with self.assertRaisesRegex(ValueError, "Subgroup scope constant"): + sbe.lower_ballot_extract(probe) + + no_fn_extract = EXTRACT_MODULE.replace("%main = OpFunction %void None %fn", "%main_alt = OpLabel") + with self.assertRaisesRegex(ValueError, "OpFunction"): + sbe.lower_ballot_extract(no_fn_extract) + + no_fn_find = FIND_MODULE.replace("%main = OpFunction %void None %fn", "%main_alt = OpLabel") + with self.assertRaisesRegex(ValueError, "OpFunction"): + sbe.lower_ballot_extract(no_fn_find) + + no_mm_find = FIND_MODULE.replace("OpMemoryModel Logical GLSL450\n", "") + with self.assertRaisesRegex(ValueError, "OpMemoryModel"): + sbe.lower_ballot_extract(no_mm_find) + + def test_fast_temp_mutations_killed(self) -> None: + original_src = TOOL.read_text(encoding="utf-8") + mutations = ( + ( + "drop_str_check", + " if not isinstance(assembly, str):", + " if False:", + lambda mod: mod.lower_ballot_extract(["OpCapability Shader"]), + TypeError, + "assembly must be a str", + ), + ( + "drop_reserved_id_check", + ' if "%x2w_ballot_" in assembly:', + " if False:", + lambda mod: mod.lower_ballot_extract(EXTRACT_MODULE.replace("%one", "%x2w_ballot_taken")), + ValueError, + "Reserved ballot lowering ID already in use", + ), + ( + "wrong_subgroup_scope", + "SUBGROUP_SCOPE = 3", + "SUBGROUP_SCOPE = 2", + lambda mod: mod.lower_ballot_extract(FIND_MODULE.replace("%scope %mask", "%workgroup %mask")), + ValueError, + "Subgroup scope constant", + ), + ( + "drop_opfunction_check", + " if not declared:", + " if False:", + lambda mod: mod.lower_ballot_extract( + EXTRACT_MODULE.replace("%main = OpFunction %void None %fn", "%main_alt = OpLabel") + ), + ValueError, + "OpFunction", + ), + ( + "drop_opmemorymodel_check", + " if import_needed and not imported:", + " if False:", + lambda mod: mod.lower_ballot_extract(FIND_MODULE.replace("OpMemoryModel Logical GLSL450\n", "")), + ValueError, + "OpMemoryModel", + ), + ) + with TemporaryDirectory() as folder: + root = Path(folder) + for label, old, new, trigger, expected_exc, expected_msg in mutations: + mutated_src = original_src.replace(old, new, 1) + self.assertNotEqual(mutated_src, original_src, label) + mut_path = root / f"mut_{label}.py" + mut_path.write_text(mutated_src, encoding="utf-8") + mod = _load_module(mut_path, f"mut_{label}") + try: + trigger(mod) + except expected_exc as exc: + if expected_msg in str(exc): + raise AssertionError(f"mutation {label} was not killed: {exc}") + except Exception: + pass + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/spirv_window/minlod.py b/tests/spirv_window/minlod.py index 49119430c3..50a2c4c012 100644 --- a/tests/spirv_window/minlod.py +++ b/tests/spirv_window/minlod.py @@ -9,6 +9,8 @@ ("implicit", "OpImageSampleImplicitLod %v4 %sampled %uv MinLod %one"), ("bias", "OpImageSampleImplicitLod %v4 %sampled %uv Bias|ConstOffset|MinLod %bias %offset %one"), ("grad", "OpImageSampleExplicitLod %v4 %sampled %uv Grad|MinLod %dx %dy %one"), + # On the 8x8 texture these gradients cover two texels, so they select mip 1 with a floor of 0. + ("grad-above-clamp", "OpImageSampleExplicitLod %v4 %sampled %uv Grad|MinLod %twoTexelsDx %twoTexelsDy %zero"), ("no-clamp", "OpImageSampleImplicitLod %v4 %sampled %uv"), ) diff --git a/tests/spirv_window/minlod.spvasm b/tests/spirv_window/minlod.spvasm index fd2782d604..08ee595e37 100644 --- a/tests/spirv_window/minlod.spvasm +++ b/tests/spirv_window/minlod.spvasm @@ -32,6 +32,8 @@ OpDecorate %color Location 0 %uv = OpConstantComposite %v2 %quarter %quarter %dx = OpConstantComposite %v2 %step %zero %dy = OpConstantComposite %v2 %zero %step +%twoTexelsDx = OpConstantComposite %v2 %quarter %zero +%twoTexelsDy = OpConstantComposite %v2 %zero %quarter %ix = OpConstant %int 1 %iy = OpConstant %int 0 %offset = OpConstantComposite %iv2 %ix %iy diff --git a/tests/startup_acphal_apu_free.cpp b/tests/startup_acphal_apu_free.cpp index 960ff5fbe0..a17ea821d9 100644 --- a/tests/startup_acphal_apu_free.cpp +++ b/tests/startup_acphal_apu_free.cpp @@ -1,5 +1,6 @@ -// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuFree returns blocks, -// neighbours coalesce, bad requests leave the heap alone and concurrent callers never get overlapping blocks. +// Source-built check of the AcpHal stand-in APU heap (src/startup_stubs/acphal.cpp): ApuCreateHeap reserves, +// ApuAlloc commits on demand, ApuFree returns blocks, coalesces neighbours and decommits interior pages without +// disturbing shared boundary pages, bad requests leave the heap alone and concurrent callers never overlap. // Usage: startup_acphal_apu_free <AcpHal.dll> #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN @@ -8,6 +9,7 @@ #define NOMINMAX #endif #include <windows.h> +#include <psapi.h> #include <atomic> #include <cstddef> @@ -161,6 +163,23 @@ void bad_requests() std::uint32_t apu = 0xDEADBEEF; check(free_fn(nullptr) == ok, "free(null) is a no-op"); check(take(nullptr, 64) == no_pointer, "null output"); + if (void* ro = VirtualAlloc(nullptr, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY)) { + auto* ro_ptr = static_cast<void**>(ro); + auto* ro_apu = static_cast<std::uint32_t*>(ro); + check(take(ro_ptr, 64, 16, &apu) == no_pointer && apu == 0xDEADBEEF, + "read-only virtual_address returns E_POINTER and leaves apu unchanged"); + out = const_cast<void*>(sentinel); + check(take(&out, 64, 16, ro_apu) == no_pointer && !out, + "read-only apu_address returns E_POINTER and zeroes virtual_address"); + out = const_cast<void*>(sentinel); + check(take(&out, 0, 16, ro_apu) == no_pointer && !out, + "read-only apu_address with size 0 returns E_POINTER"); + VirtualFree(ro, 0, MEM_RELEASE); + } else { + check(false, "VirtualAlloc PAGE_READONLY for ApuAlloc negative control"); + } + check_empty("unwritable ApuAlloc outputs"); + out = const_cast<void*>(sentinel); check(take(&out, usable + 16, 16, &apu) == no_memory && !out && apu == 0xDEADBEEF, "larger than the heap"); out = const_cast<void*>(sentinel); check(take(&out, 0xFFFFFFFFull, 16, &apu) == no_memory && !out, "size near 2^32"); @@ -283,6 +302,12 @@ void concurrent() // block that overlaps a live one, or leave a live block unfreeable. void first_creation(CreateFn create) { + // A heap that would cross 4 GiB by one byte (rounded up to 64 KiB) is refused before any memory is + // committed and leaves no heap behind; the creations below still succeed. + check(create(0xFFFFFFFFull, 2) == invalid, "heap crossing 4 GiB by one byte is refused"); + check(create(0xFFFFFFFFull, 0xFFFFFFFFull) == invalid, "two maximal 32-bit sizes are refused"); + void* refused = nullptr; + check(take(&refused, 64) == no_memory && !refused, "refused ApuCreateHeap leaves no heap"); constexpr unsigned callers = 4; std::atomic<bool> go{false}; std::atomic<int> bad{0}; @@ -376,6 +401,23 @@ void hal_and_address_mapping() } void* hal = nullptr; check(hal_create_fn(&hal) == ok && hal != nullptr, "AcpHalCreate returns stand-in object"); + { + constexpr unsigned callers = 4; + std::atomic<bool> go{false}; + std::atomic<int> bad{0}; + void* objects[callers] = {}; + std::vector<std::thread> threads; + for (unsigned id = 0; id < callers; ++id) + threads.emplace_back([&, id] { + while (!go.load()) std::this_thread::yield(); + if (hal_create_fn(&objects[id]) != ok || !objects[id]) ++bad; + }); + go = true; + for (auto& t : threads) t.join(); + check(bad.load() == 0, "concurrent AcpHalCreate calls succeed"); + for (unsigned i = 0; i < callers; ++i) + check(objects[i] == hal, "concurrent AcpHalCreate returns the same stand-in object"); + } if (hal) { auto* const* vtable = *reinterpret_cast<void* const* const*>(hal); auto connect = reinterpret_cast<HalConnectFn>(vtable[0]); @@ -401,12 +443,27 @@ void hal_and_address_mapping() check(valid_fn(nullptr) == 0, "ApuIsVirtualAddressValid(null) is 0"); check(valid_fn(&failures) == 0, "ApuIsVirtualAddressValid(foreign) is 0"); check(valid_fn(heap_base - 1) == 0, "ApuIsVirtualAddressValid(before heap) is 0"); + check(valid_fn(heap_base) == 0, "ApuIsVirtualAddressValid(reserved offset 0) is 0"); + check(valid_fn(heap_base + 0x100) == 0, "ApuIsVirtualAddressValid(inside reserved guard) is 0"); + check(valid_fn(heap_base + first_offset - 1) == 0, "ApuIsVirtualAddressValid(last reserved byte) is 0"); + check(valid_fn(heap_base + first_offset) != 0, "ApuIsVirtualAddressValid(first allocatable byte) is 1"); + check(valid_fn(heap_base + heap_size - 1) != 0, "ApuIsVirtualAddressValid(last heap byte) is 1"); check(valid_fn(heap_base + heap_size) == 0, "ApuIsVirtualAddressValid(at heap end) is 0"); check(map_fn(nullptr) == 0, "ApuMapVirtualAddress(null) is 0"); check(map_fn(&failures) == 0, "ApuMapVirtualAddress(foreign) is 0"); check(map_fn(heap_base - 1) == 0, "ApuMapVirtualAddress(before heap) is 0"); + check(map_fn(heap_base) == 0, "ApuMapVirtualAddress(reserved offset 0) is 0"); + check(map_fn(heap_base + 0x100) == 0, "ApuMapVirtualAddress(inside reserved guard) is 0"); + check(map_fn(heap_base + first_offset - 1) == 0, "ApuMapVirtualAddress(last reserved byte) is 0"); + check(map_fn(heap_base + first_offset) == first_offset, "ApuMapVirtualAddress(first allocatable byte)"); + check(map_fn(heap_base + heap_size - 1) == heap_size - 1, "ApuMapVirtualAddress(last heap byte)"); check(map_fn(heap_base + heap_size) == 0, "ApuMapVirtualAddress(at heap end) is 0"); check(map_apu_fn(0) == nullptr, "ApuMapApuAddress(0) is null"); + check(map_apu_fn(1) == nullptr, "ApuMapApuAddress(1 in reserved guard) is null"); + check(map_apu_fn(0x100) == nullptr, "ApuMapApuAddress(0x100 in reserved guard) is null"); + check(map_apu_fn(first_offset - 1) == nullptr, "ApuMapApuAddress(last reserved byte) is null"); + check(map_apu_fn(first_offset) == heap_base + first_offset, "ApuMapApuAddress(first allocatable byte)"); + check(map_apu_fn(heap_size - 1) == heap_base + heap_size - 1, "ApuMapApuAddress(last heap byte)"); check(map_apu_fn(heap_size) == nullptr, "ApuMapApuAddress(heap_size) is null"); check(map_apu_fn(heap_size + 0x1000) == nullptr, "ApuMapApuAddress(past end) is null"); @@ -475,11 +532,182 @@ void check_non_permissive_traps(const char* self_exe, const char* dll_path) check_trap_case(self_exe, dll_path, "ApuMapVirtualAddress", 0xE2570108u); check_trap_case(self_exe, dll_path, "AcpHalReleaseShapeContexts", 0xE2570102u); } + +SIZE_T pagefile_usage(SIZE_T* peak_out = nullptr) +{ + PROCESS_MEMORY_COUNTERS pmc{}; + pmc.cb = sizeof(pmc); + if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) { + check(false, "GetProcessMemoryInfo succeeds"); + if (peak_out) *peak_out = 0; + return 0; + } + if (peak_out) *peak_out = pmc.PeakPagefileUsage; + return pmc.PagefileUsage; +} + +bool query_mem(const void* address, MEMORY_BASIC_INFORMATION& mbi) +{ + if (VirtualQuery(address, &mbi, sizeof(mbi)) == sizeof(mbi)) return true; + check(false, "VirtualQuery succeeds"); + return false; +} + +int run_commit_check(const char* dll_path) +{ + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + HMODULE module = LoadLibraryA(dll_path); + if (!module) return std::printf("FAIL: cannot load %s\n", dll_path), 2; + alloc_fn = reinterpret_cast<AllocFn>(GetProcAddress(module, "ApuAlloc")); + free_fn = reinterpret_cast<FreeFn>(GetProcAddress(module, "ApuFree")); + map_apu_fn = reinterpret_cast<MapApuFn>(GetProcAddress(module, "ApuMapApuAddress")); + auto create = reinterpret_cast<CreateFn>(GetProcAddress(module, "ApuCreateHeap")); + if (!alloc_fn || !free_fn || !map_apu_fn || !create) return std::printf("FAIL: missing export\n"), 2; + + // Warm up GetProcessMemoryInfo before measuring baseline commit. + (void)pagefile_usage(); + const SIZE_T base_commit = pagefile_usage(); + + constexpr u64 large_heap = 64ull * 1024 * 1024; + constexpr u64 page_size = 0x1000; + constexpr SIZE_T slack = 256 * 1024; + check(create(large_heap, 0) == ok, "64 MiB ApuCreateHeap succeeds"); + const SIZE_T after_create_commit = pagefile_usage(); + check(after_create_commit <= base_commit + slack, + "PagefileUsage stays near 0 growth after 64 MiB ApuCreateHeap"); + + auto* first_addr = static_cast<unsigned char*>(map_apu_fn(first_offset)); + check(first_addr != nullptr, "ApuMapApuAddress(first_offset) returns non-null after 64 MiB ApuCreateHeap"); + if (!first_addr) return 1; + unsigned char* const base = first_addr - first_offset; + + MEMORY_BASIC_INFORMATION mbi{}; + if (query_mem(base, mbi)) { + check(mbi.State == MEM_RESERVE && mbi.RegionSize == large_heap, + "entire 64 MiB heap starts in MEM_RESERVE state"); + } + if (query_mem(first_addr, mbi)) { + check(mbi.State == MEM_RESERVE && mbi.RegionSize == large_heap - first_offset, + "allocatable 64 MiB range starts in MEM_RESERVE state"); + } + + // Allocate A (4 MiB + 2 KiB -> 1025 pages) and adjacent B (1 MiB + 2 KiB -> shares boundary page). + constexpr u64 size_a = 0x400800; + constexpr u64 size_b = 0x100800; + void* a = take_ok(size_a, 16); + check(a == first_addr, "first sub-block starts at first_offset"); + const SIZE_T after_a_commit = pagefile_usage(); + check(after_a_commit >= after_create_commit + 0x400000 && after_a_commit <= after_create_commit + 0x401000 + slack, + "PagefileUsage grows only by first sub-block pages"); + if (query_mem(a, mbi)) { + check(mbi.State == MEM_COMMIT && mbi.RegionSize >= 0x401000, "first sub-block pages are MEM_COMMIT"); + } + if (query_mem(first_addr + 0x401000, mbi)) { + check(mbi.State == MEM_RESERVE, "pages past first sub-block remain MEM_RESERVE"); + } + std::memset(a, 0xA5, size_a); + + void* b = take_ok(size_b, 16); + check(b == static_cast<unsigned char*>(a) + size_a, "second sub-block is adjacent on shared boundary page"); + const SIZE_T after_b_commit = pagefile_usage(); + check(after_b_commit <= after_a_commit + 0x100000 + slack, + "PagefileUsage grows only by second sub-block newly committed pages"); + bool a_intact = true; + for (u64 i = 0; i < size_a; ++i) a_intact = a_intact && static_cast<const unsigned char*>(a)[i] == 0xA5; + check(a_intact, "first sub-block bytes remain intact after committing adjacent block on shared page"); + std::memset(b, 0x5A, size_b); + + // Free A: interior pages [0x10000, 0x410000) must return to MEM_RESERVE while shared page [0x410000, 0x411000) stays MEM_COMMIT. + check(free_fn(a) == ok, "ApuFree first sub-block succeeds"); + if (query_mem(first_addr, mbi)) { + check(mbi.State == MEM_RESERVE && mbi.RegionSize == 0x400000, + "interior pages of freed first sub-block return to MEM_RESERVE"); + } + if (query_mem(first_addr + 0x400000, mbi)) { + check(mbi.State == MEM_COMMIT, + "shared boundary page stays MEM_COMMIT while adjacent second block is live"); + } + const SIZE_T after_free_a_commit = pagefile_usage(); + check(after_free_a_commit + 0x380000 <= after_b_commit, + "PagefileUsage drops after interior freed pages are decommitted"); + if (query_mem(b, mbi)) { + check(mbi.State == MEM_COMMIT && mbi.RegionSize >= size_b, + "adjacent live block stays MEM_COMMIT after freeing first block"); + if (mbi.State == MEM_COMMIT) { + bool b_intact = true; + for (u64 i = 0; i < size_b; ++i) b_intact = b_intact && static_cast<const unsigned char*>(b)[i] == 0x5A; + check(b_intact, "adjacent live block bytes on shared boundary page remain intact and readable"); + } + } + + // Reallocate A while B is still live: re-commits interior pages and zeroes still-committed shared boundary page. + void* a2 = take_ok(size_a, 16); + check(a2 == a, "reallocated sub-block reuses freed span"); + bool a2_zero = true; + for (u64 i = 0; i < size_a; ++i) a2_zero = a2_zero && static_cast<const unsigned char*>(a2)[i] == 0; + check(a2_zero, "reallocated sub-block is zeroed including shared boundary page"); + bool b_still_intact = true; + for (u64 i = 0; i < size_b; ++i) b_still_intact = b_still_intact && static_cast<const unsigned char*>(b)[i] == 0x5A; + check(b_still_intact, "adjacent live block remains untouched when neighbor reallocates"); + + check(free_fn(a2) == ok, "ApuFree reallocated first sub-block"); + check(free_fn(b) == ok, "ApuFree second sub-block"); + if (query_mem(first_addr, mbi)) { + check(mbi.State == MEM_RESERVE && mbi.RegionSize == large_heap - first_offset, + "entire allocatable heap returns to MEM_RESERVE after freeing all blocks"); + } + const SIZE_T after_free_all_commit = pagefile_usage(); + check(after_free_all_commit <= after_create_commit + slack, + "PagefileUsage returns near baseline after freeing all blocks"); + + // Verify commit-failure rollback leaves the heap intact if a process commit limit can be applied. + SIZE_T peak_commit = 0; + (void)pagefile_usage(&peak_commit); + if (HANDLE job = CreateJobObjectW(nullptr, nullptr)) { + JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; + limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY; + limits.ProcessMemoryLimit = peak_commit + 2 * 1024 * 1024; + if (SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof limits) && + AssignProcessToJobObject(job, GetCurrentProcess())) { + void* oom = reinterpret_cast<void*>(0x1234); + std::uint32_t apu = 0xDEADBEEF; + check(take(&oom, 16ull * 1024 * 1024, 16, &apu) == no_memory && !oom && apu == 0xDEADBEEF, + "commit failure in VirtualAlloc(MEM_COMMIT) returns E_OUTOFMEMORY cleanly"); + void* small_ok = nullptr; + std::uint32_t small_apu = 0; + check(take(&small_ok, page_size, 16, &small_apu) == ok && small_ok == first_addr && small_apu == first_offset, + "heap free list remains uncorrupted after commit failure"); + if (small_ok) check(free_fn(small_ok) == ok, "free small block after commit-failure rollback check"); + } + CloseHandle(job); + } + + return failures ? 1 : 0; +} + +void check_on_demand_commit(const char* self_exe, const char* dll_path) +{ + std::string cmd = std::string("\"") + self_exe + "\" --commit-check \"" + dll_path + "\""; + STARTUPINFOA si{}; + si.cb = sizeof(si); + PROCESS_INFORMATION pi{}; + if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) { + check(false, "CreateProcessA for on-demand commit check"); + return; + } + const DWORD wait_rc = WaitForSingleObject(pi.hProcess, 15000); + DWORD exit_code = 1; + const BOOL got_code = GetExitCodeProcess(pi.hProcess, &exit_code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + check(wait_rc == WAIT_OBJECT_0 && got_code && exit_code == 0, "on-demand commit child check passes"); +} } // namespace int main(int argc, char** argv) { if (argc == 4 && std::strcmp(argv[1], "--trap-control") == 0) return run_trap_control(argv[2], argv[3]); + if (argc == 3 && std::strcmp(argv[1], "--commit-check") == 0) return run_commit_check(argv[2]); if (argc != 2) return std::printf("usage: startup_acphal_apu_free <AcpHal.dll>\n"), 2; SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); HMODULE module = LoadLibraryA(argv[1]); @@ -510,6 +738,7 @@ int main(int argc, char** argv) table_full(); concurrent(); check_non_permissive_traps(argv[0], argv[1]); + check_on_demand_commit(argv[0], argv[1]); std::printf(failures ? "startup_acphal_apu_free: %d failure(s)\n" : "startup_acphal_apu_free: ok\n", failures); return failures ? 1 : 0; } diff --git a/tests/startup_acphal_xma_activity.cpp b/tests/startup_acphal_xma_activity.cpp new file mode 100644 index 0000000000..08c9ae7c72 --- /dev/null +++ b/tests/startup_acphal_xma_activity.cpp @@ -0,0 +1,548 @@ +// Source-built check of the activity counter in the AcpHal and XApu stand-ins (src/startup_stubs/acphal.cpp and +// xapu.cpp, X2W_AUDIO_ACTIVITY=1, docs/startup-runtime.md). One caller script fills, changes and clears XMA contexts, +// submits HAL commands and enqueues XApu commands. Each case runs in a child process of its own: +// on counter on: the exports and the logged lines report exactly what the script did, and a freed and +// reused context array is no longer counted +// none counter on, but the caller writes only next to the contexts and sends nothing: every count is 0 and no +// activity line is logged +// off counter unset, same script as on: the exports report nothing and no line is logged +// unload counter on: AcpHalAllocateShapeContexts runs again without an ApuFree (the old array's last changes count, +// later ones do not, the new array is counted), then the caller unloads both DLLs and stays alive for 1.5 s; +// it must exit 0, so nothing of either DLL may run after FreeLibrary +// The stand-ins log a due activity line only inside a call into them, so the cases call the exports before they read +// the log. +// Every call's result, output and last error, and the final context bytes, must be the same with the counter on and +// off. The 64-byte context stride and the command class (first UINT32) are stand-in conventions, not a console layout. +// Usage: startup_acphal_xma_activity <AcpHal.dll> <xapu.dll> +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <initializer_list> +#include <iterator> +#include <map> +#include <string> +#include <utility> +#include <vector> + +namespace { +using u64 = std::uint64_t; +using CreateHeapFn = long(__cdecl*)(u64, u64); +using AllocFn = long(__cdecl*)(void**, std::uint32_t*, u64, u64, u64); +using FreeFn = long(__cdecl*)(void*); +using HalCreateFn = long(__cdecl*)(void**); +using ShapeAllocFn = long(__cdecl*)(void*); +using HalConnectFn = long(__stdcall*)(void*, unsigned, unsigned); +using HalSubmitFn = long(__stdcall*)(void*, unsigned, u64, unsigned, const unsigned*, u64); +using ConnectFn = long(__cdecl*)(const void*, void*, u64*); +using EnqueueFn = long(__cdecl*)(u64, const void*, u64, u64); +using CountFn = std::uint32_t(__cdecl*)(u64, u64); +using DequeueFn = long(__cdecl*)(u64, void*); +using DisconnectFn = long(__cdecl*)(u64); +using ActivityFn = BOOL(WINAPI*)(ULONGLONG*); + +constexpr std::uint32_t contexts = 350; +constexpr int acphal_fields = 15, xapu_fields = 19; +// x2w_acphal_xma_activity: watched, live, filled, changed, cleared, HAL submits, submits of type 0..7, other types. +enum { watched = 0, live = 1, filled = 2, changed = 3, cleared = 4, submits = 5, submit_type0 = 6, submit_other = 14 }; +// x2w_xapu_command_counts: classes 0..15, larger classes, unreadable commands, unknown handles. +enum { class_other = 16, unreadable = 17, rejected = 18 }; + +struct ShapeContexts { + std::uint32_t counts[6]{}; + unsigned char* arrays[6]{}; + std::uint32_t apu[6]{}; +}; +static_assert(sizeof(ShapeContexts) == 0x60, "ShapeContexts layout"); + +struct Api { + CreateHeapFn create_heap; + AllocFn alloc; + FreeFn free; + HalCreateFn hal_create; + ShapeAllocFn shape_alloc; + ConnectFn connect; + EnqueueFn enqueue; + CountFn result_count; + DequeueFn dequeue; + DisconnectFn disconnect; + ActivityFn acphal_activity; + ActivityFn xapu_counts; +}; + +int failures; +std::string transcript; // every result, output and last error, compared between the on and off runs + +void check(bool condition, const char* what) +{ + if (condition) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +// Calls are made with a sentinel last error, so a stand-in that changes the caller's last error shows up. +void note(const char* what, long hr, unsigned long long value = 0) +{ + char line[160]; + std::snprintf(line, sizeof(line), "%s hr=0x%08lx value=0x%llx last_error=%lu\n", what, static_cast<unsigned long>(hr), value, + GetLastError()); + transcript += line; +} +void sentinel() { SetLastError(0x5A5A); } + +// XApuConnect refuses a shared buffer size of 0 (the u32 at input +0x0C) with E_INVALIDARG; 4 KiB is enough here. +void set_buffer_size(unsigned char* connect_input) +{ + const std::uint32_t bytes = 0x1000; + std::memcpy(connect_input + 0x0C, &bytes, sizeof(bytes)); +} + +// One aligned 8-byte store, so the sampler sees the context before or after it, never half written. +void store(unsigned char* base, std::uint32_t context, unsigned word, u64 value) +{ + InterlockedExchange64(reinterpret_cast<volatile LONG64*>(base + context * 64u + word * 8u), static_cast<LONG64>(value)); +} + +struct Snapshot { + BOOL on = FALSE; + ULONGLONG v[xapu_fields > acphal_fields ? xapu_fields : acphal_fields]; +}; + +Snapshot take(ActivityFn fn) +{ + Snapshot s; + for (auto& x : s.v) x = 0xA5A5A5A5A5A5A5A5ull; // the export must overwrite every field, on or off + s.on = fn(s.v); + return s; +} + +using Fields = std::initializer_list<std::pair<int, u64>>; // (field, value) pairs + +// Every field is zero except the listed ones. +void expect(const char* label, const Snapshot& s, BOOL on, int fields, Fields nonzero) +{ + bool good = s.on == on; + for (int i = 0; i < fields; ++i) { + u64 want = 0; + for (const auto& f : nonzero) + if (f.first == i) want = f.second; + good = good && s.v[i] == want; + } + if (good) return; + std::printf("FAIL: %s: returned %d, fields", label, s.on); + for (int i = 0; i < fields; ++i) std::printf(" %llu", s.v[i]); + std::printf("\n"); + ++failures; +} + +// The fields expected with the counter on; with it off the export returns FALSE and every field must be zero. +void expect_on(const char* label, const Snapshot& s, bool on, int fields, Fields when_on) +{ + expect(label, s, on, fields, on ? when_on : Fields{}); +} + +std::string read_file(const char* path) +{ + std::string text; + HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char buffer[4096]; + DWORD got = 0; + while (ReadFile(file, buffer, sizeof(buffer), &got, nullptr) && got) text.append(buffer, got); + CloseHandle(file); + return text; +} + +// Sums the name=value tokens of the activity lines in the log, keyed "xma.<name>" or "xapu.<name>"; zero sums are +// dropped. A bare number names a submit type (xma) or a command class (xapu). The live=n/m token is not a count. +std::map<std::string, u64> activity_sums(const std::string& log, int* lines) +{ + std::map<std::string, u64> sums; + *lines = 0; + std::size_t at = 0; + while (at < log.size()) { + std::size_t end = log.find('\n', at); + if (end == std::string::npos) end = log.size(); + const std::string line = log.substr(at, end - at); + at = end + 1; + const char* kind = line.find("x2w-audio xma-activity t=") != std::string::npos ? "xma." + : line.find("x2w-audio xapu-activity t=") != std::string::npos ? "xapu." + : nullptr; + if (!kind) continue; + ++*lines; + std::size_t pos = line.find(" s: "); + while (pos != std::string::npos && pos < line.size()) { + const std::size_t start = pos + 1; + pos = line.find(' ', start); + std::string token = line.substr(start, pos == std::string::npos ? std::string::npos : pos - start); + while (!token.empty() && (token.back() == ';' || token.back() == '\r')) token.pop_back(); + const std::size_t eq = token.find('='); + if (eq == std::string::npos || token.find('/') != std::string::npos) continue; + sums[kind + token.substr(0, eq)] += std::strtoull(token.c_str() + eq + 1, nullptr, 10); + } + } + for (auto it = sums.begin(); it != sums.end();) it = it->second ? std::next(it) : sums.erase(it); + return sums; +} + +std::string describe(const std::map<std::string, u64>& sums) +{ + std::string text; + for (const auto& s : sums) text += " " + s.first + "=" + std::to_string(s.second); + return text; +} + +int activity_lines(const char* log_path) +{ + int lines = 0; + activity_sums(read_file(log_path), &lines); + return lines; +} + +// The caller script of the on and off cases. Snapshots are taken between phases and no other counted call runs while +// the contexts are written, so each context moves once between two samples. +void script(const Api& api, bool on) +{ + sentinel(); + note("ApuCreateHeap", api.create_heap(0x200000, 0)); + void* hal = nullptr; + sentinel(); + note("AcpHalCreate", api.hal_create(&hal), hal != nullptr); + if (!hal) return check(false, "AcpHalCreate returns an object"); + auto* const* table = *reinterpret_cast<void* const* const*>(hal); + auto hal_connect = reinterpret_cast<HalConnectFn>(table[0]); + auto hal_submit = reinterpret_cast<HalSubmitFn>(table[2]); + sentinel(); + note("AcpHal connect", hal_connect(hal, 0x1000, 0x1000)); + ShapeContexts ctx{}; + ctx.counts[4] = contexts; + sentinel(); + note("AcpHalAllocateShapeContexts", api.shape_alloc(&ctx), ctx.apu[4]); + unsigned char* const base = ctx.arrays[4]; + if (!base) return check(false, "XMA contexts allocated"); + expect_on("before any write", take(api.acphal_activity), on, acphal_fields, {{watched, contexts}}); + + // Fill 5 contexts, one word each; context 349 uses its last word. + store(base, 0, 0, 0x1111); + store(base, 1, 3, 0x2222); + store(base, 2, 0, 0x3333); + store(base, 100, 5, 0x4444); + store(base, 349, 7, 0x5555); + expect_on("after 5 fills", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 5}, {filled, 5}}); + // Change 3 live contexts: the same word, the last word, another word. + store(base, 0, 0, 0x1112); + store(base, 1, 7, 0x2223); + store(base, 100, 2, 0x4445); + expect_on("after 3 changes", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 5}, {filled, 5}, {changed, 3}}); + // Clear 2 contexts. + store(base, 2, 0, 0); + store(base, 349, 7, 0); + expect_on("after 2 clears", take(api.acphal_activity), on, acphal_fields, + {{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}}); + + const unsigned input = 0x12345678u; + for (unsigned type : {1u, 1u, 3u, 12u}) { + sentinel(); + note("AcpHal submit", hal_submit(hal, type, 0x1234, 2, &input, 0), type); + } + const auto after_submits = take(api.acphal_activity); + expect_on("after 4 HAL submits", after_submits, on, acphal_fields, + {{watched, contexts}, {live, 3}, {filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, + {submit_type0 + 3, 1}, {submit_other, 1}}); + + unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + set_buffer_size(connect_input); + u64 handle = 0; + sentinel(); + note("XApuConnect", api.connect(connect_input, connect_output, &handle), handle); + unsigned char command[0x60]{}; + for (std::uint32_t command_class : {1u, 1u, 2u, 1u, 2u, 0x20u}) { + std::memcpy(command, &command_class, sizeof(command_class)); + sentinel(); + note("XApuEnqueueCommand", api.enqueue(handle, command, 0, 0), command_class); + } + sentinel(); + note("XApuEnqueueCommand null command", api.enqueue(handle, nullptr, 0, 0)); + std::uint32_t one = 1; + std::memcpy(command, &one, sizeof(one)); + sentinel(); + note("XApuEnqueueCommand unknown handle", api.enqueue(handle + 0x100, command, 0, 0)); + // A type 3 command whose 8-byte header ends where free address space begins (the rest of the page's allocation + // granule), sent with typed completions on. An X2W_WITH_OPUS build refuses it with E_POINTER before the queue, as + // too short to decode, and must still count it as class 3; without Opus it is queued like any other command. + // X2W_PROBE_PRECHECK=1 (every case) refuses the free tail without touching it, so no fault is taken. Typed + // completions are set for this call only. + SYSTEM_INFO system{}; + GetSystemInfo(&system); + auto* page = static_cast<unsigned char*>( + VirtualAlloc(nullptr, system.dwPageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + MEMORY_BASIC_INFORMATION after{}; + const bool free_after = + page && VirtualQuery(page + system.dwPageSize, &after, sizeof(after)) && after.State == MEM_FREE; + check(free_after, "free address space after the short command"); + if (free_after) { + unsigned char* short_command = page + system.dwPageSize - 8; + const std::uint32_t three = 3; + std::memcpy(short_command, &three, sizeof(three)); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", "1"); + sentinel(); + note("XApuEnqueueCommand short type 3 command", api.enqueue(handle, short_command, 0, 0)); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + } + if (page) VirtualFree(page, 0, MEM_RELEASE); + sentinel(); + const std::uint32_t pending = api.result_count(handle, 0); + note("XApuGetResultCount", 0, pending); + for (int i = 0; i < 8; ++i) { + unsigned char result[0x58]; + std::memset(result, 0xCC, sizeof(result)); + sentinel(); + const long hr = api.dequeue(handle, result); + unsigned sum = 0; + for (unsigned char b : result) sum += b; + note("XApuDequeueResult", hr, sum); + } + sentinel(); + note("XApuDisconnect", api.disconnect(handle)); + expect_on("XApu commands", take(api.xapu_counts), on, xapu_fields, + {{1, 3}, {2, 2}, {3, 1}, {class_other, 1}, {unreadable, 1}, {rejected, 1}}); + + unsigned hash = 2166136261u; // FNV-1a of the context bytes: the counter never writes caller memory + for (std::uint32_t i = 0; i < contexts * 64; ++i) hash = (hash ^ base[i]) * 16777619u; + sentinel(); + note("context bytes", 0, hash); + + // Freed contexts stop being watched; the block that comes back is not counted. + sentinel(); + note("ApuFree contexts", api.free(base)); + void* again = nullptr; + std::uint32_t again_apu = 0; + sentinel(); + note("ApuAlloc same size", api.alloc(&again, &again_apu, contexts * 64, 64, 0), again_apu); + sentinel(); + note("same block", 0, again == base); + check(again == base, "ApuAlloc of the same size returns the freed context block"); + if (again) { + auto* p = static_cast<unsigned char*>(again); + store(p, 0, 0, 0x6666); + store(p, 5, 1, 0x7777); + store(p, 300, 7, 0x8888); + Sleep(50); // several 10 ms sample periods + } + expect_on("after free and reuse", take(api.acphal_activity), on, acphal_fields, + {{filled, 5}, {changed, 3}, {cleared, 2}, {submits, 4}, {submit_type0 + 1, 2}, {submit_type0 + 3, 1}, + {submit_other, 1}}); +} + +// Zero-write control: the counter is on, the caller writes only to the block after the contexts and sends nothing. +void script_none(const Api& api) +{ + api.create_heap(0x200000, 0); + void* hal = nullptr; + check(api.hal_create(&hal) == 0 && hal, "AcpHalCreate"); + ShapeContexts ctx{}; + ctx.counts[4] = contexts; + check(api.shape_alloc(&ctx) == 0 && ctx.arrays[4], "AcpHalAllocateShapeContexts"); + void* next = nullptr; + std::uint32_t next_apu = 0; + check(api.alloc(&next, &next_apu, 0x1000, 64, 0) == 0 && next, "ApuAlloc after the contexts"); + // The control writes the 64 bytes right after the last context, so it is only meaningful if they are adjacent. + check(next_apu == ctx.apu[4] + contexts * 64, "the next block starts right after the last context"); + if (next) { + store(static_cast<unsigned char*>(next), 0, 0, 0x9999); + store(static_cast<unsigned char*>(next), 0, 7, 0x9999); + } + unsigned char connect_input[0x18]{}, connect_output[0x10]{}; + set_buffer_size(connect_input); + u64 handle = 0; + check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); + check(api.disconnect(handle) == 0, "XApuDisconnect"); + Sleep(50); + expect("zero-write control", take(api.acphal_activity), TRUE, acphal_fields, {{watched, contexts}}); + expect("zero-write control XApu", take(api.xapu_counts), TRUE, xapu_fields, {}); +} + +// The unload case. Nothing in it is compared with another run. +void script_unload(const Api& api, HMODULE acphal, HMODULE xapu) +{ + check(api.create_heap(0x200000, 0) == 0, "ApuCreateHeap"); + void* hal = nullptr; + check(api.hal_create(&hal) == 0 && hal, "AcpHalCreate"); + if (!hal) return; + auto hal_submit = reinterpret_cast<HalSubmitFn>((*reinterpret_cast<void* const* const*>(hal))[2]); + const unsigned input = 0; + check(hal_submit(hal, 1, 0x1234, 2, &input, 0) == 0, "AcpHal submit"); + ShapeContexts first{}, second{}; + first.counts[4] = contexts; + second.counts[4] = 4; + check(api.shape_alloc(&first) == 0 && first.arrays[4], "first AcpHalAllocateShapeContexts"); + if (!first.arrays[4]) return; + store(first.arrays[4], 0, 0, 0x1111); // not sampled yet: the re-run's last sample of this array counts it + check(api.shape_alloc(&second) == 0 && second.arrays[4] && second.arrays[4] != first.arrays[4], + "AcpHalAllocateShapeContexts again, without ApuFree, gives another array"); + if (!second.arrays[4]) return; + store(first.arrays[4], 1, 0, 0x2222); // the old array is no longer watched + store(second.arrays[4], 3, 7, 0x3333); // the new one is, up to its last word + expect("re-run without ApuFree", take(api.acphal_activity), TRUE, acphal_fields, + {{watched, 4}, {live, 1}, {filled, 2}, {submits, 1}, {submit_type0 + 1, 1}}); + unsigned char connect_input[0x18]{}, connect_output[0x10]{}, command[0x60]{}; + set_buffer_size(connect_input); + u64 handle = 0; + command[0] = 1; + check(api.connect(connect_input, connect_output, &handle) == 0, "XApuConnect"); + api.enqueue(handle, command, 0, 0); + expect("XApu command before unload", take(api.xapu_counts), TRUE, xapu_fields, {{1, 1}}); + // Unloading must really unmap both images, else the wait below proves nothing. + const void* const code[] = {reinterpret_cast<const void*>(api.create_heap), reinterpret_cast<const void*>(api.enqueue)}; + check(FreeLibrary(acphal) && FreeLibrary(xapu), "FreeLibrary of both stand-ins"); + for (const void* address : code) { + HMODULE still = nullptr; + check(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast<const char*>(address), &still), + "the stand-in is unloaded after FreeLibrary"); + } + Sleep(1500); // past a 10 ms sample period and a 1 s line interval: a leftover thread of either DLL would run now +} + +int run_case(const char* name, const char* acphal_path, const char* xapu_path, const char* transcript_path) +{ + HMODULE acphal = LoadLibraryA(acphal_path), xapu = LoadLibraryA(xapu_path); + if (!acphal || !xapu) return std::printf("FAIL: cannot load the stand-ins\n"), 2; + Api api{}; + api.create_heap = reinterpret_cast<CreateHeapFn>(GetProcAddress(acphal, "ApuCreateHeap")); + api.alloc = reinterpret_cast<AllocFn>(GetProcAddress(acphal, "ApuAlloc")); + api.free = reinterpret_cast<FreeFn>(GetProcAddress(acphal, "ApuFree")); + api.hal_create = reinterpret_cast<HalCreateFn>(GetProcAddress(acphal, "AcpHalCreate")); + api.shape_alloc = reinterpret_cast<ShapeAllocFn>(GetProcAddress(acphal, "AcpHalAllocateShapeContexts")); + api.acphal_activity = reinterpret_cast<ActivityFn>(GetProcAddress(acphal, "x2w_acphal_xma_activity")); + api.connect = reinterpret_cast<ConnectFn>(GetProcAddress(xapu, "XApuConnect")); + api.enqueue = reinterpret_cast<EnqueueFn>(GetProcAddress(xapu, "XApuEnqueueCommand")); + api.result_count = reinterpret_cast<CountFn>(GetProcAddress(xapu, "XApuGetResultCount")); + api.dequeue = reinterpret_cast<DequeueFn>(GetProcAddress(xapu, "XApuDequeueResult")); + api.disconnect = reinterpret_cast<DisconnectFn>(GetProcAddress(xapu, "XApuDisconnect")); + api.xapu_counts = reinterpret_cast<ActivityFn>(GetProcAddress(xapu, "x2w_xapu_command_counts")); + if (!api.create_heap || !api.alloc || !api.free || !api.hal_create || !api.shape_alloc || !api.acphal_activity || !api.connect || + !api.enqueue || !api.result_count || !api.dequeue || !api.disconnect || !api.xapu_counts) + return std::printf("FAIL: missing export\n"), 2; + char log_path[MAX_PATH] = ""; + GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, MAX_PATH); + check(api.acphal_activity(nullptr) == FALSE && api.xapu_counts(nullptr) == FALSE, "the exports refuse a null output"); + + if (!std::strcmp(name, "unload")) { + script_unload(api, acphal, xapu); + } else if (!std::strcmp(name, "none")) { + script_none(api); + Sleep(1500); // longer than the line interval: an unchanged count writes no line + take(api.acphal_activity); + take(api.xapu_counts); + check(activity_lines(log_path) == 0, "zero-write control logs no activity line"); + } else { + const bool on = !std::strcmp(name, "on"); + script(api, on); + if (on) { + const std::map<std::string, u64> want = { + {"xma.filled", 5}, {"xma.changed", 3}, {"xma.cleared", 2}, {"xma.submits", 4}, {"xma.1", 2}, + {"xma.3", 1}, {"xma.other", 1}, {"xapu.commands", 8}, {"xapu.1", 3}, {"xapu.2", 2}, + {"xapu.3", 1}, {"xapu.other", 1}, {"xapu.unreadable", 1}, {"xapu.rejected", 1}}; + std::map<std::string, u64> got; + int lines = 0; + for (int waited = 0; waited <= 5000; waited += 100) { // a call a second after the start writes the line + take(api.acphal_activity); + take(api.xapu_counts); + got = activity_sums(read_file(log_path), &lines); + if (got == want) break; + Sleep(100); + } + if (got != want) { + std::printf("FAIL: logged activity lines (%d) sum to%s\n expected%s\n", lines, describe(got).c_str(), + describe(want).c_str()); + ++failures; + } + } else { + Sleep(1500); + take(api.acphal_activity); + take(api.xapu_counts); + check(activity_lines(log_path) == 0, "counter off logs no activity line"); + check(read_file(log_path).find("-activity") == std::string::npos, "counter off logs nothing about activity"); + } + HANDLE out = CreateFileA(transcript_path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); + DWORD wrote = 0; + check(out != INVALID_HANDLE_VALUE && WriteFile(out, transcript.data(), static_cast<DWORD>(transcript.size()), &wrote, nullptr) && + wrote == transcript.size(), + "transcript written"); + if (out != INVALID_HANDLE_VALUE) CloseHandle(out); + } + std::printf(failures ? "case %s: %d failure(s)\n" : "case %s: ok\n", name, failures); + return failures ? 1 : 0; +} + +DWORD spawn(const char* self, const char* name, const char* acphal, const char* xapu, const std::string& dir) +{ + const std::string log = dir + "\\" + name + ".log", out = dir + "\\" + name + ".txt"; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_AUDIO_ACTIVITY", std::strcmp(name, "off") ? "1" : nullptr); + SetEnvironmentVariableA("X2W_PROBE_PRECHECK", "1"); // the short command's free tail is refused, not touched + SetEnvironmentVariableA("X2W_TRAP_LOG", log.c_str()); + std::string cmd = std::string("\"") + self + "\" --case " + name + " \"" + acphal + "\" \"" + xapu + "\" \"" + out + "\""; + // The child writes to this process's stdout and stderr, so its lines reach the CTest log. + STARTUPINFOA si{}; + si.cb = sizeof(si); + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + si.hStdError = GetStdHandle(STD_ERROR_HANDLE); + for (HANDLE h : {si.hStdOutput, si.hStdError}) SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + std::fflush(stdout); + PROCESS_INFORMATION pi{}; + if (!CreateProcessA(nullptr, cmd.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) return 0xFFFFFFFFu; + DWORD code = 0xFFFFFFFEu; + // 12 s per case keeps all four inside the CTest TIMEOUT of 60 s, so a hung case is named, not killed with the parent. + if (WaitForSingleObject(pi.hProcess, 12000) == WAIT_OBJECT_0) GetExitCodeProcess(pi.hProcess, &code); + else TerminateProcess(pi.hProcess, 0xFFFFFFFDu); // our own child, by handle + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + return code; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 6 && !std::strcmp(argv[1], "--case")) return run_case(argv[2], argv[3], argv[4], argv[5]); + if (argc != 3) return std::printf("usage: startup_acphal_xma_activity <AcpHal.dll> <xapu.dll>\n"), 2; + char temp[MAX_PATH]; + if (!GetTempPathA(MAX_PATH, temp)) return std::printf("FAIL: no temp folder\n"), 2; + const std::string dir = std::string(temp) + "x2w_xma_activity_" + std::to_string(GetCurrentProcessId()); + if (!CreateDirectoryA(dir.c_str(), nullptr)) return std::printf("FAIL: cannot create %s\n", dir.c_str()), 2; + char self[MAX_PATH]; + GetModuleFileNameA(nullptr, self, MAX_PATH); + for (const char* name : {"on", "none", "off", "unload"}) { + const DWORD code = spawn(self, name, argv[1], argv[2], dir); + if (code) { + std::printf("FAIL: case %s exited 0x%08lx\n", name, static_cast<unsigned long>(code)); + ++failures; + } + } + const std::string on = read_file((dir + "\\on.txt").c_str()), off = read_file((dir + "\\off.txt").c_str()); + check(!on.empty(), "the on case wrote a transcript"); + if (on != off) { + std::size_t at = 0; + while (at < on.size() && at < off.size() && on[at] == off[at]) ++at; + const std::size_t line = on.rfind('\n', at) == std::string::npos ? 0 : on.rfind('\n', at) + 1; + std::printf("FAIL: results differ with the counter on and off, first at: on '%s' off '%s'\n", + on.substr(line, on.find('\n', line) - line).c_str(), off.substr(line, off.find('\n', line) - line).c_str()); + ++failures; + } + for (const char* file : {"on.log", "none.log", "off.log", "unload.log", "on.txt", "off.txt"}) DeleteFileA((dir + "\\" + file).c_str()); + RemoveDirectoryA(dir.c_str()); + std::printf(failures ? "startup_acphal_xma_activity: %d failure(s)\n" : "startup_acphal_xma_activity: ok\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 44c6304f06..6d0ba47b36 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -11,18 +11,24 @@ def check_refusal_lines(log): prefix = r"x2w-d3d12 Device::slot70 " - expected = [ + buffer_unavailable = ( prefix + r"unavailable buffer at the supplied address: reason=buffer_unavailable " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " - + r"view\{dim=1 fmt=39 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " - + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + + r"view\{dim=1 fmt=39 map=0x1688 first=FIRST count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1" + ) + expected = [ + buffer_unavailable.replace("FIRST", "4"), # injected wrapper allocation failure + buffer_unavailable.replace("FIRST", "0"), # unaligned interior address prefix + r"unavailable acceleration structure at the supplied address: reason=as_wrong_state " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + r"view\{dim=11 fmt=0 map=0x1688 raw=(00000000,){5}00000000 " + r"\(acceleration structure view\)\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + buffer_unavailable.replace("FIRST", "0"), # unplaced raw view at page + 1 + buffer_unavailable.replace("FIRST", "0"), # unplaced raw view before stride-16 publication ] lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] if len(lines) != len(expected): @@ -50,13 +56,13 @@ def check(directory, consumer, backend): ) if actual is None: return 77 - values = (17, 63, 141, 141, 99, 17, 17, 17) + values = (17, 63, 141, 141, 99, 17, 201, 201, 55, 77, 55, 201, 201, 173, 173) row = b"".join(bytes((v, 0, 0, 255)) for v in values) expected = row * 4 if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view) exact") + print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view, unplaced structured view at a page offset the stride does not divide, unplaced buffer in a large allocation copied) exact") return 0 diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index a3b6286992..53bde47822 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -1,15 +1,29 @@ """Draw textures published by address (device slot 70) whose texels are in a console layout. - <consumer> <backend> seven textures, each drawn once; every pixel of the 512x128 target is - compared with the texel the view names; then two held descriptions - and one texture whose address is announced as XG rows after it - was published + <consumer> <backend> fourteen textures, three cubes and nine volume mips, each drawn once; every + pixel of the 512x128 target is compared with the texel the view names; + then three held descriptions and one texture whose address is announced + as XG rows after it was published <consumer> <backend> gate the upload lifetime control described at check_gate - <consumer> <backend> gate-ring the same draws with X2W_TEST_ADDRESS_UPLOAD_RING=1, which must show the - first payload overwritten + <consumer> <backend> gate-ring the same draws with X2W_TEST_ADDRESS_UPLOAD_RING=1: the 256 MiB ring + refuses the uploads past its cap, the refused draws read the null view + and the left half keeps payload 0 + <consumer> <backend> gate-ring-reuse after completion, a new ring upload draws payload 18 over the right half + <consumer> <backend> gate-ring-keep list A uploads 32 payloads (512 MiB) from the ring, is submitted, completes + and is never Reset; list B then draws payload 32 over the right half. Without + X2W_D3D12_RING_RELEASE_AT_SUBMIT, A keeps its chunks: the ring refuses past 256 MiB + and the right half reads the null view + <consumer> <backend> gate-ring-keep-release the same with X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: A releases its + chunks at its fenced submit, so B draws payload 32; A submitted again afterwards + would read reused chunks, so it is refused before the execute: the target, read + back after that submit, still holds payload 32 on the right (not A's payload 31) + <consumer> <backend> linear-unpadded the control described at check_linear_unpadded + <consumer> <backend> cube-order the control described at check_cube_order The backing bytes are built here, independently of src/startup_stubs/gfx10_layout.h, from the address -equations of AMD addrlib's GFX10 pattern tables, written out below. Reference: addrlib as Mesa carries it +equations of AMD addrlib's GFX10 pattern tables, written out below, and for the linear mode (0x100) from +HwlComputeSurfaceInfoLinear: rows whose pitch is the mip's rounded-up width aligned to 256 bytes, the mips +stored from the smallest to the largest. Reference: addrlib as Mesa carries it under src/amd/addrlib at the revision tools/fetch_addrlib.py pins (Mesa 25.1.0, commit 5c142e46f3f6e752ed745fd48912ebb8fad67145), files src/gfx10/gfx10SwizzlePattern.h, src/gfx10/gfx10addrlib.cpp and src/core/addrlib2.cpp, each with the notice "Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All @@ -33,9 +47,22 @@ class Console: - def __init__(self, width, height, mips, element, texels, layout): + def __init__(self, width, height, mips, element, texels, layout, unpadded=False): self.width, self.height, self.mips, self.element, self.texels = width, height, mips, element, texels mode = layout & 0xff + columns, rows = -(-width // texels), -(-height // texels) + size = lambda v, mip: max(1, (v + (1 << mip) - 1) >> mip) + self.linear = mode == 0 + if self.linear: + # unpadded: rows exactly one mip wide, for the control at check_linear_unpadded. + align = 1 if unpadded else 256 // element + self.pitch, self.start, offset = {}, {}, 0 + for mip in range(mips - 1, -1, -1): + self.pitch[mip] = -(-size(columns, mip) // align) * align + self.start[mip] = offset + offset += self.pitch[mip] * size(rows, mip) * element + self.bytes = offset + return self.log2 = {1: 8, 2: 8, 5: 12, 6: 12, 9: 16, 10: 16}[mode] bits = (DISPLAY if mode in (2, 6, 10) else STANDARD)[element].split() x_next, y_next = (sum(b[0] == axis for b in bits) for axis in "XY") @@ -48,8 +75,6 @@ def __init__(self, width, height, mips, element, texels, layout): y_next += 1 self.bits = bits self.block_w, self.block_h = 1 << x_next, 1 << y_next - columns, rows = -(-width // texels), -(-height // texels) - size = lambda v, mip: max(1, (v + (1 << mip) - 1) >> mip) tail_mips = self.log2 - 4 self.first_tail = mips if mips > 1: @@ -86,6 +111,8 @@ def rows(self, mip): return -(-max(1, self.height >> mip) // self.texels) def address(self, mip, x, y): + if self.linear: + return self.start[mip] + (y * self.pitch[mip] + x) * self.element if mip >= self.first_tail: ox, oy = self.origin[mip] return self.in_block(ox + x, oy + y) @@ -93,6 +120,59 @@ def address(self, mip, x, y): return self.start[mip] + (block << self.log2) + self.in_block(x % self.block_w, y % self.block_h) +# A volume in the 4 KiB standard mode (0x105): addrlib lays a 3D resource in a standard mode out in thick +# blocks (Gfx10Lib::HwlIsThick). The 12 address bits of an element follow the one-pipe row of +# GFX10_SW_4K_S3_PATINFO for its size; the block is 8x16x8 elements of 4 bytes, or 8x8x8 of 8. The volume is +# stored a layer of blocks (8 deep) at a time, and each layer holds that layer of every mip: the shared tail +# block first when the chain has one, then the mips from the smallest to the largest, blocks in x, then y. +# Mip sizes round up. A mip is in the tail when it is at most a block wide and half a block high and at most +# five mips remain; tail mip k from the end sits at byte (k << 8) of the tail block, which, read as 256-byte +# micro blocks (4x4x4 elements of 4 bytes, 4x2x4 of 8), is its origin in x and y. A BC1 volume is the volume +# of its 4x4 blocks, 8-byte elements one depth layer each: the sides are first rounded up to whole blocks, +# and every mip size after that is in blocks. +THICK_4K_S3 = {4: "0 0 X0 Y0 Z0 Y1 X1 Z1 Y2 X2 Z2 Y3", 8: "0 0 0 X0 Z0 Y0 X1 Z1 Y1 X2 Z2 Y2"} +MICRO_3D = {4: (4, 4), 8: (4, 2)} + + +class ConsoleVolume: + def __init__(self, width, height, depth, element, mips=1, texels=1): + width, height = -(-width // texels), -(-height // texels) + self.width, self.height, self.depth = width, height, depth + self.bits = THICK_4K_S3[element].split() + self.block = [1 << sum(b[0] == axis for b in self.bits) for axis in "XYZ"] + bw, bh, bd = self.block + mw, mh = MICRO_3D[element] + size = [(max(1, -(-width // (1 << m))), max(1, -(-height // (1 << m)))) for m in range(mips)] + tail = next((m for m, (w, h) in enumerate(size) if mips > 1 and w <= bw and h <= bh // 2 and mips - m <= 5), + mips) + self.wide, self.start, self.origin = {}, {}, {} + offset = 4096 if tail < mips else 0 + for m in reversed(range(tail)): + self.wide[m] = -(-size[m][0] // bw) + self.start[m] = offset + offset += self.wide[m] * -(-size[m][1] // bh) * 4096 + for m in range(tail, mips): + at = (4 - (m - tail)) << 8 + self.start[m] = 0 + self.origin[m] = (mw * ((at >> 9 & 1) | (at >> 10 & 2)), mh * ((at >> 8 & 1) | (at >> 9 & 2))) + self.layer = offset + self.bytes = self.layer * -(-depth // bd) + + def address(self, x, y, z, mip=0): + bw, bh, bd = self.block + value = (z // bd) * self.layer + self.start[mip] + if mip in self.origin: + x, y = x + self.origin[mip][0], y + self.origin[mip][1] + else: + value += ((y // bh) * self.wide[mip] + x // bw) * 4096 + x, y = x % bw, y % bh + for bit, name in enumerate(self.bits): + coordinate = {"X": x % bw, "Y": y % bh, "Z": z % bd}.get(name[0]) + if coordinate is not None and (coordinate >> int(name[1:])) & 1: + value |= 1 << bit + return value + + def rgba_texel(mip, x, y): return bytes(((7 * x + 40 * mip + 1) & 255, (5 * y + 3) & 255, (x ^ (3 * y)) & 255, 255)) @@ -114,15 +194,133 @@ def bc1_block(mip, x, y): ("RGBA8 256x256 chain 64 KiB display, tail mip 2", 256, 256, 4, RGBA8, 0x10a, 2), ("RGBA8 256x256 chain 64 KiB display, tail mip 3", 256, 256, 4, RGBA8, 0x10a, 3), ("RGBA8 40x24 256 B standard", 40, 24, 1, RGBA8, 0x101, 0), + # Linear: 100 texels are 400 bytes, so each row is padded to 512; 200 BC1 texels are 50 blocks, padded to 64. + ("RGBA8 100x40 linear", 100, 40, 1, RGBA8, 0x100, 0), + ("RGBA8 100x40 linear chain, mip 0", 100, 40, 4, RGBA8, 0x100, 0), + ("RGBA8 100x40 linear chain, mip 2", 100, 40, 4, RGBA8, 0x100, 2), + ("BC1 200x96 linear", 200, 96, 1, BC1, 0x100, 0), + # Linear one-dimensional textures (a trailing "1d"): one row per mip, each mip padded to 256 bytes and + # stored from the smallest up, so mip 0 of the 300-texel chain starts at 1536, not at 0. + ("RGBA8 300 1D linear", 300, 1, 1, RGBA8, 0x100, 0, "1d"), + ("RGBA8 300 1D linear chain, mip 0", 300, 1, 4, RGBA8, 0x100, 0, "1d"), + ("RGBA8 300 1D linear chain, mip 2", 300, 1, 4, RGBA8, 0x100, 2, "1d"), +] + + +def volume_texel(x, y, z, mip=0): + return bytes(((7 * x + 1) & 255, (5 * y + 3) & 255, (29 * z + 11) & 255, 255 - 16 * mip)) + + +def volume_bc1_block(x, y, z, mip=0): + """The block of BC1 volume block (x, y) of layer z: one colour, which differs between neighbours.""" + return bc1_block(mip, x, y + 3 * z) + + +# name, width, height, depth, format, layout, mips, viewed mip: RGBA8 or BC1 in the 4 KiB standard mode, one +# mip viewed as a Texture3D. Each target tile of the viewed mip's width and height draws one depth layer. The +# chains view a mip outside the tail and one inside it. +VOLUMES = [ + ("RGBA8 volume 17x17x17 4 KiB standard", 17, 17, 17, RGBA8, 0x105, 1, 0), + ("RGBA8 volume 33x9x18 4 KiB standard", 33, 9, 18, RGBA8, 0x105, 1, 0), + ("RGBA8 volume 32x32x32 6 mips, mip 1", 32, 32, 32, RGBA8, 0x105, 6, 1), + ("RGBA8 volume 32x32x32 6 mips, mip 3 in the tail", 32, 32, 32, RGBA8, 0x105, 6, 3), + ("RGBA8 volume 20x24x16 5 mips, mip 1", 20, 24, 16, RGBA8, 0x105, 5, 1), + ("RGBA8 volume 20x24x16 5 mips, mip 3 in the tail", 20, 24, 16, RGBA8, 0x105, 5, 3), + ("BC1 volume 48x40x12 4 KiB standard", 48, 40, 12, BC1, 0x105, 1, 0), + ("BC1 volume 64x64x8 5 mips, mip 1", 64, 64, 8, BC1, 0x105, 5, 1), + ("BC1 volume 64x64x8 5 mips, mip 3 in the tail", 64, 64, 8, BC1, 0x105, 5, 3), ] -def build(width, height, mips, fmt, layout): +def mip_sides(width, height, depth, mip): + return max(1, width >> mip), max(1, height >> mip), max(1, depth >> mip) + + +def volume_colour(fmt, x, y, z, mip): + """The RGBA8 colour a correct detile shows at texel (x, y, z) of a mip.""" + return volume_bc1_block(x // 4, y // 4, z, mip)[1] if fmt == BC1 else volume_texel(x, y, z, mip) + + +def build_volume(width, height, depth, mips=1, fmt=RGBA8): + """Backing bytes of a volume and its mips, built from the S3 rows above.""" + texels, element = (4, 8) if fmt == BC1 else (1, 4) + console = ConsoleVolume(width, height, depth, element, mips, texels) + backing = bytearray(console.bytes) + seen = set() + for mip in range(mips): + w, h, d = mip_sides(width, height, depth, mip) + for z in range(d): + for y in range(-(-h // texels)): + for x in range(-(-w // texels)): + at = console.address(x, y, z, mip) + if at in seen or at + element > len(backing): + raise AssertionError(f"oracle address {at:#x} of mip {mip} ({x},{y},{z}) is shared or outside " + "the volume") + seen.add(at) + if fmt == BC1: + backing[at:at + 8] = volume_bc1_block(x, y, z, mip)[0] + else: + backing[at:at + 4] = volume_texel(x, y, z, mip) + return backing + + +def check_volume(directory, consumer, backend, case, held=None): + name, width, height, depth, fmt, layout, mips, viewed = case + source = directory / "texels.bin" + source.write_bytes(build_volume(width, height, depth, mips, fmt)) + width, height, depth = mip_sides(width, height, depth, viewed) + across = -(-TARGET_W // width) + hlsl = ("Texture3D<float4> t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint x = uint(p.x), y = uint(p.y);\n" + f" uint z = (x / {width} + (y / {height}) * {across}) % {depth};\n" + f" return t.Load(int4(x % {width}, y % {height}, z, 0));\n}}\n") + trap_log = directory / "trap.log" + modes = {"X2W_TEST_CONSOLE_VIEW": str(source), "X2W_TRAP_LOG": str(trap_log), + "X2W_TEST_CONSOLE_DESC": f"{case[1]},{case[2]},{mips},{fmt},{layout},{viewed},{case[3]}"} + actual = draw_texture(directory, consumer, backend, hlsl, modes, "tex3d") + if actual is None: + return 77 + if len(actual) != TARGET_W * TARGET_H * 4: + raise AssertionError(f"{name}: readback length {len(actual)}") + log = trap_log.read_text(errors="replace") + if held: + if any(actual): + raise AssertionError(f"{name}: a held description drew texels") + if f"slot70 texture kind 1: {held};" not in log or "published console layout" in log: + raise AssertionError(f"{name}: no '{held}' line in the log, or a publication") + print(f"{backend} {name}: held ({held}), {TARGET_W * TARGET_H} pixels read the null view") + return 0 + layers = set() + for y in range(TARGET_H): + for x in range(TARGET_W): + z = (x // width + (y // height) * across) % depth + layers.add(z) + pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] + expect = volume_colour(fmt, x % width, y % height, z, viewed) + if pixel != expect: + raise AssertionError(f"{name}: pixel ({x},{y}) layer {z} actual {pixel.hex()} expected {expect.hex()}") + if len(layers) != depth: + raise AssertionError(f"{name}: the draw read {len(layers)} of {depth} layers") + if "slot70 texture kind 1: published console layout" not in log: + raise AssertionError(f"{name}: no 'published console layout' line in the log") + print(f"{backend} {name}: {TARGET_W * TARGET_H} RGBA pixels exact over {depth} layers") + return 0 + + +# A volume past the size the XG stand-in reports: 64x8x40 RGBA8 is eight blocks across, one down and five +# layers of blocks (163,840 bytes); the desktop footprint (40 layers of 8 rows of 256 bytes) rounded to +# 64 KiB is 131,072. A volume has one slice, so the footprint is not counted once per layer. +HELD_VOLUME = (("RGBA8 volume 64x8x40 4 KiB standard past the XG size", 64, 8, 40, RGBA8, 0x105, 1, 0), + "console_layout_beyond_xg_size") + + +def build(width, height, mips, fmt, layout, unpadded=False): """Backing bytes and, per mip, the RGBA texels a correct detile shows.""" texels = 4 if fmt == BC1 else 1 element = 8 if fmt == BC1 else 4 images = [] - console = Console(width, height, mips, element, texels, layout) + console = Console(width, height, mips, element, texels, layout, unpadded) backing = bytearray(console.bytes) seen = set() for mip in range(mips): @@ -163,19 +361,26 @@ def build(width, height, mips, fmt, layout): {"X2W_TEST_CONSOLE_XG_ROWS": "after"}) -def check(directory, consumer, backend, case, extra=None, held=None, late=False): - name, width, height, mips, fmt, layout, viewed = case - backing, images = build(width, height, mips, fmt, layout) +def check(directory, consumer, backend, case, extra=None, held=None, late=False, unpadded=False): + name, width, height, mips, fmt, layout, viewed, *dimension = case + one_d = dimension == ["1d"] + backing, images = build(width, height, mips, fmt, layout, unpadded) source = directory / "texels.bin" source.write_bytes(backing) w, h = max(1, width >> viewed), max(1, height >> viewed) - hlsl = ("Texture2D<float4> t : register(t0);\n" - "float4 main(float4 p : SV_Position) : SV_Target {\n" - f" return t.Load(int3(uint(p.x) % {w}, uint(p.y) % {h}, 0));\n}}\n") + if one_d: + hlsl = ("Texture1D<float4> t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + f" return t.Load(int2(uint(p.x) % {w}, 0));\n}}\n") + else: + hlsl = ("Texture2D<float4> t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + f" return t.Load(int3(uint(p.x) % {w}, uint(p.y) % {h}, 0));\n}}\n") trap_log = directory / "trap.log" + desc = f"{width},{height},{mips},{fmt},{layout},{viewed}" + (",1d" if one_d else "") modes = {"X2W_TEST_CONSOLE_VIEW": str(source), "X2W_TRAP_LOG": str(trap_log), - "X2W_TEST_CONSOLE_DESC": f"{width},{height},{mips},{fmt},{layout},{viewed}", **(extra or {})} - actual = draw_texture(directory, consumer, backend, hlsl, modes) + "X2W_TEST_CONSOLE_DESC": desc, **(extra or {})} + actual = draw_texture(directory, consumer, backend, hlsl, modes, "tex1d" if one_d else "tex2d") if actual is None: return 77 if len(actual) != TARGET_W * TARGET_H * 4: @@ -196,19 +401,140 @@ def check(directory, consumer, backend, case, extra=None, held=None, late=False) print(f"{backend} {name}: published, then {TARGET_W * TARGET_H} pixels read the null view") return 0 image = images[viewed] + wrong = 0 for y in range(TARGET_H): for x in range(TARGET_W): pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] expect = image[4 * ((y % h) * w + x % w):4 * ((y % h) * w + x % w) + 4] - if pixel != expect: + if pixel != expect and not unpadded: raise AssertionError(f"{name}: pixel ({x},{y}) actual {pixel.hex()} expected {expect.hex()}") + wrong += pixel != expect if "slot70 texture kind 1: published console layout" not in log: raise AssertionError(f"{name}: no 'published console layout' line in the log") + if unpadded: + if not wrong: + raise AssertionError(f"{name}: texels written without the 256-byte padding drew exactly; the padding is not checked") + print(f"{backend} {name}, without the 256-byte padding: published, {wrong} of {TARGET_W * TARGET_H} pixels differ") + return 0 print(f"{backend} {name}: {TARGET_W * TARGET_H} RGBA pixels exact") return 0 +def check_linear_unpadded(directory, consumer, backend): + """The linear cases' negative control. The first 2D linear texture has its rows written one mip wide + (400 bytes) instead of at the 256-byte pitch (512), and the 1D chain viewed at mip 2 has its mips packed + without padding, so mip 2 starts at 152 instead of 256. The runtime reads the padded layout, so each draw + must differ from the texels; an exact draw means the linear cases do not test the padding.""" + for name in ("RGBA8 100x40 linear", "RGBA8 300 1D linear chain, mip 2"): + case = next(c for c in CASES if c[0] == name) + with tempfile.TemporaryDirectory() as temporary: + result = check(Path(temporary), consumer, backend, case, unpadded=True) + if result: + return result + return 0 + + GATE_PAYLOADS = 18 +KEEP_PAYLOADS = 32 # tests/startup_stream_draw.cpp, X2W_TEST_CONSOLE_KEEP + + +# Cube views: a two-dimensional array of six in a console layout, each slice one face (+X, -X, +Y, -Y, +Z, +# -Z) and the slices one slice size apart (the whole mip chain of a slice). TextureCube has no Load, so the +# shader point-samples the centre of every texel of every face of the viewed mip: target column x picks face +# (x mod 6w) div w and column x mod w, row y picks row y mod w. The directions are the D3D cube face rules. +# name, side, mips, format, layout, viewed mip +CUBES = [ + ("RGBA8 64x64 cube 4 KiB standard", 64, 1, RGBA8, 0x105, 0), + ("RGBA8 64x64 cube 4 KiB standard chain, mip 1", 64, 4, RGBA8, 0x105, 1), + ("BC1 64x64 cube 4 KiB standard", 64, 1, BC1, 0x105, 0), +] + + +def cube_texel(face, mip, x, y): + texel = bytearray(rgba_texel(mip, x, y)) + texel[2] = (texel[2] + 37 * face) & 255 + return bytes(texel) + + +def build_cube(side, mips, fmt, layout, reversed_faces=False): + """Backing bytes and images[face][mip]. reversed_faces writes face f into slice 5 - f (the control).""" + texels = 4 if fmt == BC1 else 1 + element = 8 if fmt == BC1 else 4 + console = Console(side, side, mips, element, texels, layout) + backing = bytearray(6 * console.bytes) + images = [[None] * mips for _ in range(6)] + for face in range(6): + base = (5 - face if reversed_faces else face) * console.bytes + for mip in range(mips): + w = max(1, side >> mip) + image = bytearray(w * w * 4) + for y in range(console.rows(mip)): + for x in range(console.columns(mip)): + at = base + console.address(mip, x, y) + if fmt == BC1: + block, colour = bc1_block(mip + 3 * face, x, y) + backing[at:at + 8] = block + for row in range(4 * y, min(4 * y + 4, w)): + for column in range(4 * x, min(4 * x + 4, w)): + image[4 * (row * w + column):4 * (row * w + column) + 4] = colour + else: + texel = cube_texel(face, mip, x, y) + backing[at:at + 4] = texel + image[4 * (y * w + x):4 * (y * w + x) + 4] = texel + images[face][mip] = image + return backing, images + + +def check_cube(directory, consumer, backend, case, reversed_faces=False): + name, side, mips, fmt, layout, viewed = case + backing, images = build_cube(side, mips, fmt, layout, reversed_faces) + source = directory / "texels.bin" + source.write_bytes(backing) + w = max(1, side >> viewed) + hlsl = ("TextureCube<float4> t : register(t0);\n" + "SamplerState s : register(s0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + f" uint x = uint(p.x) % {6 * w}, y = uint(p.y) % {w}, face = x / {w};\n" + f" float a = (float(x % {w}) + 0.5) / {w} * 2 - 1, b = (float(y) + 0.5) / {w} * 2 - 1;\n" + " float3 d = face == 0 ? float3(1, -b, -a) : face == 1 ? float3(-1, -b, a) :\n" + " face == 2 ? float3(a, 1, b) : face == 3 ? float3(a, -1, -b) :\n" + " face == 4 ? float3(a, -b, 1) : float3(-a, -b, -1);\n" + " return t.SampleLevel(s, d, 0);\n}\n") + trap_log = directory / "trap.log" + modes = {"X2W_TEST_CONSOLE_VIEW": str(source), "X2W_TRAP_LOG": str(trap_log), + "X2W_TEST_CONSOLE_DESC": f"{side},{side},{mips},{fmt},{layout},{viewed},cube"} + actual = draw_texture(directory, consumer, backend, hlsl, modes, + binding="srv 0 texcube table 0 0\nsmp 0 0 0 0 0") + if actual is None: + return 77 + if len(actual) != TARGET_W * TARGET_H * 4: + raise AssertionError(f"{name}: readback length {len(actual)}") + wrong = 0 + for y in range(TARGET_H): + for x in range(TARGET_W): + pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] + column = x % (6 * w) + image = images[column // w][viewed] + expect = image[4 * ((y % w) * w + column % w):4 * ((y % w) * w + column % w) + 4] + if pixel != expect and not reversed_faces: + raise AssertionError(f"{name}: pixel ({x},{y}) actual {pixel.hex()} expected {expect.hex()}") + wrong += pixel != expect + if "slot70 texture kind 1: published console layout" not in trap_log.read_text(errors="replace"): + raise AssertionError(f"{name}: no 'published console layout' line in the log") + if reversed_faces: + if not wrong: + raise AssertionError(f"{name}: faces written in reverse slice order drew exactly; the face order is not checked") + print(f"{backend} {name}, faces in reverse slice order: published, {wrong} of {TARGET_W * TARGET_H} pixels differ") + return 0 + print(f"{backend} {name}: {TARGET_W * TARGET_H} RGBA pixels exact over 6 faces") + return 0 + + +def check_cube_order(consumer, backend): + """The cube cases' negative control: the first cube with face f written into slice 5 - f. The runtime + reads slice f as face f, so the draw must differ from the texels.""" + with tempfile.TemporaryDirectory() as temporary: + return check_cube(Path(temporary), consumer, backend, CUBES[0], reversed_faces=True) def gate_colour(payload): @@ -216,7 +542,7 @@ def gate_colour(payload): return bytes(((17 * payload + 3) & 255, (255 - 9 * payload) & 255, payload ^ 0x5a, 255)) -def check_gate(directory, consumer, backend, ring): +def check_gate(directory, consumer, backend, mode): """Uploads recorded while the queue cannot run must still hold their bytes when it does. The normal fixture records and discards a draw using payload 0 before the first submit retries that @@ -227,15 +553,31 @@ def check_gate(directory, consumer, backend, ring): The fixture then signals the fence, waits for the last submit and reads the target back: the left half must hold payload 0 and the right half payload 17. - Eighteen 16 MiB uploads are more than the 256 MiB upload ring. With X2W_TEST_ADDRESS_UPLOAD_RING=1 the - uploads come from the ring, the later ones pass over the bytes of payload 0 before the queue has copied - them, and the left half must not hold payload 0. + The shared ring refuses later reservations once its capacity is exhausted. + The left half must retain payload 0 and the final right-half draw must + read the null view. """ hlsl = ("Texture2D<float4> t : register(t0);\n" "float4 main(float4 p : SV_Position) : SV_Target {\n" " return t.Load(int3(uint(p.x) % 2048, uint(p.y) % 2048, 0));\n}\n") trap_log = directory / "trap.log" modes = {"X2W_TEST_CONSOLE_GATE": "1", "X2W_TRAP_LOG": str(trap_log)} + ring = mode != "gate" + reuse = mode == "gate-ring-reuse" + keep = mode in ("gate-ring-keep", "gate-ring-keep-release") + release = mode == "gate-ring-keep-release" + if keep: + modes["X2W_TEST_CONSOLE_KEEP"] = "1" + else: + os.environ.pop("X2W_TEST_CONSOLE_KEEP", None) + if release: + modes["X2W_D3D12_RING_RELEASE_AT_SUBMIT"] = "1" + else: + os.environ.pop("X2W_D3D12_RING_RELEASE_AT_SUBMIT", None) + if reuse: + modes["X2W_TEST_ADDRESS_UPLOAD_RING_REUSE"] = "1" + else: + os.environ.pop("X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", None) if ring: modes["X2W_TEST_ADDRESS_UPLOAD_RING"] = "1" else: @@ -246,7 +588,12 @@ def check_gate(directory, consumer, backend, ring): return 77 if len(actual) != TARGET_W * TARGET_H * 4: raise AssertionError(f"gate: readback length {len(actual)}") - first, last = gate_colour(0), gate_colour(GATE_PAYLOADS - 1) + first = gate_colour(0) + last = bytes(4) if ring else gate_colour(GATE_PAYLOADS - 1) + if reuse: + last = gate_colour(GATE_PAYLOADS) + if release: + last = gate_colour(KEEP_PAYLOADS) wrong = {"left": 0, "right": 0} seen = set() for y in range(TARGET_H): @@ -259,13 +606,31 @@ def check_gate(directory, consumer, backend, ring): log = trap_log.read_text(errors="replace") released = f"x2w-draw by-address uploads: {GATE_PAYLOADS} submits completed and released" half = TARGET_W * TARGET_H // 2 + if keep: + if wrong["left"] or wrong["right"]: + ring_lines = "\n".join(line for line in log.splitlines() if "upload ring" in line) + raise AssertionError(f"{mode}: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, " + f"{last.hex()} right\n{ring_lines}") + refused = "x2w-draw upload ring reservation refused: no unused capacity" in log + reported = "were reused; refused, it is not executed" in log + if release and not reported: + raise AssertionError(f"{mode}: list A submitted again after B reused its chunk was not refused") + if not release and (not refused or reported): + raise AssertionError(f"{mode}: expected the 256 MiB refusal and no resubmit refusal (refused={refused}, reported={reported})") + print(f"{backend} {mode}: {half} left pixels hold payload 0 and {half} right pixels hold {last.hex()} after A's " + "resubmit; " + + ("A's chunks were released at its fenced submit and its stale resubmit was refused, not executed" if release + else "the never-Reset list kept its chunks and the ring refused past its cap")) + return 0 if ring: - if not wrong["left"] or wrong["right"]: - raise AssertionError(f"gate-ring: {wrong} wrong pixels; expected the left half overwritten and the right intact") + if wrong["left"] or wrong["right"]: + raise AssertionError(f"{mode}: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, {last.hex()} right") + if "x2w-draw upload ring reservation refused: no unused capacity" not in log: + raise AssertionError("gate-ring: no upload reservation refusal") if "x2w-draw by-address uploads:" in log: raise AssertionError("gate-ring: the ring control retained upload buffers") - print(f"{backend} gate, uploads from the shared ring (control): {wrong['left']} of {half} left pixels do not hold " - f"payload 0 (found {sorted(seen)[:3]}); right half holds payload {GATE_PAYLOADS - 1}") + print(f"{backend} gate, uploads from the shared ring: exhaustion refused; " + f"{half} left pixels hold payload 0 and {half} right pixels hold {last.hex()}") return 0 if wrong["left"] or wrong["right"]: raise AssertionError(f"gate: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, {last.hex()} right") @@ -277,22 +642,43 @@ def check_gate(directory, consumer, backend, ring): return 0 +GATES = ("gate", "gate-ring", "gate-ring-reuse", "gate-ring-keep", "gate-ring-keep-release") + if __name__ == "__main__": - if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring")): - usage = "usage: startup_address_console_check.py <consumer> <backend> [gate | gate-ring]\n" + modes = GATES + ("linear-unpadded", "cube-order") + if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in modes): + usage = "usage: startup_address_console_check.py <consumer> <backend> [" + " | ".join(modes) + "]\n" sys.exit(usage + "\n\n".join(__doc__.split("\n\n")[:2])) + if len(sys.argv) == 4 and sys.argv[3] == "linear-unpadded": + sys.exit(check_linear_unpadded(None, sys.argv[1], sys.argv[2])) + if len(sys.argv) == 4 and sys.argv[3] == "cube-order": + sys.exit(check_cube_order(sys.argv[1], sys.argv[2])) if len(sys.argv) == 4: with tempfile.TemporaryDirectory() as temporary: - sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3] == "gate-ring")) + sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3])) for case in CASES: with tempfile.TemporaryDirectory() as temporary: result = check(Path(temporary), *sys.argv[1:3], case) if result: sys.exit(result) + for case in CUBES: + with tempfile.TemporaryDirectory() as temporary: + result = check_cube(Path(temporary), *sys.argv[1:3], case) + if result: + sys.exit(result) + for case in VOLUMES: + with tempfile.TemporaryDirectory() as temporary: + result = check_volume(Path(temporary), *sys.argv[1:3], case) + if result: + sys.exit(result) for case, extra, held in HELD: with tempfile.TemporaryDirectory() as temporary: result = check(Path(temporary), *sys.argv[1:3], case, extra, held) if result: sys.exit(result) + with tempfile.TemporaryDirectory() as temporary: + result = check_volume(Path(temporary), *sys.argv[1:3], *HELD_VOLUME) + if result: + sys.exit(result) with tempfile.TemporaryDirectory() as temporary: sys.exit(check(Path(temporary), *sys.argv[1:3], LATE[0], LATE[1], late=True)) diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2a72fc2d3..0033e03da1 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -1,4 +1,5 @@ #include <d3d12.h> +#include <d3d12sdklayers.h> #include <array> #include <cstddef> #include <cstdint> @@ -12,6 +13,7 @@ using Word = std::uint64_t; Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); extern "C" __declspec(dllimport) void x2w_d3d12_texture_written(void* base, unsigned long long bytes); extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void* base, UINT width, UINT height); +extern "C" __declspec(dllimport) void x2w_d3d12_fail_wraps(LONG count); namespace { template<class T> Word ptr(T* value) { return reinterpret_cast<Word>(value); } struct ViewAt { @@ -21,12 +23,23 @@ struct ViewAt { }; static_assert(offsetof(ViewAt, address) == 0x28 && sizeof(ViewAt) == 0x40); -bool bind_view_table(void* guest, void* list, Word& cpu) +bool failed_publication_keeps_view(void* guest, const D3D12_RESOURCE_DESC& desc, const ViewAt& view, Word cpu) +{ + const auto* slot = reinterpret_cast<const void*>(cpu); + std::array<unsigned char, 32> previous; + std::memcpy(previous.data(), slot, previous.size()); + x2w_d3d12_fail_wraps(1); + invoke(guest, 70, ptr(&desc), ptr(&view), cpu); + x2w_d3d12_fail_wraps(0); + return std::memcmp(previous.data(), slot, previous.size()) == 0; +} + +bool bind_view_table(void* guest, void* list, Word& cpu, UINT count = 1, Word address = 0, Word bytes = 0) { struct Extended { D3D12_DESCRIPTOR_HEAP_DESC desc; Word address, bytes; - } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, address, bytes}; void* heap = nullptr; if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) return false; cpu = invoke(heap, 9); @@ -58,7 +71,16 @@ int draw_address_srvs(ID3D12Device* desktop, void* guest, void* list) 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[i]))))) return 41; } Word cpu = 0; - if (!bind_view_table(guest, list, cpu)) return 42; + const bool joined_table = GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; + const Word stride = joined_table ? invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) : 0; + static std::vector<unsigned char> title_table; // The bound heap retains this backing memory. + if (joined_table) { + if (stride < 32) return 42; + title_table.resize(2 * stride); + } + if (!bind_view_table(guest, list, cpu, joined_table ? 2 : 1, joined_table ? ptr(title_table.data()) : 0, + joined_table ? title_table.size() : 0)) return 42; + if (joined_table && cpu != ptr(title_table.data())) return 42; ViewAt v{}; v.view.Format = DXGI_FORMAT_R8_UNORM; v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; @@ -69,6 +91,20 @@ int draw_address_srvs(ID3D12Device* desktop, void* guest, void* list) invoke(list, 22, 1, ptr(&strip)); invoke(list, 12, 3, 1); }; + if (joined_table) { + for (UINT swap = 0; swap < 2; ++swap) { + for (UINT i = 0; i < 2; ++i) + invoke(guest, 18, ptr(placed[i ^ swap]), ptr(&v.view), cpu + i * stride); + // The shader uses packed 32-byte records. Publish both views at native + // slot boundaries, then pack the second token in the guest-owned table. + std::memmove(title_table.data() + 32, title_table.data() + stride, 32); + for (UINT key = 0; key < 4; ++key) { + invoke(list, 40, 1, 1, ptr(&key), 0); + draw(static_cast<LONG>(swap * 4 + key)); + } + } + return 0; + } const auto publish = [&](const D3D12_RESOURCE_DESC& resource_desc, Word address) { v.address = address; invoke(guest, 70, ptr(&resource_desc), ptr(&v), cpu); @@ -224,30 +260,52 @@ int draw_bc_address_srvs(void* guest, void* list) } // X2W_TEST_CONSOLE_VIEW names a file of texels and X2W_TEST_CONSOLE_DESC the texture they belong to -// ("width,height,mips,format,layout,viewed mip"). No resource object exists at the address; one mip is -// viewed and drawn over the whole target. With X2W_TEST_CONSOLE_XG_ROWS=1 the address is first announced +// ("width,height,mips,format,layout,viewed mip", then optionally ",1d" for a one-dimensional texture with a +// one-dimensional view, ",cube" for a two-dimensional array of six with a cube view, or ",depth" for a volume +// viewed as a Texture3D). No resource object exists at the address; one mip is viewed and drawn over the whole +// target. With X2W_TEST_CONSOLE_XG_ROWS=1 the address is first announced // the way the XG stand-in announces a copy of desktop-footprint rows; with =after the announcement comes // between the publication and the draw. int draw_console_address_srv(void* guest, void* list) { wchar_t path[MAX_PATH]{}; const DWORD length = GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_VIEW", path, MAX_PATH); - char text[96]{}; + char text[96]{}, extra[8]{}; unsigned width = 0, height = 0, mips = 0, format = 0, layout = 0, viewed = 0; - if (!length || length >= MAX_PATH || !GetEnvironmentVariableA("X2W_TEST_CONSOLE_DESC", text, sizeof(text)) || - std::sscanf(text, "%u,%u,%u,%u,%u,%u", &width, &height, &mips, &format, &layout, &viewed) != 6) return 43; + if (!length || length >= MAX_PATH || !GetEnvironmentVariableA("X2W_TEST_CONSOLE_DESC", text, sizeof(text))) return 43; + const int fields = std::sscanf(text, "%u,%u,%u,%u,%u,%u,%7s", &width, &height, &mips, &format, &layout, &viewed, extra); + const bool one_d = fields == 7 && !std::strcmp(extra, "1d"); + const bool cube = fields == 7 && !std::strcmp(extra, "cube"); + const unsigned depth = fields == 7 && !one_d && !cube ? static_cast<unsigned>(std::strtoul(extra, nullptr, 10)) : 0; + if (fields != 6 && !one_d && !cube && !depth) return 43; alignas(4096) static std::array<char, 1 << 20> backing{}; std::ifstream input(path, std::ios::binary); input.read(backing.data(), backing.size()); if (!input.gcount() || !input.eof()) return 43; - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, static_cast<UINT16>(mips), + const D3D12_RESOURCE_DESC desc{one_d ? D3D12_RESOURCE_DIMENSION_TEXTURE1D + : depth ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D, + 0, width, height, static_cast<UINT16>(depth ? depth : cube ? 6 : 1), static_cast<UINT16>(mips), static_cast<DXGI_FORMAT>(format), {1, 0}, static_cast<D3D12_TEXTURE_LAYOUT>(layout), D3D12_RESOURCE_FLAG_NONE}; ViewAt v{}; v.view.Format = desc.Format; - v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - v.view.Texture2D.MostDetailedMip = viewed; - v.view.Texture2D.MipLevels = 1; + if (one_d) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + v.view.Texture1D.MostDetailedMip = viewed; + v.view.Texture1D.MipLevels = 1; + } else if (cube) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + v.view.TextureCube.MostDetailedMip = viewed; + v.view.TextureCube.MipLevels = 1; + } else if (depth) { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.view.Texture3D.MostDetailedMip = viewed; + v.view.Texture3D.MipLevels = 1; + } else { + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.view.Texture2D.MostDetailedMip = viewed; + v.view.Texture2D.MipLevels = 1; + } v.address = ptr(backing.data()); Word cpu = 0; if (!bind_view_table(guest, list, cpu)) return 42; @@ -438,7 +496,25 @@ int draw_formatted_view(void* guest, void* list) desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; void* placed = nullptr; - if (FAILED(static_cast<HRESULT>(invoke(guest, 133, ptr(bytes), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + char indexed_stride[16]{}; + const bool indexed = GetEnvironmentVariableA("X2W_TEST_INDEXED_STRIDE", indexed_stride, sizeof(indexed_stride)) != 0; + if (indexed) { + unsigned stride = 0; + if (std::sscanf(indexed_stride, "%u", &stride) != 1 || !stride || stride > 64 || 64 % stride) return 48; + auto* upload = reinterpret_cast<void*>(invoke(list, 148, 64, 256)); + if (!upload || ptr(upload) >> 48) return 47; + std::memcpy(upload, bytes, 64); + alignas(64) static std::array<unsigned, 64> descriptors{}; + Word cpu = 0; + const Word increment = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (increment < 32 || increment > sizeof(descriptors) || + !bind_view_table(guest, list, cpu, 1, ptr(descriptors.data()), increment) || cpu != ptr(descriptors.data())) return 42; + descriptors[0] = static_cast<unsigned>(ptr(upload)); + descriptors[1] = static_cast<unsigned>(ptr(upload) >> 32) | stride << 16; + descriptors[2] = 64 / stride; + invoke(list, 12, 3, 1); + return 0; + } else if (FAILED(static_cast<HRESULT>(invoke(guest, 133, ptr(bytes), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; Word cpu = 0; if (!bind_view_table(guest, list, cpu)) return 42; @@ -450,6 +526,200 @@ int draw_formatted_view(void* guest, void* list) return 0; } +// X2W_TEST_TABLE_ALIAS_WRITE: a buffer view the title creates over a placed buffer, at table entry 0 +// (tests/startup_table_alias_check.py). +// 1 a raw view of the whole 256-byte buffer. The title writes the record, draws the left half, writes +// it again, draws the right half, and writes it a third time after recording, before the list runs. +// A per-draw copy shows the first two values; a live alias shows the third in both halves. +// shared-index the same buffer is also the index buffer of one indexed draw (indices 0-2 at offset 0). The alias +// must be in both the index-buffer and the shader-resource states at that draw. +// odd-size a 254-byte buffer under a structured view of 127 two-byte records. The desktop raw view covers +// 256 bytes, past the alias, so the draw takes a copy: it shows the value written before recording. +// With X2W_TEST_DEBUG_LAYER, errors the debug layer stored for the device from the fixture's start +// (ID3D12InfoQueue; the message callback of ID3D12InfoQueue1 needs a newer runtime). +ID3D12InfoQueue* table_alias_messages = nullptr; + +void table_alias_debug_report() +{ + if (!table_alias_messages) return; + int errors = 0; + const UINT64 stored = table_alias_messages->GetNumStoredMessages(); + for (UINT64 i = 0; i < stored; ++i) { + SIZE_T bytes = 0; + if (FAILED(table_alias_messages->GetMessage(i, nullptr, &bytes)) || !bytes) continue; + std::vector<unsigned char> storage(bytes); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (FAILED(table_alias_messages->GetMessage(i, message, &bytes)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) + continue; + if (++errors <= 8) std::printf("debug layer id %d: %.300s\n", static_cast<int>(message->ID), message->pDescription); + } + std::printf("table alias debug layer errors: %d\n", errors); +} + +int draw_table_alias_writes(ID3D12Device* desktop, void* guest, void* list) +{ + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps))) || !heaps.Supported) + return 77; + if (GetEnvironmentVariableW(L"X2W_TEST_DEBUG_LAYER", nullptr, 0)) { + if (FAILED(desktop->QueryInterface(IID_PPV_ARGS(&table_alias_messages)))) { + std::printf("no debug layer message queue: skipped\n"); + return 77; + } + table_alias_messages->SetMessageCountLimit(4096); + table_alias_messages->ClearStoredMessages(); + } + char mode[16]{}; + GetEnvironmentVariableA("X2W_TEST_TABLE_ALIAS_WRITE", mode, sizeof(mode)); + const bool shared_index = !std::strcmp(mode, "shared-index"); + const bool odd_size = !std::strcmp(mode, "odd-size"); + if (!shared_index && !odd_size && std::strcmp(mode, "1")) return 70; + // VirtualAlloc memory, so the placement can alias it (an existing heap cannot open image memory). + auto* const records = static_cast<std::uint32_t*>(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!records) return 71; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, odd_size ? 254u : 256u, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* placed = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, ptr(records), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + D3D12_SHADER_RESOURCE_VIEW_DESC view{odd_size ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32_TYPELESS, + D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.NumElements = odd_size ? 127 : 64; + view.Buffer.StructureByteStride = odd_size ? 2 : 0; + view.Buffer.Flags = odd_size ? D3D12_BUFFER_SRV_FLAG_NONE : D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(placed), ptr(&view), cpu); + if (shared_index || odd_size) { + auto* const indices = reinterpret_cast<std::uint16_t*>(records); + for (std::uint16_t i = 0; i < 3; ++i) indices[i] = i; + records[4] = 40; + records[5] = 41; + const D3D12_RECT full{0, 0, 8, 4}; + invoke(list, 22, 1, ptr(&full)); + if (shared_index) { + const D3D12_INDEX_BUFFER_VIEW index_view{ptr(records), 6, DXGI_FORMAT_R16_UINT}; + invoke(list, 47, ptr(&index_view)); + invoke(list, 13, 3, 1, 0, 0, 0); + } else { + invoke(list, 12, 3, 1); + records[4] = 120; // after recording: only a live alias would show it + records[5] = 121; + } + return 0; + } + const auto write = [&](std::uint32_t value) { + records[4] = value; + records[5] = value + 1; + }; + const auto draw = [&](LONG left, LONG right) { + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + write(40); + draw(0, 4); + write(80); + draw(4, 8); + write(120); // after recording: only a binding that reads at execution sees it + return 0; +} + +int draw_copied_vertex_buffer_srv(void* guest, void* list) +{ + constexpr UINT full_bytes = 512; + constexpr UINT short_bytes = 256; + static std::array<std::uint8_t, 65536 + full_bytes> storage{}; + auto* records = reinterpret_cast<std::uint32_t*>((ptr(storage.data()) + 0xffff) & ~Word{0xffff}); + records[224 / sizeof(*records)] = 57; + records[288 / sizeof(*records)] = 181; + + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, full_bytes, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* placed = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, ptr(records), ptr(&buffer), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + + const Word stride = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + alignas(64) static std::array<std::uint8_t, 256> descriptors{}; + Word cpu = 0; + if (!stride || stride > descriptors.size() / 3 || + !bind_view_table(guest, list, cpu, 3, ptr(descriptors.data()), 3 * stride) || + cpu != ptr(descriptors.data())) return 42; + + ViewAt view{}; + view.view.Format = DXGI_FORMAT_R32_TYPELESS; + view.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + view.address = ptr(records); + view.view.Buffer.NumElements = full_bytes / sizeof(*records); + invoke(guest, 70, ptr(&buffer), ptr(&view), cpu + stride); + view.view.Buffer.NumElements = short_bytes / sizeof(*records); + invoke(guest, 70, ptr(&buffer), ptr(&view), cpu + 2 * stride); + if (std::memcmp(descriptors.data() + stride, descriptors.data() + 2 * stride, stride) == 0) return 54; + + const auto copy_and_draw = [&](Word source, LONG left, LONG right) { + invoke(guest, 24, 1, cpu, cpu + source * stride, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (std::memcmp(descriptors.data(), descriptors.data() + source * stride, stride) != 0) return false; + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + return true; + }; + if (!copy_and_draw(1, 0, 2) || !copy_and_draw(2, 2, 6) || !copy_and_draw(1, 6, 8)) return 55; + std::printf("copied vertex buffer SRV with %llu-byte descriptors\n", static_cast<unsigned long long>(stride)); + return 0; +} + +int draw_copied_vertex_srv_pair(void* guest, void* list) +{ + constexpr UINT bytes = 512; + constexpr Word record_bytes = 32; + static std::uint8_t inputs[2][65536 + bytes]{}; + constexpr std::uint32_t values[]{181, 211}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const Word stride = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + alignas(64) static std::array<std::uint8_t, 256> descriptors{}; + Word cpu = 0; + if (stride < record_bytes || stride > descriptors.size() / 4 || + !bind_view_table(guest, list, cpu, 4, ptr(descriptors.data()), 4 * stride) || + cpu != ptr(descriptors.data())) return 42; + + ViewAt view{}; + view.view.Format = DXGI_FORMAT_R32_TYPELESS; + view.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + view.view.Buffer.NumElements = bytes / sizeof(std::uint32_t); + for (Word i = 0; i < 2; ++i) { + void* placed = nullptr; + view.address = (ptr(inputs[i]) + 0xffff) & ~Word{0xffff}; + reinterpret_cast<std::uint32_t*>(view.address)[288 / sizeof(std::uint32_t)] = values[i]; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, view.address, ptr(&buffer), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + invoke(guest, 70, ptr(&buffer), ptr(&view), cpu + (2 + i) * stride); + } + auto* const records = descriptors.data(); + if (std::memcmp(records + 2 * stride, records + 3 * stride, record_bytes) == 0) return 54; + + const auto draw = [&](Word first, Word second, LONG left, LONG right) { + invoke(guest, 24, 1, cpu, cpu + first * stride, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + invoke(guest, 24, 1, cpu + stride, cpu + second * stride, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + // The shader reads fixed-width guest records. Copy via the reported descriptor stride first. + std::memmove(records + record_bytes, records + stride, record_bytes); + if (std::memcmp(records, records + first * stride, record_bytes) != 0 || + std::memcmp(records + record_bytes, records + second * stride, record_bytes) != 0) return false; + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + return true; + }; + if (!draw(2, 3, 0, 2) || !draw(3, 2, 2, 6) || !draw(2, 3, 6, 8)) return 55; + return 0; +} + int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) { static std::array<std::uint8_t, 65536 + 256> raw_buf0{}; @@ -500,6 +770,7 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) raw.address = ptr(buf1); raw.view.Buffer.FirstElement = 4; + if (!failed_publication_keeps_view(guest, desc, raw, cpu)) return 54; invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(2); @@ -532,8 +803,69 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) raw.view.Buffer.FirstElement = 0; invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(5); + + // An unplaced structured view whose address is not a whole number of 12-byte elements past its 64 KiB page start + // (page offset 0x104): published from a copy that starts at the address, so the shader reads 201 at element 0. + static auto* const suballoc = static_cast<unsigned char*>(VirtualAlloc(nullptr, 2 * 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!suballoc) return 56; + auto* const odd = reinterpret_cast<std::uint32_t*>((reinterpret_cast<std::uintptr_t>(suballoc) & ~std::uintptr_t{0xffff}) + 65536 + 0x104); + odd[0] = 201; + *reinterpret_cast<std::uint32_t*>(reinterpret_cast<unsigned char*>(odd) - 4) = 55; // read by the raw view at page + 0x100 below + structured.view.Buffer.FirstElement = 0; + structured.view.Buffer.StructureByteStride = 12; + structured.address = ptr(odd); + invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); draw(6); + + // An unplaced raw view at page + 1 is refused as before (the exact-start copy is only for structured and typed views): + // the previous descriptor stays, so column 7 still reads 201. + raw.view.Buffer.FirstElement = 0; + raw.address = ptr(reinterpret_cast<unsigned char*>(odd) - 0x103); + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); draw(7); + + // A raw view that overlaps the copy made for the structured view above (page + 0x100) takes its own backing of the page. + raw.address = ptr(reinterpret_cast<unsigned char*>(odd) - 4); + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(8); + + // An unplaced buffer in an allocation above the 256 MiB limit is not wrapped as an existing heap; its + // upload copy must still publish the bytes at the address. + static auto* const large = static_cast<std::uint32_t*>( + VirtualAlloc(nullptr, (256ull << 20) + 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!large) return 53; + large[4] = 77; + raw.address = ptr(large); + raw.view.Buffer.FirstElement = 4; + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(9); + + // Use fresh pages in the large allocation to exercise the upload path on every adapter. + auto* const raw_first = reinterpret_cast<unsigned char*>(large) + 65536; + *reinterpret_cast<std::uint32_t*>(raw_first + 0x100) = 55; + *reinterpret_cast<std::uint32_t*>(raw_first + 0x104) = 201; + raw.address = ptr(raw_first + 0x100); + raw.view.Buffer.FirstElement = 0; + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(10); + structured.address = ptr(raw_first + 0x104); + invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); + draw(11); + + auto* const refused_first = raw_first + 65536; + auto* const structured_only = refused_first + 65536; + *reinterpret_cast<std::uint32_t*>(refused_first + 0x10c) = 173; + *reinterpret_cast<std::uint32_t*>(structured_only + 0x10c) = 173; + raw.address = ptr(refused_first + 1); + invoke(guest, 70, ptr(&desc), ptr(&raw), cpu); + draw(12); + structured.view.Buffer.StructureByteStride = 16; + structured.address = ptr(refused_first + 0x10c); + invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); + draw(13); + structured.address = ptr(structured_only + 0x10c); + invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); + draw(14); return 0; } @@ -581,7 +913,9 @@ int draw_single_element_srvs(void* guest, void* list) const auto rgba = texel(DXGI_FORMAT_R8G8B8A8_UNORM, 0); publish(rgba, view_of(rgba, ptr(memory[0]))); draw(0); const auto swizzled = texel(DXGI_FORMAT_R8G8B8A8_UNORM, 0x105); - publish(swizzled, view_of(swizzled, ptr(memory[1]))); draw(1); + const auto second_view = view_of(swizzled, ptr(memory[1])); + if (!failed_publication_keeps_view(guest, swizzled, second_view, cpu)) return 54; + publish(swizzled, second_view); draw(1); std::memcpy(memory[0], c, 4); // rewritten, then published again at the same address publish(rgba, view_of(rgba, ptr(memory[0]))); draw(2); std::memcpy(memory[0], d, 4); // rewritten without a new publication: column 3 must read it @@ -870,7 +1204,7 @@ int draw_volume_address_srvs(ID3D12Device* desktop, void* guest, void* list) bad_clamp.view.Texture3D.ResourceMinLODClamp = 1.0f; invoke(guest, 70, ptr(&desc), ptr(&bad_clamp), cpu); - // 5. Wrong layout (console layout 0x105) + // 5. A console layout (0x105) over the live desktop-layout volume: refused as overlapping_resource D3D12_RESOURCE_DESC bad_layout = desc; bad_layout.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x105); invoke(guest, 70, ptr(&bad_layout), ptr(&v), cpu); diff --git a/tests/startup_address_srv_check.py b/tests/startup_address_srv_check.py index a5a6cc5c36..6ae9ed6ef7 100644 --- a/tests/startup_address_srv_check.py +++ b/tests/startup_address_srv_check.py @@ -9,7 +9,7 @@ from startup_stream_draw_check import gfx2hlsl, pixel, vertex -def prepare_draw_cache(directory, consumer, hlsl, modes, binding): +def prepare_draw_cache(directory, consumer, hlsl, modes, binding, *, vertex_hlsl=None): cache = directory / "cache" cache.mkdir() vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) @@ -20,19 +20,24 @@ def prepare_draw_cache(directory, consumer, hlsl, modes, binding): args = [consumer, vs, ps, root] subprocess.run(args, env=env, check=True) subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) - manifest, = cache.glob("*.txt") + manifest, = (path for path in cache.glob("*.txt") if path.name != "revision.txt") with manifest.open("a", encoding="ascii") as file: file.write(f"\n{binding}\n") source = manifest.with_suffix(".ps.hlsl") source.write_text(hlsl) subprocess.run([env["X2W_FXC"], "/nologo", "/T", "ps_5_0", "/E", "main", "/Fo", manifest.with_suffix(".ps.cso"), source], check=True) + if vertex_hlsl is not None: + source = manifest.with_suffix(".vs.hlsl") + source.write_text(vertex_hlsl, encoding="ascii") + subprocess.run([env["X2W_FXC"], "/nologo", "/T", "vs_5_0", "/E", "main", "/Fo", + manifest.with_suffix(".vs.cso"), source], check=True) return env, args, output -def draw_texture(directory, consumer, backend, hlsl, modes, view_kind="tex2d", *, binding=None): +def draw_texture(directory, consumer, backend, hlsl, modes, view_kind="tex2d", *, binding=None, vertex_hlsl=None): binding = binding or f"srv 0 {view_kind} table 0 0" - env, args, output = prepare_draw_cache(directory, consumer, hlsl, modes, binding) + env, args, output = prepare_draw_cache(directory, consumer, hlsl, modes, binding, vertex_hlsl=vertex_hlsl) result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) print(result.stdout, end="") if result.returncode == 77: @@ -54,9 +59,9 @@ def check_refusal_lines(log): # zero address, wrong width, interior address, buffer view, destination off the heap prefix + r"unsupported memory SRV arguments: reason=null_address " + R8_RESOURCE % 2 + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address=0x0 address_readable=0", - prefix + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + R8_RESOURCE % 1 + prefix + r"unavailable texture at the supplied base and layout: reason=texture_no_resource " + R8_RESOURCE % 1 + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", - prefix + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + R8_RESOURCE % 2 + prefix + r"unavailable texture at the supplied base and layout: reason=texture_no_resource " + R8_RESOURCE % 2 + " " + R8_VIEW + rf" dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", prefix + r"unavailable buffer at the supplied address: reason=buffer_unavailable " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " diff --git a/tests/startup_address_volume_srv_check.py b/tests/startup_address_volume_srv_check.py index c83b6d5ba8..de35461e5e 100644 --- a/tests/startup_address_volume_srv_check.py +++ b/tests/startup_address_volume_srv_check.py @@ -22,7 +22,7 @@ def check_refusal_lines(log): + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", # 2. Short backing / unregistered address prefix - + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + + r"unavailable texture at the supplied base and layout: reason=texture_(?:no_resource|unreadable) " + res_base + r" view\{dim=8 fmt=28 map=0x1688 mostmip=1 mips=1 clamp=0\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", @@ -38,9 +38,10 @@ def check_refusal_lines(log): + res_base + r" view\{dim=8 fmt=28 map=0x1688 mostmip=1 mips=1 clamp=1\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", - # 5. Wrong layout (0x105) + # 5. A console layout (0x105) over the live desktop-layout volume: the description is one slot 70 + # reads by address, but the address is inside a live resource. prefix - + r"unsupported memory SRV arguments: reason=unsupported_description " + + r"unavailable texture at the supplied base and layout: reason=overlapping_resource " + res_swizzle + r" view\{dim=8 fmt=28 map=0x1688 mostmip=1 mips=1 clamp=0\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", diff --git a/tests/startup_audio_output.cpp b/tests/startup_audio_output.cpp index d95dc1953d..bdb8af0554 100644 --- a/tests/startup_audio_output.cpp +++ b/tests/startup_audio_output.cpp @@ -24,11 +24,12 @@ int fail(const char* what, int code) void print_report(const char* name, const Report& r) { - std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " - "unsupported=%u rejected_full=%u padding_errors=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", - name, static_cast<long long>(r.first_block), r.frames.size(), static_cast<unsigned long long>(r.submitted_frames), - static_cast<unsigned long long>(r.consumed_frames), static_cast<unsigned long long>(r.clock_frames), - r.unsupported, r.rejected_full, r.padding_errors, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); + std::printf("%s: first_block=%lld submitted_blocks=%zu accepted=%llu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " + "unsupported=%u rejected_full=%u not_open=%u padding_errors=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", + name, static_cast<long long>(r.first_block), r.frames.size(), static_cast<unsigned long long>(r.accepted), + static_cast<unsigned long long>(r.submitted_frames), static_cast<unsigned long long>(r.consumed_frames), + static_cast<unsigned long long>(r.clock_frames), r.unsupported, r.rejected_full, r.not_open, + r.padding_errors, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); } // Polls until done() holds or ms elapse; every wait in this fixture goes through here. @@ -87,7 +88,7 @@ int run() wait_for(a, 300, [] { return false; }); const Report ra = a.report(); print_report("case a (no submission)", ra); - if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0) + if (ra.first_block != -1 || !ra.frames.empty() || ra.accepted != 0 || ra.submitted_frames != 0 || ra.consumed_frames != 0) return fail("case a reported accepted or consumed frames without a submission", 1); // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros. @@ -104,7 +105,7 @@ int run() wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; }); const Report rb = b.report(); print_report("case b (continuous with silence)", rb); - if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); + if (rb.first_block != 0 || rb.frames.size() != 8 || rb.accepted != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3); if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4); if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5); @@ -128,6 +129,7 @@ int run() wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; }); const Report rc = c.report(); print_report("case c (starvation)", rc); + if (rc.accepted != 3) return fail("case c accepted block count", 9); if (rc.drained_ms < 250) return fail("case c drained interval too short", 9); if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10); if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10); @@ -148,7 +150,7 @@ int run() if (d.submit(ch6_44, 441, blk6.data()) != Submit::Accepted) return fail("case d 5.1 44.1 kHz block not accepted", 13); const Report rd = d.report(); - if (rd.unsupported != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || + if (rd.unsupported != 1 || rd.accepted != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || rd.submitted_frames > resampled_frame_count(441, 44100, mix.rate)) return fail("case d report counts mismatch", 14); } diff --git a/tests/startup_audio_timeline_cli_check.py b/tests/startup_audio_timeline_cli_check.py index 18fe157a00..f6bba434db 100644 --- a/tests/startup_audio_timeline_cli_check.py +++ b/tests/startup_audio_timeline_cli_check.py @@ -239,9 +239,9 @@ def test_csv_error_and_non_utf8_inputs_exit_2_without_traceback(self) -> None: valid_jsonl.write_bytes(_jsonl_bytes([{"action": "a", "qpc": 100.0}])) flags = ["--process-origin-qpc", "100", "--action", "a"] - nul_csv = root / "nul.csv" + nul_csv = root / "nul_byte.csv" nul_csv.write_bytes(b"process_s,frames,rms,peak,flags\n0.0,4800,\x000.1,0.2,0\n") - self._assert_exit_2([str(nul_csv), str(valid_jsonl), *flags], expected_fragment="nul.csv:2:") + self._assert_exit_2([str(nul_csv), str(valid_jsonl), *flags], expected_fragment="nul_byte.csv:2:") # Field larger than csv.field_size_limit() triggers real csv.Error in both in-process & subprocess. oversized_csv = root / "oversized.csv" diff --git a/tests/startup_buffer_format_word3_check.cpp b/tests/startup_buffer_format_word3_check.cpp index 8df22b7b4e..5e245ecd97 100644 --- a/tests/startup_buffer_format_word3_check.cpp +++ b/tests/startup_buffer_format_word3_check.cpp @@ -45,6 +45,8 @@ int main(int argc, char** argv) std::uint32_t word = 0; check("float4 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R32G32B32A32_FLOAT), word) && word == (77u << 12 | identity)); + check("R10G10B10A2 unorm identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R10G10B10A2_UNORM), word) && + word == (50u << 12 | identity)); check("half2 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R16G16_FLOAT), word) && word == (29u << 12 | identity)); check("snorm2 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R16G16_SNORM), word) && word == (24u << 12 | identity)); check("uint8 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R8_UINT), word) && word == (5u << 12 | identity)); @@ -59,7 +61,7 @@ int main(int argc, char** argv) const DXGI_FORMAT decoded[] = {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, - DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R8G8B8A8_UINT}; + DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R10G10B10A2_UNORM}; for (DXGI_FORMAT f : decoded) { const std::uint32_t code = x2w_startup::buffer_format_code(f); if (!code || !x2w_startup::formatted_buffer_supported(code)) { diff --git a/tests/startup_buffer_format_word3_table_check.py b/tests/startup_buffer_format_word3_table_check.py index c89621218f..9099c99dc4 100644 --- a/tests/startup_buffer_format_word3_table_check.py +++ b/tests/startup_buffer_format_word3_table_check.py @@ -15,7 +15,7 @@ # Public DXGI_FORMAT values (dxgiformat.h) for the names the header uses. DXGI = {'R32G32B32A32_FLOAT': 2, 'R32G32B32_FLOAT': 6, 'R16G16B16A16_FLOAT': 10, 'R32G32_FLOAT': 16, - 'R8G8B8A8_UNORM': 28, 'R16G16_FLOAT': 34, 'R16G16_UNORM': 35, 'R16G16_UINT': 36, 'R16G16_SNORM': 37, 'R8G8B8A8_UINT': 30, 'R32_FLOAT': 41, + 'R8G8B8A8_UNORM': 28, 'R10G10B10A2_UNORM': 24, 'R16G16_FLOAT': 34, 'R16G16_UNORM': 35, 'R16G16_UINT': 36, 'R16G16_SNORM': 37, 'R8G8B8A8_UINT': 30, 'R32_FLOAT': 41, 'R8G8_UNORM': 49, 'R8_UNORM': 61, 'R8_UINT': 62} # The buffer format each DXGI format reads as: FETCH_DXGI, plus the three formats it does not list. EXPECTED = {**{dxgi: name for dxgi, (name, _) in gfx2hlsl.FETCH_DXGI.items()}, diff --git a/tests/startup_builder_gate.hlsl b/tests/startup_builder_gate.hlsl new file mode 100644 index 0000000000..f27724aa74 --- /dev/null +++ b/tests/startup_builder_gate.hlsl @@ -0,0 +1,2 @@ +[numthreads(1, 1, 1)] +void main() {} diff --git a/tests/startup_builder_module.cpp b/tests/startup_builder_module.cpp new file mode 100644 index 0000000000..c73c2abc79 --- /dev/null +++ b/tests/startup_builder_module.cpp @@ -0,0 +1,13 @@ +#include <d3d12.h> + +// A source-built module whose basename matches the console BVH builder. The gate resolves the +// caller of device slot 62; a call through this export must be tagged as a builder pipeline. +extern "C" __declspec(dllexport) HRESULT WINAPI CreateBuilderPipeline( + IUnknown* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID iid, void** out) +{ + if (!device || !desc || !out) return E_POINTER; + using Slot62 = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT, + const void*, REFIID, void**); + const auto fn = reinterpret_cast<Slot62>((*reinterpret_cast<void***>(device))[62]); + return fn(device, desc, 0, nullptr, iid, out); +} diff --git a/tests/startup_command_list_slot_names.cpp b/tests/startup_command_list_slot_names.cpp index a7e0602440..20d2e586cb 100644 --- a/tests/startup_command_list_slot_names.cpp +++ b/tests/startup_command_list_slot_names.cpp @@ -53,7 +53,7 @@ int main() {50, "OMSetRenderTargets"}, {52, "ClearRenderTargetView"}, {61, "ExecuteIndirect"}, - {139, "Reset"}, + {139, "Reset (console)"}, }; for (const auto& entry : handled) expect(is(entry.first, entry.second), "slot " + std::to_string(entry.first) + " is " + entry.second); @@ -61,12 +61,16 @@ int main() const std::vector<std::pair<int, const char*>> between = { {0, "QueryInterface"}, {1, "AddRef"}, {2, "Release"}, {3, "GetPrivateData"}, {4, "SetPrivateData"}, {5, "SetPrivateDataInterface"}, {6, "SetName"}, {8, "GetType"}, + {10, "Reset"}, {11, "ClearState"}, {14, "Dispatch"}, {15, "CopyBufferRegion"}, {16, "CopyTextureRegion"}, {17, "CopyResource"}, {18, "CopyTiles"}, {19, "ResolveSubresource"}, {24, "OMSetStencilRef"}, + {27, "ExecuteBundle"}, + {28, "BeginQuery"}, {29, "EndQuery"}, {30, "ResolveQueryData"}, {31, "SetPredication"}, + {56, "SetMarker"}, {57, "BeginEvent"}, {58, "EndEvent"}, }; for (const auto& entry : between) expect(is(entry.first, entry.second), "slot " + std::to_string(entry.first) + " is " + entry.second); - // From SetDescriptorHeaps on the console slot is the desktop slot plus four: 28 desktop methods in a row. + // From SetDescriptorHeaps through DiscardResource the console slot is the desktop slot plus four. const std::vector<const char*> shifted = { "SetDescriptorHeaps", "SetComputeRootSignature", "SetGraphicsRootSignature", "SetComputeRootDescriptorTable", "SetGraphicsRootDescriptorTable", "SetComputeRoot32BitConstant", "SetGraphicsRoot32BitConstant", @@ -74,19 +78,21 @@ int main() "SetGraphicsRootConstantBufferView", "SetComputeRootShaderResourceView", "SetGraphicsRootShaderResourceView", "SetComputeRootUnorderedAccessView", "SetGraphicsRootUnorderedAccessView", "IASetIndexBuffer", "IASetVertexBuffers", "SOSetTargets", "OMSetRenderTargets", "ClearDepthStencilView", "ClearRenderTargetView", - "ClearUnorderedAccessViewUint", "ClearUnorderedAccessViewFloat", "DiscardResource", "BeginQuery", "EndQuery", - "ResolveQueryData", "SetPredication"}; - expect(shifted.size() == 28, "the shifted run has 28 methods"); + "ClearUnorderedAccessViewUint", "ClearUnorderedAccessViewFloat", "DiscardResource"}; + expect(shifted.size() == 24, "the shifted run has 24 methods"); for (std::size_t i = 0; i < shifted.size(); ++i) expect(is(32 + static_cast<int>(i), shifted[i]), "slot " + std::to_string(32 + i) + " is " + shifted[i]); - // The run ends at 59 with the desktop slot 55; the desktop methods after it (56 to 59, plus four) are not named. - expect(is(59, "SetPredication"), "slot 59 is the desktop slot 55 plus four"); + // The run ends at 55 with DiscardResource; 56 to 58 keep the desktop marker names. + expect(is(55, "DiscardResource"), "slot 55 is the desktop slot 51 plus four"); + expect(is(56, "SetMarker"), "slot 56 is SetMarker"); + expect(is(57, "BeginEvent"), "slot 57 is BeginEvent"); + expect(is(58, "EndEvent"), "slot 58 is EndEvent"); // Slots that are not known stay unnamed: a name there would be a guess. - // 10 and 11: this console list resets through 139. 27 to 31: the remaining unconfirmed methods before the shift. - // Other slots from 60 up have unconfirmed meanings. -1 and 4096: outside the table. - std::vector<int> unknown = {10, 11, 27, 28, 29, 30, 31, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, - 131, 132, 138, 140, 142, 146, 255, 256, 999, 4096, -1, -100}; + // 59 and 60 are console-only markers; 62 and up are console-only methods not named in this table. + // 148 is the console allocation method and stays unnamed. -1 and 4096: outside the table. + std::vector<int> unknown = {59, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, + 131, 132, 138, 140, 142, 146, 147, 148, 149, 255, 256, 999, 4096, -1, -100}; for (const int slot : unknown) expect(x2w_list_slots::name(slot) == nullptr, "slot " + std::to_string(slot) + " has no name"); // Names are unique within the table and never empty, so a log line says which method it was. @@ -98,7 +104,7 @@ int main() for (const std::string& earlier : seen) expect(earlier != got, std::string("the name ") + got + " is used once"); seen.push_back(got); } - expect(seen.size() == 10 + 15 + 28 + 2, "the named slots are 0 to 9, 12 to 26, 32 to 59, 61 and 139"); + expect(seen.size() == 61, "the named slots are 0 to 58, 61 and 139"); if (failures) { std::fprintf(stderr, "%d check(s) failed\n", failures); diff --git a/tests/startup_commit_state_check.cpp b/tests/startup_commit_state_check.cpp new file mode 100644 index 0000000000..4593d5dc23 --- /dev/null +++ b/tests/startup_commit_state_check.cpp @@ -0,0 +1,107 @@ +// Check src/startup_stubs/commit_state.h: the text of the x2w-budget commit fields and of the commit-exhausted line, +// which commit errors count, and that the system commit this machine reports is consistent. +#include "startup_stubs/commit_state.h" + +#include <cstdio> +#include <cstring> + +namespace { +int failures = 0; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL %s\n", what); + ++failures; + } +} + +void expect_text(const char* got, const char* want, const char* what) +{ + if (std::strcmp(got, want) != 0) { + std::printf("FAIL %s: got [%s] want [%s]\n", what, got, want); + ++failures; + } +} +} // namespace + +int main() +{ + using namespace x2w_local; + char text[400]; + + SystemCommit known; + known.known = true; + known.used_mib = 14335; + known.limit_mib = 16100; + known.avail_mib = 1765; + format_commit(text, sizeof(text), known); + expect_text(text, "commit=14335/16100 avail=1765", "known commit text"); + format_commit(text, sizeof(text), SystemCommit{}); + expect_text(text, "commit=n/a avail=n/a", "unknown commit text"); + + JobMemory capped; // a 14 GiB job whose peak is at its limit + capped.known = capped.limited = true; + capped.limit_mib = 14336; + capped.peak_mib = 14250; + JobMemory roomy = capped; // the same job with a gigabyte to spare + roomy.peak_mib = 13000; + JobMemory unlimited; + unlimited.known = true; + unlimited.peak_mib = 900; + format_job(text, sizeof(text), capped); + expect_text(text, "job_peak=14250 job_limit=14336", "limited job text"); + format_job(text, sizeof(text), unlimited); + expect_text(text, "job_peak=900 job_limit=none", "unlimited job text"); + format_job(text, sizeof(text), JobMemory{}); + expect_text(text, "job_peak=n/a job_limit=n/a", "no job text"); + expect(job_limit_reached(capped) && !job_limit_reached(roomy) && !job_limit_reached(unlimited) && + !job_limit_reached(JobMemory{}), + "the job limit is the cause only for a limited job near its limit"); + + format_exhausted(text, sizeof(text), "XMemMapPhysicalPagesScatter", 1455, known, capped, 113609, 3, 113000, 609); + expect_text(text, + "x2w-xmem commit exhausted at XMemMapPhysicalPagesScatter (error 1455): job memory limit 14 GiB reached " + "(run.ps1 -MemoryGiB); job_peak=14250 job_limit=14336; system commit=14335/16100 avail=1765; " + "pool sections=113609 slabs=3 slots=113000/609; " + "X2W_XMEM_LAZY_COMMIT=1 (run.ps1 -LazyMemory) keeps untouched pages out of the commit", + "exhausted line, job limit reached"); + format_exhausted(text, sizeof(text), "XMemMapPhysicalPagesScatter", 1455, known, roomy, 113609, 3, 113000, 609); + expect(std::strstr(text, ": job memory limit not reached; job_peak=13000 job_limit=14336; system commit=14335/16100") != nullptr, + "exhausted line, system commit is the cause"); + + // A real job: the process joins one with a 4 GiB memory limit and job_memory() reads it back. (Skipped when the + // machine does not let this process join another job.) + HANDLE job = CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; + info.JobMemoryLimit = static_cast<SIZE_T>(4096) << 20; + if (job && SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)) && + AssignProcessToJobObject(job, GetCurrentProcess())) { + const JobMemory read = job_memory(); + // Wine accepts the limit but does not store it: only Windows must read it back. + const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; + if (wine) { + std::printf("note: Wine does not keep JobMemoryLimit, real-job case skipped\n"); + } else { + expect(read.known && read.limited && read.limit_mib == 4096 && read.peak_mib < 4096, "a real job is read back"); + expect(!job_limit_reached(read), "a fresh process is far from a 4 GiB job limit"); + } + } else { + std::printf("note: could not join a test job (error %lu), real-job case skipped\n", GetLastError()); + } + + expect(is_commit_failure(1455) && is_commit_failure(8), "commit limit and not enough memory count"); + expect(!is_commit_failure(0) && !is_commit_failure(87) && !is_commit_failure(5) && !is_commit_failure(487), + "other errors do not"); + + const SystemCommit now = system_commit(); + expect(now.known, "this machine reports its commit"); + expect(now.limit_mib > 0 && now.used_mib > 0 && now.used_mib <= now.limit_mib && now.avail_mib <= now.limit_mib, + "commit numbers are within the limit"); + expect(now.used_mib + now.avail_mib + 1 >= now.limit_mib && now.used_mib + now.avail_mib <= now.limit_mib + 1, + "used plus available is the limit (to a MiB)"); + + std::printf("startup_commit_state: %s\n", failures ? "FAIL" : "PASS"); + return failures ? 1 : 0; +} diff --git a/tests/startup_committed_slot76_check.cpp b/tests/startup_committed_slot76_check.cpp new file mode 100644 index 0000000000..284d472b29 --- /dev/null +++ b/tests/startup_committed_slot76_check.cpp @@ -0,0 +1,116 @@ +// Device check for committed resources made through the startup device wrapper's slot 76 (Xbox +// order, +0x260): the seven arguments of desktop CreateCommittedResource (heap properties, heap +// flags, desc, initial state, clear value, riid, ppv). It shares the desktop creation of slot 127 +// (tests/startup_committed_heap_state_check.cpp). A 2D render target with a clear value and buffers on +// the default, upload and readback heaps, passed as a title passes them (initial state 0xffffffff), +// must all be created and the device must stay alive. +// usage: startup_committed_slot76_check warp|hardware [--control] +// --control also requires a 2D upload-heap texture to return E_INVALIDARG with no output resource. +#include "xmem_test_device.h" + +#include <cstdio> +#include <cstring> + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +HRESULT create_wrapper(IUnknown* adapter, REFIID iid, void** out) +{ + unsigned char parameters[64]{}; + return D3D12XboxCreateDevice(adapter, parameters, iid, out); +} + +using Committed76 = HRESULT (*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, + const D3D12_CLEAR_VALUE*, const GUID*, void**); +constexpr UINT state_undefined = 0xffffffff; + +Committed76 slot76(ID3D12Device* device) +{ + return reinterpret_cast<Committed76>((*reinterpret_cast<void***>(device))[76]); +} + +D3D12_RESOURCE_DESC buffer(UINT64 bytes) +{ + 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; + return desc; +} + +D3D12_RESOURCE_DESC texture(UINT width, UINT height, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +const char* heap_name(D3D12_HEAP_TYPE type) +{ + return type == D3D12_HEAP_TYPE_DEFAULT ? "default" : type == D3D12_HEAP_TYPE_UPLOAD ? "upload" : "readback"; +} + +// Returns 0 only when the requested creation or rejection is observed and the device stays alive. +int check(ID3D12Device* wrapper, D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, + const D3D12_CLEAR_VALUE* clear = nullptr, bool reject = false) +{ + const D3D12_HEAP_PROPERTIES props{type}; + const GUID iid = __uuidof(ID3D12Resource); + void* created = nullptr; + const HRESULT hr = slot76(wrapper)(wrapper, &props, 0, &desc, state_undefined, clear, &iid, &created); + const HRESULT removed = wrapper->GetDeviceRemovedReason(); + const char* what = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? "buffer" : "2D texture"; + std::printf("%s heap, %s of 0x%llx%s: slot 76 -> 0x%08lx\n", heap_name(type), what, + static_cast<unsigned long long>(desc.Width), clear ? " with clear value" : "", static_cast<unsigned long>(hr)); + const bool expected = reject ? hr == E_INVALIDARG && !created : SUCCEEDED(hr) && created; + const int result = expected && SUCCEEDED(removed) ? 0 : 1; + if (reject && !result) std::puts("slot 76 rejected the upload-heap texture with E_INVALIDARG and no resource"); + if (result) + std::printf("FAIL: %s heap %s: hr 0x%08lx object %p device 0x%08lx\n", heap_name(type), what, static_cast<unsigned long>(hr), + created, static_cast<unsigned long>(removed)); + if (created) static_cast<IUnknown*>(created)->Release(); + return result; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2 && !(argc == 3 && std::strcmp(argv[2], "--control") == 0)) return 1; + const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool control = argc == 3; + bool unmatched = false; + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + auto wrapper = create_device(warp, unmatched, create_wrapper); + if (!wrapper) { + if (warp || unmatched) { + std::puts("FAIL: no wrapped device"); + return 1; + } + return 77; + } + int failures = 0; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_DEFAULT, texture(128, 64, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), &clear); + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_DEFAULT, buffer(0x10000)); + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_UPLOAD, buffer(0x10000)); + failures += check(wrapper.Get(), D3D12_HEAP_TYPE_READBACK, buffer(768)); + if (control) failures += check(wrapper.Get(), D3D12_HEAP_TYPE_UPLOAD, texture(64, 64), nullptr, true); + if (failures) { + std::printf("startup_committed_slot76: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_committed_slot76: PASS (render target, default, upload and readback resources created through slot 76)"); + return 0; +} diff --git a/tests/startup_compile_lds_request_cli_check.py b/tests/startup_compile_lds_request_cli_check.py new file mode 100644 index 0000000000..903874b91e --- /dev/null +++ b/tests/startup_compile_lds_request_cli_check.py @@ -0,0 +1,709 @@ +#!/usr/bin/env python3 +"""Offline unit, CLI, warm-reuse, path-guard, and mutation suite for tools/startup/compile_lds_request.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import re +import runpy +import struct +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock +import warnings + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_STARTUP = ROOT / "tools" / "startup" +TESTS_DIR = ROOT / "tests" +TOOL = TOOLS_STARTUP / "compile_lds_request.py" +sys.path.insert(0, str(TOOLS_STARTUP)) +sys.path.insert(0, str(TESTS_DIR)) +import compile_lds_request # noqa: E402 +from startup_compute_translate_check import state_a, write_request # noqa: E402 +from startup_gfx2hlsl_compute_check import CASES, USER7, TGID_X # noqa: E402 + +COMPANION_EXTS = (".root", ".data", ".desc", ".sa", ".sb") +_REAL_SUBPROCESS_RUN = subprocess.run + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with warnings.catch_warnings(), redirect_stdout(stdout), redirect_stderr(stderr): + warnings.simplefilter("ignore", ResourceWarning) + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return _REAL_SUBPROCESS_RUN( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _setup_env(base: Path) -> tuple[Path, Path, Path, Path]: + compiler = base / "fake_compile_dxil.exe" + compiler.write_bytes(b"FAKE_DXIL_COMPILER") + sdk = base / "sdk" + sdk.mkdir() + output = base / "output" + cache = base / "cache" + return compiler, sdk, output, cache + + +def _write_case_f(work: Path) -> tuple[int, Path]: + _, code, rsrc2, group, _ = CASES["F"] + key = write_request(work, code, state_a(group, rsrc2)) + return key, work / f"req_{key:016x}.c67" + + +def _fake_compile_dxil(calls: list[list[object]] | None = None, *, validate_paths: bool = True): + def _runner(cmd, check=False, **_kwargs): + assert check is True + if calls is not None: + calls.append(list(cmd)) + compiler, sdk, cache, profile, stage, bytecode = cmd + if validate_paths: + assert Path(compiler).is_file() + assert Path(sdk).is_dir() + assert profile == "cs_6_6" + assert Path(stage).is_file() + assert Path(cache).parent.exists() or not Path(cache).exists() + Path(bytecode).write_bytes(b"DXBC_SYNTHETIC_CSO") + return subprocess.CompletedProcess(cmd, 0) + + return _runner + + +class CompileLdsRequestPositiveTests(unittest.TestCase): + def test_synthetic_c67_compile_warm_reuse_and_damaged_bundle_detection(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + key, marker = _write_case_f(req_dir) + calls: list[list[object]] = [] + + argv = [ + str(marker), + str(output), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(cache), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil(calls)): + code, out, err = _run_main(compile_lds_request, argv) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(calls), 1) + dest = Path(out.strip()) + self.assertTrue(dest.is_dir()) + self.assertEqual(list(output.iterdir()), [dest]) + + hlsl = (dest / f"{key:016x}.cs.hlsl").read_text(encoding="utf-8") + self.assertIn("[WaveSize(32)]\n[numthreads(", hlsl) + self.assertIn("#pragma x2w_lds ", hlsl) + self.assertIn("#pragma x2w_vop2 ", hlsl) + self.assertIn("GroupMemoryBarrierWithGroupSync();", hlsl) + self.assertEqual((dest / f"{key:016x}.cs.cso").read_bytes(), b"DXBC_SYNTHETIC_CSO") + self.assertIn("group 64 1 1", (dest / f"{key:016x}.txt").read_text(encoding="utf-8").splitlines()) + + replay_raw = (dest / "replay.json").read_bytes() + replay = json.loads(replay_raw.decode("utf-8")) + self.assertEqual(replay["schema"], 1) + self.assertEqual(replay["profile"], "cs_6_6") + self.assertEqual(replay["rw_image"], [0, 0]) + self.assertEqual(replay["wave_size"], 32) + for rel, expected_sha in replay["sha256"].items(): + self.assertEqual(hashlib.sha256((dest / rel).read_bytes()).hexdigest(), expected_sha) + + # Warm reuse: identical inputs collide on dest, verify all sha256 entries, and succeed idempotently. + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil(calls)): + code_warm, out_warm, err_warm = _run_main(compile_lds_request, argv) + self.assertEqual(code_warm, 0, err_warm) + self.assertEqual(err_warm, "") + self.assertEqual(Path(out_warm.strip()), dest) + self.assertEqual(list(output.iterdir()), [dest]) + + # Damaged artifact sha256 detection: corrupting .cs.cso fails cleanly with no temp leftovers. + cso_path = dest / f"{key:016x}.cs.cso" + saved_cso = cso_path.read_bytes() + cso_path.write_bytes(b"CORRUPT_CSO") + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_dmg, out_dmg, err_dmg = _run_main(compile_lds_request, argv) + self.assertEqual(code_dmg, 1) + self.assertEqual(out_dmg, "") + self.assertNotIn("Traceback", err_dmg) + self.assertIn("damaged replay artifact", err_dmg) + self.assertEqual(list(output.iterdir()), [dest]) + cso_path.write_bytes(saved_cso) + + # Corrupting replay.json on disk also triggers refusal cleanly. + (dest / "replay.json").write_text("{corrupt}\n", encoding="utf-8") + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_rep, out_rep, err_rep = _run_main(compile_lds_request, argv) + self.assertEqual(code_rep, 1) + self.assertEqual(out_rep, "") + self.assertNotIn("Traceback", err_rep) + self.assertIn("damaged replay artifact replay.json", err_rep) + self.assertEqual(list(output.iterdir()), [dest]) + (dest / "replay.json").write_bytes(replay_raw) + + # Wave size 64 and argv=None sys.argv forwarding. + argv64 = argv[:-1] + ["64"] + with ( + mock.patch.object(sys, "argv", [str(TOOL), *argv64]), + mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()), + ): + code64, out64, err64 = _run_main(compile_lds_request, None) + self.assertEqual(code64, 0, err64) + self.assertEqual(err64, "") + dest64 = Path(out64.strip()) + self.assertNotEqual(dest64, dest) + self.assertIn("[WaveSize(64)]", (dest64 / f"{key:016x}.cs.hlsl").read_text(encoding="utf-8")) + self.assertEqual(sorted(output.iterdir()), sorted([dest, dest64])) + + +class CompileLdsRequestNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(compile_lds_request, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_companion_and_hostile_path_refusals(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, _, cache = _setup_env(base) + key, marker = _write_case_f(req_dir) + absent_out = base / "absent_parent" / "output" + file_target = base / "regular_file" + file_target.write_text("KEEP", encoding="utf-8") + dir_path = base / "some_dir" + dir_path.mkdir() + + def make_argv( + *, + m: Path = marker, + o: Path = absent_out, + comp: Path = compiler, + s: Path = sdk, + ca: Path = cache, + ) -> list[str]: + return [ + str(m), + str(o), + "--compiler", + str(comp), + "--sdk", + str(s), + "--cache", + str(ca), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + + with ( + mock.patch.object( + compile_lds_request.gfx, + "load_compute_request", + side_effect=AssertionError("load_compute_request called on invalid path"), + ), + mock.patch.object( + compile_lds_request.subprocess, + "run", + side_effect=AssertionError("subprocess.run called on invalid path"), + ), + ): + # Marker missing / dir / non-regular. + self._assert_clean_failure( + make_argv(m=req_dir / "req_0123456789abcdef.c67"), + fragments=("request marker", "not found"), + ) + self._assert_clean_failure( + make_argv(m=dir_path / "req_0123456789abcdef.c67"), + fragments=("request marker", "not found"), + ) + dir_marker = base / "req_0123456789abcdef.c67" + dir_marker.mkdir() + self._assert_clean_failure(make_argv(m=dir_marker), fragments=("request marker", "directory")) + + # Missing or directory companion files. + for ext in COMPANION_EXTS: + comp_file = marker.with_suffix(ext) + saved = comp_file.read_bytes() + comp_file.unlink() + self._assert_clean_failure(make_argv(), fragments=(f"companion {ext}", "not found")) + comp_file.mkdir() + self._assert_clean_failure(make_argv(), fragments=(f"companion {ext}", "directory")) + comp_file.rmdir() + comp_file.write_bytes(saved) + + # Compiler missing / dir / non-regular. + self._assert_clean_failure(make_argv(comp=base / "missing.exe"), fragments=("compiler", "not found")) + self._assert_clean_failure(make_argv(comp=dir_path), fragments=("compiler", "directory")) + + # SDK missing / file. + self._assert_clean_failure(make_argv(s=base / "missing_sdk"), fragments=("sdk", "not found")) + self._assert_clean_failure(make_argv(s=file_target), fragments=("sdk", "not a directory")) + + # Output / cache existing regular file or file-backed parent. + self._assert_clean_failure(make_argv(o=file_target), fragments=("output", "not a directory")) + self._assert_clean_failure( + make_argv(o=file_target / "sub"), + fragments=("output parent", "not a directory"), + ) + self._assert_clean_failure(make_argv(ca=file_target), fragments=("cache", "not a directory")) + self._assert_clean_failure( + make_argv(ca=file_target / "sub"), + fragments=("cache parent", "not a directory"), + ) + + # Non-regular file input (mocked unconditionally). + with mock.patch.object(Path, "is_file", return_value=False): + self._assert_clean_failure( + make_argv(), + fragments=("not a regular file",), + check_subprocess=False, + ) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual(file_target.read_text(encoding="utf-8"), "KEEP") + + # Symlinked output/cache are the caller's chosen location and now + # succeed: the bundle is written through the link into its target. + link_out = base / "link_out" + try: + link_out.symlink_to(dir_path) + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + else: + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_link, out_link, err_link = _run_main(compile_lds_request, make_argv(o=link_out)) + self.assertEqual(code_link, 0, err_link) + self.assertEqual(err_link, "") + dest_link = Path(out_link.strip()) + self.assertEqual(dest_link.resolve().parent, dir_path) + self.assertTrue((dest_link / f"{key:016x}.cs.hlsl").is_file()) + self.assertEqual(list(link_out.iterdir()), [dest_link]) + # The same bundle through a symlinked cache warm-reuses the + # bundle written above instead of refusing the link. + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_ca, out_ca, err_ca = _run_main(compile_lds_request, make_argv(o=dir_path, ca=link_out)) + self.assertEqual(code_ca, 0, err_ca) + self.assertEqual(err_ca, "") + self.assertEqual(Path(out_ca.strip()), dest_link.resolve()) + + def test_fifo_output_and_dangling_symlink_parent_refusals(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + _, marker = _write_case_f(req_dir) + + def make_argv(*, o: Path = output, ca: Path = cache) -> list[str]: + return [ + str(marker), + str(o), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(ca), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + + ran = False + # A FIFO is neither a file nor a directory: refused, not written through. + if hasattr(os, "mkfifo"): + fifo_out = base / "fifo_out" + os.mkfifo(fifo_out) + self._assert_clean_failure(make_argv(o=fifo_out), fragments=("output", "not a directory")) + ran = True + + # A dangling symlink as a parent is not a directory: refused, not followed. + dangling = base / "dangling" + try: + dangling.symlink_to(base / "no_such_target") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + else: + self._assert_clean_failure( + make_argv(o=dangling / "output"), + fragments=("output parent", "not a directory"), + ) + self._assert_clean_failure( + make_argv(ca=dangling / "cache"), + fragments=("cache parent", "not a directory"), + ) + ran = True + + if not ran: + self.skipTest("neither FIFOs nor symlinks are available on this platform") + + def test_translator_bug_keeps_traceback_and_out_of_range_branch_is_clean(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + + def make_argv(m: Path) -> list[str]: + return [ + str(m), + str(output), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(cache), + "--rw-image", + "0", + "0", + "--wave-size", + "32", + ] + + def write_modified_case(name: str, dword_index: int, value: int) -> Path: + _, code, rsrc2, group, _ = CASES[name] + words = list(struct.unpack(f"<{len(code) // 4}I", code)) + words[dword_index] = value + key = write_request(req_dir, struct.pack(f"<{len(words)}I", *words), state_a(group, rsrc2)) + return req_dir / f"req_{key:016x}.c67" + + # A translator bug (bad literal) must keep its traceback instead of + # being swallowed into a clean "error:" line. + bad_marker = write_modified_case("F", 4, 0xbf84C07F) + with self.assertRaises(ValueError) as raised: + _run_main(compile_lds_request, make_argv(bad_marker)) + self.assertIn("invalid literal for int()", str(raised.exception)) + proc = _run_subprocess(*make_argv(bad_marker)) + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(proc.stdout, "") + self.assertIn("Traceback", proc.stderr) + self.assertIn("invalid literal for int()", proc.stderr) + + # An out-of-range branch target is refused cleanly as unsupported. + branch_marker = write_modified_case("extracted-tid", 9, 0xbf852005) + self._assert_clean_failure( + make_argv(branch_marker), + fragments=("branch target", "outside the compute stage"), + ) + + def test_cli_arg_errors_key_mismatch_conditional_barrier_and_compiler_failure(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + _, marker = _write_case_f(req_dir) + + def make_argv(m: Path = marker, rw: tuple[str, str] = ("0", "0"), wave: str = "32") -> list[str]: + return [ + str(m), + str(output), + "--compiler", + str(compiler), + "--sdk", + str(sdk), + "--cache", + str(cache), + "--rw-image", + rw[0], + rw[1], + "--wave-size", + wave, + ] + + # Argparse / --rw-image / marker name errors exit 2 cleanly without tracebacks. + for argv, frags in ( + (make_argv(m=req_dir / "bad_marker.c67"), ("req_<16 hex digits>.c67",)), + (make_argv(rw=("-1", "0")), ("nonnegative",)), + (make_argv(rw=("0", "-32")), ("nonnegative",)), + (make_argv(rw=("0", "16")), ("32-byte-aligned",)), + (make_argv(wave="16"), ("invalid choice",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=2, fragments=frags) + + # Compiler nonzero exit (subprocess.CalledProcessError) cleans temp dir and exits 1. + def failing_run(cmd, check=False, **_kwargs): + raise subprocess.CalledProcessError(2, cmd) + + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=failing_run): + self._assert_clean_failure(make_argv(), expected_code=1, fragments=("returned non-zero exit status",), check_subprocess=False) + self.assertEqual(list(output.iterdir()), []) + + # Conditional s_barrier in synthetic .c67 request is rejected cleanly. + cond_dir = base / "cond" + cond_dir.mkdir() + # s_cbranch_scc0 1 (+4 bytes over s_barrier) ; s_barrier ; s_endpgm + cond_code = bytes.fromhex("010084bf" "00008abf" "000081bf") + cond_key = write_request(cond_dir, cond_code, state_a((64, 1, 1), USER7 | TGID_X | (1 << 15))) + cond_marker = cond_dir / f"req_{cond_key:016x}.c67" + with mock.patch.object( + compile_lds_request.subprocess, + "run", + side_effect=AssertionError("subprocess.run called for conditional barrier"), + ): + self._assert_clean_failure( + make_argv(m=cond_marker), + expected_code=1, + fragments=("workgroup barrier is conditional",), + ) + self.assertEqual(list(output.iterdir()), []) + + # Damaged .data bytes fail key verification with expected message and __main__ propagates SystemExit(1). + data_path = marker.with_suffix(".data") + data_path.write_bytes(bytes(b ^ 1 for b in data_path.read_bytes())) + self._assert_clean_failure(make_argv(), expected_code=1, fragments=("do not match the key",)) + self.assertEqual(list(output.iterdir()), []) + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), *make_argv()]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("do not match the key", stderr_m.getvalue()) + + def test_fast_self_mutation_controls(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + req_dir = base / "req" + req_dir.mkdir() + compiler, sdk, output, cache = _setup_env(base) + key, marker = _write_case_f(req_dir) + file_target = base / "regular_file" + file_target.write_text("KEEP", encoding="utf-8") + + cond_dir = base / "cond" + cond_dir.mkdir() + cond_code = bytes.fromhex("010084bf" "00008abf" "000081bf") + cond_key = write_request(cond_dir, cond_code, state_a((64, 1, 1), USER7 | TGID_X | (1 << 15))) + cond_marker = cond_dir / f"req_{cond_key:016x}.c67" + + def argv_for(m=marker, o=output, comp=compiler, s=sdk, ca=cache, rw=("0", "0")): + return [ + str(m), str(o), + "--compiler", str(comp), + "--sdk", str(s), + "--cache", str(ca), + "--rw-image", rw[0], rw[1], + "--wave-size", "32", + ] + + # Build one valid bundle so drop_bundle_sha256_check can probe damaged artifact detection. + with mock.patch.object(compile_lds_request.subprocess, "run", side_effect=_fake_compile_dxil()): + code_init, out_init, err_init = _run_main(compile_lds_request, argv_for()) + self.assertEqual(code_init, 0, err_init) + dest = Path(out_init.strip()) + cso_path = dest / f"{key:016x}.cs.cso" + saved_cso = cso_path.read_bytes() + + def check_drop_marker_guard(mod): + # Dropping the guard no longer refuses the missing marker + # cleanly: the tool either reaches the copy and crashes on the + # missing file, or reports a different error. Either way the + # guard's refusal is gone, which is what this control detects. + try: + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + _, _, err = _run_main(mod, argv_for(m=req_dir / "req_0123456789abcdef.c67")) + except Exception: + return + self.assertNotIn("request marker file not found", err.lower()) + + def check_drop_companion_guard(mod): + root_file = marker.with_suffix(".root") + saved = root_file.read_bytes() + root_file.unlink() + try: + try: + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + _, _, err = _run_main(mod, argv_for()) + except Exception: + return + self.assertNotIn("companion .root file not found", err.lower()) + finally: + root_file.write_bytes(saved) + + def check_drop_compiler_guard(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil(validate_paths=False)): + _, _, err = _run_main(mod, argv_for(comp=base / "missing.exe")) + self.assertNotIn("compiler file not found", err.lower()) + + def check_drop_sdk_guard(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil(validate_paths=False)): + _, _, err = _run_main(mod, argv_for(s=base / "missing_sdk")) + self.assertNotIn("sdk directory not found", err.lower()) + + def check_drop_rw_image_guard(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + code, _, err = _run_main(mod, argv_for(rw=("-1", "0"))) + self.assertEqual(code, 0, err) + self.assertNotIn("nonnegative", err.lower()) + + def check_drop_bundle_sha256(mod): + cso_path.write_bytes(b"DAMAGED") + try: + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + code, _, err = _run_main(mod, argv_for()) + self.assertEqual(code, 0, err) + finally: + cso_path.write_bytes(saved_cso) + + def check_drop_conditional_barrier(mod): + with mock.patch.object(mod.subprocess, "run", side_effect=_fake_compile_dxil()): + code, _, err = _run_main(mod, argv_for(m=cond_marker)) + self.assertNotIn("workgroup barrier is conditional", err.lower()) + self.assertEqual(code, 0, err) + + # Mutation targets are regular expressions, not exact source lines: + # they pin the distinctive structure (call, guard, loop) without + # depending on quote style, exception type or message wording, so + # a reword or requote of a guard does not silently unpin the control. + mutations = ( + ( + "drop_marker_guard", + r" _validate_regular_file\(args\.marker, [^\n]*\)\n", + " pass\n", + check_drop_marker_guard, + ), + ( + "drop_companion_guard", + r" for ext in \([^\n]*\):\n" + r" _validate_regular_file\(args\.marker\.with_suffix\(ext\), [^\n]*\)\n", + " pass\n", + check_drop_companion_guard, + ), + ( + "drop_compiler_guard", + r" _validate_regular_file\(args\.compiler, [^\n]*\)\n", + " pass\n", + check_drop_compiler_guard, + ), + ( + "drop_sdk_guard", + r" if not args\.sdk\.exists\(\):\n" + r" raise [^\n]*\n" + r" if not args\.sdk\.is_dir\(\):\n" + r" raise [^\n]*\n", + " pass\n", + check_drop_sdk_guard, + ), + ( + "drop_rw_image_guard", + r" if param < 0 or off < 0 or off ?% ?32:\n" + r" parser\.error\([^\n]*\)\n", + " pass\n", + check_drop_rw_image_guard, + ), + ( + "drop_bundle_sha256", + r" for relative, digest in metadata\[['\"]sha256['\"]\]\.items\(\):\n" + r" try:\n" + r" data = \(dest / relative\)\.read_bytes\(\)\n" + r" except OSError:\n" + r" raise [^\n]*\n" + r" if hashlib\.sha256\(data\)\.hexdigest\(\) != digest:\n" + r" raise [^\n]*\n", + " pass\n", + check_drop_bundle_sha256, + ), + ( + "drop_conditional_barrier", + r" if i not in post\[0\]:\n" + r" raise [^\n]*\n", + " pass\n", + check_drop_conditional_barrier, + ), + ) + for label, pattern, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(len(re.findall(pattern, source)), 1, f"target not unique for {label}") + mod = types.ModuleType(f"compile_lds_request_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(re.sub(pattern, replacement, source, count=1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/startup_compute_builder_gate_check.cpp b/tests/startup_compute_builder_gate_check.cpp new file mode 100644 index 0000000000..8c1b35ea07 --- /dev/null +++ b/tests/startup_compute_builder_gate_check.cpp @@ -0,0 +1,111 @@ +// Checks src/startup_stubs/compute_builder_gate.h without a device or a title module: when the +// opt-in console BVH builder gate allows a Dispatch, when it refuses a partial builder, and when a +// failed on-the-spot creation latches it off. Expectations are written out below, not computed with +// the header. +#include "startup_stubs/compute_builder_gate.h" + +#include <cstdio> +#include <cstring> + +namespace { +using x2w_startup::BuilderGateDecision; +using x2w_startup::BuilderGateState; + +int failures, cases; + +void expect(bool condition, const char* label) +{ + ++cases; + if (condition) return; + ++failures; + std::printf("FAIL %s\n", label); +} + +void expect_decision(BuilderGateState& gate, bool builder_dispatch, BuilderGateDecision expected, const char* label) +{ + std::printf("case %s\n", label); + const BuilderGateDecision got = gate.decide(builder_dispatch); + ++cases; + if (got == expected) return; + ++failures; + std::printf("FAIL %s: expected '%s', got '%s'\n", label, x2w_startup::builder_gate_reason(expected), + x2w_startup::builder_gate_reason(got)); +} +} // namespace + +int main() +{ + using x2w_startup::is_compute_builder_module; + + expect(is_compute_builder_module(L"XboxBvhBuilder.dll"), "bare module name"); + expect(is_compute_builder_module(L"xboxbvHBuilder.DLL"), "case-insensitive module name"); + expect(is_compute_builder_module(L"C:\\Games\\XboxBvhBuilder.dll"), "backslash path"); + expect(is_compute_builder_module(L"C:/Games/XboxBvhBuilder.dll"), "forward-slash path"); + expect(!is_compute_builder_module(L"C:\\Games\\XboxBvhBuilderExtra.dll"), "extra suffix is not the builder"); + expect(!is_compute_builder_module(L"C:\\Games\\NotXboxBvhBuilder.dll"), "prefix is not the builder"); + expect(!is_compute_builder_module(L"C:\\Games\\XboxBvhBuilder.dll.bak"), "backup suffix is not the builder"); + expect(!is_compute_builder_module(L""), "empty path"); + expect(!is_compute_builder_module(L"C:\\Games\\"), "directory path"); + expect(!is_compute_builder_module(L"C:\\Games\\XboxBvhBuilder.dll\\"), "trailing slash has no basename"); + + char slots[BuilderGateState::max_pipelines + 1]{}; + + // Off by default: tracking is a no-op and the existing path is unchanged even with a missing set. + BuilderGateState disabled(false); + expect(disabled.note_pipeline(&slots[0], true, false), "disabled gate accepts a note"); + expect(disabled.tracked() == 0, "disabled gate tracks nothing"); + expect_decision(disabled, true, BuilderGateDecision::unchanged, "gate off leaves a builder Dispatch unchanged"); + expect_decision(disabled, false, BuilderGateDecision::unchanged, "gate off leaves a non-builder Dispatch unchanged"); + + // Every tracked builder pipeline present: the all-or-none set is allowed. + BuilderGateState gate(true); + expect(gate.note_pipeline(&slots[0], true, true), "track a real builder pipeline"); + expect(gate.note_pipeline(&slots[1], true, true), "track a second real builder pipeline"); + expect(gate.tracked() == 2 && gate.with_pso() == 2, "two builder pipelines with PSOs"); + expect_decision(gate, true, BuilderGateDecision::allow, "all builder pipelines have a PSO"); + expect_decision(gate, false, BuilderGateDecision::unchanged, "a non-builder Dispatch is unchanged"); + + // A non-builder pipeline never joins the tracked set and never blocks the builder. + expect(gate.note_pipeline(&slots[2], false, false), "ignore a non-builder pipeline"); + expect(gate.tracked() == 2 && gate.with_pso() == 2, "non-builder pipeline is not tracked"); + expect_decision(gate, true, BuilderGateDecision::allow, "non-builder pipeline leaves the builder allowed"); + + // One tracked builder pipeline without a PSO: refuse until the on-the-spot attempt fills it. + expect(gate.note_pipeline(&slots[3], true, false), "track a placeholder builder pipeline"); + expect(gate.tracked() == 3 && gate.with_pso() == 2, "one builder pipeline is missing its PSO"); + expect_decision(gate, true, BuilderGateDecision::refuse_missing, "one missing builder pipeline is refused"); + gate.note_pso(&slots[3]); + expect(gate.with_pso() == 3, "the created PSO joins the tracked set"); + expect_decision(gate, true, BuilderGateDecision::allow, "the completed builder set is allowed"); + + // A repeated creation updates the entry instead of duplicating it. + expect(gate.note_pipeline(&slots[3], true, true), "repeat an existing builder pipeline"); + expect(gate.tracked() == 3 && gate.with_pso() == 3, "the repeated pointer does not add an entry"); + + // One failed on-the-spot creation latches the builder off for the rest of the run. + BuilderGateState failed(true); + expect(failed.note_pipeline(&slots[0], true, true), "failed set: first pipeline"); + expect(failed.note_pipeline(&slots[1], true, false), "failed set: second pipeline is missing"); + expect_decision(failed, true, BuilderGateDecision::refuse_missing, "failed set starts refused"); + failed.note_failed("desktop pipeline creation failed"); + expect(failed.off(), "a failed creation latches the gate off"); + expect(std::strcmp(failed.first_reason(), "desktop pipeline creation failed") == 0, "first reason is kept"); + expect_decision(failed, true, BuilderGateDecision::refuse_off, "the off builder stays refused"); + expect_decision(failed, true, BuilderGateDecision::refuse_off, "the refusal is permanent"); + expect_decision(failed, false, BuilderGateDecision::unchanged, "the off builder leaves other Dispatches alone"); + + // An untrackable set is not silently allowed: filling the table latches the gate off. + BuilderGateState full(true); + for (unsigned i = 0; i < BuilderGateState::max_pipelines; ++i) + expect(full.note_pipeline(&slots[i], true, true), "fill the builder pipeline table"); + expect(full.tracked() == BuilderGateState::max_pipelines && full.with_pso() == BuilderGateState::max_pipelines, + "the full table is still all present"); + expect_decision(full, true, BuilderGateDecision::allow, "a full tracked set with every PSO is allowed"); + expect(!full.note_pipeline(&slots[BuilderGateState::max_pipelines], true, false), "an extra builder pipeline is refused"); + expect(full.off() && std::strcmp(full.first_reason(), "builder pipeline table is full") == 0, + "an untrackable builder set latches off"); + expect_decision(full, true, BuilderGateDecision::refuse_off, "the untrackable builder set stays refused"); + + std::printf("startup_compute_builder_gate: %d case(s), %d failure(s)\n", cases, failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_compute_builder_gate_runtime.cpp b/tests/startup_compute_builder_gate_runtime.cpp new file mode 100644 index 0000000000..91dfcd13ef --- /dev/null +++ b/tests/startup_compute_builder_gate_runtime.cpp @@ -0,0 +1,148 @@ +#include <d3d12.h> +#include <dxgi1_4.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <memory> +#include <string> + +#include "startup_builder_gate_cs.h" + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Microsoft::WRL::ComPtr; + +void check(HRESULT hr, const char* stage) +{ + if (SUCCEEDED(hr)) return; + std::fprintf(stderr, "%s failed: 0x%08lx\n", stage, static_cast<unsigned long>(hr)); + std::exit(1); +} + +template <typename Method> +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast<Method>((*reinterpret_cast<void***>(object))[index]); +} + +using CreateBuilder = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, REFIID, void**); + +struct VirtualFreeDeleter { + void operator()(void* p) const noexcept { VirtualFree(p, 0, MEM_RELEASE); } +}; +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) return 2; + const bool builder = std::strcmp(argv[2], "builder") == 0; + const bool completed = std::strcmp(argv[2], "completed") == 0; + if (!builder && !completed && std::strcmp(argv[2], "nonbuilder") != 0) return 2; + + SetEnvironmentVariableA("X2W_COMPUTE_BUILDER_GATE", "1"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> warp; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "DXGI factory"); + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp)), "WARP adapter"); + + ComPtr<ID3D12Device> guest; + const std::uint64_t create_params[8]{}; + check(D3D12XboxCreateDevice(warp.Get(), create_params, IID_PPV_ARGS(&guest)), "guest device"); + + // A console container: slot 62 accepts it as a placeholder, and the builder gate must refuse to + // create a desktop PSO from it. The bytes are only read for the refusal, never submitted. + static const unsigned char console_code[64] = {'D', 'X', 'B', 'C'}; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.CS = {console_code, sizeof(console_code)}; + + ComPtr<ID3D12RootSignature> root; + if (completed) { + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr<ID3DBlob> root_blob; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &root_blob, nullptr), + "serialize empty root"); + check(guest->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&root)), "empty root"); + desc.pRootSignature = root.Get(); + desc.CS = {builder_gate_cs, sizeof(builder_gate_cs)}; + } + + using Slot62 = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, UINT, + const void*, REFIID, void**); + ComPtr<ID3D12PipelineState> pipeline; + if (builder || completed) { + const std::wstring path(argv[1], argv[1] + std::strlen(argv[1])); + HMODULE module = LoadLibraryW(path.c_str()); + if (!module) return 3; + const auto create = reinterpret_cast<CreateBuilder>(GetProcAddress(module, "CreateBuilderPipeline")); + if (!create) return 4; + check(create(guest.Get(), &desc, IID_PPV_ARGS(&pipeline)), "builder pipeline"); + ComPtr<ID3D12PipelineState> second; + check(create(guest.Get(), &desc, IID_PPV_ARGS(&second)), "second builder pipeline"); + } else { + check(slot<Slot62>(guest.Get(), 62)(guest.Get(), &desc, 0, nullptr, IID_PPV_ARGS(&pipeline)), + "non-builder pipeline"); + } + + ComPtr<ID3D12CommandAllocator> allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "allocator"); + const UINT list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + ComPtr<ID3D12GraphicsCommandList> list; + check(slot<CreateList>(guest.Get(), 73)(guest.Get(), list_desc, allocator.Get(), nullptr, IID_PPV_ARGS(&list)), + "list"); + using Reset = HRESULT(WINAPI*)(IUnknown*, IUnknown*, void*, void*); + check(slot<Reset>(list.Get(), 139)(list.Get(), allocator.Get(), nullptr, nullptr), "reset"); + + using SetPipeline = void(WINAPI*)(IUnknown*, IUnknown*); + using Dispatch = void(WINAPI*)(IUnknown*, UINT, UINT, UINT); + using Root = void(WINAPI*)(IUnknown*, IUnknown*); + if (completed) slot<Root>(list.Get(), 33)(list.Get(), root.Get()); + slot<SetPipeline>(list.Get(), 25)(list.Get(), pipeline.Get()); + slot<Dispatch>(list.Get(), 14)(list.Get(), 1, 1, 1); + + ComPtr<ID3D12Resource> argument_buffer; + std::unique_ptr<void, VirtualFreeDeleter> backing( + VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (completed) { + if (!backing) return 5; + auto* address = static_cast<char*>(backing.get()) + 4; + const D3D12_DISPATCH_ARGUMENTS arguments{1, 1, 1}; + std::memcpy(address, &arguments, sizeof(arguments)); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 4096; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, + void**); + check(slot<Place>(guest.Get(), 133)(guest.Get(), address, &buffer, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&argument_buffer)), + "argument placed buffer"); + } + + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + D3D12_COMMAND_SIGNATURE_DESC signature_desc{}; + signature_desc.ByteStride = sizeof(D3D12_DISPATCH_ARGUMENTS); + signature_desc.NumArgumentDescs = 1; + signature_desc.pArgumentDescs = &argument; + using CreateSignature = HRESULT(WINAPI*)(IUnknown*, const D3D12_COMMAND_SIGNATURE_DESC*, IUnknown*, REFIID, + void**); + ComPtr<ID3D12CommandSignature> signature; + check(slot<CreateSignature>(guest.Get(), 41)(guest.Get(), &signature_desc, nullptr, IID_PPV_ARGS(&signature)), + "signature"); + + using Execute = void(WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + slot<Execute>(list.Get(), 61)(list.Get(), signature.Get(), 1, argument_buffer.Get(), 0, nullptr, 0); + std::printf("%s done\n", argv[2]); + return 0; +} diff --git a/tests/startup_compute_builder_gate_runtime_check.py b/tests/startup_compute_builder_gate_runtime_check.py new file mode 100644 index 0000000000..8911559859 --- /dev/null +++ b/tests/startup_compute_builder_gate_runtime_check.py @@ -0,0 +1,34 @@ +"""Public slot 62 and indirect paths with the opt-in builder gate and a source-built module.""" +from pathlib import Path +import os +import subprocess +import sys + + +def run(executable, module, mode): + env = dict(os.environ, X2W_COMPUTE_BUILDER_GATE="1", X2W_D3D12_PERMISSIVE="1", + X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1") + result = subprocess.run([str(Path(executable).resolve()), str(Path(module).resolve()), mode], + capture_output=True, text=True, env=env) + assert result.returncode == 0, (mode, result.returncode, result.stdout, result.stderr) + return result.stderr + + +def main(executable, module): + builder = run(executable, module, "builder") + assert "compute builder gate" in builder, builder + assert "Dispatch refused" in builder, builder + assert "ExecuteIndirect refused" in builder, builder + + nonbuilder = run(executable, module, "nonbuilder") + assert "compute builder gate" not in nonbuilder, nonbuilder + + completed = run(executable, module, "completed") + assert "all have a desktop PSO" in completed, completed + assert "requires a desktop compute pipeline and root" not in completed, completed + assert "ExecuteIndirect refused" not in completed, completed + print("builder gate: incomplete set refused; completed set dispatch reaches the list; non-builder untouched") + + +if __name__ == "__main__": + main(sys.argv[1], sys.argv[2]) diff --git a/tests/startup_compute_dispatch_array_check.py b/tests/startup_compute_dispatch_array_check.py new file mode 100644 index 0000000000..343640ad87 --- /dev/null +++ b/tests/startup_compute_dispatch_array_check.py @@ -0,0 +1,125 @@ +"""Startup FP32 and packed D16 array UAV binding through the production slot-67 / slot-14 path (#2742).""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_compute_image_store_check as A +import startup_compute_image_store_d16_check as D +import startup_compute_dispatch_texture_check as T +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a + +WIDTH, HEIGHT, LAYERS, FIRST = 32, 8, 6, 1 +WORDS = WIDTH * HEIGHT * 4 + + +def reference(layer=None, rows=2, layers=LAYERS, d16=False, values=None): + result = ([0x5000 + i for i in range(layers * WORDS)] if d16 else + [0xbf000000 | (z << 12) | i for z in range(layers) for i in range(WORDS)]) + if values is None: + values = D.ARRAY_VALUES if d16 else A.ARRAY_VALUES + if layer is not None: + for y in range(rows): + for x in range(4 * A.fixture.GROUPS): + at = (FIRST + layer) * WORDS + (y * WIDTH + x) * 4 + result[at:at + 4] = values + return result + + +def check(directory, consumer, dxc, adapter, layer, masked, d16=False): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1") + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(T.C.root_blob(3, table_range=True)) + env["X2W_TEST_COMPUTE_ROOT"] = str(directory / "compute_root") + program = D.array_program(layer, masked) if d16 else A.array_program(layer) + if masked and not d16: + assert program.count(A.ARRAY_STORE) == 1 + program = program.replace(A.ARRAY_STORE, A.MASK + A.ARRAY_STORE) + (directory / "program").write_bytes(program) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a(A.fixture.GROUP, A.RSRC2)) + layout = ("<%dH" if d16 else "<%dI") % (WORDS * LAYERS) + mode = "texture-array-d16" if d16 else "texture-array" + unit = "halves" if d16 else "words" + store = D.ARRAY_LINE if d16 else A.ARRAY_LINE + got, result = T.run(directory, consumer, env, mode, layout) + print(result.stdout, end="") + assert got == reference(d16=d16), "untranslated dispatch wrote the texture" + assert len(T.lines(result, "Dispatch(2, 1, 1) refused: no translation")) == 1, result.stderr[-3000:] + key = int(T.lines(result, "x2w-draw compute request")[0].split()[3], 16) + T.translate(cache, dxc, key) + manifest = (cache / f"{key:016x}.txt").read_text() + assert "uav 0 tex2da float table 1 64 channels 4" in manifest.splitlines(), manifest + hlsl = cache / f"{key:016x}.cs.hlsl" + cso = cache / f"{key:016x}.cs.cso" + source = hlsl.read_text() + assert "RWTexture2DArray<float4> w0 : register(u0);" in source + expected = reference(layer, 1 if masked else 2, d16=d16) + assert store in source + assert sum(a != b for a, b in zip(reference(d16=d16), expected, strict=True)) == (32 if masked else 64) + got, result = T.run(directory, consumer, env, mode, layout) + assert len(T.lines(result, "Dispatch(2, 1, 1) translated")) == 1, result.stderr[-3000:] + debug = T.clean(result) + wrong = sum(a != b for a, b in zip(got, expected)) + assert wrong == 0, (layer, masked, wrong) + print(f"{adapter}: relative layer {layer}, physical layer {FIRST + layer}, partial EXEC={masked}: " + f"{len(got)} {unit}, mismatches={wrong}; debug layer: {debug}", flush=True) + + # The actual runtime must refuse a plain 2D view of the same format before dispatch. + got, result = T.run(directory, consumer, env, "texture-store" if d16 else "texture-array-2d", + ("<%dH" if d16 else "<%dI") % WORDS) + assert got == reference(layers=1, d16=d16) + refusal = T.lines(result, "Dispatch(2, 1, 1) refused:") + assert len(refusal) == 1 and refusal[0].endswith("an output texture view is not a 2D array"), result.stderr[-3000:] + assert not T.lines(result, "Dispatch(2, 1, 1) translated") + print(f"{adapter}: incompatible 2D UAV refused; {len(got)} {unit} unchanged", flush=True) + + # Negative controls run through the same production binding, not the offscreen shortcut. + guard = "if (exec & 1) " + store + if masked: + assert source.count(guard) == 1 + cases = [("dropped EXEC", source.replace(guard, store), reference(layer, d16=d16), 32)] + else: + index = "uint3(v8, v9, v10)" + assert source.count(index) == 1 + delta = "+ 1u" if layer == 1 else "- 1u" + cases = [("wrong layer", source.replace(index, f"uint3(v8, v9, v10 {delta})"), + reference(2, d16=d16), 128)] + if d16 and layer == 1: + parts = ", ".join(D.PARTS) + assert source.count(parts) == 1 and source.count(store) == 1 + for label, order, count in (("swap halves", (1, 0, 2, 3), 32), + ("swap VGPRs", (2, 3, 0, 1), 64)): + cases.append((label, source.replace(parts, ", ".join(D.PARTS[i] for i in order)), + reference(layer, d16=True, values=tuple(D.ARRAY_VALUES[i] for i in order)), count)) + cases.append(("omit store", source.replace(store, ""), reference(d16=True), 64)) + for label, mutant, control_reference, count in cases: + assert mutant != source + predicted = sum(a != b for a, b in zip(control_reference, expected, strict=True)) + assert predicted == count, (layer, label, predicted, count) + hlsl.write_text(mutant, encoding="ascii") + subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) + got, result = T.run(directory, consumer, env, mode, layout) + assert len(T.lines(result, "Dispatch(2, 1, 1) translated")) == 1, result.stderr[-3000:] + T.clean(result) + wrong = sum(a != b for a, b in zip(got, expected, strict=True)) + assert wrong == predicted and got == control_reference, (layer, label, wrong, predicted) + print(f"{adapter}: {label} control: {len(got)} {unit}, mismatches={wrong} (expected {predicted})", flush=True) + + +def main(consumer, dxc, adapter, d16=False): + with tempfile.TemporaryDirectory() as temp: + for layer in (1, 3): + for masked in (False, True): + check(Path(temp) / f"layer-{layer}-{masked}", consumer, dxc, adapter, layer, masked, d16) + print(f"startup_compute_dispatch_array{'_d16' if d16 else ''}: PASS on {adapter}") + + +if __name__ == "__main__": + if len(sys.argv) not in (4, 5) or sys.argv[3] not in ("warp", "hardware") or (len(sys.argv) == 5 and sys.argv[4] != "--d16"): + sys.exit(__doc__) + main(*sys.argv[1:4], d16=len(sys.argv) == 5) diff --git a/tests/startup_compute_dispatch_check.py b/tests/startup_compute_dispatch_check.py new file mode 100644 index 0000000000..5d81322f4d --- /dev/null +++ b/tests/startup_compute_dispatch_check.py @@ -0,0 +1,191 @@ +"""A translated compute program dispatched through the stand-in's command list (list slot 14). + +usage: startup_compute_dispatch_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer creates case A of startup_gfx2hlsl_compute_check.py as a device slot 67 pipeline and records, on a +stand-in list, the descriptor heap, the pipeline, its root signature, two root constants (word 0 by slot 37, word 1 +by slot 39, with a slot 40 call of other words in between), one table of two +hardware buffer descriptors and Dispatch(3, 2, 2). Input and output are placed buffers that alias the consumer's +memory; the output words are read from that memory after the queue's fence. The runs share one cache: + +1. before translation: the request is published, the Dispatch is refused with "no translation" and every output + word keeps the sentinel (the check fails when nothing translated is dispatched); +2. after gfx2hlsl.py --pending with DXC: all 320 words equal the case's expectation; +3. dispatch-none (no Dispatch recorded): every word keeps the sentinel; +4. dispatch-swapped (the two descriptors exchanged, so the output names the buffer without unordered access): + refused with "an output buffer has no unordered access", every word keeps the sentinel and the input is + unchanged; +5. dispatch-same-root (the same compute root set again after the constants): all 320 words still match; +6. five more refusals, each with its one logged reason and an untouched output: dispatch-missing-word (no slot 37 + call), dispatch-root-changed (another compute root and back after the constants), dispatch-reset (list closed + and reset after the constants), dispatch-wrong-root (recorded under a root the pipeline was not created with) + and dispatch-same-buffer (the output buffer is also the input). +7. slot 35 selects the correct table at descriptor index 2 instead of the swapped pair at the heap start; + setting the same heap again preserves the table, but changing the compute root or view heap after binding + must refuse at the table lookup, not an earlier check. +8. published output compatibility: the same bytecode is refused with either stale native manifest + and runs with the current native marker or with the Python sidecar. +Exit 77 only if the initial probe cannot use the adapter or required heaps. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def dispatch(directory, consumer, env, mode, *, probe=False): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if 'device removed' in result.stderr.lower(): + raise RuntimeError(f'{mode}: device removed\n{result.stderr[-3000:]}') + if result.returncode == 77 and probe: + print(result.stdout, end='') + sys.exit(77) + if result.returncode: + raise RuntimeError(f'{mode}: consumer exit {result.returncode}\n{result.stdout[-1000:]}\n{result.stderr[-3000:]}') + return list(struct.unpack('<%dI' % C.WORDS, out.read_bytes())), result + + +def lines(result, text): + return [line for line in result.stderr.splitlines() if text in line] + + +def prepare_case(directory, adapter): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + else: + env.pop('X2W_TEST_DISPATCH_HARDWARE', None) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + return cache, env + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare_case(directory, adapter) + env.pop('X2W_NATIVE_SHADERS', None) # Exercise published translations. + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch', probe=True) + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + census = lines(result, 'x2w-render compute census') + assert census == ['x2w-render compute census: 1 keys dispatched', + 'x2w-render compute census reason "no translation": 1 keys, 1 dispatches', + f'x2w-render compute census key {key:016x}: 1 dispatches, 0 translated, first refusal: ' + 'no translation [00000000 00000000 00000000 00000000]'], census + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + manifest = cache / f'{key:016x}.txt' + hlsl = cache / f'{key:016x}.cs.hlsl' + python_manifest = manifest.read_bytes() + python_hlsl = hlsl.read_bytes() + assert not any(line.startswith(b'native ') for line in python_manifest.splitlines()) + hlsl.unlink() + for marker, reason in ( + (b'', 'native translation without a revision; rebuild it'), + (b'native 0\n', 'native translation from another compiler revision; rebuild it'), + ): + manifest.write_bytes(python_manifest + marker) + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == untouched, 'a stale native output wrote the output buffer' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + reason)) == 1, result.stderr[-3000:] + + # Reuse working bytecode to isolate the manifest gate from native adapter requirements. + manifest.write_bytes(python_manifest + b'native 1\n') + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == expected and not lines(result, 'refused:'), result.stderr[-3000:] + hlsl.write_bytes(python_hlsl) + manifest.write_bytes(python_manifest) + + got, result = dispatch(directory, consumer, env, 'dispatch') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + census = lines(result, 'x2w-render compute census') + assert len(census) == 2 and census[1].endswith(': 1 dispatches, 1 translated, first refusal: none ' + '[00000000 00000000 00000000 00000000]'), census + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + got, result = dispatch(directory, consumer, env, 'dispatch-none') + assert got == untouched and not lines(result, 'Dispatch('), 'the output changed without a Dispatch' + assert not lines(result, 'x2w-render compute census'), 'a census without a Dispatch' + + got, result = dispatch(directory, consumer, env, 'dispatch-swapped') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(census) == 3 and census[1].endswith( + 'reason "an output buffer has no unordered access": 1 keys, 1 dispatches') \ + and '[00000000 00000000 ' not in census[2], census + assert len(refused) == 1 and 'an output buffer has no unordered access' in refused[0], \ + result.stderr[-3000:] + got, result = dispatch(directory, consumer, env, 'dispatch-same-root') + assert got == expected and not lines(result, 'refused'), 'setting the same compute root again lost the constants' + + unset = 'an entry value was not set since the compute root' + for mode, reason in (('dispatch-missing-word', unset), ('dispatch-root-changed', unset), ('dispatch-reset', unset), + ('dispatch-wrong-root', 'the compute root set is not the one the pipeline was created with'), + ('dispatch-same-buffer', 'an output buffer is also an input')): + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, f'{mode}: a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{mode}: {refused}\n{result.stderr[-3000:]}' + debug_enabled = bool(layer and '0x00000000' in layer[0]) + for mode in ('dispatch-table-root-changed', 'dispatch-table-heap-changed', 'dispatch-table-offset'): + got, result = dispatch(directory, consumer, env, mode) + if debug_enabled: + initialized = lines(result, 'x2w-d3d12 debug layer: ') + assert len(initialized) == 1 and '0x00000000' in initialized[0], f'{mode}: debug layer not initialized' + refused = lines(result, 'refused: ') + translated = lines(result, 'Dispatch(3, 2, 2) translated') + if mode == 'dispatch-table-offset': + wrong = sum(a != b for a, b in zip(got, expected)) + assert not wrong, f'{mode}: {wrong} words differ from the CPU reference\n{result.stderr[-3000:]}' + assert len(translated) == 1 and not refused, result.stderr[-3000:] + print(f'{mode}: all {C.WORDS} words match the CPU reference') + else: + written = sum(word != C.SENTINEL for word in got) + assert not written, f'{mode}: {written} output words changed after table invalidation\n{result.stderr[-3000:]}' + assert not translated and len(refused) == 1 and refused[0].endswith( + 'Dispatch(3, 2, 2) refused: a table descriptor is not bound'), result.stderr[-3000:] + print(f'{mode}: exact table refusal, all {C.WORDS} sentinel words unchanged') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print(f'startup_compute_dispatch: PASS on {adapter}') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_entry_check.py b/tests/startup_compute_dispatch_entry_check.py new file mode 100644 index 0000000000..1098908b27 --- /dev/null +++ b/tests/startup_compute_dispatch_entry_check.py @@ -0,0 +1,130 @@ +"""Translated compute programs whose entry values are words of a bound buffer descriptor (list slot 14). + +usage: startup_compute_dispatch_entry_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer records each program as startup_compute_dispatch_check.py does, with the input words and the stride, +record count and word 3 of both table descriptors set by this script (X2W_TEST_DISPATCH_IN and _FIELDS). Each +program writes the same lanes in every group, so the consumer's Dispatch(3, 2, 2) gives the result of one group. + +1. Case L-uint of startup_gfx2hlsl_compute_check.py reads its input with buffer_load_format_xyzw; the manifest + takes `stride 0` and `descword3 0` from the input's descriptor. Stride 6 and the word 3 of L-uint, then of + L-unorm on the same translation, must each give that case's 320 words. A FORMAT the program does not decode is + refused with one reason and keeps every output word at its sentinel. +2. Case F of startup_compute_store_d16_x_check.py stores with buffer_store_format_d16_x; the manifest takes + `uav_descword3 0`, `uav_stride 0` and `uav_numrecords 0` from the output's descriptor. Three descriptors give + three different expectations: 32_FLOAT with stride 8 and 12 records, 16_FLOAT with the same, and 32_FLOAT with + stride 12 and 7 records. A fourth sets SWIZZLE_ENABLE (word 1 bit 31): the dispatch is translated and the + program stores nothing, which holds only while the entry value keeps the upper bits of word 1. +Before translation each program is refused with "no translation". Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_compute_store_d16_x_check as D +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +RAW = (4, C.WORDS, 0) # the consumer's default stride, record count and word 3 +UNDECODED = 'a formatted input has no word 3 the program decodes' + + +def store_f32(halves, stride, records): + out = bytearray(struct.pack('<%dI' % C.WORDS, *[C.SENTINEL] * C.WORDS)) + for lane in range(records): + struct.pack_into('<I', out, lane * stride + 4, D.f16_to_f32_bits(halves[lane])) + return list(struct.unpack('<%dI' % C.WORDS, out)) + + +def run_program(root, name, consumer, dxc, adapter, program, manifest_tail, runs): + directory = root / name + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + words, rsrc2, group = program + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + untouched = [C.SENTINEL] * C.WORDS + + def run(source, fields): + (directory / 'in.bin').write_bytes(source) + (directory / 'fields.bin').write_bytes(struct.pack('<6I', *fields[0], *fields[1])) + return dispatch(directory, consumer, dict(env, X2W_TEST_DISPATCH_IN=str(directory / 'in.bin'), + X2W_TEST_DISPATCH_FIELDS=str(directory / 'fields.bin')), 'dispatch') + + source, fields, _ = runs[0][1:] + got, result = run(source, fields) + print(result.stdout, end='') + assert got == untouched and len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + manifest = (cache / f'{key:016x}.txt').read_text() + assert manifest_tail in manifest, manifest + + for label, source, fields, expected in runs: + got, result = run(source, fields) + refused = lines(result, 'refused: ') + if isinstance(expected, str): + assert got == untouched, f'{label}: a refused Dispatch wrote the output' + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and refused[0].endswith('refused: ' + expected), f'{label}: {refused}\n{result.stderr[-3000:]}' + assert len(census) == 3 and census[1].endswith(f'reason "{expected}": 1 keys, 1 dispatches'), (label, census) + print(f'{label}: refused ({expected}), output untouched') + continue + assert (expected == untouched) == label.endswith('-swizzle') + wrong =[i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, '%s: word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + label, wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not refused, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + layer = lines(result, 'x2w-d3d12 debug layer: ') + print(f'{label}: all {C.WORDS} words match (debug layer: ' + + ('enabled, no error message)' if layer and '0x00000000' in layer[0] else 'unavailable)')) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + _, words_l, rsrc2_l, group_l, _ = C.CASES['L-uint'] + formatted = bytes(C.formatted_input()) + undecoded = (C.L_WORD3['L-uint'] & ~(127 << 12)) | 2 << 12 + assert C.L_STRIDE == 6 and not (undecoded >> 12) & 127 in (1, 5, 14, 22, 23, 24, 27, 29, 56, 60, 64, 71, 74, 77) + # 20 records of 6 bytes cover the last lane's 4-byte read at byte 6 * 15 + 3. + run_program(root, 'formatted', consumer, dxc, adapter, (words_l, rsrc2_l, group_l), + 'udsrc 2 stride 0\nudsrc 3 descword3 0\nsrv 0 buf table 1 0\nuav 0 table 1 16\n', [ + ('dispatch-formatted-uint', formatted, ((6, 20, C.L_WORD3['L-uint']), RAW), C.expected('L-uint')), + ('dispatch-formatted-unorm', formatted, ((6, 20, C.L_WORD3['L-unorm']), RAW), C.expected('L-unorm')), + ('dispatch-formatted-undecoded', formatted, ((6, 20, undecoded), RAW), UNDECODED), + ]) + + _, words_f, rsrc2_f, group_f, _ = D.PROGRAMS['F'] + runs = [] + for variant, label in (('F-f32', 'f32'), ('F-f16', 'f16'), ('F-swizzle-en', 'f32-swizzle')): + _, source, constants, expected, _ = D.case_inputs(variant) + runs.append(('dispatch-store-' + label, source, (RAW, tuple(constants[3:5]) + (constants[2],)), expected)) + word3_f32, halves = D.F_VARIANTS['F-f32'][0], D.FP16_VALUES + runs.append(('dispatch-store-f32-stride12', D.poisoned_source(halves), (RAW, (12, 7, word3_f32)), store_f32(halves, 12, 7))) + assert runs[0][3] != runs[3][3] != runs[1][3] + run_program(root, 'store', consumer, dxc, adapter, (words_f, rsrc2_f, group_f), + 'udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n', runs) + print(f'startup_compute_dispatch_entry: PASS on {adapter} (6 descriptor-word dispatches match, ' + '1 refused; untouched before translation)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_heap_check.py b/tests/startup_compute_dispatch_heap_check.py new file mode 100644 index 0000000000..c5addfad71 --- /dev/null +++ b/tests/startup_compute_dispatch_heap_check.py @@ -0,0 +1,87 @@ +"""A translated compute program whose input is the resource heap record a root constant indexes (list slot 14). + +usage: startup_compute_dispatch_heap_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer creates the program of startup_gfx2hlsl_heap_record_check.py as a device slot 67 pipeline, with a +root signature that indexes the resource heap directly, and records the descriptor heap, the pipeline, the root +signature, three root constants, one table and Dispatch(3, 2, 2). The output descriptor is at table byte 16 as in +startup_compute_dispatch_check.py. The input descriptor is only in heap record 2 (heap byte 64), which the third +root constant indexes; heap bytes 0 and 32 hold the output's descriptor, so a dispatch that ignores the index or +scales it by 16 is refused instead of passing. Three runs share one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the heap record and all 320 words equal the + expectation of case A of startup_gfx2hlsl_compute_check.py (the program computes the same words); +3. dispatch-heap-outside (the constant is 0x07ffffff, a record past the heap): refused with one + logged reason, every word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +OUTSIDE = "a heap record is outside the list's view heap" + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and H.INDEX_WORD == 2, 'the consumer hard-codes the dispatch and the index word' + (directory / 'program').write_bytes(H.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == H.MANIFEST + + got, result = dispatch(directory, consumer, env, 'dispatch-heap') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-outside') + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and OUTSIDE in refused[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{OUTSIDE}": 1 keys, 1 dispatches'), census + print(f'startup_compute_dispatch_heap: PASS on {adapter} (all {C.WORDS} words match through heap record 2; ' + 'untouched before translation and for a record outside the heap)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_heap_word_check.py b/tests/startup_compute_dispatch_heap_word_check.py new file mode 100644 index 0000000000..4ddb8ad31f --- /dev/null +++ b/tests/startup_compute_dispatch_heap_word_check.py @@ -0,0 +1,94 @@ +"""A translated compute program whose input is the resource heap record a word of a table buffer indexes (slot 14). + +usage: startup_compute_dispatch_heap_word_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer creates the program of startup_gfx2hlsl_heap_word_check.py as a device slot 67 pipeline and records it +as startup_compute_dispatch_heap_check.py does, with root constant word 2 set to 1 and a buffer in the recording's +upload memory (list slot 148) at table byte 96. Word 288 + 336 * 1 of that buffer is 2, the heap record of the +input. Heap records 0 and 1 hold the output's descriptor and every other word of the buffer names one of them, so +a dispatch that ignores the word, the root constant, its scale or the byte offset is refused instead of passing. +Runs sharing one cache: + +1. before translation: the request is published and the Dispatch is refused with "no translation"; +2. after gfx2hlsl.py --pending with DXC: the manifest names the word and all 320 words equal the expectation of + case A of startup_gfx2hlsl_compute_check.py; +3. dispatch-heap-word-outside (the word is 0x07ffffff, a record past the heap), dispatch-heap-word-past (the + buffer ends at the word) and dispatch-heap-word-placed (the buffer is the placed input, not upload memory): + each refused with one logged reason, every output word keeps the sentinel and the input is unchanged. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_heap_record_check as H +import startup_gfx2hlsl_heap_word_check as W +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +CONTROLS = ( + ('dispatch-heap-word-outside', "a heap record is outside the list's view heap"), + ('dispatch-heap-word-past', 'a heap index word is outside its table buffer'), + ('dispatch-heap-word-placed', "a heap index word is not in the list's upload memory"), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert H.GROUPS == (3, 2, 2) and W.FORM == '288 rootconst 0 2 times 336', 'the consumer hard-codes these' + (directory / 'program').write_bytes(W.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(H.GROUP, H.RSRC2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + assert expected != untouched + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert (cache / f'{key:016x}.txt').read_text() == W.MANIFEST % W.FORM + + got, result = dispatch(directory, consumer, env, 'dispatch-heap-word') + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + for mode, reason in CONTROLS: + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, '%s: a refused Dispatch wrote the output' % mode + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and reason in refused[0], '%s:\n%s' % (mode, result.stderr[-3000:]) + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (mode, census) + print(f'startup_compute_dispatch_heap_word: PASS on {adapter} (all {C.WORDS} words match through the index word; ' + f'untouched before translation and for {len(CONTROLS)} refused controls)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_input_check.py b/tests/startup_compute_dispatch_input_check.py new file mode 100644 index 0000000000..66acb20d30 --- /dev/null +++ b/tests/startup_compute_dispatch_input_check.py @@ -0,0 +1,136 @@ +"""Named reasons for a translated compute input that is not a complete GPU-backed buffer range (list slot 14). + +usage: startup_compute_dispatch_input_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer records case A of startup_gfx2hlsl_compute_check.py as startup_compute_dispatch_check.py does. After +gfx2hlsl.py --pending with DXC, the unchanged recording still matches all 320 words. Then one input descriptor at a +time is replaced, and each dispatch is refused with its own reason, logs which input and descriptor once, writes +no output word and leaves the input as written: + +- dispatch-input-empty: zero records with a nonzero base and word 3 zero (synthetic values); +- dispatch-input-past: 16 bytes past the end of the placed input buffer; +- dispatch-input-unplaced: memory between the two placed buffers; +- dispatch-input-copied: a buffer placed at an offset the desktop cannot alias, so it is a separate copy; +- dispatch-input-token: the token of a texture view. + +Last, dispatch-input-memory-view replaces the input descriptor with the token of a buffer view (device slot 70) of +memory no buffer is placed over, 16 bytes in, and writes the input words there after the view exists: all 320 +words match. The stand-in places that buffer in the consumer's own heap, outside its placement index. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +CONTROLS = ( + ('dispatch-input-empty', 'an input buffer descriptor has zero records'), + ('dispatch-input-past', 'an input range crosses the end of a placed buffer'), + ('dispatch-input-unplaced', 'an input is in title memory outside any placed buffer'), + ('dispatch-input-copied', 'an input is in a placed buffer that does not alias title memory'), + ('dispatch-input-token', 'an input view token is not a buffer view of a desktop resource'), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.pop('X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT', None) # prepare() copies os.environ: every baseline run starts with the flag off + env.pop("X2W_D3D12_RING_RELEASE_AT_SUBMIT", None) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + (directory / 'program').write_bytes(words) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + + got, result = dispatch(directory, consumer, env, 'dispatch') + print(result.stdout, end='') + assert got == untouched and len(lines(result, 'refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == expected and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + + for mode, reason in CONTROLS: + got, result = dispatch(directory, consumer, env, mode) + assert got == untouched, '%s: a refused Dispatch wrote the output' % mode + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + where = lines(result, f'x2w-draw compute {key:016x} first refused input 0 (table ') + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), '%s:\n%s' % (mode, result.stderr[-3000:]) + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (mode, census) + assert len(where) == 1, (mode, result.stderr[-3000:]) + got, result = dispatch(directory, consumer, env, 'dispatch-input-memory-view') + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + # Opt-in X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT: an input in a placed buffer that does not alias title memory holds + # its bytes only in title memory (the desktop copy is zeros). Off, it is refused; on, the bytes are snapshotted + # into the snapshot pool and all 320 words match; with title memory zero (dispatch-input-copied) the dispatch runs + # on zeros: not refused, not the expected words, not untouched. + snapshot_env = dict(env, X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT='1') + got, result = dispatch(directory, consumer, env, 'dispatch-input-snapshot') + assert got == untouched and lines(result, 'refused: ')[0].endswith(CONTROLS[3][1]), result.stderr[-3000:] + got, result = dispatch(directory, consumer, snapshot_env, 'dispatch-input-snapshot') + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert len(lines(result, 'comes from a snapshot of title memory (1280 bytes)')) == 1, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + got, result = dispatch(directory, consumer, snapshot_env, 'dispatch-input-copied') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert got != expected and got != untouched, 'a snapshot of zero title memory must not give the expected words' + # Long run: 48 frames of dispatches whose 8 MiB title-memory input is snapshotted each frame, the queue completed between + # frames: 384 MiB in all, three times the snapshot pool (128 MiB). The pool must be recycled: every frame translates, + # gives the first frame's words (the consumer exits 85 if one does not), the last frame matches the CPU reference + # and no reservation is refused. + # With release enabled, keep the submitted lists closed to exercise release without Reset. + for release, mode in ((False, 'dispatch-input-snapshot-long'), (True, 'dispatch-input-snapshot-long-keep')): + long_env = dict(snapshot_env) + if release: + long_env["X2W_D3D12_RING_RELEASE_AT_SUBMIT"] = "1" + got, result = dispatch(directory, consumer, long_env, mode) + assert got == expected and not lines(result, 'refused: '), result.stderr[-3000:] + assert not lines(result, 'reservation refused'), lines(result, 'reservation refused') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) >= 1, result.stderr[-3000:] + # The input must really come from a snapshot (8 MiB), not be read in place: an empty long case would pass everything above. + assert len(lines(result, 'comes from a snapshot of title memory (8388608 bytes)')) == 1, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + # An all-zero descriptor is an unbound buffer: the dispatch runs on zeros instead of being refused (the empty + # control above has a nonzero base and stays refused). + got, result = dispatch(directory, consumer, env, 'dispatch-input-null') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert len(lines(result, 'comes from zeros for a null descriptor (16 bytes)')) == 1, result.stderr[-3000:] + assert got != expected and got != untouched, 'a null input must read zeros, not the expected words' + print(f'{adapter}: title-input snapshot: off refused, on all {C.WORDS} words match, zero title memory runs on zeros') + print(f'startup_compute_dispatch_input: PASS on {adapter} (all {C.WORDS} words match, also with the input behind ' + f'a memory view token; {len(CONTROLS)} inputs refused, each with its own reason and an untouched output)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py new file mode 100644 index 0000000000..02b5432cf5 --- /dev/null +++ b/tests/startup_compute_dispatch_native_check.py @@ -0,0 +1,166 @@ +"""A slot 67 compute program translated in-process by the C++ compiler and dispatched through the stand-in (#2934). + +usage: startup_compute_dispatch_native_check.py <startup_stream_consumer> <DXC directory> <warp|hardware> + +X2W_NATIVE_SHADERS names the directory of dxcompiler.dll and dxil.dll. The cache starts empty and no offline +translator runs before step 3. The program is case A of startup_gfx2hlsl_compute_check.py with its two buffer +descriptors loaded from 32-byte table records (two s_load_dwordx4, at table bytes 0 and 32), the layout the C++ +compiler reads a table in. The consumer's dispatch-records32 mode writes the table that way. The reference is +that case's CPU expectation. + +1. Native: the first Dispatch translates the request in the stand-in and is recorded. All 320 words match, the log + names the native translation, and the cache holds request files and compiler cache entries only (no <key>.txt, + <key>.cs.cso or <key>.fail). The same program over the plain table layout, which has no descriptor at byte 32, + is then refused when it is bound and every word keeps the sentinel: the record at byte 32 is what was bound. +2. Unsupported workload: case A itself reads its second descriptor from table byte 16. The C++ compiler refuses + it, the reason is logged, the Dispatch is refused with "no translation" and every word keeps the sentinel. +3. Fallback: gfx2hlsl.py --pending then publishes both requests, and with native translation still on the next run + dispatches case A through the published translation. All 320 words match. +4. Order: the first program runs again, now with a published translation in the cache. The native translation is + still the one used, and all 320 words match. + +A direct compute module declares wave size 32. On an adapter without 32-lane waves, step 1 instead checks that the +native translation is refused by that name with the output untouched, steps 2 and 3 run as written, step 4 runs the +first program through its published translation, and the check exits 77. Exit 77 also when the adapter is not +available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_stream_check import gfx2hlsl as G + +LOAD_X8 = bytes.fromhex('05030cf4' '000000fa') +LOADS_X4 = bytes.fromhex('050308f4' '000000fa' '050408f4' '200000fa') +RECORD_LOADS = ['s_load_dwordx4 s[12:15], s[10:11], 0x0', 's_load_dwordx4 s[16:19], s[10:11], 0x20'] +NO_WAVES = 'not translated natively: the adapter has no 32-lane waves' + + +def mismatch(got, expected, result): + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + return '' if not wrong else 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + + +def scalar_window_case(consumer, dxc_dir, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + _, env = prepare_case(directory, adapter) + env.update(X2W_NATIVE_SHADERS=dxc_dir, X2W_NATIVE_SHADERS_ONLY='1') + program = directory / 'program' + words = program.read_bytes() + op = {instruction: offset for offset, _, instruction, _ in G.decode(words)} + # Keep case A's output address calculation. Read the scalar pair at +36 + # through the three-record input at table byte 64, then store s10. + load_descriptors = bytes.fromhex('050308f4400000fa 050408f4200000fa') + read_scalar = bytes.fromhex('860224f4240000fa 7fc08cbf 0a020a7e') + wait = next(row[0] for row in G.decode(words) if row[2] == 's_waitcnt') + program.write_bytes(words[:op['s_load_dwordx8']] + load_descriptors + + words[wait:op['buffer_load_dword']] + read_scalar + words[op['buffer_store_dword']:]) + source = directory / 'input' + env['X2W_TEST_DISPATCH_IN'] = str(source) + for value in (1024, 0x45678): + data = [0x11000000 + i for i in range(C.WORDS)] + data[9] = value + source.write_bytes(struct.pack(f'<{C.WORDS}I', *data)) + expected = [value] * 288 + [C.SENTINEL] * 32 + got, result = dispatch(directory, consumer, env, 'dispatch-scalar-window') + if lines(result, NO_WAVES): + assert got == [C.SENTINEL] * C.WORDS + return + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert lines(result, 'translated natively'), result.stderr[-3000:] + got, result = dispatch(directory, consumer, env, 'dispatch-scalar-window-short') + assert got == [C.SENTINEL] * C.WORDS, result.stderr[-3000:] + assert lines(result, 'refused: an input is in title memory outside any placed buffer'), result.stderr[-3000:] + + +def main(consumer, dxc_dir, adapter): + scalar_window_case(consumer, dxc_dir, adapter) + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare_case(directory, adapter) + env['X2W_NATIVE_SHADERS'] = dxc_dir + case_a = (directory / 'program').read_bytes() + records32 = case_a.replace(LOAD_X8, LOADS_X4) + assert case_a.count(LOAD_X8) == 1 and [i[3] for i in G.decode(records32)[2:4]] == RECORD_LOADS + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + + (directory / 'program').write_bytes(records32) + got, result = dispatch(directory, consumer, env, 'dispatch-records32') + print(result.stdout, end='') + key32 = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + no_waves = bool(lines(result, NO_WAVES)) + if no_waves: + assert got == untouched, 'a Dispatch without 32-lane waves wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + else: + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert len(lines(result, 'translated natively: 2 entry values, 1 inputs, 1 outputs')) == 1, result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused'), result.stderr[-3000:] + layer = lines(result, 'x2w-d3d12 debug layer: ') + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('debug layer: ' + ('enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable')) + got, result = dispatch(directory, consumer, env, 'dispatch') + refused = lines(result, 'refused: ') + assert got == untouched, 'a Dispatch with no descriptor at table byte 32 wrote the output' + assert len(refused) == 1 and 'no translation' not in refused[0], result.stderr[-3000:] + # The first request writes revision.txt; it is cache metadata, not a publication. + published = sorted(p.name for p in cache.iterdir() + if not p.name.startswith('req_') and p.name not in ('native', 'revision.txt')) + assert not published, f'the native route left {published} in the cache' + + (directory / 'program').write_bytes(case_a) + got, result = dispatch(directory, consumer, env, 'dispatch') + reason = lines(result, 'not translated natively: ') + assert got == untouched, 'a Dispatch of a program the C++ compiler refused wrote the output' + assert len(reason) == 1 and 'unaligned descriptor table entry' in reason[0], result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + key = int(reason[0].split('compute pipeline ')[1].split()[0], 16) + + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=str(Path(dxc_dir) / 'dxc.exe'))).stdout + assert f'{key:016x}: ok' in out, out + got, result = dispatch(directory, consumer, env, 'dispatch') + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert lines(result, 'not translated natively: ') and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, \ + result.stderr[-3000:] + + assert f'{key32:016x}: ok' in out, out + (directory / 'program').write_bytes(records32) + got, result = dispatch(directory, consumer, env, 'dispatch-records32') + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert bool(lines(result, f'{key32:016x} translated natively')) != no_waves, result.stderr[-3000:] + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + + controls = ('the C++ compiler refuses case A with every word untouched, and a published translation then runs ' + 'it') + if no_waves: + print(f'startup_compute_dispatch_native: SKIP on {adapter}: the adapter has no 32-lane waves. Checked: the ' + f'native translation is refused by that name with every word untouched; {controls}; the first ' + f'program matches all {C.WORDS} words through its published translation') + sys.exit(77) + shared_loads = LOADS_X4[:4] + bytes.fromhex('200000fa') + LOADS_X4[8:] + (directory / 'program').write_bytes(case_a.replace(LOAD_X8, shared_loads)) + got, result = dispatch(directory, consumer, dict(env, X2W_NATIVE_SHADERS_ONLY='1'), 'dispatch-read-write-uav') + expected[288:] = [C.input_word(i) for i in range(288, C.WORDS)] + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert lines(result, '0 inputs, 1 outputs'), result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + print('shared guest UAV: in-place reads and writes matched with untouched tail') + print(f'startup_compute_dispatch_native: PASS on {adapter} (all {C.WORDS} words match after the in-process ' + f'translation from an empty cache, and again with a published translation in the cache; the plain table ' + f'layout is refused when bound; {controls})') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_output_check.py b/tests/startup_compute_dispatch_output_check.py new file mode 100644 index 0000000000..45729991e1 --- /dev/null +++ b/tests/startup_compute_dispatch_output_check.py @@ -0,0 +1,92 @@ +"""Named reasons for a translated compute output that is not an aliased placed buffer range (list slot 14). + +usage: startup_compute_dispatch_output_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +The consumer records case A of startup_gfx2hlsl_compute_check.py as startup_compute_dispatch_check.py does. After +gfx2hlsl.py --pending with DXC, the unchanged recording still matches all 320 words. Then the output descriptor or +its buffer is changed one condition at a time, and each dispatch is refused with its own reason in the log and the +census and writes no output word: + +- dispatch-output-texture-token: the token of a texture view where the output descriptor was; +- zero records, a range over 16 MiB (stride 4, 4 Mi + 1 records) and a range 16 bytes past the placed output + buffer, through X2W_TEST_DISPATCH_FIELDS (synthetic values); +- dispatch-output-unplaced: memory between the two placed buffers; +- dispatch-output-copied: a buffer placed there at an offset the desktop cannot alias, so it is a separate copy; +- dispatch-output-state: the output buffer placed (and aliased) in the unordered access state; +- dispatch-output-unaligned: the output starts 8 bytes into its buffer; +- dispatch-swapped: the output names the input buffer, which has no unordered access. + +A resource with an aliased placement and no recorded information also reports the common state reason; no +fixture reaches it. Exit 77 when the adapter is not available. +""" +from pathlib import Path +import os +import struct +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_stream_check import gfx2hlsl as G + + +def fields(records, stride=4): + return struct.pack('<6I', 4, C.WORDS, 0, stride, records, 0) + + +CONTROLS = ( + ('dispatch-output-texture-token', None, 'an output buffer descriptor is a view token'), + ('dispatch', fields(0), 'an output buffer descriptor has zero records'), + ('dispatch', fields((16 << 20) // 4 + 1), 'an output buffer range is over 16 MiB or not whole dwords'), + ('dispatch', fields(C.WORDS + 4), 'an output range crosses the end of a placed buffer'), + ('dispatch-output-unplaced', None, 'an output is in title memory outside any placed buffer'), + ('dispatch-output-copied', None, 'an output is in a placed buffer that does not alias title memory'), + ('dispatch-output-state', None, "an output buffer's resource was not created in the common state"), + ('dispatch-output-unaligned', None, 'an output buffer range is not 16-byte aligned in its resource'), + ('dispatch-swapped', None, 'an output buffer has no unordered access'), +) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare_case(directory, adapter) + untouched, expected = [C.SENTINEL] * C.WORDS, C.expected('A') + + got, result = dispatch(directory, consumer, env, 'dispatch', probe=True) + print(result.stdout, end='') + assert got == untouched and len(lines(result, 'refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + got, result = dispatch(directory, consumer, env, 'dispatch') + assert got == expected and not lines(result, 'refused'), result.stderr[-3000:] + + for mode, words, reason in CONTROLS: + case_env = dict(env) + if words: + (directory / 'fields').write_bytes(words) + case_env['X2W_TEST_DISPATCH_FIELDS'] = str(directory / 'fields') + got, result = dispatch(directory, consumer, case_env, mode) + name = mode if not words else f'{mode} fields {struct.unpack("<6I", words)[3:5]}' + assert got == untouched, f'{name}: a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + assert len(refused) == 1 and refused[0].endswith('refused: ' + reason), f'{name}:\n{result.stderr[-3000:]}' + assert len(census) == 3 and census[1].endswith(f'reason "{reason}": 1 keys, 1 dispatches'), (name, census) + if mode == 'dispatch-output-state': # the buffer is aliased, so only its state is refused + placed = [line for line in lines(result, 'Device::slot133') if ' state=0x8 ' in line] + assert len(placed) == 1 and '-> 0x00000000 aliased ' in placed[0], (name, placed) + print(f'startup_compute_dispatch_output: PASS on {adapter} (all {C.WORDS} words match; {len(CONTROLS)} outputs ' + 'refused, each with its own reason and an untouched output)') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_texture_check.py b/tests/startup_compute_dispatch_texture_check.py new file mode 100644 index 0000000000..1c7543bc95 --- /dev/null +++ b/tests/startup_compute_dispatch_texture_check.py @@ -0,0 +1,579 @@ +"""Translated compute programs with 2D texture views, dispatched through the stand-in's command list (slot 14). + +usage: startup_compute_dispatch_texture_check.py <startup_stream_consumer> <dxc> <warp|hardware> [two-mips] + +Texture output: the consumer creates the image store program of startup_compute_image_store_d16_check.py as a +device slot 67 pipeline, fills a 32x8 RGBA16_FLOAT texture with sentinel halves, creates an unordered access view of +it at table byte 64 (device slot 19), records Dispatch(2, 1, 1) and copies the texture to a readback buffer. Four +runs share one cache: + +1. before translation: refused with "no translation", every half keeps its sentinel; +2. after gfx2hlsl.py --pending with DXC: the 1024 halves equal mip 0 of the fixture's CPU reference (64 changed); +3. texture-store-none (no Dispatch recorded): every half keeps its sentinel; +4. texture-store-denied (a texture without unordered access, whose view the stand-in does not create): refused + with one logged reason, every half keeps its sentinel. +A fifth run binds the same program under a manifest edited to declare no entry values. +The 1D and 3D float texture cases check mip-one readback, a mismatched view, and an invalid 3D W range. + +Texture input: case A of startup_gfx2hlsl_compute_check.py with a level-zero sample of a 2D texture XORed into the +stored word (a static sampler, a texture view at table byte 64). The consumer adds a 1x1 RGBA8 texture whose red +is 1.0 and a shader resource view of it (device slot 18). After translation all 320 words equal the case's +expectation XOR the bits of 1.0f; dispatch-sampled-unbound (no view created) is refused with one logged reason and +every word keeps the sentinel. + +Filtered input: the texture input case with a constant wrap, linear sampler that the translator writes as `smpl` +and a 2x1 texture (dispatch-sampled-2x1): red 0.5 at the left edge. The same program with the manifest's sampler +changed to clamp reads red 0 (the control); an `smpheap` line is refused with its reason. + +Compared input: case A with a level-zero comparison sample (image_sample_c_lz) under a constant point, clamp, LESS +sampler that the translator writes as `smpc`, and a 2x1 R32_FLOAT texture of depths 1.0 and 2.5 +(dispatch-sampled-depth). The reference is the thread's z id and u its x id, so the 288 written words hold both +outcomes; all 320 words equal a CPU model of the comparison. The same program with the manifest's function changed +to GREATER matches the GREATER model (the control). + +The two-mips mode writes two different patterns through separate UAVs of the same texture, then swaps the views. +Exit 77 when the adapter is not available. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +import startup_compute_image_store_d16_check as S +import startup_gfx2hlsl_compute_check as C +import startup_gfx2hlsl_image_store_3d1d_check as V +from startup_compute_dispatch_check import lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + + +def run(directory, consumer, env, mode, layout): + out = directory / 'out.bin' + out.unlink(missing_ok=True) + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', mode] + result = subprocess.run(args, env=dict(env, X2W_TEST_DISPATCH_OUT=str(out)), capture_output=True, text=True) + if result.returncode == 77: + print(result.stdout, end='') + sys.exit(77) + assert result.returncode == 0, f'{mode}: consumer exit {result.returncode}\n{result.stderr[-3000:]}' + return list(struct.unpack(layout, out.read_bytes())), result + + +def translate(cache, dxc, key): + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, capture_output=True, + text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + + +def clean(result): + assert not lines(result, 'refused'), result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + layer = lines(result, 'x2w-d3d12 debug layer: ') + return 'enabled, no error message' if layer and '0x00000000' in layer[0] else 'unavailable' + + +def store(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + assert S.fixture.GROUP == (4, 2, 1) and S.fixture.GROUPS == 2, 'the consumer hard-codes Dispatch(2, 1, 1)' + (directory / 'program').write_bytes(S.fixture.WORDS) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(S.fixture.GROUP, S.RSRC2)) + reference = S.fixture.reference() + halves = 32 * 8 * 4 # mip 0 comes first in both halves of the reference + untouched, expected = reference[:halves], reference[len(reference) // 2:][:halves] + assert sum(a != b for a, b in zip(untouched, expected)) == 64 + layout = '<%dH' % halves + + got, result = run(directory, consumer, env, 'texture-store', layout) + print(result.stdout, end='') + assert got == untouched, 'a Dispatch without a translation wrote the texture' + assert len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'texture-store', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'half=%d got=%04x expected=%04x (%d halves differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + layer = clean(result) + + got, result = run(directory, consumer, env, 'texture-store-none', layout) + assert got == untouched and not lines(result, 'Dispatch('), 'the texture changed without a Dispatch' + + got, result = run(directory, consumer, env, 'texture-store-denied', layout) + assert got == untouched, 'a refused Dispatch wrote the texture' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and 'an output texture view was not created on the desktop' in refused[0], result.stderr[-3000:] + + # A refused creation over a descriptor that holds a live view keeps that view: the Dispatch still writes the texture. + got, result = run(directory, consumer, env, 'texture-store-occupied', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'occupied slot: half=%d (%d halves differ)\n%s' % (wrong[0], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + + # The same when the live token reached the slot by a memory copy in title memory instead of a creation there. + got, result = run(directory, consumer, env, 'texture-store-copied', layout) + wrong = [i for i in range(halves) if got[i] != expected[i]] + assert not wrong, 'copied token: half=%d (%d halves differ)\n%s' % (wrong[0], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + + # Refusals the runtime already had, each with its one logged reason and an untouched texture: an integer view + # format, another manifest version, another stage, and (with a manifest line added here for a view the consumer + # creates) the output texture named as an input too. + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + for mode, old, new, reason in ( + ('texture-store-uint', '', '', 'an output texture format is not a float or normalized one'), + ('texture-store', 'x2w-manifest 2', 'x2w-manifest 3', 'manifest version'), + ('texture-store', 'stage cs', 'stage ps', 'not a compute manifest'), + ('texture-store-self', 'uav 0 tex2d', 'srv 0 tex2d table 1 0' + chr(10) + 'uav 0 tex2d', + 'an output texture is also an input of the dispatch')): + assert not old or original.count(old) == 1, original + manifest.write_bytes(original.replace(old, new).encode() if old else original.encode()) + got, result = run(directory, consumer, env, mode, layout) + refused = lines(result, 'refused: ') + assert got == untouched and len(refused) == 1 and refused[0].endswith('refused: ' + reason), ( + mode, reason, refused, result.stderr[-3000:]) + manifest.write_bytes(original.encode()) + + # The same compiled program under a manifest without entry values (the program reads none of its three): the + # runtime binds no constants. The manifest is edited here; the translator writes `ud 0` for a root without them. + manifest = cache / f'{key:016x}.txt' + kept = [line for line in manifest.read_text().splitlines() if not line.startswith('udsrc ')] + assert len(kept) == 5 and kept[3] == 'ud 3', kept + manifest.write_bytes(('\n'.join(kept).replace('ud 3', 'ud 0') + '\n').encode()) + got, result = run(directory, consumer, env, 'texture-store', layout) + assert got == expected and lines(result, 'translated: 0 entry values, 0 inputs, 1 outputs'), result.stderr[-3000:] + clean(result) + print(f'texture output: all {halves} halves match after translation (64 changed) and without entry values; ' + f'untouched before translation, without a Dispatch and for a refused view; debug layer: {layer}') + + +# A second descriptor, at table byte 128, and a different color in v14. +SECOND_STORE = bytes.fromhex( + '06080cf4 800000fa ' # s_load_dwordx8 s[32:39], s[12:13], 0x80 + '7fc08cbf ' # s_waitcnt lgkmcnt(0) + 'ff021c7e 00bc0044 ' # v_mov_b32_e32 v14, 0x4400bc00 + '080f20f0 080e0880' # image_store v[14:15], v[8:9], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_2D d16 +) +MIPS = ((32, 8), (16, 4)) + + +def mip_reference(colors): + halves = [] + for mip, ((width, height), color) in enumerate(zip(MIPS, colors, strict=True)): + for y in range(height): + for x in range(width): + sentinel = 0x5000 + 0x400 * mip + 4 * (y * width + x) + if color is None or x >= 8 or y >= 2: + halves.extend(range(sentinel, sentinel + 4)) + else: + tag = 8 * y + x + rg = (0x3c00 + tag, 0xc000 + tag) if color == 0 else (0xbc00, 0x4400) + halves.extend((*rg, tag, 0x8000 + tag)) + return halves + + +def check_mips(label, got, expected): + start = 0 + for mip, (width, height) in enumerate(MIPS): + for index in range(width * height * 4): + actual, wanted = got[start + index], expected[start + index] + pixel, channel = divmod(index, 4) + y, x = divmod(pixel, width) + assert actual == wanted, (f'{label}: mip={mip} x={x} y={y} channel={channel} ' + f'expected={wanted:04x} actual={actual:04x}') + start += width * height * 4 + + +def store_two_mips(directory, consumer, dxc, env): + cache, base = prepare(directory) + root = C.root_blob(3, table_range=True) + (directory / 'compute_root').write_bytes(root) + env = dict(base, **env, X2W_TEST_COMPUTE_ROOT=str(directory / 'compute_root')) + code = S.PREFIX + S.STORE + SECOND_STORE + S.END + pipeline = G.ComputePipeline(code, root, S.RSRC2, S.fixture.GROUP) + outputs = [line for line in pipeline.manifest().splitlines() if line.startswith('uav ')] + assert outputs == [ + 'uav 0 tex2d float table 1 64 channels 4', + 'uav 1 tex2d float table 1 128 channels 4', + ], outputs + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(S.fixture.GROUP, S.RSRC2)) + untouched = mip_reference((None, None)) + layout = '<%dH' % len(untouched) + + got, result = run(directory, consumer, env, 'texture-store-mips', layout) + print(result.stdout, end='') + check_mips('missing translation', got, untouched) + assert len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + expected = mip_reference((0, 1)) + got, result = run(directory, consumer, env, 'texture-store-mips', layout) + check_mips('ordered views', got, expected) + assert len(lines(result, 'translated: 3 entry values, 0 inputs, 2 outputs')) == 1, result.stderr[-3000:] + layer = clean(result) + + got, result = run(directory, consumer, env, 'texture-store-mips-swapped', layout) + check_mips('swapped views', got, mip_reference((1, 0))) + clean(result) + changed = sum(a != b for a, b in zip(got, expected, strict=True)) + assert changed == 64, changed + print(f'two mip outputs: {len(got)} halves match; swapping views changes {changed} halves; debug layer: {layer}') + + +def store_3d1d(directory, consumer, dxc, env, form): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(3, table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(V.program(form)) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(V.group(form), V.A.RSRC2)) + + volume = form != 'line' + mode = 'texture-volume' if volume else 'texture-line' + width, height, depth = 32, 8 if volume else 1, 6 if volume else 1 + plane_words = width * height * 4 + initial = [0xbf000000 | (z << 12) | i for z in range(depth) for i in range(plane_words)] + expected = initial.copy() + for y in range(V.group(form)[1]): + # The 3D view starts at W slice 1 and the shader writes relative z=1. + start = (2 * plane_words if volume else 0) + y * width * 4 + expected[start:start + 32] = V.VALUES * 8 + layout = '<%dI' % len(initial) + got, result = run(directory, consumer, env, mode, layout) + assert got == initial and len(lines(result, 'Dispatch(2, 1, 1) refused: no translation')) == 1 + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + manifest = (cache / f'{key:016x}.txt').read_text().splitlines() + dim = '3d' if volume else '1d' + assert f'uav 0 tex{dim} float table 1 64 channels 4' in manifest, manifest + got, result = run(directory, consumer, env, mode, layout) + assert len(lines(result, 'Dispatch(2, 1, 1) translated')) == 1, result.stderr[-3000:] + assert got == expected, (form, sum(a != b for a, b in zip(got, expected, strict=True))) + clean(result) + + mismatch = initial[:32 * 8 * 4] if volume else [0xbf000000 | i for i in range(32 * 8 * 4)] + cases = [('texture-array-2d', mismatch, f'an output texture view or resource is not {dim.upper()}')] + if volume: + # Manual mutant: skipping the mip-relative W-range check must fail the required refusal. + cases.append(('texture-volume-bad-w', initial, 'an output 3D texture W range is outside the mip')) + else: + # Manual mutant: dropping the 1D mip check before `created` must fail this required refusal. + cases.append(('texture-line-bad-mip', initial, 'an output 1D texture mip is outside the resource')) + for bad_mode, untouched, reason in cases: + got, result = run(directory, consumer, env, bad_mode, '<%dI' % len(untouched)) + refusal = lines(result, 'Dispatch(2, 1, 1) refused:') + assert len(refusal) == 1 and refusal[0].endswith(reason), result.stderr[-3000:] + assert got == untouched and not lines(result, 'Dispatch(2, 1, 1) translated') + print(f'{form}: {len(expected)} mip-one words match; incompatible views refused with sentinels intact') + + +# v_xor_b32 v5, v5, v12: the assembled `v_xor_b32 v5, v5, v6` of case A with its second source register changed +# (not assembled by llvm-mc here; the translation below is checked to read it as written). +XOR = 'v_xor_b32 v5, v5, v12' +SAMPLED = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40', + 'image_sample_lz v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D', XOR) + + +def sample(directory, consumer, dxc, env): + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, words, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + assert words[96:100].hex() == '050d0a3a', 'case A no longer holds v_xor_b32 v5, v5, v6 at byte 96' + C.SPLICE[XOR] = '05190a3a' + code = C.splice(*SAMPLED) + pipeline = C.translate('A', code=code) + assert 'v5 = v5 ^ v12;' in pipeline.hlsl_cs() and pipeline.manifest().endswith( + 'srv 0 buf table 1 0\nsrv 1 tex2d table 1 64\nuav 0 table 1 16\nsmp 0 0x0 0x0 0x0 0x0\n'), pipeline.manifest() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + one = struct.unpack('<I', struct.pack('<f', 1.0))[0] + written = 24 * 3 * 2 * 2 # threads per group times groups; the words past them keep the sentinel + untouched, plain = [C.SENTINEL] * C.WORDS, C.expected('A') + assert plain[written:] == untouched[written:] + expected = [word ^ one for word in plain[:written]] + plain[written:] + layout = '<%dI' % C.WORDS + + got, result = run(directory, consumer, env, 'dispatch-sampled', layout) + assert got == untouched, 'a Dispatch without a translation wrote the output' + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'dispatch-sampled', layout) + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + layer = clean(result) + + got, result = run(directory, consumer, env, 'dispatch-sampled-compute', layout) # a compute list and queue + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + clean(result) + + got, result = run(directory, consumer, env, 'dispatch-sampled-unbound', layout) + assert got == untouched, 'a refused Dispatch wrote the output' + refused = lines(result, 'refused: ') + assert len(refused) == 1 and 'an input texture entry is not the token of a shader resource view' in refused[0], \ + result.stderr[-3000:] + print(f'texture input: all {C.WORDS} words match after translation; untouched before translation and without a ' + f'view; debug layer: {layer}') + + +# The texture input case with a constant sampler instead of the zero one: s21 MAX_LOD 12, s22 linear min, mag and mip +# filters, s20 wrap in U, V and W. A mip filter makes the translator write it as `smpl` (its LOD clamp carried over). +WRAP_LINEAR = (0x0, 0xc00000, 0x18500000, 0x0) +LOD_SAMPLED = SAMPLED[:2] + ('s_mov_b32 s21, 0xc00000', 's_mov_b32 s22, 0x18500000') + SAMPLED[2:] + + +def filtered(directory, consumer, dxc, env): + """The sampler bound is the manifest's: a 2x1 texture (red 0, 1.0) read at the left edge (the coordinates are the + bits of the thread ids, 0 or a denormal) gives red 0.5 only through a linear filter that wraps; clamp gives 0.""" + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, _, rsrc2, group, _ = C.CASES['A'] + C.SPLICE.update({XOR: '05190a3a', LOD_SAMPLED[2]: 'ff0395be0000c000', LOD_SAMPLED[3]: 'ff0396be00005018'}) + code = C.splice(*LOD_SAMPLED) + line = 'smpl 0 %s' % ' '.join('0x%x' % w for w in WRAP_LINEAR) + assert C.translate('A', code=code).manifest().endswith(line + '\n'), C.translate('A', code=code).manifest() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + written = 24 * 3 * 2 * 2 + plain = C.expected('A') + layout = '<%dI' % C.WORDS + + def reds(got): + assert got[written:] == plain[written:], 'a word past the threads changed' + return {struct.unpack('<f', struct.pack('<I', g ^ p))[0] for g, p in zip(got[:written], plain[:written])} + + got, result = run(directory, consumer, env, 'dispatch-sampled-2x1', layout) + assert got == [C.SENTINEL] * C.WORDS, 'a Dispatch without a translation wrote the output' + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'dispatch-sampled-2x1', layout) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + red = reds(got) + # 8-bit filter weights may round the half: one step of an 8-bit channel is the tolerance. + assert len(red) == 1 and abs(next(iter(red)) - 0.5) <= 1 / 255, (sorted(red), result.stderr[-3000:]) + layer = clean(result) + + # Control: the same program under the manifest's sampler changed to clamp in U, V and W reads red 0, which the + # check above refuses; a sampler heap table stays refused with its reason. + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + assert original.count(line) == 1, original + manifest.write_bytes(original.replace(line, line.replace('smpl 0 0x0 ', 'smpl 0 0x92 ')).encode()) + got, result = run(directory, consumer, env, 'dispatch-sampled-2x1', layout) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and reds(got) == {0.0}, result.stderr[-3000:] + manifest.write_bytes(original.replace(line, line + '\nsmpheap 2048 1 fallback 2047').encode()) + got, result = run(directory, consumer, env, 'dispatch-sampled-2x1', layout) + refused = lines(result, 'refused: ') + assert got == [C.SENTINEL] * C.WORDS and len(refused) == 1 and refused[0].endswith( + 'refused: a sampler from the sampler heap'), (refused, result.stderr[-3000:]) + print(f'filtered input: an smpl wrap and linear sampler reads red 0.5 at the left edge of a 2x1 texture; the same ' + f'program with a clamp sampler reads 0; a heap sampler is refused; debug layer: {layer}') + + +# The texture input case with a comparison sample: s20 clamp in U and V, TRUNC_COORD and LESS (point filters, LOD +# range 0). The reference is v7 = float(thread id z), u is v8 = float(thread id x) and v is v9 = 0. The five new +# instructions are not assembled by llvm-mc here; the decoder is checked to read them as written. +POINT_LESS = 2 | 2 << 3 | 1 << 27 | 1 << 12 +POINT_GREATER = POINT_LESS ^ 1 << 12 | 4 << 12 +COMPARED = SAMPLED[:2] + ('s_mov_b32 s20, 0x%x' % POINT_LESS, SAMPLED[2], 'v_cvt_f32_u32_e32 v7, v2', + 'v_cvt_f32_u32_e32 v8, v0', 'v_mov_b32_e32 v9, 0', + 'image_sample_c_lz v12, v[7:9], s[24:31], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'v_xor_b32_e32 v5, v5, v12') + + +def compared(directory, consumer, dxc, env): + """The sampler bound is the manifest's `smpc` one: a 2x1 R32_FLOAT texture (1.0, 2.5) is compared at u = 0 (the + left texel) or u = 1 (clamped to the right one) with the references 0.0 to 3.0. A word is XORed with the bits of + 1.0f where the CPU model of the comparison passes and is left as case A wrote it where the model fails.""" + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, _, rsrc2, group, _ = C.CASES['A'] + C.SPLICE.update({COMPARED[2]: 'ff0394be' + struct.pack('<I', POINT_LESS).hex(), COMPARED[4]: '020d0e7e', + COMPARED[5]: '000d107e', COMPARED[6]: '8002127e', COMPARED[7]: '0801bcf0070ca600', + COMPARED[8]: '05190a3a'}) + code = C.splice(*COMPARED) + decoded = [i[3] for i in G.decode(code) if i[0] >= C.STORE_A][:len(COMPARED)] + assert decoded == list(COMPARED), decoded + pipeline = C.translate('A', code=code) + line = 'smpc 0 0x%x 0x0 0x0 0x0' % POINT_LESS + assert 'v12 = U(r1.SampleCmpLevelZero(q0, float2(F(v8), F(v9)), F(v7)));' in pipeline.hlsl_cs() and \ + pipeline.manifest().endswith('srv 1 tex2d table 1 64\nuav 0 table 1 16\n' + line + '\n'), pipeline.manifest() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + one = struct.unpack('<I', struct.pack('<f', 1.0))[0] + written = 24 * 3 * 2 * 2 + plain = C.expected('A') + layout = '<%dI' % C.WORDS + depths = (1.0, 2.5) # the consumer's texels, left and right + + def model(passes): + # Word i is thread (x, y, z) of a 2x3x4 group: i % 24 == x + 2 * y + 6 * z. Reference z, texel x. + assert group == (2, 3, 4) + return [word ^ (one if passes(float(i % 24 // 6), depths[i % 2]) else 0) + for i, word in enumerate(plain[:written])] + plain[written:] + + def match(got, want, result, what): + refused = lines(result, 'refused: ') + assert not refused, f'{what}: {refused[0]}' + wrong = [i for i in range(C.WORDS) if got[i] != want[i]] + assert not wrong, '%s: word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + what, wrong[0], got[wrong[0]], want[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + + less, greater = model(lambda ref, texel: ref < texel), model(lambda ref, texel: ref > texel) + passing = [sum(a != b for a, b in zip(m, plain)) for m in (less, greater)] + differ = sum(a != b for a, b in zip(less, greater)) + assert passing == [144, 108] and differ == 252, (passing, differ) + + got, result = run(directory, consumer, env, 'dispatch-sampled-depth', layout) + assert got == [C.SENTINEL] * C.WORDS, 'a Dispatch without a translation wrote the output' + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'dispatch-sampled-depth', layout) + match(got, less, result, 'smpc LESS') + layer = clean(result) + + # Control: the function is the manifest's. Under GREATER the same program passes where the reference is above + # the texel, a result the check above refuses at 252 words. + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + assert original.count(line) == 1, original + manifest.write_bytes(original.replace(line, 'smpc 0 0x%x 0x0 0x0 0x0' % POINT_GREATER).encode()) + got, result = run(directory, consumer, env, 'dispatch-sampled-depth', layout) + match(got, greater, result, 'smpc GREATER') + clean(result) + print(f'compared input: an smpc point, clamp, LESS sampler passes at 144 of the {written} written words and all ' + f'{C.WORDS} words match the CPU model; the same program under GREATER matches its model (108 pass, 252 ' + f'words differ from LESS); debug layer: {layer}') + + +def uniform_image_load_mip(directory, consumer, dxc, env): + """Compute image_load_mip at uniform coordinates fed into v_readfirstlane_b32 (#2644 T5 follow-up). + + Loads texel (1, 0, mip 0) (red 1.0) of the 2x1 texture via image_load_mip, broadcasts channel 0 with + v_readfirstlane_b32 s20, v12, and XORs s20 into Case A's stored word. Controls: texel (0, 0, mip 0) + (red 0.0) and out-of-range mip 1 at (1, 0) each differ at all 288 written words. + """ + cache, base = prepare(directory) + env = dict(base, **env) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, _, rsrc2, group, _ = C.CASES['A'] + written = 24 * 3 * 2 * 2 + plain = C.expected('A') + one = struct.unpack('<I', struct.pack('<f', 1.0))[0] + expected = [word ^ one for word in plain[:written]] + plain[written:] + layout = '<%dI' % C.WORDS + + C.SPLICE.update({ + 'v_mov_b32_e32 v10, 1': '8102147e', + 'v_mov_b32_e32 v10, 0': '8002147e', + 'v_mov_b32_e32 v11, 0': '8002167e', + 'v_mov_b32_e32 v12, 0': '8002187e', + 'v_mov_b32_e32 v12, 1': '8102187e', + 'image_load_mip v[12:15], v[10:12], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f04f00a0c0600', + 'v_readfirstlane_b32 s20, v12': '0c05287e', + 'v_xor_b32_e32 v5, s20, v5': '140a0a3a', + }) + load_ops = ( + 's_load_dwordx8 s[24:31], s[10:11], 0x40', + 'v_mov_b32_e32 v10, 1', + 'v_mov_b32_e32 v11, 0', + 'v_mov_b32_e32 v12, 0', + 'image_load_mip v[12:15], v[10:12], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D', + 'v_readfirstlane_b32 s20, v12', + 'v_xor_b32_e32 v5, s20, v5', + ) + code = C.splice(*load_ops) + pipe = C.translate('A', code=code) + assert 's20 = v12;' in pipe.hlsl_cs() and 'v5 = s20 ^ v5;' in pipe.hlsl_cs(), pipe.hlsl_cs() + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + + got, result = run(directory, consumer, env, 'dispatch-sampled-2x1', layout) + assert got == [C.SENTINEL] * C.WORDS, 'a Dispatch without a translation wrote the output' + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + translate(cache, dxc, key) + + got, result = run(directory, consumer, env, 'dispatch-sampled-2x1', layout) + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, 'word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + layer = clean(result) + + for tag, ctrl_ops in ( + ('ctrl_x0', (load_ops[0], 'v_mov_b32_e32 v10, 0') + load_ops[2:]), + ('ctrl_mip1', load_ops[:3] + ('v_mov_b32_e32 v12, 1',) + load_ops[4:])): + ctrl_dir = directory / tag + ctrl_cache, ctrl_base = prepare(ctrl_dir) + ctrl_env = dict(env, **ctrl_base) + (ctrl_dir / 'compute_root').write_bytes(C.root_blob(table_range=True)) + ctrl_env['X2W_TEST_COMPUTE_ROOT'] = str(ctrl_dir / 'compute_root') + (ctrl_dir / 'program').write_bytes(C.splice(*ctrl_ops)) + (ctrl_dir / 'data').write_bytes(DATA) + (ctrl_dir / 'state').write_bytes(state_a(group, rsrc2)) + _, ctrl_res = run(ctrl_dir, consumer, ctrl_env, 'dispatch-sampled-2x1', layout) + ctrl_key = int(lines(ctrl_res, 'x2w-draw compute request')[0].split()[3], 16) + translate(ctrl_cache, dxc, ctrl_key) + got_ctrl, ctrl_res = run(ctrl_dir, consumer, ctrl_env, 'dispatch-sampled-2x1', layout) + assert got_ctrl == plain and sum(a != b for a, b in zip(got_ctrl, expected)) == written, ( + tag, ctrl_res.stderr[-3000:]) + clean(ctrl_res) + print(f'uniform image_load_mip + v_readfirstlane_b32: all {C.WORDS} words match texel (1, 0, mip 0); ' + f'x=0 and mip=1 controls each differ at {written} words; debug layer: {layer}') + + +def main(consumer, dxc, adapter, mode=None): + env = dict(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + if mode == 'two-mips': + store_two_mips(directory / 'mips', consumer, dxc, env) + else: + store(directory / 'store', consumer, dxc, env) + for form in V.FORMS: + store_3d1d(directory / form, consumer, dxc, env, form) + sample(directory / 'sample', consumer, dxc, env) + filtered(directory / 'filtered', consumer, dxc, env) + compared(directory / 'compared', consumer, dxc, env) + uniform_image_load_mip(directory / 'uniform_image_load_mip', consumer, dxc, env) + print(f'startup_compute_dispatch_texture: PASS on {adapter}') + + +if __name__ == '__main__': + if len(sys.argv) not in (4, 5) or sys.argv[3] not in ('warp', 'hardware') or sys.argv[4:] not in ([], ['two-mips']): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_dispatch_texture_dims_check.py b/tests/startup_compute_dispatch_texture_dims_check.py new file mode 100644 index 0000000000..2081ea54f2 --- /dev/null +++ b/tests/startup_compute_dispatch_texture_dims_check.py @@ -0,0 +1,167 @@ +"""Translated compute programs reading 1D, 2D-array and 3D texture views through the stand-in's Dispatch (slot 14). + +usage: startup_compute_dispatch_texture_dims_check.py <startup_stream_consumer> <dxc> <warp|hardware> + +Case A of startup_gfx2hlsl_compute_check.py with one image_load (for 1D an image_sample_lz at the texel's +center, because gfx2hlsl lowers no 1D image_load) spliced before its store: the texel read is XORed into every +stored word. The program's manifest names the dimension of its texture input (`srv 1 tex1d`, +`tex2da` or `tex3d`, table byte 64). The consumer (dispatch-texdim-<1d|2da|3d>) uploads a described R32_FLOAT +texture, texel (x + 4 y + 16 slice) = 0.25 * (index + 1), subresource by subresource, and creates its view at table byte 64 +(device slot 18): + +- 1d: eight texels, the program reads x = 5 (1.5); +- 2da: 4x4 with six slices, the view starts at slice 1, the program reads x = 1, y = 2, relative slice 2, which + is slice 3 of the texture (14.5); +- 3d: 4x4x4, the program reads x = 3, y = 1, z = 2 (10.0). + +Per dimension: before translation the dispatch is refused with "no translation" and writes nothing; after +gfx2hlsl.py --pending with DXC all 320 words equal case A's words XORed with the texel's bits on the 288 written +words (the rest keep the sentinel). Controls, each refused with one logged reason and an untouched output: +the title's view is a 2D view of a 2D texture (-mismatch), the view has no description (-undescribed), the view +has a ResourceMinLODClamp of 1.0, which does not fit as address_view_fits reads views (-clamped; a view outside the +texture would remove the device when the title creates it), and the published manifest line rewritten to tex2d (and, for +a second mutant, to another non-2D dimension): the runtime must read the manifest's dimension, not the title's. +Exit 77 when the adapter is not available. +""" +from pathlib import Path +import struct +import sys +import tempfile + +import startup_compute_dispatch_texture_check as T +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_stream_check import gfx2hlsl as G + +LOAD = 'image_load v12, %s, s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_%s' +# MIMG: dword 0 is 0xf0000000 | dmask << 8 | dim << 3 (1D 0, 3D 2, 2D array 5); dword 1 holds vaddr 8, vdata 12 and +# srsrc 24 / 4 in its three low bytes. The decoder below must read each word back as the text of its dictionary key. +DIM_FIELD = {'1D': 0, '3D': 2, '2D_ARRAY': 5} + +# name: (manifest word, image dim, texel coordinates, expected texel value, refusal word for the view, manifest line) +KINDS = { + '1d': ('tex1d', '1D', (5,), 1.5, '1D', 'srv 1 tex1d table 1 64'), + '2da': ('tex2da', '2D_ARRAY', (1, 2, 2), 14.5, '2D array', 'srv 1 tex2da table 1 64'), + '3d': ('tex3d', '3D', (3, 1, 2), 10.0, '3D', 'srv 1 tex3d table 1 64'), +} +# What the consumer holds: texel (x, y, slice) is 0.25 * (x + 4 y + 16 slice + 1); the 2D-array view starts at slice 1. +FIRST_SLICE = {'1d': 0, '2da': 1, '3d': 0} + + +def texel(kind, coordinates): + x, y, z = (*coordinates, 0, 0)[:3] + return 0.25 * (x + 4 * y + 16 * (z + FIRST_SLICE[kind]) + 1) + + +def vmov(register, value): + return bytes([0x80 + value, 0x02, register * 2, 0x7e]).hex() # v_mov_b32_e32 v<register>, <inline constant> + + +def program(kind): + _, dim, coordinates, _, _, _ = KINDS[kind] + C.SPLICE.update({T.XOR: '05190a3a', 's_waitcnt vmcnt(0)': '703f8cbf'}) + if dim == '1D': + # gfx2hlsl lowers a 1D image only as image_sample, _lz or _l (no image_load), so the texel is read by a + # level-zero sample at its center under the all-zero (wrap, point) sampler of the sample test. + center = struct.unpack('<I', struct.pack('<f', (coordinates[0] + 0.5) / 8))[0] + move = 'v_mov_b32 v8, 0x%08x' % center + load = 'image_sample_lz v12, v8, s[24:31], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_1D' + C.SPLICE[move] = 'ff02107e' + struct.pack('<I', center).hex() + C.SPLICE[load] = '00019cf0' '080ca600' # image_sample_lz: dword 0 as the 2D word of the sample test, dim 0 + steps = ['s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40', move, + 's_waitcnt lgkmcnt(0)', load, 's_waitcnt vmcnt(0)', T.XOR] + else: + registers = 'v[8:%d]' % (7 + len(coordinates)) + load = LOAD % (registers, dim) + movs = ['v_mov_b32 v%d, %d' % (8 + i, value) for i, value in enumerate(coordinates)] + C.SPLICE.update({'v_mov_b32 v%d, %d' % (8 + i, value): vmov(8 + i, value) for i, value in enumerate(coordinates)}) + C.SPLICE[load] = bytes([DIM_FIELD[dim] << 3, 1, 0, 0xf0]).hex() + '080c0600' + steps = ['s_load_dwordx8 s[24:31], s[10:11], 0x40', *movs, 's_waitcnt lgkmcnt(0)', load, 's_waitcnt vmcnt(0)', + T.XOR] + code = C.splice(*steps) + decoded = [i[3].replace('_e32', '') for i in G.decode(code) if i[0] >= C.STORE_A][:len(steps)] + assert decoded == [step.replace('_e32', '') for step in steps], decoded + return code + + +def check(directory, consumer, dxc, kind, adapter): + name, dim, coordinates, value, refusal, line = KINDS[kind] + assert texel(kind, coordinates) == value, (kind, texel(kind, coordinates)) + cache, base = prepare(directory) + env = dict(base, X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + _, _, rsrc2, group, groups = C.CASES['A'] + assert groups == (3, 2, 2) and (C.KEY, C.STRIDE) == (0x01234567, 0x9e3779b9), 'the consumer hard-codes case A' + code = program(kind) + (directory / 'program').write_bytes(code) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a(group, rsrc2)) + bits = struct.unpack('<I', struct.pack('<f', value))[0] + written = 24 * 3 * 2 * 2 # threads per group times groups; the words past them keep the sentinel + untouched, plain = [C.SENTINEL] * C.WORDS, C.expected('A') + assert plain[written:] == untouched[written:] + expected = [word ^ bits for word in plain[:written]] + plain[written:] + layout = '<%dI' % C.WORDS + mode = 'dispatch-texdim-' + kind + + got, result = T.run(directory, consumer, env, mode, layout) + assert got == untouched, 'a Dispatch without a translation wrote the output' + assert len(lines(result, 'Dispatch(3, 2, 2) refused: no translation')) == 1, result.stderr[-3000:] + key = int(lines(result, 'x2w-draw compute request')[0].split()[3], 16) + T.translate(cache, dxc, key) + manifest = cache / f'{key:016x}.txt' + original = manifest.read_text() + assert line in original.splitlines() and 'srv 0 buf table 1 0' in original.splitlines(), original + + got, result = T.run(directory, consumer, env, mode, layout) + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, '%s: word=%d got=%08x expected=%08x (%d words differ)\n%s' % ( + kind, wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + layer = T.clean(result) + assert sum(a != b for a, b in zip(got, plain)) == written, 'the texel must change every written word' + + def refused(label, control_mode, reason): + got, result = T.run(directory, consumer, env, control_mode, layout) + logged = lines(result, 'refused: ') + assert got == untouched and len(logged) == 1 and logged[0].endswith('refused: ' + reason), ( + label, logged, result.stderr[-3000:]) + assert not lines(result, 'Dispatch(3, 2, 2) translated'), label + errors = [l for l in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in l or ' sev=1 ' in l] + assert not errors, (label, errors[0]) + + refused('view dimension', mode + '-mismatch', f'an input texture view is not {refusal}') + refused('no description', mode + '-undescribed', f'an input {refusal} texture has no recorded view description') + refused('view does not fit', mode + '-clamped', 'an input texture view does not fit its texture') + + # Mutants: the dimension is the manifest's. The title's view is of this kind, so another name must be refused. + for other in ('tex2d', 'tex1d' if kind != '1d' else 'tex3d'): + reason = {'tex1d': 'an input texture view is not 1D', 'tex2d': 'an input texture view is not 2D', + 'tex3d': 'an input texture view is not 3D'}[other] + assert original.count(line) == 1 + manifest.write_bytes(original.replace(line, line.replace(name, other)).encode()) + refused('manifest ' + other, mode, reason) + manifest.write_bytes(original.encode()) + got, result = T.run(directory, consumer, env, mode, layout) + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1, result.stderr[-3000:] + print(f'{adapter}: {kind}: {C.WORDS} words match the texel {value} ({written} written words changed); ' + f'view of another dimension, no description, a view that does not fit and a manifest line rewritten to tex2d or ' + f'another dimension are each refused with the output untouched; debug layer: {layer}', flush=True) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as temporary: + for kind in KINDS: + check(Path(temporary) / kind, consumer, dxc, kind, adapter) + print(f'startup_compute_dispatch_texture_dims: PASS on {adapter}') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit(__doc__) + main(*sys.argv[1:]) diff --git a/tests/startup_compute_global_load_check.py b/tests/startup_compute_global_load_check.py new file mode 100644 index 0000000000..71424bacc1 --- /dev/null +++ b/tests/startup_compute_global_load_check.py @@ -0,0 +1,826 @@ +"""Compute 32-bit GLOBAL saddr load (`global_load_dword`) in tools/startup/gfx2hlsl.py (Refs #2618, #2022). + + (no arguments) or controls translation, encoding and refusal controls, pure Python + binary <llvm-mc> reassemble every fixture source and compare machine words + decode <libLLVM> disassemble GLOBAL test words with LLVM 15 and compare strings + dispatch <dxc> <offscreen_check> <adapter> translate, compile DXC cs_6_0, dispatch and verify GPU readback + +All instruction bytes below are constructed from the RDNA 2 / tools/disasm_rdna2.py bit layouts (no game bytes). +""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) + +import disasm_rdna2 as D # noqa: E402 +from startup_gfx2hlsl_compute_check import G, MASK, SENTINEL, TGID_X, WORDS, assemble, refused # noqa: E402 + +GLOBAL_LOAD_UBYTE = 0x08 +GLOBAL_LOAD_SBYTE = 0x09 +GLOBAL_LOAD_USHORT = 0x0a +GLOBAL_LOAD_SSHORT = 0x0b +GLOBAL_LOAD_DWORD = 0x0c +GLOBAL_LOAD_DWORDX2 = 0x0d +GLOBAL_LOAD_DWORDX4 = 0x0e +GLOBAL_LOAD_DWORDX3 = 0x0f +GLOBAL_STORE_DWORD = 0x1c +GLOBAL_ATOMIC_ADD = 0x32 + +# s0-s3 unmodelled, s4-s5 = two root constants (ud0, ud1), s[6:7] = root SRV (param 1), s8 = table (param 2); +# s9 = gid.x (TGID_X), v0 = tid.x. +USER9 = 9 << 1 +RSRC2_A = USER9 | TGID_X +GROUP_A = (8, 1, 1) +GROUPS_A = (2, 1, 1) +INACTIVE_TAG = 0x77000000 +PRELOAD_TAG = 0x66000000 + + +def root_blob_cs(*, extra_root_srv=False, flags=0): + """DXBC RTS0 container: + param 0 = 2 root constants (s4-s5), + param 1 = root SRV descriptor (s[6:7]), + optional param 2 = second root SRV descriptor (s[8:9]), + final param = descriptor table with 1 UAV slot. + """ + nparams = 4 if extra_root_srv else 3 + poff = 24 + coff = poff + 12 * nparams + # Root descriptor payload in RTS0: (ShaderRegister, RegisterSpace) = 8 bytes. + srv1_off = coff + 12 + srv2_off = srv1_off + 8 + toff = (srv2_off + 8) if extra_root_srv else (srv1_off + 8) + params = [ + struct.pack('<3I', 1, 0, coff), # 32BIT_CONSTANTS + struct.pack('<3I', 3, 0, srv1_off), # SRV root descriptor + ] + if extra_root_srv: + params.append(struct.pack('<3I', 3, 0, srv2_off)) + params.append(struct.pack('<3I', 0, 0, toff)) # DESCRIPTOR_TABLE + payload = struct.pack('<3I', 0, 0, 2) + struct.pack('<2I', 0, 0) + if extra_root_srv: + payload += struct.pack('<2I', 1, 0) + payload += struct.pack('<2I', 0, toff + 8) + rts0 = struct.pack('<6I', 2, nparams, poff, 0, toff + 8, flags) + b''.join(params) + payload + part = b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + return b'DXBC' + bytes(16) + struct.pack('<III', 1, 36 + len(part), 1) + struct.pack('<I', 36) + part + + +def encode_sop1(op, sdst, ssrc0, *, lit=None): + w0 = 0xbe800000 | ((sdst & 0x7f) << 16) | ((op & 0xff) << 8) | (ssrc0 & 0xff) + return struct.pack('<II', w0, lit & MASK) if lit is not None else struct.pack('<I', w0) + + +def encode_sop2(op, sdst, ssrc0, ssrc1, *, lit=None): + w0 = 0x80000000 | ((op & 0x7f) << 23) | ((sdst & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff) + return struct.pack('<II', w0, lit & MASK) if lit is not None else struct.pack('<I', w0) + + +def encode_sopp(op, simm16=0): + return struct.pack('<I', 0xbf800000 | ((op & 0x7f) << 16) | (simm16 & 0xffff)) + + +def encode_smem(op, sdata, sbase, *, soffset=0x7d, imm=0): + w0 = (0b111101 << 26) | ((op & 0xff) << 18) | ((sdata & 0x7f) << 6) | ((sbase >> 1) & 0x3f) + w1 = ((soffset & 0x7f) << 25) | (imm & 0x1fffff) + return struct.pack('<II', w0, w1) + + +def encode_vop1(op, vdst, src0, *, lit=None): + w0 = 0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff) + return struct.pack('<II', w0, lit & MASK) if lit is not None else struct.pack('<I', w0) + + +def encode_vop2(op, vdst, src0, vsrc1, *, lit=None): + w0 = ((op & 0x3f) << 25) | ((vdst & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff) + return struct.pack('<II', w0, lit & MASK) if lit is not None else struct.pack('<I', w0) + + +def encode_vopc(op, src0, vsrc1): + w0 = 0x7c000000 | ((op & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff) + return struct.pack('<I', w0) + + +def encode_vop3a(op, vdst, src0, src1, src2=0): + w0 = (0b110101 << 26) | ((op & 0x3ff) << 16) | (vdst & 0xff) + w1 = ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff) + return struct.pack('<II', w0, w1) + + +def encode_mubuf(op, vdata, vaddr, srsrc, soffset_enc=0x80, *, offen=True, offset=0): + w0 = 0xe0000000 | ((op & 0x7f) << 18) | (int(offen) << 12) | (offset & 0xfff) + w1 = ((soffset_enc & 0xff) << 24) | (((srsrc // 4) & 0x1f) << 16) | ((vdata & 0xff) << 8) | (vaddr & 0xff) + return struct.pack('<II', w0, w1) + + +def encode_global(op, vdst, addr, saddr, *, seg=2, data=0, offset=0, glc=0, slc=0, dlc=0, lds=0, nv=0, rsvd25=0): + """Construct an 8-byte RDNA 2 FLAT / SCRATCH / GLOBAL instruction from its hardware fields.""" + w0 = (0xdc000000 | ((rsvd25 & 1) << 25) | ((op & 0x7f) << 18) | ((slc & 1) << 17) + | ((glc & 1) << 16) | ((seg & 0x3) << 14) | ((lds & 1) << 13) | ((dlc & 1) << 12) | (offset & 0xfff)) + w1 = (((vdst & 0xff) << 24) | ((nv & 1) << 23) | ((saddr & 0x7f) << 16) + | ((data & 0xff) << 8) | (addr & 0xff)) + return struct.pack('<II', w0, w1) + + +# Kernel A: 2 groups x 8 threads (16 lanes). Varies per-lane vaddr via runtime root constants (ud0=bias, ud1=stride) +# and exercises four global_load_dword forms across distinct scalar base states: +# 1. v5: direct entry root pointer s[6:7] with vdst == vaddr register aliasing (base + 0); +# 2. v6: out-of-place literal-advanced scalar base s[20:21] = s[6:7] + 48 (base + 48, +12 words); +# 3. v7: in-place second advance s[20:21] += 32 (base + 80) with negative signed immediate offset:-12 and +# cache flags glc/slc/dlc (base + 68, +17 words); +# 4. v8: s_mov_b64 copy s[22:23] = s[6:7] with positive immediate offset:8 under partial EXEC (tid.x < 5 -> +# base + 8, +2 words; inactive lanes tid.x in 5..7 keep INACTIVE_TAG | lane). +KERNEL_A_SOURCE = """\ +s_mov_b32 s10, s8 +s_mov_b32 s11, 0 +s_load_dwordx4 s[16:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s12, s9, 3 +v_add_nc_u32_e32 v3, s12, v0 +v_mul_lo_u32 v4, v3, s5 +v_add_nc_u32_e32 v4, s4, v4 +v_and_b32_e32 v4, 63, v4 +v_lshlrev_b32_e32 v4, 2, v4 +v_mov_b32_e32 v5, v4 +global_load_dword v5, v5, s[6:7] +s_add_u32 s20, s6, 48 +s_addc_u32 s21, s7, 0 +global_load_dword v6, v4, s[20:21] +s_add_u32 s20, s20, 32 +s_addc_u32 s21, s21, 0 +global_load_dword v7, v4, s[20:21] offset:-12 glc slc dlc +s_mov_b64 s[22:23], s[6:7] +v_mov_b32_e32 v8, 0x77000000 +v_or_b32_e32 v8, v8, v3 +v_mov_b32_e32 v9, v4 +v_cmp_gt_u32_e32 vcc_lo, 5, v0 +s_and_saveexec_b32 s24, vcc_lo +global_load_dword v8, v9, s[22:23] offset:8 +s_mov_b32 exec_lo, s24 +s_waitcnt vmcnt(0) +v_lshlrev_b32_e32 v10, 4, v3 +buffer_store_dwordx4 v[5:8], v10, s[16:19], 0 offen +s_endpgm +""" + +KERNEL_A_BYTES = ( + encode_sop1(0x03, 10, 8) + + encode_sop1(0x03, 11, 0x80) + + encode_smem(0x02, 16, 10, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_sop2(0x1e, 12, 9, 0x80 + 3) # s_lshl_b32 s12, s9, 3 + + encode_vop2(0x25, 3, 12, 0) # v_add_nc_u32_e32 v3, s12, v0 + + encode_vop3a(0x169, 4, 0x100 + 3, 5) # v_mul_lo_u32 v4, v3, s5 + + encode_vop2(0x25, 4, 4, 4) # v_add_nc_u32_e32 v4, s4, v4 + + encode_vop2(0x1b, 4, 0x80 + 63, 4) # v_and_b32_e32 v4, 63, v4 + + encode_vop2(0x1a, 4, 0x80 + 2, 4) # v_lshlrev_b32_e32 v4, 2, v4 + + encode_vop1(0x01, 5, 0x100 + 4) # v_mov_b32_e32 v5, v4 + + encode_global(GLOBAL_LOAD_DWORD, 5, 5, 6) # global_load_dword v5, v5, s[6:7] + + encode_sop2(0x00, 20, 6, 0x80 + 48) # s_add_u32 s20, s6, 48 + + encode_sop2(0x04, 21, 7, 0x80) # s_addc_u32 s21, s7, 0 + + encode_global(GLOBAL_LOAD_DWORD, 6, 4, 20) # global_load_dword v6, v4, s[20:21] + + encode_sop2(0x00, 20, 20, 0x80 + 32) # s_add_u32 s20, s20, 32 + + encode_sop2(0x04, 21, 21, 0x80) # s_addc_u32 s21, s21, 0 + + encode_global(GLOBAL_LOAD_DWORD, 7, 4, 20, offset=-12, glc=1, slc=1, dlc=1) + + encode_sop1(0x04, 22, 6) # s_mov_b64 s[22:23], s[6:7] + + encode_vop1(0x01, 8, 0xff, lit=INACTIVE_TAG) # v_mov_b32_e32 v8, 0x77000000 + + encode_vop2(0x1c, 8, 0x100 + 8, 3) # v_or_b32_e32 v8, v8, v3 + + encode_vop1(0x01, 9, 0x100 + 4) # v_mov_b32_e32 v9, v4 + + encode_vopc(0xc4, 0x80 + 5, 0) # v_cmp_gt_u32_e32 vcc_lo, 5, v0 + + encode_sop1(0x3c, 24, 0x6a) # s_and_saveexec_b32 s24, vcc_lo + + encode_global(GLOBAL_LOAD_DWORD, 8, 9, 22, offset=8) # global_load_dword v8, v9, s[22:23] offset:8 + + encode_sop1(0x03, 0x7e, 24) # s_mov_b32 exec_lo, s24 + + encode_sopp(0x0c, 0x3f70) # s_waitcnt vmcnt(0) + + encode_vop2(0x1a, 10, 0x80 + 4, 3) # v_lshlrev_b32_e32 v10, 4, v3 + + encode_mubuf(0x1e, 5, 10, 16) # buffer_store_dwordx4 v[5:8], v10, s[16:19], 0 offen + + encode_sopp(0x01, 0) # s_endpgm +) + +# Kernel B: unadvanced entry root pointer s[6:7] (base_off = 0) with negative 12-bit signed offset:-16 +# (`v5 = (a >= 16u ? r0.Load(a - 16u) : 0u);`), verifying guarded subtraction when base_off + offset < 0. +KERNEL_B_SOURCE = """\ +s_mov_b32 s10, s8 +s_mov_b32 s11, 0 +s_load_dwordx4 s[16:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s12, s9, 3 +v_add_nc_u32_e32 v3, s12, v0 +v_mul_lo_u32 v4, v3, s5 +v_add_nc_u32_e32 v4, s4, v4 +v_and_b32_e32 v4, 63, v4 +v_add_nc_u32_e32 v4, 4, v4 +v_lshlrev_b32_e32 v4, 2, v4 +global_load_dword v5, v4, s[6:7] offset:-16 +s_waitcnt vmcnt(0) +v_lshlrev_b32_e32 v6, 2, v3 +buffer_store_dword v5, v6, s[16:19], 0 offen +s_endpgm +""" + +KERNEL_B_BYTES = ( + encode_sop1(0x03, 10, 8) + + encode_sop1(0x03, 11, 0x80) + + encode_smem(0x02, 16, 10, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_sop2(0x1e, 12, 9, 0x80 + 3) + + encode_vop2(0x25, 3, 12, 0) + + encode_vop3a(0x169, 4, 0x100 + 3, 5) + + encode_vop2(0x25, 4, 4, 4) + + encode_vop2(0x1b, 4, 0x80 + 63, 4) + + encode_vop2(0x25, 4, 0x80 + 4, 4) + + encode_vop2(0x1a, 4, 0x80 + 2, 4) + + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, offset=-16) + + encode_sopp(0x0c, 0x3f70) + + encode_vop2(0x1a, 6, 0x80 + 2, 3) + + encode_mubuf(0x1c, 5, 6, 16) + + encode_sopp(0x01, 0) +) + +# Kernel C: positive-offset 64-bit sum overflow (`v4 = (ud0 & -4) + 4 * lane` across 0xfffffff4..0x100000004 and into +# the low range), negative-offset underflow (`v9 = (ud1 & -4) + 4 * lane` across 0..12 below 16), and proven-aligned +# low-bit byte offsets (`v11 = (ud1 + lane) & -4` stepping 1 raw byte per lane across distinct neighboring DWORDs) +# against a bounded root view populated with nonzero sentinels across all 320 low-range words: +# 1. v5: s[6:7] + offset:8 (total_off = +8; v4 = 0xfffffffc -> guest base + 0x100000004 -> 0, not wrapped byte 4); +# 2. v6: (s[6:7] + 48) + offset:-12 (total_off = +36; v4 = 0xfffffffc -> guest base + 0x100000020 -> 0, not byte 32); +# 3. v7: s[6:7] + offset:-16 (total_off = -16; v9 in 0..12 -> guest base - 16..-4 -> 0, v9 >= 16 -> in-range); +# 4. v8: (s[6:7] + 8) + offset:-12 (total_off = -4; raw `ud1 + lane` carries low bits 0..3 across neighboring DWORDs). +KERNEL_C_SOURCE = """\ +s_mov_b32 s10, s8 +s_mov_b32 s11, 0 +s_load_dwordx4 s[16:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s12, s9, 3 +v_add_nc_u32_e32 v3, s12, v0 +v_lshlrev_b32_e32 v4, 2, v3 +s_and_b32 s14, s4, -4 +s_and_b32 s15, s5, -4 +v_add_nc_u32_e32 v9, s15, v4 +v_add_nc_u32_e32 v4, s14, v4 +v_add_nc_u32_e32 v11, s5, v3 +v_and_b32_e32 v11, -4, v11 +v_mov_b32_e32 v5, 0x66000000 +v_or_b32_e32 v5, v5, v3 +v_mov_b32_e32 v6, v5 +v_mov_b32_e32 v7, v5 +v_mov_b32_e32 v8, v5 +global_load_dword v5, v4, s[6:7] offset:8 +s_add_u32 s20, s6, 48 +s_addc_u32 s21, s7, 0 +global_load_dword v6, v4, s[20:21] offset:-12 +global_load_dword v7, v9, s[6:7] offset:-16 +s_add_u32 s22, s6, 8 +s_addc_u32 s23, s7, 0 +global_load_dword v8, v11, s[22:23] offset:-12 +s_waitcnt vmcnt(0) +v_lshlrev_b32_e32 v10, 4, v3 +buffer_store_dwordx4 v[5:8], v10, s[16:19], 0 offen +s_endpgm +""" + +KERNEL_C_BYTES = ( + encode_sop1(0x03, 10, 8) + + encode_sop1(0x03, 11, 0x80) + + encode_smem(0x02, 16, 10, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_sop2(0x1e, 12, 9, 0x80 + 3) + + encode_vop2(0x25, 3, 12, 0) + + encode_vop2(0x1a, 4, 0x80 + 2, 3) + + encode_sop2(0x0e, 14, 4, 192 + 4) + + encode_sop2(0x0e, 15, 5, 192 + 4) + + encode_vop2(0x25, 9, 15, 4) + + encode_vop2(0x25, 4, 14, 4) + + encode_vop2(0x25, 11, 5, 3) + + encode_vop2(0x1b, 11, 192 + 4, 11) + + encode_vop1(0x01, 5, 0xff, lit=PRELOAD_TAG) + + encode_vop2(0x1c, 5, 0x100 + 5, 3) + + encode_vop1(0x01, 6, 0x100 + 5) + + encode_vop1(0x01, 7, 0x100 + 5) + + encode_vop1(0x01, 8, 0x100 + 5) + + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, offset=8) + + encode_sop2(0x00, 20, 6, 0x80 + 48) + + encode_sop2(0x04, 21, 7, 0x80) + + encode_global(GLOBAL_LOAD_DWORD, 6, 4, 20, offset=-12) + + encode_global(GLOBAL_LOAD_DWORD, 7, 9, 6, offset=-16) + + encode_sop2(0x00, 22, 6, 0x80 + 8) + + encode_sop2(0x04, 23, 7, 0x80) + + encode_global(GLOBAL_LOAD_DWORD, 8, 11, 22, offset=-12) + + encode_sopp(0x0c, 0x3f70) + + encode_vop2(0x1a, 10, 0x80 + 4, 3) + + encode_mubuf(0x1e, 5, 10, 16) + + encode_sopp(0x01, 0) +) + +DECODE_CASES = ( + (encode_global(GLOBAL_LOAD_DWORD, 5, 5, 6), 'global_load_dword v5, v5, s[6:7]'), + (encode_global(GLOBAL_LOAD_DWORD, 6, 4, 20), 'global_load_dword v6, v4, s[20:21]'), + (encode_global(GLOBAL_LOAD_DWORD, 7, 4, 20, offset=-12, glc=1, slc=1, dlc=1), + 'global_load_dword v7, v4, s[20:21] offset:-12 glc slc dlc'), + (encode_global(GLOBAL_LOAD_DWORD, 8, 9, 22, offset=8), 'global_load_dword v8, v9, s[22:23] offset:8'), + (encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, offset=-2048), 'global_load_dword v5, v4, s[6:7] offset:-2048'), + (encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, offset=2047), 'global_load_dword v5, v4, s[6:7] offset:2047'), + (encode_global(GLOBAL_LOAD_DWORD, 5, 4, 0x7d), 'global_load_dword v5, v[4:5], off'), + (encode_global(GLOBAL_LOAD_DWORD, 0, 4, 6, lds=1), 'global_load_dword v4, s[6:7] lds'), +) + + +def make_source_words(seed): + """320 pairwise-distinct nonzero words so any low-range wrap or off-by-one shift mismatches immediately.""" + out = [((seed + (i + 1) * 0x9e3779b1) ^ ((i * 0x01010101) & MASK)) & MASK for i in range(WORDS)] + assert len(set(out)) == WORDS and 0 not in out and SENTINEL not in out + return out + + +def bounded_root_load(src_words, vaddr, total_off): + """Exact 64-bit guest offset relative to the bound 320-dword root view (`0` when out of `[0, 1280)`).""" + rel = (vaddr & MASK) + total_off + if rel < 0 or rel >= WORDS * 4: + return 0 + assert rel % 4 == 0 + return src_words[rel // 4] + + +def kernel_a_reference(src_words, ud0, ud1): + want = [SENTINEL] * WORDS + for grp in range(GROUPS_A[0]): + for tid in range(GROUP_A[0]): + lane = grp * GROUP_A[0] + tid + idx = (lane * ud1 + ud0) & 63 + w0 = src_words[idx] + w1 = src_words[idx + 12] # +48 bytes + w2 = src_words[idx + 17] # +80 - 12 = +68 bytes + w3 = src_words[idx + 2] if tid < 5 else (INACTIVE_TAG | lane) + want[4 * lane:4 * lane + 4] = [w0, w1, w2, w3] + return want + + +def kernel_b_reference(src_words, ud0, ud1): + want = [SENTINEL] * WORDS + for grp in range(GROUPS_A[0]): + for tid in range(GROUP_A[0]): + lane = grp * GROUP_A[0] + tid + idx = ((lane * ud1 + ud0) & 63) + 4 + want[lane] = src_words[idx - 4] # -16 bytes = -4 dwords + return want + + +def kernel_c_reference(src_words, ud0, ud1): + want = [SENTINEL] * WORDS + for grp in range(GROUPS_A[0]): + for tid in range(GROUP_A[0]): + lane = grp * GROUP_A[0] + tid + v4 = ((ud0 & 0xfffffffc) + 4 * lane) & MASK + v9 = ((ud1 & 0xfffffffc) + 4 * lane) & MASK + v11 = ((ud1 + lane) & 0xfffffffc) & MASK + want[4 * lane:4 * lane + 4] = [ + bounded_root_load(src_words, v4, 8), + bounded_root_load(src_words, v4, 36), + bounded_root_load(src_words, v9, -16), + bounded_root_load(src_words, v11, -4), + ] + return want + + +def cs_pipe(code=KERNEL_A_BYTES, *, root=None, rsrc2=RSRC2_A, group=GROUP_A): + return G.ComputePipeline(code, root or root_blob_cs(), rsrc2, group) + + +def disassemble_words(code): + lines = [] + off = 0 + while off < len(code): + size, _name, asm, _comment = D.decode_instruction(code, off) + lines.append(asm) + off += size + return '\n'.join(lines) + '\n' + + +def check_controls(): + # Low-level translator probes use the immutable empty alignment class fallback. + from startup_gfx2hlsl_sop2_complement_check import Probe + + probe = Probe() + probe.exec_known = True + probe.one('s_wqm_b32', 's_wqm_b32 exec_lo, exec_lo') + assert probe.wqm_exec + + for raw, expected_asm in DECODE_CASES: + size, _name, asm, _ = D.decode_instruction(raw, 0) + assert size == 8 and asm == expected_asm, (asm, expected_asm) + + assert disassemble_words(KERNEL_A_BYTES) == KERNEL_A_SOURCE, disassemble_words(KERNEL_A_BYTES) + assert disassemble_words(KERNEL_B_BYTES) == KERNEL_B_SOURCE, disassemble_words(KERNEL_B_BYTES) + assert disassemble_words(KERNEL_C_BYTES) == KERNEL_C_SOURCE, disassemble_words(KERNEL_C_BYTES) + + pipe_a = cs_pipe(KERNEL_A_BYTES) + hlsl_a = pipe_a.hlsl_cs() + manifest_a = pipe_a.manifest() + expected_manifest_a = ( + 'x2w-manifest 2\n' + 'stage cs\n' + 'group 8 1 1\n' + 'ud 2\n' + 'udsrc 0 rootconst 0 0\n' + 'udsrc 1 rootconst 0 1\n' + 'srv 0 buf root 1\n' + 'uav 0 table 2 0\n' + ) + assert manifest_a == expected_manifest_a, manifest_a + for snippet in ( + 'ByteAddressBuffer r0 : register(t0);', + 'RWByteAddressBuffer u0 : register(u0);', + 'a = v5;\n v5 = r0.Load(a);', + 'a = v4;\n v6 = (a <= 0xffffffcfu ? r0.Load(a + 48u) : 0u);', + 'a = v4;\n v7 = (a <= 0xffffffbbu ? r0.Load(a + 68u) : 0u);', + 'a = v9;\n if (exec & 1) v8 = (a <= 0xfffffff7u ? r0.Load(a + 8u) : 0u);', + ): + assert snippet in hlsl_a, (snippet, hlsl_a) + + pipe_b = cs_pipe(KERNEL_B_BYTES) + hlsl_b = pipe_b.hlsl_cs() + assert 'a = v4;\n v5 = (a >= 16u ? r0.Load(a - 16u) : 0u);' in hlsl_b, hlsl_b + + pipe_c = cs_pipe(KERNEL_C_BYTES) + hlsl_c = pipe_c.hlsl_cs() + for snippet in ( + 'v11 = 0xfffffffcu & v11;', + 'a = v4;\n v5 = (a <= 0xfffffff7u ? r0.Load(a + 8u) : 0u);', + 'a = v4;\n v6 = (a <= 0xffffffdbu ? r0.Load(a + 36u) : 0u);', + 'a = v9;\n v7 = (a >= 16u ? r0.Load(a - 16u) : 0u);', + 'a = v11;\n v8 = (a >= 4u ? r0.Load(a - 4u) : 0u);', + ): + assert snippet in hlsl_c, (snippet, hlsl_c) + + # Multi-root SRV check: s[6:7] = root 1 -> r0, s[8:9] = root 2 -> r1 (table in s10, gid.x in s11). + multi_code = ( + encode_sop1(0x03, 12, 10) + + encode_sop1(0x03, 13, 0x80) + + encode_smem(0x02, 16, 12, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_vop2(0x1a, 4, 0x80 + 2, 0) + + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6) + + encode_global(GLOBAL_LOAD_DWORD, 6, 4, 8, offset=16) + + encode_sopp(0x0c, 0x3f70) + + encode_vop2(0x25, 5, 0x100 + 5, 6) + + encode_mubuf(0x1c, 5, 4, 16) + + encode_sopp(0x01, 0) + ) + multi_pipe = G.ComputePipeline(multi_code, root_blob_cs(extra_root_srv=True), (11 << 1) | TGID_X, (8, 1, 1)) + multi_hlsl = multi_pipe.hlsl_cs() + multi_manifest = multi_pipe.manifest() + assert 'srv 0 buf root 1\nsrv 1 buf root 2\nuav 0 table 3 0\n' in multi_manifest, multi_manifest + assert 'v5 = r0.Load(a);' in multi_hlsl and 'v6 = (a <= 0xffffffefu ? r1.Load(a + 16u) : 0u);' in multi_hlsl, multi_hlsl + + # Boundary 4-byte-aligned signed 12-bit offsets (+2044 and -2048) lower cleanly with exact 32-bit guards. + edge_code = ( + encode_sop1(0x03, 10, 8) + + encode_sop1(0x03, 11, 0x80) + + encode_smem(0x02, 16, 10, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_vop2(0x1a, 4, 0x80 + 2, 0) + + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, offset=2044) + + encode_global(GLOBAL_LOAD_DWORD, 6, 4, 6, offset=-2048) + + encode_sopp(0x0c, 0x3f70) + + encode_mubuf(0x1d, 5, 4, 16) + + encode_sopp(0x01, 0) + ) + edge_hlsl = cs_pipe(edge_code).hlsl_cs() + assert ('v5 = (a <= 0xfffff803u ? r0.Load(a + 2044u) : 0u);' in edge_hlsl + and 'v6 = (a >= 2048u ? r0.Load(a - 2048u) : 0u);' in edge_hlsl), edge_hlsl + + # Encoding guards: reserved bit 25, nv (w1[23]), and non-zero data field (w1[15:8]). + prefix = ( + encode_sop1(0x03, 10, 8) + + encode_sop1(0x03, 11, 0x80) + + encode_smem(0x02, 16, 10, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_vop2(0x1a, 4, 0x80 + 2, 0) + ) + suffix = encode_sopp(0x0c, 0x3f70) + encode_mubuf(0x1c, 5, 4, 16) + encode_sopp(0x01, 0) + refused('reserved bit 25', lambda: cs_pipe(prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, rsvd25=1) + suffix)) + refused('global_load_dword nv', lambda: cs_pipe(prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, nv=1) + suffix)) + refused('unused data field', lambda: cs_pipe(prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, data=1) + suffix)) + + # Binary refusals: off form, lds modifier, wider/sub-dword/store/atomic/flat/scratch opcodes. + refused('without a scalar address pair', + lambda: cs_pipe(prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 0x7d) + suffix)) + refused('global load modifier lds', + lambda: cs_pipe(prefix + encode_global(GLOBAL_LOAD_DWORD, 0, 4, 6, lds=1) + suffix)) + for bad_name, bad_op, seg in ( + ('global_load_ubyte', GLOBAL_LOAD_UBYTE, 2), + ('global_load_sbyte', GLOBAL_LOAD_SBYTE, 2), + ('global_load_ushort', GLOBAL_LOAD_USHORT, 2), + ('global_load_sshort', GLOBAL_LOAD_SSHORT, 2), + ('global_load_dwordx2', GLOBAL_LOAD_DWORDX2, 2), + ('global_load_dwordx3', GLOBAL_LOAD_DWORDX3, 2), + ('global_load_dwordx4', GLOBAL_LOAD_DWORDX4, 2), + ('global_store_dword', GLOBAL_STORE_DWORD, 2), + ('global_atomic_add', GLOBAL_ATOMIC_ADD, 2), + ('flat_load_dword', GLOBAL_LOAD_DWORD, 0), + ('scratch_load_dword', GLOBAL_LOAD_DWORD, 1), + ): + refused(bad_name, lambda op=bad_op, s=seg: cs_pipe(prefix + encode_global(op, 5, 4, 6, seg=s) + suffix)) + + # Provenance & pointer-pair refusals on binary programs. + # 1. Incomplete pointer add (s_add_u32 s20, s6, 16 without s_addc_u32). + refused('not the matching pair', lambda: cs_pipe( + prefix + encode_sop2(0x00, 20, 6, 0x80 + 16) + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 20) + suffix)) + # 2. Clobbered entry high word s7. + refused('not the matching pair', lambda: cs_pipe( + prefix + encode_sop1(0x03, 7, 0x80) + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6) + suffix)) + # 3. High word taken from a second root pointer (s9 from root 2 instead of s7 from root 1). + refused('not the matching pair', lambda: G.ComputePipeline( + encode_sop1(0x03, 12, 10) + + encode_sop1(0x03, 13, 0x80) + + encode_smem(0x02, 16, 12, soffset=0x7d, imm=0) + + encode_sopp(0x0c, 0xc07f) + + encode_vop2(0x1a, 4, 0x80 + 2, 0) + + encode_sop1(0x03, 20, 6) + + encode_sop1(0x03, 21, 9) + + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 20) + + suffix, + root_blob_cs(extra_root_srv=True), (11 << 1) | TGID_X, (8, 1, 1))) + # 4. Table pointer s[8:9] (not a 64-bit root buffer pointer). + refused("global load through ('table', 2)", lambda: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 8) + suffix)) + # 5. Loaded V# descriptor words s[16:17]. + refused('holding (\'desc\'', lambda: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 16) + suffix)) + # 6. Numeric SGPR pair s[4:5] (root constants, not a pointer). + refused('holding (\'ud\'', lambda: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 4) + suffix)) + # 7. Special saddr encodings (vcc=106, ttmp[0:1]=108). + refused('global load base vcc', lambda: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 0x6a) + suffix)) + refused('global load base ttmp[0:1]', lambda: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 0x6c) + suffix)) + + # 8. Low-bit 4-byte alignment refusals on binary programs (vaddr, immediate offset, scalar advance, partial EXEC). + for unaligned_vaddr in (1, 2, 3): + refused('not proven 4-byte aligned', lambda c=unaligned_vaddr: cs_pipe( + prefix + encode_vop1(0x01, 7, 0x80 + c) + encode_global(GLOBAL_LOAD_DWORD, 5, 7, 6) + suffix)) + # Unshifted tid.x (v0), shift by 1 (`v0 << 1`), mask `-2` (`0xfffffffe`), and adding unmasked root constant `s4`. + refused('not proven 4-byte aligned', lambda: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 0, 6) + suffix)) + refused('not proven 4-byte aligned', lambda: cs_pipe( + prefix + encode_vop2(0x1a, 7, 0x80 + 1, 0) + encode_global(GLOBAL_LOAD_DWORD, 5, 7, 6) + suffix)) + refused('not proven 4-byte aligned', lambda: cs_pipe( + prefix + encode_vop2(0x1b, 7, 192 + 2, 0) + encode_global(GLOBAL_LOAD_DWORD, 5, 7, 6) + suffix)) + refused('not proven 4-byte aligned', lambda: cs_pipe( + prefix + encode_vop2(0x25, 7, 4, 4) + encode_global(GLOBAL_LOAD_DWORD, 5, 7, 6) + suffix)) + # Dropping `v_and_b32_e32 v11, -4, v11` from Kernel C leaves `v11 = s5 + v3` unproven and refuses translation. + mask_v11_bytes = encode_vop2(0x1b, 11, 192 + 4, 11) + assert KERNEL_C_BYTES.count(mask_v11_bytes) == 1 + refused('vaddr v11 is not proven 4-byte aligned', + lambda: cs_pipe(KERNEL_C_BYTES.replace(mask_v11_bytes, b''))) + # Partial-EXEC write of an aligned value over an odd VGPR (`v9 = 1`) leaves inactive lanes odd and is refused. + refused('vaddr v9 is not proven 4-byte aligned', lambda: cs_pipe( + prefix + + encode_vop1(0x01, 9, 0x80 + 1) + + encode_vopc(0xc4, 0x80 + 5, 0) + + encode_sop1(0x3c, 24, 0x6a) + + encode_vop1(0x01, 9, 0x100 + 4) + + encode_sop1(0x03, 0x7e, 24) + + encode_global(GLOBAL_LOAD_DWORD, 5, 9, 6) + + suffix)) + # Unaligned immediate offsets and unaligned literal scalar-base advances are refused. + for bad_imm in (1, 2, 3, -1, -2, -3, 2047, -2047): + refused(f'unaligned immediate offset {bad_imm}', lambda imm=bad_imm: cs_pipe( + prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6, offset=imm) + suffix)) + for bad_adv in (1, 2, 3): + refused(f'unaligned pointer offset {bad_adv}', lambda adv=bad_adv: cs_pipe( + prefix + + encode_sop2(0x00, 20, 6, 0x80 + adv) + + encode_sop2(0x04, 21, 7, 0x80) + + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 20) + + suffix)) + + # Direct Stage handler checks for arity, operand shapes, offset range, untracked branch add, and non-cs stages. + stage = cs_pipe(prefix + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 6) + suffix).cs + refused('expected 3', lambda: stage.op_global_load_dword([], [])) + refused('expected 3', lambda: stage.op_global_load_dword(['v5'], [])) + refused('expected 3', lambda: stage.op_global_load_dword(['v5', 'v4'], [])) + refused('expected 3', lambda: stage.op_global_load_dword(['v5', 'v4', 's[6:7]', '0'], [])) + refused('global load modifier lds', lambda: stage.op_global_load_dword(['v4', 's[6:7]'], ['lds'])) + refused('global load modifier tfe', lambda: stage.op_global_load_dword(['v5', 'v4', 's[6:7]'], ['tfe'])) + refused('global load offset 2048', lambda: stage.op_global_load_dword(['v5', 'v4', 's[6:7]'], ['offset:2048'])) + refused('global load offset -2049', lambda: stage.op_global_load_dword(['v5', 'v4', 's[6:7]'], ['offset:-2049'])) + refused('global load destination v[5:6]', lambda: stage.op_global_load_dword(['v[5:6]', 'v4', 's[6:7]'], [])) + refused('global load destination s4', lambda: stage.op_global_load_dword(['s4', 'v4', 's[6:7]'], [])) + refused('global load vaddr v[4:5]', lambda: stage.op_global_load_dword(['v5', 'v[4:5]', 's[6:7]'], [])) + refused('global load vaddr off', lambda: stage.op_global_load_dword(['v5', 'off', 's[6:7]'], [])) + refused('global load base s6', lambda: stage.op_global_load_dword(['v5', 'v4', 's6'], [])) + refused('global load base s[5:6]', lambda: stage.op_global_load_dword(['v5', 'v4', 's[5:6]'], [])) + refused('global load base s[106:107]', lambda: stage.op_global_load_dword(['v5', 'v4', 's[106:107]'], [])) + + stage.sym[30] = ('ptr', ('root', 1), 'added') + stage.sym[31] = ('ptrhi', ('root', 1)) + refused('untracked offset', lambda: stage.op_global_load_dword(['v5', 'v4', 's[30:31]'], [])) + + stage.sym[30] = ('ptr', ('root', 1), -4) + stage.sym[31] = G.ptr_high_symbol(('root', 1), -4) + refused('invalid pointer byte offset', lambda: stage.op_global_load_dword(['v5', 'v4', 's[30:31]'], [])) + + stage.sym[30] = ('ptr', ('root', 1), 0xfffffffc) + stage.sym[31] = G.ptr_high_symbol(('root', 1), 0xfffffffc) + refused('global load byte offset 0x100000000', + lambda: stage.op_global_load_dword(['v5', 'v4', 's[30:31]'], ['offset:4'])) + + for other_kind in ('vs', 'ps', 'ms', None): + stage.kind = other_kind + refused('global_load_dword', lambda: stage.op_global_load_dword(['v5', 'v4', 's[6:7]'], [])) + stage.kind = 'cs' + + # Unlowered negative control: temporarily removing op_global_load_dword restores the baseline refusal. + saved = G.Stage.op_global_load_dword + try: + delattr(G.Stage, 'op_global_load_dword') + refused('global_load_dword', lambda: cs_pipe(KERNEL_A_BYTES)) + finally: + G.Stage.op_global_load_dword = saved + + print('startup_compute_global_load controls: ok (3 kernels, multi-root SRV, 64-bit sum & 4-byte alignment guards, refusals)') + + +def check_binary(llvm_mc): + assert assemble(llvm_mc, KERNEL_A_SOURCE) == KERNEL_A_BYTES + assert assemble(llvm_mc, KERNEL_B_SOURCE) == KERNEL_B_BYTES + assert assemble(llvm_mc, KERNEL_C_SOURCE) == KERNEL_C_BYTES + for raw, asm in DECODE_CASES: + assert assemble(llvm_mc, asm + '\n') == raw, asm + print(f'startup_compute_global_load binary ({llvm_mc}): ok ({len(DECODE_CASES) + 3} assemblies exact)') + + +def check_decode(libllvm_path): + from pixel_aot import disassemble + blob = b''.join(raw for raw, _ in DECODE_CASES) + llvm_lines = disassemble(blob, libllvm_path) + ours = [expected_asm for _, expected_asm in DECODE_CASES] + assert llvm_lines == ours, f'LLVM vs disasm_rdna2 mismatch: {list(zip(llvm_lines, ours))}' + print(f'startup_compute_global_load decode ({libllvm_path}): ok ({len(DECODE_CASES)} GLOBAL instructions exact)') + + +def write_store_case(path, groups, expected, ud0, ud1, src_words): + consts = [ud0 & MASK, ud1 & MASK] + [0] * 14 + groups_word = groups[0] | (groups[1] << 8) | (groups[2] << 16) + path.write_bytes(struct.pack('<I320I16I320I', groups_word, *expected, *consts, *src_words)) + + +def run_case(directory, compiler, renderer, adapter, name, hlsl, groups, want, ud0, ud1, src_words): + src = directory / f'{name}.hlsl' + cso = directory / f'{name}.cso' + case = directory / f'{name}.case' + src.write_text(hlsl, encoding='ascii') + subprocess.run([compiler, '-Gis', '-WX', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + write_store_case(case, groups, want, ud0, ud1, src_words) + # Bind t0 as a bounded 320-dword raw buffer SRV view (matching runtime root-buffer view bounds). + return subprocess.run([renderer, adapter, '--compute-store-sized-case', str(cso), str(case)], + capture_output=True, text=True) + + +def dispatch(directory, compiler, renderer, adapter): + hlsl_a = cs_pipe(KERNEL_A_BYTES).hlsl_cs() + hlsl_b = cs_pipe(KERNEL_B_BYTES).hlsl_cs() + hlsl_c = cs_pipe(KERNEL_C_BYTES).hlsl_cs() + + # 4 parameterizations of Kernel A varying stride (including 1 = strictly adjacent words), bias, and source words. + runs_a = ( + ('a_adjacent_stride1', 0x10203040, 0, 1), + ('a_biased_adjacent', 0x55aa1234, 9, 1), + ('a_stride3', 0x89abcdef, 3, 3), + ('a_stride7', 0x31415926, 5, 7), + ) + for name, seed, ud0, ud1 in runs_a: + src_words = make_source_words(seed) + want = kernel_a_reference(src_words, ud0, ud1) + res = run_case(directory, compiler, renderer, adapter, name, hlsl_a, GROUPS_A, want, ud0, ud1, src_words) + if res.returncode == 77: + return 77 + assert res.returncode == 0 and f'compared_words={WORDS} mismatches=0' in res.stdout, (name, res.stdout, res.stderr) + assert 'debug_errors=0 debug_warnings=0' in res.stdout or 'debug_layer=unavailable' in res.stdout, res.stdout + + # 2 parameterizations of Kernel B verifying negative immediate subtraction in range. + runs_b = ( + ('b_neg16_adjacent', 0x27182818, 0, 1), + ('b_neg16_stride5', 0xdead10cc, 7, 5), + ) + for name, seed, ud0, ud1 in runs_b: + src_words = make_source_words(seed) + want = kernel_b_reference(src_words, ud0, ud1) + res = run_case(directory, compiler, renderer, adapter, name, hlsl_b, GROUPS_A, want, ud0, ud1, src_words) + assert res.returncode == 0 and f'compared_words={WORDS} mismatches=0' in res.stdout, (name, res.stdout, res.stderr) + + # 3 parameterizations of Kernel C verifying positive-offset 64-bit sum overflow (vaddr=0xfffffffc + 8 -> guest base + # + 0x100000004, which would wrap to byte 4 in the low range), negative-offset underflow (vaddr in 0..12 below 16), + # and low-bit inputs (ud0=1, ud1=5 stepping 1 raw byte per lane across distinct neighboring DWORDs) with nonzero + # sentinels across all 320 low-range words. + runs_c = ( + ('c_pos_overflow_neg_underflow', 0x13579bdf, 0xfffffffc, 0), + ('c_pos_neg_boundary_sweep', 0x2468ace0, 0xffffffdc, 0xfffffff4), + ('c_low_bits_neighbor_dwords', 0x97531eca, 1, 5), + ) + for name, seed, ud0, ud1 in runs_c: + src_words = make_source_words(seed) + want = kernel_c_reference(src_words, ud0, ud1) + res = run_case(directory, compiler, renderer, adapter, name, hlsl_c, GROUPS_A, want, ud0, ud1, src_words) + assert res.returncode == 0 and f'compared_words={WORDS} mismatches=0' in res.stdout, (name, res.stdout, res.stderr) + assert 'debug_errors=0 debug_warnings=0' in res.stdout or 'debug_layer=unavailable' in res.stdout, res.stdout + + # Reference negative controls on unmutated Kernel C: expecting the would-be wrapped low-range nonzero sentinel on + # positive overflow (word 0: 0xfffffffc + 8 -> byte 4 = src_c[1]), negative underflow (word 2: 0 - 16 -> src_c[0]), + # or an unaligned byte-gather / upper neighboring DWORD on low-bit input (word 3: raw 5 - 4 = byte 1 between + # distinct neighboring src_low[0] and src_low[1]) must each fail at that exact word. + src_c = make_source_words(0x13579bdf) + want_c = kernel_c_reference(src_c, 0xfffffffc, 0) + assert want_c[0] == 0 and want_c[1] == 0 and want_c[2] == 0 and want_c[3] == 0 + for ref_name, bad_word, wrapped_sentinel in ( + ('ref_pos_overflow_wrapped_low', 0, src_c[1]), + ('ref_neg_underflow_wrapped_low', 2, src_c[0]), + ): + wrong_want = list(want_c) + wrong_want[bad_word] = wrapped_sentinel + res = run_case(directory, compiler, renderer, adapter, ref_name, hlsl_c, GROUPS_A, wrong_want, 0xfffffffc, 0, src_c) + expected_err = f'word={bad_word} expected={wrapped_sentinel:08x} actual=00000000' + assert res.returncode == 1 and expected_err in res.stderr, (ref_name, res.returncode, expected_err, res.stderr) + + src_low = make_source_words(0x97531eca) + want_low = kernel_c_reference(src_low, 1, 5) + unaligned_byte1 = ((src_low[0] >> 8) | (src_low[1] << 24)) & MASK + assert src_low[0] != src_low[1] and unaligned_byte1 not in (src_low[0], src_low[1]) + assert want_low[3] == src_low[0] and want_low[15] == src_low[1] + for ref_name, wrong_val in ( + ('ref_low_bit_unaligned_gather', unaligned_byte1), + ('ref_low_bit_upper_neighbor', src_low[1]), + ): + wrong_want = list(want_low) + wrong_want[3] = wrong_val + res = run_case(directory, compiler, renderer, adapter, ref_name, hlsl_c, GROUPS_A, wrong_want, 1, 5, src_low) + expected_err = f'word=3 expected={wrong_val:08x} actual={src_low[0]:08x}' + assert res.returncode == 1 and expected_err in res.stderr, (ref_name, res.returncode, expected_err, res.stderr) + + # 10 GPU HLSL negative mutation controls: each must fail at the exact predicted word and value. + src_a = make_source_words(0x10203040) + want_a = kernel_a_reference(src_a, 0, 1) + src_b = make_source_words(0x27182818) + want_b = kernel_b_reference(src_b, 0, 1) + + mutations = ( + ('mut_wrong_vaddr', hlsl_a, 'v5 = r0.Load(a);', 'v5 = r0.Load(a + 4u);', want_a, 0, 1, src_a, 0, src_a[1]), + ('mut_dropped_scalar_base', hlsl_a, 'v6 = (a <= 0xffffffcfu ? r0.Load(a + 48u) : 0u);', 'v6 = r0.Load(a);', + want_a, 0, 1, src_a, 1, src_a[0]), + ('mut_dropped_neg_imm', hlsl_a, 'v7 = (a <= 0xffffffbbu ? r0.Load(a + 68u) : 0u);', + 'v7 = (a <= 0xffffffafu ? r0.Load(a + 80u) : 0u);', want_a, 0, 1, src_a, 2, src_a[20]), + ('mut_dropped_exec_guard', hlsl_a, 'if (exec & 1) v8 = (a <= 0xfffffff7u ? r0.Load(a + 8u) : 0u);', + 'v8 = (a <= 0xfffffff7u ? r0.Load(a + 8u) : 0u);', want_a, 0, 1, src_a, 23, src_a[5 + 2]), + ('mut_flipped_neg16_sign', hlsl_b, 'v5 = (a >= 16u ? r0.Load(a - 16u) : 0u);', 'v5 = r0.Load(a + 16u);', + want_b, 0, 1, src_b, 0, src_b[8]), + ('mut_dropped_pos8_overflow_guard', hlsl_c, 'v5 = (a <= 0xfffffff7u ? r0.Load(a + 8u) : 0u);', + 'v5 = r0.Load(a + 8u);', want_c, 0xfffffffc, 0, src_c, 0, src_c[1]), + ('mut_dropped_pos36_overflow_guard', hlsl_c, 'v6 = (a <= 0xffffffdbu ? r0.Load(a + 36u) : 0u);', + 'v6 = r0.Load(a + 36u);', want_c, 0xfffffffc, 0, src_c, 1, src_c[8]), + ('mut_clamped_neg16_underflow_low', hlsl_c, 'v7 = (a >= 16u ? r0.Load(a - 16u) : 0u);', + 'v7 = r0.Load(a >= 16u ? a - 16u : 0u);', want_c, 0xfffffffc, 0, src_c, 2, src_c[0]), + ('mut_wrapped_neg4_underflow_low', hlsl_c, 'v8 = (a >= 4u ? r0.Load(a - 4u) : 0u);', + 'v8 = r0.Load((a - 4u) & 0x7fu);', want_c, 0xfffffffc, 0, src_c, 3, src_c[31]), + ('mut_low_bits_unaligned_gather', hlsl_c.replace('v11 = 0xfffffffcu & v11;', ''), + 'v8 = (a >= 4u ? r0.Load(a - 4u) : 0u);', 'v8 = ldu(r0, a - 4u);', + want_low, 1, 5, src_low, 3, unaligned_byte1), + ) + for name, base_hlsl, old, new, want, ud0, ud1, src_words, bad_word, bad_actual in mutations: + assert base_hlsl.count(old) == 1, (name, old) + res = run_case(directory, compiler, renderer, adapter, name, base_hlsl.replace(old, new), + GROUPS_A, want, ud0, ud1, src_words) + expected_err = f'word={bad_word} expected={want[bad_word]:08x} actual={bad_actual:08x}' + assert res.returncode == 1 and expected_err in res.stderr, (name, res.returncode, expected_err, res.stdout, res.stderr) + + print(f'startup_compute_global_load {adapter}: ok (9 dispatches + 4 reference controls + 10 negative mutations caught)') + return 0 + + +def main(argv): + if not argv or argv == ['controls']: + check_controls() + return 0 + if len(argv) == 2 and argv[0] in ('binary', '--llvm-mc'): + check_controls() + check_binary(argv[1]) + return 0 + if len(argv) == 2 and argv[0] == 'decode': + check_decode(argv[1]) + return 0 + if len(argv) == 4 and argv[0] in ('dispatch', '--dispatch'): + out = ROOT / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + return dispatch(Path(tmp), *argv[1:]) + raise SystemExit(__doc__) + + +if __name__ == '__main__': + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/startup_compute_half_buffer_uav_check.py b/tests/startup_compute_half_buffer_uav_check.py new file mode 100644 index 0000000000..e941d3aeb1 --- /dev/null +++ b/tests/startup_compute_half_buffer_uav_check.py @@ -0,0 +1,135 @@ +"""Publish a synthetic D16 slot 67 program and check its typed buffer output.""" + +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from native_dpp_mirror_check import vop2 +from native_gather_lod_check import render +from native_scalar_lds_check import scalar, sop1 +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_translate_check import state_a, write_request +from startup_gfx2hlsl_compute_check import SENTINEL, TGID_X, TGID_Y, TGID_Z, USER7, WORDS, root_blob + + +FORMAT_WIDTHS = ((1, 13), (2, 29), (4, 71)) +OFFSET = 8 +RECORDS = 13 +MODE = 'dispatch-records32-output-offset' +STATE = state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z) + + +def program(channels): + opcode = 0x84 + channels - 1 + words = [ + sop1(3, 20, 6), sop1(3, 21, 128), + 0xf408080a, 0xfa000020, # output descriptor s[32:35], table byte 32 + 0xbf8cc07f, + scalar(0x26, 8, 8, 131), # 3 * group.y + scalar(0x26, 9, 9, 134), # 6 * group.z + scalar(0, 11, 7, 8), scalar(0, 11, 11, 9), + scalar(0x1e, 11, 11, 133), # 32 * flat group index + vop2(0x25, 8, 11, 0), # v8 = element index within the view + vop2(0x1d, 1, 255, 0), 0xc0003c00, # v1 = packed [-2, 1 + lane/1024] + 0x7e0402ff, 0xbc003800, # v2 = packed [-1, 0.5] + 0xe0002000 | (opcode << 18), 0x80080108, + 0xbf810000, + ] + return struct.pack('<%dI' % len(words), *words) + + +def expected(channels): + data = bytearray(struct.pack('<%dI' % WORDS, *([SENTINEL] * WORDS))) + for lane in range(RECORDS): + halves = (0x3c00 + lane, 0xc000, 0x3800, 0xbc00) + struct.pack_into('<%dH' % channels, data, OFFSET + lane * channels * 2, *halves[:channels]) + return list(struct.unpack('<%dI' % WORDS, data)) + + +def check_words(got, want, label): + first = next(((i, a, b) for i, (a, b) in enumerate(zip(got, want)) if a != b), None) + if first is not None: + word, actual, expected_word = first + raise AssertionError(f'{label}: word {word} expected {expected_word:08x}, read {actual:08x}') + + +def publish(compile_dxil, sdk, cache, key, stride): + result = subprocess.run([compile_dxil, sdk, cache.parent / 'native', 'gfx1013-direct-cs@0', + '--requests', cache, cache], capture_output=True, text=True, timeout=30) + manifest = cache / f'{key}.txt' + assert result.returncode == 0 and manifest.is_file(), (result.stdout, result.stderr) + text = manifest.read_text() + assert f'uav 0 bufhalf table 1 32 bytes {stride}' in text.splitlines(), text + assert not (cache / f'{key}.cs.hlsl').exists(), 'expected native publication' + + +def check_compiler(compile_dxil, sdk): + with TemporaryDirectory() as directory: + for channels, _ in FORMAT_WIDTHS: + cache = Path(directory) / str(channels) + cache.mkdir() + key = write_request(cache, program(channels), STATE, root=root_blob(table_range=True)) + publish(compile_dxil, sdk, cache, f'{key:016x}', channels * 2) + + +def check(compile_dxil, consumer, sdk, work, adapter, channels, format_code): + cache, env = prepare_case(work, adapter) + env.pop('X2W_NATIVE_SHADERS', None) + env.pop('X2W_NATIVE_SHADERS_ONLY', None) + (work / 'program').write_bytes(program(channels)) + (work / 'state').write_bytes(STATE) + fields = work / 'fields.bin' + env['X2W_TEST_DISPATCH_FIELDS'] = str(fields) + stride = channels * 2 + word3 = 0x01000fac | (format_code << 12) + untouched = [SENTINEL] * WORDS + + def run(view_stride=stride, records=RECORDS, descriptor_word=word3, *, probe=False): + fields.write_bytes(struct.pack('<6I', 4, WORDS, 0, view_stride, records, descriptor_word)) + return dispatch(work, consumer, env, MODE, probe=probe) + + got, result = run(probe=True) + check_words(got, untouched, 'before translation') + assert lines(result, 'Dispatch(3, 2, 2) refused: no translation'), result.stderr[-3000:] + [request] = cache.glob('req_*.c67') + key = request.stem.removeprefix('req_') + publish(compile_dxil, sdk, cache, key, stride) + got, result = run() + check_words(got, expected(channels), f'{channels} channels') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused:'), result.stderr[-3000:] + assert not [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + layers = lines(result, 'x2w-d3d12 debug layer: ') + layer = 'enabled' if layers and '0x00000000' in layers[0] else 'unavailable' + print(f'{channels} channels: {RECORDS} typed records at byte {OFFSET} and all guards match on {adapter} ' + f'(debug layer {layer})') + + wrong_shape = 'a half buffer store requires matching format, stride and structured bounds' + for options, reason in ( + ({'view_stride': stride + 2}, wrong_shape), + ({'view_stride': stride | 0x8000}, wrong_shape), + ({'descriptor_word': 0x01016fac}, wrong_shape), + ({'descriptor_word': word3 ^ 1}, wrong_shape), + ({'descriptor_word': word3 | 1 << 28}, wrong_shape), + ({'records': WORDS * 4 // stride}, 'an output range crosses the end of a placed buffer'), + ): + got, result = run(**options) + check_words(got, untouched, options) + assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + reason)) == 1, (options, result.stderr[-3000:]) + print(f'{channels} channels: invalid views refused and output remained untouched') + + +def main(compile_dxil, consumer, renderer, sdk, adapter): + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + with TemporaryDirectory() as directory: + for channels, format_code in FORMAT_WIDTHS: + check(compile_dxil, consumer, sdk, Path(directory) / str(channels), adapter, channels, format_code) + + +if __name__ == '__main__': + if sys.argv[1] == 'compile': + check_compiler(*sys.argv[2:]) + else: + main(*sys.argv[1:]) diff --git a/tests/startup_compute_image_store_check.py b/tests/startup_compute_image_store_check.py index e3833dbea5..d4831af416 100644 --- a/tests/startup_compute_image_store_check.py +++ b/tests/startup_compute_image_store_check.py @@ -1,4 +1,4 @@ -"""Check 32-bit float compute image stores (with and without unorm) from the startup translator.""" +"""Check 32-bit float compute image stores (2D, unorm and 2D array) from the startup translator.""" import argparse from pathlib import Path import struct @@ -16,11 +16,78 @@ MASK = bytes.fromhex('8002a47d') # v_cmpx_eq_u32_e32 0, v1 LINE = 'w0[uint2(v8, v9)] = asfloat(uint4(v14, v15, v16, v17));' +# The 2D-array store (#2742) takes x, y and the layer in v8-v10 and needs no SRV read, so its four data +# words are constants. The bound array has four layers and three mips: layer 1 is in the middle of the +# range and layer 3 its last entry. tests/compute_check.cpp selects the layered RWTexture2DArray view. +# The data words are not LLVM inline float constants: 0x40000000 (2.0) and 0x40800000 (4.0) would be +# assembled as the four-byte inline form instead of the eight-byte literal below, so the values follow +# the literal forms that tests/startup_image_2d_array_check.py and this fixture's own prologue already +# pin against llvm-mc-15. +ARRAY_STORE = bytes.fromhex('280f20f0080e0600') # image_store v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +ARRAY_FLAG = 1 << 31 # tests/compute_check.cpp texture_array_flag +ARRAY_LAYERS = 4 +ARRAY_VALUES = (0x3f400000, 0x3e800000, 0x40810000, 0xbf810001) +ARRAY_LINE = 'w0[uint3(v8, v9, v10)] = asfloat(uint4(v14, v15, v16, v17));' +ARRAY_PROLOGUE = bytes.fromhex( + '07038cbe' # s_mov_b32 s12, s7 + '80038dbe' # s_mov_b32 s13, 0 + '06060cf4400000fa' # s_load_dwordx8 s[24:31], s[12:13], 0x40 + '080046d70a040104' # v_lshl_add_u32 v8, s10, 2, v0 + '090046d70b020504') # v_lshl_add_u32 v9, s11, 1, v1 +ARRAY_SLICE = {1: bytes.fromhex('8102147e'), 3: bytes.fromhex('8302147e')} # v_mov_b32_e32 v10, 1 or 3 +ARRAY_END = bytes.fromhex('000081bf') # s_endpgm +ARRAY_DATA = bytes.fromhex( + '7fc08cbf' # s_waitcnt lgkmcnt(0) + 'ff021c7e0000403f' # v_mov_b32_e32 v14, 0x3f400000 + 'ff021e7e0000803e' # v_mov_b32_e32 v15, 0x3e800000 + 'ff02207e00008140' # v_mov_b32_e32 v16, 0x40810000 + 'ff02227e010081bf') # v_mov_b32_e32 v17, 0xbf810001 +ARRAY_SOURCE = """\ +s_mov_b32 s12, s7 +s_mov_b32 s13, 0 +s_load_dwordx8 s[24:31], s[12:13], 0x40 +v_lshl_add_u32 v8, s10, 2, v0 +v_lshl_add_u32 v9, s11, 1, v1 +v_mov_b32_e32 v10, {layer} +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v14, 0x3f400000 +v_mov_b32_e32 v15, 0x3e800000 +v_mov_b32_e32 v16, 0x40810000 +v_mov_b32_e32 v17, 0xbf810001 +image_store v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +s_endpgm +""" + def pipeline(body): return G.ComputePipeline(PREFIX + body + END, root_blob(3), RSRC2, fixture.GROUP) +def array_program(layer): + return ARRAY_PROLOGUE + ARRAY_SLICE[layer] + ARRAY_DATA + ARRAY_STORE + ARRAY_END + + +def array_pipeline(layer): + return G.ComputePipeline(array_program(layer), root_blob(3), RSRC2, fixture.GROUP) + + +def array_reference(layer): + """Initial then expected words of the four-layer, three-mip array; only mip zero of `layer` is stored to.""" + initial, expected = [], [] + for z in range(ARRAY_LAYERS): + for mip in range(3): + for y in range(8 >> mip): + for x in range(32 >> mip): + tag = mip << 16 | z << 12 | y << 7 | x << 2 + sentinels = [0xbf000000 | tag | c for c in range(4)] + initial.extend(sentinels) + if mip == 0 and z == layer and x < 4 * fixture.GROUPS and y < 2: + expected.extend(ARRAY_VALUES) + else: + expected.extend(sentinels) + return initial, expected + + def controls(llvm_mc): def encoded(line, hex_words): words = bytes.fromhex(hex_words) @@ -32,6 +99,8 @@ def encoded(line, hex_words): assert assemble(llvm_mc, '\n'.join(fixture.LINES) + '\n') == fixture.WORDS assert assemble(llvm_mc, fixture.STORE + ' unorm\n') == STORE_UNORM assert assemble(llvm_mc, 'v_cmpx_eq_u32_e32 0, v1\n') == MASK + for layer in (1, 3): + assert assemble(llvm_mc, ARRAY_SOURCE.format(layer=layer)) == array_program(layer), layer pipe = pipeline(STORE) assert pipe.manifest().splitlines()[-2:] == [ @@ -45,6 +114,32 @@ def encoded(line, hex_words): assert unorm_pipe.manifest() == pipe.manifest() assert 'if (exec & 1) ' + LINE in pipeline(MASK + STORE_UNORM).hlsl_cs() + # 2D array (#2742): x, y and the layer are indexed as uint3 into a RWTexture2DArray bound as tex2da. + for layer in (1, 3): + array = array_pipeline(layer) + hlsl, manifest = array.hlsl_cs(), array.manifest() + first = layer * 1344 + initial, expected = array_reference(layer) + assert 'RWTexture2DArray<float4> w0 : register(u0);' in hlsl, hlsl + assert ARRAY_LINE in hlsl and 'RWTexture2D<' not in hlsl, hlsl + assert f'v10 = 0x{layer:08x}u;' in hlsl, hlsl + assert 'uav 0 tex2da float table 1 64 channels 4' in manifest.splitlines(), manifest + # The four VDATA constants land at mip zero of that layer only; the other 5,312 words keep their + # sentinels. Layer 1 is in the middle of the four-layer range and layer 3 is its last entry. + assert len(initial) == len(expected) == ARRAY_LAYERS * 1344, (len(initial), len(expected)) + assert expected[first:first + 4] == list(ARRAY_VALUES), expected[first:first + 4] + changed = [i for i, (before, after) in enumerate(zip(initial, expected)) if before != after] + assert len(changed) == 16 * 4 and changed[0] == first and changed[-1] == first + 128 + 31, changed[:1] + # An eight-byte literal is encoded only for a value LLVM does not take as an inline constant: a pattern + # such as 0x40000000 (2.0) or 0x40800000 (4.0) would assemble to the four-byte inline form instead, and + # only the --llvm-mc comparison would notice. Keep the hand-written data words clear of that table. + assert not set(ARRAY_VALUES) & set(G.D.INLINE_FLOAT_LITERALS), G.D.INLINE_FLOAT_LITERALS + # The array address is exactly x, y and layer: a two- or four-register address is refused. + array_mods = ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY'] + for address in ('v[8:9]', 'v[8:11]'): + refused('x, y and layer expected', + lambda: pipe.cs.op_image_store(['v[14:17]', address, 's[24:31]'], array_mods)) + mods = ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D', 'unorm'] for data in ('v14', 'v[14:15]', 'v[14:16]', 'v[253:256]'): refused('four VGPRs expected', lambda: pipe.cs.op_image_store([data, 'v[8:9]', 's[24:31]'], mods)) @@ -55,12 +150,14 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[14:17]', 'v[14:15]').replace('dmask:0xf', 'dmask:0x3'), '080320f0080e0600', 'typed UAV store writes all four channels'), (fixture.STORE.replace('v[8:9]', 'v8') + ' a16', '080f20f0080e0640', 'modifier a16'), - (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), - '100f20f0080e0600', 'only 2D images'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) + refused('only 1D, 2D, 2D-array and 3D images', + lambda: pipe.cs.op_image_store(['v[14:17]', 'v[8:10]', 's[24:31]'], + ['dmask:0xf', 'dim:SQ_RSRC_IMG_CUBE'])) + wait = encoded('s_waitcnt lgkmcnt(0)', '7fc08cbf') changed = encoded('s_mov_b32 s26, 0', '80039abe') refused('modified image descriptor', lambda: pipeline(changed + STORE)) @@ -85,12 +182,14 @@ def encoded(line, hex_words): if offset == 64: for body in (read + STORE, STORE + read): refused('used for a load and a store', lambda: pipeline(load + wait + body)) - print('Compute 32-bit float image_store, unorm, EXEC, raw/texture binding order, alias and refusal checks passed') + print('Compute 32-bit float image_store, unorm, 2D array, EXEC, raw/texture binding order, alias and ' + 'refusal checks passed') -def draw_cases(directory, compiler, renderer, adapter, payload, cases): +def draw_cases(directory, compiler, renderer, adapter, payload, cases, selector=None, compared=1344): + selector = fixture.GROUPS | fixture.FLOAT_TEXTURE_FLAG if selector is None else selector hlsl, cso, case = (directory / f'image.{ext}' for ext in ('hlsl', 'cso', 'case')) - case.write_bytes(struct.pack(f'<2I{len(payload)}I', fixture.GROUPS | fixture.FLOAT_TEXTURE_FLAG, 0, *payload)) + case.write_bytes(struct.pack(f'<2I{len(payload)}I', selector, 0, *payload)) for name, source, expected_mismatches, needle in cases: hlsl.write_text(source, encoding='ascii') subprocess.run([compiler, '-T', 'cs_6_0', '-E', 'main', '-Fo', cso, hlsl], check=True) @@ -101,7 +200,7 @@ def draw_cases(directory, compiler, renderer, adapter, payload, cases): return 77 if 'debug_layer=enabled' in result.stdout: assert 'debug_errors=0 debug_warnings=0' in result.stdout, name - assert f'compared_words=1344 mismatches={expected_mismatches}' in result.stdout, name + assert f'compared_words={compared} mismatches={expected_mismatches}' in result.stdout, name if expected_mismatches == 0: assert result.returncode == 0, name else: @@ -136,7 +235,30 @@ def dispatch(directory, compiler, renderer, adapter): ('partial EXEC', masked, 0, None), ('drop EXEC guard', masked.replace(guard, LINE), 32, 'mip=0 word=128 expected=bf001000 actual=3f101000'), ) - return draw_cases(directory, compiler, renderer, adapter, payload, cases) + if draw_cases(directory, compiler, renderer, adapter, payload, cases) == 77: + return 77 + # 2D-array stores: layer 1 is in the middle of the four-layer range and layer 3 its last entry. The + # expected words carry the four VDATA constants at mip zero of that layer only. Storing one layer off + # must change both the wrong subresource and the untouched target, so each control differs by 128 words. + for layer, shift, needle in ( + (1, '+ 1', 'mip=0 word=1344 expected=3f400000 actual=bf001000'), + (3, '- 1', 'mip=0 word=2688 expected=bf002000 actual=3f400000'), + ): + initial, expected = array_reference(layer) + source = array_pipeline(layer).hlsl_cs() + assert source.count(ARRAY_LINE) == 1 + cases = ( + ('layer %d, full EXEC' % layer, source, 0, None), + ('layer %d, omit store' % layer, source.replace(ARRAY_LINE, ''), 64, + 'mip=0 word=%d expected=3f400000 actual=%08x' + % (layer * 1344, 0xbf000000 | layer << 12)), + ('layer %d, one layer off' % layer, + source.replace('uint3(v8, v9, v10)', 'uint3(v8, v9, v10 %s)' % shift), 128, needle), + ) + if draw_cases(directory, compiler, renderer, adapter, initial + expected, cases, + selector=fixture.GROUPS | ARRAY_FLAG, compared=len(initial)) == 77: + return 77 + return 0 if __name__ == '__main__': diff --git a/tests/startup_compute_image_store_d16_check.py b/tests/startup_compute_image_store_d16_check.py index a16a78d0c4..310e26be39 100644 --- a/tests/startup_compute_image_store_d16_check.py +++ b/tests/startup_compute_image_store_d16_check.py @@ -4,6 +4,7 @@ import tempfile import compute_mimg_float_store_d16_check as fixture +import startup_compute_image_store_check as A from startup_gfx2hlsl_compute_check import G, TGID_X, TGID_Y, assemble, refused, root_blob, tidig @@ -16,6 +17,50 @@ LINE = f'w0[uint2(v8, v9)] = float4({", ".join(PARTS)});' +# Reuse the assembled FP32 array x/y/layer prologue. The packed values +# are four distinct finite nonzero half encodings, low half first. +ARRAY_VALUES = (0x3c00, 0xc000, 0x3800, 0x7bff) +ARRAY_DATA = bytes.fromhex('7fc08cbf ff021c7e003c00c0 ff021e7e0038ff7b') +ARRAY_STORE = bytes.fromhex('280f20f0080e0680') +ARRAY_LINE = LINE.replace('uint2(v8, v9)', 'uint3(v8, v9, v10)') +ARRAY_SOURCE = A.ARRAY_SOURCE.split('s_waitcnt', 1)[0] + """\ +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v14, 0xc0003c00 +v_mov_b32_e32 v15, 0x7bff3800 +{mask}image_store v[14:15], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY d16 +s_endpgm +""" + + +def array_program(layer, masked=False): + return A.ARRAY_PROLOGUE + A.ARRAY_SLICE[layer] + ARRAY_DATA + (MASK if masked else b'') + ARRAY_STORE + A.ARRAY_END + + +def array_controls(llvm_mc): + for layer in (1, 3): + for masked in (False, True): + code = array_program(layer, masked) + if llvm_mc: + source = ARRAY_SOURCE.format(layer=layer, mask='v_cmpx_eq_u32_e32 0, v1\n' if masked else '') + assert assemble(llvm_mc, source) == code, (layer, masked) + pipe = G.ComputePipeline(code, root_blob(3), RSRC2, fixture.GROUP) + hlsl = pipe.hlsl_cs() + assert 'RWTexture2DArray<float4> w0 : register(u0);' in hlsl + assert ('if (exec & 1) ' if masked else '') + ARRAY_LINE in hlsl + assert ('if (exec & 1) ' + ARRAY_LINE in hlsl) == masked + assert f'v10 = 0x{layer:08x}u;' in hlsl + assert 'uav 0 tex2da float table 1 64 channels 4' in pipe.manifest().splitlines() + mods = ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY', 'd16'] + for data in ('v14', 'v[14:16]', 'v[14:17]', 'v[255:256]'): + refused('two VGPRs expected', lambda: pipe.cs.op_image_store([data, 'v[8:10]', 's[24:31]'], mods)) + for addr in ('v[8:9]', 'v[8:11]'): + refused('x, y and layer expected', lambda: pipe.cs.op_image_store(['v[14:15]', addr, 's[24:31]'], mods)) + refused('fixed table image descriptor', lambda: pipe.cs.op_image_store(['v[14:15]', 'v[8:10]', 's[28:35]'], mods)) + refused('typed UAV store writes all four channels', lambda: pipe.cs.op_image_store(['v14', 'v[8:10]', 's[24:31]'], ['dmask:0x3', *mods[1:]])) + refused('modifier a16', lambda: pipe.cs.op_image_store(['v[14:15]', 'v[8:10]', 's[24:31]'], mods + ['a16'])) + print('Compute packed D16 array translation and refusal checks passed' + ('; LLVM assembly matched' if llvm_mc else '')) + + def pipeline(body): return G.ComputePipeline(PREFIX + body + END, root_blob(3), RSRC2, fixture.GROUP) @@ -44,8 +89,6 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[14:15]', 'v14').replace('dmask:0xf', 'dmask:0x3'), '080320f0080e0680', 'typed UAV store writes all four channels'), (fixture.STORE.replace('v[8:9]', 'v8').replace(' d16', ' a16 d16'), '080f20f0080e06c0', 'modifier a16'), - (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), - '100f20f0080e0680', 'only 2D images'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) @@ -74,6 +117,7 @@ def encoded(line, hex_words): if offset == 64: for body in (read + STORE, STORE + read): refused('used for a load and a store', lambda: pipeline(load + wait + body)) + array_controls(llvm_mc) print('Compute D16 store, EXEC, raw/texture binding order, alias and refusal checks passed') diff --git a/tests/startup_compute_lds_b64_check.py b/tests/startup_compute_lds_b64_check.py index 312c2529ad..220764ee4b 100644 --- a/tests/startup_compute_lds_b64_check.py +++ b/tests/startup_compute_lds_b64_check.py @@ -7,6 +7,7 @@ compiles with DXC (cs_6_0) and runs WARP / hardware GPU readback verification via offscreen_check. """ +import re import struct import subprocess import sys @@ -20,7 +21,7 @@ sys.path.insert(0, str(HERE)) import gfx2hlsl as G -from startup_gfx2hlsl_compute_check import TGID_X, USER7, patch, refused, root_blob +from startup_gfx2hlsl_compute_check import TGID_X, USER7, patch, refused, renderer_diagnostics, root_blob def le32(w): @@ -325,11 +326,13 @@ def check_dispatch(dxc, runner, adapter, control=None): print(run.stdout, end='') if run.returncode == 77: return 77 + diagnostics = renderer_diagnostics(run.stderr, adapter) if control: - if run.returncode != 1 or 'expected=' not in run.stderr: + if run.returncode != 1 or not diagnostics or not re.fullmatch( + r'word=\d+ expected=[0-9a-f]{8} actual=[0-9a-f]{8}', diagnostics[0]): raise AssertionError('control %s: not rejected (exit %d) %s' % (control, run.returncode, run.stderr)) - print('control %s: rejected at %s' % (control, run.stderr.strip().splitlines()[0])) - elif run.returncode or run.stderr: + print('control %s: rejected at %s' % (control, diagnostics[0])) + elif run.returncode or diagnostics: raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) else: print('case %s: all %d words match' % (name, WORDS)) diff --git a/tests/startup_compute_lds_dual_atomics_check.py b/tests/startup_compute_lds_dual_atomics_check.py index 17b4fdd1ff..84dadc0c39 100644 --- a/tests/startup_compute_lds_dual_atomics_check.py +++ b/tests/startup_compute_lds_dual_atomics_check.py @@ -27,7 +27,7 @@ sys.path.insert(0, str(HERE)) import gfx2hlsl as G # noqa: E402 -from startup_gfx2hlsl_compute_check import MASK, SENTINEL, TGID_X, USER7, WORDS, patch, refused, root_blob # noqa: E402 +from startup_gfx2hlsl_compute_check import MASK, SENTINEL, TGID_X, USER7, WORDS, patch, refused, renderer_diagnostics, root_blob # noqa: E402 def le32(w): @@ -770,11 +770,13 @@ def check_dispatch(dxc, runner, adapter, control=None): return 77 if check_debug_layer(name, run.stdout, run.stderr) == 'unavailable': print('case %s: debug_layer=unavailable (word readback still verified)' % name) + diagnostics = renderer_diagnostics(run.stderr, adapter) if control: - if run.returncode != 1 or 'expected=' not in run.stderr: + if run.returncode != 1 or not diagnostics or not re.fullmatch( + r'word=\d+ expected=[0-9a-f]{8} actual=[0-9a-f]{8}', diagnostics[0]): raise AssertionError('control %s: not rejected (exit %d) %s' % (control, run.returncode, run.stderr)) - print('control %s: rejected at %s' % (control, run.stderr.strip().splitlines()[0])) - elif run.returncode or run.stderr: + print('control %s: rejected at %s' % (control, diagnostics[0])) + elif run.returncode or diagnostics: raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) else: print('case %s: all %d words match' % (name, WORDS)) diff --git a/tests/startup_compute_live_retry_check.py b/tests/startup_compute_live_retry_check.py new file mode 100644 index 0000000000..40adb04d63 --- /dev/null +++ b/tests/startup_compute_live_retry_check.py @@ -0,0 +1,68 @@ +"""Dispatch twice through the same device slot 67 pipeline with an offline translation arriving between calls.""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import time + +from startup_compute_dispatch_check import C, G, prepare_case + + +def words(output): + return list(struct.unpack(f'<{C.WORDS}I', output.read_bytes())) + + +def run(directory, consumer, dxc, adapter, publish): + cache, env = prepare_case(directory, adapter) + output = directory / 'out.bin' + args = [consumer, directory / 'vertex', directory / 'pixel', directory / 'root', 'slot67', + directory / 'program', directory / 'data', directory / 'state', 'dispatch-retry'] + stdout, stderr = directory / 'stdout', directory / 'stderr' + sentinel = [C.SENTINEL] * C.WORDS + with stdout.open('wb') as out, stderr.open('wb') as err, subprocess.Popen( + args, stdin=subprocess.PIPE, stdout=out, stderr=err, env=dict(env, X2W_TEST_DISPATCH_OUT=str(output))) as process: + try: + deadline = time.monotonic() + 20 + while 'first slot 67 Dispatch fenced' not in stdout.read_text(): + if process.poll() == 77: + print(stdout.read_text(), end='') + raise SystemExit(77) + if process.poll() is not None or time.monotonic() > deadline: + raise AssertionError(f'first Dispatch did not fence\n{stderr.read_text()[-2500:]}') + time.sleep(0.025) + first = time.monotonic() + assert words(output) == sentinel, 'first Dispatch wrote before translation' + output.unlink() + request, = cache.glob('req_*.c67') + key = request.stem.removeprefix('req_') + assert not (cache / (key + '.txt')).exists() + if publish: + result = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)) + assert f'{key}: ok' in result.stdout, result.stdout + # The runtime polls a missing manifest at one-second intervals. + time.sleep(max(0, first + 1.1 - time.monotonic())) + process.communicate(input=b'\n', timeout=20) + finally: + if process.poll() is None: + process.kill() + process.wait() + log = stderr.read_text() + assert process.returncode == 0, log[-2500:] + assert log.count('Dispatch(3, 2, 2) refused: no translation') == (1 if publish else 2), log[-2500:] + assert log.count('Dispatch(3, 2, 2) translated:') == int(publish), log[-2500:] + assert words(output) == (C.expected('A') if publish else sentinel) + errors = [line for line in log.splitlines() if 'x2w-d3d12-debug ' in line and (' sev=0 ' in line or ' sev=1 ' in line)] + assert not errors, errors + print(stdout.read_text(), end='') + print(f'{key}: both fenced {C.WORDS}-word readbacks match, late publication={publish}') + + +if __name__ == '__main__': + if len(sys.argv) != 4 or sys.argv[3] not in ('warp', 'hardware'): + sys.exit('usage: startup_compute_live_retry_check.py <consumer> <dxc> <warp|hardware>') + for publish in (True, False): + with tempfile.TemporaryDirectory() as tmp: + run(Path(tmp), *sys.argv[1:], publish) diff --git a/tests/startup_compute_packed_d16_x_uav_check.py b/tests/startup_compute_packed_d16_x_uav_check.py new file mode 100644 index 0000000000..fd5ed0ddff --- /dev/null +++ b/tests/startup_compute_packed_d16_x_uav_check.py @@ -0,0 +1,217 @@ +"""Publish a source-built one-component D16 buffer store and check the written halfwords. + +No game data. The program is a gfx1013 `buffer_store_format` with the D16 bit and one +component. That store is the half-buffer UAV, so `compile_dxil --requests` must publish +`uav 0 bufhalf table 1 32 bytes 2` and must not publish `bufd16x`. `bufd16x` is only for +a binding whose kind is `packed_d16_x_uav`. The stand-in then dispatches the half-buffer +translation. The reference halfwords are the low half of `v_xor_b32` of the literal +`0xc0003c00` with the lane id, which for lanes 0..12 is `0x3c00 + lane`. An R32_UINT +view (two halfwords per element), a stride other than 2, and a descriptor with swizzle +flags set must refuse by the half-buffer name. Before publication the dispatch stays +`no translation`. + +usage: + startup_compute_packed_d16_x_uav_check.py + reference only (no compiler, no device) + startup_compute_packed_d16_x_uav_check.py compile <compile_dxil> <dxc-bin-dir> + startup_compute_packed_d16_x_uav_check.py <compile_dxil> <startup_stream_consumer> + <offscreen_check> <dxc-bin-dir> <warp|hardware> +""" + +from pathlib import Path +import struct +import subprocess +import sys + +SENTINEL = 0xc5c5c5c5 +WORDS = 320 +OFFSET = 8 +RECORDS = 13 +STRIDE = 2 +# gfx10 unified BUF_FMT_16_FLOAT is 13; BUF_FMT_32_UINT is 20. RESOURCE_LEVEL is bit 24 +# and 0xfac is identity DST_SEL. A 32-bit element holds two halfwords, so it is not this store. +FLOAT16 = 13 +UINT32 = 20 +WORD3_BASE = 0x01000fac +INCOMPATIBLE = 'a half buffer store requires matching format, stride and structured bounds' +MODE = 'dispatch-records32-output-offset' +MANIFEST_LINE = f'uav 0 bufhalf table 1 32 bytes {STRIDE}' + + +def vop2(op, dst, src0, src1): + return op << 25 | dst << 17 | src1 << 9 | src0 + + +def scalar(op, dst, a, b): + return 0x80000000 | op << 23 | dst << 16 | b << 8 | a + + +def sop1(op, dst, src): + return 0xbe800000 | dst << 16 | op << 8 | src + + +def program_words(): + # Same index and payload shape as the one-channel half-buffer store. Opcode 0x84 is + # buffer_store_format_d16_x: idxen, v1, v8, s[32:35], offset 0. + store = 0xe0002000 | (0x84 << 18) + return [ + sop1(3, 20, 6), sop1(3, 21, 128), + 0xf408080a, 0xfa000020, + 0xbf8cc07f, + scalar(0x26, 8, 8, 131), + scalar(0x26, 9, 9, 134), + scalar(0, 11, 7, 8), scalar(0, 11, 11, 9), + scalar(0x1e, 11, 11, 133), + vop2(0x25, 8, 11, 0), + vop2(0x1d, 1, 255, 0), 0xc0003c00, + 0x7e0402ff, 0xbc003800, + store, 0x80080108, + 0xbf810000, + ] + + +def program(): + words = program_words() + return struct.pack('<%dI' % len(words), *words) + + +def halfword(lane): + """Low halfword of v1. Lanes below 16 have no bits in common with 0x3c00, so XOR adds.""" + return (0xc0003c00 ^ lane) & 0xffff + + +def word3(fmt): + return WORD3_BASE | (fmt << 12) + + +def expected(): + data = bytearray(struct.pack('<%dI' % WORDS, *([SENTINEL] * WORDS))) + for lane in range(RECORDS): + struct.pack_into('<H', data, OFFSET + lane * STRIDE, halfword(lane)) + return list(struct.unpack('<%dI' % WORDS, data)) + + +def check_words(got, want, label): + first = next(((i, a, b) for i, (a, b) in enumerate(zip(got, want)) if a != b), None) + if first is not None: + word, actual, expected_word = first + raise AssertionError(f'{label}: word {word} expected {expected_word:08x}, read {actual:08x}') + + +def check_reference(): + words = program_words() + store, store_b = words[-3], words[-2] + assert store == 0xe2102000, hex(store) + assert (store >> 18) & 0xff == 0x84, 'opcode is buffer_store_format_d16_x' + assert store & 0x3ffff == 0x2000, 'idxen, offset 0' + assert (store_b >> 8) & 0xff == 1 and (store_b & 0xff) == 8, 'data v1, index v8' + assert ((store_b >> 16) & 31) * 4 == 32, 'descriptor s[32:35]' + assert vop2(0x1d, 1, 255, 0) in words and 0xc0003c00 in words + for lane in range(RECORDS): + assert halfword(lane) == 0x3c00 + lane, lane + image = expected() + raw = struct.pack('<%dI' % WORDS, *image) + for lane in range(RECORDS): + got, = struct.unpack_from('<H', raw, OFFSET + lane * STRIDE) + assert got == 0x3c00 + lane, (lane, hex(got)) + assert raw[:OFFSET] == bytes([0xc5]) * OFFSET + tail = OFFSET + RECORDS * STRIDE + assert raw[tail:] == bytes([0xc5]) * (len(raw) - tail) + accepted = (STRIDE, word3(FLOAT16)) + assert accepted != (4, word3(UINT32)) + assert accepted != (STRIDE + 2, word3(FLOAT16)) + assert accepted != (STRIDE | 0x8000, word3(FLOAT16)) + assert (word3(UINT32) >> 12) & 127 == UINT32 + print(f'reference: {RECORDS} halfwords at byte {OFFSET}, guards intact, three negative descriptors differ') + + +def publish(compile_dxil, sdk, cache, key): + result = subprocess.run([compile_dxil, sdk, cache.parent / 'native', 'gfx1013-direct-cs@0', + '--requests', cache, cache], capture_output=True, text=True, timeout=30) + manifest = cache / f'{key}.txt' + assert result.returncode == 0 and manifest.is_file(), (result.returncode, result.stdout, result.stderr) + text = manifest.read_text() + assert MANIFEST_LINE in text.splitlines(), text + assert not any(line.startswith('uav ') and ' bufd16x ' in line for line in text.splitlines()), text + assert not (cache / f'{key}.cs.hlsl').exists(), 'expected native publication' + + +def check_compiler(compile_dxil, sdk): + from tempfile import TemporaryDirectory + + from startup_compute_translate_check import state_a, write_request + from startup_gfx2hlsl_compute_check import TGID_X, TGID_Y, TGID_Z, USER7, root_blob + + state = state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z) + with TemporaryDirectory() as directory: + cache = Path(directory) + key = write_request(cache, program(), state, root=root_blob(table_range=True)) + publish(compile_dxil, sdk, cache, f'{key:016x}') + print('compile: published', MANIFEST_LINE) + + +def check(compile_dxil, consumer, sdk, work, adapter): + from startup_compute_dispatch_check import dispatch, lines, prepare_case + from startup_compute_translate_check import state_a + from startup_gfx2hlsl_compute_check import TGID_X, TGID_Y, TGID_Z, USER7 + + cache, env = prepare_case(work, adapter) + env.pop('X2W_NATIVE_SHADERS', None) + env.pop('X2W_NATIVE_SHADERS_ONLY', None) + state = state_a((32, 1, 1), USER7 | TGID_X | TGID_Y | TGID_Z) + (work / 'program').write_bytes(program()) + (work / 'state').write_bytes(state) + fields = work / 'fields.bin' + env['X2W_TEST_DISPATCH_FIELDS'] = str(fields) + accepted_word3 = word3(FLOAT16) + untouched = [SENTINEL] * WORDS + + def run(view_stride=STRIDE, records=RECORDS, descriptor_word=accepted_word3, *, probe=False): + fields.write_bytes(struct.pack('<6I', 4, WORDS, 0, view_stride, records, descriptor_word)) + return dispatch(work, consumer, env, MODE, probe=probe) + + got, result = run(probe=True) + check_words(got, untouched, 'before translation') + assert lines(result, 'Dispatch(3, 2, 2) refused: no translation'), result.stderr[-3000:] + [request] = cache.glob('req_*.c67') + key = request.stem.removeprefix('req_') + publish(compile_dxil, sdk, cache, key) + got, result = run() + check_words(got, expected(), 'packed D16 x') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused:'), result.stderr[-3000:] + assert not [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + layers = lines(result, 'x2w-d3d12 debug layer: ') + layer = 'enabled' if layers and '0x00000000' in layers[0] else 'unavailable' + print(f'{RECORDS} halfwords at byte {OFFSET} and all guards match on {adapter} (debug layer {layer})') + + for label, options in ( + ('R32_UINT view', {'view_stride': 4, 'descriptor_word': word3(UINT32)}), + ('wrong stride', {'view_stride': STRIDE + 2}), + ('flags set', {'view_stride': STRIDE | 0x8000}), + ): + got, result = run(**options) + check_words(got, untouched, label) + assert len(lines(result, 'Dispatch(3, 2, 2) refused: ' + INCOMPATIBLE)) == 1, (label, result.stderr[-3000:]) + print(f'{label}: refused ({INCOMPATIBLE}), output untouched') + + +def main(compile_dxil, consumer, renderer, sdk, adapter): + from tempfile import TemporaryDirectory + + from native_gather_lod_check import render + + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + with TemporaryDirectory() as directory: + check(compile_dxil, consumer, sdk, Path(directory), adapter) + + +if __name__ == '__main__': + if len(sys.argv) == 1 or sys.argv[1] == 'reference': + check_reference() + elif sys.argv[1] == 'compile': + check_compiler(*sys.argv[2:]) + elif len(sys.argv) == 6 and sys.argv[5] in ('warp', 'hardware'): + main(*sys.argv[1:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_compute_readfirstlane_check.py b/tests/startup_compute_readfirstlane_check.py index c229be9e2f..ae1d1177f1 100644 --- a/tests/startup_compute_readfirstlane_check.py +++ b/tests/startup_compute_readfirstlane_check.py @@ -8,7 +8,8 @@ reads it through ``v_readfirstlane_b32`` at the join, runs a four-iteration uniform loop whose counter ``s22`` is incremented uniformly and read back via ``v_readfirstlane_b32`` both inside the loop and after loop exit, and stores one combined word per thread across two four-thread groups ``(4, 1, 1) x (2, 1, 1)`` so both arms of the branch -run on the GPU. +run on the GPU. The waterfall fixtures also exercise a lane-varying key. They restore the incoming threads +after selecting zero to four lanes, then read back per-key arithmetic and a load from one fixed raw buffer. """ import argparse from pathlib import Path @@ -23,6 +24,7 @@ sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) import disasm_rdna2 as D # noqa: E402 +import startup_compute_waterfall as waterfall from startup_gfx2hlsl_compute_check import ( # noqa: E402 CASES, G, KEY, MASK, SENTINEL, STRIDE, WORDS, patch, refused, root_blob, ) @@ -33,6 +35,8 @@ ONE_PATH_LINE = 's25 = uint(max(F((U(2.0 * F((U(float(s20))))))), 0.0));' LOOP_LINE = 's24 = uint(max(F((U(2.0 * F((U(float(s22))))))), 0.0));' POST_LOOP_LINE = 's26 = s22;' +CONST_SHIFT_LINE = 's29 = (0x0000003cu) >> (0x00000002u & 31);' +INT_LINE = 's28 = (s27 + (s27)) << (0x00000001u & 31);' def opcode(table, name): @@ -91,8 +95,14 @@ def build_words(): ws += sopp('s_cbranch_scc1', loop_idx - (len(ws) + 1)) ws += vop1('v_mov_b32_e32', 'v9', 's22') + vop1('v_readfirstlane_b32', 's26', 'v9') ws += sop2('s_lshl_b32', 's27', 's7', 2) + vop2('v_add_nc_u32_e32', 'v4', 's27', 'v0') + # Pure integer ops on a uniform scalar, read past the entry block: (s27 + s27) << 1 (RF1). + ws += (vop1('v_mov_b32_e32', 'v10', 's27') + vop2('v_add_nc_u32_e32', 'v10', 's27', 'v10') + + vop2('v_lshlrev_b32_e32', 'v10', 1, 'v10') + vop1('v_readfirstlane_b32', 's28', 'v10')) + # A VGPR overwritten by a constant, then shifted: 60 >> 2 is the same in every lane (RF1). + ws += (vop1('v_mov_b32_e32', 'v11', 60) + vop2('v_lshrrev_b32_e32', 'v11', 2, 'v11') + + vop1('v_readfirstlane_b32', 's29', 'v11')) ws += sop2('s_add_u32', 's25', 's25', 's21') + sop2('s_add_u32', 's25', 's25', 's23') - ws += sop2('s_add_u32', 's25', 's25', 's26') + ws += sop2('s_add_u32', 's25', 's25', 's26') + sop2('s_add_u32', 's25', 's25', 's28') + sop2('s_add_u32', 's25', 's25', 's29') ws += vop2('v_add_nc_u32_e32', 'v5', 's25', 'v4') + vop2('v_lshlrev_b32_e32', 'v4', 2, 'v4') # buffer_store_dword v5, v4, s[16:19], 0 offen; s_endpgm ws += list(struct.unpack('<2I', bytes.fromhex('001070e004050480'))) + sopp('s_endpgm') @@ -118,6 +128,14 @@ def pack_hex(*ws): ('loop counter updated from lane mask', [(pack_hex(*sop2('s_add_u32', 's22', 's22', 1)), pack_hex(*sop1('s_mov_b32', 's22', 'vcc_lo')))], 'v_readfirstlane_b32 requires a proven uniform source'), + # RF1 negative controls: the integer chain stays refused when a source differs between lanes. + ('integer chain from the thread id', + [(pack_hex(*vop1('v_mov_b32_e32', 'v10', 's27')), pack_hex(*vop1('v_mov_b32_e32', 'v10', 'v0')))], + 'v_readfirstlane_b32 requires a proven uniform source'), + # the lane-mask read as a number is refused first (#2702); the chain is not reached + ('integer chain with a lane-mask scalar', + [(pack_hex(*vop2('v_add_nc_u32_e32', 'v10', 's27', 'v10')), pack_hex(*vop2('v_add_nc_u32_e32', 'v10', 'vcc_lo', 'v10')))], + 'v_add_nc_u32 reads lane mask vcc_lo as numeric data'), ) @@ -134,28 +152,33 @@ def expected(): s21 = 9 if gx == 0 else 5 s23 = 0 + 2 + 4 + 6 # sum over uniform loop iterations i=0..3 s26 = 4 - combined = (s25 + s21 + s23 + s26) & MASK + s28 = ((gx * 4) * 2) << 1 + combined = (s25 + s21 + s23 + s26 + s28 + (60 >> 2)) & MASK for tx in range(LOCAL[0]): idx = gx * LOCAL[0] + tx out[idx] = (combined + idx) & MASK return out -def llvm_lines(): +def llvm_decoded_lines(decoded): + """Format decoded instructions for llvm-mc, resolving label branches to dword offsets.""" lines = [] - for off, _n, _name, asm in DECODED: + for off, _n, _name, asm in decoded: m = re.fullmatch(r'(s_branch|s_cbranch_\w+) label_0x([0-9a-f]+)', asm) if m: lines.append('%s %d' % (m.group(1), (int(m.group(2), 16) - off - 4) // 4)) else: lines.append(asm.replace('vcc_lo', 'vcc')) - lines += [ + return lines + + +def llvm_lines(): + return llvm_decoded_lines(DECODED) + [ 's_cbranch_vccnz -8', 's_cbranch_vccz 1', 's_mov_b32 s20, 9', 's_mov_b32 s22, vcc_lo', ] - return lines def check_binary(llvm_mc): @@ -182,7 +205,7 @@ def check_binary(llvm_mc): def controls(llvm_mc=None): pipe = translate() hlsl = pipe.hlsl_cs() - for snippet in (ONE_PATH_LINE, LOOP_LINE, POST_LOOP_LINE, 'u0.Store(a, v5);'): + for snippet in (ONE_PATH_LINE, LOOP_LINE, POST_LOOP_LINE, INT_LINE, CONST_SHIFT_LINE, 'u0.Store(a, v5);'): assert hlsl.count(snippet) == 1, (snippet, hlsl) assert 'uav 0 table 1 16' in pipe.manifest().splitlines(), pipe.manifest() @@ -194,13 +217,249 @@ def controls(llvm_mc=None): if llvm_mc: check_binary(llvm_mc) - print('Compute readfirstlane one-path, loop-counter and refusal checks passed') + log_ceil_controls(llvm_mc) + img_load_controls(llvm_mc) + waterfall.controls(llvm_mc) + print('Compute readfirstlane one-path, loop-counter, log2/ceil, image_load, waterfall and refusal checks passed') + + +LOG_CEIL_LOG_LINE = 's21 = v8;' +LOG_CEIL_CEIL_LINE = 's22 = v9;' + + +def build_log_ceil_words(): + ws = list(struct.unpack('<5I', bytes.fromhex('06038abe80038bbe05030cf4000000fa7fc08cbf'))) + ws += sop2('s_lshl_b32', 's20', 's7', 2) + sop2('s_add_u32', 's20', 's20', 5) + ws += vop1('v_cvt_f32_u32_e32', 'v7', 's20') + vop1('v_log_f32_e32', 'v7', 'v7') + ws += vop2('v_mul_f32_e32', 'v8', '2.0', 'v7') + vop1('v_cvt_u32_f32_e32', 'v8', 'v8') + ws += vop1('v_readfirstlane_b32', 's21', 'v8') + ws += vop1('v_ceil_f32_e32', 'v9', 'v7') + vop1('v_cvt_u32_f32_e32', 'v9', 'v9') + ws += vop1('v_readfirstlane_b32', 's22', 'v9') + ws += sop2('s_lshl_b32', 's21', 's21', 8) + sop2('s_or_b32', 's21', 's21', 's22') + ws += sop2('s_lshl_b32', 's23', 's7', 2) + vop2('v_add_nc_u32_e32', 'v4', 's23', 'v0') + ws += vop2('v_add_nc_u32_e32', 'v5', 's21', 'v4') + vop2('v_lshlrev_b32_e32', 'v4', 2, 'v4') + ws += list(struct.unpack('<2I', bytes.fromhex('001070e004050480'))) + sopp('s_endpgm') + return struct.pack('<%dI' % len(ws), *ws) + + +LOG_CEIL_WORDS = build_log_ceil_words() + + +def log_ceil_expected(): + out = [SENTINEL] * WORDS + for gx, base_val in ((0, 0x403), (1, 0x604)): + for tx in range(LOCAL[0]): + idx = gx * LOCAL[0] + tx + out[idx] = (base_val + idx) & MASK + return out + + +def log_ceil_controls(llvm_mc=None): + hlsl = translate(LOG_CEIL_WORDS).hlsl_cs() + for snippet in ('v7 = U(log2(F(v7)));', 'v9 = U(ceil(F(v7)));', LOG_CEIL_LOG_LINE, LOG_CEIL_CEIL_LINE, 'u0.Store(a, v5);'): + assert hlsl.count(snippet) == 1, (snippet, hlsl) + for old_ws, new_ws in ( + (vop1('v_log_f32_e32', 'v7', 'v7'), vop1('v_log_f32_e32', 'v7', 'v0')), + (vop1('v_ceil_f32_e32', 'v9', 'v7'), vop1('v_ceil_f32_e32', 'v9', 'v0'))): + refused('v_readfirstlane_b32 requires a proven uniform source', + lambda code=patch(LOG_CEIL_WORDS, pack_hex(*old_ws), pack_hex(*new_ws)): translate(code)) + saved = G.UNIFORM_VALU + try: + for removed in ('v_log_f32', 'v_ceil_f32'): + G.UNIFORM_VALU = saved - {removed} + refused('v_readfirstlane_b32 requires a proven uniform source', lambda: translate(LOG_CEIL_WORDS)) + finally: + G.UNIFORM_VALU = saved + if llvm_mc: + decoded = G.decode(LOG_CEIL_WORDS) + lines = [asm for _, _, _, asm in decoded] + proc = subprocess.run( + [llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', '-show-encoding'], + input='\n'.join(lines) + '\n', capture_output=True, text=True, check=True) + built = b''.join(bytes(int(b, 16) for b in m.group(1).split(',')) + for m in re.finditer(r'encoding: \[([^\]]*)\]', proc.stdout)) + assert built == LOG_CEIL_WORDS, (built.hex(), LOG_CEIL_WORDS.hex()) + + +LOG_CEIL_CONTROLS = { + 'dropped-log2-read': (LOG_CEIL_LOG_LINE, 's21 = 0u;', 'word=0 expected=00000403 actual=00000003'), + 'dropped-ceil-read': (LOG_CEIL_CEIL_LINE, 's22 = 0u;', 'word=0 expected=00000403 actual=00000400'), +} + + +def log_ceil_dispatch(td, dxc, runner, adapter): + hlsl = translate(LOG_CEIL_WORDS).hlsl_cs() + case = td / 'log_ceil.case' + case.write_bytes( + struct.pack('<I', GROUPS[0] | (GROUPS[1] << 8) | (GROUPS[2] << 16)) + + struct.pack('<%dI' % WORDS, *log_ceil_expected()) + + struct.pack('<16I', KEY, STRIDE, *([0] * 14))) + for label, mutation in [('log_ceil_baseline', None)] + [(k, k) for k in LOG_CEIL_CONTROLS]: + text = hlsl + if mutation: + old, new, _ = LOG_CEIL_CONTROLS[mutation] + assert text.count(old) == 1, mutation + text = text.replace(old, new) + src, cso = td / f'{label}.hlsl', td / f'{label}.cso' + src.write_text(text, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + proc = subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], + capture_output=True, text=True) + print(proc.stdout, end='') + if proc.returncode == 77: + return 77 + diagnostics = [] + for line in proc.stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) + if mutation: + want = LOG_CEIL_CONTROLS[mutation][2] + first = diagnostics[:1] + if proc.returncode != 1 or first != [want]: + raise AssertionError('control %s: expected exit 1 with %r, got exit %d %r' + % (mutation, want, proc.returncode, proc.stderr)) + print('control %s (%s): rejected at %s' % (mutation, adapter, first[0])) + elif proc.returncode or diagnostics: + raise AssertionError('log_ceil baseline (%s): %s' % (adapter, proc.stderr or 'exit %d' % proc.returncode)) + else: + print('log_ceil baseline (%s): all %d words match' % (adapter, WORDS)) + return 0 + + +IMG_LOAD_X_LINE = 's21 = ul30_7;' +IMG_LOAD_Y_LINE = 's22 = ul30_8;' +IMG_TEX_WIDTH = 32 +IMG_TEX_HEIGHT = 8 +IMG_TEX_RGBA32_FLOAT = 1 << 30 + + +def build_img_load_words(): + ws = sop1('s_mov_b32', 's10', 's6') + sop1('s_mov_b32', 's11', 0) + ws += [0xf4080305, 0xfa000000] # s_load_dwordx4 s[12:15], s[10:11], 0x0 (u0) + ws += [0xf40c0405, 0xfa000020] # s_load_dwordx8 s[16:23], s[10:11], 0x20 (r0) + ws += [0xbf8cc07f] # s_waitcnt lgkmcnt(0) + ws += sopc('s_cmp_eq_u32', 's7', 0) + sopp('s_cbranch_scc0', 1) + sopp('s_nop', 0) + ws += vop1('v_mov_b32_e32', 'v2', 's7') + vop1('v_mov_b32_e32', 'v3', 2) + ws += [0xf0000308, 0x00040702] # image_load v[7:8], v[2:3], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D + ws += [0xbf8c3f70] # s_waitcnt vmcnt(0) + ws += vop1('v_readfirstlane_b32', 's21', 'v7') + vop1('v_readfirstlane_b32', 's22', 'v8') + ws += sop2('s_xor_b32', 's21', 's21', 's22') + ws += sop2('s_lshl_b32', 's23', 's7', 2) + vop2('v_add_nc_u32_e32', 'v4', 's23', 'v0') + ws += vop2('v_add_nc_u32_e32', 'v5', 's21', 'v4') + vop2('v_lshlrev_b32_e32', 'v4', 2, 'v4') + ws += [0xe0701000, 0x80030504] # buffer_store_dword v5, v4, s[12:15], 0 offen + ws += sopp('s_endpgm') + return struct.pack('<%dI' % len(ws), *ws) + + +IMG_LOAD_WORDS = build_img_load_words() + + +def img_load_texels(): + """Distinct finite float32 bit patterns across (x, y) so groups 0 and 1 read distinct uniform x^y pairs.""" + words = [] + for y in range(IMG_TEX_HEIGHT): + for x in range(IMG_TEX_WIDTH): + base = 0x3f800000 + ((y * IMG_TEX_WIDTH + x) << 12) + words.extend((base, base + 0x100, base + 0x200, base + 0x300)) + return words + + +def img_load_expected(texels): + out = [SENTINEL] * WORDS + for gx in range(GROUPS[0]): + off = (2 * IMG_TEX_WIDTH + gx) * 4 + combined = texels[off] ^ texels[off + 1] + for tx in range(LOCAL[0]): + idx = gx * LOCAL[0] + tx + out[idx] = (combined + idx) & MASK + return out + + +def img_load_controls(llvm_mc=None): + hlsl = translate(IMG_LOAD_WORDS).hlsl_cs() + for snippet in ('t = r0.Load(int3(v2, v3, 0));', IMG_LOAD_X_LINE, IMG_LOAD_Y_LINE, 'u0.Store(a, v5);'): + assert hlsl.count(snippet) == 1, (snippet, hlsl) + # Varying coordinate control: image_load v[7:8], v[0:1], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D. + refused('v_readfirstlane_b32 requires a proven uniform source', + lambda: translate(patch(IMG_LOAD_WORDS, '080300f002070400', '080300f000070400'))) + # Image store on a different descriptor slot in the same dispatch must block the uniform image_load proof. + store_prefix = (sop1('s_mov_b32', 's10', 's6') + sop1('s_mov_b32', 's11', 0) + + [0xf40c0605, 0xfa000040, 0xbf8cc07f] # s_load_dwordx8 s[24:31], s[10:11], 0x40; s_waitcnt lgkmcnt(0) + + [0xf0200f08, 0x00060a02]) # image_store v[10:13], v[2:3], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D + refused('v_readfirstlane_b32 requires a proven uniform source', + lambda: translate(struct.pack('<%dI' % len(store_prefix), *store_prefix) + IMG_LOAD_WORDS[8:])) + saved = G.UNIFORM_IMAGE_LOADS + G.UNIFORM_IMAGE_LOADS = frozenset() + try: + refused('v_readfirstlane_b32 requires a proven uniform source', lambda: translate(IMG_LOAD_WORDS)) + finally: + G.UNIFORM_IMAGE_LOADS = saved + if llvm_mc: + lines = llvm_decoded_lines(G.decode(IMG_LOAD_WORDS)) + proc = subprocess.run( + [llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', '-show-encoding'], + input='\n'.join(lines) + '\n', capture_output=True, text=True, check=True) + built = b''.join(bytes(int(b, 16) for b in m.group(1).split(',')) + for m in re.finditer(r'encoding: \[([^\]]*)\]', proc.stdout)) + assert built == IMG_LOAD_WORDS, (built.hex(), IMG_LOAD_WORDS.hex()) + + +IMG_LOAD_CONTROLS = { + 'dropped-img-x-read': (IMG_LOAD_X_LINE, 's21 = 0u;', 'word=0 expected=00000100 actual=3f840100'), + 'dropped-img-y-read': (IMG_LOAD_Y_LINE, 's22 = 0u;', 'word=0 expected=00000100 actual=3f840000'), +} + + +def img_load_dispatch(td, dxc, runner, adapter): + hlsl = translate(IMG_LOAD_WORDS).hlsl_cs() + texels = img_load_texels() + expected_words = img_load_expected(texels) + payload = expected_words + texels + case = td / 'img_load.case' + header = GROUPS[0] | (GROUPS[1] << 8) | (GROUPS[2] << 16) | IMG_TEX_RGBA32_FLOAT + case.write_bytes(struct.pack('<I%dI' % len(payload), header, *payload)) + for label, mutation in [('img_load_baseline', None)] + [(k, k) for k in IMG_LOAD_CONTROLS]: + text = hlsl + if mutation: + old, new, _ = IMG_LOAD_CONTROLS[mutation] + assert text.count(old) == 1, mutation + text = text.replace(old, new) + src, cso = td / f'{label}.hlsl', td / f'{label}.cso' + src.write_text(text, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + proc = subprocess.run([runner, adapter, '--compute-texture-case', str(cso), str(case)], + capture_output=True, text=True) + print(proc.stdout, end='') + if proc.returncode == 77: + return 77 + diagnostics = [] + for line in proc.stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) + if mutation: + want = IMG_LOAD_CONTROLS[mutation][2] + first = diagnostics[:1] + if proc.returncode != 1 or first != [want]: + raise AssertionError('control %s: expected exit 1 with %r, got exit %d %r' + % (mutation, want, proc.returncode, proc.stderr)) + print('control %s (%s): rejected at %s' % (mutation, adapter, first[0])) + elif proc.returncode or diagnostics: + raise AssertionError('img_load baseline (%s): %s' % (adapter, proc.stderr or 'exit %d' % proc.returncode)) + else: + print('img_load baseline (%s): all %d words match' % (adapter, WORDS)) + return 0 CONTROLS = { - 'dropped-one-path': (ONE_PATH_LINE, 's25 = 0u;', 'word=0 expected=0000008b actual=00000019'), - 'dropped-loop-read': (LOOP_LINE, 's24 = 0u;', 'word=0 expected=0000008b actual=0000007f'), - 'dropped-post-loop': (POST_LOOP_LINE, 's26 = 0u;', 'word=0 expected=0000008b actual=00000087'), + 'dropped-one-path': (ONE_PATH_LINE, 's25 = 0u;', 'word=0 expected=0000009a actual=00000028'), + 'dropped-loop-read': (LOOP_LINE, 's24 = 0u;', 'word=0 expected=0000009a actual=0000008e'), + 'dropped-int-read': (INT_LINE, 's28 = 0u;', 'word=4 expected=000000ac actual=0000009c'), + 'dropped-const-shift': (CONST_SHIFT_LINE, 's29 = 0u;', 'word=0 expected=0000009a actual=0000008b'), + 'dropped-post-loop': (POST_LOOP_LINE, 's26 = 0u;', 'word=0 expected=0000009a actual=00000096'), } @@ -231,18 +490,30 @@ def dispatch(dxc, runner, adapter): print(proc.stdout, end='') if proc.returncode == 77: return 77 + diagnostics = [] + for line in proc.stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) if mutation: want = CONTROLS[mutation][2] - first = proc.stderr.strip().splitlines()[:1] + first = diagnostics[:1] if proc.returncode != 1 or first != [want]: raise AssertionError('control %s: expected exit 1 with %r, got exit %d %r' % (mutation, want, proc.returncode, proc.stderr)) print('control %s (%s): rejected at %s' % (mutation, adapter, first[0])) - elif proc.returncode or proc.stderr: + elif proc.returncode or diagnostics: raise AssertionError('baseline (%s): %s' % (adapter, proc.stderr or 'exit %d' % proc.returncode)) else: print('baseline (%s): all %d words match' % (adapter, WORDS)) - return 0 + rc = log_ceil_dispatch(td, dxc, runner, adapter) + if rc: + return rc + rc = img_load_dispatch(td, dxc, runner, adapter) + if rc: + return rc + return waterfall.dispatch(td, dxc, runner, adapter) def main(argv): diff --git a/tests/startup_compute_request_check.py b/tests/startup_compute_request_check.py index 0ac0417c2e..951d6415a5 100644 --- a/tests/startup_compute_request_check.py +++ b/tests/startup_compute_request_check.py @@ -30,6 +30,9 @@ from startup_stream_check import container, gfx2hlsl +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup")) +import shader_cache_revision # noqa: E402 + PROGRAM = struct.pack("<2I", 0x7e020280, 0xbf810000) # v_mov_b32 v1, 0; s_endpgm DATA = struct.pack("<2Q", 0xfedcba9876543210, 0xffff00001111008c) # synthetic, not addresses STATE = struct.pack("<3Q", 1, 0x2c, 0xfff0000000000003) # synthetic state block A, 24 bytes @@ -78,7 +81,8 @@ def prepare(directory): def names(cache): - return sorted(p.name for p in cache.iterdir()) + """The request files (revision.txt, which the first request writes, is checked on its own).""" + return sorted(p.name for p in cache.iterdir() if p.name != shader_cache_revision.REVISION_FILE) def check_boundaries(directory, consumer): @@ -114,6 +118,8 @@ def check_boundaries(directory, consumer): def check(directory, consumer, disabled): cache, env = prepare(directory) + # A revision.txt left by an older build: the first request replaces it. + (cache / shader_cache_revision.REVISION_FILE).write_text("graphics x2w-startup-shader-0\n", encoding="ascii") if disabled: env["X2W_D3D12_RENDER"] = "0" lines = run(directory, consumer, env) @@ -137,10 +143,19 @@ def check(directory, consumer, disabled): assert lines == [f"x2w-draw compute request {key:016x} published {detail}", f"x2w-draw compute request {key:016x} already present {detail}"], lines + # The stand-in names its revisions next to the request, and they are the ones gfx2hlsl.py at this commit hashes, + # so the launchers' check (tools/startup/shader_cache_revision.py) stays silent for a matching build. + revisions = shader_cache_revision.cache_revisions(cache) + assert revisions == shader_cache_revision.translator_revisions(gfx2hlsl.__file__), revisions + assert shader_cache_revision.warning(cache, gfx2hlsl.__file__) is None, shader_cache_revision.warning(cache, gfx2hlsl.__file__) + revision_file = cache / shader_cache_revision.REVISION_FILE + stamps = {file: (cache / file).stat().st_mtime_ns for file in files} + revision_stamp = revision_file.stat().st_mtime_ns lines = run(directory, consumer, env) assert len(lines) == 2 and all("already present" in line for line in lines), lines assert {file: (cache / file).stat().st_mtime_ns for file in files} == stamps, "a second process rewrote the request" + assert revision_file.stat().st_mtime_ns == revision_stamp, "a second process rewrote an unchanged revision.txt" assert names(cache) == sorted(files) # Each pointed-to part is in the key. diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index f57f4b28c1..7ea4df8da9 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x8421b8080fd0a5e6 # framed key at revision 17cs +KEY = 0x96c99985746a35d1 # framed key at revision 29cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-17cs': + for b in b'x2w-startup-shader-29cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack('<Q', len(part)) + part: diff --git a/tests/startup_compute_root.cpp b/tests/startup_compute_root.cpp index b31cd9bcce..d8c065d483 100644 --- a/tests/startup_compute_root.cpp +++ b/tests/startup_compute_root.cpp @@ -7,6 +7,7 @@ namespace { using x2w_startup::ComputeTables; +using x2w_startup::ViewHeapSelection; using x2w_startup::ViewTable; using x2w_startup::resolve_view_table; int failures; @@ -65,9 +66,36 @@ int main() { ComputeTables s; s.set_signature(&root_a); + const auto select = [&](std::uint64_t heap, bool visible, unsigned logical, unsigned desktop) { + ViewHeapSelection selection; + selection.note(heap, visible, logical, desktop); + s.set_view_heap(selection.compute); + return selection; + }; + auto selection = select(1, true, 8, 8); + check(selection.compute == 1 && !selection.graphics, "ordinary heap is selected only for compute invalidation"); s.set_table(7, at(6)); - s.clear(); - check(s.table(7).address == 0 && s.signature() == &root_a, "a view heap change clears the tables and keeps the signature"); + select(1, true, 8, 8); + check(s.table(7).address == at(6).address, "same ordinary heap keeps the table"); + select(2, true, 8, 8); + check(!s.table(7).address, "different ordinary heap clears the table"); + s.set_table(7, at(6)); + selection = select(3, true, 16, 8); + check(selection.compute == 3 && selection.graphics == 3, "oversized heap remains visible to graphics lookup"); + check(!s.table(7).address, "ordinary to oversized clears the table"); + s.set_table(7, at(6)); + select(3, true, 16, 8); + check(s.table(7).address == at(6).address, "same oversized heap keeps the table"); + select(4, true, 16, 8); + check(!s.table(7).address, "different oversized heap clears the table"); + s.set_table(7, at(6)); + select(1, true, 8, 8); + check(!s.table(7).address, "oversized to ordinary clears the table"); + s.set_table(7, at(6)); + s.set_view_heap(ViewHeapSelection{}.compute); + check(!s.table(7).address && s.signature() == &root_a, "unsetting the heap clears the table and keeps the signature"); + selection = select(5, false, 8, 8); + check(!selection.compute && !selection.graphics, "CPU-only heap does not select a view heap"); } { ComputeTables s; diff --git a/tests/startup_compute_root_srv_dispatch_check.py b/tests/startup_compute_root_srv_dispatch_check.py new file mode 100644 index 0000000000..4411d2f20a --- /dev/null +++ b/tests/startup_compute_root_srv_dispatch_check.py @@ -0,0 +1,347 @@ +"""Startup compute manifest consumer for `srv <i> buf root <param>` at slot-14 Dispatch (Refs #2618, #2274).""" +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_compute_dispatch_texture_check import clean, lines, run as _run, translate +from startup_compute_global_load_check import ( + GLOBAL_LOAD_DWORD, + encode_global, + encode_mubuf, + encode_smem, + encode_sop1, + encode_sop2, + encode_sopp, + encode_vop2, + encode_vop3a, +) +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_gfx2hlsl_compute_check import ( + KEY, + MASK, + SENTINEL, + STRIDE, + TGID_X, + TGID_Y, + TGID_Z, + WORDS, + tidig, +) + +IN = [(0x8b02a7f1 + i * 0x413b1) & MASK for i in range(WORDS)] +IN2 = [(0x3c6ef372 + i * 0x19660d) & MASK for i in range(WORDS)] +NEIGHBOR0 = [(0xdeadbeef + i) & MASK for i in range(64)] +NEIGHBOR2 = [(0xfeedface + i) & MASK for i in range(64)] +GROUP = (2, 3, 4) + + +def run(directory, consumer, env, mode): + return _run(directory, consumer, env, mode, f"<{WORDS}I") + + +def no_debug_errors(result): + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors[0] + + +def root_srv_blob(*, two_srvs=False, param2_type=3): + """DXBC RTS0 (v1.1) container matching startup_stream_consumer.cpp root-SRV bindings: + param 0 = 3 root constants at b0 (s4-s6; shader uses s4-s5), + param 1 = descriptor table with 2 UAV slots at u0 (s7; output UAV at table byte 16), + param 2 = root descriptor at register(t1/b1, space0) (s[8:9]; type 3=SRV, 2=CBV), + optional param 3 = root SRV descriptor at register(t2, space0) (s[10:11]). + """ + nparams = 4 if two_srvs else 3 + poff = 24 + coff = poff + 12 * nparams + toff = coff + 12 + roff = toff + 8 + srv2_off = roff + 24 + srv3_off = srv2_off + 12 + soff = (srv3_off + 12) if two_srvs else (srv2_off + 12) + params = [ + struct.pack("<3I", 1, 0, coff), + struct.pack("<3I", 0, 0, toff), + struct.pack("<3I", param2_type, 0, srv2_off), + ] + if two_srvs: + params.append(struct.pack("<3I", 3, 0, srv3_off)) + payload = ( + struct.pack("<3I", 0, 0, 3) + + struct.pack("<2I", 1, roff) + + struct.pack("<6I", 1, 2, 0, 0, 0, 0xffffffff) + + struct.pack("<3I", 1, 0, 0) + ) + if two_srvs: + payload += struct.pack("<3I", 2, 0, 0) + rts0 = struct.pack("<6I", 2, nparams, poff, 0, soff, 0) + b"".join(params) + payload + assert len(rts0) == soff + part = b"RTS0" + struct.pack("<I", len(rts0)) + rts0 + return b"DXBC" + bytes(16) + struct.pack("<III", 1, 36 + len(part), 1) + struct.pack("<I", 36) + part + + +def make_program(*, two_srvs=False): + """Build gfx1013 compute ISA loading from 1 or 2 64-bit root SRV pointers via global_load_dword.""" + # With 3 root constants (s4-s6), 1 table (s7), and 1 or 2 root SRVs (s[8:9], optional s[10:11]): + # user SGPR count is 10 (1 root SRV) or 12 (2 root SRVs), followed by TGID_X, TGID_Y, TGID_Z. + gx = 12 if two_srvs else 10 + gy, gz = gx + 1, gx + 2 + rsrc2 = ((gx << 1) | TGID_X | TGID_Y | TGID_Z | tidig(3)) + second_saddr = 10 if two_srvs else 8 + code = b"".join([ + encode_sop1(0x03, 16, 7), # s_mov_b32 s16, s7 + encode_sop1(0x03, 17, 0x80), # s_mov_b32 s17, 0 + encode_smem(0x02, 20, 16, imm=0x10), # s_load_dwordx4 s[20:23], s[16:17], 0x10 + encode_sopp(0x0c, 0xc07f), # s_waitcnt lgkmcnt(0) + encode_vop3a(0x143, 3, 256 + 1, 0x80 + 2, 256 + 0), # v_mad_u32_u24 v3, v1, 2, v0 + encode_vop3a(0x143, 3, 256 + 2, 0x80 + 6, 256 + 3), # v_mad_u32_u24 v3, v2, 6, v3 + encode_sop2(0x26, 24, gy, 0x80 + 3), # s_mul_i32 s24, s<gy>, 3 + encode_sop2(0x00, 24, 24, gx), # s_add_u32 s24, s24, s<gx> + encode_sop2(0x26, 25, gz, 0x80 + 6), # s_mul_i32 s25, s<gz>, 6 + encode_sop2(0x00, 24, 24, 25), # s_add_u32 s24, s24, s25 + encode_sop2(0x26, 24, 24, 0x80 + 24), # s_mul_i32 s24, s24, 24 + encode_vop2(0x25, 3, 24, 3), # v_add_nc_u32 v3, s24, v3 + encode_vop2(0x1a, 4, 0x80 + 2, 3), # v_lshlrev_b32 v4, 2, v3 + encode_global(GLOBAL_LOAD_DWORD, 5, 4, 8, offset=0), # global_load_dword v5, v4, s[8:9] + encode_global(GLOBAL_LOAD_DWORD, 7, 4, second_saddr, offset=128), # global_load_dword v7, v4, s[...] offset:128 + encode_vop3a(0x169, 6, 256 + 3, 5, 0), # v_mul_lo_u32 v6, v3, s5 + encode_vop2(0x25, 6, 4, 6), # v_add_nc_u32 v6, s4, v6 + encode_sopp(0x0c, 0x3f70), # s_waitcnt vmcnt(0) + encode_vop3a(0x169, 5, 256 + 5, 0x80 + 33, 0), # v_mul_lo_u32 v5, v5, 33 + encode_vop2(0x25, 5, 256 + 5, 7), # v_add_nc_u32 v5, v5, v7 + encode_vop2(0x1d, 5, 256 + 5, 6), # v_xor_b32 v5, v5, v6 + encode_mubuf(0x1c, 5, 4, 20, offen=True), # buffer_store_dword v5, v4, s[20:23], 0 offen + encode_sopp(0x01, 0), # s_endpgm + ]) + return code, rsrc2 + + +def reference(*, two_srvs=False, offset0=0, offset1=0, shift1=32, swap_srvs=False, leak_neighbor=False): + src0 = (IN2 if swap_srvs else IN) + (NEIGHBOR2 if swap_srvs else NEIGHBOR0) + src1 = (IN if swap_srvs else (IN2 if two_srvs else IN)) + (NEIGHBOR0 if swap_srvs else (NEIGHBOR2 if two_srvs else NEIGHBOR0)) + off0 = offset1 if swap_srvs else offset0 + off1 = offset0 if swap_srvs else (offset1 if two_srvs else offset0) + bound0 = WORDS - off0 + bound1 = WORDS - off1 + out = [SENTINEL] * WORDS + for i in range(12 * 24): + v5 = src0[off0 + i] if (leak_neighbor or i < bound0) else 0 + idx1 = i + shift1 + v7 = src1[off1 + idx1] if (leak_neighbor or idx1 < bound1) else 0 + out[i] = (((v5 * 33 + v7) & MASK) ^ ((KEY + i * STRIDE) & MASK)) + return out + + +def setup_case(directory, *, two_srvs=False, param2_type=3, adapter="warp"): + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP="1", X2W_D3D12_DEBUG="1") + if adapter == "hardware": + env["X2W_TEST_DISPATCH_HARDWARE"] = "1" + (directory / "compute_root").write_bytes(root_srv_blob(two_srvs=two_srvs, param2_type=param2_type)) + env["X2W_TEST_COMPUTE_ROOT"] = str(directory / "compute_root") + code, rsrc2 = make_program(two_srvs=two_srvs) + (directory / "program").write_bytes(code) + (directory / "data").write_bytes(DATA) + (directory / "state").write_bytes(state_a(GROUP, rsrc2)) + return cache, env + + +def check_single_root_srv(base, consumer, dxc, adapter): + directory = base / "single" + cache, env = setup_case(directory, two_srvs=False, adapter=adapter) + + # First run before translation publishes the request and leaves output sentinels untouched. + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert len(lines(result, "Dispatch(3, 2, 2) refused: no translation")) == 1, result.stderr[-3000:] + key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cache, dxc, key) + + manifest_path = cache / f"{key:016x}.txt" + hlsl_path = cache / f"{key:016x}.cs.hlsl" + cso_path = cache / f"{key:016x}.cs.cso" + manifest = manifest_path.read_text(encoding="utf-8") + hlsl = hlsl_path.read_text(encoding="utf-8") + assert "srv 0 buf root 2" in manifest.splitlines(), manifest + assert "ByteAddressBuffer r0 : register(t0);" in hlsl, hlsl + assert "r0.Load(a)" in hlsl and "r0.Load(a + 128u)" in hlsl, hlsl + + # Manifest parser refusal controls on bad `srv ... buf root ...` lines and descriptor-word udsrc on a root SRV. + for bad_manifest, expected_reason in ( + (manifest.replace("srv 0 buf root 2", "srv 0 buf root -1"), + "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture"), + (manifest.replace("srv 0 buf root 2", "srv 0 buf root 2 trailing"), + "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture"), + (manifest.replace("srv 0 buf root 2", "srv 1 buf root 2"), + "a resource that is not a raw table buffer or a 1D/2D/2D-array/3D texture"), + (manifest.replace("ud 3\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2", + "ud 4\nudsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\nudsrc 2 rootconst 0 2\nudsrc 3 stride 0"), + "an entry value names a descriptor that is not a buffer input or output"), + ): + sub = base / f"bad-manifest-{ abs(hash(bad_manifest)) }" + sub_cache, sub_env = setup_case(sub, two_srvs=False, adapter=adapter) + (sub_cache / f"{key:016x}.txt").write_text(bad_manifest, encoding="utf-8") + (sub_cache / f"{key:016x}.cs.cso").write_bytes(cso_path.read_bytes()) + # The Python translator's sidecar marks these unmarked manifests as Python output, not stale native output. + (sub_cache / f"{key:016x}.cs.hlsl").write_bytes(hlsl_path.read_bytes()) + got, result = run(sub, consumer, sub_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert lines(result, f"compute pipeline {key:016x} not translated: {expected_reason}"), result.stderr[-3000:] + + # Translated single-root-SRV dispatch (and re-binding the same compute root signature). + expected0 = reference(two_srvs=False, offset0=0) + for mode in ("dispatch-root-srv", "dispatch-root-srv-same-root"): + got, result = run(directory, consumer, env, mode) + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + debug = clean(result) + assert got == expected0, (mode, sum(a != b for a, b in zip(got, expected0))) + print(f"{adapter}: single root SRV (srv 0 buf root 2) and same-root rebind verified; debug: {debug}", flush=True) + + # Non-zero byte offset into placed buffer (+16 bytes = 4 dwords) and upload allocation (+16 bytes = 4 dwords), + # plus out-of-bounds offset past the bounded backing returning 0 rather than reading neighbor 0xdeadbeef words. + expected_off4 = reference(two_srvs=False, offset0=4) + leaked_off4 = reference(two_srvs=False, offset0=4, leak_neighbor=True) + assert sum(a != b for a, b in zip(expected_off4, leaked_off4)) == 4 + got, result = run(directory, consumer, env, "dispatch-root-srv-offset") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off4 and got != leaked_off4 + + got, result = run(directory, consumer, env, "dispatch-root-srv-upload") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off4 and got != leaked_off4 + print(f"{adapter}: single root SRV non-zero offset (+16B placed, +16B upload) and bounded OOB=0 verified", flush=True) + + # Refusal controls leaving output sentinels untouched and logging the exact refusal reason. + for mode, reason in ( + ("dispatch-root-srv-unset", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-reset", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-root-changed", "a compute root SRV was not set since the compute root"), + ("dispatch-root-srv-null", "a compute root SRV has a null address"), + ("dispatch-root-srv-unaligned", "a compute root SRV address is not 4-byte aligned"), + ("dispatch-root-srv-unaligned-16", "a compute root SRV range is not 16-byte aligned in its resource"), + ("dispatch-root-srv-unmapped", "a compute root SRV is in title memory outside any placed buffer"), + ("dispatch-root-srv-copied", "a compute root SRV is in a placed buffer that does not alias title memory"), + ("dispatch-root-srv-same-buffer", "an output buffer is also an input"), + ): + got, result = run(directory, consumer, env, mode) + assert got == [SENTINEL] * WORDS, mode + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith(reason), (mode, refusal, result.stderr[-3000:]) + assert not lines(result, "Dispatch(3, 2, 2) translated"), mode + no_debug_errors(result) + print(f"{adapter}: single root SRV refusal controls (unset, reset, root-changed, unaligned, unmapped, copied, UAV alias) verified", flush=True) + + # Wrong root parameter kind refusal control: param 2 declared as root CBV (type 2) instead of root SRV (type 3). + cbv_dir = base / "wrong-kind-cbv" + cbv_cache, cbv_env = setup_case(cbv_dir, two_srvs=False, param2_type=2, adapter=adapter) + got, result = run(cbv_dir, consumer, cbv_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + cbv_key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cbv_cache, dxc, cbv_key) + assert "srv 0 buf root 2" in (cbv_cache / f"{cbv_key:016x}.txt").read_text(encoding="utf-8").splitlines() + got, result = run(cbv_dir, consumer, cbv_env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith("a compute root input is not a shader resource view parameter"), ( + refusal, + result.stderr[-3000:], + ) + no_debug_errors(result) + print(f"{adapter}: wrong root parameter kind (root CBV at param 2) refused cleanly", flush=True) + + +def check_two_root_srvs(base, consumer, dxc, adapter): + directory = base / "two" + cache, env = setup_case(directory, two_srvs=True, adapter=adapter) + + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert got == [SENTINEL] * WORDS + assert len(lines(result, "Dispatch(3, 2, 2) refused: no translation")) == 1, result.stderr[-3000:] + key = int(lines(result, "x2w-draw compute request")[0].split()[3], 16) + translate(cache, dxc, key) + + manifest_path = cache / f"{key:016x}.txt" + hlsl_path = cache / f"{key:016x}.cs.hlsl" + cso_path = cache / f"{key:016x}.cs.cso" + manifest = manifest_path.read_text(encoding="utf-8") + hlsl = hlsl_path.read_text(encoding="utf-8") + assert "srv 0 buf root 2" in manifest.splitlines() and "srv 1 buf root 3" in manifest.splitlines(), manifest + assert "ByteAddressBuffer r0 : register(t0);" in hlsl and "ByteAddressBuffer r1 : register(t1);" in hlsl, hlsl + assert "r0.Load(a)" in hlsl and "r1.Load(a + 128u)" in hlsl, hlsl + + expected_two = reference(two_srvs=True, offset0=0, offset1=0) + assert expected_two != reference(two_srvs=False, offset0=0) + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_two + print(f"{adapter}: two root SRVs (srv 0 buf root 2, srv 1 buf root 3) verified", flush=True) + + # Non-zero offsets into both placed buffers (+16B = 4 dwords on root SRV 0, +32B = 8 dwords on root SRV 1) + OOB=0 on root SRV 1. + expected_off = reference(two_srvs=True, offset0=4, offset1=8) + leaked_off = reference(two_srvs=True, offset0=4, offset1=8, leak_neighbor=True) + assert sum(a != b for a, b in zip(expected_off, leaked_off)) == 8 + got, result = run(directory, consumer, env, "dispatch-root-srv-offset") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_off and got != leaked_off + print(f"{adapter}: two root SRVs non-zero offsets (+16B/+32B) and bounded OOB=0 (8 OOB lanes) verified", flush=True) + + # Second root SRV unset while first root SRV is set must refuse cleanly. + got, result = run(directory, consumer, env, "dispatch-root-srv-unset-second") + assert got == [SENTINEL] * WORDS + refusal = lines(result, "Dispatch(3, 2, 2) refused:") + assert len(refusal) == 1 and refusal[0].endswith("a compute root SRV was not set since the compute root"), ( + refusal, + result.stderr[-3000:], + ) + no_debug_errors(result) + + # Negative control 1: skipping the Dispatch leaves all 320 output words at SENTINEL (288 mismatches vs expected). + got, result = run(directory, consumer, env, "dispatch-root-srv-none") + assert not lines(result, "Dispatch(3, 2, 2) translated") + assert got == [SENTINEL] * WORDS and sum(a != b for a, b in zip(got, expected_two)) == 288 + + # Negative control 2: mutating the root SRV binding in the manifest (swapping root 2 and root 3) changes all 288 active words. + swapped_manifest = manifest.replace("srv 0 buf root 2\nsrv 1 buf root 3", "srv 0 buf root 3\nsrv 1 buf root 2") + assert swapped_manifest != manifest + manifest_path.write_text(swapped_manifest, encoding="utf-8") + expected_swapped = reference(two_srvs=True, swap_srvs=True) + assert sum(a != b for a, b in zip(expected_swapped, expected_two)) == 288 + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_swapped and sum(a != b for a, b in zip(got, expected_two)) == 288 + manifest_path.write_text(manifest, encoding="utf-8") + + # Negative control 3: mutating the translated shader (dropping the +128u byte offset on r1.Load) changes all 288 active words. + mutated_hlsl = hlsl.replace("r1.Load(a + 128u)", "r1.Load(a)") + assert mutated_hlsl != hlsl + hlsl_path.write_text(mutated_hlsl, encoding="utf-8") + subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", cso_path, hlsl_path], check=True) + expected_mutated = reference(two_srvs=True, shift1=0) + assert sum(a != b for a, b in zip(expected_mutated, expected_two)) == 288 + got, result = run(directory, consumer, env, "dispatch-root-srv") + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr[-3000:] + clean(result) + assert got == expected_mutated and sum(a != b for a, b in zip(got, expected_two)) == 288 + print(f"{adapter}: negative controls (skip Dispatch, swap root SRV bindings, mutate HLSL offset) verified", flush=True) + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + check_single_root_srv(base, consumer, dxc, adapter) + check_two_root_srvs(base, consumer, dxc, adapter) + print(f"startup_compute_root_srv_dispatch: PASS on {adapter}") + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[3] not in ("warp", "hardware"): + sys.exit(__doc__) + main(*sys.argv[1:4]) diff --git a/tests/startup_compute_tg_size_check.py b/tests/startup_compute_tg_size_check.py new file mode 100644 index 0000000000..916d9cecfd --- /dev/null +++ b/tests/startup_compute_tg_size_check.py @@ -0,0 +1,423 @@ +#!/usr/bin/env python3 +"""Verify COMPUTE_PGM_RSRC2.TG_SIZE_EN (#2274 Part A) in tools/startup/gfx2hlsl.py. + + (no arguments) pure-Python translation, uniformity and refusal controls + dispatch <dxc> <offscreen_check> <warp|hardware> + translate, compile with DXC cs_6_0, dispatch and compare all 320 words + control <dropped-base|swapped-mask> <dxc> <offscreen_check> <warp|hardware> + mutated translation must mismatch on readback + +For groups of at most 32 threads (one wave), TG_SIZE[11:6] (wave ID, mask 0xfc0) is identically 0. +TG_SIZE sits in the SGPR immediately following USER_SGPR and any enabled TGID_X/Y/Z SGPRs. +Only `s_and_b32 R, TG, 0xfc0` (or `0xfc0, TG`) into a plain SGPR <= 105 is accepted, lowering to +`R = 0u; scc = false;` with `R` tracked as `('const', 0)`; every other read of the untouched +TG_SIZE SGPR is refused. +""" + +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_compute_check import ( # noqa: E402 + SENTINEL, + TGID_X, + TGID_Y, + TGID_Z, + TG_SIZE_EN, + USER7, + WORDS, + refused, + root_blob, + tidig, +) + + +def le32(word): + return struct.pack('<I', word & 0xffffffff) + + +def sop1(op, sdst, ssrc0, lit=None): + b = le32(0xbe800000 | ((sdst & 0x7f) << 16) | ((op & 0xff) << 8) | (ssrc0 & 0xff)) + return b if lit is None else b + le32(lit) + + +def sop2(op, sdst, ssrc0, ssrc1, lit=None): + b = le32(0x80000000 | ((op & 0x7f) << 23) | ((sdst & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff)) + return b if lit is None else b + le32(lit) + + +def sopk(op, sdst, simm16): + return le32(0xb0000000 | ((op & 0x1f) << 23) | ((sdst & 0x7f) << 16) | (simm16 & 0xffff)) + + +def sopc(op, ssrc0, ssrc1, lit=None): + b = le32(0xbf000000 | ((op & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff)) + return b if lit is None else b + le32(lit) + + +def sopp(op, simm=0): + return le32(0xbf800000 | ((op & 0x7f) << 16) | (simm & 0xffff)) + + +def vop1(op, vdst, src0, lit=None): + b = le32(0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def vop2(op, vdst, src0, vsrc1, lit=None): + b = le32(((op & 0x3f) << 25) | ((vdst & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def vop3(op, vdst, src0, src1, src2=0): + w0 = 0xd4000000 | ((op & 0x3ff) << 16) | (vdst & 0xff) + w1 = ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff) + return le32(w0) + le32(w1) + + +S_MOV_B32 = 0x03 +S_MOV_B64 = 0x04 +S_ADD_U32 = 0x00 +S_CSELECT_B32 = 0x0a +S_AND_B32 = 0x0e +S_OR_B32 = 0x10 +S_LSHL_B32 = 0x1e +S_LSHR_B32 = 0x1f +S_ADDK_I32 = 0x0f +S_CMP_EQ_U32 = 0x00 +V_MOV_B32 = 0x01 +V_LSHLREV_B32 = 0x1a +V_ADD_NC_U32 = 0x25 +V_MAD_U32_U24 = 0x143 +V_MBCNT_LO_U32_B32 = 0x365 +V_MBCNT_HI_U32_B32 = 0x366 + +INLINE_0 = 128 +INLINE_2 = 130 +INLINE_4 = 132 +INLINE_6 = 134 +INLINE_17 = 128 + 17 +INLINE_42 = 128 + 42 +INLINE_NEG1 = 193 +M0 = 124 +EXEC_LO = 126 +VCC_LO = 106 +LIT = 255 + +S_LOAD_X8_S12_S10 = bytes.fromhex('05030cf4000000fa') +S_WAITCNT_LGKM0 = bytes.fromhex('7fc08cbf') +BUFFER_STORE_X4_V8_V4_S16 = bytes.fromhex('001078e004080480') +S_ENDPGM = sopp(0x01, 0) + +MASK_A = 0x85241249 +MASK_B = 0x0f0f0f0f +GROUP = (4, 2, 2) +DISPATCH_GROUPS = (2, 1, 1) +RSRC2 = USER7 | TGID_X | TG_SIZE_EN | tidig(3) + +# Two-group compute shader with TGID_X (s7) and TG_SIZE_EN (s8). +# Each thread computes: +# s20 = s8 & 0xfc0 (0u; scc = false) +# s23 = scc ? 17 : 42 (42, verifying scc = false) +# v8 = v_mbcnt_lo_u32_b32(MASK_A, s20) +# v9 = v_mbcnt_lo_u32_b32(MASK_B, v8) +# v10 = s23 +# v11 = gid.x * 16 + (tid.x + 4 * (tid.y + 2 * tid.z)) +# and stores uint4(v8, v9, v10, v11) at record index v11. +MAIN_PROGRAM = b''.join([ + sop1(S_MOV_B32, 10, 6), + sop1(S_MOV_B32, 11, INLINE_0), + S_LOAD_X8_S12_S10, + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + sop2(S_CSELECT_B32, 23, INLINE_17, INLINE_42), + sop1(S_MOV_B32, 21, LIT, MASK_A), + sop1(S_MOV_B32, 22, LIT, MASK_B), + vop3(V_MAD_U32_U24, 3, 256 + 2, INLINE_2, 256 + 1), + vop3(V_MAD_U32_U24, 3, 256 + 3, INLINE_4, 256 + 0), + sop2(S_LSHL_B32, 24, 7, INLINE_4), + vop2(V_ADD_NC_U32, 11, 24, 3), + vop2(V_LSHLREV_B32, 4, INLINE_4, 11), + vop3(V_MBCNT_LO_U32_B32, 8, 21, 20), + vop3(V_MBCNT_LO_U32_B32, 9, 22, 256 + 8), + vop1(V_MOV_B32, 10, 23), + S_WAITCNT_LGKM0, + BUFFER_STORE_X4_V8_V4_S16, + S_ENDPGM, +]) + +EXPECTED_MAIN_ASM = [ + 's_mov_b32 s10, s6', + 's_mov_b32 s11, 0', + 's_load_dwordx8 s[12:19], s[10:11], 0x0', + 's_and_b32 s20, s8, 0xfc0', + 's_cselect_b32 s23, 17, 42', + 's_mov_b32 s21, 0x85241249', + 's_mov_b32 s22, 0xf0f0f0f', + 'v_mad_u32_u24 v3, v2, 2, v1', + 'v_mad_u32_u24 v3, v3, 4, v0', + 's_lshl_b32 s24, s7, 4', + 'v_add_nc_u32_e32 v11, s24, v3', + 'v_lshlrev_b32_e32 v4, 4, v11', + 'v_mbcnt_lo_u32_b32 v8, s21, s20', + 'v_mbcnt_lo_u32_b32 v9, s22, v8', + 'v_mov_b32_e32 v10, s23', + 's_waitcnt lgkmcnt(0)', + 'buffer_store_dwordx4 v[8:11], v4, s[16:19], 0 offen', + 's_endpgm', +] + + +def translate(code=MAIN_PROGRAM, rsrc2=RSRC2, group=GROUP): + return G.ComputePipeline(code, root_blob(), rsrc2, group) + + +def expected_words(): + out = [SENTINEL] * WORDS + gx_count, gy_count, gz_count = DISPATCH_GROUPS + lx, ly, lz = GROUP + assert gy_count == 1 and gz_count == 1 + for gx in range(gx_count): + for tz in range(lz): + for ty in range(ly): + for tx in range(lx): + lane = tx + lx * (ty + ly * tz) + below = (1 << lane) - 1 + w8 = (MASK_A & below).bit_count() + w9 = (MASK_B & below).bit_count() + w8 + w10 = 42 + w11 = gx * (lx * ly * lz) + lane + out[4 * w11:4 * w11 + 4] = [w8, w9, w10, w11] + return out + + +def check_controls(): + assert [asm for _, _, _, asm in G.decode(MAIN_PROGRAM)] == EXPECTED_MAIN_ASM + + # 1. Placement of TG_SIZE SGPR across TGID combinations (USER7 -> s7..s10). + for rsrc2, tg_reg in ( + (USER7 | TG_SIZE_EN, 7), + (USER7 | TGID_X | TG_SIZE_EN, 8), + (USER7 | TGID_X | TGID_Z | TG_SIZE_EN, 9), + (USER7 | TGID_X | TGID_Y | TGID_Z | TG_SIZE_EN, 10), + ): + pipe = translate(code=S_ENDPGM, rsrc2=rsrc2, group=(8, 4, 1)) + assert pipe.tg_size_sgpr == tg_reg, (hex(rsrc2), pipe.tg_size_sgpr, tg_reg) + assert pipe.cs.sym.get(tg_reg) == ('tg_size',), (hex(rsrc2), pipe.cs.sym) + assert not pipe.cs.uniform_source('s%d' % tg_reg) + assert pipe.cs.is_const(tg_reg) is None + assert pipe.cs.const_u32('s%d' % tg_reg) is None + + # 2. Standalone s_and_b32 R, TG, 0xfc0 (both operand orders and in-place R == TG). + for and_insn in ( + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + sop2(S_AND_B32, 20, LIT, 8, 0xfc0), + ): + pipe = translate(code=and_insn + S_ENDPGM) + hlsl = pipe.hlsl_cs() + assert ' s20 = 0u;\n scc = false;' in hlsl, hlsl + assert 'uint s8' not in hlsl, hlsl + assert pipe.cs.sym.get(20) == ('const', 0) + assert pipe.cs.sym.get(8) == ('tg_size',) + assert pipe.cs.scc_uniform is True + + # In-place overwrite `s_and_b32 s8, s8, 0xfc0` lowers to 0u and turns s8 into ('const', 0). + inplace = translate(code=sop2(S_AND_B32, 8, 8, LIT, 0xfc0) + sop1(S_MOV_B32, 20, 8) + S_ENDPGM) + inplace_hlsl = inplace.hlsl_cs() + assert ' s8 = 0u;\n scc = false;\n s20 = 0x00000000u;' in inplace_hlsl, inplace_hlsl + assert inplace.cs.sym.get(8) == ('const', 0) + + # 3. Full program: s_and_b32 R, TG, 0xfc0 feeds R into v_mbcnt_lo_u32_b32, plus standalone v_mbcnt_lo/hi. + main_hlsl = translate().hlsl_cs() + assert ' s20 = 0u;\n scc = false;' in main_hlsl, main_hlsl + assert 'countbits(0x85241249u & ((1u << (tid.x + 4u * (tid.y + 2u * tid.z))) - 1u)) + 0x00000000u' in main_hlsl, main_hlsl + assert 'countbits(0x0f0f0f0fu & ((1u << (tid.x + 4u * (tid.y + 2u * tid.z))) - 1u)) + v8' in main_hlsl, main_hlsl + + hi_prog = b''.join([ + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + vop3(V_MBCNT_HI_U32_B32, 8, INLINE_NEG1, 20), + S_ENDPGM, + ]) + hi_hlsl = translate(code=hi_prog).hlsl_cs() + assert ' v8 = 0x00000000u;' in hi_hlsl, hi_hlsl + + # 4. >32 threads per group with TG_SIZE_EN is refused. + for bad_group in ((8, 4, 2), (33, 1, 1), (64, 1, 1)): + refused('TG_SIZE_EN requires at most 32 threads per group', + lambda g=bad_group: translate(code=S_ENDPGM, group=g)) + + # 5. Disallowed reads of TG_SIZE are refused. + bad_tg_reads = [ + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 20, 8, LIT, 0x3f)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 20, 8, LIT, 0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 20, 8, 8)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, M0, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, EXEC_LO, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, VCC_LO, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_AND_B32, 106, 8, LIT, 0xfc0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop1(S_MOV_B32, 20, 8)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_OR_B32, 20, 8, INLINE_0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_LSHR_B32, 20, 8, INLINE_6)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop2(S_LSHL_B32, 20, 8, INLINE_2)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sop1(S_MOV_B64, 20, 8)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', sopc(S_CMP_EQ_U32, 8, INLINE_0)), + ('s_addk_i32 on tg_size data', sopk(S_ADDK_I32, 8, 1)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', vop2(V_ADD_NC_U32, 3, 8, 0)), + ('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', vop1(V_MOV_B32, 3, 8)), + ('v_mbcnt_lo_u32_b32 requires a VGPR or known base', vop3(V_MBCNT_LO_U32_B32, 8, INLINE_NEG1, 8)), + ('v_mbcnt_lo_u32_b32 requires a known mask', vop3(V_MBCNT_LO_U32_B32, 8, 8, INLINE_0)), + ] + for msg, insn in bad_tg_reads: + refused(msg, lambda c=insn + S_ENDPGM: translate(code=c).hlsl_cs()) + + # Modified s_and_b32 (e.g. non-empty mods on unit probe) is also refused. + probe = G.Stage.__new__(G.Stage) + probe.sym = {8: ('tg_size',)} + probe.used_s = set() + probe.lines = [] + probe.exec_known = True + refused('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', + lambda: probe.scalar('s_and_b32', ['s20', 's8', '0xfc0'], ['clamp'])) + + # Descriptor-path protection: mixing descriptor and tg_size in s_add_u32 refuses tg_size instead of silently dropping it. + desc_mix = b''.join([ + sop1(S_MOV_B32, 10, 6), + sop1(S_MOV_B32, 11, INLINE_0), + S_LOAD_X8_S12_S10, + sop2(S_ADD_U32, 12, 12, 8), + S_ENDPGM, + ]) + refused('TG_SIZE register s8 read outside s_and_b32 with 0xfc0', lambda: translate(code=desc_mix).hlsl_cs()) + + # 6. Overwriting TG first restores ordinary scalar behavior. + overwrite_const = b''.join([ + sop1(S_MOV_B32, 8, 128 + 5), + sop2(S_AND_B32, 20, 8, LIT, 0x3f), + vop2(V_ADD_NC_U32, 3, 8, 0), + S_ENDPGM, + ]) + ov_const_hlsl = translate(code=overwrite_const).hlsl_cs() + assert ' s8 = 0x00000005u;\n s20 = 0x00000005u & 0x0000003fu;' in ov_const_hlsl, ov_const_hlsl + assert ' v3 = 0x00000005u + v0;' in ov_const_hlsl, ov_const_hlsl + + overwrite_runtime = b''.join([ + sop1(S_MOV_B32, 8, 7), + sop2(S_AND_B32, 20, 8, LIT, 0x3f), + vop2(V_ADD_NC_U32, 3, 8, 0), + S_ENDPGM, + ]) + ov_rt_hlsl = translate(code=overwrite_runtime).hlsl_cs() + assert ' s8 = s7;\n s20 = s8 & 0x0000003fu;' in ov_rt_hlsl, ov_rt_hlsl + assert ' v3 = s8 + v0;' in ov_rt_hlsl, ov_rt_hlsl + + # 7. Branch / execz interactions: s_and_b32 inside s_cbranch_execz live-out is refused; dead-out is accepted. + execz_live = b''.join([ + sopp(0x08, 2), # s_cbranch_execz +2 dwords (skips 8-byte s_and_b32 with literal 0xfc0) + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + vop1(V_MOV_B32, 3, 20), + S_ENDPGM, + ]) + refused('definition of s20, live where the block joins', lambda: translate(code=execz_live).hlsl_cs()) + + execz_dead = b''.join([ + sopp(0x08, 2), # s_cbranch_execz +2 dwords + sop2(S_AND_B32, 20, 8, LIT, 0xfc0), + S_ENDPGM, + ]) + translate(code=execz_dead).hlsl_cs() + + # Overwriting TG on one branch arm and reading it at join refuses (never leaks ('tg_size',) across a join). + join_leak = b''.join([ + sopc(S_CMP_EQ_U32, 7, INLINE_0), + sopp(0x04, 2), # s_cbranch_scc0 +2 dwords + sop2(S_AND_B32, 8, 8, LIT, 0xfc0), + sop1(S_MOV_B32, 20, 8), + S_ENDPGM, + ]) + refused('holding joined at a branch target', lambda: translate(code=join_leak).hlsl_cs()) + + print('tg_size_en: entry layout, s_and_b32 0xfc0 folding, v_mbcnt_lo base, overwrite and refusals pass') + + +CONTROLS = { + 'dropped-base': (' + v8', ''), + 'swapped-mask': ('v8 = (countbits(0x85241249u', 'v8 = (countbits(0x0f0f0f0fu'), +} + +CONTROL_MISMATCH = { + 'dropped-base': 'word=5 expected=00000002 actual=00000001', + 'swapped-mask': 'word=8 expected=00000001 actual=00000002', +} + + +def mutate(hlsl, control): + old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def check_dispatch(dxc, runner, adapter, control=None): + runner = str(Path(runner).resolve()) + out = ROOT / 'out' + out.mkdir(exist_ok=True) + hlsl = translate().hlsl_cs() + if control: + if control not in CONTROLS: + raise SystemExit(f'unknown control {control!r}') + hlsl = mutate(hlsl, control) + with tempfile.TemporaryDirectory(dir=out) as tmp: + d = Path(tmp) + src, cso, case = d / 'tg_size.hlsl', d / 'tg_size.cso', d / 'tg_size.case' + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + gx, gy, gz = DISPATCH_GROUPS + constants = [0] * 16 + case.write_bytes( + struct.pack('<I', gx | (gy << 8) | (gz << 16)) + + struct.pack('<%dI' % WORDS, *expected_words()) + + struct.pack('<16I', *constants) + ) + run = subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], + capture_output=True, text=True) + print(run.stdout, end='') + if run.returncode == 77: + return 77 + diagnostics = [] + for line in run.stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) + if control: + first = diagnostics[:1] + if (run.returncode != 1 or not any('expected=' in line for line in diagnostics) + or first != [CONTROL_MISMATCH[control]]): + raise AssertionError( + 'control %s: unexpected result (exit %d) %s' % (control, run.returncode, run.stderr) + ) + print('control %s: rejected at %s' % (control, first[0])) + elif run.returncode or diagnostics: + raise AssertionError('tg_size dispatch: %s' % (run.stderr or 'exit %d' % run.returncode)) + else: + print('tg_size dispatch: all %d words match (%dx%dx%d groups x %dx%dx%d threads)' % ( + WORDS, gx, gy, gz, *GROUP)) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 1: + check_controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + sys.exit(check_dispatch(*sys.argv[2:])) + elif len(sys.argv) == 6 and sys.argv[1] == 'control': + sys.exit(check_dispatch(*sys.argv[3:], control=sys.argv[2])) + else: + sys.exit(__doc__) diff --git a/tests/startup_compute_translate_check.py b/tests/startup_compute_translate_check.py index dbf5d63248..069b6b2a9d 100644 --- a/tests/startup_compute_translate_check.py +++ b/tests/startup_compute_translate_check.py @@ -29,8 +29,8 @@ def state_a(group, rsrc2): - # The observed offsets: dword 3 = X | Y << 16, dword 4 = Z, dword 6 = COMPUTE_PGM_RSRC2. - return struct.pack('<7I', 0, 0, 0, group[0] | group[1] << 16, group[2], 0, rsrc2) + # Dword 3 holds X and Y, dword 4 holds Z and the wave32 bit, and dword 6 holds COMPUTE_PGM_RSRC2. + return struct.pack('<7I', 0, 0, 0, group[0] | group[1] << 16, group[2] | (1 << 20), 0, rsrc2) def write_request(cache, code, state, data=DATA, root=None, desc_sizes=None): diff --git a/tests/startup_compute_waterfall.py b/tests/startup_compute_waterfall.py new file mode 100644 index 0000000000..ce8e00ab25 --- /dev/null +++ b/tests/startup_compute_waterfall.py @@ -0,0 +1,119 @@ +"""Source-built four-lane numeric waterfall for the compute readfirstlane fixture (#2644).""" +import struct +import subprocess + +from compute_load_format_check import check_references +from startup_gfx2hlsl_compute_check import G, MASK, SENTINEL, USER7, WORDS, assemble, refused, root_blob + + +# The input buffer contains the keys. Root constant s4 selects how many lanes enter the loop. +# Every lane writes its result after the original EXEC is restored, including the initial 13 for inactive lanes. +PREFIX = ( + ('s_mov_b32 s10, s6', '06038abe'), ('s_mov_b32 s11, 0', '80038bbe'), + ('s_load_dwordx8 s[12:19], s[10:11], 0', '05030cf4000000fa'), ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('v_lshlrev_b32_e32 v4, 2, v0', '82000834'), ('buffer_load_dword v5, v4, s[12:15], 0 offen', '001030e004050380'), + ('s_waitcnt vmcnt(0)', '703f8cbf'), ('v_mov_b32_e32 v7, 13', '8d020e7e'), + ('s_mov_b32 s26, exec_lo', '7e039abe'), ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), +) +SAVE = ('s_mov_b32 s21, exec_lo', '7e0395be') +HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e') +COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d') +ADD = ('s_add_u32 s23, s22, 17', '16911780') +CONST = ('s_mov_b32 s23, 17', '910397be') +USE_CONST = ('v_add_nc_u32 v7, s23, v7', '170e0e4a') +XOR = ('v_xor_b32_e32 v7, s23, v0', '17000e3a') +CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be') +RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe') +STORE = ('buffer_store_dword v7, v4, s[16:19], 0 offen', '001070e004070480') +END = ('s_endpgm', '000081bf') +FIXED_LOAD = (('s_load_dwordx4 s[28:31], s[10:11], 0', '050708f4000000fa'), ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('v_mov_b32_e32 v8, s22', '1602107e'), ('buffer_load_dword v7, v8, s[28:31], 0 offen', '001030e008070780'), + ('s_waitcnt vmcnt(0)', '703f8cbf')) + + +def program(*, before_save=(), after_save=(), compare=COMPARE, body=(ADD, XOR), after_restore=()): + loop = (HEAD, compare, *body, CLOSE) + offset = -(sum(len(bytes.fromhex(code)) for _, code in loop) // 4 + 1) + branch = ('s_cbranch_scc1 %d' % offset, struct.pack('<I', 0xbf850000 | (offset & 0xffff)).hex()) + return (*PREFIX, *before_save, SAVE, *after_save, *loop, branch, RESTORE, *after_restore, STORE, END) + + +def translate(rows, group=(4, 1, 1)): + code = bytes.fromhex(''.join(word for _, word in rows)) + return G.ComputePipeline(code, root_blob(), USER7, group).hlsl_cs() + + +def controls(llvm_mc=None): + live = ('v_mov_b32_e32 v7, s23', '17020e7e') + copy = ('s_mov_b32 s24, s21', '150398be') + reset = ('s_mov_b32 s23, 0', '800397be') + conditional = ('s_cbranch_scc0 1', '010084bf') + cases = ( + (program(), None), + (program(after_save=(('s_nop 0', '000080bf'),)), None), + (program(body=FIXED_LOAD), None), + (program(after_restore=(reset, live)), None), + (program(body=(('s_mov_b32 s23, s22', '160397be'), ('s_lshl_b32 s23, s23, 1', '1781178f'), + ('s_or_b32 s23, s23, 1', '17811788'), ('s_and_b32 s23, s23, 31', '179f1787'), + ('v_add_nc_u32_e32 v7, s23, v0', '17000e4a'))), None), + # A body scalar that does not depend on the key holds one value in every iteration: read after the loop. + (program(body=(CONST, XOR), after_restore=(USE_CONST,)), None), + (program(body=(CONST, ('s_add_u32 s23, s23, s22', '17161780'), XOR), after_restore=(USE_CONST,)), + 'body scalar is live'), + (program(body=(CONST, XOR), after_restore=(('v_mov_b32_e32 v7, s22', '16020e7e'),)), 'body scalar is live'), + (program(body=(STORE,)), 'body instruction buffer_store_dword'), + (program(body=(('v_mbcnt_lo_u32_b32 v7, exec_lo, 0', '070065d77e000100'),)), 'body instruction v_mbcnt'), + (program(after_restore=(live,)), 'body scalar is live'), + (program(after_restore=(conditional, reset, live)), 'body scalar is live'), + (program(after_save=(('s_mov_b32 s21, 1', '810395be'),)), 'unchanged copy of EXEC'), + (program(body=(('s_add_u32 s23, s23, 1', '17811780'), XOR)), 'loop-carried scalar'), + (program(body=(('s_add_u32 s23, 0, src_scc', '80fd1780'), XOR)), 'loop-carried scalar'), + (program(body=(copy, XOR)), 'reads or changes a lane mask'), + (program(compare=('v_cmpx_eq_i32_e32 s22, v4', '1608247d')), 'same key'), + (program(before_save=(conditional,)), 'another branch enters'), + (program(body=(('s_load_dwordx4 s[28:31], s[22:23], 0', '0b0708f4000000fa'), *FIXED_LOAD[1:])), + 'per-lane descriptor selection'), + ) + for rows, reason in cases: + if llvm_mc: + source = '\n'.join(asm for asm, _ in rows) + '\n' + assert assemble(llvm_mc, source) == bytes.fromhex(''.join(word for _, word in rows)), source + if reason: + refused(reason, lambda: translate(rows)) + else: + assert 's22 = v5;' in translate(rows) + refused('at most 32 threads', lambda: translate(program(), (33, 1, 1))) + + +def dispatch(directory, dxc, runner, adapter): + for label, body in (('arithmetic', (ADD, XOR)), ('fixed-buffer', FIXED_LOAD), ('invariant', (CONST, XOR))): + src, shader = directory / 'waterfall.hlsl', directory / 'waterfall.cso' + after = (USE_CONST,) if label == 'invariant' else () + src.write_text(translate(program(body=body, after_restore=after)), encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', shader, src], check=True) + cases = [] + inputs = [(n, (64, 32, 64, 96)) for n in range(5)] + if label == 'arithmetic': + inputs.append((4, (MASK, MASK, 0, 0))) + for active, keys in inputs: + source = [17 * i + 9 for i in range(WORDS)] + source[:4] = keys + output = [13] * 4 + for lane, key in enumerate(keys[:active]): + output[lane] = (((key + 17) & MASK) ^ lane) if label == 'arithmetic' else source[key // 4] + if label == 'invariant': # the body scalar is 17 in every pass: v7 = (17 ^ lane) + 17 + output[lane] = (17 ^ lane) + 17 + if label == 'invariant': + output = [o if i < active else 13 + 17 for i, o in enumerate(output)] # the add runs for every lane + case = directory / ('waterfall-%d.case' % len(cases)) + words = [1, *output, *([SENTINEL] * (WORDS - 4)), active, *([0] * 15), *source] + case.write_bytes(struct.pack('<%dI' % len(words), *words)) + cases.append((case, 'keys %s, %d active' % (keys, active), None)) + if active == 4 and keys[0] != keys[1]: + wrong = (output[0] ^ 1) if label != 'fixed-buffer' else output[0] + words[2] = wrong # lane 1 using lane 0's key + case = directory / 'waterfall-wrong.case' + case.write_bytes(struct.pack('<%dI' % len(words), *words)) + cases.append((case, 'uniform key', 'word=1 expected=%08x actual=%08x' % (wrong, output[1]))) + check_references(label + ' waterfall', runner, adapter, shader, cases) + return 0 diff --git a/tests/startup_compute_waterfall_heap_check.py b/tests/startup_compute_waterfall_heap_check.py new file mode 100644 index 0000000000..3229de8bd5 --- /dev/null +++ b/tests/startup_compute_waterfall_heap_check.py @@ -0,0 +1,488 @@ +"""Per-lane resource-heap record index inside a compute v_readfirstlane_b32 waterfall loop (#2644 T3). + +usage: + startup_compute_waterfall_heap_check.py [--llvm-mc <llvm-mc>] + startup_compute_waterfall_heap_check.py --dxil <dxc> + startup_compute_waterfall_heap_check.py --oracle <dxc> <offscreen_check> <warp|hardware> + startup_compute_waterfall_heap_check.py --dispatch <startup_stream_consumer> <dxc> <warp|hardware> + +Covers: +1. gfx2hlsl translation and manifest generation for bounded per-lane resource-heap indices in compute + waterfall loops, including both direct heap offsets (s_lshl_b32 + s_load_dwordx4 s[...], s[8:9], sI) + and the adjacent 64-bit pointer-add carry form (s_add_u32 + s_add_u32 0, src_scc / s_addc_u32, with + either in-body s_lshl_b32 or pre-loop v_lshlrev_b32 ..., 5), plus v_min_u32 and v_bfe_u32 bounds. +2. Soundness negative controls: unbounded keys, oversized masks, one-arm diamond bounds, bounded writes under + narrowed EXEC, missing/wrong shift, missing resheap root flag, non-zero high word, broken carry, descriptor + mutation, exit-live scalars, and forbidden store/formatted/idxen uses. +3. Independent DXIL handle metadata assertions via DXC cs_6_0: confirms the resource handle selects SRV space 2 + [0..3] with nonUniformIndex=true, and that stripping NonUniformResourceIndex changes it to false. +4. Four-record GPU oracle (--oracle): reference, static switch, no-marker, and first-active (asserting the + exact 12/25 first-active mismatches that distinguish lane-local selection from a wave-uniform shortcut). +5. End-to-end stand-in Dispatch fixture (--dispatch): translates both the direct-offset and 64-bit carry + waterfall programs via gfx2hlsl.py --pending, dispatches all five oracle key patterns plus active-lane + subsets through d3d12_xs.dll with the debug layer enabled, and verifies a short-range view heap that omits + the highest record (3) refuses cleanly before Dispatch. +""" +import argparse +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +import array_atomics_dxil_check as dxil # noqa: E402 +from startup_compute_dispatch_check import dispatch, lines # noqa: E402 +from startup_compute_request_check import DATA, prepare # noqa: E402 +from startup_compute_translate_check import state_a # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_heap_record_check as H # noqa: E402 +from startup_gfx2hlsl_compute_check import G, assemble, refused # noqa: E402 + +GROUP = (4, 1, 1) +NO_DATA = bytes(C.WORDS * 4) + +# Bounded four-record waterfall program matching the reference fixture (`bounded-waterfall.s`). +BOUNDED_PREFIX = ( + ('s_mov_b32 s12, s7', '07038cbe'), + ('s_mov_b32 s13, 0', '80038dbe'), + ('s_load_dwordx8 s[40:47], s[12:13], 0x0', '060a0cf4000000fa'), + ('s_waitcnt lgkmcnt(0)', '7fc08cbf'), + ('s_mov_b32 s9, 0', '800389be'), + ('v_lshlrev_b32_e32 v4, 2, v0', '82000834'), + ('buffer_load_dword v5, v4, s[40:43], 0 offen', '001030e004050a80'), + ('s_waitcnt vmcnt(0)', '703f8cbf'), +) +MASK_AND3 = ('v_and_b32_e32 v5, 3, v5', '830a0a36') +INIT_AND_GUARD = ( + ('v_mov_b32_e32 v7, 13', '8d020e7e'), + ('s_mov_b32 s26, exec_lo', '7e039abe'), + ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), + ('s_mov_b32 s21, exec_lo', '7e0395be'), +) +HEAD = ('v_readfirstlane_b32 s22, v5', '05052c7e') +COMPARE = ('v_cmpx_eq_i32_e32 s22, v5', '160a247d') +SHIFT5 = ('s_lshl_b32 s23, s22, 5', '1685178f') +HEAP_LOAD = ('s_load_dwordx4 s[28:31], s[8:9], s23', '040708f40000002e') +CARRY_ADD_S23 = ( + ('s_add_u32 s24, s8, s23', '08171880'), + ('s_add_u32 s25, 0, src_scc', '80fd1980'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), +) +CARRY_ADD_S22 = ( + ('s_add_u32 s24, s8, s22', '08161880'), + ('s_add_u32 s25, 0, src_scc', '80fd1980'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), +) +WAIT_LGKM = ('s_waitcnt lgkmcnt(0)', '7fc08cbf') +BODY_LOAD = ('buffer_load_dword v7, v4, s[28:31], 0 offen', '001030e004070780') +WAIT_VM = ('s_waitcnt vmcnt(0)', '703f8cbf') +CLOSE = ('s_andn2_wrexec_b32 s21, s21', '154795be') +RESTORE = ('s_mov_b32 exec_lo, s26', '1a03febe') +FINAL_STORE = ('buffer_store_dword v7, v4, s[44:47], 0 offen', '001070e004070b80') +END = ('s_endpgm', '000081bf') + +ENCODINGS = { + 'v_min_u32_e32 v5, 3, v5': '830a0a26', + 'v_bfe_u32 v5, v5, 0, 2': '050048d505010a02', + 'v_lshlrev_b32_e32 v5, 5, v5': '850a0a34', + 'v_lshlrev_b32_e32 v5, 4, v5': '840a0a34', + 'v_and_b32_e32 v5, 0x7ff, v5': 'ff0a0a36ff070000', + 's_lshl_b32 s22, s22, 5': '1685168f', + 's_lshl_b32 s23, s22, 4': '1684178f', + 's_mov_b32 s24, s23': '170398be', + 's_mov_b32 s24, s22': '160398be', + 's_load_dwordx4 s[28:31], s[8:9], s24': '040708f400000030', + 's_load_dwordx4 s[28:31], s[8:9], s22': '040708f40000002c', + 's_load_dwordx4 s[28:31], s[22:23], 0x0': '0b0708f4000000fa', + 's_addc_u32 s25, s9, 0': '09801982', + 's_mov_b32 s9, 1': '810389be', + 's_cmp_eq_u32 s4, 0': '048006bf', + 's_cbranch_scc0 1': '010084bf', + 's_cbranch_scc0 2': '020084bf', + 's_branch 1': '010082bf', + 's_nop 0': '000080bf', + 's_or_b32 s31, s31, 0': '1f801f88', + 's_mov_b32 s22, 0': '800396be', + 'v_mov_b32_e32 v7, s22': '16020e7e', + 'v_mov_b32_e32 v7, s28': '1c020e7e', + 'buffer_load_dword v7, v4, s[28:31], 0 idxen': '002030e004070780', + 'buffer_load_format_x v7, v4, s[28:31], 0 offen': '001000e004070780', + 'buffer_store_dword v7, v4, s[28:31], 0 offen': '001070e004070780', +} + +BOUNDED_ORACLE_HLSL = """\ +ByteAddressBuffer keys : register(t0); +#if defined(STATIC_SWITCH) +ByteAddressBuffer r0 : register(t1), r1 : register(t2), r2 : register(t3), r3 : register(t4); +#else +ByteAddressBuffer records[4] : register(t1); +#endif +RWByteAddressBuffer result : register(u0); +cbuffer config : register(b0) { uint active; }; + +[RootSignature("SRV(t0), DescriptorTable(SRV(t1, numDescriptors=4)), UAV(u0), RootConstants(num32BitConstants=1,b0)")] +[numthreads(4, 1, 1)] +void main(uint3 tid : SV_GroupThreadID) +{ + uint lane = tid.x; + uint value = 13; + if (lane < active) { +#if defined(FIRST_ACTIVE) + uint index = keys.Load(0) & 3; +#else + uint index = keys.Load(4 * lane) & 3; +#endif +#if defined(STATIC_SWITCH) + switch (index) { + case 0: value = r0.Load(4 * lane); break; + case 1: value = r1.Load(4 * lane); break; + case 2: value = r2.Load(4 * lane); break; + default: value = r3.Load(4 * lane); break; + } +#elif defined(NO_MARKER) + value = records[index].Load(4 * lane); +#else + value = records[NonUniformResourceIndex(index)].Load(4 * lane); +#endif + } + result.Store(4 * lane, value); +} +""" + +ORACLE_ROWS = ((0, 1, 2, 3), (3, 2, 1, 0), (2, 1, 2, 3), (4, 9, 14, 19), (7, 7, 7, 7)) + + +def row_pair(asm): + return (asm, ENCODINGS[asm]) + + +def build_program(*, bound=(MASK_AND3,), init=INIT_AND_GUARD, body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, BODY_LOAD, WAIT_VM), + after_restore=()): + loop = (HEAD, COMPARE, *body, CLOSE) + offset = -(sum(len(bytes.fromhex(code)) for _, code in loop) // 4 + 1) + branch = ('s_cbranch_scc1 %d' % offset, struct.pack('<I', 0xbf850000 | (offset & 0xffff)).hex()) + return (*BOUNDED_PREFIX, *bound, *init, *loop, branch, RESTORE, *after_restore, FINAL_STORE, END) + + +def assemble_rows(rows): + return b''.join(bytes.fromhex(code) for _, code in rows) + + +def translate(rows, *, root=None): + pipe = G.ComputePipeline(assemble_rows(rows), root or H.root_blob(), H.RSRC2, GROUP) + return pipe.hlsl_cs(), pipe.manifest() + + +def trace_srv_handle(ir_text, *, expected_binding): + """Follow buffer RawBufferLoad handle back to createHandle / createHandleFromBinding in DXIL IR.""" + definitions, metadata, named = dxil.parse_module(ir_text) + roots = named.get('!dx.resources', []) + assert len(roots) == 1, 'module missing !dx.resources' + srvs = metadata[roots[0]][0] + srv_table = {} + for entry in ([] if srvs == 'null' else metadata[srvs]): + fields = metadata[entry] + rid = dxil.integers(fields[0])[0] + srv_table[rid] = {'space': dxil.integers(fields[3])[0], 'lower': dxil.integers(fields[4])[0], + 'size': dxil.integers(fields[5])[0]} + + loads = [ops for op, ops in definitions.values() if op in ('rawBufferLoad', 'bufferLoad')] + found = [] + for ops in loads: + handle = dxil.last_value(ops[1]) + while definitions.get(handle, (None,))[0] == 'annotateHandle': + handle = dxil.last_value(definitions[handle][1][1]) + op, operands = definitions.get(handle, (None, None)) + if op == 'createHandle': + rclass = dxil.integers(operands[1])[0] + binding = srv_table.get(dxil.integers(operands[2])[0]) if rclass == 0 else None + idx, flag = operands[3], operands[4] + elif op == 'createHandleFromBinding': + lower, upper, space, rclass = dxil.integers(operands[1]) + binding = {'space': space, 'lower': lower, 'size': upper - lower + 1} if rclass == 0 else None + idx, flag = operands[2], operands[3] + else: + continue + if binding == expected_binding: + found.append({ + 'creation': op, + 'binding': binding, + 'index_var': dxil.last_value(idx), + 'non_uniform': dxil.last_value(flag) == 'true', + 'raw': idx, + }) + assert len(found) == 1, f'expected one load on {expected_binding}, found {found}\n{ir_text}' + return found[0] + + +def verify_dxil(dxc, hlsl_source, *, expected_binding, check_stripped=True): + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'shader.hlsl' + cso = Path(tmp) / 'shader.cso' + src.write_text(hlsl_source, encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', cso, src], check=True) + ir = subprocess.run([dxc, '-dumpbin', cso], check=True, capture_output=True, text=True).stdout + traced = trace_srv_handle(ir, expected_binding=expected_binding) + assert traced['non_uniform'], f'DXIL lost nonUniformIndex on {expected_binding}: {traced}' + if check_stripped: + assert 'NonUniformResourceIndex(' in hlsl_source + stripped = Path(tmp) / 'stripped.hlsl' + cso_no = Path(tmp) / 'stripped.cso' + stripped.write_text(hlsl_source.replace('NonUniformResourceIndex(', '('), encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', cso_no, stripped], check=True) + ir_no = subprocess.run([dxc, '-dumpbin', cso_no], check=True, capture_output=True, text=True).stdout + traced_no = trace_srv_handle(ir_no, expected_binding=expected_binding) + assert not traced_no['non_uniform'], f'failed to detect omitted NonUniformResourceIndex: {traced_no}' + + +def check_translator(llvm_mc=None): + # Positive forms. + hlsl_a, man_a = translate(build_program()) + assert 'ByteAddressBuffer rh[4] : register(t0, space2);' in hlsl_a + assert 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_a + assert man_a.endswith('uav 0 table 1 16\nresheap 4 2\n'), man_a + + # 64-bit pointer add + src_scc carry form (post-loop shift and pre-loop v_lshlrev_b32). + hlsl_b, man_b = translate(build_program(body=(SHIFT5, *CARRY_ADD_S23, WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_b and 'resheap 4 2\n' in man_b + hlsl_pre, man_pre = translate(build_program(bound=(MASK_AND3, row_pair('v_lshlrev_b32_e32 v5, 5, v5')), + body=(*CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = (s22 >> 5);' in hlsl_pre and 'rh[NonUniformResourceIndex(h0)].Load(a + 0)' in hlsl_pre + assert 'resheap 4 2\n' in man_pre + + # s_addc_u32 high-word carry, v_min_u32, v_bfe_u32, in-place s_lshl_b32, and clobber of s22 after load. + translate(build_program(body=(SHIFT5, ('s_add_u32 s24, s8, s23', '08171880'), row_pair('s_addc_u32 s25, s9, 0'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + translate(build_program(bound=(row_pair('v_min_u32_e32 v5, 3, v5'),))) + hlsl_bfe, man_bfe = translate(build_program(bound=(row_pair('v_bfe_u32 v5, v5, 0, 2'),))) + assert 'resheap 4 2\n' in man_bfe and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_bfe + hlsl_inp, _ = translate(build_program(body=(row_pair('s_lshl_b32 s22, s22, 5'), + row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = (s22 >> 5);' in hlsl_inp + hlsl_reused, _ = translate(build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, row_pair('s_mov_b32 s22, 0'), + BODY_LOAD, WAIT_VM))) + assert 'h0 = s22;' in hlsl_reused and 'rh[NonUniformResourceIndex(h0)].Load' in hlsl_reused + hlsl_ocpy, _ = translate(build_program(body=(SHIFT5, row_pair('s_mov_b32 s24, s23'), + row_pair('s_load_dwordx4 s[28:31], s[8:9], s24'), + WAIT_LGKM, BODY_LOAD, WAIT_VM))) + assert 'h0 = s22;' in hlsl_ocpy + + # Negative controls: every missing proof or forbidden extension stays refused. + controls = ( + ('unbounded key', build_program(bound=()), 'per-lane descriptor selection requires a proven bound heap range'), + ('oversized mask', build_program(bound=(row_pair('v_and_b32_e32 v5, 0x7ff, v5'),)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('only one diamond arm bounds key', + build_program(bound=(row_pair('s_cmp_eq_u32 s4, 0'), row_pair('s_cbranch_scc0 2'), MASK_AND3, + row_pair('s_branch 1'), row_pair('s_nop 0'))), + 'per-lane descriptor selection requires a proven bound heap range'), + ('bounded after EXEC narrowed without prior bound', + build_program(bound=(), init=(('v_mov_b32_e32 v7, 13', '8d020e7e'), ('s_mov_b32 s26, exec_lo', '7e039abe'), + ('v_cmpx_gt_u32_e32 s4, v0', '0400a87d'), MASK_AND3, + ('s_mov_b32 s21, exec_lo', '7e0395be'))), + 'per-lane descriptor selection requires a proven bound heap range'), + ('missing shift', build_program(body=(row_pair('s_load_dwordx4 s[28:31], s[8:9], s22'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('wrong shift', build_program(body=(row_pair('s_lshl_b32 s23, s22, 4'), HEAP_LOAD, + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('wrong pre-loop shift', + build_program(bound=(MASK_AND3, row_pair('v_lshlrev_b32_e32 v5, 4, v5')), + body=(*CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('non-resheap base', build_program(body=(row_pair('s_load_dwordx4 s[28:31], s[22:23], 0x0'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('modified descriptor word', build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('s_or_b32 s31, s31, 0'), BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('non-zero resheap high word', + build_program(bound=(row_pair('s_mov_b32 s9, 1'), MASK_AND3)), + 'whose high word is not a constant zero'), + ('missing carry on s_add_u32 pointer add', + build_program(body=(SHIFT5, ('s_add_u32 s24, s8, s23', '08171880'), + ('s_load_dwordx4 s[28:31], s[24:25], 0x0', '0c0708f4000000fa'), + WAIT_LGKM, BODY_LOAD, WAIT_VM)), + 'per-lane descriptor selection requires a proven bound heap range'), + ('live key at loop exit', + build_program(after_restore=(row_pair('v_mov_b32_e32 v7, s22'),)), 'body scalar is live at the loop exit'), + ('live descriptor word at loop exit', + build_program(after_restore=(row_pair('v_mov_b32_e32 v7, s28'),)), 'body scalar is live at the loop exit'), + ('idxen load through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_load_dword v7, v4, s[28:31], 0 idxen'), WAIT_VM)), + 'has unproved modifiers'), + ('formatted load through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_load_format_x v7, v4, s[28:31], 0 offen'), WAIT_VM)), + 'is not proven lane-local'), + ('store through per-lane descriptor', + build_program(body=(SHIFT5, HEAP_LOAD, WAIT_LGKM, + row_pair('buffer_store_dword v7, v4, s[28:31], 0 offen'), WAIT_VM)), + 'is not proven lane-local'), + ) + for label, rows, expected in controls: + try: + refused(expected, lambda: translate(rows)) + except AssertionError as err: + raise AssertionError(f'{label}: {err}') from None + refused('per-lane descriptor selection requires a proven bound heap range', + lambda: translate(build_program(), root=H.root_blob(flags=0))) + + # Check binary reassembly against llvm-mc if provided. + checked_asm = 0 + if llvm_mc: + seen = set() + for asm, hexcode in (*BOUNDED_PREFIX, MASK_AND3, *INIT_AND_GUARD, HEAD, COMPARE, SHIFT5, HEAP_LOAD, + *CARRY_ADD_S23, *CARRY_ADD_S22, WAIT_LGKM, BODY_LOAD, WAIT_VM, CLOSE, RESTORE, + FINAL_STORE, END, *ENCODINGS.items()): + if asm not in seen and 's_cbranch' not in asm and 's_branch' not in asm: + seen.add(asm) + got = assemble(llvm_mc, asm + '\n') + assert got == bytes.fromhex(hexcode), f'{asm}: {got.hex()} != {hexcode}' + checked_asm += 1 + print(f'startup_compute_waterfall_heap: PASS (translator + {len(controls) + 1} refused controls' + + (f' + {checked_asm} llvm-mc encodings' if checked_asm else '') + ')') + + +def check_oracle(dxc, offscreen_check, adapter): + expected_binding = {'space': 0, 'lower': 1, 'size': 4} + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + hlsl = d / 'bounded.hlsl' + hlsl.write_text(BOUNDED_ORACLE_HLSL, encoding='ascii') + results = {} + variants = ( + ('reference', [], True, ((25, 0),)), + ('static-switch', ['-D', 'STATIC_SWITCH'], None, ((25, 0),)), + ('first-active', ['-D', 'FIRST_ACTIVE'], None, ((13, 12),)), + # On WARP, dropping NonUniformResourceIndex still matches 25/25; on GPUs that scalarize dynamic + # descriptor loads (such as RX 7900 XTX), it reads lane 0 and mismatches 12/25, like first-active. + ('no-marker', ['-D', 'NO_MARKER'], False, ((25, 0), (13, 12))), + ) + for name, defs, want_nu, valid_counts in variants: + cso = d / f'{name}.cso' + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', *defs, '-Fo', cso, hlsl], check=True) + if want_nu is not None: + ir = subprocess.run([dxc, '-dumpbin', cso], check=True, capture_output=True, text=True).stdout + traced = trace_srv_handle(ir, expected_binding=expected_binding) + assert traced['non_uniform'] is want_nu, (name, traced) + res = subprocess.run([offscreen_check, adapter, '--compute-waterfall-oracle', cso], + capture_output=True, text=True) + if res.returncode == 77: + print(res.stdout + res.stderr) + return 77 + assert res.returncode == 0, f'{name} failed:\n{res.stdout}{res.stderr}' + m = re.search(r'dispatches=25 matches=(\d+) mismatches=(\d+)', res.stdout) + assert m, res.stdout + res.stderr + got_m, got_mis = int(m[1]), int(m[2]) + assert (got_m, got_mis) in valid_counts, f'{name}: got {(got_m, got_mis)}' + results[name] = (got_m, got_mis) + print(f"startup_compute_waterfall_heap_oracle ({adapter}): PASS {results}") + return 0 + + +def check_dispatch(consumer, dxc, adapter): + shapes = ( + ('direct', assemble_rows(build_program())), + ('carry64', assemble_rows(build_program(body=(SHIFT5, *CARRY_ADD_S23, WAIT_LGKM, BODY_LOAD, WAIT_VM)))), + ) + for label, program_bytes in shapes: + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + cache, env = prepare(directory) + env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + (directory / 'compute_root').write_bytes(H.root_blob(table_range=True)) + env['X2W_TEST_COMPUTE_ROOT'] = str(directory / 'compute_root') + (directory / 'program').write_bytes(program_bytes) + (directory / 'data').write_bytes(NO_DATA) + (directory / 'state').write_bytes(state_a(GROUP, H.RSRC2)) + untouched = [C.SENTINEL] * C.WORDS + + # 1. Before translation: refused with "no translation", output untouched. + got, result = dispatch(directory, consumer, env, 'dispatch-heap-waterfall') + if result.returncode == 77: + print(result.stdout + result.stderr) + return 77 + assert got == untouched, f'{label}: untranslated dispatch wrote output' + assert len(lines(result, 'Dispatch(1, 1, 1) refused: no translation')) == 1, result.stderr[-3000:] + published = lines(result, 'x2w-draw compute request') + assert published and ' published ' in published[0], result.stderr[-3000:] + key = int(published[0].split()[3], 16) + + # 2. Offline translate and validate DXIL nonUniformIndex metadata. + out = subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)).stdout + assert f'{key:016x}: ok' in out, out + assert 'resheap 4 2\n' in (cache / f'{key:016x}.txt').read_text(encoding='ascii') + verify_dxil(dxc, (cache / f'{key:016x}.cs.hlsl').read_text(encoding='ascii'), + expected_binding={'space': 2, 'lower': 0, 'size': 4}) + + # 3. Positive readback across the oracle key sets and active lane counts (0, 2, 4). + cases = [(keys, 4) for keys in ORACLE_ROWS] + [((0, 1, 2, 3), 2), ((0, 1, 2, 3), 0)] + for idx, (keys, active) in enumerate(cases): + in_path = directory / f'in-{idx}.bin' + in_words = list(keys) + [0] * (C.WORDS - 4) + in_path.write_bytes(struct.pack(f'<{C.WORDS}I', *in_words)) + case_env = dict(env, X2W_TEST_DISPATCH_IN=str(in_path), X2W_TEST_DISPATCH_ACTIVE=str(active)) + got, result = dispatch(directory, consumer, case_env, 'dispatch-heap-waterfall') + assert len(lines(result, 'Dispatch(1, 1, 1) translated')) == 1 and not lines(result, 'refused'), \ + result.stderr[-3000:] + errors = [ln for ln in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in ln or ' sev=1 ' in ln] + assert not errors, errors[0] + expected = [1000 * ((keys[lane] & 3) + 1) + 17 * lane if lane < active else 13 for lane in range(4)] + untouched[4:] + wrong = [i for i in range(C.WORDS) if got[i] != expected[i]] + assert not wrong, f'{label} case {idx} keys={keys} active={active} word={wrong[0]} got={got[wrong[0]]:08x} expected={expected[wrong[0]]:08x}' + + # 4. Short-range negative control: 3-descriptor heap omits record 3 and must refuse before Dispatch. + in_path = directory / 'in-short.bin' + in_path.write_bytes(struct.pack(f'<{C.WORDS}I', 0, 1, 2, 3, *([0] * (C.WORDS - 4)))) + short_env = dict(env, X2W_TEST_DISPATCH_IN=str(in_path), X2W_TEST_DISPATCH_ACTIVE='4') + got, result = dispatch(directory, consumer, short_env, 'dispatch-heap-waterfall-short') + assert got == untouched, f'{label}: short-range control modified output' + ref = lines(result, 'refused: ') + census = lines(result, 'x2w-render compute census') + want_reason = "a heap record is outside the list's view heap" + assert len(ref) == 1 and want_reason in ref[0], result.stderr[-3000:] + assert len(census) == 3 and census[1].endswith(f'reason "{want_reason}": 1 keys, 1 dispatches'), census + errors = [ln for ln in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in ln or ' sev=1 ' in ln] + assert not errors, errors[0] + print(f'startup_compute_waterfall_heap_dispatch ({adapter}): PASS (direct + carry64 translated, ' + f'DXIL nonUniformIndex verified, all {len(cases)} key/active readbacks matched, short-range control refused)') + return 0 + + +def main(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument('--llvm-mc') + parser.add_argument('--dxil') + parser.add_argument('--oracle', nargs=3) + parser.add_argument('--dispatch', nargs=3) + args, unknown = parser.parse_known_args() + if unknown: + sys.exit(__doc__) + if args.dxil: + hlsl, _ = translate(build_program()) + verify_dxil(args.dxil, hlsl, expected_binding={'space': 2, 'lower': 0, 'size': 4}) + print('startup_compute_waterfall_heap_dxil: PASS (nonUniformIndex true with intrinsic, false without)') + return 0 + if args.oracle: + return check_oracle(*args.oracle) + if args.dispatch: + return check_dispatch(*args.dispatch) + check_translator(args.llvm_mc) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_console_mode_check.cpp b/tests/startup_console_mode_check.cpp new file mode 100644 index 0000000000..79a8bde242 --- /dev/null +++ b/tests/startup_console_mode_check.cpp @@ -0,0 +1,409 @@ +// Source-built control for console_mode.h and registry_console_mode.inl: the console mode a title +// reads from HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM (value ConsoleMode). +// +// The real registry functions are replaced by local fakes that report the value as missing (a PC), +// so no machine state is read or changed. The hooks are reached the way a title reaches them +// through GetProcAddress. Cases: unset passes the read to the fake; 6 and 7 answer 0x60 and 0x64 +// without calling it; 1 answers missing; other keys, values and closed handles pass through. +// --control leaves X2W_DEVICE_TYPE unset for the answered cases, which must print FAIL. +// +// The fake registry lives in this EXE, which X2W_CONSOLE_MODE_FIXTURE counts as a registry +// provider. --decoy <dll> loads a source-built DLL that exports RegOpenKeyExW and RegQueryValueExW +// with a distinct result. With the switch unset and set, neither GetProcAddress on the decoy nor a +// synthetic IAT entry naming it (or naming advapi32.dll but bound to the decoy) may be hooked or +// remembered, and the hooks must still reach the fake registry. --control provider matches +// registry imports by name alone, which must print FAIL. +#define X2W_CONSOLE_MODE_FIXTURE 1 +#include <windows.h> + +#include <atomic> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <string> +#include <utility> +#include <vector> + +#include "startup_stubs/console_mode.h" +#include "startup_stubs/local_log.h" +#include "startup_stubs/runtime_gpa_patch.h" + +namespace x2w_local { +std::string fixture_log; +void fixture_logf(const char* format, ...) +{ + char line[512]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + fixture_log += line; + fixture_log += '\n'; +} +} // namespace x2w_local + +#define logf fixture_logf +namespace { +#include "../src/startup_stubs/registry_console_mode.inl" +} +#undef logf + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +HKEY const fake_oem = reinterpret_cast<HKEY>(0x5100); +HKEY const fake_other = reinterpret_cast<HKEY>(0x5200); +int real_queries, real_gets, real_closes; + +LSTATUS WINAPI fake_open_ex(HKEY root, LPCWSTR subkey, DWORD, REGSAM, PHKEY out) +{ + if (root != HKEY_LOCAL_MACHINE || !out) return ERROR_FILE_NOT_FOUND; + *out = x2w_console_mode::is_oem_subkey(subkey) ? fake_oem : fake_other; + return ERROR_SUCCESS; +} +LSTATUS WINAPI fake_open(HKEY root, LPCWSTR subkey, PHKEY out) { return fake_open_ex(root, subkey, 0, 0, out); } +LSTATUS WINAPI fake_query(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + ++real_queries; + return ERROR_FILE_NOT_FOUND; // as on a PC: the value is absent +} +LSTATUS WINAPI fake_get(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD) +{ + ++real_gets; + return ERROR_FILE_NOT_FOUND; +} +LSTATUS WINAPI fake_close(HKEY) +{ + ++real_closes; + return ERROR_SUCCESS; +} + +// The fakes live in this EXE, the fixture's registry provider. +template <class Fn> +Fn hook(const char* name, Fn fake) +{ + return reinterpret_cast<Fn>(registry_hook_for(GetModuleHandleW(nullptr), name, reinterpret_cast<FARPROC>(fake))); +} + +void device(const char* value, bool answered_case) +{ + // In the control the answered cases run without the switch, so their checks must fail. + if (!value || (control && answered_case)) + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + else + SetEnvironmentVariableA("X2W_DEVICE_TYPE", value); +} + +void pure_checks() +{ + using namespace x2w_console_mode; + check("OEM subkey", is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM")); + check("OEM subkey in capitals", is_oem_subkey(L"SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\OEM")); + check("OEM subkey with a leading and a trailing backslash", + is_oem_subkey(L"\\Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\")); + check("a longer subkey is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEMx")); + check("a child of the OEM key is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\a")); + check("a parent is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion")); + check("null subkey", !is_oem_subkey(nullptr)); + check("value name ignores case", is_console_mode_value(L"consolemode")); + check("other value name", !is_console_mode_value(L"ConsoleModeX")); + + std::uint32_t mode = 0; + check("unset passes", answer_for(false, 7, &mode) == Answer::pass); + check("6 is Series S", answer_for(true, 6, &mode) == Answer::value && mode == series_s); + check("7 is Series X", answer_for(true, 7, &mode) == Answer::value && mode == series_x); + check("1 is missing", answer_for(true, 1, &mode) == Answer::missing); + check("8 is passed on", answer_for(true, 8, &mode) == Answer::pass); + + unsigned long type = 0, bytes = 0; + unsigned char data[8] = {}; + check("size query", fill_query(series_x, &type, nullptr, &bytes) == status_ok && bytes == 4 && type == type_dword); + bytes = 3; + check("short buffer", fill_query(series_x, &type, data, &bytes) == status_more_data && bytes == 4 && data[0] == 0); + check("data without size", fill_query(series_x, &type, data, nullptr) == status_invalid); + bytes = sizeof(data); + check("value written", fill_query(series_x, &type, data, &bytes) == status_ok && bytes == 4 && data[0] == 0x64 && data[1] == 0); + bytes = sizeof(data); + check("RegGetValue refuses a string-only request", fill_get(0x2 /* RRF_RT_REG_SZ */, series_s, &type, data, &bytes) == status_wrong_type); + bytes = sizeof(data); + check("RegGetValue with RRF_RT_DWORD", fill_get(0x18, series_s, &type, data, &bytes) == status_ok && data[0] == 0x60); +} + +DWORD query(RegQueryValueExWFn query_fn, HKEY key, const wchar_t* name, LSTATUS* status) +{ + DWORD type = 0, value = 0xffffffff, bytes = sizeof(value); + *status = query_fn(key, name, nullptr, &type, reinterpret_cast<LPBYTE>(&value), &bytes); + return value; +} + +void hook_checks() +{ + const auto open_ex = hook("RegOpenKeyExW", &fake_open_ex); + const auto open = hook("RegOpenKeyW", &fake_open); + const auto query_fn = hook("RegQueryValueExW", &fake_query); + const auto get = hook("RegGetValueW", &fake_get); + const auto close = hook("RegCloseKey", &fake_close); + check("every registry name has a hook", open_ex && open && query_fn && get && close); + if (!(open_ex && open && query_fn && get && close)) return; + const HMODULE exe = GetModuleHandleW(nullptr); + check("other names have no hook", !registry_hook_for(exe, "RegSetValueExW", reinterpret_cast<FARPROC>(&fake_close))); + check("a hook is never kept as the real function", !registry_hook_for(exe, "RegCloseKey", reinterpret_cast<FARPROC>(close))); + + const wchar_t* oem_path = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; + HKEY key = nullptr, other = nullptr; + check("OEM key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &key) == ERROR_SUCCESS && key == fake_oem); + check("other key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, L"Software\\Other", 0, KEY_READ, &other) == ERROR_SUCCESS); + + LSTATUS status = 0; + device(nullptr, false); + int before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("unset: the read reaches the registry", real_queries == before + 1 && status == ERROR_FILE_NOT_FOUND); + + device("6", true); + before = real_queries; + DWORD value = query(query_fn, key, L"ConsoleMode", &status); + check("6: Series S answered locally", status == ERROR_SUCCESS && value == 0x60 && real_queries == before); + + device("7", true); + value = query(query_fn, key, L"ConsoleMode", &status); + check("7: Series X answered locally", status == ERROR_SUCCESS && value == 0x64 && real_queries == before); + + DWORD type = 0, bytes = 0; + status = query_fn(key, L"ConsoleMode", nullptr, &type, nullptr, &bytes); + check("7: size query", status == ERROR_SUCCESS && bytes == 4 && type == REG_DWORD); + + DWORD got = 0, got_bytes = sizeof(got); + before = real_gets; + status = get(HKEY_LOCAL_MACHINE, oem_path, L"ConsoleMode", RRF_RT_REG_DWORD, &type, &got, &got_bytes); + check("7: RegGetValueW by path answered locally", status == ERROR_SUCCESS && got == 0x64 && real_gets == before); + + device("1", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("1: missing, as on a PC", status == ERROR_FILE_NOT_FOUND && real_queries == before); + + device("7", false); + before = real_queries; + query(query_fn, key, L"OtherValue", &status); + check("7: another value passes through", real_queries == before + 1); + query(query_fn, other, L"ConsoleMode", &status); + check("7: ConsoleMode under another key passes through", real_queries == before + 2); + device("not-a-number", false); + query(query_fn, key, L"ConsoleMode", &status); + check("a value that is not a number passes through", real_queries == before + 3); + + HKEY second = nullptr; + device("7", true); + check("RegOpenKeyW opens the OEM key", open(HKEY_LOCAL_MACHINE, oem_path, &second) == ERROR_SUCCESS && second == fake_oem); + check("RegCloseKey reaches the registry", close(key) == ERROR_SUCCESS && real_closes == 1); + device("7", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("a closed OEM handle passes through", real_queries == before + 1); + + // A full table of OEM handles: one more open is logged once and not tracked. + const char* full_line = "OEM key handles already open, another is not tracked"; + check("no full-table line before the table fills", x2w_local::fixture_log.find(full_line) == std::string::npos); + HKEY extra = nullptr; + for (int i = 0; i < 17; ++i) open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &extra); + const std::size_t full_at = x2w_local::fixture_log.find(full_line); + check("a full OEM handle table is logged", full_at != std::string::npos); + check("the full-table line is logged once", full_at != std::string::npos && + x2w_local::fixture_log.find(full_line, full_at + 1) == std::string::npos); + close(second); + check("closing the OEM handle empties the table", !oem_key(fake_oem)); + + device(nullptr, false); + const std::string& log = x2w_local::fixture_log; + check("open is logged", log.find("RegOpenKeyExW opened the OEM key, real status 0") != std::string::npos); + check("pass-through is logged", log.find("RegQueryValueExW ConsoleMode passed through -> status 2") != std::string::npos); + check("answer is logged", log.find("ConsoleMode -> 0x64 for X2W_DEVICE_TYPE=7") != std::string::npos); +} + +// ---- a package DLL with the same export names ----------------------------------------------------- +constexpr LSTATUS decoy_status = 0x5EC0; // startup_console_mode_decoy.cpp + +struct Import { + const char* name; + void* bound; +}; +struct ImportDll { + const char* dll; + std::vector<Import> imports; +}; + +// Synthetic PE32+ image with one regular import descriptor per entry, each slot already bound. +std::vector<unsigned char> build_image(const std::vector<ImportDll>& dlls, std::vector<std::vector<std::uint32_t>>* slots) +{ + namespace patch = x2w_runtime_patch; + std::vector<unsigned char> image(0x1000, 0); + auto* dos = reinterpret_cast<patch::DosStub*>(image.data()); + dos->e_magic = 0x5A4D; + dos->e_lfanew = 0x80; + auto* nt = image.data() + 0x80; + *reinterpret_cast<std::uint32_t*>(nt) = 0x00004550; + *reinterpret_cast<std::uint16_t*>(nt + 24) = 0x20B; + auto* dirs = reinterpret_cast<patch::DataDir*>(nt + 24 + 112); + dirs[1].virtual_address = 0x200; + dirs[1].size = static_cast<std::uint32_t>(sizeof(patch::ImportDesc) * (dlls.size() + 1)); + std::uint32_t next = 0x400; + const auto take = [&](std::size_t bytes) { + const std::uint32_t at = next; + next = static_cast<std::uint32_t>((next + bytes + 7) & ~std::size_t{7}); + return at; + }; + slots->clear(); + for (std::size_t d = 0; d < dlls.size(); ++d) { + auto* imp = reinterpret_cast<patch::ImportDesc*>(image.data() + 0x200) + d; + const std::size_t count = dlls[d].imports.size(); + imp->original_first_thunk = take(8 * (count + 1)); + imp->first_thunk = take(8 * (count + 1)); + imp->name = take(std::strlen(dlls[d].dll) + 1); + std::memcpy(image.data() + imp->name, dlls[d].dll, std::strlen(dlls[d].dll) + 1); + slots->emplace_back(); + for (std::size_t i = 0; i < count; ++i) { + const char* name = dlls[d].imports[i].name; + const std::uint32_t hint = take(2 + std::strlen(name) + 1); + std::memcpy(image.data() + hint + 2, name, std::strlen(name) + 1); + reinterpret_cast<patch::Thunk64*>(image.data() + imp->original_first_thunk)[i].value = hint; + reinterpret_cast<patch::Thunk64*>(image.data() + imp->first_thunk)[i].value = + reinterpret_cast<std::uint64_t>(dlls[d].imports[i].bound); + slots->back().push_back(imp->first_thunk + static_cast<std::uint32_t>(8 * i)); + } + } + return image; +} + +// What hooked_get_proc_address returns: the hook for a registry provider, else the real export. +FARPROC resolve(HMODULE module, const char* name) +{ + const FARPROC real = GetProcAddress(module, name); + const FARPROC hooked = real ? registry_hook_for(module, name, real) : nullptr; + return hooked ? hooked : real; +} + +void* remembered(RegistryImport which) { return real_registry[which].load(); } + +void decoy_checks(HMODULE decoy, const char* pass) +{ + using SeenFn = LONG(WINAPI*)(); + const auto seen = reinterpret_cast<SeenFn>(GetProcAddress(decoy, "decoy_calls")); + void* const decoy_open = reinterpret_cast<void*>(GetProcAddress(decoy, "RegOpenKeyExW")); + void* const decoy_query = reinterpret_cast<void*>(GetProcAddress(decoy, "RegQueryValueExW")); + const std::string label = std::string(pass) + ": "; + const auto say = [&](const char* what, bool ok) { check((label + what).c_str(), ok); }; + say("the decoy exports both registry names", seen && decoy_open && decoy_query); + if (!(seen && decoy_open && decoy_query)) return; + + // GetProcAddress on the decoy: its own exports, which keep their own result. + const auto open_fn = reinterpret_cast<RegOpenKeyExWFn>(resolve(decoy, "RegOpenKeyExW")); + const auto query_fn = reinterpret_cast<RegQueryValueExWFn>(resolve(decoy, "RegQueryValueExW")); + say("GetProcAddress(decoy, RegOpenKeyExW) is the decoy's export", reinterpret_cast<void*>(open_fn) == decoy_open); + say("GetProcAddress(decoy, RegQueryValueExW) is the decoy's export", reinterpret_cast<void*>(query_fn) == decoy_query); + LONG before = seen(); + HKEY out = nullptr; + LSTATUS status = 0; + query(query_fn, fake_other, L"ConsoleMode", &status); + say("the decoy's RegQueryValueExW answers its own result", status == decoy_status && seen() == before + 1); + say("the decoy's RegOpenKeyExW answers its own result", + open_fn(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", 0, KEY_READ, &out) == decoy_status && + seen() == before + 2); + say("a decoy address is refused under the provider module", + !registry_hook_for(GetModuleHandleW(nullptr), "RegQueryValueExW", reinterpret_cast<FARPROC>(decoy_query))); + + // A synthetic IAT: the decoy by name, advapi32.dll by name but bound to the decoy, and + // advapi32.dll bound to the fake registry (the one entry that is rewritten). + std::vector<std::vector<std::uint32_t>> slots; + auto image = build_image({{"startup_console_mode_decoy.dll", {{"RegOpenKeyExW", decoy_open}, {"RegQueryValueExW", decoy_query}}}, + {"ADVAPI32.dll", {{"RegQueryValueExW", decoy_query}}}, + {"advapi32.dll", {{"RegQueryValueExW", reinterpret_cast<void*>(&fake_query)}, + {"RegCloseKey", reinterpret_cast<void*>(&fake_close)}}}}, + &slots); + const auto slot = [&](std::size_t d, std::size_t i) { return *reinterpret_cast<void**>(image.data() + slots[d][i]); }; + const int patched = patch_registry_imports(image.data(), image.size()); + say("only the provider-bound imports are rewritten", patched == 2); + say("the decoy's RegOpenKeyExW slot is untouched", slot(0, 0) == decoy_open); + say("the decoy's RegQueryValueExW slot is untouched", slot(0, 1) == decoy_query); + say("advapi32.dll bound to the decoy is untouched", slot(1, 0) == decoy_query); + say("advapi32.dll bound to the registry is rewritten", + slot(2, 0) == registry_hooks[reg_query_value_ex_w] && slot(2, 1) == registry_hooks[reg_close_key]); + before = seen(); + query(reinterpret_cast<RegQueryValueExWFn>(slot(0, 1)), fake_other, L"ConsoleMode", &status); + say("a call through the decoy's slot reaches the decoy", status == decoy_status && seen() == before + 1); + + // Neither route made the decoy the real registry: the hooks still reach the fake registry. + say("the decoy's RegOpenKeyExW is never remembered", remembered(reg_open_key_ex_w) != decoy_open); + say("the decoy's RegQueryValueExW is never remembered", + remembered(reg_query_value_ex_w) != decoy_query && remembered(reg_query_value_ex_w) == reinterpret_cast<void*>(&fake_query)); + before = seen(); + const int real_before = real_queries; + query(reinterpret_cast<RegQueryValueExWFn>(registry_hooks[reg_query_value_ex_w]), fake_other, L"ConsoleMode", &status); + say("the hook still reaches the registry, not the decoy", + status == ERROR_FILE_NOT_FOUND && real_queries == real_before + 1 && seen() == before); +} + +void provider_checks(HMODULE decoy) +{ + const HMODULE advapi = LoadLibraryW(L"advapi32.dll"); // this EXE does not import it + check("advapi32.dll is a registry provider", registry_provider_module(advapi)); + check("kernelbase.dll is a registry provider", registry_provider_module(GetModuleHandleW(L"kernelbase.dll"))); + check("advapi32.dll's RegQueryValueExW lies in a provider", + advapi && registry_provider_address(reinterpret_cast<void*>(GetProcAddress(advapi, "RegQueryValueExW")))); + check("the decoy is not a registry provider", decoy && !registry_provider_module(decoy)); + check("import names: advapi32.dll in any case", registry_provider_dll("ADVAPI32.dll")); + check("import names: the registry API set", registry_provider_dll("api-ms-win-core-registry-l1-1-0.dll")); + check("import names: kernelbase.dll", registry_provider_dll("KernelBase.dll")); + check("import names: the decoy is refused", !registry_provider_dll("startup_console_mode_decoy.dll")); + check("import names: a longer name is refused", !registry_provider_dll("advapi32.dll.x")); + check("import names: another API set is refused", !registry_provider_dll("api-ms-win-core-file-l1-1-0.dll")); +} +} // namespace + +int main(int argc, char** argv) +{ + const char* decoy_path = nullptr; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--control") == 0) { + if (i + 1 < argc && std::strcmp(argv[i + 1], "provider") == 0) { + registry_any_provider = true; // name-only matching; the decoy checks must fail + ++i; + } else { + control = true; + } + } else if (std::strcmp(argv[i], "--decoy") == 0 && i + 1 < argc) { + decoy_path = argv[++i]; + } + } + pure_checks(); + std::string decoy_file = decoy_path ? decoy_path : ""; + for (char& c : decoy_file) + if (c == '/') c = '\\'; + const HMODULE decoy = decoy_path ? LoadLibraryA(decoy_file.c_str()) : nullptr; + check("load the decoy DLL (--decoy)", decoy != nullptr); + if (!registry_any_provider) provider_checks(decoy); + // Before hook_checks registers the fake registry, so a name-only match would keep the decoy first. + if (decoy) { + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + decoy_checks(decoy, "decoy, switch unset"); + SetEnvironmentVariableA("X2W_DEVICE_TYPE", "7"); + decoy_checks(decoy, "decoy, X2W_DEVICE_TYPE=7"); + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + } + hook_checks(); + if (failures) { + std::printf("startup_console_mode: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_console_mode: ok"); + return 0; +} diff --git a/tests/startup_console_mode_decoy.cpp b/tests/startup_console_mode_decoy.cpp new file mode 100644 index 0000000000..d0fa5f6770 --- /dev/null +++ b/tests/startup_console_mode_decoy.cpp @@ -0,0 +1,28 @@ +// Source-built package-style DLL for startup_console_mode: exports RegOpenKeyExW and +// RegQueryValueExW under the registry names (startup_console_mode_decoy.def) with a result no +// registry returns. The console-mode hooks must leave it alone: neither route may hook it or keep +// its address as the real registry function. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include <windows.h> + +namespace { +LONG calls; +constexpr LONG decoy_status = 0x5EC0; +} + +extern "C" LONG WINAPI decoy_calls() { return InterlockedCompareExchange(&calls, 0, 0); } + +extern "C" LONG WINAPI decoy_open_key_ex_w(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY out) +{ + InterlockedIncrement(&calls); + if (out) *out = reinterpret_cast<HKEY>(static_cast<ULONG_PTR>(0xDEC0)); + return decoy_status; +} + +extern "C" LONG WINAPI decoy_query_value_ex_w(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + InterlockedIncrement(&calls); + return decoy_status; +} diff --git a/tests/startup_console_mode_decoy.def b/tests/startup_console_mode_decoy.def new file mode 100644 index 0000000000..8e0e44b363 --- /dev/null +++ b/tests/startup_console_mode_decoy.def @@ -0,0 +1,5 @@ +LIBRARY startup_console_mode_decoy +EXPORTS + RegOpenKeyExW = decoy_open_key_ex_w + RegQueryValueExW = decoy_query_value_ex_w + decoy_calls diff --git a/tests/startup_copied_vertex_srv_check.py b/tests/startup_copied_vertex_srv_check.py new file mode 100644 index 0000000000..2db2d8ced5 --- /dev/null +++ b/tests/startup_copied_vertex_srv_check.py @@ -0,0 +1,78 @@ +"""Read both sides of a 256-byte boundary through a copied vertex-buffer SRV.""" +from pathlib import Path +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +VERTEX_SHADER = """ +%s +struct Vertex { + float4 position : SV_Position; + nointerpolation uint2 values : TEXCOORD0; +}; +Vertex main(uint id : SV_VertexID) { + const float2 corners[3] = {float2(-1, 1), float2(3, 1), float2(-1, -3)}; + Vertex output; + output.position = float4(corners[id], 0.5, 1); + output.values = uint2(%s); + return output; +} +""" + +VERTEX = VERTEX_SHADER % ( + "ByteAddressBuffer records : register(t0);", + "records.Load(224), records.Load(288)", +) +PAIR_VERTEX = VERTEX_SHADER % ( + "ByteAddressBuffer first : register(t0);\nByteAddressBuffer second : register(t1);", + "first.Load(288), second.Load(288)", +) + +PIXEL = """ +float4 main(float4 position : SV_Position, nointerpolation uint2 values : TEXCOORD0) : SV_Target { + return float4(float2(values) / 255.0, 0, 1); +} +""" + + +def check(directory, consumer, backend): + pixels = draw_texture(directory, consumer, backend, PIXEL, + {"X2W_TEST_COPIED_VERTEX_SRV": "1"}, + binding="srv 0 buf table 0 0", vertex_hlsl=VERTEX) + if pixels is None: + return 77 + full = bytes((57, 181, 0, 255)) + short = bytes((57, 0, 0, 255)) + expected = (full * 2 + short * 4 + full * 2) * 4 + if pixels != expected: + raise AssertionError(f"{backend}: copied vertex SRV got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched full, short, and restored copied descriptors") + return 0 + + +def check_pair(directory, consumer, backend): + for name, offset in (("distinct", 32), ("collapsed", 0)): + folder = directory / name + folder.mkdir() + pixels = draw_texture(folder, consumer, backend, PIXEL, + {"X2W_TEST_COPIED_VERTEX_SRV_PAIR": "1"}, + binding=f"srv 0 buf table 0 0\nsrv 1 buf table 0 {offset}", vertex_hlsl=PAIR_VERTEX) + if pixels is None: + return 77 + first = bytes((181, 181 if offset == 0 else 211, 0, 255)) + swapped = bytes((211, 211 if offset == 0 else 181, 0, 255)) + expected = (first * 2 + swapped * 4 + first * 2) * 4 + if pixels != expected: + raise AssertionError(f"{backend}: {name} vertex SRVs got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched {name} vertex table offsets after swap and restore") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + result = check(Path(temporary), *sys.argv[1:]) + if result: + sys.exit(result) + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check_pair(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_d16_srv_check.py b/tests/startup_d16_srv_check.py index 36e7802dcc..aece29d0fa 100644 --- a/tests/startup_d16_srv_check.py +++ b/tests/startup_d16_srv_check.py @@ -72,7 +72,7 @@ def check(directory, consumer, backend): subprocess.run(args, env=env, check=True) subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) - manifest, = cache.glob('*.txt') + manifest, = (path for path in cache.glob('*.txt') if path.name != 'revision.txt') manifest_text = manifest.read_text(encoding='ascii') manifest_lines = manifest_text.splitlines() assert 'udsrc 3 d16unorm16 0' in manifest_lines, manifest_text diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index f0e78798a1..299e407ff8 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -7,6 +7,10 @@ ends the run as the timeout does; one left from an earlier run is removed at start. The launcher keeps the debug heap off unless the caller sets _NO_DEBUG_HEAP=0. X2W_NOP_SOFT_ASSERTS=1 replaces a main-image INT3 with a NOP after the first continue, and the probe repeats one site when STARTUP_DEBUG_PROBE_ASSERTS is set. +--assert-sites N steps over every hit at up to N distinct main-image sites, however often each +repeats, and stops at the first hit of one more site. +With both budgets, each counts only the hits it covers (hits A, B, A with --assert-sites 1 +--continue-asserts 2 all continue). tests/startup_debug_probe.cpp is the main input: it hits two breakpoints, optionally repeats a third, reserves 256 MiB, prints its debug-heap flags, waits 3 s and exits 0. @@ -212,6 +216,40 @@ def stack_read(address, size): assert "process exited with 0x00000000" in out, out assert breakpoint_sites(logdir, image).count(repeated[0]) == repeats, text(logdir / "events.txt") + # --assert-sites 3: every hit at the three sites is stepped over, however often the third + # repeats, with no hit budget at all. + many = 20 + out, logdir = run(probe, work, "assert-sites", {"STARTUP_DEBUG_PROBE_ASSERTS": str(many)}, + options=("--assert-sites", "3")) + assert "process exited with 0x00000000" in out, out + assert f"debug-probe repeated {many}\n" in text(logdir / "stdout.txt"), text(logdir / "stdout.txt") + assert breakpoint_sites(logdir, image).count(repeated[0]) == many, text(logdir / "events.txt") + # Control: a hit budget of three runs out at the repeated site's second hit. + out, _ = run(probe, work, "assert-sites-control", {"STARTUP_DEBUG_PROBE_ASSERTS": str(many)}, + options=("--continue-asserts", "3")) + assert f"stopped at breakpoint (0x80000003) at {image}+{repeated[0]:#x}" in out, out + # Two sites: the first hit at the third site stops the run. + out, logdir = run(probe, work, "assert-sites-two", {"STARTUP_DEBUG_PROBE_ASSERTS": str(many)}, + options=("--assert-sites", "2")) + assert f"stopped at breakpoint (0x80000003) at {image}+{repeated[0]:#x}" in out, out + assert breakpoint_sites(logdir, image).count(repeated[0]) == 1, text(logdir / "events.txt") + # X2W_STOP_AT still stops at a site the site budget covers. + out, _ = run(probe, work, "assert-sites-stop", {"X2W_STOP_AT": f"{sites[1]:x}"}, + options=("--assert-sites", "3")) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out, out + # Both budgets: the hits A, B, A with --assert-sites 1 --continue-asserts 2. The site budget + # covers A, the hit budget B, and A's second hit is still A, so the probe runs to its end. + out, logdir = run(probe, work, "assert-sites-combined", {"STARTUP_DEBUG_PROBE_REVISIT": "1"}, + options=("--assert-sites", "1", "--continue-asserts", "2")) + assert "process exited with 0x00000000" in out, out + assert breakpoint_sites(logdir, image) == [sites[0], sites[1], sites[0]], text(logdir / "events.txt") + # Control: the hit budget alone runs out at A's second hit, so the site budget is what continues it. + out, _ = run(probe, work, "assert-sites-combined-control", {"STARTUP_DEBUG_PROBE_REVISIT": "1"}, + options=("--continue-asserts", "2")) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[0]:#x}" in out, out + out, _ = run(probe, work, "assert-sites-negative", {}, options=("--assert-sites", "-1")) + assert "expected an --assert-sites value of 0 or greater" in out, out + # X2W_DUMP_AT: a dump one second in, while the probe is still alive. out, logdir = run(probe, work, "dump", {"X2W_DUMP_AT": "1"}) assert "process exited with 0x00000000" in out, out @@ -254,6 +292,8 @@ def stack_read(address, size): {"X2W_LOG_AT": ",".join((*malformed, entry, *(f"{rva:x}:rax" for rva in unusable), entry))}, options=("--continue-asserts", "10", "--offline", "0")) assert "process exited with 0x00000000" in out and f"LOG_AT hit counts: +{log_rva:x} x2\n" in out, out + assert re.search(r"^ hook windows: entries=\d+ windows=\d+ unprotected=0 " + r"deferred=\d+ timeouts=0 protection=on$", out, re.M), out assert log_probe_state(logdir) == (log_rva, opcode), text(logdir / "stdout.txt") assert log_at_records(logdir, log_rva, 2) == [ f"rdx={LOG_TOKEN + i:#x} [rcx+8]=0x89abcdef01234567 " diff --git a/tests/startup_debug_launch_args_check.py b/tests/startup_debug_launch_args_check.py new file mode 100644 index 0000000000..119203fe7c --- /dev/null +++ b/tests/startup_debug_launch_args_check.py @@ -0,0 +1,70 @@ +"""Malformed option values of tools/startup/debug_launch.py end in a one-line message and exit code 2. + +The tool must return before it creates a job object or a process, so the executable need not exist. +The tool imports Windows-only ctypes entry points, so other hosts skip (exit code 77). + +usage: startup_debug_launch_args_check.py [path/to/debug_launch.py] +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +TOOL = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "tools" / "startup" / "debug_launch.py" + +BAD = [ + ["--timeout", "abc"], + ["--timeout", "-1"], + ["--timeout", "inf"], + ["--timeout", "nan"], + ["--memory-gib", "abc"], + ["--memory-gib", "inf"], + ["--memory-gib", "-inf"], + ["--memory-gib", "nan"], + ["--memory-gib", "-1"], + ["--memory-gib", "0"], + ["--memory-gib", "1e-12"], + ["--memory-gib", "1e30"], + ["--continue-asserts", "x"], + ["--continue-asserts", "1.5"], + ["--continue-asserts", "-2"], +] + + +def main(): + if os.name != "nt": + print("debug_launch.py needs Windows; skipped") + return 77 + failures = [] + with tempfile.TemporaryDirectory() as tmp: + exe = os.path.join(tmp, "missing.exe") + for option in BAD: + logdir = os.path.join(tmp, "log") + run = subprocess.run([sys.executable, "-B", str(TOOL), exe, tmp, logdir] + option, + capture_output=True, text=True, timeout=60) + text = run.stdout + run.stderr + problems = [] + if run.returncode != 2: + problems.append(f"exit code {run.returncode}") + if "Traceback" in text: + problems.append("traceback") + if not text.startswith("expected "): + problems.append("no 'expected ...' message") + if len(text.strip().splitlines()) != 1: + problems.append("not a single line") + if os.path.exists(logdir): + problems.append("log directory created before validation") + if problems: + failures.append(f"{' '.join(option)}: {', '.join(problems)}: {text.strip()[-200:]!r}") + for failure in failures: + print("FAIL", failure) + if failures: + return 1 + print(f"{len(BAD)} malformed option values rejected") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/startup_debug_probe.cpp b/tests/startup_debug_probe.cpp index 4c1db8e51c..e4f2e4fcf1 100644 --- a/tests/startup_debug_probe.cpp +++ b/tests/startup_debug_probe.cpp @@ -1,6 +1,7 @@ // Input for the startup debugger's diagnostics check (tests/startup_debug_check.py). It reaches two // breakpoints in its own image, the way a retail image keeps soft asserts, and with -// STARTUP_DEBUG_PROBE_ASSERTS=<n> n more at a third site (the repeated-assert case). It also +// STARTUP_DEBUG_PROBE_ASSERTS=<n> n more at a third site (the repeated-assert case). With +// STARTUP_DEBUG_PROBE_REVISIT=1 it reaches the first breakpoint once more after the second. It also // reserves one large range, reports whether the loader gave it the debug heap, stays alive for a // moment and exits 0. // With STARTUP_DEBUG_PROBE_DLL=<file> and STARTUP_DEBUG_PROBE_EXPORT=<name> it also loads that DLL @@ -145,6 +146,9 @@ int main() { first_assert(); second_assert(); + if (const char* const revisit = std::getenv("STARTUP_DEBUG_PROBE_REVISIT"); revisit && *revisit == '1') { + first_assert(); + } const char* const repeated = std::getenv("STARTUP_DEBUG_PROBE_ASSERTS"); const int repeated_count = repeated ? std::atoi(repeated) : 0; repeated_assert(repeated_count); diff --git a/tests/startup_debug_window_check.py b/tests/startup_debug_window_check.py new file mode 100644 index 0000000000..5fdccde84a --- /dev/null +++ b/tests/startup_debug_window_check.py @@ -0,0 +1,79 @@ +"""Check the periodic window pictures of tools/startup/debug_launch.py (--capture-every) on a source-built window. + +usage: startup_debug_window_check.py <startup_window_probe.exe> + +tests/startup_window_probe.cpp shows a 160x120 window that is red, then blue after 3.5 s. The run lasts 9 s with +--capture-every 1. The saved window_<sss>s.png files must show red first and blue last, the frames in between +must have been skipped as unchanged, the first change must be reported inside the window of time the probe +changes it, and the end-of-run window.png must still be written (blue). Controls: without --capture-every no +window_<sss>s.png exists and no summary line is printed; an interval below one second is refused. +Exit code 77 (skip) only when the machine shows no window at all. +""" +from pathlib import Path +import os +import re +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_window_capture_check import decode_png # noqa: E402 + +DEBUG = HERE.parent / "tools/startup/debug_launch.py" +RED, BLUE = (200, 30, 30), (30, 30, 200) + + +def run(probe, work, name, *options): + logdir = work / name + env = {k: v for k, v in os.environ.items() if not k.startswith("X2W_")} + command = [sys.executable, "-B", str(DEBUG), str(probe), str(work), str(logdir), "--console", "0", *options] + result = subprocess.run(command, capture_output=True, text=True, timeout=120, env=env) + return result, logdir + + +def pixel(path): + width, height, rows = decode_png(path.read_bytes()) + assert (width, height) == (160, 120), (path.name, width, height) + return tuple(rows[60][3 * 80:3 * 80 + 3]) + + +def main(probe): + probe = Path(probe).resolve() + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + result, logdir = run(probe, work, "periodic", "--timeout", "9", "--capture-every", "1") + out = result.stdout + result.stderr + if "window capture: no visible window" in out: + print("startup_debug_window: SKIP (no window is visible on this machine)") + return 77 + frames = sorted(logdir.glob("window_*s.png")) + assert len(frames) >= 2, (out, [p.name for p in frames]) + assert all(re.fullmatch(r"window_\d{3}s\.png", p.name) for p in frames), [p.name for p in frames] + first, last = pixel(frames[0]), pixel(frames[-1]) + assert first == RED and last == BLUE, (first, last, [p.name for p in frames]) + assert all(pixel(p) in (RED, BLUE) for p in frames), [p.name for p in frames] + # Only the changes are saved: one red frame, one blue frame, the others skipped. + assert len(frames) == 2, [p.name for p in frames] + found = re.search(r"window captures: (\d+) saved, (\d+) unchanged skipped, first change at (\d+) s", out) + assert found, out + saved, unchanged, change = (int(found.group(i)) for i in (1, 2, 3)) + assert saved == 2 and unchanged >= 3 and 3 <= change <= 6, found.group(0) + assert int(frames[-1].name[7:10]) == change, (frames[-1].name, change) + assert pixel(logdir / "window.png") == BLUE, "the end-of-run picture must stay as before" + assert "window capture: 160x120 -> window.png" in out, out + + control, control_dir = run(probe, work, "control", "--timeout", "4") + assert not list(control_dir.glob("window_*s.png")), "no periodic file without --capture-every" + assert "window captures:" not in control.stdout and (control_dir / "window.png").exists(), control.stdout + + for bad in ("0.5", "-1", "abc"): + refused, _ = run(probe, work, "bad", "--timeout", "1", "--capture-every", bad) + assert refused.returncode == 2 and "--capture-every" in refused.stdout, (bad, refused.returncode, refused.stdout) + print("startup_debug_window: PASS (red then blue saved once each, unchanged frames skipped, change time reported, " + "window.png unchanged, off by default, bad interval refused)") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1])) diff --git a/tests/startup_direct_index_late_write_check.py b/tests/startup_direct_index_late_write_check.py new file mode 100644 index 0000000000..b7bc1d821b --- /dev/null +++ b/tests/startup_direct_index_late_write_check.py @@ -0,0 +1,90 @@ +"""A translated direct indexed draw uses the aliased view's pre-submit contents.""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import prepare_draw_cache + +VERTEX = """ +float4 main(uint vertex : SV_VertexID) : SV_Position { + uint corner = vertex % 3; + float2 xy = float2(corner == 1 ? 3.0 : -1.0, corner == 2 ? -3.0 : 1.0); + return float4(xy.x + (vertex >= 3 ? 8.0 : 0.0), xy.y, 0.5, 1.0); +} +""" +VERTEX_VB = """cbuffer RootConstants : register(b0) { + uint rect_flag; + int base_vertex; + uint start_instance; +}; +ByteAddressBuffer vertices : register(t0); +float4 main(uint vertex : SV_VertexID) : SV_Position { + int vindex = int(vertex) + base_vertex; + float x_offset = asfloat(vertices.Load(vindex * 16)); + uint corner = vertex % 3; + float2 xy = float2(corner == 1 ? 3.0 : -1.0, corner == 2 ? -3.0 : 1.0); + return float4(xy.x + x_offset, xy.y, 0.5, 1.0); +} +""" +PIXEL = "float4 main() : SV_Target { return float4(1, 0, 0, 1); }" +VISIBLE = bytes((255, 0, 0, 255)) +CLIPPED = bytes((0, 0, 255, 255)) +CASES = ( + ("visible", VISIBLE), + ("clipped", CLIPPED), + ("late-visible", VISIBLE), + ("late-clipped", CLIPPED), + ("late-visible-r32", VISIBLE), +) +VB_CASES = ( + ("visible-vb", VISIBLE), + ("clipped-vb", CLIPPED), + ("late-visible-vb", VISIBLE), + ("late-clipped-vb", CLIPPED), + ("late-visible-vb-unplaced", CLIPPED), +) + + +def run_cases(cache_dir, consumer, backend, vertex_src, binding, cases, is_vb=False): + cache_dir.mkdir(parents=True, exist_ok=True) + env, args, output = prepare_draw_cache(cache_dir, consumer, PIXEL, {}, binding, vertex_hlsl=vertex_src) + env["X2W_D3D12_DEBUG"] = "1" + for mode, color in cases: + output.unlink(missing_ok=True) + result = subprocess.run([*args, backend, output], env={**env, "X2W_TEST_INDEX_PROBE": mode}, + capture_output=True, text=True, errors="replace", timeout=20) + if result.returncode == 77: + print(result.stdout, result.stderr) + return 77 + if result.returncode or re.search(r"x2w-d3d12-debug [^\n]*sev=[01]\b", result.stderr): + raise RuntimeError(f"{mode} failed ({result.returncode})\n{result.stdout}\n{result.stderr[-4000:]}") + expected_aliases = 2 if is_vb and mode != "late-visible-vb-unplaced" else 1 + aliases = len(re.findall(r"slot133[^\n]*-> 0x00000000 aliased gpuva=", result.stderr)) + if aliases < expected_aliases: + raise AssertionError(f"{mode}: expected at least {expected_aliases} aliased buffers, saw {aliases}\n{result.stderr[-4000:]}") + if not re.search(r"indexed\(3, 1, start [01], base 0\)[^\n]*-> drawn;", result.stderr): + raise AssertionError(f"{mode}: translated indexed draw was not recorded\n{result.stderr[-4000:]}") + pixels = output.read_bytes() + if pixels != color * 32: + raise AssertionError(f"{mode}: got {pixels.hex()}, expected 32 pixels of {color.hex()}") + adapter = next(line for line in result.stdout.splitlines() if line.startswith("adapter=")) + debug_layer = "enabled" if "debug layer: 0x00000000 enabled" in result.stderr else "unavailable" + print(f"{mode}: 32 exact pixels, {adapter}, debug layer {debug_layer}") + return 0 + + +def check(directory, consumer, backend): + rc = run_cases(directory / "direct", consumer, backend, VERTEX, "", CASES) + if rc == 77: + return 77 + rc = run_cases(directory / "vb", consumer, backend, VERTEX_VB, "srv 0 buf vb 0", VB_CASES, is_vb=True) + if rc == 77: + return 77 + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp new file mode 100644 index 0000000000..9fc6467d43 --- /dev/null +++ b/tests/startup_dstorage_break_window_check.cpp @@ -0,0 +1,358 @@ +// A DirectStorage request whose destination lies in an XMem run that is being taken apart must wait for the break +// and then land, not be refused. +// +// With shared views (X2W_XMEM_SHARED_VIEWS=1) adjacent pages of one batch share a view, and unmapping one page of +// such a run unmaps the whole run and maps its other pages again, under xmem's mapping mutex. For that moment a +// surviving page reads as reserved. The xmem build with its test controls holds an unmap in that window +// (X2W_XMEM_TEST_HOLD_WINDOW=<name>: it sets "<name>.unmapped" and waits up to five seconds for "<name>.release"). +// +// usage: startup_dstorage_break_window_check <xmem.dll built with its test controls> <XCRDAPI.dll> +// [plain|views-off|outcomes] +// Cases, each against the real stand-in's queue with a memory source: +// - no break: a request into a mapped page of the run lands; +// - read-only destination: refused, nothing written (the writability check also runs on the xmem path); +// - break held: while an unmap holds page 2's run apart (page 2 reads MEM_RESERVE), a request into page 2 must not +// complete for the whole hold window (1000 ms, polled every 10 ms); after the release it completes with S_OK and +// every byte landed. An XCRDAPI that judges the destination with its own VirtualQuery instead refuses inside the +// window: "FAIL break window: refused while the run was broken" (the negative control in +// tests/cmake/xmem_page_runs.cmake). +// `plain` and `views-off` instead check which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared +// views, a request into a VirtualAlloc destination copies without it and one into the run with it; with +// X2W_XMEM_SHARED_VIEWS unset (`views-off`), a request into an XMem page copies without it as well. +// `outcomes` forces each copy error in turn (the test-controls build's X2W_XMEM_TEST_COPY_ERROR) and checks the +// outcome XCRDAPI logs for the request: the DLLs log to the standard error handle, which this mode points at a +// temporary file. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> + +namespace { +using u64 = std::uint64_t; +struct Object { void** vtable; }; +using GetFactoryFn = long(__stdcall*)(const void*, void**); +using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const void*, void**); +using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); +using EnqueueRequestFn = void(__stdcall*)(void*, const void*); +using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using SubmitFn = void(__stdcall*)(void*); +using IsCompleteFn = bool(__stdcall*)(void*, unsigned); +using GetHResultFn = long(__stdcall*)(void*, unsigned); +using VirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocatePagesFn = BOOL(WINAPI*)(ULONG_PTR, PULONG_PTR, PULONG_PTR); +using MapPagesFn = void*(WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); +using ScatterFn = BOOL(WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); +using CopyCountsFn = BOOL(WINAPI*)(ULONGLONG*, ULONGLONG*); + +constexpr SIZE_T page = 65536; +constexpr unsigned run_pages = 8; +constexpr unsigned bytes = 4096; +constexpr DWORD hold_ms = 1000; // the window in which a request into the broken run must not complete +constexpr DWORD poll_ms = 10; +unsigned char source[bytes]; +int failures; + +Object* status; +Object* queue; +unsigned next_index; + +void fail(const char* name, const char* what) +{ + std::printf("FAIL %s: %s\n", name, what); + ++failures; +} + +// Enqueues one uncompressed memory-source request and submits it; returns its status index. +unsigned submit(unsigned char* destination, unsigned capacity, unsigned size) +{ + unsigned char request[0x48] = {}; + *reinterpret_cast<u64*>(request + 0x00) = 0x400000; + *reinterpret_cast<unsigned char**>(request + 0x08) = destination; + *reinterpret_cast<unsigned*>(request + 0x18) = capacity; + *reinterpret_cast<const void**>(request + 0x20) = source; + *reinterpret_cast<unsigned*>(request + 0x30) = size; + const unsigned index = next_index++; + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, request); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, index); + reinterpret_cast<SubmitFn>(queue->vtable[6])(queue); + return index; +} + +// Polls the status entry for up to milliseconds; true with its HRESULT when it completed. +bool completed_within(unsigned index, DWORD milliseconds, long& hr) +{ + for (DWORD waited = 0;; waited += poll_ms) { + if (reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, index)) { + hr = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, index); + return true; + } + if (waited >= milliseconds) return false; + Sleep(poll_ms); + } +} + +bool filled(const unsigned char* at, unsigned char value, unsigned count) +{ + for (unsigned i = 0; i < count; ++i) + if (at[i] != value) return false; + return true; +} + +DWORD query_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +struct Unmap { + ScatterFn scatter; + void* address; + BOOL result; +}; + +DWORD WINAPI unmap_one(void* context) +{ + auto* unmap = static_cast<Unmap*>(context); + unmap->result = unmap->scatter(&unmap->address, 1, nullptr); // no pages: unmap + return 0; +} + +// One request per row; the change of xmem's copy counts across it names the path the copy took. +int copy_rows(HMODULE xmem, unsigned char* run_page, bool views_off) +{ + const auto counts = reinterpret_cast<CopyCountsFn>(GetProcAddress(xmem, "x2w_xmem_copy_counts")); + ULONGLONG locked = 0, unlocked = 0; + if (!counts || !counts(&locked, &unlocked)) { + std::printf("FAIL setup: x2w_xmem_copy_counts (needs the test-controls build)\n"); + return 1; + } + const auto row = [&](const char* name, unsigned char* destination, ULONGLONG want_locked, ULONGLONG want_unlocked) { + ULONGLONG locked0 = 0, unlocked0 = 0, locked1 = 0, unlocked1 = 0; + counts(&locked0, &unlocked0); + std::memset(destination, 0xAA, bytes); + long hr = -1; + const bool done = completed_within(submit(destination, bytes, bytes), 5000, hr); + counts(&locked1, &unlocked1); + std::printf("%s: completed %d hr 0x%08lx; copies under the mapping mutex %llu, without it %llu\n", name, done, + static_cast<unsigned long>(hr), locked1 - locked0, unlocked1 - unlocked0); + if (!done || hr != 0 || std::memcmp(destination, source, bytes) != 0) fail(name, "the request did not land"); + else if (locked1 - locked0 != want_locked || unlocked1 - unlocked0 != want_unlocked) fail(name, "wrong copy path"); + else std::printf("ok: %s\n", name); + }; + if (views_off) { + row("views off, XMem page destination", run_page, 0, 1); + } else { + auto* plain = static_cast<unsigned char*>(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!plain) { + fail("plain destination", "VirtualAlloc"); + } else { + row("plain destination", plain, 0, 1); + VirtualFree(plain, 0, MEM_RELEASE); + } + row("run destination", run_page, 1, 0); + } + if (failures) return 1; + std::printf("dstorage copy paths: %s\n", views_off ? "views off: no mutex" : "the mutex only for the run"); + return 0; +} + +// Waits up to two seconds for text to appear in the log file (the request's line follows its completion). +bool logged(HANDLE log, const char* text) +{ + static char all[1 << 16]; + for (int waited = 0; waited <= 2000; waited += 20) { + DWORD size = 0; + SetFilePointer(log, 0, nullptr, FILE_BEGIN); + if (ReadFile(log, all, sizeof(all) - 1, &size, nullptr)) { + all[size] = 0; + if (std::strstr(all, text)) return true; + } + Sleep(20); + } + return false; +} + +int outcome_rows() +{ + char dir[MAX_PATH], path[MAX_PATH]; + GetTempPathA(sizeof(dir), dir); + std::snprintf(path, sizeof(path), "%sx2w-dstorage-outcomes-%lu.log", dir, GetCurrentProcessId()); + const HANDLE log = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + auto* plain = static_cast<unsigned char*>(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (log == INVALID_HANDLE_VALUE || !plain) { + std::printf("FAIL setup: log file or destination\n"); + return 1; + } + const HANDLE saved = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_ERROR_HANDLE, log); + const struct { + DWORD error; + const char* text; + } rows[] = { + {ERROR_NOACCESS, "-> destination not writable"}, + {ERROR_INVALID_ADDRESS, "-> copy faulted (part of the destination may be written)"}, + {ERROR_INVALID_PARAMETER, "-> invalid copy request"}, + {ERROR_GEN_FAILURE, "-> copy failed (error 31)"}, + }; + for (const auto& row : rows) { + char code[16]; + std::snprintf(code, sizeof(code), "%lu", row.error); + SetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", code); + std::memset(plain, 0xAA, bytes); + long hr = 0; + const bool done = completed_within(submit(plain, bytes, bytes), 5000, hr); + SetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", nullptr); + const bool found = logged(log, row.text); + std::printf("error %lu: completed %d hr 0x%08lx, logged \"%s\" %d\n", row.error, done, + static_cast<unsigned long>(hr), row.text, found); + if (!done || hr == 0) fail(row.text, "the request did not fail"); + else if (!filled(plain, 0xAA, bytes)) fail(row.text, "bytes were written"); + else if (!found) fail(row.text, "outcome not logged"); + else std::printf("ok: error %lu logged %s\n", row.error, row.text); + } + SetStdHandle(STD_ERROR_HANDLE, saved); + CloseHandle(log); + VirtualFree(plain, 0, MEM_RELEASE); + if (failures) return 1; + std::printf("dstorage outcomes: one text per copy error\n"); + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + const bool plain_mode = argc == 4 && std::strcmp(argv[3], "plain") == 0; + const bool views_off = argc == 4 && std::strcmp(argv[3], "views-off") == 0; + const bool outcomes = argc == 4 && std::strcmp(argv[3], "outcomes") == 0; + if (argc != 3 && !plain_mode && !views_off && !outcomes) { + std::printf("usage: startup_dstorage_break_window_check <xmem.dll with test controls> <XCRDAPI.dll> " + "[plain|views-off|outcomes]\n"); + return 2; + } + char hold_name[64]; + std::snprintf(hold_name, sizeof(hold_name), "x2w-dstorage-break-window-%lu", GetCurrentProcessId()); + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", views_off ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", nullptr); // the run is mapped by one call; no join is needed + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold_name); + + // xmem first: XCRDAPI finds it by module name (GetModuleHandleW(L"xmem.dll")). + HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem || GetModuleHandleW(L"xmem.dll") != xmem) { + std::printf("FAIL setup: %s is not loaded as xmem.dll\n", argv[1]); + return 1; + } + const auto virtual_alloc = reinterpret_cast<VirtualAllocFn>(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto allocate = reinterpret_cast<AllocatePagesFn>(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast<MapPagesFn>(GetProcAddress(xmem, "XMemMapPhysicalPages")); + const auto scatter = reinterpret_cast<ScatterFn>(GetProcAddress(xmem, "XMemMapPhysicalPagesScatter")); + HMODULE library = LoadLibraryA(argv[2]); + auto* get_factory = library ? reinterpret_cast<GetFactoryFn>(GetProcAddress(library, "DStorageGetFactory")) : nullptr; + if (!virtual_alloc || !allocate || !map || !scatter || !get_factory) { + std::printf("FAIL setup: missing export\n"); + return 1; + } + void* factory_pointer = nullptr; + if (get_factory(nullptr, &factory_pointer) != 0 || !factory_pointer) return 1; + auto* factory = static_cast<Object*>(factory_pointer); + void* status_pointer = nullptr; + void* queue_pointer = nullptr; + unsigned char description[0x28] = {}; + *reinterpret_cast<std::uint16_t*>(description + 8) = 16; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 8, "Status", nullptr, &status_pointer) != 0 || + reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, description, nullptr, &queue_pointer) != 0) + return 1; + status = static_cast<Object*>(status_pointer); + queue = static_cast<Object*>(queue_pointer); + for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast<unsigned char>(i % 251 + 1); + if (outcomes) return outcome_rows(); + + // Eight physical pages mapped as one run at the start of a startup reservation (as xmem_page_runs_check.py). + auto* whole = static_cast<unsigned char*>(virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + ULONG_PTR count = run_pages, tokens[run_pages] = {}; + unsigned char* base = whole ? whole + page : nullptr; + if (!base || !allocate(0x20400000, &count, tokens) || count != run_pages || map(base, run_pages, tokens) != base) { + std::printf("FAIL setup: could not map %u pages (err %lu)\n", run_pages, GetLastError()); + return 1; + } + if (plain_mode || views_off) return copy_rows(xmem, base + 2 * page, views_off); + MEMORY_BASIC_INFORMATION run{}; + if (!VirtualQuery(base, &run, sizeof(run)) || run.Type != MEM_MAPPED || run.RegionSize < run_pages * page) { + std::printf("FAIL setup: the %u pages are not one view (region 0x%zx), so no unmap takes a run apart\n", run_pages, + static_cast<std::size_t>(run.RegionSize)); + return 1; + } + unsigned char* target = base + 2 * page; + + // No break: the request lands. + std::memset(target, 0xAA, bytes); + long hr = -1; + if (!completed_within(submit(target, bytes, bytes), 5000, hr)) fail("no break", "no completion"); + else if (hr != 0) fail("no break", "request failed"); + else if (std::memcmp(target, source, bytes) != 0) fail("no break", "bytes differ"); + else std::printf("ok: no break: the request into page 2 of the run landed\n"); + + // Read-only destination: refused before any write, on the xmem path too. + auto* plain = static_cast<unsigned char*>(VirtualAlloc(nullptr, 2 * bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + DWORD old = 0; + if (!plain) { + fail("read-only destination", "VirtualAlloc"); + } else { + std::memset(plain, 0xAA, 2 * bytes); + if (!VirtualProtect(plain + bytes, bytes, PAGE_READONLY, &old)) fail("read-only destination", "VirtualProtect"); + else if (!completed_within(submit(plain, 2 * bytes, bytes), 5000, hr)) fail("read-only destination", "no completion"); + else if (hr == 0) fail("read-only destination", "request succeeded"); + else if (!filled(plain, 0xAA, 2 * bytes)) fail("read-only destination", "bytes were written"); + else std::printf("ok: read-only destination: refused, nothing written\n"); + VirtualFree(plain, 0, MEM_RELEASE); + } + + // Break held: an unmap of page 5 takes the run apart and holds it there until released. + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold_name); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold_name); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::memset(target, 0xAA, bytes); + Unmap unmap{scatter, base + 5 * page, FALSE}; + HANDLE thread = unmapped && release ? CreateThread(nullptr, 0, unmap_one, &unmap, 0, nullptr) : nullptr; + if (!thread || WaitForSingleObject(unmapped, 10000) != WAIT_OBJECT_0) { + std::printf("FAIL break window: the unmap never held the run apart (hook missing or timed out)\n"); + if (release) SetEvent(release); + return 1; + } + if (query_state(target) != MEM_RESERVE) { + std::printf("FAIL break window: page 2 is not reserved while the run is apart (state 0x%lx)\n", query_state(target)); + SetEvent(release); + return 1; + } + std::printf("ok: break held: page 2 reads MEM_RESERVE while the run is apart\n"); + const unsigned index = submit(target, bytes, bytes); + const bool early = completed_within(index, hold_ms, hr); + const long early_hr = hr; + SetEvent(release); + const bool joined = WaitForSingleObject(thread, 10000) == WAIT_OBJECT_0; + if (early) { + if (early_hr != 0) fail("break window", "refused while the run was broken"); + else fail("break window", "completed while the run was broken"); + } else { + std::printf("ok: break held: no completion within %lu ms\n", hold_ms); + if (!completed_within(index, 5000, hr)) fail("break window", "no completion after the release"); + else if (hr != 0) fail("break window", "request failed after the release"); + else if (std::memcmp(target, source, bytes) != 0) fail("break window", "bytes differ after the release"); + else std::printf("ok: break released: the request completed with S_OK and every byte landed\n"); + } + if (!joined || !unmap.result) fail("break window", "the unmap of page 5 did not finish"); + CloseHandle(thread); + + if (failures) return 1; + std::printf("dstorage break window: the request waited for the break and landed\n"); + return 0; +} diff --git a/tests/startup_dstorage_destination_check.cpp b/tests/startup_dstorage_destination_check.cpp index 6e456b9b83..1c05da696e 100644 --- a/tests/startup_dstorage_destination_check.cpp +++ b/tests/startup_dstorage_destination_check.cpp @@ -12,6 +12,7 @@ #define NOMINMAX #endif #include <windows.h> +#include <psapi.h> #include <cstdint> #include <cstdio> @@ -33,9 +34,16 @@ using OpenFileFn = long(__stdcall*)(void*, const wchar_t*, const void*, void**); constexpr unsigned page = 4096; constexpr unsigned pages = 3; constexpr unsigned bytes = pages * page; -constexpr unsigned cases = 12; +constexpr unsigned cases = 15; unsigned char source[bytes]; int failures; +volatile LONG guard_notifications; // first-chance guard-page exceptions any thread raised + +LONG CALLBACK count_guard(EXCEPTION_POINTERS* info) +{ + if (info->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) InterlockedIncrement(&guard_notifications); + return EXCEPTION_CONTINUE_SEARCH; +} Object* status; Object* queue; @@ -84,6 +92,14 @@ unsigned char* fresh_region() return region; } +// A guard page must still be armed after the check; other protections are not checked here. +bool guard_kept(const unsigned char* at, DWORD protect) +{ + if (!(protect & PAGE_GUARD)) return true; + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(at, &info, sizeof(info)) && (info.Protect & PAGE_GUARD); +} + // Refusal: the middle page, or the last, is made unusable in the way `how` names. void refused(const char* name, DWORD protect, bool decommit_last) { @@ -94,12 +110,15 @@ void refused(const char* name, DWORD protect, bool decommit_last) if (decommit_last) ok = VirtualFree(region + 2 * page, page, MEM_DECOMMIT) != 0; else ok = VirtualProtect(region + page, page, protect, &old) != 0; if (!ok) { fail(name, "could not change the page"); VirtualFree(region, 0, MEM_RELEASE); return; } + const LONG guards_before = guard_notifications; const long hr = run_request(region, bytes, decommit_last ? page : bytes); if (hr == -1) fail(name, "no completion"); + else if (guard_notifications != guards_before) fail(name, "the check raised a guard-page exception"); else if (hr == 0) fail(name, "request succeeded"); // The page the case changed is not read (a guard or no-access page would trip the check itself). else if (!untouched(region, 0, page)) fail(name, "first page was written"); else if (!decommit_last && !untouched(region, 2 * page, bytes)) fail(name, "last page was written"); + else if (!guard_kept(region + page, protect)) fail(name, "guard page lost its guard bit"); else std::printf("ok: %s refused, bytes before the bad page intact\n", name); VirtualFree(region, 0, MEM_RELEASE); } @@ -126,6 +145,8 @@ int main(int argc, char** argv) status = static_cast<Object*>(status_pointer); queue = static_cast<Object*>(queue_pointer); for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast<unsigned char>(i % 251); + // Observes every first-chance exception before any handler of the stand-in: the check must raise none. + if (!AddVectoredExceptionHandler(1, count_guard)) return 1; refused("read-only middle page", PAGE_READONLY, false); refused("guard middle page", PAGE_READWRITE | PAGE_GUARD, false); @@ -142,6 +163,25 @@ int main(int argc, char** argv) else std::printf("ok: writable control after the refusals wrote every byte\n"); VirtualFree(region, 0, MEM_RELEASE); + // Committed but never touched: not in the working set, so judged by the VirtualQuery walk, and writable. + auto* untouched_region = static_cast<unsigned char*>(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!untouched_region) return 1; + const long cold_hr = run_request(untouched_region, bytes, bytes); + if (cold_hr != 0) fail("non-resident destination", "request failed"); + else if (std::memcmp(untouched_region, source, bytes) != 0) fail("non-resident destination", "bytes differ"); + else std::printf("ok: non-resident writable destination wrote every byte\n"); + VirtualFree(untouched_region, 0, MEM_RELEASE); + + // The check covers every page of the declared capacity; past the data it must leave each byte as it was. + unsigned char* roomy = fresh_region(); + if (!roomy) return 1; + const long roomy_hr = run_request(roomy, bytes, page); + if (roomy_hr != 0) fail("capacity past the data", "request failed"); + else if (std::memcmp(roomy, source, page) != 0) fail("capacity past the data", "data bytes differ"); + else if (!untouched(roomy, page, bytes)) fail("capacity past the data", "a byte past the data changed"); + else std::printf("ok: capacity past the data wrote the data, later bytes unchanged\n"); + VirtualFree(roomy, 0, MEM_RELEASE); + // Copy-on-write destination (PAGE_WRITECOPY) is also allowed and must succeed. HANDLE mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, bytes, nullptr); auto* cow = mapping ? static_cast<unsigned char*>(MapViewOfFile(mapping, FILE_MAP_COPY, 0, 0, bytes)) : nullptr; @@ -161,6 +201,42 @@ int main(int argc, char** argv) } if (mapping) CloseHandle(mapping); + // A copy-on-write page followed by a no-access page: the request is refused, and the first page stays + // shared (the check took no private copy of it) with its bytes unchanged. + HANDLE shared_mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 2 * page, nullptr); + auto* filler = shared_mapping ? static_cast<unsigned char*>(MapViewOfFile(shared_mapping, FILE_MAP_WRITE, 0, 0, 2 * page)) : nullptr; + auto* cow_pair = shared_mapping ? static_cast<unsigned char*>(MapViewOfFile(shared_mapping, FILE_MAP_COPY, 0, 0, 2 * page)) : nullptr; + DWORD old_protect = 0; + if (!filler || !cow_pair) { + fail("copy-on-write before no-access", "MapViewOfFile"); + } else { + std::memset(filler, 0xAA, 2 * page); + volatile unsigned char sink = cow_pair[0]; // a read maps the first page in, still shared + (void)sink; + PSAPI_WORKING_SET_EX_INFORMATION first{}; + first.VirtualAddress = cow_pair; + if (!VirtualProtect(cow_pair + page, page, PAGE_NOACCESS, &old_protect)) { + fail("copy-on-write before no-access", "VirtualProtect"); + } else if (!QueryWorkingSetEx(GetCurrentProcess(), &first, sizeof(first)) || !first.VirtualAttributes.Valid || + !first.VirtualAttributes.Shared) { + fail("copy-on-write before no-access", "first page not resident and shared before the request"); + } else { + const long pair_hr = run_request(cow_pair, 2 * page, 2 * page); + first.VirtualAttributes.Flags = 0; + const bool queried = QueryWorkingSetEx(GetCurrentProcess(), &first, sizeof(first)) != 0; + const bool still_shared = queried && (first.VirtualAttributes.Valid ? first.VirtualAttributes.Shared + : first.VirtualAttributes.Invalid.Shared); + if (pair_hr == -1) fail("copy-on-write before no-access", "no completion"); + else if (pair_hr == 0) fail("copy-on-write before no-access", "request succeeded"); + else if (!untouched(cow_pair, 0, page)) fail("copy-on-write before no-access", "first page was written"); + else if (!still_shared) fail("copy-on-write before no-access", "first page became private"); + else std::printf("ok: copy-on-write before no-access refused, first page still shared\n"); + } + } + if (cow_pair) UnmapViewOfFile(cow_pair); + if (filler) UnmapViewOfFile(filler); + if (shared_mapping) CloseHandle(shared_mapping); + // Distinct failure codes: a destination too small for the data, and a read past the end of a file. const long insufficient = static_cast<long>(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)); const long end_of_file = static_cast<long>(HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)); diff --git a/tests/startup_exit_report_check.py b/tests/startup_exit_report_check.py new file mode 100644 index 0000000000..e3135a62bc --- /dev/null +++ b/tests/startup_exit_report_check.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Checks tools/startup/exit_report.py against synthetic debug-launch logs.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools" / "startup")) +import exit_report # noqa: E402 + + +def report(logs: dict[str, str]) -> tuple[str, exit_report.ExitSummary]: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for name, text in logs.items(): + (root / name).write_text(text, encoding="utf-8") + summary = exit_report.summarize(root) + return exit_report.format_markdown(summary), summary + + +def expect(report_text: str, summary: exit_report.ExitSummary, want: list[str], label: str) -> None: + for snippet in want: + assert snippet in report_text, f"{label}: missing {snippet!r}\n{report_text}" + assert summary.classification() in { + "clean exit", "nonzero exit", "exception stop", "timeout", "stopped by request", "missing exit event", + }, label + + +def main() -> int: + clean, clean_summary = report({ + "events.txt": " 301.800 exit 0x00000000\n", + "stderr.txt": ( + "x2w-d3d12 heartbeat: 7395 frames presented in 301.8 s (24.53 fps overall)\n" + "x2w-render presented surface 1600x900 format 28, readback 1, mean level 0.0/255\n" + ), + }) + expect(clean, clean_summary, [ + "| Exit code | `0x00000000` (0) |", + "| Classification | clean exit |", + "| End time | `301.8` s |", + "| Last present | `7395` frames at `301.8` s (`24.53` fps overall) |", + "| Last presented surface | `1600x900` format `28`, readback `1`, mean level `0.0/255` |", + ], "clean exit") + + nonzero, nonzero_summary = report({ + "events.txt": " 307.600 exit 0x00000001\n", + }) + expect(nonzero, nonzero_summary, [ + "| Exit code | `0x00000001` (1) |", + "| Classification | nonzero exit |", + "| End time | `307.6` s |", + "| First observed exception | not reported |", + ], "nonzero exit") + + stopped, stopped_summary = report({ + "events.txt": ( + " 250.250 exception 0xE06D7363 C++ exception at C:\\Users\\alice\\game.exe+0x55 first-chance params=['0x1']\n" + " 299.900 exception 0xC0000005 access violation at KERNELBASE.dll+0x9000 second-chance params=['0x0']\n" + "debugger stop 0xc0000005 second-chance\n" + ), + "finished.txt": ( + "stopped at access violation (0xc0000005) at game.exe+0x4da6341 after 253.49 s " + "(second chance) params=['0x1']\n" + ), + }) + expect(stopped, stopped_summary, [ + "| Classification | exception stop |", + "| End time | `253.5` s |", + "| First observed exception | `0xe06d7363` (first-chance) |", + "| Last observed exception | `0xc0000005` (second-chance) |", + "| Observed exceptions | `2` |", + ], "exception stop") + for secret in ("alice", "game.exe", "KERNELBASE", "0x4da6341", "0x55", "0x9000"): + assert secret not in stopped, f"exception stop leaked {secret!r}\n{stopped}" + + timed_out, timeout_summary = report({"finished.txt": "timeout after 300.00 s\n"}) + expect(timed_out, timeout_summary, [ + "| Classification | timeout |", "| End time | `300.0` s |", + ], "timeout") + + requested, requested_summary = report({"finished.txt": "stopped by request after 42.0 s (stop file)\n"}) + expect(requested, requested_summary, ["| Classification | stopped by request |", "| End time | `42.0` s |"], "stop request") + + missing, missing_summary = report({"stderr.txt": "x2w-d3d12 heartbeat: 12 frames presented in 1.0 s (12.0 fps overall)\n"}) + expect(missing, missing_summary, ["| Classification | missing exit event |", "| Last present | `12` frames at `1` s (`12` fps overall) |"], "missing exit") + + filtered, filtered_summary = report({ + "events.txt": ( + " 1.000 exception 0x80000003 breakpoint at ntdll.dll+0x1 first-chance params=[]\n" + " 2.000 exception 0x406d1388 thread name at game.exe+0x2 first-chance params=[]\n" + ), + }) + expect(filtered, filtered_summary, ["| Observed exceptions | `0` |"], "filtered first chance") + assert "0x80000003" not in filtered and "0x406d1388" not in filtered + + hostile, hostile_summary = report({ + "events.txt": ( + " 3.000 exception 0xE06D7363 C++ exception at C:\\Users\\alice\\secret\\game.exe+0x1 second-chance " + "params=['0x00007ff7deadbeef', 'https://acme.example/leak']\n" + " 4.000 exception 0xZZ00ZZ00 junk at X second-chance\n" + ), + "stderr.txt": ( + "x2w-d3d12 heartbeat: 5 frames presented in 2.0 s (2.5 fps overall) acme_widget 0x00007ff7deadbeef\n" + "x2w-render presented surface 1x1 format 28, readback 1, mean level 0.0/255 secret\n" + ), + }) + for needle in ("alice", "secret", "game.exe", "acme", "widget", "deadbeef", "http", "0xZZ00ZZ00"): + assert needle not in hostile, f"hostile input leaked {needle!r}\n{hostile}" + assert hostile_summary.exception_events == 1 + + # The 16 MiB cap applies to the lines that are parsed, not to a discarded first read. + bounded, bounded_summary = report({ + "events.txt": " 12.500 exit 0x00000000\n", + "stdout.txt": "x" * (exit_report.MAX_BYTES + 10) + + "x2w-d3d12 heartbeat: 99 frames presented in 12.0 s (8.25 fps overall)\n", + }) + assert "| Last present | not reported |" in bounded, bounded + assert bounded_summary.last_present_frames is None, bounded_summary + + # finished.txt is authoritative even when events.txt contains an earlier exit line. + authority, authority_summary = report({ + "finished.txt": "process exited with 0x00000005 after 10.00 s\n", + "events.txt": "3.000 exit 0x00000000\n", + }) + expect(authority, authority_summary, [ + "| Exit code | `0x00000005` (5) |", + "| Classification | nonzero exit |", + "| End time | `10.0` s |", + ], "finished authority") + + # The highest present sample wins regardless of file order. + ordered, ordered_summary = report({ + "stderr.txt": "x2w-d3d12 heartbeat: 50 frames presented in 5.0 s (10.0 fps overall)\n", + "stdout.txt": "x2w-d3d12 heartbeat: 20 frames presented in 2.0 s (10.0 fps overall)\n", + }) + expect(ordered, ordered_summary, ["| Last present | `50` frames at `5` s (`10` fps overall) |"], "highest heartbeat") + + second_chance, second_chance_summary = report({ + "events.txt": " 1.000 exception 0x80000003 breakpoint at ntdll.dll+0x1 second-chance params=[]\n", + }) + assert second_chance_summary.exception_events == 1, second_chance + assert "0x80000003" in second_chance, second_chance + + payload = exit_report.as_json(clean_summary) + assert payload["classification"] == "clean exit" and payload["last_present_frames"] == 7395 + assert json.loads(json.dumps(payload)) == payload + + print("startup_exit_report_check: ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/startup_flat_param.cpp b/tests/startup_flat_param.cpp index 2fc2ae2471..7c92eb02b8 100644 --- a/tests/startup_flat_param.cpp +++ b/tests/startup_flat_param.cpp @@ -3,7 +3,7 @@ // Draws one pixel with a translated vertex and pixel stage and returns the four 32-bit words of // the colour. The entry constants (cbuffer entry : register(b0)) are visible to both stages, because // the translated vertex stage reads ud0, the rectangle-list switch; they are all 0 here (plain -// triangles). The target is R32G32B32A32_FLOAT, so the readback is the raw words the pixel stage +// triangles) unless the caller passes four words. The target is R32G32B32A32_FLOAT, so the readback is the raw words the pixel stage // exported. #include "desktop_gpu.h" @@ -33,7 +33,8 @@ std::vector<char> read_blob(const char* path) void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, std::uint32_t* words, UINT width, UINT height, - D3D12_CULL_MODE cull, BOOL front_ccw, UINT vertices) + D3D12_CULL_MODE cull, BOOL front_ccw, UINT vertices, + const std::uint32_t* constants) { const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); @@ -96,8 +97,8 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con auto* list = commands.list.Get(); list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); list->SetGraphicsRootSignature(root.Get()); - const std::uint32_t constants[entry_constants] = {0, 0, 0, 0}; - list->SetGraphicsRoot32BitConstants(0, entry_constants, constants, 0); + const std::uint32_t zeros[entry_constants] = {0, 0, 0, 0}; + list->SetGraphicsRoot32BitConstants(0, entry_constants, constants ? constants : zeros, 0); const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; const D3D12_RECT scissor{0, 0, static_cast<LONG>(width), static_cast<LONG>(height)}; list->RSSetViewports(1, &viewport); diff --git a/tests/startup_flat_param_check.py b/tests/startup_flat_param_check.py index 7d985166e1..b4b6808bd0 100644 --- a/tests/startup_flat_param_check.py +++ b/tests/startup_flat_param_check.py @@ -29,7 +29,10 @@ HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) import gfx2hlsl as G # noqa: E402 +import dxc_cache # noqa: E402 +import gpu_case_runner # noqa: E402 VS_SOURCE = """\ v_mov_b32 v3, 0x40400000 @@ -216,13 +219,14 @@ def compile_hlsl(compiler, kind, source, out, profile, directory): args = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', str(directory / ('%s.cso' % out)), str(path)] else: args = [compiler, '-T', profile, '-E', 'main', '-Fo', str(directory / ('%s.cso' % out)), str(path)] - subprocess.run(args, check=True, capture_output=True, text=True) + # DXC compiles go through the opt-in X2W_DXC_CACHE cache (tools/dxc_cache.py); FXC compiles and everything else are untouched. + dxc_cache.with_dxc_cache(subprocess).run(args, check=True, capture_output=True, text=True) return directory / ('%s.cso' % out) def draw(renderer, adapter, vs, ps, expected): - run = subprocess.run([renderer, adapter, '--startup-flat-param', str(vs), str(ps), expected], - capture_output=True, text=True) + # One long-lived offscreen_check per test (one D3D12 device); the one-shot call stays as the fallback. + run = gpu_case_runner.run(renderer, adapter, ['--startup-flat-param', vs, ps, expected]) sys.stdout.write(run.stdout) if run.returncode == 77: print(run.stdout + run.stderr) diff --git a/tests/startup_gameinput_contracts_check.cpp b/tests/startup_gameinput_contracts_check.cpp index ef56832b4f..780843e1d0 100644 --- a/tests/startup_gameinput_contracts_check.cpp +++ b/tests/startup_gameinput_contracts_check.cpp @@ -37,7 +37,7 @@ struct GamepadState { static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); struct IGameInputDevice { - const void* const* vtbl; + void* const* vtbl; HRESULT QueryInterface(const GUID* iid, void** out) { @@ -72,7 +72,7 @@ struct IGameInputDevice { }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; HRESULT QueryInterface(const GUID* iid, void** out) { @@ -131,7 +131,7 @@ using DeviceCallback = void(__stdcall*)(std::uint64_t token, void* context, IGam std::uint32_t previousStatus); struct IGameInput { - const void* const* vtbl; + void* const* vtbl; HRESULT QueryInterface(const GUID* iid, void** out) { diff --git a/tests/startup_gameinput_history.cpp b/tests/startup_gameinput_history.cpp index 8afd0caa16..bf311a7a33 100644 --- a/tests/startup_gameinput_history.cpp +++ b/tests/startup_gameinput_history.cpp @@ -32,11 +32,11 @@ struct PadShared { }; struct IGameInputDevice { - const void* const* vtbl; + void* const* vtbl; }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { @@ -61,7 +61,7 @@ struct IGameInputReading { }; struct IGameInput { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { diff --git a/tests/startup_gameinput_keys.cpp b/tests/startup_gameinput_keys.cpp index b25ea7acff..610f9c739b 100644 --- a/tests/startup_gameinput_keys.cpp +++ b/tests/startup_gameinput_keys.cpp @@ -40,11 +40,11 @@ static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); // Minimal vtable-matching C++ views of GameInput v0 COM interfaces. struct IGameInputDeviceVtbl; struct IGameInputDevice { - const void* const* vtbl; + void* const* vtbl; }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t AddRef() { @@ -93,7 +93,7 @@ using DeviceCallback = void(__stdcall*)(std::uint64_t token, void* context, IGam std::uint32_t previousStatus); struct IGameInput { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { diff --git a/tests/startup_gameinput_script.cpp b/tests/startup_gameinput_script.cpp index b7b861256f..fc861e3fd2 100644 --- a/tests/startup_gameinput_script.cpp +++ b/tests/startup_gameinput_script.cpp @@ -27,7 +27,7 @@ static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); struct IGameInputDevice; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { @@ -42,7 +42,7 @@ struct IGameInputReading { }; struct IGameInput { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { diff --git a/tests/startup_gameinput_script_syntax.cpp b/tests/startup_gameinput_script_syntax.cpp index 45abfa578a..5edf5eede2 100644 --- a/tests/startup_gameinput_script_syntax.cpp +++ b/tests/startup_gameinput_script_syntax.cpp @@ -43,7 +43,7 @@ struct PadShared { }; struct IGameInputReading { - const void* const* vtbl; + void* const* vtbl; std::uint32_t Release() { using Fn = std::uint64_t(__stdcall*)(IGameInputReading*); @@ -56,7 +56,7 @@ struct IGameInputReading { } }; struct IGameInput { - const void* const* vtbl; + void* const* vtbl; HRESULT GetCurrentReading(std::uint32_t kind, void* device, IGameInputReading** reading) { using Fn = HRESULT(__stdcall*)(IGameInput*, std::uint32_t, void*, IGameInputReading**); @@ -192,6 +192,9 @@ void check_rejections() {"ly=0.5", 0, 1, "missing @<seconds>"}, {"4@1,base=start", 1, 2, "base= must be the first item"}, {"base=later,4@1", 1, 1, "unknown base (use poll or start)"}, + {"2@1e999", 0, 1, "bad time"}, + {"1@+1e308,2@+1e308", 1, 2, "bad time"}, + {"1@1e308,2@+1e308", 1, 2, "bad time"}, }; for (const Case& c : cases) { const x2w_input_script::Script s = x2w_input_script::parse(c.script); @@ -381,6 +384,11 @@ void check_timeline() close_to(s.entries[4].at, 3.0), "relative times follow the previous item's start"); } + // A large but finite relative time is still the exact sum. + { + const tl::Script s = tl::parse("1@1e300,2@+1e300"); + check(s.entries.size() == 2 && s.rejections.empty() && s.entries[1].at == 1e300 + 1e300, "large finite relative time is the exact sum"); + } // Rejections of the new items. { struct Case { @@ -398,6 +406,8 @@ void check_timeline() {"mark=a b", 1, "bad label"}, {"4@+-1", 1, "bad time"}, {"wait@5,mark@4", 2, "time before the preceding wait"}, + {"1@1e308,wait@+1e308", 2, "bad time"}, + {"1@1e308,mark@+1e308", 2, "bad time"}, }; for (const Case& c : cases) { const tl::Script s = tl::parse(c.script); diff --git a/tests/startup_gameinput_trace.cpp b/tests/startup_gameinput_trace.cpp new file mode 100644 index 0000000000..3366474927 --- /dev/null +++ b/tests/startup_gameinput_trace.cpp @@ -0,0 +1,317 @@ +// Checks the opt-in GameInput input trace (X2W_INPUT_TRACE=1). A child process plays one +// X2W_INPUT_SCRIPT through IGameInput::GetCurrentReading with X2W_INPUT_CLOCK_MS; the parent runs +// the same child with the switch on and off, so the control proves that the default path logs no +// x2w-input-trace line and still observes the same gamepad states. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include "startup_stubs/present_signature.h" + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <string> + +namespace { + +constexpr std::uint32_t kind_gamepad = 0x00040000; +constexpr std::uint32_t button_a = 0x4; +constexpr const char* trace_prefix = "x2w-input-trace"; + +struct GamepadState { + std::uint32_t buttons; + float leftTrigger, rightTrigger, leftThumbstickX, leftThumbstickY, rightThumbstickX, rightThumbstickY; +}; +static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); + +struct PadShared { + std::uint32_t magic, buttons, title_read, reads; +}; + +struct IGameInputReading { + const void* const* vtbl; + std::uint32_t Release() + { + using Fn = std::uint64_t(__stdcall*)(IGameInputReading*); + return static_cast<std::uint32_t>(reinterpret_cast<Fn>(vtbl[2])(this)); + } + bool GetGamepadState(GamepadState* state) + { + using Fn = bool(__stdcall*)(IGameInputReading*, GamepadState*); + return reinterpret_cast<Fn>(vtbl[22])(this, state); + } +}; + +struct IGameInput { + const void* const* vtbl; + std::uint32_t Release() + { + using Fn = std::uint64_t(__stdcall*)(IGameInput*); + return static_cast<std::uint32_t>(reinterpret_cast<Fn>(vtbl[2])(this)); + } + HRESULT GetCurrentReading(std::uint32_t kind, void* device, IGameInputReading** reading) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, std::uint32_t, void*, IGameInputReading**); + return reinterpret_cast<Fn>(vtbl[4])(this, kind, device, reading); + } +}; + +int failures = 0; + +void check(bool ok, const char* what) +{ + if (ok) return; + ++failures; + std::printf("FAIL: %s\n", what); +} + +void clear_shared_pad() +{ + HANDLE mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(PadShared), L"Local\\x2w_input_pad"); + if (auto* shared = mapping ? static_cast<PadShared*>(MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(PadShared))) : nullptr) + shared->buttons = 0; +} + +std::string read_log(const std::string& path) +{ + std::string text; + if (FILE* file = std::fopen(path.c_str(), "rb")) { + char buffer[4096]; + for (std::size_t n; (n = std::fread(buffer, 1, sizeof(buffer), file)) > 0;) text.append(buffer, n); + std::fclose(file); + } + return text; +} + +std::size_t count(const std::string& text, const char* needle) +{ + std::size_t found = 0; + for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++found; + return found; +} + +bool same_state(const GamepadState& state, std::uint32_t buttons, float lt, float rt, float lx, float ly, float rx, float ry) +{ + return state.buttons == buttons && state.leftTrigger == lt && state.rightTrigger == rt && state.leftThumbstickX == lx && + state.leftThumbstickY == ly && state.rightThumbstickX == rx && state.rightThumbstickY == ry; +} + +bool expected_at(int ms, GamepadState& want) +{ + want = {}; + if (ms >= 2000 && ms < 2500) { + want.buttons = button_a; + } else if (ms >= 2500 && ms < 3000) { + want.leftThumbstickX = 1.0f; + want.leftThumbstickY = 0.5f; + } else if (ms >= 3000 && ms < 3500) { + want.leftThumbstickX = 1.0f; + } else if (ms >= 3600 && ms < 3700) { + want.buttons = 0x8; // B press, shorter than the 250 ms trace heartbeat and off its grid + } + return true; +} + +bool read_at(IGameInput* input, int ms, GamepadState& state) +{ + char text[24]; + std::snprintf(text, sizeof(text), "%d", ms); + SetEnvironmentVariableA("X2W_INPUT_CLOCK_MS", text); + IGameInputReading* reading = nullptr; + const HRESULT hr = input->GetCurrentReading(kind_gamepad, nullptr, &reading); + bool ok = SUCCEEDED(hr) && reading && reading->GetGamepadState(&state); + if (reading) reading->Release(); + return ok; +} + +bool xinput_pad_connected() +{ + struct State { + DWORD packet; + BYTE pad[12]; + }; + HMODULE module = LoadLibraryW(L"xinput1_4.dll"); + if (!module) return false; + using Fn = DWORD(WINAPI*)(DWORD, State*); + const auto get = reinterpret_cast<Fn>(GetProcAddress(module, "XInputGetState")); + State state{}; + return get && get(0, &state) == 0; +} + +// The script starts with a mark and a wait, then presses A and moves the left stick. The wait +// completes 1.5 s after the child publishes a new picture at 1.0 s; the entries that follow are +// shifted to 2.0, 2.5, 3.0 and 3.5 s. +constexpr const char* script_text = + "mark=start@0,wait=0.5/2,4@+0.5+0.5,lx=1@+0.5+1,mark=turn@+0,ly=0.5@+0+0.5,8@+1.1+0.1"; + +int run_child(const char* dll, bool trace) +{ + clear_shared_pad(); + SetEnvironmentVariableA("X2W_INPUT_PRESS", nullptr); + SetEnvironmentVariableA("X2W_INPUT_KEYS", nullptr); + + x2w_present_signature::Block* block = x2w_present_signature::create_block(GetCurrentProcessId(), 4); + if (!block) { + std::printf("child: create_block failed\n"); + return 2; + } + std::uint8_t first[x2w_present_signature::cells], second[x2w_present_signature::cells]; + std::memset(first, 40, sizeof(first)); + std::memset(second, 200, sizeof(second)); + x2w_present_signature::publish(block, first, 10); + x2w_present_signature::note_present(block, 10); + + HMODULE module = LoadLibraryA(dll); + if (!module) { + std::printf("child: LoadLibraryA(%s) failed: %lu\n", dll, GetLastError()); + return 2; + } + using CreateFn = HRESULT(__stdcall*)(IGameInput**); + const auto create = reinterpret_cast<CreateFn>(GetProcAddress(module, "GameInputCreate")); + IGameInput* input = nullptr; + if (!create || FAILED(create(&input)) || !input) { + std::printf("child: GameInputCreate failed\n"); + FreeLibrary(module); + return 2; + } + + for (int ms = 0; ms <= 4000; ms += 50) { + if (ms == 1000) { + x2w_present_signature::publish(block, second, 11); + x2w_present_signature::note_present(block, 11); + } + GamepadState state{}; + if (!read_at(input, ms, state)) { + std::printf("child: GetCurrentReading failed at %d ms\n", ms); + ++failures; + break; + } + GamepadState want{}; + expected_at(ms, want); + if (!same_state(state, want.buttons, want.leftTrigger, want.rightTrigger, want.leftThumbstickX, want.leftThumbstickY, + want.rightThumbstickX, want.rightThumbstickY)) { + std::printf("child: %s at %d ms: buttons 0x%x lt %g rt %g lx %g ly %g rx %g ry %g\n", trace ? "trace" : "control", + ms, state.buttons, state.leftTrigger, state.rightTrigger, state.leftThumbstickX, state.leftThumbstickY, + state.rightThumbstickX, state.rightThumbstickY); + ++failures; + break; + } + } + input->Release(); + FreeLibrary(module); + + char log_path[MAX_PATH]{}; + const DWORD log_length = GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, MAX_PATH); + if (!log_length || log_length >= MAX_PATH) { + std::printf("child: X2W_TRAP_LOG missing\n"); + return 2; + } + const std::string log = read_log(log_path); + if (trace) { + const char* const state_line = + "x2w-input-trace state buttons=0x00000004 lt=0.000 rt=0.000 lx=0.000 ly=0.000 rx=0.000 ry=0.000 " + "script=2.000 present=11"; + const char* const stick_line = + "x2w-input-trace state buttons=0x00000000 lt=0.000 rt=0.000 lx=1.000 ly=0.500 rx=0.000 ry=0.000 " + "script=2.500 present=11"; + const char* const b_line = + "x2w-input-trace state buttons=0x00000008 lt=0.000 rt=0.000 lx=0.000 ly=0.000 rx=0.000 ry=0.000 " + "script=3.600 present=11"; + check(count(log, state_line) == 1, "trace: A press line with script time 2.000 and present 11"); + check(count(log, stick_line) == 1, "trace: left stick and Y axis line at script time 2.500"); + check(count(log, b_line) == 1, "trace: off-grid B press line at script time 3.600"); + check(count(log, "x2w-input-trace wait event=begun item=2 at=0.000 elapsed=0.000 signal=1") == 1, + "trace: wait begun line"); + check(count(log, "x2w-input-trace wait event=changed item=2 at=1.000 elapsed=1.000 signal=1") == 1, + "trace: wait changed line"); + check(count(log, "x2w-input-trace wait event=done item=2 at=1.500 elapsed=1.500 signal=1") == 1, + "trace: wait done line"); + check(count(log, "x2w-input-trace mark label=start item=1 at=0.000 present=10") == 1, "trace: start mark line"); + check(count(log, "x2w-input-trace mark label=turn item=5 at=2.500 present=11") == 1, "trace: turn mark line"); + check(count(log, "x2w-input-trace wait event=timeout") == 0, "trace: no timeout line"); + const std::size_t states = count(log, "x2w-input-trace state "); + check(states >= 12 && states <= 21, "trace: bounded state lines (12..21 in four seconds)"); + } else { + check(count(log, trace_prefix) == 0, "control: no x2w-input-trace line without the switch"); + check(count(log, "x2w-input script mark start at 0.000 s (item 1, present 10)") == 1, + "control: the script and its ordinary log still run"); + } + return failures ? 1 : 0; +} + +std::string temp_log_path(const char* suffix) +{ + char temp[MAX_PATH]; + GetTempPathA(MAX_PATH, temp); + return std::string(temp) + "x2w_gameinput_trace_" + suffix + "_" + std::to_string(GetCurrentProcessId()) + ".log"; +} + +int run_mode(const char* self, const char* dll, bool trace) +{ + const std::string log_path = temp_log_path(trace ? "on" : "off"); + DeleteFileA(log_path.c_str()); + SetEnvironmentVariableA("X2W_TRAP_LOG", log_path.c_str()); + SetEnvironmentVariableA("X2W_INPUT_TRACE", trace ? "1" : "0"); + SetEnvironmentVariableA("X2W_INPUT_SCRIPT", script_text); + clear_shared_pad(); + + const std::string command = std::string("\"") + self + "\" \"" + dll + "\" child " + (trace ? "trace" : "control"); + STARTUPINFOA startup{sizeof(startup)}; + PROCESS_INFORMATION process{}; + if (!CreateProcessA(nullptr, const_cast<char*>(command.c_str()), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, + &process)) { + std::printf("CreateProcess(%s) failed: %lu\n", trace ? "trace" : "control", GetLastError()); + return 2; + } + DWORD code = 1; + if (WaitForSingleObject(process.hProcess, 60000) != WAIT_OBJECT_0) { + TerminateProcess(process.hProcess, 1); + std::printf("%s child timed out\n", trace ? "trace" : "control"); + } + GetExitCodeProcess(process.hProcess, &code); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + if (code != 0) { + const std::string log = read_log(log_path); + std::printf("%s child failed (exit %lu), log follows:\n%.4000s\n", trace ? "trace" : "control", code, log.c_str()); + DeleteFileA(log_path.c_str()); + return 1; + } + std::printf("PASS: startup_gameinput_trace %s\n", trace ? "trace" : "control"); + DeleteFileA(log_path.c_str()); + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) { + std::printf("usage: startup_gameinput_trace <GameInput.dll> [child trace|control]\n"); + return 2; + } + if (argc >= 4 && std::strcmp(argv[2], "child") == 0) { + if (std::strcmp(argv[3], "trace") != 0 && std::strcmp(argv[3], "control") != 0) { + std::printf("unknown child mode %s\n", argv[3]); + return 2; + } + return run_child(argv[1], std::strcmp(argv[3], "trace") == 0); + } + if (xinput_pad_connected()) { + std::printf("SKIP: XInput pad 0 is connected; its values merge into every reading\n"); + return 77; + } + char self[MAX_PATH]{}; + if (!GetModuleFileNameA(nullptr, self, MAX_PATH)) { + std::printf("GetModuleFileNameA failed: %lu\n", GetLastError()); + return 2; + } + int status = run_mode(self, argv[1], true); + if (!status) status = run_mode(self, argv[1], false); + return status ? status : (failures ? 1 : 0); +} diff --git a/tests/startup_gamesave_submit.cpp b/tests/startup_gamesave_submit.cpp index 09f83f42ac..687b361a37 100644 --- a/tests/startup_gamesave_submit.cpp +++ b/tests/startup_gamesave_submit.cpp @@ -2,7 +2,23 @@ // XAsync service can reject Begin, delay notification or enter the callback inline. #include "../src/startup_stubs/runtime_proxy.cpp" #include <array> +#include <atomic> #include <condition_variable> +#include <cstdio> +#include <cstdlib> + +static std::atomic<std::size_t> fail_allocation_size{0}; +void* operator new(std::size_t size) +{ + std::size_t expected = size; + if (size && fail_allocation_size.compare_exchange_strong(expected, 0)) { + throw std::bad_alloc(); + } + if (void* p = std::malloc(size ? size : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } namespace { using Provider = decltype(&submit_provider); @@ -92,6 +108,38 @@ int run(bool system) call(16,provider_handle,ptr("profile"),ptr(&container)) || call(23,container,0,ptr(&good)) || call(23,container,0,ptr(&bad))) return 1; unsigned char byte=0x11; + const std::string long_name(80, 'c'); + const std::string name_copy(long_name); + const std::size_t name_allocation = name_copy.capacity() + 1; + fail_allocation_size = name_allocation; + if (!x2w_save::valid_name(long_name) || fail_allocation_size != name_allocation) return 26; + fail_allocation_size = 0; + u64 long_container{}, long_update{}; + if (call(16,provider_handle,ptr(long_name.c_str()),ptr(&long_container)) || + call(23,long_container,0,ptr(&long_update))) return 22; + fail_allocation_size = name_allocation; // Fail the same string copy under save_lock. + const u64 name_copy_result = call(25,long_update,ptr("preference"),ptr(&byte),1); + if (fail_allocation_size || name_copy_result != e_outofmemory) return 23; + if (!TryAcquireSRWLockExclusive(&save_lock)) return 24; + ReleaseSRWLockExclusive(&save_lock); + if (call(25,long_update,ptr("preference"),ptr(&byte),1) || call(27,long_update)) return 25; + call(24,long_update); + call(17,long_container); + const std::array<unsigned char, 1025> large_blob{}; + for (const auto data_size : {std::size_t{1}, large_blob.size()}) { + fail_allocation_size = data_size == 1 ? sizeof(x2w_save::Action) : data_size; + u64 failed_stage{}; + try { + failed_stage = call(25,good,ptr("preference"),ptr(large_blob.data()),data_size); + } catch (const std::bad_alloc&) { + return 20; + } + if (fail_allocation_size || failed_stage != e_outofmemory) { + std::fprintf(stderr, "staging %zu bytes: pending allocation=%zu, HRESULT=0x%08llx\n", + data_size, fail_allocation_size.load(), static_cast<unsigned long long>(failed_stage)); + return 21; + } + } if (call(25,good,ptr("preference"),ptr(&byte),1) || call(27,good) || value()!=0x11) return 2; byte=0x77; if (call(25,good,ptr("preference"),ptr(&byte),1) || call(26,bad,ptr("absent"))) return 3; diff --git a/tests/startup_gather_implicit_mip_check.py b/tests/startup_gather_implicit_mip_check.py new file mode 100644 index 0000000000..57973078cb --- /dev/null +++ b/tests/startup_gather_implicit_mip_check.py @@ -0,0 +1,89 @@ +"""Differential for gathering at a derivative-selected mip in a nonzero-base SRV.""" +import math +from pathlib import Path +import struct +import sys +import tempfile + +import startup_image_gather_lz_check as gather +from startup_image_3d_check import FULLSCREEN_VS, compile_hlsl +from startup_image_get_lod_view_check import UNPACK_XY, read_pixel + +VIEW = '1/2' +MIP_BASE = 8 +UV = 0.5625 +LOD_QUERY = struct.pack('<II', 0xF1800108, 0x00C40200) # image_get_lod v2, v[0:1], ... dmask:1 +WAIT_IMAGE = gather.SUFFIX[:4] +TAPS = ((0, 1), (1, 1), (1, 0), (0, 0)) + + +def float_op(op, dst, value): + # VOP2 with a literal source and the same VGPR as the other source. + return struct.pack('<If', op << 25 | dst << 17 | dst << 9 | 255, value) + + +def prefix(step): + # Same UV at the readback pixel for both cases. The derivative of the + # window-relative UV changes from 1 to 2 texels per pixel. + before, original, after = gather.PREFIX.partition(bytes.fromhex('f002007eff02027e0000803e')) + assert original + before = before.replace(bytes.fromhex('800399be'), struct.pack('<II', 0xBE9903FF, 2 << 20)) + xy = UNPACK_XY + b''.join(float_op(0x08, axis, step) + float_op(0x03, axis, UV) for axis in range(2)) + return before + xy + after + + +def pipeline(step, selected): + lead = prefix(step) + if selected: + # Pass the image_get_lod result in v2 to the existing explicit gather. + lead += LOD_QUERY + WAIT_IMAGE + code = gather.shader(prefix=lead, opcode=0x44 if selected else 0x47) + return gather.G.Pipeline(gather.VS_WORDS, code, gather.root_blob(flags=0), ps_hw_inputs=(0x8000, 0x8000)) + + +def render(dxc, renderer, adapter, vs, pipe, name, view, work): + sampler, = (line for line in pipe.manifest().splitlines() if line.startswith(('smp ', 'smpl '))) + ps = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), name, 'ps_6_0', work) + return struct.unpack('>4f', read_pixel(renderer, adapter, vs, ps, sampler, view, mip_base=MIP_BASE)) + + +def expected_taps(resource_mip): + # Both visible levels contain four different interior taps. + extent = MIP_BASE >> resource_mip + origin = math.floor(UV * extent - 0.5) + assert 0 <= origin < extent - 1 + area = MIP_BASE ** 2 + return tuple((1 + origin + x + MIP_BASE * (origin + y) + 2 * area * resource_mip) / (8 * area) + for x, y in TAPS) + + +def expect(label, observed, wanted): + for tap, (actual, expected) in enumerate(zip(observed, wanted, strict=True)): + assert actual == expected, f'{label}, pixel (0,0), tap {tap}: expected {expected}, got {actual}' + + +def main(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', work) + for step, relative_mip in ((0.25, 0), (0.5, 1)): + resource_mip = 1 + relative_mip + selected = pipeline(step, selected=True) + fixed = pipeline(step, selected=False) + wanted = expected_taps(resource_mip) + prefix_name = f'level{relative_mip}' + actual = render(dxc, renderer, adapter, vs, selected, prefix_name, VIEW, work) + expect(prefix_name, actual, wanted) + oracle = render(dxc, renderer, adapter, vs, fixed, prefix_name + '_fixed', f'{resource_mip}/1', work) + expect(prefix_name + ' fixed-view oracle', oracle, wanted) + first = render(dxc, renderer, adapter, vs, fixed, prefix_name + '_first', VIEW, work) + expect(prefix_name + ' first-visible control', first, expected_taps(1)) + assert (first == actual) == (relative_mip == 0), (step, first, actual) + print(f'view={VIEW} step={step} relative_mip={relative_mip} resource_mip={resource_mip} taps={actual}') + if relative_mip: + print('the first-visible control differed at all four taps') + assert all(a != b for a, b in zip(first, actual, strict=True)) + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/startup_gfx10_layout_check.cpp b/tests/startup_gfx10_layout_check.cpp index 81a1ccc77b..4ea0f8d657 100644 --- a/tests/startup_gfx10_layout_check.cpp +++ b/tests/startup_gfx10_layout_check.cpp @@ -3,6 +3,8 @@ // tables (written out below as the nibbles those rows name), for six swizzle modes and five element sizes; // - agreement with the three narrower layouts already in the tree (bc7_4k_s.h, bc64_chain.h, tile64_plan.h); // - the mip offsets docs/experiments.md records for a 1024x1024 six-mip BC7 chain; +// - the linear mode (0x100): mip offsets worked out by hand from addrlib's HwlComputeSurfaceInfoLinear, +// and, with --addrlib, every element address of several linear textures against addrlib itself; // - that every element of every subresource gets its own bytes inside the texture, and that a // tile followed by a detile returns the rows it started from. // @@ -47,6 +49,13 @@ D3D12_RESOURCE_DESC texture(UINT width, UINT height, UINT mips, UINT slices, DXG return d; } +D3D12_RESOURCE_DESC texture_1d(UINT width, UINT mips, UINT slices, DXGI_FORMAT format, UINT layout) +{ + D3D12_RESOURCE_DESC d = texture(width, 1, mips, slices, format, layout); + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + return d; +} + // One format per element size: 1, 2, 4, 8 and 16 bytes. constexpr DXGI_FORMAT by_size[5] = {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT}; @@ -160,16 +169,20 @@ void check_tile64() void check_distinct_and_round_trip() { - struct Shape { UINT width, height, mips, slices; DXGI_FORMAT format; UINT layout; }; + struct Shape { UINT width, height, mips, slices; DXGI_FORMAT format; UINT layout; bool one_d = false; }; const Shape shapes[] = { {1000, 520, 10, 1, DXGI_FORMAT_BC1_UNORM, 0x105}, {300, 200, 9, 2, DXGI_FORMAT_R8_UNORM, 0x109}, {512, 1056, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105}, {1024, 2112, 1, 1, DXGI_FORMAT_R16_UNORM, 0x105}, {640, 360, 10, 1, DXGI_FORMAT_BC7_UNORM, 0x10a}, {257, 129, 9, 3, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106}, {96, 40, 1, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, 0x102}, {4, 4, 3, 1, DXGI_FORMAT_BC3_UNORM, 0x109}, {2048, 2048, 12, 1, DXGI_FORMAT_BC5_UNORM, 0x109}, + {100, 10, 3, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, 0x100}, {257, 129, 9, 2, DXGI_FORMAT_R8_UNORM, 0x100}, + {256, 256, 7, 1, DXGI_FORMAT_R32_FLOAT, 0x100}, {64, 64, 4, 3, DXGI_FORMAT_BC1_UNORM, 0x100}, + {300, 1, 9, 1, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 0x100, true}, {4096, 1, 13, 1, DXGI_FORMAT_R8_UNORM, 0x100, true}, }; for (const Shape& s : shapes) { - const D3D12_RESOURCE_DESC d = texture(s.width, s.height, s.mips, s.slices, s.format, s.layout); + const D3D12_RESOURCE_DESC d = s.one_d ? texture_1d(s.width, s.mips, s.slices, s.format, s.layout) + : texture(s.width, s.height, s.mips, s.slices, s.format, s.layout); const std::string name = std::to_string(s.width) + "x" + std::to_string(s.height) + " layout " + std::to_string(s.layout); if (!x2w_startup::gfx10::supports(d)) { fail(name + ": refused"); @@ -210,16 +223,41 @@ void check_refusals() }; D3D12_RESOURCE_DESC d = good; d.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; refused("desktop layout", d); - d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100); refused("linear mode", d); + d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x100); d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + refused("linear volume", d); d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x115); refused("XOR mode", d); d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x209); refused("layout outside 0x1xx", d); - d = good; d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; refused("volume", d); + d = good; d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x109); refused("volume outside 0x105", d); d = good; d.SampleDesc.Count = 4; refused("multisampled", d); d = good; d.Format = DXGI_FORMAT_R32G32B32_FLOAT; refused("12-byte texels", d); d = good; d.MipLevels = 16; refused("16 mips", d); d = good; d.Width = 16385; refused("too wide", d); d = good; d.DepthOrArraySize = 0; refused("no slices", d); d = good; d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x101); d.MipLevels = 2; refused("256 B chain", d); + if (!x2w_startup::gfx10::supports(texture_1d(300, 9, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100))) + fail("linear 1D RGBA8 chain refused"); + refused("1D in a 4 KiB swizzle mode", texture_1d(256, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x105)); + d = texture_1d(256, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100); d.Height = 2; refused("1D two rows high", d); + refused("1D block-compressed", texture_1d(256, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x100)); + refused("1D array", texture_1d(256, 1, 2, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100)); +} + +// The linear mode by hand: a 100x10 R16G16B16A16 texture with three mips. Each mip's pitch is its +// rounded-up width aligned to 32 elements (256 bytes), and the mips are stored from the smallest up: +// mip 2 is 32x3 elements at 0, mip 1 64x5 at 768, mip 0 128x10 at 3328, 13568 bytes a slice. +// The mutated run expects the largest mip first and is a negative control. +void check_linear(bool largest_first) +{ + const Layout l(texture(100, 10, 3, 2, DXGI_FORMAT_R16G16B16A16_FLOAT, 0x100)); + const std::uint64_t start[3] = {largest_first ? 0u : 3328u, largest_first ? 10240u : 768u, largest_first ? 12800u : 0u}; + const UINT pitch[3] = {128, 64, 32}; + if (!l.is_linear || l.first_tail != 3 || l.slice_size != 13568 || l.bytes() != 2 * 13568) fail("linear: slice size"); + for (UINT mip = 0; mip < 3; ++mip) { + if (l.start[mip] != start[mip] || l.row_pitch[mip] != pitch[mip]) fail("linear: mip " + std::to_string(mip)); + const std::uint64_t want = 13568 + start[mip] + (2ull * pitch[mip] + 3) * 8; + if (l.address(mip, 3, 2, 1) != want) fail("linear: element (3, 2) of slice 1, mip " + std::to_string(mip)); + } } // Which slot-70 descriptions are taken, and how their texels are read (address_texture.h). @@ -238,16 +276,19 @@ void check_address_textures() expect("not sampled", d, false); expect("64 KiB display R16 chain", texture(512, 512, 10, 1, DXGI_FORMAT_R16_UNORM, 0x10a), true); expect("desktop layout RGBA8", texture(1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0), false); - expect("linear mode R8", texture(256, 128, 1, 1, DXGI_FORMAT_R8_UNORM, 0x100), false); + expect("linear mode R8", texture(256, 128, 1, 1, DXGI_FORMAT_R8_UNORM, 0x100), true); + expect("linear 1D RGBA8 sRGB", texture_1d(512, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 0x100), true); + expect("linear 1D array", texture_1d(512, 1, 4, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100), false); + expect("desktop layout 1D", texture_1d(512, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0), false); expect("XOR mode", texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x119), false); expect("row-major desktop layout", texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 1), false); expect("unknown element size", texture(256, 256, 1, 1, DXGI_FORMAT_R32G32B32_FLOAT, 0), false); d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105); d.SampleDesc.Count = 2; expect("multisampled", d, false); - d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x105); + d = texture(256, 256, 1, 1, DXGI_FORMAT_BC7_UNORM, 0x109); d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; - expect("volume", d, false); + expect("volume outside 0x105", d, false); expect("BC1 width not whole blocks", texture(126, 128, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x105), false); expect("BC1 height not whole blocks", texture(128, 126, 1, 1, DXGI_FORMAT_BC1_UNORM, 0x10a), false); expect("RGBA8 odd sides", texture(257, 129, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106), true); @@ -321,17 +362,183 @@ void check_address_textures() v.Texture3D.MipLevels = 4; v.Texture3D.ResourceMinLODClamp = 1.0f; if (x2w_startup::address_view_fits(vol, v)) fail("3D volume view explicit LOD clamp"); + + const D3D12_RESOURCE_DESC row = texture_1d(300, 9, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100); + v = {}; + v.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + v.Texture1D.MipLevels = 9; + if (!x2w_startup::address_view_fits(row, v)) fail("whole 1D chain view"); + v.Texture1D.MostDetailedMip = 8; + v.Texture1D.MipLevels = 1; + if (!x2w_startup::address_view_fits(row, v)) fail("last 1D mip view"); + v.Texture1D.MipLevels = 2; + if (x2w_startup::address_view_fits(row, v)) fail("1D view past the chain"); + v.Texture1D.MostDetailedMip = 0; + v.Texture1D.MipLevels = 1; + v.Texture1D.ResourceMinLODClamp = 1.0f; + if (x2w_startup::address_view_fits(row, v)) fail("1D view explicit LOD clamp"); + v.Texture1D.ResourceMinLODClamp = 0.0f; + if (x2w_startup::address_view_fits(texture(300, 1, 9, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100), v)) + fail("1D view on a 2D texture"); + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Texture2D.MipLevels = 1; + if (x2w_startup::address_view_fits(row, v)) fail("2D view on a 1D texture"); + + const D3D12_RESOURCE_DESC faces = texture(64, 64, 4, 6, DXGI_FORMAT_BC1_UNORM, 0x105); + v = {}; + v.Format = DXGI_FORMAT_BC1_UNORM; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + v.TextureCube.MipLevels = 4; + if (!x2w_startup::address_view_fits(faces, v)) fail("whole cube chain view"); + v.TextureCube.MostDetailedMip = 3; + v.TextureCube.MipLevels = 1; + if (!x2w_startup::address_view_fits(faces, v)) fail("last cube mip view"); + v.TextureCube.MipLevels = 2; + if (x2w_startup::address_view_fits(faces, v)) fail("cube view past the chain"); + v.TextureCube.MostDetailedMip = 0; + v.TextureCube.MipLevels = 1; + v.TextureCube.ResourceMinLODClamp = 1.0f; + if (x2w_startup::address_view_fits(faces, v)) fail("cube view explicit LOD clamp"); + v.TextureCube.ResourceMinLODClamp = 0.0f; + if (x2w_startup::address_view_fits(texture(64, 64, 4, 1, DXGI_FORMAT_BC1_UNORM, 0x105), v)) + fail("cube view on a single slice"); + if (x2w_startup::address_view_fits(texture(64, 64, 4, 12, DXGI_FORMAT_BC1_UNORM, 0x105), v)) + fail("cube view on an array of twelve"); +} +} // namespace + +#ifndef XBOX2WINDOWS_HAVE_ADDRLIB +int addrlib_linear_check() +{ + std::puts("startup_gfx10_layout --addrlib: SKIP (built without addrlib; run tools/fetch_addrlib.py and configure with " + "-DXBOX2WINDOWS_ADDRLIB_DIR=<mesa>/src/amd/addrlib)"); + return 77; +} +#else +#include "addrinterface.h" + +namespace { +VOID* ADDR_API alloc_sys_mem(const ADDR_ALLOCSYSMEM_INPUT* in) { return std::malloc(in->sizeInBytes); } +ADDR_E_RETURNCODE ADDR_API free_sys_mem(const ADDR_FREESYSMEM_INPUT* in) +{ + std::free(in->pVirtAddr); + return ADDR_OK; } } // namespace +// Every element of every subresource of several linear textures, and their sizes, against +// Addr2ComputeSurfaceAddrFromCoord and Addr2ComputeSurfaceInfo with ADDR_SW_LINEAR on Mesa's "navi21" +// (gfx10.3) configuration, the one xg_swizzle_select_check uses: family 0x8F, revision 0x28, +// GB_ADDR_CONFIG 0x444. Sizes are given to addrlib in elements, so a BC texture is its 4x4 blocks. +int addrlib_linear_check() +{ + ADDR_CREATE_INPUT create{}; + ADDR_CREATE_OUTPUT created{}; + create.size = sizeof create; + created.size = sizeof created; + create.chipEngine = 0x0000000D; // CIASICIDGFXENGINE_ARCTICISLAND + create.chipFamily = 0x8F; + create.chipRevision = 0x28; + create.callbacks.allocSysMem = alloc_sys_mem; + create.callbacks.freeSysMem = free_sys_mem; + create.regValue.gbAddrConfig = 0x40 | 4u | (4u << 8); + if (AddrCreate(&create, &created) != ADDR_OK) return 1; + struct Shape { UINT width, height, mips, slices; DXGI_FORMAT format; bool one_d = false; }; + const Shape shapes[] = { + {1, 1, 1, 1, DXGI_FORMAT_R8_UNORM}, {300, 7, 1, 1, DXGI_FORMAT_R8_UNORM}, + {257, 129, 9, 2, DXGI_FORMAT_R8_UNORM}, {100, 10, 3, 2, DXGI_FORMAT_R16G16B16A16_FLOAT}, + {1920, 64, 1, 1, DXGI_FORMAT_R16G16B16A16_FLOAT}, {256, 256, 7, 1, DXGI_FORMAT_R32_FLOAT}, + {33, 17, 6, 3, DXGI_FORMAT_R16_UNORM}, {200, 100, 8, 1, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}, + {48, 40, 4, 2, DXGI_FORMAT_R32G32B32A32_FLOAT}, {64, 64, 4, 3, DXGI_FORMAT_BC1_UNORM}, + {128, 64, 6, 1, DXGI_FORMAT_BC7_UNORM}, + {300, 1, 9, 1, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, true}, {4096, 1, 13, 1, DXGI_FORMAT_R8_UNORM, true}, + {1000, 1, 10, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, true}, + }; + unsigned compared = 0, mismatches = 0; + for (const Shape& s : shapes) { + const D3D12_RESOURCE_DESC d = s.one_d ? texture_1d(s.width, s.mips, s.slices, s.format, 0x100) + : texture(s.width, s.height, s.mips, s.slices, s.format, 0x100); + const AddrResourceType type = s.one_d ? ADDR_RSRC_TEX_1D : ADDR_RSRC_TEX_2D; + const std::string name = std::string(s.one_d ? "1D " : "") + std::to_string(s.width) + "x" + std::to_string(s.height) + " format " + + std::to_string(s.format) + ", " + std::to_string(s.mips) + " mips"; + if (!x2w_startup::gfx10::supports(d)) { + fail(name + ": refused"); + ++mismatches; + continue; + } + const Layout l(d); + ADDR2_COMPUTE_SURFACE_INFO_INPUT info_in{}; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT info_out{}; + info_in.size = sizeof info_in; + info_out.size = sizeof info_out; + info_in.flags.texture = 1; + info_in.swizzleMode = ADDR_SW_LINEAR; + info_in.resourceType = type; + info_in.bpp = l.bytes_per_element * 8; + info_in.width = (s.width + l.texels - 1) / l.texels; + info_in.height = (s.height + l.texels - 1) / l.texels; + info_in.numSlices = s.slices; + info_in.numMipLevels = s.mips; + info_in.numSamples = 1; + info_in.numFrags = 1; + ++compared; + if (Addr2ComputeSurfaceInfo(created.hLib, &info_in, &info_out) != ADDR_OK || info_out.surfSize != l.bytes() || + info_out.sliceSize != l.slice_size) { + fail(name + ": size " + std::to_string(l.bytes()) + ", addrlib " + std::to_string(info_out.surfSize)); + ++mismatches; + continue; + } + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT in{}; + in.size = sizeof in; + in.flags.texture = 1; + in.swizzleMode = ADDR_SW_LINEAR; + in.resourceType = type; + in.bpp = info_in.bpp; + in.unalignedWidth = info_in.width; + in.unalignedHeight = info_in.height; + in.numSlices = s.slices; + in.numMipLevels = s.mips; + in.numSamples = 1; + in.numFrags = 1; + unsigned wrong = 0; + for (in.slice = 0; in.slice < s.slices; ++in.slice) + for (in.mipId = 0; in.mipId < s.mips; ++in.mipId) + for (in.y = 0; in.y < l.rows(in.mipId); ++in.y) + for (in.x = 0; in.x < l.columns(in.mipId); ++in.x) { + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT out{}; + out.size = sizeof out; + ++compared; + const std::uint64_t mine = l.address(in.mipId, in.x, in.y, in.slice); + if (Addr2ComputeSurfaceAddrFromCoord(created.hLib, &in, &out) != ADDR_OK || out.addr != mine) { + if (!wrong++) + fail(name + ": mip " + std::to_string(in.mipId) + " slice " + std::to_string(in.slice) + " (" + + std::to_string(in.x) + ", " + std::to_string(in.y) + ") at " + std::to_string(mine) + + ", addrlib " + std::to_string(out.addr)); + } + } + mismatches += wrong; + } + AddrDestroy(created.hLib); + std::printf("startup_gfx10_layout --addrlib: %u linear sizes and addresses compared, %u mismatches (Mesa 25.1.0 addrlib, " + "SW_LINEAR)\n", compared, mismatches); + return compared && !mismatches ? 0 : 1; +} +#endif + int main(int argc, char** argv) { + if (argc == 2 && std::string(argv[1]) == "--addrlib") return addrlib_linear_check(); const bool mutate = argc == 3 && std::string(argv[1]) == "--mutate" && std::string(argv[2]) == "display"; - if (argc != 1 && !mutate) { - std::printf("usage: startup_gfx10_layout_check [--mutate display]\n"); + const bool mutate_linear = argc == 3 && std::string(argv[1]) == "--mutate" && std::string(argv[2]) == "linear-largest-first"; + if (argc != 1 && !mutate && !mutate_linear) { + std::printf("usage: startup_gfx10_layout_check [--addrlib | --mutate display | --mutate linear-largest-first]\n"); return 2; } check_equations(mutate); + check_linear(mutate_linear); check_bc7_4k(); check_bc64(); check_tile64(); @@ -342,6 +549,6 @@ int main(int argc, char** argv) std::printf("startup_gfx10_layout: %d FAILED\n", failures); return 1; } - std::printf("startup_gfx10_layout: PASS (30 equations, 5 4 KiB surfaces, 8 64 KiB chains, 10 tile plans, 9 round trips, 11 refusals, 19 address descriptions, 27 views)\n"); + std::printf("startup_gfx10_layout: PASS (30 equations, 5 4 KiB surfaces, 8 64 KiB chains, 10 tile plans, 15 round trips, 1 linear chain, 15 refusals, 22 address descriptions, 39 views)\n"); return 0; } diff --git a/tests/startup_gfx10_volume_check.cpp b/tests/startup_gfx10_volume_check.cpp new file mode 100644 index 0000000000..17c9ba4156 --- /dev/null +++ b/tests/startup_gfx10_volume_check.cpp @@ -0,0 +1,506 @@ +// Checks the volume layout of src/startup_stubs/gfx10_layout.h (a 3D texture in the 4 KiB standard mode, +// 0x105, which addrlib lays out in thick blocks) without a device: +// - the address bit of every x, y and z bit against the one-pipe rows of addrlib's GFX10_SW_4K_S3_PATINFO, +// restated below, and the block each element size gives; +// - the order of blocks: along x, then y, then a layer of blocks at a time along z, with the sides of +// the texture padded to whole blocks; +// - a mip chain: each layer of blocks holds the tail block, then the mips from the smallest to the largest, +// and the tail mips sit at their origins inside the tail block; +// - a block-compressed volume: laid out as the uncompressed volume of its 4x4 blocks, one depth layer each; +// - that every element of a volume gets its own bytes inside the texture, and that a tile followed by a +// detile (with padded row and layer pitches) returns the texels it started from, for every mip; +// - the descriptions it takes and refuses, and the slot-70 views it allows on them. +// `--addrlib` compares the size and every element address of a set of volumes with +// Addr2ComputeSurfaceInfo and Addr2ComputeSurfaceAddrFromCoord (ADDR_RSRC_TEX_3D, ADDR_SW_4KB_S) and +// skips (77) when the build has no addrlib. `--mutate thin` lays each volume out as a thin 2D array of +// its depth layers, `--mutate tail` puts every mip of the tail at the start of the tail block, and +// `--mutate bc` sizes a block-compressed volume's blocks and mips by its texel sides instead of its 4x4 +// blocks; all three are negative controls and must fail. +// +// Reference: AMD addrlib as Mesa carries it under src/amd/addrlib, at the revision tools/fetch_addrlib.py +// pins (Mesa 25.1.0, commit 5c142e46f3f6e752ed745fd48912ebb8fad67145): src/gfx10/gfx10SwizzlePattern.h, +// src/gfx10/gfx10addrlib.cpp and src/core/addrlib2.cpp, each with the notice +// Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// The pattern rows are restated below as data; no addrlib code is included in the default run. +#include "startup_stubs/address_texture.h" +#include "startup_stubs/gfx10_layout.h" + +#include <algorithm> +#include <cstdio> +#include <cstring> +#include <string> +#include <vector> + +namespace { +using x2w_startup::gfx10::Layout; +int failures = 0; +bool thin = false; // --mutate thin +bool flat_tail = false; // --mutate tail +bool bc_texels = false; // --mutate bc + +void fail(const std::string& what) +{ + if (++failures <= 40) std::printf("FAIL %s\n", what.c_str()); +} + +D3D12_RESOURCE_DESC volume(UINT width, UINT height, UINT depth, DXGI_FORMAT format, UINT layout = 0x105, UINT mips = 1) +{ + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = static_cast<UINT16>(depth); + d.MipLevels = static_cast<UINT16>(mips); + d.Format = format; + d.SampleDesc.Count = 1; + d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(layout); + return d; +} + +// The layout under test; the controls read the volume as a thin array of its layers, or move every tail +// mip to the start of the tail block. +Layout layout_of(D3D12_RESOURCE_DESC d) +{ + if (thin) d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + const x2w_startup::gfx10::Element element = x2w_startup::gfx10::element_of(d.Format); + if (bc_texels && element.texels > 1) { + // The same volume with an uncompressed element of the block's size: blocks and mips are sized + // by the texel sides, while the elements visited stay the 4x4 blocks. + d.Format = element.bytes == 8 ? DXGI_FORMAT_R16G16B16A16_UNORM : DXGI_FORMAT_R32G32B32A32_UINT; + Layout l(d); + l.texels = element.texels; + return l; + } + Layout l(d); + for (UINT mip = l.first_tail; flat_tail && mip < l.mips; ++mip) l.origin_x[mip] = l.origin_y[mip] = 0; + return l; +} +std::uint64_t at(const Layout& l, UINT x, UINT y, UINT z, UINT mip = 0) +{ + return thin ? l.address(mip, x, y, z) : l.address(mip, x, y, 0, z); +} + +// One format per element size: 1, 2, 4, 8 and 16 bytes. +constexpr DXGI_FORMAT by_size[5] = {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT}; + +// GFX10_SW_4K_S3_PATINFO one-pipe rows by element size, address bits from bit 0 up; "0" is a bit inside +// the element. +const char* const rows_s3[5] = { + "X0 X1 Z0 Y0 Z1 Y1 X2 Z2 Y2 X3 Z3 Y3", "0 X0 Z0 Y0 Z1 Y1 X1 Z2 Y2 X2 Z3 Y3", "0 0 X0 Y0 Z0 Y1 X1 Z1 Y2 X2 Z2 Y3", + "0 0 0 X0 Z0 Y0 X1 Z1 Y1 X2 Z2 Y2", "0 0 0 0 Z0 Y0 X0 Z1 Y1 X1 Z2 Y2"}; +// addrlib Block1K_3d, scaled to 4 KiB by ComputeThickBlockDimension (height and depth doubled). +constexpr UINT block_sides[5][3] = {{16, 16, 16}, {8, 16, 16}, {8, 16, 8}, {8, 8, 8}, {4, 8, 8}}; + +void check_equations() +{ + for (UINT size = 0; size < 5; ++size) { + const Layout l = layout_of(volume(64, 64, 64, by_size[size])); + const std::string name = "element " + std::to_string(1u << size); + UINT bit = 0; + for (const char* p = rows_s3[size]; *p; ++bit) { + const char axis = *p++; + UINT index = 0; + if (axis != '0') index = static_cast<UINT>(*p++ - '0'); + if (*p == ' ') ++p; + if (axis == '0') continue; + const UINT v = 1u << index; + const std::uint64_t got = axis == 'X' ? at(l, v, 0, 0) : axis == 'Y' ? at(l, 0, v, 0) : at(l, 0, 0, v); + if (got != (1ull << bit)) + fail(name + " " + axis + std::to_string(index) + ": " + std::to_string(got) + ", expected bit " + std::to_string(bit)); + } + if (l.block_bytes != 4096 || l.block_width != block_sides[size][0] || l.block_height != block_sides[size][1] || + l.block_depth != block_sides[size][2]) + fail(name + ": block " + std::to_string(l.block_width) + "x" + std::to_string(l.block_height) + "x" + + std::to_string(l.block_depth)); + } +} + +// 17x17x17 RGBA8 in 8x16x8 blocks: 3 blocks across, 2 down and 3 layers of blocks. +void check_block_order() +{ + const Layout l = layout_of(volume(17, 17, 17, DXGI_FORMAT_R8G8B8A8_UNORM)); + const auto expect = [](const char* what, std::uint64_t got, std::uint64_t want) { + if (got != want) fail(std::string("block order: ") + what + " " + std::to_string(got) + ", expected " + std::to_string(want)); + }; + expect("bytes", l.bytes(), 3ull * 2 * 3 * 4096); + expect("next block in x", at(l, 8, 0, 0), 4096); + expect("next row of blocks", at(l, 0, 16, 0), 3 * 4096); + expect("next layer of blocks", at(l, 0, 0, 8), 6 * 4096); + expect("last element", at(l, 16, 16, 16), (2ull * 6 + 1 * 3 + 2) * 4096); +} + +// 32x32x32 RGBA8 with six mips, in 8x16x8 blocks. Mips 2 to 5 (8x8 and smaller, at most five from the +// end) share the tail block. A layer of blocks holds the tail block, mip 1 (2x1 blocks) and mip 0 (4x2 +// blocks): 11 blocks. The tail mips sit at byte (k << 8) of the tail block for k = 4, 3, 2, 1, read as +// 4x4x4 micro blocks: (0,8), (4,4), (4,0) and (0,4). +void check_mip_chain() +{ + const Layout l = layout_of(volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x105, 6)); + const auto expect = [](const char* what, std::uint64_t got, std::uint64_t want) { + if (got != want) fail(std::string("mip chain: ") + what + " " + std::to_string(got) + ", expected " + std::to_string(want)); + }; + expect("bytes", l.bytes(), 4ull * 11 * 4096); + expect("mip 0", at(l, 0, 0, 0, 0), 3 * 4096); + expect("mip 0 next row of blocks", at(l, 0, 16, 0, 0), 7 * 4096); + expect("mip 0 next layer of blocks", at(l, 0, 0, 8, 0), 14 * 4096); + expect("mip 1", at(l, 0, 0, 0, 1), 4096); + expect("mip 1 next block in x", at(l, 8, 0, 0, 1), 2 * 4096); + expect("mip 1 next layer of blocks", at(l, 0, 0, 8, 1), 12 * 4096); + expect("mip 2 at (0,8)", at(l, 0, 0, 0, 2), 0x800); // y 8: Y3, bit 11 + expect("mip 3 at (4,4)", at(l, 0, 0, 0, 3), 0x300); // x 4: X2, bit 9; y 4: Y2, bit 8 + expect("mip 4 at (4,0)", at(l, 0, 0, 0, 4), 0x200); + expect("mip 5 at (0,4)", at(l, 0, 0, 0, 5), 0x100); + expect("mip 2 next layer of blocks", at(l, 0, 0, 8, 2), 11 * 4096 + 0x800); +} + +// A block-compressed volume is the volume of its 4x4 blocks: BC1 64x64x16 with five mips takes the +// addresses of an 8-byte 16x16x16 volume with five mips, and BC7 48x20x9 with three mips those of a +// 16-byte 12x5x9 volume with three mips, element for element. +void check_block_compressed() +{ + struct Pair { + D3D12_RESOURCE_DESC bc, blocks; + }; + const Pair pairs[] = { + {volume(64, 64, 16, DXGI_FORMAT_BC1_UNORM, 0x105, 5), volume(16, 16, 16, DXGI_FORMAT_R16G16B16A16_UNORM, 0x105, 5)}, + {volume(48, 20, 9, DXGI_FORMAT_BC7_UNORM, 0x105, 3), volume(12, 5, 9, DXGI_FORMAT_R32G32B32A32_UINT, 0x105, 3)}, + }; + for (const Pair& pair : pairs) { + const Layout bc = layout_of(pair.bc), blocks = layout_of(pair.blocks); + const std::string name = "block-compressed " + std::to_string(pair.bc.Width) + "x" + std::to_string(pair.bc.Height); + if (bc.bytes() != blocks.bytes()) fail(name + ": size " + std::to_string(bc.bytes())); + bool same = true; + for (UINT mip = 0; mip < bc.mips; ++mip) { + if (bc.columns(mip) < blocks.columns(mip) || bc.rows(mip) < blocks.rows(mip) || bc.layers(mip) != blocks.layers(mip)) + same = false; + for (UINT z = 0; z < blocks.layers(mip); ++z) + for (UINT y = 0; y < blocks.rows(mip); ++y) + for (UINT x = 0; x < blocks.columns(mip); ++x) same = same && at(bc, x, y, z, mip) == at(blocks, x, y, z, mip); + } + if (!same) fail(name + ": an element differs from the uncompressed volume of its blocks"); + } +} + +struct Shape { + UINT width, height, depth; + DXGI_FORMAT format; + UINT mips = 1; +}; +const Shape shapes[] = { + {17, 17, 17, DXGI_FORMAT_R16G16B16A16_FLOAT}, {32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM}, {33, 33, 33, DXGI_FORMAT_R16G16B16A16_FLOAT}, + {32, 32, 32, DXGI_FORMAT_A8_UNORM}, {16, 16, 8, DXGI_FORMAT_R16_FLOAT}, {16, 16, 16, DXGI_FORMAT_R8G8_UNORM}, + {32, 32, 32, DXGI_FORMAT_R10G10B10A2_UNORM}, {5, 3, 7, DXGI_FORMAT_R32G32B32A32_FLOAT}, {1, 1, 2, DXGI_FORMAT_R8_UNORM}, + {64, 8, 40, DXGI_FORMAT_R32_FLOAT}, + // Mip chains: whole and partial, a tail that starts at mip 0, a chain with no tail, odd sides. + {32, 32, 32, DXGI_FORMAT_R8_UNORM, 6}, {32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 6}, + {64, 64, 32, DXGI_FORMAT_R16G16_FLOAT, 7}, {128, 128, 128, DXGI_FORMAT_R16G16B16A16_FLOAT, 8}, + {16, 16, 16, DXGI_FORMAT_R32G32B32A32_FLOAT, 5}, {8, 4, 8, DXGI_FORMAT_R8G8B8A8_UNORM, 4}, + {64, 64, 64, DXGI_FORMAT_R16_FLOAT, 2}, {33, 17, 9, DXGI_FORMAT_R16G16B16A16_FLOAT, 6}, + {4, 4, 64, DXGI_FORMAT_R8_UNORM, 7}, {256, 32, 8, DXGI_FORMAT_R16_FLOAT, 9}, + // Block-compressed volumes: 8- and 16-byte blocks, with and without a chain, sides that are not + // powers of two, and mips smaller than a block. + {64, 64, 16, DXGI_FORMAT_BC1_UNORM, 5}, {32, 32, 32, DXGI_FORMAT_BC7_UNORM, 6}, + {12, 20, 9, DXGI_FORMAT_BC5_UNORM, 5}, {256, 256, 8, DXGI_FORMAT_BC3_UNORM, 9}, + {4, 4, 4, DXGI_FORMAT_BC4_UNORM, 3}, {128, 128, 128, DXGI_FORMAT_BC5_SNORM, 8}, + {40, 8, 3, DXGI_FORMAT_BC6H_UF16, 1}, +}; + +void check_distinct_and_round_trip() +{ + for (const Shape& s : shapes) { + const D3D12_RESOURCE_DESC d = volume(s.width, s.height, s.depth, s.format, 0x105, s.mips); + const std::string name = std::to_string(s.width) + "x" + std::to_string(s.height) + "x" + std::to_string(s.depth) + + " format " + std::to_string(s.format) + " mips " + std::to_string(s.mips); + if (!x2w_startup::gfx10::supports(d)) { + fail(name + ": refused"); + continue; + } + const Layout l = layout_of(d); + const UINT e = l.bytes_per_element; + const std::uint64_t size = l.bytes(); + std::vector<unsigned char> used(static_cast<std::size_t>(size)); + // Every element of every mip has its own bytes. + bool clash = false; + for (UINT mip = 0; mip < s.mips; ++mip) + for (UINT z = 0; z < l.layers(mip); ++z) + for (UINT y = 0; y < l.rows(mip); ++y) + for (UINT x = 0; x < l.columns(mip); ++x) { + const std::uint64_t a = at(l, x, y, z, mip); + if (a % e || a + e > size) { + clash = true; + continue; + } + if (used[static_cast<std::size_t>(a)]) clash = true; + used[static_cast<std::size_t>(a)] = 1; + } + if (clash) fail(name + ": elements share bytes or fall outside the texture"); + if (thin) continue; + std::vector<unsigned char> tiled(static_cast<std::size_t>(size)); + for (UINT mip = 0; mip < s.mips; ++mip) { + const UINT w = l.columns(mip), h = l.rows(mip), n = l.layers(mip); + const std::size_t pitch = (std::size_t{w} * e + 255) & ~std::size_t{255}, layer = pitch * (h + 1); + std::vector<unsigned char> rows(layer * n), back(rows.size()); + for (std::size_t i = 0; i < rows.size(); ++i) rows[i] = static_cast<unsigned char>(i * 131 + 7 + mip); + l.tile(mip, 0, tiled.data(), rows.data(), pitch, layer); + l.detile(mip, 0, tiled.data(), back.data(), pitch, layer); + for (UINT z = 0; z < n; ++z) + for (UINT y = 0; y < h; ++y) + if (std::memcmp(&rows[z * layer + y * pitch], &back[z * layer + y * pitch], std::size_t{w} * e)) { + fail(name + ": round trip differs in mip " + std::to_string(mip) + " at layer " + std::to_string(z) + + " row " + std::to_string(y)); + z = n; + break; + } + } + } +} + +void check_descriptions() +{ + const auto supported = [](const char* name, const D3D12_RESOURCE_DESC& d, bool want) { + if (x2w_startup::gfx10::supports(d) != want) fail(std::string("layout: ") + name); + }; + const D3D12_RESOURCE_DESC good = volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM); + supported("4 KiB standard RGBA8", good, true); + D3D12_RESOURCE_DESC d = good; + d.MipLevels = 6; + supported("a whole mip chain", d, true); + d.MipLevels = 16; + supported("more mips than a layout holds", d, false); + d.MipLevels = 0; + supported("no mips", d, false); + supported("BC1", volume(32, 32, 32, DXGI_FORMAT_BC1_UNORM), true); + supported("BC7 with a mip chain", volume(32, 32, 32, DXGI_FORMAT_BC7_UNORM, 0x105, 6), true); + supported("4 KiB display", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x106), false); + supported("256 B standard", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x101), false); + supported("64 KiB standard", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x109), false); + supported("64 KiB display", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x10a), false); + supported("linear", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0x100), false); + supported("desktop layout", volume(32, 32, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 0), false); + supported("12-byte texels", volume(32, 32, 32, DXGI_FORMAT_R32G32B32_FLOAT), false); + supported("too wide", volume(2049, 4, 4, DXGI_FORMAT_R8_UNORM), false); + supported("too deep", volume(4, 4, 2049, DXGI_FORMAT_R8_UNORM), false); + supported("no depth", volume(4, 4, 0, DXGI_FORMAT_R8_UNORM), false); + d = good; + d.SampleDesc.Count = 2; + supported("multisampled", d, false); + + const auto address = [](const char* name, const D3D12_RESOURCE_DESC& d, bool want) { + if (x2w_startup::console_address_texture(d) != want) fail(std::string("address texture: ") + name); + }; + address("RGBA16F 17x17x17", volume(17, 17, 17, DXGI_FORMAT_R16G16B16A16_FLOAT), true); + address("R8 32x32x32", volume(32, 32, 32, DXGI_FORMAT_R8_UNORM), true); + address("typed depth", volume(32, 32, 32, DXGI_FORMAT_D32_FLOAT), false); + d = good; + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + address("unordered access", d, false); + address("BC7", volume(32, 32, 32, DXGI_FORMAT_BC7_UNORM), true); + address("BC1 not whole blocks wide", volume(30, 32, 32, DXGI_FORMAT_BC1_UNORM), false); + address("BC1 any depth", volume(32, 32, 3, DXGI_FORMAT_BC1_UNORM), true); + d = good; + d.MipLevels = 6; + address("mip chain", d, true); + d.MipLevels = 7; + address("more mips than the sides allow", d, false); + address("mips the depth allows", volume(4, 4, 64, DXGI_FORMAT_R8_UNORM, 0x105, 7), true); + + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.Texture3D.MipLevels = ~0u; + if (!x2w_startup::address_view_fits(good, v)) fail("view: whole volume"); + v.Texture3D.MipLevels = 1; + if (!x2w_startup::address_view_fits(good, v)) fail("view: one mip"); + v.Texture3D.MostDetailedMip = 1; + if (x2w_startup::address_view_fits(good, v)) fail("view: mip past the volume"); + D3D12_RESOURCE_DESC chain = good; + chain.MipLevels = 6; + v.Texture3D.MostDetailedMip = 2; + v.Texture3D.MipLevels = 4; + if (!x2w_startup::address_view_fits(chain, v)) fail("view: the last four mips of a chain"); + v.Texture3D.MipLevels = 5; + if (x2w_startup::address_view_fits(chain, v)) fail("view: mips past the chain"); + v.Texture3D.MipLevels = 1; + v.Texture3D.MostDetailedMip = 0; + D3D12_RESOURCE_DESC typeless = good; + typeless.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS; + v.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + if (!x2w_startup::address_view_fits(typeless, v)) fail("view: sRGB of typeless storage"); + if (x2w_startup::address_view_fits(good, v)) fail("view: sRGB of UNORM storage"); + v.Format = DXGI_FORMAT_R32_FLOAT; + if (x2w_startup::address_view_fits(good, v)) fail("view: other family"); + v.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.Texture2DArray = {0, ~0u, 0, 32, 0, 0.0f}; + if (x2w_startup::address_view_fits(good, v)) fail("view: 2D array on a volume"); +} +} // namespace + +#ifndef XBOX2WINDOWS_HAVE_ADDRLIB +int addrlib_check() +{ + std::puts("startup_gfx10_volume --addrlib: SKIP (built without addrlib; run tools/fetch_addrlib.py and configure with " + "-DXBOX2WINDOWS_ADDRLIB_DIR=<mesa>/src/amd/addrlib)"); + return 77; +} +#else +#include <cstdlib> + +#include "addrinterface.h" + +namespace { +VOID* ADDR_API alloc_sys_mem(const ADDR_ALLOCSYSMEM_INPUT* in) { return std::malloc(in->sizeInBytes); } +ADDR_E_RETURNCODE ADDR_API free_sys_mem(const ADDR_FREESYSMEM_INPUT* in) +{ + std::free(in->pVirtAddr); + return ADDR_OK; +} +} // namespace + +// The shapes above and a sweep of small odd sides, for each element size, against Mesa's "navi21" +// (gfx10.3) configuration that startup_small_texture_4k_check and xg_swizzle_select_check use: family +// 0x8F, revision 0x28, GB_ADDR_CONFIG 0x444. +int addrlib_check() +{ + ADDR_CREATE_INPUT create{}; + ADDR_CREATE_OUTPUT created{}; + create.size = sizeof create; + created.size = sizeof created; + create.chipEngine = 0x0000000D; // CIASICIDGFXENGINE_ARCTICISLAND + create.chipFamily = 0x8F; + create.chipRevision = 0x28; + create.callbacks.allocSysMem = alloc_sys_mem; + create.callbacks.freeSysMem = free_sys_mem; + create.regValue.gbAddrConfig = 0x40 | 4u | (4u << 8); + if (AddrCreate(&create, &created) != ADDR_OK) return 1; + const AddrFormat addr_formats[5] = {ADDR_FMT_8, ADDR_FMT_16, ADDR_FMT_8_8_8_8, ADDR_FMT_16_16_16_16, ADDR_FMT_32_32_32_32}; + // A block-compressed format is passed as itself, so that addrlib turns its texel sides into blocks. + const auto addr_format = [&](DXGI_FORMAT f, UINT size) { + switch (f) { + case DXGI_FORMAT_BC1_UNORM: return ADDR_FMT_BC1; + case DXGI_FORMAT_BC2_UNORM: return ADDR_FMT_BC2; + case DXGI_FORMAT_BC3_UNORM: return ADDR_FMT_BC3; + case DXGI_FORMAT_BC4_UNORM: return ADDR_FMT_BC4; + case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM: return ADDR_FMT_BC5; + case DXGI_FORMAT_BC6H_UF16: return ADDR_FMT_BC6; + case DXGI_FORMAT_BC7_UNORM: return ADDR_FMT_BC7; + default: return addr_formats[size]; + } + }; + std::vector<D3D12_RESOURCE_DESC> cases; + for (const Shape& s : shapes) cases.push_back(volume(s.width, s.height, s.depth, s.format, 0x105, s.mips)); + for (UINT size = 0; size < 5; ++size) + for (UINT w : {1u, 3u, 9u, 24u}) + for (UINT h : {1u, 7u, 17u}) + for (UINT dep : {1u, 5u, 18u}) cases.push_back(volume(w, h, dep, by_size[size])); + // Every mip count of a set of chains, so that each mip in turn is the first in the tail or the last + // outside it. + constexpr UINT chains[4][3] = {{64, 64, 64}, {40, 24, 12}, {17, 33, 5}, {8, 8, 32}}; + for (UINT size = 0; size < 5; ++size) + for (const auto& side : chains) + for (UINT mips = 2; ((std::max)({side[0], side[1], side[2]}) >> (mips - 1)) != 0; ++mips) + cases.push_back(volume(side[0], side[1], side[2], by_size[size], 0x105, mips)); + // Every mip count of a set of block-compressed chains, for each BC format. + constexpr DXGI_FORMAT bc[] = {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC4_UNORM, + DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC6H_UF16, DXGI_FORMAT_BC7_UNORM}; + constexpr UINT bc_chains[4][3] = {{64, 64, 16}, {12, 20, 9}, {4, 4, 32}, {256, 8, 8}}; + for (DXGI_FORMAT f : bc) + for (const auto& side : bc_chains) + for (UINT mips = 1; ((std::max)({side[0], side[1], side[2]}) >> (mips - 1)) != 0; ++mips) + cases.push_back(volume(side[0], side[1], side[2], f, 0x105, mips)); + unsigned compared = 0, elements = 0, mismatches = 0; + for (const D3D12_RESOURCE_DESC& d : cases) { + const Layout l(d); + UINT size = 0; + while ((1u << size) < l.bytes_per_element) ++size; + ADDR2_COMPUTE_SURFACE_INFO_INPUT in{}; + ADDR2_COMPUTE_SURFACE_INFO_OUTPUT out{}; + in.size = sizeof in; + out.size = sizeof out; + in.flags.texture = 1; + in.swizzleMode = ADDR_SW_4KB_S; + in.resourceType = ADDR_RSRC_TEX_3D; + in.format = addr_format(d.Format, size); + in.bpp = l.bytes_per_element * 8; + in.width = l.width; + in.height = l.height; + in.numSlices = l.depth; + in.numMipLevels = l.mips; + in.numSamples = 1; + in.numFrags = 1; + ++compared; + char name[64]; + std::snprintf(name, sizeof name, "%ux%ux%u %u-byte %u mips", l.width, l.height, l.depth, l.bytes_per_element, l.mips); + if (Addr2ComputeSurfaceInfo(created.hLib, &in, &out) != ADDR_OK || out.surfSize != l.bytes()) { + if (++mismatches <= 12) + std::printf("FAIL %s: size 0x%llx, addrlib 0x%llx\n", name, static_cast<unsigned long long>(l.bytes()), + static_cast<unsigned long long>(out.surfSize)); + continue; + } + for (UINT mip = 0; mip < l.mips; ++mip) + for (UINT z = 0; z < l.layers(mip); ++z) + for (UINT y = 0; y < l.rows(mip); ++y) + for (UINT x = 0; x < l.columns(mip); ++x) { + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT ain{}; + ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT aout{}; + ain.size = sizeof ain; + aout.size = sizeof aout; + ain.x = x; + ain.y = y; + ain.slice = z; + ain.mipId = mip; + ain.swizzleMode = ADDR_SW_4KB_S; + ain.flags.texture = 1; + ain.resourceType = ADDR_RSRC_TEX_3D; + ain.bpp = in.bpp; + ain.unalignedWidth = l.columns(0); // in elements: 4x4 blocks for BC + ain.unalignedHeight = (l.height + l.texels - 1) / l.texels; + ain.numSlices = l.depth; + ain.numMipLevels = l.mips; + ain.numSamples = 1; + ain.numFrags = 1; + ain.pitchInElement = out.pitch; + ++elements; + const std::uint64_t mine = l.address(mip, x, y, 0, z); + if (Addr2ComputeSurfaceAddrFromCoord(created.hLib, &ain, &aout) != ADDR_OK || aout.addr != mine) { + if (++mismatches <= 12) + std::printf("FAIL %s mip %u (%u,%u,%u): 0x%llx, addrlib 0x%llx\n", name, mip, x, y, z, + static_cast<unsigned long long>(mine), static_cast<unsigned long long>(aout.addr)); + } + } + } + AddrDestroy(created.hLib); + std::printf("startup_gfx10_volume --addrlib: %u volumes, %u element addresses compared, %u mismatches (Mesa 25.1.0 addrlib, " + "SW_4KB_S, 3D)\n", compared, elements, mismatches); + return compared && elements && !mismatches ? 0 : 1; +} +#endif + +int main(int argc, char** argv) +{ + if (argc == 2 && std::strcmp(argv[1], "--addrlib") == 0) return addrlib_check(); + const bool mutate = argc == 3 && std::strcmp(argv[1], "--mutate") == 0; + thin = mutate && std::strcmp(argv[2], "thin") == 0; + flat_tail = mutate && std::strcmp(argv[2], "tail") == 0; + bc_texels = mutate && std::strcmp(argv[2], "bc") == 0; + if (argc != 1 && !thin && !flat_tail && !bc_texels) { + std::printf("usage: startup_gfx10_volume_check [--addrlib | --mutate thin | --mutate tail | --mutate bc]\n"); + return 2; + } + check_equations(); + check_block_order(); + check_mip_chain(); + check_block_compressed(); + check_distinct_and_round_trip(); + check_descriptions(); + if (failures) { + std::printf("startup_gfx10_volume: %d failures\n", failures); + return 1; + } + std::printf("startup_gfx10_volume: PASS (5 element sizes, block order, a mip chain, %zu volumes round-tripped mip by mip, " + "17 layouts, 10 address descriptions, 9 views, 2 block-compressed volumes against their blocks)\n", sizeof(shapes) / sizeof(shapes[0])); + return 0; +} diff --git a/tests/startup_gfx2hlsl_add_sub_co_check.py b/tests/startup_gfx2hlsl_add_sub_co_check.py index 7fa75429f2..0a80e6ea1e 100644 --- a/tests/startup_gfx2hlsl_add_sub_co_check.py +++ b/tests/startup_gfx2hlsl_add_sub_co_check.py @@ -8,8 +8,8 @@ The emitted lines are evaluated with the restricted evaluator of startup_gfx2hlsl_bit_alu_check on a grid of edge values and compared with Python references written from the ISA description, for an SGPR and a VCC carry-out. Also -checked: the carry-out SGPR becomes a lane mask that is not a uniform source, a readfirstlane of a copy of it is -refused, inactive lanes keep D and get a 0 carry when exec is not known, a destination that overlaps a source reads +checked: the carry-out SGPR becomes a lane mask that is refused as vector move data, inactive lanes keep D +and get a 0 carry when exec is not known, a destination that overlaps a source reads the source first, and clamp, a wrong operand count and an EXEC carry-out are refused. Negative control: a borrow written as S0 > S1 differs from the reference on the grid. """ @@ -117,15 +117,15 @@ def main(): count += 1 check('%s matches the ISA reference on the grid' % text, bad is None, bad) - # The carry-out is per lane: a readfirstlane of a VGPR copied from it must not be proven uniform. + # The carry-out holds only this lane's bit and cannot be moved as a data word. s, text, _ = translate(vop3b(0x30f, 2, 18, V4, V3)) try: s.one('v_mov_b32', 'v_mov_b32 v5, s18') - s.one('v_readfirstlane_b32', 'v_readfirstlane_b32 s20, v5') except G.Unsupported as error: - check('%s: readfirstlane of a copy of the carry-out is refused' % text, 'uniform' in str(error), str(error)) + check('%s: moving the carry-out as data is refused' % text, + str(error) == 'v_mov_b32 data operand s18 is a lane mask', str(error)) else: - check('%s: readfirstlane of a copy of the carry-out is refused' % text, False, s.lines) + check('%s: moving the carry-out as data is refused' % text, False, s.lines) # D of varying sources is not proven uniform either. s, text, _ = translate(vop3b(0x30f, 2, 18, V4, V3)) try: diff --git a/tests/startup_gfx2hlsl_bfm_b64_check.py b/tests/startup_gfx2hlsl_bfm_b64_check.py new file mode 100644 index 0000000000..b7185e6e1a --- /dev/null +++ b/tests/startup_gfx2hlsl_bfm_b64_check.py @@ -0,0 +1,637 @@ +"""s_bfm_b64 in tools/startup/gfx2hlsl.py (census issue #1723). + +usage: startup_gfx2hlsl_bfm_b64_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]] + + (no arguments) translation controls and the CPU evaluation of the emitted text, pure Python + draw additionally draw the translated pair on a desktop adapter (WARP or hardware), compile the pixel + stage with FXC ps_5_1 when given and with DXC ps_6_0, and compare the read-back words + +`s_bfm_b64` had no lowering and was refused. RDNA 2 ISA (SOP2 opcode 37, `isa/rdna2_isa.txt` "S_BFM_B64"): +`D.u64 = ((1ULL << S0.u[5:0]) - 1) << S1.u[5:0]`. Both sources are 32-bit and only their low six bits count; a +width of 0 gives 0; the mask is truncated to 64 bits, so bits shifted past bit 63 are dropped. The ISA lists no SCC +write for this opcode (the bitwise ops print `SCC = (D != 0)`), so SCC is left alone. + +The 64-bit scalar value is two words (s[d], s[d+1]) written together. The instruction bytes are constructed here +from the SOP2 layout the checked-in decoder reads (`tools/disasm_rdna2.py`: [31:30]=0b10, opcode [29:23], sdst +[22:16], ssrc1 [15:8], ssrc0 [7:0]). + +The emitted HLSL, including the real `shl64` helper from the generated preamble, is evaluated by a small integer +evaluator that rejects any 32-bit shift count of 32 or more (undefined in HLSL), and compared with a reference built +from a bit loop over the ISA description, not from the lowering's expressions. Mutations (no width mask, 31 instead of +63, offset masked to five bits, width 0 reading all ones) must read a wrong word and are applied to the translated +text only. + +The draw mode (review of #2007) takes the evaluator out of the loop: the compiler's own treatment of `shl64`, the +`bw >= 32u ? ... : ...` selects and `uint2` is read back from the render target. Width and offset are root constants +(s8 and s9 of the pixel stage), so neither compiler can fold them. One draw computes `s_bfm_b64 s[20:21], s8, s9` and +the swapped `s_bfm_b64 s[22:23], s9, s8` and exports the four words. The expected words are the bit-loop reference. +Two negative controls must show in the draw: a reference that wraps the bits past bit 63 instead of dropping them, +and a mutated lowering (width 0 reads all ones). The pixel stage is built from instruction words made with the +encoder below and read back through the decoder, so no assembler is needed. + +A source SGPR that holds a lane mask (a compare result) is refused before either destination word or its mask flag changes, +with and without the destination aliasing the source. After #1931 both written words are proven uniform only when both sources +are, and an older proof for s[d] or s[d+1] is dropped, so a later v_readfirstlane_b32 cannot use it. +""" +import os +import re +import struct +import sys +import types + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +MASK = 0xffffffff +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def reference(width, offset): + """The ISA mask as a bit loop: bit i is set when offset <= i < offset + width and i < 64.""" + width, offset = width & 63, offset & 63 + return sum(1 << i for i in range(64) if offset <= i < offset + width) + + +# ---- instruction construction ------------------------------------------------------------------------------ +SOP2_BFM_B64 = 37 + + +def encode(dst, src0, src1, literal=None): + w0 = 0x80000000 | (SOP2_BFM_B64 << 23) | (dst << 16) | (src1 << 8) | src0 + out = struct.pack('<I', w0) + return out + (struct.pack('<I', literal) if literal is not None else b'') + + +class Pipeline: + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + +class Stage(G.Stage): + def __init__(self): + self.lines, self.sym, self.masks = [], {}, set() + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports = {} + self.pipe = Pipeline() + + +def translate(asm, sym=None): + stage = Stage() + stage.sym.update(sym or {}) + stage.one('s_bfm_b64', asm) + return stage + + +def refused(asm, sym=None): + try: + translate(asm, sym) + except G.Unsupported: + return True + return False + + +# ---- a small evaluator for the HLSL the lowering and the shl64 helper use --------------------------------- +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||&=|[-+*&|^~!<>?:(),.=])') +LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] + + +class Interp: + def __init__(self, common): + self.funcs = {} + m = re.search(r'uint2 shl64\(([^)]*)\) \{(.*?)\}\s*(?=\'|uint2 shr64u|$)', common) + assert m, 'shl64 not found in the preamble' + self.funcs['shl64'] = ([p.split()[-1] for p in m.group(1).split(',')], m.group(2)) + + def tokens(self, text): + toks = TOKEN.findall(text) + assert ''.join(toks) == re.sub(r'\s+', '', text), text + return toks + + def expr(self, text, env): + self.t, self.p, self.env = self.tokens(text), 0, env + value = self.ternary() + assert self.p == len(self.t), text + return value + + def peek(self): + return self.t[self.p] if self.p < len(self.t) else None + + def take(self): + self.p += 1 + return self.t[self.p - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + no = self.ternary() + return yes if cond else no + + def binary(self, level): + if level == len(LEVELS): + return self.unary() + node = self.binary(level + 1) + while self.peek() in LEVELS[level]: + op = self.take() + b = self.binary(level + 1) + a = node + if op in ('<<', '>>'): + assert 0 <= b < 32, 'HLSL shift count %d is not below 32' % b + node = (a << b) & MASK if op == '<<' else a >> b + elif op == '||': + node = int(bool(a or b)) + else: + node = {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b, '==': int(a == b), + '!=': int(a != b), '<': int(a < b), '>': int(a > b), '<=': int(a <= b), + '>=': int(a >= b)}[op] + node &= MASK + return node + + def unary(self): + tok = self.take() + if tok == '~': + return ~self.unary() & MASK + if tok == '(': + v = self.ternary() + assert self.take() == ')' + return self.member(v) + if tok[0].isdigit(): + return int(tok.rstrip('u'), 0) + if self.peek() == '(': + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return self.member(self.call(tok, args)) + return self.member(self.env[tok]) + + def member(self, v): + while self.peek() == '.': + self.take() + v = v['xy'.index(self.take())] + return v + + def call(self, name, args): + if name == 'uint2': + return tuple(args) + params, body = self.funcs[name] + saved = (self.t, self.p, self.env) + env = dict(zip(params, args)) + result = self.run(body, env) + self.t, self.p, self.env = saved + return result + + def run(self, text, env): + """Run statements; returns the value of a `return`.""" + for stmt in [s.strip() for s in text.split(';') if s.strip()]: + stmt = stmt.strip('{} ') + if not stmt: + continue + if stmt.startswith('return '): + return self.expr(stmt[7:], env) + m = re.match(r'(uint2|uint)\s+(.*)$', stmt) + if m: + for part in re.split(r',\s*(?=\w+\s*=)', m.group(2)): + name, _, rhs = part.partition('=') + env[name.strip()] = self.expr(rhs, env) + continue + m = re.match(r'(\w+)\s*(&=|=)\s*(.*)$', stmt) + assert m, stmt + value = self.expr(m.group(3), env) + env[m.group(1)] = (env[m.group(1)] & value) if m.group(2) == '&=' else value + return None + + +def preamble(): + pipe = object.__new__(G.Pipeline) + pipe.uds, pipe.resources, pipe.samplers, pipe.uses_sampler_heap = [], {}, {}, False + return ' '.join(pipe.common()) + + +COMMON = preamble() + + +def evaluate(stage, env, common=COMMON): + """Run the emitted lines of `stage` and return the (s20, s21) words.""" + interp = Interp(common) + env = dict(env) + for line in stage.lines: + # one block of statements: '{ ...; s20 = t.x; s21 = t.y; }' + interp.run(line, env) + return env['s20'], env['s21'] + + +def pair(value): + return value & MASK, value >> 32 + + +# ---- 1. the encoder produces the form the decoder reads ----------------------------------------------------- +decoded = G.decode(encode(20, 2, 3)) +check('encodes and decodes the register form', [a for _o, _s, _n, a in decoded] == ['s_bfm_b64 s[20:21], s2, s3'], + repr(decoded)) +decoded = G.decode(encode(20, 128 + 33, 128 + 5)) +check('encodes and decodes inline constants', [a for _o, _s, _n, a in decoded] == ['s_bfm_b64 s[20:21], 33, 5'], + repr(decoded)) +decoded = G.decode(encode(20, 255, 3, literal=0x12345681)) +check('encodes and decodes a literal', [a for _o, _s, _n, a in decoded] == ['s_bfm_b64 s[20:21], 0x12345681, s3'], + repr(decoded)) + +# ---- 2. run-time sources: the whole width x offset grid, evaluated against the bit-loop reference ----------- +asm = 's_bfm_b64 s[20:21], s2, s3' +stage = translate(asm) +text = ' '.join(stage.lines) +check('run-time form writes both words and no SCC', + 's20 = t.x;' in text and 's21 = t.y;' in text and 'scc' not in text and 'shl64(' in text, text) +bad = [] +for w in range(64): + for o in range(64): + got = evaluate(stage, {'s2': w, 's3': o}) + if got != pair(reference(w, o)): + bad.append((w, o, got)) +check('all 64 x 64 width/offset pairs match the reference', not bad, repr(bad[:3])) +key = [(0, 0), (0, 63), (1, 0), (1, 63), (31, 0), (31, 31), (31, 32), (32, 0), (32, 31), (32, 32), (33, 0), + (33, 31), (33, 32), (33, 63), (63, 0), (63, 1), (63, 31), (63, 32), (63, 63), (0, 31), (1, 31), (1, 32)] +bad = [(w, o) for w, o in key if evaluate(stage, {'s2': w, 's3': o}) != pair(reference(w, o))] +check('named widths 0/1/31/32/33/63 against offsets 0/31/32/63', not bad, repr(bad)) +# hand-written anchors, so the reference is not the only witness +anchors = {(0, 0): 0, (0, 63): 0, (1, 63): 1 << 63, (63, 1): (1 << 64) - 2, (32, 32): 0xffffffff00000000, + (33, 31): 0xffffffff80000000, (63, 63): 1 << 63, (31, 32): 0x7fffffff00000000} +check('hand-computed anchors', all(reference(*k) == v and evaluate(stage, {'s2': k[0], 's3': k[1]}) == pair(v) + for k, v in anchors.items())) +# source bits above [5:0] are ignored +junk = [(w | hi, o | hj) for w in (0, 1, 31, 32, 33, 63) for o in (0, 31, 32, 63) + for hi, hj in ((0x40, 0), (0, 0x40), (0xffffffc0, 0xffffff80), (0x80000000, 0x80000040), (0x12345640, 0xabcdef00))] +bad = [(w, o) for w, o in junk if evaluate(stage, {'s2': w, 's3': o}) != pair(reference(w, o))] +check('bits above [5:0] of either source are ignored (%d inputs)' % len(junk), not bad, repr(bad[:3])) + +# ---- 3. inline and literal sources --------------------------------------------------------------------------- +stage = translate('s_bfm_b64 s[20:21], 33, s3') +check('an inline width with a run-time offset reads the constant', + '0x00000021u' in ' '.join(stage.lines) and all( + evaluate(stage, {'s3': o}) == pair(reference(33, o)) for o in range(64))) +stage = translate('s_bfm_b64 s[20:21], s2, 32') +check('a run-time width with an inline offset reads the constant', + all(evaluate(stage, {'s2': w}) == pair(reference(w, 32)) for w in range(64))) +stage = translate('s_bfm_b64 s[20:21], 0x12345681, s3') +check('a literal width keeps only its low six bits (0x81 & 63 = 1)', + all(evaluate(stage, {'s3': o}) == pair(reference(1, o)) for o in range(64))) + +# ---- 4. fully constant sources fold, with the same result ---------------------------------------------------- +bad = [] +for w, o in [(0, 0), (1, 0), (31, 0), (32, 0), (33, 0), (63, 0), (1, 63), (63, 63), (33, 32), (32, 31), (0, 63), (5, 3)]: + stage = translate('s_bfm_b64 s[20:21], %d, %d' % (w, o)) + if stage.sym.get(20) != ('const', pair(reference(w, o))[0]) or stage.sym.get(21) != ('const', pair(reference(w, o))[1]): + bad.append((w, o, stage.sym)) +check('inline constants fold to the reference words', not bad, repr(bad[:2])) +stage = translate('s_bfm_b64 s[20:21], 0x12345681, 0x7f') +check('literals fold and mask both sources', + (stage.sym.get(20), stage.sym.get(21)) == tuple(('const', x) for x in pair(reference(1, 63)))) +stage = translate('s_bfm_b64 s[20:21], s2, s3', {2: ('const', 33), 3: ('const', 31)}) +check('SGPRs holding known constants fold', + (stage.sym.get(20), stage.sym.get(21)) == tuple(('const', x) for x in pair(reference(33, 31)))) +stage = translate('s_bfm_b64 s[20:21], s2, s3', {2: ('const', 0x1000), 3: ('const', 0)}) +check('a known width whose low six bits are 0 folds to a zero pair', + (stage.sym.get(20), stage.sym.get(21)) == (('const', 0), ('const', 0))) + +# ---- 5. an in-place destination reads the original sources ---------------------------------------------------- +stage = translate('s_bfm_b64 s[2:3], s2, s3') +env = {'s2': 33, 's3': 31} +interp = Interp(COMMON) +for line in stage.lines: + interp.run(line, env) +check('the destination may be the source registers', (env['s2'], env['s3']) == pair(reference(33, 31)), repr(env)) + +# ---- 6. refusals --------------------------------------------------------------------------------------------- +check('odd, single, vector and mask destinations are refused', all(refused(a) for a in ( + 's_bfm_b64 s[21:22], s2, s3', 's_bfm_b64 s20, s2, s3', 's_bfm_b64 v[20:21], s2, s3', 's_bfm_b64 exec, s2, s3', + 's_bfm_b64 vcc, s2, s3', 's_bfm_b64 s[20:23], s2, s3', 's_bfm_b64 s[106:107], s2, s3', 's_bfm_b64 m0, s2, s3'))) +check('pair, vector and mask sources are refused', all(refused(a) for a in ( + 's_bfm_b64 s[20:21], s[2:3], s3', 's_bfm_b64 s[20:21], s2, s[4:5]', 's_bfm_b64 s[20:21], v2, s3', + 's_bfm_b64 s[20:21], s2, vcc', 's_bfm_b64 s[20:21], exec, s3', 's_bfm_b64 s[20:21], vcc_lo, s3'))) +check('wrong operand counts and modifiers are refused', all(refused(a) for a in ( + 's_bfm_b64 s[20:21], s2', 's_bfm_b64 s[20:21], s2, s3, s4', 's_bfm_b64 s[20:21]', 's_bfm_b64 s[20:21], s2, s3 clamp'))) +check('a source holding descriptor data is refused', + refused('s_bfm_b64 s[20:21], s2, s3', {2: ('desc', 0, 0, 0)})) +check('a well-formed pair is accepted (control for the refusals)', not refused('s_bfm_b64 s[20:21], s2, s3')) + +# ---- 7. mutations must read a wrong word ------------------------------------------------------------------------- +GRID = [(w, o) for w in (0, 1, 31, 32, 33, 63) for o in (0, 31, 32, 63)] + \ + [(0x40, 0), (0x41, 5), (0xffffffa1, 3), (32, 0x80), (3, 0x7f)] +base = translate('s_bfm_b64 s[20:21], s2, s3') + + +def mutated_wrong(stage_lines, common): + class S: + lines = stage_lines + return [(w, o) for w, o in GRID if evaluate(S, {'s2': w, 's3': o}, common) != pair(reference(w, o))] + + +line = base.lines[0] +check('control: the unmutated text has no wrong word on the mutation grid', not mutated_wrong(base.lines, COMMON)) +mutations = { + 'no mask on the width': ([re.sub(r'(uint bw = s2) & 63u', r'\1', line)], COMMON), + 'width masked with 31': ([line.replace('s2 & 63u', 's2 & 31u')], COMMON), + 'offset masked to five bits': (base.lines, COMMON.replace('sh &= 63u;', 'sh &= 31u;')), + 'width 0 reads all ones': ([line.replace('bw >= 32u ?', 'bw >= 32u || bw == 0u ?', 1)], COMMON), +} +for name, (lines, common) in mutations.items(): + changed = lines != base.lines or common != COMMON + wrong = mutated_wrong(lines, common) if changed else [] + check('mutation "%s" changes the text and reads a wrong word %s' % (name, wrong[:1]), changed and bool(wrong)) + +# ---- 8. lane-mask sources are refused before any destination state changes (maintainer review of #2007) ----------- +class TrackedStage(G.Stage): + """A stage with the #1931 uniformity state, driven instruction by instruction.""" + + def __init__(self): + self.lines, self.sym, self.masks = [], {}, set() + self.used_s, self.used_v = set(), set() + self.uniform_v, self.varying_s, self.scc_uniform = set(), set(), True + self.has_branches, self.exec_known = False, True + self.past_entry = False + self.uniform_expr = {} + self.defined_uniform_s, self.bad_sgprs = {4, 5}, set() + self.exports, self.attrs = {}, {} + self.pipe = Pipeline() + + def run(self, *instructions): + for asm in instructions: + self.one(asm.split()[0], asm) + # The exec copy's high word is a wave64 mask word (a numeric read of it is refused, #2702); this check is about + # the uniformity of the sources, which s3 keeps as a varying number, so the mask-word tag is dropped here. + self.mask_high = set() + return self + + +def snapshot(stage): + return (list(stage.lines), dict(stage.sym), set(stage.masks), set(stage.varying_s), set(stage.used_s)) + + +def refused_after(*instructions): + """True when the last instruction is refused after running the earlier ones on a tracked stage.""" + stage = TrackedStage().run(*instructions[:-1]) + try: + stage.run(instructions[-1]) + except G.Unsupported: + return True + return False + + +CMP = 'v_cmp_lt_f32_e64 %s, v0, v1' +for label, cmp_dst, bfm in ( + ('compare mask as width', 's2', 's_bfm_b64 s[20:21], s2, s3'), + ('compare mask as offset', 's3', 's_bfm_b64 s[20:21], s2, s3'), + ('compare mask as width, destination aliases it', 's20', 's_bfm_b64 s[20:21], s20, s3'), + ('compare mask as offset, destination aliases it', 's21', 's_bfm_b64 s[20:21], s2, s21'), + ('compare mask as both, destination aliases it', 's20', 's_bfm_b64 s[20:21], s20, s20')): + stage = TrackedStage().run(CMP % cmp_dst) + reg = int(cmp_dst[1:]) + before = snapshot(stage) + try: + stage.run(bfm) + refusal = None + except G.Unsupported as error: + refusal = str(error) + check('%s is refused' % label, refusal is not None and 'lane mask' in refusal, repr(refusal)) + check('%s: no HLSL, no state change' % label, snapshot(stage) == before and reg in stage.masks, + repr((before, snapshot(stage)))) +# Controls: the same shapes with a non-mask scalar are accepted, and the compare destination alone stays a mask. +for asm in ('s_bfm_b64 s[20:21], s2, s3', 's_bfm_b64 s[20:21], s20, s3', 's_bfm_b64 s[20:21], s2, s21'): + stage = TrackedStage().run(asm) + check('control: %s accepted without a mask source' % asm, 'shl64(' in ' '.join(stage.lines)) +# A mask destination (not a source) loses its flag: the pair is a number afterwards. +stage = TrackedStage().run(CMP % 's20', 's_bfm_b64 s[20:21], s2, s3') +check('a mask destination that is not a source loses its flag', 20 not in stage.masks and 21 not in stage.masks) + +# A lane mask in the high word of the destination pair is a number after the write (review of #2007, the survived +# mutation of `self.masks.discard(d + 1)`): s21 is a compare result, s_bfm_b64 overwrites s[20:21], and s21 is then +# read as a source. That read must be accepted and must use the word written by the first instruction. +stage = TrackedStage().run(CMP % 's21') +check('control: the compare result in s21 is a lane mask before the write', 21 in stage.masks) +check('control: reading s21 while it is still a lane mask is refused', refused_after(CMP % 's21', 's_bfm_b64 s[22:23], s2, s21')) +stage = TrackedStage().run(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3') +check('a lane mask in s[d+1] loses its flag when s_bfm_b64 writes the pair', 21 not in stage.masks and 20 not in stage.masks, + repr(stage.masks)) +check('s21 is read as a number after the write', not refused_after(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3', + 'v_mov_b32_e32 v7, s21', 's_bfm_b64 s[22:23], s2, s21')) +nit_stage = TrackedStage().run(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3', 's_bfm_b64 s[22:23], s2, s21') +# The compare line is HLSL over vector registers; run only the two scalar blocks. +env, interp = {'s2': 33, 's3': 31}, Interp(COMMON) +for line in [l for l in nit_stage.lines if 'shl64(' in l]: + interp.run(line, env) +check('evaluated: s[22:23] = bfm(33, high word of bfm(33, 31))', + (env['s22'], env['s23']) == pair(reference(33, pair(reference(33, 31))[1])), repr(env)) +# The mutation itself: the same lowering without `self.masks.discard(d + 1)` keeps s21 a lane mask, so the read is +# refused. The patched source is executed as a separate module; the check fails if the mutation does not apply. +SOURCE = open(os.path.join(here, '..', 'tools', 'startup', 'gfx2hlsl.py'), encoding='utf-8').read() +DISCARD = ' self.masks.discard(d + 1)\n' +body = SOURCE[SOURCE.index('def op_s_bfm_b64'):] +body = body[:body.index('\n def ', 10)] +check('mutation applies: op_s_bfm_b64 holds exactly one discard of d + 1', body.count(DISCARD) == 1) +mutant_source = SOURCE.replace(body, body.replace(DISCARD, '')) +check('mutation changes the source', mutant_source != SOURCE) +mutant = types.ModuleType('gfx2hlsl_mutant') +mutant.__file__ = G.__file__ +exec(compile(mutant_source, 'gfx2hlsl_mutant.py', 'exec'), mutant.__dict__) + + +class MutantStage(mutant.Stage): + __init__ = TrackedStage.__init__ + run = TrackedStage.run + + +for label, module_stage, expect_refused in (('unmutated', TrackedStage, False), ('without discard(d + 1)', MutantStage, True)): + try: + module_stage().run(CMP % 's21', 's_bfm_b64 s[20:21], s2, s3', 's_bfm_b64 s[22:23], s2, s21') + got_refused = False + except (G.Unsupported, mutant.Unsupported): + got_refused = True + check('%s: the number read of s21 after the write is %s' % (label, 'refused' if expect_refused else 'accepted'), + got_refused == expect_refused) + +# ---- 9. both written words carry a fresh uniformity proof (#1931) ---------------------------------------------------- +READ = 'v_readfirstlane_b32 s9, v7' +REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' + + +def read_word(stage, word): + """Copy s<word> into v7 and read it back: accepted only when the word is proven uniform.""" + try: + stage.run('v_mov_b32_e32 v7, s%d' % word, READ) + except G.Unsupported as error: + return str(error) + return 'accepted' + + +# `s_mov_b64 s[2:3], exec` leaves s2 a lane mask and s3 a varying number, a non-mask varying source. +VARYING = 's_mov_b64 s[2:3], exec' +PROVE = 's_bfm_b64 s[20:21], s4, s5' +stage = TrackedStage().run(PROVE) +check('uniform sources: both words are proven uniform', read_word(stage, 20) == 'accepted' and + read_word(TrackedStage().run(PROVE), 21) == 'accepted') +for label, bfm in (('width', 's_bfm_b64 s[20:21], s3, s5'), ('offset', 's_bfm_b64 s[20:21], s4, s3'), + ('width and offset', 's_bfm_b64 s[20:21], s3, s3')): + for word in (20, 21): + # control: the old proof exists, otherwise a refusal below would prove nothing + check('old proof for s%d exists before the %s overwrite' % (word, label), + read_word(TrackedStage().run(VARYING, PROVE), word) == 'accepted') + got = read_word(TrackedStage().run(VARYING, PROVE, bfm), word) + check('varying %s: the old proof for s%d is not used' % (label, word), got == REFUSAL, got) +# Destination aliasing a varying source: s21 is the varying high word of a saved exec. +for word in (20, 21): + got = read_word(TrackedStage().run('s_mov_b64 s[20:21], exec', 's_bfm_b64 s[20:21], s21, s5'), word) + check('aliased varying source: s%d is not proven uniform' % word, got == REFUSAL, got) +# A later uniform write brings the proof back, so the refusals above come from the writes. +for word in (20, 21): + got = read_word(TrackedStage().run(VARYING, 's_bfm_b64 s[20:21], s3, s5', PROVE), word) + check('control: a later uniform write re-proves s%d' % word, got == 'accepted', got) + stage = TrackedStage().run(VARYING, 's_bfm_b64 s[20:21], s3, s5', 's_bfm_b64 s[20:21], 5, 3') + check('control: constant sources re-prove s%d' % word, read_word(stage, word) == 'accepted') + +# ---- 10. desktop draw: the compiler's own shl64, select and uint2 handling, read back (review of #2007) ---------- +def container(parts): + """DXBC header (hash zeroed) followed by (fourcc, body) parts.""" + base = 32 + 4 * len(parts) + offsets, body = [], b'' + for fourcc, data in parts: + offsets.append(base + len(body)) + body += fourcc + struct.pack('<I', len(data)) + data + return b'DXBC' + bytes(16) + struct.pack('<III', 1, base + len(body), len(parts)) + struct.pack( + '<%dI' % len(offsets), *offsets) + body + + +# One root-constant parameter of two words: s8 (width) and s9 (offset) in both stages, run-time values the compiler +# cannot see. Layout as the checked-in parser reads it: version, parameter count, parameter table at byte 24, no +# samplers, then the (type 1, visibility 0, offset 36) entry and (register 0, space 0, count 2). +ROOT = container([(b'RTS0', struct.pack('<6I', 1, 1, 24, 0, 36, 0) + struct.pack('<3I', 1, 0, 36) + + struct.pack('<3I', 0, 0, 2))]) +VS_WORDS = bytes.fromhex( # the recorded full-screen triangle that exports param0 (tests/startup_flat_param_check.py) + 'ff02067e00004040' 'ff02147e000040c0' '8100847d' 'f3060202' '8200847d' 'f2140402' 'f202087e' '80020a7e' + '81020c7e' '82020e7e' 'ff02107e0100c07f' 'ff02127e01000080' 'cf0800f801020504' '0f0200f806070809' '000081bf') +VOP1_MOV = 1 + + +def ps_instructions(): + """s_bfm_b64 s[20:21], s8, s9; s_bfm_b64 s[22:23], s9, s8; v12..v15 = s20..s23; exp mrt0 v12..v15; s_endpgm.""" + words = [encode(20, 8, 9), encode(22, 9, 8)] + words += [struct.pack('<I', 0x7e000000 | (12 + i) << 17 | VOP1_MOV << 9 | (20 + i)) for i in range(4)] + words.append(bytes.fromhex('0f1800f80c0d0e0f' '000081bf')) + return b''.join(words) + + +DRAW_WIDTHS, DRAW_OFFSETS = (0, 1, 31, 32, 33, 63), (0, 1, 31, 32, 63) +# Source bits above [5:0] are ignored: 64 reads as 0, 0x41 as 1, 0xffffffa1 as 33, 0xffffff9f as 31. +DRAW_CASES = [(w, o) for w in DRAW_WIDTHS for o in DRAW_OFFSETS] + [(64, 0), (0x41, 0xc1), (0xffffffa1, 3), + (5, 0xffffff9f)] + + +def words_of(w, o): + """Expected export: s[20:21] = bfm(w, o), s[22:23] = bfm(o, w), each as the low word then the high word.""" + return pair(reference(w, o)) + pair(reference(o, w)) + + +def wrapped_reference(w, o): + """The wrong reference of the negative control: bits shifted past bit 63 wrap into the low word instead of + being dropped (a missing cap at bit 63).""" + width, offset = w & 63, o & 63 + full = ((1 << width) - 1) << offset + return (full & ((1 << 64) - 1)) | (full >> 64) + + +def wrapped_words(w, o): + return pair(wrapped_reference(w, o)) + pair(wrapped_reference(o, w)) + + +def text_of(values): + return ','.join('%08x' % v for v in values) + + +def draw_bfm(renderer, adapter, vs, ps, w, o, expected): + import subprocess + constants = {1: w & MASK, 2: o & MASK} # ud1, ud2 (ud0 is the rectangle switch and stays 0) + entry = text_of([constants.get(i, 0) for i in range(4)]) + run = subprocess.run([renderer, adapter, '--startup-flat-param', str(vs), str(ps), text_of(expected), entry], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + import tempfile + from pathlib import Path + sys.path.insert(0, here) + from startup_flat_param_check import compile_hlsl + pipe = G.Pipeline(VS_WORDS, ps_instructions(), ROOT) + check('draw: the entry constants sit at ud0 (rect) and ud1, ud2 (width, offset)', + pipe.uds[:3] == [('rect',), ('rootconst', 0, 0), ('rootconst', 0, 1)], repr(pipe.uds)) + vs_text, ps_text = pipe.hlsl_vs(), pipe.hlsl_ps() + mask_lines = [line for line in ps_text.splitlines() + if 'uint bw = ' in line and 'uint2 t = shl64(' in line] + check('draw: the pixel stage computes both pairs from run-time constants', + len(mask_lines) == 2 and 'bw = ud1 & 63u' in mask_lines[0] and ', ud2);' in mask_lines[0] + and 'bw = ud2 & 63u' in mask_lines[1] and ', ud1);' in mask_lines[1]) + mutated_text = ps_text.replace('bw >= 32u ?', 'bw >= 32u || bw == 0u ?') + check('draw: the mutated pixel stage differs from the translation', mutated_text != ps_text) + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, vs_text, 'vs_bfm_%s' % kind, vs_profile, directory) + good = compile_hlsl(compiler, kind, ps_text, 'ps_bfm_%s' % kind, ps_profile, directory) + bad = compile_hlsl(compiler, kind, mutated_text, 'ps_bfm_mutated_%s' % kind, ps_profile, directory) + for w, o in DRAW_CASES: + expected = words_of(w, o) + run = draw_bfm(renderer, adapter, vs, good, w, o, expected) + if run.returncode: + raise AssertionError('%s width %#x offset %#x expected %s\n%s\n%s' % ( + kind, w, o, text_of(expected), run.stdout, run.stderr)) + print('%s width %#x offset %#x: %s' % (kind, w, o, text_of(expected)), flush=True) + # Negative control 1: a reference without the cap at bit 63 must not match what the compiled code returns. + for w, o in ((33, 63), (63, 63), (33, 32), (63, 33)): + wrong = wrapped_words(w, o) + check('%s: the uncapped reference differs from the ISA reference for width %d offset %d' % (kind, w, o), + wrong != words_of(w, o)) + run = draw_bfm(renderer, adapter, vs, good, w, o, wrong) + real = 'actual=%s' % text_of(words_of(w, o)) + if run.returncode == 0 or real not in run.stderr: + raise AssertionError('%s uncapped reference was not rejected for width %d offset %d\n%s\n%s' % ( + kind, w, o, run.stdout, run.stderr)) + print('%s uncapped reference: fails as expected, reads %s' % (kind, text_of(words_of(w, o))), flush=True) + # Negative control 2: the mutated lowering (width 0 reads all ones) must read different words. + for w, o, got in ((0, 0, (0xffffffff, 0, 0xffffffff, 0)), (0, 5, (0xffffffe0, 0x1f, 0x1f, 0))): + run = draw_bfm(renderer, adapter, vs, bad, w, o, words_of(w, o)) + if run.returncode == 0 or 'actual=%s' % text_of(got) not in run.stderr: + raise AssertionError('%s mutated lowering did not read %s for width %d offset %d\n%s\n%s' % ( + kind, text_of(got), w, o, run.stdout, run.stderr)) + print('%s mutation (width 0 reads all ones): fails as expected, reads %s' % (kind, text_of(got)), flush=True) + + +if len(sys.argv) > 1: + if sys.argv[1] != 'draw' or len(sys.argv) not in (5, 6): + raise SystemExit(__doc__) + check_draw(*sys.argv[2:]) + +if failures: + print('FAIL') + for item in failures: + print(' ' + item) + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_bit_alu_check.py b/tests/startup_gfx2hlsl_bit_alu_check.py index 75f4e5e2a4..be2399c576 100644 --- a/tests/startup_gfx2hlsl_bit_alu_check.py +++ b/tests/startup_gfx2hlsl_bit_alu_check.py @@ -54,6 +54,7 @@ def ref_ffbh_i32(x): 'v_ffbh_u32': (1, True, lambda x: next((k for k in range(32) if x >> (31 - k) & 1), MASK)), 'v_ffbh_i32': (1, True, ref_ffbh_i32), 'v_bfrev_b32': (1, True, lambda x: int('{:032b}'.format(x)[::-1], 2)), + 'v_bfm_b32': (2, False, lambda w, o: (((1 << (w & 31)) - 1) << (o & 31)) & MASK), # D.u = ((1 << S0[4:0]) - 1) << S1[4:0] 'v_xor3_b32': (3, False, lambda x, y, z: x ^ y ^ z), # LLVM 15 VOP3 v_xor3_b32: D.u = S0.u ^ S1.u ^ S2.u } # mnemonic -> (pattern in the translated text, replacement): a wrong lowering of the same operation @@ -64,6 +65,8 @@ def ref_ffbh_i32(x): 'v_ffbh_u32': (r'31u - firstbithigh', 'firstbithigh'), # counts from the low end 'v_ffbh_i32': (r'asint\((v\d+)\) < 0 \? ~v\d+ : v\d+', r'\1'), # negative values scanned as is 'v_bfrev_b32': (r'reversebits\((v\d+)\)', r'\1'), # not reversed + 'v_bfm_b32': (r'\(\(\(1u << \((v\d+) & 31\)\) - 1\) << \((v\d+) & 31\)\)', + r'(((1u << (\2 & 31)) - 1) << (\1 & 31))'), # width and offset swapped 'v_xor3_b32': (r'(v\d+) \^ (v\d+) \^ v\d+', r'\1 ^ \2'), # the third operand is dropped } # mnemonic -> the word the mutated lowering must produce, defined from the mutation and the inputs with plain integer @@ -75,6 +78,7 @@ def ref_ffbh_i32(x): 'v_ffbh_u32': lambda x: MASK if x == 0 else x.bit_length() - 1, 'v_ffbh_i32': lambda x: MASK if x in (0, MASK) else 32 - x.bit_length(), 'v_bfrev_b32': lambda x: x, + 'v_bfm_b32': lambda w, o: (((1 << (o & 31)) - 1) << (w & 31)) & MASK, 'v_xor3_b32': lambda x, y, z: x ^ y, } SPECIAL = [0, 1, 2, 3, 0x7f, 0x80, 0xff, 0x7fffffff, 0x80000000, 0x80000001, 0xfffffffe, MASK, 0x55555555, @@ -85,6 +89,7 @@ def ref_ffbh_i32(x): 'v_bfe_i32': [(x, off, w) for x in SPECIAL for off in range(32) for w in range(32)] + [(x, off, w) for x in SPECIAL for off, w in ((32, 33), (63, 0xffffffe5), (0x25, 0x1f))], 'v_bcnt_u32_b32': [(x, y, 0) for x in BITS for y in (0, 1, 32, MASK)], + 'v_bfm_b32': [(w, o, 0) for w in list(range(34)) + [0x3f, 0x40, 0xffffffe0, MASK] for o in list(range(34)) + [0x3f, MASK]], 'v_xor3_b32': [(x, y, z) for x in XOR3_WORDS for y in XOR3_WORDS for z in XOR3_WORDS], } for _name, (_arity, _vop1, _ref) in OPS.items(): @@ -98,6 +103,7 @@ def ref_ffbh_i32(x): (0x55555555, 0, 0), (0, MASK, 0), (0xf0f0f0f0, 7, 0), (0x00010000, 0x80000000, 0)], # Three different sources in every byte (13/24/fe, 57/68/dc, 9b/ac/ba, df/e0/98), so dropping any one source, # or OR, AND or an add for the XOR, reads a different word; the other sets check zero, all ones and a repeat. + 'v_bfm_b32': [(8, 4, 0), (31, 1, 0), (32, 5, 0), (33, 31, 0), (0, 0, 0), (1, 31, 0), (0x25, 0x3f, 0), (MASK, MASK, 0)], 'v_xor3_b32': [(0x13579bdf, 0x2468ace0, 0xfedcba98), (0x2468ace0, 0xfedcba98, 0x13579bdf), (0xfedcba98, 0x13579bdf, 0x2468ace0), (0x0f0f0f0f, 0xa5c30f96, 0x80000001), (0, 0, 0), (MASK, MASK, MASK), (0x13579bdf, 0x13579bdf, 0x2468ace0), (0, 0xdeadbeef, MASK)], @@ -123,6 +129,8 @@ def ref_ffbh_i32(x): '0077187e0d00bbd50101000002771c7e0f00bbd503010000'), 'v_bfrev_b32': bytes.fromhex( '0071187e0d00b8d50101000002711c7e0f00b8d503010000'), + 'v_bfm_b32': bytes.fromhex( + '0c0063d7000902000d0063d7010b02000e0063d7020d02000f0063d7030f0200'), 'v_xor3_b32': bytes.fromhex( '0c0078d5000922040d0078d5010b26040e0078d5020d2a040f0078d5030f2e04'), } @@ -360,6 +368,9 @@ def controls(): check('the same forms without a modifier or operand error translate', not any(refused(a) for a in ( 'v_ffbh_i32_e64 v1, v2', 'v_bfe_i32 v1, v2, v3, v4', 'v_bcnt_u32_b32 v1, v2, v3', 'v_bfrev_b32 v1, v2', 'v_xor3_b32 v1, v2, v3, v4'))) + check('v_bfm_b32 has no VOP2 spelling: _e32 refused, _e64 and the bare name translate', + refused('v_bfm_b32_e32 v1, v2, v3') and not refused('v_bfm_b32_e64 v1, v2, v3') + and not refused('v_bfm_b32 v1, v2, v3')) check('modifiers refused', all(refused(a) for a in ( 'v_ffbh_u32_e64 v1, v2 clamp', 'v_bfe_i32 v1, v2, v3, v4 clamp', 'v_bcnt_u32_b32 v1, v2, v3 clamp', 'v_ffbl_b32_e64 v1, v2 mul:2', 'v_bfrev_b32_e64 v1, -v2', 'v_ffbh_i32_e64 v1, |v2|', diff --git a/tests/startup_gfx2hlsl_buffer_store_check.py b/tests/startup_gfx2hlsl_buffer_store_check.py index dd4e6a1790..fa75e9892e 100644 --- a/tests/startup_gfx2hlsl_buffer_store_check.py +++ b/tests/startup_gfx2hlsl_buffer_store_check.py @@ -212,8 +212,8 @@ def main(): '%s %s' % (result, fail_reason(name))) # 8. The cache revision moved, so a translation from before the store lowering is never loaded. - check('cache key uses revision 17', G.pipeline_key(b'a', b'b', ROOT) == - G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-17'))))) + check('cache key uses revision 29', G.pipeline_key(b'a', b'b', ROOT) == + G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-29'))))) if failures: print('FAILED: ' + ', '.join(failures)) diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py new file mode 100644 index 0000000000..5ca0ede59b --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -0,0 +1,743 @@ +"""image_bvh_intersect_ray: the FP32 and binary16 box-node translation slice. + +The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the +box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant +node base whose low three bits are 4 (binary16) or 5 (FP32), and the four child results. +The triangle kinds have a dedicated check. The 64-bit form, A16, NSA and every dynamic +descriptor or node base are refused by name before any HLSL is emitted. The independent CPU box reference is +tests/gfx1030_bvh_box/bvh_model.py; the Windows dispatch exercises both emitted helpers. +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +from gfx1030_bvh_box import bvh_model as B # noqa: E402 + +INVALID = 0xffffffff +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +MASK = 0xffffffff +FLT_MAX = 3.4028234663852886e38 + + +def box(child, depth, x=-8): + return child, (x, -8, depth), (x + 16, 8, depth + 0.5) + + +NODES = { + 0: (box(0x25, 4), box(0x1d, 1), box(0x2d, 2, x=32), box(INVALID, 3)), + 256: (box(0x45, 7), box(0x3d, 5), box(0x35, 3), box(0x0d, 1)), + 384: (box(0x25, 4), box(INVALID, 1), box(0x2d, 2), box(0x35, 3)), + # A finite hit at FLT_MAX must sort ahead of misses (key +infinity). + 512: (box(INVALID, 1), (0x4d, (FLT_MAX,) * 3, (FLT_MAX,) * 3), + box(0x55, 2, x=32), box(INVALID, 3)), +} +ORIGIN = (0.5, -0.5, -1.0) +FORWARD = (0.25, -0.125, 0.5) +RAYS = ( + ("sorted", 0, 19.0, ORIGIN, FORWARD, (0x1d, 0x25, INVALID, INVALID)), + ("clipped", 0, 6.0, ORIGIN, FORWARD, (0x1d, INVALID, INVALID, INVALID)), + ("all_miss", 0, 2.0, ORIGIN, FORWARD, (INVALID,) * 4), + ("all_four", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), + ("reverse", 0, 21.0, (0.0, 0.0, 10.0), (0.25, -0.125, -0.5), (0x25, 0x1d, INVALID, INVALID)), + ("finite_max", 512, math.inf, (0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (0x4d, INVALID, INVALID, INVALID)), + ("encoded_base_low_bits", 0, 19.0, ORIGIN, FORWARD, (0x1d, 0x25, INVALID, INVALID)), + ("encoded_base_high_byte", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), +) +UNSORTED_RAYS = ( + ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, INVALID, 0x2d, 0x35)), + ("unsorted_mixed", 0, 19.0, ORIGIN, FORWARD, (0x25, 0x1d, INVALID, INVALID)), + ("unsorted_finite_max", 512, math.inf, (0.0, 0.0, 0.0), (1.0, 1.0, 1.0), + (INVALID, 0x4d, INVALID, INVALID)), +) +DESCRIPTOR_BASES = { + "encoded_base_low_bits": (0x1008, 0), + "encoded_base_high_byte": (0, 0x81), +} +# The independent model reads the binary16 node in 64-byte units. The FLT_MAX +# fixture has no binary16 encoding, so it has no half copy. +HALF_OFFSETS = {0: 640, 256: 704, 384: 768} +HALF_ROUND_OFFSET = 832 +RESULT_OFFSET = 896 +RESULT_WORD = RESULT_OFFSET // 4 + + +def half(value): + return struct.unpack("<e", struct.pack("<e", value))[0] + + +def half_nodes(nodes): + """The same nodes with every bound rounded to binary16 before the box test.""" + return tuple((child, tuple(half(value) for value in lo), tuple(half(value) for value in hi)) + for child, lo, hi in nodes) + + +HALF_NODES = {offset: half_nodes(NODES[offset]) for offset in HALF_OFFSETS} +HALF_NODE_BY_OFFSET = {HALF_OFFSETS[offset]: HALF_NODES[offset] for offset in HALF_OFFSETS} +# A bound only representable in binary32: 1.1 rounds to 1.099609375 in binary16. A ray +# extent between the two values hits the half node and misses the FP32 node. +HALF_ROUND_NODES = half_nodes(( + (0x25, (1.1, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), +)) +HALF_NODE_BY_OFFSET[HALF_ROUND_OFFSET] = HALF_ROUND_NODES +HALF_DESCRIPTOR_BASES = { + "box16_encoded_base_low_bits": (0x1008, 0), + "box16_encoded_base_high_byte": (0, 0x81), +} + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def node_bytes(): + data = bytearray(RESULT_OFFSET) + for offset, nodes in NODES.items(): + struct.pack_into("<4I", data, offset, *(child for child, _, _ in nodes)) + for i, (_, lo, hi) in enumerate(nodes): + struct.pack_into("<6f", data, offset + 16 + 24 * i, *lo, *hi) + for base, nodes in list(HALF_NODE_BY_OFFSET.items()): + struct.pack_into("<4I", data, base, *(child for child, _, _ in nodes)) + for i, (_, lo, hi) in enumerate(nodes): + struct.pack_into("<6e", data, base + 16 + 12 * i, *lo, *hi) + return data + + +def reference(offset, extent, origin, direction, sort_boxes, kind=5): + """Use the independent model on bytes relative to the bound allocation.""" + return tuple(B.intersect( + node_bytes(), B.descriptor(sort=sort_boxes), (offset >> 3) | kind, + extent=extent, origin=origin, direction=direction, + inverse=tuple(1.0 / c for c in direction))) + + +def model(nodes, extent, origin, direction, sort_boxes): + """The emitted HLSL helper, transcribed: four slabs, keys, five compare-exchange stages.""" + inv = [max(-FLT_MAX, min(1.0 / c, FLT_MAX)) for c in direction] + items = [] + for child, lo, hi in nodes: + if child == INVALID: + items.append([INVALID, math.inf]) + continue + bound0 = [(lo[i] - origin[i]) * inv[i] for i in range(3)] + bound1 = [(hi[i] - origin[i]) * inv[i] for i in range(3)] + tmin = max(min(bound0[i], bound1[i]) for i in range(3)) + tmax = min(max(bound0[i], bound1[i]) for i in range(3)) + hit = not math.isnan(lo[0]) and tmax >= max(0.0, tmin) and tmin < extent + if hit: + items.append([child, tmin if sort_boxes else 0.0]) + else: + items.append([INVALID, math.inf]) + if not sort_boxes: + return tuple(child for child, _key in items) + for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + if items[b][1] < items[a][1]: + items[a], items[b] = items[b], items[a] + return tuple(item[0] for item in items) + + +HALF_RAYS = tuple( + ("box16_" + name, HALF_OFFSETS[offset], extent, origin, direction, + reference(HALF_OFFSETS[offset], extent, origin, direction, True, 4)) + for name, offset, extent, origin, direction, _expected in RAYS + if name not in DESCRIPTOR_BASES and offset in HALF_OFFSETS +) + ( + ("box16_rounded_bound", HALF_ROUND_OFFSET, 1.0998, (0.0, 0.0, 0.0), (1.0, 1e-6, 1e-6), + (0x25, INVALID, INVALID, INVALID)), + ("box16_encoded_base_low_bits", HALF_OFFSETS[0], 19.0, ORIGIN, FORWARD, + reference(HALF_OFFSETS[0], 19.0, ORIGIN, FORWARD, True, 4)), + ("box16_encoded_base_high_byte", HALF_OFFSETS[256], 19.0, ORIGIN, FORWARD, + reference(HALF_OFFSETS[256], 19.0, ORIGIN, FORWARD, True, 4)), +) +HALF_UNSORTED_RAYS = tuple( + ("box16_" + name, HALF_OFFSETS[offset], extent, origin, direction, + reference(HALF_OFFSETS[offset], extent, origin, direction, False, 4)) + for name, offset, extent, origin, direction, _expected in UNSORTED_RAYS + if offset in HALF_OFFSETS +) + + +def dispatch_cases(): + cases = [] + for name, offset, extent, origin, direction, expected in RAYS: + base0, base1 = DESCRIPTOR_BASES.get(name, (0x1000, 0)) + cases.append(dict(name=name, helper="x2w_bvh_intersect_box32", pointer=(offset >> 3) | 5, + word0=base0, word1=base1 | SORT_ENABLE, word2=0x0b, + extent=extent, origin=origin, direction=direction, expected=expected)) + for name, offset, extent, origin, direction, expected in UNSORTED_RAYS: + cases.append(dict(name=name, helper="x2w_bvh_intersect_box32", pointer=(offset >> 3) | 5, + word0=0x1000, word1=0, word2=0x0b, + extent=extent, origin=origin, direction=direction, expected=expected)) + for name, offset, extent, origin, direction, expected in HALF_RAYS: + base0, base1 = HALF_DESCRIPTOR_BASES.get(name, (0x1000, 0)) + cases.append(dict(name=name, helper="x2w_bvh_intersect_box16", pointer=(offset >> 3) | 4, + word0=base0, word1=base1 | SORT_ENABLE, word2=0x40, + extent=extent, origin=origin, direction=direction, expected=expected)) + for name, offset, extent, origin, direction, expected in HALF_UNSORTED_RAYS: + cases.append(dict(name=name, helper="x2w_bvh_intersect_box16", pointer=(offset >> 3) | 4, + word0=0x1000, word1=0, word2=0x40, + extent=extent, origin=origin, direction=direction, expected=expected)) + # A T# can cover both box and triangle nodes; box kinds ignore the triangle return mode + # bit. These cases fail if either the translator or the emitted box helper rejects it. + name, offset, extent, origin, direction, expected = RAYS[0] + cases.append(dict(name="box32_return_mode_ignored", helper="x2w_bvh_intersect_box32", + pointer=(offset >> 3) | 5, word0=0x1000, word1=SORT_ENABLE, word2=0x0b, + word3=RESOURCE_TYPE | 0x01000000, extent=extent, origin=origin, + direction=direction, expected=expected)) + name, offset, extent, origin, direction, expected = HALF_RAYS[0] + cases.append(dict(name="box16_return_mode_ignored", helper="x2w_bvh_intersect_box16", + pointer=(offset >> 3) | 4, word0=0x1000, word1=SORT_ENABLE, word2=0x40, + word3=RESOURCE_TYPE | 0x01000000, extent=extent, origin=origin, + direction=direction, expected=expected)) + return cases + + +BUFFER_SIZE = RESULT_OFFSET + 16 * len(dispatch_cases()) + + +def translate_program(*, node=0x05, sort_boxes=True, word0=0x1000, word1=None, word2=0x0b, + word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", + constant_node=True, stage_kind="cs"): + """A straight-line compute program with a constant inline T# and a constant node pointer.""" + if word1 is None: + word1 = SORT_ENABLE if sort_boxes else 0 + if stage_kind != "cs": + class Probe: + kind = stage_kind + try: + G.Stage.op_image_bvh_intersect_ray(Probe(), ("v[32:35]", "v[16:31]", "s[12:15]"), []) + except G.Unsupported as error: + return None, None, [str(error)] + return None, None, ["accepted outside compute"] + decoded = [] + at = 0 + + def add(name, asm, length=8): + nonlocal at + decoded.append((at, length, name, asm)) + at += length + + if loaded_descriptor: + add("s_mov_b32", "s_mov_b32 s10, s6") + add("s_mov_b32", "s_mov_b32 s11, 0") + add("s_load_dwordx4", "s_load_dwordx4 s[12:15], s[10:11], 0x0", 16) + add("s_waitcnt", "s_waitcnt lgkmcnt(0)", 4) + else: + for reg, word in ((12, word0), (13, word1), (14, word2), (15, word3)): + add("s_mov_b32", "s_mov_b32 s%d, 0x%08x" % (reg, word)) + for reg, word in ((16, node), (17, 0x41a00000), (18, 0x3f000000), (19, 0xbf000000), + (20, 0xbf800000), (21, 0x3e800000), (22, 0xbe000000), (23, 0x3f000000), + (24, 0x40800000), (25, 0xc1000000), (26, 0x40000000)): + source = "s4" if reg == 16 and not constant_node else "0x%08x" % word + add("v_mov_b32", "v_mov_b32 v%d, %s" % (reg, source)) + add(opcode, "%s v[32:35], v[16:31], s[12:15]%s" % (opcode, (" " + modifier) if modifier else "")) + add("s_endpgm", "s_endpgm", 4) + refusals = [] + pipe = G.ComputePipeline(b"", C.root_blob(), C.USER7, (1, 1, 1), refusals=refusals, decoded=decoded) + return pipe, pipe.hlsl_cs(), [reason for reason, _kind in refusals] + + +def controls(): + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = reference(offset, extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("independent public box model matches sorted fixture expectations", bad is None, str(bad)) + + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = model(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("transcribed helper model matches independent CPU reference", bad is None, str(bad)) + + # Negative control: sort disabled keeps child order. The sorted ray's first word changes. + unsorted = reference(0, 19.0, ORIGIN, FORWARD, False) + sorted_result = reference(0, 19.0, ORIGIN, FORWARD, True) + check("sort bit negative control changes word 0", + unsorted[0] == 0x25 and sorted_result[0] == 0x1d, str((unsorted, sorted_result))) + check("model without the sort bit matches the unsorted reference", + model(NODES[0], 19.0, ORIGIN, FORWARD, False) == unsorted, + str((model(NODES[0], 19.0, ORIGIN, FORWARD, False), unsorted))) + for name, offset, extent, origin, direction, expected in UNSORTED_RAYS: + actual = reference(offset, extent, origin, direction, False) + check("CPU reference keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) + actual = model(NODES[offset], extent, origin, direction, False) + check("helper keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) + check("all-miss result is four 0xffffffff words", + reference(0, 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") + + bad = None + for name, offset, extent, origin, direction, expected in HALF_RAYS: + actual = model(HALF_NODE_BY_OFFSET[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("transcribed box16 model matches the half-packed reference", bad is None, str(bad)) + + bad = None + for name, offset, extent, origin, direction, expected in HALF_UNSORTED_RAYS: + actual = model(HALF_NODE_BY_OFFSET[offset], extent, origin, direction, False) + if actual != expected: + bad = (name, actual, expected) + break + check("transcribed box16 model keeps child order when unsorted", bad is None, str(bad)) + check("binary16 bound rounds below the ray extent", + reference(HALF_ROUND_OFFSET, 1.0998, (0.0, 0.0, 0.0), (1.0, 1e-6, 1e-6), True, 4) + == (0x25, INVALID, INVALID, INVALID), "") + fp32_round = model(((0x25, (1.1, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0)), + (INVALID, (-2.0, -2.0, -2.0), (2.0, 2.0, 2.0))), + 1.0998, (0.0, 0.0, 0.0), (1.0, 1e-6, 1e-6), True) + check("binary32 bound at 1.1 misses the same extent", fp32_round[0] == INVALID, str(fp32_round)) + + pipe, hlsl, refusals = translate_program() + check("constant box32 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + check("manifest names the node allocation", "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("HLSL declares the node buffer", "ByteAddressBuffer r0 : register(t0);" in hlsl, "") + check("HLSL contains the box32 helper", + "uint4 x2w_bvh_intersect_box32" in hlsl and "x2w_bvh_box32_slot" in hlsl, "") + check("the call carries the sort-enabled T# word and four child results", + "0x80000000u" in hlsl and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), + "") + call_line = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + check("constant T# passes literals, not descriptor SGPRs", + "0x00001000u, 0x80000000u, 0x0000000bu, 0x80000000u" in call_line + and "s12" not in call_line and "s13" not in call_line, call_line) + + pipe, hlsl, refusals = translate_program(sort_boxes=False) + check("sort-disabled box32 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + check("sort-disabled box32 call uses a zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" in call, call) + + pipe, hlsl, refusals = translate_program(node=0x04) + check("constant box16 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + check("HLSL contains the box16 helper", + "uint4 x2w_bvh_intersect_box16" in hlsl and "x2w_bvh_box16_slot" in hlsl + and "f16tof32" in hlsl, "") + call_line = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box16(r0" in line), "") + check("box16 call carries the node and four child results", + "0x00000004u" in call_line + and "0x00001000u, 0x80000000u, 0x0000000bu, 0x80000000u" in call_line + and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + + pipe, hlsl, refusals = translate_program(node=0x04, sort_boxes=False) + check("sort-disabled box16 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box16(r0" in line), "") + check("sort-disabled box16 call uses a zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" in call, call) + + # One T# can cover both node types, so a box node ignores the triangle return mode bit. + for node, helper in ((0x05, "x2w_bvh_intersect_box32"), (0x04, "x2w_bvh_intersect_box16")): + pipe, hlsl, refusals = translate_program(node=node, word3=RESOURCE_TYPE | 0x01000000) + check("box kind %d with triangle return mode bit translates" % (node & 7), + pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if helper + "(r0" in line), "") + check("box kind %d call preserves the ignored return mode bit" % (node & 7), + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call, call) + + # Independently decode the 40-bit unit field; test the same raw DWORDs in + # the emitted call and the decoded byte-address binding in the manifest. + for units, high, base in ((0x1000, 0, 0x100000), (0x1008, 0, 0x100800), + (0, 0x81, 0x810000000000)): + words = (units, high | SORT_ENABLE, 0x0b, RESOURCE_TYPE) + check("public model decodes base %#x" % base, + B.node_address(words, 5) == (5, base), str(B.node_address(words, 5))) + pipe, hlsl, refusals = translate_program(node=0x25, word0=words[0], word1=words[1]) + check("encoded base %#x translates" % base, pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + literal_words = ", ".join("0x%08xu" % word for word in words) + check("manifest uses byte base %#x" % base, "srv 0 bvh base %#x size 0xb" % base in manifest, manifest) + check("call preserves all four descriptor DWORDs at %#x" % base, literal_words in call, call) + + for units, high, base in ((0x1008, 0, 0x100800), (0, 0x81, 0x810000000000)): + words = (units, high | SORT_ENABLE, 0x0b, RESOURCE_TYPE) + pipe, hlsl, refusals = translate_program(node=0x04, word0=words[0], word1=words[1]) + check("box16 encoded base %#x translates" % base, pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box16(r0" in line), "") + literal_words = ", ".join("0x%08xu" % word for word in words) + check("box16 manifest uses byte base %#x" % base, + "srv 0 bvh base %#x size 0xb" % base in manifest, manifest) + check("box16 call preserves all four descriptor DWORDs at %#x" % base, literal_words in call, call) + + # The model wraps the absolute node address at 48 bits. The raw-bound + # helper cannot represent that wrap, so the translator must refuse it. + words = (0xffffffff, SORT_ENABLE | 0xff, 0x0b, RESOURCE_TYPE) + check("public model wraps the node address", B.node_address(words, 0x25) == (5, 0), + str(B.node_address(words, 0x25))) + pipe, boundary_hlsl, refusals = translate_program(node=0x15, word0=words[0], word1=words[1]) + check("box32 node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_program(node=0x25, word0=words[0], word1=words[1]) + check("refuses a box32 48-bit wrap before resource binding", + refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] + and " bvh base " not in pipe.manifest() + and "x2w_bvh_intersect_box32" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + pipe, boundary_hlsl, refusals = translate_program(node=0x15, word0=words[0], word1=words[1]) + check("box16 node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_program(node=0x54, word0=words[0], word1=words[1]) + check("refuses a box16 48-bit wrap before resource binding", + refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] + and " bvh base " not in pipe.manifest() + and "x2w_bvh_intersect_box16" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + + # Size is a count minus one in 64-byte units. These are exact fits and one unit short. + for node, word2, label in ((0x04, 0, "box16 at offset zero in a one-unit span"), + (0x05, 1, "box32 at offset zero in a two-unit span"), + (0x0c, 1, "box16 in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + for node, word2, label in ((0x05, 0, "box32 at offset zero in a one-unit span"), + (0x0c, 0, "box16 in the last unit of a one-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("too-short %s refuses" % label, + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + + # Portable checks ensure the actual emitted helpers and every negative + # mutation are present even when a GPU dispatch is unavailable. + pipe, hlsl, refusals = translate_program(node=0x04) + helpers = "\n".join(G.BVH_HELPERS) + check("translated shader embeds both dispatch-tested helpers", pipe is not None and helpers in hlsl, "") + for mutation in MUTATIONS: + dispatch_hlsl(mutation) + + # Every refusal must happen before a helper call or a result VGPR is emitted. + cases = [ + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), + ("non-constant node", dict(constant_node=False), "non-constant node base"), + ("64-bit form", dict(opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(modifier="a16"), "modifier a16"), + ("NSA address", dict(modifier=""), "non-sequential"), + ("loaded descriptor", dict(loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("reserved word 1", dict(word1=SORT_ENABLE | 0x100), "reserved word 1"), + ("box32 size zero", dict(word2=0), "outside descriptor size"), + ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), + ("box16 node outside size", dict(node=0x54, word2=9), "outside descriptor size"), + ("absolute base", dict(word0=0, word1=0), "absolute node base"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + # A non-sequential address is a text form the packed decoder never prints. + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 5})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_program(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_box32(r" not in hlsl + and "x2w_bvh_intersect_box16(r" not in hlsl, "") + + pipe, hlsl, refusals = translate_program(stage_kind="ps") + check("refuses a pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_box.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack("<I", struct.pack("<f", value))[0] + + +def fbits(value): + return "0x%08xu" % struct.unpack("<I", struct.pack("<f", value))[0] + + +MUTATIONS = { + "miss_fill": ("all_miss", tuple( + ("c%d = h%d ? c%d : X2W_BVH_MISS;" % (i, i, i), "c%d = c%d;" % (i, i)) for i in range(4))), + "compact": ("box16_unsorted_three_hits", ( + ("if (!sort_boxes) return uint4(c0, c1, c2, c3);", + "if (!sort_boxes) { uint4 ordered = miss; uint n = 0u; " + "if (h0) ordered[n++] = c0; if (h1) ordered[n++] = c1; " + "if (h2) ordered[n++] = c2; if (h3) ordered[n++] = c3; return ordered; }"),)), + "finite_miss": ("finite_max", tuple( + ("float k%d = h%d ? d%d : asfloat(0x7f800000u);" % (i, i, i), + "float k%d = h%d ? d%d : 3.402823466e+38;" % (i, i, i)) for i in range(4))), + "box16_miss_fill": ("box16_all_miss", tuple( + ("c%d = h%d ? c%d : X2W_BVH_MISS;" % (i, i, i), "c%d = c%d;" % (i, i)) for i in range(4))), + "base_alignment": ("encoded_base_low_bits", ( + ("return (word1 & 0x7fffff00u) == 0u &&", + "return (word0 & 0xffu) == 0u && (word1 & 0x7fffff00u) == 0u &&"),)), + "high_byte": ("encoded_base_high_byte", ( + ("(word0 != 0u || (word1 & 0x000000ffu) != 0u)", "(word0 != 0u)"),)), +} + + +def dispatch_hlsl(mutation=None): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + if mutation: + for old, new in MUTATIONS[mutation][1]: + assert helpers.count(old) >= 1, (mutation, old) + helpers = helpers.replace(old, new) + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for base_offset, children in NODES.items(): + for i, (child, lo, hi) in enumerate(children): + lines.append(" data.Store(%du, 0x%08xu);" % (base_offset + 4 * i, child)) + for j in range(3): + lines.append(" data.Store(%du, %s);" % (base_offset + 16 + 24 * i + 4 * j, fbits(lo[j]))) + lines.append(" data.Store(%du, %s);" % (base_offset + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) + for i in range(4): + lines.append(" data.Store(%du, 0u);" % (base_offset + 112 + 4 * i)) + for base_offset, children in HALF_NODE_BY_OFFSET.items(): + for i, (child, lo, hi) in enumerate(children): + lines.append(" data.Store(%du, 0x%08xu);" % (base_offset + 4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (base_offset + 16 + 12 * i + 4 * j, word)) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + for case, item in enumerate(dispatch_cases()): + inv = tuple(1.0 / c for c in item["direction"]) + lines.append( + " uint4 r%d = %s(data, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, " + "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, item["helper"], item["pointer"], item["word0"], item["word1"], item["word2"], + item.get("word3", 0x80000000), + ffloat(item["extent"]), ffloat(item["origin"][0]), ffloat(item["origin"][1]), + ffloat(item["origin"][2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +BOUNDARY_BOX32_OFFSET = 128 +BOUNDARY_RESULT_OFFSET = 256 +BOUNDARY_BUFFER_SIZE = 320 + + +def boundary_hlsl(): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i, (child, lo, hi) in enumerate(HALF_NODES[0]): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (16 + 12 * i + 4 * j, word)) + for i, (child, lo, hi) in enumerate(NODES[0]): + base = BOUNDARY_BOX32_OFFSET + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, child)) + for j in range(3): + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 4 * j, fbits(lo[j]))) + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) + for j in range(4): + lines.append(" data.Store(%du, 0u);" % (base + 112 + 4 * j)) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + box16_ray = HALF_RAYS[0] + box32_ray = RAYS[0] + cases = ( + (0, "x2w_bvh_intersect_box16", 0x04, 0, box16_ray[2:5], box16_ray[-1]), + (1, "x2w_bvh_intersect_box16", 0x0c, 0, box16_ray[2:5], (INVALID,) * 4), + (2, "x2w_bvh_intersect_box32", 0x15, 3, box32_ray[2:5], box32_ray[-1]), + (3, "x2w_bvh_intersect_box32", 0x15, 2, box32_ray[2:5], (INVALID,) * 4), + ) + expected = [] + for case, helper, pointer, word2, ray, result in cases: + extent, origin, direction = ray + inv = tuple(1.0 / c for c in direction) + lines.append( + " uint4 b%d = %s(data, 0x%08xu, 0x1000u, 0x80000000u, 0x%08xu, 0x80000000u, " + "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, helper, pointer, word2, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, b%d.%s);" % (BOUNDARY_RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) + expected.append(result) + lines.append("}") + return "\n".join(lines) + "\n", expected + + +def run_boundary_dispatch(dxc, runner, adapter, directory): + source = directory / "bvh_boundary.hlsl" + cso = directory / "bvh_boundary.cso" + output = directory / "bvh_boundary.bin" + hlsl, expected = boundary_hlsl() + source.write_text(hlsl, encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(BOUNDARY_BUFFER_SIZE), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None, expected + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == BOUNDARY_BUFFER_SIZE, (len(data), BOUNDARY_BUFFER_SIZE) + return 0, struct.unpack("<%dI" % (len(data) // 4), data), expected + + +def run_dispatch(dxc, runner, adapter, directory, mutation=None): + name = "bvh_dispatch_" + mutation if mutation else "bvh_dispatch" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutation), encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(BUFFER_SIZE), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == BUFFER_SIZE, (len(data), BUFFER_SIZE) + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if failures: + return 1 + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + cases = dispatch_cases() + for case, item in enumerate(cases): + start = RESULT_WORD + 4 * case + got = tuple(words[start:start + 4]) + check("dispatch case %d %s" % (case, item["name"]), got == item["expected"], + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in item["expected"]])) + for mutation, (witness, _replacements) in MUTATIONS.items(): + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutation=mutation) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + case = next(i for i, item in enumerate(cases) if item["name"] == witness) + start = RESULT_WORD + 4 * case + changed = tuple(mutant[start:start + 4]) + check("dispatch %s control changes %s" % (mutation, witness), changed != cases[case]["expected"], + "got %s" % ["%08x" % w for w in changed]) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("decoded descriptor extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_program() + assert not refusals, refusals + compile_check(hlsl) + pipe, hlsl, refusals = translate_program(node=0x04) + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh box32/box16: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py new file mode 100644 index 0000000000..792e61fcb5 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -0,0 +1,394 @@ +"""image_bvh_intersect_ray: the triangle-node (kinds 0..3) translation slice. + +The instruction is RDNA 2 MIMG opcode 230. A triangle node is 64 bytes: five float3 vertices +and one ID dword. This check covers the translator, the watertight ray/triangle test and the +four-word return `{t, determinant, v, w}` for triangle return mode 1. The independent model is +tests/gfx1030_bvh_box/bvh_model.py; the dispatch runs the emitted helper on WARP or hardware. +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE / "gfx1030_bvh_box")) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_bvh_check as BOX # noqa: E402 +import check as F # noqa: E402 +from gfx1030_bvh_box import bvh_model as B # noqa: E402 + +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +TRIANGLE_MODE = 1 << 24 +TRIANGLES = tuple(case for case in F.WITNESSES if case.name.startswith("tri/") and not case.wide) + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def translate_triangle(node, **kwargs): + kwargs.setdefault("word3", RESOURCE_TYPE | TRIANGLE_MODE) + return BOX.translate_program(node=node, **kwargs) + + +def controls(): + bad = None + for case in TRIANGLES: + origin, direction, inverse, extent = case.ray + actual = tuple(B.intersect( + bytearray(case.image), B.descriptor(0, sort=True), case.pointer, + origin=origin, direction=direction, inverse=inverse, extent=extent)) + if actual != case.expected: + bad = (case.name, actual, case.expected) + break + check("independent model matches every triangle fixture", bad is None, str(bad)) + + for kind in range(4): + pipe, hlsl, refusals = translate_triangle(kind) + check("triangle kind %d translates" % kind, pipe is not None and not refusals, str(refusals)) + if pipe is None: + continue + manifest = pipe.manifest() + check("triangle kind %d manifest names the node allocation" % kind, + "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("triangle kind %d HLSL contains the helper" % kind, + "uint4 x2w_bvh_intersect_triangle" in hlsl and "x2w_bvh_triangle_vertex" in hlsl + and "x2w_bvh_shear" in hlsl, "") + call_line = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_triangle(r0" in line), "") + check("triangle kind %d call carries all four descriptor DWORDs" % kind, + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call_line, call_line) + check("triangle kind %d call carries the node and four results" % kind, + "0x0000000%du" % kind in call_line + and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + check("triangle kind %d call passes origin, direction and inverse from v18..v26" % kind, + "float3(F(v18), F(v19), F(v20)), float3(F(v21), F(v22), F(v23)), " + "float3(F(v24), F(v25), F(v26))" in call_line, call_line) + + pipe, hlsl, refusals = translate_triangle(0x00, sort_boxes=False) + check("sort-disabled triangle translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_triangle(r0" in line), "") + check("sort-disabled triangle call keeps the zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x81000000u" in call, call) + + # One T# can cover both node types, so a box node ignores the triangle return mode bit. + pipe, hlsl, refusals = translate_triangle(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE) + check("box node with triangle return mode bit translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + check("box call preserves the ignored return mode bit", + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call, call) + + helpers = "\n".join(G.BVH_HELPERS) + check("translated triangle shader embeds the dispatch-tested helpers", + hlsl is not None and helpers in hlsl, "") + + # Size is a count minus one in 64-byte units. A triangle uses one unit. + for node, word2, label in ((0x00, 0, "triangle at offset zero in a one-unit span"), + (0x08, 1, "triangle in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_triangle(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x08, word2=0) + check("too-short triangle in the last unit of a one-unit span refuses", + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x00, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x00, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + + cases = [ + ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), + ("box reserved word 3 bit", dict(node=0x05, word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("node outside size", dict(node=0x20, word2=3), "outside descriptor size"), + ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), + ("loaded descriptor", dict(node=0x00, loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(node=0x00, word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(node=0x00, word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("reserved word 1", dict(node=0x00, word1=SORT_ENABLE | 0x100), "reserved word 1"), + ("8-bit return mode extra bit", dict(node=0x00, word3=RESOURCE_TYPE | TRIANGLE_MODE | 0x100), + "does not match node kind 0"), + ("64-bit form", dict(node=0x00, opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(node=0x00, modifier="a16"), "modifier a16"), + ("unaligned box32 node", dict(node=0x0d), "not an aligned 128-byte node"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 0})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_triangle(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_triangle(r" not in hlsl, "") + + words = (0xffffffff, SORT_ENABLE | 0xff, 0x0b, RESOURCE_TYPE | TRIANGLE_MODE) + pipe, boundary_hlsl, refusals = translate_triangle(0x10, word0=words[0], word1=words[1]) + check("triangle node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_triangle(0x20, word0=words[0], word1=words[1]) + check("refuses a triangle 48-bit wrap before resource binding", + refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] + and " bvh base " not in pipe.manifest() + and "x2w_bvh_intersect_triangle" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + + pipe, hlsl, refusals = translate_triangle(0x00, stage_kind="ps") + check("refuses a triangle pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_triangle.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated triangle helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack("<I", struct.pack("<f", value))[0] + + +def fbits(value): + return "0x%08xu" % struct.unpack("<I", struct.pack("<f", value))[0] + + +def triangle_layout(): + images = [] + offsets = {} + for case in TRIANGLES: + if case.image not in offsets: + offsets[case.image] = 64 * len(images) + images.append(case.image) + result_offset = (64 * len(images) + 63) & ~63 + return images, offsets, result_offset, result_offset + 16 * len(TRIANGLES) + + +MUTATIONS = { + "det_sign": ( + "bool ahead = (det > 0.0 && t >= 0.0) || (det < 0.0 && t <= 0.0);", + "bool ahead = (det > 0.0 && t >= 0.0) || (det > 0.0 && t <= 0.0);"), + "id_shift": ( + "uint id_byte = (id >> (8u * kind)) & 0xffu;", + "uint id_byte = id & 0xffu;"), + "u_sign": ( + "float u = sc.x * sb.y - sc.y * sb.x;", + "float u = sc.x * sb.y + sc.y * sb.x;"), + "miss_words": ( + "uint4 miss = uint4(0x7f800000u, 0x3f800000u, 0u, 0u);", + "uint4 miss = uint4(0u, 0u, 0u, 0u);"), +} + + +def dispatch_hlsl(mutation=None): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + if mutation: + old, new = MUTATIONS[mutation] + assert helpers.count(old) == 1, (mutation, old) + helpers = helpers.replace(old, new) + images, offsets, result_offset, _buffer_size = triangle_layout() + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for image in images: + base = offsets[image] + for i in range(16): + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, struct.unpack_from("<I", image, 4 * i)[0])) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + for case, witness in enumerate(TRIANGLES): + origin, direction, inverse, _extent = witness.ray + pointer = (offsets[witness.image] >> 3) | witness.pointer + lines.append( + " uint4 r%d = x2w_bvh_intersect_triangle(data, 0x%08xu, 0x1000u, 0x80000000u, " + "0x400u, 0x81000000u, float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, pointer, ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), + ffloat(direction[0]), ffloat(direction[1]), ffloat(direction[2]), + ffloat(inverse[0]), ffloat(inverse[1]), ffloat(inverse[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (result_offset + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +TRIANGLE_BOUNDARY_RESULT_OFFSET = 64 +TRIANGLE_BOUNDARY_BUFFER_SIZE = 96 + + +def boundary_hlsl(): + witness = TRIANGLES[0] + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i in range(16): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, struct.unpack_from("<I", witness.image, 4 * i)[0])) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + origin, direction, inverse, _extent = witness.ray + expected = [] + for case, pointer, word2, result in ((0, 0x00, 0, witness.expected), + (1, 0x08, 0, (0x7f800000, 0x3f800000, 0, 0))): + lines.append( + " uint4 b%d = x2w_bvh_intersect_triangle(data, 0x%08xu, 0x1000u, 0x80000000u, " + "0x%08xu, 0x81000000u, float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, pointer, word2, ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), + ffloat(direction[0]), ffloat(direction[1]), ffloat(direction[2]), + ffloat(inverse[0]), ffloat(inverse[1]), ffloat(inverse[2]))) + for word in range(4): + lines.append(" data.Store(%du, b%d.%s);" % ( + TRIANGLE_BOUNDARY_RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) + expected.append(result) + lines.append("}") + return "\n".join(lines) + "\n", expected + + +def run_boundary_dispatch(dxc, runner, adapter, directory): + source = directory / "bvh_triangle_boundary.hlsl" + cso = directory / "bvh_triangle_boundary.cso" + output = directory / "bvh_triangle_boundary.bin" + hlsl, expected = boundary_hlsl() + source.write_text(hlsl, encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(TRIANGLE_BOUNDARY_BUFFER_SIZE), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None, expected + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == TRIANGLE_BOUNDARY_BUFFER_SIZE, (len(data), TRIANGLE_BOUNDARY_BUFFER_SIZE) + return 0, struct.unpack("<%dI" % (len(data) // 4), data), expected + + +def run_dispatch(dxc, runner, adapter, directory, mutation=None): + _images, _offsets, _result_offset, buffer_size = triangle_layout() + name = "bvh_triangle_" + mutation if mutation else "bvh_triangle" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutation), encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(buffer_size), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == buffer_size, (len(data), buffer_size) + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if failures: + return 1 + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + _images, _offsets, result_offset, _buffer_size = triangle_layout() + result_word = result_offset // 4 + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + for case, witness in enumerate(TRIANGLES): + start = result_word + 4 * case + got = tuple(words[start:start + 4]) + check("dispatch triangle %d %s" % (case, witness.name), got == witness.expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in witness.expected])) + for mutation in MUTATIONS: + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutation=mutation) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + changed = sum(tuple(mutant[result_word + 4 * case:result_word + 4 * case + 4]) != witness.expected + for case, witness in enumerate(TRIANGLES)) + check("dispatch %s control changes a triangle result" % mutation, changed > 0, str(changed)) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = TRIANGLE_BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("triangle decoded extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_triangle(0x00) + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh triangle: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) + diff --git a/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py b/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py new file mode 100644 index 0000000000..a800179f3a --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp_class_f16_sdwa_check.py @@ -0,0 +1,448 @@ +"""The SDWA forms of `v_cmp_class_f16` / `v_cmpx_class_f16` in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls and value checks, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile source-built pixel programs with FXC ps_5_1 when given and with DXC + ps_6_0, draw 16 x 16 pixels and compare every pixel with a CPU reference + +The plain e32/e64 register and encoded-literal path (including the census form `0x7c01`) is covered by +startup_gfx2hlsl_cmp_class_f16_check.py. This file covers what that one does not: + + * SDWA: `src0_sel` DWORD and WORD_0 are lowered to the shared class16() helper on the register word (which reads + bits [15:0] only); `src1_sel` selects and sign-extends the integer mask as for the binary32 class compare. WORD_1, + each byte, sext() on src0, the abs/neg spellings, a missing select, a float mask and a bad destination are refused. + Words are built with the VOP_SDWA9Be layout tools/disasm_rdna2.py reads, and two of them are compared with the + bytes clang -cc1as (LLVM 15, gfx1013) emits for the same text. + * Value level: the emitted predicate is evaluated over boundary patterns of every class with garbage in the upper + half and against an independent reference written from the binary16 layout (struct 'e'). Three mutated helpers + (upper half read, sNaN and qNaN swapped, +0 and -0 swapped) must disagree with that reference. + * Draw: a register holding 0x7c01 in its low half (sNaN, class bit 0x1), a register with the same low half and a + qNaN (0x7e00, class bit 0x2) in the upper half, the encoded literal 0x7c01, the e32 spelling and both SDWA + selects all give the same class: the 16 x 16 pixels keep or discard by the class bit against a per-pixel mask, + and every variant must match one reference image. Two controls must fail it: classifying the upper half instead + of the low one (the independent high-half control) and swapping the sNaN/qNaN return values. A third reads the + whole mask dword instead of the BYTE_1 select. + +Encoded NEG and inline float constants are not lowered through the SDWA path and stay refused on the plain path +(tests/startup_gfx2hlsl_cmp_class_f16_check.py). +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 +from startup_gfx2hlsl_vopc_sdwa_check import ( # noqa: E402 + CLEAR, EXPORT_WORDS, HEIGHT, MASK, MUL_WORDS, MULTIPLIER, PACKED, WIDTH, draw, field, source, vopc_sdwa, + words_file) +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +CMP_CLASS_F16, CMPX_CLASS_F16 = 0x8F, 0x9F # VOPC e32 opcodes +SGPR_DST = 6 +V1, V2 = 0x101, 0x102 + + +class Probe(G.Stage): + """A Stage with no pipeline: enough state for decoded instructions to be translated.""" + + def __init__(self, exec_known=True): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = exec_known + + +def translate(code, exec_known=True): + decoded = G.decode(code) + assert len(decoded) == 1 and decoded[0][1] == 8, decoded + stage = Probe(exec_known) + stage.one(decoded[0][2], decoded[0][3]) + return decoded[0][3], stage + + +def refusal_of(name, asm): + try: + stage = Probe() + stage.one(name, asm) + except G.Unsupported as error: + return str(error) + return None + + +# ---- the independent reference and the helper under test ------------------------------------------------------- +def ref_class16(word): + """The class bit of S0[15:0] from the binary16 layout read through struct 'e'; the upper half is ignored.""" + low = word & 0xFFFF + value = struct.unpack('<e', struct.pack('<H', low))[0] + negative = bool(low & 0x8000) + if math.isnan(value): + return 0x2 if low & 0x0200 else 0x1 # struct cannot tell sNaN from qNaN: mantissa bit 9 decides + if math.isinf(value): + return 0x4 if negative else 0x200 + if value == 0.0: + return 0x20 if negative else 0x40 + if abs(value) < 2.0 ** -14: + return 0x10 if negative else 0x80 + return 0x8 if negative else 0x100 + + +# (binary16 pattern, the one class bit it must hit), written from the ISA class list, not from the lowering. +BOUNDARIES = [(0x0000, 6), (0x8000, 5), (0x0001, 7), (0x8001, 4), (0x03FF, 7), (0x83FF, 4), (0x0400, 8), + (0x8400, 3), (0x7BFF, 8), (0xFBFF, 3), (0x7C00, 9), (0xFC00, 2), (0x7C01, 0), (0xFC01, 0), + (0x7DFF, 0), (0x7E00, 1), (0xFE00, 1), (0x7FFF, 1), (0xFFFF, 1), (0x3C00, 8), (0xBC00, 3)] +UPPERS = [0x0000, 0xFFFF, 0x7C00, 0x7E00, 0x8000, 0xDEAD] + + +def class16_helper(): + pipe = object.__new__(G.Pipeline) + pipe.uds, pipe.resources, pipe.samplers, pipe.uses_sampler_heap = [], {}, {}, False + return [entry for entry in pipe.common() if 'uint class16(' in entry][0] + + +def run_helper(helper, word): + """Evaluate the emitted helper body for one register word.""" + body = helper[helper.index('{') + 1:helper.rindex('}')] + env = {'bits': word} + for statement in (piece.strip() for piece in body.split(';')): + if not statement: + continue + if statement.startswith(('uint ', 'bool ')): + for part in statement.split(' ', 1)[1].split(','): + name, expression = (piece.strip() for piece in part.split('=', 1)) + env[name] = int(bool(Expr(expression).run(env)[0])) if statement.startswith('bool ') \ + else Expr(expression).run(env)[0] + elif statement.startswith('if ') and ') return ' in statement: + condition, consequence = statement[3:].split(') return ', 1) + if Expr(condition[1:]).run(env)[0]: + return Expr(consequence).run(env)[0] + elif statement.startswith('return '): + return Expr(statement[7:]).run(env)[0] + raise ValueError('the helper returned nothing for %#x' % word) + + +HELPER = class16_helper() +HELPER_MUTATIONS = { + 'upper half read': ('uint h = bits & 0xffffu', 'uint h = bits'), + 'sNaN and qNaN swapped': ('? 0x2u : 0x1u', '? 0x1u : 0x2u'), + '+0 and -0 swapped': ('negative ? 0x20u : 0x40u', 'negative ? 0x40u : 0x20u'), +} + + +def mutated(name): + old, new = HELPER_MUTATIONS[name] + assert HELPER.count(old) == 1, name + return HELPER.replace(old, new) + + +def split_call(text, name): + """(text before, argument, text after) of the one `name(...)` call in text.""" + start = text.index(name + '(') + depth, at = 0, start + len(name) + for at in range(start + len(name), len(text)): + depth += text[at] == '(' + depth -= text[at] == ')' + if depth == 0: + break + return text[:start], text[start + len(name) + 1:at], text[at + 1:] + + +def predicate(stage, word, mask_word, helper=HELPER, lane=1): + """The value the emitted line computes for a source word and a mask register word.""" + expression = stage.lines[0].split(' = ', 1)[1].rstrip(';') + before, argument, after = split_call(expression, 'class16') + env = {'v1': mask_word, 'v2': word, 's5': word, 's6': mask_word, 'exec': lane} + env['cls'] = run_helper(helper, Expr(argument).run(env)[0]) + return Expr(before + 'cls' + after).run(env)[0] + + +# ---- controls ------------------------------------------------------------------------------------------------- +SELS_SRC1 = [('DWORD', False), ('WORD_0', False), ('BYTE_1', False), ('BYTE_1', True), ('WORD_1', True)] + + +def accepted_forms(): + for destination in ('vcc', 'sgpr', 'exec'): + for sel0 in ('DWORD', 'WORD_0'): + for sel1, sext1 in SELS_SRC1: + for src0_kind, src0_number in (('v', 2), ('s', 5)): + yield destination, sel0, sel1, sext1, src0_kind, src0_number + + +def controls(): + # 1. Words built here against the bytes LLVM assembles for the same text. + llvm_cmp = bytes([0xF9, 0x00, 0x1E, 0x7D, 0x04, 0x00, 0x04, 0x06]) + llvm_cmpx = bytes([0xF9, 0x00, 0x3E, 0x7D, 0x04, 0x00, 0x04, 0x06]) + built_cmp = vopc_sdwa(CMP_CLASS_F16, source('v', 4), source('v', 0), None, 'WORD_0', 'DWORD') + built_cmpx = vopc_sdwa(CMPX_CLASS_F16, source('v', 4), source('v', 0), None, 'WORD_0', 'DWORD') + check('built SDWA words equal the clang -cc1as bytes', built_cmp == llvm_cmp and built_cmpx == llvm_cmpx, + '%s %s' % (built_cmp.hex(), built_cmpx.hex())) + asm, stage = translate(llvm_cmp) + check('the LLVM word decodes and lowers', asm == 'v_cmp_class_f16_sdwa vcc_lo, v4, v0 src0_sel:WORD_0 ' + 'src1_sel:DWORD' and stage.lines == ['vcc = (((class16(v4) & v0) != 0u) ? 1u : 0u);'], repr((asm, stage.lines))) + asm, stage = translate(llvm_cmpx, exec_known=False) + check('the LLVM cmpx word writes exec behind the narrowed mask', + asm == 'v_cmpx_class_f16_sdwa v4, v0 src0_sel:WORD_0 src1_sel:DWORD' and stage.exec_known is False + and stage.lines == ['exec = (exec & (((class16(v4) & v0) != 0u) ? 1u : 0u));'], repr((asm, stage.lines))) + + # 2. Every accepted form: destination, src0 select and register file, src1 select and sext. The predicate + # classifies the low half of the source whatever sits in the upper half, against the selected mask. + errors, count = [], 0 + for destination, sel0, sel1, sext1, kind, number in accepted_forms(): + op = CMPX_CLASS_F16 if destination == 'exec' else CMP_CLASS_F16 + code = vopc_sdwa(op, source(kind, number), source('v', 1, sext=sext1), + SGPR_DST if destination == 'sgpr' else None, sel0, sel1) + asm, stage = translate(code, exec_known=False) + count += 1 + target = {'vcc': 'vcc', 'sgpr': 's%d' % SGPR_DST, 'exec': 'exec'}[destination] + if (len(stage.lines) != 1 or not stage.lines[0].startswith(target + ' = ') or stage.exec_known + or (SGPR_DST in stage.masks) != (destination == 'sgpr')): + errors.append((asm, stage.lines, stage.masks)) + continue + for word, _bit in BOUNDARIES: + for upper in UPPERS: + for mask_raw in (0x00000001, 0x00000200, 0x000003FF, 0x00000100, 0x0000FF80, 0xFFFF0001, 0x01FF0000): + for lane in (0, 1): + got = predicate(stage, (upper << 16) | word, mask_raw, lane=lane) + wanted = lane & int(bool(ref_class16(word) & field(mask_raw, sel1, sext1))) + if got != wanted: + errors.append((asm, hex((upper << 16) | word), hex(mask_raw), lane, got, wanted)) + check('%d accepted SDWA forms classify S0[15:0] against the selected mask and write their destination' % count, + count == 3 * 2 * len(SELS_SRC1) * 2 and not errors, repr(errors[:3])) + + # 3. Refusals, each loud and with its own reason. + def expect(label, code, message): + name, asm = (lambda d: (d[0][2], d[0][3]))(G.decode(code)) + got = refusal_of(name, asm) + check('refused: %s (%s)' % (label, got), got is not None and message in got, asm) + + for sel0 in ('WORD_1', 'BYTE_0', 'BYTE_1', 'BYTE_2', 'BYTE_3'): + expect('src0_sel:%s' % sel0, vopc_sdwa(CMP_CLASS_F16, source('v', 2), source('v', 1), None, sel0, 'DWORD'), + 'SDWA form of v_cmp_class_f16 with src0_sel:%s' % sel0) + expect('cmpx src0_sel:WORD_1', vopc_sdwa(CMPX_CLASS_F16, source('v', 2), source('v', 1), None, 'WORD_1', 'DWORD'), + 'SDWA form of v_cmpx_class_f16 with src0_sel:WORD_1') + # abs and neg on the SDWA half source print |v2|, -v2, abs() or neg(): the sign bit they act on is bit 15 of + # the half, which the SDWA path does not model, so they are refused instead of classifying the unmodified bits. + expect('abs on src0', vopc_sdwa(CMP_CLASS_F16, source('v', 2, absolute=True), source('v', 1), None, 'WORD_0', + 'DWORD'), 'with source') + expect('neg on src0', vopc_sdwa(CMP_CLASS_F16, source('v', 2, neg=True), source('v', 1), None, 'WORD_0', + 'DWORD'), 'with source') + expect('neg and abs on src0', vopc_sdwa(CMP_CLASS_F16, source('v', 2, neg=True, absolute=True), source('v', 1), + None, 'WORD_0', 'DWORD'), 'with source') + for asm, message in ( + # The decoder cannot encode sext() on a float source, so the text is given directly. + ('v_cmp_class_f16_sdwa vcc_lo, sext(v2), v1 src0_sel:WORD_0 src1_sel:DWORD', 'with source sext(v2)'), + ('v_cmp_class_f16_sdwa vcc_lo, v2, v1 src1_sel:DWORD', 'SDWA form of v_cmp_class_f16 with no src0_sel'), + ('v_cmp_class_f16_sdwa vcc_lo, v2, 1.0 src0_sel:WORD_0 src1_sel:DWORD', 'expected an integer class mask'), + ('v_cmp_class_f16_sdwa vcc_lo, 1.0, v1 src0_sel:WORD_0 src1_sel:DWORD', 'with source 1.0'), + ('v_cmp_class_f16_sdwa vcc_lo, 0x7c01, v1 src0_sel:WORD_0 src1_sel:DWORD', 'with source 0x7c01'), + ('v_cmp_class_f16_sdwa vcc_lo, v2, v1 src0_sel:WORD_0 src0_sel:DWORD src1_sel:DWORD', 'with src0_sel'), + ('v_cmp_class_f16_sdwa vcc_lo, v2, v1 src0_sel:WORD_0 src1_sel:DWORD clamp', 'clamp'), + ('v_cmp_class_f16_sdwa null, v2, v1 src0_sel:WORD_0 src1_sel:DWORD', 'into null'), + ('v_cmp_class_f16_sdwa vcc_lo, v2 src0_sel:WORD_0 src1_sel:DWORD', 'with 2 operands'), + ('v_cmpx_class_f16_sdwa vcc_lo, v2, v1 src0_sel:WORD_0 src1_sel:DWORD', 'with 3 operands'), + ('v_cmp_lt_f16_sdwa vcc_lo, v2, v1 src0_sel:WORD_0 src1_sel:WORD_0', 'v_cmp_lt_f16_sdwa')): + got = refusal_of(asm.split()[0], asm) + check('refused: %s (%s)' % (asm, got), got is not None and message in got) + + # 4. The reference separates the controls. Each mutated helper, over the whole 16-bit space with upper halves + # that differ from the low half, must disagree with it; the shipped helper agrees everywhere. + def disagreements(helper, uppers, first_only=False): + out = [] + for low in range(0x10000): + for upper in uppers: + word = (upper << 16) | low + if run_helper(helper, word) != ref_class16(word): + out.append(hex(word)) + if first_only: + return out + return out + + check('the helper agrees with the binary16 reference on every low half under two upper halves', + not disagreements(HELPER, (0x0000, 0x7E00)), repr(disagreements(HELPER, (0x0000, 0x7E00))[:4])) + for name in HELPER_MUTATIONS: + found = disagreements(mutated(name), (0x7E00,), first_only=True) + check('control %s disagrees with the reference (first at %s)' % (name, found[:1]), len(found) > 0) + _asm, stage = translate(vopc_sdwa(CMP_CLASS_F16, source('v', 2), source('v', 1), None, 'WORD_0', 'DWORD')) + for name in HELPER_MUTATIONS: + bad = [(hex(word), hex(upper)) for word, _bit in BOUNDARIES for upper in UPPERS + if predicate(stage, (upper << 16) | word, ref_class16(word), helper=mutated(name)) != 1] + check('control %s fails the emitted predicate on a boundary pattern' % name, bool(bad)) + + +# ---- the draw ------------------------------------------------------------------------------------------------- +LOW = 0x7C01 # a signaling NaN: class bit 0x1 +UPPER_QNAN = 0x7E00 # a quiet NaN in the upper half: class bit 0x2, what a translation reading bits [31:16] sees + + +def v_mov_literal(vdst, literal): + return struct.pack('<II', (0b0111111 << 25) | (vdst << 17) | (1 << 9) | 255, literal) + + +def e32_cmpx(src0, vsrc1): + return struct.pack('<I', (0b0111110 << 25) | (CMPX_CLASS_F16 << 17) | (vsrc1 << 9) | src0) + + +def e64_cmpx_literal(literal, src1): + return struct.pack('<III', (0b110101 << 26) | (CMPX_CLASS_F16 << 16) | 106, 255 | (src1 << 9), literal) + + +def sdwa_cmpx(sel0, sel1): + return vopc_sdwa(CMPX_CLASS_F16, source('v', 2), source('v', 1), None, sel0, sel1) + + +# name: (source text, words, mask select). Every variant tests class bit 0x1 of the half 0x7c01 against the mask +# v1 = position * MULTIPLIER; only the way the half reaches the compare changes. +VARIANTS = { + 'register, upper qNaN, WORD_0 / DWORD': ( + 'v_mov_b32_e32 v2, 0x7e007c01\nv_cmpx_class_f16_sdwa v2, v1 src0_sel:WORD_0 src1_sel:DWORD', + v_mov_literal(2, (UPPER_QNAN << 16) | LOW) + sdwa_cmpx('WORD_0', 'DWORD'), None), + 'register, upper qNaN, DWORD / DWORD': ( + 'v_mov_b32_e32 v2, 0x7e007c01\nv_cmpx_class_f16_sdwa v2, v1 src0_sel:DWORD src1_sel:DWORD', + v_mov_literal(2, (UPPER_QNAN << 16) | LOW) + sdwa_cmpx('DWORD', 'DWORD'), None), + 'register, clean upper, WORD_0 / DWORD': ( + 'v_mov_b32_e32 v2, 0x7c01\nv_cmpx_class_f16_sdwa v2, v1 src0_sel:WORD_0 src1_sel:DWORD', + v_mov_literal(2, LOW) + sdwa_cmpx('WORD_0', 'DWORD'), None), + 'register, upper qNaN, e32': ( + 'v_mov_b32_e32 v2, 0x7e007c01\nv_cmpx_class_f16_e32 v2, v1', + v_mov_literal(2, (UPPER_QNAN << 16) | LOW) + e32_cmpx(V2, 1), None), + 'encoded literal 0x7c01, e64': ( + 'v_cmpx_class_f16_e64 vcc_lo, 0x7c01, v1', e64_cmpx_literal(LOW, V1), None), + 'register, upper qNaN, WORD_0 / BYTE_1': ( + 'v_mov_b32_e32 v2, 0x7e007c01\nv_cmpx_class_f16_sdwa v2, v1 src0_sel:WORD_0 src1_sel:BYTE_1', + v_mov_literal(2, (UPPER_QNAN << 16) | LOW) + sdwa_cmpx('WORD_0', 'BYTE_1'), 'BYTE_1'), +} +PS_HEAD = 'v_mul_u32_u24_e32 v1, 0x9b5d, v0\n' +CONTROLS = { + 'upper half classified': ('class16(v2)', 'class16(v2 >> 16u)'), + 'sNaN and qNaN swapped': ('(h & 0x0200u) != 0u ? 0x2u : 0x1u', '(h & 0x0200u) != 0u ? 0x1u : 0x2u'), +} + + +def pixel_words(name): + return MUL_WORDS + VARIANTS[name][1] + EXPORT_WORDS + + +def pixel_hlsl(name, control=None): + text = G.Pipeline(VS_WORDS, pixel_words(name), root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + if control: + old, new = CONTROLS[control] + if old == 'class16(v2)' and name.startswith('encoded literal'): + old, new = 'class16(0x00007c01u)', 'class16(0x00007c01u >> 16u)' + assert text.count(old) == 1, (name, control, old) + text = text.replace(old, new) + return text + + +def image(select, class_bit): + words = [] + for y in range(HEIGHT): + for x in range(WIDTH): + position = x | (y << 16) + mask = (position * MULTIPLIER) & MASK + if select: + mask = field(mask, select, False) + words += [position if mask & class_bit else CLEAR] * 4 + return words + + +def check_fixture(): + for name, (text, _words, select) in VARIANTS.items(): + decoded = [asm for _o, _s, _n, asm in G.decode(pixel_words(name))] + wanted = (PS_HEAD + text + '\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm').splitlines() + wanted = [line.replace('v_mov_b32_e32', 'v_mov_b32_e32') for line in wanted] + check('%s: fixture decodes to its source' % name, decoded == wanted, '%s\n%s' % (decoded, wanted)) + hlsl = pixel_hlsl(name) + check('%s: lowered through class16 behind exec' % name, + 'class16(' in hlsl and 'if (!(exec & 1)) discard;' in hlsl, hlsl) + reference = image(select, 0x1) + kept = sum(reference[i] != CLEAR for i in range(0, len(reference), 4)) + check('%s: reference keeps %d of %d pixels' % (name, kept, WIDTH * HEIGHT), 0 < kept < WIDTH * HEIGHT) + # The controls must be distinguishable by the image, or the draw could not tell them apart. + check('classifying the upper half (class bit 0x2) changes the image', image(None, 0x1) != image(None, 0x2)) + check('swapping sNaN and qNaN changes the image', image(None, 0x1) != image(None, 0x2)) + check('ignoring the BYTE_1 select changes the image', image('BYTE_1', 0x1) != image(None, 0x1)) + for name in VARIANTS: + for control in CONTROLS: + pixel_hlsl(name, control) # every control applies to exactly one place in every variant + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + plain = words_file(directory, 'plain', image(None, 0x1)) + selected = words_file(directory, 'selected', image('BYTE_1', 0x1)) + upper = words_file(directory, 'upper', image(None, 0x2)) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for index, (name, (_text, _words, select)) in enumerate(VARIANTS.items()): + ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%d_%s' % (index, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, ps, selected if select else plain) + check('%s %s: %s matches all %d pixels' % (kind, adapter, name, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for control in CONTROLS: + name = 'register, upper qNaN, WORD_0 / DWORD' + bad = compile_hlsl(compiler, kind, pixel_hlsl(name, control), 'ps_bad_%s_%s' % (control[:5], kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, plain) + check('%s %s: control %s fails the draw' % (kind, adapter, control), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + # A translation that classified the upper half draws the image of the upper class bit. + bad = compile_hlsl(compiler, kind, pixel_hlsl('register, upper qNaN, WORD_0 / DWORD', + 'upper half classified'), 'ps_up_%s' % kind, ps_profile, + directory) + run = draw(renderer, adapter, vs, bad, upper) + check('%s %s: upper-half control matches the upper-class image' % (kind, adapter), + run.returncode == 0, run.stdout + run.stderr) + # The select control: the same program with the mask read as a whole dword draws the plain image. + name = 'register, upper qNaN, WORD_0 / BYTE_1' + text = pixel_hlsl(name) + assert text.count('((v1 >> 8u) & 0xffu)') == 1, text + bad = compile_hlsl(compiler, kind, text.replace('((v1 >> 8u) & 0xffu)', 'v1'), 'ps_sel_%s' % kind, + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, selected) + check('%s %s: mask select control fails the draw' % (kind, adapter), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + run = draw(renderer, adapter, vs, bad, plain) + check('%s %s: mask select control matches the whole-dword image' % (kind, adapter), + run.returncode == 0, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + check_fixture() + elif sys.argv[1] == 'draw': + check_fixture() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_cndmask_abs_check.py b/tests/startup_gfx2hlsl_cndmask_abs_check.py new file mode 100644 index 0000000000..4d4b31002f --- /dev/null +++ b/tests/startup_gfx2hlsl_cndmask_abs_check.py @@ -0,0 +1,398 @@ +"""Absolute-value (`|src|` and `-|src|`) modifiers on `v_cndmask_b32_e64` in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per input set and compare the four exported words + +Per RDNA2 ISA VOP3A, `abs` clears bit 31 (`& 0x7fffffffu`) FIRST and `neg` flips bit 31 (`^ 0x80000000u`) +SECOND, so `-|x|` forces bit 31 to 1 (`((x & 0x7fffffffu) ^ 0x80000000u)`), whereas `-x` flips bit 31. +All instruction bytes are **constructed here** from the RDNA2 field layout decoded by `G.decode()` (no game data): + VOP3A w0: [31:26] = 0b110101, [25:16] opcode (VOP2 e64 = 0x100 + op, VOPC e64 = op), + [15] clamp, [10:8] abs for src2..src0, [7:0] vdst + w1: [8:0] src0, [17:9] src1, [26:18] src2, [28:27] omod, [31:29] neg for src2..src0 +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import VS_WORDS, compile_hlsl, draw # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr, mov_literal # noqa: E402 + +MASK = 0xffffffff +SIGN_BIT = 0x80000000 +MAG_MASK = 0x7fffffff + +VOP2_E64_BASE = 0x100 +CNDMASK = 0x01 +AND_B32 = 0x1b +V_CMP_NE_U32 = 0xc5 + +# RDNA2 9-bit VOP3 source encoding: 0..105 = s0..s105, 256..511 = v0..v255. +S4 = 4 +S8 = 8 +V0 = 256 + 0 +V1 = 256 + 1 +V2 = 256 + 2 +V30 = 256 + 30 + +# 32-bit bit patterns covering signed zero, normal floats, qNaNs, infinities, negative denormal, and bit payloads. +PATTERNS = ( + 0x00000000, # +0.0 + 0x80000000, # -0.0 + 0x3f800000, # +1.0 + 0xbf800000, # -1.0 + 0x7fc00001, # +qNaN + 0xffc00001, # -qNaN + 0x7f800000, # +inf + 0xff800000, # -inf + 0x80000001, # -denormal + 0x12345678, # +arbitrary + 0x92345678, # -arbitrary +) + + +def encode_vop3a(opcode, vdst, src0, src1, src2=0, *, + neg0=0, neg1=0, neg2=0, abs0=0, abs1=0, abs2=0, clamp=0, omod=0): + """Encode a VOP3A instruction (VOP2 e64 or VOPC e64).""" + w0 = ((0b110101 << 26) | ((opcode & 0x3ff) << 16) | ((clamp & 1) << 15) + | ((abs2 & 1) << 10) | ((abs1 & 1) << 9) | ((abs0 & 1) << 8) | (vdst & 0xff)) + w1 = ((src0 & 0x1ff) | ((src1 & 0x1ff) << 9) | ((src2 & 0x1ff) << 18) | ((omod & 0x3) << 27) + | ((neg0 & 1) << 29) | ((neg1 & 1) << 30) | ((neg2 & 1) << 31)) + return struct.pack('<II', w0, w1) + + +def encode_vop2_e64(op, vdst, src0, src1, src2=0, **kw): + return encode_vop3a(VOP2_E64_BASE + op, vdst, src0, src1, src2, **kw) + + +def encode_sop2_literal(op, sdst, ssrc0, literal): + """Encode an SOP2 instruction with ssrc1=255 (literal dword).""" + w0 = (0b10 << 30) | ((op & 0x7f) << 23) | ((sdst & 0x7f) << 16) | (255 << 8) | (ssrc0 & 0xff) + return struct.pack('<II', w0, literal & MASK) + + +class Pipeline: + def __init__(self): + self.resources, self.notes, self.modified, self.sampler_heap = {}, set(), set(), False + + +class Stage(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports = {} + self.pipe = Pipeline() + + +def translate_code(code): + decoded = G.decode(code) + stage = Stage() + for _offset, _size, name, asm in decoded: + stage.one(name, asm) + return [asm for _o, _s, _n, asm in decoded], ' '.join(stage.lines) + + +def refused_code(code): + try: + translate_code(code) + except G.Unsupported: + return True + return False + + +def isa_abs(x): + return x & MAG_MASK + + +def isa_neg(x): + return x ^ SIGN_BIT + + +def isa_neg_abs(x): + return (x & MAG_MASK) ^ SIGN_BIT + + +def wrong_neg_before_abs(x): + return (x ^ SIGN_BIT) & MAG_MASK + + +# ---- Draw fixture: synthetic VS + PS decoded and lowered through G.Pipeline ---------------------------- +def root_blob_with_const(): + """DXBC container with one RTS0 part declaring one 32-bit root constant at b0 (ud1 = 0 in offscreen_check).""" + # RTS0 header (24 bytes): ver=2, nparam=1, poff=24, nsamp=0, soff=36, flags=0 + # param0 entry (12 bytes): type=1 (32-bit constants), vis=0 (all), off=36 + # constants payload (12 bytes): reg=0, space=0, count=1 + rts0 = struct.pack('<6I3I3I', 2, 1, 24, 0, 36, 0, 1, 0, 36, 0, 0, 1) + part = b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + return (b'DXBC' + bytes(16) + struct.pack('<III', 1, 32 + 4 + len(part), 1) + struct.pack('<I', 36) + part) + + +def vs_words(x_word, y_word, mask_word): + """Full-screen triangle VS exporting (x_word, y_word, mask_word, 0) to param0.""" + out = VS_WORDS[:40] + for idx, val in enumerate((x_word, y_word, mask_word, 0)): + out += mov_literal(11 + idx, val) + out += bytes.fromhex('cf0800f801020504') # exp pos0 v1, v2, v5, v4 done + out += struct.pack('<2I', 0xf800000f | (32 << 4), (11) | (12 << 8) | (13 << 16) | (14 << 24)) # exp param0 + return out + bytes.fromhex('000081bf') # s_endpgm + + +S4_SEED = 0x92345678 +PRE_WORDS = bytes.fromhex('0203fcbe020002c8020106c802020ac8') # s_mov_b32 m0, s2; v_interp_mov_f32 v0..v2, p0, attr0.x..z +POST_WORDS = bytes.fromhex('0f1800f80c0d0e0f000081bf') # exp mrt0 v12..v15 done vm; s_endpgm + +PS_BODY_WORDS = ( + encode_vop3a(V_CMP_NE_U32, 30, 128, V2) # v_cmp_ne_u32_e64 s30, 0, v2 + + encode_sop2_literal(0x12, S4, S8, S4_SEED) # s_xor_b32 s4, s8, 0x92345678 (runtime ud1 ^ seed) + + encode_vop2_e64(CNDMASK, 12, V0, V0, 30, abs1=1) # v12 = (s30 & 1) ? |v0| : v0 + + encode_vop2_e64(CNDMASK, 13, V0, V0, 30, abs0=1, abs1=1, neg1=1) # v13 = (s30 & 1) ? -|v0| : |v0| + + encode_vop2_e64(CNDMASK, 14, V1, V1, 30, abs0=1, neg0=1, neg1=1) # v14 = (s30 & 1) ? -v1 : -|v1| + + encode_vop2_e64(CNDMASK, 15, S4, S4, 30, abs0=1, abs1=1, neg1=1) # v15 = (s30 & 1) ? -|s4| : |s4| +) +PS_WORDS = PRE_WORDS + PS_BODY_WORDS + POST_WORDS + + +def expected_outputs(x_word, y_word, mask_bit): + """ISA-level reference words for (v12, v13, v14, v15).""" + v12 = isa_abs(x_word) if mask_bit else x_word + v13 = isa_neg_abs(x_word) if mask_bit else isa_abs(x_word) + v14 = isa_neg(y_word) if mask_bit else isa_neg_abs(y_word) + v15 = isa_neg_abs(S4_SEED) if mask_bit else isa_abs(S4_SEED) + return (v12, v13, v14, v15) + + +def words_text(values): + return ','.join('%08x' % v for v in values) + + +def mutate_reverse_order(hlsl_text): + """Mutate `((reg & 0x7fffffffu) ^ 0x80000000u)` -> `((reg ^ 0x80000000u) & 0x7fffffffu)` (wrong neg-then-abs).""" + mutated = re.sub(r'\(\((\w+) & 0x7fffffffu\) \^ 0x80000000u\)', + r'((\1 ^ 0x80000000u) & 0x7fffffffu)', hlsl_text) + assert mutated != hlsl_text + return mutated + + +def mutate_drop_abs(hlsl_text): + r"""Mutate `(\w+ & 0x7fffffffu)` -> `\1` (drops abs from both `|x|` and `-|x|`).""" + mutated = re.sub(r'\((\w+) & 0x7fffffffu\)', r'\1', hlsl_text) + assert mutated != hlsl_text + return mutated + + +def reverse_order_outputs(x_word, y_word, mask_bit): + v12 = isa_abs(x_word) if mask_bit else x_word + v13 = wrong_neg_before_abs(x_word) if mask_bit else isa_abs(x_word) + v14 = isa_neg(y_word) if mask_bit else wrong_neg_before_abs(y_word) + v15 = wrong_neg_before_abs(S4_SEED) if mask_bit else isa_abs(S4_SEED) + return (v12, v13, v14, v15) + + +def drop_abs_outputs(x_word, y_word, mask_bit): + v12 = x_word + v13 = isa_neg(x_word) if mask_bit else x_word + v14 = isa_neg(y_word) + v15 = isa_neg(S4_SEED) if mask_bit else S4_SEED + return (v12, v13, v14, v15) + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + raise AssertionError(f"{label}: {detail}" if detail else label) + + +def check_controls(): + # 1. Exact off_diag.py shape: v_cndmask_b32_e64 v0, v0, |v0|, s30. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V0, 30, abs1=1)) + check('decodes exact off_diag shape', + asm == ['v_cndmask_b32_e64 v0, v0, |v0|, s30'], repr(asm)) + check('lowers |v0| on src1 with s30 mask', + emitted == 'v0 = (s30 & 1) ? (v0 & 0x7fffffffu) : v0;', emitted) + + # 2. |v0| and -|v0| on src0 and src1, and mixed combinations. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs0=1)) + check('|v0| on src0', + asm == ['v_cndmask_b32_e64 v0, |v0|, v1, s30'] + and emitted == 'v0 = (s30 & 1) ? v1 : (v0 & 0x7fffffffu);', emitted) + + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs0=1, neg0=1)) + check('-|v0| on src0 applies abs before neg', + asm == ['v_cndmask_b32_e64 v0, -|v0|, v1, s30'] + and emitted == 'v0 = (s30 & 1) ? v1 : ((v0 & 0x7fffffffu) ^ 0x80000000u);', emitted) + + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs1=1, neg1=1)) + check('-|v1| on src1 applies abs before neg', + asm == ['v_cndmask_b32_e64 v0, v0, -|v1|, s30'] + and emitted == 'v0 = (s30 & 1) ? ((v1 & 0x7fffffffu) ^ 0x80000000u) : v0;', emitted) + + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs0=1, neg0=1, abs1=1)) + check('-|v0| on src0 and |v1| on src1 together', + asm == ['v_cndmask_b32_e64 v0, -|v0|, |v1|, s30'] + and emitted == 'v0 = (s30 & 1) ? (v1 & 0x7fffffffu) : ((v0 & 0x7fffffffu) ^ 0x80000000u);', emitted) + + # 3. SGPR |s4| and -|s4|. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 0, S4, S4, 30, abs0=1, abs1=1, neg1=1)) + check('|s4| and -|s4| on SGPR sources', + asm == ['v_cndmask_b32_e64 v0, |s4|, -|s4|, s30'] + and emitted == 'v0 = (s30 & 1) ? ((s4 & 0x7fffffffu) ^ 0x80000000u) : (s4 & 0x7fffffffu);', emitted) + + # 4. Existing -v30 behavior unchanged, and neg(|v0|) spelling also lowers identically. + asm, emitted = translate_code(encode_vop2_e64(CNDMASK, 31, V30, V30, 0, neg1=1)) + check('-v30 keeps existing bit-31 flip', + emitted == 'v31 = (s0 & 1) ? (v30 ^ 0x80000000u) : v30;', emitted) + s_neg_paren = Stage() + s_neg_paren.one('v_cndmask_b32_e64', 'v_cndmask_b32_e64 v0, v0, neg(|v0|), s30') + check('neg(|v0|) spelling applies abs before neg', + ' '.join(s_neg_paren.lines) == 'v0 = (s30 & 1) ? ((v0 & 0x7fffffffu) ^ 0x80000000u) : v0;') + + # 5. Refusals preserved: ABS on immediates, ABS/NEG on mask, ABS on other integer ops, low16_only_v. + literal = struct.pack('<I', 0x12345678) + for src_enc, desc in ((128, 'inline 0'), (129, 'inline 1'), (193, 'inline -1'), + (240, 'inline 0.5'), (243, 'inline -1.0')): + check(f'ABS on {desc} src0 refused', refused_code(encode_vop2_e64(CNDMASK, 0, src_enc, V0, 30, abs0=1))) + check(f'ABS+NEG on {desc} src1 refused', + refused_code(encode_vop2_e64(CNDMASK, 0, V0, src_enc, 30, abs1=1, neg1=1))) + check('ABS on literal src1 refused', + refused_code(encode_vop2_e64(CNDMASK, 0, V0, 255, 30, abs1=1) + literal)) + check('ABS+NEG on literal src0 refused', + refused_code(encode_vop2_e64(CNDMASK, 0, 255, V0, 30, abs0=1, neg0=1) + literal)) + check('ABS on mask (src2) refused', refused_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, abs2=1))) + check('NEG on mask (src2) refused', refused_code(encode_vop2_e64(CNDMASK, 0, V0, V1, 30, neg2=1))) + check('ABS on v_and_b32_e64 refused', refused_code(encode_vop2_e64(AND_B32, 0, V0, V1, abs1=1))) + check('v_cndmask_b32 is not in UNIFORM_VALU', 'v_cndmask_b32' not in G.UNIFORM_VALU) + + s_low16 = Stage() + s_low16.low16_only_v = {0} + try: + s_low16.one('v_cndmask_b32_e64', 'v_cndmask_b32_e64 v1, v1, |v0|, s30') + low16_refused = False + except G.Unsupported: + low16_refused = True + check('|v0| on low16_only_v refused (reads all 32 bits)', low16_refused) + + # 6. Value-level evaluation across all 11 32-bit patterns distinguishing abs, neg, -|x|, and wrong orders. + # Construct a full Pipeline from synthetic PS_WORDS and evaluate its emitted HLSL expressions on CPU. + pipe = G.Pipeline(vs_words(0, 0, 0), PS_WORDS, root_blob_with_const()) + ps_hlsl = pipe.hlsl_ps() + check('PS pipeline translates cleanly', 'v12 = ' in ps_hlsl and 'v15 = ' in ps_hlsl, ps_hlsl) + decoded_ps = [asm for _o, _s, _n, asm in G.decode(PS_WORDS)] + check('PS decodes expected v_cndmask_b32_e64 instructions', + any('v_cndmask_b32_e64 v12, v0, |v0|, s30' == a for a in decoded_ps) + and any('v_cndmask_b32_e64 v15, |s4|, -|s4|, s30' == a for a in decoded_ps), repr(decoded_ps)) + + def eval_ps(text, x_word, y_word, mask_bit): + s30_rhs = re.search(r'^\s*s30 = (.*);$', text, re.M).group(1) + s4_rhs = re.search(r'^\s*s4 = (.*);$', text, re.M).group(1) + env = {'v0': x_word, 'v1': y_word, 'v2': mask_bit, 'ud1': 0} + env['s30'] = Expr(s30_rhs).run(env)[0] + env['s4'] = Expr(s4_rhs).run(env)[0] + out = [] + for reg in range(12, 16): + rhs = re.search(r'^\s*v%d = (.*);$' % reg, text, re.M).group(1) + out.append(Expr(rhs).run(env)[0]) + return tuple(out) + + for x in PATTERNS: + for mask_bit in (0, 1): + y = x ^ SIGN_BIT + got = eval_ps(ps_hlsl, x, y, mask_bit) + want = expected_outputs(x, y, mask_bit) + if got != want: + raise AssertionError(f'CPU eval mismatch for x=0x{x:08x} y=0x{y:08x} mask={mask_bit}: ' + f'got={got} want={want}') + check('CPU HLSL evaluator matches ISA reference on all 22 (11 patterns x 2 masks) combinations', True) + + # Verify the two mutation models fail against the ISA reference and match their own HLSL mutations. + rev_hlsl = mutate_reverse_order(ps_hlsl) + drop_hlsl = mutate_drop_abs(ps_hlsl) + rev_failures = 0 + drop_failures = 0 + for x in PATTERNS: + for mask_bit in (0, 1): + y = x ^ SIGN_BIT + want = expected_outputs(x, y, mask_bit) + rev_got = eval_ps(rev_hlsl, x, y, mask_bit) + if rev_got != reverse_order_outputs(x, y, mask_bit): + raise AssertionError(f'reverse-order evaluator disagreed with model at x=0x{x:08x}') + if rev_got != want: + rev_failures += 1 + drop_got = eval_ps(drop_hlsl, x, y, mask_bit) + if drop_got != drop_abs_outputs(x, y, mask_bit): + raise AssertionError(f'drop-abs evaluator disagreed with model at x=0x{x:08x}') + if drop_got != want: + drop_failures += 1 + check(f'reverse-order mutation differs from ISA on all {rev_failures}/22 cases', rev_failures == 22) + check(f'drop-abs mutation differs from ISA on {drop_failures}/22 cases', drop_failures == 22) + + +def run_draw_case(compiler, kind, vs_profile, ps_profile, renderer, adapter, directory, + tag, x_word, y_word, mask_bit, ps_cso, expected, *, expect_wrong=None): + vs_src = G.Pipeline(vs_words(x_word, y_word, mask_bit), PS_WORDS, root_blob_with_const()).hlsl_vs() + vs_cso = compile_hlsl(compiler, kind, vs_src, f'vs_{tag}_{kind}', vs_profile, directory) + run = draw(renderer, adapter, vs_cso, ps_cso, expected) + if expect_wrong is None: + if run.returncode: + raise AssertionError(f'{kind} {tag} failed\n{run.stdout}\n{run.stderr}') + print(f'{kind} {tag}: {expected}', flush=True) + else: + if run.returncode == 0 or f'actual={expect_wrong}' not in run.stderr: + raise AssertionError(f'{kind} {tag} mutation did not report actual={expect_wrong}\n' + f'{run.stdout}\n{run.stderr}') + print(f'{kind} {tag} mutation: fails as expected, reads {expect_wrong}', flush=True) + + +def check_draw(dxc, renderer, adapter, fxc=None): + check_controls() + ps_hlsl = G.Pipeline(vs_words(0, 0, 0), PS_WORDS, root_blob_with_const()).hlsl_ps() + rev_ps_hlsl = mutate_reverse_order(ps_hlsl) + drop_ps_hlsl = mutate_drop_abs(ps_hlsl) + + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + # Representative draw patterns covering +0/-0, +/-1, +/-qNaN, +/-inf, -denorm, +/-normal on mask=0 and mask=1. + draw_cases = [(x, x ^ SIGN_BIT, m) for x in PATTERNS for m in (0, 1)] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, ps_hlsl, f'ps_good_{kind}', ps_profile, directory) + rev_ps = compile_hlsl(compiler, kind, rev_ps_hlsl, f'ps_rev_{kind}', ps_profile, directory) + drop_ps = compile_hlsl(compiler, kind, drop_ps_hlsl, f'ps_drop_{kind}', ps_profile, directory) + for idx, (x_word, y_word, mask_bit) in enumerate(draw_cases): + expected = words_text(expected_outputs(x_word, y_word, mask_bit)) + run_draw_case(compiler, kind, vs_profile, ps_profile, renderer, adapter, directory, + f'case{idx}_x{x_word:08x}_m{mask_bit}', x_word, y_word, mask_bit, good_ps, expected) + # Negative / mutated draws: reversing neg/abs order and dropping abs must fail with exact wrong words. + for m_x, m_y, m_bit, label in ((0xbf800000, 0x3f800000, 1, 'neg_one_m1'), + (0x80000000, 0x00000000, 0, 'neg_zero_m0')): + expected = words_text(expected_outputs(m_x, m_y, m_bit)) + rev_wrong = words_text(reverse_order_outputs(m_x, m_y, m_bit)) + drop_wrong = words_text(drop_abs_outputs(m_x, m_y, m_bit)) + run_draw_case(compiler, kind, vs_profile, ps_profile, renderer, adapter, directory, + f'rev_{label}', m_x, m_y, m_bit, rev_ps, expected, expect_wrong=rev_wrong) + run_draw_case(compiler, kind, vs_profile, ps_profile, renderer, adapter, directory, + f'drop_{label}', m_x, m_y, m_bit, drop_ps, expected, expect_wrong=drop_wrong) + + +def main(): + if len(sys.argv) == 1: + check_controls() + print('PASS') + return + mode, *args = sys.argv[1:] + if mode == 'draw': + check_draw(*args) + print('PASS') + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_cndmask_neg_check.py b/tests/startup_gfx2hlsl_cndmask_neg_check.py index 60ca4b7267..49b866b547 100644 --- a/tests/startup_gfx2hlsl_cndmask_neg_check.py +++ b/tests/startup_gfx2hlsl_cndmask_neg_check.py @@ -157,15 +157,10 @@ def refused(code): check('a clamp on the select is refused', refused(encode_vop2_e64(CNDMASK, 31, V30, V30, clamp=1))) check('a mul:2 on the select is refused', refused(encode_vop2_e64(CNDMASK, 31, V30, V30, omod=1))) -# 8. Source absolute values and a negated mask reach `u()`/`u_src()` as text they cannot model, and are -# refused. llvm-mc rejects all three spellings, so they are decoder-produced words only; the property -# under test is that production refuses the printed operand rather than translating it. -check('an absolute value on the first source is refused', - refused(encode_vop2_e64(CNDMASK, 31, V30, V30, abs0=1))) -check('an absolute value on the second source is refused', - refused(encode_vop2_e64(CNDMASK, 31, V30, V30, abs1=1))) -check('absolute values on both sources are refused', - refused(encode_vop2_e64(CNDMASK, 31, V30, V30, abs0=1, abs1=1))) +# 8. A negated mask, ABS on an immediate, and ABS on another integer op stay refused; source ABS on +# v_cndmask_b32_e64 registers is lowered and tested by startup_gfx2hlsl_cndmask_abs_check.py. +check('an absolute value on another integer op stays refused', + refused(encode_vop2_e64(AND_B32, 1, V30, V30, abs1=1))) check('a negated mask is refused', refused(encode_vop2_e64(CNDMASK, 31, V30, V30, neg_mask=1))) check('ABS on an inline immediate is refused', diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 5cc703fd80..928589a0c9 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -4,7 +4,7 @@ binary <llvm-mc> reassemble the fixture sources and compare them with the words below dispatch <dxc> <offscreen_check> <warp|hardware> translate, compile with DXC cs_6_0, dispatch and compare every word - control <swapped-axes|dropped-store|b-offset|c-unpredicated|j-scalar-dropped|h-inner-unpredicated|m-else-unswitched> <dxc> <offscreen_check> <warp|hardware> + control <swapped-axes|dropped-store|b-offset|c-unpredicated|j-scalar-dropped|h-inner-unpredicated|m-else-unswitched|n-unmasked|o-mask-kept|s-min-strict|s-borrow-flipped> <dxc> <offscreen_check> <warp|hardware> the same dispatch with a mutated translation, which must mismatch The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) @@ -31,9 +31,17 @@ - case M is case H with an if/else in the skipped block: each arm has its own s_cbranch_execz, s_andn2_b32 of the saved mask switches to the else arm and s_mov_b32 restores it. Lanes tid.x < 3 store the first word, lanes 3-5 the second, the rest none. +- case N skips a block that only sets vcc from a compare; the join ANDs vcc with exec before it restores exec, and + the result selects the storing lanes. Lanes tid.x < 3 store one word; lanes 6 and 7 skip the block with vcc set. +- case O removes the lanes tid.x < 3 from the saved mask with s_andn2_b32 s0, s0, exec_lo inside the skipped block, + and the join moves s0 into exec. Lanes 3-7 store one word; lanes 6 and 7 skip the block and keep their bit. - case G reads two independently offset LDS dwords with the address in the first destination VGPR. - cases L-uint and L-unorm use the same formatted load with native descriptor stride and word 3 supplied by the harness. The descriptor selects unaligned UINT16 pairs or an UNORM8 field and permutes the outputs. +- cases O-dword and O-shift store in the `off` form (no VGPR address), so every lane of a group writes the same + address. O-dword: 8 lanes per group store key ^ group ID at byte 4 * group + 8 (SGPR soffset plus immediate). + O-shift: 32 lanes per group store (group ID, the (key, stride) pair shifted right by 4, 0) as four words at + byte 16 * group, the shape of a 64-bit shift of a scalar pair. The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's @@ -42,6 +50,7 @@ and Y group IDs at entry, drop the store, drop case B's immediate offset, drop case C's exec predicate, or drop a scalar statement inside case J's block; each must change the readback. """ +import itertools import struct import subprocess import sys @@ -238,6 +247,49 @@ def tidig(components): SOURCE_K = SOURCE_J.replace('v_cmp_gt_u32 vcc_lo, 3, v0\n', 'v_mov_b32 v6, s7\nv_cmp_eq_u32_e32 vcc_lo, 1, v6\n') WORDS_K = WORDS_J.replace(bytes.fromhex('8300887d'), bytes.fromhex('07020c7e' '810c847d')) +# Case P is the compiler's i1 phi with a per-lane old value (a blend). M (s23) holds lanes tid.x < 4 before the branch; the +# block, entered by lanes tid.x < 3 * group, clears M for the lanes it runs (s_andn2 with exec) and ORs in the odd lanes +# (a compare masked with exec); the lane select after the join reads M per lane. Group 0 skips the block with the whole +# wave, groups 1 and 2 enter with a partial wave (3 and 6 lanes) and group 3 with all of it. Case Q is the same with M set +# to all ones before the branch and `s_orn2 M, C, exec_lo` in the block. +SOURCE_P = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +s_mul_i32 s24, s7, 3 +v_cmp_gt_u32 s23, 4, v0 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, s24, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz 5 +s_andn2_b32 s23, s23, exec_lo +v_and_b32 v6, 1, v0 +v_cmp_ne_u32 vcc_lo, 0, v6 +s_and_b32 s22, vcc_lo, exec_lo +s_or_b32 s23, s23, s22 +s_mov_b32 exec_lo, s21 +v_not_b32 v6, v5 +v_cndmask_b32 v7, v5, v6, s23 +buffer_store_dword v7, v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_P = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '001030e004050380' '703f8cbf' + '07831893' '1700c4d484000200' '7e0395be' '1800887d' '6a03febe' '050088bf' '177e178a' '81000c36' '800c8a7d' + '6a7e1687' '17161788' '1503febe' '056f0c7e' '070001d5050d5e00' '001070e004070480' '000081bf') +SOURCE_Q = (SOURCE_P.replace('v_cmp_gt_u32 s23, 4, v0\n', 's_mov_b32 s23, -1\n').replace('s_cbranch_execz 5', 's_cbranch_execz 3') + .replace('s_andn2_b32 s23, s23, exec_lo\n', '') + .replace('s_and_b32 s22, vcc_lo, exec_lo\ns_or_b32 s23, s23, s22\n', 's_orn2_b32 s23, vcc_lo, exec_lo\n')) +WORDS_Q = (WORDS_P.replace(bytes.fromhex('1700c4d484000200'), bytes.fromhex('c10397be')) + .replace(bytes.fromhex('050088bf'), bytes.fromhex('030088bf')).replace(bytes.fromhex('177e178a'), b'') + .replace(bytes.fromhex('6a7e168717161788'), bytes.fromhex('6a7e178b'))) + # Case M is case H with the nested if as an if/else. Each arm has its own s_cbranch_execz; the then arm stores the # first word, s_andn2_b32 of the saved mask switches to the else arm, which stores the second, and s_mov_b32 # restores the saved mask. @@ -273,6 +325,137 @@ def tidig(components): '6a03febe' '0e0088bf' '07051693' '16041680' '16060a3a' '8300887d' '6a3c80be' '020088bf' '001070e004050480' '007e7e8a' '030088bf' '056f0c7e' '041070e004060480' '0003febe' '1503febe' '000081bf') +# Case NM skips a block that only sets vcc from a compare (lanes tid.x < 3 of the lanes tid.x < 6 that enter it); +# the join masks vcc with exec (s_and_b32 s23, vcc_lo, exec_lo) before it restores exec, and s23 later selects +# the lanes that store. vcc is all ones before the branch, so lanes 6 and 7, which skip the block, hold a stale +# vcc that only the exec mask removes. +SOURCE_NM = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_and_saveexec_b32 s0, vcc_lo +s_mov_b32 vcc_lo, -1 +s_cbranch_execz 1 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_b32 s23, vcc_lo, exec_lo +s_or_b32 exec_lo, exec_lo, s0 +v_xor_b32 v5, s4, v3 +s_mov_b32 exec_lo, s23 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_NM = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '7e0395be' '8600887d' + '6a3c80be' 'c103eabe' '010088bf' '8300887d' '6a7e1787' '7e007e88' '04060a3a' '1703febe' '001070e004050480' + '1503febe' '000081bf') + +# Case O enters the block with the lanes tid.x < 6 (s_and_saveexec_b32 s0 saves all eight), narrows exec to the +# lanes tid.x < 3 and removes them from the saved mask with s_andn2_b32 s0, s0, exec_lo inside the block; the join +# moves s0 into exec. Lanes 3-5 lose their bit nowhere and lanes 6 and 7 skip the block with theirs, so lanes 3-7 +# store one word. +SOURCE_O = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_and_saveexec_b32 s0, vcc_lo +s_cbranch_execz 3 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_b32 exec_lo, exec_lo, vcc_lo +s_andn2_b32 s0, s0, exec_lo +s_mov_b32 exec_lo, s0 +v_xor_b32 v5, s4, v3 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_O = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '7e0395be' '8600887d' + '6a3c80be' '030088bf' '8300887d' '7e6a7e87' '007e008a' '0003febe' '04060a3a' '001070e004050480' '1503febe' + '000081bf') + +# The two-mask loop from #2645. The displacements name the join, exit and head, respectively. +LOOP_BREAK_SOURCE = """\ +v_lshlrev_b32 v4, 2, v0 +v_mov_b32 v5, 9 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_b32 s22, exec_lo, vcc_lo +s_mov_b32 s23, s22 +s_mov_b32 s24, 1 +s_mov_b32 exec_lo, s22 +s_cbranch_execz 6 +v_cmpx_gt_u32 s24, v0 +s_andn2_b32 s22, s22, exec_lo +s_andn2_b32 s23, s23, exec_lo +s_cbranch_scc0 6 +s_mov_b32 exec_lo, s22 +v_mov_b32 v5, s24 +s_mov_b32 exec_lo, s23 +s_add_u32 s24, s24, 1 +s_cmp_ge_u32 s24, 4 +s_cbranch_scc0 65524 +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_mov_b32 exec_lo, s21 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_endpgm +""" +LOOP_BREAK_WORDS = bytes.fromhex( + '82000834 89020a7e 7e0395be 8300887d 7e6a1687 160397be 810398be 1603febe ' + '060088bf 1800a87d 167e168a 177e178a 060084bf 1603febe 18020a7e 1703febe ' + '18811880 188409bf f4ff84bf 06038abe 80038bbe 05030cf4000000fa 7fc08cbf ' + '1503febe 001070e004050480 000081bf') + +# #2645 T3: the same shape without the loop, so the exit target is the only open condition. The s_cbranch_scc0 +# inside the skipped block leaves to the run at word 17 (a descriptor load and its wait) that ends at the +# s_mov_b32 exec_lo, s21 restore; the join path falls through into the same run. Displacements name the join and +# the exit run. +EXIT_RUN_SOURCE = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_lshlrev_b32 v4, 2, v0 +v_mov_b32 v5, 9 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_and_saveexec_b32 s0, vcc_lo +s_cbranch_execz 4 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_b32 exec_lo, exec_lo, vcc_lo +s_andn2_b32 s0, s0, exec_lo +s_cbranch_scc0 2 +s_mov_b32 exec_lo, s0 +v_xor_b32 v5, s4, v0 +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_mov_b32 exec_lo, s21 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_endpgm +""" +EXIT_RUN_WORDS = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '82000834' '89020a7e' '7e0395be' '8600887d' + '6a3c80be' '040088bf' '8300887d' '7e6a7e87' '007e008a' '020084bf' '0003febe' '04000a3a' + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '1503febe' '001070e004050480' '000081bf') + + def saveexec_fixture(): # RDNA 2 ISA, SOP1: D takes old EXEC, then EXEC takes the bitwise result and SCC reports nonzero. # A single-thread group makes the lane bit the whole participating wave mask. @@ -345,6 +528,15 @@ def saveexec_fixture(): '7fc08cbf00008abfff08103a80000000ff101036fc0000001000d8d8080000067fc08cbf8002107e' 'a400d8d8080000077fc08cbf0786158f1500124a83121234001074e009060480000081bf') +# Case F-two-fills keeps the first bank and writes each lane's byte address to a second bank. +# Broadcast lane 37 from the second bank while the peer read still addresses the first. +SOURCE_F2 = SOURCE_F.replace('ds_write_b32 v4, v5 offset:16', + 'ds_write_b32 v4, v5 offset:16\nds_write_b32 v4, v4 offset:320').replace( + 'v8 offset:164', 'v8 offset:468') +WORDS_F2 = WORDS_F.replace(bytes.fromhex('100034d804050000'), + bytes.fromhex('100034d804050000400134d804040000')).replace( + bytes.fromhex('a400d8d808000007'), bytes.fromhex('d401d8d808000007')) + SOURCE_G = """\ s_mov_b32 s10, s6 s_mov_b32 s11, 0 @@ -393,25 +585,157 @@ def saveexec_fixture(): 'L-unorm': (1 << 12) | 1 | (4 << 3) | (7 << 6) | (5 << 9), # one, X, W, Y } +# Case N: v_readfirstlane_b32 of a buffer load whose address is the same for every lane (offset 0, no VGPR), xored +# into each lane's own read-buffer word. Lane i stores word0 ^ word[i]. SOURCE_N_VARYING loads the readfirstlane +# source at a per-lane offset (v0), which is not provably uniform and must be refused. +SOURCE_N = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +buffer_load_dword v1, off, s[12:15], 0 +s_waitcnt vmcnt(0) +v_readfirstlane_b32 s20, v1 +v_lshlrev_b32 v4, 2, v0 +buffer_load_dword v2, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +v_xor_b32 v3, s20, v2 +buffer_store_dword v3, v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_N = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '000030e000010380' + '703f8cbf' '0105287e' '82000834' '001030e004020380' + '703f8cbf' '1404063a' '001070e004030480' '000081bf') +N_LOAD = bytes.fromhex('000030e000010380') +N_LOAD_VARYING = bytes.fromhex('001030e000010380') +WORDS_N_VARYING = WORDS_N.replace(N_LOAD, N_LOAD_VARYING, 1) + +# Each group uses its ID as a low addend, overwrites that SGPR, and stores the +# low word, high word and SCC left by the high add. The fourth word stays untouched. +SOURCE_CARRY = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0 +s_waitcnt lgkmcnt(0) +s_mul_i32 s20, s7, 1 +s_add_u32 s20, s20, -2 +s_add_u32 s21, 0, src_scc +s_cselect_b32 s22, 1, 0 +s_lshl_b32 s23, s7, 4 +v_mov_b32_e32 v4, s23 +v_mov_b32_e32 v8, s20 +v_mov_b32_e32 v9, s21 +v_mov_b32_e32 v10, s22 +buffer_store_dwordx3 v[8:10], v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_CARRY = bytes.fromhex( + '06038abe 80038bbe 05030cf4000000fa 7fc08cbf 07811493 14c21480 80fd1580 81801685' + ' 0784178f 1702087e 1402107e 1502127e 1602147e 00107ce004080480 000081bf') + + +SCC_EDGES = (0, 0xffffffff, 0x7fffffff, 0x80000000) +SCC_OPS = ('s_add_u32', 's_sub_u32', 's_add_i32', 's_sub_i32', 's_min_u32', 's_max_u32', 's_min_i32', 's_max_i32') + + +def scc_fixture(): + """Group (x, y) of the 4 x 4 grid takes S0 = edge[x], S1 = edge[y] (0, -1, INT_MAX, INT_MIN); the runner accepts at most 5 groups per axis. Each s_add/s_sub/s_min/s_max forms is run + twice (the destination apart from S0, then the destination that is S0) and its SCC read right after; word 0 of the + group holds the 16 SCC bits, word 1 a hash of the 16 results. RDNA 2 ISA: s_add_u32 carry out, s_sub_u32 borrow, + s_add_i32 / s_sub_i32 signed overflow, s_min / s_max SCC = (D == S0).""" + lines = ['s_mov_b32 s10, s6', 's_mov_b32 s11, 0', 's_load_dwordx8 s[12:19], s[10:11], 0x0', 's_waitcnt lgkmcnt(0)', + 's_lshl_b32 s24, s8, 2', 's_add_u32 s24, s24, s7', 'v_lshlrev_b32 v4, 3, s24', 's_mov_b32 s22, s7', + 's_mov_b32 s23, s8'] + for reg, index in (('s20', 's22'), ('s21', 's23')): + lines.append('s_mov_b32 %s, 0' % reg) + for n, value in ((1, '-1'), (2, '0x7fffffff'), (3, '0x80000000')): + lines += ['s_cmp_eq_u32 %s, %d' % (index, n), 's_cselect_b32 %s, %s, %s' % (reg, value, reg)] + lines += ['s_mov_b32 s27, 0', 's_mov_b32 s28, 0'] + bit = 0 + for op in SCC_OPS: + for dst, init in (('s24', None), ('s26', 's_mov_b32 s26, s20')): + lines += ([init] if init else []) + [ + '%s %s, %s, s21' % (op, dst, dst if init else 's20'), 's_cselect_b32 s25, 1, 0', + 's_lshl_b32 s25, s25, %d' % bit, 's_or_b32 s27, s27, s25', 's_xor_b32 s28, s28, %s' % dst, + 's_lshl_b32 s28, s28, 1'] + bit += 1 + lines += ['v_mov_b32 v5, s27', 'buffer_store_dword v5, v4, s[16:19], 0 offen', 'v_add_nc_u32 v4, 4, v4', + 'v_mov_b32 v5, s28', 'buffer_store_dword v5, v4, s[16:19], 0 offen', 's_endpgm'] + return '\n'.join(lines) + '\n' + + +def scc_reference(a, b): + """(SCC bits, result hash) of the fixture for S0 = a, S1 = b, from the ISA rules (no code shared with the translator).""" + def signed(x): + return x - (1 << 32) if x >> 31 else x + bits = hashed = 0 + for n, op in enumerate(SCC_OPS): + for alias in (0, 1): + x = a # the aliased run starts from a copy of S0, which is S0 again + if op.endswith('add_u32'): + total = x + b + result, scc = total & MASK, total > MASK + elif op == 's_sub_u32': + result, scc = (x - b) & MASK, x < b + elif op == 's_add_i32': + result = (x + b) & MASK + scc = not -(1 << 31) <= signed(x) + signed(b) < (1 << 31) + elif op == 's_sub_i32': + result = (x - b) & MASK + scc = not -(1 << 31) <= signed(x) - signed(b) < (1 << 31) + else: + view = signed if op.endswith('i32') else (lambda v: v) + pick = min if 'min' in op else max + result = pick(x, b, key=view) + scc = result == x + bits |= int(scc) << (2 * n + alias) + hashed = ((hashed ^ result) << 1) & MASK + return bits, hashed + +WORDS_S = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf0882188f1807188004001ad583300000070396be080397be800394be' + '168106bfc1141485168206bfff141485ffffff7f168306bfff14148500000080800395be178106bfc1151585178206bf' + 'ff151585ffffff7f178306bfff1515850000008080039bbe80039cbe14151880818019851980198f1b191b881c181c89' + '1c811c8f14039abe1a151a80818019851981198f1b191b881c1a1c891c811c8f14159880818019851982198f1b191b88' + '1c181c891c811c8f14039abe1a159a80818019851983198f1b191b881c1a1c891c811c8f14151881818019851984198f' + '1b191b881c181c891c811c8f14039abe1a151a81818019851985198f1b191b881c1a1c891c811c8f1415988181801985' + '1986198f1b191b881c181c891c811c8f14039abe1a159a81818019851987198f1b191b881c1a1c891c811c8f14159883' + '818019851988198f1b191b881c181c891c811c8f14039abe1a159a83818019851989198f1b191b881c1a1c891c811c8f' + '1415988481801985198a198f1b191b881c181c891c811c8f14039abe1a159a8481801985198b198f1b191b881c1a1c89' + '1c811c8f1415188381801985198c198f1b191b881c181c891c811c8f14039abe1a151a8381801985198d198f1b191b88' + '1c1a1c891c811c8f1415188481801985198e198f1b191b881c181c891c811c8f14039abe1a151a8481801985198f198f' + '1b191b881c1a1c891c811c8f1b020a7e001070e0040504808408084a1c020a7e001070e004050480000081bf' +) + CASES = { # name: (source, words, rsrc2, group size, group counts) 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | TGID_Y | TGID_Z | tidig(3), (2, 3, 4), (3, 2, 2)), + 'address-carry': (SOURCE_CARRY, WORDS_CARRY, USER7 | TGID_X, (1, 1, 1), (4, 1, 1)), 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | TGID_Z | tidig(2), (5, 2, 1), (4, 1, 3)), 'C': (SOURCE_C, WORDS_C, USER7 | TGID_Y | tidig(1), (8, 1, 1), (1, 5, 1)), 'D': (SOURCE_D, WORDS_D, USER7 | TGID_X | tidig(3), (4, 2, 4), (2, 1, 1)), 'D-wrap': (SOURCE_D_WRAP, WORDS_D_WRAP, USER7 | TGID_X | tidig(3), (4, 2, 4), (2, 1, 1)), 'E': (*saveexec_fixture(), USER7 | TGID_X | tidig(1), (1, 1, 1), (4, 1, 1)), 'F': (SOURCE_F, WORDS_F, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), + 'F-two-fills': (SOURCE_F2, WORDS_F2, USER7 | TGID_X | (2 << 15), (64, 1, 1), (2, 1, 1)), 'J': (SOURCE_J, WORDS_J, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'M': (SOURCE_M, WORDS_M, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'NM': (SOURCE_NM, WORDS_NM, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'O': (SOURCE_O, WORDS_O, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'P': (SOURCE_P, WORDS_P, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'Q': (SOURCE_Q, WORDS_Q, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), **{name: (SOURCE_L, WORDS_L, USER7, (16, 1, 1), (1, 1, 1)) for name in L_WORD3}, + 'N': (SOURCE_N, WORDS_N, USER7 | tidig(1), (16, 1, 1), (1, 1, 1)), + 'S': (scc_fixture(), WORDS_S, USER7 | TGID_X | TGID_Y | tidig(1), (1, 1, 1), (4, 4, 1)), } # Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. STORE_A = WORDS_A.index(bytes.fromhex('001070e004050480')) +SCC_LANE_SELECT = 'v_cndmask_b32_e64 v5, 0, 1, s20' SPLICE = { 's_cmp_lt_u32 s7, 4': '07840abf', 's_and_b32 s13, s13, 0xc000ffff': '0dff0d87ffff00c0', @@ -422,7 +746,7 @@ def saveexec_fixture(): 's_cmov_b32 s20, 1': '810594be', 's_cmov_b64 s[20:21], s[4:5]': '040694be', 's_cmovk_i32 s20, 3': '030014b1', - 's_cbranch_scc0 1': '010084bf', + 's_cbranch_scc0 2': '020084bf', 's_cbranch_scc1 1': '010085bf', 's_cbranch_vccz 1': '010086bf', 'v_mov_b32 v3, 0': '8002067e', @@ -441,6 +765,7 @@ def saveexec_fixture(): 's_add_u32 s20, s7, 1': '07811480', 's_or_b32 exec_lo, exec_lo, s0': '7e007e88', 'v_mov_b32 v5, s20': '14020a7e', + SCC_LANE_SELECT: '050001d580025100', 's_mov_b32 s21, exec_lo': '7e0395be', 's_mov_b32 exec_lo, vcc_lo': '6a03febe', 's_mov_b32 exec_lo, s21': '1503febe', @@ -468,6 +793,7 @@ def saveexec_fixture(): 's_bfe_u32 s21, s29, 0xe0010': '1dff959310000e00', 's_max_u32 s21, s21, 1': '15819584', 's_max_u32 s21, s21, 2': '15829584', + 'v_cmp_gt_u32_e64 s21, 3, v0': '1500c4d483000200', 's_bfe_u32 s21, s17, 0xe0011': '11ff959311000e00', 's_mul_i32 s18, s18, s21': '12151293', 's_mul_i32 s18, s18, 4': '12841293', @@ -482,6 +808,12 @@ def saveexec_fixture(): 's_mov_b32 s19, s31': '1f0393be', 's_mov_b32 s17, s29': '1d0391be', 's_cbranch_scc1 2': '020085bf', + 'buffer_store_dword v5, off, s[16:19], 0': '000070e000050480', + 'buffer_store_dword v5, off, s[16:19], s20 offset:8': '080070e000050414', + 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0': '000074e000050480', + 'v_lshrrev_b64 v[5:6], 4, s[20:21]': '050000d784280000', + 'v_lshrrev_b64 v[5:6], 4, v[3:4]': '050000d784060200', + 's_cbranch_execz 4': '040088bf', } @@ -489,6 +821,11 @@ def splice(*lines, at=STORE_A): return WORDS_A[:at] + b''.join(bytes.fromhex(SPLICE[line]) for line in lines) + WORDS_A[at:] +def replace_store(*lines): + """Case A with its store replaced by `lines` (the last one is the new store).""" + return WORDS_A[:STORE_A] + b''.join(bytes.fromhex(SPLICE[line]) for line in lines) + WORDS_A[STORE_A + 8:] + + # Case I is case A with the store descriptor's stride field cleared before the store (expected words as case A). STRIDE_CLEAR = 's_and_b32 s17, s17, 0xc000ffff' CASES['I'] = (SOURCE_A.replace('buffer_store_dword', STRIDE_CLEAR + '\nbuffer_store_dword'), splice(STRIDE_CLEAR), @@ -503,11 +840,66 @@ def splice(*lines, at=STORE_A): CASES['I-raw'] = (SOURCE_A.replace('buffer_store_dword', '\n'.join((*RAW_CONVERSION, 'buffer_store_dword'))), splice(*RAW_CONVERSION), *CASES['A'][2:]) +# Case I-raw-mask: s21 first holds a lane mask (a compare in a 24-lane group), then the clamped stride of the same +# conversion. The descriptor-data write ends the mark, so the clamp is not a lane-mask read and the store lands as +# in case A. The translator before that change refused it: s_max_u32 reads lane mask s21 as numeric data. +MASK_S21 = 'v_cmp_gt_u32_e64 s21, 3, v0' +CLAMPED_CONVERSION = (STRIDE_EXTRACT, 's_max_u32 s21, s21, 1', *RAW_CONVERSION[1:]) +CASES['I-raw-mask'] = (SOURCE_A.replace('buffer_store_dword', + '\n'.join((MASK_S21, *CLAMPED_CONVERSION, 'buffer_store_dword'))), + splice(MASK_S21, *CLAMPED_CONVERSION), *CASES['A'][2:]) + # Replace the nonzero stride constant in s5 with the first active lane of a # fresh 24-thread group. Ignoring FF1 leaves a different word at every i > 0. CASES['A-ff1'] = ('s_ff1_i32_b32 s5, exec_lo\n' + SOURCE_A, bytes.fromhex('7e1385be') + WORDS_A, *CASES['A'][2:]) +# `off` stores: the words are hand-assembled from the RDNA 2 SOP1/SOP2/VOP1/VOP3/MUBUF field layouts (the binary +# mode reassembles them with llvm-mc); check_hand_words decodes them with the repository disassembler. +OFF_PROLOGUE = 's_mov_b32 s10, s6\ns_mov_b32 s11, 0\ns_load_dwordx8 s[12:19], s[10:11], 0x0\ns_waitcnt lgkmcnt(0)\n' +OFF_PROLOGUE_WORDS = '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' +SOURCE_O_DWORD = OFF_PROLOGUE + """\ +s_lshl_b32 s20, s7, 2 +s_xor_b32 s21, s4, s7 +v_mov_b32 v5, s21 +buffer_store_dword v5, off, s[16:19], s20 offset:8 +s_endpgm +""" +WORDS_O_DWORD = bytes.fromhex(OFF_PROLOGUE_WORDS + '0782148f' '04071589' '15020a7e' '080070e000050414' '000081bf') +SOURCE_O_SHIFT = OFF_PROLOGUE + """\ +s_mov_b32 s20, s4 +s_mov_b32 s21, s5 +s_lshl_b32 s22, s7, 4 +v_lshrrev_b64 v[5:6], 4, s[20:21] +v_mov_b32 v4, s7 +v_mov_b32 v7, 0 +buffer_store_dwordx4 v[4:7], off, s[16:19], s22 +s_endpgm +""" +WORDS_O_SHIFT = bytes.fromhex(OFF_PROLOGUE_WORDS + '040394be' '050395be' '0784168f' '050000d784280000' '0702087e' + '80020e7e' '000078e000040416' '000081bf') +CASES['O-dword'] = (SOURCE_O_DWORD, WORDS_O_DWORD, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)) +CASES['O-shift'] = (SOURCE_O_SHIFT, WORDS_O_SHIFT, USER7 | TGID_X | tidig(1), (32, 1, 1), (4, 1, 1)) + +# Two groups reach the same load from different branch arms. Each of their lanes must read its group's word. +SOURCE_JOIN_LOAD = OFF_PROLOGUE + """\ +s_cmp_eq_u32 s7, 0 +s_cbranch_scc0 1 +s_nop 0 +s_lshl_b32 s3, s7, 2 +buffer_load_dword v7, off, s[12:15], s3 +s_waitcnt vmcnt(0) +v_readfirstlane_b32 s24, v7 +v_mov_b32_e32 v7, s24 +v_lshl_add_u32 v4, s7, 3, v0 +v_lshlrev_b32_e32 v4, 2, v4 +buffer_store_dword v7, v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_JOIN_LOAD = bytes.fromhex(OFF_PROLOGUE_WORDS + '078006bf 010084bf 000080bf 0782038f 000030e000070303 ' + '703f8cbf 0705307e 18020e7e 040046d707060104 82080834 001070e004070480 000081bf') +CASES['join-load'] = (SOURCE_JOIN_LOAD, WORDS_JOIN_LOAD, USER7 | TGID_X, (8, 1, 1), (2, 1, 1)) + def root_blob(constants=2, table_range=False): """RTS0: param 0 = root constants (b0), param 1 = a descriptor table with no ranges. @@ -530,6 +922,26 @@ def input_word(i): return (0x8b02a7f1 + i * 0x413b1) & MASK # tests/compute_check.cpp fills the read buffer this way +# Read the shifted field after the first branch. A zero root constant skips the read and store. +FIELD_TAIL = """\ +s_cmp_eq_u32 s4, 0 +s_cbranch_scc1 5 +v_readfirstlane_b32 s24, v1 +v_mov_b32_e32 v7, s24 +v_lshlrev_b32_e32 v4, 2, v0 +buffer_store_dword v7, v4, s[16:19], 0 offen +s_endpgm +""" +FIELD_TAIL_WORDS = '048006bf 050085bf 0105307e 18020e7e 82000834 001070e004070480 000081bf' +for name, form, encoded, size in ( + ('masked-tid', 'v_and_or_b32 v2, v0, 3, s4\nv_lshrrev_b32_e32 v1, 2, v2', + '020071d700071100 8204022c', 128), + ('extracted-tid', 'v_bfe_u32 v2, v0, 2, 3\nv_lshrrev_b32_e32 v1, 1, v2', + '020048d500050d02 8104022c', 8)): + CASES[name] = (OFF_PROLOGUE + form + '\n' + FIELD_TAIL, bytes.fromhex(OFF_PROLOGUE_WORDS + encoded + FIELD_TAIL_WORDS), + USER7, (size, 1, 1), (1, 1, 1)) + + def formatted_input(): # Every selected R8_UNORM field is an exact endpoint, while the UINT16 halves # are all distinct and the neighbouring bytes are nonzero. @@ -541,10 +953,35 @@ def formatted_input(): def expected(name): - if name in ('I', 'I-raw'): + if name in ('I', 'I-raw', 'I-raw-mask'): return expected('A') out = [SENTINEL] * WORDS + if name == 'join-load': + for i in range(16): + out[i] = input_word(i // 8) + return out + if name == 'O-loop-subset': + out[:8] = [9, 1, 2, 9, 9, 9, 9, 9] + return out + if name == 'O-dword': + for group in range(4): + out[2 + group] = KEY ^ group + return out + if name == 'O-shift': + pair = (STRIDE << 32 | KEY) >> 4 + for group in range(4): + out[4 * group:4 * group + 4] = [group, pair & MASK, pair >> 32, 0] + return out _, _, _, local, groups = CASES[name] + if name in ('masked-tid', 'extracted-tid'): + for lane in range(local[0]): + out[lane] = (((lane & 3) | KEY) >> 2 if name == 'masked-tid' else (((lane >> 2) & 7) >> 1)) + return out + if name == 'address-carry': + for group in range(groups[0]): + total = group + 0xfffffffe + out[4 * group:4 * group + 3] = [total & 0xffffffff, total >> 32, 0] + return out if name in L_WORD3: data = formatted_input() for lane in range(16): @@ -557,6 +994,13 @@ def expected(name): result = (one, one if data[at] == 255 else 0, one, 0) out[4 * lane:4 * lane + 4] = result return out + if name == 'N': + out[:16] = [input_word(0) ^ input_word(lane) for lane in range(16)] + return out + if name == 'S': + for group in range(16): + out[2 * group:2 * group + 2] = scc_reference(SCC_EDGES[group & 3], SCC_EDGES[group >> 2]) + return out producer_offsets = {'G': (1, 32), 'G-offset0-only': (31, 0), 'G-offset1-only': (0, 31)} if name in producer_offsets: # The original fill begins at dword 4, the single-field variants at dword 0. @@ -568,11 +1012,12 @@ def expected(name): index = 2 * (64 * group + lane) out[index:index + 2] = [stored[base + first], stored[base + second]] return out - if name == 'F': + if name in ('F', 'F-two-fills'): for group in range(2): for lane in range(64): index = (64 * group + lane) * 2 - out[index:index + 2] = [256 * group + (lane ^ 32), 256 * group + 37] + broadcast = 4 * 37 if name == 'F-two-fills' else 256 * group + 37 + out[index:index + 2] = [256 * group + (lane ^ 32), broadcast] return out if name == 'E': # Group IDs 0..3 encode (old EXEC, S0) = (0,0), (0,1), (1,0), (1,1). @@ -598,6 +1043,11 @@ def expected(name): i = (gx + 3 * gy + 6 * gz) * 24 + tx + 2 * ty + 6 * tz stride = 0 if name == 'A-ff1' else STRIDE out[i] = ((input_word(i) * 33) & MASK) ^ ((KEY + i * stride) & MASK) + elif name in ('P', 'Q'): + i = gx * 8 + tx + old = 1 if name == 'Q' else int(tx < 4) + mask = (tx & 1) if tx < 3 * gx else old # the block's lanes take the compare, others keep M + out[i] = ~input_word(i) & MASK if mask else input_word(i) elif name == 'K': i = gx * 8 + tx if gx == 1: # only group 1's wave enters the block @@ -616,6 +1066,14 @@ def expected(name): out[2 * i] = value elif tx < 6: # the else arm; lanes 6 and 7 skip the block out[2 * i + 1] = ~value & MASK + elif name == 'NM': + i = gx * 8 + tx + if tx < 3: # vcc & exec: the compare's lanes; lanes 6 and 7 skip it with vcc set + out[i] = i ^ KEY + elif name == 'O': + i = gx * 8 + tx + if tx >= 3: # the saved mask less the lanes the block kept; 6 and 7 skip it + out[i] = i ^ KEY elif name == 'J': i = gx * 8 + tx if tx < 3: # the lanes the compare leaves active; the others skip the block @@ -661,6 +1119,8 @@ def patch(words, old, new): words = patch(WORDS_G, '100034d804050000', '000034d804050000') words = patch(words, '0524dcd806000006', offset_bytes + 'dcd806000006') CASES[f'G-{field}-only'] = (source, words, *CASES['G'][2:]) +CASES['O-loop-subset'] = (LOOP_BREAK_SOURCE.replace('s_cbranch_scc0 6\n', 's_nop 0\n', 1), + patch(LOOP_BREAK_WORDS, '060084bf', '000080bf'), USER7 | TGID_X | tidig(1), (8, 1, 1), (1, 1, 1)) MBCNT_REFUSALS = ( @@ -674,6 +1134,250 @@ def patch(words, old, new): ) +def check_execz_loop_break(): + # Trace the fixture once as a wave and once per singleton. Both saved masks lose + # the same lanes. SCC tests the entire remaining mask at the early exit. + def trace(lanes): + remaining = {lane for lane in lanes if lane < 3} + values = dict.fromkeys(lanes, 9) + counter = 1 + while counter < 4: + if remaining: # otherwise execz goes straight to the join + remaining = {lane for lane in remaining if lane >= counter} + if not remaining: + break + values.update(dict.fromkeys(remaining, counter)) + counter += 1 + return values, counter + + lanes = range(8) + wave, counter = trace(lanes) + singles = [trace([lane]) for lane in lanes] + assert list(wave.values()) == [values[lane] for lane, (values, _) in enumerate(singles)] == [9, 1, 2, 9, 9, 9, 9, 9] + # Make the scalar counter observable after restoring EXEC. Lane 0 leaves before + # the wave, while lanes 3..7 follow the latch even after the wave has left. + assert counter == 3 and [c for _, c in singles] == [1, 2, 3, 4, 4, 4, 4, 4] + store = '001070e004050480' + with_counter = patch(LOOP_BREAK_WORDS, store, '18020a7e' + store) + reason = 's_cbranch_scc0 inside a block s_cbranch_execz skips per lane: loop exit crosses a backward s_cbranch_scc0' + for program in (LOOP_BREAK_WORDS, with_counter): + refused(reason, lambda: translate('O', code=program).hlsl_cs()) + # Removing only the guard accepts the program. Removing only the latch still leaves two different + # remasks and scalar counter work on the staying path, outside the straight T3 proof. + translate('O', code=patch(LOOP_BREAK_WORDS, '060088bf', '000080bf')).hlsl_cs() + latch_nop = patch(LOOP_BREAK_WORDS, 'f4ff84bf', '000080bf') + refused('s_cbranch_scc0 inside a block s_cbranch_execz skips per lane: branch out of the block', + lambda: translate('O', code=latch_nop).hlsl_cs()) + + +def check_execz_exit_run(): + # The exit target of the s_cbranch_scc0 inside the skipped block starts a scalar run (a descriptor load and + # its wait) that ends at the s_mov_b32 exec_lo, s21 restore. Trace the fixture once as a wave and once per + # singleton: both store 9 for lanes 0-2 (in the model they leave through the exit with v5 untouched, in the + # wave the branch is not taken and their v_xor is predicated off) and KEY ^ lane for lanes 3-7. + def trace(lanes, remask=True, scalar_on_stay=False): + values = dict.fromkeys(lanes, 9) + exec = set(lanes) + s21, s0 = set(exec), set(exec) + scalar = 9 + exec &= {lane for lane in lanes if 6 > lane} # s_and_saveexec_b32 s0, vcc_lo + if exec: # s_cbranch_execz: the block runs + exec &= {lane for lane in lanes if 3 > lane} # s_and_b32 exec_lo, exec_lo, vcc_lo + s0 -= exec # s_andn2_b32 s0, s0, exec_lo + if s0: # s_cbranch_scc0 not taken: the join path + exec = s0 if remask else s21 + scalar = 1 + values.update({lane: KEY ^ lane for lane in exec}) # v_xor_b32 v5, s4, v0 + else: # the model skips the block, the join restores s0 + exec = s0 + scalar = 1 + values.update({lane: KEY ^ lane for lane in exec}) + exec = s21 # the exit run's restore s_mov_b32 exec_lo, s21 + return [scalar if scalar_on_stay else values[lane] for lane in sorted(exec)] + + lanes = range(8) + def singletons(lanes, **kwargs): + return [trace([lane], **kwargs)[0] for lane in lanes] + + assert trace(lanes) == singletons(lanes) == [9, 9, 9] + [KEY ^ lane for lane in range(3, 8)] + # This group has only breaking lanes, so the hardware wave also takes the exit. + assert trace(range(3)) == singletons(range(3)) == [9, 9, 9] + translate('O', code=EXIT_RUN_WORDS, group=(3, 1, 1)).hlsl_cs() + # Pin the accepted upper edge of the single-wave32 scope bound (`x * y * z <= 32`). + translate('O', code=EXIT_RUN_WORDS, group=(32, 1, 1)).hlsl_cs() + assert trace(lanes, remask=False)[0] == KEY + assert singletons(lanes, remask=False)[0] == 9 + assert trace(lanes, scalar_on_stay=True)[0] == 1 + assert singletons(lanes, scalar_on_stay=True)[0] == 9 + text = translate('O', code=EXIT_RUN_WORDS).hlsl_cs() + # The exit branch is decided per lane, and the run's restore lands in the block the store follows. + assert '(!scc) ?' in text and 'exec = (s21) & 1;' in text, text + wide = patch(patch(EXIT_RUN_WORDS, '7e0395be', '7e0494be'), '1503febe', '1404febe') + assert 'exec = (s20) & 1;' in translate('O', code=wide).hlsl_cs() + # Near-misses: the run must be scalar instructions without effects outside registers up to the move into + # exec. A barrier or a sendmsg (wave-wide effects), a branch, a vector op, or no exec move at all (the run + # then reaches the store) each keep the refusal. Bytes 68/72/84/88 are the run's words 17/18/21/22. + def swap(at, new, code=EXIT_RUN_WORDS): + return code[:at] + bytes.fromhex(new) + code[at + 4:] + + reason = 's_cbranch_scc0 inside a block s_cbranch_execz skips per lane: branch out of the block' + # Workgroups above 32 threads are outside this single-wave32 proof. + for big in ((33, 1, 1), (64, 1, 1)): + refused(reason, lambda group=big: translate('O', code=EXIT_RUN_WORDS, group=group).hlsl_cs()) + for at, new in ((28, '800395be'), # s_mov_b32 s21, 0: restore mask was never saved from EXEC + (36, '800380be'), # s_mov_b32 s0, 0: ANDN2 source mask was never saved from EXEC + (52, '007e168a'), # s_andn2_b32 s22, s0, exec_lo: destination differs from source + (60, '1503febe'), # remask from s21: breaking lanes are active in the wave's v_xor + (84, '00008abf'), # s_barrier 0x0 in place of the run's s_waitcnt + (84, '090090bf'), # s_sendmsg 0x9 + (84, '01008fbf'), # s_setprio 1 + (72, '010082bf'), # s_branch inside the run + (68, '89020a7e'), # v_mov_b32 v5, 9: not a scalar instruction + (68, '7e0399be'), # s_mov_b32 s25, exec_lo: the two paths reach the run with different EXEC + (68, '800395be'), # s_mov_b32 s21, 0: clobbers the mask the restore uses + (88, '8003febe'), # s_mov_b32 exec_lo, 0: no saved-mask restore + (88, '1503ffbe'), # s_mov_b32 exec_hi, s21: does not restore the remasked half + (88, '000080bf'), # s_nop in place of the restore + (56, '050084bf'), # branch into the second word of s_load_dwordx8 + (56, 'ff7f84bf')): # branch past the end of the program + refused(reason, lambda code=swap(at, new): translate('O', code=code).hlsl_cs()) + refused(reason.replace('scc0', 'scc1'), lambda: translate('O', code=swap(56, '020085bf')).hlsl_cs()) + # On the staying path s25 is overwritten. The run reads it into s26 and the first vector op after + # the restore stores that value, exposing the 1 versus 9 traced above for lane 0. + code = swap(68, '19039abe', swap(64, '810399be')) # s_mov_b32 s25, 1; s_mov_b32 s26, s25 + code = bytes.fromhex('890399be') + code[:92] + bytes.fromhex('1a020a7e') + code[92:] + refused(reason, lambda: translate('O', code=code).hlsl_cs()) + # SCC after the scalar run still has the stay-mask test's wave/singleton difference. + code = EXIT_RUN_WORDS[:92] + bytes.fromhex('fd0399be19020a7e') + EXIT_RUN_WORDS[92:] + refusals = [] + G.ComputePipeline(code, root_blob(), CASES['O'][2], (8, 1, 1), refusals=refusals) + assert any(reason in text for text, _ in refusals), refusals + + +def check_execz_mask_subset(): + """Pre-branch EXEC subset tracking (#2645 T1): sM <= EXEC carried into an execz block lets remasks preserve skipped bits.""" + # With the early exit branch replaced by s_nop, the counted loop still exercises s_mov_b32 exec_lo, s22 before + # s_cbranch_execz and s_andn2_b32 + s_mov_b32 exec_lo, s22 inside the skipped block. + def trace_loop(lanes, narrow_before=False): + outer = {lane for lane in lanes} + if narrow_before: + # Saving s22 before narrowing EXEC makes s22 a superset of EXEC at s_cbranch_execz, not a subset. + saved = set(outer) + exec_mask = {lane for lane in outer if lane < 1} + else: + saved = {lane for lane in outer if lane < 3} + exec_mask = set(saved) + values = dict.fromkeys(lanes, 9) + for counter in range(1, 4): + if exec_mask: + breaking = {lane for lane in exec_mask if counter > lane} + saved -= breaking + exec_mask = set(saved) # s_mov_b32 exec_lo, saved + values.update(dict.fromkeys(exec_mask, counter)) + exec_mask = set(saved) + return values + + lanes = range(8) + wave = trace_loop(lanes) + singles = [trace_loop([lane]) for lane in lanes] + assert list(wave.values()) == [s[lane] for lane, s in enumerate(singles)] == [9, 1, 2, 9, 9, 9, 9, 9] + # Near-miss wave-vs-singleton disagreement when the saved mask holds skipped lanes: lane 1 skips the block in the + # singleton model (9) while the wave enters via lane 0 and re-enables lane 1 through the stale saved mask (1). + bad_wave = trace_loop(lanes, narrow_before=True) + bad_singles = [trace_loop([lane], narrow_before=True) for lane in lanes] + assert bad_wave[1] == 1 and bad_singles[1][1] == 9 + + hlsl = translate('O-loop-subset').hlsl_cs() + assert 'exec = (s22) & 1;\n if (exec & 1) v5 = s24;' in hlsl, hlsl + # LOOP_BREAK_WORDS drops the T1 exec write refusal while keeping T2 (loop exit crosses a backward s_cbranch_scc0). + st = object.__new__(G.Stage) + st.kind = 'cs' + st.ins = G.decode(LOOP_BREAK_WORDS) + st.calculated_pc = {} + assert st.execz_refusals() == { + 0x30: 's_cbranch_scc0 inside a block s_cbranch_execz skips per lane: loop exit crosses a backward s_cbranch_scc0' + } + + # Build straight-line execz checks from llvm-mc-15 verified instructions in SPLICE / LOOP_BREAK_WORDS. + W = dict(SPLICE) + W.update({ + 's_nop 0': '000080bf', + 's_and_b32 s22, exec_lo, vcc_lo': '7e6a1687', + 's_mov_b32 s23, s22': '160397be', + 's_mov_b32 s24, 1': '810398be', + 'v_cmpx_gt_u32 s24, v0': '1800a87d', + 's_andn2_b32 s22, s22, exec_lo': '167e168a', + 's_andn2_b32 s23, s23, exec_lo': '177e178a', + 's_mov_b32 exec_lo, s22': '1603febe', + 's_mov_b32 exec_lo, s23': '1703febe', + 'v_mov_b32 v5, s24': '18020a7e', + 's_and_b32 exec_lo, exec_lo, vcc_lo': '7e6a7e87', + 's_mov_b32 s23, 0': '800397be', + 's_mov_b32 vcc_lo, -1': 'c103eabe', + }) + end = bytes.fromhex('000081bf') + def seq(*lines): + return WORDS_A[:STORE_A] + b''.join(bytes.fromhex(W[line]) for line in lines) + end + + # Accepted pre-branch subset setup without re-assigning EXEC directly before s_cbranch_execz. + pre_and_copy = seq( + 's_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 3, v0', + 's_and_b32 s22, exec_lo, vcc_lo', 's_mov_b32 s23, s22', 's_mov_b32 s24, 1', + 's_cbranch_execz 4', 'v_cmpx_gt_u32 s24, v0', 's_andn2_b32 s23, s23, exec_lo', + 's_mov_b32 exec_lo, s23', 'v_mov_b32 v5, s24', 's_mov_b32 exec_lo, s21', + 'buffer_store_dword v5, v4, s[16:19], 0 offen', + ) + assert 'exec = (s23) & 1;' in translate('A', code=pre_and_copy).hlsl_cs() + pre_mov = seq( + 's_mov_b32 s21, exec_lo', 's_cbranch_execz 3', 's_mov_b32 exec_lo, s21', + 'v_mov_b32 v5, s24', 's_nop 0', 's_mov_b32 exec_lo, s21', + 'buffer_store_dword v5, v4, s[16:19], 0 offen', + ) + assert 'exec = (s21) & 1;' in translate('A', code=pre_mov).hlsl_cs() + + # Near-miss controls: each violates subset provenance and must stay refused as an exec write. + narrowed_saveexec = seq( + 's_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_saveexec_b32 s0, vcc_lo', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s24', 's_nop 0', + 's_or_b32 exec_lo, exec_lo, s0', 'buffer_store_dword v5, v4, s[16:19], 0 offen', + ) + narrowed_cmpx = seq( + 's_mov_b32 s24, 1', 's_mov_b32 s21, exec_lo', 'v_cmpx_gt_u32 s24, v0', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, s21', 's_nop 0', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + overwritten_before = seq( + 's_mov_b32 s21, exec_lo', 's_mov_b32 exec_lo, vcc_lo', 's_mov_b32 vcc_lo, -1', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, vcc_lo', 's_nop 0', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + overwritten_inside = seq( + 's_mov_b32 s21, exec_lo', 's_mov_b32 exec_lo, vcc_lo', + 's_cbranch_execz 3', 's_mov_b32 vcc_lo, -1', 's_mov_b32 exec_lo, vcc_lo', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + join_one_arm = seq( + 's_mov_b32 s21, exec_lo', 's_cbranch_scc1 2', 's_mov_b32 exec_lo, vcc_lo', 's_branch 2', + 's_mov_b32 vcc_lo, -1', 's_nop 0', + 's_cbranch_execz 3', 's_mov_b32 exec_lo, vcc_lo', 's_nop 0', 's_nop 0', + 's_mov_b32 exec_lo, s21', + ) + for near_miss in (narrowed_saveexec, narrowed_cmpx, overwritten_before, overwritten_inside, join_one_arm): + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', + lambda code=near_miss: translate('A', code=code).hlsl_cs()) + + # Unit checks for 64-bit moves and non-narrowing/invalidating steps in subset_after(). + assert G.subset_after('s_mov_b64', 's_mov_b64 exec, s[22:23]', {'exec', 'exec_hi', 'scc'}, G.EXEC_SUBSET) == ( + G.EXEC_SUBSET | {('s22', 0), ('s23', 1)}) + both = G.subset_after('s_mov_b64', 's_mov_b64 s[22:23], exec', {'s22', 's23', 'scc'}, G.EXEC_SUBSET) + assert both == (G.EXEC_SUBSET | {('s22', 0), ('s23', 1)}), both + assert G.subset_after('v_cmpx_gt_u32_e32', 'v_cmpx_gt_u32_e32 s24, v0', G.EXEC_KEYS, both) == G.EXEC_SUBSET + assert G.subset_after('s_movreld_b32', 's_movreld_b32 s0, s1', {'m0'}, both) == G.EXEC_SUBSET + assert G.subset_after('s_or_saveexec_b32', 's_or_saveexec_b32 s21, vcc_lo', + {'s21', 'exec', 'exec_hi', 'scc'}, {('exec', 0), ('exec_hi', 1), ('s22', 0)}) == ( + {('exec', 0), ('exec_hi', 1), ('s21', 0), ('s22', 0)}) + + def check_mbcnt(): for _, words, reason in MBCNT_REFUSALS: refused(reason, lambda: translate('D', code=bytes.fromhex(words + '000081bf'))) @@ -692,13 +1396,231 @@ def check_mbcnt(): assert 'uav 0 table 1 0' in translate('D').manifest() +LANE_MASK_DATA = ( + ('v_cvt_f32_u32 v5, vcc_lo', '6a0c0a7e'), # the llvm.amdgcn.ballot word converted to float + ('v_add_nc_u32 v5, vcc_lo, v5', '6a0a0a4a'), +) + + +def check_lane_mask_data(): + """A wave mask read as a number holds every lane's bit on hardware; the one-lane model has only its own.""" + compare = bytes.fromhex('8500027d') # v_cmp_lt_i32 vcc_lo, 5, v0 + select = bytes.fromhex('800a0a02') # v_cndmask_b32 v5, 0, v5, vcc_lo: the mask as a per-lane select + assert 'vcc = ' in translate('A', code=splice_words(compare, select)).hlsl_cs() + for _, word in LANE_MASK_DATA: + refused('as numeric data', lambda: translate('A', code=splice_words(compare, bytes.fromhex(word)))) + + +LANE_MASK_SCALAR_DATA = ( + ('s_cmpk_gt_u32 vcc_lo, 0x64', '6400eab5'), # c7_ballot_cmp: the ballot word compared as a number + ('s_cmp_lg_u32 vcc_lo, 0', '6a8007bf'), + ('s_lshr_b32 s6, vcc_lo, 1', '6a810690'), + ('s_add_u32 s6, vcc_lo, 1', '6a810680'), +) + + +def check_lane_mask_scalar_data(): + """A scalar op that reads a wave mask as a number sees every lane's bit on hardware; mask-only scalar ops stay.""" + compare = bytes.fromhex('8500027d') # v_cmp_lt_i32 vcc_lo, 5, v0 + for _, word in LANE_MASK_SCALAR_DATA: + refused('as numeric data', lambda: translate('A', code=splice_words(compare, bytes.fromhex(word)))) + translate('A', code=splice_words(compare, bytes.fromhex('6a7e0687'))).hlsl_cs() # s_and_b32 s6, vcc_lo, exec_lo + + +def check_lane_mask_derived_word(): + """A bitwise result of a lane mask is still a mask word: a later numeric read of it is refused.""" + compare = bytes.fromhex('8500027d') # v_cmp_lt_i32 vcc_lo, 5, v0 + mask_and = bytes.fromhex('6aff0687ff000000') # s_and_b32 s6, vcc_lo, 0xff + for use in ('060a887d', '060a0a4a'): # v_cmp_gt_u32 vcc_lo, s6, v5 ; v_add_nc_u32 v5, s6, v5 + refused('as numeric data', lambda: translate('A', code=splice_words(compare, mask_and, bytes.fromhex(use)))) + refused('as numeric data', lambda: translate('A', code=splice_words(compare, bytes.fromhex('6a0c0a7e')))) # v_cvt_f32_u32 v5, vcc_lo + + +def check_lane_mask_single_thread_group(): + """A one-thread group has one participating lane per wave: its lane bit is the whole mask (high word 0), so the one-lane + model is exact and a numeric read stays lowered (dispatch case E). With two threads the same program is refused.""" + compare = bytes.fromhex('8500027d') # v_cmp_lt_i32 vcc_lo, 5, v0 + cvt = bytes.fromhex('6a0c0a7e') # v_cvt_f32_u32 v5, vcc_lo: the mask as a number + code = splice_words(compare, cvt) + assert 'v5 = ' in translate('A', code=code, group=(1, 1, 1)).hlsl_cs() + for group in ((2, 1, 1), (1, 2, 1), (1, 1, 2), (4, 1, 1)): + refused('as numeric data', lambda: translate('A', code=code, group=group)) + xor_chunks = [bytes.fromhex(w) for w in ('000084d491000200', '8004027d', '6a008089')] + high = splice_words(*xor_chunks, bytes.fromhex('01020a7e')) # v_mov_b32 v5, s1: the high word + assert 'v5 = ' in translate('A', code=high, group=(1, 1, 1)).hlsl_cs() + refused('as numeric data', lambda: translate('A', code=high, group=(2, 1, 1))) + + +def check_lane_mask_high_word(): + """The high word of a wave64 mask (the ballot's upper 32 bits) is modelled as 0: a move of it is refused.""" + chunks = [bytes.fromhex(w) for w in ('0000 84d4 9100 0200'.replace(' ', ''), # v_cmp_gt_i32 s[0:1], 17, v0 + '8004027d', # v_cmp_lt_i32 vcc, 0, v2 + '6a008089')] # s_xor_b64 s[0:1], vcc, s[0:1] + for word in ('01020a7e', # v_mov_b32 v5, s1 + '010a0a4a', # v_add_nc_u32 v5, s1, v5 + '010c0a7e', # v_cvt_f32_u32 v5, s1 + '010a0a36', # v_and_b32 v5, s1, v5 + '01810780', # s_add_u32 s7, s1, 1 + '018006bf', # s_cmp_eq_u32 s1, 0 + '010387be'): # s_mov_b32 s7, s1 + refused('as numeric data', lambda: translate('A', code=splice_words(*chunks, bytes.fromhex(word)))) + # The compare alone leaves its high word unknown: refused too (earlier, by the unknown-SGPR rule). + refused('s1', lambda: translate('A', code=splice_words(chunks[0], bytes.fromhex('010a0a4a')))) + assert 'v5 = ud0;' in translate('A', code=splice_words(*chunks, bytes.fromhex('04020a7e'))).hlsl_cs() + + +def check_lane_mask_compare_pair(): + """A wave64 compare or carry-out into an even SGPR pair s[N:N+1] (the decoder names only sN) leaves the other 32 lanes in + s(N+1). Here s[4:5] are the two root constants, so s5 is a known register: a numeric read of it after the compare must + be refused, directly, through a copy of the pair, and through a copy of the high word.""" + reads = ('05020a7e', '050c0a7e', '050a0a36', '050a0a4a', # v_mov / v_cvt_f32_u32 / v_and / v_add with s5 + '05810781', '058006bf', '050387be') # s_add_i32 s7, s5, 1 / s_cmp_eq_u32 s5, 0 / s_mov_b32 s7, s5 + for write in ('040084d491000200', # v_cmp_gt_i32 s[4:5], 17, v0 + '06040fd700030200'): # v_add_co_u32 v6, s[4:5], v0, v1 + for read in reads: + refused('as numeric data', lambda write=write, read=read: translate('A', code=splice_words( + bytes.fromhex(write), bytes.fromhex(read)))) + for copy, use in (('040488be', '09810781'), # s_mov_b64 s[8:9], s[4:5]; s_add_i32 s7, s9, 1 + ('050388be', '08810781')): # s_mov_b32 s8, s5; s_add_i32 s7, s8, 1 + refused('as numeric data', lambda write=write, copy=copy, use=use: translate('A', code=splice_words( + bytes.fromhex(write), bytes.fromhex(copy), bytes.fromhex(use)))) + # before the compare s5 is the root constant: still a number the model has + translate('A', code=splice_words(bytes.fromhex('05810781'), bytes.fromhex('040084d491000200'))).hlsl_cs() + + +def check_lane_mask_copy_of_data_clears_tag(): + """A copy of plain data into a register that held a lane mask on an earlier path (a loop back edge) leaves no mask tag: + `s_load` through that pair is not a read of a mask. A copy of the mask itself is refused too.""" + loop = bytes.fromhex('0e00c4d483000200' # v_cmp_gt_u32 s14, 3, v0 + '800394be' # s_mov_b32 s20, 0 + '06038ebe' # L: s_mov_b32 s14, s6 (the table pointer) + '80038fbe' # s_mov_b32 s15, 0 + '070608f4000000fa' # s_load_dwordx4 s[24:27], s[14:15], 0x0 + '7fc08cbf' '14811481' '14830abf' # s_waitcnt; s_add_i32 s20, s20, 1; s_cmp_lt_u32 s20, 3 + 'f7ff85bf') # s_cbranch_scc1 L + translate('A', code=splice_words(loop)).hlsl_cs() + mask_copy = loop.replace(bytes.fromhex('06038ebe'), bytes.fromhex('0e038ebe')) # s_mov_b32 s14, s14: the mask itself + refused('s_load through s14', lambda: translate('A', code=splice_words(mask_copy)).hlsl_cs()) + + +def check_lane_mask_pair_copy_of_data_stays_refused(): + """A 64-bit copy of plain data (root constants s[4:5]) is lowered as a mask copy (the lane bit only), so its low word + must not be read as a number in a multi-thread group: the store would write 1, not the root constant.""" + copy = bytes.fromhex('040494be') # s_mov_b64 s[20:21], s[4:5] + use = bytes.fromhex('14020a7e') # v_mov_b32 v5, s20 + refused('is a lane mask', lambda: translate('A', code=splice_words(copy, use), group=(2, 1, 1)).hlsl_cs()) + # a 32-bit copy of the same plain word is a full-word copy and stays readable + word = bytes.fromhex('040394be') # s_mov_b32 s20, s4 + assert 'v5 = s20' in translate('A', code=splice_words(word, use), group=(2, 1, 1)).hlsl_cs() + + +def check_lane_mask_wqm_keeps_tag(): + """s_wqm_b32 is a no-op here (it writes nothing), so a mask it nominally rewrites from plain data keeps its tag: + the v_mov after it still reads a lane mask in a multi-thread group.""" + cmp_ = bytes.fromhex('140084d491000200') # v_cmp_gt_i32_e64 s20, 17, v0 + wqm = bytes.fromhex('800994be') # s_wqm_b32 s20, 0 + use = bytes.fromhex('14020a7e') # v_mov_b32 v5, s20 + refused('is a lane mask', lambda: translate('A', code=splice_words(cmp_, wqm, use), group=(4, 1, 1)).hlsl_cs()) + + +def check_lane_mask_high_word_copy_and_overwrite(): + """A copy of a mask's high word is itself only a high word (no low-word tag, so no '& 1' on a numeric use in a one-thread + group), and a wide write over a tagged pair ends the tag (no false refusal of the new value).""" + save = bytes.fromhex('7e0494be') # s_mov_b64 s[20:21], exec + copy = bytes.fromhex('150396be') # s_mov_b32 s22, s21: the high word + use = bytes.fromhex('16821788') # s_or_b32 s23, s22, 2 + cvt = bytes.fromhex('170c0a7e') # v_cvt_f32_u32 v5, s23 + one = translate('A', code=splice_words(save, copy, use, cvt), group=(1, 1, 1)).hlsl_cs() + assert 's23 = s22 | 0x00000002u;' in one, one + refused('as numeric data', lambda: translate('A', code=splice_words(save, copy, use, cvt), group=(2, 1, 1))) + shifted = splice_words(save, bytes.fromhex('0407948f'), bytes.fromhex('15020a7e')) # s_lshl_b64 s[20:21], s[4:5], s7 ; v_mov_b32 v5, s21 + assert 'v5 = ' in translate('A', code=shifted, group=(4, 1, 1)).hlsl_cs() + + +LANE_MASK_TAG = { + 'zero_s1': '800381be', # s_mov_b32 s1, 0: the high word the one-lane model holds as 0 + 'cmp_pair': '000084d491000200', # v_cmp_gt_i32 s[0:1], 17, v0 (writes only the low word of the pair) + 'cselect_pair': 'c1808085', # s_cselect_b64 s[0:1], -1, 0 + 'cmp_vcc': '8004027d', # v_cmp_lt_i32 vcc, 0, v2 + 'saveexec': '6a2480be', # s_and_saveexec_b64 s[0:1], vcc + 'copy_pair': '000488be', # s_mov_b64 s[8:9], s[0:1] + 'copy_vcc': '6a0488be', # s_mov_b64 s[8:9], vcc + 'copy_copy': '08048abe', # s_mov_b64 s[10:11], s[8:9] + 'xor_pair': '6a008089', # s_xor_b64 s[0:1], vcc, s[0:1] + 'clear_s9': '800389be', # s_mov_b32 s9, 0: a plain write ends the tag + 'read_s1': '01020a7e', # v_mov_b32 v5, s1 + 'read_s9': '09020a7e', # v_mov_b32 v5, s9 + 'read_s11': '0b020a7e', # v_mov_b32 v5, s11 + 'add_s9': '09810780', # s_add_u32 s7, s9, 1 +} + + +def check_lane_mask_tag_propagation(): + """The mask tag is set where a mask is written and moves with every copy: one case per way a tagged word is made, each + read back through a numeric use (a no-op tag at any of them lets a case translate).""" + w = {k: bytes.fromhex(v) for k, v in LANE_MASK_TAG.items()} + cases = [ + ('cselect writes a pair', ['zero_s1', 'cselect_pair', 'read_s1']), + ('saveexec writes a pair', ['zero_s1', 'cmp_vcc', 'saveexec', 'read_s1']), + ('bitwise op writes a pair', ['zero_s1', 'cmp_pair', 'cmp_vcc', 'xor_pair', 'read_s1']), + ('b64 copy of a pair', ['cmp_pair', 'cmp_vcc', 'xor_pair', 'copy_pair', 'read_s9']), + ('b64 copy of vcc', ['cmp_vcc', 'copy_vcc', 'read_s9']), + ('copy of a copy', ['cmp_pair', 'cmp_vcc', 'xor_pair', 'copy_pair', 'copy_copy', 'read_s11']), + ('scalar use of a copy', ['cmp_pair', 'cmp_vcc', 'xor_pair', 'copy_pair', 'add_s9']), + ] + for label, steps in cases: + try: + translate('A', code=splice_words(*[w[s] for s in steps])) + except G.Unsupported as reason: + assert 'as numeric data' in str(reason), (label, str(reason)) + else: + raise AssertionError("%s accepted, expected a refusal naming as numeric data" % label) + # A plain write ends the tag: the copy is overwritten with a constant before the read. + assert 'v5 = ' in translate('A', code=splice_words(*[w[s] for s in ( + 'cmp_pair', 'cmp_vcc', 'xor_pair', 'copy_pair', 'clear_s9', 'read_s9')])).hlsl_cs() + + +def splice_words(*chunks, at=STORE_A): + return WORDS_A[:at] + b''.join(chunks) + WORDS_A[at:] + + +def check_scc_modelled(): + # s_add / s_sub / s_min / s_max write SCC (carry, borrow, signed overflow, S0 chosen). The lowering used to leave the + # emitted SCC as it was, so a later s_cbranch_scc or s_cselect read a stale value. Each form now emits its SCC from + # its sources, ahead of the branch. + words = {'s_add_u32 s23, s7, -1': '07c11780', 's_sub_u32 s23, s7, 1': '07819780', + 's_add_i32 s23, s7, 0x7fffffff': '07ff1781ffffff7f', 's_sub_i32 s23, s7, 1': '07819781', + 's_min_u32 s23, s7, 4': '07849783', 's_max_i32 s23, s7, 4': '07841784', 's_wqm_b32 s23, s7': '070997be', + 's_cselect_b32 s24, 1, 0': '81801885', 's_cbranch_scc1 1': '010085bf'} + SPLICE.update(words) + for line, word in words.items(): # the decoder prints each hand-assembled word as its line (literals in hex) + (_, _, name, text), = G.decode(bytes.fromhex(word)) + # the decoder prints a branch with its target label and a -1 literal in hex + assert text == line or text == line.replace('-1', '0xffffffff') or ( + name.startswith('s_cbranch') and text.startswith(name + ' ')), (line, text) + for op, scc in (('s_add_u32 s23, s7, -1', 'scc = (s7 + 0xffffffffu) < (s7);'), + ('s_sub_u32 s23, s7, 1', 'scc = (s7) < (0x00000001u);'), + ('s_add_i32 s23, s7, 0x7fffffff', + 'scc = (((((s7) ^ (s7 + 0x7fffffffu)) & ((0x7fffffffu) ^ (s7 + 0x7fffffffu))) >> 31) != 0);'), + ('s_sub_i32 s23, s7, 1', 'scc = (((((s7) ^ (0x00000001u)) & ((s7) ^ (s7 - 0x00000001u))) >> 31) != 0);'), + ('s_min_u32 s23, s7, 4', 'scc = ((s7) <= (0x00000004u));'), + ('s_max_i32 s23, s7, 4', 'scc = (int(s7) >= int(0x00000004u));')): + text = translate('A', code=splice(op, 's_cbranch_scc1 1', 'v_mov_b32 v3, 0')).hlsl_cs() + assert scc in text and text.index(scc) < text.index('pc = (scc)'), (op, text) + # A reader whose last SCC writer the lowering still does not model is refused by name (s_wqm is not lowered). + refused('scc from an SCC write that is not modelled in s_cbranch_scc1', lambda: translate( + 'A', code=splice('s_wqm_b32 s23, s7', 's_cbranch_scc1 1', 'v_mov_b32 v3, 0'))) + refused('scc from an SCC write that is not modelled in s_cselect_b32', lambda: translate( + 'A', code=splice('s_wqm_b32 s23, s7', 's_cselect_b32 s24, 1, 0'))) + translate('A', code=splice('s_wqm_b32 s23, s7')).hlsl_cs() # nothing reads that SCC + + def check_descriptor_scc(): # Case A loads the input descriptor into s[12:15] and stores through s[16:19]. - # Put the condition into the stored value, or let the branch skip the move. + # Read s20's lane bit into the stored value. The SCC branches skip both dwords of the lane select. compare = 's_cmp_lt_u32 s7, 4' mask = 's_and_b32 s13, s13, 0xc000ffff' select = 's_cselect_b32 s20, 1, 0' - move = 'v_mov_b32 v5, s20' def pipeline(*lines): return translate('A', code=splice(*lines)) @@ -707,20 +1629,20 @@ def rejected(*lines): refused('scc from descriptor data', lambda: pipeline(*lines)) for reader in (select, 's_cselect_b64 s[20:21], 1, 0', 's_cmov_b32 s20, 1', 's_cmov_b64 s[20:21], s[4:5]', - 's_cmovk_i32 s20, 3', 's_cbranch_scc0 1', 's_cbranch_scc1 1'): - rejected(compare, mask, reader, move) - assert 'uav 0 table 1 16' in pipeline(mask, compare, reader, move).manifest() - rejected(compare, 's_add_u32 s13, s13, 1', select, move) - assert 's20 = scc ?' in pipeline(compare, 's_mov_b32 s13, s13', select, move).hlsl_cs() - assert 's20 = scc ?' in pipeline(mask, 's_and_b32 s22, s7, 1', select, move).hlsl_cs() - assert 's20 = scc ?' in pipeline(mask, 's_and_saveexec_b32 s0, vcc_lo', select, move).hlsl_cs() + 's_cmovk_i32 s20, 3', 's_cbranch_scc0 2', 's_cbranch_scc1 2'): + rejected(compare, mask, reader, SCC_LANE_SELECT) + assert 'uav 0 table 1 16' in pipeline(mask, compare, reader, SCC_LANE_SELECT).manifest() + rejected(compare, 's_add_u32 s13, s13, 1', select, SCC_LANE_SELECT) + assert 's20 = scc ?' in pipeline(compare, 's_mov_b32 s13, s13', select, SCC_LANE_SELECT).hlsl_cs() + assert 's20 = scc ?' in pipeline(mask, 's_and_b32 s22, s7, 1', select, SCC_LANE_SELECT).hlsl_cs() + assert 's20 = scc ?' in pipeline(mask, 's_and_saveexec_b32 s0, vcc_lo', select, SCC_LANE_SELECT).hlsl_cs() # A conditional edge can bypass the fresh comparison. A back edge can carry # the descriptor-derived flag to a read that comes first in program order. - rejected(mask, 's_cbranch_vccz 1', compare, select, move) + rejected(mask, 's_cbranch_vccz 1', compare, select, SCC_LANE_SELECT) rejected(compare, 'v_mov_b32 v3, 0', select, mask, 'v_add_nc_u32 v3, 1, v3', - 'v_cmp_gt_u32 vcc_lo, 2, v3', 's_cbranch_vccnz 65530', move) - assert 's20 = scc ?' in pipeline(compare, 's_branch 2', mask, select, move).hlsl_cs() + 'v_cmp_gt_u32 vcc_lo, 2, v3', 's_cbranch_vccnz 65530', SCC_LANE_SELECT) + assert 's20 = scc ?' in pipeline(compare, 's_branch 2', mask, select, SCC_LANE_SELECT).hlsl_cs() def check_lds(): @@ -740,7 +1662,7 @@ def check_lds(): ('82000834', '00cb087e82000834', 'unchanged entry local X'), # v_swap also writes its second operand ('82000834', '82020834', 'one bounded dword'), # use Y instead of X (store, '040134d804050000', 'one bounded dword'), # last lane exceeds the 512-byte allocation - (store, store + store, 'one bounded dword'), # overlapping fill + (store, store + store, 'disjoint'), # overlapping fill (wait + barrier, nop + barrier, 'completed fill'), (barrier, '01008abf', 'one barrier'), # nonzero reserved immediate (barrier, nop, 'after the fill barrier'), @@ -767,6 +1689,26 @@ def check_lds(): assert 'lds[(v4 + 256u) >> 2] = v5;' in translate('F', code=at_end).hlsl_cs() assert 'groupshared uint lds[8192];' in translate('F', rsrc2=base | 64 << 15).hlsl_cs() + second = '400134d804040000' + second_read = 'd401d8d808000007' + hlsl = translate('F-two-fills').hlsl_cs() + assert hlsl.index('lds[(v4 + 320u) >> 2] = v4;') < hlsl.index(sync) < hlsl.index('v7 = lds[') + reversed_fills = patch(WORDS_F2, store + second, second + store) + assert 'v7 = lds[(v8 + 468u) >> 2];' in translate('F-two-fills', code=reversed_fills).hlsl_cs() + for old, new, reason in ( + (second, '', 'initialized span'), # omit the second fill + (second, '0c0134d804040000', 'disjoint'), # final word of the first bank + (second_read, '1001d8d808000007', 'initialized span'), # first word in the gap + (second, '040334d804040000', 'bounded'), # last lane exceeds allocation + (second, '400134d805040000', 'address'), # unproven address VGPR + (second, '400136d804040000', 'optional byte offset'), # GDS + (second, '400135d804040000', 'reserved bit'), # hidden encoding bit + (second, '400134d804040100', 'unused operand field'), # unused DATA1 + (second, second + '800234d804040000', 'two'), # third fill + (second, nop + second, 'bounded'), # address proof no longer adjacent + ): + refused(reason, lambda: translate('F-two-fills', code=patch(WORDS_F2, old, new))) + pair = '0524dcd806000006' # The first result overwrites v6. Both loads must use the address saved before that write. body = translate('G').hlsl_cs() @@ -812,6 +1754,10 @@ def check_formatted_loads(): assert hlsl.count(' = ((ud3 >> ') == width # Word 3 is overwritten in an otherwise intact native descriptor. refused('words were rewritten', lambda: translate('L-uint', code=prefix + bytes.fromhex('80038fbe') + LOAD_L + end)) + # An instruction writes a derived descriptor word to a separate SGPR (s21), leaving operand s[12:15] intact. + # The indexed formatted load is refused because the descriptor is modified. + refused('indexed load through a modified descriptor', + lambda: translate('L-uint', code=prefix + bytes.fromhex('0dff1587ffff00c0') + LOAD_L + end)) # At a branch target, there is no local descriptor load to prove. refused('local table load', lambda: translate('L-uint', code=prefix + bytes.fromhex('000082bf') + LOAD_L + end)) local_load = bytes.fromhex('000082bf') + prefix + LOAD_L + end @@ -870,7 +1816,104 @@ def proof(code): assert switch in translate('L-uint', code=skip_one + bytes.fromhex('000080bf') + copy + high + target + load + tail).hlsl_cs() +def check_hand_words(): + """Hand-assembled words decode, with the repository disassembler, to the source line they stand for.""" + def decoded(words, at=0): + n, _, text, _ = G.D.decode_instruction(words, at) + return n, text.replace('_e32 ', ' ') + for line in ('buffer_store_dword v5, off, s[16:19], 0', 'buffer_store_dword v5, off, s[16:19], s20 offset:8', + 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0', 'v_lshrrev_b64 v[5:6], 4, s[20:21]', + 'v_lshrrev_b64 v[5:6], 4, v[3:4]'): + assert decoded(bytes.fromhex(SPLICE[line]))[1] == line, (line, decoded(bytes.fromhex(SPLICE[line]))) + # A branch decodes to its target: 4 bytes past the branch plus 4 bytes per dword of the simm16. + assert decoded(bytes.fromhex(SPLICE['s_cbranch_execz 4']))[1] == 's_cbranch_execz label_0x14' + for name in ('O-dword', 'O-shift'): + source, words = CASES[name][:2] + at, texts = 0, [] + while at < len(words): + n, text = decoded(words, at) + texts.append(text) + at += n + assert texts == source.splitlines(), (name, texts) + + +def check_off_stores(): + """The `off` store (MUBUF offen = idxen = 0): every lane writes the same address, accepted with uniform data.""" + def lines(*code): + return translate('A', code=replace_store(*code)).hlsl_cs().splitlines() + hlsl = lines('v_mov_b32 v5, s20', 'buffer_store_dword v5, off, s[16:19], 0') + at = hlsl.index(' a = (0) & 0xfffffffcu;') + assert hlsl[at + 1] == ' u0.Store(a, v5);', hlsl[at:at + 2] + hlsl = lines('v_mov_b32 v5, s20', 'buffer_store_dword v5, off, s[16:19], s20 offset:8') + at = hlsl.index(' a = (s20 + 8) & 0xfffffffcu;') + assert hlsl[at + 1] == ' u0.Store(a, v5);', hlsl[at:at + 2] + # A 64-bit shift of scalar sources is uniform in both halves. + hlsl = lines('v_lshrrev_b64 v[5:6], 4, s[20:21]', 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0') + at = hlsl.index(' a = (0) & 0xfffffffcu;') + assert hlsl[at + 1] == ' u0.Store2(a, uint2(v5, v6));', hlsl[at:at + 2] + # Past the entry block (inside a guard that skips per lane) the recomputable expression carries the proof. + guard = ['v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo'] + hlsl = lines(*guard, 's_cbranch_execz 3', 'v_mov_b32 v5, s20', 'buffer_store_dword v5, off, s[16:19], 0', + 's_or_b32 exec_lo, exec_lo, s0') + assert 'if (exec & 1) u0.Store(a, v5);' in [line.strip() for line in hlsl], hlsl + hlsl = lines(*guard, 's_cbranch_execz 4', 'v_lshrrev_b64 v[5:6], 4, s[20:21]', + 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0', 's_or_b32 exec_lo, exec_lo, s0') + assert 'if (exec & 1) u0.Store2(a, uint2(v5, v6));' in [line.strip() for line in hlsl], hlsl + # The saveexec between the definition and the store ends the proof (conservative: these lanes are a subset). + refused('buffer store off with data not proven wave-uniform', lambda: lines( + 'v_mov_b32 v5, s20', *guard, 's_cbranch_execz 3', 's_waitcnt lgkmcnt(0)', + 'buffer_store_dword v5, off, s[16:19], 0', 's_or_b32 exec_lo, exec_lo, s0')) + # Negative controls: per-lane data (a shift of the thread index; the per-lane load), and uniform data written + # before an EXEC change, where the entry-block proof no longer knows which lanes store. + for code in (('v_lshrrev_b64 v[5:6], 4, v[3:4]', 'buffer_store_dwordx2 v[5:6], off, s[16:19], 0'), + ('buffer_store_dword v5, off, s[16:19], 0',), + ('v_mov_b32 v5, s20', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_mov_b32 exec_lo, vcc_lo', + 'buffer_store_dword v5, off, s[16:19], 0')): + refused('buffer store off with data not proven wave-uniform', lambda code=code: lines(*code)) + + +def check_execz_mask_exact(): + """Exhaustive 4-lane wave: the one-lane model of an s_cbranch_execz block (a lane with exec clear skips it) leaves a + skipped lane's mask bit as M held it; the wave runs the block whenever any lane is active. Which block writes keep + that bit: preserving ones always, a compare / exec-masked move only if M was 0, an s_orn2 with exec only if M was 1s.""" + full = 15 + writes = {'cmp': lambda m, e, c: c & e, 'mov_exec': lambda m, e, c: e, 'andn2': lambda m, e, c: m & ~e & full, + 'blend': lambda m, e, c: (m & ~e & full) | (c & e), 'or_cmp': lambda m, e, c: m | (c & e), + 'orn2': lambda m, e, c: (c | ~e) & full} + for name, write in writes.items(): + bad = set() + for m, e, c in itertools.product(range(16), repeat=3): + wave = write(m, e, c) if e else m + if any(((wave ^ m) >> lane) & 1 for lane in range(4) if not (e >> lane) & 1): + bad.add(m) + want = {'cmp': set(range(1, 16)), 'mov_exec': set(range(1, 16)), 'orn2': set(range(15))}.get(name, set()) + assert bad == want, (name, sorted(bad)) + + def check_controls(): + for name in ('masked-tid', 'extracted-tid'): + translate(name).hlsl_cs() + # Shift by one to retain masked bit 1, or enable extracted bit 3 in a larger group. + masked = patch(CASES['masked-tid'][1], '8204022c', '8104022c') + refused('requires a proven uniform source', lambda: translate('masked-tid', code=masked)) + refused('requires a proven uniform source', lambda: translate('extracted-tid', group=(16, 1, 1))) + carry = translate('address-carry').hlsl_cs() + assert 's21 = (scc ? 1u : 0u);' in carry + lo, hi, end = (bytes.fromhex(x) for x in ('04051480', '80fd1580', '000081bf')) + for near_miss in ( + bytes.fromhex('010084bf') + lo + hi, # branch into the high add + bytes.fromhex('06811480') + hi): # elided descriptor arithmetic + refused('src_scc', lambda: translate('address-carry', code=near_miss + end)) + # Every SCC writer is modelled, so src_scc after a plain add reads the carry the add computed, whatever sits between + # (an intervening s_sub_u32 writes the borrow) or follows: the add's own carry is emitted ahead of its use. + for name, ok in (('s_sub_u32 between', lo + bytes.fromhex('81809e80') + hi), + ('non-adjacent', lo + bytes.fromhex('000080bf') + hi), + ('high addend is one', lo + bytes.fromhex('81fd1580')), + ('high register is not the next SGPR', lo + bytes.fromhex('80fd1680'))): + text = translate('address-carry', code=ok + end).hlsl_cs() + want = '(0x00000001u) < (0x00000000u)' if name.startswith('s_sub') else '(ud0 + ud1) < (ud0)' + assert want in text and text.index(want) < text.index('(scc ? 1u : 0u)'), (name, text) + refused('lane mask', lambda: translate('address-carry', code=bytes.fromhex('7e811480') + hi + end)) ff1 = bytes.fromhex('7e1385be') end = bytes.fromhex('000081bf') # A write to EXEC can disable lane zero; a backward branch can re-enter @@ -878,12 +1921,28 @@ def check_controls(): for code in (bytes.fromhex('8003febe') + ff1 + end, ff1 + bytes.fromhex('feff82bf') + end): refused('compute entry EXEC mask', lambda: translate('A', code=code)) - refused('requires compute exec_lo', lambda: translate('A', code=bytes.fromhex('6a1385be') + end)) + # vcc_lo is a lane mask; general-scalar ff1 (#2022 Item F) still refuses it. + refused('lane mask', lambda: translate('A', code=bytes.fromhex('6a1385be') + end)) assert 's5 = 0u;' in translate('A-ff1').hlsl_cs() assert expected('A-ff1') != expected('A') check_lds() check_descriptor_scc() + check_scc_modelled() check_mbcnt() + check_execz_exit_run() + check_execz_loop_break() + check_execz_mask_subset() + check_lane_mask_data() + check_lane_mask_high_word() + check_lane_mask_compare_pair() + check_lane_mask_copy_of_data_clears_tag() + check_lane_mask_pair_copy_of_data_stays_refused() + check_lane_mask_wqm_keeps_tag() + check_lane_mask_single_thread_group() + check_lane_mask_high_word_copy_and_overwrite() + check_lane_mask_derived_word() + check_lane_mask_scalar_data() + check_lane_mask_tag_propagation() check_formatted_loads() a = translate('A') # This buffer-only compute program has no typed UAV declaration or image manifest entry. @@ -913,7 +1972,7 @@ def check_controls(): assert stage.entry == entry + ['v0 = tid.x;'], (hex(rsrc2), stage.entry) # Entry refusals. end = bytes.fromhex('000081bf') - refused('TG_SIZE_EN', lambda: G.ComputePipeline(end, root_blob(), USER7 | TG_SIZE_EN, (1, 1, 1))) + refused('TG_SIZE_EN', lambda: G.ComputePipeline(end, root_blob(), USER7 | TG_SIZE_EN, (8, 4, 2))) refused('thread-ID component count', lambda: G.ComputePipeline(end, root_blob(), USER7 | (3 << 11), (1, 1, 1))) refused('gives 6 user SGPRs', lambda: G.ComputePipeline(end, root_blob(), 6 << 1, (1, 1, 1))) refused('thread group', lambda: G.ComputePipeline(end, root_blob(), USER7, (1024, 2, 1))) @@ -922,7 +1981,7 @@ def check_controls(): refused('numeric use of s7', lambda: translate('A', rsrc2=(8 << 1) | tidig(3)).hlsl_cs()) # Store forms outside this slice (the store is the dword at +0x60 of WORDS_A: offen, soffset 0x80, s[16:19]). store = '001070e004050480' - for word, fragment in (('000070e004050480', 'offen address form'), # off: no offen + for word, fragment in (('000070e004050480', 'not proven wave-uniform'), # off: one address, per-lane data ('002070e004050480', 'modifier idxen'), # idxen, no offen ('005070e004050480', 'modifier glc'), # glc offen ('001070e004050380', 'used for a load and a store')): # store through the read descriptor @@ -935,6 +1994,12 @@ def check_controls(): assert str(reason) == text, str(reason) else: raise AssertionError('graphics store accepted') + check_hand_words() + check_off_stores() + check_execz_mask_exact() + for name in ('O-dword', 'O-shift'): + hlsl = translate(name).hlsl_cs().splitlines() + assert any('u0.Store' in line for line in hlsl), (name, hlsl) # A register soffset is added to the address. hlsl = translate('A', code=patch(WORDS_A, store, '001070e004050414')).hlsl_cs() assert ' a = (v4 + s20 + 0) & 0xfffffffcu;' in hlsl.splitlines(), hlsl @@ -982,6 +2047,13 @@ def check_controls(): # Captured programs clamp the extracted stride to at least 1 before scaling NUM_RECORDS. clamped = (STRIDE_EXTRACT, 's_max_u32 s21, s21, 1', *RAW_CONVERSION[1:]) assert translate('A', code=splice(*clamped)).hlsl_cs() == raw.hlsl_cs() + # After a lane mask in s21 the clamped conversion still matches case I-raw apart from the compare itself; the + # dispatch of case I-raw-mask stores through it. Control: a clamp that reads the mask itself stays refused. + masked = translate('I-raw-mask').hlsl_cs().splitlines() + assert [line for line in masked if line not in raw.hlsl_cs().splitlines()] == [ + ' s21 = ((0x00000003u > v0) ? 1u : 0u);'], masked + refused('s_max_u32 reads lane mask s21 as numeric data', lambda: translate( + 'A', code=splice(MASK_S21, 's_max_u32 s21, s21, 1', *RAW_CONVERSION[1:])).hlsl_cs()) refused('buffer store through a modified descriptor', lambda: translate( 'A', code=splice(STRIDE_EXTRACT, 's_max_u32 s21, s21, 2', *RAW_CONVERSION[1:])).hlsl_cs()) reload = ('s_load_dwordx8 s[24:31], s[10:11], 0x0', 's_waitcnt lgkmcnt(0)') @@ -1164,6 +2236,7 @@ def block(*lines): assert translate('M').hlsl_cs().endswith('''\ if (pc == 1) { s22 = s7 * ud1; + scc = (s22 + ud0) < (s22); s22 = s22 + ud0; if (exec & 1) v5 = s22 ^ v3; vcc = (exec & ((0x00000003u > v0) ? 1u : 0u)); @@ -1197,6 +2270,123 @@ def block(*lines): } } ''') + # A definition live where the block joins whose reads are all absorbed by exec. The block's exec writes are + # proven, so a lane that skipped it has its exec bit clear at the join in the wave as in the model; while exec is + # unchanged since the join, W & exec and exec & W give that lane 0 and ~(W & exec) and W | ~exec give it 1, + # whatever W holds. Accepted at the join (case N runs the first on the GPU), and when the read overwrites W. + SPLICE.update({ + 's_and_b32 s23, vcc_lo, exec_lo': '6a7e1787', 's_and_b32 s23, exec_lo, vcc_lo': '7e6a1787', + 's_nand_b32 s23, vcc_lo, exec_lo': '6a7e178c', 's_orn2_b32 s23, vcc_lo, exec_lo': '6a7e178b', + 's_and_b32 vcc_lo, vcc_lo, exec_lo': '6a7e6a87', 's_orn2_b32 s23, exec_lo, vcc_lo': '7e6a178b', + 's_mov_b32 s23, vcc_lo': '6a0397be', 's_and_b32 s23, vcc_lo, exec_hi': '6a7f1787', 's_and_b32 s23, vcc_hi, exec_lo': '6b7e1787', + 's_cbranch_scc1 65533': 'fdff85bf'}) + compare = ['s_cbranch_execz 1', 'v_cmp_gt_u32 vcc_lo, 3, v0'] + for read in ('s_and_b32 s23, vcc_lo, exec_lo', 's_and_b32 s23, exec_lo, vcc_lo', 's_orn2_b32 s23, vcc_lo, exec_lo', + 's_and_b32 vcc_lo, vcc_lo, exec_lo'): + translate('A', code=splice(*enter, *compare, read, *leave, 's_cbranch_vccz 1', 'v_mov_b32 v5, s20') + if read.startswith('s_and_b32 vcc') else splice(*enter, *compare, read, *leave)).hlsl_cs() + assert translate('NM').hlsl_cs().endswith('''\ + if (pc == 1) { + vcc = (exec & ((0x00000003u > v0) ? 1u : 0u)); + pc = 2; + } + if (pc == 2) { + s23 = (vcc & exec) & 1; + scc = s23 != 0; + exec = (exec | s0) & 1; + scc = exec != 0; + if (exec & 1) v5 = ud0 ^ v3; + exec = (s23) & 1; + a = (v4 + 0) & 0xfffffffcu; + if (exec & 1) u0.Store(a, v5); + exec = (s21) & 1; + pc = 0xffffu; + } +} +''') + # Refused: a read once exec has been restored, a copy, exec | ~vcc (vcc decides), exec_hi in the low half, the + # vcc branch after an absorbed read, and an absorbed read at the join that a loop re-enters after the restore + # (exec is no longer the join's there). The reason names the first read that is not proven. + live = 'v_cmp_gt_u32_e32 inside a block s_cbranch_execz skips per lane: definition of vcc, live where the block joins' + for before, after, name in (([], ['s_and_b32 s23, vcc_lo, exec_lo'], 's_and_b32'), + (['s_mov_b32 s23, vcc_lo'], [], 's_mov_b32'), + (['s_orn2_b32 s23, exec_lo, vcc_lo'], [], 's_orn2_b32'), + (['s_and_b32 s23, vcc_lo, exec_hi'], [], 's_and_b32'), + (['s_and_b32 s23, vcc_lo, exec_lo'], ['s_cbranch_vccz 1', 'v_mov_b32 v5, s20'], + 's_cbranch_vccz'), + (['s_and_b32 s23, vcc_lo, exec_lo'], ['s_cbranch_scc1 65533'], 's_and_b32')): + refused('%s: read by %s after the join' % (live, name), lambda before=before, after=after: translate( + 'A', code=splice(*enter, *compare, *before, *leave, *after)).hlsl_cs()) + # Wave64: the compare writes vcc_hi too (its decoded text names vcc_lo only). A 32-bit read of vcc_hi after the join + # is not lane-wise against exec_lo, so it is refused where the same read of vcc_lo above is accepted. + refused('v_cmp_gt_u32_e32 inside a block s_cbranch_execz skips per lane: definition of vcc_hi, live where the block ' + 'joins: read by s_and_b32 after the join', + lambda: translate('A', code=splice(*enter, *compare, *leave, 's_and_b32 s23, vcc_hi, exec_lo')).hlsl_cs()) + assert G.exec_absorbs('s_and_b32', 's_and_b32 s2, vcc_hi, exec_lo', 'vcc_hi') is False + # The rule on its own: which reads exec absorbs for a word. + for line, word, absorbed in (('s_and_b32 s2, s3, exec_lo', 's3', True), ('s_and_b64 s[2:3], exec, s[4:5]', 's5', True), + ('s_nand_b32 s2, exec_lo, s3', 's3', True), ('s_orn2_b32 s2, s3, exec_lo', 's3', True), + ('s_orn2_b32 s2, exec_lo, s3', 's3', False), ('s_or_b32 s2, s3, exec_lo', 's3', False), + ('s_and_b32 s2, s3, s3', 's3', False), ('s_and_b64 s[2:3], s[4:5], exec', 's4', True), + ('s_and_b64 s[2:3], s[4:5], s[4:5]', 's4', False), ('s_and_b32 s2, s3, exec_hi', 's3', False), + ('s_and_b64 s[2:3], s[4:5], exec_lo', 's4', False)): + assert G.exec_absorbs(line.split()[0], line, word) == absorbed, line + # A mask the block only narrows by lanes whose exec bit is clear for a skipped lane: `s_andn2 R, R, X` with X + # clear for that lane (the exec-write proof's fact at that instruction) keeps its bit of R, so at the join it is + # the model's. Reads that take bit n of the result from bit n of R, for the same half, and write it to that exec + # word or back to R are then the model's too. Accepted on the restore after the block (case O runs it on the GPU). + SPLICE.update({'s_andn2_b32 s0, s0, exec_lo': '007e008a', 's_andn2_b32 s0, s0, s21': '0015008a', + 's_mov_b32 s1, s0': '000381be', 's_add_u32 s23, s0, 1': '00811780'}) + save = ['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo'] + translate('A', code=splice(*save, 's_cbranch_execz 1', 's_andn2_b32 s0, s0, exec_lo', 's_mov_b32 exec_lo, s0', + *leave)).hlsl_cs() + assert translate('O').hlsl_cs().endswith('''\ + if (pc == 1) { + vcc = (exec & ((0x00000003u > v0) ? 1u : 0u)); + exec = (exec & vcc) & 1; + scc = exec != 0; + s0 = (s0 & ~exec) & 1; + scc = s0 != 0; + pc = 2; + } + if (pc == 2) { + exec = (s0) & 1; + if (exec & 1) v5 = ud0 ^ v3; + a = (v4 + 0) & 0xfffffffcu; + if (exec & 1) u0.Store(a, v5); + exec = (s21) & 1; + pc = 0xffffu; + } +} +''') + # Refused: X not clear (the mask saved before the block), another write of s0 in the block, alone or after the + # narrowing, a copy and a data read after the join, and a block that a branch from outside enters (the fact is + # not proven there). + kept = ' inside a block s_cbranch_execz skips per lane: definition of s0, live where the block joins: read by %s ' \ + 'after the join' + for prefix, body, join, inner, name in ( + ([], ['s_andn2_b32 s0, s0, s21'], [], 's_andn2_b32', 's_mov_b32'), + ([], ['s_mov_b32 s0, 4'], [], 's_mov_b32', 's_mov_b32'), + ([], ['s_andn2_b32 s0, s0, exec_lo', 's_mov_b32 s0, 4'], [], 's_andn2_b32', 's_mov_b32'), + ([], ['s_andn2_b32 s0, s0, exec_lo'], ['s_mov_b32 s1, s0'], 's_andn2_b32', 's_mov_b32'), + ([], ['s_andn2_b32 s0, s0, exec_lo'], ['s_add_u32 s23, s0, 1'], 's_andn2_b32', 's_add_u32'), + (['s_cbranch_scc1 1'], ['s_andn2_b32 s0, s0, exec_lo'], [], 's_andn2_b32', 's_mov_b32')): + refused(inner + kept % name, lambda prefix=prefix, body=body, join=join: translate('A', code=splice( + *save, *prefix, 's_cbranch_execz %d' % len(body), *body, *join, 's_mov_b32 exec_lo, s0', *leave)).hlsl_cs()) + # The rule's steps on their own: the halves a write keeps, and the reads that keep the lane's bit. + for line, word, clear, halves in (('s_andn2_b32 s0, s0, exec_lo', 's0', start, {0}), + ('s_andn2_b64 s[0:1], s[0:1], exec', 's1', start, {1}), + ('s_andn2_b64 s[0:1], s[0:1], exec', 's1', {('exec', 0)}, set()), + ('s_andn2_b32 s0, s0, exec_hi', 's0', start, {1}), + ('s_andn2_b32 s0, s1, exec_lo', 's0', start, set()), + ('s_or_b32 s0, s0, exec_lo', 's0', start, set())): + assert G.kept_halves(line.split()[0], line, word, clear) == halves, line + for line, word, halves, ok in (('s_mov_b32 exec_lo, s0', 's0', {0}, True), ('s_mov_b32 exec_lo, s0', 's0', {1}, False), + ('s_mov_b64 exec, s[0:1]', 's1', {1}, True), ('s_mov_b64 exec, s[0:1]', 's1', {0}, False), + ('s_andn2_b32 s0, s0, exec_lo', 's0', {0}, True), ('s_mov_b32 s1, s0', 's0', {0}, False), + ('s_and_b32 exec_lo, s0, exec_hi', 's0', {0}, False), + ('s_mov_b32 exec_hi, s0', 's0', {1}, False)): + assert G.lane_read(line.split()[0], line, word, halves) == ok, line # The compiler's i1-phi lane mask: M is zeroed before the branch, set from exec in the block, and read per lane # after the join. For a lane the model skips, the wave's M bit is 0 either way (exec only narrows in the block), # which is the model's M. Accepted for vcc_lo and for an sN, with a move or an s_and in either operand order. @@ -1214,16 +2404,22 @@ def phi(zero, write, read, between=(), inside=()): return splice(*enter, *zero, *between, 's_cbranch_execz %d' % (len(write) + len(inside)), *write, *inside, *leave, *read) phi_text = lambda code: translate('A', code=code).hlsl_cs() + SPLICE.update({'s_and_b32 s20, exec_lo, vcc_lo': '7e6a1487'}) cnd_vcc, cnd_s = ['v_cndmask_b32 v5, v5, v6, vcc_lo'], ['v_cndmask_b32 v5, v5, v6, s20'] for zero, write, read in ((['s_mov_b32 vcc_lo, 0'], ['s_mov_b32 vcc_lo, exec_lo'], cnd_vcc), (['s_mov_b32 s20, 0'], ['s_mov_b32 s20, exec_lo'], cnd_s), - (['s_mov_b32 vcc_lo, 0'], ['s_and_b32 vcc_lo, s7, exec_lo'], cnd_vcc), - (['s_mov_b32 s20, 0'], ['s_and_b32 s20, s7, exec_lo'], cnd_s), - (['s_mov_b32 s20, 0'], ['s_and_b32 s20, exec_lo, s7'], cnd_s)): + (['s_mov_b32 vcc_lo, 0'], ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_b32 vcc_lo, vcc_lo, exec_lo'], cnd_vcc), + (['s_mov_b32 s20, 0'], ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_b32 s20, vcc_lo, exec_lo'], cnd_s), + (['s_mov_b32 s20, 0'], ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_b32 s20, exec_lo, vcc_lo'], cnd_s)): text = phi_text(phi(zero, write, read)) # the lane select reads the mask's lane bit, which the block set from exec (the model runs the block for # every lane it models, and skips it only where exec is clear, leaving the zeroing) assert '& 1) ? ' in text and ('vcc = (exec) & 1;' in text or 's20 = ' in text), text + # an s_and of exec with data (a group id) is not a lane mask: its lane bit is at bit `lane` in the wave + for write in (['s_and_b32 vcc_lo, s7, exec_lo'], ['s_and_b32 s20, s7, exec_lo']): + refused('definition of ' + ('vcc' if 'vcc_lo, s7' in write[0] else 's20') + ', live where the block joins', + lambda write=write: phi_text(phi(['s_mov_b32 %s, 0' % ('vcc_lo' if 'vcc_lo, s7' in write[0] else 's20')], + write, cnd_vcc if 'vcc_lo, s7' in write[0] else cnd_s))) # s_and with exec reads the lane bit only (the result is a lane mask): accepted phi_text(phi(['s_mov_b32 vcc_lo, 0'], ['s_mov_b32 vcc_lo, exec_lo'], ['s_and_b32 s20, vcc_lo, exec_lo'] + cnd_vcc)) # so does s_and_saveexec with the mask as its source (exec &= the lane bit); with the mask as its destination @@ -1262,6 +2458,58 @@ def phi(zero, write, read, between=(), inside=()): ['s_cmp_eq_u32 s20, 0'] + cnd_s))) refused(live('s20'), lambda: phi_text(phi(['s_mov_b32 s20, 0'], ['s_mov_b32 s20, exec_lo'], ['s_mov_b32 s7, s20'] + cnd_s))) + # A block that leaves the mask bit of a lane it skips unchanged is exact whatever M held before the branch: + # `s_andn2 M, M, exec_lo` and `s_or M, M, T` with T exec-masked in the block (the compiler's i1 phi with a + # per-lane old value). A compare into M, or an s_orn2 with exec, changes a skipped lane's bit: accepted only + # when M was zeroed (compare) or set to all ones (orn2) before the branch. + SPLICE.update({'s_andn2_b32 s20, s20, exec_lo': '147e148a', 's_andn2_b32 vcc_lo, vcc_lo, exec_lo': '6a7e6a8a', + 's_and_b32 s22, s7, exec_lo': '077e1687', 's_and_b32 s22, s7, s7': '07071687', + 's_or_b32 s20, s20, s22': '14161488', 's_or_b32 vcc_lo, vcc_lo, s22': '6a166a88', + 's_or_b32 s20, s20, s7': '14071488', 's_andn2_b32 s20, s7, exec_lo': '077e148a', + 's_orn2_b32 s20, s7, exec_lo': '077e148b', 'v_cmp_gt_u32 vcc_lo, 3, v0': '8300887d'}) + # T and M hold lane bits (bit 0 = the lane's bit, the model's encoding): T from a compare, M zeroed before the branch. + # Group-id data (s7) as T, or `s_mov_b32 M, 16` as M, has the wave's lane bit at bit `lane` and is refused. + cmp_t = ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_b32 s22, vcc_lo, exec_lo'] + SPLICE.update({'s_and_b32 s22, vcc_lo, exec_lo': '6a7e1687', 's_mov_b32 s20, 16': '9003 94be'.replace(' ', ''), + 's_orn2_b32 s20, vcc_lo, exec_lo': '6a7e148b'}) + blend = ['s_andn2_b32 s20, s20, exec_lo', *cmp_t, 's_or_b32 s20, s20, s22'] + z20, zv = ['s_mov_b32 s20, 0'], ['s_mov_b32 vcc_lo, 0'] + for zero, write, read in ((z20, blend, cnd_s), (z20, blend[:1], cnd_s), + (zv, ['s_andn2_b32 vcc_lo, vcc_lo, exec_lo', 's_and_b32 s22, vcc_lo, exec_lo', + 's_or_b32 vcc_lo, vcc_lo, s22'], cnd_vcc)): + phi_text(phi(zero, write, read)) + # ANDing a numeric word with EXEC does not turn it into this lane's projected bit. + refused(live('s20'), lambda: phi_text(phi(['s_and_b32 s20, s7, exec_lo'], blend[:1], cnd_s))) + phi_text(phi(['s_and_b32 s20, vcc_lo, exec_lo'], blend[:1], cnd_s)) + phi_text(phi(['s_mov_b32 vcc_lo, 0'], ['v_cmp_gt_u32 vcc_lo, 3, v0'], cnd_vcc)) # compare into a zeroed M + phi_text(phi(['s_mov_b32 s20, -1'], ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_orn2_b32 s20, vcc_lo, exec_lo'], cnd_s)) # orn2 + # controls: the same writes without their set-up, an unmasked term, M not the first source, mixed classes, + # M or an operand that is not a lane mask, and a whole-mask read after a preserving block + refused(live('vcc'), lambda: phi_text(phi([], ['v_cmp_gt_u32 vcc_lo, 3, v0'], cnd_vcc))) + refused(live('vcc'), lambda: phi_text(phi(['s_mov_b32 vcc_lo, -1'], ['v_cmp_gt_u32 vcc_lo, 3, v0'], cnd_vcc))) + for zero in ([], z20): + refused(live('s20'), lambda zero=zero: phi_text(phi(zero, ['s_orn2_b32 s20, s7, exec_lo'], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(['s_mov_b32 s20, -1'], ['s_orn2_b32 s20, s7, exec_lo'], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(['s_mov_b32 s20, -1'], ['s_mov_b32 s20, exec_lo'], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(z20, ['s_mov_b32 s20, exec_lo', 's_orn2_b32 s20, s7, exec_lo'], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(z20, [blend[0], *cmp_t, 's_or_b32 s20, s20, s7'], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(z20, [blend[0], 's_and_b32 s22, s7, exec_lo', blend[3]], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(z20, [blend[0], 's_and_b32 s22, s7, s7', blend[3]], cnd_s))) + refused(live('s20'), lambda: phi_text(phi(z20, ['s_andn2_b32 s20, s7, exec_lo'], cnd_s))) + # A compare-derived operand does not make the classes mixable: a zero write (s_mov M, exec_lo) and a ones write + # (s_orn2 with exec) in one block are refused after either setting. `s_andn2 M, M, X` keeps M's skipped bits only for + # X == exec_lo; with a compare mask it clears bits of lanes the model skips. + SPLICE.update({'s_andn2_b32 s20, s20, vcc_lo': '146a148a'}) + mixed_cmp = ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_mov_b32 s20, exec_lo', 's_orn2_b32 s20, vcc_lo, exec_lo'] + for setting in (z20, ['s_mov_b32 s20, -1']): + refused(live('s20'), lambda setting=setting: phi_text(phi(setting, mixed_cmp, cnd_s))) + for setting in (z20, [], ['s_mov_b32 s20, -1']): + refused(live('s20'), lambda setting=setting: phi_text( + phi(setting, ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_andn2_b32 s20, s20, vcc_lo'], cnd_s))) + refused(live('s20'), lambda: phi_text(phi([], blend, cnd_s))) # M unknown before the block + refused(live('s20'), lambda: phi_text(phi(['s_mov_b32 s20, 16'], blend, cnd_s))) # M holds data, not lane bits + for read in (['s_cmp_eq_u32 s20, 0'] + cnd_s, ['s_mov_b32 s7, s20'] + cnd_s): + refused(live('s20'), lambda read=read: phi_text(phi(z20, blend, read))) # An implicit-LOD sample has no derivatives in a compute lane; the level-zero form translates. load = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40') sample = 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D' @@ -1272,6 +2520,9 @@ def phi(zero, write, read, between=(), inside=()): refused('compute d16 image load requires validated SRV formats', lambda: pipeline.cs.image(['v12', 'v[0:1]', 's[24:31]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x3', 'd16'], 'load')) + # A readfirstlane of a buffer load at a uniform address translates; at a per-lane address it is refused. + assert 's20 = v1;' in translate('N').hlsl_cs() + refused('v_readfirstlane_b32 requires a proven uniform source', lambda: translate('N', code=WORDS_N_VARYING).hlsl_cs()) print('compute entry, numthreads, masked bit counts, manifest, offen store forms and the store, descriptor, execz and sample ' 'refusals pass') @@ -1282,6 +2533,8 @@ def assemble(llvm_mc, source): def check_binary(llvm_mc): + assert assemble(llvm_mc, LOOP_BREAK_SOURCE) == LOOP_BREAK_WORDS + assert assemble(llvm_mc, EXIT_RUN_SOURCE) == EXIT_RUN_WORDS for name, (source, words, *_rest) in CASES.items(): built = assemble(llvm_mc, source) assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) @@ -1297,6 +2550,11 @@ def check_binary(llvm_mc): MBCNT_LANE = '(tid.x + 4u * (tid.y + 2u * tid.z))' MBCNT_COUNT = f'countbits(0x85241249u & ((1u << {MBCNT_LANE}) - 1u))' CONTROLS = { + 'join-load-zero': ('join-load', 's24 = ul24_7;', 's24 = 0u;'), + # s_min_u32 sets SCC when S0 is chosen, equal operands included: a strict compare differs at S0 == S1. + 's-min-strict': ('S', '(s20) <= (s21)', '(s20) < (s21)'), + # s_sub_u32 borrow: the first source is the smaller one. + 's-borrow-flipped': ('S', '(s20) < (s21);\n s24 = s20 - s21;', '(s21) < (s20);\n s24 = s20 - s21;'), 'swapped-axes': ('A', ' s7 = gid.x;\n s8 = gid.y;\n', ' s7 = gid.y;\n s8 = gid.x;\n'), 'dropped-store': ('A', ' u0.Store(a, v5);\n', ''), 'b-offset': ('B', ' a = (v4 + 8) & 0xfffffffcu;\n', ' a = (v4 + 0) & 0xfffffffcu;\n'), @@ -1308,14 +2566,27 @@ def check_binary(llvm_mc): 'd-hi': ('D', 'v9 = v8;', f'v9 = v8 + {MBCNT_COUNT};'), 'd-exec': ('D', 'if (exec & 1) v10 =', 'v10 ='), 'f-peer': ('F', '0x00000080u ^ v4', 'v4'), + 'f-second-fill': ('F-two-fills', 'lds[(v4 + 320u) >> 2] = v4;', 'lds[(v4 + 320u) >> 2] = 0u;'), 'f-broadcast': ('F', 'lds[(v8 + 164u) >> 2]', 'lds[(v8 + 160u) >> 2]'), 'j-scalar-dropped': ('J', ' s22 = s7 * ud1;\n', ''), 'h-inner-unpredicated': ('H', 'if (exec & 1) u0.Store(a, v5);', 'u0.Store(a, v5);'), 'm-else-unswitched': ('M', 'exec = (s0 & ~exec) & 1;', 'exec = (s0) & 1;'), # the then lanes run the else arm + 'n-unmasked': ('NM', 's23 = (vcc & exec) & 1;', 's23 = (vcc) & 1;'), # lanes 6 and 7 store with their stale vcc + 'o-mask-kept': ('O', 's0 = (s0 & ~exec) & 1;', 's0 = (s0) & 1;'), # lanes 0-2 keep their bit and store + 'o-subset-remask-dropped': ('O-loop-subset', 'exec = (s22) & 1;\n if (exec & 1) v5 = s24;', + 'exec = 1u;\n if (exec & 1) v5 = s24;'), # broken lanes overwrite v5 'k-block-entered': ('K', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipped waves run it + 'p-dropped-andn2': ('P', 's23 = (s23 & ~exec) & 1;', 's23 = (s23) & 1;'), # an entering lane keeps its old bit + 'p-dropped-or': ('P', 's23 = (s23 | s22) & 1;', 's23 = (s23) & 1;'), # an entering lane loses its compare bit + 'p-block-entered': ('P', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipping lanes run the block + 'q-block-entered': ('Q', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), + 'q-not-all-ones': ('Q', 's23 = 0xffffffffu;', 's23 = 0u;'), # M not set before the branch: skipped lanes read 0 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), 'g-overlap': ('G', 'v7 = lds[(a + 144u)', 'v7 = lds[(v6 + 144u)'), + 'mask-shift-dropped': ('masked-tid', 's24 = (ud0 >> 2u);', 's24 = ud0;'), + 'extract-shift-dropped': ('extracted-tid', 's24 = 0u;', 's24 = v2;'), + 'n-dropped-broadcast': ('N', 'v3 = s20 ^ v2;', 'v3 = v2;'), # lane i stores word[i], not word0 ^ word[i] 'l-byte-offset': ('L-uint', 'a = v0 * ud2 + v1 + 2;', 'a = v0 * ud2 + 2;'), 'l-swizzle': ('L-unorm', 'v6 = ((ud3 >> 3)', 'v6 = ((0u >> 3)'), 'l-integer-one': ('L-uint', 'c1 = w >> 16; c2 = 0u; c3 = 1u; one = 1u;', 'c1 = w >> 16; c2 = 0u; c3 = 1u;'), @@ -1323,10 +2594,14 @@ def check_binary(llvm_mc): # First bad word for controls with a pinned mismatch. CONTROL_MISMATCH = { + 'join-load-zero': 'word=0 expected=8b02a7f1 actual=00000000', + 'f-second-fill': 'word=1 expected=00000094 actual=00000000', 'd-mask': 'word=8 expected=00000008 actual=00000009', 'd-whole-mask': 'word=0 expected=00000007 actual=00000011', 'd-x-only': 'word=16 expected=00000009 actual=00000007', 'd-base': 'word=0 expected=00000007 actual=00000000', + 'mask-shift-dropped': 'word=0 expected=0048d159 actual=01234567', + 'extract-shift-dropped': 'word=4 expected=00000000 actual=00000001', 'd-hi': 'word=5 expected=00000008 actual=00000009', 'd-exec': 'word=2 expected=ffffffff actual=00000000', 'g-swapped-offsets': 'word=0 expected=00000004 actual=00000000', @@ -1361,6 +2636,17 @@ def run_case(name, dxc, runner, adapter, directory, control=None): return subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], capture_output=True, text=True) +def renderer_diagnostics(stderr, adapter): + """Echo hardware enumeration notices and retain the remaining lines for the readback check.""" + diagnostics = [] + for line in stderr.splitlines(): + if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): + print(line, file=sys.stderr) + else: + diagnostics.append(line) + return diagnostics + + def check_dispatch(dxc, runner, adapter, control=None): runner = str(Path(runner).resolve()) out = HERE.parent / 'out' @@ -1372,18 +2658,15 @@ def check_dispatch(dxc, runner, adapter, control=None): runs = [(CONTROLS[control][0], control)] else: runs = [(name, None) for name in CASES] + runs.append(('join-load', 'join-load-zero')) runs += [(case, mutation) for mutation, (case, _, _) in CONTROLS.items() if case in L_WORD3] + runs += [('masked-tid', 'mask-shift-dropped'), ('extracted-tid', 'extract-shift-dropped')] for name, mutation in runs: run = run_case(name, dxc, runner, adapter, Path(tmp), mutation) print(run.stdout, end='') if run.returncode == 77: return 77 - diagnostics = [] - for line in run.stderr.splitlines(): - if adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '): - print(line, file=sys.stderr) - else: - diagnostics.append(line) + diagnostics = renderer_diagnostics(run.stderr, adapter) if mutation: first = diagnostics[:1] if (run.returncode != 1 or not any('expected=' in line for line in diagnostics) or diff --git a/tests/startup_gfx2hlsl_compute_mask_spill_check.py b/tests/startup_gfx2hlsl_compute_mask_spill_check.py new file mode 100644 index 0000000000..d1d6f02def --- /dev/null +++ b/tests/startup_gfx2hlsl_compute_mask_spill_check.py @@ -0,0 +1,455 @@ +"""Constant-lane SGPR spills of lane masks in compute stages of tools/startup/gfx2hlsl.py (#1723). + + (no arguments) translation controls and translator mutations, pure Python + binary <llvm-mc> assemble the fixture sources (gfx1013) and compare with the words here + dispatch <dxc> <offscreen_check> <warp|hardware> + translate, compile with DXC cs_6_0, dispatch and compare every word + control <m-saveexec-dropped|m-mask-inverted|v-branch-inverted> <dxc> <offscreen_check> <warp|hardware> + the same dispatch with a mutated translation, which must mismatch + +`v_writelane_b32 vN, M, k` copies the whole wave mask M (vcc_lo, or an SGPR holding a lane mask) into lane k of vN +whatever EXEC is, and `v_readlane_b32 D, vN, k` copies it back to every lane (AMD RDNA 2 ISA reference, VOP3 lane +operations). The translator models a lane mask per invocation as that invocation's own bit (a v_cmp stores `w`, or +`exec & w` once EXEC is not known, so an inactive lane's bit is 0). A reload that is only used as a mask afterwards +sees, in every invocation, the bit that invocation had at the write: the spill is the identity on that bit, so the slot +variable takes the mask's own variable at the write and the reload marks the destination a mask again. + +Fixtures (source-built gfx1013, 4 groups of 8 lanes, root constants key and stride in s4-s5, one descriptor table in s6): +- M spills the compare result vcc_lo (lanes below 5, lane 0 of v40) and an SGPR compare result s26 (lanes below 3, + lane 1), branches on the key, clobbers both, reloads them into SGPRs, selects with v_cndmask_b32_e64 and runs a + masked xor through s_and_saveexec_b32. +- V spills a vcc_lo that is the same in every lane of a group (2 > group index), clobbers vcc_lo, reloads it into + vcc_lo itself, selects with v_cndmask_b32_e32 and skips an add with s_cbranch_vccz. +""" +import re +import struct +import subprocess +import sys +import tempfile +import types +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TOOLS = HERE.parent / 'tools' +sys.path.insert(0, str(TOOLS / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_compute_spill_check as S # noqa: E402 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + str(detail)[:1500]) + + +PROLOGUE = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[12:15], s[10:11], 0x0 +s_load_dwordx4 s[16:19], s[10:11], 0x10 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +""" +M_SPILL = """\ +v_cmp_gt_u32 vcc_lo, 5, v0 +v_writelane_b32 v40, vcc_lo, 0 +v_cmp_gt_u32 s26, 3, v0 +v_writelane_b32 v40, s26, 1 +""" +M_BRANCH = """\ +s_and_b32 s22, s4, 1 +s_cmp_lg_u32 s22, 0 +s_cbranch_scc0 Lelse +v_mov_b32 v7, 100 +s_branch Ljoin +Lelse: +v_mov_b32 v7, 200 +Ljoin: +""" +M_CLOBBER = """\ +v_cmp_gt_u32 vcc_lo, 1, v0 +s_mov_b32 s26, 0 +""" +M_RELOAD = """\ +v_readlane_b32 s25, v40, 0 +v_readlane_b32 s27, v40, 1 +""" +M_USE = """\ +v_cndmask_b32_e64 v6, v5, v7, s25 +v_cndmask_b32_e64 v6, v6, 7, s27 +s_and_saveexec_b32 s23, s25 +v_xor_b32 v6, 0x55, v6 +s_mov_b32 exec_lo, s23 +buffer_store_dword v6, v4, s[16:19], 0 offen +s_endpgm +""" +SOURCE_M = PROLOGUE + M_SPILL + M_BRANCH + M_CLOBBER + M_RELOAD + M_USE +SOURCE_V = PROLOGUE + """\ +v_mov_b32 v8, s7 +v_cmp_gt_u32 vcc_lo, 2, v8 +v_writelane_b32 v40, vcc_lo, 0 +v_cmp_gt_u32 vcc_lo, 1, v0 +v_readlane_b32 vcc_lo, v40, 0 +v_cndmask_b32_e32 v6, v5, v8, vcc_lo +s_cbranch_vccz Lskip +v_add_nc_u32 v6, 1000, v6 +Lskip: +buffer_store_dword v6, v4, s[16:19], 0 offen +s_endpgm +""" +EXPECTED_ACCEPTED = {'M': SOURCE_M, 'V': SOURCE_V} + +# name -> (base source, [(old, new)], what the refusal must say, why it is refused). Each variant is a fixture with one +# change; it is assembled in binary mode like the fixtures and must be refused for that reason and no other. +VARIANTS = { + 'm0-source': (SOURCE_M, [('v_writelane_b32 v40, s26, 1\n', 's_mov_b32 m0, 5\nv_writelane_b32 v40, m0, 1\n')], + 'source m0 is a lane mask or m0', 'm0 is not a mask: it is refused as a spill source'), + 'exec-source': (SOURCE_M, [('v_writelane_b32 v40, s26, 1\n', 'v_writelane_b32 v40, exec_lo, 1\n')], + 'source exec_lo is a lane mask or m0', 'exec is refused as a spill source'), + 'vcc-hi-source': (SOURCE_M, [('v_writelane_b32 v40, vcc_lo, 0\n', 'v_writelane_b32 v40, vcc_hi, 0\n')], + 'source vcc_hi is a lane mask or m0', 'vcc_hi is not the wave32 mask'), + 'numeric-use': (SOURCE_M, [(M_RELOAD, M_RELOAD + 'v_add_nc_u32 v9, s25, v5\n')], 'reads as data', + 'the reloaded mask is read as numeric data'), + 'numeric-use-vcc': (SOURCE_V, [('Lskip:\n', 'Lskip:\nv_add_nc_u32 v9, vcc_lo, v5\n')], 'reads as data', + 'the reloaded vcc_lo is read as numeric data'), + 'masks-joined': (SOURCE_M, [(M_BRANCH, M_BRANCH.replace('v_mov_b32 v7, 100\n', 'v_mov_b32 v7, 100\n' + 'v_writelane_b32 v40, s26, 0\n'))], + 'one of them a lane mask', 'one arm overwrites lane 0 with a different mask'), + 'mask-and-number-joined': (SOURCE_M, [(M_BRANCH, M_BRANCH.replace('v_mov_b32 v7, 100\n', 'v_mov_b32 v7, 100\n' + 's_mov_b32 s28, 9\nv_writelane_b32 v40, s28, 0\n'))], + 'one of them a lane mask', 'one arm overwrites lane 0 with a number'), + 'reload-before-write': (SOURCE_M, [('v_writelane_b32 v40, s26, 1\n', '')], 'no v_writelane_b32 of it on some path', + 'lane 1 is never written'), + 'mask-reloaded-into-vcc-from-number': (SOURCE_V, [('v_writelane_b32 v40, vcc_lo, 0\n', 's_mov_b32 s28, 1\n' + 'v_writelane_b32 v40, s28, 0\n')], + 'requires an SGPR destination', 'a number is reloaded into vcc_lo'), + 'mask-from-one-arm': (SOURCE_M, [('v_cmp_gt_u32 s26, 3, v0\nv_writelane_b32 v40, s26, 1\n', 's_mov_b32 s26, 0\n'), + ('v_mov_b32 v7, 100\n', 'v_mov_b32 v7, 100\nv_cmp_gt_u32 s26, 3, v0\n'), + ('Ljoin:\n', 'Ljoin:\nv_writelane_b32 v40, s26, 1\n')], + 'lane mask not proven on every path', 'the mask is computed in one arm only'), + 'write-in-execz': (SOURCE_M, [(M_CLOBBER, M_CLOBBER + 's_mov_b32 s21, exec_lo\nv_cmp_gt_u32 vcc_lo, 5, v0\n' + 's_mov_b32 exec_lo, vcc_lo\ns_cbranch_execz Lz\nv_writelane_b32 v40, vcc_lo, 2\n' + 'Lz:\ns_mov_b32 exec_lo, s21\n')], + 'inside a block s_cbranch_execz skips per lane', 'a mask written inside an execz region'), + 'loop-carried': (SOURCE_M, [('Ljoin:\n', 'Ljoin:\ns_mov_b32 s22, 0\nLloop:\nv_readlane_b32 s25, v40, 0\n' + 'v_writelane_b32 v40, s25, 0\ns_add_u32 s22, s22, 1\ns_cmp_lt_u32 s22, 2\n' + 's_cbranch_scc1 Lloop\n')], + 'written later in a loop', 'a mask reloaded by a loop body that writes it again'), +} + + +def variant_source(name): + base, edits = VARIANTS[name][:2] + for old, new in edits: + assert base.count(old) == 1, (name, old) + base = base.replace(old, new) + return base + + +def all_sources(): + return {**EXPECTED_ACCEPTED, **{name: variant_source(name) for name in VARIANTS}} + + +ENCODING = (C.USER7 | C.TGID_X | C.tidig(1), (8, 1, 1), (4, 1, 1)) +WORDS = { + 'M': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600' + '060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'V': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf0702107e8210887d280061d76a0001008100887d6a0060d72801010005110c02020086bfff0c0c4ae8030000' + '001070e004060480000081bf'), + 'm0-source': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d4830002008503fcbe280061d77c02010004811687168007bf030084bf' + 'ff020e7e64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5' + '050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'exec-source': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d77e02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600' + '060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'vcc-hi-source': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76b0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600' + '060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'numeric-use': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100190a124a060001d5' + '050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'numeric-use-vcc': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf0702107e8210887d280061d76a0001008100887d6a0060d72801010005110c02020086bfff0c0c4ae8030000' + '6a0a124a001070e004060480000081bf'), + 'masks-joined': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf050084bfff020e7e' + '64000000280061d71a000100020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100' + '060001d5050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'mask-and-number-joined': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf060084bfff020e7e' + '6400000089039cbe280061d71c000100020082bfff020e7ec80000008100887d80039abe190060d7280101001b0060d7' + '28030100060001d5050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'reload-before-write': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d48300020004811687168007bf030084bfff020e7e64000000020082bf' + 'ff020e7ec80000008100887d80039abe190060d7280101001b0060d728030100060001d5050f6600060001d5060f6d00' + '193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'mask-reloaded-into-vcc-from-number': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf0702107e8210887d81039cbe280061d71c0001008100887d6a0060d72801010005110c02020086bfff0c0c4a' + 'e8030000001070e004060480000081bf'), + 'mask-from-one-arm': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a00010080039abe04811687168007bf050084bfff020e7e640000001a00c4d483000200' + '020082bfff020e7ec8000000280061d71a0201008100887d80039abe190060d7280101001b0060d728030100060001d5' + '050f6600060001d5060f6d00193c97beff0c0c3a550000001703febe001070e004060480000081bf'), + 'write-in-execz': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec80000008100887d80039abe7e0395be8500887d6a03febe020088bf280061d76a040100' + '1503febe190060d7280101001b0060d728030100060001d5050f6600060001d5060f6d00193c97beff0c0c3a55000000' + '1703febe001070e004060480000081bf'), + 'loop-carried': bytes.fromhex( + '06038abe80038bbe050308f4000000fa050408f4100000fa7fc08cbf0783148f1400064a82060834001030e004050380' + '703f8cbf8500887d280061d76a0001001a00c4d483000200280061d71a02010004811687168007bf030084bfff020e7e' + '64000000020082bfff020e7ec8000000800396be190060d728010100280061d7190001001681168016820abff9ff85bf' + '8100887d80039abe190060d7280101001b0060d728030100060001d5050f6600060001d5060f6d00193c97beff0c0c3a' + '550000001703febe001070e004060480000081bf'), +} +WORDS_OUT = C.WORDS +SENTINEL = C.SENTINEL +KEY = C.KEY + + +def translate(name, code=None, module=G): + return module.ComputePipeline(code or WORDS[name], C.root_blob(), ENCODING[0], ENCODING[1]) + + +def refusal(name, module=G): + try: + translate(name, module=module).hlsl_cs() + except module.Unsupported as reason: + return str(reason) + return None + + +def expected(name): + out = [SENTINEL] * WORDS_OUT + for gx in range(4): + for tx in range(8): + i, word = gx * 8 + tx, C.input_word(gx * 8 + tx) + if name == 'M': + v7 = 100 if KEY & 1 else 200 + a, b = tx < 5, tx < 3 + word = v7 if a else word + word = 7 if b else word + out[i] = word ^ 0x55 if a else word + else: + word = gx if gx < 2 else word + out[i] = word + 1000 if gx < 2 else word + return out + + +def controls(module=G, quiet=False): + """-> the labels of the controls that failed (all printed unless quiet).""" + red = [] + + def verdict(label, ok, detail=''): + if not ok: + red.append(label) + if not quiet: + check(label, ok, detail) + + for name in EXPECTED_ACCEPTED: + reason = refusal(name, module) + verdict('fixture %s translates (%s)' % (name, reason), reason is None) + for name, (_, _, fragment, why) in VARIANTS.items(): + reason = refusal(name, module) + verdict('refused: %s (%s)' % (why, reason), reason is not None and fragment in reason, reason) + verdict('mask spills stay refused in a pixel stage (%s)' % probe_pixel(module), 'holds a lane mask or descriptor' in + probe_pixel(module)) + return red + + +def probe_pixel(module): + """A pixel stage that spills a lane mask keeps the refusal of step 1: only compute stages model the mask this way.""" + stage = module.Stage.__new__(module.Stage) + stage.kind, stage.lines, stage.sym = 'ps', [], {} + stage.used_s, stage.used_v, stage.uniform_v, stage.varying_s = set(), set(), set(), set() + stage.scc_uniform, stage.exec_known, stage.has_branches, stage.blocks, stage.masks = True, True, False, [], {20} + stage.join_masks = set() + stage.ins = [(0, 1, 'v_writelane_b32', 'v_writelane_b32 v10, s20, 3')] + try: + stage.one('v_writelane_b32', 'v_writelane_b32 v10, s20, 3') + except module.Unsupported as why: + return str(why) + return 'accepted' + + +# Each translator mutation must turn at least one control red. +MUTATIONS = { + 'a mask is not marked again after the reload': (' if mask:\n self.masks.add(dst[1])', + ' if False:\n self.masks.add(dst[1])'), + 'a reloaded mask is read as data': (" if not (self.per_lane_read(j, key) or copy or", " if not (True or copy or"), + 'a lane select is not a mask read': (" if not (self.per_lane_read(j, key) or copy or", " if not (copy or"), + 'two writes with a mask join': (' if any(s[3] for s in stored) and len(stored) > 1:', ' if False:'), + 'm0 is a mask source': (" elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'):", + " elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi'):"), + 'exec is a mask source': (" elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'):", + " elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'm0'):"), + 'vcc_hi is a mask source': (" if ops[1] == 'vcc_lo' and self.spills_lane_masks():", + " if ops[1] in ('vcc_hi', 'vcc_lo') and self.spills_lane_masks():"), + 'a mask not proven on every path is spilled': (' if src[1] in self.join_masks:', ' if False:'), + 'the write stores the inverted bit': ("value, sym, uniform, proven, mask = 'vcc', None", + "value, sym, uniform, proven, mask = '(vcc ^ 1u)', None"), + 'the reload restores the neighbouring slot': (" self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=None if mask else sym,", + " self.set_s(dst[1], 'sp%d_%d' % (n, lane ^ int(mask)), sym=None if mask else sym,"), + 'every stage spills masks': (" return getattr(self, 'kind', None) == 'cs'", ' return True'), + 'a number is reloaded into vcc_lo': (" if not (mask and ops[0] == 'vcc_lo'):", " if ops[0] != 'vcc_lo':"), + 'no loop-carried refusal': (" if max(writes) > i:", " if False:"), + 'no write-before-read refusal': (" if writes is None:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no", + " if writes is None and False:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no"), +} + + +def mutated(old, new): + source = (TOOLS / 'startup' / 'gfx2hlsl.py').read_text(encoding='utf-8').replace('\r\n', '\n') + assert source.count(old) == 1, old + module = types.ModuleType('gfx2hlsl_mutant') + module.__file__ = str(TOOLS / 'startup' / 'gfx2hlsl.py') + exec(compile(source.replace(old, new), module.__file__, 'exec'), module.__dict__) + return module + + +def check_mutations(): + for label, (old, new) in MUTATIONS.items(): + try: + module = mutated(old, new) + red = controls(module, quiet=True) + check_text(module, quiet=True) + except Exception as error: # a mutant that crashes the translator is caught as well + red = ['crash: %s' % error] + check('mutation "%s" turns %d control(s) red: %s' % (label, len(red), red[:3]), bool(red)) + + +def check_text(module=G, quiet=False): + """-> the labels of the text checks that failed. The slot takes the mask's variable at the write and the reload copies + it back, which is what makes the spill the identity on each invocation's bit.""" + red = [] + + def verdict(label, ok, detail=''): + if not ok: + red.append(label) + if not quiet: + check(label, ok, detail) + + m, v = translate('M', module=module).hlsl_cs(), translate('V', module=module).hlsl_cs() + lines = [line.strip() for line in m.splitlines()] + verdict('M: the slots take the mask variables, the reloads copy them back', + 'sp40_0 = vcc;' in lines and 'sp40_1 = s26;' in lines and 's25 = sp40_0;' in lines and 's27 = sp40_1;' in lines, m) + verdict('M: the compare writes the bit of its own invocation', 'vcc = ((0x00000005u > v0) ? 1u : 0u);' in lines, m) + verdict('M: the reloaded masks select and narrow EXEC', 'v6 = (s25 & 1) ? v7 : v5;' in lines and + 'exec = (exec & s25) & 1; scc = exec != 0;' in lines, m) + vl = [line.strip() for line in v.splitlines()] + verdict('V: vcc_lo is reloaded into vcc and drives the branch', + 'sp40_0 = vcc;' in vl and 'vcc = sp40_0;' in vl and 'pc = ((vcc & 1) == 0) ? 2 : 1;' in vl, v) + return red + + +# ---- binary and dispatch --------------------------------------------------------------------------------------------- +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = S.assemble_labels(llvm_mc, source) + check('llvm-mc assembles %s to the recorded words' % name, built == WORDS[name], built.hex()) + + +# control -> (case, text the translation must contain once, replacement) +CONTROLS = { + 'm-saveexec-dropped': ('M', 'exec = (exec & s25) & 1; scc = exec != 0;', 'scc = exec != 0;'), + 'm-mask-inverted': ('M', 'sp40_0 = vcc;', 'sp40_0 = vcc ^ 1u;'), + 'v-branch-inverted': ('V', 'pc = ((vcc & 1) == 0) ? 2 : 1;', 'pc = ((vcc & 1) != 0) ? 2 : 1;'), +} + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate(name).hlsl_cs() + if control: + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + hlsl = hlsl.replace(old, new) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = ENCODING[2] + constants = [KEY, C.STRIDE] + [0] * 14 + case.write_bytes(struct.pack('<I', groups[0] | groups[1] << 8 | groups[2] << 16) + + struct.pack('<%dI' % WORDS_OUT, *expected(name)) + struct.pack('<16I', *constants)) + return subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], capture_output=True, text=True) + + +def check_dispatch(dxc, runner, adapter, control=None): + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + runs = [(CONTROLS[control][0], control)] if control else [(n, None) for n in ('M', 'V')] + if not control: + runs += [(case, mutation) for mutation, (case, _, _) in CONTROLS.items()] + for name, mutation in runs: + run = run_case(name, dxc, runner, adapter, Path(tmp), mutation) + print(run.stdout, end='') + if run.returncode == 77: + return 77 + diagnostics = [line for line in run.stderr.splitlines() + if not (adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '))] + if mutation: + if run.returncode != 1 or not any('expected=' in line for line in diagnostics): + raise AssertionError('control %s: unexpected result (exit %d) %s' % (mutation, run.returncode, run.stderr)) + print('control %s: rejected at %s' % (mutation, diagnostics[0])) + elif run.returncode or diagnostics: + raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) + else: + print('case %s: all %d words match' % (name, WORDS_OUT)) + return 0 + + +def main(): + args = sys.argv[1:] + if not args: + controls() + check_text() + check_mutations() + elif len(args) == 2 and args[0] == 'binary': + check_binary(args[1]) + elif len(args) == 4 and args[0] == 'dispatch': + controls() + sys.exit(check_dispatch(*args[1:]) or (1 if failures else 0)) + elif len(args) == 5 and args[0] == 'control': + sys.exit(check_dispatch(*args[2:], control=args[1])) + else: + sys.exit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_compute_spill_check.py b/tests/startup_gfx2hlsl_compute_spill_check.py new file mode 100644 index 0000000000..4bf0015e59 --- /dev/null +++ b/tests/startup_gfx2hlsl_compute_spill_check.py @@ -0,0 +1,522 @@ +"""Constant-lane SGPR spills of descriptor and pointer words in compute stages of tools/startup/gfx2hlsl.py (#1723). + + (no arguments) translation controls and translator mutations, pure Python + binary <llvm-mc> assemble the fixture sources (gfx1013) and compare with the words here + dispatch <dxc> <offscreen_check> <warp|hardware> + translate, compile with DXC cs_6_0, dispatch and compare every word + control <p-store-dropped|s-arm-swapped|s-store-dropped> <dxc> <offscreen_check> <warp|hardware> + the same dispatch with a mutated translation, which must mismatch + +`v_writelane_b32 vN, sM, k` parks SGPR sM in lane k of vN and `v_readlane_b32 sD, vN, k` reads it back; both ignore +EXEC (AMD RDNA 2 ISA reference, VOP3 lane operations). A descriptor or pointer word has no run-time value in the +translation: it is a symbol (`('desc', table, offset, dword)`, `('ptr', ...)`), so the slot carries the symbol and the +reload restores the same one. The write-before-read proof of tests/startup_gfx2hlsl_spill_branches_check.py (a write +on every path, regions the wave runs while a thread skips them, loop-carried reads) decides whether a reload sees the +symbol, and a reload keeps the provenance of the word it restores: a formatted buffer load past the entry block +accepts a reloaded descriptor only when every write that can supply it was itself the word of an entry-block or +local table load. + +Fixtures (source-built gfx1013, root constants key and stride in s4-s5, one descriptor table in s6): +- S spills the table's read descriptor s[12:15] (formatted load) in the entry block and its store descriptor s[16:19] + in both arms of a uniform branch on the key, clobbers both, and inside an s_cbranch_execz region reloads them and + loads RG16_UINT words through one and stores through the other. 16 lanes, lanes below 12 store four words each. +- P spills the table pointer pair s[10:11] (the low word a table pointer, the high word the constant zero), clobbers + it, reloads it inside an s_cbranch_execz region and loads the store descriptor through it (shape of case J of + tests/startup_gfx2hlsl_compute_check.py). Four groups of eight lanes, lanes below 3 store one word. +""" +import re +import struct +import subprocess +import sys +import tempfile +import types +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TOOLS = HERE.parent / 'tools' +sys.path.insert(0, str(TOOLS / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + str(detail)[:1500]) + + +SOURCE_S = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_writelane_b32 v40, s12, 0 +v_writelane_b32 v40, s13, 1 +v_writelane_b32 v40, s14, 2 +v_writelane_b32 v40, s15, 3 +s_and_b32 s23, s4, 1 +s_cmp_lg_u32 s23, 0 +s_cbranch_scc0 Lelse +v_writelane_b32 v40, s16, 4 +v_writelane_b32 v40, s17, 5 +v_writelane_b32 v40, s18, 6 +v_writelane_b32 v40, s19, 7 +v_mov_b32 v1, 1 +s_branch Ljoin +Lelse: +v_writelane_b32 v40, s16, 4 +v_writelane_b32 v40, s17, 5 +v_writelane_b32 v40, s18, 6 +v_writelane_b32 v40, s19, 7 +v_mov_b32 v1, 0 +Ljoin: +s_mov_b32 s12, 0 +s_mov_b32 s13, 0 +s_mov_b32 s14, 0 +s_mov_b32 s15, 0 +s_mov_b32 s16, 0 +s_mov_b32 s17, 0 +s_mov_b32 s18, 0 +s_mov_b32 s19, 0 +v_lshlrev_b32 v4, 4, v0 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 12, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz Lend +v_readlane_b32 s12, v40, 0 +v_readlane_b32 s13, v40, 1 +v_readlane_b32 s14, v40, 2 +v_readlane_b32 s15, v40, 3 +v_readlane_b32 s16, v40, 4 +v_readlane_b32 s17, v40, 5 +v_readlane_b32 s18, v40, 6 +v_readlane_b32 s19, v40, 7 +buffer_load_format_xyzw v[5:8], v[0:1], s[12:15], 0 idxen offen offset:2 +s_waitcnt vmcnt(0) +buffer_store_dwordx4 v[5:8], v4, s[16:19], 0 offen +Lend: +s_mov_b32 exec_lo, s21 +s_endpgm +""" +SOURCE_P = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[12:15], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_writelane_b32 v41, s10, 0 +v_writelane_b32 v41, s11, 1 +s_mov_b32 s10, 0 +s_mov_b32 s11, 0 +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 3, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz Lend +v_readlane_b32 s10, v41, 0 +v_readlane_b32 s11, v41, 1 +s_load_dwordx4 s[16:19], s[10:11], 0x10 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) lgkmcnt(0) +v_xor_b32 v5, s22, v5 +buffer_store_dword v5, v4, s[16:19], 0 offen +Lend: +s_mov_b32 exec_lo, s21 +s_endpgm +""" +S_ARM = ('v_writelane_b32 v40, s16, 4\nv_writelane_b32 v40, s17, 5\nv_writelane_b32 v40, s18, 6\n' + 'v_writelane_b32 v40, s19, 7\n') +S_ENTRY = 'v_writelane_b32 v40, s12, 0\nv_writelane_b32 v40, s13, 1\nv_writelane_b32 v40, s14, 2\nv_writelane_b32 v40, s15, 3\n' + +# name -> (base source, [(old, new)], what the refusal must say, why it is refused). Each variant is a fixture with one +# change; it is assembled in binary mode like the fixtures and must be refused for that reason and no other. +VARIANTS = { + 'reload-before-write': (SOURCE_S, [(S_ENTRY, '')], 'no v_writelane_b32 of it on some path', + 'the read descriptor is never written to its lanes'), + 'two-descriptors-joined': (SOURCE_S, [(S_ARM + 'v_mov_b32 v1, 0', S_ARM.replace('s16', 's12').replace('s17', 's13') + .replace('s18', 's14').replace('s19', 's15') + 'v_mov_b32 v1, 0')], + 'joins different descriptor or pointer words', + 'one arm spills the read descriptor and the other the store descriptor into the same lanes'), + 'modified-word': (SOURCE_S, [('s_and_b32 s23, s4, 1', 's_and_b32 s17, s17, 0xc000ffff\ns_and_b32 s23, s4, 1')], + 'modified descriptor or pointer word', 'a stride word rewritten before the spill'), + 'lane-mask': (SOURCE_S, [('v_writelane_b32 v40, s16, 4\nv_writelane_b32 v40, s17, 5\nv_writelane_b32 v40, s18, 6\n' + 'v_writelane_b32 v40, s19, 7\nv_mov_b32 v1, 1', + 'v_cmp_gt_u32 s20, 12, v0\nv_writelane_b32 v40, s20, 4\nv_mov_b32 v1, 1')], + 'one of them a lane mask', 'a compare result spilled in one arm where the other arm spills a descriptor ' + '(lane masks have their own fixtures in tests/startup_gfx2hlsl_compute_mask_spill_check.py)'), + 'wrong-lane': (SOURCE_S, [('v_readlane_b32 s13, v40, 1', 'v_readlane_b32 s13, v40, 5')], + 'descriptor whose words were rewritten', 'word 1 of the descriptor reloaded from the lane of word 5'), + 'unproven-descriptor': (SOURCE_S, [(S_ENTRY, ''), ('v_mov_b32 v1, 1', S_ENTRY + 'v_mov_b32 v1, 1'), + ('v_mov_b32 v1, 0', S_ENTRY + 'v_mov_b32 v1, 0')], + 'requires descriptor words proven in the entry block', + 'the read descriptor is spilled in the arms, where its load is not local'), + 'written-in-region-read-outside': (SOURCE_S, [ + (S_ARM + 'v_mov_b32 v1, 1', 'v_mov_b32 v1, 1'), (S_ARM + 'v_mov_b32 v1, 0', 'v_mov_b32 v1, 0'), + (''.join('s_mov_b32 s%d, 0\n' % r for r in range(16, 20)), ''), + (''.join('v_readlane_b32 s%d, v40, %d\n' % (r, r - 12) for r in range(16, 20)), ''), + ('s_cbranch_execz Lend\n', 's_cbranch_execz Lend\n' + S_ARM), ('Lend:\n', 'Lend:\nv_readlane_b32 s16, v40, 4\n')], + 'effect outside scalar registers', 'the store descriptor is written inside the ' + 'execz region (the lane write is a cross-lane effect there) and reloaded after it'), + 'loop-carried': (SOURCE_S, [('Ljoin:\n', 'Ljoin:\ns_mov_b32 s22, 0\nLloop:\nv_readlane_b32 s16, v40, 4\n' + 'v_writelane_b32 v40, s16, 4\ns_add_u32 s22, s22, 1\ns_cmp_lt_u32 s22, 2\n' + 's_cbranch_scc1 Lloop\n')], + 'written later in a loop', 'a reload whose lane is written again by the loop body'), +} +EXPECTED_ACCEPTED = {'S': SOURCE_S, 'P': SOURCE_P} + + +def variant_source(name): + base, edits = VARIANTS[name][:2] + for old, new in edits: + assert base.count(old) == 1, (name, old) + base = base.replace(old, new) + return base + + +def all_sources(): + return {**EXPECTED_ACCEPTED, **{name: variant_source(name) for name in VARIANTS}} + + +def assemble_labels(llvm_mc, source): + """llvm-mc leaves a branch label to the linker, so the words come from a first pass for the instruction sizes.""" + from startup_flat_param_check import assemble + lines = source.splitlines() + plain = [line for line in lines if not line.endswith(':')] + sizes = [] + for line in plain: + sizes.append(len(assemble(llvm_mc, line + '\n'))) + labels, position, at = {}, 0, 0 + for line in lines: + if line.endswith(':'): + labels[line[:-1]] = position + else: + position += sizes[at] + at += 1 + out, position = [], 0 + for line, size in zip(plain, sizes): + m = re.fullmatch(r'(s_c?branch\w*) (L\w+)', line) + if m: + line = '%s %d' % (m[1], (labels[m[2]] - (position + 4)) // 4) + out.append(line) + position += size + words = bytearray() + for line in out: + built = bytearray(assemble(llvm_mc, line + '\n')) + if re.match(r'v_(read|write)lane_b32\b|v_cmp\w*\s', line) and len(built) == 8: + # src2 of the lane operations and of the VOP3 compares is unused: LLVM 15 encodes it as 0, newer LLVM as the + # inline constant 0 (128). + # Clear it so the recorded words hold for both. + dword = int.from_bytes(built[4:8], 'little') & ~(0x1ff << 18) + built[4:8] = dword.to_bytes(4, 'little') + words += built + return bytes(words) + + +# CASE: (source, words as hex, rsrc2, group size, group counts) +USER7, TGID_X, tidig = C.USER7, C.TGID_X, C.tidig +CASES_ENCODING = { + 'S': (USER7, (16, 1, 1), (1, 1, 1)), + 'P': (USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), +} +WORDS = { + 'S': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e01008002027e80038cbe' + '80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf' + '0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100100060d728090100110060d7280b0100' + '120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'P': bytes.fromhex( + '06038abe80038bbe050308f4000000fa7fc08cbf290061d70a000100290061d70b02010080038abe80038bbe0783148f' + '1400064a820608347e0395be8300887d6a03febe0e0088bf0a0060d7290101000b0060d729030100050408f4100000fa' + '0705169316041680001030e00405038070008cbf160a0a3a001070e0040504801503febe000081bf'), + 'reload-before-write': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf04811787178007bf0a0084bf280061d710080100280061d7110a0100' + '280061d7120c0100280061d7130e01008102027e090082bf280061d710080100280061d7110a0100280061d7120c0100' + '280061d7130e01008002027e80038cbe80038dbe80038ebe80038fbe800390be800391be800392be800393be84000834' + '7e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100' + '100060d728090100110060d7280b0100120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0' + '040504801503febe000081bf'), + 'two-descriptors-joined': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d70c080100280061d70d0a0100280061d70e0c0100280061d70f0e01008002027e80038cbe' + '80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf' + '0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100100060d728090100110060d7280b0100' + '120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'modified-word': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010011ff1187ffff00c004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100' + '280061d7130e01008102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8002027e80038cbe80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d' + '6a03febe150088bf0c0060d7280101000d0060d7280301000e0060d7280501000f0060d728070100100060d728090100' + '110060d7280b0100120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe' + '000081bf'), + 'lane-mask': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf060084bf1400c4d48c000200280061d7140801008102027e090082bf280061d710080100' + '280061d7110a0100280061d7120c0100280061d7130e01008002027e80038cbe80038dbe80038ebe80038fbe800390be' + '800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d728030100' + '0e0060d7280501000f0060d728070100100060d728090100110060d7280b0100120060d7280d0100130060d7280f0100' + '02300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'wrong-lane': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e01008002027e80038cbe' + '80038dbe80038ebe80038fbe800390be800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf' + '0c0060d7280101000d0060d7280b01000e0060d7280501000f0060d728070100100060d728090100110060d7280b0100' + '120060d7280d0100130060d7280f010002300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'unproven-descriptor': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf04811787178007bf120084bf280061d710080100280061d7110a0100' + '280061d7120c0100280061d7130e0100280061d70c000100280061d70d020100280061d70e040100280061d70f060100' + '8102027e110082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100280061d70c000100' + '280061d70d020100280061d70e040100280061d70f0601008002027e80038cbe80038dbe80038ebe80038fbe800390be' + '800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d728030100' + '0e0060d7280501000f0060d728070100100060d728090100110060d7280b0100120060d7280d0100130060d7280f0100' + '02300ce000050380703f8cbf001078e0040504801503febe000081bf'), + 'written-in-region-read-outside': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf020084bf8102027e010082bf8002027e80038cbe80038dbe80038ebe80038fbe84000834' + '7e0395be8c00887d6a03febe150088bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '0c0060d7280101000d0060d7280301000e0060d7280501000f0060d72807010002300ce000050380703f8cbf001078e0' + '04050480100060d7280901001503febe000081bf'), + 'loop-carried': bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf280061d70c000100280061d70d020100280061d70e040100280061d7' + '0f06010004811787178007bf0a0084bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e0100' + '8102027e090082bf280061d710080100280061d7110a0100280061d7120c0100280061d7130e01008002027e800396be' + '100060d728090100280061d7100801001681168016820abff9ff85bf80038cbe80038dbe80038ebe80038fbe800390be' + '800391be800392be800393be840008347e0395be8c00887d6a03febe150088bf0c0060d7280101000d0060d728030100' + '0e0060d7280501000f0060d728070100100060d728090100110060d7280b0100120060d7280d0100130060d7280f0100' + '02300ce000050380703f8cbf001078e0040504801503febe000081bf'), +} + + +KEY, STRIDE, SENTINEL, WORDS_OUT = C.KEY, C.STRIDE, C.SENTINEL, C.WORDS +LIVE_LANES = 12 + + +def expected(name): + out = [SENTINEL] * WORDS_OUT + if name == 'S': + data = C.formatted_input() + for lane in range(LIVE_LANES): # the same RG16_UINT words as case L-uint, the lanes the compare leaves active + low, high = struct.unpack_from('<HH', data, 6 * lane + 3) + out[4 * lane:4 * lane + 4] = (high, low, 1, 0) + else: # P: the words of case J + for gx in range(4): + for tx in range(3): + i = gx * 8 + tx + out[i] = C.input_word(i) ^ ((gx * STRIDE + KEY) & C.MASK) + return out + + +def translate(name, code=None, module=G): + rsrc2, local, _ = CASES_ENCODING['P' if name == 'P' else 'S'] + return module.ComputePipeline(code or WORDS[name], C.root_blob(), rsrc2, local) + + +def refusal(name, module=G): + try: + translate(name, module=module).hlsl_cs() + except module.Unsupported as reason: + return str(reason) + return None + + +def controls(module=G, quiet=False): + """-> the labels of the controls that failed (all printed unless quiet).""" + red = [] + + def verdict(label, ok, detail=''): + if not ok: + red.append(label) + if not quiet: + check(label, ok, detail) + + for name in ('S', 'P'): + reason = refusal(name, module) + verdict('fixture %s translates (%s)' % (name, reason), reason is None) + for name, (_, _, fragment, why) in VARIANTS.items(): + reason = refusal(name, module) + verdict('refused: %s (%s)' % (why, reason), reason is not None and fragment in reason, reason) + return red + + +def probe_refusals(): + """Unit probes on a compute Stage that has symbols a table program cannot give it: ptrhi, a pointer with an offset.""" + def reason(sym_text, source_sym, kind='cs'): + stage = G.Stage.__new__(G.Stage) + stage.kind, stage.lines, stage.sym = kind, [], {20: source_sym} if source_sym else {} + stage.used_s, stage.used_v, stage.uniform_v, stage.varying_s = set(), set(), set(), set() + stage.scc_uniform, stage.exec_known, stage.has_branches, stage.blocks, stage.masks = True, True, False, [], set() + stage.ins = [(4 * i, 1, a.split(' ', 1)[0], a) for i, a in enumerate(sym_text)] + for _, _, name, asm in stage.ins: + try: + stage.one(name, asm) + except G.Unsupported as why: + return str(why) + return stage + + spill = ['v_writelane_b32 v10, s20, 3', 'v_readlane_b32 s21, v10, 3'] + for label, sym in (('a table pointer', ('ptr', ('table', 0))), ('the high word of a root pointer', ('ptrhi', ('root', 2))), + ('a descriptor word', ('desc', ('table', 0), 0, 1))): + stage = reason(spill, sym) + check('compute stage spills %s and reloads the same symbol' % label, + not isinstance(stage, str) and stage.sym.get(21) == sym, stage) + for label, sym in (('a pointer with an offset', ('ptr', ('table', 0), 'added')), + ('a descriptor word with its stride cleared', ('desc', ('table', 0), 0, 1, 'stride0'))): + text = reason(spill, sym) + check('refused: %s (%s)' % (label, text), isinstance(text, str) and 'modified descriptor or pointer word' in text) + for label, sym in (('a table pointer', ('ptr', ('table', 0))), ('a descriptor word', ('desc', ('table', 0), 0, 1))): + text = reason(spill, sym, kind='ps') + check('refused: %s in a pixel stage (%s)' % (label, text), + isinstance(text, str) and 'holds a lane mask or descriptor' in text) + + +# Each translator mutation must turn at least one control red. +MUTATIONS = { + 'the reload restores no symbol': (' self.set_s(dst[1], \'sp%d_%d\' % (n, lane), sym=sym, uniform=uniform)', + ' self.set_s(dst[1], \'sp%d_%d\' % (n, lane), sym=None, uniform=uniform)'), + 'the reload drops the provenance': (" return all(\n getattr(self, 'reload_proven', {}).get(reloads[w], False)", + " return all(\n False and getattr(self, 'reload_proven', {}).get(reloads[w], False)"), + 'every reload counts as proven': (" return all(\n getattr(self, 'reload_proven', {}).get(reloads[w], False)", + " return all(\n True or getattr(self, 'reload_proven', {}).get(reloads[w], False)"), + 'a write counts as proven wherever the descriptor came from': ( + " if sym[0] != 'desc' or not getattr(self, 'past_entry', False):\n return True\n return self.formatted", + " if True:\n return True\n return self.formatted"), + 'the reload reads the neighbouring lane': (' reach[i] = state.get((vreg, lane))', + ' reach[i] = state.get((vreg, lane ^ 1))'), + 'different symbols join into none': (" if sym is None and any(s[0] is not None and s[0][0] in self.SPILL_SYMBOLS for s in stored):", + " if False:"), + 'a modified word is carried': (" if not names_one_value(held):", " if False:"), + 'no branches in a compute stage': ("(kind not in ('ps', 'cs') or getattr(self, 'spill_reach', None) is None)):", + "(kind != 'ps' or getattr(self, 'spill_reach', None) is None)):"), + 'compute stages refused': ("SPILL_STAGES = ('ps', 'vs', 'ms', 'cs')", "SPILL_STAGES = ('ps', 'vs', 'ms')"), + 'no loop-carried refusal': (" if max(writes) > i:", " if False:"), + 'no write-before-read refusal': (" if writes is None:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no", + " if writes is None and False:\n raise Unsupported('v_readlane_b32 reads v%d lane %d with no"), +} + + +def mutated(old, new): + source = (TOOLS / 'startup' / 'gfx2hlsl.py').read_text(encoding='utf-8').replace('\r\n', '\n') + assert source.count(old) == 1, old + module = types.ModuleType('gfx2hlsl_mutant') + module.__file__ = str(TOOLS / 'startup' / 'gfx2hlsl.py') + exec(compile(source.replace(old, new), module.__file__, 'exec'), module.__dict__) + return module + + +def check_mutations(): + for label, (old, new) in MUTATIONS.items(): + try: + red = controls(mutated(old, new), quiet=True) + except Exception as error: # a mutant that crashes the translator is caught as well + red = ['crash: %s' % error] + check('mutation "%s" turns %d control(s) red: %s' % (label, len(red), red[:3]), bool(red)) + + +def check_text(): + s, p = translate('S').hlsl_cs(), translate('P').hlsl_cs() + check('the descriptor slots are declared and never assigned', [l for l in s.splitlines() if 'sp40_' in l] == + [l for l in s.splitlines() if l.lstrip().startswith('uint sp40_')], s) + check('the formatted load reads word 3 of the table descriptor', 'switch ((ud3 >> 12) & 127u)' in s) + check('the pointer slot is never assigned, the constant high word is', '= sp41_0' not in p and 's11 = sp41_1;' in p, p) + check('the pointer fixture stores through the reloaded table', p.count('u0.Store(') == 1) + + +# ---- binary and dispatch --------------------------------------------------------------------------------------------- +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = assemble_labels(llvm_mc, source) + check('llvm-mc assembles %s to the recorded words' % name, built == WORDS[name], built.hex()) + + +# control -> (case, text the translation must contain once, replacement) +CONTROLS = { + 's-arm-swapped': ('S', 'pc = (!scc) ? 2 : 1;', 'pc = (!scc) ? 1 : 2;'), + 's-store-dropped': ('S', 'u0.Store4(a, uint4(v5, v6, v7, v8));', ''), + 'p-store-dropped': ('P', 'u0.Store(a, v5);', ''), +} + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate(name).hlsl_cs() + if control: + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + hlsl = hlsl.replace(old, new) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = CASES_ENCODING[name][2] + constants = [KEY, STRIDE] + [0] * 14 + source = b'' + if name == 'S': + constants[2:4] = [C.L_STRIDE, C.L_WORD3['L-uint']] + source = C.formatted_input() + case.write_bytes(struct.pack('<I', groups[0] | groups[1] << 8 | groups[2] << 16) + + struct.pack('<%dI' % WORDS_OUT, *expected(name)) + struct.pack('<16I', *constants) + source) + return subprocess.run([runner, adapter, '--compute-store-case', str(cso), str(case)], capture_output=True, text=True) + + +def check_dispatch(dxc, runner, adapter, control=None): + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + runs = [(CONTROLS[control][0], control)] if control else [(n, None) for n in ('S', 'P')] + if not control: + runs += [(case, mutation) for mutation, (case, _, _) in CONTROLS.items()] + for name, mutation in runs: + run = run_case(name, dxc, runner, adapter, Path(tmp), mutation) + print(run.stdout, end='') + if run.returncode == 77: + return 77 + diagnostics = [line for line in run.stderr.splitlines() + if not (adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '))] + if mutation: + if run.returncode != 1 or not any('expected=' in line for line in diagnostics): + raise AssertionError('control %s: unexpected result (exit %d) %s' % (mutation, run.returncode, run.stderr)) + print('control %s: rejected at %s' % (mutation, diagnostics[0])) + elif run.returncode or diagnostics: + raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) + else: + print('case %s: all %d words match' % (name, WORDS_OUT)) + return 0 + + +def main(): + args = sys.argv[1:] + if not args: + controls() + probe_refusals() + check_text() + check_mutations() + elif len(args) == 2 and args[0] == 'binary': + check_binary(args[1]) + elif len(args) == 4 and args[0] == 'dispatch': + controls() + sys.exit(check_dispatch(*args[1:]) or (1 if failures else 0)) + elif len(args) == 5 and args[0] == 'control': + sys.exit(check_dispatch(*args[2:], control=args[1])) + else: + sys.exit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_const_copy_join_check.py b/tests/startup_gfx2hlsl_const_copy_join_check.py new file mode 100644 index 0000000000..8b41c836c7 --- /dev/null +++ b/tests/startup_gfx2hlsl_const_copy_join_check.py @@ -0,0 +1,96 @@ +"""`s_mov_b32` copy of a plain constant SGPR in tools/startup/gfx2hlsl.py: run-time write and join. + +The copy folds the constant into later reads (revision x2w-startup-shader-28), and these two cases pin what must +stay true next to the fold: +- the copy still assigns its register at run time (`s12 = ...;` is emitted), so a reader the fold does not reach + (a branch target after a join) sees a real value; +- at a join where one arm rewrites the copy at run time, the copy's constant is dropped, so a read after the join + uses the register and not the stale constant. + +The instruction words are built from the SOP1 / SOP2 / SOPC / SOPP field layout that `tools/disasm_rdna2.py` decodes. +""" +import os +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(op, sdst, ssrc0): + return struct.pack('<I', 0xBE800000 | ((sdst & 0x7F) << 16) | ((op & 0xFF) << 8) | (ssrc0 & 0xFF)) + + +def sop2(op, sdst, ssrc0, ssrc1): + return struct.pack('<I', (0b10 << 30) | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) + | (ssrc0 & 0xFF)) + + +def sopc(op, ssrc0, ssrc1): + return struct.pack('<I', 0xBF000000 | ((op & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF)) + + +def sopp(op, simm=0): + return struct.pack('<I', 0xBF800000 | ((op & 0x7F) << 16) | (simm & 0xFFFF)) + + +MOV, ADD, CMP_EQ, ENDPGM, CBRANCH_SCC0 = 0x03, 0x00, 0x06, 0x01, 0x04 +INLINE_1, INLINE_3, INLINE_5 = 129, 131, 133 +S4, S6, S12, S13, S15 = 4, 6, 12, 13, 15 +CONST_WORD = '0x00000005u' + + +class Pipeline: + """Just enough pipeline state for Stage.translate().""" + + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + +def blocks_of(code): + stage = G.Stage.__new__(G.Stage) + stage.pipe = Pipeline() + stage.kind = 'ps' + stage.lines, stage.sym = [], {} + stage.used_s, stage.used_v, stage.masks = set(), set(), set() + stage.attrs = {} + stage.exec_known = True + stage.ins = G.decode(code) + stage.force_joined = {} + stage.translate() + return {off: lines for off, lines, _ in stage.blocks} + + +COPY = [sop1(MOV, S15, INLINE_5), sop1(MOV, S12, S15)] # s15 = 5; s12 = s15 +READ = sop2(ADD, S13, S12, INLINE_1) # s13 = s12 + 1 + +# Straight line: the read folds the constant, and the copy is still written at run time. +straight = blocks_of(b''.join(COPY + [READ, sopp(ENDPGM)])) +text = '\n'.join(l for lines in straight.values() for l in lines) +check('straight line: the copy is still assigned at run time', 's12 = ' in text, text) +check('straight line: the read folds the copied constant', 's12 + ' not in text and CONST_WORD in text, text) + +# Skip: s_cmp_eq_u32 s4, 3; s_cbranch_scc0 JOIN; s_mov_b32 s12, s6 (run-time rewrite); JOIN: read. +join_at = 4 * (len(COPY) + 3) +skip = (COPY + [sopc(CMP_EQ, S4, INLINE_3), sopp(CBRANCH_SCC0, 1), sop1(MOV, S12, S6), READ, sopp(ENDPGM)]) +joined = blocks_of(b''.join(skip)) +after = '\n'.join(joined.get(join_at, [])) +check('join: a read after a run-time rewrite on one arm uses the register', 's12' in after, repr(joined)) +check('join: the stale constant is not folded into the read', CONST_WORD not in after, after) + +if failures: + print('FAIL: ' + ', '.join(failures)) + sys.exit(1) +print('startup_gfx2hlsl_const_copy_join_check: ok') diff --git a/tests/startup_gfx2hlsl_cselect_descnum_check.py b/tests/startup_gfx2hlsl_cselect_descnum_check.py new file mode 100644 index 0000000000..40cedf16c5 --- /dev/null +++ b/tests/startup_gfx2hlsl_cselect_descnum_check.py @@ -0,0 +1,363 @@ +"""s_cselect_b32 on descriptor-derived data in the compute stage of tools/startup/gfx2hlsl.py (#2618, C500 rows). + +usage: startup_gfx2hlsl_cselect_descnum_check.py [controls] + startup_gfx2hlsl_cselect_descnum_check.py dispatch <dxc> <offscreen_check> <warp|hardware> + +The C500 compute rows stop at `s_cselect_b32 sX, 0, sX` where sX holds a number computed from a buffer descriptor +(descnum). Such a select can zero a buffer's size, which disables the buffer, so a translation that drops the zero +arm would read real data where the console reads zeros. The select now records both arms and its own offset (the +SCC it read) as an opaque symbol, and every later use that would need its value refuses. + +The fixture is case A of startup_gfx2hlsl_compute_check.py (a descriptor table load s[12:19], a buffer load +through s[12:15], a buffer store through s[16:19]) with synthetic instructions spliced in. Their bytes come from +the RDNA 2 SOP1/SOP2/SOPC/VOP1/VOPC layouts, and the decoder must print the expected text for each. + +Checked (controls): +- accepted: the select with its result dead, in both arm orders, with a literal arm, and on an extracted stride; + the HLSL differs from case A only by the compare's scc line, and sX holds both arms and the select's offset; +- refused, each with its reason: numeric reads (v_mov, s_cmp, v_cmp, m0), scalar ALU on the result, the + structured-to-raw conversion with the selected stride, a copy into the load descriptor's word 1, 2 or 3 (also + through a second copy), a copy into the store descriptor, SCC from an ALU on descriptor data, a read after a + forward join or at a loop head that a path brings the select to, a load whose word 2 is joined after a select on + one path or on a loop back edge, and a select in the high word of a 64-bit ALU source (the same joins and loop + without the select translate); +- still refused as before: s_cselect_b64, m0 and vcc_lo destinations, a raw descriptor word, a pointer or run-time + register arm, and the vertex and pixel stages. +Negative controls, each a mutated translator that must fail a named check: +- zero-arm-dropped: the select keeps only its descnum arm, so the conversion with the selected stride translates; +- load-check-removed: Stage.select_word finds nothing, so a load through a copied select translates; +- alu-check-removed: Stage.refuse_select_source accepts everything, so an ALU copy into word 2 reaches the load; +- join-check-removed: Stage.joined_word finds nothing, so a load after a join with a select on one path translates; +- high-word-unchecked: refuse_select_source sees only the low word of each source, so s_or_b64 of a pair whose high + word holds the select translates. +The dispatch mode runs case A with the dead select on D3D12 and compares all 320 words with case A's reference. +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 +import startup_gfx2hlsl_scalar_m0_check as M # noqa: E402 + +ZERO, LIT = 128, 255 + + +def sop1(op, d, a): + return struct.pack('<I', 0xbe800000 | d << 16 | op << 8 | a) + + +def sop2(op, d, a, b, lit=None): + return struct.pack('<I', 0x80000000 | op << 23 | d << 16 | b << 8 | a) + (b'' if lit is None else struct.pack('<I', lit)) + + +def sopc(op, a, b): + return struct.pack('<I', 0xbf000000 | op << 16 | b << 8 | a) + + +def vop1(op, d, a): + return struct.pack('<I', 0x7e000000 | d << 17 | op << 9 | a) + + +def vopc(op, a, vb): + return struct.pack('<I', 0x7c000000 | op << 17 | vb << 9 | a) + + +MOV, ADD, CSEL, CSEL64, AND, LSHR = 0x03, 0x00, 0x0a, 0x0b, 0x0e, 0x20 +WORDS = { + 's_lshr_b32 s21, s14, 2': sop2(LSHR, 21, 14, 130), + 's_lshr_b32 s20, s14, 2': sop2(LSHR, 20, 14, 130), + 's_cmp_eq_u32 s4, 0': sopc(0x06, 4, ZERO), + 's_cmp_eq_u32 s21, 0': sopc(0x06, 21, ZERO), + 's_cselect_b32 s21, 0, s21': sop2(CSEL, 21, ZERO, 21), + 's_cselect_b32 s21, s21, 0': sop2(CSEL, 21, 21, ZERO), + 's_cselect_b32 s21, 0x100, s21': sop2(CSEL, 21, LIT, 21, 0x100), + 's_cselect_b32 s21, s4, s21': sop2(CSEL, 21, 4, 21), + 's_cselect_b32 s14, 0, s14': sop2(CSEL, 14, ZERO, 14), + 's_cselect_b32 s22, 0, s10': sop2(CSEL, 22, ZERO, 10), + 's_cselect_b32 m0, 0, s21': sop2(CSEL, 124, ZERO, 21), + 's_cselect_b32 vcc_lo, 0, s21': sop2(CSEL, 106, ZERO, 21), + 's_cselect_b64 s[22:23], 0, s[20:21]': sop2(CSEL64, 22, ZERO, 20), + 's_mov_b32 s13, s21': sop1(MOV, 13, 21), + 's_mov_b32 s14, s21': sop1(MOV, 14, 21), + 's_mov_b32 s15, s21': sop1(MOV, 15, 21), + 's_mov_b32 s18, s21': sop1(MOV, 18, 21), + 's_mov_b32 s22, s21': sop1(MOV, 22, 21), + 's_mov_b32 s14, s22': sop1(MOV, 14, 22), + 's_mov_b32 m0, s21': sop1(MOV, 124, 21), + 's_add_u32 s22, s21, 0': sop2(ADD, 22, 21, ZERO), + 's_add_u32 s22, s22, 1': sop2(ADD, 22, 22, 129), + 's_and_b32 s22, s15, 0x30000000': sop2(AND, 22, 15, LIT, 0x30000000), + 'v_mov_b32_e32 v5, s21': vop1(0x01, 5, 21), + 'v_mov_b32_e32 v5, m0': vop1(0x01, 5, 124), + 'v_cmp_gt_u32_e32 vcc_lo, s21, v0': vopc(0xc4, 21, 0), + 's_add_u32 s21, s4, 1': sop2(ADD, 21, 4, 129), + 's_add_u32 s21, s4, 2': sop2(ADD, 21, 4, 130), + 's_cmp_eq_u32 s5, 0': sopc(0x06, 5, ZERO), + 's_mov_b32 s22, 0': sop1(MOV, 22, ZERO), + 's_add_i32 s22, s22, 1': sop2(0x02, 22, 22, 129), + 's_cmp_lt_u32 s22, 3': sopc(0x0a, 22, 131), + 's_cbranch_scc1 1': struct.pack('<I', 0xbf850001), + 's_cbranch_scc1 3': struct.pack('<I', 0xbf850003), + 's_cbranch_scc1 65529': struct.pack('<I', 0xbf85fff9), # back 7 dwords + 's_cbranch_scc1 65528': struct.pack('<I', 0xbf85fff8), # back 8 dwords + 's_cbranch_scc1 2': struct.pack('<I', 0xbf850002), + 's_cselect_b32 s14, 0, s21': sop2(CSEL, 14, ZERO, 21), + 's_mov_b32 s14, s14': sop1(MOV, 14, 14), + 's_or_b64 s[14:15], s[20:21], 0': sop2(0x11, 14, 20, ZERO), + **{line: bytes.fromhex(C.SPLICE[line]) for line in C.RAW_CONVERSION}, +} +for _text, _code in WORDS.items(): + (_, _, _name, _decoded), = G.decode(_code) + if _name.startswith('s_cbranch'): # the decoder prints an absolute label; the key spells SIMM16 + _decoded = '%s %d' % (_name, struct.unpack('<I', _code)[0] & 0xffff) + assert _decoded == _text, (_text, _decoded) + +DESCNUM = 's_lshr_b32 s21, s14, 2' # a number from word 2 (NUM_RECORDS) of the load descriptor s[12:15] +COMPARE = 's_cmp_eq_u32 s4, 0' # SCC from a root constant: a run-time value +SELECT = 's_cselect_b32 s21, 0, s21' # the C500 form: zero or keep +SELECTED = (DESCNUM, COMPARE, SELECT) +STRIDE_EXTRACT, STRIDE_CLEAR, SCALE_RECORDS, OOB_CLEAR, OOB_RAW = C.RAW_CONVERSION # on the store descriptor s[16:19] +LOAD = C.WORDS_A.index(bytes.fromhex('001030e004050380')) # buffer_load_dword v5, v4, s[12:15], 0 offen +STORE = C.STORE_A # buffer_store_dword v5, v4, s[16:19], 0 offen +assert [t for _, _, _, t in G.decode(C.WORDS_A[LOAD:LOAD + 8])] == ['buffer_load_dword v5, v4, s[12:15], 0 offen'] + +failures = [] + + +def check(what, ok, detail=''): + print('%s %s%s' % ('ok ' if ok else 'FAIL', what, '' if ok or not detail else ': %s' % (detail,))) + if not ok: + failures.append(what) + + +def at(position, *lines): + return C.WORDS_A[:position] + b''.join(WORDS[line] for line in lines) + C.WORDS_A[position:] + + +def around_load(before, after): + """Case A with `before` spliced in front of its buffer load and `after` behind it.""" + return (C.WORDS_A[:LOAD] + b''.join(WORDS[line] for line in before) + C.WORDS_A[LOAD:LOAD + 8] + + b''.join(WORDS[line] for line in after) + C.WORDS_A[LOAD + 8:]) + + +def translate(code): + pipe = G.ComputePipeline(code, C.root_blob(), C.CASES['A'][2], (2, 3, 4)) + return pipe, pipe.hlsl_cs() + + +def accepted(what, code): + try: + result = translate(code) + except G.Unsupported as reason: + check(what, False, 'refused: %s' % reason) + return None, None + check(what, True) + return result + + +def refused(what, reason, code): + try: + translate(code) + except G.Unsupported as error: + check(what, reason in str(error), 'expected %r in %r' % (reason, str(error))) + return + check(what, False, 'translated, expected a refusal naming %r' % reason) + + +def offset(position, *lines): + """Byte offset of the instruction after `lines` spliced at `position`.""" + return position + sum(len(WORDS[line]) for line in lines) + + +def check_accepted(): + _, base = translate(C.WORDS_A) + for select, arms in ((SELECT, (('const', 0), ('descnum',))), ('s_cselect_b32 s21, s21, 0', (('descnum',), ('const', 0))), + ('s_cselect_b32 s21, 0x100, s21', (('const', 0x100), ('descnum',)))): + pipe, hlsl = accepted('dead %s translates' % select, at(STORE, DESCNUM, COMPARE, select)) + if pipe is None: + continue + extra = sorted(set(hlsl.splitlines()) - set(base.splitlines())) + check('%s adds only the compare to the HLSL' % select, + len(hlsl.splitlines()) == len(base.splitlines()) + 1 and len(extra) == 1 and extra[0].strip().startswith('scc = '), + extra) + want = ('descnum', 'cselect', offset(STORE, DESCNUM, COMPARE)) + arms + check('%s keeps both arms and its offset' % select, pipe.cs.sym.get(21) == want, (pipe.cs.sym.get(21), want)) + # The extracted stride of the structured-to-raw conversion is a descnum too; the select keeps its symbol as an arm. + pipe, _ = accepted('dead select of the extracted stride translates', + at(STORE, STRIDE_EXTRACT, COMPARE, SELECT)) + if pipe is not None: + sym = pipe.cs.sym.get(21) + check('the stride arm is kept whole', G.descriptor_select(sym) and sym[3] == ('const', 0) + and sym[4][:2] == ('descnum', 'stride') and sym[4][2][0] == 'desc' and sym[4][2][3] == 5, sym) + + +def check_later_uses(): + numeric = 'numeric use of s21 holding descnum' + refused('v_mov_b32 of the result', numeric, at(STORE, *SELECTED, 'v_mov_b32_e32 v5, s21')) + refused('s_cmp_eq_u32 on the result', numeric, at(STORE, *SELECTED, 's_cmp_eq_u32 s21, 0')) + refused('v_cmp_gt_u32 on the result', numeric, at(STORE, *SELECTED, 'v_cmp_gt_u32_e32 vcc_lo, s21, v0')) + refused('the result through m0', 'numeric use of m0 holding descnum', + at(STORE, *SELECTED, 's_mov_b32 m0, s21', 'v_mov_b32_e32 v5, m0')) + refused('scalar ALU on the result', 's_add_u32 on a select of descriptor data', + at(STORE, *SELECTED, 's_add_u32 s22, s21, 0')) + refused('scalar ALU on a copy of the result', 's_add_u32 on a select of descriptor data', + at(STORE, *SELECTED, 's_mov_b32 s22, s21', 's_add_u32 s22, s22, 1')) + # The structured-to-raw conversion scales NUM_RECORDS by the stride; with the selected stride it would scale by 0 + # on one arm. Without the select this conversion translates (case I-raw of the compute check). + refused('raw conversion with the selected stride', 's_mul_i32 on a select of descriptor data', + at(STORE, STRIDE_EXTRACT, COMPARE, SELECT, STRIDE_CLEAR, SCALE_RECORDS, OOB_CLEAR, OOB_RAW)) + for word in (13, 14, 15): + refused('load through a select copied into s%d' % word, 'descriptor operand s[12:15]: s%d holds a select' % word, + at(LOAD, *SELECTED, 's_mov_b32 s%d, s21' % word)) + refused('load through a second copy of the select', 'descriptor operand s[12:15]: s14 holds a select', + at(LOAD, *SELECTED, 's_mov_b32 s22, s21', 's_mov_b32 s14, s22')) + refused('an ALU copy into word 2 before the load', 's_add_u32 on a select of descriptor data', + at(LOAD, *SELECTED, 's_add_u32 s22, s21, 0', 's_mov_b32 s14, s22')) + refused('store through a select copied into word 2', 'buffer store through a modified descriptor', + at(STORE, *SELECTED, 's_mov_b32 s18, s21')) + # SCC from an ALU on descriptor data is not emitted, so the select's condition is unknown. + refused('select on SCC from descriptor data', 'scc from descriptor data in s_cselect_b32', + at(STORE, DESCNUM, 's_and_b32 s22, s15, 0x30000000', SELECT)) + # The select writes no HLSL variable, so a join must not turn sX back into a run-time register. Forward: one path + # skips the select and brings a run-time s21. The same shape with a run-time write in the skipped block translates. + entry = ('s_add_u32 s21, s4, 1', 's_cmp_eq_u32 s5, 0') + refused('read after a join with a skipped select', 'numeric use of s21 holding joined at a branch target', + at(STORE, *entry, 's_cbranch_scc1 3', *SELECTED, 'v_mov_b32_e32 v5, s21')) + accepted('the same join with a run-time write translates', + at(STORE, *entry, 's_cbranch_scc1 1', 's_add_u32 s21, s4, 2', 'v_mov_b32_e32 v5, s21')) + # Back edge: the loop head reads s21, which is run-time on entry and the select on the next pass. + loop = ('v_mov_b32_e32 v5, s21', *SELECTED, 's_add_i32 s22, s22, 1', 's_cmp_lt_u32 s22, 3', 's_cbranch_scc1 65529') + code = at(STORE, 's_add_u32 s21, s4, 1', 's_mov_b32 s22, 0', *loop) + head = offset(STORE, 's_add_u32 s21, s4, 1', 's_mov_b32 s22, 0') + assert 's_cbranch_scc1 label_0x%x' % head in [t for _, _, _, t in G.decode(code)], 'the back edge misses the head' + refused('read at a loop head after a select on the back edge', 'numeric use of s21 holding joined at a branch target', + code) + # A select that reaches a descriptor word through a join leaves that word joined. The access names its resource by + # word 0 only, so a joined word after it refuses (#2903 review, case 1). The same join with the loaded word on + # both paths keeps the word and translates. + split = (DESCNUM, 's_cmp_eq_u32 s5, 0', 's_cbranch_scc1 2', COMPARE) + refused('load after a join where one path selects into word 2', 'descriptor operand s[12:15]: s14 holds a word joined', + at(LOAD, *split, 's_cselect_b32 s14, 0, s21')) + accepted('the same join with the loaded word on both paths translates', at(LOAD, *split, 's_mov_b32 s14, s14')) + # The same through a loop back edge: the select into word 2 at the bottom reaches the load at the head. + tail = ('s_add_i32 s22, s22, 1', 's_cmp_lt_u32 s22, 3') + code = around_load(['s_mov_b32 s22, 0'], [DESCNUM, COMPARE, 's_cselect_b32 s14, 0, s21', *tail, 's_cbranch_scc1 65528']) + assert 's_cbranch_scc1 label_0x%x' % (LOAD + 4) in [t for _, _, _, t in G.decode(code)], 'the back edge misses the load' + refused('load at a loop head after a select into word 2 on the back edge', + 'descriptor operand s[12:15]: s14 holds a word joined', code) + code = around_load(['s_mov_b32 s22, 0'], [DESCNUM, COMPARE, *tail, 's_cbranch_scc1 65529']) + assert 's_cbranch_scc1 label_0x%x' % (LOAD + 4) in [t for _, _, _, t in G.decode(code)], 'the back edge misses the load' + accepted('the same loop without the select translates', code) + # A select in the high word of a 64-bit source (#2903 review, case 2): scalar() names the low word only. + refused('select in the high word of a 64-bit ALU source', 's_or_b64 on a select of descriptor data', + at(LOAD, 's_lshr_b32 s20, s14, 2', *SELECTED, 's_or_b64 s[14:15], s[20:21], 0')) + + +def check_still_refused(): + refused('s_cselect_b64 on descnum', 'numeric use of s20 holding descnum', + at(STORE, 's_lshr_b32 s20, s14, 2', COMPARE, 's_cselect_b64 s[22:23], 0, s[20:21]')) + refused('m0 destination', 'numeric use of s21 holding descnum', at(STORE, DESCNUM, COMPARE, 's_cselect_b32 m0, 0, s21')) + refused('vcc_lo destination', 'numeric use of s21 holding descnum', + at(STORE, DESCNUM, COMPARE, 's_cselect_b32 vcc_lo, 0, s21')) + refused('raw descriptor word arm', 'numeric use of s14 holding desc', at(STORE, COMPARE, 's_cselect_b32 s14, 0, s14')) + refused('pointer arm', 'numeric use of s10 holding ptr', at(STORE, COMPARE, 's_cselect_b32 s22, 0, s10')) + refused('run-time register arm', 'numeric use of s21 holding descnum', + at(STORE, DESCNUM, COMPARE, 's_cselect_b32 s21, s4, s21')) + # Vertex and pixel stages keep the refusal: the probe stage holds a descriptor in s[16:19]. + for kind in ('vs', 'ps'): + stage = M.ProbeStage() + stage.kind = kind + stage.one('s_add_u32', 's_add_u32 s20, s16, 4') + try: + stage.one('s_cselect_b32', 's_cselect_b32 s20, 0, s20') + except G.Unsupported as error: + check('%s stage keeps the refusal' % kind, 'numeric use of s20 holding descnum' in str(error), str(error)) + else: + check('%s stage keeps the refusal' % kind, False, 'translated') + + +def check_all(): + check_accepted() + check_later_uses() + check_still_refused() + + +def zero_arm_dropped(original): + def select(self, ops, pair): + d, r = G.reg_range(ops[0]), G.reg_range(ops[2]) + sym = self.sym.get(r[1]) if r and r[0] == 's' else None + if not pair and d and d[0] == 's' and sym and sym[0] == 'descnum' and ops[1] == '0': + self.sym[d[1]] = sym # the careless lift: the zero arm is gone + return + original(self, ops, pair) + return select + + +def low_words_only(original): + def refuse(self, base, srcs): # the check before the #2903 review: the low register of each source only + return original(self, base, ['s%d' % G.reg_range(t)[1] if G.reg_range(t) and G.reg_range(t)[0] == 's' else t + for t in srcs]) + return refuse + + +MUTATIONS = { + 'zero-arm-dropped': ('scalar_select', zero_arm_dropped, 'raw conversion with the selected stride'), + 'load-check-removed': ('select_word', lambda original: lambda self, tok: None, 'load through a select copied into s14'), + 'alu-check-removed': ('refuse_select_source', lambda original: lambda self, base, srcs: None, + 'an ALU copy into word 2 before the load'), + 'join-check-removed': ('joined_word', lambda original: lambda self, tok: None, + 'load after a join where one path selects into word 2'), + 'high-word-unchecked': ('refuse_select_source', low_words_only, 'select in the high word of a 64-bit ALU source'), +} + + +def check_mutations(): + global failures + for name, (method, mutate, expected) in MUTATIONS.items(): + original = getattr(G.Stage, method) + setattr(G.Stage, method, mutate(original)) + kept, failures = failures, [] + try: + print('-- control %s (the check must fail)' % name) + check_all() + finally: + setattr(G.Stage, method, original) + caught, failures = failures, kept + check('control %s fails "%s"' % (name, expected), expected in caught, caught) + + +def check_dispatch(dxc, runner, adapter): + """Case A with the dead select, on D3D12: every word must match case A's reference.""" + C.CASES['A-cselect'] = (C.SOURCE_A, at(STORE, *SELECTED), *C.CASES['A'][2:]) + reference = C.expected + C.expected = lambda name: reference('A' if name == 'A-cselect' else name) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + run = C.run_case('A-cselect', dxc, str(Path(runner).resolve()), adapter, Path(tmp)) + print(run.stdout, end='') + if run.returncode == 77: + return 77 + diagnostics = C.renderer_diagnostics(run.stderr, adapter) + if run.returncode or diagnostics: + print('case A-cselect: %s' % (run.stderr or 'exit %d' % run.returncode), file=sys.stderr) + return 1 + print('case A-cselect: all %d words match' % C.WORDS) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 1 or sys.argv[1:] == ['controls']: + check_all() + check_mutations() + print('%d failure(s)' % len(failures)) + sys.exit(1 if failures else 0) + if len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + sys.exit(check_dispatch(*sys.argv[2:])) + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_desc_ptr_prop_check.py b/tests/startup_gfx2hlsl_desc_ptr_prop_check.py new file mode 100644 index 0000000000..96b082b725 --- /dev/null +++ b/tests/startup_gfx2hlsl_desc_ptr_prop_check.py @@ -0,0 +1,225 @@ +"""Check descriptor pointer propagation through s_add_u32 / s_addc_u32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_desc_ptr_prop_check.py + +A shader advances a descriptor table or root pointer with `s_add_u32 sD, sP, <literal>` and +`s_addc_u32 sD+1, sP+1, 0`, into the same or another register pair, then loads descriptors through +the result. The load must read at the advanced byte offset. A non-literal addend must be refused, +never silently treated as the unchanged pointer. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + sampler_heap = False + + def __init__(self): + self.keys = [] + self.modified = set() + + def ud(self, key): + return 'ud_%s' % '_'.join(map(str, key)) + + def resource(self, key, kind): + if (key, kind) not in self.keys: + self.keys.append((key, kind)) + return 'r%d' % self.keys.index((key, kind)) + + +def stage(symbols): + s = G.Stage.__new__(G.Stage) + s.pipe, s.sym, s.lines = Pipe(), dict(symbols), [] + s.used_s, s.used_v, s.uniform_v, s.exec_known = set(), set(), set(), True + s.masks, s.varying_s = set(), set() + s.scc_uniform = True + return s + + +def run(symbols, program, branches=False): + """Symbols after the (op, operands) steps, or the Unsupported message.""" + s = stage(symbols) + s.has_branches = branches + s.ins = [(4 * i, 4, op, '') for i, (op, _operands) in enumerate(program)] + try: + for i, (op, operands) in enumerate(program): + s.pc = 4 * i + if op == 's_load_dwordx4': + s.op_s_load_dwordx4(operands.split(', '), []) + else: + s.lower(op, '%s %s' % (op, operands), operands.split(', '), []) + except G.Unsupported as error: + return 'refused: %s' % error + return s + + +TABLE = {8: ('ptr', ('table', 0))} # a table pointer is 32 bits wide: no high word +ROOT = {8: ('ptr', ('root', 1)), 9: ('ptrhi', ('root', 1))} +ADVANCE = [('s_add_u32', 's20, s8, 0x40'), ('s_addc_u32', 's21, s9, 0')] +TABLE_ADVANCE = [('s_add_u32', 's20, s8, 0x40')] +LOAD = [('s_load_dwordx4', 's[4:7], s[20:21], 0x10')] + +s = run(TABLE, TABLE_ADVANCE + LOAD) +check('table pointer advanced into another pair, descriptor read at pointer + 0x40 + 0x10', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s if isinstance(s, str) else s.sym)) + +same = [('s_add_u32', 's8, s8, 0x20')] +s = run(TABLE, same + [('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('table pointer advanced in place', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x20, 0), str(s if isinstance(s, str) else s.sym)) + +twice = [('s_add_u32', 's20, s8, 0x40'), ('s_add_u32', 's22, s20, 0x10')] +s = run(TABLE, twice + [('s_load_dwordx4', 's[4:7], s[22:23], 0x4')]) +check('two advances add up', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x54, 0), str(s if isinstance(s, str) else s.sym)) + +s = run(ROOT, ADVANCE + LOAD) +check('root constant-buffer pointer advanced, buffer read at the advanced offset', + not isinstance(s, str) and any('Load(80)' in line for line in s.lines), str(s if isinstance(s, str) else s.lines)) + +s = run(TABLE, [('s_add_u32', 's8, s8, s2')]) +check('a register addend on a pointer is refused', isinstance(s, str) and 'non-literal' in s, str(s)) + +s = run(ROOT, ADVANCE + [('s_load_dwordx4', 's[4:7], s[20:21], s2')]) +check('a register offset through an advanced pointer is still refused', isinstance(s, str), str(s)) + +# The untracked-offset mark of a branchy program must be refused here too, never a TypeError. +s = stage({8: ('ptr', ('root', 1), 'added'), 9: ('ptrhi', ('root', 1))}) +try: + s.descriptor('s[8:9]') + check('an untracked-offset pointer used whole as a descriptor is refused', False, 'accepted') +except G.Unsupported: + check('an untracked-offset pointer used whole as a descriptor is refused', True) + +s = run(ROOT, ADVANCE) +try: + s.descriptor('s[20:21]') + check('an advanced pointer used whole as a descriptor is refused', False, 'accepted') +except G.Unsupported: + check('an advanced pointer used whole as a descriptor is refused', True) + +s = run(ROOT, ADVANCE, branches=True) +check('a pointer advance in a program with branches is refused', isinstance(s, str), str(s)) + +# The high-word add is the carry of the low-word add right before it, never of an unrelated carry in SCC. +s = run(ROOT, [('s_cmp_eq_u32', '0, 0'), ('s_addc_u32', 's9, s9, 0')]) +check('s_addc_u32 without the low-word add is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [ADVANCE[0], ('s_cmp_eq_u32', '0, 0'), ADVANCE[1]]) +check('s_addc_u32 separated from its low-word add is refused', isinstance(s, str), str(s)) + +# A fold needs the complete matching pair: the load must not trust the low word alone. +LOW = ADVANCE[0] +s = run(ROOT, [LOW] + LOAD) +check('missing high-word add is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('missing high-word add in place is refused', isinstance(s, str), str(s)) + +s = run(ROOT, ADVANCE + [('s_mov_b32', 's21, 0')] + LOAD) +check('overwritten high word is refused', isinstance(s, str), str(s)) + +mixed = dict(ROOT) +mixed[10], mixed[11] = ('ptr', ('root', 2)), ('ptrhi', ('root', 2)) +s = run(mixed, [LOW, ('s_addc_u32', 's21, s11, 0')] + LOAD) +check('high word from another pointer is refused', isinstance(s, str), str(s)) + +s = run(mixed, [LOW, ('s_addc_u32', 's21, s10, 0')] + LOAD) +check('high word from a different register pair is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [('s_add_u32', 's20, s8, 0xfffff'), ('s_addc_u32', 's21, s9, 0')] + LOAD) +check('complete pair with a large low-word add is folded', + not isinstance(s, str) and any('Load(%d)' % (0xfffff + 0x10) in line for line in s.lines), str(s)) + +# The high word is bound to the accumulated offset: the original word never stands in for an advanced one. +s = run(ROOT, ADVANCE + [('s_mov_b32', 's21, s9')] + LOAD) +check('completed high word overwritten by the original one is refused', isinstance(s, str), str(s)) + +SECOND = [('s_add_u32', 's22, s20, 0x20')] +s = run(ROOT, ADVANCE + SECOND + [('s_addc_u32', 's23, s9, 0'), ('s_load_dwordx4', 's[4:7], s[22:23], 0x10')]) +check('second advance with the original high word is refused', isinstance(s, str), str(s)) + +s = run(ROOT, ADVANCE + SECOND + [('s_addc_u32', 's23, s21, 0'), ('s_load_dwordx4', 's[4:7], s[22:23], 0x10')]) +check('second advance with the completed high word of the first pair is folded', + not isinstance(s, str) and any('Load(%d)' % (0x40 + 0x20 + 0x10) in line for line in s.lines), str(s)) + +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_addc_u32', 's9, s9, 0'), ('s_add_u32', 's8, s8, 0x20'), + ('s_addc_u32', 's9, s9, 0'), ('s_load_dwordx4', 's[4:7], s[8:9], 0')]) +check('in-place advance twice with each completed high word is folded', + not isinstance(s, str) and any('Load(64)' in line for line in s.lines), str(s)) + +# Real entry state: a table pointer is one 32-bit register with no high word, so it advances with +# the low add alone and its neighbour register stays untouched. +def entry(params, kind='vs'): + s = stage({}) + s.kind, s.pipe.root = kind, {'params': params, 'flags': 0} + s.setup_entry() + return s.sym + + +REAL = entry([{'type': 0}, {'type': 2}]) +s = run(REAL, [('s_add_u32', 's20, s8, 0x40')] + LOAD) +check('real table pointer advanced by the low add alone, descriptor read at +0x50', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s)) + +s = run(REAL, [('s_add_u32', 's8, s8, 0x40'), ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')]) +check('real table pointer advanced in place keeps the next register symbol', + not isinstance(s, str) and s.sym.get(9) == REAL[9] and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s)) + +s = run(REAL, [('s_add_u32', 's20, s9, 0x40'), ('s_addc_u32', 's21, s10, 0')] + LOAD) +check('real root pointer pair advanced through the load', + not isinstance(s, str) and any('Load(80)' in line for line in s.lines), str(s)) + +s = run(REAL, [('s_add_u32', 's20, s9, 0x40')] + LOAD) +check('real root pointer without its high add is refused', isinstance(s, str), str(s)) + +copied = dict(ROOT) +copied[30] = ('ptrhi', ('root', 1)) +s = run(copied, [LOW, ('s_addc_u32', 's21, s30, 0')] + LOAD) +check('a copied high word completes the pair', not isinstance(s, str), str(s)) + +viam0 = dict(ROOT) +viam0['m0'] = ('ptr', ('root', 1)) +s = run(viam0, [('s_add_u32', 's20, m0, 0x40'), ('s_addc_u32', 's21, s9, 0')] + LOAD) +check('a low word held in m0 completes the pair', not isinstance(s, str), str(s)) + +# A program with branches does not track the added offset: the load through the advanced pointer is a refusal +# (never a crash), and the same straight-line shape keeps folding. +IN_PLACE = [('s_add_u32', 's8, s8, 0x40'), ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')] +s = run(TABLE, IN_PLACE, branches=True) +check('in-place pointer advance then load in a program with branches is refused, not a crash', + isinstance(s, str) and 'untracked offset' in s, str(s)) + +s = run(TABLE, IN_PLACE) +check('the same in-place advance without branches still folds to +0x50', + not isinstance(s, str) and s.sym.get(4) == ('desc', ('table', 0), 0x50, 0), str(s if isinstance(s, str) else s.sym)) + +# The pair is complete only after its s_addc_u32: an in-place pair folds, and a high word that was only +# copied (never advanced) must not stand in for it. +s = run(ROOT, [('s_add_u32', 's8, s8, 0x20'), ('s_addc_u32', 's9, s9, 0'), + ('s_load_dwordx4', 's[4:7], s[8:9], 0x10')]) +check('complete in-place pair folds to +0x30', + not isinstance(s, str) and any('Load(%d)' % 0x30 in line for line in s.lines), str(s if isinstance(s, str) else s.lines)) + +s = run(ROOT, [ADVANCE[0], ('s_mov_b32', 's21, s9')] + LOAD) +check('out-of-place low add with a copied, unadvanced high word is refused', isinstance(s, str), str(s)) + +s = run(ROOT, [ADVANCE[0], ADVANCE[1]] + LOAD) +check('complete out-of-place pair leaves the original high source untouched', + not isinstance(s, str) and s.sym.get(9) == ('ptrhi', ('root', 1)), str(s if isinstance(s, str) else s.sym)) + +if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) +print('startup_gfx2hlsl_desc_ptr_prop: ok') diff --git a/tests/startup_gfx2hlsl_desc_vcc_check.py b/tests/startup_gfx2hlsl_desc_vcc_check.py new file mode 100644 index 0000000000..ca1601f901 --- /dev/null +++ b/tests/startup_gfx2hlsl_desc_vcc_check.py @@ -0,0 +1,148 @@ +"""Check descriptor words moved into vcc, with optional WARP/hardware pixel readback. + +usage: startup_gfx2hlsl_desc_vcc_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]] +""" +import struct +import sys +import tempfile +from pathlib import Path + +from startup_gfx2hlsl_sload_s104_check import ( + G, TABLE_ROOT, compile_hlsl, draw, translate, vs_words, words_text, +) +from startup_gfx2hlsl_bit_alu_check import POST_WORDS + + +LOAD = 's_load_dwordx4 s[40:43], s[4:5], 0x20' +LOW = 's_mov_b64 s[104:105], s[40:41]' +COPY = 's_mov_b64 vcc, s[42:43]' +CLOBBER = 's_buffer_load_dwordx4 s[40:43], s[40:43], 0x10' +FETCH = 's_buffer_load_dwordx4 s[12:15], s[104:107], 0' +DIRECT = 's_buffer_load_dwordx4 s[12:15], s[40:43], 0' +END = 's_endpgm' +MASK_READ = 'vcc read after a descriptor load into s106/s107' + + +def refuse(message, *instructions): + try: + translate(*instructions, END) + except G.Unsupported as error: + assert message in str(error), (instructions, error) + else: + raise AssertionError(('accepted', instructions)) + + +def smem(op, dst, base, offset): + return (0xf4000000 | op << 18 | dst << 6 | base // 2, 0xfa000000 | offset) + + +def mov64(dst, src): + return 0xbe800400 | dst << 16 | src + + +def pixel_words(alias): + # s_load x4 into s[40:43] from the root table at s[8:9], then wait for the descriptor. + words = [*smem(2, 40, 8, 0x20), 0xbf8c0000] + if alias: + words += [mov64(104, 40), mov64(106, 42), *smem(10, 40, 40, 0x10), 0xbf8c0000] + words += [*smem(10, 12, 104 if alias else 40, 0), 0xbf8c0000] + # v_mov_b32_e32 v12..v15 from s12..s15, then export the four words. + words += [0x7e000200 | reg << 17 | reg for reg in range(12, 16)] + return struct.pack('<%dI' % len(words), *words) + POST_WORDS + + +def main(): + stage = translate(LOAD, LOW, COPY, CLOBBER, FETCH, END) + # Manual mutant: dropping the symbol copy must fail the positive alias or this symbol check. + assert stage.sym[106] == ('desc', ('table', 0), 0x20, 2) + assert stage.sym[107] == ('desc', ('table', 0), 0x20, 3) + assert all(stage.sym[i] == ('fixed_buffer_word',) for i in range(40, 44)) + assert stage.blocks[0][1][-4:] == translate(LOAD, DIRECT, END).blocks[0][1][-4:] + assert not any('vcc =' in line for _, lines, _ in stage.blocks for line in lines) + decoded = [asm for _, _, _, asm in G.decode(pixel_words(True))] + assert COPY in decoded and LOW in decoded, decoded + + # Manual mutant: dropping the vcc_lost marking must fail the straight-line mask refusals. + for read in ( + 'v_cndmask_b32_e32 v0, 0, 1', + 'v_add_co_ci_u32_e32 v0, vcc_lo, 0, 1, vcc_lo', + 'v_sub_co_ci_u32_e64 v0, vcc_lo, 0, 1, vcc_lo', + 'v_subrev_co_ci_u32_e64 v0, vcc_lo, 0, 1, vcc_lo', + 'v_div_fmas_f32_e64 v0, v1, v2, v3', + 'v_cmp_eq_u32_e64 s20, vcc_lo, v1', + 'v_cmp_eq_u32_e32 vcc, v1', + 'v_cmp_eq_u32_sdwa s20, vcc_hi, v1 src0_sel:DWORD src1_sel:DWORD', + 'v_add_u32_e64 v0, vcc, v1', + 's_and_saveexec_b64 s[20:21], vcc', + 's_mov_b32 s20, vcc_lo', + ): + refuse(MASK_READ, LOAD, COPY, read) + for branch in ('s_cbranch_vccz', 's_cbranch_vccnz'): + refuse(MASK_READ, LOAD, COPY, branch + ' label_000C') + compare = 'v_cmp_eq_u32_e32 0, v1' + select = 'v_cndmask_b32_e32 v0, 0, 1' + translate(LOAD, COPY, compare, select, END) + refuse(MASK_READ, LOAD, COPY, 's_cbranch_scc0 label_0010', compare, select) + refuse(MASK_READ, LOAD, COPY, 's_cbranch_scc0 label_000C', 'v_div_fmas_f32_e64 v0, v1, v2, v3') + refuse('overlaps a redefined vcc', LOAD, LOW, COPY, compare, FETCH) + refuse('without a matching load on every path', + LOAD, LOW, 's_cbranch_scc0 label_0010', COPY, FETCH) + + for operation in ( + 's_mov_b64 exec, s[42:43]', + 's_mov_b32 vcc_lo, s42', + 's_and_b64 vcc, s[42:43], -1', + 's_mov_b64 vcc, s[41:42]', + ): + refuse('mask from descriptor data', LOAD, operation) + refuse('even pair of descriptor words', LOAD, 's_mov_b32 s43, 0', COPY) + refuse('even pair of descriptor words', LOAD, 's_mov_b32 s42, 0', COPY) + + # Manual mutant: skipping the consistency check must accept these malformed descriptors. + message = 'needs four consecutive words of the same descriptor' + refuse(message, LOAD, 's_load_dwordx4 s[48:51], s[4:5], 0x30', + 's_mov_b64 s[104:105], s[48:49]', COPY, FETCH) + refuse(message, LOAD, LOW, 's_mov_b32 s105, s40', COPY, FETCH) + overlapping_load = 's_load_dwordx4 s[104:107], s[4:5], 0x20' + translate(overlapping_load, FETCH, END) + refuse(message, overlapping_load, 's_mov_b32 s105, 0', FETCH) + print('ok') + + +def check_draw(dxc, renderer, adapter, fxc=None): + main() + compilers = ([('fxc', fxc, '5_1')] if fxc else []) + [('dxc', dxc, '6_0')] + vs_code = vs_words([(0, 0, 0)] * 4) + payload = [0x3f100000, 0x3f200000, 0x3f300000, 0x3f400000] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for alias in (False, True): + pipe = G.Pipeline(vs_code, pixel_words(alias), TABLE_ROOT) + source = pipe.hlsl_ps() + assert set(pipe.resources) == {(('table', 0), 0x20)}, pipe.resources + assert source.count('ByteAddressBuffer r0 : register(t0);') == 1 + assert source.count('r0.Load(') == (8 if alias else 4) + # The flat-param runner only binds b0. Supply the test SRV's bytes in HLSL while + # keeping the translated load addresses, scalar assignments and export in the draw. + fixture = ('uint fixture_load(uint address) {\n' + ' const uint words[8] = {%s, 0u, 0u, 0u, 0u};\n' + ' return words[address >> 2];\n' + '}' % ', '.join('0x%08xu' % word for word in payload)) + source = source.replace('ByteAddressBuffer r0 : register(t0);', fixture) + source = source.replace('r0.Load(', 'fixture_load(') + for kind, compiler, profile in compilers: + vs = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%d' % (kind, alias), + 'vs_' + profile, directory) + ps = compile_hlsl(compiler, kind, source, 'ps_%s_%d' % (kind, alias), + 'ps_' + profile, directory) + result = draw(renderer, adapter, vs, ps, words_text(payload)) + assert result.returncode == 0, (kind, alias, result.stdout, result.stderr) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + main() + elif sys.argv[1] == 'draw': + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py index db9e81b77f..9c726fc014 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py @@ -1,4 +1,4 @@ -"""DPP16 quad broadcasts (quad_perm:[k,k,k,k]) in tools/startup/gfx2hlsl.py (#2125 item A). +"""DPP16 quad broadcasts (quad_perm:[k,k,k,k]) in tools/startup/gfx2hlsl.py (#2125 item A; M200-01/003). (no arguments) translation controls and refusals, pure Python binary <llvm-mc> assemble the pixel fixtures with llvm-mc (gfx1013) and compare the words @@ -19,12 +19,15 @@ second source is a plain VGPR, so a permuted second source or a lane-0 read through the add would differ float: the coarse derivative idiom, v_sub_f32_dpp (lane 1 minus own lane), and v_mul_f32_dpp with a negated permuted source (the modifier applies to the word the lane read) + loop: the integer broadcasts, then a uniform scalar loop (two trips) that does not touch EXEC; the exported + words match the integer reference. A later loop used to refuse the entry-prefix broadcasts (M200-01/003). Two mutated translations, one that reads lane k + 1 and one that reads the lane's own word, must fail the draw against the reference and match their own plain-Python image. Refused (the single-lane model cannot read a neighbour, or the quad may be partly off): swaps, pair broadcasts, row -shifts, mirrors, DPP8, a partial row_mask or bank_mask, fi:1 without the whole-quad proof, bound_ctrl:0, a scalar or constant source, a vertex -stage, a pixel stage after EXEC changed or with branches, and operations outside the VOP1/VOP2 tables. +shifts, mirrors, DPP8, a partial row_mask or bank_mask, fi:1 without the whole-quad proof, bound_ctrl:0, a scalar or +constant source, a vertex stage, a broadcast after a branch target, after EXEC changed, or with divergent EXEC before +the broadcast, and operations outside the VOP1/VOP2 tables. """ import re import struct @@ -98,9 +101,25 @@ def vop1(op, vdst, src0): """ % {'m': DPP} FLOAT_WORDS = (WQM + vop1(6, 5, 0) + dpp16(True, 0x4, 6, 5, 5, (1, 1, 1, 1), True) + dpp16(True, 0x8, 7, 5, 5, (0, 0, 0, 0), True, neg0=True) + export((6, 7, 5, 5))) +# Uniform scalar loop after the integer broadcasts (two trips); EXEC and the exported words are unchanged. +# s_mov_b32 s0, 0; s_add_u32 s0, s0, 1; s_cmp_lt_u32 s0, 2; s_cbranch_scc1 back to the add. +def sopp(op, simm): + return struct.pack('<I', (simm & 0xffff) | op << 16 | 0x17f << 23) + + +LOOP_BODY = bytes.fromhex('00ff008001000000') + bytes.fromhex('00820abf') # add + cmp (3 dwords) +EXPORT_TAIL = export((1, 2, 3, 4)) # exp + s_endpgm +LOOP_WORDS = (INT_WORDS[:-len(EXPORT_TAIL)] + bytes.fromhex('800380be') + LOOP_BODY + + sopp(5, -len(LOOP_BODY) // 4 - 1) + EXPORT_TAIL) +# Branch target before the first broadcast: still refused (no longer the entry prefix). +AFTER_BRANCH_WORDS = WQM + sopp(4, 0) + INT_WORDS[len(WQM):] +# The same loop targeting offset zero would execute the broadcast again. +ENTRY_BACKEDGE_PREFIX = LOOP_WORDS[:-len(EXPORT_TAIL) - 4] +ENTRY_BACKEDGE_WORDS = ENTRY_BACKEDGE_PREFIX + sopp(5, -len(ENTRY_BACKEDGE_PREFIX) // 4 - 1) + EXPORT_TAIL +# Divergent EXEC before the broadcast: clear exec_lo after WQM so the whole-quad proof is gone. +DIVERGENT_WORDS = WQM + bytes.fromhex('8003febe') + INT_WORDS[len(WQM):] # s_mov_b32 exec_lo, 0 NO_WQM_WORDS = INT_WORDS[len(WQM):] # the entry EXEC may leave out lanes of a partly covered quad OTHER_WQM_WORDS = struct.pack('<I', 0xBE800000 | 2 << 16 | 0x0a << 8) + NO_WQM_WORDS # s_wqm_b64 s[2:3], s[0:1] -FIXTURES = {'integer': (INT_SOURCE, INT_WORDS), 'float': (FLOAT_SOURCE, FLOAT_WORDS)} MUTATIONS = ('wrong lane', 'own lane') @@ -130,7 +149,8 @@ def image(kind, how='reference'): for y in range(HEIGHT): for x in range(WIDTH): own = x | y << 16 - if kind == 'integer': + if kind in ('integer', 'loop'): + # The loop fixture keeps the same four exported words; the scalar trips do not touch them. q0 = read(x, y, 0, how) words += [q0, read(x, y, 1, how), read(x, y, 2, how), (read(x, y, 3, how) + q0) & MASK] else: @@ -154,7 +174,8 @@ def pixel_hlsl(kind, how='reference'): text, count = re.subn(r'QuadReadLaneAt\((v\d+), [0-3]u\)', r'\1', text) else: return text - assert count == (4 if kind == 'integer' else 2), (kind, how, count) + want = 2 if kind == 'float' else 4 + assert count == want, (kind, how, count) return text @@ -185,6 +206,19 @@ def refused_in_stage(words): return False +def fixtures(): + """Build FIXTURES after LOOP_WORDS so the loop decode supplies the source lines.""" + loop_source = '\n'.join(asm for _o, _s, _n, asm in G.decode(LOOP_WORDS)) + '\n' + return { + 'integer': (INT_SOURCE, INT_WORDS), + 'float': (FLOAT_SOURCE, FLOAT_WORDS), + 'loop': (loop_source, LOOP_WORDS), + } + + +FIXTURES = fixtures() + + def controls(): for kind, (source, words) in FIXTURES.items(): decoded = [asm for _o, _s, _n, asm in G.decode(words)] @@ -192,7 +226,8 @@ def controls(): stage = pixel_stage(words) text = stage.hlsl_ps() reads = re.findall(r'v256 = QuadReadLaneAt\((v\d+), ([0-3])u\);', text) - want = [('v0', '0'), ('v0', '1'), ('v0', '2'), ('v0', '3')] if kind == 'integer' else [('v5', '1'), ('v5', '0')] + want = ([('v5', '1'), ('v5', '0')] if kind == 'float' + else [('v0', '0'), ('v0', '1'), ('v0', '2'), ('v0', '3')]) check('%s fixture reads the quad lanes' % kind, reads == want, text) check('%s fixture needs ps_6_0' % kind, stage.ps_profile() == 'ps_6_0') reference = image(kind) @@ -201,6 +236,7 @@ def controls(): differing = sum(other[i:i + 4] != reference[i:i + 4] for i in range(0, len(other), 4)) check('%s: %s mutation changes %d pixels' % (kind, how, differing), differing > 0) pixel_hlsl(kind, how) + check('loop fixture matches the integer reference image', image('loop') == image('integer')) plain = pixel_stage(vop1(6, 5, 0) + export((5, 5, 5, 5))) check('a stage without a quad read stays ps_5_1', plain.ps_profile() == 'ps_5_1') # The four lanes of the integer image are four distinct words in every quad, so a lane mix-up cannot hide. @@ -237,7 +273,13 @@ def controls(): check('refused: no s_wqm exec, exec before the broadcast', refused(sane, quad_exec=False)) check('refused: the stage translator without s_wqm', refused_in_stage(NO_WQM_WORDS)) check('refused: s_wqm into another register', refused_in_stage(OTHER_WQM_WORDS)) - check('refused: pixel stage with branches', refused(sane, branches=True)) + # A later loop in the same stage used to refuse entry-prefix broadcasts; Probe(branches=True) still + # has an empty block list, so the entry-prefix proof holds (M200-01/003). + check('entry-prefix broadcast still translates when the stage later has branches', + not refused(sane, branches=True)) + check('refused: broadcast after a branch target', refused_in_stage(AFTER_BRANCH_WORDS)) + check('refused: branch back to the broadcast entry block', refused_in_stage(ENTRY_BACKEDGE_WORDS)) + check('refused: divergent EXEC before the broadcast', refused_in_stage(DIVERGENT_WORDS)) check('control: the sane line itself translates', not refused(sane)) # fi:1 only decides what a disabled source lane returns, and the whole quad is proven active. with_fi = 'v_subrev_f32_dpp v1, v0, v0 quad_perm:[0,0,0,0]' + DPP + ' bound_ctrl:1 fi:1' @@ -250,12 +292,15 @@ def controls(): stages[0].lines == ['v256 = QuadReadLaneAt(v0, 0u);', 'v1 = U(F(v0) - F(v256));'], str(stages[0].lines)) check('refused: fi:1 without s_wqm exec, exec', refused(with_fi, quad_exec=False)) check('refused: fi:1 with EXEC no longer the entry mask', refused(with_fi, exec_known=False)) - check('refused: fi:1 in a pixel stage with branches', refused(with_fi, branches=True)) + check('fi:1 still translates when the stage later has branches', not refused(with_fi, branches=True)) check('refused: fi:1 in a vertex stage', refused(with_fi, kind='vs')) def check_binary(llvm_mc): for kind, (source, words) in FIXTURES.items(): + if kind == 'loop': + # The loop fixture's branch label is decoder text; llvm-mc needs a real symbol. + continue check('llvm-mc assembles the %s fixture to the same words' % kind, assemble(llvm_mc, source) == words) diff --git a/tests/startup_gfx2hlsl_dpp_quad_flow_check.py b/tests/startup_gfx2hlsl_dpp_quad_flow_check.py new file mode 100644 index 0000000000..27377b3201 --- /dev/null +++ b/tests/startup_gfx2hlsl_dpp_quad_flow_check.py @@ -0,0 +1,297 @@ +"""DPP16 quad reads in a pixel program with branches and loops (tools/startup/gfx2hlsl.py), read back from a real +D3D12 draw. + + (no arguments) translation controls and refusals, pure Python + binary <llvm-mc> assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pixel stage with DXC ps_6_0 (quad reads need shader + model 6.0; the optional fxc argument is accepted and ignored), draw 16 x 16 + pixels and compare every pixel with the CPU reference below + +The translator runs each guest lane as its own HLSL thread and turns branches into a pc dispatch loop. A quad read +(QuadReadAcross*, QuadReadLaneAt) gives the neighbour's word only when the four threads of the quad reach it together +with the words the four guest lanes hold. The guest wave runs as one, so this holds when every branch on a path to +the read is wave-uniform and EXEC is still the whole-quad mask of the entry s_wqm exec, exec. The translator proves +that over the whole program after translation (Stage.quad_flow_refusals) and refuses the read otherwise: a vccz/vccnz +loop, an SCC taken from a lane mask, an EXEC write that can reach the read (also around a loop back edge), and an +s_wqm that does not run before every branch. No wave size is assumed: the quad operations need only the 2 x 2 quad. + +The draw fixture LOOP is the shape of a uniform loop over a scalar counter with an if inside it: + s_mov_b64 s[4:5], exec ; s_wqm_b64 exec, exec entry: save the exact mask, whole quads on + v1 = (x | y << 16) * 0x9b5d ; v2 = v3 = v5 = 0 ; s0 = 0 + loop: k = s0 = 0 .. 4 + v2 += quad_perm:[1,0,3,2] v1 the pixel at x ^ 1 + v3 += quad_perm:[2,2,2,2] v1 lane 2 of the quad, pixel (x & ~1, y | 1) + if (s0 != 2) { v4 = quad_perm:[0,0,2,2] v1 ; v5 ^= v4 } pixel (x & ~1, y), skipped on pass 2 + v1 += 0x101 ; s0 += 1 ; loop while s0 < 5 + s_and_b64 exec, exec, s[4:5] ; exp mrt0 v2, v3, v5, v1 +So the neighbour word read on pass k is w(neighbour) + k * 0x101 and the reference below sums or XORs it with plain +integers. The EXEC restore after the loop does not reach any read and is allowed. Mutations of the translated text +(each of the three reads taking the wrong lane) must fail the same draw. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +WIDTH = HEIGHT = 16 +MULTIPLIER = 0x9b5d +STEP, PASSES, SKIPPED = 0x101, 5, 2 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +# name -> (source with numeric branch offsets, words assembled by llvm-mc 19 for gfx1013) +FIXTURES = { + 'LOOP': ('''s_mov_b64 s[4:5], exec +s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_mov_b32_e32 v3, 0 +v_mov_b32_e32 v5, 0 +s_mov_b32 s0, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_dpp v3, v1, v3 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf +s_cmp_eq_u32 s0, 2 +s_cbranch_scc1 3 +v_mov_b32_dpp v4, v1 quad_perm:[0,0,2,2] row_mask:0xf bank_mask:0xf +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v1, 0x101, v1 +s_add_u32 s0, s0, 1 +s_cmp_lt_u32 s0, 5 +s_cbranch_scc1 -14 +s_and_b64 exec, exec, s[4:5] +exp mrt0 v2, v3, v5, v1 done vm +s_endpgm +''', '7e0484be7e0afebeff0002165d9b00008002047e8002067e80020a7e800380befa04044a01b100fffa06064a01aa00ff008206bf030085bf' + 'fa02087e01a000ff040b0a3aff02024a010100000081008000850abff2ff85bf7e04fe870f1800f802030501000081bf'), + 'VCC_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_e32 v1, 3, v1 +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_cbranch_vccnz -6 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047efa04044a01b100ff8302024aff02887d00010000faff87bf0f1800f802010000000081bf'), + 'MASK_SCC_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_e32 v1, 3, v1 +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_and_b64 s[2:3], vcc, exec +s_cbranch_scc1 -7 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047efa04044a01b100ff8302024aff02887d000100006a7e8287f9ff85bf0f1800f802010000000081bf'), + 'EXEC_IN_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +s_mov_b32 s0, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_and_saveexec_b64 s[4:5], vcc +v_add_nc_u32_e32 v1, 3, v1 +s_or_b64 exec, exec, s[4:5] +s_add_u32 s0, s0, 1 +s_cmp_lt_u32 s0, 4 +s_cbranch_scc1 -10 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047e800380befa04044a01b100ffff02887d000100006a2484be8302024a7e04fe880081008000840abf' + 'f6ff85bf0f1800f802010000000081bf'), + 'WQM_AFTER_BRANCH': ('''s_mov_b32 s0, 0 +s_cmp_eq_u32 s0, 0 +s_cbranch_scc1 1 +v_mov_b32_e32 v0, 1 +s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_dpp v2, v1 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '800380be008006bf010085bf8102007e7e0afebeff0002165d9b0000fa02047e010000ff0f1800f802010000000081bf'), +} +REFUSALS = { + 'VCC_LOOP': 's_cbranch_vccnz at +0x24 is not proven wave-uniform', + 'MASK_SCC_LOOP': 's_cbranch_scc1 at +0x28 is not proven wave-uniform', + 'EXEC_IN_LOOP': 'the EXEC write at +0x24 reaches it', + 'WQM_AFTER_BRANCH': 'the s_wqm exec, exec does not run before every branch', +} + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + detail[:2000])) + if not ok: + failures.append(label) + + +def words(name): + return bytes.fromhex(FIXTURES[name][1]) + + +def translate(name): + try: + return G.Pipeline(VS_WORDS, words(name), root_blob(), ps_hw_inputs=PACKED).hlsl_ps(), None + except G.Unsupported as reason: + return None, str(reason) + + +# ---- CPU reference ---------------------------------------------------------------------------------------------------- +def word(x, y): + return ((x | (y << 16)) * MULTIPLIER) & MASK + + +def image(): + out = [] + for y in range(HEIGHT): + for x in range(WIDTH): + swap = sum(word(x ^ 1, y) + k * STEP for k in range(PASSES)) & MASK + broadcast = sum(word(x & ~1, y | 1) + k * STEP for k in range(PASSES)) & MASK + pair = 0 + for k in range(PASSES): + if k != SKIPPED: + pair ^= (word(x & ~1, y) + k * STEP) & MASK + out += [swap, broadcast, pair, (word(x, y) + PASSES * STEP) & MASK] + return out + + +# ---- mutations of the translated text --------------------------------------------------------------------------------- +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new) + + +def swap_own(text): + return replace_once(text, 'QuadReadAcrossX(v1)', 'v1') + + +def broadcast_lane1(text): + return replace_once(text, 'QuadReadLaneAt(v1, 2u)', 'QuadReadLaneAt(v1, 1u)') + + +def pair_own(text): + chain = re.compile(r'x2w_lane == 0u \? x2w_q\d : x2w_lane == 1u \? x2w_q\d : x2w_lane == 2u \? x2w_q\d : x2w_q\d;') + assert len(chain.findall(text)) == 1 + return chain.sub('x2w_lane == 0u ? x2w_q0 : x2w_lane == 1u ? x2w_q1 : x2w_lane == 2u ? x2w_q2 : x2w_q3;', text) + + +MUTATIONS = {'swap reads its own lane': swap_own, 'broadcast reads lane 1': broadcast_lane1, + 'pair keeps every lane': pair_own} + + +# ---- controls --------------------------------------------------------------------------------------------------------- +def controls(): + text, reason = translate('LOOP') + check('LOOP translates (uniform scalar loop and if, quad reads inside)', text is not None, str(reason)) + if text is not None: + check('LOOP keeps the pc dispatch loop', '[loop] for' in text, text) + check('LOOP reads the quad: X swap, lane-2 broadcast, four-lane pair read', + 'QuadReadAcrossX(v1)' in text and 'QuadReadLaneAt(v1, 2u)' in text and text.count('QuadReadLaneAt(v1, ') == 5, + text) + for how, mutate in MUTATIONS.items(): + check('LOOP %s mutation changes the text' % how, mutate(text) != text) + for name, expected in REFUSALS.items(): + text, reason = translate(name) + check('%s refused: %s' % (name, expected), text is None and reason is not None and expected in reason, + str(reason)) + reference = image() + own = [v for y in range(HEIGHT) for x in range(WIDTH) + for v in (sum(word(x, y) + k * STEP for k in range(PASSES)) & MASK,) * 2 + (0, 0)] + check('reference differs from a lane-local reading', reference[0::4] != own[0::4] and reference[1::4] != own[1::4]) + # A dead quad read behind an early s_endpgm in a branch-free program has no branch to prove: no crash. + dead = bytes.fromhex('7e0afebeff0002165d9b00008002047e000081bffa04044a01b100fffa02087e01a000ff000081bf') + try: + G.Pipeline(VS_WORDS, dead, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + check('dead quad read after s_endpgm translates without a crash', True) + except G.Unsupported as reason: + check('dead quad read after s_endpgm translates without a crash', True, str(reason)) + except Exception as error: # noqa: BLE001 - the regression is an unexpected exception type + check('dead quad read after s_endpgm translates without a crash', False, repr(error)) + # A straight-line program with the same reads still translates as before. + straight = bytes.fromhex('7e0afebeff0002165d9b0000fa02047e01b100ff0f1800f802010000000081bf') + try: + G.Pipeline(VS_WORDS, straight, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + check('straight-line quad swap still translates', True) + except G.Unsupported as reason: + check('straight-line quad swap still translates', False, str(reason)) + + +# ---- draw ------------------------------------------------------------------------------------------------------------- +def words_file(directory, name, values): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(values), *values)) + return path + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + text, reason = translate('LOOP') + if text is None: + check('LOOP translates for the draw', False, str(reason)) + return + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'vs_dxc', 'vs_6_0', directory) + reference = words_file(directory, 'reference', image()) + ps = compile_hlsl(dxc, 'dxc', text, 'ps_loop', 'ps_6_0', directory) + run = draw(renderer, adapter, vs, ps, reference) + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() + if ln.startswith(('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + check('dxc %s LOOP: all %d pixels match the reference' % (adapter, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, run.stdout + run.stderr) + for how, mutate in MUTATIONS.items(): + bad = compile_hlsl(dxc, 'dxc', mutate(text), 'ps_' + how.replace(' ', '_'), 'ps_6_0', directory) + run = draw(renderer, adapter, vs, bad, reference) + lines = [ln for ln in run.stderr.splitlines() if 'pixel' in ln] + check('dxc %s LOOP %s mutation fails against the reference: %s' % (adapter, how, ' / '.join(lines)), + run.returncode != 0 and bool(lines) and lines[0].startswith('pixel mismatch'), run.stdout + run.stderr) + + +def check_binary(llvm_mc): + for name, (source, hexwords) in FIXTURES.items(): + check('llvm-mc assembles the %s fixture to the same words' % name, + assemble(llvm_mc, source) == bytes.fromhex(hexwords)) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_draw_skip_check.py b/tests/startup_gfx2hlsl_draw_skip_check.py index 1020180fa5..46eb2f045b 100644 --- a/tests/startup_gfx2hlsl_draw_skip_check.py +++ b/tests/startup_gfx2hlsl_draw_skip_check.py @@ -19,7 +19,8 @@ def test_earlier_comparison(self): output = io.StringIO() with patch.object(module, 'failures', []), redirect_stdout(output): module.check('prior pixel comparison', passed) - with patch.object(module.subprocess, 'run', return_value=skipped): + with patch.object(module.subprocess, 'run', return_value=skipped), \ + patch('gpu_case_runner.run', return_value=skipped): # the adopted checks draw through it with self.assertRaises(SystemExit) as exit_status: draw('renderer', 'warp', 'vs', 'ps', 'reference') self.assertEqual(exit_status.exception.code, expected) diff --git a/tests/startup_gfx2hlsl_f16_alu_check.py b/tests/startup_gfx2hlsl_f16_alu_check.py index 98a93969fe..7cd26001b3 100644 --- a/tests/startup_gfx2hlsl_f16_alu_check.py +++ b/tests/startup_gfx2hlsl_f16_alu_check.py @@ -18,6 +18,8 @@ sys.path.insert(0, os.path.join(here, '..', 'tools')) sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) import gfx2hlsl as G # noqa: E402 +sys.path.insert(0, here) +import f16_packed_model as M # noqa: E402 failures = [] @@ -45,6 +47,10 @@ def fma16o(a, b, c): with_nan = a * b + c if not (math.isinf(a * b) and math.isinf(c) and (a * b > 0) != (c > 0)) else math.nan return with_nan exact = Fraction(a) * Fraction(b) + Fraction(c) + if exact == 0: + # IEEE round-to-nearest: -0 only when the product and the addend are both negative zeros, else +0. + both_neg = math.copysign(1, a) * math.copysign(1, b) < 0 and math.copysign(1, c) < 0 and a * b == 0 and c == 0 + return -0.0 if both_neg else 0.0 return h2f(f2h_exact(exact)) @@ -86,7 +92,8 @@ def run(asm, regs): dst, expr = re.fullmatch(r'(v\d+) = (.*);', s.lines[0]).groups() env = {f'v{i}': v for i, v in enumerate(regs)} env.update( - f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00), saturate=lambda x: min(max(x, 0.0), 1.0), + mul16=lambda a, b: a * b, + f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: 0x7e00 if math.isnan(x) else (f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00)), asuint=lambda x: x, saturate=lambda x: min(max(x, 0.0), 1.0), abs=abs, min=min, max=max, clamp=lambda x, lo, hi: min(max(x, lo), hi), trunc=lambda x: float(int(x)), isnan=math.isnan, asint=lambda x: x - (1 << 32) if x >> 31 else x, float=float, uint=lambda x: int(x) & 0xffffffff, int=int) @@ -128,14 +135,138 @@ def run(asm, regs): ('v_cvt_i16_f16 v3, v0', [f2h(60000.0)], 0x7fff), ('v_cvt_u16_f16 v3, v0', [f2h(2.75) | HIGH], 2), ('v_cvt_u16_f16 v3, v0', [f2h(-1.5)], 0), + # SDWA binary16: a selected half of each source, the result in one half of the destination. v3 holds the old + # value 0x5a5a1234 where the other half is preserved. + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], THREE), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0', + [0x3c00 << 16 | 0xabcd, TWO, 0, 0x5a5a1234], THREE), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:WORD_1', + [ONE | HIGH, 0x4000 << 16 | 0x1234, 0, 0x5a5a1234], THREE), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], THREE << 16), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], THREE << 16 | 0x1234), + ('v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0', + [ONE | HIGH, TWO | HIGH, 0, 0x5a5a1234], 0x5a5a0000 | THREE), + ('v_sub_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0', + [THREE << 16, ONE, 0, 0], TWO), + ('v_subrev_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_1', + [ONE, THREE << 16, 0, 0], TWO), + ('v_mul_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_1', + [THREE << 16, TWO << 16, 0, 0], f2h(6.0)), + ('v_add_f16_sdwa v3, -v0, |v1| dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [ONE, f2h(-3.0), 0, 0], TWO), + # inf - inf is NaN: the lane keeps a NaN class in the selected half. + ('v_sub_f16_sdwa v3, v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + [0x7c00, 0x7c00, 0, 0], 0x7e00 << 16), ] for asm, regs, expected in CASES: dst, got = run(asm, regs + [0] * (4 - len(regs))) check(asm + ' ' + str(regs), got == expected, 'got %#x want %#x' % (got, expected)) +# The statement the lowering emits, evaluated over every lane of the SDWA draw fixtures (edge values, NaN, infinity, +# signed zero, denormals, both halves, PAD and PRESERVE) against the exact-rational reference of the draw check. A NaN +# has no portable sign or payload, so both sides compare the NaN class (the draw canonicalises the same way). +sys.path.insert(0, here) +import startup_gfx2hlsl_f16_alu_draw_check as D # noqa: E402 +for cfg, lanes in D.SDWA_DRAW.items(): + op, s0, s1, dsel, unused, m0, m1 = cfg[:7] + asm = '%s_sdwa v3, %s, %s dst_sel:%s dst_unused:%s src0_sel:%s src1_sel:%s' % ( + op, D.sdwa_operand(m0, 0), D.sdwa_operand(m1, 1), dsel, unused, s0, s1) + bad = [(x, D.sdwa_reference(cfg, x), run(asm, [x[0], x[1], 0, x[2]])[1]) for x in lanes] + bad = [(x, want, got) for x, want, got in bad if D.canon_word(got) != want] + check('sdwa %s over %d lanes' % (D.sdwa_name(cfg), len(lanes)), not bad, + ' '.join('%08x,%08x,%08x want %08x got %08x' % (*x, want, got) for x, want, got in bad[:2])) + + +def low16_stage(): + s = stage() + s.low16_only_v, s.pinned_low16_v = {3}, set() # v3 holds a d16 load: its upper half is undefined + return s + + +SDWA = 'v_add_f16_sdwa v3, v0, v1 dst_sel:%s dst_unused:%s src0_sel:%s src1_sel:WORD_0' +for sel, unused, src0, still_low16, label in ( + ('WORD_0', 'UNUSED_PRESERVE', 'WORD_0', True, 'keeping the undefined upper half leaves it undefined'), + ('WORD_1', 'UNUSED_PRESERVE', 'WORD_0', False, 'a WORD_1 write over a defined low half is fully defined'), + ('WORD_0', 'UNUSED_PAD', 'WORD_0', False, 'UNUSED_PAD zeroes the upper half')): + s = low16_stage() + s.one('v_add_f16_sdwa', SDWA % (sel, unused, src0)) + check('SDWA binary16 ' + label, (3 in s.low16_only_v) == still_low16) +try: + low16_stage().one('v_add_f16_sdwa', 'v_add_f16_sdwa v4, v3, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD ' + 'src0_sel:WORD_1 src1_sel:WORD_0') + check('SDWA binary16 refuses the undefined upper half of a d16 load as a source', False) +except G.Unsupported: + check('SDWA binary16 refuses the undefined upper half of a d16 load as a source', True) check('clamp saturates the binary16 result', run('v_add_f16 v3, v0, v1 clamp', [THREE, TWO, 0, 0])[1] == ONE) for asm in ('v_add_f16 v3, v0, v1 op_sel:[1,0]', 'v_cvt_i16_f16 v3, v0 clamp', 'v_add_f16 v3, v0', - 'v_fmaak_f16 v3, v0, v1', 'v_mul_f16 v3, v0, v1 mul:2'): + 'v_fmaak_f16 v3, v0, v1', 'v_mul_f16 v3, v0, v1 mul:2', + # SDWA binary16: whole-word destination, byte fields, clamp, omod, integer sext and a constant + # source stay refused. + 'v_add_f16_sdwa v3, v0, v1 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 clamp dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 mul:2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, sext(v0), v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, 1.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0', + 'v_add_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0', + 'v_min_f16_sdwa v3, v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0'): + try: + stage().one(asm.split()[0], asm) + check('refuses ' + asm, False) + except G.Unsupported: + check('refuses ' + asm, True) + +# v_pk_{mul,add,fma}_f16: the lowering is evaluated over every selector pair and a value set built from NaN, inf, -0, +# denormals, the binary16 limits and random words, and compared with the independent model in f16_packed_model.py. +SEL = {2: ('v_pk_mul_f16', 'mul'), 3: ('v_pk_fma_f16', 'fma')} +for name, op, arity in (('v_pk_mul_f16', 'mul', 2), ('v_pk_add_f16', 'add', 2), ('v_pk_fma_f16', 'fma', 3)): + samples = M.sample(arity, 150, arity) + bad = [] + seen = {'swap': 0, 'zero_hi': 0, 'default_hi': 0} + for sel, hi in M.all_combos(arity): + mods = ' op_sel:[%s] op_sel_hi:[%s]' % (','.join(map(str, sel)), ','.join(map(str, hi))) + asm = '%s v3, %s%s' % (name, ', '.join('v%d' % i for i in range(arity)), mods) + for words in samples: + _, got = run(asm, list(words) + [0] * (4 - arity)) + want = M.packed(op, words, sel, hi) + if not M.same(got, want): + bad.append((asm, [hex(w) for w in words], hex(got), hex(want))) + # The model must tell a wrong lowering from the right one: swapped lanes, zeroed high lane, default selectors. + swapped = (want & 0xffff) << 16 | want >> 16 + seen['swap'] += not M.same(got, swapped) + seen['zero_hi'] += not M.same(got, want & 0xffff) + seen['default_hi'] += not M.same(got, M.packed(op, words, sel, [0] * arity)) + check('%s matches the independent model on every selector pair (%d pairs x %d value sets)' + % (name, len(M.all_combos(arity)), len(samples)), not bad, str(bad[:2])) + check('%s: the value sets tell a swapped-lane, zeroed-high-lane or wrong-op_sel_hi lowering from the right one' % name, + all(seen.values()), str(seen)) + # Default selectors (no modifier printed) are op_sel [0..] and op_sel_hi [1..]. + plain = '%s v3, %s' % (name, ', '.join('v%d' % i for i in range(arity))) + check('%s with no modifier uses the default selectors' % name, + all(M.same(run(plain, list(w) + [0] * (4 - arity))[1], M.packed(op, w, [0] * arity, [1] * arity)) + for w in samples)) +# Hand-checked words: 2*3 + 1 per lane, a high lane that reads the low half, inf*0 is NaN, overflow, -0. +PK = [ + ('v_pk_mul_f16 v3, v0, v1', [0x4000 | THREE << 16, 0x4200 | TWO << 16], 0x46004600), + ('v_pk_add_f16 v3, v0, v1 op_sel_hi:[0,1]', [ONE | THREE << 16, ONE | TWO << 16], f2h(2.0) | f2h(3.0) << 16), + ('v_pk_fma_f16 v3, v0, v1, v2', [TWO | TWO << 16, THREE | HALF << 16, ONE | ONE << 16], f2h(7.0) | f2h(2.0) << 16), + ('v_pk_mul_f16 v3, v0, v1', [0x7bff | 0x8000 << 16, 0x4000 | 0x3c00 << 16], 0x7c00 | 0x8000 << 16), + ('v_pk_mul_f16 v3, v0, v1', [0x8000 | 0x0000 << 16, 0x3c00 | 0xbc00 << 16], 0x80008000), +] +for asm, regs, expected in PK: + got = run(asm, regs + [0] * (4 - len(regs)))[1] + check(asm + ' ' + str([hex(r) for r in regs]), got == expected, 'got %#x want %#x' % (got, expected)) +check('inf * 0 is NaN in both lanes', M.is_nan(run('v_pk_mul_f16 v3, v0, v1', [0x7c00 | 0xfc00 << 16, 0 | 0x8000 << 16, 0, 0])[1] & 0xffff) + and M.is_nan(run('v_pk_mul_f16 v3, v0, v1', [0x7c00 | 0xfc00 << 16, 0 | 0x8000 << 16, 0, 0])[1] >> 16)) +for asm in ('v_pk_mul_f16 v3, v0, v1 neg_lo:[1,0]', 'v_pk_mul_f16 v3, v0, v1 neg_hi:[0,1]', 'v_pk_add_f16 v3, v0, v1 clamp', + 'v_pk_mul_f16 v3, 2.0, v1 op_sel_hi:[0,1]', 'v_pk_mul_f16 v3, v0, 0x4000', 'v_pk_add_f16 v3, s0, v1', + 'v_pk_mul_f16 v3, v0, v1 op_sel:[1]', 'v_pk_fma_f16 v3, v0, v1 op_sel:[0,0]', 'v_pk_mul_f16 v3, v0, v1 op_sel:[2,0]', + 'v_pk_mul_f16 v3, -v0, v1', 'v_pk_fma_f16 v3, v0, v1, v2 mul:2', 'v_pk_mul_f16 v[3:4], v0, v1'): try: stage().one(asm.split()[0], asm) check('refuses ' + asm, False) diff --git a/tests/startup_gfx2hlsl_f16_alu_draw_check.py b/tests/startup_gfx2hlsl_f16_alu_draw_check.py index 49a5e674c2..cff464b126 100644 --- a/tests/startup_gfx2hlsl_f16_alu_draw_check.py +++ b/tests/startup_gfx2hlsl_f16_alu_draw_check.py @@ -11,6 +11,10 @@ the pixel stage cannot fold them. Every source word carries garbage in its upper half: the 16-bit operations read the low half only and write a result whose upper half is zero. +The v_pk_{mul,add,fma}_f16 keys (name:half:group) draw four selector pairs per key and isolate one half of the result; +their reference is tests/f16_packed_model.py (exact rationals, NaN/inf/-0/denormal/overflow/tie values), and one +wrong expected word per run must be rejected. + The expected words come from an exact rational model of binary16 arithmetic (Fraction, then one round to binary16), not from the lowering's expressions. """ @@ -19,6 +23,7 @@ import struct import sys import tempfile +from concurrent.futures import ThreadPoolExecutor from fractions import Fraction from pathlib import Path @@ -26,6 +31,7 @@ sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) sys.path.insert(0, str(HERE)) import gfx2hlsl as G # noqa: E402 +import f16_packed_model as M # noqa: E402 from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 POST_WORDS, PRE_WORDS, vs_source, vs_words, words_text) @@ -130,7 +136,67 @@ def sets(pairs, accumulators=None): enumerate(FMAC_DOUBLE_ROUNDING)] + DRAW['v_fmac_f16'][4:] +# v_pk_{mul,add,fma}_f16 keys 'name:half:group'. One key draws four lanes, each with its own op_sel / op_sel_hi pair +# (every pair for mul and add, a covering sample of sixteen for fma), then isolates the low or the high half of the +# result with an integer op, so the readback word is a 16-bit value (tagged below like the integer conversions). +PK_OPS = {'v_pk_mul_f16': ('mul', 2), 'v_pk_add_f16': ('add', 2), 'v_pk_fma_f16': ('fma', 3)} + + +def pk_parse(key): + name, half, group = key.split(':') + kind, arity = PK_OPS[name] + pairs = M.combos(arity)[int(group) * 4:int(group) * 4 + 4] + return name, kind, arity, half, pairs + + +def pk_lane_ok(kind, words, sel, hi, half): + """A lane whose result half is a NaN must get it from a positive NaN operand: the sign of a NaN made by inf * 0 or + inf - inf differs between adapters, so such a lane could not be compared word for word.""" + picks = [M.pick(w, (hi if half == 'hi' else sel)[i]) for i, w in enumerate(words)] + result = M.half_op(kind, *picks) + if not M.is_nan(result): + return True + return any(M.is_nan(h) for h in picks) and not any(M.is_nan(h) and M.sign(h) for h in picks) + + +def pk_lanes(key): + name, kind, arity, half, pairs = pk_parse(key) + seeds = M.sample(sum(map(ord, key)), 400, arity) + lanes = [] + for i in range(8): + sel, hi = pairs[i % 4] + word = next(w for w in seeds if pk_lane_ok(kind, w, sel, hi, half) and w not in lanes) + lanes.append(word) + seeds = [w for w in seeds if w != word] + return [tuple(w) + (0,) * (3 - arity) for w in lanes] + + +PK_KEYS = ['%s:%s:%d' % (n, h, g) for n in PK_OPS for g in range(4) for h in ('lo', 'hi')] +for _key in PK_KEYS: + DRAW[_key] = pk_lanes(_key) + + +def pk_reference(key, x, lane): + name, kind, arity, half, pairs = pk_parse(key) + sel, hi = pairs[lane % 4] + word = M.packed(kind, x[:arity], sel, hi) + return word >> 16 if half == 'hi' else word & 0xffff + + +def pk_body_source(key): + name, kind, arity, half, pairs = pk_parse(key) + lines = [] + for lane, (sel, hi) in enumerate(pairs): + dst = 12 + lane + srcs = ', '.join('v%d' % (lane + 4 * i) for i in range(arity)) + lines.append('%s v%d, %s op_sel:[%s] op_sel_hi:[%s]\n' % (name, dst, srcs, ','.join(map(str, sel)), ','.join(map(str, hi)))) + lines.append('v_and_b32 v%d, 0xffff, v%d\n' % (dst, dst) if half == 'lo' else 'v_lshrrev_b32 v%d, 16, v%d\n' % (dst, dst)) + return ''.join(lines) + + def body_source(op): + if op in PK_KEYS: + return pk_body_source(op) arity, vop1, _ = OPS[op] lines = [] for lane in range(4): @@ -179,11 +245,293 @@ def body_source(op): } +# Recorded llvm-mc (gfx1013) encodings of the v_pk_*_f16 fixtures (see pk_body_source). +BODY_WORDS.update({ + 'v_pk_mul_f16:lo:0': bytes.fromhex( + '0c4010cc00090200ff181836ffff00000d4010cc010b0208ff1a1a36ffff00000e4010cc020d0210ff1c1c36ffff00000f4010cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:0': bytes.fromhex( + '0c4010cc000902009018182c0d4010cc010b0208901a1a2c0e4010cc020d0210901c1c2c0f4010cc030f0218901e1e2c'), + 'v_pk_mul_f16:lo:1': bytes.fromhex( + '0c4810cc00090200ff181836ffff00000d4810cc010b0208ff1a1a36ffff00000e4810cc020d0210ff1c1c36ffff00000f4810cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:1': bytes.fromhex( + '0c4810cc000902009018182c0d4810cc010b0208901a1a2c0e4810cc020d0210901c1c2c0f4810cc030f0218901e1e2c'), + 'v_pk_mul_f16:lo:2': bytes.fromhex( + '0c5010cc00090200ff181836ffff00000d5010cc010b0208ff1a1a36ffff00000e5010cc020d0210ff1c1c36ffff00000f5010cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:2': bytes.fromhex( + '0c5010cc000902009018182c0d5010cc010b0208901a1a2c0e5010cc020d0210901c1c2c0f5010cc030f0218901e1e2c'), + 'v_pk_mul_f16:lo:3': bytes.fromhex( + '0c5810cc00090200ff181836ffff00000d5810cc010b0208ff1a1a36ffff00000e5810cc020d0210ff1c1c36ffff00000f5810cc030f0218ff1e1e36ffff0000'), + 'v_pk_mul_f16:hi:3': bytes.fromhex( + '0c5810cc000902009018182c0d5810cc010b0208901a1a2c0e5810cc020d0210901c1c2c0f5810cc030f0218901e1e2c'), + 'v_pk_add_f16:lo:0': bytes.fromhex( + '0c400fcc00090200ff181836ffff00000d400fcc010b0208ff1a1a36ffff00000e400fcc020d0210ff1c1c36ffff00000f400fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:0': bytes.fromhex( + '0c400fcc000902009018182c0d400fcc010b0208901a1a2c0e400fcc020d0210901c1c2c0f400fcc030f0218901e1e2c'), + 'v_pk_add_f16:lo:1': bytes.fromhex( + '0c480fcc00090200ff181836ffff00000d480fcc010b0208ff1a1a36ffff00000e480fcc020d0210ff1c1c36ffff00000f480fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:1': bytes.fromhex( + '0c480fcc000902009018182c0d480fcc010b0208901a1a2c0e480fcc020d0210901c1c2c0f480fcc030f0218901e1e2c'), + 'v_pk_add_f16:lo:2': bytes.fromhex( + '0c500fcc00090200ff181836ffff00000d500fcc010b0208ff1a1a36ffff00000e500fcc020d0210ff1c1c36ffff00000f500fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:2': bytes.fromhex( + '0c500fcc000902009018182c0d500fcc010b0208901a1a2c0e500fcc020d0210901c1c2c0f500fcc030f0218901e1e2c'), + 'v_pk_add_f16:lo:3': bytes.fromhex( + '0c580fcc00090200ff181836ffff00000d580fcc010b0208ff1a1a36ffff00000e580fcc020d0210ff1c1c36ffff00000f580fcc030f0218ff1e1e36ffff0000'), + 'v_pk_add_f16:hi:3': bytes.fromhex( + '0c580fcc000902009018182c0d580fcc010b0208901a1a2c0e580fcc020d0210901c1c2c0f580fcc030f0218901e1e2c'), + 'v_pk_fma_f16:lo:0': bytes.fromhex( + '0c000ecc0009221cff181836ffff00000d080ecc010b2604ff1a1a36ffff00000e500ecc020d2a0cff1c1c36ffff00000f180ecc030f2e14ff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:0': bytes.fromhex( + '0c000ecc0009221c9018182c0d080ecc010b2604901a1a2c0e500ecc020d2a0c901c1c2c0f180ecc030f2e14901e1e2c'), + 'v_pk_fma_f16:lo:1': bytes.fromhex( + '0c600ecc0009221cff181836ffff00000d680ecc010b2604ff1a1a36ffff00000e300ecc020d2a0cff1c1c36ffff00000f780ecc030f2e14ff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:1': bytes.fromhex( + '0c600ecc0009221c9018182c0d680ecc010b2604901a1a2c0e300ecc020d2a0c901c1c2c0f780ecc030f2e14901e1e2c'), + 'v_pk_fma_f16:lo:2': bytes.fromhex( + '0c080ecc00092204ff181836ffff00000d200ecc010b260cff1a1a36ffff00000e380ecc020d2a14ff1c1c36ffff00000f100ecc030f2e1cff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:2': bytes.fromhex( + '0c080ecc000922049018182c0d200ecc010b260c901a1a2c0e380ecc020d2a14901c1c2c0f100ecc030f2e1c901e1e2c'), + 'v_pk_fma_f16:lo:3': bytes.fromhex( + '0c680ecc00092204ff181836ffff00000d400ecc010b260cff1a1a36ffff00000e580ecc020d2a14ff1c1c36ffff00000f700ecc030f2e1cff1e1e36ffff0000'), + 'v_pk_fma_f16:hi:3': bytes.fromhex( + '0c680ecc000922049018182c0d400ecc010b260c901a1a2c0e580ecc020d2a14901c1c2c0f700ecc030f2e1c901e1e2c'), +}) + + def ps_words(op): return PRE_WORDS + BODY_WORDS[op] + POST_WORDS -def reference(op, x): +# ---- SDWA binary16 arithmetic (v_add/sub/subrev/mul_f16_sdwa) ------------------------------------------------------- +# One configuration per draw group: four lanes run the same instruction (src0_sel, src1_sel, dst_sel, dst_unused and +# the abs/neg spelling of the sources) over different words. Lane i reads v<i> and v<4+i>; the old value of the +# destination is the third parameter word, copied into v<12+i> first so that UNUSED_PRESERVE has something to keep. +# Every source word carries a different, non-NaN value in the half that is not selected. +SDWA_BASE = ('WORD_0', 'UNUSED_PAD') +SDWA_CONFIGS = [(op, s0, s1) + SDWA_BASE + ('', '') for op in ('v_add_f16',) for s0 in ('DWORD', 'WORD_0', 'WORD_1') + for s1 in ('DWORD', 'WORD_0', 'WORD_1')] +SDWA_CONFIGS += [('v_add_f16', 'WORD_1', 'WORD_0', d, u, '', '') for d, u in + (('WORD_1', 'UNUSED_PAD'), ('WORD_0', 'UNUSED_PRESERVE'), ('WORD_1', 'UNUSED_PRESERVE'))] +SDWA_CONFIGS += [(op, 'WORD_1', 'WORD_0', 'WORD_1', 'UNUSED_PRESERVE', '', '') + for op in ('v_sub_f16', 'v_subrev_f16', 'v_mul_f16')] +SDWA_CONFIGS += [('v_add_f16', 'WORD_0', 'WORD_1', 'WORD_0', 'UNUSED_PRESERVE', '-', '|'), + ('v_sub_f16', 'WORD_1', 'WORD_0', 'WORD_1', 'UNUSED_PAD', '-|', ''), + ('v_mul_f16', 'WORD_0', 'WORD_0', 'WORD_0', 'UNUSED_PAD', '|', '-')] +# Edge values of binary16 (zeros of both signs, the smallest and largest denormal, the smallest normal, the largest +# finite value, infinities, quiet and signalling NaN, a NaN with payload) and the roundings that matter. +EDGE_PAIRS = [(0x0000, 0x0000), (0x8000, 0x8000), (0x8000, 0x0000), (0x0001, 0x0001), (0x03ff, 0x0001), + (0x7bff, 0x7bff), (0x0000, 0x7c00), (0xfbff, 0xfbff), (0x7c00, 0x7c00), (0x7c00, 0xfc00), + (0x7e00, 0x3c00), (0x3c00, 0x7c01), (0x7fff, 0x7fff), (0x3c00, 0x1000), (0x3c01, 0x1000), + (0x0400, 0x8001)] +SDWA_EDGE_CONFIGS = [(op, 'WORD_1', 'WORD_0', 'WORD_1', 'UNUSED_PRESERVE', '', '') + for op in ('v_add_f16', 'v_sub_f16', 'v_subrev_f16', 'v_mul_f16')] +GARBAGE = (0xabcd, 0x5a5a, 0xdead, 0x1234) +OLD = (0x5a5a1234, 0xdead5678, 0x1234abcd, 0x2bcd3456) +NAN_HALF = 0x7e00 +# The target is a float format: a result that fits in 16 bits reads back as binary32 zero or a subnormal and FXC drops it. +# Both the drawn word and the expected word are XORed with a tag that keeps every lane a finite normal float (0x3f800000 would turn some 0x4000-class upper halves into infinity or NaN; the control below checks every lane). +SDWA_TAG = 0x60000000 + + +def sdwa_place(value, selection, lane, salt): + """A register word holding value in the selected half and a different non-NaN value in the other.""" + other = GARBAGE[(lane + salt) % 4] + return (value << 16) | other if selection == 'WORD_1' else (other << 16) | value + + +def sdwa_lanes(cfg, pairs): + _op, s0, s1 = cfg[:3] + return [(sdwa_place(a, s0, i, 0), sdwa_place(b, s1, i, 1), OLD[i % 4]) for i, (a, b) in enumerate(pairs)] + + +SDWA_DRAW = {} +for _k, _cfg in enumerate(SDWA_CONFIGS): + SDWA_DRAW[_cfg] = sdwa_lanes(_cfg, [ARITH[(_i + _k) % 8] for _i in range(4)]) +for _cfg in SDWA_EDGE_CONFIGS: + SDWA_DRAW[_cfg + ('edge',)] = sdwa_lanes(_cfg, EDGE_PAIRS) + + +def sdwa_name(cfg): + return '_'.join(p.lower().replace('unused_', '') for p in cfg[:5]) + ''.join( + '_' + {'-': 'neg', '|': 'abs', '-|': 'negabs', '': 'plain'}[m] for m in cfg[5:7]) + ( + '_edge' if len(cfg) > 7 else '') + + +def sdwa_operand(modifier, reg): + return {'': 'v%d', '-': '-v%d', '|': '|v%d|', '-|': '-|v%d|'}[modifier] % reg + + +def sdwa_body_source(cfg): + op, s0, s1, dsel, unused, m0, m1 = cfg[:7] + lines = [] + for lane in range(4): + dst = 12 + lane + lines.append('v_mov_b32 v%d, v%d\n' % (dst, 8 + lane)) + lines.append('%s_sdwa v%d, %s, %s dst_sel:%s dst_unused:%s src0_sel:%s src1_sel:%s\n' % ( + op, dst, sdwa_operand(m0, lane), sdwa_operand(m1, 4 + lane), dsel, unused, s0, s1)) + return ''.join(lines) + + +def half_special(op, a, b): + """Reference binary16 result word of a op b over words, from exact rationals and the IEEE special cases.""" + def nan(x): + return (x & 0x7fff) > 0x7c00 + + def inf(x): + return (x & 0x7fff) == 0x7c00 + if op == 'v_subrev_f16': + op, a, b = 'v_sub_f16', b, a + if op == 'v_sub_f16': + op, b = 'v_add_f16', b ^ 0x8000 + if nan(a) or nan(b): + return NAN_HALF + sign_a, sign_b = a & 0x8000, b & 0x8000 + if op == 'v_mul_f16': + if (inf(a) and (b & 0x7fff) == 0) or (inf(b) and (a & 0x7fff) == 0): + return NAN_HALF + if inf(a) or inf(b): + return 0x7c00 | (sign_a ^ sign_b) + value = exact(a) * exact(b) + return round_half(value) if value else (sign_a ^ sign_b) + if inf(a) and inf(b): + return NAN_HALF if sign_a != sign_b else a + if inf(a) or inf(b): + return a if inf(a) else b + value = exact(a) + exact(b) + if value == 0: + return 0x8000 if (a & 0x7fff) == 0 and (b & 0x7fff) == 0 and sign_a and sign_b else 0 + return round_half(value) + + +def sdwa_half_of(word, selection, modifier): + half = word >> 16 if selection == 'WORD_1' else word & 0xffff + if 'abs' in modifier or '|' in modifier: + half &= 0x7fff + if modifier.startswith('-'): + half ^= 0x8000 + return half + + +def sdwa_reference(cfg, lane, selection_swap=False, keep_swap=False, half_swap=False): + """Expected register word. The three flags build the deliberately wrong readings of the control mutants.""" + op, s0, s1, dsel, unused, m0, m1 = cfg[:7] + w0, w1, old = lane + if selection_swap: + s0, s1 = ('WORD_0' if sel == 'WORD_1' else 'WORD_1' for sel in (s0, s1)) + result = half_special(op, sdwa_half_of(w0, s0, m0), sdwa_half_of(w1, s1, m1)) + if half_swap: + dsel = 'WORD_0' if dsel == 'WORD_1' else 'WORD_1' + if keep_swap: + unused = 'UNUSED_PAD' if unused == 'UNUSED_PRESERVE' else 'UNUSED_PRESERVE' + shift = 16 if dsel == 'WORD_1' else 0 + kept = (old & ~(0xffff << shift)) & 0xffffffff if unused == 'UNUSED_PRESERVE' else 0 + return canon_word(kept | (result << shift)) + + +def canon_half(h): + return NAN_HALF if (h & 0x7fff) > 0x7c00 else h + + +def canon_word(word): + return canon_half(word & 0xffff) | (canon_half(word >> 16) << 16) + + +# A NaN carries no portable sign or payload, so the drawn pair canonicalises every NaN half to 0x7e00 on both sides. +NAN_HLSL = ('uint nanh(uint h) { return (h & 0x7fffu) > 0x7c00u ? 0x7e00u : h; }\n' + 'uint nanc(uint w) { return nanh(w & 0xffffu) | (nanh(w >> 16u) << 16u); }\n') + + +def sdwa_draw_text(cfg): + text = G.Pipeline(vs_words([(0, 0, 0)] * 4), sdwa_ps_words(cfg), root_blob()).hlsl_ps() + return NAN_HLSL + re.sub(r'F\(v(1[2-5])\)', r'F(nanc(v\1) ^ 0x%xu)' % SDWA_TAG, text) + + +# Recorded llvm-mc (gfx1013) encodings of sdwa_body_source(cfg), by configuration name; `binary <llvm-mc>` compares. +SDWA_BODY_WORDS = { + 'v_add_f16_dword_dword_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004060609031a7ef90a1a64010406060a031c7ef90c1c64020406060b031e7ef90e1e6403040606'), + 'v_add_f16_dword_word_0_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004060409031a7ef90a1a64010406040a031c7ef90c1c64020406040b031e7ef90e1e6403040604'), + 'v_add_f16_dword_word_1_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004060509031a7ef90a1a64010406050a031c7ef90c1c64020406050b031e7ef90e1e6403040605'), + 'v_add_f16_word_0_dword_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004040609031a7ef90a1a64010404060a031c7ef90c1c64020404060b031e7ef90e1e6403040406'), + 'v_add_f16_word_0_word_0_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004040409031a7ef90a1a64010404040a031c7ef90c1c64020404040b031e7ef90e1e6403040404'), + 'v_add_f16_word_0_word_1_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004040509031a7ef90a1a64010404050a031c7ef90c1c64020404050b031e7ef90e1e6403040405'), + 'v_add_f16_word_1_dword_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004050609031a7ef90a1a64010405060a031c7ef90c1c64020405060b031e7ef90e1e6403040506'), + 'v_add_f16_word_1_word_0_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004050409031a7ef90a1a64010405040a031c7ef90c1c64020405040b031e7ef90e1e6403040504'), + 'v_add_f16_word_1_word_1_word_0_pad_plain_plain': bytes.fromhex( + '0803187ef90818640004050509031a7ef90a1a64010405050a031c7ef90c1c64020405050b031e7ef90e1e6403040505'), + 'v_add_f16_word_1_word_0_word_1_pad_plain_plain': bytes.fromhex( + '0803187ef90818640005050409031a7ef90a1a64010505040a031c7ef90c1c64020505040b031e7ef90e1e6403050504'), + 'v_add_f16_word_1_word_0_word_0_preserve_plain_plain': bytes.fromhex( + '0803187ef90818640014050409031a7ef90a1a64011405040a031c7ef90c1c64021405040b031e7ef90e1e6403140504'), + 'v_add_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef90818640015050409031a7ef90a1a64011505040a031c7ef90c1c64021505040b031e7ef90e1e6403150504'), + 'v_sub_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef90818660015050409031a7ef90a1a66011505040a031c7ef90c1c66021505040b031e7ef90e1e6603150504'), + 'v_subrev_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef90818680015050409031a7ef90a1a68011505040a031c7ef90c1c68021505040b031e7ef90e1e6803150504'), + 'v_mul_f16_word_1_word_0_word_1_preserve_plain_plain': bytes.fromhex( + '0803187ef908186a0015050409031a7ef90a1a6a011505040a031c7ef90c1c6a021505040b031e7ef90e1e6a03150504'), + 'v_add_f16_word_0_word_1_word_0_preserve_neg_abs': bytes.fromhex( + '0803187ef90818640014142509031a7ef90a1a64011414250a031c7ef90c1c64021414250b031e7ef90e1e6403141425'), + 'v_sub_f16_word_1_word_0_word_1_pad_negabs_plain': bytes.fromhex( + '0803187ef90818660005350409031a7ef90a1a66010535040a031c7ef90c1c66020535040b031e7ef90e1e6603053504'), + 'v_mul_f16_word_0_word_0_word_0_pad_abs_neg': bytes.fromhex( + '0803187ef908186a0004241409031a7ef90a1a6a010424140a031c7ef90c1c6a020424140b031e7ef90e1e6a03042414'), + 'v_add_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef90818640015050409031a7ef90a1a64011505040a031c7ef90c1c64021505040b031e7ef90e1e6403150504'), + 'v_sub_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef90818660015050409031a7ef90a1a66011505040a031c7ef90c1c66021505040b031e7ef90e1e6603150504'), + 'v_subrev_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef90818680015050409031a7ef90a1a68011505040a031c7ef90c1c68021505040b031e7ef90e1e6803150504'), + 'v_mul_f16_word_1_word_0_word_1_preserve_plain_plain_edge': bytes.fromhex( + '0803187ef908186a0015050409031a7ef90a1a6a011505040a031c7ef90c1c6a021505040b031e7ef90e1e6a03150504'), +} + + +def sdwa_ps_words(cfg): + return PRE_WORDS + SDWA_BODY_WORDS[sdwa_name(cfg)] + POST_WORDS + + +def sdwa_controls(check): + check('sdwa model: 1 + 2 = 3', half_special('v_add_f16', F['1'], F['2']) == F['3']) + check('sdwa model: -0 + -0 is -0, -0 + +0 is +0, x - x is +0', + (half_special('v_add_f16', 0x8000, 0x8000), half_special('v_add_f16', 0x8000, 0), + half_special('v_sub_f16', F['1'], F['1'])) == (0x8000, 0, 0)) + check('sdwa model: inf - inf, 0 * inf and NaN input give the NaN class', + (half_special('v_sub_f16', 0x7c00, 0x7c00), half_special('v_mul_f16', 0, 0x7c00), + half_special('v_add_f16', 0x7c01, F['1'])) == (NAN_HALF,) * 3) + check('sdwa model: 65504 + 65504 overflows to inf; the smallest denormal survives an add of zero', + (half_special('v_add_f16', 0x7bff, 0x7bff), half_special('v_add_f16', 0x0001, 0)) == (0x7c00, 0x0001)) + check('sdwa model: ties to even (1 + 2^-11 stays, 1.0009765625 + 2^-11 rounds up)', + (half_special('v_add_f16', 0x3c00, 0x1000), half_special('v_add_f16', 0x3c01, 0x1000)) == (0x3c00, 0x3c02)) + check('sdwa model: the smallest denormals add and a mixed product underflows to a signed zero', + (half_special('v_add_f16', 0x0001, 0x0001), half_special('v_mul_f16', 0x0001, 0x8001)) == (0x0002, 0x8000)) + for cfg, lanes in SDWA_DRAW.items(): + name = sdwa_name(cfg) + check('sdwa %s: four or sixteen lanes in groups of four' % name, len(lanes) % 4 == 0 and len(lanes) >= 4) + refs = [sdwa_reference(cfg, x) for x in lanes] + check('sdwa %s: every tagged word is a normal finite binary32' % name, + all(0 < ((r ^ SDWA_TAG) >> 23) & 0xff < 0xff for r in refs)) + # A wrong lowering must change at least one lane of this configuration (the value-is-wrong control). + for label, flags in (('the other half of the sources', {'selection_swap': True}), + ('the other destination half', {'half_swap': True}), + ('preserve and pad exchanged', {'keep_swap': True})): + detected = any(sdwa_reference(cfg, x, **flags) != r for x, r in zip(lanes, refs)) + check('sdwa %s: control "%s" detects a wrong lowering' % (name, label), detected) + check('sdwa draw: every configuration has an assembled body', + all(sdwa_name(cfg) in SDWA_BODY_WORDS for cfg in SDWA_DRAW) or not SDWA_BODY_WORDS) + + +def reference(op, x, lane=0): + if op in PK_KEYS: + return pk_reference(op, x, lane) return OPS[op][2](*x) & 0xffffffff @@ -194,7 +542,7 @@ def translate(op): # The target is R32G32B32A32_FLOAT, so a small integer result is a binary32 denormal and FXC drops it when it comes # from a float to integer conversion. The integer-result operations therefore set bit 30 on the way out of the pixel # stage and in the expected word; the translated statements themselves are unchanged. -INTEGER_RESULT = ('v_cvt_i16_f16', 'v_cvt_u16_f16') +INTEGER_RESULT = ('v_cvt_i16_f16', 'v_cvt_u16_f16', *PK_KEYS) TAG = 0x40000000 @@ -203,8 +551,8 @@ def draw_text(op): return re.sub(r'F\(v(1[2-5])\)', r'F(v\1 | 0x%xu)' % TAG, text) if op in INTEGER_RESULT else text -def draw_word(op, x): - return reference(op, x) | (TAG if op in INTEGER_RESULT else 0) +def draw_word(op, x, lane=0): + return reference(op, x, lane) | (TAG if op in INTEGER_RESULT else 0) def controls(): @@ -232,8 +580,23 @@ def check(label, ok): check('%s: every draw reference has a zero upper half' % op, all(reference(op, x) >> 16 == 0 for x in DRAW[op])) check('%s: draw sets cover two draws of four lanes' % op, len(DRAW[op]) == 8) + for key in PK_KEYS: + check('%s: every draw reference has a zero upper half' % key, + all(reference(key, x, i) >> 16 == 0 for i, x in enumerate(DRAW[key]))) + check('%s: draw sets cover two draws of four lanes' % key, len(DRAW[key]) == 8) + check('%s: no lane is a generated NaN' % key, + all(pk_lane_ok(pk_parse(key)[1], x[:pk_parse(key)[2]], *pk_parse(key)[4][i % 4], pk_parse(key)[3]) + for i, x in enumerate(DRAW[key]))) if BODY_WORDS: - for op in OPS: + # Non-precise multiplication can lose -0 on RDNA 4 while giving the expected word elsewhere. + # Check the qualifier and its use even when this host's driver preserves both forms. + products = (('plain', translate('v_mul_f16'), 4), + ('packed', translate('v_pk_mul_f16:lo:0'), 8), + ('SDWA', sdwa_draw_text(next(cfg for cfg in SDWA_DRAW if cfg[0] == 'v_mul_f16')), 4)) + for form, text, count in products: + check('%s binary16 multiply preserves its zero sign' % form, + 'precise float product = a * b; return product;' in text and text.count('f16rn(mul16(') == count) + for op in (*OPS, *PK_KEYS): try: text = translate(op) except G.Unsupported as e: @@ -241,43 +604,109 @@ def check(label, ok): continue check('%s: translates to four lane results' % op, all(('v%d = ' % r) in text for r in range(12, 16))) + sdwa_controls(check) + for cfg in SDWA_DRAW: + try: + text = sdwa_draw_text(cfg) + except G.Unsupported as e: + check('sdwa %s: translates (%s)' % (sdwa_name(cfg), e), False) + continue + check('sdwa %s: the four exports carry the float-target tag' % sdwa_name(cfg), + text.count('^ 0x%xu' % SDWA_TAG) == 4) + check('sdwa %s: translates to four lane results' % sdwa_name(cfg), + all(('v%d = ' % r) in text for r in range(12, 16))) if failures: raise SystemExit('FAILED: ' + ', '.join(failures)) def check_binary(llvm_mc): - for op in OPS: + for op in (*OPS, *PK_KEYS): built = assemble(llvm_mc, body_source(op)) if built != BODY_WORDS[op]: raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), BODY_WORDS[op].hex())) - for op in OPS: + for op in DRAW: for i in range(0, 8, 4): if assemble(llvm_mc, vs_source(DRAW[op][i:i + 4])) != vs_words(DRAW[op][i:i + 4]): raise AssertionError('vertex fixture for %s differs from llvm-mc' % op) + for cfg in SDWA_DRAW: + built = assemble(llvm_mc, sdwa_body_source(cfg)) + if built != SDWA_BODY_WORDS[sdwa_name(cfg)]: + raise AssertionError('%s: assembled %s, recorded %s' % (sdwa_name(cfg), built.hex(), + SDWA_BODY_WORDS[sdwa_name(cfg)].hex())) + for i in range(0, len(SDWA_DRAW[cfg]), 4): + if assemble(llvm_mc, vs_source(SDWA_DRAW[cfg][i:i + 4])) != vs_words(SDWA_DRAW[cfg][i:i + 4]): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % sdwa_name(cfg)) print('fixture words match llvm-mc') +def draw_shaders(submit, name, lanes, pixel_words, pixel_text): + pixel = submit('ps', pixel_text, 'ps_' + name) + vertices = [] + for index in range(0, len(lanes), 4): + chunk = lanes[index:index + 4] + source = G.Pipeline(vs_words(chunk), pixel_words, root_blob()).hlsl_vs() + vertices.append((index, chunk, submit('vs', source, 'vs_%s_%d' % (name, index)))) + ps = pixel.result() + for index, chunk, vertex in vertices: + yield index, chunk, vertex.result(), ps + + def check_draw(dxc, renderer, adapter, fxc=None): controls() compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] failures = [] - with tempfile.TemporaryDirectory() as tmp: + # A case group needs one pixel shader and up to two vertex shaders. Only schedule the current group, + # and consume each compiler result in draw order so that a later failure cannot hide an earlier one. + with tempfile.TemporaryDirectory() as tmp, ThreadPoolExecutor(max_workers=3) as pool: directory = Path(tmp) for kind, compiler, vs_profile, ps_profile in compilers: + stages = {} + profiles = {'vs': vs_profile, 'ps': ps_profile} + + def submit(stage, source, stem): + profile = profiles[stage] + key = profile, source + if key not in stages: + stages[key] = pool.submit(compile_hlsl, compiler, kind, source, stem + '_' + kind, profile, directory) + return stages[key] + for op, lanes in DRAW.items(): - ps = compile_hlsl(compiler, kind, draw_text(op), 'ps_%s_%s' % (op, kind), ps_profile, directory) - for index in range(0, len(lanes), 4): - chunk = lanes[index:index + 4] - vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs(), - 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) - expected = words_text(draw_word(op, x) for x in chunk) + shaders = draw_shaders(submit, op.replace(':', '_'), lanes, ps_words(op), draw_text(op)) + for index, chunk, vs, ps in shaders: + expected = words_text(draw_word(op, x, index + n) for n, x in enumerate(chunk)) run = draw(renderer, adapter, vs, ps, expected) + if op == PK_KEYS[0] and index == 0: + # A wrong expected word must be reported: the comparison is not vacuous. + wrong = words_text([draw_word(op, chunk[0], 0) ^ 1] + [draw_word(op, x, n + 1) for n, x in enumerate(chunk[1:])]) + if not draw(renderer, adapter, vs, ps, wrong).returncode: + failures.append('%s %s wrong-value control accepted' % (kind, op)) if run.returncode: failures.append('%s %s set %d' % (kind, op, index // 4)) print('%s %s set %d MISMATCH inputs %s\n%s' % (kind, op, index // 4, chunk, run.stderr.strip()), flush=True) continue print('%s %s set %d: %s' % (kind, op, index // 4, expected), flush=True) + for cfg, lanes in SDWA_DRAW.items(): + name = sdwa_name(cfg) + shaders = draw_shaders(submit, 'sdwa_' + name, lanes, sdwa_ps_words(cfg), sdwa_draw_text(cfg)) + for index, chunk, vs, ps in shaders: + if cfg == SDWA_CONFIGS[0] and index == 0: + control_vs, control_ps = vs, ps + expected = words_text(sdwa_reference(cfg, x) ^ SDWA_TAG for x in chunk) + run = draw(renderer, adapter, vs, ps, expected) + if run.returncode: + failures.append('%s sdwa %s set %d' % (kind, name, index // 4)) + print('%s sdwa %s set %d MISMATCH inputs %s\n%s' % (kind, name, index // 4, chunk, + run.stderr.strip()), flush=True) + continue + print('%s sdwa %s set %d: %s' % (kind, name, index // 4, expected), flush=True) + # Wrong-value control: a drawn word that differs by one bit must be reported as a mismatch. + cfg = SDWA_CONFIGS[0] + chunk = SDWA_DRAW[cfg][:4] + wrong = [sdwa_reference(cfg, x) ^ SDWA_TAG for x in chunk] + wrong[0] ^= 0x10000 + if not draw(renderer, adapter, control_vs, control_ps, words_text(wrong)).returncode: + failures.append('%s sdwa wrong-value control was accepted' % kind) if failures: raise AssertionError('draw mismatches: ' + ', '.join(failures)) diff --git a/tests/startup_gfx2hlsl_f32_med3_check.py b/tests/startup_gfx2hlsl_f32_med3_check.py index 25fc58b0ba..9677acb9e3 100644 --- a/tests/startup_gfx2hlsl_f32_med3_check.py +++ b/tests/startup_gfx2hlsl_f32_med3_check.py @@ -33,7 +33,7 @@ Controls, all on the emitted HLSL text (no compiler, no GPU): - the preamble defines `med3_32` with the encoding test on all three sources, the `>` of `0x7f800000u` and - `min(min(a, b), c)` for the NaN branch; no line calls a `med3(` helper; + the signed-zero `minmax_zero32` min3 chain for the NaN branch; no line calls a `med3(` helper; - the binary32 table points `v_med3_f32` at `med3_32` and the integer forms are unchanged; - every lane of the fixture lowers to `U(med3_32(F(v1), F(v2), F(v3)))` reading s44..s47, which the entry constant buffer fills at draw time; @@ -49,8 +49,9 @@ NaN), 0x40400000 (3.0), 0x3fc00000 (1.5) and 0x3f000000 (0.5); the expected words are 0x3f800000 (1.0), 0x40000000 (2.0), 0x3fc00000 (1.5) and 0x3f800000 (1.0). -The control that counts: the branchless helper restored in the same pair must MISMATCH on the NaN lane, with -0x40000000 where the ISA asks 0x3f800000, and match the other three lanes. A draw whose negative control +The control that counts: the branchless helper restored in the same pair, computed as `precise`, must MISMATCH on +the NaN lane, with 0x40000000 where the ISA asks 0x3f800000, and match the other three lanes. Without `precise` +a driver may fold the median against the constant bounds into a clamp and draw the ISA's 0x3f800000 there (#2730). A draw whose negative control passes proves nothing; this check reports that as a failure rather than accepting it. The instruction words are constructed here from the field layout the checked-in decoder reads @@ -87,9 +88,16 @@ MED3_32 = ('float med3_32(float a, float b, float c) {\n' ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);\n' - ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));\n' + ' return top > 0x7f800000u\n' + ' ? minmax_zero32(minmax_zero32(a, b, false), c, false)\n' + ' : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true);\n' '}') BRANCHLESS = 'float med3_32(float a, float b, float c) {\n return max(min(a, b), min(max(a, b), c));\n}' +# The draw control is the same helper computed as `precise`. Without it, a driver may fold the median against the +# fixture's constant bounds into a clamp whose NaN result is the ISA's: an RX 5700 XT drew 0x3f800000 on the NaN +# lane, so the defect escaped (#2730). `precise` keeps D3D's min/max NaN rule, so the NaN lane draws 2.0. +BRANCHLESS_DRAW = ('float med3_32(float a, float b, float c) {\n' + ' precise float r = max(min(a, b), min(max(a, b), c));\n return r;\n}') OLD_ISNAN = ('float med3_32(float a, float b, float c) {\n' ' return isnan(a) || isnan(b) || isnan(c) ? min(min(a, b), c)' ' : max(min(a, b), min(max(a, b), c));\n}') @@ -309,8 +317,8 @@ def actual_words(run): def naive(hlsl): - """The branchless helper restored, the table still calling med3_32.""" - return hlsl.replace(MED3_32, BRANCHLESS) + """The branchless helper restored as `precise` (BRANCHLESS_DRAW), the table still calling med3_32.""" + return hlsl.replace(MED3_32, BRANCHLESS_DRAW) def check_draw(dxc, renderer, adapter, fxc=None): diff --git a/tests/startup_gfx2hlsl_f32_nan_check.py b/tests/startup_gfx2hlsl_f32_nan_check.py index d40c4354fc..d1c4e599fd 100644 --- a/tests/startup_gfx2hlsl_f32_nan_check.py +++ b/tests/startup_gfx2hlsl_f32_nan_check.py @@ -52,6 +52,7 @@ COMPARES, F32_OPS, PAIRS, VALUES, CLEAR, ONE, WIDTH, HEIGHT, Expr, G, assemble, compile_hlsl, flushed, is_nan, modified, reference) from startup_image_3d_check import CompileQueue # noqa: E402 +import gpu_case_runner # noqa: E402 NAN_FORMS = ('nlt', 'nle', 'ngt', 'nge', 'o', 'u') BROKEN_BY = {'nlt': 'fxc', 'nle': 'fxc', 'ngt': 'fxc', 'nge': 'fxc', 'o': 'dxc', 'u': 'dxc'} @@ -345,8 +346,7 @@ def check_decode(library): def draw(renderer, adapter, vs, ps, expected): - run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), - str(expected)], capture_output=True, text=True) + run = gpu_case_runner.run(renderer, adapter, ['--startup-pixel-words', vs, ps, WIDTH, HEIGHT, expected]) if run.returncode == 77: print(run.stdout + run.stderr) sys.exit(1 if failures else 77) diff --git a/tests/startup_gfx2hlsl_f32_sdwa_check.py b/tests/startup_gfx2hlsl_f32_sdwa_check.py index b1bcc5e74e..b06677eec1 100644 --- a/tests/startup_gfx2hlsl_f32_sdwa_check.py +++ b/tests/startup_gfx2hlsl_f32_sdwa_check.py @@ -47,6 +47,7 @@ HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import startup_gfx2hlsl_f32_lg_check as L # noqa: E402 +import gpu_case_runner # noqa: E402 import startup_gfx2hlsl_f32_nan_check as N # noqa: E402 import startup_gfx2hlsl_vopc_sdwa_check as S # noqa: E402 from startup_image_3d_check import CompileQueue # noqa: E402 @@ -618,8 +619,7 @@ def check_decode(library): def draw(renderer, adapter, vs, ps, expected): - run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), - str(expected)], capture_output=True, text=True) + run = gpu_case_runner.run(renderer, adapter, ['--startup-pixel-words', vs, ps, WIDTH, HEIGHT, expected]) if run.returncode == 77: print(run.stdout + run.stderr) sys.exit(1 if failures else 77) diff --git a/tests/startup_gfx2hlsl_far_early_out_check.py b/tests/startup_gfx2hlsl_far_early_out_check.py new file mode 100644 index 0000000000..1099c95122 --- /dev/null +++ b/tests/startup_gfx2hlsl_far_early_out_check.py @@ -0,0 +1,555 @@ +#!/usr/bin/env python3 +"""Statically resolved RDNA2 far early-out control flow through the two-exit profile. + + (no arguments) pure-Python controls, extraction and negative controls + (the extraction runs when an LLVM 15 library is found, and + is skipped with a line otherwise) + binary <llvm-mc> [libLLVM] + reassemble the fixture sources and compare with the words below; + with a library the extraction runs against it as well + controls <libLLVM> the same full run with the extraction driven through the + given LLVM 15 library (LLVM-21 is accepted for a local run; + a recorded CI run should use an LLVM 15 build) + +The fixture builds one gfx1013 pixel program in three variants, all with the same per-pixel arithmetic +and the same two exports: a uniform root-constant compare selects an early path or a normal path, and +the early path transfers to a pure terminating continuation (NOPs, then the program's final s_endpgm): + + - short: the transfer is a plain s_branch onto the continuation; + - calculated: the documented far-transfer chain s_getpc_b64 / s_add_u32 displacement / + s_addc_u32 sign extension / s_setpc_b64 over a short distance; + - far: the same chain over a distance the SOPP branch word cannot encode (>= 32768 reachable + NOP DWORDs sit in the normal path, and the displacement measured from the actual assembled + offsets exceeds the 131068-byte positive s_branch range). + +Every variant is checked three ways: the startup Stage must translate it (its blocks show the jump), +the emitted dispatcher must reproduce the independent per-lane arithmetic oracle for both selector +values, and the bounded FSSM v0x101 extraction of pixel_aot must return the original code exactly. +The negative matrix refuses a register-derived displacement, a missing ADDC, a wrong sign extension, +a signed ADD, a competing entry into the chain, pair clobbering, an address escape, an SCC escape, a +stale scratch pair, an effectful continuation (export, store, barrier, EXEC write), a continuation +ending at the first rather than the final s_endpgm, a target off an +instruction boundary and a target outside the program, each with a named diagnostic. +""" +import re +import struct +import subprocess +import ctypes.util +import sys +import tempfile +import zlib +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) + +import gfx2hlsl as G # noqa: E402 +import pixel_aot # noqa: E402 +import disasm_rdna2 as D # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + + +def resolve_libllvm(): + """The LLVM 15 shared library for the extraction check, or None when this host has none. + + The binary mode takes the library as an optional argument; the plain mode searches the common + install paths, following the discovery order tests/rdna2_tools_check.py uses. + """ + candidates = ['/usr/lib64/llvm15/lib/libLLVM-15.so', 'libLLVM-15.so.1', 'libLLVM-15.so', + 'libLLVM.so.15'] + for candidate in candidates: + path = Path(candidate) + if path.is_file(): + return str(path) + found = ctypes.util.find_library(candidate) + if found and Path(found).is_file(): + return found + for directory in ('/usr/lib/x86_64-linux-gnu', '/usr/lib64/llvm15/lib', '/usr/lib64', + '/usr/lib', '/usr/local/lib'): + option = Path(directory) / candidate + if option.is_file(): + return str(option) + return None + + +LIBRARY = resolve_libllvm() + + +class Pipe: + root = {'params': [{'type': 1, 'count': 1}], 'flags': 0} + + def ud(self, key): + return 0 + + def mrt_kind(self, index): + assert index == 0 + return 'uint' + +# The shared per-pixel arithmetic: p = (x & 0xffff) | (y << 16) over the entry I/J words, then the +# early export (p, p+3, p^0x80000000, p+3) and the normal export (p, p+19, p^0x80000000, p+19), +# all modulo 2^32 (R32G32B32A32_UINT). +PREFIX = ( + ('v_mov_b32_e32 v4, v0', '0003087e'), + ('v_and_b32_e32 v4, 0xffff, v4', 'ff080836ffff0000'), + ('v_lshlrev_b32_e32 v5, 16, v1', '90020a34'), + ('v_or_b32_e32 v4, v4, v5', '040b0838'), + ('v_mov_b32_e32 v1, v4', '0403027e'), + ('v_add_nc_u32_e32 v6, 3, v4', '83080c4a'), + ('v_xor_b32_e32 v7, 0x80000000, v4', 'ff080e3a00000080'), + ('v_add_nc_u32_e32 v8, 19, v4', '9308104a'), +) +COMPARE = ('s_cmp_eq_u32 s8, 0', '088006bf') +EXP_A = ('exp mrt0 v4, v6, v7, v6 done vm', '0f1800f804060706') +EXP_B = ('exp mrt0 v4, v8, v7, v8 done vm', '0f1800f804080708') +END = ('s_endpgm', '000081bf') +NOP = ('s_nop 0', '000080bf') +GETPC = ('s_getpc_b64 s[20:21]', '001f94be') +ADDC_0 = ('s_addc_u32 s21, s21, 0', '15801582') +SETPC = ('s_setpc_b64 s[20:21]', '142080be') +# The SOPP branch word is a signed 16-bit count of DWORDs from the instruction after the branch, so +# 131068 bytes is the largest forward distance one s_branch can encode. +SOPP_LIMIT = 131068 +# The far variant's normal path holds this many reachable NOP DWORDs. +FAR_NOP_DWORDS = 32768 + + +def sopp(name, opcode, dwords): + return ('%s %d' % (name, dwords), struct.pack('<I', 0xbf800000 | (opcode << 16) | (dwords & 0xffff)).hex()) + + +def cbranch_scc0(dwords): + return sopp('s_cbranch_scc0', 4, dwords) + + +def s_branch(dwords): + return sopp('s_branch', 2, dwords) + + +def sop2_literal(opcode, sdst, ssrc0, literal): + word = 0x80000000 | (opcode << 23) | (sdst << 16) | (0xff << 8) | ssrc0 + return struct.pack('<I', word).hex() + struct.pack('<i', literal).hex() + + +def sop2_inline(opcode, sdst, ssrc0, inline): + word = 0x80000000 | (opcode << 23) | (sdst << 16) | ((128 + inline) << 8) | ssrc0 + return struct.pack('<I', word).hex() + + +def add_u32(imm): + """s_add_u32 s20, s20, imm as llvm-mc encodes it: an inline constant up to 64, a literal after.""" + if 0 <= imm <= 64: + return ('s_add_u32 s20, s20, %d' % imm, sop2_inline(0, 20, 20, imm)) + return ('s_add_u32 s20, s20, %d' % imm, sop2_literal(0, 20, 20, imm)) + + +def add_i32(imm): + """s_add_i32 s20, s20, imm: the signed SOP2 form the negative matrix substitutes.""" + if 0 <= imm <= 64: + return ('s_add_i32 s20, s20, %d' % imm, sop2_inline(2, 20, 20, imm)) + return ('s_add_i32 s20, s20, %d' % imm, sop2_literal(2, 20, 20, imm)) + + +# A transfer is a list of rows; the marker 'ADD' names the low-word ADD whose immediate is the +# displacement from the GETPC successor to the continuation, resolved by the layout solver. +CHAIN = [GETPC, 'ADD', ADDC_0, SETPC] +BRANCH = ['BRANCH'] + + +def variant(transfer, nops=0): + """(rows, code, offsets) of one variant. + + Layout: prefix; compare; entry branch over the early path to the normal block; early export; the + transfer; normal export; NOPs; first s_endpgm; continuation (NOP, final s_endpgm). The entry + branch and the symbolic ADD are re-encoded from the offsets until both are stable, because a + displacement above 64 widens the ADD from 4 to 8 bytes and moves the continuation. + """ + rows = list(PREFIX) + [COMPARE, 'CBRANCH', EXP_A] + list(transfer) \ + + [EXP_B] + [NOP] * nops + [END, NOP, END] + entry = len(PREFIX) + 1 + add_at = next((entry + 2 + i for i, row in enumerate(transfer) if row == 'ADD'), None) + branch_at = entry + 2 if not transfer or transfer[0] == 'BRANCH' else None + normal = entry + 2 + len(transfer) + continuation = normal + 1 + nops + 1 + displacement = 0 + for _ in range(8): + materialized = [] + for row in rows: + if row == 'CBRANCH' or row == 'BRANCH': + materialized.append(None) # a placeholder of the same 4-byte width + elif row == 'ADD': + materialized.append(add_u32(displacement)) # keeps the width of the last pass + else: + materialized.append(row) + offsets, words = [], bytearray() + for row in materialized: + offsets.append(len(words)) + words += bytes(4) if row is None else bytes.fromhex(row[1]) + if add_at is not None: + displacement = offsets[continuation] - offsets[add_at] + materialized[add_at] = add_u32(displacement) + else: + materialized[branch_at] = s_branch((offsets[continuation] - offsets[branch_at] - 4) // 4) + materialized[entry] = cbranch_scc0((offsets[normal] - offsets[entry] - 4) // 4) + offsets, words = [], bytearray() + for row in materialized: + offsets.append(len(words)) + words += bytes.fromhex(row[1]) + if add_at is None or materialized[add_at][1] == add_u32(offsets[continuation] - offsets[add_at])[1]: + return list(materialized), bytes(words), offsets + raise AssertionError('the layout solver did not settle') + + +def words_of(rows): + return b''.join(bytes.fromhex(row[1]) for row in rows) + + +def source_of(rows): + return '\n'.join(row[0] for row in rows) + '\n' + + +def decode_all(code): + out, off = [], 0 + while off < len(code): + n, name, asm, _ = D.decode_instruction(code, off) + out.append((off, n, name, asm)) + off += n + return out + + +# ---- independent oracle: documented RDNA 2 semantics of the fixture ------------------------------ +def oracle(selector, x, y): + """The four exported words for one selector value, from plain arithmetic over the instructions.""" + p = (x & 0xffff) | ((y << 16) & 0xffffffff) + if selector != 0: # s8 != 0: the compare is false, SCC0 is taken, the normal path runs + return (p, (p + 19) & 0xffffffff, p ^ 0x80000000, (p + 19) & 0xffffffff) + return (p, (p + 3) & 0xffffffff, p ^ 0x80000000, (p + 3) & 0xffffffff) + + +# ---- interpreter of the emitted dispatcher: the pc machine Stage.body actually emits ------------- +def block_statements(body, pc): + statements, inside = [], False + for line in body: + head = line.strip() + if head in ('}', ''): + if inside and head == '}': + return statements + continue + if head.startswith('if (pc == ') or head.startswith('else if (pc == '): + if inside: + return statements + index = head.index('pc == ') + len('pc == ') + if int(head[index:head.rindex(')')]) == pc: + inside = True + continue + if inside: + statements.append(head) + raise AssertionError('pc %d has no dispatcher block' % pc) + + +def run_dispatcher(body, ud0, x, y, steps=64): + """Execute the emitted if/else pc chain directly and return the exported uint4 words.""" + values = {'v0': x, 'v1': y, 'ud0': ud0, 'scc': 0, 'vcc': 0, 'exec': 1, 'm0': 0} + for i in (4, 5, 6, 7, 8): + values['v%d' % i] = 0 + mrt = None + pc = 0 + for _ in range(steps): + if pc == 0xffff: + return mrt + for statement in block_statements(body, pc): + if statement.startswith('pc = ('): + cond = statement[len('pc = ('):statement.index(') ?')] + taken = Expr(cond).run(values)[0] + pc = int(statement[statement.index('? ') + 2:statement.index(' :')], 0) if taken else \ + int(statement[statement.rindex(': ') + 2:-1], 0) + elif statement.startswith('pc = '): + pc = int(statement[len('pc = '):-2], 0) if statement.endswith('u;') \ + else int(statement[len('pc = '):-1], 0) + elif statement.startswith('o.mrt0'): + mrt = tuple(Expr(t).run(values)[0] for t in + statement[statement.index('(') + 1:statement.rindex(')')].split(', ')) + else: + name, _, expr = statement.partition(' = ') + values[name] = Expr(expr[:-1]).run(values)[0] + raise AssertionError('dispatcher did not reach pc == 0xffff') + + +# ---- bounded FSSM v0x101 envelope --------------------------------------------------------------- +def shader_record(blob: bytes, name: bytes) -> bytes: + encoder = zlib.compressobj(wbits=-15) + payload = encoder.compress(blob) + encoder.flush() + return (bytes([len(name) + 1]) + name + b'\0\0' + + struct.pack('<4I', len(payload), 0, len(payload), len(blob)) + payload) + + +def envelope(code: bytes, name: bytes = b'fixture') -> bytes: + program_start = 288 + base = program_start - 40 + pad = (-(40 + len(code)) % 16) or 16 + body = code + b'\x00\x00\x9f\xbf' * (pad // 4) + extent = 40 + len(body) + image = bytearray(program_start) + body + image[:4] = b'FSSM' + struct.pack_into('<I', image, 192, program_start - 40) + struct.pack_into('<I', image, 4, 0x101) + struct.pack_into('<Q', image, 200, extent) + struct.pack_into('<Q', image, 232, base + extent) + native = b'XBCH' + bytes(12) + struct.pack('<II', len(image), 0) + zlib.compress(image) + program = (bytes(24) + b'XDAT' + struct.pack('<II', 1, 0) + + struct.pack('<III', 13, 48, len(native)) + native) + sections = [b'DXIL' + struct.pack('<I', len(program)) + program] + offset = 32 + 4 * len(sections) + offsets = bytearray() + for section in sections: + offsets.extend(struct.pack('<I', offset)) + offset += len(section) + blob = b'DXBC' + bytes(16) + struct.pack('<3I', 1, offset, len(sections)) + offsets + b''.join(sections) + return shader_record(blob, name) + + +def extract(directory: Path, code: bytes, library: str | None = LIBRARY) -> bytes: + archive = directory / 'far-early-out.rpf' + archive.write_bytes(envelope(code)) + return pixel_aot.native_program(archive, 'fixture', llvm=library)[1] + + +# ---- checks --------------------------------------------------------------------------------------- +def check_variant(name, rows, code, offsets, continuation, directory, *, displacement=None, + library=LIBRARY): + stage = G.Stage(Pipe(), 'ps', code) + body = stage.body() + # The emitted CFG: the entry branches on the root constant; the transfer is a jump block. + terms = [term for _off, _lines, term in stage.blocks if term] + assert terms[0][0] == 'branch', (name, stage.blocks) + jumps = [term for term in terms if term[0] == 'jump'] + assert jumps and jumps[-1][1] == offsets[continuation], (name, stage.blocks) + # Both selector values reproduce the independent arithmetic oracle on several entry words. + for ud0 in (0, 1): + for x, y in ((0, 0), (5, 9), (0x1234, 0x5678), (0xffff, 0xffff)): + got = run_dispatcher(body, ud0, x, y) + assert got == oracle(ud0, x, y), (name, ud0, x, y, got) + # The bounded FSSM v0x101 extraction returns the original code exactly; without an LLVM 15 + # library on this host it is skipped, and the binary mode of a machine that has one covers it. + extracted = 'extraction skipped (no LLVM 15 library found)' if library is None else ( + 'extracted exactly' if extract(directory, code, library) == code else 'MISMATCH') + assert extracted in ('extracted exactly', 'extraction skipped (no LLVM 15 library found)'), \ + (name, extracted) + if displacement is not None: + assert displacement > SOPP_LIMIT, (name, displacement) + print('%s: translated, dispatcher oracle matched both selectors, %s (%d bytes)' + % (name, extracted, len(code))) + + +def negative(name, code, expected, extractor): + """A refusal with the named diagnostic, from the startup Stage and the pixel_aot extraction.""" + try: + G.Stage(Pipe(), 'ps', code) + except G.Unsupported as reason: + assert expected in str(reason), (name, str(reason)) + else: + raise AssertionError('%s: the startup translator accepted a refused program' % name) + if extractor is None: + print('%s: refused by the translator (%s); extraction skipped (no LLVM 15 library found)' + % (name, expected)) + return + try: + extractor(code) + except ValueError as reason: + assert expected in str(reason), (name, str(reason)) + else: + raise AssertionError('%s: the extractor accepted a refused program' % name) + print('%s: refused (%s)' % (name, expected)) + + +def replace_row(rows, index, row): + out = list(rows) + out[index] = row + return out + + +def drop_row(rows, index): + return rows[:index] + rows[index + 1:] + + +def check_negatives(directory, rows, code, far_rows, far_code, library=LIBRARY): + ins = decode_all(code) + index_of = {off: i for i, (off, _n, _name, _asm) in enumerate(ins)} + asm_of = {i: asm for i, (_off, _n, _name, asm) in enumerate(ins)} + getpc = next(off for off, _n, name, _asm in ins if name == 's_getpc_b64') + add = index_of[getpc + 4] + addc = next(i for i, (off, _n, name, _asm) in enumerate(ins) if name == 's_addc_u32') + setpc = next(i for i, (off, _n, name, _asm) in enumerate(ins) if name == 's_setpc_b64') + entry = next(i for i, (off, _n, name, _asm) in enumerate(ins) if name == 's_cbranch_scc0') + continuation = len(rows) - 2 + displacement = int(asm_of[add].split(', ')[-1], 0) + + def stage_and_extract(built): + if library is None: + return None + def run(_code): + return extract(directory, built, library) + return run + + # A register-derived displacement: the ADD reads s8, so the target is not a constant. + rows_reg = replace_row(rows, add, ('s_add_u32 s20, s20, s8', '14081480')) + negative('register-derived displacement', words_of(rows_reg), + 's_setpc_b64: unsupported arithmetic on calculated PC words', + stage_and_extract(words_of(rows_reg))) + + # A missing ADDC: an equally long no-op sits where the high-word addition belonged, so the SETPC + # consumes the incomplete low-word pair and every other offset stays as it was. + rows_missing = replace_row(rows, addc, NOP) + negative('missing ADDC', words_of(rows_missing), + 's_setpc_b64: incomplete calculated target (missing high-word addition with carry)', + stage_and_extract(words_of(rows_missing))) + + # A wrong high sign extension: the ADDC adds 1 while the displacement is positive. + rows_wrong = replace_row(rows, addc, ('s_addc_u32 s21, s21, 1', sop2_inline(4, 21, 21, 1))) + negative('wrong sign extension', words_of(rows_wrong), + 's_setpc_b64: calculated PC high word is not the signed displacement extension', + stage_and_extract(words_of(rows_wrong))) + + # A signed ADD in the low word: SOP2 s_add_i32 instead of s_add_u32. + rows_signed = replace_row(rows, add, add_i32(displacement)) + negative('signed low-word ADD', words_of(rows_signed), + 's_setpc_b64: calculated PC word escapes into s_add_i32', + stage_and_extract(words_of(rows_signed))) + + # A competing entry: the entry branch targets the ADD, entering the chain without its GETPC base. + branch_dwords = (ins[add][0] - ins[entry][0] - 4) // 4 + rows_competing = replace_row(rows, entry, cbranch_scc0(branch_dwords)) + negative('competing entry into the chain', words_of(rows_competing), + 's_setpc_b64: unknown or ambiguous input pair for calculated PC low-word addition', + stage_and_extract(words_of(rows_competing))) + + # Pair clobbering: an s_mov_b32 of the high word between the ADDC and the SETPC. + rows_clobber = rows[:addc + 1] + [('s_mov_b32 s21, 0', '800395be')] + rows[addc + 1:] + negative('pair clobbering', words_of(rows_clobber), + 's_setpc_b64: unknown or ambiguous calculated target', + stage_and_extract(words_of(rows_clobber))) + + # An address escape: the early block reads the low word as data between the ADDC and the SETPC. + rows_escape = rows[:setpc] + [('v_mov_b32_e32 v9, s20', '1402127e')] + rows[setpc:] + negative('address escape', words_of(rows_escape), + 's_setpc_b64: calculated PC word escapes into v_mov_b32_e32', + stage_and_extract(words_of(rows_escape))) + + # An SCC escape: an SCC-reading branch sits between the ADDC and the SETPC. + rows_scc = rows[:setpc] + [('s_cbranch_scc1 0', '000085bf')] + rows[setpc:] + negative('SCC escape', words_of(rows_scc), + 's_setpc_b64: calculated PC SCC escapes into s_cbranch_scc1', + stage_and_extract(words_of(rows_scc))) + + # A stale scratch pair: the program writes s21 before the chain, so the pair is not fresh. + rows_stale = replace_row(rows, 0, ('s_mov_b32 s21, 5', '850395be')) + negative('stale scratch pair', words_of(rows_stale), + 'far early-out: the scratch pair s[20:21] is not fresh', + stage_and_extract(words_of(rows_stale))) + + # Effectful continuations: an export, a store, a barrier and an EXEC write each refuse. + for row, label in ((('exp mrt0 v4, v4, v4, v4 done vm', '0f1800f804040404'), 'an export'), + (('buffer_store_dword v5, v6, s[16:19], 0 offen', '001070e006050480'), 'a store'), + (('s_barrier', '00008abf'), 'a barrier'), + (('s_mov_b32 exec_lo, 0', '8003febe'), 'an EXEC write')): + rows_effect = replace_row(rows, continuation, row) + negative('effectful continuation (%s)' % label, words_of(rows_effect), + 'far early-out: the continuation instruction', stage_and_extract(words_of(rows_effect))) + + # A continuation ending at the first rather than the final s_endpgm: one s_nop is inserted + # before the first exit and the ADD re-aimed four bytes earlier onto it, so the transfer is + # proven and its continuation is pure, but it terminates before the program's final exit. + first_end = next(i for i, row in enumerate(rows) if row == END) + rows_first = rows[:first_end] + [NOP] + rows[first_end:] + rows_first = replace_row(rows_first, add, add_u32(displacement - 4)) + negative('continuation ends before the final exit', words_of(rows_first), + "far early-out: the continuation ends at", + stage_and_extract(words_of(rows_first))) + + # A target off an instruction boundary: one byte past the continuation start is unaligned. + rows_boundary = replace_row(rows, add, add_u32(displacement + 1)) + negative('target off an instruction boundary', words_of(rows_boundary), + 's_setpc_b64: unaligned calculated branch target', + stage_and_extract(words_of(rows_boundary))) + + # A target outside the program: the displacement points past the final exit. The far rows hold + # the same shape with an already-literal ADD, so the wider displacement moves no instruction. + far_ins = decode_all(far_code) + far_add = next(i for i, (off, n, name, asm) in enumerate(far_ins) if name == 's_add_u32') + far_displacement = int(far_ins[far_add][3].split(', ')[-1], 0) + rows_outside = replace_row(far_rows, far_add, add_u32(far_displacement + 4096)) + negative('target outside the program', words_of(rows_outside), + 's_setpc_b64: target', + stage_and_extract(words_of(rows_outside))) + + +def main(): + args = sys.argv[1:] + if args and args[0] == 'binary': + if len(args) not in (2, 3): + raise SystemExit(__doc__) + return check_binary(args[1], args[2] if len(args) == 3 else None) + library = LIBRARY + if args and args[0] == 'controls': + # The explicit selection drives the extraction half of every control below; it is not + # captured globally, so check_binary and the no-argument auto-discovery keep their own. + if len(args) != 2 or not Path(args[1]).is_file(): + raise SystemExit(__doc__) + library = args[1] + elif args: + raise SystemExit(__doc__) + + short_rows, short_code, short_offsets = variant(BRANCH) + calc_rows, calc_code, calc_offsets = variant(CHAIN) + far_rows, far_code, far_offsets = variant(CHAIN, FAR_NOP_DWORDS) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + check_variant('short s_branch', short_rows, short_code, short_offsets, len(short_rows) - 2, directory, + library=library) + check_variant('short calculated', calc_rows, calc_code, calc_offsets, len(calc_rows) - 2, directory, + library=library) + # The far variant: the displacement measured from the actual assembled offsets must exceed + # the positive SOPP s_branch range, and its NOP run must be reachable in the normal path. + continuation = len(far_rows) - 2 + ins = decode_all(far_code) + getpc = next(off for off, _n, name, _asm in ins if name == 's_getpc_b64') + displacement = far_offsets[continuation] - (getpc + 4) + nops = sum(1 for _off, _n, name, _asm in ins if name == 's_nop') + assert nops >= FAR_NOP_DWORDS, (nops, FAR_NOP_DWORDS) + check_variant('far calculated', far_rows, far_code, far_offsets, continuation, directory, + displacement=displacement, library=library) + print('far displacement %#x exceeds the SOPP positive range %d' % (displacement, SOPP_LIMIT)) + check_negatives(directory, calc_rows, calc_code, far_rows, far_code, library=library) + print('Far early-out: three variants, dispatcher oracle and refusal controls passed') + + +def assemble(llvm_mc, source): + run = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-show-encoding'], input=source, + capture_output=True, text=True, check=True) + words = bytearray() + for line in run.stdout.splitlines(): + m = re.search(r'encoding: \[([^\]]*)\]', line) + if m: + words += bytes(int(b, 16) for b in m.group(1).replace(' ', '').split(',')) + return bytes(words) + + +def check_binary(llvm_mc, library=None): + for name, (rows, code, _offsets) in (('short s_branch', variant(BRANCH)), + ('short calculated', variant(CHAIN)), + ('far calculated', variant(CHAIN, FAR_NOP_DWORDS))): + built = assemble(llvm_mc, source_of(rows)) + assert built == code, (name, built[:80].hex(), code[:80].hex(), len(built), len(code)) + if library is not None: + with tempfile.TemporaryDirectory() as tmp: + assert extract(Path(tmp), code, library) == code, name + if library is not None: + print('fixture words match llvm-mc, and the extraction of each variant through %s is exact' % library) + else: + print('fixture words match llvm-mc') + return 0 + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_float_alu_check.py b/tests/startup_gfx2hlsl_float_alu_check.py new file mode 100644 index 0000000000..e3bff9bcab --- /dev/null +++ b/tests/startup_gfx2hlsl_float_alu_check.py @@ -0,0 +1,129 @@ +"""Binary32 arithmetic of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the pixel bodies and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_add_f32, v_sub_f32, v_subrev_f32, v_mul_f32, v_mul_legacy_f32, v_min_f32, v_max_f32, v_fma_f32, v_mad_f32, +v_mad_legacy_f32, v_med3_f32, v_min3_f32 and v_max3_f32, which no check ran before. The fixture and runner are +startup_gfx2hlsl_lane_alu.py: one operation per lane on flat parameters the compilers cannot fold, alternating the +e32 and e64 spellings of the VOP2 forms. The references follow the AMD RDNA 2 ISA reference: v_subrev is S1 - S0; +the legacy multiply reads 0 when either factor is 0, even against an infinity or a NaN; v_med3_f32 is the middle of +three values. + +Every input set has an exact result, so the operations are checked independently of rounding and of whether a +compiler fuses a multiply and an add. Not covered: inexact products (v_fma_f32 rounds once and v_mad_f32 twice, while +the translation writes both as a * b + c and leaves the choice to the compiler), NaN and signed-zero ordering in min, +max and med3, and denormals. +""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def v(word): + return struct.unpack('<f', struct.pack('<I', word))[0] + + +def op2(function): + return lambda a, b: f(function(v(a), v(b))) + + +def op3(function): + return lambda a, b, c: f(function(v(a), v(b), v(c))) + + +def legacy(a, b): + return 0.0 if a == 0.0 or b == 0.0 else a * b + + +INF, NAN = 0x7f800000, 0x7fc00000 +OPS = { + 'v_add_f32': (2, op2(lambda a, b: a + b), True), + 'v_sub_f32': (2, op2(lambda a, b: a - b), True), + 'v_subrev_f32': (2, op2(lambda a, b: b - a), True), + 'v_mul_f32': (2, op2(lambda a, b: a * b), True), + 'v_mul_legacy_f32': (2, op2(legacy), True), + 'v_min_f32': (2, op2(min), True), + 'v_max_f32': (2, op2(max), True), + 'v_fma_f32': (3, op3(lambda a, b, c: a * b + c), False), + 'v_mad_f32': (3, op3(lambda a, b, c: a * b + c), False), + 'v_mad_legacy_f32': (3, op3(lambda a, b, c: legacy(a, b) + c), False), + 'v_med3_f32': (3, op3(lambda a, b, c: sorted((a, b, c))[1]), False), + 'v_min3_f32': (3, op3(lambda a, b, c: min(a, b, c)), False), + 'v_max3_f32': (3, op3(lambda a, b, c: max(a, b, c)), False), +} + + +def sets(*rows): + return [tuple(x if isinstance(x, int) else f(x) for x in row) for row in rows] + + +# Exact inputs and results: dyadic values whose sums, differences and products fit in 24 bits. +TWO = sets((1.5, 2.25, 0), (-3.0, 0.5, 0), (1024.0, -0.125, 0), (7.0, -7.5, 0), + (0.375, 8.0, 0), (-2.5, -4.0, 0), (65536.0, 3.0, 0), (0.0, 5.0, 0)) +LEGACY = sets((0.0, INF, 0), (INF, 0.0, 0), (2.0, 3.0, 0), (0.0, NAN, 0), + (-1.5, 4.0, 0), (NAN, 0.0, 0), (0.25, -0.5, 0), (3.0, 3.0, 0)) +THREE = sets((1.5, 2.0, 0.25), (-3.0, 0.5, 10.0), (4.0, 4.0, -16.0), (0.75, -8.0, 1.0), + (2.0, 2.0, 2.0), (-1.0, 5.0, 3.0), (100.0, 0.5, -50.0), (9.0, -1.0, 2.5)) +LEGACY3 = sets((0.0, INF, 1.0), (INF, 0.0, -2.0), (2.0, 3.0, 0.5), (0.0, NAN, 4.0), + (-1.5, 4.0, 6.0), (NAN, 0.0, -0.25), (0.25, -0.5, 1.0), (3.0, 3.0, -9.0)) +DRAW = {op: TWO for op in ('v_add_f32', 'v_sub_f32', 'v_subrev_f32', 'v_mul_f32', 'v_min_f32', 'v_max_f32')} +DRAW.update({op: THREE for op in ('v_fma_f32', 'v_mad_f32', 'v_med3_f32', 'v_min3_f32', 'v_max3_f32')}) +DRAW.update({'v_mul_legacy_f32': LEGACY, 'v_mad_legacy_f32': LEGACY3}) +F = r'F\((v\d+)\)' +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_add_f32': (r'U\(%s \+ %s\)' % (F, F), r'U(F(\1) - F(\2))', op2(lambda a, b: a - b)), + 'v_sub_f32': (r'U\(%s - %s\)' % (F, F), r'U(F(\2) - F(\1))', op2(lambda a, b: b - a)), + 'v_subrev_f32': (r'U\(%s - %s\)' % (F, F), r'U(F(\2) - F(\1))', op2(lambda a, b: a - b)), + 'v_mul_f32': (r'U\(%s \* %s\)' % (F, F), r'U(F(\1) + F(\2))', op2(lambda a, b: a + b)), + 'v_mul_legacy_f32': (r'U\(mul_legacy\(', r'U(2.0 * mul_legacy(', op2(lambda a, b: 2.0 * legacy(a, b))), + 'v_min_f32': (r'U\(minmax_zero32\(%s, %s, false\)\)' % (F, F), r'U(minmax_zero32(F(\1), F(\2), true))', + op2(max)), + 'v_max_f32': (r'U\(minmax_zero32\(%s, %s, true\)\)' % (F, F), r'U(minmax_zero32(F(\1), F(\2), false))', + op2(min)), + 'v_fma_f32': (r' \+ (F\(v\d+\))\)', r' - \1)', op3(lambda a, b, c: a * b - c)), + 'v_mad_f32': (r'mad32\(%s, %s, (F\(v\d+\)), false\)' % (F, F), r'mad32(F(\1), F(\2), -\3, false)', + op3(lambda a, b, c: a * b - c)), + 'v_mad_legacy_f32': (r'mad32\(%s, %s, (F\(v\d+\)), true\)' % (F, F), r'mad32(2.0 * F(\1), F(\2), \3, true)', + op3(lambda a, b, c: 2.0 * legacy(a, b) + c)), + 'v_med3_f32': (r'med3_32\(%s, %s, %s\)' % (F, F, F), r'max(F(\1), max(F(\2), F(\3)))', + op3(lambda a, b, c: max(a, b, c))), + 'v_min3_f32': (r'U\(minmax_zero32\(%s, (minmax_zero32\(F\(v\d+\), F\(v\d+\), false\)), false\)\)' % F, + r'U(minmax_zero32(F(\1), \2, true))', op3(lambda a, b, c: max(a, min(b, c)))), + 'v_max3_f32': (r'U\(minmax_zero32\(%s, (minmax_zero32\(F\(v\d+\), F\(v\d+\), true\)), true\)\)' % F, + r'U(minmax_zero32(F(\1), \2, false))', op3(lambda a, b, c: min(a, max(b, c)))), +} +BODY = { + 'v_add_f32': words('000918060d0003d5010b0200020d1c060f0003d5030f0200'), + 'v_sub_f32': words('000918080d0004d5010b0200020d1c080f0004d5030f0200'), + 'v_subrev_f32': words('0009180a0d0005d5010b0200020d1c0a0f0005d5030f0200'), + 'v_mul_f32': words('000918100d0008d5010b0200020d1c100f0008d5030f0200'), + 'v_mul_legacy_f32': words('0009180e0d0007d5010b0200020d1c0e0f0007d5030f0200'), + 'v_min_f32': words('0009181e0d000fd5010b0200020d1c1e0f000fd5030f0200'), + 'v_max_f32': words('000918200d0010d5010b0200020d1c200f0010d5030f0200'), + 'v_fma_f32': words('0c004bd5000922040d004bd5010b26040e004bd5020d2a040f004bd5030f2e04'), + 'v_mad_f32': words('0c0041d5000922040d0041d5010b26040e0041d5020d2a040f0041d5030f2e04'), + 'v_mad_legacy_f32': words('0c0040d5000922040d0040d5010b26040e0040d5020d2a040f0040d5030f2e04'), + 'v_med3_f32': words('0c0057d5000922040d0057d5010b26040e0057d5020d2a040f0057d5030f2e04'), + 'v_min3_f32': words('0c0051d5000922040d0051d5010b26040e0051d5020d2a040f0051d5030f2e04'), + 'v_max3_f32': words('0c0054d5000922040d0054d5010b26040e0054d5020d2a040f0054d5030f2e04'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_add_f32 v1, v2, v3', 'v_mul_f32_e64 v1, -v2, |v3|', 'v_fma_f32 v1, v2, v3, v4', + 'v_max3_f32 v1, v2, 1.0, v4', 'v_min_f32_e64 v1, v2, v3 clamp'], + 'refused': ['v_add_f32_e64 v1, v2, v3 neg_lo:[1,0,0]', 'v_mul_f32_e64 v1, v2, v3 neg_hi:[0,1,0]'], +} + +if __name__ == '__main__': + main(FAMILY, __doc__) diff --git a/tests/startup_gfx2hlsl_float_round_check.py b/tests/startup_gfx2hlsl_float_round_check.py new file mode 100644 index 0000000000..6ca36fb9b9 --- /dev/null +++ b/tests/startup_gfx2hlsl_float_round_check.py @@ -0,0 +1,81 @@ +"""Binary32 rounding operations of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the pixel bodies and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_floor_f32, v_ceil_f32, v_trunc_f32, v_fract_f32 and v_rndne_f32, which no check ran before. The fixture and +runner are startup_gfx2hlsl_lane_alu.py: one operation per lane, alternating the e32 and e64 spellings, on flat +parameters the compilers cannot fold. The references follow the AMD RDNA 2 ISA reference: a zero result keeps the sign +of the source (ceil(-0.75) and trunc(-0.75) are -0), v_rndne_f32 rounds halves to even, and v_fract_f32 is +x - floor(x) capped at the largest binary32 below 1.0 (0x3f7fffff), so a tiny negative source does not give 1.0. +The inputs are exact halves and quarters, 1000000.5, the binary32 just below 0.5, 8388607.5 and -2^-30. +""" +import math +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def v(word): + return struct.unpack('<f', struct.pack('<I', word))[0] + + +def signed_zero(function): + """function on the binary32 value of a word; a zero result keeps the sign of the source.""" + def apply(a): + x = v(a) + result = float(function(x)) + return f(math.copysign(0.0, x) if result == 0 else result) + return apply + + +def fract(a): + x = v(a) + return min(f(x - math.floor(x)), 0x3f7fffff) + + +ONE_BELOW_HALF = 0x3effffff +TINY_NEGATIVE = 0xb0800000 # -2^-30 +OPS = { + 'v_floor_f32': (1, signed_zero(math.floor), True), + 'v_ceil_f32': (1, signed_zero(math.ceil), True), + 'v_trunc_f32': (1, signed_zero(math.trunc), True), + 'v_fract_f32': (1, fract, True), + 'v_rndne_f32': (1, signed_zero(round), True), +} +SETS = [(f(2.5), 0, 0), (f(-0.75), 0, 0), (f(3.5), 0, 0), (f(-2.5), 0, 0), + (f(1000000.5), 0, 0), (ONE_BELOW_HALF, 0, 0), (TINY_NEGATIVE, 0, 0), (f(8388607.5), 0, 0)] +DRAW = {op: SETS for op in OPS} +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_floor_f32': (r'U\(floor\(', r'U(ceil(', signed_zero(math.ceil)), + 'v_ceil_f32': (r'U\(ceil\(', r'U(floor(', signed_zero(math.floor)), + 'v_trunc_f32': (r'U\(trunc\(', r'U(floor(', signed_zero(math.floor)), + 'v_fract_f32': (r'U\(fract32\(F\((v\d+)\)\)\)', r'U(F(\1) - trunc(F(\1)))', lambda a: f(v(a) - math.trunc(v(a)))), + 'v_rndne_f32': (r'U\(round\(', r'U(trunc(', signed_zero(math.trunc)), +} +BODY = { + 'v_floor_f32': words('0049187e0d00a4d50101000002491c7e0f00a4d503010000'), + 'v_ceil_f32': words('0045187e0d00a2d50101000002451c7e0f00a2d503010000'), + 'v_trunc_f32': words('0043187e0d00a1d50101000002431c7e0f00a1d503010000'), + 'v_fract_f32': words('0041187e0d00a0d50101000002411c7e0f00a0d503010000'), + 'v_rndne_f32': words('0047187e0d00a3d50101000002471c7e0f00a3d503010000'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_floor_f32 v1, v2', 'v_ceil_f32_e64 v1, -v2', 'v_trunc_f32_e64 v1, |v2| clamp', + 'v_fract_f32 v1, s2', 'v_rndne_f32_e64 v1, v2 mul:2'], + 'refused': ['v_floor_f32_e64 v1, v2 neg_lo:[1]', 'v_rndne_f32_e64 v1, v2 neg_hi:[1]'], +} + +if __name__ == '__main__': + main(FAMILY, __doc__) diff --git a/tests/startup_gfx2hlsl_float_transcendental_check.py b/tests/startup_gfx2hlsl_float_transcendental_check.py new file mode 100644 index 0000000000..b973ab9084 --- /dev/null +++ b/tests/startup_gfx2hlsl_float_transcendental_check.py @@ -0,0 +1,88 @@ +"""Binary32 reciprocal, root, exponential and logarithm of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the pixel bodies and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_rcp_f32, v_rcp_iflag_f32, v_sqrt_f32, v_rsq_f32, v_exp_f32 and v_log_f32, which no check ran before. They +lower to 1.0 / x, sqrt, rsqrt, exp2 and log2. The fixture and runner are startup_gfx2hlsl_lane_alu.py: one operation +per lane, alternating the e32 and e64 spellings, on flat parameters the compilers cannot fold. The references follow +the AMD RDNA 2 ISA reference (v_exp_f32 and v_log_f32 are base 2). Every input is a power of two, or 0 and 9 for the +square root, so every result is exactly representable: the check tests which function each operation is lowered to, +not its precision. Adapters need not return those results exactly. An NVIDIA GeForce RTX 4090 reads log2(0.125) as +c03fffff, 1 ulp above -3.0 (#2797), so v_log_f32 accepts 4 ulps: the Direct3D 11.3 functional specification bounds +log to 2^-21 relative error, or 2^-21 absolute for inputs in [0.5, 2], and both are at least 4 ulps of a binary32 +result in this fixture. The other operations stay exact. The mutation (the logarithm plus one) is off by far more. +""" +import math +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def v(word): + return struct.unpack('<f', struct.pack('<I', word))[0] + + +def op(function): + return lambda a: f(function(v(a))) + + +OPS = { + 'v_rcp_f32': (1, op(lambda x: 1.0 / x), True), + 'v_rcp_iflag_f32': (1, op(lambda x: 1.0 / x), True), + 'v_sqrt_f32': (1, op(math.sqrt), True), + 'v_rsq_f32': (1, op(lambda x: 1.0 / math.sqrt(x)), True), + 'v_exp_f32': (1, op(lambda x: 2.0 ** x), True), + 'v_log_f32': (1, op(math.log2), True), +} + + +def sets(*values): + return [(f(x), 0, 0) for x in values] + + +RCP = sets(4.0, -0.5, 1.0, 0.125, 2.0 ** 20, -8.0, 256.0, 2.0 ** -10) +DRAW = { + 'v_rcp_f32': RCP, 'v_rcp_iflag_f32': RCP, + 'v_sqrt_f32': sets(16.0, 0.25, 1.0, 4096.0, 2.0 ** -20, 64.0, 0.0, 9.0), + 'v_rsq_f32': sets(4.0, 0.25, 1.0, 16.0, 2.0 ** 20, 64.0, 2.0 ** -20, 0.0625), + 'v_exp_f32': sets(3.0, -2.0, 0.0, 10.0, -10.0, 1.0, 20.0, -1.0), + 'v_log_f32': sets(8.0, 0.125, 1.0, 1024.0, 2.0 ** -20, 2.0, 2.0 ** 30, 0.5), +} +F = r'F\((v\d+)\)' +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_rcp_f32': (r'U\(1\.0 / ', r'U(2.0 / ', op(lambda x: 2.0 / x)), + 'v_rcp_iflag_f32': (r'U\(1\.0 / ', r'U(2.0 / ', op(lambda x: 2.0 / x)), + 'v_sqrt_f32': (r'U\(sqrt\(', r'U(rsqrt(', op(lambda x: 1.0 / math.sqrt(x))), + 'v_rsq_f32': (r'U\(rsqrt\(', r'U(sqrt(', op(math.sqrt)), + 'v_exp_f32': (r'U\(exp2\(%s\)\)' % F, r'U(exp2(F(\1)) * 2.0)', op(lambda x: 2.0 ** (x + 1))), + 'v_log_f32': (r'U\(log2\(%s\)\)' % F, r'U(log2(F(\1)) + 1.0)', op(lambda x: math.log2(x) + 1)), +} +BODY = { + 'v_rcp_f32': words('0055187e0d00aad50101000002551c7e0f00aad503010000'), + 'v_rcp_iflag_f32': words('0057187e0d00abd50101000002571c7e0f00abd503010000'), + 'v_sqrt_f32': words('0067187e0d00b3d50101000002671c7e0f00b3d503010000'), + 'v_rsq_f32': words('005d187e0d00aed501010000025d1c7e0f00aed503010000'), + 'v_exp_f32': words('004b187e0d00a5d501010000024b1c7e0f00a5d503010000'), + 'v_log_f32': words('004f187e0d00a7d501010000024f1c7e0f00a7d503010000'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_rcp_f32 v1, v2', 'v_sqrt_f32_e64 v1, |v2|', 'v_rsq_f32_e64 v1, v2 clamp', 'v_exp_f32 v1, 1.0', + 'v_log_f32_e64 v1, -v2 mul:2'], + 'refused': ['v_rcp_f32_e64 v1, v2 neg_lo:[1]', 'v_log_f32_e64 v1, v2 neg_hi:[1]'], + 'ulps': {'v_log_f32': 4}, +} + +if __name__ == '__main__': + main(FAMILY, __doc__) diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py index b2f25cc64f..c89f081cd8 100644 --- a/tests/startup_gfx2hlsl_fma_mix_check.py +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -130,63 +130,63 @@ def expect_refused(label, code, asm, low16_only_v=()): plain = expect('f32 sources', encode(MIX_F32, 1, (v2, v3, v4)), 'v_fma_mix_f32 v1, v2, v3, v4', - 'v1 = U(F(v2) * F(v3) + F(v4));') + 'v1 = U(mix32(F(v2), F(v3), F(v4)));') low = expect('binary16 low half of src0', encode(MIX_F32, 1, (v2, v3, v4), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, v3, v4 op_sel_hi:[1,0,0]', - 'v1 = U(f16tof32(v2) * F(v3) + F(v4));') + 'v1 = U(mix32(f16tof32(v2), F(v3), F(v4)));') high = expect('binary16 high half of src0', encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]', - 'v1 = U(f16tof32(v2 >> 16) * F(v3) + F(v4));') + 'v1 = U(mix32(f16tof32(v2 >> 16), F(v3), F(v4)));') check('control: op_sel changes the selected half', low != high) check('control: op_sel_hi changes the source format', plain != low) expect('abs then neg after widening a high half, scalar source, clamp', encode(MIX_F32, 1, (v2, S5, v4), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), abs_bits=(0, 1, 0), neg=(0, 1, 0), clamp=1), 'v_fma_mix_f32 v1, v2, -|s5|, v4 op_sel:[0,1,0] op_sel_hi:[0,1,0] clamp', - 'v1 = U(saturate(F(v2) * (-abs(f16tof32(s5 >> 16))) + F(v4)));') + 'v1 = U(saturate(mix32(F(v2), (-abs(f16tof32(s5 >> 16))), F(v4))));') expect('inline 0 as a binary16 addend', encode(MIX_F32, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1)), 'v_fma_mix_f32 v1, v2, v3, 0 op_sel_hi:[1,1,1]', - 'v1 = U(f16tof32(v2) * f16tof32(v3) + 0.0);') + 'v1 = U(mix32(f16tof32(v2), f16tof32(v3), 0.0));') expect('negated inline 0 addend keeps a -0 product', encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), neg=(0, 0, 1)), 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]', - 'v1 = U(F(v2) * f16tof32(v3 >> 16) + (-0.0));') + 'v1 = U(mix32(F(v2), f16tof32(v3 >> 16), (-0.0)));') expect('inline float on a binary32 source', encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[1,0,0]', - 'v1 = U(f16tof32(v2) * 1.0 + F(v4));') + 'v1 = U(mix32(f16tof32(v2), 1.0, F(v4)));') # neg on inline -0.5 prints as `--0.5`; `(--0.5)` would be an HLSL decrement (review on #2055). expect('negated negative inline float', encode(MIX_F32, 1, (MINUS_HALF_F, v3, v4), neg=(1, 0, 0)), 'v_fma_mix_f32 v1, --0.5, v3, v4', - 'v1 = U((-(-0.5)) * F(v3) + F(v4));') + 'v1 = U(mix32((-(-0.5)), F(v3), F(v4)));') expect('control: an unnegated literal on a binary32 source still translates', encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x3f800000), 'v_fma_mix_f32 v1, 0x3f800000, v3, v4', - 'v1 = U(F(0x3f800000u) * F(v3) + F(v4));') + 'v1 = U(mix32(F(0x3f800000u), F(v3), F(v4)));') # --- the binary16-destination forms keep their packing -------------------------------------------- expect('mixlo writes the low half', encode(MIXLO_F16, 1, (v2, v3, v4), op_sel_hi=(1, 1, 0)), 'v_fma_mixlo_f16 v1, v2, v3, v4 op_sel_hi:[1,1,0]', - 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + F(v4));') + 'v1 = (v1 & 0xffff0000u) | f32tof16(mix32(f16tof32(v2), f16tof32(v3), F(v4)));') expect('mixlo with a negated inline 0 on a binary16 source', encode(MIXLO_F16, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1), neg=(0, 0, 1)), 'v_fma_mixlo_f16 v1, v2, v3, -0 op_sel_hi:[1,1,1]', - 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + (-0.0));') + 'v1 = (v1 & 0xffff0000u) | f32tof16(mix32(f16tof32(v2), f16tof32(v3), (-0.0)));') expect('mixhi writes the high half from a high-half source', encode(MIXHI_F16, 1, (v2, v3, v4), op_sel=(0, 0, 1), op_sel_hi=(0, 0, 1)), 'v_fma_mixhi_f16 v1, v2, v3, v4 op_sel:[0,0,1] op_sel_hi:[0,0,1]', - 'v1 = (v1 & 0xffffu) | (f32tof16(F(v2) * F(v3) + f16tof32(v4 >> 16)) << 16);') + 'v1 = (v1 & 0xffffu) | (f32tof16(mix32(F(v2), F(v3), f16tof32(v4 >> 16))) << 16);') # A register whose upper 16 bits are undefined (odd-dmask D16 image_load) can feed a low-half read. expect('low half of a register with undefined upper bits', encode(MIX_F32, 1, (v2, v3, v4), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, v2, v3, v4 op_sel_hi:[1,0,0]', - 'v1 = U(f16tof32(v2) * F(v3) + F(v4));', low16_only_v={2}) + 'v1 = U(mix32(f16tof32(v2), F(v3), F(v4)));', low16_only_v={2}) # --- refusals ------------------------------------------------------------------------------------- expect_refused('high half of a register with undefined upper bits', @@ -212,7 +212,7 @@ def expect_refused(label, code, asm, low16_only_v=()): expect('literal on a binary16 source', encode(MIX_F32, 1, (LITERAL, v3, v4), op_sel_hi=(1, 0, 0), literal=0x3c00), 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]', - 'v1 = U(f16tof32(0x3c00u) * F(v3) + F(v4));') + 'v1 = U(mix32(f16tof32(0x3c00u), F(v3), F(v4)));') # The decoder prints neg on inline 1..64 or a literal as a negative integer. Read as an integer, the # sign-bit flip is lost (neg on inline 1 is 0x80000001, not 0xffffffff), so these stay refused. # Inline -1 prints the same text as neg on inline 1, so it is refused too. @@ -236,12 +236,12 @@ def expect_refused(label, code, asm, low16_only_v=()): suffix = (' op_sel:[1,0,0]' if high else '') + ' op_sel_hi:[1,0,0]' expect('select literal half %d' % high, raw, 'v_fma_mix_f32 v1, 0x40003c00, v3, v4' + suffix, - 'v1 = U(f16tof32(0x%04xu) * F(v3) + F(v4));' % bits) + 'v1 = U(mix32(f16tof32(0x%04xu), F(v3), F(v4)));' % bits) expect('inline half on a low binary16 source', encode(MIX_F32, 1, (240, v3, v4), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel_hi:[1,0,0]', - 'v1 = U(0.5 * F(v3) + F(v4));') + 'v1 = U(mix32(0.5, F(v3), F(v4)));') expect_refused('unverified high half of inline constant', encode(MIX_F32, 1, (240, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]') @@ -250,7 +250,7 @@ def expect_refused(label, code, asm, low16_only_v=()): def compile_translated(fxc): """Compile every translated line in one ps_5_1 entry point; returns FXC's exit status and output.""" regs = sorted({int(n) for line in translated for n in re.findall(r'\bv(\d+)\b', line)}) - body = ['#define F asfloat', '#define U asuint', + body = ['#define F asfloat', '#define U asuint', G.MIX32, 'uint main(nointerpolation uint4 p : TEXCOORD0) : SV_Target {', ' uint s5 = p.y;'] body += [' uint v%d = p.x + %du;' % (r, r) for r in regs] @@ -370,9 +370,9 @@ def raw_fill(index): return ((index + 1) * 0x9E3779B1 & 0xffffffff) | 1 -def dispatch_source(rows, lines): +def dispatch_source(rows, lines, helper=G.MIX32): """One thread: per case, load opaque inputs, run the translated line, store v1.""" - body = ['#define F asfloat', '#define U asuint', 'RWByteAddressBuffer data : register(u0);', + body = ['#define F asfloat', '#define U asuint', helper, 'RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] for index, ((_label, words), line) in enumerate(zip(rows, lines)): base = index * 6 @@ -408,6 +408,10 @@ def check_dispatch(dxc, runner, adapter): rows = [(label, case_inputs(label, decode_mix(code))) for label, code, _line in cases] expected = [reference(decode_mix(code), words) for (_l, code, _), (_, words) in zip(cases, rows)] lines = [line for _l, _c, line in cases] + # Information, not a check: 4097 * 4097 = 16785409 rounds to 16785408 in binary32, so a fused mad + # returns 1.0 and an unfused one 0.0. mix32 allows either (#2729). + rows.append(('cancellation', {'v2': f32_word(4097.0), 'v3': f32_word(4097.0), 'v4': f32_word(-16785408.0)})) + lines.append('v1 = U(mix32(F(v2), F(v3), F(v4)));') out_dir = os.path.join(here, '..', 'out') os.makedirs(out_dir, exist_ok=True) with tempfile.TemporaryDirectory(dir=out_dir) as directory: @@ -417,6 +421,18 @@ def check_dispatch(dxc, runner, adapter): got = words[index * 6 + 5] check('%s: %s readback' % (adapter, label), got == expected[index], 'expected %08x, got %08x' % (expected[index], got)) + fused = words[len(cases) * 6 + 5] + print('%s: mad(4097, 4097, -16785408) = %08x (%s)' % ( + adapter, fused, {0x3f800000: 'fused', 0: 'unfused'}.get(fused, 'neither fused nor unfused'))) + # Negative control: a helper that clears the sign of a zero result, as the RDNA 1 and RDNA 4 drivers + # did without precise, must fail exactly the -0 case. + lossy = G.MIX32.replace('return result;', 'return asfloat(asuint(result) == 0x80000000u ? 0u : asuint(result));') + assert lossy != G.MIX32 + lost = run_dispatch(dxc, runner, adapter, dispatch_source(rows, lines, lossy), len(rows) * 6, directory, + 'fma_mix_sign_control') + caught = [label for i, (label, _c, _l) in enumerate(cases) if lost[i * 6 + 5] != expected[i]] + check('%s: control that clears a -0 result fails only the -0 product case' % adapter, + caught == ['negated inline 0 addend keeps a -0 product'], repr(caught)) # Negative control: drop the high-half shift, so the device reads the low half. The readback must # then match a reference with op_sel cleared, and differ from the correct result somewhere. # (A zero product, as in the -0 case, hides the half it reads.) diff --git a/tests/startup_gfx2hlsl_fract_check.py b/tests/startup_gfx2hlsl_fract_check.py index de05a5e1f4..b14174be6c 100644 --- a/tests/startup_gfx2hlsl_fract_check.py +++ b/tests/startup_gfx2hlsl_fract_check.py @@ -170,8 +170,8 @@ def float_capped(word): repr((seed and seed.group(1), literal and literal.group(1)))) check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1), repr((seed and seed.group(1), literal and literal.group(1)))) -check('the revision is x2w-startup-shader-17, after the fix to the cap', - bool(seed and seed.group(1) == 'x2w-startup-shader-17'), repr(seed and seed.group(1))) +check('the revision is x2w-startup-shader-29, after the vcc_hi may-write of the mad64 carry-out', + bool(seed and seed.group(1) == 'x2w-startup-shader-29'), repr(seed and seed.group(1))) def key_from_seed(word): @@ -183,7 +183,7 @@ def key_from_seed(word): check('pipeline_key hashes the seed the source spells', G.pipeline_key(b'vs', b'ps', b'root') == key_from_seed(seed.group(1)), '%016x vs %016x' % (G.pipeline_key(b'vs', b'ps', b'root'), key_from_seed(seed.group(1)))) - old, new = key_from_seed('x2w-startup-shader-16'), key_from_seed('x2w-startup-shader-17') + old, new = key_from_seed('x2w-startup-shader-16'), key_from_seed(seed.group(1)) check('the -16 seed produces a different key, so the pre-fix entries are out of the cache', old != new, '%016x vs %016x' % (old, new)) diff --git a/tests/startup_gfx2hlsl_heap_record_check.py b/tests/startup_gfx2hlsl_heap_record_check.py new file mode 100644 index 0000000000..39fb577bbb --- /dev/null +++ b/tests/startup_gfx2hlsl_heap_record_check.py @@ -0,0 +1,240 @@ +"""A compute program that reads a buffer descriptor from the resource heap record a root constant indexes. + +usage: startup_gfx2hlsl_heap_record_check.py [--llvm-mc <llvm-mc>] + +The root signature has three root constants (s4-s6), one descriptor table (s7) and the directly indexed +resource heap (root flag 0x400, pointer in s8). The program is case A of startup_gfx2hlsl_compute_check.py +with its input descriptor loaded as + + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +after s9 is set to zero. gfx2hlsl.py names that input `srv 0 buf heap rootconst 0 2` in the manifest: the +dispatch reads the 32-byte heap record that root constant word 2 indexes. The HLSL and the manifest are +compared whole. Every other form keeps a refusal: another shift, another index, an index register written +again, a branch target between the shift and the load, a high word that is not a constant zero, an offset +modifier, eight dwords, an index read from a buffer at an offset that differs between groups (named as such; +startup_gfx2hlsl_heap_word_check.py covers the buffer forms that are accepted), a formatted load or a store through +the record, and the graphics stages. --llvm-mc reassembles every instruction used here and compares the words. +""" +import argparse +import struct + +from startup_gfx2hlsl_compute_check import G, TGID_X, TGID_Y, TGID_Z, assemble, refused, tidig + +GROUP, GROUPS = (2, 3, 4), (3, 2, 2) +RSRC2 = (9 << 1) | TGID_X | TGID_Y | TGID_Z | tidig(3) # s0-s3, three constants, the table, the heap pointer +INDEX_WORD = 2 # the root constant word the program shifts + +SHIFT, CLEAR, LOAD = 's_lshl_b32 s6, s6, 5', 's_mov_b32 s9, 0', 's_load_dwordx4 s[16:19], s[8:9], s6' +READ = 'buffer_load_dword v5, v4, s[16:19], 0 offen' +WRITE = 'buffer_store_dword v5, v4, s[20:23], 0 offen' +PROGRAM = ( + 's_mov_b32 s12, s7', 's_mov_b32 s13, 0', 's_load_dwordx4 s[20:23], s[12:13], 0x10', + 's_mov_b32 s14, s9', CLEAR, SHIFT, LOAD, 's_waitcnt lgkmcnt(0)', + 'v_mad_u32_u24 v3, v1, 2, v0', 'v_mad_u32_u24 v3, v2, 6, v3', 's_mul_i32 s24, s10, 3', 's_add_u32 s24, s24, s14', + 's_mul_i32 s25, s11, 6', 's_add_u32 s24, s24, s25', 's_mul_i32 s24, s24, 24', 'v_add_nc_u32 v3, s24, v3', + 'v_lshlrev_b32 v4, 2, v3', READ, 'v_mul_lo_u32 v6, v3, s5', 'v_add_nc_u32 v6, s4, v6', 's_waitcnt vmcnt(0)', + 'v_mul_lo_u32 v5, v5, 33', 'v_xor_b32 v5, v5, v6', WRITE, 's_endpgm') +# Every instruction of the program and of the controls, recorded from llvm-mc 15. +ENCODED = { + 's_mov_b32 s12, s7': '07038cbe', 's_mov_b32 s13, 0': '80038dbe', + 's_load_dwordx4 s[20:23], s[12:13], 0x10': '060508f4100000fa', 's_mov_b32 s14, s9': '09038ebe', + CLEAR: '800389be', SHIFT: '0685068f', LOAD: '040408f40000000c', 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 'v_mad_u32_u24 v3, v1, 2, v0': '030043d501050104', 'v_mad_u32_u24 v3, v2, 6, v3': '030043d5020d0d04', + 's_mul_i32 s24, s10, 3': '0a831893', 's_add_u32 s24, s24, s14': '180e1880', 's_mul_i32 s25, s11, 6': '0b861993', + 's_add_u32 s24, s24, s25': '18191880', 's_mul_i32 s24, s24, 24': '18981893', 'v_add_nc_u32 v3, s24, v3': '1806064a', + 'v_lshlrev_b32 v4, 2, v3': '82060834', READ: '001030e004050480', 'v_mul_lo_u32 v6, v3, s5': '060069d5030b0000', + 'v_add_nc_u32 v6, s4, v6': '040c0c4a', 's_waitcnt vmcnt(0)': '703f8cbf', 'v_mul_lo_u32 v5, v5, 33': '050069d505430100', + 'v_xor_b32 v5, v5, v6': '050d0a3a', WRITE: '001070e004050580', 's_endpgm': '000081bf', + 's_lshl_b32 s6, s6, 4': '0684068f', 's_lshl_b32 s6, s6, 6': '0686068f', 's_lshl_b32 s6, s6, s5': '0605068f', + 's_lshl_b32 s6, s14, 5': '0e85068f', 's_mov_b32 s9, 1': '810389be', 's_mov_b32 s9, s5': '050389be', + 's_load_dwordx4 s[16:19], s[8:9], s6 offset:0x20': '040408f42000000c', + 's_load_dwordx8 s[16:23], s[8:9], s6': '04040cf40000000c', 's_load_dwordx4 s[16:19], s[8:9], s5': '040408f40000000a', + 's_load_dwordx4 s[16:19], s[8:9], m0': '040408f4000000f8', 's_add_u32 s6, s6, 0': '06800680', + 's_load_dwordx4 s[28:31], s[12:13], 0x20': '060708f4200000fa', + 's_buffer_load_dword s6, s[28:31], 0x0': '8e0120f4000000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_buffer_load_dword s26, s[28:31], s14': '8e0620f40000001c', + 's_lshl_b32 s6, s26, 5': '1a85068f', 's_cmp_eq_u32 s4, 0': '048006bf', 's_cbranch_scc0 1': '010084bf', 's_nop 0': '000080bf', + 'buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen': '00100ce004050480', + 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', +} +TABLE_LOAD = 's_load_dwordx4 s[28:31], s[12:13], 0x20' +JUMP = ('s_cmp_eq_u32 s4, 0', 's_cbranch_scc0 1', 's_nop 0') # the instruction after the s_nop is a branch target + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf heap rootconst 0 2 +uav 0 table 1 16 +""" +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +RWByteAddressBuffer u0 : register(u0); +""" +MAIN = """\ +[numthreads(2, 3, 4)] +void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) { + uint s6 = 0, s9 = 0, s10 = 0, s11 = 0, s13 = 0, s14 = 0, s24 = 0, s25 = 0; + uint v0 = 0, v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0, v6 = 0; + uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0; + s9 = gid.x; + s10 = gid.y; + s11 = gid.z; + v0 = tid.x; + v1 = tid.y; + v2 = tid.z; + s13 = 0x00000000u; + s14 = s9; + s9 = 0x00000000u; + s6 = ud2 << (0x00000005u & 31); + scc = s6 != 0; + v3 = (v1 & 0xffffffu) * (0x00000002u & 0xffffffu) + v0; + v3 = (v2 & 0xffffffu) * (0x00000006u & 0xffffffu) + v3; + s24 = s10 * 0x00000003u; + scc = (s24 + s14) < (s24); + s24 = s24 + s14; + s25 = s11 * 0x00000006u; + scc = (s24 + s25) < (s24); + s24 = s24 + s25; + s24 = s24 * 0x00000018u; + v3 = s24 + v3; + v4 = v3 << (0x00000002u & 31); + a = v4 + 0; + v5 = r0.Load(a + 0); + v6 = v3 * ud1; + v6 = ud0 + v6; + v5 = v5 * 0x00000021u; + v5 = v5 ^ v6; + a = (v4 + 0) & 0xfffffffcu; + u0.Store(a, v5); +} +""" + + +def root_blob(table_range=False, flags=0x400): + """RTS0: param 0 = three root constants (b0), param 1 = a descriptor table, the resource heap directly indexed. + table_range gives the table one SRV range, as startup_gfx2hlsl_compute_check.root_blob does for a device.""" + params_at, constants_at = 24, 24 + 2 * 12 + table_at = constants_at + 12 + ranges = struct.pack('<6I', 0, 1, 0, 0, 0, 0xffffffff) if table_range else b'' + rts0 = (struct.pack('<6I', 2, 2, params_at, 0, table_at + 8 + len(ranges), flags) + + struct.pack('<3I', 1, 0, constants_at) + struct.pack('<3I', 0, 0, table_at) + + struct.pack('<3I', 0, 0, 3) + struct.pack('<2I', len(ranges) // 24, table_at + 8) + ranges) + part = b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + return b'DXBC' + bytes(16) + struct.pack('<III', 1, 32 + 4 + len(part), 1) + struct.pack('<I', 36) + part + + +def words(edits=None): + """The program's code; edits maps one of its lines to the lines that take its place.""" + edits = edits or {} + assert set(edits) <= set(PROGRAM), edits + return b''.join(bytes.fromhex(ENCODED[line]) for original in PROGRAM for line in edits.get(original, (original,))) + + +WORDS = words() + + +def pipeline(edits=None, root=None): + return G.ComputePipeline(words(edits), root or root_blob(), RSRC2, GROUP) + + +def check_lowering(): + pipe = pipeline() + hlsl = pipe.hlsl_cs() + assert pipe.manifest() == MANIFEST, pipe.manifest() + assert hlsl.endswith(BINDINGS + MAIN), hlsl[hlsl.index('cbuffer'):] + # A branch target before the shift changes nothing: the form is not tied to the entry block. + assert pipeline({SHIFT: JUMP + (SHIFT,)}).manifest() == MANIFEST + + +def check_refusals(): + not_shifted = 'whose offset is not a root constant shifted left by 5 since the last branch target' + from_buffer = 's_load of a resource heap record whose index is read from a buffer' + high = 'through a pointer whose high word is not a constant zero' + controls = ( + ('shift by 4', {SHIFT: ('s_lshl_b32 s6, s6, 4',)}, not_shifted), + ('shift by 6', {SHIFT: ('s_lshl_b32 s6, s6, 6',)}, not_shifted), + ('shift by a register', {SHIFT: ('s_lshl_b32 s6, s6, s5',)}, not_shifted), + ('no shift', {SHIFT: ()}, not_shifted), + ('a group ID shifted', {SHIFT: ('s_lshl_b32 s6, s14, 5',)}, not_shifted), + ('another register as the offset', {LOAD: ('s_load_dwordx4 s[16:19], s[8:9], s5',)}, not_shifted), + ('m0 as the offset', {LOAD: ('s_load_dwordx4 s[16:19], s[8:9], m0',)}, not_shifted), + ('index register written again', {SHIFT: (SHIFT, 's_add_u32 s6, s6, 0')}, not_shifted), + ('index register loaded from a buffer after the shift', + {SHIFT: (SHIFT, TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], 0x0')}, not_shifted), + ('branch target between the shift and the load', {SHIFT: (SHIFT,) + JUMP}, not_shifted), + ('index read from a buffer at a group-ID offset', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s26, s[28:31], s14', 's_lshl_b32 s6, s26, 5')}, from_buffer), + ('index read from a buffer at a group-ID offset into the shifted register', + {SHIFT: (TABLE_LOAD, 's_buffer_load_dword s6, s[28:31], s14', SHIFT)}, from_buffer), + ('high word 1', {CLEAR: ('s_mov_b32 s9, 1',)}, high), + ('high word a root constant', {CLEAR: ('s_mov_b32 s9, s5',)}, high), + ('high word left as the group ID', {CLEAR: ()}, high), + ('offset modifier', {LOAD: ('s_load_dwordx4 s[16:19], s[8:9], s6 offset:0x20',)}, 'with offset:0x20'), + ('eight dwords', {LOAD: ('s_load_dwordx8 s[16:23], s[8:9], s6',)}, 's_load of a resource heap record of 8 dwords'), + ('formatted load', {READ: ('buffer_load_format_xyzw v[5:8], v4, s[16:19], 0 offen',)}, + 'formatted buffer load requires a hardware table descriptor'), + ('store through the record', {WRITE: ('buffer_store_dword v5, v4, s[16:19], 0 offen',)}, "('resheap', 0, 2)"), + ) + for name, edits, reason in controls: + try: + refused(reason, lambda: pipeline(edits).manifest()) + except AssertionError as error: + raise AssertionError('%s: %s' % (name, error)) from None + # A root signature without the directly indexed heap has no heap pointer: s8 is then a plain user SGPR. + refused('s_load through s8 holding', lambda: pipeline(root=root_blob(flags=0))) + # The graphics stages keep their refusal. + stage = pipeline().cs + stage.kind = 'ps' + stage.heap_index[6] = ('rootconst', 0, INDEX_WORD) + refused("s_load with a register offset through ('resheap',)", + lambda: stage.op_s_load_dwordx4(['s[16:19]', 's[8:9]', 's6'], [])) + # Only a buffer read is named in the manifest; a store or another kind through a record is refused there too. + pipe = pipeline() + key = (('resheap', 0, INDEX_WORD), 0) + assert pipe.resources[key]['kind'] == 'buf' + pipe.resources[key]['kind'] = 'tex2d' + refused("resource through ('resheap', 0, 2)", pipe.manifest) + pipe = pipeline() + pipe.uavs[key] = dict(index=1, kind='raw') + refused("store through ('resheap', 0, 2)", pipe.manifest) + return len(controls) + + +def check_mutations(): + """Translator mutation a control above must catch: without the write tracking the refused control translates.""" + again = {SHIFT: (SHIFT, 's_add_u32 s6, s6, 0')} + saved = G.scalar_destinations + G.scalar_destinations = lambda name, asm: set() if name.startswith('s_add_u32') else saved(name, asm) + try: + assert pipeline(again).manifest() == MANIFEST, 'a write no longer ends the mark, and the control did not change' + finally: + G.scalar_destinations = saved + refused('not a root constant', lambda: pipeline(again)) + + +def check_binary(llvm_mc): + for line, encoded in ENCODED.items(): + assert assemble(llvm_mc, line + '\n') == bytes.fromhex(encoded), line + assert assemble(llvm_mc, '\n'.join(PROGRAM) + '\n') == WORDS + print('heap record fixture: %d instructions reassembled to the recorded words' % len(ENCODED)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + args = parser.parse_args() + if args.llvm_mc: + check_binary(args.llvm_mc) + check_lowering() + count = check_refusals() + check_mutations() + print('startup_gfx2hlsl_heap_record: PASS (manifest and HLSL exact; %d refused controls; graphics, manifest and ' + 'translator-mutation checks)' % count) diff --git a/tests/startup_gfx2hlsl_heap_word_check.py b/tests/startup_gfx2hlsl_heap_word_check.py new file mode 100644 index 0000000000..afe2aa29f7 --- /dev/null +++ b/tests/startup_gfx2hlsl_heap_word_check.py @@ -0,0 +1,161 @@ +"""A compute program whose resource heap record index is a word it reads from a table buffer. + +usage: startup_gfx2hlsl_heap_word_check.py [--llvm-mc <llvm-mc>] + +The program of startup_gfx2hlsl_heap_record_check.py with its index no longer the root constant itself: root constant +word 2 picks the byte offset of a word in the buffer of table byte 96, and that word is the index: + + s_load_dwordx4 s[28:31], s[12:13], 0x60 + s_mulk_i32 s6, 0x150 + s_add_u32 s6, s6, 0x120 + s_buffer_load_dword s6, s[28:31], s6 + s_lshl_b32 s6, s6, 5 + s_load_dwordx4 s[16:19], s[8:9], s6 + +gfx2hlsl.py names that input `srv 1 buf heap word table 1 96 at 288 rootconst 0 2 times 336`: the dispatch reads the +word at byte 288 + 336 * (root constant word 2) of that buffer, then the 32-byte heap record it indexes. The byte +offset is the same for every thread of the dispatch. A literal byte offset, an offset modifier, s_mul_i32 and +s_addk_i32 and a later word of a wider load give the same line with their own numbers; the HLSL and the manifest of +the first form are compared whole. Every other form keeps a refusal: an offset from the group ID, an offset read +from a buffer, a scale or a byte offset that is not a multiple of 4, a register added after the arithmetic, a +modified descriptor, and a branch target between the arithmetic and the load. --llvm-mc reassembles every +instruction used here and compares the words. +""" +import argparse + +import startup_gfx2hlsl_heap_record_check as H +from startup_gfx2hlsl_compute_check import G, assemble, refused + +TABLE = 's_load_dwordx4 s[28:31], s[12:13], 0x60' +SCALE, ADD = 's_mulk_i32 s6, 0x150', 's_add_u32 s6, s6, 0x120' +READ_INDEX = 's_buffer_load_dword s6, s[28:31], s6' +WAIT = 's_waitcnt lgkmcnt(0)' +INDEX = (TABLE, SCALE, ADD, WAIT, READ_INDEX, WAIT, H.SHIFT) +# Every instruction added here, recorded from llvm-mc 15. +ENCODED = { + TABLE: '060708f4600000fa', SCALE: '500106b8', ADD: '06ff068020010000', READ_INDEX: '8e0120f40000000c', + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6': '8e0624f40000000c', 's_lshl_b32 s6, s27, 5': '1b85068f', + 's_buffer_load_dword s6, s[28:31], 0x40': '8e0120f4400000fa', 's_buffer_load_dword s6, s[28:31], s14': '8e0120f40000001c', + 's_mulk_i32 s6, 0x152': '520106b8', 's_add_u32 s6, s6, 0x122': '06ff068022010000', + 's_and_b32 s29, s29, 0xffff': '1dff1d87ffff0000', 's_add_u32 s6, s6, s14': '060e0680', + 's_mul_i32 s6, s6, s5': '06050693', 's_mul_i32 s6, s6, 0x150': '06ff069350010000', 's_addk_i32 s6, 0x120': '200186b7', + 's_buffer_load_dword s6, s[28:31], s6 offset:0x10': '8e0120f41000000c', +} +ALL = {**H.ENCODED, **ENCODED} + +MANIFEST = """\ +x2w-manifest 2 +stage cs +group 2 3 4 +ud 3 +udsrc 0 rootconst 0 0 +udsrc 1 rootconst 0 1 +udsrc 2 rootconst 0 2 +srv 0 buf table 1 96 +srv 1 buf heap word table 1 96 at %s +uav 0 table 1 16 +""" +FORM = '288 rootconst 0 2 times 336' +BINDINGS = """\ +cbuffer entry : register(b0) { uint ud0; uint ud1; uint ud2; }; +ByteAddressBuffer r0 : register(t0); +ByteAddressBuffer r1 : register(t1); +RWByteAddressBuffer u0 : register(u0); +""" +# The heap record program's body with the index read through r0 (the table buffer) and the input through r1. +MAIN = H.MAIN.replace(' s6 = ud2 << (0x00000005u & 31);\n', """\ + s6 = ud2 * 0x00000150u; + scc = (s6 + 0x00000120u) < (s6); + s6 = s6 + 0x00000120u; + s6 = r0.Load(s6 + 0); + s6 = s6 << (0x00000005u & 31); +""").replace('v5 = r0.Load(a + 0);', 'v5 = r1.Load(a + 0);') +assert MAIN.count('r0.Load') == 1 and MAIN.count('r1.Load') == 1 + + +def words(index=INDEX): + """The heap record program with the index lines in place of its shift.""" + return b''.join(bytes.fromhex(ALL[line]) for original in H.PROGRAM + for line in (index if original == H.SHIFT else (original,))) + + +WORDS = words() + + +def pipeline(index=INDEX): + return G.ComputePipeline(words(index), H.root_blob(), H.RSRC2, H.GROUP) + + +def replace(old, *new): + assert old in INDEX + return tuple(line for original in INDEX for line in (new if original == old else (original,))) + + +def check_lowering(): + pipe = pipeline() + hlsl = pipe.hlsl_cs() + assert pipe.manifest() == MANIFEST % FORM, pipe.manifest() + assert hlsl.endswith(BINDINGS + MAIN), hlsl[hlsl.index('cbuffer'):] + forms = ( + ('literal byte offset', (TABLE, WAIT, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, H.SHIFT), '64'), + ('offset modifier', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s6 offset:0x10'), + '304 rootconst 0 2 times 336'), + ('s_mul_i32 and s_addk_i32', replace(ADD, 's_addk_i32 s6, 0x120'), FORM), + ('s_mul_i32 by a literal', replace(SCALE, 's_mul_i32 s6, s6, 0x150'), FORM), + ('second word of a wider load', replace(H.SHIFT, 's_lshl_b32 s6, s27, 5')[:4] + ( + 's_buffer_load_dwordx2 s[26:27], s[28:31], s6', WAIT, 's_lshl_b32 s6, s27, 5'), '292 rootconst 0 2 times 336'), + # A branch target before the arithmetic changes nothing. + ('branch target before the arithmetic', (TABLE,) + H.JUMP + INDEX[1:], FORM), + ) + for name, index, form in forms: + got = pipeline(index).manifest() + assert got == MANIFEST % form, '%s:\n%s' % (name, got) + return len(forms) + + +def check_refusals(): + other = ('s_load of a resource heap record whose index is read from a buffer other than a table buffer at a ' + 'dispatch-constant offset') + controls = ( + ('offset from the group ID', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], s14')), + ('offset read from a buffer', replace(READ_INDEX, 's_buffer_load_dword s6, s[28:31], 0x40', WAIT, READ_INDEX)), + ('scale not a multiple of 4', replace(SCALE, 's_mulk_i32 s6, 0x152')), + ('byte offset not a multiple of 4', replace(ADD, 's_add_u32 s6, s6, 0x122')), + ('a register added after the arithmetic', replace(ADD, ADD, 's_add_u32 s6, s6, s14')), + ('scaled by a register', replace(SCALE, 's_mul_i32 s6, s6, s5')), + ('modified descriptor', replace(TABLE, TABLE, WAIT, 's_and_b32 s29, s29, 0xffff')), + ('branch target between the arithmetic and the load', replace(ADD, ADD, *H.JUMP)), + ) + for name, index in controls: + try: + refused(other, lambda: pipeline(index).manifest()) + except AssertionError as error: + raise AssertionError('%s: %s' % (name, error)) from None + # A branch target between the load and the shift ends the word's mark, as for a root constant. + refused('whose offset is not a root constant shifted left by 5', + lambda: pipeline(replace(READ_INDEX, READ_INDEX, *H.JUMP)).manifest()) + # Only a buffer read is named in the manifest; another kind through such a record is refused there. + pipe = pipeline() + key = next(k for k in pipe.resources if k[0][:2] == ('resheap', 'word')) + pipe.resources[key]['kind'] = 'tex2d' + refused("resource through ('resheap', 'word'", pipe.manifest) + return len(controls) + 2 + + +def check_binary(llvm_mc): + for line, encoded in ENCODED.items(): + assert assemble(llvm_mc, line + '\n') == bytes.fromhex(encoded), line + text = [line for original in H.PROGRAM for line in (INDEX if original == H.SHIFT else (original,))] + assert assemble(llvm_mc, '\n'.join(text) + '\n') == WORDS + print('heap word fixture: %d instructions reassembled to the recorded words' % len(ENCODED)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + args = parser.parse_args() + if args.llvm_mc: + check_binary(args.llvm_mc) + forms = check_lowering() + count = check_refusals() + print('startup_gfx2hlsl_heap_word: PASS (manifest and HLSL exact; %d more forms; %d refused controls)' % (forms, count)) diff --git a/tests/startup_gfx2hlsl_image_1d_check.py b/tests/startup_gfx2hlsl_image_1d_check.py new file mode 100644 index 0000000000..d24436c815 --- /dev/null +++ b/tests/startup_gfx2hlsl_image_1d_check.py @@ -0,0 +1,211 @@ +"""1D image sampling in tools/startup/gfx2hlsl.py (issue #1721). + +usage: startup_gfx2hlsl_image_1d_check.py [draw <dxc> <offscreen_check> <warp|hardware>] + +A 1D image has one coordinate, and `image_sample_lz` / `image_sample_l` carry the explicit level in the next +address dword. The translator accepted 1D only for the implicit-level `image_sample`, so the two explicit-level +forms were refused - 2 of the 29 refused shaders in the first loading-screen cache (#870). + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, MIMG branch): + w0: [31:26] = 0b111100, [24:18] opcode low 7 bits, [0] opcode bit 7, [11:8] dmask, [5:3] dimension, + [2:1] NSA dword count, [12] unorm, [15] r128 + w1: [7:0] vaddr, [15:8] vdata, [20:16] srsrc/4, [25:21] sampler/4 +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +IMG_LOAD = 0x00 +IMG_SAMPLE = 0x20 +IMG_SAMPLE_L = 0x24 +IMG_SAMPLE_LZ = 0x27 +DIM_1D = 0 +DIM_2D = 1 + + +def encode_mimg(op, *, dmask=0xF, dim=DIM_1D, vaddr=0, vdata=4, srsrc=8, ssamp=12, nsa=0, + extra_addrs=(), unorm=0, r128=0, glc=0, slc=0, dlc=0): + """Encode one MIMG instruction; returns its bytes (8 + 4 per NSA dword).""" + w0 = ((0b111100 << 26) | ((op & 0x7F) << 18) | (((op >> 7) & 1) << 0) + | ((dmask & 0xF) << 8) | ((dim & 0x7) << 3) | ((nsa & 0x3) << 1) + | ((unorm & 1) << 12) | ((r128 & 1) << 15) | ((dlc & 1) << 7) + | ((glc & 1) << 13) | ((slc & 1) << 25)) + w1 = ((vaddr & 0xFF) | ((vdata & 0xFF) << 8) | (((srsrc // 4) & 0x1F) << 16) + | (((ssamp // 4) & 0x1F) << 21)) + return struct.pack('<II', w0, w1) + bytes(extra_addrs) + + +class Pipeline: + """Just enough pipeline state for an image sample.""" + + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + self.lod_unvalidated = set() + self.uses_sampler_heap = False + + def resource(self, key, kind): + entry = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + return 'r%d' % entry['index'] + + def sampler(self, key, comparison=False, lod_limits=False): + return 'smp%d' % (1 if comparison else 0) + + def ud(self, source): + return 0 + + +class Stage(G.Stage): + """A Stage with a bound image descriptor and a constant sampler, as a pixel shader would have.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports = {} + self.pipe = Pipeline() + self.kind = 'ps' + self.blocks = [] + self.sym[8] = ('desc', 'image0', None, 0) + for i in range(4): + self.sym[12 + i] = ('const', 0) + + +def translate(code): + decoded = G.decode(code) + stage = Stage() + for _offset, _size, name, asm in decoded: + stage.one(name, asm) + return [asm for _o, _s, _n, asm in decoded], ' '.join(stage.lines) + + +def refused(code): + try: + translate(code) + except G.Unsupported as error: + return 'Unsupported' in type(error).__name__ + return False + + +# 1. The encoder produces the form the decoder reads; a layout change shows up here first. +asm, emitted = translate(encode_mimg(IMG_SAMPLE_LZ, dmask=0xF, dim=DIM_1D, vdata=4)) +check('encodes and decodes a 1D sample_lz', + asm == ['image_sample_lz v[4:7], v0, s[8:15], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_1D'], repr(asm)) + +# 2. A 1D sample takes a single float location; the level is zero for the lz form. +check('1D sample_lz samples level zero', 't = r0.SampleLevel(smp0, F(v0), 0);' in emitted, emitted) + +# 3. image_sample_l takes the explicit level from the second address dword. +asm, emitted = translate(encode_mimg(IMG_SAMPLE_L, dmask=0x7, dim=DIM_1D, vdata=4)) +check('encodes and decodes a 1D sample_l', + asm == ['image_sample_l v[4:6], v[0:1], s[8:15], s[12:15] dmask:0x7 dim:SQ_RSRC_IMG_1D'], repr(asm)) +check('1D sample_l takes the level from the address', 't = r0.SampleLevel(smp0, F(v0), F(v1));' in emitted, emitted) + +# 4. The implicit-level form is unchanged. +asm, emitted = translate(encode_mimg(IMG_SAMPLE, dmask=0x3, dim=DIM_1D, vdata=4)) +check('1D sample still samples implicitly', 't = r0.Sample(smp0, F(v0));' in emitted, emitted) +check('dmask selects the written channels', emitted.endswith('v4 = U(t.x); v5 = U(t.y);'), emitted) + +# 5. A 2D sample is untouched by the 1D rules. +asm, emitted = translate(encode_mimg(IMG_SAMPLE_LZ, dmask=0xF, dim=DIM_2D, vdata=4)) +check('2D sample_lz still uses a float2 location', 'SampleLevel(smp0, float2(F(v0), F(v1)), 0)' in emitted, emitted) + +# 6. Refusals that must not widen: a 1D load (its address packing is a different slice), a 1D sample_lz with +# two address dwords, and a modifier that would change the address or result layout. +check('1D image_load stays refused', + refused(encode_mimg(IMG_LOAD, dmask=0xF, dim=DIM_1D, vdata=4))) +check('1D sample_lz with two address dwords stays refused', + refused(encode_mimg(IMG_SAMPLE_LZ, dmask=0xF, dim=DIM_1D, vdata=4, nsa=1, extra_addrs=(1,)))) +check('a unorm 1D sample_lz stays refused', + refused(encode_mimg(IMG_SAMPLE_LZ, dmask=0xF, dim=DIM_1D, vdata=4, unorm=1))) + +# 7. The cache-policy bits and the dmask guard are what the 1D rules decide, so each is pinned: the plain +# implicit-level form keeps its old rule and still refuses a cache bit, an empty dmask is refused, and a +# cache bit on the lz/l forms lowers to the same text as without it (the policies do not change the value). +check('a glc 1D sample stays refused', + refused(encode_mimg(IMG_SAMPLE, dmask=0x3, dim=DIM_1D, vdata=4, glc=1))) +check('a 1D sample_lz with an empty dmask is refused', + refused(encode_mimg(IMG_SAMPLE_LZ, dmask=0x0, dim=DIM_1D, vdata=4))) +_plain_lz = translate(encode_mimg(IMG_SAMPLE_LZ, dmask=0xF, dim=DIM_1D, vdata=4))[1] +_plain_l = translate(encode_mimg(IMG_SAMPLE_L, dmask=0x7, dim=DIM_1D, vdata=4))[1] +for _bit, _value in (('glc', 1), ('slc', 1), ('dlc', 1)): + _cache_lz = translate(encode_mimg(IMG_SAMPLE_LZ, dmask=0xF, dim=DIM_1D, vdata=4, **{_bit: _value}))[1] + check('a %s 1D sample_lz lowers like the plain one' % _bit, _cache_lz == _plain_lz, _cache_lz) + _cache_l = translate(encode_mimg(IMG_SAMPLE_L, dmask=0x7, dim=DIM_1D, vdata=4, **{_bit: _value}))[1] + check('a %s 1D sample_l lowers like the plain one' % _bit, _cache_l == _plain_l, _cache_l) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') + + +def draw(dxc, renderer, adapter): + from startup_image_3d_check import FULLSCREEN_VS, WORDS_1D, compile_hlsl, translate as translate_pair + + # Use the existing Texture1D draw, with v1 reading the provided root constant for the explicit LOD. + sample = encode_mimg(IMG_SAMPLE, vdata=0, srsrc=16, ssamp=24) + words = WORDS_1D.replace(bytes.fromhex('ff02027e0000803e'), bytes.fromhex('0902027e')) + assert sample in words + + def texel(level): + x = (4 >> level) * 3 // 4 + rgba = ((1 + x + 32 * level) / 128, x, 0, 0.75 if x else 0.5) + return ','.join(f'{struct.unpack("<I", struct.pack("<f", c))[0]:08x}' for c in rgba) + + with tempfile.TemporaryDirectory() as scratch: + directory = Path(scratch) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + for opcode, label in [(IMG_SAMPLE_LZ, 'lz'), (IMG_SAMPLE_L, 'l')]: + pipe = translate_pair(words.replace(sample, encode_mimg(opcode, vdata=0, srsrc=16, ssamp=24))) + shader = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), label, 'ps_6_0', directory) + + def read(program, lod, expected): + args = [renderer, adapter, '--startup-image-1d-mips', str(vs), str(program), str(lod), texel(expected)] + run = subprocess.run(args, capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + for lod in (1, 2): + level = lod if label == 'l' else 0 + run = read(shader, lod, level) + assert run.returncode == 0, run.stdout + run.stderr + print(run.stdout, end='') + print(f'{adapter} sample_{label} LOD input {lod}: matched mip {level}') + if label == 'l': + source = pipe.hlsl_ps() + mutant = source.replace('SampleLevel(q0, F(v0), F(v1))', 'SampleLevel(q0, F(v0), 0.0)') + assert mutant != source, source + wrong = compile_hlsl(dxc, 'dxc', mutant, 'fixed_zero', 'ps_6_0', directory) + wrong_zero = read(wrong, 2, 2) + assert wrong_zero.returncode == 1 and 'actual=' + texel(0) in wrong_zero.stderr, wrong_zero.stderr + print(f'{adapter} fixed-zero shader read mip zero where mip two was expected') + + +if len(sys.argv) > 1: + if len(sys.argv) != 5 or sys.argv[1] != 'draw': + sys.exit(__doc__) + draw(*sys.argv[2:]) diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index e9443d9ca1..c6a13633dc 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -1,18 +1,30 @@ -"""image_get_lod on a 2D texture in tools/startup/gfx2hlsl.py. +"""image_get_lod on a 2D texture and a 2D array in tools/startup/gfx2hlsl.py (M200-01 L). image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp (Mesa nir_texop_lod, emitted by ACO as image_get_lod; GLSL textureQueryLod x/y). It is lowered to HLSL CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped, which take implicit derivatives like Sample, so the stage -must be a pixel stage, straight-line, with every lane active. The clamped value depends on the sampler's LOD limits -and bias, so the sampler must be a constant descriptor under the validation of image_sample_b. +must be a pixel stage whose EXEC is still the entry mask (every lane active) with wave-uniform control flow. A +uniform (scc) join or later loop does not drop that proof; divergent EXEC or a vcc/exec-conditioned branch before +the read does. The clamped value depends on the sampler's LOD limits and bias, so the sampler must be a constant +descriptor under the validation of image_sample_b. + +The 2D-array form (dim:SQ_RSRC_IMG_2D_ARRAY) takes a third address dword, the slice, which the decoder reads +back. DXIL CalculateLOD uses two active coordinates (c0, c1) for Texture2DArray -- the slice is not part of the +LOD -- and HLSL's Texture2DArray CalculateLevelOfDetail takes float2, so the slice register is consumed but +dropped from the call: Texture2DArray r0 queried at float2(u, v), exactly the two-component coordinate of +glslang's hlsl.calculatelod.dx10.frag ("LOD queries do not pass array level in coordinate"). Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x60 -(image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip -filter point), and for the second form dmask 0x3. -Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. Controls (refused): -dmask 0x4, a 2D array, a branch before the read, a sampler LOD bias, a sampler with mipmapping disabled, and the -stage without op_image_get_lod (negative control: refused as on main). - draw <dxc> [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). +(image_get_lod; the decoder reads it back with a 2-register, or 3-register for the array, address), sampler +word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. The array fixture keeps the +original v2 = 1.0 as its slice dword; a variant swaps the slice register pair so the consumed dword is proven +to come from the address position, not the register number. +Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits, on a 2D +texture and a 2D array (Texture2DArray r0, srv tex2da, slice dropped). A uniform join before the read is +accepted on both. Controls (refused): dmask 0x4, a 3D image, s_cbranch_vccz/execz before the read (2D and +array), a sampler LOD bias, a sampler with mipmapping disabled, an array decoded with two address registers, +and the stage without op_image_get_lod (negative control: refused as on main). + draw <dxc> [fxc]: also compile the dmask 0x3 2D and 2D-array stages with dxc ps_6_0 (and fxc ps_5_1). """ import struct import subprocess @@ -34,18 +46,38 @@ MIP_POINT = 1 << 26 # SQ_IMG_SAMP_WORD2 bits 27:26 MIP_FILTER -def stage(dmask=1, dim=1, branch=False, word2=MIP_POINT): +def sopp(op, simm): + return struct.pack('<I', (simm & 0xffff) | op << 16 | 0x17f << 23) + + +def stage(dmask=1, dim=1, branch=False, divergent=False, join=False, cf_op=None, word2=MIP_POINT, back_op=None, + nsa=None): w = bytearray(C.WORDS['lz']) assert w[W2_AT:W2_AT + 4] == bytes.fromhex('80039abe'), w[W2_AT:W2_AT + 4].hex() w[W2_AT:W2_AT + 4] = struct.pack('<II', 0xbe9a03ff, word2) # s_mov_b32 s26, literal w0, w1 = struct.unpack_from('<II', w, AT) w0 = w0 & ~(0x7f << 18) & ~(0xf << 8) & ~(7 << 3) | 0x60 << 18 | dmask << 8 | dim << 3 - struct.pack_into('<II', w, AT, w0, w1) if dmask == 3: # export v4, v5 struct.pack_into('<II', w, EXPORT_AT, 0xf800180f, 4 | 5 << 8 | 4 << 16 | 5 << 24) + if nsa is not None: # nsize 1: one NSA dword whose first bytes give the address registers after vaddr0 + w0 = w0 & ~0x6 | 1 << 1 + struct.pack_into('<II', w, AT, w0, w1) + return bytes(w[:AT + 8]) + bytes(nsa) + bytes(w[AT + 8:]) + struct.pack_into('<II', w, AT, w0, w1) code = bytes(w) - if branch: # s_cbranch_scc0 to the next instruction: control flow before the read - code = code[:AT] + struct.pack('<I', 0xbf840000) + code[AT:] + if back_op is not None: # s_cbranch_<op> right after the read, back to it (a divergent back edge spanning the read) + code = code[:AT + 8] + sopp(back_op, -3) + code[AT + 8:] + insert = b'' + if branch: # s_cbranch_scc0 to the next instruction: uniform control flow before the read + insert += sopp(4, 0) + if join: # uniform forward join; every lane still has the entry EXEC at the read + insert += (bytes.fromhex('800380be') + bytes.fromhex('008006bf') + sopp(5, 1) + bytes.fromhex('810381be')) + if divergent: # s_mov_b64 exec, 0: the entry-mask proof is gone + insert += bytes.fromhex('8004febe') + if cf_op is not None: # s_mov; s_cbranch_<op> +1; s_mov (vcc/exec: divergent CF) + insert += bytes.fromhex('800380be') + sopp(cf_op, 1) + bytes.fromhex('810381be') + if insert: + code = code[:AT] + insert + code[AT:] return code @@ -74,9 +106,54 @@ def controls(): assert call in text and 'v4 = U(t.x);' in text and 'v5 = U(t.y);' in text, text _, text = ps(stage(dmask=2)) # the unclamped LOD alone lands in the first destination register assert call in text and 'v4 = U(t.y);' in text and 'U(t.x)' not in text, text + _, text = ps(stage(branch=True)) + assert call in text and 'v4 = U(t.x);' in text, text + _, text = ps(stage(join=True)) + assert call in text and 'v4 = U(t.x);' in text, text refused(stage(dmask=4), 'image_get_lod form') - refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY - refused(stage(branch=True), 'image_get_lod needs implicit derivatives') + refused(stage(dim=2), 'image_get_lod form') # SQ_RSRC_IMG_3D + # The 2D-array form: Texture2DArray, the slice consumed and dropped from the float2 coordinate. + array_call = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v0), F(v1))), ' + 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v0), F(v1))), 0.0, 0.0);') + listing = [a for _, _, _, a in G.decode(stage(dim=5))] + assert 'image_get_lod v4, v[0:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY' in listing, listing + array_pipe, text = ps(stage(dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + assert 'Texture2DArray<float4> r0 : register(t0);' in text and 'Texture2D<' not in text, text + assert 'srv 0 tex2da table 0 0' in array_pipe.manifest(), array_pipe.manifest() + assert 'smpl 0 0x8001012 0x0 0x4000000 0x0' in array_pipe.manifest(), array_pipe.manifest() + _, text = ps(stage(dmask=3, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text and 'v5 = U(t.y);' in text, text + _, text = ps(stage(dmask=2, dim=5)) + assert array_call in text and 'v4 = U(t.y);' in text and 'U(t.x)' not in text, text + code = stage(dmask=3, dim=5, nsa=[1, 3, 0, 0]) + listing = [a for _, _, _, a in G.decode(code)] + assert 'image_get_lod v[4:5], [v0, v1, v3], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY' in listing, listing + _, text = ps(code) + assert array_call in text and 'F(v2)' not in text and 'F(v3)' not in text, text + _, text = ps(stage(branch=True, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + _, text = ps(stage(join=True, dim=5)) + assert array_call in text and 'v4 = U(t.x);' in text, text + for op in (7, 9): # vccnz, execnz back edge after the array read + refused(stage(dim=5, back_op=op), 'image_get_lod needs implicit derivatives') + for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz + refused(stage(dim=5, cf_op=op), 'image_get_lod needs implicit derivatives') + refused(stage(dim=5, word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') + refused(stage(dim=5, word2=0), 'image_get_lod with mipmapping disabled') + # An array decoded with two address registers is refused (the slice dword would be unread). + original = G.D.MIMG_DIMS[5] + G.D.MIMG_DIMS[5] = (original[0], 2, original[2]) + try: + refused(stage(dim=5), 'image_get_lod form') + finally: + G.D.MIMG_DIMS[5] = original + _, text = ps(stage(divergent=True)) # a cleared EXEC is an exact per-lane write: the quad program keeps the proof + assert call in text, text + for op in (7, 9): # vccnz, execnz back edge after the read + refused(stage(back_op=op), 'image_get_lod needs implicit derivatives') + for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz + refused(stage(cf_op=op), 'image_get_lod needs implicit derivatives') refused(stage(word2=MIP_POINT | 1), 'image_get_lod with a sampler LOD bias') refused(stage(word2=0), 'image_get_lod with mipmapping disabled') saved = G.Stage.op_image_get_lod @@ -85,25 +162,30 @@ def controls(): refused(stage(), 'image_get_lod') finally: G.Stage.op_image_get_lod = saved - print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; dmask 0x4, a 2D array, a branch, ' - 'a sampler bias and a sampler without mipmapping refused; refused without the handler') + print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3 on a 2D texture and a 2D ' + 'array (Texture2DArray, slice consumed and dropped from the float2 coordinate, manifest srv tex2da, NSA ' + 'address); uniform join/branch before the read accepted on both, also after a cleared EXEC; dmask 0x4, a ' + '3D image, vcc/exec branches, a sampler bias and a sampler without mipmapping refused on both, an array ' + 'with two address registers refused; refused without the handler') return pipe def compile_check(dxc, fxc=None): - _, text = ps(stage(dmask=3)) with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / 'ps.hlsl' - path.write_text(text) - runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / 'a.cso'), str(path)])] - if fxc: - runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(Path(tmp) / 'b.cso'), - str(path)])) - for kind, args in runs: - r = subprocess.run(args, capture_output=True, text=True, timeout=60) - if r.returncode: - raise AssertionError('%s: %s' % (kind, r.stderr[-1500:])) - print('%s compiles the dmask 0x3 stage' % kind) + for name, text in (('2D', ps(stage(dmask=3))[1]), ('2D array', ps(stage(dmask=3, dim=5))[1])): + slug = name.replace(' ', '_') + path = Path(tmp) / ('ps_%s.hlsl' % slug) + path.write_text(text) + runs = [('dxc', [dxc, '-T', 'ps_6_0', '-E', 'main', '-Fo', str(Path(tmp) / ('%s.cso' % slug)), + str(path)])] + if fxc: + runs.append(('fxc', [fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', + str(Path(tmp) / ('%s_fxc.cso' % slug)), str(path)])) + for kind, args in runs: + r = subprocess.run(args, capture_output=True, text=True, timeout=60) + if r.returncode: + raise AssertionError('%s (%s): %s' % (kind, name, r.stderr[-1500:])) + print('%s compiles the dmask 0x3 %s stage' % (kind, name)) def main(): diff --git a/tests/startup_gfx2hlsl_image_store_3d1d_check.py b/tests/startup_gfx2hlsl_image_store_3d1d_check.py new file mode 100644 index 0000000000..9d892e749a --- /dev/null +++ b/tests/startup_gfx2hlsl_image_store_3d1d_check.py @@ -0,0 +1,88 @@ +"""Check full compute image stores to 1D and 3D texture UAVs.""" +import argparse + +import startup_compute_image_store_check as A +from startup_gfx2hlsl_compute_check import G, assemble, refused, root_blob +from startup_pixel_image_store_check import WORDS as PIXEL_WORDS, translate as pixel_pipeline + + +FORMS = { + 'volume': ('3D', 'v[2:4]', 's[16:23]', '101f20f002080400', 'uint3(v2, v3, v4)'), + 'volume-nsa': ('3D', '[v2, v3, v5]', 's[16:23]', '121f20f00208040003050000', 'uint3(v2, v3, v5)'), + 'line': ('1D', 'v0', 's[8:15]', '001f20f000080200', 'uint(v0)'), +} +VALUES = A.ARRAY_VALUES +DATA = bytes.fromhex( + 'ff02107e0000403f' # v_mov_b32_e32 v8, 0x3f400000 + 'ff02127e0000803e' # v_mov_b32_e32 v9, 0x3e800000 + 'ff02147e00008140' # v_mov_b32_e32 v10, 0x40810000 + 'ff02167e010081bf' # v_mov_b32_e32 v11, 0xbf810001 +) + + +def group(form): + return (4, 1, 1) if form == 'line' else A.fixture.GROUP + + +def program(form, store=None): + # s[12:13] is the fixed table pointer. Compute the global X before the 1D descriptor overwrites s10. + prefix = bytes.fromhex('07038cbe80038dbe') # s_mov_b32 s12, s7; s_mov_b32 s13, 0 + if form == 'line': + address = bytes.fromhex( + '000046d70a040104' # v_lshl_add_u32 v0, s10, 2, v0 + '06020cf4400000fa' # s_load_dwordx8 s[8:15], s[12:13], 0x40 + ) + else: + address = bytes.fromhex( + '06040cf4400000fa' # s_load_dwordx8 s[16:23], s[12:13], 0x40 + '020046d70a040104' # v_lshl_add_u32 v2, s10, 2, v0 + '030046d70b020504' # v_lshl_add_u32 v3, s11, 1, v1 + ) + address += bytes.fromhex('81020a7e' if form == 'volume-nsa' else '8102087e') # z = 1 + instruction = bytes.fromhex(FORMS[form][3]) if store is None else store + return prefix + address + bytes.fromhex('7fc08cbf') + DATA + instruction + A.ARRAY_END + + +def pipeline(form, store=None): + return G.ComputePipeline(program(form, store), root_blob(3), A.RSRC2, group(form)) + + +def controls(llvm_mc): + ps = pixel_pipeline(PIXEL_WORDS).ps + for form, (dim, address, descriptor, words, index) in FORMS.items(): + dim_mod = f'dim:SQ_RSRC_IMG_{dim}' + asm = f'image_store v[8:11], {address}, {descriptor} dmask:0xf {dim_mod} unorm' + store = bytes.fromhex(words) + assert G.D.decode_instruction(store, 0)[2] == asm + if llvm_mc: + assert assemble(llvm_mc, asm + '\n') == store, asm + pipe = pipeline(form) + hlsl, manifest = pipe.hlsl_cs(), pipe.manifest() + # Manual mutants: dropping the third coordinate or mapping 1D to 2D must fail these assertions. + assert f'RWTexture{dim}<float4> w0 : register(u0);' in hlsl, hlsl + assert f'w0[{index}] = asfloat(uint4(v8, v9, v10, v11));' in hlsl, hlsl + assert f'uav 0 tex{dim.lower()} float table 1 64 channels 4' in manifest.splitlines(), manifest + mods = ['dmask:0xf', dim_mod, 'unorm'] + refused('only 2D images', lambda: ps.op_image_store(['v[8:11]', address, descriptor], mods)) + wrong_width = 'v[0:1]' + refused('with 2 address registers', lambda: pipe.cs.op_image_store(['v[8:11]', wrong_width, descriptor], mods)) + for d16 in (False, True): + partial = bytearray(store) + partial[1] = (partial[1] & 0xf0) | 0x3 + if d16: + partial[7] |= 0x80 + refused('typed UAV store writes all four channels', lambda: pipeline(form, bytes(partial))) + # d16 with the full mask takes the same packed-half path as 2D: two data VGPRs unpacked low half first. + # Manual mutant: dropping the f16tof32 unpack for these kinds must fail this assertion. + packed = bytearray(store) + packed[7] |= 0x80 + d16_hlsl = pipeline(form, bytes(packed)).hlsl_cs() + d16_store = f'w0[{index}] = float4(f16tof32(v8 & 0xffffu), f16tof32(v8 >> 16), f16tof32(v9 & 0xffffu), f16tof32(v9 >> 16));' + assert d16_store in d16_hlsl, d16_hlsl + print('Compute 1D, 3D and 3D NSA stores, d16 full-mask stores, manifest and refusal checks passed') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--llvm-mc') + controls(parser.parse_args().llvm_mc) diff --git a/tests/startup_gfx2hlsl_int3_alu_check.py b/tests/startup_gfx2hlsl_int3_alu_check.py new file mode 100644 index 0000000000..f5c3906dc8 --- /dev/null +++ b/tests/startup_gfx2hlsl_int3_alu_check.py @@ -0,0 +1,79 @@ +"""Three-source integer vector operations of tools/startup/gfx2hlsl.py (its VEC_U table). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the pixel bodies and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_bfe_u32, v_mad_u32_u24, v_lshl_add_u32, v_add_lshl_u32, v_add3_u32, v_or3_b32, v_and_or_b32, +v_lshl_or_b32, v_xad_u32 and v_bfi_b32, which no check ran before. All ten are VOP3 only. The fixture and runner +are startup_gfx2hlsl_lane_alu.py: one operation per lane on flat parameters the compilers cannot fold. The references +follow the AMD RDNA 2 ISA reference with plain integer arithmetic: an unsigned field of width S2[4:0] at offset +S1[4:0] for v_bfe_u32, the low 24 bits of S0 and S1 for v_mad_u32_u24, shift counts taken from bits 4:0, 32-bit +wrapping sums and the bitfield insert (S0 & S1) | (~S0 & S2). +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import MASK, main, words # noqa: E402 + +M24 = 0xffffff +OPS = { + 'v_bfe_u32': (3, lambda a, b, c: (a >> (b & 31)) & ((1 << (c & 31)) - 1), False), + 'v_mad_u32_u24': (3, lambda a, b, c: (a & M24) * (b & M24) + c, False), + 'v_lshl_add_u32': (3, lambda a, b, c: (a << (b & 31)) + c, False), + 'v_add_lshl_u32': (3, lambda a, b, c: ((a + b) & MASK) << (c & 31), False), + 'v_add3_u32': (3, lambda a, b, c: a + b + c, False), + 'v_or3_b32': (3, lambda a, b, c: a | b | c, False), + 'v_and_or_b32': (3, lambda a, b, c: (a & b) | c, False), + 'v_lshl_or_b32': (3, lambda a, b, c: (a << (b & 31)) | c, False), + 'v_xad_u32': (3, lambda a, b, c: (a ^ b) + c, False), + 'v_bfi_b32': (3, lambda a, b, c: (a & b) | (~a & c), False), +} +# Input sets (src0, src1, src2), eight per operation: two draws of four pixels. Shift counts and widths above 31, +# sources with bits above bit 23, sums that wrap and masks with every bit pattern. +SETS = [(0x12345678, 4, 8), (0xdeadbeef, 31, 1), (0x80000000, 0, 0), (MASK, 33, 31), + (0xf0f0f0f0, 16, 0x0f0f0f0f), (0x01000003, 0x02000005, 7), (0xaaaaaaaa, 0x55555555, 0xffff0000), + (0x7fffffff, 1, 0x80000001)] +BFE = [(0x12345678, 4, 8), (0xdeadbeef, 31, 1), (0x80000000, 0, 0), (MASK, 33, 31), + (0xf0f0f0f0, 4, 8), (0x89abcdef, 28, 4), (0x0000ff00, 8, 40), (0x80000001, 0, 31)] +DRAW = {op: SETS for op in OPS} +DRAW['v_bfe_u32'] = BFE +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_bfe_u32': (r'\(\(1u << \((v\d+) & 31\)\) - 1\)', r'(1u << (\1 & 31))', + lambda a, b, c: (a >> (b & 31)) & (1 << (c & 31))), + 'v_mad_u32_u24': (r'= \((v\d+) & 0xffffffu\) \* ', r'= \1 * ', lambda a, b, c: a * (b & M24) + c), + 'v_lshl_add_u32': (r'(\(v\d+ << \(v\d+ & 31\)\)) \+ ', r'\1 | ', lambda a, b, c: (a << (b & 31)) | c), + 'v_add_lshl_u32': (r'<< \((v\d+) & 31\)', r'<< (\1 & 15)', lambda a, b, c: ((a + b) & MASK) << (c & 15)), + 'v_add3_u32': (r'(v\d+) \+ (v\d+) \+ (v\d+)', r'\1 + \2 - \3', lambda a, b, c: a + b - c), + 'v_or3_b32': (r'(v\d+) \| (v\d+) \| (v\d+)', r'\1 ^ \2 ^ \3', lambda a, b, c: a ^ b ^ c), + 'v_and_or_b32': (r'\) \| (v\d+)', r') ^ \1', lambda a, b, c: (a & b) ^ c), + 'v_lshl_or_b32': (r'(\(v\d+ << \(v\d+ & 31\)\)) \| ', r'\1 + ', lambda a, b, c: (a << (b & 31)) + c), + 'v_xad_u32': (r'\((v\d+) \^ (v\d+)\)', r'(\1 | \2)', lambda a, b, c: (a | b) + c), + 'v_bfi_b32': (r'\(~(v\d+) & (v\d+)\)', r'(\1 & \2)', lambda a, b, c: (a & b) | (a & c)), +} +BODY = { + 'v_bfe_u32': words('0c0048d5000922040d0048d5010b26040e0048d5020d2a040f0048d5030f2e04'), + 'v_mad_u32_u24': words('0c0043d5000922040d0043d5010b26040e0043d5020d2a040f0043d5030f2e04'), + 'v_lshl_add_u32': words('0c0046d7000922040d0046d7010b26040e0046d7020d2a040f0046d7030f2e04'), + 'v_add_lshl_u32': words('0c0047d7000922040d0047d7010b26040e0047d7020d2a040f0047d7030f2e04'), + 'v_add3_u32': words('0c006dd7000922040d006dd7010b26040e006dd7020d2a040f006dd7030f2e04'), + 'v_or3_b32': words('0c0072d7000922040d0072d7010b26040e0072d7020d2a040f0072d7030f2e04'), + 'v_and_or_b32': words('0c0071d7000922040d0071d7010b26040e0071d7020d2a040f0071d7030f2e04'), + 'v_lshl_or_b32': words('0c006fd7000922040d006fd7010b26040e006fd7020d2a040f006fd7030f2e04'), + 'v_xad_u32': words('0c0045d7000922040d0045d7010b26040e0045d7020d2a040f0045d7030f2e04'), + 'v_bfi_b32': words('0c004ad5000922040d004ad5010b26040e004ad5020d2a040f004ad5030f2e04'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_bfe_u32 v1, v2, 8, 4', 'v_mad_u32_u24 v1, v2, v3, v4', 'v_add3_u32 v1, v2, s3, 1', + 'v_bfi_b32 v1, v2, v3, v4', 'v_lshl_or_b32 v1, v2, 16, v3'], + 'refused': ['v_bfe_u32 v1, v2, v3', 'v_add3_u32 v1, v2, v3, v4, v5', 'v_or3_b32 v1, v2', + 'v_mad_u32_u24 v1, v2, v3, v4 clamp', 'v_xad_u32 v1, -v2, v3, v4', 'v_bfi_b32 v1, |v2|, v3, v4', + 'v_and_or_b32 v1, v2, v3, v4 op_sel:[1,0,0,0]'], +} + +if __name__ == '__main__': + main(FAMILY, __doc__) diff --git a/tests/startup_gfx2hlsl_int_alu_check.py b/tests/startup_gfx2hlsl_int_alu_check.py new file mode 100644 index 0000000000..093ae49ede --- /dev/null +++ b/tests/startup_gfx2hlsl_int_alu_check.py @@ -0,0 +1,105 @@ +"""Two- and one-source integer vector operations of tools/startup/gfx2hlsl.py (its VEC_U table). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the pixel bodies and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_add_nc_u32, v_sub_nc_u32, v_subrev_nc_u32, v_mul_lo_u32, v_and_b32, v_or_b32, v_xor_b32, v_not_b32, +v_lshlrev_b32, v_lshrrev_b32, v_ashrrev_i32, v_min_u32, v_max_u32, v_min_i32, v_max_i32 and v_mul_u32_u24, which +no check ran before. The fixture and runner are startup_gfx2hlsl_lane_alu.py: one operation per lane, alternating +the e32 and e64 spellings where both exist (v_mul_lo_u32 is VOP3 only), on flat parameters the compilers cannot fold. +The references follow the AMD RDNA 2 ISA reference: 32-bit wrapping arithmetic, shifts by S0[4:0] of S1 (the +"rev" forms), an arithmetic shift for v_ashrrev_i32, signed or unsigned comparisons by name, and the 24-bit +multiply of the low 24 bits of each source. The inputs include shift counts above 31, values with the sign bit +set for the signed and unsigned pairs, products that wrap and sources with bits above bit 23. +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import MASK, main, signed, words # noqa: E402 + +M24 = 0xffffff +OPS = { + 'v_add_nc_u32': (2, lambda a, b: a + b, True), + 'v_sub_nc_u32': (2, lambda a, b: a - b, True), + 'v_subrev_nc_u32': (2, lambda a, b: b - a, True), + 'v_mul_lo_u32': (2, lambda a, b: a * b, False), + 'v_and_b32': (2, lambda a, b: a & b, True), + 'v_or_b32': (2, lambda a, b: a | b, True), + 'v_xor_b32': (2, lambda a, b: a ^ b, True), + 'v_not_b32': (1, lambda a: ~a, True), + 'v_lshlrev_b32': (2, lambda a, b: b << (a & 31), True), + 'v_lshrrev_b32': (2, lambda a, b: b >> (a & 31), True), + 'v_ashrrev_i32': (2, lambda a, b: signed(b) >> (a & 31), True), + 'v_min_u32': (2, min, True), + 'v_max_u32': (2, max, True), + 'v_min_i32': (2, lambda a, b: min(signed(a), signed(b)), True), + 'v_max_i32': (2, lambda a, b: max(signed(a), signed(b)), True), + 'v_mul_u32_u24': (2, lambda a, b: (a & M24) * (b & M24), True), +} +# Input sets (src0, src1, unused), eight per operation: two draws of four pixels. +ARITH = [(1, MASK, 0), (0x80000000, 0x80000000, 0), (0x12345678, 0x9abcdef0, 0), (0, 1, 0), + (0x7fffffff, 1, 0), (0xdeadbeef, 0xfeedface, 0), (5, 3, 0), (MASK, MASK, 0)] +LOGIC = [(0xf0f0f0f0, 0x0ff00ff0, 0), (0, MASK, 0), (0x12345678, 0x9abcdef0, 0), (MASK, 0x80000001, 0), + (0xaaaaaaaa, 0x55555555, 0), (0xdeadbeef, 0, 0), (1, 3, 0), (0x00ff0000, 0x0f0f0f0f, 0)] +SHIFT = [(4, 0x80000001, 0), (31, 0xc0000000, 0), (33, 0x80000010, 0), (0, 0xdeadbeef, 0), + (16, 0x12345678, 0), (0xffffffe1, 0xf0000000, 0), (32, 0x7fffffff, 0), (7, 0xffffff80, 0)] +ORDER = [(1, 0x80000000, 0), (MASK, 0, 0), (0x7fffffff, 0x80000000, 0), (5, 5, 0), + (0xfffffffe, 0xffffffff, 0), (100, 0x80000001, 0), (0, 0x7fffffff, 0), (0x80000000, 0x7fffffff, 0)] +MUL24 = [(0x01000003, 0x02000005, 0), (M24, M24, 0), (0x12345678, 0x9abcdef0, 0), (0x00800000, 2, 0), + (MASK, 1, 0), (0x00010000, 0x00010000, 0), (0xff000000, 0xff123456, 0), (7, 0x00ffffff, 0)] +DRAW = {op: ARITH for op in ('v_add_nc_u32', 'v_sub_nc_u32', 'v_subrev_nc_u32', 'v_mul_lo_u32')} +DRAW.update({op: LOGIC for op in ('v_and_b32', 'v_or_b32', 'v_xor_b32', 'v_not_b32')}) +DRAW.update({op: SHIFT for op in ('v_lshlrev_b32', 'v_lshrrev_b32', 'v_ashrrev_i32')}) +DRAW.update({op: ORDER for op in ('v_min_u32', 'v_max_u32', 'v_min_i32', 'v_max_i32')}) +DRAW['v_mul_u32_u24'] = MUL24 +# A wrong lowering of each operation: (pattern in the translated text, replacement, reference of the mutation). +MUTATIONS = { + 'v_add_nc_u32': (r'= (v\d+) \+ (v\d+);', r'= \1 - \2;', lambda a, b: a - b), + 'v_sub_nc_u32': (r'= (v\d+) - (v\d+);', r'= \2 - \1;', lambda a, b: b - a), + 'v_subrev_nc_u32': (r'= (v\d+) - (v\d+);', r'= \2 - \1;', lambda a, b: a - b), + 'v_mul_lo_u32': (r'= (v\d+) \* (v\d+);', r'= \1 * (\2 & 0xffffffu);', lambda a, b: a * (b & M24)), + 'v_and_b32': (r'= (v\d+) & (v\d+);', r'= \1 | \2;', lambda a, b: a | b), + 'v_or_b32': (r'= (v\d+) \| (v\d+);', r'= \1 ^ \2;', lambda a, b: a ^ b), + 'v_xor_b32': (r'= (v\d+) \^ (v\d+);', r'= \1 | \2;', lambda a, b: a | b), + 'v_not_b32': (r'= ~(v\d+);', r'= \1;', lambda a: a), + 'v_lshlrev_b32': (r'= (v\d+) << \((v\d+) & 31\);', r'= \2 << (\1 & 31);', lambda a, b: a << (b & 31)), + 'v_lshrrev_b32': (r'>> \((v\d+) & 31\)', r'>> (\1 & 15)', lambda a, b: b >> (a & 15)), + 'v_ashrrev_i32': (r'uint\(int\((v\d+)\) >> ', r'(\1 >> ', lambda a, b: b >> (a & 31)), + 'v_min_u32': (r'min\((v\d+), (v\d+)\)', r'max(\1, \2)', max), + 'v_max_u32': (r'max\((v\d+), (v\d+)\)', r'min(\1, \2)', min), + 'v_min_i32': (r'uint\(min\(int\((v\d+)\), int\((v\d+)\)\)\)', r'min(\1, \2)', min), + 'v_max_i32': (r'uint\(max\(int\((v\d+)\), int\((v\d+)\)\)\)', r'max(\1, \2)', max), + 'v_mul_u32_u24': (r'\((v\d+) & 0xffffffu\) \* \((v\d+) & 0xffffffu\)', r'\1 * \2', lambda a, b: a * b), +} +BODY = { + 'v_add_nc_u32': words('0009184a0d0025d5010b0200020d1c4a0f0025d5030f0200'), + 'v_sub_nc_u32': words('0009184c0d0026d5010b0200020d1c4c0f0026d5030f0200'), + 'v_subrev_nc_u32': words('0009184e0d0027d5010b0200020d1c4e0f0027d5030f0200'), + 'v_mul_lo_u32': words('0c0069d5000902000d0069d5010b02000e0069d5020d02000f0069d5030f0200'), + 'v_and_b32': words('000918360d001bd5010b0200020d1c360f001bd5030f0200'), + 'v_or_b32': words('000918380d001cd5010b0200020d1c380f001cd5030f0200'), + 'v_xor_b32': words('0009183a0d001dd5010b0200020d1c3a0f001dd5030f0200'), + 'v_not_b32': words('006f187e0d00b7d501010000026f1c7e0f00b7d503010000'), + 'v_lshlrev_b32': words('000918340d001ad5010b0200020d1c340f001ad5030f0200'), + 'v_lshrrev_b32': words('0009182c0d0016d5010b0200020d1c2c0f0016d5030f0200'), + 'v_ashrrev_i32': words('000918300d0018d5010b0200020d1c300f0018d5030f0200'), + 'v_min_u32': words('000918260d0013d5010b0200020d1c260f0013d5030f0200'), + 'v_max_u32': words('000918280d0014d5010b0200020d1c280f0014d5030f0200'), + 'v_min_i32': words('000918220d0011d5010b0200020d1c220f0011d5030f0200'), + 'v_max_i32': words('000918240d0012d5010b0200020d1c240f0012d5030f0200'), + 'v_mul_u32_u24': words('000918160d000bd5010b0200020d1c160f000bd5030f0200'), +} +FAMILY = { + 'ops': OPS, 'draw': DRAW, 'mutations': MUTATIONS, 'body': BODY, + 'accepted': ['v_add_nc_u32 v1, v2, v3', 'v_mul_lo_u32 v1, v2, v3', 'v_not_b32_e64 v1, v2', + 'v_ashrrev_i32_e64 v1, v2, v3', 'v_min_i32 v1, 5, v3', 'v_mul_u32_u24_e64 v1, v2, v3'], + 'refused': ['v_add_nc_u32 v1, v2', 'v_mul_lo_u32 v1, v2, v3, v4', 'v_not_b32 v1, v2, v3', + 'v_add_nc_u32_e64 v1, v2, v3 clamp', 'v_and_b32_e64 v1, -v2, v3', 'v_max_i32_e64 v1, |v2|, v3', + 'v_lshlrev_b32_e64 v1, v2, v3 mul:2', 'v_xor_b32 v1, v2'], +} + +if __name__ == '__main__': + main(FAMILY, __doc__) diff --git a/tests/startup_gfx2hlsl_interp_f16_check.py b/tests/startup_gfx2hlsl_interp_f16_check.py index a6944cdfe0..d15365bd14 100644 --- a/tests/startup_gfx2hlsl_interp_f16_check.py +++ b/tests/startup_gfx2hlsl_interp_f16_check.py @@ -120,6 +120,28 @@ ('unrelated read of v2', '0203fcbe0203107e040042d70000020004005ad700021204050042d70001020005005ad700031604060042d74000020006005ad740021a04070042d74001020007005ad740031e040417087e05170a7e06170c7e07170e7e0f1800f804050607000081bf'), ('unrelated write of v9', '0203fcbef202127e040042d70000020004005ad700021204050042d70001020005005ad700031604060042d74000020006005ad740021a04070042d74001020007005ad740031e040417087e05170a7e06170c7e07170e7e0f1800f804050607000081bf'), )} +# Loops: a constant-trip loop (s20 = 2) around the pair and its full-width conversions. The scan holds no state across a +# branch, so the back edge needs no refusal of its own; the two refused loops carry a p1ll result or an unconverted p2 +# result along the back edge. The back-edge offset is patched into the llvm-mc listing (an unresolved fixup, 0x0a). +LOOP_HEAD = 's_mov_b32 m0, s2\ns_mov_b32 s20, 2\n' +LOOP_BACK = 's_sub_u32 s20, s20, 1\ns_cmp_lg_u32 s20, 0\ns_cbranch_scc1 L0\n' +LOOP_CVT = ''.join('v_cvt_f32_f16 v%d, v%d\n' % (n, n) for n in range(4, 8)) +LOOP_SOURCES = { + 'loop': LOOP_HEAD + 'L0:\n' + V_BODY.split('v_cvt_f32_f16')[0] + LOOP_CVT + LOOP_BACK + 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + 'loop p1ll pending across the back edge': + LOOP_HEAD + 'v_interp_p1ll_f16 v4, v0, attr0.x\nL0:\nv_interp_p2_f16 v4, v1, attr0.x, v4\nv_cvt_f32_f16 v4, v4\n' + 'v_interp_p1ll_f16 v4, v0, attr0.x\n' + LOOP_BACK + V_TAIL, + 'loop p2 result not converted before the back edge': + LOOP_HEAD + 'L0:\n' + V_FIRST + LOOP_BACK + 'v_cvt_f32_f16 v4, v4\n' + V_TAIL, +} +LOOP_WORDS = {name: bytes.fromhex(h) for name, h in ( + ('loop', '0203fcbe820394be040042d70000020004005ad700021204050042d70001020005005ad700031604060042d74000020006005ad740021a04' + '070042d74001020007005ad740031e040417087e05170a7e06170c7e07170e7e14819480148007bfe9ff85bf0f1800f804050607000081bf'), + ('loop p1ll pending across the back edge', + '0203fcbe820394be040042d70000020004005ad7000212040417087e040042d70000020014819480148007bff8ff85bf0f1800f804040404000081bf'), + ('loop p2 result not converted before the back edge', + '0203fcbe820394be040042d70000020004005ad70002120414819480148007bff9ff85bf0417087e0f1800f804040404000081bf'), +)} # Plain-export fixture: the vertex stage packs 8 binary16 values with v_cvt_pkrtz_f16_f32 (inputs are the f32 values # below) and exports the four words without compr; PLAIN_PS_LO / PLAIN_PS_HI read half 0 / half 1 of channels x..w. PLAIN_VALUES = ((1.5, -2.0), (0.5, 3.0), (4.0, -0.25), (8.0, 0.125)) # (low, high) half of each word @@ -212,7 +234,7 @@ def evaluate(vs, ps, channels=None, regs=None): for r, sh, zero in args] state = {} for line in ps.splitlines(): - stmt = re.fullmatch(r' (v\d+) = \((v\d+) & 0xffff0000u\) \| f32tof16\(i\.(param0|hparam0_lo|hparam0_hi)\.([xyzw])\);', + stmt = re.fullmatch(r' +(v\d+) = \((v\d+) & 0xffff0000u\) \| f32tof16\(i\.(param0|hparam0_lo|hparam0_hi)\.([xyzw])\);', line) if stmt: assert stmt.group(1) == stmt.group(2), line @@ -221,7 +243,7 @@ def evaluate(vs, ps, channels=None, regs=None): f32 = source['xyzw'.index(stmt.group(4))] state[stmt.group(1)] = f16_bits(struct.unpack('<f', struct.pack('<I', f32))[0]) continue - stmt = re.fullmatch(r' (v\d+) = U\(f16tof32\((v\d+)\)\);', line) + stmt = re.fullmatch(r' +(v\d+) = U\(f16tof32\((v\d+)\)\);', line) if stmt: state[stmt.group(1)] = f16_to_f32_bits(state[stmt.group(2)] & 0xffff) return tuple(state['v%d' % n] for n in (4, 5, 6, 7)) @@ -348,6 +370,7 @@ def counting(self): # be refused as "not exported with compr"); plain_controls() covers it. assert 'hparam0_lo' in translate(PS_WORDS, F32_VS_WORDS).hlsl_ps() barycentric_controls(expected) + loop_controls(expected) plain_controls(expected) print('controls ok') @@ -496,6 +519,28 @@ def barycentric_controls(expected): refused('branch skips the full-width conversion', skip_conversion, 'result across a branch') +def loop_controls(expected): + """A constant-trip loop around the pair translates (the pair is recomputed every iteration, so the exported words + are the reference words); a p1ll result or an unconverted p2 result carried along the back edge stays refused.""" + pipe = translate(LOOP_WORDS['loop']) + ps = pipe.hlsl_ps() + assert 'pc = (scc) ? 1 : 2;' in ps and ps.count('f32tof16(i.param0.') == 4, ps + got = evaluate(pipe.hlsl_vs(), ps) + assert got == expected, ('loop translated words', [hex(w) for w in got], [hex(w) for w in expected]) + print('translated loop: %s' % ','.join('%08x' % w for w in got)) + refused('loop: p1ll result pending across the back edge', LOOP_WORDS['loop p1ll pending across the back edge'], + 'a branch between') + refused('loop: p2 result not converted before the back edge', + LOOP_WORDS['loop p2 result not converted before the back edge'], 'result across a branch') + # The high bit inverted on the pair inside the loop reads the other halves: translated, other words. + flipped = bytearray(LOOP_WORDS['loop']) + for index in range(8): # the pair starts after two dwords (s_mov m0, s_mov s20) + flipped[8 + 8 * index + 4 + 1] ^= 0x01 + flipped = bytes(flipped) + other = evaluate(*(lambda p: (p.hlsl_vs(), p.hlsl_ps()))(translate(flipped))) + assert other != expected, 'loop with the high bit inverted evaluated to the reference words' + + def normalise(words): """Clear the unused src2 field of v_interp_p1ll_f16, which newer llvm-mc encodes as 128 and LLVM 15 as 0.""" out = bytearray(words) @@ -525,6 +570,14 @@ def check_binary(llvm_mc): built = built.replace(bytes.fromhex('0a0a86bf'), bytes.fromhex('020086bf')) if built != PS_VARIANTS[name]: raise AssertionError('%s variant: assembled %s, recorded %s' % (name, built.hex(), PS_VARIANTS[name].hex())) + for name, source in LOOP_SOURCES.items(): + built = normalise(assemble(llvm_mc, source)) + # a backward branch is an unresolved fixup too (0x0a): the offset counts dwords from the label to the branch + label = len(normalise(assemble(llvm_mc, source.split('L0:')[0]))) // 4 + branch = built.index(bytes.fromhex('0a0a85bf')) // 4 + built = built.replace(bytes.fromhex('0a0a85bf'), struct.pack('<HBB', (label - branch - 1) & 0xffff, 0x85, 0xbf)) + if built != LOOP_WORDS[name]: + raise AssertionError('%s: assembled %s, recorded %s' % (name, built.hex(), LOOP_WORDS[name].hex())) print('fixture words match llvm-mc') @@ -539,6 +592,7 @@ def check_compile(dxc): directory = Path(tmp) compile_hlsl(dxc, 'dxc', vs, 'vs', 'vs_6_0', directory) compile_hlsl(dxc, 'dxc', ps, 'ps', 'ps_6_0', directory) + compile_hlsl(dxc, 'dxc', translate(LOOP_WORDS['loop']).hlsl_ps(), 'ps_loop', 'ps_6_0', directory) for half in (0, 1): vs, ps = plain_pair(half) with tempfile.TemporaryDirectory() as tmp: @@ -567,6 +621,20 @@ def check_draw(dxc, renderer, adapter): if run.returncode == 0: raise AssertionError('high inverted: control read the reference words') print('high inverted: fails as expected', flush=True) + # The constant-trip loop around the pair exports the reference words; its high bit inverted does not. + loop = translate(LOOP_WORDS['loop']) + loop_ps = compile_hlsl(dxc, 'dxc', loop.hlsl_ps(), 'ps_loop', 'ps_6_0', directory) + run = draw(renderer, adapter, vs_cso, loop_ps, expected) + if run.returncode: + raise AssertionError('loop around the pair\n%s\n%s' % (run.stdout, run.stderr)) + print('loop around the pair: %s' % expected, flush=True) + loop_flipped = bytearray(LOOP_WORDS['loop']) + for index in range(8): + loop_flipped[8 + 8 * index + 4 + 1] ^= 0x01 + bad_loop = compile_hlsl(dxc, 'dxc', translate(bytes(loop_flipped)).hlsl_ps(), 'ps_loop_high', 'ps_6_0', directory) + if draw(renderer, adapter, vs_cso, bad_loop, expected).returncode == 0: + raise AssertionError('loop with the high bit inverted read the reference words') + print('loop, high inverted: fails as expected', flush=True) # The plain export: low and high halves of channels x..w, and the high bit inverted. for half in (0, 1): expected_plain = ','.join('%08x' % w for w in plain_reference(half)) diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py index 8d72a634de..fc3ac08fcf 100644 --- a/tests/startup_gfx2hlsl_join_symbols_check.py +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -37,6 +37,7 @@ VOP3 field layouts and checked against the decoder's text; they are not in SOURCES, so `binary` does not assemble them. """ +import re import struct import subprocess import sys @@ -92,6 +93,62 @@ 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', '04040cf4000000fa80039ebe8002007e8002027e1e8006bf020085bf04040cf4000000fa7fc08cbf080f00f000040400' '703f8cbf0f1800f804050607000081bf'), + # Rule R1 (wave64): s_and_saveexec + s_cbranch_execz skips an s_load of a descriptor. The image_load at the branch + # target runs before the exec restore, so the lanes that skipped the arm (exec == 0) do nothing and it keeps the arm's + # descriptor. EXEC_DESC_AFTER reads it after the restore, where a lane that skipped is active again: refused. + 'EXEC_DESC_MASKED': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\nimage_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + 's_waitcnt vmcnt(0)\ns_or_b64 exec, exec, s[6:7]\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf080f00f000040400' + '703f8cbf7e06fe880f1800f804050607000081bf'), + # A scalar read of the kept descriptor at the join instruction itself ends the window (refused); a reload of it + # between the join and the restore is a fresh all-path definition (translated). + 'EXEC_DESC_SCALAR_JOIN': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\ns_mov_b32 s30, s17\ns_waitcnt lgkmcnt(0)\n' + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' + 's_or_b64 exec, exec, s[6:7]\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf11039ebe7fc08cbf08' + '0f00f000040400703f8cbf7e06fe880f1800f804050607000081bf'), + 'EXEC_DESC_RELOAD': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\ns_load_dwordx8 s[16:23], s[8:9], 0x0\ns_waitcnt lgkmcnt(0)\n' + 's_or_b64 exec, exec, s[6:7]\nimage_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + 's_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf04040cf4000000fa7f' + 'c08cbf7e06fe88080f00f000040400703f8cbf0f1800f804050607000081bf'), + # The join instruction is itself a branch: its incoming edge must not carry the kept arm descriptor to the next + # target, where the read after the restore would translate (refused). EXEC_DESC_BRANCH_IN has the branch inside + # the window, after a plain join instruction: the branch ends the window too (refused). + 'EXEC_DESC_JOIN_BRANCH': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\ns_branch 0\n' + 's_or_b64 exec, exec, s[6:7]\nimage_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + 's_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf000082bf7e06fe88' + '080f00f000040400703f8cbf0f1800f804050607000081bf'), + 'EXEC_DESC_JOIN_SCC': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\ns_cbranch_scc1 1\ns_endpgm\n' + 's_or_b64 exec, exec, s[6:7]\nimage_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + 's_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf010085bf000081bf' + '7e06fe88080f00f000040400703f8cbf0f1800f804050607000081bf'), + 'EXEC_DESC_BRANCH_IN': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\ns_nop 0\ns_branch 1\ns_endpgm\n' + 's_or_b64 exec, exec, s[6:7]\nimage_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + 's_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf000080bf010082bf' + '000081bf7e06fe88080f00f000040400703f8cbf0f1800f804050607000081bf'), + 'EXEC_DESC_AFTER': ('v_mov_b32 v0, 0\nv_mov_b32 v1, 0\nv_mov_b32 v2, 0\nv_cmp_eq_u32 vcc, 0, v2\n' + 's_and_saveexec_b64 s[6:7], vcc\ns_cbranch_execz 3\ns_load_dwordx8 s[16:23], s[8:9], 0x0\n' + 's_waitcnt lgkmcnt(0)\ns_or_b64 exec, exec, s[6:7]\n' + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D\ns_waitcnt vmcnt(0)\n' + 'exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n', + '8002007e8002027e8002047e8004847d6a2486be030088bf04040cf4000000fa7fc08cbf7e06fe88080f00f000040400' + '703f8cbf0f1800f804050607000081bf'), # Compute, with the root of startup_gfx2hlsl_compute_check.py: the table descriptor is loaded before the loop, the # loop stores through it at its header and reloads it from the same place before the back edge. Each of 8 lanes # stores the counter (1, then 2) to two consecutive words. @@ -161,7 +218,9 @@ def root(*params): ROOTS = {'DESC_CALC': ('t', 1), 'PAIR_READ': ('t', 1), 'PAIR_ROOT': ('t', 1), 'PAIR_WRITE': ('t', 1), 'DESC_LOAD': ('t', 1), - 'DESC_WORD': ('t', 1), 'DESC_SAME': ('t', 1), 'DESC_ONE_PATH': ('t', 1), + 'DESC_WORD': ('t', 1), 'DESC_SAME': ('t', 1), 'DESC_ONE_PATH': ('t', 1), 'EXEC_DESC_MASKED': ('t', 1), + 'EXEC_DESC_AFTER': ('t', 1), 'EXEC_DESC_SCALAR_JOIN': ('t', 1), 'EXEC_DESC_RELOAD': ('t', 1), + 'EXEC_DESC_JOIN_BRANCH': ('t', 1), 'EXEC_DESC_JOIN_SCC': ('t', 1), 'EXEC_DESC_BRANCH_IN': ('t', 1), 'PTR_OFFSETS': ('t', 1)} @@ -226,6 +285,16 @@ def check_controls(): assert ' v0 = s23;' in lines('JOIN_SAME') # #2279 drops the constant at any join another path writes same = translate('DESC_SAME') assert ' t = r0.Load(int3(v0, v1, 0));' in same.hlsl_ps().splitlines(), same.hlsl_ps() + # Rule R1: a descriptor loaded in an s_cbranch_execz arm is kept for a read before the exec restore ... + masked = translate('EXEC_DESC_MASKED').hlsl_ps().splitlines() + assert ' t = r0.Load(int3(v0, v1, 0));' in masked, masked + # ... and still refused for a read after the restore (a lane that skipped the arm is active again). + refused('EXEC_DESC_AFTER', "holds ('joined at a branch target',)") + for branchy in ('EXEC_DESC_JOIN_BRANCH', 'EXEC_DESC_JOIN_SCC', 'EXEC_DESC_BRANCH_IN'): + refused(branchy, "holds ('joined at a branch target',)") + refused('EXEC_DESC_SCALAR_JOIN','numeric use of s17 holding joined at a branch target') + reloaded = translate('EXEC_DESC_RELOAD').hlsl_ps().splitlines() + assert ' t = r0.Load(int3(v0, v1, 0));' in reloaded, reloaded reload = translate_cs('CS_RELOAD') cs = reload.hlsl_cs().splitlines() assert ' u0.Store(a, v5);' in cs and ' s22 = s22 + 0x00000001u;' in cs, cs @@ -274,13 +343,18 @@ def cmp_ne(sdst, v): # v_cmp_ne_i32_e64 sdst, 0, v return struct.pack('<II', 0xd4000000 | 0x85 << 16 | sdst, 128 | (256 + v) << 9) -def exec_join(at_target, branch=EXECZ, fall=None, before=b'', read='1002007e'): +def select_mask(mask): + # v_cndmask_b32_e64 v0, 0, 1, mask + return struct.pack('<II', 0xd5010000, 128 | (129 << 9) | (mask << 18)) + + +def exec_join(at_target, branch=EXECZ, fall=None, before=b'', read=select_mask(16)): """s[16:23] = a descriptor; exec &= (v1 != 0); branch over `fall` (default: s16 = lane mask v0 != 0) to - `at_target`; then `read` (default: v0 = s16) and the export. `before` goes in front of the branch.""" + `at_target`; then `read` (default: select on s16 into v0) and the export. `before` goes in front of the branch.""" fall = cmp_ne(16, 0) if fall is None else fall return (bytes.fromhex('04040cf4000000fa' '8002007e' '8002027e') + cmp_ne(30, 1) + sop2(S_AND_B64, EXEC, EXEC, 30) + before + struct.pack('<I', 0xbf800000 | branch << 16 | len(fall) // 4) + fall + at_target - + bytes.fromhex(read + EXPORT_WORDS)) + + read + bytes.fromhex(EXPORT_WORDS)) def exec_join_hlsl(*args, **kwargs): @@ -306,15 +380,16 @@ def check_exec_join(): assert [asm for *_, asm in G.decode(exec_join(and_s16))] == [ 's_load_dwordx8 s[16:23], s[8:9], 0x0', 'v_mov_b32_e32 v0, 0', 'v_mov_b32_e32 v1, 0', 'v_cmp_ne_i32_e64 s30, 0, v1', 's_and_b64 exec, exec, s[30:31]', 's_cbranch_execz label_0x28', - 'v_cmp_ne_i32_e64 s16, 0, v0', 's_and_b64 s[16:17], s[16:17], exec', 'v_mov_b32_e32 v0, s16', + 'v_cmp_ne_i32_e64 s16, 0, v0', 's_and_b64 s[16:17], s[16:17], exec', 'v_cndmask_b32_e64 v0, 0, 1, s16', 'exp mrt0 v0, v0, v0, v0 done vm', 's_endpgm'], G.decode(exec_join(and_s16)) # Accepted: the mask ANDed with exec at the target (either operand order), and ORed with its complement. hlsl = exec_join_hlsl(and_s16) assert " pc = ((exec & 1) == 0) ? 2 : 1;" in hlsl and ' s16 = (s16 & exec) & 1;' in hlsl, hlsl + exec_join_refused('v_mov_b32 data operand s16 is a lane mask', and_s16, read=bytes.fromhex('1002007e')) swapped, orn2 = exec_join_hlsl(sop2(S_AND_B64, 16, EXEC, 16)), exec_join_hlsl(sop2(S_ORN2_B64, 16, 16, EXEC)) assert ' s16 = (exec & s16) & 1;' in swapped and ' s16 = (s16 | ~exec) & 1;' in orn2 # exec as the destination: the same statement, and the lane stays off on the skipping edge. - assert ' exec = (s16 & exec) & 1;' in exec_join_hlsl(sop2(S_AND_B64, EXEC, 16, EXEC), read='8002007e') + assert ' exec = (s16 & exec) & 1;' in exec_join_hlsl(sop2(S_AND_B64, EXEC, 16, EXEC), read=bytes.fromhex('8002007e')) # The emitted right-hand sides with exec bit 0, the only case in which the variable s16 may not hold the # register: every word of s16 gives 0 for the AND and 1 for the OR with the complement. def rhs(text): @@ -324,7 +399,7 @@ def rhs(text): for text, want in ((hlsl, 0), (swapped, 0), (orn2, 1)): assert eval(rhs(text), {'s16': word, 'exec': 0}) == want, (rhs(text), word) # Another destination: the result is read, and the source stays joined for the read after it. - assert ' s32 = (s16 & exec) & 1;' in exec_join_hlsl(sop2(S_AND_B64, 32, 16, EXEC), read='2002007e') # v0 = s32 + assert ' s32 = (s16 & exec) & 1;' in exec_join_hlsl(sop2(S_AND_B64, 32, 16, EXEC), read=select_mask(32)) exec_join_refused(JOINED_S16, sop2(S_AND_B64, 32, 16, EXEC)) # Refused, each for one missing piece of the argument: # the skipping branch is not s_cbranch_execz, so exec says nothing about the edge; @@ -340,7 +415,7 @@ def rhs(text): exec_join_refused(JOINED_S16, sop2(op, 16, src0, src1)) # the fall-through leaves a constant, not a plain run-time number (s_mov_b32 s16, 3); exec_join_refused(JOINED_S16, and_s16, fall=bytes.fromhex('830390be')) - # a plain read at the target; + # a read at the target without an absorbing operation; exec_join_refused(JOINED_S16, b'') # the branch into the target is backward (L: and; s_cbranch_execz L), only forward edges are absorbed; backward = and_s16 + sopp(EXECZ, -2) @@ -356,8 +431,8 @@ def rhs(text): exec_join_refused(JOINED_S16, and_s16, **only_skips) # a plain run-time number on every path is no joined register: the read is the ordinary one; assert ' s16 = (s16 & exec) & 1;' in exec_join_hlsl(and_s16, before=cmp_ne(16, 0)) - # a compute stage is left out: the pre-pass refuses a definition inside the skipped block that the target reads, - # and with the pre-pass out of the way the target's read is refused as it was, not absorbed. + # The compute pre-pass can now prove the lane absorption, but the scalar value is still a + # joined descriptor/number, so lowering must still refuse its numeric use. cs = (bytes.fromhex('06038abe80038bbe05030cf4000000fa7fc08cbf') + cmp_ne(30, 0) + sop2(S_AND_B64, EXEC, EXEC, 30) + sopp(EXECZ, 2) + cmp_ne(12, 0) + sop2(S_AND_B64, 12, 12, EXEC) + bytes.fromhex('0c02027e000081bf')) import startup_gfx2hlsl_compute_check as C @@ -368,13 +443,8 @@ def refusal_of_cs(): except G.Unsupported as reason: return str(reason) raise AssertionError('compute accepted') - assert 'definition of s12, live where the block joins' in refusal_of_cs() - pre_pass = G.Stage.execz_refusals - G.Stage.execz_refusals = lambda self: {} - try: - assert refusal_of_cs() == 'numeric use of s12 holding joined at a branch target', refusal_of_cs() - finally: - G.Stage.execz_refusals = pre_pass + reason = refusal_of_cs() + assert reason == 'numeric use of s12 holding joined at a branch target', reason # Without the lowering every accepted form is refused where it reads s16. absorbed = G.Stage.exec_absorbed_source G.Stage.exec_absorbed_source = lambda self, base, srcs: None @@ -389,7 +459,13 @@ def refusal_of_cs(): def check_binary(llvm_mc): for name, (source, words) in SOURCES.items(): - built = assemble(llvm_mc, source).hex() + if name.startswith('EXEC_DESC'): # 64-bit exec mask forms: wave64 + run = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64', '-show-encoding'], + input=source, capture_output=True, text=True, check=True) + built = ''.join(bytes(int(b, 16) for b in m.group(1).split(',')).hex() for m in + (re.search(r'encoding: \[([^\]]*)\]', l) for l in run.stdout.splitlines()) if m) + else: + built = assemble(llvm_mc, source).hex() assert built == words, '%s: assembled %s, recorded %s' % (name, built, words) print('fixture words match llvm-mc') diff --git a/tests/startup_gfx2hlsl_lane_alu.py b/tests/startup_gfx2hlsl_lane_alu.py index 4ff732d480..141a46bf2f 100644 --- a/tests/startup_gfx2hlsl_lane_alu.py +++ b/tests/startup_gfx2hlsl_lane_alu.py @@ -19,6 +19,8 @@ refused: assembly lines that must stay refused accepted: assembly lines that must translate (one instruction, no pipeline) pipeline: optional keyword arguments of the Pipeline built for the fixture (a selected contract) + ulps: optional mnemonic -> how many binary32 ulps a lane may read off its reference (default 0, exact) + a nonzero bound measures distance on the number line, so it accepts -0.0 for +0.0 and back Every reference is written from the ISA description with plain integer arithmetic, not from the lowering. """ import re @@ -72,6 +74,27 @@ def check(label, ok): raise AssertionError(label) +def order(word): + """Position of a binary32 word on the number line, so the ulp distance of two words is a subtraction.""" + return -(word & 0x7fffffff) if word >> 31 else word + + +def actual(run): + """The readback the renderer reports on a mismatch, or None if the run failed any other way.""" + # A mismatch exits 1 even when the debug layer also logged errors; those must not be tolerated away. + if re.search(r'debug_errors=[1-9]', run.stdout): + return None + found = re.search(r'startup_flat_param mismatch expected=[0-9a-f,]+ actual=([0-9a-f,]+)', run.stderr) + return [int(w, 16) for w in found.group(1).split(',')] if found else None + + +def within(got, want, ulps): + if not ulps: + return got == list(want) # exact, so -0.0 and +0.0 and the integer words stay distinct + return got is not None and len(got) == len(want) and all(abs(order(g) - order(w)) <= ulps + for g, w in zip(got, want)) + + def expected(family, op, sets, mutated=False): arity, reference, _ = family['ops'][op] function = family['mutations'][op][2] if mutated else reference @@ -89,7 +112,11 @@ def controls(family): # Each mutation reads a wrong word in the first draw, so the mutated draw cannot pass by accident. first = sets[:4] check('%s: mutation changes draw set 0' % op, - expected(family, op, first, True) != expected(family, op, first)) + not within(expected(family, op, first, True), expected(family, op, first), + 2 * family.get('ulps', {}).get(op, 0))) + # 1 ulp either side of -3.0 and of 0.0, a sign change at zero, and a word 5 ulps off. + check('ulp distance', within([0xc03fffff, 0xc0400001, 0x80000001, 0x00000002], [0xc0400000, 0xc0400000, 0, 0], 2) + and not within([0xc0400005], [0xc0400000], 4) and not within(None, [0], 4)) check('accepted forms translate', not any(refused(a) for a in family['accepted'])) check('refused forms stay refused', all(refused(a) for a in family['refused'])) @@ -126,9 +153,15 @@ def check_draw(family, dxc, renderer, adapter, fxc=None): + POST_WORDS, root_blob(), **family.get('pipeline', {})).hlsl_vs(), 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) - want = words_text(expected(family, op, chunk)) + ulps = family.get('ulps', {}).get(op, 0) + reference = expected(family, op, chunk) + want = words_text(reference) run = draw(renderer, adapter, vs, good, want) - if run.returncode: + # The renderer compares exactly; a mismatch within the operation's ulp bound still passes. + if run.returncode and ulps and within(actual(run), reference, ulps): + print('%s %s within %d ulps: reads %s' % (kind, op, ulps, words_text(actual(run))), + flush=True) + elif run.returncode: raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, op, chunk, run.stdout, run.stderr)) draws += 1 print('%s %s %s: %s' % (kind, op, [tuple('%x' % v for v in x[:arity]) for x in chunk], want), @@ -136,11 +169,13 @@ def check_draw(family, dxc, renderer, adapter, fxc=None): if index: continue # The same draw with the mutated lowering must read the mutated words, not the reference. - wrong = words_text(expected(family, op, chunk, True)) + mutated = expected(family, op, chunk, True) + wrong = words_text(mutated) bad = compile_hlsl(compiler, kind, translate(family, op, True)[1], 'mutated_%s_%s' % (op, kind), ps_profile, directory) run = draw(renderer, adapter, vs, bad, want) - if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + got = actual(run) + if run.returncode == 0 or within(got, reference, ulps) or not within(got, mutated, ulps): raise AssertionError('%s %s mutation did not read %s\n%s\n%s' % (kind, op, wrong, run.stdout, run.stderr)) mutations += 1 diff --git a/tests/startup_gfx2hlsl_ldexp_check.py b/tests/startup_gfx2hlsl_ldexp_check.py new file mode 100644 index 0000000000..4381fd0052 --- /dev/null +++ b/tests/startup_gfx2hlsl_ldexp_check.py @@ -0,0 +1,322 @@ +"""Verify that v_ldexp_f32 lowers to ldexp32 with valid float/integer operands and refuses invalid modifiers. + +Refs #2618. +""" +from pathlib import Path +import re +import struct +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + + +def vop3a(op, vdst, src0, src1, src2=0, *, abs_bits=0, clamp=0, omod=0, neg=0, lit=None): + """Encode one synthetic gfx1013 VOP3A instruction.""" + w0 = 0xd4000000 | (op << 16) | (clamp << 15) | (abs_bits << 8) | vdst + w1 = (neg << 29) | (omod << 27) | (src2 << 18) | (src1 << 9) | src0 + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & 0xffffffff) + return out + + +ENDPGM = struct.pack('<I', 0xbf800000) + + +def translate_cs(code): + return G.ComputePipeline(code + ENDPGM, C.root_blob(), C.CASES['A'][2], (2, 3, 4)).hlsl_cs() + + +def check_translations(): + # 1. Preamble contains ldexp32 + hlsl_base = translate_cs(vop3a(0x362, 5, 240, 130)) + assert 'float ldexp32(float value, int delta) {' in hlsl_base, 'preamble missing ldexp32' + assert 'v5 = U(ldexp32(0.5, asint(0x00000002u)));' in hlsl_base, f'unexpected hlsl: {hlsl_base}' + + # 2. Float input modifiers on src0: + # Negation on inline float + hlsl_neg = translate_cs(vop3a(0x362, 5, 240, 130, neg=1)) + assert 'v5 = U(ldexp32(-0.5, asint(0x00000002u)));' in hlsl_neg, f'unexpected neg: {hlsl_neg}' + + # Negation on negative inline float -0.5 (encoding 241): + # Must format as (-(-0.5)) to avoid HLSL pre-decrement syntax (--0.5) + hlsl_neg_minus_half = translate_cs(vop3a(0x362, 5, 241, 130, neg=1)) + assert 'v5 = U(ldexp32((-(-0.5)), asint(0x00000002u)));' in hlsl_neg_minus_half, f'unexpected neg -0.5: {hlsl_neg_minus_half}' + assert '--0.5' not in hlsl_neg_minus_half, f'decrement operator found in hlsl: {hlsl_neg_minus_half}' + + # Negation on VGPR src0 + hlsl_vneg = translate_cs(vop3a(0x362, 5, 257, 130, neg=1)) + assert 'v5 = U(ldexp32((-F(v1)), asint(0x00000002u)));' in hlsl_vneg, f'unexpected vneg: {hlsl_vneg}' + + # Absolute on VGPR src0 + hlsl_vabs = translate_cs(vop3a(0x362, 5, 257, 130, abs_bits=1)) + assert 'v5 = U(ldexp32(abs(F(v1)), asint(0x00000002u)));' in hlsl_vabs, f'unexpected vabs: {hlsl_vabs}' + + # Combined -|src0| on VGPR + hlsl_neg_abs = translate_cs(vop3a(0x362, 5, 257, 130, neg=1, abs_bits=1)) + assert 'v5 = U(ldexp32((-abs(F(v1))), asint(0x00000002u)));' in hlsl_neg_abs, f'unexpected neg abs: {hlsl_neg_abs}' + + # 3. Exponent operand types: + # Negative inline integer constant -2 (encoding 194) + hlsl_neg_exp = translate_cs(vop3a(0x362, 5, 240, 194)) + assert 'v5 = U(ldexp32(0.5, asint(0xfffffffeu)));' in hlsl_neg_exp, f'unexpected neg exp: {hlsl_neg_exp}' + + # Exponent from SGPR s4 (user data ud0, encoding 4) + hlsl_sreg = translate_cs(vop3a(0x362, 5, 240, 4)) + assert 'v5 = U(ldexp32(0.5, asint(ud0)));' in hlsl_sreg, f'unexpected sreg: {hlsl_sreg}' + + # Exponent from VGPR v2 (encoding 258) + hlsl_vreg = translate_cs(vop3a(0x362, 5, 240, 258)) + assert 'v5 = U(ldexp32(0.5, asint(v2)));' in hlsl_vreg, f'unexpected vreg: {hlsl_vreg}' + + # 4. Output modifiers: + # clamp (generates saturate) + hlsl_clamp = translate_cs(vop3a(0x362, 5, 240, 130, clamp=1)) + assert 'v5 = U(saturate(ldexp32(0.5, asint(0x00000002u))));' in hlsl_clamp, f'unexpected clamp: {hlsl_clamp}' + + # omod mul:2 + hlsl_mul2 = translate_cs(vop3a(0x362, 5, 240, 130, omod=1)) + assert 'v5 = U((ldexp32(0.5, asint(0x00000002u))) * 2.0);' in hlsl_mul2, f'unexpected mul2: {hlsl_mul2}' + + +def make_stage(kind='cs'): + st = G.Stage.__new__(G.Stage) + st.kind = kind + st.lines = [] + st.sym = {} + st.used_s, st.used_v, st.uniform_v = set(), set(), set() + st.varying_s = set() + st.scc_uniform = True + st.uniform_expr = {} + st.past_entry = False + st.has_branches = False + st.exec_known = True + st.masks = set() + st.exports = {} + st.low16_only_v = set() + st.pinned_low16_v = set() + st.whole_read_v = set() + st.byte_float_v = set() + st.bad_sgprs = set() + st.defined_uniform_s = None + st.wave_reductions = [] + st.emitted_reductions = [] + st.wave_reduce_used_exec = False + return st + + +def check_refusals(): + # Helper to test Stage.one directly + def lower_inst(asm_line): + name = asm_line.split()[0] + st = make_stage('cs') + return st.one(name, asm_line) + + # 1. Float modifier on integer exponent operand: + bad_modifiers = ( + ('v_ldexp_f32 v0, v1, -s4', 'v_ldexp_f32 exponent -s4 has float modifier'), + ('v_ldexp_f32 v0, v1, -v2', 'v_ldexp_f32 exponent -v2 has float modifier'), + ('v_ldexp_f32 v0, v1, |s4|', 'v_ldexp_f32 exponent |s4| has float modifier'), + ('v_ldexp_f32 v0, v1, abs(s4)', 'v_ldexp_f32 exponent abs(s4) has float modifier'), + ) + for asm, expected in bad_modifiers: + try: + lower_inst(asm) + raise AssertionError(f'expected refusal for {asm}, but succeeded') + except G.Unsupported as e: + assert expected in str(e), f'unexpected message for {asm}: {e}' + + # 2. Exponent out of 32-bit range: + try: + lower_inst('v_ldexp_f32 v0, v1, 0x100000000') + raise AssertionError('expected refusal for 0x100000000, but succeeded') + except G.Unsupported as e: + assert 'v_ldexp_f32 source 0x100000000' in str(e), f'unexpected message: {e}' + + # 3. Operand counts: + for asm in ('v_ldexp_f32 v0, v1', 'v_ldexp_f32 v0, v1, v2, v3'): + try: + lower_inst(asm) + raise AssertionError(f'expected refusal for {asm}, but succeeded') + except G.Unsupported as e: + assert 'v_ldexp_f32 with' in str(e), f'unexpected message: {e}' + + # 4. Destination not a VGPR: + try: + lower_inst('v_ldexp_f32 s0, v1, v2') + raise AssertionError('expected refusal for destination s0, but succeeded') + except G.Unsupported as e: + assert 'v_ldexp_f32 destination s0' in str(e), f'unexpected message: {e}' + + # 5. Disallowed instruction forms: + for asm, expected in ( + ('v_ldexp_f32_e32 v0, v1, v2', 'v_ldexp_f32_e32'), + ('v_ldexp_f32_sdwa v0, v1, v2', 'SDWA form of v_ldexp_f32'), + ('v_ldexp_f32_dpp v0, v1, v2', 'DPP form of v_ldexp_f32'), + ('v_ldexp_f32_dpp v0, v1, v2 quad_perm:[1,1,3,3] row_mask:0xf bank_mask:0xf', 'DPP form of v_ldexp_f32'), + ): + try: + lower_inst(asm) + raise AssertionError(f'expected refusal for {asm}, but succeeded') + except G.Unsupported as e: + assert expected in str(e), f'unexpected message: {e}' + + # 6. Machine-code VOP3 check_encoding refusals: + # NEG bit on src1 exponent (w1[30]) + try: + G.decode(vop3a(0x362, 0, 240, 130, neg=2)) + raise AssertionError('expected decode refusal for NEG on exponent') + except G.Unsupported as e: + assert 'v_ldexp_f32 with neg/abs on exponent or unused source' in str(e), f'unexpected: {e}' + + # ABS bit on src1 exponent (w0[9]) + try: + G.decode(vop3a(0x362, 0, 240, 130, abs_bits=2)) + raise AssertionError('expected decode refusal for ABS on exponent') + except G.Unsupported as e: + assert 'v_ldexp_f32 with neg/abs on exponent or unused source' in str(e), f'unexpected: {e}' + + # Unused src2 field set (w1[26:18]) + try: + G.decode(vop3a(0x362, 0, 240, 130, src2=1)) + raise AssertionError('expected decode refusal for src2 set') + except G.Unsupported as e: + assert 'v_ldexp_f32 with unused src2 field set' in str(e), f'unexpected: {e}' + + +def check_negative_controls(): + # Negative control 1: pre-fix mutant where op_v_ldexp_f32 is missing + real_handler = getattr(G.Stage, 'op_v_ldexp_f32', None) + try: + delattr(G.Stage, 'op_v_ldexp_f32') + try: + translate_cs(vop3a(0x362, 5, 240, 130)) + raise AssertionError('expected translation failure under mutant') + except G.Unsupported as e: + assert 'v_ldexp_f32' in str(e), f'unexpected mutant error: {e}' + finally: + if real_handler: + setattr(G.Stage, 'op_v_ldexp_f32', real_handler) + + # Negative control 2: mutant that treats exponent as float (accepting float modifiers) + real_op = G.Stage.op_v_ldexp_f32 + + def mutant_op(self, ops, mods): + dst = G.reg_range(ops[0]) + src0 = self.f(ops[1]) + src1 = self.f(ops[2]) + self.set_vf(dst[1], 'ldexp32(%s, %s)' % (src0, src1), mods) + + try: + G.Stage.op_v_ldexp_f32 = mutant_op + # Under this mutant, float modifier on exponent would escape refusal + st = make_stage('cs') + st.lower('v_ldexp_f32', 'v_ldexp_f32 v0, v1, -s4', ['v0', 'v1', '-s4'], []) + assert any('(-s4)' in line or 'F(s4)' in line for line in st.lines), 'mutant failed to reproduce bypass' + finally: + G.Stage.op_v_ldexp_f32 = real_op + + +def check_decode_and_lower(): + # Verify a synthetic VOP3A v_ldexp_f32 word decodes and lowers through Stage + code = vop3a(0x362, 5, 240, 130) + ins = G.decode(code) + assert len(ins) == 1 and ins[0][2] == 'v_ldexp_f32', f'unexpected decode: {ins}' + st = make_stage('vs') + name, ops, mods = G.parse(ins[0][3]) + st.lower(ins[0][2], ins[0][3], ops, mods) + assert any('ldexp32' in line for line in st.lines), 'ldexp32 missing from lowered stage' + + +def check_helper_parity(): + # Verify exact parity between the ldexp32 definition in Pipeline.common() and tools/pixel_aot.py + pixel_aot_path = HERE.parent / 'tools' / 'pixel_aot.py' + pixel_aot_text = pixel_aot_path.read_text(encoding='utf-8') + m_aot = re.search(r'float ldexp32\(float value, int delta\) \{.*?^\}', pixel_aot_text, re.M | re.S) + assert m_aot, 'ldexp32 helper missing from tools/pixel_aot.py' + aot_ldexp = m_aot.group(0) + + pipe = G.ComputePipeline(b'', C.root_blob(), C.CASES['A'][2], (1, 1, 1)) + common_text = '\n'.join(pipe.common()) + m_gfx = re.search(r'float ldexp32\(float value, int delta\) \{.*?^\}', common_text, re.M | re.S) + assert m_gfx, 'ldexp32 helper missing from Pipeline.common()' + gfx_ldexp = m_gfx.group(0) + + def normalize(code): + return [line.strip() for line in code.splitlines() if line.strip()] + + assert normalize(gfx_ldexp) == normalize(aot_ldexp), ( + 'ldexp32 in gfx2hlsl Pipeline.common() does not match tools/pixel_aot.py' + ) + + # Negative control: an altered helper fails parity + mutant = gfx_ldexp.replace('clamp(delta, -512, 512)', 'delta') + assert normalize(mutant) != normalize(aot_ldexp), 'mutant failed to differ from pixel_aot.py' + + # Pure-Python simulation of ldexp32 logic on edge cases + def ldexp32_sim(bits, delta): + sign = bits & 0x80000000 + exp = (bits >> 23) & 0xff + mant = bits & 0x7fffff + if exp == 0xff or (exp == 0 and mant == 0): + return bits + e = exp + if exp == 0: + shift = 23 - (mant.bit_length() - 1) + mant = (mant << shift) & 0x7fffff + e = 1 - shift + e += max(-512, min(512, delta)) + if e >= 255: + return sign | 0x7f800000 + if e <= 0: + if e < -23: + return sign + full = mant | 0x800000 + shift = 1 - e + half_bit = 1 << (shift - 1) + mask = (1 << shift) - 1 + rem = full & mask + q = full >> shift + if rem > half_bit or (rem == half_bit and (q & 1) != 0): + q += 1 + return sign | q + return sign | (e << 23) | mant + + def f2u(f): return struct.unpack('<I', struct.pack('<f', f))[0] + def u2f(u): return struct.unpack('<f', struct.pack('<I', u))[0] + + # Normal scaling + assert u2f(ldexp32_sim(f2u(1.0), 1)) == 2.0 + assert u2f(ldexp32_sim(f2u(1.0), -1)) == 0.5 + # Signed zero preserved + assert ldexp32_sim(f2u(0.0), 10) == f2u(0.0) + assert ldexp32_sim(f2u(-0.0), 10) == f2u(-0.0) + # Infinity and NaN preserved + assert ldexp32_sim(0x7f800000, 10) == 0x7f800000 + assert ldexp32_sim(0xff800000, -10) == 0xff800000 + assert ldexp32_sim(0x7fc00001, 5) == 0x7fc00001 + # Clamping overflow and underflow + assert ldexp32_sim(f2u(1.0), 1000) == 0x7f800000 + assert ldexp32_sim(f2u(1.0), -1000) == 0 + # Subnormal 2^-150 tie to even (q=0 is even -> rounds to 0) + assert ldexp32_sim(f2u(1.0), -150) == 0 + # Subnormal 1.5 * 2^-150 rounds up to 1 ULP + assert ldexp32_sim(f2u(1.5), -150) == 1 + + +def main(): + check_helper_parity() + check_translations() + check_refusals() + check_negative_controls() + check_decode_and_lower() + print('gfx2hlsl v_ldexp_f32 lowering and refusal checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_lerp_u8_check.py b/tests/startup_gfx2hlsl_lerp_u8_check.py new file mode 100644 index 0000000000..7b50654c52 --- /dev/null +++ b/tests/startup_gfx2hlsl_lerp_u8_check.py @@ -0,0 +1,186 @@ +"""Unsigned per-byte average with rounding (v_lerp_u8) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, on-demand helper, value-evaluation, refusal and mutation + controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +AMD RDNA 2 ISA V_LERP_U8 (VOP3A opcode 0x14d): + D.u[7:0] = (S0.u[7:0] + S1.u[7:0] + S2.u[0]) >> 1 + D.u[15:8] = (S0.u[15:8] + S1.u[15:8] + S2.u[8]) >> 1 + D.u[23:16] = (S0.u[23:16] + S1.u[23:16] + S2.u[16]) >> 1 + D.u[31:24] = (S0.u[31:24] + S1.u[31:24] + S2.u[24]) >> 1 +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + refused, + vs_words, + words_text, +) +from startup_gfx2hlsl_sad_check import HlslExpr, vop3a # noqa: E402 + +OPCODE = 0x14d +BODY_WORDS = b''.join(vop3a(OPCODE, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + + +def ref_lerp_u8(a, b, c): + a, b, c = a & MASK, b & MASK, c & MASK + out = 0 + for shift in (0, 8, 16, 24): + out |= ((((a >> shift) & 0xff) + ((b >> shift) & 0xff) + ((c >> shift) & 1)) >> 1) << shift + return out + + +U8_WORDS = ( + 0x00000000, 0x01020304, 0x04030201, 0x7f80ff00, 0x807f00ff, + 0xfefdfcfb, 0x01010101, 0x7fffffff, 0x80000000, 0xffffffff, +) +ROUND_WORDS = ( + 0x00000000, 0x01000100, 0x00010001, 0xfe02fe00, 0xff01ff01, 0xffffffff, +) + +DRAW_SETS = ( + ( + (0x01020304, 0x04030201, 0xfe02fe00), # upper S2 byte bits set, all LSBs 0 + (0x01020304, 0x04030201, 0x01010101), # all S2 byte LSBs 1 + (0x7f80ff00, 0x807f00ff, 0x01000100), # alternating LSBs + boundary sums + (0xffffffff, 0xffffffff, 0xffffffff), # max sum 511 >> 1 == 255 in every byte + ), + ( + (0x00000000, 0x01010101, 0xfe00fe00), # 0+1+0 >> 1 == 0 vs upper bits ignored + (0x00000000, 0x01010101, 0x01010101), # 0+1+1 >> 1 == 1 + (0xfefdfcfb, 0x01020304, 0x00010001), # sum 255 + carry -> 256 >> 1 == 128 + (0x12345678, 0x9abcdef0, 0xab01cd00), # mixed bytes and S2 upper bits + ), +) + + +def extract_helper(hlsl): + m = re.search(r'uint lerp_u8\(uint a, uint b, uint c\)\s*\{\s*return\s+(.+?);\s*\}', hlsl) + assert m, 'lerp_u8 helper missing from HLSL' + return m.group(1) + + +def controls(): + pipe = G.Pipeline(vs_words(DRAW_SETS[0]), PS_WORDS, root_blob()) + ps = pipe.hlsl_ps() + check('lerp_u8 helper emitted on demand', 'uint lerp_u8(uint a, uint b, uint c)' in ps) + for lane in range(4): + expected_line = f'v{12 + lane} = lerp_u8(v{lane}, v{4 + lane}, v{8 + lane});' + check(f'lane {lane} assignment emitted', expected_line in ps) + + # On-demand check: a pixel shader without v_lerp_u8 must not emit lerp_u8(). + plain_ps = G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('lerp_u8 omitted when unused', 'lerp_u8(' not in plain_ps) + + # Evaluate the exact emitted helper body over 600 edge triples. + evaluator = HlslExpr(extract_helper(ps)) + for a in U8_WORDS: + for b in U8_WORDS: + for c in ROUND_WORDS: + got = evaluator.run({'a': a, 'b': b, 'c': c})[0] + want = ref_lerp_u8(a, b, c) + assert got == want, (hex(a), hex(b), hex(c), hex(got), hex(want)) + print(f'v_lerp_u8: emitted helper matches reference on {len(U8_WORDS) * len(U8_WORDS) * len(ROUND_WORDS)} cases: ok') + + # Accepted operand forms (VGPR, SGPR, inline constants, literal) and exec-masked emission. + for asm in ( + 'v_lerp_u8 v12, v0, v4, v8', + 'v_lerp_u8 v12, s4, v4, v8', + 'v_lerp_u8 v12, 1, v4, 0', + 'v_lerp_u8 v12, 0x01020304, v4, v8', + ): + probe = Probe() + probe.lower('v_lerp_u8', asm, [o.strip() for o in asm.split(None, 1)[1].split(',')], []) + assert probe.lines and 'lerp_u8(' in probe.lines[0], (asm, probe.lines) + probe_masked = Probe() + probe_masked.exec_known = False + probe_masked.lower('v_lerp_u8', 'v_lerp_u8 v12, v0, v4, v8', ['v12', 'v0', 'v4', 'v8'], []) + check('exec-masked v_lerp_u8 guards assignment', + probe_masked.lines == ['if (exec & 1) v12 = lerp_u8(v0, v4, v8);']) + print('accepted operand forms translate: ok') + + # Refusals: VOP3A encoding neg/abs/clamp/omod/op_sel, plus wrong operand counts. + def must_refuse(fn, label, needle=''): + try: + fn() + except G.Unsupported as error: + check(f'{label} refused', needle in str(error) if needle else bool(str(error))) + else: + raise AssertionError(f'{label} was accepted') + + for label, bad, needle in ( + ('abs0', vop3a(OPCODE, 12, 256, 260, 264, abs_bits=1), 'with neg/abs'), + ('neg2', vop3a(OPCODE, 12, 256, 260, 264, neg=4), 'with neg/abs'), + ('neg_inline0', vop3a(OPCODE, 12, 129, 260, 264, neg=1), 'with neg/abs'), + ('abs_inline0', vop3a(OPCODE, 12, 129, 260, 264, abs_bits=1), 'with neg/abs'), + ('clamp', vop3a(OPCODE, 12, 256, 260, 264, clamp=1), ''), + ('omod', vop3a(OPCODE, 12, 256, 260, 264, omod=1), ''), + ('op_sel', vop3a(OPCODE, 12, 256, 260, 264, op_sel=1), ''), + ): + must_refuse(lambda b=bad: G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + b + POST_WORDS, root_blob()), label, needle) + for bad_ops in (['v12', 'v0', 'v4'], ['v12', 'v0', 'v4', 'v8', 'v9']): + must_refuse(lambda ops=bad_ops: Probe().lower('v_lerp_u8', 'v_lerp_u8', ops, []), f'arity {len(bad_ops)}') + print('modifiers and wrong operand counts refused: ok') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = [('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else [] + compilers.append(('dxc', dxc, 'vs_6_0', 'ps_6_0')) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for tag, compiler, vs_profile, ps_profile in compilers: + for idx, triples in enumerate(DRAW_SETS): + pipe = G.Pipeline(vs_words(triples), PS_WORDS, root_blob()) + vs_bin = compile_hlsl(compiler, tag, pipe.hlsl_vs(), f'{tag}_vs_{idx}', vs_profile, directory) + ps_text = pipe.hlsl_ps() + ps_bin = compile_hlsl(compiler, tag, ps_text, f'{tag}_ps_{idx}', ps_profile, directory) + want = words_text(ref_lerp_u8(*t) for t in triples) + run = draw(renderer, adapter, vs_bin, ps_bin, want) + sys.stdout.write(run.stdout) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, f'{tag} set {idx} failed:\n{run.stdout}\n{run.stderr}' + print(f'{tag} v_lerp_u8 draw {idx}: {want}') + if idx == 0: + # Mutation 1: drop `& 1u` so upper S2 byte bits leak into the byte average. + mut1 = ps_text.replace('(c & 1u)', '(c & 0xffu)').replace('((c >> 8) & 1u)', '((c >> 8) & 0xffu)') + assert mut1 != ps_text + mut1_bin = compile_hlsl(compiler, tag, mut1, f'{tag}_ps_mut_mask', ps_profile, directory) + run_m1 = draw(renderer, adapter, vs_bin, mut1_bin, want) + assert run_m1.returncode != 0, f'{tag} upper-bit mask mutation escaped' + print(f'{tag} v_lerp_u8 mask mutation: fails as expected (rc={run_m1.returncode})') + # Mutation 2: drop rounding bits (S2 = 0). + mut2 = ps_text.replace('lerp_u8(v0, v4, v8)', 'lerp_u8(v0, v4, 0u)').replace( + 'lerp_u8(v1, v5, v9)', 'lerp_u8(v1, v5, 0u)') + assert mut2 != ps_text + mut2_bin = compile_hlsl(compiler, tag, mut2, f'{tag}_ps_mut_round', ps_profile, directory) + run_m2 = draw(renderer, adapter, vs_bin, mut2_bin, want) + assert run_m2.returncode != 0, f'{tag} drop-rounding mutation escaped' + print(f'{tag} v_lerp_u8 round mutation: fails as expected (rc={run_m2.returncode})') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + check_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_gfx2hlsl_load_desc_check.py b/tests/startup_gfx2hlsl_load_desc_check.py new file mode 100644 index 0000000000..597f201589 --- /dev/null +++ b/tests/startup_gfx2hlsl_load_desc_check.py @@ -0,0 +1,143 @@ +"""Verify that compute buffer loads through a modified or overwritten descriptor word are refused. + +Refs #2901, #2618. +""" +from pathlib import Path +import struct +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + + +def sop2(op, d, a, b, lit=None): + return struct.pack('<I', 0x80000000 | op << 23 | d << 16 | b << 8 | a) + (b'' if lit is None else struct.pack('<I', lit)) + + +def sop1(op, d, a): + return struct.pack('<I', 0xbe800000 | d << 16 | op << 8 | a) + + +W = C.WORDS_A +LOAD_SITE = W.index(bytes.fromhex('001030e004050380')) +STORE_SITE = C.STORE_A + +# r = first register of the descriptor (12 for load s[12:15], 16 for store s[16:19]) +# Word 1: stride; Word 2: NUM_RECORDS; Word 3: format/OOB +EDITS = { + 'descnum copy w1': lambda r: sop2(0x20, 21, r + 2, 130) + sop1(0x03, r + 1, 21), + 'descnum copy w2': lambda r: sop2(0x20, 21, r + 2, 130) + sop1(0x03, r + 2, 21), + 'descnum copy w3': lambda r: sop2(0x20, 21, r + 2, 130) + sop1(0x03, r + 3, 21), + 'descnum alu w2': lambda r: sop2(0x20, 21, r + 2, 130) + sop2(0x20, r + 2, 21, 128), + 'in-place and 0 w2': lambda r: sop2(0x0e, r + 2, r + 2, 128), + 'constant 0 w2': lambda r: sop1(0x03, r + 2, 128), +} + + +def translate_code(code): + return G.ComputePipeline(code, C.root_blob(), C.CASES['A'][2], (2, 3, 4)).hlsl_cs() + + +def check_refusals(): + # 1. Base case A translates cleanly without edits + base_hlsl = translate_code(W) + assert 'v5 = r0.Load(a + 0);' in base_hlsl, 'base case A load missing' + assert 'u0.Store(a, v5);' in base_hlsl, 'base case A store missing' + + # 2. Check each edit refused for both load and store + for label, edit in EDITS.items(): + # Check load refusal + load_code = W[:LOAD_SITE] + edit(12) + W[LOAD_SITE:] + try: + translate_code(load_code) + raise AssertionError(f'expected load refusal for {label}, but translation succeeded') + except G.Unsupported as e: + assert 'buffer load through a modified descriptor' in str(e), ( + f'unexpected refusal for load {label}: {e}' + ) + + # Check store refusal + store_code = W[:STORE_SITE] + edit(16) + W[STORE_SITE:] + try: + translate_code(store_code) + raise AssertionError(f'expected store refusal for {label}, but translation succeeded') + except G.Unsupported as e: + assert 'buffer store through a modified descriptor' in str(e), ( + f'unexpected refusal for store {label}: {e}' + ) + + # 3. Proven stride-0 clear on raw load is accepted (stride0_ok=True for non-indexed load) + # s_and_b32 s13, s13, 0xc000ffff + stride0_inst = sop2(0x0e, 13, 13, 255) + struct.pack('<I', 0xc000ffff) + stride0_hlsl = translate_code(W[:LOAD_SITE] + stride0_inst + W[LOAD_SITE:]) + assert 'v5 = r0.Load(a + 0);' in stride0_hlsl, 'stride0 load failed to translate' + + # 4. Incorrect stride mask (0xc000fff0) is refused on load + bad_stride_inst = sop2(0x0e, 13, 13, 255) + struct.pack('<I', 0xc000fff0) + try: + translate_code(W[:LOAD_SITE] + bad_stride_inst + W[LOAD_SITE:]) + raise AssertionError('expected refusal for bad stride mask on load, but succeeded') + except G.Unsupported as e: + assert 'buffer load through a modified descriptor' in str(e), f'unexpected refusal: {e}' + + # 5. Proven structured-to-raw conversion on load descriptor is accepted (raw_conversion_ok=True) + # Extracts stride from s13, clears stride in s13, scales s14 by s21, sets raw OOB in s15. + raw_conv = ( + sop2(0x27, 21, 13, 255, 0xe0010) + + sop2(0x0e, 13, 13, 255, 0xc000ffff) + + sop2(0x26, 14, 14, 21) + + sop2(0x0e, 15, 15, 255, 0xcfffffff) + + sop2(0x10, 15, 15, 255, 0x30000000) + ) + raw_hlsl = translate_code(W[:LOAD_SITE] + raw_conv + W[LOAD_SITE:]) + assert 'v5 = r0.Load(a + 0);' in raw_hlsl, 'raw conversion load failed to translate' + + # 6. Incomplete or invalid raw conversion (e.g. constant multiplier 4 instead of extracted stride s21) is refused + bad_raw_conv = ( + sop2(0x27, 21, 13, 255, 0xe0010) + + sop2(0x0e, 13, 13, 255, 0xc000ffff) + + sop2(0x26, 14, 14, 132) + # literal 4 + sop2(0x0e, 15, 15, 255, 0xcfffffff) + + sop2(0x10, 15, 15, 255, 0x30000000) + ) + try: + translate_code(W[:LOAD_SITE] + bad_raw_conv + W[LOAD_SITE:]) + raise AssertionError('expected refusal for bad raw conversion on load, but succeeded') + except G.Unsupported as e: + assert 'buffer load through a modified descriptor' in str(e), f'unexpected refusal: {e}' + + # 7. Formatted indexed buffer load through a modified descriptor is refused. + # Inserting `s_and_b32 s21, s13, 0xc000ffff` immediately before LOAD_L writes + # a derived descriptor word to s21, leaving the four operand registers s[12:15] + # intact. The indexed formatted load must be refused with 'indexed load through a modified descriptor'. + prefix_l = C.WORDS_L[:C.WORDS_L.index(C.LOAD_L)] + end_l = bytes.fromhex('000081bf') + s_and_s21_s13 = sop2(0x0e, 21, 13, 255, 0xc000ffff) + formatted_mod_code = prefix_l + s_and_s21_s13 + C.LOAD_L + end_l + try: + G.ComputePipeline(formatted_mod_code, C.root_blob(), C.CASES['L-uint'][2], (2, 3, 4)).hlsl_cs() + raise AssertionError('expected refusal for formatted indexed load with modified descriptor, but translated') + except G.Unsupported as e: + assert 'indexed load through a modified descriptor' in str(e), f'unexpected refusal: {e}' + + # 8. Negative control: pre-fix mutant (bypassing load descriptor validation) + # Under this mutant, unvalidated loads must translate (escaping detection). + real_load_desc = G.Stage.load_descriptor + try: + G.Stage.load_descriptor = lambda self, tok, what, **kw: self.descriptor(tok) + for label, edit in EDITS.items(): + mutant_code = W[:LOAD_SITE] + edit(12) + W[LOAD_SITE:] + res = translate_code(mutant_code) + assert 'v5 = r0.Load(a + 0);' in res, f'mutant failed to reproduce issue on {label}' + finally: + G.Stage.load_descriptor = real_load_desc + + print('compute buffer load modified descriptor checks passed') + + +if __name__ == '__main__': + check_refusals() diff --git a/tests/startup_gfx2hlsl_mad64_check.py b/tests/startup_gfx2hlsl_mad64_check.py new file mode 100644 index 0000000000..475ba6bc93 --- /dev/null +++ b/tests/startup_gfx2hlsl_mad64_check.py @@ -0,0 +1,306 @@ +"""v_mad_u64_u32 and v_mad_i64_i32 in tools/startup/gfx2hlsl.py (Part of #1723). + +D = S0 * S1 + S2 modulo 2^64 with two 32-bit factors and a 64-bit S2, written to a VGPR pair. The unsigned form +also writes the carry-out of the 64-bit add to a lane mask; the signed form is accepted only with `null`. + + (no arguments) pure Python controls described below + binary <llvm-mc> reassemble the pixel fixtures and compare them with the words below + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pixel shaders (FXC ps_5_1 when given, DXC ps_6_0), + draw one pixel per input and compare mrt0 with the 64-bit reference + +Draw pixel: v0 = S0, v1 = S1, v[2:3] = the 64-bit S2. The unsigned shader exports (lo, hi, 1.0f when carry else 0, 0), the signed +shader exports (lo, hi, 0, 0). A mutation that drops the low-word carry into the high word must read the exact +mutated words, so the draw cannot pass by accident. + +Controls: translate each form, evaluate the emitted helpers in 32-bit arithmetic against an independent +Python 64-bit reference over a value grid, and check the refusals. Pure Python, no GPU and no assembler. +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, Expr, Probe, check, vs_source, vs_words, words_text) + +M64 = (1 << 64) - 1 +VALUES = (0, 1, 2, 0xffff, 0x10000, 0x7fffffff, 0x80000000, 0x89abcdef, 0xfffffffe, 0xffffffff) +ADDENDS = (0, 1, M64, 1 << 63, 0x00000001ffffffff, 0xfedcba9876543210, 0x7fffffffffffffff) + +BODY_SOURCE = { + False: ('v_mad_u64_u32 v[12:13], vcc_lo, v0, v1, v[2:3]\n' + 'v_cndmask_b32_e64 v14, 0, 1.0, vcc_lo\nv_mov_b32 v15, 0\n'), + True: 'v_mad_i64_i32 v[12:13], null, v0, v1, v[2:3]\nv_mov_b32 v14, 0\nv_mov_b32 v15, 0\n', +} +BODY_WORDS = { + False: bytes.fromhex('0c6a76d500030a040e0001d580e4a90180021e7e'), + True: bytes.fromhex('0c7d77d500030a0480021c7e80021e7e'), +} +# (S0, S1, S2): carry out of the low word, carry out of the 64-bit add, negative factors, the largest products. +DRAWS = ( + (0xffffffff, 0xffffffff, 0xffffffffffffffff), + (0x89abcdef, 0x76543210, 0xfedcba9876543210), + (0xffffffff, 0x00000002, 0x00000001ffffffff), + (0x80000000, 0x80000000, 0x8000000000000000), + (0x80000000, 0x7fffffff, 0x7fffffffffffffff), + (0xfffffffe, 0x00010001, 0x00000000ffff0000), + (0x0000ffff, 0x0000ffff, 0), + (0x00000003, 0x00000005, 0x000000000000000f), +) + + +def signed32(x): + return x - (1 << 32) if x >> 31 else x + + +def reference(signed, a, b, c): + """(result, carry) from plain Python integers: the exact product plus the 64-bit addend.""" + product = (signed32(a) * signed32(b) if signed else a * b) & M64 + total = product + c + return total & M64, int(total > M64) + + +class Evaluator: + """Runs the emitted mulhi32/mad64u/mad64i helpers with the 32-bit evaluator of the bit-ALU check.""" + + def __init__(self, text): + self.helpers = {} + for name in ('mulhi32', 'mad64u', 'mad64i'): + m = re.search(r'uint3? %s\((.*?)\) \{ (.*?) \}$' % name, text, re.M) + assert m, '%s missing from the generated HLSL' % name + self.helpers[name] = ([p.split()[1] for p in m.group(1).split(',')], m.group(2)) + self.original_call = Expr.call + Expr.call = staticmethod(self.call) + + def close(self): + Expr.call = staticmethod(self.original_call) + + def call(self, name, args): + if name == 'mulhi32': + return self.run('mulhi32', [a[0] for a in args])[0], False + return self.original_call(name, args) + + def run(self, name, values): + params, body = self.helpers[name] + env = dict(zip(params, values)) + stmts = [s.strip() for s in body.split(';') if s.strip()] + for stmt in stmts[:-1]: + for item in re.split(r',\s*(?=\w+ = )', stmt[len('uint '):]): + var, rhs = [x.strip() for x in item.split('=', 1)] + env[var] = Expr(rhs).run(env)[0] + ret = stmts[-1] + inner = re.fullmatch(r'return (?:uint3\((.*)\)|(.*))', ret) + if inner.group(2) is not None: + return [Expr(inner.group(2)).run(env)[0]] + parts, depth, start = [], 0, 0 + text = inner.group(1) + for i, ch in enumerate(text): + depth += ch == '(' + depth -= ch == ')' + if ch == ',' and depth == 0: + parts.append(text[start:i]) + start = i + 1 + parts.append(text[start:]) + return [Expr(p).run(env)[0] for p in parts] + + +def translate(asm): + probe = Probe() + probe.masks, probe.varying_s = set(), set() + probe.one(asm.split(' ', 1)[0], asm) + return probe + + +def refused(asm): + try: + translate(asm) + except G.Unsupported: + return True + return False + + +def helper_source(): + """The helpers as a pixel stage emits them (a program that only exports).""" + return G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + + +def controls(): + ev = Evaluator(helper_source()) + try: + for signed, name in ((False, 'mad64u'), (True, 'mad64i')): + bad = None + for a in VALUES: + for b in VALUES: + for c in ADDENDS: + lo, hi, carry = ev.run(name, [a, b, c & MASK, c >> 32]) + want, want_carry = reference(signed, a, b, c) + if (hi << 32 | lo) != want or (not signed and carry != want_carry): + bad = bad or (hex(a), hex(b), hex(c), hex(hi << 32 | lo), hex(want), carry) + check('%s: %d inputs match the 64-bit reference' % (name, len(VALUES) ** 2 * len(ADDENDS)), bad is None) + finally: + ev.close() + + u = translate('v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21]') + check('unsigned form writes the pair and vcc', + u.lines == ['{ uint3 r = mad64u(v18, v19, v20, v21);', 'v12 = r.x;', 'v13 = r.y;', 'vcc = r.z;', '}']) + s = translate('v_mad_u64_u32 v[12:13], s60, v18, v19, -1') + check('inline S2 is sign-extended and an SGPR mask is tracked', + s.lines[0] == '{ uint3 r = mad64u(v18, v19, 4294967295u, 4294967295u);' and 60 in s.masks) + i = translate('v_mad_i64_i32 v[12:13], null, v18, v19, s[46:47]') + check('signed form with null writes only the pair', + i.lines == ['{ uint3 r = mad64i(v18, v19, s46, s47);', 'v12 = r.x;', 'v13 = r.y;', '}']) + overlap = translate('v_mad_u64_u32 v[20:21], s60, v18, v19, v[20:21]') + check('a destination overlapping S2 reads S2 before it writes', overlap.lines[0].endswith('v20, v21);')) + + for asm in ('v_mad_u64_u32 v[14:15], vcc_lo, s60, 1, 0', + 'v_mad_u64_u32 v[14:15], vcc_lo, vcc_lo, 1, 0', + 'v_mad_u64_u32 v[14:15], vcc_lo, v18, v19, s[60:61]', + 'v_mad_u64_u32 v[14:15], vcc_lo, v18, v19, s[59:60]'): + masked = Probe() + masked.masks, masked.varying_s = {60}, set() + try: + masked.one('v_mad_u64_u32', asm) + ok = False + except G.Unsupported: + ok = True + check('refused lane-mask input: %s' % asm, ok) + unmasked = Probe() + unmasked.masks, unmasked.varying_s = {60}, set() + unmasked.one('v_mad_u64_u32', 'v_mad_u64_u32 v[14:15], vcc_lo, s58, 1, s[56:57]') + check('a scalar that is not a lane mask is still accepted', bool(unmasked.lines)) + tracked = Probe() + tracked.masks, tracked.varying_s = set(), set() + tracked.uniform_v, tracked.scc_uniform = set(), True + tracked.one('v_mad_u64_u32', 'v_mad_u64_u32 v[12:13], s60, v18, v19, v[20:21]') + check('an SGPR carry mask is marked varying, not uniform', + 60 in tracked.masks and 60 in tracked.varying_s and not tracked.uniform_source('s60')) + for asm in ('v_mad_i64_i32 v[12:13], vcc_lo, v18, v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], null, v18, v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21] clamp', + 'v_mad_u64_u32 v12, vcc_lo, v18, v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], vcc_lo, v[18:19], v19, v[20:21]', + 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19', + 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v20'): + check('refused: %s' % asm, refused(asm)) + + # Discarded carry destinations have no VCC effect, even on forms the translator refuses. + for name, asm, may in ( + ('v_mad_u64_u32', 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21]', {'vcc', 'vcc_hi'}), + ('v_mad_u64_u32', 'v_mad_u64_u32 v[12:13], null, v18, v19, v[20:21]', set()), + ('v_mad_i64_i32', 'v_mad_i64_i32 v[12:13], null, v18, v19, v[20:21]', set()), + ('v_add_co_u32', 'v_add_co_u32 v4, vcc_lo, v5, v6', {'vcc', 'vcc_hi'}), + ('v_cmp_gt_u32_e64', 'v_cmp_gt_u32_e64 vcc_lo, v1, v2', {'vcc', 'vcc_hi'})): + _, writes, may_write = G.scalar_effects(name, asm) + check('%s may-writes %s' % (asm, ' and '.join(sorted(may)) or 'no VCC half'), + (writes | may_write) & G.VCC_KEYS == may and 'vcc_hi' not in writes) + # A skipped-block join must not retain a stale high-half clear fact. + start = {('exec', 0), ('exec_hi', 1), ('vcc_hi', 0)} + mad = 'v_mad_u64_u32 v[12:13], vcc_lo, v18, v19, v[20:21]' + after = G.clear_after('v_mad_u64_u32', mad, G.scalar_effects('v_mad_u64_u32', mad)[2], start) + check('a clear vcc_hi fact does not survive the unsigned mad', after == start - {('vcc_hi', 0)}) + null_mad = 'v_mad_u64_u32 v[12:13], null, v18, v19, v[20:21]' + after_null = G.clear_after('v_mad_u64_u32', null_mad, G.scalar_effects('v_mad_u64_u32', null_mad)[2], start) + check('a discarded null carry keeps the vcc_hi fact', after_null == start) + + +def pack_draw(a, b, c): + return [(a, 0, 0), (b, 0, 0), (c & MASK, 0, 0), (c >> 32, 0, 0)] + + +def ps_words(signed): + return PRE_WORDS + BODY_WORDS[signed] + POST_WORDS + + +def pixel_text(signed, mutate=False): + text = G.Pipeline(vs_words(pack_draw(0, 0, 0)), ps_words(signed), root_blob()).hlsl_ps() + if mutate: + helper = 'mad64i' if signed else 'mad64u' + # Drop the low-word carry into the high word, in the helper this shader calls. + mutated = re.sub(r'(uint3 %s\(.*?\) \{.*?)(?:hi = hs \+ c0|\+ \(lo < pl \? 1u : 0u\))' % helper, + lambda m: m.group(1) + ('hi = hs + 0u' if not signed else '+ 0u'), text, count=1) + assert mutated != text, helper + text = mutated + return text + + +def expected_words(signed, a, b, c): + result, carry = reference(signed, a, b, c) + return [result & MASK, result >> 32, 0 if signed else (0x3f800000 if carry else 0), 0] + + +def mutated_words(signed, a, b, c): + """The same reference with the low-word carry dropped from the high word (the carry-out stays exact).""" + product = (signed32(a) * signed32(b) if signed else a * b) & M64 + low = (product & MASK) + (c & MASK) + hi = ((product >> 32) + (c >> 32)) & MASK + total = product + c + return [low & MASK, hi, 0 if signed else (0x3f800000 if total > M64 else 0), 0] + + +def check_binary(llvm_mc): + for signed in (False, True): + built = assemble(llvm_mc, BODY_SOURCE[signed]) + if built != BODY_WORDS[signed]: + raise AssertionError('signed=%s: assembled %s, recorded %s' % (signed, built.hex(), BODY_WORDS[signed].hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for draw_inputs in DRAWS: + chunk = pack_draw(*draw_inputs) + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (draw_inputs,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for signed in (False, True): + label = 'i64' if signed else 'u64' + good_ps = compile_hlsl(compiler, kind, pixel_text(signed), 'ps_mad_%s_%s' % (label, kind), + ps_profile, directory) + for index, inputs in enumerate(DRAWS): + vs = compile_hlsl(compiler, kind, + G.Pipeline(vs_words(pack_draw(*inputs)), ps_words(signed), root_blob()).hlsl_vs(), + 'vs_mad_%s_%d_%s' % (label, index, kind), vs_profile, directory) + expected = words_text(expected_words(signed, *inputs)) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, label, inputs, run.stdout, run.stderr)) + print('%s %s draw %d: %s' % (kind, label, index, expected), flush=True) + if index: + continue + wrong = words_text(mutated_words(signed, *inputs)) + bad_ps = compile_hlsl(compiler, kind, pixel_text(signed, True), 'mutated_mad_%s_%s' % (label, kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s %s mutation did not read %s\n%s\n%s' + % (kind, label, wrong, run.stdout, run.stderr)) + print('%s %s mutation: fails as expected, reads %s' % (kind, label, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_mad_u32_u16_check.py b/tests/startup_gfx2hlsl_mad_u32_u16_check.py new file mode 100644 index 0000000000..98ca9a61ce --- /dev/null +++ b/tests/startup_gfx2hlsl_mad_u32_u16_check.py @@ -0,0 +1,374 @@ +"""Lower v_mad_u32_u16 in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the fixture sources and compare them with the encoded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input sets and compare the four result words + +RDNA 2 ISA semantics for v_mad_u32_u16 (when op_sel:[0,0,0] and no clamp/omod/abs/neg): + D.u32 = (S0.u32 & 0xffffu) * (S1.u32 & 0xffffu) + S2.u32 (32-bit unsigned wraparound). + +S0 and S1 read only bits [15:0] (allowed on low16-only odd-dmask d16 image_load results), while S2 reads all +32 bits (refused on low16-only registers). Any modifier (op_sel, clamp, omod, abs, neg) or wrong operand count +is refused. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import (Expr, POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, # noqa: E402 + lane_expressions, lane_results, vs_source, vs_words, words_text) + +MASK = 0xffffffff +VOP3_MAD_U32_U16 = 0x373 + + +def ref_mad_u32_u16(s0, s1, s2): + return ((s0 & 0xffff) * (s1 & 0xffff) + s2) & MASK + + +def encode_mad_u32_u16(vdst, src0, src1, src2, *, literal=None, op_sel=(0, 0, 0, 0), + abs_bits=(0, 0, 0), neg=(0, 0, 0), clamp=0, omod=0): + """Encode synthetic gfx1013 VOP3A bytes for v_mad_u32_u16 (opcode 0x373).""" + w0 = (0b110101 << 26) | (VOP3_MAD_U32_U16 << 16) | ((clamp & 1) << 15) | (vdst & 0xff) + for i, bit in enumerate(op_sel): + w0 |= (bit & 1) << (11 + i) + for i, bit in enumerate(abs_bits): + w0 |= (bit & 1) << (8 + i) + w1 = ((src0 & 0x1ff) | ((src1 & 0x1ff) << 9) | ((src2 & 0x1ff) << 18) | + ((omod & 0x3) << 27) | ((neg[0] & 1) << 29) | ((neg[1] & 1) << 30) | ((neg[2] & 1) << 31)) + if 255 in (src0, src1, src2): + assert literal is not None + return struct.pack('<3I', w0, w1, literal & MASK) + assert literal is None + return struct.pack('<2I', w0, w1) + + +BODY_WORDS = b''.join(encode_mad_u32_u16(12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) + for lane in range(4)) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS +BODY_SOURCE = ''.join('v_mad_u32_u16 v%d, v%d, v%d, v%d\n' % (12 + lane, lane, 4 + lane, 8 + lane) + for lane in range(4)) + +# Synthetic non-register forms decoded through G.decode() and translated via Stage. +SYNTHETIC_CASES = [ + ( + 'literal src0 + vgpr src1 + inline 0 src2', + encode_mad_u32_u16(1, 255, 256 + 15, 128 + 0, literal=0x1f0), + 'v_mad_u32_u16 v1, 0x1f0, v15, 0', + 'v1 = (0x000001f0u & 0xffffu) * (v15 & 0xffffu) + 0x00000000u;', + lambda v: ref_mad_u32_u16(0x1f0, v['v15'], 0), + ), + ( + 'sgpr src0 + inline -1 src1 + vgpr src2', + encode_mad_u32_u16(3, 4, 193, 256 + 9), + 'v_mad_u32_u16 v3, s4, -1, v9', + 'v3 = (s4 & 0xffffu) * (0xffffffffu & 0xffffu) + v9;', + lambda v: ref_mad_u32_u16(v['s4'], 0xffffffff, v['v9']), + ), + ( + 'vgpr src0 + inline 7 src1 + literal src2', + encode_mad_u32_u16(2, 256 + 5, 128 + 7, 255, literal=0x12345678), + 'v_mad_u32_u16 v2, v5, 7, 0x12345678', + 'v2 = (v5 & 0xffffu) * (0x00000007u & 0xffffu) + 0x12345678u;', + lambda v: ref_mad_u32_u16(v['v5'], 7, 0x12345678), + ), +] + +S01_EDGES = [ + 0, 1, 2, 0x7fff, 0x8000, 0xffff, + 0x00010000, 0xdead0000, 0xffff0000, + 0xffff0001, 0xdeadbeef, 0x7fffffff, 0x80000000, 0x8000ffff, MASK, +] +S2_EDGES = [0, 1, 0x12345678, 0x7fffffff, 0x80000000, 0xfffe0000, 0xffff0000, MASK] +GRID = [(s0, s1, s2) for s0 in S01_EDGES for s1 in S01_EDGES for s2 in S2_EDGES] + +# 4 input sets per chunk; chunk 0 simultaneously distinguishes all three mutations below. +DRAW_SETS = [ + # Chunk 0: non-zero upper-16 bits on S0, S1, and S2; all distinct from mutations. + (0xdead0003, 0xbeef0005, 0x12345678), + (0xffff0007, 0x80000009, 0xabcd0000), + (0x0001ffff, 0x0002ffff, 0x00020000), + (0x12340002, 0x56780003, 0x89abcdef), + # Chunk 1: max product 0xffff * 0xffff = 0xfffe0001, wraparound with 0xffffffff, zero product + upper S2. + (0x0000ffff, 0x0000ffff, 0x00000000), + (0x0000ffff, 0x0000ffff, MASK), + (0xdead0000, 0xbeef0000, 0x76543210), + (0xffff0003, 0xffff0005, MASK), + # Chunk 2: boundary bits 0x8000 * 0x8000, 0xffff * 1 + 0xffff0000, wraparound to 0, large addend. + (0x00008000, 0x00008000, 0x00000000), + (0xabcdffff, 0x12340001, 0xffff0000), + (0x00010001, 0x0001ffff, 0xffff0000), + (0xffffffff, 0xffffffff, 0x0001ffff), +] + +MUTATIONS = { + 'drop_s0_mask': ( + r'\((v[0-3]) & 0xffffu\) \* \((v[4-7]) & 0xffffu\) \+ (v(?:[89]|1[01]))', + r'\1 * (\2 & 0xffffu) + \3', + lambda s0, s1, s2: (s0 * (s1 & 0xffff) + s2) & MASK, + ), + 'drop_s1_mask': ( + r'\((v[0-3]) & 0xffffu\) \* \((v[4-7]) & 0xffffu\) \+ (v(?:[89]|1[01]))', + r'(\1 & 0xffffu) * \2 + \3', + lambda s0, s1, s2: ((s0 & 0xffff) * s1 + s2) & MASK, + ), + 'mask_s2': ( + r'\((v[0-3]) & 0xffffu\) \* \((v[4-7]) & 0xffffu\) \+ (v(?:[89]|1[01]))', + r'(\1 & 0xffffu) * (\2 & 0xffffu) + (\3 & 0xffffu)', + lambda s0, s1, s2: ((s0 & 0xffff) * (s1 & 0xffff) + (s2 & 0xffff)) & MASK, + ), +} + + +class Probe(G.Stage): + """Minimal Stage for single-instruction / decoded-byte translation probes.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.low16_only_v = set() + self.pinned_low16_v = set() + self.whole_read_v = set() + + +def check(label, ok, detail=''): + print('%s: %s%s' % (label, 'ok' if ok else 'MISMATCH', ' ' + detail if detail and not ok else '')) + if not ok: + raise AssertionError(label) + + +def translate_ps(mutate=None): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate is not None: + pattern, replacement, _ = MUTATIONS[mutate] + mutated, count = re.subn(pattern, replacement, text) + assert count == 4 and mutated != text, (mutate, count, text) + text = mutated + return pipe, text + + +def decode_one(word_bytes): + decoded = G.decode(word_bytes) + assert len(decoded) == 1, decoded + _, size, name, asm = decoded[0] + assert size == len(word_bytes), (size, len(word_bytes), decoded) + return name, asm + + +def translate_bytes(word_bytes): + name, asm = decode_one(word_bytes) + stage = Probe() + stage.one(name, asm) + return name, asm, stage + + +def refused_bytes(word_bytes): + try: + translate_bytes(word_bytes) + except G.Unsupported as exc: + return str(exc) + return None + + +def refused_asm(asm): + try: + stage = Probe() + stage.one(asm.split(' ', 1)[0], asm) + except G.Unsupported as exc: + return str(exc) + return None + + +def controls(): + # 1. Decode check on the 4-lane pixel body bytes. + body_decoded = G.decode(BODY_WORDS) + expected_body = ['v_mad_u32_u16 v%d, v%d, v%d, v%d' % (12 + i, i, 4 + i, 8 + i) for i in range(4)] + check('synthetic BODY_WORDS decode', + [asm for _, _, _, asm in body_decoded] == expected_body + and all(name == 'v_mad_u32_u16' for _, _, name, _ in body_decoded)) + + # 2. Value-level verification over all 4 lanes across the 1800-case grid. + _, ps_text = translate_ps() + exprs = lane_expressions(ps_text) + mismatch = None + for index, (s0, s1, s2) in enumerate(GRID): + lane = index % 4 + env = {'v%d' % lane: s0, 'v%d' % (4 + lane): s1, 'v%d' % (8 + lane): s2} + got = exprs[lane].run(env)[0] + want = ref_mad_u32_u16(s0, s1, s2) + if got != want: + mismatch = (lane, (s0, s1, s2), got, want) + break + check('pixel lowering: %d 32-bit inputs match reference' % len(GRID), mismatch is None, repr(mismatch)) + + # 3. Synthetic non-register forms: literal, inline integer, SGPR. + sample_vals = { + 'v5': 0xdead0011, 'v9': 0x87654321, 'v15': 0xbeef0005, 's4': 0xcafe0009, + } + for label, word_bytes, want_asm, want_line, ref_fn in SYNTHETIC_CASES: + name, asm, stage = translate_bytes(word_bytes) + check('decode %s' % label, name == 'v_mad_u32_u16' and asm == want_asm, asm) + check('lower %s' % label, stage.lines == [want_line], repr(stage.lines)) + parsed = Expr(stage.lines[0].split(' = ', 1)[1].rstrip(';')) + for hi_s in (0x00000000, 0xdead0000, 0xffff0000): + for lo_s in (0x0000, 0x0001, 0xffff): + env = dict(sample_vals) + val = hi_s | lo_s + env['v5'] = val + env['v15'] = val + env['s4'] = val + env['v9'] = (hi_s ^ 0x12345678) | lo_s + got = parsed.run(env)[0] + want = ref_fn(env) + assert got == want, (label, env, got, want) + check('evaluate %s' % label, True) + + # 4. low16_only contract: S0 and S1 allow odd-dmask d16 low16_only_v; S2 must refuse whole-word read; + # writing dst clears low16_only_v on dst. + stage = Probe() + stage.low16_only_v.update({4, 5}) + stage.one('v_mad_u32_u16', 'v_mad_u32_u16 v4, v4, v5, v7') + check('low16_only allowed on S0/S1 and cleared on dst', + 4 not in stage.low16_only_v and 4 not in stage.whole_read_v and 5 not in stage.whole_read_v + and 7 in stage.whole_read_v) + + stage_s2 = Probe() + stage_s2.low16_only_v.add(7) + try: + stage_s2.one('v_mad_u32_u16', 'v_mad_u32_u16 v6, v4, v5, v7') + except G.Unsupported as exc: + s2_reason = str(exc) + else: + s2_reason = None + check('low16_only refused on S2', s2_reason == 'whole-word read of v7 after odd d16 image_load', repr(s2_reason)) + + # 5. Refusal controls from synthetic VOP3A bytes and malformed operand counts. + byte_refusals = [ + ('op_sel:[1,0,0]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(1, 0, 0, 0)), 'v_mad_u32_u16 with'), + ('op_sel:[0,1,0]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(0, 1, 0, 0)), 'v_mad_u32_u16 with'), + ('op_sel:[0,0,1]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(0, 0, 1, 0)), 'v_mad_u32_u16 with'), + ('op_sel:[0,0,0,1]', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, op_sel=(0, 0, 0, 1)), 'v_mad_u32_u16 with'), + ('clamp', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, clamp=1), 'v_mad_u32_u16 with'), + ('omod mul:2', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, omod=1), 'v_mad_u32_u16 with'), + ('abs', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, abs_bits=(1, 0, 0)), 'operand'), + ('neg', encode_mad_u32_u16(1, 256 + 2, 256 + 3, 256 + 4, neg=(1, 0, 0)), 'operand'), + ] + for label, word_bytes, needle in byte_refusals: + reason = refused_bytes(word_bytes) + check('refused bytes (%s)' % label, reason is not None and needle in reason, repr(reason)) + + for bad_asm in ('v_mad_u32_u16 v1, v2, v3', 'v_mad_u32_u16 v1, v2, v3, v4, v5'): + reason = refused_asm(bad_asm) + check('refused arity (%s)' % bad_asm, + reason is not None and 'operands, expected 4' in reason, repr(reason)) + + # 6. Mutation controls: each mutated HLSL must disagree on GRID and match its own MUTATIONS reference on DRAW_SETS. + first_chunk = DRAW_SETS[:4] + first_ref = [ref_mad_u32_u16(*row) for row in first_chunk] + for mut_name, (_, _, mut_ref) in MUTATIONS.items(): + _, mut_text = translate_ps(mut_name) + mut_exprs = lane_expressions(mut_text) + found = None + for index, (s0, s1, s2) in enumerate(GRID): + lane = index % 4 + env = {'v%d' % lane: s0, 'v%d' % (4 + lane): s1, 'v%d' % (8 + lane): s2} + got = mut_exprs[lane].run(env)[0] + if got != ref_mad_u32_u16(s0, s1, s2): + found = (lane, (s0, s1, s2), got) + break + check('mutation %s breaks GRID' % mut_name, found is not None) + all_match_mut = all( + mut_exprs[i % 4].run({'v%d' % (i % 4): s0, 'v%d' % (4 + i % 4): s1, 'v%d' % (8 + i % 4): s2})[0] + == mut_ref(s0, s1, s2) + for i, (s0, s1, s2) in enumerate(GRID) + ) + check('mutation %s matches its own reference across %d inputs' % (mut_name, len(GRID)), all_match_mut) + wrong_words = [mut_ref(*row) for row in first_chunk] + check('mutation %s differs from reference on draw chunk 0' % mut_name, wrong_words != first_ref) + check('mutation %s evaluator matches draw chunk 0' % mut_name, + lane_results(mut_exprs, first_chunk) == wrong_words) + + # 7. Unlowered negative control: removing v_mad_u32_u16 from VEC_U must refuse. + saved = G.VEC_U.pop('v_mad_u32_u16') + try: + reason = refused_bytes(BODY_WORDS[:8]) + check('unlowered control refuses v_mad_u32_u16', reason == 'v_mad_u32_u16', repr(reason)) + finally: + G.VEC_U['v_mad_u32_u16'] = saved + + +def check_binary(llvm_mc): + built = assemble(llvm_mc, BODY_SOURCE) + if built != BODY_WORDS: + raise AssertionError('body: assembled %s, recorded %s' % (built.hex(), BODY_WORDS.hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for _, word_bytes, want_asm, _, _ in SYNTHETIC_CASES: + built = assemble(llvm_mc, want_asm + '\n') + if built != word_bytes: + raise AssertionError('%s: assembled %s, recorded %s' % (want_asm, built.hex(), word_bytes.hex())) + for i in range(0, len(DRAW_SETS), 4): + chunk = DRAW_SETS[i:i + 4] + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (chunk,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, translate_ps()[1], 'ps_mad_u32_u16_%s' % kind, ps_profile, directory) + for index in range(0, len(DRAW_SETS), 4): + chunk = DRAW_SETS[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + 'vs_mad_u32_u16_%d_%s' % (index, kind), vs_profile, directory) + expected = words_text(ref_mad_u32_u16(*x) for x in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s chunk %d inputs %s\n%s\n%s' + % (kind, index // 4, chunk, run.stdout, run.stderr)) + print('%s chunk %d %s: %s' % (kind, index // 4, + [tuple('%08x' % v for v in x) for x in chunk], expected), flush=True) + if index: + continue + for mut_name, (_, _, mut_ref) in MUTATIONS.items(): + wrong = words_text(mut_ref(*x) for x in chunk) + bad_ps = compile_hlsl(compiler, kind, translate_ps(mut_name)[1], + 'mutated_%s_%s' % (mut_name, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s mutation %s did not read %s\n%s\n%s' + % (kind, mut_name, wrong, run.stdout, run.stderr)) + print('%s mutation %s: fails as expected, reads %s' % (kind, mut_name, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_mask_data_check.py b/tests/startup_gfx2hlsl_mask_data_check.py new file mode 100644 index 0000000000..bb13ffc4e5 --- /dev/null +++ b/tests/startup_gfx2hlsl_mask_data_check.py @@ -0,0 +1,65 @@ +"""Check whole-word vector data refusals for the startup translator's lane masks.""" +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + sampler_heap = False + root = {'params': [], 'flags': 0} + + +COMPARE = 'v_cmp_eq_u32_e64 s[30:31], 0, v0' +SDWA = 'dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD' + + +def stage(): + s = G.Stage(Pipe(), 'ps', struct.pack('<I', 0xbf810000)) + s.lines = [] + s.pc = 0 + s.one(COMPARE.split()[0], COMPARE) + return s + + +def main(): + refused = ( + ('v_cndmask_b32_e64 v1, 0, s30, s[30:31]', 's30'), + ('v_cndmask_b32_e64 v1, -s30, v0, s[30:31]', '-s30'), + ('v_cndmask_b32_e64 v1, 0, |s30|, s[30:31]', '|s30|'), + ('v_cndmask_b32_e64 v1, neg(abs(s30)), v0, s[30:31]', 'neg(abs(s30))'), + ('v_cndmask_b32_e32 v1, vcc_lo, v0, vcc_lo', 'vcc_lo'), + ('v_mov_b32 v1, s30', 's30'), + ('v_mov_b32_e32 v1, exec_lo', 'exec_lo'), + ('v_mov_b32_e64 v1, vcc_lo', 'vcc_lo'), + ('v_mov_b32_sdwa v1, s30 ' + SDWA, 's30'), + ('v_mov_b32_sdwa v1, sext(s30) ' + SDWA, 'sext(s30)'), + ) + for asm, source in refused: + s = stage() + name = asm.split()[0] + op = name.removesuffix('_e32').removesuffix('_e64').removesuffix('_sdwa') + try: + s.one(name, asm) + except G.Unsupported as error: + assert str(error) == f'{op} data operand {source} is a lane mask', (asm, error) + else: + raise AssertionError(f'Accepted a lane mask as data: {asm}') + + accepted = ( + ('v_cndmask_b32_e64 v1, 0, v0, s[30:31]', 'v1 = (s30 & 1) ? v0 : 0x00000000u;'), + ('v_cndmask_b32_e32 v1, s29, v0, vcc_lo', 'v1 = (vcc & 1) ? v0 : 0x12345678u;'), + ('v_mov_b32_e64 v1, s29', 'v1 = 0x12345678u;'), + ) + for asm, line in accepted: + s = stage() + s.one('s_mov_b32', 's_mov_b32 s29, 0x12345678') + s.one(asm.split()[0], asm) + assert s.lines[-1] == line, (asm, s.lines) + print(f'mask data: {len(refused)} refusals and {len(accepted)} accepted controls') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_mask_overwrite_check.py b/tests/startup_gfx2hlsl_mask_overwrite_check.py index dc3fcfaf6b..b6840bdbed 100644 --- a/tests/startup_gfx2hlsl_mask_overwrite_check.py +++ b/tests/startup_gfx2hlsl_mask_overwrite_check.py @@ -6,7 +6,7 @@ scalar logic op with a mask source is lowered as a mask op: its result is reduced to the lane's bit. The generic scalar path cleared the mark when it overwrote a register with ordinary data, but the other writers did not: after `v_cmp_eq_u32_e64 s6, v0, v1` and `s_buffer_load_dword s6, s[16:19], 0x0`, s6 holds a buffer word, yet -`s_or_b32 s8, s6, s7` was still lowered as a mask OR and cut to bit 0. Every scalar write through `set_s` now clears +`s_or_b32 s8, s6, s20` was still lowered as a mask OR and cut to bit 0. Every scalar write through `set_s` now clears the mark (the writers of a mask mark the register again after it), and `s_load` clears it on its destination registers, also in the forms that only record a descriptor symbol. @@ -14,6 +14,11 @@ buffer word with the restricted evaluator of startup_gfx2hlsl_bit_alu_check: an s_buffer_load, an s_load through a root pointer, an s_load of a descriptor, and an s_cselect_b32 into the former mask register. Controls: without the overwrite the OR stays a mask OR, and a compare or a mask logic op written after a load marks the register again. + +Scalar ALU on descriptor data (an s_mov of a descriptor word, the s_bfe_u32 and s_and_b32 of a structured-to-raw +conversion, an s_add_u32 to a descriptor pointer) records only a symbol for its destination. It now clears the mark +as well, in a pixel and a vertex stage, so the s_max_u32 that clamps an extracted stride is not taken as a mask read. +Control: such a write into another SGPR keeps the mark on s6. """ import struct import sys @@ -39,6 +44,9 @@ class Pipe: sampler_heap = False root = {'params': [{'type': 2}], 'flags': 0} + def __init__(self): + self.modified = set() # descriptors written by scalar ALU (the structured-to-raw conversion marks them) + def resource(self, key, kind): return 'r0' @@ -66,11 +74,11 @@ def run(s, *texts): def or_value(s, s6, s7): - """Value of s8 after s_or_b32 s8, s6, s7, from the emitted line.""" + """Value of s8 after s_or_b32 s8, s6, s20, from the emitted line.""" s.lines = [] - run(s, 's_or_b32 s8, s6, s7') + run(s, 's_or_b32 s8, s6, s20') line = next(l for l in s.lines if l.startswith('s8 = ')) - return Expr(line[5:-1]).run({'s6': s6, 's7': s7})[0], line + return Expr(line[5:-1]).run({'s6': s6, 's20': s7})[0], line COMPARE = 'v_cmp_eq_u32_e64 s6, v0, v1' @@ -104,6 +112,34 @@ def main(): run(s, 'v_cmp_eq_u32_e64 s5, v0, v1', 's_load_dwordx4 s[4:7], s[12:13], 0x20') check('s_load_dwordx4 of a descriptor clears the mark on s5', 5 not in s.masks, s.masks) + # Scalar ALU on descriptor data writes the destination's symbol without set_s. The register then holds + # descriptor data, so a later numeric read of it is not a lane-mask read (the stride clamp of a + # structured-to-raw conversion: s_bfe_u32 of DW1[29:16], then s_max_u32 with 1). + for kind in ('ps', 'vs'): + for text in ('s_mov_b32 s6, s17', 's_bfe_u32 s6, s17, 0xe0010', 's_and_b32 s6, s19, 0xcfffffff', + 's_add_u32 s6, s2, 16'): + s = stage() + s.kind = kind + try: + run(s, COMPARE, text) + except G.Unsupported as error: + check('%s %s after a compare translates' % (kind, text), False, error) + continue + check('%s %s (descriptor data) clears the mark on s6' % (kind, text), 6 not in s.masks, s.masks) + s = stage() + s.kind = kind + try: + run(s, COMPARE, 's_bfe_u32 s6, s17, 0xe0010', 's_max_u32 s6, s6, 1') + check('%s s_max_u32 of the extracted stride is not refused as a lane-mask read' % kind, True) + except G.Unsupported as error: + check('%s s_max_u32 of the extracted stride is not refused as a lane-mask read' % kind, False, error) + # Control: only the destination loses its mark; a descriptor write to another SGPR leaves the mask s6. + s = stage() + s.kind = kind + run(s, COMPARE, 's_bfe_u32 s8, s17, 0xe0010') + check('control: %s s_bfe_u32 into s8 keeps the mask mark on s6' % kind, 6 in s.masks and 8 not in s.masks, + s.masks) + # A mask written after a load marks the register again. s = stage() run(s, 's_buffer_load_dword s6, s[16:19], 0x0', COMPARE) @@ -122,6 +158,25 @@ def main(): continue check('control: %s after the load marks s6 again' % writer, 6 in s.masks, (s.masks, s.lines)) + # A lane mask read as a number is refused in the pixel and vertex stages too (the wave's ballot word is every lane's + # bit, the model holds one): the compare into vcc_lo then v_cvt_f32_u32, and the compare into s0 then s_add_i32. + for kind in ('ps', 'vs'): + for compare, use in (('v_cmp_lt_u32_e32 vcc_lo, 5, v0', 'v_cvt_f32_u32_e32 v1, vcc_lo'), + ('v_cmp_lt_u32_e64 s0, 5, v0', 's_add_i32 s1, s0, 0')): + s = stage() + s.kind = kind + run(s, compare) + try: + run(s, use) + check('%s: %s after %s is refused' % (kind, use, compare), False, s.lines) + except G.Unsupported as why: + check('%s: %s after %s is refused' % (kind, use, compare), 'as numeric data' in str(why), str(why)) + s = stage() + s.kind = kind + run(s, 'v_cmp_lt_u32_e64 s0, 5, v0', 's_mov_b32 s0, 7') # overwritten: a number again + run(s, 's_add_i32 s1, s0, 0') + check('%s: a mask register overwritten by a constant is a number again' % kind, 0 not in s.masks, s.masks) + if failures: print('FAILED: %d check(s)' % failures) return 1 diff --git a/tests/startup_gfx2hlsl_modifier_free_check.py b/tests/startup_gfx2hlsl_modifier_free_check.py new file mode 100644 index 0000000000..e18d4c1d16 --- /dev/null +++ b/tests/startup_gfx2hlsl_modifier_free_check.py @@ -0,0 +1,179 @@ +"""Handlers whose lowering does not model a modifier they can receive (issue #1771). + +usage: startup_gfx2hlsl_modifier_free_check.py + +Several handlers take the modifier list and never read it, so a modifier their encoding can carry was dropped +from the emitted HLSL - the same class as the `op_sel`/`clamp` cases fixed one at a time earlier +(`set_vf`, `op_v_cndmask_b32`, `compare`). The dispatch now refuses a modifier for the handlers declared in +`MODIFIER_FREE_HANDLERS`, before the handler can ignore it. + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`): VOP1/VOP2-as-VOP3 use prefix `0b110101` with opcode `0x180 + n` / `0x100 + n`, +modifiers at `w0[15]` (clamp), `w0[14:11]` (op_sel) and `w1[28:27]` (omod); VOP3A uses the opcode in `w0[25:16]`. +""" +import os +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +VOP1_E64_BASE = 0x180 +VOP2_E64_BASE = 0x100 +VOP1_MOV_B32 = 0x01 +VOP2_CVT_PKRTZ_F16_F32 = 0x2F +VOP3A_INTERP_P1 = 0x200 +VOP3A_INTERP_P2 = 0x201 +VOP3A_INTERP_MOV = 0x202 +V1, V2, V3 = 0x101, 0x102, 0x103 + + +def _word0(opcode, vdst, *, clamp=0, op_sel=(0, 0, 0, 0)): + w0 = (0b110101 << 26) | ((opcode & 0x3FF) << 16) | ((clamp & 1) << 15) | (vdst & 0xFF) + for i, bit in enumerate(op_sel): + w0 |= (bit & 1) << (11 + i) + return w0 + + +def encode_vop1(op, vdst, src0, *, clamp=0): + return struct.pack('<II', _word0(VOP1_E64_BASE + op, vdst, clamp=clamp), src0 & 0x1FF) + + +def encode_vop2(op, vdst, src0, src1, *, clamp=0, op_sel=(0, 0, 0, 0), omod=0): + w1 = (src0 & 0x1FF) | ((src1 & 0x1FF) << 9) | ((omod & 0x3) << 27) + return struct.pack('<II', _word0(VOP2_E64_BASE + op, vdst, clamp=clamp, op_sel=op_sel), w1) + + +def encode_interp(op, vdst, source, *, attr=0, chan=0, abs_source=0, neg_source=0, clamp=0): + """Encode the gfx10 VOP3 spelling of v_interp_p1_f32 / v_interp_p2_f32.""" + w0 = ((0b110101 << 26) | ((op & 0x3FF) << 16) | ((clamp & 1) << 15) + | ((abs_source & 1) << 9) | (vdst & 0xFF)) + w1 = ((attr & 0x3F) | ((chan & 0x3) << 6) | ((source & 0x1FF) << 9) | ((neg_source & 1) << 30)) + return struct.pack('<II', w0, w1) + + +def encode_vop3a(op, vdst, srcs, *, clamp=0): + w1 = 0 + for i, src in enumerate(srcs): + w1 |= (src & 0x1FF) << (9 * i) + return struct.pack('<II', _word0(op, vdst, clamp=clamp), w1) + + +class Pipeline: + """Just enough pipeline state for one instruction.""" + + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + def ud(self, key): + return 0 + + +class Stage(G.Stage): + """A Stage with no pipeline: enough state for a decoded instruction to be translated.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports = {} + self.attrs = {} + self.pipe = Pipeline() + self.kind = 'ps' + self.blocks = [] + + +def translate(code): + decoded = G.decode(code) + stage = Stage() + for _offset, _size, name, asm in decoded: + stage.one(name, asm) + return [asm for _o, _s, _n, asm in decoded], ' '.join(stage.lines) + + +def refused(code): + try: + translate(code) + except G.Unsupported: + return True + return False + + +# 1. The declared set is what we expect; a handler silently added to or dropped from it shows up here. +check('the declared modifier-free handlers are exactly these five', + set(G.MODIFIER_FREE_HANDLERS) == { + 'op_v_mov_b32', 'op_v_cvt_pkrtz_f16_f32', 'op_v_interp_p1_f32', + 'op_v_interp_p2_f32', 'op_v_interp_mov_f32'}, ', '.join(sorted(G.MODIFIER_FREE_HANDLERS))) + +# 2. v_mov_b32: a plain move translates, and a modifier it never modelled is refused. +asm, emitted = translate(encode_vop1(VOP1_MOV_B32, 1, V2)) +check('a plain move still translates', emitted == 'v1 = v2;', emitted) +check('a clamp on the move is refused', refused(encode_vop1(VOP1_MOV_B32, 1, V2, clamp=1))) +check('a mul:2 on the move is refused', + refused(struct.pack('<II', _word0(VOP1_E64_BASE + VOP1_MOV_B32, 1), + (V2 & 0x1FF) | (1 << 27)))) + +# 3. v_cvt_pkrtz_f16_f32: a plain pack translates, and op_sel/clamp are refused. +asm, emitted = translate(encode_vop2(VOP2_CVT_PKRTZ_F16_F32, 1, V2, V3)) +check('a plain packed conversion still translates', + emitted == 'v1 = f32tof16(F(v2)) | (f32tof16(F(v3)) << 16);', emitted) +check('an op_sel on the packed conversion is refused', + refused(encode_vop2(VOP2_CVT_PKRTZ_F16_F32, 1, V2, V3, op_sel=(0, 0, 1, 0)))) +check('a clamp on the packed conversion is refused', + refused(encode_vop2(VOP2_CVT_PKRTZ_F16_F32, 1, V2, V3, clamp=1))) + +# 4. v_interp_mov_f32: the parameter selector is the VINTRP field, which decodes as p10, p20, p0 in that +# order. Only p0 is the flat copy; p10 and p20 need the per-vertex attribute values, so they are +# refused by name rather than read as p0. A plain p0 read translates, and a modifier on it is refused. +_p10 = encode_vop3a(VOP3A_INTERP_MOV, 1, [0, 0]) +asm, emitted = translate(encode_vop3a(VOP3A_INTERP_MOV, 1, [0, 2])) +check('encodes and decodes the flat p0 read', asm == ['v_interp_mov_f32_e64 v1, p0, attr0.x'], repr(asm)) +check('a plain flat interpolation still translates', emitted == 'v1 = i.fparam0.x;', emitted) +check('a clamp on the flat interpolation is refused', refused(encode_vop3a(VOP3A_INTERP_MOV, 1, [0, 2], clamp=1))) +check('a p10 selector is refused rather than read as p0', refused(_p10)) +check('a p20 selector is refused rather than read as p0', refused(encode_vop3a(VOP3A_INTERP_MOV, 1, [0, 1]))) + +# 5. The p1/p2 interpolations have their own operand profile. A valid form carries a data-source VGPR in +# w1[16:9], and the decoder prints an abs/neg on that source as `|v2|` / `-v2` - inside the operand +# text, not as a mod - so the dispatch guard does not see it. The lowering never reads that operand +# (the value comes from the interpolator), so the handler refuses a modified source itself. +_asm, _emitted = translate(encode_interp(VOP3A_INTERP_P1, 1, V2)) +check('a plain p1 interpolation translates', _emitted == '', _emitted) +_asm, emitted = translate(encode_interp(VOP3A_INTERP_P2, 1, V2)) +check('a plain p2 interpolation translates', emitted == 'v1 = U(i.param0.x);', emitted) +_asm, emitted = translate(encode_interp(VOP3A_INTERP_P2, 1, V2, attr=1, chan=1)) +check('the attribute channel is read from the operand', emitted == 'v1 = U(i.param1.y);', emitted) +check('an absolutely-modified p1 source is refused', + refused(encode_interp(VOP3A_INTERP_P1, 1, V2, abs_source=1))) +check('a negated p1 source is refused', + refused(encode_interp(VOP3A_INTERP_P1, 1, V2, neg_source=1))) +check('an absolutely-modified p2 source is refused', + refused(encode_interp(VOP3A_INTERP_P2, 1, V2, abs_source=1))) +check('a clamp on the p1 interpolation is refused', + refused(encode_interp(VOP3A_INTERP_P1, 1, V2, clamp=1))) + +# 6. No scalar-ALU handler is in the set: their encoding has no modifier field, so there is nothing for the +# dispatch to refuse and they must keep translating whatever the decoder prints. +check('no scalar handler is declared modifier-free', + not [name for name in G.MODIFIER_FREE_HANDLERS if name.startswith('op_s_')], + ', '.join(sorted(G.MODIFIER_FREE_HANDLERS))) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') \ No newline at end of file diff --git a/tests/startup_gfx2hlsl_mul_hi_i32_check.py b/tests/startup_gfx2hlsl_mul_hi_i32_check.py new file mode 100644 index 0000000000..5965576845 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul_hi_i32_check.py @@ -0,0 +1,303 @@ +"""Signed 32x32->high-32 multiply (v_mul_hi_i32, s_mul_hi_i32) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, helper-math, refusal and mutation controls, pure Python + binary <llvm-mc> reassemble the fixture sources and compare them with the words below + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +The pixel fixture reads two flat parameters (v0..v3 and v4..v7), computes v_mul_hi_i32 across all four lanes into +v12..v15, and exports v12..v15 to mrt0. The vertex stage supplies the input words through flat parameters so the +pixel stage cannot constant-fold them. + +Every result is compared with an independent Python signed 64-bit reference ((s32(a) * s32(b)) >> 32) & 0xffffffff. +The emitted mul_hi_i32 helper (built on the existing mul_hi_u32 helper in Pipeline.common()) is parsed and evaluated +in 32-bit unsigned arithmetic over a 361-pair edge grid including INT_MIN * INT_MIN, INT_MIN * -1, -1 * -1, and mixed +signs. Controls verify s_mul_hi_i32 decoding/lowering (SCC unchanged, lane-mask/descriptor/bounds refusals), exec-masked +emission, modifier/arity refusals, and mutations replacing mul_hi_i32 with mul_hi_u32 (unsigned high product) or +dropping one sign-correction term on both CPU evaluation and desktop GPU draws. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + Expr, + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + Probe, + check, + refused, + vs_source, + vs_words, + words_text, +) + +BODY_SOURCE = ''.join('v_mul_hi_i32 v%d, v%d, v%d\n' % (12 + lane, lane, 4 + lane) for lane in range(4)) +BODY_WORDS = bytes.fromhex( + '0c006cd500090200' + '0d006cd5010b0200' + '0e006cd5020d0200' + '0f006cd5030f0200' +) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + +SCALAR_SOURCE = 's_mul_hi_i32 s12, s10, s11\n' +SCALAR_WORDS = struct.pack('<I', (0b10 << 30) | (0x36 << 23) | (12 << 16) | (11 << 8) | 10) + +SPECIAL = ( + 0, 1, 2, 3, 0xffff, 0x10000, 0x10001, 0x0001ffff, 0x7fffffff, 0x80000000, 0x80000001, + 0xdeadbeef, 0xcafebabe, 0x9e3779b9, 0x85ebca6b, 0xffff0000, 0xffff0001, 0xfffffffe, MASK, +) +GRID = [(a, b) for a in SPECIAL for b in SPECIAL] + +# Four (src0, src1, unused_src2) tuples per draw. Set 0 separates signed mul_hi_i32 from unsigned mul_hi_u32 +# and from dropping either sign-correction term. +DRAW = [ + (0xffffffff, 0xffffffff, 0), # -1 * -1 -> hi 0x00000000 (unsigned: 0xfffffffe) + (0x80000000, 0x80000000, 0), # INT_MIN * INT_MIN -> hi 0x40000000 (unsigned: 0x40000000, 1-term drop: 0xc0000000) + (0x80000000, 0x00000002, 0), # INT_MIN * 2 -> hi 0xffffffff (unsigned: 0x00000001) + (0xdeadbeef, 0x7fffffff, 0), # neg * INT_MAX -> hi 0xef56df77 (unsigned: 0x6f56df77) + (0x80000000, 0xffffffff, 0), # INT_MIN * -1 -> hi 0x00000000 + (0x00000000, 0xffffffff, 0), # 0 * -1 -> hi 0x00000000 + (0x7fffffff, 0x7fffffff, 0), # INT_MAX * INT_MAX -> hi 0x3fffffff + (0x00000001, 0x80000000, 0), # 1 * INT_MIN -> hi 0xffffffff + (0xdeadbeef, 0xcafebabe, 0), # neg * neg -> hi 0x0b164486 + (0x9e3779b9, 0x85ebca6b, 0), # neg * neg -> hi 0x2ec3a0c2 + (0xffff0000, 0x00010001, 0), # -65536 * 65537 -> hi 0xffffffff + (0x00010001, 0x00010001, 0), # pos * pos -> hi 0x00000001 +] + + +def s32(v): + v &= MASK + return v - (1 << 32) if v & 0x80000000 else v + + +def ref_mul_hi_i32(a, b): + return ((s32(a) * s32(b)) >> 32) & MASK + + +def ref_mul_hi_u32(a, b): + return ((a & MASK) * (b & MASK)) >> 32 + + +def translate(mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate: + mutated = re.sub(r'mul_hi_i32\((v\d+), (v\d+)\)', r'mul_hi_u32(\1, \2)', text) + assert mutated != text, text + text = mutated + return pipe, text + + +def eval_emitted_helpers(ps_text): + """Parse the emitted mul_hi_u32 and mul_hi_i32 helpers and return a 32-bit evaluator for mul_hi_i32.""" + mu = re.search(r'uint mul_hi_u32\(uint a, uint b\) \{ (.*?) \}', ps_text) + assert mu, 'mul_hi_u32 helper missing from generated HLSL' + u_stmts = [part.strip() for part in mu.group(1).split(';') if part.strip()] + u_decls = [] + for stmt in u_stmts[:-1]: + assert stmt.startswith('uint '), stmt + for item in stmt[5:].split(','): + name, rhs = [x.strip() for x in item.split('=', 1)] + u_decls.append((name, Expr(rhs))) + assert u_stmts[-1].startswith('return '), u_stmts[-1] + u_ret = Expr(u_stmts[-1][7:]) + + def run_u(a, b): + env = {'a': a & MASK, 'b': b & MASK} + for name, expr in u_decls: + env[name] = expr.run(env)[0] + return u_ret.run(env)[0] + + mi = re.search(r'uint mul_hi_i32\(uint a, uint b\) \{ return ([^;]+); \}', ps_text) + assert mi, 'mul_hi_i32 helper missing from generated HLSL' + i_expr_text = mi.group(1) + assert 'mul_hi_u32(a, b)' in i_expr_text, i_expr_text + i_expr = Expr(i_expr_text.replace('mul_hi_u32(a, b)', 'u')) + + def run_i(a, b): + return i_expr.run({'a': a & MASK, 'b': b & MASK, 'u': run_u(a, b)})[0] + + return run_i + + +class ScalarProbe(Probe): + def __init__(self): + super().__init__() + self.masks = set() + self.scc_effect = None + + +def scalar_refused(line): + try: + ScalarProbe().one(line.split(' ', 1)[0], line) + except G.Unsupported: + return True + return False + + +def controls(): + _, text = translate() + found = re.findall(r'^\s*v(1[2-5]) = mul_hi_i32\(v(\d+), v(\d+)\);$', text, re.M) + check('v_mul_hi_i32: four lane calls emitted', + found == [('12', '0', '4'), ('13', '1', '5'), ('14', '2', '6'), ('15', '3', '7')]) + + helper = eval_emitted_helpers(text) + mismatch = next(((a, b, helper(a, b), ref_mul_hi_i32(a, b)) for a, b in GRID + if helper(a, b) != ref_mul_hi_i32(a, b)), None) + check('v_mul_hi_i32: emitted helper matches reference on %d edge pairs' % len(GRID), mismatch is None) + + # Sign-correction negative controls: dropping either sign term must mismatch. + drop_a = text.replace('((a >> 31) != 0u ? b : 0u)', '0u') + drop_b = text.replace('((b >> 31) != 0u ? a : 0u)', '0u') + assert drop_a != text and drop_b != text + check('mul_hi_i32: dropping a-sign correction mismatches INT_MIN * 2', + eval_emitted_helpers(drop_a)(0x80000000, 2) != ref_mul_hi_i32(0x80000000, 2)) + check('mul_hi_i32: dropping b-sign correction mismatches 2 * INT_MIN', + eval_emitted_helpers(drop_b)(2, 0x80000000) != ref_mul_hi_i32(2, 0x80000000)) + + # Draw set 0 mutation: substituting mul_hi_u32 for mul_hi_i32 produces distinct words. + mutated = translate(mutate=True)[1] + check('v_mul_hi_i32: mutated text calls mul_hi_u32 on all four lanes', + re.findall(r'^\s*v(1[2-5]) = mul_hi_u32\(v(\d+), v(\d+)\);$', mutated, re.M) + == [('12', '0', '4'), ('13', '1', '5'), ('14', '2', '6'), ('15', '3', '7')]) + first = DRAW[:4] + ref_first = [ref_mul_hi_i32(a, b) for a, b, _ in first] + mut_first = [ref_mul_hi_u32(a, b) for a, b, _ in first] + check('v_mul_hi_i32: draw set 0 unsigned mutation reads %s (differs from %s)' + % (words_text(mut_first), words_text(ref_first)), mut_first != ref_first) + + # Accepted vector operand forms (VGPR, SGPR, inline constant, literal) and exec-masked emission. + check('v_mul_hi_i32: accepted operand forms translate', not any(refused(a) for a in ( + 'v_mul_hi_i32 v1, v2, v3', 'v_mul_hi_i32 v1, s0, v3', + 'v_mul_hi_i32 v1, v2, -1', 'v_mul_hi_i32 v1, v2, 0x80000000'))) + masked = Probe() + masked.exec_known = False + masked.one('v_mul_hi_i32', 'v_mul_hi_i32 v1, v2, v3') + check('exec-masked v_mul_hi_i32 guards assignment', + masked.lines == ['if (exec & 1) v1 = mul_hi_i32(v2, v3);']) + + # Vector refusals: modifiers and wrong operand counts. + check('v_mul_hi_i32: modifiers and operand modifiers refused', all(refused(a) for a in ( + 'v_mul_hi_i32 v1, v2, v3 clamp', 'v_mul_hi_i32 v1, v2, v3 mul:2', + 'v_mul_hi_i32 v1, v2, v3 div:2', 'v_mul_hi_i32 v1, v2, v3 op_sel:[1,0,0,0]', + 'v_mul_hi_i32 v1, -v2, v3', 'v_mul_hi_i32 v1, |v2|, v3', + 'v_mul_hi_i32 v1, v2, -v3', 'v_mul_hi_i32 v1, v2, |v3|'))) + check('v_mul_hi_i32: wrong operand counts refused', all(refused(a) for a in ( + 'v_mul_hi_i32 v1', 'v_mul_hi_i32 v1, v2', 'v_mul_hi_i32 v1, v2, v3, v4'))) + + # Scalar s_mul_hi_i32: decode, lowering (SCC unchanged), SGPR-over-mask overwrite, and refusals. + decoded = G.decode(SCALAR_WORDS) + check('s_mul_hi_i32: SOP2 encoding decodes', + len(decoded) == 1 and decoded[0][2] == 's_mul_hi_i32' and decoded[0][3] == 's_mul_hi_i32 s12, s10, s11') + sp = ScalarProbe() + sp.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + check('s_mul_hi_i32: lowers to mul_hi_i32 without touching scc', + sp.lines == ['s12 = mul_hi_i32(s10, s11);']) + sp_lit = ScalarProbe() + sp_lit.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, 0x80000001') + check('s_mul_hi_i32: literal source translates', + sp_lit.lines == ['s12 = mul_hi_i32(s10, 0x80000001u);']) + # Overwriting an SGPR that previously held a compare mask succeeds and drops its mask mark. + sp_over = ScalarProbe() + sp_over.masks.add(12) + sp_over.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + check('s_mul_hi_i32: overwriting mask-marked SGPR drops mask mark', 12 not in sp_over.masks) + # Reading a mask-marked SGPR as source must be refused. + sp_mask_src = ScalarProbe() + sp_mask_src.masks.add(10) + mask_src_refused = False + try: + sp_mask_src.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + except G.Unsupported: + mask_src_refused = True + check('s_mul_hi_i32: mask-marked SGPR source refused', mask_src_refused) + check('s_mul_hi_i32: lane-mask, vcc/exec, out-of-range and wrong-count forms refused', all(scalar_refused(a) for a in ( + 's_mul_hi_i32 vcc_lo, s10, s11', 's_mul_hi_i32 exec_lo, s10, s11', + 's_mul_hi_i32 s12, vcc_lo, s11', 's_mul_hi_i32 s12, s10, exec_lo', + 's_mul_hi_i32 s106, s10, s11', 's_mul_hi_i32 s12, s106, s11', + 's_mul_hi_i32 s12, s10', 's_mul_hi_i32 s12, s10, s11, s13'))) + sym_p = ScalarProbe() + sym_p.sym[10] = ('ptr', ('vbtab',)) + sym_refused = False + try: + sym_p.one('s_mul_hi_i32', 's_mul_hi_i32 s12, s10, s11') + except G.Unsupported: + sym_refused = True + check('s_mul_hi_i32: symbolic pointer source refused', sym_refused) + + +def check_binary(llvm_mc): + for label, source, words in ( + ('v_mul_hi_i32 body', BODY_SOURCE, BODY_WORDS), + ('s_mul_hi_i32', SCALAR_SOURCE, SCALAR_WORDS), + ('prologue', PRE_SOURCE, PRE_WORDS), + ('export', POST_SOURCE, POST_WORDS), + ): + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s: assembled %s, recorded %s' % (label, built.hex(), words.hex())) + for index in range(0, len(DRAW), 4): + chunk = DRAW[index:index + 4] + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (chunk,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, translate()[1], 'ps_mul_hi_i32_%s' % kind, ps_profile, directory) + for index in range(0, len(DRAW), 4): + chunk = DRAW[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + 'vs_mul_hi_i32_%d_%s' % (index, kind), vs_profile, directory) + expected = words_text(ref_mul_hi_i32(a, b) for a, b, _ in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s v_mul_hi_i32 inputs %s\n%s\n%s' % (kind, chunk, run.stdout, run.stderr)) + print('%s v_mul_hi_i32 %s: %s' % (kind, [('%x' % a, '%x' % b) for a, b, _ in chunk], expected), + flush=True) + if index: + continue + wrong = words_text(ref_mul_hi_u32(a, b) for a, b, _ in chunk) + bad_ps = compile_hlsl(compiler, kind, translate(mutate=True)[1], + 'mutated_mul_hi_i32_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s v_mul_hi_i32 mutation did not read %s\n%s\n%s' + % (kind, wrong, run.stdout, run.stderr)) + print('%s v_mul_hi_i32 mutation: fails as expected, reads %s' % (kind, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_pack_b32_f16_check.py b/tests/startup_gfx2hlsl_pack_b32_f16_check.py new file mode 100644 index 0000000000..071eddee7c --- /dev/null +++ b/tests/startup_gfx2hlsl_pack_b32_f16_check.py @@ -0,0 +1,141 @@ +"""v_pack_b32_f16 (VOP3) in tools/startup/gfx2hlsl.py: D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA). + +Synthetic VOP3 words (gfx10 opcode 0x311; op_sel in word 0 bits 14:11, abs in bits 10:8, clamp in bit 15, neg in +word 1 bits 31:29). The decoder reads each word back, and the test asserts the printed op_sel and modifier forms. +The emitted expression is evaluated in Python for every op_sel[0..1] x abs x neg combination over sample register +pairs. The reference written here selects the half (op_sel[i] = high half of source i), then applies abs (clear +bit 15) and then neg (flip bit 15). An SGPR source is accepted. +Controls (refused): a destination op_sel bit, clamp, an inline float constant and an inline integer source. +Negative controls: an expression with the halves swapped, or with neg applied before abs, is caught by the +reference; without op_v_pack_b32_f16 the instruction is refused, as on main. +The draw mode checks raw integer readback under DXC and FXC and rejects a lowering that omits negation. +""" +import re +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop3(vdst, s0, s1, opsel=0, absm=0, neg=0, clamp=0): + """s0 and s1 are 9-bit source fields: 256 + n is vN, n < 106 is sN, 128..208 and 240..248 inline constants.""" + return [0xd4000000 | 0x311 << 16 | clamp << 15 | opsel << 11 | absm << 8 | vdst, s0 | s1 << 9 | neg << 29] + + +def one(words): + s = G.Stage(Pipe(), 'vs', b'') + s.lines, s.pc = [], 0 + _, _, name, text = G.decode(struct.pack('<2I', *words))[0] + s.one(name, text) + return text, s.lines + + +def ev(expr, env): + py = re.sub(r'(0x[0-9a-f]+|\d+)u\b', r'\1', expr) + return eval(py, {}, env) & 0xffffffff + + +def ref(a, b, sel, absm, neg, neg_first=False): + out = [] + for i, x in enumerate((a, b)): + h = (x >> 16) & 0xffff if sel >> i & 1 else x & 0xffff + if neg_first and neg >> i & 1: + h ^= 0x8000 + if absm >> i & 1: + h &= 0x7fff + if not neg_first and neg >> i & 1: + h ^= 0x8000 + out.append(h) + return out[0] | out[1] << 16 + + +VALUES = [0x00000000, 0x3c00bc00, 0x80017fff, 0xfc007e00, 0x12345678, 0xffff0001] + + +def refused(words, why): + try: + one(words) + except G.Unsupported as error: + assert why in str(error), str(error) + else: + raise AssertionError('accepted: %s' % why) + + +def main(): + cases = 0 + for sel in range(4): + for absm in range(4): + for neg in range(4): + text, lines = one(vop3(3, 257, 258, sel, absm, neg)) + assert text.startswith('v_pack_b32_f16 v3, '), text + assert ('op_sel:[%d,%d,0]' % (sel & 1, sel >> 1) in text) == bool(sel), text + m = re.fullmatch(r'v3 = (.*);', lines[0]) + assert m and len(lines) == 1, lines + for a in VALUES: + for b in VALUES: + got = ev(m.group(1), {'v1': a, 'v2': b}) + assert got == ref(a, b, sel, absm, neg), (text, hex(a), hex(b), hex(got)) + cases += 1 + if absm and neg & absm: + # The modifier order matters only where both act: the wrong order must be caught. + assert any(ev(m.group(1), {'v1': a, 'v2': b}) != ref(a, b, sel, absm, neg, neg_first=True) + for a in VALUES for b in VALUES), text + text, lines = one(vop3(3, 5, 258, 1)) # SGPR source, high half + assert text == 'v_pack_b32_f16 v3, s5, v2 op_sel:[1,0,0]', text + assert all(ev(lines[0][len('v3 = '):-1], {'s5': a, 'v2': b}) == ref(a, b, 1, 0, 0) + for a in VALUES for b in VALUES), lines + _, lines = one(vop3(3, 257, 258, 1)) + swapped = re.fullmatch(r'v3 = (.*) \| \((.*) << 16\);', lines[0]) + wrong = '%s | (%s << 16)' % (swapped.group(2), swapped.group(1)) + assert any(ev(wrong, {'v1': a, 'v2': b}) != ref(a, b, 1, 0, 0) for a in VALUES for b in VALUES) + refused(vop3(3, 257, 258, 4), 'v_pack_b32_f16 form') + refused(vop3(3, 257, 258, clamp=1), 'v_pack_b32_f16 modifier clamp') + refused(vop3(3, 242, 258), 'v_pack_b32_f16 source 1.0') + refused(vop3(3, 129, 258), 'v_pack_b32_f16 source 1') + saved = G.Stage.op_v_pack_b32_f16 + del G.Stage.op_v_pack_b32_f16 + try: + refused(vop3(3, 257, 258), 'v_pack_b32_f16') + finally: + G.Stage.op_v_pack_b32_f16 = saved + print('pack_b32_f16: %d (op_sel, abs, neg, value) cases match the reference; SGPR source accepted; swapped ' + 'halves and neg-before-abs caught; destination op_sel, clamp and constants refused; refused without the ' + 'handler' % cases) + + +def draw_cases(dxc, renderer, adapter, fxc=None): + from startup_gfx2hlsl_lane_alu import check_draw + + op = 'v_pack_b32_f16' + # The selected halves cover zeros, subnormals, infinities and NaN payloads as integer bits. + values = [ + (0x0000bc00, 0xa5a58000, 0), (0x80017e00, 0xf0f00001, 0), + (0xfc008001, 0xabcd7d55, 0), (0x7d337c00, 0xdcba7c00, 0), + ] + body = b''.join(struct.pack('<2I', *vop3(12 + lane, 256 + lane, 260 + lane, 1, 1, 1)) + for lane in range(4)) + family = { + 'ops': {op: (2, lambda a, b: ref(a, b, 1, 1, 1), False)}, + 'draw': {op: values}, + 'body': {op: body}, + 'mutations': {op: (r' \^ 0x8000u', '', lambda a, b: ref(a, b, 1, 1, 0))}, + 'accepted': [], + 'refused': [], + } + check_draw(family, dxc, renderer, adapter, fxc) + + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == 'draw': + draw_cases(*sys.argv[2:]) + else: + main() diff --git a/tests/startup_gfx2hlsl_perm_b32_check.py b/tests/startup_gfx2hlsl_perm_b32_check.py new file mode 100644 index 0000000000..3192aa3a8a --- /dev/null +++ b/tests/startup_gfx2hlsl_perm_b32_check.py @@ -0,0 +1,211 @@ +"""Byte permutation (v_perm_b32) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, on-demand helper, exhaustive selector 0..255 evaluation, + refusal and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +AMD RDNA 2 ISA V_PERM_B32 (VOP3A opcode 0x344): + Input bytes in[0..3] = S1 bytes 0..3, in[4..7] = S0 bytes 0..3. + For each output byte i in 0..3, sel = (S2 >> (8*i)) & 0xff: + 0..7 -> in[sel] + 8 -> in[1][7] ? 0xff : 0x00 + 9 -> in[3][7] ? 0xff : 0x00 + 10 -> in[5][7] ? 0xff : 0x00 + 11 -> in[7][7] ? 0xff : 0x00 + 12 -> 0x00 + >= 13 -> 0xff +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) +from startup_gfx2hlsl_sad_check import HlslExpr, vop3a # noqa: E402 + +OPCODE = 0x344 +BODY_WORDS = b''.join(vop3a(OPCODE, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + + +def ref_perm_byte(hi, lo, sel): + sel &= 0xff + if sel >= 13: + return 0xff + if sel == 12: + return 0x00 + if sel >= 8: + word = hi if sel >= 10 else lo + bit = 31 if (sel & 1) else 15 + return 0xff if ((word >> bit) & 1) else 0x00 + word = hi if sel >= 4 else lo + return (word >> ((sel & 3) * 8)) & 0xff + + +def ref_perm_b32(hi, lo, sel): + hi, lo, sel = hi & MASK, lo & MASK, sel & MASK + out = 0 + for shift in (0, 8, 16, 24): + out |= ref_perm_byte(hi, lo, (sel >> shift) & 0xff) << shift + return out + + +# Pairs that distinguish odd-byte sign bits (bytes 1, 3, 5, 7) from even-byte sign bits (bytes 0, 2, 4, 6). +WORD_PAIRS = ( + (0x81020384, 0x05868708), + (0x01828304, 0x85060788), + (0x00800080, 0x80008000), + (0x80008000, 0x00800080), + (0x7f7f7f7f, 0x80808080), + (0x11223344, 0x55667788), +) + +DRAW_SETS = ( + ( + (0x11223344, 0x55667788, 0x07040300), # bytes from S0 and S1 + (0x81020384, 0x05868708, 0x0b0a0908), # sign-ext selectors 8,9,10,11 (even vs odd sign bits differ) + (0x01828304, 0x85060788, 0x0b0a0908), # sign-ext selectors 8,9,10,11 (flipped signs) + (0x11223344, 0x55667788, 0xfe0d0c05), # 0xfe (>=13 -> 0xff), 13 (-> 0xff), 12 (-> 0x00), 5 (S0 byte 1) + ), + ( + (0xdeadbeef, 0xcafebabe, 0x00010203), # reverse bytes of S1 + (0xdeadbeef, 0xcafebabe, 0x04050607), # reverse bytes of S0 + (0x00800080, 0x80008000, 0x08090a0b), # reverse sign-ext selectors + (0x01234567, 0x89abcdef, 0x0c0c0d0f), # constant 0x00 and 0xff selectors + ), +) + + +def extract_helper(hlsl, name): + m = re.search(rf'uint {name}\(uint hi, uint lo, uint sel\)\s*\{{\s*return\s+(.+?);\s*\}}', hlsl) + assert m, f'{name} helper missing from HLSL' + return m.group(1) + + +def controls(): + pipe = G.Pipeline(vs_words(DRAW_SETS[0]), PS_WORDS, root_blob()) + ps = pipe.hlsl_ps() + check('perm_byte helper emitted on demand', 'uint perm_byte(uint hi, uint lo, uint sel)' in ps) + check('perm_b32 helper emitted on demand', 'uint perm_b32(uint hi, uint lo, uint sel)' in ps) + for lane in range(4): + expected_line = f'v{12 + lane} = perm_b32(v{lane}, v{4 + lane}, v{8 + lane});' + check(f'lane {lane} assignment emitted', expected_line in ps) + + plain_ps = G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('perm_b32 omitted when unused', 'perm_b32(' not in plain_ps and 'perm_byte(' not in plain_ps) + + # Exhaustively evaluate the emitted perm_byte helper over all 256 selectors x 6 word pairs, plus perm_b32. + byte_eval = HlslExpr(extract_helper(ps, 'perm_byte')) + b32_eval = HlslExpr(extract_helper(ps, 'perm_b32'), + helpers={'perm_byte': lambda hi, lo, s: byte_eval.run({'hi': hi, 'lo': lo, 'sel': s})[0]}) + for hi, lo in WORD_PAIRS: + for sel in range(256): + got = byte_eval.run({'hi': hi, 'lo': lo, 'sel': sel})[0] + want = ref_perm_byte(hi, lo, sel) + assert got == want, (hex(hi), hex(lo), sel, hex(got), hex(want)) + for triples in DRAW_SETS: + for hi, lo, sel in triples: + got = b32_eval.run({'hi': hi, 'lo': lo, 'sel': sel})[0] + want = ref_perm_b32(hi, lo, sel) + assert got == want, (hex(hi), hex(lo), hex(sel), hex(got), hex(want)) + print(f'v_perm_b32: emitted helpers match reference on {len(WORD_PAIRS) * 256} selector cases + draw sets: ok') + + # Accepted operand forms and exec-masked emission. + for asm in ( + 'v_perm_b32 v12, v0, v4, v8', + 'v_perm_b32 v12, s4, v4, v8', + 'v_perm_b32 v12, 1, v4, 0', + 'v_perm_b32 v12, 0x11223344, v4, v8', + ): + probe = Probe() + probe.lower('v_perm_b32', asm, [o.strip() for o in asm.split(None, 1)[1].split(',')], []) + assert probe.lines and 'perm_b32(' in probe.lines[0], (asm, probe.lines) + probe_masked = Probe() + probe_masked.exec_known = False + probe_masked.lower('v_perm_b32', 'v_perm_b32 v12, v0, v4, v8', ['v12', 'v0', 'v4', 'v8'], []) + check('exec-masked v_perm_b32 guards assignment', + probe_masked.lines == ['if (exec & 1) v12 = perm_b32(v0, v4, v8);']) + print('accepted operand forms translate: ok') + + # Refusals: VOP3A neg/abs on VGPR and inline constants, clamp, omod, op_sel, wrong operand counts. + def must_refuse(fn, label, needle=''): + try: + fn() + except G.Unsupported as error: + check(f'{label} refused', needle in str(error) if needle else bool(str(error))) + else: + raise AssertionError(f'{label} was accepted') + + for label, bad, needle in ( + ('abs0', vop3a(OPCODE, 12, 256, 260, 264, abs_bits=1), 'with neg/abs'), + ('neg2', vop3a(OPCODE, 12, 256, 260, 264, neg=4), 'with neg/abs'), + ('neg_inline0', vop3a(OPCODE, 12, 129, 260, 264, neg=1), 'with neg/abs'), + ('abs_inline0', vop3a(OPCODE, 12, 129, 260, 264, abs_bits=1), 'with neg/abs'), + ('clamp', vop3a(OPCODE, 12, 256, 260, 264, clamp=1), ''), + ('omod', vop3a(OPCODE, 12, 256, 260, 264, omod=1), ''), + ('op_sel', vop3a(OPCODE, 12, 256, 260, 264, op_sel=1), ''), + ): + must_refuse(lambda b=bad: G.Pipeline(vs_words(DRAW_SETS[0]), PRE_WORDS + b + POST_WORDS, root_blob()), label, needle) + for bad_ops in (['v12', 'v0', 'v4'], ['v12', 'v0', 'v4', 'v8', 'v9']): + must_refuse(lambda ops=bad_ops: Probe().lower('v_perm_b32', 'v_perm_b32', ops, []), f'arity {len(bad_ops)}') + print('modifiers and wrong operand counts refused: ok') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = [('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else [] + compilers.append(('dxc', dxc, 'vs_6_0', 'ps_6_0')) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for tag, compiler, vs_profile, ps_profile in compilers: + for idx, triples in enumerate(DRAW_SETS): + pipe = G.Pipeline(vs_words(triples), PS_WORDS, root_blob()) + vs_bin = compile_hlsl(compiler, tag, pipe.hlsl_vs(), f'{tag}_vs_{idx}', vs_profile, directory) + ps_text = pipe.hlsl_ps() + ps_bin = compile_hlsl(compiler, tag, ps_text, f'{tag}_ps_{idx}', ps_profile, directory) + want = words_text(ref_perm_b32(*t) for t in triples) + run = draw(renderer, adapter, vs_bin, ps_bin, want) + sys.stdout.write(run.stdout) + if run.returncode == 77: + sys.exit(77) + assert run.returncode == 0, f'{tag} set {idx} failed:\n{run.stdout}\n{run.stderr}' + print(f'{tag} v_perm_b32 draw {idx}: {want}') + if idx == 0: + # Mutation 1: swap S0 and S1. + mut1 = ps_text.replace('perm_b32(v0, v4, v8)', 'perm_b32(v4, v0, v8)') + assert mut1 != ps_text + mut1_bin = compile_hlsl(compiler, tag, mut1, f'{tag}_ps_mut_swap', ps_profile, directory) + run_m1 = draw(renderer, adapter, vs_bin, mut1_bin, want) + assert run_m1.returncode != 0, f'{tag} S0/S1 swap mutation escaped' + print(f'{tag} v_perm_b32 swap mutation: fails as expected (rc={run_m1.returncode})') + # Mutation 2: use byte 0/4 sign bit (bit 7) instead of byte 1/5 sign bit (bit 15). + mut2 = ps_text.replace('31u : 15u', '31u : 7u') + assert mut2 != ps_text + mut2_bin = compile_hlsl(compiler, tag, mut2, f'{tag}_ps_mut_sign', ps_profile, directory) + run_m2 = draw(renderer, adapter, vs_bin, mut2_bin, want) + assert run_m2.returncode != 0, f'{tag} sign-bit mutation escaped' + print(f'{tag} v_perm_b32 sign-bit mutation: fails as expected (rc={run_m2.returncode})') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + check_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_gfx2hlsl_pixel_first_lane_check.py b/tests/startup_gfx2hlsl_pixel_first_lane_check.py new file mode 100644 index 0000000000..afdad8dbf6 --- /dev/null +++ b/tests/startup_gfx2hlsl_pixel_first_lane_check.py @@ -0,0 +1,330 @@ +"""The first active lane of a pixel stage in tools/startup/gfx2hlsl.py (#2618, the F rows), read back from a D3D12 draw. + + (no arguments) a 32-lane model of the source pair, translation controls and refusals + binary <llvm-mc> assemble every fixture with LLVM (gfx1013) and compare with the words here + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pixel stage with DXC ps_6_0 (the lowering uses a shader + model 6.0 wave intrinsic, so FXC is not used), draw a triangle over 32 x 32 + pixels and compare every covered pixel with a CPU reference for its desktop + wave. The optional fxc argument is accepted and ignored. + +The source pair (RDNA 2 ISA, S_FF1_I32_B32 and V_READLANE_B32): + s_ff1_i32_b32 sD, exec_lo the index of the lowest set bit of EXEC: the first active lane + v_readlane_b32 sX, vY, sD vY of lane sD (bits 4:0 in wave32), whatever EXEC says +so sX is vY of the first active lane. The fixtures are written in LLVM 15 spelling and assembled from source. + +The model below runs the pair on 32 lanes with plain integers, from the ISA text and not from the lowering, for random +EXEC masks, and shows that sX is the input of the lowest active lane. + +The desktop contract is the one of the #2835 wave reductions: the console packs pixels into waves in its own way, so a +correct program cannot depend on which pixel is first, and the pair becomes WaveReadLaneFirst(vY) over the active lanes +of the desktop wave. The lane number has no desktop meaning, so every other read of sD is refused, as are a program +with branches, an EXEC that is not the entry mask at the s_ff1 or at the readlane, s_wqm (helper lanes in EXEC on the +console), a readlane source that is a v_writelane_b32 spill, and the other stages. + +The draw cannot know the desktop packing in advance, so the test appends one observation to the translated pixel +stage: the fourth channel is replaced by the lane index, the lane count (WaveGetLaneCount) and WaveActiveMin of the +pixel id, which names the wave without using the intrinsic under test. The readback (offscreen_check +--startup-pixel-dump) is grouped by that name, and every covered pixel's result is compared with the input of the +covered pixel with the lowest lane index in its group. The triangle leaves quads partly covered: their helper lanes run +the stage, are not in the console EXEC (no s_wqm), and must not be picked. Planted errors in the translated text (the +lane's own value, the wave's largest value, the first lane of the quad, the lane after the first) must fail. +""" +import collections +import random +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import compile_hlsl # noqa: E402 +from startup_gfx2hlsl_s_ff1_check import Probe # noqa: E402 +from startup_gfx2hlsl_wave_reduce_check import ( # noqa: E402 + CLEAR, CMP, MULTIPLIER, SIZE, START_MUL, TRIANGLE_VS, V_READLANE_B32, WQM, assemble_object, dump, export, move, + program, sop1, sopp, translate, vop3) + +MASK = 0xffffffff +EXEC_LO, EXEC_HI, VCC_LO = 126, 127, 106 +S_MOV_B32, S_FF1_I32_B32, S_AND_SAVEEXEC_B32, S_LSHL_B32 = 0x03, 0x13, 0x3c, 0x1e +V_WRITELANE_B32 = 0x361 +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + detail)) + if not ok: + failures.append(label) + + +def sop2(op, sdst, ssrc0, ssrc1): + return struct.pack('<I', 0x80000000 | (op << 23) | (sdst << 16) | (ssrc1 << 8) | ssrc0) + + +def ff1(sd=5): + return [('s_ff1_i32_b32 s%d, exec_lo' % sd, sop1(S_FF1_I32_B32, sd, EXEC_LO))] + + +def readlane(sx=6, vy=1, sd=5): + return [('v_readlane_b32 s%d, v%d, s%d' % (sx, vy, sd), vop3(V_READLANE_B32, sx, 256 + vy, sd))] + + +def s_mov(sd, src, text): + return ('s_mov_b32 s%d, %s' % (sd, text), sop1(S_MOV_B32, sd, src)) + + +SAVEEXEC = [('s_and_saveexec_b32 s0, vcc_lo', sop1(S_AND_SAVEEXEC_B32, 0, VCC_LO))] +RESTORE = [('s_mov_b32 exec_lo, s0', sop1(S_MOV_B32, EXEC_LO, 0))] +SHIFT = [('s_lshl_b32 s7, s5, 2', sop2(S_LSHL_B32, 7, 5, 130))] +SPILL = [('v_writelane_b32 v3, s0, 0', vop3(V_WRITELANE_B32, 3, 0, 128))] # v3: a table of scalar slots +END = [move(4, 6)] + export('v4', 'v1', 'v1') # first lane's input, own input, own input, position +FIRST = program(START_MUL, ff1(), readlane(), END) +# Two reads of one first lane: the input and the packed position (x | y << 16) of the same pixel. +TWO = program(START_MUL, ff1(), readlane(), readlane(7, 0), [move(4, 6), move(2, 7)], export('v4', 'v2', 'v1')) +# The lane number overwritten after its readlane, then read as a number: the new value, not the lane. +REUSED = program(START_MUL, ff1(), readlane(), [s_mov(5, 131, '3'), move(2, 5)], [move(4, 6)], + export('v4', 'v2', 'v1')) + + +def branch_program(): + """s_cbranch_execz at the top, landing on the export after the pair.""" + body = START_MUL + ff1() + readlane() + [move(4, 6)] + words_before = sum(len(w) for _t, w in body) // 4 + label = [('s_cbranch_execz label_%04X' % (4 * (1 + words_before)), sopp(0x08, words_before))] + return program(label, body, export('v4', 'v1', 'v1')) + + +def refusals(): + """(label, program, expected reason fragment): each is refused, the fragment names the reason.""" + return [ + ('after s_wqm exec, exec', program(START_MUL, WQM, ff1(), readlane(), END), 'after s_wqm exec, exec'), + ('EXEC changed before the s_ff1', program(START_MUL, CMP, SAVEEXEC, ff1(), readlane(), END), + 'EXEC is not the entry mask'), + ('EXEC changed between the s_ff1 and the readlane', program(START_MUL, CMP, ff1(), SAVEEXEC, readlane(), END), + 'EXEC is no longer the entry mask'), + # Conservative: the restore brings the entry mask back, but the one-lane model no longer knows it. + ('EXEC changed and restored between (conservative)', + program(START_MUL, CMP, ff1(), SAVEEXEC, RESTORE, readlane(), END), 'EXEC is no longer the entry mask'), + ('the lane number shifted as data', program(START_MUL, ff1(), SHIFT, readlane(), END), + 's_lshl_b32 s7, s5, 2 reads the lane number as data'), + ('the lane number moved to a VGPR', program(START_MUL, ff1(), readlane(), [move(4, 5)], + export('v4', 'v1', 'v1')), + 'v_mov_b32_e32 v4, s5 reads the lane number as data'), + ('the lane number copied to another SGPR', program(START_MUL, ff1(), [s_mov(7, 5, 's5')], readlane(6, 1, 7), + END), + 's_mov_b32 s7, s5 reads the lane number as data'), + ('a lane spill VGPR as the readlane source', program(START_MUL, SPILL, ff1(), readlane(6, 3), END), + 'is a lane spill written by v_writelane_b32'), + ('a program with branches', branch_program(), 'with branches'), + # The translator refuses exec_hi as an operand before the pair is reached; the pair's own wave64 guard is + # behind it. + ('a program that names exec_hi', program(START_MUL, [s_mov(8, EXEC_HI, 'exec_hi')], ff1(), readlane(), END), + 'exec_hi'), + ] + + +# ---- 32-lane model of the source pair (the ISA, not the lowering) ----------------------------------------------------- +def model_pair(inputs, exec_mask): + """sX after s_ff1_i32_b32 sD, exec_lo / v_readlane_b32 sX, vY, sD on 32 lanes (vY = inputs).""" + sd = MASK if exec_mask == 0 else (exec_mask & -exec_mask).bit_length() - 1 + return inputs[sd & 31] # wave32: the lane select's bits 4:0 + + +def controls(): + rng = random.Random(2618) + agree = True + for _ in range(500): + inputs = [rng.getrandbits(32) for _ in range(32)] + mask = rng.getrandbits(32) or 1 + first = min(k for k in range(32) if mask >> k & 1) + agree &= model_pair(inputs, mask) == inputs[first] + check('32-lane model: the pair reads the input of the lowest active lane for 500 random EXEC masks', agree) + + for label, (_source, words), want in ( + ('the pair', FIRST, ['s6 = WaveReadLaneFirst(v1);']), + ('two reads of one first lane', TWO, ['s6 = WaveReadLaneFirst(v1);', 's7 = WaveReadLaneFirst(v0);']), + ('the lane number overwritten after its readlane', REUSED, + ['s6 = WaveReadLaneFirst(v1);', 's5 = 0x00000003u;', 'v2 = 0x00000003u;'])): + text, reason = translate(words) + lines = [ln.strip() for ln in (text or '').split('\n')] + check('%s translates' % label, text is not None and all(w in lines for w in want), + reason or '\n'.join(ln for ln in lines if re.search(r'\bs[5-7]\b', ln))) + if text is not None and label != 'the lane number overwritten after its readlane': + check('%s: the lane number has no run-time value' % label, + not any(re.search(r'\bs5\b', ln) for ln in lines), '\n'.join(lines)) + + for label, (_source, words), want in refusals(): + text, reason = translate(words) + check('refused: %s (%s)' % (label, reason), text is None and want in (reason or ''), str(reason)) + + for kind in ('vs', 'ms'): + stage = Probe(kind=kind) + try: + stage.one('s_ff1_i32_b32', 's_ff1_i32_b32 s5, exec_lo') + check('s_ff1_i32_b32 of exec_lo in a %s stage is refused' % kind, False, str(stage.lines)) + except G.Unsupported as error: + check('s_ff1_i32_b32 of exec_lo in a %s stage is refused (%s)' % (kind, error), + 'outside compute' in str(error), str(error)) + + +# ---- the draw --------------------------------------------------------------------------------------------------------- +OBSERVE = (' o.mrt0.w = asfloat(WaveGetLaneIndex() | (WaveGetLaneCount() << 8) |' + ' (WaveActiveMin(uint(i.pos.x) | (uint(i.pos.y) << 5)) << 16));\n return o;') + + +def observed(text): + assert text.count(' return o;') == 1 + return text.replace(' return o;', OBSERVE) + + +def input_word(x, y): + """v_mul_u32_u24_e32 v1, 0x9b5d, v0 with v0 = x | y << 16 (both below 2^24 here).""" + return ((x | (y << 16)) * MULTIPLIER) & MASK + + +def position(x, y): + return x | (y << 16) + + +# Planted errors in the translated text, each a replacement of the lowered readlane. +MUTATIONS = { + 'own lane': lambda v: v, + 'largest value of the wave': lambda v: 'WaveActiveMax(%s)' % v, + 'first lane of the quad': lambda v: 'QuadReadLaneAt(%s, 0)' % v, + 'lane after the first': lambda v: 'WaveReadLaneAt(%s, WaveReadLaneFirst(WaveGetLaneIndex()) + 1)' % v, +} + + +def mutate(text, how): + return re.sub(r'WaveReadLaneFirst\((v\d+)\)', lambda m: MUTATIONS[how](m.group(1)), text) + + +# (label, program, channels): each of the first three output channels is 'first' (the first lane's input), 'first +# position' (the first lane's packed position) or 'input' (the pixel's own input). +DRAWS = [('the pair', FIRST, ('first', 'input', 'input')), + ('two reads of one first lane', TWO, ('first', 'first position', 'input'))] + + +def verify(channels, words): + """Group the readback by desktop wave and compare with the CPU reference. Returns (errors, facts).""" + pixels = struct.unpack('<%dI' % (len(words) // 4), words) + groups, errors = collections.defaultdict(list), [] + for y in range(SIZE): + for x in range(SIZE): + p = pixels[(y * SIZE + x) * 4:(y * SIZE + x) * 4 + 4] + if p == (CLEAR,) * 4: + continue + groups[p[3] >> 16].append((x, y, p)) + counts = set() + for key, members in groups.items(): + lanes = [p[3] & 0xff for _x, _y, p in members] + counts.update((p[3] >> 8) & 0xff for _x, _y, p in members) + if len(set(lanes)) != len(lanes) or (key & 31, key >> 5) not in {(x, y) for x, y, _p in members}: + errors.append('wave %d: lanes %s do not name one wave' % (key, lanes)) + continue + fx, fy, _fp = min(members, key=lambda m: m[2][3] & 0xff) + for x, y, p in members: + expected = [input_word(fx, fy) if kind == 'first' else position(fx, fy) if kind == 'first position' + else input_word(x, y) for kind in channels] + if list(p[:3]) != expected: + errors.append('pixel (%d,%d): %s, reference %s (first lane (%d,%d) of %d pixels)' + % (x, y, ' / '.join('%08x' % w for w in p[:3]), ' / '.join('%08x' % w for w in expected), + fx, fy, len(members))) + covered = {(x, y) for members in groups.values() for x, y, _p in members} + quads = {(x // 2, y // 2) for x, y in covered} + partial_quads = sum(1 for qx, qy in quads + if sum((2 * qx + i, 2 * qy + j) in covered for i in (0, 1) for j in (0, 1)) < 4) + if len(counts) != 1: + errors.append('lane counts %s' % sorted(counts)) + lane_count = min(counts) if counts else 0 + shared = sum(1 for members in groups.values() if len(members) > 1) + facts = ('covered=%d waves=%d lane_count=%s partial_waves=%d partial_quads=%d waves_of_several=%d' + % (len(covered), len(groups), '/'.join(map(str, sorted(counts))), + sum(1 for members in groups.values() if len(members) < lane_count), partial_quads, shared)) + if partial_quads == 0 or len(covered) < 100 or shared == 0: + errors.append('the draw does not exercise partly covered quads and shared waves: ' + facts) + return errors, facts + + +def check_draw(dxc, renderer, adapter, fxc=None): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', TRIANGLE_VS, 'vs_dxc', 'vs_6_0', directory) + for label, (_source, words), channels in DRAWS: + text, reason = translate(words) + if text is None: + check('%s translates for the draw' % label, False, str(reason)) + continue + for how in [None] + list(MUTATIONS): + source = observed(text if how is None else mutate(text, how)) + if how is not None and source == observed(text): + check('%s %s %s: the planted error applies' % (adapter, label, how), False) + continue + tag = re.sub(r'\W+', '_', label + ('' if how is None else '_' + how)) + ps = compile_hlsl(dxc, 'dxc', source, 'ps_' + tag, 'ps_6_0', directory) + out = directory / ('%s.bin' % tag) + run = dump(renderer, adapter, vs, ps, out) + if run.returncode != 0 or not out.exists(): + check('%s %s %s: draw' % (adapter, label, how or 'lowering'), False, run.stdout + run.stderr) + continue + errors, facts = verify(channels, out.read_bytes()) + clean = 'debug_layer=enabled' not in run.stdout or 'debug_errors=0 debug_warnings=0' in run.stdout + if how is None: + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() if ln.startswith( + ('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + print(' %s: %s' % (label, facts)) + check('%s %s: every covered pixel matches the first lane of its desktop wave' % (adapter, label), + not errors and clean, '; '.join(errors[:3]) + ' ' + run.stdout) + else: + check('%s %s %s mutation fails against the reference: %s (%d pixels)' % ( + adapter, label, how, errors[0] if errors else '', len(errors)), bool(errors)) + + +def check_binary(llvm_mc): + programs = [(label, prog) for label, prog, _c in DRAWS] + [('the lane number overwritten', REUSED)] + programs += [(label, prog) for label, prog, _w in refusals()] + for label, (source, words) in programs: + if 'label_' not in source: + built = assemble(llvm_mc, source) + else: # a branch: llvm-mc needs the label defined, at the word the fixture names + target = int(re.search(r'label_([0-9A-F]{4})', source).group(1), 16) + out, offset = [], 0 + for text, size in zip(source.splitlines(), [n for _o, n, _name, _t in G.decode(words)]): + if offset == target: + out.append('L%04X:' % target) + out.append(text.replace('label_', 'L')) + offset += size + built = assemble_object(llvm_mc, '\n'.join(out) + '\n') + check('llvm-mc assembles the program "%s" to the same words' % label, built == words, + built.hex() + ' / ' + words.hex()) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_pk_minmax_check.py b/tests/startup_gfx2hlsl_pk_minmax_check.py new file mode 100644 index 0000000000..c9a12ef49c --- /dev/null +++ b/tests/startup_gfx2hlsl_pk_minmax_check.py @@ -0,0 +1,168 @@ +"""Packed binary16 min/max translation and D3D12 readback (#2022). + +Run without arguments for translation controls, or use +draw <dxc> <offscreen_check> <warp|hardware> to compare both halves with the CPU reference. +""" +import math +import re +import struct +import sys +import tempfile +from pathlib import Path + +from startup_gfx2hlsl_bit_alu_check import G, POST_WORDS, PRE_WORDS, vs_words, words_text +from startup_flat_param_check import compile_hlsl, draw, root_blob + + +OPS = {'min': 'false', 'max': 'true'} +DEFAULT_LO, DEFAULT_HI = (0, 0), (1, 1) +LITERAL = 0x4400c000 # high +4, low -2 +TAG = 0x40000000 + + +def lower(asm, sym=None, masks=()): + stage = G.Stage.__new__(G.Stage) + stage.lines, stage.sym, stage.masks = [], sym or {}, set(masks) + stage.used_s, stage.used_v, stage.exec_known = set(), set(), True + stage.one(asm.split()[0], asm) + return stage.lines + + +def controls(): + for op, flag in OPS.items(): + mnemonic = f'v_pk_{op}_f16' + for operands, words in ( + ('v0, v1', ('v0', 'v1')), + ('v0, 0', ('v0', '0x00000000u')), + ('0x4400c000, v1', ('0x4400c000u', 'v1')), + ('v0, s20', ('v0', 's20')), + ): + for low, high, modifiers in ( + (DEFAULT_LO, DEFAULT_HI, ''), + ((1, 1), (0, 0), ' op_sel:[1,1] op_sel_hi:[0,0]'), + ((1, 0), (0, 1), ' op_sel:[1,0] op_sel_hi:[0,1]'), + ): + expected = [] + for picks in (low, high): + args = [f'({w} >> 16) & 0xffffu' if h else f'{w} & 0xffffu' for w, h in zip(words, picks)] + expected.append(f'minmax16_bits({", ".join(args)}, {flag})') + asm = f'{mnemonic} v3, {operands}{modifiers}' + got = lower(asm) + assert got == [f'v3 = {expected[0]} | ({expected[1]} << 16);'], (asm, got) + print(f'{asm}: packed HLSL matches') + + for tail in ('v0, v1 neg_lo:[1,0]', 'v0, v1 neg_hi:[0,1]', 'v0, v1 clamp', 'v0, v1 mul:2', + 'v0, v1 op_sel:[1]', 'v0, v1 op_sel_hi:[0,2]'): + refuses(f'{mnemonic} v3, {tail}', tail.split()[-1]) + for source in ('1', '-1', '0.0', '1.0', 'vcc', 'exec', 'm0', 'null', 'src_scc', 'v[0:1]', + 's[20:20]', 'v256', 's106', '-v0', '0x100000000'): + refuses(f'{mnemonic} v3, {source}, v1', f'source {source} requires') + refuses(f'{mnemonic} v256, v0, v1', 'destination v256 is out of range') + refuses(f'{mnemonic} v3, v0, s20', 'numeric use of s20 holding root', sym={20: ('root',)}) + refuses(f'{mnemonic} v3, v0, s20', 'is a lane mask', masks=(20,)) + + for op, tail in (('add', ''), ('mul', ''), ('fma', ', v2')): + refuses(f'v_pk_{op}_f16 v3, v0, 0x4000{tail}', 'is not a single VGPR') + + +def refuses(asm, reason, **kwargs): + try: + lower(asm, **kwargs) + except G.Unsupported as error: + assert reason in str(error), (asm, error) + else: + raise AssertionError(f'accepted {asm}') + print(f'{asm}: refused') + + +def half_reference(op, a, b): + x, y = (struct.unpack('<e', struct.pack('<H', bits))[0] for bits in (a, b)) + if math.isnan(x) and math.isnan(y): + return 0x7e00 + if math.isnan(x): + return b + if math.isnan(y): + return a + if x == y == 0.0: + return (a | b) if op == 'min' else (a & b) + return a if (x <= y if op == 'min' else x >= y) else b + + +def reference(op, a, b, low, high): + lo, hi = (half_reference(op, (a >> (16 * i)) & 0xffff, (b >> (16 * j)) & 0xffff) + for i, j in (low, high)) + return lo | (hi << 16) + + +# Four output channels per group. Each row holds two source words, optional special source, and low/high picks. +# Manual mutants that must fail the draws: swap op_sel/op_sel_hi, use max for min, and replace the NaN tests +# with float isnan() folded to false (model that fold by replacing both tests with false). +GROUPS = { + 'zeros': ( + (0x80000000, 0x00008000, '', DEFAULT_LO, DEFAULT_HI), + (0x00008000, 0x80000000, '', DEFAULT_LO, DEFAULT_HI), + (0x80000000, 0x80000000, '', DEFAULT_LO, DEFAULT_HI), + (0x00008000, 0x00008000, '', DEFAULT_LO, DEFAULT_HI), + ), + 'nan_and_range': ( + (0xfe017d01, 0x40003c00, '', DEFAULT_LO, DEFAULT_HI), + (0x40003c00, 0x7e02fd02, '', DEFAULT_LO, DEFAULT_HI), + (0xfe017d01, 0x7e02fd02, '', DEFAULT_LO, DEFAULT_HI), + (0x7c008001, 0xfc000001, '', DEFAULT_LO, DEFAULT_HI), + ), + 'selectors': ( + (LITERAL, 0x42003c00, 'literal', (1, 0), (0, 1)), + (0x42003c00, LITERAL, 'sgpr', (0, 1), (1, 0)), + (0x4200bc00, 0, 'zero', DEFAULT_LO, (1, 0)), + (0x42003c00, 0x4400c000, '', DEFAULT_LO, DEFAULT_HI), + ), +} + + +def pixel_words(op, cases): + """Encode the source-built fixture using the two-source gfx1013 VOP3P fields.""" + body = bytearray() + if any(kind == 'sgpr' for _, _, kind, _, _ in cases): + body += struct.pack('<2I', 0xbe9403ff, LITERAL) # s_mov_b32 s20, literal + opcode = 0x11 if op == 'min' else 0x12 + for channel, (_, _, kind, low, high) in enumerate(cases): + src0 = 256 + channel if kind != 'literal' else 255 + src1 = {'sgpr': 20, 'zero': 128}.get(kind, 260 + channel) + w0 = 0xcc004000 | (opcode << 16) | (12 + channel) | (low[0] << 11) | (low[1] << 12) + w1 = src0 | (src1 << 9) | (high[0] << 27) | (high[1] << 28) + body += struct.pack('<2I', w0, w1) + if kind == 'literal': + body += struct.pack('<I', LITERAL) + return PRE_WORDS + bytes(body) + POST_WORDS + + +def check_draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for group, cases in GROUPS.items(): + vs_code = vs_words([(a, b, 0) for a, b, _, _, _ in cases]) + for op in OPS: + name = f'{group}_{op}' + pipeline = G.Pipeline(vs_code, pixel_words(op, cases), root_blob()) + vs = compile_hlsl(dxc, 'dxc', pipeline.hlsl_vs(), f'vs_{name}', 'vs_6_0', directory) + packed_ps = pipeline.hlsl_ps() + for shift in (0, 16): + # Export each half in a normal binary32 word so D3D preserves every result bit. + ps_text, count = re.subn(r'F\((v1[2-5])\)', + rf'F(((\1 >> {shift}) & 0xffffu) | 0x{TAG:x}u)', packed_ps) + assert count == 4, packed_ps + ps = compile_hlsl(dxc, 'dxc', ps_text, f'ps_{name}_{shift}', 'ps_6_0', directory) + expected = words_text(TAG | ((reference(op, a, b, low, high) >> shift) & 0xffff) + for a, b, _, low, high in cases) + result = draw(renderer, adapter, vs, ps, expected) + assert result.returncode == 0, (name, shift, expected, result.stderr) + print(f'{name}, shift {shift}: {expected}') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'draw' and sys.argv[4] in ('warp', 'hardware'): + check_draw(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py b/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py new file mode 100644 index 0000000000..b79e184e35 --- /dev/null +++ b/tests/startup_gfx2hlsl_readfirstlane_load_recompute_check.py @@ -0,0 +1,207 @@ +"""Check v_readfirstlane_b32 of a uniform compute buffer load past the entry block, without shader machine code. + +A lane the load skipped keeps an older VGPR, so every lane loads the words again into a temporary from an address +every lane computes alike (the uniform expression of the address VGPR, or its copy while EXEC is still the entry +mask), and the read copies that temporary. A branch target, an EXEC write or an overwrite between the load and +the read still refuses, as do a per-lane address, a graphics stage and a destination of the wrong width. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + resources = {(('table', 0), 0): {'index': 0}} # the formatted load reads the stride and FORMAT words by index + + def __init__(self): + self.modified, self.other_modified, self.uavs = set(), set(), {} + + def resource(self, key, kind): + return 'r0' + + def uav(self, key, kind='raw'): + return 'w0' + + def stored_images(self): + return self.uavs + + def ud(self, key): + return 0 + + +def run(*instructions, kind='cs', descriptor_proven=False): + """Translate disassembly text through the same dispatch and block split as a real stage.""" + s = G.Stage.__new__(G.Stage) + if descriptor_proven: + # The past-entry descriptor proof of a formatted load is checked in startup_gfx2hlsl_compute_check.py. + s.formatted_descriptor_from_block = lambda reg, first: True + s.pipe, s.lines, s.attrs = Pipe(), [], {} + s.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)} + s.sym.update({16 + i: ('desc', ('table', 0), 32, i) for i in range(8)}) + s.sym.update({24 + i: ('desc', ('table', 0), 64, i) for i in range(8)}) + s.used_s, s.used_v, s.masks = set(), set(), set() + s.exec_known, s.kind = True, kind + s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + try: + s.translate() + except G.Unsupported as error: + return str(error) + return [line for _, lines, _ in s.blocks for line in lines] + + +REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' +READ = 'v_readfirstlane_b32 s9, v7' +# Offset 0x8 is a join: the branch at 0x0 skips the instruction at 0x4, so everything after it is past the entry. +JOIN = ('s_cbranch_scc0 label_0008', 's_nop 0') +SCALAR = 's_buffer_load_dword s3, s[4:7], 0x10' # a uniform scalar written after the join +LOAD = 'buffer_load_dword v7, off, s[4:7], s3' # at 0xc after JOIN + (SCALAR,) +NARROW = 's_and_saveexec_b32 s8, s2' + +# (label, instructions, the lines from the load on) +ACCEPTED = [ + ('scalar offset load', JOIN + (SCALAR, LOAD, READ), + ['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 's9 = ulc_7;']), + # The temporary already holds the words, so a later write of the offset scalar does not matter. + ('offset scalar rewritten after the load', JOIN + (SCALAR, LOAD, 's_mov_b32 s3, 0', READ), + ['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 's3 = 0x00000000u;', 's9 = ulc_7;']), + # While EXEC is the entry mask every lane ran the address definition, so its copy serves even after the + # scalar it read is rewritten. + ('address copy under the entry exec', + JOIN + (SCALAR, 'v_mov_b32_e32 v6, s3', 's_mov_b32 s3, 0', 'buffer_load_dword v7, v6, s[4:7], 0 offen', READ), + ['a = v6 + 0;', 'v7 = r0.Load(a + 0);', 'ul14_7 = r0.Load(a + 0);', 's9 = ul14_7;']), + ('second word of a two-dword load', + JOIN + (SCALAR, 'buffer_load_dwordx2 v[7:8], off, s[4:7], s3', 'v_readfirstlane_b32 s9, v8'), + ['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 'v8 = r0.Load(a + 4);', + 'ulc_8 = r0.Load(a + 4);', 's9 = ulc_8;']), + ('conversion of the loaded word', + JOIN + (SCALAR, LOAD, 'v_cvt_f32_u32_e32 v8, v7', 'v_readfirstlane_b32 s9, v8'), + ['a = s3 + 0;', 'v7 = r0.Load(a + 0);', 'ulc_7 = r0.Load(a + 0);', 'v8 = U(float(v7));', + 's9 = U(float((ulc_7)));']), +] +for label, instructions, lines in ACCEPTED: + got = run(*instructions) + check(f'{label} accepted', isinstance(got, list) and got[-len(lines):] == lines, repr(got)) + +# A formatted load keeps the selected component; the address and the selection are the ones the guarded write uses. +got = run(*JOIN, SCALAR, 'buffer_load_format_x v7, off, s[4:7], s3', READ, descriptor_proven=True) +pick = '((ud0 >> 0) & 7u) == 4u ? c0 : ((ud0 >> 0) & 7u) == 5u ? c1 : ((ud0 >> 0) & 7u) == 6u ? c2 : ' \ + '((ud0 >> 0) & 7u) == 7u ? c3 : ((ud0 >> 0) & 7u) == 1u ? one : 0u' +check('formatted load accepted', isinstance(got, list) and 'a = s3 + 0;' in got and + got[-3:] == ['ulc_7 = %s;' % pick, '}', 's9 = ulc_7;'] and got[-4] == 'v7 = %s;' % pick, repr(got)) +# The temporary is declared once at function scope, next to the registers. +s = G.Stage.__new__(G.Stage) +s.uniform_load_temps, s.used_s, s.used_v, s.kind, s.pipe = {'ulc_7'}, set(), set(), 'cs', Pipe() +s.pipe.packed_position_vgpr = None +check('temporary declared', ' uint ulc_7 = 0;' in s.declarations(), repr(s.declarations())) + +REFUSED = [ + ('loop carries a narrowed EXEC into the load', JOIN + (SCALAR, LOAD, READ, 's_add_u32 s3, s3, 4', + 'v_cmp_lt_f32_e32 vcc_lo, v0, v1', 's_and_b32 exec_lo, exec_lo, vcc_lo', 's_cmp_lt_u32 s3, 64', + 's_cbranch_scc1 label_000c', 's_endpgm')), + ('EXEC write outside the textual back edge', JOIN + (SCALAR, LOAD, READ, 's_branch label_0020', + 's_cbranch_scc1 label_000c', 's_endpgm', NARROW, 's_branch label_0018')), + # Two definitions reach the read at a join. + ('join of a load and another definition', ('s_cbranch_scc0 label_0014', SCALAR, LOAD, 's_branch label_0014', + 'v_mov_b32_e32 v7, 0', READ, 's_endpgm')), + ('per-lane address', JOIN + ('buffer_load_dword v7, v0, s[4:7], 0 offen', READ)), + ('per-lane offset scalar', JOIN + ('v_cmp_lt_f32_e64 s3, v0, v1', LOAD, READ)), + # A loop head between the load and the read: a later iteration reaches the read without the load. + ('back-edge target between load and read', JOIN + (SCALAR, LOAD, 's_nop 0', READ, 's_cbranch_scc0 label_0014', + 's_endpgm')), + # The load runs inside a block lanes with clear EXEC skip, and the read is past the block's join. + ('load inside a block one lane skips', JOIN + (SCALAR, 's_and_saveexec_b32 s8, vcc_lo', 's_cbranch_execz label_0018', + LOAD, 's_mov_b32 exec_lo, s8', READ, 's_endpgm')), + ('EXEC narrowed between load and read', JOIN + (SCALAR, LOAD, NARROW, READ)), + # On empty EXEC, RDNA 2 reads the old lane-0 VGPR, not an unguarded reload. + ('empty EXEC keeps the old lane-zero VGPR', JOIN + ('v_mov_b32_e32 v7, 17', 's_mov_b32 exec_lo, 0', + SCALAR, LOAD, READ)), + ('address expression with potentially empty EXEC', + JOIN + (NARROW, SCALAR, 'v_mov_b32_e32 v7, s3', 'buffer_load_dword v7, v7, s[4:7], 0 offen', READ)), + # Under a narrowed EXEC a lane that skipped the address definition holds an older copy, and the expression + # is gone once its scalar is rewritten. + ('stale address copy under a narrowed exec', + JOIN + (NARROW, SCALAR, 'v_mov_b32_e32 v6, s3', 's_mov_b32 s3, 0', 'buffer_load_dword v7, v6, s[4:7], 0 offen', + READ)), + ('loaded register overwritten before the read', JOIN + (SCALAR, LOAD, 'v_mov_b32_e32 v7, v0', READ)), + ('two-dword load into three registers', JOIN + (SCALAR, 'v_mov_b32_e32 v9, v0', + 'buffer_load_dwordx2 v[7:9], off, s[4:7], s3', + 'v_readfirstlane_b32 s9, v9')), +] +for label, instructions in REFUSED: + got = run(*instructions) + check(f'{label} refused', got == REFUSAL, repr(got)) +got = run(*JOIN, SCALAR, LOAD, READ, 's_add_u32 s3, s3, 4', 's_cmp_lt_u32 s3, 64', + 's_cbranch_scc1 label_000c', NARROW, 's_endpgm') +check('loop with unchanged EXEC accepts the load', isinstance(got, list) and 's9 = ulc_7;' in got, repr(got)) +got = run(*JOIN, SCALAR, LOAD, READ, kind='ps') +check('graphics stage refused', got == REFUSAL, repr(got)) + +# Without the load allowlist the accepted programs refuse again. +original = G.UNIFORM_LOADS +G.UNIFORM_LOADS = frozenset() +try: + for label, instructions, _ in ACCEPTED: + got = run(*instructions) + check(f'control: {label} refused without the load proof', got == REFUSAL, repr(got)) +finally: + G.UNIFORM_LOADS = original + +IMG_LOAD = 'image_load v7, [v2, v3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D' +IMG_COORDS = ('v_mov_b32_e32 v2, s3', 'v_mov_b32_e32 v3, 1') +IMG_ACCEPTED = [ + ('image_load past entry block', JOIN + (SCALAR,) + IMG_COORDS + (IMG_LOAD, READ), + ['t = r0.Load(int3(v2, v3, 0));', 'v7 = U(t.x);', 'ul14_7 = U(t.x);', 's9 = ul14_7;']), + ('two-channel image_load past entry block converted', + JOIN + (SCALAR,) + IMG_COORDS + ( + 'image_load v[7:8], v[2:3], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D', + 'v_cvt_f32_u32_e32 v9, v8', 'v_readfirstlane_b32 s9, v9'), + ['t = r0.Load(int3(v2, v3, 0));', 'v7 = U(t.x);', 'ul14_7 = U(t.x);', + 'v8 = U(t.y);', 'ul14_8 = U(t.y);', 'v9 = U(float(v8));', 's9 = U(float((ul14_8)));']), +] +for label, instructions, lines in IMG_ACCEPTED: + got = run(*instructions) + check(f'{label} accepted', isinstance(got, list) and got[-len(lines):] == lines, repr(got)) + +for label, instructions in ( + ('image_load past entry block with image_store in dispatch', + JOIN + (SCALAR,) + IMG_COORDS + ( + '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', + IMG_LOAD, 'image_store v[12:15], v[10:11], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D', READ)), + ('image_load in EXEC-modifying loop', + JOIN + (SCALAR,) + IMG_COORDS + ( + IMG_LOAD, READ, 's_add_u32 s3, s3, 4', + 'v_cmp_lt_f32_e32 vcc_lo, v0, v1', 's_and_b32 exec_lo, exec_lo, vcc_lo', + 's_cmp_lt_u32 s3, 64', 's_cbranch_scc1 label_000c', 's_endpgm')), + ('image_load inside a skipped execz block', + JOIN + (SCALAR,) + IMG_COORDS + ( + 's_and_saveexec_b32 s8, vcc_lo', 's_cbranch_execz label_0020', + IMG_LOAD, 's_mov_b32 exec_lo, s8', READ, 's_endpgm')), + ('join of image_load and another definition', + ('s_cbranch_scc0 label_001c', SCALAR) + IMG_COORDS + ( + IMG_LOAD, 's_branch label_001c', 'v_mov_b32_e32 v7, 0', READ, 's_endpgm'))): + got = run(*instructions) + check(f'{label} refused', got == REFUSAL, repr(got)) + +original_img = G.UNIFORM_IMAGE_LOADS +G.UNIFORM_IMAGE_LOADS = frozenset() +try: + for label, instructions, _ in IMG_ACCEPTED: + got = run(*instructions) + check(f'control: {label} refused without image_load proof', got == REFUSAL, repr(got)) +finally: + G.UNIFORM_IMAGE_LOADS = original_img + +print('Readfirstlane load recompute checks: %d failed' % len(failures)) +sys.exit(1 if failures else 0) diff --git a/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py b/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py index 538adf7899..9cfb81f773 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py @@ -41,6 +41,7 @@ def run(*instructions): REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' +EARLIER = {'lane mask source': 'v_mul_f32 reads lane mask s3 as numeric data'} READ = 'v_readfirstlane_b32 s9, v7' # Offset 0x8 is a join: the branch at 0x0 skips the instruction at 0x4. JOIN = ('s_cbranch_scc0 label_0008', 's_nop 0') @@ -64,6 +65,7 @@ def read_line(lines): ('chain through a second VGPR', JOIN + (LOAD, 'v_mov_b32_e32 v6, s3', 'v_mul_f32_e64 v7, v6, 2.0', READ)), ('unrelated scalar write in between', JOIN + (LOAD, DEFINE, 's_mov_b32 s2, 0', READ)), ('median of three after a join', JOIN + (LOAD, 'v_med3_f32 v7, s3, 0, 0.5', READ)), + ('log2 then ceil after a join', JOIN + (LOAD, 'v_log_f32_e32 v7, s3', 'v_ceil_f32_e32 v7, v7', READ)), # A one-path scalar written before the join stays proven across a join whose other paths do not write it. ('one-path scalar written before the join', (LOAD,) + JOIN + (DEFINE, READ)), ('one-path scalar across a divergent branch when untouched', @@ -81,7 +83,8 @@ def read_line(lines): 's_cbranch_scc1 label_0018', DEFINE, READ, 's_endpgm')), ] EXPECTED = {'chain through a second VGPR': 's9 = U(F((s3)) * 2.0);', - 'median of three after a join': 's9 = U(med3_32(F(s3), F(0x00000000u), 0.5));'} + 'median of three after a join': 's9 = U(med3_32(F(s3), F(0x00000000u), 0.5));', + 'log2 then ceil after a join': 's9 = U(ceil(F((U(log2(F(s3)))))));'} for label, instructions in ACCEPTED: got = run(*instructions) want = EXPECTED.get(label, RECOMPUTED) @@ -127,7 +130,7 @@ def read_line(lines): ] for label, instructions in REFUSED: got = run(*instructions) - check(f'{label} refused', got == REFUSAL, repr(got)) + check(f'{label} refused', got == EARLIER.get(label, REFUSAL), repr(got)) # Writes the translator does not route through the first operand. probe = G.Stage.__new__(G.Stage) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index b1fb5ee6f5..9082323bce 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -15,11 +15,25 @@ def check(label, condition, detail=''): class Pipe: - """The single resource needed by the buffer-load probe.""" + """The minimal pipeline resources needed by the load probes.""" + + resources = {(('table', 0), 0): {'index': 0}} # the formatted load reads the stride and FORMAT words by index + + def __init__(self): + self.modified, self.other_modified, self.uavs = set(), set(), {} def resource(self, key, kind): return 'r0' + def uav(self, key, kind='raw'): + return 'w0' + + def stored_images(self): + return self.uavs + + def ud(self, key): + return 0 + REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' READ = 'v_readfirstlane_b32 s9, v7' @@ -28,15 +42,21 @@ def resource(self, key, kind): ALIAS_LOAD = 's_buffer_load_dwordx2 s[2:3], s[4:7], s2' -def run(*instructions, exec_known=True): +def run(*instructions, exec_known=True, kind=None, group=None): """Translate disassembly text using the same dispatch and branch scan as a real stage.""" s = G.Stage.__new__(G.Stage) s.pipe, s.lines = Pipe(), [] + if group: + s.pipe.group = group s.attrs = {} s.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)} + s.sym.update({16 + i: ('desc', ('table', 0), 32, i) for i in range(8)}) + s.sym.update({24 + i: ('desc', ('table', 0), 64, i) for i in range(8)}) s.sym[3] = ('fixed_buffer_word',) s.used_s, s.used_v, s.masks = set(), set(), set() s.exec_known = exec_known + if kind: + s.kind = kind s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] try: s.translate() @@ -79,6 +99,16 @@ def run(*instructions, exec_known=True): ['v7 = U(F(s2) * 2.0 + F(0x3f800000u));']), ('reciprocal', ('v_rcp_f32_e32 v7, s2',), ['v7 = U(1.0 / F(s2));']), + ('base-2 logarithm', ('v_log_f32_e32 v7, s2',), + ['v7 = U(log2(F(s2)));']), + ('clamped log2 of abs scalar', ('v_log_f32_e64 v7, |s2| clamp',), + ['v7 = U(saturate(log2(abs(F(s2)))));']), + ('ceiling', ('v_ceil_f32_e32 v7, s2',), + ['v7 = U(ceil(F(s2)));']), + ('scaled ceiling of negated scalar', ('v_ceil_f32_e64 v7, -s2 mul:2',), + ['v7 = U((ceil((-F(s2)))) * 2.0);']), + ('log2 then ceil chain', ('v_log_f32_e32 v7, s2', 'v_ceil_f32_e32 v7, v7'), + ['v7 = U(log2(F(s2)));', 'v7 = U(ceil(F(v7)));']), # The clamp to [0, 0.5] of a scalar, as compiled shaders write it. ('median of three', ('v_med3_f32 v7, s2, 0, 0.5',), ['v7 = U(med3_32(F(s2), F(0x00000000u), 0.5));']), @@ -119,6 +149,10 @@ def run(*instructions, exec_known=True): ('varying scalar buffer offset', (COMPARE, 's_buffer_load_dword s3, s[4:7], s2', 'v_mov_b32_e32 v7, s3', READ)), ('listed op with varying source', (MOVE, 'v_mul_f32_e64 v7, v0, 2.0', READ)), + ('log2 of a varying source', ('v_log_f32_e32 v7, v0', READ)), + ('ceil of a varying source', ('v_ceil_f32_e32 v7, v0', READ)), + ('log2 of a lane mask', (COMPARE, 'v_log_f32_e32 v7, s2', READ)), + ('ceil of a lane mask', (COMPARE, 'v_ceil_f32_e32 v7, s2', READ)), ('median of three with a varying source', (MOVE, 'v_med3_f32 v7, s2, v0, 0.5', READ)), ('median of three of a lane mask', (COMPARE, 'v_med3_f32 v7, s2, 0, 0.5', READ)), ('op_sel overwrite', (MOVE, 'v_mul_f32_e64 v7, s2, 2.0 op_sel:[0,0]', READ)), @@ -175,8 +209,30 @@ def run(*instructions, exec_known=True): # (tests/startup_gfx2hlsl_readfirstlane_recompute_check.py covers that rule). got = run(MOVE, 's_cbranch_scc0 label_0010', READ, 's_endpgm', 's_endpgm') check('read after the first terminator recomputed', got[:2] == ['v7 = s2;', 's9 = s2;'], repr(got)) -# Since #1755 the float lowering itself refuses an op_sel it does not model, before the read. -EARLIER = {'op_sel overwrite': 'modifier op_sel:[0,0]'} +# These instructions refuse before v_readfirstlane_b32 is reached. +EARLIER = { + 'op_sel overwrite': 'modifier op_sel:[0,0]', + # The high word of a copied wave64 mask carries the mask tag: its numeric read is refused where it is lowered. + 'overlapping 64-bit move high word': 'v_mov_b32 reads lane mask s4 as numeric data', + 'high word of saved exec': 'v_mov_b32 reads lane mask s3 as numeric data', + 'modified move overwrite': "v_mov_b32 with ['clamp']", + 'mask from uniform compare': 'v_mov_b32 data operand s2 is a lane mask', + 'vcc': 'v_mov_b32 data operand vcc_lo is a lane mask', + 'exec': 'v_mov_b32 data operand exec_lo is a lane mask', + 'compare into SGPR': 'v_mov_b32 data operand s2 is a lane mask', + 'saved exec': 'v_mov_b32 data operand s2 is a lane mask', + 'mask in the entry block': 'v_mov_b32 data operand s2 is a lane mask', + 'median of three of a lane mask': 'v_med3_f32 reads lane mask s2 as numeric data', + 'log2 of a lane mask': 'v_log_f32 reads lane mask s2 as numeric data', + 'ceil of a lane mask': 'v_ceil_f32 reads lane mask s2 as numeric data', + 'unsigned to float conversion of a mask': 'v_cvt_f32_u32 reads lane mask s2 as numeric data', + # A scalar op that reads a lane mask as a number is refused where it is lowered (before the read). + 'aliased load first word': 's_buffer_load_dwordx2 reads lane mask s2 as numeric data', + 'aliased load second word': 's_buffer_load_dwordx2 reads lane mask s2 as numeric data', + 'varying scalar buffer offset': 's_buffer_load_dword reads lane mask s2 as numeric data', + 'mask through scalar arithmetic': 's_add_u32 reads lane mask s2 as numeric data', + 'mask through scalar condition': 's_cmp_eq_u32 reads lane mask vcc_lo as numeric data', +} for label, instructions in REFUSED: got = run(*instructions) check(f'{label} refused', got == EARLIER.get(label, REFUSAL), repr(got)) @@ -190,16 +246,229 @@ def run(*instructions, exec_known=True): check('uniform m0 write into SCC accepted', got == ['m0 = s2 & 0x000000ffu;', 'scc = m0 != 0;', 's3 = scc ? 0x00000001u : 0x00000000u;', 'v7 = s3;', 's9 = v7;'], repr(got)) -# Every other SCC write either updates the proof or invalidates it: ops whose SCC result is not -# modelled (carry, selected source), s_wqm, and the symbolic descriptor path, which emits nothing. -for label, first in (('unmodelled carry', 's_add_u32 s3, s2, 1'), - ('whole quad mode', 's_wqm_b64 exec, exec'), +# s_add_u32 and its siblings emit their SCC (carry, borrow, overflow, selected source) from the sources, so the select that +# reads it is uniform when the sources are. +got = run('s_add_u32 s3, s2, 1', 's_cselect_b32 s3, 1, 0', 'v_mov_b32_e32 v7, s3', READ) +check('select after a modelled carry from a uniform source accepted', + got == ['scc = (s2 + 0x00000001u) < (s2);', 's3 = s2 + 0x00000001u;', 's3 = scc ? 0x00000001u : 0x00000000u;', + 'v7 = s3;', 's9 = v7;'], repr(got)) +# Every other SCC write either updates the proof or invalidates it: s_wqm and the symbolic descriptor path, which emits nothing. +for label, first in (('whole quad mode', 's_wqm_b64 exec, exec'), ('symbolic descriptor word', 's_and_b32 s10, s4, 0xff')): got = run(first, 's_cselect_b32 s3, 1, 0', 'v_mov_b32_e32 v7, s3', READ) check(f'select after {label} refused', got == REFUSAL, repr(got)) got = run('v_mov_b32_e32 v7, s2', READ, exec_known=False) check('unknown exec refused', got == REFUSAL, repr(got)) +# A compute load through a read-only descriptor with a uniform address is uniform; the value has no recomputable +# expression, so only the entry block reads it. +LOAD_OFF = 'buffer_load_dword v7, off, s[4:7], s2' +LOAD_OFFEN = 'buffer_load_dword v8, v7, s[4:7], 0 offen' +got = run(LOAD_OFF, READ, kind='cs') +check('uniform scalar offset load accepted', got[-2:] == ['v7 = r0.Load(a + 0);', 's9 = v7;'], repr(got)) +got = run(MOVE, LOAD_OFFEN, 'v_readfirstlane_b32 s9, v8', kind='cs') +check('uniform vgpr offset load accepted', got[-1] == 's9 = v8;' and len(got) == 4, repr(got)) +got = run(MOVE, 'buffer_load_dword v7, v7, s[4:7], 0 offen', READ, kind='cs') +check('load overwriting its uniform address accepted', got[-1] == 's9 = v7;', repr(got)) +for label, instructions, kind, known in ( + ('load with a varying vgpr offset', ('buffer_load_dword v8, v0, s[4:7], 0 offen', 'v_readfirstlane_b32 s9, v8'), 'cs', True), + ('load with a varying scalar offset', (COMPARE, 'buffer_load_dword v7, off, s[4:7], s2', READ), 'cs', True), + ('load in a graphics stage', (LOAD_OFF, READ), 'ps', True), + ('load without a stage kind', (LOAD_OFF, READ), None, True), + ('load with unknown exec', (LOAD_OFF, READ), 'cs', False), + ('load after the entry block', (LOAD_OFF, 's_cbranch_scc0 label_0010', READ, 's_endpgm', 's_endpgm'), 'cs', True), + ('load then a varying overwrite', (LOAD_OFF, 'v_mov_b32_e32 v7, v0', READ), 'cs', True)): + got = run(*instructions, kind=kind, exec_known=known) + check(f'{label} refused', got == REFUSAL, repr(got)) +original = G.UNIFORM_LOADS +G.UNIFORM_LOADS = frozenset() +try: + got = run(LOAD_OFF, READ, kind='cs') + check('control: load refused without tracking', got == REFUSAL, repr(got)) +finally: + G.UNIFORM_LOADS = original + +# Every destination register of a multi-register load is uniform, and only the registers the opcode writes. +for label, instructions, read in ( + ('two-dword load, first word', ('buffer_load_dwordx2 v[7:8], off, s[4:7], s2',), 7), + ('two-dword load, second word', ('buffer_load_dwordx2 v[7:8], off, s[4:7], s2',), 8), + ('four-dword load, last word', ('buffer_load_dwordx4 v[6:9], off, s[4:7], s2',), 9), + ('load over a varying register', ('v_mov_b32_e32 v8, v0', 'buffer_load_dwordx2 v[7:8], off, s[4:7], s2'), 8), + ('formatted two-component load', ('buffer_load_format_xy v[7:8], off, s[4:7], s2',), 8)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} accepted', got[-1] == 's9 = v%d;' % read, repr(got)) +for label, instructions, read in ( + ('two-dword load into three registers', ('v_mov_b32_e32 v9, v0', 'buffer_load_dwordx2 v[7:9], off, s[4:7], s2'), 9), + ('two-dword load into one register', ('v_mov_b32_e32 v8, v0', 'buffer_load_dwordx2 v7, off, s[4:7], s2'), 8), + ('two-dword load with a varying offset', ('buffer_load_dwordx2 v[7:8], v0, s[4:7], 0 offen',), 8), + ('other register after a load', ('v_mov_b32_e32 v6, v0', 'buffer_load_dwordx2 v[7:8], off, s[4:7], s2'), 6)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} refused', got == REFUSAL, repr(got)) + +# A compute image_load through an unmodified fixed table descriptor at uniform coordinates is uniform when +# no image write exists in the dispatch; the entry-block read has no recomputable expression. +IMG_LOAD = 'image_load v7, [v2, v3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D' +IMG_COORDS = ('v_mov_b32_e32 v2, s2', 'v_mov_b32_e32 v3, 1') +for label, instructions, read in ( + ('2D single-channel image_load', IMG_COORDS + (IMG_LOAD,), 7), + ('2D multi-channel image_load, second component', + IMG_COORDS + ('image_load v[7:8], v[2:3], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D',), 8), + ('2D partial dmask 0x5 image_load', + IMG_COORDS + ('image_load v[7:8], v[2:3], s[16:23] dmask:0x5 dim:SQ_RSRC_IMG_2D',), 8), + ('2D full dmask 0xf image_load, lane 3', + IMG_COORDS + ('image_load v[7:10], v[2:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D',), 10), + ('2D packed a16 image_load', + ('v_mov_b32_e32 v2, s2', 'image_load v7, v2, s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D a16'), 7), + ('2D-array image_load', + ('v_mov_b32_e32 v2, 1', 'v_mov_b32_e32 v3, 2', 'v_mov_b32_e32 v4, s2', + 'image_load v7, v[2:4], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY'), 7), + ('2D image_load_mip with uniform coordinates', + IMG_COORDS + ('v_mov_b32_e32 v4, 0', 'image_load_mip v7, v[2:4], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D'), 7), + ('2D-array image_load_mip with uniform coordinates', + ('v_mov_b32_e32 v2, 1', 'v_mov_b32_e32 v3, 2', 'v_mov_b32_e32 v4, s2', 'v_mov_b32_e32 v5, 0', + 'image_load_mip v[7:10], v[2:5], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY'), 10), + ('3D image_load_mip with uniform coordinates', + ('v_mov_b32_e32 v2, 1', 'v_mov_b32_e32 v3, 2', 'v_mov_b32_e32 v4, s2', 'v_mov_b32_e32 v5, 0', + 'image_load_mip v[7:8], v[2:5], s[16:23] dmask:0x5 dim:SQ_RSRC_IMG_3D'), 8), + ('image_load overwriting its uniform coordinate', + IMG_COORDS + ('image_load v2, v[2:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D',), 2)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind='cs') + check(f'{label} accepted', isinstance(got, list) and got[-1] == 's9 = v%d;' % read, repr(got)) + +for label, instructions, read, kind, known in ( + ('image_load with varying x coordinate', + ('v_mov_b32_e32 v3, 1', 'image_load v7, [v0, v3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D'), 7, 'cs', True), + ('image_load with varying y coordinate', + ('v_mov_b32_e32 v2, 1', 'image_load v7, [v2, v0], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D'), 7, 'cs', True), + ('image_load with modified descriptor', + ('s_or_b32 s17, s17, 0x1000',) + IMG_COORDS + (IMG_LOAD,), 7, 'cs', True), + ('image_load with overwritten descriptor word', + ('s_mov_b32 s18, 0',) + IMG_COORDS + (IMG_LOAD,), 7, 'cs', True), + ('image_load in a dispatch with image_store', + IMG_COORDS + ( + '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', + IMG_LOAD, 'image_store v[12:15], v[10:11], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D'), + 7, 'cs', True), + ('image_load_mip with varying mip coordinate', + IMG_COORDS + ('image_load_mip v7, [v2, v3, v0], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D',), + 7, 'cs', True), + ('image_load_mip with varying x coordinate', + ('v_mov_b32_e32 v3, 1', 'v_mov_b32_e32 v4, 0', + 'image_load_mip v7, [v0, v3, v4], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D'), + 7, 'cs', True), + ('image_load_mip in a dispatch with image_store', + IMG_COORDS + ( + 'v_mov_b32_e32 v4, 0', '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', + 'image_load_mip v7, v[2:4], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D', + 'image_store v[12:15], v[10:11], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D'), + 7, 'cs', True), + ('image_load in a graphics stage', IMG_COORDS + (IMG_LOAD,), 7, 'ps', True), + ('image_load without a stage kind', IMG_COORDS + (IMG_LOAD,), 7, None, True), + ('image_load with unknown exec', IMG_COORDS + (IMG_LOAD,), 7, 'cs', False), + ('image_load read after a branch target', + IMG_COORDS + (IMG_LOAD, 's_cbranch_scc0 label_0018', 's_endpgm', 's_endpgm'), 7, 'cs', True), + ('other register after two-channel image_load', + ('v_mov_b32_e32 v9, v0',) + IMG_COORDS + + ('image_load v[7:8], v[2:3], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D',), 9, 'cs', True)): + got = run(*instructions, 'v_readfirstlane_b32 s9, v%d' % read, kind=kind, exec_known=known) + check(f'{label} refused', got == REFUSAL, repr(got)) + +original_img = G.UNIFORM_IMAGE_LOADS +G.UNIFORM_IMAGE_LOADS = frozenset() +try: + got = run(*(IMG_COORDS + (IMG_LOAD, READ)), kind='cs') + check('control: image_load refused without tracking', got == REFUSAL, repr(got)) +finally: + G.UNIFORM_IMAGE_LOADS = original_img + +# tid.x >> n is 0 in every lane when the group's X size is at most 1 << n (the thread id VGPR is untouched). +WAVE = 'v_lshrrev_b32_e32 v1, 6, v0' +READ1 = 'v_readfirstlane_b32 s9, v1' +for size in (1, 33, 64): + got = run(WAVE, READ1, kind='cs', group=(size, 1, 1)) + check(f'wave index of a group of {size} accepted', got[-1] == 's9 = v1;', repr(got)) +got = run(WAVE, 's_cbranch_scc0 label_0010', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) +check('wave index read past the entry block recomputed as zero', got[-1] == 's9 = 0u;', repr(got)) +# v0 overwritten by a constant is no thread id: the shift of a uniform value is itself uniform (200 >> 6). +got = run('v_mov_b32_e32 v0, 200', WAVE, READ1, kind='cs', group=(64, 1, 1)) +check('shift of an overwritten v0 is a uniform integer chain', got[-1] == 's9 = v1;' and 'v1 = v0 >> (0x00000006u & 31);' in got, repr(got)) +for label, instructions, kind, group in ( + ('wave index of a group of 65', (WAVE, READ1), 'cs', (65, 1, 1)), + ('wave index of a group of 128', (WAVE, READ1), 'cs', (128, 1, 1)), + ('wave index of a group with no recorded size', (WAVE, READ1), 'cs', None), + ('shift by 5 of a group of 64', ('v_lshrrev_b32_e32 v1, 5, v0', READ1), 'cs', (64, 1, 1)), + ('wave index in a graphics stage', (WAVE, READ1), 'ps', (64, 1, 1)), + ('wave index without a stage kind', (WAVE, READ1), None, (64, 1, 1)), + ('wave index of v1', ('v_lshrrev_b32_e32 v1, 6, v1', READ1), 'cs', (64, 1, 1)), + ('wave index after v0 is loaded', ('buffer_load_dword v[0:1], off, s[4:7], s2', WAVE, READ1), 'cs', (64, 1, 1)), + ('wave index after v0 is swapped', ('v_swap_b32 v2, v0', WAVE, READ1), 'cs', (64, 1, 1)), + ('wave index with an output modifier', ('v_lshrrev_b32_e64 v1, 6, v0 clamp', READ1), 'cs', (64, 1, 1)), + ('wave index of a register shift', ('v_lshrrev_b32_e32 v1, v2, v0', READ1), 'cs', (64, 1, 1))): + got = run(*instructions, kind=kind, group=group) + check(f'{label} refused', got == ("v_lshrrev_b32 with ['clamp']" if 'modifier' in label else REFUSAL), repr(got)) + +# The global thread id of a 64-wide group, (uniform << 6) + tid.x, shifted back by 6 is the uniform part. +GID = 'v_lshl_add_u32 v0, s2, 6, v0' +got = run(GID, WAVE, READ1, kind='cs', group=(64, 1, 1)) +check('global thread id shifted back accepted', got[-1] == 's9 = v1;', repr(got)) +got = run(GID, WAVE, 's_cbranch_scc0 label_0014', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) +check('thread id base shifted back recomputed past the entry block', got[-1] == 's9 = ((s2 << 6u) >> 6u);', repr(got)) +got = run(GID, WAVE, 's_mov_b32 s2, 5', 's_cbranch_scc0 label_0018', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(64, 1, 1)) +check('thread id base shifted back refused past the entry block after the scalar changed', got == REFUSAL, repr(got)) +for label, instructions, group in ( + ('thread id base of a group of 128', (GID, WAVE, READ1), (128, 1, 1)), + ('thread id base shifted by more than the scale', ('v_lshl_add_u32 v0, s2, 6, v0', 'v_lshrrev_b32_e32 v1, 7, v0', READ1), (64, 1, 1)), + ('thread id base from a varying scalar', (COMPARE, 'v_lshl_add_u32 v0, s2, 6, v0', WAVE, READ1), (64, 1, 1)), + ('thread id base with the scalar rewritten', (GID, 's_mov_b32 s2, vcc_lo', WAVE, READ1), (64, 1, 1)), + ('thread id base from a vector', ('v_lshl_add_u32 v0, v5, 6, v0', WAVE, READ1), (64, 1, 1)), + ('thread id base added to another vector', ('v_lshl_add_u32 v0, s2, 6, v4', WAVE, READ1), (64, 1, 1)), + ('thread id base added to a rewritten v0', ('v_mov_b32_e32 v0, 3', GID, WAVE, READ1), (64, 1, 1)), + ('thread id base rewritten after', (GID, 'v_add_nc_u32_e32 v0, s3, v0', WAVE, READ1), (64, 1, 1)), + ('thread id base scaled by 32', ('v_lshl_add_u32 v0, s2, 5, v0', WAVE, READ1), (64, 1, 1))): + got = run(*instructions, kind='cs', group=group) + # The compare's mask in s2 is refused where v_lshl_add_u32 reads it as a number, before the read. + expected = ('v_lshl_add_u32 reads lane mask s2 as numeric data' + if label == 'thread id base from a varying scalar' else REFUSAL) + check(f'{label} refused', got == expected, repr(got)) + +# Only bits that survive both the field operation and the final shift may vary across threads. +AND_OR = 'v_and_or_b32 v2, v0, 3, s2' +EXTRACT = 'v_bfe_u32 v2, v0, 2, 3' +SHIFT = 'v_lshrrev_b32_e32 v1, 2, v2' +SHIFT1 = 'v_lshrrev_b32_e32 v1, 1, v2' +for label, op, shift, size, expression in ( + ('masked low bits of a large group', AND_OR, SHIFT, 128, '(s2 >> 2u)'), + ('mask above a non-power-of-two group', 'v_and_or_b32 v2, v0, 8, s2', SHIFT1, 7, '(s2 >> 1u)'), + ('extracted bit cleared by shift', EXTRACT, SHIFT1, 8, '0u'), + ('empty extracted field', 'v_bfe_u32 v2, v0, 0, 0', SHIFT1, 64, '0u'), + ('narrow field of a large group', 'v_bfe_u32 v2, v0, 1, 2', SHIFT, 128, '0u')): + got = run(op, shift, READ1, kind='cs', group=(size, 1, 1)) + check(f'{label} accepted at entry', got[-1] == 's9 = v1;', repr(got)) + got = run(op, shift, 's_cbranch_scc0 label_0014', READ1, 's_endpgm', 's_endpgm', kind='cs', group=(size, 1, 1)) + check(f'{label} recomputed past entry', got[-1] == f's9 = {expression};', repr(got)) +for label, instructions, size in ( + ('surviving masked bit', (AND_OR, SHIFT1, READ1), 4), + ('surviving extracted bit', (EXTRACT, SHIFT1, READ1), 9), + ('variable mask', ('v_and_or_b32 v2, v0, s2, s2', SHIFT, READ1), 4), + ('vector OR source', ('v_and_or_b32 v2, v0, 3, v1', SHIFT, READ1), 4), + ('predicate as OR source', (COMPARE, AND_OR, SHIFT, READ1), 4), + ('scalar overwritten before shift', (AND_OR, 's_mov_b32 s2, 5', SHIFT, READ1), 4), + ('scalar overwritten before recompute', (AND_OR, SHIFT, 's_mov_b32 s2, 5', 's_cbranch_scc0 label_0018', + READ1, 's_endpgm', 's_endpgm'), 4), + ('overwritten thread id', ('v_swap_b32 v1, v0', EXTRACT, SHIFT1, READ1), 8), + ('overwritten field', (EXTRACT, 'v_mov_b32_e32 v2, v0', SHIFT1, READ1), 8), + ('register field offset', ('v_bfe_u32 v2, v0, s2, 3', SHIFT1, READ1), 8), + ('register field width', ('v_bfe_u32 v2, v0, 2, s2', SHIFT1, READ1), 8), + ('signed field', ('v_bfe_i32 v2, v0, 2, 3', SHIFT1, READ1), 8), + ('unknown group for a masked field', (AND_OR, SHIFT, READ1), None)): + got = run(*instructions, kind='cs', group=(size, 1, 1) if size else None) + # a lane mask as the OR source meets the mask rule (#2702) before the uniformity rule: either refusal keeps it refused + mask_first = label == 'predicate as OR source' and got == 'v_and_or_b32 reads lane mask s2 as numeric data' + check(f'{label} refused', got == REFUSAL or mask_first, repr(got)) + # Older probes may provide either no tracker or only part of the tracking state. for present in ((), ('uniform_v',), ('uniform_v', 'varying_s')): s = G.Stage.__new__(G.Stage) @@ -230,5 +499,24 @@ def run(*instructions, exec_known=True): finally: G.UNIFORM_VALU = original +# A uniform VGPR used as both operands doubles its recomputation text each time: the text stays bounded (a chain of +# 22 doublings would otherwise grow to megabytes per instruction). The entry-block read copies the VGPR, so it needs no +# expression; only a read past the entry block recomputes, and past the limit that chain has none. +DOUBLE = 'v_add_nc_u32_e32 v7, v7, v7' +got = run(MOVE, *[DOUBLE] * 3, READ, kind='cs', group=(64, 1, 1)) +check('short doubling chain stays readable', isinstance(got, list) and got[-1] == 's9 = v7;', repr(got)[:200]) +stage = G.Stage.__new__(G.Stage) +stage.pipe, stage.lines, stage.attrs = Pipe(), [], {} +stage.pipe.group = (64, 1, 1) +stage.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)} +stage.sym[3] = ('fixed_buffer_word',) +stage.used_s, stage.used_v, stage.masks, stage.exec_known, stage.kind = set(), set(), set(), True, 'cs' +stage.ins = [(4 * i, 4, a.split()[0], a) for i, a in enumerate([MOVE] + [DOUBLE] * 22)] +stage.translate() +longest = max(map(len, stage.uniform_expr.values()), default=0) +check('long doubling chain keeps a bounded recompute expression', longest <= 2 * G.UNIFORM_EXPR_LIMIT, str(longest)) +got = run(MOVE, *[DOUBLE] * 22, READ, kind='cs', group=(64, 1, 1)) +check('entry-block read of a long doubling chain copies the VGPR', isinstance(got, list) and got[-1] == 's9 = v7;', repr(got)[:200]) + print('Readfirstlane uniformity checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) diff --git a/tests/startup_gfx2hlsl_root_check.py b/tests/startup_gfx2hlsl_root_check.py index 31413e53df..a32c5dbb19 100644 --- a/tests/startup_gfx2hlsl_root_check.py +++ b/tests/startup_gfx2hlsl_root_check.py @@ -51,7 +51,13 @@ def container(parts): def main(): table = gfx2hlsl.parse_root(TABLE_ROOT)["params"] assert table == [dict(type=1, vis=0, reg=5, space=2, count=3)], table - vs, ps = code(12), code(0) + # --pending visits requests in key order, and every key hashes the cache revision. Pick the pixel + # export target (mrt0..mrt7) so that the valid request sorts after a bad one at the current revision. + vs = code(12) + for target in range(8): + ps = code(target) + if gfx2hlsl.pipeline_key(vs, ps, VALID_ROOT) > min(gfx2hlsl.pipeline_key(vs, ps, root) for root, _ in BAD.values()): + break with tempfile.TemporaryDirectory() as tmp: directory = Path(tmp) requests = {name: root for name, (root, _) in BAD.items()} diff --git a/tests/startup_gfx2hlsl_s_abs_check.py b/tests/startup_gfx2hlsl_s_abs_check.py new file mode 100644 index 0000000000..3067316891 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_abs_check.py @@ -0,0 +1,254 @@ +"""s_abs_i32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_abs_check.py + startup_gfx2hlsl_s_abs_check.py dispatch <dxc> <offscreen_check> <warp|hardware> + +RDNA 2 ISA SOP1: S_ABS_I32 sets D to the absolute value of S0 as a signed 32-bit word +(INT_MIN stays 0x80000000) and SCC = (D != 0). Matches pixel_aot. Lane masks and +descriptor sources are refused. The reference is plain Python; the translated text is +evaluated on the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_pack_absdiff_check). Each case stores D, SCC, and an SCC-dependent +branch token so `asint` / `0u - x` and the nonzero SCC test are exercised on device. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0x00000001, 0xffffffff, 0x80000000, 0x7fffffff, 0xfffffff1, 0x12345678) +# GPU cases from review: INT_MIN, -1, 0, a positive value (SCC follows D != 0). +DRAW = (0x80000000, 0xffffffff, 0x00000000, 0x12345678) +SCC_BRANCH_TAKEN = 0x00a11ced +SCC_BRANCH_NOT = 0x00dead00 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + + +def ref_abs(word): + word &= MASK + return (-word if word & 0x80000000 else word) & MASK + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_abs_i32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': 0}) + want = (ref_abs(word), int(ref_abs(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_abs_i32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_abs_i32', 's_abs_i32 s3, %d' % (word if word < 0x80000000 else word - (1 << 32))) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': 0}) + want = (ref_abs(word), int(ref_abs(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), stage.lines, (out['s3'], out['scc']), want) + break + check('s_abs_i32 immediate source', bad is None, str(bad)) + + lines, sym = translate(sop1('s_abs_i32', 3, 1), sym={1: ('const', 0xfffffff1)}) + # 0xfffffff1 = -15; abs = 15 + check('s_abs_i32 folds a constant source', + lines[0].startswith('s3 = 0x0000000fu;') and sym.get(3) == ('const', 15) + and any(l.startswith('scc = ') for l in lines), + str((lines, sym.get(3)))) + + # INT_MIN stays. + lines, sym = translate(sop1('s_abs_i32', 3, 1), sym={1: ('const', 0x80000000)}) + check('s_abs_i32 keeps INT_MIN', + lines[0].startswith('s3 = 0x80000000u;') and sym.get(3) == ('const', 0x80000000), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_abs_i32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_abs_i32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_abs_i32', 's_abs_i32 s3, s1') + check('s_abs_i32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_abs_i32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_abs_i32', 's_abs_i32 s3, s1') + check('s_abs_i32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_abs_i32 refuses a descriptor source', 'desc' in str(error), str(error)) + + # Negative control: drop the abs; evaluation must diverge on a negative word. + stage = Probe() + stage.one('s_abs_i32', 's_abs_i32 s3, s1') + mutated = [re.sub(r'\(asint\(s1\) < 0 \? \(0u - s1\) : s1\)', 's1', stage.lines[0])] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0xfffffff1, 'scc': 0}) + out_bad = run(mutated + stage.lines[1:], {'s1': 0xfffffff1, 'scc': 0}) + check('mutation that drops abs diverges', + out_ok['s3'] == 15 and out_bad['s3'] == 0xfffffff1, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_abs(dxc, runner, adapter, cases, directory): + """Translate s_abs_i32 once; feed each case through a UAV and read D, SCC, and a branch token.""" + lines, _ = translate(sop1('s_abs_i32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + # Per case: abs result, SCC as uint, SCC-dependent branch token. + result_width = 3 + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + result_width * i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' data.Store(%d, uint(scc));' % (dst_byte + 4)) + # Prove SCC drives a real branch on the device (not only a stored bool). + hlsl.append(' if (scc) {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_TAKEN)) + hlsl.append(' } else {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_NOT)) + hlsl.append(' }') + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_abs_i32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + result_width * len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + got = dispatch_abs(dxc, runner, adapter, DRAW, Path(tmp)) + for i, word in enumerate(DRAW): + abs_v = ref_abs(word) + scc_v = int(abs_v != 0) + branch = SCC_BRANCH_TAKEN if scc_v else SCC_BRANCH_NOT + base = 3 * i + label = 'dispatch s_abs_i32 %#010x' % word + check('%s result' % label, got[base] == abs_v, + 'got %#x want %#x' % (got[base], abs_v)) + check('%s SCC' % label, got[base + 1] == scc_v, + 'got %#x want %#x' % (got[base + 1], scc_v)) + check('%s SCC branch' % label, got[base + 2] == branch, + 'got %#x want %#x' % (got[base + 2], branch)) + # Explicit INT_MIN / zero controls called out in the review. + check('dispatch keeps INT_MIN as 0x80000000', got[0] == 0x80000000, hex(got[0])) + check('dispatch SCC of 0 is false (branch not-taken)', + got[3 * 2 + 1] == 0 and got[3 * 2 + 2] == SCC_BRANCH_NOT, + str((got[3 * 2 + 1], got[3 * 2 + 2]))) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_s_bit_scan_check.py b/tests/startup_gfx2hlsl_s_bit_scan_check.py new file mode 100644 index 0000000000..34cc810d76 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bit_scan_check.py @@ -0,0 +1,216 @@ +"""Scalar bit counts and scans in tools/startup/gfx2hlsl.py (Frontier next batch 3 #1, #1723). + +usage: startup_gfx2hlsl_s_bit_scan_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]] + +With `draw` the same instructions also run as a pixel shader on the adapter and the result words are read back +and compared with the integer reference (D3D12 readback, FXC 5_1 and DXC 6_0). + +s_bcnt0/1_i32_b32/b64 count zero/one bits (SCC = result != 0). s_ff0/ff1_i32_b64 return the index of the lowest +zero/one bit of a 64-bit source, s_flbit_i32_b64 the number of leading zeros, s_flbit_i32_i64 the number of leading +bits equal to the sign bit; the scans return -1 when nothing qualifies and leave SCC alone. The translator refused +all of them with `Unsupported`. The instruction words are built from the SOP1 layout the decoder reads, the emitted +HLSL runs on the integer evaluator of startup_gfx2hlsl_bit_alu_check.py, and every result is compared with a plain +integer reference written from the ISA description (string and loop based, not the lowering's expressions). +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +failures = [] +OPCODES = {'s_bcnt0_i32_b32': 0x0d, 's_bcnt0_i32_b64': 0x0e, 's_bcnt1_i32_b32': 0x0f, 's_bcnt1_i32_b64': 0x10, + 's_ff0_i32_b64': 0x12, 's_ff1_i32_b64': 0x14, 's_flbit_i32_b64': 0x16, 's_flbit_i32_i64': 0x18} +EXEC_LO, M0 = 126, 124 + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def encode(name, sdst, ssrc0): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (OPCODES[name] << 8) | ssrc0) + + +class Pipeline: + def __init__(self): + self.resources, self.notes, self.modified, self.sampler_heap = {}, set(), set(), False + + +class Stage(G.Stage): + def __init__(self, masks=()): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports, self.masks = {}, set(masks) + self.pipe = Pipeline() + + +def translate(name, sdst, ssrc0, masks=()): + stage = Stage(masks) + decoded = G.decode(encode(name, sdst, ssrc0)) + for _offset, _size, op, asm in decoded: + stage.one(op, asm) + return [asm for _o, _s, _n, asm in decoded], stage.lines + + +def refused(name, sdst, ssrc0, masks=()): + try: + translate(name, sdst, ssrc0, masks) + except G.Unsupported: + return True + return False + + +def run(lines, regs): + """Evaluate the emitted `sN = expr;` and `scc = expr;` lines over the register dict.""" + env = dict(regs) + for line in lines: + target, expr = line.rstrip(';').split(' = ', 1) + env[target] = Expr(expr).run(env)[0] + return env + + +def bits(value, width): + return [(value >> i) & 1 for i in range(width)] + + +def ref(name, value): + """(result, scc or None) from the ISA text, with the source as a 32- or 64-bit integer.""" + width = 32 if name.endswith('b32') else 64 + b = bits(value, width) + if 'bcnt0' in name: + return b.count(0), True + if 'bcnt1' in name: + return b.count(1), True + if 'ff0' in name or 'ff1' in name: + want = 0 if 'ff0' in name else 1 + return next((i for i, x in enumerate(b) if x == want), MASK), False + sign = b[63] if name.endswith('i64') else 0 + n = 0 + for x in reversed(b): + if x != sign: + return n, False + n += 1 + return MASK, False + + +VALUES = [0, 1, 2, 0x80, 0xff, 0x7fffffff, 0x80000000, 0xffffffff, 0x12345678, 0xfffffffe, 0xdeadbeef] +WIDE = [0, 1, 1 << 31, 1 << 32, 1 << 33, 1 << 62, 1 << 63, (1 << 64) - 1, (1 << 63) - 1, (1 << 64) - 2, + 0x00000000ffffffff, 0xffffffff00000000, 0x0123456789abcdef, 0xfedcba9876543210, 0x8000000000000001, + 0xffffffff7fffffff] + [1 << k for k in range(64)] + [((1 << 64) - 1) ^ (1 << k) for k in range(64)] + +for name in OPCODES: + wide = not name.endswith('b32') + asm, lines = translate(name, 3, 4 if wide else 2) + src = 's[4:5]' if wide else 's2' + check('%s decodes' % name, asm == ['%s s3, %s' % (name, src)], repr(asm)) + bad = [] + for value in (WIDE if wide else VALUES): + regs = {'scc': 0, 's4': value & MASK, 's5': value >> 32, 's2': value & MASK} + env = run(lines, regs) + want, scc = ref(name, value) + want_scc = int(want != 0) if scc else 0 + if env['s3'] != want or env['scc'] != want_scc: + bad.append((hex(value), env['s3'], env['scc'], want, want_scc)) + if len(bad) == 3: + break + check('%s values' % name, not bad, repr(bad)) + scc_emitted = any(line.startswith('scc') for line in lines) + check('%s SCC %s' % (name, 'follows result' if 'bcnt' in name else 'untouched'), scc_emitted == ('bcnt' in name), + repr(lines)) + +# Refusals that must not widen: a 64-bit scan needs a register pair, 32-bit one register, and no lane-mask data. +# s_ff0 keeps the pair-only SCALAR_BITS path (inline constants refused). s_ff1_i32_b64 also accepts a +# zero-extended 32-bit immediate (#2022 Item F), so the pair-only refusal is checked on s_ff0. +check('b64 refuses an inline constant source', refused('s_ff0_i32_b64', 3, 0x80)) +check('b32 refuses exec destination', refused('s_bcnt1_i32_b32', EXEC_LO, 2)) +check('b32 refuses m0 destination', refused('s_bcnt1_i32_b32', M0, 2)) +check('b32 refuses exec source', refused('s_bcnt1_i32_b32', 3, EXEC_LO)) +check('b64 refuses a lane-mask source', refused('s_bcnt1_i32_b64', 3, 4, masks=(5,))) +check('b32 refuses a lane-mask source', refused('s_bcnt0_i32_b32', 3, 2, masks=(2,))) + + +# ---- a real draw: the translated pixel shader runs on the adapter and its words are read back ---------------- +# Each channel loads a 64-bit (or 32-bit) literal into s4/s5 and runs the scalar op into s3. +# Counts and bit indices are 0..64 or 0xffffffff. XOR moves each expected word into a distinct +# finite normal float bit pattern before the RGBA32_FLOAT export. A raw small result can flush to zero. +DRAW_TRANSPORT_XOR = 0x3f000000 +DRAW_VALUES = { + 32: [0, MASK, 0x80000000, 0x12345678, 1, 0xfffffffe, 0x0000ff00, 0xdeadbeef], + 64: [0, (1 << 64) - 1, 1 << 63, 1 << 32, 0x00000000ffffffff, 0xffffffff00000000, 0x0123456789abcdef, + 0xfedcba9876543210, 0x8000000000000001, (1 << 64) - 2, 1 << 31, 0xffffffff7fffffff], +} +POST_WORDS = bytes.fromhex('0f1800f80c0d0e0f000081bf') # exp mrt0 v12..v15 done vm; s_endpgm + + +def sop1(op, sdst, ssrc0): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (op << 8) | ssrc0) + + +def lane_words(name, value): + """Load the literals, evaluate the scalar operation, then encode its result for the export.""" + out = sop1(0x03, 4, 255) + struct.pack('<I', value & MASK) + if not name.endswith('b32'): + out += sop1(0x03, 5, 255) + struct.pack('<I', value >> 32) + xor_s3_literal = (0b10 << 30) | (0x12 << 23) | (3 << 16) | (255 << 8) | 3 + return out + sop1(OPCODES[name], 3, 4) + struct.pack('<2I', xor_s3_literal, DRAW_TRANSPORT_XOR) + + +def ps_words_for(name, chunk): + from startup_gfx2hlsl_bit_alu_check import PRE_WORDS + body = b'' + for lane, value in enumerate(chunk): + body += lane_words(name, value) + struct.pack('<I', 0x7e000000 | (12 + lane) << 17 | 1 << 9 | 3) + return PRE_WORDS + body + POST_WORDS + + +def draw_check(dxc, renderer, adapter, fxc=None): + import tempfile + from startup_gfx2hlsl_bit_alu_check import vs_words, words_text + from startup_flat_param_check import compile_hlsl, draw, root_blob + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for name in OPCODES: + values = DRAW_VALUES[32 if name.endswith('b32') else 64] + for index in range(0, len(values), 4): + chunk = values[index:index + 4] + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words_for(name, chunk), root_blob()) + tag = '%s_%s_%d' % (name, kind, index) + ps = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps_' + tag, ps_profile, directory) + vs = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_' + tag, vs_profile, directory) + expected = words_text(ref(name, v)[0] ^ DRAW_TRANSPORT_XOR for v in chunk) + run = draw(renderer, adapter, vs, ps, expected) + if run.returncode: + raise AssertionError('%s %s %s\n%s\n%s' % (kind, name, [hex(v) for v in chunk], run.stdout, + run.stderr)) + print('%s %s %s: %s' % (kind, name, [hex(v) for v in chunk], expected), flush=True) + if index == 0 and name == 's_bcnt1_i32_b64': + wrong = words_text(((ref(name, v)[0] + 1) & MASK) ^ DRAW_TRANSPORT_XOR for v in chunk) + run = draw(renderer, adapter, vs, ps, wrong) + if run.returncode != 1 or 'startup_flat_param mismatch' not in run.stderr: + raise AssertionError('%s wrong count did not produce a readback mismatch: %s%s' % + (kind, run.stdout, run.stderr)) + print('%s wrong-expectation control: fails as expected' % kind, flush=True) + + +if failures: + print('FAIL: %s' % ', '.join(failures)) + sys.exit(1) +if len(sys.argv) > 1: + if sys.argv[1] != 'draw': + raise SystemExit(__doc__) + draw_check(*sys.argv[2:]) +print('PASS') diff --git a/tests/startup_gfx2hlsl_s_bitcmp64_check.py b/tests/startup_gfx2hlsl_s_bitcmp64_check.py new file mode 100644 index 0000000000..f311b995be --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitcmp64_check.py @@ -0,0 +1,403 @@ +"""64-bit scalar bit-compare (s_bitcmp0_b64, s_bitcmp1_b64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOPC decode, value evaluation, uniformity, refusal and mutation + controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per (lo, hi, index) triple and compare the four result words + +RDNA 2 ISA, SOPC: + S_BITCMP0_B64 S0, S1: SCC = (S0.u64[S1.u[5:0]] == 0) + S_BITCMP1_B64 S0, S1: SCC = (S0.u64[S1.u[5:0]] == 1) + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads (lo, hi, index) +into s4..s6 with SOP1 literal moves, executes s_bitcmp0_b64 / s_bitcmp1_b64 (register index, immediate index 37, +and sign-extended inline -1 source), materializes each SCC via s_cselect_b32, XORs with 0x3f800000 for normal +IEEE-754 transport into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +SOPC_OPCODES = { + 's_bitcmp0_b64': 0x0e, + 's_bitcmp1_b64': 0x0f, +} + + +def sopc(op, ssrc0, ssrc1, lit=None): + """Encode one synthetic gfx1013 SOPC 32-bit (or 64-bit with literal) instruction.""" + w0 = 0xbf000000 | (op << 16) | (ssrc1 << 8) | ssrc0 + out = struct.pack('<I', w0) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def sop1_mov_lit(sdst, val): + """Encode SOP1 s_mov_b32 s<sdst>, <32-bit literal> (op 0x03, ssrc0=255).""" + return struct.pack('<2I', (0b101111101 << 23) | (sdst << 16) | (0x03 << 8) | 255, val & MASK) + + +def s_cselect_b32(sdst, ssrc0, ssrc1): + """Encode SOP2 s_cselect_b32 s<sdst>, ssrc0, ssrc1 (op 0x0a).""" + return struct.pack('<I', 0x80000000 | (0x0a << 23) | (sdst << 16) | (ssrc1 << 8) | ssrc0) + + +def s_xor_lit(sdst, ssrc0, lit): + """Encode SOP2 s_xor_b32 s<sdst>, s<ssrc0>, <32-bit literal> (op 0x12, ssrc1=255).""" + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + """Encode VOP1 v_mov_b32_e32 v<vdst>, s<ssrc> (op 0x01).""" + return struct.pack('<I', 0x7e000000 | (vdst << 17) | (0x01 << 9) | ssrc) + + +# XOR 0/1 with 0x3f800000 so exported lanes are normal IEEE-754 floats (1.0 / 1.0 + 1 ULP), never subnormals. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def ps_words(lo, hi, idx): + """Synthetic gfx1013 pixel stage exercising s_bitcmp0_b64 and s_bitcmp1_b64.""" + # Inline integer encodings in RDNA 2: 0 -> 128, 1 -> 129, 37 -> 128+37=165, -1 -> 193. + body = b''.join([ + sop1_mov_lit(4, lo), # s4 = lo + sop1_mov_lit(5, hi), # s5 = hi + sop1_mov_lit(6, idx), # s6 = bit index + sopc(0x0e, 4, 6), # s_bitcmp0_b64 s[4:5], s6 + s_cselect_b32(8, 129, 128), # s8 = scc ? 1 : 0 + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 8), # v12 = s8 ^ 0x3f800000 + sopc(0x0f, 4, 6), # s_bitcmp1_b64 s[4:5], s6 + s_cselect_b32(9, 129, 128), # s9 = scc ? 1 : 0 + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(13, 9), # v13 = s9 ^ 0x3f800000 + sopc(0x0f, 4, 128 + 37), # s_bitcmp1_b64 s[4:5], 37 + s_cselect_b32(10, 129, 128), # s10 = scc ? 1 : 0 + s_xor_lit(10, 10, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(14, 10), # v14 = s10 ^ 0x3f800000 + sopc(0x0f, 193, 6), # s_bitcmp1_b64 -1, s6 + s_cselect_b32(11, 129, 128), # s11 = scc ? 1 : 0 + s_xor_lit(11, 11, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(15, 11), # v15 = s11 ^ 0x3f800000 + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(lo=0x00000001, hi=0x00000020, idx=37): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(lo, hi, idx), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_bitcmp64(want, lo, hi, idx): + """Independent bit-string reference for S_BITCMP{0,1}_B64.""" + bits = format((hi & MASK) << 32 | (lo & MASK), '064b')[::-1] + return int(bits[idx & 63]) == want + + +def eval_scc_expr(expr, env): + """Evaluate a translated HLSL boolean SCC expression in Python.""" + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + # Convert C ternary (cond ? a : b) handling arbitrary balanced parens inside cond/a/b. + while '?' in text: + q = text.index('?') + depth = 0 + start = q - 1 + while start >= 0: + if text[start] == ')': + depth += 1 + elif text[start] == '(': + if depth == 0: + break + depth -= 1 + start -= 1 + depth = 0 + colon = -1 + end = q + 1 + while end < len(text): + if text[end] == '(': + depth += 1 + elif text[end] == ')': + if depth == 0: + break + depth -= 1 + elif text[end] == ':' and depth == 0 and colon == -1: + colon = end + end += 1 + cond = text[start + 1:q].strip() + yes = text[q + 1:colon].strip() + no = text[colon + 1:end].strip() + text = text[:start] + ('((%s) if (%s) else (%s))' % (yes, cond, no)) + text[end + 1:] + return bool(eval(text, {'__builtins__': {}}, env)) + + +def run_one(line, env, *, sym=None, scc_verified=False): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.scc_verified = scc_verified + stage.one(line.split(' ', 1)[0], line) + assert len(stage.lines) == 1, stage.lines + target, _, expr = stage.lines[0].rstrip(';').partition(' = ') + assert target == 'scc', stage.lines + return eval_scc_expr(expr, env), stage + + +def stage_refused(stage, mnemonic, line, needle=''): + try: + stage.one(mnemonic, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +PAIRS = ( + (0x00000000, 0x00000000), + (0xffffffff, 0xffffffff), + (0x00000001, 0x80000000), + (0x80000000, 0x00000001), + (0xffffffff, 0x00000000), + (0x00000000, 0xffffffff), + (0x55555555, 0xaaaaaaaa), + (0xaaaaaaaa, 0x55555555), + (0x00010020, 0x00000020), +) +INDEXES = (0, 1, 5, 31, 32, 33, 37, 63, 64, 65, 96, 127, 0xffffffe5) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOPC bytes via G.decode(). + decoded = [ + G.decode(sopc(0x0e, 4, 6))[0][3], + G.decode(sopc(0x0f, 4, 128 + 37))[0][3], + G.decode(sopc(0x0f, 193, 6))[0][3], + G.decode(sopc(0x0e, 255, 6, lit=0x80000001))[0][3], + G.decode(sopc(0x0f, 125, 128))[0][3], + ] + check('decode s_bitcmp0_b64 reg/reg', decoded[0] == 's_bitcmp0_b64 s[4:5], s6') + check('decode s_bitcmp1_b64 reg/imm37', decoded[1] == 's_bitcmp1_b64 s[4:5], 37') + check('decode s_bitcmp1_b64 inline -1', decoded[2] == 's_bitcmp1_b64 -1, s6') + check('decode s_bitcmp0_b64 literal', decoded[3] == 's_bitcmp0_b64 0x80000001, s6') + check('decode s_bitcmp1_b64 null', decoded[4] == 's_bitcmp1_b64 null, 0') + + # 2. Exhaustive SGPR pair + register/immediate index grid. + grid_ok = True + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for lo, hi in PAIRS: + for idx in INDEXES: + expected = ref_bitcmp64(want, lo, hi, idx) + for line, env in ( + ('%s s[4:5], s6' % mnemonic, {'s4': lo, 's5': hi, 's6': idx}), + ('%s s[4:5], %d' % (mnemonic, idx), {'s4': lo, 's5': hi}), + ): + got, _ = run_one(line, env) + if got != expected: + grid_ok = False + print('MISMATCH %s lo=%#x hi=%#x idx=%#x got=%s want=%s' % ( + line, lo, hi, idx, got, expected)) + check('SGPR pair grid (%d cases)' % (2 * len(PAIRS) * len(INDEXES) * 2), grid_ok) + + # 3. Inline integer 64-bit S0 (including negative sign-extension to 64 bits). + inline_ok = True + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for val in (0, 1, 64, -1, -16): + lo, hi = val & MASK, (val >> 32) & MASK + for idx in (0, 3, 4, 6, 31, 32, 37, 63, 64): + got, _ = run_one('%s %d, s6' % (mnemonic, val), {'s6': idx}) + if got != ref_bitcmp64(want, lo, hi, idx): + inline_ok = False + check('inline integer S0 sign-extends negative values to 64 bits', inline_ok) + + # 4. 32-bit hex literal S0 zero-extends to 64 bits (hi == 0 even when bit 31 is set). + lit_ok = True + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for idx in (0, 1, 31, 32, 33, 63): + got, _ = run_one('%s 0x80000001, s6' % mnemonic, {'s6': idx}) + if got != ref_bitcmp64(want, 0x80000001, 0, idx): + lit_ok = False + check('32-bit hex literal S0 zero-extends to 64 bits', lit_ok) + + # 5. null as S0 and S1, src_scc as S1, and const-tracked SGPR pair. + for mnemonic, want in (('s_bitcmp0_b64', 0), ('s_bitcmp1_b64', 1)): + for idx in (0, 31, 32, 63): + got, _ = run_one('%s null, s6' % mnemonic, {'s6': idx}) + check('%s null, s6 (idx=%d)' % (mnemonic, idx), got == (want == 0)) + got_null_idx, _ = run_one('%s s[4:5], null' % mnemonic, {'s4': 1, 's5': 0}) + check('%s s[4:5], null reads bit 0' % mnemonic, got_null_idx == (want == 1)) + for scc_val in (False, True): + got_scc, _ = run_one('%s s[4:5], src_scc' % mnemonic, + {'s4': 0x2, 's5': 0x0, 'scc': scc_val}, scc_verified=True) + check('%s src_scc=%s' % (mnemonic, scc_val), + got_scc == ref_bitcmp64(want, 0x2, 0x0, 1 if scc_val else 0)) + got_const, _ = run_one('%s s[4:5], s6' % mnemonic, {'s5': 0x20, 's6': 37}, + sym={4: ('const', 0)}) + check('%s const-tracked lo + runtime hi' % mnemonic, got_const == (want == 1)) + + # 6. Uniformity tracking on lo, hi, and bit index. + for mnemonic in ('s_bitcmp0_b64', 's_bitcmp1_b64'): + s = Probe() + s.varying_s = set() + s.scc_uniform = False + s.one(mnemonic, '%s s[4:5], s6' % mnemonic) + check('%s uniform inputs -> scc_uniform=True' % mnemonic, s.scc_uniform is True) + for bad_reg in (4, 5, 6): + s = Probe() + s.varying_s = {bad_reg} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], s6' % mnemonic) + check('%s varying s%d -> scc_uniform=False' % (mnemonic, bad_reg), s.scc_uniform is False) + + # 7. Refusals (arity, modifiers, lane masks, mask_high, invalid register classes/alignment). + for mnemonic in ('s_bitcmp0_b64', 's_bitcmp1_b64'): + check('%s 1 operand refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5]' % mnemonic, 'two unmodified operands')) + check('%s 3 operands refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6, s7' % mnemonic, 'two unmodified operands')) + check('%s modifier refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6 clamp' % mnemonic, 'two unmodified operands')) + for operands in ( + 'exec, 1', 'exec_lo, 1', 'vcc, 1', 'vcc_lo, 1', + 's[4:5], exec_lo', 's[4:5], vcc_lo', 's[4:5], exec', 's[4:5], vcc', + ): + check('%s %s lane mask refused' % (mnemonic, operands), + stage_refused(Probe(), mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], 1'), + (13, None, 's[12:13], 1'), + (None, 13, 's[12:13], 1'), + (12, None, 's[4:5], s12'), + (None, 13, 's[4:5], s13'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s %s tracked mask refused' % (mnemonic, operands), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for bad_s0 in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', '1.0', 'm0', 'src_scc'): + check('%s bad S0 %s refused' % (mnemonic, bad_s0), + stage_refused(Probe(), mnemonic, '%s %s, s6' % (mnemonic, bad_s0))) + for bad_s1 in ('v0', 's[6:7]', 's106', '1.0'): + check('%s bad S1 %s refused' % (mnemonic, bad_s1), + stage_refused(Probe(), mnemonic, '%s s[4:5], %s' % (mnemonic, bad_s1), 'bit index')) + p_unv = Probe() + p_unv.scc_verified = False + check('%s unverified src_scc refused' % mnemonic, + stage_refused(p_unv, mnemonic, '%s s[4:5], src_scc' % mnemonic, 'unverified SCC')) + + # 8. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', '& 32u' in ps_hlsl and '& 31u' in ps_hlsl) + + # 9. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_s_bitcmp0_b64', 'op_s_bitcmp1_b64')} + try: + for name in saved: + delattr(G.Stage, name) + for mnemonic in ('s_bitcmp0_b64', 's_bitcmp1_b64'): + check('unlowered %s refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6' % mnemonic)) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + # 10. Mutation / negative controls: prove our test inputs distinguish common bugs. + check('mutation: dropping bit 5 diverges on bit 37', + ref_bitcmp64(1, 0x0, 0x20, 37) != ref_bitcmp64(1, 0x0, 0x20, 37 & 31)) + check('mutation: swapping lo/hi diverges on bit 0', + ref_bitcmp64(1, 0x1, 0x0, 0) != ref_bitcmp64(1, 0x0, 0x1, 0)) + check('mutation: inverting bit0/bit1 diverges', + ref_bitcmp64(0, 0x0, 0x20, 37) != ref_bitcmp64(1, 0x0, 0x20, 37)) + check('mutation: zero-extending -1 diverges on bit 37', + ref_bitcmp64(1, 0xffffffff, 0xffffffff, 37) != ref_bitcmp64(1, 0xffffffff, 0x0, 37)) + check('mutation: sign-extending 0x80000001 diverges on bit 63', + ref_bitcmp64(1, 0x80000001, 0x0, 63) != ref_bitcmp64(1, 0x80000001, 0xffffffff, 63)) + + +GPU_VECTORS = ( + # (label, lo, hi, idx) + ('lo_bit0_set', 0x00000001, 0x00000000, 0), + ('lo_bit31_clear', 0x7fffffff, 0xffffffff, 31), + ('hi_bit32_set', 0x00000000, 0x00000001, 32), + ('hi_bit37_set', 0x00000000, 0x00000020, 37), + ('hi_bit63_set', 0x00000000, 0x80000000, 63), + ('wrapped_101', 0x00000000, 0x00000020, 101), # 101 & 63 == 37 + ('wrapped_64', 0x00000001, 0x00000000, 64), # 64 & 63 == 0 +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_bitcmp64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, lo, hi, idx in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(lo, hi, idx) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = ( + (1 if ref_bitcmp64(0, lo, hi, idx) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_bitcmp64(1, lo, hi, idx) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_bitcmp64(1, lo, hi, 37) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_bitcmp64(1, 0xffffffff, 0xffffffff, idx) else 0) ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + # Negative control: deliberately wrong expected word must fail draw(). + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_bitcmp64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_bitcmp64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_bitcmp64_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_bitreplicate_check.py b/tests/startup_gfx2hlsl_s_bitreplicate_check.py new file mode 100644 index 0000000000..ce798140d6 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitreplicate_check.py @@ -0,0 +1,311 @@ +"""64-bit scalar bit-replicate (s_bitreplicate_b64_b32) in tools/startup/gfx2hlsl.py. + + (no arguments) SOP1 decode, helper emission, value evaluation, aliasing, constant + folding, uniformity, refusal and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per 32-bit input and compare the four result words + +RDNA 2 ISA, SOP1 (0x3b): + S_BITREPLICATE_B64_B32 s[D:D+1], S0: D[2*i] = D[2*i+1] = S0[i] for i in 0..31; SCC unchanged. + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads a 32-bit +value into runtime SGPRs s6 and s4, runs disjoint s_bitreplicate_b64_b32 s[8:9], s6 and aliased +s_bitreplicate_b64_b32 s[4:5], s4, XORs the four output words with 0x3f800000 for normal IEEE-754 transport +into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +# Keep exported lanes in normal IEEE-754 float range on float render targets. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def sop1(op, sdst, ssrc0, lit=None): + """Encode one synthetic gfx1013 SOP1 32-bit (or 64-bit with literal) instruction.""" + w0 = (0b101111101 << 23) | (sdst << 16) | (op << 8) | ssrc0 + out = struct.pack('<I', w0) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def sop1_mov_lit(sdst, val): + return sop1(0x03, sdst, 255, lit=val) + + +def s_xor_lit(sdst, ssrc0, lit): + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + return struct.pack('<I', 0x7e000000 | (vdst << 17) | (0x01 << 9) | ssrc) + + +def ps_words(val): + """Synthetic gfx1013 pixel stage exercising disjoint and aliased s_bitreplicate_b64_b32.""" + body = b''.join([ + sop1_mov_lit(6, val), + s_xor_lit(6, 6, 0), # clear const sym so runtime helper is emitted + sop1_mov_lit(4, val), + s_xor_lit(4, 4, 0), + sop1(0x3b, 8, 6), # disjoint: s_bitreplicate_b64_b32 s[8:9], s6 + sop1(0x3b, 4, 4), # aliased: s_bitreplicate_b64_b32 s[4:5], s4 + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + s_xor_lit(4, 4, DRAW_TRANSPORT_XOR), + s_xor_lit(5, 5, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 8), + v_mov_b32_from_sgpr(13, 9), + v_mov_b32_from_sgpr(14, 4), + v_mov_b32_from_sgpr(15, 5), + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(val=0x00010001): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(val), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_bitreplicate(val): + """Independent bit-string reference returning (lo, hi).""" + bits = ''.join(ch * 2 for ch in format(val & MASK, '032b')) + out = int(bits, 2) + return out & MASK, (out >> 32) & MASK + + +def _bitreplicate16(x): + x &= 0xffff + x = (x | (x << 8)) & 0x00ff00ff + x = (x | (x << 4)) & 0x0f0f0f0f + x = (x | (x << 2)) & 0x33333333 + x = (x | (x << 1)) & 0x55555555 + return (x | (x << 1)) & MASK + + +def eval_u32(expr, env): + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + return eval(text, {'__builtins__': {}, 'bitreplicate16': _bitreplicate16}, env) & MASK + + +def run_lines(line, env, *, sym=None): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.one('s_bitreplicate_b64_b32', line) + out = dict(env) + for stmt in stage.lines: + m = re.fullmatch(r'(\w+) = (.*);', stmt) + assert m, stmt + assert m.group(1) != 'scc', 'SCC must remain unchanged: %s' % stmt + out[m.group(1)] = eval_u32(m.group(2), out) + return out, stage + + +def stage_refused(stage, line, needle=''): + try: + stage.one('s_bitreplicate_b64_b32', line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +VALUES = ( + 0x00000000, 0xffffffff, 0x00000001, 0x80000000, 0x00008000, 0x00010000, + 0x55555555, 0xaaaaaaaa, 0x12345678, 0x9abcdef0, 0x00ff00ff, 0xff00ff00, +) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOP1 bytes via G.decode(). + decoded = [ + G.decode(sop1(0x3b, 8, 6))[0][3], + G.decode(sop1(0x3b, 4, 4))[0][3], + G.decode(sop1(0x3b, 4, 193))[0][3], + G.decode(sop1(0x3b, 4, 255, lit=0x12345678))[0][3], + G.decode(sop1(0x3b, 4, 125))[0][3], + ] + check('decode s_bitreplicate_b64_b32 disjoint', decoded[0] == 's_bitreplicate_b64_b32 s[8:9], s6') + check('decode s_bitreplicate_b64_b32 aliased', decoded[1] == 's_bitreplicate_b64_b32 s[4:5], s4') + check('decode s_bitreplicate_b64_b32 inline -1', decoded[2] == 's_bitreplicate_b64_b32 s[4:5], -1') + check('decode s_bitreplicate_b64_b32 literal', decoded[3] == 's_bitreplicate_b64_b32 s[4:5], 0x12345678') + check('decode s_bitreplicate_b64_b32 null', decoded[4] == 's_bitreplicate_b64_b32 s[4:5], null') + + # 2. Disjoint and aliased (s[4:5], s4 and s[4:5], s5) evaluation (SCC untouched). + disjoint_ok = True + alias_lo_ok = True + alias_hi_ok = True + for val in VALUES: + want = ref_bitreplicate(val) + out_d, _ = run_lines('s_bitreplicate_b64_b32 s[8:9], s6', {'s6': val}) + if (out_d['s8'], out_d['s9']) != want: + disjoint_ok = False + out_l, _ = run_lines('s_bitreplicate_b64_b32 s[4:5], s4', {'s4': val, 's5': 0xdeadbeef}) + if (out_l['s4'], out_l['s5']) != want: + alias_lo_ok = False + out_h, _ = run_lines('s_bitreplicate_b64_b32 s[4:5], s5', {'s4': 0xdeadbeef, 's5': val}) + if (out_h['s4'], out_h['s5']) != want: + alias_hi_ok = False + check('disjoint SGPR (%d cases)' % len(VALUES), disjoint_ok) + check('aliased s[4:5], s4 (%d cases)' % len(VALUES), alias_lo_ok) + check('aliased s[4:5], s5 (%d cases)' % len(VALUES), alias_hi_ok) + + # 3. Constant folding (inline, literal, null, const-tracked SGPR). + for val in (0, 1, 64, -1, -16, 0x12345678): + want = ref_bitreplicate(val) + tok = hex(val) if val > 64 else str(val) + out, st = run_lines('s_bitreplicate_b64_b32 s[4:5], %s' % tok, {}) + check('const %s folds' % tok, + (out['s4'], out['s5']) == want and st.sym.get(4) == ('const', want[0]) + and st.sym.get(5) == ('const', want[1])) + out_n, st_n = run_lines('s_bitreplicate_b64_b32 s[4:5], null', {}) + check('null folds to (0, 0)', (out_n['s4'], out_n['s5']) == (0, 0) and st_n.sym.get(4) == ('const', 0)) + out_cs, st_cs = run_lines('s_bitreplicate_b64_b32 s[4:5], s6', {}, sym={6: ('const', 0x00018001)}) + want_cs = ref_bitreplicate(0x00018001) + check('const-tracked SGPR folds', (out_cs['s4'], out_cs['s5']) == want_cs and st_cs.sym.get(5) == ('const', want_cs[1])) + + # 4. Uniformity tracking. + s = Probe() + s.varying_s = {6} + s.scc_uniform = True + s.one('s_bitreplicate_b64_b32', 's_bitreplicate_b64_b32 s[4:5], s6') + check('varying source taints s4 and s5', 4 in s.varying_s and 5 in s.varying_s) + s = Probe() + s.varying_s = {4, 5} + s.scc_uniform = True + s.one('s_bitreplicate_b64_b32', 's_bitreplicate_b64_b32 s[4:5], s6') + check('uniform source clears varying on s4 and s5', 4 not in s.varying_s and 5 not in s.varying_s) + + # 5. Refusals (arity, modifiers, lane masks, mask_high, descriptors, invalid register classes/alignment). + check('1 operand refused', stage_refused(Probe(), 's_bitreplicate_b64_b32 s[4:5]', 'expected 2 unmodified')) + check('3 operands refused', stage_refused(Probe(), 's_bitreplicate_b64_b32 s[4:5], s6, s7', 'expected 2 unmodified')) + check('modifier refused', stage_refused(Probe(), 's_bitreplicate_b64_b32 s[4:5], s6 clamp', 'expected 2 unmodified')) + for operands in ('exec, s6', 'vcc, s6', 's[4:5], exec_lo', 's[4:5], vcc_lo'): + check('%s lane mask refused' % operands, stage_refused(Probe(), 's_bitreplicate_b64_b32 %s' % operands)) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], s6'), + (13, None, 's[12:13], s6'), + (None, 13, 's[12:13], s6'), + (12, None, 's[4:5], s12'), + (None, 13, 's[4:5], s13'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s tracked mask refused' % operands, + stage_refused(p, 's_bitreplicate_b64_b32 %s' % operands, 'lane mask')) + for bad_dst in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', 'm0'): + check('bad dst %s refused' % bad_dst, + stage_refused(Probe(), 's_bitreplicate_b64_b32 %s, s6' % bad_dst, 'destination')) + for bad_src in ('v0', 's[6:7]', 's106', '1.0', 'm0', 'src_scc'): + check('bad src %s refused' % bad_src, + stage_refused(Probe(), 's_bitreplicate_b64_b32 s[4:5], %s' % bad_src, 'source')) + p_desc = Probe() + p_desc.sym[6] = ('descriptor', 0) + check('descriptor sym on s6 refused', + stage_refused(p_desc, 's_bitreplicate_b64_b32 s[4:5], s6', 'descriptor data')) + + # 6. On-demand helper emission: emitted when used dynamically, omitted when unused. + _, ps_hlsl = translate_ps() + check('bitreplicate16 helper emitted on demand', 'uint bitreplicate16(uint x)' in ps_hlsl) + zero = [(0, 0, 0)] * 4 + unused_ps = G.Pipeline(vs_words(zero), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('bitreplicate16 helper omitted when unused', 'bitreplicate16' not in unused_ps) + + # 7. Unlowered control: removing op_s_bitreplicate_b64_b32 from Stage restores refusals. + saved = G.Stage.op_s_bitreplicate_b64_b32 + try: + delattr(G.Stage, 'op_s_bitreplicate_b64_b32') + check('unlowered s_bitreplicate_b64_b32 refused', + stage_refused(Probe(), 's_bitreplicate_b64_b32 s[8:9], s6')) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + G.Stage.op_s_bitreplicate_b64_b32 = saved + + +# Keep bits [14:11] and [30:27] clear so replicated bits [29:22] are 0 and XOR 0x3f800000 stays normal IEEE-754. +GPU_VECTORS = ( + ('bit0_and_bit16', 0x00010001), + ('bit15_and_31', 0x80008000), + ('low_pattern', 0x000005a3), + ('high_pattern', 0x05a30000), + ('mixed_pattern', 0x01230456), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_bitreplicate_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, val in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(val) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + r0, r1 = ref_bitreplicate(val) + raw_exp = ( + r0 ^ DRAW_TRANSPORT_XOR, + r1 ^ DRAW_TRANSPORT_XOR, + r0 ^ DRAW_TRANSPORT_XOR, + r1 ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_bitreplicate controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_bitreplicate draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_bitreplicate_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_bitset64_check.py b/tests/startup_gfx2hlsl_s_bitset64_check.py new file mode 100644 index 0000000000..59df39b6c4 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitset64_check.py @@ -0,0 +1,383 @@ +"""64-bit scalar bit set/clear (s_bitset0_b64, s_bitset1_b64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOP1 decode, value evaluation, aliasing, constant folding, uniformity, + refusal and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per (lo, hi, index) triple and compare the four result words + +RDNA 2 ISA, SOP1: + S_BITSET0_B64 s[D:D+1], S0: D.u64[S0.u[5:0]] = 0; SCC unchanged. + S_BITSET1_B64 s[D:D+1], S0: D.u64[S0.u[5:0]] = 1; SCC unchanged. + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads (lo, hi, index) +into s[4:5]/s6 and s[8:9]/s6 with SOP1 literal moves, runs s_bitset0_b64 on s[4:5] and s_bitset1_b64 on s[8:9], +XORs the resulting four 32-bit words with 0x3f800000 for normal IEEE-754 transport into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +SOP1_OPCODES = { + 's_bitset0_b64': 0x1c, + 's_bitset1_b64': 0x1e, +} + +# Keep exported lanes away from NaN/subnormal bit patterns on float render targets. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def sop1(op, sdst, ssrc0, lit=None): + """Encode one synthetic gfx1013 SOP1 32-bit (or 64-bit with literal) instruction.""" + w0 = (0b101111101 << 23) | (sdst << 16) | (op << 8) | ssrc0 + out = struct.pack('<I', w0) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def sop1_mov_lit(sdst, val): + return sop1(0x03, sdst, 255, lit=val) + + +def s_xor_lit(sdst, ssrc0, lit): + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + return struct.pack('<I', 0x7e000000 | (vdst << 17) | (0x01 << 9) | ssrc) + + +def ps_words(lo, hi, idx): + """Synthetic gfx1013 pixel stage running s_bitset0_b64 and s_bitset1_b64 on dynamic SGPRs.""" + # Use a non-const SGPR for idx by xoring two literals into s6 so the translator emits dynamic HLSL. + body = b''.join([ + sop1_mov_lit(4, lo), + sop1_mov_lit(5, hi), + sop1_mov_lit(8, lo), + sop1_mov_lit(9, hi), + sop1_mov_lit(6, idx), + s_xor_lit(6, 6, 0), # keeps s6 runtime (clears const sym) + sop1(0x1c, 4, 6), # s_bitset0_b64 s[4:5], s6 + sop1(0x1e, 8, 6), # s_bitset1_b64 s[8:9], s6 + s_xor_lit(4, 4, DRAW_TRANSPORT_XOR), + s_xor_lit(5, 5, DRAW_TRANSPORT_XOR), + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 4), + v_mov_b32_from_sgpr(13, 5), + v_mov_b32_from_sgpr(14, 8), + v_mov_b32_from_sgpr(15, 9), + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(lo=0x00000001, hi=0x00000020, idx=37): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(lo, hi, idx), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_bitset64(clear, lo, hi, idx): + """Independent 64-bit integer reference returning (new_lo, new_hi).""" + val = ((hi & MASK) << 32) | (lo & MASK) + bit = 1 << (idx & 63) + res = (val & ~bit) if clear else (val | bit) + return res & MASK, (res >> 32) & MASK + + +def eval_u32_expr(expr, env): + """Evaluate a translated HLSL uint expression (with optional ternaries) in Python.""" + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + while '?' in text: + q = text.index('?') + depth = 0 + start = q - 1 + while start >= 0: + if text[start] == ')': + depth += 1 + elif text[start] == '(': + if depth == 0: + break + depth -= 1 + start -= 1 + depth = 0 + colon = -1 + end = q + 1 + while end < len(text): + if text[end] == '(': + depth += 1 + elif text[end] == ')': + if depth == 0: + break + depth -= 1 + elif text[end] == ':' and depth == 0 and colon == -1: + colon = end + end += 1 + cond = text[start + 1:q].strip() + yes = text[q + 1:colon].strip() + no = text[colon + 1:end].strip() + text = text[:start] + ('((%s) if (%s) else (%s))' % (yes, cond, no)) + text[end + 1:] + return eval(text, {'__builtins__': {}}, env) & MASK + + +def run_lines(line, env, *, sym=None): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.one(line.split(' ', 1)[0], line) + out = dict(env) + for stmt in stage.lines: + m = re.fullmatch(r'(\w+) = (.*);', stmt) + assert m, stmt + assert m.group(1) != 'scc', 'SCC must remain unchanged: %s' % stmt + out[m.group(1)] = eval_u32_expr(m.group(2), out) + return out, stage + + +def stage_refused(stage, mnemonic, line, needle=''): + try: + stage.one(mnemonic, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +PAIRS = ( + (0x00000000, 0x00000000), + (0xffffffff, 0xffffffff), + (0x00000001, 0x80000000), + (0x80000000, 0x00000001), + (0xffffffff, 0x00000000), + (0x00000000, 0xffffffff), + (0x55555555, 0xaaaaaaaa), + (0x12345678, 0x9abcdef0), +) +INDEXES = (0, 1, 5, 31, 32, 33, 37, 63, 64, 65, 96, 127, 0xffffffe5) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOP1 bytes via G.decode(). + decoded = [ + G.decode(sop1(0x1c, 4, 6))[0][3], + G.decode(sop1(0x1e, 4, 128 + 37))[0][3], + G.decode(sop1(0x1c, 4, 255, lit=0x25))[0][3], + G.decode(sop1(0x1e, 4, 125))[0][3], + ] + check('decode s_bitset0_b64 reg/reg', decoded[0] == 's_bitset0_b64 s[4:5], s6') + check('decode s_bitset1_b64 reg/imm37', decoded[1] == 's_bitset1_b64 s[4:5], 37') + check('decode s_bitset0_b64 literal', decoded[2] == 's_bitset0_b64 s[4:5], 0x25') + check('decode s_bitset1_b64 null', decoded[3] == 's_bitset1_b64 s[4:5], null') + + # 2. Exhaustive SGPR pair + register/immediate index grid (SCC untouched). + grid_ok = True + for mnemonic, clear in (('s_bitset0_b64', True), ('s_bitset1_b64', False)): + for lo, hi in PAIRS: + for idx in INDEXES: + want_lo, want_hi = ref_bitset64(clear, lo, hi, idx) + for line, env in ( + ('%s s[4:5], s6' % mnemonic, {'s4': lo, 's5': hi, 's6': idx}), + ('%s s[4:5], %d' % (mnemonic, idx), {'s4': lo, 's5': hi}), + ): + out, _ = run_lines(line, env) + if (out['s4'], out['s5']) != (want_lo, want_hi): + grid_ok = False + print('MISMATCH %s lo=%#x hi=%#x idx=%#x got=(%#x,%#x) want=(%#x,%#x)' % ( + line, lo, hi, idx, out['s4'], out['s5'], want_lo, want_hi)) + check('SGPR pair grid (%d cases)' % (2 * len(PAIRS) * len(INDEXES) * 2), grid_ok) + + # 3. Aliasing: S0 == s4 (low word of destination pair) and S0 == s5 (high word of destination pair). + alias_ok = True + for mnemonic, clear in (('s_bitset0_b64', True), ('s_bitset1_b64', False)): + for lo, hi in ((0, 0), (35, 0), (35, 0xffffffff), (5, 0x12345678), (63, 0x80000000), (0, 37), (0xffffffff, 5)): + out_lo, _ = run_lines('%s s[4:5], s4' % mnemonic, {'s4': lo, 's5': hi}) + if (out_lo['s4'], out_lo['s5']) != ref_bitset64(clear, lo, hi, lo): + alias_ok = False + out_hi, _ = run_lines('%s s[4:5], s5' % mnemonic, {'s4': lo, 's5': hi}) + if (out_hi['s4'], out_hi['s5']) != ref_bitset64(clear, lo, hi, hi): + alias_ok = False + check('aliasing s[4:5], s4 and s[4:5], s5 preserve original index', alias_ok) + + # 4. Constant folding (imm, null, and const-tracked SGPR index) leaves the untouched half's sym intact. + for mnemonic, clear in (('s_bitset0_b64', True), ('s_bitset1_b64', False)): + out_lo, st_lo = run_lines('%s s[4:5], 5' % mnemonic, {'s4': 0x20, 's5': 0x77}, + sym={4: ('const', 0x20), 5: ('const', 0x77)}) + want_lo, want_hi = ref_bitset64(clear, 0x20, 0x77, 5) + check('%s folds const low word (bit 5)' % mnemonic, + st_lo.sym.get(4) == ('const', want_lo) and st_lo.sym.get(5) == ('const', 0x77) + and out_lo['s4'] == want_lo and len(st_lo.lines) == 1) + out_hi, st_hi = run_lines('%s s[4:5], 37' % mnemonic, {'s4': 0x77, 's5': 0x20}, + sym={4: ('const', 0x77), 5: ('const', 0x20)}) + want_lo, want_hi = ref_bitset64(clear, 0x77, 0x20, 37) + check('%s folds const high word (bit 37)' % mnemonic, + st_hi.sym.get(4) == ('const', 0x77) and st_hi.sym.get(5) == ('const', want_hi) + and out_hi['s5'] == want_hi and len(st_hi.lines) == 1) + out_null, _ = run_lines('%s s[4:5], null' % mnemonic, {'s4': 1, 's5': 0x10}) + check('%s null targets bit 0' % mnemonic, (out_null['s4'], out_null['s5']) == ref_bitset64(clear, 1, 0x10, 0)) + out_cs, st_cs = run_lines('%s s[4:5], s6' % mnemonic, {'s4': 0, 's5': 0}, + sym={4: ('const', 0), 5: ('const', 0), 6: ('const', 63)}) + want_lo, want_hi = ref_bitset64(clear, 0, 0, 63) + check('%s folds const SGPR index 63' % mnemonic, + st_cs.sym.get(5) == ('const', want_hi) and out_cs['s5'] == want_hi) + + # 5. Uniformity tracking (varying index taints both halves; varying half stays varying). + for mnemonic in ('s_bitset0_b64', 's_bitset1_b64'): + s = Probe() + s.varying_s = {6} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], s6' % mnemonic) + check('%s varying index taints s4 and s5' % mnemonic, 4 in s.varying_s and 5 in s.varying_s) + s = Probe() + s.varying_s = {4} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], 37' % mnemonic) + check('%s immediate bit 37 keeps s5 uniform when only s4 varies' % mnemonic, + 4 in s.varying_s and 5 not in s.varying_s) + + # 6. Refusals (arity, modifiers, lane masks, mask_high, descriptors, invalid register classes/alignment). + for mnemonic in ('s_bitset0_b64', 's_bitset1_b64'): + check('%s 1 operand refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5]' % mnemonic, 'expected 2 unmodified')) + check('%s 3 operands refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6, s7' % mnemonic, 'expected 2 unmodified')) + check('%s modifier refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6 clamp' % mnemonic, 'expected 2 unmodified')) + for operands in ('exec, 1', 'vcc, 1', 's[4:5], exec_lo', 's[4:5], vcc_lo'): + check('%s %s lane mask refused' % (mnemonic, operands), + stage_refused(Probe(), mnemonic, '%s %s' % (mnemonic, operands))) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], 1'), + (13, None, 's[12:13], 1'), + (None, 13, 's[12:13], 1'), + (12, None, 's[4:5], s12'), + (None, 13, 's[4:5], s13'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s %s tracked mask refused' % (mnemonic, operands), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for bad_dst in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', 'm0'): + check('%s bad dst %s refused' % (mnemonic, bad_dst), + stage_refused(Probe(), mnemonic, '%s %s, s6' % (mnemonic, bad_dst), 'destination')) + for bad_src in ('v0', 's[6:7]', 's106', '1.0', 'm0', 'src_scc'): + check('%s bad src %s refused' % (mnemonic, bad_src), + stage_refused(Probe(), mnemonic, '%s s[4:5], %s' % (mnemonic, bad_src), 'source')) + for sym_reg, operands in ((4, 's[4:5], 1'), (5, 's[4:5], 1'), (6, 's[4:5], s6')): + p = Probe() + p.sym[sym_reg] = ('descriptor', 0) + check('%s descriptor sym on s%d refused' % (mnemonic, sym_reg), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'descriptor data')) + + # 7. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', '& 32u' in ps_hlsl and '& 31u' in ps_hlsl) + + # 8. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_s_bitset0_b64', 'op_s_bitset1_b64')} + try: + for name in saved: + delattr(G.Stage, name) + for mnemonic in ('s_bitset0_b64', 's_bitset1_b64'): + check('unlowered %s refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s6' % mnemonic)) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + # 9. Mutation / negative controls. + check('mutation: dropping bit 5 diverges on bit 37', + ref_bitset64(False, 0, 0, 37) != ref_bitset64(False, 0, 0, 37 & 31)) + check('mutation: swapping clear/set diverges', + ref_bitset64(True, 0, 0x20, 37) != ref_bitset64(False, 0, 0x20, 37)) + + +GPU_VECTORS = ( + # Use small low/high patterns whose XOR with 0x3f800000 stays a normal IEEE-754 float (exponent 0x7f). + # (label, lo, hi, idx) + ('lo_bit0', 0x00000001, 0x00000000, 0), + ('lo_bit20', 0x00100000, 0x00000000, 20), + ('hi_bit32', 0x00000000, 0x00000001, 32), + ('hi_bit37', 0x00000000, 0x00000020, 37), + ('hi_bit52', 0x00000000, 0x00100000, 52), + ('wrap_101', 0x00000000, 0x00000020, 101), # 101 & 63 == 37 + ('wrap_64', 0x00000001, 0x00000000, 64), # 64 & 63 == 0 +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_bitset64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, lo, hi, idx in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(lo, hi, idx) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + c0, c1 = ref_bitset64(True, lo, hi, idx) + s0, s1 = ref_bitset64(False, lo, hi, idx) + raw_exp = ( + c0 ^ DRAW_TRANSPORT_XOR, + c1 ^ DRAW_TRANSPORT_XOR, + s0 ^ DRAW_TRANSPORT_XOR, + s1 ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + # Negative control: deliberately wrong expected word must fail draw(). + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_bitset64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_bitset64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_bitset64_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_bitset_check.py b/tests/startup_gfx2hlsl_s_bitset_check.py new file mode 100644 index 0000000000..baa873e0ca --- /dev/null +++ b/tests/startup_gfx2hlsl_s_bitset_check.py @@ -0,0 +1,155 @@ +"""s_bitset0_b32 and s_bitset1_b32 in tools/startup/gfx2hlsl.py (#2023 Item J). + +usage: startup_gfx2hlsl_s_bitset_check.py + +RDNA 2 ISA SOP1: S_BITSET0_B32 clears bit S0[4:0] of D in place; S_BITSET1_B32 sets that bit. +SCC is unchanged. The reference is plain Python integer arithmetic; the translated text is evaluated +on the CPU. Lane-mask and descriptor-bearing destinations or sources are refused. A mutation that +drops the bit update must disagree with the reference. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x80000001, 0x00010020, 0x55555555, 0xaaaaaaaa, 0x12345678) +INDEXES = (0, 1, 5, 16, 31, 32, 33, 0x21, 0xffffffe5) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def ref(clear, word, index): + bit = 1 << (index & 31) + return (word & ~bit if clear else word | bit) & MASK + + +for clear, name in ((True, 's_bitset0_b32'), (False, 's_bitset1_b32')): + bad = None + lines, _ = translate(sop1(name, 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + for index in INDEXES: + out = run(lines, {'s1': index, 's3': word, 'scc': SCC_UNSET}) + want = (ref(clear, word, index), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (name, hex(word), hex(index), (out['s3'], out['scc']), want) + break + if bad: + break + check('%s SGPR bit index' % name, bad is None, str(bad)) + + bad = None + for word in WORDS: + for index in (0, 1, 5, 16, 31, 32, 0x21): + stage = Probe() + try: + stage.one(name, '%s s3, %d' % (name, index)) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'s3': word, 'scc': SCC_UNSET}) + want = (ref(clear, word, index), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), hex(index), (out['s3'], out['scc']), want) + break + if bad: + break + check('%s immediate bit index' % name, bad is None, str(bad)) + + # Constant destination folds when the bit index is a known immediate (ssrc 128+5 = 5). + lines, sym = translate(sop1(name, 3, 128 + 5), sym={3: ('const', 0x100)}) + want_const = (0x100 & ~(1 << 5) if clear else 0x100 | (1 << 5)) & MASK + check('%s folds a constant destination with an immediate bit' % name, + lines == ['s3 = 0x%08xu;' % want_const] and sym.get(3) == ('const', want_const), + str((lines, sym.get(3), want_const))) + + refused = [translate(sop1(name, d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1), (125, 1))] + check('%s refuses lane-mask and discard destinations/sources' % name, + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(3) + try: + stage.one(name, '%s s3, 1' % name) + check('%s refuses a tracked lane-mask destination' % name, False, stage.lines) + except G.Unsupported as error: + check('%s refuses a tracked lane-mask destination' % name, 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[3] = ('desc', ('root', 0), 0, 0) + try: + stage.one(name, '%s s3, 1' % name) + check('%s refuses a descriptor destination' % name, False, stage.lines) + except G.Unsupported as error: + check('%s refuses a descriptor destination' % name, 'desc' in str(error), str(error)) + +# Negative control: drop the bit update from the emitted expression; the CPU evaluation must diverge. +stage = Probe() +stage.one('s_bitset1_b32', 's_bitset1_b32 s3, s1') +mutated = [re.sub(r'\(s3 \| \(1u << \(s1 & 31\)\)\)', 's3', stage.lines[0])] +assert mutated != stage.lines, stage.lines +out_ok = run(stage.lines, {'s1': 5, 's3': 0x100, 'scc': 0}) +out_bad = run(mutated, {'s1': 5, 's3': 0x100, 'scc': 0}) +check('mutation that drops the set diverges', out_ok['s3'] == 0x120 and out_bad['s3'] == 0x100, + str((out_ok['s3'], out_bad['s3']))) + +if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) +print('all ok') diff --git a/tests/startup_gfx2hlsl_s_brev64_check.py b/tests/startup_gfx2hlsl_s_brev64_check.py new file mode 100644 index 0000000000..af7c57f113 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_brev64_check.py @@ -0,0 +1,329 @@ +"""64-bit scalar bit-reverse (s_brev_b64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOP1 decode, value evaluation, in-place aliasing, constant folding, + uniformity, refusal and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per 64-bit input and compare the four result words + +RDNA 2 ISA, SOP1 (0x0c): + S_BREV_B64 s[D:D+1], S0: D.u64[63:0] = S0.u64[0:63]; SCC unchanged. + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads a 64-bit value +into runtime SGPR pairs s[4:5] and s[6:7], runs disjoint s_brev_b64 s[8:9], s[4:5] and in-place +s_brev_b64 s[6:7], s[6:7], XORs the four output words with 0x3f800000 for normal IEEE-754 transport into +v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +# Keep exported lanes in normal IEEE-754 float range on float render targets. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def sop1(op, sdst, ssrc0, lit=None): + """Encode one synthetic gfx1013 SOP1 32-bit (or 64-bit with literal) instruction.""" + w0 = (0b101111101 << 23) | (sdst << 16) | (op << 8) | ssrc0 + out = struct.pack('<I', w0) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def sop1_mov_lit(sdst, val): + return sop1(0x03, sdst, 255, lit=val) + + +def s_xor_lit(sdst, ssrc0, lit): + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + return struct.pack('<I', 0x7e000000 | (vdst << 17) | (0x01 << 9) | ssrc) + + +def ps_words(lo, hi): + """Synthetic gfx1013 pixel stage exercising disjoint and in-place s_brev_b64.""" + body = b''.join([ + sop1_mov_lit(4, lo), + sop1_mov_lit(5, hi), + s_xor_lit(4, 4, 0), # clear const sym so s_brev_b64 emits runtime reversebits + s_xor_lit(5, 5, 0), + sop1_mov_lit(6, lo), + sop1_mov_lit(7, hi), + s_xor_lit(6, 6, 0), + s_xor_lit(7, 7, 0), + sop1(0x0c, 8, 4), # disjoint: s_brev_b64 s[8:9], s[4:5] + sop1(0x0c, 6, 6), # in-place: s_brev_b64 s[6:7], s[6:7] + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + s_xor_lit(6, 6, DRAW_TRANSPORT_XOR), + s_xor_lit(7, 7, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 8), + v_mov_b32_from_sgpr(13, 9), + v_mov_b32_from_sgpr(14, 6), + v_mov_b32_from_sgpr(15, 7), + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(lo=0x80000001, hi=0x00000001): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(lo, hi), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_brev64(lo, hi): + """Independent 64-bit bit-string reference returning (rev_lo, rev_hi).""" + bits = format(((hi & MASK) << 32) | (lo & MASK), '064b')[::-1] + val = int(bits, 2) + return val & MASK, (val >> 32) & MASK + + +def _reversebits(v): + return int('{:032b}'.format(v & MASK)[::-1], 2) + + +def eval_u32(expr, env): + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + return eval(text, {'__builtins__': {}, 'reversebits': _reversebits}, env) & MASK + + +def run_lines(line, env, *, sym=None): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.one('s_brev_b64', line) + out = dict(env) + for stmt in stage.lines: + body = stmt.strip() + if body.startswith('{') and body.endswith('}'): + parts = [p.strip() for p in body[1:-1].split(';') if p.strip()] + else: + parts = [body.rstrip(';')] + for p in parts: + m = re.fullmatch(r'(?:uint\s+)?(\w+)\s*=\s*(.*)', p) + assert m, p + assert m.group(1) != 'scc', 'SCC must remain unchanged: %s' % p + out[m.group(1)] = eval_u32(m.group(2), out) + return out, stage + + +def stage_refused(stage, line, needle=''): + try: + stage.one('s_brev_b64', line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +PAIRS = ( + (0x00000000, 0x00000000), + (0xffffffff, 0xffffffff), + (0x00000001, 0x00000000), + (0x00000000, 0x80000000), + (0x80000001, 0x00000001), + (0x12345678, 0x9abcdef0), + (0x55555555, 0xaaaaaaaa), + (0x00ff00ff, 0xff00ff00), +) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOP1 bytes via G.decode(). + decoded = [ + G.decode(sop1(0x0c, 8, 4))[0][3], + G.decode(sop1(0x0c, 4, 4))[0][3], + G.decode(sop1(0x0c, 4, 193))[0][3], + G.decode(sop1(0x0c, 4, 255, lit=0x80000001))[0][3], + G.decode(sop1(0x0c, 4, 125))[0][3], + ] + check('decode s_brev_b64 disjoint pair', decoded[0] == 's_brev_b64 s[8:9], s[4:5]') + check('decode s_brev_b64 in-place pair', decoded[1] == 's_brev_b64 s[4:5], s[4:5]') + check('decode s_brev_b64 inline -1', decoded[2] == 's_brev_b64 s[4:5], -1') + check('decode s_brev_b64 literal', decoded[3] == 's_brev_b64 s[4:5], 0x80000001') + check('decode s_brev_b64 null', decoded[4] == 's_brev_b64 s[4:5], null') + + # 2. Disjoint and in-place SGPR pair evaluation (SCC untouched). + disjoint_ok = True + inplace_ok = True + for lo, hi in PAIRS: + want = ref_brev64(lo, hi) + out_d, _ = run_lines('s_brev_b64 s[8:9], s[4:5]', {'s4': lo, 's5': hi}) + if (out_d['s8'], out_d['s9']) != want: + disjoint_ok = False + out_i, _ = run_lines('s_brev_b64 s[4:5], s[4:5]', {'s4': lo, 's5': hi}) + if (out_i['s4'], out_i['s5']) != want: + inplace_ok = False + check('disjoint SGPR pair (%d cases)' % len(PAIRS), disjoint_ok) + check('in-place SGPR pair aliasing (%d cases)' % len(PAIRS), inplace_ok) + + # 3. Inline integers (negative sign-extends to 64 bits), 32-bit hex literal (zero-extends), null. + for val in (0, 1, 64, -1, -16): + lo, hi = val & MASK, (val >> 32) & MASK + want = ref_brev64(lo, hi) + out, st = run_lines('s_brev_b64 s[4:5], %d' % val, {}) + check('inline %d folds to %#x, %#x' % (val, want[0], want[1]), + (out['s4'], out['s5']) == want and st.sym.get(4) == ('const', want[0]) + and st.sym.get(5) == ('const', want[1])) + want_lit = ref_brev64(0x80000001, 0) + out_lit, st_lit = run_lines('s_brev_b64 s[4:5], 0x80000001', {}) + check('32-bit hex literal zero-extends to 64 bits', + (out_lit['s4'], out_lit['s5']) == want_lit and st_lit.sym.get(4) == ('const', 0)) + out_null, st_null = run_lines('s_brev_b64 s[4:5], null', {}) + check('null folds to (0, 0)', + (out_null['s4'], out_null['s5']) == (0, 0) and st_null.sym.get(4) == ('const', 0)) + + # 4. Constant-tracked SGPR pair (both halves const, and mixed const + runtime). + want_c = ref_brev64(0x12345678, 0x9abcdef0) + out_c, st_c = run_lines('s_brev_b64 s[4:5], s[4:5]', {}, + sym={4: ('const', 0x12345678), 5: ('const', 0x9abcdef0)}) + check('const-tracked in-place pair folds', + (out_c['s4'], out_c['s5']) == want_c and st_c.sym.get(4) == ('const', want_c[0])) + out_m, st_m = run_lines('s_brev_b64 s[8:9], s[4:5]', {'s5': 0x80000001}, sym={4: ('const', 0x1)}) + check('mixed const lo + runtime hi folds hi output', + (out_m['s8'], out_m['s9']) == ref_brev64(0x1, 0x80000001) and st_m.sym.get(9) == ('const', 0x80000000)) + + # 5. Uniformity tracking (swapping halves swaps uniformity accurately, both disjoint and in-place). + s = Probe() + s.varying_s = {4} + s.scc_uniform = True + s.one('s_brev_b64', 's_brev_b64 s[8:9], s[4:5]') + check('disjoint: varying s4 -> s9 varying, s8 uniform', 8 not in s.varying_s and 9 in s.varying_s) + + s = Probe() + s.varying_s = {4} + s.scc_uniform = True + s.one('s_brev_b64', 's_brev_b64 s[4:5], s[4:5]') + check('in-place: varying s4 -> s5 varying, s4 uniform', 4 not in s.varying_s and 5 in s.varying_s) + + # 6. Refusals (arity, modifiers, lane masks, mask_high, descriptors, invalid register classes/alignment). + check('1 operand refused', stage_refused(Probe(), 's_brev_b64 s[4:5]', 'expected 2 unmodified')) + check('3 operands refused', stage_refused(Probe(), 's_brev_b64 s[4:5], s[6:7], s[8:9]', 'expected 2 unmodified')) + check('modifier refused', stage_refused(Probe(), 's_brev_b64 s[4:5], s[6:7] clamp', 'expected 2 unmodified')) + for operands in ('exec, s[6:7]', 'vcc, s[6:7]', 's[4:5], exec', 's[4:5], vcc'): + check('%s lane mask refused' % operands, stage_refused(Probe(), 's_brev_b64 %s' % operands)) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], s[6:7]'), + (13, None, 's[12:13], s[6:7]'), + (None, 13, 's[12:13], s[6:7]'), + (12, None, 's[4:5], s[12:13]'), + (13, None, 's[4:5], s[12:13]'), + (None, 13, 's[4:5], s[12:13]'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s tracked mask refused' % operands, stage_refused(p, 's_brev_b64 %s' % operands, 'lane mask')) + for bad_dst in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', 'm0'): + check('bad dst %s refused' % bad_dst, stage_refused(Probe(), 's_brev_b64 %s, s[6:7]' % bad_dst, 'destination')) + for bad_src in ('v[0:1]', 's6', 's[7:8]', 's[106:107]', '1.0', 'm0', 'src_scc'): + check('bad src %s refused' % bad_src, stage_refused(Probe(), 's_brev_b64 s[4:5], %s' % bad_src)) + for sym_reg in (6, 7): + p = Probe() + p.sym[sym_reg] = ('descriptor', 0) + check('descriptor sym on s%d refused' % sym_reg, + stage_refused(p, 's_brev_b64 s[4:5], s[6:7]', 'descriptor data')) + + # 7. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', 'reversebits(' in ps_hlsl and '_t0' in ps_hlsl) + + # 8. Unlowered control: removing op_s_brev_b64 from Stage restores refusals. + saved = G.Stage.op_s_brev_b64 + try: + delattr(G.Stage, 'op_s_brev_b64') + check('unlowered s_brev_b64 refused', stage_refused(Probe(), 's_brev_b64 s[8:9], s[4:5]')) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + G.Stage.op_s_brev_b64 = saved + + # 9. Mutation / negative controls. + check('mutation: not swapping halves diverges', ref_brev64(0x1, 0x0) != (0x80000000, 0x0)) + check('mutation: zero-extending -1 diverges', ref_brev64(0xffffffff, 0xffffffff) != ref_brev64(0xffffffff, 0)) + + +# Choose inputs with bits [8:1] clear so reversebits(word) has bits [30:23] == 0, keeping XOR 0x3f800000 normal. +GPU_VECTORS = ( + ('bit0_to_bit63', 0x00000001, 0x00000000), + ('bit63_to_bit0', 0x00000000, 0x80000000), + ('mixed_halves', 0x80000001, 0x12345001), + ('high_bits_only', 0x00000000, 0xf0a00001), + ('both_halves', 0x13579001, 0x2468a000), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_brev64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, lo, hi in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(lo, hi) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + r0, r1 = ref_brev64(lo, hi) + raw_exp = ( + r0 ^ DRAW_TRANSPORT_XOR, + r1 ^ DRAW_TRANSPORT_XOR, + r0 ^ DRAW_TRANSPORT_XOR, + r1 ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_brev64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_brev64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_brev64_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_cmp64_check.py b/tests/startup_gfx2hlsl_s_cmp64_check.py new file mode 100644 index 0000000000..5a48dbd648 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_cmp64_check.py @@ -0,0 +1,368 @@ +"""64-bit scalar equality comparisons (s_cmp_eq_u64, s_cmp_lg_u64) in tools/startup/gfx2hlsl.py. + + (no arguments) SOPC decode, value evaluation, uniformity, refusal and mutation + controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per 64-bit pair and compare the four result words + +RDNA 2 ISA, SOPC: + S_CMP_EQ_U64 S0, S1: SCC = (S0.u64 == S1.u64) + S_CMP_LG_U64 S0, S1: SCC = (S0.u64 != S1.u64) + +The pixel fixture decodes synthetic gfx1013 bytes via G.decode() ONLY (no game data). It loads two 64-bit +values into s[4:5] and s[6:7] with SOP1 literal moves, executes s_cmp_eq_u64 / s_cmp_lg_u64 (pair vs pair, +pair vs sign-extended inline -1, and pair vs zero-extended 32-bit hex literal 0x80000001), materializes each +SCC via s_cselect_b32, XORs with 0x3f800000 for normal IEEE-754 transport into v12..v15, and exports mrt0. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +SOPC_OPCODES = { + 's_cmp_eq_u64': 0x12, + 's_cmp_lg_u64': 0x13, +} + +# XOR 0/1 with 0x3f800000 so exported lanes are normal IEEE-754 floats (1.0 / 1.0 + 1 ULP), never subnormals. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def sopc(op, ssrc0, ssrc1, lit=None): + """Encode one synthetic gfx1013 SOPC 32-bit (or 64-bit with literal) instruction.""" + w0 = 0xbf000000 | (op << 16) | (ssrc1 << 8) | ssrc0 + out = struct.pack('<I', w0) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def sop1_mov_lit(sdst, val): + """Encode SOP1 s_mov_b32 s<sdst>, <32-bit literal> (op 0x03, ssrc0=255).""" + return struct.pack('<2I', (0b101111101 << 23) | (sdst << 16) | (0x03 << 8) | 255, val & MASK) + + +def s_cselect_b32(sdst, ssrc0, ssrc1): + """Encode SOP2 s_cselect_b32 s<sdst>, ssrc0, ssrc1 (op 0x0a).""" + return struct.pack('<I', 0x80000000 | (0x0a << 23) | (sdst << 16) | (ssrc1 << 8) | ssrc0) + + +def s_xor_lit(sdst, ssrc0, lit): + """Encode SOP2 s_xor_b32 s<sdst>, s<ssrc0>, <32-bit literal> (op 0x12, ssrc1=255).""" + return struct.pack('<2I', 0x80000000 | (0x12 << 23) | (sdst << 16) | (255 << 8) | ssrc0, lit & MASK) + + +def v_mov_b32_from_sgpr(vdst, ssrc): + """Encode VOP1 v_mov_b32_e32 v<vdst>, s<ssrc> (op 0x01).""" + return struct.pack('<I', 0x7e000000 | (vdst << 17) | (0x01 << 9) | ssrc) + + +def ps_words(a0, a1, b0, b1): + """Synthetic gfx1013 pixel stage exercising s_cmp_eq_u64 and s_cmp_lg_u64.""" + # Inline integer encodings in RDNA 2: 0 -> 128, 1 -> 129, -1 -> 193, literal -> 255. + body = b''.join([ + sop1_mov_lit(4, a0), # s4 = a0 + sop1_mov_lit(5, a1), # s5 = a1 + sop1_mov_lit(6, b0), # s6 = b0 + sop1_mov_lit(7, b1), # s7 = b1 + sopc(0x12, 4, 6), # s_cmp_eq_u64 s[4:5], s[6:7] + s_cselect_b32(8, 129, 128), # s8 = scc ? 1 : 0 + s_xor_lit(8, 8, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(12, 8), # v12 = (a == b) ^ 0x3f800000 + sopc(0x13, 4, 6), # s_cmp_lg_u64 s[4:5], s[6:7] + s_cselect_b32(9, 129, 128), # s9 = scc ? 1 : 0 + s_xor_lit(9, 9, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(13, 9), # v13 = (a != b) ^ 0x3f800000 + sopc(0x12, 4, 193), # s_cmp_eq_u64 s[4:5], -1 + s_cselect_b32(10, 129, 128), # s10 = scc ? 1 : 0 + s_xor_lit(10, 10, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(14, 10), # v14 = (a == 0xffffffff_ffffffff) ^ 0x3f800000 + sopc(0x12, 4, 255, lit=0x80000001), # s_cmp_eq_u64 s[4:5], 0x80000001 + s_cselect_b32(11, 129, 128), # s11 = scc ? 1 : 0 + s_xor_lit(11, 11, DRAW_TRANSPORT_XOR), + v_mov_b32_from_sgpr(15, 11), # v15 = (a == 0x00000000_80000001) ^ 0x3f800000 + ]) + return PRE_WORDS + body + POST_WORDS + + +def translate_ps(a0=0x00000001, a1=0x00000002, b0=0x00000001, b1=0x00000002): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(a0, a1, b0, b1), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def ref_cmp64(eq, a0, a1, b0, b1): + """Independent 64-bit integer reference for S_CMP_EQ_U64 / S_CMP_LG_U64.""" + a = ((a1 & MASK) << 32) | (a0 & MASK) + b = ((b1 & MASK) << 32) | (b0 & MASK) + return (a == b) if eq else (a != b) + + +def eval_scc_expr(expr, env): + """Evaluate a translated HLSL boolean SCC expression in Python.""" + text = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + text = text.replace('&&', ' and ').replace('||', ' or ') + return bool(eval(text, {'__builtins__': {}}, env)) + + +def run_one(line, env, *, sym=None): + stage = Probe() + if sym: + stage.sym.update(sym) + stage.one(line.split(' ', 1)[0], line) + assert len(stage.lines) == 1, stage.lines + target, _, expr = stage.lines[0].rstrip(';').partition(' = ') + assert target == 'scc', stage.lines + return eval_scc_expr(expr, env), stage + + +def stage_refused(stage, mnemonic, line, needle=''): + try: + stage.one(mnemonic, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS64 = ( + (0x00000000, 0x00000000), + (0x00000001, 0x00000000), + (0x00000000, 0x00000001), + (0xffffffff, 0x00000000), + (0x00000000, 0xffffffff), + (0xffffffff, 0xffffffff), + (0x80000001, 0x00000000), + (0x80000001, 0xffffffff), + (0x12345678, 0x9abcdef0), + (0x12345678, 0x9abcdef1), + (0x12345679, 0x9abcdef0), +) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 SOPC bytes via G.decode(). + decoded = [ + G.decode(sopc(0x12, 4, 6))[0][3], + G.decode(sopc(0x13, 4, 6))[0][3], + G.decode(sopc(0x12, 4, 193))[0][3], + G.decode(sopc(0x13, 255, 6, lit=0x80000001))[0][3], + G.decode(sopc(0x12, 125, 128))[0][3], + ] + check('decode s_cmp_eq_u64 pair/pair', decoded[0] == 's_cmp_eq_u64 s[4:5], s[6:7]') + check('decode s_cmp_lg_u64 pair/pair', decoded[1] == 's_cmp_lg_u64 s[4:5], s[6:7]') + check('decode s_cmp_eq_u64 inline -1', decoded[2] == 's_cmp_eq_u64 s[4:5], -1') + check('decode s_cmp_lg_u64 literal', decoded[3] == 's_cmp_lg_u64 0x80000001, s[6:7]') + check('decode s_cmp_eq_u64 null/0', decoded[4] == 's_cmp_eq_u64 null, 0') + + # 2. Exhaustive SGPR pair x SGPR pair grid (including low-only and high-only mismatches). + grid_ok = True + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + for a0, a1 in WORDS64: + for b0, b1 in WORDS64: + expected = ref_cmp64(eq, a0, a1, b0, b1) + got, _ = run_one('%s s[4:5], s[6:7]' % mnemonic, + {'s4': a0, 's5': a1, 's6': b0, 's7': b1}) + if got != expected: + grid_ok = False + print('MISMATCH %s a=(%#x,%#x) b=(%#x,%#x) got=%s want=%s' % ( + mnemonic, a0, a1, b0, b1, got, expected)) + check('SGPR pair grid (%d cases)' % (2 * len(WORDS64) * len(WORDS64)), grid_ok) + + # 3. Inline integer 64-bit operands (negative values sign-extend to 64 bits). + inline_ok = True + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + for val in (0, 1, 64, -1, -16): + v0, v1 = val & MASK, (val >> 32) & MASK + for a0, a1 in ((v0, v1), (v0, 0), (v0, 0xffffffff), (0, v1)): + got_r, _ = run_one('%s s[4:5], %d' % (mnemonic, val), {'s4': a0, 's5': a1}) + got_l, _ = run_one('%s %d, s[4:5]' % (mnemonic, val), {'s4': a0, 's5': a1}) + want = ref_cmp64(eq, a0, a1, v0, v1) + if got_r != want or got_l != want: + inline_ok = False + check('inline integers sign-extend negative values to 64 bits', inline_ok) + + # 4. 32-bit hex literal zero-extends to 64 bits (hi == 0 even when bit 31 is set). + lit_ok = True + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + for a0, a1 in ((0x80000001, 0), (0x80000001, 0xffffffff), (0x80000000, 0)): + got_r, _ = run_one('%s s[4:5], 0x80000001' % mnemonic, {'s4': a0, 's5': a1}) + got_l, _ = run_one('%s 0x80000001, s[4:5]' % mnemonic, {'s4': a0, 's5': a1}) + want = ref_cmp64(eq, a0, a1, 0x80000001, 0) + if got_r != want or got_l != want: + lit_ok = False + check('32-bit hex literal zero-extends to 64 bits', lit_ok) + + # 5. null operand and const-tracked SGPR pair. + for mnemonic, eq in (('s_cmp_eq_u64', True), ('s_cmp_lg_u64', False)): + got_zero, _ = run_one('%s s[4:5], null' % mnemonic, {'s4': 0, 's5': 0}) + got_hi, _ = run_one('%s null, s[4:5]' % mnemonic, {'s4': 0, 's5': 1}) + check('%s null == 0' % mnemonic, got_zero == eq) + check('%s null != (0, 1)' % mnemonic, got_hi == (not eq)) + got_const, _ = run_one('%s s[4:5], s[6:7]' % mnemonic, {'s5': 0x99, 's6': 0x42, 's7': 0x99}, + sym={4: ('const', 0x42)}) + check('%s const-tracked lo + runtime hi' % mnemonic, got_const == eq) + + # 6. Uniformity tracking across all four registers s4, s5, s6, s7. + for mnemonic in ('s_cmp_eq_u64', 's_cmp_lg_u64'): + s = Probe() + s.varying_s = set() + s.scc_uniform = False + s.one(mnemonic, '%s s[4:5], s[6:7]' % mnemonic) + check('%s uniform inputs -> scc_uniform=True' % mnemonic, s.scc_uniform is True) + for bad_reg in (4, 5, 6, 7): + s = Probe() + s.varying_s = {bad_reg} + s.scc_uniform = True + s.one(mnemonic, '%s s[4:5], s[6:7]' % mnemonic) + check('%s varying s%d -> scc_uniform=False' % (mnemonic, bad_reg), s.scc_uniform is False) + + # 7. Refusals (arity, modifiers, lane masks, mask_high, invalid register classes/alignment). + for mnemonic in ('s_cmp_eq_u64', 's_cmp_lg_u64'): + check('%s 1 operand refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5]' % mnemonic, 'two unmodified operands')) + check('%s 3 operands refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s[6:7], s[8:9]' % mnemonic, 'two unmodified operands')) + check('%s modifier refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s[6:7] clamp' % mnemonic, 'two unmodified operands')) + for operands in ( + 'exec, s[6:7]', 'exec_lo, s[6:7]', 'vcc, s[6:7]', 'vcc_lo, s[6:7]', + 's[4:5], exec', 's[4:5], exec_lo', 's[4:5], vcc', 's[4:5], vcc_lo', + ): + check('%s %s lane mask refused' % (mnemonic, operands), + stage_refused(Probe(), mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for mask_reg, high_reg, operands in ( + (12, None, 's[12:13], s[6:7]'), + (13, None, 's[12:13], s[6:7]'), + (None, 13, 's[12:13], s[6:7]'), + (12, None, 's[4:5], s[12:13]'), + (13, None, 's[4:5], s[12:13]'), + (None, 13, 's[4:5], s[12:13]'), + ): + p = Probe() + if mask_reg is not None: + p.masks = {mask_reg} + if high_reg is not None: + p.mask_high = {high_reg} + check('%s %s tracked mask refused' % (mnemonic, operands), + stage_refused(p, mnemonic, '%s %s' % (mnemonic, operands), 'lane mask')) + for bad_op in ('v[0:1]', 's4', 's[5:6]', 's[106:107]', '1.0', 'm0', 'src_scc'): + check('%s bad S0 %s refused' % (mnemonic, bad_op), + stage_refused(Probe(), mnemonic, '%s %s, s[6:7]' % (mnemonic, bad_op))) + check('%s bad S1 %s refused' % (mnemonic, bad_op), + stage_refused(Probe(), mnemonic, '%s s[4:5], %s' % (mnemonic, bad_op))) + + # 8. Full synthetic pixel pipeline translates cleanly through G.Pipeline(). + _, ps_hlsl = translate_ps() + check('synthetic pixel pipeline translates', '&&' in ps_hlsl and '||' in ps_hlsl) + + # 9. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_s_cmp_eq_u64', 'op_s_cmp_lg_u64')} + try: + for name in saved: + delattr(G.Stage, name) + for mnemonic in ('s_cmp_eq_u64', 's_cmp_lg_u64'): + check('unlowered %s refused' % mnemonic, + stage_refused(Probe(), mnemonic, '%s s[4:5], s[6:7]' % mnemonic)) + try: + translate_ps() + except G.Unsupported: + check('unlowered synthetic pipeline refused', True) + else: + check('unlowered synthetic pipeline refused', False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + # 10. Mutation / negative controls: prove our inputs distinguish common bugs. + check('mutation: ignoring high word diverges on (1,0) vs (1,1)', + ref_cmp64(True, 1, 0, 1, 1) != (1 == 1)) + check('mutation: ignoring low word diverges on (0,1) vs (1,1)', + ref_cmp64(True, 0, 1, 1, 1) != (1 == 1)) + check('mutation: using && instead of || for lg diverges on high-only mismatch', + ref_cmp64(False, 1, 0, 1, 1) != ((1 != 1) and (0 != 1))) + check('mutation: zero-extending -1 diverges on (0xffffffff, 0xffffffff)', + ref_cmp64(True, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff) + != ref_cmp64(True, 0xffffffff, 0xffffffff, 0xffffffff, 0)) + check('mutation: sign-extending 0x80000001 diverges on (0x80000001, 0)', + ref_cmp64(True, 0x80000001, 0, 0x80000001, 0) + != ref_cmp64(True, 0x80000001, 0, 0x80000001, 0xffffffff)) + + +GPU_VECTORS = ( + # (label, a0, a1, b0, b1) + ('equal_pair', 0x12345678, 0x9abcdef0, 0x12345678, 0x9abcdef0), + ('diff_lo_only', 0x12345678, 0x9abcdef0, 0x12345679, 0x9abcdef0), + ('diff_hi_only', 0x12345678, 0x9abcdef0, 0x12345678, 0x9abcdef1), + ('match_inline_m1', 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000), + ('m1_hi_zero_only', 0xffffffff, 0x00000000, 0xffffffff, 0x00000000), + ('match_lit_zext', 0x80000001, 0x00000000, 0x00000000, 0x00000000), + ('lit_hi_all_ones', 0x80000001, 0xffffffff, 0x80000001, 0xffffffff), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_s_cmp64_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for label, a0, a1, b0, b1 in GPU_VECTORS: + vs_hlsl, ps_hlsl = translate_ps(a0, a1, b0, b1) + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = ( + (1 if ref_cmp64(True, a0, a1, b0, b1) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_cmp64(False, a0, a1, b0, b1) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_cmp64(True, a0, a1, 0xffffffff, 0xffffffff) else 0) ^ DRAW_TRANSPORT_XOR, + (1 if ref_cmp64(True, a0, a1, 0x80000001, 0x00000000) else 0) ^ DRAW_TRANSPORT_XOR, + ) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + # Negative control: deliberately wrong expected word must fail draw(). + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('s_cmp64 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('s_cmp64 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_s_cmp64_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_s_ff0_check.py b/tests/startup_gfx2hlsl_s_ff0_check.py new file mode 100644 index 0000000000..34e0e283b1 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_ff0_check.py @@ -0,0 +1,159 @@ +"""s_ff0_i32_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_ff0_check.py + +RDNA 2 ISA SOP1: S_FF0_I32_B32 returns the least-significant zero-bit index +(0xffffffff if every bit is set). SCC is unchanged. Matches pixel_aot / +ff0_i32_b32 (`firstbitlow(~S0)`). Lane masks and descriptor sources are refused. +The reference is plain Python; the translated text is evaluated on the CPU. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0xffffffff, 0xfffffffe, 0x00000000, 0x80000000, 0x7fffffff, 0x55555555, 0x12345678) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + + +def ref_ff0(word): + zeros = (~(word & MASK)) & MASK + return MASK if zeros == 0 else (zeros & -zeros).bit_length() - 1 + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_ff0_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': SCC_UNSET}) + want = (ref_ff0(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_ff0_i32_b32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_ff0_i32_b32', 's_ff0_i32_b32 s3, %d' % word) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': SCC_UNSET}) + want = (ref_ff0(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_ff0_i32_b32 immediate source', bad is None, str(bad)) + + lines, sym = translate(sop1('s_ff0_i32_b32', 3, 1), sym={1: ('const', 0xfffffffe)}) + check('s_ff0_i32_b32 folds a constant source', + lines == ['s3 = 0x00000000u;'] and sym.get(3) == ('const', 0), + str((lines, sym.get(3)))) + + lines, sym = translate(sop1('s_ff0_i32_b32', 3, 1), sym={1: ('const', MASK)}) + check('s_ff0_i32_b32 of all-ones is -1', + lines == ['s3 = 0xffffffffu;'] and sym.get(3) == ('const', MASK), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_ff0_i32_b32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_ff0_i32_b32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_ff0_i32_b32', 's_ff0_i32_b32 s3, s1') + check('s_ff0_i32_b32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_ff0_i32_b32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_ff0_i32_b32', 's_ff0_i32_b32 s3, s1') + check('s_ff0_i32_b32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_ff0_i32_b32 refuses a descriptor source', 'desc' in str(error), str(error)) + + stage = Probe() + stage.one('s_ff0_i32_b32', 's_ff0_i32_b32 s3, s1') + mutated = [re.sub(r'firstbitlow\(~s1\)', 'firstbitlow(s1)', stage.lines[0])] + assert mutated != stage.lines, stage.lines + # firstbitlow(~1) == 1, firstbitlow(1) == 0 + out_ok = run(stage.lines, {'s1': 0x00000001, 'scc': 0}) + out_bad = run(mutated, {'s1': 0x00000001, 'scc': 0}) + check('mutation that drops the complement diverges', + out_ok['s3'] == 1 and out_bad['s3'] == 0, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_s_ff1_check.py b/tests/startup_gfx2hlsl_s_ff1_check.py new file mode 100644 index 0000000000..365a215215 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_ff1_check.py @@ -0,0 +1,401 @@ +"""s_ff1_i32_b32 of a general scalar and s_ff1_i32_b64 immediates + SGPR pairs (#2022 Item F). + +usage: startup_gfx2hlsl_s_ff1_check.py + startup_gfx2hlsl_s_ff1_check.py dispatch <dxc> <offscreen_check> <warp|hardware> + +RDNA 2 ISA SOP1: S_FF1_I32_B32 finds the lowest set bit of a 32-bit word (0xffffffff if zero); +SCC is unchanged. The compute-entry special case on exec_lo still folds to lane 0. Lane masks +and descriptor sources are refused. + +S_FF1_I32_B64 accepts a 32-bit SOP1 literal/inline (ISA zero-extends the high word to 0) and +folds it, and also lowers a live SGPR pair with the same 64-bit firstbitlow scan as the scalar +bit-scan forms. + +With `dispatch`, the b32 lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_pack_absdiff_check). The +reference is plain Python; the translated text is evaluated on the CPU without `dispatch`. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x80000001, 0x00010020, 0x55555555, 0xaaaaaaaa, 0x12345678, 0x10) +# GPU cases from review: prove firstbitlow(0) == 0xffffffff and the named edge bits. +DRAW_B32 = (0x00000000, 0x00000001, 0x80000000, 0x00010000) +# b64 immediates only (hi forced to 0 by zero-extension). hi-nonzero is #2072. +IMMEDIATE_B64 = (0x00000000, 0x00000001, 0x00010000, 0x80000000) +# Live SGPR pair s4:s5 as (lo, hi): both zero, lo only, hi only, both set (lo wins), edge bits in each half. +PAIR_B64 = ((0, 0), (1, 0), (0, 1), (0, 0x80000000), (0, 0x10), (0x80000000, 0xffffffff), (0x00010000, 0x1), + (0xffffffff, 0xffffffff)) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc, lit=None): + word = struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + if lit is not None: + word += struct.pack('<I', lit & MASK) + return word + + +def ff1_32(word): + word &= MASK + return MASK if word == 0 else (word & -word).bit_length() - 1 + + +class Probe(G.Stage): + def __init__(self, kind='vs'): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + self.kind = kind + self.past_entry = False + + +def translate(words, masks=(), sym=None, kind='vs'): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe(kind=kind) + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + # --- s_ff1_i32_b32 of a general SGPR --- + bad = None + lines, _ = translate(sop1('s_ff1_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': SCC_UNSET}) + want = (ff1_32(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_ff1_i32_b32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_ff1_i32_b32', 's_ff1_i32_b32 s3, %d' % word) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': SCC_UNSET}) + want = (ff1_32(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_ff1_i32_b32 immediate source', bad is None, str(bad)) + + # Constant source folds. + lines, sym = translate(sop1('s_ff1_i32_b32', 3, 1), sym={1: ('const', 0x10)}) + check('s_ff1_i32_b32 folds a constant source', + lines == ['s3 = 0x00000004u;'] and sym.get(3) == ('const', 4), + str((lines, sym.get(3)))) + + # firstbitlow of zero is 0xffffffff (HLSL / ISA). + lines, _ = translate(sop1('s_ff1_i32_b32', 3, 1)) + out = run(lines, {'s1': 0, 'scc': SCC_UNSET}) + check('s_ff1_i32_b32 of 0 is 0xffffffff', + out['s3'] == MASK and out['scc'] == SCC_UNSET, + str((out['s3'], out['scc']))) + + # Compute-entry exec_lo still folds to lane 0. + lines, sym = translate(sop1('s_ff1_i32_b32', 5, EXEC_LO), kind='cs') + check('s_ff1_i32_b32 of compute-entry exec_lo folds to 0', + lines == ['s5 = 0u;'] and sym.get(5) == ('const', 0), + str((lines, sym.get(5)))) + + # Outside compute, or past entry, exec_lo is refused. + stage = Probe(kind='vs') + try: + stage.one('s_ff1_i32_b32', 's_ff1_i32_b32 s5, exec_lo') + check('s_ff1_i32_b32 of exec_lo outside compute is refused', False, stage.lines) + except G.Unsupported as error: + check('s_ff1_i32_b32 of exec_lo outside compute is refused', 'exec_lo' in str(error), str(error)) + + # --- s_ff1_i32_b64 of a 32-bit immediate (zero-extended; hi = 0) --- + bad = None + for word in IMMEDIATE_B64: + lines, sym = translate(sop1('s_ff1_i32_b64', 3, 255, word)) + if lines[0].startswith('refused'): + bad = ('refused %s for %s' % (lines[0], hex(word)),) + break + want = ff1_32(word) + if lines != ['s3 = 0x%08xu;' % want] or sym.get(3) != ('const', want): + bad = (hex(word), lines, sym.get(3), want) + break + check('s_ff1_i32_b64 folds a zero-extended immediate', bad is None, str(bad)) + + lines, _ = translate(sop1('s_ff1_i32_b64', 3, 255, 0)) + check('s_ff1_i32_b64 of immediate 0 is 0xffffffff', + lines == ['s3 = 0xffffffffu;'], + str(lines)) + + # Inline constant 0 (ssrc 128) is the same zero-extend rule. + lines, sym = translate(sop1('s_ff1_i32_b64', 3, 128)) + check('s_ff1_i32_b64 folds inline 0', + lines == ['s3 = 0xffffffffu;'] and sym.get(3) == ('const', MASK), + str((lines, sym.get(3)))) + + # SGPR pairs use the same 64-bit firstbitlow scan as #2072 / SCALAR_BITS. + lines, _ = translate(sop1('s_ff1_i32_b64', 3, 4)) + check('s_ff1_i32_b64 of a live SGPR pair emits firstbitlow over the pair', + (not lines[0].startswith('refused:') + and 'firstbitlow' in lines[0] + and 's4' in lines[0] + and 's5' in lines[0]), + str(lines)) + + lines, _ = translate(sop1('s_ff1_i32_b64', 3, 4), + sym={4: ('const', 0), 5: ('const', 0x10)}) + # Known consts substitute into the scan text (hi half at +32); still not refused. + check('s_ff1_i32_b64 of a constant SGPR pair still scans both halves', + (not lines[0].startswith('refused:') + and 'firstbitlow' in lines[0] + and '32u' in lines[0] + and '0x00000010u' in lines[0]), + str(lines)) + + # Refusals: lane masks and descriptors. + refused = [translate(sop1('s_ff1_i32_b32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_ff1_i32_b32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_ff1_i32_b32', 's_ff1_i32_b32 s3, s1') + check('s_ff1_i32_b32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_ff1_i32_b32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_ff1_i32_b32', 's_ff1_i32_b32 s3, s1') + check('s_ff1_i32_b32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_ff1_i32_b32 refuses a descriptor source', 'desc' in str(error), str(error)) + + # Negative control: replace firstbitlow with a constant; evaluation must diverge. + stage = Probe() + stage.one('s_ff1_i32_b32', 's_ff1_i32_b32 s3, s1') + mutated = [re.sub(r'firstbitlow\(s1\)', '0u', stage.lines[0])] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0x10, 'scc': 0}) + out_bad = run(mutated, {'s1': 0x10, 'scc': 0}) + check('mutation that drops firstbitlow diverges', + out_ok['s3'] == 4 and out_bad['s3'] == 0, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_b32(dxc, runner, adapter, cases, directory): + """Translate s_ff1_i32_b32 once; feed each case through a UAV and read the result back.""" + lines, _ = translate(sop1('s_ff1_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_ff1_b32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def ff1_64(lo, hi): + """CPU reference for s_ff1_i32_b64: lowest set bit of the pair, -1 when both words are zero.""" + lo, hi = lo & MASK, hi & MASK + return ff1_32(lo) if lo else (32 + ff1_32(hi) if hi else MASK) + + +def dispatch_b64_pairs(dxc, runner, adapter, cases, directory): + """Translate s_ff1_i32_b64 of the live pair s4:s5 once; feed each (lo, hi) through a UAV and read it back.""" + lines, _ = translate(sop1('s_ff1_i32_b64', 3, 4)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(2 * len(cases))) + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, (lo, hi) in enumerate(cases): + hlsl.extend(( + ' {', + ' uint s4 = data.Load(%d) ^ %s;' % (8 * i, '%#010xu' % (fill[2 * i] ^ lo)), + ' uint s5 = data.Load(%d) ^ %s;' % (8 * i + 4, '%#010xu' % (fill[2 * i + 1] ^ hi)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % (4 * (len(fill) + i))) + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_ff1_b64_pair' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def dispatch_b64_immediates(dxc, runner, adapter, cases, directory): + """Store the folded b64-immediate results; proves the zero-extend fold on the adapter.""" + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + stage = Probe() + stage.one('s_ff1_i32_b64', 's_ff1_i32_b64 s3, %#x' % word) + hlsl.extend(( + ' {', + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in stage.lines) + hlsl.append(' data.Store(%d, s3);' % (4 * i)) + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_ff1_b64_imm' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + return actual[:word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + directory = Path(tmp) + got = dispatch_b32(dxc, runner, adapter, DRAW_B32, directory) + for i, word in enumerate(DRAW_B32): + want = ff1_32(word) + check('dispatch s_ff1_i32_b32 %#010x' % word, got[i] == want, + 'got %#x want %#x' % (got[i], want)) + # Negative control: a wrong expected word for 0 must not match. + check('dispatch proves firstbitlow(0) is 0xffffffff', got[0] == MASK, hex(got[0])) + + got64 = dispatch_b64_immediates(dxc, runner, adapter, IMMEDIATE_B64, directory) + for i, word in enumerate(IMMEDIATE_B64): + want = ff1_32(word) # hi = 0 by zero-extension + check('dispatch s_ff1_i32_b64 immediate %#010x (hi=0)' % word, got64[i] == want, + 'got %#x want %#x' % (got64[i], want)) + gotpair = dispatch_b64_pairs(dxc, runner, adapter, PAIR_B64, directory) + for i, (lo, hi) in enumerate(PAIR_B64): + want = ff1_64(lo, hi) + check('dispatch s_ff1_i32_b64 pair hi=%#010x lo=%#010x' % (hi, lo), gotpair[i] == want, + 'got %#x want %#x' % (gotpair[i], want)) + # Negative control: a lo-first scan that ignored the high word would answer 0xffffffff here. + check('dispatch scans the high word when lo is zero', gotpair[PAIR_B64.index((0, 0x10))] == 36, + hex(gotpair[PAIR_B64.index((0, 0x10))])) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_s_flbit_check.py b/tests/startup_gfx2hlsl_s_flbit_check.py new file mode 100644 index 0000000000..ee0b67850f --- /dev/null +++ b/tests/startup_gfx2hlsl_s_flbit_check.py @@ -0,0 +1,229 @@ +"""s_flbit_i32_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_flbit_check.py + startup_gfx2hlsl_s_flbit_check.py dispatch <dxc> <offscreen_check> <warp|hardware> + +RDNA 2 ISA SOP1: S_FLBIT_I32_B32 returns the number of leading zero bits +(0xffffffff if the word is zero). SCC is unchanged. Matches pixel_aot / +dpp_ffbh_u32. Lane masks and descriptor sources are refused. The reference is +plain Python; the translated text is evaluated on the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_s_abs_check). Cases cover zero (0xffffffff), bit 0, bit 31 and +a mid-word bit so firstbithigh is exercised on the device. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0x00000001, 0x80000000, 0xffffffff, 0x00010020, 0x55555555, 0x12345678) +DRAW = (0x00000000, 0x00000001, 0x80000000, 0x00010000) +SCC_UNSET = 2 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + + +def ref_flbit(word): + word &= MASK + return MASK if word == 0 else 31 - (word.bit_length() - 1) + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_flbit_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': SCC_UNSET}) + want = (ref_flbit(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_flbit_i32_b32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, %d' % word) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': SCC_UNSET}) + want = (ref_flbit(word), SCC_UNSET) + if (out['s3'], out['scc']) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_flbit_i32_b32 immediate source', bad is None, str(bad)) + + lines, sym = translate(sop1('s_flbit_i32_b32', 3, 1), sym={1: ('const', 0x10)}) + # 0x10 bit_length=5 -> firstbithigh=4 -> 31-4=27 + check('s_flbit_i32_b32 folds a constant source', + lines == ['s3 = 0x0000001bu;'] and sym.get(3) == ('const', 0x1b), + str((lines, sym.get(3)))) + + lines, sym = translate(sop1('s_flbit_i32_b32', 3, 1), sym={1: ('const', 0)}) + check('s_flbit_i32_b32 of zero is -1', + lines == ['s3 = 0xffffffffu;'] and sym.get(3) == ('const', MASK), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_flbit_i32_b32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_flbit_i32_b32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, s1') + check('s_flbit_i32_b32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_flbit_i32_b32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, s1') + check('s_flbit_i32_b32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_flbit_i32_b32 refuses a descriptor source', 'desc' in str(error), str(error)) + + stage = Probe() + stage.one('s_flbit_i32_b32', 's_flbit_i32_b32 s3, s1') + mutated = [re.sub(r'31u - firstbithigh\(s1\)', 'firstbithigh(s1)', stage.lines[0])] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0x10, 'scc': 0}) + out_bad = run(mutated, {'s1': 0x10, 'scc': 0}) + check('mutation that drops the 31-offset diverges', + out_ok['s3'] == 27 and out_bad['s3'] == 4, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_flbit(dxc, runner, adapter, cases, directory): + """Translate s_flbit_i32_b32 once; feed each case through a UAV and read the result back.""" + lines, _ = translate(sop1('s_flbit_i32_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_flbit_i32_b32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + got = dispatch_flbit(dxc, runner, adapter, DRAW, Path(tmp)) + for i, word in enumerate(DRAW): + want = ref_flbit(word) + check('dispatch s_flbit_i32_b32 %#010x' % word, got[i] == want, + 'got %#x want %#x' % (got[i], want)) + check('dispatch proves flbit(0) is 0xffffffff', got[0] == MASK, hex(got[0])) + check('dispatch flbit(0x80000000) is 0', got[2] == 0, hex(got[2])) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_s_quadmask_b64_check.py b/tests/startup_gfx2hlsl_s_quadmask_b64_check.py new file mode 100644 index 0000000000..ff92fa5aec --- /dev/null +++ b/tests/startup_gfx2hlsl_s_quadmask_b64_check.py @@ -0,0 +1,173 @@ +"""s_quadmask_b64 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_quadmask_b64_check.py + +RDNA 2 ISA SOP1: each output bit is the OR of one four-bit group of the 64-bit +source. Sixteen nibbles collapse into bits 0..15 of D.lo; D.hi is 0. +SCC = (D.lo | D.hi) != 0. Matches pixel_aot. Negative integer inline constants +extend to 64 bits and 32-bit literals zero-extend. Lane masks and descriptor sources are refused. +The reference is plain Python; the translated text is evaluated on the CPU. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +# (lo, hi) pairs: null, low nibble, high bit of low word, high-word nibble, both halves, all ones. +PAIRS = ( + (0x00000000, 0x00000000), + (0x0000000f, 0x00000000), + (0x80000000, 0x00000000), + (0x00000000, 0x0000000f), + (0x000f0000, 0x00f00000), + (0xffffffff, 0xffffffff), + (0x12345678, 0x9abcdef0), + (0xf0f0f0f0, 0x0f0f0f0f), +) +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc, literal=None): + words = struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + if literal is not None: + words += struct.pack('<I', literal & MASK) + return words + + +def quadmask32(word): + return sum((((word >> (4 * group)) & 0xf) != 0) << group for group in range(8)) + + +def quadmask64(lo, hi): + return quadmask32(lo) | (quadmask32(hi) << 8) + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_quadmask_b64', 4, 2)) + assert lines and not lines[0].startswith('refused'), lines + for lo, hi in PAIRS: + out = run(lines, {'s2': lo, 's3': hi, 'scc': 0}) + want_lo = quadmask64(lo, hi) + want = (want_lo, 0, int(want_lo != 0)) + if (out['s4'], out['s5'], int(bool(out['scc']))) != want: + bad = ((hex(lo), hex(hi)), (out['s4'], out['s5'], out['scc']), want) + break + check('s_quadmask_b64 SGPR pair source', bad is None, str(bad)) + + bad = None + for word in (0x00000000, 0x0000000f, 0x80000000, 0x000f0000, 0xffffffff, 0x12345678): + lines, _ = translate(sop1('s_quadmask_b64', 4, 255, word)) + if lines[0].startswith('refused'): + bad = ('refused %s for %s' % (lines[0], hex(word)),) + break + out = run(lines, {'scc': 0}) + want_lo = quadmask64(word, 0) + if (out['s4'], out['s5'], int(bool(out['scc']))) != (want_lo, 0, int(want_lo != 0)): + bad = (hex(word), (out['s4'], out['s5'], out['scc']), (want_lo, 0, int(want_lo != 0))) + break + check('s_quadmask_b64 zero-extended literal', bad is None, str(bad)) + + # SSRC 193 and 208 decode as the inline integers -1 and -16. The same + # low DWORD encoded as a literal must leave the upper eight result bits clear. + for ssrc, want in ((193, 0xffff), (208, 0xfffe)): + lines, _ = translate(sop1('s_quadmask_b64', 4, ssrc)) + out = run(lines, {'scc': 0}) + actual = (out['s4'], out['s5'], int(bool(out['scc']))) + check('s_quadmask_b64 negative inline SSRC %d' % ssrc, actual == (want, 0, 1), str(actual)) + + lines, sym = translate(sop1('s_quadmask_b64', 4, 2), + sym={2: ('const', 0x000f0000), 3: ('const', 0x00f00000)}) + # nibble 4 of lo -> bit 4; nibble 5 of hi -> bit 8+5 = bit 13 + want = quadmask64(0x000f0000, 0x00f00000) + check('s_quadmask_b64 folds a constant pair', + lines[0].startswith('s4 = 0x%08xu;' % want) + and any(line.startswith('s5 = 0u;') or line.startswith('s5 = 0x00000000u;') for line in lines) + and sym.get(4) == ('const', want) + and sym.get(5) == ('const', 0), + str((lines, sym.get(4), sym.get(5), want))) + + refused = [] + for words, masks, sym in ( + (sop1('s_quadmask_b64', VCC_LO, 2), (), None), + (sop1('s_quadmask_b64', 4, VCC_LO), (), None), + (sop1('s_quadmask_b64', 4, 2), (2,), None), + (sop1('s_quadmask_b64', 4, 2), (), {2: ('desc', 0, 0, 0)}), + (sop1('s_quadmask_b64', 3, 2), (), None), # odd destination + (sop1('s_quadmask_b64', 4, 1), (), None), # odd source + ): + lines, _ = translate(words, masks=masks, sym=sym) + refused.append(lines[0]) + check('s_quadmask_b64 refuses lane masks, descriptors, and odd pairs', + all(r.startswith('refused:') for r in refused), str(refused)) + + # Negative control: leave the high-word nibble bits unshifted (<< 0 instead of << 8). + lines, _ = translate(sop1('s_quadmask_b64', 4, 2)) + mutated = [lines[0].replace('<< 8u', '<< 0u', 1)] + lines[1:] + diverged = False + for lo, hi in ((0x00000000, 0x0000000f), (0x000f0000, 0x00f00000)): + good = run(lines, {'s2': lo, 's3': hi, 'scc': 0})['s4'] + bad_out = run(mutated, {'s2': lo, 's3': hi, 'scc': 0})['s4'] + if good != bad_out: + diverged = True + break + check('mutation that drops the high-word shift diverges', diverged, str(mutated[0])) + + +if __name__ == '__main__': + controls() + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') diff --git a/tests/startup_gfx2hlsl_s_quadmask_check.py b/tests/startup_gfx2hlsl_s_quadmask_check.py new file mode 100644 index 0000000000..b1c80d6f72 --- /dev/null +++ b/tests/startup_gfx2hlsl_s_quadmask_check.py @@ -0,0 +1,244 @@ +"""s_quadmask_b32 in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_s_quadmask_check.py + startup_gfx2hlsl_s_quadmask_check.py dispatch <dxc> <offscreen_check> <warp|hardware> + +RDNA 2 ISA SOP1: each output bit is the OR of one four-bit group of S0 (8-bit +result). SCC = (D != 0). Matches pixel_aot. Lane masks and descriptor sources +are refused. The reference is plain Python; the translated text is evaluated on +the CPU. + +With `dispatch`, the lowering runs as a compute shader on the adapter (D3D12 UAV +readback via offscreen_check, same pattern as startup_gfx2hlsl_s_ff1_check / +startup_gfx2hlsl_s_abs_check). Each case stores D, SCC, and an SCC-dependent +branch token so the nibble collapse and nonzero SCC test are exercised on device. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +SOP1 = {name: op for op, (name, _) in D.SOP1_OPS.items()} +WORDS = (0x00000000, 0xffffffff, 0x00000001, 0x80000000, 0x11111111, 0x000f0000, 0x12345678, 0xf0f0f0f0) +# GPU cases: zero (SCC clear), low nibble, high bit, mid nibble-only. +DRAW = (0x00000000, 0x0000000f, 0x80000000, 0x000f0000) +SCC_BRANCH_TAKEN = 0x00a11ced +SCC_BRANCH_NOT = 0x00dead00 +VCC_LO, EXEC_LO = 106, 126 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def sop1(name, sdst, ssrc): + return struct.pack('<I', (0b101111101 << 23) | (sdst << 16) | (SOP1[name] << 8) | ssrc) + + +def quadmask32(word): + return sum((((word >> (4 * group)) & 0xf) != 0) << group for group in range(8)) + + +class Probe(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def translate(words, masks=(), sym=None): + decoded = G.decode(words) + assert len(decoded) == 1 and decoded[0][1] == len(words), decoded + stage = Probe() + stage.masks = set(masks) + if sym: + stage.sym.update(sym) + try: + stage.one(decoded[0][2], decoded[0][3]) + except G.Unsupported as error: + stage.lines = ['refused: %s' % error] + return stage.lines, stage.sym + + +def run(lines, env): + env = dict(env) + for line in lines: + m = re.fullmatch(r'(\w+) = (.*);', line) + assert m, line + env[m.group(1)] = Expr(m.group(2)).run(env)[0] + return env + + +def controls(): + bad = None + lines, _ = translate(sop1('s_quadmask_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + for word in WORDS: + out = run(lines, {'s1': word, 'scc': 0}) + want = (quadmask32(word), int(quadmask32(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_quadmask_b32 SGPR source', bad is None, str(bad)) + + bad = None + for word in WORDS: + stage = Probe() + try: + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, %d' % word) + except G.Unsupported as error: + bad = ('refused %s' % error,) + break + out = run(stage.lines, {'scc': 0}) + want = (quadmask32(word), int(quadmask32(word) != 0)) + if (out['s3'], int(bool(out['scc']))) != want: + bad = (hex(word), (out['s3'], out['scc']), want) + break + check('s_quadmask_b32 immediate source', bad is None, str(bad)) + + # 0x000f0000 -> nibble 4 set -> bit 4 -> 0x10 + lines, sym = translate(sop1('s_quadmask_b32', 3, 1), sym={1: ('const', 0x000f0000)}) + check('s_quadmask_b32 folds a constant source', + lines[0].startswith('s3 = 0x00000010u;') and sym.get(3) == ('const', 0x10) + and any(l.startswith('scc = ') for l in lines), + str((lines, sym.get(3)))) + + refused = [translate(sop1('s_quadmask_b32', d, s))[0][0] for d, s in ( + (3, VCC_LO), (3, EXEC_LO), (VCC_LO, 1), (EXEC_LO, 1))] + check('s_quadmask_b32 refuses lane-mask destinations/sources', + all(r.startswith('refused: ') for r in refused), str(refused)) + + stage = Probe() + stage.masks.add(1) + try: + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, s1') + check('s_quadmask_b32 refuses a tracked lane-mask source', False, stage.lines) + except G.Unsupported as error: + check('s_quadmask_b32 refuses a tracked lane-mask source', 'lane mask' in str(error), str(error)) + + stage = Probe() + stage.sym[1] = ('desc', ('root', 0), 0, 0) + try: + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, s1') + check('s_quadmask_b32 refuses a descriptor source', False, stage.lines) + except G.Unsupported as error: + check('s_quadmask_b32 refuses a descriptor source', 'desc' in str(error), str(error)) + + # Negative control: drop the first nibble contribution; must diverge. + stage = Probe() + stage.one('s_quadmask_b32', 's_quadmask_b32 s3, s1') + mutated = [re.sub(r'\(\(s1 & 0xfu\) != 0u \? 1u : 0u\)', '0u', stage.lines[0], count=1)] + assert mutated != stage.lines, stage.lines + out_ok = run(stage.lines, {'s1': 0x0000000f, 'scc': 0}) + out_bad = run([mutated[0]] + stage.lines[1:], {'s1': 0x0000000f, 'scc': 0}) + check('mutation that drops the first nibble bit diverges', + out_ok['s3'] == 1 and out_bad['s3'] == 0, + str((out_ok['s3'], out_bad['s3']))) + + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('all ok') + + +def dispatch_quadmask(dxc, runner, adapter, cases, directory): + """Translate s_quadmask_b32 once; feed each case through a UAV and read D, SCC, and a branch token.""" + lines, _ = translate(sop1('s_quadmask_b32', 3, 1)) + assert lines and not lines[0].startswith('refused'), lines + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(len(cases))) + result_width = 3 + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, word in enumerate(cases): + dst_byte = 4 * (len(fill) + result_width * i) + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %s;' % (4 * i, '%#010xu' % (fill[i] ^ word)), + ' uint s3;', + ' bool scc = true;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % dst_byte) + hlsl.append(' data.Store(%d, uint(scc));' % (dst_byte + 4)) + hlsl.append(' if (scc) {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_TAKEN)) + hlsl.append(' } else {') + hlsl.append(' data.Store(%d, %#010xu);' % (dst_byte + 8, SCC_BRANCH_NOT)) + hlsl.append(' }') + hlsl.append(' }') + hlsl.append('}') + + src, cso, output = (directory / ('s_quadmask_b32' + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or 'DXC exited with %d' % compile_result.returncode) + word_count = len(fill) + result_width * len(cases) + dump_words = (word_count + 3) // 4 * 4 + run_result = subprocess.run( + [runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run_result.stdout, end='') + if run_result.returncode == 77: + sys.exit(77) + if run_result.returncode or run_result.stderr: + raise AssertionError(run_result.stderr or 'raw UAV dump exited with %d' % run_result.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:len(fill)] == fill, 'operand region changed: %s' % (actual[:len(fill)],) + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + controls() + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + got = dispatch_quadmask(dxc, runner, adapter, DRAW, Path(tmp)) + for i, word in enumerate(DRAW): + result = quadmask32(word) + scc_v = int(result != 0) + branch = SCC_BRANCH_TAKEN if scc_v else SCC_BRANCH_NOT + base = 3 * i + label = 'dispatch s_quadmask_b32 %#010x' % word + check('%s result' % label, got[base] == result, + 'got %#x want %#x' % (got[base], result)) + check('%s SCC' % label, got[base + 1] == scc_v, + 'got %#x want %#x' % (got[base + 1], scc_v)) + check('%s SCC branch' % label, got[base + 2] == branch, + 'got %#x want %#x' % (got[base + 2], branch)) + check('dispatch quadmask(0) clears SCC', + got[1] == 0 and got[2] == SCC_BRANCH_NOT, + str((got[1], got[2]))) + check('dispatch quadmask(0x000f0000) is 0x10', got[3 * 3] == 0x10, hex(got[3 * 3])) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) diff --git a/tests/startup_gfx2hlsl_sad_check.py b/tests/startup_gfx2hlsl_sad_check.py index f89588c73c..09d63fe62c 100644 --- a/tests/startup_gfx2hlsl_sad_check.py +++ b/tests/startup_gfx2hlsl_sad_check.py @@ -178,8 +178,10 @@ def mut_sad_u32(a, b, c): # ---- 32-bit HLSL expression evaluator (supports uint/int, abs(), and sad_u* helpers) ------------------------- -TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||[-+*&|^~!<>?:(),])') -LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] +# `&&` and the `true`/`false` literals are what the bool `masked` argument of the shared sad4_u8 helper needs +# (tests/startup_gfx2hlsl_sad_hi_msad_check.py); no existing sad_u* helper uses them. +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||&&|[-+*&|^~!<>?:(),])') +LEVELS = [['&&'], ['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] class HlslExpr: @@ -217,6 +219,8 @@ def binary(self, level): return node def unary(self): + if self.peek() in ('true', 'false'): + return ('bool', self.take() == 'true') token = self.take() if token in ('~', '-', '!'): return ('u' + token, self.unary()) @@ -239,6 +243,8 @@ def unary(self): def run(self, env, node=None): node = node or self.tree kind = node[0] + if kind == 'bool': + return int(node[1]), False if kind == 'num': return node[1] & MASK, node[2] if kind == 'var': @@ -260,6 +266,8 @@ def run(self, env, node=None): return int({'==': x == y, '!=': x != y, '<': x < y, '>': x > y, '<=': x <= y, '>=': x >= y}[kind]), True if kind == '||': return int(bool(a or b)), True + if kind == '&&': + return int(bool(a) and bool(b)), True return {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b}[kind] & MASK, both def call(self, name, args): diff --git a/tests/startup_gfx2hlsl_sad_hi_msad_check.py b/tests/startup_gfx2hlsl_sad_hi_msad_check.py new file mode 100644 index 0000000000..bf9ec1f1ec --- /dev/null +++ b/tests/startup_gfx2hlsl_sad_hi_msad_check.py @@ -0,0 +1,346 @@ +"""High-half and masked unsigned sum-of-absolute-differences in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls: on-demand helpers, value evaluation against the + tools/pixel_aot.py formulas, the zero-src1-byte and 2^32 carry cases, and + refusals; pure Python + +`v_sad_hi_u8` (VOP3A opcode 0x15b, 347) and `v_msad_u8` (0x171, 369) are lowered like `v_sad_u8`, but the reference +is the AOT table in `tools/pixel_aot.py` so the two translators agree: + + "sad_hi_u8": (3, "(sad4_u8({0}, {1}, false) << 16u) + {2}"), + "msad_u8": (3, "sad4_u8({0}, {1}, true) + {2}"), + +where `sad4_u8(a, b, masked)` sums ABSDIFF over the four byte lanes and, when masked, leaves out each byte lane whose +src1 byte is zero ("Components where the reference value in S1 are zero are not included in the sum"). Both results +are modulo 2^32. The fixture decodes synthetic gfx1013 VOP3A bytes via G.decode() only (no game data) and evaluates +the emitted HLSL with the evaluator of tests/startup_gfx2hlsl_sad_check.py. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + refused, + vs_words, + words_text, +) +from startup_gfx2hlsl_sad_check import HlslExpr, vop3a # noqa: E402 + +OPCODES = { + 'v_sad_hi_u8': 0x15b, + 'v_msad_u8': 0x171, +} + +# The helper names the two instructions ask Pipeline.common() for. +HELPERS = { + 'v_sad_hi_u8': 'sad_hi_u8', + 'v_msad_u8': 'msad_u8', +} + +BODY_WORDS = { + op: b''.join(vop3a(code, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) + for op, code in OPCODES.items() +} +# The unchanged v_sad_u8 body of tests/startup_gfx2hlsl_sad_check.py, used only for the no-regression text check. +BODY_WORDS_U8 = b''.join(vop3a(0x15a, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +# ---- the AOT reference (tools/pixel_aot.py SAD FORMS), evaluated in Python ------------------------------------ +def sad4_u8(a, b, masked): + """Sums |x - y| over the four byte lanes; a masked lane with a zero src1 byte contributes nothing.""" + total = 0 + for shift in (0, 8, 16, 24): + x, y = (a >> shift) & 0xff, (b >> shift) & 0xff + if masked and y == 0: + continue + total += abs(x - y) + return total + + +# The two formula strings above, with {0} = a, {1} = b, {2} = c and the 32-bit wraparound of the destination. +AOT_REFERENCE = { + 'v_sad_hi_u8': lambda a, b, c: ((sad4_u8(a, b, False) << 16) + c) & MASK, + 'v_msad_u8': lambda a, b, c: (sad4_u8(a, b, True) + c) & MASK, +} + +# Word grids with every interesting byte boundary. 1,728 grid triples in total; src1 = 0 and the words with zero +# bytes exercise the masking rule on msad_u8, and S2 = 0xffffffff / 0xfffffc04 exercise the << 16 + S2 wrap. +U8_WORDS = ( + 0x00000000, 0x01020304, 0x04030201, 0x7f80ff00, 0x807f00ff, + 0x00010000, 0x0000ffff, 0x7fffffff, 0x80000000, 0xffffffff, + 0x00ff00ff, 0xff00ff00, +) +U8_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xfffffc04, 0xffffffff) +GRID = {op: [(a, b, c) for a in U8_WORDS for b in U8_WORDS for c in U8_ADDENDS] for op in OPCODES} + +# Explicit cases with hand-computed results: (a, b, c, v_sad_hi_u8, v_msad_u8). The msad_u8 entries are where the +# skip-zero-src1-byte rule changes the sum; the carry rows are where (sum << 16) + S2 wraps 2^32. +CASES = [ + # normal: byte lane 3 differs by 0xe0 and the others match; both forms add c unshifted (msad does not shift). + (0x10203040, 0xf0203040, 5, 0x00e00005, 0x000000e5), + # every src1 byte is zero: v_msad_u8 adds only c, v_sad_hi_u8 keeps all four lanes. + (0x01020304, 0x00000000, 5, 0x000a0005, 0x00000005), + # lanes 0, 2 and 3 are skipped and lane 1 contributes |0x30 - 0x20| = 0x10. + (0x10203040, 0x00002000, 0, 0x00800000, 0x00000010), + # b = 0x000000ff: lane 0 matches and contributes nothing, lanes 1 to 3 are skipped (each would add 0xff). + (0xffffffff, 0x000000ff, 0, 0x02fd0000, 0x00000000), + # 1020 << 16 = 0x03fc0000; adding 0xffffffff wraps 2^32. msad skips every lane and adds c. + (0xffffffff, 0x00000000, 0xffffffff, 0x03fbffff, 0xffffffff), + # (0xfe << 16) + 0xffffffff wraps as well; lane 3 is the only lane not skipped by msad (0xfe + 0xffffffff wraps). + (0xff000000, 0x01000000, 0xffffffff, 0x00fdffff, 0x000000fd), + # The addend of the v_sad_u8 carry control; msad adds it to a skipped-lane sum of zero. + (0xffffffff, 0x00000000, 0xfffffc04, 0x03fbfc04, 0xfffffc04), +] + +# The emitted helper text, pinned exactly (the same style as the inlined sad_u8 helper: a single return statement). +SAD4_U8_HELPER = ( + 'uint sad4_u8(uint a, uint b, bool masked) {' + ' return (masked && ((b & 0xffu) == 0u) ? 0u : uint(abs(int(a & 0xffu) - int(b & 0xffu))))' + ' + (masked && (((b >> 8) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu))))' + ' + (masked && (((b >> 16) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu))))' + ' + (masked && (((b >> 24) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu)))); }') +EXPECTED_HELPER = { + 'v_sad_hi_u8': 'uint sad_hi_u8(uint a, uint b, uint c) { return (sad4_u8(a, b, false) << 16u) + c; }', + 'v_msad_u8': 'uint msad_u8(uint a, uint b, uint c) { return sad4_u8(a, b, true) + c; }', +} + +# The unchanged inline helper of the existing v_sad_u8 lowering, which must stay byte for byte as it was. +SAD_U8_HELPER = ( + 'uint sad_u8(uint a, uint b, uint c) {' + ' return uint(abs(int(a & 0xffu) - int(b & 0xffu)))' + ' + uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu)))' + ' + uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu)))' + ' + uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu))) + c; }') + + +def translate(op): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + return pipe, pipe.hlsl_ps() + + +def extract_helpers(hlsl_text): + """Parse emitted helpers into 32-bit evaluators. sad4_u8 has the bool `masked` argument of the AOT helper.""" + helpers = {} + m = re.search(r'^uint sad4_u8\(uint a, uint b, bool masked\) \{ return (.*); \}$', hlsl_text, re.M) + if m: + expr = HlslExpr(m.group(1)) + helpers['sad4_u8'] = lambda a, b, masked, e=expr: e.run({'a': a, 'b': b, 'masked': 1 if masked else 0})[0] + for name in ('sad_hi_u8', 'msad_u8'): + m = re.search(r'^uint %s\(uint a, uint b, uint c\) \{ return (.*); \}$' % name, hlsl_text, re.M) + if m: + expr = HlslExpr(m.group(1), helpers) + helpers[name] = lambda a, b, c, e=expr: e.run({'a': a, 'b': b, 'c': c})[0] + return helpers + + +def lane_evaluators(hlsl_text): + helpers = extract_helpers(hlsl_text) + found = re.findall(r'^\s*v(1[2-5]) = (.*);$', hlsl_text, re.M) + assert [r for r, _ in found] == ['12', '13', '14', '15'], found + return helpers, [HlslExpr(rhs, helpers) for _, rhs in found] + + +def eval_lane(expr, lane, triple): + a, b, c = triple + return expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b, 'v%d' % (8 + lane): c})[0] + + +def mentions(hlsl_text, name): + """True when `name` is defined or called in the text, without matching another name's suffix (msad_u8/sad_u8).""" + return re.search(r'(?<![A-Za-z0-9_])%s\(' % re.escape(name), hlsl_text) is not None + + +def controls(): + # 1. On-demand helpers: none without a SAD op, and the existing v_sad_u8 lowering is unchanged (it keeps its + # inlined four-term helper and must not pull in the shared sad4_u8 helper). + base_pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + POST_WORDS, root_blob()) + base_text = base_pipe.hlsl_ps() + base_pipe.hlsl_vs() + check('on-demand: baseline pipeline without v_sad_* emits no sad4_u8/sad_hi_u8/msad_u8 helper', + not any(mentions(base_text, h) for h in ('sad4_u8', 'sad_hi_u8', 'msad_u8'))) + + u8_pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + BODY_WORDS_U8 + POST_WORDS, root_blob()) + u8_text = u8_pipe.hlsl_ps() + check('existing v_sad_u8: helper text and call sites are unchanged and no new SAD helper is emitted', + SAD_U8_HELPER in u8_text and 'v12 = sad_u8(v0, v4, v8);' in u8_text + and not any(mentions(u8_text, h) for h in ('sad4_u8', 'sad_hi_u8', 'msad_u8'))) + + for op, helper in HELPERS.items(): + pipe, text = translate(op) + helpers, exprs = lane_evaluators(text) + + # 1a. Four lane calls in the emitted HLSL. + found = re.findall(r'^\s*v(1[2-5]) = %s\(v(\d+), v(\d+), v(\d+)\);$' % helper, text, re.M) + check('%s: four lane calls emitted through %s' % (op, helper), + found == [('12', '0', '4', '8'), ('13', '1', '5', '9'), + ('14', '2', '6', '10'), ('15', '3', '7', '11')]) + + # 1b. Value-level evaluation of the emitted HLSL against the AOT formula over 864 edge/grid triples. + grid = GRID[op] + mismatch = next(((i % 4, triple, eval_lane(exprs[i % 4], i % 4, triple), AOT_REFERENCE[op](*triple)) + for i, triple in enumerate(grid) + if eval_lane(exprs[i % 4], i % 4, triple) != AOT_REFERENCE[op](*triple)), None) + check('%s: emitted HLSL matches the AOT formula on %d edge/grid triples (first mismatch: %r)' + % (op, len(grid), mismatch), mismatch is None) + + # 1c. The explicit normal, zero-src1-byte and carry cases, against the hand-computed results. The same + # table is checked against the AOT formula, so the pin and the formula cannot drift together. + op_index = 3 if op == 'v_sad_hi_u8' else 4 + rows = [(case[:3], case[op_index], AOT_REFERENCE[op](*case[:3]), eval_lane(exprs[0], 0, case[:3])) + for case in CASES] + bad = [(triple, pinned, formula, got) for triple, pinned, formula, got in rows + if not (pinned == formula == got)] + check('%s: pinned normal/zero-lane/carry rows all match (%s; first bad: %r)' + % (op, words_text(r[3] for r in rows), bad[0] if bad else None), not bad) + # The zero-src1-byte rule is what separates the two forms on these rows; require the cases to show it. + if op == 'v_msad_u8': + zero_lane = next(((case[0], case[1], case[2]) for case in CASES + if sad4_u8(case[0], case[1], False) != sad4_u8(case[0], case[1], True)), None) + check('%s: a row with skipped src1 byte lanes separates msad_u8 from the unmasked sum (%r)' + % (op, zero_lane), zero_lane is not None) + + # 1d. Exact emitted helper text, on demand only: the shared sad4_u8 plus the thin wrapper, and neither the + # other new helper nor the old sad_u8/sad_u16/sad_u32 helpers. + others = [h for o, h in HELPERS.items() if o != op] + check('%s: on-demand emits exactly sad4_u8 plus %s and no other SAD helper' % (op, helper), + SAD4_U8_HELPER in text and EXPECTED_HELPER[op] in text + and not any(mentions(text, h) for h in others + ['sad_u8', 'sad_u16', 'sad_u32']) + and text.count('uint sad4_u8(') == 1) + + # 1e. The pipeline records the op for the helper emission, and both stages share the common preamble, so + # both emitted shaders carry the same two helpers and nothing else from the SAD family. + check('%s: uses_sad accounting names only %s and the shared preamble carries only its two helpers' + % (op, op), + pipe.uses_sad == {op} + and all(SAD4_U8_HELPER in t and EXPECTED_HELPER[op] in t for t in (text, pipe.hlsl_vs())) + and not any(mentions(pipe.hlsl_vs(), h) for h in others + ['sad_u8', 'sad_u16', 'sad_u32'])) + + # Both new forms in one pixel stage: the shared sad4_u8 helper is emitted once and each wrapper once. + both_pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), + PRE_WORDS + BODY_WORDS['v_sad_hi_u8'] + BODY_WORDS['v_msad_u8'] + POST_WORDS, + root_blob()) + both_text = both_pipe.hlsl_ps() + check('both forms in one stage: sad4_u8 once, sad_hi_u8 once, msad_u8 once', + both_text.count('uint sad4_u8(') == 1 and both_text.count('uint sad_hi_u8(') == 1 + and both_text.count('uint msad_u8(') == 1 and both_pipe.uses_sad == set(OPCODES)) + + # 2. ComputePipeline on-demand helper check + SGPR / inline constant / literal encodings. + for op, code in OPCODES.items(): + cs_words = vop3a(code, 1, 4, 129, 255, lit=0x12345678) + struct.pack('<I', 0xbf810000) + cs_pipe = G.ComputePipeline(cs_words, root_blob(), (4 << 1) | (1 << 7), (1, 1, 1)) + cs_hlsl = cs_pipe.hlsl_cs() + check('ComputePipeline %s: SGPR/inline/literal emits sad4_u8 and %s only' % (op, HELPERS[op]), + '%s(s4, 0x00000001u, 0x12345678u)' % HELPERS[op] in cs_hlsl + and SAD4_U8_HELPER in cs_hlsl and EXPECTED_HELPER[op] in cs_hlsl + and not any(mentions(cs_hlsl, h) for o, h in HELPERS.items() if o != op)) + + # Genuine inline -1 (src=193, neg=0) and literal (src=255) decoded via G.decode(). + bad_word = vop3a(code, 12, 256, 193, 255, lit=0xabcdef01) + ins = G.decode(bad_word) + assert len(ins) == 1, ins + _, _, name, asm = ins[0] + stage = Probe() + stage.one(name, asm) + check('%s: decoded inline -1 and literal lower cleanly' % op, + stage.lines == ['v12 = %s(v0, 0xffffffffu, 0xabcdef01u);' % HELPERS[op]]) + + # Exec-masked emission. + masked = Probe() + masked.exec_known = False + masked.one(op, '%s v1, v2, v3, v4' % op) + check('%s: exec-masked emission guards assignment' % op, + masked.lines == ['if (exec & 1) v1 = %s(v2, v3, v4);' % HELPERS[op]]) + + # 3. Refusal controls (binary VOP3A decoded via G.decode() + Stage.one assembly/arity/unlowered). + for op, code in OPCODES.items(): + modifiers = [ + ('clamp', vop3a(code, 12, 256, 260, 264, clamp=1)), + ('omod=mul:2', vop3a(code, 12, 256, 260, 264, omod=1)), + ('omod=mul:4', vop3a(code, 12, 256, 260, 264, omod=2)), + ('omod=div:2', vop3a(code, 12, 256, 260, 264, omod=3)), + ('op_sel=[1,0,0]', vop3a(code, 12, 256, 260, 264, op_sel=1)), + ('op_sel=[0,0,0,1]', vop3a(code, 12, 256, 260, 264, op_sel=8)), + ] + abs_neg = [ + ('abs src0 VGPR', vop3a(code, 12, 256, 260, 264, abs_bits=1)), + ('abs src1 VGPR', vop3a(code, 12, 256, 260, 264, abs_bits=2)), + ('abs src2 VGPR', vop3a(code, 12, 256, 260, 264, abs_bits=4)), + ('abs src0 inline 1', vop3a(code, 12, 129, 260, 264, abs_bits=1)), + ('abs src1 inline 1', vop3a(code, 12, 256, 129, 264, abs_bits=2)), + ('abs src2 inline 1', vop3a(code, 12, 256, 260, 129, abs_bits=4)), + ('neg src0 VGPR', vop3a(code, 12, 256, 260, 264, neg=1)), + ('neg src1 VGPR', vop3a(code, 12, 256, 260, 264, neg=2)), + ('neg src2 VGPR', vop3a(code, 12, 256, 260, 264, neg=4)), + ('neg src0 inline 1', vop3a(code, 12, 129, 260, 264, neg=1)), + ('neg src1 inline 1', vop3a(code, 12, 256, 129, 264, neg=2)), + ('neg src2 inline 1', vop3a(code, 12, 256, 260, 129, neg=4)), + ] + for label, bad_word in modifiers + abs_neg: + try: + G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + bad_word + POST_WORDS, root_blob()) + except G.Unsupported: + pass + else: + raise AssertionError('%s: accepted binary VOP3A with %s' % (op, label)) + for label, bad_word in abs_neg: + reasons = [] + G.decode(bad_word, reasons) + check('%s: encoding guard refuses %s' % (op, label), + [reason for reason, where in reasons] == ['%s with neg/abs' % op]) + + # Direct Stage.one refusals: modifiers, abs/neg, arity. + check('%s: Stage refuses modifiers, abs/neg, and wrong operand counts' % op, all(refused(asm) for asm in ( + '%s v1, v2, v3, v4 clamp' % op, + '%s v1, v2, v3, v4 mul:2' % op, + '%s v1, v2, v3, v4 op_sel:[1,0,0]' % op, + '%s v1, |v2|, v3, v4' % op, + '%s v1, v2, |v3|, v4' % op, + '%s v1, v2, v3, |v4|' % op, + '%s v1, -v2, v3, v4' % op, + '%s v1, v2, -v3, v4' % op, + '%s v1, v2, v3, -v4' % op, + '%s v1' % op, + '%s v1, v2' % op, + '%s v1, v2, v3' % op, + '%s v1, v2, v3, v4, v5' % op, + ))) + + # 4. Unlowered control: removing the entries from VEC_U must cause G.Pipeline and Stage.one to refuse. + saved = {op: G.VEC_U.pop(op) for op in OPCODES} + try: + for op in OPCODES: + try: + translate(op) + except G.Unsupported: + pass + else: + raise AssertionError('%s: translated after removal from VEC_U' % op) + assert refused('%s v1, v2, v3, v4' % op), op + finally: + G.VEC_U.update(saved) + check('unlowered control: removing v_sad_hi_u8/v_msad_u8 from VEC_U restores refusals', True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/tests/startup_gfx2hlsl_scalar_null_check.py b/tests/startup_gfx2hlsl_scalar_null_check.py new file mode 100644 index 0000000000..416904bbfa --- /dev/null +++ b/tests/startup_gfx2hlsl_scalar_null_check.py @@ -0,0 +1,660 @@ +"""RDNA 2 scalar null operand (code 125) and Stage.scalar destination guards in tools/startup/gfx2hlsl.py. + + (no arguments) translation, CPU SCC evaluation across 14 32-bit SALU ops, null-source + folding/uniformity, TypeError/Unsupported destination sweep, pure Python + binary <llvm-mc> reassemble every fixture and instruction spelling and compare with recorded words + decode <libLLVM> disassemble the canonical encodings with LLVM's C API and compare with disasm_rdna2.py + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile and draw the pixel fixture (FXC ps_5_1 + DXC ps_6_0) and execute the + root-constant SALU null-destination + branch buffer fixture with negative controls + +AMD RDNA 2 ISA reference (scalar/vector source and destination encoding code 125 = null): + - Reading null returns 0 (wave-uniform 32-bit zero). + - Writing null discards the destination register result while still performing modeled 32-bit SCC updates. + - Unmodelled scalar destinations (vcc_hi, exec_hi, ttmp*, _b64/lane-mask/descriptor/unmodelled-SCC writes to null) + raise gfx2hlsl.Unsupported instead of TypeError (#2618, #1723, #2463). +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + Expr, + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + check, + signed, + vs_source, + vs_words, + words_text, +) + +NULL = 125 +M0 = 124 +VCC_LO, VCC_HI = 106, 107 +TTMP0 = 108 +EXEC_LO, EXEC_HI = 126, 127 + +SENTINEL = 0xc5c5c5c5 +# Matches offscreen_check --compute-store-case's built-in t0 ByteAddressBuffer pattern. +DATA = b''.join(struct.pack('<I', (0x8b02a7f1 + i * 0x413b1) & 0xffffffff) for i in range(320)) + + +def sop1(op, sdst, ssrc0, lit=None): + out = struct.pack('<I', 0xbe800000 | ((sdst & 0x7f) << 16) | ((op & 0xff) << 8) | (ssrc0 & 0xff)) + return out if lit is None else out + struct.pack('<I', lit & MASK) + + +def sop2(op, sdst, ssrc0, ssrc1, lit=None): + out = struct.pack('<I', 0x80000000 | ((op & 0x7f) << 23) | ((sdst & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff)) + return out if lit is None else out + struct.pack('<I', lit & MASK) + + +def sopk(op, sdst, simm16): + return struct.pack('<I', 0xb0000000 | ((op & 0x1f) << 23) | ((sdst & 0x7f) << 16) | (simm16 & 0xffff)) + + +def sopc(op, ssrc0, ssrc1): + return struct.pack('<I', 0xbf000000 | ((op & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff)) + + +def sopp(op, simm16=0): + return struct.pack('<I', 0xbf800000 | ((op & 0x7f) << 16) | (simm16 & 0xffff)) + + +def vop1(op, vdst, src0): + return struct.pack('<I', 0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff)) + + +def vop2(op, vdst, src0, vsrc1): + return struct.pack('<I', ((op & 0x3f) << 25) | ((vdst & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff)) + + +def vop3a(op, vdst, src0, src1, src2=0): + return struct.pack('<2I', 0xd4000000 | (op << 16) | (vdst & 0xff), (src2 << 18) | (src1 << 9) | src0) + + +def smem(op, sdata, sbase, *, soffset=NULL, imm=0): + w0 = (0b111101 << 26) | ((op & 0xff) << 18) | ((sdata & 0x7f) << 6) | ((sbase >> 1) & 0x3f) + w1 = ((soffset & 0x7f) << 25) | (imm & 0x1fffff) + return struct.pack('<2I', w0, w1) + + +def root_with_one_constant(): + header = struct.pack('<6I', 2, 1, 24, 0, 0, 0) + param = struct.pack('<3I', 1, 0, 36) + const = struct.pack('<3I', 0, 0, 1) + rts0 = header + param + const + part = b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + return b'DXBC' + bytes(16) + struct.pack('<III', 1, 36 + len(part), 1) + struct.pack('<I', 36) + part + + +# Canonical LLVM 15 round-trip lines (disasm_rdna2 <-> llvm-mc <-> libLLVM). +CANONICAL_CASES = ( + ('s_and_b32 null, s8, 4', sop2(0x0e, NULL, 8, 128 + 4)), + ('s_bfe_u32 null, s8, 0x30008', sop2(0x27, NULL, 8, 255, lit=0x30008)), + ('s_mov_b32 null, s8', sop1(0x03, NULL, 8)), + ('s_not_b32 null, s8', sop1(0x07, NULL, 8)), + ('s_movk_i32 null, 0x100', sopk(0x00, NULL, 0x100)), + ('s_cselect_b32 s2, 32, null', sop2(0x0a, 2, 128 + 32, NULL)), + ('s_or_b32 m0, null, s2', sop2(0x10, M0, NULL, 2)), + ('s_cmp_eq_u32 s8, null', sopc(0x06, 8, NULL)), + ('s_bfm_b32 null, s8, 2', sop2(0x24, NULL, 8, 128 + 2)), + ('s_and_b64 null, exec, s[0:1]', sop2(0x0f, NULL, EXEC_LO, 0)), + ('v_subrev_nc_u32_e32 v12, null, v0', vop2(0x27, 12, NULL, 0)), + ('v_xor3_b32 v13, v1, v5, null', vop3a(0x178, 13, 257, 261, NULL)), + ('v_add_f32_e32 v14, null, v2', vop2(0x03, 14, NULL, 2)), + ('v_cvt_pk_u16_u32 v15, null, v3', vop3a(0x36a, 15, NULL, 259)), +) + +# Pixel-stage draw fixture (FXC ps_5_1 + DXC ps_6_0): exercises null as VOP2/VOP3A source and SALU null-dst + null-src. +PS_BODY_SOURCE = """\ +v_subrev_nc_u32_e32 v12, null, v0 +v_xor3_b32 v13, v1, v5, null +v_add_f32_e32 v14, null, v2 +s_mov_b32 s4, 1.0 +s_and_b32 null, s4, 0x7f800000 +s_cselect_b32 s5, 0x55, null +v_xor_b32_e32 v15, s5, v3 +""" +PS_BODY_WORDS = b''.join(( + vop2(0x27, 12, NULL, 0), + vop3a(0x178, 13, 257, 261, NULL), + vop2(0x03, 14, NULL, 2), + sop1(0x03, 4, 242), + sop2(0x0e, NULL, 4, 255, lit=0x7f800000), + sop2(0x0a, 5, 255, NULL, lit=0x55), + vop2(0x1d, 15, 5, 3), +)) +PS_WORDS = PRE_WORDS + PS_BODY_WORDS + POST_WORDS + +PS_DRAW_INPUTS = [ + # Set 0: normal binary32 words in v0..v3, plus v5 (set index 1's second element) for v_xor3_b32. + (0x3f800011, 0, 0), + (0x40200022, 0x0000ff00, 0), + (0x40600000, 0, 0), # 3.5f + (0x41000033, 0, 0), + # Set 1: + (0xbf800044, 0, 0), + (0xc1200055, 0x00aa5500, 0), + (0xc0100000, 0, 0), # -2.25f + (0x3e800066, 0, 0), +] + + +def f32_add_zero(bits, addend_bits=0): + a = struct.unpack('<f', struct.pack('<I', addend_bits))[0] + b = struct.unpack('<f', struct.pack('<I', bits))[0] + return struct.unpack('<I', struct.pack('<f', a + b))[0] + + +def ref_ps_chunk(chunk): + return [ + chunk[0][0] & MASK, + (chunk[1][0] ^ chunk[1][1]) & MASK, + f32_add_zero(chunk[2][0], 0), + (chunk[3][0] ^ 0x55) & MASK, + ] + + +# 14 32-bit SCA operations that write modeled SCC ($ != 0). +SCC_32_OPS = ( + ('s_and_b32', 2, lambda a, b: (a & b) != 0), + ('s_or_b32', 2, lambda a, b: (a | b) != 0), + ('s_xor_b32', 2, lambda a, b: (a ^ b) != 0), + ('s_andn2_b32', 2, lambda a, b: (a & (~b & MASK)) != 0), + ('s_orn2_b32', 2, lambda a, b: (a | (~b & MASK)) != 0), + ('s_not_b32', 1, lambda a, _b: (~a & MASK) != 0), + ('s_nand_b32', 2, lambda a, b: (~(a & b) & MASK) != 0), + ('s_nor_b32', 2, lambda a, b: (~(a | b) & MASK) != 0), + ('s_xnor_b32', 2, lambda a, b: (~(a ^ b) & MASK) != 0), + ('s_lshl_b32', 2, lambda a, b: ((a << (b & 31)) & MASK) != 0), + ('s_lshr_b32', 2, lambda a, b: ((a >> (b & 31)) & MASK) != 0), + ('s_ashr_i32', 2, lambda a, b: ((signed(a) >> (b & 31)) & MASK) != 0), + ('s_bfe_u32', 2, lambda a, b: ((a >> (b & 31)) & (MASK if ((b >> 16) & 127) >= 32 else ((1 << ((b >> 16) & 31)) - 1))) != 0), + ('s_absdiff_i32', 2, lambda a, b: (abs(signed((a - b) & MASK)) & MASK) != 0), +) + +SCC_PAIRS = ( + (0, 0), (0, MASK), (MASK, 0), (MASK, MASK), (0x55555555, 0xaaaaaaaa), + (0x80000000, 1), (0x80000000, 31), (1, 31), (0x0000ff00, 0x00080008), + (0x0000ff00, 0x00040000), (0x00010000, 0x00200010), (0xdeadbeef, 0xdeadbeef), +) + + +class DummyPipe: + sampler_heap = False + rtv_formats = () + srv_formats = {} + + def __init__(self): + self.resources = {} + self.uavs = {} + self.uds = [] + self.modified = set() + self.other_modified = set() + + def ud(self, tag): + if tag not in self.uds: + self.uds.append(tag) + return self.uds.index(tag) + + def resource(self, key, kind): + entry = self.resources.setdefault(key, {'index': len(self.resources), 'kind': kind}) + return 'r%d' % entry['index'] + + +class ProbeStage(G.Stage): + def __init__(self, kind='ps'): + self.pipe = DummyPipe() + self.kind = kind + self.lines = [] + self.sym = { + 5: ('const', 0x12), + 10: ('ptr', ('root', 1)), + 11: ('ptrhi', ('root', 1)), + **{16 + i: ('desc', ('table', 0), 16, i) for i in range(4)}, + } + self.used_s, self.used_v = set(), set() + self.uniform_v, self.varying_s = set(), set() + self.scc_uniform = True + self.defined_uniform_s = {0, 1, 2, 5} + self.bad_sgprs = set() + self.uniform_expr = {} + self.since_join = None + self.low16_only_v, self.pinned_low16_v, self.whole_read_v = set(), set(), set() + self.exec_known = True + self.exports, self.attrs, self.write_masks, self.masks = {}, {}, {}, set() + + +def eval_scc_line(line, s0, s1): + assert line.startswith('scc = ') and line.endswith(';'), line + return bool(Expr(line[len('scc = '):-1]).run({'s0': s0 & MASK, 's1': s1 & MASK})[0]) + + +def build_root_null_pipeline(): + """VS exercising runtime root-constant s8 through SALU null-destination SCC updates, no-SCC null discards, + null scalar sources, and s_cbranch_scc0 into s_buffer_load_dwordx4.""" + vs = b''.join(( + smem(0x02, 16, 0, soffset=NULL, imm=0x10), # s_load_dwordx4 s[16:19], s[0:1], 0x10 + sop2(0x0e, NULL, 8, 128 + 4), # s_and_b32 null, s8, 4 -> scc = (s8 & 4) != 0 + sop1(0x03, NULL, 8), # s_mov_b32 null, s8 -> no-op, keeps scc + sop2(0x26, NULL, 8, 128 + 7), # s_mul_i32 null, s8, 7 -> no-op, keeps scc + sop2(0x24, NULL, 8, 128 + 2), # s_bfm_b32 null, s8, 2 -> no-op, keeps scc + sop2(0x0a, 2, 128 + 32, NULL), # s_cselect_b32 s2, 32, null -> s2 = scc ? 32 : 0 + sop2(0x27, NULL, 8, 255, lit=0x30008), # s_bfe_u32 null, s8, 0x30008 -> scc = ((s8 >> 8) & 7) != 0 + sopp(0x04, 2), # s_cbranch_scc0 +2 dwords (skips the 8-byte literal add) + sop2(0x00, 2, 2, 255, lit=0x40), # s_add_u32 s2, s2, 0x40 -> s2 += 64 when scc + sop2(0x10, M0, NULL, 2), # s_or_b32 m0, null, s2 -> m0 = 0 | s2 + smem(0x0a, 20, 16, soffset=M0), # s_buffer_load_dwordx4 s[20:23], s[16:19], m0 + vop1(0x01, 4, 20), + vop1(0x01, 5, 21), + vop1(0x01, 6, 22), + vop1(0x01, 7, 23), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + ps = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + return G.Pipeline(vs, ps, root_with_one_constant()) + + +def expected_root_null(s8, *, drop_and_scc=False, clobber_mov_scc=False, invert_bfe_scc=False, bad_null_src=False): + scc1 = False if drop_and_scc else ((s8 & 4) != 0) + if clobber_mov_scc: + scc1 = True + null_val = 16 if bad_null_src else 0 + s2 = 32 if scc1 else null_val + bfe_nz = (((s8 >> 8) & 7) != 0) + scc2 = (not bfe_nz) if invert_bfe_scc else bfe_nz + if scc2: + s2 = (s2 + 64) & MASK + addr = (null_val | s2) & MASK + quad = list(struct.unpack_from('<4I', DATA, addr)) + return quad * 16 + [SENTINEL] * (320 - 64) + + +def controls(): + # 1. Canonical encodings round-trip through disasm_rdna2.decode_instruction. + for text, raw in CANONICAL_CASES: + n, _, asm, _ = D.decode_instruction(raw, 0) + check(f'disasm_rdna2 round-trip: {text}', n == len(raw) and asm == text) + off, body_lines = 0, [] + while off < len(PS_BODY_WORDS): + n, _, asm, _ = D.decode_instruction(PS_BODY_WORDS, off) + body_lines.append(asm + '\n') + off += n + check('PS_BODY_WORDS matches PS_BODY_SOURCE', ''.join(body_lines) == PS_BODY_SOURCE) + + # 2. All 14 32-bit SCC-writing SCA ops into null emit only `scc = ...;` and match ISA SCC across boundary pairs. + for op, arity, ref_scc in SCC_32_OPS: + st = ProbeStage() + asm = f'{op} null, s0' if arity == 1 else f'{op} null, s0, s1' + st.one(op, asm) + check(f'{op} null: emits single SCC assignment and leaves SGPRs unwritten', + len(st.lines) == 1 and st.lines[0].startswith('scc = ') and st.scc_uniform) + seen = set() + mismatches = 0 + for a, b in SCC_PAIRS: + got = eval_scc_line(st.lines[0], a, b) + want = ref_scc(a, b) + seen.add(got) + if got != want: + mismatches += 1 + check(f'{op} null: {len(SCC_PAIRS)} boundary pairs match ISA SCC (reaches both True and False)', + mismatches == 0 and seen == {False, True}) + + # 3. 32-bit non-SCC ops into null validate sources, emit no assignment, and leave SCC / scc_uniform untouched. + for op, asm in ( + ('s_mov_b32', 's_mov_b32 null, s0'), + ('s_movk_i32', 's_movk_i32 null, 0x100'), + ('s_brev_b32', 's_brev_b32 null, s0'), + ('s_mul_i32', 's_mul_i32 null, s0, s1'), + ('s_bfm_b32', 's_bfm_b32 null, s0, s1'), + ): + st = ProbeStage() + st.scc_uniform = False + st.one(op, asm) + check(f'{op} into null: emits nothing and preserves scc_uniform', + st.lines == [] and st.scc_uniform is False) + + # 4. null (code 125) as a 32-bit source reads as 0x00000000u, folds constants, and preserves UNIFORM_VALU. + st_fold = ProbeStage() + st_fold.one('s_brev_b32', 's_brev_b32 s2, null') + st_fold.one('s_bfm_b32', 's_bfm_b32 s3, 8, null') + st_fold.one('s_mov_b32', 's_mov_b32 s4, 1') + st_fold.one('s_bitset0_b32', 's_bitset0_b32 s4, null') + st_fold.one('s_bfe_i32', 's_bfe_i32 s6, null, 0x40000') + check('null source folds in s_brev_b32, s_bfm_b32, s_bitset0_b32 and s_bfe_i32', + st_fold.sym.get(2) == ('const', 0) + and st_fold.sym.get(3) == ('const', 0xff) + and st_fold.sym.get(4) == ('const', 0) + and st_fold.sym.get(6) == ('const', 0)) + + def run_stage(*instructions, varying=()): + s = G.Stage.__new__(G.Stage) + s.pipe, s.kind, s.lines = DummyPipe(), 'ps', [] + s.attrs, s.exports, s.write_masks = {}, {}, {} + s.sym, s.used_s, s.used_v, s.masks = {}, set(), set(), set() + s.uniform_v, s.varying_s, s.scc_uniform = set(), set(varying), True + s.entry_uniform_s = {2} + s.exec_known = True + s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + s.translate() + return [line for _, lines, _ in s.blocks for line in lines] + + u_lines = run_stage( + 's_and_b32 null, s2, 4', + 's_cselect_b32 s3, 10, null', + 'v_cvt_pk_u16_u32 v7, null, s3', + 'v_readfirstlane_b32 s9, v7', + ) + check('uniform s_and_b32 null + null source propagates to v_readfirstlane_b32', + u_lines[-1] == 's9 = v7;') + try: + run_stage( + 'v_cmp_lt_f32_e32 vcc_lo, v0, v1', + 's_and_b32 m0, vcc_lo, -1', + 's_cselect_b32 s8, 4, 0', + 's_cmp_eq_u32 s2, s2', + 's_and_b32 null, s8, 4', + 's_cselect_b32 s3, 10, null', + 'v_mov_b32_e32 v7, s3', + 'v_readfirstlane_b32 s9, v7', + ) + except G.Unsupported as exc: + check('varying s_and_b32 null clears scc_uniform and refuses v_readfirstlane_b32', + 'proven uniform source' in str(exc)) + else: + raise AssertionError('varying s_and_b32 null unexpectedly accepted by v_readfirstlane_b32') + + # ComputePipeline lowering with s_and_b32 null + s_cbranch_scc0 + VALU null source. + cs_blob = ( + sop2(0x0e, NULL, 4, 128 + 4) + + sopp(0x04, 1) + + vop2(0x25, 1, NULL, 0) + + sopp(0x01, 0) + ) + cs_hlsl = G.ComputePipeline(cs_blob, root_blob(), (4 << 1) | (1 << 7), (1, 1, 1)).hlsl_cs() + check('ComputePipeline: s_and_b32 null + s_cbranch_scc0 + v_add_nc_u32 null lowers cleanly', + 'scc = (s4 & 0x00000004u) != 0;' in cs_hlsl and '0x00000000u + v0' in cs_hlsl) + + # 5. Complete TypeError elimination & explicit Unsupported refusal sweep across all SCA ops + s_bfm_b32. + bad_dests = ('vcc_hi', 'exec_hi', 'ttmp0') + for op in sorted(G.SCA): + arity = 1 if op in ('s_mov_b32', 's_mov_b64', 's_movk_i32', 's_not_b32', 's_not_b64', + 's_brev_b32', 's_sext_i32_i8', 's_sext_i32_i16') else 2 + src_a = '0x10' if op == 's_movk_i32' else ('s[0:1]' if op.endswith('_b64') else 's0') + src_b = 's[2:3]' if op.endswith('_b64') else 's1' + rhs = src_a if arity == 1 else f'{src_a}, {src_b}' + for dst in bad_dests: + for use_desc in (False, True): + st = ProbeStage() + if use_desc and not op.endswith('_b64') and op != 's_movk_i32': + st.sym[0] = ('desc', ('table', 0), 16, 0) + try: + st.one(op, f'{op} {dst}, {rhs}') + except G.Unsupported as exc: + assert dst in str(exc) or 'descriptor' in str(exc) or 'lane mask' in str(exc), (op, dst, exc) + except Exception as exc: + raise AssertionError(f'{op} into {dst} (desc={use_desc}) raised {type(exc).__name__}: {exc}') + else: + raise AssertionError(f'{op} into {dst} unexpectedly accepted: {st.lines}') + + for dst in ('vcc_lo', 'vcc_hi', 'exec_lo', 'exec_hi', 'ttmp0'): + st = ProbeStage() + try: + st.one('s_bfm_b32', f's_bfm_b32 {dst}, s0, s1') + except G.Unsupported as exc: + assert f's_bfm_b32 destination {dst}' == str(exc), exc + else: + raise AssertionError(f's_bfm_b32 into {dst} accepted') + check(f'all {len(G.SCA)} SCA ops + s_bfm_b32 refuse unmodelled non-SGPR destinations without TypeError', True) + + # Specific null-destination refusals: _b64, lane-mask sources (#2618 wave64 pattern), SCC_UNMODELLED, descriptors. + specific_refusals = ( + ('s_and_b64', 's_and_b64 null, exec, s[0:1]', 's_and_b64 into null on a lane mask'), + ('s_or_b64', 's_or_b64 null, vcc, s[0:1]', 's_or_b64 into null on a lane mask'), + ('s_and_b64', 's_and_b64 null, s[0:1], s[2:3]', 's_and_b64 into null'), + ('s_mov_b64', 's_mov_b64 null, s[0:1]', 's_mov_b64 into null'), + ('s_and_b32', 's_and_b32 null, exec_lo, s0', 's_and_b32 into null on a lane mask'), + ('s_or_b32', 's_or_b32 null, vcc_lo, s0', 's_or_b32 into null on a lane mask'), + ('s_nand_b32', 's_nand_b32 null, vcc_lo, exec_lo', 's_nand_b32 on a lane mask'), + ('s_bfm_b32', 's_bfm_b32 null, vcc_lo, 4', 's_bfm_b32 into null on a lane mask'), + ('s_and_b32', 's_and_b32 null, s16, 0xff', 'scc from descriptor data'), + ('s_add_u32', 's_add_u32 null, s10, 4', 'scc from descriptor data'), + ('s_mov_b32', 's_mov_b32 null, s16', 's_mov_b32 into null on descriptor data'), + ) + for op, asm, expected_reason in specific_refusals: + st = ProbeStage() + try: + st.one(op, asm) + except G.Unsupported as exc: + check(f'refuses {asm} ({exc})', str(exc) == expected_reason and not st.lines) + else: + raise AssertionError(f'{asm} unexpectedly accepted: {st.lines}') + + # A null destination keeps only the SCC the operation computes (no register is written, nothing else is emitted). + for asm, scc_line in ( + ('s_add_u32 null, s0, s1', 'scc = (s0 + s1) < (s0);'), + ('s_sub_u32 null, s0, s1', 'scc = (s0) < (s1);'), + ('s_add_i32 null, s0, s1', 'scc = (((((s0) ^ (s0 + s1)) & ((s1) ^ (s0 + s1))) >> 31) != 0);'), + ('s_sub_i32 null, s0, s1', 'scc = (((((s0) ^ (s1)) & ((s0) ^ (s0 - s1))) >> 31) != 0);'), + ('s_min_u32 null, s0, s1', 'scc = ((s0) <= (s1));'), + ('s_max_u32 null, s0, s1', 'scc = ((s0) >= (s1));'), + ('s_min_i32 null, s0, s1', 'scc = (int(s0) <= int(s1));'), + ('s_max_i32 null, s0, s1', 'scc = (int(s0) >= int(s1));')): + st = ProbeStage() + st.one(asm.split()[0], asm) + check(f'{asm} computes only its SCC {st.lines}', st.lines == [scc_line]) + + # SGPR holding a compare mask must also be refused when combined into null. + st_mask = ProbeStage() + st_mask.masks.add(0) + try: + st_mask.one('s_and_b32', 's_and_b32 null, s0, s1') + except G.Unsupported as exc: + check('s_and_b32 null with SGPR compare mask refused', str(exc) == 's_and_b32 into null on a lane mask') + else: + raise AssertionError('accepted SGPR compare mask into null') + + # 6. Unlowered negative control: reverting Stage.u('null') restores the pre-change refusal. + real_u = G.Stage.u + + def no_null_u(self, tok, *, low16_only=False): + if tok == 'null': + raise G.Unsupported("operand 'null'") + return real_u(self, tok, low16_only=low16_only) + + G.Stage.u = no_null_u + try: + try: + G.Pipeline(vs_words(PS_DRAW_INPUTS[:4]), PS_WORDS, root_blob()) + except G.Unsupported as exc: + check("unlowered control: removing null from Stage.u restores operand 'null' refusal", + str(exc) == "operand 'null'") + else: + raise AssertionError('PS_WORDS translated with Stage.u null handling disabled') + finally: + G.Stage.u = real_u + + +def check_binary(llvm_mc): + for text, expected in CANONICAL_CASES: + built = assemble(llvm_mc, text + '\n') + assert built == expected, f'{text}: assembled {built.hex()}, recorded {expected.hex()}' + assert assemble(llvm_mc, PS_BODY_SOURCE) == PS_BODY_WORDS, 'PS_BODY_WORDS differs from llvm-mc' + for name, source, raw in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + assert assemble(llvm_mc, source) == raw, f'{name} fixture differs from llvm-mc' + for idx in range(0, len(PS_DRAW_INPUTS), 4): + chunk = PS_DRAW_INPUTS[idx:idx + 4] + assert assemble(llvm_mc, vs_source(chunk)) == vs_words(chunk), chunk + print('llvm-mc: all scalar/vector null cases and draw fixtures match recorded words') + + +def check_decode(library): + from pixel_aot import disassemble + blob = b''.join(raw for _, raw in CANONICAL_CASES) + llvm_lines = disassemble(blob, library) + ours = [text for text, _ in CANONICAL_CASES] + assert llvm_lines == ours, f'LLVM vs disasm_rdna2 mismatch: {list(zip(llvm_lines, ours))}' + print(f'libLLVM: {len(CANONICAL_CASES)} encodings with null match disasm_rdna2.py verbatim') + + +def run_root_case(directory, dxc, renderer, adapter, pipe, vs_hlsl, ref_words, *, s8=0, fxc=None): + hlsl, binary, case = (directory / n for n in ('root_null.hlsl', 'root_null.cso', 'root_null.case')) + constants = [0] * 16 + if ('rootconst', 0, 0) in pipe.uds: + constants[pipe.uds.index(('rootconst', 0, 0))] = s8 + case.write_bytes(struct.pack('<337I', 1, *ref_words, *constants)) + hlsl.write_text(vs_hlsl, encoding='ascii') + if fxc: + ps_hlsl = directory / 'root_null_ps.hlsl' + ps_hlsl.write_text(pipe.hlsl_ps(), encoding='ascii') + subprocess.run([fxc, '/nologo', '/T', 'vs_5_1', '/E', 'main', '/Fo', str(directory / 'vs51.cso'), str(hlsl)], + check=True, capture_output=True, text=True) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(directory / 'ps51.cso'), str(ps_hlsl)], + check=True, capture_output=True, text=True) + subprocess.run([dxc, '-T', 'vs_6_0', '-E', 'main', '-Fo', str(binary), str(hlsl)], + check=True, capture_output=True, text=True) + wrapper = ( + '\nRWByteAddressBuffer outputWords : register(u0);\n' + '[numthreads(16, 1, 1)]\n' + 'void readback(uint id : SV_GroupIndex) {\n' + ' float4 p = body(id).pos;\n' + ' outputWords.Store4(id * 16, asuint(p));\n' + '}\n' + ) + with hlsl.open('a', encoding='ascii') as handle: + handle.write(wrapper) + subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'readback', '-Fo', str(binary), str(hlsl)], + check=True, capture_output=True, text=True) + return subprocess.run([renderer, adapter, '--compute-store-case', str(binary), str(case)], + capture_output=True, text=True) + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ps_draws = ps_muts = 0 + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + ps_text = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()).hlsl_ps() + + # Part A: Graphics VS+PS draw across FXC ps_5_1 and DXC ps_6_0 + three pixel-stage mutations. + ps_mutations = ( + ( + 'subrev_null_1', + 'v0 - 0x00000000u', + 'v0 - 0x00000001u', + lambda c: [(c[0][0] - 1) & MASK, (c[1][0] ^ c[1][1]) & MASK, f32_add_zero(c[2][0]), (c[3][0] ^ 0x55) & MASK], + ), + ( + 'f32_null_one', + 'F(0x00000000u) + F(v2)', + '1.0 + F(v2)', + lambda c: [c[0][0] & MASK, (c[1][0] ^ c[1][1]) & MASK, f32_add_zero(c[2][0], 0x3f800000), (c[3][0] ^ 0x55) & MASK], + ), + ( + 'drop_null_scc', + 'scc = (s4 & 0x7f800000u) != 0;', + 'scc = false;', + lambda c: [c[0][0] & MASK, (c[1][0] ^ c[1][1]) & MASK, f32_add_zero(c[2][0]), c[3][0] & MASK], + ), + ) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, ps_text, f'ps_null_{kind}', ps_profile, directory) + for idx in range(0, len(PS_DRAW_INPUTS), 4): + chunk = PS_DRAW_INPUTS[idx:idx + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + f'vs_null_{idx}_{kind}', vs_profile, directory) + expected = words_text(ref_ps_chunk(chunk)) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode == 77: + print(run.stdout, run.stderr) + sys.exit(77) + if run.returncode: + raise AssertionError(f'{kind} PS null draw {idx}\n{run.stdout}\n{run.stderr}') + ps_draws += 1 + print(f'{kind} PS null draw {idx // 4}: {expected}', flush=True) + if idx: + continue + for mut_name, target, repl, mut_fn in ps_mutations: + assert target in ps_text, (mut_name, ps_text) + bad_ps = compile_hlsl(compiler, kind, ps_text.replace(target, repl, 1), + f'mut_ps_{mut_name}_{kind}', ps_profile, directory) + wrong = words_text(mut_fn(chunk)) + mrun = draw(renderer, adapter, vs, bad_ps, expected) + if mrun.returncode == 0 or f'actual={wrong}' not in mrun.stderr: + raise AssertionError(f'{kind} mutation {mut_name} did not read {wrong}\n{mrun.stdout}\n{mrun.stderr}') + ps_muts += 1 + print(f'{kind} PS mutation ({mut_name}): fails as expected, reads {wrong}', flush=True) + + # Part B: Runtime root-constant s8 through SALU null-destination SCC updates + branch + buffer load. + root_pipe = build_root_null_pipeline() + vs_hlsl = root_pipe.hlsl_vs() + for s8 in (0x000, 0x004, 0x300, 0x504): + ref = expected_root_null(s8) + res = run_root_case(directory, dxc, renderer, adapter, root_pipe, vs_hlsl, ref, + s8=s8, fxc=fxc if s8 == 0 else None) + if res.returncode == 77: + print(res.stdout, res.stderr) + sys.exit(77) + if res.returncode: + raise AssertionError(f'root null case s8={s8:#x}\n{res.stdout}\n{res.stderr}') + print(f'root null SALU+branch (s8={s8:#x}):', + [l for l in res.stdout.splitlines() if 'mismatches=' in l][0], flush=True) + + # Four HLSL mutations on the runtime root-constant shader must fail GPU readback. + ref_504 = expected_root_null(0x504) + ref_300 = expected_root_null(0x300) + and_mut, n1 = re.subn(r'scc = \(ud\d+ & 0x00000004u\) != 0;', 'scc = false;', vs_hlsl, count=1) + clob_mut, n2 = re.subn(r's2 = scc \? 0x00000020u : 0x00000000u;', + 'scc = true; s2 = scc ? 0x00000020u : 0x00000000u;', vs_hlsl, count=1) + bfe_mut, n3 = re.subn(r'(scc = \(\(ud\d+ >> \(0x00030008u & 31\)\).*?)\) != 0;', r'\1) == 0;', vs_hlsl, count=1) + src_mut, n4 = re.subn(r'm0 = 0x00000000u \| s2;', 'm0 = 0x00000010u | s2;', vs_hlsl, count=1) + assert (n1, n2, n3, n4) == (1, 1, 1, 1), (n1, n2, n3, n4, vs_hlsl) + root_mutants = ( + ('dropped s_and_b32 null SCC write', and_mut, 0x504, ref_504), + ('no-SCC null discard clobbering SCC', clob_mut, 0x300, ref_300), + ('inverted s_bfe_u32 null SCC write', bfe_mut, 0x504, ref_504), + ('non-zero null source in s_or_b32', src_mut, 0x504, ref_504), + ) + for label, mutant_hlsl, s8_val, good_ref in root_mutants: + assert mutant_hlsl != vs_hlsl, (label, vs_hlsl) + fail = run_root_case(directory, dxc, renderer, adapter, root_pipe, mutant_hlsl, good_ref, s8=s8_val) + if fail.returncode != 1 or 'Compute readback differs' not in fail.stderr: + raise AssertionError(f'root mutation {label!r} escaped detection:\n{fail.stdout}\n{fail.stderr}') + print(f'root mutation ({label}): fails GPU readback as expected', flush=True) + + print(f'{adapter}: {ps_draws} PS draws + 4 root-constant runs matched; {ps_muts} PS + 4 root mutations caught') + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary' and len(args) == 1: + check_binary(args[0]) + elif mode == 'decode' and len(args) == 1: + check_decode(args[0]) + elif mode == 'draw' and len(args) in (3, 4): + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_scalar_table_arity_check.py b/tests/startup_gfx2hlsl_scalar_table_arity_check.py index 7a2d86ebcf..f33cff0f59 100644 --- a/tests/startup_gfx2hlsl_scalar_table_arity_check.py +++ b/tests/startup_gfx2hlsl_scalar_table_arity_check.py @@ -16,6 +16,9 @@ HERE = Path(__file__).resolve().parent SOURCE = HERE.parent / 'tools' / 'startup' / 'gfx2hlsl.py' +# Templates that refuse a short form in their own body (before the shared SCA arity guard). +OWN_ARITY = frozenset(('s_bfm_b32', 's_mul_hi_u32', 's_mul_hi_i32')) + def load(text=None): spec = importlib.util.spec_from_loader('gfx2hlsl_table', loader=None) @@ -91,17 +94,19 @@ def refusal(module, op, sources): changed.append(op) check('a complete form is never refused for its operand count', not changed, repr(changed[:4])) -# Negative control: with the guard removed the short form raises IndexError again. One template keeps its own -# arity check (s_bfm_b32 spells "expected 3" in its body), so it refuses either way and is excluded here rather -# than counted as a survivor. +# Negative control: with the guard removed the short form raises IndexError again. Templates that keep +# their own arity check refuse either way and are excluded here rather than counted as survivors. stripped = load(SOURCE.read_text(encoding='utf-8').replace(' if len(srcs) < needed:', ' if False:')) control = [op for op in TWO_SOURCE if refusal(stripped, op, needed_sources(stripped, op) - 1) == 'IndexError'] -check('control: without the guard the short form raises IndexError', len(control) >= len(TWO_SOURCE) - 1, +check('control: without the guard the short form raises IndexError', + len(control) >= len(TWO_SOURCE) - len(OWN_ARITY), '%d of %d' % (len(control), len(TWO_SOURCE))) kept = [op for op in TWO_SOURCE if op not in control] -check('the one template with its own arity check still refuses without the guard', - all(refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), repr(kept)) +check('templates with their own arity check still refuse without the guard', + set(kept) <= OWN_ARITY and all( + refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), + repr(kept)) print('scalar table arity checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) diff --git a/tests/startup_gfx2hlsl_sdwa_check.py b/tests/startup_gfx2hlsl_sdwa_check.py index 419946c63e..a1c9ae9459 100644 --- a/tests/startup_gfx2hlsl_sdwa_check.py +++ b/tests/startup_gfx2hlsl_sdwa_check.py @@ -86,6 +86,18 @@ def translate(assembly): print(' emitted:', emitted) +# 5b. The VOP2 select takes its lane mask from VCC (the fourth operand) and its sources through their selects. +emitted = translate('v_cndmask_b32_sdwa v3, v1, v2, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD ' + 'src0_sel:WORD_1 src1_sel:BYTE_0') +check('SDWA select picks src1 under VCC', + emitted.replace(' ', '') == 'v3=(vcc&1)?((v2>>0u)&0xffu):((v1>>16u)&0xffffu);') +print(' emitted:', emitted) +emitted = translate('v_cndmask_b32_sdwa v3, v1, v2, vcc_lo dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE ' + 'src0_sel:DWORD src1_sel:DWORD') +check('SDWA select grouped before a word destination', '((vcc & 1) ? v2 : v1)' in emitted and 'v3' in emitted) +print(' emitted:', emitted) + + # 6. Forms with no lowering are refused rather than mistranslated. def refused(assembly): try: @@ -149,7 +161,8 @@ def mov(source, dst_sel, unused, src_sel): mov('-16', 'DWORD', 'UNUSED_PAD', 'BYTE_0') == 'v1 = ((0xfffffff0u >> 0u) & 0xffu);') check('v_mov UNUSED_SEXT with a DWORD destination has no unused bits', mov('v2', 'DWORD', 'UNUSED_SEXT', 'WORD_0') == 'v1 = ((v2 >> 0u) & 0xffffu);') -check('v_mov whole lane mask is the plain move', mov('exec_lo', 'DWORD', 'UNUSED_PAD', 'DWORD') == 'v1 = exec;') +check('v_mov whole lane mask refused', + mov('exec_lo', 'DWORD', 'UNUSED_PAD', 'DWORD') == 'refused: v_mov_b32 data operand exec_lo is a lane mask') check('v_mov UNUSED_SEXT with a sub-dword destination refused', refused_as('v_mov_b32_sdwa v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:DWORD', 'SDWA UNUSED_SEXT')) check('v_mov clamp refused', refused_as('v_mov_b32_sdwa v1, v2 clamp dst_sel:DWORD dst_unused:UNUSED_PAD ' @@ -172,4 +185,4 @@ def mov(source, dst_sel, unused, src_sel): for text in failures: print(' ' + text) sys.exit(1) -print('PASS') \ No newline at end of file +print('PASS') diff --git a/tests/startup_gfx2hlsl_sdwa_cndmask_check.py b/tests/startup_gfx2hlsl_sdwa_cndmask_check.py new file mode 100644 index 0000000000..82209cb5f8 --- /dev/null +++ b/tests/startup_gfx2hlsl_sdwa_cndmask_check.py @@ -0,0 +1,291 @@ +"""The SDWA form of v_cndmask_b32 in tools/startup/gfx2hlsl.py, drawn on a GPU. + + (no arguments) fixture and model controls, pure Python + binary <llvm-mc> assemble the fixture with LLVM 15 (-mcpu=gfx1013) and require its words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the 16 x 16 pixel fixture (FXC ps_5_1 when given, and DXC ps_6_0), + draw and compare all 1,024 exported words with the model, then require + each mutated shader to fail against the model and match its own + +The VOP2 select in SDWA form reads its lane mask from VCC, printed as the fourth operand. Each source takes its +src0_sel/src1_sel field, zero-extended or sign-extended under sext(), the select picks src1 where the lane's VCC +bit is set and src0 elsewhere, and dst_sel/dst_unused place the low bits of the result. These are the integer SDWA +rules the other forms already use (sdwa_source/sdwa_dest); the draw shows a desktop GPU computing the translated +select, not that the console does. + +The render target is R32G32B32A32_FLOAT, so every exported word must be a normal binary32 value: each select writes +a byte or word of a register that holds 1.0 (0x3f800000) under UNUSED_PRESERVE, which keeps the exponent normal. +The test asserts this, and that both VCC states occur. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + +WIDTH = HEIGHT = 16 +MULTIPLIER = 0x9B5D +ONE = 0x3F800000 +PACKED_INPUT = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: packed screen position x | (y << 16) in v0 + +SEL = {'BYTE_0': 0, 'BYTE_1': 1, 'BYTE_2': 2, 'BYTE_3': 3, 'WORD_0': 4, 'WORD_1': 5, 'DWORD': 6} +UNUSED = {'UNUSED_PAD': 0, 'UNUSED_SEXT': 1, 'UNUSED_PRESERVE': 2} +VOP2_CNDMASK_B32 = 1 + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(detail) + + +def encode_cndmask_sdwa(vdst, src0, src1, *, src0_sel, src1_sel, dst_sel, dst_unused='UNUSED_PRESERVE', + src0_sext=0, src1_sext=0): + """VOP2 SDWA (GFX10 VOP_SDWA9Ae): w0 [30:25] opcode, [24:17] vdst, [16:9] VGPR src1, [8:0] = 249; + w1 [7:0] VGPR src0, [10:8] dst_sel, [12:11] dst_unused, [18:16] src0_sel, [19] src0_sext, + [26:24] src1_sel, [27] src1_sext.""" + w0 = (VOP2_CNDMASK_B32 << 25) | (vdst << 17) | (src1 << 9) | 249 + w1 = (src0 | (SEL[dst_sel] << 8) | (UNUSED[dst_unused] << 11) | (SEL[src0_sel] << 16) | (src0_sext << 19) + | (SEL[src1_sel] << 24) | (src1_sext << 27)) + return struct.pack('<II', w0, w1) + + +# One select per exported channel: (vdst, src0, src0 sext, src0_sel, src1, src1 sext, src1_sel, dst_sel). +SELECTS = ( + (2, 0, 0, 'WORD_0', 1, 0, 'BYTE_1', 'WORD_0'), + (3, 1, 1, 'BYTE_2', 0, 0, 'WORD_1', 'WORD_0'), + (4, 1, 0, 'BYTE_3', 1, 0, 'WORD_0', 'BYTE_1'), + (5, 1, 0, 'BYTE_1', 0, 0, 'BYTE_0', 'BYTE_2'), +) + + +def assembly(select): + vdst, s0, x0, sel0, s1, x1, sel1, dst = select + a = 'sext(v%d)' % s0 if x0 else 'v%d' % s0 + b = 'sext(v%d)' % s1 if x1 else 'v%d' % s1 + return ('v_cndmask_b32_sdwa v%d, %s, %s, vcc_lo dst_sel:%s dst_unused:UNUSED_PRESERVE src0_sel:%s src1_sel:%s' + % (vdst, a, b, dst, sel0, sel1)) + + +# Constructed gfx1013 pixel stage (LLVM 15 assembles each line to these words; see `binary`): +# v_mul_u32_u24_e32 v1, 0x9b5d, v0 +# v_mov_b32_e32 v2..v5, 1.0 +# v_cmp_gt_u32_e32 vcc_lo, 0x80000000, v1 (VCC: bit 31 of v1 clear) +# the four selects above +# exp mrt0 v2, v3, v4, v5 done vm +# s_endpgm +PROGRAM = ( + [('v_mul_u32_u24_e32 v1, 0x9b5d, v0', struct.pack('<II', (0x0B << 25) | (1 << 17) | 255, MULTIPLIER))] + + [('v_mov_b32_e32 v%d, 1.0' % v, struct.pack('<I', 0x7E000000 | (v << 17) | (1 << 9) | 242)) for v in (2, 3, 4, 5)] + + [('v_cmp_gt_u32_e32 vcc_lo, 0x80000000, v1', struct.pack('<II', 0x7C000000 | (0xC4 << 17) | (1 << 9) | 255, + 0x80000000))] + + [(assembly(s), encode_cndmask_sdwa(s[0], s[1], s[4], src0_sel=s[3], src1_sel=s[6], dst_sel=s[7], + src0_sext=s[2], src1_sext=s[5])) for s in SELECTS] + + [('exp mrt0 v2, v3, v4, v5 done vm', bytes.fromhex('0f1800f802030405')), + ('s_endpgm', bytes.fromhex('000081bf'))] +) +PS_WORDS = b''.join(raw for _, raw in PROGRAM) + +# The model of the hardware, and the wrong variants each mutation implements. +MODES = ('swapped operands', 'mask ignored', 'mask inverted', 'dropped sext', 'neighbouring byte', + 'wrong destination byte') + + +def field(value, sel, sext): + shift, 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)}[sel] + part = (value >> shift) & ((1 << width) - 1) + if sext and width < 32 and part >> (width - 1): + part |= (0xFFFFFFFF << width) & 0xFFFFFFFF + return part + + +def place(old, result, sel, preserve): + shift, 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)}[sel] + mask = ((1 << width) - 1) << shift + return ((old & ~mask) if preserve else 0) & 0xFFFFFFFF | ((result << shift) & mask) + + +def lanes(): + for y in range(HEIGHT): + for x in range(WIDTH): + v0 = x | (y << 16) + v1 = (v0 & 0xFFFFFF) * MULTIPLIER & 0xFFFFFFFF + yield v0, v1, 0x80000000 > v1 + + +def expected_pixel_words(mode='reference'): + words = [] + for v0, v1, vcc in lanes(): + regs = {0: v0, 1: v1} + for channel, (_, s0, x0, sel0, s1, x1, sel1, dst) in enumerate(SELECTS): + if mode == 'dropped sext' and channel == 1: + x0 = 0 + if mode == 'neighbouring byte' and channel == 3: + sel0 = 'BYTE_2' + if mode == 'wrong destination byte' and channel == 2: + dst = 'BYTE_0' + a, b = field(regs[s0], sel0, x0), field(regs[s1], sel1, x1) + if mode == 'swapped operands' and channel == 0: + a, b = b, a + lane = (not vcc) if (mode == 'mask inverted' and channel == 2) else vcc + picked = a if (mode == 'mask ignored' and channel == 3) else (b if lane else a) + words.append(place(ONE, picked, dst, True)) + return words + + +def normal_or_zero(word): + exponent = (word >> 23) & 0xFF + return word & 0x7FFFFFFF == 0 or 0 < exponent < 0xFF + + +def pixel_hlsl(mode='reference'): + text = G.Pipeline(VS_WORDS, PS_WORDS, root_blob(), ps_hw_inputs=PACKED_INPUT).hlsl_ps() + if mode == 'reference': + return text + # Each mutation edits one select statement of the translated shader. + lines = text.split('\n') + targets = {'swapped operands': 'v2', 'dropped sext': 'v3', 'mask inverted': 'v4', 'wrong destination byte': 'v4', + 'neighbouring byte': 'v5', 'mask ignored': 'v5'} + register = targets[mode] + found = [i for i, line in enumerate(lines) if re.match(r'\s*(uint\s+)?%s\s*=.*\?' % register, line)] + assert len(found) == 1, (mode, found, text) + i = found[0] + line = lines[i] + edited = { + 'swapped operands': lambda s: re.sub(r'\? (\(\(v1 >> 8u\) & 0xffu\)) : (\(\(v0 >> 0u\) & 0xffffu\))', + r'? \2 : \1', s), + 'mask inverted': lambda s: re.sub(r'\((\w+) & 1\) \? ', r'((\1 & 1) ^ 1) ? ', s), + 'dropped sext': lambda s: s.replace('asuint(asint(v1 << 8u) >> 24u)', '((v1 >> 16u) & 0xffu)'), + 'wrong destination byte': lambda s: s.replace('& 0xffff00ffu', '& 0xffffff00u').replace( + '& 0xffu) << 8u)', '& 0xffu) << 0u)'), + 'neighbouring byte': lambda s: s.replace(': ((v1 >> 8u) & 0xffu)', ': ((v1 >> 16u) & 0xffu)'), + 'mask ignored': lambda s: re.sub(r'\(\w+ & 1\) \? ', '(0u & 1) ? ', s), + }[mode](line) + assert edited != line, (mode, line) + lines[i] = edited + return '\n'.join(lines) + + +def controls(): + states = [vcc for _, _, vcc in lanes()] + check('both VCC states occur in at least 64 pixels each', min(states.count(True), states.count(False)) >= 64, + 'set in %d of %d pixels' % (states.count(True), len(states))) + reference = expected_pixel_words() + check('every reference word is a normal binary32 value', all(normal_or_zero(w) for w in reference)) + for mode in MODES: + model = expected_pixel_words(mode) + check(f'model ({mode}) differs from the reference', model != reference) + check(f'model ({mode}) words are normal binary32 values', all(normal_or_zero(w) for w in model)) + # Every channel of every mutated model differs in at least one pixel of its own channel only. + for mode in MODES: + model = expected_pixel_words(mode) + channels = {i % 4 for i, (a, b) in enumerate(zip(reference, model)) if a != b} + check(f'model ({mode}) changes one channel', len(channels) == 1, str(channels)) + try: + text = pixel_hlsl() + except G.Unsupported as error: + check('the fixture translates', False, str(error)) + return + check('the fixture translates', True) + print(text) + for mode in MODES: + try: + pixel_hlsl(mode) + check(f'mutation ({mode}) applies to the translated shader', True) + except AssertionError as error: + check(f'mutation ({mode}) applies to the translated shader', False, repr(error)) + + +def check_binary(llvm_mc): + source = '\n'.join(text for text, _ in PROGRAM) + '\n' + proc = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-show-encoding'], + input=source, capture_output=True, text=True, check=True) + built = bytearray() + for line in proc.stdout.splitlines(): + m = re.search(r'encoding: \[([^\]]*)\]', line) + if m: + built += bytes(int(b, 16) for b in m.group(1).split(',')) + check('the fixture words match llvm-mc', bytes(built) == PS_WORDS, + 'llvm-mc %s\nfixture %s' % (bytes(built).hex(), PS_WORDS.hex())) + printed = [line.split(';')[0].strip() for line in proc.stdout.splitlines() if 'v_cndmask_b32_sdwa' in line] + check('llvm-mc prints each select as written', printed == [assembly(s) for s in SELECTS], '\n'.join(printed)) + + +def run_pixel_words(renderer, adapter, vs, ps, expected_path): + run = subprocess.run( + [renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), str(expected_path)], + capture_output=True, + text=True, + ) + if run.returncode == 77: + print(run.stdout + run.stderr, end='', flush=True) + sys.exit(1 if failures else 77) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + ref_words = expected_pixel_words('reference') + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + out_dir = HERE.parent / 'out' + out_dir.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix='sdwa-cndmask-', dir=out_dir) as tmp: + directory = Path(tmp) + ref_bin = directory / 'reference.bin' + ref_bin.write_bytes(struct.pack('<%dI' % len(ref_words), *ref_words)) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, f'vs_{kind}', vs_profile, directory) + ps = compile_hlsl(compiler, kind, pixel_hlsl('reference'), f'ps_ref_{kind}', ps_profile, directory) + run = run_pixel_words(renderer, adapter, vs, ps, ref_bin) + check(f'{kind} ({adapter}): 16x16 pixel draw matches all 1,024 model words', + run.returncode == 0, run.stdout + run.stderr) + print(run.stdout, end='', flush=True) + for idx, mode in enumerate(MODES): + mut_ps = compile_hlsl(compiler, kind, pixel_hlsl(mode), f'ps_mut_{idx}_{kind}', ps_profile, directory) + fail_run = run_pixel_words(renderer, adapter, vs, mut_ps, ref_bin) + check(f'{kind} ({adapter}) mutation ({mode}) fails against the model', + fail_run.returncode != 0, fail_run.stdout + fail_run.stderr) + mut_words = expected_pixel_words(mode) + mut_bin = directory / f'mut_{idx}.bin' + mut_bin.write_bytes(struct.pack('<%dI' % len(mut_words), *mut_words)) + own_run = run_pixel_words(renderer, adapter, vs, mut_ps, mut_bin) + check(f'{kind} ({adapter}) mutation ({mode}) matches its own model', + own_run.returncode == 0, own_run.stdout + own_run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + check_binary(sys.argv[2]) + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_sgpr_spill_check.py b/tests/startup_gfx2hlsl_sgpr_spill_check.py index 5f4d8ef9d1..4d831c5f08 100644 --- a/tests/startup_gfx2hlsl_sgpr_spill_check.py +++ b/tests/startup_gfx2hlsl_sgpr_spill_check.py @@ -165,7 +165,9 @@ def controls(): ('read of a lane nothing wrote', ['v_writelane_b32 v10, s0, 3', 'v_readlane_b32 s1, v10, 4']), ('read of another VGPR at the written lane', ['v_writelane_b32 v10, s0, 3', 'v_readlane_b32 s1, v11, 3']), ('lane chosen by an SGPR', ['v_writelane_b32 v10, s0, s2', 'v_readlane_b32 s1, v10, 3']), - ('lane 32', ['v_writelane_b32 v10, s0, 32']), + ('lane 64', ['v_writelane_b32 v10, s0, 64']), + ('lanes 8 and 40 of one VGPR (one slot in wave32, two in wave64)', + ['v_writelane_b32 v10, s0, 8', 'v_writelane_b32 v10, s1, 40', 'v_readlane_b32 s2, v10, 8']), ('lane mask value (vcc_lo)', ['v_writelane_b32 v10, vcc_lo, 3']), ('lane mask value (exec_lo)', ['v_writelane_b32 v10, exec_lo, 3']), ('destination outside the plain SGPRs', ['v_writelane_b32 v10, s0, 3', 'v_readlane_b32 vcc_lo, v10, 3']), @@ -178,7 +180,11 @@ def controls(): for label, program in cases: reason = refused(program) check('refused: %s (%s)' % (label, reason), reason is not None) - check('refused: vertex stage (%s)' % refused(ok, kind='vs'), refused(ok, kind='vs') is not None) + check('a vertex stage is accepted', refused(ok, kind='vs') is None, str(refused(ok, kind='vs'))) + check('a compute stage is accepted', refused(ok, kind='cs') is None, str(refused(ok, kind='cs'))) + check('refused: a kind outside pixel, vertex, mesh and compute (%s)' % refused(ok, kind='gs'), refused(ok, kind='gs') is not None) + wave64 = ['v_writelane_b32 v10, s0, 40', 'v_writelane_b32 v10, s1, 63', 'v_readlane_b32 s2, v10, 40'] + check('wave64 lanes 40 and 63 are accepted', refused(wave64) is None, str(refused(wave64))) check('refused: a shader with branches (%s)' % refused(ok, branches=True), refused(ok, branches=True) is not None) # 5. The reload keeps the constant the write stored, so later scalar folding sees the same word. diff --git a/tests/startup_gfx2hlsl_shift64_check.py b/tests/startup_gfx2hlsl_shift64_check.py index 71a51c295c..83f6882f2a 100644 --- a/tests/startup_gfx2hlsl_shift64_check.py +++ b/tests/startup_gfx2hlsl_shift64_check.py @@ -232,7 +232,7 @@ def controls(): % (op, corrupted_hi, new_hi), corrupted_hi != new_hi) # Accepted operand forms (VGPR pair, unaligned VGPR pair, _e64 spelling, aligned SGPR pair, inline -16..64, - # SGPR/literal/m0/vcc_lo/exec_lo shift count) and inline sign-extension check. + # SGPR/literal/m0 shift count) and inline sign-extension check. accepted = [ 'v_lshrrev_b64 v[0:1], v2, v[4:5]', 'v_lshrrev_b64_e64 v[1:2], v0, v[1:2]', @@ -240,8 +240,6 @@ def controls(): 'v_ashrrev_i64 v[0:1], v2, s[4:5]', 'v_lshrrev_b64 v[0:1], 0x80000020, v[2:3]', 'v_lshrrev_b64 v[0:1], m0, v[2:3]', - 'v_lshrrev_b64 v[0:1], vcc_lo, v[2:3]', - 'v_lshrrev_b64 v[0:1], exec_lo, v[2:3]', 'v_lshrrev_b64 v[0:1], 32, -1', 'v_lshlrev_b64 v[0:1], 1, 64', 'v_ashrrev_i64 v[0:1], 1, -16', @@ -313,13 +311,14 @@ def controls(): 'v_lshrrev_b64 v[0:1], v2, v[255:256]', 'v_lshrrev_b64 v[0:1], v2, vcc', 'v_lshrrev_b64 v[0:1], v2, exec', - 'v_lshrrev_b64 v[0:1], v2, 0x41', 'v_lshrrev_b64 v[0:1], v2, 65', 'v_lshrrev_b64 v[0:1], v2, -17', 'v_lshrrev_b64 v[0:1], v2, 1.0', 'v_lshrrev_b64 v[0:1]', 'v_lshrrev_b64 v[0:1], v2', 'v_lshrrev_b64 v[0:1], v2, v[4:5], v6', + 'v_lshrrev_b64 v[0:1], vcc_lo, v[2:3]', # a wave mask is not a shift count in the one-lane model + 'v_lshrrev_b64 v[0:1], exec_lo, v[2:3]', ] check('modifiers, invalid operands and wrong counts refused (%d cases)' % len(refusals), all(refused(a) for a in refusals)) diff --git a/tests/startup_gfx2hlsl_shift64_literal_check.py b/tests/startup_gfx2hlsl_shift64_literal_check.py new file mode 100644 index 0000000000..c6abbcb27c --- /dev/null +++ b/tests/startup_gfx2hlsl_shift64_literal_check.py @@ -0,0 +1,60 @@ +"""32-bit hex literal as the 64-bit source of v_lshlrev_b64, v_lshrrev_b64 and v_ashrrev_i64 (Refs #1723). + +A literal fills the low word. The high word is zero for the unsigned shifts and copies bit 31 for the signed +shift (the rule of s_mov_b64; the scalar shifts and bitfield extracts take it from this change). Pure Python; run with no arguments. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import startup_gfx2hlsl_scalar_m0_check as M # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe, check, refused # noqa: E402 + +# (operation, helper, literal, expected low word, expected high word) +CASES = ( + ('v_lshlrev_b64', 'shl64', '0x41', '65u', '0u'), + ('v_lshrrev_b64', 'shr64u', '0x80000000', '2147483648u', '0u'), + ('v_lshrrev_b64', 'shr64u', '0xffffffff', '4294967295u', '0u'), + ('v_ashrrev_i64', 'shr64i', '0x7fffffff', '2147483647u', '0u'), + ('v_ashrrev_i64', 'shr64i', '0x80000000', '2147483648u', '4294967295u'), + ('v_ashrrev_i64', 'shr64i', '0xffffffff', '4294967295u', '4294967295u'), +) + + +def lowered(op, literal): + probe = Probe() + probe.one(op, '%s v[0:1], v2, %s' % (op, literal)) + return probe.lines + + +def scalar_lowered(opcode): + """s_<op> s[20:21], 0xffffffff, s9 as encoded (SOP2, source 255 plus a literal dword).""" + stage = M.run_seq(M.encode_sop2(opcode, 20, 255, 9) + struct.pack('<I', 0xffffffff)) + return [line for line in stage.lines if 'shr64' in line or 'bfe64' in line] + + +def main(): + check('s_ashr_i64 literal 0xffffffff is sign-extended', + scalar_lowered(0x23)[0].startswith('{ uint2 t = shr64i(4294967295u, 4294967295u, s9);')) + check('s_lshr_b64 literal 0xffffffff is zero-extended', + scalar_lowered(0x21)[0].startswith('{ uint2 t = shr64u(4294967295u, 0u, s9);')) + check('s_bfe_i64 literal 0xffffffff is sign-extended', + 'bfe64(4294967295u, 4294967295u, s9, 1u)' in scalar_lowered(0x2a)[0]) + check('s_bfe_u64 literal 0xffffffff is zero-extended', + 'bfe64(4294967295u, 0u, s9, 0u)' in scalar_lowered(0x29)[0]) + for op, helper, literal, low, high in CASES: + want = ['{ uint2 t = %s(%s, %s, v2); v0 = t.x; v1 = t.y; }' % (helper, low, high)] + check('%s with literal %s' % (op, literal), lowered(op, literal) == want) + check('literals wider than 32 bits stay refused', + all(refused('%s v[0:1], v2, 0x100000000' % op) for op in ('v_lshlrev_b64', 'v_ashrrev_i64'))) + check('a hex literal stays refused as the addend of v_mad_u64_u32 and v_mad_i64_i32', + all(refused('%s v[0:1], vcc_lo, v2, v3, 0x41' % op) for op in ('v_mad_u64_u32', 'v_mad_i64_i32'))) + check('a literal is not accepted as a destination or in the wrong operand count', + refused('v_lshrrev_b64 0x41, v2, v[4:5]') and refused('v_lshrrev_b64 v[0:1], 0x41')) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_sopk_accum_check.py b/tests/startup_gfx2hlsl_sopk_accum_check.py index 4f92dd3528..bc689e701f 100644 --- a/tests/startup_gfx2hlsl_sopk_accum_check.py +++ b/tests/startup_gfx2hlsl_sopk_accum_check.py @@ -290,7 +290,11 @@ def load_mutant(old, new): ('no mask refusal', "if d in self.masks or self.sym.get(d, ('',))[0] == 'execcopy':", 'if False:'), ('no descriptor refusal', - "if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'):", 'if False:'), + # Pin the sopk-only raise (uses `base`); other SOP1 ports share the same sym allow-list line. + "if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'):\n" + " raise Unsupported('%s on %s data' % (base, sym[0]))", + "if False:\n" + " raise Unsupported('%s on %s data' % (base, sym[0]))"), ('lowering removed', 'def op_s_addk_i32(self, ops, mods):', 'def op_unused_addk(self, ops, mods):'), ] diff --git a/tests/startup_gfx2hlsl_spill_branches_check.py b/tests/startup_gfx2hlsl_spill_branches_check.py new file mode 100644 index 0000000000..5ae651d3aa --- /dev/null +++ b/tests/startup_gfx2hlsl_spill_branches_check.py @@ -0,0 +1,390 @@ +"""SGPR spill to VGPR lanes across branches in the pixel stage of tools/startup/gfx2hlsl.py (#2125). + +`v_writelane_b32 vN, sM, k` parks a scalar in lane k of vN and `v_readlane_b32 sD, vN, k` reads it back; both ignore +EXEC (AMD RDNA 2 ISA reference, VOP3 lane operations). The translator keeps one scalar per (vN, k). In a program with +branches that scalar is assigned on the pixel's own path, while the hardware slot holds the last write on the wave's +path. A read is accepted when a write of its (VGPR, lane) reaches it on every path (forward must-dataflow: +intersection at joins, fixed point through loops) and no write that can supply it lies where the wave can run it +while this pixel skips it: inside the region of a branch not proven uniform that the read is outside, or, when several +writes can supply the read, inside any such region. + +Synthetic programs only, translated through Stage.translate(). Every refusal has a negative control, and the +translator mutations at the end (union instead of intersection, one pass instead of the fixed point, each region rule +removed) must each turn a control red. + + (no arguments) pure Python + binary <llvm-mc> the draw fixtures assemble to their words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] both uniform choices drawn, read back, opposite arm refused +""" +import re +import struct +import subprocess +import sys +import tempfile +import types +from pathlib import Path +from types import SimpleNamespace + +HERE = Path(__file__).resolve().parent +TOOLS = HERE.parent / 'tools' +sys.path.insert(0, str(TOOLS)) +sys.path.insert(0, str(TOOLS / 'startup')) +import gfx2hlsl as G # noqa: E402 +sys.path.insert(0, str(HERE)) +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +def program(text): + """Assembly text with `Name:` labels -> decoded (offset, size, name, text) tuples, four bytes each.""" + lines = [line.strip() for line in text.strip().splitlines()] + labels, offset = {}, 0 + for line in lines: + if line.endswith(':'): + labels[line[:-1]] = offset + else: + offset += 4 + decoded, offset = [], 0 + for line in lines: + if not line.endswith(':'): + line = re.sub(r'\bL\w+\b', lambda m: 'label_%x' % labels[m[0]], line) + decoded.append((offset, 4, line.split(' ', 1)[0], line)) + offset += 4 + return decoded + + +def translate(text, module=G): + """-> (refusal reasons, emitted lines in block order).""" + refusals = [] + stage = module.Stage(SimpleNamespace(root={'params': [], 'flags': 0}), 'ps', b'', refusals=refusals, + decoded=program(text)) + return [reason for reason, _ in refusals], [line for _, lines, _ in stage.blocks for line in lines] + + +# s3 is an entry scalar, so `s_cmp_eq_u32 s2, s3` is a uniform SCC branch; s_cbranch_execz is never proven uniform. +ACCEPTED = { + 'two arms of a uniform branch, each writing a different constant': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Lelse + v_writelane_b32 v10, 7, 3 + s_branch Ljoin + Lelse: + v_writelane_b32 v10, 9, 3 + Ljoin: + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + s_endpgm''', ['sp10_3 = 0x00000007u;', 'sp10_3 = 0x00000009u;', 's1 = sp10_3;', 'v1 = s1;']), + 'two arms of a uniform branch writing the same constant keep it': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Lelse + v_writelane_b32 v10, 7, 3 + s_branch Ljoin + Lelse: + v_writelane_b32 v10, 7, 3 + Ljoin: + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + s_endpgm''', ['sp10_3 = 0x00000007u;', 'sp10_3 = 0x00000007u;', 's1 = sp10_3;', 'v1 = 0x00000007u;']), + 'write before a non-uniform branch, read inside its region and after the join': (''' + v_writelane_b32 v10, s3, 3 + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Ljoin + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + Ljoin: + s_or_b32 exec_lo, exec_lo, s4 + v_readlane_b32 s5, v10, 3 + v_mov_b32 v2, s5 + s_endpgm''', ['sp10_3 = s3;', 's1 = sp10_3;', 'if (exec & 1) v1 = s1;', 's5 = sp10_3;', + 'if (exec & 1) v2 = s5;']), + 'write and read inside the same non-uniform region': (''' + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Ljoin + v_writelane_b32 v10, s3, 3 + s_mov_b32 s3, 0 + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + Ljoin: + s_or_b32 exec_lo, exec_lo, s4 + s_endpgm''', ['sp10_3 = s3;', 's1 = sp10_3;', 'if (exec & 1) v1 = s1;']), + 'a lane spelled 0x3 overwrites lane 3': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Ljoin + Ljoin: + v_writelane_b32 v10, 7, 3 + v_writelane_b32 v10, 9, 0x3 + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + s_endpgm''', ['sp10_3 = 0x00000007u;', 'sp10_3 = 0x00000009u;', 's1 = sp10_3;', 'v1 = 0x00000009u;']), + 'write before a uniform loop, read in the body and after it': (''' + v_writelane_b32 v10, s3, 3 + s_mov_b32 s2, 0 + Lloop: + v_readlane_b32 s1, v10, 3 + s_add_u32 s2, s2, 1 + s_cmp_lt_u32 s2, 4 + s_cbranch_scc1 Lloop + v_readlane_b32 s5, v10, 3 + v_mov_b32 v1, s5 + s_endpgm''', ['sp10_3 = s3;', 's1 = sp10_3;', 's5 = sp10_3;', 'v1 = s5;']), +} + +REFUSED = { + 'a write on one arm only (no write on some path)': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Ljoin + v_writelane_b32 v10, 7, 3 + Ljoin: + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 with no v_writelane_b32 of it on some path'), + 'another lane on the other arm': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Lelse + v_writelane_b32 v10, 7, 3 + s_branch Ljoin + Lelse: + v_writelane_b32 v10, 7, 4 + Ljoin: + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 with no v_writelane_b32 of it on some path'), + 'a later write in a uniform loop reaches the loop head (loop-carried)': (''' + v_writelane_b32 v10, 7, 3 + s_mov_b32 s2, 0 + Lloop: + v_readlane_b32 s1, v10, 3 + v_mov_b32 v1, s1 + v_writelane_b32 v10, 9, 3 + s_add_u32 s2, s2, 1 + s_cmp_lt_u32 s2, 4 + s_cbranch_scc1 Lloop + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 written later in a loop (loop-carried)'), + 'the only write inside a non-uniform loop, read after it': (''' + s_mov_b32 s2, 0 + Lloop: + v_writelane_b32 v10, s2, 3 + s_add_u32 s2, s2, 1 + v_cmp_gt_u32 vcc_lo, s2, v0 + s_cbranch_vccnz Lloop + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 outside the region of the branch at 0x10 that writes it, ' + 'which is not proven uniform'), + 'a write before and a write inside a non-uniform region, read after the join': (''' + v_writelane_b32 v10, s3, 3 + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Ljoin + v_writelane_b32 v10, 9, 3 + Ljoin: + s_or_b32 exec_lo, exec_lo, s4 + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 joins 2 writes of v10 lane 3, one inside the region of the branch at 0x8, which ' + 'is not proven uniform'), + 'two arms of a non-uniform branch rejoining inside an outer non-uniform region': (''' + s_and_saveexec_b32 s4, vcc_lo + s_cbranch_execz Lend + v_writelane_b32 v10, 7, 3 + s_cbranch_vccz Lelse + v_writelane_b32 v10, 9, 3 + Lelse: + v_readlane_b32 s1, v10, 3 + Lend: + s_or_b32 exec_lo, exec_lo, s4 + s_endpgm''', 'v_readlane_b32 joins 2 writes of v10 lane 3, one inside the region of the branch at 0x4, which ' + 'is not proven uniform'), + 'the reaching write was refused': (''' + s_mov_b32 s2, 5 + s_cmp_eq_u32 s2, s3 + s_cbranch_scc0 Ljoin + Ljoin: + v_writelane_b32 v10, vcc_lo, 3 + v_readlane_b32 s1, v10, 3 + s_endpgm''', 'v_readlane_b32 reads v10 lane 3 from a v_writelane_b32 that was not translated'), +} + + +def controls(module=G, quiet=False): + """-> labels of the controls that failed against `module`.""" + failed = [] + for label, (text, want) in ACCEPTED.items(): + reasons, lines = translate(text, module) + ok = not reasons and [line for line in lines if re.match(r'(if \(exec & 1\) )?(sp\d|s1 |s5 |v[12] )', line)] == want + failed += [] if ok else ['accepted: ' + label] + if not quiet: + check('accepted: %s' % label, ok, '%s %s' % (reasons, lines)) + for label, (text, want) in REFUSED.items(): + reasons, _ = translate(text, module) + ok = want in reasons + failed += [] if ok else ['refused: ' + label] + if not quiet: + check('refused: %s' % label, ok, str(reasons)) + return failed + + +MUTATIONS = { + 'union instead of intersection at joins': ( + '{k: into[t][k] | state[k] for k in into[t].keys() & state.keys()}', + '{k: into[t].get(k, frozenset()) | state.get(k, frozenset()) for k in into[t].keys() | state.keys()}'), + 'one pass instead of the fixed point': ( + ' while changed:\n changed = False\n for b, (lo, hi) in enumerate(bounds):\n', + ' for changed in [False]:\n for b, (lo, hi) in enumerate(bounds):\n'), + 'lanes keyed by their spelling': ('lane = int(ops[2], 0) # 3 and 0x3', 'lane = ops[2] # 3 and 0x3'), + 'no region rule for a single write': (' if here not in blocks:\n', ' if False:\n'), + 'no region rule for joined writes': (' if len(writes) > 1:\n', ' if False:\n'), + 'every conditional branch counted as uniform': (' if off in self.uniform_branches or', + ' if True or'), +} + + +def mutated(old, new): + source = (TOOLS / 'startup' / 'gfx2hlsl.py').read_text(encoding='utf-8').replace('\r\n', '\n') + assert source.count(old) == 1, old + module = types.ModuleType('gfx2hlsl_mutant') + module.__file__ = str(TOOLS / 'startup' / 'gfx2hlsl.py') + exec(compile(source.replace(old, new), module.__file__, 'exec'), module.__dict__) + return module + + +# The same slot drawn on D3D12: two uniform branch choices write different words to v10 lane 3, the join reloads it and +# exports it OR-ed with the packed screen position. s3 is 5 (the compare s2 == s3 holds: first arm) or 6 (second arm). +WIDTH = HEIGHT = 16 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +ARM_WORDS = (0x40200000, 0x40400000) # binary32 words with no bit below 21, clear of x | y << 16 +FIXTURE_TEXT = '''s_mov_b32 s0, 0x40200000 +s_mov_b32 s1, 0x40400000 +s_mov_b32 s2, 5 +s_mov_b32 s3, %d +s_cmp_eq_u32 s2, s3 +s_cbranch_scc0 3 +v_writelane_b32 v10, s0, 3 +s_branch 2 +v_writelane_b32 v10, s1, 3 +v_readlane_b32 s5, v10, 3 +v_or_b32_e32 v1, s5, v0 +exp mrt0 v1, v1, v1, v1 done vm +s_endpgm +''' +_COMMON = (0xbe8003ff, 0x40200000, 0xbe8103ff, 0x40400000, 0xbe820385) +_TAIL = (0xbf060302, 0xbf840003, 0xd761000a, 0x00010600, 0xbf820002, 0xd761000a, 0x00010601, 0xd7600005, + 0x0001070a, 0x38020005, 0xf800180f, 0x01010101, 0xbf810000) +CHOICES = {5: ARM_WORDS[0], 6: ARM_WORDS[1]} +CHOICE_WORDS = {s3: struct.pack('<19I', *_COMMON, 0xbe830380 | s3, *_TAIL) for s3 in CHOICES} + + +def pixel_image(arm): + return [(x | y << 16) | arm for y in range(HEIGHT) for x in range(WIDTH) for _ in range(4)] + + +def check_binary(llvm_mc): + for s3 in CHOICES: + check('llvm-mc assembles the s3 == %d fixture to the same words' % s3, + assemble(llvm_mc, FIXTURE_TEXT % s3) == CHOICE_WORDS[s3]) + + +def words_file(directory, name, words): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(words), *words)) + return path + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + texts = {} + for s3, words in CHOICE_WORDS.items(): + refusals = [] + texts[s3] = G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=PACKED, refusals=refusals).hlsl_ps() + check('s3 == %d: the pixel stage translates with no refusal' % s3, not refusals, str(refusals)) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + images = {s3: words_file(directory, 'image%d' % s3, pixel_image(arm)) for s3, arm in CHOICES.items()} + for name, compiler, profile_vs, profile_ps in ( + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else [])): + vs = compile_hlsl(compiler, name, FULLSCREEN_VS, 'vs_' + name, profile_vs, directory) + for s3, text in texts.items(): + ps = compile_hlsl(compiler, name, text, 'ps_%s_%d' % (name, s3), profile_ps, directory) + run = draw(renderer, adapter, vs, ps, images[s3]) + check('%s %s s3 == %d: all %d pixels equal the selected arm' % (adapter, name, s3, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + # Negative control: the opposite arm's reference must differ from what this choice draws. + run = draw(renderer, adapter, vs, ps, images[11 - s3]) + check('%s %s s3 == %d: the opposite arm as reference fails' % (adapter, name, s3), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) != 1: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + return + controls() + # The straight-line requirement stays for a stage with no block graph (a unit probe that skips translate()). + probe = G.Stage.__new__(G.Stage) + probe.kind, probe.lines, probe.sym, probe.masks = 'ps', [], {}, set() + probe.used_s, probe.used_v, probe.uniform_v, probe.varying_s = set(), set(), set(), set() + probe.scc_uniform, probe.has_branches, probe.ins = True, True, [] + try: + probe.one('v_writelane_b32', 'v_writelane_b32 v10, s0, 3') + reason = None + except G.Unsupported as error: + reason = str(error) + check('a stage with branches and no block graph keeps the straight-line refusal (%s)' % reason, + reason == 'v_writelane_b32 needs straight-line code to prove write-before-read') + # The whole pixel stage: the slot is declared once before the blocks and assigned on each arm. + from startup_image_3d_check import VS_WORDS, root_blob + text = ACCEPTED['two arms of a uniform branch, each writing a different constant'][0].replace( + 'v_mov_b32 v1, s1', 'v_mov_b32 v1, s1\nexp mrt0 v1, v1, v1, v1 done vm') + refusals = [] + ps = G.Pipeline(VS_WORDS, b'', root_blob(), refusals=refusals, decoded={'ps': program(text)}).hlsl_ps() + want = [' uint sp10_3 = 0;', ' if (pc == 1) {', ' sp10_3 = 0x00000007u;', ' if (pc == 2) {', + ' sp10_3 = 0x00000009u;', ' if (pc == 3) {', ' s1 = sp10_3;'] + lines = ps.splitlines() + at = [lines.index(line) if line in lines else -1 for line in want] + check('pixel stage: slot declared once, assigned on both arms, read after the join', + not refusals and -1 not in at and at == sorted(at) and ps.count('uint sp10_3') == 1, '%s\n%s' % (refusals, ps)) + for label, (old, new) in MUTATIONS.items(): + red = controls(mutated(old, new), quiet=True) + check('mutation "%s" turns %d control(s) red: %s' % (label, len(red), red), bool(red)) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_spill_wave64_check.py b/tests/startup_gfx2hlsl_spill_wave64_check.py new file mode 100644 index 0000000000..11e79a1fa7 --- /dev/null +++ b/tests/startup_gfx2hlsl_spill_wave64_check.py @@ -0,0 +1,300 @@ +"""SGPR spills to VGPR lanes 32..63 (wave64) and in vertex stages, tools/startup/gfx2hlsl.py, read back from a real +D3D12 draw. + + (no arguments) translation controls and refusals, pure Python + binary <llvm-mc> assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated stages with DXC (and FXC when given), draw and compare + every exported word with the slot reference below + +`v_writelane_b32 vN, sM, k` writes SGPR sM into lane k of vN and `v_readlane_b32 sD, vN, k` reads lane k back (AMD +RDNA 2 ISA reference, VOP3 lane operations). Both ignore EXEC and touch only lane k, so with a constant k and a VGPR +no other instruction names, vN is a table of scalar slots (tests/startup_gfx2hlsl_sgpr_spill_check.py has the +lanes 0..31 pixel case). A wave64 program spills into lanes 0..63, and a vertex stage spills the same way. The +translator does not know the wave size: a wave32 program takes the lane select modulo 32, so lanes k and k + 32 of one +VGPR are one slot there and two in wave64, and that pair is refused; lane 64 and above stay refused. + +Fixtures: + PS pixel stage, slots v10[40], v10[63], v11[32], v12[33]; the SGPRs are clobbered, reloaded (v10[40] after a + second write) and ORed into the packed screen position, 16 x 16 pixels compared word by word. + VS vertex stage, slots v40[0], v40[48], v41[0]; reloads (v40[48] after a second write) go to param0, which the + flat pixel stage FLATPS exports; one pixel compared. +The reference is the last value written to (VGPR, lane), computed here by replaying the lane writes on a dictionary. +Mutations of the translated text (lane 63 read as lane 40, the overwrite ignored, another VGPR's slot) must fail. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, draw as draw_flat # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +WIDTH = HEIGHT = 16 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +PS_TEXT = '''s_mov_b32 s0, 0x40200000 +s_mov_b32 s1, 0x40400000 +s_mov_b32 s2, 4.0 +v_writelane_b32 v10, s0, 40 +v_writelane_b32 v10, s1, 63 +v_writelane_b32 v11, s2, 32 +s_or_b32 s8, s0, s1 +v_writelane_b32 v12, s8, 33 +s_mov_b32 s0, 0 +s_mov_b32 s1, 0 +s_mov_b32 s2, 0 +s_mov_b32 s8, 0 +v_readlane_b32 s3, v10, 40 +v_readlane_b32 s4, v10, 63 +v_readlane_b32 s5, v11, 32 +v_writelane_b32 v10, s5, 40 +v_readlane_b32 s6, v10, 40 +v_readlane_b32 s9, v12, 33 +v_or_b32_e32 v1, s3, v0 +v_or_b32_e32 v2, s4, v0 +v_or_b32_e32 v3, s6, v0 +v_or_b32_e32 v4, s9, v0 +exp mrt0 v1, v2, v3, v4 done vm +s_endpgm +''' +PS_WORDS = bytes.fromhex( + 'ff0380be00002040ff0381be00004040f60382be0a0061d7005001000a0061d7017e01000b0061d702400100000108880c0061d708420100' + '800380be800381be800382be800388be030060d70a510100040060d70a7f0100050060d70b4101000a0061d705500100060060d70a510100' + '090060d70c430100030002380400043806000638090008380f1800f801020304000081bf') +VS_TEXT = '''v_mov_b32_e32 v3, 0x40400000 +v_mov_b32_e32 v10, 0xc0400000 +v_cmp_eq_u32_e32 vcc_lo, 1, v0 +v_cndmask_b32_e32 v1, -1.0, v3, vcc_lo +v_cmp_eq_u32_e32 vcc_lo, 2, v0 +v_cndmask_b32_e32 v2, 1.0, v10, vcc_lo +v_mov_b32_e32 v4, 1.0 +v_mov_b32_e32 v5, 0 +s_mov_b32 s20, 0x12345678 +s_mov_b32 s21, 0x9abcdef0 +v_writelane_b32 v40, s20, 0 +v_writelane_b32 v40, s21, 48 +v_writelane_b32 v41, s21, 0 +s_mov_b32 s20, 0 +s_mov_b32 s21, 0 +v_readlane_b32 s22, v40, 0 +v_readlane_b32 s23, v40, 48 +v_readlane_b32 s24, v41, 0 +v_writelane_b32 v40, s22, 48 +v_readlane_b32 s25, v40, 48 +v_mov_b32_e32 v11, s22 +v_mov_b32_e32 v12, s23 +v_mov_b32_e32 v13, s24 +v_mov_b32_e32 v14, s25 +exp pos0 v1, v2, v5, v4 done +exp param0 v11, v12, v13, v14 +s_endpgm +''' +VS_FIXTURE = bytes.fromhex( + 'ff02067e00004040ff02147e000040c08100847df30602028200847df2140402f202087e80020a7eff0394be78563412ff0395bef0debc9a' + '280061d714000100280061d715600100290061d715000100800394be800395be160060d728010100170060d728610100180060d729010100' + '280061d716600100190060d7286101001602167e1702187e18021a7e19021c7ecf0800f8010205040f0200f80b0c0d0e000081bf') +FLAT_PS_TEXT = '''s_mov_b32 m0, s2 +v_interp_mov_f32_e32 v0, p0, attr0.x +v_interp_mov_f32_e32 v1, p0, attr0.y +v_interp_mov_f32_e32 v2, p0, attr0.z +v_interp_mov_f32_e32 v3, p0, attr0.w +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm +''' +FLAT_PS_WORDS = bytes.fromhex('0203fcbe020002c8020106c802020ac802030ec80f1800f800010203000081bf') + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + str(detail)[:1500])) + if not ok: + failures.append(label) + + +# ---- reference: replay the lane writes and reads on a dictionary ------------------------------------------------------ +def replay(text, outputs): + lanes, scalars = {}, {} + for line in text.splitlines(): + op, _, rest = line.partition(' ') + args = [a.strip() for a in rest.split(',')] + if op == 's_mov_b32': + scalars[args[0]] = 0x40800000 if args[1] == '4.0' else int(args[1], 0) + elif op == 's_or_b32': + scalars[args[0]] = scalars[args[1]] | scalars[args[2]] + elif op == 'v_writelane_b32': + lanes[(args[0], int(args[2]))] = scalars[args[1]] + elif op == 'v_readlane_b32': + scalars[args[0]] = lanes[(args[1], int(args[2]))] + return [scalars[r] for r in outputs] + + +PS_SLOTS = replay(PS_TEXT, ('s3', 's4', 's6', 's9')) +VS_SLOTS = replay(VS_TEXT, ('s22', 's23', 's24', 's25')) + + +def ps_image(): + return [(x | y << 16) | value for y in range(HEIGHT) for x in range(WIDTH) for value in PS_SLOTS] + + +def ps_text(): + return G.Pipeline(VS_WORDS, PS_WORDS, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + + +def vs_pipeline(): + return G.Pipeline(VS_FIXTURE, FLAT_PS_WORDS, root_blob()) + + +def mutate(text, old, new): + mutated = re.sub(old, new, text) + assert mutated != text, old + return mutated + + +# Each wrong lowering, written on the folded text (a constant slot folds into the export). +PS_MUTATIONS = { + 'lane 63 reads lane 40 of the same VGPR': (r'v2 = 0x40400000u', 'v2 = 0x40200000u'), + 'the overwritten slot keeps its first value': (r'sp10_40 = s5;', 'sp10_40 = sp10_40;'), + 'v11 lane 32 reads v10 lane 40': (r'= sp11_32;', '= sp10_40;'), +} +VS_MUTATIONS = { + 'lane 48 reads lane 0 of the same VGPR': (r'v12 = 0x9abcdef0u', 'v12 = 0x12345678u'), + 'the overwritten slot keeps its first value': (r'v14 = 0x12345678u', 'v14 = 0x9abcdef0u'), +} + + +# ---- controls --------------------------------------------------------------------------------------------------------- +def refused(program, kind='ps'): + stage = G.Stage.__new__(G.Stage) + stage.kind, stage.lines, stage.sym = kind, [], {} + stage.used_s, stage.used_v, stage.uniform_v, stage.varying_s = set(), set(), set(), set() + stage.scc_uniform, stage.exec_known, stage.has_branches, stage.blocks, stage.masks = True, True, False, [], set() + stage.ins = [(4 * i, 1, re.sub(r'_e(32|64)$', '', a.split(' ', 1)[0]), a) for i, a in enumerate(program)] + for _, _, name, asm in stage.ins: + try: + stage.one(name, asm) + except G.Unsupported as reason: + return str(reason) + return None + + +def controls(): + check('pixel reference: v10[40], v10[63], v10[40] after the overwrite with v11[32], and the derived word', + PS_SLOTS == [0x40200000, 0x40400000, 0x40800000, 0x40600000], [hex(v) for v in PS_SLOTS]) + check('vertex reference: v40[0], v40[48], v41[0], v40[48] after the overwrite', + VS_SLOTS == [0x12345678, 0x9abcdef0, 0x9abcdef0, 0x12345678], [hex(v) for v in VS_SLOTS]) + for label, text, words in (('PS', PS_TEXT, PS_WORDS), ('VS', VS_TEXT, VS_FIXTURE), ('FLATPS', FLAT_PS_TEXT, + FLAT_PS_WORDS)): + got = [re.sub(r'_e(32|64)\b', '', asm) for _o, _n, _m, asm in G.decode(words)] + want = [re.sub(r'_e(32|64)\b', '', line) for line in text.splitlines()] + check('%s fixture decodes to its source' % label, got == want, '%s\n%s' % (got, want)) + try: + text = ps_text() + check('wave64 pixel slots translate to one scalar per (VGPR, lane)', + all(re.search(r'\b%s = 0' % s, text) for s in ('sp10_40', 'sp10_63', 'sp11_32', 'sp12_33')), text) + for label, (old, new) in PS_MUTATIONS.items(): + check('PS mutation "%s" changes the text' % label, mutate(text, old, new) != text) + except G.Unsupported as reason: + check('wave64 pixel slots translate', False, str(reason)) + try: + text = vs_pipeline().hlsl_vs() + check('vertex stage slots translate', all(re.search(r'\b%s = 0' % s, text) for s in ('sp40_0', 'sp40_48', 'sp41_0')), + text) + for label, (old, new) in VS_MUTATIONS.items(): + check('VS mutation "%s" changes the text' % label, mutate(text, old, new) != text) + except G.Unsupported as reason: + check('vertex stage slots translate', False, str(reason)) + for label, program, kind in ( + ('lane 64', ['v_writelane_b32 v10, s0, 64'], 'ps'), + ('lanes 8 and 40 of one VGPR', ['v_writelane_b32 v10, s0, 8', 'v_writelane_b32 v10, s1, 40'], 'ps'), + ('lanes 63 and 31 of one VGPR in a vertex stage', + ['v_writelane_b32 v10, s0, 63', 'v_readlane_b32 s1, v10, 31'], 'vs'), + ('a lane of a stage outside pixel, vertex, mesh and compute', ['v_writelane_b32 v10, s0, 40'], 'gs'), + ('a lane chosen by an SGPR', ['v_writelane_b32 v10, s0, s2'], 'vs')): + reason = refused(program, kind) + check('refused: %s (%s)' % (label, reason), reason is not None) + apart = ['v_writelane_b32 v10, s0, 8', 'v_writelane_b32 v11, s1, 40', 'v_readlane_b32 s2, v11, 40'] + check('lanes 8 and 40 of two different VGPRs are accepted', refused(apart) is None, str(refused(apart))) + + +# ---- draw ------------------------------------------------------------------------------------------------------------- +def draw_pixels(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + ps_source = ps_text() + pipe = vs_pipeline() + vs_source, flat_source = pipe.hlsl_vs(), pipe.hlsl_ps() + expected_vs = ','.join('%08x' % v for v in VS_SLOTS) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + reference = directory / 'reference.bin' + reference.write_bytes(struct.pack('<%dI' % (WIDTH * HEIGHT * 4), *ps_image())) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_' + kind, vs_profile, directory) + ps = compile_hlsl(compiler, kind, ps_source, 'ps_' + kind, ps_profile, directory) + run = draw_pixels(renderer, adapter, vs, ps, reference) + check('%s %s PS: all %d pixels equal the slot reference' % (adapter, kind, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for label, (old, new) in PS_MUTATIONS.items(): + bad = compile_hlsl(compiler, kind, mutate(ps_source, old, new), 'bad_ps_%s_%d' % (kind, len(old)), + ps_profile, directory) + run = draw_pixels(renderer, adapter, vs, bad, reference) + check('%s %s PS mutation "%s" fails' % (adapter, kind, label), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + vs2 = compile_hlsl(compiler, kind, vs_source, 'vs_spill_' + kind, vs_profile, directory) + flat = compile_hlsl(compiler, kind, flat_source, 'ps_flat_' + kind, ps_profile, directory) + run = draw_flat(renderer, adapter, vs2, flat, expected_vs) + check('%s %s VS: exported param0 equals the slot reference %s' % (adapter, kind, expected_vs), + run.returncode == 0, run.stdout + run.stderr) + for label, (old, new) in VS_MUTATIONS.items(): + bad = compile_hlsl(compiler, kind, mutate(vs_source, old, new), 'bad_vs_%s_%d' % (kind, len(old)), + vs_profile, directory) + run = draw_flat(renderer, adapter, bad, flat, expected_vs) + check('%s %s VS mutation "%s" fails' % (adapter, kind, label), run.returncode not in (0, 77), + run.stdout + run.stderr) + + +def check_binary(llvm_mc): + for label, text, words in (('PS', PS_TEXT, PS_WORDS), ('VS', VS_TEXT, VS_FIXTURE), + ('FLATPS', FLAT_PS_TEXT, FLAT_PS_WORDS)): + check('llvm-mc assembles the %s fixture to the same words' % label, assemble(llvm_mc, text) == words) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_src_scc_check.py b/tests/startup_gfx2hlsl_src_scc_check.py new file mode 100644 index 0000000000..fe69f50d97 --- /dev/null +++ b/tests/startup_gfx2hlsl_src_scc_check.py @@ -0,0 +1,316 @@ +"""The `src_scc` scalar source in tools/startup/gfx2hlsl.py (issue #1820). + +usage: startup_gfx2hlsl_src_scc_check.py + startup_gfx2hlsl_src_scc_check.py dispatch <dxc> <offscreen_check> <warp|hardware> + +The census contained `s_mul_i32 s28, 1.0, src_scc`, refused as `operand 'src_scc'` (#870, issue #1820). +Source code 253 reads the SCC bit as the integer value 0 or 1; the generated shader carries SCC as a +`bool scc`, so `Stage.u()` lowers `src_scc` to `(scc ? 1u : 0u)` when a modeled writer has set SCC on +every reaching path in the current block, and refuses when the incoming SCC is unverified (at shader entry, +after an unmodeled SCC writer such as `s_add_u32`, after descriptor-elided SCC, or across control-flow +joins). + +The instruction bytes are **constructed here** from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`): +- SOP2 (`[31:30] == 0b10`, op in `w0[29:23]`, sdst in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`, + optional literal dword when a source is 255) +- SOPC (`[31:23] == 0b101111110`, op in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`) +- SOPP (`[31:23] == 0b101111111`, op in `w0[22:16]`, simm16 in `w0[15:0]`) +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +SOP2_ADD_U32 = 0x00 +SOP2_AND_B32 = 0x0E +SOP2_MUL_I32 = 0x26 +SOPC_CMP_EQ_U32 = 0x06 +SOPP_NOP = 0x00 +SOPP_ENDPGM = 0x01 +SOPP_CBRANCH_SCC0 = 0x04 + +S_ZERO = 128 # inline integer 0 +S_ONE = 129 # inline integer 1 +S_SCC = 253 # the src_scc scalar source code +S_1_0 = 242 # the inline float constant 1.0 (its raw bits are 0x3f800000) +LITERAL = 255 +S1, S4, S5, S27, S28, S29 = 1, 4, 5, 27, 28, 29 + + +def encode_sop2(op, sdst, ssrc0, ssrc1, literal=None): + w0 = ((0b10 << 30) | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16) + | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF)) + code = struct.pack('<I', w0) + if literal is not None: + code += struct.pack('<I', literal) + return code + + +def encode_sopc(op, ssrc0, ssrc1, literal=None): + w0 = (0xBF000000 | ((op & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF)) + code = struct.pack('<I', w0) + if literal is not None: + code += struct.pack('<I', literal) + return code + + +def encode_sopp(op, simm=0): + w0 = 0xBF800000 | ((op & 0x7F) << 16) | (simm & 0xFFFF) + return struct.pack('<I', w0) + + +class Pipeline: + """Just enough pipeline state for Stage.translate().""" + + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + +def translate_program(code): + """Decode and run the full Stage.translate() CFG/block pass on synthetic bytes.""" + decoded = G.decode(code) + stage = G.Stage.__new__(G.Stage) + stage.pipe = Pipeline() + stage.kind = 'ps' + stage.lines, stage.sym = [], {} + stage.used_s, stage.used_v, stage.masks = set(), set(), set() + stage.attrs = {} + stage.exec_known = True + stage.ins = decoded + stage.force_joined = {} + stage.translate() + body = ' '.join(line for _, lines, _ in stage.blocks for line in lines) + return [asm for _o, _s, _n, asm in decoded], body, stage + + +def refused_reason(code): + try: + translate_program(code) + except G.Unsupported as error: + return str(error) + return None + + +MASK = 0xFFFFFFFF +SOP1_MOV_B32 = 0x03 +# (a, b) pairs: s_cmp_eq_u32 sets SCC = (a == b), then s_mov_b32 s3, src_scc stores it. +DISPATCH_CASES = ((0, 0), (1, 1), (0xFFFFFFFF, 0xFFFFFFFF), (0x12345678, 0x12345678), + (0, 1), (1, 0), (0x80000000, 0x00000001), (0xFFFFFFFF, 0xFFFFFFFE)) + + +def encode_sop1(op, sdst, ssrc): + return struct.pack('<I', (0b101111101 << 23) | ((sdst & 0x7F) << 16) | ((op & 0xFF) << 8) | (ssrc & 0xFF)) + + +class Probe(G.Stage): + """Minimal Stage for one-instruction-at-a-time lowering (same shape as the s_ff1 check).""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + self.kind = 'vs' + self.past_entry = False + + +def lower_cmp_then_read_scc(): + """Lower `s_cmp_eq_u32 s1, s2` then `s_mov_b32 s3, src_scc` with the real handlers.""" + code = encode_sopc(SOPC_CMP_EQ_U32, S1, 2) + encode_sop1(SOP1_MOV_B32, 3, S_SCC) + stage = Probe() + for _o, _n, ins, _asm in G.decode(code): + stage.one(ins, _asm) + return stage.lines + + +def dispatch(dxc, runner, adapter, lines, directory, name): + n = len(DISPATCH_CASES) + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(2 * n)) + hlsl = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, (a, b) in enumerate(DISPATCH_CASES): + hlsl.extend(( + ' {', + ' uint s1 = data.Load(%d) ^ %#010xu;' % (8 * i, fill[2 * i] ^ a), + ' uint s2 = data.Load(%d) ^ %#010xu;' % (8 * i + 4, fill[2 * i + 1] ^ b), + ' uint s3;', + ' bool scc;', + )) + hlsl.extend(' ' + line for line in lines) + hlsl.append(' data.Store(%d, s3);' % (4 * (2 * n + i))) + hlsl.append(' }') + hlsl.append('}') + src, cso, output = (directory / (name + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(hlsl) + '\n', encoding='ascii') + compiled = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or 'DXC exited with %d' % compiled.returncode) + words = 3 * n + dump_words = (words + 3) // 4 * 4 + ran = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(ran.stdout, end='') + if ran.returncode == 77: + sys.exit(77) + if ran.returncode or ran.stderr: + raise AssertionError(ran.stderr or 'raw UAV dump exited with %d' % ran.returncode) + actual = struct.unpack('<%dI' % dump_words, output.read_bytes()) + assert actual[:2 * n] == fill, 'operand region changed: %s' % (actual[:2 * n],) + return actual[2 * n:words] + + +def check_dispatch(dxc, runner, adapter): + lines = lower_cmp_then_read_scc() + check('dispatch lowering is the compare then the SCC read', + lines == ['scc = s1 == s2;', 's3 = (scc ? 1u : 0u);'], repr(lines)) + runner = str(Path(runner).resolve()) + out = Path(here).parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + directory = Path(tmp) + got = dispatch(dxc, runner, adapter, lines, directory, 'src_scc') + for i, (a, b) in enumerate(DISPATCH_CASES): + want = 1 if a == b else 0 # CPU reference: src_scc reads the SCC bit as 0 or 1 + check('dispatch src_scc after s_cmp_eq_u32 %#x, %#x' % (a, b), got[i] == want, + 'got %#x want %#x' % (got[i], want)) + check('dispatch covers both SCC=0 and SCC=1', {0, 1} <= set(got), repr(got)) + # Negative control: the same harness with the lowering mutated to (scc ? 0u : 1u) must read back + # the wrong value on every case, so a wrong src_scc lowering cannot pass the checks above. + mutated = [line.replace('(scc ? 1u : 0u)', '(scc ? 0u : 1u)') for line in lines] + check('negative control mutates the lowering', mutated != lines, repr(mutated)) + bad = dispatch(dxc, runner, adapter, mutated, directory, 'src_scc_mutated') + for i, (a, b) in enumerate(DISPATCH_CASES): + check('negative control reads the wrong value for %#x, %#x' % (a, b), + bad[i] == (0 if a == b else 1), 'got %#x' % bad[i]) + if failures: + print('FAILED: %s' % ', '.join(failures)) + sys.exit(1) + print('dispatch ok') + + +if len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + sys.exit(0) +elif len(sys.argv) != 1: + sys.exit(__doc__) + + +# 1. At shader entry, SCC is unverified: reading src_scc before any modeled writer must be refused. +check('entry src_scc in s_mul_i32 is refused', + refused_reason(encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + encode_sopp(SOPP_ENDPGM)) + == 'src_scc with unverified SCC') +check('entry src_scc in s_and_b32 is refused', + refused_reason(encode_sop2(SOP2_AND_B32, S28, S_SCC, S5) + encode_sopp(SOPP_ENDPGM)) + == 'src_scc with unverified SCC') + +# 2. Modeled compare -> census s_mul_i32 s28, 1.0, src_scc: decodes and lowers using the SCC bit. +cmp_census = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, stage = translate_program(cmp_census) +check('encodes and decodes compare + census form', + asm[:2] == ['s_cmp_eq_u32 0, 0', 's_mul_i32 s28, 1.0, src_scc'], repr(asm)) +check('compare + census form lowers to the SCC bit', + 'scc = 0x00000000u == 0x00000000u;' in emitted and 's28 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, + emitted) +check('low16_only=True returns the same 0/1 expression', + stage.u('src_scc', low16_only=True) == '(scc ? 1u : 0u)') + +# 3. Modeled bitwise writer -> src_scc in the first source position -> next instruction reads updated SCC. +bitwise_seq = (encode_sop2(SOP2_AND_B32, S27, S4, S5) + + encode_sop2(SOP2_AND_B32, S28, S_SCC, S5) + + encode_sop2(SOP2_MUL_I32, S29, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, _stage = translate_program(bitwise_seq) +check('encodes and decodes bitwise sequence with src_scc in first position', + asm[:3] == ['s_and_b32 s27, s4, s5', 's_and_b32 s28, src_scc, s5', 's_mul_i32 s29, 1.0, src_scc'], + repr(asm)) +check('bitwise sequence reads and updates SCC cleanly', + 's28 = (scc ? 1u : 0u) & s5; scc = s28 != 0;' in emitted + and 's29 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, + emitted) + +# 4. Distinguishing carry case: compare sets SCC=0, then s_add_u32 0xffffffff + 1 wraps and sets hardware +# carry SCC=1. The add emits that carry, so the src_scc read afterwards sees it (not the stale compare result). +carry_seq = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ONE) + + encode_sop2(SOP2_ADD_U32, S1, LITERAL, S_ONE, literal=0xFFFFFFFF) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +_asm, emitted, _stage = translate_program(carry_seq) +carry_line = 'scc = (0xffffffffu + 0x00000001u) < (0xffffffffu);' +check('s_add_u32 carry after compare is emitted ahead of the src_scc read', + carry_line in emitted and emitted.index(carry_line) < emitted.index('0x3f800000u * (scc ? 1u : 0u)'), emitted) + +# 5. s_add_u32 reading src_scc as an input before overwriting SCC is accepted (input read precedes write), +# while a second src_scc after s_add_u32 is refused. +add_reads_scc = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_ADD_U32, S1, S_SCC, S_ONE) + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, _stage = translate_program(add_reads_scc) +read_line = 's1 = (scc ? 1u : 0u) + 0x00000001u;' +check('s_add_u32 reading incoming verified src_scc is accepted', + read_line in emitted, emitted) +# The destination reads the incoming SCC before this add's own carry replaces it (the carry is emitted after the write). +check('s_add_u32 src_scc operand is read before the add writes SCC', + emitted.index(read_line) < emitted.index('scc = ((scc ? 1u : 0u) + 0x00000001u) < ((scc ? 1u : 0u));'), emitted) +check('s_add_u32 whose destination is also a source and reads src_scc is refused', + refused_reason(encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_ADD_U32, S1, S1, S_SCC) + + encode_sopp(SOPP_ENDPGM)) == 's_add_u32 reads src_scc with a destination that is also a source ' + 'or a special register') +_asm, emitted, _stage = translate_program( + encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) + + encode_sop2(SOP2_ADD_U32, S1, S_SCC, S_ONE) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) + + encode_sopp(SOPP_ENDPGM)) +carry_line = 'scc = ((scc ? 1u : 0u) + 0x00000001u) < ((scc ? 1u : 0u));' +check('reading src_scc after s_add_u32 sees the add\'s carry', + carry_line in emitted and emitted.index(carry_line) < emitted.index('0x3f800000u * (scc ? 1u : 0u)'), emitted) + +# 6. Across a control-flow join: branch skips an SCC write to target 0x0c, so the two paths into the join carry +# different SCC writes and src_scc there is refused unless a modeled writer runs inside the joined block first. +# (A skipped block without an SCC write keeps SCC proven: startup_gfx2hlsl_src_scc_join_check.py.) +join_refused = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00 + + encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> label_0x0c (skip 1 dword at 0x08) + + encode_sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x08 + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x0c (branch target / join) + + encode_sopp(SOPP_ENDPGM)) # 0x10 +check('src_scc across a control-flow join is refused', + refused_reason(join_refused) == 'src_scc with unverified SCC', + repr(refused_reason(join_refused))) + +join_rewritten = (encode_sopc(SOPC_CMP_EQ_U32, S_ZERO, S_ZERO) # 0x00 + + encode_sopp(SOPP_CBRANCH_SCC0, simm=1) # 0x04 -> 0x0c + + encode_sopp(SOPP_NOP, simm=0) # 0x08 + + encode_sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x0c (modeled writer after join) + + encode_sop2(SOP2_MUL_I32, S28, S_1_0, S_SCC) # 0x10 + + encode_sopp(SOPP_ENDPGM)) +asm, emitted, _stage = translate_program(join_rewritten) +check('src_scc after a modeled writer in the joined block is accepted', + 's28 = 0x3f800000u * (scc ? 1u : 0u);' in emitted, emitted) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_src_scc_join_check.py b/tests/startup_gfx2hlsl_src_scc_join_check.py new file mode 100644 index 0000000000..5dc0417c27 --- /dev/null +++ b/tests/startup_gfx2hlsl_src_scc_join_check.py @@ -0,0 +1,263 @@ +"""`src_scc` at a branch target in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_src_scc_join_check.py [dispatch <dxc> <offscreen_check> <adapter>] + +`dispatch` also compiles the accepted if/else and skipped-block programs with DXC and compares a D3D12 UAV +readback (WARP or hardware) with the compare each read must see. + +A compiler materializes SCC into an SGPR on both arms of an if/else: `s_bitcmp1_b32 s4, 3`, +`s_cbranch_scc0 ELSE`, then `s_mov_b32 s10, src_scc` in each arm. The arm at ELSE starts at a branch +target, where `src_scc` was refused as unverified. The translator now carries, on every forward branch +edge, the offset of the emitted SCC write that reaches it, and only when that write was uniform. A branch +target keeps SCC proven when the fall-through and every edge into it carry the same write and no back edge +enters it. Every path into the target then ran that one write last, both for the lane being modelled and +for the wave, whichever path each took (a per-lane `s_cbranch_execz` skip included). So the model's SCC is +the hardware value. + +Negative controls keep the refusal: an SCC write in one arm, an SCC write in a block `s_cbranch_execz` +skips, a back edge into the target, a lane-mask SCC (`s_and_b32` with `vcc_lo`), and an unmodelled +writer (`s_add_u32`) on one path. + +The instruction words are built here from the field layout that `tools/disasm_rdna2.py` decodes: +- SOP1 (`[31:23] == 0b101111101`, sdst in `w0[22:16]`, op in `w0[15:8]`, src0 in `w0[7:0]`) +- SOP2 (`[31:30] == 0b10`, op in `w0[29:23]`, sdst in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`) +- SOPC (`[31:23] == 0b101111110`, op in `w0[22:16]`, src1 in `w0[15:8]`, src0 in `w0[7:0]`) +- SOPP (`[31:23] == 0b101111111`, op in `w0[22:16]`, simm16 in `w0[15:0]`, branch target + `pc + 4 + 4 * simm16`) +""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +SOP1_MOV_B32 = 0x03 +SOP2_ADD_U32 = 0x00 +SOP2_AND_B32 = 0x0E +SOPC_CMP_EQ_U32 = 0x06 +SOPC_BITCMP1_B32 = 0x0D +SOPP_NOP, SOPP_ENDPGM, SOPP_BRANCH, SOPP_CBRANCH_SCC0, SOPP_CBRANCH_EXECZ = 0x00, 0x01, 0x02, 0x04, 0x08 + +S_SCC = 253 +S_THREE = 131 # inline integer 3 +VCC_LO = 106 +S4, S5, S6, S7, S10 = 4, 5, 6, 7, 10 +UNVERIFIED = 'src_scc with unverified SCC' + + +def sop1(op, sdst, ssrc0): + return struct.pack('<I', 0xBE800000 | ((sdst & 0x7F) << 16) | ((op & 0xFF) << 8) | (ssrc0 & 0xFF)) + + +def sop2(op, sdst, ssrc0, ssrc1): + return struct.pack('<I', (0b10 << 30) | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) + | (ssrc0 & 0xFF)) + + +def sopc(op, ssrc0, ssrc1): + return struct.pack('<I', 0xBF000000 | ((op & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF)) + + +def sopp(op, simm=0): + return struct.pack('<I', 0xBF800000 | ((op & 0x7F) << 16) | (simm & 0xFFFF)) + + +def branch(op, at, target): + """SOPP branch at byte offset `at` to byte offset `target`.""" + return sopp(op, (target - at - 4) // 4) + + +class Pipeline: + """Just enough pipeline state for Stage.translate().""" + + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + +def translate_program(code): + decoded = G.decode(code) + stage = G.Stage.__new__(G.Stage) + stage.pipe = Pipeline() + stage.kind = 'ps' + stage.lines, stage.sym = [], {} + stage.used_s, stage.used_v, stage.masks = set(), set(), set() + stage.attrs = {} + stage.exec_known = True + stage.ins = decoded + stage.force_joined = {} + stage.translate() + return [asm for _o, _s, _n, asm in decoded], [lines for _, lines, _ in stage.blocks] + + +def refused_reason(code): + try: + translate_program(code) + except G.Unsupported as error: + return str(error) + return None + + +READ = sop1(SOP1_MOV_B32, S10, S_SCC) # s_mov_b32 s10, src_scc +TEST = sopc(SOPC_BITCMP1_B32, S4, S_THREE) # s_bitcmp1_b32 s4, 3 + +# 1. The if/else shape: the else arm is entered only by the taken s_cbranch_scc0 edge. The then arm writes SCC +# after its read, which reaches neither arm's read. +if_else = (TEST # 0x00 + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x14) # 0x04 -> 0x14 + + READ # 0x08 + + sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x0c + + branch(SOPP_BRANCH, 0x10, 0x18) # 0x10 -> 0x18 + + READ # 0x14 (target of the taken edge only) + + sopp(SOPP_ENDPGM)) # 0x18 (join) +asm, blocks = translate_program(if_else) +check('if/else words decode as written', + asm == ['s_bitcmp1_b32 s4, 3', 's_cbranch_scc0 label_0x14', 's_mov_b32 s10, src_scc', 's_cmp_eq_u32 s4, s5', + 's_branch label_0x18', 's_mov_b32 s10, src_scc', 's_endpgm'], repr(asm)) +check('if/else: both arms read the SCC of s_bitcmp1_b32', + blocks == [['scc = ((s4 >> (0x00000003u & 31)) & 1u) == 1u;'], + ['s10 = (scc ? 1u : 0u);', 'scc = s4 == s5;'], + ['s10 = (scc ? 1u : 0u);'], []], repr(blocks)) + +# 2. A join that a skipped block without an SCC write reaches: both edges carry the compare at 0x00. +skip_nop = (sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x0c) # 0x04 -> 0x0c + + sopp(SOPP_NOP) # 0x08 + + READ # 0x0c (join) + + sopp(SOPP_ENDPGM)) +asm, blocks = translate_program(skip_nop) +check('join after a block without SCC writes reads the compare', + blocks == [['scc = s4 == s5;'], [], ['s10 = (scc ? 1u : 0u);']], repr(blocks)) + +# 3. The same over s_cbranch_execz: the lane can skip a block the wave runs, which is harmless only because +# the block writes no SCC. +skip_execz = (sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + branch(SOPP_CBRANCH_EXECZ, 0x04, 0x0c) # 0x04 -> 0x0c + + sopp(SOPP_NOP) # 0x08 + + READ # 0x0c (join) + + sopp(SOPP_ENDPGM)) +asm, blocks = translate_program(skip_execz) +check('join after an execz-skipped block without SCC writes reads the compare', + blocks == [['scc = s4 == s5;'], [], ['s10 = (scc ? 1u : 0u);']], repr(blocks)) + +# Negative controls: each keeps `src_scc with unverified SCC`. +# 4. An SCC write in the skipped arm: the two edges carry different writes. +check('SCC write in one arm refuses the read at the join', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x0c) # 0x04 -> 0x0c + + sopc(SOPC_CMP_EQ_U32, S6, S7) # 0x08 + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) # 0x0c +# 5. An SCC write inside a block s_cbranch_execz skips: the wave may run it while the lane skips it. +check('SCC write in an execz-skipped block refuses the read at the join', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) + + branch(SOPP_CBRANCH_EXECZ, 0x04, 0x0c) + + sopc(SOPC_CMP_EQ_U32, S6, S7) + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) +# 6. A back edge into the target: the loop body's SCC write is not known when the target is reached. +check('back-edge target refuses the read', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) # 0x00 + + READ # 0x04 (loop head) + + sopc(SOPC_CMP_EQ_U32, S6, S7) # 0x08 + + branch(SOPP_CBRANCH_SCC0, 0x0c, 0x04) # 0x0c -> 0x04 + + sopp(SOPP_ENDPGM)) == UNVERIFIED) +# 7. A lane-mask SCC: s_and_b32 with vcc_lo sets SCC from every lane's bit, which one lane does not see. +check('lane-mask SCC across a branch refuses the read', + refused_reason(sop2(SOP2_AND_B32, S6, S4, VCC_LO) # 0x00 + + branch(SOPP_CBRANCH_EXECZ, 0x04, 0x0c) # 0x04 -> 0x0c + + sopp(SOPP_NOP) # 0x08 + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) # 0x0c +# 8. An unmodelled SCC writer on one path: s_add_u32 sets the carry the model does not emit. +check('unmodelled writer on one path refuses the read', + refused_reason(sopc(SOPC_CMP_EQ_U32, S4, S5) + + branch(SOPP_CBRANCH_SCC0, 0x04, 0x0c) + + sop2(SOP2_ADD_U32, S6, S4, S5) + + READ + sopp(SOPP_ENDPGM)) == UNVERIFIED) + + +MASK = 0xFFFFFFFF +DISPATCH_CASES = ((0x00000000, 0x00000000), (0x00000008, 0x00000008), (0x00000008, 0x00000001), + (0xFFFFFFF7, 0xFFFFFFF7), (0xFFFFFFFF, 0x12345678), (0x12345678, 0x12345678)) + + +def dispatch_hlsl(cases, fill): + """One thread, one block per case: structured if/else, then the skipped-block join, on the translated lines.""" + _, if_blocks = translate_program(if_else) + _, skip_blocks = translate_program(skip_nop) + lines = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, (a, b) in enumerate(cases): + out = 4 * (len(fill) + 2 * i) + lines += [' {', + f' uint s4 = data.Load({8 * i}) ^ {fill[2 * i] ^ a:#010x}u;', + f' uint s5 = data.Load({8 * i + 4}) ^ {fill[2 * i + 1] ^ b:#010x}u;', + ' uint s10 = 0u;', ' bool scc = true;'] + lines += [' ' + t for t in if_blocks[0]] + lines += [' if (scc) {'] + [' ' + t for t in if_blocks[1]] + lines += [' } else {'] + [' ' + t for t in if_blocks[2]] + [' }'] + lines.append(f' data.Store({out}, s10);') + lines += [' s10 = 0u;', ' scc = true;'] + lines += [' ' + t for t in skip_blocks[0] + skip_blocks[2]] + lines += [f' data.Store({out + 4}, s10);', ' }'] + return '\n'.join(lines + ['}']) + '\n' + + +def check_dispatch(dxc, runner, adapter): + runner = str(Path(runner).resolve()) + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(2 * len(DISPATCH_CASES))) + out = Path(__file__).resolve().parent.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + src, cso, dump = (Path(tmp) / ('src_scc_join' + e) for e in ('.hlsl', '.cso', '.bin')) + src.write_text(dispatch_hlsl(DISPATCH_CASES, fill), encoding='ascii') + compiled = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or f'DXC exited with {compiled.returncode}') + words = len(fill) + 2 * len(DISPATCH_CASES) + padded = (words + 3) // 4 * 4 + run = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * padded), str(dump)], + capture_output=True, text=True) + print(run.stdout, end='') + if run.returncode == 77: + sys.exit(77) + if run.returncode or run.stderr: + raise AssertionError(run.stderr or f'raw UAV dump exited with {run.returncode}') + got = struct.unpack(f'<{padded}I', dump.read_bytes()) + check('operand region unchanged', got[:len(fill)] == fill) + for i, (a, b) in enumerate(DISPATCH_CASES): + # CPU reference: the if/else reads the s_bitcmp1_b32 s4, 3 result on both arms; the join reads s4 == s5. + want = ((a >> 3) & 1, int(a == b)) + have = got[len(fill) + 2 * i:len(fill) + 2 * i + 2] + check(f'readback s4={a:#010x} s5={b:#010x}: got {have}, want {want}', have == want) + if failures: + sys.exit(1) + + +if len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + print('PASS') + sys.exit(0) +elif len(sys.argv) != 1: + sys.exit(__doc__) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_tbuffer_2101010_check.py b/tests/startup_gfx2hlsl_tbuffer_2101010_check.py new file mode 100644 index 0000000000..1f9fbae098 --- /dev/null +++ b/tests/startup_gfx2hlsl_tbuffer_2101010_check.py @@ -0,0 +1,125 @@ +"""Packed 2-10-10-10 UNORM typed buffer loads in tools/startup/gfx2hlsl.py (Part of #1723). + +usage: startup_gfx2hlsl_tbuffer_2101010_check.py + +`BUF_FMT_2_10_10_10_UNORM` stores x, y and z as 10-bit fields and w as a 2-bit field in one dword, lowest bits +first. The format table did not name it, so a typed load of it was refused with +`buffer format BUF_FMT_2_10_10_10_UNORM`. DXGI_FORMAT_R10G10B10A2_UNORM (24) in an input layout maps to it. + +The instruction bytes are constructed here from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, the MTBUF branch): no game-derived bytes are used. Each case encodes the instruction, +decodes it, translates it, and then evaluates the emitted component expressions against a reference that +decodes the same dword from the format definition (UNORM n / (2^bits - 1)). +""" +import os +import re +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +MTBUF_LOAD = {'x': 0, 'xy': 1, 'xyz': 2, 'xyzw': 3} +MTBUF_FORMAT_2_10_10_10_UNORM = 50 +MTBUF_FORMAT_2_10_10_10_SNORM = 51 # a sibling the table must keep refusing + + +def encode_mtbuf(op, fmt, *, vdata=0, vaddr=0, srsrc=4, soffset=128): + """Encode one MTBUF instruction (idxen); returns the 8 bytes the decoder reads.""" + w0 = (0b111010 << 26) | ((fmt & 0x7f) << 19) | ((op & 0x7) << 16) | (1 << 13) + w1 = (vaddr & 0xff) | ((vdata & 0xff) << 8) | (((srsrc // 4) & 0x1f) << 16) | (((op >> 3) & 1) << 21) | (soffset << 24) + return struct.pack('<II', w0, w1) + + +class Pipeline: + def __init__(self): + self.resources, self.notes, self.modified = {}, set(), set() + + def resource(self, key, kind): + entry = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) + return 'r%d' % entry['index'] + + def ud(self, source): + return 0 + + +class Stage(G.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.exports = {} + self.pipe = Pipeline() + + def descriptor(self, tok): + return ('buffer', tok) + + +def translate_bytes(code): + decoded = G.decode(code) + stage = Stage() + for _offset, _size, name, asm in decoded: + stage.one(name, asm) + return [asm for _o, _s, _n, asm in decoded], stage.lines + + +def run_components(lines, word): + """Evaluate the emitted `vN = <expr>;` lines with `w` bound to the loaded dword; returns {N: value}.""" + out = {} + for line in lines: + m = re.fullmatch(r'v(\d+) = (.*);', line.strip()) + if m: + out[int(m.group(1))] = eval(m.group(2), {'U': lambda x: x, 'ldu': lambda *_: 0}, {'w': word}) + return out + + +def reference(word): + return [(word & 1023) / 1023.0, ((word >> 10) & 1023) / 1023.0, ((word >> 20) & 1023) / 1023.0, (word >> 30) / 3.0] + + +code = encode_mtbuf(MTBUF_LOAD['xyzw'], MTBUF_FORMAT_2_10_10_10_UNORM, vdata=1, vaddr=2, srsrc=4) +asm, lines = translate_bytes(code) +check('decodes the named format', 'BUF_FMT_2_10_10_10_UNORM' in asm[0], repr(asm)) +check('the word is loaded with ldu', any('w = ldu(r0, a)' in l for l in lines), repr(lines)) + +for word in (0x00000000, 0xffffffff, 0x4012a3ff, 0x8007fc01, 0xc0000000, 0x2aaaaaaa, 0x155ff3d1): + got = run_components(lines, word) + want = reference(word) + check('all four components for 0x%08x' % word, [got.get(1 + i) for i in range(4)] == want, + 'got %r want %r' % (got, want)) + +# Fewer components read the same leading fields. +_, lines_xy = translate_bytes(encode_mtbuf(MTBUF_LOAD['xy'], MTBUF_FORMAT_2_10_10_10_UNORM, vdata=1, vaddr=2)) +got = run_components(lines_xy, 0x4012a3ff) +check('the xy form reads two components', sorted(got) == [1, 2] and [got[1], got[2]] == reference(0x4012a3ff)[:2], repr(got)) + +# The input-layout mapping: DXGI_FORMAT_R10G10B10A2_UNORM is 24, one dword per element. +check('DXGI 24 maps to the format', G.FETCH_DXGI.get(24) == ('BUF_FMT_2_10_10_10_UNORM', 4), repr(G.FETCH_DXGI.get(24))) + +# A sibling format stays refused. +try: + translate_bytes(encode_mtbuf(MTBUF_LOAD['xyzw'], MTBUF_FORMAT_2_10_10_10_SNORM, vdata=1, vaddr=2)) + refused = False +except G.Unsupported: + refused = True +check('the SNORM sibling stays refused', refused) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py b/tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py new file mode 100644 index 0000000000..154c788b04 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_add_sub_nc_i32_check.py @@ -0,0 +1,349 @@ +"""Signed 32-bit add/sub (v_add_nc_i32, v_sub_nc_i32, with and without clamp) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3A decode, value evaluation against emitted HLSL, EXEC masking, + align4/uniformity rules, encoding & Stage refusals, unlowered controls + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +RDNA 2 ISA, VOP3A: + V_ADD_NC_I32 (0x37f): D.i32 = S0.i32 + S1.i32; with clamp, saturates to [-2^31, 2^31 - 1]. + V_SUB_NC_I32 (0x376): D.i32 = S0.i32 - S1.i32; with clamp, saturates to [-2^31, 2^31 - 1]. +""" +import ast +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OP_ADD = 0x37f +OP_SUB = 0x376 +XOR_MASK = 0x3f800000 +INT32_MIN = -0x80000000 +INT32_MAX = 0x7fffffff + + +def vop3a(op, vdst, src0, src1, src2=0, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0, lit=None): + w0 = 0xd4000000 | ((op & 0x3ff) << 16) | (clamp << 15) | (op_sel << 11) | (abs_bits << 8) | (vdst & 0xff) + w1 = (neg << 29) | (omod << 27) | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def v_xor_lit(vdst, vsrc, lit): + # VOP2 v_xor_b32_e32 (op 0x1d) with src0 = 255 (literal) and vsrc1 = vsrc. + w = (0x1d << 25) | ((vdst & 0xff) << 17) | ((vsrc & 0xff) << 9) | 255 + return struct.pack('<2I', w, lit & MASK) + + +def ps_words(op, clamp=0): + # Compute 4 lanes and XOR each output with 0x3f800000 so INT32_MAX (0x7fffffff, NaN bits) + # and small integers remain normal float32 values through the R32G32B32A32_FLOAT mrt0 export. + body = b''.join( + vop3a(op, 12 + lane, 256 + lane, 256 + 4 + lane, clamp=clamp) + v_xor_lit(12 + lane, 12 + lane, XOR_MASK) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, clamp=clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def s32(v): + v &= MASK + return v - 0x100000000 if v >= 0x80000000 else v + + +def ref_op(op, a, b, clamp): + res = s32(a) + s32(b) if op == OP_ADD else s32(a) - s32(b) + if clamp: + res = max(INT32_MIN, min(INT32_MAX, res)) + return res & MASK + + +def eval_hlsl_u32(expr, env, helpers=None): + """Evaluate a 32-bit unsigned HLSL expression (supporting helper calls, ternaries, bitwise/arith ops).""" + cleaned = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + # Convert C/HLSL ternary `cond ? a : b` at top level of helper return expressions. + m = re.fullmatch(r'\s*(.+?)\s*\?\s*(.+?)\s*:\s*(.+?)\s*', cleaned) + if m: + cond, t_br, f_br = m.groups() + return eval_hlsl_u32(t_br if eval_hlsl_u32(cond, env, helpers) else f_br, env, helpers) + + def ev(node): + if isinstance(node, ast.Expression): + return ev(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Invert): + return (~ev(node.operand)) & MASK + if isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], ast.NotEq): + return int(ev(node.left) != ev(node.comparators[0])) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + fn = node.func.id + if helpers and fn in helpers: + args = [ev(a) & MASK for a in node.args] + return helpers[fn](*args) + raise ValueError('unsupported call %s' % fn) + if isinstance(node, ast.BinOp): + l, r = ev(node.left), ev(node.right) + if isinstance(node.op, ast.Add): + return (l + r) & MASK + if isinstance(node.op, ast.Sub): + return (l - r) & MASK + if isinstance(node.op, ast.BitXor): + return (l ^ r) & MASK + if isinstance(node.op, ast.BitAnd): + return (l & r) & MASK + if isinstance(node.op, ast.RShift): + return (l & MASK) >> (r & 31) + raise ValueError('unsupported binop %s' % node.op) + raise ValueError('unsupported node %s' % ast.dump(node)) + + return ev(ast.parse(cleaned, mode='eval')) & MASK + + +def extract_helper(hlsl, fn_name): + m = re.search( + r'uint\s+%s\(uint a, uint b\)\s*\{\s*uint\s+(\w+)\s*=\s*([^;]+);\s*return\s+([^;]+);\s*\}' % fn_name, + hlsl, + ) + if not m: + return None + tmp_var, tmp_expr, ret_expr = m.groups() + + def fn(a, b): + env = {'a': a & MASK, 'b': b & MASK} + env[tmp_var] = eval_hlsl_u32(tmp_expr, env) + return eval_hlsl_u32(ret_expr, env) + + return fn + + +def stage_refused(stage, name, line, needle=''): + try: + stage.one(name, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +EDGE_WORDS = ( + 0x00000000, 0x00000001, 0x00000002, 0x3fffffff, 0x7ffffffe, + 0x7fffffff, 0x80000000, 0x80000001, 0xc0000000, 0xffffffff, +) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 VOP3A bytes via G.decode(). + for op, name in ((OP_ADD, 'v_add_nc_i32'), (OP_SUB, 'v_sub_nc_i32')): + check('decode %s' % name, + G.decode(vop3a(op, 12, 256, 260))[0][3] == '%s v12, v0, v4' % name) + check('decode %s clamp' % name, + G.decode(vop3a(op, 12, 256, 260, clamp=1))[0][3] == '%s v12, v0, v4 clamp' % name) + + # 2. Selective helper emission and direct evaluation of emitted HLSL across 400 edge cases. + _, ps_add = translate(OP_ADD, clamp=0) + _, ps_sub = translate(OP_SUB, clamp=0) + _, ps_add_c = translate(OP_ADD, clamp=1) + _, ps_sub_c = translate(OP_SUB, clamp=1) + check('unclamped add emits no sat helpers', + 'add_sat_i32' not in ps_add and 'sub_sat_i32' not in ps_add) + check('unclamped sub emits no sat helpers', + 'add_sat_i32' not in ps_sub and 'sub_sat_i32' not in ps_sub) + check('clamped add emits only add_sat_i32', + 'add_sat_i32(' in ps_add_c and 'sub_sat_i32' not in ps_add_c) + check('clamped sub emits only sub_sat_i32', + 'sub_sat_i32(' in ps_sub_c and 'add_sat_i32' not in ps_sub_c) + + helpers = { + 'add_sat_i32': extract_helper(ps_add_c, 'add_sat_i32'), + 'sub_sat_i32': extract_helper(ps_sub_c, 'sub_sat_i32'), + } + check('extracted sat helpers from HLSL', all(helpers.values())) + + for op, name in ((OP_ADD, 'v_add_nc_i32'), (OP_SUB, 'v_sub_nc_i32')): + for clamp in (0, 1): + p = Probe() + asm = '%s v12, v0, v4%s' % (name, ' clamp' if clamp else '') + p.one(name, asm) + check('emitted %s' % asm, + len(p.lines) == 1 and p.lines[0].startswith('v12 = ') and p.lines[0].endswith(';')) + rhs = p.lines[0][len('v12 = '):-1] + ok = True + for a in EDGE_WORDS: + for b in EDGE_WORDS: + got = eval_hlsl_u32(rhs, {'v0': a, 'v4': b}, helpers) + if got != ref_op(op, a, b, clamp): + ok = False + check('%s%s grid (%d cases)' % (name, ' clamp' if clamp else '', len(EDGE_WORDS) ** 2), ok) + + # 3. EXEC masking, align4 propagation, and uniformity tracking. + for name in ('v_add_nc_i32', 'v_sub_nc_i32'): + for suffix in ('', ' clamp'): + p = Probe() + p.exec_known = False + p.one(name, '%s v12, v0, v4%s' % (name, suffix)) + check('exec-masked %s%s guards assignment' % (name, suffix), + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + p_a = Probe() + p_a.align4_v = {0, 4} + p_a.one(name, '%s v12, v0, v4' % name) + check('unclamped %s preserves align4' % name, 12 in p_a.align4_v) + + p_ac = Probe() + p_ac.align4_v = {0, 4} + p_ac.one(name, '%s v12, v0, v4 clamp' % name) + check('clamped %s clears align4' % name, 12 not in p_ac.align4_v) + + for suffix in ('', ' clamp'): + p_u = Probe() + p_u.exec_known = True + p_u.past_entry = False + p_u.uniform_v = {0, 4} + p_u.varying_s = set() + p_u.scc_uniform = True + p_u.one(name, '%s v12, v0, v4%s' % (name, suffix)) + check('%s%s preserves uniformity' % (name, suffix), 12 in p_u.uniform_v) + + # 4. VOP3A encoding guard refuses neg/abs and nonzero unused src2. + for op, name in ((OP_ADD, 'v_add_nc_i32'), (OP_SUB, 'v_sub_nc_i32')): + for label, bad_word, needle in ( + ('abs0', vop3a(op, 12, 256, 260, abs_bits=1), 'with neg/abs'), + ('neg1', vop3a(op, 12, 256, 260, neg=2), 'with neg/abs'), + ('neg_inline0', vop3a(op, 12, 129, 260, neg=1), 'with neg/abs'), + ('unused_src2', vop3a(op, 12, 256, 260, src2=264), 'unused src2'), + ): + reasons = [] + G.decode(bad_word, reasons) + check('encoding guard refuses %s %s' % (name, label), + len(reasons) == 1 and needle in reasons[0][0]) + + # 5. Stage refusals: _e32 spelling, bad modifiers, abs/neg, wrong arity, lane mask, bad dst. + for name in ('v_add_nc_i32', 'v_sub_nc_i32'): + check('Stage refuses %s_e32' % name, + stage_refused(Probe(), '%s_e32' % name, '%s_e32 v12, v0, v4' % name)) + for asm in ( + '%s v12, v0, v4 mul:2' % name, + '%s v12, v0, v4 clamp mul:2' % name, + '%s v12, v0, v4 op_sel:[1,0,0]' % name, + '%s v12, |v0|, v4' % name, + '%s v12, v0, -v4' % name, + '%s v12, v0' % name, + '%s v12, v0, v4, v8' % name, + '%s v12, vcc_lo, v4' % name, + '%s s0, v0, v4' % name, + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), name, asm)) + + # 6. Unlowered control: removing handlers from Stage restores refusals. + for op, name in ((OP_ADD, 'v_add_nc_i32'), (OP_SUB, 'v_sub_nc_i32')): + attr = 'op_' + name + saved = getattr(G.Stage, attr) + delattr(G.Stage, attr) + try: + check('unlowered %s refused' % name, + stage_refused(Probe(), name, '%s v12, v0, v4' % name)) + try: + translate(op, clamp=0) + except G.Unsupported: + check('unlowered %s pipeline refused' % name, True) + else: + check('unlowered %s pipeline refused' % name, False) + finally: + setattr(G.Stage, attr, saved) + + +DRAW_CASES = ( + (OP_ADD, 0, 'add_wrap', [ + (0x00000003, 0x00000005, 0), # 3 + 5 = 8 + (0x7fffffff, 0x00000001, 0), # INT32_MAX + 1 wraps to 0x80000000 + (0x80000000, 0xffffffff, 0), # INT32_MIN + (-1) wraps to 0x7fffffff + (0x80000000, 0x80000000, 0), # INT32_MIN + INT32_MIN wraps to 0 + ]), + (OP_ADD, 1, 'add_clamp', [ + (0x00000003, 0x00000005, 0), # 3 + 5 = 8 (no saturation) + (0x7fffffff, 0x00000001, 0), # saturates to INT32_MAX (0x7fffffff) + (0x80000000, 0xffffffff, 0), # saturates to INT32_MIN (0x80000000) + (0x7fffffff, 0x80000000, 0), # opposite signs: -1 (0xffffffff, no saturation) + ]), + (OP_SUB, 0, 'sub_wrap', [ + (0x0000000a, 0x00000003, 0), # 10 - 3 = 7 + (0x7fffffff, 0xffffffff, 0), # INT32_MAX - (-1) wraps to 0x80000000 + (0x80000000, 0x00000001, 0), # INT32_MIN - 1 wraps to 0x7fffffff + (0x00000000, 0x80000000, 0), # 0 - INT32_MIN wraps to 0x80000000 + ]), + (OP_SUB, 1, 'sub_clamp', [ + (0x0000000a, 0x00000003, 0), # 10 - 3 = 7 (no saturation) + (0x7fffffff, 0xffffffff, 0), # saturates to INT32_MAX (0x7fffffff) + (0x80000000, 0x00000001, 0), # saturates to INT32_MIN (0x80000000) + (0x00000000, 0x80000000, 0), # 0 - INT32_MIN saturates to INT32_MAX (0x7fffffff) + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_add_sub_nc_i32_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = first_ps = first_exp = None + for op, clamp, label, triples in DRAW_CASES: + pipe = G.Pipeline(vs_words(triples), ps_words(op, clamp=clamp), root_blob()) + vs_bin = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = tuple(ref_op(op, a, b, clamp) ^ XOR_MASK for a, b, _ in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_add_nc_i32 / v_sub_nc_i32 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_add_nc_i32 / v_sub_nc_i32 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_add_sub_nc_i32_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_dot2_check.py b/tests/startup_gfx2hlsl_v_dot2_check.py new file mode 100644 index 0000000000..1434c19028 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_dot2_check.py @@ -0,0 +1,308 @@ +"""VOP3P 2-halfword integer dot products (v_dot2_i32_i16, v_dot2_u32_u16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, on-demand helpers, value evaluation (wrapping and clamp, + including double-overflow cases), EXEC masking, refusal and mutation + controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +RDNA 2 ISA, VOP3P (0x14 / 0x15): + V_DOT2_I32_I16 vD, S0, S1, S2 [clamp]: D = int16(S0.lo)*int16(S1.lo) + int16(S0.hi)*int16(S1.hi) + int32(S2) + V_DOT2_U32_U16 vD, S0, S1, S2 [clamp]: D = uint16(S0.lo)*uint16(S1.lo) + uint16(S0.hi)*uint16(S1.hi) + uint32(S2) +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OPCODES = { + 'v_dot2_i32_i16': 0x14, + 'v_dot2_u32_u16': 0x15, +} + + +def vop3p(op, vdst, src0, src1, src2, *, clamp=0, op_sel=0, op_sel_hi=0b111, neg_lo=0, neg_hi=0, lit=None): + w0 = (0xcc000000 + | (op << 16) + | (clamp << 15) + | (((op_sel_hi >> 2) & 1) << 14) + | ((op_sel & 0x7) << 11) + | ((neg_hi & 0x7) << 8) + | (vdst & 0xff)) + w1 = (((neg_lo & 0x7) << 29) + | ((op_sel_hi & 0x3) << 27) + | ((src2 & 0x1ff) << 18) + | ((src1 & 0x1ff) << 9) + | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def ps_words(op, clamp=0): + code = OPCODES[op] + body = b''.join( + vop3p(code, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane, clamp=clamp) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def sext32(v): + v &= MASK + return v - (1 << 32) if v >= (1 << 31) else v + + +def ref_dot2_u32_u16(a, b, c, clamp=False): + total = (c & MASK) + ((a & 0xffff) * (b & 0xffff)) + (((a >> 16) & 0xffff) * ((b >> 16) & 0xffff)) + if clamp and total > MASK: + return MASK + return total & MASK + + +def ref_dot2_i32_i16(a, b, c, clamp=False): + total = sext32(c) + (sext16(a) * sext16(b)) + (sext16(a >> 16) * sext16(b >> 16)) + if clamp: + if total > 0x7fffffff: + return 0x7fffffff + if total < -0x80000000: + return 0x80000000 + return total & MASK + + +def eval_dot2_u32_u16_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + p0 = ((a & 0xffff) * (b & 0xffff)) & MASK + p1 = (((a >> 16) & 0xffff) * ((b >> 16) & 0xffff)) & MASK + r0 = (c + p0) & MASK + carry = 1 if r0 < c else 0 + r1 = (r0 + p1) & MASK + carry += 1 if r1 < r0 else 0 + return 0xffffffff if (sat and carry != 0) else r1 + + +def eval_dot2_i32_i16_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + p0 = sext16(a) * sext16(b) + p1 = sext16(a >> 16) * sext16(b >> 16) + lo = c + hi = -1 if sext32(c) < 0 else 0 + t0 = (lo + (p0 & MASK)) & MASK + hi += (-1 if p0 < 0 else 0) + (1 if t0 < lo else 0) + lo = t0 + t1 = (lo + (p1 & MASK)) & MASK + hi += (-1 if p1 < 0 else 0) + (1 if t1 < lo else 0) + lo = t1 + if sat: + if hi > 0 or (hi == 0 and (lo & 0x80000000) != 0): + return 0x7fffffff + if hi < -1 or (hi == -1 and (lo & 0x80000000) == 0): + return 0x80000000 + return lo + + +def stage_refused(stage, op, line, needle=''): + try: + stage.one(op, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS_A = (0x00000000, 0xffffffff, 0x80008000, 0x7fff7fff, 0x80007fff, 0x00010002, 0xffff0001) +WORDS_B = (0x00000000, 0xffffffff, 0x80008000, 0x7fff7fff, 0x7fff8000, 0x00030004) +ACCUMS = (0x00000000, 0x00000001, 0x40000000, 0x7fffffff, 0x80000000, 0xc0000000, 0xffffffff) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 VOP3P bytes via G.decode(). + check('decode v_dot2_i32_i16 plain', + G.decode(vop3p(0x14, 12, 256, 260, 264))[0][3] == 'v_dot2_i32_i16 v12, v0, v4, v8') + check('decode v_dot2_i32_i16 clamp', + G.decode(vop3p(0x14, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot2_i32_i16 v12, v0, v4, v8 clamp') + check('decode v_dot2_u32_u16 plain', + G.decode(vop3p(0x15, 12, 256, 260, 264))[0][3] == 'v_dot2_u32_u16 v12, v0, v4, v8') + check('decode v_dot2_u32_u16 clamp', + G.decode(vop3p(0x15, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot2_u32_u16 v12, v0, v4, v8 clamp') + + # 2. Exhaustive grid for both wrapping and saturating modes (including 2*2^30 = 2^31 signed & 2*0xfffe0001 unsigned). + u_ok = True + i_ok = True + for a in WORDS_A: + for b in WORDS_B: + for c in ACCUMS: + for sat in (False, True): + if eval_dot2_u32_u16_hlsl(a, b, c, sat) != ref_dot2_u32_u16(a, b, c, sat): + u_ok = False + if eval_dot2_i32_i16_hlsl(a, b, c, sat) != ref_dot2_i32_i16(a, b, c, sat): + i_ok = False + n_cases = len(WORDS_A) * len(WORDS_B) * len(ACCUMS) * 2 + check('v_dot2_u32_u16 grid (%d cases, wrap + clamp)' % n_cases, u_ok) + check('v_dot2_i32_i16 grid (%d cases, wrap + clamp)' % n_cases, i_ok) + + # 3. On-demand helper emission: each helper emitted only when its instruction is used. + _, ps_u = translate('v_dot2_u32_u16', 0) + _, ps_i = translate('v_dot2_i32_i16', 0) + check('dot2_u32_u16 emitted on demand and dot2_i32_i16 omitted', + 'uint dot2_u32_u16(' in ps_u and 'dot2_i32_i16' not in ps_u) + check('dot2_i32_i16 emitted on demand and dot2_u32_u16 omitted', + 'uint dot2_i32_i16(' in ps_i and 'dot2_u32_u16' not in ps_i) + check('dot2_i32_i16 helper uses strict unsigned carry compares', + '((t0 < lo) ? 1 : 0)' in ps_i and '((t1 < lo) ? 1 : 0)' in ps_i) + zero = [(0, 0, 0)] * 4 + unused_ps = G.Pipeline(vs_words(zero), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('both dot2 helpers omitted when unused', 'dot2_' not in unused_ps) + + # 4. EXEC masking & clamp flag propagation. + for op, helper in (('v_dot2_u32_u16', 'dot2_u32_u16'), ('v_dot2_i32_i16', 'dot2_i32_i16')): + p = Probe() + p.exec_known = False + p.one(op, '%s v12, v0, v4, v8 clamp' % op) + check('%s exec-masked + clamp' % op, + p.lines == ['if (exec & 1) v12 = %s(v0, v4, v8, true);' % helper]) + + # 5. Refusals: arity, non-clamp VOP3P modifiers, bad dst/src, source modifiers. + for op, code in OPCODES.items(): + check('%s 3 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3' % op, 'expected 4')) + check('%s 5 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3, v4, v5' % op, 'expected 4')) + for label, bad_word in ( + ('op_sel', vop3p(code, 12, 256, 260, 264, op_sel=1)), + ('op_sel_hi', vop3p(code, 12, 256, 260, 264, op_sel_hi=0)), + ('neg_lo', vop3p(code, 12, 256, 260, 264, neg_lo=1)), + ('neg_hi', vop3p(code, 12, 256, 260, 264, neg_hi=1)), + ): + asm = G.decode(bad_word)[0][3] + check('%s VOP3P %s refused' % (op, label), + stage_refused(Probe(), op, asm, 'unsupported modifiers')) + for bad_dst in ('s4', 'v[0:1]', 'v256'): + check('%s bad dst %s refused' % (op, bad_dst), + stage_refused(Probe(), op, '%s %s, v0, v4, v8' % (op, bad_dst), 'destination')) + for bad_src in ('|v0|', '-v0', 'neg(1)', 'v[0:1]', 's[0:1]', 'v256', 's106'): + check('%s bad src %s refused' % (op, bad_src), + stage_refused(Probe(), op, '%s v12, %s, v4, v8' % (op, bad_src))) + + # 6. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_v_dot2_i32_i16', 'op_v_dot2_u32_u16')} + try: + for name in saved: + delattr(G.Stage, name) + for op in OPCODES: + check('unlowered %s refused' % op, stage_refused(Probe(), op, '%s v12, v0, v4, v8' % op)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % op, True) + else: + check('unlowered %s pipeline refused' % op, False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + +DRAW_CASES = ( + ('v_dot2_u32_u16', 0, [ + (0x00020003, 0x00040005, 0x3f800000), # 3*5 + 2*4 = +23 + (0x00100020, 0x01000200, 0x3f800000), # 32*512 + 16*256 = +20480 + (0x00010001, 0x00010001, 0xfffffffe), # wraps cleanly to 0x00000000 + (0x00000000, 0xffffffff, 0x40000000), # zero sum + ]), + ('v_dot2_u32_u16', 1, [ + (0x00020003, 0x00040005, 0x3f800000), # no saturation + (0xffffffff, 0xffffffff, 0x3f800000), # double overflow -> saturates to 0xffffffff + (0x80008000, 0x80008000, 0x80000000), # overflow -> saturates to 0xffffffff + (0x00000000, 0xffffffff, 0x3f800000), # zero sum + ]), + ('v_dot2_i32_i16', 0, [ + (0x00020003, 0x00040005, 0x3f800000), # +23 + (0xfffefffd, 0x00040005, 0x3f800000), # (-3)*5 + (-2)*4 = -23 + (0x80008000, 0x80008000, 0x80000000), # 2^30 + 2^30 - 2^31 = 0x00000000 + (0x00010000, 0xffff0000, 0x3f800000), # -1 + ]), + ('v_dot2_i32_i16', 1, [ + (0x80008000, 0x80008000, 0x00000000), # 2^30 + 2^30 = +2^31 -> saturates to 0x7fffffff + (0x80008000, 0x7fff7fff, 0x80000000), # negative overflow -> saturates to 0x80000000 + (0x80008000, 0x80008000, 0x80000000), # exact cancellation: 2^31 - 2^31 = 0x00000000 (NO sat!) + (0x00020003, 0x00040005, 0x3f800000), # no overflow + ]), + ('v_dot2_i32_i16', 1, [ + (0x00000003, 0x00010005, 0x3f800000), # p1 == 0: no carry, no saturation + (0x00030000, 0x00050001, 0xffffffff), # p0 == 0, c < 0: +14 + (0x00000000, 0x12345678, 0x7fffffff), # both products 0, c = INT32_MAX + (0x00000000, 0x00000000, 0x80000000), # both products 0, c = INT32_MIN + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_dot2_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for op, clamp, triples in DRAW_CASES: + ref_fn = ref_dot2_i32_i16 if op == 'v_dot2_i32_i16' else ref_dot2_u32_u16 + _, ps_hlsl = translate(op, clamp) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%d_%s' % (op, clamp, kind), ps_profile, td) + vs_hlsl = G.Pipeline(vs_words(triples), ps_words(op, clamp), root_blob()).hlsl_vs() + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%d_%s' % (op, clamp, kind), vs_profile, td) + raw_exp = tuple(ref_fn(a, b, c, bool(clamp)) for a, b, c in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s clamp=%d expected=%s\n%s\n%s' % ( + kind, adapter, op, clamp, expected, res.stdout, res.stderr)) + print('%s %s %s clamp=%d: %s' % (kind, adapter, op, clamp, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_dot2 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_dot2 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_dot2_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_dot4_check.py b/tests/startup_gfx2hlsl_v_dot4_check.py new file mode 100644 index 0000000000..7322b7a3e6 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_dot4_check.py @@ -0,0 +1,308 @@ +"""VOP3P 4-byte integer dot products (v_dot4_i32_i8, v_dot4_u32_u8) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, on-demand helpers, value evaluation (wrapping and clamp), + EXEC masking, refusal and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +RDNA 2 ISA, VOP3P (0x16 / 0x17): + V_DOT4_I32_I8 vD, S0, S1, S2 [clamp]: D = sum_{k=0..3} int8(S0_k)*int8(S1_k) + int32(S2) (sat int32 if clamp) + V_DOT4_U32_U8 vD, S0, S1, S2 [clamp]: D = sum_{k=0..3} uint8(S0_k)*uint8(S1_k) + uint32(S2) (sat uint32 if clamp) + +The pixel fixture decodes synthetic gfx1013 VOP3P bytes via G.decode() ONLY (no game data). It reads three +flat parameters (v0..v3, v4..v7, v8..v11), computes v_dot4_* across all four lanes into v12..v15, and exports mrt0. +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OPCODES = { + 'v_dot4_i32_i8': 0x16, + 'v_dot4_u32_u8': 0x17, +} + + +def vop3p(op, vdst, src0, src1, src2, *, clamp=0, op_sel=0, op_sel_hi=0b111, neg_lo=0, neg_hi=0, lit=None): + """Encode one synthetic gfx1013 VOP3P 64-bit (or 96-bit with literal) instruction.""" + w0 = (0xcc000000 + | (op << 16) + | (clamp << 15) + | (((op_sel_hi >> 2) & 1) << 14) + | ((op_sel & 0x7) << 11) + | ((neg_hi & 0x7) << 8) + | (vdst & 0xff)) + w1 = (((neg_lo & 0x7) << 29) + | ((op_sel_hi & 0x3) << 27) + | ((src2 & 0x1ff) << 18) + | ((src1 & 0x1ff) << 9) + | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def ps_words(op, clamp=0): + code = OPCODES[op] + body = b''.join( + vop3p(code, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane, clamp=clamp) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext8(b): + b &= 0xff + return b - 256 if b >= 128 else b + + +def sext32(v): + v &= MASK + return v - (1 << 32) if v >= (1 << 31) else v + + +def ref_dot4_u32_u8(a, b, c, clamp=False): + s = sum(((a >> (8 * k)) & 0xff) * ((b >> (8 * k)) & 0xff) for k in range(4)) + total = (c & MASK) + s + if clamp and total > MASK: + return MASK + return total & MASK + + +def ref_dot4_i32_i8(a, b, c, clamp=False): + s = sum(sext8(a >> (8 * k)) * sext8(b >> (8 * k)) for k in range(4)) + total = sext32(c) + s + if clamp: + if total > 0x7fffffff: + return 0x7fffffff + if total < -0x80000000: + return 0x80000000 + return total & MASK + + +def eval_dot4_u32_u8_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + s = (((a & 0xff) * (b & 0xff) + + ((a >> 8) & 0xff) * ((b >> 8) & 0xff) + + ((a >> 16) & 0xff) * ((b >> 16) & 0xff) + + ((a >> 24) & 0xff) * ((b >> 24) & 0xff)) & MASK) + r = (c + s) & MASK + return 0xffffffff if (sat and r < c) else r + + +def eval_dot4_i32_i8_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + s = (sext8(a) * sext8(b) + + sext8(a >> 8) * sext8(b >> 8) + + sext8(a >> 16) * sext8(b >> 16) + + sext8(a >> 24) * sext8(b >> 24)) + r = (c + (s & MASK)) & MASK + if sat and sext32(c) > 0 and s > 0 and sext32(r) < 0: + return 0x7fffffff + if sat and sext32(c) < 0 and s < 0 and sext32(r) >= 0: + return 0x80000000 + return r + + +def stage_refused(stage, op, line, needle=''): + try: + stage.one(op, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS_A = (0x00000000, 0xffffffff, 0x80808080, 0x7f7f7f7f, 0x01020304, 0xfefdfcfb, 0x807f01ff) +WORDS_B = (0x00000000, 0xffffffff, 0x80808080, 0x7f7f7f7f, 0x05060708, 0x01ff807f) +ACCUMS = (0x00000000, 0x00000001, 0x7fffffff, 0x7fff0000, 0x80000000, 0x8000ffff, 0xffff0000, 0xffffffff) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 VOP3P bytes via G.decode(). + check('decode v_dot4_i32_i8 plain', + G.decode(vop3p(0x16, 12, 256, 260, 264))[0][3] == 'v_dot4_i32_i8 v12, v0, v4, v8') + check('decode v_dot4_i32_i8 clamp', + G.decode(vop3p(0x16, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot4_i32_i8 v12, v0, v4, v8 clamp') + check('decode v_dot4_u32_u8 plain', + G.decode(vop3p(0x17, 12, 256, 260, 264))[0][3] == 'v_dot4_u32_u8 v12, v0, v4, v8') + check('decode v_dot4_u32_u8 clamp', + G.decode(vop3p(0x17, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot4_u32_u8 v12, v0, v4, v8 clamp') + + # 2. Exhaustive grid for both wrapping and saturating modes. + u_ok = True + i_ok = True + for a in WORDS_A: + for b in WORDS_B: + for c in ACCUMS: + for sat in (False, True): + if eval_dot4_u32_u8_hlsl(a, b, c, sat) != ref_dot4_u32_u8(a, b, c, sat): + u_ok = False + if eval_dot4_i32_i8_hlsl(a, b, c, sat) != ref_dot4_i32_i8(a, b, c, sat): + i_ok = False + n_cases = len(WORDS_A) * len(WORDS_B) * len(ACCUMS) * 2 + check('v_dot4_u32_u8 grid (%d cases, wrap + clamp)' % n_cases, u_ok) + check('v_dot4_i32_i8 grid (%d cases, wrap + clamp)' % n_cases, i_ok) + + # 3. On-demand helper emission: each helper emitted only when its instruction is used. + _, ps_u = translate('v_dot4_u32_u8', 0) + _, ps_i = translate('v_dot4_i32_i8', 0) + check('dot4_u32_u8 emitted on demand and dot4_i32_i8 omitted', + 'uint dot4_u32_u8(' in ps_u and 'dot4_i32_i8' not in ps_u) + check('dot4_i32_i8 emitted on demand and dot4_u32_u8 omitted', + 'uint dot4_i32_i8(' in ps_i and 'dot4_u32_u8' not in ps_i) + check('dot4_i32_i8 helper keeps both signed overflow sign guards', + 'asint(c) > 0 && s > 0 && asint(r) < 0' in ps_i and + 'asint(c) < 0 && s < 0 && asint(r) >= 0' in ps_i) + zero = [(0, 0, 0)] * 4 + unused_ps = G.Pipeline(vs_words(zero), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('both dot4 helpers omitted when unused', 'dot4_' not in unused_ps) + + # 4. EXEC masking & clamp flag propagation. + for op, helper in (('v_dot4_u32_u8', 'dot4_u32_u8'), ('v_dot4_i32_i8', 'dot4_i32_i8')): + p = Probe() + p.exec_known = False + p.one(op, '%s v12, v0, v4, v8 clamp' % op) + check('%s exec-masked + clamp' % op, + p.lines == ['if (exec & 1) v12 = %s(v0, v4, v8, true);' % helper]) + + # 5. Refusals: arity, non-clamp VOP3P modifiers (op_sel, op_sel_hi, neg_lo, neg_hi), bad dst/src, source mods. + for op, code in OPCODES.items(): + check('%s 3 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3' % op, 'expected 4')) + check('%s 5 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3, v4, v5' % op, 'expected 4')) + for label, bad_word in ( + ('op_sel', vop3p(code, 12, 256, 260, 264, op_sel=1)), + ('op_sel_hi', vop3p(code, 12, 256, 260, 264, op_sel_hi=0)), + ('neg_lo', vop3p(code, 12, 256, 260, 264, neg_lo=1)), + ('neg_hi', vop3p(code, 12, 256, 260, 264, neg_hi=1)), + ): + asm = G.decode(bad_word)[0][3] + check('%s VOP3P %s refused' % (op, label), + stage_refused(Probe(), op, asm, 'unsupported modifiers')) + for bad_dst in ('s4', 'v[0:1]', 'v256'): + check('%s bad dst %s refused' % (op, bad_dst), + stage_refused(Probe(), op, '%s %s, v0, v4, v8' % (op, bad_dst), 'destination')) + for bad_src in ('|v0|', '-v0', 'neg(1)', 'v[0:1]', 's[0:1]', 'v256', 's106'): + check('%s bad src %s refused' % (op, bad_src), + stage_refused(Probe(), op, '%s v12, %s, v4, v8' % (op, bad_src))) + + # 6. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_v_dot4_i32_i8', 'op_v_dot4_u32_u8')} + try: + for name in saved: + delattr(G.Stage, name) + for op in OPCODES: + check('unlowered %s refused' % op, stage_refused(Probe(), op, '%s v12, v0, v4, v8' % op)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % op, True) + else: + check('unlowered %s pipeline refused' % op, False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + +# Four-lane draw cases covering wrapping, positive/negative signed sums, and saturation. +DRAW_CASES = ( + ('v_dot4_u32_u8', 0, [ + (0x01020304, 0x05060708, 0x3f800000), # 0x3f800000 + 70 + (0xff00ff00, 0x01000200, 0x3f800000), # 0x3f800000 + 765 + (0xffffffff, 0xffffffff, 0x3f800000), # 0x3f800000 + 260100 (max unsigned dot4) + (0x00000001, 0x00000001, 0xffffffff), # wraps cleanly to 0x00000000 (+0.0) + ]), + ('v_dot4_u32_u8', 1, [ + (0x01020304, 0x05060708, 0x3f800000), # no saturation + (0x00000001, 0x00000001, 0xfffffffe), # saturates to 0xffffffff + (0x10203040, 0x01010101, 0x40000000), # no saturation + (0x00000000, 0xffffffff, 0x3f800000), # zero sum + ]), + ('v_dot4_i32_i8', 0, [ + (0x01020304, 0x05060708, 0x3f800000), # positive sum (+70) + (0xfefdfcfb, 0x01020304, 0x3f800000), # negative sum (-40) + (0x80808080, 0x80808080, 0x3f800000), # (-128)*(-128)*4 = +65536 + (0x80808080, 0x7f7f7f7f, 0x3f800000), # (-128)*(+127)*4 = -65024 + ]), + ('v_dot4_i32_i8', 1, [ + (0x80808080, 0x80808080, 0x7fff0000), # positive overflow -> saturates to 0x7fffffff + (0x80808080, 0x7f7f7f7f, 0x80000000), # negative overflow -> saturates to 0x80000000 + (0x80808080, 0x7f7f7f7f, 0x3f800000), # no overflow + (0x01020304, 0x05060708, 0x3f800000), # no overflow + ]), + ('v_dot4_i32_i8', 1, [ + (0xfefdfcfb, 0x01020304, 0x00000001), # c > 0, s < 0, r < 0: no overflow (-39) + (0x01020304, 0x05060708, 0xffffffff), # c < 0, s > 0, r >= 0: no overflow (+69) + (0x7f7f7f7f, 0x7f7f7f7f, 0x7fff0000), # close to INT32_MAX, no overflow + (0x80808080, 0x7f7f7f7f, 0xffff0000), # negative + negative, no overflow + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_dot4_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for op, clamp, triples in DRAW_CASES: + ref_fn = ref_dot4_i32_i8 if op == 'v_dot4_i32_i8' else ref_dot4_u32_u8 + _, ps_hlsl = translate(op, clamp) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%d_%s' % (op, clamp, kind), ps_profile, td) + vs_hlsl = G.Pipeline(vs_words(triples), ps_words(op, clamp), root_blob()).hlsl_vs() + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%d_%s' % (op, clamp, kind), vs_profile, td) + raw_exp = tuple(ref_fn(a, b, c, bool(clamp)) for a, b, c in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s clamp=%d expected=%s\n%s\n%s' % ( + kind, adapter, op, clamp, expected, res.stdout, res.stderr)) + print('%s %s %s clamp=%d: %s' % (kind, adapter, op, clamp, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_dot4 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_dot4 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_dot4_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_dot8_check.py b/tests/startup_gfx2hlsl_v_dot8_check.py new file mode 100644 index 0000000000..8a62ccb59d --- /dev/null +++ b/tests/startup_gfx2hlsl_v_dot8_check.py @@ -0,0 +1,292 @@ +"""VOP3P 8-nibble integer dot products (v_dot8_i32_i4, v_dot8_u32_u4) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, on-demand helpers, value evaluation (wrapping and clamp), + EXEC masking, refusal and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +RDNA 2 ISA, VOP3P (0x18 / 0x19): + V_DOT8_I32_I4 vD, S0, S1, S2 [clamp]: D = sum_{k=0..7} int4(S0_k)*int4(S1_k) + int32(S2) (sat int32 if clamp) + V_DOT8_U32_U4 vD, S0, S1, S2 [clamp]: D = sum_{k=0..7} uint4(S0_k)*uint4(S1_k) + uint32(S2) (sat uint32 if clamp) + +The pixel fixture decodes synthetic gfx1013 VOP3P bytes via G.decode() ONLY (no game data). It reads three +flat parameters (v0..v3, v4..v7, v8..v11), computes v_dot8_* across all four lanes into v12..v15, and exports mrt0. +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OPCODES = { + 'v_dot8_i32_i4': 0x18, + 'v_dot8_u32_u4': 0x19, +} + + +def vop3p(op, vdst, src0, src1, src2, *, clamp=0, op_sel=0, op_sel_hi=0b111, neg_lo=0, neg_hi=0, lit=None): + """Encode one synthetic gfx1013 VOP3P 64-bit (or 96-bit with literal) instruction.""" + w0 = (0xcc000000 + | (op << 16) + | (clamp << 15) + | (((op_sel_hi >> 2) & 1) << 14) + | ((op_sel & 0x7) << 11) + | ((neg_hi & 0x7) << 8) + | (vdst & 0xff)) + w1 = (((neg_lo & 0x7) << 29) + | ((op_sel_hi & 0x3) << 27) + | ((src2 & 0x1ff) << 18) + | ((src1 & 0x1ff) << 9) + | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def ps_words(op, clamp=0): + code = OPCODES[op] + body = b''.join( + vop3p(code, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane, clamp=clamp) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext4(n): + n &= 0xf + return n - 16 if n >= 8 else n + + +def sext32(v): + v &= MASK + return v - (1 << 32) if v >= (1 << 31) else v + + +def ref_dot8_u32_u4(a, b, c, clamp=False): + s = sum(((a >> (4 * k)) & 0xf) * ((b >> (4 * k)) & 0xf) for k in range(8)) + total = (c & MASK) + s + if clamp and total > MASK: + return MASK + return total & MASK + + +def ref_dot8_i32_i4(a, b, c, clamp=False): + s = sum(sext4(a >> (4 * k)) * sext4(b >> (4 * k)) for k in range(8)) + total = sext32(c) + s + if clamp: + if total > 0x7fffffff: + return 0x7fffffff + if total < -0x80000000: + return 0x80000000 + return total & MASK + + +def eval_dot8_u32_u4_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + s = sum(((a >> (4 * k)) & 0xf) * ((b >> (4 * k)) & 0xf) for k in range(8)) & MASK + r = (c + s) & MASK + return 0xffffffff if (sat and r < c) else r + + +def eval_dot8_i32_i4_hlsl(a, b, c, sat): + a, b, c = a & MASK, b & MASK, c & MASK + s = sum(sext4(a >> (4 * k)) * sext4(b >> (4 * k)) for k in range(8)) + r = (c + (s & MASK)) & MASK + if sat and sext32(c) > 0 and s > 0 and sext32(r) < 0: + return 0x7fffffff + if sat and sext32(c) < 0 and s < 0 and sext32(r) >= 0: + return 0x80000000 + return r + + +def stage_refused(stage, op, line, needle=''): + try: + stage.one(op, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS_A = (0x00000000, 0xffffffff, 0x88888888, 0x77777777, 0x01234567, 0xfedcba98, 0x871f0e92) +WORDS_B = (0x00000000, 0xffffffff, 0x88888888, 0x77777777, 0x11223344, 0x78f1e029) +ACCUMS = (0x00000000, 0x00000001, 0x7fffffff, 0x7fffff00, 0x80000000, 0x800000ff, 0xffffff00, 0xffffffff) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 VOP3P bytes via G.decode(). + check('decode v_dot8_i32_i4 plain', + G.decode(vop3p(0x18, 12, 256, 260, 264))[0][3] == 'v_dot8_i32_i4 v12, v0, v4, v8') + check('decode v_dot8_i32_i4 clamp', + G.decode(vop3p(0x18, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot8_i32_i4 v12, v0, v4, v8 clamp') + check('decode v_dot8_u32_u4 plain', + G.decode(vop3p(0x19, 12, 256, 260, 264))[0][3] == 'v_dot8_u32_u4 v12, v0, v4, v8') + check('decode v_dot8_u32_u4 clamp', + G.decode(vop3p(0x19, 12, 256, 260, 264, clamp=1))[0][3] == 'v_dot8_u32_u4 v12, v0, v4, v8 clamp') + + # 2. Exhaustive grid for both wrapping and saturating modes. + u_ok = True + i_ok = True + for a in WORDS_A: + for b in WORDS_B: + for c in ACCUMS: + for sat in (False, True): + if eval_dot8_u32_u4_hlsl(a, b, c, sat) != ref_dot8_u32_u4(a, b, c, sat): + u_ok = False + if eval_dot8_i32_i4_hlsl(a, b, c, sat) != ref_dot8_i32_i4(a, b, c, sat): + i_ok = False + n_cases = len(WORDS_A) * len(WORDS_B) * len(ACCUMS) * 2 + check('v_dot8_u32_u4 grid (%d cases, wrap + clamp)' % n_cases, u_ok) + check('v_dot8_i32_i4 grid (%d cases, wrap + clamp)' % n_cases, i_ok) + + # 3. On-demand helper emission: each helper emitted only when its instruction is used. + _, ps_u = translate('v_dot8_u32_u4', 0) + _, ps_i = translate('v_dot8_i32_i4', 0) + check('dot8_u32_u4 emitted on demand and dot8_i32_i4 omitted', + 'uint dot8_u32_u4(' in ps_u and 'dot8_i32_i4' not in ps_u) + check('dot8_i32_i4 emitted on demand and dot8_u32_u4 omitted', + 'uint dot8_i32_i4(' in ps_i and 'dot8_u32_u4' not in ps_i) + zero = [(0, 0, 0)] * 4 + unused_ps = G.Pipeline(vs_words(zero), PRE_WORDS + POST_WORDS, root_blob()).hlsl_ps() + check('both dot8 helpers omitted when unused', 'dot8_' not in unused_ps) + + # 4. EXEC masking & clamp flag propagation. + for op, helper in (('v_dot8_u32_u4', 'dot8_u32_u4'), ('v_dot8_i32_i4', 'dot8_i32_i4')): + p = Probe() + p.exec_known = False + p.one(op, '%s v12, v0, v4, v8 clamp' % op) + check('%s exec-masked + clamp' % op, + p.lines == ['if (exec & 1) v12 = %s(v0, v4, v8, true);' % helper]) + + # 5. Refusals: arity, non-clamp VOP3P modifiers, bad dst/src, source modifiers. + for op, code in OPCODES.items(): + check('%s 3 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3' % op, 'expected 4')) + check('%s 5 operands refused' % op, stage_refused(Probe(), op, '%s v1, v2, v3, v4, v5' % op, 'expected 4')) + for label, bad_word in ( + ('op_sel', vop3p(code, 12, 256, 260, 264, op_sel=1)), + ('op_sel_hi', vop3p(code, 12, 256, 260, 264, op_sel_hi=0)), + ('neg_lo', vop3p(code, 12, 256, 260, 264, neg_lo=1)), + ('neg_hi', vop3p(code, 12, 256, 260, 264, neg_hi=1)), + ): + asm = G.decode(bad_word)[0][3] + check('%s VOP3P %s refused' % (op, label), + stage_refused(Probe(), op, asm, 'unsupported modifiers')) + for bad_dst in ('s4', 'v[0:1]', 'v256'): + check('%s bad dst %s refused' % (op, bad_dst), + stage_refused(Probe(), op, '%s %s, v0, v4, v8' % (op, bad_dst), 'destination')) + for bad_src in ('|v0|', '-v0', 'neg(1)', 'v[0:1]', 's[0:1]', 'v256', 's106'): + check('%s bad src %s refused' % (op, bad_src), + stage_refused(Probe(), op, '%s v12, %s, v4, v8' % (op, bad_src))) + + # 6. Unlowered control: removing handlers from Stage restores refusals. + saved = {name: getattr(G.Stage, name) for name in ('op_v_dot8_i32_i4', 'op_v_dot8_u32_u4')} + try: + for name in saved: + delattr(G.Stage, name) + for op in OPCODES: + check('unlowered %s refused' % op, stage_refused(Probe(), op, '%s v12, v0, v4, v8' % op)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % op, True) + else: + check('unlowered %s pipeline refused' % op, False) + finally: + for name, fn in saved.items(): + setattr(G.Stage, name, fn) + + +DRAW_CASES = ( + ('v_dot8_u32_u4', 0, [ + (0x01234567, 0x11111111, 0x3f800000), # +28 + (0xffffffff, 0xffffffff, 0x3f800000), # +1800 (max unsigned dot8) + (0xf0f0f0f0, 0x20202020, 0x3f800000), # +120 + (0x00000001, 0x00000001, 0xffffffff), # wraps cleanly to 0x00000000 + ]), + ('v_dot8_u32_u4', 1, [ + (0x01234567, 0x11111111, 0x3f800000), # no saturation + (0x00000001, 0x00000001, 0xfffffffe), # saturates to 0xffffffff + (0x12345678, 0x11111111, 0x40000000), # no saturation + (0x00000000, 0xffffffff, 0x3f800000), # zero sum + ]), + ('v_dot8_i32_i4', 0, [ + (0x01234567, 0x11111111, 0x3f800000), # positive sum (+28) + (0xffffffff, 0x11111111, 0x3f800000), # negative sum (-8) + (0x88888888, 0x88888888, 0x3f800000), # (-8)*(-8)*8 = +512 + (0x88888888, 0x77777777, 0x3f800000), # (-8)*(+7)*8 = -448 + ]), + ('v_dot8_i32_i4', 1, [ + (0x88888888, 0x88888888, 0x7fffff00), # positive overflow -> saturates to 0x7fffffff + (0x88888888, 0x77777777, 0x80000000), # negative overflow -> saturates to 0x80000000 + (0x88888888, 0x77777777, 0x3f800000), # no overflow + (0x01234567, 0x11111111, 0x3f800000), # no overflow + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_dot8_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for op, clamp, triples in DRAW_CASES: + ref_fn = ref_dot8_i32_i4 if op == 'v_dot8_i32_i4' else ref_dot8_u32_u4 + _, ps_hlsl = translate(op, clamp) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s_%d_%s' % (op, clamp, kind), ps_profile, td) + vs_hlsl = G.Pipeline(vs_words(triples), ps_words(op, clamp), root_blob()).hlsl_vs() + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%s_%d_%s' % (op, clamp, kind), vs_profile, td) + raw_exp = tuple(ref_fn(a, b, c, bool(clamp)) for a, b, c in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s clamp=%d expected=%s\n%s\n%s' % ( + kind, adapter, op, clamp, expected, res.stdout, res.stderr)) + print('%s %s %s clamp=%d: %s' % (kind, adapter, op, clamp, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_dot8 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_dot8 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_dot8_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_mad_i32_i16_check.py b/tests/startup_gfx2hlsl_v_mad_i32_i16_check.py new file mode 100644 index 0000000000..808e89126b --- /dev/null +++ b/tests/startup_gfx2hlsl_v_mad_i32_i16_check.py @@ -0,0 +1,253 @@ +"""Signed 16x16+32 multiply-add (v_mad_i32_i16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3A decode, value evaluation, low16_only_v compatibility, EXEC masking, + encoding & Stage refusals, unlowered and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +RDNA 2 ISA, VOP3A (0x375): + V_MAD_I32_I16 vD, S0, S1, S2: D = int32(int16(S0[15:0]) * int16(S1[15:0])) + int32(S2) (mod 2^32). +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + + +def vop3a(op, vdst, src0, src1, src2, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0, lit=None): + w0 = 0xd4000000 | ((op & 0x3ff) << 16) | (clamp << 15) | (op_sel << 11) | (abs_bits << 8) | (vdst & 0xff) + w1 = (neg << 29) | (omod << 27) | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def ps_words(): + body = b''.join(vop3a(0x375, 12 + lane, 256 + lane, 256 + 4 + lane, 256 + 8 + lane) for lane in range(4)) + return PRE_WORDS + body + POST_WORDS + + +def translate(): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def ref_mad_i32_i16(a, b, c): + return (sext16(a) * sext16(b) + (c & MASK)) & MASK + + +def stage_refused(stage, line, needle=''): + try: + stage.one('v_mad_i32_i16', line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +WORDS_A = (0x00000000, 0xdead0001, 0xbeef7fff, 0x12348000, 0x5678ffff, 0x0000fffe) +WORDS_B = (0x00000000, 0xcafe0001, 0xbabe7fff, 0x9abc8000, 0xdef0ffff, 0x00000002) +ACCUMS = (0x00000000, 0x00000001, 0x3f800000, 0x7fffffff, 0x80000000, 0xffffffff) + + +def eval_emitted_u32(expr, env): + """Evaluate a 32-bit HLSL uint/int expression (with asint/asuint, shifts, +, *) in Python.""" + import ast + + def to_i32(x): + x &= MASK + return x - 0x100000000 if x >= 0x80000000 else x + + def to_u32(x): + return x & MASK + + def ev(node): + if isinstance(node, ast.Expression): + return ev(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + arg = ev(node.args[0]) + if node.func.id == 'asint': + return to_i32(arg) + if node.func.id == 'asuint': + return to_u32(arg) + raise ValueError(f'unsupported call {node.func.id}') + if isinstance(node, ast.BinOp): + l, r = ev(node.left), ev(node.right) + if isinstance(node.op, ast.LShift): + return to_u32(l << (r & 31)) + if isinstance(node.op, ast.RShift): + return to_i32(l) >> (r & 31) if l < 0 or isinstance(node.left, ast.Call) and getattr(node.left.func, 'id', '') == 'asint' else to_u32(l) >> (r & 31) + if isinstance(node.op, ast.Mult): + return to_u32(l * r) + if isinstance(node.op, ast.Add): + return to_u32(l + r) + if isinstance(node.op, ast.BitAnd): + return to_u32(l & r) + raise ValueError(f'unsupported op {node.op}') + raise ValueError(f'unsupported node {ast.dump(node)}') + + import re + cleaned = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + return to_u32(ev(ast.parse(cleaned, mode='eval'))) + + +def run_controls(): + # 1. Decode verification from synthetic gfx1013 VOP3A bytes via G.decode(). + check('decode v_mad_i32_i16', + G.decode(vop3a(0x375, 12, 256, 260, 264))[0][3] == 'v_mad_i32_i16 v12, v0, v4, v8') + + # 2. Exhaustive grid against the emitted HLSL expression (upper 16 bits of S0/S1 ignored; signed 16-bit). + p_expr = Probe() + p_expr.one('v_mad_i32_i16', 'v_mad_i32_i16 v12, v0, v4, v8') + check('emitted v_mad_i32_i16 assignment', + len(p_expr.lines) == 1 and p_expr.lines[0].startswith('v12 = ') and p_expr.lines[0].endswith(';')) + emitted_rhs = p_expr.lines[0][len('v12 = '):-1] + grid_ok = True + for a in WORDS_A: + for b in WORDS_B: + for c in ACCUMS: + got = eval_emitted_u32(emitted_rhs, {'v0': a & MASK, 'v4': b & MASK, 'v8': c & MASK}) + if got != ref_mad_i32_i16(a, b, c): + grid_ok = False + check('v_mad_i32_i16 grid (%d cases)' % (len(WORDS_A) * len(WORDS_B) * len(ACCUMS)), grid_ok) + + # 3. Pipeline translates; EXEC masking works; low16_only_v accepted for S0/S1 and refused for S2. + _, ps_hlsl = translate() + check('pipeline translates', '<< 16) >> 16' in ps_hlsl) + p = Probe() + p.exec_known = False + p.one('v_mad_i32_i16', 'v_mad_i32_i16 v12, v0, v4, v8') + check('exec-masked v_mad_i32_i16 guards assignment', + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + p_lo = Probe() + p_lo.low16_only_v = {0, 4} + p_lo.one('v_mad_i32_i16', 'v_mad_i32_i16 v12, v0, v4, v8') + check('low16_only_v accepted on S0 and S1', len(p_lo.lines) == 1) + p_s2 = Probe() + p_s2.low16_only_v = {8} + check('low16_only_v refused on S2 (32-bit addend)', + stage_refused(p_s2, 'v_mad_i32_i16 v12, v0, v4, v8', 'whole-word read')) + + # 4. VOP3A encoding guard refuses neg/abs. + for label, bad_word in ( + ('abs0', vop3a(0x375, 12, 256, 260, 264, abs_bits=1)), + ('neg2', vop3a(0x375, 12, 256, 260, 264, neg=4)), + ('neg_inline0', vop3a(0x375, 12, 129, 260, 264, neg=1)), + ): + reasons = [] + G.decode(bad_word, reasons) + check('encoding guard refuses %s' % label, + len(reasons) == 1 and 'with neg/abs' in reasons[0][0]) + + # 5. Stage refusals: modifiers, abs/neg, wrong arity. + for asm in ( + 'v_mad_i32_i16 v12, v0, v4, v8 clamp', + 'v_mad_i32_i16 v12, v0, v4, v8 mul:2', + 'v_mad_i32_i16 v12, v0, v4, v8 op_sel:[1,0,0]', + 'v_mad_i32_i16 v12, |v0|, v4, v8', + 'v_mad_i32_i16 v12, v0, -v4, v8', + 'v_mad_i32_i16 v12, v0, v4', + 'v_mad_i32_i16 v12, v0, v4, v8, v9', + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), asm)) + + # 6. Unlowered control: removing v_mad_i32_i16 from VEC_U restores refusals. + saved = G.VEC_U.pop('v_mad_i32_i16') + try: + check('unlowered v_mad_i32_i16 refused', stage_refused(Probe(), 'v_mad_i32_i16 v12, v0, v4, v8')) + try: + translate() + except G.Unsupported: + check('unlowered pipeline refused', True) + else: + check('unlowered pipeline refused', False) + finally: + G.VEC_U['v_mad_i32_i16'] = saved + + +DRAW_BATCHES = ( + [ + (0xdead0003, 0xbeef0005, 0x3f800000), # (+3)*(+5) + 0x3f800000 (upper 16 bits ignored) + (0x1234ffff, 0x56780007, 0x3f800010), # (-1)*(+7) + 0x3f800010 = 0x3f800009 + (0xabcd8000, 0xef018000, 0x3f800000), # (-32768)*(-32768) = +0x40000000 -> 0x7f800000 (+inf, exact) + (0x00008000, 0x00007fff, 0x80000000), # (-32768)*(+32767) + 0x80000000 = 0x40008000 + ], + [ + (0x0000fffe, 0x0000fffd, 0x3f800000), # (-2)*(-3) + 0x3f800000 = 0x3f800006 + (0xffff0000, 0xffff7fff, 0x40000000), # 0*(+32767) + 0x40000000 = 0x40000000 + (0x00000001, 0x00000001, 0xffffffff), # wraps cleanly to 0x00000000 + (0x99990010, 0x8888fff0, 0x3f800100), # (+16)*(-16) + 0x3f800100 = 0x3f800000 + ], +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + _, ps_hlsl = translate() + with tempfile.TemporaryDirectory(prefix='x2w_v_mad_i32_i16_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_%s' % kind, ps_profile, td) + first_vs = None + first_exp = None + for b_idx, triples in enumerate(DRAW_BATCHES): + vs_hlsl = G.Pipeline(vs_words(triples), ps_words(), root_blob()).hlsl_vs() + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, 'vs_%d_%s' % (b_idx, kind), vs_profile, td) + raw_exp = tuple(ref_mad_i32_i16(a, b, c) for a, b, c in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s batch=%d expected=%s\n%s\n%s' % ( + kind, adapter, b_idx, expected, res.stdout, res.stderr)) + print('%s %s batch=%d: %s' % (kind, adapter, b_idx, expected), flush=True) + if first_vs is None: + first_vs, first_exp = vs_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, ps_bin, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_mad_i32_i16 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_mad_i32_i16 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_mad_i32_i16_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py b/tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py new file mode 100644 index 0000000000..08b3de54e0 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_pk_add_sub_16_check.py @@ -0,0 +1,388 @@ +"""Packed 16-bit integer add/sub (v_pk_add/sub_i16, v_pk_add/sub_u16, with and without clamp) in gfx2hlsl.py. + + (no arguments) VOP3P decode, value evaluation against emitted HLSL across op_sel/op_sel_hi + and clamp, EXEC masking, low16_only_v rules, refusals, unlowered controls + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +RDNA 2 ISA, VOP3P: + V_PK_ADD_I16 (0x02), V_PK_SUB_I16 (0x03): lane-wise signed 16-bit add/sub (saturating to [-32768, 32767] with clamp). + V_PK_ADD_U16 (0x0a), V_PK_SUB_U16 (0x0b): lane-wise unsigned 16-bit add/sub (saturating to [0, 65535] with clamp). +""" +import ast +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OP_ADD_I16 = 0x02 +OP_SUB_I16 = 0x03 +OP_ADD_U16 = 0x0a +OP_SUB_U16 = 0x0b +ALL_OPS = ( + (OP_ADD_I16, 'v_pk_add_i16', True, False), + (OP_SUB_I16, 'v_pk_sub_i16', True, True), + (OP_ADD_U16, 'v_pk_add_u16', False, False), + (OP_SUB_U16, 'v_pk_sub_u16', False, True), +) +XOR_MASK = 0x3f800000 + + +def vop3p(op, vdst, src0, src1, src2=0, *, op_sel=0, op_sel_hi=3, neg_lo=0, neg_hi=0, clamp=0, lit=None): + w0 = (0xcc000000 | ((op & 0x7f) << 16) | (clamp << 15) | ((op_sel & 7) << 11) + | ((neg_hi & 7) << 8) | (vdst & 0xff)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def v_xor_lit(vdst, vsrc, lit): + w = (0x1d << 25) | ((vdst & 0xff) << 17) | ((vsrc & 0xff) << 9) | 255 + return struct.pack('<2I', w, lit & MASK) + + +def ps_words(op, op_sel=0, op_sel_hi=3, clamp=0): + body = b''.join( + vop3p(op, 12 + lane, 256 + lane, 256 + 4 + lane, op_sel=op_sel, op_sel_hi=op_sel_hi, clamp=clamp) + + v_xor_lit(12 + lane, 12 + lane, XOR_MASK) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, op_sel=0, op_sel_hi=3, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi, clamp=clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def ref_pk_add_sub(a, b, signed, is_sub, clamp, op_sel=0, op_sel_hi=3): + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xffff + + def lane(sel_mask): + x = pick(a, sel_mask & 1) + y = pick(b, (sel_mask >> 1) & 1) + if signed: + xv, yv = sext16(x), sext16(y) + r = xv - yv if is_sub else xv + yv + if clamp: + r = max(-32768, min(32767, r)) + return r & 0xffff + r = x - y if is_sub else x + y + if clamp: + r = max(0, min(0xffff, r)) + return r & 0xffff + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def rewrite_ternaries(s): + """Convert parenthesized C/HLSL `(cond ? t : f)` into Python `((t) if (cond) else (f))`.""" + while '?' in s: + q = s.index('?') + depth = 0 + start = q - 1 + while start >= 0: + if s[start] == ')': + depth += 1 + elif s[start] == '(': + if depth == 0: + break + depth -= 1 + start -= 1 + depth = 0 + colon = q + 1 + while colon < len(s): + if s[colon] == '(': + depth += 1 + elif s[colon] == ')': + depth -= 1 + elif s[colon] == ':' and depth == 0: + break + colon += 1 + depth = 0 + end = colon + 1 + while end < len(s): + if s[end] == '(': + depth += 1 + elif s[end] == ')': + if depth == 0: + break + depth -= 1 + end += 1 + cond = s[start + 1:q].strip() + t_br = s[q + 1:colon].strip() + f_br = s[colon + 1:end].strip() + s = s[:start] + '((%s) if (%s) else (%s))' % (t_br, cond, f_br) + s[end + 1:] + return s + + +def eval_hlsl_u32(expr, env): + """Evaluate the emitted 32-bit HLSL expression (including inline ternaries and clamp) in Python.""" + cleaned = rewrite_ternaries(re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr)) + + class I32(int): + pass + + def to_i32(x): + x &= MASK + return I32(x - 0x100000000 if x >= 0x80000000 else x) + + def to_u32(x): + return int(x) & MASK + + def ev(node): + if isinstance(node, ast.Expression): + return ev(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): + return I32(-ev(node.operand)) + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.IfExp): + return ev(node.body) if ev(node.test) else ev(node.orelse) + if isinstance(node, ast.Compare) and len(node.ops) == 1: + lv, rv = to_u32(ev(node.left)), to_u32(ev(node.comparators[0])) + if isinstance(node.ops[0], ast.Gt): + return int(lv > rv) + if isinstance(node.ops[0], ast.Lt): + return int(lv < rv) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + fn = node.func.id + args = [ev(a) for a in node.args] + if fn == 'asint': + return to_i32(args[0]) + if fn == 'asuint': + return to_u32(args[0]) + if fn == 'min': + return min(args[0], args[1]) + if fn == 'clamp': + res = max(args[1], min(args[2], args[0])) + return I32(res) if isinstance(args[0], I32) else to_u32(res) + raise ValueError('unsupported call %s' % fn) + if isinstance(node, ast.BinOp): + l, r = ev(node.left), ev(node.right) + signed_bin = isinstance(l, I32) or isinstance(r, I32) + if isinstance(node.op, ast.Add): + return to_i32(l + r) if signed_bin else to_u32(l + r) + if isinstance(node.op, ast.Sub): + return to_i32(l - r) if signed_bin else to_u32(l - r) + if isinstance(node.op, ast.LShift): + return to_u32(l << (r & 31)) + if isinstance(node.op, ast.RShift): + return I32(to_i32(l) >> (r & 31)) if isinstance(l, I32) else to_u32(l) >> (r & 31) + if isinstance(node.op, ast.BitAnd): + return to_u32(l & r) + if isinstance(node.op, ast.BitOr): + return to_u32(l | r) + raise ValueError('unsupported binop %s' % node.op) + raise ValueError('unsupported node %s' % ast.dump(node)) + + return to_u32(ev(ast.parse(cleaned, mode='eval'))) + + +def stage_refused(stage, name, line, needle=''): + try: + stage.one(name, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +EDGE_WORDS = ( + 0x00000000, 0x0001ffff, 0x7fff8000, 0x80007fff, + 0xffff0001, 0x4000c000, 0x7ffe8001, 0xdeadbeef, +) + + +def run_controls(): + # 1. Decode verification via G.decode(). + for op, name, _, _ in ALL_OPS: + check('decode %s default' % name, + G.decode(vop3p(op, 12, 256, 260))[0][3] == '%s v12, v0, v4' % name) + check('decode %s clamp' % name, + G.decode(vop3p(op, 12, 256, 260, clamp=1))[0][3] == '%s v12, v0, v4 clamp' % name) + check('decode %s op_sel/op_sel_hi/clamp' % name, + G.decode(vop3p(op, 12, 256, 260, op_sel=1, op_sel_hi=2, clamp=1))[0][3] + == '%s v12, v0, v4 op_sel:[1,0] op_sel_hi:[0,1] clamp' % name) + check('decode %s rejects reserved src2' % name, + G.decode(vop3p(op, 12, 256, 260, src2=1))[0][2] == '%s_unsupported' % name) + + # 2. Exhaustive grid evaluated directly against emitted HLSL across clamp={0,1} and 2 op_sel configs (1024 cases). + for op, name, signed, is_sub in ALL_OPS: + for clamp in (0, 1): + for op_sel, op_sel_hi, mod_str in ( + (0, 3, ''), + (1, 2, ' op_sel:[1,0] op_sel_hi:[0,1]'), + ): + p = Probe() + asm = '%s v12, v0, v4%s%s' % (name, mod_str, ' clamp' if clamp else '') + p.one(name, asm) + check('emitted %s' % asm, + len(p.lines) == 1 and p.lines[0].startswith('v12 = ') and p.lines[0].endswith(';')) + rhs = p.lines[0][len('v12 = '):-1] + ok = True + for a in EDGE_WORDS: + for b in EDGE_WORDS: + if eval_hlsl_u32(rhs, {'v0': a, 'v4': b}) != ref_pk_add_sub( + a, b, signed, is_sub, clamp, op_sel, op_sel_hi): + ok = False + check('%s%s%s grid (%d cases)' % ( + name, mod_str, ' clamp' if clamp else '', len(EDGE_WORDS) ** 2), ok) + + # 3. EXEC masking and low16_only_v tracking. + for _, name, _, _ in ALL_OPS: + for suffix in ('', ' clamp'): + p = Probe() + p.exec_known = False + p.one(name, '%s v12, v0, v4%s' % (name, suffix)) + check('exec-masked %s%s guards assignment' % (name, suffix), + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + p_lo = Probe() + p_lo.low16_only_v = {0, 4} + p_lo.one(name, '%s v12, v0, v4 op_sel:[0,0] op_sel_hi:[0,0]' % name) + check('%s accepts low16_only_v when only low halves are read' % name, len(p_lo.lines) == 1) + + p_hi = Probe() + p_hi.low16_only_v = {0} + check('%s refuses low16_only_v when high half is read' % name, + stage_refused(p_hi, name, '%s v12, v0, v4' % name, 'whole-word read')) + + # 4. Stage refusals: neg_lo, neg_hi, duplicate clamp, bad op_sel, wrong arity, lane mask, bad dst. + for _, name, _, _ in ALL_OPS: + for asm in ( + '%s v12, v0, v4 clamp clamp' % name, + '%s v12, v0, v4 neg_lo:[1,0]' % name, + '%s v12, v0, v4 neg_hi:[0,1]' % name, + '%s v12, v0, v4 op_sel:[1,0,0]' % name, + '%s v12, v0, v4 op_sel:[2,0]' % name, + '%s v12, v0' % name, + '%s v12, v0, v4, v8' % name, + '%s v12, vcc_lo, v4' % name, + '%s s0, v0, v4' % name, + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), name, asm)) + + # 5. Unlowered control: removing handlers from Stage restores refusals. + for op, name, _, _ in ALL_OPS: + attr = 'op_' + name + saved = getattr(G.Stage, attr) + delattr(G.Stage, attr) + try: + check('unlowered %s refused' % name, stage_refused(Probe(), name, '%s v12, v0, v4' % name)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % name, True) + else: + check('unlowered %s pipeline refused' % name, False) + finally: + setattr(G.Stage, attr, saved) + + +DRAW_CASES = ( + (OP_ADD_I16, True, False, 0, 0, 3, 'add_i16_wrap', [ + (0x7fff8000, 0x0001ffff, 0), # hi: 0x7fff+1=0x8000 (wrap), lo: 0x8000+(-1)=0x7fff (wrap) + (0x00030005, 0x0007000b, 0), # hi: 10, lo: 16 + (0xffff0001, 0x0001ffff, 0), # hi: 0, lo: 0 (no carry bleed!) + (0x80008000, 0x80008000, 0), # hi: 0, lo: 0 + ]), + (OP_ADD_I16, True, False, 1, 0, 3, 'add_i16_clamp', [ + (0x7fff8000, 0x0001ffff, 0), # hi: +32767+1 -> 0x7fff, lo: -32768-1 -> 0x8000 + (0x4000c000, 0x4000c000, 0), # hi: +16384+16384 -> 0x7fff, lo: -16384-16384 -> 0x8000 + (0x7fff8000, 0x80007fff, 0), # opposite signs: -1 in both lanes (0xffffffff) + (0x0003fffd, 0x00050002, 0), # hi: +8, lo: -1 + ]), + (OP_SUB_I16, True, True, 1, 1, 2, 'sub_i16_clamp_swizzle', [ + # op_sel=[1,0] (a.hi - b.lo), op_sel_hi=[0,1] (a.lo - b.hi) + (0x00008000, 0x00018000, 0), # lo: 0 - (-32768) -> 0x7fff; hi: -32768 - 1 -> 0x8000 + (0x7fffffff, 0x8000ffff, 0), # lo: +32767 - (-1) -> 0x7fff; hi: -1 - (-32768) -> 0x7fff + (0x80000005, 0x000a7fff, 0), # lo: -32768 - 32767 -> 0x8000; hi: 5 - 10 = -5 (0xfffb) + (0x12345678, 0x56781234, 0), # lo: 0, hi: 0 + ]), + (OP_ADD_U16, False, False, 1, 0, 3, 'add_u16_clamp', [ + (0xffff8000, 0x00018000, 0), # hi: 0xffff, lo: 0xffff + (0x0003fffe, 0x00050001, 0), # hi: 8, lo: 0xffff (exact max) + (0x00000000, 0x12345678, 0), # 0x12345678 + (0xdeadbeef, 0x11112222, 0), # hi: 0xefbe, lo: 0xe111 + ]), + (OP_SUB_U16, False, True, 1, 0, 3, 'sub_u16_clamp', [ + (0x00010005, 0x00020003, 0), # hi: 1-2 -> 0, lo: 5-3 = 2 + (0x0000ffff, 0xffff0001, 0), # hi: 0, lo: 0xfffe + (0x80007fff, 0x7fff8000, 0), # hi: 1, lo: 0 + (0x12345678, 0x12345678, 0), # 0 + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_pk_add_sub_16_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = first_ps = first_exp = None + for op, signed, is_sub, clamp, op_sel, op_sel_hi, label, triples in DRAW_CASES: + pipe = G.Pipeline(vs_words(triples), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi, clamp=clamp), + root_blob()) + vs_bin = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = tuple(ref_pk_add_sub(a, b, signed, is_sub, clamp, op_sel, op_sel_hi) ^ XOR_MASK + for a, b, _ in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_pk_add/sub_16 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_pk_add/sub_16 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_pk_add_sub_16_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py b/tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py new file mode 100644 index 0000000000..7346ba7223 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py @@ -0,0 +1,316 @@ +"""Packed 16-bit integer min/max (v_pk_min/max_i16, v_pk_min/max_u16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, value evaluation against emitted HLSL across op_sel/op_sel_hi, + EXEC masking, low16_only_v rules, refusals, unlowered controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +RDNA 2 ISA, VOP3P: + V_PK_MAX_I16 (0x07), V_PK_MIN_I16 (0x08): lane-wise signed 16-bit max/min with op_sel / op_sel_hi. + V_PK_MAX_U16 (0x0c), V_PK_MIN_U16 (0x0d): lane-wise unsigned 16-bit max/min with op_sel / op_sel_hi. +""" +import ast +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OP_MAX_I16 = 0x07 +OP_MIN_I16 = 0x08 +OP_MAX_U16 = 0x0c +OP_MIN_U16 = 0x0d +ALL_OPS = ( + (OP_MAX_I16, 'v_pk_max_i16', True, True), + (OP_MIN_I16, 'v_pk_min_i16', True, False), + (OP_MAX_U16, 'v_pk_max_u16', False, True), + (OP_MIN_U16, 'v_pk_min_u16', False, False), +) +XOR_MASK = 0x3f800000 + + +def vop3p(op, vdst, src0, src1, src2=0, *, op_sel=0, op_sel_hi=3, neg_lo=0, neg_hi=0, clamp=0, lit=None): + w0 = (0xcc000000 | ((op & 0x7f) << 16) | (clamp << 15) | ((op_sel & 7) << 11) + | ((neg_hi & 7) << 8) | (vdst & 0xff)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def v_xor_lit(vdst, vsrc, lit): + w = (0x1d << 25) | ((vdst & 0xff) << 17) | ((vsrc & 0xff) << 9) | 255 + return struct.pack('<2I', w, lit & MASK) + + +def ps_words(op, op_sel=0, op_sel_hi=3): + # XOR with 0x3f800000 so arbitrary 16-bit packed results (including 0x7fff/0xffff) stay normal float32 values. + body = b''.join( + vop3p(op, 12 + lane, 256 + lane, 256 + 4 + lane, op_sel=op_sel, op_sel_hi=op_sel_hi) + + v_xor_lit(12 + lane, 12 + lane, XOR_MASK) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, op_sel=0, op_sel_hi=3): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def ref_pk_minmax(a, b, signed, is_max, op_sel=0, op_sel_hi=3): + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xffff + + def lane(sel_mask): + x = pick(a, sel_mask & 1) + y = pick(b, (sel_mask >> 1) & 1) + if signed: + xv, yv = sext16(x), sext16(y) + r = max(xv, yv) if is_max else min(xv, yv) + return r & 0xffff + return max(x, y) if is_max else min(x, y) + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def eval_hlsl_u32(expr, env): + """Evaluate the emitted 32-bit HLSL expression (asint/asuint, min/max, shifts, bitwise ops) in Python.""" + cleaned = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + + def to_i32(x): + x &= MASK + return x - 0x100000000 if x >= 0x80000000 else x + + def to_u32(x): + return x & MASK + + def ev(node): + if isinstance(node, ast.Expression): + return ev(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + fn = node.func.id + args = [ev(a) for a in node.args] + if fn == 'asint': + return to_i32(args[0]) + if fn == 'asuint': + return to_u32(args[0]) + if fn == 'max': + return max(args[0], args[1]) + if fn == 'min': + return min(args[0], args[1]) + raise ValueError('unsupported call %s' % fn) + if isinstance(node, ast.BinOp): + l, r = ev(node.left), ev(node.right) + if isinstance(node.op, ast.LShift): + return to_u32(l << (r & 31)) + if isinstance(node.op, ast.RShift): + is_signed = isinstance(node.left, ast.Call) and getattr(node.left.func, 'id', '') == 'asint' + return (to_i32(l) >> (r & 31)) if is_signed else (to_u32(l) >> (r & 31)) + if isinstance(node.op, ast.BitAnd): + return to_u32(l & r) + if isinstance(node.op, ast.BitOr): + return to_u32(l | r) + raise ValueError('unsupported binop %s' % node.op) + raise ValueError('unsupported node %s' % ast.dump(node)) + + return to_u32(ev(ast.parse(cleaned, mode='eval'))) + + +def stage_refused(stage, name, line, needle=''): + try: + stage.one(name, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +EDGE_HALVES = (0x0000, 0x0001, 0x7fff, 0x8000, 0xffff) +EDGE_WORDS = tuple((hi << 16) | lo for hi, lo in ( + (0x0000, 0x0000), (0x0001, 0xffff), (0x7fff, 0x8000), + (0x8000, 0x7fff), (0xffff, 0x0001), (0x1234, 0xfedc), + (0x8001, 0x7ffe), (0xdead, 0xbeef), +)) + + +def run_controls(): + # 1. Decode verification via G.decode(). + for op, name, _, _ in ALL_OPS: + check('decode %s default' % name, + G.decode(vop3p(op, 12, 256, 260))[0][3] == '%s v12, v0, v4' % name) + check('decode %s op_sel/op_sel_hi' % name, + G.decode(vop3p(op, 12, 256, 260, op_sel=1, op_sel_hi=2))[0][3] + == '%s v12, v0, v4 op_sel:[1,0] op_sel_hi:[0,1]' % name) + # Reserved src2 bitfield must decode as unsupported. + check('decode %s rejects reserved src2' % name, + G.decode(vop3p(op, 12, 256, 260, src2=1))[0][2] == '%s_unsupported' % name) + + # 2. Exhaustive grid directly against emitted HLSL for all 4 ops and 2 op_sel/op_sel_hi configs. + for op, name, signed, is_max in ALL_OPS: + for op_sel, op_sel_hi, mod_str in ( + (0, 3, ''), + (1, 2, ' op_sel:[1,0] op_sel_hi:[0,1]'), + (0, 0, ' op_sel:[0,0] op_sel_hi:[0,0]'), + ): + p = Probe() + asm = '%s v12, v0, v4%s' % (name, mod_str) + p.one(name, asm) + check('emitted %s' % asm, + len(p.lines) == 1 and p.lines[0].startswith('v12 = ') and p.lines[0].endswith(';')) + rhs = p.lines[0][len('v12 = '):-1] + ok = True + for a in EDGE_WORDS: + for b in EDGE_WORDS: + if eval_hlsl_u32(rhs, {'v0': a, 'v4': b}) != ref_pk_minmax(a, b, signed, is_max, op_sel, op_sel_hi): + ok = False + check('%s%s grid (%d cases)' % (name, mod_str, len(EDGE_WORDS) ** 2), ok) + + # 3. EXEC masking and low16_only_v tracking. + for _, name, _, _ in ALL_OPS: + p = Probe() + p.exec_known = False + p.one(name, '%s v12, v0, v4' % name) + check('exec-masked %s guards assignment' % name, + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + p_lo = Probe() + p_lo.low16_only_v = {0, 4} + p_lo.one(name, '%s v12, v0, v4 op_sel:[0,0] op_sel_hi:[0,0]' % name) + check('%s accepts low16_only_v when only low halves are read' % name, len(p_lo.lines) == 1) + + p_hi = Probe() + p_hi.low16_only_v = {0} + check('%s refuses low16_only_v when high half is read' % name, + stage_refused(p_hi, name, '%s v12, v0, v4' % name, 'whole-word read')) + + # 4. Stage refusals: clamp, neg_lo, neg_hi, bad op_sel, wrong arity, lane mask, bad dst. + for _, name, _, _ in ALL_OPS: + for asm in ( + '%s v12, v0, v4 clamp' % name, + '%s v12, v0, v4 neg_lo:[1,0]' % name, + '%s v12, v0, v4 neg_hi:[0,1]' % name, + '%s v12, v0, v4 op_sel:[1,0,0]' % name, + '%s v12, v0, v4 op_sel:[2,0]' % name, + '%s v12, v0' % name, + '%s v12, v0, v4, v8' % name, + '%s v12, vcc_lo, v4' % name, + '%s s0, v0, v4' % name, + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), name, asm)) + + # 5. Unlowered control: removing handlers from Stage restores refusals. + for op, name, _, _ in ALL_OPS: + attr = 'op_' + name + saved = getattr(G.Stage, attr) + delattr(G.Stage, attr) + try: + check('unlowered %s refused' % name, stage_refused(Probe(), name, '%s v12, v0, v4' % name)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % name, True) + else: + check('unlowered %s pipeline refused' % name, False) + finally: + setattr(G.Stage, attr, saved) + + +DRAW_CASES = ( + (OP_MAX_I16, True, True, 0, 3, 'max_i16', [ + (0x7fff8000, 0x80007fff, 0), # hi: max(+32767,-32768)=0x7fff, lo: max(-32768,+32767)=0x7fff + (0xffff0001, 0x0000ffff, 0), # hi: max(-1,0)=0x0000, lo: max(+1,-1)=0x0001 + (0x8000ffff, 0x8001fffe, 0), # hi: max(-32768,-32767)=0x8001, lo: max(-1,-2)=0xffff + (0x12345678, 0x12345678, 0), # equal lanes + ]), + (OP_MIN_I16, True, False, 1, 2, 'min_i16_swizzle', [ + # op_sel=[1,0] (a.hi vs b.lo), op_sel_hi=[0,1] (a.lo vs b.hi) + (0x7fff8000, 0x0001ffff, 0), # lo: min(+32767,-1)=0xffff; hi: min(-32768,+1)=0x8000 + (0xffff0002, 0xfffe0001, 0), # lo: min(-1,+1)=0xffff; hi: min(+2,-2)=0xfffe + (0x80007fff, 0x80007fff, 0), # lo: min(-32768,+32767)=0x8000; hi: min(+32767,-32768)=0x8000 + (0x00000000, 0xdeadbeef, 0), # lo: min(0,-16657)=0xbeef; hi: min(0,-8531)=0xdead + ]), + (OP_MAX_U16, False, True, 0, 3, 'max_u16', [ + (0x7fff8000, 0x80007fff, 0), # unsigned: 0x8000 > 0x7fff in both lanes -> 0x80008000 + (0xffff0001, 0x0000ffff, 0), # unsigned: 0xffffffff + (0x00000000, 0x00010002, 0), # 0x00010002 + (0x1234abcd, 0x56789abc, 0), # 0x5678abcd + ]), + (OP_MIN_U16, False, False, 0, 0, 'min_u16_broadcast_lo', [ + # op_sel=[0,0], op_sel_hi=[0,0]: both output lanes compute min(a.lo, b.lo) + (0xdead8000, 0xbeef7fff, 0), # min(0x8000, 0x7fff) = 0x7fff -> 0x7fff7fff + (0x1234ffff, 0x56780001, 0), # min(0xffff, 0x0001) = 0x0001 -> 0x00010001 + (0xffff0000, 0x0000ffff, 0), # min(0x0000, 0xffff) = 0x0000 -> 0x00000000 + (0x11112222, 0x33332222, 0), # min(0x2222, 0x2222) = 0x2222 -> 0x22222222 + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_pk_minmax_i16_u16_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = first_ps = first_exp = None + for op, signed, is_max, op_sel, op_sel_hi, label, triples in DRAW_CASES: + pipe = G.Pipeline(vs_words(triples), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi), root_blob()) + vs_bin = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = tuple(ref_pk_minmax(a, b, signed, is_max, op_sel, op_sel_hi) ^ XOR_MASK for a, b, _ in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_pk_min/max_i16/u16 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_pk_min/max_i16/u16 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_pk_minmax_i16_u16_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py b/tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py new file mode 100644 index 0000000000..2fdb9f2b9e --- /dev/null +++ b/tests/startup_gfx2hlsl_v_pk_mul_mad_16_check.py @@ -0,0 +1,359 @@ +"""Packed 16-bit integer multiply/mad (v_pk_mul_lo_u16, v_pk_mad_u16, v_pk_mad_i16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, value evaluation against emitted HLSL across op_sel/op_sel_hi + and clamp, EXEC masking, low16_only_v rules, refusals, unlowered controls + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +RDNA 2 ISA, VOP3P: + V_PK_MUL_LO_U16 (0x01): D_i = (S0_i * S1_i) & 0xffff (no clamp). + V_PK_MAD_U16 (0x09): D_i = S0_i * S1_i + S2_i (mod 2^16, or saturated to [0, 65535] with clamp). + V_PK_MAD_I16 (0x00): D_i = int16(S0_i) * int16(S1_i) + int16(S2_i) (mod 2^16, or saturated to [-32768, 32767]). +""" +import ast +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OP_MAD_I16 = 0x00 +OP_MUL_LO_U16 = 0x01 +OP_MAD_U16 = 0x09 +XOR_MASK = 0x3f800000 + + +def vop3p(op, vdst, src0, src1, src2=0, *, op_sel=0, op_sel_hi=7, neg_lo=0, neg_hi=0, clamp=0, lit=None): + w0 = (0xcc000000 | ((op & 0x7f) << 16) | (clamp << 15) | (((op_sel_hi >> 2) & 1) << 14) + | ((op_sel & 7) << 11) | ((neg_hi & 7) << 8) | (vdst & 0xff)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def v_xor_lit(vdst, vsrc, lit): + w = (0x1d << 25) | ((vdst & 0xff) << 17) | ((vsrc & 0xff) << 9) | 255 + return struct.pack('<2I', w, lit & MASK) + + +def ps_words(op, op_sel=0, op_sel_hi=7, clamp=0): + is_3src = op in (OP_MAD_I16, OP_MAD_U16) + body = b''.join( + vop3p(op, 12 + lane, 256 + lane, 256 + 4 + lane, (256 + 8 + lane) if is_3src else 0, + op_sel=op_sel, op_sel_hi=op_sel_hi if is_3src else (op_sel_hi & 3), clamp=clamp) + + v_xor_lit(12 + lane, 12 + lane, XOR_MASK) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, op_sel=0, op_sel_hi=7, clamp=0): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi, clamp=clamp), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def ref_op(op, a, b, c, clamp, op_sel=0, op_sel_hi=7): + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xffff + + def lane(sel_mask): + x = pick(a, sel_mask & 1) + y = pick(b, (sel_mask >> 1) & 1) + if op == OP_MUL_LO_U16: + return (x * y) & 0xffff + z = pick(c, (sel_mask >> 2) & 1) + if op == OP_MAD_I16: + r = sext16(x) * sext16(y) + sext16(z) + if clamp: + r = max(-32768, min(32767, r)) + return r & 0xffff + r = x * y + z + if clamp: + r = min(0xffff, r) + return r & 0xffff + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def eval_hlsl_u32(expr, env): + """Evaluate the emitted 32-bit HLSL expression in Python preserving signed/unsigned types.""" + cleaned = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + + class I32(int): + pass + + def to_i32(x): + x &= MASK + return I32(x - 0x100000000 if x >= 0x80000000 else x) + + def to_u32(x): + return int(x) & MASK + + def ev(node): + if isinstance(node, ast.Expression): + return ev(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub): + return I32(-ev(node.operand)) + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + fn = node.func.id + args = [ev(a) for a in node.args] + if fn == 'asint': + return to_i32(args[0]) + if fn == 'asuint': + return to_u32(args[0]) + if fn == 'min': + return min(args[0], args[1]) + if fn == 'clamp': + res = max(args[1], min(args[2], args[0])) + return I32(res) if isinstance(args[0], I32) else to_u32(res) + raise ValueError('unsupported call %s' % fn) + if isinstance(node, ast.BinOp): + l, r = ev(node.left), ev(node.right) + signed_bin = isinstance(l, I32) or isinstance(r, I32) + if isinstance(node.op, ast.Add): + return to_i32(l + r) if signed_bin else to_u32(l + r) + if isinstance(node.op, ast.Mult): + return to_i32(l * r) if signed_bin else to_u32(l * r) + if isinstance(node.op, ast.LShift): + return to_u32(l << (r & 31)) + if isinstance(node.op, ast.RShift): + return I32(to_i32(l) >> (r & 31)) if isinstance(l, I32) else to_u32(l) >> (r & 31) + if isinstance(node.op, ast.BitAnd): + return to_u32(l & r) + if isinstance(node.op, ast.BitOr): + return to_u32(l | r) + raise ValueError('unsupported binop %s' % node.op) + raise ValueError('unsupported node %s' % ast.dump(node)) + + return to_u32(ev(ast.parse(cleaned, mode='eval'))) + + +def stage_refused(stage, name, line, needle=''): + try: + stage.one(name, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +EDGE_A = (0x00000000, 0x0002ffff, 0x7fff8000, 0x80007fff, 0xffff0003) +EDGE_B = (0x00000000, 0x0003fffe, 0x7fff8000, 0x80000002, 0xffff0005) +EDGE_C = (0x00000000, 0x0001ffff, 0x7fff8000, 0xffff0001) + + +def run_controls(): + # 1. Decode verification via G.decode(). + check('decode v_pk_mul_lo_u16', + G.decode(vop3p(OP_MUL_LO_U16, 12, 256, 260, op_sel_hi=3))[0][3] == 'v_pk_mul_lo_u16 v12, v0, v4') + check('decode v_pk_mul_lo_u16 rejects reserved src2', + G.decode(vop3p(OP_MUL_LO_U16, 12, 256, 260, 1, op_sel_hi=3))[0][2] == 'v_pk_mul_lo_u16_unsupported') + for op, name in ((OP_MAD_U16, 'v_pk_mad_u16'), (OP_MAD_I16, 'v_pk_mad_i16')): + check('decode %s default' % name, + G.decode(vop3p(op, 12, 256, 260, 264))[0][3] == '%s v12, v0, v4, v8' % name) + check('decode %s clamp' % name, + G.decode(vop3p(op, 12, 256, 260, 264, clamp=1))[0][3] == '%s v12, v0, v4, v8 clamp' % name) + check('decode %s op_sel/op_sel_hi/clamp' % name, + G.decode(vop3p(op, 12, 256, 260, 264, op_sel=5, op_sel_hi=2, clamp=1))[0][3] + == '%s v12, v0, v4, v8 op_sel:[1,0,1] op_sel_hi:[0,1,0] clamp' % name) + + # 2. Exhaustive grid evaluated directly against emitted HLSL. + for op_sel, op_sel_hi, mod_str in ((0, 3, ''), (1, 2, ' op_sel:[1,0] op_sel_hi:[0,1]')): + p = Probe() + asm = 'v_pk_mul_lo_u16 v12, v0, v4%s' % mod_str + p.one('v_pk_mul_lo_u16', asm) + check('emitted %s' % asm, len(p.lines) == 1 and p.lines[0].startswith('v12 = ')) + rhs = p.lines[0][len('v12 = '):-1] + ok = all( + eval_hlsl_u32(rhs, {'v0': a, 'v4': b}) == ref_op(OP_MUL_LO_U16, a, b, 0, 0, op_sel, op_sel_hi) + for a in EDGE_A for b in EDGE_B + ) + check('v_pk_mul_lo_u16%s grid (%d cases)' % (mod_str, len(EDGE_A) * len(EDGE_B)), ok) + + for op, name in ((OP_MAD_U16, 'v_pk_mad_u16'), (OP_MAD_I16, 'v_pk_mad_i16')): + for clamp in (0, 1): + for op_sel, op_sel_hi, mod_str in ((0, 7, ''), (5, 2, ' op_sel:[1,0,1] op_sel_hi:[0,1,0]')): + p = Probe() + asm = '%s v12, v0, v4, v8%s%s' % (name, mod_str, ' clamp' if clamp else '') + p.one(name, asm) + check('emitted %s' % asm, len(p.lines) == 1 and p.lines[0].startswith('v12 = ')) + rhs = p.lines[0][len('v12 = '):-1] + ok = all( + eval_hlsl_u32(rhs, {'v0': a, 'v4': b, 'v8': c}) == ref_op(op, a, b, c, clamp, op_sel, op_sel_hi) + for a in EDGE_A for b in EDGE_B for c in EDGE_C + ) + check('%s%s%s grid (%d cases)' % ( + name, mod_str, ' clamp' if clamp else '', len(EDGE_A) * len(EDGE_B) * len(EDGE_C)), ok) + + # 3. EXEC masking & low16_only_v tracking. + p = Probe() + p.exec_known = False + p.one('v_pk_mul_lo_u16', 'v_pk_mul_lo_u16 v12, v0, v4') + check('exec-masked v_pk_mul_lo_u16 guards assignment', + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + p_lo = Probe() + p_lo.low16_only_v = {0, 4} + p_lo.one('v_pk_mul_lo_u16', 'v_pk_mul_lo_u16 v12, v0, v4 op_sel:[0,0] op_sel_hi:[0,0]') + check('v_pk_mul_lo_u16 accepts low16_only_v when only low halves are read', len(p_lo.lines) == 1) + + for name in ('v_pk_mad_u16', 'v_pk_mad_i16'): + for suffix in ('', ' clamp'): + pm = Probe() + pm.exec_known = False + pm.one(name, '%s v12, v0, v4, v8%s' % (name, suffix)) + check('exec-masked %s%s guards assignment' % (name, suffix), + len(pm.lines) == 1 and pm.lines[0].startswith('if (exec & 1) v12 = ')) + pl = Probe() + pl.low16_only_v = {0, 4, 8} + pl.one(name, '%s v12, v0, v4, v8 op_sel:[0,0,0] op_sel_hi:[0,0,0]' % name) + check('%s accepts low16_only_v when only low halves are read' % name, len(pl.lines) == 1) + ph = Probe() + ph.low16_only_v = {8} + check('%s refuses low16_only_v when high half is read' % name, + stage_refused(ph, name, '%s v12, v0, v4, v8' % name, 'whole-word read')) + + # 4. Stage refusals. + for asm in ( + 'v_pk_mul_lo_u16 v12, v0, v4 clamp', + 'v_pk_mul_lo_u16 v12, v0, v4 neg_lo:[1,0]', + 'v_pk_mul_lo_u16 v12, v0, v4 neg_hi:[0,1]', + 'v_pk_mul_lo_u16 v12, v0, v4 op_sel:[1,0,0]', + 'v_pk_mul_lo_u16 v12, v0, v4, v8', + 'v_pk_mul_lo_u16 v12, vcc_lo, v4', + 'v_pk_mul_lo_u16 s0, v0, v4', + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), 'v_pk_mul_lo_u16', asm)) + for name in ('v_pk_mad_u16', 'v_pk_mad_i16'): + for asm in ( + '%s v12, v0, v4, v8 clamp clamp' % name, + '%s v12, v0, v4, v8 neg_lo:[1,0,0]' % name, + '%s v12, v0, v4, v8 neg_hi:[0,1,0]' % name, + '%s v12, v0, v4, v8 op_sel:[1,0]' % name, + '%s v12, v0, v4' % name, + '%s v12, v0, v4, v8, v9' % name, + '%s v12, vcc_lo, v4, v8' % name, + '%s s0, v0, v4, v8' % name, + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), name, asm)) + + # 5. Unlowered controls. + for op, name, sample in ( + (OP_MUL_LO_U16, 'v_pk_mul_lo_u16', 'v_pk_mul_lo_u16 v12, v0, v4'), + (OP_MAD_U16, 'v_pk_mad_u16', 'v_pk_mad_u16 v12, v0, v4, v8'), + (OP_MAD_I16, 'v_pk_mad_i16', 'v_pk_mad_i16 v12, v0, v4, v8'), + ): + attr = 'op_' + name + saved = getattr(G.Stage, attr) + delattr(G.Stage, attr) + try: + check('unlowered %s refused' % name, stage_refused(Probe(), name, sample)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % name, True) + else: + check('unlowered %s pipeline refused' % name, False) + finally: + setattr(G.Stage, attr, saved) + + +DRAW_CASES = ( + (OP_MUL_LO_U16, 0, 0, 3, 'mul_lo_u16', [ + (0x00030005, 0x0007000b, 0), # hi: 21, lo: 55 + (0xffff8000, 0xffff0002, 0), # hi: (0xffff^2)&0xffff=1, lo: (0x8000*2)&0xffff=0 (no bleed!) + (0x12345678, 0x00010000, 0), # hi: 0x1234, lo: 0 + (0xabcd0100, 0x00040100, 0), # hi: (0xabcd*4)&0xffff=0xaf34, lo: (0x100*0x100)&0xffff=0 + ]), + (OP_MAD_U16, 1, 0, 7, 'mad_u16_clamp', [ + (0x01000003, 0x01000005, 0x00010007), # hi: 0x10001 -> 0xffff, lo: 3*5+7 = 22 + (0xffff8000, 0xffff0002, 0xffff0000), # hi: 0xffff, lo: 0xffff + (0x00ff0000, 0x0100ffff, 0x00ff0001), # hi: 255*256+255=0xffff (exact), lo: 1 + (0x00020004, 0x00030005, 0x00010002), # hi: 7, lo: 22 + ]), + (OP_MAD_I16, 0, 0, 7, 'mad_i16_wrap', [ + (0x7fffffff, 0x00020003, 0x00010005), # hi: (0x7fff*2+1)&0xffff=0xffff, lo: (-1*3+5)=2 + (0x80008000, 0x80000002, 0x00010001), # hi: 1, lo: 1 + (0x0003fffe, 0x0005fffd, 0x00010001), # hi: 16, lo: (-2)*(-3)+1 = 7 + (0x00000000, 0xffff7fff, 0xdeadbeef), # hi: 0xdead, lo: 0xbeef + ]), + (OP_MAD_I16, 1, 5, 2, 'mad_i16_clamp_swizzle', [ + # op_sel=[1,0,1] (a.hi * b.lo + c.hi), op_sel_hi=[0,1,0] (a.lo * b.hi + c.lo) + (0x80007fff, 0x00028000, 0x7fff0001), # lo: (-32768)*(-32768)+32767 -> 0x7fff; hi: (+32767)*2+1 -> 0x7fff + (0x80008000, 0x7fff7fff, 0x80008000), # lo: (-32768)*32767-32768 -> 0x8000; hi: (-32768)*32767-32768 -> 0x8000 + (0x0003fffd, 0x00050002, 0x0001fffe), # lo: 3*2+1=7; hi: (-3)*5+(-2)=-17 (0xffef) + (0xffff0001, 0x0001ffff, 0x00000000), # lo: (-1)*(-1)=1; hi: 1*1=1 + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_pk_mul_mad_16_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = first_ps = first_exp = None + for op, clamp, op_sel, op_sel_hi, label, triples in DRAW_CASES: + pipe = G.Pipeline(vs_words(triples), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi, clamp=clamp), + root_blob()) + vs_bin = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = tuple(ref_op(op, a, b, c, clamp, op_sel, op_sel_hi) ^ XOR_MASK for a, b, c in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_pk_mul_lo_u16 / v_pk_mad_16 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_pk_mul_lo_u16 / v_pk_mad_16 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_pk_mul_mad_16_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_pk_shift16_check.py b/tests/startup_gfx2hlsl_v_pk_shift16_check.py new file mode 100644 index 0000000000..ca964c1ce7 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_pk_shift16_check.py @@ -0,0 +1,306 @@ +"""Packed 16-bit integer shifts (v_pk_lshlrev_b16, v_pk_lshrrev_b16, v_pk_ashrrev_i16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP3P decode, value evaluation against emitted HLSL across op_sel/op_sel_hi, + EXEC masking, low16_only_v rules, refusals, unlowered controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +RDNA 2 ISA, VOP3P: + V_PK_LSHLREV_B16 (0x04): D_i = (S1_i << (S0_i & 15)) & 0xffff. + V_PK_LSHRREV_B16 (0x05): D_i = S1_i >> (S0_i & 15) (unsigned 16-bit). + V_PK_ASHRREV_I16 (0x06): D_i = (int16(S1_i) >> (S0_i & 15)) & 0xffff (signed 16-bit). +""" +import ast +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +OP_LSHL = 0x04 +OP_LSHR = 0x05 +OP_ASHR = 0x06 +ALL_OPS = ( + (OP_LSHL, 'v_pk_lshlrev_b16'), + (OP_LSHR, 'v_pk_lshrrev_b16'), + (OP_ASHR, 'v_pk_ashrrev_i16'), +) +XOR_MASK = 0x3f800000 + + +def vop3p(op, vdst, src0, src1, src2=0, *, op_sel=0, op_sel_hi=3, neg_lo=0, neg_hi=0, clamp=0, lit=None): + w0 = (0xcc000000 | ((op & 0x7f) << 16) | (clamp << 15) | ((op_sel & 7) << 11) + | ((neg_hi & 7) << 8) | (vdst & 0xff)) + w1 = (((neg_lo & 7) << 29) | ((op_sel_hi & 3) << 27) + | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff)) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def v_xor_lit(vdst, vsrc, lit): + w = (0x1d << 25) | ((vdst & 0xff) << 17) | ((vsrc & 0xff) << 9) | 255 + return struct.pack('<2I', w, lit & MASK) + + +def ps_words(op, op_sel=0, op_sel_hi=3): + # XOR with 0x3f800000 so all 16-bit packed outputs survive R32G32B32A32_FLOAT mrt0 export bit-for-bit. + body = b''.join( + vop3p(op, 12 + lane, 256 + lane, 256 + 4 + lane, op_sel=op_sel, op_sel_hi=op_sel_hi) + + v_xor_lit(12 + lane, 12 + lane, XOR_MASK) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(op, op_sel=0, op_sel_hi=3): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def ref_pk_shift(op, a, b, op_sel=0, op_sel_hi=3): + def pick(word, hi): + return ((word >> 16) if hi else word) & 0xffff + + def lane(sel_mask): + amt = pick(a, sel_mask & 1) & 15 + val = pick(b, (sel_mask >> 1) & 1) + if op == OP_LSHL: + return (val << amt) & 0xffff + if op == OP_LSHR: + return (val >> amt) & 0xffff + return (sext16(val) >> amt) & 0xffff + + return (lane(op_sel) | (lane(op_sel_hi) << 16)) & MASK + + +def eval_hlsl_u32(expr, env): + """Evaluate the emitted 32-bit HLSL expression directly in Python.""" + cleaned = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + + def to_i32(x): + x &= MASK + return x - 0x100000000 if x >= 0x80000000 else x + + def to_u32(x): + return x & MASK + + def ev(node): + if isinstance(node, ast.Expression): + return ev(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.Name): + return env[node.id] + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + arg = ev(node.args[0]) + if node.func.id == 'asint': + return to_i32(arg) + if node.func.id == 'asuint': + return to_u32(arg) + raise ValueError('unsupported call %s' % node.func.id) + if isinstance(node, ast.BinOp): + l, r = ev(node.left), ev(node.right) + if isinstance(node.op, ast.Add): + return to_u32(l + r) + if isinstance(node.op, ast.LShift): + return to_u32(l << (r & 31)) + if isinstance(node.op, ast.RShift): + is_signed = isinstance(node.left, ast.Call) and getattr(node.left.func, 'id', '') == 'asint' + return (to_i32(l) >> (r & 31)) if is_signed else (to_u32(l) >> (r & 31)) + if isinstance(node.op, ast.BitAnd): + return to_u32(l & r) + if isinstance(node.op, ast.BitOr): + return to_u32(l | r) + raise ValueError('unsupported binop %s' % node.op) + raise ValueError('unsupported node %s' % ast.dump(node)) + + return to_u32(ev(ast.parse(cleaned, mode='eval'))) + + +def stage_refused(stage, name, line, needle=''): + try: + stage.one(name, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +SHIFT_WORDS = ( + 0x00000000, 0x00010004, 0x000f0008, 0x0010001f, # includes >15 counts (must mask & 15) + 0x00070002, 0xfff0000f, 0x000c0001, 0xabcd0000, +) +VAL_WORDS = ( + 0x00000000, 0x0001ffff, 0x7fff8000, 0x80007fff, + 0xffff0001, 0x1234abcd, 0x80017ffe, 0xdeadbeef, +) + + +def run_controls(): + # 1. Decode verification via G.decode(). + for op, name in ALL_OPS: + check('decode %s default' % name, + G.decode(vop3p(op, 12, 256, 260))[0][3] == '%s v12, v0, v4' % name) + check('decode %s op_sel/op_sel_hi' % name, + G.decode(vop3p(op, 12, 256, 260, op_sel=1, op_sel_hi=2))[0][3] + == '%s v12, v0, v4 op_sel:[1,0] op_sel_hi:[0,1]' % name) + check('decode %s rejects reserved src2' % name, + G.decode(vop3p(op, 12, 256, 260, src2=1))[0][2] == '%s_unsupported' % name) + + # 2. Exhaustive grid evaluated directly against emitted HLSL across 3 op_sel configs (576 cases total). + for op, name in ALL_OPS: + for op_sel, op_sel_hi, mod_str in ( + (0, 3, ''), + (1, 2, ' op_sel:[1,0] op_sel_hi:[0,1]'), + (0, 0, ' op_sel:[0,0] op_sel_hi:[0,0]'), + ): + p = Probe() + asm = '%s v12, v0, v4%s' % (name, mod_str) + p.one(name, asm) + check('emitted %s' % asm, + len(p.lines) == 1 and p.lines[0].startswith('v12 = ') and p.lines[0].endswith(';')) + rhs = p.lines[0][len('v12 = '):-1] + ok = True + for a in SHIFT_WORDS: + for b in VAL_WORDS: + if eval_hlsl_u32(rhs, {'v0': a, 'v4': b}) != ref_pk_shift(op, a, b, op_sel, op_sel_hi): + ok = False + check('%s%s grid (%d cases)' % (name, mod_str, len(SHIFT_WORDS) * len(VAL_WORDS)), ok) + + # 3. EXEC masking and low16_only_v tracking. + for _, name in ALL_OPS: + p = Probe() + p.exec_known = False + p.one(name, '%s v12, v0, v4' % name) + check('exec-masked %s guards assignment' % name, + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + p_lo = Probe() + p_lo.low16_only_v = {0, 4} + p_lo.one(name, '%s v12, v0, v4 op_sel:[0,0] op_sel_hi:[0,0]' % name) + check('%s accepts low16_only_v when only low halves are read' % name, len(p_lo.lines) == 1) + + p_hi = Probe() + p_hi.low16_only_v = {4} + check('%s refuses low16_only_v when high half is read' % name, + stage_refused(p_hi, name, '%s v12, v0, v4' % name, 'whole-word read')) + + # 4. Stage refusals: clamp, neg_lo, neg_hi, bad op_sel, wrong arity, lane mask, bad dst. + for _, name in ALL_OPS: + for asm in ( + '%s v12, v0, v4 clamp' % name, + '%s v12, v0, v4 neg_lo:[1,0]' % name, + '%s v12, v0, v4 neg_hi:[0,1]' % name, + '%s v12, v0, v4 op_sel:[1,0,0]' % name, + '%s v12, v0, v4 op_sel:[2,0]' % name, + '%s v12, v0' % name, + '%s v12, v0, v4, v8' % name, + '%s v12, vcc_lo, v4' % name, + '%s s0, v0, v4' % name, + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), name, asm)) + + # 5. Unlowered control: removing handlers from Stage restores refusals. + for op, name in ALL_OPS: + attr = 'op_' + name + saved = getattr(G.Stage, attr) + delattr(G.Stage, attr) + try: + check('unlowered %s refused' % name, stage_refused(Probe(), name, '%s v12, v0, v4' % name)) + try: + translate(op) + except G.Unsupported: + check('unlowered %s pipeline refused' % name, True) + else: + check('unlowered %s pipeline refused' % name, False) + finally: + setattr(G.Stage, attr, saved) + + +DRAW_CASES = ( + (OP_LSHL, 0, 3, 'lshlrev_b16', [ + (0x00040001, 0x00018001, 0), # hi: 0x0001<<4=0x0010, lo: (0x8001<<1)&0xffff=0x0002 (no bleed!) + (0x000f0010, 0x0001abcd, 0), # hi: 0x0001<<15=0x8000, lo: 0xabcd<<(16&15=0)=0xabcd + (0x001f0008, 0xffff1234, 0), # hi: 0xffff<<15=0x8000, lo: 0x1234<<8=0x3400 + (0x00000000, 0x7fff8000, 0), # identity + ]), + (OP_LSHR, 1, 2, 'lshrrev_b16_swizzle', [ + # op_sel=[1,0] (a.hi, b.lo), op_sel_hi=[0,1] (a.lo, b.hi) + (0x00040001, 0x8000ffff, 0), # lo: 0xffff>>4=0x0fff; hi: 0x8000>>1=0x4000 + (0x000f0010, 0xdeadbeef, 0), # lo: 0xbeef>>15=0x0001; hi: 0xdead>>0=0xdead + (0x0008000c, 0xfedc1234, 0), # lo: 0x1234>>8=0x0012; hi: 0xfedc>>12=0x000f + (0x0000000f, 0x80007fff, 0), # lo: 0x7fff>>0=0x7fff; hi: 0x8000>>15=0x0001 + ]), + (OP_ASHR, 0, 3, 'ashrrev_i16', [ + (0x00010001, 0x80007fff, 0), # hi: -32768>>1=0xc000, lo: +32767>>1=0x3fff + (0x000f000f, 0x80007fff, 0), # hi: -32768>>15=0xffff, lo: +32767>>15=0x0000 + (0x00140004, 0xff0000f0, 0), # hi: (-256)>>4=0xfff0, lo: 0x00f0>>4=0x000f + (0x00000008, 0xffff8000, 0), # hi: -1>>0=0xffff, lo: -32768>>8=0xff80 + ]), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_pk_shift16_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = first_ps = first_exp = None + for op, op_sel, op_sel_hi, label, triples in DRAW_CASES: + pipe = G.Pipeline(vs_words(triples), ps_words(op, op_sel=op_sel, op_sel_hi=op_sel_hi), root_blob()) + vs_bin = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs_%s_%s' % (label, kind), vs_profile, td) + ps_bin = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps_%s_%s' % (label, kind), ps_profile, td) + raw_exp = tuple(ref_pk_shift(op, a, b, op_sel, op_sel_hi) ^ XOR_MASK for a, b, _ in triples) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s %s expected=%s\n%s\n%s' % ( + kind, adapter, label, expected, res.stdout, res.stderr)) + print('%s %s %s: %s' % (kind, adapter, label, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_pk_shift16 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_pk_shift16 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_pk_shift16_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_v_sat_pk_u8_i16_check.py b/tests/startup_gfx2hlsl_v_sat_pk_u8_i16_check.py new file mode 100644 index 0000000000..5958002fc6 --- /dev/null +++ b/tests/startup_gfx2hlsl_v_sat_pk_u8_i16_check.py @@ -0,0 +1,242 @@ +"""Saturating int16x2-to-uint8x2 pack (v_sat_pk_u8_i16) in tools/startup/gfx2hlsl.py. + + (no arguments) VOP1/VOP3A decode, value evaluation, EXEC masking, encoding & Stage + refusals, unlowered and mutation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input words and compare the four result words + +RDNA 2 ISA, VOP1 (0x62) / VOP3A (0x1e2): + V_SAT_PK_U8_I16 vD, S0: + D[7:0] = clamp(int16(S0[15:0]), 0, 255) + D[15:8] = clamp(int16(S0[31:16]), 0, 255) + D[31:16] = 0 + +The pixel fixture decodes synthetic gfx1013 VOP1/VOP3A bytes via G.decode() ONLY (no game data). It reads +flat parameter v0..v3, applies v_sat_pk_u8_i16 (both e32 and e64), XORs with 0x3f800000 via v_xor_b32 so the +packed uint16 output never lands in float32 subnormal range on float render targets, and exports mrt0. +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + vs_words, + words_text, +) + +# XOR with 0x3f800000 so 0x0000..0xffff outputs transport as normal IEEE-754 floats on R32G32B32A32_FLOAT. +DRAW_TRANSPORT_XOR = 0x3f800000 + + +def vop1(op, vdst, src0, lit=None): + w0 = 0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff) + out = struct.pack('<I', w0) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def vop3a_1src(op, vdst, src0, *, abs_bits=0, neg=0, clamp=0, omod=0, op_sel=0, src1=0, src2=0, lit=None): + w0 = 0xd4000000 | ((op & 0x3ff) << 16) | (clamp << 15) | (op_sel << 11) | (abs_bits << 8) | (vdst & 0xff) + w1 = (neg << 29) | (omod << 27) | ((src2 & 0x1ff) << 18) | ((src1 & 0x1ff) << 9) | (src0 & 0x1ff) + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +def v_xor_lit(vdst, vsrc, lit): + # VOP2 v_xor_b32_e32 v<vdst>, <literal>, v<vsrc> (op 0x1d, src0=255) + w0 = (0x1d << 25) | ((vdst & 0xff) << 17) | ((vsrc & 0xff) << 9) | 255 + return struct.pack('<2I', w0, lit & MASK) + + +def ps_words(e64=False): + body = b''.join( + (vop3a_1src(0x1e2, 12 + lane, 256 + lane) if e64 else vop1(0x62, 12 + lane, 256 + lane)) + + v_xor_lit(12 + lane, 12 + lane, DRAW_TRANSPORT_XOR) + for lane in range(4) + ) + return PRE_WORDS + body + POST_WORDS + + +def translate(e64=False): + zero = [(0, 0, 0)] * 4 + pipe = G.Pipeline(vs_words(zero), ps_words(e64), root_blob()) + return pipe.hlsl_vs(), pipe.hlsl_ps() + + +def sext16(v): + v &= 0xffff + return v - 0x10000 if v >= 0x8000 else v + + +def ref_sat_pk_u8_i16(x): + lo = max(0, min(255, sext16(x & 0xffff))) + hi = max(0, min(255, sext16((x >> 16) & 0xffff))) + return lo | (hi << 8) + + +def eval_hlsl(x): + x &= MASK + # Mirrors VEC_U['v_sat_pk_u8_i16']: + lo_s = sext16(x & 0xffff) + hi_s = sext16((x >> 16) & 0xffff) + lo = max(0, min(255, lo_s)) & 0xff + hi = max(0, min(255, hi_s)) & 0xff + return lo | (hi << 8) + + +def stage_refused(stage, op, line, needle=''): + try: + stage.one(op, line) + except G.Unsupported as exc: + return (not needle or needle in str(exc)) and not stage.lines + return False + + +HALVES = (-32768, -32767, -256, -1, 0, 1, 127, 128, 254, 255, 256, 1000, 32767) + + +def run_controls(): + # 1. Decode verification for both VOP1 (e32) and VOP3A (e64) via G.decode(). + check('decode v_sat_pk_u8_i16_e32', + G.decode(vop1(0x62, 12, 256))[0][3] == 'v_sat_pk_u8_i16_e32 v12, v0') + check('decode v_sat_pk_u8_i16_e64', + G.decode(vop3a_1src(0x1e2, 12, 256))[0][3] == 'v_sat_pk_u8_i16_e64 v12, v0') + + # 2. Exhaustive 16-bit half-word pair grid (169 combinations). + grid_ok = True + for lo_s in HALVES: + for hi_s in HALVES: + word = (lo_s & 0xffff) | ((hi_s & 0xffff) << 16) + if eval_hlsl(word) != ref_sat_pk_u8_i16(word): + grid_ok = False + check('v_sat_pk_u8_i16 grid (%d cases)' % (len(HALVES) * len(HALVES)), grid_ok) + + # 3. Both e32 and e64 pipelines translate cleanly; EXEC masking works. + for e64 in (False, True): + _, ps_hlsl = translate(e64) + check('pipeline e64=%s translates' % e64, 'clamp(' in ps_hlsl and '<< 8u' in ps_hlsl) + p = Probe() + p.exec_known = False + p.one('v_sat_pk_u8_i16_e32', 'v_sat_pk_u8_i16_e32 v12, v0') + check('exec-masked v_sat_pk_u8_i16 guards assignment', + len(p.lines) == 1 and p.lines[0].startswith('if (exec & 1) v12 = ')) + + # 4. VOP3A encoding guard refuses neg/abs and unused src1/src2 fields. + for label, bad_word, needle in ( + ('abs0', vop3a_1src(0x1e2, 12, 256, abs_bits=1), 'with neg/abs'), + ('neg0', vop3a_1src(0x1e2, 12, 256, neg=1), 'with neg/abs'), + ('neg_inline0', vop3a_1src(0x1e2, 12, 129, neg=1), 'with neg/abs'), + ('unused_src1', vop3a_1src(0x1e2, 12, 256, src1=1), 'unused src1/src2'), + ('unused_src2', vop3a_1src(0x1e2, 12, 256, src2=1), 'unused src1/src2'), + ): + reasons = [] + G.decode(bad_word, reasons) + check('encoding guard refuses %s' % label, + len(reasons) == 1 and needle in reasons[0][0]) + + # 5. Stage refusals: modifiers, abs/neg, wrong arity. + for asm in ( + 'v_sat_pk_u8_i16_e64 v12, v0 clamp', + 'v_sat_pk_u8_i16_e64 v12, v0 mul:2', + 'v_sat_pk_u8_i16_e64 v12, v0 op_sel:[1,0]', + 'v_sat_pk_u8_i16_e64 v12, |v0|', + 'v_sat_pk_u8_i16_e64 v12, -v0', + 'v_sat_pk_u8_i16_e32 v12', + 'v_sat_pk_u8_i16_e32 v12, v0, v1', + ): + check('Stage refuses %s' % asm, stage_refused(Probe(), asm.split()[0], asm)) + + # 6. Unlowered control: removing v_sat_pk_u8_i16 from VEC_U restores refusals. + saved = G.VEC_U.pop('v_sat_pk_u8_i16') + try: + check('unlowered v_sat_pk_u8_i16 refused', + stage_refused(Probe(), 'v_sat_pk_u8_i16_e32', 'v_sat_pk_u8_i16_e32 v12, v0')) + try: + translate(False) + except G.Unsupported: + check('unlowered pipeline refused', True) + else: + check('unlowered pipeline refused', False) + finally: + G.VEC_U['v_sat_pk_u8_i16'] = saved + + +DRAW_BATCHES = ( + # Each tuple is 4 input words (packed as (lo_i16, hi_i16) per lane). + ( + (0x0000 | (0x00ff << 16)), # (0, 255) -> 0xff00 + (0xffff | (0x8000 << 16)), # (-1, -32768) -> 0x0000 + (0x0100 | (0x7fff << 16)), # (256, 32767) -> 0xffff + (0x0042 | (0x00ab << 16)), # (0x42, 0xab) -> 0xab42 + ), + ( + (0x00fe | (0xfffe << 16)), # (254, -2) -> 0x00fe + (0x8001 | (0x007f << 16)), # (-32767, 127) -> 0x7f00 + (0x0001 | (0x0101 << 16)), # (1, 257) -> 0xff01 + (0x0080 | (0x0080 << 16)), # (128, 128) -> 0x8080 + ), +) + + +def run_draw(dxc, renderer, adapter, fxc=None): + run_controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory(prefix='x2w_v_sat_pk_u8_i16_') as tmp: + td = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + first_vs = None + first_ps = None + first_exp = None + for e64 in (False, True): + _, ps_hlsl = translate(e64) + ps_bin = compile_hlsl(compiler, kind, ps_hlsl, 'ps_e%d_%s' % (64 if e64 else 32, kind), ps_profile, td) + for b_idx, batch in enumerate(DRAW_BATCHES): + triples = [(w, 0, 0) for w in batch] + vs_hlsl = G.Pipeline(vs_words(triples), ps_words(e64), root_blob()).hlsl_vs() + vs_bin = compile_hlsl(compiler, kind, vs_hlsl, + 'vs_e%d_%d_%s' % (64 if e64 else 32, b_idx, kind), vs_profile, td) + raw_exp = tuple(ref_sat_pk_u8_i16(w) ^ DRAW_TRANSPORT_XOR for w in batch) + expected = words_text(raw_exp) + res = draw(renderer, adapter, vs_bin, ps_bin, expected) + if res.returncode == 77: + print('SKIP (%s): %s' % (adapter, res.stdout.strip() or res.stderr.strip())) + sys.exit(77) + if res.returncode != 0: + raise AssertionError('%s %s e%d batch=%d expected=%s\n%s\n%s' % ( + kind, adapter, 64 if e64 else 32, b_idx, expected, res.stdout, res.stderr)) + print('%s %s e%d batch=%d: %s' % (kind, adapter, 64 if e64 else 32, b_idx, expected), flush=True) + if first_vs is None: + first_vs, first_ps, first_exp = vs_bin, ps_bin, raw_exp + + bad = words_text((first_exp[0] ^ 1, first_exp[1], first_exp[2], first_exp[3])) + neg = draw(renderer, adapter, first_vs, first_ps, bad) + check('draw %s %s negative control rejects wrong expectation' % (kind, adapter), + neg.returncode != 0) + + +if __name__ == '__main__': + if len(sys.argv) == 1: + run_controls() + print('v_sat_pk_u8_i16 controls: ok') + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + run_draw(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) + print('v_sat_pk_u8_i16 draw (%s): ok' % sys.argv[4]) + else: + print('usage: startup_gfx2hlsl_v_sat_pk_u8_i16_check.py [draw <dxc> <offscreen_check> <warp|hardware> [fxc]]', + file=sys.stderr) + sys.exit(2) diff --git a/tests/startup_gfx2hlsl_vcc_hi_check.py b/tests/startup_gfx2hlsl_vcc_hi_check.py new file mode 100644 index 0000000000..51de51d2a8 --- /dev/null +++ b/tests/startup_gfx2hlsl_vcc_hi_check.py @@ -0,0 +1,290 @@ +"""wave32 vcc_hi as an ordinary scalar register in tools/startup/gfx2hlsl.py, read back from a real D3D12 draw. + + (no arguments) translation controls and refusals, pure Python + binary <llvm-mc> assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pixel stage (DXC, and FXC when given), draw 16 x 16 + pixels and compare every word with the CPU reference below + +In wave32 VCC is vcc_lo alone, and compilers allocate vcc_hi (SGPR 107) like any other scalar register: a compare or +carry-out destination, a v_cndmask mask, a scalar operand. The decoder prints wave32 syntax, so the text does not +give the wave size; the translator renames vcc_hi to an SGPR the program never names only when that is exact in both +wave sizes: no instruction names the 64-bit pair `vcc`, and either a VALU compare/carry writes vcc_hi (or an odd +SGPR) or a VOP3 mask source reads one (a misaligned pair in wave64, so the program is wave32), or no VALU instruction +and no vcc branch uses vcc_lo as a lane mask (in wave64 those also write or read vcc_hi for lanes 32..63). Otherwise vcc_hi is refused by name, as before, and a +scalar write into vcc_hi or exec_hi is now a refusal instead of a TypeError. + +The draw fixture PS (packed screen position v0 = x | y << 16): + v_cmp_gt_u32_e64 vcc_hi, v0, 0x50005 ; v_cndmask_b32_e64 v2, 1.0, 2.0, vcc_hi -> 2.0 where v0 > 0x50005 + v_add_co_u32 v3, vcc_hi, v0, 0xfff7fff8 ; v_add_co_ci_u32_e64 v4, s3, v0, 2.0, vcc_hi -> + the carry + s_mov_b32 vcc_hi, 0x1234 ; s_add_u32 s0, vcc_hi, 16 ; v5 = s0 + v0 +The reference below computes the same words with Python integers. The selected words are 1.0 and 2.0, not the +integers 1 and 2, and the carry rides on v0 + 0x40000000: with FXC a word that can only be 0 or 1 came back as +0 on WARP where it was 1 (DXC kept it), a denormal export artifact, not a translation error. Mutations (the compare bit not read, the carry +lost, vcc_hi read as zero) must fail the draw. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +WIDTH = HEIGHT = 16 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +# name -> (source, words assembled by llvm-mc 19 for gfx1013, expected refusal or None) +FIXTURES = { + 'PS': ('''v_cmp_gt_u32_e64 vcc_hi, v0, 0x50005 +v_cndmask_b32_e64 v2, 1.0, 2.0, vcc_hi +v_add_co_u32 v3, vcc_hi, v0, 0xfff7fff8 +v_add_co_ci_u32_e64 v4, s3, v0, 0x40000000, vcc_hi +s_mov_b32 vcc_hi, 0x1234 +s_add_u32 s0, vcc_hi, 16 +v_add_nc_u32_e32 v5, s0, v0 +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm +''', '6b00c4d400ff010005000500020001d5f2e8ad01036b0fd700ff0100f8fff7ff040328d500e9ad01ff03ebbe341200006b900080' + '00000a4a0f1800f802030405000081bf', None), + # Only scalar writes of vcc_hi and no VALU VCC write: exact in either wave size. + 'SCALAR_ONLY': ('''s_mov_b32 vcc_hi, 0x1234 +s_lshl_b32 vcc_hi, vcc_hi, 4 +s_add_u32 s0, vcc_hi, 16 +v_add_nc_u32_e32 v5, s0, v0 +exp mrt0 v5, v0, v0, v0 done vm +s_endpgm +''', 'ff03ebbe341200006b846b8f6b90008000000a4a0f1800f805000000000081bf', None), + # A VOPC writes vcc_lo and nothing proves wave32: in wave64 the compare would also write vcc_hi. + 'SCALAR_AND_VOPC': ('''s_mov_b32 vcc_hi, 0x1234 +s_lshl_b32 vcc_hi, vcc_hi, 4 +s_add_u32 s0, vcc_hi, 16 +v_cmp_gt_u32_e32 vcc_lo, 0x50005, v0 +v_cndmask_b32_e64 v2, 1, 2, vcc_lo +v_add_nc_u32_e32 v5, s0, v0 +exp mrt0 v2, v5, v0, v0 done vm +s_endpgm +''', 'ff03ebbe341200006b846b8f6b900080ff00887d05000500020001d58104a90100000a4a0f1800f802050000000081bf', + 's_mov_b32 destination vcc_hi'), + # A VALU mask read of vcc_lo and nothing proves wave32: in wave64 lanes 32..63 would read vcc_hi as their mask + # bit, which the renamed scalar register does not model (found by an independent review). + 'MASK_READ': ('''s_mov_b32 vcc_lo, 0 +s_mov_b32 vcc_hi, -1 +v_mov_b32_e32 v2, 2.0 +v_cndmask_b32_e32 v1, 1.0, v2, vcc_lo +exp mrt0 v1, v1, v1, v1 done vm +s_endpgm +''', '8003eabec103ebbef402047ef20402020f1800f801010101000081bf', 's_mov_b32 destination vcc_hi'), + # A whole scalar word is not a lane mask: the lowering would test bit 0 of 0x55555555 for every lane. + 'SCALAR_MASK': ('''s_mov_b32 vcc_hi, 0x55555555 +v_cndmask_b32_e64 v2, 1.0, 2.0, vcc_hi +exp mrt0 v2, v2, v2, v2 done vm +s_endpgm +''', 'ff03ebbe55555555020001d5f2e8ad010f1800f802020202000081bf', 's_mov_b32 destination vcc_hi'), + # The 64-bit pair `vcc` names vcc_hi as its high word. + 'PAIR': ('''v_cmp_gt_u32_e64 vcc_hi, v0, 0x50005 +s_and_b64 s[2:3], vcc, exec +v_cndmask_b32_e64 v2, 1, 2, vcc_hi +exp mrt0 v2, v2, v2, v2 done vm +s_endpgm +''', '6b00c4d400ff0100050005006a7e8287020001d58104ad010f1800f802020202000081bf', 'v_cmp_gt_u32 into vcc_hi'), + # exec_hi is a mask half in every wave size: a scalar write is refused, not a crash. + 'EXEC_HI': ('''s_mov_b32 exec_hi, 0 +v_mov_b32_e32 v2, 1 +exp mrt0 v2, v2, v2, v2 done vm +s_endpgm +''', '8003ffbe8102047e0f1800f802020202000081bf', 's_mov_b32 destination exec_hi'), + # A v_readfirstlane_b32 into vcc_hi writes a whole word too: a straight-line VOP3 mask source read of it would + # test bit 0 of that word for every lane, so the rename is refused (the old rule caught only s_ and v_readlane). + 'READFIRSTLANE_MASK': ('''v_mov_b32_e32 v2, s0 +v_readfirstlane_b32 vcc_hi, v2 +v_cndmask_b32_e64 v1, 1.0, 2.0, vcc_hi +exp mrt0 v1, v1, v1, v1 done vm +s_endpgm +''', '0002047e0205d67e010001d5f2e8ad010f1800f801010101000081bf', 'v_readfirstlane_b32 requires a proven uniform source'), + # The same writer with the mask read across a branch boundary: the order is unknown, so it is refused as well. + 'READFIRSTLANE_BRANCH': ('''v_mov_b32_e32 v2, s0 +v_readfirstlane_b32 vcc_hi, v2 +s_cbranch_execz skip +v_cndmask_b32_e64 v1, 1.0, 2.0, vcc_hi +exp mrt0 v1, v1, v1, v1 done vm +s_endpgm +skip: +s_endpgm +''', '0002047e0205d67e0a0a88bf010001d5f2e8ad010f1800f801010101000081bf000081bf', + 'v_readfirstlane_b32 requires a proven uniform source'), + # Branch-only: the VOP3 mask read comes before the whole-word writer in source order and a back edge reaches it, + # so no sequential read_after applies: only the branchy writer check refuses. The old rule (s_ and v_readlane + # writers only) renamed this one, so the old branchy check never saw a lane-read writer. + 'READFIRSTLANE_BACK_EDGE': ('''loop: +v_cndmask_b32_e64 v1, 1.0, 2.0, vcc_hi +v_add_nc_u32_e32 v3, v1, v0 +exp mrt0 v3, v0, v0, v0 done vm +v_mov_b32_e32 v2, s0 +v_readfirstlane_b32 vcc_hi, v2 +s_branch loop +''', '010001d5f2e8ad010101064a0f1800f8030000000002047e0205d67e0a0a82bf', + 'operand \'vcc_hi\''), + # The same shape with a v_readlane_b32 writer: refused by the pre-existing branchy writer check. + 'READLANE_BACK_EDGE': ('''loop: +v_cndmask_b32_e64 v1, 1.0, 2.0, vcc_hi +v_add_nc_u32_e32 v3, v1, v0 +exp mrt0 v3, v0, v0, v0 done vm +v_readlane_b32 vcc_hi, v2, s0 +s_branch loop +''', '010001d5f2e8ad010101064a0f1800f8030000006b0060d7020100000a0a82bf', + 'operand \'vcc_hi\''), + # The same lane-read writer with only scalar reads of vcc_hi: exact in either wave size, so it translates. + 'READFIRSTLANE_SCALAR': ('''v_mov_b32_e32 v2, s0 +v_readfirstlane_b32 vcc_hi, v2 +s_add_u32 s1, vcc_hi, 16 +v_add_nc_u32_e32 v5, s1, v0 +exp mrt0 v5, v0, v0, v0 done vm +s_endpgm +''', '0002047e0205d67e6b90018001000a4a0f1800f805000000000081bf', None), +} + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + str(detail)[:1500])) + if not ok: + failures.append(label) + + +def translate(name): + try: + return G.Pipeline(VS_WORDS, bytes.fromhex(FIXTURES[name][1]), root_blob(), ps_hw_inputs=PACKED).hlsl_ps(), None + except G.Unsupported as reason: + return None, str(reason) + + +def image(): + out = [] + for y in range(HEIGHT): + for x in range(WIDTH): + v0 = x | y << 16 + total = v0 + 0xfff7fff8 + out += [0x40000000 if v0 > 0x50005 else 0x3f800000, total & MASK, (v0 + 0x40000000 + (total >> 32)) & MASK, + (0x1244 + v0) & MASK] + return out + + +def sub(text, pattern, replacement): + mutated, count = re.subn(pattern, replacement, text) + assert count == 1, pattern + return mutated + + +# The renamed register is whichever SGPR the program never names; the patterns accept any number. +MUTATIONS = { + 'the compare bit is not read': (r'v2 = \(s(\d+) & 1\)', 'v2 = (0u & 1)'), + 'the carry-out is lost': (r'a = a \+ \(s(\d+) & 1u\);', 'a = a;'), + 'vcc_hi reads as zero': (r's0 = 0x00001234u \+', 's0 = 0x00000000u +'), +} + + +def controls(): + for name, (_source, _words, refusal) in FIXTURES.items(): + try: + text, reason = translate(name) + except Exception as error: # noqa: BLE001 - a crash is the failure this guards + check('%s translates or refuses without a crash' % name, False, '%s: %s' % (type(error).__name__, error)) + continue + if refusal is None: + check('%s translates' % name, text is not None and 'vcc_hi' not in text, str(reason)) + else: + check('%s refused: %s' % (name, refusal), text is None and reason == refusal, str(reason)) + # A wide operand covering SGPR 107 (s_load_dwordx4 s[104:107]) writes vcc_hi: no free alias exists, so it stays refused. + wide = [(0, 0, 's_mov_b32', 's_mov_b32 vcc_hi, 0x1234'), + (4, 1, 's_load_dwordx4', 's_load_dwordx4 s[104:107], s[0:1], 0x0'), + (12, 2, 'v_mov_b32_e32', 'v_mov_b32_e32 v2, vcc_hi')] + check('a load into s[104:107] keeps vcc_hi refused', G.wave32_vcc_hi(wide) is wide) + # Negative control for the whole-word writer rule: the readfirstlane mask-read fixtures must be stopped by + # wave32_vcc_hi itself. The old rule (only s_ and v_readlane writers) renamed them, so this check fails there. + for name in ('READFIRSTLANE_MASK', 'READFIRSTLANE_BRANCH', 'READFIRSTLANE_BACK_EDGE'): + ins = G.decode(G.strip_header(bytes.fromhex(FIXTURES[name][1]))) + check('%s is refused before the vcc_hi rename' % name, G.wave32_vcc_hi(ins) is ins) + text, _ = translate('PS') + if text is not None: + check('PS keeps the compare and carry in the renamed register', + re.search(r's(\d+) = \(\(v0 > 0x00050005u\) \? 1u : 0u\);', text) is not None, text) + for label, (pattern, replacement) in MUTATIONS.items(): + check('PS mutation "%s" changes the text' % label, sub(text, pattern, replacement) != text) + reference = image() + check('reference covers both compare outcomes and both carries', + {reference[i] for i in range(0, len(reference), 4)} == {0x3f800000, 0x40000000} + and {(reference[i] - 0x40000000 - (i // 4) % WIDTH - ((i // 4 // WIDTH) << 16)) & MASK + for i in range(2, len(reference), 4)} == {0, 1}) + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + text, reason = translate('PS') + if text is None: + check('PS translates for the draw', False, reason) + return + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + reference = directory / 'reference.bin' + reference.write_bytes(struct.pack('<%dI' % (WIDTH * HEIGHT * 4), *image())) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_' + kind, vs_profile, directory) + ps = compile_hlsl(compiler, kind, text, 'ps_' + kind, ps_profile, directory) + run = draw(renderer, adapter, vs, ps, reference) + check('%s %s PS: all %d pixels match the reference' % (adapter, kind, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for n, (label, (pattern, replacement)) in enumerate(MUTATIONS.items()): + bad = compile_hlsl(compiler, kind, sub(text, pattern, replacement), 'bad_%s_%d' % (kind, n), ps_profile, + directory) + run = draw(renderer, adapter, vs, bad, reference) + check('%s %s PS mutation "%s" fails' % (adapter, kind, label), + run.returncode != 0 and 'pixel mismatch' in run.stderr, run.stdout + run.stderr) + + +def check_binary(llvm_mc): + for name, (source, words, _refusal) in FIXTURES.items(): + check('llvm-mc assembles the %s fixture to the same words' % name, + assemble(llvm_mc, source) == bytes.fromhex(words)) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index 99e552a102..548df23a86 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -3,13 +3,15 @@ A request is consumed only once its ready marker (.a or .rtv) exists and it is not finished: a published .txt with both .cso files (or a .txt under X2W_FXC='') is done; a .txt without bytecode is resumed. After the watcher's first pass, a request whose .fail is newer than its marker is not -retried; the first pass and the one-shot --pending scan retry it. The --watch process must retry an -earlier failure once, translate a new request while it runs and not rewrite a failure on later -passes. A --pending scan with four parallel workers must print the same results and write the same -failures as one worker, an unexpected translator error must become <key>.fail, a broken process -pool must end one watcher pass and not the watcher, and an invalid X2W_TRANSLATE_JOBS must fall -back to the processor count. +retried; the first pass and the one-shot --pending scan retry it unless --skip-failed (-s) or +X2W_SKIP_FAILED=1 is set. The --watch process must retry an earlier failure once, translate a new +request while it runs and not rewrite a failure on later passes. An in-memory completed cache skips +published requests whose stage metadata has not changed without re-reading container bytecode on disk. A --pending scan with four +parallel workers must print the same results and write the same failures as one worker, an +unexpected translator error must become <key>.fail, a broken process pool must end one watcher pass +and not the watcher, and an invalid X2W_TRANSLATE_JOBS falls back to the processor count. """ +from contextlib import suppress import json import os import re @@ -77,6 +79,135 @@ def local(text): # the temporary directory differs between runs; keep the file touch(d / ('%016x.txt' % 9)) expect('watch pass', scan(d, True), [1, 5, 6, 9]) expect('one-shot pass', scan(d, False), [1, 4, 5, 6, 9]) + completed = {} + expect('pass with completed dict', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('published key cached in completed', 2 in completed, True) + expect('rescan with completed matches', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + + # Cache invalidation P1: req_<key>.psin rewritten newer than published manifest drops key 2 from completed and rechecks + touch(d / ('req_%016x.psin' % 2), b'new description', mtime=now + 5) + expect('cache invalidation on rewritten description', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated from completed', 2 in completed, False) + (d / ('req_%016x.psin' % 2)).unlink() + expect('cache re-populates completed', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + + # Cache invalidation P2: manifest withdrawn (deleted) drops key 2 from completed and rechecks + (d / ('%016x.txt' % 2)).unlink() + expect('cache invalidation on withdrawn manifest', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated on withdrawn manifest', 2 in completed, False) + touch(d / ('%016x.txt' % 2)) + expect('cache re-populates after manifest restored', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + + # Cache invalidation P3: bytecode lost (deleted stage file) drops key 2 from completed and rechecks + (d / ('%016x.vs.cso' % 2)).unlink() + expect('cache invalidation on lost bytecode stage', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated on lost stage', 2 in completed, False) + touch(d / ('%016x.vs.cso' % 2), b'DXBC') + expect('cache re-populates after bytecode restored', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + + # Cache invalidation P4: bytecode truncated to zero size drops key 2 from completed and rechecks + touch(d / ('%016x.vs.cso' % 2), b'') + expect('cache invalidation on zero-byte bytecode stage', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 2, 4, 5, 6, 9]) + expect('key 2 invalidated on zero-byte stage', 2 in completed, False) + touch(d / ('%016x.vs.cso' % 2), b'DXBC') + expect('cache re-populates after zero-byte restored', gfx2hlsl.pending_keys(str(d), False, completed=completed), [1, 4, 5, 6, 9]) + expect('key 2 re-cached', 2 in completed, True) + +with tempfile.TemporaryDirectory() as tmp: + d_cli = Path(tmp) + now = time.time() + for ext in ('.b', '.root'): + touch(d_cli / ('req_%016x%s' % (4, ext))) + touch(d_cli / ('req_%016x.a' % 4), mtime=now - 10) + touch(d_cli / ('%016x.fail' % 4), b'prior refusal\n', mtime=now - 5) + # Default one-shot --pending retries key 4 (failure is present but retried) + out_default = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '--jobs=1'], + capture_output=True, text=True, timeout=30) + expect('default --pending retries failure', ('%016x:' % 4) in out_default.stdout, True) + # With --skip-failed, key 4 is skipped and no translation is performed + out_skip = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '--skip-failed', '-j', '1'], + capture_output=True, text=True, timeout=30) + expect('--skip-failed skips up-to-date failure', ('%016x:' % 4) in out_skip.stdout, False) + # With -s short flag + out_s = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '-s', '--jobs=1'], + capture_output=True, text=True, timeout=30) + expect('-s skips up-to-date failure', ('%016x:' % 4) in out_s.stdout, False) + # With X2W_SKIP_FAILED=1 + env_skip = dict(os.environ, X2W_SKIP_FAILED='1') + out_env = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_cli), '--jobs=1'], + capture_output=True, text=True, timeout=30, env=env_skip) + expect('X2W_SKIP_FAILED=1 skips up-to-date failure', ('%016x:' % 4) in out_env.stdout, False) + + # --watch CLI argument parsing: worker count (--jobs / -j) must reach watch_pass and interval must be parsed separately. + observed_watch = [] + real_watch_pass = gfx2hlsl.watch_pass + real_sleep = time.sleep + try: + def mock_watch_pass_single(out_dir, skip_failed, jobs=None, completed=None): + observed_watch.append(('pass', jobs)) + raise KeyboardInterrupt + + def mock_sleep(secs): + observed_watch.append(('sleep', secs)) + + gfx2hlsl.watch_pass = mock_watch_pass_single + time.sleep = mock_sleep + + saved_argv = sys.argv + try: + # --watch <dir> --jobs 4: jobs must be 4, interval must remain default 2.0 (not read 4 as interval) + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '--jobs', '4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch --jobs 4 passes jobs to watch_pass', observed_watch, [('pass', 4)]) + + # --watch <dir> 3.5 --jobs 4: interval is 3.5, jobs is 4 + pass_count = [0] + def mock_watch_pass_multi(out_dir, skip_failed, jobs=None, completed=None): + pass_count[0] += 1 + observed_watch.append(('pass', jobs)) + if pass_count[0] >= 2: + raise KeyboardInterrupt + return True + + gfx2hlsl.watch_pass = mock_watch_pass_multi + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '3.5', '--jobs', '4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch 3.5 --jobs 4 parses interval and passes jobs', observed_watch, + [('pass', 4), ('sleep', 3.5), ('pass', 4)]) + + # --watch <dir> --jobs=4: jobs is 4, interval is default 2.0 + pass_count[0] = 0 + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '--jobs=4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch --jobs=4 passes jobs and keeps default interval', observed_watch, + [('pass', 4), ('sleep', 2.0), ('pass', 4)]) + + # --watch <dir> -j 4: jobs is 4, interval is default 2.0 + pass_count[0] = 0 + sys.argv = ['gfx2hlsl.py', '--watch', str(d_cli), '-j', '4'] + observed_watch.clear() + with suppress(KeyboardInterrupt): + gfx2hlsl.main() + expect('--watch -j 4 passes jobs and keeps default interval', observed_watch, + [('pass', 4), ('sleep', 2.0), ('pass', 4)]) + finally: + sys.argv = saved_argv + finally: + gfx2hlsl.watch_pass = real_watch_pass + time.sleep = real_sleep def mesh57_fixture(ms, ps, expected, tamper=False): root = (b'DXBC' + bytes(24) + struct.pack('<II', 1, 36) + b'RTS0' + @@ -107,9 +238,10 @@ def mesh57_fixture(ms, ps, expected, tamper=False): # A pair without a pixel stage is translated when the mesh has the accepted shape; this synthetic mesh does not. mesh57_fixture(mesh, b'', 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') mesh57_fixture(vertex, pixel, 'slot 57 mesh stage has no verified allocation and primitive export') -# A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check. +# A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check; +# the pair is translated when the mesh has the accepted shape, which this synthetic mesh does not. null_export = struct.pack('<3I', 0xf8001890, 0, endpgm) -mesh57_fixture(mesh, null_export, 'slot 57 mesh with a depth-only pixel stage is not covered') +mesh57_fixture(mesh, null_export, 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') # Controls: a position export, or a null export mixed with one, stays refused. mesh57_fixture(mesh, struct.pack('<3I', *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') mesh57_fixture(mesh, struct.pack('<5I', 0xf8001890, 0, *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') @@ -135,14 +267,49 @@ def mesh57_resume_controls(): expect('slot 57 with only mesh bytecode is pending', scan(d, False), [key]) touch(ps, bytecode) expect('slot 57 with both complete containers is done', scan(d, False), []) + + # Warm-cache controls: populate completed, verify truncation invalidates and rechecks + completed = {} + expect('slot 57 completed cache populates', gfx2hlsl.pending_keys(str(d), False, completed=completed), []) + expect('slot 57 cached in completed', key in completed, True) + expect('slot 57 warm cache hit is done', gfx2hlsl.pending_keys(str(d), False, completed=completed), []) + # Truncating ps bytecode invalidates warm cache and marks key pending + touch(ps, bytecode[:-1]) + expect('slot 57 warm cache detects truncated ps bytecode', gfx2hlsl.pending_keys(str(d), False, completed=completed), [key]) + expect('slot 57 invalidated from completed on ps truncation', key in completed, False) + touch(ps, bytecode) + expect('slot 57 restored ps re-caches in completed', gfx2hlsl.pending_keys(str(d), False, completed=completed), []) + expect('slot 57 re-cached after ps restored', key in completed, True) + # Truncating ms bytecode invalidates warm cache and marks key pending + touch(ms, bytecode[:-1]) + expect('slot 57 warm cache detects truncated ms bytecode', gfx2hlsl.pending_keys(str(d), False, completed=completed), [key]) + expect('slot 57 invalidated from completed on ms truncation', key in completed, False) + touch(ms, bytecode) + expect('slot 57 restored ms re-caches in completed', gfx2hlsl.pending_keys(str(d), False, completed=completed), []) + expect('slot 57 re-cached after ms restored', key in completed, True) + for stage in (ms, ps): touch(stage, bytecode[:-1]) expect(f'{stage.suffixes[0]} with truncated bytecode is pending', scan(d, True), [key]) touch(stage, b'bad!' + bytecode[4:]) expect(f'{stage.suffixes[0]} with a bad container header is pending', scan(d, False), [key]) touch(stage, bytecode) - os.environ['X2W_FXC'] = '' + + # Mesh-only ps none case with warm cache + touch(stem.with_suffix('.ms57.txt'), b'ps none\n') ps.unlink() + completed_none = {} + expect('slot 57 ps none populates completed', gfx2hlsl.pending_keys(str(d), False, completed=completed_none), []) + expect('slot 57 ps none cached in completed', key in completed_none, True) + expect('slot 57 ps none warm cache hit is done', gfx2hlsl.pending_keys(str(d), False, completed=completed_none), []) + # Truncating ms bytecode invalidates warm cache in ps none mode + touch(ms, bytecode[:-1]) + expect('slot 57 ps none truncated ms is pending on warm cache', gfx2hlsl.pending_keys(str(d), False, completed=completed_none), [key]) + expect('slot 57 ps none invalidated from completed on truncation', key in completed_none, False) + touch(ms, bytecode) + expect('slot 57 ps none restored ms re-caches', gfx2hlsl.pending_keys(str(d), False, completed=completed_none), []) + + os.environ['X2W_FXC'] = '' expect('slot 57 manifest-only mode finishes without pixel bytecode', scan(d, False), []) finally: os.environ.pop('X2W_FXC', None) @@ -224,10 +391,14 @@ def mesh57_resume_controls(): from concurrent.futures.process import BrokenProcessPool # noqa: E402 -def broken(out_dir, skip_failed=False): +def broken(out_dir, skip_failed=False, jobs=None, completed=None): raise BrokenProcessPool('a worker was terminated abruptly') +def broken_type_error(out_dir, skip_failed=False, jobs=None, completed=None): + raise TypeError('unexpected internal error') + + real = gfx2hlsl.translate_pending gfx2hlsl.translate_pending = broken try: @@ -236,6 +407,18 @@ def broken(out_dir, skip_failed=False): failures.append('a broken process pool escaped watch_pass') finally: gfx2hlsl.translate_pending = real + +# watch_pass does not swallow an unexpected internal TypeError raised by translate_pending. +gfx2hlsl.translate_pending = broken_type_error +try: + try: + gfx2hlsl.watch_pass('.', True) + except TypeError: + pass + else: + failures.append('watch_pass swallowed an unexpected TypeError') +finally: + gfx2hlsl.translate_pending = real with tempfile.TemporaryDirectory() as tmp: expect('normal pass reported as complete', gfx2hlsl.watch_pass(tmp, True), True) @@ -244,6 +427,7 @@ def broken(out_dir, skip_failed=False): for value in ('', 'abc', '-3'): os.environ['X2W_TRANSLATE_JOBS'] = value expect('X2W_TRANSLATE_JOBS=%r' % value, gfx2hlsl.translation_jobs() >= 1, True) + expect('translation_jobs(%r)' % value, gfx2hlsl.translation_jobs(value) >= 1, True) os.environ['X2W_TRANSLATE_JOBS'] = '2' expect('X2W_TRANSLATE_JOBS=2', gfx2hlsl.translation_jobs(), 2) if saved is None: @@ -251,6 +435,97 @@ def broken(out_dir, skip_failed=False): else: os.environ['X2W_TRANSLATE_JOBS'] = saved +# Both environment variable and explicit argument route through the Windows limit of 61 workers. +saved_os_name = os.name +saved_env = os.environ.get('X2W_TRANSLATE_JOBS') +try: + os.name = 'nt' + # Environment form + os.environ['X2W_TRANSLATE_JOBS'] = '62' + expect('X2W_TRANSLATE_JOBS=62 capped to 61 on Windows', gfx2hlsl.translation_jobs(), 61) + os.environ['X2W_TRANSLATE_JOBS'] = '60' + expect('X2W_TRANSLATE_JOBS=60 not capped on Windows', gfx2hlsl.translation_jobs(), 60) + # Explicit argument form + os.environ.pop('X2W_TRANSLATE_JOBS', None) + expect('translation_jobs(62) capped to 61 on Windows', gfx2hlsl.translation_jobs(62), 61) + expect('translation_jobs(60) not capped on Windows', gfx2hlsl.translation_jobs(60), 60) + # Explicit argument overrides environment variable + os.environ['X2W_TRANSLATE_JOBS'] = '10' + expect('explicit jobs 62 overrides environment variable to 61 on Windows', gfx2hlsl.translation_jobs(62), 61) + expect('explicit jobs 4 overrides environment variable to 4 on Windows', gfx2hlsl.translation_jobs(4), 4) +finally: + os.name = saved_os_name + if saved_env is None: + os.environ.pop('X2W_TRANSLATE_JOBS', None) + else: + os.environ['X2W_TRANSLATE_JOBS'] = saved_env + +# 62 synthetic pending RTV markers: verify worker pool capping across explicit and environment forms. +with tempfile.TemporaryDirectory() as tmp: + d_62 = Path(tmp) + for n in range(62): + req = b'rtv1 %d 28' % (0x9000 + n) + touch(d_62 / ('req_%016x.rtv' % gfx2hlsl.fnv(req)), req) + + from concurrent.futures import ProcessPoolExecutor as RealExecutor + observed_workers = [] + + class MockExecutor: + def __init__(self, max_workers=None, **kwargs): + observed_workers.append(max_workers) + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def map(self, fn, *iterables, **kwargs): + return [] + + sys.modules['concurrent.futures'].ProcessPoolExecutor = MockExecutor + try: + saved_os = os.name + os.name = 'nt' + try: + # 1. Explicit argument in translate_pending + del observed_workers[:] + gfx2hlsl.translate_pending(str(d_62), jobs=62) + expect('translate_pending with explicit jobs=62 capped to 61 on Windows', observed_workers, [61]) + + # 2. Environment variable in translate_pending + del observed_workers[:] + os.environ['X2W_TRANSLATE_JOBS'] = '62' + try: + gfx2hlsl.translate_pending(str(d_62)) + expect('translate_pending with X2W_TRANSLATE_JOBS=62 capped to 61 on Windows', observed_workers, [61]) + finally: + os.environ.pop('X2W_TRANSLATE_JOBS', None) + + # 3. Watch mode forwarding explicit jobs=62 + del observed_workers[:] + gfx2hlsl.watch_pass(str(d_62), skip_failed=True, jobs=62) + expect('watch_pass with explicit jobs=62 capped to 61 on Windows', observed_workers, [61]) + finally: + os.name = saved_os + finally: + sys.modules['concurrent.futures'].ProcessPoolExecutor = RealExecutor + + if os.name == 'nt': + # Live Windows CLI control: --pending with --jobs 62 executes without raising ValueError + res = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_62), '--jobs', '62'], + capture_output=True, text=True, timeout=120) + expect('CLI --pending --jobs 62 exits 0 on Windows', res.returncode, 0) + expect('no ValueError in stderr for --jobs 62', 'ValueError: max_workers must be <= 61' in res.stderr, False) + + res_env = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), + '--pending', str(d_62)], + capture_output=True, text=True, timeout=120, + env=dict(os.environ, X2W_TRANSLATE_JOBS='62')) + expect('CLI --pending X2W_TRANSLATE_JOBS=62 exits 0 on Windows', res_env.returncode, 0) + expect('no ValueError in stderr for env form', 'ValueError: max_workers must be <= 61' in res_env.stderr, False) + with tempfile.TemporaryDirectory() as tmp: d = Path(tmp) # A failure from an earlier run, newer than its marker: the watcher's first pass retries it once. diff --git a/tests/startup_gfx2hlsl_wave_reduce_check.py b/tests/startup_gfx2hlsl_wave_reduce_check.py new file mode 100644 index 0000000000..2eedc450ac --- /dev/null +++ b/tests/startup_gfx2hlsl_wave_reduce_check.py @@ -0,0 +1,959 @@ +"""Whole-wave reductions in tools/startup/gfx2hlsl.py (#2125 item D), read back from a real D3D12 draw. + + (no arguments) a 32-lane model of the source chains, translation controls and refusals + binary <llvm-mc> assemble every fixture with LLVM (gfx1013) and compare with the words here + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pixel stage with DXC ps_6_0 (the lowering uses shader + model 6.0 wave intrinsics, so FXC is not used), draw a triangle over 32 x 32 + pixels and compare every covered pixel with a CPU reference for its desktop + wave. The optional fxc argument is accepted and ignored. + +The three wave32 shapes of the #2125 censuses (RDNA 2 ISA: DPP16 quad_perm, row_half_mirror, row_mirror, +V_PERMLANEX16_B32, V_READLANE_B32; every DPP step with row_mask:0xf bank_mask:0xf fi:1): + OR s_or_saveexec_b32 sS, -1 / v_cndmask_b32_e64 vT, 0, vX, sS / v_or_b32_dpp vT, vT, vT quad_perm:[1,0,3,2], + quad_perm:[2,3,0,1], row_half_mirror, row_mirror / v_permlanex16_b32 vP, vT, 0, 0 / v_or_b32_e32 vT, vP, vT / + s_mov_b32 exec_lo, sS / v_readlane_b32 sD, vT, 31 + MIN the same with identity -1, but after the restore come one v_cndmask_b32_sdwa, the s_or_saveexec_b32 sS2, -1 of + the max chain, and only then v_readlane_b32 sD, vT, 31 + MAX right after a min: s_or_saveexec_b32 sS2, -1 / (the min's readlane) / v_cndmask_b32_e64 vT, 0, vX, sS2 / the + same steps with v_max_u32 / restore / readlane at once +The fixtures here are those shapes, written in LLVM 15 spelling and assembled from source, plus the immediate readlane +for each operation alone and variants that must be accepted or refused. + +The model below runs the source lines on 32 lanes with plain integers, from the ISA text and not from the lowering, +and shows that sD is OP over the lanes active before the chain for random EXEC masks, and that each refused mutation +either is not that reduction for some mask or is a conservative refusal (said so in its label). It also shows the +order that matters in the interleaved form: with vT shared by the two chains, the min's readlane moved after the max +fill reads the max. + +A uniform branch may sit before the chain, after it, or both. The branch here is s_cmp_eq_u32 of a constant with +itself (SCC proven uniform) and s_cbranch_scc0, which is not taken, over one s_nop; the other edge lands on the +chain too, so every lane runs the chain. The chain stays straight: no branch instruction and no branch target +inside it, and EXEC is saved and restored as in the shapes above. A branch target inside the chain, a non-uniform +branch that changes EXEC inside the chain (s_and_saveexec_b32 and s_cbranch_execz before the fill), a divergent +branch outside the chain, and wave64 stay refused. Restoring the straight-line refusal (the test wraps the matcher) +refuses the uniform-branch programs and still lowers the straight-line ones. + +The desktop contract: the console packs pixels into waves in its own way, so a correct program cannot depend on which +pixels share a wave; the lowering is one WaveActive* over the active lanes of the desktop wave. The draw cannot know +the desktop packing in advance, so the test appends one observation to the translated pixel stage: the fourth channel +is replaced by the lane index, the lane count (WaveGetLaneCount) and the pixel id of WaveReadLaneFirst, which names +the wave. The readback (offscreen_check --startup-pixel-dump) is grouped by that id and every covered pixel's results +are compared with OP over the inputs of the covered pixels of its group. The triangle leaves quads partly covered: +their helper lanes run the stage, are not in the console EXEC (no s_wqm), and must not change the result. Planted +errors in the translated text (another operation, the lane's own value, the first lane's value; signed for +unsigned only where that rewrite changes the program, which is min and max, since v_or_b32 has no signed form; +for the interleaved pair the min's readlane lowered after the max, min and max swapped, the v_cndmask_b32_sdwa +dropped) must fail. +""" +import collections +import random +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +SIZE = 32 # the draw is SIZE x SIZE pixels +CLEAR = 0xbf800000 # -1.0: the target's clear value, kept by uncovered pixels +MULTIPLIER = 0x9b5d +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +# A triangle with three slanted edges, so many quads are partly covered (helper lanes) and some waves are partial. +TRIANGLE_VS = """\ +float4 main(uint id : SV_VertexID) : SV_Position +{ + return id == 0 ? float4(-1.0, 1.0, 0.0, 1.0) : id == 1 ? float4(1.0, 0.37, 0.0, 1.0) : float4(-0.61, -1.0, 0.0, 1.0); +} +""" + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + detail)) + if not ok: + failures.append(label) + + +# ---- encoders (gfx10 field layouts; the binary mode checks every word against llvm-mc) -------------------------------- +def sop1(op, sdst, ssrc): + return struct.pack('<I', 0xbe800000 | (sdst << 16) | (op << 8) | ssrc) + + +def vop1_mov(vdst, src): + return struct.pack('<I', 0x7e000000 | (vdst << 17) | (1 << 9) | src) + + +def vop2(op, vdst, src0, vsrc1): + return struct.pack('<I', (op << 25) | (vdst << 17) | (vsrc1 << 9) | src0) + + +def vop2_dpp(op, vdst, src0, vsrc1, ctrl, bound_ctrl=False, fi=True, bank=0xf, row=0xf): + return struct.pack('<II', (op << 25) | (vdst << 17) | (vsrc1 << 9) | 250, + src0 | (ctrl << 8) | (int(fi) << 18) | (int(bound_ctrl) << 19) | (bank << 24) | (row << 28)) + + +def vop2_sdwa(op, vdst, src0, vsrc1, dst_sel, src0_sel, src1_sel): + """VOP2 SDWA with VGPR sources and dst_unused:UNUSED_PAD (selects: 0..3 BYTE_n, 4 WORD_0, 5 WORD_1, 6 DWORD).""" + return struct.pack('<II', (op << 25) | (vdst << 17) | (vsrc1 << 9) | 249, + src0 | (dst_sel << 8) | (src0_sel << 16) | (src1_sel << 24)) + + +def vop3(op, vdst, src0, src1, src2=0, opsel=0): + return struct.pack('<II', 0xd4000000 | (op << 16) | (opsel << 11) | vdst, src0 | (src1 << 9) | (src2 << 18)) + + +def sopp(op, simm=0): + return struct.pack('<I', 0xbf800000 | (op << 16) | (simm & 0xffff)) + + +def sopc(op, ssrc0, ssrc1): + return struct.pack('<I', 0xbf000000 | (op << 16) | (ssrc1 << 8) | ssrc0) + + +S_MOV_B32, S_WQM_B32, S_OR_SAVEEXEC_B32, S_OR_SAVEEXEC_B64 = 0x03, 0x09, 0x3d, 0x25 +S_AND_SAVEEXEC_B32, S_CMP_EQ_U32 = 0x3c, 0x06 +S_CBRANCH_SCC0, INLINE_1 = 0x04, 129 +EXEC_LO, INLINE_M1 = 126, 0xc1 +V_PERMLANEX16_B32, V_READLANE_B32, V_CNDMASK_B32_E64, V_LSHLREV_B32_E64 = 0x378, 0x360, 0x101, 0x11a +V_CNDMASK_B32, V_CMP_GT_U32 = 0x01, 0xc4 +VOP2_OPS = {'v_or_b32': 0x1c, 'v_min_u32': 0x13, 'v_max_u32': 0x14, 'v_max_i32': 0x12, 'v_add_nc_u32': 0x25, + 'v_max_f32': 0x10} +CTRL = {'quad_perm:[1,0,3,2]': 0xb1, 'quad_perm:[2,3,0,1]': 0x4e, 'row_half_mirror': 0x141, 'row_mirror': 0x140, + 'row_shr:1': 0x111} +IDENTITY = {'v_or_b32': 0, 'v_min_u32': 0xffffffff, 'v_max_u32': 0, 'v_max_i32': 0x80000000, 'v_add_nc_u32': 0} +OPS = ('v_or_b32', 'v_min_u32', 'v_max_u32') +STEPS = ('quad_perm:[1,0,3,2]', 'quad_perm:[2,3,0,1]', 'row_half_mirror', 'row_mirror') + + +def inline(value): + """A fill constant as an inline constant: (LLVM spelling, encoded field).""" + return {0: ('0', 128), 1: ('1', 129), 5: ('5', 133), MASK: ('-1', INLINE_M1)}[value] + + +def cndmask_fill(vt, src, ss, value, mask=None): + """The census fill: v_cndmask_b32_e64 vT, <identity>, vX, sS.""" + text, field = inline(value) + mask = ss if mask is None else mask + return [('v_cndmask_b32_e64 v%d, %s, v%d, s%d' % (vt, text, src, mask), + vop3(V_CNDMASK_B32_E64, vt, field, 256 + src, mask))] + + +def dpp_line(op, vt, ctrl, bound_ctrl=False, fi=True, row=0xf): + text = '%s_dpp v%d, v%d, v%d %s row_mask:0x%x bank_mask:0xf%s%s' % ( + op, vt, vt, vt, ctrl, row, ' bound_ctrl:1' if bound_ctrl else '', ' fi:1' if fi else '') + return text, vop2_dpp(VOP2_OPS[op], vt, vt, vt, CTRL[ctrl], bound_ctrl, fi, row=row) + + +def saveexec(ss): + return ('s_or_saveexec_b32 s%d, -1' % ss, sop1(S_OR_SAVEEXEC_B32, ss, INLINE_M1)) + + +def readlane(sd, vt, lane=31): + return ('v_readlane_b32 s%d, v%d, %d' % (sd, vt, lane), vop3(V_READLANE_B32, sd, 256 + vt, 128 + lane)) + + +def chain(op, vt=2, vp=3, ss=0, sd=1, src=1, fill='census', identity=None, fill_mask=None, steps=STEPS, + step_ops=None, perm=(0, 0), perm_opsel=0, lane=31, combine='census', tail_order=('restore', 'readlane'), + restore_reg=None, wave='b32', bound_ctrl=False, fi=True, row=0xf): + """One chain as (source line, words) pairs; the keyword arguments build the mutations.""" + identity = IDENTITY[op] if identity is None else identity + if wave == 'b64': + lines = [('s_or_saveexec_b64 s[%d:%d], -1' % (ss, ss + 1), sop1(S_OR_SAVEEXEC_B64, ss, INLINE_M1))] + else: + lines = [saveexec(ss)] + if fill == 'census': + lines += cndmask_fill(vt, src, ss, identity, fill_mask) + elif fill == 'copy': # the input copied with no identity: the lanes outside sS keep their own value + lines.append(('v_mov_b32_e32 v%d, v%d' % (vt, src), vop1_mov(vt, 256 + src))) + for k, ctrl in enumerate(steps): + lines.append(dpp_line((step_ops or {}).get(k, op), vt, ctrl, bound_ctrl, fi, row if k == 0 else 0xf)) + spelling = 'v_permlanex16_b32 v%d, v%d, %d, %d%s' % ((vp, vt) + perm + (' op_sel:[1,0]' if perm_opsel else '',)) + lines.append((spelling, vop3(V_PERMLANEX16_B32, vp, 256 + vt, 128 + perm[0], 128 + perm[1], perm_opsel))) + if combine == 'census': # v_or_b32_e32 vT, vP, vT + lines.append(('%s_e32 v%d, v%d, v%d' % (op, vt, vp, vt), vop2(VOP2_OPS[op], vt, 256 + vp, vt))) + elif combine == 'e32': # the sources the other way round + lines.append(('%s_e32 v%d, v%d, v%d' % (op, vt, vt, vp), vop2(VOP2_OPS[op], vt, 256 + vt, vp))) + else: # VOP3 + lines.append(('%s_e64 v%d, v%d, v%d' % (op, vt, vp, vt), vop3(0x100 + VOP2_OPS[op], vt, 256 + vp, 256 + vt))) + restore_reg = ss if restore_reg is None else restore_reg + parts = {'readlane': readlane(sd, vt, lane), + 'restore': ('s_mov_b32 exec_lo, s%d' % restore_reg, sop1(S_MOV_B32, EXEC_LO, restore_reg))} + return lines + [parts[t] for t in tail_order] + + +START_MUL = [('v_mul_u32_u24_e32 v1, 0x9b5d, v0', struct.pack('<II', (0x0b << 25) | (1 << 17) | 255, MULTIPLIER))] +START_BIT = [('v_lshlrev_b32_e64 v1, v0, 1', vop3(V_LSHLREV_B32_E64, 1, 256 + 0, 129))] # 1 << (x & 31) +WQM = [('s_wqm_b32 exec_lo, exec_lo', sop1(S_WQM_B32, EXEC_LO, EXEC_LO))] +CMP = [('v_cmp_gt_u32_e32 vcc_lo, v1, v0', struct.pack('<I', 0x7c000000 | (V_CMP_GT_U32 << 17) | (0 << 9) | 257))] + + +def sdwa_line(vdst=6): + """The census's v_cndmask_b32_sdwa between the min chain's restore and the max chain: vcc ? y : x * MULTIPLIER low + word, here with v1 (the input) and v0 (the packed position, y in the high word).""" + return [('v_cndmask_b32_sdwa v%d, v1, v0, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 ' + 'src1_sel:WORD_1' % vdst, vop2_sdwa(V_CNDMASK_B32, vdst, 1, 0, 6, 4, 5))] + + +def export(first, second, third, last='v0'): + regs = [int(r[1:]) for r in (first, second, third, last)] + return [('exp mrt0 %s, %s, %s, %s done vm' % (first, second, third, last), + struct.pack('<II', 0xf800180f, regs[0] | regs[1] << 8 | regs[2] << 16 | regs[3] << 24)), + ('s_endpgm', sopp(0x01))] + + +def move(vd, sn): + return ('v_mov_b32_e32 v%d, s%d' % (vd, sn), vop1_mov(vd, sn)) + + +RESULT = [move(4, 1)] +END = export('v4', 'v1', 'v2') # result, input, vT after the chain, position +END_READS_VP = export('v4', 'v1', 'v3') +KILL_VP = [('v_mov_b32_e32 v3, 0', vop1_mov(3, 128))] + + +def program(*parts): + lines = [line for part in parts for line in part] + return '\n'.join(text for text, _w in lines) + '\n', b''.join(w for _t, w in lines) + + +def start(op): + return START_BIT if op == 'v_or_b32' else START_MUL + + +def word(op, x, y): + return (1 << (x & 31)) if op == 'v_or_b32' else ((x | (y << 16)) * MULTIPLIER) & MASK + + +def fixture(op): + return program(start(op), chain(op), RESULT, END) + + +def interleaved(min_kw=None, max_kw=None, between=None, carry=True, carrier='v_max_u32', min_op='v_min_u32'): + """The census's min then max: the min chain up to its restore, the v_cndmask_b32_sdwa, the max chain's saveexec, + the min's readlane, then the rest of the max chain. Defaults: both chains on v1, vT v2 shared, vP v3, sS s0 and s4, + sD s1 and s5.""" + min_kw = dict(dict(vt=2, vp=3, ss=0, sd=1), **(min_kw or {})) + max_kw = dict(dict(vt=2, vp=3, ss=4, sd=5), **(max_kw or {})) + head = chain(min_op, tail_order=('restore',), **min_kw) + tail = chain(carrier, **max_kw) + later = [readlane(min_kw['sd'], min_kw['vt'])] if carry else [] + return head + (sdwa_line() if between is None else between) + tail[:1] + later + tail[1:] + + +# The census's min then max (vT shared), with the results and the v_cndmask_b32_sdwa exported. +PAIR_RESULTS = [move(4, 1), move(8, 5)] +PAIR = program(START_MUL, CMP, interleaved(), PAIR_RESULTS, export('v4', 'v6', 'v8')) +# The same with a vT of its own for the max chain. +PAIR_SPLIT = program(START_MUL, CMP, interleaved(max_kw=dict(vt=5)), PAIR_RESULTS, export('v4', 'v6', 'v8')) +# Min then max each read at once, back to back with their own saveexec (accepted: the OR shape for each). +PAIR_AT_ONCE = program(START_MUL, chain('v_min_u32'), chain('v_max_u32', vt=5, vp=3, ss=6, sd=7), + [move(4, 1), move(8, 7)], export('v4', 'v1', 'v8')) +# One set as the capture reports it per program: an or, then the min and max pair. +SET = program(START_MUL, CMP, chain('v_or_b32', vt=9, vp=3, ss=10, sd=11), interleaved(), + [move(4, 1), move(8, 5), move(12, 11)], export('v4', 'v8', 'v12')) + + +def branch_program(op, into): + """s_cbranch_execz at the top, landing on the chain's v_permlanex16_b32 (into) or on the export after it.""" + body = start(op) + chain(op) + RESULT + upto = start(op) + chain(op)[:7] if into else body + words_before = sum(len(w) for _t, w in upto) // 4 + label = [('s_cbranch_execz label_%04X' % (4 * (1 + words_before)), sopp(0x08, words_before))] + return program(label, body, END) + + +def uniform_scc_block(at, skip=1): + """s_mov_b32 s2, 1 / s_cmp_eq_u32 s2, 1 / s_cbranch_scc0 over `skip` s_nop instructions, starting at byte `at`. + + The compare is true, so s_cbranch_scc0 is not taken and every lane falls through the nop into the next + instruction. The taken edge lands on that same instruction, so the chain runs on every lane either way. + s2 is not a register the chain uses.""" + mov = ('s_mov_b32 s2, 1', sop1(S_MOV_B32, 2, INLINE_1)) + cmp = ('s_cmp_eq_u32 s2, 1', sopc(S_CMP_EQ_U32, 2, INLINE_1)) + branch_at = at + 8 + target = branch_at + 4 + skip * 4 + branch = ('s_cbranch_scc0 label_0x%x' % target, sopp(S_CBRANCH_SCC0, (target - (branch_at + 4)) // 4)) + return [mov, cmp, branch] + [('s_nop 0', sopp(0))] * skip + + +def uniform_around(op, where): + """The op's straight-line program with a uniform branch before the chain, after it, or both.""" + head = start(op) + chain(op) + if where == 'before': + return program(uniform_scc_block(0), head, RESULT, END) + if where == 'after': + return program(head, uniform_scc_block(sum(len(w) for _t, w in head)), RESULT, END) + if where == 'both': + prefix = uniform_scc_block(0) + at = sum(len(w) for part in (prefix, head) for _t, w in part) + return program(prefix, head, uniform_scc_block(at), RESULT, END) + raise AssertionError(where) + + +def wave64_with_uniform_branch(op): + """wave64 chain after a uniform branch: the wave64 refusal comes before the branch allowance.""" + prefix = uniform_scc_block(0) + return program(prefix, start(op), chain(op, wave='b64'), RESULT, END) + + +def exec_inside(op): + """s_and_saveexec_b32 and s_cbranch_execz between the chain's saveexec and its fill.""" + opening = [saveexec(0)] + rest = chain(op)[1:] + inserted = opening + [ + ('s_and_saveexec_b32 s6, s7', sop1(S_AND_SAVEEXEC_B32, 6, 7)), + ] + at = sum(len(w) for _t, w in inserted) + # The branch instruction is inside the chain; its target is the export, past the chain. + before_end = rest + RESULT + target = at + 4 + sum(len(w) for _t, w in before_end) + branch = [('s_cbranch_execz label_0x%x' % target, sopp(0x08, (target - (at + 4)) // 4))] + return program(inserted, branch, before_end, END) + + +def nonuniform_after(op): + """s_cbranch_execz after the chain, targeting the next instruction. EXEC is still the entry mask.""" + head = start(op) + chain(op) + at = sum(len(w) for _t, w in head) + branch = [('s_cbranch_execz label_0x%x' % (at + 4), sopp(0x08, 0))] + return program(head, branch, RESULT, END) + + +def branch_into_later_readlane(): + """s_cbranch_execz at the top, landing on the min chain's later readlane inside the max chain.""" + body = START_MUL + CMP + interleaved() + PAIR_RESULTS + upto = START_MUL + CMP + interleaved()[:11] + assert upto[-1][0].startswith('s_or_saveexec_b32 s4') + words_before = sum(len(w) for _t, w in upto) // 4 + label = [('s_cbranch_execz label_%04X' % (4 * (1 + words_before)), sopp(0x08, words_before))] + return program(label, body, export('v4', 'v6', 'v8')) + + +def translate(words): + try: + return G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=PACKED).hlsl_ps(), None + except G.Unsupported as reason: + return None, str(reason) + + +def straight_line_refusal(words): + """Translate with the pre-allowance guard put back: any branch refuses the chain. + + The wrapper runs the real matcher, then refuses once it has accepted an instruction of a chain in a program + that has branches. A straight-line chain never takes that path.""" + original = G.Stage.wave_reduction + + def reverted(self, base, ops): + branched = bool(getattr(self, 'has_branches', False) or getattr(self, 'blocks', False)) + allowed = original(self, base, ops) + if allowed and branched: + raise G.Unsupported('wave reduction in a program with branches: only straight-line pixel stages are lowered') + return allowed + + G.Stage.wave_reduction = reverted + try: + return translate(words) + finally: + G.Stage.wave_reduction = original + + +# ---- 32-lane model of the source chain (the ISA, not the lowering) -------------------------------------------------- +def apply(op, a, b): + if op == 'v_or_b32': + return a | b + if op == 'v_min_u32': + return min(a, b) + if op == 'v_max_u32': + return max(a, b) + if op == 'v_max_i32': + return max(a, b, key=lambda v: v - (1 << 32) if v & 0x80000000 else v) + if op == 'v_add_nc_u32': + return (a + b) & MASK + raise AssertionError(op) + + +def dpp_source(ctrl, lane): + row, within = lane & ~15, lane & 15 + if ctrl.startswith('quad_perm:'): + perm = [int(c) for c in re.findall(r'\d', ctrl)] + return (lane & ~3) | perm[lane & 3] + if ctrl == 'row_half_mirror': + return row | (within & 8) | (7 - (within & 7)) + if ctrl == 'row_mirror': + return row | (15 - within) + if ctrl == 'row_shr:1': + return lane - 1 if within >= 1 else None # no source: bound_ctrl decides + raise AssertionError(ctrl) + + +SELECT = {'BYTE_0': (0, 0xff), 'BYTE_1': (8, 0xff), 'BYTE_2': (16, 0xff), 'BYTE_3': (24, 0xff), 'WORD_0': (0, 0xffff), + 'WORD_1': (16, 0xffff), 'DWORD': (0, MASK)} + + +def run_model(source, inputs, exec_mask, rng): + """Run the source lines on 32 lanes; v1 holds the inputs, every other VGPR starts with arbitrary words, as + registers a lane never wrote do. Returns the SGPRs.""" + v = collections.defaultdict(lambda: [rng.getrandbits(32) for _ in range(32)]) + v[1] = list(inputs) + s, exec_lo, vcc = {}, exec_mask, 0 + + def reg(tok): + return v[int(tok[1:])] + + for line in source.splitlines(): + name, ops, mods = G.parse(line) + base = re.sub(r'_e(32|64)$', '', name) + if base in ('v_mul_u32_u24', 'v_lshlrev_b32', 'exp', 's_endpgm') or (base == 'v_mov_b32' and ops[1][0] == 's'): + continue + if base == 's_or_saveexec_b32': + s[int(ops[0][1:])], exec_lo = exec_lo, MASK + elif base == 's_mov_b32' and ops[0] == 'exec_lo': + exec_lo = s[int(ops[1][1:])] + elif base == 'v_mov_b32': + value = reg(ops[1]) if ops[1].startswith('v') else [int(ops[1], 0) & MASK] * 32 + dst = reg(ops[0]) + v[int(ops[0][1:])] = [value[i] if exec_lo >> i & 1 else dst[i] for i in range(32)] + elif base == 'v_cmp_gt_u32': + a, b = reg(ops[1]), reg(ops[2]) + vcc = sum(1 << i for i in range(32) if exec_lo >> i & 1 and a[i] > b[i]) + elif base == 'v_cndmask_b32_sdwa': + sel = dict(m.split(':') for m in mods) + assert sel['dst_sel'] == 'DWORD' and ops[3] == 'vcc_lo', line + pick = [(lambda w, k=k: (w >> SELECT[sel[k]][0]) & SELECT[sel[k]][1]) for k in ('src0_sel', 'src1_sel')] + a, b, dst = reg(ops[1]), reg(ops[2]), reg(ops[0]) + v[int(ops[0][1:])] = [(pick[1](b[i]) if vcc >> i & 1 else pick[0](a[i])) if exec_lo >> i & 1 else dst[i] + for i in range(32)] + elif base == 'v_cndmask_b32': + mask, a, b, dst = s[int(ops[3][1:])], int(ops[1], 0) & MASK, reg(ops[2]), reg(ops[0]) + v[int(ops[0][1:])] = [(b[i] if mask >> i & 1 else a) if exec_lo >> i & 1 else dst[i] for i in range(32)] + elif base.endswith('_dpp'): + ctrl = [m for m in mods if not m.startswith(('row_mask:', 'bank_mask:', 'bound_ctrl:', 'fi:'))][0] + row_mask = int([m for m in mods if m.startswith('row_mask:')][0][9:], 0) + dst, src0, src1 = int(ops[0][1:]), reg(ops[1]), reg(ops[2]) + out = list(v[dst]) + for i in range(32): + if not (exec_lo >> i & 1 and row_mask >> (i // 16) & 1): + continue + k = dpp_source(ctrl, i) + if k is not None and (exec_lo >> k & 1 or 'fi:1' in mods): + word_in = src0[k] # fi:1 reads a disabled source lane too + elif 'bound_ctrl:1' in mods: + word_in = 0 + else: + continue # the lane keeps its old value + out[i] = apply(base[:-4], word_in, src1[i]) + v[dst] = out + elif base == 'v_permlanex16_b32': + sel, src = (int(ops[2], 0), int(ops[3], 0)), reg(ops[1]) + out = list(reg(ops[0])) + for i in range(32): + if exec_lo >> i & 1: + within = i & 15 + nibble = ((sel[0] >> (4 * within)) if within < 8 else (sel[1] >> (4 * (within - 8)))) & 15 + out[i] = src[(i ^ 16) & ~15 | nibble] + v[int(ops[0][1:])] = out + elif base in IDENTITY: + a, b, dst = reg(ops[1]), reg(ops[2]), reg(ops[0]) + v[int(ops[0][1:])] = [apply(base, a[i], b[i]) if exec_lo >> i & 1 else dst[i] for i in range(32)] + elif base == 'v_readlane_b32': + s[int(ops[0][1:])] = reg(ops[1])[int(ops[2], 0)] + elif base == 's_mov_b32' and ops[0].startswith('s'): + continue # the uniform-branch fixture's constant; it is not an input of the reduction + elif base in ('s_nop', 's_cmp_eq_u32', 's_cbranch_scc0', 's_cbranch_scc1', 's_branch'): + # The accepted branch is not taken (s_cbranch_scc0 on a true compare) and its other edge lands on the + # chain, so executing every line still runs the chain on every lane. + continue + else: + raise AssertionError(line) + return s + + +def reduction(op, inputs, exec_mask): + value = IDENTITY[op] + for i in range(32): + if exec_mask >> i & 1: + value = apply(op, value, inputs[i]) + return value + + +def model_says_reduction(source, expect, trials=300, seed=2125): + """expect: [(SGPR, op)]: each SGPR must be op over the lanes active before the program.""" + rng = random.Random(seed) + masks = [MASK, 1, 1 << 31, 0x0000ffff, 0xffff0000, 0x80000001] + [rng.getrandbits(32) | 1 for _ in range(trials)] + for mask in masks: + inputs = [rng.getrandbits(32) for _ in range(32)] + s = run_model(source, inputs, mask, rng) + if any(s.get(sd) != reduction(op, inputs, mask) for sd, op in expect): + return False + return True + + +# ---- controls --------------------------------------------------------------------------------------------------------- +INTRINSIC = {'v_or_b32': 'WaveActiveBitOr(v1)', 'v_min_u32': 'WaveActiveMin(v1)', 'v_max_u32': 'WaveActiveMax(v1)'} +PAIR_EXPECT = [(1, 'v_min_u32'), (5, 'v_max_u32')] + + +def refusals(): + """(label, program, refusal fragment, model: True a conservative refusal, False not the reduction, None not run, + or a list of (SGPR, op) to run the model with when the result is not s1).""" + op = 'v_max_u32' + full = lambda **kw: program(START_MUL, chain(op, **kw), RESULT, END) # noqa: E731 + pair = lambda **kw: program(START_MUL, CMP, interleaved(**kw), PAIR_RESULTS, export('v4', 'v6', 'v8')) # noqa: E731 + yield ('wave64 (s_or_saveexec_b64 s[0:1], -1)', full(wave='b64'), 'wave64', None) + yield ('no identity fill', full(fill=None), 'identity fill', False) + yield ('the input copied without the identity', full(fill='copy'), 'identity fill', False) + yield ('a fill with another constant (1 for v_max_u32)', full(identity=1), 'identity fill', None) + for other in OPS: # a constant that is no operation's identity, for each operation + yield ('a fill with another constant (5 for %s)' % other, + program(start(other), chain(other, identity=5), RESULT, END), 'identity fill', None) + yield ('a fill under another saved mask (s5)', full(fill_mask=5), 'identity fill', None) + yield ('wrong identity (-1 for v_max_u32)', full(identity=MASK), 'identity', False) + yield ('wrong identity (0 for v_min_u32)', program(START_MUL, chain('v_min_u32', identity=0), RESULT, END), + 'identity', [(1, 'v_min_u32')]) + yield ('wrong identity (-1 for v_or_b32)', program(START_BIT, chain('v_or_b32', identity=MASK), RESULT, END), + 'identity', [(1, 'v_or_b32')]) + yield ('wrong identity (0 for the interleaved v_min_u32)', pair(min_kw=dict(identity=0)), 'identity', + [(1, 'v_min_u32')]) + yield ('row_mirror step removed', full(steps=STEPS[:3]), 'missing step row_mirror', False) + yield ('row_half_mirror step removed', full(steps=STEPS[:2] + STEPS[3:]), 'in place of row_half_mirror', False) + yield ('first quad step removed', full(steps=STEPS[1:]), 'in place of quad_perm:[1,0,3,2]', False) + yield ('mirror steps reordered (conservative)', full(steps=STEPS[:2] + STEPS[3:1:-1]), 'out of order', True) + yield ('quad steps reordered (conservative)', full(steps=STEPS[1::-1] + STEPS[2:]), 'out of order', True) + yield ('row_shr:1 in place of row_mirror', full(steps=STEPS[:3] + ('row_shr:1',)), 'row_shr:1 in place of', False) + yield ('mixed operations (one v_min_u32 step)', full(step_ops={2: 'v_min_u32'}), 'mixes', False) + yield ('v_add_nc_u32 (not in the census)', program(START_MUL, chain('v_add_nc_u32'), RESULT, END), + 'only v_or_b32', None) + yield ('v_max_i32 (not in the census)', program(START_MUL, chain('v_max_i32', identity=0), RESULT, END), + 'only v_or_b32', None) + yield ('a float step (v_max_f32)', full(step_ops={0: 'v_max_f32'}), 'only v_or_b32', None) + yield ('readlane of lane 30 (conservative)', full(lane=30), 'lane 30', True) + yield ('permlanex16 lane selects 1, 0 (conservative)', full(perm=(1, 0)), 'lane selects', True) + yield ('permlanex16 with op_sel (fi) (conservative)', full(perm_opsel=1), 'lane selects', True) + yield ('readlane before the restore (conservative)', full(tail_order=('readlane', 'restore')), + 'EXEC restored before the readlane', True) + yield ('EXEC restored from another SGPR', full(restore_reg=5), 'in place of s_mov_b32 exec_lo, s0', None) + yield ('partial row mask on a step', full(row=0x1), 'partial row or bank mask', False) + yield ('branch target inside the chain', branch_program(op, True), 'branch target', None) + yield ('branch target on the later readlane of the v_min_u32 chain', branch_into_later_readlane(), + 'branch target', None) + yield ('a program with branches', branch_program(op, False), 'program with branches', None) + yield ('a non-uniform branch that changes EXEC inside the chain', exec_inside(op), 'non-uniform branch', None) + yield ('a non-uniform branch after the chain', nonuniform_after(op), 'program with branches', None) + yield ('wave64 with a uniform branch before the chain', wave64_with_uniform_branch(op), 'wave64', None) + yield ('after s_wqm exec_lo, exec_lo', program(WQM, START_MUL, chain(op), RESULT, END), 'helper lanes', None) + yield ('the permlane VGPR read after the chain', program(START_MUL, chain(op), RESULT, END_READS_VP), + 'read after the chain', None) + # The interleaved min then max of the census, each piece missing or changed. + yield ('the later readlane of the v_min_u32 chain missing', pair(carry=False), + 'in place of v_readlane_b32 sN, v2, 31', [(1, 'v_min_u32')]) + yield ('vT rewritten between the restore and the later readlane', + pair(between=sdwa_line(vdst=2)), 'rewrites v2 before the readlane', [(1, 'v_min_u32')]) + # Only the v_cndmask_b32_sdwa reads v0 after the min chain (the export does not), so the scan must start at the + # restore, not after the later readlane. + yield ('the permlane VGPR read by the v_cndmask_b32_sdwa (vP = v0)', + program(START_MUL, CMP, interleaved(min_kw=dict(vp=0)), PAIR_RESULTS, export('v4', 'v6', 'v8', 'v8')), + 'read after the chain by v_cndmask_b32_sdwa', None) + yield ('another instruction in place of the v_cndmask_b32_sdwa (conservative)', pair(between=KILL_VP), + 'in place of v_readlane_b32 sN, v2, 31', (True, PAIR_EXPECT)) + yield ('a v_or_b32 chain carrying the later readlane (conservative)', pair(carrier='v_or_b32'), + 'only a v_max_u32 chain', (True, [(1, 'v_min_u32'), (5, 'v_or_b32')])) + yield ('a v_max_u32 chain that reads its lane later (conservative)', pair(min_op='v_max_u32'), + 'only the v_min_u32 chain reads its lane later', (True, [(1, 'v_max_u32'), (5, 'v_max_u32')])) + yield ('the later readlane overwrites the EXEC saved by the v_max_u32 chain', pair(min_kw=dict(sd=4)), + 'overwrites s4', [(4, 'v_min_u32'), (5, 'v_max_u32')]) + lone = START_MUL + CMP + chain('v_min_u32', tail_order=('restore',)) + sdwa_line() + \ + [saveexec(4), readlane(1, 2), ('s_mov_b32 exec_lo, s4', sop1(S_MOV_B32, EXEC_LO, 4))] + RESULT + yield ('the later readlane after an s_or_saveexec_b32 that starts no chain', program(lone, END), + 'not carried by a v_max_u32 chain', None) + + +def body_of(text): + return text.split('PSOut o = (PSOut)0;', 1)[1] + + +def model_run(label, source, model, default): + """model: None (not run), True (a conservative refusal: still reduces), False (not the reduction), a list of + (SGPR, op) (not the reduction, checked on those), or (flag, list).""" + if model is None: + return + if isinstance(model, list): + model = (False, model) + want, expect = model if isinstance(model, tuple) else (model, default) + got = model_says_reduction(source, expect) + check('%s: the 32-lane model %s' % (label, 'still reduces' if want else 'is not the reduction'), got == want) + + +def controls(): + fills = G.Stage.WAVE_REDUCE_FILLS + census = G.Stage.__dict__['wave_reduce_cndmask_fill'] + check('the identity fill table holds the census form only', fills == (census,), str(fills)) + for op in OPS: + source, words = fixture(op) + decoded = [text for _o, _s, _n, text in G.decode(words)] + check('%s fixture decodes to its source' % op, decoded == source.splitlines(), str(decoded)) + check('%s chain is the reduction on the 32-lane model' % op, model_says_reduction(source, [(1, op)])) + text, reason = translate(words) + check('%s translates' % op, text is not None, str(reason)) + if text is None: + continue + body = body_of(text) + check('%s lowers to one %s' % (op, INTRINSIC[op]), + body.count('Wave') == 1 and 'v2 = %s;' % INTRINSIC[op] in body and 's1 = v2;' in body + and 'QuadRead' not in body and 'exec &' not in body, body) + check('%s keeps the saved EXEC and SCC of the chain' % op, 's0 = exec;' in body and 'scc = true;' in body, body) + # The census's interleaved min then max, and the full set of one program. + for label, (source, words), expect, order in ( + ('min then max, interleaved, vT shared', PAIR, PAIR_EXPECT, + ('v2 = WaveActiveMin(v1);', 'v6 = ', 's1 = v2;', 'v2 = WaveActiveMax(v1);', 's5 = v2;')), + ('min then max, interleaved, vT apart', PAIR_SPLIT, PAIR_EXPECT, + ('v2 = WaveActiveMin(v1);', 'v6 = ', 's1 = v2;', 'v5 = WaveActiveMax(v1);', 's5 = v5;')), + ('min then max, each read at once', PAIR_AT_ONCE, [(1, 'v_min_u32'), (7, 'v_max_u32')], + ('v2 = WaveActiveMin(v1);', 's1 = v2;', 'v5 = WaveActiveMax(v1);', 's7 = v5;')), + ('or, then min and max interleaved', SET, PAIR_EXPECT + [(11, 'v_or_b32')], + ('v9 = WaveActiveBitOr(v1);', 's11 = v9;', 'v2 = WaveActiveMin(v1);', 'v6 = ', 's1 = v2;', + 'v2 = WaveActiveMax(v1);', 's5 = v2;'))): + decoded = [text for _o, _s, _n, text in G.decode(words)] + check('%s fixture decodes to its source' % label, decoded == source.splitlines(), str(decoded)) + check('%s chains are the reductions on the 32-lane model' % label, model_says_reduction(source, expect)) + text, reason = translate(words) + check('%s translates' % label, text is not None, str(reason)) + if text is None: + continue + body = body_of(text) + at = [body.find('\n ' + piece) for piece in order] # statements, not the declarations + check('%s: one wave operation per chain, in program order' % label, + -1 not in at and at == sorted(at) and body.count('WaveActive') == len(expect), body) + # The order that matters: the min's readlane after the max fill reads the max when vT is shared. + lines = PAIR[0].splitlines() + late = lines[:] + moved = late.pop(late.index('v_readlane_b32 s1, v2, 31')) + late.insert(late.index('v_cndmask_b32_e64 v2, 0, v1, s4') + 1, moved) + check('planted error: the min readlane after the max fill is not the min on the 32-lane model', + not model_says_reduction('\n'.join(late) + '\n', [(1, 'v_min_u32')])) + for label, variant in (('bound_ctrl on every step', chain('v_max_u32', bound_ctrl=True)), + ('steps without fi', chain('v_max_u32', fi=False)), + ('the combine with the sources the other way round', chain('v_max_u32', combine='e32')), + ('the combine in VOP3', chain('v_max_u32', combine='e64'))): + source, words = program(START_MUL, variant, RESULT, END) + text, reason = translate(words) + check('accepts %s' % label, text is not None and 'v2 = WaveActiveMax(v1);' in text, str(reason)) + check('%s is the reduction on the 32-lane model' % label, model_says_reduction(source, [(1, 'v_max_u32')])) + _source, words = program(START_MUL, chain('v_max_u32'), RESULT, KILL_VP, END_READS_VP) + text, reason = translate(words) + check('accepts the permlane VGPR rewritten before it is read', text is not None and 'v3 = 0' in text, str(reason)) + for label, (source, words), fragment, model in refusals(): + text, reason = translate(words) + check('refuses %s, by name' % label, text is None and reason is not None and 'wave reduction' in reason + and fragment in reason, str(reason)) + model_run(label, source, model, [(1, 'v_max_u32')]) + # A uniform branch before the chain, after it, or both. The chain is the same shape; the branch does not + # enter it. The 32-lane model runs every line (the branch is not taken) and the readlane is still the reduction. + for where in ('before', 'after', 'both'): + for op in OPS: + if where != 'before' and op != 'v_max_u32': + continue # one operation carries the after and both placements; before covers all three + source, words = uniform_around(op, where) + label = 'uniform branch %s the %s chain' % (where, op) + decoded = [text for _o, _s, _n, text in G.decode(words)] + check('%s fixture decodes to its source' % label, decoded == source.splitlines(), str(decoded)) + check('%s is the reduction on the 32-lane model' % label, model_says_reduction(source, [(1, op)])) + text, reason = translate(words) + check('%s translates' % label, text is not None, str(reason)) + if text is None: + continue + body = body_of(text) + check('%s lowers to one %s' % (label, INTRINSIC[op]), + body.count('Wave') == 1 and 'v2 = %s;' % INTRINSIC[op] in body and 's1 = v2;' in body + and 'QuadRead' not in body, body) + # Reverted pass: the allowance is the branch guard. With the straight-line refusal put back, the same + # uniform-branch program is refused and the straight-line chain still lowers. A mutant that drops the + # intrinsic is not the lowering the fixture asks for. + source, words = uniform_around('v_max_u32', 'before') + text, reason = translate(words) + if text is not None: + mutant = text.replace(INTRINSIC['v_max_u32'], 'v1') + check('mutant replaces the wave reduction and is not the accepted lowering', + mutant != text and INTRINSIC['v_max_u32'] not in mutant and 'v2 = v1;' in mutant) + text, reason = straight_line_refusal(words) + check('reverted straight-line guard refuses a uniform branch before the chain', + text is None and reason is not None and 'program with branches' in reason, str(reason)) + text, reason = straight_line_refusal(uniform_around('v_max_u32', 'after')[1]) + check('reverted straight-line guard refuses a uniform branch after the chain', + text is None and reason is not None and 'program with branches' in reason, str(reason)) + text, reason = straight_line_refusal(fixture('v_max_u32')[1]) + check('reverted straight-line guard still lowers the straight-line chain', + text is not None and 'v2 = %s;' % INTRINSIC['v_max_u32'] in text, str(reason)) + # Each draw plant must change the translated program, except signed-for-unsigned on v_or_b32, which has no + # signed form. That includes the uniform-branch-after or draw, not only the straight-line or draw. + for label, words, input_op, channels in DRAWS: + text, reason = translate(words) + check('%s draw translates for the planted errors' % label, text is not None, str(reason)) + if text is None: + continue + single_op = channels[0] == ('reduce', input_op) and all(kind != 'lane' for kind, _arg in channels) + hows = ([(how, (lambda t, f=f, op=input_op: f(t, op))) for how, f in MUTATIONS.items()] + if single_op else list(PAIR_MUTATIONS.items())) + for how, mutate in hows: + changed = observed(mutate(text)) != observed(text) + expect = not (input_op == 'v_or_b32' and how == 'signed for unsigned') + check('%s %s %s the program' % (label, how, 'changes' if expect else 'leaves'), changed is expect) + # Not a chain: s_or_saveexec_b32 with -1 and no mirror or permlane after it keeps its own handler. + _source, words = program(START_MUL, [saveexec(0)], export('v1', 'v1', 'v1')) + text, reason = translate(words) + check('s_or_saveexec_b32 s0, -1 outside a chain keeps its handler', reason is None or 'wave reduction' not in reason, + str(reason)) + # A vertex stage, through a Stage probe: the hook needs only the instruction list and the program counter. + probe = G.Stage.__new__(G.Stage) + probe.lines, probe.sym, probe.blocks, probe.masks = [], {}, [], set() + probe.used_s, probe.used_v, probe.uniform_v = set(), set(), set() + probe.kind, probe.exec_known, probe.has_branches, probe.wqm_exec = 'vs', True, False, False + probe.ins = G.decode(fixture('v_max_u32')[1]) + probe.pc = probe.ins[1][0] + try: + probe.lower('s_or_saveexec_b32', 's_or_saveexec_b32 s0, -1', ['s0', '-1'], []) + reason = None + except G.Unsupported as error: + reason = str(error) + check('refuses a chain in a vertex stage, by name', reason is not None and 'outside a pixel stage' in reason, + str(reason)) + + +# ---- draw ------------------------------------------------------------------------------------------------------------- +OBSERVE = (' o.mrt0.w = asfloat(WaveGetLaneIndex() | (WaveGetLaneCount() << 8) |' + ' (WaveReadLaneFirst(uint(i.pos.x) | (uint(i.pos.y) << 5)) << 16));\n return o;') + + +def observed(text): + assert text.count(' return o;') == 1 + return text.replace(' return o;', OBSERVE) + + +def late_readlane(text): + """Planted error: the min chain's readlane lowered after the max chain's result (vT shared).""" + lines = text.split('\n') + moved = [ln for ln in lines if ln.strip() == 's1 = v2;'] + if len(moved) != 1: + return text + lines.remove(moved[0]) + at = [k for k, ln in enumerate(lines) if ln.strip() == 'v2 = WaveActiveMax(v1);'] + return '\n'.join(lines[:at[0] + 1] + moved + lines[at[0] + 1:]) if len(at) == 1 else text + + +def drop_sdwa(text): + """Planted error: the v_cndmask_b32_sdwa between the chains lowered as nothing (v6 keeps its old value).""" + lines = text.split('\n') + kept = [ln for ln in lines if not ln.strip().startswith('v6 = ')] + return '\n'.join(kept) if len(kept) == len(lines) - 1 else text + + +OTHER = {'v_or_b32': 'v_max_u32', 'v_min_u32': 'v_max_u32', 'v_max_u32': 'v_min_u32'} +MUTATIONS = { + 'another operation': lambda text, op: text.replace(INTRINSIC[op], INTRINSIC[OTHER[op]]), + 'signed for unsigned': lambda text, op: text.replace(INTRINSIC[op], INTRINSIC[op].replace( + '(v1)', '(int(v1))').replace('Wave', 'uint(Wave', 1) + ')') if op != 'v_or_b32' else text, + "the lane's own value": lambda text, op: text.replace(INTRINSIC[op], 'v1'), + "the first lane's value": lambda text, op: text.replace(INTRINSIC[op], 'WaveReadLaneFirst(v1)'), +} +PAIR_MUTATIONS = { + 'the min readlane after the max': late_readlane, + 'min and max swapped': lambda text: text.replace('WaveActiveMin', 'WaveActiveTmp').replace( + 'WaveActiveMax', 'WaveActiveMin').replace('WaveActiveTmp', 'WaveActiveMax'), + 'the v_cndmask_b32_sdwa dropped': drop_sdwa, +} + + +def single(op): + """Channels of a one-chain draw: the readlane result, the input, vT after the chain.""" + return op, (('reduce', op), ('input', None), ('reduce', op)) + + +def pair_sdwa(x, y): + value = word('v_min_u32', x, y) + return y if value > (x | (y << 16)) else value & 0xffff + + +DRAWS = [(op, fixture(op)[1]) + single(op) for op in OPS] + [ + ('min then max, interleaved', PAIR[1], 'v_min_u32', + (('reduce', 'v_min_u32'), ('lane', pair_sdwa), ('reduce', 'v_max_u32'))), + ('uniform branch before',) + (uniform_around('v_max_u32', 'before')[1],) + single('v_max_u32'), + ('uniform branch after',) + (uniform_around('v_or_b32', 'after')[1],) + single('v_or_b32'), +] + + +def verify(input_op, channels, words): + """Group the readback by desktop wave and compare with the CPU reference. Returns (errors, facts).""" + pixels = struct.unpack('<%dI' % (len(words) // 4), words) + groups, errors = collections.defaultdict(list), [] + for y in range(SIZE): + for x in range(SIZE): + p = pixels[(y * SIZE + x) * 4:(y * SIZE + x) * 4 + 4] + if p == (CLEAR,) * 4: + continue + groups[p[3] >> 16].append((x, y, p)) + counts = set() + for key, members in groups.items(): + lanes = [p[3] & 0xff for _x, _y, p in members] + counts.update((p[3] >> 8) & 0xff for _x, _y, p in members) + if len(set(lanes)) != len(lanes) or (key & 31, key >> 5) not in {(x, y) for x, y, _p in members}: + errors.append('wave %d: lanes %s do not name one wave' % (key, lanes)) + reduced = {} + for kind, op in channels: + if kind == 'reduce': + value = IDENTITY[op] + for x, y, _p in members: + value = apply(op, value, word(input_op, x, y)) + reduced[op] = value + for x, y, p in members: + expected = [reduced[arg] if kind == 'reduce' else word(input_op, x, y) if kind == 'input' else arg(x, y) + for kind, arg in channels] + if list(p[:3]) != expected: + errors.append('pixel (%d,%d): %s, reference %s over %d pixels of its wave' + % (x, y, ' / '.join('%08x' % w for w in p[:3]), + ' / '.join('%08x' % w for w in expected), len(members))) + covered = {(x, y) for members in groups.values() for x, y, _p in members} + quads = {(x // 2, y // 2) for x, y in covered} + partial_quads = sum(1 for qx, qy in quads + if sum((2 * qx + i, 2 * qy + j) in covered for i in (0, 1) for j in (0, 1)) < 4) + if len(counts) != 1: + errors.append('lane counts %s' % sorted(counts)) + lane_count = min(counts) if counts else 0 + facts = ('covered=%d waves=%d lane_count=%s partial_waves=%d partial_quads=%d' + % (len(covered), len(groups), '/'.join(map(str, sorted(counts))), + sum(1 for members in groups.values() if len(members) < lane_count), partial_quads)) + if partial_quads == 0 or len(covered) < 100: + errors.append('the draw does not exercise partly covered quads: ' + facts) + return errors, facts + + +def dump(renderer, adapter, vs, ps, out): + run = subprocess.run([renderer, adapter, '--startup-pixel-dump', str(vs), str(ps), str(SIZE), str(SIZE), str(out)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', TRIANGLE_VS, 'vs_dxc', 'vs_6_0', directory) + for label, words, input_op, channels in DRAWS: + text, reason = translate(words) + if text is None: + check('%s translates for the draw' % label, False, str(reason)) + continue + single_op = channels[0] == ('reduce', input_op) and all(kind != 'lane' for kind, _arg in channels) + if single_op: + hows = [(how, (lambda t, f=f, op=input_op: f(t, op))) for how, f in MUTATIONS.items()] + else: + hows = list(PAIR_MUTATIONS.items()) + for how, mutate in [(None, None)] + hows: + source = observed(text if how is None else mutate(text)) + if how is not None and source == observed(text): + if input_op == 'v_or_b32' and how == 'signed for unsigned': + continue # v_or_b32 has no signed form; the plant does not change the program + check('%s %s %s: the planted error applies' % (adapter, label, how), False) + continue + tag = re.sub(r'\W+', '_', label + ('' if how is None else '_' + how)) + ps = compile_hlsl(dxc, 'dxc', source, 'ps_' + tag, 'ps_6_0', directory) + out = directory / ('%s.bin' % tag) + run = dump(renderer, adapter, vs, ps, out) + if run.returncode != 0 or not out.exists(): + check('%s %s %s: draw' % (adapter, label, how or 'lowering'), False, run.stdout + run.stderr) + continue + errors, facts = verify(input_op, channels, out.read_bytes()) + clean = 'debug_layer=enabled' not in run.stdout or 'debug_errors=0 debug_warnings=0' in run.stdout + if how is None: + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() if ln.startswith( + ('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + print(' %s: %s' % (label, facts)) + check('%s %s: every covered pixel matches its desktop wave' % (adapter, label), + not errors and clean, '; '.join(errors[:3]) + ' ' + run.stdout) + else: + check('%s %s %s mutation fails against the reference: %s (%d pixels)' % ( + adapter, label, how, errors[0] if errors else '', len(errors)), bool(errors)) + + +def assemble_object(llvm_mc, source): + """The .text bytes of an object assembled by llvm-mc. -show-encoding prints a branch to a label with its offset + still a fixup ([A,A,0x88,0xbf]); the object has it resolved.""" + with tempfile.TemporaryDirectory() as tmp: + src, obj = Path(tmp) / 'a.s', Path(tmp) / 'a.o' + src.write_text(source) + subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-filetype=obj', str(src), '-o', str(obj)], + check=True) + elf = obj.read_bytes() + # ELF64 little endian: section headers at e_shoff, e_shentsize bytes each; e_shstrndx names them. + shoff, = struct.unpack_from('<Q', elf, 0x28) + shentsize, shnum, shstrndx = struct.unpack_from('<HHH', elf, 0x3a) + sections = [struct.unpack_from('<IIQQQQ', elf, shoff + k * shentsize) for k in range(shnum)] + names = sections[shstrndx][4] + for name, _type, _flags, _addr, offset, size in sections: + if elf[names + name:elf.index(b'\0', names + name)] == b'.text': + return elf[offset:offset + size] + raise AssertionError('no .text section in the object llvm-mc wrote') + + +def check_binary(llvm_mc): + programs = [('%s fixture' % op, fixture(op)) for op in OPS] + programs += [('min then max, interleaved, vT shared', PAIR), ('min then max, interleaved, vT apart', PAIR_SPLIT), + ('min then max, each read at once', PAIR_AT_ONCE), ('or, then min and max interleaved', SET)] + programs += [('uniform branch %s %s' % (where, op), uniform_around(op, where)) + for where in ('before', 'after', 'both') for op in OPS + if where == 'before' or op == 'v_max_u32'] + programs += [(label, prog) for label, prog, _f, _m in refusals()] + programs += [('bound_ctrl variant', program(START_MUL, chain('v_max_u32', bound_ctrl=True), RESULT, END)), + ('no fi variant', program(START_MUL, chain('v_max_u32', fi=False), RESULT, END)), + ('e32 combine variant', program(START_MUL, chain('v_max_u32', combine='e32'), RESULT, END)), + ('VOP3 combine variant', program(START_MUL, chain('v_max_u32', combine='e64'), RESULT, END)), + ('rewritten permlane VGPR', program(START_MUL, chain('v_max_u32'), RESULT, KILL_VP, END_READS_VP))] + for label, (source, words) in programs: + if 'label_' not in source: + built = assemble(llvm_mc, source) + else: # a branch: llvm-mc needs every label defined, at the word the fixture names + targets = {int(m, 16) for m in re.findall(r'label_((?:0x)?[0-9A-Fa-f]+)', source)} + out, offset = [], 0 + for text, size in zip(source.splitlines(), [n for _o, n, _name, _t in G.decode(words)]): + if offset in targets: + out.append('L%04X:' % offset) + out.append(re.sub(r'label_((?:0x)?[0-9A-Fa-f]+)', lambda m: 'L%04X' % int(m.group(1), 16), text)) + offset += size + built = assemble_object(llvm_mc, '\n'.join(out) + '\n') + check('llvm-mc assembles the program "%s" to the same words' % label, built == words, + built.hex() + ' / ' + words.hex()) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_hook_check.py b/tests/startup_hook_check.py new file mode 100644 index 0000000000..aaf8a7446c --- /dev/null +++ b/tests/startup_hook_check.py @@ -0,0 +1,236 @@ +"""Check that the startup debugger's function hooks see every concurrent call (#1281). + +usage: startup_hook_check.py the step-window bookkeeping + startup_hook_check.py <startup_launch_probe.exe> two threads through a hooked function + +A hook is one patched byte. While one thread steps over it the original byte is back, so a second +thread entering the function at that moment ran untraced. tools/startup/hook_window.py holds the +other threads for the step. The first form checks that bookkeeping with fake threads and needs no +Windows. The second runs the source-built probe, whose two threads open one file 32 times each, +entering CreateFileW together, under tools/startup/debug_launch.py: every one of the 64 opens must +appear in files.txt with its result, and the run reports no unprotected window. Control: +--suspend-others 0 must lose opens and say so. +""" +from pathlib import Path +import os +import re +import subprocess +import sys +import tempfile + +TOOLS = Path(__file__).resolve().parents[1] / "tools/startup" +sys.path.insert(0, str(TOOLS)) +from hook_window import FAILED, GONE, HELD, STILL_ACTIVE, STATUS_INVALID_HANDLE, STATUS_THREAD_IS_TERMINATING, ReturnBook, StepWindow, classify_hold, classify_status # noqa: E402 + +NAME = "x2w_hook_overlap.dat" +OPENS = 64 + + +def fakes(results=None): + log = {"held": [], "released": []} + results = results or {} + + def hold(tid): + result = results.get(tid, HELD) + if result == HELD: + log["held"].append(tid) + return result + + return log, hold, lambda tid: log["released"].append(tid) + + +def bookkeeping(): + # Every other thread is held before the step and resumed when the owner finishes; the owner never is. + log, hold, release = fakes() + window = StepWindow(hold, release) + window.open(1, [1, 2, 3], now=0) + assert log["held"] == [2, 3] and not window.defer(1) and window.defer(2) and window.deferred == 1 + assert not window.finish(2) and log["released"] == [], "only the owner closes a window" + assert window.finish(1) and sorted(log["released"]) == [2, 3] and not window.defer(2) + assert window.unprotected == 0 and window.timeouts == 0 + window.open(2, [1], now=1) # a closed window can be opened again + window.abandon() + + # A thread created during the step is held too; one that never joins the window is not. + log, hold, release = fakes() + window = StepWindow(hold, release) + window.hold(9) + assert log["held"] == [] + window.open(1, [2], now=0) + window.hold(9) + window.hold(9) + window.hold(1) + assert log["held"] == [2, 9] + window.finish(1) + assert sorted(log["released"]) == [2, 9] + + # A thread that is gone needs nothing; one that cannot be held leaves the window unprotected. + log, hold, release = fakes({2: GONE, 3: FAILED}) + window = StepWindow(hold, release) + window.open(1, [2, 3, 4], now=0) + assert log["held"] == [4] and window.unprotected == 1 + window.finish(1) + assert log["released"] == [4] + + # A window that outlives its limit is closed, resumed and counted, once. + log, hold, release = fakes() + window = StepWindow(hold, release, limit=2.0) + window.open(1, [2], now=10) + assert not window.expire(11.9) and log["released"] == [] + assert window.expire(12.0) and log["released"] == [2] + assert window.timeouts == 1 and window.unprotected == 1 + assert not window.expire(99) and not window.finish(1) and window.timeouts == 1 + + # With protection off nothing is held or deferred, and a window with company is reported. + log, hold, release = fakes() + window = StepWindow(hold, release, protect=False) + window.open(1, [2], now=0) + assert log["held"] == [] and not window.defer(2) and window.unprotected == 1 + window.finish(1) + window.open(1, [], now=0) + assert window.windows == 2 and window.unprotected == 1 + + # A thread that was not held and steps while a window is open does not take the window over: the + # owner keeps it, the held threads stay held until the owner is done, and the window is exposed. + log, hold, release = fakes({3: FAILED}) + window = StepWindow(hold, release) + window.open(1, [2, 3], now=0) + assert not window.defer(3), "a thread that is not held cannot be deferred" + window.open(3, [1, 2], now=0) + assert window.owner == 1 and window.unprotected == 1 and log["released"] == [] + assert not window.finish(3) and window.finish(1) and log["released"] == [2] + + returns_bookkeeping() + hold_outcomes() + + # The summary is always there, with zeros. + line = StepWindow(hold, release).summary(0) + assert line == "hook windows: entries=0 windows=0 unprotected=0 deferred=0 timeouts=0 protection=on", line + + +def hold_outcomes(): + """A thread that called ExitThread but whose EXIT_THREAD event is not read yet cannot be suspended + (access denied). It runs no code, so it is GONE; the same failure on a live thread is FAILED.""" + access_denied = 5 + assert classify_hold(0, signaled=False) == GONE, "exited with code 0" + assert classify_hold(STILL_ACTIVE + 1) == GONE + assert classify_hold(STILL_ACTIVE, signaled=True) == GONE, "exit code not stored yet, handle signaled" + assert classify_hold(None, error=87) == GONE, "no such thread" + assert classify_hold(STILL_ACTIVE) == FAILED, "alive and not suspendable: a real hole" + assert classify_hold(None, error=access_denied) == FAILED, "exit code unknown: not assumed gone" + assert classify_status(STATUS_THREAD_IS_TERMINATING) == GONE, "exiting thread, exit code still 259" + assert classify_status(STATUS_INVALID_HANDLE) == GONE + assert classify_status(0xC0000022) == FAILED, "access denied: not assumed gone" + # The window counts a gone thread as nothing and a live unsuspendable one as unprotected. + for outcome, unprotected in ((classify_hold(0), 0), (classify_status(STATUS_THREAD_IS_TERMINATING), 0), + (classify_hold(STILL_ACTIVE), 1)): + log, hold, release = fakes({2: outcome}) + window = StepWindow(hold, release) + window.open(1, [2, 3], now=0) + assert window.unprotected == unprotected and log["held"] == [3] + window.finish(1) + + +def traced_returns(retrapped): + """Two threads call from fixed stack slots, 32 calls each. A call in `retrapped` hits its entry + hook twice: another thread re-patched the byte before this one ran the original instruction, so + the same call is registered again. Returns how many lines the book writes for the 64 calls.""" + book, lines = ReturnBook(), 0 + for call in range(32): + for tid in (1, 2): + for _ in range(2 if (call, tid) in retrapped else 1): + book.add(0x7000, tid, 0x1000 * tid, f"NtCreateFile call {call}", 0x5000) + lines += len(book.take(0x7000, tid, 0x1000 * tid)) + return lines + + +def returns_bookkeeping(): + # One call is traced once however many times its entry trapped: a run showed "88 of 64". + retrapped = {(call, 1) for call in range(0, 32, 4)} | {(call, 2) for call in range(0, 32, 4)} \ + | {(call, 1) for call in range(1, 32, 4)} + assert len(retrapped) == 24 + assert traced_returns(set()) == 64 + assert traced_returns(retrapped) == 64, traced_returns(retrapped) + book = ReturnBook() + book.add(0x10, 1, 0x100, "a", 0x5000) + book.add(0x10, 2, 0x100, "b", 0x5000) # same slot value on another thread is another call + assert book.take(0x10, 1, 0x100) == ["a"] and book.take(0x10, 1, 0x100) == [] + assert book.take(0x10, 2, 0x100) == ["b"] and book.take(0x99, 2, 0x100) == [] + + # Tail-calling another hooked function shares (tid, slot) with a different entry address: + # both return records stay, while a re-trap of the same entry replaces only that entry. + book.add(0x20, 1, 0x200, "CreateFileW", 0x5000) + book.add(0x20, 1, 0x200, "NtCreateFile first", 0x6000) + book.add(0x20, 1, 0x200, "NtCreateFile retrapped", 0x6000) + assert book.take(0x20, 1, 0x200) == ["CreateFileW", "NtCreateFile retrapped"] + assert book.take(0x20, 1, 0x200) == [] + + # A restore callback runs once, when its call returns, and only for that call. + undone = [] + book.add(0x40, 1, 0x400, "mapped", 0x5000, restore=lambda: undone.append("first")) + book.add(0x40, 2, 0x400, "other thread", 0x5000, restore=lambda: undone.append("second")) + assert book.take(0x40, 1, 0x400) == ["mapped"] and undone == ["first"] + assert book.take(0x40, 1, 0x400) == [] and undone == ["first"], "a restore must not run twice" + # A re-trap of the same call keeps the first restore (the caller's original state). + book.add(0x50, 1, 0x500, "x", 0x5000, restore=lambda: undone.append("original")) + book.add(0x50, 1, 0x500, "x", 0x5000, restore=lambda: undone.append("rewritten twice")) + book.take(0x50, 1, 0x500) + assert undone == ["first", "second"][:1] + ["original"], undone + assert book.take(0x40, 2, 0x400) == ["other thread"] and undone[-1] == "second" + + # The launcher asks whether any call still returns to an address before it lets a hit-limited + # breakpoint run free: a returned call must not keep it armed, a waiting one must. + assert not book.pending(0x20) and not book.pending(0x99) + book.add(0x30, 1, 0x300, "waiting", 0x5000) + assert book.pending(0x30) + book.take(0x30, 1, 0x300) + assert not book.pending(0x30) + + +def run(probe, scratch, name, options): + logdir = scratch / name + data = scratch / NAME + data.write_bytes(b"x2w") + env = {k: v for k, v in os.environ.items() if not k.startswith("X2W_")} + env.update(X2W_LAUNCH_PROBE_MODE="overlap", X2W_LAUNCH_PROBE_FILE=str(data)) + command = [sys.executable, "-B", str(TOOLS / "debug_launch.py"), str(probe), str(scratch), str(logdir), + "--timeout", "60", "--console", "0", "--trace-files", "1", "--continue-asserts", "0", *options] + result = subprocess.run(command, capture_output=True, text=True, timeout=180, env=env) + files = (logdir / "files.txt").read_text(encoding="utf-8", errors="replace") + traced = sum(1 for line in files.splitlines() + if " NtCreateFile " in line and NAME in line.lower() and line.endswith("-> 0x00000000")) + stdout = (logdir / "stdout.txt").read_text(encoding="utf-8", errors="replace") + summary = re.search(r"hook windows: entries=\d+ windows=(\d+) unprotected=(\d+) deferred=\d+ timeouts=(\d+) " + r"protection=(on|off)", result.stdout + files) + assert summary, (result.returncode, result.stdout, result.stderr[-2000:]) + return traced, stdout, [int(summary.group(i)) for i in (1, 2, 3)], summary.group(4) + + +def launcher(probe, scratch): + for attempt in range(3): + traced, stdout, (windows, unprotected, timeouts), protection = run(probe, scratch, f"held{attempt}", []) + assert "overlap opens 64 of 64" in stdout, stdout + assert traced == OPENS, f"attempt {attempt}: {traced} of {OPENS} opens traced (more than made means double counting)" + assert windows >= OPENS and unprotected == 0 and timeouts == 0 and protection == "on", (windows, unprotected, timeouts) + # Control: without holding the other thread the same run loses opens, and the report says so. + for attempt in range(8): + traced, stdout, (windows, unprotected, timeouts), protection = run(probe, scratch, f"free{attempt}", + ["--suspend-others", "0"]) + assert "overlap opens 64 of 64" in stdout, stdout + assert protection == "off" + assert traced <= OPENS, f"control attempt {attempt}: {traced} traces for {OPENS} opens: a call was counted twice" + lost = max(0, OPENS - traced) + if lost: + assert unprotected > 0, "opens were lost but the run reported no unprotected window" + return lost + raise AssertionError(f"the control never lost an open in 8 runs: the overlap was not exercised ({traced} of {OPENS})") + + +if __name__ == "__main__": + bookkeeping() + if len(sys.argv) == 1: + print("startup_hook_window: PASS (hold, defer, finish, new thread, gone/failed thread, deadline, protection off, summary)") + sys.exit(0) + with tempfile.TemporaryDirectory() as temporary: + lost = launcher(Path(sys.argv[1]).resolve(), Path(temporary)) + print(f"startup_hook_overlap: PASS ({OPENS} of {OPENS} opens traced with the window; control lost {lost})") diff --git a/tests/startup_image_2d_array_check.py b/tests/startup_image_2d_array_check.py index 4aaf0edc88..728971b38a 100644 --- a/tests/startup_image_2d_array_check.py +++ b/tests/startup_image_2d_array_check.py @@ -24,7 +24,7 @@ of a slice (root constant 1) at a constant mip level. They are drawn with --startup-image-2d-array-mips: a 4x4 texture of two slices with three mip levels whose cells all differ, texel (x, y) of slice s at mip m holding ((1 + x + 4y + 16s + 32m) / 128, x, y, s + 2m). The expected colours come from mip_cell() below. -Cube maps stay refused. The mip fixtures use spellings that llvm-mc 19 assembles; LLVM 15 is not known to +Cube loads stay refused (cube sampling: tests/startup_image_cube_check.py). The mip fixtures use spellings that llvm-mc 19 assembles; LLVM 15 is not known to accept them, so 'binary <llvm-mc> mip' is opt-in and CI does not pass it. """ import re @@ -261,7 +261,7 @@ def mip_controls(): G.D.MIMG_DIMS[5] = original assert G.D.MIMG_DIMS[5] == original - # Cube maps are refused as before. 2D and 3D keep their forms (same words, dim field changed). + # Cube loads are refused as before. 2D and 3D keep their forms (same words, dim field changed). cube = bytearray(MIP_IMAGE) cube[0] = 0x18 try: diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 6c0070de66..be18b7e5b7 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -26,21 +26,24 @@ using Microsoft::WRL::ComPtr; namespace { constexpr UINT entry_constants = 4; // ud0..ud3 of the fixture's manifest constexpr UINT side = 2; -// The mip fixture: a 4x4 array of two slices with three mip levels (4x4, 2x2, 1x1). -constexpr UINT mip_base = 4; constexpr UINT max_levels = 3; +// A cube fixture: six 4x4 faces, one level (dim:SQ_RSRC_IMG_CUBE, #2943). +constexpr UINT cube_faces = 6; +constexpr UINT cube_side = 4; // The value at texel (x, y) of slice s and mip level m. One level keeps the 2x2x2 fixture's values. With // several levels every (slice, mip, x, y) cell is distinct: the red channel is a dyadic fraction and // alpha is s + 2m, so exchanging slice and mip, or reading another level, changes the colour. -void texel_value(UINT x, UINT y, UINT s, UINT m, UINT levels, float out[4]) +void texel_value(UINT x, UINT y, UINT s, UINT m, UINT levels, UINT base, float out[4]) { if (levels == 1) { const float one[4] = {(1.0f + x + 2.0f * y + 4.0f * s) / 8.0f, float(x), float(y), float(s)}; std::memcpy(out, one, sizeof(one)); return; } - const float many[4] = {(1.0f + x + 4.0f * y + 16.0f * s + 32.0f * m) / 128.0f, float(x), float(y), float(s + 2 * m)}; + const UINT area = base * base; + const float red = float(1 + x + base * y + area * (s + 2 * m)) / float(8 * area); + const float many[4] = {red, float(x), float(y), float(s + 2 * m)}; std::memcpy(out, many, sizeof(many)); } @@ -64,22 +67,40 @@ ComPtr<ID3D12RootSignature> create_root(ID3D12Device* device, const x2w_startup: // array: the same eight texels as two slices of a 2D array (dim:SQ_RSRC_IMG_2D_ARRAY); the default // view of a two-slice texture is a Texture2DArray over both. Multi-mip fixtures use a 4x4 base. -// A nonzero view_levels selects an explicit 2D SRV starting at first_mip. When sampler_line is a +// A nonzero view_levels selects an explicit 2D or 2D-array SRV starting at first_mip. When sampler_line is a // comparison sampler (smpc), the texture uses DXGI_FORMAT_R32_FLOAT holding the red channel as depth. void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array, UINT levels, bool one_dimensional, - bool two_dimensional, UINT first_mip, UINT view_levels) + bool two_dimensional, UINT first_mip, UINT view_levels, UINT mip_base, bool cube) { - if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional)) + if (cube && (levels != 1 || array || one_dimensional || two_dimensional || view_levels)) + throw std::runtime_error("A cube image fixture has one level and no other layout"); + if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional && !one_dimensional)) throw std::runtime_error("Unsupported image mip level count"); - if (view_levels && (!two_dimensional || first_mip >= levels || view_levels > levels - first_mip)) + if (view_levels && ((!two_dimensional && !array) || first_mip >= levels || view_levels > levels - first_mip)) throw std::runtime_error("2D mip window exceeds the resource"); - const UINT base = levels > 1 ? mip_base : side; + const UINT base = cube ? cube_side : (levels > 1 ? mip_base : side); const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); x2w_startup::TranslatedSamplers samplers; - if (!samplers.read_manifest_line(sampler_line) || samplers.statics.size() != 1) - throw std::runtime_error("Expected one inline sampler in the image 3D draw"); + const char* newline = std::strchr(sampler_line, '\n'); + if (!newline) { + if (!samplers.read_manifest_line(sampler_line) || samplers.statics.size() != 1) + throw std::runtime_error("Expected one inline sampler in the image 3D draw"); + } else { + const std::string first(sampler_line, newline); + const char* second = newline + 1; + int first_index = -1, second_index = -1; + if (!two_dimensional || !view_levels || std::strchr(second, '\n') || + (std::sscanf(first.c_str(), "smp %d", &first_index) != 1 && + std::sscanf(first.c_str(), "smpl %d", &first_index) != 1) || + (std::sscanf(second, "smp %d", &second_index) != 1 && + std::sscanf(second, "smpl %d", &second_index) != 1) || + first_index != 0 || second_index != 1 || + !samplers.read_manifest_line(first.c_str()) || !samplers.read_manifest_line(second) || + samplers.statics.size() != 2 || samplers.heap || samplers.comparison[0] || samplers.comparison[1]) + throw std::runtime_error("Expected two ordered noncomparison inline samplers in the 2D view draw"); + } const bool comparison = !samplers.comparison.empty() && samplers.comparison[0]; const auto root = create_root(device, samplers); @@ -101,19 +122,19 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const D3D12_RESOURCE_DESC td{}; td.Dimension = one_dimensional ? D3D12_RESOURCE_DIMENSION_TEXTURE1D - : (array || two_dimensional) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D + : (array || two_dimensional || cube) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; td.Width = base; td.Height = one_dimensional ? 1 : base; - td.DepthOrArraySize = (one_dimensional || two_dimensional) ? 1 : side; + td.DepthOrArraySize = cube ? cube_faces : (one_dimensional || two_dimensional) ? 1 : side; td.MipLevels = levels; td.Format = comparison ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32G32B32A32_FLOAT; td.SampleDesc.Count = 1; const auto texture = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); // A volume is one subresource of two slices; an array is two subresources of one slice each. // The subresource of slice s and mip m is m + s * levels. - const UINT subresources = (array ? side : 1) * levels; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[side * max_levels]{}; + const UINT subresources = (cube ? cube_faces : array ? side : 1) * levels; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[cube_faces * max_levels]{}; UINT64 upload_size = 0; device->GetCopyableFootprints(&td, 0, subresources, 0, footprints, nullptr, nullptr, &upload_size); const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint = footprints[0]; @@ -126,13 +147,18 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const for (UINT tz = 0; tz < td.DepthOrArraySize; ++tz) for (UINT level = 0; level < levels; ++level) { const UINT extent = base >> level; - const auto& place = footprints[level + (array ? tz * levels : 0)]; + const auto& place = footprints[level + ((array || cube) ? tz * levels : 0)]; for (UINT ty = 0; ty < (one_dimensional ? 1u : extent); ++ty) for (UINT tx = 0; tx < extent; ++tx) { float texel[4]; - texel_value(tx, ty, tz, level, levels, texel); + texel_value(tx, ty, tz, level, levels, base, texel); if (one_dimensional) texel[3] = tx ? 0.75f : 0.5f; - auto* const slice = array ? start + place.Offset : start + place.Offset + tz * slice_pitch; + if (cube) { + // Every one of the 96 texels differs: face f, column tx and row ty. + const float face[4] = {(1.0f + tx + 4.0f * ty + 16.0f * tz) / 128.0f, float(tx), float(ty), float(tz)}; + std::memcpy(texel, face, sizeof(face)); + } + auto* const slice = (array || cube) ? start + place.Offset : start + place.Offset + tz * slice_pitch; const UINT texel_bytes = comparison ? sizeof(float) : sizeof(texel); std::memcpy(slice + ty * place.Footprint.RowPitch + tx * texel_bytes, texel, texel_bytes); } @@ -161,12 +187,26 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const D3D12_SHADER_RESOURCE_VIEW_DESC view{}; if (view_levels) { view.Format = td.Format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + if (array) { + view.Texture2DArray.MostDetailedMip = first_mip; + view.Texture2DArray.MipLevels = view_levels; + view.Texture2DArray.ArraySize = td.DepthOrArraySize; + } else { + view.Texture2D.MostDetailedMip = first_mip; + view.Texture2D.MipLevels = view_levels; + } + } + if (cube) { + view.Format = td.Format; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MostDetailedMip = first_mip; - view.Texture2D.MipLevels = view_levels; + view.TextureCube.MostDetailedMip = 0; + view.TextureCube.MipLevels = 1; } - device->CreateShaderResourceView(texture.Get(), view_levels ? &view : nullptr, views->GetCPUDescriptorHandleForHeapStart()); + device->CreateShaderResourceView(texture.Get(), (view_levels || cube) ? &view : nullptr, + views->GetCPUDescriptorHandleForHeapStart()); hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create image 3D RTV heap"); const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); @@ -211,7 +251,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const std::memcpy(color, static_cast<std::uint8_t*>(mapped) + target_footprint.Offset, 4 * sizeof(float)); readback->Unmap(0, &none); std::printf("startup_image_%s z=%g color=(%g, %g, %g, %g)\n", - one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", + cube ? "cube" : one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", z, color[0], color[1], color[2], color[3]); } diff --git a/tests/startup_image_3d_check.py b/tests/startup_image_3d_check.py index 0cfc30d79e..bcc2ed62ea 100644 --- a/tests/startup_image_3d_check.py +++ b/tests/startup_image_3d_check.py @@ -107,11 +107,16 @@ def controls(): assert 'Texture1D<float4> r0' in pipe.hlsl_ps() assert 'r0.Sample(q0, F(v0))' in pipe.hlsl_ps() assert 'srv 0 tex1d table 0 0' in pipe.manifest() - unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0')) + # The MIMG words carry no address count: the disassembler sizes the address from the dimension. With the cube + # dimension (field 3) the same words are a three-register cube sample, translated since #2943; the 2D MSAA + # dimension (field 6) stays an unverified dimension and must be refused. + cube = translate(WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0'))).hlsl_ps() + assert 'TextureCube<float4> r0' in cube and 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))' in cube, cube + unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('300f80f0')) try: translate(unsupported) - except G.Unsupported: - pass + except G.Unsupported as error: + assert 'image dimension SQ_RSRC_IMG_2D_MSAA' in str(error), error else: raise AssertionError('unverified image dimension accepted') diff --git a/tests/startup_image_cube_check.py b/tests/startup_image_cube_check.py new file mode 100644 index 0000000000..b507e313a3 --- /dev/null +++ b/tests/startup_image_cube_check.py @@ -0,0 +1,393 @@ +"""Cube images in tools/startup/gfx2hlsl.py (dim:SQ_RSRC_IMG_CUBE, #2943). + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble the fixture sources and compare them with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> + translate, compile (DXC ps_6_0) and draw against a six-face TextureCube + +A gfx10 cube sample addresses the face coordinates s and t and then the face id. Mesa's prepare_cube_coords +(src/amd/common/nir/ac_nir_lower_tex.c) builds s = sc/|ma| + 1.5 and t = tc/|ma| + 1.5 from v_cubesc, v_cubetc +and v_cubema, and LLVM's ConstantFoldAMDGCNCubeIntrinsic defines v_cubema as twice the major coordinate, so s and +t lie in [1, 2] and s - 1, t - 1 are the position on the face. The translator rebuilds a direction from (s, t, +face) for TextureCube (x2w_cube_dir in the HLSL). + +tests/startup_image_3d.cpp, run as --startup-image-cube, binds six 4x4 R32G32B32A32_FLOAT faces as a TextureCube +whose texel (x, y) of face f holds ((1 + x + 4y + 16f) / 128, x, y, f), so all 96 texels differ. The sampler is the +all-zero inline sampler (point, wrap); every (s, t) is a texel centre (in {1.125, 1.375, 1.625, 1.875}). + +What the draws show: the literal cases feed (s, t, face) directly, without v_cube, and the reference is only the +address meaning above (x = floor(4 * (s - 1)), y = floor(4 * (t - 1))). The desktop driver selects the +face of the rebuilt direction itself, so a wrong face, sign, axis or 2.0 * (s - 1.5) / 2.0 * (t - 1.5) scale in +x2w_cube_dir reads another texel. The mutants edit one row of the emitted helper (sign of the u term flipped, u and v +exchanged, faces 2 and 3 exchanged, and dropping the 2.0 * scale on u or v) and must read the texel a D3D cube +lookup of the mutated direction gives. The end-to-end cases run the v_cube chain on six directions and must equal +both that reference and a desktop PS that samples the direction. +They do not show that the console's face order and orientation equal D3D's: that rests on LLVM's cube table +being the D3D11.3 cube face table. Only one mip is bound, so LOD and bias values are not tested; the image_sample_l +and image_sample_b draws only show that the extra address dword is not taken as a coordinate. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 + +INLINE_FLOATS = {0.0: 128, 0.5: 240, -0.5: 241, 1.0: 242, -1.0: 243, 2.0: 244, -2.0: 245, 4.0: 246, -4.0: 247} +PROLOGUE = bytes.fromhex('04040cf4000000fa' '800398be' '800399be' '80039abe' '80039bbe') +PROLOGUE_SOURCE = """\ +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0 +s_mov_b32 s27, 0 +""" +EPILOGUE = bytes.fromhex('703f8cbf' '0f1800f800010203' '000081bf') +EPILOGUE_SOURCE = """\ +s_waitcnt vmcnt(0) +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm +""" +WAIT = bytes.fromhex('7fc08cbf') +# First and second dword of each MIMG form on dim:SQ_RSRC_IMG_CUBE (field value 3), vdata v[0:3], vaddr v0, +# s[16:23] and s[24:27]; recorded from LLVM 15. +MIMG = { + 'sample': ('image_sample v[0:3], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f80f00000c400'), + 'lz': ('image_sample_lz v[0:3], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f9cf00000c400'), + 'l': ('image_sample_l v[0:3], v[0:3], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f90f00000c400'), + 'b': ('image_sample_b v[0:3], v[0:3], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f94f00000c400'), +} + + +def bits(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def v_mov(dst, value): + """v_mov_b32 vdst, value: an inline constant where LLVM uses one, else a literal.""" + if value in INLINE_FLOATS: + return struct.pack('<I', 0x7e000200 | dst << 17 | INLINE_FLOATS[value]), 'v_mov_b32 v%d, %s' % (dst, value) + return (struct.pack('<I', 0x7e0002ff | dst << 17) + struct.pack('<I', bits(value)), + 'v_mov_b32 v%d, 0x%08x' % (dst, bits(value))) + + +# image_sample_b needs a sampler with mipmapping (word 2 mip filter 1) and MAX_LOD 2 (word 1), as in +# startup_image_sample_b_check.py SAMPLER; only one mip is bound, so neither changes the texel. +B_SAMPLER = bytes.fromhex('04040cf4000000fa' '800398be' 'ff0399be00002000' 'ff039abe00000004' '80039bbe') +B_SAMPLER_SOURCE = PROLOGUE_SOURCE.replace('s_mov_b32 s25, 0', 's_mov_b32 s25, 0x200000').replace( + 's_mov_b32 s26, 0', 's_mov_b32 s26, 0x4000000') + + +def program(moves, form='lz', middle=b'', middle_source=''): + """The prologue, the given v_mov constants, an optional middle part, one cube sample and the export.""" + words, source = (bytearray(B_SAMPLER), B_SAMPLER_SOURCE) if form == 'b' else (bytearray(PROLOGUE), PROLOGUE_SOURCE) + for dst, value in moves: + w, s = v_mov(dst, value) + words += w + source += s + '\n' + words += middle + source += middle_source + text, mimg = MIMG[form] + words += WAIT + bytes.fromhex(mimg) + EPILOGUE + source += 's_waitcnt lgkmcnt(0)\n' + text + '\n' + EPILOGUE_SOURCE + return bytes(words), source + + +def texel(x, y, face): + return ','.join('%08x' % bits(c) for c in ((1 + x + 4 * y + 16 * face) / 128, x, y, face)) + + +def address_texel(s, t, face): + """The AMD cube address meaning: face-local position s - 1 and t - 1 on a 4x4 face.""" + return (min(3, max(0, int((s - 1.0) * 4))), min(3, max(0, int((t - 1.0) * 4))), face) + + +# The per-face (sc, tc) of v_cubesc and v_cubetc (LLVM ConstantFoldAMDGCNCubeIntrinsic), used here to model a D3D +# TextureCube lookup of a direction; LLVM's table is the D3D11.3 face table. +def cube_lookup(d): + x, y, z = d + ax, ay, az = abs(x), abs(y), abs(z) + if az >= ax and az >= ay: + face, sc, tc, ma = (5, -x, -y, z) if z < 0 else (4, x, -y, z) + elif ay >= ax: + face, sc, tc, ma = (3, x, -z, y) if y < 0 else (2, x, z, y) + else: + face, sc, tc, ma = (1, z, -y, x) if x < 0 else (0, -z, -y, x) + inv = 1.0 / abs(2 * ma) + return address_texel(sc * inv + 1.5, tc * inv + 1.5, face) + + +# The emitted helper rows, face 0 to 5, as (x, y, z) expressions in u and v. +ROWS = [('1.0', '-v', '-u'), ('-1.0', '-v', 'u'), ('u', '1.0', 'v'), ('u', '-1.0', '-v'), ('u', '-v', '1.0'), + ('-u', '-v', '-1.0')] + + +def row_line(face, row): + body = 'return float3(%s, %s, %s);' % row + return body if face == 5 else 'if (k == %d) %s' % (face, body) + + +def helper_dir(rows, s, t, face, su=2.0, sv=2.0): + u, v = su * (s - 1.5), sv * (t - 1.5) + return tuple(eval(c, {}, {'u': u, 'v': v}) for c in rows[face]) # noqa: S307 (fixed expressions above) + + +def flip_u(row): + return tuple(c.replace('-u', '#').replace('u', '-u').replace('#', 'u') for c in row) + + +def swap_uv(row): + return tuple(c.replace('u', '#').replace('v', 'u').replace('#', 'v') for c in row) + + +def mutants(): + """(label, edits [(old line, new line)], mutated rows, (su, sv)).""" + out = [] + for face in range(6): + for label, change in (('u sign flipped', flip_u), ('u and v exchanged', swap_uv)): + rows = list(ROWS) + rows[face] = change(ROWS[face]) + out.append(('face %d %s' % (face, label), [(row_line(face, ROWS[face]), row_line(face, rows[face]))], + rows, (2.0, 2.0))) + rows = list(ROWS) + rows[2], rows[3] = ROWS[3], ROWS[2] + out.append(('faces 2 and 3 exchanged', [(row_line(2, ROWS[2]), row_line(2, ROWS[3])), + (row_line(3, ROWS[3]), row_line(3, ROWS[2]))], rows, (2.0, 2.0))) + out.append(('u scale 2 dropped', [('clamp(2.0 * (s - 1.5), -1.0, 1.0)', 'clamp((s - 1.5), -1.0, 1.0)')], + ROWS, (1.0, 2.0))) + out.append(('v scale 2 dropped', [('clamp(2.0 * (t - 1.5), -1.0, 1.0)', 'clamp((t - 1.5), -1.0, 1.0)')], + ROWS, (2.0, 1.0))) + return out + + +# Literal (s, t, face) cases: outer-ring 4x4 texel centres so every face has x != y and dropping scale 2 moves texels. +CASES = [(1.125, 1.875, 0), (1.875, 1.125, 1), (1.125, 1.875, 2), (1.875, 1.125, 3), (1.875, 1.125, 4), (1.125, 1.875, 5), + (1.875, 1.875, 2)] +# End-to-end directions, one per face, each on a 4x4 texel centre with x != y. +DIRECTIONS = [(1.0, -0.75, 0.25), (-1.0, -0.75, -0.25), (0.75, 1.0, -0.25), (0.75, -1.0, 0.25), (0.75, 0.25, 1.0), + (-0.75, 0.25, -1.0)] +CHAIN_SOURCE = """\ +v_cubema_f32 v7, v4, v5, v6 +v_cubesc_f32 v8, v4, v5, v6 +v_cubetc_f32 v9, v4, v5, v6 +v_cubeid_f32 v2, v4, v5, v6 +v_rcp_f32_e64 v7, |v7| +v_mov_b32 v10, 0x3fc00000 +v_fma_f32 v0, v8, v7, v10 +v_fma_f32 v1, v9, v7, v10 +""" +CHAIN = bytes.fromhex('070047d5040b1a04' '080045d5040b1a04' '090046d5040b1a04' '020044d5040b1a04' + '0701aad507010000' 'ff02147e0000c03f' '00004bd5080f2a04' '01004bd5090f2a04') + + +def literal_program(s, t, face, form='lz'): + if form in ('lz', 'sample'): + return program([(0, s), (1, t), (2, float(face))], form) + if form == 'l': + return program([(0, s), (1, t), (2, float(face)), (3, 0.0)], form) + return program([(0, 0.0), (1, s), (2, t), (3, float(face))], form) # b: bias first + + +def chain_program(d): + return program([(4, d[0]), (5, d[1]), (6, d[2])], 'lz', CHAIN, CHAIN_SOURCE) + + +def desktop_ps(d): + return ('TextureCube<float4> r0 : register(t0);\nSamplerState q0 : register(s0);\n' + 'float4 main() : SV_Target { return r0.SampleLevel(q0, float3(%r, %r, %r), 0); }\n' % d) + + +def translate(words): + return G.Pipeline(VS_WORDS, words, root_blob()) + + +def expect_refused(call, needle): + try: + call() + except G.Unsupported as error: + assert needle in str(error), (needle, str(error)) + return str(error) + raise AssertionError('accepted, expected refusal containing %r' % needle) + + +def bare_image(how, mods, kind='ps'): + stage = G.Stage.__new__(G.Stage) + stage.kind = kind + return lambda: stage.image(['v[0:3]', 'v[0:2]', 's[16:23]', 's[24:27]'], mods, how) + + +def model_controls(): + values = {texel(x, y, f) for f in range(6) for y in range(4) for x in range(4)} + assert len(values) == 96, len(values) + for s, t, face in CASES: + # The helper rebuilds a direction that a D3D lookup maps back to the address texel. + assert cube_lookup(helper_dir(ROWS, s, t, face)) == address_texel(s, t, face), (s, t, face) + assert {f for s, t, f in CASES if address_texel(s, t, f)[0] != address_texel(s, t, f)[1]} == set(range(6)) + for d in DIRECTIONS: + x, y, face = cube_lookup(d) + assert x != y, d + assert sorted(cube_lookup(d)[2] for d in DIRECTIONS) == list(range(6)) + for label, _, rows, scale in mutants(): + assert any(cube_lookup(helper_dir(rows, s, t, f, *scale)) != address_texel(s, t, f) + for s, t, f in CASES), label + print('model: 96 distinct texels; helper rows invert a D3D lookup on %d cases; %d mutants each change a case' + % (len(CASES), len(mutants()))) + + +def controls(): + model_controls() + words, _ = literal_program(1.875, 1.125, 1) + pipe = translate(words) + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + assert 'TextureCube<float4> r0 : register(t0);' in ps and 'Texture2DArray' not in ps, ps + assert 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), 0)' in ps, ps + assert 'float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);' in ps, ps + assert 'float v = clamp(2.0 * (t - 1.5), -1.0, 1.0);' in ps, ps + for face, row in enumerate(ROWS): + assert row_line(face, row) in ps, (face, ps) + assert ps.count('float3 x2w_cube_dir(') == 1, ps + assert 'srv 0 texcube table 0 0' in manifest.splitlines(), manifest + for form, call in (('sample', 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))'), + ('l', 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))'), + ('b', 'r0.SampleBias(q0, x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))')): + ps = translate(literal_program(1.875, 1.125, 1, form)[0]).hlsl_ps() + assert call in ps, (form, ps) + # Other dimensions keep their declarations and calls. + from startup_image_2d_array_check import SAMPLE_WORDS, SAMPLE_CALL # noqa: E402 + ps = translate(SAMPLE_WORDS).hlsl_ps() + assert SAMPLE_CALL in ps and 'x2w_cube_dir' not in ps and 'TextureCube' not in ps, ps + print('translation: TextureCube r0 with x2w_cube_dir for sample, lz, l and b; manifest srv 0 texcube') + refusals = [ + (bare_image('load', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image dimension SQ_RSRC_IMG_CUBE: Load'), + (bare_image('load_mip', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image dimension SQ_RSRC_IMG_CUBE: Load'), + (bare_image('d', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image_sample_d on SQ_RSRC_IMG_CUBE'), + (bare_image('get_lod', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0x3']), 'image_get_lod on SQ_RSRC_IMG_CUBE'), + (bare_image('lz', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf', 'a16']), 'image_sample_lz on SQ_RSRC_IMG_CUBE with a16'), + (bare_image('sample', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf', 'd16']), + 'image_sample on SQ_RSRC_IMG_CUBE with d16'), + (bare_image('l', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf'], kind='cs'), 'cube image in a compute program'), + ] + for call, needle in refusals: + expect_refused(call, needle) + # A constant sampler with DISABLE_CUBE_WRAP (word 0 bit 28) is refused; the bit clear is accepted above. + wrap = bytes.fromhex('ff0398be00000010') + words = literal_program(1.75, 1.25, 1)[0].replace(bytes.fromhex('800398be'), wrap, 1) + expect_refused(lambda: translate(words), 'DISABLE_CUBE_WRAP') + print('refused: cube load and load_mip, sample_d, get_lod, a16, d16, compute, DISABLE_CUBE_WRAP') + + +def check_binary(llvm_mc): + fixtures = [('literal %s' % (case,), *reversed(literal_program(*case))) for case in CASES] + fixtures += [('%s' % form, *reversed(literal_program(1.875, 1.125, 1, form))) for form in ('sample', 'l', 'b')] + fixtures += [('chain %s' % (d,), *reversed(chain_program(d))) for d in DIRECTIONS] + for name, source, words in fixtures: + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), words.hex())) + print('fixture words match llvm-mc (%d programs)' % len(fixtures)) + + +def check_draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + count = [0, 0] # reference draws that matched, controls and mutants that failed as predicted + + def draw(shader, expected, label, fail_reads=None, sampler=None): + run = subprocess.run([renderer, adapter, '--startup-image-cube', str(vs), str(shader), '0', expected] + + ([sampler] if sampler else []), capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if not any(count): + for line in run.stdout.splitlines(): + if line.startswith(('backend=', 'adapter=', 'driver=')): + print(line) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) + if fail_reads is None: + if run.returncode: + raise AssertionError('%s\n%s\n%s' % (label, run.stdout, run.stderr)) + print('%s: %s' % (label, expected), flush=True) + count[0] += 1 + else: + if run.returncode == 0 or 'actual=%s' % fail_reads not in run.stderr: + raise AssertionError('%s: control did not read %s\n%s\n%s' + % (label, fail_reads, run.stdout, run.stderr)) + print('%s: fails as expected, reads %s' % (label, fail_reads), flush=True) + count[1] += 1 + + def build(words, name): + return compile_hlsl(dxc, 'dxc', translate(words).hlsl_ps(), name, 'ps_6_0', directory) + + def sampler_line(words): + lines = [line for line in translate(words).manifest().splitlines() if line.startswith(('smp ', 'smpl '))] + assert len(lines) == 1, lines + return lines[0] + + for i, (s, t, face) in enumerate(CASES): + draw(build(literal_program(s, t, face)[0], 'lit%d' % i), texel(*address_texel(s, t, face)), + 'image_sample_lz s=%g t=%g face=%d' % (s, t, face)) + case = (1.875, 1.125, 1) + for form in ('sample', 'l', 'b'): + words = literal_program(*case, form)[0] + draw(build(words, 'form_%s' % form), texel(*address_texel(*case)), + 'image_sample%s s=%g t=%g face=%d' % ('' if form == 'sample' else '_' + form, *case), + sampler=sampler_line(words)) + # Guest-input controls: the face one higher and s, t exchanged must read those texels. + s, t, face = case + draw(build(literal_program(s, t, face + 1)[0], 'face_plus'), texel(*address_texel(*case)), + 'control face + 1', texel(*address_texel(s, t, face + 1))) + draw(build(literal_program(t, s, face)[0], 'swap_st'), texel(*address_texel(*case)), + 'control s and t exchanged', texel(*address_texel(t, s, face))) + # l and b with the face in the slot the translator reads as LOD or bias: another texel. + draw(build(program([(0, s), (1, t), (2, 0.0), (3, float(face))], 'l')[0], 'l_swapped'), + texel(*address_texel(*case)), 'control image_sample_l face and lod exchanged', + texel(*address_texel(s, t, 0))) + words = program([(0, float(face)), (1, s), (2, t), (3, 0.0)], 'b')[0] + draw(build(words, 'b_swapped'), texel(*address_texel(*case)), 'control image_sample_b face and bias exchanged', + texel(*address_texel(s, t, 0)), sampler=sampler_line(words)) + # Translator mutants: each edits the emitted helper and must read the texel a D3D lookup of its direction gives. + for index, (label, edits, rows, scale) in enumerate(mutants()): + hit = next((c for c in CASES if cube_lookup(helper_dir(rows, *c, *scale)) != address_texel(*c))) + source = translate(literal_program(*hit)[0]).hlsl_ps() + mutated = source + for old, new in edits: + assert mutated.count(old) == 1, (label, old) + mutated = mutated.replace(old, new) + assert mutated != source, label + shader = compile_hlsl(dxc, 'dxc', mutated, 'mutant%d' % index, 'ps_6_0', directory) + draw(shader, texel(*address_texel(*hit)), 'mutant %s (case %s)' % (label, hit), + texel(*cube_lookup(helper_dir(rows, *hit, *scale)))) + # End to end: the v_cube chain on six directions, against the reference and a desktop TextureCube draw. + for i, d in enumerate(DIRECTIONS): + expected = texel(*cube_lookup(d)) + draw(build(chain_program(d)[0], 'chain%d' % i), expected, 'v_cube chain d=%s' % (d,)) + native = compile_hlsl(dxc, 'dxc', desktop_ps(d), 'native%d' % i, 'ps_6_0', directory) + draw(native, expected, 'desktop TextureCube d=%s' % (d,)) + print('%d cube draws matched their references; %d controls and mutants read the texel they predict' + % tuple(count)) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(args[0]) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_gather_lz_check.py b/tests/startup_image_gather_lz_check.py index 7282c36bcd..b10961de17 100644 --- a/tests/startup_image_gather_lz_check.py +++ b/tests/startup_image_gather_lz_check.py @@ -81,7 +81,7 @@ def controls(llvm_mc): refused(shader(dst=0xff), 'four destination registers') # The explicit-LOD and fixed-mip comparison gathers are lowered by their own tests; the implicit, # biased and offset gathers stay refused here. - refused(shader(opcode=0x40), 'image_gather4') + refused(shader(opcode=0x40), 'image_gather4 requires the guest implicit mip level') refused(shader(opcode=0x45), 'image_gather4_b') refused(shader(opcode=0x54), 'image_gather4_l_o') refused(shader(opcode=0x48), 'image_gather4_c') diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py new file mode 100644 index 0000000000..00be477e5f --- /dev/null +++ b/tests/startup_image_get_lod_flow_check.py @@ -0,0 +1,315 @@ +"""image_get_lod past a branch or an EXEC change in tools/startup/gfx2hlsl.py (implicit derivatives of the quad). + + (no arguments) translation controls and refusals, pure Python + binary <llvm-mc> reassemble every fixture source and compare it with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + translate, compile (DXC ps_6_0, and FXC ps_5_1 when given), draw each accepted + fixture and compare the readback with the CPU reference; each mutant must differ + +Semantics. image_get_lod returns the LOD a sample would use, clamped, and the LOD before the clamp, from the same quad +derivatives as image_sample_b; the lowering is CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped and the +control-flow proof is Stage.uniform_cf with the quad vote of EXEC branches (see tests/startup_image_sample_b_flow_check.py +for the model: a lane EXEC masked off offers the address it last wrote). + +Fixtures (synthetic gfx1013 wave64 programs, no game data). v0 is the packed pixel position, x = v0 & 0xffff. Every +program starts with `s_wqm_b64 exec, exec`, sets u = 0.125 + 0.5 * x and v = 0.25 and queries the LOD of the 4x4, +three-mip 2D texture of tests/startup_image_3d.cpp (--startup-image-2d-view 0/3: one covered pixel at (0, 0), three +helper lanes) through a sampler with mip filter point, MIN_LOD 0 and MAX_LOD 2. The unclamped LOD is +log2(4 * |u(x=1) - u(x=0)|); the clamped one is that in [0, 2]. The export is (clamped, unclamped, 0, 0): + join_pixel lanes with x == 0 branch into u -= 0.5, the quad queries at the join: |du| = 1, LOD 2 + join_helper the helper column x == 1 branches into u += 1.5: |du| = 2, unclamped 3, clamped 2 + cmpx v_cmpx keeps x == 0, u -= 0.5 there only, the query runs with that EXEC: stale helper u, LOD 2 + scc a branch on root constant 1 (the same in every lane, not taken) before the query: LOD 1 + inside the query inside the s_cbranch_execz block of x == 0 after u -= 0.5 there (EXEC branches are decided + per quad, see tests/startup_image_sample_b_flow_check.py): stale helper u, LOD 2 + kill v_cmpx keeps x == 0, s_cbranch_execnz past an s_endpgm, u -= 0.5, query: LOD 2 +Refused: the query inside a block a VCC branch skips. +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 +from startup_image_sample_b_flow_check import PS_INPUTS, assemble # noqa: E402 + +PROLOGUE = """\ +s_wqm_b64 exec, exec +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0x200000 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_and_b32_e32 v8, 0xffff, v0 +v_cvt_f32_u32_e32 v9, v8 +v_mul_f32_e32 v9, 0.5, v9 +v_add_f32_e32 v2, 0x3e000000, v9 +v_mov_b32_e32 v3, 0x3e800000 +v_mov_b32_e32 v12, 0 +v_mov_b32_e32 v13, 0 +""" +QUERY = """\ +s_waitcnt lgkmcnt(0) +image_get_lod v[10:11], v[2:3], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D +""" +EXPORT = """\ +s_waitcnt vmcnt(0) +exp mrt0 v10, v11, v12, v13 done vm +s_endpgm +""" + + +def branch_on_x(x, delta): + return ('v_cmp_eq_u32_e32 vcc, %d, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 'v_add_f32_e32 v2, %s, v2\nBB1:\ns_or_b64 exec, exec, s[0:1]\n' % (x, delta)) + + +# name: (source, u at x = 0 and x = 1 when the quad queries) +FIXTURES = { + 'join_pixel': (PROLOGUE + branch_on_x(0, '-0.5') + QUERY + EXPORT, (Fraction(-3, 8), Fraction(5, 8))), + 'join_helper': (PROLOGUE + branch_on_x(1, '0x3fc00000') + QUERY + EXPORT, (Fraction(1, 8), Fraction(17, 8))), + 'cmpx': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + (Fraction(-3, 8), Fraction(5, 8))), + 'scc': (PROLOGUE + 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + QUERY + 'BB1:\n' + EXPORT, + (Fraction(1, 8), Fraction(5, 8))), + 'inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 'v_add_f32_e32 v2, -0.5, v2\n' + QUERY + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, + (Fraction(-3, 8), Fraction(5, 8))), + 'kill': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\ns_cbranch_execnz BB1\ns_endpgm\nBB1:\nv_add_f32_e32 v2, -0.5, v2\n' + + QUERY + EXPORT, (Fraction(-3, 8), Fraction(5, 8))), + # u is the same in every lane and v = 0.25 + 0.5 * y, so the LOD comes from the vertical derivative alone; only the row + # y == 0 enters the block. (u0, u1) is (u of the drawn pixel, u + the footprint along y): 4 * 0.5 = 2, LOD 1 - 1 = 0. + 'inside_y': (PROLOGUE + 'v_mov_b32_e32 v2, 0x3e000000\nv_lshrrev_b32_e32 v7, 16, v0\nv_cvt_f32_u32_e32 v6, v7\nv_mul_f32_e32 v6, 0.5, v6\nv_add_f32_e32 v3, 0x3e800000, v6\nv_cmp_eq_u32_e32 vcc, 0, v7\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\nv_mov_b32_e32 v14, 0\n' + + QUERY + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(1, 8), Fraction(5, 8))), +} +REFUSED = { + # The plain s_mov_b64 exec, s[N] restore of a mask saved before s_wqm is a lane-exec break too (main accepts the form). + 'restore_mov': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_mov_b64 exec, s[12:13]\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. + 'exec_lo_const': (PROLOGUE + 's_mov_b32 exec_lo, -1\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A mask saved before s_wqm exec, exec has the guest's helper lanes off, while every thread here starts + # with exec = 1: writing it back is a lane-exec break (review of ef786354). + 'restore': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # The same restore, then u -= 0.5 on the lanes it leaves on: the guest's helper keeps its stale u, the + # translation's helper takes the new one (measured by the reviewer on WARP and an RX 9070 XT). + 'restore_helper': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + 'v_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A kill export under v_cmpx before the op: the discard is a lane-exec break (it fails without it). + 'discard_break': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\nexp null off, off, off, off vm\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A 32-bit EXEC write keeps lanes 32..63 of the old mask in wave64: only the 64-bit forms are exact. + 'exec_lo_mask': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_mov_b32 exec_lo, vcc_lo\n' + 'v_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + QUERY + 'BB1:\n' + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A scalar write inside the block an EXEC branch can skip happens once for the wave in the guest; a quad that + # votes to skip it would miss it (review of the first version): the branch is not voted, the op is refused. + 'scalar_in_block': (PROLOGUE + 's_mov_b32 s28, -1.0\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 's_mov_b32 s28, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\nv_mov_b32_e32 v1, s28\n' + + QUERY + EXPORT, 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), +} +# llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources +WORDS_HEX = { + 'restore_mov': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' + '0d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e0c04febef10404067fc08cbf080380f1020a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'inside_y': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003eff02067e0000803e8002187e80021a7eff02047e0000003e90000e2c070d0c7ef00c0c10ff0c' + '06060000803e800e847d6a2480be040088bf80021c7e7fc08cbf080380f1020ac4007e00fe88703f8cbf0f1800f80a0b0c' + '0d000081bf' + ), + 'exec_lo_const': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003eff02067e0000803e8002187e80021a7ec103febef10404067fc08cbf080380f1020ac400703f' + '8cbf0f1800f80a0b0c0d000081bf' + ), + 'restore_helper': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' + '0d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e7e0cfe87f10404067fc08cbf080380f1020a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'discard_break': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003eff02067e0000803e8002187e80021a7e8010a47d901000f8000000007fc08cbf080380f1020a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'exec_lo_mask': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d6a03febef10404067fc08cbf080380f1020a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'join_pixel': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d6a2480be010088bff10404067e00fe88' + '7fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'join_helper': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8110847d6a2480be020088bfff0404060000c03f' + '7e00fe887fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'cmpx': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010a47df10404067fc08cbf080380f1020ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'scc': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e098007bf030085bf7fc08cbf080380f1020ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d6a2480be040088bff10404067fc08cbf' + '080380f1020ac4007e00fe88703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'kill': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010a47d010089bf000081bff10404067fc08cbf' + '080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'vcc_inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d030086bf7fc08cbf080380f1020ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'scalar_in_block': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7ef3039cbe8210847d6a2480be010088bf80039cbe7e00fe881c02027e7fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'restore': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e7e0cfe877fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), +} +CALL = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v2), F(v3))), ' + 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v2), F(v3))), 0.0, 0.0);') + + +def all_sources(): + return dict({k: v[0] for k, v in FIXTURES.items()}, **{k: v[0] for k, v in REFUSED.items()}) + + +def pipeline(name): + return G.Pipeline(VS_WORDS, bytes.fromhex(WORDS_HEX[name]), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def refused(name, text): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (name, text, str(error)) + else: + raise AssertionError('%s accepted, expected %r' % (name, text)) + + +def reference(u): + """(clamped, unclamped) LOD of the drawn pixel: u is the same down a column, v is constant.""" + lod = math.log2(4 * abs(u[1] - u[0])) + assert lod == int(lod), u + return min(max(lod, 0.0), 2.0), lod + + +def controls(): + for name in FIXTURES: + text = pipeline(name).hlsl_ps() + assert text.count(CALL) == 1, (name, text) + for name, (_source, text) in REFUSED.items(): + refused(name, text) + print('image_get_lod after a join, under a v_cmpx EXEC, after a uniform branch, inside an EXEC branch and ' + 'past a kill branch: CalculateLevelOfDetail; ' + 'references %s' % ', '.join('%s=%s' % (n, reference(f[1])) for n, f in FIXTURES.items())) + print('refused: inside a block a VCC branch skips') + + +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = assemble(llvm_mc, source) + if built.hex() != WORDS_HEX[name]: + raise AssertionError('%s: assembled %s, recorded %s' % (name, built.hex(), WORDS_HEX[name])) + print('every fixture reassembles to its recorded words with %s' % llvm_mc) + + +def mutants(name, hlsl): + """HLSL variants that must give another LOD: the branch write dropped, or the EXEC guard dropped.""" + write = re.search(r'\n\s*if \(exec & 1\) v2 = U\((-0\.5|F\(0x3fc00000u\)) \+ F\(v2\)\);', hlsl) + if name.startswith('join'): + return [('without the branch write', hlsl.replace(write.group(0), ''))] + if name in ('cmpx', 'inside', 'kill'): + return [('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))] + return [] + + +def read_lod(renderer, adapter, vs, ps, sampler): + run = subprocess.run([renderer, adapter, '--startup-image-2d-view', str(vs), str(ps), sampler, '0/3'], + capture_output=True, text=True, timeout=60) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + match = re.search(r'view_rgba=((?:[0-9a-f]{8},){3}[0-9a-f]{8})', run.stdout) + if run.returncode or not match: + raise AssertionError(run.stdout + run.stderr) + return struct.unpack('>4f', bytes.fromhex(match.group(1).replace(',', ''))) + + +def close(got, want): + # One D3D12 LOD fractional step (1/256), as tests/startup_image_get_lod_view_check.py allows. + return all(abs(g - w) <= 1 / 256 for g, w in zip(got, want)) + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name, (_source, u) in FIXTURES.items(): + pipe = pipeline(name) + hlsl = pipe.hlsl_ps() + sampler, = (line for line in pipe.manifest().splitlines() if line.startswith('smpl ')) + want = reference(u) + (0.0, 0.0) + ps = compile_hlsl(compiler, kind, hlsl, '%s_%s' % (name, kind), ps_profile, directory) + got = read_lod(renderer, adapter, vs, ps, sampler) + if not close(got, want): + raise AssertionError('%s %s %s: GPU %s, CPU reference %s' % (adapter, kind, name, got, want)) + seen = [] + for i, (label, text) in enumerate(mutants(name, hlsl)): + ps = compile_hlsl(compiler, kind, text, '%s_m%d_%s' % (name, i, kind), ps_profile, directory) + other = read_lod(renderer, adapter, vs, ps, sampler) + if close(other, want): + raise AssertionError('%s %s %s: mutant "%s" matched the reference %s' + % (adapter, kind, name, label, other)) + seen.append('%s -> %s' % (label, other[:2])) + print('%s %s %s: GPU %s == CPU reference %s; %s' + % (adapter, kind, name, got[:2], want[:2], '; '.join(seen) or 'no mutant'), flush=True) + + +def main(): + if len(sys.argv) == 1 or sys.argv[1] == 'controls': + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + elif sys.argv[1] == 'draw' and len(sys.argv) in (5, 6): + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_get_lod_view_check.py b/tests/startup_image_get_lod_view_check.py index 9dd9652e8a..175ab68557 100644 --- a/tests/startup_image_get_lod_view_check.py +++ b/tests/startup_image_get_lod_view_check.py @@ -1,4 +1,4 @@ -"""Draw gfx1013 image_get_lod through the translated static sampler and four views of a 4x4 texture.""" +"""Draw gfx1013 image_get_lod through translated static samplers and 2D/array mip views.""" import re import struct import subprocess @@ -28,6 +28,31 @@ return float4(clamped, raw, clamped, raw); } """ +SLICE_LIT = bytes.fromhex('ff02047e') # v_mov_b32 v2, <imm32> (VOP1 literal): the slice dword of the array address +DIRECT_ARRAY_PS = DIRECT_PS.replace('Texture2D<', 'Texture2DArray<', 1) + + +def patch_sampler(code, low, high): + # s_mov_b32 s25, literal: sampler word 1 carries the two unsigned 4.8 LOD limits. + at = fixture.W2_AT - 4 + assert code[at:at + 4] == bytes.fromhex('800399be') + limits = int(low * 256) | (int(high * 256) << 12) + return code[:at] + struct.pack('<II', 0xbe9903ff, limits) + code[at + 4:] + + +def array_pipeline(step, slice_index, low, high, mip_filter): + """The dim 0x5 (SQ_RSRC_IMG_2D_ARRAY) stage: v[0:2] is u, v and the slice; the u/v moves are the same + pixel-position unpacking and scaling as the 2D lane, and the slice dword becomes a literal move (the + fixture's VOP1 v2 = 1.0 cannot hold 0.0 as an inline constant).""" + code = fixture.stage(dmask=3, dim=5, word2=mip_filter << 26) + coords = bytes.fromhex('f002007eff02027e0000803ef202047ef402067e') + assert code.count(coords) == 1 + scale = {1: b'', 0.125: SCALE_EIGHTH}[step] + lit = struct.pack('<I', 0 if slice_index == 0 else 0x3f800000) + # v2 (the slice) and v3 (unused) keep moving constants; only their encodings shift with the insertion. + code = code.replace(coords, UNPACK_XY + scale + SLICE_LIT + lit + bytes.fromhex('f402067e')) + code = patch_sampler(code, low, high) + return fixture.G.Pipeline(fixture.VS_WORDS, code, fixture.root_blob(flags=0), ps_hw_inputs=(0x8000, 0x8000)) def pipeline(step, low, high, mip_filter): @@ -37,17 +62,18 @@ def pipeline(step, low, high, mip_filter): assert code.count(coords) == 1 scale = {1: b'', 0.125: SCALE_EIGHTH}[step] code = code.replace(coords, UNPACK_XY + scale) - # s_mov_b32 s25, literal: sampler word 1 carries the two unsigned 4.8 LOD limits. - at = fixture.W2_AT - 4 - assert code[at:at + 4] == bytes.fromhex('800399be') - limits = int(low * 256) | (int(high * 256) << 12) - code = code[:at] + struct.pack('<II', 0xbe9903ff, limits) + code[at + 4:] + code = patch_sampler(code, low, high) return fixture.G.Pipeline(fixture.VS_WORDS, code, fixture.root_blob(flags=0), ps_hw_inputs=(0x8000, 0x8000)) -def read_pixel(renderer, adapter, vs, ps, sampler, view): - run = subprocess.run([renderer, adapter, '--startup-image-2d-view', vs, ps, sampler, view], - capture_output=True, text=True, timeout=30) +def read_pixel(renderer, adapter, vs, ps, sampler, view, *, selector=None, array=False, mip_base=None): + mode = '--startup-image-2d-array-view' if array else '--startup-image-2d-view' + args = [renderer, adapter, mode, vs, ps, sampler, view] + if selector is not None or mip_base is not None: + args.append(str(0 if selector is None else selector)) + if mip_base is not None: + args.append(str(mip_base)) + run = subprocess.run(args, capture_output=True, text=True, timeout=30) print(run.stdout, end='') if run.returncode == 77: print(run.stderr, file=sys.stderr) @@ -98,5 +124,37 @@ def draw(dxc, renderer, adapter): print(f'ordinary sampler control rgba={unlimited.hex()}') +def draw_array(dxc, renderer, adapter): + """The array lane: the dim 0x5 get_lod stage against the same 4x4 two-slice three-mip texture through + --startup-image-2d-array-view. The whole resource is bound (srv tex2da table 0 0: no SRV mip window), so + the raw LOD is log2(step * 4) and the clamped LOD is that value clamped by the sampler's MIN_LOD/MAX_LOD + word. Two different valid slices (0 and 1; a slice coordinate is not normalized) must return the same LOD + pair: the slice is consumed but not part of the query. The translated and direct HLSL readbacks must + match exactly, and check_color keeps both near the CPU reference (mip filter 1 = point, 2 = linear).""" + # UV step, slice, sampler min/max, mip filter (1 point, 2 linear), expected (clamped, raw). + cases = ( + (1, 0, 0, 2, 1, (2, 2)), + (1, 1, 0, 2, 1, (2, 2)), + (0.125, 0, 0.5, 2, 2, (0.5, -1)), + (0.125, 1, 0.5, 2, 2, (0.5, -1)), + ) + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen_array', 'vs_6_0', work) + for step, slice_index, low, high, mip_filter, expected in cases: + pipe = array_pipeline(step, slice_index, low, high, mip_filter) + sampler, = (line for line in pipe.manifest().splitlines() if line.startswith('smpl ')) + guest = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), 'translated_array_%d' % slice_index, 'ps_6_0', work) + direct = compile_hlsl(dxc, 'dxc', DIRECT_ARRAY_PS.replace('STEP', str(float(step))), + 'direct_array_%d' % slice_index, 'ps_6_0', work) + pixel = read_pixel(renderer, adapter, vs, guest, sampler, '0/3', array=True) + reference = read_pixel(renderer, adapter, vs, direct, sampler, '0/3', array=True) + assert pixel == reference, (slice_index, pixel.hex(), reference.hex()) + check_color(pixel, expected) + print(f'array slice={slice_index} step={step} min={low} max={high} mip_filter={mip_filter} ' + f'rgba={pixel.hex()}') + + if __name__ == '__main__': draw(*sys.argv[1:]) + draw_array(*sys.argv[1:]) diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index f72cc4242b..3be4b1cc0b 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -1,4 +1,4 @@ -"""Biased implicit-LOD image_sample_b in tools/startup/gfx2hlsl.py (pixel stage only). +"""Biased implicit-LOD image_sample_b in tools/startup/gfx2hlsl.py (pixel stage only; M200-01 B). (no arguments) translation controls, pure Python binary <llvm-mc> reassemble every fixture source and compare it with the recorded words @@ -12,7 +12,11 @@ IntrinsicsAMDGPU.td lists the extra argument of AMDGPUSample_b as llvm_anyfloat_ty "bias" and MIMGInstructions.td gives IMAGE_SAMPLE_B the gfx10 opcode 0x25. HLSL Texture.SampleBias(sampler, location, bias) adds the bias to the implicit mip level, so the lowering is tex.SampleBias(smp, uv, bias). D3D documents the bias range as -16.0 to 15.99; -the ISA text states no hardware clamp, so values outside that range are an unverified difference. +the ISA text states no hardware clamp, so values outside that range are an unverified difference. Accepted under the +entry EXEC mask and wave-uniform control flow even after a uniform (scc) join or later loop; an EXEC written per lane +(v_cmpx, saveexec, a cleared EXEC) is followed exactly by the one-lane model, so it is accepted in a program without a +backward branch (tests/startup_image_sample_b_flow_check.py draws it); divergent EXEC or a +vcc/exec-conditioned branch before the sample stays refused. Each fixture is a source-built gfx1013 pixel stage: v0 = bias, v1 = u = 0.75, v2 = v = 0.25 and v3 = the slice (root constant 1, s9). Constant coordinates have no derivatives (the implicit LOD would be log2(0) and the bias is lost), so @@ -46,6 +50,7 @@ import startup_sampler_heap_check as H # noqa: E402 from startup_image_2d_array_check import mip_cell # noqa: E402 from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 +import gpu_case_runner # noqa: E402 # Sampler words: point filters, wrap, MAX_LOD 2.0 (u4.8 at word 1 bits 23:12), mip filter point (word 2 bits 27:26). SAMPLER = ('0', '0x200000', '0x4000000') @@ -386,9 +391,10 @@ def texel_cell(mip, slice_index): def check_guards(): """The stage guard and the address-count guard are decided before any state is read, so a bare stage reaches them.""" - def call(coords, kind='ps', exec_known=True, blocks=()): + def call(coords, kind='ps', exec_known=True, blocks=(), uniform_cf=True): bare = G.Stage.__new__(G.Stage) bare.kind, bare.exec_known, bare.blocks = kind, exec_known, list(blocks) + bare.uniform_cf = uniform_cf bare.image(['v5', coords, 's0'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1'], 'b') for coords, count in (('[v1, v2]', 2), ('[v1, v2, v3, v4]', 4)): @@ -399,13 +405,23 @@ def call(coords, kind='ps', exec_known=True, blocks=()): else: raise AssertionError('image_sample_b accepted %d address registers' % count) for label, kwargs in (('vertex stage', {'kind': 'vs'}), ('compute stage', {'kind': 'cs'}), - ('exec modified', {'exec_known': False}), ('after a branch', {'blocks': [object()]})): + ('exec modified', {'exec_known': False}), + ('divergent CF', {'uniform_cf': False})): try: call('[v1, v2, v3]', **kwargs) except G.Unsupported as error: assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) else: raise AssertionError('image_sample_b accepted: %s' % label) + # A prior join (non-empty blocks) is fine while EXEC and wave-uniform CF hold (M200-01 B). + try: + call('[v1, v2, v3]', blocks=[object()], uniform_cf=True) + except G.Unsupported as error: + raise AssertionError('image_sample_b refused with entry EXEC after a uniform join: %s' % error) + except AttributeError: + pass + else: + raise AssertionError('image_sample_b after a join returned without needing a pipeline') # The legal case gets past both guards: the bare stage then stops where it needs a pipeline. try: call('[v1, v2, v3]') @@ -413,7 +429,42 @@ def call(coords, kind='ps', exec_known=True, blocks=()): raise AssertionError('legal image_sample_b refused: %s' % error) except AttributeError: pass - print('refused: wrong address count, vertex and compute stages, modified exec, code after a branch') + else: + raise AssertionError('legal image_sample_b returned without needing a pipeline') + print('refused: wrong address count, vertex and compute stages, modified exec, divergent CF; ' + 'join with entry EXEC and uniform CF accepted') + + +def sopp(op, simm): + return struct.pack('<I', (simm & 0xffff) | op << 16 | 0x17f << 23) + + +def with_join_before_sample(data): + """Uniform forward join (every lane takes the same path) immediately before the sample (sample_b or plain).""" + off = next(o for o, _s, _n, a in G.decode(data) if a.startswith('image_sample')) + join = (bytes.fromhex('800380be') + bytes.fromhex('008006bf') + sopp(5, 1) + bytes.fromhex('810381be')) + return data[:off] + join + data[off:] + + +def with_divergent_exec_before_sample(data, word='8004febe'): + """Clear EXEC after the loads so the entry-mask proof is gone before the sample (s_mov_b64 exec, 0 by default; + 8003febe is s_mov_b32 exec_lo, 0).""" + off = next(o for o, _s, _n, a in G.decode(data) if 'image_sample_b' in a) + return data[:off] + bytes.fromhex(word) + data[off:] + + +def with_branch_before_sample(data, sopp_op): + """Insert s_mov; s_cbranch_<op> +1; s_mov immediately before the sample_b (review probe).""" + off = next(o for o, _s, _n, a in G.decode(data) if 'image_sample_b' in a) + insert = bytes.fromhex('800380be') + sopp(sopp_op, 1) + bytes.fromhex('810381be') + return data[:off] + insert + data[off:] + + +def with_divergent_back_edge_after_sample(data, sopp_op): + """Insert s_cbranch_<op> right after the sample_b, jumping back to it: the branch comes later in program order, but + the sample runs again on the next pass, with lanes that left the loop at different passes.""" + off, size = next((o, s) for o, s, _n, a in G.decode(data) if 'image_sample_b' in a) + return data[:off + size] + sopp(sopp_op, -(size // 4 + 1)) + data[off + size:] def controls(): @@ -421,6 +472,33 @@ def controls(): locate() stage('array 1').hlsl_ps() # the plain translation first: a translator without the lowering stops here check_guards() + plain = bytes.fromhex(WORDS['plain']) + join_ps = G.Pipeline(VS_WORDS, with_join_before_sample(plain), root_blob()).hlsl_ps() + assert 'SampleBias' in join_ps and bias_call(join_ps, 'float2') == (['v1', 'v2'], 'v0'), join_ps + for label, mutate in ( + ('s_cbranch_vccz', lambda d: with_branch_before_sample(d, 6)), + ('s_cbranch_vccnz', lambda d: with_branch_before_sample(d, 7)), + ('s_cbranch_execz', lambda d: with_branch_before_sample(d, 8)), + ('s_cbranch_execnz', lambda d: with_branch_before_sample(d, 9)), + ('s_cbranch_vccnz back edge after the sample', lambda d: with_divergent_back_edge_after_sample(d, 7)), + ('s_cbranch_execnz back edge after the sample', lambda d: with_divergent_back_edge_after_sample(d, 9))): + try: + G.Pipeline(VS_WORDS, mutate(plain), root_blob()).hlsl_ps() + except G.Unsupported as error: + assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) + else: + raise AssertionError('image_sample_b accepted after %s' % label) + # A 64-bit cleared EXEC is an exact per-lane write: the quad program (no backward branch) keeps the proof. The + # 32-bit form keeps lanes 32..63 of the old mask in wave64, so it is refused. + try: + G.Pipeline(VS_WORDS, with_divergent_exec_before_sample(plain, '8003febe'), root_blob()).hlsl_ps() + except G.Unsupported as error: + assert 'image_sample_b needs implicit derivatives' in str(error), error + else: + raise AssertionError('image_sample_b accepted after s_mov_b32 exec_lo, 0') + cleared = G.Pipeline(VS_WORDS, with_divergent_exec_before_sample(plain), root_blob()).hlsl_ps() + assert 'SampleBias' in cleared and 'exec = (0x00000000u) & 1;' in cleared, cleared + print('uniform join before sample_b accepted; divergent EXEC and vcc/exec branches before sample_b refused') # Address order: the bias register comes first and is the third SampleBias argument. expected = { 'array 1': (['v1', 'v2', 'v3'], 'v0', 'float3', 'Texture2DArray<float4> r0'), @@ -451,9 +529,11 @@ def controls(): refused('c_b', 'image_sample_c_b') refused('offset', 'image_sample_b_o') refused('gather', 'image_gather4_b') - refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') + # Since #2943 a cube lowers to TextureCube; the bias dword comes before the face address. + cube = stage('cube').hlsl_ps() + assert 'TextureCube<float4>' in cube and 'SampleBias(' in cube and 'x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))' in cube, cube refused('msaa', 'image dimension SQ_RSRC_IMG_') - refused('dim1d', 'unverified 1D image sample address or modifiers') + refused('dim1d', 'unverified 1D image b address or modifiers') refused('unorm', 'image_sample_b modifier unorm') refused('tfe', 'image_sample_b modifier tfe') refused('a16', 'image_sample_b modifier a16') @@ -465,7 +545,8 @@ def controls(): refused(name, 'image_sample_b modifier reserved') refused('sampler bias', 'image_sample_b with a sampler LOD bias (word 2 0x4000001)') refused('sampler bias sec', 'image_sample_b with a sampler LOD bias (word 2 0x4004000)') - print('refused: b_cl, c_b, offset, gather4_b, cube, MSAA, 1D, a16, d16, tfe, lwe, unorm, r128, dmask 0, ' + print('cube: TextureCube SampleBias with x2w_cube_dir') + print('refused: b_cl, c_b, offset, gather4_b, MSAA, 1D, a16, d16, tfe, lwe, unorm, r128, dmask 0, ' 'reserved bits, sampler LOD bias') # Guest sampler limits: carried over for a constant descriptor, refused where they cannot be shown irrelevant. @@ -554,8 +635,7 @@ def check_draw(dxc, renderer, adapter, fxc=None): locate() def draw_once(vs, shader, slice_index, expected, sampler): - run = subprocess.run([renderer, adapter, operation, str(vs), str(shader), str(slice_index), expected, sampler], - capture_output=True, text=True) + run = gpu_case_runner.run(renderer, adapter, [operation, vs, shader, slice_index, expected, sampler]) sys.stdout.write(run.stdout) if run.returncode == 77: print(run.stdout + run.stderr) @@ -588,6 +668,36 @@ def sampler_line(pipe): if run.returncode: raise AssertionError('%s %s slice=%d\n%s\n%s' % (kind, name, slice_index, run.stdout, run.stderr)) print('%s sample_b %s slice=%d: %s' % (kind, name, slice_index, expected), flush=True) + # M200-01 B: the same bias-1 array sample after a uniform join must still read mip 0. + join_words = with_join_before_sample(bytes.fromhex(WORDS['array -1'])) + join_pipe = G.Pipeline(VS_WORDS, join_words, root_blob()) + join_shader = compile_hlsl(compiler, kind, drawable(join_pipe.hlsl_ps()), 'ps_join_m1_%s' % kind, + ps_profile, directory) + join_line = sampler_line(join_pipe) + for slice_index in (0, 1): + expected = texel_cell(mip_for(-1), slice_index) + run = draw_once(vs, join_shader, slice_index, expected, join_line) + if run.returncode: + raise AssertionError('%s join sample_b slice=%d\n%s\n%s' % (kind, slice_index, run.stdout, run.stderr)) + print('%s sample_b join-before bias=-1 slice=%d: %s' % (kind, slice_index, expected), flush=True) + # A plain image_sample after a uniform join keeps the implicit LOD: it reads mip 1, not the mip 0 of + # SampleLevel(.., 0). The mip-0 expectation is the negative control and must fail on the readback. + plain_pipe = G.Pipeline(VS_WORDS, with_join_before_sample(bytes.fromhex(WORDS['array nobias'])), root_blob()) + plain_hlsl = plain_pipe.hlsl_ps() + assert '.Sample(' in plain_hlsl and 'SampleLevel' not in plain_hlsl, plain_hlsl + plain_shader = compile_hlsl(compiler, kind, drawable(plain_hlsl), 'ps_plain_join_%s' % kind, ps_profile, directory) + plain_line = sampler_line(plain_pipe) + for slice_index in (0, 1): + expected = texel_cell(1, slice_index) + run = draw_once(vs, plain_shader, slice_index, expected, plain_line) + if run.returncode: + raise AssertionError('%s plain image_sample join slice=%d\n%s\n%s' % (kind, slice_index, run.stdout, run.stderr)) + level0 = draw_once(vs, plain_shader, slice_index, texel_cell(0, slice_index), plain_line) + if level0.returncode == 0 or 'actual=%s' % expected not in level0.stderr: + raise AssertionError('%s plain image_sample join slice=%d: the level-0 expectation did not fail\n%s\n%s' + % (kind, slice_index, level0.stdout, level0.stderr)) + print('%s image_sample join-before slice=%d: %s (level 0 fails as expected)' % (kind, slice_index, expected), + flush=True) # Negative control: without a bias the draw reads mip 1, so the bias -1 and bias +1 expectations must fail. line = sampler_line(stage('array nobias')) nobias = compile_hlsl(compiler, kind, drawable(translated['array nobias']), 'ps_nobias_%s' % kind, ps_profile, directory) diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py new file mode 100644 index 0000000000..b51aea26b8 --- /dev/null +++ b/tests/startup_image_sample_b_flow_check.py @@ -0,0 +1,502 @@ +"""image_sample_b past a branch or an EXEC change in tools/startup/gfx2hlsl.py (implicit derivatives of the quad). + + (no arguments) translation controls and refusals, pure Python + binary <llvm-mc> reassemble every fixture source and compare it with the recorded words + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + translate, compile (DXC ps_6_0, and FXC ps_5_1 when given), draw each accepted + fixture and compare the readback with the CPU reference; each mutant must differ + +Semantics. image_sample_b adds its bias to the LOD the texture unit derives from the address VGPRs of the four lanes of +the pixel quad (RDNA 2 ISA section 8.2.4, "_B LOD BIAS: Add this BIAS to the LOD computed"). The lanes are read whatever +their EXEC bits (that is why compilers switch to whole quad mode before computing coordinates): a lane EXEC masked off +offers the value it last wrote. The translation runs one guest lane per D3D pixel or helper lane, writes a VGPR only +where the lane's EXEC bit is 1 and calls SampleBias unconditionally, so HLSL derives from the same four values when the +four lanes reach the call together. In a pixel program with such an op and no backward branch, s_cbranch_execz/execnz +are decided per quad (x2w_quad_any, fine derivatives of the EXEC bit): the guest's wave skips a +block only when no lane is active and runs it with the other lanes masked, so a quad with an active lane stays together. +A voted branch parts no quad, so it does not clear Stage.uniform_cf; the vote reads the quad, so it is only taken while +uniform_cf holds and no lane-exec break (s_wqm of a narrowed EXEC, a discard) came first. Any other branch that can +differ between lanes (a VCC test, an SCC not proven uniform) clears uniform_cf, as in #2659. + +Fixtures (synthetic gfx1013 wave64 programs, no game data). v0 is the packed pixel position (POS_FIXED_PT, the only +pixel input enabled), x = v0 & 0xffff. Every program starts with `s_wqm_b64 exec, exec`, sets u = 0.125 + 0.5 * x, +v = 0.25, the slice from root constant 1 (s9, drawn as 0), the bias -1, and samples the 4x4, two-slice, three-mip array +of tests/startup_image_3d.cpp (--startup-image-2d-array-mips: one covered pixel at (0, 0) and its three helper lanes) +with a point sampler, mip filter point, MAX_LOD 2. u depends on x only, so the LOD is log2(4 * |u(x=1) - u(x=0)|) - 1: + join_pixel lanes with x == 0 (the drawn pixel's column) branch into u -= 0.5, then EXEC is restored and the quad + samples at the join: u = (-0.375, 0.625), LOD 2 - 1 = 1 + join_helper the helper column x == 1 branches into u += 0.5: u = (0.125, 1.125), LOD 1; the drawn pixel did not branch + cmpx v_cmpx keeps x == 0, u -= 0.5 runs on those lanes only and the sample runs with that EXEC: the helper column + offers its stale u = 0.625, LOD 2 - 1 = 1 (u = 0.125 there would give LOD 0) + scc a branch on root constant 1 (the same in every lane, not taken) before the sample: LOD 1 - 1 = 0 + inside the sample inside the s_cbranch_execz block of x == 0, after u -= 0.5 there: the quad enters together, + the helper column masked with its stale u: LOD 1 + kill v_cmpx keeps x == 0, s_cbranch_execnz past an s_endpgm, u -= 0.5, sample: the quad goes on, LOD 1 + inside_y u is the same in every lane and v = 0.25 + 0.5 * y: the block is entered by the row y == 0 only, the quad + stays together and the LOD comes from the vertical derivative: LOD 1 - 1 = 0. The vote itself is drawn + alone (VOTE_CASES): one lane of the quad set at each position, and each half of the helper dropped. + uni_loop a loop of two passes on a constant SGPR counter (SCC proven uniform): sample, then u -= 0.5 on every + lane; the second pass reads u = (-0.375, 0.125), LOD 0 +Refused: the sample inside or after a block a VCC branch skips (the guest takes a VCC branch once per wave, with EXEC +unchanged, so a lane skipping it on its own bit can hold another u), and inside a loop whose exit reads VCC. +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_2d_array_check import mip_cell # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +PS_INPUTS = (0x8000, 0x8000) # SPI_PS_INPUT_ENA / ADDR: POS_FIXED_PT only, so v0 holds x | y << 16 +PROLOGUE = """\ +s_wqm_b64 exec, exec +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0x200000 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_and_b32_e32 v8, 0xffff, v0 +v_cvt_f32_u32_e32 v9, v8 +v_mul_f32_e32 v9, 0.5, v9 +v_add_f32_e32 v2, 0x3e000000, v9 +v_mov_b32_e32 v1, -1.0 +v_mov_b32_e32 v3, 0x3e800000 +v_mov_b32_e32 v4, s9 +""" +SAMPLE = """\ +s_waitcnt lgkmcnt(0) +image_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +""" +EXPORT = """\ +s_waitcnt vmcnt(0) +exp mrt0 v10, v11, v12, v13 done vm +s_endpgm +""" + + +def branch_on_x(x, delta): + return ('v_cmp_eq_u32_e32 vcc, %d, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 'v_add_f32_e32 v2, %s, v2\nBB1:\ns_or_b64 exec, exec, s[0:1]\n' % (x, delta)) + + +# name: (source, u at x = 0 and x = 1 when the quad samples, bias) for the drawn fixtures +SUB = 'v_add_f32_e32 v2, -0.5, v2\n' +CMPX = 'v_cmpx_eq_u32_e32 0, v8\n' +FIXTURES = { + 'join_pixel': (PROLOGUE + branch_on_x(0, '-0.5') + SAMPLE + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + 'join_helper': (PROLOGUE + branch_on_x(1, '0.5') + SAMPLE + EXPORT, (Fraction(1, 8), Fraction(9, 8)), -1), + 'cmpx': (PROLOGUE + CMPX + SUB + SAMPLE + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + 'scc': (PROLOGUE + 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + SAMPLE + 'BB1:\n' + EXPORT, + (Fraction(1, 8), Fraction(5, 8)), -1), + 'inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + SUB + + SAMPLE + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + 'kill': (PROLOGUE + CMPX + 's_cbranch_execnz BB1\ns_endpgm\nBB1:\n' + SUB + SAMPLE + EXPORT, + (Fraction(-3, 8), Fraction(5, 8)), -1), + # u is the same in every lane and v = 0.25 + 0.5 * y, so the LOD comes from the vertical derivative alone; only the row + # y == 0 enters the block. (u0, u1) is (u of the drawn pixel, u + the footprint along y): 4 * 0.5 = 2, LOD 1 - 1 = 0. + 'inside_y': (PROLOGUE + 'v_mov_b32_e32 v2, 0x3e000000\nv_lshrrev_b32_e32 v7, 16, v0\nv_cvt_f32_u32_e32 v6, v7\nv_mul_f32_e32 v6, 0.5, v6\nv_add_f32_e32 v3, 0x3e800000, v6\nv_cmp_eq_u32_e32 vcc, 0, v7\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\nv_mov_b32_e32 v14, 0\n' + + SAMPLE + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(1, 8), Fraction(5, 8)), -1), + 'uni_loop': (PROLOGUE + 's_mov_b32 s30, 2\nBB1:\n' + SAMPLE + SUB + 's_add_i32 s30, s30, -1\ns_cmp_lg_u32 s30, 0\n' + 's_cbranch_scc1 BB1\n' + EXPORT, (Fraction(-3, 8), Fraction(1, 8)), -1), +} +# name: (source, text of the refusal) +REFUSED = { + # The plain s_mov_b64 exec, s[N] restore of a mask saved before s_wqm is a lane-exec break too (main accepts the form). + 'restore_mov': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_mov_b64 exec, s[12:13]\nv_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. + 'exec_lo_const': (PROLOGUE + 's_mov_b32 exec_lo, -1\nv_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A mask saved before s_wqm exec, exec has the guest's helper lanes off, while every thread here starts + # with exec = 1: writing it back is a lane-exec break (review of ef786354). + 'restore': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # The same restore, then u -= 0.5 on the lanes it leaves on: the guest's helper keeps its stale u, the + # translation's helper takes the new one (measured by the reviewer on WARP and an RX 9070 XT). + 'restore_helper': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + 'v_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A kill export under v_cmpx before the op: the discard is a lane-exec break (it fails without it). + 'discard_break': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\nexp null off, off, off, off vm\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A 32-bit EXEC write keeps lanes 32..63 of the old mask in wave64: only the 64-bit forms are exact. + 'exec_lo_mask': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_mov_b32 exec_lo, vcc_lo\n' + 'v_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # The wave takes a VCC branch once for all lanes and runs the block with EXEC unchanged, while a lane here follows + # its own bit: it clears uniform_cf, so the sample after it is refused (#2659). + 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + SAMPLE + 'BB1:\n' + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'vcc_join': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + SUB + 'BB1:\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'loop': (PROLOGUE + 'BB1:\n' + SAMPLE + 's_waitcnt vmcnt(0)\nv_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccnz BB1\n' + + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # s_wqm of a narrowed EXEC is a no-op here while the guest turns the quad back on: a lane-exec break. + 'wqm_break': (PROLOGUE + CMPX + 's_wqm_b64 exec, exec\n' + SUB + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A scalar write inside the block an EXEC branch can skip happens once for the wave in the guest; a quad that + # votes to skip it would miss it (review of the first version): the branch is not voted, the op is refused. + 'scalar_in_block': (PROLOGUE + 's_mov_b32 s28, -1.0\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 's_mov_b32 s28, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\nv_mov_b32_e32 v1, s28\n' + + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'carry_in_block': (PROLOGUE + 's_mov_b64 s[28:29], exec\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\nv_add_co_u32_e64 v14, s[28:29], 0, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\ns_or_b64 exec, exec, s[28:29]\ns_waitcnt lgkmcnt(0)\nimage_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\ns_waitcnt vmcnt(0)\nexp mrt0 v10, v11, v12, v13 done vm\ns_endpgm\n', 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'exec_const_mask': (PROLOGUE + 's_mov_b64 s[12:13], exec\ns_mov_b64 exec, 1\nv_add_f32_e32 v2, 0.5, v2\ns_mov_b64 exec, s[12:13]\ns_waitcnt lgkmcnt(0)\nimage_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\ns_waitcnt vmcnt(0)\nexp mrt0 v10, v11, v12, v13 done vm\ns_endpgm\n', 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'kill_then_restore': (PROLOGUE + 's_mov_b64 s[12:13], exec\nv_cmpx_eq_u32_e32 0, v8\ns_cbranch_execnz BB1\ns_endpgm\nBB1:\ns_mov_b64 exec, s[12:13]\nv_add_f32_e32 v2, -0.5, v2\ns_waitcnt lgkmcnt(0)\nimage_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\ns_waitcnt vmcnt(0)\nexp mrt0 v10, v11, v12, v13 done vm\ns_endpgm\n', 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A bias that differs per lane (a join of two values) past a divergent EXEC is not drawn: refused by name. + 'bias_per_lane': (PROLOGUE + 'v_mov_b32_e32 v14, 1.0\nv_cmp_eq_u32_e32 vcc, 0, v8\nv_cndmask_b32_e32 v1, v1, v14, vcc\n' + + branch_on_x(0, '-0.5') + SAMPLE + EXPORT, + 'image_sample_b with a per-lane bias past a divergent EXEC'), +} +# llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources +WORDS_HEX = { + 'restore_mov': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' + '0d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e0c04febef10404067fc08cbf280f94f0010a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'inside_y': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003ef302027eff02067e0000803e0902087eff02047e0000003e90000e2c070d0c7ef00c0c10ff0c' + '06060000803e800e847d6a2480be040088bf80021c7e7fc08cbf280f94f0010ac4007e00fe88703f8cbf0f1800f80a0b0c' + '0d000081bf' + ), + 'exec_lo_const': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003ef302027eff02067e0000803e0902087ec103febef10404067fc08cbf280f94f0010ac400703f' + '8cbf0f1800f80a0b0c0d000081bf' + ), + 'restore_helper': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' + '0d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e7e0cfe87f10404067fc08cbf280f94f0010a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'discard_break': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d901000f8000000007fc08cbf280f94f0010a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'exec_lo_mask': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d6a03febef10404067fc08cbf280f94f0010a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'join_pixel': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d6a2480be010088bff10404067e00fe88' + '7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'join_helper': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8110847d6a2480be010088bff00404067e00fe88' + '7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'cmpx': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47df10404067fc08cbf280f94f0010ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'scc': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e098007bf030085bf7fc08cbf280f94f0010ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d6a2480be040088bff10404067fc08cbf' + '280f94f0010ac4007e00fe88703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'kill': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d010089bf000081bff10404067fc08cbf' + '280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'wqm_break': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d7e0afebef10404067fc08cbf280f94f0' + '010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'uni_loop': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e82039ebe7fc08cbf280f94f0010ac400f1040406' + '1ec11e811e8007bff9ff85bf703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'vcc_inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d030086bf7fc08cbf280f94f0010ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'vcc_join': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d010086bff10404067fc08cbf280f94f0' + '010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'loop': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7fc08cbf280f94f0010ac400703f8cbf8010847d' + 'faff87bf703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'scalar_in_block': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef3039cbe8210847d6a2480be010088bf80039cbe7e00fe881c02027e7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'restore': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e7e0cfe877fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'carry_in_block': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7e049cbe8210847d6a2480be020088bf0e1c0fd7' + '800001007e00fe887e1cfe887fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'exec_const_mask': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7e048cbe8104febef00404060c04febe7fc08cbf' + '280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'kill_then_restore': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7e048cbe8010a47d010089bf000081bf0c04febe' + 'f10404067fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'bias_per_lane': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef2021c7e8010847d011d02028010847d6a2480be010088bff10404067e00fe887fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), +} +BRANCH = re.compile(r'^(s_c?branch\w*) (BB\d+)$') + + +def resolve(source, sizes): + """The source with each label operand replaced by its SIMM16 (dwords after the next instruction).""" + lines = [line for line in source.splitlines() if line] + labels, at, off = {}, [], 0 + for line in lines: + if line.endswith(':'): + labels[line[:-1]] = off + else: + at.append(off) + off += sizes[len(at) - 1] + out = [] + for line in (line for line in lines if not line.endswith(':')): + m = BRANCH.match(line) + if m: + line = '%s %d' % (m.group(1), (labels[m.group(2)] - at[len(out)] - 4) // 4) + out.append(line) + return '\n'.join(out) + '\n' + + +def assemble(llvm_mc, source): + """Words of a labelled source: one pass with every branch at 0 sizes the instructions, the second encodes.""" + def encode(text): + run = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', + '-show-encoding'], input=text, capture_output=True, text=True, check=True) + return [bytes(int(b, 16) for b in m.group(1).split(',')) + for m in re.finditer(r'encoding: \[([^\]]*)\]', run.stdout)] + plain = [BRANCH.sub(r'\1 0', line) for line in source.splitlines() if line and not line.endswith(':')] + sizes = [len(w) for w in encode('\n'.join(plain) + '\n')] + assert len(sizes) == len(plain), (len(sizes), len(plain)) + return b''.join(encode(resolve(source, sizes))) + + +def all_sources(): + return dict({k: v[0] for k, v in FIXTURES.items()}, **{k: v[0] for k, v in REFUSED.items()}) + + +def words(name): + return bytes.fromhex(WORDS_HEX[name]) + + +def pipeline(name): + return G.Pipeline(VS_WORDS, words(name), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def refused(name, text): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (name, text, str(error)) + else: + raise AssertionError('%s accepted, expected %r' % (name, text)) + + +def reference(name): + """The texel the drawn pixel reads: LOD log2(4 |du/dx|) + bias (u is the same down a column), mip filter point.""" + _source, (u0, u1), bias = FIXTURES[name] + footprint = 4 * abs(u1 - u0) + lod = math.log2(footprint) + assert lod == int(lod), (name, footprint) + mip = min(max(int(lod) + bias, 0), 2) + size = 4 >> mip + wrapped = u0 - math.floor(u0) + return mip_cell(int(wrapped * size), int(Fraction(1, 4) * size), 0, mip) + + +CALL = 't = r0.SampleBias(q0, float3(F(v2), F(v3), F(v4)), F(v1));' + + +def controls(): + for name in FIXTURES: + text = pipeline(name).hlsl_ps() + assert text.count(CALL) == 1, (name, text) + assert 'SampleLevel' not in text, (name, text) + for name, (_source, text) in REFUSED.items(): + refused(name, text) + # The quad votes: the EXEC branches of inside, kill and join_pixel, one vote each; v_cmpx alone needs none. + for name, votes in (('inside', 1), ('kill', 1), ('cmpx', 0), ('join_pixel', 1), ('join_helper', 1), ('scc', 0), ('inside_y', 1)): + text = pipeline(name).hlsl_ps() + assert text.count('x2w_quad_any(exec)') == votes, (name, text) + # The gate is the vote's: with the EXEC rule of #2659 (the entry mask only) the divergent-EXEC fixtures are refused. + saved = G.Stage.derivative_exec_ok + G.Stage.derivative_exec_ok = lambda self: self.exec_known + try: + for name in ('cmpx', 'inside', 'kill'): + refused(name, 'image_sample_b needs implicit derivatives') + finally: + G.Stage.derivative_exec_ok = saved + # A lane-exec break before the sample keeps it refused: s_wqm of a narrowed EXEC is a no-op in the one-lane model. + refused('wqm_break', 'image_sample_b needs implicit derivatives') + # The drawn vote helper is the text the translation emits. + assert '\n'.join(G.QUAD_ANY_HLSL) in pipeline('inside').hlsl_ps() + cells = {name: reference(name) for name in FIXTURES} + print('image_sample_b after a join, under a v_cmpx EXEC, after a uniform branch, inside an EXEC branch and ' + 'past a kill branch: SampleBias; references %s' + % ', '.join('%s=%s' % kv for kv in cells.items())) + print('refused: inside or after a block a VCC branch skips, in a VCC loop, after s_wqm of a narrowed EXEC') + + +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = assemble(llvm_mc, source) + if built != words(name): + raise AssertionError('%s: assembled %s, recorded %s' % (name, built.hex(), WORDS_HEX[name])) + print('every fixture reassembles to its recorded words with %s' % llvm_mc) + + +def mutants(name, hlsl): + """HLSL variants that must read another texel: the branch write dropped, the EXEC guard of the u write dropped, + the bias dropped.""" + out = [] + write = re.search(r'\n\s*if \(exec & 1\) v2 = U\(-?0\.5 \+ F\(v2\)\);', hlsl) + if name.startswith('join'): + out.append(('without the branch write', hlsl.replace(write.group(0), ''))) + if name in ('cmpx', 'inside', 'kill'): + out.append(('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))) + out.append(('bias ignored', hlsl.replace(CALL, CALL.replace('F(v1))', '0.0)')))) + for label, text in out: + assert text != hlsl, (name, label) + return out + + +# The vote helper alone (QUAD_ANY_HLSL, the text the translation emits), drawn on the covered pixel (0, 0): a pixel shader +# whose bit is set on one lane of the quad only. The covered pixel answers 1 for every position of that lane, and each +# half of the helper is the only way to see one of them: the drawn lane is in row 0, column 0, so a lane at (1, 0) is +# seen through ddx_fine and a lane at (0, 1) through ddy_fine, and a lane at (1, 1) through both. Red is the answer. +VOTE_PS = """ +%s +float4 main(float4 pos : SV_Position) : SV_Target { + uint x = (uint)pos.x & 1u, y = (uint)pos.y & 1u; + return float4(x2w_quad_any(%s) ? 1.0 : 0.0, 0.0, 0.0, 1.0); +} +""" +ONE, ZERO = '3f800000,00000000,00000000,3f800000', '00000000,00000000,00000000,3f800000' +# name: (bit of the lane, red answer of the covered pixel); the quad is x, y in {0, 1}^2 +VOTE_CASES = { + 'lane_10': ('(x == 1u && y == 0u) ? 1u : 0u', ONE), + 'lane_01': ('(x == 0u && y == 1u) ? 1u : 0u', ONE), + 'lane_11': ('(x == 1u && y == 1u) ? 1u : 0u', ONE), + 'lane_00': ('(x == 0u && y == 0u) ? 1u : 0u', ONE), + 'none': ('0u', ZERO), +} +# what each case must stop answering when a half of the helper is dropped +VOTE_MUTANTS = { + 'lane_10': ('abs(ddx_fine(lane))', 'without the horizontal derivative'), + 'lane_01': ('abs(ddy_fine(row))', 'without the vertical derivative'), +} + + +def vote_hlsl(bit, mutant=None): + helper = '\n'.join(G.QUAD_ANY_HLSL) + if mutant: + assert mutant in helper, mutant + helper = helper.replace(mutant, '0.0') + return VOTE_PS % (helper, bit) + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + + def draw(vs, ps, expected, sampler): + run = subprocess.run([renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected] + + ([sampler] if sampler else []), capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name in FIXTURES: + pipe = pipeline(name) + hlsl = pipe.hlsl_ps() + sampler = [line for line in pipe.manifest().splitlines() if line.startswith(('smp ', 'smpl '))] + assert len(sampler) == 1, pipe.manifest() + want = reference(name) + ps = compile_hlsl(compiler, kind, hlsl, '%s_%s' % (name, kind), ps_profile, directory) + run = draw(vs, ps, want, sampler[0]) + if run.returncode: + raise AssertionError('%s %s %s: GPU differs from the CPU reference %s\n%s%s' + % (adapter, kind, name, want, run.stdout, run.stderr)) + seen = [] + for i, (label, text) in enumerate(mutants(name, hlsl)): + ps = compile_hlsl(compiler, kind, text, '%s_m%d_%s' % (name, i, kind), ps_profile, directory) + run = draw(vs, ps, want, sampler[0]) + got = re.search(r'actual=(\S+)', run.stderr) + if run.returncode == 0 or not got: + raise AssertionError('%s %s %s: mutant "%s" matched the reference\n%s%s' + % (adapter, kind, name, label, run.stdout, run.stderr)) + seen.append('%s -> %s' % (label, got.group(1))) + print('%s %s %s: GPU == CPU reference %s; %s' % (adapter, kind, name, want, '; '.join(seen)), + flush=True) + for name, (bit, want) in VOTE_CASES.items(): + ps = compile_hlsl(compiler, kind, vote_hlsl(bit), 'vote_%s_%s' % (name, kind), ps_profile, directory) + run = draw(vs, ps, want, None) + if run.returncode: + raise AssertionError('%s %s vote %s: GPU differs from the CPU reference %s\n%s%s' + % (adapter, kind, name, want, run.stdout, run.stderr)) + seen = [] + if name in VOTE_MUTANTS: + cut, label = VOTE_MUTANTS[name] + ps = compile_hlsl(compiler, kind, vote_hlsl(bit, cut), 'vote_%s_m_%s' % (name, kind), + ps_profile, directory) + run = draw(vs, ps, want, None) + got = re.search(r'actual=(\S+)', run.stderr) + if run.returncode == 0 or not got: + raise AssertionError('%s %s vote %s: the helper %s matched the reference\n%s%s' + % (adapter, kind, name, label, run.stdout, run.stderr)) + seen.append('%s -> %s' % (label, got.group(1))) + print('%s %s vote %s: GPU == CPU reference %s; %s' % (adapter, kind, name, want, '; '.join(seen)), + flush=True) + + +def main(): + if len(sys.argv) == 1 or sys.argv[1] == 'controls': + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + elif sys.argv[1] == 'draw' and len(sys.argv) in (5, 6): + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_d_check.py b/tests/startup_image_sample_d_check.py new file mode 100644 index 0000000000..d684232c5c --- /dev/null +++ b/tests/startup_image_sample_d_check.py @@ -0,0 +1,134 @@ +"""Explicit-gradient image_sample_d in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary <llvm-mc> reassemble every fixture source and compare it with the recorded words + +The address dwords of image_sample_d are ddx, then ddy (one register per coordinate axis each), then the coordinates. +The lowering must pass those registers to SampleGrad in that order: a 2D sample has six, a 2D array seven (the slice +last) and a volume nine. image_sample_c_d would need SampleCmpGrad (shader model 6.8) and is refused by name instead +of being sampled without its gradients. +""" +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_sample_l_check import POST, PRE # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, assemble, root_blob # noqa: E402 + +TAIL = 's[16:23], s[24:27] dmask:0xf dim:' +IMAGE = { + 'd2': 'image_sample_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd2nsa': 'image_sample_d v[4:7], [v0, v1, v2, v3, v1, v0], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'd3': 'image_sample_d v[4:7], v[0:15], ' + TAIL + 'SQ_RSRC_IMG_3D', + 'd2a': 'image_sample_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D_ARRAY', + 'd1': 'image_sample_d v[4:7], [v0, v1, v2], ' + TAIL + 'SQ_RSRC_IMG_1D', + 'cd': 'image_sample_c_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'do': 'image_sample_d_o v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D', + 'dtfe': 'image_sample_d v[4:5], v[0:7], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D tfe', + 'dglc': 'image_sample_d v[4:7], v[0:7], ' + TAIL + 'SQ_RSRC_IMG_2D glc', +} +WORDS = { + 'd2': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd2nsa': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf0c0f88f00004c4000102030100000000703f8cbf0f1800f804050607000081bf'), + 'd3': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf100f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd2a': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf280f88f00004c400703f8cbf0f1800f804050607000081bf'), + 'd1': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf020f88f00004c40001020000703f8cbf0f1800f804050607000081bf'), + 'cd': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080fa8f00004c400703f8cbf0f1800f804050607000081bf'), + 'do': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080fc8f00004c400703f8cbf0f1800f804050607000081bf'), + 'dtfe': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf080189f00004c400703f8cbf0f1800f804050607000081bf'), + 'dglc': bytes.fromhex('04040cf4000000fa800398be800399be80039abe80039bbef002007eff02027e0000803ef202047ef402067e7fc08cbf082f88f00004c400703f8cbf0f1800f804050607000081bf'), +} + + +def stage(name): + return G.Pipeline(VS_WORDS, WORDS[name], root_blob(flags=0)).hlsl_ps() + + +def grad_call(name): + """(location, ddx, ddy) register lists of the SampleGrad call.""" + call = re.search(r'SampleGrad\(([^;]*)\);', stage(name)) + assert call, name + parts = call.group(1).split('float')[1:] + assert len(parts) == 3, call.group(1) + return [re.findall(r'F\((v\d+)\)', part) for part in parts] + + +def refused(name, text): + try: + stage(name) + except G.Unsupported as error: + assert text in str(error), (name, str(error)) + else: + raise AssertionError('%s was accepted' % name) + + +def check_address_count(): + """A count that does not match the dimension is refused before any register is read.""" + for coords, count in (('[v0, v1, v2, v3, v1]', 5), ('[v0, v1, v2, v3, v1, v0, v2]', 7)): + bare = G.Stage.__new__(G.Stage) + try: + bare.image(['v5', coords, 's0'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x1'], 'd') + except G.Unsupported as error: + assert str(error) == 'image_sample_d with %d address registers' % count, (coords, error) + else: + raise AssertionError('image_sample_d accepted %d address registers' % count) + + +def check_lod_cap(): + """A guest sampler capped to MAX_LOD 0 keeps its cap: the static sampler carries it, so SampleGrad cannot reach mip 2. + + The cap fixture is the 2D program with `s_mov_b32 s26, 0` (80039abe) widened to the literal 0x04000000, mip filter + point (word 2 bits 27:26 = 1), words (0, 0, 0x04000000, 0). A mip filter of 0 keeps the ordinary sampler.""" + words = WORDS['d2'] + assert words.count(bytes.fromhex('80039abe')) == 1 + capped = words.replace(bytes.fromhex('80039abe'), bytes.fromhex('ff039abe') + (0x04000000).to_bytes(4, 'little')) + pipe = G.Pipeline(VS_WORDS, capped, root_blob(flags=0)) + assert 'SampleGrad(' in pipe.hlsl_ps() + lines = pipe.manifest().splitlines() + assert 'smpl 0 0x0 0x0 0x4000000 0x0' in lines and 'smp ' not in pipe.manifest(), pipe.manifest() + plain = G.Pipeline(VS_WORDS, words, root_blob(flags=0)) + plain.hlsl_ps() + assert 'smp 0 0x0 0x0 0x0 0x0' in plain.manifest().splitlines() and 'smpl' not in plain.manifest(), plain.manifest() + print('a capped constant sampler is carried to the static sampler; mip filter 0 keeps the ordinary one') + + +def controls(): + check_address_count() + check_lod_cap() + assert grad_call('d2') == [['v4', 'v5'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2') + assert grad_call('d2nsa') == [['v1', 'v0'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2nsa') + assert grad_call('d3') == [['v6', 'v7', 'v8'], ['v0', 'v1', 'v2'], ['v3', 'v4', 'v5']], grad_call('d3') + assert grad_call('d2a') == [['v4', 'v5', 'v6'], ['v0', 'v1'], ['v2', 'v3']], grad_call('d2a') + assert 'Texture2DArray' in stage('d2a') and 'Texture3D' in stage('d3') + print('2D, NSA 2D, 3D and 2D array pass ddx, ddy and the coordinates to SampleGrad in address order') + + refused('cd', 'image_sample_c_d') + refused('do', 'image_sample_d_o') + refused('d1', 'unverified 1D image d address or modifiers') + refused('dtfe', 'image_sample_d modifier tfe') + print('refused: compare, offset, 1D, tfe') + + assert grad_call('dglc') == grad_call('d2') # cache-policy bits do not change the sampled value + print('glc is accepted') + + +def check_binary(llvm_mc): + # The assembler takes the wide tuple spelling (8 VGPRs, 16 for a volume); the decoder lists the active ones. + for name, line in IMAGE.items(): + built = assemble(llvm_mc, PRE + line + '\n' + POST) + if built != WORDS[name]: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), WORDS[name].hex())) + print('fixture words match llvm-mc') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + else: + sys.exit(__doc__) diff --git a/tests/startup_image_sample_d_draw_check.py b/tests/startup_image_sample_d_draw_check.py new file mode 100644 index 0000000000..409aeca02a --- /dev/null +++ b/tests/startup_image_sample_d_draw_check.py @@ -0,0 +1,203 @@ +"""image_sample_d drawn on D3D12 (WARP and hardware), GPU readback against a CPU reference (Part of #1723). + + (no arguments) build the programs, translate them, check the CPU reference + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile (DXC ps_6_0, and FXC ps_5_1 when given) and draw against the + 4x4 two-slice, three-mip R32G32B32A32_FLOAT fixture of startup_image_3d.cpp + +One pixel stage samples four times with explicit gradients. The gradients, not the coordinates, pick the mip level: +rho = largest gradient component * 4 texels, so 0.25 -> mip 0, 0.5 -> mip 1, 1.0 -> mip 2 (exact powers of two, no +rounding ambiguity). Probes use ddx only, ddy only, a gradient on the second axis and the second array slice. +The expected colours come from the fixture formula red = (1 + x + 4y + 16s + 32m) / 128 evaluated here with +exact fractions. Mutants: a sampler capped to MAX_LOD 0 and SampleGrad replaced by an implicit Sample must both +return mip 0 on every probe, which the same draw must report as different from the expected colours. +""" +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import ( # noqa: E402 + FULLSCREEN_VS, + VS_WORDS, + CompileQueue, + compile_hlsl, + root_blob, +) +from startup_image_sample_c_border_check import ( # noqa: E402 + DIM_2D_ARRAY, + EXP_MRT0_V4_V7, + INLINE_FLOATS, + S_ENDPGM, + S_LOAD_DWORDX8, + S_WAIT_LGKM, + S_WAIT_VM, + f32_hex, + manifest_sampler, + mimg_seq, + s_mov_b32, + v_mov_inline, + v_mov_lit, +) + +IMG_SAMPLE_D = 0x22 +SIZE = 4 +LEVELS = 3 +# Point filters, mip filter point (word 2 bits 27:26 = 1), MIN_LOD 0 and MAX_LOD 2.0 (u4.8, word 1 bits 23:12). +SAMPLER_WORDS = (0, 2 * 256 << 12, 0x04000000, 0) +CAPPED_WORDS = (0, 0, 0x04000000, 0) +ADDR = 10 # v10..v16: ddx, ddy, coordinates, slice; v4..v7 receive the four probes + +# (u, v, slice, ddx, ddy) +PROBES = ( + (Fraction(5, 8), Fraction(3, 8), 0, (Fraction(1, 4), 0), (0, Fraction(1, 4))), + (Fraction(5, 8), Fraction(3, 8), 0, (Fraction(1, 2), 0), (0, 0)), + (Fraction(1, 8), Fraction(7, 8), 0, (0, 0), (0, 1)), + (Fraction(7, 8), Fraction(5, 8), 1, (0, Fraction(1, 2)), (0, 0)), +) + + +def bits(value): + return struct.unpack('<I', struct.pack('<f', float(value)))[0] + + +def mov_value(vdst, value): + raw = bits(value) + code = 0x80 if raw == 0 else INLINE_FLOATS.get(raw) + asm = 'v_mov_b32 v%d, %s' % (vdst, '0' if raw == 0 else '%#x' % raw) + return asm, (v_mov_inline(vdst, code) if code is not None else v_mov_lit(vdst, raw)) + + +def build_program(words): + lines = ['s_load_dwordx8 s[16:23], s[8:9], 0x0'] + code = bytearray(S_LOAD_DWORDX8) + for reg, val in zip((24, 25, 26, 27), words): + lines.append('s_mov_b32 s%d, %s' % (reg, '0' if val == 0 else '%#x' % val)) + code += s_mov_b32(reg, val) + lines.append('s_waitcnt lgkmcnt(0)') + code += S_WAIT_LGKM + for i, (u, v, slice_, ddx, ddy) in enumerate(PROBES): + for k, value in enumerate((*ddx, *ddy, u, v, slice_)): + asm, raw = mov_value(ADDR + k, value) + lines.append(asm) + code += raw + lines.append('image_sample_d v%d, v[%d:%d], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY' + % (4 + i, ADDR, ADDR + 6)) + code += mimg_seq(IMG_SAMPLE_D, 4 + i, ADDR, dmask=0x1, dim=DIM_2D_ARRAY) + lines += ['s_waitcnt vmcnt(0)', 'exp mrt0 v4, v5, v6, v7 done vm', 's_endpgm'] + code += S_WAIT_VM + EXP_MRT0_V4_V7 + S_ENDPGM + return '\n'.join(lines) + '\n', bytes(code) + + +def texel_red(x, y, s, m): + return Fraction(1 + x + 4 * y + 16 * s + 32 * m, 128) + + +def reference(max_lod=LEVELS - 1): + """Red channel of every probe: the level follows the largest gradient component, texel = floor(coord * size).""" + out = [] + for u, v, s, ddx, ddy in PROBES: + rho = max(abs(Fraction(c)) for c in (*ddx, *ddy)) * SIZE + m = 0 + while Fraction(2) ** (m + 1) <= rho and m < max_lod: + m += 1 + dim = SIZE >> m + out.append(texel_red(int(u * dim), int(v * dim), s, m)) + return out + + +def pipeline(code): + return G.Pipeline(VS_WORDS, code, root_blob()) + + +def check_disassembly(code): + off, decoded = 0, [] + while off < len(code): + size, mnemonic, asm, _ = D.decode_instruction(code, off) + assert size > 0 and 'unknown' not in mnemonic, (off, mnemonic, asm) + decoded.append(asm) + off += size + assert off == len(code) and decoded[-1] == 's_endpgm' + assert sum(a.startswith('image_sample_d') for a in decoded) == len(PROBES), decoded + + +def controls(): + _src, code = build_program(SAMPLER_WORDS) + check_disassembly(code) + hlsl = pipeline(code).hlsl_ps() + assert hlsl.count('SampleGrad(') == len(PROBES), hlsl + expected = reference() + # Mip 1 and 2 are reached, and every probe differs from its mip 0 value: the draw can tell the levels apart. + assert expected == [Fraction(7, 128), Fraction(34, 128), Fraction(65, 128), Fraction(54, 128)], expected + assert all(a != b for a, b in list(zip(expected, reference(0)))[1:]) and expected[0] == reference(0)[0] + assert 'smpl ' in pipeline(code).manifest() + print('four SampleGrad probes translate; reference reaches mips 0, 1, 2 and slice 1') + + +def run_draw(renderer, adapter, vs, ps, expected, sampler): + cmd = [renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected, sampler] + return subprocess.run(cmd, capture_output=True, text=True) + + +def check_draw(dxc, renderer, adapter, fxc=None): + _src, code = build_program(SAMPLER_WORDS) + pipe = pipeline(code) + sampler = manifest_sampler(pipe) + capped = manifest_sampler(pipeline(build_program(CAPPED_WORDS)[1])) + hlsl = pipe.hlsl_ps() + # Sample takes (sampler, uv) only: drop the two gradient arguments of each call. + gradient = r'float2\(F\(v\d+\), F\(v\d+\)\)' + implicit, changed = re.subn(rf', {gradient}, {gradient}(?=\);)', '', hlsl) + assert changed == hlsl.count('.SampleGrad(') == 4 + implicit = implicit.replace('.SampleGrad(', '.Sample(') + want = ','.join(f32_hex(float(r)) for r in reference()) + mip0 = ','.join(f32_hex(float(r)) for r in reference(0)) + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp, CompileQueue() as queue: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = queue.call(compile_hlsl, compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + grad = queue.call(compile_hlsl, compiler, kind, hlsl, 'grad_%s' % kind, ps_profile, directory) + run = run_draw(renderer, adapter, vs, grad, want, sampler) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if run.returncode != 0: + raise AssertionError('%s image_sample_d draw failed:\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s image_sample_d: %s' % (kind, want), flush=True) + + capped_run = run_draw(renderer, adapter, vs, grad, want, capped) + if capped_run.returncode == 0 or ('actual=' + mip0) not in capped_run.stderr: + raise AssertionError('%s capped-sampler mutant did not produce mip 0:\n%s\n%s' + % (kind, capped_run.stdout, capped_run.stderr)) + print('%s mutant MAX_LOD 0 caught' % kind, flush=True) + + flat = queue.call(compile_hlsl, compiler, kind, implicit, 'flat_%s' % kind, ps_profile, directory) + flat_run = run_draw(renderer, adapter, vs, flat, want, sampler) + if flat_run.returncode == 0 or ('actual=' + mip0) not in flat_run.stderr: + raise AssertionError('%s implicit-Sample mutant did not produce mip 0:\n%s\n%s' + % (kind, flat_run.stdout, flat_run.stderr)) + print('%s mutant implicit Sample caught' % kind, flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_implicit_lod_check.py b/tests/startup_image_sample_implicit_lod_check.py new file mode 100644 index 0000000000..2155049518 --- /dev/null +++ b/tests/startup_image_sample_implicit_lod_check.py @@ -0,0 +1,128 @@ +"""Plain image_sample keeps its implicit LOD past a uniform join in tools/startup/gfx2hlsl.py. + +A plain image_sample takes its LOD from the coordinate derivatives of the pixel quad. After a block boundary the +translation lowered it to SampleLevel(.., 0), so the guest's mip was lost. Where the rule image_sample_b and +image_get_lod already use holds (pixel stage, entry EXEC mask, wave-uniform control flow, no divergent back edge over +the call) it is now the implicit-LOD Sample; everywhere else it stays level 0 (no new refusal). + +Fixture (synthetic): the recorded c_lz stage of startup_image_sample_c_check with the MIMG opcode set to 0x20 +(image_sample, a 2-register address), the same edits as startup_gfx2hlsl_image_get_lod_check.py: + straight nothing before the sample -> Sample (as before) + branch s_cbranch_scc0 to the next instruction -> Sample + join a uniform forward join (scc), entry EXEC -> Sample + divergent s_mov_b32 exec_lo, 0 before the sample -> SampleLevel 0 (as before) + cf_<op> s_cbranch_vccz / vccnz / execz / execnz before it -> SampleLevel 0 (as before) + back_<op> a divergent back edge over the sample -> SampleLevel 0 (as before) + exit_<op> a divergent forward exit, loop closed by s_branch -> SampleLevel 0 (as before) + + (no arguments) translation controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_image_sample_c_check as C # noqa: E402 +from startup_gfx2hlsl_image_get_lod_check import AT, MIP_POINT, W2_AT, sopp # noqa: E402 +from startup_sampler_heap_check import VS_WORDS, root_blob # noqa: E402 + +IMAGE_SAMPLE = 0x20 + + +def stage(branch=False, divergent=False, join=False, cf_op=None, back_op=None, exit_op=None): + w = bytearray(C.WORDS['lz']) + w[W2_AT:W2_AT + 4] = struct.pack('<II', 0xbe9a03ff, MIP_POINT) # s_mov_b32 s26, literal (mip filter point) + w0, w1 = struct.unpack_from('<II', w, AT) + w0 = w0 & ~(0x7f << 18) & ~(0xf << 8) & ~(7 << 3) | IMAGE_SAMPLE << 18 | 1 << 8 | 1 << 3 + struct.pack_into('<II', w, AT, w0, w1) + code = bytes(w) + if back_op is not None: # a backward branch right after the sample, to it + code = code[:AT + 8] + sopp(back_op, -3) + code[AT + 8:] + if exit_op is not None: # a forward exit right after the sample, then an unconditional branch back to it + code = code[:AT + 8] + sopp(exit_op, 1) + sopp(2, -4) + code[AT + 8:] + insert = b'' + if branch: + insert += sopp(4, 0) + if join: + insert += bytes.fromhex('800380be') + bytes.fromhex('008006bf') + sopp(5, 1) + bytes.fromhex('810381be') + if divergent: + insert += bytes.fromhex('8003febe') + if cf_op is not None: + insert += bytes.fromhex('800380be') + sopp(cf_op, 1) + bytes.fromhex('810381be') + return code[:AT] + insert + code[AT:] if insert else code + + +def calls(**kwargs): + text = G.Pipeline(VS_WORDS, stage(**kwargs), root_blob(flags=0)).hlsl_ps() + return [l.strip() for l in text.splitlines() if '.Sample' in l and 'SamplerState' not in l] + + +def main(): + for name, kwargs in (('straight', {}), ('branch', {'branch': True}), ('join', {'join': True})): + got = calls(**kwargs) + assert len(got) == 1 and '.Sample(' in got[0] and 'SampleLevel' not in got[0], (name, got) + cases = [('divergent', {'divergent': True})] + cases += [('cf_%d' % op, {'cf_op': op}) for op in (6, 7, 8, 9)] # vccz, vccnz, execz, execnz + cases += [('back_%d' % op, {'back_op': op}) for op in (7, 9)] # vccnz, execnz back edge over the sample + cases += [('exit_%d' % op, {'exit_op': op}) for op in (7, 9)] # a divergent forward exit of a loop closed by s_branch + for name, kwargs in cases: + got = calls(**kwargs) + assert len(got) == 1 and 'SampleLevel(' in got[0] and got[0].rstrip(';').endswith(', 0)'), (name, got) + print('plain image_sample: implicit LOD past a uniform branch/join, level 0 with divergent EXEC or control flow') + + +def draw(dxc, renderer, adapter, fxc=None): + from startup_image_get_lod_view_check import FULLSCREEN_VS, UNPACK_XY, compile_hlsl, read_pixel + + # Use screen coordinates so one pixel step is four texels at mip 0. + # The 4x4 fixture must select physical mip 2 through either SRV window. + code = stage(join=True) + constant_coords = bytes.fromhex('f002007eff02027e0000803ef202047ef402067e') + assert code.count(constant_coords) == 1 + code = code.replace(constant_coords, UNPACK_XY) + lod_limits = bytes.fromhex('800399be') + assert code.count(lod_limits) == 1 + code = code.replace(lod_limits, struct.pack('<II', 0xbe9903ff, 2 << 20)) + pipe = G.Pipeline(VS_WORDS, code, root_blob(flags=0), ps_hw_inputs=(0x8000, 0x8000)) + source = pipe.hlsl_ps() + sampler, = (line for line in pipe.manifest().splitlines() if line.startswith('smpl ')) + implicit = '.Sample(q0, float2(F(v0), F(v1)))' + assert source.count(implicit) == 1 + forced_level_zero = source.replace(implicit, '.SampleLevel(q0, float2(F(v0), F(v1)), 0)') + + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + if fxc: + compilers.append(('fxc', fxc, 'vs_5_1', 'ps_5_1')) + work_root = HERE.parent / 'out' + work_root.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=work_root) as tmp: + work = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_' + kind, vs_profile, work) + guest = compile_hlsl(compiler, kind, source, 'implicit_' + kind, ps_profile, work) + forced = compile_hlsl(compiler, kind, forced_level_zero, 'forced_' + kind, ps_profile, work) + # Every channel exports the texel's red field. At (0,0), physical mip m stores (1+32m)/128. + wanted = struct.pack('>4f', *((65.0 / 128,) * 4)) + for window, first_mip in (('0/3', 0), ('1/2', 1)): + actual = read_pixel(renderer, adapter, str(vs), str(guest), sampler, window) + control = read_pixel(renderer, adapter, str(vs), str(forced), sampler, window) + wrong = struct.pack('>4f', *(((1 + 32 * first_mip) / 128,) * 4)) + assert actual == wanted, (kind, window, actual.hex(), wanted.hex()) + assert control == wrong and control != actual, (kind, window, control.hex(), wrong.hex()) + print(f'{kind} {adapter} {window}: implicit physical mip 2 {actual.hex()}, ' + f'forced physical mip {first_mip} {control.hex()}') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + main() + elif sys.argv[1] == 'draw' and len(sys.argv) in (5, 6): + draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_image_sample_l_check.py b/tests/startup_image_sample_l_check.py index d406e77dc8..c5b83c2fa5 100644 --- a/tests/startup_image_sample_l_check.py +++ b/tests/startup_image_sample_l_check.py @@ -243,7 +243,9 @@ def controls(): refused('offset', 'image_sample_l_o') refused('compare', 'image_sample_c_l') refused('gather', 'image_gather4_l') - refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') + # Since #2943 a cube lowers to TextureCube with the face address rebuilt as a direction, level after it. + cube = stage('cube') + assert 'TextureCube<float4>' in cube and 'x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))' in cube, cube refused('unorm', 'image_sample_l modifier unorm') refused('tfe', 'image_sample_l modifier tfe') # the extra status register is not modelled refused('a16', 'image_sample_l modifier a16') # packed 16-bit address: v[0:1] holds u, v and the level as halves @@ -251,11 +253,16 @@ def controls(): refused('d16', 'image_sample_l modifier d16') # half-precision result layout refused('r128', 'image_sample_l modifier r128') # four-dword resource descriptor refused('dmask0', 'empty dmask') - refused('dim1d', 'unverified 1D image sample address or modifiers') + # A 1D image has one coordinate and the level in the next address dword, so it lowers to Texture1D + # with the same SampleLevel call shape a 2D image uses (issue #1721). + one_d = stage('dim1d') + assert 'Texture1D<float4>' in one_d, one_d + assert re.search(r'SampleLevel\(\w+, F\(v0\), F\(v1\)\)', one_d), one_d refused('msaa', 'image dimension SQ_RSRC_IMG_') for name in RESERVED: refused(name, 'image_sample_l modifier reserved') # bits LLVM ignores must not be silently accepted - print('refused: offset, compare, gather, cube, 1D, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') + print('cube: TextureCube SampleLevel with x2w_cube_dir') + print('refused: offset, compare, gather, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') # Cache-policy bits do not change the sampled value: same lowering as the plain form. for name in ('glc', 'slc', 'dlc'): diff --git a/tests/startup_image_sample_l_join_check.py b/tests/startup_image_sample_l_join_check.py new file mode 100644 index 0000000000..3cbd4d4d77 --- /dev/null +++ b/tests/startup_image_sample_l_join_check.py @@ -0,0 +1,219 @@ +"""Source-built 2D point samplers with differing address modes or maximum LOD. + +No arguments: portable translation and independent dispatcher/sample oracle. +binary <llvm-mc>: reassemble every recorded fixture. +draw <dxc> <offscreen_check> <warp|hardware>: actual translated shader and manifest readback. +""" +import math +import re +import struct +import sys +import subprocess +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob +from startup_image_sample_b_flow_check import PS_INPUTS, assemble +from startup_image_get_lod_view_check import read_pixel + +CLAMP_XY = 2 | (2 << 3) +PRE = '''s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_mov_b32_e32 v0, 0x3f900000 +v_mov_b32_e32 v1, 0x3ec00000 +v_mov_b32_e32 v2, 1.0 +''' +POST = '''s_waitcnt vmcnt(0) +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm +''' + + +def arm(w0, w1=0x200000): + return (f's_mov_b32 s24, {w0:#x}\ns_mov_b32 s25, {w1:#x}\n' + 's_mov_b32 s26, 0x4000000\ns_mov_b32 s27, 0\n') + + +def source(name): + form = 'lz' if name == 'lz' else 'b' if name == 'implicit bias' else 'l' + pre = PRE + cond = 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + if name == 'nonuniform': + pre = 'v_mov_b32_e32 v8, v0\n' + pre + cond = 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + taken = arm(CLAMP_XY | 0x8000 if name == 'invalid mode' else CLAMP_XY) + if name == 'l_word1': + taken = arm(0, 0) + if name == 'high word1': + # Bit 24 of word1 sits above the translator's whole-word1 mask; a sampler keeping it must be refused. + taken = arm(CLAMP_XY, 0x200000 | (1 << 24)) + if name == 'partial': + taken = f's_mov_b32 s24, {CLAMP_XY:#x}\n' + tail = 's_mov_b32 s24, s9\n' if name == 'overwrite' else '' + if name == 'extra branch': + tail = 's_cbranch_scc1 BB3\nBB3:\n' + addr = 'v[0:1]' if form == 'lz' else 'v[0:2]' + return (pre + cond + arm(0) + 's_branch BB2\nBB1:\n' + taken + 'BB2:\n' + tail + + 's_waitcnt lgkmcnt(0)\n' + + f'image_sample_{form} v[4:7], {addr}, s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D\n' + + POST) + + +WORDS = { + 'l': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'lz': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f9cf00004c400703f8cbf0f1800f804050607000081bf', + 'l_word1': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe050082bf800398be800399beff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'nonuniform': '0003107e04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e8010847d070086bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'partial': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe010082bf920398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'overwrite': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe090398be7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'invalid mode': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe070082bfff0398be12800000ff0399be00002000ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'high word1': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002001ff039abe0000000480039bbe7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', + 'implicit bias': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe7fc08cbf080f94f00004c400703f8cbf0f1800f804050607000081bf', + 'extra branch': '04040cf4000000fa800398be800399beff039abe0000000480039bbeff02007e0000903fff02027e0000c03ef202047e098007bf070085bf800398beff0399be00002000ff039abe0000000480039bbe060082bf920398beff0399be00002000ff039abe0000000480039bbe000085bf7fc08cbf080f90f00004c400703f8cbf0f1800f804050607000081bf', +} +REFUSALS = { + 'nonuniform': 'descriptor operand s[24:27]', + 'partial': 'descriptor operand s[24:27]', + 'overwrite': 'descriptor operand s[24:27]', + 'invalid mode': 'unsupported joined sampler words', + 'high word1': 'unsupported joined sampler words', + 'implicit bias': 'image_sample_b with a sampler that is not constant', + 'extra branch': 'descriptor operand s[24:27]', +} + + +def pipeline(name): + return G.Pipeline(VS_WORDS, bytes.fromhex(WORDS[name]), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def texel(mip, x, y): + return struct.pack('>4f', (1 + x + 4 * y + 32 * mip) / 128, x, y, 2 * mip) + + +# u=1.125 wraps to x=0 or clamps to the final column; v=0.375 is interior. +EXPECTED = { + 'l': (texel(1, 0, 0), texel(1, 1, 0)), + 'lz': (texel(0, 0, 1), texel(0, 3, 1)), + 'l_word1': (texel(1, 0, 0), texel(0, 0, 1)), +} + + +def sampler_manifest(pipe, name): + lines = [line for line in pipe.manifest().splitlines() if line.startswith('smpl ')] + assert len(lines) == 2, lines + fields = [line.split() for line in lines] + assert [int(f[1]) for f in fields] == [0, 1], lines + samplers = [tuple(int(w, 0) for w in f[2:]) for f in fields] + expected = ({(0, 0, 1 << 26, 0), (0, 0x200000, 1 << 26, 0)} if name == 'l_word1' + else {(0, 0x200000, 1 << 26, 0), (CLAMP_XY, 0x200000, 1 << 26, 0)}) + assert set(samplers) == expected, samplers + return lines, samplers + + +def selected_texel(text, samplers, selector): + """Execute this authored dispatcher subset and evaluate its selected point sample independently.""" + regs = {} + pc, scc = 0, False + call = re.compile(r't = \(s(\d+) == (0x[0-9a-f]+)u \? r0\.SampleLevel\(q(\d+), ' + r'float2\(F\(v0\), F\(v1\)\), (F\(v2\)|0)\) : r0\.SampleLevel\(q(\d+), ' + r'float2\(F\(v0\), F\(v1\)\), \4\)\);') + for block in re.finditer(r'^\s*if \(pc == (\d+)\) \{\n(.*?)^\s*\}', text, re.M | re.S): + if int(block[1]) != pc: + continue + for line in block[2].splitlines(): + line = line.strip() + m = re.fullmatch(r'([sv]\d+) = (0x[0-9a-f]+)u;', line) + if m: + regs[m[1]] = int(m[2], 16) + continue + m = re.fullmatch(r'scc = ud1 != (0x[0-9a-f]+)u;', line) + if m: + scc = selector != int(m[1], 16) + continue + m = re.fullmatch(r'pc = \(scc\) \? (\d+) : (\d+);', line) + if m: + pc = int(m[1 if scc else 2]) + continue + m = re.fullmatch(r'pc = (\d+);', line) + if m: + pc = int(m[1]) + continue + m = call.fullmatch(line) + if m: + q = int(m[3] if regs['s' + m[1]] == int(m[2], 16) else m[5]) + def f32(reg): + return struct.unpack('<f', struct.pack('<I', regs[reg]))[0] + mip = int(f32('v2')) if m[4] != '0' else 0 + w0, w1, _, _ = samplers[q] + mip = min(max(mip, (w1 & 0xfff) // 256), ((w1 >> 12) & 0xfff) // 256) + size = 4 >> mip + def address(coord, mode): + index = math.floor(coord * size) + return index % size if mode == 0 else min(max(index, 0), size - 1) + return texel(mip, address(f32('v0'), w0 & 7), address(f32('v1'), (w0 >> 3) & 7)) + raise AssertionError(f'unmodelled dispatcher statement: {line}') + raise AssertionError('dispatcher never sampled') + + +def controls(): + for name, expected in EXPECTED.items(): + pipe = pipeline(name) + text = pipe.hlsl_ps() + _, samplers = sampler_manifest(pipe, name) + assert 'udsrc 1 rootconst 1 0' in pipe.manifest() + assert expected[0] != expected[1] + for selector, want in zip((0, 0x3f800000), expected): + assert selected_texel(text, samplers, selector) == want, (name, selector) + assert selected_texel(text, samplers[::-1], selector) != want, (name, selector, 'swapped') + for name, reason in REFUSALS.items(): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert reason in str(error), (name, reason, str(error)) + else: + raise AssertionError(f'{name} unexpectedly accepted') + print(f'uniform sampler diamond: {len(EXPECTED)} forms, both selector outcomes, ' + f'swapped bindings and {len(REFUSALS)} refusal controls passed') + + +def binary(llvm_mc): + for name, encoded in WORDS.items(): + assert assemble(llvm_mc, source(name)) == bytes.fromhex(encoded), name + print(f'all {len(WORDS)} authored fixtures reassemble exactly') + + +def draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + for name, expected in EXPECTED.items(): + pipe = pipeline(name) + ps = compile_hlsl(dxc, 'dxc', pipe.hlsl_ps(), f'joined_{name}', 'ps_6_0', directory) + lines, _ = sampler_manifest(pipe, name) + manifest = '\n'.join(lines) + for selector, want in enumerate(expected): + got = read_pixel(renderer, adapter, vs, ps, manifest, '0/3', selector=selector) + assert got == want, (name, selector, got.hex(), want.hex()) + swapped = '\n'.join(f'smpl {i} ' + ' '.join(line.split()[2:]) for i, line in enumerate(reversed(lines))) + got = read_pixel(renderer, adapter, vs, ps, swapped, '0/3', selector=0) + assert got == expected[1] and got != expected[0], (name, 'swapped', got.hex()) + print(f'{name}: actual uniform root selector and swapped binding readback matched') + + +if __name__ == '__main__': + args = sys.argv[1:] + if not args: + controls() + elif args[0] == 'binary' and len(args) == 2: + binary(args[1]) + elif args[0] == 'draw' and len(args) == 4: + draw(*args[1:]) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_image_store.cpp b/tests/startup_image_store.cpp index a428055be9..d6e7ff9f57 100644 --- a/tests/startup_image_store.cpp +++ b/tests/startup_image_store.cpp @@ -1,11 +1,13 @@ // Desktop readback for tools/startup/gfx2hlsl.py's pixel-stage image_store (#1996 item F). // // The translated pixel shader stores to w0 : register(u0), a RWTexture2D<float4>, and reads its entry -// constants from cbuffer entry : register(b0). This draws one pixel with that shader and a source-built -// full-screen vertex shader into a 4x4 R32G32B32A32_FLOAT texture whose texels all start as -1.0, then -// reads every texel back. The caller names the one texel it expects the store to change and its value; -// every other texel must still hold -1.0. +// constants from cbuffer entry : register(b0). This draws one or two pixels (coverage) with that shader +// and a source-built full-screen vertex shader into a 4x4 R32G32B32A32_FLOAT texture whose texels all +// start as -1.0, then reads every texel back. The caller names the one texel it expects the store to +// change and its value; every other texel must still hold -1.0. Coverage 2 uses a 2x1 viewport so two +// invocations run in one draw. #include "desktop_gpu.h" +#include "startup_stubs/typed_uav_load.h" #include <cstdint> #include <cstdio> @@ -54,8 +56,9 @@ ComPtr<ID3D12RootSignature> store_root(ID3D12Device* device) // Returns 0 when texel (x, y) holds expected and every other texel holds -1.0; otherwise prints the first // differing texel as "texel_mismatch x=.. y=.. expected=.. actual=.." and returns 1. int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, - const std::uint32_t expected[4]) + const std::uint32_t expected[4], unsigned coverage) { + if (coverage != 1 && coverage != 2) throw std::runtime_error("Image store coverage is not 1 or 2"); if (x >= side || y >= side) throw std::runtime_error("Expected a texel inside the 4x4 image"); const auto vs = read_shader(vertex_path); const auto ps = read_shader(pixel_path); @@ -102,7 +105,8 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con upload->Unmap(0, nullptr); D3D12_RESOURCE_DESC rd = td; - rd.Width = rd.Height = 1; + rd.Width = coverage; + rd.Height = 1; rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {0.0f, 0.0f, 0.0f, 0.0f}}; const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); @@ -130,8 +134,8 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con const std::uint32_t constants[entry_constants] = {0, 0, 0, 0}; // ud0 = 0: plain triangles list->SetGraphicsRoot32BitConstants(0, entry_constants, constants, 0); list->SetGraphicsRootDescriptorTable(1, views->GetGPUDescriptorHandleForHeapStart()); - const D3D12_VIEWPORT viewport{0, 0, 1, 1, 0, 1}; - const D3D12_RECT scissor{0, 0, 1, 1}; + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(coverage), 1, 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast<LONG>(coverage), 1}; list->RSSetViewports(1, &viewport); list->RSSetScissorRects(1, &scissor); list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); @@ -164,3 +168,34 @@ int check_startup_image_store(ID3D12Device* device, const char* vertex_path, con if (!result) std::printf("image store: texel (%u, %u) written, %u others untouched\n", x, y, side * side - 1); return result; } + +// Colour formats a pixel UAV may store. None of these is an R32 typed-load format, so a missing +// UAV_TYPED_LOAD bit, or a device without TypedUAVLoadAdditionalFormats, is a real refusal. +// The function does not create a command list and does not draw. +const char* check_startup_image_store_typed_load(ID3D12Device* device) +{ + D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; + const bool options_ok = SUCCEEDED(check_feature(device, D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))); + const bool additional = options_ok && options.TypedUAVLoadAdditionalFormats; + const DXGI_FORMAT candidates[] = { + DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16B16A16_UNORM, + DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R32G32B32A32_FLOAT, + }; + for (DXGI_FORMAT format : candidates) { + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(check_feature(device, D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support)))) continue; + if (typed_uav_load_refusal(format, support.Support2, additional)) { + std::fprintf(stderr, "typed_uav_load_refused format=%d\n", static_cast<int>(format)); + return "typed_uav_load_refused"; + } + } + // Every queried format can load on this device. The same helper must still refuse a cleared + // UAV_TYPED_LOAD bit, and this path still returns before any draw. + if (typed_uav_load_refusal(DXGI_FORMAT_R11G11B10_FLOAT, 0, additional)) { + std::fprintf(stderr, "typed_uav_load_refused format=%d support2=0\n", + static_cast<int>(DXGI_FORMAT_R11G11B10_FLOAT)); + return "typed_uav_load_refused"; + } + return nullptr; +} diff --git a/tests/startup_import_gfx10_tables_cli_check.py b/tests/startup_import_gfx10_tables_cli_check.py new file mode 100644 index 0000000000..dd1f1bde2e --- /dev/null +++ b/tests/startup_import_gfx10_tables_cli_check.py @@ -0,0 +1,642 @@ +#!/usr/bin/env python3 +"""Offline unit, CLI, atomic-write, path-guard, and mutation suite for tools/startup/import_gfx10_tables.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import os +from pathlib import Path +import re +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +STARTUP_DIR = TOOLS_DIR / "startup" +TOOL = STARTUP_DIR / "import_gfx10_tables.py" +sys.path.insert(0, str(STARTUP_DIR)) +sys.path.insert(0, str(TOOLS_DIR)) +import disasm_rdna2 # noqa: E402 +import import_gfx10_tables # noqa: E402 + + +def _build_synthetic_opcodes_rs( + *, + notice: str = "// Synthetic Mesa GFX10 notice\n//\n\n", + include_marker: bool = True, + omit_table: str | None = None, + empty_table: str | None = None, + overrides: dict[str, list[tuple[int, str]]] | None = None, +) -> str: + parts = [notice] + if include_marker: + parts.append("// Each table maps opcode index to mnemonic.\n\n") + custom = overrides or {} + for idx, table in enumerate(import_gfx10_tables.TABLES): + if table == omit_table: + continue + if table == empty_table: + body = "" + else: + rows = custom.get(table, [(idx & 0x3, f"syn_{table.lower()}_{idx}")]) + body = "\n".join(f' (0x{op:02x}, "{name}"),' for op, name in rows) + if body: + body = "\n" + body + "\n" + parts.append(f"const {table}: &[(u16, &str)] = &[{body}];\n") + return "".join(parts) + + +def _sha256_lf(raw: bytes) -> str: + return hashlib.sha256(raw.replace(b"\r\n", b"\n")).hexdigest() + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _tmp_files(directory: Path) -> list[Path]: + return [p for p in directory.iterdir() if p.suffix == ".tmp"] + + +class ImportGfx10TablesPositiveTests(unittest.TestCase): + def test_synthetic_merge_strips_e32_e64_preserves_existing_and_writes_atomically(self) -> None: + # Leave opcodes 0x01 in VOP1/VOP2 and 0x128 in VOP3 absent so disasm_rdna2 fills them + # and strips _e32 / _e64, while pinning 0x00 in SOPP to verify existing entries win. + overrides = { + "SOPP": [(0x00, "custom_nop_keep")], + "VOP1": [(0x00, "v_nop")], + "VOP2": [(0x03, "v_add_f32")], + "VOP3": [(0x140, "v_mad_legacy_f32")], + "VINTRP": [(0x00, "v_interp_p1_f32"), (0x02, "v_interp_mov_f32")], + "SMEM": [(0x01, "s_load_dwordx2")], + "MIMG": [(0x00, "image_load")], + } + notice = "// Synthetic notice header\n// Line 2\n\n" + text = _build_synthetic_opcodes_rs(notice=notice, overrides=overrides) + raw_crlf = text.replace("\n", "\r\n").encode("utf-8") + digest = _sha256_lf(raw_crlf) + + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + rs_path = base / "opcodes.rs" + rs_path.write_bytes(raw_crlf) + nested_out = base / "nested" / "sub" / "gfx1013_isa_tables.inl" + self.assertFalse(nested_out.parent.exists()) + + direct_out = io.StringIO() + with redirect_stdout(direct_out): + generated = import_gfx10_tables.generate(rs_path, expected_sha256=digest) + + self.assertTrue(generated.startswith(notice)) + self.assertIn("// Generated by tools/startup/import_gfx10_tables.py.", generated) + self.assertNotIn("\r", generated) + + # Existing opcodes.rs entry is preserved over disasm_rdna2 SOPP_OPS[0x00] = "s_nop". + sopp_block = re.search(r"constexpr const char\* sopp_names\[\] = \{(.*?)\};", generated, re.S) + self.assertIsNotNone(sopp_block) + self.assertIn('"custom_nop_keep"', sopp_block.group(1)) + self.assertIn('"s_endpgm"', sopp_block.group(1)) + + # VOP1_OPS[0x01] = "v_mov_b32_e32" -> "v_mov_b32"; VOP2_OPS[0x01] = "v_cndmask_b32_e32" -> "v_cndmask_b32". + vop1_block = re.search(r"constexpr const char\* vop1_names\[\] = \{(.*?)\};", generated, re.S) + vop2_block = re.search(r"constexpr const char\* vop2_names\[\] = \{(.*?)\};", generated, re.S) + self.assertIn('"v_mov_b32"', vop1_block.group(1)) + self.assertNotIn("_e32", vop1_block.group(1)) + self.assertIn('"v_cndmask_b32"', vop2_block.group(1)) + self.assertNotIn("_e32", vop2_block.group(1)) + + # VOP3_NATIVE_OPS[0x128] = "v_add_co_ci_u32_e64" -> "v_add_co_ci_u32" and INTERP_F16_OPS merged. + vop3_block = re.search(r"constexpr const char\* vop3_names\[\] = \{(.*?)\};", generated, re.S) + self.assertIn('"v_add_co_ci_u32"', vop3_block.group(1)) + self.assertIn('"v_interp_p1ll_f16"', vop3_block.group(1)) + self.assertNotIn("_e64", vop3_block.group(1)) + + # MIMG_BVH_OPS merged into MIMG and SMEM string entries imported. + mimg_block = re.search(r"constexpr const char\* mimg_names\[\] = \{(.*?)\};", generated, re.S) + smem_block = re.search(r"constexpr const char\* smem_names\[\] = \{(.*?)\};", generated, re.S) + self.assertIn('"image_bvh_intersect_ray"', mimg_block.group(1)) + self.assertIn('"s_load_dword"', smem_block.group(1)) + + # VINTRP has no disasm_rdna2 table and gap at index 1 emits nullptr. + vintrp_block = re.search(r"constexpr const char\* vintrp_names\[\] = \{(.*?)\};", generated, re.S) + self.assertIn('"v_interp_p1_f32", nullptr, "v_interp_mov_f32"', vintrp_block.group(1)) + + # Verify expected X2W addition count matches summary stdout. + expected_tables = {t for t in import_gfx10_tables.TABLES} + self.assertEqual(len(expected_tables), len(import_gfx10_tables.TABLES)) + self.assertIn("Imported ", direct_out.getvalue()) + + # CLI atomic write into missing nested directory, checking os.replace & 0 temps. + real_replace = os.replace + replaced_pairs: list[tuple[Path, Path]] = [] + + def tracking_replace(src, dst): + src_p, dst_p = Path(src), Path(dst) + replaced_pairs.append((src_p, dst_p)) + self.assertEqual(src_p.parent.resolve(), dst_p.parent.resolve()) + self.assertEqual(src_p.suffix, ".tmp") + return real_replace(src, dst) + + with ( + mock.patch.object(import_gfx10_tables, "SHA256", digest), + mock.patch.object(import_gfx10_tables.os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main(import_gfx10_tables, [str(rs_path), str(nested_out)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("Imported ", out) + self.assertEqual(nested_out.read_text(encoding="utf-8"), generated) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["gfx1013_isa_tables.inl"]) + self.assertEqual(len(replaced_pairs), 1) + + # Overwrite stale file via argv=None forwarding sys.argv. + nested_out.write_text("stale\n", encoding="utf-8") + with ( + mock.patch.object(import_gfx10_tables, "SHA256", digest), + mock.patch.object(sys, "argv", [str(TOOL), str(rs_path), str(nested_out)]), + ): + code_none, _, err_none = _run_main(import_gfx10_tables, None) + self.assertEqual(code_none, 0, err_none) + self.assertEqual(nested_out.read_text(encoding="utf-8"), generated) + self.assertEqual(_tmp_files(nested_out.parent), []) + + +class ImportGfx10TablesNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + allow_stdout: bool = False, + ) -> str: + code, out, err = _run_main(import_gfx10_tables, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + if not allow_stdout: + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + if not allow_stdout: + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_sha256_mismatch_and_non_utf8_refused(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + rs_path = base / "opcodes.rs" + rs_path.write_text(_build_synthetic_opcodes_rs(), encoding="utf-8") + absent_out = base / "absent_dir" / "tables.inl" + + # Default SHA256 rejects synthetic opcodes.rs both in generate() and CLI/__main__. + with self.assertRaises(ValueError): + import_gfx10_tables.generate(rs_path) + self._assert_clean_failure( + [str(rs_path), str(absent_out)], + expected_code=1, + fragments=("9376fd6",), + ) + self.assertFalse(absent_out.parent.exists()) + + # __main__ entrypoint exits 1 cleanly without traceback. + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(rs_path), str(absent_out)]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("9376fd6", stderr_m.getvalue()) + + # Non-UTF-8 bytes (even with matching SHA256) fail cleanly with 0 temps and preserved output. + bad_bytes = b"// Each table\n\xff\xfe\x80\n" + bad_digest = _sha256_lf(bad_bytes) + bad_rs = base / "bad_utf8.rs" + bad_rs.write_bytes(bad_bytes) + existing_out = base / "existing.inl" + existing_out.write_text("KEEP", encoding="utf-8") + with self.assertRaises(UnicodeDecodeError): + import_gfx10_tables.generate(bad_rs, expected_sha256=bad_digest) + with mock.patch.object(import_gfx10_tables, "SHA256", bad_digest): + self._assert_clean_failure( + [str(bad_rs), str(existing_out)], + expected_code=1, + fragments=("utf-8",), + check_subprocess=False, + ) + self.assertEqual(existing_out.read_text(encoding="utf-8"), "KEEP") + self.assertEqual(_tmp_files(base), []) + + def test_missing_marker_missing_table_and_empty_table_refusals(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + out_path = base / "out" / "tables.inl" + + cases = [ + ("missing_marker", _build_synthetic_opcodes_rs(include_marker=False), ("each table",)), + ("missing_table_vop3", _build_synthetic_opcodes_rs(omit_table="VOP3"), ("missing vop3 table",)), + ("missing_table_vintrp", _build_synthetic_opcodes_rs(omit_table="VINTRP"), ("missing vintrp table",)), + ("empty_table_sopp", _build_synthetic_opcodes_rs(empty_table="SOPP"), ("empty sopp table",)), + ("empty_table_vintrp", _build_synthetic_opcodes_rs(empty_table="VINTRP"), ("empty vintrp table",)), + ] + for idx, (label, text, frags) in enumerate(cases): + with self.subTest(case=label): + rs_path = base / f"{label}_{idx}.rs" + rs_path.write_text(text, encoding="utf-8") + digest = _sha256_lf(text.encode("utf-8")) + with self.assertRaises(ValueError) as ctx: + import_gfx10_tables.generate(rs_path, expected_sha256=digest) + self.assertNotIsInstance(ctx.exception, TypeError) + for frag in frags: + self.assertIn(frag, str(ctx.exception).lower()) + with mock.patch.object(import_gfx10_tables, "SHA256", digest): + self._assert_clean_failure( + [str(rs_path), str(out_path)], + expected_code=1, + fragments=frags, + check_subprocess=False, + ) + self.assertFalse(out_path.parent.exists()) + + def test_hostile_input_and_output_paths_leave_zero_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + rs_path = base / "opcodes.rs" + rs_text = _build_synthetic_opcodes_rs() + rs_path.write_text(rs_text, encoding="utf-8") + dir_rs = base / "dir_rs" + dir_rs.mkdir() + sub_dir = base / "sub" + sub_dir.mkdir() + out_dir = base / "out_dir" + out_dir.mkdir() + file_parent = base / "regular_parent.txt" + file_parent.write_text("KEEP_PARENT", encoding="utf-8") + hardlink_out = base / "hardlink.inl" + hardlink_out.hardlink_to(rs_path) + absent_out = base / "absent_dir" / "tables.inl" + + with ( + mock.patch.object( + import_gfx10_tables, + "generate", + side_effect=AssertionError("generate called for invalid paths"), + ), + mock.patch.object( + import_gfx10_tables, + "_write_atomic", + side_effect=AssertionError("_write_atomic called for invalid paths"), + ), + ): + for label, argv, frags, check_sub in ( + ("missing_input", [str(base / "missing.rs"), str(absent_out)], ("not found",), True), + ("dir_input", [str(dir_rs), str(absent_out)], ("directory",), True), + ("output_is_dir", [str(rs_path), str(out_dir)], ("directory",), True), + ("parent_is_file", [str(rs_path), str(file_parent / "tables.inl")], ("not a directory",), True), + ( + "ancestor_is_file", + [str(rs_path), str(file_parent / "deep" / "tables.inl")], + ("not a directory",), + True, + ), + ("same_path", [str(rs_path), str(rs_path)], ("must differ",), True), + ("resolve_alias", [str(rs_path), str(sub_dir / ".." / "opcodes.rs")], ("must differ",), True), + ("hardlink_samefile", [str(rs_path), str(hardlink_out)], ("must differ",), True), + ): + with self.subTest(case=label): + self._assert_clean_failure(argv, expected_code=1, fragments=frags, check_subprocess=check_sub) + + # Non-regular-file input (e.g. FIFO/device simulated via Path.is_file=False). + with mock.patch.object(Path, "is_file", return_value=False): + self._assert_clean_failure( + [str(rs_path), str(absent_out)], + expected_code=1, + fragments=("not a regular file",), + check_subprocess=False, + ) + + # Symlink output guard (mocked unconditionally + live/dangling if OS allows). + with mock.patch.object(Path, "is_symlink", return_value=True): + self._assert_clean_failure( + [str(rs_path), str(out_dir / "mock_link.inl")], + expected_code=1, + fragments=("symlink",), + check_subprocess=False, + ) + + self.assertFalse(absent_out.parent.exists()) + self.assertEqual(rs_path.read_text(encoding="utf-8"), rs_text) + self.assertEqual(file_parent.read_text(encoding="utf-8"), "KEEP_PARENT") + self.assertEqual(list(out_dir.iterdir()), []) + self.assertEqual(_tmp_files(base), []) + + live_link = out_dir / "live_link.inl" + dangling_link = out_dir / "dangling_link.inl" + real_target = out_dir / "real.inl" + real_target.write_text("UNTOUCHED", encoding="utf-8") + try: + live_link.symlink_to(real_target) + dangling_link.symlink_to(out_dir / "missing.inl") + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + else: + for label, link in (("live_symlink", live_link), ("dangling_symlink", dangling_link)): + with self.subTest(case=label): + self._assert_clean_failure( + [str(rs_path), str(link)], + expected_code=1, + fragments=("symlink",), + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "UNTOUCHED") + + def test_os_replace_and_write_failures_preserve_output_and_clean_temps(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + rs_path = base / "opcodes.rs" + rs_text = _build_synthetic_opcodes_rs() + rs_path.write_text(rs_text, encoding="utf-8") + digest = _sha256_lf(rs_text.encode("utf-8")) + out_dir = base / "out_dir" + out_dir.mkdir() + out_inl = out_dir / "gfx1013_isa_tables.inl" + out_inl.write_text("ORIGINAL_CONTENT", encoding="utf-8") + + with ( + mock.patch.object(import_gfx10_tables, "SHA256", digest), + mock.patch.object(import_gfx10_tables.os, "replace", side_effect=OSError("simulated replace failure")), + ): + self._assert_clean_failure( + [str(rs_path), str(out_inl)], + expected_code=1, + fragments=("simulated replace failure",), + check_subprocess=False, + allow_stdout=True, + ) + + self.assertEqual(out_inl.read_text(encoding="utf-8"), "ORIGINAL_CONTENT") + self.assertEqual([p.name for p in out_dir.iterdir()], ["gfx1013_isa_tables.inl"]) + + # Temp write failure (e.g. disk full) unlinks temp file and preserves original output. + with ( + mock.patch.object(import_gfx10_tables, "SHA256", digest), + mock.patch.object(import_gfx10_tables, "generate", return_value="NEW_CONTENT"), + ): + real_ntf = tempfile.NamedTemporaryFile + + def failing_ntf(*args, **kwargs): + handle = real_ntf(*args, **kwargs) + orig_write = handle.write + + def boom(_text): + raise OSError("simulated disk full") + + handle.write = boom + handle._orig_write = orig_write + return handle + + with mock.patch.object(import_gfx10_tables.tempfile, "NamedTemporaryFile", side_effect=failing_ntf): + self._assert_clean_failure( + [str(rs_path), str(out_inl)], + expected_code=1, + fragments=("simulated disk full",), + check_subprocess=False, + ) + + self.assertEqual(out_inl.read_text(encoding="utf-8"), "ORIGINAL_CONTENT") + self.assertEqual([p.name for p in out_dir.iterdir()], ["gfx1013_isa_tables.inl"]) + + def test_argparse_errors_and_help(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + rs_path = Path(tmp) / "opcodes.rs" + rs_path.write_text("x", encoding="utf-8") + help_proc = _run_subprocess("--help") + self.assertEqual(help_proc.returncode, 0) + self.assertIn("opcodes_rs", help_proc.stdout) + self.assertIn("output", help_proc.stdout) + self.assertEqual(help_proc.stderr, "") + + for argv, frags in ( + ([], ("required",)), + ([str(rs_path)], ("required",)), + ([str(rs_path), str(Path(tmp) / "out.inl"), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure(argv, expected_code=None, fragments=frags) + + def test_fast_self_mutation_controls(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + rs_text = _build_synthetic_opcodes_rs() + rs_path = base / "opcodes.rs" + rs_path.write_text(rs_text, encoding="utf-8") + digest = _sha256_lf(rs_text.encode("utf-8")) + + no_marker_text = _build_synthetic_opcodes_rs(include_marker=False) + no_marker_rs = base / "no_marker.rs" + no_marker_rs.write_text(no_marker_text, encoding="utf-8") + no_marker_digest = _sha256_lf(no_marker_text.encode("utf-8")) + + missing_tbl_text = _build_synthetic_opcodes_rs(omit_table="VOP3") + missing_tbl_rs = base / "missing_tbl.rs" + missing_tbl_rs.write_text(missing_tbl_text, encoding="utf-8") + missing_tbl_digest = _sha256_lf(missing_tbl_text.encode("utf-8")) + + empty_sopp_text = _build_synthetic_opcodes_rs(empty_table="SOPP") + empty_sopp_rs = base / "empty_sopp.rs" + empty_sopp_rs.write_text(empty_sopp_text, encoding="utf-8") + empty_sopp_digest = _sha256_lf(empty_sopp_text.encode("utf-8")) + + hardlink_out = base / "hardlink.inl" + hardlink_out.hardlink_to(rs_path) + file_parent = base / "file_parent.txt" + file_parent.write_text("KEEP", encoding="utf-8") + out_dir = base / "out_dir" + out_dir.mkdir() + out_inl = out_dir / "tables.inl" + out_inl.write_text("ORIGINAL", encoding="utf-8") + + def check_drop_sha256(mod): + with redirect_stdout(io.StringIO()), self.assertRaises(AssertionError): + with self.assertRaises(ValueError): + mod.generate(rs_path) + + def check_drop_marker(mod): + with redirect_stdout(io.StringIO()), self.assertRaises(AssertionError): + with self.assertRaises(ValueError): + mod.generate(no_marker_rs, expected_sha256=no_marker_digest) + + def check_drop_table_match(mod): + try: + with redirect_stdout(io.StringIO()): + mod.generate(missing_tbl_rs, expected_sha256=missing_tbl_digest) + except ValueError: + self.fail("expected mutant to fail with TypeError instead of ValueError") + except TypeError: + pass + + def check_drop_empty_entries(mod): + with redirect_stdout(io.StringIO()), self.assertRaises(AssertionError): + with self.assertRaises(ValueError): + mod.generate(empty_sopp_rs, expected_sha256=empty_sopp_digest) + + def check_drop_symlink(mod): + with mock.patch.object(Path, "is_symlink", return_value=True): + _, _, err = _run_main(mod, [str(rs_path), str(out_dir / "sym.inl")]) + self.assertNotIn("symlink", err.lower()) + + def check_drop_samefile(mod): + _, _, err = _run_main(mod, [str(rs_path), str(hardlink_out)]) + self.assertNotIn("must differ", err.lower()) + + def check_drop_parent_file(mod): + _, _, err = _run_main(mod, [str(rs_path), str(file_parent / "tables.inl")]) + self.assertNotIn("output parent is not a directory", err.lower()) + + def check_drop_tmp_unlink(mod): + with ( + mock.patch.object(mod, "SHA256", digest), + mock.patch.object(mod.os, "replace", side_effect=OSError("boom")), + ): + code, _, _ = _run_main(mod, [str(rs_path), str(out_inl)]) + self.assertEqual(code, 1) + leaked = _tmp_files(out_dir) + self.assertTrue(leaked, "expected leaked .tmp under drop_tmp_unlink mutation") + for p in leaked: + p.unlink(missing_ok=True) + + def check_non_atomic_write(mod): + out_inl.write_text("ORIGINAL", encoding="utf-8") + with ( + mock.patch.object(mod, "SHA256", digest), + mock.patch.object(mod.os, "replace", side_effect=OSError("boom")), + ): + _run_main(mod, [str(rs_path), str(out_inl)]) + self.assertNotEqual(out_inl.read_text(encoding="utf-8"), "ORIGINAL") + + mutations = ( + ( + "drop_sha256_check", + ' if hashlib.sha256(data).hexdigest() != expected_sha256:\n' + ' raise ValueError("expected victory-shader gfx10/opcodes.rs at 9376fd6")\n', + " pass\n", + check_drop_sha256, + ), + ( + "drop_marker_guard", + ' if marker_idx == -1:\n' + ' raise ValueError(f"missing {marker!r} marker in {source_path}")\n', + " pass\n", + check_drop_marker, + ), + ( + "drop_table_match_guard", + ' if match is None:\n' + ' raise ValueError(f"missing {table} table in {source_path}")\n' + ' entries = {int(op, 16): name for op, name in re.findall(r\'\\(0x([0-9a-f]+), "(\\w+)"\\)\', match.group(1))}\n', + ' entries = {int(op, 16): name for op, name in re.findall(r\'\\(0x([0-9a-f]+), "(\\w+)"\\)\', match[1])}\n', + check_drop_table_match, + ), + ( + "drop_empty_entries_guard", + ' if not entries:\n' + ' raise ValueError(f"empty {table} table in {source_path}")\n', + " pass\n", + check_drop_empty_entries, + ), + ( + "drop_output_is_symlink_guard", + ' if output.is_symlink():\n' + ' raise ValueError(f"output path must not be a symlink: {output}")\n', + " pass\n", + check_drop_symlink, + ), + ( + "drop_samefile_guard", + " if output.resolve() == opcodes_rs.resolve() or (output.exists() and opcodes_rs.samefile(output)):\n", + " if output.resolve() == opcodes_rs.resolve():\n", + check_drop_samefile, + ), + ( + "drop_parent_is_file_guard", + ' if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()):\n' + ' raise NotADirectoryError(f"output parent is not a directory: {parent}")\n', + " pass\n", + check_drop_parent_file, + ), + ( + "drop_tmp_unlink", + " if tmp_path is not None:\n tmp_path.unlink(missing_ok=True)\n", + " pass\n", + check_drop_tmp_unlink, + ), + ( + "non_atomic_write", + " os.replace(tmp_path, path)\n", + ' path.write_text(content, encoding="utf-8", newline="\\n")\n tmp_path.unlink(missing_ok=True)\n', + check_non_atomic_write, + ), + ) + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, f"target not unique for {label}") + mod = types.ModuleType(f"import_gfx10_tables_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/startup_indirect_dispatch.cpp b/tests/startup_indirect_dispatch.cpp index 99d28e7bb6..5d8d53e01e 100644 --- a/tests/startup_indirect_dispatch.cpp +++ b/tests/startup_indirect_dispatch.cpp @@ -4,7 +4,8 @@ #include <dxgi1_6.h> #include <wrl/client.h> -#include "desktop_gpu.h" +#include "adapter_name_filter.h" +#include "startup_indirect_writer.h" #include <algorithm> #include <array> @@ -15,6 +16,8 @@ #include <vector> extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_fixture_compute_root_uav(void*, UINT, UINT64); +extern "C" __declspec(dllimport) UINT x2w_d3d12_recording_scratches(void*); namespace { using Microsoft::WRL::ComPtr; @@ -24,6 +27,13 @@ using Words = std::vector<std::uint32_t>; bool constants = false; // The `count` mode runs a three-record argument buffer behind a GPU-written count word (max count 3). bool counted = false; +// X2W_SPLIT_INDIRECT_DISPATCH=1 (the startup_indirect_count_split_* tests): the shim splits a batched or counted +// Dispatch into single-command calls over a scratch copy of the records (split_indirect_dispatch.h). +bool split = false; +// The follow-up case records one more Dispatch(1, 1, 2) on the desktop list after the counted ExecuteIndirect, with +// the state the shim left there. It adds 1 + 101 = 102 to the result only if the consumer pipeline, its compute root +// and the result UAV are still bound, also after the split replaced them for its own pass. +constexpr std::uint32_t follow_up_term = 102; constexpr UINT max_commands = 3; Words initial; UINT argument_bytes = 0; @@ -61,6 +71,10 @@ void write_count2() { write_records(2); } void write_count9() { write_records(9); } [numthreads(1, 1, 1)] void write_count0() { write_records(0); } +[numthreads(1, 1, 1)] +void write_count1() { write_records(1); } +[numthreads(1, 1, 1)] +void write_count3() { write_records(3); } [numthreads(1, 1, 1)] void write_args() { data.Store3(4, uint3(4, 3, 2)); } @@ -102,22 +116,6 @@ Method slot(IUnknown* object, unsigned index) return reinterpret_cast<Method>((*reinterpret_cast<void***>(object))[index]); } -template <typename T> -ComPtr<T> native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) -{ - // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. - constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; - check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); - ComPtr<IUnknown> stored; - UINT bytes = sizeof(IUnknown*); - const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); - check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); - check(read, "retrieve underlying object"); - ComPtr<T> result; - check(stored.As(&result), "query underlying object"); - return result; -} - ComPtr<IUnknown> guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root) { const auto code = compile(constants ? "consume_constant_args" : "consume_args"); @@ -147,9 +145,13 @@ enum class Rejection { none, unmapped, short_range, placeholder, other_root, par // The constants mode also refuses a rooted signature with two records (rooted_multi) or a count buffer // (rooted_count_buffer): batching is rootless-only in this slice. // The other-root control binds `other_guest_root`, which lacks the signature's constants. +// Count mode only: `follow_up` adds the follow-up Dispatch above. `retire` submits through a guest queue held +// behind a gate fence, resets the guest allocator while that work is still pending, and requires the recording's +// split scratch to be held until the gate opens and the records run. bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, ID3D12RootSignature* guest_root, ID3D12RootSignature* other_guest_root, ID3D12PipelineState* writer, IUnknown* consumer, - ID3D12CommandSignature* signature, const Words& record, Rejection rejection) + ID3D12CommandSignature* signature, const Words& record, Rejection rejection, bool follow_up = false, + bool retire = false) { const UINT total_bytes = static_cast<UINT>(initial.size() * sizeof(std::uint32_t)); auto upload = make_buffer(device, total_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); @@ -169,7 +171,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I check(slot<Place>(guest, 133)(guest, static_cast<char*>(memory_backing.get()) + 4, &argument_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(guest_arguments.GetAddressOf())), "place guest argument buffer"); - const auto arguments = native_object<ID3D12Resource>(device, guest, guest_arguments.Get()); + const auto arguments = indirect_native_object<ID3D12Resource>(device, guest, guest_arguments.Get()); auto result = make_buffer(device, result_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); void* memory = nullptr; @@ -187,7 +189,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I reinterpret_cast<void**>(guest_list.GetAddressOf())), "create guest command list"); using Reset = HRESULT (WINAPI*)(IUnknown*, IUnknown*, void*, void*); check(slot<Reset>(guest_list.Get(), 139)(guest_list.Get(), allocator.Get(), nullptr, nullptr), "reset guest command list"); - const auto native_list = native_object<ID3D12GraphicsCommandList>(device, guest, guest_list.Get()); + const auto native_list = indirect_native_object<ID3D12GraphicsCommandList>(device, guest, guest_list.Get()); auto* list = native_list.Get(); transition(list, arguments.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); list->CopyBufferRegion(arguments.Get(), 0, upload.Get(), 0, argument_bytes); @@ -198,9 +200,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I if (writer) { transition(list, arguments.Get(), argument_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); argument_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - list->SetPipelineState(writer); - list->SetComputeRootUnorderedAccessView(0, arguments->GetGPUVirtualAddress()); - list->Dispatch(1, 1, 1); + record_indirect_writer(list, writer, arguments.Get()); } transition(list, arguments.Get(), argument_state, D3D12_RESOURCE_STATE_COPY_SOURCE); list->CopyBufferRegion(readback.Get(), 0, arguments.Get(), 0, argument_bytes); @@ -209,7 +209,10 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I using Bind = void (WINAPI*)(IUnknown*, IUnknown*); slot<Bind>(guest_list.Get(), 25)(guest_list.Get(), consumer); slot<Bind>(guest_list.Get(), 33)(guest_list.Get(), rejection == Rejection::other_root ? other_guest_root : guest_root); - list->SetComputeRootUnorderedAccessView(0, result->GetGPUVirtualAddress()); + // Bound through the shim, which sets it again after a compute pass of its own (the split of a batched Dispatch). + // If the shim has no matching UAV parameter for the bound guest root, bind on the desktop list as before. + if (!x2w_d3d12_fixture_compute_root_uav(guest_list.Get(), 0, result->GetGPUVirtualAddress())) + list->SetComputeRootUnorderedAccessView(0, result->GetGPUVirtualAddress()); using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); auto* argument = rejection == Rejection::unmapped ? nullptr : guest_arguments.Get(); UINT64 offset = counted ? 2 * sizeof(std::uint32_t) : argument_offset; @@ -228,19 +231,54 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I argument, offset, rejection == Rejection::rooted_count_buffer ? argument : nullptr, rejection == Rejection::rooted_count_buffer ? sizeof(std::uint32_t) : 0); + if (follow_up) list->Dispatch(1, 1, 2); transition(list, result.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); list->CopyBufferRegion(readback.Get(), argument_bytes, result.Get(), 0, result_bytes); using Close = HRESULT (WINAPI*)(IUnknown*); check(slot<Close>(guest_list.Get(), 9)(guest_list.Get()), "close guest command list"); + // Each run records on a fresh guest allocator: an accepted counted call holds one split scratch when the split is on. + const bool accepted = rejection == Rejection::none || rejection == Rejection::no_count_buffer; + const UINT scratches = counted && split && accepted ? 1 : 0; + if (counted && x2w_d3d12_recording_scratches(guest_list.Get()) != scratches) { + std::fprintf(stderr, "recording holds %u split scratch buffers after Close, expected %u\n", + x2w_d3d12_recording_scratches(guest_list.Get()), scratches); + return false; + } const D3D12_COMMAND_QUEUE_DESC queue_desc{}; - ComPtr<ID3D12CommandQueue> queue; ComPtr<ID3D12Fence> fence; - check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create queue"); check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "create completion fence"); - ID3D12CommandList* submitted[]{list}; - queue->ExecuteCommandLists(1, submitted); - check(queue->Signal(fence.Get(), 1), "signal completion fence"); - check(fence->SetEventOnCompletion(1, nullptr), "wait for completion"); + if (retire) { + // The shim tracks this submission's fence, so the allocator reset below must not release the scratch the + // split calls read: the desktop queue waits on the gate before it can run them. + ComPtr<IUnknown> guest_queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), + reinterpret_cast<void**>(guest_queue.GetAddressOf())), "create guest queue"); + const auto queue = indirect_native_object<ID3D12CommandQueue>(device, guest, guest_queue.Get()); + ComPtr<ID3D12Fence> gate; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate)), "create gate fence"); + check(queue->Wait(gate.Get(), 1), "hold the guest queue on the gate"); + using Submit = void (WINAPI*)(IUnknown*, UINT, IUnknown* const*); + IUnknown* submitted_list = guest_list.Get(); + slot<Submit>(guest_queue.Get(), 10)(guest_queue.Get(), 1, &submitted_list); + const HRESULT reset = allocator->Reset(); + const UINT held = x2w_d3d12_recording_scratches(guest_list.Get()); + check(gate->Signal(1), "open the gate"); + check(queue->Signal(fence.Get(), 1), "signal completion fence"); + check(fence->SetEventOnCompletion(1, nullptr), "wait for completion"); + std::printf("retire: allocator reset while pending -> 0x%08lx, recording holds %u split scratch buffers\n", + static_cast<unsigned long>(reset), held); + if (FAILED(reset) || held != scratches) { + std::fprintf(stderr, "split scratch was released before its submission retired\n"); + return false; + } + } else { + ComPtr<ID3D12CommandQueue> queue; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create queue"); + ID3D12CommandList* submitted[]{list}; + queue->ExecuteCommandLists(1, submitted); + check(queue->Signal(fence.Get(), 1), "signal completion fence"); + check(fence->SetEventOnCompletion(1, nullptr), "wait for completion"); + } check(device->GetDeviceRemovedReason(), "GPU completion"); const D3D12_RANGE read{0, total_bytes}; @@ -261,9 +299,11 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I for (std::uint32_t y = 0; y < expected[3 + 3 * i]; ++y) for (std::uint32_t x = 0; x < expected[2 + 3 * i]; ++x) expected[result_word] += 1 + x + 10 * y + 100 * z; - std::printf("%s: count word=%u, executed=%u, result=0x%08x (expected 0x%08x)\n", + if (follow_up) expected[result_word] += follow_up_term; + std::printf("%s%s%s: count word=%u, executed=%u, result=0x%08x (expected 0x%08x)\n", rejection == Rejection::none ? (writer ? "GPU writer" : "omitted writer") : rejection == Rejection::no_count_buffer ? "no count buffer" : "refused call", + follow_up ? " + follow-up Dispatch" : "", retire ? " + retired allocator" : "", observed[1], executed, observed[result_word], expected[result_word]); for (std::size_t i = 0; i < expected.size(); ++i) { if (observed[i] == expected[i]) continue; @@ -303,6 +343,10 @@ int main(int argc, char** argv) try constants = argc == 3 && std::strcmp(argv[2], "constants") == 0; counted = argc == 3 && std::strcmp(argv[2], "count") == 0; if (argc > 3 || (argc == 3 && !constants && !counted)) return 2; + { + char value[4]{}; + split = GetEnvironmentVariableA("X2W_SPLIT_INDIRECT_DISPATCH", value, sizeof(value)) && value[0] == '1'; + } initial = counted ? Words{0xa5a5a5a5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x31415926, 0x5a5a5a5a} : constants ? Words{0xa5a5a5a5, 0, 0, 0, 0, 0, 3, 5, 1, 1, 1, 0x31415926, 0x5a5a5a5a} : Words{0xa5a5a5a5, 0, 0, 0, 0x31415926, 0x5a5a5a5a}; argument_bytes = static_cast<UINT>((initial.size() - 2) * sizeof(std::uint32_t)); @@ -317,12 +361,15 @@ int main(int argc, char** argv) try if (warp) { check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)), "find WARP"); } else { + AdapterNameFilter filter; + if (!filter.read()) return 4; for (UINT index = 0; factory->EnumAdapters1(index, adapter.ReleaseAndGetAddressOf()) == S_OK; ++index) { DXGI_ADAPTER_DESC1 desc{}; if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + filter.matches(desc.Description) && SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) break; } - if (!adapter) return 77; + if (!adapter) return filter.no_match(); } check(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device)), "create desktop device through d3d12_xs"); SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); @@ -331,6 +378,10 @@ int main(int argc, char** argv) try const std::array<unsigned char, 64> parameters{}; ComPtr<ID3D12Device> guest; check(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), IID_PPV_ARGS(&guest)), "create guest device"); + if (!reinterpret_cast<const unsigned char*>(guest.Get())[0x18]) { + std::fputs("guest device permits inline descriptor creation\n", stderr); + return 1; + } DXGI_ADAPTER_DESC1 adapter_desc{}; check(adapter->GetDesc1(&adapter_desc), "get adapter description"); std::printf("adapter: %ls, debug layer %s\n", adapter_desc.Description, debug ? "enabled" : "unavailable"); @@ -396,20 +447,28 @@ int main(int argc, char** argv) try const auto writer = pipeline(device.Get(), root.Get(), counted ? "write_count2" : constants ? "write_constant_args" : "write_args"); const auto clamped_writer = pipeline(device.Get(), root.Get(), "write_count9"); const auto zero_writer = pipeline(device.Get(), root.Get(), "write_count0"); + const auto one_writer = pipeline(device.Get(), root.Get(), "write_count1"); + const auto three_writer = pipeline(device.Get(), root.Get(), "write_count3"); const auto other_writer = pipeline(device.Get(), root.Get(), constants ? "write_swapped_args" : "write_fewer_args"); const auto consumer = guest_pipeline(guest.Get(), guest_root.Get()); const auto verify = [&](ID3D12PipelineState* producer, const Words& record, Rejection rejection, - ID3D12CommandSignature* command_signature) { + ID3D12CommandSignature* command_signature, bool follow_up = false, bool retire = false) { return run(device.Get(), guest.Get(), root.Get(), guest_root.Get(), other_guest_root.Get(), producer, - consumer.Get(), command_signature, record, rejection); + consumer.Get(), command_signature, record, rejection, follow_up, retire); }; const auto run_counted = [&] { const Words records{0, 2, 1, 1, 1, 2, 1, 1, 1, 3}; const auto with_count = [&](std::uint32_t count) { Words r = records; r[0] = count; return r; }; const auto& sig = signature; + // GPU-written counts 2, above the maximum (9), 0, 1 and 3; a zero count must leave the result untouched. + // With the split on, the last case also resets the guest allocator before its submission retires. return verify(writer.Get(), with_count(2), Rejection::none, sig.Get()) && verify(clamped_writer.Get(), with_count(9), Rejection::none, sig.Get()) && verify(zero_writer.Get(), with_count(0), Rejection::none, sig.Get()) && + verify(one_writer.Get(), with_count(1), Rejection::none, sig.Get()) && + verify(three_writer.Get(), with_count(3), Rejection::none, sig.Get()) && + verify(writer.Get(), with_count(2), Rejection::none, sig.Get(), true) && + (!split || verify(writer.Get(), with_count(2), Rejection::none, sig.Get(), false, true)) && verify(nullptr, {}, Rejection::none, sig.Get()) && verify(zero_writer.Get(), with_count(0), Rejection::no_count_buffer, sig.Get()) && verify(writer.Get(), with_count(2), Rejection::unmapped, sig.Get()) && diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 234eb8c3b8..2cc49b9dc1 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -7,6 +7,7 @@ #include "desktop_gpu.h" #include "xmem_section_lease.h" #include "startup_stubs/rect_indirect_args.h" +#include "startup_stubs/mesh57_profile.h" #include "startup_indirect_mesh_mesh.h" #include "startup_indirect_mesh_amplify.h" #include "startup_indirect_mesh_amplified_mesh.h" @@ -106,6 +107,12 @@ void write_buffer_colour() { data.Store(32, 0xff0000ffu); } +[numthreads(1, 1, 1)] +void write_large_buffer_colour() { + data.Store(0x100000c, 0xff00ff00u); + data.Store(0x100001c, 0xff0000ffu); +} + [numthreads(1, 1, 1)] void write_replay_colour() { data.Store(0, 0xff00ff00u); @@ -213,6 +220,11 @@ float4 translated_buffer_pixel() : SV_Target { return float4(value & 255, (value >> 8) & 255, (value >> 16) & 255, 255) / 255.0; } +float4 translated_buffer_tail_pixel() : SV_Target { + uint value = translated_buffer.Load(0x100000c); + return float4(value & 255, (value >> 8) & 255, (value >> 16) & 255, 255) / 255.0; +} + struct RectVarying { float4 pos : SV_Position; float4 uv : PARAM0; @@ -291,15 +303,18 @@ ComPtr<ID3D12RootSignature> create_root(ID3D12Device* device, const D3D12_ROOT_S return root; } +enum class TableSample { texture, buffer, buffer_tail }; + ComPtr<IUnknown> translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* root_blob, - bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) + bool needs_start, TableSample sample = TableSample::texture, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-17"; + constexpr char revision[] = "x2w-startup-shader-29"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; - static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; + static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000205}; + static std::uint32_t indexed_pixel_id = 0xe0000204; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; - auto& pixel_id = pixel_ids[indexed ? 2 : table_buffer]; + auto& pixel_id = indexed ? indexed_pixel_id : pixel_ids[static_cast<unsigned>(sample)]; std::uint64_t key = 1469598103934665603ull; const auto add = [&key](const void* data, std::size_t bytes) { const auto* p = static_cast<const unsigned char*>(data); @@ -321,14 +336,15 @@ ComPtr<IUnknown> translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r check(file.good() ? S_OK : E_FAIL, "write fixture cache"); }; const auto vs = compile(rect ? "translated_rect_vertex" : indexed ? "translated_indexed_vertex" : needs_start ? "translated_vertex_with_start" : "translated_vertex", "vs_5_1"); - const auto ps = compile(rect ? "translated_rect_pixel" : indexed ? "translated_indexed_pixel" : table_buffer ? "translated_buffer_pixel" : "translated_pixel", "ps_5_1"); + const char* table_pixels[]{"translated_pixel", "translated_buffer_pixel", "translated_buffer_tail_pixel"}; + const auto ps = compile(rect ? "translated_rect_pixel" : indexed ? "translated_indexed_pixel" : table_pixels[static_cast<unsigned>(sample)], "ps_5_1"); write(".vs.cso", vs->GetBufferPointer(), vs->GetBufferSize()); write(".ps.cso", ps->GetBufferPointer(), ps->GetBufferSize()); constexpr char manifest[] = "x2w-manifest 1\nud 2\nudsrc 0 rect\nudsrc 1 basevertex\nsrv 0 tex2d table 0 0\nparams 0\ntargets 0\n"; constexpr char buffer_manifest[] = "x2w-manifest 1\nud 3\nudsrc 0 rect\nudsrc 1 basevertex\nudsrc 2 stride 0\nsrv 0 buf table 0 0\nparams 0\ntargets 0\n"; constexpr char indexed_manifest[] = "x2w-manifest 1\nud 3\nudsrc 0 rect\nudsrc 1 basevertex\nudsrc 2 stride 0\nsrv 0 buf vb 0\nsrv 1 tex2d table 0 0\nparams 1\ntargets 0\n"; if (indexed) write(".txt", indexed_manifest, sizeof(indexed_manifest) - 1); - else if (table_buffer) write(".txt", buffer_manifest, sizeof(buffer_manifest) - 1); + else if (sample != TableSample::texture) write(".txt", buffer_manifest, sizeof(buffer_manifest) - 1); else write(".txt", manifest, sizeof(manifest) - 1); const std::array<UINT64, 0x300 / sizeof(UINT64)> desc{ reinterpret_cast<UINT64>(root), 0, 0, 0, 0, @@ -584,7 +600,7 @@ enum class Refusal { none, index_upload_cross, index_upload_foreign, index_uploa insufficient_table_range, copied_table_buffer, upload_range_crossing, unproven_copy, indexed_base_overrun, indexed_vertex_range, invalid_mesh_tag, rect_bad_index, rect_bad_count, rect_bad_w, rect_bad_shape, - incomplete_mesh_constants, mesh_attachment_count, mesh_pending, overflowing_count, rect_live_compute }; + mesh_pixel_array, mesh_pixel_hole, mesh_wrong_heap_format, mesh_empty_heap_slot, mesh_outside_heap, mesh_short_table, mesh_bad_root_address, incomplete_mesh_constants, mesh_attachment_count, mesh_pending, overflowing_count, rect_live_compute }; enum class DrawKind { indexed, vertices, mesh, indexed_rect, rect }; ComPtr<ID3D12Resource> make_gpu_table_buffer(ID3D12Device* guest, UINT64 bytes) @@ -602,19 +618,20 @@ ComPtr<ID3D12Resource> make_gpu_table_buffer(ID3D12Device* guest, UINT64 bytes) struct TranslatedDrawFixture { TranslatedDrawFixture(ID3D12Device* guest, std::uint32_t colour, ID3D12Device* desktop = nullptr, - bool short_view = false, bool copied = false, bool replay = false) + bool short_view = false, bool copied = false, bool replay = false, bool allow_rt = false, + UINT committed_bytes = 64) : wrong_root(create_root(guest, {0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE})), backing(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { if (!backing) throw std::bad_alloc(); if (desktop && !copied) { - sampled = make_gpu_table_buffer(guest, 64); + sampled = make_gpu_table_buffer(guest, committed_bytes); } else { const D3D12_RESOURCE_DESC desc = copied ? D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_BUFFER, 0, replay ? replay_copy_bytes : 64u, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS} : - D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, - D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, allow_rt ? width : 1u, allow_rt ? height : 1u, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, allow_rt ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAG_NONE}; auto* address = static_cast<unsigned char*>(backing.get()) + (copied ? 16 : 0); std::memcpy(address + (replay ? 4 : copied ? 32 : 0), &colour, sizeof(colour)); using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); @@ -641,6 +658,8 @@ struct TranslatedDrawFixture { srv.Buffer.FirstElement = replay ? 0 : 1; srv.Buffer.NumElements = replay ? static_cast<UINT>(replay_copy_bytes / 4) : short_view ? 1 : 2; srv.Buffer.StructureByteStride = replay ? 4 : 16; + if (committed_bytes > 64) + srv.Buffer.NumElements = (committed_bytes / 16) - 1 - (short_view ? 1 : 0); } else { srv.Format = format; srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; @@ -730,13 +749,139 @@ void report_rect_conversion(ID3D12Device* device, const Words& observed, UINT wo converted[3] == source_words[3] ? "matches the CPU reference" : "differs from the CPU reference"); } +// Two table bases in a shader-visible guest heap and an independent guest root address. +// Each source contributes different bits to the output color. The raw records keep byte bounds. +static bool bind_fixed_mesh_buffers(ID3D12Device* device, ID3D12Device* guest, IUnknown* list, Refusal refusal, + const x2w_startup::Mesh57Profile& profile, int variant, ComPtr<ID3D12Resource>& heap_resource, + ComPtr<ID3D12DescriptorHeap>& heap, std::vector<ComPtr<ID3D12Resource>>& textures) +{ + using Allocate = void* (WINAPI*)(IUnknown*, UINT64, UINT64); + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + using Root = void (WINAPI*)(IUnknown*, UINT, UINT64); + constexpr UINT bytes = 16384, bank = 4096; + alignas(64) static UINT table[bytes / 4]; + std::fill_n(table, bytes / 4, 0u); + const UINT step = guest->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!step || bank % step) return false; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } desc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, bytes / step, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast<UINT64>(table),bytes}; + using Handle = UINT64 (WINAPI*)(IUnknown*); + if (FAILED(guest->CreateDescriptorHeap(&desc.desc,IID_PPV_ARGS(&heap))) || + slot<Handle>(heap.Get(),9)(heap.Get()) != desc.address) return false; + const auto gpu = slot<Handle>(heap.Get(),10)(heap.Get()); + auto* native = heap.Get(); + slot<Heaps>(list,32)(list,1,&native); + slot<Root>(list,36)(list,0,gpu); + slot<Root>(list,36)(list,1,gpu + bank); + const auto alloc = [&](unsigned value) { + auto* data = static_cast<UINT*>(slot<Allocate>(list,148)(list,16,256)); + if (data) { std::fill_n(data,4,0u); data[1] = value; } + return reinterpret_cast<UINT64>(data); + }; + const auto a = alloc(0x00400000), b = alloc(0x00200000), c = alloc(0x00100000), d = alloc(0x00080000); + if (!a || !b || !c || !d) return false; + const auto record = [&](UINT at, UINT64 address, UINT size) { + table[at/4] = static_cast<UINT>(address); + table[at/4+1] = static_cast<UINT>(address >> 32); + table[at/4+2] = size; + table[at/4+3] = 0x31016fac; + }; + record(2848,a,16); + record(bank + 32,d,16); + record(bank + 96,b,refusal == Refusal::mesh_short_table ? 4 : 16); + const bool pixel_heap = !std::memcmp(profile.magic,"X2WM576",8); + if (pixel_heap || !std::memcmp(profile.magic,"X2WM575",8)) { + // Seed one actual desktop buffer. Distinct nonzero view bases and element 1 distinguish + // selecting the wrong slot, losing FirstElement, or fetching the first element. + heap_resource = make_gpu_table_buffer(guest,48); + auto buffer = native_object<ID3D12Resource>(device,guest,heap_resource.Get()); + auto upload = make_buffer(device,48,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + D3D12_RANGE none{}; + check(upload->Map(0,&none,&mapped),"map typed heap fixture input"); + auto* values = static_cast<UINT*>(mapped); + std::fill_n(values,12,0u); + values[4] = 0x3e800000; + values[8] = 0x3f400000; + upload->Unmap(0,nullptr); + ComputeCommands seed(device,nullptr,D3D12_COMMAND_LIST_TYPE_DIRECT); + seed.list->CopyBufferRegion(buffer.Get(),0,upload.Get(),0,48); + seed.submit_and_wait(device); + using View = void (WINAPI*)(IUnknown*,IUnknown*,const D3D12_SHADER_RESOURCE_VIEW_DESC*,UINT64); + for (const UINT index : {147u,151u}) { + if (index == 147 && refusal == Refusal::mesh_empty_heap_slot) continue; + D3D12_SHADER_RESOURCE_VIEW_DESC view{index == 147 && refusal == Refusal::mesh_wrong_heap_format ? + DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER,D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.FirstElement = index == 147 && variant != 4 ? 3 : 7; + view.Buffer.NumElements = variant == 5 ? 1 : 2; + // Create on a guest API descriptor boundary, then copy its recorded bytes into + // the shader-native heap, whose independently indexed descriptors are 32 bytes. + const UINT scratch = index == 147 ? 0 : step; + slot<View>(guest,18)(guest,heap_resource.Get(),&view,desc.address + scratch); + std::memcpy(table + index * 8,reinterpret_cast<char*>(table) + scratch,32); + } + } + if (pixel_heap) { + using View = void (WINAPI*)(IUnknown*,IUnknown*,const D3D12_SHADER_RESOURCE_VIEW_DESC*,UINT64); + using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const void*, void*, UINT, const void*, REFIID, void**); + for (UINT index=32; index<=36; ++index) { + if (index==34 && refusal==Refusal::mesh_pixel_hole) continue; + ComPtr<ID3D12Resource> wrapped; + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM,D3D12_SRV_DIMENSION_TEXTURE2D,D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MostDetailedMip=1; + view.Texture2D.MipLevels=1; + if (GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)) { + view.Texture2D.MostDetailedMip=0; + view.Texture2D.MipLevels=2; + } + if ((index==32 && variant!=5) || index==36) { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC texture{D3D12_RESOURCE_DIMENSION_TEXTURE2D,0,2,2,1,2,DXGI_FORMAT_R8G8B8A8_UNORM,{1,0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN,D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + check(slot<Create>(guest,127)(guest,&props,0,&texture,D3D12_RESOURCE_STATE_COMMON,nullptr,nullptr, + 0,nullptr,IID_PPV_ARGS(&wrapped)), "create material texture"); + auto resource=native_object<ID3D12Resource>(device,guest,wrapped.Get()); + D3D12_DESCRIPTOR_HEAP_DESC rtv{D3D12_DESCRIPTOR_HEAP_TYPE_RTV,2}; + ComPtr<ID3D12DescriptorHeap> views; + check(device->CreateDescriptorHeap(&rtv,IID_PPV_ARGS(&views)), "create material RTVs"); + auto handle=views->GetCPUDescriptorHandleForHeapStart(); + ComputeCommands seed(device,nullptr,D3D12_COMMAND_LIST_TYPE_DIRECT); + transition(seed.list.Get(),resource.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_RENDER_TARGET); + for (UINT mip=0;mip<2;++mip) { + const float color[]{float(mip && index==32),float(mip && index==36),float(!mip),1.f}; + D3D12_RENDER_TARGET_VIEW_DESC output{texture.Format,D3D12_RTV_DIMENSION_TEXTURE2D}; + output.Texture2D.MipSlice=mip; + device->CreateRenderTargetView(resource.Get(),&output,handle); + seed.list->ClearRenderTargetView(handle,color,0,nullptr); + handle.ptr+=device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + } + transition(seed.list.Get(),resource.Get(),D3D12_RESOURCE_STATE_RENDER_TARGET,D3D12_RESOURCE_STATE_COMMON); + seed.submit_and_wait(device); + textures.push_back(wrapped); + } else { view.Texture2D.MostDetailedMip=0; view.Texture2D.MipLevels=1; } + if (index==36 && refusal==Refusal::mesh_pixel_array) { + view.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray.ArraySize=1; + } + slot<View>(guest,18)(guest,wrapped.Get(),&view,desc.address+index*step); + std::memmove(table+index*8,reinterpret_cast<char*>(table)+index*step,32); + } + } + // A readable CPU address outside the GPU allocations must fail even when it holds the right word. + slot<Root>(list,44)(list,3,refusal == Refusal::mesh_bad_root_address ? desc.address : c); + return true; +} + bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, ID3D12PipelineState* writer, ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature, DrawKind kind, bool draw_right, Refusal refusal, const char* label, const TranslatedDrawFixture* translated = nullptr, bool upload_table = false, const ReplayCopy* replay = nullptr, bool upload_index = false, bool alias_index = false, UINT cached_mesh_targets = 0, bool cached_depth_only = false, bool restore_compute = false, - const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false) + const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false, + int fixed_mesh_pixels = 0, const x2w_startup::Mesh57Profile* fixed_profile = nullptr) { std::unique_lock<std::mutex> recording; if (gate) recording = std::unique_lock<std::mutex>(gate->state); @@ -785,7 +930,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ constexpr float clear[]{0, 0, 0, 1}; D3D12_CLEAR_VALUE clear_value{target_format, {0, 0, 0, 1}}; if (cached_depth_only) clear_value.DepthStencil = {1, 0}; - const UINT target_count = cached_mesh_targets ? cached_mesh_targets : 1; + const UINT target_count = fixed_profile ? fixed_profile->targets.NumRenderTargets : cached_mesh_targets ? cached_mesh_targets : 1; std::vector<ComPtr<ID3D12Resource>> targets; const auto heap_kind = cached_depth_only ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV; const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{heap_kind, target_count, @@ -804,7 +949,10 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ rtv = heap->GetCPUDescriptorHandleForHeapStart(); } for (UINT i = 0; i < target_count; ++i) { - targets.push_back(resource(device, target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value)); + auto attachment = target_desc; + auto initial_color = clear_value; + if (fixed_profile) attachment.Format = initial_color.Format = fixed_profile->targets.RTFormats[i]; + targets.push_back(resource(device, attachment, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &initial_color)); if (cached_depth_only) { D3D12_DEPTH_STENCIL_VIEW_DESC depth_view{}; depth_view.Format = target_format; @@ -814,6 +962,24 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ rtvs.push_back(rtv); rtv.ptr += device->GetDescriptorHandleIncrementSize(heap_kind); } + ComPtr<ID3D12Resource> fixed_depth; + ComPtr<ID3D12DescriptorHeap> fixed_depth_heap; + D3D12_CPU_DESCRIPTOR_HANDLE fixed_dsv{}, desktop_fixed_dsv{}; + if (fixed_profile && fixed_profile->depth_format != DXGI_FORMAT_UNKNOWN) { + auto desc = target_desc; + desc.Format = fixed_profile->depth_format; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE initial_depth{}; + initial_depth.Format = desc.Format; + initial_depth.DepthStencil = {0.25f, 3}; + fixed_depth = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &initial_depth); + const D3D12_DESCRIPTOR_HEAP_DESC descriptors{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + check(guest->CreateDescriptorHeap(&descriptors,IID_PPV_ARGS(&fixed_depth_heap)), "create fixture DSV heap"); + using GetCpu = UINT64(WINAPI*)(IUnknown*, void*); + fixed_dsv.ptr = slot<GetCpu>(fixed_depth_heap.Get(),9)(fixed_depth_heap.Get(),nullptr); + desktop_fixed_dsv = native_object<ID3D12DescriptorHeap>(device,guest,fixed_depth_heap.Get())->GetCPUDescriptorHandleForHeapStart(); + guest->CreateDepthStencilView(fixed_depth.Get(), nullptr, fixed_dsv); + } ComPtr<ID3D12CommandAllocator> allocator; check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create guest allocator"); @@ -907,7 +1073,12 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ using Scissor = void (WINAPI*)(IUnknown*, UINT, const D3D12_RECT*); using Index = void (WINAPI*)(IUnknown*, const D3D12_INDEX_BUFFER_VIEW*); using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); - const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const bool material_waterfall = fixed_profile && + GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)!=0; + // NDC vertices (0,0), (1,0), (0,1) map to (0,2), (8,2), (0,-6). + // All eight target pixel centers lie strictly inside the triangle. + const D3D12_VIEWPORT viewport = material_waterfall ? D3D12_VIEWPORT{-8,-6,16,16,0,1} : + D3D12_VIEWPORT{0,0,width,height,0,1}; const D3D12_RECT scissor{rect ? 1 : 0, 0, width, height}; if (cached_depth_only) { slot<Targets>(wrapped, 50)(wrapped, 0, nullptr, FALSE, rtvs.data()); @@ -929,13 +1100,31 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ } for (const auto target_view : rtvs) slot<Clear>(wrapped, 52)(wrapped, target_view.ptr, clear, 0, nullptr); const UINT bound_targets = target_count - (refusal == Refusal::mesh_attachment_count ? 1 : 0); - slot<Targets>(wrapped, 50)(wrapped, bound_targets, rtvs.data(), FALSE, nullptr); + slot<Targets>(wrapped, 50)(wrapped, bound_targets, rtvs.data(), FALSE, fixed_depth ? &fixed_dsv : nullptr); + if (fixed_depth) { + list->ClearDepthStencilView(desktop_fixed_dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.25f, 3, 0, nullptr); + using StencilRef = void(WINAPI*)(IUnknown*,UINT); + slot<StencilRef>(wrapped,24)(wrapped,7); + } } + std::vector<ComPtr<ID3D12Resource>> fixed_textures; + ComPtr<ID3D12Resource> fixed_heap_resource; + ComPtr<ID3D12DescriptorHeap> fixed_source_heap; slot<Bind>(wrapped, 25)(wrapped, graphics); slot<Bind>(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot<RootSrv>(wrapped, 44)(wrapped, 0, leased->address); + } else if (fixed_profile && (!std::memcmp(fixed_profile->magic, "X2WM573", 8) || !std::memcmp(fixed_profile->magic, "X2WM574", 8) || + !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8))) { + // Guest root4 is b5/space2. DXIL expects the first word of host b0/space0. + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + const bool heap = !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8); + const bool buffers = heap || !std::memcmp(fixed_profile->magic, "X2WM574", 8); + if (buffers && !bind_fixed_mesh_buffers(device, guest, wrapped, refusal, *fixed_profile, fixed_mesh_pixels, fixed_heap_resource, fixed_source_heap, fixed_textures)) return false; + const UINT value = heap ? 0x3e000000u + (refusal == Refusal::mesh_outside_heap ? 490u : fixed_mesh_pixels == 3 ? 151u : 147u) : buffers ? 0x3e000000 : fixed_mesh_pixels == 3 ? 0x3f400000 : 0x3e800000; // 0.75 or 0.25 in PARAM12.y / green + if (refusal != Refusal::incomplete_mesh_constants) + slot<Constants>(wrapped, 40)(wrapped, 4, 1, &value, 0); } else if (cached_mesh_targets || cached_depth_only) { using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); const UINT values[]{17, 29}; @@ -975,7 +1164,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ std::memcpy(allocation, contents, vertex_bytes); const UINT bytes = vertex_bytes + (refusal == Refusal::indexed_vertex_range ? 4 : 0); const D3D12_VERTEX_BUFFER_VIEW vertex{reinterpret_cast<UINT64>(allocation), bytes, - rect ? sizeof(RectVertex) : sizeof(std::uint32_t)}; + static_cast<UINT>(rect ? sizeof(RectVertex) : sizeof(std::uint32_t))}; slot<VertexBuffer>(wrapped, 48)(wrapped, 0, 1, &vertex); } if (index_buffer) { @@ -1057,6 +1246,10 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ? sizeof(initial_words) - command_stride(kind) + sizeof(std::uint32_t) : indexed_argument_offset; slot<Execute>(wrapped, 61)(wrapped, signature, 1, external_arguments ? leased->argument : arguments->wrapped.Get(), external_arguments ? leased->argument_offset : offset, nullptr, 0); + // Slot 61 has already frozen the desktop heap and retained its backing. Release the guest + // resource before closing/submitting the list, including for the positive readbacks. + fixed_source_heap.Reset(); + fixed_heap_resource.Reset(); if (restore_compute) { // Leave the previously forwarded root + SRV alone. Only install the // consumer PSO and the output UAV that this fixture owns. @@ -1162,8 +1355,9 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; UINT64 bytes = 0; - device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); for (const auto& target : targets) { + const auto desc = target->GetDesc(); + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); const auto pixel_readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); ComputeCommands copy(device, kept_direct_queue(device), nullptr); transition(copy.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -1187,10 +1381,38 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const bool covered = (cached_depth_only && !cached_depth_pixel) || (indexed ? right_half == draw_right : translated || !right_half || draw_right); const bool drawn = writer && refusal == Refusal::none && covered; // overflowing_count draws nothing - const std::uint32_t background = cached_depth_only ? 0xffff : black; + const std::uint32_t background = cached_depth_only ? 0xffff : desc.Format == DXGI_FORMAT_R16G16_FLOAT ? 0 : black; const auto depth_word = cached_depth_pixel ? 0x4000u : 0u; // D16_UNORM encodes SV_Depth 0.25. auto wanted = drawn ? (cached_depth_only ? depth_word : translated ? (draw_right ? green : red) : (right_half ? green : red)) : background; + if (fixed_mesh_pixels) { + const bool white = (fixed_mesh_pixels == 1 || fixed_mesh_pixels >= 3) && target.Get() == targets.front().Get() && x == 2 && y == 0; + if (target.Get() == targets.front().Get() && x == 2 && y == 0) + std::printf("%s: target zero (2,0) packed RGBA = 0x%08x\n", label, actual); + wanted = background; + if (white) { + const auto mask = fixed_profile->blend.RenderTarget[0].RenderTargetWriteMask; + const bool linked = !std::memcmp(fixed_profile->magic, "X2WM572", 8); + const bool heap = !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8); + if (heap) wanted = 0; // This fixture writes all four channels, including alpha. + for (UINT channel=0; channel<4; ++channel) + if ((mask & (1u<<channel)) && !(linked && channel == 1)) + wanted |= (heap ? (channel == 1 ? 62u : fixed_mesh_pixels == 5 ? 0u : fixed_mesh_pixels >= 3 ? 191u : 64u) : + channel == 1 && !std::memcmp(fixed_profile->magic, "X2WM574", 8) ? 62u : + channel == 1 && !std::memcmp(fixed_profile->magic, "X2WM573", 8) ? + (fixed_mesh_pixels == 3 ? 0xbfu : 0x40u) : 0xffu) << (8*channel); + if (!std::memcmp(fixed_profile->magic,"X2WM576",8)) + wanted = fixed_mesh_pixels==5 ? 0 : fixed_mesh_pixels==3 ? 0xff00ff00u : 0xff0000ffu; + } + if (material_waterfall && target.Get()==targets.front().Get() && fixed_mesh_pixels!=2) { + // floor(SV_Position.x) selects slot 32 on even pixels + // and 36 on odd ones. Variant 5 binds typed null at 32. + const bool fine=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_FINE_LOD",nullptr,0)!=0; + wanted=!(x&1) && fixed_mesh_pixels==5 ? 0u : + fine ? 0xffff0000u : (x&1) ? 0xff00ff00u : 0xff0000ffu; + if (!y) std::printf("waterfall x=%u RGBA=%08x\n",x,actual); + } + } if (leased) wanted = right_half ? leased->expected_right.value_or(leased->expected) : leased->expected; if (rect) { // NDC pixel centers are x=(-.75,-.25,.25,.75), y=(.5,-.5). @@ -1212,6 +1434,43 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ return false; } } + if (fixed_depth) { + const auto desc = fixed_depth->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT planes[2]{}; + UINT64 row_sizes[2]{}; + device->GetCopyableFootprints(&desc, 0, 2, 0, planes, nullptr, row_sizes, &bytes); + const auto rb = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, kept_direct_queue(device), nullptr); + transition(copy.list.Get(), fixed_depth.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT plane=0; plane<2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION src{fixed_depth.Get(),D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,{}}; + src.SubresourceIndex=plane; + D3D12_TEXTURE_COPY_LOCATION dst{rb.Get(),D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,{}}; + dst.PlacedFootprint=planes[plane]; + copy.list->CopyTextureRegion(&dst,0,0,0,&src,nullptr); + } + copy.submit_and_wait(device); + const D3D12_RANGE range{0,static_cast<SIZE_T>(bytes)}; + check(rb->Map(0,&range,&memory),"map depth/stencil planes"); + bool match=true; + for (UINT y=0;y<height;++y) for (UINT x=0;x<width;++x) { + const auto texel=[&](UINT plane) { + return static_cast<const unsigned char*>(memory)+planes[plane].Offset+ + y*planes[plane].Footprint.RowPitch+x*row_sizes[plane]/width; + }; + float z; std::memcpy(&z,texel(0),sizeof(z)); + const auto stencil=*texel(1); + const bool hit=fixed_mesh_pixels==1 && x==2 && y==0; + if (z!=(hit?0.5f:0.25f) || stencil!=(hit?7:3)) { + std::fprintf(stderr,"%s: depth/stencil (%u,%u) got %.3f/%u, row sizes %llu/%llu\n",label,x,y,z,stencil,row_sizes[0],row_sizes[1]); + match=false; + } + } + rb->Unmap(0,&untouched); + if (!match) return false; + std::printf("%s: 8 depth/stencil texels matched, selected pixel %.2f/%u\n", + label,fixed_mesh_pixels==1?0.5:0.25,fixed_mesh_pixels==1?7:3); + } return true; } // Calls refused before any argument is read: one per counted reason, and one with two commands, which is @@ -1337,6 +1596,252 @@ bool check_translated_refusal_census(const std::wstring& log_path) return true; } +bool check_translated_targets(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, + ID3D12PipelineState* writer, ID3D12RootSignature* title_root, IUnknown* pso, + ID3D12CommandSignature* signature, const TranslatedDrawFixture& red_binding, + const std::filesystem::path& delayed_manifest = {}, bool fallback_enabled = false) +{ + const TranslatedDrawFixture alias_binding(guest, red, nullptr, false, false, false, true); + enum class Mode { mrt_two, color_and_dsv, depth_only, no_attachments, alias_rtv1, direct_missing, direct_ready }; + const auto run_mode = [&](Mode mode, const char* label) -> bool { + const bool direct = mode == Mode::direct_missing || mode == Mode::direct_ready; + const auto& binding = mode == Mode::alias_rtv1 ? alias_binding : red_binding; + PlacedBuffer arguments(device, guest, static_cast<UINT>(sizeof(initial)), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Words initial_words = initial; + initial_words[1 + command_stride(DrawKind::vertices) / sizeof(std::uint32_t)] = 0x3c3c3c3c; + const auto upload = make_buffer(device, sizeof(initial_words), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* memory = nullptr; + const D3D12_RANGE untouched{0, 0}; + check(upload->Map(0, &untouched, &memory), "map targets upload"); + std::memcpy(memory, initial_words.data(), sizeof(initial_words)); + upload->Unmap(0, nullptr); + + const D3D12_RESOURCE_DESC color_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_RESOURCE_DESC depth_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_D16_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + constexpr float clear[]{0, 0, 0, 1}; + D3D12_CLEAR_VALUE color_clear{format, {0, 0, 0, 1}}; + D3D12_CLEAR_VALUE depth_clear{DXGI_FORMAT_D16_UNORM, {0, 0, 0, 1}}; + depth_clear.DepthStencil = {1.0f, 0}; + + const auto color0 = resource(device, color_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &color_clear); + const auto color1 = resource(device, color_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &color_clear); + const auto depth = resource(device, depth_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &depth_clear); + + const D3D12_DESCRIPTOR_HEAP_DESC rtv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr<ID3D12DescriptorHeap> rtv_heap; + check(device->CreateDescriptorHeap(&rtv_heap_desc, IID_PPV_ARGS(&rtv_heap)), "create targets rtv heap"); + const UINT rtv_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2]{ + rtv_heap->GetCPUDescriptorHandleForHeapStart(), + {rtv_heap->GetCPUDescriptorHandleForHeapStart().ptr + rtv_inc}}; + guest->CreateRenderTargetView(color0.Get(), nullptr, rtvs[0]); + ID3D12Resource* rtv1_res = mode == Mode::alias_rtv1 ? binding.sampled.Get() : color1.Get(); + guest->CreateRenderTargetView(rtv1_res, nullptr, rtvs[1]); + + const D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr<ID3D12DescriptorHeap> dsv_heap; + check(guest->CreateDescriptorHeap(&dsv_heap_desc, IID_PPV_ARGS(&dsv_heap)), "create targets dsv heap"); + using GetCpu = UINT64(WINAPI*)(IUnknown*, void*); + D3D12_CPU_DESCRIPTOR_HANDLE guest_dsv{slot<GetCpu>(dsv_heap.Get(), 9)(dsv_heap.Get(), nullptr)}; + const D3D12_CPU_DESCRIPTOR_HANDLE native_dsv = + native_object<ID3D12DescriptorHeap>(device, guest, dsv_heap.Get())->GetCPUDescriptorHandleForHeapStart(); + D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{}; + dsv_desc.Format = DXGI_FORMAT_D16_UNORM; + dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + guest->CreateDepthStencilView(depth.Get(), &dsv_desc, guest_dsv); + + ComPtr<ID3D12CommandAllocator> allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create targets allocator"); + auto wrapped_list = begin_guest_list(guest, allocator.Get()); + auto* wrapped = wrapped_list.Get(); + const auto native_list = native_object<ID3D12GraphicsCommandList>(device, guest, wrapped); + auto* list = native_list.Get(); + + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(arguments.native.Get(), 0, upload.Get(), 0, sizeof(initial_words)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetPipelineState(writer); + list->SetComputeRootSignature(writer_root); + list->SetComputeRootUnorderedAccessView(0, arguments.native->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Topology = void (WINAPI*)(IUnknown*, D3D12_PRIMITIVE_TOPOLOGY); + using Viewport = void (WINAPI*)(IUnknown*, UINT, const D3D12_VIEWPORT*); + using Scissor = void (WINAPI*)(IUnknown*, UINT, const D3D12_RECT*); + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + using Table = void (WINAPI*)(IUnknown*, UINT, UINT64); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + + slot<Clear>(wrapped, 52)(wrapped, rtvs[0].ptr, clear, 0, nullptr); + if (mode == Mode::mrt_two) slot<Clear>(wrapped, 52)(wrapped, rtvs[1].ptr, clear, 0, nullptr); + if (mode == Mode::mrt_two || mode == Mode::alias_rtv1) + slot<Targets>(wrapped, 50)(wrapped, 2, rtvs, FALSE, nullptr); + else if (mode == Mode::color_and_dsv || direct) { + slot<Targets>(wrapped, 50)(wrapped, 1, rtvs, FALSE, &guest_dsv); + list->ClearDepthStencilView(native_dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + } else if (mode == Mode::depth_only) { + slot<Targets>(wrapped, 50)(wrapped, 0, nullptr, FALSE, &guest_dsv); + list->ClearDepthStencilView(native_dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + } else { + slot<Targets>(wrapped, 50)(wrapped, 0, nullptr, FALSE, nullptr); + } + + ComPtr<ID3D12QueryHeap> query_heap; + ComPtr<ID3D12Resource> query_readback; + if (mode == Mode::depth_only) { + const D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 1, 0}; + check(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&query_heap)), "create depth-only occlusion query heap"); + query_readback = make_buffer(device, sizeof(std::uint64_t), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + } + if (direct) { + const D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, 1, 0}; + check(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&query_heap)), "create direct draw query heap"); + query_readback = make_buffer(device, sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS), + D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + } + + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + slot<Bind>(wrapped, 25)(wrapped, pso); + slot<Bind>(wrapped, 34)(wrapped, title_root); + ID3D12DescriptorHeap* heaps[]{binding.heap.Get()}; + slot<Heaps>(wrapped, 32)(wrapped, 1, heaps); + slot<Table>(wrapped, 36)(wrapped, 0, binding.gpu); + slot<Topology>(wrapped, 20)(wrapped, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + slot<Viewport>(wrapped, 21)(wrapped, 1, &viewport); + slot<Scissor>(wrapped, 22)(wrapped, 1, &scissor); + if (mode == Mode::depth_only) list->BeginQuery(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0); + if (direct) { + using Draw = void (WINAPI*)(IUnknown*, UINT, UINT, UINT, UINT); + list->BeginQuery(query_heap.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + slot<Draw>(wrapped, 12)(wrapped, 3, 1, 0, 0); + list->EndQuery(query_heap.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0); + list->ResolveQueryData(query_heap.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, 1, query_readback.Get(), 0); + } else { + slot<Execute>(wrapped, 61)(wrapped, signature, 1, arguments.wrapped.Get(), argument_offset, nullptr, 0); + } + if (mode == Mode::depth_only) { + list->EndQuery(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0); + list->ResolveQueryData(query_heap.Get(), D3D12_QUERY_TYPE_OCCLUSION, 0, 1, query_readback.Get(), 0); + } + check(slot<HRESULT(WINAPI*)(IUnknown*)>(wrapped, 9)(wrapped), "close targets list"); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr<IUnknown> guest_queue; + check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(guest_queue.GetAddressOf())), + "create targets queue"); + IUnknown* lists[]{wrapped}; + slot<void (WINAPI*)(IUnknown*, UINT, IUnknown* const*)>(guest_queue.Get(), 10)(guest_queue.Get(), 1, lists); + const auto native_queue = native_object<ID3D12CommandQueue>(device, guest, guest_queue.Get()); + ComPtr<ID3D12Fence> fence; + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "create targets fence"); + check(native_queue->Signal(fence.Get(), 1), "signal targets fence"); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + check(fence->SetEventOnCompletion(1, done), "set targets fence event"); + WaitForSingleObject(done, INFINITE); + CloseHandle(done); + + if (mode == Mode::depth_only) { + std::uint64_t samples = 0; + const D3D12_RANGE query_range{0, sizeof(samples)}; + check(query_readback->Map(0, &query_range, &memory), "map depth-only occlusion query"); + std::memcpy(&samples, memory, sizeof(samples)); + query_readback->Unmap(0, &untouched); + const auto expected_samples = static_cast<std::uint64_t>(width) * height; + if (samples != expected_samples) { + std::fprintf(stderr, "%s: expected %llu rasterized samples, got %llu\n", + label, static_cast<unsigned long long>(expected_samples), + static_cast<unsigned long long>(samples)); + return false; + } + } + + if (direct) { + D3D12_QUERY_DATA_PIPELINE_STATISTICS stats{}; + const D3D12_RANGE range{0, sizeof(stats)}; + check(query_readback->Map(0, &range, &memory), "map direct draw query"); + std::memcpy(&stats, memory, sizeof(stats)); + query_readback->Unmap(0, &untouched); + const UINT64 expected = mode == Mode::direct_ready || fallback_enabled ? 3 : 0; + if (stats.IAVertices != expected) { + std::fprintf(stderr, "%s: IA vertices %llu, expected %llu\n", label, stats.IAVertices, expected); + return false; + } + } + const auto read_pixels = [&](ID3D12Resource* target, std::uint32_t expected_pixel, const char* which) -> bool { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + const auto desc = target->GetDesc(); + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + transition(copy.list.Get(), target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint = footprint; + copy.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + copy.submit_and_wait(device); + const D3D12_RANGE range{0, static_cast<SIZE_T>(bytes)}; + check(readback->Map(0, &range, &memory), "map targets readback"); + bool ok = true; + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + std::uint32_t actual = 0; + const auto size = desc.Format == DXGI_FORMAT_D16_UNORM ? sizeof(std::uint16_t) : sizeof(actual); + std::memcpy(&actual, static_cast<char*>(memory) + y * footprint.Footprint.RowPitch + x * size, size); + if (actual != expected_pixel) { + std::fprintf(stderr, "%s (%s) pixel (%u,%u): got 0x%08x, expected 0x%08x\n", + label, which, x, y, actual, expected_pixel); + ok = false; + } + } + readback->Unmap(0, &untouched); + return ok; + }; + const bool expect_draw = mode == Mode::mrt_two || mode == Mode::color_and_dsv || mode == Mode::direct_ready; + if (!read_pixels(color0.Get(), expect_draw ? red : black, "rtv0")) return false; + if (mode == Mode::mrt_two && !read_pixels(color1.Get(), black, "rtv1")) return false; + if (mode == Mode::direct_missing && !read_pixels(depth.Get(), 0xffff, "dsv")) return false; + std::printf("%s: OK\n", label); + return true; + }; + if (!delayed_manifest.empty()) { + auto staged_manifest = delayed_manifest; + staged_manifest += ".staged"; + std::filesystem::rename(delayed_manifest, staged_manifest); + if (!run_mode(Mode::direct_missing, "missing translation")) return false; + const auto request = delayed_manifest.parent_path() / ("req_" + delayed_manifest.stem().string() + ".a"); + if (!std::filesystem::exists(request)) { + std::fprintf(stderr, "missing draw did not publish its shader request\n"); + return false; + } + std::filesystem::rename(staged_manifest, delayed_manifest); + Sleep(1100); // The runtime polls absent manifests at one-second intervals. + return run_mode(Mode::direct_ready, "published translation"); + } + const bool ok = + run_mode(Mode::mrt_two, "translated indirect MRT (2 color targets)") && + run_mode(Mode::color_and_dsv, "translated indirect color + DSV") && + run_mode(Mode::depth_only, "translated indirect depth-only (0 RTV + DSV)") && + run_mode(Mode::no_attachments, "translated indirect refuses 0 RTV + no DSV") && + run_mode(Mode::alias_rtv1, "translated indirect refuses sampled texture aliasing RTV 1"); + if (!ok) return false; + const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); + std::string report(needed + 1, '\0'); + x2w_d3d12_census_report(report.data(), report.size()); + if (report.find("reason=sampled_texture_mismatch calls=1") == std::string::npos) { + std::fprintf(stderr, "expected sampled_texture_mismatch refusal for RTV 1 alias in census report:\n%s\n", report.c_str()); + return false; + } + return true; +} + bool check_indirect_other_refusal_census(const std::wstring& log_path) { const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); @@ -1408,7 +1913,7 @@ bool check_indirect_other_refusal_census(const std::wstring& log_path) std::string log_line; bool saw_vp_log = false, saw_arg_log = false, saw_multi_log = false; const std::string want_vp = "x2w-render ExecuteIndirect refused, key " + parsed[0].key + - " [missing_viewport_or_scissor]: indirect graphics requires one matching target, viewport and scissor"; + " [missing_viewport_or_scissor]: translated indirect draw requires bound target or depth view, viewport and scissor"; const std::string want_arg = "x2w-render ExecuteIndirect refused, key " + parsed[0].key + " [argument_outside_placed_buffer]: argument record is outside a unique placed buffer"; const std::string want_multi = "x2w-render ExecuteIndirect refused, key " + zero_key + @@ -1428,8 +1933,56 @@ bool check_indirect_other_refusal_census(const std::wstring& log_path) for (const auto& line : entries) std::printf("%s\n", line.c_str()); return true; } +bool mesh57_descriptor_relocations() +{ + using Bytes = std::vector<unsigned char>; + const auto put = [](Bytes& bytes, size_t offset, auto value) { + std::memcpy(bytes.data() + offset, &value, sizeof(value)); + }; + const auto build = [&](uint64_t section, uint64_t allocation) { + Bytes bytes(0x300); + constexpr size_t offsets[]{ + 0x38, 0x78, 0x120, 0x128, 0x168, 0x178, 0x198, 0x1d8, + 0x280, 0x288, 0x2c8, 0x2d8, 0x2f8 + }; + for (size_t i = 0; i < std::size(offsets); ++i) + put(bytes, offsets[i], section + i * 16); + put(bytes, 0x78, section - 16); + put(bytes, 0x110, static_cast<uint32_t>(section + 8 * 16)); + put(bytes, 0x270, static_cast<uint32_t>(section + 16)); + put(bytes, 0x30, uint64_t{512}); + put(bytes, 0x70, uint64_t{1024}); + put(bytes, 0x11c, uint32_t{0x04010000}); + put(bytes, 0x27c, uint32_t{0x04010000}); + put(bytes, 0x160, allocation); + put(bytes, 0x2c0, allocation); + return bytes; + }; + constexpr uint64_t first_section = 0x10020000; + const auto original = build(first_section, 0x30030000); + const auto relocated = build(0x140050000, 0x260070000); + const auto normalized = x2w_startup::normalize_mesh57_descriptor(original); + if (normalized == original || normalized != x2w_startup::normalize_mesh57_descriptor(relocated) || + normalized != x2w_startup::normalize_mesh57_descriptor(normalized)) + return false; + + auto different_metadata = original; + different_metadata[0x207] = 1; + auto different_offset = original; + put(different_offset, 0x1d8, first_section + 0x400); + auto unknown_layout = original; + put(unknown_layout, 0x2c0, uint64_t{0x30070000}); + if (normalized == x2w_startup::normalize_mesh57_descriptor(different_metadata) || + normalized == x2w_startup::normalize_mesh57_descriptor(different_offset) || + unknown_layout != x2w_startup::normalize_mesh57_descriptor(unknown_layout)) + return false; + std::puts("extended Mesh57 layout normalizes relocations and preserves metadata and relative offsets"); + return true; +} + bool fixed_mesh_create_contract(ID3D12Device* guest) { + if (!mesh57_descriptor_relocations()) return false; const D3D12_ROOT_SIGNATURE_DESC root_desc{}; const auto root = create_root(guest, root_desc); const std::array<UINT, 7> ms{0xbfa00003, 0xbf900009, 0xf80008cf, 0x03020100, 0xf8000941, 0, 0xbf810000}; @@ -1499,6 +2052,297 @@ bool fixed_mesh_create_contract(ID3D12Device* guest) #include "startup_indirect_mesh_lease.inl" } // namespace +static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer) +{ + const bool mrt = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_MRT", nullptr, 0) != 0; + const bool waterfall=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)!=0; + const bool pixel_heap=waterfall || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_PIXEL_HEAP",nullptr,0)!=0; + const bool heap = pixel_heap || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_UINT_HEAP",nullptr,0) != 0; + const bool buffers = heap || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_BUFFERS", nullptr, 0) != 0; + const bool constants = buffers || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_CONSTANT", nullptr, 0) != 0; + const bool varying = constants || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_VARYING", nullptr, 0) != 0; + // Windows recycles process IDs. Retain failed runs for inspection without reading an old archive. + const auto prefix = "mesh57-native-" + std::to_string(GetCurrentProcessId()) + "-"; + std::filesystem::path cache; + for (unsigned attempt = 0; ; ++attempt) { + cache = std::filesystem::current_path() / (prefix + std::to_string(attempt)); + if (std::filesystem::create_directory(cache)) break; + } + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "native mesh cache"); + ComPtr<ID3DBlob> blob; + D3D12_ROOT_SIGNATURE_DESC empty{}; + D3D12_ROOT_PARAMETER params[5]{}; + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + if (constants) { + for (UINT i = 0; i < 5; ++i) { + params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[i].Constants = {i + 1, 2, 1}; + } + if (buffers) { + for (UINT i = 0; i < 2; ++i) { + ranges[i] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 128, 0, i, 0}; + params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[i].DescriptorTable = {1, &ranges[i]}; + } + params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params[3].Descriptor = {0, 3}; + } + if (pixel_heap) params[2].ShaderVisibility=D3D12_SHADER_VISIBILITY_VERTEX; + empty.NumParameters = 5; + empty.pParameters = params; + empty.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + } + const auto root = create_root(guest, empty, &blob); + // Guest ALU derives positions (0,0), (1,0), (0,1) from lane indices and exports triangle 0,1,2. + std::vector<UINT> ms{0xbefc03ff, 0x1003, 0xbf900009, 0xd7650000, 0x100c1, 0x36020081, + 0x2c040081, 0x7e020d01, 0x7e040d02, 0x7e0602f0, 0x7e0802f2, 0xf80008cf, + 0x04030201, 0x7e0a02ff, 0x200400, 0xf8000941, 0x80808005, 0xbf810000}; + std::vector<UINT> ps{0x7e0002f2, 0xf800180f, 0, 0xbf810000}; + if (varying) { + // Export PARAM12.xy = (1,0). The PS reads p0.x and p0.y back as (x,y,x,x). + ms.insert(ms.end()-1, {constants ? 0x7e0c020cu : 0x7e0c0280u, 0xf80002c3, heap ? 0x0000060au : 0x00000604u}); + ps = {0xc8023002, 0xc8063102, 0xf800180f, 0x00000100, 0xbf810000}; + } + if (buffers) { + // s_load_dwordx4 table0+2848 and table1+32/+96; s_buffer_load_dword at +4 of each SRV. + // Read root3+4 through its synthesized byte descriptor. Combine their disjoint bits with root4 in s12. + ms.insert(ms.begin(), {0xbe910380, 0xbe930380, 0xf4080608, 0xfa000b20, 0xf4080709, 0xfa000060, + 0xf420080c, 0xfa000004, 0xf420084e, 0xfa000004, 0xbe960390, 0xbe9703ff, 0x31016fac, 0xf420088a, 0xfa000004, + 0xf4080a09, 0xfa000020, 0xf42008d4, 0xfa000004, + 0x880c200c, 0x880c210c, 0x880c220c, 0x880c230c}); + } + if (heap) { + // Guest slot = root4[0] & 1023. Read typed element 1 into v10. + ms.insert(ms.begin(), {0xbe9e032f,0xbe9f0380,0x872dff0c,1023,0x8f2d852d, + 0xf408080f,0x5a000000,0x7e020281,0xe0002000,0x80080a01}); + } + if (pixel_heap) { + // ((root4 & 4) << 5) + 1024 selects slot 32 or 36. Both views begin at mip 1. + ps={0xbe8f0380,0x8712840d,0x8f128512,0xf40c0507,0x24000400, + 0xbe9c0380,0xbe9d03ff,0x00fff000,0xbe9e03ff,0x04000000,0xbe9f0380, + 0x7e0002f0,0x7e0202f0,0xf09c0f08,0x00e50000,0xf800180f,0x03020100,0xbf810000}; + } + if (waterfall) { + // slot = 32 | ((uint(SV_Position.x) & 1) << 2). Each iteration + // samples exactly the lanes with the first active lane's slot. + // Preserve the incoming float position before converting v0 to a slot + // selector. A unit texcoord gradient on a 2x2 view selects mip 1; + // constant coordinates select the blue mip 0 with the same sampler. + const bool fine=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_FINE_LOD",nullptr,0)!=0; + ps={fine ? 0x7e0a02f0u : 0x7e0a0300u,0xbe8f0380,0x7e000f00,0x362e0081,0x342e2e82,0x382e2ea0, + 0x7e0c02f0,0xbe9c0380,0xbe9d03ff,0x00fff000,0xbe9e03ff,0x04000000,0xbe9f0380, + 0xbebc047e,0xbeb4047e, + 0x7e240517,0x7d242e12,0x8f128512,0xf40c0507,0x24000000, + 0xf0800f08,0x00e50005,0xbeb43a34,0xbf85fff7,0xbefe043c, + 0xf800180f,0x03020100,0xbf810000}; + } + const auto ms_size = ms.size()*sizeof(UINT), ps_size = ps.size()*sizeof(UINT); + const std::array<UINT, 2> expected_a{0x12345678, 0x9abcdef0}; + const bool masked = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_MASK", nullptr, 0) != 0; + const std::array<UINT, 1> expected_b{masked ? 0x55aa5501u : 0x55aa55aau}; + auto state_a = expected_a; + auto state_b = expected_b; + UINT64 fields[0x300 / sizeof(UINT64)]{}; + fields[2] = sizeof(state_a); + fields[4] = sizeof(state_b); + fields[6] = ps_size; + fields[14] = ms_size; + const auto fold = [](UINT64 key, const void* data, size_t n) { + const auto* p = static_cast<const unsigned char*>(data); + for (size_t i = 0; i < n; ++i) + key = (key ^ p[i]) * 1099511628211ull; + return key; + }; + const char revision[] = "x2w-startup-mesh-57-3"; + auto key = fold(1469598103934665603ull, revision, sizeof(revision) - 1); + const auto extend = [&](UINT64 base, const void* data, UINT64 n) { return fold(fold(base, &n, sizeof(n)), data, n); }; + const auto part = [&](const void* data, UINT64 n) { key = extend(key,data,n); }; + part(ms.data(), ms_size); + part(ps.data(), ps_size); + part(blob->GetBufferPointer(), blob->GetBufferSize()); + char name[64]; + const auto variant = [&] { + return extend(extend(extend(key,fields,sizeof(fields)),state_a.data(),sizeof(state_a)),state_b.data(),sizeof(state_b)); + }; + std::snprintf(name, sizeof(name), "%016llx.mesh57-state", variant()); + x2w_startup::Mesh57Profile profile{}; + std::memcpy(profile.magic, pixel_heap ? "X2WM576" : heap ? "X2WM575" : buffers ? "X2WM574" : constants ? "X2WM573" : varying ? "X2WM572" : "X2WM571", 8); + profile.lengths[0] = sizeof(fields); + profile.lengths[3] = static_cast<UINT>(blob->GetBufferSize()); + profile.lengths[1] = sizeof(state_a); + profile.lengths[2] = sizeof(state_b); + profile.lengths[4] = static_cast<UINT>(ms_size); + profile.lengths[5] = static_cast<UINT>(ps_size); + profile.threads = 64; + profile.vertices = 3; + profile.primitives = 1; + profile.topology = 2; + profile.group_stride = 64; + profile.wave_size = 64; + profile.targets.NumRenderTargets = 1; + profile.targets.RTFormats[0] = format; + profile.samples.Count = 1; + profile.sample_mask = UINT_MAX; + profile.rasterizer.FillMode = D3D12_FILL_MODE_SOLID; + profile.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + profile.rasterizer.DepthClipEnable = TRUE; + auto& blend = profile.blend.RenderTarget[0]; + blend.SrcBlend = blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlend = blend.DestBlendAlpha = D3D12_BLEND_ZERO; + blend.BlendOp = blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + blend.LogicOp = D3D12_LOGIC_OP_NOOP; + blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + profile.depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + if (mrt) { + const DXGI_FORMAT formats[]{DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, format, format, format, DXGI_FORMAT_R16G16_FLOAT, format}; + profile.targets.NumRenderTargets = static_cast<UINT>(std::size(formats)); + std::copy(std::begin(formats), std::end(formats), profile.targets.RTFormats); + profile.blend.IndependentBlendEnable = TRUE; + for (UINT i=1; i<profile.targets.NumRenderTargets; ++i) profile.blend.RenderTarget[i]=blend; + profile.blend.RenderTarget[4].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_RED | D3D12_COLOR_WRITE_ENABLE_GREEN; + if (masked) profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_RED; + profile.rasterizer.CullMode = D3D12_CULL_MODE_BACK; + profile.rasterizer.FrontCounterClockwise = TRUE; + profile.depth_format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + profile.depth.DepthEnable = TRUE; + profile.depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + profile.depth.DepthFunc = D3D12_COMPARISON_FUNC_GREATER_EQUAL; + profile.depth.StencilEnable = TRUE; + profile.depth.StencilReadMask = profile.depth.StencilWriteMask = 0xff; + profile.depth.FrontFace = profile.depth.BackFace = { + D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_REPLACE, D3D12_COMPARISON_FUNC_ALWAYS}; + } + { + std::ofstream out(cache / name, std::ios::binary); + const auto put = [&](const void* data, size_t n) { out.write(static_cast<const char*>(data), n); }; + put(&profile, sizeof(profile)); + if (varying) { + const UINT position_x = waterfall ? 1u<<8 : 0; + const x2w_startup::Mesh57PixelEntry entry{position_x,position_x,64}; + put(&entry,sizeof(entry)); + if (constants) { + const x2w_startup::Mesh57ConstantEntry mapping{12,4,1}; + put(&mapping,sizeof(mapping)); + if (buffers) { + const UINT count = 3; + const x2w_startup::Mesh57ViewEntry inputs[]{{16,0,0},{18,1,0},{20,3,1}}; + put(&count,sizeof(count)); + put(inputs,sizeof(inputs)); + if (heap) { const UINT sgpr = 47; put(&sgpr,sizeof(sgpr)); } + } + } + } + put(fields, sizeof(fields)); + put(state_a.data(), sizeof(state_a)); + put(state_b.data(), sizeof(state_b)); + put(blob->GetBufferPointer(), blob->GetBufferSize()); + put(ms.data(), ms_size); + put(ps.data(), ps_size); + if (!out) + return 1; + } + fields[15]=1; + char other_name[64]; + std::snprintf(other_name,sizeof(other_name),"%016llx.mesh57-state",variant()); + std::filesystem::copy_file(cache/name,cache/other_name,std::filesystem::copy_options::overwrite_existing); + fields[15]=0; + fields[0] = reinterpret_cast<UINT64>(root.Get()); + fields[1] = reinterpret_cast<UINT64>(state_a.data()); + fields[3] = reinterpret_cast<UINT64>(state_b.data()); + fields[5] = reinterpret_cast<UINT64>(ps.data()); + fields[13] = reinterpret_cast<UINT64>(ms.data()); + const auto create = [&] { + ComPtr<IUnknown> pso; + using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); + check(slot<Create>(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), + reinterpret_cast<void**>(pso.GetAddressOf())), + "create native fixed mesh"); + return pso; + }; + const auto pso = create(); + fields[15] = 1; // Same stages and root, unreviewed fixed pipeline state. + const auto mismatched = create(); + state_a.fill(0); + state_b.fill(0); + check(SetEnvironmentVariableA("X2W_MESH57_CAPTURE_STATE", "1") ? S_OK : E_FAIL, "enable fixed-state archive"); + D3D12_INDIRECT_ARGUMENT_DESC arg{}; + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + D3D12_COMMAND_SIGNATURE_DESC desc{sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), 1, &arg, 0}; + ComPtr<ID3D12CommandSignature> signature; + check(guest->CreateCommandSignature(&desc, nullptr, IID_PPV_ARGS(&signature)), "mesh signature"); + const auto work = writer_pipeline(device, writer, "write_one_mesh_group"); + const bool ok = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, + Refusal::none, "native fixed mesh triangle", nullptr, false, nullptr, false, false, 0, false, false, + nullptr, nullptr, false, 1, &profile) && + run(device, guest, writer, work.Get(), root.Get(), mismatched.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::none, "unreviewed fixed mesh state", nullptr, false, nullptr, false, false, 0, false, + false, nullptr, nullptr, false, 2, &profile); + if (ok && mrt && !run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::mesh_attachment_count, "native fixed mesh missing color attachment", nullptr, false, nullptr, false, + false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; + if (ok && constants && (!buffers || heap) && !run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::none, "native fixed mesh changed root4", nullptr, false, nullptr, false, + false, 0, false, false, nullptr, nullptr, false, 3, &profile)) return 1; + if (ok && pixel_heap && !run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false, + Refusal::mesh_pixel_hole,"PS bounded range has an unregistered slot",nullptr,false,nullptr,false,false,0,false,false, + nullptr,nullptr,false,2,&profile)) return 1; + if (ok && pixel_heap && !run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false, + Refusal::mesh_pixel_array,"PS Texture2DArray supplied to Texture2D",nullptr,false,nullptr,false,false,0,false,false, + nullptr,nullptr,false,2,&profile)) return 1; + if (ok && heap) { + for (int variant : {4,5}) { + if (!run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false,Refusal::none, + variant == 4 ? "heap slot 147 replaced view" : pixel_heap ? "PS explicit typed null" : "heap element beyond view",nullptr,false,nullptr,false, + false,0,false,false,nullptr,nullptr,false,variant,&profile)) return 1; + } + for (auto failure : {Refusal::mesh_wrong_heap_format,Refusal::mesh_empty_heap_slot,Refusal::mesh_outside_heap}) { + const char* label = failure == Refusal::mesh_wrong_heap_format ? "heap R32_FLOAT" : + failure == Refusal::mesh_empty_heap_slot ? "heap empty slot" : "heap index out of range"; + if (!run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false,failure, + label,nullptr,false,nullptr,false,false,0,false,false,nullptr,nullptr,false,2,&profile)) return 1; + } + } + if (ok && buffers) { + for (auto failure : {Refusal::mesh_short_table, Refusal::mesh_bad_root_address}) + if (!run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, failure, + failure == Refusal::mesh_short_table ? "short table1 SRV" : "unbacked root3 address", nullptr, false, + nullptr, false, false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; + } + if (ok && constants && !run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::incomplete_mesh_constants, "native fixed mesh missing root4", nullptr, false, nullptr, false, + false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; + if (!ok) + return 1; + for (const auto i : {0, 1, 3, 5, 13}) + fields[i] = 0; + const UINT sizes[]{sizeof(fields), sizeof(expected_a), sizeof(expected_b)}; + std::vector<char> expected; + const auto append = [&](const void* p, size_t n) { + const auto bytes = static_cast<const char*>(p); + expected.insert(expected.end(), bytes, bytes + n); + }; + append(&key, sizeof(key)); + append(sizes, sizeof(sizes)); + append(fields, sizeof(fields)); + append(expected_a.data(), sizeof(expected_a)); + append(expected_b.data(), sizeof(expected_b)); + auto valid = expected; + std::fill_n(valid.begin() + sizeof(key) + sizeof(sizes) + 15 * sizeof(UINT64), sizeof(UINT64), 0); + bool saw_valid = false, saw_other = false; + for (const auto& f : std::filesystem::directory_iterator(cache)) + if (f.path().extension() == ".s57") { + std::ifstream in(f.path(), std::ios::binary); + const std::vector<char> persisted(std::istreambuf_iterator<char>(in), {}); + if (persisted == valid && !saw_valid) saw_valid = true; + else if (persisted == expected && !saw_other) saw_other = true; + else return 1; + } + std::printf("fixed mesh state archives matching creation bytes: accepted=%d refused=%d\n", saw_valid, saw_other); + if (!saw_valid || !saw_other) return 1; + std::filesystem::remove_all(cache); + return 0; +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -1526,6 +2370,10 @@ int main(int argc, char** argv) try const bool copy_off = argc == 3 && std::strcmp(argv[2], "copy-provenance-off") == 0; const bool refusal_census_control = argc == 3 && std::strcmp(argv[2], "translated-refusal-census-control") == 0; const bool refusal_census = refusal_census_control || (argc == 3 && std::strcmp(argv[2], "translated-refusal-census") == 0); + const bool translated_targets = argc == 3 && std::strcmp(argv[2], "translated-targets") == 0; + const bool fallback_enabled = argc == 3 && std::strcmp(argv[2], "missing-shader-fallback") == 0; + const bool fallback_fixture = fallback_enabled || + (argc == 3 && std::strcmp(argv[2], "missing-shader-fallback-off") == 0); const bool other_refusal_census_control = argc == 3 && std::strcmp(argv[2], "indirect-other-refusal-census-control") == 0; const bool other_refusal_census = other_refusal_census_control || (argc == 3 && std::strcmp(argv[2], "indirect-other-refusal-census") == 0); const bool upload_index = argc == 3 && std::strcmp(argv[2], "translated-indexed-upload") == 0; @@ -1533,7 +2381,8 @@ int main(int argc, char** argv) try const bool alias_disabled = argc == 3 && std::strcmp(argv[2], "translated-indexed-alias-off") == 0; const bool alias_index = alias_disabled || (argc == 3 && std::strcmp(argv[2], "translated-indexed-alias") == 0); const bool translated_indexed = alias_index || upload_index || rect || (argc == 3 && std::strcmp(argv[2], "translated-indexed") == 0); - const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); + const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_targets || + fallback_fixture || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; @@ -1622,6 +2471,8 @@ int main(int argc, char** argv) try const auto root_flags = mesh ? D3D12_ROOT_SIGNATURE_FLAG_NONE : D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; const D3D12_ROOT_SIGNATURE_DESC graphics_desc{0, nullptr, 0, nullptr, root_flags}; const auto writer = create_root(device.Get(), writer_desc); + if (mesh && GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57", nullptr, 0)) + return native_fixed_mesh_fixture(device.Get(), guest.Get(), writer.Get()); wchar_t mesh86_dir[MAX_PATH]{}; if (mesh && GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_DIR", mesh86_dir, MAX_PATH)) { const bool depth_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH", nullptr, 0) != 0; @@ -1836,18 +2687,24 @@ int main(int argc, char** argv) try const auto ms_size = exchange_size ? source_ms.size() : sizeof(default_ms); const auto ps_size = exchange_size ? source_ps.size() : sizeof(default_ps); const auto make_pso = [&](bool with_pixel, bool with_vertex, bool incomplete_pixel) { + const auto* ms_begin = static_cast<const unsigned char*>(ms); + const auto* ps_begin = static_cast<const unsigned char*>(ps); + std::vector<unsigned char> caller_ms(ms_begin, ms_begin + ms_size); + std::vector<unsigned char> caller_ps(ps_begin, ps_begin + ps_size); std::array<UINT64, 0x300 / sizeof(UINT64)> fields{}; fields[0] = reinterpret_cast<UINT64>(root.Get()); - fields[5] = with_pixel ? reinterpret_cast<UINT64>(ps) : 0; + fields[5] = with_pixel ? reinterpret_cast<UINT64>(caller_ps.data()) : 0; fields[6] = with_pixel && !incomplete_pixel ? ps_size : 0; fields[9] = with_vertex ? reinterpret_cast<UINT64>(ps) : 0; fields[10] = with_vertex ? ps_size : 0; - fields[13] = reinterpret_cast<UINT64>(ms); + fields[13] = reinterpret_cast<UINT64>(caller_ms.data()); fields[14] = ms_size; using Create = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); ComPtr<IUnknown> pso; check(slot<Create>(guest.Get(), 57)(guest.Get(), fields.data(), __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso.GetAddressOf())), "create fixed mesh placeholder"); + std::fill(caller_ms.begin(), caller_ms.end(), 0xcc); + std::fill(caller_ps.begin(), caller_ps.end(), 0xcc); return pso; }; D3D12_INDIRECT_ARGUMENT_DESC mesh_argument{}; @@ -1878,8 +2735,9 @@ int main(int argc, char** argv) try return !size || (stream.read(contents.data(), size) && std::memcmp(contents.data(), bytes, size) == 0); }; for (const auto& file : std::filesystem::directory_iterator(cache)) { - ++files; auto path = file.path(); + if (path.filename() == "revision.txt") continue; // the runtime's revisions, written with the first request + ++files; if (path.extension() != ".m57") continue; ++requests; if (!matches(path, ms, ms_size) || @@ -1910,7 +2768,7 @@ int main(int argc, char** argv) try ComPtr<ID3DBlob> root_blob; const auto title_root = create_root(guest.Get(), title_desc, &root_blob); if (translated_indexed) { - const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), true, false, true, rect); + const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), true, TableSample::texture, true, rect); const auto left = writer_pipeline(device.Get(), writer.Get(), "write_left"); const auto right = writer_pipeline(device.Get(), writer.Get(), "write_indexed_base"); const auto invalid = writer_pipeline(device.Get(), writer.Get(), "write_indexed_overrun"); @@ -1973,8 +2831,23 @@ int main(int argc, char** argv) try return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; } const auto pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false); + if (fallback_fixture) { + check(SetEnvironmentVariableW(L"X2W_DRAW_MISSING_SHADER", fallback_enabled ? L"1" : L"0") ? S_OK : E_FAIL, + "configure missing shader fallback"); + std::filesystem::path manifest; + for (const auto& file : std::filesystem::directory_iterator(cache)) + if (file.path().extension() == ".txt") manifest = file.path(); + check(manifest.empty() ? E_FAIL : S_OK, "find fixture manifest"); + const auto producer = writer_pipeline(device.Get(), writer.Get(), "write_one_triangle"); + const TranslatedDrawFixture binding(guest.Get(), red); + const bool ok = check_translated_targets(device.Get(), guest.Get(), writer.Get(), producer.Get(), + title_root.Get(), pso.Get(), nullptr, binding, + manifest, fallback_enabled); + std::filesystem::remove_all(cache); + return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; + } const auto start_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), true); - const auto buffer_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false, true); + const auto buffer_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false, TableSample::buffer); const auto producer = writer_pipeline(device.Get(), writer.Get(), "write_one_triangle"); const auto buffer_writer = writer_pipeline(device.Get(), writer.Get(), "write_buffer_colour"); D3D12_INDIRECT_ARGUMENT_DESC argument{}; @@ -2008,6 +2881,30 @@ int main(int argc, char** argv) try DeleteFileW(log_path.c_str()); return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; } + if (translated_targets) { + const bool ok = check_translated_targets(device.Get(), guest.Get(), writer.Get(), producer.Get(), + title_root.Get(), pso.Get(), signature.Get(), red_binding); + std::filesystem::remove_all(cache); + bool debug_ok = true; + if (info) { + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + info->GetMessage(i, nullptr, &bytes); + std::vector<char> storage(bytes); + auto* msg = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + info->GetMessage(i, msg, &bytes); + // Message 679 (PS expects RTV0 with NumRenderTargets=0) is an expected benign warning when + // reusing the colour-writing pixel shader for the depth-only pass. + if (msg->Severity <= D3D12_MESSAGE_SEVERITY_ERROR || + (msg->Severity == D3D12_MESSAGE_SEVERITY_WARNING && msg->ID != 679)) { + std::fprintf(stderr, "D3D12 debug message %u (sev %d): %s\n", + static_cast<unsigned>(msg->ID), static_cast<int>(msg->Severity), msg->pDescription); + debug_ok = false; + } + } + } + return ok && debug_ok ? 0 : 1; + } if (other_refusal_census) { bool ok = verify(producer.Get(), false, Refusal::none, "other census warm up translated pipeline key") && verify(producer.Get(), false, Refusal::missing_viewport, "other census key1 missing_viewport_or_scissor #1") && @@ -2047,12 +2944,25 @@ int main(int argc, char** argv) try if (SUCCEEDED(D3D12SerializeRootSignature(&deferred_desc, D3D_ROOT_SIGNATURE_VERSION_1, &deferred_blob, nullptr)) && SUCCEEDED(guest->CreateRootSignature(0, deferred_blob->GetBufferPointer(), deferred_blob->GetBufferSize(), IID_PPV_ARGS(&deferred_root)))) { - const auto deferred_pso = translated_pipeline(guest.Get(), deferred_root.Get(), deferred_blob.Get(), false, true); + const auto deferred_pso = translated_pipeline(guest.Get(), deferred_root.Get(), deferred_blob.Get(), false, TableSample::buffer); if (ok) ok = run(device.Get(), guest.Get(), writer.Get(), producer.Get(), deferred_root.Get(), deferred_pso.Get(), signature.Get(), DrawKind::vertices, false, Refusal::none, "translated table with deferred guest root", &full_buffer); } else { std::puts("deferred guest root capability unavailable"); } + if (ok && !copy_on && !copy_off) { + const auto tail_pso = translated_pipeline(guest.Get(), title_root.Get(), root_blob.Get(), false, TableSample::buffer_tail); + const auto tail_writer = writer_pipeline(device.Get(), writer.Get(), "write_large_buffer_colour"); + // Both resources contain the sentinel. Only the full view includes the final DWORD. + for (bool short_view : {false, true}) { + TranslatedDrawFixture large(guest.Get(), 0, device.Get(), short_view, false, false, false, 0x1000020); + large.buffer_writer = tail_writer; + ok = run(device.Get(), guest.Get(), writer.Get(), producer.Get(), title_root.Get(), tail_pso.Get(), signature.Get(), + DrawKind::vertices, false, short_view ? Refusal::insufficient_table_range : Refusal::none, + short_view ? "large buffer tail outside view" : "large buffer tail inside view", &large); + if (!ok) break; + } + } if (ok && (copy_on || copy_off)) { const TranslatedDrawFixture copied(guest.Get(), green, device.Get(), false, true, true); const auto source = make_gpu_table_buffer(guest.Get(), replay_copy_offset + replay_copy_bytes); diff --git a/tests/startup_indirect_writer.h b/tests/startup_indirect_writer.h new file mode 100644 index 0000000000..b853427d37 --- /dev/null +++ b/tests/startup_indirect_writer.h @@ -0,0 +1,26 @@ +#pragma once +#include "desktop_gpu.h" + +template <typename T> +Microsoft::WRL::ComPtr<T> indirect_native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +{ + // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. + constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; + check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); + Microsoft::WRL::ComPtr<IUnknown> stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); + check(read, "retrieve underlying object"); + Microsoft::WRL::ComPtr<T> result; + check(stored.As(&result), "query underlying object"); + return result; +} + +inline void record_indirect_writer(ID3D12GraphicsCommandList* list, ID3D12PipelineState* writer, + ID3D12Resource* arguments) +{ + list->SetPipelineState(writer); + list->SetComputeRootUnorderedAccessView(0, arguments->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); +} diff --git a/tests/startup_inline_sampler_check.py b/tests/startup_inline_sampler_check.py index f73fe79b25..c0c7003201 100644 --- a/tests/startup_inline_sampler_check.py +++ b/tests/startup_inline_sampler_check.py @@ -35,6 +35,11 @@ WRAP_SOURCE = CLAMP_SOURCE.replace('s_bfm_b32 s24, s28, 33', 's_bfm_b32 s24, 0, 33') WRAP_WORDS = CLAMP_WORDS.replace(bytes.fromhex('1ca11892'), bytes.fromhex('80a11892')) +# The clamp sampler with word 0 built in s29 and copied into s24 (s_mov_b32 s24, s29): only the copy fold lets +# the four words be read as constants, so the draw below depends on it. +COPY_CLAMP_SOURCE = CLAMP_SOURCE.replace('s_bfm_b32 s24, s28, 33', 's_bfm_b32 s29, s28, 33\ns_mov_b32 s24, s29') +COPY_CLAMP_WORDS = CLAMP_WORDS.replace(bytes.fromhex('1ca11892'), bytes.fromhex('1ca11d92' '1d0398be')) + # s9 is root constant 1. Overwrite a previously folded word to check that the # run-time write clears its constant value before the sampler is consumed. DYNAMIC_SOURCE = CLAMP_SOURCE.replace('v_mov_b32 v0,', 's_bfm_b32 s24, s9, 33\nv_mov_b32 v0,') @@ -74,12 +79,78 @@ def bare_stage(symbols=None): except AttributeError: pass +# llc builds a constant sampler by copying one zeroed SGPR into the other words (s_mov_b32 s25, s24). +COPY_WORDS = IMAGE_WORDS.replace( + bytes.fromhex('800398be' '800399be' '80039abe' '80039bbe'), + bytes.fromhex('800398be' '180399be' '18039abe' '18039bbe'), +) + + +def check_copied_constant_sampler(): + """A sampler word copied from a constant SGPR is that constant, not an unknown value.""" + assert COPY_WORDS != IMAGE_WORDS + expected = [l for l in translate(IMAGE_WORDS).manifest().splitlines() if l.startswith('smp ')] + got = [l for l in translate(COPY_WORDS).manifest().splitlines() if l.startswith('smp ')] + assert got == expected and got, (got, expected) + print('copied constant sampler folds to %s' % got[0]) + + +def copy_symbol(symbols, copy='s_mov_b32 s12, s15'): + """The symbol s12 holds after `copy` runs on a bare stage that starts with `symbols`.""" + class Pipe: + sampler_heap = False + + stage = G.Stage.__new__(G.Stage) + stage.pipe, stage.sym, stage.lines = Pipe(), dict(symbols), [] + stage.used_s, stage.used_v, stage.uniform_v, stage.exec_known = set(), set(), set(), True + stage.has_branches, stage.masks = False, set() + stage.one(copy.split()[0], copy) + return stage.sym.get(12) + + +def check_copy_only_folds_plain_constants(): + """Only a plain ('const', value) copies as a constant; every other source must not fold.""" + assert copy_symbol({15: ('const', 0)}) == ('const', 0) + # The default-sampler placeholder is tagged 'unassigned': a copy of it is no run-time constant. + assert copy_symbol({15: ('const', 0, 'unassigned')}) != ('const', 0) + # A register that holds a root constant or nothing known is not a constant. + assert copy_symbol({15: ('ud', 1)}) != ('const', 1) + assert copy_symbol({}) is None + # A copy of a plain constant takes that constant's value. + assert copy_symbol({15: ('const', 7)}) == ('const', 7) + print('copies fold only plain constants') + + +def check_copied_sampler_after_overwrite(): + """A sampler word copied after its source was rewritten by a run-time value or another constant.""" + prefix = bytes.fromhex('800398be') # s_mov_b32 s24, 0 + copies = bytes.fromhex('180399be' '18039abe' '18039bbe') + anchor = prefix + copies + assert anchor in COPY_WORDS + runtime = COPY_WORDS.replace(anchor, prefix + bytes.fromhex('090398be') + copies) # s24 = s9 (root constant) + try: + translate(runtime) + except G.Unsupported as error: + assert 'holds' in str(error), error + else: + raise AssertionError('a sampler copied from a run-time register was accepted') + # s28 = 0, then s28 = 1, then s27 = s28; s24..s26 stay literal zeros + one = COPY_WORDS.replace(anchor, bytes.fromhex('800398be' '800399be' '80039abe' '80039cbe' '81039cbe' '1c039bbe')) + smp = [l for l in translate(one).manifest().splitlines() if l.startswith('smp ')] + assert smp == ['smp 0 0x0 0x0 0x0 0x1'], smp + print('copy after overwrite: run-time source refused, new constant wins (%s)' % smp[0]) + + def controls(): check_compare_sampler_constant() + check_copied_constant_sampler() + check_copy_only_folds_plain_constants() + check_copied_sampler_after_overwrite() fixtures = [] for name, code, words in ( ('clamp', CLAMP_WORDS, (0x2, 0, 0x00100000, 0)), ('wrap', WRAP_WORDS, (0, 0, 0x00100000, 0)), + ('copied clamp', COPY_CLAMP_WORDS, (0x2, 0, 0x00100000, 0)), ): pipe = translate(code) manifest = pipe.manifest() @@ -98,8 +169,9 @@ def controls(): print('root-constant mask width: inline sampler refused (%s)' % error) else: raise AssertionError('run-time write to s24 was accepted as an inline sampler') - (clamp_ps, clamp_line), (_, wrap_line) = fixtures - return clamp_ps, clamp_line, wrap_line + (clamp_ps, clamp_line), (_, wrap_line), (copy_ps, copy_line) = fixtures + assert copy_line == clamp_line, (copy_line, clamp_line) + return clamp_ps, clamp_line, wrap_line, copy_ps def check_binary(llvm_mc): @@ -107,14 +179,15 @@ def check_binary(llvm_mc): ('clamp', CLAMP_SOURCE, CLAMP_WORDS), ('wrap', WRAP_SOURCE, WRAP_WORDS), ('root constant', DYNAMIC_SOURCE, DYNAMIC_WORDS), + ('copied clamp', COPY_CLAMP_SOURCE, COPY_CLAMP_WORDS), ): built = assemble(llvm_mc, source) assert built == recorded, '%s: assembled %s, recorded %s' % (name, built.hex(), recorded.hex()) - print('all three fixture programs match llvm-mc') + print('all four fixture programs match llvm-mc') def check_draw(dxc, renderer, adapter, fxc=None): - ps, clamp, wrap = controls() + ps, clamp, wrap, copy_ps = controls() expected_clamp = texel(1, 0, 0) expected_wrap = texel(0, 0, 0) compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] @@ -129,9 +202,13 @@ def check_draw(dxc, renderer, adapter, fxc=None): for kind, compiler, vs_profile, ps_profile in compilers: vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'fullscreen', vs_profile, directory) shader = compile_hlsl(compiler, kind, ps, 'inline_sampler', ps_profile, directory) - command = [renderer, adapter, '--startup-image-3d', str(vs), str(shader), '0.25', expected_clamp] - # Hold shader, texture, and reference fixed. Only the manifest sampler changes. - for label, line, result in (('clamp', clamp, 0), ('wrap control', wrap, 1)): + copy_shader = compile_hlsl(compiler, kind, copy_ps, 'inline_sampler_copy', ps_profile, directory) + # Hold shader, texture, and reference fixed. Only the manifest sampler changes. The copied-word shader + # is drawn with its own sampler (must read the clamped texel) and with the wrap sampler (must mismatch). + for label, shader_path, line, result in (('clamp', shader, clamp, 0), ('wrap control', shader, wrap, 1), + ('copied-word clamp', copy_shader, clamp, 0), + ('copied-word wrap control', copy_shader, wrap, 1)): + command = [renderer, adapter, '--startup-image-3d', str(vs), str(shader_path), '0.25', expected_clamp] run = subprocess.run([*command, line], capture_output=True, text=True) print(run.stdout, end='', flush=True) if run.returncode == 77: diff --git a/tests/startup_joined_table_pointer_check.py b/tests/startup_joined_table_pointer_check.py new file mode 100644 index 0000000000..4672736b64 --- /dev/null +++ b/tests/startup_joined_table_pointer_check.py @@ -0,0 +1,211 @@ +"""Check 32-bit graphics table pointers at forward joins and read both bound textures (#2463). + +Run with no arguments for the host controls, or with binary <llvm-mc> to reassemble every source. +The draw arguments are <startup_stream_consumer> <warp|hardware> <fxc|dxc> <dxc> <fxc>. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_flat_param_check import G, PS_WORDS, VS_WORDS, assemble +from startup_gfx2hlsl_join_symbols_check import root +from startup_stream_draw_check import container, vertex +from startup_mrt_check import compile_shader + + +# LLVM 15 gfx1013 encodings. Each program is also assembled in full by the binary check. +WORDS = { + 'buffer_load_dword v6, off, s[16:19], 0': '000030e000060480', + 'exp mrt0 v4, v5, v6, v7 done vm': '0f1800f804050607', + 'exp param0 v6, v6, v6, v6': '0f0200f806060606', + 'exp pos0 v6, v6, v6, v6 done': 'cf0800f806060606', + 'image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D': '080f00f000040400', + 's_add_u32 s24, s24, 32': '18a01880', + 's_add_u32 s24, s0, 16': '00901880', + 's_add_u32 s24, s8, 32': '08a01880', + 's_add_u32 s24, s8, 64': '08c01880', + 's_add_u32 s26, s26, 0xfffff': '1aff1a80ffff0f00', + 's_add_u32 s26, s26, 2': '1a821a80', + 's_add_u32 s26, s26, 32': '1aa01a80', + 's_add_u32 s26, s26, s9': '1a091a80', + 's_cbranch_scc1 1': '010085bf', + 's_cbranch_scc1 65531': 'fbff85bf', + 's_cbranch_scc1 65533': 'fdff85bf', + 's_cmp_eq_u32 s9, 0': '098006bf', + 's_cmp_eq_u32 s9, 1': '098106bf', + 's_cmp_lg_u32 s30, 0': '1e8007bf', + 's_endpgm': '000081bf', + 's_load_dwordx4 s[16:19], s[0:1], 0x20': '000408f4200000fa', + 's_load_dwordx4 s[16:19], s[24:25], 0x10': '0c0408f4100000fa', + 's_load_dwordx8 s[16:23], s[24:25], 0x0': '0c040cf4000000fa', + 's_mov_b32 s24, 5': '850398be', + 's_mov_b32 s24, s26': '1a0398be', + 's_mov_b32 s24, s8': '080398be', + 's_mov_b32 s25, 0': '800399be', + 's_mov_b32 s25, s1': '010399be', + 's_mov_b32 s26, 13': '8d039abe', + 's_mov_b32 s26, s8': '08039abe', + 's_mov_b32 s30, 17': '91039ebe', + 's_mov_b32 s30, 2': '82039ebe', + 's_sub_u32 s30, s30, 1': '1e819e80', + 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 's_waitcnt vmcnt(0)': '703f8cbf', + 's_xor_b32 s26, s26, 16': '1a901a89', + 'v_cvt_f32_u32_e32 v5, s9': '090c0a7e', + 'v_mov_b32 v0, 0': '8002007e', + 'v_mov_b32 v1, 0': '8002027e', + 'v_mul_f32_e32 v5, 0x3e000000, v5': 'ff0a0a100000003e', +} + +PREFIX = """s_cmp_eq_u32 s9, 0 +s_cbranch_scc1 1 +s_mov_b32 s24, 5 +""" +ADVANCE = """s_mov_b32 s26, s8 +s_add_u32 s26, s26, 32 +s_mov_b32 s24, s26 +""" +BRANCH = """s_cmp_eq_u32 s9, 1 +s_cbranch_scc1 1 +""" +HIGH = 's_mov_b32 s25, 0\n' +DRAW = """v_mov_b32 v0, 0 +v_mov_b32 v1, 0 +s_load_dwordx8 s[16:23], s[24:25], 0x0 +s_waitcnt lgkmcnt(0) +image_load v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +v_cvt_f32_u32_e32 v5, s9 +v_mul_f32_e32 v5, 0x3e000000, v5 +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm +""" +HELD = PREFIX + ADVANCE + HIGH + BRANCH +# Each accepted program loads one descriptor. The old arm writes s24 before the copy. +# Once s24 holds the pointer, a write to its source s26 cannot change it. +ACCEPT = { + 'base': ('s_mov_b32 s24, s8\n' + HIGH, 0), + 'straight': (ADVANCE + HIGH, 32), + 'joined': (HELD + 's_mov_b32 s30, 17\n', 32), + 'source changed': (HELD + 's_mov_b32 s26, 13\n', 32), + 'equal addresses': (HELD + 's_add_u32 s24, s8, 32\n', 32), +} +REJECT = { + 'different addresses': (HELD + 's_add_u32 s24, s8, 64\n', 'joined at a branch target'), + 'missing on an arm': (BRANCH + 's_add_u32 s24, s8, 32\n' + HIGH, 'joined at a branch target'), + 'unproven address': (HELD.replace('s_add_u32 s26, s26, 32', 's_add_u32 s26, s26, s9') + + 's_mov_b32 s30, 17\n', 'joined at a branch target'), + 'unsupported arithmetic': (ADVANCE.replace('s_mov_b32 s24, s26', 's_xor_b32 s26, s26, 16\ns_mov_b32 s24, s26') + + HIGH + BRANCH + 's_mov_b32 s30, 17\n', 'untracked offset'), + 'loop-carried address': (ADVANCE + HIGH + 's_add_u32 s24, s24, 32\ns_cmp_eq_u32 s9, 0\ns_cbranch_scc1 65533\n', + 'joined at a branch target'), + # Reset the low word inside each of two iterations. The join alone cannot reject the load: + # it is the restriction to forward edges that prevents the advance from being folded. + 'advance inside a backward loop': ( + 's_mov_b32 s30, 2\ns_mov_b32 s24, s8\ns_add_u32 s24, s24, 32\n' + 's_sub_u32 s30, s30, 1\ns_cmp_lg_u32 s30, 0\ns_cbranch_scc1 65531\n' + HIGH, 'untracked offset'), + 'offset overflow': (HELD.replace('s_add_u32 s26, s26, 32', 's_add_u32 s26, s26, 0xfffff\ns_add_u32 s26, s26, 2') + + 's_mov_b32 s30, 17\n', 'accumulated table pointer offset'), +} + +# The direct load reads VB slot 2. The low add in the second program may carry, so copying +# the original high word is insufficient to prove the same address. +VB_DRAW = """s_waitcnt lgkmcnt(0) +buffer_load_dword v6, off, s[16:19], 0 +s_waitcnt vmcnt(0) +exp pos0 v6, v6, v6, v6 done +exp param0 v6, v6, v6, v6 +s_endpgm +""" +VB_DIRECT = 's_load_dwordx4 s[16:19], s[0:1], 0x20\n' + VB_DRAW +VB_COPIED_HIGH = ('s_add_u32 s24, s0, 16\ns_mov_b32 s25, s1\n' + 's_load_dwordx4 s[16:19], s[24:25], 0x10\n' + VB_DRAW) + + +def encode(source): + return bytes.fromhex(''.join(WORDS[line] for line in source.splitlines())) + + +def bindings(vs, ps): + pipe = G.Pipeline(vs, ps, root('t', 1)) + return [line for line in pipe.manifest().splitlines() if line.startswith('srv ')] + + +def require_refusal(name, vs, ps, reason): + try: + bindings(vs, ps) + except G.Unsupported as error: + assert reason in str(error), (name, str(error)) + else: + raise AssertionError(f'{name} was accepted') + + +def check_host(): + for name, (prefix, offset) in ACCEPT.items(): + assert bindings(VS_WORDS, encode(prefix + DRAW)) == [f'srv 0 tex2d table 0 {offset}'], name + for name, (prefix, reason) in REJECT.items(): + require_refusal(name, VS_WORDS, encode(prefix + DRAW), reason) + assert bindings(encode(VB_DIRECT), PS_WORDS) == ['srv 0 buf vb 2'] + require_refusal('copied vertex buffer table high word', encode(VB_COPIED_HIGH), PS_WORDS, + 'its high word is not the matching advanced pair') + print('Graphics table pointer joins: six resource bindings and eight refusals matched') + + +def expected(offset): + # Each group of four columns sees opposite table contents. G records the root constant + # used by the branches. Multiplication by 1/8 avoids ambiguous half-integer UNORM results. + return bytes(channel for _ in range(4) for x in range(8) for channel in + (16 + 128 * ((offset // 32) ^ (x // 4)), (0, 32, 64, 96)[x % 4], 0, 255)) + + +def draw(folder, consumer, backend, kind, compiler, prefix, offset): + cache = folder / 'cache' + cache.mkdir() + vs, ps, signature, pixels = (folder / file for file in ('vs', 'ps', 'root', 'pixels')) + vs.write_bytes(vertex()) + ps.write_bytes(container(0, [word for word, in struct.iter_unpack('<I', encode(prefix + DRAW))])) + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_TEST_JOINED_TABLE='1', X2W_SHADER_CACHE=str(cache), X2W_FXC=str(compiler) if kind == 'fxc' else '') + env['PATH'] = str(Path(compiler).resolve().parent) + os.pathsep + env['PATH'] + cmd = [consumer, vs, ps, signature] + subprocess.run(cmd, env=env, check=True) + subprocess.run([sys.executable, '-B', G.__file__, '--pending', cache], env=env, check=True) + manifest, = (path for path in cache.glob('*.txt') if path.name != 'revision.txt') + text = manifest.read_text(encoding='ascii') + line = f'srv 0 tex2d table 0 {offset}' + assert text.splitlines().count(line) == 1 + for stage in ('vs', 'ps'): + compile_shader(compiler, kind, stage, manifest.with_suffix(f'.{stage}.hlsl'), + manifest.with_suffix(f'.{stage}.cso'), folder / f'{stage}.asm') + baseline = expected(offset) + for wanted in (offset, 32 - offset): + manifest.write_text(text.replace(line, f'srv 0 tex2d table 0 {wanted}'), encoding='ascii') + result = subprocess.run(cmd + [backend, pixels], env=env, capture_output=True, text=True) + if result.returncode == 77: + raise SystemExit(77) + assert result.returncode == 0 and '-> drawn;' in result.stderr, result.stdout + result.stderr + data = pixels.read_bytes() + assert data == expected(wanted), (data.hex(), expected(wanted).hex()) + changes = sum(data[i:i+4] != baseline[i:i+4] for i in range(0, len(data), 4)) + assert changes == (0 if wanted == offset else 32), changes + print(f'{kind} {backend} table byte {wanted}, {changes} pixels changed from the source expectation') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + check_host() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + sources = [prefix + DRAW for prefix, _ in (*ACCEPT.values(), *REJECT.values())] + for source in [*sources, VB_DIRECT, VB_COPIED_HIGH]: + assert assemble(sys.argv[2], source) == encode(source) + print('All fourteen graphics table fixtures match gfx1013 assembly') + elif len(sys.argv) == 6: + consumer, backend, kind, dxc, fxc = sys.argv[1:] + for prefix, offset in ACCEPT.values(): + with tempfile.TemporaryDirectory() as temporary: + draw(Path(temporary), consumer, backend, kind, fxc if kind == 'fxc' else dxc, prefix, offset) + else: + raise SystemExit(__doc__) diff --git a/tests/startup_launch_check.py b/tests/startup_launch_check.py index 7b09b15c0a..5f424950ef 100644 --- a/tests/startup_launch_check.py +++ b/tests/startup_launch_check.py @@ -34,10 +34,30 @@ def captured(logdir, name): return path.read_text(encoding="utf-8") if path.exists() else None +def child_env(extra): + """The environment of a probe child: ours without X2W_LOW_ADDRESSES (a caller that has it set must not turn the + default runs into low-address runs), plus `extra`.""" + env = {k: v for k, v in os.environ.items() if k != "X2W_LOW_ADDRESSES"} + env.update(extra) + return env + + def run_unit_tests(): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) + # 0. The control children never inherit X2W_LOW_ADDRESSES; the switch-on children get it only from the test. + saved = os.environ.get("X2W_LOW_ADDRESSES") + os.environ["X2W_LOW_ADDRESSES"] = "1" + try: + assert "X2W_LOW_ADDRESSES" not in child_env({}), "the control environment kept X2W_LOW_ADDRESSES" + assert child_env({"X2W_LOW_ADDRESSES": "1"})["X2W_LOW_ADDRESSES"] == "1" + finally: + if saved is None: + del os.environ["X2W_LOW_ADDRESSES"] + else: + os.environ["X2W_LOW_ADDRESSES"] = saved + # 1. X2W_STORAGE_PATH fallback creation when unset/empty and default missing. logdir = root / "run_unset" logdir.mkdir() @@ -222,6 +242,26 @@ def main(probe): assert result.returncode == 0, result.stderr assert captured(logdir, "stdout.txt") == "spawn ok\n", captured(logdir, "stdout.txt") + # X2W_LOW_ADDRESSES=1 starts the child with bottom-up ASLR off, so its blocks stay below 2^40 (the package + # acceleration-structure builder refuses a destination with bits set above bit 39, #1758). + limit = 1 << 40 + + def highest(env_extra, name): + env = child_env(env_extra) + result, logdir, _ = launch(probe, work, name, ["--timeout", "20"], ["addresses"], env=env) + assert result.returncode == 0, result.stderr + text = captured(logdir, "stdout.txt") + assert text and text.startswith("addresses highest=0x"), (text, result.stdout) + return int(text.split("=")[1], 16), result.stdout + + for attempt in range(4): + top, out = highest({"X2W_LOW_ADDRESSES": "1"}, f"low-{attempt}") + assert top < limit, f"with X2W_LOW_ADDRESSES=1 a block ends at 0x{top:x}, above 2^40" + assert "bottom-up ASLR off" in out, out + # Control: without the switch, the same child gets blocks above 2^40 on some runs (the default ASLR picks a random start). + above = [highest({}, f"default-{attempt}")[0] >= limit for attempt in range(8)] + assert any(above), "the control never saw a block above 2^40, so the check above proves nothing on this host" + # A missing executable is reported instead of looking like a finished run. logdir = work / "missing" logdir.mkdir() diff --git a/tests/startup_launch_probe.cpp b/tests/startup_launch_probe.cpp index 732092034d..b71e889b99 100644 --- a/tests/startup_launch_probe.cpp +++ b/tests/startup_launch_probe.cpp @@ -2,10 +2,13 @@ // executable in a kill-on-close job with a timeout, a commit cap and captured stdout/stderr, and // this fixture is the only executable the check needs: it writes known bytes to both streams and // the trap log, reports a known exit code, or holds memory, spawns a child or stays alive so the -// job limits have to stop it. Paths stay UTF-16 throughout: the launcher passes a Unicode trap-log +// job limits have to stop it. The "overlap" mode (from X2W_LAUNCH_PROBE_MODE, because the debugger passes no +// arguments) opens one file from four threads that enter CreateFileW together, for tests/startup_hook_check.py. Paths stay UTF-16 throughout: the launcher passes a Unicode trap-log // path, and its build or temp folder can hold characters the active ANSI code page cannot. #include <windows.h> +#include <algorithm> +#include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> @@ -45,11 +48,56 @@ void spawn_second_process(const wchar_t* self) CloseHandle(child.hProcess); std::printf("spawn ok\n"); } +constexpr int overlap_threads = 4; +constexpr int overlap_rounds = 16; + +struct Overlap { + const wchar_t* path; + volatile LONG arrived[overlap_rounds]; + volatile LONG opened; +}; + +// All threads spin for each other before every open, so each round enters the same function at once. +DWORD WINAPI overlap_thread(LPVOID parameter) +{ + auto* shared = static_cast<Overlap*>(parameter); + for (int round = 0; round < overlap_rounds; ++round) { + InterlockedIncrement(&shared->arrived[round]); + const ULONGLONG begin = GetTickCount64(); + while (shared->arrived[round] < overlap_threads && GetTickCount64() - begin < 10000) YieldProcessor(); + const HANDLE file = CreateFileW(shared->path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) continue; + CloseHandle(file); + InterlockedIncrement(&shared->opened); + } + return 0; +} + +int overlapping_opens() +{ + wchar_t path[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableW(L"X2W_LAUNCH_PROBE_FILE", path, MAX_PATH); + if (length == 0 || length >= MAX_PATH) return 64; + static Overlap shared{}; + shared.path = path; + HANDLE threads[overlap_threads]{}; + for (HANDLE& thread : threads) { + thread = CreateThread(nullptr, 0, overlap_thread, &shared, 0, nullptr); + if (!thread) return 65; + } + const DWORD waited = WaitForMultipleObjects(overlap_threads, threads, TRUE, 60000); + constexpr int total = overlap_threads * overlap_rounds; + std::printf("overlap opens %ld of %d\n", static_cast<long>(shared.opened), total); + return waited == WAIT_OBJECT_0 && shared.opened == total ? 0 : 1; +} } // namespace int main(int argc, char** argv) { const char* mode = argc > 1 ? argv[1] : "report"; + char from_env[16]{}; + if (argc == 1 && GetEnvironmentVariableA("X2W_LAUNCH_PROBE_MODE", from_env, sizeof(from_env))) mode = from_env; + if (std::strcmp(mode, "overlap") == 0) return overlapping_opens(); if (std::strcmp(mode, "report") == 0) { stream(stdout, "launch-probe stdout\n"); stream(stderr, "launch-probe stderr\n"); @@ -73,6 +121,21 @@ int main(int argc, char** argv) VirtualFree(memory, 0, MEM_RELEASE); return 0; } + if (std::strcmp(mode, "addresses") == 0) { + // The highest address VirtualAlloc hands out for blocks of several sizes (the title's blocks come the same way). + unsigned long long highest = 0; + const SIZE_T sizes[] = {SIZE_T{64} << 10, SIZE_T{16} << 20, SIZE_T{1} << 30, SIZE_T{4} << 30}; + for (const SIZE_T bytes : sizes) { + void* memory = VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS); + if (!memory) { + std::printf("addresses failed error=%lu\n", GetLastError()); + return 0; + } + highest = (std::max)(highest, static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(memory)) + bytes - 1); + } + std::printf("addresses highest=0x%llx\n", highest); + return 0; + } if (std::strcmp(mode, "spawn") == 0) { wchar_t self[MAX_PATH]{}; if (!GetModuleFileNameW(nullptr, self, MAX_PATH)) return 65; diff --git a/tests/startup_list_dispatch_check.cpp b/tests/startup_list_dispatch_check.cpp new file mode 100644 index 0000000000..17abf36480 --- /dev/null +++ b/tests/startup_list_dispatch_check.cpp @@ -0,0 +1,90 @@ +// Checks src/startup_stubs/list_dispatch.h without a device: when command-list slot 14 (Dispatch) is forwarded to the +// desktop list and which refusal applies otherwise. Expectations are written out below, not computed with the header. +// +// startup_list_dispatch_check [--mutate no-limit|no-state|no-root-args|no-pairing|no-bound] +// +// The mutations change the expectations to those of a wrong decision (no group-count limit, a forward without a +// compute pipeline and root, or a forward with unforwarded compute root arguments); each must make the check fail. +#include "startup_stubs/list_dispatch.h" + +#include <cstdio> +#include <cstring> + +namespace { +using namespace x2w_startup; +using D = DispatchDecision; +int failures, cases; +bool no_limit, no_state, no_root_args, no_pairing, no_bound; + +void expect(const char* label, const ListDispatch& in, D expected) +{ + ++cases; + const D got = decide_dispatch(in); + if (got == expected) return; + ++failures; + std::printf("FAIL %s: expected '%s', got '%s'\n", label, dispatch_reason(expected), dispatch_reason(got)); +} + +ListDispatch ready(UINT x, UINT y, UINT z) +{ + ListDispatch d; + d.list_open = true; + d.compute_pipeline = d.compute_root = true; + d.x = x, d.y = y, d.z = z; + return d; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate")) { + no_limit = !std::strcmp(argv[2], "no-limit"); + no_state = !std::strcmp(argv[2], "no-state"); + no_root_args = !std::strcmp(argv[2], "no-root-args"); + no_pairing = !std::strcmp(argv[2], "no-pairing"); + no_bound = !std::strcmp(argv[2], "no-bound"); + if (!no_limit && !no_state && !no_root_args && !no_pairing && !no_bound) return 2; + } + expect("one group", ready(1, 1, 1), D::forward); + expect("limit on every axis", ready(65535, 65535, 65535), D::forward); + expect("zero groups", ready(0, 5, 5), D::forward); + expect("x over limit", ready(65536, 1, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("y over limit", ready(1, 65536, 1), no_limit ? D::forward : D::group_count_over_limit); + expect("z over limit", ready(1, 1, 0xffffffffu), no_limit ? D::forward : D::group_count_over_limit); + ListDispatch d = ready(8, 1, 1); + d.compute_pipeline = false; + expect("graphics pipeline bound", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.compute_root = false; + expect("no compute root", d, no_state ? D::forward : D::no_compute_state); + d = ready(8, 1, 1); + d.compute_root_has_arguments = true; // e.g. a root UAV set through slot 45, which is not forwarded + expect("root with arguments", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d.x = 0; + expect("root with arguments, zero groups", d, no_root_args ? D::forward : D::unforwarded_root_arguments); + d = ready(8, 1, 1); + d.root_matches_pipeline = false; // pipeline built against a different root signature + expect("root and pipeline differ", d, no_pairing ? D::forward : D::root_pipeline_mismatch); + d = ready(8, 1, 1); + d.root_arguments_bound = false; // a root SRV was never set, or a replacement was rejected + expect("unbound root SRV", d, no_bound ? D::forward : D::unbound_root_argument); + d.x = 0; + expect("unbound root SRV, zero groups", d, no_bound ? D::forward : D::unbound_root_argument); + d = ready(8, 1, 1); + d.root_matches_pipeline = d.root_arguments_bound = true; + expect("paired root with every SRV bound", d, D::forward); + d = ready(8, 1, 1); + d.list_open = false; + expect("closed list", d, D::list_closed); + d = ready(8, 1, 1); + d.type = D3D12_COMMAND_LIST_TYPE_COPY; + expect("copy list", d, D::wrong_list_type); + d.type = D3D12_COMMAND_LIST_TYPE_COMPUTE; + expect("compute list", d, D::forward); + if (failures) { + std::printf("%d of %d cases failed\n", failures, cases); + return 1; + } + std::printf("%d cases passed\n", cases); + return 0; +} diff --git a/tests/startup_list_dispatch_native.cpp b/tests/startup_list_dispatch_native.cpp new file mode 100644 index 0000000000..25586fde22 --- /dev/null +++ b/tests/startup_list_dispatch_native.cpp @@ -0,0 +1,440 @@ +// Command-list slot 14 (Dispatch) driven through the d3d12_xs stand-in on a desktop device. Slots 86 (compute +// pipeline stream), 25 (pipeline), 33 (compute root), 43 (compute root SRV in the recording's upload pages), 148 +// (upload allocation), 9 (Close) and 139 (Reset) set up each case. A refused call must log exactly one +// "x2w-render Dispatch(x, y, z) refused: <reason>" line to %X2W_TRAP_LOG% and record nothing. A forwarded call must +// log no line, and the desktop Dispatch is observed through a pipeline-statistics query that the fixture wraps +// around the slot 14 call on the underlying desktop list: CSInvocations is groups * 4 for a forwarded call and 0 +// for a refused one. The root SRV roots carry no UAV, so the shader writes nothing; the invocation count is the +// result. The recordings are executed to a fence, and the debug layer, when present, must report no error. +// +// `skip-srv` is the negative control: the first forwarded case omits slot 43, so the fixture must fail on it. +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <stdexcept> +#include <string> +#include <vector> + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Microsoft::WRL::ComPtr; + +void check(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) { + std::fprintf(stderr, "%s failed (HRESULT 0x%08lx)\n", stage, static_cast<unsigned long>(hr)); + throw std::runtime_error(stage); + } +} + +template <typename Method> +Method slot(IUnknown* object, unsigned index) +{ + return reinterpret_cast<Method>((*reinterpret_cast<void***>(object))[index]); +} + +using Bind = void(WINAPI*)(IUnknown*, IUnknown*); +using Address = void(WINAPI*)(IUnknown*, UINT, UINT64); +using Dispatch = void(WINAPI*)(IUnknown*, UINT, UINT, UINT); +using Upload = void*(WINAPI*)(IUnknown*, UINT64, UINT64); +using Reset = HRESULT(WINAPI*)(IUnknown*, IUnknown*, void*, void*); +using Close = HRESULT(WINAPI*)(IUnknown*); + +constexpr UINT threads_per_group = 4; +constexpr char shader[] = R"( +ByteAddressBuffer input : register(t0); +[numthreads(4, 1, 1)] +void main() {} +)"; + +template <typename T> +ComPtr<T> native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +{ + // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. + constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; + check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); + ComPtr<IUnknown> stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); + check(read, "retrieve underlying object"); + ComPtr<T> result; + check(stored.As(&result), "query underlying object"); + return result; +} + +ComPtr<ID3D12RootSignature> guest_root(ID3D12Device* guest, const D3D12_ROOT_SIGNATURE_DESC& desc, const char* name) +{ + ComPtr<ID3DBlob> serialized, errors; + check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, &errors), name); + ComPtr<ID3D12RootSignature> result; + check(guest->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), IID_PPV_ARGS(&result)), + name); + return result; +} + +// A compute pipeline created through device slot 86 (pipeline state stream) against a guest root. +ComPtr<IUnknown> guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, ID3DBlob* code) +{ + struct { + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE root_type; + ID3D12RootSignature* root; + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE cs_type; + D3D12_SHADER_BYTECODE code; + } stream{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, {code->GetBufferPointer(), code->GetBufferSize()}}; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + using Create = HRESULT(WINAPI*)(IUnknown*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + ComPtr<IUnknown> result; + check(slot<Create>(guest, 86)(guest, &desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(result.GetAddressOf())), + "create guest compute pipeline"); + return result; +} + +std::wstring log_path; +std::size_t lines_seen = 0; + +// The Dispatch lines logged since the previous call. +std::vector<std::string> new_dispatch_lines() +{ + std::vector<std::string> all; + std::ifstream file(log_path, std::ios::binary); + std::string line; + while (std::getline(file, line)) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back(); + if (line.rfind("x2w-render Dispatch(", 0) == 0) all.push_back(line); + } + std::vector<std::string> fresh; + if (all.size() > lines_seen) fresh.assign(all.begin() + static_cast<std::ptrdiff_t>(lines_seen), all.end()); + lines_seen = all.size(); + return fresh; +} + +struct Case { + const char* label; + UINT x, y, z; + const char* reason; // null: the call is forwarded + int query; // pipeline-statistics query index, or -1 on a closed list +}; + +class Fixture { +public: + Fixture(ID3D12Device* device, ID3D12Device* guest, bool skip_srv) : device_(device), guest_(guest), skip_srv_(skip_srv) + { + ComPtr<ID3DBlob> errors; + const HRESULT hr = D3DCompile(shader, sizeof(shader) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code_, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast<const char*>(errors->GetBufferPointer())); + check(hr, "compile compute shader"); + + // root_a: one root SRV (t0). root_b: two root SRVs (t0, t1), so its serialized form and desktop object differ + // from root_a's. root_table: one descriptor table. root_sampler: no parameters, one static sampler. + D3D12_ROOT_PARAMETER srvs[2]{}; + for (UINT i = 0; i < 2; ++i) { + srvs[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + srvs[i].Descriptor = {i, 0}; + srvs[i].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + } + root_a_ = guest_root(guest, {1, srvs, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}, "create root with one root SRV"); + root_b_ = guest_root(guest, {2, srvs, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}, "create root with two root SRVs"); + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER table{}; + table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + table.DescriptorTable = {1, &range}; + table.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + root_table_ = guest_root(guest, {1, &table, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}, "create root with a table"); + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + root_sampler_ = guest_root(guest, {0, nullptr, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}, + "create root with a static sampler"); + pso_a_ = guest_pipeline(guest, root_a_.Get(), code_.Get()); + pso_b_ = guest_pipeline(guest, root_b_.Get(), code_.Get()); + pso_table_ = guest_pipeline(guest, root_table_.Get(), code_.Get()); + pso_sampler_ = guest_pipeline(guest, root_sampler_.Get(), code_.Get()); + + const D3D12_QUERY_HEAP_DESC heap_desc{D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, max_queries, 0}; + check(device->CreateQueryHeap(&heap_desc, IID_PPV_ARGS(&queries_)), "create pipeline-statistics query heap"); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = max_queries * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS); + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + check(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback_)), "create query readback buffer"); + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue_)), "create desktop queue"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_)), "create completion fence"); + + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_)), "create guest allocator"); + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + check(slot<CreateList>(guest, 73)(guest, list_desc, allocator_.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast<void**>(list_.GetAddressOf())), "create guest command list"); + native_ = native_object<ID3D12GraphicsCommandList>(device, guest, list_.Get()); + } + + bool run() + { + // Recording 1: the fully bound call alone, executed and counted before any refused case runs. + reset(); + bool ok = expect({"bound", 2, 3, 1, nullptr, 0}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + if (!skip_srv_) srv(upload_); + }); + if (!ok) return false; + resolve(1); + check(slot<Close>(list_.Get(), 9)(list_.Get()), "close first recording"); + if (!execute(0, 1)) return false; + + // Recording 2: each refusal after a fresh Close, so no binding is left over from recording 1. + reset(); + ok = expect({"root SRV never set", 3, 1, 1, "a compute root SRV is not bound", 0}, + [&] { bind(pso_a_.Get(), root_a_.Get()); }); + ok = ok && expect({"rejected replacement after a valid root SRV", 4, 1, 1, "a compute root SRV is not bound", 1}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + srv(reinterpret_cast<UINT64>(&foreign_)); // not in this recording's upload pages + }); + ok = ok && expect({"misaligned replacement after a valid root SRV", 5, 1, 1, "a compute root SRV is not bound", 2}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + srv(upload_ + 2); // in the upload pages, not 4-byte aligned + }); + ok = ok && expect({"root changed and changed back", 6, 1, 1, "a compute root SRV is not bound", 3}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + root(root_b_.Get()); + root(root_a_.Get()); + }); + ok = ok && expect({"pipeline built against another root", 7, 1, 1, + "compute pipeline was built against another root signature", 4}, [&] { + bind(pso_b_.Get(), root_a_.Get()); + srv(upload_); + }); + ok = ok && expect({"root with a descriptor table", 8, 1, 1, "compute root arguments are not forwarded", 5}, + [&] { bind(pso_table_.Get(), root_table_.Get()); }); + ok = ok && expect({"root with a static sampler", 9, 1, 1, "compute root arguments are not forwarded", 6}, + [&] { bind(pso_sampler_.Get(), root_sampler_.Get()); }); + ok = ok && expect({"root SRV never set, zero groups", 0, 10, 1, "a compute root SRV is not bound", 7}, + [&] { bind(pso_a_.Get(), root_a_.Get()); }); + ok = ok && expect({"bound, X over the limit", 65536, 1, 1, "group count is over 65535", 8}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + }); + ok = ok && expect({"bound, zero groups", 0, 1, 1, nullptr, 9}, [] {}); + ok = ok && expect({"valid root SRV after a rejected one", 1, 2, 1, nullptr, 10}, [&] { + srv(reinterpret_cast<UINT64>(&foreign_)); + srv(upload_); + }); + if (!ok) return false; + resolve(11); + check(slot<Close>(list_.Get(), 9)(list_.Get()), "close second recording"); + // Close drops the recording's bindings; a Dispatch on the closed list is refused before any of them. + if (!expect({"closed list", 11, 1, 1, "list is closed", -1}, [] {})) return false; + if (!execute(0, 11)) return false; + + // Recording 3: Reset without rebinding, then rebound. + reset(); + ok = expect({"after Reset without rebinding", 12, 1, 1, "requires a desktop compute pipeline and root", 0}, [] {}); + ok = ok && expect({"rebound after Reset", 2, 2, 1, nullptr, 1}, [&] { + bind(pso_a_.Get(), root_a_.Get()); + srv(upload_); + }); + if (!ok) return false; + resolve(2); + check(slot<Close>(list_.Get(), 9)(list_.Get()), "close third recording"); + return execute(0, 2); + } + +private: + static constexpr UINT max_queries = 16; + + void reset() + { + check(slot<Reset>(list_.Get(), 139)(list_.Get(), allocator_.Get(), nullptr, nullptr), "reset guest command list"); + upload_ = reinterpret_cast<UINT64>(slot<Upload>(list_.Get(), 148)(list_.Get(), 256, 256)); + if (!upload_) throw std::runtime_error("allocate upload pages through slot 148"); + expected_.clear(); + } + void bind(IUnknown* pipeline, IUnknown* root_signature) + { + slot<Bind>(list_.Get(), 25)(list_.Get(), pipeline); + root(root_signature); + } + void root(IUnknown* root_signature) { slot<Bind>(list_.Get(), 33)(list_.Get(), root_signature); } + void srv(UINT64 address) { slot<Address>(list_.Get(), 43)(list_.Get(), 0, address); } + + template <typename Setup> + bool expect(const Case& c, Setup setup) + { + setup(); + if (c.query >= 0) native_->BeginQuery(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, c.query); + slot<Dispatch>(list_.Get(), 14)(list_.Get(), c.x, c.y, c.z); + if (c.query >= 0) native_->EndQuery(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, c.query); + char wanted[256] = ""; + if (c.reason) std::snprintf(wanted, sizeof(wanted), "x2w-render Dispatch(%u, %u, %u) refused: %s", c.x, c.y, c.z, c.reason); + const auto lines = new_dispatch_lines(); + const bool matched = c.reason ? lines.size() == 1 && lines[0] == wanted : lines.empty(); + if (!matched) { + std::fprintf(stderr, "%s: expected %s%s, got %zu Dispatch line(s)\n", c.label, c.reason ? "exactly " : "no Dispatch line", + wanted, lines.size()); + for (const auto& line : lines) std::fprintf(stderr, " %s\n", line.c_str()); + return false; + } + std::printf("%s: Dispatch(%u, %u, %u) %s%s\n", c.label, c.x, c.y, c.z, c.reason ? "refused: " : "forwarded", + c.reason ? c.reason : ""); + if (c.query >= 0) + expected_.push_back({c.label, c.reason ? 0 : UINT64{c.x} * c.y * c.z * threads_per_group}); + return true; + } + + void resolve(UINT count) + { + native_->ResolveQueryData(queries_.Get(), D3D12_QUERY_TYPE_PIPELINE_STATISTICS, 0, count, readback_.Get(), 0); + } + + bool execute(UINT first, UINT count) + { + ID3D12CommandList* lists[]{native_.Get()}; + queue_->ExecuteCommandLists(1, lists); + check(queue_->Signal(fence_.Get(), ++fence_value_), "signal completion fence"); + check(fence_->SetEventOnCompletion(fence_value_, nullptr), "wait for completion"); + check(device_->GetDeviceRemovedReason(), "GPU completion"); + void* mapped = nullptr; + const D3D12_RANGE read{0, count * sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS)}; + check(readback_->Map(0, &read, &mapped), "map query readback"); + std::vector<D3D12_QUERY_DATA_PIPELINE_STATISTICS> stats(count); + std::memcpy(stats.data(), mapped, read.End); + const D3D12_RANGE untouched{0, 0}; + readback_->Unmap(0, &untouched); + if (expected_.size() != count) { + std::fprintf(stderr, "internal: %zu queries recorded, %u resolved\n", expected_.size(), count); + return false; + } + bool ok = true; + for (UINT i = first; i < count; ++i) { + const UINT64 got = stats[i].CSInvocations; + std::printf(" query %u (%s): CSInvocations %llu (expected %llu)\n", i, expected_[i].label, + static_cast<unsigned long long>(got), static_cast<unsigned long long>(expected_[i].invocations)); + if (got != expected_[i].invocations) { + std::fprintf(stderr, "%s: CSInvocations %llu, expected %llu\n", expected_[i].label, + static_cast<unsigned long long>(got), static_cast<unsigned long long>(expected_[i].invocations)); + ok = false; + } + } + return ok; + } + + struct Expected { + const char* label; + UINT64 invocations; + }; + ID3D12Device* device_; + ID3D12Device* guest_; + bool skip_srv_; + ComPtr<ID3DBlob> code_; + ComPtr<ID3D12RootSignature> root_a_, root_b_, root_table_, root_sampler_; + ComPtr<IUnknown> pso_a_, pso_b_, pso_table_, pso_sampler_; + ComPtr<ID3D12QueryHeap> queries_; + ComPtr<ID3D12Resource> readback_; + ComPtr<ID3D12CommandQueue> queue_; + ComPtr<ID3D12Fence> fence_; + UINT64 fence_value_ = 0; + ComPtr<ID3D12CommandAllocator> allocator_; + ComPtr<IUnknown> list_; + ComPtr<ID3D12GraphicsCommandList> native_; + UINT64 upload_ = 0; + std::uint32_t foreign_ = 0; + std::vector<Expected> expected_; +}; +} // namespace + +int main(int argc, char** argv) try +{ + const bool warp = argc >= 2 && std::strcmp(argv[1], "warp") == 0; + if (!warp && (argc < 2 || std::strcmp(argv[1], "hardware") != 0)) return 2; + const bool skip_srv = argc == 3 && std::strcmp(argv[2], "skip-srv") == 0; + if (argc > 3 || (argc == 3 && !skip_srv)) return 2; + ComPtr<ID3D12Debug> debug; + const HRESULT debug_hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug)); + if (debug_hr != DXGI_ERROR_SDK_COMPONENT_MISSING) check(debug_hr, "get debug layer"); + if (debug) debug->EnableDebugLayer(); + ComPtr<IDXGIFactory6> factory; + check(CreateDXGIFactory1(IID_PPV_ARGS(&factory)), "create DXGI factory"); + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + check(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)), "find WARP"); + } else { + bool found = false; + for (UINT index = 0; factory->EnumAdapters1(index, adapter.ReleaseAndGetAddressOf()) == S_OK; ++index) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + found = true; + break; + } + } + if (!found) return 77; + } + wchar_t directory[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, directory)) return 4; + log_path = std::wstring(directory) + L"x2w_list_dispatch_" + std::to_wstring(GetCurrentProcessId()) + L".log"; + DeleteFileW(log_path.c_str()); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + SetEnvironmentVariableA("X2W_D3D12_DEBUG", "0"); // keep the debug messages for the check below + ComPtr<ID3D12Device> device; + check(D3D12XboxCreateDevice(adapter.Get(), nullptr, IID_PPV_ARGS(&device)), "create desktop device through d3d12_xs"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + const std::array<unsigned char, 64> parameters{}; + ComPtr<ID3D12Device> guest; + check(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), IID_PPV_ARGS(&guest)), "create guest device"); + DXGI_ADAPTER_DESC1 adapter_desc{}; + check(adapter->GetDesc1(&adapter_desc), "get adapter description"); + std::printf("adapter: %ls, debug layer %s\n", adapter_desc.Description, debug ? "enabled" : "unavailable"); + LARGE_INTEGER driver{}; + if (SUCCEEDED(adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver))) + std::printf("driver: %u.%u.%u.%u\n", HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), + LOWORD(driver.LowPart)); + ComPtr<ID3D12InfoQueue> info; + if (debug) check(device.As(&info), "get debug message queue"); + + bool ok = false; + { + Fixture fixture(device.Get(), guest.Get(), skip_srv); + ok = fixture.run(); + } + if (info) { + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + check(info->GetMessage(i, nullptr, &bytes), "get debug message size"); + std::vector<char> storage(bytes); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + check(info->GetMessage(i, message, &bytes), "get debug message"); + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + std::fprintf(stderr, "D3D12 debug message %u: %s\n", static_cast<unsigned>(message->ID), message->pDescription); + ok = false; + } + } + } + DeleteFileW(log_path.c_str()); + if (ok) std::printf("all slot 14 cases matched\n"); + return ok ? 0 : 1; +} +catch (const std::exception&) { + return 3; +} diff --git a/tests/startup_list_resubmit.cpp b/tests/startup_list_resubmit.cpp index 431694f6b3..174a9f5091 100644 --- a/tests/startup_list_resubmit.cpp +++ b/tests/startup_list_resubmit.cpp @@ -41,6 +41,8 @@ using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) unsigned x2w_d3d12_allocator_pool_size(void* allocator); +extern "C" __declspec(dllimport) UINT x2w_d3d12_allocator_sampler_snapshots(void* allocator); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_record_sampler_snapshot(void* list); namespace { using Word = std::uint64_t; @@ -145,6 +147,48 @@ struct Probe { } }; +bool sampler_retirement(void* device, Probe& first, bool untracked) +{ + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + Probe second; + second.fence = make_fence(device); + void* gate = make_fence(device); + void* allocator = nullptr; + void* list = nullptr; + if (!second.fence || !gate || + !ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&second.queue))) || + !ok(invoke(device, 9, list_desc[0], arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list))) || + !ok(invoke(list, 139, arg(allocator))) || + !x2w_d3d12_record_sampler_snapshot(list) || + x2w_d3d12_allocator_sampler_snapshots(allocator) != 1 || + !ok(invoke(list, 9)) || !first.submit(list)) + return false; + + struct ReleaseGate { + void* fence; + ~ReleaseGate() { invoke(fence, 10, 1); } + } release_gate{gate}; + if (!ok(invoke(second.queue, 17, arg(gate), 1)) || !second.submit(list, false) || + invoke(list, 2) != 0 || !ok(invoke(allocator, 8)) || + invoke(second.fence, 8) != 0 || x2w_d3d12_allocator_sampler_snapshots(allocator) != 1) + return false; + + if (!ok(invoke(gate, 10, 1)) || !second.reached()) return false; + void* spare_list = nullptr; + if (!ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, + arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&spare_list))) || + !ok(invoke(spare_list, 139, arg(allocator))) || !ok(invoke(spare_list, 9)) || + !ok(invoke(allocator, 8))) + return false; + + const UINT held = x2w_d3d12_allocator_sampler_snapshots(allocator); + const UINT expected = untracked ? 1 : 0; + std::printf("sampler snapshots after both queues completed: %u (expected %u)\n", held, expected); + return held == expected; +} + bool expect(Probe& probe, const char* step, std::uint32_t wanted) { const std::uint32_t got = probe.texel(); @@ -273,6 +317,7 @@ int main(int argc, char** argv) probe.record(list_a, a, blue); if (!probe.submit(list_a)) return 64; if (!expect(probe, "6 A after the Reset, clear blue", blue_bits)) return 65; + if (!sampler_retirement(device, probe, untracked)) return 66; const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); const UINT64 errors = probe.debug_errors(); diff --git a/tests/startup_live_telemetry_check.py b/tests/startup_live_telemetry_check.py index 7f42258525..2dda4843c0 100644 --- a/tests/startup_live_telemetry_check.py +++ b/tests/startup_live_telemetry_check.py @@ -54,6 +54,24 @@ def test_storage_and_render_totals_are_preserved(self): self.assertIn(render, output) self.assertIn("7 chunks decompressed", output) + def test_status_lines_old_and_new_format(self): + # #2816: the counters of the status lines are raw= (uncompressed copies) and completed= (raw + inflated + + # bcpack-blank); "inflated=N failed=N" is unchanged. An old line (done=) still parses, and a run with only + # compressed requests reads as progressing in both. + new = ("x2w-dstorage Queue::EnqueueStatus array=0x1 index=3 (requests raw=0 inflated=5 failed=1 " + "bcpack-blank=2 completed=7)") + old = "x2w-dstorage Queue::EnqueueStatus array=0x1 index=3 (requests done=0 inflated=5 failed=1)" + beat = ("x2w-dstorage heartbeat 10 s: requests raw=0 inflated=5 failed=1 bcpack-blank=2 completed=7; " + "page tokens 0 at enqueue=0, still 0 at run=0; commit unknown, live physical-page sections=unknown") + old_beat = ("x2w-dstorage heartbeat 10 s: requests done=0 inflated=5 failed=1 bcpack-blank=2; " + "page tokens 0 at enqueue=0, still 0 at run=0; commit unknown, live physical-page sections=unknown") + for line, completed in ((new, 7), (old, 5), (beat, 7), (old_beat, 7)): + output = self.view_log(line + "\n") + self.assertIn("5 chunks decompressed", output, line) + self.assertIn(f"{completed} storage requests completed", output, line) + self.assertIn("7 requests completed so far, 5 compressed chunks decompressed, 1 failed", self.view_log(new + "\n")) + self.assertIn("5 requests completed so far, 5 compressed chunks decompressed, 1 failed", self.view_log(old + "\n")) + def test_unknown_and_split_heartbeat(self): first = "x2w-dstorage heartbeat 20 s: requests done=0 inflated=0 failed=0 bcpack-blank=0; " second = "page tokens 0 at enqueue=0, still 0 at run=0; commit unknown, live physical-page sections=unknown\n" diff --git a/tests/startup_live_view_cli_check.py b/tests/startup_live_view_cli_check.py index bf08404720..21249854d7 100644 --- a/tests/startup_live_view_cli_check.py +++ b/tests/startup_live_view_cli_check.py @@ -4,6 +4,7 @@ from contextlib import redirect_stderr, redirect_stdout import importlib import io +import os from pathlib import Path import runpy import subprocess @@ -38,6 +39,16 @@ def _run_subprocess(*args: str | Path) -> subprocess.CompletedProcess[str]: ) +def _short_path(path: Path) -> str | None: + if os.name != "nt": + return None + import ctypes + + buffer = ctypes.create_unicode_buffer(32768) + length = ctypes.windll.kernel32.GetShortPathNameW(str(path), buffer, len(buffer)) + return buffer.value if length else None + + class _ReconfigurableStringIO(io.StringIO): def __init__(self): super().__init__() @@ -160,6 +171,25 @@ def test_main_and_subprocess_preserve_output_reconfigure_and_split_utf8(self) -> ["events.txt", "files.txt", "finished.txt", "trap.log"], ) + def test_short_path_alias_matches_resolved_package_file(self) -> None: + import live_view + + with TemporaryDirectory() as tmp: + package = Path(tmp) / "pkg" + package.mkdir() + short = _short_path(package) + if not short or os.path.normcase(short) == os.path.normcase(os.path.abspath(package)): + self.skipTest("the temp volume has no distinct 8.3 alias") + viewer = live_view._LogViewer(short) + out = io.StringIO() + with redirect_stdout(out): + viewer.on_file( + "1.0 NtOpenFile " + + str(package.resolve()) + + "\\data.bin from 0x1000 -> 0xc0000034" + ) + self.assertIn("data.bin (failed 0xc0000034)", out.getvalue()) + class LiveViewCliNegativeAndMutationTests(unittest.TestCase): def test_rundir_and_package_path_guards_exit_2_without_looping(self) -> None: diff --git a/tests/startup_local_log_check.cpp b/tests/startup_local_log_check.cpp index daff26103b..f2f5ec2a0e 100644 --- a/tests/startup_local_log_check.cpp +++ b/tests/startup_local_log_check.cpp @@ -3,9 +3,12 @@ // logf formatting/truncation/X2W_TRAP_LOG append, // one X2W_TRAP_LOG open per module under 8 concurrent writers (in a child process), recovery // after a first open into a missing directory or of a locked file fails (in child processes), -// probe_readable page truncation and PAGE_GUARD re-arming, and readable/writable boundary checks. +// probe_readable page truncation and PAGE_GUARD re-arming, readable/writable boundary checks, and that an +// unmapped range is refused by the probe and the guarded copies with zero first-chance exceptions. #include "startup_stubs/local_log.h" +#include <intrin.h> + #include <atomic> #include <cstdint> #include <cstdio> @@ -585,12 +588,188 @@ void test_probe_and_access(bool guard_drop_mutate) } } +// Exceptions seen by a vectored handler, for the thread that runs the check only: a debugger stops on every +// first-chance fault, and faults of other threads in the process do not belong to it. +volatile LONG first_chance_faults = 0; +volatile LONG counted_thread = 0; +LONG CALLBACK count_first_chance(PEXCEPTION_POINTERS info) +{ + const DWORD code = info->ExceptionRecord->ExceptionCode; + if (GetCurrentThreadId() == static_cast<DWORD>(counted_thread) && + (code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR || code == 0x80000001u)) + InterlockedIncrement(&first_chance_faults); + return EXCEPTION_CONTINUE_SEARCH; +} + +bool range_is_free(std::uintptr_t base, std::size_t bytes) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(reinterpret_cast<const void*>(base), &info, sizeof(info)) && info.State == MEM_FREE && + info.RegionSize >= bytes; +} + +// Free address space is refused with zero first-chance exceptions by the probe, readable() and both copy flavours, +// each counted in faults_avoided; a mapped source still copies and counts nothing. +// +// The range is one this check released itself. Nothing else can be trusted to leave it free (another thread, or +// this thread's own heap, may reuse it the moment it is released), so each round is only judged when the range is +// verified MEM_FREE right before and right after the calls, the handler is installed beforehand and the calls +// in between allocate nothing. A round that lost its range is dropped, not counted; the check needs enough stable +// rounds and holds every stable one to zero faults. +void test_unmapped_no_faults() +{ + constexpr std::size_t kPage = 0x1000; + constexpr int rounds = 40, needed = 10; + char copy[64] = {}; + { + void* const mapped = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + check(mapped != nullptr, "VirtualAlloc a page for the mapped-source check"); + if (!mapped) return; + std::memset(mapped, 0x5A, kPage); + x2w_local::forget_mapped_spans(); + const LONG before = x2w_local::faults_avoided; + const bool copied = x2w_local::guarded_memcpy(copy, mapped, sizeof(copy), false); + check(copied && copy[0] == 0x5A, "a mapped source is copied"); + check(x2w_local::faults_avoided == before, "a mapped source avoids no fault"); + VirtualFree(mapped, 0, MEM_RELEASE); + } + counted_thread = static_cast<LONG>(GetCurrentThreadId()); + void* const handler = AddVectoredExceptionHandler(1, count_first_chance); + check(handler != nullptr, "vectored handler installed"); + int stable = 0, wrong_results = 0, faulted = 0, miscounted = 0, control_faults = 0, controls = 0; + for (int round = 0; round < rounds && stable < needed; ++round) { + void* const block = VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!block) continue; + const auto base = reinterpret_cast<std::uintptr_t>(block); + VirtualFree(block, 0, MEM_RELEASE); + x2w_local::forget_mapped_spans(); + if (!range_is_free(base, 2 * kPage)) continue; + InterlockedExchange(&first_chance_faults, 0); + const LONG before = x2w_local::faults_avoided; + const bool probe_zero = x2w_local::probe_readable(base, 16) == 0; + const bool not_readable = !x2w_local::readable(reinterpret_cast<const void*>(base), 16); + const bool refused_av = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), false); + const bool refused_any = !x2w_local::guarded_memcpy(copy, reinterpret_cast<const void*>(base), sizeof(copy), true); + const LONG faults = first_chance_faults; + const LONG counted = x2w_local::faults_avoided - before; + if (!range_is_free(base, 2 * kPage)) continue; // the range was taken meanwhile: this round proves nothing + ++stable; + if (!(probe_zero && not_readable && refused_av && refused_any)) ++wrong_results; + if (faults != 0) ++faulted; + if (counted != 4) ++miscounted; + if (controls == 0) { // retried until one control round survived the address-space churn + // Control: the handler does see a real fault, so the zero above means something. Touch a freshly + // released range directly, again only when it is verified free around the touch. + void* const second = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (second) { + const auto at = reinterpret_cast<std::uintptr_t>(second); + VirtualFree(second, 0, MEM_RELEASE); + if (range_is_free(at, kPage)) { + InterlockedExchange(&first_chance_faults, 0); + __try { + volatile unsigned char sink = *reinterpret_cast<const volatile unsigned char*>(at); + (void)sink; + } __except (EXCEPTION_EXECUTE_HANDLER) { + } + const LONG seen = first_chance_faults; + if (range_is_free(at, kPage)) { + ++controls; + control_faults = seen; + } + } + } + } + } + RemoveVectoredExceptionHandler(handler); + check(stable >= needed, "enough rounds kept their released range free to be judged"); + check(wrong_results == 0, "free address space: probe_readable 0, readable false, both copies refuse"); + check(faulted == 0, "free address space: zero first-chance exceptions in every judged round"); + check(miscounted == 0, "free address space: the four refusals of every judged round are counted"); + check(controls == 1 && control_faults == 1, "control: touching a verified-free range directly is one first-chance fault"); +} + +// A protected page before a free tail still faults in the touch loop, so the free tail is not an avoided fault. +void test_protected_prefix_not_counted() +{ + constexpr std::size_t kPage = 0x1000; + bool judged = false; + for (int round = 0; round < 20 && !judged; ++round) { + void* const block = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); + if (!block) continue; + const auto base = reinterpret_cast<std::uintptr_t>(block); + x2w_local::forget_mapped_spans(); + if (!range_is_free(base + kPage, kPage)) { + VirtualFree(block, 0, MEM_RELEASE); + continue; + } + const LONG before = x2w_local::faults_avoided; + const std::size_t got = x2w_local::probe_readable(base, 2 * kPage); + const LONG counted = x2w_local::faults_avoided - before; + const bool still_free = range_is_free(base + kPage, kPage); + VirtualFree(block, 0, MEM_RELEASE); + if (!still_free) continue; + judged = true; + check(got == 0, "a protected page before a free tail is not readable"); + check(counted == 0, "a free tail behind a protected page is not counted as an avoided fault"); + } + check(judged, "one round kept the free tail free to be judged"); +} + +// With X2W_PROBE_PRECHECK=0 the pre-check is off: a free range is still refused, but by the touch / __try path +// (nothing counted in faults_avoided) and the touch is a real first-chance fault. simulate_debugger sets the PEB's +// BeingDebugged byte first, which is what IsDebuggerPresent reads, so the explicit 0 must win over an attached +// debugger (title runs always start under debug_launch.py); no real debugger is attached, so faults still reach +// the vectored handler. +int precheck_off_child(bool simulate_debugger) +{ + auto* const being_debugged = reinterpret_cast<volatile unsigned char*>(__readgsqword(0x60) + 2); + const unsigned char was = *being_debugged; + if (simulate_debugger) { + *being_debugged = 1; + check(IsDebuggerPresent() != FALSE, "precheck off: the simulated debugger is visible to IsDebuggerPresent"); + } else if (IsDebuggerPresent()) { + return 0; // unset-style run under a real debugger: nothing to judge here + } + constexpr std::size_t kPage = 0x1000; + counted_thread = static_cast<LONG>(GetCurrentThreadId()); + void* const handler = AddVectoredExceptionHandler(1, count_first_chance); + int judged = 0, refused = 0, counted_rounds = 0, faulted = 0; + for (int round = 0; round < 40 && judged < 5; ++round) { + void* const block = VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!block) continue; + const auto base = reinterpret_cast<std::uintptr_t>(block); + VirtualFree(block, 0, MEM_RELEASE); + if (!range_is_free(base, kPage)) continue; + InterlockedExchange(&first_chance_faults, 0); + const LONG before = x2w_local::faults_avoided; + const bool zero = x2w_local::probe_readable(base, 16) == 0; + const LONG faults = first_chance_faults; + const LONG counted = x2w_local::faults_avoided - before; + if (!range_is_free(base, kPage)) continue; + ++judged; + if (zero) ++refused; + if (counted != 0) ++counted_rounds; + if (faults != 0) ++faulted; + } + RemoveVectoredExceptionHandler(handler); + *being_debugged = was; + check(judged >= 5, "precheck off: enough rounds judged"); + check(refused == judged, "precheck off: a free range is still not readable"); + check(counted_rounds == 0, "precheck off: no refusal is counted as an avoided fault"); + check(faulted == judged, "precheck off: the free range is found by the touch, one first-chance fault each"); + std::printf("startup_local_log precheck off%s: %d of %d FAILED\n", simulate_debugger ? " (debugger)" : "", + failures, cases); + return failures ? 1 : 0; +} + } // namespace int main(int argc, char** argv) { const bool two_args = argc == 3; if (two_args && std::strcmp(argv[1], "--phase") == 0) { + if (std::strcmp(argv[2], "precheck-off") == 0) return precheck_off_child(false); + if (std::strcmp(argv[2], "precheck-off-debugger") == 0) return precheck_off_child(true); if (std::strcmp(argv[2], "concurrency") == 0) return concurrency_child(false); if (std::strcmp(argv[2], "concurrency-reopen") == 0) return concurrency_child(true); if (std::strcmp(argv[2], "recovery-missing") == 0) return recovery_child(Recovery::missing); @@ -629,6 +808,7 @@ int main(int argc, char** argv) std::printf("startup_local_log: wrap control %d of %d FAILED\n", failures, cases); return failures ? 1 : 0; } + SetEnvironmentVariableA("X2W_PROBE_PRECHECK", "1"); // the pre-check cases below need it on (read once) test_env_on(); test_first_calls(); test_first_calls_wrap(false); @@ -644,6 +824,8 @@ int main(int argc, char** argv) static_cast<unsigned long>(locked)); test_logf(); test_probe_and_access(guard_drop_mutate); + test_unmapped_no_faults(); + test_protected_prefix_not_counted(); if (cache_failure_mutate) { std::printf("startup_local_log cache-failure control: parent failures %d\n", failures); diff --git a/tests/startup_logical_view_check.py b/tests/startup_logical_view_check.py index 1f8a3d9fc3..221fed742c 100644 --- a/tests/startup_logical_view_check.py +++ b/tests/startup_logical_view_check.py @@ -21,7 +21,7 @@ def check(directory, consumer, backend): subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) # Isolate table publication from instruction lowering. Keep the fixture's generated # screen triangle and replace its constant-colour PS with a single bound buffer read. - manifest, = cache.glob("*.txt") + manifest, = (path for path in cache.glob("*.txt") if path.name != "revision.txt") with manifest.open("a", encoding="ascii") as file: file.write("\nsrv 0 buffer table 0 0\n") shader = manifest.with_suffix(".ps.hlsl") diff --git a/tests/startup_manifest_retry_check.cpp b/tests/startup_manifest_retry_check.cpp new file mode 100644 index 0000000000..b3f0acf198 --- /dev/null +++ b/tests/startup_manifest_retry_check.cpp @@ -0,0 +1,75 @@ +// The retry schedule for an absent shader cache manifest (startup_stubs/manifest_retry.h). +// The first look again comes 1 s after the first miss, each further miss doubles the wait, and the wait +// stops growing at 32 s. A found manifest starts the schedule over. +#include "startup_stubs/manifest_retry.h" + +#include <cstdio> + +namespace { + +int failures = 0; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +} // namespace + +int main() +{ + using x2w_startup::ManifestRetry; + using x2w_startup::manifest_retry_delay_ms; + + expect(manifest_retry_delay_ms(0) == 1000, "first miss waits 1 s"); + expect(manifest_retry_delay_ms(1) == 2000, "second miss waits 2 s"); + expect(manifest_retry_delay_ms(4) == 16000, "fifth miss waits 16 s"); + expect(manifest_retry_delay_ms(5) == 32000, "sixth miss waits 32 s"); + expect(manifest_retry_delay_ms(6) == 32000, "the wait stops at 32 s"); + expect(manifest_retry_delay_ms(64) == 32000, "a large miss count does not overflow the shift"); + expect(manifest_retry_delay_ms(~0u) == 32000, "the largest miss count stays at 32 s"); + + ManifestRetry retry; + expect(!retry.pending(), "a fresh schedule has no retry pending"); + expect(!retry.due(0) && !retry.due(~0ull), "a fresh schedule is never due"); + + retry.missed(10000); + expect(retry.pending(), "a miss leaves a retry pending"); + expect(!retry.due(10999), "not due before 1 s"); + expect(retry.due(11000), "due at 1 s"); + + retry.missed(11000); + expect(!retry.due(12999) && retry.due(13000), "second miss: due after 2 s"); + + for (int i = 0; i < 20; ++i) retry.missed(100000); + expect(!retry.due(131999) && retry.due(132000), "many misses: due after 32 s"); + + retry.found(); + expect(!retry.pending() && !retry.due(~0ull), "a found manifest clears the retry"); + retry.missed(200000); + expect(!retry.due(200999) && retry.due(201000), "a later miss starts again at 1 s"); + + // One key that never gets a translation: over ten minutes the old fixed 1 s retry looked it up about 600 times; + // the schedule looks it up 23 times (6 lookups in the first 63 s, then one per 32 s). + { + ManifestRetry key; + unsigned lookups = 0; + unsigned long long now = 0; + key.missed(now); + ++lookups; + for (; now <= 600000; now += 50) + if (key.due(now)) { + key.missed(now); + ++lookups; + } + expect(lookups <= 25, "an absent key is looked up at most 25 times in ten minutes"); + expect(lookups >= 20, "an absent key is still looked up at least 20 times in ten minutes"); + } + + if (failures) return 1; + std::printf("startup_manifest_retry: all checks passed\n"); + return 0; +} diff --git a/tests/startup_map_drive_check.py b/tests/startup_map_drive_check.py new file mode 100644 index 0000000000..b62b00e49f --- /dev/null +++ b/tests/startup_map_drive_check.py @@ -0,0 +1,154 @@ +"""Check the launcher's --map-drive option (#1158). + +usage: startup_map_drive_check.py <consumer.exe> <debug_launch.py> <scratch dir> [overlap] + +A console executable opens its package at a fixed drive letter. The option rewrites an open on a +mapped letter to a real folder, in the caller's own path structure, so the package can live on any +volume. + +1. Mapped letter: the consumer opens a file through a letter that is not a real volume and reads it, + and the trace shows the rewrite. +2. Negative control: without the option the same open fails. +3. Unmapped letter: with the option, an open on a letter that is not mapped is left alone. +4. Reuse: one caller-owned name over 32 serial opens is restored after every return. +5. (overlap argument) Two threads, 32 opens each, with their own caller-owned names in flight at once: + all 64 opens must see the mapped name and succeed, every caller string must be back as built, and + the debugger must report no unprotected step window; three times. The control runs the same case + with --suspend-others 0 (the other thread is not held): it must lose at least one open in 8 runs. +""" +import os +import re +import shutil +import subprocess +import sys + +consumer, launcher, scratch = sys.argv[1:4] +python = sys.executable +# The serial and the overlap check run as two CTests that may run at the same time: each owns its folders. +overlap_mode = len(sys.argv) > 4 and sys.argv[4] == "overlap" +tag = "overlap" if overlap_mode else "serial" +failures = [] + + +def free_letter(): + """A letter that is not a mounted volume, so only the rewrite can make the open succeed.""" + for letter in "ZYXWVUTSRQPONMLKJIHG": + if not os.path.exists(letter + ":\\"): + return letter + return None + + +def run(letter, map_spec, log_name, mode="", extra=()): + log = os.path.join(scratch, f"map_drive_{tag}_{log_name}") + shutil.rmtree(log, ignore_errors=True) + env = dict(os.environ, X2W_PROBE_DRIVE=letter) + if mode: + env["X2W_PROBE_MODE"] = mode + command = [python, "-B", launcher, consumer, scratch, log, "--timeout", "15", "--memory-gib", "2", + "--trace-files", "1", "--continue-asserts", "0"] + command += list(extra) + if map_spec: + command += ["--map-drive", map_spec] + launcher_out = subprocess.run(command, capture_output=True, text=True, env=env, timeout=120).stdout + stdout_path = os.path.join(log, "stdout.txt") + files_path = os.path.join(log, "files.txt") + stdout = open(stdout_path, encoding="utf-8", errors="replace").read() if os.path.exists(stdout_path) else "" + trace = open(files_path, encoding="utf-8", errors="replace").read() if os.path.exists(files_path) else "" + return stdout, trace, launcher_out + + +letter = free_letter() +if not letter: + print("no free drive letter to map; skipping") + sys.exit(77) + +package = os.path.join(scratch, f"map_drive_pkg_{tag}") +shutil.rmtree(package, ignore_errors=True) +os.makedirs(package) +with open(os.path.join(package, "map_drive_probe.txt"), "w", encoding="ascii", newline="") as handle: + handle.write("mapped ok") +if overlap_mode: + # The second thread's file has a longer name; the contents tell the files apart in the trace-free case. + with open(os.path.join(package, "map_drive_probe_second_longer_name.txt"), "w", encoding="ascii", newline="") as handle: + handle.write("second file") + +if not overlap_mode: + # The launcher exits 0 whether or not the child succeeded, so the child's own output is the signal. + stdout, trace, _ = run(letter, f"{letter}={package}", "map_on") + ok = "mapped ok" in stdout and "MAP " in trace and "map_drive_pkg" in trace + print(f"mapped letter {letter}: {'ok' if ok else 'MISMATCH'} ({stdout.strip()!r})") + if not ok: + failures.append(f"mapped letter: stdout {stdout.strip()!r}, trace has MAP: {'MAP ' in trace}") + + stdout, trace, _ = run(letter, "", "map_off") + ok = "open failed" in stdout and "mapped ok" not in stdout + print(f"negative control without the option: {'ok' if ok else 'MISMATCH'} ({stdout.strip()!r})") + if not ok: + failures.append(f"negative control did not fail as expected: stdout {stdout.strip()!r}") + + stdout, trace, _ = run("C", f"{letter}={package}", "map_unmapped") + ok = "MAP " not in trace + print(f"unmapped letter C: {'ok' if ok else 'MISMATCH'}") + if not ok: + failures.append("an open on an unmapped letter was rewritten") + + # One caller-owned UNICODE_STRING through many opens: the borrowed name has to be given back after + # every return, and the backing allocation must be reused rather than grown per open. + stdout, trace, _ = run(letter, f"{letter}={package}", "map_reuse", mode="reuse") + name_buffers = trace.count("NAMEBUF alloc") + ok = "reuse ok" in stdout and name_buffers <= 1 and trace.count("MAP ") >= 32 + print(f"reused caller name over 32 opens: {'ok' if ok else 'MISMATCH'} " + f"(name allocations={name_buffers}, rewrites={trace.count('MAP ')})") + if not ok: + failures.append(f"reuse: stdout {stdout.strip()!r}, name allocations {name_buffers}, " + f"rewrites {trace.count('MAP ')}") + + +OPENS = 64 # two threads, 32 opens each + + +def overlap(label, extra): + """One two-thread run: (every open mapped and succeeded and every caller name restored, text, unprotected).""" + stdout, trace, launcher_out = run(letter, f"{letter}={package}", label, mode="overlap", extra=extra) + def mapped_opens(name): + return sum(1 for line in trace.splitlines() if " NtCreateFile " in line and "(mapped from " in line + and line.rstrip().endswith("-> 0x00000000") and f"\\{name} from " in line) + first, second = mapped_opens("map_drive_probe.txt"), mapped_opens("map_drive_probe_second_longer_name.txt") + mapped_ok = first + second + rewrites = trace.count("MAP ") + summary = re.search(r"hook windows: entries=\d+ windows=\d+ unprotected=(\d+)", launcher_out + trace) + unprotected = int(summary.group(1)) if summary else -1 + good = f"overlap ok: {OPENS} opens across two threads, both caller names intact" in stdout \ + and first == second == OPENS // 2 and rewrites == OPENS + return good, f"{stdout.strip()!r} (mapped opens traced {first} + {second}, rewrites {rewrites})", unprotected + + +if overlap_mode: + # With the other threads held for each step, every one of the 64 opens is rewritten, succeeds and gets + # its own caller-owned name back; the debugger reports no unprotected window. Three times. + for attempt in range(3): + good, text, unprotected = overlap(f"held{attempt}", []) + print(f"two overlapping threads, attempt {attempt}: {'ok' if good else 'MISMATCH'} {text} unprotected={unprotected}") + if not good or unprotected != 0: + failures.append(f"overlap attempt {attempt}: {text}, unprotected={unprotected}") + # Control (the broken copy): the same case without holding the other thread loses opens, and the + # debugger says so. If it never does in 8 runs the overlap was not exercised and the case above proves nothing. + lost = None + for attempt in range(8): + good, text, unprotected = overlap(f"free{attempt}", ["--suspend-others", "0"]) + if not good: + if unprotected <= 0: + failures.append(f"control attempt {attempt} lost opens but reported no unprotected window: {text}") + lost = text + break + print(f"control without holding the other thread: {'lost opens: ' + lost if lost else 'NEVER LOST'}") + if lost is None: + failures.append("the control never lost an open in 8 runs: the overlap was not exercised") + +shutil.rmtree(package, ignore_errors=True) +if failures: + print("FAIL") + for text in failures: + print(" " + text) + sys.exit(1) +print("PASS") diff --git a/tests/startup_map_drive_consumer.cpp b/tests/startup_map_drive_consumer.cpp new file mode 100644 index 0000000000..37c25b9f3d --- /dev/null +++ b/tests/startup_map_drive_consumer.cpp @@ -0,0 +1,229 @@ +// Source-built consumer for the launcher's --map-drive option (#1158). +// +// A console executable opens its package at a fixed drive letter. The letter comes from +// X2W_PROBE_DRIVE (default Z) because the launcher passes no program arguments. +// +// Two modes, chosen with X2W_PROBE_MODE: +// (default) one open of "<letter>:\map_drive_probe.txt" through CreateFileW, printing what it read. +// Under the launcher with --map-drive the open is rewritten and succeeds; without it, it +// fails, which is the negative control. +// reuse a caller-owned UNICODE_STRING is passed to NtCreateFile many times. After every return +// its length, buffer pointer and contents must be the ones the caller built, and every +// open must still succeed: the rewritten name is only borrowed for the duration of each +// call, and one backing buffer is reused rather than one allocation per open. +#include <windows.h> +#include <winternl.h> + +#include <cstdio> +#include <cwchar> + +namespace { +constexpr int reuse_opens = 32; + +// ntdll's declarations in <winternl.h> differ across SDK versions, so resolve the two entry points +// at run time: the fixture only needs to make the call, not to link against a signature. +using NtCreateFileFn = NTSTATUS(NTAPI*)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PIO_STATUS_BLOCK, + PLARGE_INTEGER, ULONG, ULONG, ULONG, ULONG, PVOID, ULONG); +using NtCloseFn = NTSTATUS(NTAPI*)(HANDLE); + +bool resolve(HMODULE ntdll, NtCreateFileFn& create, NtCloseFn& close) +{ + create = reinterpret_cast<NtCreateFileFn>(GetProcAddress(ntdll, "NtCreateFile")); + close = reinterpret_cast<NtCloseFn>(GetProcAddress(ntdll, "NtClose")); + return create && close; +} + +wchar_t probe_letter() +{ + wchar_t letter = L'Z'; + wchar_t from_env[8]{}; + if (GetEnvironmentVariableW(L"X2W_PROBE_DRIVE", from_env, 8) == 1) letter = from_env[0]; + return letter; +} + +// One open through CreateFileW; the mapped letter has no volume of its own. +int single_open() +{ + wchar_t path[64]; + _snwprintf_s(path, 64, _TRUNCATE, L"%c:\\map_drive_probe.txt", probe_letter()); + HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) { + std::printf("open failed: %lu\n", static_cast<unsigned long>(GetLastError())); + return 2; + } + char text[64]{}; + DWORD got = 0; + const BOOL ok = ReadFile(file, text, sizeof(text) - 1, &got, nullptr); + CloseHandle(file); + if (!ok) return 3; + std::printf("read %lu bytes: %s\n", static_cast<unsigned long>(got), text); + return 0; +} + +int reused_string() +{ + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + NtCreateFileFn create = nullptr; + NtCloseFn close = nullptr; + if (!ntdll || !resolve(ntdll, create, close)) { + std::printf("ntdll entry points not resolved\n"); + return 1; + } + wchar_t name[64]; + // NtCreateFile takes the NT form of the name; CreateFileW would add this prefix itself. + _snwprintf_s(name, 64, _TRUNCATE, L"\\??\\%c:\\map_drive_probe.txt", probe_letter()); + wchar_t built[64]; + wcscpy_s(built, name); + + UNICODE_STRING string{}; + string.Buffer = name; + string.Length = static_cast<USHORT>(std::wcslen(name) * sizeof(wchar_t)); + string.MaximumLength = string.Length; // exactly the caller's size, so a longer name must borrow + OBJECT_ATTRIBUTES attributes{}; + InitializeObjectAttributes(&attributes, &string, OBJ_CASE_INSENSITIVE, nullptr, nullptr); + + const USHORT length = string.Length, maximum = string.MaximumLength; + PWSTR buffer = string.Buffer; + for (int index = 0; index < reuse_opens; ++index) { + HANDLE handle = nullptr; + IO_STATUS_BLOCK status{}; + const NTSTATUS result = create(&handle, GENERIC_READ | SYNCHRONIZE, &attributes, &status, nullptr, + FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, + FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, nullptr, 0); + if (result < 0) { + std::printf("reuse open %d failed: 0x%08lx\n", index, static_cast<unsigned long>(result)); + return 1; + } + close(handle); + // The launcher borrows the caller's name for the call only; it must be back exactly as built. + if (string.Length != length || string.MaximumLength != maximum || string.Buffer != buffer || + std::wcscmp(string.Buffer, built) != 0) { + std::printf("caller name changed after open %d: length=%u maximum=%u buffer_moved=%d text=%ls\n", + index, string.Length, string.MaximumLength, string.Buffer != buffer ? 1 : 0, + string.Buffer ? string.Buffer : L"(null)"); + return 1; + } + } + std::printf("reuse ok: %d opens, caller name intact after every return\n", reuse_opens); + return 0; +} +// Two threads open through the mapped letter at the same time with their own caller-owned names. +// Each rewritten name must stay valid for the call that is still in flight, so both threads must see +// their own mapped file and get their own UNICODE_STRING back. +struct Overlap { + HANDLE start; + wchar_t letter; + int opens; + LONG completed; + LONG broken; + LONG wrong_file; // an open that reached a file other than the one its own thread named +}; + +// The two threads name DIFFERENT files of DIFFERENT lengths, so a name buffer shared between the calls in +// flight would hand one thread the other's name (or a cut-off one) instead of its own file. +struct Worker { + Overlap* shared; + int index; +}; +const wchar_t* const overlap_file[2] = {L"map_drive_probe.txt", L"map_drive_probe_second_longer_name.txt"}; + + +DWORD WINAPI overlap_thread(LPVOID parameter) +{ + auto* worker = static_cast<Worker*>(parameter); + Overlap* shared = worker->shared; + const wchar_t* const file_name = overlap_file[worker->index]; + wchar_t name[96]; + _snwprintf_s(name, 96, _TRUNCATE, L"\\??\\%c:\\%ls", shared->letter, file_name); + wchar_t built[96]; + wcscpy_s(built, name); + + UNICODE_STRING string{}; + string.Buffer = name; + string.Length = static_cast<USHORT>(std::wcslen(name) * sizeof(wchar_t)); + string.MaximumLength = string.Length; + OBJECT_ATTRIBUTES attributes{}; + InitializeObjectAttributes(&attributes, &string, OBJ_CASE_INSENSITIVE, nullptr, nullptr); + const USHORT length = string.Length, maximum = string.MaximumLength; + PWSTR buffer = string.Buffer; + + HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); + NtCreateFileFn create = nullptr; + NtCloseFn close = nullptr; + if (!ntdll || !resolve(ntdll, create, close)) return 1; + const size_t file_length = std::wcslen(file_name); + + WaitForSingleObject(shared->start, INFINITE); + for (int index = 0; index < shared->opens; ++index) { + HANDLE handle = nullptr; + IO_STATUS_BLOCK status{}; + const NTSTATUS result = create(&handle, GENERIC_READ | SYNCHRONIZE, &attributes, &status, nullptr, + FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, + FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, nullptr, 0); + if (result < 0) return 1; + // Which file did the call open? It has to be this thread's own, not the other thread's. + wchar_t final_path[MAX_PATH * 2]{}; + const DWORD got = GetFinalPathNameByHandleW(handle, final_path, MAX_PATH * 2, FILE_NAME_NORMALIZED); + const bool own_file = got > file_length && got < MAX_PATH * 2 && + _wcsicmp(final_path + got - file_length, file_name) == 0 && final_path[got - file_length - 1] == L'\\'; + close(handle); + if (!own_file) { + InterlockedIncrement(&shared->wrong_file); + return 1; + } + if (string.Length != length || string.MaximumLength != maximum || string.Buffer != buffer || + std::wcscmp(string.Buffer, built) != 0) { + InterlockedIncrement(&shared->broken); + return 1; + } + InterlockedIncrement(&shared->completed); + SwitchToThread(); // give the other thread a chance to be inside its own call + } + return 0; +} + +int overlapping_names() +{ + Overlap shared{}; + shared.start = CreateEventW(nullptr, TRUE, FALSE, nullptr); + shared.letter = probe_letter(); + shared.opens = 32; + if (!shared.start) return 1; + Worker workers[2] = {{&shared, 0}, {&shared, 1}}; + HANDLE threads[2] = {CreateThread(nullptr, 0, overlap_thread, &workers[0], 0, nullptr), + CreateThread(nullptr, 0, overlap_thread, &workers[1], 0, nullptr)}; + if (!threads[0] || !threads[1]) return 1; + SetEvent(shared.start); + WaitForMultipleObjects(2, threads, TRUE, 30000); + const DWORD first = WaitForSingleObject(threads[0], 0), second = WaitForSingleObject(threads[1], 0); + for (HANDLE thread : threads) CloseHandle(thread); + CloseHandle(shared.start); + if (first != WAIT_OBJECT_0 || second != WAIT_OBJECT_0) { + std::printf("overlap threads did not finish\n"); + return 1; + } + if (shared.wrong_file) { + std::printf("overlap: %ld opens reached another thread's file (a name was shared between calls)\n", shared.wrong_file); + return 1; + } + if (shared.broken) { + std::printf("overlap: a caller name was changed while its call was in flight\n"); + return 1; + } + if (shared.completed != 2 * shared.opens) { + std::printf("overlap incomplete: %ld of %d opens succeeded\n", shared.completed, 2 * shared.opens); + return 1; + } + std::printf("overlap ok: %ld opens across two threads, both caller names intact\n", shared.completed); + return 0; +} +} // namespace + +int main() +{ + wchar_t mode[16]{}; + const DWORD len = GetEnvironmentVariableW(L"X2W_PROBE_MODE", mode, 16); + if (len == 5 && _wcsicmp(mode, L"reuse") == 0) return reused_string(); + if (len == 7 && _wcsicmp(mode, L"overlap") == 0) return overlapping_names(); + return single_open(); +} \ No newline at end of file diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index abc4c7005a..bcc4a2a086 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -5,6 +5,8 @@ // --mutate first-32: expect a resolved FirstElement above 4 Gi elements to be cut to 32 bits. // --mutate unplaced-extent: expect page span calculation crossing a 64 KiB boundary to return a single page. // --mutate unplaced-covers: expect a buffer range past the end of the cached page to be accepted as covered. +// --mutate unplaced-heap-limit: expect a 2 GiB allocation to be wrapped as an existing heap for an unplaced buffer. +// --mutate exact-start: expect a page-start base to be kept for a view address that is not a whole number of elements in. // Each mutated run is a negative control and must fail. #include "startup_stubs/memory_srv_buffer.h" @@ -84,10 +86,11 @@ int main(int argc, char** argv) if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && (std::strcmp(argv[2], "height") == 0 || std::strcmp(argv[2], "exact-fit") == 0 || std::strcmp(argv[2], "first-32") == 0 || - std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0)) { + std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0 || + std::strcmp(argv[2], "unplaced-heap-limit") == 0 || std::strcmp(argv[2], "exact-start") == 0)) { mutation = argv[2]; } else if (argc != 1) { - std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers]\n"); + std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers|unplaced-heap-limit|exact-start]\n"); return 2; } const auto buf = buffer_desc(1024); @@ -301,6 +304,37 @@ int main(int argc, char** argv) check("unplaced covers zero cached span", !x2w_startup::unplaced_buffer_covers(0x10000, 0, 0x10000, 48)); check("unplaced covers zero requested span", !x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x10000, 0)); + // Shapes of the three structured views the title published at sub-allocated addresses (low 16 bits of the address, stride). + const std::uint64_t shapes[3][2] = {{0x6200, 2048}, {0x1c80, 320}, {0x6a00, 180}}; + for (const auto& shape : shapes) { + const std::uint64_t address = 0x7f0000000000ull + shape[0]; + const std::uint64_t page = address & ~0xffffull; + D3D12_SHADER_RESOURCE_VIEW_DESC structured{}; + structured.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + structured.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + structured.Buffer.NumElements = 1; + structured.Buffer.StructureByteStride = static_cast<UINT>(shape[1]); + D3D12_SHADER_RESOURCE_VIEW_DESC out{}; + check("page-start base cannot name a sub-allocated structured view", + !x2w_startup::resolve_buffer_srv_desc(page, 65536, address, structured, out)); + const bool exact = x2w_startup::unplaced_view_needs_exact_start(address, page, shape[1], false) && !mutated("exact-start"); + const std::uint64_t base = exact ? address : page; + check("exact-start base names a sub-allocated structured view", + x2w_startup::resolve_buffer_srv_desc(base, shape[1], address, structured, out) && out.Buffer.FirstElement == 0); + } + check("aligned address keeps the page base", !x2w_startup::unplaced_view_needs_exact_start(0x14000, 0x10000, 2048, false)); + check("raw view keeps the page base", + !(x2w_startup::unplaced_view_needs_exact_start(0x10001, 0x10000, 4, true) || mutated("raw-exact"))); + + // Existing-heap wrap of the allocation holding an unplaced buffer: up to the 256 MiB span limit only. + check("unplaced heap 64 KiB allocation", x2w_startup::unplaced_existing_heap_allowed(65536)); + check("unplaced heap 256 MiB allocation", x2w_startup::unplaced_existing_heap_allowed(256ull << 20)); + check("unplaced heap 256 MiB + 64 KiB allocation", + !x2w_startup::unplaced_existing_heap_allowed((256ull << 20) + 65536)); + check("unplaced heap 2 GiB allocation", + x2w_startup::unplaced_existing_heap_allowed(2ull << 30) == mutated("unplaced-heap-limit")); + check("unplaced heap unknown allocation size", !x2w_startup::unplaced_existing_heap_allowed(0)); + if (failures) return 1; std::printf("slot 70 buffer memory SRV validation: all checks passed\n"); return 0; diff --git a/tests/startup_memory_srv_census_check.cpp b/tests/startup_memory_srv_census_check.cpp index c8f4b0ec20..e0fdcbfbb9 100644 --- a/tests/startup_memory_srv_census_check.cpp +++ b/tests/startup_memory_srv_census_check.cpp @@ -2,8 +2,10 @@ // distinct refused shapes, the first 4 pipelines and the first 8 written entries, shapes only for // description-dependent reasons, the overflow counters, and a periodic report that is skipped when // nothing changed. +#include "startup_stubs/memory_srv_as.h" #include "startup_stubs/memory_srv_census.h" +#include <cstdint> #include <cstdio> #include <cstring> #include <string> @@ -34,6 +36,26 @@ template <class Census> std::vector<std::string> lines(Census& census, bool only int main() { using namespace x2w_startup; + { + // The cause texture_unavailable names (d3d12_memory_srv.inl, texture_unavailable_reason). A lookup that never tried to + // publish is a missing resource whatever the size; a layout over the 64 MiB single-copy limit is named by size and + // never touches its pages; within the limit unreadable texels and an unexplained failure stay apart. + bool touched = false; + const auto readable = [&](bool value) { return [&touched, value] { touched = true; return value; }; }; + const std::uint64_t limit = max_published_texture_bytes; + check("limit is 64 MiB", limit == 64ull << 20); + check("no publication: no resource", !std::strcmp(texture_unavailable_cause(false, 0, readable(true)), "texture_no_resource")); + check("no publication, huge layout: still no resource", !std::strcmp(texture_unavailable_cause(false, limit + 1, readable(false)), "texture_no_resource")); + touched = false; + check("over the limit: named by size", !std::strcmp(texture_unavailable_cause(true, limit + 1, readable(true)), "texture_over_64mib")); + check("over the limit: the pages are not touched", !touched); + check("over the limit and unreadable: still size", !std::strcmp(texture_unavailable_cause(true, limit + 1, readable(false)), "texture_over_64mib")); + check("exactly the limit is within it", !std::strcmp(texture_unavailable_cause(true, limit, readable(false)), "texture_unreadable")); + check("within the limit, readable: other failure", !std::strcmp(texture_unavailable_cause(true, 4096, readable(true)), "texture_unavailable")); + check("within the limit, unreadable texels", !std::strcmp(texture_unavailable_cause(true, 4096, readable(false)), "texture_unreadable")); + for (const char* name : {"texture_no_resource", "texture_unreadable", "texture_over_64mib"}) + check("each cause has its own census reason", memory_srv_reason_index(name) < memory_srv_reason_count); + } MemorySrvCensus srv; const auto a = texture(64, DXGI_FORMAT_BC1_UNORM, 7); check("first shape is detailed", srv.note("unsupported_description", &a)); @@ -41,6 +63,27 @@ int main() check("same shape, other reason is a new shape", srv.note("texture_unavailable", &a)); check("reasons without a shape keep none", !srv.note("null_address", &a) && !srv.note("null_destination", &a)); check("unreadable description keeps no shape", !srv.note("unsupported_description", nullptr)); + // Every name the acceleration-structure resolver can return is a census reason of its own (not "other") + // and, because that path does not read the resource description, keeps no shape. The names come from + // as_srv_refusal_name, so a fourth refusal that is not added to memory_srv_reasons fails here. + { + int as_names = 0; + MemorySrvCensus probe; + for (int r = static_cast<int>(AsSrvRefusal::none) + 1;; ++r) { + const char* name = as_srv_refusal_name(static_cast<AsSrvRefusal>(r)); + if (!std::strcmp(name, "none")) break; + ++as_names; + const int index = memory_srv_reason_index(name); + check("acceleration-structure refusal has its own census reason", index < memory_srv_reason_count); + check("acceleration-structure refusal keeps no shape", !memory_srv_reason_has_shape(index) && !probe.note(name, &a)); + } + check("the acceleration-structure refusals were enumerated", as_names >= 3); + MemorySrvCensus fresh; + fresh.note("as_unaligned", &a); + const auto fresh_report = lines(fresh, false); + check("as_unaligned is reported by name", fresh_report.size() == 1 && fresh_report[0].find(" as_unaligned 1,") != std::string::npos && + fresh_report[0].find(" other 0;") != std::string::npos); + } const auto b = texture(128, DXGI_FORMAT_BC7_UNORM, 8), c = texture(256, DXGI_FORMAT_R8G8B8A8_UNORM, 9), d = texture(512, DXGI_FORMAT_BC3_UNORM, 10); check("third shape is detailed", srv.note("buffer_unavailable", &b)); @@ -58,7 +101,7 @@ int main() check("summary", !report.empty() && report[0] == "x2w-d3d12 memory SRV refusals (slot 70): total 138; null_destination 1, unreadable_resource 0, unreadable_view 0, " "null_address 1, unsupported_description 133, destination_outside_view_heaps 0, gpu_written_resource 0, " - "buffer_unavailable 1, texture_unavailable 1, partial_tile_xg_rows 0, partial_tile_beyond_xg_size 0, unsupported_desktop_format 0, " + "as_unaligned 0, as_not_placed 0, as_wrong_state 0, buffer_unavailable 1, texture_unavailable 1, texture_no_resource 0, texture_unreadable 0, texture_over_64mib 0, partial_tile_xg_rows 0, partial_tile_beyond_xg_size 0, unsupported_desktop_format 0, " "console_layout_xg_rows 0, console_layout_without_footprints 0, console_layout_beyond_xg_size 0, overlapping_resource 0, " "other 1; distinct shapes 128 (calls past the shape table 5)"); check("first shape line", report.size() > 1 && report[1] == diff --git a/tests/startup_memory_srv_diag_check.py b/tests/startup_memory_srv_diag_check.py index 539e9cb62b..3ebacd9c2f 100644 --- a/tests/startup_memory_srv_diag_check.py +++ b/tests/startup_memory_srv_diag_check.py @@ -25,7 +25,7 @@ " return float4(t.Load(int3(uint2(p.xy) % 2, 0)), 0, 0, 1);\n}\n") REFUSALS = (r"x2w-d3d12 memory SRV refusals \(slot 70\): total 9; null_destination 0, unreadable_resource 0, " r"unreadable_view 0, null_address 8, unsupported_description 1, destination_outside_view_heaps 0, " - r"gpu_written_resource 0, buffer_unavailable 0, texture_unavailable 0, partial_tile_xg_rows 0, partial_tile_beyond_xg_size 0, " + r"gpu_written_resource 0, as_unaligned 0, as_not_placed 0, as_wrong_state 0, buffer_unavailable 0, texture_unavailable 0, texture_no_resource 0, texture_unreadable 0, texture_over_64mib 0, partial_tile_xg_rows 0, partial_tile_beyond_xg_size 0, " r"unsupported_desktop_format 0, console_layout_xg_rows 0, console_layout_without_footprints 0, " r"console_layout_beyond_xg_size 0, overlapping_resource 0, other 0; " r"distinct shapes 1 \(calls past the shape table 0\)") diff --git a/tests/startup_mesh57_depth_only_check.py b/tests/startup_mesh57_depth_only_check.py new file mode 100644 index 0000000000..7ca3c62ab6 --- /dev/null +++ b/tests/startup_mesh57_depth_only_check.py @@ -0,0 +1,140 @@ +"""Slot 57 mesh requests with a depth-only pixel stage translate in tools/startup/gfx2hlsl.py (#2413, T5). + +usage: startup_mesh57_depth_only_check.py + +A pixel stage without a colour output ends in `exp null off, off, off, off done vm` (LLVM SILateBranchLowering, +Mesa ACO create_fs_null_export). Before an alpha test it narrows EXEC, so the `vm` export kills the lanes it left. +The mesh stage is the accepted fixture of startup_mesh57_skeleton_check.py. The pixel words are built here: +v_interp_mov_f32 v0, p0, attr0.x; v_cmp_gt_f32 vcc, 0.5, v0; s_andn2_b64 exec, exec, vcc; exp null done vm; +s_endpgm. The pair must translate to a pixel stage with no SV_Target that keeps the discard, and a manifest with +an empty `targets` line. Controls: without the EXEC narrowing there is no discard, a null export followed by +a position export is still refused by the role check, and a null export before or after an mrt0, mrtz or param0 +export is refused with no source or manifest written. + +A colour stage whose null export is only the early exit of a kill (after the main s_endpgm, reached only by +s_cbranch_execz, or by s_cbranch_scc0 directly after s_cselect exec, exec, 0 in the demote form) translates with its +colour target and discard; five near misses of each form stay refused. +""" +import os +from pathlib import Path +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import startup_mesh57_skeleton_check as S # noqa: E402 + +INTERP, COMPARE, NARROW = 'c8020002', '7c0800f0', '8afe6a7e' +NULL_EXPORT, ENDPGM = ['f8001890', '00000000'], 'bf810000' +ALPHA_TEST = [INTERP, COMPARE, NARROW] + NULL_EXPORT + [ENDPGM] + + +def translate(pixel): + with tempfile.TemporaryDirectory() as tmp: + key, result = S.request(tmp, S.MESH, pixel) + files = [Path(tmp) / ('%016x.%s' % (key, ext)) for ext in ('ps57.hlsl', 'ms57.txt')] + return (result,) + tuple(f.read_text() if f.exists() else '' for f in files) + + +MIXES = 'unsupported: slot 57 pixel stage mixes the null export with another export' + + +def kill_exit(): + """A colour stage whose null export is only the early exit of a kill translates; near misses stay refused.""" + words = S.KILL_EXIT_PIXEL + exit_at = len(words) - 3 # the null export's first word; it and s_endpgm follow the main s_endpgm + S.expect('kill-exit words decode', [x[3] for x in S.G.decode(S.code(words))], + ['v_interp_mov_f32_e32 v0, p0, attr0.x', 'v_interp_mov_f32_e32 v1, p0, attr0.y', + 'v_interp_mov_f32_e32 v2, p0, attr0.z', 'v_interp_mov_f32_e32 v3, p0, attr0.w', + 'v_cmpx_lt_f32_e32 0.5, v0', 's_cbranch_execz label_0x24', 'exp mrt0 v0, v1, v2, v3 done vm', 's_endpgm', + 'exp null off, off, off, off done vm', 's_endpgm']) + result, hlsl, manifest = translate(words) + S.expect('kill-exit colour stage translates', result, 'ok') + S.expect('kill-exit stage writes its colour', 'SV_Target' in hlsl, True) + S.expect('kill-exit stage keeps the vm discard', 'if (!(exec & 1)) discard;' in hlsl, True) + _, _, colour_manifest = translate(S.PIXEL) + S.expect('kill-exit manifest names the colour target', manifest.splitlines()[-1:], colour_manifest.splitlines()[-1:]) + branch = words.index('bf880003') + for label, mutant in ( + # The main s_endpgm removed: the colour export falls through into the null export. + ('a null export the colour export falls into', + words[:branch] + [S.branch(0xbf88, branch, exit_at - 1)] + words[branch + 1:exit_at - 1] + words[exit_at:]), + # No branch reaches the block. + ('an exit block no branch reaches', words[:branch] + ['bf800000'] + words[branch + 1:]), + # s_branch enters with lanes still alive. + ('an exit block entered by s_branch', words[:branch] + ['bf820003'] + words[branch + 1:]), + # The exit export without vm kills nothing. + ('an exit export without vm', words[:exit_at] + ['f8000890'] + words[exit_at + 1:]), + # Anything else in the block: v_mov_b32 v0, 0 before the null export. + ('an exit block with another instruction', + words[:branch] + ['bf880004'] + words[branch + 1:exit_at] + ['7e000280'] + words[exit_at:])): + S.expect(label + ' is refused', translate(mutant)[0], MIXES) + demote_exit() + + +def demote_exit(): + """The demote form enters the exit with s_cbranch_scc0 right after s_cselect exec, exec, 0; near misses stay refused.""" + words = S.DEMOTE_EXIT_PIXEL + result, hlsl, manifest = translate(words) + S.expect('demote-exit colour stage translates', result, 'ok') + S.expect('demote-exit stage writes its colour', 'SV_Target' in hlsl, True) + S.expect('demote-exit stage keeps the vm discard', 'if (!(exec & 1)) discard;' in hlsl, True) + select, branch = words.index('85fe807e'), words.index('bf840004') + for label, mutant in ( + # SCC still comes from the live mask, but EXEC is not cleared before the branch. + ('s_cbranch_scc0 without the s_cselect', words[:select] + ['bf800000'] + words[select + 1:]), + ('an s_cselect that keeps EXEC', words[:select] + ['85fec17e'] + words[select + 1:]), + ('an s_cselect into another register', words[:select] + ['858e807e'] + words[select + 1:]), + # An instruction between s_cselect and the branch (s_mov_b32 s20, 0) breaks the adjacency. + ('an instruction between s_cselect and s_cbranch_scc0', + words[:branch] + ['be940380', 'bf840004'] + words[branch + 1:]), + # s_cbranch_scc1 enters the exit when lanes are still live. + ('s_cbranch_scc1 into the exit', words[:branch] + ['bf850004'] + words[branch + 1:])): + S.expect(label + ' is refused', translate(mutant)[0], MIXES) + + +def main(): + os.environ['X2W_FXC'] = '' # source and manifest only; no compiler needed + S.expect('alpha-test words decode', [x[3] for x in S.G.decode(S.code(ALPHA_TEST))], + ['v_interp_mov_f32_e32 v0, p0, attr0.x', 'v_cmp_gt_f32_e32 vcc_lo, 0.5, v0', 's_andn2_b64 exec, exec, vcc', + 'exp null off, off, off, off done vm', 's_endpgm']) + result, hlsl, manifest = translate(ALPHA_TEST) + S.expect('depth-only pair translates', result, 'ok') + S.expect('pixel stage has no colour output', ('SV_Target' in hlsl, 'void main(PSIn i)' in hlsl), (False, True)) + S.expect('pixel stage keeps the vm discard', 'if (!(exec & 1)) discard;' in hlsl, True) + S.expect('manifest names no target', manifest.splitlines()[-1:], ['targets ']) + S.expect('manifest is not the mesh-only form', 'ps none' in manifest.splitlines(), False) + # Control: the same stage with all lanes alive exports under the entry EXEC, so nothing is discarded. + result, hlsl, _ = translate([INTERP] + NULL_EXPORT + [ENDPGM]) + S.expect('null export alone translates', result, 'ok') + S.expect('no narrowing, no discard', 'discard' in hlsl, False) + # Control: a null export followed by a position export is not a depth-only pixel stage. + position = ['f80008cf', '03020100'] + S.expect('null plus position is refused', translate(NULL_EXPORT + position + [ENDPGM])[0], + 'unsupported: slot 57 pixel stage has an incompatible export or termination') + # Control: the slot 57 profile is the null export alone. A colour, depth or parameter export before or after + # it is refused before any source or manifest is written. + null_first = ['f8000090', '00000000'] # exp null off, off, off, off + for target, before, after in (('mrt0', 'f800000f', 'f800180f'), ('mrtz', 'f8000081', 'f8001881'), + ('param0', 'f800020f', 'f8001a0f')): + for label, words, order in ( + ('%s + null' % target, [INTERP, before, '00000000'] + NULL_EXPORT + [ENDPGM], [target, 'null']), + ('null + %s' % target, [INTERP] + null_first + [after, '00000000', ENDPGM], ['null', target])): + decoded = [x[3] for x in S.G.decode(S.code(words))] + S.expect(label + ' decodes', ([a.split()[1] for a in decoded[1:3]], decoded[2].endswith('done vm')), + (order, True)) + with tempfile.TemporaryDirectory() as tmp: + key, result = S.request(tmp, S.MESH, words) + S.expect(label + ' is refused', result, + 'unsupported: slot 57 pixel stage mixes the null export with another export') + S.expect(label + ' leaves only the failure', sorted(p.name for p in Path(tmp).iterdir() + if not p.name.startswith('req_')), + ['%016x.fail' % key]) + kill_exit() + if S.FAILED: + return 1 + print('ok') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_mesh57_lane_spill_check.py b/tests/startup_mesh57_lane_spill_check.py new file mode 100644 index 0000000000..66091ef852 --- /dev/null +++ b/tests/startup_mesh57_lane_spill_check.py @@ -0,0 +1,243 @@ +"""Constant-lane v_writelane_b32 / v_readlane_b32 in translate_mesh57 (#2413 T7). + +usage: startup_mesh57_lane_spill_check.py + startup_mesh57_lane_spill_check.py binary <llvm-mc> + startup_mesh57_lane_spill_check.py draw <dxc> <offscreen_check> <warp|hardware> + +The fixture extends the accepted slot 57 group-memory shape with the #2127 spill idiom: +park ordinary scalars in fixed wave64 lanes of a spill-only VGPR under EXEC-independent +writelane/readlane, clobber the SGPRs, reload them, and use the colour reload as vertex red. +Raw EXEC sources stay refused. Ordinary VGPR use of the spill register, an exchange VGPR, an +unwritten slot, a register-selected lane, and a mutant that zeroes the spilled colour assignment +(not the multi-decl) must fail by name or change pixels. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 +from startup_mesh57_skeleton_check import ( # noqa: E402 + MESH, PIXEL, PIXEL_ASM, POST_COUNT, assemble, buffer, code, expect, FAILED, geometry, rasterise, root, +) + +SIDE = 32 + + +def writelane(vd, src, lane): + """Two little-endian words for `v_writelane_b32 vD, src, lane` (src is an SGPR index or special).""" + return ['%08x' % (0xd7610000 | vd), '%08x' % (src | ((128 + lane) << 9))] + + +def readlane(sd, vv, lane): + """Two little-endian words for `v_readlane_b32 sD, vV, lane` (VGPR encoded as 256+V).""" + return ['%08x' % (0xd7600000 | sd), '%08x' % ((256 + vv) | ((128 + lane) << 9))] + + +# s_mov_b32 s40, 1.0; writelane v30 lane 3; clobber; park/reload a second ordinary scalar in lane 63 +# (wave64); v_mov_b32 v7, s40 — vertex red comes from the colour reload. Raw EXEC spills are refused. +SPILL_ASM = """s_mov_b32 s40, 1.0 +v_writelane_b32 v30, s40, 3 +s_mov_b32 s40, 0 +s_mov_b32 s41, 0x11 +v_writelane_b32 v30, s41, 63 +s_mov_b32 s41, 0 +v_readlane_b32 s41, v30, 63 +v_readlane_b32 s40, v30, 3 +v_mov_b32 v7, s40""" +SPILL_WORDS = ( + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + ['bea90391'] + writelane(30, 41, 63) + ['bea90380'] + readlane(41, 30, 63) + + readlane(40, 30, 3) + ['7e0e0228'] +) +# After the colour load's waitcnt, overwrite v20 (red) with the reloaded spill in v7. +_WAIT = MESH.index('bf8c3f70') +SPILL_MESH = ( + MESH[:POST_COUNT] + SPILL_WORDS + MESH[POST_COUNT:_WAIT + 1] + + ['7e280307'] + MESH[_WAIT + 1:] +) +# Mutant: drop the colour writelane so the reload of lane 3 is unwritten at the host, or after a +# successful translation zero the spill assignment in HLSL so the draw oracle fails. +MUTANT_NO_WRITE = ( + MESH[:POST_COUNT] + ( + ['bea803f2', 'bea80380'] + ['bea90391'] + writelane(30, 41, 63) + ['bea90380'] + + readlane(41, 30, 63) + readlane(40, 30, 3) + ['7e0e0228'] + ) + MESH[POST_COUNT:_WAIT + 1] + ['7e280307'] + MESH[_WAIT + 1:] +) + + +def request(directory, mesh, pixel=PIXEL): + ms, ps, blob = code(mesh), code(pixel), root() + key = G.mesh57_key(ms, ps, blob) + for ext, data in (('.root', blob), ('.ps57', ps), ('.m57', ms)): + (Path(directory) / ('req_%016x%s' % (key, ext))).write_bytes(data) + return key, G.translate_request(str(directory), key) + + +def controls(): + os.environ['X2W_FXC'] = '' + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, SPILL_MESH) + expect('spill fixture translates', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('spill slots are declared', 'sp30_3' in text and 'sp30_63' in text, True) + expect('colour spill is assigned', 'sp30_3 =' in text, True) + expect('wave64 lane 63 parks the second scalar', 'sp30_63 =' in text and 's41 = sp30_63' in text, True) + expect('reload feeds the SGPR', 's40 = sp30_3' in text, True) + expect('spill VGPR is not a vector temporary', not re.search(r'\bv30\b', text), True) + + # Slot 57 mesh is always wave64: lanes 3 and 35 of one VGPR are two slots there (the k / k + 32 pair rule of the + # pixel and vertex stages, whose wave size is unknown, must not refuse them). + with tempfile.TemporaryDirectory() as tmp: + pair = (MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + ['bea90391'] + writelane(30, 41, 35) + ['bea90380'] + readlane(41, 30, 35) + + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:]) + key, result = request(tmp, pair) + expect('mesh lanes 3 and 35 of one VGPR are two slots', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('both slots are declared', 'sp30_3' in text and 'sp30_35' in text, True) + + refusals = ( + ('unwritten spill slot', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + readlane(40, 30, 4) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_readlane_b32 reads v30 lane 4 before any v_writelane_b32 wrote it'), + ('register-selected lane', + MESH[:POST_COUNT] + ['bea803f2', 'bea80380'] + + ['%08x' % (0xd761001e), '%08x' % (40 | (40 << 9))] # v_writelane v30, s40, s40 + + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_writelane_b32 requires a constant lane, got s40'), + ('lane 64 outside wave64', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 64) + MESH[POST_COUNT:], + 'v_writelane_b32 lane 64 outside 0..63'), + ('mixed ordinary use of the spill VGPR', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(30, 40, 3) + ['bea80380'] + + ['7e3c0300'] # v_mov_b32 v30, v0 — ordinary vector write of the spill VGPR + + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_writelane_b32: v30 is also used as a vector (v_mov_b32_e32)'), + ('spill into the group-index exchange VGPR', + MESH[:POST_COUNT] + ['bea803f2'] + writelane(5, 40, 3) + ['bea80380'] + + readlane(40, 5, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_writelane_b32: v5 is also used as a vector (v_lshrrev_b32_e32)'), + ('raw exec_hi spill', + MESH[:POST_COUNT] + writelane(30, 127, 63) + MESH[POST_COUNT:], + 'v_writelane_b32 source exec_hi is a lane mask or m0'), + ('raw exec_lo spill', + MESH[:POST_COUNT] + writelane(30, 126, 3) + MESH[POST_COUNT:], + 'v_writelane_b32 source exec_lo is a lane mask or m0'), + ('read before any write', + MESH[:POST_COUNT] + readlane(40, 30, 3) + ['7e0e0228'] + MESH[POST_COUNT:], + 'v_readlane_b32 reads v30 lane 3 before any v_writelane_b32 wrote it'), + ('missing colour write refuses at reload', MUTANT_NO_WRITE, + 'v_readlane_b32 reads v30 lane 3 before any v_writelane_b32 wrote it'), + ) + for what, mesh, reason in refusals: + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, mesh) + expect(what, result, 'unsupported: ' + reason) + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), + ['%016x.fail' % key]) + + +def binary(mc): + mesh = (HERE / 'startup_mesh57_skeleton.s').read_text() + insert = mesh.replace('v_cmpx_gt_i32 s14, v0', SPILL_ASM + '\nv_cmpx_gt_i32 s14, v0') + insert = insert.replace('exp pos0', 'v_mov_b32 v20, v7\nexp pos0') + expect('spill mesh words match llvm-mc', assemble(mc, insert), SPILL_MESH) + expect('pixel words match llvm-mc', assemble(mc, PIXEL_ASM), PIXEL) + + +def draw(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, SPILL_MESH) + expect('spill fixture translates and compiles', result, 'ok') + if result != 'ok': + return 0 + name = Path(tmp) / ('%016x' % key) + pipe = G.MeshPipeline(code(SPILL_MESH), code(PIXEL), root()) + constants = bytearray(1024) + for slot, count in enumerate((4, 12)): + struct.pack_into('<I', constants, 4 * pipe.uds.index(('rootconst', 0, slot)), count) + words = [a | b << 10 | c << 20 for a, b, c in indices] + # Reloaded s40 is 1.0 (0x3f800000); v_mov v7, s40 so every vertex red channel is 255. + red = [(255, g, b, a) for (_, g, b, a) in colours] + image = rasterise(points, red, indices, 12, 4) + head = bytes(constants) + buffer(points, colours, words) + b'\xcd' * 80 + path = Path(tmp) / 'spill.bin' + path.write_bytes(head + b''.join(map(bytes, image))) + args = [renderer, adapter, '--mesh-indexed', str(name) + '.ms57.cso', str(name) + '.ps57.cso', str(path)] + run = subprocess.run(args, capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect('draw of spill fixture', (run.returncode, 'pixels=1024 mismatches=0' in run.stdout), (0, True)) + + # Mutant: zero the spilled colour word in HLSL so the reload yields 0 and red becomes 0. + # Match a standalone assignment only (not the multi-decl `uint sp30_3 = 0, sp30_63 = 0;`). + source = name.with_suffix('.ms57.hlsl').read_text() + expect('fixture writes the colour spill slot', + re.search(r'(?m)^\s*sp30_3 = ', source) is not None, True) + mutated = Path(tmp) / 'zero-spill.hlsl' + mutated_text, nsub = re.subn(r'(?m)^(\s*)sp30_3 = [^;]+;', r'\1sp30_3 = 0u;', source, count=1) + expect('mutant rewrites exactly one colour spill assignment', nsub, 1) + expect('mutant still declares lane 63', 'sp30_63' in mutated_text, True) + mutated.write_text(mutated_text) + mutant = Path(tmp) / 'zero-spill.cso' + subprocess.run([dxc, '-T', 'ms_6_5', '-E', 'main', '-Fo', mutant, mutated], check=True) + zero_red = [(0, g, b, a) for (_, g, b, a) in colours] + wrong = rasterise(points, zero_red, indices, 12, 4) + different = sum(a != b for a, b in zip(image, wrong)) + expect('zeroing the spill changes pixels', different > 0, True) + path.write_bytes(head + b''.join(map(bytes, image))) + run = subprocess.run( + [renderer, adapter, '--mesh-indexed', str(mutant), str(name) + '.ps57.cso', str(path)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect('mutant fails the correct reference', + (run.returncode != 0 and 'mismatches=' in run.stdout), True) + path.write_bytes(head + b''.join(map(bytes, wrong))) + run = subprocess.run( + [renderer, adapter, '--mesh-indexed', str(mutant), str(name) + '.ps57.cso', str(path)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect('mutant matches the zeroed reference', + (run.returncode, 'pixels=1024 mismatches=0' in run.stdout), (0, True)) + print('spill draw: %d pixels differ when the spilled word is zeroed' % different) + return 0 + + +def main(argv): + status = 0 + if argv[1:2] == ['binary'] and len(argv) == 3: + binary(argv[2]) + elif argv[1:2] == ['draw'] and len(argv) == 5: + status = draw(*argv[2:]) + elif len(argv) == 1: + controls() + else: + print(__doc__) + return 2 + if FAILED: + return 1 + print('skip: no mesh shader tier' if status == 77 else 'ok') + return status + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/tests/startup_mesh57_loop.s b/tests/startup_mesh57_loop.s new file mode 100644 index 0000000000..3537b099ac --- /dev/null +++ b/tests/startup_mesh57_loop.s @@ -0,0 +1,85 @@ +// Source-built slot 57 mesh fixture for #2413 item T6: the accepted group-memory exchanges plus one +// constant-trip scalar loop after the count exchange. translate_mesh57 unrolls the four iterations; +// unsupported loop shapes still refuse by name (see startup_mesh57_loop_check.py). +// Entry and buffer layout match tests/startup_mesh57_skeleton.s. +// After the loop, s40 == 4 selects vertex red = 1.0 via v7; a mutant that drops the back-edge leaves +// s40 == 1 and red = 0. v20 is overwritten from v7 after the colour load, as in the skeleton branch draws. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +// Constant-trip loop (4 iterations). Final s40 == 4 writes vertex red = 1.0 into v7. +// Numeric SOPP offsets (as in startup_mesh57_skeleton.s): -3 retargets the add; +1 skips the red write. +v_mov_b32 v7, 0 +s_mov_b32 s40, 0 +s_add_u32 s40, s40, 1 +s_cmp_lt_u32 s40, 4 +s_cbranch_scc1 -3 +s_cmp_eq_u32 s40, 4 +s_cbranch_scc0 1 +v_mov_b32 v7, 1.0 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +v_mov_b32 v20, v7 +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_loop_check.py b/tests/startup_mesh57_loop_check.py new file mode 100644 index 0000000000..10aab1927a --- /dev/null +++ b/tests/startup_mesh57_loop_check.py @@ -0,0 +1,287 @@ +"""Slot 57 mesh constant-trip loop lowering outside the accepted group-memory exchanges (#2413 T6). + +usage: startup_mesh57_loop_check.py + startup_mesh57_loop_check.py binary <llvm-mc> + startup_mesh57_loop_check.py draw <dxc> <offscreen_check> <warp|hardware> + +The source-built fixture (tests/startup_mesh57_loop.s) keeps the skeleton exchanges and inserts one +constant-trip scalar loop after the count exchange. translate_mesh57 unrolls it; the request translates +and draws with vertex red = 1.0. Unsupported shapes still refuse with the named loop message: an +unconditional back-edge (the #2622 refusal program), a data-dependent trip count, and a loop whose +body writes EXEC. The once-through mutant replaces the back-edge with s_nop so s40 stays 1 and red +stays 0; a draw reference that expects the constant-trip image must fail on that mutant. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LOOP_REASON = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' + +# Constant-trip fixture: four iterations of s_add_u32 s40, s40, 1; s_cmp_lt_u32 s40, 4; then red from s40 == 4. +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 7e0e0280 bea80380 80288128 bf0a8428 bf85fffd bf068428 bf840001' + ' 7e0e02f2 7d28000e 3608008f 34080884 e0381000 80041004 e03810c0 80041404 bf8c3f70 7e280307' + ' f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f 34080882 e0301180 80041804' + ' bf8c3f70 f8000941 00000018 bf810000').split() +# Once-through mutant: back-edge replaced by s_nop (body runs once; s40 == 1; red stays 0). +ONCE = MESH[: MESH.index('bf85fffd')] + ['bf800000'] + MESH[MESH.index('bf85fffd') + 1:] +# Unconditional back-edge after the count exchange (#2622 refusal shape). +INFINITE = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 bf800000 bf82fffe 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80041404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Data-dependent trip: s_cmp_lt_u32 s40, s8 (root constant) instead of an immediate. +DATA_DEP = MESH[: MESH.index('bf0a8428')] + ['bf0a0828'] + MESH[MESH.index('bf0a8428') + 1:] +# EXEC write in the loop body: v_cmpx_gt_u32_e32 0, v0 between the add and the compare (branch -4). +_EXEC_AT = MESH.index('80288128') +EXEC_BODY = MESH[: _EXEC_AT + 1] + ['7da80080', 'bf0a8428', 'bf85fffc'] + MESH[_EXEC_AT + 3:] + +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + +FAILED = [] +SIDE = 32 +TRIANGLES = (((2, 2), (14, 2), (2, 14)), ((18, 3), (30, 5), (21, 14)), + ((3, 18), (13, 20), (6, 30)), ((18, 18), (30, 18), (30, 30))) +ORDER = (7, 2, 10, 5, 0, 8, 3, 11, 1, 6, 9, 4) + + +def expect(what, got, want): + if got != want: + FAILED.append(what) + print('FAIL %s: got %r, want %r' % (what, got, want)) + + +def code(words): + return b''.join(struct.pack('<I', int(word, 16)) for word in words) + + +def root(): + rts0 = (struct.pack('<6I', 2, 2, 24, 0, 0, 0) + struct.pack('<3I', 1, 0, 48) + struct.pack('<3I', 0, 0, 60) + + struct.pack('<3I', 0, 0, 2) + struct.pack('<2I', 0, 0)) + return b'DXBC' + bytes(16) + struct.pack('<4I', 1, 44 + len(rts0), 1, 36) + b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + + +def request(directory, mesh): + ms, ps, blob = code(mesh), code(PIXEL), root() + key = G.mesh57_key(ms, ps, blob) + for ext, data in (('.root', blob), ('.ps57', ps), ('.m57', ms)): + (Path(directory) / ('req_%016x%s' % (key, ext))).write_bytes(data) + return key, G.translate_request(str(directory), key) + + +def ignores_refusal_string(got, _want): + """Stubbed comparator: any unsupported result matches, regardless of the named reason.""" + return isinstance(got, str) and got.startswith('unsupported:') + + +def assemble(mc, text): + r = subprocess.run([mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', + '-show-encoding'], input=text, capture_output=True, text=True, check=True) + data = b''.join(bytes(int(b, 16) for b in m.split(',')) for m in re.findall(r'encoding: \[([^\]]*)\]', r.stdout)) + return ['%08x' % word for word in struct.unpack('<%dI' % (len(data) // 4), data)] + + +def geometry(): + points, colours, indices = [None] * 12, [None] * 12, [] + for t, triangle in enumerate(TRIANGLES): + for c, point in enumerate(triangle): + slot = ORDER[3 * t + c] + points[slot] = point + colours[slot] = (40 + 17 * slot, 250 - 19 * slot, (slot * 53) % 256, 255) + indices.append(tuple(ORDER[3 * t:3 * t + 3])) + return points, colours, indices + + +def buffer(points, colours, words): + data = bytearray(512) + for slot, (x, y) in enumerate(points): + struct.pack_into('<4f', data, 16 * slot, x / 16 - 1, 1 - y / 16, 0.5, 1) + struct.pack_into('<4f', data, 192 + 16 * slot, *(channel / 255 for channel in colours[slot])) + for t, word in enumerate(words): + struct.pack_into('<I', data, 384 + 4 * t, word) + return bytes(data) + + +def rasterise(points, colours, indices, verts, prims): + verts, prims = min(verts, 128), min(prims, 128) + image = [(0, 0, 0, 255)] * (SIDE * SIDE) + if not verts: + return image + for a, b, c in indices[:prims]: + a, b, c = (min(i, verts - 1) for i in (a, b, c)) + colour = colours[a % 16] + tri = [(2 * points[i % 16][0], 2 * points[i % 16][1]) for i in (a, b, c)] + area = (tri[1][0] - tri[0][0]) * (tri[2][1] - tri[0][1]) - (tri[1][1] - tri[0][1]) * (tri[2][0] - tri[0][0]) + if not area: + continue + if area < 0: + tri[1], tri[2] = tri[2], tri[1] + for y in range(SIDE): + for x in range(SIDE): + inside = True + for k in range(3): + (ax, ay), (bx, by) = tri[k], tri[(k + 1) % 3] + dx, dy = bx - ax, by - ay + edge = dx * (2 * y + 1 - ay) - dy * (2 * x + 1 - ax) + inside &= edge > 0 or (edge == 0 and (dy < 0 or (dy == 0 and dx > 0))) + if inside: + image[y * SIDE + x] = colour + return image + + +def binary(mc): + text = (HERE / 'startup_mesh57_loop.s').read_text() + expect('constant-trip fixture words match llvm-mc', assemble(mc, text), MESH) + mutant_text = text.replace('s_cbranch_scc1 -3\n', 's_nop 0\n') + expect('once-through mutant words match llvm-mc', assemble(mc, mutant_text), ONCE) + + +def host(): + os.environ['X2W_FXC'] = '' # sources and manifest only; draw mode compiles + want = 'unsupported: ' + LOOP_REASON + + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('constant-trip loop translates', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('constant-trip publishes mesh and pixel sources', names, + ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + hlsl = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('constant-trip unrolls four counter updates', + hlsl.count('0x00000001u') >= 4 and 's40' in hlsl, True) + + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, ONCE) + expect('once-through mutant translates', result, 'ok') + + for what, mesh in ( + ('unconditional back-edge', INFINITE), + ('data-dependent trip count', DATA_DEP), + ('EXEC write in the loop body', EXEC_BODY), + ): + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, mesh) + expect(what + ' refuses by name', result, want) + if result == want: + expect(what + ' .fail text', (Path(tmp) / ('%016x.fail' % key)).read_text(), LOOP_REASON + '\n') + + other = 'unsupported: slot 57 mesh: a branch enters or crosses a group-memory exchange' + expect('stubbed comparator would accept a wrong reason', ignores_refusal_string(other, want), True) + expect('exact oracle rejects that wrong reason', other == want, False) + expect('exact oracle matches the named loop refusal', want == 'unsupported: ' + LOOP_REASON, True) + + # Signedness comes from the compare alone: signed update + unsigned compare across bit 31 is not + # a finite unroll within MESH_TRIP_MAX (review on #2630). + expect('signed update / unsigned compare across bit 31 is not a finite trip count', + G.mesh_trip_count(0x7fffffff, 's_add_i32', 1, 's_cmp_gt_u32', 4, 's_cbranch_scc1', True), + None) + expect('unsigned compare after signed update from -3 is one trip', + G.mesh_trip_count((-3) & 0xffffffff, 's_add_i32', 1, 's_cmp_lt_u32', 0, 's_cbranch_scc1', True), + 1) + + if FAILED: + print('startup_mesh57_loop: %d failed' % len(FAILED)) + return 1 + print('startup_mesh57_loop: ok') + return 0 + + +def draw(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + words = [a | b << 10 | c << 20 for a, b, c in indices] + # Constant-trip: every vertex red channel is 255. Once-through mutant keeps the buffer reds. + trip_colours = [(255, *colour[1:]) for colour in colours] + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('constant-trip translates and compiles', result, 'ok') + if result != 'ok': + return 1 if FAILED else 0 + name = str(Path(tmp) / ('%016x' % key)) + uds = G.MeshPipeline(code(MESH), code(PIXEL), root()).uds + constants = bytearray(1024) + struct.pack_into('<I', constants, 4 * uds.index(('rootconst', 0, 0)), 4) + struct.pack_into('<I', constants, 4 * uds.index(('rootconst', 0, 1)), 12) + image = rasterise(points, trip_colours, indices, 12, 4) + path = Path(tmp) / 'draw.bin' + path.write_bytes(bytes(constants) + buffer(points, colours, words) + b'\xcd' * 80 + + b''.join(bytes(pixel) for pixel in image)) + r = subprocess.run([renderer, adapter, '--mesh-indexed', name + '.ms57.cso', name + '.ps57.cso', str(path)], + capture_output=True, text=True) + if r.returncode == 77: + print(r.stdout + r.stderr) + return 77 + print('constant-trip draw: %s' % (r.stdout.strip().splitlines()[-1:] or [r.stderr.strip()])) + expect('constant-trip draw matches CPU oracle', + (r.returncode, 'pixels=1024 mismatches=0' in r.stdout), (0, True)) + + # Negative control: same reference against the once-through mutant (red stays buffer red ≠ 255). + key2, result2 = request(tmp, ONCE) + expect('once-through mutant translates and compiles', result2, 'ok') + if result2 == 'ok': + name2 = str(Path(tmp) / ('%016x' % key2)) + r = subprocess.run( + [renderer, adapter, '--mesh-indexed', name2 + '.ms57.cso', name2 + '.ps57.cso', str(path)], + capture_output=True, text=True) + if r.returncode == 77: + print(r.stdout + r.stderr) + return 77 + # Require a real draw-reference mismatch (not an unrelated PSO/command failure). + expect('once-through mutant fails the constant-trip reference', + (r.returncode != 0 + and 'Draw reference mismatch' in r.stderr + and 'mismatches=' in r.stdout + and 'mismatches=0' not in r.stdout), True) + + wrong = list(image) + at = next(i for i, pixel in enumerate(image) if pixel != (0, 0, 0, 255)) + wrong[at] = (0, 0, 0, 255) + path.write_bytes(bytes(constants) + buffer(points, colours, words) + b'\xcd' * 80 + + b''.join(bytes(pixel) for pixel in wrong)) + r = subprocess.run([renderer, adapter, '--mesh-indexed', name + '.ms57.cso', name + '.ps57.cso', str(path)], + capture_output=True, text=True) + expect('a reference with one wrong pixel fails', + (r.returncode, 'pixels=1024 mismatches=1' in r.stdout, 'Draw reference mismatch' in r.stderr), + (1, True, True)) + + if FAILED: + print('startup_mesh57_loop draw: %d failed' % len(FAILED)) + return 1 + print('startup_mesh57_loop draw: ok') + return 0 + + +if __name__ == '__main__': + argv = sys.argv + if len(argv) == 3 and argv[1] == 'binary': + binary(argv[2]) + raise SystemExit(1 if FAILED else 0) + if argv[1:2] == ['draw'] and len(argv) == 5: + raise SystemExit(draw(*argv[2:])) + if len(argv) != 1: + print(__doc__.strip(), file=sys.stderr) + raise SystemExit(2) + raise SystemExit(host()) diff --git a/tests/startup_mesh57_loop_refusal.s b/tests/startup_mesh57_loop_refusal.s new file mode 100644 index 0000000000..4303b79411 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal.s @@ -0,0 +1,74 @@ +// Source-built slot 57 mesh fixture for #2413 item T6: the accepted group-memory exchanges plus one +// deliberate back-edge outside them. Tip translate_mesh57 must refuse that loop by name. +// Entry and buffer layout match tests/startup_mesh57_skeleton.s. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +// Back-edge outside both modelled exchanges: s_branch -2 retargets the preceding s_nop. +s_nop 0 +s_branch -2 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_loop_refusal_check.py b/tests/startup_mesh57_loop_refusal_check.py new file mode 100644 index 0000000000..83f8da976f --- /dev/null +++ b/tests/startup_mesh57_loop_refusal_check.py @@ -0,0 +1,128 @@ +"""Slot 57 mesh loop refusal outside the accepted group-memory exchanges (#2413 T6). + +usage: startup_mesh57_loop_refusal_check.py + startup_mesh57_loop_refusal_check.py binary <llvm-mc> + +The source-built fixture (tests/startup_mesh57_loop_refusal.s) keeps the skeleton exchanges and inserts one +back-edge after the count exchange. Tip translate_mesh57 must refuse it with the named loop message. The mutant +replaces that back-edge with a second s_nop so the request no longer stops on the loop refusal (it translates +through the source-only path). A stubbed comparator that ignores the refusal string would accept a different +unsupported reason; this check uses an exact match so that stub fails. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LOOP_REASON = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' +# Skeleton words through the count-exchange join (s_mov_b64 exec, -1), then s_nop; s_branch -2; then the body. +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 bf800000 bf82fffe 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80041404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Mutant: the same program with the back-edge replaced by a second s_nop. +MUTANT = MESH[: MESH.index('bf82fffe')] + ['bf800000'] + MESH[MESH.index('bf82fffe') + 1:] +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + +FAILED = [] + + +def expect(what, got, want): + if got != want: + FAILED.append(what) + print('FAIL %s: got %r, want %r' % (what, got, want)) + + +def code(words): + return b''.join(struct.pack('<I', int(word, 16)) for word in words) + + +def root(): + rts0 = (struct.pack('<6I', 2, 2, 24, 0, 0, 0) + struct.pack('<3I', 1, 0, 48) + struct.pack('<3I', 0, 0, 60) + + struct.pack('<3I', 0, 0, 2) + struct.pack('<2I', 0, 0)) + return b'DXBC' + bytes(16) + struct.pack('<4I', 1, 44 + len(rts0), 1, 36) + b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + + +def request(directory, mesh): + ms, ps, blob = code(mesh), code(PIXEL), root() + key = G.mesh57_key(ms, ps, blob) + for ext, data in (('.root', blob), ('.ps57', ps), ('.m57', ms)): + (Path(directory) / ('req_%016x%s' % (key, ext))).write_bytes(data) + return key, G.translate_request(str(directory), key) + + +def ignores_refusal_string(got, _want): + """Stubbed comparator: any unsupported result matches, regardless of the named reason.""" + return isinstance(got, str) and got.startswith('unsupported:') + + +def assemble(mc, text): + r = subprocess.run([mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', '-show-encoding'], + input=text, capture_output=True, text=True, check=True) + data = b''.join(bytes(int(b, 16) for b in m.split(',')) for m in re.findall(r'encoding: \[([^\]]*)\]', r.stdout)) + return ['%08x' % word for word in struct.unpack('<%dI' % (len(data) // 4), data)] + + +def binary(mc): + text = (HERE / 'startup_mesh57_loop_refusal.s').read_text() + expect('loop fixture words match llvm-mc', assemble(mc, text), MESH) + mutant_text = text.replace('s_nop 0\ns_branch -2\n', 's_nop 0\ns_nop 0\n') + expect('mutant words match llvm-mc', assemble(mc, mutant_text), MUTANT) + + +def main(): + os.environ['X2W_FXC'] = '' # sources and manifest only; the refusal is raised before DXC + want = 'unsupported: ' + LOOP_REASON + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('loop fixture refuses by name', result, want) + expect('loop fixture publishes only the .fail', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), + ['%016x.fail' % key]) + if result == want: + expect('loop .fail text', (Path(tmp) / ('%016x.fail' % key)).read_text(), LOOP_REASON + '\n') + + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MUTANT) + expect('mutant does not report the loop refusal', result.startswith('unsupported: ' + LOOP_REASON), False) + expect('mutant translates through the source-only path', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('mutant publishes mesh and pixel sources', names, + ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + + # A stub that ignores the refusal string would accept a different unsupported reason for this oracle. + other = 'unsupported: slot 57 mesh: a branch enters or crosses a group-memory exchange' + expect('stubbed comparator would accept a wrong reason', ignores_refusal_string(other, want), True) + expect('exact oracle rejects that wrong reason', other == want, False) + expect('exact oracle matches the named loop refusal', want == 'unsupported: ' + LOOP_REASON, True) + + if FAILED: + print('startup_mesh57_loop_refusal: %d failed' % len(FAILED)) + return 1 + print('startup_mesh57_loop_refusal: ok') + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'binary': + binary(sys.argv[2]) + raise SystemExit(1 if FAILED else 0) + if len(sys.argv) != 1: + print(__doc__.strip(), file=sys.stderr) + raise SystemExit(2) + raise SystemExit(main()) diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 5635450901..ad4d0f2d5c 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -3,6 +3,8 @@ usage: startup_mesh57_skeleton_check.py startup_mesh57_skeleton_check.py binary <llvm-mc> startup_mesh57_skeleton_check.py draw <dxc> <offscreen_check> <warp|hardware> + startup_mesh57_skeleton_check.py depth <dxc> <offscreen_check> <warp|hardware> + startup_mesh57_skeleton_check.py killexit <dxc> <offscreen_check> <warp|hardware> startup_mesh57_skeleton_check.py formatted <dxc> <offscreen_check> <warp|hardware> startup_mesh57_skeleton_check.py shift <dxc> <offscreen_check> <warp|hardware> startup_mesh57_skeleton_check.py exchange <dxc> <offscreen_check> <warp|hardware> <publisher> @@ -17,6 +19,14 @@ refused with its own message. `binary` compares the embedded words with llvm-mc. `draw` compiles the request path's output (ms_6_5, ps_6_0), draws it and compares the read-back target with a CPU rasteriser written here; a reference with one wrong pixel must fail. +`depth` compiles the pair with a pixel stage that exports only to the null target (a depth-only pass), draws it +twice into a depth buffer cleared to the sentinel 1.0 with depth test LESS, and compares colour (left cleared) and +depth with the CPU rasteriser; a reference without the depth writes, and the same mesh with a null-export stage +that does not discard, must each fail. +`killexit` draws the colour pair whose pixel stage kills lanes with red at or below 0.5 and leaves through the +early-exit null export (entered by s_cbranch_execz, and in the demote form by s_cbranch_scc0 after s_cselect), +and compares both with the CPU rasteriser without the killed triangles; the same mesh with the pixel stage that +does not kill must differ at exactly the killed pixels. The exchange mode uses the runtime-published request and the same pixel comparison. """ import os @@ -45,6 +55,40 @@ PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_interp_mov_f32 v1, p0, attr0.y\nv_interp_mov_f32 v2, p0, attr0.z\n' 'v_interp_mov_f32 v3, p0, attr0.w\nexp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n') PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() +# A depth-only pixel stage: no colour output, only the null-target export (done, vm, no channel). Lanes whose flat +# attribute 0 red is not above 0.5 leave EXEC, so the vm export kills them and they write no depth. +DEPTH_PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_cmpx_lt_f32_e32 0.5, v0\n' + 'exp null off, off, off, off done vm\ns_endpgm\n') +DEPTH_PIXEL = 'c8020002 7c2200f0 f8001890 00000000 bf810000'.split() +NULL_EXPORT = DEPTH_PIXEL.index('f8001890') +# The drawn stage with exp mrt0 v0, v0, v0, v0 inserted before its null export (after the v_cmpx), then the drawn +# stage reading attribute 1, which the mesh does not export. The other mixed forms (mrtz, param0, pos0, both orders, +# no EXEC narrowing) are covered by startup_mesh57_depth_only_check.py. +# A colour stage with the early exit of a kill (LLVM SILateBranchLowering, Mesa ACO): when no lane is left after +# v_cmpx, s_cbranch_execz jumps past the main s_endpgm to a block that is only the null export and s_endpgm. +# Lanes whose flat attribute 0 red is not above 0.5 are killed; the others write their colour. +KILL_EXIT_PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_interp_mov_f32 v1, p0, attr0.y\n' + 'v_interp_mov_f32 v2, p0, attr0.z\nv_interp_mov_f32 v3, p0, attr0.w\n' + 'v_cmpx_lt_f32_e32 0.5, v0\ns_cbranch_execz .exit\nexp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n' + '.exit:\nexp null off, off, off, off done vm\ns_endpgm\n') +KILL_EXIT_PIXEL = ('c8020002 c8060102 c80a0202 c80e0302 7c2200f0 bf880003 f800180f 03020100 bf810000' + ' f8001890 00000000 bf810000').split() +# The demote form of the same exit (LLVM SILateBranchLowering): the live mask leaves SCC, s_cselect sets EXEC to 0 +# when no lane is live, and s_cbranch_scc0 then enters the exit with EXEC zero. Same kill as KILL_EXIT_PIXEL. +DEMOTE_EXIT_PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_interp_mov_f32 v1, p0, attr0.y\n' + 'v_interp_mov_f32 v2, p0, attr0.z\nv_interp_mov_f32 v3, p0, attr0.w\n' + 's_mov_b64 s[12:13], exec\nv_cmp_gt_f32_e32 vcc, 0.5, v0\ns_andn2_b64 s[12:13], s[12:13], vcc\n' + 's_cselect_b64 exec, exec, 0\ns_cbranch_scc0 .exit\ns_mov_b64 exec, s[12:13]\n' + 'exp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n' + '.exit:\nexp null off, off, off, off done vm\ns_endpgm\n') +DEMOTE_EXIT_PIXEL = ('c8020002 c8060102 c80a0202 c80e0302 be8c047e 7c0800f0 8a8c6a0c 85fe807e bf840004 befe040c' + ' f800180f 03020100 bf810000 f8001890 00000000 bf810000').split() +DEPTH_PIXEL_MUTANTS = ( + ('a colour write next to the drawn null export', DEPTH_PIXEL[:NULL_EXPORT] + ['f800000f', '00000000'] + DEPTH_PIXEL[NULL_EXPORT:], + 'slot 57 pixel stage mixes the null export with another export'), + ('a depth-only pixel stage reading an attribute the mesh does not export', ['c8020402'] + DEPTH_PIXEL[1:], + 'pixel stage reads attributes [1] the vertex stage does not export'), +) # Overwrite red after the raw colour load; green, blue and alpha still come from its other three words. COLOUR_LOAD = 'buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192' @@ -84,9 +128,13 @@ def vertex_red(words): return mesh[:at] + words.split() + mesh[at:] -def masked_vertex_red(): - mesh = vertex_red('7e0e02f0 7d880086 be94246a bf880002 7e0e02f2 bf820001 bf800000 ' - '8afe7e14 7e0e0280 befe04c1') +MASKED_IF_ELSE = '7e0e02f0 7d880086 be94246a bf880002 7e0e02f2 bf820001 bf800000 8afe7e14 7e0e0280 befe04c1' +# The same if/else with s_add_u32 s50, s13, 1 in the then arm. No path reads s50 after the join. +MASKED_DEAD_SCALAR = '7e0e02f0 7d880086 be94246a bf880003 7e0e02f2 8032810d bf820001 bf800000 8afe7e14 7e0e0280 befe04c1' + + +def masked_vertex_red(words=MASKED_IF_ELSE): + mesh = vertex_red(words) at = mesh.index('f80008cf') return mesh[:at] + ['bf880004'] + mesh[at:] # s_cbranch_execz skips both vertex exports @@ -132,6 +180,8 @@ def masked_vertex_red(): # v_mov v7, 1.0; s_branch .else; .empty: s_nop; .else: s_andn2_b64 exec, s[20:21], exec # v_mov v7, 0; s_mov_b64 exec, -1 ('lane-masked if/else', masked_vertex_red(), lambda lane: 255 if lane < 6 else 0), + ('lane-masked if/else with a dead scalar write', masked_vertex_red(MASKED_DEAD_SCALAR), + lambda lane: 255 if lane < 6 else 0), ) COUNT = [i for i, word in enumerate(MESH) if word == 'bf8a0000'][2] @@ -139,6 +189,132 @@ def masked_vertex_red(): GROUP_END = MESH.index('05000006') + 1 PRIMITIVE_EXPORT = MESH.index('f8000941') +WAVE_LOAD_ASM = """s_mov_b32 s40, 0x3e808081 +s_lshl_b32 s41, s6, 8 +s_mov_b32 s42, 6 +v_mov_b32 v7, 0 +s_mov_b64 exec, -1 +v_cmpx_gt_u32_e32 s42, v0 +s_mov_b32 s42, 0 +s_cbranch_execz 4 +s_buffer_load_dword s40, s[16:19], s41 offset:0x1e0 +v_mov_b32 v7, 1.0 +s_waitcnt lgkmcnt(0) +s_mov_b64 exec, -1""" +WAVE_LOAD_PREFIX = 'bea803ff 3e808081 8f298806 beaa0386 7e0e0280 befe04c1 7da8002a beaa0380' +WAVE_LOAD_BODY = 'f4200a08 520001e0 7e0e02f2 bf8cc07f' + + +def wave_load_mesh(prefix=WAVE_LOAD_PREFIX, body=WAVE_LOAD_BODY, *, exports='7e280228 7e2a0307'): + """Insert the scalar load before the count exchange and export its value as vertex red.""" + body = body.split() + before = MESH.index('be8d0308') + wait = MESH.index('bf8c3f70') + return (MESH[:before] + prefix.split() + [branch(0xbf88, 0, len(body) + 1)] + body + ['befe04c1'] + + MESH[before:wait + 1] + exports.split() + MESH[wait + 1:]) + + +WAVE_LOAD_MESH = wave_load_mesh() +WAVE_LOAD_REFUSAL = 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes' +WAVE_LOAD_REFUSALS = ( + ('different EXEC compare', wave_load_mesh(WAVE_LOAD_PREFIX.replace('7da8002a', '7d28002a'))), + ('missing full EXEC reset', wave_load_mesh(WAVE_LOAD_PREFIX.replace('befe04c1', 'befe0404'))), + ('different compare index', wave_load_mesh(WAVE_LOAD_PREFIX.replace('7da8002a', '7da80e2a'))), + ('EXEC write between compare and branch', wave_load_mesh(WAVE_LOAD_PREFIX.replace('beaa0380', 'befe04c1'))), + ('branch into load block', wave_load_mesh('bf840009 ' + WAVE_LOAD_PREFIX)), + ('branch to the EXEC-zero instruction', wave_load_mesh('bf840008 ' + WAVE_LOAD_PREFIX)), + # The block writes s43, which the join reads, but s43 has no value before the block for an empty wave to keep. + ('second live scalar write without an old value', + wave_load_mesh(body=WAVE_LOAD_BODY + ' beab0386', exports='7e280228 7e2a022b')), + ('buffer store', wave_load_mesh(body=WAVE_LOAD_BODY + ' f4600a08 520001e0')), + ('buffer atomic', wave_load_mesh(body=WAVE_LOAD_BODY + ' e0c81000 80040700')), +) +# Blocks that #2660 refused and that the wave block accepts: every scalar instruction of the block runs once for a +# wave with an active lane, so further scalar loads and writes, live or dead after the join, follow the guest. +WAVE_LOAD_ACCEPTED = ( + ('wider SMEM load', wave_load_mesh(body=WAVE_LOAD_BODY.replace('f4200a08', 'f4240a08'))), + ('dead scalar result', wave_load_mesh(exports='7e2a0307')), + # With the adjacent reset replaced by s_nop, the reset that closes the group-index exchange still reaches the + # compare: nothing between them reads or writes EXEC or VCC, and no branch enters that range. + ('full EXEC reset earlier in the region', wave_load_mesh(WAVE_LOAD_PREFIX.replace('befe04c1', 'bf800000'))), +) +# A table load is accepted by the wave block; this one then stops at the register-offset rule of s_load. +WAVE_LOAD_OTHER_REFUSALS = ( + ('ordinary SMEM load with a register offset', wave_load_mesh(body=WAVE_LOAD_BODY.replace('f4200a08', 'f4000a05')), + "s_load with a register offset through ('table', 1)"), +) + +# Two scalar buffer loads (the second at an offset computed in the block), a dead table load, a dead per-lane VCC compare and a scalar +# write between the EXEC reset and the compare. The second load reads the same word as WAVE_LOAD_ASM +# (s45 + 0x1dc = s41 + 0x1e0); the first reads the next word and is dead after the join. +WAVE_BLOCK_ASM = """s_mov_b32 s40, 0x3e808081 +s_lshl_b32 s41, s6, 8 +s_mov_b32 s42, 6 +v_mov_b32 v7, 0 +s_mov_b64 exec, -1 +s_mov_b32 s43, 0 +v_cmpx_gt_u32_e32 s42, v0 +s_mov_b32 s42, 0 +s_cbranch_execz 11 +s_buffer_load_dword s44, s[16:19], s41 offset:0x1e4 +s_load_dwordx4 s[48:51], s[10:11], 0x0 +s_add_u32 s45, s41, 4 +s_waitcnt lgkmcnt(0) +s_buffer_load_dword s40, s[16:19], s45 offset:0x1dc +v_cmp_class_f32_e32 vcc, -1, v7 +v_mov_b32 v7, 1.0 +s_waitcnt lgkmcnt(0) +s_mov_b64 exec, -1""" +WAVE_BLOCK_PREFIX = WAVE_LOAD_PREFIX.replace('befe04c1 7da8002a', 'befe04c1 beab0380 7da8002a') +WAVE_BLOCK_BODY = 'f4200b08 520001e4 f4080c05 fa000000 802d8429 bf8cc07f f4200a08 5a0001dc 7d100ec1 7e0e02f2 bf8cc07f' +WAVE_BLOCK_MESH = wave_load_mesh(WAVE_BLOCK_PREFIX, WAVE_BLOCK_BODY) +WAVE_BLOCK_REFUSALS = ( + ('VCC live at the join', wave_load_mesh(WAVE_BLOCK_PREFIX, WAVE_BLOCK_BODY, exports='7e280228 022a0e80')), + ('src_scc in the block', wave_load_mesh(WAVE_BLOCK_PREFIX, WAVE_BLOCK_BODY + ' beaf03fd')), + ('EXEC copied in the block', wave_load_mesh(WAVE_BLOCK_PREFIX, WAVE_BLOCK_BODY + ' beb0047e')), + ('branch inside the block', wave_load_mesh(WAVE_BLOCK_PREFIX, WAVE_BLOCK_BODY.replace('bf8cc07f', 'bf840000', 1))), + ('branch from outside between the reset and the compare', wave_load_mesh('bf840006 ' + WAVE_BLOCK_PREFIX, + WAVE_BLOCK_BODY)), + # s_cmp_eq_u32 s43, 0; s_cbranch_scc1 to the execz branch: that path never runs the compare. + ('branch from between the reset and the compare past the compare', + wave_load_mesh(WAVE_BLOCK_PREFIX.replace('beab0380', 'beab0380 bf06802b bf850002'), WAVE_BLOCK_BODY)), + ('EXEC write between the reset and the compare', + wave_load_mesh(WAVE_BLOCK_PREFIX.replace('beab0380', 'befe0404'), WAVE_BLOCK_BODY)), +) + + +def count_entry_red(*extra_words): + wait = MESH.index('bf8c3f70') + return MESH[:COUNT] + [ + '7e0e0280', # v_mov_b32_e32 v7, 0 + 'befe04c1', # s_mov_b64 exec, -1 + '7da8000d', # v_cmpx_gt_u32_e32 s13, v0 (the proven thread index) + branch(0xbf88, COUNT + 3, COUNT + 5 + len(extra_words)), # s_cbranch_execz to the first count barrier + '7e0e02f2', # v_mov_b32_e32 v7, 1.0 + ] + list(extra_words) + MESH[COUNT:wait + 1] + [ + '7e280307', # v_mov_b32_e32 v20, v7 + ] + MESH[wait + 1:] + + +COUNT_ENTRY = count_entry_red() +COUNT_ENTRY_LT = mutate('7da8000d', '7da2000d', mesh=COUNT_ENTRY) +# v_mov_b32_e32 v8, 4 before the reset, then v_cmpx_lt_u32_e32 v8, v0. +COUNT_ENTRY_VGPRS = mutate('7da8000d', '7da20108', mesh=COUNT_ENTRY) +COUNT_ENTRY_VGPRS = COUNT_ENTRY_VGPRS[:COUNT + 1] + ['7e100284'] + COUNT_ENTRY_VGPRS[COUNT + 1:] +DEAD_SCALAR = '87288080' # s_and_b32 s40, 0, 0 +COUNT_ENTRY_SCALAR = count_entry_red(DEAD_SCALAR) +COUNT_ENTRY_CASES = ( + ('EXEC-zero branch to the count exchange after GT', COUNT_ENTRY, lambda lane: 255 if lane < 4 else 0), + ('EXEC-zero branch to the count exchange after LT', COUNT_ENTRY_LT, lambda lane: 255 if lane > 4 else 0), + ('EXEC-zero branch to the count exchange after LT with two VGPRs', COUNT_ENTRY_VGPRS, + lambda lane: 255 if lane > 4 else 0), + ('EXEC compare with a defined VGPR other than the thread index', + mutate('7da8000d', '7da80e0d', mesh=COUNT_ENTRY), lambda lane: 255), # s13 > v7 (4 > 0) + ('EXEC-zero branch to the count exchange over dead scalar ALU', COUNT_ENTRY_SCALAR, + lambda lane: 255 if lane < 4 else 0), +) +EXCHANGE_BRANCH_REFUSAL = 'slot 57 mesh: a branch enters or crosses a group-memory exchange' + def joined_vertex_masks(): pos = MESH.index('f80008cf') @@ -190,6 +366,33 @@ def expect(what, got, want): ('a branch into the count exchange', MESH[:COUNT] + [branch(0xbf82, COUNT, COUNT + 2)] + MESH[COUNT:], 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), + ('an EXEC compare with an undefined first VGPR operand', + mutate('7da20108', '7da20101', mesh=COUNT_ENTRY_VGPRS), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC compare with an unmodelled entry VGPR', + mutate('7da8000d', '7da8020d', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('no EXEC reset before the compare', + mutate('befe04c1', 'bf800000', 1, mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC-nonzero branch to the count exchange', + mutate('bf880001', 'bf890001', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC write in the skipped block', + mutate('7e0e02f2', 'befe04c1', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + # Replace v_mov_b32 v20, v7 after the count exchange with v_mov_b32 v20, s40. + ('scalar ALU in the count-entry block with a live SGPR', + mutate('7e280307', '7e280228', mesh=COUNT_ENTRY_SCALAR), EXCHANGE_BRANCH_REFUSAL), + ('scalar ALU writing VCC in the count-entry block', + count_entry_red('876a8080'), EXCHANGE_BRANCH_REFUSAL), # s_and_b32 vcc_lo, 0, 0 + ('a scalar load in the count-entry block', + count_entry_red('f4000a05', 'fa000000'), EXCHANGE_BRANCH_REFUSAL), # s_load_dword s40, s[10:11], 0 + ('a v_cmpx in the skipped block', + mutate('7e0e02f2', '7da8000d', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC-zero branch over the count exchange', + mutate('bf880001', branch(0xbf88, COUNT + 3, POST_COUNT + 5), mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('an EXEC-zero branch past the start of the count exchange', + mutate('bf880001', 'bf880002', mesh=COUNT_ENTRY), EXCHANGE_BRANCH_REFUSAL), + ('a branch that bypasses the EXEC reset', + COUNT_ENTRY[:COUNT] + ['bf850002'] + COUNT_ENTRY[COUNT:], EXCHANGE_BRANCH_REFUSAL), + ('a branch into the skipped count-entry block', + COUNT_ENTRY[:COUNT] + ['bf850004'] + COUNT_ENTRY[COUNT:], EXCHANGE_BRANCH_REFUSAL), ('a branch over the group-index exchange', MESH[:1] + [branch(0xbf82, 1, GROUP_END + 1)] + MESH[1:], 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), # s_branch .post_count replaces s_waitcnt lgkmcnt(0) between the exchanges. @@ -256,9 +459,6 @@ def expect(what, got, want): 'slot 57 mesh: export pos0 is not under exec = -1 narrowed by its output count > thread index'), ('a position export after joining different EXEC masks', joined_vertex_masks(), 'slot 57 mesh: export pos0 is not under exec = -1 narrowed by its output count > thread index'), - # s_mov_b32 s40, 1 replaces the then-arm v_mov inside the s_cbranch_execz range. - ('an EXEC-zero branch that skips a scalar write', mutate('7e0e02f2', 'bea80381', mesh=masked_vertex_red()), - 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), ('EXEC-zero skips a scalar memory load', vertex_red(SHIFT_WORDS.replace('8f2881ff 1fc00000', 'f4000a00 fa000000')), 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), ('a shift with a mask from an unproven thread register', @@ -301,6 +501,58 @@ def expect(what, got, want): ) +def depth_only_controls(): + """A pixel stage that exports only to the null target is published as a depth-only pair.""" + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, DEPTH_PIXEL) + expect('the depth-only pair translates', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('depth-only pair source and manifest', names, ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + # The pixel stage is bound but names no render target: an empty targets line, never 'ps none'. + expect('depth-only manifest stage information', + [line for line in manifest if line.startswith(('params ', 'targets', 'wmask ', 'ps '))], + ['params 1', 'targets ']) + pixel = (Path(tmp) / ('%016x.ps57.hlsl' % key)).read_text() + expect('depth-only pixel stage has no output', ('void main(PSIn i)' in pixel, 'SV_Target' in pixel, + 'SV_Depth' in pixel), (True, False, False)) + expect('depth-only pixel stage keeps the vm discard', pixel.count('discard;'), 1) + # The existing manifest reader (pending_keys): the pair is complete only with both bytecodes. + expect('depth-only manifest is enough in source-only mode', G.pending_keys(tmp, False), []) + part = struct.pack('<4sI4s', b'DXIL', 4, b'test') + bytecode = struct.pack('<4s16sHHIII', b'DXBC', bytes(16), 1, 0, 36 + len(part), 1, 36) + part + os.environ.pop('X2W_FXC') + (Path(tmp) / ('%016x.ms57.cso' % key)).write_bytes(bytecode) + expect('a depth-only pair without its pixel bytecode is pending (unlike ps none)', G.pending_keys(tmp, False), [key]) + pixel_bytecode = Path(tmp) / ('%016x.ps57.cso' % key) + pixel_bytecode.write_bytes(bytecode) + expect('a depth-only pair with both bytecodes is done', G.pending_keys(tmp, False), []) + pixel_bytecode.write_bytes(bytecode[:-1]) + expect('a depth-only pair with truncated pixel bytecode is pending', G.pending_keys(tmp, False), [key]) + os.environ['X2W_FXC'] = '' + for what, pixel, reason in DEPTH_PIXEL_MUTANTS: + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, pixel) + expect(what, result, 'unsupported: ' + reason) + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), ['%016x.fail' % key]) + # A pair whose pixel stage is not the one the key was computed over, in both directions. + for what, keyed, stored in (('a colour stage stored under a depth-only key', DEPTH_PIXEL, PIXEL), + ('a depth-only stage stored under a colour key', PIXEL, DEPTH_PIXEL)): + with tempfile.TemporaryDirectory() as tmp: + key = G.mesh57_key(code(MESH), code(keyed), root()) + for ext, data in (('.root', root()), ('.ps57', code(stored)), ('.m57', code(MESH))): + (Path(tmp) / ('req_%016x%s' % (key, ext))).write_bytes(data) + expect(what, G.translate_request(tmp, key), 'unsupported: slot 57 mesh request key mismatch') + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), ['%016x.fail' % key]) + # The mesh shapes the paired path refuses stay refused, with the same message, next to a depth-only pixel stage. + for what, mesh, reason in REFUSALS: + with tempfile.TemporaryDirectory() as tmp: + expect(what + ' (depth-only pair)', request(tmp, mesh, DEPTH_PIXEL)[1], 'unsupported: ' + reason) + + def controls(): os.environ['X2W_FXC'] = '' # sources and manifest only; the draw mode compiles with tempfile.TemporaryDirectory() as tmp: @@ -326,7 +578,7 @@ def controls(): expect('outputs follow the allocation', all(body.index(line) > body.index(want[-1]) for line in body if 'verts[tid]' in line or 'tris[tid]' in line), True) prefix = MESH[:1] + 'bf008080 bf850001 bf800000 bf800000'.split() + MESH[1:] - for what, mesh, _ in BRANCH_CASES + (('SCC branch before the group-index exchange', prefix, None),): + for what, mesh, _ in BRANCH_CASES + COUNT_ENTRY_CASES + (('SCC branch before the group-index exchange', prefix, None),): with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, mesh) expect(what + ' translates', result, 'ok') @@ -335,6 +587,51 @@ def controls(): expect(what + ' uses forward block dispatch', ('if (pc ==' in text, '[loop]' in text), (True, False)) expect(what + ' guards the position export', bool(re.search( r'if \(exec & 1\) \{[^\n]*o\.pos = [^\n]*mesh_vertex = true;', text)), True) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, WAVE_LOAD_MESH) + expect('pre-exchange wave load translates', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('the branch uses the wave predicate captured at the compare', + ('wave_any = (tid & ~63u) < ' in text, 'pc = (!wave_any) ?' in text), (True, True)) + expect('the scalar buffer read is inside a branched fall-through', + bool(re.search(r'\[branch\] if \(pc == \d+\) \{[^}]*s40 = [^\n]*\.Load\(', text)), True) + # #2643 kept its dead-scalar rule to the count-entry block. A scalar result that no path reads past the join + # is invisible in every other execz block too: lanes that skip never read it, lanes that run it compute the + # wave-uniform value. These two shapes were refusal controls of #2643 and translate now. + for what, mesh in ( + ('dead scalar ALU in a different EXEC-zero block', vertex_red('7e0e02f2 bf880001 ' + DEAD_SCALAR)), + ('an EXEC-zero branch that skips a dead scalar write', + mutate('7e0e02f2', 'bea80381', mesh=masked_vertex_red()))): + expect(what + ' translates', request(tmp, mesh)[1], 'ok') + # v_mov_b32 v8, s50 after the full EXEC restore reads the scalar the skipped arm wrote. + live = masked_vertex_red(MASKED_DEAD_SCALAR.replace('befe04c1', 'befe04c1 7e100232')) + expect('scalar write in a skipped block read after the join', request(tmp, live)[1], + 'unsupported: ' + WAVE_LOAD_REFUSAL) + for what, mesh in WAVE_LOAD_REFUSALS + WAVE_BLOCK_REFUSALS: + expect(what, request(tmp, mesh)[1], 'unsupported: ' + WAVE_LOAD_REFUSAL) + for what, mesh in WAVE_LOAD_ACCEPTED: + expect(what + ' translates', request(tmp, mesh)[1], 'ok') + for what, mesh, reason in WAVE_LOAD_OTHER_REFUSALS: + expect(what, request(tmp, mesh)[1], 'unsupported: ' + reason) + key, result = request(tmp, WAVE_BLOCK_MESH) + expect('pre-exchange wave block translates', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + block = re.search(r'\[branch\] if \(pc == \d+\) \{(.*?)\n \}', text, re.S) + expect('the wave block is one branched fall-through', bool(block) and 'pc = (!wave_any) ?' in text, True) + if block: + expect('both scalar loads and the offset sum run inside it', + (block[1].count('.Load('), bool(re.search(r'\bs45 = ', block[1]))), (2, True)) + # The accepted mesh opcodes cannot produce a lane-varying numeric SGPR here. + # Inject that analysis fact at the Stage boundary to exercise the uniformity refusal. + from unittest.mock import patch + + uniform_source = G.Stage.uniform_source + with patch.object(G.Stage, 'uniform_source', lambda stage, token: token != 's42' and uniform_source(stage, token)): + expect('non-uniform wave load bound', request(tmp, WAVE_LOAD_MESH)[1], 'unsupported: ' + WAVE_LOAD_REFUSAL) + with patch.object(G.Stage, 'uniform_source', lambda stage, token: token != 's41' and uniform_source(stage, token)): + expect('unproven wave load address', request(tmp, WAVE_LOAD_MESH)[1], 'unsupported: ' + WAVE_LOAD_REFUSAL) with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, FORMATTED_MESH) expect('formatted mesh translates', result, 'ok') @@ -384,8 +681,8 @@ def controls(): os.environ['X2W_FXC'] = '' # exp null off, off, off, off done vm; s_endpgm: a pixel stage without a colour output. with tempfile.TemporaryDirectory() as tmp: - expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], - 'unsupported: slot 57 mesh with a depth-only pixel stage is not covered') + expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], 'ok') + depth_only_controls() # The request path refuses a missing s_endpgm earlier; the walk takes the last instruction as the terminator # unread, so the pipeline refuses it too (s_nop in its place). try: @@ -413,6 +710,12 @@ def binary(mc): shift = mesh.replace('v_cmpx_gt_i32 s14, v0', SHIFT_ASM + '\nv_cmpx_gt_i32 s14, v0') shift = shift.replace('exp pos0', 'v_mov_b32 v20, v7\nexp pos0') expect('scalar shift mesh words match llvm-mc', assemble(mc, shift), SHIFT_MESH) + wave_load = mesh.replace('s_mov_b32 s13, s8', WAVE_LOAD_ASM + '\ns_mov_b32 s13, s8') + wave_load = wave_load.replace('exp pos0', 'v_mov_b32 v20, s40\nv_mov_b32 v21, v7\nexp pos0') + expect('pre-exchange wave load words match llvm-mc', assemble(mc, wave_load), WAVE_LOAD_MESH) + wave_block = mesh.replace('s_mov_b32 s13, s8', WAVE_BLOCK_ASM + '\ns_mov_b32 s13, s8') + wave_block = wave_block.replace('exp pos0', 'v_mov_b32 v20, s40\nv_mov_b32 v21, v7\nexp pos0') + expect('pre-exchange wave block words match llvm-mc', assemble(mc, wave_block), WAVE_BLOCK_MESH) # ---- draw: four triangles in a 32x32 target, vertices stored out of order ---------------------- @@ -474,6 +777,91 @@ def rasterise(points, colours, indices, verts, prims): return image +def draw_wave_load(directory, renderer, adapter, mesh=WAVE_LOAD_MESH, label='wave load', dxc=None): + """Draw the mesh and compare. With dxc, also draw a mutant whose block branch skips per lane instead of per + wave: it must match the per-lane image and differ from the correct one.""" + key, result = request(directory, mesh) + expect('pre-exchange %s compiles' % label, result, 'ok') + if result != 'ok': + return 0 + base = Path(directory) / ('%016x' % key) + points, colours, indices = geometry() + # Provoking threads 39 and 5 share the mixed wave; threads 67 and 70 are + # in the empty wave. Every vertex keeps its original low-four-bit slot. + triangles = [tuple(slot + wave for slot in tri) for tri, wave in zip(indices, (32, 0, 64, 64))] + words = [a | b << 10 | c << 20 for a, b, c in triangles] + data = bytearray(buffer(points, colours, words)) + struct.pack_into('<f', data, 480, 1.0) + constants = bytearray(1024) + uds = G.MeshPipeline(code(mesh), code(PIXEL), root()).uds + for slot, count in enumerate((len(triangles), 128)): + struct.pack_into('<I', constants, 4 * uds.index(('rootconst', 0, slot)), count) + + bound, old = 6, 64 + wave_red = {} + reads = [] + for first in range(0, 128, 64): + wave_red[first] = old + if first < bound: + address = 480 + 4 * first + reads.append(address) + wave_red[first] = round(struct.unpack_from('<f', data, address)[0] * 255) + expect('only the mixed wave reads; the empty wave address is past the SRV', + (reads, len(data) + 80 < 480 + 4 * 64, wave_red), ([480], True, {0: 255, 64: 64})) + + def reference(swap): + rendered = list(colours) + for tri in triangles: + for tid in tri: + first, slot = tid & ~63, tid & 15 + red = wave_red[first ^ (64 if swap else 0)] + rendered[slot] = (red, 255 if tid < bound else 0, *colours[slot][2:]) + return rasterise(points, rendered, triangles, 128, len(triangles)) + + correct, swapped = reference(False), reference(True) + different = sum(a != b for a, b in zip(correct, swapped)) + expect('swapping old and loaded red changes every covered pixel', different, + sum(pixel != (0, 0, 0, 255) for pixel in correct)) + expect('the wave load covers pixels', different > 0, True) + path = Path(directory) / 'wave-load.bin' + shader = base.with_suffix('.ms57.cso') + cases = [(label, shader, correct, 0, 0), ('swapped %s selection' % label, shader, swapped, 1, different)] + if dxc: + # Lanes outside EXEC in the mixed wave keep the old red when the block is skipped per lane. + per_lane = reference_per_lane(points, colours, triangles, bound, old, wave_red) + lanes = sum(a != b for a, b in zip(correct, per_lane)) + expect('the per-lane %s mutant changes pixels' % label, lanes > 0, True) + source = base.with_suffix('.ms57.hlsl').read_text() + expect('one wave predicate on the block branch', source.count('pc = (!wave_any) ?'), 1) + mutated = Path(directory) / 'per-lane.hlsl' + mutated.write_text(source.replace('pc = (!wave_any) ?', 'pc = ((exec & 1) == 0) ?')) + mutant = Path(directory) / 'per-lane.cso' + subprocess.run([dxc, '-T', 'ms_6_5', '-E', 'main', '-Fo', mutant, mutated], check=True, capture_output=True) + cases += [('per-lane %s against the wave image' % label, mutant, correct, 1, lanes), + ('per-lane %s against its own image' % label, mutant, per_lane, 0, 0)] + for what, shader, image, status, mismatches in cases: + path.write_bytes(bytes(constants) + bytes(data) + b'\xcd' * 80 + b''.join(map(bytes, image))) + run = subprocess.run([renderer, adapter, '--mesh-indexed', shader, + base.with_suffix('.ps57.cso'), path], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + expect(what, (run.returncode, f'pixels=1024 mismatches={mismatches}' in run.stdout), (status, True)) + print('%s: %d pixels differ from the reference' % (what, mismatches)) + return 0 + + +def reference_per_lane(points, colours, triangles, bound, old, wave_red): + """The image when each lane skips the block by its own EXEC bit: only threads below the bound load.""" + rendered = list(colours) + for tri in triangles: + for tid in tri: + slot = tid & 15 + red = wave_red[tid & ~63] if tid < bound else old + rendered[slot] = (red, 255 if tid < bound else 0, *colours[slot][2:]) + return rasterise(points, rendered, triangles, 128, len(triangles)) + + def publish_request(directory, publisher, adapter): ms, ps = code(MESH), code(PIXEL) (directory / 'ms.bin').write_bytes(ms) @@ -567,7 +955,7 @@ def draw(dxc, renderer, adapter, publisher=None): expect('a reference with one wrong pixel fails', (r.returncode, 'pixels=1024 mismatches=1' in r.stdout, 'Draw reference mismatch' in r.stderr), (1, True, True)) - for what, mesh, red in BRANCH_CASES: + for what, mesh, red in BRANCH_CASES + COUNT_ENTRY_CASES: key, result = request(tmp, mesh) expect(what + ' translates and compiles', result, 'ok') if result != 'ok': @@ -586,6 +974,145 @@ def draw(dxc, renderer, adapter, publisher=None): print(r.stdout + r.stderr) return 77 expect('draw of ' + what, (r.returncode, 'pixels=1024 mismatches=0' in r.stdout), (0, True)) + if publisher is None: + status = draw_wave_load(tmp, renderer, adapter) + if status: + return status + return draw_wave_load(tmp, renderer, adapter, WAVE_BLOCK_MESH, 'wave block', dxc) + return 0 + + +# ---- depth: the depth-only pair drawn twice into a D32 target cleared to 1.0, depth test LESS ------------------ +# Per triangle and draw: (depth, kept). A kept triangle has attribute 0 red 1.0 at its three vertices, a killed one +# 0.25, so the depth-only pixel stage keeps or discards all of its pixels. The four triangles cover: the second draw +# behind the first, the second in front, a first draw killed, both killed. +DEPTH_DRAWS = (((0.25, True), (0.75, True), (0.125, False), (0.5, False)), + ((0.75, True), (0.375, True), (0.625, True), (0.875, False))) + + +def depth_scene(points, indices, draws, honour_kill=True): + """The upload of each draw and the expected colour and depth images (cleared to black and 1.0).""" + uploads, depth = [], [1.0] * (SIDE * SIDE) + words = [a | b << 10 | c << 20 for a, b, c in indices] + for draw in draws: + data = bytearray(buffer(points, [(0, 0, 0, 0)] * 12, words)) + for t, (z, kept) in enumerate(draw): + for slot in indices[t]: + struct.pack_into('<f', data, 16 * slot + 8, z) + struct.pack_into('<f', data, 192 + 16 * slot, 1.0 if kept else 0.25) + if not (kept or not honour_kill): + continue + covered = rasterise(points, [(1, 1, 1, 1)] * 12, [indices[t]], 12, 1) + for i, pixel in enumerate(covered): + if pixel == (1, 1, 1, 1) and z < depth[i]: + depth[i] = z + uploads.append(bytes(data)) + colour = b''.join(bytes((0, 0, 0, 255)) for _ in range(SIDE * SIDE)) + return uploads, colour, b''.join(struct.pack('<f', z) for z in depth) + + +def draw_depth(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, _, indices = geometry() + uploads, colour, depth = depth_scene(points, indices, DEPTH_DRAWS) + _, _, unkilled = depth_scene(points, indices, DEPTH_DRAWS, honour_kill=False) + cleared = struct.pack('<f', 1.0) * (SIDE * SIDE) + pixels = lambda a, b: sum(a[i:i + 4] != b[i:i + 4] for i in range(0, len(a), 4)) + written, killed = pixels(depth, cleared), pixels(depth, unkilled) + assert written > 100 and killed > 50, (written, killed) + # Depth is cleared to the sentinel 1.0 and every drawn depth is below it, so a discarded pixel keeps the sentinel. + covered = pixels(unkilled, cleared) + print('covered %d pixels: %d keep a written depth, %d keep the sentinel only because of the discard, ' + '%d differ from a draw without the discard' % (covered, written, covered - written, killed)) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, DEPTH_PIXEL) + expect('the depth-only pair translates and compiles', result, 'ok') + # The same mesh with a null export and no discard: what a pass without the pixel stage would draw. + bare, bare_result = request(tmp, MESH, 'f8001890 00000000 bf810000'.split()) + expect('the pixel stage without discard translates and compiles', bare_result, 'ok') + if result != 'ok' or bare_result != 'ok': + return 0 + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if p.name.startswith('%016x' % key)) + expect('depth-only compiled files', names, ['.ms57.cso', '.ms57.hlsl', '.ms57.txt', '.ps57.cso', '.ps57.hlsl']) + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + uds = {tuple(fields[2:]): int(fields[1]) for fields in map(str.split, manifest) if fields and fields[0] == 'udsrc'} + constants = bytearray(1024) + struct.pack_into('<I', constants, 4 * uds['rootconst', '0', '0'], len(indices)) + struct.pack_into('<I', constants, 4 * uds['rootconst', '0', '1'], len(points)) + head = b''.join(bytes(constants) + upload for upload in uploads) + b'\xcd' * 160 + path = Path(tmp) / 'depth.bin' + stems = {'depth-only pair': key, 'pixel stage without discard': bare} + # (label, pair, reference depth, depth mismatches). The colour target must stay cleared in every case. + cases = (('baseline', 'depth-only pair', depth, 0), + ('a reference without the depth writes', 'depth-only pair', cleared, written), + ('the discard dropped', 'pixel stage without discard', depth, killed)) + for label, pair, ref_depth, depth_errors in cases: + name = str(Path(tmp) / ('%016x' % stems[pair])) + path.write_bytes(head + colour + ref_depth) + run = subprocess.run([renderer, adapter, '--mesh-depth-pair', name + '.ms57.cso', name + '.ps57.cso', str(path)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + lines = set(run.stdout.splitlines()) + message = 'Depth reference mismatch' if depth_errors else None + want = {'mesh_exports bytes=160 matched=1', 'pixels=1024 mismatches=0', + 'depth_pixels=1024 depth_mismatches=%d' % depth_errors} + clean = ('backend=%s debug_layer=unavailable' % adapter in lines or 'debug_errors=0 debug_warnings=0' in lines) + ok = (run.returncode == int(message is not None) and want <= lines and clean + and (message is None or message in run.stderr)) + print('%s (%s): depth mismatches want %d, exit=%d -> %s' % (label, pair, depth_errors, run.returncode, + 'as expected' if ok else 'UNEXPECTED')) + if not ok or label == 'baseline': + print(run.stdout + run.stderr) + expect('depth draw: ' + label, ok, True) + return 0 + + +def draw_kill_exit(dxc, renderer, adapter): + """The colour pair whose pixel stage leaves through the early exit of a kill, against a CPU reference without + the killed triangles; the same mesh with the pixel stage that does not kill must fail against it.""" + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + kept = [triangle for triangle in indices if colours[triangle[0]][0] / 255 > 0.5] + image, unkilled = rasterise(points, colours, kept, 12, len(kept)), rasterise(points, colours, indices, 12, 4) + killed = sum(a != b for a, b in zip(image, unkilled)) + assert 0 < len(kept) < len(indices) and killed > 50, (len(kept), killed) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, KILL_EXIT_PIXEL) + expect('the kill-exit pair translates and compiles', result, 'ok') + demote, demote_result = request(tmp, MESH, DEMOTE_EXIT_PIXEL) + expect('the demote-exit pair translates and compiles', demote_result, 'ok') + plain, plain_result = request(tmp, MESH, PIXEL) + expect('the pair without the kill translates and compiles', plain_result, 'ok') + if result != 'ok' or demote_result != 'ok' or plain_result != 'ok': + return 0 + uds = G.MeshPipeline(code(MESH), code(KILL_EXIT_PIXEL), root()).uds + constants = bytearray(1024) + struct.pack_into('<I', constants, 4 * uds.index(('rootconst', 0, 0)), len(indices)) + struct.pack_into('<I', constants, 4 * uds.index(('rootconst', 0, 1)), len(points)) + words = [a | b << 10 | c << 20 for a, b, c in indices] + path = Path(tmp) / 'kill.bin' + path.write_bytes(bytes(constants) + buffer(points, colours, words) + b'\xcd' * 80 + + b''.join(bytes(pixel) for pixel in image)) + print('kept %d of %d triangles; %d pixels differ from a draw without the kill' % (len(kept), len(indices), killed)) + for label, stem, mismatches in (('kill-exit pair', key, 0), ('demote-exit pair', demote, 0), + ('the pair without the kill', plain, killed)): + name = str(Path(tmp) / ('%016x' % stem)) + run = subprocess.run([renderer, adapter, '--mesh-indexed', name + '.ms57.cso', name + '.ps57.cso', str(path)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + ok = (run.returncode == int(mismatches > 0) + and 'pixels=1024 mismatches=%d' % mismatches in run.stdout) + print('%s: mismatches want %d, exit=%d -> %s' % (label, mismatches, run.returncode, + 'as expected' if ok else 'UNEXPECTED')) + if not ok: + print(run.stdout + run.stderr) + expect('kill-exit draw: ' + label, ok, True) return 0 @@ -692,6 +1219,10 @@ def main(argv): binary(argv[2]) elif argv[1:2] == ['draw'] and len(argv) == 5: status = draw(*argv[2:]) + elif argv[1:2] == ['depth'] and len(argv) == 5: + status = draw_depth(*argv[2:]) + elif argv[1:2] == ['killexit'] and len(argv) == 5: + status = draw_kill_exit(*argv[2:]) elif argv[1:2] == ['formatted'] and len(argv) == 5: status = draw_formatted(*argv[2:]) elif argv[1:2] == ['shift'] and len(argv) == 5: diff --git a/tests/startup_mubuf_descriptor_check.py b/tests/startup_mubuf_descriptor_check.py index 26f46cb67a..057bd69f47 100644 --- a/tests/startup_mubuf_descriptor_check.py +++ b/tests/startup_mubuf_descriptor_check.py @@ -26,7 +26,7 @@ def check(directory, consumer, backend): args = [consumer, vs, ps, root] subprocess.run(args, env=env, check=True) subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) - manifest, = cache.glob('*.txt') + manifest, = (path for path in cache.glob('*.txt') if path.name != 'revision.txt') text = manifest.read_text(encoding='ascii') assert 'descword3 0' in text and 'srv 0 buf table 0 0' in text, text result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) diff --git a/tests/startup_native_graphics_draw_check.py b/tests/startup_native_graphics_draw_check.py new file mode 100644 index 0000000000..b62230cca7 --- /dev/null +++ b/tests/startup_native_graphics_draw_check.py @@ -0,0 +1,111 @@ +"""Exercise first-use native graphics translation and a fresh-process cache hit.""" +import os +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from native_direct_container_check import patched_pixel, vertex +from startup_stream_draw_check import vop1, vop2 + + +def triangle(): + code = [vop2(0x1a, 1, 129, 0), vop2(0x1b, 1, 130, 1), vop2(0x1b, 2, 130, 0)] + for v in (1, 2): + code.extend([vop1(6, v, 256 + v), vop2(8, v, 244, v), vop2(3, v, 243, v)]) + code.extend([vop1(1, 3, 128), vop1(1, 4, 242), 0xf80008cf, 0x04030201, 0xbf810000]) + return vertex(program=code) + + +def check(folder, consumer, sdk, adapter, compiler): + cache = folder / "cache" + cache.mkdir() + vs, ps, root, pixels = [folder / name for name in ("vs", "ps", "root", "pixels")] + vs.write_bytes(triangle()) + ps.write_bytes(patched_pixel(2, [vop1(1, 0, 128), vop1(1, 1, 242)], export=(0xf800180f, 0x01000001))) + env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk, + X2W_D3D12_DEBUG="1", X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1") + clear = bytes((0, 0, 255, 255)) + red = bytes((255, 0, 0, 255)) + args = [consumer, vs, ps, root, adapter, pixels] + for name, hits in (("cold", "0,0,0"), ("hot", "1,1,1")): + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + if run.returncode == 77: + return 77 + if run.returncode or f"ready=1 cache(frontend,vs,ps)={hits}" not in run.stderr or "-> drawn;" not in run.stderr: + raise RuntimeError(run.stderr[-8000:]) + for line in run.stderr.splitlines(): + if "x2w-d3d12-debug " in line: + assert " sev=0 " not in line and " sev=1 " not in line, line + if "debug layer:" in line: + print(line) + print(run.stdout.strip()) + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + print(f"{adapter} {name}: cache={hits}, 16 red and 16 clear pixels") + # Publish a verified disk pair, then hold back its ready marker until after the first draw. + subprocess.run([compiler, "--watch", sdk, cache, cache, "--once"], check=True, timeout=45) + marker, = cache.glob("req_*.a") + key = marker.stem.removeprefix("req_") + manifest = cache / f"{key}.txt" + published = {p: p.read_bytes() for p in + (manifest, manifest.with_suffix(".vs.cso"), manifest.with_suffix(".ps.cso"))} + published_draw = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert published_draw.returncode == 0 and "-> drawn;" in published_draw.stderr, published_draw.stderr + assert "native graphics " not in published_draw.stderr, published_draw.stderr + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + assert all(path.read_bytes() == expected for path, expected in published.items()) + print(f"{adapter} existing disk pair takes precedence with native enabled") + faults = ( + ("missing DXC", {"X2W_NATIVE_SHADERS": str(folder / "missing-sdk")}, f"native graphics {key} refused:"), + ("manifest", {"X2W_TEST_NATIVE_GRAPHICS_MANIFEST_FAILURE": "1"}, "unsupported manifest version"), + ("root", {"X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE": "1"}, "failed 0x80004005"), + ) + for fault, override, diagnostic in faults: + manifest.rename(str(manifest) + ".pending") + first = Path(str(pixels) + ".first") + first.unlink(missing_ok=True) + pixels.unlink() + fault_env = dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest), X2W_NATIVE_SHADERS_ONLY="0", **override) + run = subprocess.run(args, env=fault_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and diagnostic in run.stderr and "-> drawn;" in run.stderr, run.stderr + assert first.read_bytes() == clear * 32 + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + assert all(path.read_bytes() == expected for path, expected in published.items()) + print(f"{adapter} {fault}: same-process fallback drew 16 red pixels after publication") + ps.write_bytes(patched_pixel(1, [0xffffffff], export=(0xf800180f, 0x01000001))) + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and "refused:" in run.stderr and "-> drawn;" not in run.stderr, run.stderr + assert pixels.read_bytes() == clear * 32 + print("unsupported stage: all 32 pixels retain the clear color") + # The first DWORD is 0.25 in record zero, 1.0 in record one. Its byte-1 window is 0x003e8000. + records = bytearray(64) + struct.pack_into("<f", records, 0, 0.25) + struct.pack_into("<f", records, 16, 1.0) + env["X2W_TEST_FORMATTED_VIEW"] = f"0:1688:0:{records.hex()}" + for index, stride in ((1, 16), (1, 8), (0xffffffff, 16)): + env["X2W_TEST_INDEXED_STRIDE"] = str(stride) + program = [0xbe810380, 0xf4080200, 0xfa000000, vop1(1, 0, 255), index, + 0xe0302000, 0x80020000, vop1(1, 1, 128), vop1(1, 2, 242)] + ps.write_bytes(patched_pixel(len(program), program, table=True, uses=[(0x300, 0, 0, 16, 4)], + export=(0xf800180f, 0x02010100))) + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + for line in run.stderr.splitlines(): + if "x2w-d3d12-debug " in line: + assert " sev=0 " not in line and " sev=1 " not in line, line + image = pixels.read_bytes() + if stride == 8: + assert "needs stride 16, got 8" in run.stderr and "-> drawn;" not in run.stderr, run.stderr[-7000:] + assert image == clear * 32 + else: + assert "-> drawn;" in run.stderr, run.stderr[-7000:] + color = red if index == 1 else bytes((0, 0, 0, 255)) + assert image == (color * 4 + clear * 4) * 4, (image.hex(), run.stderr[-6000:]) + print(f"{adapter} idxbuf index={index:#x} actual stride={stride}: first RGBA {image[:4].hex()}") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as directory: + sys.exit(check(Path(directory), *sys.argv[1:])) diff --git a/tests/startup_null_cause_labels_check.cpp b/tests/startup_null_cause_labels_check.cpp index 0d3811db4b..e9455430f5 100644 --- a/tests/startup_null_cause_labels_check.cpp +++ b/tests/startup_null_cause_labels_check.cpp @@ -10,7 +10,7 @@ namespace { using x2w_local::BindingFacts; int failures, cases; -const char* const labels[] = {"entry", "buffer", "token", "wrapper", "dimension"}; +const char* const labels[] = {"entry", "buffer", "token", "wrapper", "dimension", "ring_full"}; // Facts as the texture binding builds them: from a table, with a readable entry carrying a known // view token for a resource wrapper of the shader's dimension. @@ -68,13 +68,13 @@ int main(int argc, char** argv) std::printf("unknown mutation\n"); return 2; } - const int entry = 0, buffer = swapped ? 2 : 1, token = swapped ? 1 : 2, wrapper = 3, dimension = 4; + const int entry = 0, buffer = swapped ? 2 : 1, token = swapped ? 1 : 2, wrapper = 3, dimension = 4, ring_full = 5; - if (x2w_local::null_cause_count != 5) { - std::printf("FAIL: %d causes, expected 5\n", x2w_local::null_cause_count); + if (x2w_local::null_cause_count != 6) { + std::printf("FAIL: %d causes, expected 6\n", x2w_local::null_cause_count); return 1; } - for (int i = 0; i < 5; ++i) { + for (int i = 0; i < 6; ++i) { ++cases; if (std::strcmp(x2w_local::null_cause_names[i], labels[i]) != 0) { std::printf("FAIL: slot %d named \"%s\", expected \"%s\"\n", i, x2w_local::null_cause_names[i], labels[i]); @@ -101,6 +101,12 @@ int main(int argc, char** argv) f = texture(); f.dimension_matches = false; counted("texture view of another dimension", f, dimension); + f = table_buffer(false); + f.ring_failed = true; + counted("table buffer whose copy found no upload ring space", f, ring_full); + f = table_buffer(true); + f.ring_failed = true; + counted("a ring failure outranks a bound flag only for buffers", f, ring_full); // A frame of bindings in which each cause occurs a different power of two times, so a count // printed under another label changes the line. Valid bindings add nothing. @@ -113,32 +119,34 @@ int main(int argc, char** argv) unknown.token_known = unknown.resource_wrapper = false; no_wrapper.resource_wrapper = false; mismatch.dimension_matches = false; + BindingFacts ring_buffer = table_buffer(false); + ring_buffer.ring_failed = true; const Binding frame[] = { {texture(), 3}, {table_buffer(true), 2}, {unreadable, 1}, {table_buffer(false), 2}, - {unknown, 4}, {no_wrapper, 8}, {mismatch, 16}, + {unknown, 4}, {no_wrapper, 8}, {mismatch, 16}, {ring_buffer, 32}, }; - long total = 0, by_slot[5] = {}; + long total = 0, by_slot[6] = {}; for (const Binding& b : frame) { const int slot = slot_of(b.facts); if (slot == static_cast<int>(x2w_local::NullCause::none)) continue; - if (slot < 0 || slot >= 5) { - std::printf("FAIL: a null binding in slot %d, outside the five printed\n", slot); + if (slot < 0 || slot >= 6) { + std::printf("FAIL: a null binding in slot %d, outside the six printed\n", slot); return 1; } total += b.times; by_slot[slot] += b.times; } // The device's format string, with the slots in the order it passes them. - char line[160]; - std::snprintf(line, sizeof(line), "null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld)", - total, by_slot[0], by_slot[1], by_slot[2], by_slot[3], by_slot[4]); - const char* const expected = swapped ? "null bindings 31 (entry 1, buffer 4, token 2, wrapper 8, dimension 16)" - : "null bindings 31 (entry 1, buffer 2, token 4, wrapper 8, dimension 16)"; + char line[200]; + std::snprintf(line, sizeof(line), "null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld, ring_full %ld)", + total, by_slot[0], by_slot[1], by_slot[2], by_slot[3], by_slot[4], by_slot[5]); + const char* const expected = swapped ? "null bindings 63 (entry 1, buffer 4, token 2, wrapper 8, dimension 16, ring_full 32)" + : "null bindings 63 (entry 1, buffer 2, token 4, wrapper 8, dimension 16, ring_full 32)"; same_text("totals line", line, expected); // The same counts labelled from the header's names. const char* const* n = x2w_local::null_cause_names; - std::snprintf(line, sizeof(line), "null bindings %ld (%s %ld, %s %ld, %s %ld, %s %ld, %s %ld)", total, n[0], by_slot[0], - n[1], by_slot[1], n[2], by_slot[2], n[3], by_slot[3], n[4], by_slot[4]); + std::snprintf(line, sizeof(line), "null bindings %ld (%s %ld, %s %ld, %s %ld, %s %ld, %s %ld, %s %ld)", total, n[0], by_slot[0], + n[1], by_slot[1], n[2], by_slot[2], n[3], by_slot[3], n[4], by_slot[4], n[5], by_slot[5]); same_text("totals line from the header's names", line, expected); if (failures) { diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py new file mode 100644 index 0000000000..a06abb7b75 --- /dev/null +++ b/tests/startup_packed_position_provenance_check.py @@ -0,0 +1,426 @@ +"""Pixel input masks from the captured stream description of the exact pipeline (#1629). + + (no arguments) association controls, pure Python + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + translate the requests below through translate_request, compile the + pixel stage (DXC ps_6_0, and FXC ps_5_1 when given) and draw it with the + #1634 gradient: every pixel must read back its own packed x | (y << 16); + with fxc, also the compiled-result path of a rewritten description + +Two source-built requests share one cache directory. Each has a stream description, req_<key>.psin: + target exports v4; enable 0x8002 (PERSP_CENTER, POS_FIXED_PT) and address 0x8003 (PERSP_SAMPLE allocated + but not enabled). The address mask lays out v0..v1 PERSP_SAMPLE, v2..v3 PERSP_CENTER, v4 the packed + position. Laying out by the enable mask would put the position in v2. + decoy exports v2; enable = address = 0x8002, so its position is v2. +Both draw correctly only when each translation takes the masks of its own description, so no fixed register +and no mask taken from the other description passes. The controls also refuse, by name, a description that +names another pipeline, a stale description whose stage blobs changed, a missing enable or address mask, +contradictory masks (an enabled input not allocated) and a malformed line. + +The masks are part of the request identity (pipeline_key with ps_inputs). In the same cache, pipelines with +the target's exact stage bytes, root signature and input layout but another mask pair are requests of their +own: 0x8003/0x8003 also places the position in v4 and draws the gradient; 0x8002/0x8002 places it in v2, so +the v4 this code reads is not the position and the draw fails at (1,0) as expected. They arrive after the +target's result exists and are translated as new requests, leaving that result untouched. A description +rewritten in place with another pair after its result was published is checked again, refused by name and +its old result withdrawn. The watcher follows the description each translation reads (an RTV variant reads its +source pipeline's): a wrong pair in a base description withdraws the base and its variant, and the corrected +description, newer than their failures, publishes both again without touching the request files. A result +translated with a description records it (<key>.psdep): removing only the base description withdraws the base +and its variant and refuses both by name, while a legacy request that never had a description has no record +and is not checked again. +""" +import os +import re +import struct +import subprocess +import sys +import tempfile +from contextlib import contextmanager +from pathlib import Path + +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, G, compile_hlsl, root_blob + +TARGET = (0x8002, 0x8003) # (enable, address): the packed position in v4 +DECOY = (0x8002, 0x8002) # the packed position in v2 +SAME_V4 = (0x8003, 0x8003) # another valid pair with the packed position in v4 (PERSP_SAMPLE also enabled) + + +def ps_words(reg): + # exp mrt0 vN, vN, vN, vN done vm; s_endpgm (the #1634 fixture's pixel stage) + return struct.pack('<III', 0xf800180f, reg * 0x01010101, 0xbf810000) + + +def put_request(cache, ps, masks=None, line=None): + """Write req_<key>.a/.b/.root for VS_WORDS and `ps` under pipeline_key() with `masks`, and the stream + description: `line` when given, else the line naming that key and `masks` (none without masks).""" + key = G.pipeline_key(VS_WORDS, ps, root_blob(), ps_inputs=masks) + name = cache / ('req_%016x' % key) + for ext, blob in (('.b', ps), ('.root', root_blob()), ('.a', VS_WORDS)): + name.with_suffix(ext).write_bytes(blob) + description = line if line is not None else describe(key, masks) if masks else None + if description is not None: + name.with_suffix('.psin').write_bytes(description.encode('ascii')) + return key + + +def describe(key, masks): + return 'psin1 %016x ena=0x%04x addr=0x%04x\n' % (key, *masks) + + +@contextmanager +def fxc_setting(fxc=''): + """X2W_FXC for the translator: by default the manifest-only path (''), where a published manifest is a + finished result without bytecode; with an fxc path, the compile path.""" + previous = os.environ.get('X2W_FXC') + os.environ['X2W_FXC'] = fxc + try: + yield + finally: + if previous is None: + del os.environ['X2W_FXC'] + else: + os.environ['X2W_FXC'] = previous + + +def pending(cache, fxc=''): + """The keys a later --watch pass would translate (failures already written are skipped).""" + with fxc_setting(fxc): + return G.pending_keys(str(cache), True) + + +def watch_pass(cache): + """One translate_pending pass as --watch runs it, on the manifest-only path.""" + with fxc_setting(): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + + +def translated_ps(cache, key, through_pending=False): + """translate_request with the manifest-only path: the pixel HLSL, or the refusal. With through_pending, a + translate_pending pass (as --pending and --watch run it) translates whatever it finds pending instead.""" + with fxc_setting(): + if through_pending: + G.translate_pending(str(cache), skip_failed=True, jobs=1) + fail = cache / ('%016x.fail' % key) + result = 'ok' if (cache / ('%016x.txt' % key)).is_file() else ( + 'unsupported: ' + fail.read_text().strip() if fail.is_file() else 'not translated') + else: + result = G.translate_request(str(cache), key) + if result != 'ok': + return None, result + return (cache / ('%016x.ps.hlsl' % key)).read_text(), result + + +def packed_line(text): + found = re.findall(r'\bv(\d+) = \(uint\(i\.pos\.x\) & 0xffffu\)', text) + return [int(n) for n in found] + + +def build_pair(cache, target=TARGET, decoy=DECOY): + return put_request(cache, ps_words(4), target), put_request(cache, ps_words(2), decoy) + + +def controls(): + failures = [] + + def check(label, ok): + print(('ok ' if ok else 'FAIL ') + label) + if not ok: + failures.append(label) + + def refused(label, cache, key, reason): + text, result = translated_ps(cache, key) + rows = G.request_refusals(str(cache), key) + check(label, text is None and reason in result and any(reason in r for r, _ in rows)) + + # The translator lays out by the address mask and loads by the enable mask. + pipe = G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=TARGET) + check('distinct masks: position after the allocated PERSP_SAMPLE and PERSP_CENTER pairs (v4)', + pipe.packed_position_vgpr == 4 and pipe.persp_center_vgpr == 2) + pipe = G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=(0x0002, 0x8002)) + check('position allocated but not enabled is not modelled', pipe.packed_position_vgpr is None) + for masks in ((0x8003, 0x8002), (0x8100, 0x8000)): + try: + G.Pipeline(VS_WORDS, ps_words(4), root_blob(), ps_hw_inputs=masks) + except G.Unsupported as err: + check('contradictory masks %04x/%04x refused by name' % masks, + 'contradictory pixel input enable/address masks' in str(err)) + else: + check('contradictory masks %04x/%04x refused by name' % masks, False) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t, d = build_pair(cache) + text, _ = translated_ps(cache, t) + check('target takes its own description: packed position in v4', text is not None and packed_line(text) == [4]) + text, _ = translated_ps(cache, d) + check('decoy takes its own description: packed position in v2', text is not None and packed_line(text) == [2]) + check('refusal report sees no refusal for either request', + G.request_refusals(str(cache), t) == [] and G.request_refusals(str(cache), d) == []) + # An RTV variant reads its source pipeline's description. + request = 'rtv1 %d 28' % t + variant = G.fnv(request.encode('ascii')) + (cache / ('req_%016x.rtv' % variant)).write_text(request, encoding='ascii') + text, _ = translated_ps(cache, variant) + check('RTV variant takes its source pipeline description: v4', text is not None and packed_line(text) == [4]) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4)) + text, _ = translated_ps(cache, t) + check('no captured description: no hardware inputs, position not modelled (today)', + text is not None and packed_line(text) == []) + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t, d = build_pair(cache) + # The decoy's description copied over the target's. + (cache / ('req_%016x.psin' % t)).write_bytes((cache / ('req_%016x.psin' % d)).read_bytes()) + refused('decoy description under the target name refused', cache, t, + 'pixel input description names another pipeline') + # A stale description: the line names the key, but the stored pixel stage changed after capture. + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, TARGET).encode('ascii')) + (cache / ('req_%016x.b' % t)).write_bytes(ps_words(2)) + refused('stale description (stage blob changed) refused', cache, t, + 'pixel input description names another pipeline') + + for label, line, reason in ( + ('missing address mask', 'psin1 {k} ena=0x8002\n', 'pixel input address mask missing from the stream description'), + ('missing enable mask', 'psin1 {k} addr=0x8003\n', 'pixel input enable mask missing from the stream description'), + ('no masks', 'psin1 {k}\n', 'pixel input enable mask missing from the stream description'), + ('contradictory masks', 'psin1 {k} ena=0x8003 addr=0x8002\n', 'contradictory pixel input enable/address masks'), + ('duplicate mask', 'psin1 {k} ena=0x8002 ena=0x8002\n', 'invalid pixel input description'), + ('malformed line', 'psin1 {k} ena=8002 addr=8003\n', 'invalid pixel input description'), + ('unknown version', 'psin2 {k} ena=0x8002 addr=0x8003\n', 'invalid pixel input description'), + ): + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + masks = tuple(int(m, 16) for m in re.findall(r'(?:ena|addr)=(0x[0-9a-f]+)', line)) + masks = masks if len(masks) == 2 else None + t = G.pipeline_key(VS_WORDS, ps_words(4), root_blob(), ps_inputs=masks) + put_request(cache, ps_words(4), masks, line=line.format(k='%016x' % t)) + refused(label + ' refused by name', cache, t, reason) + + # One cache, pipelines with identical stage bytes, root signature and input layout but different masks. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) + check('without a description the key is unchanged', + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-29'))))) + keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] + check('same stages, root and layout with three mask pairs: three request identities', + len(set(keys)) == 3 and bare not in keys + and all(len(list(cache.glob('req_%016x.*' % key))) == 4 for key in keys)) + texts = [translated_ps(cache, key)[0] for key in keys] + # Under the third pair the position is v2, so the v4 this code reads is not the position. + check('same cache: each pipeline takes its own masks (position v4, v4, not v4), each result under its own key', + None not in texts and [packed_line(text) for text in texts] == [[4], [4], []] + and all((cache / ('%016x.txt' % key)).is_file() for key in keys)) + + # A different mask pair for the same stage bytes after a result exists. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4), TARGET) + translated_ps(cache, t, through_pending=True) + published = {ext: (cache / ('%016x%s' % (t, ext))).read_bytes() for ext in ('.txt', '.ps.hlsl')} + w = put_request(cache, ps_words(4), DECOY) + check('another mask pair after the result exists is a pending request of its own', pending(cache) == [w]) + text, _ = translated_ps(cache, w, through_pending=True) + check('it is translated with its own masks (position not v4), the existing result untouched', + text is not None and packed_line(text) == [] + and all((cache / ('%016x%s' % (t, ext))).read_bytes() == data for ext, data in published.items())) + # The target's own description rewritten in place with the other pair, its line still naming the target. + manifest = cache / ('%016x.txt' % t) + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, DECOY).encode('ascii')) + check('a description rewritten after the result is published is checked again', pending(cache) == [t]) + text, result = translated_ps(cache, t, through_pending=True) + check('the rewritten mask pair is refused by name and the old result withdrawn, not reused', + text is None and 'pixel input description names another pipeline' in result and not manifest.is_file()) + check('the refusal is not retried while the request stays the same', pending(cache) == []) + # A description rewritten with the same masks is checked once, then the result counts as done again. + manifest = cache / ('%016x.txt' % w) + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % w)).write_bytes(describe(w, DECOY).encode('ascii')) + first = pending(cache) + text, _ = translated_ps(cache, w, through_pending=True) + check('a description rewritten unchanged is checked once, then done', + first == [w] and text is not None and packed_line(text) == [] and pending(cache) == []) + + # The watcher follows the description each translation reads: an RTV variant depends on its source's. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + t = put_request(cache, ps_words(4), TARGET) + request = 'rtv1 %d 28' % t + v = G.fnv(request.encode('ascii')) + (cache / ('req_%016x.rtv' % v)).write_text(request, encoding='ascii') + for path in cache.glob('req_*'): # captured well before anything below + stamp = path.stat().st_mtime - 1000 + os.utime(path, (stamp, stamp)) + sources = {path: (path.read_bytes(), path.stat().st_mtime_ns) + for path in (cache / ('req_%016x.a' % t), cache / ('req_%016x.rtv' % v))} + watch_pass(cache) + manifests = [cache / ('%016x.txt' % key) for key in (t, v)] + description = cache / ('req_%016x.psin' % t) + check('base and RTV variant published, nothing pending', all(m.is_file() for m in manifests) and pending(cache) == []) + # The base description rewritten with the wrong pair (its line still naming the base), newer than both manifests. + for path in manifests: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, DECOY).encode('ascii')) + check('a wrong pair in the base description queues the base and its RTV variant', pending(cache) == sorted([t, v])) + watch_pass(cache) + fails = [cache / ('%016x.fail' % key) for key in (t, v)] + check('both refused by name and both published results withdrawn', + not any(m.is_file() for m in manifests) and all(f.is_file() for f in fails) + and 'pixel input description names another pipeline' in fails[0].read_text() + and 'RTV variant source key mismatch' in fails[1].read_text()) + check('the refusals are not retried while the description stays the same', pending(cache) == []) + # The valid description restored, newer than both failures. + for path in fails: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, TARGET).encode('ascii')) + check('the restored description, newer than the failures, queues both again', pending(cache) == sorted([t, v])) + watch_pass(cache) + texts = [(cache / ('%016x.ps.hlsl' % key)).read_text() if m.is_file() else '' for key, m in zip((t, v), manifests)] + check('both republished from the restored description (position v4), .a and .rtv untouched', + all(m.is_file() for m in manifests) and [packed_line(text) for text in texts] == [[4], [4]] + and all((path.read_bytes(), path.stat().st_mtime_ns) == state for path, state in sources.items()) + and pending(cache) == []) + # Only the base description removed: both results were translated with it, so both are withdrawn. + records = [cache / ('%016x.psdep' % key) for key in (t, v)] + check('both results record the description line they were translated with', + all(r.is_file() and r.read_text() == describe(t, TARGET) for r in records)) + # The failures of the wrong-pair cycle stay: on the manifest-only path a success does not remove them. + description.unlink() + check('a removed description queues the base and its RTV variant', pending(cache) == sorted([t, v])) + watch_pass(cache) + check('both refused by name as missing their description and both published results withdrawn', + not any(m.is_file() for m in manifests) and all(f.is_file() for f in fails) + and all('pixel input description missing for a request translated with one' in f.read_text() + for f in fails)) + check('the refusals are not retried while the description stays missing', pending(cache) == []) + for path in fails: + if path.is_file(): + stamp = path.stat().st_mtime - 100 + os.utime(path, (stamp, stamp)) + description.write_bytes(describe(t, TARGET).encode('ascii')) + check('the description restored again queues both', pending(cache) == sorted([t, v])) + watch_pass(cache) + check('both republished from the restored description', + all(m.is_file() for m in manifests) and pending(cache) == []) + + # A legacy request that never had a description: no dependency record, and its result stays done. + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) + legacy = put_request(cache, ps_words(4)) + watch_pass(cache) + check('a legacy request publishes without a dependency record and is not checked again', + (cache / ('%016x.txt' % legacy)).is_file() and not (cache / ('%016x.psdep' % legacy)).exists() + and pending(cache) == []) + + # Re-keying a cache keeps both pipelines and their descriptions, each naming its own key. + with tempfile.TemporaryDirectory() as tmp: + old, new = Path(tmp) / 'old', Path(tmp) / 'new' + old.mkdir() + keys = [put_request(old, ps_words(4), masks) for masks in (TARGET, DECOY)] + import io + import shader_cache_rekey + status = shader_cache_rekey.rekey(str(old), str(new), jobs=1, out=io.StringIO()) + check('re-keying keeps both mask pairs as requests with their own descriptions', + status == 0 and all((new / ('req_%016x.psin' % key)).read_bytes() == describe(key, masks).encode('ascii') + for key, masks in zip(keys, (TARGET, DECOY))) + and sorted(p.name for p in new.glob('req_*.psin')) == sorted('req_%016x.psin' % key for key in keys)) + + if failures: + print('%d control(s) failed' % len(failures)) + return 1 + print('controls: masks from the exact pipeline description; decoy, stale, missing and contradictory refused; ' + 'masks in the request identity') + return 0 + + +def draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, '6_0')] + if fxc: + compilers.append(('fxc', fxc, '5_1')) + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + cache = folder / 'cache' + cache.mkdir() + t, d = build_pair(cache) + sources = {} + for label, key in (('target', t), ('decoy', d)): + text, result = translated_ps(cache, key) + assert text is not None, (label, result) + sources[label] = text + # After those results exist, two more pipelines with the target's exact stage bytes, root signature and + # input layout arrive in the same cache: one whose masks also place the position in v4, and one whose + # masks place it in v2 (wrong register for this code). Each is a request of its own and is translated. + same = put_request(cache, ps_words(4), SAME_V4) + wrong = put_request(cache, ps_words(4), DECOY) + assert len({t, d, same, wrong}) == 4 and pending(cache) == sorted([same, wrong]), 'identities' + for label, key in (('same bytes, other masks (v4)', same), ('same bytes, other masks (v2)', wrong)): + text, result = translated_ps(cache, key, through_pending=True) + assert text is not None, (label, result) + sources[label] = text + for kind, compiler, profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs', 'vs_' + profile, folder) + for label, good in (('target', True), ('decoy', True), ('same bytes, other masks (v4)', True), + ('same bytes, other masks (v2)', False)): + ps = compile_hlsl(compiler, kind, sources[label], 'ps', 'ps_' + profile, folder) + run = subprocess.run([renderer, adapter, '--startup-packed-position', vs, ps], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + if good: + assert run.returncode == 0 and 'all 91 packed positions matched' in run.stdout, (label, run.stdout, run.stderr) + else: + assert run.returncode != 0 and 'position mismatch (1,0): expected 00000001 actual 00000000' in run.stderr, (label, run.stderr) + device = [line for line in run.stdout.splitlines() if line.startswith(('backend=', 'adapter=', 'debug_'))] + print(f'{kind} {adapter} {label}: ' + ('91 pixels matched' if good else 'expected mismatch at (1,0)') + + ' [%s]' % '; '.join(device)) + if fxc: + compiled_results(folder / 'compiled', fxc) + return 0 + + +def compiled_results(cache, fxc): + """With bytecode (FXC), an unchanged manifest is not rewritten. A description rewritten unchanged is still + checked once and then done, and one rewritten with another mask pair withdraws the published result.""" + cache.mkdir() + t = put_request(cache, ps_words(4), TARGET) + with fxc_setting(fxc): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + manifest = cache / ('%016x.txt' % t) + assert manifest.is_file() and (cache / ('%016x.ps.cso' % t)).is_file() and pending(cache, fxc) == [], 'compiled' + for masks, done in ((TARGET, True), (DECOY, False)): + stamp = manifest.stat().st_mtime - 100 + os.utime(manifest, (stamp, stamp)) + (cache / ('req_%016x.psin' % t)).write_bytes(describe(t, masks).encode('ascii')) + assert pending(cache, fxc) == [t], ('checked again', masks) + with fxc_setting(fxc): + G.translate_pending(str(cache), skip_failed=True, jobs=1) + assert pending(cache, fxc) == [] and manifest.is_file() == done, ('checked once', masks) + assert 'pixel input description names another pipeline' in (cache / ('%016x.fail' % t)).read_text() + print('fxc compiled result: rewritten description checked once; another mask pair withdraws the result') + + +def main(argv): + if not argv: + return controls() + mode, *args = argv + if mode == 'draw': + status = controls() + return status or draw(*args) + raise SystemExit(__doc__) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tests/startup_pixel_history.cpp b/tests/startup_pixel_history.cpp new file mode 100644 index 0000000000..15afa2572d --- /dev/null +++ b/tests/startup_pixel_history.cpp @@ -0,0 +1,278 @@ +#include <d3d12.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <cstring> +#include <filesystem> +#include <fstream> +#include <string> +#include <vector> + +#include "../src/startup_stubs/pixel_history.h" +#include "desktop_gpu.h" + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; +constexpr UINT width = 4, height = 4; +constexpr float black[4]{0, 0, 0, 0}, red[4]{1, 0, 0, 1}, green[4]{0, 1, 0, 1}, blue[4]{0, 0, 1, 1}; + +ComPtr<ID3DBlob> compile(const char* source, const char* entry, const char* target) +{ + ComPtr<ID3DBlob> code, errors; + const HRESULT hr = D3DCompile(source, std::strlen(source), nullptr, nullptr, nullptr, entry, target, + D3DCOMPILE_ENABLE_STRICTNESS, 0, &code, &errors); + if (FAILED(hr)) { + if (errors) std::fprintf(stderr, "shader %s: %s\n", entry, static_cast<const char*>(errors->GetBufferPointer())); + check(hr, "compile shader"); + } + return code; +} + +ComPtr<ID3D12RootSignature> make_root(ID3D12Device* device) +{ + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameter.Constants.ShaderRegister = 0; + parameter.Constants.Num32BitValues = 4; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_ROOT_SIGNATURE_DESC desc{}; + desc.NumParameters = 1; + desc.pParameters = ¶meter; + ComPtr<ID3DBlob> blob, errors; + check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &errors), "serialize root signature"); + ComPtr<ID3D12RootSignature> root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), + "create root signature"); + return root; +} + +ComPtr<ID3D12PipelineState> make_pipeline(ID3D12Device* device, ID3D12RootSignature* root) +{ + const char* vertex = R"( +struct VsOut { float4 position : SV_Position; }; +VsOut main(uint id : SV_VertexID) { + float2 corner = float2((id << 1) & 2, id & 2); + VsOut vertex; vertex.position = float4(corner * 2.0 - 1.0, 0, 1); return vertex; +})"; + const char* pixel = R"( +cbuffer Color : register(b0) { float4 color; }; +float4 main() : SV_Target { return color; } +)"; + const ComPtr<ID3DBlob> vs = compile(vertex, "main", "vs_5_1"); + const ComPtr<ID3DBlob> ps = compile(pixel, "main", "ps_5_1"); + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root; + desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.DepthStencilState.DepthEnable = FALSE; + desc.DepthStencilState.StencilEnable = FALSE; + desc.SampleMask = UINT_MAX; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = format; + desc.SampleDesc.Count = 1; + ComPtr<ID3D12PipelineState> pipeline; + check(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)), "create pipeline"); + return pipeline; +} + +struct Target { + ComPtr<ID3D12Device> device; + ComPtr<ID3D12Resource> texture, readback; + ComPtr<ID3D12DescriptorHeap> rtv_heap; + D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; +}; + +Target make_target(IDXGIAdapter* adapter) +{ + Target target; + check(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&target.device)), "create device"); + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear{format, {0, 0, 0, 0}}; + check(target.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_RENDER_TARGET, + &clear, IID_PPV_ARGS(&target.texture)), "create target"); + D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + check(target.device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&target.rtv_heap)), "create rtv heap"); + target.rtv = target.rtv_heap->GetCPUDescriptorHandleForHeapStart(); + target.device->CreateRenderTargetView(target.texture.Get(), nullptr, target.rtv); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC readback{D3D12_RESOURCE_DIMENSION_BUFFER, 0, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + check(target.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&target.readback)), + "create readback"); + return target; +} + +void clear_target(Target& target, ComputeCommands& commands) +{ + check(commands.list->Reset(commands.allocator.Get(), nullptr), "reset clear list"); + commands.list->ClearRenderTargetView(target.rtv, black, 0, nullptr); + commands.submit_and_wait(target.device.Get()); +} + +struct Recorded { + int draw{}; + std::uint64_t key{}; + x2w_startup::PixelHistorySample sample{}; +}; + +// One full-screen triangle on a scissored area. After it completes, the chosen texel is copied and +// decoded exactly as the runtime history does. +void record_draw(Target& target, ComputeCommands& commands, ID3D12RootSignature* root, ID3D12PipelineState* pipeline, + const float* color, D3D12_RECT scissor, int draw, std::uint64_t key, Recorded& recorded) +{ + check(commands.list->Reset(commands.allocator.Get(), pipeline), "reset list"); + commands.list->SetGraphicsRootSignature(root); + commands.list->SetPipelineState(pipeline); + commands.list->SetGraphicsRoot32BitConstants(0, 4, color, 0); + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + commands.list->RSSetViewports(1, &viewport); + commands.list->RSSetScissorRects(1, &scissor); + commands.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + commands.list->OMSetRenderTargets(1, &target.rtv, FALSE, nullptr); + commands.list->DrawInstanced(3, 1, 0, 0); + transition(commands.list.Get(), target.texture.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{target.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint.Footprint = {format, 1, 1, 1, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT}; + const D3D12_TEXTURE_COPY_LOCATION from{target.texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + const D3D12_BOX box{1, 1, 0, 2, 2, 1}; + commands.list->CopyTextureRegion(&to, 0, 0, 0, &from, &box); + transition(commands.list.Get(), target.texture.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + commands.submit_and_wait(target.device.Get()); + void* mapped = nullptr; + const D3D12_RANGE read{0, 4}; + check(target.readback->Map(0, &read, &mapped), "map readback"); + recorded.draw = draw; + recorded.key = key; + recorded.sample.draw = draw; + recorded.sample.frame = 7; + recorded.sample.x = 1; + recorded.sample.y = 1; + recorded.sample.key = key; + recorded.sample.count = 3; + recorded.sample.format = format; + if (!x2w_startup::pixel_history_decode(recorded.sample, mapped)) std::fprintf(stderr, "decode failed\n"); + const D3D12_RANGE no_writes{}; + target.readback->Unmap(0, &no_writes); +} + +bool has_rgba(const std::string& line, unsigned r, unsigned g, unsigned b, unsigned a) +{ + char wanted[64]; + std::snprintf(wanted, sizeof(wanted), "rgba=%u,%u,%u,%u", r, g, b, a); + return line.find(wanted) != std::string::npos; +} + +std::string line_for(const std::vector<std::string>& lines, int draw) +{ + char prefix[32]; + std::snprintf(prefix, sizeof(prefix), "draw=%d ", draw); + for (const auto& line : lines) if (line.rfind(prefix, 0) == 0) return line; + return {}; +} +} // namespace + +int main(int argc, char** argv) +{ + const bool hardware = argc >= 2 && std::strcmp(argv[1], "hardware") == 0; + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + if (hardware) { + ComPtr<IDXGIFactory6> factory6; + if (FAILED(factory.As(&factory6))) return 3; + for (UINT i = 0;; ++i) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT found = factory6->EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, + IID_PPV_ARGS(&candidate)); + if (found == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(found)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 77; + } + DXGI_ADAPTER_DESC description{}; + if (FAILED(adapter->GetDesc(&description))) return 3; + std::printf("adapter=%ls vendor=0x%x device=0x%x\n", description.Description, description.VendorId, description.DeviceId); + std::fflush(stdout); + + Target target = make_target(adapter.Get()); + const auto root = make_root(target.device.Get()); + const auto pipeline = make_pipeline(target.device.Get(), root.Get()); + ComputeCommands commands(target.device.Get(), pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + check(commands.list->Close(), "close initial list"); + clear_target(target, commands); + + // Three source-built draws: the first and the third only cover the top-left texel, so the second + // is the only one that changes the watched texel (1, 1). + const D3D12_RECT corner{0, 0, 1, 1}, all{0, 0, width, height}; + std::vector<Recorded> recorded(3); + record_draw(target, commands, root.Get(), pipeline.Get(), red, corner, 1, 0x1111111111111111ull, recorded[0]); + record_draw(target, commands, root.Get(), pipeline.Get(), green, all, 2, 0x2222222222222222ull, recorded[1]); + record_draw(target, commands, root.Get(), pipeline.Get(), blue, corner, 3, 0x3333333333333333ull, recorded[2]); + + std::vector<x2w_startup::PixelHistorySample> samples; + for (const auto& item : recorded) samples.push_back(item.sample); + const auto room = std::filesystem::temp_directory_path() / ("x2w-pixel-history-" + std::to_string(GetCurrentProcessId())); + std::filesystem::create_directories(room); + const std::string path = (room / "pixel_history.txt").string(); + if (!x2w_startup::pixel_history_write(room.string().c_str(), samples.data(), samples.size())) return 4; + std::ifstream input(path); + std::vector<std::string> lines; + for (std::string line; std::getline(input, line);) lines.push_back(line); + const auto first = line_for(lines, 1), second = line_for(lines, 2), third = line_for(lines, 3); + std::printf("draw 1: %s\ndraw 2: %s\ndraw 3: %s\n", first.c_str(), second.c_str(), third.c_str()); + std::fflush(stdout); + const bool first_black = has_rgba(first, 0, 0, 0, 0); + const bool second_green = has_rgba(second, 0, 255, 0, 255); + const bool third_green = has_rgba(third, 0, 255, 0, 255); + const bool second_key = second.find("key=2222222222222222") != std::string::npos && second.find("frame=7") != std::string::npos && + second.find("x=1 y=1") != std::string::npos; + bool ok = first_black && second_green && third_green && second_key; + + // Negative control: without the second draw the watched texel stays black at draw 3. + clear_target(target, commands); + std::vector<Recorded> control(2); + record_draw(target, commands, root.Get(), pipeline.Get(), red, corner, 1, 0x1111111111111111ull, control[0]); + record_draw(target, commands, root.Get(), pipeline.Get(), blue, corner, 3, 0x3333333333333333ull, control[1]); + std::vector<x2w_startup::PixelHistorySample> control_samples; + for (const auto& item : control) control_samples.push_back(item.sample); + if (!x2w_startup::pixel_history_write(room.string().c_str(), control_samples.data(), control_samples.size())) return 4; + std::ifstream control_input(path); + std::vector<std::string> control_lines; + for (std::string line; std::getline(control_input, line);) control_lines.push_back(line); + const auto control_third = line_for(control_lines, 3); + std::printf("control without draw 2: %s\n", control_third.c_str()); + const bool control_has_no_second = line_for(control_lines, 2).empty(); + const bool control_black = has_rgba(control_third, 0, 0, 0, 0); + ok = ok && control_has_no_second && control_black; + std::printf("checks: first_black=%d second_green=%d third_green=%d second_key=%d no_second=%d control_black=%d\n", + first_black, second_green, third_green, second_key, control_has_no_second, control_black); + std::fflush(stdout); + input.close(); + control_input.close(); + std::puts(ok ? "PASS: the history names draw 2; without it the texel stays black" + : "FAIL: pixel history report mismatch"); + std::fflush(stdout); + return ok ? 0 : 1; +} diff --git a/tests/startup_pixel_history_draw_check.py b/tests/startup_pixel_history_draw_check.py new file mode 100644 index 0000000000..71dac37e94 --- /dev/null +++ b/tests/startup_pixel_history_draw_check.py @@ -0,0 +1,112 @@ +"""Exercise the runtime pixel-history hook through the real translated draw path and queue_present (#2843).""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import pixel, vertex + + +def run_case(consumer, backend, vs, ps, root, pixels, env, dump_dir): + run_env = dict(env, X2W_DRAW_DUMP_FRAME="1", X2W_DRAW_DUMP_DIR=str(dump_dir)) + result = subprocess.run([consumer, vs, ps, root, backend, pixels], env=run_env, + capture_output=True, text=True, timeout=60) + print(result.stdout, end="") + for line in result.stderr.splitlines(): + if "debug layer:" in line or "x2w-d3d12-debug " in line or "x2w-draw pixel history:" in line: + print(line) + if backend == "hardware" and result.returncode == 77: + return result + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"draw failed on {backend}: {result.returncode}\n{result.stderr}") + return result + + +def parse_history(path): + lines = path.read_text(encoding="ascii").splitlines() + assert lines and lines[0].startswith("x2w-pixel-history 1 "), lines + return lines + + +def check(directory, consumer, backend): + cache = directory / "cache" + cache.mkdir() + vs, ps, root, pixels = (directory / name for name in ("vs", "ps", "root", "pixels")) + vs.write_bytes(vertex()) + ps.write_bytes(pixel(True)) + + base_env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(cache), X2W_TEST_PIXEL_HISTORY="1") + for name in ("X2W_DRAW_DUMP_PIXEL", "X2W_DRAW_DUMP_FRAME", "X2W_DRAW_DUMP_DIR"): + base_env.pop(name, None) + base_env.setdefault("X2W_D3D12_DEBUG", "0") + + # Publish and translate the green triangle pipeline once, before any draw runs. + subprocess.run([consumer, vs, ps, root], env=base_env, check=True) + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=base_env, check=True) + expected_key = f"{gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()):016x}" + assert int(expected_key, 16) != 0 + + # 1. Watched pixel (3, 2) inside scissor [2, 6) x [1, 3): green (0, 255, 0, 255). + covered_dir = directory / "dump_covered" + covered_dir.mkdir() + res = run_case(consumer, backend, vs, ps, root, pixels, + dict(base_env, X2W_DRAW_DUMP_PIXEL="3,2"), covered_dir) + if backend == "hardware" and res.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + + # Check the target readback itself has distinct origin (0,0)=blue vs (3,2)=green. + raw_pixels = pixels.read_bytes() + assert len(raw_pixels) == 8 * 4 * 4, len(raw_pixels) + assert raw_pixels[0:4] == bytes((0, 0, 255, 255)), raw_pixels[0:4].hex() + texel_3_2 = (2 * 8 + 3) * 4 + assert raw_pixels[texel_3_2:texel_3_2 + 4] == bytes((0, 255, 0, 255)), raw_pixels[texel_3_2:texel_3_2 + 4].hex() + + history_path = covered_dir / "pixel_history.txt" + assert history_path.is_file(), f"missing {history_path}" + lines = parse_history(history_path) + assert lines[0] == "x2w-pixel-history 1 samples=1", lines + assert len(lines) == 2, lines + line = lines[1] + assert re.search(rf"\bdraw=1\b.*\bframe=1\b.*\bx=3 y=2\b.*\bkey={expected_key}\b.*\brgba=0,255,0,255\b", line), line + print(f"{backend} covered (3,2): {line}") + + # 2. Control: target origin (0, 0) lies outside scissor, so its texel stays clear blue (0, 0, 255, 255); + # an origin-copy mutant would report blue at (3, 2) instead of green. + origin_dir = directory / "dump_origin" + origin_dir.mkdir() + run_case(consumer, backend, vs, ps, root, pixels, + dict(base_env, X2W_DRAW_DUMP_PIXEL="0,0"), origin_dir) + origin_lines = parse_history(origin_dir / "pixel_history.txt") + assert len(origin_lines) == 2, origin_lines + assert re.search(rf"\bdraw=1\b.*\bframe=1\b.*\bx=0 y=0\b.*\bkey={expected_key}\b.*\brgba=0,0,255,255\b", + origin_lines[1]), origin_lines[1] + print(f"{backend} origin control (0,0): {origin_lines[1]}") + + # 3. Control: off-target pixel outside the 8x4 target produces no pixel_history.txt sample. + off_dir = directory / "dump_off_target" + off_dir.mkdir() + run_case(consumer, backend, vs, ps, root, pixels, + dict(base_env, X2W_DRAW_DUMP_PIXEL="8,4"), off_dir) + off_history = off_dir / "pixel_history.txt" + assert not off_history.exists() or parse_history(off_history)[0] == "x2w-pixel-history 1 samples=0", off_history.read_text() + print(f"{backend} off-target control (8,4): no sample") + + # 4. Control: without X2W_DRAW_DUMP_PIXEL, no pixel_history.txt is created and full-dump BMP is written. + full_dir = directory / "dump_full" + full_dir.mkdir() + run_case(consumer, backend, vs, ps, root, pixels, base_env, full_dir) + assert not (full_dir / "pixel_history.txt").exists(), "pixel_history.txt written without X2W_DRAW_DUMP_PIXEL" + bmps = sorted(full_dir.glob(f"draw_*_{expected_key}_3.bmp")) + assert len(bmps) == 1 and bmps[0].stat().st_size >= 54 + 8 * 4 * 4, bmps + print(f"{backend} full-dump control: {bmps[0].name} written, no pixel_history.txt") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 7c1c0c4aca..d505024ba2 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -1,14 +1,25 @@ -"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F). +"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F; M200-01 I). The pixel program loads an image descriptor from descriptor table 0, sets the texel address (1, 2) and four distinct binary32 values, stores them with image_store ... dmask:0xf dim:SQ_RSRC_IMG_2D, and exports the same values to mrt0. The words were assembled by hand from the MIMG layout and are decoded back by tools/disasm_rdna2.py here; --llvm-mc reassembles the source and compares the words. +A full-mask 2D-array program stores the same four values at layer 1. The address is x, y and the +layer, and the manifest line is tex2da. A partial mask on that form is refused. + +A second program uses dmask:0x5 (x and z) so VDATA is two registers. The lowering writes only those +components. It does not read the texel. The UAV starts at -1 in every channel, so y and w stay -1. + +A third program draws two pixels in one pass. Both address texel (1, 2). The pixel at x=0 stores channel +x (dmask:0x1, 1.0) and the pixel at x=1 stores channel z (dmask:0x4, 2.0). Both updates must survive. +Writing the second value into y instead of z is the negative control. + Without arguments: translation controls and refusals. With draw: also compile the translation with DXC and draw it through offscreen_check --startup-image-store, which reads every texel of a 4x4 image back. Negative controls: the translator refuses the program when the lowering is removed, and the translated shader with -its store deleted, or with x and y exchanged, leaves texel (1, 2) at its starting value. +its store deleted, or with x and y exchanged, leaves texel (1, 2) at its starting value. A binding that +asks for a typed UAV load is refused before the draw when the format cannot load. The store runs under the lane's exec bit. Two variants put v_cmpx_eq_u32 before the store, so exec is not known at translation time: with 1 == v0 the lane stays on and the texel is written, with 2 == v0 every lane @@ -45,12 +56,65 @@ s_endpgm """ STORE = bytes.fromhex('080f20f000040400') +# dmask:0x5 → VDATA v[4:5] written to channels x then z (same PREFIX: v4=1.0, v5=2.0). +STORE_XZ = bytes.fromhex('080520f000040400') +ARRAY_STORE = bytes.fromhex('280f20f000040400') PREFIX = bytes.fromhex('04040cf4000000fa' '8102007e' '8202027e' 'f202087e' 'f4020a7e' 'ff020c7e00004040' 'f6020e7e' '7fc08cbf') SUFFIX = bytes.fromhex('703f8cbf' '0f1800f804050607' '000081bf') WORDS = PREFIX + STORE + SUFFIX +WORDS_XZ = PREFIX + STORE_XZ + SUFFIX +# Two pixels, one texel. Packed position is v0 (SPI input bit 15). The pixel whose x is 0 stores +# channel x; the pixel whose x is 1 stores channel z. Both write texel (1, 2). +SOURCE_LANES = """\ +v_cmp_eq_u32_e32 0, v0 +v_mov_b32_e32 v2, 1 +v_cndmask_b32_e32 v3, 0, v2 +v_mov_b32_e32 v0, 1 +v_mov_b32_e32 v1, 2 +v_mov_b32_e32 v4, 1.0 +v_mov_b32_e32 v6, 2.0 +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_waitcnt lgkmcnt(0) +v_cmpx_eq_u32_e32 1, v3 +image_store v4, v[0:1], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D +s_mov_b64 exec, -1 +v_cmpx_eq_u32_e32 0, v3 +image_store v6, v[0:1], s[16:23] dmask:0x4 dim:SQ_RSRC_IMG_2D +s_waitcnt vmcnt(0) +exp mrt0 v4, v4, v6, v6 done vm +s_endpgm +""" +WORDS_LANES = bytes.fromhex( + '8000847d' '8102047e' '80040602' '8102007e' '8202027e' 'f202087e' 'f4020c7e' + '04040cf4000000fa' '7fc08cbf' '8106a47d' '080120f000040400' 'c104febe' '8006a47d' + '080420f000060400' '703f8cbf' '0f1800f804040606' '000081bf') +LANE_X = 'if (exec & 1) w0[uint2(v0, v1)].x = asfloat(v4);' +LANE_Z = 'if (exec & 1) w0[uint2(v0, v1)].z = asfloat(v6);' STORE_LINE = 'w0[uint2(v0, v1)] = asfloat(uint4(v4, v5, v6, v7));' +# Init -1: an xz component store leaves the texel at (1.0, -1.0, 2.0, -1.0). No texel read. +SPARSE_LINE = 'w0[uint2(v0, v1)].xz = float2(asfloat(v4), asfloat(v5));' GUARDED_LINE = 'if (exec & 1) ' + STORE_LINE +SPARSE_BITS = ['3f800000', 'bf800000', '40000000', 'bf800000'] # 1.0, -1.0, 2.0, -1.0 +ARRAY_SOURCE = SOURCE.replace( + 'image_store v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D', + 'v_mov_b32 v2, 1\nimage_store v[4:7], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY', +) +ARRAY_STORE_LINE = 'w0[uint3(v0, v1, v2)] = asfloat(uint4(v4, v5, v6, v7));' +ARRAY_GUARDED_LINE = 'if (exec & 1) ' + ARRAY_STORE_LINE + + +def mov_v2_inline(constant): + """v_mov_b32_e32 v2, <constant>: VOP1 opcode 0x01, vdst=2, inline integer 0..64 (0x80 + n).""" + return struct.pack('<I', 0x7e040280 + constant) + + +def array_program(layer): + return PREFIX + mov_v2_inline(layer) + ARRAY_STORE + SUFFIX + + +ARRAY_WORDS = array_program(1) +ARRAY_WORDS_LAST = array_program(3) def cmpx_eq(constant): @@ -61,12 +125,19 @@ def cmpx_eq(constant): EXEC_ON = PREFIX + cmpx_eq(1) + STORE + SUFFIX # v0 is 1: the lane stays active EXEC_OFF = PREFIX + cmpx_eq(2) + STORE + SUFFIX # v0 is 1: every lane is turned off before the store +ARRAY_EXEC_ON = PREFIX + mov_v2_inline(1) + cmpx_eq(1) + ARRAY_STORE + SUFFIX +ARRAY_EXEC_OFF = PREFIX + mov_v2_inline(1) + cmpx_eq(2) + ARRAY_STORE + SUFFIX def translate(words): return G.Pipeline(VS_WORDS, words, root_blob()) +def translate_lanes(words): + # SPI_PS_INPUT bit 15 alone: the packed position occupies v0. + return G.Pipeline(VS_WORDS, words, root_blob(), ps_hw_inputs=(0x8000, 0x8000)) + + def refused(words, *needles): try: translate(words) @@ -106,34 +177,89 @@ def controls(): assert STORE_LINE in translate(with_store(store)).hlsl_ps(), name print('glc, slc, dlc and unorm accepted') + # 2D-array pixel store (#2742): three address registers, RWTexture2DArray<float4>, manifest tex2da. + array_text = D.decode_instruction(ARRAY_STORE, 0)[2] + assert array_text == 'image_store v[4:7], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY', array_text + array_pipe = translate(ARRAY_WORDS) + array_ps, array_manifest = array_pipe.hlsl_ps(), array_pipe.manifest() + assert 'RWTexture2DArray<float4> w0 : register(u0);' in array_ps, array_ps + assert ' ' + ARRAY_STORE_LINE in array_ps, array_ps + assert 'register(t' not in array_ps, array_ps + assert 'uav 0 tex2da table 0 0' in array_manifest and 'srv ' not in array_manifest, array_manifest + assert array_manifest.startswith('x2w-manifest 2\n'), array_manifest + print('array store: %s manifest uav 0 tex2da table 0 0' % ARRAY_STORE_LINE) + # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, - # a partial channel mask and other image dimensions. + # and other image dimensions. cases = (('d16', patched(7, 0x80)), ('a16', patched(7, 0x40)), ('tfe', patched(2, 0x01)), ('lwe', patched(2, 0x02)), ('r128', patched(1, 0x80)), ('reserved', patched(1, 0x40)), ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), - ('SQ_RSRC_IMG_2D_ARRAY', bytes.fromhex('280f20f000040400')), + ('SQ_RSRC_IMG_CUBE', bytes.fromhex('180f20f000040400')), ('SQ_RSRC_IMG_1D', bytes.fromhex('000f20f000040400'))) for name, store in cases: decoded = D.decode_instruction(store, 0)[2] message = refused(with_store(store), 'image_store') print('refused %-20s %s' % (name + ':', message)) assert decoded.startswith('image_store'), decoded - # A partial channel mask, encoded: the decoder sizes VDATA from the mask (v[4:6], v4), so each must be - # refused for the mask itself, which the translator checks before the data registers. - for mask, data in ((0x7, 'v[4:6]'), (0x1, 'v4')): + # 2D-array requires three address registers, a full mask, and still refuses pixel d16. + try: + array_pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY']) + except G.Unsupported as error: + assert 'x, y and layer expected' in str(error), error + else: + raise AssertionError('2D-array store with two address registers was accepted') + try: + array_pipe.ps.op_image_store(['v[4:5]', 'v[0:2]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY', 'd16']) + except G.Unsupported as error: + assert 'modifier d16' in str(error), error + else: + raise AssertionError('pixel 2D-array d16 store was accepted') + try: + array_pipe.ps.op_image_store(['v[4:5]', 'v[0:2]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D_ARRAY']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('2D-array sparse dmask was accepted') + print('refused 2D-array with two address registers, pixel d16 and sparse dmask 0x5') + # Sparse DMASK on a pixel 2D store: selected components only, in VDATA order. The UAV starts at + # -1; dmask:0x5 with v[4:5] = (1.0, 2.0) yields (1, -1, 2, -1) without reading the texel. + decoded_xz = D.decode_instruction(STORE_XZ, 0)[2] + assert decoded_xz == 'image_store v[4:5], v[0:1], s[16:23] dmask:0x5 dim:SQ_RSRC_IMG_2D', decoded_xz + sparse_ps = translate(WORDS_XZ).hlsl_ps() + assert ' ' + SPARSE_LINE in sparse_ps, sparse_ps + assert 't = w0[' not in sparse_ps, sparse_ps + assert 'typedload' not in translate(WORDS_XZ).manifest() + print('sparse dmask 0x5: %s' % SPARSE_LINE) + partial = { + 0x7: 'w0[uint2(v0, v1)].xyz = float3(asfloat(v4), asfloat(v5), asfloat(v6));', + 0x1: 'w0[uint2(v0, v1)].x = asfloat(v4);', + 0x3: 'w0[uint2(v0, v1)].xy = float2(asfloat(v4), asfloat(v5));', + } + for mask, data, count in ((0x7, 'v[4:6]', 3), (0x1, 'v4', 1), (0x3, 'v[4:5]', 2)): store = patched(1, 0, mask) decoded = D.decode_instruction(store, 0)[2] assert decoded.startswith('image_store %s, ' % data) and 'dmask:%#x' % mask in decoded, decoded - message = refused(with_store(store), 'dmask %#x' % mask, 'writes all four channels') - print('refused %-20s %s' % ('dmask %#x:' % mask, message)) - # The same partial mask with four data registers, through the handler: only the mask guard can refuse it. + text = translate(with_store(store)).hlsl_ps() + assert ' ' + partial[mask] in text, (mask, text) + assert 't = w0[' not in text, text + print('sparse dmask %#x accepted (%d channel(s))' % (mask, count)) + # Wrong VGPR count for a sparse mask is refused for the data, not the mask. try: - pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x7', 'dim:SQ_RSRC_IMG_2D']) + pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D']) except G.Unsupported as error: - assert 'dmask 0x7' in str(error) and 'writes all four channels' in str(error), error + assert '2 VGPRs expected' in str(error), error else: - raise AssertionError('a partial dmask with four data registers was accepted') - print('refused dmask 0x7 with four data registers (v[4:7])') + raise AssertionError('dmask 0x5 with four data registers was accepted') + print('refused dmask 0x5 with four data registers (v[4:7])') + # Empty and out-of-range masks still refuse like a full-channel typed store. + for bad in (0x0, 0x10): + try: + pipe.ps.op_image_store(['v4', 'v[0:1]', 's[16:23]'], ['dmask:%#x' % bad, 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('dmask %#x was accepted' % bad) + print('refused dmask 0x0 and 0x10') # Four data registers are required for the full mask: three are refused for the data, not the mask. try: pipe.ps.op_image_store(['v[4:6]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D']) @@ -142,6 +268,17 @@ def controls(): else: raise AssertionError('dmask 0xf with three data registers was accepted') print('refused dmask 0xf with three data registers (v[4:6])') + # Compute still requires the full mask (shared handler; pixel-only sparse). + try: + pipe.ps.kind = 'cs' + pipe.ps.op_image_store(['v[4:5]', 'v[0:1]', 's[16:23]'], ['dmask:0x5', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'writes all four channels' in str(error), error + else: + raise AssertionError('compute sparse dmask was accepted') + finally: + pipe.ps.kind = 'ps' + print('refused compute-stage sparse dmask 0x5') # Mask text that is not an integer is a named refusal, not a ValueError. try: pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xz', 'dim:SQ_RSRC_IMG_2D']) @@ -177,8 +314,37 @@ def controls(): assert ps.count(STORE_LINE) == 1, ps # With exec known (the entry mask) the store is not guarded. assert GUARDED_LINE not in translate(WORDS).hlsl_ps() + for constant, words in ((1, ARRAY_EXEC_ON), (2, ARRAY_EXEC_OFF)): + ps = translate(words).hlsl_ps() + assert ' exec = ((0x%08xu == v0) ? 1u : 0u);' % constant in ps, ps + assert ' ' + ARRAY_GUARDED_LINE in ps, ps + assert ps.count(ARRAY_STORE_LINE) == 1, ps + assert ARRAY_GUARDED_LINE not in array_ps print('exec after v_cmpx: %s' % GUARDED_LINE) + # Same texel, disjoint masks: two invocations write x and z, and neither store reads the texel. + lanes = translate_lanes(WORDS_LANES).hlsl_ps() + assert 'v0 = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' in lanes, lanes + assert ' ' + LANE_X in lanes and ' ' + LANE_Z in lanes, lanes + assert 't = w0[' not in lanes and 'typedload' not in translate_lanes(WORDS_LANES).manifest(), lanes + swapped = lanes.replace(LANE_Z, LANE_Z.replace('.z = asfloat(v6)', '.y = asfloat(v6)')) + assert swapped != lanes and '.z = asfloat(v6)' not in swapped + print('same texel: %s and %s' % (LANE_X, LANE_Z)) + print('control: swapping the z store onto y changes the lowering') + + # A binding that asks for a typed load is refused in pixel_uav_view, before the view is filled. + # The translator does not emit that request for a component store. + draw_inl = (HERE.parent / 'src/startup_stubs/d3d12_draw.inl').read_text(encoding='utf-8') + view = draw_inl.split('const char* pixel_uav_view', 1)[1].split('\nstruct Translation', 1)[0] + assert 'needs_typed_load' in view and 'typed_uav_load_refusal' in view and 'bool array' in view, view + assert view.find('typed_uav_load_refusal') < view.find('out.Format = format'), view + parser = draw_inl.split('const char* read_pixel_uav_line', 1)[1].split('\nbool float_uav_format', 1)[0] + assert 'typedload' in parser and 'needs_typed_load' in parser and 'tex2da' in parser, parser + store_cpp = (HERE / 'startup_image_store.cpp').read_text(encoding='utf-8') + gate = store_cpp.split('check_startup_image_store_typed_load', 1)[1] + assert 'DrawInstanced' not in gate and 'typed_uav_load_refusal' in gate, gate + print('typed UAV load is refused before the view is filled and before any draw') + # Negative control: without the lowering the program is refused as before. lowering = G.Stage.op_image_store del G.Stage.op_image_store @@ -190,9 +356,13 @@ def controls(): def check_binary(llvm_mc): - built = assemble(llvm_mc, SOURCE) - if built != WORDS: - raise AssertionError('assembled %s, recorded %s' % (built.hex(), WORDS.hex())) + for name, source, words in ( + ('full mask', SOURCE, WORDS), + ('2d array', ARRAY_SOURCE, ARRAY_WORDS), + ('same texel', SOURCE_LANES, WORDS_LANES)): + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), words.hex())) print('fixture words match llvm-mc') @@ -208,10 +378,12 @@ def check_draw(dxc, renderer, adapter): directory = Path(tmp) vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) - def draw(text, label, want=expected): + def draw(text, label, want=expected, coverage=None): ps = compile_hlsl(dxc, 'dxc', text, label, 'ps_6_0', directory) - return subprocess.run([renderer, adapter, '--startup-image-store', str(vs), str(ps), '1,2', want], - capture_output=True, text=True) + command = [renderer, adapter, '--startup-image-store', str(vs), str(ps), '1,2', want] + if coverage is not None: + command.append(str(coverage)) + return subprocess.run(command, capture_output=True, text=True) run = draw(source, 'store') sys.stdout.write(run.stdout) @@ -247,6 +419,52 @@ def draw(text, label, want=expected): raise AssertionError('control exec guard removed was not detected\n%s\n%s' % (run.stdout, run.stderr)) print('control exec guard removed: fails as expected (%s)' % mismatch_line(run.stderr)) + # Sparse dmask 0x5: only x and z change; y and w stay at the UAV clear (-1.0). + sparse_want = ','.join(SPARSE_BITS) + sparse_source = translate(WORDS_XZ).hlsl_ps() + assert SPARSE_LINE in sparse_source, sparse_source + run = draw(sparse_source, 'store_xz', sparse_want) + if run.returncode: + raise AssertionError('sparse store draw failed\n%s\n%s' % (run.stdout, run.stderr)) + print('draw sparse dmask 0x5: texel (1, 2) = %s' % sparse_want) + # Control: writing all four channels instead of the selected components must mismatch on y and w. + full_instead = sparse_source.replace(SPARSE_LINE, STORE_LINE) + assert full_instead != sparse_source + run = draw(full_instead, 'sparse_as_full', sparse_want) + needle = 'texel_mismatch x=1 y=2 expected=%s actual=%s' % (sparse_want, expected) + if run.returncode == 0 or needle not in run.stderr: + raise AssertionError('control sparse-as-full was not detected\n%s\n%s' % (run.stdout, run.stderr)) + print('control sparse-as-full: fails as expected (%s)' % mismatch_line(run.stderr)) + + # Two invocations, one draw, one texel, disjoint masks. Both component writes must survive. + lanes = translate_lanes(WORDS_LANES).hlsl_ps() + assert LANE_X in lanes and LANE_Z in lanes, lanes + assert 't = w0[' not in lanes, lanes + run = draw(lanes, 'same_texel', sparse_want, coverage=2) + if run.returncode: + raise AssertionError('same-texel draw failed\n%s\n%s' % (run.stdout, run.stderr)) + print('draw same texel disjoint masks: texel (1, 2) = %s' % sparse_want) + # Negative control: the z store written into y must mismatch. + swapped = lanes.replace(LANE_Z, LANE_Z.replace('.z = asfloat(v6)', '.y = asfloat(v6)')) + assert swapped != lanes and '.z = asfloat(v6)' not in swapped + run = draw(swapped, 'same_texel_y', sparse_want, coverage=2) + swapped_actual = '3f800000,40000000,bf800000,bf800000' # (1, 2, -1, -1) + needle = 'texel_mismatch x=1 y=2 expected=%s actual=%s' % (sparse_want, swapped_actual) + if run.returncode == 0 or needle not in run.stderr: + raise AssertionError('control same-texel channel swap was not detected\n%s\n%s' % (run.stdout, run.stderr)) + print('control same-texel channel swap: fails as expected (%s)' % mismatch_line(run.stderr)) + + refused_load = subprocess.run([renderer, adapter, '--startup-image-store-reject-load'], + capture_output=True, text=True) + if refused_load.returncode == 77: + sys.exit(77) + if refused_load.returncode == 0 or 'typed_uav_load_refused' not in refused_load.stderr: + raise AssertionError('typed UAV load was not refused before the draw\n%s\n%s' % ( + refused_load.stdout, refused_load.stderr)) + if 'image store:' in refused_load.stdout: + raise AssertionError('typed UAV load refusal drew\n%s' % refused_load.stdout) + print('typed UAV load refused before the draw') + def main(): controls() diff --git a/tests/startup_pixel_uav.cpp b/tests/startup_pixel_uav.cpp new file mode 100644 index 0000000000..dbffeb7f5c --- /dev/null +++ b/tests/startup_pixel_uav.cpp @@ -0,0 +1,525 @@ +// X2W_TEST_PIXEL_UAV=<case> (tests/startup_pixel_uav_check.py): a translated pixel program that stores to a +// 2D image (#1996 item F) drawn through d3d12_xs.dll, with the image bound from the title's descriptor table. +// +// Four committed 4x4 textures with two mips each, every word of every texel a distinct sentinel: +// A R32G32B32A32_FLOAT with ALLOW_UNORDERED_ACCESS, B the same, C without the flag, D R32G32B32A32_TYPELESS. +// One shader-visible heap of eight entries: +// 0 UAV of A (explicit 2D view, mip 0) 1 UAV of B (no description: the default view) +// 2 UAV of C (the stand-in skips the desktop call and keeps the title's view) +// 3 UAV of D as R32G32B32A32_UINT 4 left unwritten +// 5 SRV of A 6 UAV of A, mip 1 +// 7 UAV of A as a one-slice 2D array 8 UAV of E, a 4x4 R8G8B8A8_UNORM render target with the flag +// The case names the table bound at root parameter 0 (and, for srv-and-uav, parameter 1); one draw follows. +// The target case binds E as the draw's render target first. +// After the fence every subresource of the four textures is written to <pixels>.uav, and the debug layer's +// errors are counted when it is on. +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <wrl/client.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <string> +#include <vector> + +using Word = std::uint64_t; +Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); + +namespace { +using Microsoft::WRL::ComPtr; +template<class T> Word ptr(T* value) { return reinterpret_cast<Word>(value); } + +constexpr UINT side = 4, mips = 2, textures = 4, array_slices = 6; + +// The sentinel of word c of texel (x, y) of mip m of texture t; tests/startup_pixel_uav_check.py makes the same. +std::uint32_t sentinel(UINT t, UINT m, UINT texel, UINT c) { return 0xc0000000u | (t << 12) | (m << 8) | (texel << 2) | c; } +std::uint32_t array_sentinel(UINT s, UINT m, UINT texel, UINT c) { return 0xd0000000u | (s << 12) | (m << 8) | (texel << 2) | c; } + +struct Fixture { + ID3D12Device* desktop = nullptr; + bool array_mode = false, raw_mode = false; + void* resources[textures]{}; + ComPtr<ID3D12Resource> natives[textures]; + void* array_resources[3]{}; + ComPtr<ID3D12Resource> array_natives[3]; +} fixture; + +ComPtr<ID3D12Resource> native_of(void* guest, void* wrapped) +{ + // The stand-in forwards SetPrivateDataInterface with the desktop object behind its argument. + constexpr GUID key{0x5e1f0b42, 0x2d8c, 0x4f61, {0x9a, 0x37, 0x0c, 0x71, 0x52, 0x88, 0xe4, 0x1d}}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 5, ptr(&key), ptr(wrapped))))) return nullptr; + ComPtr<IUnknown> stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = fixture.desktop->GetPrivateData(key, &bytes, stored.GetAddressOf()); + invoke(guest, 5, ptr(&key), 0); + ComPtr<ID3D12Resource> result; + if (FAILED(read) || FAILED(stored.As(&result))) return nullptr; + return result; +} + +D3D12_RESOURCE_DESC texture_desc(UINT t) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, mips, + t == 3 ? DXGI_FORMAT_R32G32B32A32_TYPELESS : DXGI_FORMAT_R32G32B32A32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, t == 2 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; +} + +D3D12_RESOURCE_DESC array_texture_desc(UINT t) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, array_slices, mips, + t == 2 ? DXGI_FORMAT_R32G32B32A32_TYPELESS : DXGI_FORMAT_R32G32B32A32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, t == 1 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; +} + +struct Copier { + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + bool open(ID3D12Device* device) + { + const D3D12_COMMAND_QUEUE_DESC desc{}; + return SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + bool run() + { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return false; + const ULONGLONG deadline = GetTickCount64() + 10000; + while (fence->GetCompletedValue() < 1 && GetTickCount64() < deadline) Sleep(1); + return fence->GetCompletedValue() == 1; + } +}; + +void barrier(ID3D12GraphicsCommandList* list, 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}; + list->ResourceBarrier(1, &b); +} + +ComPtr<ID3D12Resource> buffer(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + const D3D12_HEAP_PROPERTIES heap{type}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + ComPtr<ID3D12Resource> result; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&result)))) + return nullptr; + return result; +} + +// Fills every subresource of the four textures with its sentinels (to_textures) or copies them all back. +bool copy_all(ID3D12Device* device, bool to_textures, std::vector<std::uint32_t>* words) +{ + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[mips]{}; + UINT64 total = 0; + const auto desc = texture_desc(0); + device->GetCopyableFootprints(&desc, 0, mips, 0, footprints, nullptr, nullptr, &total); + if (!total || total == ~UINT64{0}) return false; + auto staging = buffer(device, to_textures ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_READBACK, total * textures, + to_textures ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST); + Copier copier; + if (!staging || !copier.open(device)) return false; + unsigned char* memory = nullptr; + if (to_textures) { + if (FAILED(staging->Map(0, nullptr, reinterpret_cast<void**>(&memory)))) return false; + for (UINT t = 0; t < textures; ++t) + for (UINT m = 0; m < mips; ++m) { + const UINT n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n; ++x) + for (UINT c = 0; c < 4; ++c) { + const std::uint32_t value = sentinel(t, m, y * n + x, c); + std::memcpy(memory + t * total + footprints[m].Offset + y * footprints[m].Footprint.RowPitch + (x * 4 + c) * 4, + &value, 4); + } + } + staging->Unmap(0, nullptr); + } + for (UINT t = 0; t < textures; ++t) { + auto* texture = fixture.natives[t].Get(); + const auto state = to_textures ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier(copier.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, state); + for (UINT m = 0; m < mips; ++m) { + D3D12_TEXTURE_COPY_LOCATION placed{staging.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed.PlacedFootprint = footprints[m]; + placed.PlacedFootprint.Offset += t * total; + D3D12_TEXTURE_COPY_LOCATION subresource{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + subresource.SubresourceIndex = m; + if (to_textures) copier.list->CopyTextureRegion(&subresource, 0, 0, 0, &placed, nullptr); + else copier.list->CopyTextureRegion(&placed, 0, 0, 0, &subresource, nullptr); + } + barrier(copier.list.Get(), texture, state, D3D12_RESOURCE_STATE_COMMON); + } + if (!copier.run()) return false; + if (to_textures) return true; + if (FAILED(staging->Map(0, nullptr, reinterpret_cast<void**>(&memory)))) return false; + for (UINT t = 0; t < textures; ++t) + for (UINT m = 0; m < mips; ++m) { + const UINT n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n * 4; ++x) { + std::uint32_t value = 0; + std::memcpy(&value, memory + t * total + footprints[m].Offset + y * footprints[m].Footprint.RowPitch + x * 4, 4); + words->push_back(value); + } + } + staging->Unmap(0, nullptr); + return true; +} + +// Fills every subresource of the 6-slice array texture with its sentinels (to_texture) or copies them all back. +bool copy_array(ID3D12Device* device, bool to_texture, std::vector<std::uint32_t>* words) +{ + constexpr UINT subresources = array_slices * mips; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[subresources]{}; + UINT64 total = 0; + const auto desc = array_texture_desc(0); + device->GetCopyableFootprints(&desc, 0, subresources, 0, footprints, nullptr, nullptr, &total); + if (!total || total == ~UINT64{0}) return false; + auto staging = buffer(device, to_texture ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_READBACK, total, + to_texture ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST); + Copier copier; + if (!staging || !copier.open(device)) return false; + unsigned char* memory = nullptr; + if (to_texture) { + if (FAILED(staging->Map(0, nullptr, reinterpret_cast<void**>(&memory)))) return false; + for (UINT s = 0; s < array_slices; ++s) + for (UINT m = 0; m < mips; ++m) { + const UINT sub = s * mips + m, n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n; ++x) + for (UINT c = 0; c < 4; ++c) { + const std::uint32_t value = array_sentinel(s, m, y * n + x, c); + std::memcpy(memory + footprints[sub].Offset + y * footprints[sub].Footprint.RowPitch + (x * 4 + c) * 4, + &value, 4); + } + } + staging->Unmap(0, nullptr); + } + auto* texture = fixture.array_natives[0].Get(); + const auto state = to_texture ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier(copier.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, state); + for (UINT sub = 0; sub < subresources; ++sub) { + D3D12_TEXTURE_COPY_LOCATION placed{staging.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed.PlacedFootprint = footprints[sub]; + D3D12_TEXTURE_COPY_LOCATION subresource{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + subresource.SubresourceIndex = sub; + if (to_texture) copier.list->CopyTextureRegion(&subresource, 0, 0, 0, &placed, nullptr); + else copier.list->CopyTextureRegion(&placed, 0, 0, 0, &subresource, nullptr); + } + barrier(copier.list.Get(), texture, state, D3D12_RESOURCE_STATE_COMMON); + if (!copier.run()) return false; + if (to_texture) return true; + if (FAILED(staging->Map(0, nullptr, reinterpret_cast<void**>(&memory)))) return false; + for (UINT s = 0; s < array_slices; ++s) + for (UINT m = 0; m < mips; ++m) { + const UINT sub = s * mips + m, n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n * 4; ++x) { + std::uint32_t value = 0; + std::memcpy(&value, memory + footprints[sub].Offset + y * footprints[sub].Footprint.RowPitch + x * 4, 4); + words->push_back(value); + } + } + staging->Unmap(0, nullptr); + return true; +} + +// Two 32-DWORD buffers, distinct sentinels, and an explicit view of words 4..19. +bool copy_raw(ID3D12Device* device, bool upload, std::vector<std::uint32_t>* words) +{ + constexpr UINT bytes = 32 * 4; + auto staging = buffer(device, upload ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_READBACK, 2 * bytes, + upload ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST); + Copier copier; + if (!staging || !copier.open(device)) return false; + std::uint32_t* data = nullptr; + if (upload) { + if (FAILED(staging->Map(0, nullptr, reinterpret_cast<void**>(&data)))) return false; + for (UINT i = 0; i < 64; ++i) data[i] = 0xabcd0000u + i; + staging->Unmap(0, nullptr); + } + for (UINT t = 0; t < 2; ++t) { + auto* resource = fixture.natives[t].Get(); + const auto state = upload ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier(copier.list.Get(), resource, D3D12_RESOURCE_STATE_COMMON, state); + if (upload) copier.list->CopyBufferRegion(resource, 0, staging.Get(), t * bytes, bytes); + else copier.list->CopyBufferRegion(staging.Get(), t * bytes, resource, 0, bytes); + barrier(copier.list.Get(), resource, state, D3D12_RESOURCE_STATE_COMMON); + } + if (!copier.run()) return false; + if (upload) return true; + if (FAILED(staging->Map(0, nullptr, reinterpret_cast<void**>(&data)))) return false; + words->assign(data, data + 64); + staging->Unmap(0, nullptr); + return true; +} + +int draw_raw_uavs(ID3D12Device* desktop, void* guest, void* list, const std::string& mode) +{ + D3D12_FEATURE_DATA_SHADER_MODEL shader_model{D3D_SHADER_MODEL_6_6}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &shader_model, sizeof(shader_model))) || + shader_model.HighestShaderModel < D3D_SHADER_MODEL_6_6) { + std::puts("raw pixel UAV: shader model 6.6 unavailable (skip)"); + return 77; + } + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, + const void*, void*, UINT, const void*, REFIID, void**); + const auto create = reinterpret_cast<Create>((*static_cast<void***>(guest))[127]); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + for (UINT t = 0; t < 2; ++t) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 128, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, t == 1 && mode == "raw-no-ua" ? D3D12_RESOURCE_FLAG_NONE : + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + if (FAILED(create(guest, &heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.resources[t])) || !fixture.resources[t]) return 70; + fixture.natives[t] = native_of(guest, fixture.resources[t]); + if (!fixture.natives[t]) return 71; + } + if (!copy_raw(desktop, true, nullptr)) return 72; + struct Extended { D3D12_DESCRIPTOR_HEAP_DESC desc; Word address, bytes; }; + Extended desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* views = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr(&desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&views))))) return 73; + const Word cpu = invoke(views, 9), gpu = invoke(views, 10); + const UINT stride = static_cast<UINT>(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 73; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R32_TYPELESS, D3D12_UAV_DIMENSION_BUFFER}; + view.Buffer.FirstElement = 4; + const bool atomic = mode.rfind("raw-atomic", 0) == 0; + view.Buffer.NumElements = atomic ? 20 : 16; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&view), cpu); + if (mode == "raw-short") view.Buffer.NumElements = 8; + if (mode == "raw-last") view.Buffer.FirstElement = 16; + if (mode == "raw-typed") { view.Format = DXGI_FORMAT_R32_UINT; view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; } + if (mode == "raw-structured") { + view.Format = DXGI_FORMAT_UNKNOWN; view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; view.Buffer.StructureByteStride = 4; + } + if (mode == "raw-srv") { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.NumElements = 32; srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(fixture.resources[1]), ptr(&srv), cpu + stride); + } else if (mode != "raw-missing") { + invoke(guest, 19, ptr(fixture.resources[1]), 0, ptr(&view), cpu + stride); + } + std::printf("raw pixel UAV case %s, title descriptor stride %u\n", mode.c_str(), stride); + invoke(list, 32, 1, ptr(&views)); + if (mode != "raw-no-table") invoke(list, 36, 0, gpu); + if (mode == "raw-atomic-edge") { + const D3D12_RECT scissor{0, 0, 3, 3}; + invoke(list, 22, 1, ptr(&scissor)); + } + invoke(list, 12, 3, 1); + return 0; +} + +ID3D12InfoQueue* debug_messages() +{ + static ComPtr<ID3D12InfoQueue> queue; + if (!queue && fixture.desktop) fixture.desktop->QueryInterface(IID_PPV_ARGS(&queue)); + return queue.Get(); +} +} // namespace + +int draw_pixel_uavs(ID3D12Device* desktop, void* guest, void* list) +{ + char mode[32]{}; + GetEnvironmentVariableA("X2W_TEST_PIXEL_UAV", mode, sizeof(mode)); + const std::string which(mode); + fixture.desktop = desktop; + fixture.raw_mode = which.rfind("raw-", 0) == 0; + if (fixture.raw_mode) return draw_raw_uavs(desktop, guest, list, which); + fixture.array_mode = which.rfind("arr-", 0) == 0; + if (fixture.array_mode) { + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const auto create = reinterpret_cast<Create>((*static_cast<void***>(guest))[127]); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + for (UINT t = 0; t < 3; ++t) { + const auto desc = array_texture_desc(t); + if (FAILED(create(guest, &heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.array_resources[t])) || !fixture.array_resources[t]) + return 70; + fixture.array_natives[t] = native_of(guest, fixture.array_resources[t]); + if (!fixture.array_natives[t]) return 71; + } + const auto plain_desc = texture_desc(0); + if (FAILED(create(guest, &heap, 0, &plain_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.resources[0])) || !fixture.resources[0]) + return 70; + if (!copy_array(desktop, true, nullptr)) return 72; + + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* desc_heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&desc_heap))))) + return 73; + const Word cpu = invoke(desc_heap, 9), gpu = invoke(desc_heap, 10); + const UINT stride = static_cast<UINT>(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 73; + + D3D12_UNORDERED_ACCESS_VIEW_DESC arr_view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY}; + arr_view.Texture2DArray = {0, 1, 4, 0}; // FirstArraySlice=1, ArraySize=4 -> physical slices 1..4 + invoke(guest, 19, ptr(fixture.array_resources[0]), 0, ptr(&arr_view), cpu + 0 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC plain_view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&plain_view), cpu + 1 * stride); + invoke(guest, 19, ptr(fixture.array_resources[0]), 0, 0, cpu + 2 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC mip1 = arr_view; + mip1.Texture2DArray.MipSlice = 1; + invoke(guest, 19, ptr(fixture.array_resources[0]), 0, ptr(&mip1), cpu + 3 * stride); + D3D12_SHADER_RESOURCE_VIEW_DESC arr_srv{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + arr_srv.Texture2DArray = {0, 1, 1, 4, 0, 0.0f}; + invoke(guest, 18, ptr(fixture.array_resources[0]), ptr(&arr_srv), cpu + 4 * stride); + invoke(guest, 19, ptr(fixture.array_resources[1]), 0, ptr(&arr_view), cpu + 5 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC integer = arr_view; + integer.Format = DXGI_FORMAT_R32G32B32A32_UINT; + invoke(guest, 19, ptr(fixture.array_resources[2]), 0, ptr(&integer), cpu + 6 * stride); + + struct Case { const char* name; int entry; int srv_entry; }; + static const Case cases[] = { + {"arr-ok", 0, -1}, {"arr-2d-view", 1, -1}, {"arr-default", 2, -1}, {"arr-mip1", 3, -1}, + {"arr-srv-and-uav", 0, 4}, {"arr-no-ua", 5, -1}, {"arr-uint", 6, -1}, + }; + const Case* chosen = nullptr; + for (const Case& c : cases) + if (which == c.name) chosen = &c; + if (!chosen) return 74; + std::printf("pixel uav case %s: table entry %d, title descriptor stride %u\n", chosen->name, chosen->entry, stride); + invoke(list, 32, 1, ptr(&desc_heap)); + if (chosen->entry >= 0) invoke(list, 36, 0, gpu + Word(chosen->entry) * stride); + if (chosen->srv_entry >= 0) invoke(list, 36, 1, gpu + Word(chosen->srv_entry) * stride); + invoke(list, 12, 3, 1); + return 0; + } + for (UINT t = 0; t < textures; ++t) { + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = texture_desc(t); + const auto create = reinterpret_cast<Create>((*static_cast<void***>(guest))[127]); + if (FAILED(create(guest, &heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.resources[t])) || !fixture.resources[t]) + return 70; + fixture.natives[t] = native_of(guest, fixture.resources[t]); + if (!fixture.natives[t]) return 71; + } + if (!copy_all(desktop, true, nullptr)) return 72; + + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 9, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) + return 73; + const Word cpu = invoke(heap, 9), gpu = invoke(heap, 10); + const UINT stride = static_cast<UINT>(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 73; + + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&view), cpu + 0 * stride); + invoke(guest, 19, ptr(fixture.resources[1]), 0, 0, cpu + 1 * stride); + invoke(guest, 19, ptr(fixture.resources[2]), 0, ptr(&view), cpu + 2 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC integer = view; + integer.Format = DXGI_FORMAT_R32G32B32A32_UINT; + invoke(guest, 19, ptr(fixture.resources[3]), 0, ptr(&integer), cpu + 3 * stride); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(fixture.resources[0]), ptr(&srv), cpu + 5 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC mip1 = view; + mip1.Texture2D.MipSlice = 1; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&mip1), cpu + 6 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC array{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY}; + array.Texture2DArray.ArraySize = 1; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&array), cpu + 7 * stride); + + // E: a 4x4 R8G8B8A8_UNORM texture that is both a render target and writable; entry 8 is its UAV. The target + // case binds it as the draw's render target and names that entry. + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + static void* target = nullptr; + if (FAILED(reinterpret_cast<Create>((*static_cast<void***>(guest))[127])(guest, &default_heap, 0, &target_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, __uuidof(ID3D12Resource), &target)) || !target) + return 70; + D3D12_UNORDERED_ACCESS_VIEW_DESC target_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(target), 0, ptr(&target_view), cpu + 8 * stride); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* rtv_heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, ptr(&rtv_heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&rtv_heap))))) + return 73; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(rtv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC target_rtv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(guest, 20, ptr(target), ptr(&target_rtv), rtv.ptr); + + struct Case { const char* name; int entry; int srv_entry; }; + static const Case cases[] = { + {"a", 0, -1}, {"b", 1, -1}, {"no-ua", 2, -1}, {"uint", 3, -1}, {"missing", 4, -1}, {"srv", 5, -1}, + {"mip1", 6, -1}, {"array", 7, -1}, {"out-of-range", 7, -1}, {"no-table", -1, -1}, {"srv-and-uav", 0, 5}, + {"target", 8, -1}, + }; + const Case* chosen = nullptr; + for (const Case& c : cases) + if (which == c.name) chosen = &c; + if (!chosen) return 74; + std::printf("pixel uav case %s: table entry %d, title descriptor stride %u\n", chosen->name, chosen->entry, stride); + if (which == "target") invoke(list, 50, 1, ptr(&rtv)); + invoke(list, 32, 1, ptr(&heap)); + if (chosen->entry >= 0) invoke(list, 36, 0, gpu + Word(chosen->entry) * stride); + if (chosen->srv_entry >= 0) invoke(list, 36, 1, gpu + Word(chosen->srv_entry) * stride); + invoke(list, 12, 3, 1); + return 0; +} + +// After the fence: every word of every subresource of the four textures, texture by texture, mip by mip, row by +// row, to <pixels>.uav; then the debug layer's error count. +int report_pixel_uavs(const char* pixels) +{ + std::vector<std::uint32_t> words; + const bool copied = fixture.raw_mode ? copy_raw(fixture.desktop, false, &words) : + fixture.array_mode ? copy_array(fixture.desktop, false, &words) : copy_all(fixture.desktop, false, &words); + if (copied) { + std::ofstream out(std::string(pixels) + ".uav", std::ios::binary); + out.write(reinterpret_cast<const char*>(words.data()), static_cast<std::streamsize>(words.size() * 4)); + if (!out) return 76; + } + const HRESULT removed = fixture.desktop->GetDeviceRemovedReason(); + std::printf("device removed reason: 0x%08lx\n", static_cast<unsigned long>(removed)); + auto* messages = debug_messages(); + if (!messages) { + std::printf("debug layer: absent\n"); + return copied ? 0 : 75; + } + UINT errors = 0; + for (UINT64 i = 0; i < messages->GetNumStoredMessages(); ++i) { + SIZE_T size = 0; + if (FAILED(messages->GetMessage(i, nullptr, &size)) || !size) continue; + std::vector<char> storage(size); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (FAILED(messages->GetMessage(i, message, &size)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) continue; + if (++errors <= 8) std::printf("debug layer error id %d: %.300s\n", static_cast<int>(message->ID), message->pDescription); + } + std::printf("debug layer: on, errors: %u\n", errors); + return copied ? 0 : 75; +} diff --git a/tests/startup_pixel_uav_check.py b/tests/startup_pixel_uav_check.py new file mode 100644 index 0000000000..825b049663 --- /dev/null +++ b/tests/startup_pixel_uav_check.py @@ -0,0 +1,369 @@ +"""Bind a translated pixel-stage image store through the runtime (#1996 item F, runtime slice). + +The pixel program is the hand-assembled gfx1013 one of tests/startup_pixel_image_store_check.py: it loads an +image descriptor from table 0, stores 1.0, 2.0, 3.0 and 4.0 at texel (1, 2) and exports the same values. It is +published by startup_stream_consumer, translated by tools/startup/gfx2hlsl.py --pending (manifest line +'uav 0 tex2d table 0 0') and drawn through d3d12_xs.dll with X2W_TEST_PIXEL_UAV=<case> +(tests/startup_pixel_uav.cpp). Each case is its own process. After the fence the fixture writes every word of +both mips of four 4x4 textures (A and B writable, C without ALLOW_UNORDERED_ACCESS, D typeless), each word a +distinct sentinel, and the debug layer's error count when the layer is on. + +Drawn: the table names A (case a) or B (case b, a view without a description). Texel (1, 2) of mip 0 of that +texture holds the four values; every other word of all four textures, both mips, keeps its sentinel. +Refused, each by its logged reason, with every word unchanged and no translated draw: a table entry with no +view, an SRV, a texture without ALLOW_UNORDERED_ACCESS, an integer view, a view of mip 1, a 2D-array view, an +entry outside the bound table, no table at the parameter, the same texture also bound as an SRV of the draw, and +a texture E that is also the draw's render target (bound through list slot 50). +Manifest lines: a view qualifier (float, uint, and the compute line with 'channels 4'), another image kind, +a 'channels' field and a view index out of order are refused when the manifest is loaded. A raw buffer +line naming a texture is refused during view resolution. +Exec: the v_cmpx variants of the program, through the same runtime path: exec on writes the texel, exec off +leaves it. Control: the exec-off shader recompiled with the guard removed from the store must write the texel, +and the check must report it. +""" +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_stream_check import container, gfx2hlsl # noqa: E402 +from startup_stream_draw_check import vertex # noqa: E402 +from startup_pixel_image_store_check import ( # noqa: E402 + ARRAY_EXEC_OFF, ARRAY_EXEC_ON, ARRAY_GUARDED_LINE, ARRAY_STORE_LINE, ARRAY_WORDS, ARRAY_WORDS_LAST, + BITS, EXEC_OFF, EXEC_ON, GUARDED_LINE, STORE_LINE, WORDS, +) + +SIDE, MIPS, TEXTURES, ARRAY_SLICES = 4, 2, 4, 6 +WRITTEN = [int(b, 16) for b in BITS] +CLEAR, WHITE = bytes((0, 0, 255, 255)), bytes((255, 255, 255, 255)) +DRAWN_LINE = 'x2w-draw draw(3, 1, start 0, base 0) pipeline' + +# case: (table entry the fixture binds, texture written or None, reason logged, manifest edit) +CASES = { + 'a': (0, 0, None, None), + 'b': (1, 1, None, None), + 'missing': (4, None, 'uav 0 refused: table entry holds no view', None), + 'srv': (5, None, 'uav 0 refused: table entry is not an unordered-access view', None), + # The device skips a UAV over a resource without ALLOW_UNORDERED_ACCESS and records it as not created, so the draw names the resource. + 'no-ua': (2, None, 'uav 0 refused: resource lacks ALLOW_UNORDERED_ACCESS', None), + 'uint': (3, None, 'uav 0 refused: integer format for a float view', None), + 'mip1': (6, None, 'uav 0 refused: view names a mip other than 0', None), + 'array': (7, None, 'uav 0 refused: view is not a 2D texture view', None), + 'out-of-range': (7, None, 'uav 0 refused: table entry outside the bound table', + ('uav 0 tex2d table 0 0', 'uav 0 tex2d table 0 4096')), + 'no-table': (None, None, 'uav 0 refused: no descriptor table at the parameter', None), + 'srv-and-uav': (0, None, 'uav 0 refused: the texture is also an SRV of this draw', + ('uav 0 tex2d table 0 0', 'uav 0 tex2d table 0 0\nsrv 0 tex2d table 1 0')), + 'target': (8, None, 'uav 0 refused: the texture is also a render or depth target of this draw', None), +} + +# case: (replacement of 'uav 0 tex2d table 0 0', texture written or None, reason logged) +LINES = ( + ('a.float-line', 'uav 0 tex2d float table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.compute-line', 'uav 0 tex2d float table 0 0 channels 4', None, + 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.tex3d-line', 'uav 0 tex3d table 0 0', None, 'uav line refused (only tex2d, tex2da and raw views are bound)'), + ('a.buffer-line', 'uav 0 raw table 0 0', None, 'uav 0 refused: incompatible raw buffer UAV'), + ('a.uint-line', 'uav 0 tex2d uint table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.channels-field', 'uav 0 tex2d table 0 0 channels 4', None, + 'uav line refused (unexpected field after the table offset)'), + ('a.second-view', 'uav 1 tex2d table 0 0', None, 'uav line refused (view index out of order)'), +) + + +ARRAY_CASES = ( + ('arr-2d-view', 'uav 0 refused: view is not a 2D array texture view', None), + ('arr-default', 'uav 0 refused: view is not a 2D array texture view', None), + ('arr-mip1', 'uav 0 refused: view names a mip other than 0', None), + ('arr-srv-and-uav', 'uav 0 refused: the texture is also an SRV of this draw', + ('uav 0 tex2da table 0 0', 'uav 0 tex2da table 0 0\nsrv 0 tex2da table 1 0')), + ('arr-no-ua', 'uav 0 refused: resource lacks ALLOW_UNORDERED_ACCESS', None), + ('arr-uint', 'uav 0 refused: integer format for a float view', None), +) + + +def sentinel(t, m, texel, c): + return 0xc0000000 | t << 12 | m << 8 | texel << 2 | c + + +def array_sentinel(s, m, texel, c): + return 0xd0000000 | s << 12 | m << 8 | texel << 2 | c + + +def expected_array_words(written_slice): + words = [] + for s in range(ARRAY_SLICES): + for m in range(MIPS): + n = SIDE >> m + for texel in range(n * n): + for c in range(4): + hit = s == written_slice and m == 0 and texel == 2 * n + 1 + words.append(WRITTEN[c] if hit else array_sentinel(s, m, texel, c)) + return words + + +def describe_array(index): + for s in range(ARRAY_SLICES): + for m in range(MIPS): + n = SIDE >> m + if index < n * n * 4: + texel, c = divmod(index, 4) + return 'slice %d mip %d texel (%d, %d) word %d' % (s, m, texel % n, texel // n, c) + index -= n * n * 4 + return 'word past the end' + + +def expected_words(written): + words = [] + for t in range(TEXTURES): + for m in range(MIPS): + n = SIDE >> m + for texel in range(n * n): + for c in range(4): + hit = t == written and m == 0 and texel == 2 * n + 1 + words.append(WRITTEN[c] if hit else sentinel(t, m, texel, c)) + return words + + +def describe(index): + """texture, mip, texel and channel of word index of the .uav file.""" + for t in range(TEXTURES): + for m in range(MIPS): + n = SIDE >> m + if index < n * n * 4: + texel, c = divmod(index, 4) + return 'texture %s mip %d texel (%d, %d) word %d' % ('ABCD'[t], m, texel % n, texel // n, c) + index -= n * n * 4 + return 'word past the end' + + +class Program: + """One pixel program published and translated into its own cache.""" + + def __init__(self, directory, consumer, words, env, kind='tex2d'): + self.directory, self.consumer, self.kind = directory, consumer, kind + directory.mkdir() + self.cache = directory / 'cache' + self.cache.mkdir() + self.vs, self.ps, self.root = (directory / name for name in ('vs', 'ps', 'root')) + self.vs.write_bytes(vertex()) + self.ps.write_bytes(container(0, list(struct.unpack('<%dI' % (len(words) // 4), words)))) + publish = dict(env, X2W_SHADER_CACHE=str(self.cache), X2W_TEST_PIXEL_UAV='arr-ok' if kind == 'tex2da' else 'a') + publish.pop('X2W_TEST_DEBUG_LAYER', None) + subprocess.run([consumer, self.vs, self.ps, self.root], env=publish, check=True) + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', self.cache], env=publish, check=True) + self.manifest, = (path for path in self.cache.glob('*.txt') if path.name != 'revision.txt') + lines = self.manifest.read_text(encoding='ascii').splitlines() + assert lines[0] == 'x2w-manifest 2' and ('uav 0 %s table 0 0' % kind) in lines and not any( + line.startswith('srv ') for line in lines), lines + + +def run_case(program, name, env, backend, cache=None): + """Returns (returncode, stdout, trap log, render target bytes, texture words).""" + folder = program.directory / name + folder.mkdir() + output, trap = folder / 'pixels', folder / 'trap.log' + case_env = dict(env, X2W_SHADER_CACHE=str(cache or program.cache), X2W_TEST_PIXEL_UAV=name.split('.')[0], + X2W_TRAP_LOG=str(trap)) + run = subprocess.run([program.consumer, program.vs, program.ps, program.root, backend, output], env=case_env, + capture_output=True, text=True) + if run.returncode == 77 and 'no debug layer: skipped' in run.stdout and 'X2W_TEST_DEBUG_LAYER' in env: + # Rule of the neighbouring fixtures: the debug layer is a condition, not a requirement. + print('%s: no debug layer on this machine, run without it' % name) + shutil.rmtree(folder) + env.pop('X2W_TEST_DEBUG_LAYER') + return run_case(program, name, env, backend, cache) + log = trap.read_text(errors='replace') if trap.exists() else '' + pixels = output.read_bytes() if output.exists() else b'' + uav = Path(str(output) + '.uav') + words = list(struct.unpack('<%dI' % (uav.stat().st_size // 4), uav.read_bytes())) if uav.exists() else [] + return run.returncode, run.stdout + run.stderr, log, pixels, words + + +def verdict(name, result, written, reason, drawn, array=False): + """None when the case holds, otherwise the first difference.""" + returncode, out, log, pixels, words = result + if returncode: + return 'consumer exited %d\n%s' % (returncode, out[-3000:]) + if 'device removed reason: 0x00000000' not in out: + return 'device removed or no report\n%s' % out[-3000:] + if 'debug layer: on' in out and 'debug layer: on, errors: 0' not in out: + return 'debug layer errors\n%s' % out[-3000:] + want = expected_array_words(written) if array else expected_words(written) + if len(words) != len(want): + return '%d texture words read back, expected %d' % (len(words), len(want)) + for i, (got, expected) in enumerate(zip(words, want)): + if got != expected: + return 'texel_mismatch %s: got %08x, expected %08x' % ( + describe_array(i) if array else describe(i), got, expected) + if (DRAWN_LINE in log) != drawn: + return 'translated draw %s' % ('missing' if drawn else 'present although refused') + if reason and reason not in log: + return 'reason "%s" not logged\n%s' % (reason, log[-3000:]) + if drawn is not None and name in ('a', 'b', 'arr-ok'): + rows = [pixels[i:i + 32] for i in range(0, len(pixels), 32)] + want_row = WHITE * 4 + CLEAR * 4 + if len(rows) != 4 or any(row != want_row for row in rows): + return 'render target %s, expected the left half white' % pixels.hex() + if not drawn and pixels != CLEAR * 32: + return 'render target changed by a refused draw: %s' % pixels.hex() + return None + + +def recompile_mutated(program, folder, tag, old, new): + """A copy of the cache whose pixel shader has old replaced with new.""" + cache = folder / tag + shutil.copytree(program.cache, cache) + hlsl, = cache.glob('*.ps.hlsl') + text = hlsl.read_text() + assert old in text, (old, text) + hlsl.write_text(text.replace(old, new)) + fxc = gfx2hlsl.find_fxc() + if not fxc: + return None + cso = hlsl.with_name(hlsl.name.replace('.hlsl', '.cso')) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(cso), str(hlsl)], check=True, + capture_output=True) + return cache + + +def recompile_without_guard(program, folder): + return recompile_mutated(program, folder, 'cache_unguarded', GUARDED_LINE, STORE_LINE) + + +def check(directory, consumer, backend): + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='0', X2W_D3D12_DEVICE_NOOP='1', X2W_TEST_DEBUG_LAYER='1') + if os.environ.get('X2W_PIXEL_UAV_NO_DEBUG') == '1': + env.pop('X2W_TEST_DEBUG_LAYER') + store = Program(directory / 'store', consumer, WORDS, env) + failures = [] + + def expect(program, name, written, reason, drawn, cache=None, array=False): + result = run_case(program, name, env, backend, cache) + if result[0] == 77: + print(result[1]) + sys.exit(77) + problem = verdict(name, result, written, reason, drawn, array=array) + adapter = next((line for line in result[1].splitlines() if line.startswith('adapter=')), '') + layer = next((line for line in result[1].splitlines() if line.startswith('debug layer:')), 'debug layer: ?') + stride = next((line.rsplit(' ', 1)[1] for line in result[1].splitlines() if 'title descriptor stride' in line), '?') + layer += '; descriptor stride ' + stride + if problem: + failures.append('%s: %s' % (name, problem)) + print('FAIL %s: %s' % (name, problem.splitlines()[0])) + for line in result[1].splitlines(): + if line.startswith(('debug layer', 'device removed')): + print(' ' + line) + else: + if array: + what = ('texel (1, 2) of slice %d written, all other words of 6 slices unchanged' % written + if written is not None else 'all 6 slices unchanged') + else: + what = ('texel (1, 2) of texture %s written, every other word unchanged' % 'ABCD'[written] + if written is not None else 'every word unchanged') + print('%-16s %s; %s%s [%s; %s]' % (name + ':', 'drawn' if drawn else 'refused', what, + (' (' + reason + ')') if reason else '', adapter, layer)) + return problem + + for name, (_, written, reason, edit) in CASES.items(): + if edit: + text = store.manifest.read_text(encoding='ascii') + assert edit[0] in text + store.manifest.write_text(text.replace(edit[0], edit[1]), encoding='ascii') + try: + expect(store, name, written, reason, written is not None) + finally: + if edit: + store.manifest.write_text(text, encoding='ascii') + # Other forms of the manifest line, table entry 0: load_translation refuses the translation and nothing is drawn. + text = store.manifest.read_text(encoding='ascii') + for name, replacement, written, reason in LINES: + store.manifest.write_text(text.replace('uav 0 tex2d table 0 0', replacement), encoding='ascii') + try: + expect(store, name, written, reason, written is not None) + finally: + store.manifest.write_text(text, encoding='ascii') + + exec_on = Program(directory / 'exec_on', consumer, EXEC_ON, env) + exec_off = Program(directory / 'exec_off', consumer, EXEC_OFF, env) + for program in (exec_on, exec_off): + assert (' ' + GUARDED_LINE) in next(program.cache.glob('*.ps.hlsl')).read_text() + expect(exec_on, 'a.exec-on', 0, None, True) + expect(exec_off, 'a.exec-off', None, None, True) + # Control: the exec-off shader without the guard writes the texel, and the check above must catch it. + unguarded = recompile_without_guard(exec_off, directory) + if unguarded is None: + print('control exec guard removed: no fxc, not run') + else: + result = run_case(exec_off, 'a.exec-off-unguarded', env, backend, unguarded) + problem = verdict('a', result, None, None, True) + needle = 'texel_mismatch texture A mip 0 texel (1, 2) word 0: got %08x, expected %08x' % (WRITTEN[0], sentinel(0, 0, 9, 0)) + if not problem or not problem.startswith(needle): + failures.append('control exec guard removed was not detected: %s' % problem) + else: + print('control exec guard removed: fails as expected (%s)' % problem) + # 2D-array pixel UAV path (#2742): FirstArraySlice=1, ArraySize=4 -> relative layers 1 and 3 hit physical slices 2 and 4. + arr_mid = Program(directory / 'arr_mid', consumer, ARRAY_WORDS, env, kind='tex2da') + arr_last = Program(directory / 'arr_last', consumer, ARRAY_WORDS_LAST, env, kind='tex2da') + expect(arr_mid, 'arr-ok', 2, None, True, array=True) + expect(arr_last, 'arr-ok.last', 4, None, True, array=True) + wrong_layer = recompile_mutated(arr_mid, directory, 'cache_wrong_layer', + 'uint3(v0, v1, v2)', 'uint3(v0, v1, v2 + 1u)') + if wrong_layer is None: + print('control array wrong layer: no fxc, not run') + else: + result = run_case(arr_mid, 'arr-ok.wrong-layer', env, backend, wrong_layer) + problem = verdict('arr-ok', result, 2, None, True, array=True) + needle = 'texel_mismatch slice 2 mip 0 texel (1, 2) word 0: got %08x, expected %08x' % ( + array_sentinel(2, 0, 9, 0), WRITTEN[0]) + if not problem or not problem.startswith(needle): + failures.append('control array wrong layer was not detected: %s' % problem) + else: + print('control array wrong layer: fails as expected (%s)' % problem) + for name, reason, edit in ARRAY_CASES: + text = arr_mid.manifest.read_text(encoding='ascii') + if edit: + assert edit[0] in text + arr_mid.manifest.write_text(text.replace(edit[0], edit[1]), encoding='ascii') + try: + expect(arr_mid, name, None, reason, False, array=True) + finally: + if edit: + arr_mid.manifest.write_text(text, encoding='ascii') + arr_exec_on = Program(directory / 'arr_exec_on', consumer, ARRAY_EXEC_ON, env, kind='tex2da') + arr_exec_off = Program(directory / 'arr_exec_off', consumer, ARRAY_EXEC_OFF, env, kind='tex2da') + for program in (arr_exec_on, arr_exec_off): + assert (' ' + ARRAY_GUARDED_LINE) in next(program.cache.glob('*.ps.hlsl')).read_text() + expect(arr_exec_on, 'arr-ok.exec-on', 2, None, True, array=True) + expect(arr_exec_off, 'arr-ok.exec-off', None, None, True, array=True) + arr_unguarded = recompile_mutated(arr_exec_off, directory, 'cache_arr_unguarded', + ARRAY_GUARDED_LINE, ARRAY_STORE_LINE) + if arr_unguarded is None: + print('control array exec guard removed: no fxc, not run') + else: + result = run_case(arr_exec_off, 'arr-ok.exec-off-unguarded', env, backend, arr_unguarded) + problem = verdict('arr-ok', result, None, None, True, array=True) + needle = 'texel_mismatch slice 2 mip 0 texel (1, 2) word 0: got %08x, expected %08x' % ( + WRITTEN[0], array_sentinel(2, 0, 9, 0)) + if not problem or not problem.startswith(needle): + failures.append('control array exec guard removed was not detected: %s' % problem) + else: + print('control array exec guard removed: fails as expected (%s)' % problem) + + if failures: + raise SystemExit('\n'.join(failures)) + print('%s: %d cases and the exec/layer controls' % (backend, len(CASES) + len(LINES) + len(ARRAY_CASES) + 6)) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) != 3: + raise SystemExit(__doc__) + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_placed_buffer_range_check.cpp b/tests/startup_placed_buffer_range_check.cpp index 2b395c9456..b5806b6cf0 100644 --- a/tests/startup_placed_buffer_range_check.cpp +++ b/tests/startup_placed_buffer_range_check.cpp @@ -27,6 +27,8 @@ // it. Decisions as above; in addition every placement must be proven without VirtualQuery (a call // count, not a time). The time per placement of the full walk, the bounded walk and the exact // proof is printed. +// 10. allocation_bytes (the unplaced slot 70 path's existing-heap limit): 64 KiB and 256 MiB + 64 KiB +// reservations with only their first page committed, asked at the base and at the last byte. // // --mutate region-only trusts the allocation size without checking that every page is committed: it // passes (exits 0) only if decisions differ in the partly committed cases and nowhere else. @@ -411,6 +413,23 @@ int main(int argc, char** argv) } } + // Case 10: allocation_bytes reports the whole allocation from any address in it, committed or not. + { + const SIZE_T sizes[] = {page, (SIZE_T{256} << 20) + page}; + for (const SIZE_T bytes : sizes) { + auto* block = static_cast<char*>(VirtualAlloc(nullptr, bytes, MEM_RESERVE, PAGE_NOACCESS)); + if (!block || !VirtualAlloc(block, page, MEM_COMMIT, PAGE_READWRITE)) { + setup_fail("cannot reserve the allocation-size block", block); + if (block) VirtualFree(block, 0, MEM_RELEASE); + continue; + } + if (x2w_startup::allocation_bytes(block) != bytes) fail("allocation_bytes at the base", block); + if (x2w_startup::allocation_bytes(block + bytes - 1) != bytes) fail("allocation_bytes at the last byte", block); + VirtualFree(block, 0, MEM_RELEASE); + } + if (x2w_startup::allocation_bytes(nullptr) != 0) fail("allocation_bytes of a null address", nullptr); + } + std::printf("all %llu placements: VirtualQuery calls full walk %llu, measured %llu\n", placements, full_queries, exact_queries); const int total = failures[other] + failures[partial] + failures[cost]; diff --git a/tests/startup_present_composite_warp.cpp b/tests/startup_present_composite_warp.cpp new file mode 100644 index 0000000000..e7e054724b --- /dev/null +++ b/tests/startup_present_composite_warp.cpp @@ -0,0 +1,481 @@ +// Pixel readback of the presented-plane composite on WARP (docs/startup-runtime.md#presented-planes). +// Source-built planes go through the code the output window uses: synthetic 0x48-byte plane records +// read by present_plane_resource, the order from composite_steps (present_planes.h), and the draws of +// PlaneCompositor (plane_compositor.h) into a 64 x 32 RGBA8 target that is read back. +// +// Contract checked: the bottom plane is drawn opaque, its alpha ignored; each later plane is blended +// over the result in plane order, colour = src * a + dst * (1 - a); the target alpha stays 255; +// repeats of a surface and planes whose record has no readable resource are left out. +// +// Cases: +// baseline one plane of four colours, one cell with alpha 0, shown as is. +// stacked black opaque plane 0; plane 1 with a fully transparent cell, a half-transparent cell, +// a nearly transparent cell (alpha 5) and an opaque cell; plane 2 with an opaque cell, a +// cell blended over plane 1's opaque cell (order) and transparent elsewhere. +// skipped plane 0 black, plane 1 as above, plane 2 the same surface as plane 1, plane 3 a record +// with no resource: the same picture as plane 0 and 1 alone. +// --control runs the same cases and then removes the overlay: stacked composited from the black +// plane 0 alone. It prints "control ok:" and exits 0 only when the baseline and stacked cases matched, +// every fence completed without device removal, and the overlay-free result is black and differs from +// the stacked expectation in exactly the six cells the overlays draw. A setup failure, a missing +// fence, device removal or any other difference prints FAIL and exits 1. +// usage: startup_present_composite_warp [--control] (exit 77 when no WARP adapter is available) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include "startup_stubs/plane_compositor.h" +#include "startup_stubs/present_planes.h" + +#include <d3d12.h> +#include <dxgi1_4.h> + +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <vector> + +namespace { + +int failures = 0; +void fail(const char* format, const char* a, unsigned b, unsigned c, const unsigned char* got, const unsigned char* want) +{ + ++failures; + std::printf(format, a, b, c, got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]); +} + +constexpr UINT width = 64, height = 32; +constexpr UINT columns = 4, rows = 2; // cells of 16 x 16 texels +constexpr UINT cell_w = width / columns, cell_h = height / rows; + +struct Rgba { + unsigned char r, g, b, a; +}; +// A plane picture: one colour per cell, row-major. +using Cells = Rgba[rows][columns]; + +struct Gpu { + ID3D12Device* device = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + + // Executes the list and waits for its fence. A list that does not close or execute, a fence that + // does not reach the value in time, or one that reports device removal (UINT64_MAX) is a failure. + bool run() + { + const HRESULT closed = list->Close(); + if (FAILED(closed)) { + ++failures; + std::printf("FAIL: command list close 0x%08lx\n", static_cast<unsigned long>(closed)); + return false; + } + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + const HRESULT signalled = queue->Signal(fence, ++value); + if (SUCCEEDED(signalled) && fence->GetCompletedValue() < value && SUCCEEDED(fence->SetEventOnCompletion(value, event))) + WaitForSingleObject(event, 10000); + const UINT64 completed = fence->GetCompletedValue(); + if (FAILED(signalled) || completed == UINT64_MAX || completed < value) { + ++failures; + std::printf("FAIL: fence %llu not completed (completed %llu, signal 0x%08lx)\n", static_cast<unsigned long long>(value), + static_cast<unsigned long long>(completed), static_cast<unsigned long>(signalled)); + return false; + } + ++fences; + allocator->Reset(); + list->Reset(allocator, nullptr); + return true; + } + unsigned fences = 0; // fences that completed +}; + +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + 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 = from; + b.Transition.StateAfter = to; + list->ResourceBarrier(1, &b); +} + +D3D12_RESOURCE_DESC texture_desc(D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +ID3D12Resource* buffer(Gpu& gpu, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + 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; + ID3D12Resource* out = nullptr; + gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&out)); + return out; +} + +// A plane surface holding `cells`, left in COMMON as the compositor expects. +ID3D12Resource* plane(Gpu& gpu, const Cells& cells) +{ + const D3D12_RESOURCE_DESC desc = texture_desc(D3D12_RESOURCE_FLAG_NONE); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + ID3D12Resource* texture = nullptr; + if (FAILED(gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&texture)))) + return nullptr; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + gpu.device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + ID3D12Resource* upload = buffer(gpu, D3D12_HEAP_TYPE_UPLOAD, total, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + upload->Map(0, nullptr, &mapped); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const Rgba& c = cells[y / cell_h][x / cell_w]; + unsigned char* t = static_cast<unsigned char*>(mapped) + footprint.Offset + std::size_t{y} * footprint.Footprint.RowPitch + x * 4; + t[0] = c.r, t[1] = c.g, t[2] = c.b, t[3] = c.a; + } + upload->Unmap(0, nullptr); + barrier(gpu.list, texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = texture; + to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + from.pResource = upload; + from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + from.PlacedFootprint = footprint; + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + barrier(gpu.list, texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + const bool ran = gpu.run(); + upload->Release(); + if (!ran) { + texture->Release(); + return nullptr; + } + return texture; +} + +// Plane records as a console present passes them: 0x48 bytes each, +0x08 the resource count and +// +0x10 a pointer to the resource array. A null surface gives a record with no resource. +struct Records { + alignas(8) unsigned char bytes[4 * x2w_startup::present_plane_stride] = {}; + std::uint64_t arrays[4][1] = {}; + explicit Records(ID3D12Resource* const* surfaces, unsigned count) + { + for (unsigned i = 0; i < count; ++i) { + unsigned char* record = bytes + i * x2w_startup::present_plane_stride; + const std::uint64_t token = 7, resources = surfaces[i] ? 1 : 0; + arrays[i][0] = reinterpret_cast<std::uint64_t>(surfaces[i]); + const std::uint64_t pointer = reinterpret_cast<std::uint64_t>(arrays[i]); + std::memcpy(record + 0x00, &token, 8); + std::memcpy(record + 0x08, &resources, 8); + std::memcpy(record + 0x10, &pointer, 8); + } + } +}; + +struct Target { + ID3D12Resource* texture = nullptr; + ID3D12DescriptorHeap* heap = nullptr; + ID3D12Resource* readback = nullptr; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; +}; + +// Runs the window's composite path on `count` plane records and reads the target back. +// Returns width * height RGBA texels, or nothing when the composite drew no plane. +std::vector<unsigned char> composite(Gpu& gpu, x2w_startup::PlaneCompositor& compositor, Target& target, ID3D12Resource* const* surfaces, + unsigned count, unsigned* steps_out) +{ + Records records(surfaces, count); + const auto readable = [&](const void* address, std::size_t bytes) { + const auto* a = static_cast<const unsigned char*>(address); + const auto* lo = reinterpret_cast<const unsigned char*>(&records); + return a >= lo && a + bytes <= lo + sizeof(records); + }; + // As queue_present: plane i's first resource, 0 when the record has none. + std::uint64_t resources[4] = {}; + ID3D12Resource* plane_surfaces[4] = {}; + for (unsigned i = 0; i < count; ++i) { + resources[i] = x2w_startup::present_plane_resource(records.bytes, count, i, readable); + plane_surfaces[i] = reinterpret_cast<ID3D12Resource*>(resources[i]); + } + x2w_startup::PlaneStep steps[4]; + const unsigned n = x2w_startup::composite_steps(resources, count, steps, 4); + *steps_out = n; + barrier(gpu.list, target.texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + const float clear[4] = {0.25f, 0.5f, 0.75f, 0.0f}; // nothing of this may survive the opaque base + gpu.list->ClearRenderTargetView(target.heap->GetCPUDescriptorHandleForHeapStart(), clear, 0, nullptr); + const UINT drawn = compositor.record(gpu.device, gpu.list, target.heap->GetCPUDescriptorHandleForHeapStart(), width, height, steps, n, + plane_surfaces); + barrier(gpu.list, target.texture, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = target.readback; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = target.footprint; + from.pResource = target.texture; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + std::vector<unsigned char> pixels; + if (!gpu.run() || !drawn) return pixels; + pixels.resize(std::size_t{width} * height * 4); + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast<SIZE_T>(target.footprint.Footprint.RowPitch) * height}; + target.readback->Map(0, &range, &mapped); + for (UINT y = 0; y < height; ++y) + std::memcpy(&pixels[std::size_t{y} * width * 4], + static_cast<const unsigned char*>(mapped) + target.footprint.Offset + std::size_t{y} * target.footprint.Footprint.RowPitch, + std::size_t{width} * 4); + const D3D12_RANGE none{0, 0}; + target.readback->Unmap(0, &none); + return pixels; +} + +// Whether every texel of a cell is within `tolerance` of `want` (alpha 255); the first texel off it +// goes to `got`. +bool cell_matches(const std::vector<unsigned char>& pixels, UINT row, UINT column, const Rgba& want, int tolerance, unsigned char* got) +{ + const unsigned char w[4] = {want.r, want.g, want.b, 255}; + for (UINT y = row * cell_h; y < (row + 1) * cell_h; ++y) + for (UINT x = column * cell_w; x < (column + 1) * cell_w; ++x) { + const unsigned char* g = &pixels[(std::size_t{y} * width + x) * 4]; + for (int k = 0; k < 4; ++k) + if (std::abs(int{g[k]} - int{w[k]}) > tolerance) { + std::memcpy(got, g, 4); + return false; + } + } + return true; +} + +// Every texel of every cell must be within `tolerance` of the expected colour (alpha 255). +void expect(const char* name, const std::vector<unsigned char>& pixels, const Rgba (&want)[rows][columns], const int (&tolerance)[rows][columns]) +{ + if (pixels.empty()) { + ++failures; + std::printf("FAIL: %s: nothing composited\n", name); + return; + } + for (UINT row = 0; row < rows; ++row) + for (UINT column = 0; column < columns; ++column) { + const unsigned char w[4] = {want[row][column].r, want[row][column].g, want[row][column].b, 255}; + bool reported = false; + for (UINT y = row * cell_h; y < (row + 1) * cell_h && !reported; ++y) + for (UINT x = column * cell_w; x < (column + 1) * cell_w && !reported; ++x) { + const unsigned char* g = &pixels[(std::size_t{y} * width + x) * 4]; + for (int k = 0; k < 4 && !reported; ++k) + if (std::abs(int{g[k]} - int{w[k]}) > tolerance[row][column]) { + fail("FAIL: %s cell row %u column %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", name, row, column, g, w); + reported = true; + } + } + if (!reported) + std::printf("%s cell row %u column %u: %u,%u,%u,255 (+/-%d)\n", name, row, column, w[0], w[1], w[2], tolerance[row][column]); + } +} + +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + IDXGIFactory4* factory = nullptr; + IDXGIAdapter* warp = nullptr; + Gpu gpu; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp))) || + FAILED(D3D12CreateDevice(warp, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&gpu.device)))) { + std::printf("SKIP: no WARP device\n"); + return 77; + } + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(gpu.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&gpu.queue))) || + FAILED(gpu.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&gpu.allocator))) || + FAILED(gpu.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, gpu.allocator, nullptr, IID_PPV_ARGS(&gpu.list))) || + FAILED(gpu.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gpu.fence)))) { + std::printf("FAIL: WARP queue setup\n"); + return 1; + } + x2w_startup::PlaneCompositor compositor; + const HRESULT created = compositor.create(gpu.device, DXGI_FORMAT_R8G8B8A8_UNORM, 1); + if (FAILED(created)) { + std::printf("FAIL: compositor setup 0x%08lx\n", static_cast<unsigned long>(created)); + return 1; + } + + Target target; + { + const D3D12_RESOURCE_DESC desc = texture_desc(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, nullptr, + IID_PPV_ARGS(&target.texture)); + const D3D12_DESCRIPTOR_HEAP_DESC rtv{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + gpu.device->CreateDescriptorHeap(&rtv, IID_PPV_ARGS(&target.heap)); + gpu.device->CreateRenderTargetView(target.texture, nullptr, target.heap->GetCPUDescriptorHandleForHeapStart()); + UINT64 total = 0; + gpu.device->GetCopyableFootprints(&desc, 0, 1, 0, &target.footprint, nullptr, nullptr, &total); + target.readback = buffer(gpu, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST); + } + if (!target.texture || !target.heap || !target.readback) { + std::printf("FAIL: target setup\n"); + return 1; + } + + // Plane pictures. The baseline plane's last cell has alpha 0 to show that the bottom plane's + // alpha is ignored. + const Cells baseline = {{{200, 40, 10, 255}, {10, 200, 40, 255}, {40, 10, 200, 128}, {250, 250, 250, 255}}, + {{0, 0, 0, 255}, {128, 64, 32, 255}, {1, 2, 3, 255}, {90, 180, 60, 0}}}; + const Cells black = {{{0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}, + {{0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}}; + // Plane 1: row 0 transparent (alpha 0), half (128), nearly transparent (5), opaque; row 1 opaque + // blue under plane 2's blended cell, opaque blue under plane 2's opaque cell, transparent twice. + const Cells overlay = {{{255, 0, 0, 0}, {0, 255, 0, 128}, {255, 255, 255, 5}, {0, 0, 255, 255}}, + {{0, 0, 255, 255}, {0, 0, 255, 255}, {255, 255, 255, 0}, {255, 255, 255, 0}}}; + // Plane 2: row 0 transparent; row 1 half red over blue (order), opaque yellow over blue, opaque + // cyan over black, transparent. + const Cells top = {{{255, 255, 0, 0}, {255, 255, 0, 0}, {255, 255, 0, 0}, {255, 255, 0, 0}}, + {{255, 0, 0, 128}, {255, 255, 0, 255}, {0, 255, 255, 255}, {255, 0, 255, 0}}}; + ID3D12Resource* const p_baseline = plane(gpu, baseline); + ID3D12Resource* const p_black = plane(gpu, black); + ID3D12Resource* const p_overlay = plane(gpu, overlay); + ID3D12Resource* const p_top = plane(gpu, top); + if (!p_baseline || !p_black || !p_overlay || !p_top) { + std::printf("FAIL: plane setup\n"); + return 1; + } + + const int exact[rows][columns] = {{0, 0, 0, 0}, {0, 0, 0, 0}}; + unsigned steps = 0; + + // Baseline: one plane, shown as is, alpha forced to 255. + { + ID3D12Resource* const planes[] = {p_baseline}; + const auto pixels = composite(gpu, compositor, target, planes, 1, &steps); + Rgba want[rows][columns]; + for (UINT r = 0; r < rows; ++r) + for (UINT c = 0; c < columns; ++c) want[r][c] = baseline[r][c]; + if (steps != 1) { + ++failures; + std::printf("FAIL: baseline: %u steps, want 1\n", steps); + } + expect("baseline", pixels, want, exact); + } + + const HRESULT composite_created = compositor.create(gpu.device, DXGI_FORMAT_R8G8B8A8_UNORM, 4); + if (FAILED(composite_created)) { + std::printf("FAIL: multi-plane compositor setup 0x%08lx\n", static_cast<unsigned long>(composite_created)); + return 1; + } + + // Stacked: black, overlay, top. + // Expected (UNORM8, src * a/255 + dst * (1 - a/255)): 128/255 of 255 is 128; 5/255 of 255 is 5; + // half red over blue is 128,0,127. + const Rgba stacked_want[rows][columns] = {{{0, 0, 0, 255}, {0, 128, 0, 255}, {5, 5, 5, 255}, {0, 0, 255, 255}}, + {{128, 0, 127, 255}, {255, 255, 0, 255}, {0, 255, 255, 255}, {0, 0, 0, 255}}}; + const int blended[rows][columns] = {{0, 1, 1, 0}, {1, 0, 0, 0}}; + { + ID3D12Resource* const planes[] = {p_black, p_overlay, p_top}; + const auto pixels = composite(gpu, compositor, target, planes, 3, &steps); + if (steps != 3) { + ++failures; + std::printf("FAIL: stacked: %u steps, want 3\n", steps); + } + expect("stacked", pixels, stacked_want, blended); + } + + // Skipped: plane 2 repeats plane 1's surface and plane 3 has no resource. Drawing the repeat + // would blend the half-green cell twice (0,191,0) and the nearly transparent one twice (10). + { + ID3D12Resource* const planes[] = {p_black, p_overlay, p_overlay, nullptr}; + const auto pixels = composite(gpu, compositor, target, planes, 4, &steps); + if (steps != 2) { + ++failures; + std::printf("FAIL: skipped: %u steps, want 2 (plane 0 and plane 1)\n", steps); + } + const Rgba want[rows][columns] = {{{0, 0, 0, 255}, {0, 128, 0, 255}, {5, 5, 5, 255}, {0, 0, 255, 255}}, + {{0, 0, 255, 255}, {0, 0, 255, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}}; + const int tolerance[rows][columns] = {{0, 1, 1, 0}, {0, 0, 0, 0}}; + expect("skipped", pixels, want, tolerance); + } + + // Control: the overlays removed, stacked is composited from the black plane 0 alone. That must be + // black everywhere, and must differ from the stacked expectation in exactly the cells the overlays + // draw: every cell except row 0 column 0 (plane 1 transparent) and row 1 column 3 (both transparent). + unsigned control_differences = 0; + if (control && !failures) { + const bool overlay_drawn[rows][columns] = {{false, true, true, true}, {true, true, true, false}}; + const Rgba black_want = {0, 0, 0, 255}; + ID3D12Resource* const planes[] = {p_black}; + const auto pixels = composite(gpu, compositor, target, planes, 1, &steps); + if (steps != 1) { + ++failures; + std::printf("FAIL: control: overlay removed: %u steps, want 1\n", steps); + } + if (pixels.empty()) { + ++failures; + std::printf("FAIL: control: overlay removed: nothing composited\n"); + } + for (UINT row = 0; row < rows && !pixels.empty(); ++row) + for (UINT column = 0; column < columns; ++column) { + unsigned char got[4] = {}; + const unsigned char black[4] = {0, 0, 0, 255}; + if (!cell_matches(pixels, row, column, black_want, 0, got)) { + fail("FAIL: %s cell row %u column %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", "control: overlay removed", row, column, got, + black); + continue; + } + const bool differs = !cell_matches(pixels, row, column, stacked_want[row][column], blended[row][column], got); + if (differs) ++control_differences; + if (differs != overlay_drawn[row][column]) { + ++failures; + std::printf("FAIL: control: overlay removed: cell row %u column %u %s the stacked expectation, want it to %s\n", row, + column, differs ? "differs from" : "matches", overlay_drawn[row][column] ? "differ" : "match"); + } else { + std::printf("control: overlay removed: cell row %u column %u %s the stacked expectation\n", row, column, + differs ? "differs from" : "matches"); + } + } + } + + const HRESULT removed = gpu.device->GetDeviceRemovedReason(); + if (FAILED(removed)) { + ++failures; + std::printf("FAIL: device removed 0x%08lx\n", static_cast<unsigned long>(removed)); + } + if (failures) { + std::printf("startup_present_composite: FAIL (%d)\n", failures); + return 1; + } + if (control) { + std::printf("control ok: baseline matched, %u fences completed, removing the overlay changed %u of %u cells as expected\n", + gpu.fences, control_differences, rows * columns); + return 0; + } + std::puts("startup_present_composite: ok (baseline, stacked and skipped planes on WARP)"); + return 0; +} diff --git a/tests/startup_present_planes_check.cpp b/tests/startup_present_planes_check.cpp new file mode 100644 index 0000000000..88473d3c6c --- /dev/null +++ b/tests/startup_present_planes_check.cpp @@ -0,0 +1,89 @@ +// Checks src/startup_stubs/present_planes.h on synthetic plane records: two 0x48-byte records, each +// with a frame token, a resource count and a pointer to its resource array. +// Also checks the window composite order (composite_steps) on synthetic plane surfaces. +// --control reads the records with a 0x40-byte stride (the record size before the second plane was +// measured) and composites plane 0 alone (the window present before planes were composited); the +// second-plane rows must print FAIL. +#include "startup_stubs/present_planes.h" + +#include <cstdio> +#include <cstring> + +namespace { +int failures; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +void put(unsigned char* at, std::uint64_t value) { std::memcpy(at, &value, 8); } +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + const std::size_t stride = control ? 0x40 : x2w_startup::present_plane_stride; + const std::uint64_t first_plane[] = {0x1111}, second_plane[] = {0x2222, 0x3333}; + alignas(8) unsigned char records[2 * 0x48] = {}; + alignas(8) unsigned char empty[0x48] = {}; + // Readable: only this fixture's own records and resource arrays. + const auto inside = [](const void* address, std::size_t bytes, const void* base, std::size_t size) { + const auto* a = static_cast<const unsigned char*>(address); + const auto* b = static_cast<const unsigned char*>(base); + return a >= b && a + bytes <= b + size; + }; + const auto readable = [&](const void* address, std::size_t bytes) { + return inside(address, bytes, records, sizeof(records)) || inside(address, bytes, empty, sizeof(empty)) || + inside(address, bytes, first_plane, sizeof(first_plane)) || inside(address, bytes, second_plane, sizeof(second_plane)); + }; + put(records + 0x00, 7); // frame token + put(records + 0x08, 1); + put(records + 0x10, reinterpret_cast<std::uint64_t>(first_plane)); + put(records + 0x48, 7); + put(records + 0x50, 2); + put(records + 0x58, reinterpret_cast<std::uint64_t>(second_plane)); + + using x2w_startup::present_plane_resource; + check("plane 0 resource", present_plane_resource(records, 2, 0, readable, stride) == 0x1111); + check("plane 1 resource (the second record starts at +0x48)", present_plane_resource(records, 2, 1, readable, stride) == 0x2222); + check("a plane past the count has no resource", present_plane_resource(records, 1, 1, readable, stride) == 0); + check("no records", present_plane_resource(nullptr, 2, 0, readable, stride) == 0); + + put(empty + 0x10, reinterpret_cast<std::uint64_t>(first_plane)); + check("a plane with no resources has none", present_plane_resource(empty, 1, 0, readable, stride) == 0); + const auto unreadable = [](const void*, std::size_t) { return false; }; + check("an unreadable record has no resource", present_plane_resource(records, 2, 0, unreadable, stride) == 0); + + // Composite order: the lowest shown plane is opaque, later ones blend over it. + using x2w_startup::PlaneStep; + const auto composite = [&](const std::uint64_t* resources, unsigned count, PlaneStep* steps) { + return x2w_startup::composite_steps(resources, control && count > 1 ? 1 : count, steps, 4); + }; + PlaneStep steps[4]; + const std::uint64_t two[] = {0x1111, 0x2222}; + unsigned n = composite(two, 2, steps); + check("two planes give two steps", n == 2); + check("plane 0 is drawn first, opaque", n >= 1 && steps[0].plane == 0 && !steps[0].blended); + check("plane 1 is drawn over plane 0, blended", n >= 2 && steps[1].plane == 1 && steps[1].blended); + const std::uint64_t missing_base[] = {0, 0x2222}; + n = composite(missing_base, 2, steps); + check("with plane 0 not shown, plane 1 is the opaque base", n == 1 && steps[0].plane == 1 && !steps[0].blended); + const std::uint64_t repeated[] = {0x1111, 0x1111}; + n = x2w_startup::composite_steps(repeated, 2, steps, 4); + check("a surface presented twice is drawn once", n == 1 && steps[0].plane == 0); + const std::uint64_t one[] = {0x1111}; + n = composite(one, 1, steps); + check("one plane is one opaque step", n == 1 && steps[0].plane == 0 && !steps[0].blended); + check("no planes, no steps", x2w_startup::composite_steps(nullptr, 2, steps, 4) == 0); + + if (failures) { + std::printf("startup_present_planes: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_present_planes: ok"); + return 0; +} diff --git a/tests/startup_present_readback_check.cpp b/tests/startup_present_readback_check.cpp new file mode 100644 index 0000000000..2e18d31939 --- /dev/null +++ b/tests/startup_present_readback_check.cpp @@ -0,0 +1,89 @@ +#include "startup_stubs/present_readback_state.h" + +#include <cstdio> +#include <cstdlib> + +namespace { +using x2w_startup::FenceCompletion; +using x2w_startup::PresentReadbackState; +using x2w_startup::fence_completion; + +void require(bool ok, const char* message) +{ + if (!ok) { + std::fprintf(stderr, "%s\n", message); + std::exit(1); + } +} +} + +int main() +{ + PresentReadbackState state; + require(!state.pending() && !state.unusable(), "initial readback not reusable"); + state.submitted(7); + require(state.pending(), "submission not retained"); + require(state.observe(6) == FenceCompletion::pending && state.pending(), + "premature completion would release the submitted surface"); + require(state.observe(7) == FenceCompletion::completed && !state.pending() && !state.unusable(), + "completed submission did not allow reuse"); + state.submitted(8); + require(state.observe(7) == FenceCompletion::pending && state.pending(), + "stale event would publish a later submission"); + require(state.observe(9) == FenceCompletion::completed && !state.pending(), + "past-target completion did not settle submission"); + state.submitted(10); + require(state.observe(UINT64_MAX) == FenceCompletion::removed && state.unusable(), + "device removal would publish or allow reuse"); + + PresentReadbackState failed; + failed.signal_failed(); + require(failed.unusable(), "failed signal would allow reuse"); + require(fence_completion(UINT64_MAX - 1, UINT64_MAX - 1) == FenceCompletion::completed, + "highest usable fence value rejected"); + require(fence_completion(UINT64_MAX, UINT64_MAX) == FenceCompletion::removed, + "reserved fence value accepted as completion"); + + // Ownership disposition: retire() must release the held references exactly once, only for a + // confirmed completion, never while pending or removed, and a drain registered for one + // submission must not retire a different pending target. + { + int released = 0; + const auto release = [&] { ++released; }; + PresentReadbackState retired; + require(retired.retire(5, release) == FenceCompletion::completed && released == 0, + "a never-submitted state has no ownership to release"); + retired.submitted(20); + require(retired.retire(19, release) == FenceCompletion::pending && released == 0 && retired.pending(), + "a pending fence would retire ownership"); + require(retired.retire(20, release) == FenceCompletion::completed && released == 1 && !retired.pending(), + "a completed fence did not retire ownership"); + require(retired.retire(20, release) == FenceCompletion::completed && released == 1, + "a second completed observation retired ownership again"); + retired.submitted(21); + require(retired.retire(UINT64_MAX, release) == FenceCompletion::removed && released == 1 && retired.unusable(), + "device removal retired ownership"); + require(retired.retire(21, release) == FenceCompletion::removed && released == 1, + "an unusable state retired ownership"); + } + { + int released = 0; + PresentReadbackState drained; + drained.submitted(30); + // The drain was registered for 29; the fence completed but the pending target is a later + // submission, so the drain must not release it. + require(drained.retire(30, [&] { ++released; }, 29) == FenceCompletion::completed && released == 0 && drained.pending(), + "a drain retired a submission it was not registered for"); + // The drain for the current target releases it exactly once. + require(drained.retire(30, [&] { ++released; }, 30) == FenceCompletion::completed && released == 1 && !drained.pending(), + "a drain for the current target did not retire ownership"); + // A drain registered for the settled submission observes completed without releasing again. + drained.submitted(31); + // Completed fence value, but the drain is for the settled earlier submission: it must + // not release or settle the later target it does not own. + require(drained.retire(31, [&] { ++released; }, 30) == FenceCompletion::completed && released == 1 && drained.pending(), + "a stale drain retired or settled a later submission"); + } + std::puts("present readback: pending, stale event, completion, failed signal, removal and " + "ownership retirement controls passed"); +} diff --git a/tests/startup_present_signature.cpp b/tests/startup_present_signature.cpp index 316db9d9a4..09cc4ded72 100644 --- a/tests/startup_present_signature.cpp +++ b/tests/startup_present_signature.cpp @@ -183,11 +183,60 @@ std::vector<x2w_present_signature::Snapshot> present_all(Gpu& gpu, x2w_present_s return published; } +// Forwards every call to a real fence, except that GetCompletedValue reports UINT64_MAX once +// `removed` is set: the device-removal case the sampler has to survive without treating it as +// completion. Signal and SetEventOnCompletion still succeed, as they do while a device is being +// removed. For the destructor controls, `pending_observations`/`next` make each successive +// GetCompletedValue report a chosen value a fixed number of times and then the real fence's own +// value, so a transition across the destructor's wait is deterministic: the pre-wait +// observation sees pending, the wait runs on the real fence, the post-wait observation sees the +// completed (or, with `removed`, the removal sentinel) state. The real fence is the only object +// the driver ever sees. +class RemovedFence : public ID3D12Fence { +public: + explicit RemovedFence(ID3D12Fence* real) : real_(real) {} + bool removed = false; + UINT64 pending_observations = 0; // report `next` this many times, then the real value + UINT64 next = 0; + unsigned observations = 0; // GetCompletedValue calls since construction + unsigned event_registrations = 0; + ID3D12Fence* real() const { return real_; } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { return real_ ? real_->QueryInterface(riid, out) : E_FAIL; } + ULONG STDMETHODCALLTYPE AddRef() override { return real_ ? real_->AddRef() : 0; } + ULONG STDMETHODCALLTYPE Release() override { return real_ ? real_->Release() : 0; } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID g, UINT* n, void* d) override { return real_ ? real_->GetPrivateData(g, n, d) : E_FAIL; } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID g, UINT n, const void* d) override { return real_ ? real_->SetPrivateData(g, n, d) : E_FAIL; } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID g, const IUnknown* d) override { return real_ ? real_->SetPrivateDataInterface(g, d) : E_FAIL; } + HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return real_ ? real_->SetName(name) : E_FAIL; } + HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** out) override { return real_ ? real_->GetDevice(riid, out) : E_FAIL; } + UINT64 STDMETHODCALLTYPE GetCompletedValue() override + { + ++observations; + if (pending_observations) { + --pending_observations; + return next; + } + if (removed) return UINT64_MAX; + return real_ ? real_->GetCompletedValue() : 0; + } + HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64 value, HANDLE event) override + { + ++event_registrations; + return real_ ? real_->SetEventOnCompletion(value, event) : E_FAIL; + } + HRESULT STDMETHODCALLTYPE Signal(UINT64 value) override { return real_ ? real_->Signal(value) : E_FAIL; } + +private: + ID3D12Fence* real_; +}; // Forwards every call to a real queue, except that Signal fails once `fail_signal` is set: the -// "submitted, but no fence" case the sampler has to survive. +// "submitted, but no fence" case the sampler has to survive. With `observed`, Signal and Wait +// unwrap exactly our RemovedFence to its real fence, so a test fake never enters the driver. + class SignalFailingQueue : public ID3D12CommandQueue { public: - explicit SignalFailingQueue(ID3D12CommandQueue* real) : real_(real) {} + explicit SignalFailingQueue(ID3D12CommandQueue* real, RemovedFence* observed = nullptr) + : real_(real), observed_(observed) {} bool fail_signal = false; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { return real_->QueryInterface(riid, out); } ULONG STDMETHODCALLTYPE AddRef() override { return 2; } @@ -213,8 +262,17 @@ class SignalFailingQueue : public ID3D12CommandQueue { void STDMETHODCALLTYPE SetMarker(UINT m, const void* d, UINT n) override { real_->SetMarker(m, d, n); } void STDMETHODCALLTYPE BeginEvent(UINT m, const void* d, UINT n) override { real_->BeginEvent(m, d, n); } void STDMETHODCALLTYPE EndEvent() override { real_->EndEvent(); } - HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence* fence, UINT64 value) override { return fail_signal ? E_FAIL : real_->Signal(fence, value); } - HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override { return real_->Wait(fence, value); } + HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence* fence, UINT64 value) override + { + if (fail_signal) return E_FAIL; + // A test fake never enters the driver: unwrap exactly our RemovedFence to its real fence. + if (observed_ && fence == observed_) fence = observed_->real(); + return real_->Signal(fence, value); + } + HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override + { + return real_->Wait(observed_ && fence == observed_ ? observed_->real() : fence, value); + } HRESULT STDMETHODCALLTYPE GetTimestampFrequency(UINT64* f) override { return real_->GetTimestampFrequency(f); } HRESULT STDMETHODCALLTYPE GetClockCalibration(UINT64* g, UINT64* c) override { return real_->GetClockCalibration(g, c); } #if defined(_MSC_VER) || !defined(_WIN32) @@ -225,8 +283,87 @@ class SignalFailingQueue : public ID3D12CommandQueue { private: ID3D12CommandQueue* real_; + RemovedFence* observed_; }; +// Forwards every ID3D12Device method to a real device, except that CreateFence returns the +// RemovedFence above, so the fixture controls what GetCompletedValue reports. +class RemovalDevice : public ID3D12Device { +public: + explicit RemovalDevice(ID3D12Device* real) : real_(real) {} + RemovedFence& fence() { return fence_; } + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { return real_->QueryInterface(riid, out); } + ULONG STDMETHODCALLTYPE AddRef() override { return 2; } + ULONG STDMETHODCALLTYPE Release() override { return 1; } + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID g, UINT* n, void* d) override { return real_->GetPrivateData(g, n, d); } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID g, UINT n, const void* d) override { return real_->SetPrivateData(g, n, d); } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID g, const IUnknown* d) override { return real_->SetPrivateDataInterface(g, d); } + HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return real_->SetName(name); } + // clang-format off + UINT STDMETHODCALLTYPE GetNodeCount() override { return real_->GetNodeCount(); } + HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC *desc, REFIID riid, void **command_queue) override { return real_->CreateCommandQueue(desc, riid, command_queue); } + HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void **command_allocator) override { return real_->CreateCommandAllocator(type, riid, command_allocator); } + HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC *desc, REFIID riid, void **pipeline_state) override { return real_->CreateGraphicsPipelineState(desc, riid, pipeline_state); } + HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC *desc, REFIID riid, void **pipeline_state) override { return real_->CreateComputePipelineState(desc, riid, pipeline_state); } + HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator *command_allocator, ID3D12PipelineState *initial_pipeline_state, REFIID riid, void **command_list) override { return real_->CreateCommandList(node_mask, type, command_allocator, initial_pipeline_state, riid, command_list); } + HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void *feature_data, UINT feature_data_size) override { return real_->CheckFeatureSupport(feature, feature_data, feature_data_size); } + HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC *desc, REFIID riid, void **descriptor_heap) override { return real_->CreateDescriptorHeap(desc, riid, descriptor_heap); } + UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type) override { return real_->GetDescriptorHandleIncrementSize(descriptor_heap_type); } + HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT node_mask, const void *bytecode, SIZE_T bytecode_length, REFIID riid, void **root_signature) override { return real_->CreateRootSignature(node_mask, bytecode, bytecode_length, riid, root_signature); } + void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateConstantBufferView(desc, descriptor); } + void STDMETHODCALLTYPE CreateShaderResourceView(ID3D12Resource *resource, const D3D12_SHADER_RESOURCE_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateShaderResourceView(resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource *resource, ID3D12Resource *counter_resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateUnorderedAccessView(resource, counter_resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateRenderTargetView(ID3D12Resource *resource, const D3D12_RENDER_TARGET_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateRenderTargetView(resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateDepthStencilView(ID3D12Resource *resource, const D3D12_DEPTH_STENCIL_VIEW_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateDepthStencilView(resource, desc, descriptor); } + void STDMETHODCALLTYPE CreateSampler(const D3D12_SAMPLER_DESC *desc, D3D12_CPU_DESCRIPTOR_HANDLE descriptor) override { real_->CreateSampler(desc, descriptor); } + void STDMETHODCALLTYPE CopyDescriptors(UINT dst_descriptor_range_count, const D3D12_CPU_DESCRIPTOR_HANDLE *dst_descriptor_range_offsets, const UINT *dst_descriptor_range_sizes, UINT src_descriptor_range_count, const D3D12_CPU_DESCRIPTOR_HANDLE *src_descriptor_range_offsets, const UINT *src_descriptor_range_sizes, D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type) override { real_->CopyDescriptors(dst_descriptor_range_count, dst_descriptor_range_offsets, dst_descriptor_range_sizes, src_descriptor_range_count, src_descriptor_range_offsets, src_descriptor_range_sizes, descriptor_heap_type); } + void STDMETHODCALLTYPE CopyDescriptorsSimple(UINT descriptor_count, const D3D12_CPU_DESCRIPTOR_HANDLE dst_descriptor_range_offset, const D3D12_CPU_DESCRIPTOR_HANDLE src_descriptor_range_offset, D3D12_DESCRIPTOR_HEAP_TYPE descriptor_heap_type) override { real_->CopyDescriptorsSimple(descriptor_count, dst_descriptor_range_offset, src_descriptor_range_offset, descriptor_heap_type); } +#ifdef WIDL_EXPLICIT_AGGREGATE_RETURNS + D3D12_RESOURCE_ALLOCATION_INFO* STDMETHODCALLTYPE GetResourceAllocationInfo(D3D12_RESOURCE_ALLOCATION_INFO* out, UINT visible_mask, UINT reource_desc_count, const D3D12_RESOURCE_DESC *resource_descs) override { return real_->GetResourceAllocationInfo(out, visible_mask, reource_desc_count, resource_descs); } + D3D12_HEAP_PROPERTIES* STDMETHODCALLTYPE GetCustomHeapProperties(D3D12_HEAP_PROPERTIES* out, UINT node_mask, D3D12_HEAP_TYPE heap_type) override { return real_->GetCustomHeapProperties(out, node_mask, heap_type); } +#else + D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo(UINT visible_mask, UINT reource_desc_count, const D3D12_RESOURCE_DESC *resource_descs) override { return real_->GetResourceAllocationInfo(visible_mask, reource_desc_count, resource_descs); } + D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE heap_type) override { return real_->GetCustomHeapProperties(node_mask, heap_type); } +#endif + HRESULT STDMETHODCALLTYPE CreateCommittedResource(const D3D12_HEAP_PROPERTIES *heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE *optimized_clear_value, REFIID riid, void **resource) override { return real_->CreateCommittedResource(heap_properties, heap_flags, desc, initial_state, optimized_clear_value, riid, resource); } + HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC *desc, REFIID riid, void **heap) override { return real_->CreateHeap(desc, riid, heap); } + HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap *heap, UINT64 heap_offset, const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE *optimized_clear_value, REFIID riid, void **resource) override { return real_->CreatePlacedResource(heap, heap_offset, desc, initial_state, optimized_clear_value, riid, resource); } + HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC *desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE *optimized_clear_value, REFIID riid, void **resource) override { return real_->CreateReservedResource(desc, initial_state, optimized_clear_value, riid, resource); } + HRESULT STDMETHODCALLTYPE CreateSharedHandle(ID3D12DeviceChild *object, const SECURITY_ATTRIBUTES *attributes, DWORD access, const WCHAR *name, HANDLE *handle) override { return real_->CreateSharedHandle(object, attributes, access, name, handle); } + HRESULT STDMETHODCALLTYPE OpenSharedHandle(HANDLE handle, REFIID riid, void **object) override { return real_->OpenSharedHandle(handle, riid, object); } + HRESULT STDMETHODCALLTYPE OpenSharedHandleByName(const WCHAR *name, DWORD access, HANDLE *handle) override { return real_->OpenSharedHandleByName(name, access, handle); } + HRESULT STDMETHODCALLTYPE MakeResident(UINT object_count, ID3D12Pageable *const *objects) override { return real_->MakeResident(object_count, objects); } + HRESULT STDMETHODCALLTYPE Evict(UINT object_count, ID3D12Pageable *const *objects) override { return real_->Evict(object_count, objects); } + HRESULT STDMETHODCALLTYPE CreateFence(UINT64 initial_value, D3D12_FENCE_FLAGS flags, REFIID riid, void **fence) override + { + if (riid != __uuidof(ID3D12Fence)) return E_NOINTERFACE; + ID3D12Fence* real_fence = nullptr; + const HRESULT hr = real_->CreateFence(initial_value, flags, IID_PPV_ARGS(&real_fence)); + if (SUCCEEDED(hr)) { + fence_ = RemovedFence(real_fence); + *fence = static_cast<ID3D12Fence*>(&fence_); + } + return hr; + } + HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason() override { return real_->GetDeviceRemovedReason(); } + void STDMETHODCALLTYPE GetCopyableFootprints(const D3D12_RESOURCE_DESC *desc, UINT first_sub_resource, UINT sub_resource_count, UINT64 base_offset, D3D12_PLACED_SUBRESOURCE_FOOTPRINT *layouts, UINT *row_count, UINT64 *row_size, UINT64 *total_bytes) override { real_->GetCopyableFootprints(desc, first_sub_resource, sub_resource_count, base_offset, layouts, row_count, row_size, total_bytes); } + HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC *desc, REFIID riid, void **heap) override { return real_->CreateQueryHeap(desc, riid, heap); } + HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL enable) override { return real_->SetStablePowerState(enable); } + HRESULT STDMETHODCALLTYPE CreateCommandSignature(const D3D12_COMMAND_SIGNATURE_DESC *desc, ID3D12RootSignature *root_signature, REFIID riid, void **command_signature) override { return real_->CreateCommandSignature(desc, root_signature, riid, command_signature); } + void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource *resource, UINT *total_tile_count, D3D12_PACKED_MIP_INFO *packed_mip_info, D3D12_TILE_SHAPE *standard_tile_shape, UINT *sub_resource_tiling_count, UINT first_sub_resource_tiling, D3D12_SUBRESOURCE_TILING *sub_resource_tilings) override { real_->GetResourceTiling(resource, total_tile_count, packed_mip_info, standard_tile_shape, sub_resource_tiling_count, first_sub_resource_tiling, sub_resource_tilings); } +#ifdef WIDL_EXPLICIT_AGGREGATE_RETURNS + LUID* STDMETHODCALLTYPE GetAdapterLuid(LUID* out) override { return real_->GetAdapterLuid(out); } +#else + LUID STDMETHODCALLTYPE GetAdapterLuid() override { return real_->GetAdapterLuid(); } +#endif + // clang-format on + +private: + ID3D12Device* real_; + RemovedFence fence_{nullptr}; +}; + + // Error and corruption messages the debug layer has stored since the last call; prints each one. // `deleted_in_use` is set when one of them reports an object released while the GPU still used it. int debug_errors(ID3D12InfoQueue* info, bool* deleted_in_use = nullptr) @@ -349,6 +486,96 @@ int lifetime(Gpu& gpu, ID3D12InfoQueue* info, x2w_present_signature::Block* bloc delete sampler; // a stranded sampler releases nothing it may still be using gate->Release(); } + // Device removal while a copy is in flight: the fence reports UINT64_MAX, which is not a + // completion. Nothing is mapped or published, the sampler stops sampling, and the source stays + // held; the destructor keeps every object the copy uses. A genuine prior sample (published + // before the removal) stays as it was: no stale publish, no clearing. + { + ID3D12Resource* presented = surface(gpu, DXGI_FORMAT_R8G8B8A8_UNORM, picture); + RemovalDevice removed_device(gpu.device); + // The queue proxy unwraps the sampler's RemovedFence to its real fence by exact fake + // identity, so no fake COM object ever reaches the driver. + SignalFailingQueue unwrapping(gpu.queue, &removed_device.fence()); + x2w_present_signature::Sampler sampler(1, true, true); + ID3D12Fence* gate = stall(gpu); + const LONG64 before = block->sequence / 2; + // First a genuine completed copy: it publishes and fills the historical sample state. + sampler.present(&removed_device, &unwrapping, presented, 1, block); + gate->Signal(1); + gpu.idle(); + sampler.present(&removed_device, &unwrapping, nullptr, 2, block); + ID3D12Resource* const sampled_surface = sampler.last_surface(); + const bool had_sample = block->sequence / 2 == before + 1 && sampler.last_present() == 1 + && sampled_surface && !sampler.holds_source(); + check(had_sample, "a genuine copy completes and publishes before the removal"); + // Then a second copy whose fence will report device removal. + sampler.present(&removed_device, &unwrapping, presented, 3, block); + check(sampler.in_flight() && sampler.holds_source(), "the second copy is in flight before the removal"); + const ULONG left = presented->Release(); // the caller's only reference + check(left == 1, "before the removal only the sampler's reference is left"); + gate->Signal(1); + gpu.idle(); // the copy has really finished; the fence still reports device removal + removed_device.fence().removed = true; + const LONG64 published_before = block->sequence / 2; + sampler.present(&removed_device, &unwrapping, nullptr, 4, block); + check(!sampler.in_flight() && sampler.failed() && sampler.stranded(), + "a removed fence is not a completion: the sampler stops, stranded like a failed Signal"); + check(sampler.holds_source(), "the source stays held after a removed fence"); + check(block->sequence / 2 == published_before, "a removed fence publishes no sample"); + // The prior historical sample survives exactly as it was: nothing cleared, nothing stale. + check(sampler.last_present() == 1 && sampler.last_surface() == sampled_surface, + "the prior published sample (number and surface) survives the removal unchanged"); + sampler.present(&removed_device, &unwrapping, nullptr, 5, block); + check(sampler.failed() && sampler.stranded() && !sampler.in_flight() && block->sequence / 2 == published_before, + "a stranded sampler records nothing more and keeps the surface"); + gate->Release(); + // The destructor must keep every object the copy uses (stranded): nothing is released + // under a removed device. (The destructor runs at the block's end.) + } + // The destructor's own re-observation: a copy still pending at destruction transitions across + // the destructor's 10 s wait deterministically, because the fence reports a chosen value for a + // fixed number of observations and then the real (or removed) state. Pending that completes + // while the wait runs releases normally; a fence that reports removal afterwards keeps + // everything. The real fence is the only object the driver sees. + { + // Pending completes during the destructor's wait: normal release, no strand. + { + ID3D12Resource* presented = surface(gpu, DXGI_FORMAT_R8G8B8A8_UNORM, picture); + RemovalDevice removal(gpu.device); + SignalFailingQueue unwrapping(gpu.queue, &removal.fence()); + ID3D12Fence* gate = stall(gpu); + x2w_present_signature::Sampler* sampler = new x2w_present_signature::Sampler(1); + sampler->present(&removal, &unwrapping, presented, 1, block); + check(sampler->in_flight() && sampler->holds_source(), "a stalled copy is in flight at destruction"); + gate->Signal(1); // the copy really completes; the fence is scripted to report pending once + removal.fence().pending_observations = 1; + removal.fence().next = 0; + delete sampler; // pre-wait observation: pending; wait: on the real fence; post-wait: completed + check(removal.fence().observations >= 2 && removal.fence().event_registrations == 1, + "the destructor observes before and after its wait, and registers its event once"); + check(presented->Release() == 0, "a copy that completes while the destructor waits releases the source normally"); + gate->Release(); + } + // The fence reports the removal sentinel to the post-wait observation: nothing releases. + { + ID3D12Resource* presented = surface(gpu, DXGI_FORMAT_R8G8B8A8_UNORM, picture); + RemovalDevice removal(gpu.device); + SignalFailingQueue unwrapping(gpu.queue, &removal.fence()); + ID3D12Fence* gate = stall(gpu); + x2w_present_signature::Sampler* sampler = new x2w_present_signature::Sampler(1); + sampler->present(&removal, &unwrapping, presented, 2, block); + check(sampler->in_flight() && sampler->holds_source(), "the second stalled copy is in flight at destruction"); + gate->Signal(1); // the copy really completes + removal.fence().pending_observations = 1; + removal.fence().next = 0; + removal.fence().removed = true; // from the second observation on: the removal sentinel + delete sampler; + check(removal.fence().observations == 2 && removal.fence().event_registrations == 1, + "the destructor re-observed removal after exactly one wait registration"); + check(presented->Release() == 1, "a fence that reports removal after the wait keeps the sampler's source reference"); + gate->Release(); + } + } const int errors = debug_errors(info); std::printf("held source: %d debug-layer errors\n", errors); check(errors == 0, "the debug layer reports no error for the sampler's stalled copy"); diff --git a/tests/startup_ps_input_scan_check.py b/tests/startup_ps_input_scan_check.py index fe2c444638..eaba71a977 100644 --- a/tests/startup_ps_input_scan_check.py +++ b/tests/startup_ps_input_scan_check.py @@ -143,13 +143,22 @@ def sets(contract): interp(7, 1, 0, True), exp(7, 7, 7, 7)), 'alias_straight': shader(mov(4, 0), interp(7, 4, 0, False), interp(7, 1, 0, True), exp(7, 7, 7, 7)), 'unsat_v40': shader(add(6, 40, 40), exp(6, 6, 6, 6)), + # Diamond: a forward conditional branch skips the write to v2 and the join reads v2, so on the + # taken edge v2 still holds its entry value. v1 is never written. + 'diamond_skip': shader(br('s_cbranch_scc1', 0, 8), mov_zero(2), add(6, 2, 1), exp(6, 6, 6, 6)), + # The same join with v2 written on both incoming edges: v2 is defined on every path. + 'diamond_both': shader(br('s_cbranch_scc1', 0, 12), mov_zero(2), br('s_branch', 8, 16), mov_zero(2), + add(6, 2, 1), exp(6, 6, 6, 6)), } # The address mask each informative shader needs, and one that satisfies it. MASKS = {'packed_only@v1': 0x8100, 'packed_sdwa@v1': 0x8080, 'packed_bfe@v1': 0x8200, 'packed_alias@v1': 0x8100, 'pair_then_packed@v2': 0x8002, 'two_pairs': 0x0012, 'no_inputs': 0x0004, 'write_first': 0x0001, 'packed_misfire': 0x8100, - 'loop_ambiguous': 0x0001, 'unsat_v40': 0x0001} + 'loop_ambiguous': 0x0001, 'unsat_v40': 0x0001, + 'diamond_skip': 0x0082, 'diamond_both': 0x0001} +# A decoy mask that omits v2: two registers, v0 and v1. It is tight for diamond_skip unless v2 is live-in. +DIAMOND_DECOY = 0x0001 def empty_contract(): @@ -164,7 +173,9 @@ def unit_checks(): 'no_inputs': ([], [], []), 'write_first': ([], [], []), 'cmp_and_exp': ([1, 2, 3, 4], [], []), 'packed_misfire': ([0, 1], [], [0]), 'overwritten': ([1], [], []), 'loop_ambiguous': ([], [], []), 'loop_definite': ([1], [], []), 'loop_rmw': ([1, 5], [], []), - 'alias_block': ([0, 1], [], []), 'alias_straight': ([0, 1], [0], []), 'unsat_v40': ([40], [], []), + # The branch skips the move into v4, so v4 can reach the interpolation with its entry value. + 'alias_block': ([0, 1, 4], [], []), 'alias_straight': ([0, 1], [0], []), 'unsat_v40': ([40], [], []), + 'diamond_skip': ([1, 2], [], []), 'diamond_both': ([1], [], []), } for name, code in SHADERS.items(): assert sets(contract_of(code)) == expected[name], (name, sets(contract_of(code))) @@ -172,6 +183,30 @@ def unit_checks(): assert all(not contract_of(code).ambiguous for name, code in SHADERS.items() if name != 'loop_ambiguous') print('loop rule: loop-carried v5 is ambiguous, not live-in; unwritten and read-modify-write ' 'loop registers stay live-in; no alias across a block boundary') + skip = contract_of(SHADERS['diamond_skip']) + assert S.consistent(skip, DIAMOND_DECOY) == (False, 'C1 coverage'), S.consistent(skip, DIAMOND_DECOY) + assert S.consistent(skip, MASKS['diamond_skip']) == (True, '') + assert S.Judge(skip).code(DIAMOND_DECOY) & S.RULE_MASK == 1 + print('join rule: a write skipped by a forward branch leaves v2 live-in at the join, so the decoy ' + 'mask without v2 fails C1; written on both edges, v2 is not live-in') + + # Two cases from review: the I/J pair inputs and the context-index tags, against literal values. + pair_starts = {0, 1, 2, 4, 5, 6} # PERSP_SAMPLE/CENTER/CENTROID, LINEAR_SAMPLE/CENTER/CENTROID + for bit in range(16): + pair = S.Contract(frozenset({0}), frozenset({0}), frozenset()) + expected_ok = bit in pair_starts + assert S.consistent(pair, 1 << bit) == (expected_ok, '' if expected_ok else 'C2 pairs'), bit + assert (S.Judge(pair).code(1 << bit) & S.RULE_MASK == 0) == expected_ok, bit + words = [7, 0x1B3, 0x8100, 0x8102, 0x9] # a context run: index, ena, addr + assert S.tag_values(words) == {'tag:ctxrun': (0x8100, 0x8102)}, S.tag_values(words) + words = [0x1B4, 0x0002, 0x1B3, 0x0003, 0] # separate tags, addr before ena + assert S.tag_values(words) == {'tag:ctxindex': (0x0003, 0x0002), 'tag:ctxrun': (0x0003, 0)}, \ + S.tag_values(words) + words = [0x286D0, 0x0012, 0xA1B4, 0x0102, 0x286CC, 0x0010, 0xA1B3, 0x0100] + assert S.tag_values(words) == {'tag:byteaddr': (0x0010, 0x0012), 'tag:mmindex': (0x0100, 0x0102)}, \ + S.tag_values(words) + print('tables: bit 0, 1, 2, 4, 5 and 6 start an I/J pair and the other ten do not; byte-address, ' + 'context-index, context-run and mm tags read their own enable and address words') with mock.patch.object(G, 'decode', side_effect=G.Unsupported('undecodable word at +0x4: fixture')): try: S.make_record('0', b'', {}) @@ -478,6 +513,24 @@ def tagged(index, name): print('loop control: a loop-carried register is ambiguous and the planted location stays the unique ' 'full match; an unsatisfiable contract (v40) is excluded and counted') + # Diamond decoy: header +16/+20 holds the same masks as +8/+12, except that the diamond_skip + # shader gets a mask without v2 there. With v2 missed at the join the decoy is tight for that + # shader and wins; with v2 live-in it fails C1 there. + def diamond_maker(index, name): + words = list(struct.unpack('<12I', header_words(index, MASKS[name], MASKS[name]))) + words[4] = words[5] = DIAMOND_DECOY if name == 'diamond_skip' else MASKS[name] + return blob_with_header(w(*words), SHADERS[name]) + build(tmp / 'l', diamond_maker, names=ORDER + ('diamond_skip', 'diamond_both')) + text, data = scan(tmp / 'l', tmp, 'l') + assert data['verdict'] == 'unique full match ps.header pair32@8', text + top = data['candidates'][0] + assert (top['candidate'], top['tight'], top['inconsistent']) == ('pair32@8', 8, 0), top + decoy = by_name(data, 'ps.header', 'pair32@16') + assert not decoy['full_match'] and (decoy['inconsistent'], decoy['fail_c1']) == (1, 1), decoy + assert decoy['example_inconsistent'][1] == 'C1 coverage' and decoy['rank'] > top['rank'], decoy + print('diamond decoy: the mask without v2 fails C1 for the branch-skipped write; the planted ' + 'location stays the unique full match with 8 tight') + # Packed lens: two full matches tie on tight; only the real one agrees on every packed split. alternatives = {'pair_then_packed@v2': 0x0102, 'packed_only@v1': 0x0300, 'two_pairs': 0x0012, 'no_inputs': 0x0004} @@ -514,7 +567,8 @@ def lens_maker(index, name): capture_case(tmp) determinism(tmp) - count = reference_check(tmp / 'a') + reference_check(tmp / 'd') + reference_check(tmp / 'h') + count = (reference_check(tmp / 'a') + reference_check(tmp / 'd') + reference_check(tmp / 'h') + + reference_check(tmp / 'l')) print('reference: %d candidate summaries equal a direct per-candidate evaluation' % count) # Usage errors exit 2; an empty directory still completes. diff --git a/tests/startup_pso_recipe_check.cpp b/tests/startup_pso_recipe_check.cpp new file mode 100644 index 0000000000..267c55b300 --- /dev/null +++ b/tests/startup_pso_recipe_check.cpp @@ -0,0 +1,173 @@ +// Device-free checks for the opt-in translated-PSO recipe format. The runtime reads the same +// serializer/parser and reconstructs the desktop pipeline description from these fields. +#include "startup_stubs/pso_recipe.h" + +#include <cstdio> +#include <cstring> +#include <string> + +namespace { +int failures = 0; + +void expect(bool condition, const char* what) +{ + std::printf("%s: %s\n", what, condition ? "ok" : "MISMATCH"); + failures += !condition; +} + +x2w_startup::PsoRecipe sample_recipe() +{ + x2w_startup::PsoRecipe recipe; + recipe.translation_key = 0x1122334455667788ull; + recipe.target_count = 2; + recipe.target_formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + recipe.target_formats[1] = DXGI_FORMAT_R16G16B16A16_FLOAT; + recipe.dsv_format = DXGI_FORMAT_D32_FLOAT; + recipe.indexed_rect = true; + recipe.use_depth_stencil = true; + recipe.has_rasterizer = true; + recipe.blend = x2w_startup::default_pso_blend(); + recipe.blend.IndependentBlendEnable = TRUE; + recipe.blend.RenderTarget[0].BlendEnable = TRUE; + recipe.blend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; + recipe.blend.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + recipe.blend.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; + recipe.blend.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; + recipe.blend.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + recipe.blend.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; + recipe.blend.RenderTarget[0].RenderTargetWriteMask = 0x9; + recipe.blend.RenderTarget[1].RenderTargetWriteMask = 0x3; + recipe.depth_stencil.DepthEnable = TRUE; + recipe.depth_stencil.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + recipe.depth_stencil.DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL; + recipe.depth_stencil.StencilEnable = TRUE; + recipe.depth_stencil.StencilReadMask = 0x7f; + recipe.depth_stencil.StencilWriteMask = 0x0f; + recipe.depth_stencil.FrontFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_INCR, D3D12_STENCIL_OP_REPLACE, + D3D12_COMPARISON_FUNC_EQUAL}; + recipe.depth_stencil.BackFace = {D3D12_STENCIL_OP_ZERO, D3D12_STENCIL_OP_DECR, D3D12_STENCIL_OP_KEEP, + D3D12_COMPARISON_FUNC_ALWAYS}; + recipe.rasterizer = x2w_startup::default_pso_rasterizer(); + recipe.rasterizer.CullMode = D3D12_CULL_MODE_BACK; + recipe.rasterizer.FrontCounterClockwise = TRUE; + recipe.rasterizer.DepthBias = -3; + recipe.rasterizer.DepthBiasClamp = 0.5f; + recipe.rasterizer.SlopeScaledDepthBias = -1.25f; + recipe.rasterizer.MultisampleEnable = TRUE; + recipe.sample_mask = 0xf0f0u; + recipe.sample_count = 1; + recipe.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + recipe.state_key = x2w_startup::pso_recipe_state_key(recipe); + return recipe; +} + +std::string replace_state_key(std::string text) +{ + const std::string marker = "state 0x"; + const std::size_t at = text.find(marker); + if (at == std::string::npos) return text; + for (std::size_t i = 0; i < 16; ++i) text[at + marker.size() + i] = '0'; + return text; +} +} // namespace + +int main() +{ + using namespace x2w_startup; + const PsoRecipe recipe = sample_recipe(); + const std::string text = serialize_pso_recipe(recipe); + expect(text.rfind("x2w-pso-recipe 1\n", 0) == 0, "serialized record starts with version 1"); + expect(text.size() <= pso_recipe_file_limit, "one record stays inside the file-size bound"); + + const PsoRecipeParseResult parsed = parse_pso_recipe_file(text); + expect(parsed.rejected == 0 && parsed.recipes.size() == 1, "record parses"); + if (parsed.recipes.size() == 1) { + expect(serialize_pso_recipe(parsed.recipes[0]) == text, "serializer/parser round-trips byte-for-byte"); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.NumRenderTargets = 8; + desc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; + desc.SampleMask = 0; + desc.SampleDesc.Count = 4; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; + apply_pso_recipe(parsed.recipes[0], desc); + expect(same_pso_blend(desc.BlendState, recipe.blend), "blend state recreated"); + expect(same_pso_depth(desc.DepthStencilState, recipe.depth_stencil), "depth-stencil state recreated"); + expect(same_pso_rasterizer(desc.RasterizerState, recipe.rasterizer), "rasterizer state recreated"); + expect(desc.SampleMask == recipe.sample_mask && desc.SampleDesc.Count == recipe.sample_count, + "sample mask and count recreated"); + expect(desc.PrimitiveTopologyType == recipe.topology, "topology recreated"); + expect(desc.NumRenderTargets == recipe.target_count && desc.RTVFormats[0] == recipe.target_formats[0] && + desc.RTVFormats[1] == recipe.target_formats[1] && desc.RTVFormats[2] == DXGI_FORMAT_UNKNOWN && + desc.DSVFormat == recipe.dsv_format, + "target formats and DSV recreated"); + } + + PsoRecipe second = recipe; + second.target_count = 1; + second.target_formats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + second.target_formats[1] = DXGI_FORMAT_UNKNOWN; + second.dsv_format = DXGI_FORMAT_UNKNOWN; + second.indexed_rect = false; + second.state_key = pso_recipe_state_key(second); + const std::string two_records = text + serialize_pso_recipe(second); + const PsoRecipeParseResult both = parse_pso_recipe_file(two_records); + expect(both.rejected == 0 && both.recipes.size() == 2, "two appended records parse"); + if (both.recipes.size() == 2) + expect(serialize_pso_recipe(both.recipes[0]) + serialize_pso_recipe(both.recipes[1]) == two_records, + "two-record file round-trips byte-for-byte"); + + const PsoRecipeParseResult corrupted = parse_pso_recipe_file(replace_state_key(text)); + expect(corrupted.recipes.empty() && corrupted.rejected == 1, "corrupt state key is rejected"); + + std::string unknown = text; + unknown.replace(0, std::strlen("x2w-pso-recipe 1"), "x2w-pso-recipe 2"); + const PsoRecipeParseResult future = parse_pso_recipe_file(unknown); + expect(future.recipes.empty() && future.rejected == 1, "unknown recipe version is rejected"); + + const PsoRecipeParseResult oversized = parse_pso_recipe_file(std::string(pso_recipe_file_limit + 1, 'x')); + expect(oversized.recipes.empty() && oversized.rejected == 1, "oversized recipe file is rejected"); + + DXGI_FORMAT wrong_formats[2] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT}; + expect(pso_recipe_targets_match(recipe, 2, recipe.target_formats, recipe.dsv_format), + "matching target formats and DSV accepted"); + expect(!pso_recipe_targets_match(recipe, 2, wrong_formats, recipe.dsv_format), "target-format mismatch rejected"); + expect(!pso_recipe_targets_match(recipe, 2, recipe.target_formats, DXGI_FORMAT_D24_UNORM_S8_UINT), + "DSV-format mismatch rejected"); + + // The writer stops where the parser stops. At 63 records the next append is still readable; + // at 64 it would become the record the next process rejects, so it is refused instead. + std::string sixty_three; + for (unsigned i = 0; i < pso_recipe_record_limit - 1; ++i) sixty_three += text; + const PsoRecipeParseResult at_63 = parse_pso_recipe_file(sixty_three); + expect(at_63.rejected == 0 && at_63.recipes.size() == pso_recipe_record_limit - 1, "63 records parse"); + expect(pso_recipe_append_allowed(sixty_three, text), "63 records accept one more append"); + expect(pso_recipe_append_allowed("", text), "an empty file accepts the first record"); + + const std::string sixty_four = sixty_three + text; + const PsoRecipeParseResult at_64 = parse_pso_recipe_file(sixty_four); + expect(at_64.rejected == 0 && at_64.recipes.size() == pso_recipe_record_limit, "64 records parse"); + expect(!pso_recipe_append_allowed(sixty_four, text), "64 records refuse a 65th append"); + + const PsoRecipeParseResult at_65 = parse_pso_recipe_file(sixty_four + text); + expect(at_65.recipes.size() == pso_recipe_record_limit && at_65.rejected == 1 && + at_65.error == "recipe record limit reached", + "65 records reject the extra record"); + expect(!pso_recipe_append_allowed(replace_state_key(text), text), "a malformed file is not appended to"); + expect(!pso_recipe_append_allowed(std::string(pso_recipe_file_limit, 'x'), text), + "an unparseable full-size file is not appended to"); + + // A record without its final LF still parses, but appending would put `end` and the next + // header on one line. The writer refuses and leaves the parseable record intact. + const std::string no_final_lf = text.substr(0, text.size() - 1); + const PsoRecipeParseResult parsed_no_lf = parse_pso_recipe_file(no_final_lf); + expect(parsed_no_lf.rejected == 0 && parsed_no_lf.recipes.size() == 1, + "a record without a final LF still parses"); + expect(!pso_recipe_append_allowed(no_final_lf, text), "a file without a final LF refuses an append"); + const PsoRecipeParseResult after_refusal = parse_pso_recipe_file(no_final_lf); + expect(after_refusal.rejected == 0 && after_refusal.recipes.size() == 1, + "the earlier record remains readable after the refused append"); + + std::printf("startup pso recipe checks: %d failed\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_rect_gap.cpp b/tests/startup_rect_gap.cpp new file mode 100644 index 0000000000..626111ef27 --- /dev/null +++ b/tests/startup_rect_gap.cpp @@ -0,0 +1,121 @@ +// X2W_TEST_RECT_GAP (#3131): the eight-vertex quad-and-edge-ring draw. +// +// Every vertex record is 12 bytes: a binary32 mask at +0, then XY at +4. Two vertex-buffer views name +// the same records, slot 0 (TEXCOORD, R32_FLOAT at offset 0, the mask) and slot 1 (POSITION, +// R32G32_FLOAT at offset 4), both with a 12-byte stride. Records 0-2 are the edge ring that encloses the +// quad (mask 0) and 3-5 the inner quad (mask 1); 6 and 7 are their fourth corners, so a rectangle list of +// six vertices and an indexed triangle list built from the same bytes describe the same four triangles. +// The ring is drawn first, so the quad's diagonal stays visible. A mask-controlled pixel shader paints +// the quad red and the ring green; a constant-colour pixel shader paints whatever the geometry covers red. +// +// triangle R16 indexed triangle list, ring then quad (12 indices: 0-1-2, 0-2-6, 3-4-5, 3-5-7) +// triangle-copy the same draw from a vertex stream and an index view that no placed buffer holds, +// so the recording-time vertex read and the index scan size the copy +// rect non-indexed rectangle list of six vertices (the ring and the quad) +// rect8 the same rectangle list with eight vertices, two of them unused +// rect8-copy the eight-vertex rectangle list from an unregistered vertex stream +// none no draw: the cleared target, read back through the same path +// +// X2W_TEST_RECT_GAP_BYTES names a file that receives the vertex bytes the draw bound, then the index +// bytes it bound, so the check can compare them with what it wrote. +#include <d3d12.h> + +#include <array> +#include <cmath> +#include <cstdint> +#include <cstring> +#include <fstream> + +#include "startup_stream_setup.h" + +namespace { +using Word = std::uint64_t; +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } + +struct Vertex { + float mask, x, y; +}; +// Each rectangle is three corners clockwise on screen (bottom-left, top-left, top-right); the fourth +// corner of a rectangle is v0 + v2 - v1 and is stored at 6 and 7. +constexpr std::array<Vertex, 8> vertices{{ + {0.0f, -1.0f, -1.0f}, {0.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 1.0f}, // ring + {1.0f, -0.75f, -0.625f}, {1.0f, -0.75f, 0.625f}, {1.0f, 0.75f, 0.625f}, // quad + {0.0f, 1.0f, -1.0f}, {1.0f, 0.75f, -0.625f}, // the fourth corners +}}; +constexpr std::array<std::uint16_t, 12> indices{{0, 1, 2, 0, 2, 6, 3, 4, 5, 3, 5, 7}}; + +// Memory no placed buffer covers: the draw then copies the bytes it needs while recording. +alignas(64) unsigned char unplaced[256]; +} + +int draw_rect_gap(void* guest, void* list) +{ + char mode[32]{}; + if (!GetEnvironmentVariableA("X2W_TEST_RECT_GAP", mode, sizeof(mode))) return 2; + // The stream harness scissors an 8x4 target to its left half by default; this draw covers the whole + // target, so both sides of each diagonal are read back. + const D3D12_RECT whole{0, 0, 8, 4}; + invoke(list, 22, 1, arg(&whole)); + if (std::strcmp(mode, "none") == 0) return 0; + const bool indexed = std::strcmp(mode, "triangle") == 0 || std::strcmp(mode, "triangle-copy") == 0; + const bool short_view = std::strcmp(mode, "triangle-short") == 0; + const bool copied = std::strstr(mode, "-copy") != nullptr; + const bool rotated = std::strstr(mode, "rotated") != nullptr; + const bool indexed_path = indexed || short_view || std::strcmp(mode, "triangle-rotated") == 0; + if (!indexed_path && std::strncmp(mode, "rect", 4) != 0) return 2; + + // A rotation keeps the parallelogram, so v0 + v2 - v1 is still its fourth corner, but no corner shares + // an axis with its two neighbours any more. + std::array<Vertex, 8> records = vertices; + if (rotated) { + const float angle = 0.2617993877991494f; // 15 degrees + const float c = std::cos(angle), s = std::sin(angle); + for (Vertex& v : records) { + const float x = v.x, y = v.y; + v.x = c * x - s * y; + v.y = s * x + c * y; + } + } + + void* const placed = VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!placed) return 43; + unsigned char* const vertex_bytes = copied ? unplaced : static_cast<unsigned char*>(placed); + unsigned char* const index_bytes = static_cast<unsigned char*>(placed) + 0x2000; + std::memcpy(vertex_bytes, records.data(), sizeof(records)); + std::memcpy(index_bytes, indices.data(), sizeof(indices)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 0x10000; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* resource = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, arg(static_cast<unsigned char*>(placed)), arg(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&resource))))) return 44; + // triangle-short declares a three-record view although its indices name records up to seven: desktop IA + // reads the bytes the indices name, so the quad still has to be covered. + const UINT view_bytes = short_view ? 3 * sizeof(Vertex) : static_cast<UINT>(sizeof(records)); + const D3D12_VERTEX_BUFFER_VIEW views[2] = { + {arg(vertex_bytes), view_bytes, sizeof(Vertex)}, {arg(vertex_bytes), view_bytes, sizeof(Vertex)}}; + invoke(list, 48, 0, 2, arg(views)); + if (indexed_path) { + // The quad's indices, 3-4-5 and 3-5-7, follow the ring's six. + const UINT index_offset = short_view ? 12 : 0; + const D3D12_INDEX_BUFFER_VIEW index_view{arg(index_bytes + index_offset), + static_cast<UINT>(sizeof(indices)) - index_offset, + DXGI_FORMAT_R16_UINT}; + invoke(list, 47, arg(&index_view)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 13, static_cast<Word>(std::size(indices)) - index_offset / 2, 1, 0, 0, 0); + } else { + invoke(list, 20, 17 /* D3D_PRIMITIVE_TOPOLOGY_RECTLIST, the console topology value */); + invoke(list, 12, std::strncmp(mode, "rect8", 5) == 0 ? 8 : 6, 1); + } + char dump[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableA("X2W_TEST_RECT_GAP_BYTES", dump, MAX_PATH); + if (length && length < MAX_PATH) { + std::ofstream file(dump, std::ios::binary); + file.write(reinterpret_cast<const char*>(vertex_bytes), sizeof(records)); + if (indexed_path) file.write(reinterpret_cast<const char*>(index_bytes), sizeof(indices)); + } + return 0; +} diff --git a/tests/startup_rect_gap_check.py b/tests/startup_rect_gap_check.py new file mode 100644 index 0000000000..690429a37c --- /dev/null +++ b/tests/startup_rect_gap_check.py @@ -0,0 +1,283 @@ +"""The eight-vertex quad-and-edge-ring draw of #3131, with a 12-byte vertex record and XY at +4. + +Source-built gfx1013 code only. The vertex stage calls the driver's fetch routine: two records, POSITION +(register 0, mask 0x7) read as R32G32_FLOAT at +4 of a 12-byte record and TEXCOORD (register 1, mask 0x1) +read as R32_FLOAT at +0. The stream's input layout therefore names slot 0 TEXCOORD R32_FLOAT at offset 0 and +slot 1 POSITION R32G32_FLOAT at offset 4, and both views name the same records with a 12-byte stride. + +Records 0-2 are the edge ring that encloses the quad (mask 0) and 3-5 the inner quad (mask 1); 6 and 7 are +their fourth corners, so a rectangle list of six vertices and an indexed triangle list built from the same +bytes describe the same four triangles. The ring is drawn first, so the quad's diagonal stays visible. Two +pixel shaders read the same draw: + mask: interpolates TEXCOORD (the mask) and paints the quad red and the ring green, so every pixel + says which region covered it and a missing triangle leaves the clear colour. + constant: exports opaque red without reading an input, so a gap here would be a coverage gap and a gap + only in the mask picture would be an attribute or interpolation gap. + +Draws, each read back as 32 RGBA pixels: + triangle R16 indexed triangle list, ring then quad + triangle-copy the same draw from a stream and index view no placed buffer holds: the recording-time + vertex read and the index scan size what is copied + rect non-indexed rectangle list of six vertices + rect8 the eight-vertex rectangle list (the last two vertices are not part of a rectangle) + rect8-copy the eight-vertex rectangle list from an unregistered stream + none no draw: the cleared target +The rect modes use the six-vertex expansion the vertex stage applies to a rectangle list. With +X2W_TEST_RASTERIZER=back the same picture must come back with back-face culling on, and =back-ccw +(counter-clockwise front faces) must cull the whole draw: that is the winding control. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import zlib +import math + +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import vop1, vop2 + +WIDTH, HEIGHT = 8, 4 +BLUE, RED, GREEN = bytes((0, 0, 255, 255)), bytes((255, 0, 0, 255)), bytes((0, 255, 0, 255)) +VS_BASE, PS_BASE = 0x2f8, 0xef8 +FETCH_CALL, PREFETCH, WAIT_VM, ENDPGM = 0xbe842104, 0xbfa00003, 0xbf8c3f70, 0xbf810000 + +# mask, x, y per 12-byte record. Each rectangle is three corners clockwise on screen; 6 and 7 hold the +# fourth corner v0 + v2 - v1, which the indexed list names and the rectangle list derives. +VERTICES = [(0.0, -1.0, -1.0), (0.0, -1.0, 1.0), (0.0, 1.0, 1.0), + (1.0, -0.75, -0.625), (1.0, -0.75, 0.625), (1.0, 0.75, 0.625), + (0.0, 1.0, -1.0), (1.0, 0.75, -0.625)] +INDICES = [0, 1, 2, 0, 2, 6, 3, 4, 5, 3, 5, 7] +TRIANGLES = [(0, 1, 2), (0, 2, 6), (3, 4, 5), (3, 5, 7)] +ROTATED = math.radians(15.0) +LAYOUT_TEXT = "ia1 2\nTEXCOORD 0 41 0 0 0 0\nPOSITION 0 16 1 4 0 0\n" +LAYOUT_LINE = "x2w-draw stream input layout: 2 elements (format/slot/offset/class) 41/0/0/0 16/1/4/0" + + +def signature(tag, entries): + names, body = b"", b"" + first = 8 + 32 * len(entries) + for name, index, register, system, mask in entries: + body += struct.pack("<6IBBHI", 0, first + len(names), index, system, 3, register, mask, mask, 0, 0) + names += name.encode("ascii") + b"\0" + data = struct.pack("<II", len(entries), 8) + body + names + return tag + struct.pack("<I", len(data)) + data + + +def container(stage, words, base, sections, table): + """A container with an FSSM header of `base` bytes; `table` maps header offsets to bytes.""" + code = struct.pack("<%dI" % len(words), *words) + extent = (40 + len(code) + 4 + 15) & ~15 + image = bytearray(base + extent) + image[:4] = b"FSSM" + struct.pack_into("<I", image, 4, 0x101) + struct.pack_into("<QQ", image, 192, base, extent) + struct.pack_into("<Q", image, 232, len(image)) + for offset, data in table.items(): + image[offset:offset + len(data)] = data + image[base + 40:base + 40 + len(code)] = code + padding = (len(image) - base - 40 - len(code)) // 4 + image[base + 40 + len(code):] = struct.pack("<I", 0xbf9f0000) * padding + native = b"XBCH" + bytes(12) + struct.pack("<II", len(image), 0) + zlib.compress(bytes(image)) + program = struct.pack("<HH", 0, stage) + bytes(20) + b"XDAT" + struct.pack("<5I", 1, 0, 13, 48, len(native)) + native + parts = sections + [b"DXIL" + struct.pack("<I", len(program)) + program] + offsets, at = [], 32 + 4 * len(parts) + for part in parts: + offsets.append(at) + at += len(part) + return b"DXBC" + bytes(16) + struct.pack("<3I", 1, at, len(parts)) + struct.pack("<%dI" % len(parts), *offsets) \ + + b"".join(parts) + + +def vertex(): + # Fetch POSITION into v4-v6 (mask 0x7, count 3) and TEXCOORD into v8; export pos0 from v4-v7 and + # param0 from v8. + records = [(6, 0, 0x7, 4, 2), (6, 1, 0x1, 8, 0)] + words = [FETCH_CALL, PREFETCH, vop1(1, 7, 242), WAIT_VM, + 0xf80008cf, 0x07060504, # exp pos0 v4, v5, v6, v7 + 0xf800020f, 0x08080808, # exp param0 v8, v8, v8, v8 + ENDPGM] + table = {0x138: b"".join(bytes(r) for r in records), 0x1d8: struct.pack("<I", len(records)), + 0x1dc: bytes((6, 1, 0, 0, 0, 0)), 0x29c: struct.pack("<I", 1)} + outputs = [("SV_POSITION", 0, 0, 1, 0xf), ("TEXCOORD", 0, 1, 0, 0x1)] + return container(1, words, VS_BASE, [signature(b"ISG1", [("POSITION", 0, 0, 0, 0x7), ("TEXCOORD", 0, 1, 0, 0x1)]), + signature(b"OSG1", outputs)], table) + + +def pixel(mask): + if not mask: + words = [vop1(1, 0, 128), vop1(1, 1, 242), 0xf800180f, 0x01000001, ENDPGM] # opaque red + return container(0, words, PS_BASE, [signature(b"ISG1", [("SV_POSITION", 0, 0, 1, 0xf)])], + {0x238: struct.pack("<I", 0)}) + # v2 = interpolated TEXCOORD.x (the mask); vcc = 0.5 > mask; red where the mask is 1, green where it is 0. + words = [0xc8080000, 0xc8090001, vop1(1, 0, 128), vop1(1, 1, 242), + 0x7c0804f0, # v_cmp_gt_f32 vcc_lo, 0.5, v2 + vop2(1, 3, 256 + 1, 0), # v3 = vcc ? v0 : v1 (red) + vop2(1, 4, 256 + 0, 1), # v4 = vcc ? v1 : v0 (green) + 0xf800180f, 0x01000403, # exp mrt0 v3, v4, v0, v1 done vm + ENDPGM] + inputs = [("SV_POSITION", 0, 0, 1, 0xf), ("TEXCOORD", 0, 2, 0, 0x1)] + return container(0, words, PS_BASE, [signature(b"ISG1", inputs)], + {0x138: bytes((6, 2, 0x1, 0, 0, 0, 2, 2)), 0x238: struct.pack("<I", 1)}) + + +EMPTY_ROOT = (b"DXBC" + bytes(16) + struct.pack("<4I", 1, 68, 1, 36) + b"RTS0" + struct.pack("<I", 24) + + struct.pack("<6I", 1, 0, 24, 0, 24, 0)) + + +def cross(a, b, p): + return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) + + +def placed(rotated): + """The vertex records a mode writes: the rotation the fixture applies to a rect-* / triangle-* run.""" + if not rotated: + return VERTICES + c, s = math.cos(ROTATED), math.sin(ROTATED) + return [(m, c * x - s * y, s * x + c * y) for m, x, y in VERTICES] + + +def region(x, y, rotated=False): + """The last triangle in draw order that holds pixel centre (x, y), or None. Asserts no centre is on an edge.""" + records = placed(rotated) + p = ((2.0 * x + 1.0) / WIDTH - 1.0, 1.0 - (2.0 * y + 1.0) / HEIGHT) + hit = None + for triangle in TRIANGLES: + points = [records[i][1:] for i in triangle] + edges = [cross(points[i], points[(i + 1) % 3], p) for i in range(3)] + assert min(abs(e) for e in edges) > 1e-3, f"pixel ({x}, {y}) lies on an edge of {triangle}" + if not (any(e < 0 for e in edges) and any(e > 0 for e in edges)): + hit = "quad" if triangle[0] >= 3 else "ring" + return hit + + +def expected(mask, rotated=False): + out = bytearray() + for y in range(HEIGHT): + for x in range(WIDTH): + covered = region(x, y, rotated) + out += (BLUE if covered is None else RED if (covered == "quad" or not mask) else GREEN) + return bytes(out) + + +def describe(image): + """Counts of each colour, so a failure says which region moved.""" + names = {BLUE: "clear", RED: "red", GREEN: "green"} + counts = {} + for i in range(0, len(image), 4): + name = names.get(image[i:i + 4], image[i:i + 4].hex()) + counts[name] = counts.get(name, 0) + 1 + return ", ".join(f"{n} {c}" for n, c in sorted(counts.items())) + + +def first_difference(actual, want): + for i in range(0, len(want), 4): + if actual[i:i + 4] != want[i:i + 4]: + return "pixel (%d, %d) is %s, expected %s" % (i // 4 % WIDTH, i // 4 // WIDTH, + actual[i:i + 4].hex(), want[i:i + 4].hex()) + return None + + +class Run: + def __init__(self, directory, consumer, mode, mask, rasterizer=None): + directory.mkdir(parents=True) + self.cache = directory / "cache" + self.cache.mkdir() + self.output = directory / "pixels" + self.bound = directory / "bound" + vs, ps, root = directory / "vs", directory / "ps", directory / "root" + vs.write_bytes(vertex()) + ps.write_bytes(pixel(mask)) + self.args = [consumer, str(vs), str(ps), str(root)] + self.env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(self.cache), X2W_TEST_INPUT_LAYOUT="gradient", + X2W_TEST_RECT_GAP=mode, X2W_TEST_RECT_GAP_BYTES=str(self.bound)) + self.env.setdefault("X2W_D3D12_DEBUG", "0") + if rasterizer: + self.env["X2W_TEST_RASTERIZER"] = rasterizer + else: + self.env.pop("X2W_TEST_RASTERIZER", None) + subprocess.run(self.args, env=self.env, check=True) + self.key = None + if mode != "none": + requests = sorted(self.cache.glob("req_*.a")) + assert len(requests) == 1, requests + self.key = int(requests[0].name[4:20], 16) + + def translate(self): + status = gfx2hlsl.translate_request(str(self.cache), self.key) + assert status == "ok", status + return self.cache / ("%016x.vs.hlsl" % self.key) + + def draw(self, backend): + result = subprocess.run(self.args + [backend, str(self.output)], env=self.env, capture_output=True, text=True) + for line in result.stderr.splitlines(): + if line.startswith("adapter=") or "debug layer:" in line: + print(" " + line) + return result + + +def check(directory, consumer, backend, rasterizer=None): + # The clear colour, before any draw. + plain = Run(directory / "none", consumer, "none", True) + result = plain.draw(backend) + if result.returncode == 77: + print("No D3D12 feature-level 12 adapter") + return 77 + if result.returncode: + raise RuntimeError(f"none failed on {backend}: {result.returncode}\n{result.stderr}") + if plain.output.read_bytes() != BLUE * (WIDTH * HEIGHT): + raise AssertionError("the cleared target is not the expected blue: " + describe(plain.output.read_bytes())) + print(f"{backend} none: 32 clear pixels, pre-draw state exact") + + for mode, mask in (("triangle", True), ("triangle", False), ("triangle-copy", True), + ("rect", True), ("rect8", True), ("rect8-copy", True), ("rect8", False), + ("triangle-rotated", True), ("rect-rotated", True)): + label = f"{mode} {'mask' if mask else 'constant'}" + rotated = "rotated" in mode + run = Run(directory / (label.replace(" ", "_") + ("_" + rasterizer if rasterizer else "")), consumer, + mode, mask, rasterizer) + hlsl = run.translate() + text = hlsl.read_text() + layout = (run.cache / ("req_%016x.ia" % run.key)).read_bytes() + assert layout == LAYOUT_TEXT.encode(), layout + # POSITION (slot 1, R32G32_FLOAT at +4) and the mask (slot 0, R32_FLOAT at +0), each scaled by its + # own stream stride. + for line in ("a = (vid + ud1) * ud3 + 4;", "a = (vid + ud1) * ud4 + 0;"): + assert " " + line + "\n" in text, line + "\n" + text + if mode.startswith("rect"): + for line in ("uint first = (vid / 6) * 3, corner = vid % 6;", "o.pos = p.pos + r.pos - q.pos;"): + assert line in text, line + "\n" + text + result = run.draw(backend) + if result.returncode == 77: + print("No D3D12 feature-level 12 adapter") + return 77 + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"{label} failed on {backend}: {result.returncode}\n{result.stderr}") + if LAYOUT_LINE not in result.stderr: + raise AssertionError("missing layout diagnostic:\n" + result.stderr) + bound = run.bound.read_bytes() + records = placed(rotated) + got = struct.unpack("<24f", bound[:96]) + for i, (mask_value, x, y) in enumerate(records): + for name, actual, want in (("mask", got[3 * i], mask_value), ("x", got[3 * i + 1], x), + ("y", got[3 * i + 2], y)): + if abs(actual - want) > 1e-6: + raise AssertionError(f"{label}: record {i} {name} is {actual}, expected {want}") + if "triangle" in mode and bound[96:] != struct.pack("<%dH" % len(INDICES), *INDICES): + raise AssertionError(f"{label}: bound indices {bound[96:].hex()}") + actual = run.output.read_bytes() + want = expected(mask, rotated) + difference = first_difference(actual, want) + if difference: + raise AssertionError(f"{label}: {difference} ({describe(actual)})") + print(f"{backend} {label}: 32 pixels exact ({describe(actual)}); 8 records of 12 bytes bound") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + args = sys.argv[1:] + rasterizer = args[2] if len(args) > 2 else None + sys.exit(check(Path(temp), *args[:2], rasterizer=rasterizer)) diff --git a/tests/startup_rect_geometry.cpp b/tests/startup_rect_geometry.cpp new file mode 100644 index 0000000000..5846fce089 --- /dev/null +++ b/tests/startup_rect_geometry.cpp @@ -0,0 +1,411 @@ +// The shared rectangle-expansion rule of src/startup_stubs/indexed_rect_geometry.h on a desktop device (#3131). +// +// The translated indexed rectangle draw binds this geometry stage, and the runtime compiles it from the +// vertex and pixel bytecode of the same translation. This fixture compiles the same rule and draws one +// rectangle that a rectangle list names with three corners, with back-face culling on, so the coverage it +// emits is measured directly: +// axis bottom-left, top-left, top-right: the corner test always finds a corner that shares an axis +// with each neighbour, and the fourth corner is v0 + v2 - v1 +// swung bottom-left, top-right, top-left: the same three corners in another order, which the stage +// normalises to the same square +// rotated the square turned by 15 degrees: still a parallelogram whose fourth corner is v0 + v2 - v1 after +// the right-angle corner is identified, and the corner the non-indexed path derives in the vertex +// stage. No corner shares an axis with its neighbours, so the axis test cannot identify it. +// Each vertex record is 12 bytes (a mask at +0, XY at +4) and both orders must cover the pixels the two +// triangles of the literal rule cover. Without an adapter argument the fixture uses WARP. `--native-gs` +// replaces the HLSL stage with a geometry CSO emitted from src/gfx1013_rect_geometry.cpp. +#include <d3d12.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <algorithm> +#include <array> +#include <cmath> +#include <cstdio> +#include <cstring> +#include <fstream> +#include <iterator> +#include <string> +#include <utility> +#include <vector> + +#include "startup_stubs/indexed_rect_geometry.h" + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT width = 8, height = 4; +constexpr DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; +// R8G8B8A8 words: the low byte is red, then green and blue. +constexpr std::uint32_t red = 0xff0000ff, blue = 0xffff0000; + +struct Vertex { + float mask, x, y; +}; +static_assert(sizeof(Vertex) == 12); + +// The three corners of a rectangle, clockwise on screen (bottom-left, top-left, top-right). +constexpr std::array<Vertex, 3> corners{{ + {1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, 1.0f}, {1.0f, 1.0f, 1.0f}}}; + +int failures; +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +HRESULT compile(const char* source, const char* profile, ComPtr<ID3DBlob>& blob) +{ + ComPtr<ID3DBlob> errors; + const HRESULT hr = D3DCompile(source, std::strlen(source), "rect_geometry_fixture", nullptr, nullptr, "main", profile, + 0, 0, &blob, &errors); + if (FAILED(hr) && errors) std::printf("compile %s: %s\n", profile, static_cast<const char*>(errors->GetBufferPointer())); + return hr; +} + +bool inside(const std::array<std::array<float, 2>, 3>& triangle, float x, float y, float& margin) +{ + float edges[3]; + for (int i = 0; i < 3; ++i) { + const auto& a = triangle[i]; + const auto& b = triangle[(i + 1) % 3]; + edges[i] = (b[0] - a[0]) * (y - a[1]) - (b[1] - a[1]) * (x - a[0]); + } + margin = (std::min)({std::fabs(edges[0]), std::fabs(edges[1]), std::fabs(edges[2])}); + const bool negative = edges[0] < 0 || edges[1] < 0 || edges[2] < 0; + const bool positive = edges[0] > 0 || edges[1] > 0 || edges[2] > 0; + return !(negative && positive); +} + +// The pixels the rectangle covers: (v0, v1, v2) and (v0, v2, v3) of its four corners. For the axis order this +// is the literal rule (v3 = v0 + v2 - v1); a swung order names the same four corners, which is the order the +// existing indirect fixture pins for the geometry stage. +std::vector<std::uint32_t> reference(const std::array<std::pair<float, float>, 4>& quad) +{ + const auto at = [&](int i, int axis) { return axis ? quad[i].second : quad[i].first; }; + const std::array<std::array<float, 2>, 3> first{at(0, 0), at(0, 1), at(1, 0), at(1, 1), at(2, 0), at(2, 1)}; + const std::array<std::array<float, 2>, 3> second{at(0, 0), at(0, 1), at(2, 0), at(2, 1), at(3, 0), at(3, 1)}; + std::vector<std::uint32_t> pixels(width * height, blue); // the clear colour + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + const float centre_x = (2.0f * x + 1.0f) / width - 1.0f; + const float centre_y = 1.0f - (2.0f * y + 1.0f) / height; + float margin = 0; + const bool covered = inside(first, centre_x, centre_y, margin) || inside(second, centre_x, centre_y, margin); + expect(margin > 1e-3f, "a pixel centre lies on a rectangle edge"); + pixels[y * width + x] = covered ? red : blue; + } + } + return pixels; +} +} + +int main(int argc, char** argv) +{ + bool hardware = false; + const char* native_vs = nullptr; + const char* native_ps = nullptr; + const char* native_gs = nullptr; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "hardware") == 0) { + hardware = true; + } else if (std::strcmp(argv[i], "--native-gs") == 0 && i + 1 < argc) { + native_gs = argv[++i]; + } else if (std::strcmp(argv[i], "--native-vs") == 0 && i + 1 < argc) { + native_vs = argv[++i]; + } else if (std::strcmp(argv[i], "--native-ps") == 0 && i + 1 < argc) { + native_ps = argv[++i]; + } else { + std::printf("usage: startup_rect_geometry [hardware] [--native-gs FILE]\n"); + return 2; + } + } + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (hardware) { + ComPtr<IDXGIFactory6> factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr<IDXGIAdapter1> candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; + if (SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 4; + } + ComPtr<ID3D12Device> device; + { + ComPtr<ID3D12Debug> debug; + const HRESULT hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug)); + if (SUCCEEDED(hr)) debug->EnableDebugLayer(); + std::printf("debug_layer=%s\n", SUCCEEDED(hr) ? "on" : "unavailable"); + } + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 5; + DXGI_ADAPTER_DESC desc{}; + LARGE_INTEGER driver{}; + adapter->GetDesc(&desc); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u\n", desc.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart)); + + // The vertex stage exports the 12-byte record's XY as the position, which is what the geometry stage reads + // back through its signature. The mask at +0 is not named by the layout: this fixture measures coverage. + static const char vs_text[] = R"( +struct In { float2 xy : POSITION; }; +float4 main(In input) : SV_Position { return float4(input.xy, 0, 1); })"; + static const char ps_text[] = R"( +float4 main(float4 pos : SV_Position) : SV_Target { return float4(1, 0, 0, 1); })"; + ComPtr<ID3DBlob> vs, ps, gs, gs_errors; + const auto load_blob = [](const char* path, ComPtr<ID3DBlob>& blob) { + std::ifstream file(path, std::ios::binary); + if (!file) return false; + const std::string bytes{std::istreambuf_iterator<char>(file), {}}; + if (FAILED(D3DCreateBlob(bytes.size(), &blob))) return false; + std::memcpy(blob->GetBufferPointer(), bytes.data(), bytes.size()); + return true; + }; + const bool native = native_vs || native_ps || native_gs; + if (native && !(native_vs && native_ps && native_gs)) { + std::printf("--native-vs, --native-ps and --native-gs must be used together\n"); + return 2; + } + if (native) { + if (!load_blob(native_vs, vs) || !load_blob(native_ps, ps) || !load_blob(native_gs, gs)) { + std::printf("missing native stage\n"); + return 7; + } + std::printf("geometry: native %zu bytes\n", static_cast<std::size_t>(gs->GetBufferSize())); + } else if (FAILED(compile(vs_text, "vs_5_1", vs)) || FAILED(compile(ps_text, "ps_5_1", ps))) { + return 6; + } + if (!native && FAILED(x2w_startup::compile_indexed_rect_geometry(vs.Get(), ps.Get(), &gs, &gs_errors))) { + if (gs_errors) std::printf("geometry: %s\n", static_cast<const char*>(gs_errors->GetBufferPointer())); + return 7; + } + + const D3D12_INPUT_ELEMENT_DESC elements[] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 4, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + }; + // A pipeline state that sets an input layout needs this flag on its root signature. + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + ComPtr<ID3DBlob> root_blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &root_blob, nullptr))) return 8; + ComPtr<ID3D12RootSignature> root; + if (FAILED(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&root)))) return 8; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.Get(); + pso_desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + pso_desc.GS = {gs->GetBufferPointer(), gs->GetBufferSize()}; + pso_desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + pso_desc.InputLayout = {elements, 1}; + pso_desc.BlendState.RenderTarget[0] = {TRUE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; + pso_desc.RasterizerState.FrontCounterClockwise = FALSE; // clockwise on screen is front, as in the source + pso_desc.RasterizerState.DepthClipEnable = TRUE; + // A zero-filled depth-stencil description holds invalid enum values (stencil op 0), so the fields a + // depth-less pipeline still needs are spelled out. + pso_desc.DepthStencilState.DepthEnable = FALSE; + pso_desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + pso_desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pso_desc.DepthStencilState.StencilEnable = FALSE; + pso_desc.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + pso_desc.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + pso_desc.DepthStencilState.FrontFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, + D3D12_COMPARISON_FUNC_ALWAYS}; + pso_desc.DepthStencilState.BackFace = pso_desc.DepthStencilState.FrontFace; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = format; + pso_desc.SampleDesc.Count = 1; + pso_desc.SampleMask = UINT_MAX; + ComPtr<ID3D12PipelineState> pso; + const HRESULT pso_hr = device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso)); + if (FAILED(pso_hr)) { + std::printf("CreateGraphicsPipelineState: 0x%08lx\n", static_cast<unsigned long>(pso_hr)); + ComPtr<ID3D12InfoQueue> queue; + if (SUCCEEDED(device.As(&queue))) { + const UINT64 count = queue->GetNumStoredMessages(); + for (UINT64 i = 0; i < count; ++i) { + SIZE_T size = 0; + queue->GetMessage(i, nullptr, &size); + std::vector<char> message(size); + auto* entry = reinterpret_cast<D3D12_MESSAGE*>(message.data()); + if (SUCCEEDED(queue->GetMessage(i, entry, &size))) + std::printf("debug layer: %s\n", entry->pDescription); + } + } + return 9; + } + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const float clear[4] = {0, 0, 1, 1}; + const D3D12_CLEAR_VALUE optimized{format, {clear[0], clear[1], clear[2], clear[3]}}; + ComPtr<ID3D12Resource> target; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_COMMON, + &optimized, IID_PPV_ARGS(&target)))) return 10; + D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + ComPtr<ID3D12DescriptorHeap> rtv_heap; + if (FAILED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap)))) return 10; + device->CreateRenderTargetView(target.Get(), nullptr, rtv_heap->GetCPUDescriptorHandleForHeapStart()); + + struct Scene { + const char* name; + std::array<Vertex, 6> records; + // The four corners of the rectangle the three records name, clockwise on screen from the bottom left. + std::array<std::pair<float, float>, 4> quad; + float angle; + // False when the stage must draw nothing: the swung order is rejected by back-face culling, the + // skewed triangle by the rectangle rule's right-angle guard. + bool covered; + }; + const auto turned = [](std::array<Vertex, 3> rectangle, float degrees) { + const float c = std::cos(degrees * 3.14159265358979324f / 180.0f); + const float s = std::sin(degrees * 3.14159265358979324f / 180.0f); + for (Vertex& v : rectangle) { + const float x = v.x, y = v.y; + v.x = c * x - s * y; + v.y = s * x + c * y; + } + return rectangle; + }; + const std::array<std::pair<float, float>, 4> square{{ + {-1.0f, -1.0f}, {-1.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, -1.0f}}}; + std::array<std::pair<float, float>, 4> turned_square = square; + { + const float c = std::cos(15.0f * 3.14159265358979324f / 180.0f); + const float s = std::sin(15.0f * 3.14159265358979324f / 180.0f); + for (auto& p : turned_square) p = {c * p.first - s * p.second, s * p.first + c * p.second}; + } + std::array<Vertex, 3> skewed = corners; + skewed[1].x = -0.5f; // the top-left corner moved a quarter of the way to the top-right + std::array<Scene, 4> scenes{{ + {"axis", {}, square, 0.0f, true}, + {"swung", {}, square, 0.0f, false}, + {"rotated", {}, turned_square, 15.0f, true}, + {"skewed", {}, square, 0.0f, false}, + }}; + // The three corners a rectangle list names per rectangle: v0, v1 and v2. The fourth is derived. Both + // records of the six-vertex dispatch name the same rectangle. + const std::array<std::array<Vertex, 3>, 4> records{{ + {corners[0], corners[1], corners[2]}, // bottom left, top left, top right + {corners[0], corners[2], corners[1]}, // bottom left, top right, top left + {turned(corners, 15.0f)[0], turned(corners, 15.0f)[1], turned(corners, 15.0f)[2]}, + {skewed[0], skewed[1], skewed[2]}, // no axis corner and no right angle + }}; + for (auto& scene : scenes) { + const auto& three = records[&scene - scenes.data()]; + for (int i = 0; i < 3; ++i) scene.records[i] = three[i]; + for (int i = 0; i < 3; ++i) scene.records[3 + i] = three[i]; + } + + D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const auto make_buffer = [&](UINT64 bytes, D3D12_RESOURCE_STATES state, ID3D12Resource** out) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + return device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(out)); + }; + ComPtr<ID3D12Resource> vertices; + void* mapped = nullptr; + if (FAILED(make_buffer(sizeof(Scene::records), D3D12_RESOURCE_STATE_GENERIC_READ, &vertices)) || + FAILED(vertices->Map(0, nullptr, &mapped))) return 11; + UINT64 total = 0; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, nullptr, nullptr, nullptr, &total); + ComPtr<ID3D12Resource> readback; + { + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + if (FAILED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) + return 12; + } + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + const D3D12_VERTEX_BUFFER_VIEW vertex_view{vertices->GetGPUVirtualAddress(), sizeof(Scene::records), sizeof(Vertex)}; + for (const auto& scene : scenes) { + std::memcpy(mapped, scene.records.data(), sizeof(scene.records)); + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), pso.Get(), IID_PPV_ARGS(&list)))) + return 13; + const auto transition = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &barrier); + }; + transition(target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ClearRenderTargetView(rtv_heap->GetCPUDescriptorHandleForHeapStart(), clear, 0, nullptr); + list->OMSetRenderTargets(1, &rtv_heap->GetCPUDescriptorHandleForHeapStart(), FALSE, nullptr); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->IASetVertexBuffers(0, 1, &vertex_view); + list->DrawInstanced(6, 1, 0, 0); + transition(target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(target.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (FAILED(list->Close())) return 14; + ComPtr<ID3D12CommandQueue> queue; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr<ID3D12Fence> fence; + if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return 15; + ID3D12CommandList* lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return 15; + while (fence->GetCompletedValue() != 1) Sleep(1); + void* pixels = nullptr; + if (FAILED(readback->Map(0, nullptr, &pixels))) return 16; + std::vector<std::uint32_t> actual(width * height); + for (UINT y = 0; y < height; ++y) + std::memcpy(&actual[y * width], static_cast<const unsigned char*>(pixels) + y * footprint.Footprint.RowPitch, + width * 4); + readback->Unmap(0, nullptr); + auto want = reference(scene.quad); + if (!scene.covered) std::fill(want.begin(), want.end(), blue); + UINT differing = 0; + for (UINT i = 0; i < actual.size(); ++i) { + if (actual[i] != want[i]) { + if (!differing) + std::printf(" %s: pixel (%u, %d) is %08x, expected %08x\n", scene.name, i % width, + static_cast<int>(i / width), actual[i], want[i]); + ++differing; + } + } + expect(differing == 0, scene.name); + std::printf("%s: %u of %u pixels differ from the literal rectangle rule (angle %.1f)\n", scene.name, differing, + width * height, scene.angle); + } + vertices->Unmap(0, nullptr); + std::printf("rect geometry: %s, %d failure(s)\n", failures ? "failed" : "passed", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_resource_retire.cpp b/tests/startup_resource_retire.cpp index 2787867a04..d97928eb5f 100644 --- a/tests/startup_resource_retire.cpp +++ b/tests/startup_resource_retire.cpp @@ -39,6 +39,7 @@ struct RetireProbe { unsigned cache_entries; // texture_uploads, pending_gpu_writes and view_targets entries naming the resource unsigned list_states; // resources the open recording of the list moved out of COMMON unsigned list_holds; // resources the list's recordings hold + unsigned view_refs; // tracked descriptor slots (18-21) holding the resource }; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index fa6fbaf4c5..9645bda5f5 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -23,6 +23,18 @@ // descriptor table. The readback must hold the sampled texels and a clear sentinel corner, the draw must record // a retire hold (so removing it fails here), and after the final Release and the descriptor overwrite the // texture leaves the budget only when the closed draw recording is dropped (case runs with the switch on). +// 8 slot 19-21 view references (Slice 3a): a materialized RTV (20), DSV (21) and UAV (19, resource and counter) in a +// tracked heap slot holds one ref per slot; the same view written again adds nothing, and overwrite, descriptor +// copy and heap destruction release exactly what was added. Read through the retire probe (case runs with the +// switch on; the retire class still excludes non-SRV view textures, so the budget column cannot show these refs). +// 10 struct-return ABI: descriptor heap slot 9 (GetCPUDescriptorHandleForHeapStart) returns its 8-byte handle in rax +// with only `this` in rcx. A live wrapper left in the second register must not select the (return buffer, +// object) form, which wrote the handle over the heap object; the hidden-pointer form still fills its buffer. +// Release builds of case 9 left a resource wrapper there and crashed at the heap's next Release. +// 9 slot 19-21 fallback (Slice 3a): the same view call in a tracked slot leaves a class texture in the retire class +// (a refused view adds no ref, so the released texture retires), while a descriptor in a heap the shim does not +// track keeps the retire_leave_class fallback and the texture is not freed. Runs in both modes; without the switch +// nothing is freed. #include "startup_stubs/resource_budget.h" #include <d3d12sdklayers.h> @@ -45,6 +57,7 @@ struct RetireProbe { unsigned cache_entries; unsigned list_states; unsigned list_holds; + unsigned view_refs; // tracked descriptor slots (18-21) holding the resource; slice 3a fixture probe }; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); @@ -218,19 +231,42 @@ struct Context { IUnknown* lists[] = {l.list.Get()}; invoke<void>(q.queue.Get(), 10, 1u, lists); } - Res& make_committed(const char* name, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) + Res& make_committed(const char* name, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, + DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN) { const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; D3D12_RESOURCE_DESC d = desc; d.Flags = flags; + if (format != DXGI_FORMAT_UNKNOWN) d.Format = format; Res& r = pool.emplace_back(); r.name = name; - r.bytes = texture_bytes; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; if (!require(invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, nullptr, &iid_resource[0], r.guest.GetAddressOf()), name)) throw 4; return r; } + Res& make_committed_buffer(const char* name, UINT64 bytes, D3D12_RESOURCE_FLAGS flags) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC d{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, flags}; + Res& r = pool.emplace_back(); + r.name = name; + r.category = buffer; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + if (!require(invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid_resource[0], r.guest.GetAddressOf()), name)) + throw 4; + return r; + } + ComPtr<IUnknown> make_descriptor_heap(const char* name, D3D12_DESCRIPTOR_HEAP_TYPE type, UINT count) + { + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{type, count, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr<IUnknown> heap; + if (!require(invoke(guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), name)) throw 4; + return heap; + } Res& make_slot133(const char* name, void* address, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, UINT width = side) { D3D12_RESOURCE_DESC d = desc; @@ -256,7 +292,9 @@ struct Context { upload->Unmap(0, nullptr); if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; - own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint_tex(real.Get()); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint(upload.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; @@ -278,7 +316,9 @@ struct Context { b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE}; own_list->ResourceBarrier(1, &b); - own_list->CopyTextureRegion(&footprint(readback.Get(), fmt, width), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint(readback.Get(), fmt, width); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint_tex(real.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; own_list->ResourceBarrier(1, &b); @@ -371,7 +411,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-17"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-29"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; @@ -973,6 +1013,210 @@ bool case7_draw_samples_slot133_texture(Context& c, void* title_mem) return check_target("readback after the texture left the budget", target_bytes.data(), row_pitch); } +// 8 (Slice 3a, Refs #2379): UAV/RTV/DSV descriptor slots 19-21 hold a retire reference on their resource(s) the way +// slot-18 SRVs do. The refs are read through the retire probe: the retire class still excludes render-target, +// depth-stencil and unordered-access textures (retire_classify), so no budget column can show the reference yet. A +// materialized view in a tracked heap slot adds one ref - slot 19 one for its resource and one for its counter - and +// writing the same view to the same slot again adds nothing. Overwriting the slot, copying another view over it, and +// destroying its heap each release exactly the refs that were added; a view in a heap the shim does not shadow adds +// none and keeps the retire_leave_class fallback. +bool case8_view_slot_refs(Context& c) +{ + auto refs = [&](const char* stage, IUnknown* resource) { + RetireProbe probe{}; + if (!x2w_d3d12_retire_probe(resource, nullptr, &probe)) { + std::printf("FAIL: %s: the retire probe reported nothing\n", stage); + return -1L; + } + return static_cast<long>(probe.view_refs); + }; + auto check = [&](const char* stage, IUnknown* resource, long want) { + const long got = refs(stage, resource); + if (got == want) return true; + std::printf("FAIL: %s: %ld tracked slot refs, expected %ld\n", stage, got, want); + return false; + }; + + // RTV (slot 20): add on creation, no-op on the same view again, release on overwrite, copy and heap destruction. + Res& rtv_a = c.make_committed("R_rtv_a", D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Res& rtv_b = c.make_committed("R_rtv_b", D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + D3D12_RENDER_TARGET_VIEW_DESC rtv{}; + rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rtv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + ComPtr<IUnknown> rtv_heap = c.make_descriptor_heap("rtv heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const UINT64 rtv0 = invoke<UINT64>(rtv_heap.Get(), 9); + invoke<void>(c.guest, 20, rtv_a.guest.Get(), &rtv, rtv0); + if (!check("RTV created in a tracked slot", rtv_a.guest.Get(), 1)) return false; + invoke<void>(c.guest, 20, rtv_a.guest.Get(), &rtv, rtv0); // the same view written again + if (!check("RTV written to the same slot again", rtv_a.guest.Get(), 1)) return false; + invoke<void>(c.guest, 20, rtv_b.guest.Get(), &rtv, rtv0); + if (!check("RTV overwrote the slot: previous resource", rtv_a.guest.Get(), 0) || + !check("RTV overwrote the slot: new resource", rtv_b.guest.Get(), 1)) + return false; + // A copy makes a second tracked slot name the same view, so the resource holds two refs. + ComPtr<IUnknown> rtv_copy = c.make_descriptor_heap("rtv copy heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const UINT64 rtv_copy0 = invoke<UINT64>(rtv_copy.Get(), 9); + invoke<void>(c.guest, 24, 1u, rtv_copy0, rtv0, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + if (!check("RTV copied into a second tracked heap", rtv_b.guest.Get(), 2)) return false; + invoke<void>(c.guest, 20, rtv_a.guest.Get(), &rtv, rtv0); + if (!check("copied slot overwritten: copy still holds the view", rtv_b.guest.Get(), 1)) return false; + rtv_copy.Reset(); + if (!check("copy heap destroyed", rtv_b.guest.Get(), 0)) return false; + rtv_heap.Reset(); + if (!check("RTV heap destroyed", rtv_a.guest.Get(), 0)) return false; + + // An untracked destination: the view is forwarded to a desktop heap the shim never shadowed, so no ref is added. + D3D12_RENDER_TARGET_VIEW_DESC untracked_rtv = rtv; + const D3D12_DESCRIPTOR_HEAP_DESC desktop_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr<ID3D12DescriptorHeap> desktop_heap; + if (!require(c.device->CreateDescriptorHeap(&desktop_heap_desc, IID_PPV_ARGS(&desktop_heap)), "untracked rtv heap")) + return false; + invoke<void>(c.guest, 20, rtv_a.guest.Get(), &untracked_rtv, desktop_heap->GetCPUDescriptorHandleForHeapStart().ptr); + if (!check("RTV in an untracked slot", rtv_a.guest.Get(), 0)) return false; + + // DSV (slot 21): the same accounting on a depth texture. + Res& dsv_a = c.make_committed("R_dsv_a", D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, DXGI_FORMAT_D32_FLOAT); + Res& dsv_b = c.make_committed("R_dsv_b", D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, DXGI_FORMAT_D32_FLOAT); + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + ComPtr<IUnknown> dsv_heap = c.make_descriptor_heap("dsv heap", D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1); + const UINT64 dsv0 = invoke<UINT64>(dsv_heap.Get(), 9); + invoke<void>(c.guest, 21, dsv_a.guest.Get(), &dsv, dsv0); + if (!check("DSV created in a tracked slot", dsv_a.guest.Get(), 1)) return false; + invoke<void>(c.guest, 21, dsv_b.guest.Get(), &dsv, dsv0); + if (!check("DSV overwrote the slot: previous resource", dsv_a.guest.Get(), 0) || + !check("DSV overwrote the slot: new resource", dsv_b.guest.Get(), 1)) + return false; + dsv_heap.Reset(); + if (!check("DSV heap destroyed", dsv_b.guest.Get(), 0)) return false; + + // UAV (slot 19): a texture UAV holds its view resource; a buffer UAV additionally names its counter resource, so + // both resources hold one ref. Desktop refuses a counter on a non-buffer UAV (DXGI_ERROR_INVALID_CALL), and the + // console makes UAVs of resources desktop does not allow, so the counter half is driven through a buffer UAV. + Res& uav_a = c.make_committed("R_uav_a", D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Res& uav_b = c.make_committed("R_uav_b", D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + ComPtr<IUnknown> uav_heap = c.make_descriptor_heap("uav heap", D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1); + const UINT64 uav0 = invoke<UINT64>(uav_heap.Get(), 9); + invoke<void>(c.guest, 19, uav_a.guest.Get(), nullptr, &uav, uav0); + if (!check("UAV created in a tracked slot: resource", uav_a.guest.Get(), 1)) return false; + invoke<void>(c.guest, 19, uav_a.guest.Get(), nullptr, &uav, uav0); // the same view written again + if (!check("UAV written to the same slot again: resource", uav_a.guest.Get(), 1)) return false; + invoke<void>(c.guest, 19, uav_b.guest.Get(), nullptr, &uav, uav0); + if (!check("UAV overwrote the slot: previous resource", uav_a.guest.Get(), 0) || + !check("UAV overwrote the slot: new resource", uav_b.guest.Get(), 1)) + return false; + uav_heap.Reset(); + if (!check("UAV heap destroyed: resource", uav_b.guest.Get(), 0)) return false; + + // Slot 19 with a counter resource: one ref for the resource and one for the counter, released together. + Res& uav_buffer_a = c.make_committed_buffer("R_uav_buffer_a", 256, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Res& uav_buffer_b = c.make_committed_buffer("R_uav_buffer_b", 256, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Res& counter_a = c.make_committed_buffer("R_counter_a", 256, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Res& counter_b = c.make_committed_buffer("R_counter_b", 256, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + D3D12_UNORDERED_ACCESS_VIEW_DESC buffer_uav{}; + buffer_uav.Format = DXGI_FORMAT_UNKNOWN; + buffer_uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + buffer_uav.Buffer.NumElements = 64; + buffer_uav.Buffer.StructureByteStride = 4; + + ComPtr<IUnknown> counter_heap = c.make_descriptor_heap("counter uav heap", D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1); + const UINT64 counter0 = invoke<UINT64>(counter_heap.Get(), 9); + invoke<void>(c.guest, 19, uav_buffer_a.guest.Get(), counter_a.guest.Get(), &buffer_uav, counter0); + if (!check("UAV with counter created: resource", uav_buffer_a.guest.Get(), 1) || + !check("UAV with counter created: counter", counter_a.guest.Get(), 1)) + return false; + invoke<void>(c.guest, 19, uav_buffer_a.guest.Get(), counter_a.guest.Get(), &buffer_uav, counter0); + if (!check("UAV with counter written again: resource", uav_buffer_a.guest.Get(), 1) || + !check("UAV with counter written again: counter", counter_a.guest.Get(), 1)) + return false; + invoke<void>(c.guest, 19, uav_buffer_b.guest.Get(), counter_b.guest.Get(), &buffer_uav, counter0); + if (!check("UAV with counter overwritten: previous resource", uav_buffer_a.guest.Get(), 0) || + !check("UAV with counter overwritten: previous counter", counter_a.guest.Get(), 0) || + !check("UAV with counter overwritten: new resource", uav_buffer_b.guest.Get(), 1) || + !check("UAV with counter overwritten: new counter", counter_b.guest.Get(), 1)) + return false; + counter_heap.Reset(); + if (!check("UAV counter heap destroyed: resource", uav_buffer_b.guest.Get(), 0) || + !check("UAV counter heap destroyed: counter", counter_b.guest.Get(), 0)) + return false; + return true; +} + +// 9 (Slice 3a): the view_slot fallback for slots 19-21. A view call whose destination descriptor slot shadow_slot() +// tracks leaves the resource in the retire class and lets the slot accounting own it; the call here is refused because +// the class texture lacks the use flag (a case the console allows: UAV of a depth texture, RTV of a non-render-target), +// so no reference is added and the released texture still retires. In a heap the shim does not track, the same call +// keeps the old fallback, retire_leave_class, so the texture is never freed under a descriptor the shim cannot follow. +// Runs in both modes: with the switch off nothing retires, as before. +bool case9_view_slot_fallback(Context& c, bool on, void* tracked_memory, void* untracked_memory) +{ + D3D12_RENDER_TARGET_VIEW_DESC rtv{}; + rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rtv.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; + // A guest heap: note_heap() shadows its slots, so the destination is tracked even though the view is refused. + Res& tracked = c.make_slot133("T_rtv_tracked", tracked_memory); + ComPtr<IUnknown> tracked_heap = c.make_descriptor_heap("fallback rtv heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + invoke<void>(c.guest, 20, tracked.guest.Get(), &rtv, invoke<UINT64>(tracked_heap.Get(), 9)); + c.release(tracked); + if (!c.sync(c.direct)) return false; + if (on) tracked.freed = true; + if (!c.settle("class texture with a refused RTV in a tracked slot", + "a refused view in a tracked slot kept the texture out of the retire class")) + return false; + // A desktop heap the shim never saw: shadow_slot() has no entry, so the use keeps the retire_leave_class fallback. + Res& untracked = c.make_slot133("T_rtv_untracked", untracked_memory); + const D3D12_DESCRIPTOR_HEAP_DESC desktop_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr<ID3D12DescriptorHeap> desktop_heap; + if (!require(c.device->CreateDescriptorHeap(&desktop_heap_desc, IID_PPV_ARGS(&desktop_heap)), "fallback rtv heap")) + return false; + invoke<void>(c.guest, 20, untracked.guest.Get(), &rtv, desktop_heap->GetCPUDescriptorHandleForHeapStart().ptr); + c.release(untracked); + if (!c.sync(c.direct)) return false; + return c.settle("class texture with a refused RTV in an untracked slot", + "the untracked-descriptor fallback did not keep the texture retained"); +} + +// 10: descriptor heap slot 9 returns an 8-byte structure. The title calls it with `this` in rcx and reads rax, so +// the second register holds whatever the caller left there; an optimized caller computing the next call's arguments +// can leave another live object there. That must not select the (return buffer, object) form, which wrote the +// handle over the heap object's vtable and returned the heap's address. The hidden-pointer form, a stack buffer +// first and the object second, still fills the buffer and returns it. +bool case10_heap_start_abi(Context& c) +{ + ComPtr<IUnknown> heap = c.make_descriptor_heap("abi heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + ComPtr<IUnknown> other = c.make_descriptor_heap("abi second heap", D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const UINT64 want = invoke<UINT64>(heap.Get(), 9, static_cast<void*>(nullptr)); + const UINT64 got = invoke<UINT64>(heap.Get(), 9, static_cast<void*>(other.Get())); + if (!want || got != want) { + std::printf("FAIL: heap start with a live object in the second argument: got %#llx, expected %#llx (heap %p)\n", + static_cast<unsigned long long>(got), static_cast<unsigned long long>(want), + static_cast<void*>(heap.Get())); + heap.Detach(); // its vtable slot may now hold a descriptor handle; never call through it again + return false; + } + using HiddenForm = D3D12_CPU_DESCRIPTOR_HANDLE*(WINAPI*)(D3D12_CPU_DESCRIPTOR_HANDLE*, IUnknown*); + const auto hidden = reinterpret_cast<HiddenForm>((*reinterpret_cast<void***>(heap.Get()))[9]); + D3D12_CPU_DESCRIPTOR_HANDLE buffer{}; + const D3D12_CPU_DESCRIPTOR_HANDLE* returned = hidden(&buffer, heap.Get()); + if (returned != &buffer || buffer.ptr != want) { + std::printf("FAIL: heap start through a return buffer: returned %p (buffer %p) holding %#llx, expected %#llx\n", + static_cast<const void*>(returned), static_cast<void*>(&buffer), + static_cast<unsigned long long>(buffer.ptr), static_cast<unsigned long long>(want)); + return false; + } + const UINT64 again = invoke<UINT64>(heap.Get(), 9, static_cast<void*>(nullptr)); + if (again != want) { + std::printf("FAIL: heap start changed after the calls above: got %#llx, expected %#llx\n", + static_cast<unsigned long long>(again), static_cast<unsigned long long>(want)); + return false; + } + return true; +} + } // namespace int main(int argc, char** argv) @@ -1023,10 +1267,14 @@ int main(int argc, char** argv) auto* mem1 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); auto* mem2 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); auto* mem3 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!mem1 || !mem2 || !mem3) return 4; + auto* mem4 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + auto* mem5 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!mem1 || !mem2 || !mem3 || !mem4 || !mem5) return 4; Context c{guest.Get(), device.Get(), debug.Get()}; try { + if (!case10_heap_start_abi(c)) return 5; + std::puts("10 heap start ABI: a live object in the second register keeps the rax form; a return buffer is filled"); c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; c.texture_bytes = device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; @@ -1065,15 +1313,25 @@ int main(int argc, char** argv) if (!case7_draw_samples_slot133_texture(c, mem1)) return 5; std::puts("7 translated draw: slot 133 texture sampled through a descriptor table, held until the recording drained"); } + if (!case9_view_slot_fallback(c, on, mem4, mem5)) return 5; + std::puts("9 slot 19-21 fallback: a refused view in a tracked slot retires, an untracked slot keeps the texture"); + if (on) { + if (!case8_view_slot_refs(c)) return 5; + std::puts("8 slot 19-21 refs: RTV/DSV/UAV (+counter) hold and release one ref per tracked slot"); + } } catch (int code) { VirtualFree(mem1, 0, MEM_RELEASE); VirtualFree(mem2, 0, MEM_RELEASE); VirtualFree(mem3, 0, MEM_RELEASE); + VirtualFree(mem4, 0, MEM_RELEASE); + VirtualFree(mem5, 0, MEM_RELEASE); return code; } VirtualFree(mem1, 0, MEM_RELEASE); VirtualFree(mem2, 0, MEM_RELEASE); VirtualFree(mem3, 0, MEM_RELEASE); + VirtualFree(mem4, 0, MEM_RELEASE); + VirtualFree(mem5, 0, MEM_RELEASE); const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; std::printf("debug_errors_or_warnings=%llu\n", errors); if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; diff --git a/tests/startup_resource_retire_views.cpp b/tests/startup_resource_retire_views.cpp index 6db82d2895..25842a0e23 100644 --- a/tests/startup_resource_retire_views.cpp +++ b/tests/startup_resource_retire_views.cpp @@ -1,24 +1,9 @@ -// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (with X2W_D3D12_RELEASE_RETIRED=1, Refs #2379): a released committed 2D texture that -// only tracked slot-18 descriptor slots keep alive is freed once those slots hold null descriptors. The title never has -// to overwrite them. -// +// Live SRVs keep retired textures available for later bindings (#2379). // startup_resource_retire_views <warp|hardware> [keep] -// -// `keep` is the negative control: the views switch is off (or the retire switch is, with the views switch set), so a -// released texture stays retained exactly as before and its descriptors keep naming it. -// -// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue loads -// texel (0,0) through a slot of a guest heap (bound directly when the heap is shader-visible, copied into a probe -// heap when it is not). A filled texture reads back non-zero, a null descriptor reads back zero. -// Cases: -// 1 single SRV in a shader-visible heap, never overwritten: freed after the release fences, descriptor null, view -// token in title descriptor memory cleared. -// 2 the same texture also copied into a second (non-shader-visible) heap, release behind a gated queue: nothing is -// touched until the gate opens, then both copies are null and the texture is freed (copies are handled). -// 3 a closed list recorded a CopyResource from the texture, submitted behind a gate: descriptors are nulled but the -// desktop object lives until the submission's fence, and the copy still reads the texels. -// 4 a closed, never submitted list names the texture: nulled, retained until the recording is discarded. -// 5 a live texture's descriptor is never touched. +// `keep` runs without base retirement, as a control for the budget drop after explicit overwrite. +// The legacy views switch may be on or off. Both settings preserve the original and copied slots. +// The fixture uses the shim's descriptor creation and copying paths and reads the desktop descriptors +// with a compute probe. The gated queue and the two recorded copies cover pending GPU work. #include "startup_stubs/resource_budget.h" #include <d3d12sdklayers.h> @@ -241,7 +226,9 @@ struct Context { upload->Unmap(0, nullptr); if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; - own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint_tex(real.Get()); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint(upload.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON}; @@ -258,7 +245,9 @@ struct Context { b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE}; own_list->ResourceBarrier(1, &b); - own_list->CopyTextureRegion(&footprint(readback.Get()), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + D3D12_TEXTURE_COPY_LOCATION tex_dst = footprint(readback.Get()); + D3D12_TEXTURE_COPY_LOCATION tex_src = footprint_tex(real.Get()); + own_list->CopyTextureRegion(&tex_dst, 0, 0, 0, &tex_src, nullptr); b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; own_list->ResourceBarrier(1, &b); @@ -417,75 +406,74 @@ D3D12_SHADER_RESOURCE_VIEW_DESC texture_view() return srv; } -// 1: one SRV in a shader-visible heap, never overwritten. -bool case1_single_view(Context& c, bool on, GuestHeap& visible) +void overwrite_srv(Context& c, const GuestHeap& heap, UINT index) { - Res& T = c.make_committed("T1"); - if (!c.fill_desktop(T.guest.Get(), 1)) return false; const auto srv = texture_view(); - invoke<void>(c.guest, 18, T.guest.Get(), &srv, visible.cpu); - if (!c.slot_is(visible, 0, false, "case 1 control: live texture's descriptor") || - Context::token_word(visible, 0, c.increment) != view_token_magic) { - std::puts("FAIL: case 1 control: live texture's view token missing"); - return false; - } - c.release(T); - if (on) { - T.freed = true; - if (!c.settle("T1 freed with its descriptor never overwritten", "T1 kept although only a descriptor names it")) - return false; - if (!c.slot_is(visible, 0, true, "case 1: descriptor after the free")) return false; - if (Context::token_word(visible, 0, c.increment) == view_token_magic) { - std::puts("FAIL: case 1: view token still in title descriptor memory after the free"); - return false; - } - return true; - } + invoke<void>(c.guest, 18, static_cast<IUnknown*>(nullptr), &srv, heap.cpu + c.increment * static_cast<UINT64>(index)); +} + +// 1: a later binding of the same slot after the last guest Release. +bool case1_single_view(Context& c, bool retire_on, GuestHeap& visible) +{ + Res& texture = c.make_committed("T1"); + if (!c.fill_desktop(texture.guest.Get(), 1)) return false; + const auto srv = texture_view(); + invoke<void>(c.guest, 18, texture.guest.Get(), &srv, visible.cpu); + if (!c.slot_is(visible, 0, false, "case 1: live descriptor") || + Context::token_word(visible, 0, c.increment) != view_token_magic) return false; + + c.release(texture); for (int i = 0; i < 8; ++i) - if (!c.stays("T1 released, views switch off", "T1 freed without the views switch")) return false; - return c.slot_is(visible, 0, false, "case 1 control: descriptor with the views switch off"); + if (!c.stays("T1 with a live slot", "T1 retired before its slot was overwritten")) return false; + if (!c.slot_is(visible, 0, false, "case 1: rebound descriptor after Release") || + Context::token_word(visible, 0, c.increment) != view_token_magic) return false; + + overwrite_srv(c, visible, 0); + if (!c.slot_is(visible, 0, true, "case 1: explicitly overwritten slot")) return false; + texture.freed = retire_on; + return c.settle("T1 after explicit overwrite", "unexpected backing lifetime after overwrite"); } // 2: a copy in a second heap, release behind a gated queue. -bool case2_copy_and_gate(Context& c, bool on, GuestHeap& visible, GuestHeap& staging) +bool case2_copy_and_gate(Context& c, bool retire_on, GuestHeap& visible, GuestHeap& staging) { - Res& T = c.make_committed("T2"); - if (!c.fill_desktop(T.guest.Get(), 2)) return false; + Res& texture = c.make_committed("T2"); + if (!c.fill_desktop(texture.guest.Get(), 2)) return false; const auto srv = texture_view(); - invoke<void>(c.guest, 18, T.guest.Get(), &srv, visible.cpu + c.increment); + invoke<void>(c.guest, 18, texture.guest.Get(), &srv, visible.cpu + c.increment); invoke<void>(c.guest, 24, 1u, staging.cpu, visible.cpu + c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); ComPtr<IUnknown> gate; if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate") || - !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait")) - return false; - c.release(T); + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait")) return false; + + c.release(texture); for (int i = 0; i < 8; ++i) - if (!c.stays("T2 released behind a closed gate", "T2 freed before the release fences passed")) return false; - if (!c.slot_is(visible, 1, false, "case 2: original descriptor before the gate opens") || - !c.slot_is(staging, 0, false, "case 2: copied descriptor before the gate opens")) - return false; + if (!c.stays("T2 behind a closed gate", "T2 retired before the release fences passed")) return false; + if (!c.slot_is(visible, 1, false, "case 2: original before the gate opens") || + !c.slot_is(staging, 0, false, "case 2: copy before the gate opens")) return false; if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate") || !c.sync(c.gated)) return false; - if (!on) { - for (int i = 0; i < 8; ++i) - if (!c.stays("T2 released, views switch off", "T2 freed without the views switch")) return false; - return c.slot_is(staging, 0, false, "case 2 control: copied descriptor with the views switch off"); - } - T.freed = true; - if (!c.settle("T2 freed after the gate opened", "T2 kept after its fences passed")) return false; - return c.slot_is(visible, 1, true, "case 2: original descriptor after the free") && - c.slot_is(staging, 0, true, "case 2: copied descriptor after the free"); + if (!c.stays("T2 after its release fences", "T2 retired while both descriptors were live") || + !c.slot_is(visible, 1, false, "case 2: original after the release fences") || + !c.slot_is(staging, 0, false, "case 2: copy after the release fences")) return false; + + overwrite_srv(c, visible, 1); + if (!c.stays("T2 with only its copy live", "T2 retired while its copy was live") || + !c.slot_is(staging, 0, false, "case 2: copy after overwriting the original")) return false; + overwrite_srv(c, staging, 0); + if (!c.slot_is(staging, 0, true, "case 2: explicitly overwritten copy")) return false; + texture.freed = retire_on; + return c.settle("T2 after both slots were overwritten", "unexpected backing lifetime after overwriting both slots"); } -// 3 and 4: lists that name the texture. -bool case3_list_holds(Context& c, bool on, GuestHeap& visible) +// 3 and 4: lists that name the texture. Overwriting the slots cannot drop list or submission holds. +bool case3_list_holds(Context& c, bool retire_on, GuestHeap& visible) { Res& T3 = c.make_committed("T3"); Res& D3 = c.make_committed("D3"); Res& T4 = c.make_committed("T4"); Res& D4 = c.make_committed("D4"); if (!c.fill_desktop(T3.guest.Get(), 3) || !c.fill_desktop(D3.guest.Get(), 99) || !c.fill_desktop(T4.guest.Get(), 4) || - !c.fill_desktop(D4.guest.Get(), 99)) - return false; + !c.fill_desktop(D4.guest.Get(), 99)) return false; const auto srv = texture_view(); invoke<void>(c.guest, 18, T3.guest.Get(), &srv, visible.cpu + 2 * c.increment); invoke<void>(c.guest, 18, T4.guest.Get(), &srv, visible.cpu + 3 * c.increment); @@ -494,30 +482,31 @@ bool case3_list_holds(Context& c, bool on, GuestHeap& visible) invoke<void>(submitted.list.Get(), 17, D3.guest.Get(), T3.guest.Get()); invoke<void>(discarded.list.Get(), 17, D4.guest.Get(), T4.guest.Get()); if (!c.close(submitted) || !c.close(discarded)) return false; + c.release(T3); c.release(T4); for (int i = 0; i < 8; ++i) - if (!c.stays("T3/T4 released behind closed lists", "a texture left the budget while a closed list names it")) - return false; - if (on && (!c.slot_is(visible, 2, true, "case 3: descriptor of the listed texture T3") || - !c.slot_is(visible, 3, true, "case 4: descriptor of the listed texture T4"))) - return false; + if (!c.stays("T3/T4 behind closed lists", "a texture retired while its list was closed")) return false; + if (!c.slot_is(visible, 2, false, "case 3: slot with a closed list") || + !c.slot_is(visible, 3, false, "case 4: slot with a closed list")) return false; + ComPtr<IUnknown> gate; if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate3") || - !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait3")) - return false; + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait3")) return false; c.execute(c.gated, submitted); - if (!SUCCEEDED(c.reset_list(submitted))) return false; + if (!SUCCEEDED(c.reset_list(submitted)) || + !c.slot_is(visible, 2, false, "case 3: live slot during an in-flight recording")) return false; + overwrite_srv(c, visible, 2); + overwrite_srv(c, visible, 3); for (int i = 0; i < 8; ++i) - if (!c.stays("T3 held by a gated submission", "T3 left the budget while its submission is in flight")) return false; - if (!SUCCEEDED(c.reset_list(discarded))) return false; // discards the recording that was never submitted - if (on) T4.freed = true; - if (!c.settle("T4 freed after its recording was discarded", "T4 kept after its recording was discarded")) return false; + if (!c.stays("T3/T4 after overwrite", "a texture retired while its list or submission still held it")) return false; + if (!SUCCEEDED(c.reset_list(discarded))) return false; + T4.freed = retire_on; + if (!c.settle("T4 after its recording was discarded", "unexpected T4 lifetime after discarding the list")) return false; if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate3") || !c.sync(c.gated)) return false; - if (on) T3.freed = true; - if (!c.settle("T3 freed after its submission's fence", "T3 kept after its submission's fence passed")) return false; - // The copy ran against the live texels, not against anything freed or nulled. - return c.holds(D3.guest.Get(), 3, "D3 copy of T3 recorded before the release"); + T3.freed = retire_on; + if (!c.settle("T3 after its submission's fence", "unexpected T3 lifetime after the fence")) return false; + return c.holds(D3.guest.Get(), 3, "D3 copy of T3 recorded before Release and overwrite"); } // 5: a live texture is never touched. @@ -573,12 +562,11 @@ int main(int argc, char** argv) value[0] = 0; const bool views_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED_VIEWS", value, sizeof(value)) == 1 && value[0] == '1'; const bool keep_mode = argc == 3; - // The effective switch needs both; `keep` runs with either one missing. - if ((retire_on && views_on) == keep_mode) return 2; - const bool on = !keep_mode; + if (retire_on == keep_mode) return 2; DXGI_ADAPTER_DESC1 adapter_desc{}; adapter->GetDesc1(&adapter_desc); - std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", keep_mode ? "keep" : "on"); + std::printf("adapter=%ls debug_layer=%s retire=%s legacy_views=%s\n", adapter_desc.Description, + debug ? "enabled" : "off", retire_on ? "on" : "off", views_on ? "on" : "off"); Context c{guest.Get(), device.Get()}; try { @@ -638,12 +626,12 @@ int main(int argc, char** argv) GuestHeap visible, staging; if (!c.make_heap(visible, 8, true) || !c.make_heap(staging, 1, false)) return 4; - if (!case1_single_view(c, on, visible)) return 5; - std::puts("1 single SRV in a shader-visible heap, never overwritten: freed with a null descriptor and a cleared token"); - if (!case2_copy_and_gate(c, on, visible, staging)) return 5; - std::puts("2 copied descriptor behind a closed gate: untouched until the fences pass, then both copies null"); - if (!case3_list_holds(c, on, visible)) return 5; - std::puts("3/4 listed texture: descriptors null, desktop object kept until the submission's fence or the discard"); + if (!case1_single_view(c, retire_on, visible)) return 5; + std::puts("1 same slot rebind reads its texture after Release and permits retirement after overwrite"); + if (!case2_copy_and_gate(c, retire_on, visible, staging)) return 5; + std::puts("2 original and copied slots read their texture after the release fences, retaining it through the final overwrite"); + if (!case3_list_holds(c, retire_on, visible)) return 5; + std::puts("3/4 overwritten slots preserve list and submission holds, recorded copy reads the original texels"); if (!case5_live_control(c, visible)) return 5; std::puts("5 live texture: descriptor untouched"); } catch (int code) { @@ -652,6 +640,6 @@ int main(int argc, char** argv) const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; std::printf("debug_errors_or_warnings=%llu\n", errors); if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; - std::puts(on ? "release-retired views checks passed" : "views-off control checks passed"); + std::puts(retire_on ? "live descriptor retirement checks passed" : "base retirement off: all retention controls passed"); return 0; } diff --git a/tests/startup_root_constant_store.cpp b/tests/startup_root_constant_store.cpp new file mode 100644 index 0000000000..a07bb3acf1 --- /dev/null +++ b/tests/startup_root_constant_store.cpp @@ -0,0 +1,62 @@ +// Experimental (docs/startup-runtime.md, #870): the root constants a command list keeps for compute +// (list slots 37 and 39). Plain standard C++; synthetic values, no title data. +#include "../src/startup_stubs/root_constant_store.h" + +#include <cstdio> +#include <string> + +namespace { +using x2w_root_constants::Result; +using x2w_root_constants::Store; +int failures; + +void expect(bool ok, const std::string& what) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what.c_str()); + ++failures; + } +} +} // namespace + +int main() +{ + Store store; + const std::uint32_t data[4] = {11, 22, 33, 44}; + + expect(store.set(3, 4, data, 2) == Result::stored, "four words at offset 2 are stored"); + expect(store.word(3, 2) == 11 && store.word(3, 5) == 44, "stored words read back at their offsets"); + expect(store.word(3, 1) == 0 && store.word(3, 6) == 0, "neighbouring words stay zero"); + + expect(store.set_one(5, 77, 7) == Result::stored, "a single word at the last offset is stored"); + expect(store.word(5, 7) == 77, "the single word reads back"); + + expect(store.set(6, 4, data, 6) == Result::truncated, "a write past the end of the parameter is cut off"); + expect(store.word(6, 6) == 11 && store.word(6, 7) == 22, "the words that fit are kept"); + expect(store.word(7, 0) == 0, "a cut-off write does not spill into the next parameter"); + + expect(store.set(16, 1, data, 0) == Result::dropped, "parameter 16 is refused"); + expect(store.set(0, 1, data, 8) == Result::dropped, "offset 8 is refused"); + expect(store.set(0, 0, data, 0) == Result::dropped, "an empty write is refused"); + expect(store.set(0, 1, nullptr, 0) == Result::dropped, "a null source is refused"); + expect(store.set_one(15, 5, 0) == Result::stored && store.word(15, 0) == 5, "parameter 15 is the last one kept"); + expect(store.word(16, 0) == 0 && store.word(-1, 0) == 0 && store.word(0, 8) == 0, "reads outside the range give 0"); + + expect(store.is_bound(3, 2, 4) && store.is_bound(3, 3, 1), "written words are marked set"); + expect(!store.is_bound(3, 1, 1) && !store.is_bound(3, 1, 2) && !store.is_bound(3, 6, 1), + "words never written are not set, and a range with one unset word is not set"); + expect(store.is_bound(6, 6, 2) && !store.is_bound(6, 6, 3), "a cut-off write marks only the words that fit"); + expect(!store.is_bound(0, 0, 1), "a dropped write marks nothing"); + expect(!store.is_bound(16, 0, 1) && !store.is_bound(0, 8, 1) && !store.is_bound(0, 0, 0) && !store.is_bound(0, 7, 2), + "ranges outside the kept words are never set"); + expect(store.set_one(1, 0, 0) == Result::stored && store.is_bound(1, 0, 1) && store.word(1, 0) == 0, + "writing 0 is set, unlike never written"); + + store.clear(); + expect(store.word(3, 2) == 0 && store.word(15, 0) == 0, "clear zeroes every word"); + expect(!store.is_bound(3, 2, 4) && !store.is_bound(1, 0, 1), "clear forgets which words were set"); + + if (failures) return 1; + std::puts("root constant store ok"); + return 0; +} diff --git a/tests/startup_root_srv_draw.cpp b/tests/startup_root_srv_draw.cpp new file mode 100644 index 0000000000..e3d11e08e1 --- /dev/null +++ b/tests/startup_root_srv_draw.cpp @@ -0,0 +1,38 @@ +#include <windows.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> + +#include "startup_stream_setup.h" + +extern "C" __declspec(dllimport) void x2w_d3d12_root_srv_copies(LONG* skipped, LONG* copied); + +// A translated draw that reads a graphics root SRV set through list slot 44, at a title address without an upload +// mapping (X2W_TEST_ROOT_SRV_DRAW=write-after). Slot 44 sees the buffer holding red; the title then writes green and +// draws. The translated draw reads the SRV from its title address at the draw, so it draws green whether or not slot 44 +// also copied the bytes for the desktop binding (skipped with X2W_D3D12_ROOT_SRV_AT_DRAW=1). After the draw is recorded +// it prints the stand-in's copy counts (x2w_d3d12_root_srv_copies). The stream root's parameter 0 is a root SRV in this +// mode (startup_stream_setup.cpp). +int draw_root_srv(void* list) +{ + char mode[16]{}; + GetEnvironmentVariableA("X2W_TEST_ROOT_SRV_DRAW", mode, sizeof(mode)); + if (std::strcmp(mode, "write-after")) return 2; + const StreamWord root = reinterpret_cast<std::uintptr_t>(stream_root_signature()); + if (!root) return 40; + // Title memory outside any resource: slot 44 finds no upload mapping. + auto* colour = static_cast<float*>(VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!colour) return 41; + const float red[4] = {1, 0, 0, 1}, green[4] = {0, 1, 0, 1}; + std::memcpy(colour, red, sizeof(red)); + invoke(list, 34, root); // SetGraphicsRootSignature + invoke(list, 44, 0, reinterpret_cast<std::uintptr_t>(colour)); // SetGraphicsRootShaderResourceView(0, address) + std::memcpy(colour, green, sizeof(green)); + invoke(list, 12, 3, 1); // DrawInstanced(3, 1) + // The stand-in's slot 44 copy counts after the draw was recorded, for the check script. + LONG skipped = -1, copied = -1; + x2w_d3d12_root_srv_copies(&skipped, &copied); + std::printf("root SRV copies: skipped %ld, copied %ld\n", skipped, copied); + return 0; // The buffer stays allocated until the process ends. +} diff --git a/tests/startup_root_srv_draw_check.py b/tests/startup_root_srv_draw_check.py new file mode 100644 index 0000000000..e01f8fbde6 --- /dev/null +++ b/tests/startup_root_srv_draw_check.py @@ -0,0 +1,72 @@ +"""A graphics root SRV (list slot 44) at a title address without an upload mapping, read by a translated draw. + +tests/startup_root_srv_draw.cpp (X2W_TEST_ROOT_SRV_DRAW=write-after): slot 44 sees the buffer holding red, the title +writes green, then draws, and the stand-in's copy counts are printed. Run with X2W_D3D12_ROOT_SRV_AT_DRAW unset and set: + - both: the translated draw reads the SRV from its title address at the draw and draws green; + - unset: slot 44 also copies a window into the upload ring for the desktop binding (copied 1); + - set: no draw reads that binding, so slot 44 skips the copy (skipped 1, copied 0). +The left half of the 8x4 target is drawn, the right half keeps the clear colour. +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import prepare_draw_cache + +HLSL = ( + "ByteAddressBuffer colour : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return asfloat(colour.Load4(0));\n" + "}\n" +) +CLEAR = bytes((0, 0, 255, 255)) +GREEN = bytes((0, 255, 0, 255)) +SWITCH = "X2W_D3D12_ROOT_SRV_AT_DRAW" +COUNTS = re.compile(r"root SRV copies: skipped (-?\d+), copied (-?\d+)") + + +def run(directory, consumer, backend, at_draw): + folder = directory / f"write-after-{int(at_draw)}" + folder.mkdir() + os.environ.pop(SWITCH, None) # an inherited setting must not decide the unset case + modes = {"X2W_TEST_ROOT_SRV_DRAW": "write-after", "X2W_TRAP_LOG": str(folder / "trap.log")} + if at_draw: + modes[SWITCH] = "1" + env, args, output = prepare_draw_cache(folder, consumer, HLSL, modes, "srv 0 buf root 0") + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return None, None + if result.returncode: + raise RuntimeError(f"consumer failed ({result.returncode})\n{result.stderr[-5000:]}") + found = COUNTS.search(result.stdout) + if not found: + raise AssertionError(f"{SWITCH}={int(at_draw)}: no copy counts printed") + return output.read_bytes(), tuple(int(value) for value in found.groups()) + + +def check(directory, consumer, backend): + expected_pixels = (GREEN * 4 + CLEAR * 4) * 4 + # (skipped, copied) + expected_counts = {False: (0, 1), True: (1, 0)} + for at_draw in (False, True): + pixels, counts = run(directory, consumer, backend, at_draw) + if pixels is None: + return 77 + label = f"{SWITCH}={int(at_draw)}" + if pixels != expected_pixels: + raise AssertionError(f"{label}: actual {pixels.hex()} expected {expected_pixels.hex()}") + if counts != expected_counts[at_draw]: + raise AssertionError(f"{label}: copies (skipped, copied) {counts}, " + f"expected {expected_counts[at_draw]}") + print(f"{backend} {label}: 32 pixels exact (green, read at the draw); " + f"skipped {counts[0]}, copied {counts[1]}") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index 8d9c55a686..9efb9a1cc5 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -14,11 +14,13 @@ import subprocess import sys import tempfile +from concurrent.futures import ThreadPoolExecutor from pathlib import Path RUN_PS1 = Path(__file__).resolve().parent.parent / "tools" / "startup" / "run.ps1" DLLS = ["xmem", "d3d12_xs", "AcpHal", "XCRDAPI", "chad", "xapu", "xg_xs", "GameInput"] STUB_LINES = [f"stub debugger line {n}" for n in range(1, 8)] +STUB_ERROR = "synthetic debugger error" HEAD_LINES = 5 # run.ps1 prints this many lines of "<LogDir>.out" # The stub stands in for tools/startup/debug_launch.py: it records its arguments, # prints seven lines and exits with the code under test. @@ -30,7 +32,8 @@ import time from pathlib import Path -record = [sys.argv[1:], os.environ.get("X2W_TRACE_API")] +record = [sys.argv[1:], os.environ.get("X2W_TRACE_API"), os.environ.get("X2W_NATIVE_SHADERS"), + os.environ.get("X2W_TITLE_ID"), os.environ.get("X2W_STORAGE_MB")] Path(__file__).with_name("debugger.json").write_text(json.dumps(record), encoding="utf-8") # Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then. watch = Path(__file__).with_name("watch.json") @@ -48,12 +51,16 @@ time.sleep(0.05) for n in range(1, 8): print("stub debugger line", n) +if {emit_stderr}: + print("synthetic debugger error", file=sys.stderr) sys.exit({code}) """ # Stands in for tools/startup/gfx2hlsl.py under -Translate: starts a child process, as the parallel # workers are, records the PIDs and arguments, then waits to be stopped. The early-exit case # publishes just the watcher's PID and arguments and returns without spawning a child. WATCH_STUB = """\ +# The revisions the launcher compares with the cache: fnv(b'x2w-startup-shader-90'), b'x2w-startup-shader-90cs', +# b'x2w-startup-mesh-57-9' (synthetic, as gfx2hlsl.py spells them). import json import os import subprocess @@ -75,7 +82,7 @@ WATCH_CLEANUP = re.compile( r"if\s*\(\s*\$translator\s+-and\s+-not\s+\$translator\.HasExited\s*\)\s*\{\s*&\s*\{\s*" r"""\$ErrorActionPreference\s*=\s*['"]Continue['"]\s+&\s+taskkill\.exe\b[^|#\n]*\s/T\b""", re.I) -CAPTURE = re.compile(r"\$(\w+)\s*=\s*\$LASTEXITCODE", re.I) +CAPTURE = re.compile(r"\$(?:script:)?(\w+)\s*=\s*\$LASTEXITCODE", re.I) EXIT = re.compile(r"exit\s+\$(\w+)", re.I) HEAD = 'Get-Content "$LogDir.out" -TotalCount 5' # Without -FakeUser, user APIs hit the host runtime; run.ps1 must warn (docs/startup-runtime.md). @@ -92,6 +99,19 @@ WARNING_PREFIXES = {} +def unwrap_first_line(printed, want): + """Join the leading lines of `printed` that PowerShell wrapped at its host width back into `want`. + + The host wraps a long Write-Warning at the console width it finds (80 columns when it is not + attached to a wide console, which depends on load and on the parent), so the one warning can + arrive as two lines. Only a split of exactly `want` is joined; any other text is left as printed. + """ + for count in range(1, len(printed) + 1): + if " ".join(printed[:count]) == want: + return [want, *printed[count:]] + return printed + + def warning_prefix(shell, env): """Return the prefix this shell puts before a Write-Warning message, such as "WARNING: ". @@ -121,32 +141,62 @@ def alive(pid): return f'"{pid}"' in out.stdout +# A shader cache of an older build (#2815): its revision.txt and one request, against the stub's revisions. +OLDER_CACHE = {"revision.txt": b"graphics x2w-startup-shader-89\ncompute x2w-startup-shader-89cs\n", + "req_0123456789abcdef.a": b""} +REVISION_PHRASES = ("was written by stand-ins of revision graphics x2w-startup-shader-89", + "but the translator", "is revision graphics x2w-startup-shader-90", "Fix: rebuild the stand-ins") + + def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False, - early_exit=False, trace_api_env=None): + early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, emit_stderr=False, + missing_python=False, real_log_error=False, native=False, manifest="absent", cache_files=None): """Run one copy of the script on a stub that exits with `code`; return what is wrong. `switches` are extra run.ps1 switches and `passed` the debugger arguments they must add. `translate` exercises -Render -Translate and requires the watcher to stop with its child. With `early_exit` the watcher has no child and exits before the debugger finishes. + `native` passes -Render -NativeShaders <dir>: the stand-in gets the directory and no watcher starts. This checks the log head and debugger exit code. The live watcher case checks worker cleanup. """ root = Path(tempfile.mkdtemp(dir=work)).resolve() startup = root / "tools" / "startup" startup.mkdir(parents=True) (startup / "run.ps1").write_bytes(script.encode("utf-8")) - (startup / "debug_launch.py").write_text(STUB.format(code=code, early_exit=early_exit), encoding="utf-8") + if real_log_error: + for name in ("debug_launch.py", "launch.py", "host_cpu.py", "hook_window.py", "window_capture.py"): + shutil.copyfile(RUN_PS1.parent / name, startup / name) + else: + (startup / "debug_launch.py").write_text(STUB.format(code=code, early_exit=early_exit, emit_stderr=emit_stderr), encoding="utf-8") (startup / "gfx2hlsl.py").write_text(WATCH_STUB.format(early_exit=early_exit), encoding="utf-8") - (root / "bld").mkdir() + shutil.copyfile(RUN_PS1.with_name("shader_cache_revision.py"), startup / "shader_cache_revision.py") + if cache_files is not None: # a shader cache left by an earlier run + (root / "cache").mkdir() + for name, data in cache_files.items(): + (root / "cache" / name).write_bytes(data) + build = root / ("build [with spaces]" if absolute_build else "bld") + build.mkdir() for dll in DLLS: # the stand-ins the script copies next to the executable - (root / "bld" / f"{dll}.dll").write_bytes(b"") - exe, data, log = root / "run" / "t.exe", root / "data", root / "log" + (build / f"{dll}.dll").write_bytes(b"") + exe, data, log = root / "run" / "t.exe", root / ("data [test]" if manifest.startswith("bracket") else "data"), root / "log" exe.parent.mkdir() exe.write_bytes(b"") data.mkdir() + if real_log_error: + (log / "events.txt").mkdir(parents=True) + if manifest in ("normal", "bracket"): + (data / "MicrosoftGame.config").write_text("<TitleId>1234</TitleId><SizeMB>42</SizeMB>", encoding="utf-8") + if manifest.startswith("bracket"): + decoy = root / "data t" + decoy.mkdir() + (decoy / "MicrosoftGame.config").write_text("<TitleId>9999</TitleId><SizeMB>99</SizeMB>", encoding="utf-8") env = dict(os.environ) + env.pop("X2W_TITLE_ID", None) + env.pop("X2W_STORAGE_MB", None) # Compare PowerShell's warning text consistently on hosts that enable ANSI colors. env["NO_COLOR"] = "1" env.pop("X2W_FAKE_USER", None) + env.pop("X2W_NATIVE_SHADERS", None) if trace_api_env is None: env.pop("X2W_TRACE_API", None) else: @@ -156,9 +206,19 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), # In this tree run.ps1 finds `python` through PATH. This interpreter's directory # goes first so the stub runs under the Python that runs this check. env["PATH"] = os.path.dirname(sys.executable) + os.pathsep + env.get("PATH", "") + if missing_python: + env["PATH"] = str(Path(os.environ["SystemRoot"]) / "System32") + build_arg = str(build) if absolute_build else "bld" + if missing_build: + build_arg = str(root / "missing build") command = [shell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(startup / "run.ps1"), - "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), "-BuildDir", "bld", - "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", *switches] + "-Exe", str(exe), "-DataDir", str(data), "-LogDir", str(log), + "-BuildDir", build_arg, + "-Seconds", "9", "-MemoryGiB", "3", "-ContinueAsserts", "4", "-AssertSites", "2", *switches] + sdk = root / "dxc" + if native: + sdk.mkdir() + command += ["-Render", "-NativeShaders", str(sdk), "-ShaderCache", "cache"] if translate: command += ["-Render", "-Translate", "-ShaderCache", "cache"] (startup / "translate.flag").write_bytes(b"") @@ -174,27 +234,53 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), stderr.seek(0) printed = [line.strip() for line in stdout if line.strip()] error_text = stderr.read().strip() + if missing_python: + return (["missing Python returned success"] if out.returncode == 0 else []) + ( + ["missing Python launched debugger"] if (startup / "debugger.json").exists() else []) + if real_log_error: + summary = Path(str(log) + ".out") + text = decode(summary.read_bytes()) if summary.is_file() else "" + return ([f"real debugger log error returned {out.returncode}, expected 1"] if out.returncode != 1 else []) + ( + ["real debugger log error was not captured in the summary"] if "PermissionError" not in text else []) found = [] + for dll in DLLS: + if not (exe.parent / f"{dll}.dll").is_file(): + found.append(f"stand-in {dll}.dll was not copied") if out.returncode != code: found.append(f"stub debugger exited {code}, run.ps1 exited {out.returncode}") - want_output = STUB_LINES[:HEAD_LINES] + summary = Path(str(log) + ".out") + summary_lines = [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] if summary.is_file() else [] + want_output = summary_lines[:HEAD_LINES] if emit_stderr else STUB_LINES[:HEAD_LINES] + if cache_files is not None: + # One warning with both revisions and the fixes; PowerShell may wrap it, so compare without whitespace. + flat = re.sub(r"\s", "", " ".join(printed)) + missing = [phrase for phrase in REVISION_PHRASES if re.sub(r"\s", "", phrase) not in flat] + if missing or flat.count("Fix:rebuildthestand-ins") != 1: + found.append(f"stale shader cache: no single revision warning with {missing} (printed {printed})") + printed = [line for line in printed if line in STUB_LINES] # the case runs with -FakeUser: no other warning if not fake_user_env and "-FakeUser" not in switches: want_output = [warning_prefix(shell, env) + FAKE_USER_WARNING, *want_output] + printed = unwrap_first_line(printed, want_output[0]) if printed != want_output: found.append(f"stub exit {code}: printed {printed}, expected {want_output} " f"(stderr: {error_text!r})") - summary = Path(str(log) + ".out") if not summary.is_file(): found.append(f"stub exit {code}: {summary.name} was not written") - elif [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] != STUB_LINES: + elif emit_stderr and ([line for line in summary_lines if line in STUB_LINES] != STUB_LINES or + not any(STUB_ERROR in line for line in summary_lines)): + found.append(f"stub exit {code}: {summary.name} does not hold stdout and stderr") + elif not emit_stderr and summary_lines != STUB_LINES: found.append(f"stub exit {code}: {summary.name} does not hold the debugger's output") want = [str(exe), str(data), str(log), "--timeout", "9", "--memory-gib", "3", - "--trace-files", "1", "--continue-asserts", "4", *passed] + "--trace-files", "1", "--continue-asserts", "4", "--assert-sites", "2", *passed] record = startup / "debugger.json" got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None - expected = [want, "1" if "-TraceApi" in switches else trace_api_env] + expected = [want, "1" if "-TraceApi" in switches else trace_api_env, + str(sdk) if native else None, + "1234" if manifest in ("normal", "bracket") else None, + "42" if manifest in ("normal", "bracket") else None] if got != expected: - found.append(f"stub exit {code}: debugger [argv, X2W_TRACE_API] was {got}, expected {expected}") + found.append(f"stub exit {code}: debugger [argv, trace, native shaders, title ID, storage MB] was {got}, expected {expected}") watch = startup / "watch.json" if translate: started = json.loads(watch.read_text(encoding="utf-8")) if watch.is_file() else None @@ -218,17 +304,35 @@ def run_problems(shell, script, work, first_only): found += run_case(shell, script, code, work) if found and first_only: return found + found += run_case(shell, script, 7, work, absolute_build=True) + for manifest in ("normal", "bracket", "bracket_missing"): + found += run_case(shell, script, 0, work, manifest=manifest) + if found and first_only: + return found + for code in (0, 7): + found += run_case(shell, script, code, work, emit_stderr=True) + if found and first_only: + return found + found += run_case(shell, script, 7, work, translate=True, emit_stderr=True) + if found and first_only: + return found found += run_case(shell, script, 0, work, switches=["-FakeUser"]) found += run_case(shell, script, 0, work, fake_user_env=True) if found and first_only: return found # -TraceCalls arms the debugger's call hooks; without it the arguments above stay as they are. found += run_case(shell, script, 0, work, switches=["-TraceCalls"], passed=["--trace-calls", "1"]) + found += run_case(shell, script, 0, work, switches=["-CaptureEvery", "5"], passed=["--capture-every", "5"]) + # -SuspendOthers 0 turns off the debugger's thread holding (#1408); 1 is its default and adds nothing. + found += run_case(shell, script, 0, work, switches=["-SuspendOthers", "0"], passed=["--suspend-others", "0"]) + found += run_case(shell, script, 0, work, switches=["-SuspendOthers", "1"]) found += run_case(shell, script, 0, work, switches=["-TraceApi"], trace_api_env="0") found += run_case(shell, script, 0, work, trace_api_env="1") + found += run_case(shell, script, 0, work, native=True) if found and first_only: return found found += run_case(shell, script, 7, work, translate=True) + found += run_case(shell, script, 7, work, translate=True, switches=["-FakeUser"], cache_files=OLDER_CACHE) for code in (0, 7): found += run_case(shell, script, code, work, translate=True, early_exit=True) return found @@ -267,6 +371,8 @@ def text_problems(script): if not re.search(r"""^if\s*\(\s*\$TraceApi\s*\)\s*\{\s*\$env:X2W_TRACE_API\s*=\s*["']1["']\s*\}""", before, re.I | re.M): found.append("missing -TraceApi environment opt-in before launch") + if not re.search(r"\$env:X2W_NATIVE_SHADERS\s*=", before): + found.append("missing -NativeShaders directory hand-over before launch") if not WATCH_CLEANUP.search("\n".join(after)): found.append("tree cleanup lacks taskkill /T, the live-watcher guard or the local Continue scope") return found @@ -288,6 +394,7 @@ def mutants_of(script): "fixed exit 2": ["exit 2" if is_exit(line) else line for line in lines], "exit before the log head": early, "no FakeUser warning": no_fake_warn, + "no X2W_NATIVE_SHADERS": [line for line in lines if "$env:X2W_NATIVE_SHADERS" not in line], # The same text without the warning prefix: the run must still see Write-Warning's prefix. "FakeUser warning printed with Write-Host": [ line.replace(FAKE_USER_WARN_LINE, f'Write-Host "{FAKE_USER_WARNING}"') for line in lines], @@ -295,6 +402,61 @@ def mutants_of(script): return {name: None if mutant == lines else "\n".join(mutant) + "\n" for name, mutant in mutants.items()} +def shell_failures(shell, script, tmp): + """Every failure for one shell (None: the text-only checks), in a fixed order.""" + failures = [] + name = Path(shell).stem.lower() if shell else "text" + bad = run_problems(shell, script, tmp, False) + failures += [f"{name}: {item}" for item in bad] + if bad: + return failures + for label, mutant in mutants_of(script).items(): + if mutant is None or not run_problems(shell, mutant, tmp, True): + failures.append(f"{name}: mutant '{label}' was not detected") + if shell: + failures += [f"{name}: {item}" for item in run_case(shell, script, 7, tmp, real_log_error=True)] + failures += [f"{name}: {item}" for item in run_case(shell, script, 7, tmp, missing_python=True)] + missing = run_case(shell, script, 7, tmp, missing_build=True) + if not any("debugger [argv" in item and "was None" in item for item in missing): + failures.append(f"{name}: missing build directory did not prevent debugger startup") + # Expire the live fixture tree after HasExited has been read. The launcher's + # own taskkill then hits the missing PID and writes native stderr. + kill = f"& {STOP} 2>&1 | Out-Null" + expire = kill + '\nif (-not $translator.WaitForExit(5000)) { throw "fixture watcher still alive" }\n' + race = script.replace(kill, expire + kill) + if race == script: + failures.append(f"{name}: could not exercise the watcher exit during cleanup") + else: + failures += [f"{name}: watcher exit during cleanup: {item}" + for item in run_case(shell, race, 7, tmp, translate=True)] + stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" + parent_only = script.replace(STOP, "Stop-Process -Id $translator.Id -Force") + for mutant, who in ((stopless, "translator"), (parent_only, "translator's child process")): + problems = run_case(shell, mutant, 7, tmp, translate=True) + if f"-Translate: the {who} was still running after run.ps1 exited" not in problems: + failures.append(f"{name}: expected a surviving {who}, got {problems}") + else: + for removed in (' -and -not $translator.HasExited', '$ErrorActionPreference = "Continue"', '/T '): + if not text_problems(script.replace(removed, '')): + failures.append(f"text: removing {removed.strip()} escaped the cleanup check") + return failures + + +def unwrap_problems(): + """Controls for unwrap_first_line: a wrapped warning joins, any other text is left alone.""" + want = "WARNING: Without -FakeUser, user API calls go to the host gaming runtime (docs/x.md)." + head = "WARNING: Without -FakeUser, user API calls go to the host gaming runtime" + cases = [ + ("one line", [want, "a"], [want, "a"]), + ("wrapped at 80 columns", [head, "(docs/x.md).", "a"], [want, "a"]), + ("different text", [head, "(docs/other.md).", "a"], [head, "(docs/other.md).", "a"]), + ("missing warning", ["a"], ["a"]), + ] + return [f"unwrap_first_line {name}: got {got}, expected {expected}" + for name, printed, expected in cases + if (got := unwrap_first_line(printed, want)) != expected] + + def main(): if sys.argv[1:] not in ([], ["--text-only"]): sys.exit("usage: startup_run_ps1_check.py [--text-only]") @@ -309,38 +471,13 @@ def main(): mode = "executed with " + ", ".join(Path(shell).stem.lower() for shell in shells) if not shells: mode = "text only: no PowerShell found" - failures = [] + failures = unwrap_problems() with tempfile.TemporaryDirectory() as tmp: - for shell in shells or [None]: - name = Path(shell).stem.lower() if shell else "text" - bad = run_problems(shell, script, tmp, False) - failures += [f"{name}: {item}" for item in bad] - if bad: - continue - for label, mutant in mutants_of(script).items(): - if mutant is None or not run_problems(shell, mutant, tmp, True): - failures.append(f"{name}: mutant '{label}' was not detected") - if shell: - # Expire the live fixture tree after HasExited has been read. The launcher's - # own taskkill then hits the missing PID and writes native stderr. - kill = f"& {STOP} 2>&1 | Out-Null" - expire = kill + '\nif (-not $translator.WaitForExit(5000)) { throw "fixture watcher still alive" }\n' - race = script.replace(kill, expire + kill) - if race == script: - failures.append(f"{name}: could not exercise the watcher exit during cleanup") - else: - failures += [f"{name}: watcher exit during cleanup: {item}" - for item in run_case(shell, race, 7, tmp, translate=True)] - stopless = "\n".join(line for line in script.splitlines() if STOP not in line) + "\n" - parent_only = script.replace(STOP, "Stop-Process -Id $translator.Id -Force") - for mutant, who in ((stopless, "translator"), (parent_only, "translator's child process")): - problems = run_case(shell, mutant, 7, tmp, translate=True) - if f"-Translate: the {who} was still running after run.ps1 exited" not in problems: - failures.append(f"{name}: expected a surviving {who}, got {problems}") - else: - for removed in (' -and -not $translator.HasExited', '$ErrorActionPreference = "Continue"', '/T '): - if not text_problems(script.replace(removed, '')): - failures.append(f"text: removing {removed.strip()} escaped the cleanup check") + # Each shell works in its own scratch dirs, so PowerShell 5.1 and 7 run side by side. + with ThreadPoolExecutor(max_workers=len(shells) or 1) as pool: + jobs = [pool.submit(shell_failures, shell, script, tmp) for shell in shells or [None]] + for job in jobs: + failures += job.result() for item in failures: print("FAIL", item) print(f"startup run.ps1 exit code: {len(failures)} failed ({mode})") diff --git a/tests/startup_run_sh_check.py b/tests/startup_run_sh_check.py index beab30d418..cb30331d60 100644 --- a/tests/startup_run_sh_check.py +++ b/tests/startup_run_sh_check.py @@ -11,6 +11,7 @@ """ import json import os +import re import shutil import signal import subprocess @@ -28,12 +29,23 @@ CHECKED = PERMISSIVE + [ "X2W_FAKE_USER", "X2W_XMEM_GPU_MIRROR", "X2W_HOST_CPU", "X2W_XMEM_STARTUP_BELOW_40", "X2W_HIDE_TITLE_WINDOW", "X2W_D3D12_RENDER", "X2W_DRAW_NULL_IDENTITY", "X2W_SHADER_CACHE", "X2W_TITLE_ID", "X2W_STORAGE_MB", - "X2W_STORAGE_PATH", "X2W_INPUT_SCRIPT", "X2W_XMEM_SHARED_VIEWS", "WINEDLLOVERRIDES", "WINEFSYNC", "WINEDEBUG", - "WINEPREFIX", "XDG_RUNTIME_DIR", "PULSE_SERVER", "X2W_FXC"] + "X2W_STORAGE_PATH", "X2W_INPUT_SCRIPT", "X2W_XMEM_SHARED_VIEWS", "X2W_XMEM_JOIN_CALLS", "WINEDLLOVERRIDES", + "WINEFSYNC", "WINEDEBUG", "WINEPREFIX", "XDG_RUNTIME_DIR", "PULSE_SERVER", "X2W_FXC"] GAME_OVERRIDES = "d3d12,d3d12core,dxgi,d3d11=n" # docs/wine.md FAKE_USER_WARNING = ("WARNING: Without --fake-user, user API calls go to the host gaming runtime " "(docs/startup-runtime.md).") TRANSLATE_WARNING = "WARNING: --translate needs --render (no shader cache without it); ignored" +# A cache of an older build (#2815): its revision.txt and one request, against the stub translator's revisions. +REQUEST = "req_0123456789abcdef.a" +OLDER_CACHE = {"revision.txt": b"graphics x2w-startup-shader-89\ncompute x2w-startup-shader-89cs\n", REQUEST: b""} +SAME_CACHE = {"revision.txt": b"graphics x2w-startup-shader-90\ncompute x2w-startup-shader-90cs\n" + b"mesh57 x2w-startup-mesh-57-9\n", REQUEST: b""} +REVISION_WARNING = re.compile(r"WARNING: shader cache \S+ was written by stand-ins of revision graphics " + r"x2w-startup-shader-89, compute x2w-startup-shader-89cs, but the translator \S+ is " + r"revision graphics x2w-startup-shader-90, compute x2w-startup-shader-90cs, mesh57 " + r"x2w-startup-mesh-57-9: .*Fix: rebuild the stand-ins .*") +LEGACY_WARNING = re.compile(r"WARNING: shader cache \S+ holds requests but no revision.txt, so their revision is unknown: .*Fix: .*") +MOVED_NOTE = re.compile(r"moved the old shader cache \S+ to \S+cache\.old-[0-9]{8}-[0-9]{6}") HIDE_WARNING = "WARNING: --hide-title-window needs --render (no output window without it); it has no effect" # Synthetic package values; not any title's. Only the first of each tag counts, as in run.ps1. CONFIG = ("<Game>\r\n<Identity/>\r\n<TitleId>X2WTEST</TitleId>\r\n<TitleId>SECOND</TitleId>\r\n" @@ -113,6 +125,8 @@ def alive(pid): # workers are, records its own and the child's process ids, its arguments and environment, then # waits to be stopped. Both ignore SIGTERM, so only run.sh's SIGKILL fallback stops them. WATCH_STUB = """\ +# The revisions the launcher compares with the cache: fnv(b'x2w-startup-shader-90'), b'x2w-startup-shader-90cs', +# b'x2w-startup-mesh-57-9' (synthetic, as gfx2hlsl.py spells them). import json import os import subprocess @@ -153,7 +167,7 @@ def read_json(path): def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_data=False, config=CONFIG, translate=False, stop=None, drive_log=False, log_slash=False, expect_env=None, expect_warnings=None, - expect_exit=None): + expect_exit=None, cache_files=None, expect_moved=False): """Run one copy of the script on a stub that exits with `code`; return what is wrong.""" root = Path(tempfile.mkdtemp(dir=work)).resolve() startup = root / "tools" / "startup" @@ -168,6 +182,11 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d (startup / "debug_launch.py").write_text( STUB.format(code=code, alive=ALIVE, prefixes=ENV_PREFIXES), encoding="utf-8") (startup / "gfx2hlsl.py").write_text(WATCH_STUB.format(prefixes=ENV_PREFIXES), encoding="utf-8") + shutil.copyfile(RUN_SH.with_name("shader_cache_revision.py"), startup / "shader_cache_revision.py") + if cache_files is not None: # a shader cache left by an earlier run + (root / "cache").mkdir() + for name, data in cache_files.items(): + (root / "cache" / name).write_bytes(data) wine = root / "wine" wine.write_text(WINE_STUB, encoding="utf-8") wine.chmod(0o755) @@ -197,7 +216,7 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d log = data / "logs" command = ["bash", str(startup / "run.sh"), "--exe", str(exe), "--data", "G:\\" if drive_data else str(data), "--log", log_arg, "--build-dir", "bld", "--seconds", "9", "--memory-gib", "3", - "--continue-asserts", "4", *switches] + "--continue-asserts", "4", "--assert-sites", "2", *switches] if translate: command += ["--render", "--translate", "--shader-cache", "cache"] (startup / "translate.flag").write_bytes(b"") @@ -245,8 +264,15 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d expect_warnings = [] if fake else [FAKE_USER_WARNING] if "--hide-title-window" in switches and "--render" not in switches and not translate: expect_warnings.append(HIDE_WARNING) - if warnings != expect_warnings: + # A pattern stands for a line that names scratch paths. + if len(warnings) != len(expect_warnings) or not all( + want.fullmatch(got) if isinstance(want, re.Pattern) else want == got + for want, got in zip(expect_warnings, warnings)): found.append(f"{label}: warnings {warnings}, expected {expect_warnings}") + if expect_moved: + moved = [p for p in root.iterdir() if p.name.startswith("cache.old-")] + if len(moved) != 1 or not (moved[0] / REQUEST).is_file() or list((root / "cache").iterdir()): + found.append(f"{label}: --fresh-shader-cache did not move the old cache aside ({moved})") if stop == "term" and not debugger_done: found.append(f"{label}: run.sh ended before the debugger finished") if drive_log: @@ -266,13 +292,13 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d if missing: found.append(f"{label}: stand-in DLLs not copied next to the executable: {missing}") want = [win(exe), "G:\\" if drive_data else win(data), log_win, "--timeout", "9", "--memory-gib", "3", - "--trace-files", "1", "--continue-asserts", "4", *passed] + "--trace-files", "1", "--continue-asserts", "4", "--assert-sites", "2", *passed] got = read_json(startup / "argv.json") if got != want: found.append(f"{label}: the debugger received {got}, expected {want}") seen = read_json(startup / "env.json") or {} expected = {name: "1" for name in PERMISSIVE} - expected.update(X2W_XMEM_SHARED_VIEWS="1", X2W_TITLE_ID="X2WTEST", X2W_STORAGE_MB="123", + expected.update(X2W_XMEM_SHARED_VIEWS="1", X2W_XMEM_JOIN_CALLS="1", X2W_TITLE_ID="X2WTEST", X2W_STORAGE_MB="123", WINEDLLOVERRIDES=GAME_OVERRIDES, WINEFSYNC="1", WINEDEBUG="-all", WINEPREFIX=str(prefix)) if translate: expected.update(X2W_D3D12_RENDER="1", X2W_DRAW_NULL_IDENTITY="1", X2W_SHADER_CACHE=win(root / "cache"), @@ -317,6 +343,12 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d dict(code=0, switches=["--fake-user"], expect_env={"X2W_FAKE_USER": "1"}), dict(code=0, env_extra={"X2W_FAKE_USER": "1"}, expect_env={"X2W_FAKE_USER": "1"}), dict(code=0, switches=["--trace-calls", "--console", "0"], passed=["--trace-calls", "1", "--console", "0"]), + dict(code=0, switches=["--capture-every", "5"], passed=["--capture-every", "5"]), + # --suspend-others 0 turns off the debugger's thread holding (#1408); 1 is its default and adds nothing. + dict(code=0, switches=["--suspend-others", "0"], passed=["--suspend-others", "0"]), + dict(code=0, switches=["--suspend-others", "1"]), + dict(code=0, switches=["--suspend-others", "2"], expect_exit=64, + expect_warnings=["run.sh: --suspend-others takes 0 or 1"]), # --data as a drive path stays as it is; its config is read through the prefix's dosdevices. # --storage is relative to the working directory, the scratch root, and gains a backslash. dict(code=7, drive_data=True, @@ -349,6 +381,13 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d dict(code=0, env_extra={"WINEPREFIX": ""}, expect_exit=64, expect_warnings=["run.sh: set WINEPREFIX"]), dict(code=0, env_extra={"X2W_WIN_PYTHON": ""}, expect_exit=64, expect_warnings=["run.sh: set X2W_WIN_PYTHON"]), dict(code=7, translate=True), + # A cache from another revision, or from a build that wrote no revision.txt, warns once; a matching one does not. + dict(code=7, translate=True, cache_files=OLDER_CACHE, expect_warnings=[FAKE_USER_WARNING, REVISION_WARNING]), + dict(code=7, translate=True, cache_files={REQUEST: b""}, expect_warnings=[FAKE_USER_WARNING, LEGACY_WARNING]), + dict(code=7, translate=True, cache_files=SAME_CACHE), + # --fresh-shader-cache moves the old cache aside, so the run starts empty and does not warn. + dict(code=7, translate=True, cache_files=OLDER_CACHE, switches=["--fresh-shader-cache"], expect_moved=True, + expect_warnings=[FAKE_USER_WARNING, MOVED_NOTE]), dict(code=7, translate=True, stop="int"), dict(code=7, translate=True, stop="term"), ] @@ -384,6 +423,7 @@ def mutants_of(script): "no FakeUser warning": replace(script, ' echo "WARNING: Without --fake-user', ' : "WARNING: Without --fake-user'), "short DLL list": replace(script, " xg_xs GameInput; do", " xg_xs; do"), "no shared views": drop_line(script, "export X2W_XMEM_SHARED_VIEWS="), + "no join calls": drop_line(script, "export X2W_XMEM_JOIN_CALLS="), "watcher without --render": replace(script, 'if [ -n "$translate" ] && [ -n "$render" ]; then', 'if [ -n "$translate" ]; then'), "config not read": replace(script, 'if [ -f "$config" ]; then', "if false; then"), @@ -392,6 +432,8 @@ def mutants_of(script): "title_id=$(sed -n 's/.*<TitleId>\\([^<]*\\).*/\\1/p' \"$config\" | head -n 1)"), "case-sensitive tags": replace(script, "grep -oi '<", "grep -o '<", count=2), "no hide warning": replace(script, ' echo "WARNING: --hide-title-window', ' : "WARNING: --hide-title-window'), + "no revision warning": replace(script, ' echo "WARNING: $note" >&2', ' : "WARNING: $note"'), + "fresh cache kept": replace(script, ' if [ -n "$fresh_cache" ]; then', ' if false; then'), "log through the raw path": replace(script, 'log_host=$(host_path "$log")', 'log_host=$log'), "cache through the raw path": replace(script, 'mkdir -p "$(host_path "$shader_cache")"', 'mkdir -p "$shader_cache"'), "trailing separator kept": drop_line(script, "do log=${log%?}; done"), diff --git a/tests/startup_runtime_proxy_scope/decoy.cpp b/tests/startup_runtime_proxy_scope/decoy.cpp index ddba2565e0..86f8aefe30 100644 --- a/tests/startup_runtime_proxy_scope/decoy.cpp +++ b/tests/startup_runtime_proxy_scope/decoy.cpp @@ -1,4 +1,5 @@ -// Unrelated DLL that also exports QueryApiImpl; must not become the cached gaming-runtime provider. +// Unrelated DLL that also exports QueryApiImpl and RegQueryValueExW; must not become the cached +// gaming-runtime provider or the remembered registry function. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -6,6 +7,7 @@ namespace { LONG calls; +LONG registry_calls; } extern "C" __declspec(dllexport) LONG WINAPI query_calls() { return InterlockedCompareExchange(&calls, 0, 0); } @@ -16,3 +18,12 @@ extern "C" __declspec(dllexport) HRESULT WINAPI QueryApiImpl(const GUID*, const if (out) *out = nullptr; return 0xA11C0001; // distinct from the fake xgameruntime path } + +extern "C" LONG WINAPI registry_query_calls() { return InterlockedCompareExchange(®istry_calls, 0, 0); } + +// Exported as RegQueryValueExW (decoy.def): a result no registry returns. +extern "C" LONG WINAPI decoy_reg_query_value_ex_w(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + InterlockedIncrement(®istry_calls); + return 0x5EC1; +} diff --git a/tests/startup_runtime_proxy_scope/decoy.def b/tests/startup_runtime_proxy_scope/decoy.def index 223c116b56..9da19864b5 100644 --- a/tests/startup_runtime_proxy_scope/decoy.def +++ b/tests/startup_runtime_proxy_scope/decoy.def @@ -2,3 +2,5 @@ LIBRARY startup_runtime_proxy_decoy EXPORTS QueryApiImpl query_calls + RegQueryValueExW = decoy_reg_query_value_ex_w + registry_query_calls diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index ec4221b3e9..516e652699 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -4,7 +4,8 @@ // unrelated decoy that also exports QueryApiImpl, then a helper beside the EXE. The helper's // GetProcAddress IAT is rewritten after linking (outside LdrDllNotification). Looking up // QueryApiImpl on xgameruntime must return the proxy; the same name on the decoy must still be the -// decoy's export. No game files. +// decoy's export. RegQueryValueExW is hooked on advapi32.dll only: the decoy's same-named export stays +// its own, with X2W_DEVICE_TYPE unset and set, and never becomes the registry the hook calls. No game files. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -25,6 +26,8 @@ void check(const char* label, bool ok) using ResolveFn = FARPROC(WINAPI*)(HMODULE); using QueryFn = HRESULT(WINAPI*)(const GUID*, const GUID*, void**); +using RegQueryFn = LONG(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using SeenFn = LONG(WINAPI*)(); std::wstring dir_of_self() { @@ -69,6 +72,11 @@ int main() const FARPROC xgr_query = xgr ? GetProcAddress(xgr, "QueryApiImpl") : nullptr; check("xgameruntime exports QueryApiImpl", xgr_query != nullptr); check("decoy and xgameruntime exports differ", decoy_query && xgr_query && decoy_query != xgr_query); + const FARPROC decoy_reg = decoy ? GetProcAddress(decoy, "RegQueryValueExW") : nullptr; + check("decoy exports RegQueryValueExW", decoy_reg != nullptr); + const HMODULE advapi = LoadLibraryW(L"advapi32.dll"); + const FARPROC advapi_reg = advapi ? GetProcAddress(advapi, "RegQueryValueExW") : nullptr; + check("advapi32.dll exports RegQueryValueExW", advapi_reg != nullptr && advapi_reg != decoy_reg); const HMODULE carrier = load_beside(dir, L"startup_runtime_proxy_carrier.dll"); check("load proxy carrier", carrier != nullptr); @@ -99,7 +107,6 @@ int main() check("helper GetProcAddress(decoy) stays original", helper_decoy == decoy_query); // Intended call: invoke the proxied entry; the fake xgameruntime must run. - using SeenFn = LONG(WINAPI*)(); const auto xgr_seen = xgr ? reinterpret_cast<SeenFn>(GetProcAddress(xgr, "query_calls")) : nullptr; const auto decoy_seen = decoy ? reinterpret_cast<SeenFn>(GetProcAddress(decoy, "query_calls")) : nullptr; const LONG xgr_before = xgr_seen ? xgr_seen() : -1; @@ -109,6 +116,32 @@ int main() check("proxied call reached xgameruntime", xgr_seen && xgr_seen() == xgr_before + 1); check("decoy call reached decoy only", decoy_seen && decoy_seen() == decoy_before + 1); + // Registry names, with the switch unset and set. The decoy is looked up first each time, so a + // match by name alone would keep the decoy as the registry the hook calls. + const auto decoy_reg_seen = decoy ? reinterpret_cast<SeenFn>(GetProcAddress(decoy, "registry_query_calls")) : nullptr; + DWORD type = 0, bytes = 0; + const LONG expect_real = advapi_reg ? reinterpret_cast<RegQueryFn>(advapi_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check("advapi32.dll's own answer differs from the decoy's", expect_real != 0x5EC1); + for (const wchar_t* device : {static_cast<const wchar_t*>(nullptr), L"7"}) { + SetEnvironmentVariableW(L"X2W_DEVICE_TYPE", device); + const std::string pass = device ? "X2W_DEVICE_TYPE=7: " : "switch unset: "; + const FARPROC host_decoy_reg = decoy ? GetProcAddress(decoy, "RegQueryValueExW") : nullptr; + check((pass + "host GetProcAddress(decoy, RegQueryValueExW) stays original").c_str(), host_decoy_reg == decoy_reg); + const LONG decoy_before = decoy_reg_seen ? decoy_reg_seen() : -1; + const LONG decoy_answer = + host_decoy_reg ? reinterpret_cast<RegQueryFn>(host_decoy_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check((pass + "decoy RegQueryValueExW answers its own result").c_str(), + decoy_answer == 0x5EC1 && decoy_reg_seen && decoy_reg_seen() == decoy_before + 1); + const FARPROC host_advapi_reg = advapi ? GetProcAddress(advapi, "RegQueryValueExW") : nullptr; + check((pass + "host GetProcAddress(advapi32, RegQueryValueExW) is hooked").c_str(), + host_advapi_reg && host_advapi_reg != advapi_reg && host_advapi_reg != decoy_reg); + const LONG hooked_answer = + host_advapi_reg ? reinterpret_cast<RegQueryFn>(host_advapi_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check((pass + "hooked RegQueryValueExW reaches advapi32.dll, not the decoy").c_str(), + hooked_answer == expect_real && decoy_reg_seen && decoy_reg_seen() == decoy_before + 1); + } + SetEnvironmentVariableW(L"X2W_DEVICE_TYPE", nullptr); + if (failures) { std::printf("startup_runtime_proxy_scope: FAIL (%d)\n", failures); return 1; diff --git a/tests/startup_runtime_target_check.py b/tests/startup_runtime_target_check.py new file mode 100644 index 0000000000..82aa90a093 --- /dev/null +++ b/tests/startup_runtime_target_check.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Check the `startup_runtime` target (`cmake --build --preset runtime`): the eight DLLs tools/startup/run.ps1 copies +and no executable. + +usage: startup_runtime_target_check.py <cmake> <build dir> <run.ps1> <dll>... + +1. `cmake --build <build dir> --target startup_runtime` succeeds and leaves every DLL on disk. +2. The DLL names are exactly the ones run.ps1 copies next to the title. +3. Ninja's recursive inputs of the target contain no executable: the target does not pull in a test program. +""" +import os +import re +import subprocess +import sys + + +def main(argv): + cmake, build, run_ps1, dlls = argv[1], argv[2], argv[3], argv[4:] + for dll in dlls: # a full build leaves them on disk: delete first, so the target itself has to build each one + if os.path.isfile(dll): + os.remove(dll) + built = subprocess.run([cmake, "--build", build, "--target", "startup_runtime"], capture_output=True, text=True) + assert built.returncode == 0, built.stdout[-2000:] + built.stderr[-2000:] + for dll in dlls: + assert os.path.isfile(dll), "startup_runtime did not leave " + dll + with open(run_ps1, encoding="utf-8") as handle: + copied = re.search(r"foreach \(\$dll in (.*?)\) \{", handle.read()).group(1) + wanted = sorted(name.lower() for name in re.findall(r'"([A-Za-z0-9_]+)"', copied)) + got = sorted(os.path.splitext(os.path.basename(dll))[0].lower() for dll in dlls) + assert got == wanted, "run.ps1 copies %s, the target builds %s" % (wanted, got) + inputs = subprocess.run(["ninja", "-C", build, "-t", "inputs", "startup_runtime"], capture_output=True, text=True) + assert inputs.returncode == 0, inputs.stdout[-2000:] + inputs.stderr[-2000:] + executables = [line for line in inputs.stdout.splitlines() if line.strip().lower().endswith(".exe")] + assert not executables, "startup_runtime depends on executables: %s" % executables[:5] + assert inputs.stdout.strip(), "ninja listed no inputs for startup_runtime" + print("startup_runtime builds the %d DLLs run.ps1 copies and no executable" % len(dlls)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/startup_sampler_heap_check.py b/tests/startup_sampler_heap_check.py index 882ab32549..973315a459 100644 --- a/tests/startup_sampler_heap_check.py +++ b/tests/startup_sampler_heap_check.py @@ -289,7 +289,29 @@ def heap(flags): for slot, address_u in ((1, 1), (2, 3)): desc = c.create_string_buffer(struct.pack('<4If2I6f', 0, address_u, 3, 3, 0.0, 1, 1, *([0.0] * 6))) create_sampler(device, desc, src + 16 * slot, 0, 0) - assert source[0] == 0xABCDEF00 and source[4] == source[8] == 0x56573258, list(source) + # The console method and the desktop method must publish identical tokens + # for equivalent samplers, including when the U address mode changes. + console_sampler = method(device, 61, None, ptr, word) + console = (uint * 27)() + console[7] = console[8] = 3 + for slot, address_u in ((1, 1), (2, 3)): + console[6] = address_u + console_sampler(device, console, src) + assert source[:4] == source[4 * slot:4 * slot + 4], list(source) + # Independently encode linear min/mip + point mag, three address modes, + # explicit bias, border and LOD range in each ABI. + mixed = c.create_string_buffer(struct.pack('<4If2I6f', 0x11, 2, 3, 4, -.5, 1, 1, + .25, .5, .75, 1., 1., 3.)) + create_sampler(device, mixed, src, 0, 0) + expected = list(source[:4]) + assert expected != list(source[4:8]) and expected != list(source[8:12]) + console[2], console[3] = 1, 2 + console[6:9] = 2, 3, 4 + console[9:12] = struct.unpack('<3I', struct.pack('<3f', 1., 3., -.5)) + console[17:21] = struct.unpack('<4I', struct.pack('<4f', .25, .5, .75, 1.)) + console_sampler(device, console, src) + assert list(source[:4]) == expected, list(source) + assert source[4] == source[8] == 0x56573258, list(source) assert source[5] != source[9], 'distinct samplers produced the same token' method(device, 24, None, uint, word, word, uint)(device, 1, dst + 32, src + 16, 1) assert target[8:12] == source[4:8] and target[:8] == [0xABCDEF00] * 8, list(target) diff --git a/tests/startup_sampler_x.cpp b/tests/startup_sampler_x.cpp index a64ce2bd77..3f49a03cfb 100644 --- a/tests/startup_sampler_x.cpp +++ b/tests/startup_sampler_x.cpp @@ -18,8 +18,11 @@ constexpr UINT texture_size = 8; constexpr UINT mip_levels = 4; constexpr float border_value = 1.0f; // OPAQUE_WHITE red channel; every texel value is at least 2. // Linear probes use 0.25-step texel fractions and a 0.5 LOD fraction, which fixed-point filter -// weights represent exactly; the tolerance only absorbs float rounding. +// weights represent exactly. D3D12 only requires the bilinear weights and the mip weight to carry +// 8 fractional bits (D3D11.3 functional spec, texture filtering precision), so a sampler may move a weight +// by one 1/256 step. The tolerance is that step times the texel range the weight blends, plus float rounding. constexpr float linear_tolerance = 0.01f; +constexpr float weight_step = 1.0f / 256.0f; struct Probe { float u, v, lod; @@ -128,6 +131,29 @@ float reference(const SamplerCase& s, const Probe& p) return bilinear(s, mip, p.u, p.v) * (1 - f) + bilinear(s, next, p.u, p.v) * f; } +// Largest value difference inside the 2x2 footprint of one mip: what a one-step weight error is multiplied by. +float footprint_span(const SamplerCase& s, UINT mip, float u, float v) +{ + const float n = static_cast<float>(texture_size >> mip); + const int x = static_cast<int>(std::floor(u * n - 0.5f)), y = static_cast<int>(std::floor(v * n - 0.5f)); + const float a = fetch(s, mip, x, y), b = fetch(s, mip, x + 1, y); + const float c = fetch(s, mip, x, y + 1), d = fetch(s, mip, x + 1, y + 1); + return (std::max)((std::max)(a, b), (std::max)(c, d)) - (std::min)((std::min)(a, b), (std::min)(c, d)); +} + +// Point filtering is exact. Linear filtering may move each 8-bit weight by one step: the two bilinear weights +// act within a mip, and the mip weight acts across the difference between the two bilinear results. +float tolerance_for(const SamplerCase& s, const Probe& p) +{ + if (!is_linear(s)) return 0.0f; + const float lod = (std::min)((std::max)(p.lod, s.min_lod), (std::min)(s.max_lod, float(mip_levels - 1))); + const UINT mip = static_cast<UINT>(lod); + const UINT next = (std::min)(mip + 1, mip_levels - 1); + const float mip_gap = std::fabs(bilinear(s, next, p.u, p.v) - bilinear(s, mip, p.u, p.v)); + const float span = footprint_span(s, mip, p.u, p.v) + footprint_span(s, next, p.u, p.v); + return linear_tolerance + weight_step * (2.0f * span + mip_gap); +} + bool probes_differ(const SamplerCase& a, const SamplerCase& b) { for (const auto& p : point_probes) { @@ -329,7 +355,6 @@ bool check_startup_sampler_x(ID3D12Device* device, bool swapped) for (UINT table = 0; table < samplers.size(); ++table) { // In the swapped control, table 0 holds sampler 1 and table 1 holds sampler 0. const auto& bound = samplers[bound_case(table)]; - const float tolerance = is_linear(bound) ? linear_tolerance : 0.0f; UINT count = 0; const Probe* probes = table_probes(table, count); std::printf("startup_sampler_x swapped=%u table=%u values=", static_cast<unsigned>(swapped), table); @@ -337,7 +362,7 @@ bool check_startup_sampler_x(ID3D12Device* device, bool swapped) const float got = actual[word]; const float want = reference(bound, probes[p]); std::printf("%s%g", p ? "," : "", got); - if (std::fabs(got - want) <= tolerance) continue; + if (std::fabs(got - want) <= tolerance_for(bound, probes[p])) continue; if (!mismatches++) { std::fprintf(stderr, "First sampler mismatch: table %u probe %u (u=%g v=%g lod=%g) expected %g, got %g\n", table, p, probes[p].u, probes[p].v, probes[p].lod, want, got); diff --git a/tests/startup_scene_color_report_check.py b/tests/startup_scene_color_report_check.py new file mode 100644 index 0000000000..60671ae993 --- /dev/null +++ b/tests/startup_scene_color_report_check.py @@ -0,0 +1,273 @@ +"""Synthetic histories for tools/startup/scene_color_report.py. + +Refs #870. No dump, title file or GPU is used here. Each case writes the exact +``pixel_history.txt`` shape from ``src/startup_stubs/pixel_history.h`` in a +temporary directory and checks the bounded Markdown result. +""" + +from __future__ import annotations + +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "startup" / "scene_color_report.py" + + +def raw_rgba(red: int, green: int, blue: int, alpha: int, fmt: int = 28) -> int: + """Return the little-endian word pixel_history_decode() reads.""" + if fmt in (87, 91): + return blue | (green << 8) | (red << 16) | (alpha << 24) + return red | (green << 8) | (blue << 16) | (alpha << 24) + + +def sample(draw: int, *, frame: int = 1, x: int = 1, y: int = 1, + key: int = 1, count: int = 3, fmt: int = 28, + rgba: tuple[int, int, int, int] | None = None) -> str: + if rgba is None: + rgba = (0, 0, 0, 0) + raw = raw_rgba(*rgba, fmt=fmt) + line = (f"draw={draw} frame={frame} x={x} y={y} key={key:016x} " + f"count={count} format={fmt} raw={raw:08x}") + if fmt in (28, 29, 87, 91): + line += " rgba=%d,%d,%d,%d" % rgba + return line + + +def history(*lines: str) -> str: + return "x2w-pixel-history 1 samples=%d\n" % len(lines) + "".join(line + "\n" for line in lines) + + +def write_bmp(path: Path, width: int, height: int, + pixels: dict[tuple[int, int], tuple[int, int, int]]) -> None: + """Write the 32-bit bottom-up BI_RGB BMP shape draw_bmp.h produces.""" + body = bytearray() + for y in range(height - 1, -1, -1): + for x in range(width): + red, green, blue = pixels.get((x, y), (0, 0, 0)) + body += bytes((blue, green, red, 255)) + header = struct.pack("<2sIHHI", b"BM", 54 + len(body), 0, 0, 54) + info = struct.pack("<IiiHHIIiiII", 40, width, height, 1, 32, 0, len(body), 0, 0, 0, 0) + path.write_bytes(header + info + body) + + +class SceneColorReportCheck(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def dump_dir(self, name: str = "dump") -> Path: + folder = self.root / name + folder.mkdir() + return folder + + def write_history(self, folder: Path, text: str) -> None: + (folder / "pixel_history.txt").write_text(text, encoding="ascii") + + def run_report(self, folder: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), str(folder), *args], + capture_output=True, text=True, encoding="utf-8", timeout=30, + ) + + def test_first_change_is_not_the_last_writer(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0), key=0x1111111111111111), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(4, rgba=(0, 0, 255, 255), key=0x4444444444444444), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `target_write`", result.stdout) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("Last observed writer: `draw=4`", result.stdout) + self.assertIn("Frame: `1`", result.stdout) + self.assertIn("Pixel: `1,1`", result.stdout) + + def test_last_writer_can_be_the_first_change(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, rgba=(0, 255, 0, 255), key=0x2222222222222222), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("Last observed writer: `draw=2`", result.stdout) + self.assertIn("first change; last writer", result.stdout) + + def test_value_unchanged_after_a_restore(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, rgba=(0, 0, 0, 0), key=0x3333333333333333), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `value_unchanged`", result.stdout) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("Last observed writer: `draw=3`", result.stdout) + + def test_ui_only_when_no_sample_changes(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + sample(2, rgba=(0, 0, 0, 0)), + sample(3, rgba=(0, 0, 0, 0)), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `ui_only`", result.stdout) + self.assertIn("First observed change: _none among the retained samples", result.stdout) + self.assertIn("Last observed writer: _none_", result.stdout) + + def test_empty_history_is_no_draw(self) -> None: + folder = self.dump_dir() + self.write_history(folder, "x2w-pixel-history 1 samples=0\n") + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `no_draw`", result.stdout) + self.assertIn("Selected sample group: _none_", result.stdout) + self.assertIn("_No retained sample for the selected frame and pixel._", result.stdout) + + def test_malformed_line_is_ignored_without_echo(self) -> None: + folder = self.dump_dir("private-title-folder") + malformed = "draw=2 frame=1 x=1 y=1 key=2222222222222222 count=3 format=28 raw=00000000 " \ + "C:\\Users\\someone\\secret\\GameName.exe" + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + malformed, + sample(3, rgba=(0, 255, 0, 255), key=0x3333333333333333), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Malformed records ignored: `1`", result.stdout) + self.assertIn("First observed change: `draw=3`", result.stdout) + self.assertNotIn("GameName", result.stdout) + self.assertNotIn("secret", result.stdout) + self.assertNotIn("Users", result.stdout) + self.assertNotIn("private-title-folder", result.stdout) + self.assertNotIn(str(self.root), result.stdout) + + def test_non_rgba8_target_is_not_decoded(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + "draw=1 frame=1 x=1 y=1 key=1111111111111111 count=3 format=10 raw=00000000", + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `target_non_rgba8`", result.stdout) + self.assertIn("First observed change: _not evaluated", result.stdout) + self.assertIn("target is not RGBA8", result.stdout) + + def test_bgra_format_uses_the_documented_channel_order(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, fmt=87, rgba=(255, 0, 0, 255)), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("DXGI_FORMAT_B8G8R8A8_UNORM (`87`)", result.stdout) + self.assertIn("`255,0,0,255`", result.stdout) + + def test_history_cap_marks_truncated_and_bounds_rows(self) -> None: + folder = self.dump_dir() + lines = [sample(1, rgba=(0, 0, 0, 0), key=1)] + for draw in range(2, 49): + lines.append(sample(draw, rgba=(0, 255, 0, 255), key=0x2000000000000000 + draw)) + self.write_history(folder, history(*lines)) + result = self.run_report(folder, "--max-rows", "12") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `history_truncated`", result.stdout) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("History limit: the runtime cap", result.stdout) + timeline = result.stdout.split("## Retained timeline", 1)[1].split("## Input accounting", 1)[0] + rows = [line for line in timeline.splitlines() if line.startswith("| `")] + self.assertLessEqual(len(rows), 12, timeline) + self.assertIn("row(s) omitted", timeline) + + def test_frame_and_pixel_selection(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, frame=1, x=0, y=0, rgba=(0, 0, 0, 0)), + sample(2, frame=1, x=0, y=0, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, frame=2, x=1, y=1, rgba=(0, 0, 0, 0)), + sample(4, frame=2, x=1, y=1, rgba=(0, 0, 255, 255), key=0x4444444444444444), + sample(5, frame=2, x=1, y=1, rgba=(0, 0, 255, 255), key=0x4444444444444444), + )) + selected = self.run_report(folder, "--frame", "1", "--pixel", "0,0") + self.assertEqual(selected.returncode, 0, selected.stderr) + self.assertIn("Frame: `1`", selected.stdout) + self.assertIn("Pixel: `0,0`", selected.stdout) + self.assertIn("First observed change: `draw=2`", selected.stdout) + + default = self.run_report(folder) + self.assertEqual(default.returncode, 0, default.stderr) + self.assertIn("Frame: `2`", default.stdout) + self.assertIn("Pixel: `1,1`", default.stdout) + + def test_supplied_baseline_can_name_the_first_draw(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 255, 0, 255)), + )) + without = self.run_report(folder) + self.assertEqual(without.returncode, 0, without.stderr) + self.assertIn("Classification: `value_unchanged`", without.stdout) + with_baseline = self.run_report(folder, "--baseline-raw", "0x00000000") + self.assertEqual(with_baseline.returncode, 0, with_baseline.stderr) + self.assertIn("Classification: `target_write`", with_baseline.stdout) + self.assertIn("First observed change: `draw=1`", with_baseline.stdout) + + def test_bmp_cross_check_and_mismatch_control(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0), key=0x1111111111111111), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + )) + bmp = folder / "draw_02_2222222222222222_3.bmp" + write_bmp(bmp, 4, 4, {(1, 1): (0, 255, 0)}) + matched = self.run_report(folder) + self.assertEqual(matched.returncode, 0, matched.stderr) + self.assertIn("BMP files: `1` (valid `1`, invalid `0`)", matched.stdout) + self.assertIn("Target dimensions: `4x4`", matched.stdout) + self.assertIn("Matching selected samples: `1` matched", matched.stdout) + + write_bmp(bmp, 4, 4, {(1, 1): (0, 0, 255)}) + mismatched = self.run_report(folder) + self.assertEqual(mismatched.returncode, 0, mismatched.stderr) + self.assertIn("Matching selected samples: `0` matched, `1` mismatched", mismatched.stdout) + self.assertIn("BMP mismatch at `draw=2`", mismatched.stdout) + + def test_header_mismatch_is_bounded(self) -> None: + folder = self.dump_dir() + text = "x2w-pixel-history 1 samples=5\n" + sample(1, rgba=(0, 0, 0, 0)) + "\n" + self.write_history(folder, text) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `history_truncated`", result.stdout) + self.assertIn("Header count and physical record count differ", result.stdout) + + def test_missing_history_is_a_controlled_error(self) -> None: + folder = self.dump_dir() + result = self.run_report(folder) + self.assertEqual(result.returncode, 2) + self.assertIn("pixel_history.txt not found", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(result.stdout, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index 7a7d7218a4..134cfccf96 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): def main(): # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. - # Revision x2w-startup-shader-17 excludes NUL. Stored order is a, b, root, then optional input layout. + # Revision x2w-startup-shader-29 excludes NUL. Stored order is a, b, root, then optional input layout. vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") - assert gfx2hlsl.pipeline_key(*vector) == 0xd9521cd3fde79d61 - assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xbaa2837ef61006ad + assert gfx2hlsl.pipeline_key(*vector) == 0xa837b162afd547ce + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0x6d5c0b7786182e0e blobs = (VERTEX, PIXEL, ROOT) canonical = gfx2hlsl.pipeline_key(*blobs) check_request(blobs, canonical) diff --git a/tests/startup_shader_cache_rekey_check.py b/tests/startup_shader_cache_rekey_check.py index fc9a5ffa1a..978639b909 100644 --- a/tests/startup_shader_cache_rekey_check.py +++ b/tests/startup_shader_cache_rekey_check.py @@ -6,11 +6,11 @@ - An old cache holds requests of the older revision (two graphics requests, one with an input layout, one compute request, an RTV variant of the first graphics request), one current-revision graphics request, the same - pipeline as the first at the current revision, a mesh request, a result and a .fail. Their old names differ - from pipeline_key / compute_key of the current revision. + pipeline as the first at the current revision, an old and a current slot 57 mesh request, a slot 86 marker, + a result and a .fail. Old request names differ from the current pipeline_key, compute_key or mesh57_key. - The tool, run as a script with two hashing processes, writes exactly the current names with the same bytes (the RTV variant re-keyed to its new base), no results or .fail, and gfx2hlsl.pending_keys lists them. -- With the newer revision the same requests get other names again. +- With the newer graphics and compute revision those requests and the RTV variant get other names again. - A second run writes nothing; re-keying a current cache keeps every name. - A missing request part, a truncated RTV variant or an RTV variant whose base request is missing exits with 1 and creates nothing. @@ -75,12 +75,19 @@ def gkey(module, parts): COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} +MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'} +MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root', + '.m57': b'another synthetic mesh'} def ckey(module, parts): return module.compute_key(parts['.c67'], parts['.data'], parts['.root'], parts['.desc'], parts['.sa'], parts['.sb']) +def mkey(module, parts): + return module.mesh57_key(parts['.m57'], parts['.ps57'], parts['.root']) + + def rtv_text(base): return 'rtv1 %d 28 87' % base @@ -108,7 +115,7 @@ def run(src, dst, jobs='2'): env=env, timeout=120) -def expected_files(module, requests, computes, rtv_bases): +def expected_files(module, requests, computes, rtv_bases, meshes): """{name: bytes} of the requests named under module's revision.""" files = {} for parts in requests: @@ -120,6 +127,9 @@ def expected_files(module, requests, computes, rtv_bases): for parts in rtv_bases: text = rtv_text(gkey(module, parts)).encode('ascii') files['req_%016x.rtv' % G.fnv(text)] = text + for parts in meshes: + for ext, data in parts.items(): + files['req_%016x%s' % (mkey(module, parts), ext)] = data return files @@ -143,7 +153,12 @@ def main(): old_rtv = write_rtv(src, gkey(older, g1)) write_request(src, gkey(G, g1), g1) # the same pipeline at the current revision write_request(src, gkey(G, g3), g3) # current only - write_request(src, 0x123456789abcdef0, {'.ps57': b'', '.root': b'RTS0 mesh', '.m57': b'\x01' * 8}) + meshes = (MESH_OLD, MESH_CURRENT) + old_mesh = mkey(G, MESH_OLD) ^ 1 + mesh_keys = {mkey(G, parts) for parts in meshes} + write_request(src, old_mesh, MESH_OLD) + write_request(src, mkey(G, MESH_CURRENT), MESH_CURRENT) + write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86 marker'}) (src / ('%016x.txt' % gkey(older, g1))).write_text('synthetic result\n') (src / ('%016x.fail' % gkey(older, g2))).write_text('synthetic refusal\n') before = snapshot(src) @@ -152,22 +167,26 @@ def main(): current_names = {gkey(G, g1), gkey(G, g2), ckey(G, COMPUTE)} check('older-revision names differ from the current keys', not old_names & current_names) - # (a) re-keyed names are pipeline_key / compute_key of the current revision, with the same bytes. + # (a) re-keyed names use the current key functions, with the same bytes. dst = tmp / 'rekeyed' first = run(src, dst) check('re-key exits 0', first.returncode == 0, first.stderr.strip()) - want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,)) + want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,), meshes) got = contents(dst) if dst.is_dir() else {} check('re-keyed files are exactly the current requests', got == want, 'extra %s missing %s' % (sorted(set(got) - set(want)), sorted(set(want) - set(got)))) check('no results or .fail written', all(name.startswith('req_') for name in got)) check('graphics summary counts the duplicate and the current request', 'graphics: 4 requests, 2 already current -> 3 keys' in first.stdout, first.stdout) - check('mesh request counted, not re-keyed', 'm57 1, m86 0' in first.stdout, first.stdout) + check('mesh summary counts the old and current slot 57 requests', + 'm57: 2 requests, 1 already current -> 2 keys' in first.stdout, first.stdout) + check('slot 86 marker is only counted', 'not re-keyed (own key strings): m86 1' in first.stdout, + first.stdout) pending = G.pending_keys(str(dst), False) rtv_new = G.fnv(rtv_text(gkey(G, g1)).encode('ascii')) check('gfx2hlsl.pending_keys lists the re-keyed requests', - pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new}), pending) + pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new} | mesh_keys), + pending) # (e) the RTV variant names the new base and is named by the hash of its new text. rtv_file = dst / ('req_%016x.rtv' % rtv_new) @@ -186,7 +205,8 @@ def main(): third = run(dst, again, jobs='1') check('current requests keep their names', third.returncode == 0 and contents(again) == want and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout - and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout, third.stdout + third.stderr) + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout + and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, third.stdout + third.stderr) # (b) under a newer revision the same requests get other names (in process: one job keeps the patch). R.g, saved = newer, R.g @@ -198,18 +218,23 @@ def main(): R.g = saved got_newer = contents(newest) if newest.is_dir() else {} check('newer revision re-keys to its own names', code == 0 - and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,))) - check('newer names differ from the current names', not set(got_newer) & set(want)) + and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,), meshes)) + check('only mesh names are shared between the graphics and compute revisions', + set(got_newer) & set(want) == set(expected_files(G, (), (), (), meshes))) # (f) negative controls: an incomplete request, a truncated RTV variant or an RTV variant without its base - # request writes nothing. Without the base's ready marker (.a) there is one graphics request less: 5, not 6. + # request writes nothing. Without the base's ready marker (.a), the request count drops from 8 to 7. for label, total, reason, damage in ( - ('missing .root', 6, 'unreadable req_%016x.root' % gkey(older, g2), + ('missing .root', 8, 'unreadable req_%016x.root' % gkey(older, g2), lambda d: (d / ('req_%016x.root' % gkey(older, g2))).unlink()), - ('truncated RTV variant', 6, '.rtv text does not hash to its name', + ('missing slot 57 .root', 8, 'unreadable req_%016x.root' % old_mesh, + lambda d: (d / ('req_%016x.root' % old_mesh)).unlink()), + ('missing slot 57 .ps57', 8, 'unreadable req_%016x.ps57' % old_mesh, + lambda d: (d / ('req_%016x.ps57' % old_mesh)).unlink()), + ('truncated RTV variant', 8, '.rtv text does not hash to its name', lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes( rtv_text(gkey(older, g1)).encode('ascii')[:-3])), - ('missing RTV base', 5, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), + ('missing RTV base', 7, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), lambda d: (d / ('req_%016x.a' % gkey(older, g1))).unlink())): bad = tmp / ('bad_' + label.replace(' ', '_')) shutil.copytree(src, bad) diff --git a/tests/startup_shader_cache_rekey_cli_check.py b/tests/startup_shader_cache_rekey_cli_check.py index c8bee38ebc..39a3f850a3 100644 --- a/tests/startup_shader_cache_rekey_cli_check.py +++ b/tests/startup_shader_cache_rekey_cli_check.py @@ -80,7 +80,7 @@ def test_positive_main_argv_none_and_subprocess(self): rc, stdout, stderr = _run_main([str(src), str(dst_argv)]) self.assertEqual(rc, 0, stderr) self.assertEqual(stderr, "") - self.assertIn("m57 0, m86 1", stdout) + self.assertIn("not re-keyed (own key strings): m86 1", stdout) expected_names = sorted([ f"req_{keys['g']:016x}.a", f"req_{keys['g']:016x}.b", @@ -116,7 +116,7 @@ def test_positive_main_argv_none_and_subprocess(self): ) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(proc.stderr, "") - self.assertIn("m57 0, m86 1", proc.stdout) + self.assertIn("not re-keyed (own key strings): m86 1", proc.stdout) self.assertEqual(sorted(p.name for p in dst_sub.iterdir()), expected_names) def test_usage_and_path_guards(self): diff --git a/tests/startup_shader_cache_revision_check.py b/tests/startup_shader_cache_revision_check.py new file mode 100644 index 0000000000..0f29451662 --- /dev/null +++ b/tests/startup_shader_cache_revision_check.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Check tools/startup/shader_cache_revision.py, the launchers' shader cache revision warning (#2815). + +The command line runs on synthetic cache folders and a synthetic translator file: +- same revisions in revision.txt: no output, exit 0; +- a different revision: one line naming both revisions and the fixes, exit 1; +- requests (req_*) but no revision.txt: the same kind of line, exit 1; no requests: silent; +- --fresh moves a cache that is not empty aside and leaves an empty or missing one alone. +The real gfx2hlsl.py must yield all three revisions, or the launchers could not compare anything. +""" +from pathlib import Path +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +TOOL = HERE.parent / 'tools' / 'startup' / 'shader_cache_revision.py' +sys.path.insert(0, str(TOOL.parent)) +import shader_cache_revision as R # noqa: E402 + +# Synthetic translator source: the three literals as gfx2hlsl.py spells them. +TRANSLATOR = (b"def pipeline_key():\n return fnv(b'x2w-startup-shader-90')\n" + b"def compute_key():\n return fnv(b'x2w-startup-shader-90cs')\n" + b"def mesh57_key():\n return fnv(b'x2w-startup-mesh-57-9')\n") +SAME = 'graphics x2w-startup-shader-90\ncompute x2w-startup-shader-90cs\nmesh57 x2w-startup-mesh-57-9\n' +OLDER = 'graphics x2w-startup-shader-89\ncompute x2w-startup-shader-89cs\nmesh57 x2w-startup-mesh-57-9\n' +failures = [] + + +def check(name, ok, detail=''): + print('%s: %s' % (name, 'ok' if ok else 'FAIL %s' % detail)) + if not ok: + failures.append(name) + + +def run(*args): + result = subprocess.run([sys.executable, '-B', str(TOOL), *map(str, args)], capture_output=True, text=True) + return result.returncode, result.stdout, result.stderr + + +def cache_with(root, name, revision=None, request=True): + cache = root / name + cache.mkdir() + if revision is not None: + (cache / 'revision.txt').write_text(revision, encoding='ascii') + if request: + (cache / 'req_0123456789abcdef.a').write_bytes(b'\0' * 8) + return cache + + +def main(): + real = R.translator_revisions(TOOL.parent / 'gfx2hlsl.py') + check('the real gfx2hlsl.py yields graphics, compute and mesh57 revisions', sorted(real) == sorted(R.KINDS), real) + check('the compute revision is the graphics one with cs', + real.get('compute') == real.get('graphics', '') + 'cs', real) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + translator = root / 'gfx2hlsl.py' + translator.write_bytes(TRANSLATOR) + + code, out, err = run(cache_with(root, 'same', SAME), '--translator', translator) + check('same revisions: silent', (code, out, err) == (0, '', ''), (code, out, err)) + + stale = cache_with(root, 'older', OLDER) + code, out, err = run(stale, '--translator', translator) + lines = out.splitlines() + check('different revision: exit 1, one line', code == 1 and len(lines) == 1 and not err, (code, out, err)) + check('different revision: both revisions named', + 'x2w-startup-shader-89' in out and 'x2w-startup-shader-90' in out and str(stale) in out, out) + check('different revision: both fixes named', 'rebuild the stand-ins' in out and 'empty shader cache' in out, out) + + code, out, err = run(cache_with(root, 'compute-only', 'compute x2w-startup-shader-89cs\n'), + '--translator', translator) + check('one differing kind is enough', code == 1 and 'x2w-startup-shader-89cs' in out, (code, out)) + + code, out, err = run(cache_with(root, 'garbled', 'not a revision\n'), '--translator', translator) + check('a revision.txt with no known line warns', code == 1 and 'none readable' in out, (code, out)) + + legacy = cache_with(root, 'legacy') + code, out, err = run(legacy, '--translator', translator) + check('requests without revision.txt warn', + code == 1 and 'revision.txt' in out and 'x2w-startup-shader-90' in out and 'rebuild' in out, (code, out)) + + code, out, err = run(cache_with(root, 'fresh', request=False), '--translator', translator) + check('no requests, no revision.txt: silent', (code, out) == (0, ''), (code, out)) + code, out, err = run(root / 'missing', '--translator', translator) + check('missing cache folder: silent', (code, out) == (0, ''), (code, out)) + + code, out, err = run(legacy, '--fresh') + moved = [p for p in root.iterdir() if p.name.startswith('legacy.old-')] + check('--fresh moves a cache with files aside', + code == 0 and not legacy.exists() and len(moved) == 1 and (moved[0] / 'req_0123456789abcdef.a').exists() + and str(moved[0]) in out, (code, out, moved)) + empty = root / 'empty' + empty.mkdir() + code, out, err = run(empty, '--fresh') + check('--fresh leaves an empty cache in place', (code, out) == (0, '') and empty.is_dir(), (code, out)) + code, out, err = run(root / 'missing', '--fresh') + check('--fresh with no cache folder does nothing', (code, out) == (0, ''), (code, out)) + + code, out, err = run() + check('no cache argument: usage, exit 2', code == 2 and 'usage' in out, (code, out)) + code, out, err = run(stale, '--fresh', '--translator', translator) + check('--fresh with --translator: usage, exit 2', code == 2, (code, out)) + print('FAIL: %s' % ', '.join(failures) if failures else 'PASS') + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_slot133_heap_cap_check.cpp b/tests/startup_slot133_heap_cap_check.cpp new file mode 100644 index 0000000000..a45f05e871 --- /dev/null +++ b/tests/startup_slot133_heap_cap_check.cpp @@ -0,0 +1,821 @@ +// Slot 133 existing-heap cap (opt-in X2W_D3D12_CAP_EXISTING_HEAP=1, <= 256 MiB), deferred +// commit_lazy_block, and incremental reserve_upload_ring growth (Refs #1199, Fixes #2765). +// +// startup_slot133_heap_cap_check <warp|hardware> [cap] +// +// 1. With X2W_XMEM_LAZY_COMMIT=1 and X2W_XMEM_LAZY_STARTUP=1: +// - Allocate a 260 MiB (> 256 MiB) MEM_PRIVATE lazy startup block via XMemVirtualAlloc. +// - Default (no `cap`): the aligned 64 KiB placement at +0 opens the 260 MiB existing heap +// (aliased, ALLOW_CROSS_ADAPTER) and commits the block. A guest CopyBufferRegion (list slot 15) +// recorded from it into a readback buffer must observe a late CPU write made after recording +// and before submit (fenced readback, every byte 0x59): a capped copied placement would be +// refused as title_backed_source and lose that write, so the cap stays opt-in. +// - With `cap` (X2W_D3D12_CAP_EXISTING_HEAP=1): place a 64 KiB aligned buffer at +0 and a +// 64 KiB unaligned buffer at +2 MiB + 16 via slot 133: neither opens an existing_heap +// (x2w-budget heap stays 0/0, desktop resources lack ALLOW_CROSS_ADAPTER) and untouched +// pages of the 260 MiB block remain MEM_RESERVE. +// - Meanwhile, <= 256 MiB blocks (4 MiB VirtualAlloc and 64 MiB XMemVirtualAlloc lazy block at +// +2 MiB with an untouched [0, 2 MiB) MEM_RESERVE prefix) open existing_heap (aliased) cleanly, +// verified with a late A-to-B CPU write and GPU readback; unaligned and out-of-bounds nonzero +// offsets in a 64 MiB lazy block leave untouched pages MEM_RESERVE. +// 2. reserve_upload_ring incremental growth (cap variant): +// - First upload (64x64 RGBA8 CopyResource) commits 16 MiB (not 256 MiB) in x2w-budget upload. +// - A second small upload (32x32 RGBA8) reuses the same 16 MiB chunk. +// - Uploading a 2048x2048 RGBA8 (16 MiB) texture exceeds chunk 0 and appends a 32 MiB chunk +// (48 MiB / 2 objects), and another small upload lands in chunk 1; GPU readbacks verify the +// uploaded texels from both chunks with zero debug-layer errors. +#include "startup_stubs/resource_budget.h" + +#include <d3d12sdklayers.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <cwchar> +#include <string> +#include <vector> + +using Microsoft::WRL::ComPtr; + +namespace { +using namespace x2w_budget; + +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using CreateXboxDeviceFn = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); +using BudgetSnapshotFn = BOOL (*)(Snapshot*, SIZE_T); + +XMemVirtualAllocFn g_xmem_virtual_alloc = nullptr; +CreateXboxDeviceFn g_create_xbox_device = nullptr; +BudgetSnapshotFn g_budget_snapshot = nullptr; + +constexpr UINT64 page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; +constexpr UINT64 mib = UINT64{1} << 20; +constexpr DWORD wait_ms = 10000; + +template<class Result = HRESULT, class... Args> +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +template<class T> +ComPtr<T> desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr<T> output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr<IUnknown> reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast<IUnknown*>(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast<unsigned long>(hr)); + return SUCCEEDED(hr); +} + +bool check(bool ok, const char* what) +{ + if (!ok) std::printf("FAIL: %s\n", what); + return ok; +} + +bool snap(Snapshot& counts) +{ + if (g_budget_snapshot && g_budget_snapshot(&counts, sizeof(counts))) return true; + std::puts("FAIL: budget snapshot unavailable"); + return false; +} + +DWORD mem_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) +{ + return {D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; +} + +D3D12_RESOURCE_DESC tex2d_desc(UINT width, UINT height) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; +} + +std::uint8_t pattern_byte(int seed, UINT64 index) +{ + return static_cast<std::uint8_t>((index * 131 + seed * 37 + 19) & 0xff); +} + +ComPtr<IDXGIAdapter1> pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +bool load_shims(bool cap) +{ + SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); + SetEnvironmentVariableA("X2W_XMEM_LAZY_STARTUP", "1"); + SetEnvironmentVariableA("X2W_D3D12_BUDGET", "1"); + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + SetEnvironmentVariableA("X2W_D3D12_CAP_EXISTING_HEAP", cap ? "1" : nullptr); + + wchar_t exe_dir[MAX_PATH]{}; + const DWORD n = GetModuleFileNameW(nullptr, exe_dir, MAX_PATH); + if (!n || n >= MAX_PATH) return false; + std::wstring dir(exe_dir, n); + const std::size_t slash = dir.find_last_of(L"\\/"); + dir.resize(slash == std::wstring::npos ? 0 : slash + 1); + + const HMODULE xmem = LoadLibraryW((dir + L"xmem.dll").c_str()); + const HMODULE d3d = LoadLibraryW((dir + L"d3d12_xs.dll").c_str()); + if (!xmem || !d3d) { + std::printf("FAIL: could not load xmem.dll (%p) or d3d12_xs.dll (%p), err=%lu\n", + static_cast<void*>(xmem), static_cast<void*>(d3d), GetLastError()); + return false; + } + g_xmem_virtual_alloc = reinterpret_cast<XMemVirtualAllocFn>(GetProcAddress(xmem, "XMemVirtualAlloc")); + g_create_xbox_device = reinterpret_cast<CreateXboxDeviceFn>(GetProcAddress(d3d, "D3D12XboxCreateDevice")); + g_budget_snapshot = reinterpret_cast<BudgetSnapshotFn>(GetProcAddress(d3d, "x2w_d3d12_budget_snapshot")); + return g_xmem_virtual_alloc && g_create_xbox_device && g_budget_snapshot; +} + +bool verify_texture_box(ID3D12Device* device, ID3D12CommandQueue* own_queue, ID3D12CommandAllocator* own_alloc, + ID3D12GraphicsCommandList* own_list, ID3D12Fence* own_fence, UINT64& own_val, + ID3D12Resource* real_tex, UINT box_x, UINT box_y, UINT box_w, UINT box_h, + UINT full_w, int seed, const char* label) +{ + const UINT pitch = (box_w * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1); + const UINT64 rb_bytes = UINT64{pitch} * box_h; + const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; + const auto rb_desc = buffer_desc(rb_bytes); + ComPtr<ID3D12Resource> rb; + if (!require(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&rb)), + "readback buffer")) + return false; + + if (!require(own_alloc->Reset(), "own alloc reset") || !require(own_list->Reset(own_alloc, nullptr), "own list reset")) + return false; + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {real_tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + + D3D12_TEXTURE_COPY_LOCATION dst{rb.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, box_w, box_h, 1, pitch}; + D3D12_TEXTURE_COPY_LOCATION src{real_tex, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + D3D12_BOX box{box_x, box_y, 0, box_x + box_w, box_y + box_h, 1}; + own_list->CopyTextureRegion(&dst, 0, 0, 0, &src, &box); + + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + own_list->ResourceBarrier(1, &b); + if (!require(own_list->Close(), "own list close")) return false; + ID3D12CommandList* lists[] = {own_list}; + own_queue->ExecuteCommandLists(1, lists); + if (!require(own_queue->Signal(own_fence, ++own_val), "own signal")) return false; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return false; + const bool waited = SUCCEEDED(own_fence->SetEventOnCompletion(own_val, ev)) && + WaitForSingleObject(ev, wait_ms) == WAIT_OBJECT_0; + CloseHandle(ev); + if (!check(waited, "own fence wait")) return false; + + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast<SIZE_T>(rb_bytes)}; + if (!require(rb->Map(0, &range, &mapped), "readback map")) return false; + const auto* got = static_cast<const std::uint8_t*>(mapped); + UINT mismatches = 0; + for (UINT y = 0; y < box_h; ++y) { + for (UINT x = 0; x < box_w * 4; ++x) { + const UINT64 src_idx = (UINT64{box_y + y} * full_w * 4) + (UINT64{box_x} * 4) + x; + const std::uint8_t expected = pattern_byte(seed, src_idx); + if (got[UINT64{y} * pitch + x] != expected) ++mismatches; + } + } + rb->Unmap(0, nullptr); + if (mismatches) { + std::printf("FAIL: %s readback mismatches=%u\n", label, mismatches); + return false; + } + return true; +} + +bool verify_buffer_pattern(ID3D12Device* device, ID3D12CommandQueue* own_queue, ID3D12CommandAllocator* own_alloc, + ID3D12GraphicsCommandList* own_list, ID3D12Fence* own_fence, UINT64& own_val, + ID3D12Resource* real_buf, UINT64 bytes, int seed, const char* label) +{ + const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; + const auto rb_desc = buffer_desc(bytes); + ComPtr<ID3D12Resource> rb; + if (!require(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&rb)), + "buffer readback")) + return false; + + if (!require(own_alloc->Reset(), "own alloc reset") || !require(own_list->Reset(own_alloc, nullptr), "own list reset")) + return false; + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {real_buf, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyBufferRegion(rb.Get(), 0, real_buf, 0, bytes); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + own_list->ResourceBarrier(1, &b); + if (!require(own_list->Close(), "own list close")) return false; + ID3D12CommandList* lists[] = {own_list}; + own_queue->ExecuteCommandLists(1, lists); + if (!require(own_queue->Signal(own_fence, ++own_val), "own signal")) return false; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return false; + const bool waited = SUCCEEDED(own_fence->SetEventOnCompletion(own_val, ev)) && + WaitForSingleObject(ev, wait_ms) == WAIT_OBJECT_0; + CloseHandle(ev); + if (!check(waited, "own fence wait")) return false; + + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast<SIZE_T>(bytes)}; + if (!require(rb->Map(0, &range, &mapped), "buffer readback map")) return false; + const auto* got = static_cast<const std::uint8_t*>(mapped); + UINT mismatches = 0; + for (UINT64 i = 0; i < bytes; ++i) { + if (got[i] != pattern_byte(seed, i)) ++mismatches; + } + rb->Unmap(0, nullptr); + if (mismatches) { + std::printf("FAIL: %s readback mismatches=%u\n", label, mismatches); + return false; + } + return true; +} + +int run_check(IUnknown* guest, ID3D12Device* device, ID3D12InfoQueue* debug, bool cap) +{ + const GUID& resource_iid = __uuidof(ID3D12Resource); + D3D12_FEATURE_DATA_EXISTING_HEAPS existing{}; + const bool existing_supported = + SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &existing, sizeof(existing))) && + existing.Supported; + + Snapshot base_snap{}; + if (!snap(base_snap)) return 4; + if (!check(base_snap.live[heap].objects == 0 && base_snap.retained[heap].objects == 0, + "baseline heap budget starts at 0/0")) + return 5; + if (!check(base_snap.live[upload].objects == 0 && base_snap.retained[upload].objects == 0, + "baseline upload budget starts at 0/0")) + return 5; + + // ------------------------------------------------------------------------- + // Part 1: slot 133 multi-GiB / >256 MiB existing-heap cap & lazy block commit + // ------------------------------------------------------------------------- + constexpr SIZE_T large_bytes = 260 * mib; + auto* const large_block = static_cast<char*>( + g_xmem_virtual_alloc(nullptr, large_bytes, 0x20403000, 0x181, PAGE_READWRITE)); + if (!check(large_block != nullptr, "XMemVirtualAlloc 260 MiB block")) return 4; + if (!check(mem_state(large_block) == MEM_RESERVE && + mem_state(large_block + 1 * mib) == MEM_RESERVE && + mem_state(large_block + 128 * mib) == MEM_RESERVE && + mem_state(large_block + 259 * mib) == MEM_RESERVE, + "260 MiB startup block starts MEM_RESERVE under X2W_XMEM_LAZY_STARTUP")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 4; + } + + const auto buf_64k = buffer_desc(page); + ComPtr<IUnknown> large_aligned; + if (!require(invoke(guest, 133, large_block, &buf_64k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, large_aligned.GetAddressOf()), + "slot 133 aligned buffer in 260 MiB block")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 4; + } + const auto large_aligned_real = desktop_object<ID3D12Resource>(guest, device, large_aligned.Get()); + if (!check(large_aligned_real != nullptr, "desktop resource for aligned 260 MiB buffer")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 4; + } + + if (!cap) { + if (!existing_supported) { + std::puts("skipping default aliased existing-heap check: D3D12_FEATURE_EXISTING_HEAPS=0"); + large_aligned.Reset(); + VirtualFree(large_block, 0, MEM_RELEASE); + return 77; + } + Snapshot s{}; + if (!snap(s)) return 4; + // A failed placement check does not stop the late-write case below: with the cap forced on, + // the copied fallback is refused by slot 15 and the readback sentinel survives, which is the + // loss this fixture exists to catch. Any failure still fails the run. + bool aliased_ok = check((large_aligned_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) != 0, + "default keeps aliased placement on 260 MiB block"); + aliased_ok &= check(s.live[heap].bytes == large_bytes && s.live[heap].objects == 1, + "default accounts 260 MiB heap"); + aliased_ok &= check(s.live[placed].objects == 1, "default accounts placed buffer"); + aliased_ok &= check(mem_state(large_block + 128 * mib) == MEM_COMMIT, + "default commits lazy block right before OpenExistingHeapFromAddress"); + + // R0Y00's late-write case: record a guest CopyBufferRegion (list slot 15) from the aliased + // buffer into a readback buffer, change the title memory after recording and before submit, + // and require the fenced readback to hold the late bytes. The default alias keeps the + // contents authoritative; a capped copied placement is refused as title_backed_source + // (list_copy.inl sync_title_source) and the readback keeps its 0x6d sentinel. + std::memset(large_block, 0x2a, static_cast<std::size_t>(page)); + const D3D12_COMMAND_QUEUE_DESC late_qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + const unsigned late_list_desc[] = {static_cast<unsigned>(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + ComPtr<IUnknown> late_queue, late_alloc, late_list, late_fence; + if (!require(invoke(guest, 8, &late_qd, &__uuidof(ID3D12CommandQueue), late_queue.GetAddressOf()), + "late-write guest queue") || + !require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + late_alloc.GetAddressOf()), + "late-write guest allocator") || + !require(invoke(guest, 73, late_list_desc, late_alloc.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), + late_list.GetAddressOf()), + "late-write guest list") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), + late_fence.GetAddressOf()), + "late-write guest fence") || + !require(invoke(late_list.Get(), 139, late_alloc.Get(), nullptr), "late-write guest list reset")) + return 4; + const auto late_real_fence = desktop_object<ID3D12Fence>(guest, device, late_fence.Get()); + if (!late_real_fence) return 4; + + const D3D12_HEAP_PROPERTIES late_rb_heap{D3D12_HEAP_TYPE_READBACK}; + const auto late_rb_desc = buffer_desc(page); + ComPtr<ID3D12Resource> late_readback; + if (!require(device->CreateCommittedResource(&late_rb_heap, D3D12_HEAP_FLAG_NONE, &late_rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&late_readback)), + "late-write readback buffer")) + return 4; + void* primed = nullptr; + const D3D12_RANGE prime_range{0, static_cast<SIZE_T>(page)}; + if (!require(late_readback->Map(0, &prime_range, &primed), "late-write readback prime map")) return 4; + std::memset(primed, 0x6d, static_cast<std::size_t>(page)); + late_readback->Unmap(0, nullptr); + + // Slot 15 takes the raw desktop readback pointer as its destination (copy_endpoint). + invoke<void>(late_list.Get(), 15, reinterpret_cast<UINT64>(late_readback.Get()), UINT64{0}, + reinterpret_cast<UINT64>(large_aligned.Get()), UINT64{0}, UINT64{page}); + if (!require(invoke(late_list.Get(), 9), "late-write list close")) return 4; + + // The late guest write: after recording, before submit. + std::memset(large_block, 0x59, static_cast<std::size_t>(page)); + + IUnknown* late_lists[] = {late_list.Get()}; + invoke<void>(late_queue.Get(), 10, 1u, late_lists); + UINT64 late_val = 1; + if (!require(invoke(late_queue.Get(), 14, late_fence.Get(), late_val), "late-write queue signal")) return 4; + HANDLE late_ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!late_ev) return 4; + const bool late_waited = SUCCEEDED(late_real_fence->SetEventOnCompletion(late_val, late_ev)) && + WaitForSingleObject(late_ev, wait_ms) == WAIT_OBJECT_0; + CloseHandle(late_ev); + if (!check(late_waited, "late-write fence wait")) return 4; + + void* late_mapped = nullptr; + const D3D12_RANGE late_read_range{0, static_cast<SIZE_T>(page)}; + if (!require(late_readback->Map(0, &late_read_range, &late_mapped), "late-write readback map")) return 4; + const auto* late_got = static_cast<const std::uint8_t*>(late_mapped); + UINT64 late_stale = 0, late_first = 0; + std::uint8_t late_first_byte = 0; + for (UINT64 i = 0; i < page; ++i) { + if (late_got[i] != 0x59) { + if (!late_stale) { late_first = i; late_first_byte = late_got[i]; } + ++late_stale; + } + } + late_readback->Unmap(0, nullptr); + if (late_stale) { + std::printf("FAIL: late write lost on 260 MiB buffer: %llu of %llu readback bytes are not 0x59 " + "(first at offset %llu = 0x%02x; 0x6d is the readback sentinel, 0x2a the pre-record " + "contents; a capped copied placement is refused as title_backed_source)\n", + static_cast<unsigned long long>(late_stale), static_cast<unsigned long long>(page), + static_cast<unsigned long long>(late_first), late_first_byte); + return 5; + } + if (!aliased_ok) return 5; + large_aligned.Reset(); + std::puts("PASS (default aliased + late write)"); + return 0; + } + + // Cap mode (X2W_D3D12_CAP_EXISTING_HEAP=1): > 256 MiB block must NOT open an existing_heap and + // untouched pages remain MEM_RESERVE. + if (!check((large_aligned_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) == 0, + "260 MiB aligned buffer must fall back (not aliased)")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 5; + } + Snapshot after_large_aligned{}; + if (!snap(after_large_aligned)) return 4; + if (!check(after_large_aligned.live[heap].bytes == 0 && after_large_aligned.live[heap].objects == 0 && + after_large_aligned.retained[heap].bytes == 0 && after_large_aligned.retained[heap].objects == 0, + "260 MiB aligned buffer keeps x2w-budget heap at 0/0") || + !check(after_large_aligned.live[buffer].objects == 1, + "260 MiB aligned buffer uses committed buffer fallback") || + !check(mem_state(large_block + 1 * mib) == MEM_RESERVE && + mem_state(large_block + 128 * mib) == MEM_RESERVE && + mem_state(large_block + 259 * mib) == MEM_RESERVE, + "untouched pages of 260 MiB block stay MEM_RESERVE after aligned slot 133")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 5; + } + + // Unaligned 64 KiB buffer inside the 260 MiB lazy startup block must also leave untouched pages MEM_RESERVE. + ComPtr<IUnknown> large_unaligned; + if (!require(invoke(guest, 133, large_block + 2 * mib + 16, &buf_64k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, large_unaligned.GetAddressOf()), + "slot 133 unaligned buffer in 260 MiB block")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 4; + } + const auto large_unaligned_real = desktop_object<ID3D12Resource>(guest, device, large_unaligned.Get()); + Snapshot after_large_unaligned{}; + if (!snap(after_large_unaligned)) return 4; + if (!check(large_unaligned_real && + (large_unaligned_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) == 0, + "260 MiB unaligned buffer is not aliased") || + !check(after_large_unaligned.live[heap].bytes == 0 && after_large_unaligned.live[heap].objects == 0 && + after_large_unaligned.retained[heap].bytes == 0 && after_large_unaligned.retained[heap].objects == 0, + "260 MiB unaligned buffer keeps x2w-budget heap at 0/0") || + !check(after_large_unaligned.live[buffer].objects == 2, + "260 MiB unaligned buffer uses committed buffer fallback") || + !check(mem_state(large_block + 1 * mib) == MEM_RESERVE && + mem_state(large_block + 128 * mib) == MEM_RESERVE && + mem_state(large_block + 259 * mib) == MEM_RESERVE, + "untouched pages of 260 MiB block stay MEM_RESERVE after unaligned slot 133")) { + VirtualFree(large_block, 0, MEM_RELEASE); + return 5; + } + large_aligned.Reset(); + large_unaligned.Reset(); + if (!check(VirtualFree(large_block, 0, MEM_RELEASE) != 0, "release 260 MiB lazy block")) return 4; + + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + ComPtr<ID3D12CommandQueue> own_queue; + ComPtr<ID3D12CommandAllocator> own_alloc; + ComPtr<ID3D12GraphicsCommandList> own_list; + ComPtr<ID3D12Fence> own_fence; + if (!require(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&own_queue)), "own queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&own_alloc)), "own alloc") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, own_alloc.Get(), nullptr, + IID_PPV_ARGS(&own_list)), + "own list") || + !require(own_list->Close(), "own list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&own_fence)), "own fence")) + return 4; + UINT64 own_val = 0, guest_val = 0; + + if (existing_supported) { + // <= 256 MiB (4 MiB VirtualAlloc) MUST open an existing_heap (aliased) and reuse it. + constexpr SIZE_T small_block_bytes = 4 * mib; + auto* const small_block = static_cast<char*>( + VirtualAlloc(nullptr, small_block_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!check(small_block != nullptr, "VirtualAlloc 4 MiB block")) return 4; + ComPtr<IUnknown> small_a, small_b; + if (!require(invoke(guest, 133, small_block + page, &buf_64k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, small_a.GetAddressOf()), + "slot 133 aligned buffer in 4 MiB block") || + !require(invoke(guest, 133, small_block + 2 * page, &buf_64k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, small_b.GetAddressOf()), + "slot 133 second aligned buffer in 4 MiB block")) + return 4; + const auto small_a_real = desktop_object<ID3D12Resource>(guest, device, small_a.Get()); + const auto small_b_real = desktop_object<ID3D12Resource>(guest, device, small_b.Get()); + Snapshot after_4m{}; + if (!snap(after_4m)) return 4; + if (!check(small_a_real && (small_a_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) != 0 && + small_b_real && (small_b_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) != 0, + "4 MiB <= 256 MiB buffers are aliased") || + !check(after_4m.live[heap].bytes == small_block_bytes && after_4m.live[heap].objects == 1, + "4 MiB block opens one existing_heap") || + !check(after_4m.live[placed].objects == 2, "4 MiB block places 2 aliased buffers")) { + return 5; + } + small_a.Reset(); + small_b.Reset(); + + // Negative controls on a <= 256 MiB lazy startup block (64 MiB): unaligned and out-of-bounds + // nonzero offsets must NOT commit the whole lazy block or open an existing_heap. + constexpr SIZE_T mid_bytes = 64 * mib; + auto* const mid_ctrl = static_cast<char*>( + g_xmem_virtual_alloc(nullptr, mid_bytes, 0x20403000, 0x181, PAGE_READWRITE)); + if (!check(mid_ctrl != nullptr, "XMemVirtualAlloc 64 MiB control block") || + !check(mem_state(mid_ctrl) == MEM_RESERVE && mem_state(mid_ctrl + 1 * mib) == MEM_RESERVE && + mem_state(mid_ctrl + 4 * mib) == MEM_RESERVE, + "64 MiB control block starts lazy")) { + if (mid_ctrl) VirtualFree(mid_ctrl, 0, MEM_RELEASE); + return 4; + } + ComPtr<IUnknown> mid_unaligned; + if (!require(invoke(guest, 133, mid_ctrl + 2 * mib + 0x100, &buf_64k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, mid_unaligned.GetAddressOf()), + "slot 133 unaligned nonzero offset in 64 MiB lazy block")) { + VirtualFree(mid_ctrl, 0, MEM_RELEASE); + return 4; + } + const auto mid_unaligned_real = desktop_object<ID3D12Resource>(guest, device, mid_unaligned.Get()); + Snapshot after_ctrl_unaligned{}; + if (!snap(after_ctrl_unaligned)) return 4; + if (!check(mid_unaligned_real && + (mid_unaligned_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) == 0, + "64 MiB unaligned nonzero offset is not aliased") || + !check(after_ctrl_unaligned.live[heap].objects == 0, + "64 MiB unaligned nonzero offset does not open existing_heap") || + !check(mem_state(mid_ctrl) == MEM_RESERVE && mem_state(mid_ctrl + 1 * mib) == MEM_RESERVE && + mem_state(mid_ctrl + 4 * mib) == MEM_RESERVE, + "64 MiB unaligned nonzero offset leaves untouched pages MEM_RESERVE")) { + VirtualFree(mid_ctrl, 0, MEM_RELEASE); + return 5; + } + const auto buf_128k = buffer_desc(2 * page); + ComPtr<IUnknown> mid_oob; + if (!require(invoke(guest, 133, mid_ctrl + mid_bytes - page, &buf_128k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, mid_oob.GetAddressOf()), + "slot 133 out-of-bounds aligned offset in 64 MiB lazy block")) { + VirtualFree(mid_ctrl, 0, MEM_RELEASE); + return 4; + } + const auto mid_oob_real = desktop_object<ID3D12Resource>(guest, device, mid_oob.Get()); + Snapshot after_ctrl_oob{}; + if (!snap(after_ctrl_oob)) return 4; + if (!check(mid_oob_real && (mid_oob_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) == 0, + "64 MiB out-of-bounds aligned offset is not aliased") || + !check(after_ctrl_oob.live[heap].objects == 0, + "64 MiB out-of-bounds aligned offset does not open existing_heap") || + !check(mem_state(mid_ctrl) == MEM_RESERVE && mem_state(mid_ctrl + 1 * mib) == MEM_RESERVE && + mem_state(mid_ctrl + 4 * mib) == MEM_RESERVE, + "64 MiB out-of-bounds aligned offset leaves untouched pages MEM_RESERVE")) { + VirtualFree(mid_ctrl, 0, MEM_RELEASE); + return 5; + } + mid_unaligned.Reset(); + mid_oob.Reset(); + if (!check(VirtualFree(mid_ctrl, 0, MEM_RELEASE) != 0, "release 64 MiB control block")) return 4; + + // <= 256 MiB lazy startup block (64 MiB) at nonzero aligned offset (+2 MiB): [0, 2 MiB) starts + // MEM_RESERVE before slot 133, commits whole when eligible, aliases, and sees late A-to-B CPU writes. + auto* const mid_block = static_cast<char*>( + g_xmem_virtual_alloc(nullptr, mid_bytes, 0x20403000, 0x181, PAGE_READWRITE)); + if (!check(mid_block != nullptr, "XMemVirtualAlloc 64 MiB block") || + !check(mem_state(mid_block) == MEM_RESERVE && mem_state(mid_block + 1 * mib) == MEM_RESERVE && + mem_state(mid_block + 2 * mib) == MEM_RESERVE, + "64 MiB startup block starts lazy")) + return 4; + ComPtr<IUnknown> mid_buf; + if (!require(invoke(guest, 133, mid_block + 2 * mib, &buf_64k, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, mid_buf.GetAddressOf()), + "slot 133 aligned +2 MiB buffer in 64 MiB lazy block")) + return 4; + const auto mid_real = desktop_object<ID3D12Resource>(guest, device, mid_buf.Get()); + Snapshot after_64m{}; + if (!snap(after_64m)) return 4; + if (!check(mid_real && (mid_real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER) != 0, + "64 MiB <= 256 MiB lazy block buffer is aliased") || + !check(after_64m.live[heap].bytes == mid_bytes && after_64m.live[heap].objects == 1, + "64 MiB block opens existing_heap") || + !check(mem_state(mid_block) == MEM_COMMIT && mem_state(mid_block + 1 * mib) == MEM_COMMIT && + mem_state(mid_block + 2 * mib) == MEM_COMMIT, + "64 MiB lazy block committed right before OpenExistingHeapFromAddress")) { + return 5; + } + auto* const mid_cpu = reinterpret_cast<std::uint8_t*>(mid_block + 2 * mib); + for (UINT64 i = 0; i < page; ++i) mid_cpu[i] = pattern_byte(10, i); + if (!verify_buffer_pattern(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + mid_real.Get(), page, 10, "64 MiB +2 MiB initial A")) + return 5; + for (UINT64 i = 0; i < page; ++i) mid_cpu[i] = pattern_byte(11, i); + if (!verify_buffer_pattern(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + mid_real.Get(), page, 11, "64 MiB +2 MiB late write B")) + return 5; + mid_buf.Reset(); + std::printf("existing_heaps <= 256 MiB aliased cleanly (4 MiB + 64 MiB lazy +2 MiB A-to-B)\n"); + } else { + std::puts("skipping <= 256 MiB existing_heap check: D3D12_FEATURE_EXISTING_HEAPS=0"); + } + + // ------------------------------------------------------------------------- + // Part 2: reserve_upload_ring incremental growth (16 MiB start, grows > 16 MiB) + // ------------------------------------------------------------------------- + Snapshot pre_upload{}; + if (!snap(pre_upload)) return 4; + if (!check(pre_upload.live[upload].bytes == 0 && pre_upload.live[upload].objects == 0, + "upload budget starts at 0/0 before any upload")) + return 5; + + const unsigned list_desc[] = {static_cast<unsigned>(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + ComPtr<IUnknown> queue, allocator, allocator2, list, fence; + if (!require(invoke(guest, 8, &qd, &__uuidof(ID3D12CommandQueue), queue.GetAddressOf()), "guest queue") || + !require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), allocator.GetAddressOf()), + "guest allocator") || + !require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), allocator2.GetAddressOf()), + "guest allocator2") || + !require(invoke(guest, 73, list_desc, allocator.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), + list.GetAddressOf()), + "guest list") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), fence.GetAddressOf()), + "guest fence") || + !require(invoke(list.Get(), 139, allocator.Get(), nullptr), "guest list reset")) + return 4; + const auto real_fence = desktop_object<ID3D12Fence>(guest, device, fence.Get()); + if (!real_fence) return 4; + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto make_slot133_tex = [&](UINT w, UINT h, int seed, std::vector<std::uint8_t>& backing, + ComPtr<IUnknown>& src, ComPtr<IUnknown>& dst) { + backing.resize(UINT64{w} * h * 4); + for (UINT64 i = 0; i < backing.size(); ++i) backing[i] = pattern_byte(seed, i); + const auto td = tex2d_desc(w, h); + return require(invoke(guest, 133, backing.data(), &td, D3D12_RESOURCE_STATE_COMMON, nullptr, + &resource_iid, src.GetAddressOf()), + "slot 133 tex") && + require(invoke(guest, 127, &default_heap, D3D12_HEAP_FLAG_NONE, &td, D3D12_RESOURCE_STATE_COMMON, + nullptr, nullptr, 0u, nullptr, &resource_iid, dst.GetAddressOf()), + "slot 127 dst tex"); + }; + + std::vector<std::uint8_t> small_mem, small2_mem, big_mem, small3_mem; + ComPtr<IUnknown> small_src, small_dst, small2_src, small2_dst, big_src, big_dst, small3_src, small3_dst; + if (!make_slot133_tex(64, 64, 1, small_mem, small_src, small_dst) || + !make_slot133_tex(64, 16, 2, small2_mem, small2_src, small2_dst) || + !make_slot133_tex(2048, 2048, 3, big_mem, big_src, big_dst) || + !make_slot133_tex(64, 64, 4, small3_mem, small3_src, small3_dst)) + return 4; + + // First small upload (16 KiB): upload ring starts at 16 MiB (1 object), NOT 256 MiB. + invoke<void>(list.Get(), 17, small_dst.Get(), small_src.Get()); + Snapshot after_small1{}; + if (!snap(after_small1)) return 4; + if (!check(after_small1.live[upload].bytes == 16 * mib && after_small1.live[upload].objects == 1, + "first upload reserves 16 MiB / 1 chunk (not 256 MiB)")) { + std::printf(" got upload=%llu/%llu\n", after_small1.live[upload].bytes, after_small1.live[upload].objects); + return 5; + } + + // Second small upload (4 KiB): fits in chunk 0 (remains 16 MiB / 1 object). + invoke<void>(list.Get(), 17, small2_dst.Get(), small2_src.Get()); + Snapshot after_small2{}; + if (!snap(after_small2)) return 4; + if (!check(after_small2.live[upload].bytes == 16 * mib && after_small2.live[upload].objects == 1, + "second small upload reuses 16 MiB chunk")) + return 5; + + // Submit & verify small1 and small2 before growing past 16 MiB. + if (!require(invoke(list.Get(), 9), "list close 1")) return 4; + IUnknown* lists1[] = {list.Get()}; + invoke<void>(queue.Get(), 10, 1u, lists1); + if (!require(invoke(queue.Get(), 14, fence.Get(), ++guest_val), "queue signal 1")) return 4; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 4; + const bool done1 = SUCCEEDED(real_fence->SetEventOnCompletion(guest_val, ev)) && + WaitForSingleObject(ev, wait_ms) == WAIT_OBJECT_0; + CloseHandle(ev); + if (!check(done1, "guest queue wait 1")) return 4; + + const auto small_dst_real = desktop_object<ID3D12Resource>(guest, device, small_dst.Get()); + const auto small2_dst_real = desktop_object<ID3D12Resource>(guest, device, small2_dst.Get()); + if (!verify_texture_box(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + small_dst_real.Get(), 0, 0, 64, 64, 64, 1, "small1 (chunk 0)") || + !verify_texture_box(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + small2_dst_real.Get(), 0, 0, 64, 16, 64, 2, "small2 (chunk 0)")) + return 5; + + // Next upload: 2048x2048 RGBA8 (16 MiB exact) > remaining space in chunk 0 -> appends 32 MiB chunk (48 MiB / 2). + if (!require(invoke(list.Get(), 139, allocator2.Get(), nullptr), "guest list reset 2")) return 4; + invoke<void>(list.Get(), 17, big_dst.Get(), big_src.Get()); + Snapshot after_big{}; + if (!snap(after_big)) return 4; + if (!check(after_big.live[upload].objects == 2 && after_big.live[upload].bytes == 48 * mib, + "upload > 16 MiB appends 32 MiB chunk (48 MiB / 2 objects)")) { + std::printf(" got upload=%llu/%llu\n", after_big.live[upload].bytes, after_big.live[upload].objects); + return 5; + } + + // Subsequent small upload lands in chunk 1 without adding another chunk. + invoke<void>(list.Get(), 17, small3_dst.Get(), small3_src.Get()); + Snapshot after_small3{}; + if (!snap(after_small3)) return 4; + if (!check(after_small3.live[upload].objects == 2 && after_small3.live[upload].bytes == 48 * mib, + "third small upload reuses chunk 1 (48 MiB / 2 objects)")) + return 5; + + if (!require(invoke(list.Get(), 9), "list close 2")) return 4; + IUnknown* lists2[] = {list.Get()}; + invoke<void>(queue.Get(), 10, 1u, lists2); + if (!require(invoke(queue.Get(), 14, fence.Get(), ++guest_val), "queue signal 2")) return 4; + ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 4; + const bool done2 = SUCCEEDED(real_fence->SetEventOnCompletion(guest_val, ev)) && + WaitForSingleObject(ev, wait_ms) == WAIT_OBJECT_0; + CloseHandle(ev); + if (!check(done2, "guest queue wait 2")) return 4; + + const auto big_dst_real = desktop_object<ID3D12Resource>(guest, device, big_dst.Get()); + const auto small3_dst_real = desktop_object<ID3D12Resource>(guest, device, small3_dst.Get()); + if (!verify_texture_box(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + big_dst_real.Get(), 0, 0, 64, 64, 2048, 3, "big top-left (chunk 1)") || + !verify_texture_box(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + big_dst_real.Get(), 1984, 1984, 64, 64, 2048, 3, "big bottom-right (chunk 1)") || + !verify_texture_box(device, own_queue.Get(), own_alloc.Get(), own_list.Get(), own_fence.Get(), own_val, + small3_dst_real.Get(), 0, 0, 64, 64, 64, 4, "small3 (chunk 1)")) + return 5; + + const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("upload_ring grew 16 MiB -> 48 MiB (2 chunks); debug_errors_or_warnings=%llu\n", errors); + if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; + + std::puts("PASS"); + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + // The growth checks describe the default ring (doubling chunks up to 256 MiB). The stand-in reads + // X2W_D3D12_RING_RELEASE_AT_SUBMIT on first use in this process, so clear it before any call. + SetEnvironmentVariableW(L"X2W_D3D12_RING_RELEASE_AT_SUBMIT", nullptr); + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "cap"))) { + std::puts("usage: startup_slot133_heap_cap_check <warp|hardware> [cap]"); + return 2; + } + const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool cap = argc == 3; + if (!load_shims(cap)) return 3; + + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), warp); + if (!adapter) return 77; + + char debug_env[2]{}; + const bool debug_on = GetEnvironmentVariableA("X2W_D3D12_DEBUG", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_on) { + ComPtr<ID3D12Debug> debug_iface; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug_iface)))) return 77; + } + + ComPtr<IUnknown> guest; + ComPtr<ID3D12Device> device; + std::array<unsigned char, 64> parameters{}; + if (!require(g_create_xbox_device(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(guest.GetAddressOf())), + "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + + ComPtr<ID3D12InfoQueue> debug; + if (debug_on && FAILED(device.As(&debug))) return 3; + if (debug) { + D3D12_MESSAGE_SEVERITY severities[] = { + D3D12_MESSAGE_SEVERITY_CORRUPTION, D3D12_MESSAGE_SEVERITY_ERROR, D3D12_MESSAGE_SEVERITY_WARNING}; + D3D12_INFO_QUEUE_FILTER filter{}; + filter.AllowList.NumSeverities = static_cast<UINT>(std::size(severities)); + filter.AllowList.pSeverityList = severities; + if (FAILED(debug->AddStorageFilterEntries(&filter))) return 3; + debug->ClearStoredMessages(); + } + + DXGI_ADAPTER_DESC1 desc{}; + LARGE_INTEGER version{}; + adapter->GetDesc1(&desc); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &version); + const auto driver = static_cast<UINT64>(version.QuadPart); + std::printf("adapter=%ls driver=%llu.%llu.%llu.%llu debug_layer=%s\n", desc.Description, + driver >> 48, (driver >> 32) & 0xffff, (driver >> 16) & 0xffff, driver & 0xffff, + debug ? "enabled" : "off"); + return run_check(guest.Get(), device.Get(), debug.Get(), cap); +} diff --git a/tests/startup_slot67_indirect.cpp b/tests/startup_slot67_indirect.cpp new file mode 100644 index 0000000000..6cb52681fd --- /dev/null +++ b/tests/startup_slot67_indirect.cpp @@ -0,0 +1,255 @@ +#include "startup_slot67_indirect.h" +#include "startup_indirect_writer.h" +#include "startup_stream_setup.h" +#include <d3dcompiler.h> +#include <d3d12sdklayers.h> +#include <array> +#include <cstdio> +#include <cstring> +#include <fstream> + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +using Microsoft::WRL::ComPtr; + +namespace { +using Record = std::array<UINT, 7>; +constexpr Record initial{0xa5a5a5a5, 0, 0, 0, 0x5a5a5a5a, 0x12345678, 0x9abcdef0}; +constexpr UINT offset = sizeof(UINT); // leading guard and a neighboring three-DWORD guard record +constexpr char producer[] = R"( +RWByteAddressBuffer args : register(u0); +cbuffer Size : register(b0) { uint groups; }; +[numthreads(1, 1, 1)] +void main() { args.Store3(4, uint3(groups, 1, 1)); } +)"; +StreamWord word(const void* value) { return reinterpret_cast<StreamWord>(value); } +} + +void Slot67Indirect::prepare(IDXGIAdapter* adapter, void* guest_device, void* guest_list, void* backing, UINT groups, bool write_zero, + void* guest_queue, void* guest_output) +{ + auto* guest = static_cast<ID3D12Device*>(guest_device); + ComPtr<ID3D12Device> device; + check(D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(&device)), "open producer's desktop device"); + auto list = indirect_native_object<ID3D12GraphicsCommandList>(device.Get(), guest, static_cast<IUnknown*>(guest_list)); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, sizeof(initial), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + check(static_cast<HRESULT>(invoke(guest, 133, word(backing), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(placed.GetAddressOf()))), "place indirect arguments"); + native_args = indirect_native_object<ID3D12Resource>(device.Get(), guest, placed.Get()); + const auto& args = native_args; + if (guest_queue) { + native_queue = indirect_native_object<ID3D12CommandQueue>(device.Get(), guest, static_cast<IUnknown*>(guest_queue)); + native_output = indirect_native_object<ID3D12Resource>(device.Get(), guest, static_cast<IUnknown*>(guest_output)); + std::printf("chain queue=%p output=%p gpu=0x%llx\n", static_cast<void*>(native_queue.Get()), + static_cast<void*>(native_output.Get()), static_cast<unsigned long long>(native_output->GetGPUVirtualAddress())); + } + std::printf("writer resource=%p gpu=0x%llx interval=[4,16) writer=%s\n", + static_cast<void*>(args.Get()), static_cast<unsigned long long>(args->GetGPUVirtualAddress()), + groups || write_zero ? "dispatch" : "omitted"); + upload = make_buffer(device.Get(), sizeof(initial), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + readback = make_buffer(device.Get(), sizeof(initial), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_RANGE empty{0, 0}; + void* mapped = nullptr; + check(upload->Map(0, &empty, &mapped), "map zero dispatch record"); + std::memcpy(mapped, initial.data(), sizeof(initial)); + upload->Unmap(0, nullptr); + transition(list.Get(), args.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(args.Get(), 0, upload.Get(), 0, sizeof(initial)); + auto state = D3D12_RESOURCE_STATE_COPY_DEST; + if (groups || write_zero) { + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 1}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> blob, code; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr), "serialize producer root"); + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), "create producer root"); + check(D3DCompile(producer, sizeof(producer) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code, nullptr), "compile indirect producer"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&writer)), "create indirect producer"); + transition(list.Get(), args.Get(), state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + list->SetComputeRootSignature(root.Get()); + list->SetComputeRoot32BitConstant(1, groups, 0); + record_indirect_writer(list.Get(), writer.Get(), args.Get()); + } + transition(list.Get(), args.Get(), state, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback.Get(), 0, args.Get(), 0, sizeof(initial)); + transition(list.Get(), args.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + D3D12_INDIRECT_ARGUMENT_DESC command{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC sig{sizeof(D3D12_DISPATCH_ARGUMENTS), 1, &command, 0}; + check(guest->CreateCommandSignature(&sig, nullptr, IID_PPV_ARGS(&signature)), "create guest dispatch signature"); +} + +void Slot67Indirect::execute(void* list, UINT commands, bool count_buffer, bool outside) const +{ + invoke(list, 61, word(signature.Get()), commands, word(placed.Get()), outside ? sizeof(initial) - sizeof(UINT) : offset, + count_buffer ? word(placed.Get()) : 0, count_buffer ? offset : 0); +} + +void Slot67Indirect::capture_before_consumer(IDXGIAdapter* adapter, void* guest_device, void* guest_list) +{ + auto* guest = static_cast<ID3D12Device*>(guest_device); + ComPtr<ID3D12Device> device; + check(D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(&device)), "open consumer's desktop device"); + auto list = indirect_native_object<ID3D12GraphicsCommandList>(device.Get(), guest, static_cast<IUnknown*>(guest_list)); + auto args = indirect_native_object<ID3D12Resource>(device.Get(), guest, placed.Get()); + if (args.Get() != native_args.Get() || args->GetGPUVirtualAddress() != native_args->GetGPUVirtualAddress()) + throw std::runtime_error("indirect argument resource changed"); + std::printf("consumer resource=%p gpu=0x%llx interval=[4,16)\n", + static_cast<void*>(args.Get()), static_cast<unsigned long long>(args->GetGPUVirtualAddress())); + before_consumer = make_buffer(device.Get(), sizeof(initial), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + transition(list.Get(), args.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(before_consumer.Get(), 0, args.Get(), 0, sizeof(initial)); + transition(list.Get(), args.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); +} + +bool Slot67Indirect::check_record(UINT groups, bool write_zero, bool consumer_boundary) const +{ + const D3D12_RANGE range{0, sizeof(initial)}, empty{0, 0}; + void* mapped = nullptr; + auto* snapshot = consumer_boundary ? before_consumer.Get() : readback.Get(); + check(snapshot->Map(0, &range, &mapped), "map GPU argument readback after queue fence"); + Record actual{}; + std::memcpy(actual.data(), mapped, sizeof(actual)); + snapshot->Unmap(0, &empty); + const UINT yz = groups || write_zero ? 1u : 0u; + Record expected = initial; + expected[1] = groups; + expected[2] = expected[3] = yz; + std::printf("GPU argument record: %08x [%u,%u,%u] %08x %08x %08x (%s)\n", + actual[0], actual[1], actual[2], actual[3], actual[4], actual[5], actual[6], + consumer_boundary ? "before consumer" : "after writer"); + std::fflush(stdout); + return actual == expected; +} + +// A source-built desktop graphics observer. The slot-67 shader's actual aliased UAV is the SRV; +// no CPU copy or CPU-derived colour is used as a draw input. Both captures are fenced on the same +// underlying DIRECT queue as the writer and translated ExecuteIndirect. +void Slot67Indirect::draw_pixels(IDXGIAdapter* adapter, void* guest_device, void* guest_queue, void* guest_output, bool stale) const +{ + auto* guest = static_cast<ID3D12Device*>(guest_device); + ComPtr<ID3D12Device> device; + check(D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(&device)), "open graphics observer's desktop device"); + auto queue = indirect_native_object<ID3D12CommandQueue>(device.Get(), guest, static_cast<IUnknown*>(guest_queue)); + auto output = indirect_native_object<ID3D12Resource>(device.Get(), guest, static_cast<IUnknown*>(guest_output)); + if (queue.Get() != native_queue.Get() || (output.Get() == native_output.Get()) == stale) + throw std::runtime_error("graphics queue/output identity mismatch"); + std::printf("graphics queue=%p output=%p gpu=0x%llx\n", static_cast<void*>(queue.Get()), + static_cast<void*>(output.Get()), static_cast<unsigned long long>(output->GetGPUVirtualAddress())); + constexpr char shader[] = R"( +ByteAddressBuffer result : register(t0); +float4 vs(uint id : SV_VertexID) : SV_Position { + return float4(id == 1 ? 3 : -1, id == 2 ? -3 : 1, 0, 1); +} +float4 ps(float4 position : SV_Position) : SV_Target { + uint word = result.Load(uint(position.x) * 4); + if (word == 0xc5c5c5c5) discard; + return float4(word & 255, (word >> 8) & 255, (word >> 16) & 255, 255) / 255.0; +} +)"; + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + param.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> blob, vs, ps; + ComPtr<ID3D12RootSignature> graphics_root; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr), "serialize pixel root"); + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&graphics_root)), "create pixel root"); + check(D3DCompile(shader, sizeof(shader)-1, nullptr, nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr), "compile observer VS"); + check(D3DCompile(shader, sizeof(shader)-1, nullptr, nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr), "compile observer PS"); + constexpr UINT width = 8, height = 4; + constexpr DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = graphics_root.Get(); + pso.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + pso.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + pso.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso.SampleMask = UINT_MAX; + pso.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso.RasterizerState.DepthClipEnable = TRUE; + pso.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso.NumRenderTargets = 1; + pso.RTVFormats[0] = format; + pso.SampleDesc.Count = 1; + ComPtr<ID3D12PipelineState> pipeline; + check(device->CreateGraphicsPipelineState(&pso, IID_PPV_ARGS(&pipeline)), "create observer graphics pipeline"); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear{format, {0, 0, 0, 1}}; + auto target = resource(device.Get(), desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + ComPtr<ID3D12Resource> captures[2]; + for (auto& capture : captures) + capture = make_buffer(device.Get(), bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + ComPtr<ID3D12DescriptorHeap> rtvs; + check(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtvs)), "create observer RTV heap"); + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv); + ComputeCommands commands(device.Get(), queue.Get(), pipeline.Get()); + auto* list = commands.list.Get(); + const auto capture = [&](ID3D12Resource* readback) { + transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{readback, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + const D3D12_TEXTURE_COPY_LOCATION from{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(list, target.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + }; + list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); + capture(captures[0].Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + list->SetGraphicsRootSignature(graphics_root.Get()); + list->SetGraphicsRootShaderResourceView(0, output->GetGPUVirtualAddress()); + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + capture(captures[1].Get()); + transition(list, output.Get(), D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + commands.submit_and_wait(device.Get()); + std::puts("graphics fence completed: clear and draw captures"); + ComPtr<ID3D12InfoQueue> info; + if (SUCCEEDED(device.As(&info))) { + for (UINT64 i = 0, n = info->GetNumStoredMessagesAllowedByRetrievalFilter(); i < n; ++i) { + SIZE_T size = 0; + check(info->GetMessage(i, nullptr, &size), "size graphics debug message"); + std::vector<unsigned char> storage(size); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + check(info->GetMessage(i, message, &size), "read graphics debug message"); + if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { + std::fprintf(stderr, "graphics debug error: %s\n", message->pDescription); + throw std::runtime_error("graphics debug layer error"); + } + } + std::puts("graphics debug layer: no errors"); + } else { + std::puts("graphics debug layer: unavailable"); + } + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_INDIRECT_PIXEL_OUT", path, MAX_PATH); + if (!n || n >= MAX_PATH) throw std::runtime_error("missing pixel output path"); + std::ofstream file(path, std::ios::binary); + const D3D12_RANGE range{0, static_cast<SIZE_T>(bytes)}, empty{0, 0}; + for (const auto& readback : captures) { + void* mapped = nullptr; + check(readback->Map(0, &range, &mapped), "map fenced pixel capture"); + for (UINT y = 0; y < height; ++y) + file.write(static_cast<const char*>(mapped) + footprint.Offset + y * footprint.Footprint.RowPitch, width * sizeof(UINT)); + readback->Unmap(0, &empty); + } + file.close(); + if (!file) throw std::runtime_error("write pixel capture"); +} diff --git a/tests/startup_slot67_indirect.h b/tests/startup_slot67_indirect.h new file mode 100644 index 0000000000..7acc7b0d47 --- /dev/null +++ b/tests/startup_slot67_indirect.h @@ -0,0 +1,22 @@ +#pragma once +#include <d3d12.h> +#include <dxgi.h> +#include <wrl/client.h> + +// Keeps the producer, argument resource and signature alive until the consumer's queue fence. +struct Slot67Indirect { + Microsoft::WRL::ComPtr<ID3D12RootSignature> root; + Microsoft::WRL::ComPtr<ID3D12PipelineState> writer; + Microsoft::WRL::ComPtr<ID3D12Resource> placed, upload, readback, before_consumer, native_args; + Microsoft::WRL::ComPtr<ID3D12CommandSignature> signature; + Microsoft::WRL::ComPtr<ID3D12CommandQueue> native_queue; + Microsoft::WRL::ComPtr<ID3D12Resource> native_output; + + void prepare(IDXGIAdapter* adapter, void* guest_device, void* guest_list, void* backing, UINT groups, bool write_zero = false, + void* guest_queue = nullptr, void* guest_output = nullptr); + void execute(void* guest_list, UINT commands, bool count_buffer, bool outside) const; + void capture_before_consumer(IDXGIAdapter* adapter, void* guest_device, void* guest_list); + bool check_record(UINT groups, bool write_zero = false, bool consumer_boundary = false) const; + // The guest list has closed and its fence has completed; the output rests in COMMON. + void draw_pixels(IDXGIAdapter* adapter, void* guest_device, void* guest_queue, void* guest_output, bool stale) const; +}; diff --git a/tests/startup_slot67_indirect_dispatch_check.py b/tests/startup_slot67_indirect_dispatch_check.py new file mode 100644 index 0000000000..b40606dbac --- /dev/null +++ b/tests/startup_slot67_indirect_dispatch_check.py @@ -0,0 +1,229 @@ +"""GPU-written Dispatch arguments consumed by a translated slot 67 pipeline on the same queue (#2492). + +`mutation` runs the device-free half: it builds the same 320-word expectation as `check()`, verifies that the +prefilled sentinel readback matches zero written words, that one flipped consumer word and one flipped sentinel are +both caught, and that the 2-group and 5-group references differ only at indices 2, 3 and 4. +#3209 additionally fences the writer and consumer separately and draws actual GPU output to an offscreen target. +""" +import os +import re +import struct +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_flat_param_check import assemble + + +# One thread per group. s7 is GroupID.x, s4 is a root constant, s6 is the buffer table. +SOURCE = """s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v3, s7 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +v_xor_b32 v5, s4, v5 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_endpgm +""" +PROGRAM = bytes.fromhex('06038abe80038bbe05030cf4000000fa7fc08cbf0702067e82060834001030e004050380' + '703f8cbf040a0a3a001070e004050480000081bf') + + +def expected_words(written): + return [(((0x8b02a7f1 + i * 0x413b1) & C.MASK) ^ C.KEY) if i < written else C.SENTINEL + for i in range(C.WORDS)] + + +def compare_words(actual, expected): + """Return the differing indices, or one length entry when the readback size is wrong.""" + if len(actual) != len(expected): + return [('length', len(actual), len(expected))] + return [i for i, (word, want) in enumerate(zip(actual, expected)) if word != want] + + +def setup(directory, adapter): + cache, env = prepare(directory) + env.update(X2W_TEST_COMPUTE_ROOT=str(directory / 'compute_root'), X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + else: + env.pop('X2W_TEST_DISPATCH_HARDWARE', None) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + (directory / 'program').write_bytes(PROGRAM) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a((1, 1, 1), C.USER7 | C.TGID_X)) + return cache, env + + +def check(directory, consumer, env, mode, groups, written, direct=False): + actual, result = dispatch(directory, consumer, env, ('dispatch-reference-' if direct else 'dispatch-indirect-') + mode) + print(result.stdout, end='') + expected = expected_words(written) + if direct: + assert len(lines(result, f'Dispatch({groups}, 1, 1) translated')) == 1, result.stderr[-2500:] + else: + assert f'[{groups},{int(bool(groups))},{int(bool(groups))}]' in result.stdout, result.stdout + wrong = compare_words(actual, expected) + if wrong: + first = wrong[0] + if isinstance(first, tuple): + raise AssertionError(f'{mode}: readback has {first[1]} words, expected {first[2]}\n' + f'{result.stderr[-2500:]}') + raise AssertionError(f'{mode}: word {first} got {actual[first]:08x}, expected {expected[first]:08x}, ' + f'{len(wrong)} differences\n{result.stderr[-2500:]}') + for line in lines(result, 'x2w-d3d12-debug '): + assert ' sev=0 ' not in line and ' sev=1 ' not in line, line + label = 'direct' if direct else 'indirect' + print(f'{label} {mode}: all {C.WORDS} words match ({written} written, {C.WORDS-written} sentinel)') + return result + + +def expected_pixels(words): + # Eight columns, four rows. The native observer discards sentinel pixels and encodes + # the low three bytes of each actual GPU output word into an RGBA8 render target. + return [(0xff000000 if word == C.SENTINEL else 0xff000000 | (word & 0xffffff)) + for word in words[:8]] * 4 + + +def check_pixels(directory, consumer, env, mode, groups, written, writer=True, stale=False): + path = directory / 'pixels.bin' + path.unlink(missing_ok=True) + actual, run = dispatch(directory, consumer, dict(env, X2W_TEST_INDIRECT_PIXEL_OUT=str(path)), + 'dispatch-indirect-pixel-' + mode) + print(run.stdout, end='') + assert not lines(run, 'ExecuteIndirect refused'), run.stderr[-3000:] + census = lines(run, 'x2w-render compute census key ') + assert any('1 dispatches, 1 translated' in line for line in census), run.stderr[-3000:] + assert compare_words(actual, expected_words(written)) == [], (mode, 'compute output mismatch') + identity = re.findall(r'(?:writer|consumer) resource=(\S+) gpu=(\S+) interval=\[4,16\)', run.stdout) + assert len(identity) == 2 and identity[0] == identity[1], run.stdout + yz = int(writer) + record = f'a5a5a5a5 [{groups},{yz},{yz}] 5a5a5a5a 12345678 9abcdef0' + assert f'GPU argument record: {record} (after writer)' in run.stdout, run.stdout + assert f'GPU argument record: {record} (before consumer)' in run.stdout, run.stdout + assert f'writer={"dispatch" if writer else "omitted"}' in run.stdout, run.stdout + queues = re.findall(r'guest queue=(\S+) (?:writer fence=1|consumer fence=2) completed', run.stdout) + assert len(queues) == 2 and queues[0] == queues[1], run.stdout + native = re.findall(r'(?:chain|graphics) queue=(\S+) output=(\S+) gpu=(\S+)', run.stdout) + assert len(native) == 2 and native[0][0] == native[1][0], run.stdout + assert (native[0][1:] != native[1][1:]) == stale, run.stdout + stages = ['writer fence=1 completed', '(after writer)', 'consumer resource=', 'consumer fence=2 completed', + '(before consumer)', 'graphics queue=', 'graphics fence completed'] + assert [run.stdout.index(stage) for stage in stages] == sorted(run.stdout.index(stage) for stage in stages), run.stdout + pixels = list(struct.unpack('<64I', path.read_bytes())) + assert pixels[:32] == [0xff000000] * 32, (mode, 'clear capture') + expected = expected_pixels(expected_words(written)) + if stale: + assert compare_words(pixels[32:], expected), 'stale SRV incorrectly passed the positive oracle' + expected = expected_pixels([(0x8b02a7f1 + i * 0x413b1) & C.MASK for i in range(8)]) + assert compare_words(pixels[32:], expected) == [], (mode, pixels[32:], expected) + for line in lines(run, 'x2w-d3d12-debug '): + assert ' sev=0 ' not in line and ' sev=1 ' not in line, line + print('pixel first row:', ' '.join(f'{word:08x}' for word in pixels[32:40])) + print(f'pixel {mode}: 320 compute words, two 7-DWORD argument snapshots, 64 RGBA8 pixels match; ' + f'{sum(v != 0xff000000 for v in pixels[32:])}/32 changed' + + (' (stale SRV rejected by positive oracle)' if stale else '')) + return run + + +def check_mutation(): + sentinel = [C.SENTINEL] * C.WORDS + assert len(sentinel) == 320 and C.WORDS == 320, (len(sentinel), C.WORDS) + assert compare_words(sentinel, expected_words(0)) == [], 'a fully sentinel readback must match zero writes' + for groups in (2, 5): + reference = expected_words(groups) + assert compare_words(list(reference), reference) == [], f'{groups}: reference must match itself' + assert all(word != C.SENTINEL for word in reference[:groups]), f'{groups}: consumer words use the sentinel' + for label, index in (('first consumer', 0), ('last consumer', groups - 1), + ('first sentinel', groups), ('last sentinel', C.WORDS - 1)): + mutated = list(reference) + mutated[index] ^= 1 + assert compare_words(mutated, reference) == [index], f'{groups}: {label} mutation was not isolated' + assert compare_words(reference[:-1], reference), f'{groups}: a short readback passed' + assert compare_words(reference + [C.SENTINEL], reference), f'{groups}: a long readback passed' + two, five = expected_words(2), expected_words(5) + differing = [i for i in range(C.WORDS) if two[i] != five[i]] + assert differing == [2, 3, 4], f'2/5 group references differ at {differing}' + assert compare_words(two, five) == [2, 3, 4] + for groups in (0, 2, 5): + pixels = expected_pixels(expected_words(groups)) + for index in (0, 7, 31): + mutant = list(pixels) + mutant[index] ^= 1 + assert compare_words(mutant, pixels) == [index] + assert compare_words(pixels[:-1], pixels) + assert compare_words(expected_pixels(two), expected_pixels(five)) == [y * 8 + x for y in range(4) for x in (2, 3, 4)] + print(f'mutation oracle: {C.WORDS} words, sentinel 0x{C.SENTINEL:08x}; consumer and sentinel flips detected; ' + '2/5 references differ at [2, 3, 4]') + + +def run_mutation(): + try: + check_mutation() + except AssertionError as error: + print(f'FAIL: {error}', file=sys.stderr) + return 1 + print('slot67 indirect mutation oracle: PASS (device-free)') + return 0 + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + cache, env = setup(directory, adapter) + missing = check(directory, consumer, env, '5', 5, 0) + refused = lines(missing, 'refused') + assert any('no translation' in line for line in refused), missing.stderr[-2500:] + print(next(line for line in refused if 'no translation' in line)) + req, = cache.glob('req_*.c67') + key = req.stem.removeprefix('req_') + translated = subprocess.run([sys.executable, '-B', C.G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)) + assert f'{key}: ok' in translated.stdout, translated.stdout + for groups in (2, 5, 0): + run = check(directory, consumer, env, str(groups) if groups else 'zero', groups, groups) + assert not lines(run, 'refused:'), run.stderr[-2500:] + if groups: + check(directory, consumer, env, str(groups), groups, groups, direct=True) + for mode, groups, writer in (('2', 2, True), ('5', 5, True), ('zero', 0, True), ('omit', 0, False)): + check_pixels(directory, consumer, env, mode, groups, groups, writer) + check_pixels(directory, consumer, env, '5-stale', 5, 5, stale=True) + for mode, reason in (('multi', 'one rootless command'), ('counted', 'no count buffer'), + ('outside', 'outside a unique placed buffer'), ('output-alias', 'also a bound shader resource')): + run = check(directory, consumer, env, mode, 5, 0) + refusals = lines(run, 'ExecuteIndirect refused') + assert len(refusals) == 1 and reason in refusals[0], run.stderr[-2500:] + print(refusals[0]) + manifest = cache / f'{key}.txt' + text = manifest.read_text() + buf = 'srv 0 buf table 1 0' + assert text.count(buf) == 1 + for other in ('srv 0 tex2d table 1 0', 'srv 0 buf heap rootconst 0 0'): + manifest.write_text(text.replace(buf, other)) + run = check(directory, consumer, env, '5', 5, 0) + refusals = lines(run, 'ExecuteIndirect refused') + assert len(refusals) == 1 and 'requires fixed-table raw buffers' in refusals[0], run.stderr[-2500:] + print(refusals[0]) + layer = lines(run, 'x2w-d3d12 debug layer: ') + print('debug layer:', 'enabled' if layer and '0x00000000' in layer[0] else 'unavailable') + + +if __name__ == '__main__': + if len(sys.argv) == 2 and sys.argv[1] == 'mutation': + sys.exit(run_mutation()) + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + assert assemble(sys.argv[2], SOURCE) == PROGRAM + print('slot 67 indirect consumer matches LLVM gfx1013 assembly') + elif len(sys.argv) == 4 and sys.argv[3] in ('hardware', 'warp'): + main(*sys.argv[1:]) + else: + sys.exit('usage: startup_slot67_indirect_dispatch_check.py <consumer> <dxc> <warp|hardware> | ' + 'binary <llvm-mc> | mutation') diff --git a/tests/startup_smem_address_check.py b/tests/startup_smem_address_check.py index e2d53f0f3f..ba169a9e82 100644 --- a/tests/startup_smem_address_check.py +++ b/tests/startup_smem_address_check.py @@ -291,6 +291,22 @@ def controls(): for word in words[:64]: assert 0 < ((word >> 23) & 0xff) < 0xff, hex(word) + # 10. A complete s_add_u32/s_addc_u32 table-pointer pair goes through the full translate() (with its SCC + # check) and reads the same bytes as the single load at the summed offset; any other SCC reader is refused. + assert build_smem_pointer_pair_pipeline().hlsl_vs() == build_smem_dwordx4_pipeline().hlsl_vs() + vs_scc = b''.join(( + encode_sop2(0x00, 20, 0, 128 + 8), + encode_sop2(0x04, 21, 1, 128 + 0), + encode_sop2(0x0a, 30, 129, 128), # s_cselect_b32 s30, 1, 0 reads the carry + encode_smem(SMEM_LOAD_DWORDX4, 16, 20, soffset=125, imm=0x8), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + try: + G.Pipeline(vs_scc, struct.pack('<3I', 0xf800180f, 0, 0xbf810000), root_with_one_constant()).hlsl_vs() + raise AssertionError('an independent SCC read after the pointer pair was accepted') + except G.Unsupported as error: + assert 'scc' in str(error), error + # ---- D3D12 GPU readback cases ------------------------------------------------------------------------- @@ -309,6 +325,24 @@ def build_smem_dwordx4_pipeline(): return G.Pipeline(vs, ps, root_with_one_constant()) +def build_smem_pointer_pair_pipeline(): + """Same loads as build_smem_dwordx4_pipeline, but the vertex-buffer table pointer s[0:1] is advanced by a complete + s_add_u32 s20, s0, 8 / s_addc_u32 s21, s1, 0 pair and the load adds offset:0x8 (total 0x10).""" + vs = b''.join(( + encode_sop2(0x00, 20, 0, 128 + 8), # s_add_u32 s20, s0, 8 + encode_sop2(0x04, 21, 1, 128 + 0), # s_addc_u32 s21, s1, 0 + encode_smem(SMEM_LOAD_DWORDX4, 16, 20, soffset=125, imm=0x8), + encode_smem(SMEM_BUFFER_LOAD_DWORDX4, 20, 16, soffset=8, imm=0x18, glc=1), + encode_vop1(0x01, 4, 20), + encode_vop1(0x01, 5, 21), + encode_vop1(0x01, 6, 22), + encode_vop1(0x01, 7, 23), + struct.pack('<3I', 0xf80008cf, 0x07060504, 0xbf810000), + )) + ps = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + return G.Pipeline(vs, ps, root_with_one_constant()) + + def build_smem_m0_and_overlap_pipeline(): """VS: m0 + offset:0x14 dlc, const SGPR + offset:0x08, and overlapping runtime SGPR s[20:21] + offset:0x1c glc.""" vs = b''.join(( @@ -416,6 +450,15 @@ def check_gpu(directory, compiler, consumer, adapter, fxc=None): print(f's_buffer_load_dwordx4 (soffset={soffset}, offset:0x18):', [l for l in res.stdout.splitlines() if 'mismatches=' in l][0]) + # 1b. Vertex-buffer table pointer advanced by a complete s_add_u32/s_addc_u32 pair must read the same bytes as case 1. + p_pair = build_smem_pointer_pair_pipeline() + res_pair = run_buffer_case(directory, compiler, consumer, adapter, p_pair, p_pair.hlsl_vs(), + expected_smem_dwordx4(soffset=32), soffset=32) + if res_pair.returncode: + raise RuntimeError('advanced vertex-buffer table pointer pair:\n' + res_pair.stdout + res_pair.stderr) + print('advanced vertex-buffer table pointer (s_add_u32 + s_addc_u32, offset:0x8):', + [l for l in res_pair.stdout.splitlines() if 'mismatches=' in l][0]) + # 2. m0 + offset:0x14 dlc and destination-overlapping runtime SGPR s[20:21] + offset:0x1c glc. p_m0 = build_smem_m0_and_overlap_pipeline() src_m0 = p_m0.hlsl_vs() diff --git a/tests/startup_stage_package_check.py b/tests/startup_stage_package_check.py index fdc7cfeae3..a08145f767 100644 --- a/tests/startup_stage_package_check.py +++ b/tests/startup_stage_package_check.py @@ -1,4 +1,5 @@ """Exercise safe startup staging using synthetic files; no game package is needed.""" +import ctypes import os from pathlib import Path import subprocess @@ -12,7 +13,7 @@ def call(powershell, package, exe, run): return subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), "-PackageDir", str(package), "-Exe", str(exe), "-RunDir", str(run)], - capture_output=True, text=True, timeout=30, + capture_output=True, encoding="utf-8", errors="replace", timeout=30, ) @@ -22,7 +23,8 @@ def stage_from_changed_location(powershell, root, package, location): r"$ErrorActionPreference = 'Stop'; Set-Location -LiteralPath $env:X2W_TEST_LOCATION; " r"& $env:X2W_TEST_SCRIPT -PackageDir $env:X2W_TEST_PACKAGE -Exe 'bin\child.exe' -RunDir 'package-run'"], cwd=root, env=dict(os.environ, X2W_TEST_LOCATION=str(location), X2W_TEST_SCRIPT=str(SCRIPT), - X2W_TEST_PACKAGE=str(package)), capture_output=True, text=True, timeout=30, + X2W_TEST_PACKAGE=str(package)), + capture_output=True, encoding="utf-8", errors="replace", timeout=30, ) @@ -84,7 +86,7 @@ def main(): junction = root / "link" result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(junction), str(location)], - capture_output=True, text=True, timeout=30) + capture_output=True, errors="replace", timeout=30) assert result.returncode == 0, result.stdout + result.stderr try: result = call(powershell, package, exe.name, junction / "new-run") @@ -92,6 +94,73 @@ def main(): assert not (location / "new-run").exists() finally: junction.rmdir() + + # The package can be named through an alias while the destination uses its real path. + # Both spellings must refer to the same tree for the separation check. + alias = root / "package-alias" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(alias), str(package)], + capture_output=True, errors="replace", timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + nested = package / "new" / "run" + result = call(powershell, alias, exe.name, nested) + assert result.returncode != 0 and "separate from PackageDir" in result.stderr, result.stdout + result.stderr + assert not nested.exists() + safe = root / "alias-safe-run" + result = call(powershell, alias, exe.name, safe) + assert result.returncode == 0, result.stdout + result.stderr + assert (safe / exe.name).read_bytes() == original[exe.name] + finally: + alias.rmdir() + + # A path spelled inside the package can also lead outside through a junction. + outside_dir = root / "outside-dir" + outside_dir.mkdir() + (outside_dir / "outside.exe").write_bytes(b"outside executable") + escape = package / "escape" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(escape), str(outside_dir)], + capture_output=True, errors="replace", timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + refused = root / "escape-run" + result = call(powershell, package, "escape/outside.exe", refused) + assert result.returncode != 0 and "inside PackageDir" in result.stderr, result.stdout + result.stderr + assert not refused.exists() + finally: + escape.rmdir() + + # A junction whose target stays inside the package remains usable. + inside = package / "inside" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(inside), str(bin_dir)], + capture_output=True, errors="replace", timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + safe = root / "inside-run" + result = call(powershell, package, "inside/child.exe", safe) + assert result.returncode == 0, result.stdout + result.stderr + assert (safe / "child.exe").read_bytes() == b"child" + assert (safe / "side.DLL").read_bytes() == b"beside child" + finally: + inside.rmdir() + + # Volume GUID paths are returned as provider-qualified paths by PowerShell. + # Staging to a sibling must work, while the underlying package is still protected. + volume = ctypes.create_unicode_buffer(1024) + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.GetVolumeNameForVolumeMountPointW.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32] + kernel.GetVolumeNameForVolumeMountPointW.restype = ctypes.c_int + if kernel.GetVolumeNameForVolumeMountPointW(package.anchor, volume, len(volume)): + volume_package = volume.value + str(package)[len(package.anchor):] + nested = package / "volume-nested" + result = call(powershell, volume_package, exe.name, nested) + assert result.returncode != 0 and "separate from PackageDir" in result.stderr, result.stdout + result.stderr + assert not nested.exists() + safe = root / "volume-safe" + result = call(powershell, volume_package, exe.name, safe) + assert result.returncode == 0, result.stdout + result.stderr + assert (safe / exe.name).read_bytes() == original[exe.name] + else: + print("volume GUID control skipped: temporary volume has no GUID path") print("safe startup staging: isolated executable/DLL copy, package preservation and overwrite/path guards passed") diff --git a/tests/startup_storage_failure_counts.cpp b/tests/startup_storage_failure_counts.cpp index c80a4988aa..4c8b051a6b 100644 --- a/tests/startup_storage_failure_counts.cpp +++ b/tests/startup_storage_failure_counts.cpp @@ -307,7 +307,7 @@ int main(int argc, char** argv) std::snprintf(what, sizeof what, "the causes add up to %ld, failed total %ld, expected %ld", sum, requests_failed, expected_failed); ok = expect(sum == requests_failed && requests_failed == expected_failed, what) && ok; - std::snprintf(what, sizeof what, "done=%ld inflated=%ld, expected 1 and 1", requests_done, requests_compressed); + std::snprintf(what, sizeof what, "raw=%ld inflated=%ld, expected 1 and 1", requests_done, requests_compressed); ok = expect(requests_done == 1 && requests_compressed == 1, what) && ok; // The heartbeat's line, through the stand-in's formatter, against text written out here. @@ -351,6 +351,75 @@ int main(int argc, char** argv) ok = expect(outcome == "read failed", what) && ok; } + // The status-line counters (#2816). This mixed run finished one raw copy and one zlib request and + // failed the rest: completed is raw + inflated + bcpack-blank, a failure is not in it, and the + // "inflated=%ld failed=%ld" text that tools/startup/live_view.py parses is unchanged. + // The heartbeat check above added one more failure (count_failure(C::other)) after the totals were sampled. + const LONG failed_now = expected_failed + 1; + char counts[160], want_counts[160]; + format_request_counts(counts, sizeof counts, requests_done, requests_compressed, requests_failed, + requests_bcpack_blank); + std::snprintf(want_counts, sizeof want_counts, "raw=1 inflated=1 failed=%ld bcpack-blank=0 completed=2", failed_now); + std::snprintf(what, sizeof what, "mixed run counts \"%s\", expected \"%s\"", counts, want_counts); + ok = expect(std::strcmp(counts, want_counts) == 0, what) && ok; + char parsed_tail[64]; + std::snprintf(parsed_tail, sizeof parsed_tail, "inflated=1 failed=%ld", failed_now); + ok = expect(std::strstr(counts, parsed_tail) != nullptr, "the inflated=N failed=N text live_view.py parses changed") && ok; + + // Every term of completed is non-zero here, so a total that leaves out raw, inflated or bcpack-blank (or adds + // failed) is caught: the mixed run above has no BCPack-blank request. + format_request_counts(counts, sizeof counts, 1, 2, 3, 4); + ok = expect(std::strcmp(counts, "raw=1 inflated=2 failed=3 bcpack-blank=4 completed=7") == 0, + "completed is not raw + inflated + bcpack-blank (1, 2, 3, 4 must give completed=7)") && ok; + + // A run whose requests are all zlib: nothing is counted raw, yet completed equals the finished requests, + // so the status line no longer reads as if storage were stuck. + { + requests_done = requests_compressed = requests_failed = requests_bcpack_blank = 0; + constexpr unsigned zlib_requests = 3; + void *zlib_status_ptr = nullptr, *zlib_queue_ptr = nullptr; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, zlib_requests, "Zlib", nullptr, &zlib_status_ptr) != 0 || + reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, description, nullptr, &zlib_queue_ptr) != 0) { + std::fprintf(stderr, "cannot create the zlib-only queue\n"); + return 1; + } + auto* zlib_status = static_cast<Object*>(zlib_status_ptr); + auto* zlib_queue = static_cast<Object*>(zlib_queue_ptr); + std::vector<unsigned char> zlib_destination[zlib_requests]; + for (unsigned i = 0; i < zlib_requests; ++i) { + zlib_destination[i].assign(piece, 0xA5); + alignas(8) unsigned char request[0x48] = {}; + *reinterpret_cast<u64*>(request + 0x00) = 1; + *reinterpret_cast<unsigned char**>(request + 0x08) = zlib_destination[i].data(); + *reinterpret_cast<unsigned*>(request + 0x18) = piece; + *reinterpret_cast<void**>(request + 0x20) = file_ptr; + *reinterpret_cast<u64*>(request + 0x28) = zlib_offset; + *reinterpret_cast<unsigned*>(request + 0x30) = stream_size; + *reinterpret_cast<unsigned*>(request + 0x38) = piece; + reinterpret_cast<EnqueueRequestFn>(zlib_queue->vtable[3])(zlib_queue, request); + reinterpret_cast<EnqueueStatusFn>(zlib_queue->vtable[4])(zlib_queue, zlib_status, i); + } + Fence zlib_fence{fence_vtable, 0}; + reinterpret_cast<EnqueueSignalFn>(zlib_queue->vtable[5])(zlib_queue, &zlib_fence, 1); + reinterpret_cast<SubmitFn>(zlib_queue->vtable[6])(zlib_queue); + const DWORD zlib_start = GetTickCount(); + while (!zlib_fence.signaled && GetTickCount() - zlib_start < completion_timeout_ms) Sleep(2); + ok = expect(zlib_fence.signaled, "the fence after the zlib-only requests was never signaled") && ok; + unsigned finished = 0; + for (unsigned i = 0; i < zlib_requests; ++i) + finished += reinterpret_cast<IsCompleteFn>(zlib_status->vtable[3])(zlib_status, i) ? 1 : 0; + format_request_counts(counts, sizeof counts, requests_done, requests_compressed, requests_failed, + requests_bcpack_blank); + std::snprintf(want_counts, sizeof want_counts, "raw=0 inflated=%u failed=0 bcpack-blank=0 completed=%u", finished, finished); + std::snprintf(what, sizeof what, "zlib-only run: %u finished, counts \"%s\", expected \"%s\"", finished, counts, want_counts); + ok = expect(finished == zlib_requests && std::strcmp(counts, want_counts) == 0, what) && ok; + const std::string status_text = read_text(log_path); + ok = expect(status_text.find("(requests raw=") != std::string::npos && + status_text.find(" completed=") != std::string::npos && + status_text.find("requests done=") == std::string::npos, + "the EnqueueStatus line does not carry raw= and completed= (or still says done=)") && ok; + } + ok = check_edge_ranges() && ok; reinterpret_cast<CloseFileFn>(static_cast<Object*>(file_ptr)->vtable[3])(file_ptr); diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index e7dcab0a22..092b6e91e0 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -7,6 +7,7 @@ #include <cstring> #include <wrl/client.h> +#include <algorithm> #include <array> #include <fstream> #include <iterator> @@ -15,9 +16,18 @@ #include "startup_stream_draw.h" #include "startup_stream_setup.h" +#include "startup_slot67_indirect.h" + +#ifdef OFFSCREEN_AGILITY_620 +extern "C" { +__declspec(dllexport) extern const UINT D3D12SDKVersion = 620; +__declspec(dllexport) const char* D3D12SDKPath = ".\\D3D12\\"; +} +#endif using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_compute_census(); // A slot-55 patch is a tagged union with room for the full eight-target blend state. struct Patch { UINT tag; D3D12_BLEND_DESC blend; }; @@ -161,7 +171,760 @@ static void* desktop_pipeline(void* device) // data-pointer valid, with the first data qword pointing at state block A // code-zero, data-zero, no-root, code-unreadable, code-past-end, data-unreadable, state-unreadable, // stateb-unreadable, desc-unreadable +// dispatch, dispatch-swapped, dispatch-none, dispatch-records32, dispatch-sampled, dispatch-sampled-unbound, dispatch-sampled-2x1, dispatch-sampled-depth, dispatch-heap, +// dispatch-heap-outside, dispatch-heap-word*, dispatch-input-*, dispatch-output-*: one creation, then dispatch_slot67 below +// texture-store and texture-array modes: one creation, then texture_slot67 below // The unreadable cases point at a PAGE_NOACCESS page; code-past-end ends the code on the last byte before one. +static void* slot67_pipeline; +static void* slot67_root; +static void* slot67_other_root; // a second root signature object, for the root-change controls + +// A console resource through device slot 127 (CreateCommittedResource3). +static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) +{ + using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, const GUID*, void**); + const D3D12_HEAP_PROPERTIES heap{type}; + void* resource = nullptr; + const HRESULT hr = reinterpret_cast<Create>((*static_cast<void***>(device))[127])( + device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, &__uuidof(ID3D12Resource), &resource); + return SUCCEEDED(hr) ? resource : nullptr; +} + +// Case A of startup_gfx2hlsl_compute_check.py through the stand-in's own list: two root constants (word 0 by slot +// 37, word 1 by slot 39; a slot 40 call with other words in between must not reach them), a +// table (slot 35) of two 16-byte hardware buffer descriptors written into the title heap's memory, and Dispatch +// (slot 14) of 3x2x2 groups with the slot 67 placeholder bound. Input and output are placed buffers 64 KiB apart +// in one allocation, so both alias this process's memory and the result is read from that memory after the queue's +// fence. dispatch-swapped exchanges the two descriptors (the output then names the buffer without unordered +// access); dispatch-none records everything but the Dispatch. The 320 output words go to X2W_TEST_DISPATCH_OUT. +// dispatch-records32 writes the table as 32-byte records, the layout the C++ compiler reads a table in +// (startup_compute_dispatch_native_check.py): the output's descriptor at byte 32 and none at byte 16. +// dispatch-sampled adds what the sampling variant of the case reads: a committed 1x1 RGBA8 texture filled by +// CopyTextureRegion (list slot 16) and a shader resource view of it (device slot 18) whose token the stand-in +// writes at table byte 64. dispatch-sampled-unbound creates no view, so that entry holds no token. +// dispatch-sampled-2x1 makes the texture 2x1 with red 0 in its left texel and 1.0 in its right one. +// dispatch-sampled-depth makes it 2x1 R32_FLOAT, a format a comparison sample reads: 1.0 left, 2.5 right. +// dispatch-heap runs the program of startup_gfx2hlsl_heap_record_check.py: a third root constant, 2, indexes the +// 32-byte heap record that holds the input descriptor (heap byte 64). Heap bytes 0 and 32 hold the output's +// descriptor, so an index that is ignored or scaled by 16 names a buffer the dispatch refuses as an input. +// dispatch-heap-outside sets the constant to 0x07ffffff, whose record is past any heap. +// dispatch-heap-word runs the program of startup_gfx2hlsl_heap_word_check.py: the constant is 1 and picks the word +// of the upload buffer at table byte 96 that holds the index, 2. dispatch-heap-word-outside makes that word +// 0x07ffffff, dispatch-heap-word-past ends the buffer at that word, and dispatch-heap-word-placed names the placed +// input buffer instead of upload memory. +// Controls on the recorded state: dispatch-missing-word leaves out the slot 37 call; dispatch-root-changed sets +// another compute root and the first one again after the constants, dispatch-same-root sets the same root again; +// dispatch-reset closes and resets the list after the constants; dispatch-wrong-root records under the other +// root; dispatch-same-buffer names the output buffer as the input too. +// Input descriptors the dispatch refuses, one reason each: dispatch-input-empty has zero records (a nonzero base, +// word 3 zero), dispatch-input-past ends 16 bytes past the input buffer, dispatch-input-unplaced names memory between +// the two buffers, dispatch-input-copied a third buffer placed there at an offset the desktop cannot alias, and +// dispatch-input-null (all four words zero, an unbound buffer) is not refused and reads zeros; +// dispatch-input-token writes the token of a texture view where the input descriptor was. +// Output descriptors the dispatch refuses, one reason each: dispatch-output-texture-token, -unplaced and -copied do +// to the output what dispatch-input-token, -unplaced and -copied do to the input, dispatch-output-unaligned starts +// the output 8 bytes into its buffer and dispatch-output-state places the output buffer in the unordered access state. +// For any mode, X2W_TEST_DISPATCH_IN names 1280 bytes that replace the input words, and X2W_TEST_DISPATCH_FIELDS +// names six words that replace, for the input and then the output descriptor, the stride (word 1 bits 16-31), the +// record count (word 2) and word 3, which are otherwise 4, 320 and 0. +// (The long case puts its input at 0x28000, not at a 64 KiB multiple like 0x20000: there the placed buffer would alias title memory +// and the input would be read in place, never snapshotted, which is how an earlier version of this case passed without a snapshot.) +// dispatch-input-snapshot-long: dispatch-input-snapshot with an 8 MiB input range (the descriptor declares 2M records; the program +// reads the first 320 words) dispatched in 48 frames, 384 MiB of snapshots in all, with the queue completed between frames. The +// snapshot pool holds 128 MiB, so every frame after the sixteenth reuses chunks the GPU is done with; a pool that is not recycled +// refuses them. Every frame must translate and give the first frame's words. +// Table controls bind away from the heap start or change the root/view heap after slot 35 without rebinding. +static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) +{ + constexpr UINT words = 320; + const bool keep_closed = mode == "dispatch-input-snapshot-long-keep"; + const bool long_run = keep_closed || mode == "dispatch-input-snapshot-long"; + constexpr UINT long_records = 2u << 20, long_frames = 48; + const bool shared_uav = mode == "dispatch-read-write-uav"; + const bool typed_output_offset = mode == "dispatch-records32-output-offset"; + const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const bool heap_waterfall = mode.rfind("dispatch-heap-waterfall", 0) == 0; + const bool pixel = mode.rfind("dispatch-indirect-pixel-", 0) == 0; + const bool write_zero = mode == "dispatch-indirect-pixel-zero"; + const bool root_srv = mode.rfind("dispatch-root-srv", 0) == 0; + const UINT groups = mode == "dispatch-indirect-zero" || write_zero || mode == "dispatch-indirect-pixel-omit" ? 0u : + mode == "dispatch-indirect-2" || mode == "dispatch-indirect-pixel-2" ? 2u : 5u; + const SIZE_T mem_bytes = heap_waterfall ? 0x60000 : long_run ? 0x28000 + long_records * sizeof(UINT) : + (indirect || root_srv) ? 0x30000 : 0x20000; + auto* memory = static_cast<UINT*>(VirtualAlloc(nullptr, mem_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!memory) return 70; + UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; + UINT* const buffer2 = memory + 0x20000 / sizeof(UINT); + for (UINT i = 0; i < words; ++i) { + buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; + buffers[1][i] = 0xc5c5c5c5u; + } + UINT fields[2][3] = {{4, long_run ? long_records : words, 0}, {4, words, 0}}; + const auto from_file = [](const char* variable, void* data, std::streamsize bytes) { + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA(variable, path, MAX_PATH); + return !n || (n < MAX_PATH && std::ifstream(path, std::ios::binary).read(static_cast<char*>(data), bytes).gcount() == bytes); + }; + if (!from_file("X2W_TEST_DISPATCH_IN", buffers[0], words * sizeof(UINT)) || + !from_file("X2W_TEST_DISPATCH_FIELDS", fields, sizeof(fields))) return 2; + UINT input[words]; + std::memcpy(input, buffers[0], sizeof(input)); + if (shared_uav) std::memcpy(buffers[1], input, sizeof(input)); + const auto word = [](const void* value) { return reinterpret_cast<StreamWord>(value); }; + void* placed[2]{}; + UINT descriptors[2][4]{}; + for (int i = 0; i < 2; ++i) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, i ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE}; + const auto state = i && mode == "dispatch-output-state" ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_COMMON; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(buffers[i]), word(&desc), state, 0, + word(&__uuidof(ID3D12Resource)), word(&placed[i]))))) return 71; + const UINT64 address = reinterpret_cast<UINT64>(buffers[mode == "dispatch-same-buffer" ? 1 : i]); + const UINT view[4] = {static_cast<UINT>(address), static_cast<UINT>(address >> 32) | fields[i][0] << 16, fields[i][1], fields[i][2]}; + std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); + } + UINT record_descs[4][4]{}; + if (heap_waterfall) { + for (UINT rec = 0; rec < 4; ++rec) { + UINT* const rec_buf = memory + (0x20000 + rec * 0x10000) / sizeof(UINT); + for (UINT i = 0; i < words; ++i) rec_buf[i] = 1000u * (rec + 1u) + 17u * i; + const D3D12_RESOURCE_DESC rdesc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* rec_res = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(rec_buf), word(&rdesc), D3D12_RESOURCE_STATE_COMMON, + 0, word(&__uuidof(ID3D12Resource)), word(&rec_res))))) return 71; + const UINT64 address = reinterpret_cast<UINT64>(rec_buf); + const UINT view[4] = {static_cast<UINT>(address), static_cast<UINT>(address >> 32) | (4u << 16), words, 0}; + std::memcpy(record_descs[rec], view, sizeof(view)); + } + } + const UINT64 between = reinterpret_cast<UINT64>(memory) + (long_run ? 0x28000 : 0x8000); + void* placed2 = nullptr; + if (root_srv) { + for (UINT i = 0; i < words; ++i) buffer2[i] = 0x3c6ef372u + i * 0x19660du; + for (UINT i = 0; i < 64; ++i) { + buffers[0][words + i] = 0xdeadbeefu + i; + buffer2[words + i] = 0xfeedfaceu + i; + } + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(buffer2), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&placed2))))) return 71; + } + // dispatch-input-snapshot: the input words are written into the memory the third buffer is placed over, so they + // exist only in title memory (the desktop copy of a buffer that does not alias holds zeros); dispatch-input-copied + // leaves that memory zero. + if (mode == "dispatch-input-snapshot" || long_run) std::memcpy(reinterpret_cast<void*>(between), input, sizeof(input)); + if (mode == "dispatch-input-copied" || mode == "dispatch-input-snapshot" || long_run || mode == "dispatch-root-srv-copied" || + mode == "dispatch-output-copied") { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, long_run ? long_records * sizeof(UINT) : words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* copied = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, word(reinterpret_cast<void*>(between)), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&copied))))) return 71; + } + if (mode == "dispatch-input-empty") { + const UINT view[4] = {0x32c, 0, 0, 0}; + std::memcpy(descriptors[0], view, sizeof(view)); + } else if (mode == "dispatch-input-null") { + std::memset(descriptors[0], 0, sizeof(descriptors[0])); // an unbound buffer: all four words zero + } else if (mode == "dispatch-input-past") { + descriptors[0][2] = words + 4; + } else if (mode == "dispatch-input-unplaced" || mode == "dispatch-input-copied" || mode == "dispatch-input-snapshot" || long_run) { + descriptors[0][0] = static_cast<UINT>(between); + descriptors[0][1] = static_cast<UINT>(between >> 32) | 4u << 16; + } else if (mode == "dispatch-output-unplaced" || mode == "dispatch-output-copied") { + descriptors[1][0] = static_cast<UINT>(between); + descriptors[1][1] = static_cast<UINT>(between >> 32) | 4u << 16; + } else if (mode == "dispatch-output-unaligned") { + descriptors[1][0] += 8; // still inside the buffer: 318 records + descriptors[1][2] = words - 2; + } else if (typed_output_offset) { + const UINT64 address = reinterpret_cast<UINT64>(buffers[1]) + 8; + descriptors[1][0] = static_cast<UINT>(address); + descriptors[1][1] = static_cast<UINT>(address >> 32) | fields[1][0] << 16; + } + const bool heap_short = mode == "dispatch-heap-waterfall-short"; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, heap_waterfall ? (heap_short ? 3u : 5u) : 4u, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + // dispatch-sampled-compute records the same calls on a compute list and queue. + const D3D12_COMMAND_LIST_TYPE list_type = mode == "dispatch-sampled-compute" ? D3D12_COMMAND_LIST_TYPE_COMPUTE : D3D12_COMMAND_LIST_TYPE_DIRECT; + const D3D12_COMMAND_QUEUE_DESC queue_desc{list_type}; + const UINT list_desc[]{static_cast<UINT>(list_type), 2, 1, 0}; + if (FAILED(static_cast<HRESULT>(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast<HRESULT>(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast<HRESULT>(invoke(device, 9, list_type, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast<HRESULT>(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast<HRESULT>(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu) return 73; + if (mode == "dispatch-indirect-output-alias") { + const UINT64 address = reinterpret_cast<UINT64>(memory) + 0x20000; + const UINT alias[4] = {static_cast<UINT>(address), static_cast<UINT>(address >> 32) | (4u << 16), 5, 0}; + std::memcpy(descriptors[1], alias, sizeof(alias)); + } + const bool change_table_root = mode == "dispatch-table-root-changed"; + const bool change_table_heap = mode == "dispatch-table-heap-changed"; + StreamWord table_gpu = gpu; + if (mode == "dispatch-table-offset") { + const UINT increment = static_cast<UINT>(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (increment < sizeof(descriptors[0])) return 73; + const StreamWord offset = StreamWord{2} * increment; + // The heap starts with the wrong pair, but both records are well-formed. The correct pair starts at index 2. + std::memcpy(reinterpret_cast<void*>(cpu), descriptors[1], sizeof(descriptors[1])); + std::memcpy(reinterpret_cast<void*>(cpu + sizeof(descriptors[1])), descriptors[0], sizeof(descriptors[0])); + std::memcpy(reinterpret_cast<void*>(cpu + offset), descriptors, sizeof(descriptors)); + table_gpu += offset; + } else { + std::memcpy(reinterpret_cast<void*>(cpu), descriptors, sizeof(descriptors)); + } + if (mode == "dispatch-scalar-window" || mode == "dispatch-scalar-window-short") { + // An unplaced, three-record view at table byte 64. Only this + // descriptor names the scalar input; byte 0 still names a decoy. + std::memcpy(reinterpret_cast<void*>(between), buffers[0], 48); + // Point the placed decoy four words further into the source so that + // taking table byte 0 instead of byte 64 produces a distinct value. + const UINT64 decoy = reinterpret_cast<UINT64>(buffers[0] + 4); + const UINT decoy_view[]{static_cast<UINT>(decoy), static_cast<UINT>(decoy >> 32) | (16u << 16), 3, 0x2403c}; + std::memcpy(reinterpret_cast<void*>(cpu), decoy_view, sizeof(decoy_view)); + const UINT window[]{static_cast<UINT>(between), static_cast<UINT>(between >> 32) | (16u << 16), + mode == "dispatch-scalar-window-short" ? 2u : 3u, 0x2403c}; + std::memcpy(reinterpret_cast<void*>(cpu + 64), window, sizeof(window)); + std::memcpy(reinterpret_cast<void*>(cpu + 32), descriptors[1], sizeof(descriptors[1])); + } + if (mode == "dispatch-records32" || typed_output_offset || shared_uav) { // output at byte 32, none at byte 16 + std::memset(reinterpret_cast<void*>(cpu + sizeof(descriptors[0])), 0, sizeof(descriptors[1])); + std::memcpy(reinterpret_cast<void*>(cpu + 32), descriptors[1], sizeof(descriptors[1])); + } + void* other_heap = nullptr; + if (change_table_heap && + (FAILED(static_cast<HRESULT>(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), + word(&other_heap)))) || !other_heap || other_heap == heap)) return 72; + void* copied_token_output = nullptr; + if (mode.rfind("dispatch-uav-token-", 0) == 0) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.Buffer.FirstElement = 4; + view.Buffer.NumElements = words - 8; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + if (mode == "dispatch-uav-token-structured") { + view.Format = DXGI_FORMAT_UNKNOWN; + view.Buffer.StructureByteStride = 8; + view.Buffer.FirstElement /= 2; + view.Buffer.NumElements /= 2; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + } + if (mode == "dispatch-uav-token-typed") { + view.Format = DXGI_FORMAT_R32_UINT; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + } + void* output = placed[1]; + if (mode == "dispatch-uav-token-copied") { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + if (FAILED(static_cast<HRESULT>(invoke(device, 133, between, word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&output))))) return 71; + } + if (mode == "dispatch-uav-token-copied") copied_token_output = output; + invoke(device, 19, word(output), 0, word(&view), cpu + 32); + if (mode == "dispatch-uav-token-wrong-slot") + reinterpret_cast<UINT*>(cpu + 32)[2] = 18; + } + const bool heap_record = mode.rfind("dispatch-heap", 0) == 0 && !heap_waterfall; + if (heap_record) + for (const UINT at : {0u, 32u, 64u}) + std::memcpy(reinterpret_cast<void*>(cpu + at), descriptors[at != 64], sizeof(descriptors[0])); + if (heap_waterfall) { + if (heap_short) { + std::memcpy(reinterpret_cast<void*>(cpu + 32), record_descs[1], sizeof(record_descs[1])); + std::memcpy(reinterpret_cast<void*>(cpu + 64), record_descs[2], sizeof(record_descs[2])); + } else { + for (UINT rec = 0; rec < 4; ++rec) + std::memcpy(reinterpret_cast<void*>(cpu + rec * 32u), record_descs[rec], sizeof(record_descs[rec])); + std::memcpy(reinterpret_cast<void*>(cpu + 128), descriptors, sizeof(descriptors)); + } + } + const bool heap_word = mode.rfind("dispatch-heap-word", 0) == 0; + UINT active_lanes = 4u; + if (heap_waterfall) { + char buf[32]; + const DWORD len = GetEnvironmentVariableA("X2W_TEST_DISPATCH_ACTIVE", buf, sizeof(buf)); + if (len && len < sizeof(buf)) active_lanes = static_cast<UINT>(std::strtoul(buf, nullptr, 10)); + } + const UINT constants[3] = {heap_waterfall ? active_lanes : 0x01234567u, 0x9e3779b9u, + mode == "dispatch-heap-outside" ? 0x07ffffffu : heap_word ? 1u : 2u}; + const UINT graphics[2] = {0xdeadbeef, 0xfeedface}; + const auto bind = [&] { + invoke(list, 32, 1, word(&heap)); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(mode == "dispatch-wrong-root" ? slot67_other_root : slot67_root)); + }; + if (FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + const auto submit = [&](UINT64 value) -> int { + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, word(fence), value)))) return 76; + // Render mode publishes the guest fence value after desktop queue completion. + const ULONGLONG deadline = GetTickCount64() + 10000; + for (;;) { + const auto completed = invoke(fence, 8); + const HRESULT removed = static_cast<HRESULT>(invoke(device, 37)); + if (completed == ~UINT64{0} || FAILED(removed)) { + std::fprintf(stderr, "slot 67 Dispatch fence: device removed (0x%08lx)\n", static_cast<unsigned long>(removed)); + return 78; + } + if (completed == value) break; + if (GetTickCount64() >= deadline) { + std::fputs("slot 67 Dispatch fence: timed out\n", stderr); + return 78; + } + Sleep(1); + } + return 0; + }; + Slot67Indirect record; + if (indirect) record.prepare(adapter, device, list, memory + 0x20000 / sizeof(UINT), groups, write_zero, + pixel ? queue : nullptr, pixel ? placed[1] : nullptr); + if (pixel) { + if (const int rc = submit(1)) return rc; + std::printf("guest queue=%p writer fence=1 completed\n", queue); + if (!record.check_record(groups, write_zero)) return 80; + if (FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + } + bind(); + if (mode.rfind("dispatch-sampled", 0) == 0 || mode == "dispatch-input-token" || mode == "dispatch-output-texture-token") { + const bool depth = mode == "dispatch-sampled-depth"; + const UINT width = depth || mode == "dispatch-sampled-2x1" ? 2 : 1; + const DXGI_FORMAT format = depth ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8G8B8A8_UNORM; + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, 1, 1, 1, format, {1, 0}}; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!texture || !upload || FAILED(static_cast<HRESULT>(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + // The program reads red: 1.0f. The 2x1 texture's left texel has red 0, so only a linear filter that wraps + // reads 0.5 at the left edge (point or clamp read 0). + unsigned char rgba[8] = {255, 64, 128, 32, 255, 64, 128, 32}; + if (width == 2) rgba[0] = 0; + const float depths[2] = {1.0f, 2.5f}; + std::memcpy(texel, depth ? static_cast<const void*>(depths) : rgba, sizeof(rgba)); + invoke(upload, 9, 0, 0); + D3D12_TEXTURE_COPY_LOCATION image{static_cast<ID3D12Resource*>(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION source{static_cast<ID3D12Resource*>(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {0, {format, width, 1, 1, 256}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + D3D12_SHADER_RESOURCE_VIEW_DESC view{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MipLevels = 1; + if (mode != "dispatch-sampled-unbound") invoke(device, 18, word(texture), word(&view), cpu + (mode == "dispatch-input-token" ? 0 : 64)); + // Byte 16 is not a descriptor of the heap: the token's words are copied there, as a title copies descriptors. + if (mode == "dispatch-output-texture-token") std::memcpy(reinterpret_cast<void*>(cpu + 16), reinterpret_cast<const void*>(cpu + 64), 16); + } + if (mode.rfind("dispatch-texdim-", 0) == 0) { + // dispatch-texdim-<1d|2da|3d>[-mismatch|-undescribed|-clamped]: the sampled input is a described R32_FLOAT texture + // of that dimension in the SRV at table byte 64, texel (x + y * 4 + slice * 16) holding 0.25 * (index + 1): + // 1d is 8 texels wide, 2da is 4x4 with six slices (the view starts at slice 1 and spans four), 3d is 4x4x4. + // Each subresource is uploaded by its own copy. -mismatch views a plain 2D texture instead (a view dimension + // that is not the manifest's), -undescribed creates the view without a description, -clamped sets + // ResourceMinLODClamp 1.0 (a valid desktop view that is not a view of the texels as stored; a view outside the + // texture would remove the device when it is created). + const std::string rest = mode.substr(16); + const std::string kind = rest.substr(0, rest.find('-')); + const std::string control = rest.find('-') == std::string::npos ? "" : rest.substr(rest.find('-') + 1); + const bool one = kind == "1d", array = kind == "2da", volume = kind == "3d"; + if (!one && !array && !volume) return 2; + const bool plain = control == "mismatch"; + constexpr DXGI_FORMAT format = DXGI_FORMAT_R32_FLOAT; + const UINT width = one && !plain ? 8 : 4, height = one && !plain ? 1 : 4; + const UINT depth = plain || one ? 1 : array ? 6 : 4; + const D3D12_RESOURCE_DIMENSION dimension = plain || array ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : + one ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const D3D12_RESOURCE_DESC texture_desc{dimension, 0, width, height, static_cast<UINT16>(depth), 1, format, {1, 0}}; + constexpr UINT pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT, slice_bytes = pitch * 4; + const D3D12_RESOURCE_DESC upload_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 8192, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, upload_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* texel = nullptr; + if (!texture || !upload || FAILED(static_cast<HRESULT>(invoke(upload, 8, 0, 0, word(&texel)))) || !texel) return 80; + std::memset(texel, 0, 8192); + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const float value = 0.25f * static_cast<float>(x + y * 4 + z * 16 + 1); + std::memcpy(static_cast<char*>(texel) + z * slice_bytes + y * pitch + x * 4, &value, sizeof(value)); + } + invoke(upload, 9, 0, 0); + // A 3D texture is one subresource whose footprint spans its depth; a 2D one has a subresource per slice. + const UINT copies = volume ? 1 : depth; + for (UINT i = 0; i < copies; ++i) { + D3D12_TEXTURE_COPY_LOCATION image{static_cast<ID3D12Resource*>(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + image.SubresourceIndex = i; + D3D12_TEXTURE_COPY_LOCATION source{static_cast<ID3D12Resource*>(upload), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + source.PlacedFootprint = {UINT64{i} * slice_bytes, {format, width, height, volume ? depth : 1, pitch}}; + invoke(list, 16, word(&image), 0, 0, 0, word(&source), 0); + } + D3D12_SHADER_RESOURCE_VIEW_DESC view{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + const float clamp = control == "clamped" ? 1.0f : 0.0f; + if (plain) view.Texture2D.MipLevels = 1; + else if (one) { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE1D; + view.Texture1D = {0, 1, clamp}; + } else if (array) { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray = {0, 1, 1, 4, 0, clamp}; + } else { + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + view.Texture3D = {0, 1, clamp}; + } + invoke(device, 18, word(texture), control == "undescribed" ? 0 : word(&view), cpu + 64); + } + if (mode == "dispatch-input-memory-view") { + // The input is a buffer view (device slot 70) of memory no buffer is placed over, 16 bytes in; its token + // replaces the input descriptor and the words are written after the view exists. + auto* const unplaced = static_cast<UINT*>(VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!unplaced) return 70; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 0x10000, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + struct { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + UINT64 address; + } input{{DXGI_FORMAT_UNKNOWN, D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}, + reinterpret_cast<UINT64>(unplaced)}; + input.view.Buffer = {4, words, sizeof(UINT), D3D12_BUFFER_SRV_FLAG_NONE}; + invoke(device, 70, word(&desc), word(&input), cpu); + // The token is wider than a table descriptor: the output descriptor after it is written again. + std::memcpy(reinterpret_cast<void*>(cpu + sizeof(descriptors[0])), descriptors[1], sizeof(descriptors[1])); + std::memcpy(unplaced + 4, buffers[0], words * sizeof(UINT)); + } + if (root_srv && mode != "dispatch-root-srv-unset") { + UINT64 addr0 = reinterpret_cast<UINT64>(buffers[0]); + UINT64 addr1 = reinterpret_cast<UINT64>(buffer2); + if (mode == "dispatch-root-srv-offset") { + addr0 += 16; + addr1 += 32; + } else if (mode == "dispatch-root-srv-upload") { + auto* const up = static_cast<UINT*>(reinterpret_cast<void*>(invoke(list, 148, words * sizeof(UINT), 256))); + if (!up) return 81; + std::memcpy(up, buffers[0], words * sizeof(UINT)); + addr0 = reinterpret_cast<UINT64>(up) + 16; + } else if (mode == "dispatch-root-srv-null") { + addr0 = 0; + } else if (mode == "dispatch-root-srv-unaligned") { + addr0 += 2; + } else if (mode == "dispatch-root-srv-unaligned-16") { + addr0 += 4; + } else if (mode == "dispatch-root-srv-unmapped" || mode == "dispatch-root-srv-copied") { + addr0 = between; + } else if (mode == "dispatch-root-srv-same-buffer") { + addr0 = reinterpret_cast<UINT64>(buffers[1]); + } + invoke(list, 43, 2, addr0); + if (mode != "dispatch-root-srv-unset-second") invoke(list, 43, 3, addr1); + } + if (mode == "dispatch-root-srv-root-changed") { + invoke(list, 33, word(slot67_other_root)); + invoke(list, 33, word(slot67_root)); + } else if (mode == "dispatch-root-srv-same-root") { + invoke(list, 33, word(slot67_root)); + } else if (mode == "dispatch-root-srv-reset") { + if (FAILED(static_cast<HRESULT>(invoke(list, 9))) || FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + bind(); + } + if (mode != "dispatch-missing-word") invoke(list, 37, 0, constants[0], 0); + invoke(list, 40, 0, 2, word(graphics), 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + if (mode == "dispatch-root-changed") invoke(list, 33, word(slot67_other_root)); + if (mode == "dispatch-root-changed" || mode == "dispatch-same-root") invoke(list, 33, word(slot67_root)); + if (mode == "dispatch-reset") { + if (FAILED(static_cast<HRESULT>(invoke(list, 9))) || FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + bind(); + } + if (heap_record || root_srv || heap_waterfall) invoke(list, 39, 0, 1, word(&constants[2]), 2); + if (heap_word) { + // The index buffer of table byte 96, in this recording's upload memory (list slot 148). Byte 288 + 336 * 1 + // holds the index, 2; every other word names record 0 or 1, the output's descriptor. + constexpr UINT bytes = 0x400, at = 0x270; + auto* const index = static_cast<UINT*>(reinterpret_cast<void*>(invoke(list, 148, bytes, 256))); + if (!index) return 81; + std::memset(index, 0, bytes); + index[0x120 / 4] = index[0x150 / 4] = 1; + index[at / 4] = mode == "dispatch-heap-word-outside" ? 0x07ffffffu : 2u; + const UINT64 address = reinterpret_cast<UINT64>(mode == "dispatch-heap-word-placed" ? buffers[0] : index); + const UINT view[4] = {static_cast<UINT>(address), static_cast<UINT>(address >> 32), + mode == "dispatch-heap-word-past" ? at : mode == "dispatch-heap-word-placed" ? words * 4 : bytes, 0}; + std::memcpy(reinterpret_cast<void*>(cpu + 96), view, sizeof(view)); + } + invoke(list, 35, 1, table_gpu + (heap_waterfall && !heap_short ? 128u : 0u)); + if (change_table_root) { + invoke(list, 33, word(slot67_other_root)); + invoke(list, 33, word(slot67_root)); + } + if (change_table_heap) invoke(list, 32, 1, word(&other_heap)); + if (change_table_root || change_table_heap) { + // Give Dispatch the expected entry values without rebinding slot 35. + invoke(list, 37, 0, constants[0], 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + } + if (mode == "dispatch-table-offset") invoke(list, 32, 1, word(&heap)); // same heap keeps the offset table + if (pixel) record.capture_before_consumer(adapter, device, list); + if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1, + mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); + else if (heap_waterfall) invoke(list, 14, 1, 1, 1); + else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") + invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); + else if (mode != "dispatch-none" && mode != "dispatch-root-srv-none") invoke(list, 14, 3, 2, 2); + if (copied_token_output) { + // An attempted read of the very placement whose UAV could not be made guest-visible. + invoke(list, 15, word(placed[1]), 16, word(copied_token_output), 16, 16); + } + if (const int rc = submit(pixel ? 2 : 1)) return rc; + if (pixel) { + std::printf("guest queue=%p consumer fence=2 completed\n", queue); + if (!record.check_record(groups, write_zero, true)) return 80; + const bool stale = mode == "dispatch-indirect-pixel-5-stale"; + record.draw_pixels(adapter, device, queue, placed[stale ? 0 : 1], stale); + } + if (copied_token_output) { + D3D12_RANGE range{16, 32}, none{}; + void* mapped = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(copied_token_output, 8, 0, word(&range), word(&mapped)))) || + mapped != reinterpret_cast<void*>(between)) return 83; + invoke(copied_token_output, 9, 0, word(&none)); + } + if (indirect && !pixel && !record.check_record(groups)) return 80; + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != input[i]) return 79; // the input must stay as written + if (long_run) { + UINT first[words]; + std::memcpy(first, buffers[1], sizeof(first)); + for (UINT frame = 1; frame < long_frames; ++frame) { + std::fill_n(buffers[1], words, 0xc5c5c5c5u); + if (FAILED(static_cast<HRESULT>(invoke(allocator, 8)))) return 84; + // Keep each submitted list alive and closed so only fenced submit can drop its snapshot hold. + if (keep_closed && FAILED(static_cast<HRESULT>(invoke(device, 73, word(list_desc), word(allocator), 0, + word(&__uuidof(ID3D12GraphicsCommandList)), word(&list))))) return 72; + if (FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + bind(); + invoke(list, 37, 0, constants[0], 0); + invoke(list, 40, 0, 2, word(graphics), 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + invoke(list, 35, 1, gpu); + invoke(list, 14, 3, 2, 2); + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, word(fence), frame + 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < frame + 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + if (std::memcmp(first, buffers[1], sizeof(first)) != 0) return 85; // a frame gave other words than the first + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != input[i]) return 79; + } + } + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + if (!n || n >= MAX_PATH) return 2; + std::ofstream(path, std::ios::binary).write(reinterpret_cast<const char*>(buffers[1]), words * sizeof(UINT)); + return 0; +} + +// The image store program of startup_compute_image_store_d16_check.py through the stand-in's own list: a committed +// 32x8 RGBA16_FLOAT texture (device slot 127) filled with sentinel halves by CopyTextureRegion (list slot 16), an +// unordered access view of it (device slot 19) whose token the stand-in writes into the title heap at table byte 64, +// three root constants, Dispatch of 2x1x1 groups, and the texture copied to a readback buffer whose 1024 halves go +// to X2W_TEST_DISPATCH_OUT. texture-store-none records no Dispatch; texture-store-denied creates the texture +// without unordered access, so the stand-in records its view as not created. texture-store-uint makes the texture +// and its view RGBA16_UINT; texture-store-occupied then asks for a view of a texture without unordered access at the same +// handle, which keeps the first view; texture-store-self also creates a shader resource view of the texture at table byte 0. +// texture-store-mips adds a second UAV of the same texture. The swapped mode reverses the two mip views. +static int texture_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) +{ + constexpr UINT width = 32; + const bool exact = mode.rfind("texture-exact-", 0) == 0; + const bool volume = mode == "texture-volume" || mode == "texture-volume-bad-w" || mode == "texture-exact-volume"; + const bool line = mode == "texture-line" || mode == "texture-line-bad-mip"; + const UINT first_mip = volume || line ? 1 : 0; + const UINT height = line ? 1 : 8; + const bool fp32 = volume || line || mode == "texture-array" || mode == "texture-array-2d"; + const bool atomic_uint = mode == "texture-store-atomic"; + const UINT layers = volume || mode == "texture-array" || mode == "texture-array-d16" || + mode == "texture-exact-array" ? 6 : 1; + const UINT subresources = volume ? 1 : layers; + const bool swapped = mode == "texture-store-mips-swapped"; + const bool dual = swapped || mode == "texture-store-mips"; + const UINT mips = dual ? 2 : 1; + const UINT pixel_bytes = exact ? (mode == "texture-exact-rg" ? 8 : 4) : atomic_uint ? 4 : fp32 ? 16 : 8; + const UINT pitch = (std::max)(width * pixel_bytes, UINT{D3D12_TEXTURE_DATA_PITCH_ALIGNMENT}); + const UINT slice_bytes = pitch * (height + (dual ? height / 2 : 0)), bytes = slice_bytes * layers; + const auto offset = [&](UINT layer, UINT mip) { return UINT64{layer} * slice_bytes + (mip ? pitch * height : 0); }; + const auto word = [](const void* value) { return reinterpret_cast<StreamWord>(value); }; + const auto make = [&](D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) { + return make_committed(device, type, desc, state); + }; + const DXGI_FORMAT format = mode == "texture-exact-r" ? DXGI_FORMAT_R32_FLOAT : + mode == "texture-exact-rg" ? DXGI_FORMAT_R32G32_FLOAT : + mode == "texture-exact-rgba" ? DXGI_FORMAT_R8G8B8A8_UNORM : + exact ? DXGI_FORMAT_R11G11B10_FLOAT : + atomic_uint ? DXGI_FORMAT_R32_UINT : fp32 ? DXGI_FORMAT_R32G32B32A32_FLOAT : + mode == "texture-store-uint" ? DXGI_FORMAT_R16G16B16A16_UINT : DXGI_FORMAT_R16G16B16A16_FLOAT; + if (exact) { + ComPtr<ID3D12Device> desktop; + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&desktop))) || + FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE) || + (volume && !(support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D))) { + std::printf("exact-width image store format %u unavailable\n", static_cast<unsigned>(format)); + return 77; + } + } + const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : + D3D12_RESOURCE_DIMENSION_TEXTURE2D; + const D3D12_RESOURCE_DESC texture_desc{dimension, 0, width << first_mip, line ? 1 : height << first_mip, + static_cast<UINT16>(volume ? layers << first_mip : layers), static_cast<UINT16>(first_mip + mips), format, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + mode == "texture-store-denied" ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + const D3D12_RESOURCE_DESC buffer_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* const texture = make(D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* const upload = make(D3D12_HEAP_TYPE_UPLOAD, buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ); + void* const readback = make(D3D12_HEAP_TYPE_READBACK, buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST); + void* memory = nullptr; + if (!texture || !upload || !readback || FAILED(static_cast<HRESULT>(invoke(upload, 8, 0, 0, word(&memory)))) || !memory) return 71; + if (exact) { + for (UINT layer = 0; layer < layers; ++layer) + for (UINT y = 0; y < height; ++y) { + auto* row = reinterpret_cast<UINT*>(static_cast<char*>(memory) + offset(layer, 0) + y * pitch); + const UINT row_words = width * pixel_bytes / sizeof(UINT); + for (UINT x = 0; x < row_words; ++x) + row[x] = 0x30000000u + (layer * height + y) * row_words + x; + } + } else if (atomic_uint) { + auto* words = static_cast<UINT*>(memory); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + words[y * pitch / sizeof(UINT) + x] = 0x10f00000u + y * width + x; + } else if (fp32) { + for (UINT layer = 0; layer < layers; ++layer) + for (UINT i = 0; i < slice_bytes / 4; ++i) + static_cast<UINT*>(memory)[layer * slice_bytes / 4 + i] = 0xbf000000u | (layer << 12) | i; + } else if (dual) { + for (UINT mip = 0; mip < mips; ++mip) { + const UINT row_halves = (width >> mip) * (pixel_bytes / sizeof(UINT16)); + auto* start = reinterpret_cast<UINT16*>(static_cast<char*>(memory) + offset(0, mip)); + for (UINT y = 0; y < (height >> mip); ++y) + for (UINT x = 0; x < row_halves; ++x) + start[y * pitch / sizeof(UINT16) + x] = + static_cast<UINT16>(0x5000 + 0x400 * mip + y * row_halves + x); + } + } else { + for (UINT i = 0; i < bytes / 2; ++i) static_cast<UINT16*>(memory)[i] = static_cast<UINT16>(0x5000 + i); + } + invoke(upload, 9, 0, 0); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, dual ? 5u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void *heap = nullptr, *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const UINT list_desc[]{D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast<HRESULT>(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&heap)))) || + FAILED(static_cast<HRESULT>(invoke(device, 8, word(&queue_desc), word(&__uuidof(ID3D12CommandQueue)), word(&queue)))) || + FAILED(static_cast<HRESULT>(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&__uuidof(ID3D12CommandAllocator)), word(&allocator)))) || + FAILED(static_cast<HRESULT>(invoke(device, 73, word(list_desc), word(allocator), 0, word(&__uuidof(ID3D12GraphicsCommandList)), word(&list)))) || + FAILED(static_cast<HRESULT>(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; + const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); + if (!cpu || !gpu) return 73; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{format, D3D12_UAV_DIMENSION_TEXTURE2D}; + if (volume) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + // At mip 1 the depth is six. The bad count fits only if the binder uses the base mip's depth. + view.Texture3D = {first_mip, 1, mode == "texture-volume-bad-w" ? layers : ~0u}; + } else if (line) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + view.Texture1D.MipSlice = mode == "texture-line-bad-mip" ? first_mip + 1 : first_mip; + } else if (layers > 1) { + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray = {0, 1, 4, 0}; // four selected slices, with untouched neighbors on both sides + } else { + view.Texture2D.MipSlice = swapped ? 1 : 0; + } + if (mode != "texture-store-copied") invoke(device, 19, word(texture), 0, word(&view), cpu + 64); + if (mode == "texture-store-copied") { + // The view is created at another handle and its token copied into this slot by memcpy, as a title does; a + // refused creation at this slot then keeps that copied token. + invoke(device, 19, word(texture), 0, word(&view), cpu); + std::memcpy(reinterpret_cast<void*>(cpu + 64), reinterpret_cast<void*>(cpu), 32); + D3D12_RESOURCE_DESC plain = texture_desc; + plain.Flags = D3D12_RESOURCE_FLAG_NONE; + void* const other = make(D3D12_HEAP_TYPE_DEFAULT, plain, D3D12_RESOURCE_STATE_COMMON); + if (!other) return 79; + invoke(device, 19, word(other), 0, word(&view), cpu + 64); + } else if (mode == "texture-store-occupied") { + // A second creation at the same handle, over a texture without unordered access, is refused and leaves the first view. + D3D12_RESOURCE_DESC plain = texture_desc; + plain.Flags = D3D12_RESOURCE_FLAG_NONE; + void* const other = make(D3D12_HEAP_TYPE_DEFAULT, plain, D3D12_RESOURCE_STATE_COMMON); + if (!other) return 79; + invoke(device, 19, word(other), 0, word(&view), cpu + 64); + } + if (dual) { + view.Texture2D.MipSlice = swapped ? 0 : 1; + invoke(device, 19, word(texture), 0, word(&view), cpu + 128); + } + D3D12_SHADER_RESOURCE_VIEW_DESC read{format, D3D12_SRV_DIMENSION_TEXTURE2D, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + read.Texture2D.MipLevels = 1; + if (mode == "texture-store-self") invoke(device, 18, word(texture), word(&read), cpu); + const auto transfer = [&](void* buffer, bool to_texture) { + for (UINT layer = 0; layer < subresources; ++layer) + for (UINT mip = 0; mip < mips; ++mip) { + D3D12_TEXTURE_COPY_LOCATION image{static_cast<ID3D12Resource*>(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + image.SubresourceIndex = layer * texture_desc.MipLevels + first_mip + mip; + D3D12_TEXTURE_COPY_LOCATION rows{static_cast<ID3D12Resource*>(buffer), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + rows.PlacedFootprint = {offset(layer, mip), {format, width >> mip, height >> mip, volume ? layers : 1, pitch}}; + invoke(list, 16, word(to_texture ? &image : &rows), 0, 0, 0, word(to_texture ? &rows : &image), 0); + } + }; + const UINT constants[3] = {1, 2, 3}; + if (FAILED(static_cast<HRESULT>(invoke(list, 139, word(allocator))))) return 74; + invoke(list, 32, 1, word(&heap)); + transfer(upload, true); + invoke(list, 25, word(slot67_pipeline)); + invoke(list, 33, word(slot67_root)); + invoke(list, 39, 0, 3, word(constants), 0); + invoke(list, 35, 1, gpu); + if (mode != "texture-store-none") invoke(list, 14, 2, 1, 1); + transfer(readback, false); + if (FAILED(static_cast<HRESULT>(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, word(fence), 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + x2w_d3d12_compute_census(); + char path[MAX_PATH]; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); + memory = nullptr; + if (!n || n >= MAX_PATH || FAILED(static_cast<HRESULT>(invoke(readback, 8, 0, 0, word(&memory)))) || !memory) return 2; + std::ofstream output(path, std::ios::binary); + for (UINT layer = 0; layer < layers; ++layer) + for (UINT mip = 0; mip < mips; ++mip) + for (UINT y = 0; y < (height >> mip); ++y) + output.write(static_cast<const char*>(memory) + offset(layer, mip) + y * pitch, (width >> mip) * pixel_bytes); + invoke(readback, 9, 0, 0); + return output ? 0 : 2; +} + static bool create_slot67(void* device, const char* code_path, const char* data_path, const char* state_path, const char* mode) { std::ifstream code_file(code_path, std::ios::binary), data_file(data_path, std::ios::binary), state_file(state_path, std::ios::binary); @@ -170,6 +933,7 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ std::vector<char> state{std::istreambuf_iterator<char>(state_file), {}}; if (code.empty() || data.empty() || state.empty() || !stream_root_signature()) return false; void* root = stream_root_signature(); + slot67_other_root = root; char root_path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA("X2W_TEST_COMPUTE_ROOT", root_path, MAX_PATH); if (n && n < MAX_PATH) { @@ -218,8 +982,11 @@ static bool create_slot67(void* device, const char* code_path, const char* data_ using Create = HRESULT (WINAPI*)(void*, const void*, REFIID, void**); auto create = [&](const void* d) { void* pipeline = nullptr; - return SUCCEEDED(reinterpret_cast<Create>((*static_cast<void***>(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && + const bool created = SUCCEEDED(reinterpret_cast<Create>((*static_cast<void***>(device))[67])(device, d, __uuidof(ID3D12PipelineState), &pipeline)) && pipeline; + slot67_pipeline = pipeline; + slot67_root = root; + return created; }; if (m == "order") { if (!create(desc)) return false; @@ -250,21 +1017,39 @@ int main(int argc, char** argv) std::strcmp(argv[9], "tiled") == 0}; bc7.small4k = std::strcmp(argv[9], "small4k") == 0; if (bc7.small4k ? bc7.width != 32 || bc7.height != 32 - : (bc7.width != 64 || bc7.height != 64) && (bc7.width != 81 || bc7.height != 69)) return 2; + : (bc7.width != 64 || bc7.height != 64) && (bc7.width != 81 || bc7.height != 69) && + (bc7.width != 512 || bc7.height != 256)) return 2; if (std::strncmp(argv[9], "packed:", 7) == 0) bc7.packed = argv[9] + 7; else if (bc7.small4k) {} + else if (std::strcmp(argv[9], "display64k") == 0) bc7.display64k = true; else if (!bc7.tiled && std::strcmp(argv[9], "linear") != 0) return 2; } ComPtr<IDXGIAdapter> adapter; void* device = nullptr; void* pso = nullptr; - const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; + const bool hardware = (draw && std::strcmp(argv[4], "hardware") == 0) || + GetEnvironmentVariableW(L"X2W_TEST_DISPATCH_HARDWARE", nullptr, 0) != 0; const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || - GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0; + GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV_PAIR", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // <vs> <ps> <root> slot67 <code> <data> <state> [case]: WARP device and root only, then slot-67 creations. + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) { + if (!create_slot67(device, argv[5], argv[6], argv[7], argv[8])) return 10; + if (std::strcmp(argv[8], "dispatch-retry") == 0) { + if (int rc = dispatch_slot67(adapter.Get(), device, "dispatch")) return rc; + std::puts("first slot 67 Dispatch fenced"); + std::fflush(stdout); + if (std::getchar() != '\n') return 2; + } + return dispatch_slot67(adapter.Get(), device, argv[8]); + } + if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) + return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(adapter.Get(), device, argv[8]) : 10; if ((argc == 8 || argc == 9) && std::strcmp(argv[4], "slot67") == 0) return create_slot67(device, argv[5], argv[6], argv[7], argc == 9 ? argv[8] : "valid") ? 0 : 10; if (GetEnvironmentVariableW(L"X2W_TEST_TRUNCATED_ONLY", nullptr, 0)) return 0; diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 34a837861c..d59971e41b 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -192,15 +192,128 @@ int bind_packed(ID3D12Device* desktop, void* guest, const StartupBc7Input& input bool bind_table(ID3D12Device* desktop, void* guest, void* texture, Bc7Binding& binding); +int draw_pixel_history(ID3D12Device* desktop, void* guest, void* pso, const char* pixels) +{ + constexpr UINT width = 8, height = 4; + const DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; + const float clear[] = {0, 0, 1, 1}; + const D3D12_CLEAR_VALUE optimized_clear{format, {clear[0], clear[1], clear[2], clear[3]}}; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + void* target = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 27, arg(&default_heap), D3D12_HEAP_FLAG_NONE, arg(&target_desc), + D3D12_RESOURCE_STATE_COMMON, arg(&optimized_clear), arg(&__uuidof(ID3D12Resource)), arg(&target)))) || !target) + return 21; + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + desktop->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC readback_desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + void* readback = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 27, arg(&readback_heap), D3D12_HEAP_FLAG_NONE, arg(&readback_desc), + D3D12_RESOURCE_STATE_COPY_DEST, 0, arg(&__uuidof(ID3D12Resource)), arg(&readback)))) || !readback) { + invoke(target, 2); + return 27; + } + + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } rtv_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* rtv_heap = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(guest, 14, arg(&rtv_desc), arg(&__uuidof(ID3D12DescriptorHeap)), + arg(&rtv_heap))))) { + invoke(readback, 2); + invoke(target, 2); + return 22; + } + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(rtv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC view{format, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(guest, 20, arg(target), arg(&view), rtv.ptr); + + void *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))))) return 23; + + // Plane record as queue_present resolves it: 0x48 bytes, +0x08 resource count, +0x10 pointer to wrapper array. + alignas(8) unsigned char plane[0x48]{}; + const std::uint64_t resources[1]{reinterpret_cast<std::uint64_t>(target)}; + const std::uint64_t token = 7, count_one = 1, resources_ptr = reinterpret_cast<std::uint64_t>(resources); + std::memcpy(plane + 0x00, &token, 8); + std::memcpy(plane + 0x08, &count_one, 8); + std::memcpy(plane + 0x10, &resources_ptr, 8); + + // First present advances frame_number to 1 before the dumped draw runs. + invoke(queue, 32, 1, arg(plane), 0); + + if (FAILED(static_cast<HRESULT>(invoke(allocator, 8))) || + FAILED(static_cast<HRESULT>(invoke(list, 139, arg(allocator))))) return 35; + invoke(list, 52, rtv.ptr, arg(clear)); + invoke(list, 50, 1, arg(&rtv)); + const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + const D3D12_RECT scissor{2, 1, 6, 3}; + invoke(list, 21, 1, arg(&viewport)); + invoke(list, 22, 1, arg(&scissor)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 25, arg(pso)); + invoke(list, 12, 3, 1); + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + + const auto wait_fence = [&](UINT64 value) -> int { + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, arg(fence), value)))) return 24; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) == value ? 0 : 25; + }; + if (const int rc = wait_fence(1)) return rc; + + // Second present invokes draw_dump_flush() once the frame-1 draw copy has completed. + invoke(queue, 32, 1, arg(plane), 0); + + if (FAILED(static_cast<HRESULT>(invoke(allocator, 8))) || + FAILED(static_cast<HRESULT>(invoke(list, 139, arg(allocator))))) return 35; + D3D12_TEXTURE_COPY_LOCATION to{static_cast<ID3D12Resource*>(readback), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{static_cast<ID3D12Resource*>(target), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + invoke(list, 16, arg(&to), 0, 0, 0, arg(&from), 0); + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (const int rc = wait_fence(2)) return rc; + + void* mapped = nullptr; + if (FAILED(static_cast<HRESULT>(invoke(readback, 8, 0, 0, arg(&mapped)))) || !mapped) return 32; + std::ofstream out(pixels, std::ios::binary); + for (UINT y = 0; y < height; ++y) + out.write(static_cast<const char*>(mapped) + y * footprint.Footprint.RowPitch, width * 4); + const D3D12_RANGE none{}; + invoke(readback, 9, 0, arg(&none)); + invoke(readback, 2); + invoke(target, 2); + return out ? 0 : 33; +} + bool bind_bc7(ID3D12Device* desktop, void* guest, const StartupBc7Input& input, Bc7Binding& binding) { std::ifstream file(input.blocks, std::ios::binary); const std::vector<unsigned char> blocks{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>{}}; const UINT columns = (input.width + 3) / 4, rows = (input.height + 3) / 4, row_bytes = columns * 16; if (blocks.size() != static_cast<std::size_t>(row_bytes) * rows) return false; - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, input.width, input.height, 1, 1, + D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, input.width, input.height, 1, 1, DXGI_FORMAT_BC7_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; - if (input.tiled) { + if (input.display64k) { + // The fixture supplies complete 256x256-texel display tiles in guest memory order. + if (input.width % 256 || input.height % 256) return false; + desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(0x10a); + binding.backing = blocks; + } else if (input.tiled) { if (!populate_tiled_bc7(input, desc, blocks, row_bytes, binding)) return false; } else { auto aligned = desc; @@ -289,10 +402,12 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* // The translated MRT formats draw one pixel; the other formats keep the 8x4 target. const bool single = typed; const bool legacy = !single; - const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : 8; + const UINT width = bc_chain ? 384 : bc7 ? (bc7->small4k ? 48 : bc7->width) : bc ? 4 * 128 : single ? 1 : GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0) ? 15 : 8; const UINT height = bc_chain ? 32 : bc7 ? bc7->height : bc ? 128 : single ? 1 : 4; ComPtr<ID3D12Device> desktop; if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_HISTORY", nullptr, 0)) + return draw_pixel_history(desktop.Get(), guest, pso, pixels); Bc7Binding binding; if (bc7 && bc7->packed) { if (const int rc = bind_packed(desktop.Get(), guest, *bc7, binding)) return rc; @@ -307,7 +422,70 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* auto* queue = frame.queue; auto* fence = frame.fence; if (export_word) invoke(list, 40, 0, 1, arg(&export_word), 0); - if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) { + char index_probe[32]{}; + GetEnvironmentVariableA("X2W_TEST_INDEX_PROBE", index_probe, sizeof(index_probe)); + void* index_resource = nullptr; + void* vertex_resource = nullptr; + void* copied_vertex_memory = nullptr; + if (index_probe[0]) { + bool initial_visible = false, final_visible = false; + const bool wide_indices = !std::strcmp(index_probe, "late-visible-r32"); + const bool with_vb = std::strstr(index_probe, "-vb") != nullptr; + const bool unplaced_vb = !std::strcmp(index_probe, "late-visible-vb-unplaced"); + if (!std::strcmp(index_probe, "visible") || !std::strcmp(index_probe, "visible-vb")) initial_visible = final_visible = true; + else if (!std::strcmp(index_probe, "late-visible") || !std::strcmp(index_probe, "late-visible-vb") || wide_indices || unplaced_vb) final_visible = true; + else if (!std::strcmp(index_probe, "late-clipped") || !std::strcmp(index_probe, "late-clipped-vb")) initial_visible = true; + else if (std::strcmp(index_probe, "clipped") && std::strcmp(index_probe, "clipped-vb")) return 70; + D3D12_FEATURE_DATA_EXISTING_HEAPS capability{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &capability, sizeof(capability))) || !capability.Supported) + return 77; + void* index_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!index_memory) return 71; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, arg(index_memory), arg(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&index_resource)))) || + !index_resource || invoke(index_resource, 11) != arg(index_memory)) return 72; + if (with_vb || unplaced_vb) { + void* vertex_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!vertex_memory) return 73; + if (!unplaced_vb) { + const D3D12_RESOURCE_DESC vdesc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, arg(vertex_memory), arg(&vdesc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&vertex_resource)))) || + !vertex_resource || invoke(vertex_resource, 11) != arg(vertex_memory)) return 74; + } + auto* vwords = static_cast<float*>(vertex_memory); + for (UINT i = 0; i < 6; ++i) { + vwords[4 * i + 0] = i >= 3 ? 8.0f : 0.0f; + vwords[4 * i + 1] = 0.0f; + vwords[4 * i + 2] = 0.0f; + vwords[4 * i + 3] = 0.0f; + } + const D3D12_VERTEX_BUFFER_VIEW vb_view{arg(vertex_memory), 6 * 16, 16}; + invoke(list, 48, 0, 1, arg(&vb_view)); + } + const auto write = [&](bool visible) { + const UINT first = visible ? 0 : 3; + if (wide_indices) { + auto* words = static_cast<std::uint32_t*>(index_memory); + words[0] = 9; // Not part of the draw. A binding that misses the start offset sees this index. + for (UINT i = 0; i < 3; ++i) words[i + 1] = first + i; + } else { + auto* words = static_cast<std::uint16_t*>(index_memory); + for (UINT i = 0; i < 3; ++i) words[i] = static_cast<std::uint16_t>(first + i); + } + }; + write(initial_visible); + const D3D12_INDEX_BUFFER_VIEW index_view{arg(index_memory), wide_indices ? 16u : 6u, + wide_indices ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT}; + const D3D12_RECT full{0, 0, static_cast<LONG>(width), static_cast<LONG>(height)}; + invoke(list, 22, 1, arg(&full)); + invoke(list, 47, arg(&index_view)); + invoke(list, 13, 3, 1, wide_indices ? 1 : 0, 0, 0); + write(final_visible); + } else if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) { if (int result = draw_logical_tables(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) { extern int draw_placed_vertices(ID3D12Device*, void*, void*); @@ -315,6 +493,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (bc_chain) { extern int draw_bc_chain(void*, void*); if (const int result = draw_bc_chain(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_SRV_DRAW", nullptr, 0)) { + extern int draw_root_srv(void*); + if (const int result = draw_root_srv(list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_CBV", nullptr, 0)) { extern int root_heap_control(ID3D12Device*); extern int draw_root_cbv(void*); @@ -323,7 +504,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_1D_SRV", nullptr, 0)) { extern int draw_1d_srvs(void*, void*); if (const int result = draw_1d_srvs(guest, list)) return result; - } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_SRV", nullptr, 0)) { + } else if (GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) || GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_SRV", nullptr, 0)) { extern int draw_address_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_srvs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_MEMORY_SRV_DIAG", nullptr, 0)) { @@ -335,6 +516,15 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0)) { extern int draw_formatted_view(void*, void*); if (const int result = draw_formatted_view(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_TABLE_ALIAS_WRITE", nullptr, 0)) { + extern int draw_table_alias_writes(ID3D12Device*, void*, void*); + if (const int result = draw_table_alias_writes(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV", nullptr, 0)) { + extern int draw_copied_vertex_buffer_srv(void*, void*); + if (const int result = draw_copied_vertex_buffer_srv(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV_PAIR", nullptr, 0)) { + extern int draw_copied_vertex_srv_pair(void*, void*); + if (const int result = draw_copied_vertex_srv_pair(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; @@ -347,6 +537,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0)) { extern int draw_d16_srvs(ID3D12Device*, void*, void*); if (const int result = draw_d16_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { + extern int draw_pixel_uavs(ID3D12Device*, void*, void*); + if (const int result = draw_pixel_uavs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_VERTEX_FETCH", nullptr, 0)) { // TEXCOORD float3 in slot 0 and POSITION float3 in slot 1, 12 bytes each; vertices 0-2 are unused. Vertices // 3-8 are drawn from start vertex 3: positions cover pixels [1, 3) x [1, 3) of the 8x4 target, texture @@ -362,18 +555,43 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* corners(positions + 3, {-0.75f, 0.5f, -0.25f, -0.5f}); corners(texcoords + 9, {-0.25f, -0.5f, 0.0f, -1.0f}); corners(positions + 9, {-1.0f, 1.0f, -0.75f, -1.0f}); + // Keep the interpolated fixed-stream color at the center of an RGBA8 quantization bin. + if (GetEnvironmentVariableW(L"X2W_TEST_FIXED_COLOR", nullptr, 0)) + for (auto& vertex : texcoords) vertex[2] = 64.0f / 255.0f; static const std::uint16_t indices[6] = {4, 5, 6, 7, 8, 9}; - const D3D12_VERTEX_BUFFER_VIEW views[2] = { + D3D12_VERTEX_BUFFER_VIEW views[2] = { {reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(texcoords), sizeof(texcoords), sizeof(texcoords[0])}, {reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(positions), sizeof(positions), sizeof(positions[0])}}; const D3D12_INDEX_BUFFER_VIEW index_view{reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(indices), sizeof(indices), DXGI_FORMAT_R16_UINT}; + const bool fixed_rect = GetEnvironmentVariableW(L"X2W_TEST_FIXED_RECT", nullptr, 0) != 0; + if (fixed_rect) { + // A byte offset of four prevents an existing-heap alias. The CPU vertices + // are written after placement, so reading its separate desktop buffer fails. + copied_vertex_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!copied_vertex_memory) return 73; + auto* data = static_cast<unsigned char*>(copied_vertex_memory) + 4; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1,0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, arg(data), arg(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, arg(&__uuidof(ID3D12Resource)), arg(&vertex_resource)))) || !vertex_resource) return 74; + std::memcpy(data, texcoords, sizeof(texcoords)); + views[0].BufferLocation = arg(data); + } invoke(list, 48, 0, 2, arg(views)); - invoke(list, 12, 6, 1, 3, 0); - invoke(list, 47, arg(&index_view)); - invoke(list, 13, 6, 1, 0, 5, 0); + if (fixed_rect) { + invoke(list, 20, 0x11); + invoke(list, 12, 3, 1, 3, 0); + } else { + invoke(list, 12, 6, 1, 3, 0); + invoke(list, 47, arg(&index_view)); + invoke(list, 13, 6, 1, 0, 5, 0); + } } else if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { extern int draw_root_reset(void*, void*); if (const int result = draw_root_reset(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_RECT_GAP", nullptr, 0)) { + extern int draw_rect_gap(void*, void*); + if (const int result = draw_rect_gap(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_FRAME_COPY", nullptr, 0)) { extern int draw_frame_copies(ID3D12Device*, void*, void*, UINT, UINT); if (const int result = draw_frame_copies(desktop.Get(), guest, list, width, height)) return result; @@ -403,8 +621,49 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* invoke(list, 25, arg(pso)); return true; }; - // Retrying the same bytes after abandoning a recording still needs an upload. Keep the - // shared-ring control's first upload submitted so its mismatch comes from ring wrap. + // X2W_TEST_CONSOLE_KEEP (with the shared ring): a second list A records 32 payloads (32 x 16 MiB = 512 MiB), + // is submitted and waited for, and is never Reset. The fixture's own list then draws payload 32 over the right + // half. A is then submitted again, still closed and not Reset, and the target is read back. + if (GetEnvironmentVariableW(L"X2W_TEST_CONSOLE_KEEP", nullptr, 0)) { + constexpr unsigned kept = 32; + void *allocator_a = nullptr, *list_a = nullptr; + const unsigned list_a_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, + arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator_a)))) || + FAILED(static_cast<HRESULT>(invoke(guest, 73, arg(list_a_desc), arg(allocator_a), 0, + arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list_a)))) || + FAILED(static_cast<HRESULT>(invoke(allocator_a, 8))) || + FAILED(static_cast<HRESULT>(invoke(list_a, 139, arg(allocator_a))))) return 23; // created closed + const D3D12_VIEWPORT whole{0, 0, static_cast<float>(width), static_cast<float>(height), 0, 1}; + invoke(list_a, 50, 1, arg(&rtv)); + invoke(list_a, 21, 1, arg(&whole)); + invoke(list_a, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list_a, 25, arg(pso)); + for (unsigned payload = 0; payload < kept; ++payload) + if (const int result = draw_gated_console_payload(guest, list_a, payload, payload == 0)) return result; + const auto submit_and_wait = [&](void* recorded, UINT64 value) { + invoke(queue, 10, 1, arg(&recorded)); + if (FAILED(static_cast<HRESULT>(invoke(queue, 14, arg(fence), value)))) return false; + const auto deadline = GetTickCount64() + 60000; + while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) == value; + }; + invoke(list, 9); // the fixture's own recording so far (its clear) runs first + if (!submit_and_wait(list, 1)) return 25; + invoke(list_a, 9); + if (!submit_and_wait(list_a, 2)) return 25; + if (!next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, kept, false)) return result; + invoke(list, 9); + if (!submit_and_wait(list, 3)) return 25; + // A again: closed, never Reset. The target is read back after it, so a stale A that ran (its last + // payload, 31, over the right half) shows in the pixels. + if (!submit_and_wait(list_a, 4)) return 25; + return read_stream_target(desktop.Get(), frame, pixels); + } + // Retrying the same bytes after abandoning a recording still needs an upload. The shared-ring + // control skips it so every upload behind the gate comes from the ring, whose 256 MiB cap is + // then exhausted: the later reservations are refused and those draws bind the null view. if (!GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING", nullptr, 0)) { if (const int result = draw_gated_console_payload(guest, list, 0, true)) return result; if (FAILED(static_cast<HRESULT>(invoke(list, 9))) || !next_recording()) return 35; @@ -420,7 +679,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* Sleep(250); if (invoke(fence, 8) != 0) return 46; // a submit completed although the queue was held if (FAILED(static_cast<HRESULT>(invoke(gate, 10, 1)))) return 47; - // One more recording without a draw: its submit is where the stand-in visits the completed ones. + // The last submit visits the completed uploads. In the ring-reuse case it also draws a new payload. const auto reached = [&](UINT64 value) { const auto deadline = GetTickCount64() + 60000; while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); @@ -428,6 +687,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* }; if (!reached(payloads)) return 25; if (!next_recording()) return 35; + if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { + if (const int result = draw_gated_console_payload(guest, list, payloads, false)) return result; + } invoke(list, 9); invoke(queue, 10, 1, arg(&list)); if (FAILED(static_cast<HRESULT>(invoke(queue, 14, arg(fence), payloads + 1))) || !reached(payloads + 1)) return 25; @@ -492,10 +754,21 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* last = 2; } if (const int rc = submit(last)) return rc; + if (index_resource) invoke(index_resource, 2); // The backing heap can outlive the resource. + if (vertex_resource) invoke(vertex_resource, 2); + if (copied_vertex_memory) VirtualFree(copied_vertex_memory, 0, MEM_RELEASE); + if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { + extern int report_pixel_uavs(const char*); + if (const int rc = report_pixel_uavs(pixels)) return rc; + } if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_CBV", nullptr, 0)) { extern int root_heap_report(); if (const int rc = root_heap_report()) return rc; } + if (GetEnvironmentVariableW(L"X2W_TEST_TABLE_ALIAS_WRITE", nullptr, 0)) { + extern void table_alias_debug_report(); + table_alias_debug_report(); + } return read_stream_target(desktop.Get(), frame, pixels); } diff --git a/tests/startup_stream_draw.h b/tests/startup_stream_draw.h index 4e42a9e9bb..e8e845addf 100644 --- a/tests/startup_stream_draw.h +++ b/tests/startup_stream_draw.h @@ -17,6 +17,7 @@ struct StartupBc7Input { // holds mip 0 then mip 1 as tight rows; both go through XG slot 8 into memory of exactly the size XG slot 2 // reports, followed by a no-access guard page. The target is 48x32: mip 0 at the left, mip 1 top right. bool small4k = false; + bool display64k = false; }; int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* pixels, diff --git a/tests/startup_stream_draw_check.py b/tests/startup_stream_draw_check.py index 565b912b71..11ec21a0b7 100644 --- a/tests/startup_stream_draw_check.py +++ b/tests/startup_stream_draw_check.py @@ -1,6 +1,9 @@ """Draw two source-built gfx1013 pixel shaders through a slot-86 wrapper and check every RGBA byte.""" +import ctypes +from ctypes import wintypes import os from pathlib import Path +import re import subprocess import sys import tempfile @@ -34,11 +37,13 @@ def pixel(green): def check(directory, consumer, backend): cache = directory / "cache" cache.mkdir() + recipes = directory / "recipes" + recipes.mkdir() vs, ps, root, output = (directory / name for name in ("vs", "ps", "root", "pixels")) vs.write_bytes(vertex()) args = [consumer, vs, ps, root] env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", - X2W_SHADER_CACHE=str(cache)) + X2W_SHADER_CACHE=str(cache), X2W_PSO_RECIPE_DIR=str(recipes)) env.setdefault("X2W_D3D12_DEBUG", "0") observations = [] for green in (False, True): @@ -63,9 +68,40 @@ def check(directory, consumer, backend): if pixels != expected: raise AssertionError(f"actual {pixels.hex()} expected {expected.hex()}") observations.append(pixels) + # The translated stream draw creates its desktop PSO through pipeline_for. A second + # process with the same recipe directory must replay it instead of reconstructing the + # state from scratch. + assert list(recipes.glob("pso_*.txt")), "the successful draw wrote no PSO recipe" + replay = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert replay.returncode == 0, replay.stderr + assert "pso recipes" in replay.stderr and "precreated" in replay.stderr, replay.stderr + assert output.read_bytes() == pixels, "the recipe replay changed the drawn pixels" + # A second writer cannot enter while this process owns the recipe file exclusively. The + # draw must still render through the PSO it creates; only the cache append is skipped. + recipe_key = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) + recipe_file = recipes / f"pso_{recipe_key:016x}.txt" + assert recipe_file.is_file(), f"missing recipe {recipe_file}" + size_before = recipe_file.stat().st_size + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE] + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + handle = kernel32.CreateFileW(str(recipe_file), 0x80000000, 0, None, 3, 0, None) + assert handle != wintypes.HANDLE(-1).value, ctypes.get_last_error() + try: + locked = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert locked.returncode == 0, locked.stderr + assert output.read_bytes() == pixels, "the locked recipe path changed the drawn pixels" + assert recipe_file.stat().st_size == size_before, "a contending draw appended to the locked recipe" + finally: + kernel32.CloseHandle(handle) + print(f"{backend}: exclusive recipe ownership keeps the draw on the fallback path") # Hold back the last-published marker while keeping the generated shader bytecode in place. key = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) manifest = cache / f"{key:016x}.txt" + green_recipe = recipes / f"pso_{key:016x}.txt" + assert green_recipe.is_file(), f"missing green recipe {green_recipe}" manifest.rename(str(manifest) + ".pending") run = subprocess.run(args + [backend, output], env=dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest)), capture_output=True, text=True, timeout=30) @@ -87,6 +123,49 @@ def check(directory, consumer, backend): if output.read_bytes() != expected: raise AssertionError(f"{mode}: got {output.read_bytes().hex()} expected {expected.hex()}") print(f"{backend} {mode} green={green}: 32 pixels exact, drawn byte {value}") + + # Seed the file with valid records that belong to another translation key. They parse but + # never replay, so the next successful draw appends the matching record as number 64 and the + # process after it precreates that record. At 64 records the writer must refuse the 65th. + ps.write_bytes(pixel(True)) + original = green_recipe.read_text(encoding="ascii") + records = original.split("x2w-pso-recipe 1\n") + assert len(records) >= 2, original + original = "x2w-pso-recipe 1\n" + records[1] + foreign = re.sub(r"(?m)^translation 0x[0-9a-f]{16}$", "translation 0xdeadbeefcafef00d", original) + assert foreign != original + green_recipe.write_text(foreign * 63, encoding="ascii") + run = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert run.returncode == 0, run.stderr + assert output.read_bytes() == observations[1] + assert green_recipe.read_text(encoding="ascii").count("x2w-pso-recipe 1") == 64 + replay = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert replay.returncode == 0, replay.stderr + assert "precreated 1" in replay.stderr, replay.stderr + assert output.read_bytes() == observations[1] + + green_recipe.write_text(foreign * 64, encoding="ascii") + run = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert run.returncode == 0, run.stderr + assert output.read_bytes() == observations[1] + assert green_recipe.read_text(encoding="ascii").count("x2w-pso-recipe 1") == 64, \ + "a full recipe file accepted a 65th record" + print(f"{backend}: 63+1 records precreate; 64 records refuse the 65th") + + # A record without its final LF still parses, but appending would join `end` and the next + # header on one line. The draw must render and leave the parseable file byte-for-byte intact. + no_final_lf = green_recipe.read_bytes() + assert no_final_lf.rstrip(b"\r\n").endswith(b"end"), no_final_lf[-40:] + green_recipe.write_bytes(no_final_lf[:-1]) + before = green_recipe.read_bytes() + run = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert run.returncode == 0, run.stderr + assert output.read_bytes() == observations[1] + assert green_recipe.read_bytes() == before, "a no-LF recipe file was modified by the refused append" + replay = subprocess.run(args + [backend, output], env=env, capture_output=True, text=True) + assert replay.returncode == 0, replay.stderr + assert output.read_bytes() == observations[1] + print(f"{backend}: a recipe without a final LF stays readable and refuses the append") return 0 diff --git a/tests/startup_stream_fetch_check.py b/tests/startup_stream_fetch_check.py index 94fc6499f5..c7b2530419 100644 --- a/tests/startup_stream_fetch_check.py +++ b/tests/startup_stream_fetch_check.py @@ -101,7 +101,7 @@ def first_difference(actual, want): class Run: - def __init__(self, directory, consumer, backend, vs_bytes, layout): + def __init__(self, directory, consumer, backend, vs_bytes, layout, zero_fill=False): self.cache = directory / "cache" self.cache.mkdir(parents=True) self.vs, ps, self.root, self.output = (directory / name for name in ("vs", "ps", "root", "pixels")) @@ -112,8 +112,11 @@ def __init__(self, directory, consumer, backend, vs_bytes, layout): self.env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_SHADER_CACHE=str(self.cache), X2W_TEST_VERTEX_FETCH="1") self.env.setdefault("X2W_D3D12_DEBUG", "0") + self.env.pop("X2W_STREAM_ZERO_FILL", None) + if zero_fill: + self.env["X2W_STREAM_ZERO_FILL"] = "1" if layout: - self.env["X2W_TEST_INPUT_LAYOUT"] = "1" + self.env["X2W_TEST_INPUT_LAYOUT"] = layout if isinstance(layout, str) else "1" else: self.env.pop("X2W_TEST_INPUT_LAYOUT", None) subprocess.run(self.args, env=self.env, check=True) @@ -191,6 +194,29 @@ def patched(*args): if "-> drawn;" in result.stderr: raise AssertionError("a vertex shader with a fetch call and no layout was drawn") print(f"{backend} no layout: refused and not drawn") + + # empty layout, production default: declared with no elements, nothing is published and the fetch is refused. + refused = Run(directory / "empty_default", consumer, backend, vertex(), "empty") + assert not list(refused.cache.glob("req_*.ia")), "an empty layout was published without the opt-in" + result = refused.draw() + if "-> drawn;" in result.stderr: + raise AssertionError("an empty declared layout was drawn without X2W_STREAM_ZERO_FILL") + print(f"{backend} empty layout, default: refused and not drawn") + + # empty layout, experimental opt-in X2W_STREAM_ZERO_FILL=1: every fetched input reads zero (an assumption, not a + # measurement); the vertices collapse and nothing but the blue clear reaches the readback. + empty = Run(directory / "empty", consumer, backend, vertex(), "empty", zero_fill=True) + layout = (empty.cache / ("req_%016x.ia" % empty.key)).read_bytes() + assert layout == b"ia1 0\n", layout + status = gfx2hlsl.translate_request(str(empty.cache), empty.key) + assert status == "ok", status + result = empty.draw() + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"empty layout draw failed on {backend}: {result.returncode}\n{result.stderr}") + difference = first_difference(empty.output.read_bytes(), expected(lambda x, y: False)) + if difference: + raise AssertionError(f"empty layout: {difference}") + print(f"{backend} empty layout: zero-fed vertices draw nothing, all {WIDTH * HEIGHT} pixels exact") return 0 @@ -252,6 +278,14 @@ def translate_cases(directory): for line in ("w = ldu(r0, a);", "v4 = w & 255u;", "v5 = (w >> 8) & 255u;", "v6 = (w >> 16) & 255u;"): assert " %s\n" % line in vs, line + "\n" + vs + # A layout declared with no elements translates: no vertex-buffer load, every fetched register reads zero. + status, vs, manifest = translate(directory / "empty_layout", vertex(), "ia1 0\n") + assert status == "ok", status + for line in ("v4 = 0u;", "v6 = 0u;", "v8 = 0u;", "v10 = 0u;"): + assert " %s\n" % line in vs, line + "\n" + vs + assert "r0.Load(" not in vs and "buf vb" not in manifest, vs + manifest + print("translate: an empty declared layout reads every fetched input as zero") + # Refused: no layout; a register nothing defines; the only write masked off by exec, or bypassed by a branch. for label, words, layout, want in ( ("no layout", None, None, NO_LAYOUT), diff --git a/tests/startup_stream_rasterizer_check.py b/tests/startup_stream_rasterizer_check.py index bc3c55c84b..2f094c361a 100644 --- a/tests/startup_stream_rasterizer_check.py +++ b/tests/startup_stream_rasterizer_check.py @@ -6,6 +6,7 @@ import sys import tempfile +from hardware_adapter_filter_check import check as check_adapter_filter from startup_stream_check import gfx2hlsl from startup_stream_draw_check import pixel, vertex @@ -25,17 +26,7 @@ def check(directory, consumer, backend, mode): X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache)) base_args = [consumer, str(vs), str(ps), str(root), backend] if mode == "filter": - missing = "x2w-no-such-hardware-adapter" - for selector, message in (("x" * 128, "XBOX2WINDOWS_ADAPTER is longer than 127 characters"), - (missing, f"No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER={missing}")): - req = subprocess.run(base_args, env=dict(env, XBOX2WINDOWS_ADAPTER=selector), - capture_output=True, text=True) - if selector == missing and req.returncode == 77: - return 77 - if req.returncode != 4 or message not in req.stderr: - raise RuntimeError(f"expected {message!r}, got exit {req.returncode}\n{req.stdout}{req.stderr}") - print("overlong and unmatched hardware adapter filters rejected") - return 0 + return check_adapter_filter(base_args, env, allow_missing_factory=True) req = subprocess.run(base_args, env=env, capture_output=True, text=True) if backend == "hardware" and req.returncode == 77: print("No D3D12 feature-level 12 hardware adapter") diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 09a1ad6c00..e29b3985f4 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -7,11 +7,13 @@ #include <wrl/client.h> #include <array> +#include <cstddef> #include <fstream> #include <iterator> #include <string> #include <vector> +#include "adapter_name_filter.h" #include "startup_stream_setup.h" using Microsoft::WRL::ComPtr; @@ -34,6 +36,12 @@ struct alignas(8) Layout { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; D3D12_INPUT_LAYOUT_DESC desc; }; +// X2W_TEST_RASTERIZER: a RASTERIZER subobject after the shaders, so a translated draw runs with the cull +// mode and front-face winding of the console pipeline instead of the default (no culling). +struct alignas(8) Raster { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_RASTERIZER_DESC desc; +}; // X2W_TEST_INPUT_LAYOUT: the stream also declares two per-vertex float3 elements, TEXCOORD in slot 0 and POSITION in // slot 1 at D3D12_APPEND_ALIGNED_ELEMENT, in the opposite order of the vertex shader's input signature // (startup_stream_fetch_check.py). @@ -41,10 +49,20 @@ struct LayoutStream { Layout layout; Stream stream; }; +struct RasterLayoutStream { + LayoutStream stream; + Raster rasterizer; +}; static const D3D12_INPUT_ELEMENT_DESC layout_elements[] = { {"TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, }; +// X2W_TEST_INPUT_LAYOUT=gradient: 12-byte records whose first dword is a mask and whose XY follows at +4 +// (startup_rect_gap_check.py). Both views name the same records, each with a 12-byte stride. +static const D3D12_INPUT_ELEMENT_DESC gradient_elements[] = { + {"TEXCOORD", 0, DXGI_FORMAT_R32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 1, 4, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, +}; namespace { void* stream_root = nullptr; @@ -79,32 +97,20 @@ int pick_stream_adapter(bool hardware, ComPtr<IDXGIAdapter>& adapter) if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; - wchar_t wanted[128]{}; - const DWORD length = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", wanted, 128); - if (length >= 128) { - std::fputs("XBOX2WINDOWS_ADAPTER is longer than 127 characters\n", stderr); - return 4; - } + AdapterNameFilter filter; + if (!filter.read()) return 4; ComPtr<IDXGIFactory6> factory6; if (FAILED(factory.As(&factory6))) return 77; for (UINT n = 0;; ++n) { ComPtr<IDXGIAdapter1> candidate; const HRESULT hr = factory6->EnumAdapterByGpuPreference( n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) { - if (!length) return 77; - std::fprintf(stderr, "No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", wanted); - return 4; - } + if (hr == DXGI_ERROR_NOT_FOUND) return filter.no_match(); if (FAILED(hr)) return 4; DXGI_ADAPTER_DESC1 desc{}; if (FAILED(candidate->GetDesc1(&desc))) return 4; if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; - bool matches = length == 0; - for (const wchar_t* p = desc.Description; !matches && *p; ++p) { - matches = _wcsnicmp(p, wanted, length) == 0; - } - if (matches && SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, + if (filter.matches(desc.Description) && SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { adapter = candidate; return 0; @@ -128,6 +134,15 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char return 77; } debug->EnableDebugLayer(); + // X2W_TEST_GPU_VALIDATION=1: also check the states of resources reached through descriptor tables. + ComPtr<ID3D12Debug1> debug1; + if (GetEnvironmentVariableW(L"X2W_TEST_GPU_VALIDATION", nullptr, 0)) { + if (FAILED(debug.As(&debug1))) { + std::printf("no GPU-based validation: skipped\n"); + return 77; + } + debug1->SetEnableGPUBasedValidation(TRUE); + } } if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; @@ -141,16 +156,24 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 5; D3D12_ROOT_SIGNATURE_DESC root_desc{}; - const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + const bool joined_table = GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; + const bool vertex_srv_pair = GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV_PAIR", nullptr, 0) != 0; + char pixel_uav_mode[32]{}; + GetEnvironmentVariableA("X2W_TEST_PIXEL_UAV", pixel_uav_mode, sizeof(pixel_uav_mode)); + const bool raw_pixel = std::strncmp(pixel_uav_mode, "raw-", 4) == 0; + if (raw_pixel) + std::printf("raw descriptor stride: %llu\n", static_cast<unsigned long long>(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV))); + const D3D12_DESCRIPTOR_RANGE srv{raw_pixel ? D3D12_DESCRIPTOR_RANGE_TYPE_UAV : D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + raw_pixel ? 4u : (joined_table || vertex_srv_pair ? 2u : 1u), 0, 0, 0}; D3D12_ROOT_PARAMETER textured_parameters[2]{}; if (textured) { D3D12_ROOT_PARAMETER& table = textured_parameters[0]; table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; table.DescriptorTable = {1, &srv}; - table.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + table.ShaderVisibility = vertex_srv_pair ? D3D12_SHADER_VISIBILITY_VERTEX : D3D12_SHADER_VISIBILITY_PIXEL; root_desc.NumParameters = 1; root_desc.pParameters = textured_parameters; - if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { + if (joined_table || GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { D3D12_ROOT_PARAMETER& constant = textured_parameters[1]; constant.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; constant.Constants = {0, 0, 1}; @@ -160,11 +183,13 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char } // X2W_TEST_ROOT_CBV=<mode> declares root parameter 0 as a constant buffer view (startup_root_cbv.cpp); // "wrong_type" declares a shader resource view there instead. + // X2W_TEST_ROOT_SRV_DRAW (startup_root_srv_draw.cpp) declares it as a shader resource view as well. D3D12_ROOT_PARAMETER root_cbv{}; char cbv_mode[16]{}; - if (!textured && GetEnvironmentVariableA("X2W_TEST_ROOT_CBV", cbv_mode, sizeof(cbv_mode))) { - root_cbv.ParameterType = std::strcmp(cbv_mode, "wrong_type") == 0 ? D3D12_ROOT_PARAMETER_TYPE_SRV - : D3D12_ROOT_PARAMETER_TYPE_CBV; + const bool root_srv_draw = GetEnvironmentVariableW(L"X2W_TEST_ROOT_SRV_DRAW", nullptr, 0) != 0; + if (!textured && (root_srv_draw || GetEnvironmentVariableA("X2W_TEST_ROOT_CBV", cbv_mode, sizeof(cbv_mode)))) { + root_cbv.ParameterType = root_srv_draw || std::strcmp(cbv_mode, "wrong_type") == 0 ? D3D12_ROOT_PARAMETER_TYPE_SRV + : D3D12_ROOT_PARAMETER_TYPE_CBV; root_cbv.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; root_desc.NumParameters = 1; root_desc.pParameters = &root_cbv; @@ -198,13 +223,36 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char &stream_alternate_root))) return 7; } - LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {layout_elements, 2}}, + wchar_t layout_mode[16] = L""; + GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", layout_mode, 16); + const bool empty_layout = std::wcscmp(layout_mode, L"empty") == 0; // declared layout with zero elements + const bool gradient_layout = std::wcscmp(layout_mode, L"gradient") == 0; + LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + {gradient_layout ? gradient_elements : layout_elements, empty_layout ? 0u : 2u}}, {{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}}}; const bool layout = GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", nullptr, 0) != 0; - void* first = layout ? static_cast<void*>(&with_layout) : static_cast<void*>(&with_layout.stream); - const SIZE_T whole = layout ? sizeof(with_layout) : sizeof(with_layout.stream); + // X2W_TEST_RASTERIZER=back|back-ccw|front: cull mode and front-face winding for the translated draw. + char rasterizer_mode[16]{}; + const bool cull = GetEnvironmentVariableA("X2W_TEST_RASTERIZER", rasterizer_mode, sizeof(rasterizer_mode)) != 0; + RasterLayoutStream with_rasterizer{}; + static_assert(offsetof(RasterLayoutStream, rasterizer.desc) == offsetof(RasterLayoutStream, stream) + sizeof(LayoutStream) + 4); + if (cull) { + std::memcpy(&with_rasterizer.stream, &with_layout, sizeof(with_layout)); + with_rasterizer.rasterizer.tag = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; + D3D12_RASTERIZER_DESC& raster = with_rasterizer.rasterizer.desc; + raster.FillMode = D3D12_FILL_MODE_SOLID; + raster.CullMode = std::strcmp(rasterizer_mode, "front") == 0 ? D3D12_CULL_MODE_FRONT : D3D12_CULL_MODE_BACK; + raster.FrontCounterClockwise = std::strcmp(rasterizer_mode, "back-ccw") == 0 ? TRUE : FALSE; + raster.DepthClipEnable = TRUE; + } + void* first = cull ? static_cast<void*>(&with_rasterizer) + : layout ? static_cast<void*>(&with_layout) + : static_cast<void*>(&with_layout.stream); + const SIZE_T whole = cull ? sizeof(with_rasterizer) - sizeof(Raster) + sizeof(unsigned) + sizeof(D3D12_RASTERIZER_DESC) + : layout ? sizeof(with_layout) + : sizeof(with_layout.stream); auto submit = [&](SIZE_T bytes) { D3D12_PIPELINE_STATE_STREAM_DESC desc{bytes, first}; const auto hr = reinterpret_cast<CreateStream>(slots[86])(device, &desc, __uuidof(ID3D12PipelineState), &pso); diff --git a/tests/startup_stub_check.py b/tests/startup_stub_check.py index f2e39ccfa5..1398c34630 100644 --- a/tests/startup_stub_check.py +++ b/tests/startup_stub_check.py @@ -102,7 +102,7 @@ run.stderr) requests_by_format = {int(f): int(n) for f, n in re.findall(r"(\d+):(\d+)", summary.group(1))} if summary else {} blank_by_format = {int(f): int(n) for f, n in re.findall(r"(\d+):(\d+)", summary.group(2))} if summary else {} -bcpack_ok = (requests_by_format.get(6) == 1 and blank_by_format.get(6) == 1 +bcpack_ok = (requests_by_format.get(6) == 1 and blank_by_format.get(6, 0) == 0 and requests_by_format.get(1) == 2 and blank_by_format.get(1, 0) == 0 and requests_by_format.get(3) == 3 and blank_by_format.get(3, 0) == 0 and requests_by_format.get(4) == 4 and blank_by_format.get(4, 0) == 0 diff --git a/tests/startup_stub_consumer.cpp b/tests/startup_stub_consumer.cpp index 3951fa93a8..722f7f4b2f 100644 --- a/tests/startup_stub_consumer.cpp +++ b/tests/startup_stub_consumer.cpp @@ -24,6 +24,8 @@ #include <fstream> #include <cstring> #include <vector> +#include "bcpack_format_fixtures.h" +#include "bcpack_storage_goldens.h" using u64 = std::uint64_t; @@ -1964,39 +1966,40 @@ bool dstorage_checks() { std::memcpy(bc1_packed_trailing, bc1_packed, sizeof(bc1_packed)); bc1_packed_trailing[515] = 0x01; + // GDK 1.2603.3.0 output for the unchanged synthetic_11 input above. const unsigned char bc1_expected[512] = { - 0x85, 0x31, 0x64, 0xd5, 0xaf, 0xbe, 0xff, 0xbf, 0x50, 0x84, 0xc7, 0x6b, 0xba, 0xa5, 0xbf, 0xbf, - 0x50, 0x84, 0x27, 0xc9, 0x56, 0x06, 0x5e, 0x5f, 0x25, 0x6a, 0x43, 0xaa, 0x5e, 0xee, 0xf5, 0xf5, - 0xe8, 0x72, 0xa0, 0x91, 0x5e, 0x5e, 0xfb, 0xfb, 0x2a, 0x3b, 0x83, 0xf1, 0x9a, 0xa5, 0x7a, 0xfa, - 0x81, 0x08, 0xcc, 0xa2, 0x9a, 0x9d, 0xbb, 0xff, 0x28, 0x73, 0x20, 0xbe, 0x8a, 0x8f, 0x05, 0x05, - 0x41, 0x00, 0x8c, 0xda, 0xfa, 0x5f, 0xfa, 0xdb, 0xfe, 0x8a, 0x7a, 0x5a, 0x72, 0x3a, 0xfa, 0xba, - 0x41, 0xf8, 0x8c, 0x32, 0x0f, 0xff, 0xfa, 0xba, 0xec, 0x5a, 0xa6, 0xa9, 0x6b, 0x5f, 0xaf, 0xaf, - 0x50, 0x84, 0x26, 0x89, 0x5a, 0x5f, 0x5f, 0x5f, 0x44, 0x21, 0x23, 0xb1, 0xaf, 0x5d, 0xaf, 0xab, - 0x0d, 0x6b, 0x24, 0x52, 0xaf, 0xf7, 0xbf, 0xfd, 0x0c, 0x5b, 0x26, 0x7c, 0xbe, 0x9e, 0x05, 0x05, - 0x3e, 0x83, 0x7a, 0x39, 0xd5, 0x95, 0xaa, 0x5a, 0x61, 0x10, 0x6e, 0x68, 0x5b, 0x0f, 0xff, 0xbd, - 0x8a, 0x9b, 0x65, 0x51, 0x2f, 0xaa, 0xaa, 0x5a, 0xb8, 0xc6, 0xd3, 0x4a, 0x4f, 0x45, 0xf0, 0xb0, - 0x1e, 0xb6, 0x1e, 0x6d, 0x5b, 0x5f, 0xba, 0xba, 0x50, 0x84, 0x27, 0xe4, 0xfa, 0x5a, 0xaa, 0xaf, - 0x65, 0x52, 0x45, 0xd2, 0x5e, 0x0f, 0xaf, 0xef, 0xaf, 0x73, 0x06, 0x55, 0xae, 0x8f, 0xae, 0x5f, - 0x89, 0x52, 0xa1, 0x80, 0x0f, 0x0b, 0xa5, 0xa5, 0x03, 0x21, 0xe2, 0xe8, 0x7b, 0x5f, 0x0a, 0x0a, - 0xa5, 0x39, 0x23, 0x99, 0xd0, 0xd0, 0xaa, 0xff, 0x2c, 0x8b, 0xca, 0x0a, 0x20, 0xa0, 0xaf, 0xfb, - 0x28, 0x6b, 0xc1, 0x08, 0x0a, 0x5a, 0xff, 0xaa, 0x4a, 0x4a, 0x45, 0x09, 0xba, 0xab, 0x5e, 0x5e, - 0x0c, 0x7a, 0x40, 0xaa, 0x7f, 0x7e, 0x0e, 0x0f, 0x20, 0x48, 0x9d, 0x3b, 0x5f, 0x5f, 0x00, 0x00, - 0x4b, 0xd6, 0xc4, 0xd4, 0x60, 0x60, 0xfb, 0xef, 0x45, 0x3a, 0x41, 0xa9, 0xba, 0x9f, 0xa7, 0xf7, - 0x0d, 0x5b, 0x37, 0x4a, 0xdb, 0x2b, 0xef, 0xaa, 0x20, 0x48, 0x8e, 0x0b, 0x8e, 0xaa, 0xaf, 0xaf, - 0xd8, 0xcd, 0x75, 0x6d, 0x0e, 0x0a, 0xba, 0xff, 0xbc, 0xa3, 0xf8, 0x3e, 0xbf, 0xdf, 0x5a, 0xfa, - 0x9f, 0x08, 0xd2, 0x9a, 0x25, 0x5f, 0xff, 0xba, 0x09, 0x94, 0xc3, 0x82, 0xff, 0xfe, 0xba, 0xba, - 0x21, 0x79, 0x3c, 0x31, 0xaf, 0xfe, 0xaf, 0x5a, 0xbf, 0x53, 0xe1, 0xd1, 0xbf, 0xab, 0x5f, 0x5b, - 0x26, 0x6b, 0xc3, 0xd8, 0x2a, 0xb5, 0xfb, 0xbf, 0x89, 0x42, 0x5f, 0xe1, 0xaf, 0xff, 0xb5, 0xb5, - 0x0a, 0x94, 0x8b, 0xfb, 0xa5, 0xd5, 0x0f, 0x0f, 0xa8, 0x52, 0xc7, 0x01, 0x9f, 0xab, 0x55, 0x55, - 0x29, 0xf8, 0x86, 0x7a, 0xfa, 0xfa, 0xff, 0xaa, 0x40, 0x00, 0x9a, 0x7a, 0xbe, 0xfe, 0xfa, 0xfa, - 0x54, 0x8c, 0x29, 0xc4, 0x0a, 0x0a, 0xaf, 0xab, 0x6c, 0x6b, 0x08, 0x0a, 0xa0, 0xd0, 0xf0, 0xf0, - 0x6b, 0x7c, 0xd9, 0x51, 0xa5, 0xd5, 0xf5, 0xe5, 0x82, 0x21, 0x00, 0x32, 0x00, 0x50, 0xa0, 0xa0, - 0x42, 0x19, 0x35, 0x99, 0xbf, 0xe7, 0xaf, 0xff, 0x46, 0x7b, 0x60, 0x42, 0x60, 0x45, 0x0f, 0x0f, - 0xd4, 0x31, 0x33, 0x99, 0xda, 0xaa, 0xa5, 0xaf, 0x1a, 0xd7, 0xe9, 0x80, 0xba, 0xba, 0x0a, 0x0f, - 0xc6, 0x08, 0x97, 0xe0, 0xff, 0xfa, 0xba, 0xba, 0x51, 0xd6, 0xdf, 0xec, 0x65, 0x65, 0x5f, 0x5a, - 0xbb, 0xbe, 0xda, 0x22, 0x2e, 0xaa, 0xf0, 0xf0, 0x6c, 0x63, 0x1d, 0x72, 0xeb, 0xeb, 0x5f, 0x5f, - 0xce, 0x31, 0x36, 0x91, 0x70, 0x70, 0xaa, 0xf2, 0x57, 0x8c, 0x27, 0xb4, 0x8f, 0xab, 0xf0, 0xb0, - 0x49, 0x7b, 0x6a, 0x42, 0xef, 0xfb, 0xa5, 0xb5, 0x7f, 0x6b, 0x2a, 0x3a, 0x75, 0x75, 0x5a, 0x5f + 0x8d, 0x73, 0x0a, 0x07, 0xea, 0xb8, 0xfa, 0xbe, 0x91, 0x84, 0x04, 0x53, 0xd8, 0xa7, 0x2a, 0x4a, + 0xc3, 0x18, 0xe2, 0x75, 0xa9, 0xf9, 0xa1, 0xa0, 0xef, 0x83, 0x6d, 0xd4, 0xf8, 0x8e, 0xa0, 0xb5, + 0x48, 0x4a, 0x63, 0xaa, 0xd7, 0xd7, 0xbd, 0xb9, 0x8c, 0x6c, 0xc2, 0xf9, 0x3b, 0x05, 0xe0, 0xa0, + 0x90, 0x84, 0xc5, 0x60, 0x30, 0x33, 0xb2, 0x5f, 0x2f, 0x84, 0xed, 0xf8, 0xba, 0xbc, 0xb4, 0x5a, + 0x3e, 0x71, 0x3e, 0xa0, 0x2e, 0x08, 0xdf, 0x9d, 0x82, 0x18, 0xa1, 0xe9, 0xec, 0x20, 0x70, 0xb8, + 0x91, 0x7c, 0x04, 0xab, 0xf7, 0x71, 0x5a, 0xc0, 0xe1, 0x07, 0x40, 0x88, 0xea, 0xdf, 0x25, 0x2f, + 0xb2, 0x94, 0x6c, 0x2b, 0xf0, 0xfa, 0x5f, 0x5f, 0xc1, 0x10, 0xa1, 0xa0, 0x5f, 0xa4, 0x00, 0x04, + 0xad, 0x8b, 0x88, 0x83, 0x2a, 0xae, 0x2b, 0xfd, 0x43, 0x29, 0x62, 0xf3, 0x2f, 0x3a, 0x7b, 0x7b, + 0x68, 0x42, 0xe1, 0xd0, 0x40, 0xc5, 0xe0, 0x10, 0xad, 0x8b, 0x46, 0x57, 0x0d, 0xa5, 0x55, 0xd4, + 0xa2, 0x18, 0x01, 0xd1, 0x14, 0xa0, 0x7a, 0x0a, 0x4b, 0x53, 0x87, 0xe7, 0xda, 0xdf, 0xa4, 0xb0, + 0xe5, 0x39, 0x22, 0xe9, 0xda, 0x5e, 0xde, 0xda, 0x03, 0x19, 0xc5, 0xa1, 0x58, 0x08, 0xe0, 0xee, + 0x0f, 0x84, 0x21, 0x88, 0x0e, 0xae, 0xaa, 0xc0, 0x69, 0x52, 0x46, 0x65, 0xe8, 0x92, 0x08, 0xdf, + 0x4b, 0x63, 0x03, 0x99, 0xd8, 0xd0, 0xdb, 0xd3, 0x99, 0xce, 0xa6, 0xf9, 0xc2, 0xff, 0x50, 0x50, + 0xbf, 0x53, 0xfd, 0xa9, 0x4a, 0xd2, 0x02, 0xaa, 0xeb, 0x62, 0x64, 0xb9, 0xca, 0x0e, 0x41, 0x2d, + 0xb9, 0xd6, 0xa6, 0x21, 0xef, 0xb5, 0xda, 0xb5, 0x8b, 0x52, 0xa6, 0x19, 0x3a, 0x2a, 0xf8, 0xf8, + 0xb9, 0xac, 0x25, 0x42, 0xc2, 0xea, 0x27, 0xa5, 0x6b, 0xac, 0xd3, 0xc1, 0xe2, 0xea, 0x54, 0x42, + 0xc2, 0x7b, 0x9d, 0x82, 0xe1, 0xe0, 0xbd, 0xaf, 0xb0, 0x54, 0xc3, 0xc0, 0x4e, 0xd1, 0xf7, 0x4e, + 0x4c, 0x53, 0x54, 0x00, 0xb2, 0x43, 0x8d, 0x0b, 0x91, 0x84, 0x15, 0x23, 0xb5, 0xa0, 0x7f, 0xff, + 0xcc, 0x6a, 0xec, 0x22, 0x4e, 0x4a, 0x22, 0x8b, 0xb7, 0xde, 0xa2, 0xe9, 0x65, 0x30, 0x02, 0x4a, + 0xcc, 0x73, 0xc9, 0x10, 0x67, 0x46, 0xd6, 0xb8, 0xfa, 0x9b, 0x7a, 0xa5, 0xc5, 0xd7, 0x4e, 0x4e, + 0xee, 0x62, 0x62, 0xb1, 0x00, 0x5a, 0xaf, 0x52, 0xbf, 0x7a, 0x03, 0xfd, 0x3f, 0xab, 0xff, 0xfb, + 0xa0, 0x18, 0x03, 0x91, 0x4b, 0x30, 0x5d, 0xd7, 0x67, 0x5a, 0x01, 0x1a, 0x90, 0x54, 0x4a, 0x42, + 0x26, 0x4a, 0x43, 0x90, 0xa0, 0xd5, 0x5a, 0x72, 0xec, 0x52, 0xc6, 0xe0, 0x22, 0x03, 0x40, 0x00, + 0x79, 0x84, 0x9c, 0xb0, 0xb0, 0xb8, 0xba, 0xa8, 0x8c, 0x73, 0x8f, 0xb0, 0xd7, 0xaa, 0x80, 0xa2, + 0x07, 0x21, 0xc7, 0x81, 0x0a, 0x0a, 0xaf, 0xab, 0x40, 0x08, 0xe4, 0xe8, 0x35, 0xe0, 0xf2, 0xba, + 0x37, 0x5b, 0x60, 0x11, 0x28, 0x37, 0x0e, 0xa8, 0xa1, 0x39, 0x7d, 0x39, 0x5d, 0x55, 0xa0, 0xa0, + 0xff, 0xff, 0x52, 0x70, 0x97, 0xdc, 0xa1, 0x57, 0x1d, 0x41, 0xba, 0x18, 0xea, 0x94, 0x0d, 0xa5, + 0x73, 0x21, 0x30, 0x70, 0xce, 0x91, 0xa8, 0xf7, 0xb7, 0xce, 0xa8, 0x49, 0x37, 0x3f, 0x2b, 0x84, + 0x68, 0x19, 0x56, 0xd8, 0x5f, 0x20, 0x2f, 0x0b, 0x29, 0x29, 0x05, 0x7b, 0x30, 0x64, 0xfb, 0xf0, + 0x85, 0x08, 0x08, 0xd8, 0x17, 0xbf, 0x08, 0x08, 0x01, 0xf8, 0x15, 0x68, 0x37, 0xfb, 0xef, 0x27, + 0xa4, 0x52, 0x6c, 0x42, 0xe5, 0x71, 0xbe, 0xf2, 0xc4, 0x10, 0xbf, 0x90, 0x05, 0x49, 0xf2, 0xda, + 0x33, 0x7c, 0x53, 0x42, 0x8d, 0xa9, 0xa5, 0xd5, 0x7f, 0x6b, 0xa9, 0x31, 0xae, 0x10, 0x1a, 0x0d, }; void* status_ptr = nullptr; @@ -2019,7 +2022,7 @@ bool dstorage_checks() { std::vector<unsigned char> dest_truncated(32, 0xCC); std::vector<unsigned char> dest_bc1_valid(512, 0xEE); std::vector<unsigned char> dest_bc1_trailing(512, 0xDD); - std::vector<unsigned char> dest_bc6h_blank(64, 0xAA); + std::vector<unsigned char> dest_bc6h_invalid(64, 0xAA); std::vector<unsigned char> dest_bc4_wrong_size(8, 0x5A); std::vector<unsigned char> dest_bc4_non_mult(7, 0x5B); std::vector<unsigned char> dest_bc5_wrong_size(16, 0x5C); @@ -2097,11 +2100,11 @@ bool dstorage_checks() { *reinterpret_cast<unsigned*>(req5 + 0x30) = sizeof(bc1_packed_trailing); *reinterpret_cast<unsigned*>(req5 + 0x38) = 512; - // Request 6: BCPack format 6 (BC6H) is not decoded yet; it must be zero-filled and counted. + // Request 6: malformed BC6H must fail without publishing partial output. static const unsigned char bc6h_packed[] = {0x00, 0x01, 0x02, 0x03}; unsigned char req6[0x48] = {}; *reinterpret_cast<u64*>(req6 + 0x00) = (6ull << 1) | 0x400000; - *reinterpret_cast<void**>(req6 + 0x08) = dest_bc6h_blank.data(); + *reinterpret_cast<void**>(req6 + 0x08) = dest_bc6h_invalid.data(); *reinterpret_cast<u64*>(req6 + 0x10) = 0; *reinterpret_cast<unsigned*>(req6 + 0x18) = 64; *reinterpret_cast<const unsigned char**>(req6 + 0x20) = bc6h_packed; @@ -2187,9 +2190,9 @@ bool dstorage_checks() { for (unsigned char b : dest_bc1_trailing) { if (b != 0xDD) return false; } - if (hrs[6] != 0) return false; - for (unsigned char b : dest_bc6h_blank) { - if (b != 0) return false; + if (hrs[6] == 0) return false; + for (unsigned char b : dest_bc6h_invalid) { + if (b != 0xAA) return false; } if (hrs[7] == 0) return false; for (unsigned char b : dest_bc4_wrong_size) { @@ -2340,6 +2343,8 @@ bool dstorage_file_information_checks() return ok; } +#include "bcpack_storage_checks.inl" + } // namespace int main(int argc, char** argv) @@ -2347,6 +2352,7 @@ int main(int argc, char** argv) if (argc != 2) return 2; const char* which = argv[1]; if (!std::strcmp(which, "none")) return 0; + if (!std::strcmp(which, "bcpack-storage")) return bcpack_storage_checks() ? 0 : 11; if (!std::strcmp(which, "chad")) return static_cast<int>(XDspActivate(0x11, 0x22, 0x33, 0x44)); if (!std::strcmp(which, "xg_xs")) return static_cast<int>(XGSuggestSwizzleMode(0x55, 0, 0, 0)); if (!std::strcmp(which, "physical")) { diff --git a/tests/startup_table_alias_check.py b/tests/startup_table_alias_check.py new file mode 100644 index 0000000000..2e07c583be --- /dev/null +++ b/tests/startup_table_alias_check.py @@ -0,0 +1,109 @@ +"""A table buffer view over a placed buffer: per-draw copies by default, a live alias with X2W_D3D12_TABLE_ALIAS=1. + +Cases (X2W_TEST_TABLE_ALIAS_WRITE in tests/startup_address_srv.cpp): + writes records rewritten between two draws and after recording: copies show 40 | 80, the alias 120. + shared-index the alias is also the draw's index buffer. Run with the debug layer and GPU-based validation; no + error may be reported, so the alias must hold both the index-buffer and shader-resource states. + odd-size a 254-byte buffer under a 127 x 2-byte structured view: the 256-byte raw view does not fit the + alias, so even with the switch the draw reads a copy (40), not the later write (120). +""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import draw_texture, prepare_draw_cache + +VERTEX = """ +ByteAddressBuffer records : register(t0); +struct Vertex { + float4 position : SV_Position; + nointerpolation uint2 values : TEXCOORD0; +}; +Vertex main(uint id : SV_VertexID) { + const float2 corners[3] = {float2(-1, 1), float2(3, 1), float2(-1, -3)}; + Vertex output; + output.position = float4(corners[id], 0.5, 1); + output.values = uint2(records.Load(16), records.Load(20)); + return output; +} +""" + +PIXEL = """ +float4 main(float4 position : SV_Position, nointerpolation uint2 values : TEXCOORD0) : SV_Target { + return float4(float2(values) / 255.0, 0, 1); +} +""" + +BINDING = "srv 0 buf table 0 0" +VALIDATION = {"X2W_TEST_DEBUG_LAYER": "1", "X2W_TEST_GPU_VALIDATION": "1"} + + +def texel(value): + return bytes((value, value + 1, 0, 255)) + + +def run(folder, consumer, backend, modes): + """Pixels and stdout of one consumer run, or (None, "") for a capability skip.""" + try: + env, args, output = prepare_draw_cache(folder, consumer, PIXEL, modes, BINDING, vertex_hlsl=VERTEX) + except subprocess.CalledProcessError as error: + if error.returncode == 77: # no existing heaps, debug layer or GPU-based validation + return None, "" + raise + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return None, "" + if result.returncode: + raise RuntimeError(f"consumer failed ({result.returncode})\n{result.stderr[-5000:]}") + return output.read_bytes(), result.stdout + + +def debug_errors(stdout, name): + found = re.search(r"^table alias debug layer errors: (\d+)$", stdout, re.M) + if not found: + raise AssertionError(f"{name}: no debug layer message count") + return int(found.group(1)) + + +def check(directory, consumer, backend): + # The fixture writes 40, draws the left half, writes 80, draws the right half, then writes 120 before the list runs. + cases = ( + # The copy case clears the switch, so it keeps testing the default when the switch is set in the environment. + ("copy", {"X2W_D3D12_TABLE_ALIAS": "0"}, texel(40) * 4 + texel(80) * 4), + ("alias", {"X2W_D3D12_TABLE_ALIAS": "1"}, texel(120) * 8), + ) + for name, switches, row in cases: + folder = directory / name + folder.mkdir() + pixels = draw_texture(folder, consumer, backend, PIXEL, {"X2W_TEST_TABLE_ALIAS_WRITE": "1", **switches}, + binding=BINDING, vertex_hlsl=VERTEX) + if pixels is None: + return 77 + expected = row * 4 + if pixels != expected: + raise AssertionError(f"{backend}: {name} table buffer got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched the {name} reading of a rewritten table buffer") + + for name, extra, value in (("shared-index", VALIDATION, 40), ("odd-size", VALIDATION, 40)): + folder = directory / name + folder.mkdir() + modes = {"X2W_TEST_TABLE_ALIAS_WRITE": name, "X2W_D3D12_TABLE_ALIAS": "1", **extra} + pixels, stdout = run(folder, consumer, backend, modes) + if pixels is None: + return 77 + expected = texel(value) * 32 + if pixels != expected: + raise AssertionError(f"{backend}: {name} got {pixels.hex()}, expected {expected.hex()}") + errors = debug_errors(stdout, name) + if errors: + raise AssertionError(f"{backend}: {name}: {errors} debug layer errors") + print(f"{backend}: {name}: 32 pixels exact, no debug layer errors") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_teardown_unload.cpp b/tests/startup_teardown_unload.cpp index 44cc0297d9..af71c53d36 100644 --- a/tests/startup_teardown_unload.cpp +++ b/tests/startup_teardown_unload.cpp @@ -1,20 +1,46 @@ -// Loads the built d3d12_xs.dll by explicit path, warms the two caches that keep desktop D3D12 objects +// Loads the built d3d12_xs.dll by explicit path, warms the four caches that keep desktop D3D12 objects // (#2572) through that module, and walks both detach paths it has to survive: // // startup_teardown_unload <path-to-d3d12_xs.dll> <warp|hardware> // // Unload: FreeLibrary detaches the module with lpReserved == nullptr. Each cache is loaded and warmed on -// its own, so its release can be seen alone: the device's reference count must return to the count the -// test itself holds (otherwise an owned object was leaked), the module must be gone, and the process must -// still run. +// its own, so its release can be seen alone: the module must be gone, what it owned must be released, and +// the process must still run. The two original caches hold a reference on the device handle this fixture +// holds, so the count of that handle is the measure there. The caches added with the placed page aliases +// and the draw dumps own desktop objects instead, and a desktop object holds no reference on the wrapper: +// for them the probe hands over one reference of every object an entry owns (x2w_d3d12_cached_object_probe) +// and that reference has to stay alone once the module is gone -- the count of the entry's own object is +// the release measure. // -// Termination: a second load warms both caches and is deliberately left loaded. On process exit the +// The placed-alias case also owns the heap its buffer is placed on. The probe creates that heap and hands +// its one reference over (the entry keeps the heap as a key only, as the real route does), so the fixture +// holds it across the unload and releases it only after the cache released the placed buffer: a heap must +// outlive the resources placed in it. That release has to be the last reference on the heap, and the case +// fails when it is not, because a heap left with no owner is the leak this check exists to catch. +// +// Termination: a second load warms every cache and is deliberately left loaded. On process exit the // loader detaches the module with lpReserved != nullptr, after Windows has stopped the display driver; // releasing a pipeline state then faults inside the driver (amdxc64 offset 0x35f2a19, through // D3D12Core!CPipelineState::FinalRelease) and the process dies with 0xC0000409 before it can report a // result. The caches must detach their references instead. This is the path the five // startup_indirect_*_hardware runs hit. // +// That second load runs in a child process (this executable again, --termination-only), because the +// evidence only exists while that process tears the module down: the shim prints one line per destroyed +// cache on stderr, +// +// x2w-teardown <cache> detached=<n> released=<n> +// +// when X2W_TEARDOWN_REPORT is set. The child is run with it set and its report is required to say, for +// both caches that own something new here, that every owned reference was detached and none released. +// +// Negative control, the test hook the review of the ownership change asked for: X2W_TEARDOWN_NO_GUARD= +// <pages|readbacks|all> makes that cache's destructor release instead of detach during process exit, so +// the termination check has to fail with it set. Every passing run re-runs the child once per cache with +// the hook set and requires the check to fail, so a check that passes with and without a guard cannot +// report success. Set in this process's own environment the hook is passed through to the child, and this +// run fails with the reason. +// // The fixture is source-built and loads no title. #include <windows.h> #include <d3d12.h> @@ -30,19 +56,28 @@ using Microsoft::WRL::ComPtr; namespace { using XboxCreateDevice = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); -// Probe bits: 1 the indexed-validation pipeline, 2 the rectangle-list argument converter. -using CachedObjectsProbe = UINT(WINAPI*)(ID3D12Device*, UINT); +// Probe bits: 1 the indexed-validation pipeline, 2 the rectangle-list argument converter, 4 the placed +// page aliases, 8 the draw-dump readbacks. Bit 4 also creates a heap and hands its one reference over +// through the third argument, which only it fills; the alias entry keeps that heap as a key only. +using CachedObjectsProbe = UINT(WINAPI*)(ID3D12Device*, UINT, ID3D12Heap**); +// One reference of an object a warmed entry owns: cache 4 slot 0 the placed buffer, cache 8 slot 0 the +// readback buffer, cache 8 slot 1 its fence. +using CachedObjectProbe = IUnknown*(WINAPI*)(UINT, UINT); struct CacheCase { const char* name; UINT probe_bits; - UINT owned; // objects the warmed cache holds for one device + UINT owned; // objects the warmed cache holds for one device + unsigned slots; // owned objects the probe hands out; 0: measured through the device count + bool heap; // the probe also hands over the placed buffer's backing heap }; // One case per cache, so a leak names the cache that kept it. constexpr CacheCase cache_cases[] = { - {"indexed-validation", 1u, 3u}, // device, root signature, pipeline - {"rect-converter", 2u, 2u}, // root signature, pipeline + {"indexed-validation", 1u, 3u, 0u, false}, // device, root signature, pipeline + {"rect-converter", 2u, 2u, 0u, false}, // root signature, pipeline + {"placed-pages", 4u, 1u, 1u, true}, // the placed buffer behind the alias entry, and its heap + {"draw-readbacks", 8u, 2u, 2u, false}, // the readback buffer and the fence that owns its completion }; // Same selection convention as the other D3D12 fixtures: WARP on request, otherwise the first @@ -83,13 +118,41 @@ int select_adapter(bool warp, ComPtr<IDXGIFactory6>& factory, ComPtr<IDXGIAdapte std::wstring widen(const char* path) { const int length = MultiByteToWideChar(CP_ACP, 0, path, -1, nullptr, 0); - if (length <= 0) return std::wstring(); + if (length <= 1) return std::wstring(); std::wstring wide(static_cast<std::size_t>(length), L'\0'); if (!MultiByteToWideChar(CP_ACP, 0, path, -1, wide.data(), length)) return std::wstring(); + // -1 makes the conversion include the terminating null. Keeping it would put a null inside the path, + // and a command line built from this string would end there: CreateProcessW truncates at the first one. + wide.resize(static_cast<std::size_t>(length) - 1); return wide; } -HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObjectsProbe& probe) +std::wstring narrow_to_wide(const std::string& text) +{ + return std::wstring(text.begin(), text.end()); +} + +std::wstring quoted(const std::wstring& text) +{ + return L'"' + text + L'"'; +} + +std::wstring executable_path() +{ + std::wstring path(MAX_PATH, L'\0'); + for (;;) { + const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size())); + if (!length) return std::wstring(); + if (length < path.size()) { + path.resize(length); + return path; + } + path.resize(path.size() * 2); + } +} + +HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObjectsProbe& probe, + CachedObjectProbe& object_probe) { HMODULE module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); @@ -100,18 +163,23 @@ HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObje } create = reinterpret_cast<XboxCreateDevice>(GetProcAddress(module, "D3D12XboxCreateDevice")); probe = reinterpret_cast<CachedObjectsProbe>(GetProcAddress(module, "x2w_d3d12_cached_objects_probe")); - if (!create || !probe) { - std::fputs("d3d12_xs.dll does not export D3D12XboxCreateDevice and x2w_d3d12_cached_objects_probe\n", stderr); + object_probe = reinterpret_cast<CachedObjectProbe>(GetProcAddress(module, "x2w_d3d12_cached_object_probe")); + if (!create || !probe || !object_probe) { + std::fputs("d3d12_xs.dll does not export D3D12XboxCreateDevice, x2w_d3d12_cached_objects_probe " + "and x2w_d3d12_cached_object_probe\n", stderr); FreeLibrary(module); return nullptr; } - HMODULE owner = nullptr; - if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast<LPCWSTR>(probe), &owner) || - owner != module) { - std::fputs("x2w_d3d12_cached_objects_probe does not resolve inside d3d12_xs.dll\n", stderr); - FreeLibrary(module); - return nullptr; + const LPCWSTR entries[] = {reinterpret_cast<LPCWSTR>(probe), reinterpret_cast<LPCWSTR>(object_probe)}; + for (LPCWSTR entry : entries) { + HMODULE owner = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + entry, &owner) || + owner != module) { + std::fputs("a cache probe does not resolve inside d3d12_xs.dll\n", stderr); + FreeLibrary(module); + return nullptr; + } } return module; } @@ -124,12 +192,32 @@ ULONG reference_count(IUnknown* object) return object->Release(); } +void release_objects(IUnknown* (&objects)[2]) +{ + for (IUnknown*& object : objects) { + if (object) object->Release(); + object = nullptr; + } +} + +// Gives back what the fixture holds of a placed alias entry on an error path: the placed buffer's +// reference first, then the heap behind it. A heap must outlive the resources placed in it, so the two +// releases are not interchangeable; the success path below releases them one at a time instead, because +// it reports each count. +void release_placed(ComPtr<ID3D12Heap>& heap, IUnknown* (&objects)[2], bool unloaded = true) +{ + release_objects(objects); + if (unloaded) heap.Reset(); + else (void)heap.Detach(); // The still-loaded cache owns a placed buffer until process exit. +} + // Phase 1: load, warm one cache, unload explicitly, and check that this cache released what it owned. int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase& cache) { XboxCreateDevice create = nullptr; CachedObjectsProbe probe = nullptr; - HMODULE shim = load_shim(path, create, probe); + CachedObjectProbe object_probe = nullptr; + HMODULE shim = load_shim(path, create, probe, object_probe); if (!shim) return 1; ComPtr<ID3D12Device> device; @@ -141,30 +229,116 @@ int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase return 4; } - const ULONG before = reference_count(device.Get()); - const UINT owned = probe(device.Get(), cache.probe_bits); + ULONG before = 0, warm = 0; + IUnknown* objects[2] = {nullptr, nullptr}; + ULONG held[2] = {0, 0}; + // The backing heap of the placed buffer, when this case has one: the probe hands it over with the one + // reference it holds, so the fixture owns it from here to the end of this function -- across the + // unload -- and it is released last, after the cache and the fixture both let the placed buffer go. + ComPtr<ID3D12Heap> heap; + const auto unload_after_error = [&] { + const bool unloaded = FreeLibrary(shim) && !GetModuleHandleW(L"d3d12_xs.dll"); + release_placed(heap, objects, unloaded); + }; + ULONG heap_held = 0; + if (!cache.slots) before = reference_count(device.Get()); + + ID3D12Heap* warmed_heap = nullptr; + const UINT owned = probe(device.Get(), cache.probe_bits, &warmed_heap); + if (warmed_heap) heap.Attach(warmed_heap); if (owned != cache.owned) { std::fprintf(stderr, "%s: probe reports %u cached objects, expected %u\n", cache.name, owned, cache.owned); - FreeLibrary(shim); + unload_after_error(); return 5; } - const ULONG warm = reference_count(device.Get()); - if (warm <= before) { - std::fprintf(stderr, "%s: the cache holds no reference on the device: %lu before, %lu warm\n", cache.name, - static_cast<unsigned long>(before), static_cast<unsigned long>(warm)); - FreeLibrary(shim); - return 6; + if (cache.heap != (heap.Get() != nullptr)) { + std::fprintf(stderr, "%s: the probe %s a backing heap for the placed buffer, expected %s\n", cache.name, + heap ? "also handed over" : "handed over no", cache.heap ? "one" : "none"); + unload_after_error(); + return 15; + } + if (heap) { + heap_held = reference_count(heap.Get()); + std::printf("warm %s: backing heap handed over with %lu reference%s\n", cache.name, + static_cast<unsigned long>(heap_held), heap_held == 1 ? "" : "s"); + } + + if (cache.slots) { + // One reference of each object the entry owns: before the unload it is the cache's plus this one. + for (unsigned slot = 0; slot < cache.slots; ++slot) { + objects[slot] = object_probe(cache.probe_bits, slot); + if (!objects[slot]) { + std::fprintf(stderr, "%s: the warmed cache owns no object in slot %u\n", cache.name, slot); + unload_after_error(); + return 6; + } + held[slot] = reference_count(objects[slot]); + if (held[slot] < 2) { + std::fprintf(stderr, "%s: slot %u reports %lu references, expected the cache's and this fixture's\n", + cache.name, slot, static_cast<unsigned long>(held[slot])); + unload_after_error(); + return 6; + } + } + } else { + warm = reference_count(device.Get()); + if (warm <= before) { + std::fprintf(stderr, "%s: the cache holds no reference on the device: %lu before, %lu warm\n", cache.name, + static_cast<unsigned long>(before), static_cast<unsigned long>(warm)); + FreeLibrary(shim); + return 6; + } } if (!FreeLibrary(shim)) { std::fprintf(stderr, "%s: FreeLibrary failed: %lu\n", cache.name, static_cast<unsigned long>(GetLastError())); + release_placed(heap, objects, false); return 7; } if (GetModuleHandleW(L"d3d12_xs.dll")) { std::fprintf(stderr, "%s: d3d12_xs.dll is still loaded after FreeLibrary\n", cache.name); + release_placed(heap, objects, false); return 8; } + + if (cache.slots) { + for (unsigned slot = 0; slot < cache.slots; ++slot) { + const ULONG after = reference_count(objects[slot]); + if (after + 1 != held[slot]) { + std::fprintf(stderr, "%s: the unloaded module kept a reference on slot %u: %lu -> %lu (expected %lu)\n", + cache.name, slot, static_cast<unsigned long>(held[slot]), + static_cast<unsigned long>(after), static_cast<unsigned long>(held[slot] - 1)); + release_placed(heap, objects); + return 9; + } + std::printf("unload %s: slot %u reference %lu -> %lu\n", cache.name, slot, + static_cast<unsigned long>(held[slot]), static_cast<unsigned long>(after)); + } + // The module dropped its reference on the placed buffer above; this drops the fixture's. The heap + // has to outlive the buffer placed in it, so it is released only now -- and that release is the + // last reference, which is what proves the fixture, and not the cache, owned the heap. + release_objects(objects); + if (heap) { + // Still alive with the module gone, and what keeps it alive is the fixture's reference: it was + // taken from the probe before the unload and this scope is where it ends. + const ULONG alive = reference_count(heap.Get()); + std::printf("unload %s: heap alive after the unload, %lu reference%s, placed buffer released first\n", + cache.name, static_cast<unsigned long>(alive), alive == 1 ? "" : "s"); + ID3D12Heap* released = heap.Detach(); + const ULONG last = released->Release(); + if (last != 0) { + std::fprintf(stderr, "%s: the fixture's heap release was not the last: %lu references left, so " + "something else owns the backing heap\n", + cache.name, static_cast<unsigned long>(last)); + return 16; + } + std::printf("unload %s: heap released last, %lu -> 0\n", cache.name, static_cast<unsigned long>(alive)); + } + std::printf("unload %s: %u objects released, module unloaded\n", cache.name, owned); + return 0; + } + const ULONG after = reference_count(device.Get()); if (after != before) { std::fprintf(stderr, "%s: the unloaded module left %lu device references behind (expected %lu)\n", @@ -176,40 +350,253 @@ int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase return 0; } -// Phase 2: load and warm both caches, then let the process exit with the module still loaded. Nothing may -// be released from the caches then, so nothing reaches the driver Windows has already stopped. -int termination_path(const std::wstring& path, IDXGIAdapter* adapter) +// The child body: load, warm every cache, return without unloading, so the loader detaches the module +// during process exit. Nothing else runs here -- the report lines come out of the CRT teardown. +int termination_warm(const std::wstring& path, const std::string& backend) { + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter> adapter; + const int selected = select_adapter(backend == "warp", factory, adapter); + if (selected) return selected; + DXGI_ADAPTER_DESC desc{}; + if (SUCCEEDED(adapter->GetDesc(&desc))) + std::printf("termination child backend=%s adapter=%ls vendor=%04x device=%04x\n", backend.c_str(), + desc.Description, desc.VendorId, desc.DeviceId); + XboxCreateDevice create = nullptr; CachedObjectsProbe probe = nullptr; - HMODULE shim = load_shim(path, create, probe); + CachedObjectProbe object_probe = nullptr; + HMODULE shim = load_shim(path, create, probe, object_probe); if (!shim) return 1; ComPtr<ID3D12Device> device; - HRESULT hr = create(adapter, nullptr, __uuidof(ID3D12Device), + HRESULT hr = create(adapter.Get(), nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(device.GetAddressOf())); if (FAILED(hr) || !device) { - std::fprintf(stderr, "D3D12XboxCreateDevice failed on the second load: 0x%08lx\n", + std::fprintf(stderr, "D3D12XboxCreateDevice failed on the termination load: 0x%08lx\n", static_cast<unsigned long>(hr)); return 4; } - UINT expected = 0; - for (const CacheCase& cache : cache_cases) expected += cache.owned; - const UINT owned = probe(device.Get(), 3u); + UINT caches = 0, expected = 0; + for (const CacheCase& cache : cache_cases) { + caches |= cache.probe_bits; + expected += cache.owned; + } + ID3D12Heap* placed_heap = nullptr; + const UINT owned = probe(device.Get(), caches, &placed_heap); if (owned != expected) { std::fprintf(stderr, "termination: probe reports %u cached objects, expected %u\n", owned, expected); return 5; } + if (!placed_heap) { + std::fputs("termination: the placed alias probe handed over no backing heap\n", stderr); + return 6; + } // Deliberately no FreeLibrary: the shim stays loaded, so the loader detaches it during process exit. // Releasing the device here, while the process and the driver still run, is the test's own reference. + // The backing heap is kept for the same reason and is not released either: the exit path detaches the + // placed buffer instead of releasing it, so the heap has to outlive the process exit. Unlike before + // this reference has an owner -- this child -- instead of being abandoned by the probe. std::printf("termination: %u objects left to the process exit path\n", owned); return 0; } +// One x2w-teardown line of the child's report, if it printed one for this cache. +bool teardown_line(const std::string& text, const char* cache, unsigned& detached, unsigned& released) +{ + const std::string prefix = std::string("x2w-teardown ") + cache + " detached="; + for (std::size_t at = text.find(prefix); at != std::string::npos; at = text.find(prefix, at + 1)) { + unsigned detached_value = 0, released_value = 0; + if (std::sscanf(text.c_str() + at + prefix.size(), "%u released=%u", &detached_value, &released_value) == 2) { + detached = detached_value; + released = released_value; + return true; + } + } + return false; +} + +// The termination contract: the child exited cleanly and both caches that own something here report every +// reference detached and none released. Answers the failures found, empty when the contract holds. +struct ChildRun { + DWORD exit_code = 0; + std::string text; // everything the child wrote, stdout and stderr on one pipe +}; + +std::string termination_failure(const ChildRun& run) +{ + std::string failure; + char line[256]; + const auto add = [&failure](const char* text) { + if (!failure.empty()) failure += "; "; + failure += text; + }; + if (run.exit_code != 0) { + std::snprintf(line, sizeof(line), "the child exited 0x%08lx instead of returning", + static_cast<unsigned long>(run.exit_code)); + add(line); + } + struct Expectation { + const char* cache; + unsigned detached; + }; + constexpr Expectation expectations[] = {{"pages", 1u}, {"readbacks", 2u}}; + for (const Expectation& want : expectations) { + unsigned detached = 0, released = 0; + if (!teardown_line(run.text, want.cache, detached, released)) { + std::snprintf(line, sizeof(line), "x2w-teardown %s: no report line", want.cache); + add(line); + } else if (detached != want.detached || released != 0) { + std::snprintf(line, sizeof(line), "x2w-teardown %s detached=%u released=%u (want detached=%u released=0)", + want.cache, detached, released, want.detached); + add(line); + } + } + return failure; +} + +// An environment variable of this process; empty when it is unset or empty (the shim reads both the same +// way). +std::wstring variable(const wchar_t* name) +{ + wchar_t value[64]{}; + const DWORD length = GetEnvironmentVariableW(name, value, 64); + return length && length < 64 ? std::wstring(value, length) : std::wstring(); +} + +// Sets (non-empty) or clears (empty) an environment variable of this process. +void set_variable(const wchar_t* name, const std::wstring& value) +{ + SetEnvironmentVariableW(name, value.empty() ? nullptr : value.c_str()); +} + +// The caller's own X2W_TEARDOWN_NO_GUARD, passed through to the guarded child so that setting it makes +// this run fail -- that is the documented negative control at fixture level. +std::wstring caller_no_guard() +{ + return variable(L"X2W_TEARDOWN_NO_GUARD"); +} + +// Runs this executable once as a termination child. Its stdout and stderr share one pipe, read while it +// runs, so a child that dies mid-teardown still leaves whatever it printed; stdin comes from NUL. The +// child inherits this process's environment, so the two teardown variables are set here around +// CreateProcessW and the caller's values are put back afterwards. +bool run_child(const std::wstring& command, const std::wstring& no_guard, ChildRun& run) +{ + SECURITY_ATTRIBUTES security{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; + HANDLE read_end = nullptr, write_end = nullptr; + if (!CreatePipe(&read_end, &write_end, &security, 0)) { + std::fprintf(stderr, "CreatePipe failed: %lu\n", static_cast<unsigned long>(GetLastError())); + return false; + } + HANDLE input = CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &security, OPEN_EXISTING, 0, + nullptr); + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + startup.dwFlags = STARTF_USESTDHANDLES; + startup.hStdInput = input; + startup.hStdOutput = write_end; + startup.hStdError = write_end; + PROCESS_INFORMATION process{}; + const std::wstring saved_report = variable(L"X2W_TEARDOWN_REPORT"); + const std::wstring saved_guard = variable(L"X2W_TEARDOWN_NO_GUARD"); + set_variable(L"X2W_TEARDOWN_REPORT", L"1"); + set_variable(L"X2W_TEARDOWN_NO_GUARD", no_guard); + std::wstring line = command; // CreateProcessW may write to its command line + const BOOL created = CreateProcessW(nullptr, line.data(), nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, + nullptr, &startup, &process); + const DWORD error = GetLastError(); + set_variable(L"X2W_TEARDOWN_REPORT", saved_report); + set_variable(L"X2W_TEARDOWN_NO_GUARD", saved_guard); + CloseHandle(write_end); + if (input != INVALID_HANDLE_VALUE) CloseHandle(input); + if (!created) { + std::fprintf(stderr, "CreateProcessW failed: %lu for %ls\n", static_cast<unsigned long>(error), + command.c_str()); + CloseHandle(read_end); + return false; + } + CloseHandle(process.hThread); + for (;;) { + char buffer[4096]; + DWORD got = 0; + if (!ReadFile(read_end, buffer, sizeof(buffer), &got, nullptr) || !got) break; + run.text.append(buffer, got); + } + CloseHandle(read_end); + WaitForSingleObject(process.hProcess, INFINITE); + GetExitCodeProcess(process.hProcess, &run.exit_code); + CloseHandle(process.hProcess); + return true; +} + +// Phase 2: the termination load runs in a child of this process. The guarded child has to pass; with +// X2W_TEARDOWN_NO_GUARD naming one cache, the same checks have to fail -- the negative control the review +// asked for, run per cache on every pass so that a check insensitive to either guard cannot go green. +int termination_path(const std::wstring& path, const std::string& backend) +{ + const std::wstring executable = executable_path(); + if (executable.empty()) { + std::fputs("GetModuleFileNameW failed: cannot run the termination child\n", stderr); + return 10; + } + const std::wstring command = quoted(executable) + L" --termination-only " + quoted(path) + L" " + + narrow_to_wide(backend); + const std::wstring no_guard = caller_no_guard(); + if (!no_guard.empty()) + std::printf("termination: X2W_TEARDOWN_NO_GUARD=%ls is set in this environment: the guarded check must fail\n", + no_guard.c_str()); + + ChildRun guarded; + if (!run_child(command, no_guard, guarded)) return 10; + std::printf("%s", guarded.text.c_str()); + const std::string failure = termination_failure(guarded); + if (!failure.empty()) { + std::fprintf(stderr, "termination: %s\n", failure.c_str()); + return 11; + } + std::printf("termination: both caches detached every owned reference, released none\n"); + if (!no_guard.empty()) { + // The caller set the hook and the check still passed: the hook did nothing, so nothing here + // proves the guard is needed. + std::fprintf(stderr, "negative control: the termination check passed with X2W_TEARDOWN_NO_GUARD=%ls: " + "the hook has no effect on this build\n", no_guard.c_str()); + return 14; + } + + for (const char* cache : {"pages", "readbacks"}) { + ChildRun unguarded; + if (!run_child(command, narrow_to_wide(cache), unguarded)) return 12; + const std::string unguarded_failure = termination_failure(unguarded); + if (unguarded_failure.empty()) { + std::fprintf(stderr, "negative control: the termination check passed with X2W_TEARDOWN_NO_GUARD=%s, " + "so it does not prove the %s guard is needed\n", cache, cache); + std::fprintf(stderr, "%s", unguarded.text.c_str()); + return 13; + } + std::printf("negative control X2W_TEARDOWN_NO_GUARD=%s: the check failed as it must (%s)\n", cache, + unguarded_failure.c_str()); + } + return 0; +} + } // namespace int main(int argc, char** argv) { + if (argc == 4 && std::string_view(argv[1]) == "--termination-only") { + const std::string_view backend = argv[3]; + if (backend != "warp" && backend != "hardware") { + std::fputs("unknown backend\n", stderr); + return 2; + } + const std::wstring path = widen(argv[2]); + if (path.empty()) { + std::fputs("cannot convert the d3d12_xs.dll path\n", stderr); + return 2; + } + return termination_warm(path, std::string(backend)); + } if (argc != 3) { std::fprintf(stderr, "usage: %s <path-to-d3d12_xs.dll> <warp|hardware>\n", argv[0]); return 2; @@ -231,15 +618,16 @@ int main(int argc, char** argv) if (selected) return selected; DXGI_ADAPTER_DESC desc{}; if (SUCCEEDED(adapter->GetDesc(&desc))) - std::printf("startup_teardown_unload backend=%s adapter=%ls vendor=%04x device=%04x\n", argv[2], - desc.Description, desc.VendorId, desc.DeviceId); + std::printf("startup_teardown_unload backend=%.*s adapter=%ls vendor=%04x device=%04x\n", + static_cast<int>(backend.size()), backend.data(), desc.Description, desc.VendorId, desc.DeviceId); int result = 0; for (const CacheCase& cache : cache_cases) { result = unload_path(path, adapter.Get(), cache); if (result) break; } - if (result == 0) result = termination_path(path, adapter.Get()); - std::printf("startup_teardown_unload %s: %s\n", argv[2], result == 0 ? "PASS" : "FAIL"); + if (result == 0) result = termination_path(path, std::string(backend)); + std::printf("startup_teardown_unload %.*s: %s\n", static_cast<int>(backend.size()), backend.data(), + result == 0 ? "PASS" : "FAIL"); return result; } diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index c2fcba5db0..494d0f40be 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -59,6 +59,11 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: # A device slot 67 compute request with the same reason is counted in its own class. (cache_dir / "0000000000000004.fail").write_text("image_load_mip tfe\n", encoding="utf-8") (cache_dir / "req_0000000000000004.c67").write_bytes(b"\0" * 4) + # A compute runtime manifest reason is a fixed category; text outside its allowlist is not copied. + for key, line in ((5, "unsupported startup runtime manifest bindings: UAV kind texture_uav cube"), + (6, "unsupported startup runtime manifest bindings: SRV kind /home/alice/x")): + (cache_dir / f"{key:016x}.fail").write_text(line + "\n", encoding="utf-8") + (cache_dir / f"req_{key:016x}.c67").write_bytes(b"\0" * 4) report = triage_run.triage_run(logdir, shader_cache=cache_dir, max_items=16) @@ -77,6 +82,8 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "| 1 | `persistent_local_storage` | `0x80070005` |", "| 2 | `image_load_mip tfe` |", "| 1 | `compute: image_load_mip tfe` |", + "| 1 | `compute: runtime manifest: UAV kind texture_uav cube` |", + f"| 1 | `compute: {triage_run.OTHER}` |", f"| 1 | `{triage_run.OTHER}` |", ] for snippet in expected_snippets: @@ -122,6 +129,8 @@ def check_aggregation_and_redaction(failures: list[str]) -> None: "undecodable word at +0x10: AcmeTitle shader text", "image_load_mip tfe AcmeTitle", "image_load_mip tfe", + "native compute +0x1a: unsupported instruction v_acme_widget_7f3a 0xdeadbeefu", + "native compute +0x1c: AcmeTitle secret reason", ] PRIVATE_NEEDLES = [ "Acme", "acme", "ACME", "Private", "secret", "leak", "widget", "7f3a", "exploded", @@ -159,6 +168,10 @@ def check_private_text_never_echoed(failures: list[str]) -> None: ]: if want not in report: failures.append(f"missing grouped allowlist row: {want!r}") + if "| 4 | `other (text omitted)` |" not in report: + failures.append("unknown shader .fail lines were not grouped as other (text omitted)") + if "| 1 | `v_* instruction` |" not in report: + failures.append("native unsupported instruction .fail line was not grouped under its mnemonic family") if "| 1 | other (text omitted) | ? | ? | ? | ? | ? | ? |" not in report: failures.append("unknown slot70 reason/values were not grouped as other/?") @@ -203,8 +216,14 @@ def check_every_slot70_reason_is_reported(failures: list[str]) -> None: ("unsupported memory SRV arguments", "unsupported_description"), ("unsupported memory SRV arguments", "destination_outside_view_heaps"), ("GPU-written resource at the supplied address", "gpu_written_resource"), + ("unavailable acceleration structure at the supplied address", "as_unaligned"), + ("unavailable acceleration structure at the supplied address", "as_not_placed"), + ("unavailable acceleration structure at the supplied address", "as_wrong_state"), ("unavailable buffer at the supplied address", "buffer_unavailable"), ("unavailable texture at the supplied base and layout", "texture_unavailable"), + ("unavailable texture at the supplied base and layout", "texture_no_resource"), + ("unavailable texture at the supplied base and layout", "texture_unreadable"), + ("unavailable texture at the supplied base and layout", "texture_over_64mib"), ("unavailable texture at the supplied base and layout", "partial_tile_xg_rows"), ("unavailable texture at the supplied base and layout", "partial_tile_beyond_xg_size"), ("unavailable texture at the supplied base and layout", "unsupported_desktop_format"), @@ -224,6 +243,15 @@ def check_every_slot70_reason_is_reported(failures: list[str]) -> None: reported = sorted(key[0] for key in refusals) if reported != sorted(reasons): failures.append(f"slot70 reasons reported as {reported}, expected {sorted(reasons)}") + # The acceleration-structure names come from the header, so a new one cannot be forgotten here. + as_header = (Path(__file__).resolve().parent.parent / "src" / "startup_stubs" / "memory_srv_as.h").read_text(encoding="utf-8") + body = as_header.split("as_srv_refusal_name", 1)[1].split("}", 1)[0] + as_names = re.findall(r'return "(as_\w+)";', body) + if len(as_names) < 3: + failures.append(f"as_srv_refusal_name names not found in memory_srv_as.h: {as_names}") + for name in as_names: + if name not in triage_run.SLOT70_REASONS: + failures.append(f"SLOT70_REASONS lacks acceleration-structure refusal {name}") def check_empty_and_missing_dirs(failures: list[str]) -> None: @@ -479,6 +507,22 @@ def check_every_shader_reason_entry_is_reachable(failures: list[str]) -> None: # text changed, folds a known cause into "other" without failing anything else. The samples are # matched back to the table so a new entry without a sample fails here. samples = ( + ("native compute +0x14: unsupported instruction v_add3_u32 0xd76d0002u", "v_* instruction"), + ("native compute +0x8: unsupported opcode 0xdeadbeefu", "unsupported opcode"), + ("native compute +0x10: unsupported pixel entry VGPR 2", "unsupported pixel entry VGPR"), + ("unsupported startup runtime manifest bindings: SRV kind texture_srv 2d array", + "runtime manifest: SRV kind texture_srv 2d array"), + ("unsupported startup runtime manifest bindings: more than 8 UAVs", "runtime manifest: more than 8 UAVs"), + ("native compute +0x1c: unproven resource descriptor s12", "unproven resource descriptor"), + ("native compute +0x20: unbound numeric SGPR s0", "unbound numeric SGPR"), + ("unknown gfx1013 instruction format at byte 24", "undecodable word"), + ("graphics request key mismatch or missing root", "graphics request key mismatch"), + ("compute request key mismatch", "compute request key mismatch"), + ("stale pixel input description: graphics request key mismatch", "stale pixel input description"), + ("pixel input description names another pipeline", "pixel input description names another pipeline"), + ("contradictory pixel input enable/address masks", "contradictory pixel input enable/address masks"), + ("pixel input enable mask missing from the stream description", "invalid pixel input description"), + ("invalid pixel input description", "invalid pixel input description"), ("image_load_mip tfe", "image_load_mip tfe"), ("image_load_mip a16", "image_load_mip a16"), ("buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL", "buffer_* instruction"), @@ -562,12 +606,16 @@ def check_indirect_outcomes(failures: list[str]) -> None: def check_gpu_memory_budget(failures: list[str]) -> None: - def sample(local, texture): + def sample(local, texture, commit=""): return ( f'x2w-budget local={local} nonlocal=2/8 placed=10000/2+20000/3 texture={texture} ' - 'buffer=1/1+0/0 upload=0/0+0/0 readback=0/0+0/0 heap=0/0+0/0 unmeasured=0' + f'buffer=1/1+0/0 upload=0/0+0/0 readback=0/0+0/0 heap=0/0+0/0 unmeasured=0{commit}' ) + # The system commit and pool counters report_budget() appends (known, and unavailable). + with_commit = " commit=14335/16100 avail=1765 sections=113609 slabs=3 slots=113000/609 job_peak=14250 job_limit=14336" + commit_n_a = " commit=n/a avail=n/a sections=n/a slabs=n/a slots=n/a job_peak=n/a job_limit=none" + high_usage = sample("2500/3000", "100/5+40/2") high_ratio = sample("1800/1000", "150/7+50/3") high_retained = sample("n/a", "250/8+900/40").replace("nonlocal=2/8", "nonlocal=n/a") @@ -575,12 +623,14 @@ def sample(local, texture): sample("4000/1", "500/7+950/4").replace(" unmeasured=0", ""), sample("9000/1", "900/1+999/1").replace(" buffer=1/1+0/0", r" buffer=C:\Users\alice"), sample("9000/1", "900/1+999/1") + " path=secret.exe", + sample("9000/1", "900/1+999/1", " commit=14335/x avail=1765 sections=1 slabs=1 slots=1/1"), + sample("9000/1", "900/1+999/1", with_commit + " path=secret.exe"), ) with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) log = root / "stderr.txt" - samples = (high_usage, high_ratio, sample("2100/1800", "170/8+80/4"), high_retained, - sample("5000/0", "300/9+10/3"), sample("1000/1000", "90/6+20/1"), *malformed) + samples = (high_usage, high_ratio, sample("2100/1800", "170/8+80/4", with_commit), high_retained, + sample("5000/0", "300/9+10/3", commit_n_a), sample("1000/1000", "90/6+20/1"), *malformed) log.write_text("\n".join(samples), encoding="utf-8") (root / "trap.log").write_text(high_ratio + "\n", encoding="utf-8") report = triage_run.triage_run(root) diff --git a/tests/startup_triage_run_cli_check.py b/tests/startup_triage_run_cli_check.py new file mode 100644 index 0000000000..346be0e1bb --- /dev/null +++ b/tests/startup_triage_run_cli_check.py @@ -0,0 +1,393 @@ +#!/usr/bin/env python3 +"""Pure-Python synthetic log/cache CLI, validation, and mutation suite for tools/startup/triage_run.py.""" + +from __future__ import annotations + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_STARTUP = ROOT / "tools" / "startup" +TOOL = TOOLS_STARTUP / "triage_run.py" +sys.path.insert(0, str(TOOLS_STARTUP)) +import triage_run # noqa: E402 + + +SYNTHETIC_LOG = "\n".join([ + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " + "res{dim=1 fmt=0 size=4096x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} " + "view{dim=11 fmt=0 map=0x1688} dest=0x1 dest_in_view_heap=1 address=0x2 address_readable=0", + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x0 size=0x100 -> zlib failed", + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x100 size=0x100 -> read failed", + "x2w-runtime 12345678::slot5(0x1) -> 0x80004005 from +0x100", + "x2w-runtime 12345678::slot6(0x1) -> 0x80070005 from +0x200", + "x2w-runtime 12345678::slot7(0x1) -> 0x80070057 from +0x300", +]) + "\n" + + +def _run_main(module, argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = module.main(argv) + except SystemExit as exc: + code = exc.code + if not isinstance(code, int): + if code is not None: + stderr.write(f"{code}\n") + code = 0 if code is None else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class StartupTriageRunCliPositiveTests(unittest.TestCase): + def test_directory_logdir_with_shader_cache_and_max_items(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + (logdir / "nested").mkdir(parents=True) + (logdir / "stderr.txt").write_text(SYNTHETIC_LOG, encoding="utf-8") + # Mirrored trap.log line should be deduplicated against sibling stderr.txt. + (logdir / "trap.log").write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x0 size=0x100 -> zlib failed\n", + encoding="utf-8", + ) + (logdir / "nested" / "extra.out").write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x200 size=0x100 -> bcpack failed\n", + encoding="utf-8", + ) + # Non-log extension must be ignored. + (logdir / "ignored.json").write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x1000 source=0x1 offset=0x300 size=0x100 -> read failed\n", + encoding="utf-8", + ) + + cache_dir = root / "shader_cache" + cache_dir.mkdir() + (cache_dir / "0000000000000001.fail").write_text("image_load_mip tfe\n", encoding="utf-8") + (cache_dir / "0000000000000002.fail").write_text("image_load_mip tfe\n", encoding="utf-8") + (cache_dir / "0000000000000003.fail").write_text("image_load_mip a16\n", encoding="utf-8") + (cache_dir / "req_0000000000000003.c67").write_bytes(b"\0" * 4) + + argv = [str(logdir), "--shader-cache", str(cache_dir), "--max-items", "2"] + code, out, err = _run_main(triage_run, argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("## Startup Run Triage Summary", out) + self.assertIn("- Log files scanned: `3`", out) + self.assertIn("- `X2W_SHADER_CACHE` `.fail` shaders: `3` (2 unique reasons)", out) + self.assertIn("### `X2W_SHADER_CACHE` `.fail` Reasons", out) + self.assertIn("| 2 | `image_load_mip tfe` |", out) + self.assertIn("| 1 | `compute: image_load_mip a16` |", out) + self.assertIn("_Showing top 2 of 3 unique entries (3 total events)._", out) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(proc.stdout, out) + + def test_single_file_logdir_argv_none_and_main_entrypoint(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + single = root / "single.log" + single.write_text( + "x2w-dstorage options=0x1 dest=0x1 dest_size=0x10 source=0x1 offset=0x0 size=0x10 -> read failed\n", + encoding="utf-8", + ) + + with mock.patch.object(sys, "argv", [str(TOOL), str(single), "--max-items", "1"]): + code, out, err = _run_main(triage_run, None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("- Log files scanned: `1`", out) + self.assertIn("| 1 | read failed |", out) + self.assertNotIn("X2W_SHADER_CACHE", out) + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(single)]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr_m.getvalue(), "") + self.assertIn("| 1 | read failed |", stdout_m.getvalue()) + + +class StartupTriageRunCliNegativeTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(triage_run, argv) + if expected_code is None: + self.assertNotEqual(code, 0) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + for fragment in fragments: + self.assertIn(fragment.lower(), err.lower()) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + for fragment in fragments: + self.assertIn(fragment.lower(), proc.stderr.lower()) + return err + + def test_missing_and_non_regular_logdir_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing_log = root / "missing_logs" + non_regular = root / "special_entry" + + with mock.patch.object( + triage_run, + "triage_run", + side_effect=AssertionError("triage_run called for invalid logdir"), + ): + self._assert_clean_failure( + [str(missing_log)], + expected_code=1, + fragments=("log path not found",), + ) + + orig_exists = Path.exists + orig_is_file = Path.is_file + orig_is_dir = Path.is_dir + + def fake_exists(p: Path) -> bool: + return True if p == non_regular else orig_exists(p) + + def fake_is_file(p: Path) -> bool: + return False if p == non_regular else orig_is_file(p) + + def fake_is_dir(p: Path) -> bool: + return False if p == non_regular else orig_is_dir(p) + + with ( + mock.patch.object(Path, "exists", fake_exists), + mock.patch.object(Path, "is_file", fake_is_file), + mock.patch.object(Path, "is_dir", fake_is_dir), + ): + self._assert_clean_failure( + [str(non_regular)], + expected_code=1, + fragments=("regular file or directory",), + check_subprocess=False, + ) + + def test_missing_and_file_shader_cache_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + (logdir / "stderr.txt").write_text("", encoding="utf-8") + missing_cache = root / "missing_cache" + file_cache = root / "not_a_dir.txt" + file_cache.write_text("file contents", encoding="utf-8") + + with mock.patch.object( + triage_run, + "triage_run", + side_effect=AssertionError("triage_run called for invalid shader_cache"), + ): + self._assert_clean_failure( + [str(logdir), "--shader-cache", str(missing_cache)], + expected_code=1, + fragments=("shader cache directory not found",), + ) + self._assert_clean_failure( + [str(logdir), "--shader-cache", str(file_cache)], + expected_code=1, + fragments=("shader cache path is not a directory",), + ) + + def test_non_positive_max_items_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + + with mock.patch.object( + triage_run, + "triage_run", + side_effect=AssertionError("triage_run called for invalid --max-items"), + ): + for bad_value in ("0", "-1", "-100"): + with self.subTest(max_items=bad_value): + self._assert_clean_failure( + [str(logdir), "--max-items", bad_value], + expected_code=1, + fragments=("--max-items must be at least 1", bad_value), + ) + + def test_runtime_oserror_valueerror_and_main_exit_code_1_without_traceback(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + + for exc in (OSError("simulated I/O failure"), ValueError("simulated parse failure")): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(triage_run, "triage_run", side_effect=exc): + self._assert_clean_failure( + [str(logdir)], + expected_code=1, + fragments=(str(exc),), + check_subprocess=False, + ) + + stdout_m, stderr_m = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(root / "absent")]), + redirect_stdout(stdout_m), + redirect_stderr(stderr_m), + self.assertRaises(SystemExit) as exited, + ): + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 1) + self.assertEqual(stdout_m.getvalue(), "") + self.assertNotIn("Traceback", stderr_m.getvalue()) + self.assertIn("log path not found", stderr_m.getvalue().lower()) + + def test_argparse_errors_py314_safe(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + logdir = root / "logs" + logdir.mkdir() + + for argv, frags in ( + ([], ("required",)), + ([str(logdir), "--shader-cache"], ("expected one argument",)), + ([str(logdir), "--max-items"], ("expected one argument",)), + ([str(logdir), "--max-items", "abc"], ("invalid",)), + ([str(logdir), "--bogus-flag"], ("unrecognized",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid_logdir = root / "logs" + valid_logdir.mkdir() + (valid_logdir / "stderr.txt").write_text("", encoding="utf-8") + missing_log = root / "missing_logs" + non_regular = root / "special_entry" + missing_cache = root / "missing_cache" + file_cache = root / "file_cache.txt" + file_cache.write_text("not a dir", encoding="utf-8") + + mutations = [ + ( + "drop_logdir_exists_guard", + " if not args.logdir.exists():\n", + " if False:\n", + [str(missing_log)], + False, + "log path not found", + ), + ( + "drop_logdir_regular_or_dir_guard", + " if not (args.logdir.is_file() or args.logdir.is_dir()):\n", + " if False:\n", + [str(non_regular)], + True, + None, + ), + ( + "drop_shader_cache_exists_guard", + " if not args.shader_cache.exists():\n", + " if False:\n", + [str(valid_logdir), "--shader-cache", str(missing_cache)], + False, + "shader cache directory not found", + ), + ( + "drop_shader_cache_is_dir_guard", + " if not args.shader_cache.is_dir():\n", + " if False:\n", + [str(valid_logdir), "--shader-cache", str(file_cache)], + False, + None, + ), + ( + "allow_zero_max_items", + " if args.max_items < 1:\n", + " if args.max_items < 0:\n", + [str(valid_logdir), "--max-items", "0"], + False, + None, + ), + ] + + for label, target, replacement, argv, mock_non_regular, broken_fragment in mutations: + with self.subTest(mutation=label): + self.assertEqual(source.count(target), 1, target) + mutated = types.ModuleType(f"triage_run_mut_{label}") + mutated.__file__ = str(TOOL) + sys.modules[mutated.__name__] = mutated + try: + exec(compile(source.replace(target, replacement, 1), str(TOOL), "exec"), mutated.__dict__) + + if mock_non_regular: + orig_exists = Path.exists + orig_is_file = Path.is_file + orig_is_dir = Path.is_dir + with ( + mock.patch.object(Path, "exists", lambda p: True if p == non_regular else orig_exists(p)), + mock.patch.object(Path, "is_file", lambda p: False if p == non_regular else orig_is_file(p)), + mock.patch.object(Path, "is_dir", lambda p: False if p == non_regular else orig_is_dir(p)), + ): + code, _, err = _run_main(mutated, argv) + else: + code, _, err = _run_main(mutated, argv) + finally: + sys.modules.pop(mutated.__name__, None) + + if broken_fragment is None: + self.assertEqual(code, 0, f"mutation {label} unexpectedly failed: {err}") + else: + self.assertNotIn(broken_fragment, err.lower(), f"mutation {label} still emitted {broken_fragment!r}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/startup_ui_regression_matrix_check.py b/tests/startup_ui_regression_matrix_check.py new file mode 100644 index 0000000000..bed9200905 --- /dev/null +++ b/tests/startup_ui_regression_matrix_check.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Check tools/startup/ui_regression_matrix.py with a fake CTest executable. + +The fixture covers a full mixed matrix, a 77 capability skip, a failure, an +adapter-only selection, a custom filter and empty selections. It runs without +CMake, D3D12 or game files. +""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parent.parent +MATRIX = ROOT / "tools" / "startup" / "ui_regression_matrix.py" + +FAKE_CTEST = r'''#!/usr/bin/env python3 +"""Small CTest stand-in: list tests as JSON and write a CTest-shaped JUnit file.""" +import datetime +import json +import os +from pathlib import Path +import re +import sys +import xml.etree.ElementTree as ET + + +def option(args, name): + try: + return args[args.index(name) + 1] + except (ValueError, IndexError): + raise SystemExit("fake ctest: missing %s" % name) + + +args = sys.argv[1:] +scenario_path = Path(os.environ["UI_MATRIX_SCENARIO"]) +record_path = Path(os.environ["UI_MATRIX_INVOCATIONS"]) +tests = json.loads(scenario_path.read_text(encoding="utf-8"))["tests"] +exit_code = json.loads(scenario_path.read_text(encoding="utf-8")).get("exit_code") +with record_path.open("a", encoding="utf-8") as record: + record.write(json.dumps(args) + "\n") + +pattern = option(args, "-R") if "-R" in args else ".*" +selected = [test for test in tests if re.search(pattern, test["name"])] + +if "--show-only=json-v1" in args: + print(json.dumps({ + "kind": "ctestInfo", + "version": {"major": 3, "minor": 31, "patch": 0}, + "tests": [{"name": test["name"]} for test in selected], + })) + raise SystemExit(0) + +junit = Path(option(args, "--output-junit")) +if not selected: + print("No tests were found!!!", file=sys.stderr) + raise SystemExit(8) + +failures = sum(test.get("status") == "fail" for test in selected) +skips = sum(test.get("status") == "skip" for test in selected) +duration = sum(float(test.get("duration", 0)) for test in selected) +root = ET.Element("testsuite", { + "name": "fake-ctest", + "tests": str(len(selected)), + "failures": str(failures), + "errors": "0", + "skipped": str(skips), + "time": "%.3f" % duration, + "timestamp": datetime.datetime.now().astimezone().isoformat(timespec="seconds"), +}) +for test in selected: + status = test.get("status", "pass") + junit_status = "run" if status == "pass" else "fail" if status == "fail" else "notrun" + case = ET.SubElement(root, "testcase", { + "name": test["name"], + "status": junit_status, + "time": str(test.get("duration", 0)), + }) + detail = str(test.get("detail", "")) + if status in ("skip", "notrun"): + ET.SubElement(case, "skipped", {"message": detail or "SKIP_RETURN_CODE=77: skipped"}) + elif status == "fail": + ET.SubElement(case, "failure", {"message": detail or "failure"}).text = detail + +ET.ElementTree(root).write(junit, encoding="utf-8", xml_declaration=True) +print("%d tests ran" % len(selected)) +raise SystemExit(exit_code if exit_code is not None else (1 if failures else 0)) +''' + + +def test_case(name, status, detail="", duration=0.1): + return {"name": name, "status": status, "detail": detail, "duration": duration} + + +FULL_SCENARIO = { + "tests": [ + test_case("startup_sampler_heap_wrapped_warp", "pass", duration=0.2), + test_case( + "startup_sampler_heap_wrapped_hardware", + "skip", + "SKIP_RETURN_CODE=77: hardware adapter unavailable", + ), + test_case( + "startup_xg_bc7_draw_warp", + "fail", + "pixel (4, 0): read 000000ff, expected ff0000ff", + duration=1.5, + ), + test_case( + "startup_xg_bc7_draw_hardware", + "skip", + "SKIP_RETURN_CODE=77: D3D12 feature level 12 unavailable", + ), + test_case("startup_rect_gap_warp", "pass", duration=0.3), + test_case("startup_rect_gap_hardware", "skip", "SKIP_RETURN_CODE=77: no physical adapter"), + test_case("startup_ui_texture_bands_warp", "pass", duration=0.4), + test_case( + "startup_ui_texture_bands_hardware", + "skip", + "SKIP_RETURN_CODE=77: D3D12 debug layer unavailable", + ), + ] +} + + +class Fixture: + def __init__(self, root): + self.root = Path(root) + self.build = self.root / "build" + self.build.mkdir() + self.fake = self.root / "fake_ctest.py" + self.fake.write_text(FAKE_CTEST, encoding="utf-8") + self.serial = 0 + + def run(self, scenario, *extra, expect_outputs=True): + self.serial += 1 + stem = "matrix-%d" % self.serial + scenario_path = self.root / (stem + ".scenario.json") + invocations = self.root / (stem + ".invocations.jsonl") + output = self.root / (stem + ".md") + report = self.root / (stem + ".json") + scenario_path.write_text(json.dumps(scenario), encoding="utf-8") + env = dict(os.environ, UI_MATRIX_SCENARIO=str(scenario_path), + UI_MATRIX_INVOCATIONS=str(invocations)) + command = [ + sys.executable, "-B", str(MATRIX), + "--build-dir", str(self.build), + "--ctest", str(self.fake), + "--json", str(report), + "--output", str(output), + *extra, + ] + proc = subprocess.run( + command, + cwd=ROOT, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + errors="replace", + timeout=30, + ) + calls = [] + if invocations.is_file(): + calls = [json.loads(line) for line in invocations.read_text(encoding="utf-8").splitlines()] + if expect_outputs: + assert output.is_file(), proc.stderr + assert report.is_file(), proc.stderr + return proc, output, report, calls + + +def rows(markdown, names): + found = {} + for name in names: + matches = [line for line in markdown.splitlines() if name in line] + assert len(matches) == 1, (name, matches) + found[name] = matches[0] + return found + + +def main(): + with tempfile.TemporaryDirectory() as temporary: + fixture = Fixture(temporary) + names = [test["name"] for test in FULL_SCENARIO["tests"]] + + proc, output, report, calls = fixture.run(FULL_SCENARIO) + assert proc.returncode == 1, (proc.returncode, proc.stdout, proc.stderr) + assert len(calls) == 2, calls + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 8, "passed": 3, "skipped": 4, "failed": 1}, data + statuses = {item["name"]: item["status"] for item in data["tests"]} + assert statuses["startup_sampler_heap_wrapped_hardware"] == "skip", statuses + assert statuses["startup_xg_bc7_draw_warp"] == "fail", statuses + skipped = next(item for item in data["tests"] + if item["name"] == "startup_sampler_heap_wrapped_hardware") + assert "77" in skipped["detail"], skipped + markdown = output.read_text(encoding="utf-8") + table = rows(markdown, names) + assert "| PASS |" in table["startup_sampler_heap_wrapped_warp"], table + assert "| SKIP |" in table["startup_sampler_heap_wrapped_hardware"], table + assert "| FAIL |" in table["startup_xg_bc7_draw_warp"], table + assert "not a pass" in markdown, markdown + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_rect_gap_hardware$") + assert proc.returncode == 3, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 1, "passed": 0, "skipped": 1, "failed": 0}, data + assert "| SKIP |" in output.read_text(encoding="utf-8") + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_rect_gap_warp$") + assert proc.returncode == 0, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 1, "passed": 1, "skipped": 0, "failed": 0}, data + + proc, output, report, calls = fixture.run(FULL_SCENARIO, "--adapter", "warp") + assert proc.returncode == 1, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 4, "passed": 3, "skipped": 0, "failed": 1}, data + assert all(item["adapter"] == "warp" for item in data["tests"]), data + selected_run = calls[-1] + exact = selected_run[selected_run.index("-R") + 1] + assert "hardware" not in exact, exact + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_ui_texture_bands_") + assert proc.returncode == 3, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 2, "passed": 1, "skipped": 1, "failed": 0}, data + + proc, output, report, _ = fixture.run({"tests": []}, expect_outputs=False) + assert proc.returncode == 2, (proc.returncode, proc.stdout, proc.stderr) + assert "no CTest tests matched" in proc.stderr, proc.stderr + assert not output.exists() and not report.exists() + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_rect_gap_warp$", "--adapter", "hardware", + expect_outputs=False) + assert proc.returncode == 2, (proc.returncode, proc.stdout, proc.stderr) + assert "no CTest tests matched" in proc.stderr, proc.stderr + + proc, output, report, calls = fixture.run( + FULL_SCENARIO, "--filter", "", expect_outputs=False) + assert proc.returncode == 2, (proc.returncode, proc.stdout, proc.stderr) + assert "must not be empty" in proc.stderr, proc.stderr + assert not calls + + # A binary that was never built is not a capability skip. + proc, output, report, _ = fixture.run({ + "tests": [test_case("startup_ui_texture_bands_warp", "notrun", "Unable to find executable")] + }) + assert proc.returncode == 1, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 1, "passed": 0, "skipped": 0, "failed": 1}, data + assert data["tests"][0]["status"] == "fail", data + assert "Unable to find executable" in data["tests"][0]["detail"], data + assert "| FAIL |" in output.read_text(encoding="utf-8") + + # A nonzero CTest exit must not become exit 0 when every JUnit row says pass. + proc, output, report, _ = fixture.run({ + "tests": [test_case("startup_ui_texture_bands_warp", "pass")], + "exit_code": 8, + }) + assert proc.returncode == 1, (proc.returncode, proc.stdout, proc.stderr) + assert "without a failed test result" in proc.stderr, proc.stderr + + print("startup_ui_regression_matrix_check: ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/startup_ui_texture_bands_check.cpp b/tests/startup_ui_texture_bands_check.cpp new file mode 100644 index 0000000000..789ddc687d --- /dev/null +++ b/tests/startup_ui_texture_bands_check.cpp @@ -0,0 +1,1402 @@ +// Stage-by-stage trace and regression for horizontal alternating nonzero/black row bands +// on textured indexed UI draws (#3132). +// +// Usage: startup_ui_texture_bands_check warp|hardware +// Exit codes: 0 pass, 77 adapter unavailable, other nonzero test failure. +#include <windows.h> +#include <d3d12.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <algorithm> +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <cstring> +#include <vector> + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) HRESULT WINAPI XGCreateTextureComputer(const D3D12_RESOURCE_DESC*, void***, UINT64, UINT64); +extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_texture_stats(LONG* forwarded, LONG* refused); +extern "C" __declspec(dllimport) void x2w_d3d12_texture_written(void* base, unsigned long long bytes); + +namespace { +using Word = std::uint64_t; +template <class T> +Word arg(T* value) { return reinterpret_cast<Word>(value); } + +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, + Word e = 0, Word f = 0, Word g = 0, Word h = 0, Word i = 0, Word j = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e, f, g, h, i, j); +} + +bool ok(Word hr) { return SUCCEEDED(static_cast<HRESULT>(hr)); } + +constexpr UINT kWidth = 32; +constexpr UINT kHeight = 32; +constexpr UINT kMips = 3; + +struct UiVertex { + float x, y; + float u, v; +}; + +struct Rgba { + std::uint8_t r, g, b, a; + bool operator==(const Rgba& o) const { return r == o.r && g == o.g && b == o.b && a == o.a; } + bool operator!=(const Rgba& o) const { return !(*this == o); } + bool is_black() const { return r == 0 && g == 0 && b == 0 && a == 0; } +}; + +Rgba expected_texel(UINT mip, UINT x, UINT y) +{ + return { + static_cast<std::uint8_t>(24 + y * 6), + static_cast<std::uint8_t>(32 + x * 6), + static_cast<std::uint8_t>(64 + mip * 80), + 255, + }; +} + +Rgba expected_gradient(UINT x, UINT y) +{ + return { + static_cast<std::uint8_t>(16 + x * 6), + static_cast<std::uint8_t>(16 + y * 6), + 128, + 255, + }; +} + +std::uint64_t fnv_bytes(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + const auto* p = static_cast<const unsigned char*>(data); + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull; + return hash; +} + +std::uint64_t shader_key(const void* vs, std::size_t vs_bytes, const void* ps, std::size_t ps_bytes, + const void* root, std::size_t root_bytes) +{ + constexpr char rev[] = "x2w-startup-shader-29"; + auto h = fnv_bytes(rev, sizeof(rev) - 1); + h = fnv_bytes(vs, vs_bytes, h); + h = fnv_bytes(ps, ps_bytes, h); + return fnv_bytes(root, root_bytes, h); +} + +bool write_file_bytes(const wchar_t* path, const void* data, std::size_t bytes) +{ + HANDLE f = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (f == INVALID_HANDLE_VALUE) { + std::fprintf(stderr, "CreateFileW(%ls) failed err=%lu\n", path, GetLastError()); + return false; + } + DWORD written = 0; + const bool done = WriteFile(f, data, static_cast<DWORD>(bytes), &written, nullptr) && written == bytes; + if (!done) std::fprintf(stderr, "WriteFile(%ls) failed err=%lu written=%lu/%zu\n", path, GetLastError(), written, bytes); + CloseHandle(f); + return done; +} + +bool compile_hlsl(const char* source, const char* target, ComPtr<ID3DBlob>& blob) +{ + ComPtr<ID3DBlob> errors; + const HRESULT hr = D3DCompile(source, std::strlen(source), nullptr, nullptr, nullptr, "main", target, + D3DCOMPILE_OPTIMIZATION_LEVEL2, 0, &blob, &errors); + if (FAILED(hr)) { + std::fprintf(stderr, "D3DCompile(%s) failed 0x%08lx: %s\n", target, static_cast<unsigned long>(hr), + errors ? static_cast<const char*>(errors->GetBufferPointer()) : ""); + return false; + } + return true; +} + +bool publish_translated_pso(void* device, const wchar_t* cache_dir, const char* vs_hlsl, const char* ps_hlsl, + const char* manifest, void* root, const void* root_blob, std::size_t root_bytes, + void*& out_pso, HRESULT* out_hr = nullptr) +{ + if (out_hr) *out_hr = E_FAIL; + ComPtr<ID3DBlob> vs, ps; + if (!compile_hlsl(vs_hlsl, "vs_5_1", vs) || !compile_hlsl(ps_hlsl, "ps_5_1", ps)) return false; + + const auto key = shader_key(vs->GetBufferPointer(), vs->GetBufferSize(), + ps->GetBufferPointer(), ps->GetBufferSize(), + root_blob, root_bytes); + wchar_t vs_path[MAX_PATH], ps_path[MAX_PATH], txt_path[MAX_PATH]; + std::swprintf(vs_path, MAX_PATH, L"%s\\%016llx.vs.cso", cache_dir, static_cast<unsigned long long>(key)); + std::swprintf(ps_path, MAX_PATH, L"%s\\%016llx.ps.cso", cache_dir, static_cast<unsigned long long>(key)); + std::swprintf(txt_path, MAX_PATH, L"%s\\%016llx.txt", cache_dir, static_cast<unsigned long long>(key)); + if (!write_file_bytes(vs_path, vs->GetBufferPointer(), vs->GetBufferSize()) || + !write_file_bytes(ps_path, ps->GetBufferPointer(), ps->GetBufferSize()) || + !write_file_bytes(txt_path, manifest, std::strlen(manifest))) { + return false; + } + + struct alignas(8) Stage { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; D3D12_SHADER_BYTECODE code; }; + struct alignas(8) RootSub { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; void* root; }; + struct Stream { Stage ps; RootSub root; Stage vs; } stream{ + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps->GetBufferPointer(), ps->GetBufferSize()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs->GetBufferPointer(), vs->GetBufferSize()}}, + }; + const D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), &stream}; + const HRESULT hr = static_cast<HRESULT>(invoke(device, 86, arg(&stream_desc), arg(&__uuidof(ID3D12PipelineState)), arg(&out_pso))); + if (out_hr) *out_hr = hr; + if (FAILED(hr) || !out_pso) { + std::fprintf(stderr, "CreatePipelineState(slot 86) failed hr=0x%08lx out_pso=%p\n", + static_cast<unsigned long>(hr), out_pso); + return false; + } + return true; +} + +// Clean-room GFX10 thin non-XOR tiler for 32-bit texels (modes 0x105 = 4K_S, 0x10a = 64K_D) +// matching AMD addrlib GFX10 pattern tables (Mesa 25.1.0, MIT). +struct Gfx10Tiler { + UINT width = 0, height = 0, mips = 1, mode = 0x105; + UINT block_w = 0, block_h = 0, block_bytes = 0, first_tail = 0; + std::array<UINT, 15> start{}, blocks_wide{}, ox{}, oy{}; + std::array<UINT, 256> x_bits{}, y_bits{}; + UINT total_bytes = 0; + + void init(UINT w, UINT h, UINT m, UINT layout_mode) + { + width = w; height = h; mips = m; mode = layout_mode; + const UINT log2 = (layout_mode & 0xff) == 5 ? 12u : 16u; + block_bytes = 1u << log2; + const char* pat[16] = {}; + // For 4-byte elements, standard and display micro-block patterns are identical. + const char* micro[8] = {"0", "0", "X0", "X1", "Y0", "Y1", "Y2", "X2"}; + UINT nx = 3, ny = 3; + for (UINT b = 0; b < 8; ++b) pat[b] = micro[b]; + std::array<UINT, 8> x_at{}, y_at{}; + x_at[0] = 2; x_at[1] = 3; x_at[2] = 7; + y_at[0] = 4; y_at[1] = 5; y_at[2] = 6; + for (UINT b = 8; b < log2; ++b) { + if (b & 1) x_at[nx++] = b; + else y_at[ny++] = b; + } + block_w = 1u << nx; + block_h = 1u << ny; + for (UINT v = 0; v < 256; ++v) { + x_bits[v] = y_bits[v] = 0; + for (UINT bit = 0; bit < 8; ++bit) { + if (bit < nx && ((v >> bit) & 1)) x_bits[v] |= 1u << x_at[bit]; + if (bit < ny && ((v >> bit) & 1)) y_bits[v] |= 1u << y_at[bit]; + } + } + const UINT tail_mips = log2 - 4; + first_tail = mips; + for (UINT mip = 0; mips > 1 && mip < mips; ++mip) { + const UINT mw = (std::max)(1u, width >> mip); + const UINT mh = (std::max)(1u, height >> mip); + if (mw <= block_w / 2 && mh <= block_h && mips - mip <= tail_mips) { + first_tail = mip; + break; + } + } + UINT off = first_tail < mips ? block_bytes : 0; + for (UINT mip = first_tail; mip-- > 0;) { + const UINT mw = (std::max)(1u, width >> mip); + const UINT mh = (std::max)(1u, height >> mip); + blocks_wide[mip] = (mw + block_w - 1) / block_w; + start[mip] = off; + off += blocks_wide[mip] * ((mh + block_h - 1) / block_h) * block_bytes; + } + total_bytes = off; + for (UINT mip = first_tail; mip < mips; ++mip) { + const UINT idx = tail_mips - 1 - (mip - first_tail); + const UINT toff = idx > 6 ? 16u << idx : idx << 8; + UINT tx = 0, ty = 0; + for (UINT b = 0; b < 6; ++b) { + ty |= ((toff >> (8 + 2 * b)) & 1) << b; + tx |= ((toff >> (9 + 2 * b)) & 1) << b; + } + start[mip] = toff; + ox[mip] = tx * 8; + oy[mip] = ty * 8; + } + } + + UINT addr(UINT mip, UINT x, UINT y) const + { + if (mip >= first_tail) return x_bits[(ox[mip] + x) & 255] | y_bits[(oy[mip] + y) & 255]; + const UINT blk = (y / block_h) * blocks_wide[mip] + (x / block_w); + return start[mip] + blk * block_bytes + (x_bits[x % block_w] | y_bits[y % block_h]); + } +}; + +struct MemoryViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + Word address; + Word pad[2]; +}; + +void print_platform_header(IDXGIAdapter* adapter) +{ + using RtlGetVersionFn = LONG(WINAPI*)(OSVERSIONINFOW*); + OSVERSIONINFOW ver{sizeof(ver)}; + if (const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll")) { + const auto fn = reinterpret_cast<RtlGetVersionFn>(GetProcAddress(ntdll, "RtlGetVersion")); + if (fn) fn(&ver); + } + DXGI_ADAPTER_DESC desc{}; + LARGE_INTEGER driver{}; + adapter->GetDesc(&desc); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + char dbg[16]{}; + const bool debug_env = GetEnvironmentVariableA("X2W_D3D12_DEBUG", dbg, sizeof(dbg)) && dbg[0] != '0'; + std::printf("platform: Windows %lu.%lu.%lu adapter=\"%ls\" driver=%u.%u.%u.%u x2w_debug_env=%s\n", + ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber, desc.Description, + HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart), + debug_env ? "on" : "off"); +} + +int pick_adapter(const char* backend, ComPtr<IDXGIAdapter>& adapter) +{ + ComPtr<IDXGIFactory4> factory; + HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); + if (FAILED(hr)) { + std::fprintf(stderr, "FAIL CreateDXGIFactory1: hr=0x%08lx\n", static_cast<unsigned long>(hr)); + return 3; + } + if (std::strcmp(backend, "warp") == 0) { + hr = factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + if (FAILED(hr)) { + std::printf("skip: EnumWarpAdapter unavailable hr=0x%08lx (rc=77)\n", static_cast<unsigned long>(hr)); + return 77; + } + return 0; + } + if (std::strcmp(backend, "hardware") != 0) { + std::fprintf(stderr, "FAIL invalid backend '%s'\n", backend); + return 2; + } + ComPtr<IDXGIFactory6> factory6; + hr = factory.As(&factory6); + if (FAILED(hr)) { + std::printf("skip: IDXGIFactory6 unavailable hr=0x%08lx (rc=77)\n", static_cast<unsigned long>(hr)); + return 77; + } + for (UINT i = 0;; ++i) { + ComPtr<IDXGIAdapter1> cand; + hr = factory6->EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&cand)); + if (hr == DXGI_ERROR_NOT_FOUND) { + std::printf("skip: no physical D3D12 FL12_0 adapter found (rc=77)\n"); + return 77; + } + if (FAILED(hr)) { + std::fprintf(stderr, "FAIL EnumAdapterByGpuPreference(%u): hr=0x%08lx\n", i, static_cast<unsigned long>(hr)); + return 3; + } + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(cand->GetDesc1(&desc))) continue; + const bool is_basic_render = desc.VendorId == 0x1414 && desc.DeviceId == 0x008c; + if ((desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) || is_basic_render) continue; + if (SUCCEEDED(D3D12CreateDevice(cand.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = cand; + return 0; + } + } +} + +bool wait_fence(void* fence, UINT64 value) +{ + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) == value; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) +{ + return {D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; +} + +void* make_committed(void* device, D3D12_HEAP_TYPE heap_type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, + HRESULT* out_hr = nullptr) +{ + const D3D12_HEAP_PROPERTIES props{heap_type}; + void* out = nullptr; + const HRESULT hr = static_cast<HRESULT>(invoke(device, 127, arg(&props), D3D12_HEAP_FLAG_NONE, arg(&desc), state, + 0, 0, 0, 0, arg(&__uuidof(ID3D12Resource)), arg(&out))); + if (out_hr) *out_hr = hr; + if (FAILED(hr) || !out) return nullptr; + return out; +} + +void print_rows_summary(const char* tag, const Rgba* data, UINT pitch_texels, UINT w, UINT h, UINT max_rows = 6) +{ + std::printf(" %s (first %u rows at x=0,1):", tag, (std::min)(h, max_rows)); + for (UINT y = 0; y < (std::min)(h, max_rows); ++y) { + const Rgba p0 = data[y * pitch_texels + 0]; + const Rgba p1 = w > 1 ? data[y * pitch_texels + 1] : p0; + std::printf(" y%u=[(%u,%u,%u,%u),(%u,%u,%u,%u)]", y, p0.r, p0.g, p0.b, p0.a, p1.r, p1.g, p1.b, p1.a); + } + std::printf("\n"); +} + +bool find_first_texel_mismatch(const Rgba* actual, UINT pitch_texels, UINT mip, UINT w, UINT h, + UINT& bad_x, UINT& bad_y, Rgba& got, Rgba& exp) +{ + for (UINT y = 0; y < h; ++y) { + for (UINT x = 0; x < w; ++x) { + const Rgba g = actual[y * pitch_texels + x]; + const Rgba e = expected_texel(mip, x, y); + if (g != e) { + bad_x = x; bad_y = y; got = g; exp = e; + return true; + } + } + } + return false; +} + +bool has_alternating_black_bands(const Rgba* rows, UINT pitch_texels, UINT h) +{ + if (h < 4) return false; + bool even_nz = true, odd_black = true; + for (UINT y = 0; y < h; ++y) { + const bool blk = rows[y * pitch_texels].is_black(); + if (y % 2 == 0) even_nz &= !blk; + else odd_black &= blk; + } + return even_nz && odd_black; +} +bool check_xg_mip0_layout(ID3D12Device* desktop) +{ + std::printf("[Path 2c] Pin XG MipLevels==0 layout against desktop GetCopyableFootprints\n"); + using LayoutFn = HRESULT(WINAPI*)(void*, unsigned char*); + using CopyIntoFn = HRESULT(WINAPI*)(void*, unsigned char*, UINT, UINT, const unsigned char*, UINT, UINT); + using ReleaseFn = UINT64(WINAPI*)(void*); + auto read64 = [](const unsigned char* p) { + std::uint64_t v = 0; + std::memcpy(&v, p, sizeof(v)); + return v; + }; + auto read32 = [](const unsigned char* p) { + std::uint32_t v = 0; + std::memcpy(&v, p, sizeof(v)); + return v; + }; + + struct Case { + const char* name; + D3D12_RESOURCE_DIMENSION dim; + UINT width; + UINT height; + UINT16 depth_or_array; + UINT expected_mips; + bool verify_copy_into; + }; + const Case cases[] = { + {"32x32 2D MipLevels=0 (6 mips)", D3D12_RESOURCE_DIMENSION_TEXTURE2D, 32, 32, 1, 6, true}, + {"32x32x2 2D-Array MipLevels=0 (12 subresources)", D3D12_RESOURCE_DIMENSION_TEXTURE2D, 32, 32, 2, 6, true}, + {"32x8 2D MipLevels=0 (6 mips)", D3D12_RESOURCE_DIMENSION_TEXTURE2D, 32, 8, 1, 6, false}, + {"16x1x4 1D-Array MipLevels=0 (5 mips)", D3D12_RESOURCE_DIMENSION_TEXTURE1D, 16, 1, 4, 5, false}, + {"8x4x16 3D MipLevels=0 (5 mips)", D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 4, 16, 5, false}, + }; + + for (const auto& c : cases) { + const D3D12_RESOURCE_DESC xg_desc{c.dim, 0, c.width, c.height, c.depth_or_array, 0, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC ref_desc = xg_desc; + ref_desc.MipLevels = static_cast<UINT16>(c.expected_mips); + + std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, 15> fp{}; + std::array<UINT, 15> rows{}; + std::array<UINT64, 15> row_bytes{}; + UINT64 slice_total = 0; + desktop->GetCopyableFootprints(&ref_desc, 0, c.expected_mips, 0, fp.data(), rows.data(), row_bytes.data(), &slice_total); + const UINT64 expected_stride = (slice_total + 0xFFFFull) & ~0xFFFFull; + const bool volume = c.dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const UINT expected_slices = volume ? 1u : c.depth_or_array; + const UINT64 expected_total = expected_stride * expected_slices; + + void** computer = nullptr; + const HRESULT create_hr = XGCreateTextureComputer(&xg_desc, &computer, 0, 0); + if (FAILED(create_hr) || !computer) { + std::fprintf(stderr, " FAIL Path 2c (%s): XGCreateTextureComputer hr=0x%08lx\n", + c.name, static_cast<unsigned long>(create_hr)); + return false; + } + auto* tbl = static_cast<void**>(computer[0]); + std::array<unsigned char, 0x18 + 4 * 0x6c8 + 8> layout{}; + const HRESULT layout_hr = reinterpret_cast<LayoutFn>(tbl[2])(computer, layout.data()); + if (FAILED(layout_hr)) { + std::fprintf(stderr, " FAIL Path 2c (%s): computer_layout hr=0x%08lx\n", + c.name, static_cast<unsigned long>(layout_hr)); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + + const UINT64 got_total = read64(layout.data() + 0x00); + const UINT64 got_align = read64(layout.data() + 0x08); + const UINT32 got_mips = read32(layout.data() + 0x10); + const UINT32 got_planes = read32(layout.data() + 0x14); + const unsigned char* plane0 = layout.data() + 0x18; + const UINT64 got_plane_size = read64(plane0 + 0x08); + const UINT64 got_slice_stride = read64(plane0 + 0x10); + const UINT64 got_plane_align = read64(plane0 + 0x18); + const UINT64 expected_slice_stride = expected_slices > 1 ? expected_stride : 0; + + if (got_total != expected_total || got_align != 0x10000 || got_mips != c.expected_mips || got_planes != 1 || + got_plane_size != expected_total || got_slice_stride != expected_slice_stride || got_plane_align != 0x10000) { + std::fprintf(stderr, + " FAIL Path 2c (%s): header/plane mismatch total=0x%llx(exp 0x%llx) align=0x%llx mips=%u(exp %u) " + "planes=%u plane_size=0x%llx stride=0x%llx(exp 0x%llx)\n", + c.name, static_cast<unsigned long long>(got_total), static_cast<unsigned long long>(expected_total), + static_cast<unsigned long long>(got_align), got_mips, c.expected_mips, got_planes, + static_cast<unsigned long long>(got_plane_size), static_cast<unsigned long long>(got_slice_stride), + static_cast<unsigned long long>(expected_slice_stride)); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + + for (UINT m = 0; m < c.expected_mips; ++m) { + const unsigned char* mip = plane0 + 0x38 + m * 0x70; + const UINT64 exp_slice_size = UINT64{fp[m].Footprint.RowPitch} * rows[m]; + const UINT64 exp_size = exp_slice_size * fp[m].Footprint.Depth; + const UINT32 exp_depth = volume ? fp[m].Footprint.Depth : expected_slices; + if (read64(mip + 0x00) != exp_size || read64(mip + 0x08) != fp[m].Offset || + read64(mip + 0x10) != exp_slice_size || read32(mip + 0x18) != fp[m].Footprint.Width || + read32(mip + 0x1c) != fp[m].Footprint.RowPitch || + read32(mip + 0x20) != D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT || + read32(mip + 0x24) != fp[m].Footprint.Width || read32(mip + 0x28) != fp[m].Footprint.Height || + read32(mip + 0x2c) != exp_depth || read32(mip + 0x30) != fp[m].Footprint.Width || + read32(mip + 0x34) != fp[m].Footprint.Height || read32(mip + 0x38) != exp_depth || + read32(mip + 0x3c) != 1) { + std::fprintf(stderr, + " FAIL Path 2c (%s): mip %u mismatch off=0x%llx(exp 0x%llx) pitch=%u(exp %u) " + "size=0x%llx(exp 0x%llx) dims=%ux%ux%u(exp %ux%ux%u)\n", + c.name, m, static_cast<unsigned long long>(read64(mip + 0x08)), + static_cast<unsigned long long>(fp[m].Offset), read32(mip + 0x1c), fp[m].Footprint.RowPitch, + static_cast<unsigned long long>(read64(mip + 0x00)), static_cast<unsigned long long>(exp_size), + read32(mip + 0x18), read32(mip + 0x28), read32(mip + 0x2c), + fp[m].Footprint.Width, fp[m].Footprint.Height, exp_depth); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + } + + if (c.verify_copy_into) { + auto* mem = static_cast<unsigned char*>(VirtualAlloc(nullptr, static_cast<SIZE_T>(got_total), + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!mem) { + std::fprintf(stderr, " FAIL Path 2c (%s): VirtualAlloc(%llu) failed\n", + c.name, static_cast<unsigned long long>(got_total)); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + std::memset(mem, 0, static_cast<std::size_t>(got_total)); + for (UINT s = 0; s < expected_slices; ++s) { + for (UINT m = 0; m < c.expected_mips; ++m) { + const UINT w = fp[m].Footprint.Width; + const UINT h = fp[m].Footprint.Height; + const UINT sub = s * c.expected_mips + m; + std::vector<Rgba> lin(w * h); + for (UINT y = 0; y < h; ++y) { + for (UINT x = 0; x < w; ++x) { + lin[y * w + x] = {static_cast<std::uint8_t>(1 + x), + static_cast<std::uint8_t>(17 + y), + static_cast<std::uint8_t>(33 + m * 20), + static_cast<std::uint8_t>(100 + s * 50)}; + } + } + const HRESULT copy_hr = reinterpret_cast<CopyIntoFn>(tbl[8])( + computer, mem, 0, sub, reinterpret_cast<const unsigned char*>(lin.data()), w * 4, 0); + if (FAILED(copy_hr)) { + std::fprintf(stderr, " FAIL Path 2c (%s): CopyIntoSubresource(sub=%u) hr=0x%08lx\n", + c.name, sub, static_cast<unsigned long>(copy_hr)); + VirtualFree(mem, 0, MEM_RELEASE); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + } + } + const UINT total_subs = expected_slices * c.expected_mips; + std::array<unsigned char, 16> dummy{}; + const HRESULT oob_hr = reinterpret_cast<CopyIntoFn>(tbl[8])( + computer, mem, 0, total_subs, dummy.data(), 4, 0); + if (oob_hr != E_INVALIDARG) { + std::fprintf(stderr, " FAIL Path 2c (%s): out-of-range subresource %u returned 0x%08lx instead of E_INVALIDARG\n", + c.name, total_subs, static_cast<unsigned long>(oob_hr)); + VirtualFree(mem, 0, MEM_RELEASE); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + for (UINT s = 0; s < expected_slices; ++s) { + const UINT64 slice_base = UINT64{s} * expected_stride; + for (UINT m = 0; m < c.expected_mips; ++m) { + const UINT w = fp[m].Footprint.Width; + const UINT h = fp[m].Footprint.Height; + for (UINT y = 0; y < h; ++y) { + for (UINT x = 0; x < w; ++x) { + Rgba got{}; + std::memcpy(&got, mem + slice_base + fp[m].Offset + UINT64{y} * fp[m].Footprint.RowPitch + x * 4, 4); + const Rgba exp{static_cast<std::uint8_t>(1 + x), + static_cast<std::uint8_t>(17 + y), + static_cast<std::uint8_t>(33 + m * 20), + static_cast<std::uint8_t>(100 + s * 50)}; + if (got != exp) { + std::fprintf(stderr, " FAIL Path 2c (%s): slice=%u mip=%u (%u,%u) layout mismatch\n", + c.name, s, m, x, y); + VirtualFree(mem, 0, MEM_RELEASE); + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + return false; + } + } + } + } + } + VirtualFree(mem, 0, MEM_RELEASE); + } + reinterpret_cast<ReleaseFn>(tbl[1])(computer); + std::printf(" Path 2c (%s): PASS (mips=%u, total=0x%llx, stride=0x%llx)\n", + c.name, got_mips, static_cast<unsigned long long>(got_total), + static_cast<unsigned long long>(got_slice_stride)); + } + return true; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) { + std::fprintf(stderr, "usage: startup_ui_texture_bands_check warp|hardware\n"); + return 2; + } + SetEnvironmentVariableA("X2W_D3D12_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_D3D12_LIST_NOOP", "1"); + SetEnvironmentVariableA("X2W_D3D12_RENDER", "1"); + if (!GetEnvironmentVariableA("X2W_D3D12_DEBUG", nullptr, 0)) + SetEnvironmentVariableA("X2W_D3D12_DEBUG", "1"); + + wchar_t temp_root[MAX_PATH]{}, cache_dir[MAX_PATH]{}; + const DWORD temp_len = GetTempPathW(MAX_PATH, temp_root); + if (!temp_len || temp_len >= MAX_PATH) { + std::fprintf(stderr, "FAIL GetTempPathW: err=%lu (rc=3)\n", GetLastError()); + return 3; + } + const bool has_sep = temp_root[temp_len - 1] == L'\\' || temp_root[temp_len - 1] == L'/'; + std::swprintf(cache_dir, MAX_PATH, L"%s%sx2w_ui_bands_%lu", temp_root, has_sep ? L"" : L"\\", GetCurrentProcessId()); + if (!CreateDirectoryW(cache_dir, nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) { + std::fprintf(stderr, "FAIL CreateDirectoryW(%ls): err=%lu (rc=3)\n", cache_dir, GetLastError()); + return 3; + } + SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache_dir); + + auto cleanup_cache = [&] { + wchar_t pattern[MAX_PATH]; + std::swprintf(pattern, MAX_PATH, L"%s\\*", cache_dir); + WIN32_FIND_DATAW fd{}; + HANDLE h = FindFirstFileW(pattern, &fd); + if (h != INVALID_HANDLE_VALUE) { + do { + if (std::wcscmp(fd.cFileName, L".") != 0 && std::wcscmp(fd.cFileName, L"..") != 0) { + wchar_t f[MAX_PATH]; + std::swprintf(f, MAX_PATH, L"%s\\%s", cache_dir, fd.cFileName); + DeleteFileW(f); + } + } while (FindNextFileW(h, &fd)); + FindClose(h); + } + RemoveDirectoryW(cache_dir); + }; + auto fail_step = [&](const char* step, HRESULT hr, int rc) { + std::fflush(stdout); + std::fprintf(stderr, "FAIL %s: hr=0x%08lx (rc=%d)\n", step, static_cast<unsigned long>(hr), rc); + cleanup_cache(); + return rc; + }; + + ComPtr<IDXGIAdapter> adapter; + const int adapter_rc = pick_adapter(argv[1], adapter); + if (adapter_rc != 0) { + cleanup_cache(); + return adapter_rc; + } + print_platform_header(adapter.Get()); + + // Create the stand-in device first so X2W_D3D12_DEBUG=1 enables the debug layer before any ID3D12Device exists. + std::array<unsigned char, 64> params{}; + void* device = nullptr; + HRESULT hr = D3D12XboxCreateDevice(adapter.Get(), params.data(), __uuidof(ID3D12Device), &device); + if (FAILED(hr) || !device) { + return fail_step("D3D12XboxCreateDevice", hr, 5); + } + + ComPtr<ID3D12Device> desktop; + hr = D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)); + if (FAILED(hr)) { + invoke(device, 2); + return fail_step("D3D12CreateDevice(desktop)", hr, 77); + } + + // Guest root signature: [0] SRV descriptor table (1 entry at t1 for PS), matching runtime manifests. + // Note: translated VS/PS use d3d12_draw's create_translated_root(b0 constants, t0.. SRV table, s0.. static samplers). + const D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER root_param{}; + root_param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + root_param.DescriptorTable = {1, &srv_range}; + root_param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{1, &root_param, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> root_blob; + hr = D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &root_blob, nullptr); + if (FAILED(hr)) { + return fail_step("D3D12SerializeRootSignature", hr, 6); + } + void* guest_root = nullptr; + hr = static_cast<HRESULT>(invoke(device, 16, 0, arg(root_blob->GetBufferPointer()), root_blob->GetBufferSize(), + arg(&__uuidof(ID3D12RootSignature)), arg(&guest_root))); + if (FAILED(hr) || !guest_root) { + return fail_step("CreateRootSignature(slot 16)", hr, 7); + } + + // 1) Preceding gradient draw PSO (indexed quad, no texture) + const char* grad_vs = R"( +cbuffer Entry : register(b0) { uint basev; uint stride; }; +ByteAddressBuffer vb : register(t0); +struct Out { float4 pos : SV_Position; float2 uv : TEXCOORD0; }; +Out main(uint vid : SV_VertexID) { + uint off = (vid + basev) * stride; + float2 p = asfloat(vb.Load2(off)); + float2 uv = asfloat(vb.Load2(off + 8)); + Out o; o.pos = float4(p, 0.0, 1.0); o.uv = uv; return o; +})"; + const char* grad_ps = R"( +struct In { float4 pos : SV_Position; float2 uv : TEXCOORD0; }; +float4 main(In i) : SV_Target { + uint x = uint(i.pos.x); + uint y = uint(i.pos.y); + return float4(float(16 + x * 6) / 255.0, float(16 + y * 6) / 255.0, 128.0 / 255.0, 1.0); +})"; + const char* grad_manifest = "x2w-manifest 1\nud 2\nudsrc 0 basevertex\nudsrc 1 stride 0\nsrv 0 buf vb 0\n"; + + // 2) Textured indexed UI quad PSO (vertex buffer t0 via vb 0, Texture2D t1 via table 0 0, point-clamp sampler s0) + // w0 = 2|(2<<3)|(2<<6) = 0x92 -> CLAMP, filter=0 (POINT) + const char* tex_ps = R"( +Texture2D<float4> uiTex : register(t1); +SamplerState uiSmp : register(s0); +struct In { float4 pos : SV_Position; float2 uv : TEXCOORD0; }; +float4 main(In i) : SV_Target { + return uiTex.SampleLevel(uiSmp, i.uv, 0); +})"; + const char* tex_manifest = "x2w-manifest 1\nud 2\nudsrc 0 basevertex\nudsrc 1 stride 0\nsrv 0 buf vb 0\nsrv 1 tex2d table 0 0\nsmp 0 00000092 00000000 00000000 00000000\n"; + + void *grad_pso = nullptr, *tex_pso = nullptr; + HRESULT pso_hr = S_OK; + if (!publish_translated_pso(device, cache_dir, grad_vs, grad_ps, grad_manifest, guest_root, + root_blob->GetBufferPointer(), root_blob->GetBufferSize(), grad_pso, &pso_hr)) { + return fail_step("publish_translated_pso(grad_pso)", pso_hr, 8); + } + if (!publish_translated_pso(device, cache_dir, grad_vs, tex_ps, tex_manifest, guest_root, + root_blob->GetBufferPointer(), root_blob->GetBufferSize(), tex_pso, &pso_hr)) { + return fail_step("publish_translated_pso(tex_pso)", pso_hr, 8); + } + + // Render target & readbacks (using desktop resources for RT via wrapped RTV + guest resources for upload/readback) + const D3D12_RESOURCE_DESC rt_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, kWidth, kHeight, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + HRESULT res_hr = S_OK; + void* rt = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, rt_desc, D3D12_RESOURCE_STATE_COMMON, &res_hr); + if (!rt) return fail_step("make_committed(rt)", res_hr, 9); + + D3D12_PLACED_SUBRESOURCE_FOOTPRINT rt_fp{}; + UINT rt_rows = 0; + UINT64 rt_row_bytes = 0, rt_total = 0; + desktop->GetCopyableFootprints(&rt_desc, 0, 1, 0, &rt_fp, &rt_rows, &rt_row_bytes, &rt_total); + void* rt_readback = make_committed(device, D3D12_HEAP_TYPE_READBACK, buffer_desc(rt_total), + D3D12_RESOURCE_STATE_COPY_DEST, &res_hr); + if (!rt_readback) return fail_step("make_committed(rt_readback)", res_hr, 10); + + const struct { D3D12_DESCRIPTOR_HEAP_DESC d; Word b, s; } rtv_hdesc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* rtv_heap = nullptr; + hr = static_cast<HRESULT>(invoke(device, 14, arg(&rtv_hdesc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&rtv_heap))); + if (FAILED(hr) || !rtv_heap) return fail_step("CreateDescriptorHeap(rtv)", hr, 10); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast<SIZE_T>(invoke(rtv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_desc{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(device, 20, arg(rt), arg(&rtv_desc), rtv.ptr); + + const UINT desc_inc = static_cast<UINT>(invoke(device, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + std::vector<unsigned char> view_shadow(16 * desc_inc, 0); + const struct { D3D12_DESCRIPTOR_HEAP_DESC d; Word b, s; } srv_hdesc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + arg(view_shadow.data()), view_shadow.size()}; + void* srv_heap = nullptr; + hr = static_cast<HRESULT>(invoke(device, 14, arg(&srv_hdesc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&srv_heap))); + if (FAILED(hr) || !srv_heap) return fail_step("CreateDescriptorHeap(srv)", hr, 11); + const Word srv_cpu0 = invoke(srv_heap, 9); + const Word srv_gpu0 = invoke(srv_heap, 10); + + D3D12_COMMAND_QUEUE_DESC qd{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *alloc = nullptr, *list = nullptr, *fence = nullptr; + hr = static_cast<HRESULT>(invoke(device, 8, arg(&qd), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))); + if (FAILED(hr) || !queue) return fail_step("CreateCommandQueue(slot 8)", hr, 12); + hr = static_cast<HRESULT>(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&alloc))); + if (FAILED(hr) || !alloc) return fail_step("CreateCommandAllocator(slot 9)", hr, 12); + hr = static_cast<HRESULT>(invoke(device, 73, arg(list_desc), arg(alloc), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list))); + if (FAILED(hr) || !list) return fail_step("CreateCommandList(slot 73)", hr, 12); + hr = static_cast<HRESULT>(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))); + if (FAILED(hr) || !fence) return fail_step("CreateFence(slot 36)", hr, 12); + Word fence_val = 0; + + // Indexed quad vertices (full 32x32 target, top-down UV [0,1]x[0,1]) + static const UiVertex quad_verts[4] = { + {-1.0f, 1.0f, 0.0f, 0.0f}, + { 1.0f, 1.0f, 1.0f, 0.0f}, + { 1.0f, -1.0f, 1.0f, 1.0f}, + {-1.0f, -1.0f, 0.0f, 1.0f}, + }; + static const std::uint16_t quad_indices[6] = {0, 1, 2, 0, 2, 3}; + const D3D12_VERTEX_BUFFER_VIEW vbv{reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(quad_verts), sizeof(quad_verts), sizeof(UiVertex)}; + const D3D12_INDEX_BUFFER_VIEW ibv{reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(quad_indices), sizeof(quad_indices), DXGI_FORMAT_R16_UINT}; + + const D3D12_RESOURCE_DESC mip_desc_3{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, kWidth, kHeight, 1, kMips, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, + D3D12_RESOURCE_FLAG_NONE}; + std::array<D3D12_PLACED_SUBRESOURCE_FOOTPRINT, kMips> mip_fp{}; + std::array<UINT, kMips> mip_rows{}; + std::array<UINT64, kMips> mip_row_bytes{}; + UINT64 mip_total = 0; + desktop->GetCopyableFootprints(&mip_desc_3, 0, kMips, 0, mip_fp.data(), mip_rows.data(), mip_row_bytes.data(), &mip_total); + + std::printf("generated 32x32 3-mip RGBA8 source (mip0 row_bytes=%llu, desktop RowPitch=%u, total=%llu):\n", + static_cast<unsigned long long>(mip_row_bytes[0]), mip_fp[0].Footprint.RowPitch, + static_cast<unsigned long long>(mip_total)); + std::vector<Rgba> gen_preview(kWidth * 6); + for (UINT y = 0; y < 6; ++y) + for (UINT x = 0; x < kWidth; ++x) gen_preview[y * kWidth + x] = expected_texel(0, x, y); + print_rows_summary("cpu mip0", gen_preview.data(), kWidth, kWidth, 6); + + auto readback_rt = [&](std::vector<Rgba>& out, UINT& pitch_texels) -> bool { + out.assign(static_cast<std::size_t>(rt_total / 4), {0, 0, 0, 0}); + pitch_texels = rt_fp.Footprint.RowPitch / 4; + if (!ok(invoke(alloc, 8)) || !ok(invoke(list, 139, arg(alloc), 0))) return false; + D3D12_TEXTURE_COPY_LOCATION dst_loc{static_cast<ID3D12Resource*>(rt_readback), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst_loc.PlacedFootprint = rt_fp; + D3D12_TEXTURE_COPY_LOCATION src_loc{static_cast<ID3D12Resource*>(rt), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + invoke(list, 16, arg(&dst_loc), 0, 0, 0, arg(&src_loc), 0); + if (!ok(invoke(list, 9))) return false; + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_val)) || !wait_fence(fence, fence_val)) return false; + void* mapped = nullptr; + if (!ok(invoke(rt_readback, 8, 0, 0, arg(&mapped))) || !mapped) return false; + std::memcpy(out.data(), mapped, static_cast<std::size_t>(rt_total)); + invoke(rt_readback, 9, 0, 0); + return true; + }; + + auto readback_texture_mips = [&](void* guest_tex, std::vector<std::vector<Rgba>>& mips_out) -> bool { + void* rb = make_committed(device, D3D12_HEAP_TYPE_READBACK, buffer_desc(mip_total), D3D12_RESOURCE_STATE_COPY_DEST); + if (!rb) return false; + if (!ok(invoke(alloc, 8)) || !ok(invoke(list, 139, arg(alloc), 0))) { invoke(rb, 2); return false; } + for (UINT m = 0; m < kMips; ++m) { + D3D12_TEXTURE_COPY_LOCATION dst_loc{static_cast<ID3D12Resource*>(rb), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst_loc.PlacedFootprint = mip_fp[m]; + D3D12_TEXTURE_COPY_LOCATION src_loc{static_cast<ID3D12Resource*>(guest_tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src_loc.SubresourceIndex = m; + invoke(list, 16, arg(&dst_loc), 0, 0, 0, arg(&src_loc), 0); + } + if (!ok(invoke(list, 9))) { invoke(rb, 2); return false; } + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_val)) || !wait_fence(fence, fence_val)) { invoke(rb, 2); return false; } + void* mapped = nullptr; + if (!ok(invoke(rb, 8, 0, 0, arg(&mapped))) || !mapped) { invoke(rb, 2); return false; } + const auto* base = static_cast<const unsigned char*>(mapped); + mips_out.resize(kMips); + for (UINT m = 0; m < kMips; ++m) { + const UINT pitch = mip_fp[m].Footprint.RowPitch / 4; + mips_out[m].resize(static_cast<std::size_t>(pitch) * mip_rows[m]); + std::memcpy(mips_out[m].data(), base + mip_fp[m].Offset, static_cast<std::size_t>(pitch) * 4 * mip_rows[m]); + } + invoke(rb, 9, 0, 0); + invoke(rb, 2); + return true; + }; + + auto draw_gradient_then_ui = [&](Word srv_gpu, const char* case_name, UINT view_mip) -> bool { + if (!ok(invoke(alloc, 8)) || !ok(invoke(list, 139, arg(alloc), 0))) return false; + const float clear[] = {0, 0, 0, 0}; + const D3D12_VIEWPORT vp{0, 0, static_cast<float>(kWidth), static_cast<float>(kHeight), 0, 1}; + const D3D12_RECT sc{0, 0, static_cast<LONG>(kWidth), static_cast<LONG>(kHeight)}; + invoke(list, 52, rtv.ptr, arg(clear)); + invoke(list, 50, 1, arg(&rtv)); + invoke(list, 21, 1, arg(&vp)); + invoke(list, 22, 1, arg(&sc)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 32, 1, arg(&srv_heap)); + invoke(list, 48, 0, 1, arg(&vbv)); + invoke(list, 47, arg(&ibv)); + // 1) Separate indexed gradient draw first + invoke(list, 25, arg(grad_pso)); + invoke(list, 13, 6, 1, 0, 0, 0); + if (!ok(invoke(list, 9))) return false; + void* lists1[] = {list}; + invoke(queue, 10, 1, arg(lists1)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_val)) || !wait_fence(fence, fence_val)) return false; + + std::vector<Rgba> pre_px; + UINT pre_pitch = 0; + if (!readback_rt(pre_px, pre_pitch)) return false; + for (UINT y = 0; y < kHeight; ++y) { + for (UINT x = 0; x < kWidth; ++x) { + if (pre_px[y * pre_pitch + x] != expected_gradient(x, y)) { + std::fprintf(stderr, "FAIL %s: pre-draw gradient mismatch at (%u,%u)\n", case_name, x, y); + return false; + } + } + } + + // 2) Textured indexed UI quad draw over the gradient + if (!ok(invoke(alloc, 8)) || !ok(invoke(list, 139, arg(alloc), 0))) return false; + invoke(list, 50, 1, arg(&rtv)); + invoke(list, 21, 1, arg(&vp)); + invoke(list, 22, 1, arg(&sc)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 32, 1, arg(&srv_heap)); + invoke(list, 36, 0, srv_gpu); + invoke(list, 48, 0, 1, arg(&vbv)); + invoke(list, 47, arg(&ibv)); + invoke(list, 25, arg(tex_pso)); + invoke(list, 13, 6, 1, 0, 0, 0); + if (!ok(invoke(list, 9))) return false; + invoke(queue, 10, 1, arg(lists1)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_val)) || !wait_fence(fence, fence_val)) return false; + (void)view_mip; + return true; + }; + + auto verify_rt_for_mip = [&](const char* name, UINT mip, bool expect_pass, bool expect_bands) -> bool { + std::vector<Rgba> px; + UINT pitch = 0; + if (!readback_rt(px, pitch)) return false; + const UINT mw = kWidth >> mip, mh = kHeight >> mip; + // Print sample coordinates, UV and neighboring row RGBA + const Rgba row0 = px[0 * pitch + 0]; + const Rgba row1 = px[1 * pitch + 0]; + const double u0 = 0.5 / kWidth; + const double v0 = 0.5 / kHeight; + const double v1 = 1.5 / kHeight; + std::printf(" %s (view_mip=%u): uv(0,0)=(%.5f,%.5f) uv(0,1)=(%.5f,%.5f) final_rgba[y0]=(%u,%u,%u,%u) final_rgba[y1]=(%u,%u,%u,%u)\n", + name, mip, u0, v0, u0, v1, row0.r, row0.g, row0.b, row0.a, row1.r, row1.g, row1.b, row1.a); + print_rows_summary("post-ui rt", px.data(), pitch, kWidth, kHeight); + const bool banded = has_alternating_black_bands(px.data(), pitch, kHeight); + UINT bad_x = 0, bad_y = 0; + Rgba got{}, exp{}; + bool any_bad = false; + for (UINT y = 0; y < kHeight; ++y) { + const UINT sy = (y * mh) / kHeight; + for (UINT x = 0; x < kWidth; ++x) { + const UINT sx = (x * mw) / kWidth; + const Rgba e = expected_texel(mip, sx, sy); + const Rgba g = px[y * pitch + x]; + if (g != e) { + bad_x = x; bad_y = y; got = g; exp = e; any_bad = true; + break; + } + } + if (any_bad) break; + } + if (any_bad) { + std::printf(" %s (view_mip=%u): first sample mismatch at (%u,%u) got=(%u,%u,%u,%u) expected=(%u,%u,%u,%u) alternating_black_bands=%s\n", + name, mip, bad_x, bad_y, got.r, got.g, got.b, got.a, exp.r, exp.g, exp.b, exp.a, + banded ? "YES" : "NO"); + } else { + std::printf(" %s (view_mip=%u): ALL %u pixels exact\n", name, mip, kWidth * kHeight); + } + if (expect_pass && any_bad) return false; + if (expect_bands && (!any_bad || !banded)) return false; + return true; + }; + + auto make_srv18 = [&](void* tex, UINT slot_idx, UINT most_detailed_mip, UINT mip_levels) -> Word { + 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.MostDetailedMip = most_detailed_mip; + srv.Texture2D.MipLevels = mip_levels; + invoke(device, 18, arg(tex), arg(&srv), srv_cpu0 + Word{slot_idx} * desc_inc); + return srv_gpu0 + Word{slot_idx} * desc_inc; + }; + + // Helper for filling a desktop-footprint buffer + auto fill_linear_footprints = [&](unsigned char* dst) { + for (UINT m = 0; m < kMips; ++m) { + const UINT w = kWidth >> m, h = kHeight >> m; + for (UINT y = 0; y < h; ++y) { + for (UINT x = 0; x < w; ++x) { + const Rgba t = expected_texel(m, x, y); + std::memcpy(dst + mip_fp[m].Offset + y * mip_fp[m].Footprint.RowPitch + x * 4, &t, 4); + } + } + } + }; + + // ========================================================================= + // PATH 1: Linear Reference (CopyTextureRegion list slot 16) + // ========================================================================= + bool all_ok = true; + int first_fail_rc = 0; + auto record_fail = [&](int rc) { + all_ok = false; + if (!first_fail_rc) first_fail_rc = rc; + }; + + std::printf("[Path 1] Linear Reference (CopyTextureRegion slot 16 -> committed & placed DEFAULT textures)\n"); + { + HRESULT step_hr = S_OK; + void* tex = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, mip_desc_3, D3D12_RESOURCE_STATE_COMMON, &step_hr); + if (!tex) return fail_step("Path 1 make_committed(tex)", step_hr, 20); + void* up = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(mip_total), D3D12_RESOURCE_STATE_GENERIC_READ, &step_hr); + if (!up) return fail_step("Path 1 make_committed(up)", step_hr, 20); + void* mapped = nullptr; + step_hr = static_cast<HRESULT>(invoke(up, 8, 0, 0, arg(&mapped))); + if (FAILED(step_hr) || !mapped) return fail_step("Path 1 Map(up)", step_hr, 21); + std::memset(mapped, 0, static_cast<std::size_t>(mip_total)); + fill_linear_footprints(static_cast<unsigned char*>(mapped)); + invoke(up, 9, 0, 0); + + step_hr = static_cast<HRESULT>(invoke(alloc, 8)); + if (FAILED(step_hr)) return fail_step("Path 1 CommandAllocator::Reset", step_hr, 22); + step_hr = static_cast<HRESULT>(invoke(list, 139, arg(alloc), 0)); + if (FAILED(step_hr)) return fail_step("Path 1 CommandList::Reset", step_hr, 22); + for (UINT m = 0; m < kMips; ++m) { + D3D12_TEXTURE_COPY_LOCATION to{static_cast<ID3D12Resource*>(tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + to.SubresourceIndex = m; + D3D12_TEXTURE_COPY_LOCATION from{static_cast<ID3D12Resource*>(up), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + from.PlacedFootprint = mip_fp[m]; + invoke(list, 16, arg(&to), 0, 0, 0, arg(&from), 0); + } + step_hr = static_cast<HRESULT>(invoke(list, 9)); + if (FAILED(step_hr)) return fail_step("Path 1 CommandList::Close", step_hr, 23); + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + step_hr = static_cast<HRESULT>(invoke(queue, 14, arg(fence), ++fence_val)); + if (FAILED(step_hr) || !wait_fence(fence, fence_val)) return fail_step("Path 1 Signal/Wait", step_hr, 24); + + std::vector<std::vector<Rgba>> rb_mips; + if (!readback_texture_mips(tex, rb_mips)) return fail_step("Path 1 readback_texture_mips", E_FAIL, 25); + print_rows_summary("gpu texels mip0", rb_mips[0].data(), mip_fp[0].Footprint.RowPitch / 4, kWidth, kHeight); + for (UINT m = 0; m < kMips; ++m) { + UINT bx = 0, by = 0; Rgba g{}, e{}; + if (find_first_texel_mismatch(rb_mips[m].data(), mip_fp[m].Footprint.RowPitch / 4, m, kWidth >> m, kHeight >> m, bx, by, g, e)) { + std::fprintf(stderr, "FAIL Path 1: GPU texel mismatch mip%u (%u,%u)\n", m, bx, by); + record_fail(26); + } + } + for (UINT m = 0; m < kMips; ++m) { + const Word gpu = make_srv18(tex, 0, m, kMips - m); + if (!draw_gradient_then_ui(gpu, "Path 1", m) || !verify_rt_for_mip("Path 1", m, true, false)) { + record_fail(27); + } + } + invoke(up, 2); + invoke(tex, 2); + } + + // Path 1b: CopyTextureRegion (slot 16) into a slot-133 placed texture whose title_memory holds zeros, + // then advance 16 frames + mutate title_memory to confirm GPU-written state is preserved across rechecks. + std::printf("[Path 1b] CopyTextureRegion into slot-133 texture preserves GPU writes across title_memory mutation\n"); + { + auto* backing = static_cast<unsigned char*>(VirtualAlloc(nullptr, static_cast<SIZE_T>(mip_total), + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + std::memset(backing, 0, static_cast<std::size_t>(mip_total)); + HRESULT step_hr = S_OK; + void* tex = nullptr; + step_hr = static_cast<HRESULT>(invoke(device, 133, arg(backing), arg(&mip_desc_3), D3D12_RESOURCE_STATE_COMMON, + 0, arg(&__uuidof(ID3D12Resource)), arg(&tex))); + if (FAILED(step_hr) || !tex) { + VirtualFree(backing, 0, MEM_RELEASE); + return fail_step("Path 1b place_resource_x(slot 133)", step_hr, 28); + } + void* up = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(mip_total), D3D12_RESOURCE_STATE_GENERIC_READ, &step_hr); + if (!up) { + invoke(tex, 2); + VirtualFree(backing, 0, MEM_RELEASE); + return fail_step("Path 1b make_committed(up)", step_hr, 28); + } + void* mapped = nullptr; + step_hr = static_cast<HRESULT>(invoke(up, 8, 0, 0, arg(&mapped))); + if (FAILED(step_hr) || !mapped) { + invoke(up, 2); invoke(tex, 2); VirtualFree(backing, 0, MEM_RELEASE); + return fail_step("Path 1b Map(up)", step_hr, 28); + } + fill_linear_footprints(static_cast<unsigned char*>(mapped)); + invoke(up, 9, 0, 0); + + step_hr = static_cast<HRESULT>(invoke(alloc, 8)); + if (FAILED(step_hr)) { invoke(up, 2); invoke(tex, 2); VirtualFree(backing, 0, MEM_RELEASE); return fail_step("Path 1b CommandAllocator::Reset", step_hr, 28); } + step_hr = static_cast<HRESULT>(invoke(list, 139, arg(alloc), 0)); + if (FAILED(step_hr)) { invoke(up, 2); invoke(tex, 2); VirtualFree(backing, 0, MEM_RELEASE); return fail_step("Path 1b CommandList::Reset", step_hr, 28); } + for (UINT m = 0; m < kMips; ++m) { + D3D12_TEXTURE_COPY_LOCATION to{static_cast<ID3D12Resource*>(tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + to.SubresourceIndex = m; + D3D12_TEXTURE_COPY_LOCATION from{static_cast<ID3D12Resource*>(up), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + from.PlacedFootprint = mip_fp[m]; + invoke(list, 16, arg(&to), 0, 0, 0, arg(&from), 0); + } + step_hr = static_cast<HRESULT>(invoke(list, 9)); + if (FAILED(step_hr)) { invoke(up, 2); invoke(tex, 2); VirtualFree(backing, 0, MEM_RELEASE); return fail_step("Path 1b CommandList::Close", step_hr, 28); } + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + step_hr = static_cast<HRESULT>(invoke(queue, 14, arg(fence), ++fence_val)); + if (FAILED(step_hr) || !wait_fence(fence, fence_val)) { + invoke(up, 2); invoke(tex, 2); VirtualFree(backing, 0, MEM_RELEASE); + return fail_step("Path 1b Signal/Wait", step_hr, 28); + } + + // Mutate backing memory with distinct non-zero bytes and advance >15 frames so CPU recheck would + // overwrite the CopyTextureRegion result unless list_copy_texture marked the texture GPU-written. + std::memset(backing, 0x5A, static_cast<std::size_t>(mip_total)); + for (int f = 0; f < 16; ++f) invoke(queue, 32, 0, 0, 0); + const Word gpu = make_srv18(tex, 0, 0, kMips); + if (!draw_gradient_then_ui(gpu, "Path 1b", 0) || !verify_rt_for_mip("Path 1b", 0, true, false)) { + std::fprintf(stderr, "FAIL Path 1b: CopyTextureRegion destination was overwritten from stale title_memory\n"); + record_fail(29); + } + invoke(up, 2); + invoke(tex, 2); + VirtualFree(backing, 0, MEM_RELEASE); + } + + // ========================================================================= + // PATH 2: XGCreateTextureComputer (Alignment = 0, Layout = UNKNOWN) + // ========================================================================= + auto run_xg_footprint_path = [&](const char* label, UINT desc_mips) -> bool { + std::printf("%s\n", label); + auto desc = mip_desc_3; + desc.MipLevels = static_cast<UINT16>(desc_mips); + void** computer = nullptr; + if (FAILED(XGCreateTextureComputer(&desc, &computer, 0, 0)) || !computer) return false; + auto* tbl = static_cast<void**>(computer[0]); + using LayoutFn = HRESULT (WINAPI*)(void*, unsigned char*); + using CopyIntoFn = HRESULT (WINAPI*)(void*, unsigned char*, UINT, UINT, const unsigned char*, UINT, UINT); + std::array<unsigned char, 0x18 + 4 * 0x6c8 + 8> layout{}; + if (FAILED(reinterpret_cast<LayoutFn>(tbl[2])(computer, layout.data()))) return false; + UINT64 total_bytes = 0; UINT32 reported_mips = 0; + std::memcpy(&total_bytes, layout.data() + 0x00, 8); + std::memcpy(&reported_mips, layout.data() + 0x10, 4); + const UINT expected_mips = desc_mips ? desc_mips : 6u; // 32x32 full chain = 6 mips + std::printf(" XG slot 2 reported_mips=%u (expected %u) total=0x%llx\n", reported_mips, expected_mips, + static_cast<unsigned long long>(total_bytes)); + if (reported_mips < kMips || total_bytes < mip_total) { + std::fprintf(stderr, " FAIL %s: XG reported %u mips instead of >=%u\n", label, reported_mips, kMips); + reinterpret_cast<UINT64 (WINAPI*)(void*)>(tbl[1])(computer); + return false; + } + auto* mem = static_cast<unsigned char*>(VirtualAlloc(nullptr, static_cast<SIZE_T>(total_bytes), + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + std::memset(mem, 0, static_cast<std::size_t>(total_bytes)); + for (UINT m = 0; m < kMips; ++m) { + const UINT w = kWidth >> m, h = kHeight >> m; + std::vector<Rgba> lin(w * h); + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) lin[y * w + x] = expected_texel(m, x, y); + const HRESULT hr = reinterpret_cast<CopyIntoFn>(tbl[8])(computer, mem, 0, m, + reinterpret_cast<const unsigned char*>(lin.data()), w * 4, 0); + if (FAILED(hr)) { + std::fprintf(stderr, " FAIL %s: XG slot 8 subresource %u returned 0x%08lx\n", + label, m, static_cast<unsigned long>(hr)); + reinterpret_cast<UINT64 (WINAPI*)(void*)>(tbl[1])(computer); + VirtualFree(mem, 0, MEM_RELEASE); + return false; + } + } + reinterpret_cast<UINT64 (WINAPI*)(void*)>(tbl[1])(computer); + + void* tex = nullptr; + if (!ok(invoke(device, 133, arg(mem), arg(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, arg(&__uuidof(ID3D12Resource)), arg(&tex))) || !tex) { + VirtualFree(mem, 0, MEM_RELEASE); + return false; + } + for (UINT m = 0; m < kMips; ++m) { + const Word gpu = make_srv18(tex, 0, m, kMips - m); + if (!draw_gradient_then_ui(gpu, label, m) || !verify_rt_for_mip(label, m, true, false)) { + invoke(tex, 2); + VirtualFree(mem, 0, MEM_RELEASE); + return false; + } + } + std::vector<std::vector<Rgba>> rb_mips; + if (!readback_texture_mips(tex, rb_mips)) { invoke(tex, 2); VirtualFree(mem, 0, MEM_RELEASE); return false; } + for (UINT m = 0; m < kMips; ++m) { + UINT bx = 0, by = 0; Rgba g{}, e{}; + if (find_first_texel_mismatch(rb_mips[m].data(), mip_fp[m].Footprint.RowPitch / 4, m, kWidth >> m, kHeight >> m, bx, by, g, e)) { + std::fprintf(stderr, " FAIL %s: GPU texel mismatch mip%u (%u,%u)\n", label, m, bx, by); + invoke(tex, 2); VirtualFree(mem, 0, MEM_RELEASE); return false; + } + } + invoke(tex, 2); + VirtualFree(mem, 0, MEM_RELEASE); + return true; + }; + + if (!run_xg_footprint_path("[Path 2a] XG footprint path (Alignment=0, MipLevels=3)", 3)) record_fail(30); + if (!run_xg_footprint_path("[Path 2b] XG footprint path (Alignment=0, MipLevels=0 full chain)", 0)) record_fail(31); + if (!check_xg_mip0_layout(desktop.Get())) record_fail(32); + + // ========================================================================= + // PATH 3: small_texture_4k compact path (Alignment = 0x1000, MipLevels = 3) + // ========================================================================= + std::printf("[Path 3] small_texture_4k compact path (Alignment=0x1000, MipLevels=3)\n"); + { + auto desc = mip_desc_3; + desc.Alignment = 0x1000; + void** computer = nullptr; + if (FAILED(XGCreateTextureComputer(&desc, &computer, 0, 0)) || !computer) { record_fail(40); } else { + auto* tbl = static_cast<void**>(computer[0]); + using LayoutFn = HRESULT (WINAPI*)(void*, unsigned char*); + using CopyIntoFn = HRESULT (WINAPI*)(void*, unsigned char*, UINT, UINT, const unsigned char*, UINT, UINT); + std::array<unsigned char, 0x18 + 4 * 0x6c8 + 8> layout{}; + if (FAILED(reinterpret_cast<LayoutFn>(tbl[2])(computer, layout.data()))) { record_fail(41); } + UINT64 total = 0, align = 0; + std::memcpy(&total, layout.data() + 0x00, 8); + std::memcpy(&align, layout.data() + 0x08, 8); + std::printf(" small4k slot 2: total=0x%llx align=0x%llx\n", + static_cast<unsigned long long>(total), static_cast<unsigned long long>(align)); + if (total != 0x2000 || align != 0x1000) record_fail(42); + auto* mem = static_cast<unsigned char*>(VirtualAlloc(nullptr, 0x3000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + DWORD old = 0; + if (!mem || !VirtualProtect(mem + 0x2000, 0x1000, PAGE_NOACCESS, &old)) record_fail(43); + for (UINT m = 0; m < kMips; ++m) { + const UINT w = kWidth >> m, h = kHeight >> m; + std::vector<Rgba> lin(w * h); + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) lin[y * w + x] = expected_texel(m, x, y); + if (FAILED(reinterpret_cast<CopyIntoFn>(tbl[8])(computer, mem, 0, m, + reinterpret_cast<const unsigned char*>(lin.data()), w * 4, 0))) { + record_fail(44); + } + } + reinterpret_cast<UINT64 (WINAPI*)(void*)>(tbl[1])(computer); + + void* tex = nullptr; + if (!ok(invoke(device, 133, arg(mem), arg(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, arg(&__uuidof(ID3D12Resource)), arg(&tex))) || !tex) { + record_fail(45); + } else { + for (UINT m = 0; m < kMips; ++m) { + const Word gpu = make_srv18(tex, 0, m, kMips - m); + if (!draw_gradient_then_ui(gpu, "Path 3 (small4k)", m) || !verify_rt_for_mip("Path 3 (small4k)", m, true, false)) { + record_fail(46); + } + } + std::vector<std::vector<Rgba>> rb_mips; + if (!readback_texture_mips(tex, rb_mips)) record_fail(47); + else { + for (UINT m = 0; m < kMips; ++m) { + UINT bx = 0, by = 0; Rgba g{}, e{}; + if (find_first_texel_mismatch(rb_mips[m].data(), mip_fp[m].Footprint.RowPitch / 4, m, kWidth >> m, kHeight >> m, bx, by, g, e)) { + std::fprintf(stderr, "FAIL Path 3: GPU texel mismatch mip%u (%u,%u)\n", m, bx, by); + record_fail(48); + } + } + } + invoke(tex, 2); + } + VirtualFree(mem, 0, MEM_RELEASE); + } + } + + // ========================================================================= + // PATH 4: Console-tiled gfx10::Layout via Device::slot70 (0x105 & 0x10a) + // ========================================================================= + for (UINT layout_mode : {0x105u, 0x10au}) { + std::printf("[Path 4] Console-tiled gfx10 via Device::slot70 (layout=0x%x, 3 mips)\n", layout_mode); + Gfx10Tiler tiler; + tiler.init(kWidth, kHeight, kMips, layout_mode); + std::vector<unsigned char> tiled(tiler.total_bytes, 0); + for (UINT m = 0; m < kMips; ++m) { + const UINT w = kWidth >> m, h = kHeight >> m; + for (UINT y = 0; y < h; ++y) + for (UINT x = 0; x < w; ++x) { + const Rgba t = expected_texel(m, x, y); + std::memcpy(tiled.data() + tiler.addr(m, x, y), &t, 4); + } + } + auto desc = mip_desc_3; + desc.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(layout_mode); + MemoryViewAt mv{}; + mv.view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + mv.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + mv.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + mv.address = reinterpret_cast<Word>(tiled.data()); + for (UINT m = 0; m < kMips; ++m) { + mv.view.Texture2D.MostDetailedMip = m; + mv.view.Texture2D.MipLevels = kMips - m; + invoke(device, 70, arg(&desc), arg(&mv), srv_cpu0); + const char* lbl = layout_mode == 0x105 ? "Path 4 (slot70 0x105)" : "Path 4 (slot70 0x10a)"; + if (!draw_gradient_then_ui(srv_gpu0, lbl, m) || !verify_rt_for_mip(lbl, m, true, false)) { + record_fail(50); + } + } + } + + // ========================================================================= + // NEGATIVE CONTROL 1: Intentionally wrong row pitch (2x stride = 512 vs 256) + // ========================================================================= + std::printf("[Neg Ctrl 1] Linear upload with intentionally wrong row pitch (512 stride read at 256 RowPitch)\n"); + { + // Author mip 0 with stride 512 (rows at 0, 512, 1024...), leaving bytes [256..511] black (0), + // then upload at desktop RowPitch 256 -> even rows get nonzero source rows, odd rows get zero gap! + constexpr UINT wrong_stride = 512; + const UINT upload_bytes = (kHeight * 2) * 256; + std::vector<unsigned char> wrong_lin(kHeight * wrong_stride, 0); + for (UINT y = 0; y < kHeight; ++y) { + for (UINT x = 0; x < kWidth; ++x) { + const Rgba t = expected_texel(0, x, y); + std::memcpy(wrong_lin.data() + y * wrong_stride + x * 4, &t, 4); + } + } + auto desc1 = mip_desc_3; + desc1.MipLevels = 1; + void* tex = make_committed(device, D3D12_HEAP_TYPE_DEFAULT, desc1, D3D12_RESOURCE_STATE_COMMON); + void* up = make_committed(device, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(upload_bytes), D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + if (!tex || !up || !ok(invoke(up, 8, 0, 0, arg(&mapped))) || !mapped) { record_fail(60); } else { + std::memcpy(mapped, wrong_lin.data(), kHeight * 256); // uploader thinks height=32 * pitch=256 + invoke(up, 9, 0, 0); + + if (!ok(invoke(alloc, 8)) || !ok(invoke(list, 139, arg(alloc), 0))) record_fail(61); + D3D12_TEXTURE_COPY_LOCATION to{static_cast<ID3D12Resource*>(tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION from{static_cast<ID3D12Resource*>(up), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + from.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, kWidth, kHeight, 1, 256}}; + invoke(list, 16, arg(&to), 0, 0, 0, arg(&from), 0); + if (!ok(invoke(list, 9))) record_fail(62); + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_val)) || !wait_fence(fence, fence_val)) record_fail(63); + + void* rb = make_committed(device, D3D12_HEAP_TYPE_READBACK, buffer_desc(mip_fp[0].Footprint.RowPitch * kHeight), D3D12_RESOURCE_STATE_COPY_DEST); + void* rb_map = nullptr; + if (!rb || !ok(invoke(alloc, 8)) || !ok(invoke(list, 139, arg(alloc), 0))) record_fail(64); + D3D12_TEXTURE_COPY_LOCATION rb_dst{static_cast<ID3D12Resource*>(rb), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + rb_dst.PlacedFootprint = mip_fp[0]; + D3D12_TEXTURE_COPY_LOCATION rb_src{static_cast<ID3D12Resource*>(tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + invoke(list, 16, arg(&rb_dst), 0, 0, 0, arg(&rb_src), 0); + if (!ok(invoke(list, 9))) record_fail(64); + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_val)) || !wait_fence(fence, fence_val) || + !ok(invoke(rb, 8, 0, 0, arg(&rb_map))) || !rb_map) record_fail(64); + std::vector<Rgba> gpu_rows((mip_fp[0].Footprint.RowPitch / 4) * kHeight); + std::memcpy(gpu_rows.data(), rb_map, gpu_rows.size() * 4); + invoke(rb, 9, 0, 0); + invoke(rb, 2); + print_rows_summary("neg1 gpu texels", gpu_rows.data(), mip_fp[0].Footprint.RowPitch / 4, kWidth, kHeight); + UINT bx = 0, by = 0; Rgba g{}, e{}; + if (!find_first_texel_mismatch(gpu_rows.data(), mip_fp[0].Footprint.RowPitch / 4, 0, kWidth, kHeight, bx, by, g, e) || + by != 1 || bx != 0 || !g.is_black()) { + std::fprintf(stderr, "FAIL Neg Ctrl 1: expected first GPU mismatch at (0,1)=black, got (%u,%u)\n", bx, by); + record_fail(65); + } + std::printf(" Neg Ctrl 1: first GPU texel mismatch at (x=%u, y=%u, byte_offset=%u) got=(%u,%u,%u,%u) expected=(%u,%u,%u,%u)\n", + bx, by, by * mip_fp[0].Footprint.RowPitch + bx * 4, g.r, g.g, g.b, g.a, e.r, e.g, e.b, e.a); + + const Word gpu = make_srv18(tex, 0, 0, 1); + if (!draw_gradient_then_ui(gpu, "Neg Ctrl 1", 0) || !verify_rt_for_mip("Neg Ctrl 1", 0, false, true)) { + std::fprintf(stderr, "FAIL Neg Ctrl 1: did not reproduce alternating nonzero/black horizontal bands\n"); + record_fail(66); + } + invoke(up, 2); + invoke(tex, 2); + } + } + + // ========================================================================= + // NEGATIVE CONTROL 2: Compact Alignment=0x1000 placed texture filled with desktop 256B row pitch + // ========================================================================= + std::printf("[Neg Ctrl 2] Compact small_texture_4k (Alignment=0x1000) backed by 256B footprint rows (128B row mismatch)\n"); + { + auto desc = mip_desc_3; + desc.MipLevels = 1; + desc.Alignment = 0x1000; + const UINT64 alloc_bytes = 0x2000; + auto* backing = static_cast<unsigned char*>(VirtualAlloc(nullptr, static_cast<SIZE_T>(alloc_bytes), + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + std::memset(backing, 0, static_cast<std::size_t>(alloc_bytes)); + // Title placed 32x32 RGBA8 rows 256 bytes apart (128 bytes texels + 128 bytes zero padding) into Alignment=0x1000 memory; + // runtime small_texture_4k reads compact 128-byte rows -> odd rows hit zero padding [128..255] of row y/2! + for (UINT y = 0; y < kHeight / 2; ++y) { + for (UINT x = 0; x < kWidth; ++x) { + const Rgba t = expected_texel(0, x, y); + std::memcpy(backing + y * 256 + x * 4, &t, 4); + } + } + void* tex = nullptr; + if (!ok(invoke(device, 133, arg(backing), arg(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, arg(&__uuidof(ID3D12Resource)), arg(&tex))) || !tex) { + record_fail(70); + } else { + const Word gpu = make_srv18(tex, 0, 0, 1); + if (!draw_gradient_then_ui(gpu, "Neg Ctrl 2", 0) || !verify_rt_for_mip("Neg Ctrl 2", 0, false, true)) { + std::fprintf(stderr, "FAIL Neg Ctrl 2: Alignment=0x1000 pitch mismatch did not reproduce alternating bands\n"); + record_fail(71); + } else { + // Also read back GPU texels after upload to record the first mismatching byte/texel on GPU. + void* rb = make_committed(device, D3D12_HEAP_TYPE_READBACK, buffer_desc(mip_fp[0].Footprint.RowPitch * kHeight), + D3D12_RESOURCE_STATE_COPY_DEST); + void* rb_map = nullptr; + if (rb && ok(invoke(alloc, 8)) && ok(invoke(list, 139, arg(alloc), 0))) { + D3D12_TEXTURE_COPY_LOCATION rb_dst{static_cast<ID3D12Resource*>(rb), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + rb_dst.PlacedFootprint = mip_fp[0]; + D3D12_TEXTURE_COPY_LOCATION rb_src{static_cast<ID3D12Resource*>(tex), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + invoke(list, 16, arg(&rb_dst), 0, 0, 0, arg(&rb_src), 0); + void* lists[] = {list}; + if (ok(invoke(list, 9)) && (invoke(queue, 10, 1, arg(lists)), ok(invoke(queue, 14, arg(fence), ++fence_val))) && + wait_fence(fence, fence_val) && ok(invoke(rb, 8, 0, 0, arg(&rb_map))) && rb_map) { + std::vector<Rgba> gpu_rows((mip_fp[0].Footprint.RowPitch / 4) * kHeight); + std::memcpy(gpu_rows.data(), rb_map, gpu_rows.size() * 4); + invoke(rb, 9, 0, 0); + print_rows_summary("neg2 gpu texels", gpu_rows.data(), mip_fp[0].Footprint.RowPitch / 4, kWidth, kHeight); + UINT bx = 0, by = 0; Rgba g{}, e{}; + if (find_first_texel_mismatch(gpu_rows.data(), mip_fp[0].Footprint.RowPitch / 4, 0, kWidth, kHeight, bx, by, g, e)) { + std::printf(" Neg Ctrl 2: first GPU texel mismatch at (x=%u, y=%u, source_offset=%u -> gpu_offset=%u) " + "got=(%u,%u,%u,%u) expected=(%u,%u,%u,%u)\n", + bx, by, by * 128 + bx * 4, by * mip_fp[0].Footprint.RowPitch + bx * 4, + g.r, g.g, g.b, g.a, e.r, e.g, e.b, e.a); + } + } + invoke(rb, 2); + } + } + invoke(tex, 2); + } + VirtualFree(backing, 0, MEM_RELEASE); + } + + invoke(fence, 2); + invoke(list, 2); + invoke(alloc, 2); + invoke(queue, 2); + invoke(srv_heap, 2); + invoke(rtv_heap, 2); + invoke(rt_readback, 2); + invoke(rt, 2); + invoke(tex_pso, 2); + invoke(grad_pso, 2); + invoke(guest_root, 2); + desktop.Reset(); + invoke(device, 2); + cleanup_cache(); + if (!all_ok) { + std::printf("startup_ui_texture_bands_check: FAIL (%d)\n", first_fail_rc); + return first_fail_rc; + } + std::printf("startup_ui_texture_bands_check: PASS\n"); + return 0; +} diff --git a/tests/startup_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 187fa7b563..0dcdc6480d 100644 --- a/tests/startup_vertex_fetch_formats_check.py +++ b/tests/startup_vertex_fetch_formats_check.py @@ -9,7 +9,7 @@ (startup_r8_uint_check.py). This drives each table entry the way that check does: a source-built vertex stage with one tbuffer_load_format_xyzw from vertex buffer 1 is translated, its generated vertex body is called from a compute wrapper, and the four position components of 16 vertices are read back through -offscreen_check --compute-store-case and compared with a reference that decodes the same bytes from the +offscreen_check and compared with a reference that decodes the same bytes from the format definitions (little-endian fields from the lowest byte, UNORM n / (2^bits - 1), binary16 widened to binary32, missing X, Y and Z as 0 and a missing W as 1.0, or 1 for an integer format). @@ -21,9 +21,11 @@ that word as an entry constant and the translation switches on it. Each format is run through a MUBUF xyz load with its own descriptor word, then descriptor words with swizzles and constants 0 and 1 run through the same translated body. -Wrong references (channels swapped, a shift off by one field, a missing W read as 0, UNORM over 2^bits) -and mutated translations must fail the readback. +Each TBUFFER format runs its matching reference and each wrong reference that changes a word in one renderer +batch. The first mismatched word must match the predicted index and values. Each distinct vertex or compute +source compiles once in the fixture's temporary directory. Mutated translations dispatch separately. """ +import hashlib import re import struct import subprocess @@ -31,6 +33,7 @@ import tempfile from pathlib import Path +from compute_load_format_check import check_references from startup_sampler_heap_check import root_blob from startup_stream_check import gfx2hlsl @@ -51,6 +54,9 @@ def f16(bits): 'BUF_FMT_8_UINT': (5, 3, 1, 8, 'uint', 1), 'BUF_FMT_8_8_UNORM': (14, 3, 2, 8, 'unorm', 2), 'BUF_FMT_16_16_UNORM': (23, 6, 2, 16, 'unorm', 2), + # One dword: x, y, z are 10-bit fields (bits 9:0, 19:10, 29:20) and w the 2-bit field in bits 31:30. The field + # width is listed as 16 only so the stride and offset checks see sub-dword alignment; see PACKED_2101010. + 'BUF_FMT_2_10_10_10_UNORM': (50, 6, 2, 16, 'unorm2101010', 4), 'BUF_FMT_16_16_SNORM': (24, 6, 2, 16, 'snorm', 2), 'BUF_FMT_16_16_UINT': (27, 6, 2, 16, 'uint', 2), 'BUF_FMT_16_16_FLOAT': (29, 10, 10, 16, 'f16', 2), @@ -64,6 +70,9 @@ def f16(bits): } +PACKED_2101010 = ((0, 10), (10, 10), (20, 10), (30, 2)) # (low bit, width) of x, y, z, w + + def snorm_words(fields, unsigned=False, no_clamp=False): """SNORM fields as the compared integers round(v * 32767): two's complement, -32768 clamped to -32767.""" out = [] @@ -77,6 +86,14 @@ def reference(name, vertex, *, offset=None, swap=False, shift=False, w_zero=Fals """The four compared words of one vertex, from the format definition. The keywords give wrong references.""" _, stride, own_offset, bits, kind, count = FORMATS[name] address, size = vertex * stride + (own_offset if offset is None else offset), bits // 8 + if kind == 'unorm2101010': + word = int.from_bytes(DATA[address + (1 if shift else 0):address + (1 if shift else 0) + 4], 'little') + fields = [(word >> low) & ((1 << width) - 1) for low, width in PACKED_2101010] + if swap: + fields[0], fields[1] = fields[1], fields[0] + if unorm_pow2: + fields = [round(f * ((1 << w) - 1) / (1 << w)) for f, (_, w) in zip(fields, PACKED_2101010)] + return fields fields = [int.from_bytes(DATA[address + size * i:address + size * (i + 1)], 'little') for i in range(count)] if shift and bits < 32: # Each field read one field higher, as a wrong shift would; the last reads past the element. @@ -97,6 +114,8 @@ def reference(name, vertex, *, offset=None, swap=False, shift=False, w_zero=Fals def compared(name): """Return the integer readback scale for each normalized component.""" _, _, _, bits, kind, count = FORMATS[name] + if kind == 'unorm2101010': + return [(1 << width) - 1 for _, width in PACKED_2101010] scale = {'unorm': (1 << bits) - 1, 'snorm': (1 << (bits - 1)) - 1}.get(kind) return [scale if i < count else None for i in range(4)] @@ -140,6 +159,9 @@ def wrapper(name): MUTATIONS = ( ('BUF_FMT_8_8_8_8_UNORM', 'second byte from the third', 'U(((w >> 8) & 255) / 255.0)', 'U(((w >> 16) & 255) / 255.0)'), ('BUF_FMT_8_8_8_8_UNORM', 'fourth byte as 255', 'U((w >> 24) / 255.0)', 'U(1.0)'), + ('BUF_FMT_2_10_10_10_UNORM', 'y from the x field', 'v5 = U(((w >> 10) & 1023) / 1023.0);', 'v5 = U((w & 1023) / 1023.0);'), + ('BUF_FMT_2_10_10_10_UNORM', 'z from the y field', 'v6 = U(((w >> 20) & 1023) / 1023.0);', 'v6 = U(((w >> 10) & 1023) / 1023.0);'), + ('BUF_FMT_2_10_10_10_UNORM', 'w over 4', 'v7 = U((w >> 30) / 3.0);', 'v7 = U((w >> 30) / 4.0);'), ('BUF_FMT_8_8_8_8_UINT', 'normalized green byte', 'v5 = (w >> 8) & 255u;', 'v5 = U(((w >> 8) & 255u) / 255.0);'), ('BUF_FMT_8_8_8_8_UINT', 'blue byte from green', 'v6 = (w >> 16) & 255u;', 'v6 = (w >> 8) & 255u;'), ('BUF_FMT_8_8_8_8_UINT', 'alpha byte from blue', 'v7 = w >> 24;', 'v7 = (w >> 16) & 255u;'), @@ -408,8 +430,10 @@ def stage(words): def runtime_gate(source): """Check that both FORMAT metadata and usable backing are required before submission.""" assert 'formatted_buffers_ready(*tr, pass, formatted_buffers)' in source + decoder = source[source.index('const char* formatted_buffer_word3('):source.index('bool formatted_buffers_ready(')] + assert 'formatted_buffer_supported(' in decoder preflight = source[source.index('bool formatted_buffers_ready('):source.index('bool draw_translated(')] - for condition in ('x2w_local::readable(', 'view_token_magic', 'formatted_buffer_supported('): + for condition in ('x2w_local::readable(', 'view_token_magic', 'formatted_buffer_word3('): assert condition in preflight, condition start = source.index('bool draw_translated(') gate = source.index('if (!have && formatted.entry)', start) @@ -421,8 +445,15 @@ def runtime_gate(source): def runtime_gate_controls(): source = RUNTIME.read_text(encoding='utf-8') runtime_gate(source) + decoder = source[source.index('const char* formatted_buffer_word3('):source.index('bool formatted_buffers_ready(')] + try: + runtime_gate(source.replace(decoder, decoder.replace('formatted_buffer_supported(', 'omitted'))) + except AssertionError: + pass + else: + raise AssertionError('descriptor decoder without FORMAT support checking must fail the control') preflight = source[source.index('bool formatted_buffers_ready('):source.index('bool draw_translated(')] - for dropped in ('x2w_local::readable(', 'view_token_magic', 'formatted_buffer_supported('): + for dropped in ('x2w_local::readable(', 'view_token_magic', 'formatted_buffer_word3('): try: runtime_gate(source.replace(preflight, preflight.replace(dropped, 'omitted'))) except AssertionError: @@ -441,24 +472,29 @@ def runtime_gate_controls(): def compile_fetch(directory, compiler, name, source): - hlsl, binary = directory / 'fetch.hlsl', directory / 'fetch.cso' - hlsl.write_text(source, encoding='ascii') - # Compile the vertex entry as the startup tools do, then the same body in the compute wrapper. - subprocess.run([compiler, '-T', 'vs_6_0', '-E', 'main', '-Fo', binary, hlsl], check=True) - with hlsl.open('a', encoding='ascii') as handle: - handle.write(wrapper(name)) - subprocess.run([compiler, '-T', 'cs_6_0', '-E', 'readback', '-Fo', binary, hlsl], check=True) + hlsl, output = directory / 'fetch.hlsl', directory / 'fetch.cso' + # Descriptor words can change without changing the vertex program. The readback wrapper + # also depends on the format, so key each stage by its complete input in this run's temporary directory. + for profile, entry, text in (('vs_6_0', 'main', source), ('cs_6_0', 'readback', source + wrapper(name))): + binary = directory / ('%s-%s.cso' % (profile, hashlib.sha256(text.encode('ascii')).hexdigest())) + if not binary.exists(): + hlsl.write_text(text, encoding='ascii') + subprocess.run([compiler, '-T', profile, '-E', entry, '-Fo', output, hlsl], check=True) + output.replace(binary) return binary -def run_reference(directory, consumer, adapter, binary, name, words, translated=None, word3=None): - case = directory / 'fetch.case' - translated = translated or pipeline(name) +def write_reference(case, name, words, translated, word3=None): constants = [0] * 16 constants[translated.uds.index(('stride', 0))] = FORMATS[name][1] if word3 is not None: constants[translated.uds.index(('descword3', 0))] = word3 case.write_bytes(struct.pack('<337I', 1, *words, *constants)) + + +def run_reference(directory, consumer, adapter, binary, name, words, translated=None, word3=None): + case = directory / 'fetch.case' + write_reference(case, name, words, translated or pipeline(name), word3) return subprocess.run([consumer, adapter, '--compute-store-case', binary, case], capture_output=True, text=True) @@ -469,26 +505,23 @@ def run(directory, compiler, consumer, adapter, name, source, words, translated= def check(directory, compiler, consumer, adapter): for name in FORMATS: - source = pipeline(name).hlsl_vs() - binary = compile_fetch(directory, compiler, name, source) + translated = pipeline(name) + binary = compile_fetch(directory, compiler, name, translated.hlsl_vs()) correct = expected(name) - result = run_reference(directory, consumer, adapter, binary, name, correct) - if result.returncode == 77: - print(result.stdout, result.stderr) - return 77 - if result.returncode: - raise RuntimeError('%s: %s%s' % (name, result.stdout, result.stderr)) - print('%s: 16 vertices, stride %d, offset %d: %s' % ( - name, FORMATS[name][1], FORMATS[name][2], - [line for line in result.stdout.splitlines() if 'mismatches=' in line][0])) + case = directory / 'fetch-correct.case' + write_reference(case, name, correct, translated) + references = [(case, '16 vertices, stride %d, offset %d' % FORMATS[name][1:3], None)] for label, wrong in WRONG: words = expected(name, **wrong) if words == correct: continue first = next(i for i, (a, b) in enumerate(zip(words, correct)) if a != b) - bad = run_reference(directory, consumer, adapter, binary, name, words) - if bad.returncode != 1 or 'word=%d expected=' % first not in bad.stderr: - raise AssertionError('%s: reference %r escaped detection\n%s' % (name, label, bad.stderr)) + case = directory / f'fetch-wrong-{len(references)}.case' + write_reference(case, name, words, translated) + diagnostic = f'word={first} expected={words[first]:08x} actual={correct[first]:08x}' + references.append((case, label, diagnostic)) + if check_references(name, consumer, adapter, binary, references, allow_skip=True) == 77: + return 77 for name, label, old, new in MUTATIONS: source = pipeline(name).hlsl_vs() binary = compile_fetch(directory, compiler, name, source.replace(old, new, 1)) diff --git a/tests/startup_view_alloc.cpp b/tests/startup_view_alloc.cpp new file mode 100644 index 0000000000..84dd71acbc --- /dev/null +++ b/tests/startup_view_alloc.cpp @@ -0,0 +1,307 @@ +// A view is published into three containers (view_records, view_materialized, view_ids). When one of them cannot +// allocate, the stand-in must record nothing, untrack the destination descriptor and keep running (#1199, +// docs/startup-runtime.md#d3d12-view-allocation-failure). The fixture-only export x2w_d3d12_fail_view_allocations +// makes the allocations at one site fail. +// +// startup_view_alloc <warp|hardware> <records|materialized|ids> [control] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_RELEASE_RETIRED=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1 X2W_TRAP_LOG=<file>) +// "control" never arms the failure, so the armed expectations must fail and the fixture must print FAIL. +#include <windows.h> + +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <string> + +using Microsoft::WRL::ComPtr; + +struct ViewStoreProbe { + unsigned long long records, materialized, ids, records_capacity, materialized_capacity; + unsigned shadow, view_refs, retire_when_idle; +}; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_fail_view_allocations(int, LONG); +extern "C" __declspec(dllimport) void x2w_d3d12_view_probe(unsigned long long, void*, ViewStoreProbe*); + +namespace { + +constexpr std::uint32_t token_magic = 0x56573258; // "X2WV" +constexpr LONG failing_calls = 3; +constexpr UINT fill_limit = 100000; + +template<class Result = HRESULT, class... Args> +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +int failures; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +ComPtr<IDXGIAdapter1> pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +std::string read_log() +{ + wchar_t path[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", path, MAX_PATH); + std::string text; + if (!length || length >= MAX_PATH) return text; + const HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char chunk[4096]; + DWORD got = 0; + while (ReadFile(file, chunk, sizeof(chunk), &got, nullptr) && got) text.append(chunk, got); + CloseHandle(file); + return text; +} + +// The view id + 1 in the token the stand-in writes into title descriptor memory, or 0 when it holds no token. +std::uint32_t token(UINT64 handle) +{ + std::uint32_t words[2]; + std::memcpy(words, reinterpret_cast<const void*>(handle), sizeof(words)); + return words[0] == token_magic ? words[1] + 1 : 0; +} + +ViewStoreProbe probe(UINT64 handle, void* resource = nullptr) +{ + ViewStoreProbe p{}; + x2w_d3d12_view_probe(handle, resource, &p); + return p; +} + +} // namespace + +int main(int argc, char** argv) +{ + const char* const sites[] = {"records", "materialized", "ids"}; + int site = -1; + for (int i = 0; argc >= 3 && i < 3; ++i) + if (!std::strcmp(argv[2], sites[i])) site = i; + if (argc < 3 || argc > 4 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || site < 0 || + (argc == 4 && std::strcmp(argv[3], "control"))) + return 2; + const bool control = argc == 4; + std::setvbuf(stdout, nullptr, _IONBF, 0); // the lines before a crash must reach the test log + wchar_t log_path[MAX_PATH]; + const DWORD log_length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path, MAX_PATH); + if (!log_length || log_length >= MAX_PATH) { + std::puts("FAIL: X2W_TRAP_LOG is not set"); + return 2; + } + DeleteFileW(log_path); // before the stand-in writes its first line + + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) std::printf("adapter=%ls\n", adapter_desc.Description); + ComPtr<IUnknown> guest, heap; + std::array<unsigned char, 64> parameters{}; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(guest.GetAddressOf())))) + return 3; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 3}, 0, 0}; + if (FAILED(invoke(guest.Get(), 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()))) return 3; + const UINT64 first = invoke<UINT64>(heap.Get(), 9); + const UINT stride = invoke<UINT>(guest.Get(), 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const UINT64 earlier = first, filler = first + stride, target = first + 2 * UINT64{stride}; + + D3D12_HEAP_PROPERTIES default_heap{}; + default_heap.Type = 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; + ComPtr<IUnknown> textures[3]; // replaced view, failed view, later view + const IID iid = __uuidof(ID3D12Resource); + for (auto& t : textures) + if (FAILED(invoke(guest.Get(), 27, &default_heap, D3D12_HEAP_FLAG_NONE, &texture, D3D12_RESOURCE_STATE_COMMON, + static_cast<const D3D12_CLEAR_VALUE*>(nullptr), &iid, + reinterpret_cast<void**>(t.GetAddressOf())))) + return 3; + + // The stand-in identifies a view by every byte of its description, padding included, so each description is zeroed + // with memset before its fields are set: brace initialization need not clear the padding. + D3D12_SHADER_RESOURCE_VIEW_DESC srv; + std::memset(&srv, 0, sizeof(srv)); + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + const auto texture_view = [&](int index, UINT64 handle) { + invoke<void>(guest.Get(), 18, static_cast<void*>(textures[index].Get()), &srv, handle); + }; + const auto constant_view = [&](UINT index, UINT64 handle) { + D3D12_CONSTANT_BUFFER_VIEW_DESC desc; + std::memset(&desc, 0, sizeof(desc)); + desc.BufferLocation = 0x100000ull + 256ull * index; + desc.SizeInBytes = 256; + invoke<void>(guest.Get(), 17, &desc, handle); + }; + + // Two views published before any failure. + constant_view(0, earlier); + const std::uint32_t earlier_id = token(earlier); + texture_view(0, target); + const std::uint32_t replaced_id = token(target); + if (!earlier_id || !replaced_id || probe(earlier).shadow != earlier_id || probe(target).shadow != replaced_id) { + std::puts("FAIL: the views published before the failure are not tracked"); + return 3; + } + const auto first_texture = probe(target, textures[0].Get()); + if (first_texture.view_refs != 1 || !first_texture.retire_when_idle) { + std::puts("FAIL: the first texture is not in the retire class with one tracked view"); + return 3; + } + + // A vector allocates only when it is full: distinct views until the next one has to grow it. + UINT filled = 1; + const auto fill = [&] { + if (site == 2) return true; + for (; filled < fill_limit; ++filled) { + const auto p = probe(target); + if (site == 0 ? p.records == p.records_capacity : p.materialized == p.materialized_capacity) return true; + constant_view(filled, filler); + } + std::puts("FAIL: the vector never filled up"); + return false; + }; + if (!fill()) return 3; + + const auto before = probe(target); + std::printf("site=%s records=%llu capacity=%llu: arming %ld failures\n", sites[site], before.records, + before.records_capacity, control ? 0 : failing_calls); + if (!control) x2w_d3d12_fail_view_allocations(site, failing_calls); + for (LONG call = 0; call < failing_calls; ++call) { + texture_view(1, target); + const auto p = probe(target, textures[1].Get()); + expect(p.records == before.records && p.materialized == before.materialized && p.ids == before.ids, + "a failed publication changed a view container"); + expect(!p.shadow, "the destination slot still names a view after a failed publication"); + expect(!token(target), "title memory still holds a view token after a failed publication"); + expect(!p.view_refs && !p.retire_when_idle, "the resource of the failed view can still be released early"); + } + x2w_d3d12_fail_view_allocations(site, 0); + const auto replaced = probe(target, textures[0].Get()); + expect(!replaced.view_refs && replaced.retire_when_idle, "the replaced view kept its reference"); + + // Views published before the failure keep their ids and add no record. + const unsigned long long held = probe(target).records; + constant_view(0, earlier); + expect(token(earlier) == earlier_id && probe(earlier).shadow == earlier_id, "an earlier view changed its id"); + texture_view(0, target); + expect(token(target) == replaced_id && probe(target).shadow == replaced_id, "the replaced view changed its id"); + expect(probe(target).records == held, "an earlier view added a record"); + + // The view that failed, and then a view never seen before, are published normally. + for (int index = 1; index < 3; ++index) { + const auto start = probe(target); + texture_view(index, target); + const std::uint32_t id = token(target); + const auto p = probe(target, textures[index].Get()); + expect(id && p.shadow == id, "a later view is not tracked"); + // In "control" the second texture view was already published by the unarmed calls. + expect(p.records == start.records + (control && index == 1 ? 0 : 1) && p.materialized == p.records && + p.ids == p.records, + "a later view did not add one record to each container"); + expect(p.view_refs == 1, "a later view holds no reference"); + texture_view(index, target); + expect(token(target) == id && probe(target).records == p.records, "a later view did not keep its id"); + } + + // Slot 19 names two resources, the view's and its counter. A failed UAV publication over a tracked UAV drops both + // references of the earlier one and adds none. UAV-capable textures and buffers are never in the retire class, so + // only the reference counts are observable here. + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 4096; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + ComPtr<IUnknown> buffers[4]; // earlier resource and counter, then the failed view's resource and counter + for (auto& b : buffers) + if (FAILED(invoke(guest.Get(), 27, &default_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COMMON, + static_cast<const D3D12_CLEAR_VALUE*>(nullptr), &iid, + reinterpret_cast<void**>(b.GetAddressOf())))) + return 3; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav; + std::memset(&uav, 0, sizeof(uav)); + uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + uav.Buffer.NumElements = 16; + uav.Buffer.StructureByteStride = 16; + const auto counted_view = [&](int index) { + invoke<void>(guest.Get(), 19, static_cast<void*>(buffers[index].Get()), + static_cast<void*>(buffers[index + 1].Get()), &uav, target); + }; + const auto refs = [&](int index) { return probe(target, buffers[index].Get()).view_refs; }; + counted_view(0); + const std::uint32_t counted_id = token(target); + if (!counted_id || probe(target).shadow != counted_id || refs(0) != 1 || refs(1) != 1) { + std::puts("FAIL: the slot 19 view and its counter are not tracked"); + return 3; + } + if (!fill()) return 3; + const auto counted = probe(target); + if (!control) x2w_d3d12_fail_view_allocations(site, 1); + counted_view(2); + x2w_d3d12_fail_view_allocations(site, 0); + const auto dropped = probe(target); + expect(dropped.records == counted.records && dropped.materialized == counted.materialized && dropped.ids == counted.ids, + "a failed slot 19 publication changed a view container"); + expect(!dropped.shadow && !token(target), "the destination still names a view after a failed slot 19 publication"); + expect(!refs(0), "the replaced slot 19 view kept its resource reference"); + expect(!refs(1), "the replaced slot 19 view kept its counter reference"); + expect(control || (!refs(2) && !refs(3)), "the failed slot 19 view holds a reference"); + counted_view(2); + expect(token(target) && probe(target).shadow == token(target) && refs(2) == 1 && refs(3) == 1, + "a later slot 19 view and its counter are not tracked"); + counted_view(0); + expect(token(target) == counted_id && refs(0) == 1 && refs(1) == 1 && !refs(2) && !refs(3), + "the earlier slot 19 view did not take its slot back"); + + const std::string line = std::string("x2w-d3d12 note_view: out of memory in view_") + sites[site]; + expect(read_log().find(line) != std::string::npos, "the log does not name the failed allocation"); + + if (failures) return 5; + std::printf("view allocation failure checks passed (%s)\n", sites[site]); + return 0; +} diff --git a/tests/startup_view_census.cpp b/tests/startup_view_census.cpp new file mode 100644 index 0000000000..d11b99cfde --- /dev/null +++ b/tests/startup_view_census.cpp @@ -0,0 +1,288 @@ +// X2W_D3D12_VIEW_CENSUS=1 (docs/startup-runtime.md#d3d12-view-census): the stand-in counts new distinct view records +// by slot and logs the vector capacity and hash bucket count before an insertion that grows either. The fixture compares +// a stream of one repeated descriptor with a stream of distinct descriptors, both through the real device view slots +// and both under a job commit limit set above what the process holds after setup. +// +// startup_view_census <warp|hardware> [off|vary] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_RENDER=1 X2W_D3D12_VIEW_CENSUS=1 X2W_TRAP_LOG=<file>) +// "off" runs without X2W_D3D12_VIEW_CENSUS: nothing may be reported or logged. "vary" is the negative control: +// the stream meant to repeat one descriptor changes it every call, which the fixture must report as a failure. +#include <windows.h> + +#include <d3d12.h> +#include <dxgi1_6.h> +#include <psapi.h> +#include <wrl/client.h> + +#include <array> +#include <cstdio> +#include <cstring> +#include <string> + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) std::size_t x2w_d3d12_view_census_line(char*, std::size_t); + +namespace { + +constexpr unsigned long long headroom = 256ull << 20; // job commit limit above the commit held after setup +constexpr UINT repeated_calls = 200000; +constexpr UINT distinct_buffers = 200000; // slot 17 +constexpr UINT distinct_views = 3000; // slot 18 +constexpr UINT distinct_samplers = 100; // slot 22 + +template<class Result = HRESULT, class... Args> +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast<unsigned long>(hr)); + return SUCCEEDED(hr); +} + +ComPtr<IDXGIAdapter1> pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +unsigned long long process_commit() +{ + PROCESS_MEMORY_COUNTERS_EX counters{}; + if (!GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&counters), sizeof(counters))) + return 0; + return counters.PrivateUsage; +} + +// Puts this process in its own job with a commit limit. The job lives until the process ends. +bool limit_commit(unsigned long long limit) +{ + const HANDLE job = CreateJobObjectW(nullptr, nullptr); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; + info.JobMemoryLimit = static_cast<SIZE_T>(limit); + return job && SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)) && + AssignProcessToJobObject(job, GetCurrentProcess()); +} + +struct Census { + unsigned long long cbv, srv, uav, rtv, dsv, sampler, records, capacity, ids, buckets, grows_records, grows_ids, missed; +}; + +bool read_census(Census& c, const char* stage) +{ + char line[1024]{}; + if (!x2w_d3d12_view_census_line(line, sizeof(line))) { + std::printf("FAIL: %s: the census line is empty although the switch is on\n", stage); + return false; + } + const int fields = std::sscanf(line, + "x2w-view-census distinct by slot: cbv=%llu srv=%llu uav=%llu rtv=%llu dsv=%llu sampler=%llu records=%llu " + "capacity=%llu ids=%llu buckets=%llu grows-records=%llu grows-ids=%llu missed=%llu", + &c.cbv, &c.srv, &c.uav, &c.rtv, &c.dsv, &c.sampler, &c.records, &c.capacity, &c.ids, &c.buckets, + &c.grows_records, &c.grows_ids, &c.missed); + std::printf("%s: %s\n", stage, line); + if (fields != 13) std::printf("FAIL: %s: unreadable census line (%d fields)\n", stage, fields); + return fields == 13; +} + +bool check(bool ok, const char* what) +{ + if (!ok) std::printf("FAIL: %s\n", what); + return ok; +} + +std::string read_log() +{ + wchar_t path[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", path, MAX_PATH); + std::string text; + if (!length || length >= MAX_PATH) return text; + const HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return text; + char chunk[4096]; + DWORD got = 0; + while (ReadFile(file, chunk, sizeof(chunk), &got, nullptr) && got) text.append(chunk, got); + CloseHandle(file); + return text; +} + +unsigned long long occurrences(const std::string& text, const char* needle) +{ + unsigned long long count = 0; + for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; + return count; +} + +struct Streams { + IUnknown* guest; + UINT64 view_handle, sampler_handle; + + void constant_buffer(UINT index) const + { + const D3D12_CONSTANT_BUFFER_VIEW_DESC desc{0x100000ull + 256ull * index, 256}; + invoke<void>(guest, 17, &desc, view_handle); + } + void buffer_view(UINT index) const + { + D3D12_SHADER_RESOURCE_VIEW_DESC desc; + std::memset(&desc, 0, sizeof(desc)); // padding is part of the record's content + desc.Format = DXGI_FORMAT_R32_FLOAT; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = index; + desc.Buffer.NumElements = 1; + invoke<void>(guest, 18, static_cast<void*>(nullptr), &desc, view_handle); + } + void sampler(UINT index) const + { + D3D12_SAMPLER_DESC desc{}; + desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + desc.AddressU = desc.AddressV = desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + desc.MipLODBias = static_cast<float>(index) / 16.0f; + desc.MaxAnisotropy = 1; + desc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + desc.MaxLOD = D3D12_FLOAT32_MAX; + invoke<void>(guest, 22, &desc, sampler_handle); + } +}; + +bool scenario(const Streams& s, bool vary) +{ + // One of each first, so the repeated stream starts from records that already exist. + s.constant_buffer(0); + s.buffer_view(0); + s.sampler(0); + Census start{}, repeated{}, distinct{}; + if (!read_census(start, "start")) return false; + + const unsigned long long before_repeated = process_commit(); + for (UINT i = 0; i < repeated_calls; ++i) s.constant_buffer(vary ? i : 0); + for (UINT i = 0; i < distinct_views; ++i) s.buffer_view(0); + const unsigned long long after_repeated = process_commit(); + if (!read_census(repeated, "repeated")) return false; + if (!check(repeated.records == start.records && repeated.cbv == start.cbv && repeated.srv == start.srv && + repeated.sampler == start.sampler, + "the repeated stream added records")) + return false; + if (!check(repeated.capacity == start.capacity && repeated.buckets == start.buckets && + repeated.grows_records == start.grows_records && repeated.grows_ids == start.grows_ids, + "the repeated stream grew a container")) + return false; + + for (UINT i = 1; i <= distinct_buffers; ++i) s.constant_buffer(i); + for (UINT i = 1; i <= distinct_views; ++i) s.buffer_view(i); + for (UINT i = 1; i <= distinct_samplers; ++i) s.sampler(i); + const unsigned long long after_distinct = process_commit(); + if (!read_census(distinct, "distinct")) return false; + std::printf("commit bytes: repeated stream %+lld, distinct stream %+lld\n", + static_cast<long long>(after_repeated - before_repeated), + static_cast<long long>(after_distinct - after_repeated)); + if (!check(distinct.cbv - repeated.cbv == distinct_buffers, "slot 17 count") || + !check(distinct.srv - repeated.srv == distinct_views, "slot 18 count") || + !check(distinct.sampler - repeated.sampler == distinct_samplers, "slot 22 count") || + !check(!distinct.uav && !distinct.rtv && !distinct.dsv, "a slot without calls has records") || + !check(distinct.records - repeated.records == distinct_buffers + distinct_views + distinct_samplers, + "record total") || + !check(distinct.ids == distinct.records, "ids and records differ") || + !check(distinct.capacity >= distinct.records, "capacity below size") || + !check(distinct.grows_records > repeated.grows_records, "no vector growth announced") || + !check(distinct.grows_ids > repeated.grows_ids, "no bucket growth announced") || + !check(!distinct.missed, "a container grew without an announcement")) + return false; + + // Every announced growth has its log line. + const std::string log = read_log(); + const unsigned long long both = occurrences(log, "x2w-view-census before growth of records and ids:"); + const unsigned long long records = occurrences(log, "x2w-view-census before growth of records:") + both; + const unsigned long long ids = occurrences(log, "x2w-view-census before growth of ids:") + both; + std::printf("growth lines in the log: records %llu, ids %llu\n", records, ids); + return check(records == distinct.grows_records && ids == distinct.grows_ids, "growth lines and counters differ"); +} + +// With the switch off the same calls report nothing. +bool nothing_reported(const Streams& s) +{ + for (UINT i = 0; i < 1000; ++i) s.constant_buffer(i); + char line[256]; + std::memset(line, 'x', sizeof(line)); + const std::size_t length = x2w_d3d12_view_census_line(line, sizeof(line)); + return check(!length && !line[0], "the census reported without its switch") && + check(!occurrences(read_log(), "x2w-view-census"), "the census logged without its switch"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "vary"))) + return 2; + const bool off = argc == 3 && !std::strcmp(argv[2], "off"); + const bool vary = argc == 3 && !std::strcmp(argv[2], "vary"); + char value[2]{}; + const bool census_on = GetEnvironmentVariableA("X2W_D3D12_VIEW_CENSUS", value, sizeof(value)) == 1 && value[0] == '1'; + wchar_t log_path[MAX_PATH]; + const DWORD log_length = GetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path, MAX_PATH); + if (census_on == off || !log_length || log_length >= MAX_PATH) { + std::puts("FAIL: the environment does not match the requested mode"); + return 2; + } + DeleteFileW(log_path); // before the stand-in writes its first line + + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr<IUnknown> guest, views, samplers; + std::array<unsigned char, 64> parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(guest.GetAddressOf())), "Xbox device")) + return 3; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}, sampler_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1}, 0, 0}; + if (!require(invoke(guest.Get(), 14, &view_heap, &__uuidof(ID3D12DescriptorHeap), views.GetAddressOf()), "view heap") || + !require(invoke(guest.Get(), 14, &sampler_heap, &__uuidof(ID3D12DescriptorHeap), samplers.GetAddressOf()), "sampler heap")) + return 3; + const Streams streams{guest.Get(), invoke<UINT64>(views.Get(), 9), invoke<UINT64>(samplers.Get(), 9)}; + + const unsigned long long held = process_commit(); + if (!held || !limit_commit(held + headroom)) { + std::printf("FAIL: could not set the job commit limit (error %lu)\n", GetLastError()); + return 4; + } + // The limit is real: a commit larger than the room under it is refused. + if (void* too_much = VirtualAlloc(nullptr, static_cast<SIZE_T>(headroom + held), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)) { + VirtualFree(too_much, 0, MEM_RELEASE); + std::puts("FAIL: the job commit limit did not refuse an allocation above it"); + return 4; + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + if (SUCCEEDED(adapter->GetDesc1(&adapter_desc))) std::printf("adapter=%ls\n", adapter_desc.Description); + std::printf("mode=%s, commit after setup %llu bytes, job limit %llu bytes\n", off ? "off" : vary ? "vary" : "on", held, + held + headroom); + if (!(off ? nothing_reported(streams) : scenario(streams, vary))) return 5; + std::puts(off ? "view-census off checks passed" : "view-census checks passed"); + return 0; +} diff --git a/tests/startup_view_dimension_check.cpp b/tests/startup_view_dimension_check.cpp new file mode 100644 index 0000000000..319d88ffd6 --- /dev/null +++ b/tests/startup_view_dimension_check.cpp @@ -0,0 +1,124 @@ +// Source-built control for view_dimension.h: whether a view's ViewDimension suits the dimension of +// the resource it is made on (desktop D3D12 removes the device for a mismatch). Values are the +// public d3d12.h enumerations. --control swaps the resource dimension of the mismatched cases for +// the matching one and enables default views for every slot in the gated cases, so the checks +// that expect a refusal must print FAIL. +#include <cstdio> +#include <cstring> + +#include "startup_stubs/view_dimension.h" + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +// A refusal case: in the control the resource is given the dimension the view needs. +bool refused(int slot, unsigned view_dimension, unsigned resource_dimension) +{ + using namespace x2w_view_dimension; + if (control) resource_dimension = needed(slot, view_dimension); + return !fits(slot, view_dimension, resource_dimension); +} +} // namespace + +int main(int argc, char** argv) +{ + using namespace x2w_view_dimension; + control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + + // Matching shapes are accepted. + check("SRV texture 2D on a 2D texture", fits(18, 4, texture2d)); + check("SRV cube on a 2D texture", fits(18, 9, texture2d)); + check("SRV cube array on a 2D texture", fits(18, 10, texture2d)); + check("SRV texture 3D on a 3D texture", fits(18, 8, texture3d)); + check("SRV buffer on a buffer", fits(18, 1, buffer)); + check("SRV texture 1D array on a 1D texture", fits(18, 3, texture1d)); + check("UAV texture 2D array on a 2D texture", fits(19, 5, texture2d)); + check("UAV texture 3D on a 3D texture", fits(19, 8, texture3d)); + check("RTV buffer on a buffer", fits(20, 1, buffer)); + check("RTV texture 2D on a 2D texture", fits(20, 4, texture2d)); + check("DSV texture 1D on a 1D texture", fits(21, 1, texture1d)); + check("DSV texture 2D on a 2D texture", fits(21, 3, texture2d)); + + // Values this check does not judge pass on: unknown dimension, raytracing structure, other slots. + check("SRV unknown dimension is not judged", fits(18, 0, texture3d)); + check("SRV raytracing structure is not judged", fits(18, 11, unknown)); + check("out-of-range SRV dimension is not judged", fits(18, 99, buffer)); + check("DSV dimension 7 is not judged", fits(21, 7, buffer)); + check("sampler slot is not judged", fits(22, 4, buffer)); + + // Mismatches are refused (the control turns each into a match, so these print FAIL). + check("SRV texture 2D on a 3D texture is refused", refused(18, 4, texture3d)); + check("SRV texture 3D on a 2D texture is refused", refused(18, 8, texture2d)); + check("SRV buffer on a 2D texture is refused", refused(18, 1, texture2d)); + check("SRV cube on a 3D texture is refused", refused(18, 9, texture3d)); + check("UAV texture 2D on a buffer is refused", refused(19, 4, buffer)); + check("RTV texture 3D on a 2D texture is refused", refused(20, 8, texture2d)); + check("DSV texture 2D on a 1D texture is refused", refused(21, 3, texture1d)); + + // ViewDimension 0 (unknown): a default view only where desktop allows a null description. Under + // X2W_D3D12_VIEW_DEFAULTS=all (experimental) every view type may get one. + const auto all = DefaultViews::all, srv = DefaultViews::srv, off = DefaultViews::off; + check("default SRV of an RGBA8 2D texture", default_view_allowed(18, texture2d, 28, all)); + check("default RTV of an RGBA8 2D texture", default_view_allowed(20, texture2d, 28, all)); + check("default DSV of a D32 2D texture", default_view_allowed(21, texture2d, 40, all)); + check("default SRV of a 3D texture", default_view_allowed(18, texture3d, 10, all)); + check("default SRV of an R16_SINT 2D texture", default_view_allowed(18, texture2d, 59, all)); + const auto no_default = [all](int slot, unsigned dimension, unsigned format) { + if (control) dimension = texture2d, format = 28; // a texture that has a default view + return !default_view_allowed(slot, dimension, format, all); + }; + check("no default view of a buffer", no_default(18, buffer, 28)); + check("no default view of a typeless texture", no_default(18, texture2d, 27)); + check("no default view of a typeless BC7 texture", no_default(19, texture2d, 97)); + check("no default view of a typeless R8 texture", no_default(18, texture2d, 60)); + check("no default SRV of a depth texture", no_default(18, texture2d, 40)); + check("no default view of an unknown format", no_default(18, texture2d, 0)); + check("no default view on the constant-buffer slot", !default_view_allowed(17, texture2d, 28, all)); + + // The default (srv): only the measured typed-SRV case; UAV, RTV and DSV need the experiment. + // The control enables all slots, so the three refusals print FAIL. + const auto gated = [all, srv](int slot, unsigned dimension, unsigned format) { + return !default_view_allowed(slot, dimension, format, control ? all : srv); + }; + check("default SRV of an RGBA8 2D texture without the experiment", default_view_allowed(18, texture2d, 28, srv)); + check("default SRV of a 3D texture without the experiment", default_view_allowed(18, texture3d, 10, srv)); + check("no default SRV of a depth texture without the experiment", !default_view_allowed(18, texture2d, 40, srv)); + check("no default UAV without the experiment", gated(19, texture2d, 28)); + check("no default RTV without the experiment", gated(20, texture2d, 28)); + check("no default DSV without the experiment", gated(21, texture2d, 40)); + check("off: no default SRV", !default_view_allowed(18, texture2d, 28, off)); + check("off: no default RTV", !default_view_allowed(20, texture2d, 28, off)); + + // X2W_D3D12_VIEW_DEFAULTS parsing: exact "all" or "off", anything else is the default. + check("unset is srv", default_views_mode(nullptr) == srv); + check("empty is srv", default_views_mode("") == srv); + check("all", default_views_mode("all") == all); + check("off", default_views_mode("off") == off); + check("ALL is srv", default_views_mode("ALL") == srv); + check("allx is srv", default_views_mode("allx") == srv); + check("1 is srv", default_views_mode("1") == srv); + + // A refused SRV's null descriptor keeps a texture dimension and turns the rest into texture 2D. + check("null for a refused 3D view is 3D", refused_srv_null_dimension(8) == 8); + check("null for a refused cube array is a cube array", refused_srv_null_dimension(10) == 10); + check("null for a refused 1D view is 1D", refused_srv_null_dimension(2) == 2); + check("null for a refused unknown view is 2D", refused_srv_null_dimension(0) == 4); + check("null for a refused buffer view is 2D", refused_srv_null_dimension(1) == 4); + check("null for a refused raytracing view is 2D", refused_srv_null_dimension(11) == 4); + + if (failures) { + std::printf("startup_view_dimension: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_view_dimension: ok"); + return 0; +} diff --git a/tests/startup_view_dimension_device.cpp b/tests/startup_view_dimension_device.cpp new file mode 100644 index 0000000000..823b6c7c77 --- /dev/null +++ b/tests/startup_view_dimension_device.cpp @@ -0,0 +1,425 @@ +// Device slot 18 (CreateShaderResourceView) through d3d12_xs.dll with view descriptions whose ViewDimension is +// unknown or does not suit the resource (src/startup_stubs/view_dimension.h, docs/startup-runtime.md#unknown-and- +// mismatched-view-dimensions). +// +// startup_view_dimension_device <warp|hardware> [off] +// +// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue +// samples texel (0,0) through a slot of a shader-visible guest heap, by the desktop heap behind it. A null +// descriptor reads zero. +// (a) an SRV with ViewDimension 0 and a requested format that differs from the texture's (R32G32B32A32_FLOAT on an +// R8G8B8A8_UNORM texture) gets the texture's default view: the slot samples the texture's distinct colour. +// (b) an explicit TEXTURE3D SRV of the 2D texture is refused: the device is not removed. +// (c) a slot that holds a valid view of a second texture (its colour is read first) receives a refused TEXTURE2D +// SRV of a buffer. The device is not removed and the slot reads zero: the refusal leaves a null SRV, not the +// old descriptor. A CopyDescriptorsSimple copy of the slot over another valid view reads zero too. +// (d) a refused UAV replacement leaves the prior descriptor and its title token intact. +// +// `off` is the negative control and needs X2W_D3D12_VIEW_DEFAULTS=off: (a) must then fail, printing +// "FAIL: (a) default view reads 0.000 0.000 0.000 0.000 ... device not removed", and nothing else may fail. +#include <d3d12.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <cwchar> + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +constexpr UINT side = 4, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr std::uint8_t colour_a[4] = {51, 153, 204, 255}; // 0.2 0.6 0.8 1.0 +constexpr std::uint8_t colour_b[4] = {255, 64, 0, 128}; + +template<class Result = HRESULT, class... Args> +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +template<class T> +ComPtr<T> desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr<T> output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr<IUnknown> reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast<IUnknown*>(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: setup: %s hr=0x%08lx\n", stage, static_cast<unsigned long>(hr)); + return SUCCEEDED(hr); +} + +ComPtr<IDXGIAdapter1> pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +constexpr char probe_shader[] = R"( +Texture2D<float4> source : register(t0); +SamplerState point_sampler : register(s0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.SampleLevel(point_sampler, float2(0.125, 0.125), 0))); +} +)"; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ComPtr<ID3D12CommandQueue> queue; + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<ID3D12GraphicsCommandList> list; + ComPtr<ID3D12Fence> fence; + UINT64 value = 0; + HANDLE event = nullptr; + ComPtr<ID3D12Resource> upload, readback, probe_out; + ComPtr<ID3D12RootSignature> root; + ComPtr<ID3D12PipelineState> pso; + ComPtr<IUnknown> heap; + ComPtr<ID3D12DescriptorHeap> heap_real; + UINT64 heap_cpu = 0; + UINT increment = 0; + + bool run() + { + if (!require(list->Close(), "list close")) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (!require(queue->Signal(fence.Get(), ++value), "signal")) return false; + if (fence->GetCompletedValue() >= value) return true; + if (!require(fence->SetEventOnCompletion(value, event), "fence event")) return false; + if (WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0) return true; + std::puts("FAIL: setup: queue timed out"); + return false; + } + bool begin() { return require(allocator->Reset(), "allocator reset") && require(list->Reset(allocator.Get(), nullptr), "list reset"); } + ComPtr<IUnknown> committed(const D3D12_RESOURCE_DESC& desc, const char* name) + { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + const GUID iid = __uuidof(ID3D12Resource); + ComPtr<IUnknown> out; + if (!require(invoke(guest, 127, &props, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid, out.GetAddressOf()), name)) + out.Reset(); + return out; + } + // Fills every texel of a guest 2D texture with one colour through its desktop object. + bool fill(IUnknown* texture, const std::uint8_t (&colour)[4]) + { + const auto real = desktop_object<ID3D12Resource>(guest, device, texture); + if (!real) { + std::puts("FAIL: setup: texture has no desktop object"); + return false; + } + void* mapped = nullptr; + const D3D12_RANGE none{}; + if (!require(upload->Map(0, &none, &mapped), "upload map")) return false; + auto* dst = static_cast<std::uint8_t*>(mapped); + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < side; ++x) std::memcpy(dst + y * pitch + x * 4, colour, 4); + upload->Unmap(0, nullptr); + if (!begin()) return false; + D3D12_TEXTURE_COPY_LOCATION to{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + to.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + from.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COMMON}; + list->ResourceBarrier(1, &b); + return run(); + } + // Samples texel (0,0) through the desktop descriptor behind slot `index` of the guest heap. + bool read_slot(UINT index, float (&texel)[4]) + { + if (!begin()) return false; + ID3D12DescriptorHeap* bound = heap_real.Get(); + D3D12_GPU_DESCRIPTOR_HANDLE gpu = heap_real->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += std::uint64_t{index} * increment; + list->SetDescriptorHeaps(1, &bound); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(pso.Get()); + list->SetComputeRootDescriptorTable(0, gpu); + list->SetComputeRootUnorderedAccessView(1, probe_out->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {probe_out.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(readback.Get(), 0, probe_out.Get(), 0, 16); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + list->ResourceBarrier(1, &b); + if (!run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, 16}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + std::memcpy(texel, mapped, sizeof(texel)); + readback->Unmap(0, nullptr); + return true; + } + const char* device_state() + { + return SUCCEEDED(device->GetDeviceRemovedReason()) && SUCCEEDED(invoke(guest, 37)) ? "device not removed" + : "DEVICE REMOVED"; + } + bool device_ok() { return SUCCEEDED(device->GetDeviceRemovedReason()) && SUCCEEDED(invoke(guest, 37)); } + // want: the colour the slot must sample, or nullptr for null (all zero). *failed is set on a mismatch; false is + // returned only when the probe itself could not run. + bool expect(UINT index, const std::uint8_t* want, const char* what, bool* failed) + { + float texel[4]{}; + if (!read_slot(index, texel)) return false; + bool match = true; + for (int i = 0; i < 4; ++i) { + const float expected = want ? want[i] / 255.0f : 0.0f; + if (std::fabs(texel[i] - expected) > 0.5f / 255.0f) match = false; + } + if (match) { + std::printf("%s: reads %.3f %.3f %.3f %.3f as expected\n", what, texel[0], texel[1], texel[2], texel[3]); + return true; + } + std::printf("FAIL: %s reads %.3f %.3f %.3f %.3f, expected ", what, texel[0], texel[1], texel[2], texel[3]); + if (want) std::printf("%.3f %.3f %.3f %.3f", want[0] / 255.0f, want[1] / 255.0f, want[2] / 255.0f, want[3] / 255.0f); + else std::printf("null (all zero)"); + std::printf("; %s\n", device_state()); + *failed = true; + return true; + } + UINT64 slot(UINT index) const { return heap_cpu + std::uint64_t{index} * increment; } +}; + +D3D12_SHADER_RESOURCE_VIEW_DESC texture2d_view() +{ + 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.MipLevels = 1; + return srv; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off"))) + return 2; + const bool off = argc == 3; + char mode[8]{}; + const DWORD mode_n = GetEnvironmentVariableA("X2W_D3D12_VIEW_DEFAULTS", mode, sizeof(mode)); + const bool env_off = mode_n == 3 && std::strcmp(mode, "off") == 0; + if (env_off != off || (!off && mode_n)) { + std::puts("FAIL: setup: X2W_D3D12_VIEW_DEFAULTS must be unset, or off with the `off` argument"); + return 2; + } + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr<IUnknown> guest; + ComPtr<ID3D12Device> device; + std::array<unsigned char, 64> parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + std::printf("adapter=%ls debug_layer=off view_defaults=%s\n", adapter_desc.Description, off ? "off" : "unset (srv)"); + + Context c{guest.Get(), device.Get()}; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}, + default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC out_desc = buffer; + out_desc.Width = 256; + out_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.queue)), "queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.allocator)), "allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.allocator.Get(), nullptr, IID_PPV_ARGS(&c.list)), "list") || + !require(c.list->Close(), "list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.fence)), "fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback") || + !require(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &out_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&c.probe_out)), "probe output")) + return 4; + + // The probe: samples (0,0) through descriptor table slot 0 with a point sampler. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER root_parameters[2]{}; + root_parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + root_parameters[0].DescriptorTable = {1, &range}; + root_parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + root_parameters[1].Descriptor = {0, 0}; + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, root_parameters, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> root_blob, errors, code; + if (!require(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, root_blob.GetAddressOf(), + errors.GetAddressOf()), "root serialize") || + !require(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), IID_PPV_ARGS(&c.root)), + "root signature") || + !require(D3DCompile(probe_shader, std::strlen(probe_shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, + code.GetAddressOf(), errors.ReleaseAndGetAddressOf()), "probe shader")) + return 4; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = c.root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (!require(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&c.pso)), "probe pipeline")) return 4; + + // A shader-visible guest heap of four SRV slots. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (!require(invoke(c.guest, 14, &request, &__uuidof(ID3D12DescriptorHeap), c.heap.GetAddressOf()), "guest heap")) return 4; + c.heap_real = desktop_object<ID3D12DescriptorHeap>(c.guest, device.Get(), c.heap.Get()); + if (!c.heap_real) { + std::puts("FAIL: setup: guest heap has no desktop object"); + return 4; + } + c.heap_cpu = invoke<UINT64>(c.heap.Get(), 9); + + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC small_buffer = buffer; + small_buffer.Width = 256; + const auto texture_a = c.committed(texture_desc, "texture A"); + const auto texture_b = c.committed(texture_desc, "texture B"); + const auto buffer_c = c.committed(small_buffer, "buffer"); + if (!texture_a || !texture_b || !buffer_c || !c.fill(texture_a.Get(), colour_a) || !c.fill(texture_b.Get(), colour_b)) + return 4; + if (!c.device_ok()) { + std::puts("FAIL: setup: device removed before the cases"); + return 4; + } + + bool failed = false; + // (a) ViewDimension 0 with another format: the texture's default view. + D3D12_SHADER_RESOURCE_VIEW_DESC unknown{}; + unknown.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + unknown.ViewDimension = D3D12_SRV_DIMENSION_UNKNOWN; + unknown.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + invoke<void>(c.guest, 18, texture_a.Get(), &unknown, c.slot(0)); + if (!c.device_ok()) { + std::puts("FAIL: (a) the unknown-dimension SRV removed the device"); + return 5; + } + if (!c.expect(0, colour_a, "(a) default view", &failed)) return 4; + + // (b) an explicit TEXTURE3D SRV of the 2D texture: refused, the device stays. + D3D12_SHADER_RESOURCE_VIEW_DESC volume = texture2d_view(); + volume.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + volume.Texture3D = {0, 1, 0.0f}; + invoke<void>(c.guest, 18, texture_a.Get(), &volume, c.slot(1)); + if (!c.device_ok()) { + std::puts("FAIL: (b) the incompatible explicit SRV was forwarded and removed the device"); + return 5; + } + std::puts("(b) TEXTURE3D SRV of a 2D texture: refused, device not removed"); + + // (c) a refused replacement over a valid view, and a copy of the slot over another valid view. + const auto valid = texture2d_view(); + invoke<void>(c.guest, 18, texture_b.Get(), &valid, c.slot(2)); + invoke<void>(c.guest, 18, texture_b.Get(), &valid, c.slot(3)); + bool setup_failed = false; + if (!c.expect(2, colour_b, "(c) valid view before the replacement", &setup_failed) || + !c.expect(3, colour_b, "(c) valid copy target before the copy", &setup_failed)) + return 4; + if (setup_failed) { + std::puts("FAIL: setup: valid views do not read their texture"); + return 4; + } + invoke<void>(c.guest, 18, buffer_c.Get(), &valid, c.slot(2)); // TEXTURE2D of a buffer + if (!c.device_ok()) { + std::puts("FAIL: (c) the refused replacement removed the device"); + return 5; + } + if (!c.expect(2, nullptr, "(c) slot after the refused replacement", &failed)) return 4; + invoke<void>(c.guest, 24, 1u, c.slot(3), c.slot(2), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!c.expect(3, nullptr, "(c) copy of the refused slot", &failed)) return 4; + + auto uav_desc = texture_desc; + uav_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto uav_texture = c.committed(uav_desc, "UAV texture"); + if (!uav_texture) return 4; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + const auto uav_slot = c.slot(1); + invoke<void>(c.guest, 19, uav_texture.Get(), static_cast<IUnknown*>(nullptr), &uav, uav_slot); + if (!c.device_ok()) return 5; + std::array<std::uint32_t, 8> before{}, after{}; + std::memcpy(before.data(), reinterpret_cast<const void*>(uav_slot), sizeof(before)); + if (!before[0] || before[2] != 19) { + std::puts("FAIL: (d) no valid UAV token before the replacement"); + return 4; + } + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + uav.Texture3D = {0, 0, 1}; + invoke<void>(c.guest, 19, uav_texture.Get(), static_cast<IUnknown*>(nullptr), &uav, uav_slot); + std::memcpy(after.data(), reinterpret_cast<const void*>(uav_slot), sizeof(after)); + if (after != before) { + std::puts("FAIL: (d) refused UAV replacement changed the live descriptor token"); + failed = true; + } else { + std::puts("(d) refused UAV replacement kept the live descriptor token"); + } + + if (!c.device_ok()) { + std::puts("FAIL: device removed after the cases"); + return 5; + } + std::printf("cases complete, %s\n", failed ? "with failures" : "all passed"); + if (failed) return 1; + std::puts("startup_view_dimension_device: default SRV samples its texture; refused SRVs leave null descriptors; " + "device not removed"); + return 0; +} diff --git a/tests/startup_window_capture_check.py b/tests/startup_window_capture_check.py new file mode 100644 index 0000000000..ba1bf351a2 --- /dev/null +++ b/tests/startup_window_capture_check.py @@ -0,0 +1,145 @@ +"""Check the pure parts of the startup debugger's periodic window pictures (tools/startup/window_capture.py). + +usage: startup_window_capture_check.py + +Covers the BGRA -> PNG conversion (decoded again and compared with a per-pixel reference), the file names, the +skip of a frame that equals the previous one, the file cap, and the summary line. The Windows side (a real +window whose picture changes at a known time) is tests/startup_debug_check.py, group "window". +""" +import os +import struct +import sys +import tempfile +import unittest +import zlib + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools", "startup")) +from window_capture import PNG_SIGNATURE, Series, frame_hash, frame_name, png_bytes # noqa: E402 + + +def decode_png(data): + """(width, height, [rows of RGB bytes]) of a truecolour 8 bit PNG with filter 0 on every row.""" + assert data[:8] == PNG_SIGNATURE + at, idat, header = 8, b"", None + while at < len(data): + size, kind = struct.unpack_from(">I4s", data, at) + body = data[at + 8:at + 8 + size] + assert struct.unpack_from(">I", data, at + 8 + size)[0] == zlib.crc32(kind + body) & 0xFFFFFFFF, kind + if kind == b"IHDR": + header = struct.unpack(">IIBBBBB", body) + elif kind == b"IDAT": + idat += body + at += 12 + size + width, height, depth, colour, _, _, _ = header + assert (depth, colour) == (8, 2) + raw = zlib.decompress(idat) + stride = 1 + width * 3 + assert len(raw) == stride * height + rows = [] + for y in range(height): + assert raw[y * stride] == 0, "filter byte" + rows.append(raw[y * stride + 1:(y + 1) * stride]) + return width, height, rows + + +def reference_rows(width, height, bgra): + """Per-pixel BGRA -> RGB, the slow way the first capture code did it.""" + return [bytes(b for x in range(width) for b in (bgra[(y * width + x) * 4 + 2], bgra[(y * width + x) * 4 + 1], + bgra[(y * width + x) * 4])) for y in range(height)] + + +def picture(width, height, seed): + return bytes((seed * 31 + i * 7 + (i >> 3)) & 0xFF for i in range(width * height * 4)) + + +class Conversion(unittest.TestCase): + def test_png_matches_the_per_pixel_reference(self): + for width, height in ((1, 1), (3, 2), (17, 5), (64, 3)): + pixels = picture(width, height, width) + self.assertEqual(decode_png(png_bytes(width, height, pixels)), (width, height, reference_rows(width, height, pixels))) + + def test_alpha_is_dropped_and_channels_are_swapped(self): + self.assertEqual(decode_png(png_bytes(1, 1, bytes([10, 20, 30, 99])))[2], [bytes([30, 20, 10])]) + + def test_level_changes_the_size_not_the_picture(self): + pixels = bytes(4 * 40 * 40) + self.assertEqual(decode_png(png_bytes(40, 40, pixels, 1)), decode_png(png_bytes(40, 40, pixels, 9))) + + def test_a_buffer_that_does_not_fit_is_refused(self): + for args in ((2, 2, bytes(15)), (0, 2, b""), (2, 0, b"")): + with self.assertRaises(ValueError): + png_bytes(*args) + + +class Naming(unittest.TestCase): + def test_names_are_whole_seconds_with_three_digits(self): + self.assertEqual([frame_name(s) for s in (0, 1.9, 74, 120.4, 1000)], + ["window_000s.png", "window_001s.png", "window_074s.png", "window_120s.png", "window_1000s.png"]) + + def test_hash_depends_on_pixels_and_size(self): + pixels = bytes(16) + self.assertEqual(frame_hash(2, 2, pixels), frame_hash(2, 2, bytes(16))) + self.assertNotEqual(frame_hash(2, 2, pixels), frame_hash(4, 1, pixels)) + self.assertNotEqual(frame_hash(2, 2, pixels), frame_hash(2, 2, bytes(15) + b"\x01")) + + +class Frames(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.a, self.b, self.c = (picture(4, 4, seed) for seed in (1, 2, 3)) + + def files(self): + return sorted(os.listdir(self.dir.name)) + + def test_identical_frames_are_skipped_and_changes_are_saved(self): + series = Series(self.dir.name) + results = [series.offer(t, 4, 4, p) for t, p in ((5, self.a), (10, self.a), (15, self.a), (20, self.b), (25, self.b), (30, self.a))] + self.assertEqual(results, ["saved", "unchanged", "unchanged", "saved", "unchanged", "saved"]) + self.assertEqual(self.files(), ["window_005s.png", "window_020s.png", "window_030s.png"]) + self.assertEqual((series.saved, series.unchanged, series.first_change), (3, 3, 20)) + with open(os.path.join(self.dir.name, "window_020s.png"), "rb") as handle: + self.assertEqual(decode_png(handle.read())[2], reference_rows(4, 4, self.b)) + + def test_a_size_change_is_a_change(self): + series = Series(self.dir.name) + self.assertEqual(series.offer(1, 4, 4, bytes(64)), "saved") + self.assertEqual(series.offer(2, 2, 8, bytes(64)), "saved") + + def test_file_cap_stops_saving_and_counts_what_it_dropped(self): + series = Series(self.dir.name, cap=2) + results = [series.offer(t, 4, 4, picture(4, 4, t)) for t in range(1, 6)] + self.assertEqual(results, ["saved", "saved", "capped", "capped", "capped"]) + self.assertEqual(self.files(), ["window_001s.png", "window_002s.png"]) + self.assertEqual(series.offer(9, 4, 4, picture(4, 4, 50)), "capped") + self.assertIn("file cap 2 reached (4 changed frames dropped)", series.summary()) + + def test_default_cap_is_120_files(self): + series = Series(self.dir.name, write=lambda path, data: None) + for t in range(300): + series.offer(t, 2, 2, bytes([t & 255, (t >> 8) & 255] * 8)) + self.assertEqual((series.saved, series.dropped), (120, 180)) + + def test_summary_line(self): + series = Series(self.dir.name) + self.assertEqual(series.summary(), "window captures: 0 saved, 0 unchanged skipped, no change seen") + series.offer(5, 4, 4, self.a) + series.offer(10, 4, 4, self.a) + self.assertEqual(series.summary(), "window captures: 1 saved, 1 unchanged skipped, no change seen") + series.offer(74, 4, 4, self.b) + series.miss() + self.assertEqual(series.summary(), "window captures: 2 saved, 1 unchanged skipped, first change at 74 s, 1 ticks without a window") + + def test_a_failing_write_leaves_the_series_unchanged(self): + def refuse(path, data): + raise OSError("disk full") + series = Series(self.dir.name, write=refuse) + with self.assertRaises(OSError): + series.offer(1, 4, 4, self.a) + self.assertEqual((series.saved, series.unchanged), (0, 0)) + series._write = Series._write_file + self.assertEqual(series.offer(2, 4, 4, self.a), "saved") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/startup_window_probe.cpp b/tests/startup_window_probe.cpp new file mode 100644 index 0000000000..401ea12635 --- /dev/null +++ b/tests/startup_window_probe.cpp @@ -0,0 +1,63 @@ +// Input for tests/startup_debug_window_check.py: one visible window whose picture changes at a known time. +// +// A 160x120 popup window at the top left corner of the screen, painted red; after STARTUP_WINDOW_PROBE_FLIP_MS +// milliseconds (default 3500) it is painted blue. The probe keeps running until the debugger ends the run +// (or for one minute), so the debugger's end-of-run window.png shows the last picture. +#include <windows.h> + +#include <cstdio> +#include <cstdlib> + +namespace { +COLORREF g_color = RGB(200, 30, 30); + +LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) +{ + if (message == WM_PAINT) { + PAINTSTRUCT paint{}; + HDC dc = BeginPaint(hwnd, &paint); + RECT area{}; + GetClientRect(hwnd, &area); + HBRUSH brush = CreateSolidBrush(g_color); + FillRect(dc, &area, brush); + DeleteObject(brush); + EndPaint(hwnd, &paint); + return 0; + } + if (message == WM_ERASEBKGND) return 1; + return DefWindowProcW(hwnd, message, wparam, lparam); +} +} // namespace + +int main() +{ + WNDCLASSW wc{}; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpfnWndProc = window_proc; + wc.lpszClassName = L"startup_window_probe"; + if (!RegisterClassW(&wc)) return 1; + HWND hwnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_NOACTIVATE, wc.lpszClassName, L"window probe", WS_POPUP | WS_VISIBLE, + 0, 0, 160, 120, nullptr, nullptr, wc.hInstance, nullptr); + if (!hwnd) return 2; + ULONGLONG flip_ms = 3500; + char text[32]; + if (GetEnvironmentVariableA("STARTUP_WINDOW_PROBE_FLIP_MS", text, sizeof(text)) && text[0]) flip_ms = strtoull(text, nullptr, 10); + const ULONGLONG begin = GetTickCount64(); + bool flipped = false; + std::printf("window-probe shown\n"); + std::fflush(stdout); + while (GetTickCount64() - begin < 60000) { + MSG message; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) DispatchMessageW(&message); + if (!flipped && GetTickCount64() - begin >= flip_ms) { + g_color = RGB(30, 30, 200); + InvalidateRect(hwnd, nullptr, TRUE); + UpdateWindow(hwnd); + flipped = true; + std::printf("window-probe flipped\n"); + std::fflush(stdout); + } + Sleep(10); + } + return 0; +} diff --git a/tests/startup_wrap_allocation.cpp b/tests/startup_wrap_allocation.cpp new file mode 100644 index 0000000000..c2d0b02ec6 --- /dev/null +++ b/tests/startup_wrap_allocation.cpp @@ -0,0 +1,206 @@ +// #2653: when the D3D12 stand-in cannot allocate an object wrapper, the slot that creates the object returns +// E_OUTOFMEMORY with a null output instead of writing through a null pointer. The fixture-only export +// x2w_d3d12_fail_wraps makes the next wrapper allocations fail; each slot is then called once armed and once +// normally. +// +// startup_wrap_allocation [control] (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_DEBUG=0) +// "control" never arms the failure, so every armed expectation must fail and the fixture must print FAIL. +#include <windows.h> + +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdio> +#include <cstring> +#include <memory> + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_fail_wraps(LONG count); + +namespace { + +bool control; +int failures; + +template<class... Args> +HRESULT invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = HRESULT (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +void arm() +{ + if (!control) x2w_d3d12_fail_wraps(1); +} + +// One creation: armed it must return E_OUTOFMEMORY and leave the output null; then it must succeed. +template<class Create> +void check(const char* name, Create create) +{ + ComPtr<IUnknown> object; + arm(); + HRESULT hr = create(object.ReleaseAndGetAddressOf()); + x2w_d3d12_fail_wraps(0); + const bool refused = hr == E_OUTOFMEMORY && !object; + if (!refused) { + std::printf("FAIL: %s with the wrapper allocation failing returned 0x%08lx and %s output\n", name, + static_cast<unsigned long>(hr), object ? "a non-null" : "a null"); + ++failures; + } + hr = create(object.ReleaseAndGetAddressOf()); + if (FAILED(hr) || !object) { + std::printf("FAIL: %s afterwards returned 0x%08lx\n", name, static_cast<unsigned long>(hr)); + ++failures; + return; + } + if (refused) std::printf("%s: E_OUTOFMEMORY with a null output, then S_OK\n", name); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 || (argc == 2 && std::strcmp(argv[1], "control"))) return 2; + control = argc == 2; + + ComPtr<IDXGIFactory4> factory; + ComPtr<IDXGIAdapter1> adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) + return 77; + std::array<unsigned char, 64> parameters{}; + + // Device creation itself: the desktop device reference is released and the output stays null. + ComPtr<IUnknown> device; + check("D3D12XboxCreateDevice", [&](IUnknown** out) { + return D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), reinterpret_cast<void**>(out)); + }); + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(device.GetAddressOf()))) || !device) { + std::puts("FAIL: no device to continue with"); + return 3; + } + + // Slot 55, derived pipeline: the placeholder path of the reported stop. + check("Device::slot55 derived pipeline", [&](IUnknown** out) { + return invoke(device.Get(), 55, static_cast<void*>(nullptr), 0u, static_cast<const void*>(nullptr), + &__uuidof(ID3D12PipelineState), reinterpret_cast<void**>(out)); + }); + + // Slot 8, command queue: a desktop queue is created before the wrapper. + const D3D12_COMMAND_QUEUE_DESC queue{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check("Device::CreateCommandQueue", [&](IUnknown** out) { + return invoke(device.Get(), 8, &queue, &__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(out)); + }); + + // A failed device creation must leave the previously published device visible to its children. + if (!control) { + ComPtr<ID3D12CommandQueue> existing_queue; + HRESULT hr = invoke(device.Get(), 8, &queue, &__uuidof(ID3D12CommandQueue), + reinterpret_cast<void**>(existing_queue.GetAddressOf())); + if (FAILED(hr) || !existing_queue) return 3; + + ComPtr<IUnknown> second_device; + arm(); + hr = D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(second_device.GetAddressOf())); + x2w_d3d12_fail_wraps(0); + if (hr != E_OUTOFMEMORY || second_device) { + std::puts("FAIL: second device allocation did not return E_OUTOFMEMORY and a null output"); + ++failures; + } + ComPtr<IUnknown> parent; + hr = existing_queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(parent.GetAddressOf())); + if (FAILED(hr) || parent.Get() != device.Get()) { + std::puts("FAIL: failed device creation changed the existing queue's device"); + ++failures; + } + } + + // Slot 16, root signature: a desktop root signature is created before the wrapper. + ComPtr<ID3DBlob> blob; + const D3D12_ROOT_SIGNATURE_DESC empty{}; + if (FAILED(D3D12SerializeRootSignature(&empty, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 3; + check("Device::CreateRootSignature", [&](IUnknown** out) { + return invoke(device.Get(), 16, 0u, blob->GetBufferPointer(), blob->GetBufferSize(), &__uuidof(ID3D12RootSignature), + reinterpret_cast<void**>(out)); + }); + + // Slot 14, descriptor heap: memory of the stand-in's own may back the heap before the wrapper. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4}, 0, 0}; + check("Device::CreateDescriptorHeap", [&](IUnknown** out) { + return invoke(device.Get(), 14, &heap, &__uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(out)); + }); + + // Slot 9, command allocator: the shared creation path (create_slot) wraps what desktop returned. + check("Device::CreateCommandAllocator", [&](IUnknown** out) { + return invoke(device.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + reinterpret_cast<void**>(out)); + }); + + // Slot 73, command list on that allocator: a desktop list is created before the 64 KiB list wrapper. + ComPtr<IUnknown> allocator; + if (FAILED(invoke(device.Get(), 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + reinterpret_cast<void**>(allocator.GetAddressOf())))) + return 3; + const std::array<UINT, 4> list_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + check("Device::slot73 command list", [&](IUnknown** out) { + return invoke(device.Get(), 73, static_cast<const void*>(list_desc.data()), static_cast<void*>(allocator.Get()), + static_cast<void*>(nullptr), &__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(out)); + }); + + // Slot 127, committed resource: a desktop buffer is created before the wrapper. + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 65536; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + check("Device::slot127 committed resource", [&](IUnknown** out) { + return invoke(device.Get(), 127, &props, 0u, &buffer, 0u, static_cast<const D3D12_CLEAR_VALUE*>(nullptr), + static_cast<void*>(nullptr), 0u, static_cast<const void*>(nullptr), &__uuidof(ID3D12Resource), + reinterpret_cast<void**>(out)); + }); + + const auto free_backing = [](void* ptr) { VirtualFree(ptr, 0, MEM_RELEASE); }; + const std::unique_ptr<void, decltype(free_backing)> backing( + VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE), free_backing); + if (!backing) { + std::puts("FAIL: could not allocate slot 133 fixture backing"); + return 3; + } + auto* base = static_cast<char*>(backing.get()); + buffer.Width = 256; + D3D12_RESOURCE_DESC texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = texture.Height = 4; + texture.DepthOrArraySize = texture.MipLevels = texture.SampleDesc.Count = 1; + texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + + const auto check_placement = [&](const char* name, void* address, const D3D12_RESOURCE_DESC& desc) { + check(name, [&](IUnknown** out) { + return invoke(device.Get(), 133, address, &desc, static_cast<UINT>(D3D12_RESOURCE_STATE_COMMON), + static_cast<const void*>(nullptr), &__uuidof(ID3D12Resource), reinterpret_cast<void**>(out)); + }); + }; + // The unaligned buffer address selects the desktop stand-in. Slot 133 also has a separate + // texture path, which creates a committed desktop texture before trying to wrap it. + check_placement("Device::slot133 placed buffer", base + 4, buffer); + check_placement("Device::slot133 placed texture", base + 2048, texture); + + if (failures) { + std::printf("FAIL: %d check(s)\n", failures); + return 1; + } + std::puts("PASS"); + return 0; +} diff --git a/tests/startup_xapu_opus_check.cpp b/tests/startup_xapu_opus_check.cpp index b3207f55a0..9402f4b16a 100644 --- a/tests/startup_xapu_opus_check.cpp +++ b/tests/startup_xapu_opus_check.cpp @@ -184,6 +184,63 @@ void expect_refused(const char* label, long want, const std::array<unsigned char check(untouched(out), label); } +void check_activated_stereo(std::uint32_t options) +{ + const std::array<std::uint32_t, 6> connection{1, 2, 2, 0x10000, 0, options}; + std::array<void*, 2> shared{}; + void* device = nullptr; + if (connect(connection.data(), shared.data(), &device) != hr_ok) { + check(false, "connect typed Opus stream"); + return; + } + std::array<unsigned char, 0x58> result{}; + auto open = plain_cmd(1, 0); + put(open, 24, 2u); + check(enqueue(device, open.data(), 0, 0) == hr_ok && dequeue(device, result.data()) == hr_ok, "activate stereo"); + auto packets = tone_packets(48000, 2, 960, 1); + int err = OPUS_OK; + OpusDecoder* reference = opus_decoder_create(48000, 2, &err); + if (packets.size() == 1 && reference) { + const auto& p = packets.front(); + float want[1920]{}; + check(opus_decode_float(reference, p.data(), static_cast<opus_int32>(p.size()), want, 960, 0) == 960, + "decode complete reference packet"); + auto out = filled(2 * 649); + const auto capacity = 2u * 648 * sizeof(float); + // The decoder must consume all 960 frames before trimming the 312-frame prefix. + auto cmd = decode_cmd(0, 1.0f, 960, p.data(), static_cast<std::uint32_t>(p.size()), + out.data(), static_cast<std::uint32_t>(capacity)); + put(cmd, 8, 37u); + put(cmd, 16, std::uint64_t{0x123456789abcdef0}); + put(cmd, 32, 312u); + result.fill(0xCD); + check(enqueue(device, cmd.data(), 0, 0) == hr_ok && dequeue(device, result.data()) == hr_ok, "decode trimmed packet"); + std::uint32_t frames{}, bytes{}; + std::memcpy(&frames, result.data() + 0x30, 4); + std::memcpy(&bytes, result.data() + 0x34, 4); + check(frames == 648 && bytes == capacity && std::memcmp(cmd.data(), result.data(), 24) == 0, + "completed frames, length and command identity"); + check(std::memcmp(result.data() + 0x38, cmd.data() + 0x38, 8) == 0 && + std::memcmp(result.data() + 0x44, cmd.data() + 0x28, 12) == 0, "completed packet and output spans"); + check(result[0x50] == 0xCD && result.back() == 0xCD, "next packed result is untouched"); + bool matches = true; + for (unsigned i = 0; i < 648; ++i) { + for (unsigned c = 0; c < 2; ++c) { + const auto dest = (options & 4) ? c * 648 + i : 2 * i + c; + matches &= out[dest] == want[2 * (312 + i) + c]; + } + } + check(matches && untouched(out, 1296), "trim and channel order match reference, tail preserved"); + auto close = plain_cmd(2, 0); + check(enqueue(device, close.data(), 0, 0) == hr_ok && dequeue(device, result.data()) == hr_ok, "close stereo"); + check(enqueue(device, cmd.data(), 0, 0) == hr_invalid_arg && get_count(device, 0) == 0, + "a closed stream cannot decode another packet"); + } else { + check(false, "construct stereo reference"); + } + if (reference) opus_decoder_destroy(reference); + disconnect(device); +} } // namespace int main(int argc, char** argv) @@ -199,6 +256,8 @@ int main(int argc, char** argv) enqueue = reinterpret_cast<EnqueueCommandFn>(GetProcAddress(module, "XApuEnqueueCommand")); disconnect = reinterpret_cast<DisconnectFn>(GetProcAddress(module, "XApuDisconnect")); if (!connect || !get_count || !dequeue || !enqueue || !disconnect) return std::printf("FAIL: missing export\n"), 2; + check_activated_stereo(1); + check_activated_stereo(5); std::array<unsigned char, 0x18> input{}; const std::uint32_t buffer_bytes = 0x104000; diff --git a/tests/startup_xapu_opus_count_check.cpp b/tests/startup_xapu_opus_count_check.cpp new file mode 100644 index 0000000000..fe2b2334dc --- /dev/null +++ b/tests/startup_xapu_opus_count_check.cpp @@ -0,0 +1,389 @@ +// Source-built checks for the optional XApu Opus telemetry: decoded packets, dequeued decoded +// completions, refusals by reason, and the stable summary line. Synthetic tones are encoded here +// with libopus; no game data or captured packet is used. +#include "startup_stubs/audio_telemetry.h" + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <opus.h> + +#include <array> +#include <atomic> +#include <cmath> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <limits> +#include <string> +#include <vector> + +namespace { + +using ConnectFn = long(__cdecl*)(const void* input, void* output, void** handle); +using GetResultCountFn = std::uint32_t(__cdecl*)(void* handle, std::uint64_t unused); +using DequeueResultFn = long(__cdecl*)(void* handle, void* result); +using EnqueueCommandFn = long(__cdecl*)(void* handle, const void* command, std::uint64_t r8, std::uint64_t r9); +using DisconnectFn = long(__cdecl*)(void* handle); + +constexpr long hr_ok = 0; +constexpr long hr_pointer = static_cast<long>(0x80004003); +constexpr long hr_handle = static_cast<long>(0x80070006); +constexpr long hr_out_of_memory = static_cast<long>(0x8007000E); +constexpr long hr_invalid_arg = static_cast<long>(0x80070057); +constexpr long hr_fail = static_cast<long>(0x80004005); +constexpr std::size_t result_size = 0x58; +constexpr std::size_t max_queue_entries = 16384; +constexpr unsigned char fill = 0xCD; + +int failures = 0; +ConnectFn connect; +GetResultCountFn get_count; +DequeueResultFn dequeue; +EnqueueCommandFn enqueue; +DisconnectFn disconnect; +void* handle; + +void check(bool condition, const char* label) +{ + if (condition) return; + ++failures; + std::printf("FAIL: %s\n", label); +} + +template <typename T> +void put(std::array<unsigned char, 0x60>& cmd, std::size_t offset, T value) +{ + std::memcpy(cmd.data() + offset, &value, sizeof(value)); +} + +// Type 3 command with the fields one title fills. +std::array<unsigned char, 0x60> decode_cmd(std::uint32_t slot, float rate, std::uint32_t frames, const void* packet, + std::uint32_t packet_bytes, void* out, std::uint32_t out_bytes) +{ + std::array<unsigned char, 0x60> cmd{}; + put(cmd, 0x00, std::uint32_t{3}); + put(cmd, 0x04, slot); + put(cmd, 0x1C, rate); + put(cmd, 0x24, frames); + put(cmd, 0x28, packet_bytes); + put(cmd, 0x2C, reinterpret_cast<std::uint64_t>(packet)); + put(cmd, 0x34, out_bytes); + put(cmd, 0x38, reinterpret_cast<std::uint64_t>(out)); + return cmd; +} + +std::array<unsigned char, 0x60> plain_cmd(std::uint32_t type, std::uint32_t slot) +{ + std::array<unsigned char, 0x60> cmd{}; + put(cmd, 0x00, type); + put(cmd, 0x04, slot); + return cmd; +} + +std::vector<unsigned char> tone_packet(int rate, int frames) +{ + int error = OPUS_OK; + OpusEncoder* encoder = opus_encoder_create(rate, 1, OPUS_APPLICATION_AUDIO, &error); + if (!encoder || error != OPUS_OK) return {}; + std::vector<float> pcm(static_cast<std::size_t>(frames)); + for (int i = 0; i < frames; ++i) + pcm[static_cast<std::size_t>(i)] = + 0.5f * static_cast<float>(std::sin(6.283185307179586 * 1000.0 * i / rate)); + std::vector<unsigned char> packet(4000); + const int n = opus_encode_float(encoder, pcm.data(), frames, packet.data(), static_cast<opus_int32>(packet.size())); + opus_encoder_destroy(encoder); + if (n <= 0) return {}; + packet.resize(static_cast<std::size_t>(n)); + return packet; +} + +std::vector<float> filled(std::size_t floats) +{ + std::vector<float> buffer(floats); + std::memset(buffer.data(), fill, floats * sizeof(float)); + return buffer; +} + +bool untouched(const std::vector<float>& buffer, std::size_t from = 0) +{ + const auto* bytes = reinterpret_cast<const unsigned char*>(buffer.data()); + for (std::size_t i = from * sizeof(float); i < buffer.size() * sizeof(float); ++i) + if (bytes[i] != fill) return false; + return true; +} + +struct Result { + std::uint32_t type = 0xFFFFFFFFu, slot = 0xFFFFFFFFu, bytes = 0xFFFFFFFFu; +}; + +Result pop() +{ + std::array<unsigned char, result_size> raw{}; + Result result; + if (dequeue(handle, raw.data()) != hr_ok) return result; + std::memcpy(&result.type, raw.data(), 4); + std::memcpy(&result.slot, raw.data() + 4, 4); + std::memcpy(&result.bytes, raw.data() + 0x34, 4); + return result; +} + +void expect_refused(const char* label, long want, const std::array<unsigned char, 0x60>& cmd, + const std::vector<float>& out) +{ + check(enqueue(handle, cmd.data(), 0, 0) == want, label); + check(get_count(handle, 0) == 0, label); + check(untouched(out), label); +} + +std::string read_log(const char* path) +{ + HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return {}; + std::string text; + char buffer[4096]; + for (;;) { + DWORD read = 0; + if (!ReadFile(file, buffer, sizeof(buffer), &read, nullptr) || read == 0) break; + text.append(buffer, read); + } + CloseHandle(file); + return text; +} + +struct Counts { + unsigned long long type3 = 0, packets = 0, completions = 0, refusals = 0; + unsigned long long invalid_argument = 0, opus_error = 0, capacity = 0, queue_full = 0; + unsigned long long short_command = 0, unknown_handle = 0, out_of_memory = 0, header = 0; +}; + +// Returns false on a malformed summary; counts every summary line in `lines`. +bool parse_summary(const std::string& text, Counts& counts, int& lines) +{ + counts = Counts{}; + lines = 0; + const char prefix[] = "x2w-audio XApu opus summary:"; + for (std::size_t start = 0; start < text.size();) { + const std::size_t end = text.find('\n', start); + const std::string line = text.substr(start, end == std::string::npos ? std::string::npos : end - start); + if (line.rfind(prefix, 0) == 0) { + Counts parsed; + const int fields = std::sscanf( + line.c_str(), + "x2w-audio XApu opus summary: type3=%llu packets=%llu completions=%llu refusals=%llu " + "invalid_argument=%llu opus_error=%llu capacity=%llu queue_full=%llu short_command=%llu " + "unknown_handle=%llu out_of_memory=%llu header=%llu", + &parsed.type3, &parsed.packets, &parsed.completions, &parsed.refusals, &parsed.invalid_argument, + &parsed.opus_error, &parsed.capacity, &parsed.queue_full, &parsed.short_command, + &parsed.unknown_handle, &parsed.out_of_memory, &parsed.header); + if (fields != 12) return false; + counts = parsed; + ++lines; + } + if (end == std::string::npos) break; + start = end + 1; + } + return true; +} + +void check_counts(const Counts& counts, const char* label) +{ + check(counts.type3 == 10, label); + check(counts.packets == 2, label); + check(counts.completions == 2, label); + check(counts.refusals == 9, label); + check(counts.invalid_argument == 3, label); + check(counts.opus_error == 1, label); + check(counts.capacity == 1, label); + check(counts.queue_full == 1, label); + check(counts.short_command == 1, label); + check(counts.unknown_handle == 1, label); + check(counts.out_of_memory == 0, label); + check(counts.header == 1, label); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return std::printf("usage: startup_xapu_opus_count_check <xapu.dll>\n"), 2; + + // The saturation contract is independent of the endpoint: prove the helper stops at UINT64_MAX. + std::atomic<std::uint64_t> bounded{(std::numeric_limits<std::uint64_t>::max)() - 1}; + x2w_audio::saturating_add(bounded, 2); + check(bounded == (std::numeric_limits<std::uint64_t>::max)(), "counter saturates at UINT64_MAX"); + x2w_audio::saturating_add(bounded); + check(bounded == (std::numeric_limits<std::uint64_t>::max)(), "a saturated counter stays at UINT64_MAX"); + + char temp_path[MAX_PATH]{}; + char log_path[MAX_PATH]{}; + if (!GetTempPathA(MAX_PATH, temp_path) || !GetTempFileNameA(temp_path, "x2w-opus-", 0, log_path)) + return std::printf("FAIL: cannot create the telemetry log path\n"), 2; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", "1"); + SetEnvironmentVariableA("X2W_TRAP_LOG", log_path); + + HMODULE module = LoadLibraryA(argv[1]); + if (!module) return std::printf("FAIL: cannot load %s\n", argv[1]), 2; + connect = reinterpret_cast<ConnectFn>(GetProcAddress(module, "XApuConnect")); + get_count = reinterpret_cast<GetResultCountFn>(GetProcAddress(module, "XApuGetResultCount")); + dequeue = reinterpret_cast<DequeueResultFn>(GetProcAddress(module, "XApuDequeueResult")); + enqueue = reinterpret_cast<EnqueueCommandFn>(GetProcAddress(module, "XApuEnqueueCommand")); + disconnect = reinterpret_cast<DisconnectFn>(GetProcAddress(module, "XApuDisconnect")); + if (!connect || !get_count || !dequeue || !enqueue || !disconnect) + return std::printf("FAIL: missing export\n"), 2; + + std::array<unsigned char, 0x18> input{}; + const std::uint32_t buffer_bytes = 0x10000; + std::memcpy(input.data() + 0x0C, &buffer_bytes, sizeof(buffer_bytes)); + std::array<unsigned char, 0x10> output{}; + if (connect(input.data(), output.data(), &handle) != hr_ok || !handle) + return std::printf("FAIL: XApuConnect\n"), 2; + + const auto packet = tone_packet(48000, 960); + if (packet.empty()) return std::printf("FAIL: libopus produced no packet\n"), 2; + + // Two successful packets, each completion retired by the caller. + for (int i = 0; i < 2; ++i) { + auto out = filled(964); + const auto cmd = decode_cmd(0, 48000.0f, 960, packet.data(), static_cast<std::uint32_t>(packet.size()), + out.data(), 3840); + check(enqueue(handle, cmd.data(), 0, 0) == hr_ok, "valid packet accepted"); + const Result result = pop(); + check(result.type == 3 && result.slot == 0 && result.bytes == 3840, "valid packet completes with 3840 bytes"); + check(untouched(out, 960), "valid packet leaves guard floats untouched"); + } + + // Malformed packet: libopus refuses it. + { + const unsigned char bad[] = {0x03, 0x00}; + auto out = filled(960); + expect_refused("malformed packet -> E_FAIL", hr_fail, + decode_cmd(1, 48000.0f, 960, bad, sizeof(bad), out.data(), 3840), out); + } + // Insufficient output capacity: libopus reports OPUS_BUFFER_TOO_SMALL for a 20 ms packet in 80 frames. + { + auto out = filled(964); + expect_refused("insufficient capacity -> E_FAIL", hr_fail, + decode_cmd(1, 48000.0f, 80, packet.data(), static_cast<std::uint32_t>(packet.size()), + out.data(), 320), out); + } + // Invalid argument before libopus. + { + auto out = filled(960); + expect_refused("rate 44100 -> E_INVALIDARG", hr_invalid_arg, + decode_cmd(1, 44100.0f, 960, packet.data(), static_cast<std::uint32_t>(packet.size()), + out.data(), 3840), out); + } + // An out-of-range slot is classified in the legacy decode path. + { + auto out = filled(960); + expect_refused("legacy slot UINT32_MAX -> E_INVALIDARG", hr_invalid_arg, + decode_cmd((std::numeric_limits<std::uint32_t>::max)(), 48000.0f, 960, packet.data(), + static_cast<std::uint32_t>(packet.size()), out.data(), 3840), out); + } + // A type 3 header whose decode fields cross a guard page. + if (auto* pages = static_cast<unsigned char*>(VirtualAlloc(nullptr, 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) { + DWORD old = 0; + check(VirtualProtect(pages + 0x1000, 0x1000, PAGE_NOACCESS, &old) != FALSE, "guard page for short command"); + const auto full = decode_cmd(1, 48000.0f, 960, packet.data(), static_cast<std::uint32_t>(packet.size()), + pages, 3840); + std::memcpy(pages + 0x1000 - 0x20, full.data(), 0x20); + check(enqueue(handle, pages + 0x1000 - 0x20, 0, 0) == hr_pointer, "short decode command -> E_POINTER"); + check(get_count(handle, 0) == 0, "short decode command queues nothing"); + VirtualFree(pages, 0, MEM_RELEASE); + } else { + check(false, "VirtualAlloc for short command"); + } + // A null header is a header refusal, not a type 3 one. + check(enqueue(handle, nullptr, 0, 0) == hr_pointer, "null command header -> E_POINTER"); + // A readable type 3 command on an unknown handle. + { + auto out = filled(960); + const auto cmd = decode_cmd(0, 48000.0f, 960, packet.data(), static_cast<std::uint32_t>(packet.size()), + out.data(), 3840); + check(enqueue(reinterpret_cast<void*>(0xDEADBEEFULL), cmd.data(), 0, 0) == hr_handle, + "unknown handle -> E_HANDLE"); + } + // Queue cap: the decode is refused before it touches the slot's decoder. + { + bool filled_up = true; + for (std::uint32_t i = 0; i < max_queue_entries && filled_up; ++i) + filled_up = enqueue(handle, plain_cmd(4, 99).data(), 0, 0) == hr_ok; + check(filled_up && get_count(handle, 0) == max_queue_entries, "queue fills to 16384 entries"); + auto out = filled(960); + const auto cmd = decode_cmd(1, 48000.0f, 960, packet.data(), static_cast<std::uint32_t>(packet.size()), + out.data(), 3840); + check(enqueue(handle, cmd.data(), 0, 0) == hr_out_of_memory, "full queue decode -> E_OUTOFMEMORY"); + check(untouched(out), "full queue refusal leaves output untouched"); + bool drained = true; + std::array<unsigned char, result_size> raw{}; + for (std::size_t i = 0; i < max_queue_entries && drained; ++i) + drained = dequeue(handle, raw.data()) == hr_ok; + check(drained && get_count(handle, 0) == 0, "capped queue drains"); + } + + // The typed-stream path rejects an out-of-range slot before decode_packet; keep this connection + // open until the legacy connection closes so both refusals reach one summary line. + std::array<unsigned char, 0x18> stream_input = input; + const std::uint32_t process = 1; + std::memcpy(stream_input.data(), &process, sizeof(process)); + void* stream_handle = nullptr; + check(connect(stream_input.data(), output.data(), &stream_handle) == hr_ok && stream_handle, + "stream XApuConnect"); + { + auto out = filled(960); + const auto cmd = decode_cmd((std::numeric_limits<std::uint32_t>::max)(), 48000.0f, 960, + packet.data(), static_cast<std::uint32_t>(packet.size()), out.data(), 3840); + check(enqueue(stream_handle, cmd.data(), 0, 0) == hr_invalid_arg, + "stream slot UINT32_MAX -> E_INVALIDARG"); + check(get_count(stream_handle, 0) == 0, "stream slot refusal queues nothing"); + check(untouched(out), "stream slot refusal leaves output untouched"); + } + check(disconnect(handle) == hr_ok, "XApuDisconnect succeeds"); + check(disconnect(stream_handle) == hr_ok, "stream XApuDisconnect succeeds"); + + Counts counts; + int lines = 0; + const std::string log = read_log(log_path); + check(parse_summary(log, counts, lines), "summary line has the documented fields"); + check(lines == 1, "one summary line after the last disconnect"); + check_counts(counts, "summary counts successes and each refusal reason"); + + // Typed completions off: the same command is queued without decoding and the counters do not move. + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + void* second = nullptr; + check(connect(input.data(), output.data(), &second) == hr_ok && second != nullptr, "second XApuConnect"); + auto out = filled(960); + const auto untyped = decode_cmd(2, 48000.0f, 960, packet.data(), static_cast<std::uint32_t>(packet.size()), + out.data(), 3840); + check(enqueue(second, untyped.data(), 0, 0) == hr_ok, "untyped type 3 accepted"); + std::array<unsigned char, result_size> raw{}; + check(dequeue(second, raw.data()) == hr_ok, "untyped type 3 completion"); + check(untouched(out), "untyped type 3 leaves output untouched"); + check(disconnect(second) == hr_ok, "second XApuDisconnect succeeds"); + Counts unchanged; + int after = 0; + check(parse_summary(read_log(log_path), unchanged, after), "summary still parses"); + check(after == 1, "typed completions off do not add a summary line"); + check(unchanged.packets == 2 && unchanged.completions == 2, "typed completions off do not move the counters"); + + FreeLibrary(module); + int at_exit_lines = 0; + check(parse_summary(read_log(log_path), counts, at_exit_lines), "summary parses after unload"); + check(at_exit_lines == 1, "process exit does not repeat an unchanged summary"); + + DeleteFileA(log_path); + SetEnvironmentVariableA("X2W_TRAP_LOG", nullptr); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", nullptr); + if (failures) return std::printf("%d failure(s)\n", failures), 1; + std::printf("PASS: startup_xapu_opus_count (%s)\n", opus_get_version_string()); + return 0; +} diff --git a/tests/startup_xcrdapi_lifetime.cpp b/tests/startup_xcrdapi_lifetime.cpp new file mode 100644 index 0000000000..8df0308cee --- /dev/null +++ b/tests/startup_xcrdapi_lifetime.cpp @@ -0,0 +1,281 @@ +// #2788: the DirectStorage stand-in frees its COM objects at final Release, the queue's worker leaves +// before the queue object is freed, and a pending entry keeps the status array and source file it uses +// alive after the guest releases them. +// +// Usage: startup_xcrdapi_lifetime XCRDAPI.dll [control] +// control runs the same scenario with X2W_TEST_XCRDAPI_LIFETIME_MUTANT=naive, which deletes at final +// Release without stopping the worker or retaining what an entry uses: the fixture must print FAIL. +// +// The live-object counters are the stand-in's fixture-only exports x2w_xcrdapi_live_objects(kind) and +// x2w_xcrdapi_live_workers(). No GPU or game data is used. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include <windows.h> + +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <vector> + +namespace { + +using u64 = std::uint64_t; +constexpr unsigned piece = 4096; +constexpr DWORD completion_timeout_ms = 15000; +constexpr unsigned factory_kind = 0x20, file_kind = 0x40, status_kind = 0x60, queue_kind = 0x80; + +struct Object { void** vtable; }; +using GetFactoryFn = long(__stdcall*)(const void*, void**); +using OpenFileFn = long(__stdcall*)(void*, const wchar_t*, const void*, void**); +using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const void*, void**); +using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); +using EnqueueRequestFn = void(__stdcall*)(void*, const void*); +using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using EnqueueSignalFn = void(__stdcall*)(void*, void*, u64); +using SubmitFn = void(__stdcall*)(void*); +using ReleaseFn = unsigned long(__stdcall*)(void*); +using IsCompleteFn = bool(__stdcall*)(void*, unsigned); +using GetHResultFn = long(__stdcall*)(void*, unsigned); +using LiveObjectsFn = unsigned long(__cdecl*)(unsigned); +using LiveWorkersFn = unsigned long(__cdecl*)(); + +bool expect(bool condition, const char* what) +{ + if (!condition) std::fprintf(stderr, "FAIL: %s\n", what); + return condition; +} + +unsigned long live(LiveObjectsFn fn, unsigned kind) { return fn(kind); } + +struct Fence { + void** vtable; + volatile LONG signaled; + u64 value; + static long __stdcall signal(void* self, u64 value) + { + auto* fence = static_cast<Fence*>(self); + fence->value = value; + InterlockedExchange(&fence->signaled, 1); + return 0; + } +}; + +// Releases the queue from inside the worker's signal callback. The queue's final Release then runs on +// the worker itself, which must free the object as it exits instead of trying to join itself. +struct ReleasingFence { + void** vtable; + Object* queue; + volatile LONG signaled; + static long __stdcall signal(void* self, u64) + { + auto* fence = static_cast<ReleasingFence*>(self); + reinterpret_cast<ReleaseFn>(fence->queue->vtable[2])(fence->queue); + InterlockedExchange(&fence->signaled, 1); + return 0; + } +}; + +bool wait_fence(Fence& fence, DWORD timeout_ms) +{ + const DWORD start = GetTickCount(); + while (!fence.signaled && GetTickCount() - start < timeout_ms) Sleep(2); + return fence.signaled != 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2 && argc != 3) { + std::fprintf(stderr, "usage: startup_xcrdapi_lifetime XCRDAPI.dll [control]\n"); + return 2; + } + const bool control = argc == 3 && std::strcmp(argv[2], "control") == 0; + if (control) { + SetEnvironmentVariableA("X2W_TEST_XCRDAPI_LIFETIME_MUTANT", "naive"); + } else { + SetEnvironmentVariableA("X2W_TEST_XCRDAPI_LIFETIME_MUTANT", nullptr); + } + + wchar_t temp_dir[MAX_PATH] = {}, log_path[MAX_PATH] = {}, data_path[MAX_PATH] = {}; + GetTempPathW(MAX_PATH, temp_dir); + std::swprintf(log_path, MAX_PATH, L"%lsx2w_lifetime_%lu.log", temp_dir, GetCurrentProcessId()); + std::swprintf(data_path, MAX_PATH, L"%lsx2w_lifetime_%lu.bin", temp_dir, GetCurrentProcessId()); + DeleteFileW(log_path); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path); + + std::vector<unsigned char> payload(piece); + for (unsigned i = 0; i < piece; ++i) payload[i] = static_cast<unsigned char>((i * 13 + (i >> 5)) ^ 0x5a); + { + HANDLE file = CreateFileW(data_path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + DWORD written = 0; + if (file == INVALID_HANDLE_VALUE || + !WriteFile(file, payload.data(), piece, &written, nullptr) || written != piece) { + std::fprintf(stderr, "cannot write the test file\n"); + return 2; + } + CloseHandle(file); + } + + HMODULE library = LoadLibraryA(argv[1]); + auto* get_factory = library ? reinterpret_cast<GetFactoryFn>(GetProcAddress(library, "DStorageGetFactory")) : nullptr; + auto* live_objects = library ? reinterpret_cast<LiveObjectsFn>(GetProcAddress(library, "x2w_xcrdapi_live_objects")) : nullptr; + auto* live_workers = library ? reinterpret_cast<LiveWorkersFn>(GetProcAddress(library, "x2w_xcrdapi_live_workers")) : nullptr; + void* factory_ptr = nullptr; + if (!get_factory || !live_objects || !live_workers || get_factory(nullptr, &factory_ptr) != 0 || !factory_ptr) { + std::fprintf(stderr, "cannot load the DirectStorage stand-in or its lifetime probes\n"); + return 2; + } + auto* factory = static_cast<Object*>(factory_ptr); + unsigned char description[0x28] = {}; + *reinterpret_cast<std::uint16_t*>(description + 8) = 16; + bool ok = true; + + ok = expect(live(live_objects, factory_kind) == 1, "the factory singleton is not reported alive") && ok; + ok = expect(live(live_objects, 0) == 1, "objects are alive before any creation") && ok; + + // A. A file and a status array released by their only owner are freed. + void* file0 = nullptr; + if (reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, data_path, nullptr, &file0) != 0 || !file0) { + std::fprintf(stderr, "cannot open the test file\n"); + return 2; + } + void* status0 = nullptr; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 4, "Lifetime", nullptr, &status0) != 0 || !status0) + return 2; + ok = expect(live(live_objects, file_kind) == 1, "the open file is not counted") && ok; + ok = expect(live(live_objects, status_kind) == 1, "the status array is not counted") && ok; + reinterpret_cast<ReleaseFn>(static_cast<Object*>(file0)->vtable[2])(file0); + ok = expect(live(live_objects, file_kind) == 0, "a file released by its only owner was not freed") && ok; + reinterpret_cast<ReleaseFn>(static_cast<Object*>(status0)->vtable[2])(status0); + ok = expect(live(live_objects, status_kind) == 0, "a status array released by its only owner was not freed") && ok; + if (!ok) return 1; + + // B. A submitted entry keeps its source file alive after the guest releases it, the status entry + // completes, and the queue's worker has left by the time the queue's final Release returns. The + // status array keeps the guest's own reference for the checks below, so it can be read after + // completion; section C proves the entry retains it when the guest has released it. + void* file1 = nullptr; + void* status1 = nullptr; + void* queue1 = nullptr; + if (reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, data_path, nullptr, &file1) != 0 || !file1) return 2; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 4, "Pending", nullptr, &status1) != 0 || !status1) return 2; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, description, nullptr, &queue1) != 0 || !queue1) return 2; + auto* queue = static_cast<Object*>(queue1); + auto* status = static_cast<Object*>(status1); + void* fence_vtable[11] = {}; + fence_vtable[10] = reinterpret_cast<void*>(&Fence::signal); + Fence first{}, barrier{}; + first.vtable = fence_vtable; + barrier.vtable = fence_vtable; + + std::vector<unsigned char> destination(piece, 0xA5); + alignas(8) unsigned char request[0x48] = {}; + *reinterpret_cast<unsigned char**>(request + 0x08) = destination.data(); + *reinterpret_cast<unsigned*>(request + 0x18) = piece; + *reinterpret_cast<void**>(request + 0x20) = file1; + *reinterpret_cast<u64*>(request + 0x30) = piece; + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, request); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 0); + reinterpret_cast<EnqueueSignalFn>(queue->vtable[5])(queue, &first, 0x100); + // A barrier behind the request: when it runs, the request's entry has released its references. + reinterpret_cast<EnqueueSignalFn>(queue->vtable[5])(queue, &barrier, 0x101); + + // The guest drops the file while the request is pending. + reinterpret_cast<ReleaseFn>(static_cast<Object*>(file1)->vtable[2])(file1); + ok = expect(live(live_objects, file_kind) == 1, + "a file referenced by a pending entry was freed by the guest's Release") && ok; + if (!ok) return 1; + + reinterpret_cast<SubmitFn>(queue->vtable[6])(queue); + ok = expect(wait_fence(first, completion_timeout_ms), "the request's fence was never signaled") && ok; + ok = expect(wait_fence(barrier, completion_timeout_ms), "the barrier fence was never signaled") && ok; + if (!ok) return 1; + ok = expect(reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 0), "the status entry did not complete") && ok; + ok = expect(reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 0) == S_OK, "the request status is not S_OK") && ok; + ok = expect(destination == payload, "the request did not write the file bytes") && ok; + ok = expect(live(live_objects, file_kind) == 0, "the entry did not drop its file reference") && ok; + ok = expect(live(live_objects, status_kind) == 1, "the status array lost the guest's reference before the checks") && ok; + reinterpret_cast<ReleaseFn>(status->vtable[2])(status); + ok = expect(live(live_objects, status_kind) == 0, "the status array was not freed at its last reference") && ok; + ok = expect(live_workers() == 1, "the queue's worker is not reported running before the queue is released") && ok; + if (!ok) return 1; + + reinterpret_cast<ReleaseFn>(queue->vtable[2])(queue); + ok = expect(live(live_objects, queue_kind) == 0, "the queue was not freed at final Release") && ok; + ok = expect(live_workers() == 0, "the queue's worker was still running after the queue was freed") && ok; + if (!ok) return 1; + + // C. A queue released with entries that were never submitted drops their references too. + void* file2 = nullptr; + void* status2 = nullptr; + void* queue2 = nullptr; + if (reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, data_path, nullptr, &file2) != 0 || !file2) return 2; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 4, "Unsubmitted", nullptr, &status2) != 0 || !status2) return 2; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, description, nullptr, &queue2) != 0 || !queue2) return 2; + auto* queue_2 = static_cast<Object*>(queue2); + alignas(8) unsigned char request2[0x48] = {}; + *reinterpret_cast<unsigned char**>(request2 + 0x08) = destination.data(); + *reinterpret_cast<unsigned*>(request2 + 0x18) = piece; + *reinterpret_cast<void**>(request2 + 0x20) = file2; + *reinterpret_cast<u64*>(request2 + 0x30) = piece; + reinterpret_cast<EnqueueRequestFn>(queue_2->vtable[3])(queue_2, request2); + reinterpret_cast<EnqueueStatusFn>(queue_2->vtable[4])(queue_2, static_cast<Object*>(status2), 1); + reinterpret_cast<ReleaseFn>(static_cast<Object*>(file2)->vtable[2])(file2); + reinterpret_cast<ReleaseFn>(static_cast<Object*>(status2)->vtable[2])(status2); + ok = expect(live(live_objects, file_kind) == 1, "an unsubmitted entry did not retain its file") && ok; + ok = expect(live(live_objects, status_kind) == 1, "an unsubmitted entry did not retain its status array") && ok; + reinterpret_cast<ReleaseFn>(queue_2->vtable[2])(queue_2); + ok = expect(live(live_objects, file_kind) == 0, "releasing the queue left its file alive") && ok; + ok = expect(live(live_objects, status_kind) == 0, "releasing the queue left its status array alive") && ok; + ok = expect(live_workers() == 0, "an unused queue's worker outlived the queue") && ok; + ok = expect(live(live_objects, 0) == 1, "objects other than the factory singleton outlived every release") && ok; + + // D. The last external reference can be released from the queue's own worker (a fence callback). + // The worker cannot join itself: it must stop, drop the entries that never ran, and free the queue. + void* file3 = nullptr; + void* status3 = nullptr; + void* queue3 = nullptr; + if (reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, data_path, nullptr, &file3) != 0 || !file3) return 2; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 4, "WorkerRelease", nullptr, &status3) != 0 || !status3) return 2; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, description, nullptr, &queue3) != 0 || !queue3) return 2; + auto* queue_3 = static_cast<Object*>(queue3); + auto* status_3 = static_cast<Object*>(status3); + void* release_vtable[11] = {}; + release_vtable[10] = reinterpret_cast<void*>(&ReleasingFence::signal); + ReleasingFence releasing{}; + releasing.vtable = release_vtable; + releasing.queue = queue_3; + alignas(8) unsigned char request3[0x48] = {}; + *reinterpret_cast<unsigned char**>(request3 + 0x08) = destination.data(); + *reinterpret_cast<unsigned*>(request3 + 0x18) = piece; + *reinterpret_cast<void**>(request3 + 0x20) = file3; + *reinterpret_cast<u64*>(request3 + 0x30) = piece; + reinterpret_cast<EnqueueRequestFn>(queue_3->vtable[3])(queue_3, request3); + reinterpret_cast<EnqueueStatusFn>(queue_3->vtable[4])(queue_3, status_3, 0); + reinterpret_cast<EnqueueSignalFn>(queue_3->vtable[5])(queue_3, &releasing, 0x200); + reinterpret_cast<ReleaseFn>(static_cast<Object*>(file3)->vtable[2])(file3); + reinterpret_cast<ReleaseFn>(status_3->vtable[2])(status3); + reinterpret_cast<SubmitFn>(queue_3->vtable[6])(queue_3); + const DWORD release_start = GetTickCount(); + while ((!releasing.signaled || live(live_objects, queue_kind) || live_workers()) && + GetTickCount() - release_start < completion_timeout_ms) + Sleep(2); + ok = expect(releasing.signaled != 0, "the releasing fence never ran") && ok; + ok = expect(live(live_objects, queue_kind) == 0, "a queue released from its own worker was not freed") && ok; + ok = expect(live_workers() == 0, "a queue's worker outlived a release from that worker") && ok; + ok = expect(live(live_objects, file_kind) == 0, "the worker-release queue left its file alive") && ok; + ok = expect(live(live_objects, status_kind) == 0, "the worker-release queue left its status array alive") && ok; + + reinterpret_cast<ReleaseFn>(factory->vtable[2])(factory); + DeleteFileW(data_path); + DeleteFileW(log_path); + if (!ok) return 1; + std::puts("xcrdapi objects are freed at final Release; pending entries kept their status array and file alive; " + "the queue worker left before the queue was freed"); + return 0; +} diff --git a/tests/startup_xg_bc7_draw_check.py b/tests/startup_xg_bc7_draw_check.py index 5c92926a01..5b4f3929a1 100644 --- a/tests/startup_xg_bc7_draw_check.py +++ b/tests/startup_xg_bc7_draw_check.py @@ -14,7 +14,7 @@ def write_fixture(upload, width, height): pixels = bytearray(width * height * 4) for y in range((height + 3) // 4): for x in range((width + 3) // 4): - block, colors = make_block(x, y) + block, colors = make_block(x % 21, y % 19) blocks.extend(block) for row in range(min(4, height - y * 4)): destination = ((y * 4 + row) * width + x * 4) * 4 @@ -24,6 +24,19 @@ def write_fixture(upload, width, height): return pixels +def display64k_blocks(linear, width, height): + """BC7 block order within one display tile is x0 y0 x1 y1 y2 x2 y3 x3 y4 x4 y5 x5.""" + tiled = bytearray(len(linear)) + for y in range(height // 4): + for x in range(width // 4): + tile = (y // 64) * (width // 256) + x // 64 + block = sum(((x >> bit) & 1) << shift for bit, shift in enumerate((0, 2, 5, 7, 9, 11))) + block |= sum(((y >> bit) & 1) << shift for bit, shift in enumerate((1, 3, 4, 6, 8, 10))) + dest = (tile * 4096 + block) * 16 + src = (y * (width // 4) + x) * 16 + tiled[dest:dest + 16] = linear[src:src + 16] + return tiled + def check(work, consumer, dxc, backend): cache = work / "cache" cache.mkdir() @@ -57,9 +70,15 @@ def check(work, consumer, dxc, backend): cache / f"{key}.{stage}.cso", shader], check=True) mismatches = [] - for width, height in ((64, 64), (81, 69)): + for width, height in ((64, 64), (81, 69), (512, 256)): reference = write_fixture(upload, width, height) - for layout in ("linear", "tiled"): + layouts = ("linear", "display64k") if width == 512 else ("linear", "tiled") + for layout in layouts: + if layout == "display64k": + linear = upload.read_bytes() + tiled = display64k_blocks(linear, width, height) + assert tiled != linear + upload.write_bytes(tiled) if image.exists(): image.unlink() result = subprocess.run(base + [str(width), str(height), layout], env=env, capture_output=True, text=True) diff --git a/tests/texture_bc_volume_check.py b/tests/texture_bc_volume_check.py index d15e58f91c..cc9f361f10 100644 --- a/tests/texture_bc_volume_check.py +++ b/tests/texture_bc_volume_check.py @@ -90,7 +90,7 @@ def test_table(self) -> None: "BC1_UNORM": (71, (4, 4, 1), 8, 2), "BC2_UNORM": (74, (4, 4, 1), 16, 2), "BC3_UNORM": (77, (4, 4, 1), 16, 2), - "BC4_UNORM": (79, (4, 4, 1), 8, 2), + "BC4_UNORM": (80, (4, 4, 1), 8, 2), "BC5_UNORM": (83, (4, 4, 1), 16, 2), "BC6H_UF16": (95, (4, 4, 1), 16, 2), "BC7_UNORM": (98, (4, 4, 1), 16, 2), diff --git a/tests/texture_blocks_check.py b/tests/texture_blocks_check.py new file mode 100644 index 0000000000..24ead3e516 --- /dev/null +++ b/tests/texture_blocks_check.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +"""Standalone unit, bounds-guard, and mutation suite for tools/texture_blocks.py.""" + +from __future__ import annotations + +import array +from pathlib import Path +import struct +import sys +import types +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "texture_blocks.py" +sys.path.insert(0, str(ROOT / "tools")) + +import texture_blocks # noqa: E402 + + +BC_2D_FORMATS = ( + ("BC1_UNORM", 71, 8), + ("BC2_UNORM", 74, 16), + ("BC3_UNORM", 77, 16), + ("BC4_UNORM", 80, 8), + ("BC5_UNORM", 83, 16), + ("BC6H_UF16", 95, 16), + ("BC7_UNORM", 98, 16), +) + + +def _block_bytes_tag(fam: int, x: int, y: int, block_bytes: int, z: int = 0) -> bytes: + head = struct.pack("<BBHI", fam, x & 0xFF, y & 0xFFFF, z) + return head[:block_bytes] + bytes(((fam * 17 + x * 3 + y * 5 + z + i) & 0xFF) for i in range(block_bytes - len(head))) + + +def _columns_rows(width: int, height: int) -> tuple[int, int]: + return (width + 3) // 4, (height + 3) // 4 + + +class TextureBlocksPositiveTests(unittest.TestCase): + def test_formats_table_preserved(self) -> None: + for name, dxgi, bpb in BC_2D_FORMATS: + with self.subTest(format=name): + info = texture_blocks.format_info(name) + self.assertEqual(info.dxgi_format, dxgi) + self.assertEqual(info.block_extent, (4, 4, 1)) + self.assertEqual(info.bytes_per_block, bpb) + self.assertEqual(info.dimension, 2) + vol = texture_blocks.format_info("BC7_UNORM_VOLUME") + self.assertEqual((vol.dxgi_format, vol.block_extent, vol.bytes_per_block, vol.dimension), + (98, (4, 4, 1), 16, 3)) + + def test_2d_bc1_to_bc7_round_trips_non_mult4_and_pitched(self) -> None: + dims = ((1, 1, 0), (3, 5, 1), (5, 3, 2), (17, 9, 3), (65, 19, 4)) + for fam, (name, _, bpb) in enumerate(BC_2D_FORMATS, start=1): + custom_pad = bytes([(0xA0 + fam) & 0xFF]) * bpb + for width, height, extra in dims: + cols, rows = _columns_rows(width, height) + pitch = cols + extra + tight = b"".join(_block_bytes_tag(fam, x, y, bpb) for y in range(rows) for x in range(cols)) + with self.subTest(format=name, width=width, height=height, pitch=pitch): + self.assertEqual(texture_blocks.surface_bytes(width, height, name), cols * rows * bpb) + self.assertEqual( + texture_blocks.surface_bytes(width, height, name, pitch_blocks=pitch), + pitch * rows * bpb, + ) + + tiled_tight = texture_blocks.tile_blocks(tight, width, height, name) + self.assertEqual(tiled_tight, tight) + self.assertEqual(texture_blocks.linearize_blocks(tiled_tight, width, height, name), tight) + + for pad in (custom_pad, bytearray(custom_pad), memoryview(custom_pad)): + tiled = texture_blocks.tile_blocks( + tight, + width, + height, + name, + pitch_blocks=pitch, + padding=pad, + ) + self.assertEqual(len(tiled), pitch * rows * bpb) + if extra > 0: + for y in range(rows): + row_tail_start = (y * pitch + cols) * bpb + row_tail_end = ((y + 1) * pitch) * bpb + self.assertEqual(tiled[row_tail_start:row_tail_end], custom_pad * extra) + self.assertEqual( + texture_blocks.linearize_blocks(memoryview(tiled), width, height, name, pitch_blocks=pitch), + tight, + ) + + def test_3d_volume_round_trip_with_non_mult4_dims(self) -> None: + for width, height, depth in ((1, 1, 1), (3, 5, 3), (65, 19, 2)): + cols, rows = _columns_rows(width, height) + slices = [ + b"".join(_block_bytes_tag(7, x, y, 16, z) for y in range(rows) for x in range(cols)) + for z in range(depth) + ] + expected_tight = b"".join(slices) + with self.subTest(width=width, height=height, depth=depth): + payload = texture_blocks.tile_volume_4k_s( + (s for s in slices), + width, + height, + depth, + "BC7_UNORM_VOLUME", + ) + tile_pitch = (cols + 15) // 16 + slice_stride = tile_pitch * ((rows + 15) // 16) * 4096 + self.assertEqual(len(payload), depth * slice_stride) + self.assertEqual( + texture_blocks.linearize_volume_4k_s(payload, width, height, depth, "BC7_UNORM_VOLUME"), + expected_tight, + ) + self.assertEqual( + texture_blocks.linearize_volume_4k_s(memoryview(payload), width, height, depth, "BC7_UNORM_VOLUME"), + expected_tight, + ) + + +class TextureBlocksNegativeAndMutationTests(unittest.TestCase): + def test_bool_non_int_and_non_positive_dims_and_pitch_rejected(self) -> None: + fmt = texture_blocks.format_info("BC7_UNORM") + tight_4x4 = bytes(16) + padded_4x4 = bytes(32) + vol_slice = bytes(16) + vol_payload = bytes(4096) + + for bad_dim in (True, False, 0, -1, -8, 1.5, "4", None): + with self.subTest(bad_dim=bad_dim): + with self.assertRaises(ValueError): + texture_blocks._grid(bad_dim, 4, fmt) + with self.assertRaises(ValueError): + texture_blocks._grid(4, bad_dim, fmt) + with self.assertRaises(ValueError): + texture_blocks.surface_bytes(bad_dim, 4, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.surface_bytes(4, bad_dim, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(tight_4x4, bad_dim, 4, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(tight_4x4, 4, bad_dim, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(tight_4x4, bad_dim, 4, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(tight_4x4, 4, bad_dim, "BC7_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([vol_slice], bad_dim, 4, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([vol_slice], 4, bad_dim, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([vol_slice], 4, 4, bad_dim, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(vol_payload, bad_dim, 4, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(vol_payload, 4, bad_dim, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(vol_payload, 4, 4, bad_dim, "BC7_UNORM_VOLUME") + + for bad_pitch in (True, False, 0, 1, -1, 2.0, "2"): + with self.subTest(bad_pitch=bad_pitch): + with self.assertRaises(ValueError): + texture_blocks.surface_bytes(8, 4, "BC7_UNORM", pitch_blocks=bad_pitch) + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(padded_4x4, 8, 4, "BC7_UNORM", pitch_blocks=bad_pitch) + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(padded_4x4, 8, 4, "BC7_UNORM", pitch_blocks=bad_pitch) + + def test_wrong_payload_padding_and_format_mismatches_rejected(self) -> None: + tight_bc1 = bytes(16) # 8x4 BC1_UNORM = 2 blocks * 8 bytes + for bad_len_payload in (b"", bytes(15), bytes(17), bytes(24)): + with self.subTest(bad_len=len(bad_len_payload)): + with self.assertRaises(ValueError): + texture_blocks.linearize_blocks(bad_len_payload, 8, 4, "BC1_UNORM") + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(bad_len_payload, 8, 4, "BC1_UNORM") + + int_view = memoryview(array.array("I", [1, 2])) # nbytes=8 but format != 'B' + for bad_pad in (b"", b"x" * 7, b"x" * 9, "x" * 8, [0] * 8, (0,) * 8, 123, int_view): + with self.subTest(bad_pad=repr(bad_pad)): + with self.assertRaises(ValueError): + texture_blocks.tile_blocks(tight_bc1, 8, 4, "BC1_UNORM", pitch_blocks=3, padding=bad_pad) + with self.assertRaisesRegex(ValueError, "Expected one 8-byte padding block"): + texture_blocks.tile_blocks(bytes(8), 4, 4, "BC1_UNORM", pitch_blocks=1, padding=b"") + + # Volume slice count and payload length mismatches. + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([bytes(16)], 4, 4, 2, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.tile_volume_4k_s([bytes(15)], 4, 4, 1, "BC7_UNORM_VOLUME") + with self.assertRaises(ValueError): + texture_blocks.linearize_volume_4k_s(bytes(4095), 4, 4, 1, "BC7_UNORM_VOLUME") + + # 2D vs 3D and unknown format mismatches. + with self.assertRaisesRegex(ValueError, "volume format"): + texture_blocks.surface_bytes(4, 4, "BC7_UNORM_VOLUME") + with self.assertRaisesRegex(ValueError, "volume format"): + texture_blocks.tile_blocks(bytes(16), 4, 4, "BC7_UNORM_VOLUME") + with self.assertRaisesRegex(ValueError, "2-D format"): + texture_blocks.tile_volume_4k_s([bytes(16)], 4, 4, 1, "BC7_UNORM") + with self.assertRaisesRegex(ValueError, "2-D format"): + texture_blocks.linearize_volume_4k_s(bytes(4096), 4, 4, 1, "BC1_UNORM") + for unknown in ("UNKNOWN_BC", 123, None, ["BC7_UNORM"]): + with self.subTest(unknown=unknown): + with self.assertRaises(ValueError): + texture_blocks.format_info(unknown) + + def test_fast_temp_mutations(self) -> None: + source = TOOL.read_text(encoding="utf-8") + + def _check_bool_mutation(mod) -> None: + self.assertEqual(mod.surface_bytes(True, 4, "BC7_UNORM"), 16) + + def _check_narrow_pitch_mutation(mod) -> None: + self.assertEqual(mod.surface_bytes(8, 4, "BC7_UNORM", pitch_blocks=1), 16) + + def _check_padding_type_mutation(mod) -> None: + out = mod.tile_blocks(bytes(8), 4, 4, "BC1_UNORM", pitch_blocks=2, padding=[0x5A] * 8) + self.assertEqual(len(out), 16) + + def _check_padding_len_mutation(mod) -> None: + out = mod.tile_blocks(bytes(8), 4, 4, "BC1_UNORM", pitch_blocks=1, padding=b"") + self.assertEqual(out, bytes(8)) + + def _check_depth_positive_mutation(mod) -> None: + self.assertEqual(mod.linearize_volume_4k_s(b"", 4, 4, 0, "BC7_UNORM_VOLUME"), b"") + + mutations = ( + ( + "drop_bool_guard", + " if isinstance(value, bool) or not isinstance(value, int):\n", + " if not isinstance(value, int):\n", + _check_bool_mutation, + ), + ( + "drop_narrow_pitch_guard", + ' if pitch < columns:\n raise ValueError(f"Block pitch {pitch} is narrower than the {columns}-block surface")\n', + " pass\n", + _check_narrow_pitch_mutation, + ), + ( + "drop_padding_type_guard", + ' elif isinstance(padding, (bytes, bytearray)):\n' + ' padding_bytes = bytes(padding)\n' + ' elif isinstance(padding, memoryview) and padding.ndim == 1 and padding.format == "B":\n' + ' padding_bytes = bytes(padding)\n' + ' else:\n' + ' raise ValueError(f"Expected bytes-like padding of {block_bytes} bytes, got {type(padding).__name__}")\n', + " else:\n padding_bytes = padding\n", + _check_padding_type_mutation, + ), + ( + "drop_padding_len_guard", + ' if len(padding_bytes) != block_bytes:\n raise ValueError(f"Expected one {block_bytes}-byte padding block")\n', + " pass\n", + _check_padding_len_mutation, + ), + ( + "drop_depth_positive_guard", + ' if depth <= 0:\n raise ValueError("Expected a positive volume depth")\n', + " pass\n", + _check_depth_positive_mutation, + ), + ) + + for label, target, replacement, check_fn in mutations: + with self.subTest(mutation=label): + count = source.count(target) + self.assertGreaterEqual(count, 1, target) + # For depth guard, target appears twice (tile_volume_4k_s and linearize_volume_4k_s); + # mutate the linearize_volume_4k_s guard or replace all for clean mutant check. + mutated_src = source.replace(target, replacement) + mod = types.ModuleType(f"texture_blocks_mut_{label}") + mod.__file__ = str(TOOL) + sys.modules[mod.__name__] = mod + try: + exec(compile(mutated_src, str(TOOL), "exec"), mod.__dict__) + check_fn(mod) + finally: + sys.modules.pop(mod.__name__, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/texture_descriptors_cli_check.py b/tests/texture_descriptors_cli_check.py new file mode 100644 index 0000000000..daac72a8b2 --- /dev/null +++ b/tests/texture_descriptors_cli_check.py @@ -0,0 +1,417 @@ +#!/usr/bin/env python3 +"""CLI validation, multi-archive lookup, and error-exit suite for tools/texture_descriptors.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "texture_descriptors.py" +sys.path.insert(0, str(ROOT / "tools")) + +from paged_resource import PagedResource # noqa: E402 +import texture_descriptors as td # noqa: E402 + + +def _pack_boundary(stored: int, logical: int, codec: int = 0, trailing_bytes: int = 0) -> bytes: + assert stored % 256 == 0 and logical % 4096 == 0 + stored_units = stored // 256 + logical_pages = logical // 4096 + low = (stored_units & 0x03ffffff) | ((codec & 15) << 26) | ((logical_pages & 3) << 30) + high = ((logical_pages >> 2) & 0xfffff) | ((trailing_bytes & 0xfff) << 20) + return struct.pack("<II", low, high) + + +def _shape(width: int, height: int) -> int: + return ((height - 1) << 14) | (width - 1) + + +def _flags(dxgi_format: int, mip_marker: int) -> int: + return (mip_marker << 24) | (dxgi_format << 3) + + +def _build_synthetic_archive( + *, + keys: tuple[int, ...] = (0x0123456789abcdef, (1 << 64) - 1), + raw_padding: int = 512, +) -> tuple[bytearray, bytes, bytes]: + """Build a synthetic RDS5/ETPF archive with one padded raw range and one zlib range.""" + raw_payload = bytes((i * 17 + 5) % 256 for i in range(4096)) + zlib_plain = b"ZPAGE0_" + b"X" * 4089 + b"ZPAGE1_" + b"Y" * 4089 + zlib_packed = zlib.compress(zlib_plain) + + raw_start = 4352 + raw_end = raw_start + 4096 + raw_padding + zlib_slot = ((len(zlib_packed) + 255) // 256) * 256 + total_size = raw_end + zlib_slot + + archive = bytearray(total_size) + struct.pack_into("<4sIQ", archive, 0, b"RDS5", 4, 16384) + archive[16:24] = _pack_boundary(256, 0, codec=0, trailing_bytes=0) + archive[24:32] = _pack_boundary(raw_start, 4096, codec=0, trailing_bytes=raw_padding) + archive[32:40] = _pack_boundary(raw_end, 8192, codec=8, trailing_bytes=0) + archive[40:48] = _pack_boundary(total_size, 16384, codec=0, trailing_bytes=0) + + records = len(keys) + struct.pack_into("<4sIII", archive, 256, b"ETPF", 0x27a, records, 0) + struct.pack_into("<4I", archive, 272, _shape(64, 32), _flags(71, 3), 1, 0) + if records > 1: + struct.pack_into("<4I", archive, 288, _shape(128, 16), _flags(98, 1), 3, 0) + struct.pack_into(f"<{records}Q", archive, 272 + records * 16, *keys) + + archive[raw_start:raw_start + 4096] = raw_payload + archive[raw_end:raw_end + len(zlib_packed)] = zlib_packed + return archive, raw_payload, zlib_plain + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = td.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class TextureDescriptorsCliPositiveTests(unittest.TestCase): + def test_direct_main_all_modes_and_boundary_keys(self) -> None: + max_u64 = (1 << 64) - 1 + key_a = 0x0123456789ABCDEF + arch_bytes_1, raw_payload, zlib_plain = _build_synthetic_archive(keys=(0, key_a)) + arch_bytes_2, _, _ = _build_synthetic_archive(keys=(key_a, max_u64)) + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + arch1 = root / "first.ttpf" + arch2 = root / "nested" / "second.ttpf" + arch2.parent.mkdir() + arch1.write_bytes(arch_bytes_1) + arch2.write_bytes(arch_bytes_2) + + # 1) Inventory mode. + code, out, err = _run_main([str(arch1)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + json.loads(out), + { + "descriptor_count": 2, + "groups": [ + {"width": 64, "height": 32, "dxgi_format": 71, "mip_marker": 3, "count": 1}, + {"width": 128, "height": 16, "dxgi_format": 98, "mip_marker": 1, "count": 1}, + ], + }, + ) + + # 2) --descriptor mode (0 and 1). + code, out, err = _run_main([str(arch1), "--descriptor", "0"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + json.loads(out), + { + "descriptor_index": 0, + "width": 64, + "height": 32, + "dxgi_format": 71, + "mip_marker": 3, + "logical_offset": 4096, + }, + ) + code, out, err = _run_main([str(arch1), "--descriptor", "1"]) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(out)["logical_offset"], 12288) + + # 3) --raw-page-map mode. + code, out, err = _run_main([str(arch1), "--raw-page-map", "0"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + rpm = json.loads(out) + self.assertEqual(rpm, {"logical_offset": 4096, "file_offset": 4352}) + self.assertEqual(arch_bytes_1[rpm["file_offset"]:rpm["file_offset"] + 4096], raw_payload) + + # 4) --zlib-segment mode. + code, out, err = _run_main([str(arch1), "--zlib-segment", "1"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + zseg = json.loads(out) + self.assertEqual(zseg["segment_logical_offset"], 8192) + self.assertEqual(zseg["page_offset_in_segment"], 4096) + self.assertEqual(zseg["segment"]["codec"], "zlib") + self.assertEqual(zseg["segment"]["size"], 8192) + with arch1.open("rb") as stream: + seg_obj = td.zlib_segment(stream, 1) + decoded = PagedResource(stream, [seg_obj.segment]).read(seg_obj.page_offset_in_segment, 4096) + self.assertEqual(decoded, zlib_plain[4096:]) + + # 5) --lookup-key decimal, 0x/0X hex, boundary 0 and 2^64-1, and absent key. + for raw_key, expected in ( + (str(key_a), [(arch1, 1), (arch2, 0)]), + (f"0x{key_a:x}", [(arch1, 1), (arch2, 0)]), + (f"0X{key_a:X}", [(arch1, 1), (arch2, 0)]), + ("0", [(arch1, 0)]), + ("0x0", [(arch1, 0)]), + (str(max_u64), [(arch2, 1)]), + (hex(max_u64), [(arch2, 1)]), + ("0xdeadbeefcafebabe", []), + ): + with self.subTest(raw_key=raw_key): + code, out, err = _run_main([str(arch1), str(arch2), "--lookup-key", raw_key]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + json.loads(out), + { + "matches": [ + {"archive": str(path), "descriptor_index": index} + for path, index in expected + ] + }, + ) + + def test_sys_argv_and_script_entrypoint_and_subprocess(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + arch = Path(tmp) / "entry.ttpf" + arch.write_bytes(arch_bytes) + cli_argv = [str(TOOL), str(arch), "--descriptor", "0"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(json.loads(out)["descriptor_index"], 0) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue())["width"], 64) + + proc = _run_subprocess(str(arch), "--lookup-key", "0x0123456789abcdef") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual( + json.loads(proc.stdout), + {"matches": [{"archive": str(arch), "descriptor_index": 0}]}, + ) + + +class TextureDescriptorsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> str: + code, out, err = _run_main(argv) + if expected_code is None: + self.assertNotEqual(code, 0, (code, err)) + else: + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertTrue(err.strip(), f"expected stderr for {argv!r}") + self.assertNotIn("Traceback", err) + err_lower = err.lower() + for fragment in fragments: + self.assertIn(fragment.lower(), err_lower) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0, proc.stderr) + else: + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr for {argv!r}") + self.assertNotIn("Traceback", proc.stderr) + sub_lower = proc.stderr.lower() + for fragment in fragments: + self.assertIn(fragment.lower(), sub_lower) + return err + + def test_upfront_archive_existence_and_is_file_before_opening(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + missing = root / "missing.ttpf" + dir_arch = root / "dir_arch" + dir_arch.mkdir() + + # Single-archive missing & directory checks never open files. + for bad_path, frag in ( + (missing, f"{missing}: archive file not found"), + (dir_arch, f"{dir_arch}: archive path is not a regular file"), + ): + with self.subTest(bad_path=bad_path): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + [str(bad_path)], + expected_code=1, + fragments=(frag,), + check_subprocess=False, + ) + open_mock.assert_not_called() + self._assert_clean_failure([str(bad_path)], expected_code=1, fragments=(frag,)) + + # Multi-archive --lookup-key validates ALL archives before opening the first! + for argv, frag in ( + ([str(valid), str(missing), "--lookup-key", "0"], f"{missing}: archive file not found"), + ([str(valid), str(dir_arch), "--lookup-key", "0"], f"{dir_arch}: archive path is not a regular file"), + ): + with self.subTest(argv=argv): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + argv, + expected_code=1, + fragments=(frag,), + check_subprocess=False, + ) + open_mock.assert_not_called() + self._assert_clean_failure(argv, expected_code=1, fragments=(frag,)) + + def test_lookup_key_range_validated_upfront_before_opening(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + + for argv_tail, frag in ( + (["--lookup-key", "-1"], "unsigned 64-bit integer"), + (["--lookup-key=-0x1"], "invalid literal"), + (["--lookup-key", str(1 << 64)], "unsigned 64-bit integer"), + (["--lookup-key", hex(1 << 64)], "unsigned 64-bit integer"), + (["--lookup-key", "not_a_key"], "invalid literal"), + (["--lookup-key", ""], "invalid literal"), + ): + with self.subTest(argv_tail=argv_tail): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + [str(valid), *argv_tail], + expected_code=1, + fragments=(f"{valid}:", frag), + check_subprocess=False, + ) + open_mock.assert_not_called() + self._assert_clean_failure( + [str(valid), *argv_tail], + expected_code=1, + fragments=(f"{valid}:", frag), + ) + + def test_negative_descriptor_index_validated_before_file_checks(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + missing = root / "missing.ttpf" + + for target in (valid, missing): + for flag in ("--descriptor", "--raw-page-map", "--zlib-segment"): + with self.subTest(target=target.name, flag=flag): + with mock.patch.object(Path, "open") as open_mock: + self._assert_clean_failure( + [str(target), flag, "-1"], + expected_code=1, + fragments=(f"{target}:", "nonnegative"), + check_subprocess=False, + ) + open_mock.assert_not_called() + + def test_truncated_corrupt_zlib_and_duplicate_archive_failures(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.ttpf" + valid.write_bytes(arch_bytes) + + empty = root / "empty.ttpf" + empty.write_bytes(b"") + self._assert_clean_failure([str(empty)], expected_code=1, fragments=(f"{empty}:", "Truncated RDS5 header")) + + short = root / "short.ttpf" + short.write_bytes(b"RDS5" + bytes(12)) + self._assert_clean_failure([str(short)], expected_code=1, fragments=(f"{short}:", "Truncated RDS5 header")) + + corrupt_zlib = root / "corrupt_zlib.ttpf" + corrupt = bytearray(arch_bytes) + corrupt[4352 + 4096 + 512] ^= 0xFF + corrupt_zlib.write_bytes(corrupt) + self._assert_clean_failure( + [str(corrupt_zlib), "--zlib-segment", "1"], + expected_code=1, + fragments=(f"{corrupt_zlib}:", "Invalid zlib stream"), + ) + + # Duplicate archive input: identical path and hardlink alias. + alias = root / "alias.ttpf" + os.link(valid, alias) + for dup_pair in ([str(valid), str(valid)], [str(valid), str(alias)]): + with self.subTest(dup_pair=dup_pair): + self._assert_clean_failure( + [*dup_pair, "--lookup-key", "0x0123456789abcdef"], + expected_code=1, + fragments=(f"{dup_pair[1]}:", "Duplicate archive input"), + ) + + def test_argparse_errors_py314_safe(self) -> None: + arch_bytes, _, _ = _build_synthetic_archive() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + arch1 = root / "one.ttpf" + arch2 = root / "two.ttpf" + arch1.write_bytes(arch_bytes) + arch2.write_bytes(arch_bytes) + + for argv, frags in ( + ([], ("required",)), + ([str(arch1), "--bogus-flag"], ("unrecognized",)), + ([str(arch1), "--descriptor", "bad"], ("invalid",)), + ([str(arch1), "--descriptor"], ("expected one argument",)), + ([str(arch1), "--descriptor", "0", "--lookup-key", "0"], ("not allowed with argument",)), + ([str(arch1), str(arch2)], ("--lookup-key",)), + ): + with self.subTest(argv=argv): + self._assert_clean_failure( + argv, + expected_code=None, + fragments=frags, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/tracy_new_check.cpp b/tests/tracy_new_check.cpp new file mode 100644 index 0000000000..83cad82e13 --- /dev/null +++ b/tests/tracy_new_check.cpp @@ -0,0 +1,62 @@ +// src/startup_stubs/tracy_new.cpp replaces the DLL's operator new/delete in X2W_TRACY builds. This fixture compiles it +// against a recording stand-in for Tracy's memory macros and checks what a caller of the C++ heap relies on. +#include "../src/startup_stubs/tracy_new.cpp" + +#include <cstdint> +#include <cstdio> +#include <cstring> + +namespace { +int failures = 0; + +void expect(bool condition, const char* what) +{ + if (condition) return; + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; +} + +bool pool_is_heap(const char* pool) { return pool && std::strcmp(pool, X2W_TRACY_HEAP) == 0; } +} + +int main() +{ + // An empty allocation is legal C++: it must return a usable pointer, and be reported with the requested size. + void* empty = operator new(0); + expect(empty != nullptr, "operator new(0) returns a block"); + expect(g_tracy_event_count == 1 && g_tracy_events[0].alloc && g_tracy_events[0].pointer == empty && + g_tracy_events[0].bytes == 0 && pool_is_heap(g_tracy_events[0].pool), + "operator new(0) is reported once to the C++ heap pool with 0 bytes"); + + operator delete(empty); + expect(g_tracy_event_count == 2 && !g_tracy_events[1].alloc && g_tracy_events[1].pointer == empty && + pool_is_heap(g_tracy_events[1].pool), + "operator delete reports the same pointer and pool"); + + // Over-aligned blocks come from _aligned_malloc, so they must go back through _aligned_free (a plain free() + // here corrupts the heap). + g_tracy_event_count = 0; + const std::align_val_t alignment{4096}; + void* aligned = operator new(100, alignment); + expect(aligned != nullptr, "aligned operator new returns a block"); + expect(reinterpret_cast<std::uintptr_t>(aligned) % 4096 == 0, "aligned operator new honours the alignment"); + std::memset(aligned, 0xA5, 100); + expect(g_tracy_event_count == 1 && g_tracy_events[0].bytes == 100, "aligned allocation reports its size"); + operator delete(aligned, alignment); + expect(g_tracy_event_count == 2 && !g_tracy_events[1].alloc && g_tracy_events[1].pointer == aligned, + "aligned delete reports the same pointer"); + + void* aligned_empty = operator new(0, alignment); + expect(aligned_empty != nullptr, "aligned operator new(0) returns a block"); + operator delete(aligned_empty, alignment); + + // Deleting a null pointer is a no-op and must not reach the profiler. + g_tracy_event_count = 0; + operator delete(nullptr); + operator delete(nullptr, alignment); + expect(g_tracy_event_count == 0, "operator delete(nullptr) reports nothing"); + + if (failures) return 1; + std::puts("tracy_new_check: ok"); + return 0; +} diff --git a/tests/ttpf_batch_export_check.py b/tests/ttpf_batch_export_check.py index cb209a608d..5cd1bb9126 100644 --- a/tests/ttpf_batch_export_check.py +++ b/tests/ttpf_batch_export_check.py @@ -404,6 +404,74 @@ def test_manifest_generation(self): finally: batch.load_tools = orig_load + def test_manifest_cannot_replace_a_requested_dds(self): + for index in (0, 1, 2): + for existing in (False, True): + with self.subTest(index=index, existing=existing), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"DUMMY_POOL") + out_dir = root / "out" + dds = out_dir / f"tex_{index:05d}.dds" + if existing: + out_dir.mkdir() + dds.write_bytes(b"previous dds") + with patch.object(batch, "load_tools", return_value=MockTtpfModule), \ + patch.object(MockTtpfModule, "export", wraps=MockTtpfModule.export) as export: + with self.assertRaisesRegex(ValueError, "manifest path collides with DDS"): + batch.batch_export(pool, out_dir, indices=[index], manifest_path=dds) + export.assert_not_called() + self.assertEqual(pool.read_bytes(), b"DUMMY_POOL") + if existing: + self.assertEqual(dds.read_bytes(), b"previous dds") + else: + self.assertFalse(out_dir.exists()) + + def test_manifest_dds_name_in_a_different_directory_is_allowed(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"DUMMY_POOL") + out_dir = root / "out" + manifest = root / "tex_00000.dds" + with patch.object(batch, "load_tools", return_value=MockTtpfModule): + summary = batch.batch_export(pool, out_dir, indices=[0], manifest_path=manifest) + self.assertEqual(summary["stats"]["strict"], 1) + row, = json.loads(manifest.read_text()) + dds = out_dir / row["file"] + self.assertEqual(dds.read_bytes(), b"DDS_STRICT_BC1_DATA") + self.assertEqual(row["sha256"], hashlib.sha256(dds.read_bytes()).hexdigest()) + + def test_manifest_cannot_replace_a_history_or_calibration_input(self): + for option in ("history", "calibration"): + with self.subTest(option=option), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"DUMMY_POOL") + profile = root / "profile.json" + original = b'{"version": 1}' + profile.write_bytes(original) + out_dir = root / "out" + tools = SimpleNamespace( + __file__=str(root / "ttpf_mips.py"), Pool=MockTtpfModule.Pool, + analyze=MockTtpfModule.analyze, export=MockTtpfModule.export, + BC_FORMATS=MockTtpfModule.BC_FORMATS, + ) + calibrated = SimpleNamespace( + __file__=str(root / "calibrated_texture.py"), ttpf=tools, + native=Mock(), LocalDecoder=Mock(), + ) + kwargs = ({"history_path": profile, "allow_provisional": True} if option == "history" + else {"calibration_path": profile}) + with patch.object(batch, "load_tools", return_value=tools) as load, patch.dict( + sys.modules, {"calibrated_texture": calibrated} + ): + with self.assertRaisesRegex(ValueError, f"manifest path collides with --{option}"): + batch.batch_export(pool, out_dir, indices=[0], manifest_path=profile, **kwargs) + load.assert_not_called() + self.assertEqual(profile.read_bytes(), original) + self.assertFalse(out_dir.exists()) + def test_export_fitted_then_strict_reused_directory(self): """A failed strict export keeps the prior DDS outside the current manifest.""" with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/unified_buffer_paths_check.cpp b/tests/unified_buffer_paths_check.cpp index fe8d868a37..1a0b74089b 100644 --- a/tests/unified_buffer_paths_check.cpp +++ b/tests/unified_buffer_paths_check.cpp @@ -18,9 +18,8 @@ // section, or on the allocation base for the private range, after // D3D12_FEATURE_EXISTING_HEAPS) and a cross-adapter buffer is placed at the slot offset. // The GPU reads and writes title memory; nothing is copied. -// copy A default-heap buffer fed from a two-slot upload ring that wraps like reserve_upload_ring -// but checks each slot's fence: a slot still in flight is refused -// (DXGI_ERROR_WAS_STILL_DRAWING) instead of being overwritten. Title memory is copied into +// copy A default-heap buffer fed from a two-slot upload ring that checks each slot's fence: +// a slot still in flight is refused (DXGI_ERROR_WAS_STILL_DRAWING). Title memory is copied into // the ring at one named copy point: bind (upload_from_title), record (frame_copy) or submit // (just before ExecuteCommandLists, the contract point). The ring slot is copied into the // buffer at the start of the submission; a use that declares GPU writes copies buffer -> @@ -190,8 +189,7 @@ struct FencedSlots { } }; -// The upload ring: a cursor that wraps, as reserve_upload_ring does, but a slot whose submission has not -// completed is refused rather than reused. reuse_early (the mutant) takes it anyway, as production does. +// The modeled ring wraps only when a slot's submission has completed. struct Ring { UINT64 state[ring_slots]{}; unsigned cursor = 0, wraps = 0; diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp new file mode 100644 index 0000000000..0eaa3c6661 --- /dev/null +++ b/tests/upload_reservation_check.cpp @@ -0,0 +1,235 @@ +#include "startup_stubs/upload_reservation.h" + +#include <cstdint> +#include <cstdio> +#include <cstdlib> +#include <map> +#include <memory> +#include <vector> + +namespace { + +void check(bool ok, const char* what) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + std::exit(1); + } +} + +constexpr std::uint64_t kAlign = 512; + +struct TestFence { + std::uint64_t value = 0; + std::uint64_t GetCompletedValue() const { return value; } +}; + +void check_ring_reuse() +{ + // Four 64 MiB reservations fill the 256 MiB budget. The queues run independently. + constexpr auto bytes = max_upload_ring_bytes / 4; + std::unique_ptr<unsigned char[]> storage(new unsigned char[max_upload_ring_bytes]); + std::array<UploadRingChunk, 4> chunks{}; + UploadChunkMask recording = 0; + for (unsigned i = 0; i < chunks.size(); ++i) { + chunks[i] = {nullptr, storage.get() + i * bytes, bytes}; + const auto slice = reserve_upload_chunk(chunks[i], bytes); + check(slice.mapped != nullptr, "fill ring"); + chunks[i].hold(recording, i); + chunks[i].hold(recording, i); + check(chunks[i].recordings == 1, "one hold per recording and chunk"); + } + + TestFence a, b; + std::map<unsigned, UploadQueue<TestFence>> queues{{0, {&a, 1}}, {1, {&b, 1}}}; + for (auto& queue : queues) queue.second.submitted(recording, true); + a.value = b.value = 1; + auto& chunk = chunks[0]; + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "closed list can be resubmitted"); + + ++queues[1].value; + queues[1].submitted(recording, true); + const auto submitted = recording; + discard_upload_chunks(recording, chunks.data()); // reset after the second submit on queue b + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "latest submit on every queue must complete"); + b.value = UINT64_MAX; + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "device removal is not completion"); + b.value = 2; + const auto next = reuse_upload_chunk(chunk, 0, bytes, queues); + check(next.mapped == storage.get() && next.offset == 0 && next.generation == 1, + "320 MiB cumulative reservations reuse completed storage"); + + queues[0].submitted(submitted, false); + queues[0].submitted(submitted, true); + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "untracked submit prevents reuse"); +} + +void check_snapshot_pool() +{ + // The snapshot pool's chunks are numbered after the ring's in the same recording mask and the same per-queue table. + check(snapshot_chunk_base == max_upload_chunks && max_snapshot_chunks == 8 && upload_chunk_bits == 40, "pool numbering"); + unsigned char storage[4 * kAlign]; + std::array<UploadRingChunk, 2> ring{}; + std::array<UploadRingChunk, 2> snap{}; + UploadRingChunk& chunk = snap[1]; + chunk = {nullptr, storage, sizeof(storage), sizeof(storage)}; + UploadChunkMask recording = 0; + ring[1].hold(recording, 1); + snap[0].hold(recording, snapshot_chunk_base + 0); + snap[1].hold(recording, snapshot_chunk_base + 1); + check(ring[1].recordings == 1 && snap[0].recordings == 1 && snap[1].recordings == 1 && ring[0].recordings == 0, "holds land in their pool"); + TestFence fence; + std::map<unsigned, UploadQueue<TestFence>> queues{{0, {&fence, 1}}}; + queues[0].submitted(recording, true); + check(!queues[0].completed(snapshot_chunk_base + 1), "a snapshot chunk in flight is not complete"); + fence.value = 1; + check(queues[0].completed(snapshot_chunk_base + 1) && queues[0].completed(snapshot_chunk_base + 7), "completed, or never used"); + check(!reuse_upload_chunk(chunk, snapshot_chunk_base + 1, kAlign, queues).mapped, "a held chunk is not reused"); + discard_upload_chunks(recording, ring.data(), snap.data()); + check(recording == 0 && ring[1].recordings == 0 && snap[0].recordings == 0 && snap[1].recordings == 0, "discard releases both pools"); + const auto again = reuse_upload_chunk(chunk, snapshot_chunk_base + 1, kAlign, queues); + check(again.mapped == storage && again.generation == 1, "a finished, unheld snapshot chunk is reused"); +} + +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 bookkeeping: a closed list stops holding its chunks once its submit is fenced, +// the fence alone then guards the chunks, and a later submit of the same list before its Reset fences the intact +// chunks again and reports the reused ones. +void check_release_at_submit() +{ + constexpr std::uint64_t bytes = 4 * kAlign; + unsigned char storage[2][bytes]; + std::array<UploadRingChunk, 2> chunks{}; + UploadChunkMask recording = 0; + for (unsigned i = 0; i < chunks.size(); ++i) { + chunks[i] = {nullptr, storage[i], bytes}; + check(reserve_upload_chunk(chunks[i], bytes).mapped != nullptr, "release: fill chunk"); + chunks[i].hold(recording, i); + } + + TestFence fence; + std::map<unsigned, UploadQueue<TestFence>> queues{{0, {&fence, 1}}}; + queues[0].submitted(recording, true); + check(!reuse_upload_chunk(chunks[0], 0, bytes, queues).mapped, "release: a closed list holds until released"); + + ReleasedUploadChunks released; + release_upload_chunks_at_submit(recording, chunks.data(), released); + check(recording == 0 && chunks[0].recordings == 0 && chunks[1].recordings == 0, "release: holds dropped"); + check(released.chunks == 3 && released.generation[0] == 0 && released.generation[1] == 0, + "release: chunks and generations recorded"); + check(!reuse_upload_chunk(chunks[0], 0, bytes, queues).mapped, "release: the fence still guards the chunk"); + + fence.value = 1; + const auto reused = reuse_upload_chunk(chunks[0], 0, bytes, queues); + check(reused.mapped == storage[0] && reused.generation == 1, "release: chunk reused after the fence"); + + UploadChunkMask recycled = UINT64_MAX; + const auto intact = resubmitted_upload_chunks(released, chunks.data(), recycled); + check(intact == 2 && recycled == 1, "release: a resubmit finds chunk 1 intact and chunk 0 reused"); + + ++queues[0].value; + queues[0].submitted(intact, true); + check(!reuse_upload_chunk(chunks[1], 1, bytes, queues).mapped, "release: the resubmit fences the intact chunk"); + fence.value = 2; + check(reuse_upload_chunk(chunks[1], 1, bytes, queues).mapped != nullptr, + "release: the intact chunk is reused after the resubmit's fence"); + check(resubmitted_upload_chunks(released, chunks.data(), recycled) == 0 && recycled == 3, + "release: both chunks reported once reused"); +} + +void check_snapshot_release_at_submit() +{ + constexpr unsigned ring_index = max_upload_chunks - 1; + constexpr unsigned snapshot_index = upload_chunk_bits - 1; + constexpr auto ring_bit = UploadChunkMask{1} << ring_index; + constexpr auto snapshot_bit = UploadChunkMask{1} << snapshot_index; + constexpr auto both = ring_bit | snapshot_bit; + unsigned char storage[2][kAlign]; + std::array<UploadRingChunk, max_upload_chunks> ring{}; + std::array<UploadRingChunk, max_snapshot_chunks> snapshots{}; + auto& ring_chunk = ring.back(); + auto& snapshot = snapshots.back(); + ring_chunk = {nullptr, storage[0], kAlign, kAlign, 2}; + snapshot = {nullptr, storage[1], kAlign, kAlign, 3}; + UploadChunkMask recording = 0; + ring_chunk.hold(recording, ring_index); + snapshot.hold(recording, snapshot_index); + check(recording == both, "snapshot release: both boundary bits are recorded"); + + TestFence first, second; + std::map<unsigned, UploadQueue<TestFence>> queues{{0, {&first, 1}}, {1, {&second, 1}}}; + queues[0].submitted(recording, true); + ReleasedUploadChunks released; + release_upload_chunks_at_submit(recording, ring.data(), released, snapshots.data()); + check(!recording && !ring_chunk.recordings && !snapshot.recordings, "snapshot release: both holds dropped"); + check(released.chunks == both && released.generation[ring_index] == 2 && released.generation[snapshot_index] == 3, + "snapshot release: both generations saved"); + check(!reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues).mapped, + "snapshot release: first fence guards the snapshot after release"); + + UploadChunkMask recycled = UINT64_MAX; + const auto intact = resubmitted_upload_chunks(released, ring.data(), recycled, snapshots.data()); + check(intact == both && !recycled, "snapshot release: intact resubmit includes both pools"); + queues[1].submitted(intact, true); + first.value = 1; + check(!reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues).mapped, + "snapshot release: the other queue's resubmit fence still guards reuse"); + second.value = 1; + const auto reused = reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues); + check(reused.mapped == storage[1] && reused.generation == 4, "snapshot release: reuse after both fences"); + check(resubmitted_upload_chunks(released, ring.data(), recycled, snapshots.data()) == ring_bit && + recycled == snapshot_bit, "snapshot release: a recycled snapshot alone invalidates the recording"); +} + +} // namespace + +int main() +{ + unsigned char storage_a[4 * kAlign]; + unsigned char storage_b[8 * kAlign]; + std::vector<UploadRingChunk> chunks; + chunks.push_back({nullptr, storage_a, sizeof(storage_a), 0}); + + const auto first = reserve_upload_chunk(chunks[0], 2 * kAlign); + check(first.mapped == storage_a && first.offset == 0, "initial reservation"); + check(chunks[0].used == 2 * kAlign, "initial cursor"); + first.mapped[0] = 0xa5; + first.mapped[2 * kAlign - 1] = 0x5a; + + const auto refused = reserve_upload_chunk(chunks[0], 3 * kAlign); + check(!refused.mapped && !refused.resource && refused.offset == 0, + "insufficient tail refuses the reservation"); + check(chunks[0].used == 2 * kAlign, "refusal preserves cursor"); + + chunks.push_back({nullptr, storage_b, sizeof(storage_b), 0}); + const auto second = reserve_upload_chunk(chunks[1], 3 * kAlign); + check(second.mapped == storage_b && second.offset == 0, "new chunk reservation"); + second.mapped[0] = 0xc3; + chunks.reserve(chunks.capacity() + 1); + check(first.mapped[0] == 0xa5 && first.mapped[2 * kAlign - 1] == 0x5a, + "first mapped reservation survives vector growth"); + check(second.mapped[0] == 0xc3, "new mapped reservation survives vector growth"); + + const auto next = reserve_upload_chunk(chunks[1], 5 * kAlign); + check(next.mapped == storage_b + 3 * kAlign && next.offset == 3 * kAlign, + "exact remaining active tail"); + check(chunks[1].used == chunks[1].capacity, "active cursor reaches capacity"); + check(!reserve_upload_chunk(chunks[1], kAlign).mapped, "full active chunk refuses"); + check(chunks[1].used == chunks[1].capacity, "active refusal preserves cursor"); + + const auto older = reserve_upload_chunk(chunks[0], 2 * kAlign); + check(older.mapped == storage_a + 2 * kAlign && older.offset == 2 * kAlign, + "older chunk reserves only previously unused bytes"); + older.mapped[0] = 0x7d; + check(chunks[0].used == chunks[0].capacity, "older cursor reaches capacity"); + check(!reserve_upload_chunk(chunks[0], kAlign).mapped, "full older chunk refuses"); + check(chunks[0].used == chunks[0].capacity && storage_a[0] == 0xa5 && + storage_a[2 * kAlign - 1] == 0x5a && storage_a[2 * kAlign] == 0x7d, + "existing reservations survive exhaustion"); + + check_ring_reuse(); + check_snapshot_pool(); + check_release_at_submit(); + check_snapshot_release_at_submit(); + std::puts("upload_reservation_check: all checks passed"); + return 0; +} diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp new file mode 100644 index 0000000000..981608bb05 --- /dev/null +++ b/tests/xmem_cross_call_merge_check.cpp @@ -0,0 +1,470 @@ +// Cross-call merge of shared views (X2W_XMEM_SHARED_VIEWS=1 and X2W_XMEM_JOIN_CALLS=1, src/xmem_mapped_pages.cpp, +// merge_with_previous). A run mapped by a call of its own joins the recorded run that ends at its address when its +// first page is the next slot of the section behind that run's last page and both lie in one reservation of the shim. +// What a view is, is measured with VirtualQuery: inside a view AllocationBase is the view's base and RegionSize the +// bytes to the view's end. +// +// Modes (each sets X2W_XMEM_SHARED_VIEWS and X2W_XMEM_JOIN_CALLS itself; JOIN_CALLS=1 in every mode but no-join): +// check (test-controls xmem.dll) every case below. +// control (test-controls xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) single-page calls keep a view each: the layout +// before the merge. Prints "no-merge control: 32 views". +// deployed (deployed xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) the deployed shim ignores the test switch and merges. +// default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own; the join +// switch alone does nothing. +// no-join (deployed xmem.dll, X2W_XMEM_JOIN_CALLS unset) single-page calls keep a view each: joins are opt-in. +// Prints "no-join: 32 views". +// timing (test-controls xmem.dll; not a ctest case) ms of a join, of a break and of an own-view map against the +// run length R (X2W_XMEM_TEST_MERGE_CAP): a table of "timing:" lines, one row per R from 16 to 4096. +// The pass line of control, deployed, default and no-join is printed at the end of main, only when no check failed. +// +// Cases of `check`: +// joined 32 single-page calls on consecutive slots: one view of 32 pages; each page keeps the mark written +// right after its own call. +// middle unmapping page 10 of that view leaves views [0, 10) and [11, 32) with their marks. +// reversed 32 single-page calls on slots in reverse order (adjacent addresses, not adjacent slots): 32 views, +// page i shows slot 31 - i. +// window X2W_XMEM_TEST_HOLD_WINDOW holds the merge while the earlier run is unmapped: a raw query of one +// of its pages is not committed; a thread that reads the page and an x2w_xmem_stable_call query both +// wait, then read the mark and MEM_COMMIT; the result is one view of 9 pages. +// refused-4/5 X2W_XMEM_TEST_FAULT=4:0 (the joined map refused) and 5:0 (joining the placeholders refused): the call +// succeeds, the earlier run is a view of 8 pages again, the new page a view of its own, marks kept, +// the pages unmap and release, and the live page count returns to where it was. +// two-reservations a caller placeholder split in two pieces, each recorded with XMemVirtualAlloc (permissive +// replace-placeholder call): a page at the start of the second piece does not join the first's run. +// capped 192 single-page calls make three runs of 64 pages (max_merged_run_pages); an unmap held in its window +// inside the middle run takes apart at most 64 pages, and the outer runs stay mapped. +// +// Usage: xmem_cross_call_merge_check <xmem.dll> check|control|deployed|default|no-join|timing +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> + +#include <algorithm> +#include <atomic> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <thread> +#include <vector> + +namespace { +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*, SIZE_T*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, SIZE_T, SIZE_T*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*); +using StableCallFn = BOOL(WINAPI*)(void (*)(void*), void*); +using PageStatsFn = BOOL(WINAPI*)(ULONGLONG*); +using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T count = 32; + +int failures = 0; +const char* token = nullptr; // the mode's pass line; main prints it at its end, and only with no failure + +bool check(bool ok, const char* name, const char* detail = "") +{ + std::printf("%s: %s%s%s\n", ok ? "ok" : "check_failed", name, *detail ? " " : "", detail); + if (!ok) ++failures; + return ok; +} + +struct Region { + ULONG_PTR allocation_base = 0; + SIZE_T size = 0; + DWORD state = 0; +}; + +Region region(const unsigned char* address) +{ + MEMORY_BASIC_INFORMATION info{}; + if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info)) return {}; + return {reinterpret_cast<ULONG_PTR>(info.AllocationBase), info.RegionSize, info.State}; +} + +// The view that holds address starts at first and ends at end (exclusive). +bool view_is(const unsigned char* address, const unsigned char* first, const unsigned char* end) +{ + const Region r = region(address); + return r.state == MEM_COMMIT && r.allocation_base == reinterpret_cast<ULONG_PTR>(first) && + r.size == static_cast<SIZE_T>(end - address); +} + +std::uint32_t& word(unsigned char* address) { return *reinterpret_cast<std::uint32_t*>(address); } + +struct Shim { + XMemVirtualAllocFn virtual_alloc; + XMemAllocatePhysicalPagesFn allocate; + XMemMapPhysicalPagesFn map; + XMemFreePhysicalPagesFn release; + StableCallFn stable_call; + PageStatsFn page_stats; + + std::vector<SIZE_T> pages(SIZE_T n) const + { + std::vector<SIZE_T> tokens(n); + SIZE_T got = n; + if (!allocate(0x20400000, &got, tokens.data()) || got != n) tokens.clear(); + return tokens; + } + ULONGLONG live() const + { + ULONGLONG value = ~0ull; + page_stats(&value); + return value; + } +}; + +// Maps tokens[order(i)] at base + i pages, one call each, and marks each page right after its call, before the next +// call merges it. Returns false when a call fails. +template <class Order> +bool map_one_by_one(const Shim& shim, unsigned char* base, std::vector<SIZE_T>& tokens, std::uint32_t tag, Order order) +{ + for (SIZE_T i = 0; i < tokens.size(); ++i) { + unsigned char* const at = base + i * page; + if (shim.map(at, 1, &tokens[order(i)]) != at) return false; + word(at) = tag + static_cast<std::uint32_t>(i); + word(at + page - 4) = static_cast<std::uint32_t>(order(i)); + } + return true; +} + +bool marked(unsigned char* base, SIZE_T n, std::uint32_t tag, SIZE_T skip = SIZE_T(-1)) +{ + for (SIZE_T i = 0; i < n; ++i) { + if (i == skip) continue; + if (region(base + i * page).state != MEM_COMMIT || word(base + i * page) != tag + i) return false; + } + return true; +} + +// joined (merging modes) or the per-page layout (control, default); then middle in `check`. +void single_page_calls(const Shim& shim, unsigned char* base, bool merges, bool middle) +{ + auto tokens = shim.pages(count); + if (!check(tokens.size() == count, "allocate 32 pages")) return; + if (!check(map_one_by_one(shim, base, tokens, 0x61000000u, [](SIZE_T i) { return i; }), "32 single-page calls")) return; + if (merges) { + if (check(view_is(base, base, base + count * page) && view_is(base + (count - 1) * page, base, base + count * page), + "joined: one view of 32 pages")) + token = "merge: 1 view of 32 pages"; + } else { + bool each = true; + for (SIZE_T i = 0; i < count; ++i) each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); + if (check(each, "one view per call")) token = "no-merge control: 32 views"; + } + check(marked(base, count, 0x61000000u), "joined: marks kept"); + if (middle) { + check(shim.map(base + 10 * page, 1, nullptr) == base + 10 * page, "middle: unmap page 10"); + check(view_is(base, base, base + 10 * page) && view_is(base + 9 * page, base, base + 10 * page), "middle: view [0, 10)"); + check(view_is(base + 11 * page, base + 11 * page, base + count * page), "middle: view [11, 32)"); + check(region(base + 10 * page).state == MEM_RESERVE, "middle: page 10 reserved"); + check(marked(base, count, 0x61000000u, 10), "middle: neighbours keep their marks"); + check(shim.map(base, 10, nullptr) == base && shim.map(base + 11 * page, count - 11, nullptr) == base + 11 * page, + "middle: unmap the rest"); + } else { + check(shim.map(base, count, nullptr) == base, "unmap 32 pages"); + } + check(shim.release(count, tokens.data()) != FALSE, "release 32 pages"); +} + +void reversed(const Shim& shim, unsigned char* base, unsigned char* scratch) +{ + auto tokens = shim.pages(count); + if (!check(tokens.size() == count, "reversed: allocate")) return; + // Mark every slot through one view first: slot k holds 0x62000000 + k. + if (!check(shim.map(scratch, count, tokens.data()) == scratch, "reversed: map the slots in order")) return; + for (SIZE_T k = 0; k < count; ++k) word(scratch + k * page) = 0x62000000u + static_cast<std::uint32_t>(k); + check(shim.map(scratch, count, nullptr) == scratch, "reversed: unmap the slots"); + bool mapped = true; + for (SIZE_T i = 0; i < count && mapped; ++i) + mapped = shim.map(base + i * page, 1, &tokens[count - 1 - i]) == base + i * page; + if (!check(mapped, "reversed: 32 single-page calls")) return; + bool each = true, data = true; + for (SIZE_T i = 0; i < count; ++i) { + each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); + data &= region(base + i * page).state == MEM_COMMIT && word(base + i * page) == 0x62000000u + (count - 1 - i); + } + check(each, "reversed: 32 views"); + check(data, "reversed: page i shows slot 31 - i"); + check(shim.map(base, count, nullptr) == base && shim.release(count, tokens.data()), "reversed: unmap and release"); +} + +void window(const Shim& shim, unsigned char* base) +{ + auto tokens = shim.pages(9); + if (!check(tokens.size() == 9 && shim.map(base, 8, tokens.data()) == base, "window: map a run of 8 pages")) return; + for (SIZE_T i = 0; i < 8; ++i) word(base + i * page) = 0x63000000u + static_cast<std::uint32_t>(i); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-cross-call-merge-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + bool joined_call = false; + std::thread mapper([&] { joined_call = shim.map(base + 8 * page, 1, &tokens[8]) == base + 8 * page; }); + const bool opened = WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0; + check(opened, "window: the merge held the window"); + unsigned char* const target = base + 2 * page; + if (opened) check(region(target).state != MEM_COMMIT, "window: raw query inside the window not committed"); + std::atomic<bool> read_done{false}, query_done{false}; + std::uint32_t value = 0; + DWORD state = 0; + std::thread reader([&] { + value = word(target); // faults inside the window; retried by the shim after it + read_done = true; + }); + std::thread querier([&] { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast<Query*>(context); + q.state = region(q.target).state; + }, &query); + state = query.state; + query_done = true; + }); + Sleep(300); + check(!read_done.load(), "window: the reader waits for the merge"); + check(!query_done.load(), "window: x2w_xmem_stable_call waits for the merge"); + SetEvent(release); + reader.join(); + querier.join(); + mapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(joined_call, "window: the mapping call succeeded"); + check(value == 0x63000002u, "window: the reader read the mark"); + check(state == MEM_COMMIT, "window: x2w_xmem_stable_call answered committed"); + check(view_is(base, base, base + 9 * page), "window: one view of 9 pages"); + check(marked(base, 8, 0x63000000u), "window: marks kept"); + check(shim.map(base, 9, nullptr) == base && shim.release(9, tokens.data()), "window: unmap and release"); + CloseHandle(unmapped); + CloseHandle(release); +} + +void refused(const Shim& shim, unsigned char* base, const char* stage, const char* name) +{ + const ULONGLONG live_before = shim.live(); + auto tokens = shim.pages(9); + if (!check(tokens.size() == 9 && shim.map(base, 8, tokens.data()) == base, name, "map a run of 8 pages")) return; + for (SIZE_T i = 0; i < 8; ++i) word(base + i * page) = 0x64000000u + static_cast<std::uint32_t>(i); + SetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", stage); + const bool mapped = shim.map(base + 8 * page, 1, &tokens[8]) == base + 8 * page; + SetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", nullptr); + check(mapped, name, "the mapping call succeeded"); + // State first: a page without a view is not touched. + bool committed = true; + for (SIZE_T i = 0; i < 9; ++i) committed &= region(base + i * page).state == MEM_COMMIT; + if (!check(committed, name, "all 9 pages committed")) return; + check(view_is(base, base, base + 8 * page) && view_is(base + 7 * page, base, base + 8 * page), name, + "the run is a view of 8 pages again"); + check(view_is(base + 8 * page, base + 8 * page, base + 9 * page), name, "the new page has a view of its own"); + check(marked(base, 8, 0x64000000u), name, "marks kept"); + word(base + 8 * page) = 0x64000008u; + check(marked(base, 9, 0x64000000u), name, "the new page holds its write"); + check(shim.map(base, 9, nullptr) == base, name, "unmap 9 pages"); + check(shim.release(9, tokens.data()) != FALSE, name, "release 9 pages"); + check(shim.live() == live_before, name, "live page count back where it was"); +} + +// Named events for X2W_XMEM_TEST_HOLD_WINDOW: "<name>.unmapped" (set by the held call) and "<name>.release". +struct Hold { + char name[64]; + HANDLE unmapped, release; + explicit Hold(const char* stem) + { + std::snprintf(name, sizeof(name), "x2w-cross-call-merge-%s-%lu", stem, GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", name); + unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", name); + release = CreateEventA(nullptr, TRUE, FALSE, event_name); + } + ~Hold() + { + CloseHandle(unmapped); + CloseHandle(release); + } +}; + +// capped: 3 * cap single-page calls make three runs of cap pages (the cap of the shim, 64), not one. The unmap of a +// page in the middle run is held in its window: the pages that read as not committed there are the pages the break +// took apart, at most one run of cap pages; the runs before and after it stay mapped. +void capped(const Shim& shim, unsigned char* base) +{ + constexpr SIZE_T cap = 64, n = 3 * cap, hole = cap + cap / 2; + auto tokens = shim.pages(n); + if (!check(tokens.size() == n, "capped: allocate 192 pages")) return; + if (!check(map_one_by_one(shim, base, tokens, 0x65000000u, [](SIZE_T i) { return i; }), "capped: 192 single-page calls")) + return; + bool runs = true; + for (SIZE_T r = 0; r < 3; ++r) + runs &= view_is(base + r * cap * page, base + r * cap * page, base + (r + 1) * cap * page) && + view_is(base + ((r + 1) * cap - 1) * page, base + r * cap * page, base + (r + 1) * cap * page); + check(runs, "capped: three views of 64 pages"); + Hold hold("capped"); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold.name); + bool unmapped_call = false; + std::thread unmapper([&] { unmapped_call = shim.map(base + hole * page, 1, nullptr) == base + hole * page; }); + const bool opened = WaitForSingleObject(hold.unmapped, 10000) == WAIT_OBJECT_0; + SIZE_T taken_apart = 0; + bool outer_mapped = true; + for (SIZE_T i = 0; opened && i < n; ++i) { + const bool committed = region(base + i * page).state == MEM_COMMIT; + taken_apart += !committed; + if (i < cap || i >= 2 * cap) outer_mapped &= committed; + } + SetEvent(hold.release); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + char detail[64]; + std::snprintf(detail, sizeof(detail), "(%zu pages)", static_cast<std::size_t>(taken_apart)); + check(opened, "capped: the unmap held the window"); + check(opened && taken_apart <= cap, "capped: the break took apart at most 64 pages", detail); + check(opened && outer_mapped, "capped: the runs before and after stay mapped in the window"); + check(unmapped_call, "capped: the unmap succeeded"); + check(view_is(base + cap * page, base + cap * page, base + hole * page) && + view_is(base + (hole + 1) * page, base + (hole + 1) * page, base + 2 * cap * page), "capped: views [64, 96) and [97, 128)"); + check(marked(base, n, 0x65000000u, hole), "capped: marks kept"); + check(shim.map(base, hole, nullptr) == base && shim.map(base + (hole + 1) * page, n - hole - 1, nullptr) == base + (hole + 1) * page && + shim.release(n, tokens.data()), "capped: unmap and release"); +} + +// timing (not a ctest case; one row per R): for a run of R pages, the ms of the call that joins page R to a run of +// R - 1 (X2W_XMEM_TEST_MERGE_CAP=R), of the unmap of page R/2 (one break of the whole run) and, for comparison, of a +// single-page call that maps a view of its own (X2W_XMEM_TEST_NO_MERGE=1). Every byte of the run is written before +// the join and before the break, as a title's use of the pages would (a run that is mostly untouched unmaps much +// faster). Median of 5 (3 from 1024 pages). This process has a few +// views; a title process has tens of thousands, and under Wine each map costs more the more views there are. +double ms_since(const LARGE_INTEGER& from) +{ + LARGE_INTEGER now, frequency; + QueryPerformanceCounter(&now); + QueryPerformanceFrequency(&frequency); + return 1000.0 * static_cast<double>(now.QuadPart - from.QuadPart) / static_cast<double>(frequency.QuadPart); +} + +double median(std::vector<double> v) +{ + std::sort(v.begin(), v.end()); + return v.empty() ? 0.0 : v[v.size() / 2]; +} + +void timing(const Shim& shim, unsigned char* base) +{ + std::printf("timing: R pages | join ms | break ms | own-view map ms (median of 5)\n"); + for (const SIZE_T r : {SIZE_T{16}, SIZE_T{32}, SIZE_T{64}, SIZE_T{128}, SIZE_T{256}, SIZE_T{512}, SIZE_T{1024}, + SIZE_T{2048}, SIZE_T{4096}}) { + std::vector<double> join, unmap, own; + char cap[24]; + std::snprintf(cap, sizeof(cap), "%zu", static_cast<std::size_t>(r)); + for (int rep = 0; rep < (r >= 1024 ? 3 : 5); ++rep) { + auto tokens = shim.pages(r + 1); + if (!check(tokens.size() == r + 1 && shim.map(base, r - 1, tokens.data()) == base, "timing: map R - 1 pages")) return; + std::memset(base, 0x5a, (r - 1) * page); + SetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", cap); + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + const bool joined = shim.map(base + (r - 1) * page, 1, &tokens[r - 1]) == base + (r - 1) * page; + join.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", nullptr); + check(joined && view_is(base, base, base + r * page), "timing: joined run of R pages"); + std::memset(base, 0x5b, r * page); + QueryPerformanceCounter(&t); + check(shim.map(base + (r / 2) * page, 1, nullptr) == base + (r / 2) * page, "timing: unmap page R/2"); + unmap.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_NO_MERGE", "1"); + QueryPerformanceCounter(&t); + const bool alone = shim.map(base + r * page, 1, &tokens[r]) == base + r * page; + own.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_NO_MERGE", nullptr); + check(alone && view_is(base + r * page, base + r * page, base + (r + 1) * page), "timing: own view"); + check(shim.map(base, r / 2, nullptr) == base && shim.map(base + (r / 2 + 1) * page, r / 2, nullptr) && + shim.release(r + 1, tokens.data()), "timing: unmap and release"); + } + std::printf("timing: %4zu | %7.3f | %7.3f | %7.3f\n", static_cast<std::size_t>(r), median(join), median(unmap), median(own)); + } +} + +void two_reservations(const Shim& shim) +{ + const auto virtual_alloc2 = reinterpret_cast<VirtualAlloc2Fn>( + GetProcAddress(GetModuleHandleA("kernelbase.dll"), "VirtualAlloc2")); + if (!check(virtual_alloc2 != nullptr, "two-reservations: VirtualAlloc2")) return; + auto* const piece = static_cast<unsigned char*>(virtual_alloc2(GetCurrentProcess(), nullptr, 8 * page, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)); + if (!check(piece && VirtualFree(piece, 4 * page, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "two-reservations: split a placeholder")) + return; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + const bool recorded = shim.virtual_alloc(piece, 4 * page, 0x20406000, 0x21, PAGE_READWRITE) == piece && + shim.virtual_alloc(piece + 4 * page, 4 * page, 0x20406000, 0x21, PAGE_READWRITE) == piece + 4 * page; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + if (!check(recorded, "two-reservations: record both pieces")) return; + auto tokens = shim.pages(5); + if (!check(tokens.size() == 5 && shim.map(piece, 4, tokens.data()) == piece && + shim.map(piece + 4 * page, 1, &tokens[4]) == piece + 4 * page, "two-reservations: map 4 + 1 pages")) + return; + check(view_is(piece, piece, piece + 4 * page), "two-reservations: the first piece's run stays 4 pages"); + check(view_is(piece + 4 * page, piece + 4 * page, piece + 5 * page), "two-reservations: the page has a view of its own"); + check(shim.map(piece, 4, nullptr) == piece && shim.map(piece + 4 * page, 1, nullptr) == piece + 4 * page && + shim.release(5, tokens.data()), "two-reservations: unmap and release"); + VirtualFree(piece, 0, MEM_RELEASE); + VirtualFree(piece + 4 * page, 0, MEM_RELEASE); +} +} // namespace + +int main(int argc, char** argv) +{ + const char* const mode = argc == 3 ? argv[2] : ""; + const bool all = std::strcmp(mode, "check") == 0, control = std::strcmp(mode, "control") == 0, + deployed = std::strcmp(mode, "deployed") == 0, plain = std::strcmp(mode, "default") == 0, + timed = std::strcmp(mode, "timing") == 0, no_join = std::strcmp(mode, "no-join") == 0; + if (!all && !control && !deployed && !plain && !timed && !no_join) { + std::printf("usage: xmem_cross_call_merge_check <xmem.dll> check|control|deployed|default|no-join|timing\n"); + return 2; + } + // The mode is read by the first mapping call. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", plain ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", no_join ? nullptr : "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + const Shim shim{reinterpret_cast<XMemVirtualAllocFn>(GetProcAddress(xmem, "XMemVirtualAlloc")), + reinterpret_cast<XMemAllocatePhysicalPagesFn>(GetProcAddress(xmem, "XMemAllocatePhysicalPages")), + reinterpret_cast<XMemMapPhysicalPagesFn>(GetProcAddress(xmem, "XMemMapPhysicalPages")), + reinterpret_cast<XMemFreePhysicalPagesFn>(GetProcAddress(xmem, "XMemFreePhysicalPages")), + reinterpret_cast<StableCallFn>(GetProcAddress(xmem, "x2w_xmem_stable_call")), + reinterpret_cast<PageStatsFn>(GetProcAddress(xmem, "x2w_xmem_page_stats"))}; + if (!shim.virtual_alloc || !shim.allocate || !shim.map || !shim.release || !shim.stable_call || !shim.page_stats) { + std::printf("check_failed: exports\n"); + return 1; + } + auto* const whole = static_cast<unsigned char*>(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!whole) { + std::printf("check_failed: startup reservation (error %lu)\n", GetLastError()); + return 1; + } + unsigned char* const base = whole + page; + if (timed) { + timing(shim, base); + VirtualFree(whole, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } + single_page_calls(shim, base, all || deployed, all); + if (no_join && token) token = "no-join: 32 views"; + if (all) { + reversed(shim, base + 64 * page, base + 128 * page); + window(shim, base + 192 * page); + refused(shim, base + 256 * page, "4:0", "refused-4"); + refused(shim, base + 320 * page, "5:0", "refused-5"); + two_reservations(shim); + capped(shim, base + 512 * page); + } + VirtualFree(whole, 0, MEM_RELEASE); + if (!failures && token) std::printf("%s\n", token); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/xmem_lazy_startup_check.py b/tests/xmem_lazy_startup_check.py index e98f519e37..48171e9af7 100644 --- a/tests/xmem_lazy_startup_check.py +++ b/tests/xmem_lazy_startup_check.py @@ -19,13 +19,22 @@ import tempfile import threading -from xmem_page_runs_check import MEM_COMMIT, MEM_RESERVE, WIN_RELEASE, Shim, bind +from xmem_page_runs_check import MEM_COMMIT, MEM_RESERVE, PAGE, WIN_RELEASE, Shim, bind CHUNK = 256 << 10 STARTUP_64K, LARGE = 0x20403000, 0x20003000 ERROR_NOACCESS = 998 GENERIC_READ, OPEN_EXISTING = 0x80000000, 3 THREADS = 8 +SLAB_TEST_PAGES = 1024 # 64 MiB of 64 KiB pages +MIN_COMMIT_DROP = 32 << 20 + + +class PerformanceInformation(C.Structure): + _fields_ = [("cb", W.DWORD)] + [(name, C.c_size_t) for name in ( + "CommitTotal", "CommitLimit", "CommitPeak", "PhysicalTotal", "PhysicalAvailable", "SystemCache", + "KernelTotal", "KernelPaged", "KernelNonpaged", "PageSize")] + [ + (name, W.DWORD) for name in ("HandleCount", "ProcessCount", "ThreadCount")] def main(path, mode=""): @@ -37,6 +46,8 @@ def main(path, mode=""): shim = Shim(path) commit_range = bind(shim.library, "x2w_xmem_commit_range", [C.c_void_p, C.c_size_t], W.BOOL) commit_block = bind(shim.library, "x2w_xmem_commit_block", [C.c_void_p], W.BOOL) + slab_stats = bind(shim.library, "x2w_xmem_slab_stats", [C.POINTER(C.c_ulonglong)] * 3, W.BOOL) + performance = bind(kernel32, "K32GetPerformanceInfo", [C.POINTER(PerformanceInformation), W.DWORD], W.BOOL) create_file = bind(kernel32, "CreateFileW", [W.LPCWSTR, W.DWORD, W.DWORD, C.c_void_p, W.DWORD, W.DWORD, W.HANDLE], W.HANDLE) read_file = bind(kernel32, "ReadFile", [W.HANDLE, C.c_void_p, W.DWORD, C.POINTER(W.DWORD), C.c_void_p], W.BOOL) @@ -45,6 +56,17 @@ def main(path, mode=""): def state(address): return shim.query(address)[3] + def commit_bytes(): + info = PerformanceInformation() + info.cb = C.sizeof(info) + assert performance(C.byref(info), info.cb), C.get_last_error() + return info.CommitTotal * info.PageSize + + def slabs(): + values = [C.c_ulonglong() for _ in range(3)] + assert slab_stats(*map(C.byref, values)), "x2w_xmem_slab_stats failed" + return tuple(v.value for v in values) + blocks = [] try: # Reserved, not committed; below the threshold a block is committed as before. @@ -123,6 +145,44 @@ def touch(index): assert state(large) == MEM_COMMIT and state(large + (32 << 20) - 1) == MEM_COMMIT, "commit_block left part lazy" C.c_uint32.from_address(large + (32 << 20) - 4).value = 7 assert commit_block(C.c_void_p(small)), "an address outside the lazy blocks must not fail" + + # X2W_XMEM_LAZY_STARTUP=1 + X2W_XMEM_STARTUP_BELOW_40=1: a 32 MiB 0x20003000 / 0x283 block is placed < 2^40, + # starts MEM_RESERVE, and commits a 256 KiB chunk on first touch. + assert set_env("X2W_XMEM_STARTUP_BELOW_40", "1") + below40 = shim.reserve_startup(None, 32 << 20, LARGE, 0x283, 0x2004) + assert set_env("X2W_XMEM_STARTUP_BELOW_40", None) + if below40: + blocks.append(below40) + assert below40, C.get_last_error() + assert below40 % (2 << 20) == 0 and below40 + (32 << 20) <= (1 << 40), f"below40 block not < 2^40: {hex(below40)}" + assert state(below40) == MEM_RESERVE and state(below40 + (32 << 20) - 1) == MEM_RESERVE, ( + "below40 block was committed up front" + ) + below40_target = below40 + CHUNK + 128 + C.c_uint32.from_address(below40_target).value = 0xCAFEBABE + assert C.c_uint32.from_address(below40_target).value == 0xCAFEBABE + assert state(below40 + CHUNK) == MEM_COMMIT and state(below40 + 2 * CHUNK - 1) == MEM_COMMIT + assert state(below40) == MEM_RESERVE and state(below40 + 2 * CHUNK) == MEM_RESERVE, ( + "below40 touch committed more than its 256 KiB chunk" + ) + + # Empty slab reclamation: allocate & map pages, touch them so OS commit grows, unmap & free all pages, + # then verify open_slabs == 0 and OS CommitTotal drops. + tokens = shim.pages(SLAB_TEST_PAGES) + try: + assert shim.contiguous(shim.whole, SLAB_TEST_PAGES, tokens) == shim.whole, C.get_last_error() + for i in range(SLAB_TEST_PAGES): + C.c_uint32.from_address(shim.whole + i * PAGE).value = i + 1 + assert slabs() == (1, SLAB_TEST_PAGES, 4096 - SLAB_TEST_PAGES), f"unexpected slab stats: {slabs()}" + before_free = commit_bytes() + assert shim.contiguous(shim.whole, SLAB_TEST_PAGES, None) == shim.whole, C.get_last_error() + assert slabs() == (1, SLAB_TEST_PAGES, 4096 - SLAB_TEST_PAGES) + finally: + assert shim.release(SLAB_TEST_PAGES, tokens) + assert slabs() == (0, 0, 0), f"empty slab was not reclaimed: {slabs()}" + dropped = before_free - commit_bytes() + print(f"slab reclaim dropped commit by {dropped >> 20} MiB (expected >= {MIN_COMMIT_DROP >> 20} MiB)") + assert dropped >= MIN_COMMIT_DROP, f"OS CommitTotal did not drop enough after slab reclaim: {dropped}" print("ok") finally: for b in blocks: diff --git a/tests/xmem_map_split_first_check.cpp b/tests/xmem_map_split_first_check.cpp new file mode 100644 index 0000000000..f2c6e56ec3 --- /dev/null +++ b/tests/xmem_map_split_first_check.cpp @@ -0,0 +1,101 @@ +// XMemMapPhysicalPages into an owned XMem reservation: when the target is in the middle of a larger placeholder, xmem +// splits first and maps once (one MapViewOfFile3 per page). Under Wine each failed map is a server round trip whose +// cost grows with the number of views, and the title maps one 64 KiB page per call at startup. +// xmem_map_split_first_check <xmem.dll> N single-page maps take N map attempts; an exact placeholder +// (left by an unmap) is mapped without a split +// xmem_map_split_first_check <xmem.dll> control test-controls build (X2W_XMEM_TEST_CONTROLS) with +// X2W_XMEM_TEST_MAP_FIRST=1: the old order takes 2N map attempts and +// prints "map-first control: maps=2N" +// xmem_map_split_first_check <xmem.dll> deployed deployed build with X2W_XMEM_TEST_MAP_FIRST=1: the build ignores +// the switch, so the checks of the first mode pass +// Each mode sets or clears X2W_XMEM_TEST_MAP_FIRST itself, so an inherited value cannot change the result. +#include <windows.h> +#include <cstdio> +#include <cwchar> + +namespace { +constexpr SIZE_T page_bytes = 65536; +constexpr ULONG_PTR pages = 8; +using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +using MapPages = void* (WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); +using MapCounts = BOOL (WINAPI*)(ULONGLONG*, ULONGLONG*); + +bool require(bool ok, const char* step) +{ + if (!ok) std::printf("FAIL: %s (last error %lu)\n", step, GetLastError()); + return ok; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; + if (argc != 2 && !control && !deployed) return 2; + // xmem reads the switch on first use and keeps the value; set it before any map. + SetEnvironmentVariableW(L"X2W_XMEM_TEST_MAP_FIRST", control || deployed ? L"1" : nullptr); + const HMODULE xmem = LoadLibraryW(argv[1]); + if (!require(xmem != nullptr, "load xmem.dll")) return 1; + const auto reserve = reinterpret_cast<Reserve>(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto alloc = reinterpret_cast<AllocPages>(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast<MapPages>(GetProcAddress(xmem, "XMemMapPhysicalPages")); + const auto counts = reinterpret_cast<MapCounts>(GetProcAddress(xmem, "x2w_xmem_map_counts")); + if (!require(reserve && alloc && map && counts, "find the xmem exports")) return 1; + auto* const pool = static_cast<BYTE*>(reserve(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!require(pool != nullptr, "reserve XMem addresses")) return 1; + ULONG_PTR grants[pages]{}, count = pages; + if (!require(alloc(0x280, &count, grants) && count == pages, "allocate the pages")) return 1; + + // N single-page maps, each into the middle of the reservation's placeholder (every other page, so no two + // targets are neighbours). + ULONGLONG maps0 = 0, splits0 = 0, maps1 = 0, splits1 = 0; + if (!require(counts(&maps0, &splits0), "read the map counts")) return 1; + for (ULONG_PTR i = 0; i < pages; ++i) { + BYTE* const target = pool + (16 + 2 * i) * page_bytes; + if (!require(map(target, 1, &grants[i]) == target, "map one page into the reservation")) return 1; + target[0] = static_cast<BYTE>(0x40 + i); + target[page_bytes - 1] = static_cast<BYTE>(0x40 + i); + } + if (!require(counts(&maps1, &splits1), "read the map counts")) return 1; + const ULONGLONG maps = maps1 - maps0, splits = splits1 - splits0; + std::printf("%llu single-page maps: map attempts %llu, split attempts %llu\n", static_cast<unsigned long long>(pages), + maps, splits); + for (ULONG_PTR i = 0; i < pages; ++i) { + const BYTE* const target = pool + (16 + 2 * i) * page_bytes; + if (!require(target[0] == 0x40 + i && target[page_bytes - 1] == 0x40 + i, "each mapped page keeps its bytes")) + return 1; + } + MEMORY_BASIC_INFORMATION gap{}; + VirtualQuery(pool + 17 * page_bytes, &gap, sizeof(gap)); + if (!require(gap.State == MEM_RESERVE, "the page between two targets stays reserved")) return 1; + if (control) { + if (maps == 2 * pages && splits == pages) { + std::puts("map-first control: maps=2N"); + return 1; // CTest passes the control on the line above, not on the exit code + } + std::printf("FAIL: map-first control measured %llu maps for %llu pages\n", maps, + static_cast<unsigned long long>(pages)); + return 1; + } + if (!require(maps == pages && splits == pages, "split-first: one map attempt and one split per page")) return 1; + + // An exact placeholder: unmap the first page (the placeholder is kept), then map a page there again. No split. + BYTE* const first = pool + 16 * page_bytes; + if (!require(map(first, 1, nullptr) == first, "unmap the first page")) return 1; + MEMORY_BASIC_INFORMATION hole{}; + VirtualQuery(first, &hole, sizeof(hole)); + std::printf("after unmap: state 0x%lx base %p allocation %p size 0x%llx\n", hole.State, hole.BaseAddress, + hole.AllocationBase, static_cast<unsigned long long>(hole.RegionSize)); + if (!require(counts(&maps0, &splits0), "read the map counts") || + !require(map(first, 1, &grants[0]) == first, "map a page into the exact placeholder") || + !require(counts(&maps1, &splits1), "read the map counts")) + return 1; + std::printf("exact placeholder: map attempts %llu, split attempts %llu\n", maps1 - maps0, splits1 - splits0); + if (!require(maps1 - maps0 == 1 && splits1 - splits0 == 0, "an exact placeholder is mapped without a split") || + !require(first[0] == 0x40, "the remapped page reads its bytes")) + return 1; + std::puts("split-first: maps=N; exact placeholder mapped without a split"); + if (deployed) std::puts("deployed build: X2W_XMEM_TEST_MAP_FIRST=1 was ignored"); + return 0; +} diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index e89264236e..16071992de 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -2,8 +2,10 @@ // Adjacent pages of one mapping call share a view, so a buffer can lie inside one view or across // two: two mapping calls next to each other, the boundary between two backing sections inside one // call, or pages that each have a view of their own. The device wrapper's placed-resource entry -// (slot 133) must accept all of them alike and leave the memory as it was. -// usage: xmem_page_runs_device_check warp|hardware +// (slot 133) must accept all of them alike and leave the memory as it was. With `join`, X2W_XMEM_JOIN_CALLS=1 as +// well: a mapping call may then join the view that ends at its address, and the mapping order below keeps every +// boundary in place all the same. Without it the switch is cleared. +// usage: xmem_page_runs_device_check warp|hardware [join] #include "xmem_test_device.h" #include <cstring> @@ -76,11 +78,13 @@ void place(const char* name, ID3D12Device* wrapper, unsigned char* boundary, int int main(int argc, char** argv) { - if (argc != 2) return 1; + if (argc != 2 && !(argc == 3 && std::strcmp(argv[2], "join") == 0)) return 1; const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool join = argc == 3; bool unmatched = false; SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); // the mode under test; read by the first mapping call + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", join ? L"1" : nullptr); auto wrapper = create_device(warp, unmatched, create_wrapper); if (!wrapper) return warp || unmatched ? 1 : 77; @@ -88,11 +92,15 @@ int main(int argc, char** argv) if (!whole) return 1; unsigned char* const first = whole + page; - // Two mapping calls next to each other: two views that meet at first + 8 pages. + // Two mapping calls next to each other: two views that meet at first + 8 pages. The upper one is mapped first: with + // X2W_XMEM_JOIN_CALLS=1 a call joins only a view that ends at its address (merge_with_previous), never one that + // starts after it. const auto a = pages(8), b = pages(8); - if (a.empty() || b.empty() || XMemMapPhysicalPages(first, 8, a.data()) != first || - XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page) + if (a.empty() || b.empty() || XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page || + XMemMapPhysicalPages(first, 8, a.data()) != first) { + std::printf("check_failed: allocate or map the two 8-page calls (error %lu)\n", GetLastError()); return 1; + } place("inside one view", wrapper.Get(), first + 4 * page, 1); place("across two mapping calls", wrapper.Get(), first + 8 * page, 2); @@ -107,12 +115,20 @@ int main(int argc, char** argv) } place("across two backing sections", wrapper.Get(), second + info.RegionSize, 2); - // Pages mapped one call at a time get a view each: the layout every page had before views were shared. + // Pages mapped one call at a time get a view each. They are mapped from high to low addresses: with + // X2W_XMEM_JOIN_CALLS=1 no call then has an adjacent view below it to join, regardless of the order in which the + // allocator assigned the backing slots. unsigned char* const third = second + 8192 * page; const auto single = pages(8); - if (single.empty()) return 1; - for (int i = 0; i < 8; ++i) - if (XMemMapPhysicalPages(third + i * page, 1, &single[i]) != third + i * page) return 1; + if (single.empty()) { + std::printf("check_failed: allocate 8 single pages (error %lu)\n", GetLastError()); + return 1; + } + for (int i = 7; i >= 0; --i) + if (XMemMapPhysicalPages(third + i * page, 1, &single[7 - i]) != third + i * page) { + std::printf("check_failed: single-page call %d (error %lu)\n", i, GetLastError()); + return 1; + } place("across two single-page views", wrapper.Get(), third + 4 * page, 2); if (failures) { diff --git a/tests/xmem_page_stats_check.py b/tests/xmem_page_stats_check.py index 85a2d26011..73c46271f4 100644 --- a/tests/xmem_page_stats_check.py +++ b/tests/xmem_page_stats_check.py @@ -50,8 +50,8 @@ def slabs(): def snapshot(stage, expected, slab_counts): actual = sections() assert actual == expected, f"{stage}: {actual} live sections, expected {expected}" - # (slabs open, slots in use, slots free). A slab holds 4096 slots and stays open after its slots are - # freed, so the pages in use are the slots in use. + # (slabs open, slots in use, slots free). A slab holds 4096 slots, stays open while any slot is live, + # and is closed once all of its slots are released. counts = slabs() assert counts == slab_counts, f"{stage}: slabs, in use, free = {counts}, expected {slab_counts}" assert counts[1] == actual, f"{stage}: {counts[1]} slots in use but {actual} pages hold a slot" @@ -69,7 +69,7 @@ def snapshot(stage, expected, slab_counts): assert allocate(PHYSICAL_64K, C.byref(count), pages) and count.value == 3 snapshot("after the grant", 0, (0, 0, 0)) - # Mapping two pages backs them with two 64 KiB sections. + # Mapping two pages backs them with two 64 KiB slots of one slab. one, other = number(pages[0]), number(pages[1]) assert contiguous(first, 1, C.byref(one)) == first assert contiguous(second, 1, C.byref(other)) == second @@ -80,24 +80,24 @@ def snapshot(stage, expected, slab_counts): assert contiguous(second, 1, None) == second snapshot("after unmapping", 2, (1, 2, 4094)) + # A second grant backed by a page-token write shares the same slab. + extra_count, extra_pages = number(1), (number * 1)() + assert allocate(PHYSICAL_64K, C.byref(extra_count), extra_pages) and extra_count.value == 1 + token = number(extra_pages[0] << 4) + assert write_physical(C.byref(token), 1, 0, b"section", len(b"section")) + snapshot("write through page tokens", 3, (1, 3, 4093)) + + # Releasing the first grant leaves the slab open while the second grant still holds a slot. assert release(3, pages) - # The slab stays open: its commit is not given back. - snapshot("after releasing the grant", 0, (1, 0, 4096)) + snapshot("after releasing first grant", 1, (1, 1, 4095)) + + # Releasing the last slot in the slab closes and reclaims it. + assert release(1, extra_pages) + snapshot("after releasing the written grant", 0, (0, 0, 0)) finally: free(first, 0, WIN_RELEASE) free(second, 0, WIN_RELEASE) - - # A decoded DirectStorage request backs its destination pages without mapping them. - count, pages = number(1), (number * 1)() - assert allocate(PHYSICAL_64K, C.byref(count), pages) and count.value == 1 - snapshot("second grant", 0, (1, 0, 4096)) - token = number(pages[0] << 4) - assert write_physical(C.byref(token), 1, 0, b"section", len(b"section")) - snapshot("write through page tokens", 1, (1, 1, 4095)) - assert release(1, pages) - snapshot("after releasing the written grant", 0, (1, 0, 4096)) - print("physical pages: grant=0 mapped=2 unmapped=2 released=0; page-token write created and released 1; " - "one slab stayed open with 4096 slots free") + print("physical pages: grant=0 mapped=2 unmapped=2 extra=1 first_released=1 all_released=0") if __name__ == "__main__": diff --git a/tests/xmem_physical_write_owner_check.py b/tests/xmem_physical_write_owner_check.py new file mode 100644 index 0000000000..b02284dd6b --- /dev/null +++ b/tests/xmem_physical_write_owner_check.py @@ -0,0 +1,215 @@ +"""Check that x2w_xmem_write_physical writes only into granted physical pages. + +A physical page gets its 64 KiB section on first use and loses it when its grant is released +(docs/startup-runtime.md), and a fresh grant reads as zero. A page-token write to a page nobody owns +must therefore be refused the way XMemMapPhysicalPages refuses it (FALSE, ERROR_INVALID_PARAMETER): +otherwise it leaves a section outside any grant, and the next grant of that page number maps the +written bytes instead of zeros. + +usage: xmem_physical_write_owner_check.py <xmem.dll> +Each case runs in a process of its own (--child <case>), so that its page numbers and the section +count start from a shim nothing else has used. +""" +import ctypes as C +import os +from pathlib import Path +import subprocess +import sys + +PAGE_BYTES = 65536 +PHYSICAL_64K = 0x20400000 +WIN_RESERVE = 0x2000 +RESERVE_PLACEHOLDER = 0x40000 +WIN_RELEASE = 0x8000 +NOACCESS = 1 +ERROR_INVALID_PARAMETER = 87 +CAPACITY_PAGES = 1 << 18 # era_physical::capacity_pages +CHUNK = 4096 +CHECKS_FAILED = 2 # exit code of a case that ran to its end with failed checks + + +def bind(library, name, args, result): + function = getattr(library, name) + function.argtypes, function.restype = args, result + return function + + +class Shim: + def __init__(self, path): + library = C.WinDLL(str(Path(path).resolve()), use_last_error=True, winmode=0x900) + kernel = C.WinDLL("kernelbase.dll", use_last_error=True) + pointer, number = C.c_void_p, C.c_size_t + self.pointer, self.number = pointer, number + self.stats = bind(library, "x2w_xmem_page_stats", [C.POINTER(C.c_ulonglong)], C.c_int) + self.allocate = bind(library, "XMemAllocatePhysicalPages", [number, C.POINTER(number), C.POINTER(number)], C.c_int) + self.release = bind(library, "XMemFreePhysicalPages", [number, C.POINTER(number)], C.c_int) + self.contiguous = bind(library, "XMemMapPhysicalPages", [pointer, number, C.POINTER(number)], pointer) + self.write_physical = bind(library, "x2w_xmem_write_physical", + [C.POINTER(number), number, number, C.c_char_p, number], C.c_int) + self.reserve = bind(kernel, "VirtualAlloc2", + [pointer, pointer, number, C.c_ulong, C.c_ulong, pointer, C.c_ulong], pointer) + self.free = bind(kernel, "VirtualFree", [pointer, number, C.c_ulong], C.c_int) + self.failures = 0 + + def check(self, condition, message): + if not condition: + self.failures += 1 + print(f" FAIL: {message}", flush=True) + + def sections(self): + value = C.c_ulonglong() + assert self.stats(C.byref(value)), "x2w_xmem_page_stats refused a valid snapshot" + return value.value + + def grant(self, count): + got, pages = self.number(count), (self.number * count)() + assert self.allocate(PHYSICAL_64K, C.byref(got), pages) and got.value == count, C.get_last_error() + return pages + + def write(self, tokens, offset, data): + """One page-token write. Returns its result and the last error it left.""" + array = (self.number * len(tokens))(*tokens) + C.set_last_error(0) + result = self.write_physical(array, len(tokens), offset, data, len(data)) + return bool(result), C.get_last_error() + + def accepted(self, what, tokens, offset, data): + ok, error = self.write(tokens, offset, data) + self.check(ok, f"{what}: a write to a granted page was refused (last error {error})") + + def refused(self, what, tokens, offset, data): + ok, error = self.write(tokens, offset, data) + self.check(not ok, f"{what}: the write was accepted") + self.check(ok or error == ERROR_INVALID_PARAMETER, + f"{what}: last error {error}, expected ERROR_INVALID_PARAMETER ({ERROR_INVALID_PARAMETER})") + + def live(self, what, expected): + actual = self.sections() + self.check(actual == expected, f"{what}: {actual} live sections, expected {expected}") + + def read(self, page, offset, size): + """Maps one granted page into a placeholder of its own and returns size bytes at offset.""" + base = self.reserve(self.pointer(-1), None, PAGE_BYTES, WIN_RESERVE | RESERVE_PLACEHOLDER, NOACCESS, None, 0) + assert base, C.get_last_error() + try: + token = self.number(page) + assert self.contiguous(base, 1, C.byref(token)) == base, C.get_last_error() + data = C.string_at(base + offset, size) + assert self.contiguous(base, 1, None) == base, C.get_last_error() + return data + finally: + self.free(base, 0, WIN_RELEASE) + + def grant_again(self, page): + """Grants pages until the registry issues this page number (page numbers are reused).""" + chunk = CHUNK + while chunk: + got, pages = self.number(chunk), (self.number * chunk)() + if not self.allocate(PHYSICAL_64K, C.byref(got), pages): + chunk //= 2 # fewer pages than that are left + elif page in pages: + return + raise AssertionError(f"page {page} was not granted") + + def reads_zero(self, what, page, offset): + data = self.read(page, offset, 5) + self.check(data == bytes(5), f"{what}: the page reads {data!r}, expected zeros") + + +def never_granted(shim): + """A page number that no grant has named yet.""" + held = shim.grant(1)[0] + page = held + 1 if held < CAPACITY_PAGES else 1 + shim.refused("never granted", [page << 4], 16, b"stale") + shim.live("never granted, after the refused write", 0) + shim.grant_again(page) + shim.reads_zero("never granted, first grant of the page", page, 16) + + +def released(shim): + """A granted page takes the write (control). After the release the same token is refused.""" + pages = shim.grant(1) + page = pages[0] + shim.accepted("control", [page << 4], 16, b"owned") + shim.live("control, after the write", 1) + data = shim.read(page, 16, 5) + shim.check(data == b"owned", f"control: the granted page reads {data!r}, expected b'owned'") + assert shim.release(1, pages), C.get_last_error() + shim.live("control, after the release", 0) + shim.refused("released", [page << 4], 16, b"stale") + shim.live("released, after the refused write", 0) + shim.grant_again(page) + shim.reads_zero("released, next grant of the page", page, 16) + + +def regrant(shim): + """Control: with no write in between, a page written under one grant reads zero under the next.""" + pages = shim.grant(1) + page = pages[0] + shim.accepted("control", [page << 4], 16, b"owned") + assert shim.release(1, pages), C.get_last_error() + shim.live("control, after the release", 0) + shim.grant_again(page) + shim.reads_zero("control, next grant of the page", page, 16) + + +def second_token(shim): + """Every token of a write is checked, not only the first.""" + first, second = shim.grant(1), shim.grant(1) + page, owned = first[0], second[0] + assert shim.release(1, first), C.get_last_error() + shim.refused("second token", [owned << 4, page << 4], 0, bytes(PAGE_BYTES) + b"stale") + shim.grant_again(page) + shim.reads_zero("second token, next grant of the page", page, 0) + + +def permissive(shim): + """X2W_XMEM_PERMISSIVE=1, the mode the DirectStorage stand-in runs in: grants are page tokens.""" + tokens = shim.grant(1) + token = tokens[0] + assert token and not token & 0xF, f"the permissive grant {token:#x} is not a page token" + shim.accepted("permissive control", [token], 16, b"owned") + data = shim.read(token, 16, 5) + shim.check(data == b"owned", f"permissive control: the granted page reads {data!r}, expected b'owned'") + assert shim.release(1, tokens), C.get_last_error() + shim.refused("permissive, released", [token], 16, b"stale") + shim.live("permissive, after the refused write", 0) + + +CASES = {"never-granted": (never_granted, {}), "released": (released, {}), "regrant": (regrant, {}), + "second-token": (second_token, {}), "permissive": (permissive, {"X2W_XMEM_PERMISSIVE": "1"})} + + +def child(path, case): + shim = Shim(path) + CASES[case][0](shim) + return CHECKS_FAILED if shim.failures else 0 + + +def main(path): + failed = [] + for case, (_, environment) in CASES.items(): + env = dict(os.environ) + env.pop("X2W_XMEM_PERMISSIVE", None) + env.update(environment) + result = subprocess.run([sys.executable, "-B", __file__, "--child", case, str(path)], capture_output=True, + text=True, timeout=60, env=env) + if result.returncode == 0: + print(f"{case}: ok") + continue + failed.append(case) + print(f"{case}: FAIL (exit code {result.returncode & 0xFFFFFFFF:#x})") + print(result.stdout.rstrip() or " (no output)") + if result.returncode != CHECKS_FAILED: # the case did not get to its end + print(result.stderr.rstrip()[-800:]) + if failed: + print(f"xmem_physical_write_owner: FAIL ({len(failed)} of {len(CASES)} cases: {', '.join(failed)})") + return 1 + print(f"xmem_physical_write_owner: PASS ({len(CASES)} cases)") + return 0 + + +if __name__ == "__main__": + if sys.argv[1] == "--child": + sys.exit(child(sys.argv[3], sys.argv[2])) + sys.exit(main(sys.argv[1])) diff --git a/tests/xmem_placeholder_split_check.cpp b/tests/xmem_placeholder_split_check.cpp new file mode 100644 index 0000000000..e1ce8d7dae --- /dev/null +++ b/tests/xmem_placeholder_split_check.cpp @@ -0,0 +1,189 @@ +// Queue slot 31 (X2WMapPageBatch) into the middle of an XMem reservation needs a placeholder split. Where the region +// query does not report placeholders (Wine), xmem probes whether a placeholder release refuses a plain reservation +// and then offers reserved regions to the split (xmem placeholder_fallback). +// xmem_placeholder_split_check <xmem.dll> split succeeds; a committed target still fails and stays intact +// xmem_placeholder_split_check <xmem.dll> control the same checks in the test-controls build (X2W_XMEM_TEST_CONTROLS) +// with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1; CTest expects the +// split step to fail +// xmem_placeholder_split_check <xmem.dll> deployed the same checks in the deployed build with the same switch, which +// that build ignores, so they pass +// xmem_placeholder_split_check <xmem.dll> partial test-controls build with shared views: a two-page view over a +// private reservation whose second page is committed is refused +// by the region walk (x2w_xmem_alias_counts), and the committed +// page keeps its bytes; prints where its allocation starts after +// the batch (the limit in alias_placeholders) +// control, deployed and partial exit 77 where the OS reports the bit, because there the fallback is never used. Each +// mode sets or clears X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK itself, so an inherited value cannot change the result. +#include <windows.h> +#include "xmem_page_batch.h" +#include <cstdio> +#include <cstring> +#include <cwchar> + +namespace { +constexpr SIZE_T page_bytes = 65536; +constexpr UINT pool_pages = 4; +using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +using Scatter = BOOL (WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); +using AliasCounts = BOOL (WINAPI*)(ULONGLONG*, ULONGLONG*); + +bool require(bool ok, const char* step) +{ + if (!ok) std::printf("FAIL: %s (last error %lu)\n", step, GetLastError()); + return ok; +} + +bool os_reports_placeholder_bit() +{ + void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, nullptr, 0); + if (!probe) return false; + WIN32_MEMORY_REGION_INFORMATION info{}; + const bool bit = QueryVirtualMemoryInformation(GetCurrentProcess(), probe, MemoryRegionInfo, &info, sizeof(info), + nullptr) && (info.Flags & 0x100); + VirtualFree(probe, 0, MEM_RELEASE); + return bit; +} + +MEMORY_BASIC_INFORMATION query(const BYTE* pointer) +{ + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(pointer, &info, sizeof(info)); + return info; +} + +// Where the region's allocation starts, in pages from `at` (negative: before it). +long long base_pages(const MEMORY_BASIC_INFORMATION& info, const BYTE* at) +{ + return (static_cast<const BYTE*>(info.AllocationBase) - at) / static_cast<long long>(page_bytes); +} + +// partial: two pages of the reservation become a private reservation whose second page is committed and tagged. Its +// first region is reserved, so a check of that region alone would accept the whole two-page view. +int partial_case(HMODULE xmem, BYTE* pool, decltype(&X2WMapPageBatch) batch_map) +{ + const auto counts = reinterpret_cast<AliasCounts>(GetProcAddress(xmem, "x2w_xmem_alias_counts")); + ULONGLONG refusals0 = 0, splits0 = 0, refusals1 = 0, splits1 = 0; + if (!require(counts && counts(&refusals0, &splits0), "read the alias counts (test-controls build)")) return 1; + BYTE* const piece = pool + 192 * page_bytes; + if (!require(VirtualFree(piece, 2 * page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split out two pages") || + !require(VirtualAlloc2(GetCurrentProcess(), piece, 2 * page_bytes, MEM_RESERVE | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == piece, "reserve the two pages privately") || + !require(VirtualAlloc(piece + page_bytes, page_bytes, MEM_COMMIT, PAGE_READWRITE) == piece + page_bytes, + "commit the second page")) + return 1; + std::memset(piece + page_bytes, 0x7a, page_bytes); + const MEMORY_BASIC_INFORMATION before = query(piece + page_bytes); + if (!require(before.AllocationBase == piece, "the two pages are one allocation")) return 1; + const X2WPageRange two{0, 1, 2}; + const X2WPageBatch onto_partial{reinterpret_cast<UINT64>(piece), 1, &two}; + const HRESULT hr = batch_map(1, &onto_partial, reinterpret_cast<UINT64>(pool), pool_pages, 0, nullptr); + if (!require(counts(&refusals1, &splits1), "read the alias counts")) return 1; + const MEMORY_BASIC_INFORMATION first = query(piece), second = query(piece + page_bytes); + std::printf("batch onto a reserved page and a committed one -> 0x%08lx; alias refusals %llu, placeholder " + "releases tried %llu; after: state 0x%lx type 0x%lx, then state 0x%lx type 0x%lx byte 0x%02x\n", + static_cast<unsigned long>(hr), refusals1 - refusals0, splits1 - splits0, first.State, first.Type, + second.State, second.Type, second.State == MEM_COMMIT ? piece[page_bytes] : 0u); + std::printf("allocation base in pages from the first page: first page %+lld (region %llu pages); committed page " + "%+lld before the batch, %+lld after\n", + base_pages(first, piece), static_cast<unsigned long long>(first.RegionSize / page_bytes), + base_pages(before, piece), base_pages(second, piece)); + // The walk refuses the two-page view. The batch then retries each page on its own (install_alias_plan): the + // reserved page alone is accepted, released and mapped, and the rollback unmaps it again; the committed page alone + // is refused. A walk that checks only the first region of each allocation accepts the view, and under Wine the + // release then succeeds and the view replaces the committed page (measured 2026-11-27 before the fix). + // Limit: the fallback cannot tell a reserved page of a private allocation made in place of a placeholder + // (MEM_REPLACE_PLACEHOLDER) from a placeholder. Under Wine the per-page release cuts that page out of the caller's + // allocation: afterwards the committed page's allocation starts one page later (measured 2026-11-27). The row + // asserts only that the first page is still one reserved page with its own address as its allocation base, and + // prints where the committed page's allocation starts. + if (!require(refusals1 - refusals0 >= 1, "the region walk refuses the two-page view") || + !require(FAILED(hr), "the partly committed target is refused") || + !require(first.State == MEM_RESERVE && first.AllocationBase == piece && first.RegionSize == page_bytes && + second.State == MEM_COMMIT && second.Type == MEM_PRIVATE && piece[page_bytes] == 0x7a && + piece[2 * page_bytes - 1] == 0x7a, + "the committed page keeps its bytes and the first page stays one reserved page at its address")) + return 1; + if (second.AllocationBase != piece) + std::puts("limit: the per-page retry cut the reserved page out of the caller's allocation " + "(docs/experiments/xmem-page-runs.md)"); + std::puts("partial: a view over a reserved and a committed page was refused; the committed page kept its bytes"); + return 0; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; + const bool partial = argc == 3 && std::wcscmp(argv[2], L"partial") == 0; + if (argc != 2 && !control && !deployed && !partial) return 2; + // xmem reads the switch once, in its first placeholder probe; set it before loading xmem.dll. + SetEnvironmentVariableW(L"X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK", control || deployed ? L"1" : nullptr); + if (partial) { + // A two-page view needs shared views (one view per run of pool pages); joins across calls stay off. + SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", nullptr); + } + const bool bit = os_reports_placeholder_bit(); + std::printf("placeholder bit reported=%d\n", bit); + if ((control || deployed || partial) && bit) { + std::puts("SKIP: the OS reports the placeholder bit, so the fallback is never used"); + return 77; + } + const HMODULE xmem = LoadLibraryW(argv[1]); + if (!require(xmem != nullptr, "load xmem.dll")) return 1; + const auto reserve = reinterpret_cast<Reserve>(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto alloc = reinterpret_cast<AllocPages>(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto scatter = reinterpret_cast<Scatter>(GetProcAddress(xmem, "XMemMapPhysicalPagesScatter")); + const auto batch_map = reinterpret_cast<decltype(&X2WMapPageBatch)>(GetProcAddress(xmem, "X2WMapPageBatch")); + if (!require(reserve && alloc && scatter && batch_map, "find the xmem exports")) return 1; + + auto* const pool = static_cast<BYTE*>(reserve(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!require(pool != nullptr, "reserve XMem addresses")) return 1; + ULONG_PTR grants[pool_pages]{}, count = pool_pages; + void* addresses[pool_pages]{}; + for (UINT i = 0; i < pool_pages; ++i) addresses[i] = pool + i * page_bytes; + if (!require(alloc(0x280, &count, grants) && count == pool_pages, "allocate the pool") || + !require(scatter(addresses, pool_pages, grants), "map the pool")) + return 1; + for (UINT i = 0; i < pool_pages; ++i) std::memset(addresses[i], 0x51 + i, page_bytes); + if (partial) return partial_case(xmem, pool, batch_map); + + // Negative control: a committed page inside the reservation is not a placeholder. The batch must fail and leave + // the page committed with its bytes. + BYTE* const committed = pool + 64 * page_bytes; + if (!require(VirtualFree(committed, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split out a page") || + !require(VirtualAlloc2(GetCurrentProcess(), committed, page_bytes, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == committed, "commit that page")) + return 1; + std::memset(committed, 0x77, page_bytes); + const X2WPageRange one{0, 0, 1}; + const X2WPageBatch onto_committed{reinterpret_cast<UINT64>(committed), 1, &one}; + const HRESULT refused = batch_map(1, &onto_committed, reinterpret_cast<UINT64>(pool), pool_pages, 0, nullptr); + std::printf("batch onto a committed page -> 0x%08lx\n", static_cast<unsigned long>(refused)); + // The code is the OS's map failure: Windows 487, Wine 87 (measured 2026-11-26). + if (!require(FAILED(refused), "a committed target is refused") || + !require(query(committed).State == MEM_COMMIT && committed[0] == 0x77 && committed[page_bytes - 1] == 0x77, + "the committed target keeps its bytes")) + return 1; + + // The split: pool pages 1 and 2 into the middle of an untouched part of the reservation. + BYTE* const window = pool + 128 * page_bytes; + const X2WPageRange two{0, 1, 2}; + const X2WPageBatch split{reinterpret_cast<UINT64>(window + page_bytes), 1, &two}; + const HRESULT hr = batch_map(1, &split, reinterpret_cast<UINT64>(pool), pool_pages, 0, nullptr); + std::printf("batch into the middle of the reservation -> 0x%08lx\n", static_cast<unsigned long>(hr)); + if (!require(SUCCEEDED(hr), "map two pool pages into the middle of the reservation") || + !require(window[page_bytes] == 0x52 && window[2 * page_bytes] == 0x53 && window[3 * page_bytes - 1] == 0x53, + "the destination reads the pool pages") || + !require(query(window).State == MEM_RESERVE && query(window + 3 * page_bytes).State == MEM_RESERVE, + "the neighbours stay reserved")) + return 1; + window[page_bytes] = 0x60; + if (!require(pool[page_bytes] == 0x60, "a write through the destination reaches the pool page")) return 1; + std::puts("slot31 split inside an XMem reservation matched; a committed target was refused and kept"); + if (deployed) std::puts("deployed build: X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 was ignored"); + return 0; +} diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp new file mode 100644 index 0000000000..3f1767ab66 --- /dev/null +++ b/tests/xmem_run_break_readers_check.cpp @@ -0,0 +1,897 @@ +// Readers that do not fault, inside a run break of the shared-view mode (X2W_XMEM_SHARED_VIEWS=1). Unmapping one +// page of a run unmaps the whole run, then maps its other pages again (src/xmem_mapped_pages.cpp, map_pages_locked). +// A thread that touches one of those pages in between faults and is retried; a region query or a kernel copy does +// not fault, so it reads the pages as reserved or fails. Each case below opens that window with the test-controls +// build's X2W_XMEM_TEST_HOLD_WINDOW, proves it is open with a raw VirtualQuery of a neighbour page (not committed), +// starts the reader under test on another thread, checks that it has not answered 300 ms later, releases the window +// and then checks the reader's answer: the neighbour page is committed, mapped and holds its data. +// +// Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, this program's VirtualQueryEx import (wrapped by +// xmem.dll when it loads with the switch), this program's ReadFile and WriteFile imports (synchronous, into and out +// of the page; wrapped the same way), a ReadFile from an anonymous pipe into the page (not run again: it fails inside +// the window), x2w_local::writable, x2w_startup::measure_placed_buffer and x2w_startup::snapshot_samplers. Then +// io_outside_runs: a ReadFile into a reserved page in no run fails at once. +// +// With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run +// directly) the three header readers answer inside the window: the check expects that, and fails if they wait. +// +// Then a page that faults in two breaks in a row (retry_remapped_page): a thread faults on a page of a run taken +// apart by break A, and the test build's X2W_XMEM_TEST_HOLD_RETRY holds the handler until break A has ended, so the +// handler finds the page mapped again and looks up the stamp break A left on the run; the thread is retried and reads +// its page. Break B then takes the same page apart and stamps the run again, and the thread faults on it again: that +// fault must be retried as well (a different stamp). With `next-break-control` the handler is not held, so it sees +// break A in progress and waits for memory.mutex before the lookup: that order passes even when the handler's check +// of a fault after its break has ended is wrong, which shows the hold is what this case depends on. +// +// A fault whose handler looks the page up only after a later break on another run has begun (two_runs: break B on a +// disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) +// must be retried as well: the page's run keeps the stamp of the break that mapped it again, whatever breaks follow on +// other runs. Joins across calls need X2W_XMEM_JOIN_CALLS=1: main sets it for `mirror` and clears it for every other +// mode. +// +// Many later breaks (later_breaks): a held fault in break A whose handler runs after 63, 64 or 200 later breaks on +// another page is retried each time (the reader's own __except would catch a fault passed on). A fault that stays +// (persistent_fault, a page of a run made no-access): passed on at once when no break mapped the run, and after one +// retry when one did; a first-chance handler of the test counts the faults. +// +// A break that begins while x2w_xmem_stable_call's fn runs (break_during_fn): fn itself starts the unmap, waits until +// the window is open and queries a page of the run (reserved). stable_call must see the generation change and run fn +// again under memory.mutex: 2 calls, the last one committed. +// +// `default` (X2W_XMEM_SHARED_VIEWS unset): every page has a view of its own, and readers that overlap an unmap +// answer inside it, without waiting for memory.mutex, as before x2w_xmem_stable_call. +// `lazy` (X2W_XMEM_SHARED_VIEWS=1, X2W_XMEM_LAZY_COMMIT=1): XMemVirtualQuery and VirtualQueryEx wait for a break +// with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. Then a +// ReadFile into another such slot, with no break: the lazy-commit ReadFile wrapper still runs inside the run-break one. +// +// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process); `stamps` runs +// later_breaks with 63, 64 and 200 later breaks, then persistent_fault. +// +// Usage: xmem_run_break_readers_check <xmem.dll built with its test controls> +// [control|next-break-control|default|lazy|two-runs|mirror|stamps] +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include <windows.h> + +#include <d3d12.h> + +#include "startup_stubs/local_log.h" +#include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/translated_sampler_bindings.h" + +#include <atomic> +#include <cstdio> +#include <cstring> +#include <functional> +#include <thread> + +namespace { +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*, SIZE_T*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, SIZE_T, SIZE_T*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*); +using XMemVirtualQueryFn = BOOL(WINAPI*)(HANDLE, LPCVOID, void*); +using StableCallFn = BOOL(WINAPI*)(void (*)(void*), void*); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T pages = 8; +constexpr SIZE_T broken_page = 5; // the page unmapped; its run [0, 8) is taken apart +constexpr SIZE_T neighbour = 2; // a surviving page of that run, unmapped while the window is held + +int failures = 0; + +bool check(bool ok, const char* name, const char* reader) +{ + std::printf("%s: %s %s\n", ok ? "ok" : "check_failed", reader, name); + if (!ok) ++failures; + return ok; +} + +DWORD raw_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +struct Shim { + XMemVirtualAllocFn virtual_alloc; + XMemAllocatePhysicalPagesFn allocate; + XMemMapPhysicalPagesFn map; + XMemFreePhysicalPagesFn release; + XMemVirtualQueryFn query; + StableCallFn stable_call; +}; + +// One window: maps a fresh run of eight pages at base, marks every page, unmaps broken_page on a thread of its own +// with the hold set, and runs reader on another thread once the window is open. reader returns whether its answer +// says the neighbour page is committed and readable. waits: the reader must not answer before the release. +void window_case(const Shim& shim, unsigned char* base, int index, const char* name, bool waits, + const std::function<bool(unsigned char*)>& reader) +{ + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast<std::uint32_t*>(base + i * page) = 0x51000000u + static_cast<std::uint32_t>(i); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-readers-%lu-%d", GetCurrentProcessId(), index); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + unsigned char* const broken = base + broken_page * page; + std::thread unmapper([&] { shim.map(broken, 1, nullptr); }); + const bool opened = WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0; + check(opened, "window_reached", name); + unsigned char* const target = base + neighbour * page; + if (opened) check(raw_state(target) != MEM_COMMIT, "window_open_raw_query_not_committed", name); + std::atomic<bool> started{false}, answered{false}; + bool answer = false; + std::thread reading([&] { + started = true; + answer = reader(target); + answered = true; + }); + for (int i = 0; i < 10000 && !started.load(); ++i) Sleep(1); // the 300 ms count from the reader's start + Sleep(300); + const bool early = answered.load(); + check(waits ? !early : early, waits ? "reader_waits_for_the_break" : "reader_answers_inside_the_window", name); + SetEvent(release); + reading.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(waits ? answer : !answer, waits ? "answer_after_the_break_committed" : "answer_inside_the_window_not_committed", name); + check(*reinterpret_cast<std::uint32_t*>(target) == 0x51000000u + neighbour, "neighbour_data_kept", name); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} +// fn starts the unmap and waits for the window inside x2w_xmem_stable_call. +void break_during_fn(const Shim& shim, unsigned char* base) +{ + const char* const name = "break_during_fn"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + struct Context { + const Shim* shim; + unsigned char* base; + char hold[64]; + HANDLE unmapped, release; + std::thread unmapper, releaser; + int calls = 0; + DWORD first = 0, last = 0; + bool opened = false; + } c{&shim, base, {}, nullptr, nullptr}; + std::snprintf(c.hold, sizeof(c.hold), "x2w-run-break-during-fn-%lu", GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", c.hold); + c.unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", c.hold); + c.release = CreateEventA(nullptr, TRUE, FALSE, event_name); + shim.stable_call([](void* context) { + auto& c = *static_cast<Context*>(context); + if (++c.calls == 1) { + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", c.hold); + c.unmapper = std::thread([&c] { c.shim->map(c.base + broken_page * page, 1, nullptr); }); + c.opened = WaitForSingleObject(c.unmapped, 10000) == WAIT_OBJECT_0; + c.first = raw_state(c.base + neighbour * page); + c.releaser = std::thread([&c] { // stable_call waits for memory.mutex until the window is released + Sleep(100); + SetEvent(c.release); + }); + } + c.last = raw_state(c.base + neighbour * page); + }, &c); + c.unmapper.join(); + c.releaser.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(c.opened, "window_reached", name); + check(c.first != MEM_COMMIT, "first_call_inside_the_window_not_committed", name); + check(c.calls == 2, "fn_ran_again_after_the_break", name); + check(c.last == MEM_COMMIT, "answer_after_the_break_committed", name); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(c.unmapped); + CloseHandle(c.release); +} + +// Kernel I/O into or out of a page of the run: this program's ReadFile and WriteFile imports (wrapped by xmem.dll +// when it loads with the switch). Synchronous calls on a file opened without FILE_FLAG_OVERLAPPED. +constexpr DWORD io_bytes = 4096; + +struct TempFile { + char path[MAX_PATH] = {}; + explicit TempFile(const char* stem) + { + char dir[MAX_PATH]; + GetTempPathA(sizeof(dir), dir); + std::snprintf(path, sizeof(path), "%sx2w-run-break-%s-%lu.bin", dir, stem, GetCurrentProcessId()); + } + ~TempFile() { DeleteFileA(path); } + HANDLE open(DWORD access, DWORD disposition) const + { + return CreateFileA(path, access, 0, nullptr, disposition, FILE_ATTRIBUTE_NORMAL, nullptr); + } +}; + +// The file's bytes: the neighbour page's mark, then 0xa5. +void io_pattern(unsigned char* out) +{ + std::memset(out, 0xa5, io_bytes); + const std::uint32_t mark = 0x51000000u + neighbour; + std::memcpy(out, &mark, sizeof(mark)); +} + +bool read_file_into(unsigned char* target) +{ + TempFile file("read"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE, CREATE_ALWAYS); + DWORD done = 0; + const bool written = h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && done == io_bytes; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + if (!written) return false; + h = file.open(GENERIC_READ, OPEN_EXISTING); + if (h == INVALID_HANDLE_VALUE) return false; + done = 0; + const BOOL ok = ReadFile(h, target, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + LARGE_INTEGER position{}; + SetFilePointerEx(h, LARGE_INTEGER{}, &position, FILE_CURRENT); + CloseHandle(h); + std::printf("ReadFile into the run: ok=%d bytes=%lu error=%lu position=%lld\n", ok, done, error, position.QuadPart); + return ok && done == io_bytes && std::memcmp(target, data, io_bytes) == 0; +} + +bool write_file_from(unsigned char* target) +{ + TempFile file("write"); + HANDLE h = file.open(GENERIC_WRITE, CREATE_ALWAYS); + if (h == INVALID_HANDLE_VALUE) return false; + DWORD done = 0; + const BOOL ok = WriteFile(h, target, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + CloseHandle(h); + std::printf("WriteFile from the run: ok=%d bytes=%lu error=%lu\n", ok, done, error); + if (!ok || done != io_bytes) return false; + unsigned char data[io_bytes]; + h = file.open(GENERIC_READ, OPEN_EXISTING); + const bool read = h != INVALID_HANDLE_VALUE && ReadFile(h, data, io_bytes, &done, nullptr) && done == io_bytes; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + return read && std::memcmp(data, target, io_bytes) == 0; +} + +// An anonymous pipe with two 4096-byte messages queued, read into the page inside the window. The wrapper runs a +// failed call again only on a disk file, so this one fails inside the window instead of waiting for the break. Its +// error must be one the wrapper retries on a disk file, or answering at once would show nothing. Measured under Wine +// (Proton Experimental, 2026-11): ERROR_NOACCESS inside the window, both messages still queued. A pipe read into a +// mapped page of a run fails there even outside a break (ERROR_INVALID_USER_BUFFER), while one into a VirtualAlloc +// buffer reads the first message, so a retry after the break would not have read it either. +struct PipeRead { + BOOL ok = FALSE; + DWORD bytes = 0, error = 0, queued_before = 0, queued_after = 0; + bool second_message = false; // the bytes read are the second message's +} pipe_read; + +bool read_pipe_into(unsigned char* target) +{ + HANDLE r = nullptr, w = nullptr; + if (!CreatePipe(&r, &w, nullptr, 16 * io_bytes)) return false; + unsigned char first[io_bytes], second[io_bytes]; + io_pattern(first); + std::memset(second, 0x5a, io_bytes); + DWORD done = 0; + const bool queued = WriteFile(w, first, io_bytes, &done, nullptr) && done == io_bytes && + WriteFile(w, second, io_bytes, &done, nullptr) && done == io_bytes; + PipeRead& p = pipe_read; + PeekNamedPipe(r, nullptr, 0, nullptr, &p.queued_before, nullptr); + p.ok = queued && ReadFile(r, target, io_bytes, &p.bytes, nullptr); + p.error = p.ok ? 0 : GetLastError(); + PeekNamedPipe(r, nullptr, 0, nullptr, &p.queued_after, nullptr); + p.second_message = p.ok && std::memcmp(target, second, io_bytes) == 0; + CloseHandle(r); + CloseHandle(w); + std::printf("ReadFile from a pipe into the run: ok=%d bytes=%lu error=%lu queued before %lu after %lu, second " + "message %d\n", p.ok, p.bytes, p.error, p.queued_before, p.queued_after, p.second_message); + return p.ok && p.bytes == io_bytes && std::memcmp(target, first, io_bytes) == 0; +} + +// A read into a reserved page that is in no run fails at once, as without the wrapper: nothing waits for it. +void io_outside_runs() +{ + const char* const name = "io_outside_runs"; + auto* const reserved = static_cast<unsigned char*>(VirtualAlloc(nullptr, page, MEM_RESERVE, PAGE_NOACCESS)); + if (!check(reserved != nullptr, "reserve", name)) return; + TempFile file("outside"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS); + DWORD done = 0; + if (!check(h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && + SetFilePointer(h, 0, nullptr, FILE_BEGIN) == 0, "temp_file", name)) { + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + VirtualFree(reserved, 0, MEM_RELEASE); + return; + } + const ULONGLONG from = GetTickCount64(); + const BOOL ok = ReadFile(h, reserved, io_bytes, &done, nullptr); + const DWORD error = GetLastError(); + const ULONGLONG took = GetTickCount64() - from; + CloseHandle(h); + VirtualFree(reserved, 0, MEM_RELEASE); + std::printf("ReadFile into a reserved page outside the runs: ok=%d error=%lu %llu ms\n", ok, error, took); + check(!ok && error == ERROR_NOACCESS, "read_into_reserved_page_fails_with_ERROR_NOACCESS", name); + check(took < 1000, "read_into_reserved_page_fails_at_once", name); +} + +// Default mode: eight single-page views; the unmap of page 5 is held open while readers query page 2. +void default_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "default"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map", name); + return; + } + unsigned char* const target = base + neighbour * page; + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(target, &info, sizeof(info)) && info.RegionSize == page, "one_view_per_page", name); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-default-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread unmapper([&] { shim.map(base + broken_page * page, 1, nullptr); }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0, "window_reached", name); + std::atomic<int> answered{0}; + DWORD stable = 0, xmem = 0; + bool writable = false; + std::thread reading([&] { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast<Query*>(context); + q.state = raw_state(q.target); + }, &query); + stable = query.state; + unsigned char buffer[64] = {}; + if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&xmem, buffer + 0x20, sizeof(xmem)); + writable = x2w_local::writable(target, 64); + answered = 1; + }); + for (int i = 0; i < 300 && !answered.load(); ++i) Sleep(10); + check(answered.load() == 1, "readers_answer_inside_the_unmap", name); + check(stable == MEM_COMMIT && xmem == MEM_COMMIT && writable, "answers_committed", name); + SetEvent(release); + reading.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} + +// Lazy commit: the output buffers lie in a mapped page whose slot is not committed until it is touched. +void lazy_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "lazy"; + SIZE_T count = pages, tokens[pages] = {}, out_count = 1, out_token = 0; + unsigned char* const out = base + 32 * page; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base || + !shim.allocate(0x20400000, &out_count, &out_token) || shim.map(out, 1, &out_token) != out) { + check(false, "map", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast<std::uint32_t*>(base + i * page) = 0x53000000u + static_cast<std::uint32_t>(i); + if (!check(raw_state(out) != MEM_COMMIT, "output_slot_not_committed_yet", name)) return; + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-lazy-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread unmapper([&] { shim.map(base + broken_page * page, 1, nullptr); }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0, "window_reached", name); + unsigned char* const target = base + neighbour * page; + BOOL xmem_ok = FALSE; + SIZE_T ex_bytes = 0; + auto* const ex_info = reinterpret_cast<MEMORY_BASIC_INFORMATION*>(out + 0x100); + std::atomic<int> answered{0}; + std::thread xmem_reader([&] { + xmem_ok = shim.query(GetCurrentProcess(), target, out); + ++answered; + }); + std::thread ex_reader([&] { + ex_bytes = VirtualQueryEx(GetCurrentProcess(), target, ex_info, sizeof(*ex_info)); + ++answered; + }); + Sleep(300); + check(answered.load() == 0, "readers_wait_for_the_break", name); + SetEvent(release); + xmem_reader.join(); + ex_reader.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + // The answers are the state after the break, read back from the slot they were written to. Measured under Wine: a + // slot committed lazily (through the slab) still reads as reserved in the title's view, and so does a page of the + // view mapped again after the break (its bytes are kept), so compare with a raw query taken now. + const DWORD after = raw_state(target); + DWORD xmem_state = 0; + std::memcpy(&xmem_state, out + 0x20, sizeof(xmem_state)); + std::printf("lazy: target 0x%lx after the break; XMemVirtualQuery %d 0x%lx; VirtualQueryEx %zu 0x%lx\n", + static_cast<unsigned long>(after), xmem_ok, static_cast<unsigned long>(xmem_state), + static_cast<std::size_t>(ex_bytes), static_cast<unsigned long>(ex_info->State)); + check(xmem_ok && xmem_state == after, "XMemVirtualQuery_answer_after_the_break_in_the_lazy_slot", name); + check(ex_bytes == sizeof(*ex_info) && ex_info->State == after, "VirtualQueryEx_answer_after_the_break_in_the_lazy_slot", name); + check(*reinterpret_cast<std::uint32_t*>(target) == 0x53000000u + neighbour, "neighbour_data_kept", name); + shim.map(out, 1, nullptr); + shim.release(1, &out_token); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} + +// Lazy commit and shared views: the ReadFile import goes through both wrappers. A read into a mapped slot that is not +// committed yet (no break around it) commits the slot first and succeeds, as with lazy commit alone. +void lazy_read_file(const Shim& shim, unsigned char* at) +{ + const char* const name = "lazy_read_file"; + SIZE_T count = 1, token = 0; + if (!check(shim.allocate(0x20400000, &count, &token) && shim.map(at, 1, &token) == at, "map", name)) return; + if (check(raw_state(at) != MEM_COMMIT, "slot_not_committed_yet", name)) { + TempFile file("lazy"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS); + DWORD done = 0; + const bool ready = h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && + SetFilePointer(h, 0, nullptr, FILE_BEGIN) == 0; + const BOOL ok = ready && ReadFile(h, at, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + std::printf("lazy: ReadFile into an uncommitted mapped slot: ok=%d error=%lu\n", ok, error); + check(ok && done == io_bytes && std::memcmp(at, data, io_bytes) == 0, "read_into_the_slot", name); + } + shim.map(at, 1, nullptr); + shim.release(1, &token); +} + +struct Events { + char name[64]; + HANDLE first, second; + Events(const char* stem, const char* a, const char* b) + { + std::snprintf(name, sizeof(name), "x2w-run-break-%s-%lu", stem, GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.%s", name, a); + first = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.%s", name, b); + second = CreateEventA(nullptr, TRUE, FALSE, event_name); + } + ~Events() + { + CloseHandle(first); + CloseHandle(second); + } +}; + +// Break A: unmap page 7 of a run of eight; break B: unmap page 6 of what is left, [0, 7). The reader's page 2 is in +// both. hold_retry: the handler for the fault in break A looks the page up only after A has ended. +void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) +{ + const char* const name = hold_retry ? "next_break" : "next_break_control"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast<std::uint32_t*>(base + i * page) = 0x52000000u + static_cast<std::uint32_t>(i); + unsigned char* const target = base + 2 * page; + Events window_a("a", "unmapped", "release"), window_b("b", "unmapped", "release"), retry("retry", "faulted", "go"); + HANDLE second_read = CreateEventA(nullptr, TRUE, FALSE, nullptr); + std::atomic<int> reads{0}; + std::uint32_t first_value = 0, second_value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_a.name); + std::thread unmap_a([&] { shim.map(base + 7 * page, 1, nullptr); }); + const bool a_open = WaitForSingleObject(window_a.first, 10000) == WAIT_OBJECT_0; + check(a_open, "break_a_held", name); + if (hold_retry) SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + first_value = *reinterpret_cast<volatile std::uint32_t*>(target); // faults in break A + ++reads; + WaitForSingleObject(second_read, 10000); + second_value = *reinterpret_cast<volatile std::uint32_t*>(target); // faults in break B + ++reads; + }); + if (hold_retry) { + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_break", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + } else { + Sleep(100); // the handler sees break A in progress and waits for memory.mutex + } + SetEvent(window_a.second); + unmap_a.join(); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + if (hold_retry) SetEvent(retry.second); // the handler now looks the page up after break A + for (int i = 0; i < 200 && reads.load() < 1; ++i) Sleep(10); + check(reads.load() == 1 && first_value == 0x52000002u, "first_fault_retried", name); + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_b.name); + std::thread unmap_b([&] { shim.map(base + 6 * page, 1, nullptr); }); + const bool b_open = WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0; + check(b_open && raw_state(target) != MEM_COMMIT, "break_b_held_page_not_committed", name); + SetEvent(second_read); + Sleep(300); + check(reads.load() == 1, "second_fault_waits_for_break_b", name); + SetEvent(window_b.second); + unmap_b.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(reads.load() == 2 && second_value == 0x52000002u, "second_fault_retried", name); + shim.map(base, 6, nullptr); + shim.release(pages, tokens); + CloseHandle(second_read); + if (!hold_retry) std::printf("next-break control: the handler ran while break A was open\n"); +} +// Break A takes apart run 1, break B (begun after A ended) run 2, a disjoint run. The handler for a fault in A is held +// (X2W_XMEM_TEST_HOLD_RETRY) until B is held open, so it looks the page up while B is in progress: it must still find +// the stamp of A on run 1 and retry the fault. A handler that knew only the last break's ranges passes the fault on, +// and the process ends with an access violation. +void two_runs_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "two_runs"; + unsigned char* const run1 = base; + unsigned char* const run2 = base + 16 * page; + SIZE_T count = 2 * pages, tokens[2 * pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != 2 * pages || shim.map(run1, pages, tokens) != run1 || + shim.map(run2, pages, tokens + pages) != run2) { + check(false, "map_runs", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) { + *reinterpret_cast<std::uint32_t*>(run1 + i * page) = 0x54000000u + static_cast<std::uint32_t>(i); + *reinterpret_cast<std::uint32_t*>(run2 + i * page) = 0x54100000u + static_cast<std::uint32_t>(i); + } + unsigned char* const target = run1 + 2 * page; + Events window_a("two-a", "unmapped", "release"), window_b("two-b", "unmapped", "release"), retry("two-retry", "faulted", "go"); + std::atomic<int> reads{0}; + std::uint32_t value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_a.name); + std::thread unmap_a([&] { shim.map(run1 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window_a.first, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, + "break_a_held_on_run_1", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + value = *reinterpret_cast<volatile std::uint32_t*>(target); // faults in break A + ++reads; + }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(window_a.second); + unmap_a.join(); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_b.name); + std::thread unmap_b([&] { shim.map(run2 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0 && raw_state(run2 + 2 * page) != MEM_COMMIT, + "break_b_held_on_run_2", name); + SetEvent(retry.second); // the handler looks the page up now, with B in progress + Sleep(100); + SetEvent(window_b.second); + unmap_b.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(reads.load() == 1 && value == 0x54000002u, "fault_in_break_a_retried_during_break_b", name); + check(*reinterpret_cast<std::uint32_t*>(run2 + 2 * page) == 0x54100002u, "run_2_data_kept", name); + shim.map(run1, 7, nullptr); + shim.map(run2, 7, nullptr); + shim.release(2 * pages, tokens); +} + +// The owner's configuration (X2W_XMEM_PERMISSIVE=1, X2W_XMEM_GPU_MIRROR=1, X2W_XMEM_JOIN_CALLS=1 from main): one +// XMemMapPhysicalPages call joins the CPU run, then the same pages' GPU mirror run, under one memory.mutex hold; the +// two breaks follow each other at once. A fault on the CPU run in the first break, whose handler is held until the GPU +// break is held open, must be retried. The release event is auto-reset, so each of the call's two holds waits for a +// release of its own. +void mirror_case(const Shim& shim, unsigned char* cpu) +{ + const char* const name = "mirror"; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", "1"); + auto* const gpu_view = static_cast<unsigned char*>(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 3, 0x800 | PAGE_NOACCESS)); + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", nullptr); + unsigned char* const at = cpu + page; + SIZE_T count = pages + 1, tokens[pages + 1] = {}; + if (!check(gpu_view != nullptr, "gpu_reservation", name) || + !check(shim.allocate(0x280, &count, tokens) && count == pages + 1 && shim.map(at, pages, tokens) == at, "map_run", name)) { + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + if (gpu_view) VirtualFree(gpu_view, 0, MEM_RELEASE); + return; + } + unsigned char* const twin = at - cpu + gpu_view; + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast<std::uint32_t*>(at + i * page) = 0x55000000u + static_cast<std::uint32_t>(i); + check(*reinterpret_cast<std::uint32_t*>(twin + 2 * page) == 0x55000002u, "gpu_twin_shows_the_cpu_page", name); + unsigned char* const target = at + 2 * page; + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-mirror-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, FALSE, FALSE, event_name); + Events retry("mirror-retry", "faulted", "go"); + std::atomic<int> reads{0}; + std::uint32_t value = 0; + bool mapped = false; + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread mapper([&] { mapped = shim.map(at + pages * page, 1, &tokens[pages]) == at + pages * page; }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, "cpu_merge_held", name); + ResetEvent(unmapped); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + value = *reinterpret_cast<volatile std::uint32_t*>(target); // faults in the CPU merge's break + ++reads; + }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(release); // the CPU merge ends; the GPU merge begins and holds + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(twin + 2 * page) != MEM_COMMIT && + raw_state(target) == MEM_COMMIT, "gpu_merge_held_after_the_cpu_merge", name); + SetEvent(retry.second); // the handler looks the page up now, with the GPU merge in progress + Sleep(100); + SetEvent(release); + mapper.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(mapped, "mapping_call_succeeded", name); + check(reads.load() == 1 && value == 0x55000002u, "fault_in_the_cpu_merge_retried_during_the_gpu_merge", name); + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(at, &info, sizeof(info)) && info.RegionSize == (pages + 1) * page && + VirtualQuery(twin, &info, sizeof(info)) && info.RegionSize == (pages + 1) * page, "both_views_joined", name); + shim.map(at, pages + 1, nullptr); + shim.release(pages + 1, tokens); + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + VirtualFree(gpu_view, 0, MEM_RELEASE); + CloseHandle(unmapped); + CloseHandle(release); +} + +// Reads *address into value; false when the access violation reaches this frame (the handler passed it on). No C++ +// objects in the __try frame, and not inlined: inlined into the reader's lambda (clang-cl, under Wine), the code after +// the __except wrote through a null pointer. +__declspec(noinline) bool guarded_read(const volatile std::uint32_t* address, std::uint32_t* value) +{ + __try { + *value = *address; + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +// Break A takes apart run 1; a fault in it is held before its handler looks the page up (X2W_XMEM_TEST_HOLD_RETRY). +// A ends, then `later` breaks follow, each the unmap of a lone page mapped by a call of its own (one break per unmap +// call; the lone page joins no run). Run 1's views keep the stamp of break A, which mapped them again, however many +// breaks follow, so the fault is retried and the reader reads its page. A fault passed on would reach the reader's +// own __except. +void later_breaks_case(const Shim& shim, unsigned char* run1, SIZE_T later) +{ + char name[32], stem[32]; + std::snprintf(name, sizeof(name), "later_breaks_%zu", later); + std::snprintf(stem, sizeof(stem), "later-%zu", later); + unsigned char* const lone = run1 + 32 * page; + SIZE_T count = pages + 1, tokens[pages + 1] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages + 1 || shim.map(run1, pages, tokens) != run1) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast<std::uint32_t*>(run1 + i * page) = 0x56000000u + static_cast<std::uint32_t>(i); + unsigned char* const target = run1 + 2 * page; + Events window(stem, "unmapped", "release"), retry(stem, "faulted", "go"); + std::atomic<int> outcome{0}; // 0: the reader has not finished; 1: it read its page; 2: the fault was passed on + std::uint32_t value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window.name); + std::thread unmap_a([&] { shim.map(run1 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window.first, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, "break_a_held", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { outcome = guarded_read(reinterpret_cast<volatile std::uint32_t*>(target), &value) ? 1 : 2; }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(window.second); + unmap_a.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + // The handler waits at most five seconds for "go" (hold_retry): the later breaks must all end inside that wait. + const ULONGLONG started = GetTickCount64(); + SIZE_T made = 0; + for (SIZE_T k = 0; k < later; ++k) { + if (shim.map(lone, 1, &tokens[pages]) != lone || raw_state(lone) != MEM_COMMIT) break; + if (shim.map(lone, 1, nullptr) != lone || raw_state(lone) == MEM_COMMIT) break; + ++made; + } + const ULONGLONG elapsed = GetTickCount64() - started; + std::printf("%s: %zu later breaks in %llu ms\n", name, made, static_cast<unsigned long long>(elapsed)); + check(made == later, "later_breaks_made", name); + check(outcome.load() == 0 && elapsed < 4000, "handler_still_held_after_the_later_breaks", name); + SetEvent(retry.second); // the handler looks the page up now + reader.join(); + check(outcome.load() == 1 && value == 0x56000002u, "fault_retried_after_the_later_breaks", name); + shim.map(run1, 7, nullptr); + shim.release(pages + 1, tokens); +} + +std::atomic<int> first_chance_faults{0}; +ULONG_PTR counted_page = 0; + +// Added after xmem's handler with FirstHandler=1, so it sees each access violation first, also one xmem retries. +LONG CALLBACK count_fault(EXCEPTION_POINTERS* e) +{ + const EXCEPTION_RECORD* record = e->ExceptionRecord; + if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2 && + (record->ExceptionInformation[1] & ~(ULONG_PTR{page} - 1)) == counted_page) + ++first_chance_faults; + return EXCEPTION_CONTINUE_SEARCH; +} + +// A fault that stays: page 2 of a run made no-access, read once by a new thread. On a run no break has mapped (stamp +// 0) the handler passes the fault on at once: one fault. After a break maps the run again (the unmap of page 7), it +// retries once and then passes it on: two faults. Both reach the reader's __except. +void persistent_fault_case(const Shim& shim, unsigned char* run1) +{ + const char* const name = "persistent_fault"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(run1, pages, tokens) != run1) { + check(false, "map_run", name); + return; + } + unsigned char* const target = run1 + 2 * page; + const auto faults = [&](const char* step) { + DWORD old = 0; + if (!check(VirtualProtect(target, page, PAGE_NOACCESS, &old) != FALSE, step, name)) return -1; + counted_page = reinterpret_cast<ULONG_PTR>(target); + first_chance_faults = 0; + void* const counter = AddVectoredExceptionHandler(1, count_fault); + std::uint32_t value = 0; + bool read = true; + std::thread reader([&] { read = guarded_read(reinterpret_cast<volatile std::uint32_t*>(target), &value); }); + reader.join(); + if (counter) RemoveVectoredExceptionHandler(counter); + VirtualProtect(target, page, PAGE_READWRITE, &old); + const int counted = first_chance_faults.load(); + std::printf("%s: %s -> read %d, first-chance faults %d\n", name, step, read, counted); + return counter && !read ? counted : -1; + }; + check(faults("no_break_mapped_the_run") == 1, "passed_on_at_once_without_a_stamp", name); + check(shim.map(run1 + 7 * page, 1, nullptr) == run1 + 7 * page, "unmap_page_7", name); + check(faults("a_break_mapped_the_run") == 2, "retried_once_with_a_stamp", name); + shim.map(run1, 7, nullptr); + shim.release(pages, tokens); +} +} // namespace + +int main(int argc, char** argv) +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); // a case that ends the process with an access violation keeps its lines + const bool control = argc > 2 && std::strcmp(argv[2], "control") == 0; + const bool next_break_control = argc > 2 && std::strcmp(argv[2], "next-break-control") == 0; + const bool default_mode = argc > 2 && std::strcmp(argv[2], "default") == 0; + const bool lazy = argc > 2 && std::strcmp(argv[2], "lazy") == 0; + const bool two_runs = argc > 2 && std::strcmp(argv[2], "two-runs") == 0; + const bool mirror = argc > 2 && std::strcmp(argv[2], "mirror") == 0; + const bool stamps = argc > 2 && std::strcmp(argv[2], "stamps") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror && + !stamps)) { + std::printf("usage: xmem_run_break_readers_check <test-controls xmem.dll> " + "[control|next-break-control|default|lazy|two-runs|mirror|stamps]\n"); + return 2; + } + // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", default_mode ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", mirror ? "1" : nullptr); // only `mirror` joins across calls + if (lazy) SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + Shim shim{reinterpret_cast<XMemVirtualAllocFn>(GetProcAddress(xmem, "XMemVirtualAlloc")), + reinterpret_cast<XMemAllocatePhysicalPagesFn>(GetProcAddress(xmem, "XMemAllocatePhysicalPages")), + reinterpret_cast<XMemMapPhysicalPagesFn>(GetProcAddress(xmem, "XMemMapPhysicalPages")), + reinterpret_cast<XMemFreePhysicalPagesFn>(GetProcAddress(xmem, "XMemFreePhysicalPages")), + reinterpret_cast<XMemVirtualQueryFn>(GetProcAddress(xmem, "XMemVirtualQuery")), + reinterpret_cast<StableCallFn>(GetProcAddress(xmem, "x2w_xmem_stable_call"))}; + if (!shim.virtual_alloc || !shim.allocate || !shim.map || !shim.release || !shim.query || !shim.stable_call) { + std::printf("check_failed: exports\n"); + return 1; + } + auto* const base = static_cast<unsigned char*>(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!base) { + std::printf("check_failed: startup reservation (error %lu)\n", GetLastError()); + return 1; + } + unsigned char* const at = base + page; + if (next_break_control || default_mode || lazy || two_runs || mirror || stamps) { + if (next_break_control) next_break_case(shim, at, false); + if (default_mode) default_case(shim, at); + if (lazy) { + lazy_case(shim, at); + lazy_read_file(shim, at + 40 * page); + } + if (two_runs) two_runs_case(shim, at); + if (mirror) mirror_case(shim, base); + if (stamps) { + later_breaks_case(shim, at, 63); + later_breaks_case(shim, at + 64 * page, 64); + later_breaks_case(shim, at + 128 * page, 200); + persistent_fault_case(shim, at + 192 * page); + } + VirtualFree(base, 0, MEM_RELEASE); + // The default mode's pass line, at the end and only with no failed check (ctest matches it). + if (default_mode && !failures) std::printf("default mode: readers answer inside an unmap\n"); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } + int index = 0; + if (!control) { + window_case(shim, at, index++, "x2w_xmem_stable_call", true, [&](unsigned char* target) { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast<Query*>(context); + q.state = raw_state(q.target); + }, &query); + return query.state == MEM_COMMIT; + }); + window_case(shim, at, index++, "XMemVirtualQuery", true, [&](unsigned char* target) { + unsigned char buffer[64] = {}; + DWORD state = 0; + if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&state, buffer + 0x20, sizeof(state)); + return state == MEM_COMMIT; + }); + window_case(shim, at, index++, "VirtualQueryEx_import", true, [&](unsigned char* target) { + MEMORY_BASIC_INFORMATION info{}; + return VirtualQueryEx(GetCurrentProcess(), target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_COMMIT; + }); + window_case(shim, at, index++, "ReadFile_import", true, read_file_into); + window_case(shim, at, index++, "WriteFile_import", true, write_file_from); + window_case(shim, at, index++, "ReadFile_pipe", false, read_pipe_into); + check(!pipe_read.ok && (pipe_read.error == ERROR_NOACCESS || pipe_read.error == ERROR_INVALID_USER_BUFFER), + "fails_with_an_error_the_wrapper_retries_for_disk_files", "ReadFile_pipe"); + io_outside_runs(); + } + // The header readers: waiting with the export, answering inside the window without it (control). + const bool waits = !control; + window_case(shim, at, index++, "x2w_local::writable", waits, [&](unsigned char* target) { + return x2w_local::writable(target, 64); + }); + window_case(shim, at, index++, "measure_placed_buffer", waits, [&](unsigned char* target) { + x2w_startup::PlacedBufferRange range; + return x2w_startup::measure_placed_buffer(target, 4096, range) && range.type == MEM_MAPPED && range.covered; + }); + window_case(shim, at, index++, "snapshot_samplers", waits, [&](unsigned char* target) { + const auto snapshot = x2w_startup::snapshot_samplers({reinterpret_cast<std::uintptr_t>(target), 4}, false); + return snapshot.count == 4 && snapshot.readable.count() == 4 && snapshot.words[0][0] == 0x51000000u + neighbour; + }); + if (!control) { + next_break_case(shim, at, true); + break_during_fn(shim, at); + } + VirtualFree(base, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/xmem_slab_slots_check.cpp b/tests/xmem_slab_slots_check.cpp index e2dc7157a1..023789fc09 100644 --- a/tests/xmem_slab_slots_check.cpp +++ b/tests/xmem_slab_slots_check.cpp @@ -175,6 +175,67 @@ void invalid_releases_are_refused() CHECK(!slots.release(0, slot.offset)); // already free counters(slots, 1, 0, per_slab); } + +void reclaiming_empty_slabs_closes_handles() +{ + Slots slots(slot_bytes); + Factory factory; + std::vector<Slots::Slot> first_slab, second_slab; + for (std::uint64_t i = 0; i < per_slab; ++i) first_slab.push_back(fresh(slots, factory)); + for (std::uint64_t i = 0; i < 10; ++i) second_slab.push_back(fresh(slots, factory)); + counters(slots, 2, per_slab + 10, per_slab - 10); + + // Releasing all of slab 0 while slab 1 stays live closes only slab 0 and leaves a tombstone at index 0. + for (const auto& slot : first_slab) CHECK(slots.release(slot.slab_index, slot.offset)); + std::vector<int> closed; + slots.reclaim_empty_slabs([&](int h) { closed.push_back(h); }); + CHECK(closed.size() == 1 && closed[0] == 100); + counters(slots, 1, 10, per_slab - 10); + CHECK(slots.slabs().size() == 2 && slots.slabs()[0] == 0 && slots.slabs()[1] == 101); + CHECK(!slots.release(0, 0)); // tombstone slab refuses release + + // Next acquire skips the closed slab 0 and uses slab 1. + const auto next = acquire(slots, factory); + CHECK(next.slab == 101 && next.slab_index == 1 && next.offset == 10 * slot_bytes); + second_slab.push_back(next); + + // Releasing the last live slab pops both it and the preceding tombstone. + for (const auto& slot : second_slab) CHECK(slots.release(slot.slab_index, slot.offset)); + slots.reclaim_empty_slabs([&](int h) { closed.push_back(h); }); + CHECK(closed.size() == 2 && closed[1] == 101); + counters(slots, 0, 0, 0); + CHECK(slots.slabs().empty()); + + // Reclaiming a trailing empty slab while an earlier slab stays live preserves the earlier slab's full state. + first_slab.clear(); + second_slab.clear(); + for (std::uint64_t i = 0; i < per_slab; ++i) first_slab.push_back(fresh(slots, factory)); + for (std::uint64_t i = 0; i < 5; ++i) second_slab.push_back(fresh(slots, factory)); + CHECK(slots.release(0, 0)); + for (const auto& slot : second_slab) CHECK(slots.release(slot.slab_index, slot.offset)); + closed.clear(); + slots.reclaim_empty_slabs([&](int h) { closed.push_back(h); }); + CHECK(closed.size() == 1 && closed[0] == 103); + counters(slots, 1, per_slab - 1, 1); + CHECK(slots.slabs().size() == 1 && slots.slabs()[0] == 102); + + // Reusing the one free slot in slab 0 works, then the next acquire opens a fresh slab (does not overwrite slab 0). + const auto reused = acquire(slots, factory); + CHECK(reused.slab == 102 && reused.slab_index == 0 && reused.offset == 0); + counters(slots, 1, per_slab, 0); + const auto opened = acquire(slots, factory); + CHECK(opened.slab == 104 && opened.slab_index == 1 && opened.offset == 0); + counters(slots, 2, per_slab + 1, per_slab - 1); + + // Release everything and reclaim all remaining slabs. + for (const auto& slot : first_slab) CHECK(slots.release(slot.slab_index, slot.offset)); + CHECK(slots.release(opened.slab_index, opened.offset)); + closed.clear(); + slots.reclaim_empty_slabs([&](int h) { closed.push_back(h); }); + CHECK(closed.size() == 2 && closed[0] == 102 && closed[1] == 104); + counters(slots, 0, 0, 0); + CHECK(slots.slabs().empty()); +} } // namespace int main() @@ -186,6 +247,7 @@ int main() a_failing_factory_changes_nothing(); unwinding_a_fresh_slot_gives_it_back(); invalid_releases_are_refused(); + reclaiming_empty_slabs_closes_handles(); std::puts("xmem slab slots: all checks passed"); return 0; } diff --git a/tests/xmem_test_device.h b/tests/xmem_test_device.h index 3b7b5383c0..58acbbc291 100644 --- a/tests/xmem_test_device.h +++ b/tests/xmem_test_device.h @@ -28,7 +28,8 @@ inline HRESULT create_desktop_device(IUnknown* adapter, REFIID iid, void** devic } inline Microsoft::WRL::ComPtr<ID3D12Device> create_device(bool warp, bool& unmatched, - CreateDeviceFn create = create_desktop_device) + CreateDeviceFn create = create_desktop_device, + std::FILE* diagnostics = stdout) { unmatched = false; Microsoft::WRL::ComPtr<IDXGIFactory6> factory; @@ -44,7 +45,7 @@ inline Microsoft::WRL::ComPtr<ID3D12Device> create_device(bool warp, bool& unmat wchar_t wanted[128]{}; const DWORD filter = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", wanted, 128); if (filter >= 128) { - std::puts("XBOX2WINDOWS_ADAPTER is longer than 127 characters"); + std::fputs("XBOX2WINDOWS_ADAPTER is longer than 127 characters\n", diagnostics); unmatched = true; return nullptr; } @@ -59,12 +60,12 @@ inline Microsoft::WRL::ComPtr<ID3D12Device> create_device(bool warp, bool& unmat if (!match) continue; } if (SUCCEEDED(create(adapter.Get(), IID_PPV_ARGS(&device)))) { - std::printf("device adapter %04x:%04x %ls\n", desc.VendorId, desc.DeviceId, desc.Description); + std::fprintf(diagnostics, "device adapter %04x:%04x %ls\n", desc.VendorId, desc.DeviceId, desc.Description); return device; } } if (filter) { - std::printf("No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", wanted); + std::fprintf(diagnostics, "No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", wanted); unmatched = true; } return nullptr; diff --git a/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md b/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md index 8b16a91595..5e9550ce8a 100644 --- a/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md +++ b/tools/_bcpack_rans/THIRD_PARTY_NOTICES.md @@ -34,12 +34,12 @@ SOFTWARE ## Ahmet Dedeler bcpack-rs -`src/startup_stubs/bcpack_tables.h` and `src/startup_stubs/bcpack_tables_bcn.inl` contain BC1, BC3, BC4, BC5, and BC7 -codebook, rank, window, and dictionary tables (`BC7_CONTROL_TABLE`, `BC7_DICTIONARY`, `BC1_WINDOW`, `BC1_QUAD_MASKS`, +`src/startup_stubs/bcpack_tables.h` and `src/startup_stubs/bcpack_tables_bcn.inl` contain BC3, BC4, BC5, and BC7 +codebook, rank, and dictionary tables (`BC7_CONTROL_TABLE`, `BC7_DICTIONARY`, `RANK_PAIR_BC4`, `BC4_DICTIONARY`, `RANK_PAIR_BC5`, `BC5_DICTIONARY`, `RANK_PAIR_BC3_ALPHA`, `RANK_QUAD_BC3_COLOUR`, `BC3_DICTIONARY`) adapted from https://github.com/Ahmet-Dedeler/bcpack-rs (pinned revision c55c5fad539644b8cf5a705051df214291763fc0). -The BC1, BC3, BC4, BC5, and BC7 block reconstruction routines in `src/startup_stubs/bcpack_decoder.h` are adapted from +The BC3, BC4, BC5, and BC7 block reconstruction routines in `src/startup_stubs/bcpack_decoder.h` are adapted from the same repository. Used under the MIT License: ``` @@ -65,3 +65,35 @@ 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. ``` + +## Microsoft DirectXTex + +The `BC6_WIRE` descriptors in `src/startup_stubs/bcpack_tables_extra.inl` adapt +the BC6H bit layout in `DirectXTex/BC6HBC7.cpp` at revision +[`a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379`](https://github.com/microsoft/DirectXTex/tree/a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379). +The BCPack-specific bit ordering is described in +[the implementation notes](../../docs/experiments/bcpack-standalone.md). + +```text +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/tools/bcpack_recover_constants.py b/tools/bcpack_recover_constants.py new file mode 100644 index 0000000000..3fab7e05f2 --- /dev/null +++ b/tools/bcpack_recover_constants.py @@ -0,0 +1,228 @@ +"""Reproduce BCPack format constants with chosen synthetic lane streams. + +SPDX-License-Identifier: MIT + +The GDK is a development oracle only. No DLL bytes or memory tables are read here. +BC6H wire bit descriptors are parsed from the public MIT DirectXTex source. +""" +import ctypes as c +import json +import argparse +import hashlib +from pathlib import Path +import re + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("--sdk", type=Path, required=True, help="Installed BCPack.dll, development oracle only") +parser.add_argument("--bridge", type=Path, required=True, help="Source-built bcpack_oracle_bridge.dll") +parser.add_argument("--bc6-reference", type=Path, required=True, help="Pinned public DirectXTex BC6HBC7.cpp") +parser.add_argument("--output", type=Path, required=True, help="Generated .inl (normally under out/)") +parser.add_argument("--storage-goldens", type=Path, help="Also regenerate the source-built storage fixture's expected blocks") +args = parser.parse_args() +sdk = c.CDLL(str(args.sdk.resolve())) +dec = sdk.BCPackDecompress +dec.argtypes = [c.c_size_t, c.c_void_p, c.c_size_t, c.c_void_p, c.c_size_t] +dec.restype = c.c_int32 +encoder = c.CDLL(str(args.bridge.resolve())) +enc = encoder.encode_symbols +enc.argtypes = [c.c_uint, c.POINTER(c.c_uint16), c.c_size_t, c.c_void_p, c.c_size_t] +enc.restype = c.c_size_t +N = {1:12, 2:15, 3:12, 4:12, 5:12, 6:16, 7:16} +PER = {b:1 if b in (1,4) else 2 for b in N} +LINE = [0, 3, 1, 2] +BC6_BITS = [[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]] + + +def wire_descriptors(): + source = args.bc6_reference.read_bytes() + if hashlib.sha256(source).hexdigest() != "187434fab12351df0f875ae09390981034e8479159a6f4aaaf0904f007182b8a": + raise ValueError("DirectXTex reference does not match pinned a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379") + text = source.decode("utf-8-sig") + text = text.split('const D3DX_BC6H::ModeDescriptor D3DX_BC6H::ms_aDesc',1)[1] + text = text.split('// Mode, Partitions, Transformed, IndexPrec',1)[0] + desc = [[]] + for mode, body in re.findall(r'\{\s*// Mode (\d+)[^\n]*\n(.*?)\n\s*\},',text,re.S): + mode = int(mode) + pairs = [(f,int(b)) for f,b in re.findall(r'\{\s*(\w+),\s*(\d+)\s*\}',body)] + assert len(pairs) == 82 and mode == len(desc) + # BCPack's packer writes the high base bits ascending in modes 13/14. + if mode in (13,14): + for f in ['RW','GW','BW']: + positions = [i for i,(field,bit) in enumerate(pairs) if field == f and bit >= 10] + for i,b in zip(positions,sorted(pairs[i][1] for i in positions)): + pairs[i] = (f,b) + desc.append(pairs[:82 if mode <= 10 else 65]) + assert len(desc) == 15 + return desc + + +DESC = wire_descriptors() + + +def interleave(a,b): + return sum(((a>>k&1)<<(2*k)) | ((b>>k&1)<<(2*k+1)) for k in range(4)) + + +def split(v): + return [sum((v>>(2*k+j)&1)<<k for k in range(4)) for j in range(2)] + + +def query(fmt, ep=0, ix=0, mode=11, rank=0): + per = PER[fmt] + s = [0] * (N[fmt] * per) + delta = (ep - ix + 128) % 256 - 128 + zz = 2*delta if delta >= 0 else -2*delta-1 + s[:per] = split(zz) if per == 2 else [zz] + s[per:2*per] = split(ix) if per == 2 else [ix] + if fmt == 1: + s[8:] = [rank]*4 + elif fmt == 2: + s[26:] = [rank]*4 + elif fmt == 6: + s[30] = mode-1 + v = (c.c_uint16*len(s))(*s) + packed = c.create_string_buffer(65536) + n = enc(fmt,v,per,packed,len(packed)) + assert n, (fmt,ep,ix,mode,rank,'encode') + size = 8*per + out = c.create_string_buffer(b'\xa5'*(size+32),size+32) + hr = dec(fmt,c.addressof(out)+16,size,packed,n) + assert hr >= 0, (fmt,ep,ix,mode,rank,hex(hr&0xffffffff)) + assert out.raw[:16] == b'\xa5'*16 and out.raw[-16:] == b'\xa5'*16 + return out.raw[16:-16] + + +def colour(raw): + a,b = int.from_bytes(raw[:2],'little'),int.from_bytes(raw[2:4],'little') + ep = [a>>11,a>>5&63,a&31,b>>11,b>>5&63,b&31] + word = int.from_bytes(raw[4:8],'little') + ix = [LINE[word>>(2*p)&3] for p in range(16)] + return ep,ix + + +def unpack6(raw,mode): + word = int.from_bytes(raw,'little') + fields = {f:0 for f in ['RW','RX','RY','RZ','GW','GX','GY','GZ','BW','BX','BY','BZ']} + for i,(f,bit) in enumerate(DESC[mode]): + if f in fields: fields[f] |= ((word>>i)&1)<<bit + ep = [[0]*3 for _ in range(4)] + for k,e in enumerate('WXYZ'): + if mode > 10 and k > 1: continue + for channel,ch in enumerate('RGB'): + bits = BC6_BITS[mode][0 if k == 0 else channel+1] + ep[k][channel] = (fields[ch+e] << (16-bits)) ^ 0x8000 + at = 82 if mode <= 10 else 65 + bits = 3 if mode <= 10 else 4 + ix = [] + for p in range(16): + width = bits - int(p == 0 or mode <= 10 and p == 15) + value = (word>>at)&((1<<width)-1) + ix.append(((value-(1<<(bits-1))) << (16-bits))&65535) + at += width + assert at == 128 + return ep,ix + + +def main(): + tables = {'method':'Synthetic BCPack lane streams -> decoder API -> public BC block fields; no SDK binary-table extraction', + 'bc6_wire':DESC, 'bc6_bits':BC6_BITS} + for fmt in (1,2): + ranks=[] + for rank in range(256): + _, ix = colour(query(fmt,rank=rank)[0 if fmt == 1 else 8:]) + ranks.append([ix[p] for p in (0,1,4,5)]) + zero = ranks.index([0]*4) + rows=[] + for r in range(1,256): + raw = query(fmt,ep=r,ix=r,rank=zero) + ep,ix=colour(raw[0 if fmt == 1 else 8:]) + row={'ep':ep,'ix':ix} + if fmt == 2: + a=int.from_bytes(raw[:8],'little') + row['alpha']=[((a>>(4*p))&15)^8 for p in range(16)] + rows.append(row) + tables[f'bc{fmt}_ranks']=ranks + tables[f'bc{fmt}_dictionary']=rows + print(f'BC{fmt}: {len(ranks)} quadrant ranks and {len(rows)} predictor entries recovered',flush=True) + rows=[] + for r in range(1,256): + a,_=unpack6(query(6,ep=r,mode=14),14) + b,_=unpack6(query(6,ep=r,mode=11),11) + c,_=unpack6(query(6,ep=r,mode=2),2) + _,ix=unpack6(query(6,ix=r,mode=11),11) + rows.append({'ep':[a[0],b[1],c[2],c[3]],'ix':ix}) + tables['bc6_dictionary']=rows + write_tables(tables, args.output) + if args.storage_goldens: + storage_goldens(args.storage_goldens) + print(f'BC6H: {len(rows)} predictor entries recovered',flush=True) + + +def initializer(values): + return '{ ' + ', '.join(initializer(v) if isinstance(v,list) else str(v) for v in values) + ' }' + + +def storage_goldens(out): + build = encoder.storage_symbols + build.argtypes = [c.c_uint, c.POINTER(c.c_uint16), c.c_size_t] + build.restype = c.c_size_t + lines = ["// GDK 1.2603.3.0 golden BC blocks from random_symbols(fmt,4,0x7700+fmt).", + "// Entirely synthetic input, no SDK or title bytes. SPDX-License-Identifier: MIT", "#pragma once"] + for fmt in (2, 6): + symbols = (c.c_uint16 * 128)() + assert build(fmt, symbols, 128) + packed = c.create_string_buffer(65536) + size = enc(fmt, symbols, 8, packed, len(packed)) + assert size + output = c.create_string_buffer(64) + assert dec(fmt, output, 64, packed, size) >= 0 + lines.append(f"inline constexpr unsigned char BC{fmt}_STORAGE_EXPECTED[64] = {{") + for at in range(0, 64, 16): + lines.append(" " + ", ".join(f"0x{v:02x}" for v in output.raw[at:at+16]) + ",") + lines.append("};") + out.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") + + +def write_tables(t, out): + lines=['// BCPack format constants reconstructed with synthetic lane streams.', + '// No SDK binaries or title data are embedded. See docs/experiments/bcpack-standalone.md.', + '// BC6H wire descriptors adapt the MIT-licensed Microsoft DirectXTex BC6HBC7.cpp.', + '// Copyright (c) Microsoft Corporation. All rights reserved.', + '// SPDX-License-Identifier: MIT', '', + 'struct Bc1FullState { uint8_t ep[6]; uint8_t ix[16]; };', + 'struct Bc2State { uint8_t alpha[16]; uint8_t ep[6]; uint8_t ix[16]; };', + 'struct Bc6State { uint16_t ep[4][3]; uint16_t ix[16]; };', + 'struct Bc6WireBit { uint8_t field; uint8_t bit; };',''] + for fmt in (1,2): + lines.append(f'inline constexpr uint8_t BC{fmt}_POSITION_RANK[256][4] = {{') + lines.extend(' '+initializer(row)+',' for row in t[f'bc{fmt}_ranks']) + lines.extend(['};','']) + typ='Bc1FullState' if fmt==1 else 'Bc2State' + lines.append(f'inline constexpr {typ} BC{fmt}_FULL_DICTIONARY[255] = {{') + fields=['ep','ix'] if fmt==1 else ['alpha','ep','ix'] + lines.extend(' '+initializer([row[f] for f in fields])+',' for row in t[f'bc{fmt}_dictionary']) + lines.extend(['};','']) + lines.append('inline constexpr Bc6State BC6_DICTIONARY[255] = {') + lines.extend(' '+initializer([row['ep'],row['ix']])+',' for row in t['bc6_dictionary']) + lines.extend(['};','','inline constexpr uint8_t BC6_ENDPOINT_BITS[15][4] = {']) + lines.extend(' '+initializer(row)+',' for row in t['bc6_bits']) + lines.extend(['};','','// 0 = mode bit, 1 = partition bit; 2 + 3 * endpoint + channel = endpoint bit.', + 'inline constexpr Bc6WireBit BC6_WIRE[14][82] = {']) + for mode,row in enumerate(t['bc6_wire'][1:],1): + vals=[] + for f,b in row: + field = 0 if f in ('M','NA') else 1 if f=='D' else 2+3*'WXYZ'.index(f[1])+'RGB'.index(f[0]) + vals.append([field,b]) + lines.append(' { // Mode '+str(mode)) + for pos in range(0,len(vals),10): + lines.append(' '+', '.join(initializer(v) for v in vals[pos:pos+10])+',') + lines.append(' },') + lines.extend(['};','']) + out.write_text('\n'.join(lines),encoding='utf-8',newline='\n') + print(out, out.stat().st_size) + + +if __name__ == "__main__": + main() diff --git a/tools/bink_descriptors_aot.py b/tools/bink_descriptors_aot.py index f6638f4dbf..da1f62f8e9 100644 --- a/tools/bink_descriptors_aot.py +++ b/tools/bink_descriptors_aot.py @@ -1,6 +1,9 @@ """Translate the two Bink leaf functions that build grouped allocation descriptors.""" import argparse +import os from pathlib import Path +import struct +import tempfile import pefile from iced_x86 import Mnemonic as M, OpKind as K, Register as R @@ -70,6 +73,47 @@ def generate(image: Path, package: bool, frame_planes: bool = False) -> str: + append_body + '\n}\n' + planes) +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) @@ -78,10 +122,9 @@ def main(argv=None) -> int: parser.add_argument("--frame-planes", action="store_true") args = parser.parse_args(argv) try: - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") - args.output.write_text(generate(args.image, args.package, args.frame_planes), encoding="ascii") - except (OSError, ValueError, pefile.PEFormatError) as error: + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image, args.package, args.frame_planes)) + except (OSError, ValueError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 diff --git a/tools/bink_frame_aot.py b/tools/bink_frame_aot.py index 9b72bb297a..8ccef75940 100644 --- a/tools/bink_frame_aot.py +++ b/tools/bink_frame_aot.py @@ -1,6 +1,7 @@ """Translate the frame allocator, binding its direct calls to the existing Bink translations.""" import argparse from pathlib import Path +import tempfile from iced_x86 import Mnemonic as M, OpKind as K, Register as R import pefile @@ -64,15 +65,55 @@ def generate(image): """ + code + "\n}\n" +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args(argv) - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") try: - args.output.write_text(generate(args.image), encoding="ascii") + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image)) except (OSError, ValueError, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 diff --git a/tools/bink_heap_aot.py b/tools/bink_heap_aot.py index 430f392236..49455a3045 100644 --- a/tools/bink_heap_aot.py +++ b/tools/bink_heap_aot.py @@ -1,6 +1,8 @@ """Lower the Bink callback setter and heap callers to a Windows DLL.""" import argparse from pathlib import Path +import struct +import tempfile import pefile from iced_x86 import Decoder, MemorySizeExt, Mnemonic as M, OpKind as K, Register as R @@ -208,7 +210,52 @@ def generate(image, entries, group_entry=None): """ + group -def main(argv=None): +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + if args.image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {args.image}") + if not args.image.is_file(): + raise FileNotFoundError(f"image file not found: {args.image}") + if args.entries is not None and any(rva < 0 for rva in args.entries): + raise ValueError("--entries RVAs must be non-negative") + if args.group_entry is not None and not args.group_entry.strip(): + raise ValueError("--group-entry must be non-empty") + if args.output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if args.output.resolve() == args.image.resolve() or (args.output.exists() and args.image.samefile(args.output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("output", type=Path) @@ -216,13 +263,13 @@ def main(argv=None): metavar=("ALLOC_RVA", "FREE_RVA")) parser.add_argument("--group-entry", help="Grouped allocation caller RVA or the fixture export heap_group") args = parser.parse_args(argv) - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") try: - args.output.write_text(generate(args.image, args.entries, args.group_entry), encoding="ascii") - except (ValueError, OSError, pefile.PEFormatError) as error: + _validate_args(args, parser) + _write_atomic(args.output, generate(args.image, args.entries, args.group_entry)) + except (ValueError, OSError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/tools/call_evidence.py b/tools/call_evidence.py index 5261d880eb..0d8a2865d6 100644 --- a/tools/call_evidence.py +++ b/tools/call_evidence.py @@ -2,12 +2,15 @@ import argparse from collections import defaultdict +from collections.abc import Sequence import hashlib import json +import os from pathlib import Path import re import struct import subprocess +import tempfile import pefile @@ -112,7 +115,63 @@ def inspect(path): containers=shader_containers(data, pe, memory)) -def main(argv=None): +def _validate_inputs(root: Path, parser: argparse.ArgumentParser) -> None: + missing = [] + for name in NAMES: + image = root / name + if image.is_symlink(): + raise ValueError(f"Expected image must not be a symlink: {image}") + if not image.exists(): + missing.append(name) + continue + if image.is_dir(): + raise IsADirectoryError(f"Expected image path is a directory: {image}") + if not image.is_file(): + raise ValueError(f"Expected image must be a regular file: {image}") + if not os.access(image, os.R_OK): + raise PermissionError(f"Expected image is not readable: {image}") + with image.open("rb"): + pass + if missing: + parser.error(f"Missing expected image(s) in {root}: {', '.join(missing)}") + + +def _validate_output(output: Path) -> None: + if output.is_symlink(): + raise ValueError(f"Output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {output}") + if output.exists() and not output.is_file(): + raise ValueError(f"Output path is not a regular file: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"Output parent is not a directory: {parent}") + + +def _write_atomic(path: Path, content: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("directory", type=Path) args = parser.parse_args(argv) @@ -123,20 +182,18 @@ def main(argv=None): if not root.is_dir(): parser.error(f"Input path is not a directory: {root}") output = Path(__file__).resolve().parents[1] / "out/calls/six-apis.json" - if output.resolve().is_relative_to(root): - parser.error("Choose a build directory separate from the report directory") - missing = [name for name in NAMES if not (root / name).is_file()] - if missing: - parser.error(f"Missing expected image(s) in {root}: {', '.join(missing)}") try: + if output.is_relative_to(root) or output.resolve().is_relative_to(root): + parser.error("Choose a build directory separate from the report directory") + _validate_output(output) + _validate_inputs(root, parser) rows = {name: inspect(root / name) for name in NAMES} - except (OSError, ValueError, pefile.PEFormatError, subprocess.SubprocessError) as exc: + _write_atomic(output, json.dumps(rows, indent=2) + "\n") + except (OSError, ValueError, struct.error, pefile.PEFormatError, subprocess.SubprocessError) as exc: parser.exit(1, f"call_evidence: {exc}\n") - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") print(output) return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index a76f40afdd..703a8e81ec 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -50,6 +50,7 @@ # src0[23:0] * src1[23:0] + src2, modulo 2^32. None of them writes vcc, so the guard compare stays valid. ALU = { "v_and_b32_e32": f"({INTEGER['and_b32'][1]})", + "v_bfm_b32": "(((1u << ({0} & 31u)) - 1u) << ({1} & 31u))", # VOP3 only: ((1 << src0[4:0]) - 1) << src1[4:0] "v_lshrrev_b32_e32": f"({INTEGER['lshrrev_b32'][1]})", "v_lshlrev_b32_e32": f"({INTEGER['lshlrev_b32'][1]})", # v_max3_u32 and v_min3_u32 are the unsigned maximum and minimum of the three sources, max(max(a, b), c). @@ -78,6 +79,14 @@ "v_mul_lo_u32": INTEGER["mul_lo_u32"][1], "v_mad_u32_u24": "((({0} & 0xffffffu) * ({1} & 0xffffffu)) + {2})", } +# The VOP1 bit subset on one known word (AMD RDNA 2 ISA reference, VOP1 opcodes 56 and 59). v_bfrev_b32 reverses +# the 32 bits. v_ffbh_i32 counts from the sign bit (bit 31 is position 0) to the first bit that differs from it, +# and is 0xffffffff for 0 and 0xffffffff: v_ffbh_u32 of m = x ^ (x >> 31, arithmetic). firstbitlow(reversebits(m)) +# is 31 - firstbithigh(m) and 0xffffffff for m = 0, so the source appears only twice. +VOP1_ALU = { + "v_bfrev_b32_e32": "reversebits({0})", + "v_ffbh_i32_e32": "firstbitlow(reversebits({0} ^ asuint(asint({0}) >> 31u)))", +} # The scalar ALU subset, on known words only: s_<op> sD, a, b with two scalar sources (an SGPR holding a known # word, an integer inline constant or a 32-bit literal). The carry out of s_add_u32 and s_sub_u32 and the # nonzero flag of the logic forms go to SCC, which no accepted instruction reads. s_lshr_b32 is a logical @@ -94,6 +103,8 @@ # RDNA2 SOP2: temp.i64 = (int64)S0.i32 - (int64)S1.i32; D.i32 = temp.i32[31:0]; SCC = (temp.i64 != (int64)D.i32) ? 1 : 0 (unread). "s_sub_i32": "({0} - {1})", "s_and_b32": "({0} & {1})", + "s_bitset0_b32": "({0} & ~(1u << ({1} & 31u)))", + "s_bitset1_b32": "({0} | (1u << ({1} & 31u)))", "s_or_b32": "({0} | {1})", "s_xor_b32": "({0} ^ {1})", "s_lshr_b32": "({0} >> ({1} & 31u))", @@ -240,35 +251,146 @@ "ds_max_u32": "max({0}, {1})", } +# Group-shared LDS on gfx1013 (issue #1541): the D3D12 groupshared limit, the barrier after every DS step, and the +# non-returning updates as HLSL Interlocked methods on `lds` (all are order-independent within an instruction). +LDS_SHARED_LIMIT = 32768 +LDS_BARRIER = " GroupMemoryBarrierWithGroupSync();" +LDS_SHARED_ATOMICS = {"add_u32": "Add", "sub_u32": "Add", "and_b32": "And", "or_b32": "Or", "xor_b32": "Xor", + "min_u32": "Min", "max_u32": "Max"} +LDS_SHARED_FORMS = ( + r"ds_(?P<op>write|read)_b(?P<bits>32|64|128) (?P<a>v\d+|v\[\d+:\d+\]), (?P<b>v\d+|v\[\d+:\d+\])" + r"(?: offset:(?P<offset>\d+))?", + r"ds_(?P<op>write2|write2st64)_b(?P<bits>32|64) (?P<a>v\d+), (?P<b>v\d+|v\[\d+:\d+\]), (?P<c>v\d+|v\[\d+:\d+\])" + r"(?: offset0:(?P<offset0>\d+))?(?: offset1:(?P<offset1>\d+))?", + r"ds_(?P<op>read2|read2st64)_b(?P<bits>32|64) (?P<b>v\[\d+:\d+\]), (?P<a>v\d+)" + r"(?: offset0:(?P<offset0>\d+))?(?: offset1:(?P<offset1>\d+))?", + rf"ds_(?P<op>{'|'.join(LDS_SHARED_ATOMICS)}) (?P<a>v\d+), (?P<b>v\d+)(?: offset:(?P<offset>\d+))?", +) + + +def vgpr_range(token, count): + """The VGPR numbers of `token` (vN or v[a:b]), which must name exactly `count` registers below v256.""" + m = re.fullmatch(r"v(\d+)|v\[(\d+):(\d+)\]", token) + first, last = (int(m[1]), int(m[1])) if m[1] else (int(m[2]), int(m[3])) + if last - first + 1 != count or last > 255 or (m[1] is None and count == 1): + raise ValueError("Unverified shared LDS register range") + return list(range(first, last + 1)) + + +def shared_lds_step(line, step, vector, words): + """HLSL statements for one gfx1013 DS instruction on `groupshared uint lds[]`; updates `vector` for reads. + + The byte address is the address VGPR plus the instruction offset (offset0/offset1 in elements of the access + size, times 64 for st64), and word i of the access is lds[(address >> 2) + i]. + + Input contract, not checked: every access is in bounds and aligned (b32 to 4 bytes, wider forms to their + size); every word a read or an atomic touches was written earlier in the group; and no two lanes of one + non-atomic write store to the same word. Outside the contract a word past the allocation reads as zero and + is not written, and the low two address bits are dropped. + """ + m = next((m for form in LDS_SHARED_FORMS if (m := re.fullmatch(form, line))), None) + if m is None: + raise ValueError(f"Unsupported shared LDS instruction: {line}") + op = m["op"] + # ds_read_bNN names its destination first; every other form names the address first. + addr, data = (m["b"], m["a"]) if op == "read" else (m["a"], m["b"]) + address = vector.get(int(addr[1:])) if re.fullmatch(r"v\d+", addr) else None + if not is_word(address) or int(addr[1:]) > 255: + raise ValueError("Unverified shared LDS address") + base = f"lds_a{step}" + statements = [] + + def place(offset): + statements.append(f" uint {base} = ({hlsl_word(address)} + {offset}u) >> 2u;") + + def words_of(token, count): + values = [vector.get(reg) for reg in vgpr_range(token, count)] + if not all(map(is_word, values)): + raise ValueError("Shared LDS data is not a known word") + return list(map(hlsl_word, values)) + + def write(index, word): + statements.append(f" if ({index} < {words}u) lds[{index}] = {word};") + + def read(index, reg, name): + statements.append(f" uint {name} = {index} < {words}u ? lds[{index}] : 0u;") + vector[reg] = ("alu", name) + + single = int(m["offset"] or 0) if "offset" in m.groupdict() else 0 + if single > 65535: + raise ValueError("Unverified shared LDS offset") + if op in LDS_SHARED_ATOMICS: + place(single) + (value,) = words_of(data, 1) + method = LDS_SHARED_ATOMICS[op] + if op == "sub_u32": + # mem - v == mem + ~v + 1 (mod 2^32), as two additions. One InterlockedAdd of (0u - v) on groupshared + # memory fails compute PSO creation with E_OUTOFMEMORY on NVIDIA GeForce RTX 5080 (driver + # 32.0.16.2124); DXC folds every spelling of the negation to `sub i32 0, v`. The update has no + # return value and the step ends with a barrier, so the intermediate word is never read. + statements.append(f" if ({base} < {words}u) InterlockedAdd(lds[{base}], ~({value}));") + value = "1u" + statements.append(f" if ({base} < {words}u) Interlocked{method}(lds[{base}], {value});") + return "\n".join(statements) + count = int(m["bits"]) // 32 + if op in ("write", "read"): + place(single) + indices = [f"{base} + {i}u" if i else base for i in range(count)] + if op == "write": + for index, word in zip(indices, words_of(data, count)): + write(index, word) + else: + for i, (index, reg) in enumerate(zip(indices, vgpr_range(data, count))): + read(index, reg, f"lds_r{step}_{i}") + return "\n".join(statements) + # Paired forms: two elements of `count` words at offset0 and offset1, in elements (64 elements for st64). + offsets = [int(m["offset0"] or 0), int(m["offset1"] or 0)] + if max(offsets) > 255 or offsets[0] == offsets[1]: + raise ValueError("Unverified shared LDS pair offsets") + scale = count * (64 if op.endswith("st64") else 1) + place(0) + indices = [f"{base} + {offset * scale + i}u" if offset * scale + i else base + for offset in offsets for i in range(count)] + if op.startswith("write"): + for index, word in zip(indices, words_of(m["b"], count) + words_of(m["c"], count)): + write(index, word) + else: + for i, (index, reg) in enumerate(zip(indices, vgpr_range(m["b"], 2 * count))): + read(index, reg, f"lds_r{step}_{i}") + return "\n".join(statements) + + MUBUF_ATOMIC_METHODS = { "add": "Add", "sub": "Add", "and": "And", "or": "Or", "xor": "Xor", "smin": "Min", "umin": "Min", "smax": "Max", "umax": "Max", "swap": "Exchange", "cmpswap": "CompareExchange", "inc": "CompareExchange", "dec": "CompareExchange", "csub": "CompareExchange", - "fmin": "CompareExchange", "fmax": "CompareExchange", + "fmin": "CompareExchange", "fmax": "CompareExchange", "fcmpswap": "CompareExchange", } IMAGE_FLOAT_ATOMIC_OPS = ("fcmpswap", "fmin", "fmax") -def float_min_max_cas(cas_prefix, value, op): - """Raw-word finite-normal binary32 min/max as an InterlockedCompareExchange loop. +def float_min_max_cas(cas_prefix, value, op, *, wide=False): + """Raw-word finite-normal binary32/binary64 min/max as an InterlockedCompareExchange loop. Shared by the image (texel) and MUBUF (byte-address) atomic profiles; cas_prefix is the call up to the opening parenthesis: the free intrinsic `InterlockedCompareExchange(dest)` for a texel destination and the raw UAV method `outputData.InterlockedCompareExchange(off)` for the byte-address destination. The caller guarantees every stored word and the operand - are finite-normal binary32, never NaN, subnormal or signed zero. The sign-dependent key + are finite normals, never NaN, subnormal or signed zero. The sign-dependent key orders those values exactly as unsigned integers, so integer CAS reproduces the fmin/fmax result bit-for-bit. The zero seed is outside the caller's domain and can only fetch the observed word; it never writes. """ comparison = "<" if op == "fmin" else ">" - return (f" uint value = {value};", - " uint valueKey = value ^ ((value & 0x80000000u) ? 0xffffffffu : 0x80000000u);", - " uint observed = 0u;", " uint expected;", + kind, zero, sign, mask = ("uint64_t", "0ull", "0x8000000000000000ull", "0xffffffffffffffffull") if wide else ( + "uint", "0u", "0x80000000u", "0xffffffffu") + return (f" {kind} value = {value};", + f" {kind} valueKey = value ^ ((value & {sign}) ? {mask} : {sign});", + f" {kind} observed = {zero};", f" {kind} expected;", " [allow_uav_condition] do {", " expected = observed;", - " uint oldKey = expected ^ ((expected & 0x80000000u) ? 0xffffffffu : 0x80000000u);", - f" uint next = (valueKey {comparison} oldKey) ? value : expected;", + f" {kind} oldKey = expected ^ ((expected & {sign}) ? {mask} : {sign});", + f" {kind} next = (valueKey {comparison} oldKey) ? value : expected;", f" {cas_prefix}, expected, next, observed);", " } while (observed != expected);") @@ -368,6 +490,29 @@ def float_word(token, scalar, vector, pending, sizes=None): return word +def float_e64_source(token, scalar, vector, pending): + """The HLSL word of a VOP3 binary32 source after its source modifiers, or None for an unknown word. + + LLVM prints the VOP3 source modifiers on a register as -v, |v| and -|v|. They act on the sign bit of the word: + abs clears bit 31, then neg flips it, as pixel_aot does for v_cvt_f64_f32_e64 and binary64 compare sources, so a + zero or NaN keeps its other bits. Modifiers on a constant (neg(0x...), |1.0|) and the abs() spelling are refused. + """ + m = re.fullmatch(r"(-?)(\|?)(s\d+|v\d+)(\|?)", token) + if not m and not re.fullmatch(FLOAT_SOURCE, token): + raise ValueError(f"Unsupported float source modifier: {token}") + if m and m[2] != m[4]: + raise ValueError(f"Unsupported float source modifier: {token}") + word = float_word(m[3] if m else token, scalar, vector, pending) + if word is None: + return None + expression = hlsl_word(word) + if m and m[2]: + expression = f"({expression} & 0x7fffffffu)" + if m and m[1]: + expression = f"({expression} ^ 0x80000000u)" + return expression + + def vector_operands(line): """VGPR numbers named by an instruction, single or as a range.""" regs = set() @@ -618,6 +763,11 @@ def descriptor_load_hlsl(): Every conversion is integer arithmetic, so the result does not depend on the GPU's float division. UNORM is x / (2^n - 1) and SNORM16 is max(x / 32767, -1), rounded to nearest even binary32 by long division. FLOAT16 widens exactly, keeping NaN payloads. 16-bit UINT and SINT zero- and sign-extend the low halfword. + + With d16 the channels pack two per result word, x in the low half. Float-type formats give binary16: the + FLOAT16 halves as stored, and UNORM and SNORM16 rounded to nearest even binary16 (denormals kept) by long + division. 16-bit UINT and SINT give the 16-bit integer, not a float. A 32-bit format has no d16 rule here and + is invalid. """ legacy = [] for field, code in sorted(LEGACY_DESCRIPTOR_FORMATS.items()): @@ -642,14 +792,32 @@ def descriptor_load_hlsl(): grouped = {} for code, (kind, channels) in DESCRIPTOR_STORE_FORMATS.items(): grouped.setdefault((kind, channels), []).append(code) + halves = { + "unorm8": ("h = uint4(descriptor_ratio16(raw.x & 0xffu, 255u), descriptor_ratio16((raw.x >> 8u) & 0xffu, 255u), " + "descriptor_ratio16((raw.x >> 16u) & 0xffu, 255u), descriptor_ratio16(raw.x >> 24u, 255u));"), + "unorm16x2": ("h.xy = uint2(descriptor_ratio16(raw.x & 0xffffu, 65535u), " + "descriptor_ratio16(raw.x >> 16u, 65535u));"), + "unorm10": ("h = uint4(descriptor_ratio16(raw.x & 0x3ffu, 1023u), " + "descriptor_ratio16((raw.x >> 10u) & 0x3ffu, 1023u), " + "descriptor_ratio16((raw.x >> 20u) & 0x3ffu, 1023u), descriptor_ratio16(raw.x >> 30u, 3u));"), + "f16x2": "h.xy = uint2(raw.x & 0xffffu, raw.x >> 16u);", + "f16x4": "h = uint4(raw.x & 0xffffu, raw.x >> 16u, raw.y & 0xffffu, raw.y >> 16u);", + "unorm16": "h.x = descriptor_ratio16(raw.x & 0xffffu, 65535u);", + "snorm16": "h.x = descriptor_snorm16_half(raw.x & 0xffffu);", + "uint16": "h.x = raw.x & 0xffffu;", + "sint16": "h.x = raw.x & 0xffffu;", + "f16": "h.x = raw.x & 0xffffu;", + } arms = [] - for kind in _DESCRIPTOR_KIND_ORDER: - for channels in range(1, 5): - codes = grouped.get((kind, channels)) - if codes: - test = " || ".join(f"format == {code}u" for code in sorted(codes)) - keyword = "if" if not arms else "else if" - arms.append(f" {keyword} (({test}) && channels == {channels}u) {{ {bodies[kind]} valid = true; }}") + for d16, table in ((False, bodies), (True, halves)): + for kind in _DESCRIPTOR_KIND_ORDER: + for channels in range(1, 5): + codes = grouped.get((kind, channels)) + if codes and kind in table: + test = " || ".join(f"format == {code}u" for code in sorted(codes)) + keyword = "if" if not arms else "else if" + arms.append(f" {keyword} (d16 {'!=' if d16 else '=='} 0u && ({test}) && channels == {channels}u) " + f"{{ {table[kind]} valid = true; }}") return ( "uint descriptor_ratio(uint x, uint d) {\n" " // binary32 bits of x / d for 0 <= x <= d < 2^16, rounded to nearest even by long division.\n" @@ -668,6 +836,31 @@ def descriptor_load_hlsl(): " if ((bits & 1u) != 0u && (r != 0u || (result & 1u) != 0u)) ++result;\n" " return result;\n" "}\n" + "uint descriptor_ratio16(uint x, uint d) {\n" + " // binary16 bits of x / d for 0 <= x <= d < 2^16, rounded to nearest even, denormals kept.\n" + " if (x == 0u) return 0u;\n" + " if (x == d) return 0x3c00u;\n" + " uint r = x, f = 0u;\n" + " for (uint i = 0u; i < 26u; ++i) {\n" + " r <<= 1u;\n" + " uint bit = r >= d ? 1u : 0u;\n" + " r -= bit * d;\n" + " f = (f << 1u) | bit;\n" + " }\n" + " // x / d = f / 2^26 plus a remainder. A normal result keeps 11 bits; a denormal counts units of 2^-24.\n" + " uint lead = firstbithigh(f);\n" + " uint shift = lead >= 12u ? lead - 10u : 2u;\n" + " uint result = lead >= 12u ? (((lead - 11u) << 10u) | ((f >> shift) & 0x3ffu)) : (f >> shift);\n" + " uint roundBit = (f >> (shift - 1u)) & 1u;\n" + " bool sticky = (f & ((1u << (shift - 1u)) - 1u)) != 0u || r != 0u;\n" + " if (roundBit != 0u && (sticky || (result & 1u) != 0u)) ++result;\n" + " return result;\n" + "}\n" + "uint descriptor_snorm16_half(uint bits16) {\n" + " int value = (int)(bits16 << 16u) >> 16;\n" + " if (value <= -32767) return 0xbc00u;\n" + " return value < 0 ? 0x8000u | descriptor_ratio16((uint)(-value), 32767u) : descriptor_ratio16((uint)value, 32767u);\n" + "}\n" "uint descriptor_snorm16_load(uint bits16) {\n" " int value = (int)(bits16 << 16u) >> 16;\n" " if (value <= -32767) return 0xbf800000u;\n" @@ -681,7 +874,7 @@ def descriptor_load_hlsl(): " uint top = firstbithigh(m);\n" " return sign | ((top + 103u) << 23u) | ((m << (23u - top)) & 0x7fffffu);\n" "}\n" - "uint4 load_descriptor_format(uint formatWord, uint addr, uint channels, out bool valid) {\n" + "uint4 load_descriptor_format(uint formatWord, uint addr, uint channels, uint d16, out bool valid) {\n" " valid = false;\n" f" uint fixedBits = formatWord & {DESCRIPTOR_FIXED_MASK:#x}u;\n" f" uint field = (formatWord >> {DESCRIPTOR_FORMAT_SHIFT}u) & {DESCRIPTOR_FORMAT_MASK:#x}u;\n" @@ -692,8 +885,9 @@ def descriptor_load_hlsl(): + "\n".join(legacy) + "\n" " }\n" " uint4 raw = inputData.Load4(addr);\n" - " uint4 r = uint4(0u, 0u, 0u, 0u);\n" + " uint4 r = uint4(0u, 0u, 0u, 0u), h = uint4(0u, 0u, 0u, 0u);\n" + "\n".join(arms) + "\n" + " if (d16 != 0u) r = uint4(h.x | (h.y << 16u), h.z | (h.w << 16u), 0u, 0u);\n" " return r;\n" "}\n" ) @@ -738,7 +932,7 @@ def heap_view_hlsl(table_offset, view_count, buffer_bytes): " inRange = inRange && instOffset + 4u * channels <= left - start;\n" " addr = v.x + start + instOffset;\n" " }\n" - " uint4 r = load_descriptor_format(v.w, inRange ? addr : 0u, channels, valid);\n" + " uint4 r = load_descriptor_format(v.w, inRange ? addr : 0u, channels, 0u, valid);\n" " return inRange ? r : zero;\n" "}\n" ) @@ -821,7 +1015,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N A full-mask 2D D16 image_store requires an RGBA16 FLOAT UAV. mubuf_d16_xyz_mode opts into a caller-verified W-preserving RGBA16 store. wave_size is the caller's statement that the program runs as wave32 (32). A lane index is only - derived for a group of more than 32 threads under that statement. + derived for a group of more than 32 threads under that statement. With group-shared LDS on gfx1013 + the statement may also be 64 (wave64), which lets a group of up to 64 threads count as one guest wave. image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for writes, where image_uav_mip selects the writable subresource and replaces descriptor_offset. @@ -832,9 +1027,10 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N and selects signed min/max. R32_FLOAT declares a native atomic image carried as raw words in a desktop R32_UINT UAV. The caller guarantees finite-normal binary32 in the accessed texels and operand VGPRs by setting image_float_domain="finite-normal". - A raw fixed-address buffer_atomic_fmin/fmax also requires the caller's - buffer_float_domain="finite-normal" statement: every stored word and the operand VGPR - hold finite-normal binary32, never NaN, subnormal or signed zero. + A raw fixed-address floating buffer atomic requires buffer_float_domain="finite-normal": + the caller guarantees finite-normal binary32 or binary64 at the accessed address and in the + operands, never NaN, subnormal or signed zero. For binary64 or compare-swap, the lowering + further requires finite-normal literal operands. gather_mips declares the visible mip count of matching gfx1013 RGBA32 FLOAT native and desktop 2D views at t0 for one image_gather4_l (see GATHER_HLSL). """ @@ -878,7 +1074,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unknown image SRV dimension") if image_srv_dimension == "1d" and not (rgba32_float_image and image_srv_descriptor is not None): raise ValueError("1D image loads require a separate gfx1013 RGBA32 FLOAT SRV binding") - # gfx1013 takes the shared image atomic lowering on an R32_UINT UAV only (add, umax, cmpswap; see lower()). + # gfx1013 takes the shared image atomic lowering on an R32_UINT UAV only + # (add, umin, umax, cmpswap; see lower()). gfx1013_image_atomic = cpu == "gfx1013" and image_atomic_type is not None and image_format == "R32_UINT" if image_output: if ((cpu != "gfx1030" and not float_image and not gfx1013_image_atomic) @@ -945,8 +1142,6 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if output_format is not None and (output_format not in MUBUF_OUTPUT_FORMATS or cpu != "gfx1030" or stride is None): raise ValueError("Unsupported formatted output binding") - if wave_size not in (None, 32): - raise ValueError("Unsupported wave size statement") if mubuf_d16_xyz_mode is not None and (mubuf_d16_xyz_mode != "preserve-w" or output_format != MUBUF_D16_OUTPUT_FORMATS[4] or cpu != "gfx1030"): raise ValueError("D16 XYZ mode requires a gfx1030 RGBA16 UINT output binding") @@ -1015,6 +1210,18 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N image_step_count = 0 image_uav_address = None lds_enabled = ds_group and 128 <= lds_bytes <= 65536 + # gfx1013 has no private LDS profile; an allocation there selects group-shared LDS. + shared_lds = cpu == "gfx1013" and lds_bytes != 0 + if shared_lds and not (4 <= lds_bytes <= LDS_SHARED_LIMIT and lds_bytes % 4 == 0): + raise ValueError("Invalid shared LDS allocation") + # wave64 is stated only for the one-wave shared LDS profile; elsewhere it is not a known lane layout. + if wave_size not in (None, 32) and not (wave_size == 64 and shared_lds): + raise ValueError("Unsupported wave size statement") + # Per-instruction group barriers give the group one wave's DS order. With several guest waves the order + # before s_barrier is not fixed by the program, so the profile is one wave: at most 32 threads is one wave + # of either width, and a larger group needs the wave64 statement. + if shared_lds and dims[0] * dims[1] * dims[2] > (wave_size or 32): + raise ValueError("Shared LDS requires a group of one guest wave") lds_word = None lds_strided_words = {} lds_strided_width = None @@ -1222,6 +1429,17 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if len(expression) > ALU_EXPRESSION_LIMIT: raise ValueError("ALU expression too large") scalar[dst] = ("alu", expression) + elif m := re.fullmatch(rf"(s_bitset[01]_b32) s(\d+), {SALU_SOURCE}", line): + # SOP1 s_bitset0_b32 and s_bitset1_b32 clear or set bit src0[4:0] of sD and keep its other bits, so sD + # is read as well as written: it must already hold a known word. SCC is not written. + op, dst = m[1], int(m[2]) + words = [alu_word(f"s{dst}", scalar, vector, pending, sizes), alu_word(m[3], scalar, vector, pending, sizes)] + if dst > 105 or dst in pending or None in words: + raise ValueError("Unverified scalar ALU operand") + expression = SALU[op].format(*map(hlsl_word, words)) + if len(expression) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + scalar[dst] = ("alu", expression) elif m := re.fullmatch(rf"s_cmp_(eq|lg)_([iu])32 {SALU_SOURCE}, {SALU_SOURCE}", line): # SCC = S0 == S1 (eq) or S0 != S1 (lg); the signedness does not change a 32-bit equality. words = [alu_word(token, scalar, vector, pending, sizes) for token in m.groups()[2:]] @@ -1546,6 +1764,10 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N and not alu_data_word(vector.get(int(m[3])))): dst, shift, src = map(int, m.groups()) tag = vector.get(src) + if shared_lds and dst <= 255 and shift <= 31 and isinstance(tag, tuple) and tag[0] == "local": + # A shared LDS byte address from the local ID; it is data only to the DS instructions below. + vector[dst] = ("alu", f"(local.{AXES[tag[1]]} << {shift}u)") + continue if ds_group and dst <= 255 and shift == 2 and isinstance(tag, tuple) and tag[0] == "ds_lane": vector[dst] = ("ds_address", tag[1]) continue @@ -1563,6 +1785,21 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if dst > 255 or not (isinstance(tag, tuple) and tag[0] == "thread"): raise ValueError("Unverified dispatch byte offset") vector[dst] = ("thread_bytes", tag[1], shift) + elif shared_lds and (line == "s_barrier" or line.startswith("ds_")): + # Group-shared LDS (issue #1541). Each DS instruction becomes HLSL statements on `lds`, followed by a + # group barrier, so the group observes DS operations in program order, as one wave does; s_barrier + # adds nothing beyond that and becomes the same barrier. Barriers need uniform control flow, so no + # DS instruction may follow a lane guard. + if guard_span is not None or guard is not None: + raise ValueError("Shared LDS access under a lane guard") + if line == "s_barrier": + if not staged_steps or not staged_steps[-1][1].endswith(LDS_BARRIER): + staged_steps.append((None, LDS_BARRIER)) + continue + text = shared_lds_step(line, ds_step_count, vector, lds_bytes // 4) + ds_step_count += 1 + staged_steps.append((None, text + "\n" + LDS_BARRIER)) + ds_wait = True elif m := re.fullmatch(r"ds_(b?permute)_b32 v(\d+), v(\d+), v(\d+)", line): op, dst, addr, src = m[1], *map(int, m.groups()[1:]) address = vector.get(addr) @@ -2098,11 +2335,27 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unverified plane byte offset") vector[dst] = ("plane_bytes", row_tag[1], shift, *column_tag[1:]) elif ((m := re.fullmatch(r"v_and_b32_e32 v(\d+), (?:0xffff|65535), v(\d+)", line)) - and isinstance(partial := vector.get(int(m[2])), tuple) and partial[0] == "source_low16"): + and isinstance(partial := vector.get(int(m[2])), tuple) and partial[0] in ("source_low16", "alu_low16")): dst = int(m[1]) if dst > 255: raise ValueError("Invalid vector destination") - vector[dst] = ("alu", f"(inputData.Load({partial[1]}) & 0xffffu)") + word = f"inputData.Load({partial[1]})" if partial[0] == "source_low16" else partial[1] + vector[dst] = ("alu", f"({word} & 0xffffu)") + elif ((m := re.fullmatch(r"(v_(?:add|sub|subrev|mul)_f32)_e64 v(\d+), ([^,\s]+), ([^,\s]+)( .+)?", line)) + and any(token.startswith(("-", "|", "neg(", "abs(")) and not re.fullmatch(FLOAT_SOURCE, token) + for token in m.groups()[2:4])): + # The VOP3 spelling with a source modifier on at least one source; either source is any binary32 source. + # The unmodified _e64 form is left to the fall-through. clamp and omod (mul:2, mul:4, div:2) are refused. + op, dst = m[1] + "_e32", int(m[2]) + if m[5]: + raise ValueError(f"Unsupported float output modifier: {line}") + sources = [float_e64_source(token, scalar, vector, pending) for token in m.groups()[2:4]] + if dst > 255 or None in sources: + raise ValueError("Unverified float operand") + expression = FALU[op].format(*sources) + if len(expression) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + vector[dst] = ("alu", expression) elif m := re.fullmatch(rf"(v_(?:add|sub|subrev|mul)_f32_e32) v(\d+), {FLOAT_SOURCE}, (v\d+)", line): op, dst = m[1], int(m[2]) words = [float_word(token, scalar, vector, pending, sizes) for token in m.groups()[2:]] @@ -2206,7 +2459,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N + (f"{result};" if bound else f"{inside} ? {result} : ({hlsl_word(values[2])});"))) vector[dst] = ("alu", value) elif ((m := re.fullmatch(rf"(v_(?:and_b32|lshrrev_b32|min_u32|max_u32|add_nc_u32|or_b32|xor_b32|lshlrev_b32|ashrrev_i32|sub_nc_u32|subrev_nc_u32)_e32) v(\d+), {ALU_SOURCE}, (v\d+)", line)) - or (m := re.fullmatch(rf"(v_mul_lo_u32|v_add_nc_i32|v_sub_nc_i32|v_bcnt_u32_b32) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) + or (m := re.fullmatch(rf"(v_mul_lo_u32|v_add_nc_i32|v_sub_nc_i32|v_bcnt_u32_b32|v_bfm_b32) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) or (m := re.fullmatch(rf"(v_mad_u32_u24|v_xor3_b32|v_max3_u32|v_min3_u32|v_med3_u32|v_med3_i32|v_mad_i32_i24) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}, {ALU_SOURCE}", line)) and None not in [alu_word(token, scalar, vector, pending, sizes) for token in m.groups()[2:]]): # VOP2 takes a VGPR as src1. A v_mad_u32_u24 with an address operand is a row pitch below. @@ -2218,6 +2471,16 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if len(expression) > ALU_EXPRESSION_LIMIT: raise ValueError("ALU expression too large") vector[dst] = ("alu", expression) + elif m := re.fullmatch(rf"(v_(?:bfrev_b32|ffbh_i32)_e32) v(\d+), {ALU_SOURCE}", line): + # VOP1 src0 is any source. The VOP3, SDWA and DPP spellings and source modifiers do not match. + op, dst = m[1], int(m[2]) + word = alu_word(m[3], scalar, vector, pending) + if dst > 255 or word is None: + raise ValueError("Unverified ALU operand") + expression = VOP1_ALU[op].format(hlsl_word(word)) + if len(expression) > ALU_EXPRESSION_LIMIT: + raise ValueError("ALU expression too large") + vector[dst] = ("alu", expression) elif ((m := re.fullmatch(rf"(v_sub(?:rev)?_co_u32) v(\d+), (vcc_lo|s\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) or (m := re.fullmatch(rf"(v_sub(?:rev)?_co_ci_u32_e32) v(\d+), (vcc_lo), {ALU_SOURCE}, (v\d+), (vcc_lo)", line)) or (m := re.fullmatch(rf"(v_sub(?:rev)?_co_ci_u32_e64) v(\d+), (vcc_lo|s\d+), {ALU_SOURCE}, {ALU_SOURCE}, (vcc_lo|s\d+)", line))): @@ -2357,8 +2620,6 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N descriptor_load = None if resource_channels and load_format_words is not None: # The format is V# word 3 from a constant word, decoded in the shader (descriptor_load_hlsl). - if packed: - raise ValueError("Descriptor-format d16 loads are not lowered") if not idxen or offen: raise ValueError("Unsupported formatted buffer read target or address mode") if format_load_index >= len(load_format_words): @@ -2436,15 +2697,19 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if descriptor_load is not None: result = f"format_load_{format_load_index - 1}" slot = hlsl_word(('constant_word', descriptor_load)) + if heap_view is not None and packed: + raise ValueError("D16 descriptor-format loads are not lowered through a heap view") call = (f"load_heap_view_format({slot}, tid.{AXES[tag[1]]}, {aligned}u, {components}u, " f"format_valid_{format_load_index - 1})" if heap_view is not None else - f"load_descriptor_format({slot}, {addresses[0]}, {components}u, " + f"load_descriptor_format({slot}, {addresses[0]}, {components}u, {int(packed)}u, " f"format_valid_{format_load_index - 1})") staged_steps.append((None, f" bool format_valid_{format_load_index - 1};\n" f" uint4 {result} = {call};")) for reg in range(dst, dst + count): vector.pop(reg, None) - loading[reg] = ("alu", f"{result}.{'xyzw'[reg - dst]}") + # An odd d16 count leaves the high half of the last word undefined, as for source_low16. + low16 = packed and components % 2 and reg == dst + count - 1 + loading[reg] = ("alu_low16" if low16 else "alu", f"{result}.{'xyzw'[reg - dst]}") continue # The address has been captured, so the index can alias a destination. for reg, address in enumerate(addresses, dst): @@ -2500,8 +2765,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N op = m["op"] signed = op in ("smin", "smax") # gfx1013 is limited to the forms its draws cover; the lowering itself is the gfx1030 one. - if cpu == "gfx1013" and op not in ("add", "umax", "cmpswap"): - raise ValueError("gfx1013 image atomics require add, umax or cmpswap") + if cpu == "gfx1013" and op not in ("add", "umin", "umax", "cmpswap"): + raise ValueError("gfx1013 image atomics require add, umin, umax or cmpswap") if (image_atomic_type != ("int" if signed else "uint") or image_float != (op in IMAGE_FLOAT_ATOMIC_OPS) or guard_span is not None or stores): raise ValueError("Unsupported image atomic target or binding") @@ -2766,6 +3031,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N r"s\[(?P<base>\d+):(?P<high>\d+)\], 0" r"(?P<idxen> idxen)?(?P<offen> offen)?(?: offset:(?P<offset>\d+))?(?P<glc> glc)?", line): op, wide, glc = m["op"], bool(m["wide"]), bool(m["glc"]) + floating = op in IMAGE_FLOAT_ATOMIC_OPS + float_extended = floating and (wide or op == "fcmpswap") fixed = m["addr"] == "off" and not (m["idxen"] or m["offen"]) if cpu == "gfx1030" and not fixed: raise ValueError(f"Unsupported compute instruction: {line}") @@ -2785,7 +3052,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unsupported atomic reduction target or binding: " "gfx1013 requires an unguarded raw-buffer program") else: - if op in ("fmin", "fmax") and (buffer_float_domain != "finite-normal" or wide or glc): + if float_extended and (buffer_float_domain != "finite-normal" or glc): + raise ValueError("Float buffer compare-swap and _x2 require a finite-normal domain and no glc") + if floating and not float_extended and (buffer_float_domain != "finite-normal" or glc): raise ValueError("buffer_atomic fmin/fmax require a finite-normal domain, " "a single 32-bit operand and no glc") if op == "csub" and (wide or not glc): @@ -2814,12 +3083,19 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N written_spans.append((offset, offset + 4)) src, *last = map(int, re.findall(r"\d+", m["data"])) width = 2 if wide else 1 - count = 2 * width if op == "cmpswap" else width + compare_swap = op in ("cmpswap", "fcmpswap") + count = 2 * width if compare_swap else width if last != ([src + count - 1] if count > 1 else []) or src + count > 256: raise ValueError("Unverified atomic reduction data range") values = [vector.get(reg) for reg in range(src, src + count)] if not all(is_word(value) for value in values): raise ValueError("Atomic reduction data is not a known word") + if float_extended: + shift, exponent = (20, 0x7ff) if wide else (23, 0xff) + if not all(isinstance(value, int) for value in values) or any( + ((high_word >> shift) & exponent) in (0, exponent) + for high_word in values[width - 1::width]): + raise ValueError("Float buffer atomic operands must be finite-normal constants") words = list(map(hlsl_word, values)) operands = ([f"(uint64_t({lo}) | (uint64_t({hi}) << 32u))" for lo, hi in zip(words[::2], words[1::2])] if wide else words) @@ -2832,14 +3108,12 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N # Raw UAV atomics on pairs require SM 6.6. kind = ("int64_t" if signed else "uint64_t") if wide else ("int" if signed else "uint") method = MUBUF_ATOMIC_METHODS[op] + ("64" if wide else "") - if op == "cmpswap": - # RDNA 2 MUBUF opcode 49 takes replacement in VDATA and compare in VDATA+1. - # HLSL takes compare first. + if compare_swap: + # RDNA 2 takes replacement first, then compare, each in one word or a pair. + # HLSL takes compare first. Finite-normal float equality is bit equality. word = f"{operands[1]}, {word}" if op in ("fmin", "fmax"): - # Raw-word finite-normal binary32 min/max on the raw UAV, under the caller's - # finite-normal domain statement. Reuses the image ordering. - stores.extend(float_min_max_cas(f"outputData.InterlockedCompareExchange({offset}u", word, op)) + stores.extend(float_min_max_cas(f"outputData.Interlocked{method}({offset}u", word, op, wide=wide)) elif op in ("inc", "dec", "csub"): one, zero = ("1ull", "0ull") if wide else ("1u", "0u") if op == "inc": @@ -2869,7 +3143,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if glc: loading[src] = ("alu", result) atomic_update = True - if op in ("fmin", "fmax"): + if floating: buffer_float_update = True elif m := re.fullmatch(r"(?:buffer_store_(?:dword(?:x(?P<raw_count>[234]))?|(?P<subword>byte|short)(?P<store_hi>_d16_hi)?)|" r"(?P<typed>t)?buffer_store_format_(?P<channels>(?:d16_)?(?:x|xy|xyz|xyzw))) " @@ -3106,6 +3380,10 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N cbuffer += "".join(f"groupshared uint {slot}[{dims[0]}];\n" for slot in shared) if shared: local = ", uint3 local : SV_GroupThreadID" + if "local." in body: + local = ", uint3 local : SV_GroupThreadID" + if shared_lds and ds_step_count: + cbuffer += f"groupshared uint lds[{lds_bytes // 4}];\n" if "gindex" in body: local += ", uint gindex : SV_GroupIndex" # Helpers are selected from the final body, so a float ALU result used only by a DS step still gets its definition. @@ -3194,10 +3472,11 @@ def main(): parser.add_argument("--image-float-domain", choices=("finite-normal",), help="Required for R32_FLOAT atomics. All accessed texels and operands are finite normals.") parser.add_argument("--buffer-float-domain", choices=("finite-normal",), - help="Required for raw fixed-address buffer_atomic_fmin/fmax. Every stored word " - "and the operand is finite-normal binary32, never NaN, subnormal or signed zero.") - parser.add_argument("--wave-size", type=int, choices=(32,), - help="Caller's statement that the program runs as wave32, for lane indices in larger groups") + help="Required for raw fixed-address floating buffer atomics. The stored value and " + "operands are finite-normal binary32 or binary64.") + parser.add_argument("--wave-size", type=int, choices=(32, 64), + help="Caller's statement of the wave width: 32 for lane indices in larger groups, " + "64 (gfx1013 shared LDS only) for a group of up to 64 threads as one wave") parser.add_argument("--gather-mips", type=int, help="Visible mip count of the matching native and desktop RGBA32 FLOAT 2D gather views") args = parser.parse_args() diff --git a/tools/coverage_svg.py b/tools/coverage_svg.py index cf3dbeb558..e90a51e0f2 100644 --- a/tools/coverage_svg.py +++ b/tools/coverage_svg.py @@ -104,7 +104,23 @@ def group(name, counts, x, y, w, h): return "".join(parts) + "</svg>", labelled +def _validate_counts(covered, total, scope: str) -> None: + if ( + isinstance(covered, bool) + or not isinstance(covered, int) + or isinstance(total, bool) + or not isinstance(total, int) + ): + raise TypeError(f"{scope} counts must be integers") + if total < 0 or covered < 0: + raise ValueError(f"{scope} counts must be non-negative") + if covered > total: + raise ValueError(f"{scope} covered count ({covered}) must not exceed total ({total})") + + def render(m, source): + if not isinstance(source, str) or not source.strip(): + raise ValueError("--source must not be empty") if not isinstance(m, dict): raise TypeError("coverage root must be a JSON object") rows = [text(20, 34, "Instruction-form coverage", 20, bold=True), text(20, 56, NOTE, 12, MUTED), @@ -119,6 +135,7 @@ def render(m, source): groups = r["groups"] if not isinstance(blocked, list) or not isinstance(groups, dict): raise TypeError(f"{key} entry has invalid blocked_by_skip or groups") + _validate_counts(r["covered"], r["total"], key) held = {} for form in blocked: if not isinstance(form, str): @@ -137,8 +154,7 @@ def render(m, source): raise TypeError(f"{key}.{g} must be a JSON object") total = v["total"] covered = v["covered"] - if total < 0 or covered < 0: - raise ValueError(f"{key}.{g} counts must be non-negative") + _validate_counts(covered, total, f"{key}.{g}") if total > 0: items.append((g, total)) items.sort(key=lambda kv: -kv[1]) @@ -180,6 +196,35 @@ def _write_atomic(path: Path, content: str) -> None: raise +def _same_path(left: Path, right: Path) -> bool: + if left == right: + return True + if left.exists() and right.exists() and left.samefile(right): + return True + try: + return left.resolve() == right.resolve() + except OSError: + return False + + +def _validate_paths(coverage: Path, output: Path) -> None: + if not coverage.exists(): + raise FileNotFoundError(f"coverage file not found: {coverage}") + if coverage.is_dir(): + raise IsADirectoryError(f"coverage path is a directory: {coverage}") + if not coverage.is_file(): + raise ValueError(f"coverage path must be a regular file: {coverage}") + if output.is_symlink(): + raise ValueError(f"output path must not be a symbolic link: {output}") + if output.exists() and output.is_dir(): + raise IsADirectoryError(f"output path is an existing directory: {output}") + for parent in output.parents: + if (parent.exists() or parent.is_symlink()) and not parent.is_dir(): + raise ValueError(f"output parent path is not a directory: {parent}") + if _same_path(output, coverage): + raise ValueError(f"output path must not match input path: {output}") + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("coverage", type=Path, help="JSON written by form_coverage.py --json") @@ -187,10 +232,9 @@ def main(argv=None) -> int: parser.add_argument("--source", required=True, help="commit, OS build and adapter of the measured run") args = parser.parse_args(argv) try: - coverage_path = args.coverage.resolve() - output_path = args.output.resolve() - if output_path == coverage_path: - raise ValueError(f"output path must not match input path: {args.output}") + if not args.source.strip(): + raise ValueError("--source must not be empty") + _validate_paths(args.coverage, args.output) svg = render(json.loads(args.coverage.read_text(encoding="utf-8")), args.source) _write_atomic(args.output, svg) except (OSError, ValueError, KeyError, TypeError) as exc: diff --git a/tools/cpu_adx_aot.py b/tools/cpu_adx_aot.py new file mode 100644 index 0000000000..762c27199a --- /dev/null +++ b/tools/cpu_adx_aot.py @@ -0,0 +1,693 @@ +"""Lift bounded Windows x64 leaf functions with ADX ADCX and ADOX to C++. + +Each export uses the straight-line leaf ABI: + std::uint64_t lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported ADX instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - ADCX r32, r/m32 | ADCX r64, r/m64 (dst = dst + src + CF; reads/writes ONLY CF; preserves OF/others) + - ADOX r32, r/m32 | ADOX r64, r/m64 (dst = dst + src + OF; reads/writes ONLY OF; preserves CF/others) + +32-bit destinations zero-extend into bits [63:32]. +Memory operands are flat zero-displacement [rcx|rdx|r8] loads read unconditionally via +load_always() so /O2 cannot drop faulting reads. + +Transport / flag-seeding & flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, movzx, xor, or, add, cmp, test, shl, stc, clc, + setb/setae/sete/setne/sets/setns/seto/setno/setp/setnp (reg or flat [r8]), flat [r8] stores, + and terminal ret. + +ADC/SBB, BMI1/BMI2, VEX/EVEX/XOP, nonvolatile GPRs, writes to argument GPRs (rcx/rdx/r8), +high-byte GPRs, undefined GPR or CF/OF/flag reads, displaced/indexed/non-flat memory operands, +stores outside [r8], instruction prefixes, branches/calls, and missing or trailing instructions +after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8", + R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", R.R8D: "r8", + R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", R.CX: "rcx", R.DX: "rdx", R.R8W: "r8", + R.R9W: "r9", R.R10W: "r10", R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", R.R8L: "r8", + R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (kind, width_bits, flag_name) +ADX_SPECS = { + Code.ADCX_R32_RM32: ("adcx", 32, "cf"), + Code.ADCX_R64_RM64: ("adcx", 64, "cf"), + Code.ADOX_R32_RM32: ("adox", 32, "of"), + Code.ADOX_R64_RM64: ("adox", 64, "of"), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_RM32_IMM32: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, + Code.XOR_RM64_IMM32: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_RM32_IMM32: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, + Code.OR_RM64_IMM32: 64, +} +ADD_WIDTHS = { + Code.ADD_R32_RM32: 32, + Code.ADD_RM32_R32: 32, + Code.ADD_RM32_IMM8: 32, + Code.ADD_RM32_IMM32: 32, + Code.ADD_R64_RM64: 64, + Code.ADD_RM64_R64: 64, + Code.ADD_RM64_IMM8: 64, + Code.ADD_RM64_IMM32: 64, +} +CMP_WIDTHS = { + Code.CMP_R32_RM32: 32, + Code.CMP_RM32_R32: 32, + Code.CMP_RM32_IMM8: 32, + Code.CMP_RM32_IMM32: 32, + Code.CMP_R64_RM64: 64, + Code.CMP_RM64_R64: 64, + Code.CMP_RM64_IMM8: 64, + Code.CMP_RM64_IMM32: 64, +} +TEST_WIDTHS = { + Code.TEST_RM32_R32: 32, + Code.TEST_RM32_IMM32: 32, + Code.TEST_RM64_R64: 64, + Code.TEST_RM64_IMM32: 64, +} +SHL_SPECS = { + Code.SHL_RM32_1: (32, True), + Code.SHL_RM32_IMM8: (32, False), + Code.SHL_RM64_1: (64, True), + Code.SHL_RM64_IMM8: (64, False), +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#if defined(_MSC_VER) +#include <intrin.h> +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template <class T> +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast<const void*>(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template <class T> +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast<std::uint8_t>(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(masked)); +} + +static inline word op_add(word lhs_w, word rhs_w, unsigned width, Flags& flags) { + if (width == 32u) { + const std::uint32_t a = static_cast<std::uint32_t>(lhs_w); + const std::uint32_t b = static_cast<std::uint32_t>(rhs_w); + const std::uint64_t sum64 = static_cast<std::uint64_t>(a) + static_cast<std::uint64_t>(b); + const std::uint32_t res = static_cast<std::uint32_t>(sum64); + flags.cf = (sum64 >> 32) != 0ull; + flags.of = (((a ^ res) & (b ^ res)) >> 31) != 0u; + flags.zf = res == 0u; + flags.sf = (res >> 31) != 0u; + flags.pf = parity_even(static_cast<std::uint8_t>(res)); + return static_cast<word>(res); + } + const word res = lhs_w + rhs_w; + flags.cf = res < lhs_w; + flags.of = (((lhs_w ^ res) & (rhs_w ^ res)) >> 63) != 0ull; + flags.zf = res == 0ull; + flags.sf = (res >> 63) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(res)); + return res; +} + +static inline void op_cmp(word lhs_w, word rhs_w, unsigned width, Flags& flags) { + if (width == 32u) { + const std::uint32_t a = static_cast<std::uint32_t>(lhs_w); + const std::uint32_t b = static_cast<std::uint32_t>(rhs_w); + const std::uint32_t diff = a - b; + flags.cf = a < b; + flags.of = (((a ^ b) & (a ^ diff)) >> 31) != 0u; + flags.zf = diff == 0u; + flags.sf = (diff >> 31) != 0u; + flags.pf = parity_even(static_cast<std::uint8_t>(diff)); + return; + } + const word diff = lhs_w - rhs_w; + flags.cf = lhs_w < rhs_w; + flags.of = (((lhs_w ^ rhs_w) & (lhs_w ^ diff)) >> 63) != 0ull; + flags.zf = diff == 0ull; + flags.sf = (diff >> 63) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(diff)); +} + +static inline word op_shl(word cur, unsigned width, unsigned count, Flags& flags) { + const unsigned mask = (width == 32u) ? 31u : 63u; + const unsigned c = count & mask; + if (width == 32u) { + const std::uint32_t v = static_cast<std::uint32_t>(cur); + if (c == 0u) return static_cast<word>(v); + const std::uint32_t r = v << c; + flags.cf = ((v >> (32u - c)) & 1u) != 0u; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((r >> 31) & 1u) != (flags.cf ? 1u : 0u)); + flags.pf = parity_even(static_cast<std::uint8_t>(r)); + return static_cast<word>(r); + } + if (c == 0u) return cur; + const word r = cur << c; + flags.cf = ((cur >> (64u - c)) & 1ull) != 0ull; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((r >> 63) & 1ull) != (flags.cf ? 1ull : 0ull)); + flags.pf = parity_even(static_cast<std::uint8_t>(r)); + return r; +} + +// --- Portable ADX ADCX / ADOX helpers (read/write ONLY their designated carry flag) --- + +static inline word op_adcx32(word dst_w, word src_w, Flags& flags) { + const std::uint32_t a = static_cast<std::uint32_t>(dst_w); + const std::uint32_t b = static_cast<std::uint32_t>(src_w); + const std::uint64_t sum = static_cast<std::uint64_t>(a) + static_cast<std::uint64_t>(b) + (flags.cf ? 1ull : 0ull); + flags.cf = (sum >> 32) != 0ull; + return sum & 0xFFFFFFFFull; +} + +static inline word op_adcx64(word dst_w, word src_w, Flags& flags) { + const word cin = flags.cf ? 1ull : 0ull; + const word sum = dst_w + src_w + cin; + flags.cf = (sum < dst_w) || (cin != 0ull && sum == dst_w); + return sum; +} + +static inline word op_adox32(word dst_w, word src_w, Flags& flags) { + const std::uint32_t a = static_cast<std::uint32_t>(dst_w); + const std::uint32_t b = static_cast<std::uint32_t>(src_w); + const std::uint64_t sum = static_cast<std::uint64_t>(a) + static_cast<std::uint64_t>(b) + (flags.of ? 1ull : 0ull); + flags.of = (sum >> 32) != 0ull; + return sum & 0xFFFFFFFFull; +} + +static inline word op_adox64(word dst_w, word src_w, Flags& flags) { + const word oin = flags.of ? 1ull : 0ull; + const word sum = dst_w + src_w + oin; + flags.of = (sum < dst_w) || (oin != 0ull && sum == dst_w); + return sum; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_adx() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast<std::uint32_t>(info[1]) & (1u << 19)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line ADX (ADCX/ADOX) leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast<word>(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in ADX_SPECS: + kind, width, flag_name = ADX_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + dst = check_dst_reg(0, ins, width, require_defined=True) + dst_expr = read_reg(0, ins, width) + src_expr = read_rm(1, ins, width) + statements.append(f"{dst} = op_{kind}{width}({dst_expr}, {src_expr}, flags);") + defined_gpr.add(dst) + defined_flags.add(flag_name) + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code == Code.STC: + statements.append("flags.cf = true;") + defined_flags.add("cf") + elif code == Code.CLC: + statements.append("flags.cf = false;") + defined_flags.add("cf") + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + rhs_expr = read_rm(1, ins, width) if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY) else f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + rhs_expr = read_rm(1, ins, width) if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY) else f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in ADD_WIDTHS: + width = ADD_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + rhs_expr = read_rm(1, ins, width) if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY) else f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = op_add({lhs_expr}, {rhs_expr}, {width}u, flags);") + defined_gpr.add(dst) + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in CMP_WIDTHS: + width = CMP_WIDTHS[code] + lhs_expr = read_rm(0, ins, width) + rhs_expr = read_rm(1, ins, width) if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY) else f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"op_cmp({lhs_expr}, {rhs_expr}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in TEST_WIDTHS: + width = TEST_WIDTHS[code] + lhs_expr = read_rm(0, ins, width) + rhs_expr = read_rm(1, ins, width) if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY) else f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"compute_logic_flags(({lhs_expr}) & ({rhs_expr}), {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SHL_SPECS: + width, is_one = SHL_SPECS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + cnt = 1 if is_one else (ins.immediate8 & 0xFF) + eff = cnt & (31 if width == 32 else 63) + statements.append(f"{dst} = op_shl({dst}, {width}u, {cnt}u, flags);") + if eff == 1: + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif eff > 1: + defined_flags = {"cf", "zf", "sf", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always<std::uint8_t>({addr}, static_cast<std::uint8_t>(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + decls.append(" (void)flags;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_aes_pclmul_aot.py b/tools/cpu_aes_pclmul_aot.py new file mode 100644 index 0000000000..50c09626a7 --- /dev/null +++ b/tools/cpu_aes_pclmul_aot.py @@ -0,0 +1,668 @@ +"""Lift bounded Windows x64 leaf functions with legacy SSE & VEX.128 AES-NI and PCLMULQDQ to C++. + +Each export uses the straight-line leaf ABI: + void lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned 16/32-byte buffers +(rcx and rdx are inputs, r8 is the output/in-out buffer). YMM0..YMM5 are modeled +as pure portable 256-bit value structs (four 64-bit lanes) with GF(2^8) AES tables/math +and GF(2) carryless multiplication (zero compiler intrinsics / zero <wmmintrin.h>). + +Supported AES-NI and PCLMULQDQ instructions (docs/coverage/x64_zen2.tsv groups AES/Crypto): + - Legacy SSE (preserves YMM_dst[255:128]): + AESENC, AESENCLAST, AESDEC, AESDECLAST, AESIMC, AESKEYGENASSIST, PCLMULQDQ + - VEX.128 (zeroes YMM_dst[255:128]): + VAESENC, VAESENCLAST, VAESDEC, VAESDECLAST, VAESIMC, VAESKEYGENASSIST, VPCLMULQDQ + +Transport / ABI glue: + - MOVDQA / MOVDQU (legacy 128-bit reg/flat-[rcx|rdx|r8] loads, [r8] stores, reg-reg copies; preserves YMM[255:128]) + - VMOVDQA / VMOVDQU (VEX.128 128-bit zeroes YMM[255:128]; VEX.256 256-bit move glue only) + - VZEROUPPER (zeroes YMM[255:128] of all defined XMMs) + - terminal RET + +VEX.256 compute ops (VAES*/VPCLMULQDQ on YMM), EVEX/XOP, nonvolatile XMM6-15/YMM6-15, +nonvolatile/unsupported GPRs, undefined XMM/YMM reads, displaced/indexed/RIP-relative/ +non-argument memory operands, stores outside [r8], instruction prefixes, branches, and +missing or trailing instructions after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (helper, arity, has_imm8, is_vex) +CRYPTO_SPECS = { + Code.AESENC_XMM_XMMM128: ("op_aesenc", 2, False, False), + Code.AESENCLAST_XMM_XMMM128: ("op_aesenclast", 2, False, False), + Code.AESDEC_XMM_XMMM128: ("op_aesdec", 2, False, False), + Code.AESDECLAST_XMM_XMMM128: ("op_aesdeclast", 2, False, False), + Code.AESIMC_XMM_XMMM128: ("op_aesimc", 1, False, False), + Code.AESKEYGENASSIST_XMM_XMMM128_IMM8: ("op_aeskeygenassist", 1, True, False), + Code.PCLMULQDQ_XMM_XMMM128_IMM8: ("op_pclmulqdq", 2, True, False), + Code.VEX_VAESENC_XMM_XMM_XMMM128: ("op_aesenc", 2, False, True), + Code.VEX_VAESENCLAST_XMM_XMM_XMMM128: ("op_aesenclast", 2, False, True), + Code.VEX_VAESDEC_XMM_XMM_XMMM128: ("op_aesdec", 2, False, True), + Code.VEX_VAESDECLAST_XMM_XMM_XMMM128: ("op_aesdeclast", 2, False, True), + Code.VEX_VAESIMC_XMM_XMMM128: ("op_aesimc", 1, False, True), + Code.VEX_VAESKEYGENASSIST_XMM_XMMM128_IMM8: ("op_aeskeygenassist", 1, True, True), + Code.VEX_VPCLMULQDQ_XMM_XMM_XMMM128_IMM8: ("op_pclmulqdq", 2, True, True), +} + +# (is_ymm, is_vex) +MOVE_LOAD_CODES = { + Code.MOVDQA_XMM_XMMM128: (False, False), + Code.MOVDQU_XMM_XMMM128: (False, False), + Code.VEX_VMOVDQA_XMM_XMMM128: (False, True), + Code.VEX_VMOVDQU_XMM_XMMM128: (False, True), + Code.VEX_VMOVDQA_YMM_YMMM256: (True, True), + Code.VEX_VMOVDQU_YMM_YMMM256: (True, True), +} +MOVE_STORE_CODES = { + Code.MOVDQA_XMMM128_XMM: (False, False), + Code.MOVDQU_XMMM128_XMM: (False, False), + Code.VEX_VMOVDQA_XMMM128_XMM: (False, True), + Code.VEX_VMOVDQU_XMMM128_XMM: (False, True), + Code.VEX_VMOVDQA_YMMM256_YMM: (True, True), + Code.VEX_VMOVDQU_YMMM256_YMM: (True, True), +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *CRYPTO_SPECS, + *MOVE_LOAD_CODES, + *MOVE_STORE_CODES, +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#if defined(_MSC_VER) +#include <intrin.h> +#endif + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_aes_pclmul_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 1) | (1 << 25) | (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} +#endif + +using word = std::uint64_t; + +struct Vec128 { + std::uint64_t q[2]; +}; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline Vec128 low128(const Vec256& v) { + return {{v.q[0], v.q[1]}}; +} + +static inline void set_low128(Vec256& dst, const Vec128& v) { + dst.q[0] = v.q[0]; + dst.q[1] = v.q[1]; +} + +static inline Vec256 zext256(const Vec128& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +static inline Vec128 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + Vec128 out{}; + std::memcpy(out.q, reinterpret_cast<const void*>(address), sizeof(out.q)); + const volatile std::uint64_t q0 = out.q[0]; + const volatile std::uint64_t q1 = out.q[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + Vec256 out{}; + std::memcpy(out.q, reinterpret_cast<const void*>(address), sizeof(out.q)); + const volatile std::uint64_t q0 = out.q[0]; + const volatile std::uint64_t q1 = out.q[1]; + const volatile std::uint64_t q2 = out.q[2]; + const volatile std::uint64_t q3 = out.q[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, sizeof(v.q)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, sizeof(v.q)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static constexpr std::uint8_t AES_SBOX[256] = { + 0x63u, 0x7Cu, 0x77u, 0x7Bu, 0xF2u, 0x6Bu, 0x6Fu, 0xC5u, 0x30u, 0x01u, 0x67u, 0x2Bu, 0xFEu, 0xD7u, 0xABu, 0x76u, + 0xCAu, 0x82u, 0xC9u, 0x7Du, 0xFAu, 0x59u, 0x47u, 0xF0u, 0xADu, 0xD4u, 0xA2u, 0xAFu, 0x9Cu, 0xA4u, 0x72u, 0xC0u, + 0xB7u, 0xFDu, 0x93u, 0x26u, 0x36u, 0x3Fu, 0xF7u, 0xCCu, 0x34u, 0xA5u, 0xE5u, 0xF1u, 0x71u, 0xD8u, 0x31u, 0x15u, + 0x04u, 0xC7u, 0x23u, 0xC3u, 0x18u, 0x96u, 0x05u, 0x9Au, 0x07u, 0x12u, 0x80u, 0xE2u, 0xEBu, 0x27u, 0xB2u, 0x75u, + 0x09u, 0x83u, 0x2Cu, 0x1Au, 0x1Bu, 0x6Eu, 0x5Au, 0xA0u, 0x52u, 0x3Bu, 0xD6u, 0xB3u, 0x29u, 0xE3u, 0x2Fu, 0x84u, + 0x53u, 0xD1u, 0x00u, 0xEDu, 0x20u, 0xFCu, 0xB1u, 0x5Bu, 0x6Au, 0xCBu, 0xBEu, 0x39u, 0x4Au, 0x4Cu, 0x58u, 0xCFu, + 0xD0u, 0xEFu, 0xAAu, 0xFBu, 0x43u, 0x4Du, 0x33u, 0x85u, 0x45u, 0xF9u, 0x02u, 0x7Fu, 0x50u, 0x3Cu, 0x9Fu, 0xA8u, + 0x51u, 0xA3u, 0x40u, 0x8Fu, 0x92u, 0x9Du, 0x38u, 0xF5u, 0xBCu, 0xB6u, 0xDAu, 0x21u, 0x10u, 0xFFu, 0xF3u, 0xD2u, + 0xCDu, 0x0Cu, 0x13u, 0xECu, 0x5Fu, 0x97u, 0x44u, 0x17u, 0xC4u, 0xA7u, 0x7Eu, 0x3Du, 0x64u, 0x5Du, 0x19u, 0x73u, + 0x60u, 0x81u, 0x4Fu, 0xDCu, 0x22u, 0x2Au, 0x90u, 0x88u, 0x46u, 0xEEu, 0xB8u, 0x14u, 0xDEu, 0x5Eu, 0x0Bu, 0xDBu, + 0xE0u, 0x32u, 0x3Au, 0x0Au, 0x49u, 0x06u, 0x24u, 0x5Cu, 0xC2u, 0xD3u, 0xACu, 0x62u, 0x91u, 0x95u, 0xE4u, 0x79u, + 0xE7u, 0xC8u, 0x37u, 0x6Du, 0x8Du, 0xD5u, 0x4Eu, 0xA9u, 0x6Cu, 0x56u, 0xF4u, 0xEAu, 0x65u, 0x7Au, 0xAEu, 0x08u, + 0xBAu, 0x78u, 0x25u, 0x2Eu, 0x1Cu, 0xA6u, 0xB4u, 0xC6u, 0xE8u, 0xDDu, 0x74u, 0x1Fu, 0x4Bu, 0xBDu, 0x8Bu, 0x8Au, + 0x70u, 0x3Eu, 0xB5u, 0x66u, 0x48u, 0x03u, 0xF6u, 0x0Eu, 0x61u, 0x35u, 0x57u, 0xB9u, 0x86u, 0xC1u, 0x1Du, 0x9Eu, + 0xE1u, 0xF8u, 0x98u, 0x11u, 0x69u, 0xD9u, 0x8Eu, 0x94u, 0x9Bu, 0x1Eu, 0x87u, 0xE9u, 0xCEu, 0x55u, 0x28u, 0xDFu, + 0x8Cu, 0xA1u, 0x89u, 0x0Du, 0xBFu, 0xE6u, 0x42u, 0x68u, 0x41u, 0x99u, 0x2Du, 0x0Fu, 0xB0u, 0x54u, 0xBBu, 0x16u, +}; + +static constexpr std::uint8_t AES_INV_SBOX[256] = { + 0x52u, 0x09u, 0x6Au, 0xD5u, 0x30u, 0x36u, 0xA5u, 0x38u, 0xBFu, 0x40u, 0xA3u, 0x9Eu, 0x81u, 0xF3u, 0xD7u, 0xFBu, + 0x7Cu, 0xE3u, 0x39u, 0x82u, 0x9Bu, 0x2Fu, 0xFFu, 0x87u, 0x34u, 0x8Eu, 0x43u, 0x44u, 0xC4u, 0xDEu, 0xE9u, 0xCBu, + 0x54u, 0x7Bu, 0x94u, 0x32u, 0xA6u, 0xC2u, 0x23u, 0x3Du, 0xEEu, 0x4Cu, 0x95u, 0x0Bu, 0x42u, 0xFAu, 0xC3u, 0x4Eu, + 0x08u, 0x2Eu, 0xA1u, 0x66u, 0x28u, 0xD9u, 0x24u, 0xB2u, 0x76u, 0x5Bu, 0xA2u, 0x49u, 0x6Du, 0x8Bu, 0xD1u, 0x25u, + 0x72u, 0xF8u, 0xF6u, 0x64u, 0x86u, 0x68u, 0x98u, 0x16u, 0xD4u, 0xA4u, 0x5Cu, 0xCCu, 0x5Du, 0x65u, 0xB6u, 0x92u, + 0x6Cu, 0x70u, 0x48u, 0x50u, 0xFDu, 0xEDu, 0xB9u, 0xDAu, 0x5Eu, 0x15u, 0x46u, 0x57u, 0xA7u, 0x8Du, 0x9Du, 0x84u, + 0x90u, 0xD8u, 0xABu, 0x00u, 0x8Cu, 0xBCu, 0xD3u, 0x0Au, 0xF7u, 0xE4u, 0x58u, 0x05u, 0xB8u, 0xB3u, 0x45u, 0x06u, + 0xD0u, 0x2Cu, 0x1Eu, 0x8Fu, 0xCAu, 0x3Fu, 0x0Fu, 0x02u, 0xC1u, 0xAFu, 0xBDu, 0x03u, 0x01u, 0x13u, 0x8Au, 0x6Bu, + 0x3Au, 0x91u, 0x11u, 0x41u, 0x4Fu, 0x67u, 0xDCu, 0xEAu, 0x97u, 0xF2u, 0xCFu, 0xCEu, 0xF0u, 0xB4u, 0xE6u, 0x73u, + 0x96u, 0xACu, 0x74u, 0x22u, 0xE7u, 0xADu, 0x35u, 0x85u, 0xE2u, 0xF9u, 0x37u, 0xE8u, 0x1Cu, 0x75u, 0xDFu, 0x6Eu, + 0x47u, 0xF1u, 0x1Au, 0x71u, 0x1Du, 0x29u, 0xC5u, 0x89u, 0x6Fu, 0xB7u, 0x62u, 0x0Eu, 0xAAu, 0x18u, 0xBEu, 0x1Bu, + 0xFCu, 0x56u, 0x3Eu, 0x4Bu, 0xC6u, 0xD2u, 0x79u, 0x20u, 0x9Au, 0xDBu, 0xC0u, 0xFEu, 0x78u, 0xCDu, 0x5Au, 0xF4u, + 0x1Fu, 0xDDu, 0xA8u, 0x33u, 0x88u, 0x07u, 0xC7u, 0x31u, 0xB1u, 0x12u, 0x10u, 0x59u, 0x27u, 0x80u, 0xECu, 0x5Fu, + 0x60u, 0x51u, 0x7Fu, 0xA9u, 0x19u, 0xB5u, 0x4Au, 0x0Du, 0x2Du, 0xE5u, 0x7Au, 0x9Fu, 0x93u, 0xC9u, 0x9Cu, 0xEFu, + 0xA0u, 0xE0u, 0x3Bu, 0x4Du, 0xAEu, 0x2Au, 0xF5u, 0xB0u, 0xC8u, 0xEBu, 0xBBu, 0x3Cu, 0x83u, 0x53u, 0x99u, 0x61u, + 0x17u, 0x2Bu, 0x04u, 0x7Eu, 0xBAu, 0x77u, 0xD6u, 0x26u, 0xE1u, 0x69u, 0x14u, 0x63u, 0x55u, 0x21u, 0x0Cu, 0x7Du, +}; + +static inline std::uint8_t aes_gf_mul(std::uint8_t a, std::uint8_t b) { + std::uint8_t p = 0u; + for (int i = 0; i < 8; ++i) { + if ((b & 1u) != 0u) { + p ^= a; + } + const bool hi = (a & 0x80u) != 0u; + a = static_cast<std::uint8_t>(a << 1); + if (hi) { + a ^= 0x1Bu; + } + b >>= 1; + } + return p; +} + +static inline void unpack_bytes(const Vec128& v, std::uint8_t out[16]) { + std::memcpy(out, v.q, 16); +} + +static inline Vec128 pack_bytes(const std::uint8_t in[16]) { + Vec128 v{}; + std::memcpy(v.q, in, 16); + return v; +} + +static inline Vec128 xor128(const Vec128& a, const Vec128& b) { + return {{a.q[0] ^ b.q[0], a.q[1] ^ b.q[1]}}; +} + +static inline void aes_shift_sub(const std::uint8_t in[16], std::uint8_t out[16]) { + static constexpr unsigned idx[16] = {0u, 5u, 10u, 15u, 4u, 9u, 14u, 3u, 8u, 13u, 2u, 7u, 12u, 1u, 6u, 11u}; + for (unsigned i = 0u; i < 16u; ++i) { + out[i] = AES_SBOX[in[idx[i]]]; + } +} + +static inline void aes_inv_shift_sub(const std::uint8_t in[16], std::uint8_t out[16]) { + static constexpr unsigned idx[16] = {0u, 13u, 10u, 7u, 4u, 1u, 14u, 11u, 8u, 5u, 2u, 15u, 12u, 9u, 6u, 3u}; + for (unsigned i = 0u; i < 16u; ++i) { + out[i] = AES_INV_SBOX[in[idx[i]]]; + } +} + +static inline void aes_mix_columns(const std::uint8_t in[16], std::uint8_t out[16]) { + for (unsigned c = 0u; c < 4u; ++c) { + const std::uint8_t a0 = in[c * 4u + 0u]; + const std::uint8_t a1 = in[c * 4u + 1u]; + const std::uint8_t a2 = in[c * 4u + 2u]; + const std::uint8_t a3 = in[c * 4u + 3u]; + out[c * 4u + 0u] = static_cast<std::uint8_t>(aes_gf_mul(2u, a0) ^ aes_gf_mul(3u, a1) ^ a2 ^ a3); + out[c * 4u + 1u] = static_cast<std::uint8_t>(a0 ^ aes_gf_mul(2u, a1) ^ aes_gf_mul(3u, a2) ^ a3); + out[c * 4u + 2u] = static_cast<std::uint8_t>(a0 ^ a1 ^ aes_gf_mul(2u, a2) ^ aes_gf_mul(3u, a3)); + out[c * 4u + 3u] = static_cast<std::uint8_t>(aes_gf_mul(3u, a0) ^ a1 ^ a2 ^ aes_gf_mul(2u, a3)); + } +} + +static inline void aes_inv_mix_columns(const std::uint8_t in[16], std::uint8_t out[16]) { + for (unsigned c = 0u; c < 4u; ++c) { + const std::uint8_t a0 = in[c * 4u + 0u]; + const std::uint8_t a1 = in[c * 4u + 1u]; + const std::uint8_t a2 = in[c * 4u + 2u]; + const std::uint8_t a3 = in[c * 4u + 3u]; + out[c * 4u + 0u] = static_cast<std::uint8_t>(aes_gf_mul(0x0Eu, a0) ^ aes_gf_mul(0x0Bu, a1) ^ aes_gf_mul(0x0Du, a2) ^ aes_gf_mul(0x09u, a3)); + out[c * 4u + 1u] = static_cast<std::uint8_t>(aes_gf_mul(0x09u, a0) ^ aes_gf_mul(0x0Eu, a1) ^ aes_gf_mul(0x0Bu, a2) ^ aes_gf_mul(0x0Du, a3)); + out[c * 4u + 2u] = static_cast<std::uint8_t>(aes_gf_mul(0x0Du, a0) ^ aes_gf_mul(0x09u, a1) ^ aes_gf_mul(0x0Eu, a2) ^ aes_gf_mul(0x0Bu, a3)); + out[c * 4u + 3u] = static_cast<std::uint8_t>(aes_gf_mul(0x0Bu, a0) ^ aes_gf_mul(0x0Du, a1) ^ aes_gf_mul(0x09u, a2) ^ aes_gf_mul(0x0Eu, a3)); + } +} + +static inline Vec128 op_aesenc(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}, mixed[16]{}; + unpack_bytes(state, b); + aes_shift_sub(b, tmp); + aes_mix_columns(tmp, mixed); + return xor128(pack_bytes(mixed), key); +} + +static inline Vec128 op_aesenclast(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}; + unpack_bytes(state, b); + aes_shift_sub(b, tmp); + return xor128(pack_bytes(tmp), key); +} + +static inline Vec128 op_aesdec(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}, mixed[16]{}; + unpack_bytes(state, b); + aes_inv_shift_sub(b, tmp); + aes_inv_mix_columns(tmp, mixed); + return xor128(pack_bytes(mixed), key); +} + +static inline Vec128 op_aesdeclast(const Vec128& state, const Vec128& key) { + std::uint8_t b[16]{}, tmp[16]{}; + unpack_bytes(state, b); + aes_inv_shift_sub(b, tmp); + return xor128(pack_bytes(tmp), key); +} + +static inline Vec128 op_aesimc(const Vec128& src) { + std::uint8_t b[16]{}, mixed[16]{}; + unpack_bytes(src, b); + aes_inv_mix_columns(b, mixed); + return pack_bytes(mixed); +} + +static inline std::uint32_t aes_sub_word(std::uint32_t w) { + return static_cast<std::uint32_t>(AES_SBOX[w & 0xFFu]) + | (static_cast<std::uint32_t>(AES_SBOX[(w >> 8) & 0xFFu]) << 8) + | (static_cast<std::uint32_t>(AES_SBOX[(w >> 16) & 0xFFu]) << 16) + | (static_cast<std::uint32_t>(AES_SBOX[(w >> 24) & 0xFFu]) << 24); +} + +static inline Vec128 op_aeskeygenassist(const Vec128& src, std::uint8_t imm8) { + std::uint32_t w[4]{}; + std::memcpy(w, src.q, 16); + const std::uint32_t s1 = aes_sub_word(w[1]); + const std::uint32_t s3 = aes_sub_word(w[3]); + const std::uint32_t rcon = static_cast<std::uint32_t>(imm8); + const std::uint32_t out[4] = { + s1, + ((s1 >> 8) | (s1 << 24)) ^ rcon, + s3, + ((s3 >> 8) | (s3 << 24)) ^ rcon, + }; + Vec128 res{}; + std::memcpy(res.q, out, 16); + return res; +} + +static inline Vec128 op_pclmulqdq(const Vec128& src1, const Vec128& src2, std::uint8_t imm8) { + const std::uint64_t a = ((imm8 & 0x01u) != 0u) ? src1.q[1] : src1.q[0]; + const std::uint64_t b = ((imm8 & 0x10u) != 0u) ? src2.q[1] : src2.q[0]; + std::uint64_t lo = 0ull; + std::uint64_t hi = 0ull; + for (unsigned i = 0u; i < 64u; ++i) { + if (((b >> i) & 1ull) != 0ull) { + lo ^= (a << i); + if (i != 0u) { + hi ^= (a >> (64u - i)); + } + } + } + return {{lo, hi}}; +} +""" + + +def vec_index(register, ins): + """Map volatile XMM0..XMM5/YMM0..YMM5 to (index, is_ymm), rejecting nonvolatile/unsupported.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register], False + if register in VOLATILE_YMM: + return VOLATILE_YMM[register], True + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, store=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AES-NI / PCLMULQDQ leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used_vec = set() + defined_xmm = set() + defined_ymm_hi = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, require_ymm=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx, wide = vec_index(ins.op_register(op_index), ins) + if wide != require_ymm: + raise ValueError(f"unexpected vector register width {ins.op_register(op_index)} at RVA {ins.ip:#x}: {ins}") + if idx not in defined_xmm or (require_ymm and idx not in defined_ymm_hi): + reg_label = f"ymm{idx}" if require_ymm else f"xmm{idx}" + raise ValueError(f"undefined vector register {reg_label} at RVA {ins.ip:#x}: {ins}") + used_vec.add(idx) + return f"ymm{idx}" if require_ymm else f"low128(ymm{idx})" + + def read_rm128(op_index, ins): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_vec(op_index, ins, require_ymm=False) + if kind == OpKind.MEMORY: + addr = flat_address(ins, 16, store=False) + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const Vec128 {load_var} = load128({addr});") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + def read_rm256(op_index, ins): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_vec(op_index, ins, require_ymm=True) + if kind == OpKind.MEMORY: + addr = flat_address(ins, 32, store=False) + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const Vec256 {load_var} = load256({addr});") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + def check_dst_vec(op_index, ins, *, expect_ymm=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx, wide = vec_index(ins.op_register(op_index), ins) + if wide != expect_ymm: + raise ValueError(f"unexpected vector destination width at RVA {ins.ip:#x}: {ins}") + used_vec.add(idx) + return idx + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ( + ins.has_lock_prefix + or ins.has_rep_prefix + or ins.has_repne_prefix + or ins.has_segment_prefix + or ins.has_xacquire_prefix + or ins.has_xrelease_prefix + ): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.VEX and op_code.l == 1 and ins.code not in ( + Code.VEX_VMOVDQA_YMM_YMMM256, + Code.VEX_VMOVDQA_YMMM256_YMM, + Code.VEX_VMOVDQU_YMM_YMMM256, + Code.VEX_VMOVDQU_YMMM256_YMM, + ): + raise ValueError(f"unsupported VEX.256 instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code == Code.RETNQ: + statements.append("return;") + returned = True + elif code == Code.VEX_VZEROUPPER: + for idx in sorted(defined_xmm): + statements.append(f"ymm{idx}.q[2] = 0ull;") + statements.append(f"ymm{idx}.q[3] = 0ull;") + defined_ymm_hi.add(idx) + elif code in CRYPTO_SPECS: + helper, arity, has_imm8, is_vex = CRYPTO_SPECS[code] + expected_enc = EncodingKind.VEX if is_vex else EncodingKind.LEGACY + if encoding != expected_enc: + raise ValueError(f"unexpected encoding for {helper} at RVA {ins.ip:#x}: {ins}") + if is_vex: + if arity == 2: + arg1 = read_vec(1, ins, require_ymm=False) + arg2 = read_rm128(2, ins) + args = [arg1, arg2] + else: + args = [read_rm128(1, ins)] + else: + if arity == 2: + arg1 = read_vec(0, ins, require_ymm=False) + arg2 = read_rm128(1, ins) + args = [arg1, arg2] + else: + args = [read_rm128(1, ins)] + if has_imm8: + imm8 = ins.immediate8 & 0xFF + args.append(f"{imm8:#x}u") + dst_idx = check_dst_vec(0, ins, expect_ymm=False) + call_expr = f"{helper}({', '.join(args)})" + if is_vex: + statements.append(f"ymm{dst_idx} = zext256({call_expr});") + defined_ymm_hi.add(dst_idx) + else: + statements.append(f"set_low128(ymm{dst_idx}, {call_expr});") + defined_xmm.add(dst_idx) + elif code in MOVE_LOAD_CODES: + is_ymm, is_vex = MOVE_LOAD_CODES[code] + if is_ymm: + src_expr = read_rm256(1, ins) + dst_idx = check_dst_vec(0, ins, expect_ymm=True) + statements.append(f"ymm{dst_idx} = {src_expr};") + defined_ymm_hi.add(dst_idx) + else: + src_expr = read_rm128(1, ins) + dst_idx = check_dst_vec(0, ins, expect_ymm=False) + if is_vex: + statements.append(f"ymm{dst_idx} = zext256({src_expr});") + defined_ymm_hi.add(dst_idx) + else: + statements.append(f"set_low128(ymm{dst_idx}, {src_expr});") + defined_xmm.add(dst_idx) + elif code in MOVE_STORE_CODES: + is_ymm, is_vex = MOVE_STORE_CODES[code] + src_expr = read_vec(1, ins, require_ymm=is_ymm) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 32 if is_ymm else 16, store=True) + fn = "store256" if is_ymm else "store128" + statements.append(f"{fn}({addr}, {src_expr});") + else: + dst_idx = check_dst_vec(0, ins, expect_ymm=is_ymm) + if is_ymm: + statements.append(f"ymm{dst_idx} = {src_expr};") + defined_ymm_hi.add(dst_idx) + elif is_vex: + statements.append(f"ymm{dst_idx} = zext256({src_expr});") + defined_ymm_hi.add(dst_idx) + else: + statements.append(f"set_low128(ymm{dst_idx}, {src_expr});") + defined_xmm.add(dst_idx) + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used_vec)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_amd_monitor_rdpru_aot.py b/tools/cpu_amd_monitor_rdpru_aot.py new file mode 100644 index 0000000000..e71ad79e84 --- /dev/null +++ b/tools/cpu_amd_monitor_rdpru_aot.py @@ -0,0 +1,809 @@ +"""Lift bounded Windows x64 leaf functions using AMD MONITORX, MWAITX, and RDPRU to C++. + +Each export uses the straight-line leaf ABI: + std::uint64_t lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat caller-owned 64-bit argument values/pointers +(r8 is the output buffer; stores are allowed only to [r8 + disp] within the +bounded 64-byte output slot). + +Supported AMD Zen 2 user-mode instructions (docs/coverage/x64_zen2.tsv group Integer): + - RDPRU (0F 01 FD): statically validates ECX in {0, 1} (0 = MPERF, 1 = APERF), + zero-extends EAX -> RAX and EDX -> RDX, preserves RCX and + RFLAGS, and resists /O2 CSE/DCE via volatile read + signal + fences. Bounded approximation: both selectors (0 and 1) map + to a serialized host RDTSC read (monotonic progression only; + does not return distinct hardware MPERF/APERF counter values). + - MONITORX (0F 01 FA): arms address-range monitor on flat caller-owned + [rcx|rdx|r8] linear address in RAX with ECX == 0 and + EDX == 0; probes address readability, preserves all GPRs + and RFLAGS, and prevents elision/reordering of + surrounding observable stores. + - MWAITX (0F 01 FB): hint-driven wait using defined RAX hints and statically + validated ECX extensions (0 or 1; ECX[1] timer mode is + rejected because it implicitly reads nonvolatile EBX, and + reserved bits ECX[31:2] are rejected); preserves all GPRs + and RFLAGS without eliding surrounding observable stores. + Bounded approximation: lowers to a fenced _mm_pause() + (an allowed early wake-up). + +Bounded volatile GPR transport (RAX, RCX, RDX, R8..R11 only): + - mov (reg-reg, reg-imm, [r8 + disp] 32/64-bit store) + - lea r64, [rcx|rdx|r8] (flat zero-displacement pointer copy) + - xor, or, shl, add, cmp (32/64-bit reg-reg / reg-imm with CF/ZF/SF/OF model) + - setb, sete, sets, seto (volatile 8-bit low GPRs; require defined flag & reg) + - terminal ret (requires defined RAX) + +MONITOR, MWAIT, RDTSC, RDTSCP, 16/32-bit MONITORX overrides, VEX/EVEX/non-legacy +encodings, vector/x87 instructions, nonvolatile GPRs (RBX, RBP, RSI, RDI, RSP, +R12..R15), undefined or out-of-range ECX on RDPRU, non-flat/unowned RAX or +undefined/non-zero ECX/EDX on MONITORX, undefined/timer/reserved ECX on MWAITX, +undefined GPR/flag reads, stores outside [r8], branches, prefixes, missing ret, +and trailing instructions after ret are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", + R.R8: "r8", R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", + R.R8D: "r8", R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", + R.R8L: "r8", R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} + +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +LEGACY_SYS_REJECT_CODES = { + Code.MONITORW, + Code.MONITORD, + Code.MONITORQ, + Code.MWAIT, + Code.RDTSC, + Code.RDTSCP, +} + +MONITORX_BAD_ADDR_CODES = { + Code.MONITORXW, + Code.MONITORXD, +} + +SETCC_CODES = { + Code.SETB_RM8: "cf", + Code.SETE_RM8: "zf", + Code.SETS_RM8: "sf", + Code.SETO_RM8: "of", +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.MONITORXQ, + Code.MWAITX, + Code.RDPRU, + # mov + Code.MOV_R64_RM64, + Code.MOV_RM64_R64, + Code.MOV_R64_IMM64, + Code.MOV_RM64_IMM32, + Code.MOV_R32_RM32, + Code.MOV_RM32_R32, + Code.MOV_R32_IMM32, + Code.MOV_RM32_IMM32, + # lea + Code.LEA_R64_M, + # xor + Code.XOR_R64_RM64, + Code.XOR_RM64_R64, + Code.XOR_RM64_IMM8, + Code.XOR_RM64_IMM32, + Code.XOR_RAX_IMM32, + Code.XOR_R32_RM32, + Code.XOR_RM32_R32, + Code.XOR_RM32_IMM8, + Code.XOR_RM32_IMM32, + Code.XOR_EAX_IMM32, + # or + Code.OR_R64_RM64, + Code.OR_RM64_R64, + Code.OR_RM64_IMM8, + Code.OR_RM64_IMM32, + Code.OR_RAX_IMM32, + Code.OR_R32_RM32, + Code.OR_RM32_R32, + Code.OR_RM32_IMM8, + Code.OR_RM32_IMM32, + Code.OR_EAX_IMM32, + # shl + Code.SHL_RM64_1, + Code.SHL_RM64_IMM8, + Code.SHL_RM32_1, + Code.SHL_RM32_IMM8, + # add + Code.ADD_R64_RM64, + Code.ADD_RM64_R64, + Code.ADD_RM64_IMM8, + Code.ADD_RM64_IMM32, + Code.ADD_RAX_IMM32, + Code.ADD_R32_RM32, + Code.ADD_RM32_R32, + Code.ADD_RM32_IMM8, + Code.ADD_RM32_IMM32, + Code.ADD_EAX_IMM32, + # cmp + Code.CMP_R64_RM64, + Code.CMP_RM64_R64, + Code.CMP_RM64_IMM8, + Code.CMP_RM64_IMM32, + Code.CMP_RAX_IMM32, + Code.CMP_R32_RM32, + Code.CMP_RM32_R32, + Code.CMP_RM32_IMM8, + Code.CMP_RM32_IMM32, + Code.CMP_EAX_IMM32, + # setcc + *SETCC_CODES, +} + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +MAX_OUT_BYTES = 64 + + +PRELUDE = r"""#include <atomic> +#include <cstdint> +#include <cstring> +#if defined(_MSC_VER) +#include <emmintrin.h> +#include <intrin.h> +#endif + +#if defined(_MSC_VER) +// Host AMD CPUID feature probes: +// MWAITX: CPUID Fn8000_0001_ECX[29] +// RDPRU : CPUID Fn8000_0008_EBX[4] +extern "C" __declspec(dllexport) std::uint32_t host_has_mwaitx() { + int info[4]{}; + __cpuid(info, static_cast<int>(0x80000000u)); + if (static_cast<std::uint32_t>(info[0]) < 0x80000001u) return 0u; + __cpuid(info, static_cast<int>(0x80000001u)); + return (static_cast<std::uint32_t>(info[2]) & (1u << 29)) != 0u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_has_rdpru() { + int info[4]{}; + __cpuid(info, static_cast<int>(0x80000000u)); + if (static_cast<std::uint32_t>(info[0]) < 0x80000008u) return 0u; + __cpuid(info, static_cast<int>(0x80000008u)); + return (static_cast<std::uint32_t>(info[1]) & (1u << 4)) != 0u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint64_t host_serial_tsc() { + _mm_lfence(); + const volatile std::uint64_t t = __rdtsc(); + _mm_lfence(); + return t; +} +#endif + +using word = std::uint64_t; + +static inline void store32(word address, std::uint32_t value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &value, sizeof(value)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &value, sizeof(value)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +// RDPRU bounded approximation: ECX (0 = MPERF, 1 = APERF) is statically validated, +// and both selectors map to a serialized host RDTSC read (monotonic only, not true +// hardware MPERF/APERF). The volatile capture and signal fences prevent /O2 from +// CSE-merging consecutive reads or DCE-eliminating overwritten reads. +static inline std::uint64_t op_rdpru_read(std::uint32_t selector) { + (void)selector; + std::atomic_signal_fence(std::memory_order_seq_cst); +#if defined(_MSC_VER) + const volatile std::uint64_t counter = __rdtsc(); +#else + std::uint32_t lo = 0u, hi = 0u; + __asm__ __volatile__("rdtsc" : "=a"(lo), "=d"(hi)); + const volatile std::uint64_t counter = (static_cast<std::uint64_t>(hi) << 32) | lo; +#endif + std::atomic_signal_fence(std::memory_order_seq_cst); + return counter; +} + +// MONITORX: probes readability of the flat linear address (preserving #PF fault +// semantics and surrounding store ordering) without modifying memory, GPRs, or RFLAGS. +static inline void op_monitorx(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const volatile std::uint8_t armed = *reinterpret_cast<const volatile std::uint8_t*>(address); + (void)armed; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +// MWAITX bounded approximation: lowers to a fenced _mm_pause() (an allowed early +// wake-up; ECX in {0, 1}; timer mode ECX[1] rejected at lift time). Preserves all +// GPRs and RFLAGS and keeps surrounding observable stores ordered. +static inline void op_mwaitx(std::uint32_t hints, std::uint32_t extensions) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const volatile std::uint32_t observed = hints ^ (extensions << 16); + (void)observed; +#if defined(_MSC_VER) + _mm_pause(); +#endif + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint64_t op_add64(std::uint64_t a, std::uint64_t b, bool& cf, bool& zf, bool& sf, bool& of) { + const std::uint64_t r = a + b; + cf = r < a; + zf = r == 0ull; + sf = (r >> 63) != 0ull; + of = (((~(a ^ b)) & (a ^ r)) >> 63) != 0ull; + return r; +} + +static inline std::uint64_t op_add32(std::uint64_t a64, std::uint64_t b64, bool& cf, bool& zf, bool& sf, bool& of) { + const std::uint32_t a = static_cast<std::uint32_t>(a64); + const std::uint32_t b = static_cast<std::uint32_t>(b64); + const std::uint32_t r = a + b; + cf = r < a; + zf = r == 0u; + sf = (r >> 31) != 0u; + of = (((~(a ^ b)) & (a ^ r)) >> 31) != 0u; + return static_cast<std::uint64_t>(r); +} + +static inline void op_cmp64(std::uint64_t a, std::uint64_t b, bool& cf, bool& zf, bool& sf, bool& of) { + const std::uint64_t r = a - b; + cf = a < b; + zf = r == 0ull; + sf = (r >> 63) != 0ull; + of = (((a ^ b) & (a ^ r)) >> 63) != 0ull; +} + +static inline void op_cmp32(std::uint64_t a64, std::uint64_t b64, bool& cf, bool& zf, bool& sf, bool& of) { + const std::uint32_t a = static_cast<std::uint32_t>(a64); + const std::uint32_t b = static_cast<std::uint32_t>(b64); + const std::uint32_t r = a - b; + cf = a < b; + zf = r == 0u; + sf = (r >> 31) != 0u; + of = (((a ^ b) & (a ^ r)) >> 31) != 0u; +} + +static inline std::uint64_t op_logic64(std::uint64_t r, bool& cf, bool& zf, bool& sf, bool& of) { + cf = false; + of = false; + zf = r == 0ull; + sf = (r >> 63) != 0ull; + return r; +} + +static inline std::uint64_t op_logic32(std::uint32_t r, bool& cf, bool& zf, bool& sf, bool& of) { + cf = false; + of = false; + zf = r == 0u; + sf = (r >> 31) != 0u; + return static_cast<std::uint64_t>(r); +} + +static inline std::uint64_t op_shl64(std::uint64_t a, unsigned count, bool& cf, bool& zf, bool& sf, bool& of) { + count &= 63u; + if (count == 0u) return a; + const std::uint64_t r = a << count; + cf = ((a >> (64u - count)) & 1ull) != 0ull; + zf = r == 0ull; + sf = (r >> 63) != 0ull; + if (count == 1u) of = ((r >> 63) != 0ull) != cf; + return r; +} + +static inline std::uint64_t op_shl32(std::uint64_t a64, unsigned count, bool& cf, bool& zf, bool& sf, bool& of) { + const std::uint32_t a = static_cast<std::uint32_t>(a64); + count &= 31u; + if (count == 0u) return static_cast<std::uint64_t>(a); + const std::uint32_t r = a << count; + cf = ((a >> (32u - count)) & 1u) != 0u; + zf = r == 0u; + sf = (r >> 31) != 0u; + if (count == 1u) of = ((r >> 31) != 0u) != cf; + return static_cast<std::uint64_t>(r); +} +""" + + +def _check_reg_class(reg, table, ins): + if reg in table: + return table[reg] + if reg in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {reg} at RVA {ins.ip:#x}: {ins}") + if RegisterExt.is_vector_register(reg): + raise ValueError(f"unsupported vector register {reg} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported register {reg} at RVA {ins.ip:#x}: {ins}") + + +def _store_r8_address(ins, width): + """Lower a flat [r8 + disp] output store within [0, MAX_OUT_BYTES - width].""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base != R.R8: + raise ValueError(f"store outside output buffer r8 at RVA {ins.ip:#x}: {ins}") + if MemorySizeExt.size(ins.memory_size) != width: + raise ValueError(f"unsupported memory width at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & MASK64 + if disp > MAX_OUT_BYTES - width: + raise ValueError(f"out-of-buffer store displacement {disp:#x} at RVA {ins.ip:#x}: {ins}") + return f"(r8 + {disp:#x}ull)" if disp else "r8" + + +def _lea_flat_base(ins): + """Lower a flat zero-displacement [rcx|rdx|r8] LEA address.""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported lea memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in lea at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported lea base {base} at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & MASK64 + if disp != 0: + raise ValueError(f"unsupported displaced lea operand at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def _imm_value(ins, op_index, *, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & MASK32 + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & MASK64 + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & MASK32 + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & MASK64 + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & MASK64 + raise ValueError(f"unsupported immediate kind {kind} at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AMD MONITORX/MWAITX/RDPRU leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined = {"rcx", "rdx", "r8"} + const_val = {} + flat_ptr = {"rcx", "rdx", "r8"} + used_temps = set() + flags_defined = set() + used_flags = False + statements = [] + returned = False + + def mark_reg(reg_name): + if reg_name not in ("rcx", "rdx", "r8"): + used_temps.add(reg_name) + + def read_reg(op_index, table, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + rname = _check_reg_class(ins.op_register(op_index), table, ins) + if rname not in defined: + raise ValueError(f"undefined register {rname} at RVA {ins.ip:#x}: {ins}") + mark_reg(rname) + return rname + + def write_reg(op_index, table, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + rname = _check_reg_class(ins.op_register(op_index), table, ins) + mark_reg(rname) + return rname + + def kill_provenance(rname): + const_val.pop(rname, None) + flat_ptr.discard(rname) + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ( + ins.has_lock_prefix + or ins.has_rep_prefix + or ins.has_repne_prefix + or ins.has_segment_prefix + or ins.has_xacquire_prefix + or ins.has_xrelease_prefix + ): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + op_code = ins.op_code() + if ( + op_code.encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding != EncodingKind.LEGACY: + raise ValueError(f"unsupported non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code in LEGACY_SYS_REJECT_CODES: + raise ValueError(f"unsupported legacy monitor/mwait/rdtsc instruction at RVA {ins.ip:#x}: {ins}") + if ins.code in MONITORX_BAD_ADDR_CODES: + raise ValueError(f"unsupported non-64-bit monitorx address size at RVA {ins.ip:#x}: {ins}") + if ins.flow_control not in (FlowControl.NEXT, FlowControl.RETURN): + raise ValueError(f"unsupported control-flow instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + code = ins.code + + if code == Code.RETNQ: + if "rax" not in defined: + raise ValueError(f"undefined return register rax at ret RVA {ins.ip:#x}") + mark_reg("rax") + statements.append("return rax;") + returned = True + + elif code == Code.RDPRU: + if "rcx" not in defined: + raise ValueError(f"undefined ECX for rdpru at RVA {ins.ip:#x}") + if "rcx" not in const_val: + raise ValueError(f"non-constant/unproven ECX for rdpru at RVA {ins.ip:#x}") + sel = const_val["rcx"] & MASK32 + if sel not in (0, 1): + raise ValueError(f"out-of-range ECX={sel:#x} for rdpru at RVA {ins.ip:#x}") + mark_reg("rax") + statements.append( + f"{{ const std::uint64_t pru = op_rdpru_read({sel}u); " + f"rax = static_cast<std::uint32_t>(pru); rdx = pru >> 32; }}" + ) + defined.add("rax") + defined.add("rdx") + kill_provenance("rax") + kill_provenance("rdx") + + elif code == Code.MONITORXQ: + if "rax" not in defined or "rax" not in flat_ptr: + raise ValueError(f"non-flat or unowned RAX address for monitorx at RVA {ins.ip:#x}") + if "rcx" not in defined or "rcx" not in const_val or (const_val["rcx"] & MASK32) != 0: + raise ValueError(f"undefined or non-zero ECX for monitorx at RVA {ins.ip:#x}") + if "rdx" not in defined or "rdx" not in const_val or (const_val["rdx"] & MASK32) != 0: + raise ValueError(f"undefined or non-zero EDX for monitorx at RVA {ins.ip:#x}") + mark_reg("rax") + statements.append("op_monitorx(rax);") + + elif code == Code.MWAITX: + if "rax" not in defined: + raise ValueError(f"undefined RAX hints for mwaitx at RVA {ins.ip:#x}") + if "rcx" not in defined or "rcx" not in const_val: + raise ValueError(f"undefined or non-constant ECX extensions for mwaitx at RVA {ins.ip:#x}") + ext = const_val["rcx"] & MASK32 + if ext & 0x2: + raise ValueError( + f"unsupported MWAITX timer extension ECX[1] (requires nonvolatile EBX) at RVA {ins.ip:#x}" + ) + if ext & ~0x3: + raise ValueError(f"unsupported reserved MWAITX extension bits ECX={ext:#x} at RVA {ins.ip:#x}") + mark_reg("rax") + statements.append(f"op_mwaitx(static_cast<std::uint32_t>(rax), {ext}u);") + + elif code == Code.LEA_R64_M: + dst = write_reg(0, VOLATILE_GPR64, ins) + src_base = _lea_flat_base(ins) + if src_base not in defined: + raise ValueError(f"undefined lea base {src_base} at RVA {ins.ip:#x}: {ins}") + statements.append(f"{dst} = {src_base};") + defined.add(dst) + kill_provenance(dst) + if src_base in flat_ptr: + flat_ptr.add(dst) + if src_base in const_val: + const_val[dst] = const_val[src_base] + + elif code in (Code.MOV_R64_RM64, Code.MOV_RM64_R64): + if ins.op0_kind == OpKind.MEMORY: + src = read_reg(1, VOLATILE_GPR64, ins) + addr = _store_r8_address(ins, 8) + statements.append(f"store64({addr}, {src});") + elif ins.op1_kind == OpKind.MEMORY: + raise ValueError(f"unsupported memory load at RVA {ins.ip:#x}: {ins}") + else: + src = read_reg(1, VOLATILE_GPR64, ins) + dst = write_reg(0, VOLATILE_GPR64, ins) + statements.append(f"{dst} = {src};") + defined.add(dst) + if src in const_val: + const_val[dst] = const_val[src] + else: + const_val.pop(dst, None) + if src in flat_ptr: + flat_ptr.add(dst) + else: + flat_ptr.discard(dst) + + elif code in (Code.MOV_R64_IMM64, Code.MOV_RM64_IMM32): + if ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported memory immediate store at RVA {ins.ip:#x}: {ins}") + dst = write_reg(0, VOLATILE_GPR64, ins) + imm = _imm_value(ins, 1, width=64) + statements.append(f"{dst} = {imm:#x}ull;") + defined.add(dst) + flat_ptr.discard(dst) + const_val[dst] = imm + + elif code in (Code.MOV_R32_RM32, Code.MOV_RM32_R32): + if ins.op0_kind == OpKind.MEMORY: + src = read_reg(1, VOLATILE_GPR32, ins) + addr = _store_r8_address(ins, 4) + statements.append(f"store32({addr}, static_cast<std::uint32_t>({src}));") + elif ins.op1_kind == OpKind.MEMORY: + raise ValueError(f"unsupported memory load at RVA {ins.ip:#x}: {ins}") + else: + src = read_reg(1, VOLATILE_GPR32, ins) + dst = write_reg(0, VOLATILE_GPR32, ins) + statements.append(f"{dst} = static_cast<std::uint32_t>({src});") + defined.add(dst) + flat_ptr.discard(dst) + if src in const_val: + const_val[dst] = const_val[src] & MASK32 + else: + const_val.pop(dst, None) + + elif code in (Code.MOV_R32_IMM32, Code.MOV_RM32_IMM32): + if ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported memory immediate store at RVA {ins.ip:#x}: {ins}") + dst = write_reg(0, VOLATILE_GPR32, ins) + imm = _imm_value(ins, 1, width=32) + statements.append(f"{dst} = {imm:#x}ull;") + defined.add(dst) + flat_ptr.discard(dst) + const_val[dst] = imm + + elif code in ( + Code.XOR_R64_RM64, Code.XOR_RM64_R64, Code.XOR_RM64_IMM8, Code.XOR_RM64_IMM32, Code.XOR_RAX_IMM32, + Code.XOR_R32_RM32, Code.XOR_RM32_R32, Code.XOR_RM32_IMM8, Code.XOR_RM32_IMM32, Code.XOR_EAX_IMM32, + ): + is64 = code in (Code.XOR_R64_RM64, Code.XOR_RM64_R64, Code.XOR_RM64_IMM8, Code.XOR_RM64_IMM32, Code.XOR_RAX_IMM32) + table = VOLATILE_GPR64 if is64 else VOLATILE_GPR32 + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind == OpKind.MEMORY: + raise ValueError(f"unsupported memory xor at RVA {ins.ip:#x}: {ins}") + used_flags = True + flags_defined = {"cf", "zf", "sf", "of"} + if ins.op1_kind == OpKind.REGISTER and ins.op0_register == ins.op1_register: + dst = write_reg(0, table, ins) + statements.append(f"{dst} = op_logic{'64' if is64 else '32'}(0u, cf, zf, sf, of);") + defined.add(dst) + flat_ptr.discard(dst) + const_val[dst] = 0 + else: + dst = read_reg(0, table, ins) + if ins.op1_kind == OpKind.REGISTER: + src = read_reg(1, table, ins) + src_expr = src if is64 else f"static_cast<std::uint32_t>({src})" + src_c = const_val.get(src) + else: + imm = _imm_value(ins, 1, width=64 if is64 else 32) + src_expr = f"{imm:#x}ull" if is64 else f"{imm:#x}u" + src_c = imm + dst_expr = dst if is64 else f"static_cast<std::uint32_t>({dst})" + statements.append(f"{dst} = op_logic{'64' if is64 else '32'}({dst_expr} ^ {src_expr}, cf, zf, sf, of);") + flat_ptr.discard(dst) + if dst in const_val and src_c is not None: + const_val[dst] = (const_val[dst] ^ src_c) & (MASK64 if is64 else MASK32) + else: + const_val.pop(dst, None) + + elif code in ( + Code.OR_R64_RM64, Code.OR_RM64_R64, Code.OR_RM64_IMM8, Code.OR_RM64_IMM32, Code.OR_RAX_IMM32, + Code.OR_R32_RM32, Code.OR_RM32_R32, Code.OR_RM32_IMM8, Code.OR_RM32_IMM32, Code.OR_EAX_IMM32, + ): + is64 = code in (Code.OR_R64_RM64, Code.OR_RM64_R64, Code.OR_RM64_IMM8, Code.OR_RM64_IMM32, Code.OR_RAX_IMM32) + table = VOLATILE_GPR64 if is64 else VOLATILE_GPR32 + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind == OpKind.MEMORY: + raise ValueError(f"unsupported memory or at RVA {ins.ip:#x}: {ins}") + used_flags = True + flags_defined = {"cf", "zf", "sf", "of"} + dst = read_reg(0, table, ins) + if ins.op1_kind == OpKind.REGISTER: + src = read_reg(1, table, ins) + src_expr = src if is64 else f"static_cast<std::uint32_t>({src})" + src_c = const_val.get(src) + else: + imm = _imm_value(ins, 1, width=64 if is64 else 32) + src_expr = f"{imm:#x}ull" if is64 else f"{imm:#x}u" + src_c = imm + dst_expr = dst if is64 else f"static_cast<std::uint32_t>({dst})" + statements.append(f"{dst} = op_logic{'64' if is64 else '32'}({dst_expr} | {src_expr}, cf, zf, sf, of);") + flat_ptr.discard(dst) + if dst in const_val and src_c is not None: + const_val[dst] = (const_val[dst] | src_c) & (MASK64 if is64 else MASK32) + else: + const_val.pop(dst, None) + + elif code in (Code.SHL_RM64_1, Code.SHL_RM64_IMM8, Code.SHL_RM32_1, Code.SHL_RM32_IMM8): + is64 = code in (Code.SHL_RM64_1, Code.SHL_RM64_IMM8) + table = VOLATILE_GPR64 if is64 else VOLATILE_GPR32 + if ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported memory shl at RVA {ins.ip:#x}: {ins}") + dst = read_reg(0, table, ins) + cnt = 1 if code in (Code.SHL_RM64_1, Code.SHL_RM32_1) else (ins.immediate8 & 0xFF) + eff = cnt & (63 if is64 else 31) + used_flags = True + statements.append(f"{dst} = op_shl{'64' if is64 else '32'}({dst}, {cnt}u, cf, zf, sf, of);") + if eff == 1: + flags_defined = {"cf", "zf", "sf", "of"} + elif eff > 1: + flags_defined = {"cf", "zf", "sf"} + flat_ptr.discard(dst) + if dst in const_val: + mask = MASK64 if is64 else MASK32 + const_val[dst] = ((const_val[dst] & mask) << eff) & mask + + elif code in ( + Code.ADD_R64_RM64, Code.ADD_RM64_R64, Code.ADD_RM64_IMM8, Code.ADD_RM64_IMM32, Code.ADD_RAX_IMM32, + Code.ADD_R32_RM32, Code.ADD_RM32_R32, Code.ADD_RM32_IMM8, Code.ADD_RM32_IMM32, Code.ADD_EAX_IMM32, + ): + is64 = code in (Code.ADD_R64_RM64, Code.ADD_RM64_R64, Code.ADD_RM64_IMM8, Code.ADD_RM64_IMM32, Code.ADD_RAX_IMM32) + table = VOLATILE_GPR64 if is64 else VOLATILE_GPR32 + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind == OpKind.MEMORY: + raise ValueError(f"unsupported memory add at RVA {ins.ip:#x}: {ins}") + used_flags = True + flags_defined = {"cf", "zf", "sf", "of"} + dst = read_reg(0, table, ins) + if ins.op1_kind == OpKind.REGISTER: + src = read_reg(1, table, ins) + src_expr = src + src_c = const_val.get(src) + else: + imm = _imm_value(ins, 1, width=64 if is64 else 32) + src_expr = f"{imm:#x}ull" + src_c = imm + statements.append(f"{dst} = op_add{'64' if is64 else '32'}({dst}, {src_expr}, cf, zf, sf, of);") + flat_ptr.discard(dst) + if dst in const_val and src_c is not None: + const_val[dst] = (const_val[dst] + src_c) & (MASK64 if is64 else MASK32) + else: + const_val.pop(dst, None) + + elif code in ( + Code.CMP_R64_RM64, Code.CMP_RM64_R64, Code.CMP_RM64_IMM8, Code.CMP_RM64_IMM32, Code.CMP_RAX_IMM32, + Code.CMP_R32_RM32, Code.CMP_RM32_R32, Code.CMP_RM32_IMM8, Code.CMP_RM32_IMM32, Code.CMP_EAX_IMM32, + ): + is64 = code in (Code.CMP_R64_RM64, Code.CMP_RM64_R64, Code.CMP_RM64_IMM8, Code.CMP_RM64_IMM32, Code.CMP_RAX_IMM32) + table = VOLATILE_GPR64 if is64 else VOLATILE_GPR32 + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind == OpKind.MEMORY: + raise ValueError(f"unsupported memory cmp at RVA {ins.ip:#x}: {ins}") + used_flags = True + flags_defined = {"cf", "zf", "sf", "of"} + lhs = read_reg(0, table, ins) + if ins.op1_kind == OpKind.REGISTER: + rhs_expr = read_reg(1, table, ins) + else: + imm = _imm_value(ins, 1, width=64 if is64 else 32) + rhs_expr = f"{imm:#x}ull" + statements.append(f"op_cmp{'64' if is64 else '32'}({lhs}, {rhs_expr}, cf, zf, sf, of);") + + elif code in SETCC_CODES: + if ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported memory setcc at RVA {ins.ip:#x}: {ins}") + flag = SETCC_CODES[code] + if flag not in flags_defined: + raise ValueError(f"undefined flag {flag} read at RVA {ins.ip:#x}: {ins}") + dst = read_reg(0, VOLATILE_GPR8, ins) + used_flags = True + statements.append(f"{dst} = ({dst} & ~0xffull) | ({flag} ? 1ull : 0ull);") + kill_provenance(dst) + + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" word {reg} = 0ull;" for reg in sorted(used_temps)] + if used_flags: + decls.append(" bool cf = false, zf = false, sf = false, of = false;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, args.exports.split(",")) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") diff --git a/tools/cpu_avx_cmp_aot.py b/tools/cpu_avx_cmp_aot.py new file mode 100644 index 0000000000..1e9bbf03af --- /dev/null +++ b/tools/cpu_avx_cmp_aot.py @@ -0,0 +1,630 @@ +"""Lift bounded Windows x64 leaf functions with AVX VEX FP compare instructions to C++. + +Each export uses the straight-line leaf ABI: + void lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. YMM0..YMM5 +are modeled as portable 256-bit value structs (four 64-bit lanes); every VEX.128 +write to XMM0..XMM5 zeroes bits [255:128] of the corresponding YMM register. + +Supported AVX FP compare encodings (docs/coverage/x64_zen2.tsv group AVX): + - VCMPPS: VEX.128 (xmm, xmm, xmm/m128, imm8) and VEX.256 (ymm, ymm, ymm/m256, imm8) + - VCMPPD: VEX.128 (xmm, xmm, xmm/m128, imm8) and VEX.256 (ymm, ymm, ymm/m256, imm8) + - VCMPSS: VEX.128 scalar f32 (xmm, xmm, xmm/m32, imm8), preserving src1[127:32] + - VCMPSD: VEX.128 scalar f64 (xmm, xmm, xmm/m64, imm8), preserving src1[127:64] +All 32 5-bit predicates (imm8 & 0x1F) are modeled via baseline SSE2 comparisons +on volatile operand copies (preventing fast-math folding while preserving +0.0 == -0.0, ++/-Inf, qNaN/sNaN, MXCSR DAZ, and quiet vs signaling NaN exception behavior). + +Transport / ABI glue: + - VMOVAPS, VMOVAPD, VMOVUPS, VMOVUPD (128/256-bit reg-reg, flat [rcx|rdx|r8] loads, + and flat [r8] stores) + - VMOVSS, VMOVSD (scalar reg-reg merge, flat [rcx|rdx|r8] load, flat [r8] store) + - VZEROUPPER and terminal RET. + +EVEX encodings, legacy SSE forms (CMPPS/CMPPD/CMPSS/CMPSD/MOVAPS/etc.), nonvolatile +vector registers (XMM6..15/YMM6..15), undefined vector reads, displaced or non-flat +memory operands, non-[r8] stores, instruction prefixes, branches, and trailing or +missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +# (helper_name, is_ymm, mem_size, is_scalar, is_double) +VCMP_CODES = { + Code.VEX_VCMPPS_XMM_XMM_XMMM128_IMM8: ("op_vcmpps", False, 16, False, False), + Code.VEX_VCMPPS_YMM_YMM_YMMM256_IMM8: ("op_vcmpps", True, 32, False, False), + Code.VEX_VCMPPD_XMM_XMM_XMMM128_IMM8: ("op_vcmppd", False, 16, False, True), + Code.VEX_VCMPPD_YMM_YMM_YMMM256_IMM8: ("op_vcmppd", True, 32, False, True), + Code.VEX_VCMPSS_XMM_XMM_XMMM32_IMM8: ("op_vcmpss", False, 4, True, False), + Code.VEX_VCMPSD_XMM_XMM_XMMM64_IMM8: ("op_vcmpsd", False, 8, True, True), +} + +# is_ymm for full-width VEX FP moves +VEC_MOVE_CODES = { + Code.VEX_VMOVAPS_XMM_XMMM128: False, + Code.VEX_VMOVAPS_XMMM128_XMM: False, + Code.VEX_VMOVAPS_YMM_YMMM256: True, + Code.VEX_VMOVAPS_YMMM256_YMM: True, + Code.VEX_VMOVAPD_XMM_XMMM128: False, + Code.VEX_VMOVAPD_XMMM128_XMM: False, + Code.VEX_VMOVAPD_YMM_YMMM256: True, + Code.VEX_VMOVAPD_YMMM256_YMM: True, + Code.VEX_VMOVUPS_XMM_XMMM128: False, + Code.VEX_VMOVUPS_XMMM128_XMM: False, + Code.VEX_VMOVUPS_YMM_YMMM256: True, + Code.VEX_VMOVUPS_YMMM256_YMM: True, + Code.VEX_VMOVUPD_XMM_XMMM128: False, + Code.VEX_VMOVUPD_XMMM128_XMM: False, + Code.VEX_VMOVUPD_YMM_YMMM256: True, + Code.VEX_VMOVUPD_YMMM256_YMM: True, +} + +VMOVSS_REG_CODES = { + Code.VEX_VMOVSS_XMM_XMM_XMM, + Code.VEX_VMOVSS_XMM_XMM_XMM_0F11, +} +VMOVSD_REG_CODES = { + Code.VEX_VMOVSD_XMM_XMM_XMM, + Code.VEX_VMOVSD_XMM_XMM_XMM_0F11, +} +SCALAR_MOVE_CODES = { + Code.VEX_VMOVSS_XMM_M32, + Code.VEX_VMOVSS_M32_XMM, + *VMOVSS_REG_CODES, + Code.VEX_VMOVSD_XMM_M64, + Code.VEX_VMOVSD_M64_XMM, + *VMOVSD_REG_CODES, +} + +LEGACY_SSE_REJECT_CODES = { + Code.CMPPS_XMM_XMMM128_IMM8, + Code.CMPPD_XMM_XMMM128_IMM8, + Code.CMPSS_XMM_XMMM32_IMM8, + Code.CMPSD_XMM_XMMM64_IMM8, + Code.MOVAPS_XMM_XMMM128, + Code.MOVAPS_XMMM128_XMM, + Code.MOVAPD_XMM_XMMM128, + Code.MOVAPD_XMMM128_XMM, + Code.MOVUPS_XMM_XMMM128, + Code.MOVUPS_XMMM128_XMM, + Code.MOVUPD_XMM_XMMM128, + Code.MOVUPD_XMMM128_XMM, + Code.MOVSS_XMM_XMMM32, + Code.MOVSS_XMMM32_XMM, + Code.MOVSD_XMM_XMMM64, + Code.MOVSD_XMMM64_XMM, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *VCMP_CODES, + *VEC_MOVE_CODES, + *SCALAR_MOVE_CODES, +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#include <emmintrin.h> +#if defined(_MSC_VER) +#include <intrin.h> +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline std::uint32_t load32(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint32_t v = *reinterpret_cast<const volatile std::uint32_t X2W_UNALIGNED*>(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline std::uint64_t load64(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint64_t v = *reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline Vec256 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, 0ull, 0ull}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + const std::uint64_t q2 = p[2]; + const std::uint64_t q3 = p[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store32(word address, std::uint32_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &val, 4); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &val, 8); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store128(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, 32); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline Vec256 copy128(const Vec256& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +static inline std::uint32_t lane32(const Vec256& v, unsigned i) { + return static_cast<std::uint32_t>(v.q[i >> 1] >> ((i & 1u) * 32u)); +} + +static inline void set_lane32(Vec256& v, unsigned i, std::uint32_t val) { + const unsigned shift = (i & 1u) * 32u; + v.q[i >> 1] = (v.q[i >> 1] & ~(0xffffffffull << shift)) | (static_cast<std::uint64_t>(val) << shift); +} + +// Model all 32 AVX FP compare predicates (imm8 & 0x1F) using baseline SSE2 scalar operations +// on volatile operand copies so /O2 cannot fast-math fold +0/-0, Inf, NaN, DAZ, or IE signaling. +static inline std::uint32_t cmp_f32_scalar(std::uint32_t a, std::uint32_t b, std::uint8_t pred) { + const volatile std::uint32_t va = a; + const volatile std::uint32_t vb = b; + const __m128 x = _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast<int>(va))); + const __m128 y = _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast<int>(vb))); + __m128 r; + switch (pred & 0x1fu) { + case 0x00u: r = _mm_cmpeq_ss(x, y); break; + case 0x01u: r = _mm_cmplt_ss(x, y); break; + case 0x02u: r = _mm_cmple_ss(x, y); break; + case 0x03u: r = _mm_cmpunord_ss(x, y); break; + case 0x04u: r = _mm_cmpneq_ss(x, y); break; + case 0x05u: r = _mm_cmpnlt_ss(x, y); break; + case 0x06u: r = _mm_cmpnle_ss(x, y); break; + case 0x07u: r = _mm_cmpord_ss(x, y); break; + case 0x08u: r = _mm_or_ps(_mm_cmpeq_ss(x, y), _mm_cmpunord_ss(x, y)); break; + case 0x09u: r = _mm_cmpnle_ss(y, x); break; + case 0x0au: r = _mm_cmpnlt_ss(y, x); break; + case 0x0bu: { const volatile __m128 t = _mm_cmpeq_ss(x, y); (void)t; return 0u; } + case 0x0cu: r = _mm_and_ps(_mm_cmpneq_ss(x, y), _mm_cmpord_ss(x, y)); break; + case 0x0du: r = _mm_cmple_ss(y, x); break; + case 0x0eu: r = _mm_cmplt_ss(y, x); break; + case 0x0fu: { const volatile __m128 t = _mm_cmpeq_ss(x, y); (void)t; return 0xffffffffu; } + case 0x10u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpeq_ss(x, y); break; } + case 0x11u: return _mm_ucomigt_ss(y, x) ? 0xffffffffu : 0u; + case 0x12u: return _mm_ucomige_ss(y, x) ? 0xffffffffu : 0u; + case 0x13u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpunord_ss(x, y); break; } + case 0x14u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpneq_ss(x, y); break; } + case 0x15u: return _mm_ucomigt_ss(y, x) ? 0u : 0xffffffffu; + case 0x16u: return _mm_ucomige_ss(y, x) ? 0u : 0xffffffffu; + case 0x17u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_cmpord_ss(x, y); break; } + case 0x18u: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_or_ps(_mm_cmpeq_ss(x, y), _mm_cmpunord_ss(x, y)); break; } + case 0x19u: return _mm_ucomige_ss(x, y) ? 0u : 0xffffffffu; + case 0x1au: return _mm_ucomigt_ss(x, y) ? 0u : 0xffffffffu; + case 0x1bu: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; return 0u; } + case 0x1cu: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; r = _mm_and_ps(_mm_cmpneq_ss(x, y), _mm_cmpord_ss(x, y)); break; } + case 0x1du: return _mm_ucomige_ss(x, y) ? 0xffffffffu : 0u; + case 0x1eu: return _mm_ucomigt_ss(x, y) ? 0xffffffffu : 0u; + default: { const volatile __m128 t = _mm_cmplt_ss(x, y); (void)t; return 0xffffffffu; } + } + return static_cast<std::uint32_t>(_mm_cvtsi128_si32(_mm_castps_si128(r))); +} + +static inline std::uint64_t cmp_f64_scalar(std::uint64_t a, std::uint64_t b, std::uint8_t pred) { + const volatile std::uint64_t va = a; + const volatile std::uint64_t vb = b; + const __m128d x = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast<long long>(va))); + const __m128d y = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast<long long>(vb))); + __m128d r; + switch (pred & 0x1fu) { + case 0x00u: r = _mm_cmpeq_sd(x, y); break; + case 0x01u: r = _mm_cmplt_sd(x, y); break; + case 0x02u: r = _mm_cmple_sd(x, y); break; + case 0x03u: r = _mm_cmpunord_sd(x, y); break; + case 0x04u: r = _mm_cmpneq_sd(x, y); break; + case 0x05u: r = _mm_cmpnlt_sd(x, y); break; + case 0x06u: r = _mm_cmpnle_sd(x, y); break; + case 0x07u: r = _mm_cmpord_sd(x, y); break; + case 0x08u: r = _mm_or_pd(_mm_cmpeq_sd(x, y), _mm_cmpunord_sd(x, y)); break; + case 0x09u: r = _mm_cmpnle_sd(y, x); break; + case 0x0au: r = _mm_cmpnlt_sd(y, x); break; + case 0x0bu: { const volatile __m128d t = _mm_cmpeq_sd(x, y); (void)t; return 0ull; } + case 0x0cu: r = _mm_and_pd(_mm_cmpneq_sd(x, y), _mm_cmpord_sd(x, y)); break; + case 0x0du: r = _mm_cmple_sd(y, x); break; + case 0x0eu: r = _mm_cmplt_sd(y, x); break; + case 0x0fu: { const volatile __m128d t = _mm_cmpeq_sd(x, y); (void)t; return 0xffffffffffffffffull; } + case 0x10u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpeq_sd(x, y); break; } + case 0x11u: return _mm_ucomigt_sd(y, x) ? 0xffffffffffffffffull : 0ull; + case 0x12u: return _mm_ucomige_sd(y, x) ? 0xffffffffffffffffull : 0ull; + case 0x13u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpunord_sd(x, y); break; } + case 0x14u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpneq_sd(x, y); break; } + case 0x15u: return _mm_ucomigt_sd(y, x) ? 0ull : 0xffffffffffffffffull; + case 0x16u: return _mm_ucomige_sd(y, x) ? 0ull : 0xffffffffffffffffull; + case 0x17u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_cmpord_sd(x, y); break; } + case 0x18u: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_or_pd(_mm_cmpeq_sd(x, y), _mm_cmpunord_sd(x, y)); break; } + case 0x19u: return _mm_ucomige_sd(x, y) ? 0ull : 0xffffffffffffffffull; + case 0x1au: return _mm_ucomigt_sd(x, y) ? 0ull : 0xffffffffffffffffull; + case 0x1bu: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; return 0ull; } + case 0x1cu: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; r = _mm_and_pd(_mm_cmpneq_sd(x, y), _mm_cmpord_sd(x, y)); break; } + case 0x1du: return _mm_ucomige_sd(x, y) ? 0xffffffffffffffffull : 0ull; + case 0x1eu: return _mm_ucomigt_sd(x, y) ? 0xffffffffffffffffull : 0ull; + default: { const volatile __m128d t = _mm_cmplt_sd(x, y); (void)t; return 0xffffffffffffffffull; } + } + return static_cast<std::uint64_t>(_mm_cvtsi128_si64(_mm_castpd_si128(r))); +} + +static inline Vec256 op_vcmpps(const Vec256& a, const Vec256& b, std::uint8_t pred, bool wide) { + Vec256 out{}; + const unsigned count = wide ? 8u : 4u; + for (unsigned i = 0; i < count; ++i) { + set_lane32(out, i, cmp_f32_scalar(lane32(a, i), lane32(b, i), pred)); + } + return out; +} + +static inline Vec256 op_vcmppd(const Vec256& a, const Vec256& b, std::uint8_t pred, bool wide) { + Vec256 out{}; + const unsigned count = wide ? 4u : 2u; + for (unsigned i = 0; i < count; ++i) { + out.q[i] = cmp_f64_scalar(a.q[i], b.q[i], pred); + } + return out; +} + +static inline Vec256 op_vcmpss(const Vec256& a, std::uint32_t b32, std::uint8_t pred) { + Vec256 out = copy128(a); + set_lane32(out, 0u, cmp_f32_scalar(lane32(a, 0u), b32, pred)); + return out; +} + +static inline Vec256 op_vcmpsd(const Vec256& a, std::uint64_t b64, std::uint8_t pred) { + Vec256 out = copy128(a); + out.q[0] = cmp_f64_scalar(a.q[0], b64, pred); + return out; +} + +static inline Vec256 op_vmovss_reg(const Vec256& a, std::uint32_t b32) { + Vec256 out = copy128(a); + set_lane32(out, 0u, b32); + return out; +} + +static inline Vec256 op_vmovss_mem(std::uint32_t b32) { + Vec256 out{}; + set_lane32(out, 0u, b32); + return out; +} + +static inline Vec256 op_vmovsd_reg(const Vec256& a, std::uint64_t b64) { + Vec256 out = copy128(a); + out.q[0] = b64; + return out; +} + +static inline Vec256 op_vmovsd_mem(std::uint64_t b64) { + return {{b64, 0ull, 0ull, 0ull}}; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins, *, expected_wide): + """Map XMM0..XMM5 or YMM0..YMM5 to register index, enforcing width and rejecting nonvolatile/other.""" + if register in VOLATILE_XMM: + if expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_XMM[register] + if register in VOLATILE_YMM: + if not expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_YMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, store=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + or base not in ARGUMENTS + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AVX VEX FP compare leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + if idx not in defined: + raise ValueError(f"undefined vector register ymm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"ymm{idx}" + + def write_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + used.add(idx) + return idx, f"ymm{idx}" + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ( + ins.op_code().encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code in LEGACY_SSE_REJECT_CODES: + raise ValueError(f"unsupported legacy SSE instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code == Code.VEX_VZEROUPPER: + for idx in sorted(defined): + statements.append(f"ymm{idx}.q[2] = 0ull; ymm{idx}.q[3] = 0ull;") + elif ins.code in VCMP_CODES: + helper, wide, mem_size, is_scalar, is_double = VCMP_CODES[ins.code] + if ins.op_count != 4 or ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported AVX compare operands at RVA {ins.ip:#x}: {ins}") + pred = ins.immediate8 & 0x1F + src1 = read_vec(1, ins, expected_wide=wide) + if ins.op2_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=mem_size) + if is_scalar: + src2 = f"{'load64' if is_double else 'load32'}({addr})" + else: + src2 = f"{'load256' if wide else 'load128'}({addr})" + elif ins.op2_kind == OpKind.REGISTER: + reg2 = read_vec(2, ins, expected_wide=wide) + if is_scalar: + src2 = f"{reg2}.q[0]" if is_double else f"lane32({reg2}, 0u)" + else: + src2 = reg2 + else: + raise ValueError(f"unsupported AVX compare operands at RVA {ins.ip:#x}: {ins}") + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + if is_scalar: + statements.append(f"{dst} = {helper}({src1}, {src2}, {pred:#x}u);") + else: + statements.append(f"{dst} = {helper}({src1}, {src2}, {pred:#x}u, {'true' if wide else 'false'});") + defined.add(dst_idx) + elif ins.code in VEC_MOVE_CODES: + wide = VEC_MOVE_CODES[ins.code] + expected_size = 32 if wide else 16 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=expected_size) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {'load256' if wide else 'load128'}({addr});") + defined.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + addr = flat_address(ins, store=True, expected_size=expected_size) + statements.append(f"{'store256' if wide else 'store128'}({addr}, {src});") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {src};" if wide else f"{dst} = copy128({src});") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported vector move operands at RVA {ins.ip:#x}: {ins}") + elif ins.code == Code.VEX_VMOVSS_XMM_M32: + addr = flat_address(ins, expected_size=4) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovss_mem(load32({addr}));") + defined.add(dst_idx) + elif ins.code == Code.VEX_VMOVSS_M32_XMM: + src = read_vec(1, ins, expected_wide=False) + addr = flat_address(ins, store=True, expected_size=4) + statements.append(f"store32({addr}, lane32({src}, 0u));") + elif ins.code in VMOVSS_REG_CODES: + src1 = read_vec(1, ins, expected_wide=False) + src2 = read_vec(2, ins, expected_wide=False) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovss_reg({src1}, lane32({src2}, 0u));") + defined.add(dst_idx) + elif ins.code == Code.VEX_VMOVSD_XMM_M64: + addr = flat_address(ins, expected_size=8) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovsd_mem(load64({addr}));") + defined.add(dst_idx) + elif ins.code == Code.VEX_VMOVSD_M64_XMM: + src = read_vec(1, ins, expected_wide=False) + addr = flat_address(ins, store=True, expected_size=8) + statements.append(f"store64({addr}, {src}.q[0]);") + elif ins.code in VMOVSD_REG_CODES: + src1 = read_vec(1, ins, expected_wide=False) + src2 = read_vec(2, ins, expected_wide=False) + dst_idx, dst = write_vec(0, ins, expected_wide=False) + statements.append(f"{dst} = op_vmovsd_reg({src1}, {src2}.q[0]);") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + if path.exists() and path.is_dir(): + raise ValueError(f"output path must not be a directory: {path}") + if path.is_symlink(): + raise ValueError(f"output path must not be a symlink: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path must not be a directory: {args.output}") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_avx_cmp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_avx_horiz_fp_aot.py b/tools/cpu_avx_horiz_fp_aot.py new file mode 100644 index 0000000000..e84bfbbcce --- /dev/null +++ b/tools/cpu_avx_horiz_fp_aot.py @@ -0,0 +1,403 @@ +"""Lift bounded Windows x64 leaf functions with AVX horizontal and add/sub FP ops to C++. + +Each export uses the straight-line leaf ABI: + void lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. YMM0..YMM5 +are modeled as portable 256-bit value structs (four 64-bit lanes); every VEX.128 +write to an XMM destination zeroes bits [255:128] of the corresponding YMM register. + +Supported AVX horizontal / alternating FP forms (docs/coverage/x64_zen2.tsv group AVX): + - VHADDPS, VHADDPD, VHSUBPS, VHSUBPD, VADDSUBPS, VADDSUBPD + in VEX.128 (xmm, xmm, xmm/m128) and VEX.256 (ymm, ymm, ymm/m256) forms. + +Transport / ABI glue: + - VMOVAPS, VMOVAPD, VMOVUPS, VMOVUPD (reg-reg, flat [rcx|rdx|r8] loads, flat [r8] stores) + - VZEROUPPER and terminal RET. + +EVEX encodings, legacy SSE forms, nonvolatile vector registers (XMM6..15/YMM6..15), +undefined vector reads, displaced or non-flat memory operands, non-[r8] stores, +instruction prefixes, branches, and trailing or missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +VOLATILE_YMM = {getattr(R, f"YMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(6, 32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +# (helper_name, is_ymm) +HORIZ_FP_CODES = { + Code.VEX_VHADDPS_XMM_XMM_XMMM128: ("op_vhaddps", False), + Code.VEX_VHADDPS_YMM_YMM_YMMM256: ("op_vhaddps", True), + Code.VEX_VHADDPD_XMM_XMM_XMMM128: ("op_vhaddpd", False), + Code.VEX_VHADDPD_YMM_YMM_YMMM256: ("op_vhaddpd", True), + Code.VEX_VHSUBPS_XMM_XMM_XMMM128: ("op_vhsubps", False), + Code.VEX_VHSUBPS_YMM_YMM_YMMM256: ("op_vhsubps", True), + Code.VEX_VHSUBPD_XMM_XMM_XMMM128: ("op_vhsubpd", False), + Code.VEX_VHSUBPD_YMM_YMM_YMMM256: ("op_vhsubpd", True), + Code.VEX_VADDSUBPS_XMM_XMM_XMMM128: ("op_vaddsubps", False), + Code.VEX_VADDSUBPS_YMM_YMM_YMMM256: ("op_vaddsubps", True), + Code.VEX_VADDSUBPD_XMM_XMM_XMMM128: ("op_vaddsubpd", False), + Code.VEX_VADDSUBPD_YMM_YMM_YMMM256: ("op_vaddsubpd", True), +} + +# is_ymm for full-width VEX FP moves +VEC_MOVE_CODES = { + Code.VEX_VMOVAPS_XMM_XMMM128: False, + Code.VEX_VMOVAPS_XMMM128_XMM: False, + Code.VEX_VMOVAPS_YMM_YMMM256: True, + Code.VEX_VMOVAPS_YMMM256_YMM: True, + Code.VEX_VMOVAPD_XMM_XMMM128: False, + Code.VEX_VMOVAPD_XMMM128_XMM: False, + Code.VEX_VMOVAPD_YMM_YMMM256: True, + Code.VEX_VMOVAPD_YMMM256_YMM: True, + Code.VEX_VMOVUPS_XMM_XMMM128: False, + Code.VEX_VMOVUPS_XMMM128_XMM: False, + Code.VEX_VMOVUPS_YMM_YMMM256: True, + Code.VEX_VMOVUPS_YMMM256_YMM: True, + Code.VEX_VMOVUPD_XMM_XMMM128: False, + Code.VEX_VMOVUPD_XMMM128_XMM: False, + Code.VEX_VMOVUPD_YMM_YMMM256: True, + Code.VEX_VMOVUPD_YMMM256_YMM: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.VEX_VZEROUPPER, + *HORIZ_FP_CODES, + *VEC_MOVE_CODES, +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#include <pmmintrin.h> +#if defined(_MSC_VER) +#include <intrin.h> +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec256 { + std::uint64_t q[4]; +}; + +static inline Vec256 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, 0ull, 0ull}}; +} + +static inline Vec256 load256(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + const std::uint64_t q2 = p[2]; + const std::uint64_t q3 = p[3]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1, q2, q3}}; +} + +static inline void store128(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store256(word address, const Vec256& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, 32); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline Vec256 copy128(const Vec256& v) { + return {{v.q[0], v.q[1], 0ull, 0ull}}; +} + +template <typename LaneVec, typename Fn> +static inline Vec256 apply_sse3_lanes(const Vec256& a, const Vec256& b, bool wide, Fn fn) { + Vec256 out{}; + const unsigned lanes = wide ? 2u : 1u; + for (unsigned lane = 0; lane < lanes; ++lane) { + LaneVec va; + LaneVec vb; + std::memcpy(&va, &a.q[lane * 2u], 16); + std::memcpy(&vb, &b.q[lane * 2u], 16); + const LaneVec vr = fn(va, vb); + std::memcpy(&out.q[lane * 2u], &vr, 16); + } + return out; +} + +static inline Vec256 op_vhaddps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_hadd_ps(x, y); }); +} + +static inline Vec256 op_vhaddpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_hadd_pd(x, y); }); +} + +static inline Vec256 op_vhsubps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_hsub_ps(x, y); }); +} + +static inline Vec256 op_vhsubpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_hsub_pd(x, y); }); +} + +static inline Vec256 op_vaddsubps(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128>(a, b, wide, [](__m128 x, __m128 y) { return _mm_addsub_ps(x, y); }); +} + +static inline Vec256 op_vaddsubpd(const Vec256& a, const Vec256& b, bool wide) { + return apply_sse3_lanes<__m128d>(a, b, wide, [](__m128d x, __m128d y) { return _mm_addsub_pd(x, y); }); +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_avx() { + int info[4]{}; + __cpuid(info, 1); + const int need = (1 << 27) | (1 << 28); + if ((info[2] & need) != need) return 0u; + return (_xgetbv(0) & 6u) == 6u ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins, *, expected_wide): + """Map XMM0..XMM5 or YMM0..YMM5 to register index, enforcing width and rejecting nonvolatile/other.""" + if register in VOLATILE_XMM: + if expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_XMM[register] + if register in VOLATILE_YMM: + if not expected_wide: + raise ValueError(f"unsupported vector width for {register} at RVA {ins.ip:#x}: {ins}") + return VOLATILE_YMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, store=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + allowed = {R.R8} if store else ARGUMENTS + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + or base not in allowed + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line AVX horizontal/addsub FP leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + if idx not in defined: + raise ValueError(f"undefined vector register ymm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"ymm{idx}" + + def write_vec(op_index, ins, *, expected_wide): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins, expected_wide=expected_wide) + used.add(idx) + return idx, f"ymm{idx}" + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ( + ins.op_code().encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code == Code.VEX_VZEROUPPER: + for idx in sorted(defined): + statements.append(f"ymm{idx}.q[2] = 0ull; ymm{idx}.q[3] = 0ull;") + elif ins.code in HORIZ_FP_CODES: + helper, wide = HORIZ_FP_CODES[ins.code] + if ins.op_count != 3 or ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported AVX horizontal FP operands at RVA {ins.ip:#x}: {ins}") + src1 = read_vec(1, ins, expected_wide=wide) + if ins.op2_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=32 if wide else 16) + src2 = f"{'load256' if wide else 'load128'}({addr})" + elif ins.op2_kind == OpKind.REGISTER: + src2 = read_vec(2, ins, expected_wide=wide) + else: + raise ValueError(f"unsupported AVX horizontal FP operands at RVA {ins.ip:#x}: {ins}") + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {helper}({src1}, {src2}, {'true' if wide else 'false'});") + defined.add(dst_idx) + elif ins.code in VEC_MOVE_CODES: + wide = VEC_MOVE_CODES[ins.code] + expected_size = 32 if wide else 16 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=expected_size) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {'load256' if wide else 'load128'}({addr});") + defined.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + addr = flat_address(ins, store=True, expected_size=expected_size) + statements.append(f"{'store256' if wide else 'store128'}({addr}, {src});") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins, expected_wide=wide) + dst_idx, dst = write_vec(0, ins, expected_wide=wide) + statements.append(f"{dst} = {src};" if wide else f"{dst} = copy128({src});") + defined.add(dst_idx) + else: + raise ValueError(f"unsupported vector move operands at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec256 ymm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_avx_horiz_fp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_avx_int_aot.py b/tools/cpu_avx_int_aot.py index 0e67cda336..7f1d4b03bb 100644 --- a/tools/cpu_avx_int_aot.py +++ b/tools/cpu_avx_int_aot.py @@ -40,6 +40,9 @@ - 256-bit (VEX.L=1, AVX2, register operands only) pack with saturation: vpacksswb, vpackssdw, vpackusdw. Each 128-bit lane is computed independently (128-bit vpackuswb stays with cpu_vex_aot.py). + - 256-bit (VEX.L=1, AVX2, register operands only) cross-lane extend: vpmovsxbw/bd/bq/wd/wq/dq, + vpmovzxbw/bd/bq/wd/wq/dq (XMM low 128 bits -> YMM 256 bits; upper source bits ignored). + - 256-bit (VEX.L=1, AVX2, register operands only) in-lane unpack: vpunpckldq/hdq/lqdq/hqdq. Transport/ABI glue: vmovdqu (128/256-bit flat load, store and register copy), flat 32/64-bit GPR load/store mov for scratch GPRs, and terminal ret. @@ -95,6 +98,7 @@ "vphaddw", "vphaddd", "vphaddsw", "vphsubw", "vphsubd", "vphsubsw", "vpmuldq", "vpmuludq", "vpmulhrsw", "vpsadbw", "vpacksswb", "vpackssdw", "vpackusdw", + "vpunpckldq", "vpunpckhdq", "vpunpcklqdq", "vpunpckhqdq", ) } WIDE_BINARY_CODES = { @@ -112,6 +116,7 @@ "VPHADDW", "VPHADDD", "VPHADDSW", "VPHSUBW", "VPHSUBD", "VPHSUBSW", "VPMULDQ", "VPMULUDQ", "VPMULHRSW", "VPSADBW", "VPACKSSWB", "VPACKSSDW", "VPACKUSDW", + "VPUNPCKLDQ", "VPUNPCKHDQ", "VPUNPCKLQDQ", "VPUNPCKHQDQ", ) } # 256-bit one-source forms: the 128-bit helper runs on each half. vpshufhw/vpshuflw use the @@ -128,6 +133,28 @@ WIDE_UNARY_IMM_CODES = { getattr(Code, f"VEX_{name}_YMM_YMMM256_IMM8") for name in ("VPSHUFHW", "VPSHUFLW") } +# 256-bit cross-lane sign/zero-extend moves (XMM low 128 bits -> YMM 256 bits). +WIDE_EXTEND_HELPERS = { + getattr(M, name.upper()): f"op_{name}_ymm" + for name in ( + "vpmovsxbw", "vpmovsxbd", "vpmovsxbq", "vpmovsxwd", "vpmovsxwq", "vpmovsxdq", + "vpmovzxbw", "vpmovzxbd", "vpmovzxbq", "vpmovzxwd", "vpmovzxwq", "vpmovzxdq", + ) +} +WIDE_EXTEND_CODES = { + Code.VEX_VPMOVSXBW_YMM_XMMM128, + Code.VEX_VPMOVSXBD_YMM_XMMM64, + Code.VEX_VPMOVSXBQ_YMM_XMMM32, + Code.VEX_VPMOVSXWD_YMM_XMMM128, + Code.VEX_VPMOVSXWQ_YMM_XMMM64, + Code.VEX_VPMOVSXDQ_YMM_XMMM128, + Code.VEX_VPMOVZXBW_YMM_XMMM128, + Code.VEX_VPMOVZXBD_YMM_XMMM64, + Code.VEX_VPMOVZXBQ_YMM_XMMM32, + Code.VEX_VPMOVZXWD_YMM_XMMM128, + Code.VEX_VPMOVZXWQ_YMM_XMMM64, + Code.VEX_VPMOVZXDQ_YMM_XMMM128, +} # Unary: dst = helper(src) UNARY_HELPERS = { @@ -379,7 +406,7 @@ } -ALLOWED_CODES |= WIDE_BINARY_CODES | WIDE_UNARY_CODES | WIDE_UNARY_IMM_CODES +ALLOWED_CODES |= WIDE_BINARY_CODES | WIDE_UNARY_CODES | WIDE_UNARY_IMM_CODES | WIDE_EXTEND_CODES PRELUDE = """#include <cstdint> @@ -1092,68 +1119,91 @@ // --- Sign-extend and zero-extend moves --- -static Vec256 op_vpmovsxbw(const Vec256& a) { +static Vec256 extend_bw(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 8u; ++i) set_lane16(out, i, static_cast<std::uint16_t>(static_cast<std::int16_t>(s8(lane8(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + set_lane16(out, i, sign_ext ? static_cast<std::uint16_t>(static_cast<std::int16_t>(s8(u))) + : static_cast<std::uint16_t>(u)); + } return out; } -static Vec256 op_vpmovsxbd(const Vec256& a) { +static Vec256 extend_bd(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, static_cast<std::uint32_t>(static_cast<std::int32_t>(s8(lane8(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + set_lane32(out, i, sign_ext ? static_cast<std::uint32_t>(static_cast<std::int32_t>(s8(u))) + : static_cast<std::uint32_t>(u)); + } return out; } -static Vec256 op_vpmovsxbq(const Vec256& a) { - return {{static_cast<std::uint64_t>(static_cast<std::int64_t>(s8(lane8(a, 0u)))), - static_cast<std::uint64_t>(static_cast<std::int64_t>(s8(lane8(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxwd(const Vec256& a) { +static Vec256 extend_bq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, static_cast<std::uint32_t>(static_cast<std::int32_t>(s16(lane16(a, i))))); + for (unsigned i = 0; i < count; ++i) { + const std::uint8_t u = lane8(a, i); + out.q[i] = sign_ext ? static_cast<std::uint64_t>(static_cast<std::int64_t>(s8(u))) + : static_cast<std::uint64_t>(u); + } return out; } -static Vec256 op_vpmovsxwq(const Vec256& a) { - return {{static_cast<std::uint64_t>(static_cast<std::int64_t>(s16(lane16(a, 0u)))), - static_cast<std::uint64_t>(static_cast<std::int64_t>(s16(lane16(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovsxdq(const Vec256& a) { - return {{static_cast<std::uint64_t>(static_cast<std::int64_t>(s32(lane32(a, 0u)))), - static_cast<std::uint64_t>(static_cast<std::int64_t>(s32(lane32(a, 1u)))), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxbw(const Vec256& a) { +static Vec256 extend_wd(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 8u; ++i) set_lane16(out, i, lane8(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint16_t u = lane16(a, i); + set_lane32(out, i, sign_ext ? static_cast<std::uint32_t>(static_cast<std::int32_t>(s16(u))) + : static_cast<std::uint32_t>(u)); + } return out; } -static Vec256 op_vpmovzxbd(const Vec256& a) { +static Vec256 extend_wq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, lane8(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint16_t u = lane16(a, i); + out.q[i] = sign_ext ? static_cast<std::uint64_t>(static_cast<std::int64_t>(s16(u))) + : static_cast<std::uint64_t>(u); + } return out; } -static Vec256 op_vpmovzxbq(const Vec256& a) { - return {{lane8(a, 0u), lane8(a, 1u), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxwd(const Vec256& a) { +static Vec256 extend_dq(const Vec256& a, unsigned count, bool sign_ext) { Vec256 out{}; - for (unsigned i = 0; i < 4u; ++i) set_lane32(out, i, lane16(a, i)); + for (unsigned i = 0; i < count; ++i) { + const std::uint32_t u = lane32(a, i); + out.q[i] = sign_ext ? static_cast<std::uint64_t>(static_cast<std::int64_t>(s32(u))) + : static_cast<std::uint64_t>(u); + } return out; } -static Vec256 op_vpmovzxwq(const Vec256& a) { - return {{lane16(a, 0u), lane16(a, 1u), 0ull, 0ull}}; -} - -static Vec256 op_vpmovzxdq(const Vec256& a) { - return {{lane32(a, 0u), lane32(a, 1u), 0ull, 0ull}}; -} +static Vec256 op_vpmovsxbw(const Vec256& a) { return extend_bw(a, 8u, true); } +static Vec256 op_vpmovsxbd(const Vec256& a) { return extend_bd(a, 4u, true); } +static Vec256 op_vpmovsxbq(const Vec256& a) { return extend_bq(a, 2u, true); } +static Vec256 op_vpmovsxwd(const Vec256& a) { return extend_wd(a, 4u, true); } +static Vec256 op_vpmovsxwq(const Vec256& a) { return extend_wq(a, 2u, true); } +static Vec256 op_vpmovsxdq(const Vec256& a) { return extend_dq(a, 2u, true); } +static Vec256 op_vpmovzxbw(const Vec256& a) { return extend_bw(a, 8u, false); } +static Vec256 op_vpmovzxbd(const Vec256& a) { return extend_bd(a, 4u, false); } +static Vec256 op_vpmovzxbq(const Vec256& a) { return extend_bq(a, 2u, false); } +static Vec256 op_vpmovzxwd(const Vec256& a) { return extend_wd(a, 4u, false); } +static Vec256 op_vpmovzxwq(const Vec256& a) { return extend_wq(a, 2u, false); } +static Vec256 op_vpmovzxdq(const Vec256& a) { return extend_dq(a, 2u, false); } + +static Vec256 op_vpmovsxbw_ymm(const Vec256& a) { return extend_bw(a, 16u, true); } +static Vec256 op_vpmovsxbd_ymm(const Vec256& a) { return extend_bd(a, 8u, true); } +static Vec256 op_vpmovsxbq_ymm(const Vec256& a) { return extend_bq(a, 4u, true); } +static Vec256 op_vpmovsxwd_ymm(const Vec256& a) { return extend_wd(a, 8u, true); } +static Vec256 op_vpmovsxwq_ymm(const Vec256& a) { return extend_wq(a, 4u, true); } +static Vec256 op_vpmovsxdq_ymm(const Vec256& a) { return extend_dq(a, 4u, true); } +static Vec256 op_vpmovzxbw_ymm(const Vec256& a) { return extend_bw(a, 16u, false); } +static Vec256 op_vpmovzxbd_ymm(const Vec256& a) { return extend_bd(a, 8u, false); } +static Vec256 op_vpmovzxbq_ymm(const Vec256& a) { return extend_bq(a, 4u, false); } +static Vec256 op_vpmovzxwd_ymm(const Vec256& a) { return extend_wd(a, 8u, false); } +static Vec256 op_vpmovzxwq_ymm(const Vec256& a) { return extend_wq(a, 4u, false); } +static Vec256 op_vpmovzxdq_ymm(const Vec256& a) { return extend_dq(a, 4u, false); } // --- Unpack / interleave --- @@ -1379,7 +1429,8 @@ def write_gpr(op_index, ins): wide_unary = ins.code in WIDE_UNARY_CODES wide_unary_imm = ins.code in WIDE_UNARY_IMM_CODES wide_binary = ins.code in WIDE_BINARY_CODES - wide_any = wide_unary or wide_unary_imm or wide_binary + wide_extend = ins.code in WIDE_EXTEND_CODES + wide_any = wide_unary or wide_unary_imm or wide_binary or wide_extend if (mnemonic in AVX_INT_128_ONLY_MNEMONICS and not wide_any and op_code.encoding == EncodingKind.VEX and op_code.l == 1): raise ValueError(f"unsupported VEX.256 (L=1) packed-integer encoding at RVA {ins.ip:#x}: {ins}") @@ -1445,6 +1496,11 @@ def write_gpr(op_index, ins): statements.append( f"{dst} = wide128_unary_imm({WIDE_UNARY_IMM_HELPERS[mnemonic]}, {src}, {imm:#x}u);") defined_vec.add(dst_idx) + elif wide_extend: + src, _ = read_vec(1, ins) + dst_idx, dst, _ = write_vec(0, ins, allow_ymm=True) + statements.append(f"{dst} = {WIDE_EXTEND_HELPERS[mnemonic]}({src});") + defined_vec.add(dst_idx) elif mnemonic in UNARY_HELPERS: src, _ = read_vec(1, ins) dst_idx, dst, _ = write_vec(0, ins) diff --git a/tools/cpu_bmi1_logic_aot.py b/tools/cpu_bmi1_logic_aot.py new file mode 100644 index 0000000000..72dfa21999 --- /dev/null +++ b/tools/cpu_bmi1_logic_aot.py @@ -0,0 +1,670 @@ +"""Lift bounded Windows x64 leaf functions with BMI1 ANDN, BEXTR, and TZCNT to C++. + +Each export uses the straight-line leaf ABI: + std::uint64_t lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI1 logic/extract/count instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - ANDN r32, r32, r/m32 | ANDN r64, r64, r/m64 (dst = (~src1) & src2; SF/ZF, CF=OF=0) + - BEXTR r32, r/m32, r32 | BEXTR r64, r/m64, r64 (start=op2[7:0], len=op2[15:8]; ZF=(dst==0), CF=OF=0) + - TZCNT r32, r/m32 | TZCNT r64, r/m64 (dst=width/CF=1/ZF=0 if src==0 else ctz/CF=0/ZF=(dst==0)) + +32-bit destinations zero-extend into bits [63:32]. Per Intel SDM: + - ANDN leaves PF and AF undefined. + - BEXTR leaves SF, PF, and AF undefined. + - TZCNT leaves SF, OF, PF, and AF undefined. +Reading an undefined flag before a subsequent flag-defining instruction is rejected. +Memory operands are flat zero-displacement [rcx|rdx|r8] loads read unconditionally via +load_always() so /O2 cannot drop faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, xor, or, shl, movzx, setb/sete/sets/seto + (and inverses, reg or flat [r8]), flat [r8] stores, and terminal ret. + +BMI1 BLSI/BLSMSK/BLSR, BMI2, EVEX/XOP, 16-bit TZCNT, BSF/BSR/LZCNT/POPCNT, nonvolatile GPRs, +writes to argument GPRs (rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads, +displaced/indexed/non-flat memory operands, stores outside [r8], instruction prefixes, +branches/calls, and missing or trailing instructions after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8", + R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", R.R8D: "r8", + R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", R.CX: "rcx", R.DX: "rdx", R.R8W: "r8", + R.R9W: "r9", R.R10W: "r10", R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", R.R8L: "r8", + R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (kind, width_bits, expected_encoding, defined_flags) +BMI1_LOGIC_SPECS = { + Code.VEX_ANDN_R32_R32_RM32: ("andn", 32, EncodingKind.VEX, frozenset({"sf", "zf", "cf", "of"})), + Code.VEX_ANDN_R64_R64_RM64: ("andn", 64, EncodingKind.VEX, frozenset({"sf", "zf", "cf", "of"})), + Code.VEX_BEXTR_R32_RM32_R32: ("bextr", 32, EncodingKind.VEX, frozenset({"zf", "cf", "of"})), + Code.VEX_BEXTR_R64_RM64_R64: ("bextr", 64, EncodingKind.VEX, frozenset({"zf", "cf", "of"})), + Code.TZCNT_R32_RM32: ("tzcnt", 32, EncodingKind.LEGACY, frozenset({"cf", "zf"})), + Code.TZCNT_R64_RM64: ("tzcnt", 64, EncodingKind.LEGACY, frozenset({"cf", "zf"})), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SHL_SPECS = { + Code.SHL_RM32_1: (32, True), + Code.SHL_RM32_IMM8: (32, False), + Code.SHL_RM64_1: (64, True), + Code.SHL_RM64_IMM8: (64, False), +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + # PF is tracked solely to reject reading it when undefined. + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#if defined(_MSC_VER) +#include <intrin.h> +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template <class T> +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast<const void*>(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template <class T> +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast<std::uint8_t>(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(masked)); +} + +static inline word op_shl(word cur, unsigned width, unsigned count, Flags& flags) { + const unsigned mask = (width == 32u) ? 31u : 63u; + const unsigned c = count & mask; + if (width == 32u) { + const std::uint32_t v = static_cast<std::uint32_t>(cur); + if (c == 0u) return static_cast<word>(v); + const std::uint32_t r = v << c; + flags.cf = ((v >> (32u - c)) & 1u) != 0u; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((r >> 31) & 1u) != (flags.cf ? 1u : 0u)); + flags.pf = parity_even(static_cast<std::uint8_t>(r)); + return static_cast<word>(r); + } + if (c == 0u) return cur; + const word r = cur << c; + flags.cf = ((cur >> (64u - c)) & 1ull) != 0ull; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((r >> 63) & 1ull) != (flags.cf ? 1ull : 0ull)); + flags.pf = parity_even(static_cast<std::uint8_t>(r)); + return r; +} + +// --- Portable BMI1 ANDN / BEXTR / TZCNT helpers --- + +static inline word op_andn32(word src1_w, word src2_w, Flags& flags) { + const std::uint32_t s1 = static_cast<std::uint32_t>(src1_w); + const std::uint32_t s2 = static_cast<std::uint32_t>(src2_w); + const std::uint32_t d = (~s1) & s2; + flags.cf = false; + flags.of = false; + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + return static_cast<word>(d); +} + +static inline word op_andn64(word s1, word s2, Flags& flags) { + const word d = (~s1) & s2; + flags.cf = false; + flags.of = false; + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + return d; +} + +static inline word op_bextr32(word src1_w, word src2_w, Flags& flags) { + const std::uint32_t s1 = static_cast<std::uint32_t>(src1_w); + const unsigned start = static_cast<unsigned>(src2_w & 0xFFull); + const unsigned len = static_cast<unsigned>((src2_w >> 8) & 0xFFull); + std::uint32_t d = 0u; + if (len != 0u && start < 32u) { + const std::uint32_t shifted = s1 >> start; + const std::uint32_t mask = (len >= 32u) ? 0xFFFFFFFFu : ((1u << len) - 1u); + d = shifted & mask; + } + flags.zf = (d == 0u); + flags.cf = false; + flags.of = false; + return static_cast<word>(d); +} + +static inline word op_bextr64(word s1, word s2, Flags& flags) { + const unsigned start = static_cast<unsigned>(s2 & 0xFFull); + const unsigned len = static_cast<unsigned>((s2 >> 8) & 0xFFull); + word d = 0ull; + if (len != 0u && start < 64u) { + const word shifted = s1 >> start; + const word mask = (len >= 64u) ? ~0ull : ((1ull << len) - 1ull); + d = shifted & mask; + } + flags.zf = (d == 0ull); + flags.cf = false; + flags.of = false; + return d; +} + +static inline word op_tzcnt32(word src_w, Flags& flags) { + const std::uint32_t s = static_cast<std::uint32_t>(src_w); + std::uint32_t count = 32u; + if (s != 0u) { + count = 0u; + std::uint32_t t = s; + while ((t & 1u) == 0u) { + t >>= 1u; + ++count; + } + } + flags.cf = (s == 0u); + flags.zf = (count == 0u); + return static_cast<word>(count); +} + +static inline word op_tzcnt64(word s, Flags& flags) { + word count = 64ull; + if (s != 0ull) { + count = 0ull; + word t = s; + while ((t & 1ull) == 0ull) { + t >>= 1u; + ++count; + } + } + flags.cf = (s == 0ull); + flags.zf = (count == 0ull); + return count; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi1() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast<std::uint32_t>(info[1]) & (1u << 3)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI1 ANDN/BEXTR/TZCNT leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast<word>(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI1_LOGIC_SPECS: + kind, width, expected_enc, out_flags = BMI1_LOGIC_SPECS[code] + if encoding != expected_enc: + raise ValueError(f"unexpected encoding for {kind} at RVA {ins.ip:#x}: {ins}") + if kind == "andn": + src1_expr = read_reg(1, ins, width) + src2_expr = read_rm(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_andn{width}({src1_expr}, {src2_expr}, flags);") + elif kind == "bextr": + src1_expr = read_rm(1, ins, width) + src2_expr = read_reg(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_bextr{width}({src1_expr}, {src2_expr}, flags);") + else: # tzcnt + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_tzcnt{width}({src_expr}, flags);") + defined_gpr.add(dst) + defined_flags = set(out_flags) + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SHL_SPECS: + width, is_one = SHL_SPECS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + cnt = 1 if is_one else (ins.immediate8 & 0xFF) + eff = cnt & (31 if width == 32 else 63) + statements.append(f"{dst} = op_shl({dst}, {width}u, {cnt}u, flags);") + if eff == 1: + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif eff > 1: + defined_flags = {"cf", "zf", "sf", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always<std::uint8_t>({addr}, static_cast<std::uint8_t>(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + decls.append(" (void)flags;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_bmi2_bit_aot.py b/tools/cpu_bmi2_bit_aot.py new file mode 100644 index 0000000000..b953edfad9 --- /dev/null +++ b/tools/cpu_bmi2_bit_aot.py @@ -0,0 +1,688 @@ +"""Lift bounded Windows x64 leaf functions with BMI2 BZHI, MULX, PDEP, and PEXT to C++. + +Each export uses the leaf ABI: + std::uint64_t lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI2 bit-manipulation instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - BZHI r32, r/m32, r32 | BZHI r64, r/m64, r64 (index = src2[7:0]; CF=1 if index>=width) + - MULX r32, r32, r/m32 | MULX r64, r64, r/m64 (implicit EDX/RDX src1; op0==op1 -> hi) + - PDEP r32, r32, r/m32 | PDEP r64, r64, r/m64 (parallel bit deposit, flagless) + - PEXT r32, r32, r/m32 | PEXT r64, r64, r/m64 (parallel bit extract, flagless) + +Exact SDM semantics: + - 32-bit destinations zero-extend into bits [63:32]. + - BZHI masks index to low 8 bits (index >= width preserves src and sets CF=1; index == 0 + yields 0 with CF=0; updates CF, ZF, SF, clears OF, and leaves PF/AF undefined). + - MULX reads implicit EDX/RDX and src2 before writing dst_lo then dst_hi (so op0==op1 + writes the high half) and leaves all flags unmodified. + - PDEP and PEXT leave all flags unmodified. + - Memory operands are flat zero-displacement [rcx|rdx|r8] loads read unconditionally via + load_always() so /O2 cannot eliminate faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, movzx, cmp, xor, or, setcc (reg or [r8]), + flat zero-displacement [r8] stores, and terminal ret. + +EVEX/XOP encodings, shifts/rotates (legacy SHL/SHR/SAR/ROR/ROL and BMI2 RORX/SARX/SHLX/SHRX), +BMI1 (ANDN/BEXTR/BLSI/BLSMSK/BLSR/TZCNT), nonvolatile GPRs, writes to argument GPRs +(rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads (including PF/AF after BZHI), +RIP-relative/SIB-indexed/displaced/non-argument memory operands, stores outside [r8], +instruction prefixes, branches/calls, and missing or trailing instructions after ret are +rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", + R.RCX: "rcx", + R.RDX: "rdx", + R.R8: "r8", + R.R9: "r9", + R.R10: "r10", + R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", + R.ECX: "rcx", + R.EDX: "rdx", + R.R8D: "r8", + R.R9D: "r9", + R.R10D: "r10", + R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", + R.CX: "rcx", + R.DX: "rdx", + R.R8W: "r8", + R.R9W: "r9", + R.R10W: "r10", + R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", + R.CL: "rcx", + R.DL: "rdx", + R.R8L: "r8", + R.R9L: "r9", + R.R10L: "r10", + R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +BMI2_BIT_SPECS = { + Code.VEX_BZHI_R32_RM32_R32: ("bzhi", 32), + Code.VEX_BZHI_R64_RM64_R64: ("bzhi", 64), + Code.VEX_MULX_R32_R32_RM32: ("mulx", 32), + Code.VEX_MULX_R64_R64_RM64: ("mulx", 64), + Code.VEX_PDEP_R32_R32_RM32: ("pdep", 32), + Code.VEX_PDEP_R64_R64_RM64: ("pdep", 64), + Code.VEX_PEXT_R32_R32_RM32: ("pext", 32), + Code.VEX_PEXT_R64_R64_RM64: ("pext", 64), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +CMP_WIDTHS = { + Code.CMP_R32_RM32: 32, + Code.CMP_RM32_R32: 32, + Code.CMP_RM32_IMM8: 32, + Code.CMP_RM32_IMM32: 32, + Code.CMP_EAX_IMM32: 32, + Code.CMP_R64_RM64: 64, + Code.CMP_RM64_R64: 64, + Code.CMP_RM64_IMM8: 64, + Code.CMP_RM64_IMM32: 64, + Code.CMP_RAX_IMM32: 64, +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + # PF is tracked solely to validate flag preservation and reject reads after BZHI. + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#if defined(_MSC_VER) +#include <intrin.h> +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template <class T> +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast<const void*>(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template <class T> +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast<std::uint8_t>(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_cmp32(word lhs_w, word rhs_w, Flags& flags) { + const std::uint32_t a = static_cast<std::uint32_t>(lhs_w); + const std::uint32_t b = static_cast<std::uint32_t>(rhs_w); + const std::uint32_t r = a - b; + flags.cf = a < b; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((a ^ b) & (a ^ r)) & 0x80000000u) != 0u; + flags.pf = parity_even(static_cast<std::uint8_t>(r)); +} + +static inline void compute_cmp64(word a, word b, Flags& flags) { + const word r = a - b; + flags.cf = a < b; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((a ^ b) & (a ^ r)) >> 63) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(r)); +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(masked)); +} + +// --- BMI2 BZHI / MULX / PDEP / PEXT helpers --- + +static inline word op_bzhi32(word src_w, word idx_w, Flags& flags) { + const std::uint32_t s = static_cast<std::uint32_t>(src_w); + const unsigned idx = static_cast<unsigned>(idx_w & 0xFFull); + std::uint32_t d = 0u; + if (idx >= 32u) { + d = s; + flags.cf = true; + } else { + d = (idx == 0u) ? 0u : (s & ((1u << idx) - 1u)); + flags.cf = false; + } + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + flags.of = false; + return static_cast<word>(d); +} + +static inline word op_bzhi64(word s, word idx_w, Flags& flags) { + const unsigned idx = static_cast<unsigned>(idx_w & 0xFFull); + word d = 0ull; + if (idx >= 64u) { + d = s; + flags.cf = true; + } else { + d = (idx == 0u) ? 0ull : (s & ((1ull << idx) - 1ull)); + flags.cf = false; + } + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + flags.of = false; + return d; +} + +static inline void op_mulx32(word src1_w, word src2_w, word& hi, word& lo) { + const std::uint64_t prod = static_cast<std::uint64_t>(static_cast<std::uint32_t>(src1_w)) + * static_cast<std::uint64_t>(static_cast<std::uint32_t>(src2_w)); + lo = prod & 0xFFFFFFFFull; + hi = prod >> 32; +} + +static inline void op_mulx64(word src1, word src2, word& hi, word& lo) { +#if defined(_MSC_VER) + word high = 0ull; + lo = _umul128(src1, src2, &high); + hi = high; +#else + const unsigned __int128 prod = static_cast<unsigned __int128>(src1) * static_cast<unsigned __int128>(src2); + lo = static_cast<word>(prod); + hi = static_cast<word>(prod >> 64); +#endif +} + +static inline word op_pdep32(word src_w, word mask_w) { + std::uint32_t s = static_cast<std::uint32_t>(src_w); + std::uint32_t m = static_cast<std::uint32_t>(mask_w); + std::uint32_t d = 0u; + while (m != 0u) { + const std::uint32_t lowest = m & (~m + 1u); + if ((s & 1u) != 0u) { + d |= lowest; + } + s >>= 1; + m &= ~lowest; + } + return static_cast<word>(d); +} + +static inline word op_pdep64(word s, word m) { + word d = 0ull; + while (m != 0ull) { + const word lowest = m & (~m + 1ull); + if ((s & 1ull) != 0ull) { + d |= lowest; + } + s >>= 1; + m &= ~lowest; + } + return d; +} + +static inline word op_pext32(word src_w, word mask_w) { + const std::uint32_t s = static_cast<std::uint32_t>(src_w); + std::uint32_t m = static_cast<std::uint32_t>(mask_w); + std::uint32_t d = 0u; + std::uint32_t out_bit = 1u; + while (m != 0u) { + const std::uint32_t lowest = m & (~m + 1u); + if ((s & lowest) != 0u) { + d |= out_bit; + } + out_bit <<= 1; + m &= ~lowest; + } + return static_cast<word>(d); +} + +static inline word op_pext64(word s, word m) { + word d = 0ull; + word out_bit = 1ull; + while (m != 0ull) { + const word lowest = m & (~m + 1ull); + if ((s & lowest) != 0ull) { + d |= out_bit; + } + out_bit <<= 1; + m &= ~lowest; + } + return d; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi2() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast<std::uint32_t>(info[1]) & (1u << 8)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI2 BZHI/MULX/PDEP/PEXT leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast<word>(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI2_BIT_SPECS: + if encoding != EncodingKind.VEX: + raise ValueError(f"expected VEX encoding for BMI2 op at RVA {ins.ip:#x}: {ins}") + mnemonic, width = BMI2_BIT_SPECS[code] + if mnemonic == "bzhi": + src_expr = read_rm(1, ins, width) + idx_expr = read_reg(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_bzhi{width}({src_expr}, {idx_expr}, flags);") + defined_gpr.add(dst) + # BZHI defines CF, ZF, SF, OF and leaves PF/AF undefined. + defined_flags = {"cf", "zf", "sf", "of"} + elif mnemonic == "mulx": + src1_expr = "(rdx & 0xFFFFFFFFull)" if width == 32 else "rdx" + src2_expr = read_rm(2, ins, width) + dst_hi = check_dst_reg(0, ins, width, require_defined=False) + dst_lo = check_dst_reg(1, ins, width, require_defined=False) + hi_var = f"mulx_hi_{ins.ip:x}" + lo_var = f"mulx_lo_{ins.ip:x}" + statements.append(f"word {hi_var} = 0ull;") + statements.append(f"word {lo_var} = 0ull;") + statements.append(f"op_mulx{width}({src1_expr}, {src2_expr}, {hi_var}, {lo_var});") + # Write dst_lo first, then dst_hi so op0 == op1 receives the high half per Intel SDM. + statements.append(f"{dst_lo} = {lo_var};") + statements.append(f"{dst_hi} = {hi_var};") + defined_gpr.add(dst_lo) + defined_gpr.add(dst_hi) + else: + src_expr = read_reg(1, ins, width) + mask_expr = read_rm(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = op_{mnemonic}{width}({src_expr}, {mask_expr});") + defined_gpr.add(dst) + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in CMP_WIDTHS: + width = CMP_WIDTHS[code] + lhs_expr = read_rm(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"compute_cmp{width}({lhs_expr}, {rhs_expr}, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flags read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always<std::uint8_t>({addr}, static_cast<std::uint8_t>(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, [n for n in args.exports.split(",") if n]) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") diff --git a/tools/cpu_call_aot.py b/tools/cpu_call_aot.py index 99a9a7f988..1245df1627 100644 --- a/tools/cpu_call_aot.py +++ b/tools/cpu_call_aot.py @@ -1,8 +1,11 @@ """Recompile a bounded Windows x64 caller with direct calls or one ordinary import call.""" import argparse +import os from pathlib import Path import struct +import sys +import tempfile import pefile @@ -160,6 +163,9 @@ def lift_body(start, code, *, caller, bind_import=None, name=None, def resolve_import(pe, slot, provider, symbol, link_name=None): + provider = Path(provider) + if link_name is not None and (not isinstance(link_name, str) or not link_name.strip()): + raise ValueError("link name must not be empty") pe.parse_data_directories(directories=[1]) # ordinary import directory matches = [(desc.dll, imp) for desc in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []) for imp in desc.imports if imp.address - pe.OPTIONAL_HEADER.ImageBase == slot] @@ -194,8 +200,20 @@ def resolve_import(pe, slot, provider, symbol, link_name=None): def translate(image, entry, binding=None, link_name=None): - if link_name is not None and not binding: - raise ValueError("link name requires a provider binding") + if link_name is not None: + if not binding: + raise ValueError("link name requires a provider binding") + if not isinstance(link_name, str) or not link_name.strip(): + raise ValueError("link name must not be empty") + if binding: + if len(binding) != 2: + raise ValueError("expected provider path and symbol for --bind") + provider_raw, bind_symbol = binding + if not str(provider_raw).strip() or not isinstance(bind_symbol, str) or not bind_symbol.strip(): + raise ValueError("provider path and symbol must not be empty") + provider_path = Path(provider_raw) + if not provider_path.is_file(): + raise ValueError(f"missing provider for {provider_path.name}!{bind_symbol}") with pefile.PE(str(image), fast_load=True) as pe: start = export_rva(pe, entry) code = bounded_code(pe, start) @@ -225,7 +243,76 @@ def bind_import(slot): return f"#include <cstdint>\nusing word = std::uint64_t;\n{body}\n" -if __name__ == "__main__": +def _validate_paths( + image: Path, + export: str, + output: Path, + bind: list[str] | None = None, + link_name: str | None = None, +) -> None: + if image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {image}") + if not image.is_file(): + raise FileNotFoundError(f"image file not found: {image}") + if not isinstance(export, str) or not export.strip(): + raise ValueError("export name must not be empty") + if output.suffix.lower() != ".cpp": + raise ValueError(f"output path must have .cpp suffix: {output}") + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if link_name is not None: + if not bind: + raise ValueError("link name requires a provider binding") + if not isinstance(link_name, str) or not link_name.strip(): + raise ValueError("link name must not be empty") + if bind: + if len(bind) != 2: + raise ValueError("expected provider path and symbol for --bind") + provider_raw, bind_symbol = bind + if not str(provider_raw).strip() or not isinstance(bind_symbol, str) or not bind_symbol.strip(): + raise ValueError("provider path and symbol must not be empty") + provider = Path(provider_raw) + if not provider.is_file(): + raise ValueError(f"missing provider for {provider.name}!{bind_symbol}") + inputs = (image, provider) + else: + inputs = (image,) + out_resolved = output.resolve() + for input_path in inputs: + if out_resolved == input_path.resolve() or (output.exists() and input_path.samefile(output)): + raise ValueError(f"output path must not match input path: {output}") + + +def _write_atomic(path: Path, content: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, unlinking temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("export") @@ -233,8 +320,15 @@ def bind_import(slot): parser.add_argument("--bind", nargs=2, metavar=("PROVIDER_DLL", "SYMBOL"), help="export name or #ordinal with the fixture's two-word and output-pointer ABI") parser.add_argument("--link-name", help="local import-library symbol for an ordinal binding") - args = parser.parse_args() + args = parser.parse_args(argv) try: - args.output.write_text(translate(args.image, args.export, args.bind, args.link_name), encoding="utf-8") + _validate_paths(args.image, args.export, args.output, args.bind, args.link_name) + _write_atomic(args.output, translate(args.image, args.export, args.bind, args.link_name)) except (OSError, ValueError, pefile.PEFormatError) as error: - parser.exit(1, f"{error}\n") + sys.stderr.write(f"{error}\n") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_chained_aot.py b/tools/cpu_chained_aot.py index e1268ac0e9..bec80d6e79 100644 --- a/tools/cpu_chained_aot.py +++ b/tools/cpu_chained_aot.py @@ -1,8 +1,11 @@ """Lift acyclic pointer checks and early returns across AMD64 chained unwind ranges.""" import argparse +import os from pathlib import Path import re +import sys +import tempfile import pefile from iced_x86 import Code, Decoder, OpKind, Register as R, RegisterExt @@ -16,9 +19,15 @@ def translate(image, name, partial=False, callback_offset=None, ffx_destroy=False): + if not isinstance(name, str) or not name.strip(): + raise ValueError("export name must be non-empty") if ffx_destroy and (partial or callback_offset is not None): raise ValueError("the destroy contract requires a complete translation and its own typed bindings") - if callback_offset is not None and (not 0 <= callback_offset <= 0x7fffffff or callback_offset % 8): + if callback_offset is not None and ( + type(callback_offset) is not int + or not 0 <= callback_offset <= 0x7fffffff + or callback_offset % 8 + ): raise ValueError("callback slot must be a nonnegative aligned table offset") with pefile.PE(str(image), fast_load=True) as pe: entry = export_rva(pe, name) @@ -224,7 +233,53 @@ def walk(ip, regs, stack, sp, visited, indent, stage="entry", allocator_null=Non return source + "\n".join(lines) + "\n}\n", ranges, returns, stops -if __name__ == "__main__": +def _validate_cli_inputs(image: Path, export: str, output: Path) -> None: + if not image.is_file(): + raise ValueError(f"input image is not an existing file: {image}") + if not export.strip(): + raise ValueError("export name must not be empty") + if output.suffix.lower() != ".cpp": + raise ValueError(f"output path must have a .cpp suffix: {output}") + if output.is_symlink(): + raise ValueError(f"output path must not be a symbolic link: {output}") + if output.is_dir(): + raise ValueError(f"output path is a directory: {output}") + if output.parent.is_file() or (output.parent.exists() and not output.parent.is_dir()): + raise ValueError(f"output parent is not a directory: {output.parent}") + try: + same = output.resolve() == image.resolve() + except OSError: + same = False + if not same and output.exists(): + same = output.samefile(image) + if same: + raise ValueError(f"output path must not collide with input image: {output}") + + +def _write_atomic(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent)) + tmp_path = Path(tmp_name) + fd_open = True + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle: + fd_open = False + handle.write(text) + os.replace(tmp_path, path) + except BaseException: + if fd_open: + try: + os.close(fd) + except OSError: + pass + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("export") @@ -233,10 +288,19 @@ def walk(ip, regs, stack, sp, visited, indent, stage="entry", allocator_null=Non parser.add_argument("--ffx-destroy", action="store_true", help="use the verified FidelityFX destroy and cleanup ABI") parser.add_argument("--callback-offset", type=lambda s: int(s, 0), help="bind a table slot with a known Windows x64 word(word, word) callback ABI") - args = parser.parse_args() + args = parser.parse_args(argv) try: - source, ranges, returns, stops = translate(args.image, args.export, args.partial, args.callback_offset, args.ffx_destroy) - args.output.write_text(source, encoding="utf-8") + _validate_cli_inputs(args.image, args.export, args.output) + source, ranges, returns, stops = translate( + args.image, args.export, args.partial, args.callback_offset, args.ffx_destroy + ) + _write_atomic(args.output, source) print(f"{len(ranges)} owned ranges, {len(returns)} return paths, indirect stops: {sorted(stops)}") + return 0 except (ValueError, OSError, pefile.PEFormatError) as error: - parser.exit(1, f"{error}\n") + print(f"{error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_leaf_aot.py b/tools/cpu_leaf_aot.py index 7628396917..a6c4418a0b 100644 --- a/tools/cpu_leaf_aot.py +++ b/tools/cpu_leaf_aot.py @@ -1,8 +1,11 @@ """Lift a bounded AMD64 leaf function with the fixture's (uint32, uint32*) ABI to C++.""" import argparse +import os from pathlib import Path import struct +import sys +import tempfile import pefile @@ -52,6 +55,15 @@ def function_bytes(image, name): def translate(start, code): + if isinstance(start, bool) or not isinstance(start, int): + raise ValueError(f"expected integer start RVA, got {type(start).__name__}") + if start < 0: + raise ValueError(f"expected non-negative start RVA, got {start}") + if not isinstance(code, bytes): + try: + code = memoryview(code).tobytes() + except TypeError as exc: + raise ValueError(f"expected bytes-like code, got {type(code).__name__}") from exc # This profile initializes EAX from ECX before either branch. A compare and # its immediate consumer form one operation, so flags never cross a join. if not code.startswith((b"\x8b\xc1", b"\x89\xc8")): @@ -125,14 +137,65 @@ def translate(start, code): return "\n".join([*lines, "}", ""]) -if __name__ == "__main__": +def _validate_paths(image: Path, export: str, output: Path) -> None: + if image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {image}") + if not image.is_file(): + raise FileNotFoundError(f"image file not found: {image}") + if not isinstance(export, str) or not export.strip(): + raise ValueError("export name must not be empty") + if output.suffix.lower() != ".cpp": + raise ValueError(f"output path must have .cpp suffix: {output}") + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if output.resolve() == image.resolve() or (output.exists() and image.samefile(output)): + raise ValueError(f"output path must not match input image: {output}") + + +def _write_atomic(path: Path, content: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, unlinking temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("export") parser.add_argument("output", type=Path) - args = parser.parse_args() + args = parser.parse_args(argv) try: + _validate_paths(args.image, args.export, args.output) rva, code = function_bytes(args.image, args.export) - args.output.write_text(translate(rva, code), encoding="utf-8") + _write_atomic(args.output, translate(rva, code)) except (ValueError, OSError, pefile.PEFormatError) as error: - parser.exit(1, f"{error}\n") + sys.stderr.write(f"{error}\n") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_movbe_aot.py b/tools/cpu_movbe_aot.py new file mode 100644 index 0000000000..d439ee29de --- /dev/null +++ b/tools/cpu_movbe_aot.py @@ -0,0 +1,630 @@ +"""Lift bounded Windows x64 leaf functions with MOVBE (16/32/64-bit load & store) to C++. + +Each export uses the straight-line leaf ABI: + std::uint64_t lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported MOVBE instructions (docs/coverage/x64_zen2.tsv group MOVBE): + - MOVBE r16, m16 | MOVBE r32, m32 | MOVBE r64, m64 (loads from [rcx|rdx|r8 (+0..64)]) + - MOVBE m16, r16 | MOVBE m32, r32 | MOVBE m64, r64 (stores to [r8 (+0..64)]) + +Exact x64 semantics: + - 16-bit MOVBE load reverses 2 bytes and preserves destination bits [63:16]. + - 32-bit MOVBE load reverses 4 bytes and zero-extends bits [63:32]. + - 64-bit MOVBE load and all MOVBE stores reverse byte order. + - All 6 MOVBE forms leave RFLAGS (CF, ZF, SF, OF, PF, AF) completely unmodified. + - Memory operands are flat [rcx|rdx|r8] or [rcx|rdx|r8 + small_disp] (0 <= disp <= 64) + read/written unconditionally via load_always()/store_always() so /O2 cannot drop + faulting accesses. + +Transport / flag-testing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, xor, or, shl, movzx, setcc (reg or [r8+disp]), + flat [r8+disp] stores, and terminal ret. + +Stores outside [r8], negative or out-of-window displacements (> 64), indexed/scaled/RIP-rel +memory operands, nonvolatile GPRs, writes to argument GPRs (rcx/rdx/r8), high-byte GPRs, +undefined GPR or flag reads, VEX/EVEX/XOP encodings, instruction prefixes, branches/calls, +and missing or trailing instructions after ret are rejected. +""" + +import argparse +import os +from pathlib import Path +import sys +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} +MAX_DISPL = 64 + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8", + R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", R.R8D: "r8", + R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", R.CX: "rcx", R.DX: "rdx", R.R8W: "r8", + R.R9W: "r9", R.R10W: "r10", R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", R.R8L: "r8", + R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (is_store, width_bits) +MOVBE_SPECS = { + Code.MOVBE_R16_M16: (False, 16), + Code.MOVBE_R32_M32: (False, 32), + Code.MOVBE_R64_M64: (False, 64), + Code.MOVBE_M16_R16: (True, 16), + Code.MOVBE_M32_R32: (True, 32), + Code.MOVBE_M64_R64: (True, 64), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R16_RM16: 16, + Code.MOV_RM16_R16: 16, + Code.MOV_RM16_IMM16: 16, + Code.MOV_R16_IMM16: 16, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SHL_SPECS = { + Code.SHL_RM32_1: (32, True), + Code.SHL_RM32_IMM8: (32, False), + Code.SHL_RM64_1: (64, True), + Code.SHL_RM64_IMM8: (64, False), +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#if defined(_MSC_VER) +#include <intrin.h> +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template <class T> +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast<const void*>(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template <class T> +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint16_t bswap16(std::uint16_t v) { + return static_cast<std::uint16_t>((v >> 8) | (v << 8)); +} + +static inline std::uint32_t bswap32(std::uint32_t v) { + return ((v & 0x000000FFu) << 24) + | ((v & 0x0000FF00u) << 8) + | ((v & 0x00FF0000u) >> 8) + | ((v & 0xFF000000u) >> 24); +} + +static inline std::uint64_t bswap64(std::uint64_t v) { + return ((v & 0x00000000000000FFull) << 56) + | ((v & 0x000000000000FF00ull) << 40) + | ((v & 0x0000000000FF0000ull) << 24) + | ((v & 0x00000000FF000000ull) << 8) + | ((v & 0x000000FF00000000ull) >> 8) + | ((v & 0x0000FF0000000000ull) >> 24) + | ((v & 0x00FF000000000000ull) >> 40) + | ((v & 0xFF00000000000000ull) >> 56); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast<std::uint8_t>(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 16u) { + return (cur & ~0xFFFFull) | (val & 0xFFFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast<std::uint8_t>(masked)); +} + +static inline word op_shl(word cur, unsigned width, unsigned count, Flags& flags) { + const unsigned mask = (width == 32u) ? 31u : 63u; + const unsigned c = count & mask; + if (width == 32u) { + const std::uint32_t v = static_cast<std::uint32_t>(cur); + if (c == 0u) return static_cast<word>(v); + const std::uint32_t r = v << c; + flags.cf = ((v >> (32u - c)) & 1u) != 0u; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((r >> 31) & 1u) != (flags.cf ? 1u : 0u)); + flags.pf = parity_even(static_cast<std::uint8_t>(r)); + return static_cast<word>(r); + } + if (c == 0u) return cur; + const word r = cur << c; + flags.cf = ((cur >> (64u - c)) & 1ull) != 0ull; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((r >> 63) & 1ull) != (flags.cf ? 1ull : 0ull)); + flags.pf = parity_even(static_cast<std::uint8_t>(r)); + return r; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_movbe() { + int info[4]{}; + __cpuid(info, 1); + return (static_cast<std::uint32_t>(info[2]) & (1u << 22)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat [rcx|rdx|r8 (+0..64)] memory operand (stores only to [r8 (+0..64)]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & 0xFFFFFFFFFFFFFFFF + if disp > MAX_DISPL: + raise ValueError(f"out-of-range displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + name = ARGUMENTS[base] + return f"({name} + {disp:#x}ull)" if disp else name + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE16: + return ins.immediate16 & 0xFFFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO16: + return ins.immediate8to16 & 0xFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line MOVBE leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 16: "0xFFFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = { + 8: "std::uint8_t", + 16: "std::uint16_t", + 32: "std::uint32_t", + 64: "std::uint64_t", + }[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast<word>(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in MOVBE_SPECS: + is_store, width = MOVBE_SPECS[code] + ctype = {16: "std::uint16_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + bswap_fn = {16: "bswap16", 32: "bswap32", 64: "bswap64"}[width] + if is_store: + if ins.op0_kind != OpKind.MEMORY or ins.op1_kind != OpKind.REGISTER: + raise ValueError(f"unsupported movbe store operands at RVA {ins.ip:#x}: {ins}") + src_expr = read_reg(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + statements.append( + f"store_always<{ctype}>({addr}, {bswap_fn}(static_cast<{ctype}>({src_expr})));" + ) + else: + if ins.op0_kind != OpKind.REGISTER or ins.op1_kind != OpKind.MEMORY: + raise ValueError(f"unsupported movbe load operands at RVA {ins.ip:#x}: {ins}") + addr = flat_address(ins, width // 8, write=False) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + load_var = f"ld_{ins.ip:x}_1" + statements.append(f"const word {load_var} = static_cast<word>({bswap_fn}(load_always<{ctype}>({addr})));") + statements.append(f"{dst} = update_gpr_width({dst}, {load_var}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + ctype = { + 8: "std::uint8_t", + 16: "std::uint16_t", + 32: "std::uint32_t", + 64: "std::uint64_t", + }[width] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SHL_SPECS: + width, is_one = SHL_SPECS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + cnt = 1 if is_one else (ins.immediate8 & 0xFF) + eff = cnt & (31 if width == 32 else 63) + statements.append(f"{dst} = op_shl({dst}, {width}u, {cnt}u, flags);") + if eff == 1: + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif eff > 1: + defined_flags = {"cf", "zf", "sf", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always<std::uint8_t>({addr}, static_cast<std::uint8_t>(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + decls.append(" (void)flags;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _same_path(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return a.resolve(strict=False) == b.resolve(strict=False) + + +def _write_atomic(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image is not a regular file: {args.image}") + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + if args.output.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {args.output}") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path is a directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"output path matches input image: {args.output}") + source, meta = translate(args.image, names) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + return 0 + except (ValueError, OSError, pefile.PEFormatError) as error: + sys.stderr.write(f"{error}\n") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/cpu_ranges.py b/tools/cpu_ranges.py index 2345501295..1729287a4f 100644 --- a/tools/cpu_ranges.py +++ b/tools/cpu_ranges.py @@ -3,9 +3,20 @@ import struct +def _require_int(value, name): + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"expected integer {name}, got {type(value).__name__}") + return value + + def image_bytes(pe, rva, size, executable=False): + rva = _require_int(rva, "rva") + size = _require_int(size, "size") + if rva < 0 or size <= 0: + raise ValueError(f"invalid file-backed range at RVA {rva:#x}") section = pe.get_section_by_rva(rva) - if (not section or size <= 0 or (executable and not section.Characteristics & 0x20000000) + if (not section or rva < section.VirtualAddress + or (executable and not section.Characteristics & 0x20000000) or rva + size - section.VirtualAddress > min(section.Misc_VirtualSize, section.SizeOfRawData)): raise ValueError(f"invalid file-backed range at RVA {rva:#x}") data = pe.get_data(rva, size) @@ -15,10 +26,15 @@ def image_bytes(pe, rva, size, executable=False): def function_ranges(pe, entry): + entry = _require_int(entry, "entry") + if entry < 0: + raise ValueError(f"invalid entry RVA {entry:#x}") directories = pe.OPTIONAL_HEADER.DATA_DIRECTORY if len(directories) < 4: raise ValueError("image has no runtime-function directory") table = directories[3] + if table.VirtualAddress == 0 or table.Size <= 0: + raise ValueError("image has no runtime-function directory") if table.Size % 12: raise ValueError("incomplete runtime-function record") records = list(struct.iter_unpack("<III", image_bytes(pe, table.VirtualAddress, table.Size))) diff --git a/tools/cpu_sse41_fp_aot.py b/tools/cpu_sse41_fp_aot.py new file mode 100644 index 0000000000..e5c1ca2d12 --- /dev/null +++ b/tools/cpu_sse41_fp_aot.py @@ -0,0 +1,716 @@ +"""Lift bounded Windows x64 leaf functions with legacy SSE4.1 FP ops to C++. + +Each export uses the straight-line leaf ABI: + void lifted_<name>(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned buffers. XMM0..XMM5 +are modeled as portable 128-bit value structs (two 64-bit lanes); volatile scratch +GPRs (rax, r9, r10, r11) are modeled as 64-bit words for EXTRACTPS and 32/64-bit +mov glue. + +Supported legacy SSE4.1 FP encodings (docs/coverage/x64_zen2.tsv group SSE3-4): + - ROUNDPS, ROUNDPD: imm8[1:0] when imm8[2]==0 else host MXCSR RC; handles -0.0, + +/-Inf, qNaN/sNaN quieting, and MXCSR DAZ. + - ROUNDSS, ROUNDSD: scalar rounding preserving destination bits [127:32]/[127:64]. + - DPPS, DPPD: dot product using source mask imm8[7:4]/[5:4] and destination mask + imm8[3:0]/[1:0] (disabled outputs set to +0.0), executing under host MXCSR + (rounding mode, DAZ, FTZ). + - INSERTPS: inserts count_s=imm8[7:6] from xmm (or lane 0 from m32) into + count_d=imm8[5:4] of dst, then applies zmask=imm8[3:0] last. + - EXTRACTPS: extracts lane imm8[1:0] to scratch r32/r64 (zero-extending [63:32]) + or flat m32 [r8]. + +Transport / ABI glue: + - MOVAPS, MOVAPD, MOVDQA (128-bit reg-reg, 16-byte-aligned flat loads & [r8] stores) + - MOVUPS, MOVUPD, MOVDQU (128-bit reg-reg, flat loads & [r8] stores) + - MOVSS, MOVSD (scalar load/store/reg-merge) + - MOV (32/64-bit scratch GPR reg-reg, flat load, [r8] store) and terminal RET. + +VEX/EVEX encodings, nonvolatile XMM6..15 / GPRs, writes to argument GPRs, undefined +reads, unaligned 128-bit aligned-only memory operands, non-flat memory operands, +non-[r8] stores, prefixes, branches, and trailing or missing ret are rejected. +""" + +import argparse +from pathlib import Path +import tempfile + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_GPRS = {R.RCX, R.ECX, R.CL, R.RDX, R.EDX, R.DL, R.R8, R.R8D, R.R8L} + +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) + +SCRATCH_GPR64 = {R.RAX: "rax", R.R9: "r9", R.R10: "r10", R.R11: "r11"} +SCRATCH_GPR32 = {R.EAX: "rax", R.R9D: "r9", R.R10D: "r10", R.R11D: "r11"} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +LOAD_ALIGNED_VEC_CODES = { + Code.MOVAPS_XMM_XMMM128, + Code.MOVAPD_XMM_XMMM128, + Code.MOVDQA_XMM_XMMM128, +} +STORE_ALIGNED_VEC_CODES = { + Code.MOVAPS_XMMM128_XMM, + Code.MOVAPD_XMMM128_XMM, + Code.MOVDQA_XMMM128_XMM, +} +LOAD_UNALIGNED_VEC_CODES = { + Code.MOVUPS_XMM_XMMM128, + Code.MOVUPD_XMM_XMMM128, + Code.MOVDQU_XMM_XMMM128, +} +STORE_UNALIGNED_VEC_CODES = { + Code.MOVUPS_XMMM128_XMM, + Code.MOVUPD_XMMM128_XMM, + Code.MOVDQU_XMMM128_XMM, +} +MOVSS_REG_CODES = {Code.MOVSS_XMM_XMMM32, Code.MOVSS_XMMM32_XMM} +MOVSD_REG_CODES = {Code.MOVSD_XMM_XMMM64, Code.MOVSD_XMMM64_XMM} +EXTRACTPS_CODES = {Code.EXTRACTPS_RM32_XMM_IMM8, Code.EXTRACTPS_R64M32_XMM_IMM8} +MOV_GPR_CODES = { + Code.MOV_R32_RM32: False, + Code.MOV_RM32_R32: False, + Code.MOV_R64_RM64: True, + Code.MOV_RM64_R64: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.ROUNDPS_XMM_XMMM128_IMM8, + Code.ROUNDPD_XMM_XMMM128_IMM8, + Code.ROUNDSS_XMM_XMMM32_IMM8, + Code.ROUNDSD_XMM_XMMM64_IMM8, + Code.DPPS_XMM_XMMM128_IMM8, + Code.DPPD_XMM_XMMM128_IMM8, + Code.INSERTPS_XMM_XMMM32_IMM8, + *EXTRACTPS_CODES, + *LOAD_ALIGNED_VEC_CODES, + *STORE_ALIGNED_VEC_CODES, + *LOAD_UNALIGNED_VEC_CODES, + *STORE_UNALIGNED_VEC_CODES, + *MOVSS_REG_CODES, + *MOVSD_REG_CODES, + *MOV_GPR_CODES, +} + +PRELUDE = """#include <atomic> +#include <cstdint> +#include <cstring> +#include <emmintrin.h> +#if defined(_MSC_VER) +#include <intrin.h> +#define X2W_UNALIGNED __unaligned +#else +#define X2W_UNALIGNED +#endif + +using word = std::uint64_t; + +struct Vec128 { + std::uint64_t q[2]; +}; + +static inline std::uint32_t load32(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint32_t v = *reinterpret_cast<const volatile std::uint32_t X2W_UNALIGNED*>(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline std::uint64_t load64(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const std::uint64_t v = *reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +static inline Vec128 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const auto* p = reinterpret_cast<const volatile std::uint64_t X2W_UNALIGNED*>(address); + const std::uint64_t q0 = p[0]; + const std::uint64_t q1 = p[1]; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{q0, q1}}; +} + +static inline void store32(word address, std::uint32_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &val, 4); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t val) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), &val, 8); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast<void*>(address), v.q, 16); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint32_t lane32(const Vec128& v, unsigned i) { + return static_cast<std::uint32_t>(v.q[i >> 1] >> ((i & 1u) * 32u)); +} + +static inline void set_lane32(Vec128& v, unsigned i, std::uint32_t val) { + const unsigned shift = (i & 1u) * 32u; + v.q[i >> 1] = (v.q[i >> 1] & ~(0xffffffffull << shift)) | (static_cast<std::uint64_t>(val) << shift); +} + +static inline std::uint32_t round_mode(std::uint8_t imm8) { + if ((imm8 & 4u) == 0u) { + return static_cast<std::uint32_t>(imm8 & 3u); + } + return (_mm_getcsr() >> 13u) & 3u; +} + +static inline std::int64_t round_double_to_int(double val, std::uint32_t rc) { + const std::int64_t t = static_cast<std::int64_t>(val); + const double tf = static_cast<double>(t); + if (rc == 1u) { + return (tf > val) ? (t - 1) : t; + } + if (rc == 2u) { + return (tf < val) ? (t + 1) : t; + } + if (rc == 3u) { + return t; + } + const double rem = val - tf; + if (val >= 0.0) { + return (rem > 0.5 || (rem == 0.5 && (t & 1) != 0)) ? (t + 1) : t; + } + return (rem < -0.5 || (rem == -0.5 && (t & 1) != 0)) ? (t - 1) : t; +} + +static inline std::uint32_t round_f32_bits(std::uint32_t bits, std::uint8_t imm8) { + const volatile std::uint32_t vb = bits; + const std::uint32_t raw = vb; + const std::uint32_t abs_bits = raw & 0x7fffffffu; + const std::uint32_t sign_bit = raw & 0x80000000u; + if (abs_bits > 0x7f800000u) { + return raw | 0x00400000u; + } + if (abs_bits == 0x7f800000u || abs_bits == 0u) { + return raw; + } + if ((_mm_getcsr() & 0x0040u) != 0u && abs_bits < 0x00800000u) { + return sign_bit; + } + if (abs_bits >= 0x4b000000u) { + return raw; + } + float f = 0.0f; + std::memcpy(&f, &raw, 4); + const std::int64_t n = round_double_to_int(static_cast<double>(f), round_mode(imm8)); + if (n == 0) { + return sign_bit; + } + const float out_f = static_cast<float>(n); + std::uint32_t out_bits = 0u; + std::memcpy(&out_bits, &out_f, 4); + return out_bits; +} + +static inline std::uint64_t round_f64_bits(std::uint64_t bits, std::uint8_t imm8) { + const volatile std::uint64_t vb = bits; + const std::uint64_t raw = vb; + const std::uint64_t abs_bits = raw & 0x7fffffffffffffffull; + const std::uint64_t sign_bit = raw & 0x8000000000000000ull; + if (abs_bits > 0x7ff0000000000000ull) { + return raw | 0x0008000000000000ull; + } + if (abs_bits == 0x7ff0000000000000ull || abs_bits == 0ull) { + return raw; + } + if ((_mm_getcsr() & 0x0040u) != 0u && abs_bits < 0x0010000000000000ull) { + return sign_bit; + } + if (abs_bits >= 0x4330000000000000ull) { + return raw; + } + double d = 0.0; + std::memcpy(&d, &raw, 8); + const std::int64_t n = round_double_to_int(d, round_mode(imm8)); + if (n == 0) { + return sign_bit; + } + const double out_d = static_cast<double>(n); + std::uint64_t out_bits = 0ull; + std::memcpy(&out_bits, &out_d, 8); + return out_bits; +} + +static inline Vec128 op_roundps(const Vec128& src, std::uint8_t imm8) { + Vec128 out{}; + for (unsigned i = 0; i < 4u; ++i) { + set_lane32(out, i, round_f32_bits(lane32(src, i), imm8)); + } + return out; +} + +static inline Vec128 op_roundpd(const Vec128& src, std::uint8_t imm8) { + return {{round_f64_bits(src.q[0], imm8), round_f64_bits(src.q[1], imm8)}}; +} + +static inline Vec128 op_roundss(const Vec128& dst, std::uint32_t src32, std::uint8_t imm8) { + Vec128 out = dst; + set_lane32(out, 0u, round_f32_bits(src32, imm8)); + return out; +} + +static inline Vec128 op_roundsd(const Vec128& dst, std::uint64_t src64, std::uint8_t imm8) { + return {{round_f64_bits(src64, imm8), dst.q[1]}}; +} + +static inline __m128 sse_ss_from_bits(std::uint32_t bits) { + const volatile std::uint32_t vb = bits; + return _mm_castsi128_ps(_mm_cvtsi32_si128(static_cast<int>(vb))); +} + +static inline std::uint32_t bits_from_sse_ss(__m128 v) { + return static_cast<std::uint32_t>(_mm_cvtsi128_si32(_mm_castps_si128(v))); +} + +static inline __m128d sse_sd_from_bits(std::uint64_t bits) { + const volatile std::uint64_t vb = bits; + return _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast<long long>(vb))); +} + +static inline std::uint64_t bits_from_sse_sd(__m128d v) { + return static_cast<std::uint64_t>(_mm_cvtsi128_si64(_mm_castpd_si128(v))); +} + +// DPPS executes products and pairwise sums via host SSE2 so MXCSR RC, DAZ, FTZ, +// +/-0.0, Inf, and NaN quieting match the host processor. +static inline Vec128 op_dpps(const Vec128& a, const Vec128& b, std::uint8_t imm8) { + __m128 t[4]; + for (unsigned k = 0; k < 4u; ++k) { + if ((imm8 & (1u << (4u + k))) != 0u) { + t[k] = _mm_mul_ss(sse_ss_from_bits(lane32(a, k)), sse_ss_from_bits(lane32(b, k))); + } else { + t[k] = _mm_setzero_ps(); + } + } + const __m128 s01 = _mm_add_ss(t[0], t[1]); + const __m128 s23 = _mm_add_ss(t[2], t[3]); + const std::uint32_t sum = bits_from_sse_ss(_mm_add_ss(s01, s23)); + Vec128 out{}; + for (unsigned k = 0; k < 4u; ++k) { + set_lane32(out, k, ((imm8 >> k) & 1u) != 0u ? sum : 0u); + } + return out; +} + +static inline Vec128 op_dppd(const Vec128& a, const Vec128& b, std::uint8_t imm8) { + __m128d t[2]; + for (unsigned k = 0; k < 2u; ++k) { + if ((imm8 & (1u << (4u + k))) != 0u) { + t[k] = _mm_mul_sd(sse_sd_from_bits(a.q[k]), sse_sd_from_bits(b.q[k])); + } else { + t[k] = _mm_setzero_pd(); + } + } + const std::uint64_t sum = bits_from_sse_sd(_mm_add_sd(t[0], t[1])); + return {{ + (imm8 & 1u) != 0u ? sum : 0ull, + (imm8 & 2u) != 0u ? sum : 0ull, + }}; +} + +static inline Vec128 op_insertps(const Vec128& dst, std::uint32_t src_lane, std::uint8_t imm8) { + Vec128 out = dst; + const unsigned count_d = (imm8 >> 4u) & 3u; + set_lane32(out, count_d, src_lane); + for (unsigned k = 0; k < 4u; ++k) { + if (((imm8 >> k) & 1u) != 0u) { + set_lane32(out, k, 0u); + } + } + return out; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_sse41() { + int info[4]{}; + __cpuid(info, 1); + return (info[2] & (1 << 19)) != 0 ? 1u : 0u; +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif +""" + + +def vec_index(register, ins): + """Map XMM0..XMM5 to an index, rejecting nonvolatile and unsupported registers.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def gpr_target(register, ins, *, write=False): + """Map scratch GPR32/GPR64 to its 64-bit variable name, rejecting nonvolatile/arg writes.""" + if register in SCRATCH_GPR64: + return SCRATCH_GPR64[register] + if register in SCRATCH_GPR32: + return SCRATCH_GPR32[register] + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + if write and register in ARGUMENT_GPRS: + raise ValueError(f"write to argument GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, alignment=1, write=False, expected_size=None): + """Lower a flat zero-displacement [rcx|rdx|r8] pointer operand (stores restricted to [r8]).""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or ins.memory_displacement != 0 + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported memory base {base} at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + if expected_size is not None and MemorySizeExt.size(ins.memory_size) != expected_size: + raise ValueError(f"unsupported memory size at RVA {ins.ip:#x}: {ins}") + if alignment > 1 and (ins.memory_displacement % alignment) != 0: + raise ValueError(f"unaligned {alignment}-byte memory operand at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line legacy SSE4.1 FP leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used_vec = set() + defined_vec = set() + used_gpr = set() + defined_gpr = set() + statements = [] + returned = False + + def read_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + if idx not in defined_vec: + raise ValueError(f"undefined vector register xmm{idx} at RVA {ins.ip:#x}: {ins}") + used_vec.add(idx) + return f"xmm{idx}" + + def write_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + used_vec.add(idx) + return idx, f"xmm{idx}" + + def vec_src128(op_index, ins, *, alignment): + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load128({flat_address(ins, alignment=alignment, expected_size=16)})" + return read_vec(op_index, ins) + + def read_gpr(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected GPR operand {op_index} at RVA {ins.ip:#x}: {ins}") + gpr = gpr_target(ins.op_register(op_index), ins, write=False) + if gpr not in defined_gpr: + raise ValueError(f"undefined GPR {gpr} at RVA {ins.ip:#x}: {ins}") + used_gpr.add(gpr) + return gpr + + def write_gpr(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected GPR destination at RVA {ins.ip:#x}: {ins}") + gpr = gpr_target(ins.op_register(op_index), ins, write=True) + used_gpr.add(gpr) + return gpr + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + if ins.op_code().encoding != EncodingKind.LEGACY: + raise ValueError(f"non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + elif ins.code in (Code.ROUNDPS_XMM_XMMM128_IMM8, Code.ROUNDPD_XMM_XMMM128_IMM8): + helper = "op_roundpd" if ins.code == Code.ROUNDPD_XMM_XMMM128_IMM8 else "op_roundps" + imm = ins.immediate8 & 0x0F + src = vec_src128(1, ins, alignment=16) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {helper}({src}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code == Code.ROUNDSS_XMM_XMMM32_IMM8: + imm = ins.immediate8 & 0x0F + dst_in = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src32 = f"load32({flat_address(ins, expected_size=4)})" + else: + src32 = f"lane32({read_vec(1, ins)}, 0u)" + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = op_roundss({dst_in}, {src32}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code == Code.ROUNDSD_XMM_XMMM64_IMM8: + imm = ins.immediate8 & 0x0F + dst_in = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src64 = f"load64({flat_address(ins, expected_size=8)})" + else: + src64 = f"{read_vec(1, ins)}.q[0]" + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = op_roundsd({dst_in}, {src64}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code in (Code.DPPS_XMM_XMMM128_IMM8, Code.DPPD_XMM_XMMM128_IMM8): + helper = "op_dppd" if ins.code == Code.DPPD_XMM_XMMM128_IMM8 else "op_dpps" + imm = ins.immediate8 & 0xFF + dst_in = read_vec(0, ins) + src = vec_src128(1, ins, alignment=16) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {helper}({dst_in}, {src}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code == Code.INSERTPS_XMM_XMMM32_IMM8: + imm = ins.immediate8 & 0xFF + dst_in = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src32 = f"load32({flat_address(ins, expected_size=4)})" + else: + count_s = (imm >> 6) & 3 + src32 = f"lane32({read_vec(1, ins)}, {count_s}u)" + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = op_insertps({dst_in}, {src32}, {imm:#x}u);") + defined_vec.add(dst_idx) + elif ins.code in EXTRACTPS_CODES: + lane = ins.immediate8 & 3 + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, write=True, expected_size=4) + statements.append(f"store32({addr}, lane32({src}, {lane}u));") + else: + gpr = write_gpr(0, ins) + statements.append(f"{gpr} = static_cast<word>(lane32({src}, {lane}u));") + defined_gpr.add(gpr) + elif ins.code in (*LOAD_ALIGNED_VEC_CODES, *LOAD_UNALIGNED_VEC_CODES): + align = 16 if ins.code in LOAD_ALIGNED_VEC_CODES else 1 + src = vec_src128(1, ins, alignment=align) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {src};") + defined_vec.add(dst_idx) + elif ins.code in (*STORE_ALIGNED_VEC_CODES, *STORE_UNALIGNED_VEC_CODES): + align = 16 if ins.code in STORE_ALIGNED_VEC_CODES else 1 + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, alignment=align, write=True, expected_size=16) + statements.append(f"store128({addr}, {src});") + else: + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = {src};") + defined_vec.add(dst_idx) + elif ins.code in MOVSS_REG_CODES: + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=4) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = Vec128{{static_cast<std::uint64_t>(load32({addr})), 0ull}};") + defined_vec.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins) + addr = flat_address(ins, write=True, expected_size=4) + statements.append(f"store32({addr}, lane32({src}, 0u));") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst = write_vec(0, ins) + statements.append(f"set_lane32({dst}, 0u, lane32({src}, 0u));") + defined_vec.add(dst_idx) + else: + raise ValueError(f"unsupported movss operands at RVA {ins.ip:#x}: {ins}") + elif ins.code in MOVSD_REG_CODES: + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=8) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst} = Vec128{{load64({addr}), 0ull}};") + defined_vec.add(dst_idx) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_vec(1, ins) + addr = flat_address(ins, write=True, expected_size=8) + statements.append(f"store64({addr}, {src}.q[0]);") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + read_vec(0, ins) + src = read_vec(1, ins) + dst_idx, dst = write_vec(0, ins) + statements.append(f"{dst}.q[0] = {src}.q[0];") + defined_vec.add(dst_idx) + else: + raise ValueError(f"unsupported movsd operands at RVA {ins.ip:#x}: {ins}") + elif ins.code in MOV_GPR_CODES: + is64 = MOV_GPR_CODES[ins.code] + sz = 8 if is64 else 4 + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + addr = flat_address(ins, expected_size=sz) + dst = write_gpr(0, ins) + loader = f"load64({addr})" if is64 else f"static_cast<word>(load32({addr}))" + statements.append(f"{dst} = {loader};") + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src = read_gpr(1, ins) + addr = flat_address(ins, write=True, expected_size=sz) + if is64: + statements.append(f"store64({addr}, {src});") + else: + statements.append(f"store32({addr}, static_cast<std::uint32_t>({src}));") + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src = read_gpr(1, ins) + dst = write_gpr(0, ins) + expr = src if is64 else f"static_cast<word>(static_cast<std::uint32_t>({src}))" + statements.append(f"{dst} = {expr};") + defined_gpr.add(dst) + else: + raise ValueError(f"unsupported GPR mov operands at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec128 xmm{idx}{{}};" for idx in sorted(used_vec)] + decls.extend(f" word {gpr} = 0ull;" for gpr in sorted(used_gpr)) + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +def _write_atomic(path: Path, content: str) -> None: + if path.exists() and path.is_dir(): + raise ValueError(f"output path must not be a directory: {path}") + if path.is_symlink(): + raise ValueError(f"output path must not be a symlink: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + if not args.image.is_file(): + raise ValueError(f"input image must be a regular file: {args.image}") + exports = [name for name in args.exports.split(",") if name] + if not exports: + raise ValueError("exports list must not be empty") + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"output path must not be a directory: {args.output}") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + source, meta = translate(args.image, exports) + _write_atomic(args.output, source) + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"cpu_sse41_fp_aot: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/dxc_cache.py b/tools/dxc_cache.py index 8a9f36161c..8f9cd73e06 100644 --- a/tools/dxc_cache.py +++ b/tools/dxc_cache.py @@ -5,6 +5,7 @@ about (includes, -I, response files, unknown -F outputs, extra run options) bypasses it, so a cached result is never reused for a different compile. """ +import errno import hashlib import json import os @@ -83,8 +84,47 @@ def _store(path, payload): def _write_file(path, data): - with open(path, "wb") as out: - out.write(data) + """Write data to path atomically, refusing symlink or directory targets.""" + target = os.fspath(path) + stripped = os.path.normpath(target) + if os.path.islink(target) or os.path.islink(stripped): + raise OSError(errno.ELOOP, "refusing symlink target", target) + if target.endswith(("/", "\\")) or os.path.isdir(target): + raise IsADirectoryError(errno.EISDIR, "refusing directory target", target) + parent = os.path.dirname(os.path.abspath(target)) + handle, temp = tempfile.mkstemp(dir=parent, prefix=".tmp-", suffix=".tmp") + closed = False + try: + with os.fdopen(handle, "wb") as out: + closed = True + out.write(data) + os.replace(temp, target) + except BaseException: + if not closed: + os.close(handle) + if os.path.exists(temp): + os.unlink(temp) + raise + + +def _valid_cache_dir(cache_dir): + """Return True when cache_dir is usable and neither symlink- nor file-backed.""" + if not cache_dir: + return False + target = os.path.normpath(os.fspath(cache_dir)) + if os.path.islink(target): + return False + if os.path.lexists(target): + return os.path.isdir(target) + probe = os.path.dirname(os.path.abspath(target)) + while probe: + if os.path.lexists(probe): + return os.path.isdir(probe) + parent = os.path.dirname(probe) + if parent == probe: + break + probe = parent + return True def _emit(result_bytes, text, stream): @@ -143,7 +183,7 @@ def run_dxc(compiler, args, **options): cache_dir = os.environ.get(ENV_VAR) plan = None resolved = None - if cache_dir and not extra: + if _valid_cache_dir(cache_dir) and not extra: resolved = _resolve(compiler) if resolved is not None and not _is_wrapper(resolved): plan = _plan(compiler, args) diff --git a/tools/dxc_compile_time.py b/tools/dxc_compile_time.py index 9bf68e7583..3d9011cfca 100644 --- a/tools/dxc_compile_time.py +++ b/tools/dxc_compile_time.py @@ -43,6 +43,7 @@ import csv from datetime import datetime, timezone import json +import math import os from pathlib import Path import re @@ -584,8 +585,8 @@ def main(argv=None) -> int: parser.error("--repeat must be at least 1") if args.timeout is None: parser.error("--timeout is required; pass the local policy value, for example 90") - if args.timeout <= 0: - parser.error("--timeout must be positive") + if not math.isfinite(args.timeout) or args.timeout <= 0: + parser.error("--timeout must be a finite positive number") if args.dxc is None: parser.error("--dxc is required unless --list-variants is given") if not args.dxc.is_file(): diff --git a/tools/exe_aot.py b/tools/exe_aot.py index 7a00cc1b20..000e16d99d 100644 --- a/tools/exe_aot.py +++ b/tools/exe_aot.py @@ -10,7 +10,7 @@ import hashlib import json import os -from pathlib import Path +from pathlib import Path, PureWindowsPath import re import shutil import subprocess @@ -143,6 +143,7 @@ def build(cxx, source, exe, *, timeout=BUILD_TIMEOUT_S): compiler = shutil.which(str(cxx)) if cxx else shutil.which("cl") if compiler is None: raise Refusal("build", f"C++ compiler {cxx or 'cl'} not found; run tools/dev.ps1 or pass --cxx") + compiler_name = PureWindowsPath(compiler).name # The provenance export would otherwise make the linker write an import library and .exp file. command = [compiler, *CXX_FLAGS, source.name, f"/Fe{exe.name}", f"/Fo{source.stem}.obj", "/link", "/NOIMPLIB", "/NOEXP"] @@ -163,15 +164,15 @@ def build(cxx, source, exe, *, timeout=BUILD_TIMEOUT_S): ) raise Refusal( "build", - f"{Path(compiler).name} timed out after {exc.timeout}s", + f"{compiler_name} timed out after {exc.timeout}s", output=_tail_lines(combined), ) from exc except (OSError, subprocess.SubprocessError) as exc: - raise Refusal("build", f"failed to run {Path(compiler).name}: {exc}") from exc + raise Refusal("build", f"failed to run {compiler_name}: {exc}") from exc if result.returncode or not exe.is_file(): tail = _tail_lines((result.stdout or "") + (result.stderr or "")) - raise Refusal("build", f"{Path(compiler).name} exited {result.returncode}", output=tail) - return Path(compiler).name + raise Refusal("build", f"{compiler_name} exited {result.returncode}", output=tail) + return compiler_name def convert(image, out_dir, *, entry_export=None, cxx=None, compile_exe=True): diff --git a/tools/ffx_create_context.py b/tools/ffx_create_context.py index 1346166f1c..616696bd7f 100644 --- a/tools/ffx_create_context.py +++ b/tools/ffx_create_context.py @@ -1,6 +1,8 @@ """Statically bind the inspected loader's create path to a host-owned provider table.""" import argparse +import os from pathlib import Path +import tempfile import pefile @@ -67,18 +69,59 @@ def generate(path): "r8 = reinterpret_cast<word>(allocator);"]) -def main(argv=None): +def _validate_paths(loader: Path, output: Path, parser: argparse.ArgumentParser) -> None: + if loader.is_dir(): + raise IsADirectoryError(f"loader path is a directory: {loader}") + if not loader.is_file(): + raise FileNotFoundError(f"loader file not found: {loader}") + if output.suffix.lower() != ".cpp": + parser.error("choose a separate .cpp output") + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if output.resolve() == loader.resolve() or (output.exists() and loader.samefile(output)): + parser.error("choose a separate .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("loader", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args(argv) try: - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.loader.resolve(): - parser.error("choose a separate .cpp output") - args.output.write_text(generate(args.loader), encoding="ascii") + _validate_paths(args.loader, args.output, parser) + _write_atomic(args.output, generate(args.loader)) except (OSError, ValueError, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/tools/ffx_scratch_reference.py b/tools/ffx_scratch_reference.py index 78364b59cb..4bab3b5972 100644 --- a/tools/ffx_scratch_reference.py +++ b/tools/ffx_scratch_reference.py @@ -4,6 +4,7 @@ It evaluates only the integer network and its quantizers. No generated HLSL is parsed or executed. The four final logits suffice for spatially constant colors. """ +from collections.abc import Mapping import re import struct @@ -21,6 +22,8 @@ def signed(x): def simm16(token): + if not isinstance(token, str): + raise ValueError(f"Invalid 16-bit signed immediate: {token!r}") value = int(token, 0) if -0x8000 <= value < 0: return value & 0xffffffff @@ -34,6 +37,8 @@ def seed(x, y, c): def network(program, taps, initializer, stage): + if isinstance(stage, bool) or not isinstance(stage, int) or stage not in (24, 26): + raise ValueError(f"Expected network stage 24 or 26, got {stage!r}") regs = {"s16": 0} # group z logits = [] tap = 0 @@ -50,8 +55,15 @@ def network(program, taps, initializer, stage): tap += 1 continue if mn == "s_buffer_load_dwordx16": + if not src: + raise ValueError("Missing constant-buffer offset for s_buffer_load_dwordx16") first = int(dst.split(":")[0][2:]) - for i, val in enumerate(struct.unpack_from("<16I", initializer, int(src[-1], 0))): + offset = int(src[-1], 0) + if offset < 0 or offset % 4 != 0 or offset + 64 > len(initializer): + raise ValueError( + f"Constant-buffer offset {offset} out of bounds for {len(initializer)}-byte initializer" + ) + for i, val in enumerate(struct.unpack_from("<16I", initializer, offset)): regs[f"s{first+i}"] = val continue if stage == 24 and mn == "buffer_store_dwordx4": @@ -111,6 +123,8 @@ def value(s): def make_reference(programs, initializer): + if not isinstance(programs, Mapping) or "pass24" not in programs or "producer" not in programs: + raise ValueError("Expected programs mapping with 'pass24' and 'producer'") rows, gates = [], [] for mode in range(3): # The 6x4 union includes a pass-24 overdispatch column at x=5. diff --git a/tools/ffx_version_query.py b/tools/ffx_version_query.py index e5cd253ed1..6846c594a0 100644 --- a/tools/ffx_version_query.py +++ b/tools/ffx_version_query.py @@ -47,6 +47,11 @@ for opcode in ("0F19", "0F1D", "0F1E", "0F1F") ) +# CET indirect-branch tracking markers (F3 0F 1E FA = ENDBR64, F3 0F 1E FB = ENDBR32). +# Intel SDM Vol. 2A documents no register, flag, or memory side effects; x64_zen2 has no CET-IBT so both +# execute as NOPs. Selected by exact iced Code so RDSSPD/RDSSPQ (F3 0F 1E /1) remain refused. +_ENDBR_CODES = frozenset((C.ENDBR64, C.ENDBR32)) + INTEGER_HEADER = """#include <array> #include <cmath> #include <cstdint> @@ -594,6 +599,7 @@ def lower(body, initial, globals_, calls, exits, *, host_ops=None, x87=False, ho M.SHUFPS, M.UNPCKHPS, M.UNPCKLPS, M.MOVHLPS, M.MOVLHPS, M.MOVMSKPS, M.MOVUPS, M.MOVAPS, M.RCPPS, M.RCPSS, M.RSQRTPS, M.RSQRTSS, M.SHUFPD, M.UNPCKHPD, M.UNPCKLPD, M.MOVMSKPD, M.MOVUPD, M.MOVAPD, M.MOVDQA, + M.MOVNTPS, M.MOVNTPD, M.MOVNTDQ, M.VSHUFPS, M.VUNPCKHPS, M.VUNPCKLPS, M.VSHUFPD, M.VUNPCKHPD, M.VUNPCKLPD, M.VPSHUFD, M.VPSHUFHW, M.VPSHUFLW, M.VMOVHLPS, M.VMOVLHPS, M.VMOVMSKPS, M.VMOVMSKPD, M.VMOVAPS, M.VMOVAPD, M.VMOVDQA, M.VPMOVMSKB, M.VRCPPS, M.VRCPSS, M.VRSQRTPS, M.VRSQRTSS, @@ -918,6 +924,12 @@ def write_register(dest, expr): stmt = f"{decrement} if ({count} != 0{condition}) goto block_{target:x};" elif op in (M.MOV, M.MOVZX): stmt = write(operand(1)) + elif op == M.MOVNTI and i.op0_kind == K.MEMORY and i.op1_kind == K.REGISTER: + # A non-temporal store of a 32- or 64-bit register, with no alignment requirement and no flag change. + if MemorySizeExt.size(i.memory_size) == 8: + stmt = f"_mm_stream_si64(reinterpret_cast<long long*>({address()}), static_cast<long long>({operand(1)}));" + else: + stmt = f"_mm_stream_si32(reinterpret_cast<int*>({address()}), static_cast<int>({operand(1)}));" elif op == M.MOVSXD: stmt = write(f"int64_t(int32_t({operand(1)}))") elif op == M.MOVSX: @@ -2559,6 +2571,16 @@ def _lane_copy(sel, out_off): f"memcpy(reinterpret_cast<void*>(target), {wide_xmm[i.op1_register]}.data(), 16); }}") else: raise ValueError(f"unsupported aligned SSE move form at {i.ip:#x}: {i}") + elif op in (M.MOVNTPS, M.MOVNTPD, M.MOVNTDQ) and i.encoding == EncodingKind.LEGACY and has_wide: + # Non-temporal stores of a whole XMM register. Like MOVAPS, a target that is not 16-byte aligned + # raises #GP(0) before anything is written. The streaming store keeps the non-temporal hint; its weak + # ordering is the guest's own (only an SFENCE, MFENCE or locked instruction orders it). + if i.op0_kind == K.MEMORY and i.op1_kind == K.REGISTER and i.op1_register in wide_xmm: + stmt = (f"{{ const word target = {address()}; if (target & 15u) raise_aligned_m128_fault(); " + f"__m128i value; memcpy(&value, {wide_xmm[i.op1_register]}.data(), 16); " + f"_mm_stream_si128(reinterpret_cast<__m128i*>(target), value); }}") + else: + raise ValueError(f"unsupported non-temporal SSE store form at {i.ip:#x}: {i}") elif op in (M.MOVUPS, M.MOVUPD) and has_wide: is_vex = i.encoding == EncodingKind.VEX if i.op0_kind == K.REGISTER and i.op0_register in wide_xmm and i.op1_kind == K.MEMORY: @@ -3086,15 +3108,16 @@ def p2_lane(sel, out_off): suffix, host = {1: ("8", "char"), 2: ("16", "short"), 4: ("", "long"), 8: ("64", "__int64")}[size] stmt = write_register(register, f"_InterlockedExchange{suffix}(reinterpret_cast<{host} volatile*>({address()}), " f"static_cast<{host}>({operand(n)}))") - elif op == M.NOP or i.code in _RESERVED_NOP_CODES or (op == M.XCHG and i.op0_register == i.op1_register == R.AX): - # The reserved/hint NOP space: 0F 19 /r, 0F 1D /r, 0F 1E /r and 0F 1F /r. The APM documents them as - # reserved hint NOPs that take a ModRM but access no memory, so lowering to ";" is exact: the operand - # is not evaluated, so no address is computed, nothing is loaded and nothing faults. Selection is by + elif op == M.NOP or i.code in _RESERVED_NOP_CODES or i.code in _ENDBR_CODES or (op == M.XCHG and i.op0_register == i.op1_register == R.AX): + # The reserved/hint NOP space (0F 19 /r, 0F 1D /r, 0F 1E /r, 0F 1F /r) and ENDBR64/ENDBR32 + # (F3 0F 1E FA/FB). The AMD APM documents the hint NOPs as taking a ModRM without accessing memory, + # and Intel SDM Vol. 2A documents ENDBR64/ENDBR32 as affecting no registers, flags, or memory (and + # executing as NOPs on x64_zen2 without CET-IBT), so lowering to ";" is exact. Selection is by # iced code rather than by mnemonic because iced also decodes 0F 0D (Group P, which aliases PREFETCH # Exclusive), 0F 18 (PREFETCHT0-T2/PREFETCHNTA, with /6-/7 being PREFETCHIT1/0 under CPUID # Fn8000_0021_EAX), 0F 1A, 0F 1B and 0F 1C as RESERVEDNOP; a mnemonic test would have lowered every # one of those to a no-op. They stay refused here, as do CLDEMOTE (0F 1C /0), RDSSPD/RDSSPQ - # (F3 0F 1E /1), ENDBR64/ENDBR32 (F3 0F 1E FA/FB) and the MPX forms. + # (F3 0F 1E /1) and the MPX forms. stmt = ";" elif (op in (M.SETE, M.SETNE, M.SETA, M.SETAE, M.SETB, M.SETBE) or (x87_depth is None and op in (M.SETL, M.SETGE, M.SETLE, M.SETG, M.SETS, M.SETNS, M.SETO, M.SETNO))): diff --git a/tools/ffx_working_set_delta.py b/tools/ffx_working_set_delta.py index 6ed27189a1..cf9184fc42 100644 --- a/tools/ffx_working_set_delta.py +++ b/tools/ffx_working_set_delta.py @@ -1,6 +1,8 @@ """Translate the counter updates following two upscaler working-set queries.""" import argparse from pathlib import Path +import struct +import tempfile import pefile @@ -31,6 +33,47 @@ def generate(image: Path, package: bool) -> str: return "\n".join(source) +def _validate_paths(image: Path, output: Path, parser: argparse.ArgumentParser) -> None: + if image.is_dir(): + raise IsADirectoryError(f"image path is a directory: {image}") + if not image.is_file(): + raise FileNotFoundError(f"image file not found: {image}") + if output.suffix.lower() != ".cpp": + parser.error("choose a distinct .cpp output") + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if output.resolve() == image.resolve() or (output.exists() and image.samefile(output)): + parser.error("choose a distinct .cpp output") + + +def _write_atomic(path: Path, content: str) -> None: + """Write ASCII content to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="ascii", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + tmp_path.replace(path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) @@ -38,10 +81,9 @@ def main(argv=None) -> int: parser.add_argument("--package", action="store_true") args = parser.parse_args(argv) try: - if args.output.suffix.lower() != ".cpp" or args.output.resolve() == args.image.resolve(): - parser.error("choose a distinct .cpp output") - args.output.write_text(generate(args.image, args.package), encoding="ascii") - except (OSError, ValueError, pefile.PEFormatError) as error: + _validate_paths(args.image, args.output, parser) + _write_atomic(args.output, generate(args.image, args.package)) + except (OSError, ValueError, struct.error, pefile.PEFormatError) as error: parser.exit(1, f"{error}\n") return 0 diff --git a/tools/form_reference.py b/tools/form_reference.py index 9ca34952d0..206036022d 100644 --- a/tools/form_reference.py +++ b/tools/form_reference.py @@ -1,18 +1,25 @@ """Regenerate the instruction reference lists in docs/coverage/ (rarely needed). -Usage: out/pe-env/Scripts/python.exe tools/form_reference.py <llvm-docs-dir> +Usage: out/pe-env/Scripts/python.exe tools/form_reference.py <llvm-docs-dir> [--out-dir DIR] <llvm-docs-dir> holds AMDGPUAsmGFX10.rst, AMDGPUAsmGFX1011.rst, AMDGPUAsmGFX1013.rst and AMDGPUAsmGFX1030.rst from llvm-project tag llvmorg-15.0.7, llvm/docs/AMDGPU/ (Apache-2.0 WITH LLVM-exception). These are generated from LLVM's instruction tables. The x64 list comes from the iced-x86 package already in requirements-dev.txt. Output lines are "group<TAB>form". """ +import argparse +import os +from pathlib import Path import re +import stat import sys -from pathlib import Path +import tempfile OUT = Path(__file__).resolve().parents[1] / "docs" / "coverage" LLVM_SOURCE = "llvm-project llvmorg-15.0.7 llvm/docs/AMDGPU/" +REQUIRED_GFX1013_RST = ("AMDGPUAsmGFX10.rst", "AMDGPUAsmGFX1011.rst", "AMDGPUAsmGFX1013.rst") +REQUIRED_RDNA2_RST = ("AMDGPUAsmGFX1030.rst",) +OUTPUT_TSV_NAMES = ("gfx1013.tsv", "rdna2.tsv", "x64_zen2.tsv") # Xbox Series CPUs are AMD Zen 2. These iced CPUID groups are what Zen 2 runs in user mode; the group # names are what the dashboard shows. AVX-512, XOP/FMA4/TBM, 3DNow!, AMX and vendor extras are left out. @@ -73,19 +80,112 @@ def names(module): return {(group, mnemonic) for mnemonic, group in forms.items()} -def write(name, source, forms): - OUT.mkdir(parents=True, exist_ok=True) +def _validate_docs_dir(docs): + """Validate that docs is a directory containing all required AMDGPUAsmGFX*.rst regular files.""" + if not docs.is_dir(): + raise ValueError(f"LLVM docs path is not a directory: {docs}") + gfx1013_files = [docs / name for name in REQUIRED_GFX1013_RST] + rdna2_files = [docs / name for name in REQUIRED_RDNA2_RST] + for rst in (*gfx1013_files, *rdna2_files): + if not rst.is_file(): + raise ValueError(f"missing or non-regular LLVM doc file: {rst}") + return gfx1013_files, rdna2_files + + +def _validate_output_file(path): + """Reject symlink, directory, or file-parent output paths before writing.""" + if path.is_symlink(): + raise ValueError(f"output path must not be a symlink: {path}") + if path.exists() and path.is_dir(): + raise ValueError(f"output path must not be a directory: {path}") + for ancestor in path.parents: + if ancestor.exists() and not ancestor.is_dir(): + raise ValueError(f"output parent is not a directory: {ancestor}") + + +def _validate_out_dir_and_targets(out_dir): + """Validate --out-dir and each target .tsv path upfront before parsing inputs.""" + if out_dir.is_symlink(): + raise ValueError(f"output directory must not be a symlink: {out_dir}") + if out_dir.exists() and not out_dir.is_dir(): + raise ValueError(f"output directory path is not a directory: {out_dir}") + for ancestor in out_dir.parents: + if ancestor.exists() and not ancestor.is_dir(): + raise ValueError(f"output parent is not a directory: {ancestor}") + for name in OUTPUT_TSV_NAMES: + _validate_output_file(out_dir / name) + + +def _write_atomic(path, content): + """Write via a sibling temp file, preserving POSIX output permissions.""" + _validate_output_file(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + if os.name == "posix": + try: + mode = stat.S_IMODE(path.stat().st_mode) + except FileNotFoundError: + mode = 0o666 & ~_umask() + os.chmod(tmp_path, mode) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def _umask(): + # Temporarily restrict permissions rather than relaxing the existing mask. + current = os.umask(0o777) + os.umask(current) + return current + + +def write(name, source, forms, out_dir=OUT): body = "".join(f"{g}\t{f}\n" for g, f in sorted(forms)) - (OUT / name).write_text(f"# {len(forms)} forms. Source: {source}. Regenerate: tools/form_reference.py\n" - + body, encoding="utf-8") + content = (f"# {len(forms)} forms. Source: {source}. Regenerate: tools/form_reference.py\n" + + body) + _write_atomic(Path(out_dir) / name, content) print(name, len(forms)) +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("llvm_docs_dir", help="directory containing AMDGPUAsmGFX*.rst docs") + parser.add_argument("--out-dir", default=None, help="output directory for generated .tsv files") + args = parser.parse_args(argv) + try: + if not args.llvm_docs_dir.strip(): + raise ValueError("llvm_docs_dir must not be empty") + if args.out_dir is not None and not args.out_dir.strip(): + raise ValueError("--out-dir must not be empty") + docs = Path(args.llvm_docs_dir) + out_dir = OUT if args.out_dir is None else Path(args.out_dir) + gfx1013_files, rdna2_files = _validate_docs_dir(docs) + _validate_out_dir_and_targets(out_dir) + gfx1013 = llvm_forms(*gfx1013_files) + rdna2 = llvm_forms(*rdna2_files) + x64 = x64_forms() + write("gfx1013.tsv", LLVM_SOURCE + "AMDGPUAsmGFX10/1011/1013.rst", gfx1013, out_dir=out_dir) + write("rdna2.tsv", LLVM_SOURCE + "AMDGPUAsmGFX1030.rst", rdna2, out_dir=out_dir) + write("x64_zen2.tsv", "iced-x86 1.21.0 mnemonics, Zen 2 user-mode CPUID groups", x64, out_dir=out_dir) + except (OSError, ValueError) as error: + sys.stderr.write(f"form_reference: {error}\n") + return 1 + return 0 + + if __name__ == "__main__": - if len(sys.argv) != 2: - raise SystemExit(__doc__) - docs = Path(sys.argv[1]) - write("gfx1013.tsv", LLVM_SOURCE + "AMDGPUAsmGFX10/1011/1013.rst", - llvm_forms(*(docs / f"AMDGPUAsmGFX{v}.rst" for v in ("10", "1011", "1013")))) - write("rdna2.tsv", LLVM_SOURCE + "AMDGPUAsmGFX1030.rst", llvm_forms(docs / "AMDGPUAsmGFX1030.rst")) - write("x64_zen2.tsv", "iced-x86 1.21.0 mnemonics, Zen 2 user-mode CPUID groups", x64_forms()) + raise SystemExit(main()) diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index 36823e02e9..99a49f06a9 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -3,13 +3,21 @@ import argparse import ctypes from dataclasses import dataclass, field +import os from pathlib import Path import random import re import struct import sys +import tempfile import types +try: + import pefile + _PE_ERRORS: tuple[type[BaseException], ...] = (pefile.PEFormatError,) +except ImportError: + _PE_ERRORS = () + WIDTHS = { "b": ("al", "dl", "BYTE PTR", 1), "w": ("ax", "dx", "WORD PTR", 2), @@ -2037,13 +2045,75 @@ def buffer_text(data, start, stop): return " ".join(f"{byte:02x}" for byte in data[start:stop]) +def _validate_count(count: int) -> None: + if count < 1: + raise ValueError(f"count must be >= 1, got {count}") + + +def _validate_input_file(path: Path, label: str) -> None: + if path.is_dir(): + raise IsADirectoryError(f"{label} path is a directory: {path}") + if not path.is_file(): + raise FileNotFoundError(f"{label} file not found: {path}") + + +def _validate_output_path(path: Path, label: str) -> None: + if path.is_symlink(): + raise ValueError(f"{label} output path must not be a symlink: {path}") + if path.is_dir(): + raise IsADirectoryError(f"{label} output path is a directory: {path}") + for parent in path.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"{label} output parent is not a directory: {parent}") + + +def _validate_distinct_paths(left: Path, right: Path, message: str) -> None: + left_resolved = left.resolve() + right_resolved = right.resolve() + if ( + left_resolved == right_resolved + or left_resolved in right_resolved.parents + or right_resolved in left_resolved.parents + or (left.exists() and right.exists() and left.samefile(right)) + ): + raise ValueError(message) + + +def _write_atomic(path: Path, text: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, unlinking temps on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + def run_check(seed, count, native, lifted, o2, only=None, input_index=None, area="leaf", mutant=None): + _validate_count(count) + for path, label in ((native, "native"), (lifted, "lifted"), (o2, "o2")): + _validate_input_file(Path(path), label) + if mutant is not None: + _validate_input_file(Path(mutant), "mutant") if first_difference(b"\x01\x02", b"\x01\x02") is not None: raise SystemExit("comparator self-test failed on equal bytes") if first_difference(b"\x01\x02", b"\x01\x03") != 1: raise SystemExit("comparator self-test failed on a changed byte") if mutant is not None and area not in MUTANTS: - raise SystemExit(f"no planted translator fault for --area {area}") + raise ValueError(f"no planted translator fault for --area {area}") functions = AREAS[area][0](seed, count) controls = [function for function in functions if function.refused] @@ -2069,8 +2139,6 @@ def run_check(seed, count, native, lifted, o2, only=None, input_index=None, area loaded.append((library, prefix)) native_library, lifted_library, o2_library = (item[0] for item in loaded[:3]) - if count <= 0: - raise SystemExit("CPU_FUZZ_FUNCTIONS must be positive") selected = [function for function in functions if only is None or function.name == only] def function_inputs(function): @@ -2155,14 +2223,20 @@ def function_inputs(function): def emit(seed, count, asm_path, def_path, area="leaf"): + _validate_count(count) + asm_out = Path(asm_path) + def_out = Path(def_path) + _validate_output_path(asm_out, "asm") + _validate_output_path(def_out, "definition") + _validate_distinct_paths(asm_out, def_out, f"asm and definition outputs must be distinct: {asm_out}") generator, library = AREAS[area] functions = generator(seed, count) body = "\n\n".join(function.asm() for function in functions) asm = ("EXTERN __ImageBase:BYTE\n" if "__ImageBase" in body else "") + ".code\n\n" + body + "\n\nEND\n" definition = (f"LIBRARY {library}\nEXPORTS\n" + "".join(f" {function.name}\n" for function in functions if function.export)) - Path(asm_path).write_text(asm, encoding="utf-8") - Path(def_path).write_text(definition, encoding="utf-8") + _write_atomic(asm_out, asm) + _write_atomic(def_out, definition) def plant_reload_shift(cpu_switch_aot, image, functions): @@ -2364,33 +2438,39 @@ def plant_set_reset_swap(cpu_switch_aot, image, functions): def translate(seed, count, image, output, area="leaf", mutant=False): + _validate_count(count) + image_path = Path(image) + out_path = Path(output) + _validate_input_file(image_path, "image") + _validate_output_path(out_path, "output") + _validate_distinct_paths(out_path, image_path, f"output path must be distinct from input image: {out_path}") + if mutant and area not in MUTANTS: + raise ValueError(f"no planted translator fault for --area {area}") lifter = translator_module(area) functions = AREAS[area][0](seed, count) if mutant: - if area not in MUTANTS: - raise SystemExit(f"no planted translator fault for --area {area}") MUTANTS[area][1](lifter, image, functions) # Negative controls stay in the image for the check to translate on their own. functions = [function for function in functions if not function.refused and function.export and function.host_features is None] names = [export_name(function) for function in functions] try: - source, _ = lifter.translate(Path(image), names) + source, _ = lifter.translate(image_path, names) except ValueError as error: print(f"seed={seed:#x} functions={count}: {error}", file=sys.stderr) for function in functions: try: - lifter.translate(Path(image), [export_name(function)]) + lifter.translate(image_path, [export_name(function)]) except ValueError as inner: print(f"refused {function.name}: {inner}", file=sys.stderr) print(function.asm(), file=sys.stderr) break return 1 - Path(output).write_text(source, encoding="utf-8") + _write_atomic(out_path, source) return 0 -def main(argv=None): +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) emit_parser = commands.add_parser("emit") @@ -2420,13 +2500,17 @@ def main(argv=None): check_parser.add_argument("--mutant", type=Path, help="a translation with the planted fault, which must mismatch") args = parser.parse_args(argv) - if args.command == "emit": - emit(args.seed, args.count, args.asm, args.definition, args.area) - return 0 - if args.command == "translate": - return translate(args.seed, args.count, args.image, args.output, args.area, args.mutant) - return run_check(args.seed, args.count, args.native, args.lifted, args.o2, args.only, args.input_index, - args.area, args.mutant) + try: + if args.command == "emit": + emit(args.seed, args.count, args.asm, args.definition, args.area) + return 0 + if args.command == "translate": + return translate(args.seed, args.count, args.image, args.output, args.area, args.mutant) + return run_check(args.seed, args.count, args.native, args.lifted, args.o2, args.only, args.input_index, + args.area, args.mutant) + except (OSError, ValueError, struct.error, KeyError, *_PE_ERRORS) as error: + print(f"error: {error}", file=sys.stderr) + return 1 if __name__ == "__main__": diff --git a/tools/gdk_abi_probe.py b/tools/gdk_abi_probe.py new file mode 100644 index 0000000000..656a9f06f9 --- /dev/null +++ b/tools/gdk_abi_probe.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Generate and compare C++ ABI probes from parsed GDK layouts. + +The layout JSON comes from tools/gdk_layouts.py. The generated probe can either +assert sizes and offsets at compile time or print them for a GRDK/GXDK diff. +Only names, sizes and offsets are used; private members and non-standard-layout +classes need an explicit review before offsetof is enabled. + +Commands: + generate --layouts <json> --out <cpp> [--include H]... [--print] [--offsetof] + parse <log> [--json <out>] + diff <left.json> <right.json> +""" + +import argparse +import json +import re +import sys +from pathlib import Path + + +IDENTIFIER = re.compile(r"^[A-Za-z_]\w*$") +CLASS_NAME = re.compile(r"^(?:::)?[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*$") + + +def load_classes(path): + document = json.loads(Path(path).read_text(encoding="utf-8")) + return document, document.get("classes", []) + + +def member_offsets(block): + has_dynamic_layout = bool(block.get("bases")) or any( + item.get("kind") == "vftable" for item in block.get("members", []) + ) + if has_dynamic_layout: + return [] + offsets = [] + for item in block.get("members", []): + if item.get("kind") != "field" or item.get("bits") is not None: + continue + name = item.get("name", "") + if IDENTIFIER.fullmatch(name): + offsets.append((name, item["offset"])) + return offsets + + +def generate_command(args): + document, classes = load_classes(args.layouts) + if args.prefix: + classes = [ + block + for block in classes + if any(block["name"].startswith(prefix) for prefix in args.prefix) + ] + skipped = [block["name"] for block in classes if not CLASS_NAME.fullmatch(block["name"])] + classes = [block for block in classes if CLASS_NAME.fullmatch(block["name"])] + lines = [ + "// Generated by tools/gdk_abi_probe.py; do not edit.", + f"// module: {document.get('module', '')}", + f"// source: {document.get('header', '')}", + "", + ] + lines += [f"#include <{header}>" if not header.startswith('"') else f"#include {header}" for header in args.include] + lines.append("#include <cstddef>") + if args.print: + lines.append("#include <cstdio>") + lines.append("") + for block in classes: + name = block["name"] + lines.append(f'static_assert(sizeof({name}) == {block["size"]}, "sizeof({name})");') + if args.offsetof: + for member, offset in member_offsets(block): + lines.append( + f'static_assert(offsetof({name}, {member}) == {offset}, "offsetof({name}, {member})");' + ) + if args.print: + lines += ["", "int main()", "{"] + for block in classes: + name = block["name"] + lines.append(f' std::printf("sizeof({name})=%zu\\n", sizeof({name}));') + if args.offsetof: + for member, _ in member_offsets(block): + lines.append( + f' std::printf("offsetof({name}, {member})=%zu\\n", offsetof({name}, {member}));' + ) + lines += [" return 0;", "}"] + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text("\n".join(lines) + "\n", encoding="utf-8") + print( + json.dumps( + { + "classes": len(classes), + "skipped": len(skipped), + "offsetof": bool(args.offsetof), + "print": bool(args.print), + } + ) + ) + return 0 + + +def parse_command(args): + facts = {} + for line in Path(args.log).read_text(encoding="utf-8", errors="replace").splitlines(): + if "=" not in line: + continue + key, value = line.split("=", 1) + try: + facts[key.strip()] = int(value.strip(), 0) + except ValueError: + facts[key.strip()] = value.strip() + document = {"facts": facts} + if args.json: + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"facts": len(facts)})) + return 0 + + +def diff_command(args): + left = json.loads(Path(args.left).read_text(encoding="utf-8")).get("facts", {}) + right = json.loads(Path(args.right).read_text(encoding="utf-8")).get("facts", {}) + changes = [] + for key in sorted(set(left) | set(right)): + if left.get(key) != right.get(key): + changes.append({"key": key, "left": left.get(key), "right": right.get(key)}) + if not changes: + print("no ABI differences") + return 0 + for change in changes: + print(json.dumps(change, sort_keys=True)) + return 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + generate = sub.add_parser("generate", help="emit a C++ probe") + generate.add_argument("--layouts", required=True) + generate.add_argument("--out", required=True) + generate.add_argument("--include", action="append", default=[]) + generate.add_argument("--prefix", action="append", default=[]) + generate.add_argument("--offsetof", action="store_true") + generate.add_argument("--print", action="store_true") + generate.set_defaults(func=generate_command) + + parse = sub.add_parser("parse", help="parse a probe log") + parse.add_argument("log") + parse.add_argument("--json") + parse.set_defaults(func=parse_command) + + diff = sub.add_parser("diff", help="compare two parsed probe logs") + diff.add_argument("left") + diff.add_argument("right") + diff.set_defaults(func=diff_command) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_exports.py b/tools/gdk_exports.py new file mode 100644 index 0000000000..e5fe321383 --- /dev/null +++ b/tools/gdk_exports.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Collect GDK export names and ordinals from dumpbin text or a PE DLL. + +The GDK libraries stay outside the repository. This tool writes the inventory +JSON that tools/gdk_shim_coverage.py compares with the shim .def files. + +Commands: + parse-dumpbin <dumpbin.txt>... --json <out> [--kind lib|dll] + scan-pe <dll>... --json <out> + +parse-dumpbin accepts a file or a directory of text captured from: + dumpbin /nologo /exports <library> +Its sha256 identifies that capture, not the LIB or DLL it was taken from. +""" + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +DLL_ROW = re.compile(r"^\s*(\d+)\s+([0-9A-Fa-f]+)\s+([0-9A-Fa-f]+)\s+(\S+)\s*$") +LIB_ROW = re.compile(r"^\s*(\d+)?\s+([A-Za-z_?$@][^\s]*)\s*$") +SKIP = {"Exports", "Summary", "ordinal", "name", "hint", "RVA"} + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def parse_dumpbin_report(text): + exports = [] + started = False + unparsed = 0 + for line in text.splitlines(): + if re.match(r"^\s*ordinal\s+name\b", line) or re.match( + r"^\s*ordinal\s+hint\s+RVA\s+name\b", line + ): + started = True + continue + if not started: + if line.strip() == "Exports": + started = True + continue + stripped = line.strip() + if not stripped: + continue + if stripped.startswith("Summary") or stripped.startswith("Dump of file"): + break + match = DLL_ROW.match(line) + if match: + exports.append( + { + "ordinal": int(match.group(1)), + "name": match.group(4), + "rva": "0x%X" % int(match.group(3), 16), + } + ) + continue + match = LIB_ROW.match(line) + if match and match.group(2) not in SKIP: + exports.append( + { + "ordinal": int(match.group(1)) if match.group(1) else None, + "name": match.group(2), + "rva": None, + } + ) + continue + unparsed += 1 + return exports, unparsed + + +def parse_dumpbin_text(text): + return parse_dumpbin_report(text)[0] + + +def module_name(path, kind): + name = Path(path).stem + for suffix in (".lib", ".dll"): + if name.lower().endswith(suffix): + return name[:-len(suffix)] + return name + + +def collect_dumpbin(path, kind, sdk="261000"): + path = Path(path) + if path.is_dir(): + entries = sorted( + item for item in path.iterdir() if item.is_file() and item.suffix.lower() == ".txt" + ) + else: + entries = [path] + modules = [] + for entry in entries: + text = entry.read_text(encoding="utf-8", errors="replace") + parsed, unparsed = parse_dumpbin_report(text) + module = { + "sdk": sdk, + "module": module_name(entry, kind), + "file": str(entry), + "kind": kind, + "sha256": sha256(entry), + "exports": parsed, + } + if unparsed: + module["unparsed"] = unparsed + if not parsed: + module["error"] = "no exports parsed" + elif unparsed: + module["error"] = f"{unparsed} unparsed export line(s)" + modules.append(module) + return modules + + +def scan_pe(path, sdk="261000"): + import pefile # Imported here so parse-dumpbin needs only the standard library. + + pe = pefile.PE(str(path), fast_load=True) + pe.parse_data_directories( + directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"]] + ) + exports = [] + directory = getattr(pe, "DIRECTORY_ENTRY_EXPORT", None) + if directory: + for symbol in directory.symbols: + exports.append( + { + "ordinal": symbol.ordinal, + "name": symbol.name.decode("ascii", "replace") if symbol.name else "", + "rva": "0x%X" % symbol.address, + } + ) + module = { + "sdk": sdk, + "module": module_name(path, "dll"), + "file": str(path), + "kind": "dll", + "sha256": sha256(path), + "exports": exports, + } + if not exports: + module["error"] = "no exports parsed" + return module + + +def write_document(path, modules, sdk="261000"): + document = { + "sdk": sdk, + "count": sum(len(module["exports"]) for module in modules), + "modules": modules, + } + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"modules": len(modules), "exports": document["count"]})) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + dumpbin = sub.add_parser("parse-dumpbin", help="parse captured dumpbin /exports text") + dumpbin.add_argument("inputs", nargs="+") + dumpbin.add_argument("--json", required=True) + dumpbin.add_argument("--kind", choices=("lib", "dll"), default="lib") + dumpbin.add_argument("--sdk", default="261000") + dumpbin.set_defaults( + func=lambda args: write_document( + args.json, + [module for path in args.inputs for module in collect_dumpbin(path, args.kind, args.sdk)], + args.sdk, + ) + ) + + pe = sub.add_parser("scan-pe", help="read exports from a PE DLL") + pe.add_argument("dlls", nargs="+") + pe.add_argument("--json", required=True) + pe.add_argument("--sdk", default="261000") + pe.set_defaults( + func=lambda args: write_document( + args.json, [scan_pe(path, args.sdk) for path in args.dlls], args.sdk + ) + ) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_knowledge_report.py b/tools/gdk_knowledge_report.py new file mode 100644 index 0000000000..33e9b17935 --- /dev/null +++ b/tools/gdk_knowledge_report.py @@ -0,0 +1,1676 @@ +#!/usr/bin/env python3 +"""Merge GDK knowledge facts, report conflicts and count coverage. + +The tool reads only JSON metadata. It never loads a GDK binary, header or SDK +file. Inputs are optional directories under a knowledge root: + + layouts/*.json layout classes with a size and members + abi/*.json ABI facts (structs, enums, constants, GUIDs) + exports/*.json export rows, or a root exports-all.json + behavior/*.json runtime observations + platform/*.json build defines, includes, libraries and flags + shaders/corpus.json shader corpus cases + +Normalised facts carry module, kind, name, value, source, confidence and +targets. Conflicts are grouped by fact identity and by type name. The report is +deterministic: facts, conflicts, modules and shims are sorted before writing. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import sys +from collections import defaultdict + + +SCHEMA = "xbox2windows.gdk_knowledge/1" +TOOL = "gdk_knowledge_report" +VERSION = 1 +CATEGORIES = ("layouts", "abi", "exports", "behavior", "platform", "shaders") +TYPE_KINDS = frozenset( + {"layout", "class", "struct", "union", "type", "typedef", "sizeof"} +) +ENUM_KINDS = frozenset({"enum", "enumerator", "enumeration", "enum-value"}) +CONFLICT_ORDER = {"value": 0, "size": 1, "ordinal": 2, "enum": 3, "type-size": 4} +FACT_FIELDS = ("module", "kind", "name", "value", "source", "confidence", "targets") +DEFAULT_CONFIDENCE = { + "layouts": "header", + "abi": "compiled", + "exports": "export-table", + "behavior": "runtime", + "platform": "build-profile", + "shaders": "shader-corpus", +} +LEFTOVER_KEYS = frozenset( + {"module", "kind", "name", "value", "source", "confidence", "targets"} +) +METHOD_SOURCES = frozenset( + { + "msvc-layout", + "compiled-probe", + "dumpbin", + "runtime-oracle", + "header-msvc-layout", + } +) + + +class InputError(Exception): + """A malformed input or unusable path. The CLI maps this to exit code 2.""" + + +def _canonical(value): + return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def _as_int(value): + if isinstance(value, bool) or value is None: + return None + if isinstance(value, int): + return value + if isinstance(value, str): + text = value.strip() + if not text: + return None + try: + if text.lower().startswith(("0x", "-0x")): + return int(text, 16) + return int(text, 10) + except ValueError: + return None + return None + + +def _display_source(source): + if isinstance(source, str): + return source + return _canonical(source) + + +def _value_sort_key(value): + if isinstance(value, bool): + return (0, int(value), "") + if isinstance(value, (int, float)): + return (1, value, "") + if isinstance(value, str): + return (2, 0, value) + return (3, 0, _canonical(value)) + + +def _relative(path, root): + path = Path(path) + root = Path(root) + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except (OSError, ValueError): + return path.name + + +def _read_json(path): + path = Path(path) + try: + text = path.read_text(encoding="utf-8-sig") + except OSError as exc: + raise InputError("cannot read {}: {}".format(path, exc)) from exc + try: + return json.loads(text) + except json.JSONDecodeError as exc: + raise InputError( + "invalid JSON in {} at line {} column {}: {}".format( + path, exc.lineno, exc.colno, exc.msg + ) + ) from exc + + +def _require_object(value, where): + if not isinstance(value, dict): + raise InputError("{} must be a JSON object".format(where)) + return value + + +def _require_list(value, where): + if not isinstance(value, list): + raise InputError("{} must be a JSON array".format(where)) + return value + + +def _require_name(item, where, keys=("name",)): + for key in keys: + value = item.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + raise InputError("{} has no non-empty {}".format(where, "/".join(keys))) + + +def _normalise_targets(value, where): + if value is None: + return [] + if isinstance(value, str): + return [value] + if not isinstance(value, list): + raise InputError("{} targets must be a string or an array".format(where)) + targets = [] + for target in value: + if not isinstance(target, str): + raise InputError("{} targets must contain strings".format(where)) + if target: + targets.append(target) + return sorted(set(targets)) + + +def _source_and_confidence(item, meta, default_source, default_confidence): + item = item if isinstance(item, dict) else {} + meta = meta if isinstance(meta, dict) else {} + source = None + method = None + for candidate in (item.get("source"), meta.get("source")): + if isinstance(candidate, str) and candidate.strip(): + text = candidate.strip() + if text.casefold() in METHOD_SOURCES: + if method is None: + method = text + elif source is None: + source = text + elif candidate is not None and source is None: + source = candidate + confidence = ( + item.get("confidence") + or meta.get("confidence") + or method + or default_confidence + ) + return source or default_source, confidence + + +def _module_from_stem(stem): + text = Path(stem).stem + lowered = text.casefold() + suffixes = ( + "-all-layout", + "-interesting-layout", + "-layout-report", + "-layout", + "_layout", + "-vtables", + "-facts", + "-exports", + ) + for suffix in suffixes: + if lowered.endswith(suffix) and len(text) > len(suffix): + return text[: -len(suffix)] + return text + + +def _module_from_library(path): + name = Path(path).name + lowered = name.casefold() + for suffix in (".lib", ".dll"): + if lowered.endswith(suffix): + return name[: -len(suffix)] + return _module_from_stem(name) + + +def _module_from_def_stem(stem): + module = _module_from_stem(stem) + lowered = module.casefold() + for suffix in ("_shim", "-shim"): + if lowered.endswith(suffix) and len(module) > len(suffix): + return module[: -len(suffix)] + return module + + +def _make_fact(module, kind, name, value, source, confidence, targets): + if not isinstance(module, str) or not module.strip(): + raise InputError("fact {} has no module".format(name)) + if not isinstance(kind, str) or not kind.strip(): + raise InputError("fact {} has no kind".format(name)) + if not isinstance(name, str) or not name.strip(): + raise InputError("fact has no non-empty name") + if confidence is None: + confidence = "" + if not isinstance(confidence, str): + confidence = str(confidence) + return { + "module": module.strip(), + "kind": kind.strip(), + "name": name.strip(), + "value": value, + "source": source, + "confidence": confidence, + "targets": list(targets), + } + + +def _fact_sort_key(fact): + return ( + fact["module"].casefold(), + fact["module"], + fact["kind"].casefold(), + fact["kind"], + fact["name"].casefold(), + fact["name"], + _canonical(fact["value"]), + _canonical(fact["source"]), + ) + + +def _dedupe_facts(facts): + seen = set() + result = [] + for fact in facts: + key = _canonical(fact) + if key in seen: + continue + seen.add(key) + result.append(fact) + result.sort(key=_fact_sort_key) + return result + + +def _canonicalise_modules(facts): + counts = defaultdict(lambda: defaultdict(int)) + for fact in facts: + counts[fact["module"].casefold()][fact["module"]] += 1 + canonical = {} + for key, variants in counts.items(): + if len(variants) == 1: + canonical[key] = next(iter(variants)) + continue + canonical[key] = sorted( + variants, + key=lambda name: ( + -variants[name], + name != name.lower(), + name.casefold(), + name, + ), + )[0] + for fact in facts: + fact["module"] = canonical[fact["module"].casefold()] + return facts + + +def _is_type_kind(kind): + return kind.casefold() in TYPE_KINDS + + +def _is_enum_kind(kind): + lowered = kind.casefold().replace("_", "-") + return lowered in ENUM_KINDS or lowered.startswith("enum-") + + +def _is_anonymous_name(name): + lowered = name.casefold() + return "<unnamed" in lowered or "<anonymous" in lowered + + +def _size_of(fact): + if not _is_type_kind(fact["kind"]): + return None + value = fact["value"] + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, dict): + for key in ("size", "sizeof", "bytes", "size_bytes"): + if key in value: + number = _as_int(value[key]) + if number is not None: + return number + return None + + +def _ordinal_of(fact): + value = fact["value"] + if isinstance(value, dict): + return _as_int(value.get("ordinal")) + return _as_int(value) + + +def _json_files(directory): + directory = Path(directory) + if not directory.is_dir(): + return [] + return sorted( + (path for path in directory.iterdir() if path.is_file() and path.suffix.lower() == ".json"), + key=lambda path: path.name.casefold(), + ) + + +def _load_layouts(path, root): + data = _read_json(path) + where = _relative(path, root) + meta = data if isinstance(data, dict) else {} + if isinstance(data, list): + classes = data + elif isinstance(data, dict): + classes = data.get("classes") + if classes is None and "name" in data: + classes = [data] + if classes is None: + raise InputError("{} has no classes array".format(where)) + _require_list(classes, where + " classes") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(classes): + item_where = "{} classes[{}]".format(where, index) + item = _require_object(item, item_where) + name = _require_name(item, item_where) + size = _as_int(item.get("size")) + if size is None: + size = _as_int(item.get("bytes")) + if size is None or size < 0: + raise InputError("{} has no non-negative integer size".format(item_where)) + members = item.get("members", []) + if members is None: + members = [] + _require_list(members, item_where + " members") + module = item.get("module") or top_module or fallback_module + kind = item.get("kind") or "layout" + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["layouts"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact( + module, + kind, + name, + {"size": size, "members": members}, + source, + confidence, + targets, + ) + ) + return facts + + +def _load_abi(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + facts_data = data + meta = {} + elif isinstance(data, dict): + meta = data + facts_data = data.get("facts") + if facts_data is None: + raise InputError("{} has no facts array".format(where)) + _require_list(facts_data, where + " facts") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(facts_data): + item_where = "{} facts[{}]".format(where, index) + item = _require_object(item, item_where) + name = _require_name(item, item_where) + kind = item.get("kind") or meta.get("kind") + if not isinstance(kind, str) or not kind.strip(): + raise InputError("{} has no non-empty kind".format(item_where)) + if "value" in item: + value = item["value"] + else: + value = {key: val for key, val in item.items() if key not in LEFTOVER_KEYS} + module = item.get("module") or top_module or fallback_module + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["abi"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact(module, kind.strip(), name, value, source, confidence, targets) + ) + return facts + + +def _export_groups(data, where): + if isinstance(data, list): + if not data: + return [] + if all(isinstance(item, dict) and isinstance(item.get("exports"), list) for item in data): + return data + if all(isinstance(item, dict) and "name" in item for item in data): + return [{"exports": data}] + raise InputError("{} export array has an unsupported shape".format(where)) + + data = _require_object(data, where) + if isinstance(data.get("modules"), list): + return _require_list(data["modules"], where + " modules") + if isinstance(data.get("modules"), dict): + groups = [] + for module, rows in data["modules"].items(): + if not isinstance(rows, list): + raise InputError( + "{} module {} must have an exports array".format(where, module) + ) + groups.append({"module": module, "exports": rows}) + return groups + if "exports" in data: + return [data] + + metadata = { + "schema", + "generated", + "sdk", + "module", + "source", + "confidence", + "targets", + "kind", + "file", + } + groups = [] + for module, rows in data.items(): + if module in metadata: + continue + if not isinstance(rows, list): + raise InputError("{} mapping entry {} must be an array".format(where, module)) + groups.append({"module": module, "exports": rows}) + if not groups: + raise InputError("{} has no exports array".format(where)) + return groups + + +def _load_exports(path, root): + data = _read_json(path) + where = _relative(path, root) + groups = _export_groups(data, where) + meta = data if isinstance(data, dict) else {} + fallback_module = _module_from_stem(path.stem) + fallback_source = where + top_module = meta.get("module") + + facts = [] + for group_index, group in enumerate(groups): + group_where = "{} exports[{}]".format(where, group_index) + group = _require_object(group, group_where) + rows = group.get("exports", []) + _require_list(rows, group_where + " exports") + + module = group.get("module") or top_module + if not module and group.get("file"): + module = _module_from_library(group["file"]) + if not module: + module = fallback_module + + source, confidence = _source_and_confidence( + group, meta, fallback_source, DEFAULT_CONFIDENCE["exports"] + ) + if group.get("file"): + origin = Path(str(group["file"])).name + if origin: + source = "{}#{}".format(source, origin) + targets = _normalise_targets( + group["targets"] if "targets" in group else meta.get("targets"), + group_where, + ) + + for row_index, row in enumerate(rows): + row_where = "{} row {}".format(group_where, row_index) + if isinstance(row, str): + row = {"name": row} + row = _require_object(row, row_where) + name = _require_name(row, row_where) + ordinal = _as_int(row.get("ordinal")) + rva = row.get("rva") + parsed_rva = _as_int(rva) + if parsed_rva is not None: + rva = parsed_rva + row_module = row.get("module") or module + row_source = row.get("source") or source + row_confidence = row.get("confidence") or confidence + row_targets = _normalise_targets( + row["targets"] if "targets" in row else targets, + row_where, + ) + facts.append( + _make_fact( + row_module, + "export", + name, + {"ordinal": ordinal, "rva": rva}, + row_source, + row_confidence, + row_targets, + ) + ) + return facts + + +def _observation_value(item): + payload = { + key: value + for key, value in item.items() + if key not in {"module", "kind", "name", "source", "confidence", "targets"} + } + observation_kind = item.get("kind") + if isinstance(observation_kind, str): + lowered = observation_kind.casefold() + if lowered not in {"behavior", "runtime", "observation", "value", ""}: + payload["observation"] = observation_kind + if not payload: + return None + if set(payload) == {"value"}: + return payload["value"] + return payload + + +def _load_behavior(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + observations = data + meta = {} + elif isinstance(data, dict): + meta = data + observations = data.get("observations") + if observations is None: + raise InputError("{} has no observations array".format(where)) + _require_list(observations, where + " observations") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(observations): + item_where = "{} observations[{}]".format(where, index) + item = _require_object(item, item_where) + name = _require_name(item, item_where) + module = item.get("module") or top_module or fallback_module + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["behavior"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact( + module, + "behavior", + name, + _observation_value(item), + source, + confidence, + targets, + ) + ) + return facts + + +def _load_platform(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + items = data + meta = {} + elif isinstance(data, dict): + meta = data + platforms = data.get("platforms") + if platforms is not None: + _require_list(platforms, where + " platforms") + items = platforms + else: + items = [data] + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = _module_from_stem(path.stem) + top_module = meta.get("module") + facts = [] + for index, item in enumerate(items): + item_where = "{} platforms[{}]".format(where, index) + item = _require_object(item, item_where) + values = {} + has_values = False + for key in ("defines", "includes", "libs", "flags"): + rows = item.get(key, []) + if rows is None: + rows = {} if key == "flags" else [] + if isinstance(rows, str): + rows = [rows] + if not isinstance(rows, (list, dict)): + raise InputError( + "{} {} must be an array or object".format(item_where, key) + ) + values[key] = rows + has_values = has_values or bool(rows) + name = item.get("platform") or item.get("name") or item.get("id") + if not name and not has_values and not item.get("module"): + raise InputError("{} has no platform name or build facts".format(item_where)) + module = item.get("module") or top_module or name or fallback_module + if not name: + name = module + if not isinstance(name, str) or not name.strip(): + raise InputError("{} has no non-empty platform name".format(item_where)) + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["platform"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact( + module, + "platform", + name, + values, + source, + confidence, + targets, + ) + ) + return facts + + +def _load_shaders(path, root): + data = _read_json(path) + where = _relative(path, root) + if isinstance(data, list): + cases = data + meta = {} + elif isinstance(data, dict): + meta = data + cases = data.get("cases") + if cases is None: + raise InputError("{} has no cases array".format(where)) + _require_list(cases, where + " cases") + else: + raise InputError("{} must contain an object or an array".format(where)) + + fallback_module = meta.get("module") or meta.get("platform") or path.parent.name + facts = [] + for index, item in enumerate(cases): + item_where = "{} cases[{}]".format(where, index) + item = _require_object(item, item_where) + name = None + for key in ("name", "id", "case"): + value = item.get(key) + if isinstance(value, str) and value.strip(): + name = value.strip() + break + if name is None: + name = "case-{:04d}".format(index) + value = { + key: val + for key, val in item.items() + if key not in {"module", "name", "id", "case", "source", "confidence", "targets"} + } + module = item.get("module") or fallback_module + source, confidence = _source_and_confidence( + item, meta, where, DEFAULT_CONFIDENCE["shaders"] + ) + targets = _normalise_targets( + item["targets"] if "targets" in item else meta.get("targets"), + item_where, + ) + facts.append( + _make_fact(module, "shader", name, value, source, confidence, targets) + ) + return facts + + +def load_knowledge(root): + root = Path(root) + if not root.exists(): + raise InputError("knowledge root does not exist: {}".format(root)) + if not root.is_dir(): + raise InputError("knowledge root is not a directory: {}".format(root)) + + category_files = {category: [] for category in CATEGORIES} + category_facts = {category: 0 for category in CATEGORIES} + facts = [] + + for category in ("layouts", "abi", "behavior", "platform"): + loader = { + "layouts": _load_layouts, + "abi": _load_abi, + "behavior": _load_behavior, + "platform": _load_platform, + }[category] + files = _json_files(root / category) + for path in files: + loaded = loader(path, root) + facts.extend(loaded) + category_facts[category] += len(loaded) + category_files[category] = [_relative(path, root) for path in files] + + export_files = _json_files(root / "exports") + if not export_files: + root_exports = root / "exports-all.json" + if root_exports.is_file(): + export_files = [root_exports] + for path in export_files: + loaded = _load_exports(path, root) + facts.extend(loaded) + category_facts["exports"] += len(loaded) + category_files["exports"] = [_relative(path, root) for path in export_files] + + shader_corpus = root / "shaders" / "corpus.json" + if not shader_corpus.is_file(): + shader_corpus = root / "shaders" / "corpus" / "corpus.json" + if shader_corpus.is_file(): + loaded = _load_shaders(shader_corpus, root) + facts.extend(loaded) + category_facts["shaders"] = len(loaded) + category_files["shaders"] = [_relative(shader_corpus, root)] + + return facts, category_files, category_facts + + +def _unique_value_entries(entries): + chosen = {} + for fact, value in entries: + key = _canonical(value) + source = _display_source(fact["source"]) + candidate = (fact["module"], value, source) + previous = chosen.get(key) + if previous is None or (source.casefold(), source) < ( + previous[2].casefold(), + previous[2], + ): + chosen[key] = candidate + return [ + {"module": module, "value": value, "source": source} + for module, value, source in sorted( + chosen.values(), + key=lambda item: ( + item[0].casefold(), + item[0], + _value_sort_key(item[1]), + item[2].casefold(), + item[2], + ), + ) + ] + + +def _fact_value_entries(items): + return _unique_value_entries([(fact, fact["value"]) for fact in items]) + + +def _conflict(kind, module, name, values, message, modules=None): + sources = sorted({_display_source(item["source"]) for item in values}) + conflict = { + "kind": kind, + "module": module, + "name": name, + "values": values, + "sources": sources, + "message": message, + } + if modules is not None: + conflict["modules"] = sorted(modules) + return conflict + + +def detect_conflicts(facts): + grouped = defaultdict(list) + type_by_module_name = defaultdict(list) + type_by_name = defaultdict(lambda: defaultdict(list)) + enum_by_name = defaultdict(list) + export_by_name = defaultdict(list) + + for fact in facts: + grouped[(fact["module"], fact["kind"], fact["name"])].append(fact) + kind = fact["kind"] + anonymous_type = _is_type_kind(kind) and _is_anonymous_name(fact["name"]) + if _is_type_kind(kind) and not anonymous_type: + size = _size_of(fact) + if size is not None: + type_by_module_name[(fact["module"], fact["name"])].append((fact, size)) + type_by_name[fact["name"]][fact["module"]].append((fact, size)) + if _is_enum_kind(kind) and not _is_anonymous_name(fact["name"]): + enum_by_name[(fact["module"], fact["name"])].append(fact) + if kind.casefold() == "export": + export_by_name[(fact["module"], fact["name"])].append(fact) + + conflicts = [] + size_conflict_keys = set() + for (module, name), entries in sorted(type_by_module_name.items()): + sizes = {size for _, size in entries} + if len(sizes) <= 1: + continue + values = _unique_value_entries(entries) + conflicts.append( + _conflict( + "size", + module, + name, + values, + "type {} has conflicting sizes in module {}: {}".format( + name, module, ", ".join(str(size) for size in sorted(sizes)) + ), + ) + ) + size_conflict_keys.add((module, name)) + + enum_conflict_keys = set() + for (module, name), items in sorted(enum_by_name.items()): + values = _fact_value_entries(items) + if len(values) <= 1: + continue + conflicts.append( + _conflict( + "enum", + module, + name, + values, + "enum {} has conflicting values in module {}".format(name, module), + ) + ) + enum_conflict_keys.add((module, name)) + + for (module, name), items in sorted(export_by_name.items()): + ordinals = sorted({_ordinal_of(fact) for fact in items if _ordinal_of(fact) is not None}) + if len(ordinals) <= 1: + continue + values = [ + { + "module": module, + "value": ordinal, + "source": _display_source( + next( + fact["source"] + for fact in items + if _ordinal_of(fact) == ordinal + ) + ), + } + for ordinal in ordinals + ] + conflicts.append( + _conflict( + "ordinal", + module, + name, + values, + "export {} has conflicting ordinals: {}".format( + name, ", ".join(str(ordinal) for ordinal in ordinals) + ), + ) + ) + + for (module, kind, name), items in sorted(grouped.items()): + values = _fact_value_entries(items) + if len(values) <= 1: + continue + if kind.casefold() == "export": + continue + if (_is_type_kind(kind) or _is_enum_kind(kind)) and _is_anonymous_name(name): + continue + if _is_type_kind(kind) and (module, name) in size_conflict_keys: + continue + if _is_enum_kind(kind) and (module, name) in enum_conflict_keys: + continue + conflicts.append( + _conflict( + "value", + module, + name, + values, + "{} {} has {} distinct values in module {}".format( + kind, name, len(values), module + ), + ) + ) + + for name in sorted(type_by_name, key=lambda text: (text.casefold(), text)): + modules = type_by_name[name] + if len(modules) < 2: + continue + all_sizes = {size for entries in modules.values() for _, size in entries} + if len(all_sizes) <= 1: + continue + values = [] + for module in sorted(modules, key=lambda text: (text.casefold(), text)): + unique_sizes = {} + for fact, size in modules[module]: + key = _canonical(size) + source = _display_source(fact["source"]) + previous = unique_sizes.get(key) + if previous is None or (source.casefold(), source) < ( + previous[0].casefold(), + previous[0], + ): + unique_sizes[key] = (source, size) + for source, size in sorted( + unique_sizes.values(), key=lambda item: (_value_sort_key(item[1]), item[0]) + ): + values.append({"module": module, "value": size, "source": source}) + module_summary = ", ".join( + "{}={}".format( + module, + "/".join( + str(size) + for size in sorted( + {size for _, size in modules[module]} + ) + ), + ) + for module in sorted(modules, key=lambda text: (text.casefold(), text)) + ) + conflicts.append( + _conflict( + "type-size", + "*", + name, + values, + "type {} has incompatible sizes across modules: {}".format( + name, module_summary + ), + modules=modules, + ) + ) + + conflicts.sort( + key=lambda item: ( + CONFLICT_ORDER.get(item["kind"], 99), + item["kind"], + item["module"].casefold(), + item["module"], + item["name"].casefold(), + item["name"], + _canonical(item["values"]), + ) + ) + return conflicts + + +def _is_internal_shim(name): + return name.casefold().startswith("x2w") + + +def _clean_export_name(name): + text = name.strip().strip('"') + match = re.match(r"^(.*?)@\d+$", text) + if match: + text = match.group(1) + return text.strip() + + +def _parse_def(path, root): + text = path.read_text(encoding="utf-8-sig", errors="replace") + module = None + in_exports = False + entries = [] + source = _relative(path, root) + + for raw in text.splitlines(): + line = raw.split(";", 1)[0].strip() + if not line: + continue + upper = line.upper() + if upper.startswith("LIBRARY"): + rest = line[len("LIBRARY"):].strip() + module = rest.strip().strip('"') or None + continue + if upper.startswith("EXPORTS"): + in_exports = True + continue + if not in_exports: + continue + + token = line.split()[0] + alias = None + if "=" in token: + token, alias = token.split("=", 1) + export_name = _clean_export_name(token) + if alias: + alias = _clean_export_name(alias) + if not export_name or export_name.startswith(";"): + continue + entries.append( + { + "module": module or _module_from_def_stem(path.stem), + "name": export_name, + "alias": alias, + "source": source, + } + ) + return entries + + +def _load_shim_mapping(path): + data = _read_json(path) + source = path.name + entries = [] + default_module = data.get("module") if isinstance(data, dict) else None + + def add(module, item): + if isinstance(item, str): + name = item.strip() + alias = None + elif isinstance(item, dict): + name = item.get("name") + alias = item.get("alias") + else: + raise InputError("{} shim entry must be a string or object".format(source)) + if not isinstance(name, str) or not name.strip(): + raise InputError("{} shim entry has no non-empty name".format(source)) + if alias is not None: + if not isinstance(alias, str): + raise InputError("{} shim alias must be a string".format(source)) + alias = alias.strip() or None + entries.append( + { + "module": module or "shims", + "name": name.strip(), + "alias": alias, + "source": source, + } + ) + + def add_mapping(mapping): + for module, rows in mapping.items(): + if not isinstance(rows, list): + raise InputError("{} mapping {} must be an array".format(source, module)) + for item in rows: + add(module, item) + + def add_rows(module, rows): + if not isinstance(rows, list): + raise InputError("{} group {} must be an array".format(source, module)) + for item in rows: + add(module, item) + + metadata = { + "schema", + "generated", + "sdk", + "module", + "source", + "confidence", + "targets", + "note", + "version", + } + + if isinstance(data, dict): + if isinstance(data.get("modules"), dict): + add_mapping(data["modules"]) + elif isinstance(data.get("modules"), list): + for group in data["modules"]: + group = _require_object(group, source + " module group") + module = group.get("module") or default_module + rows = group.get("exports", group.get("shims")) + if rows is None: + raise InputError("{} module group has no exports".format(source)) + add_rows(module, rows) + elif isinstance(data.get("shims"), list): + for item in data["shims"]: + if isinstance(item, dict) and item.get("module"): + add(item["module"], item) + else: + add(default_module, item) + elif isinstance(data.get("shims"), dict): + add_mapping(data["shims"]) + elif isinstance(data.get("exports"), list): + add_rows(default_module, data["exports"]) + else: + mapping = {} + for key, value in data.items(): + if key in metadata: + continue + if not isinstance(value, list): + raise InputError( + "{} mapping {} must be an array".format(source, key) + ) + mapping[key] = value + if mapping: + add_mapping(mapping) + elif not data: + return [] + else: + raise InputError("{} has no shim mapping".format(source)) + elif isinstance(data, list): + for item in data: + if isinstance(item, dict) and isinstance(item.get("exports"), list): + module = item.get("module") or default_module + add_rows(module, item["exports"]) + elif isinstance(item, dict) and item.get("module"): + add(item["module"], item) + else: + add(default_module, item) + else: + raise InputError("{} must contain a shim mapping".format(source)) + return entries + + +def load_shims(path): + if path is None: + return { + "source": None, + "exports": 0, + "covered": 0, + "without_fact": [], + "internal": 0, + } + path = Path(path) + if not path.exists(): + raise InputError("defs path does not exist: {}".format(path)) + + entries = [] + if path.is_file(): + if path.suffix.lower() == ".json": + entries = _load_shim_mapping(path) + elif path.suffix.lower() == ".def": + entries = _parse_def(path, path.parent) + else: + raise InputError("defs file must be .def or .json: {}".format(path)) + elif path.is_dir(): + files = sorted( + ( + item + for item in path.rglob("*") + if item.is_file() and item.suffix.lower() == ".def" + ), + key=lambda item: item.as_posix().casefold(), + ) + for item in files: + entries.extend(_parse_def(item, path)) + else: + raise InputError("defs path is not a file or directory: {}".format(path)) + + merged = {} + internal = 0 + for entry in entries: + if _is_internal_shim(entry["name"]): + internal += 1 + continue + key = (entry["module"].casefold(), entry["name"].casefold()) + if key not in merged: + merged[key] = entry + elif not merged[key].get("alias") and entry.get("alias"): + merged[key]["alias"] = entry["alias"] + + result = [] + for entry in sorted( + merged.values(), + key=lambda item: ( + item["module"].casefold(), + item["module"], + item["name"].casefold(), + item["name"], + ), + ): + result.append( + { + "module": entry["module"], + "name": entry["name"], + "alias": entry.get("alias"), + "source": entry["source"], + } + ) + return { + "source": str(path), + "exports": len(result), + "covered": 0, + "without_fact": result, + "internal": internal, + } + + +def _associate_shims(shims, facts): + if not shims["without_fact"]: + return shims + exact = {fact["name"] for fact in facts} + folded = {fact["name"].casefold() for fact in facts} + covered = 0 + missing = [] + for entry in shims["without_fact"]: + names = [entry["name"]] + if entry.get("alias"): + names.append(entry["alias"]) + if any(name in exact or name.casefold() in folded for name in names): + covered += 1 + else: + missing.append(entry) + shims["covered"] = covered + shims["without_fact"] = missing + return shims + + +def _module_rows(facts): + rows = {} + for fact in facts: + module = fact["module"] + row = rows.setdefault( + module, + { + "module": module, + "types": set(), + "exports": set(), + "runtime_facts": 0, + "shader_facts": 0, + "platform_facts": 0, + "facts": 0, + }, + ) + row["facts"] += 1 + kind = fact["kind"] + if _is_type_kind(kind): + row["types"].add(fact["name"]) + elif kind.casefold() == "export": + row["exports"].add(fact["name"]) + elif kind.casefold() == "behavior": + row["runtime_facts"] += 1 + elif kind.casefold() == "shader": + row["shader_facts"] += 1 + elif kind.casefold() == "platform": + row["platform_facts"] += 1 + + result = [] + for module in sorted(rows, key=lambda text: (text.casefold(), text)): + row = rows[module] + result.append( + { + "module": row["module"], + "types": len(row["types"]), + "exports": len(row["exports"]), + "runtime_facts": row["runtime_facts"], + "shader_facts": row["shader_facts"], + "platform_facts": row["platform_facts"], + "facts": row["facts"], + } + ) + return result + + +def _count_unique_types(facts): + return len( + { + (fact["module"], fact["name"]) + for fact in facts + if _is_type_kind(fact["kind"]) + } + ) + + +def _count_unique_exports(facts): + return len( + { + (fact["module"], fact["name"]) + for fact in facts + if fact["kind"].casefold() == "export" + } + ) + + +def build_report(root, defs=None, required=()): + facts, category_files, category_facts = load_knowledge(root) + facts = _canonicalise_modules(facts) + facts = _dedupe_facts(facts) + conflicts = detect_conflicts(facts) + shims = _associate_shims(load_shims(defs), facts) + + categories = {} + missing = [] + for category in CATEGORIES: + files = category_files[category] + present = bool(files) + if not present: + missing.append(category) + categories[category] = { + "present": present, + "files": files, + "facts": category_facts[category], + } + + required = list(required) + required_missing = [category for category in required if category in missing] + + modules = _module_rows(facts) + runtime_facts = sum(fact["kind"].casefold() == "behavior" for fact in facts) + shader_facts = sum(fact["kind"].casefold() == "shader" for fact in facts) + platforms = len( + {fact["name"] for fact in facts if fact["kind"].casefold() == "platform"} + ) + summary = { + "modules": len(modules), + "types": _count_unique_types(facts), + "classes_types": _count_unique_types(facts), + "exports": _count_unique_exports(facts), + "export_rows": category_facts["exports"], + "runtime_facts": runtime_facts, + "shader_facts": shader_facts, + "platforms": platforms, + "facts": len(facts), + "conflicts": len(conflicts), + "shims_without_fact": len(shims["without_fact"]), + "shims": shims["exports"], + } + + return { + "schema": SCHEMA, + "generated_by": {"tool": TOOL, "version": VERSION}, + "inputs": { + "root": str(root), + "defs": str(defs) if defs is not None else None, + }, + "summary": summary, + "categories": categories, + "missing": missing, + "required": required, + "required_missing": required_missing, + "modules": modules, + "conflicts": conflicts, + "shims": shims, + "facts": facts, + } + + +def _md_cell(value): + return ( + str(value) + .replace("|", "\\|") + .replace("\r", " ") + .replace("\n", " ") + ) + + +def _md_value(value): + if isinstance(value, str): + return value + return _canonical(value) + + +def _md_values(values): + parts = [] + for item in values: + value = item.get("value") + if isinstance(value, dict) and "size" in value and "members" in value: + shown = "size={} members={}".format(value["size"], len(value["members"])) + else: + shown = _md_value(value) + if len(shown) > 160: + shown = shown[:157] + "..." + parts.append( + "{}={} ({})".format( + item.get("module", ""), + shown, + _md_cell(item.get("source", "")), + ) + ) + return "; ".join(parts) + + +def render_markdown(report): + summary = report["summary"] + lines = [ + "# GDK knowledge coverage", + "", + "- Schema: {}".format(report["schema"]), + "- Tool: {} version {}".format( + report["generated_by"]["tool"], report["generated_by"]["version"] + ), + "- Knowledge root: {}".format(_md_cell(report["inputs"]["root"])), + "", + "The report merges metadata facts from the knowledge root. It does not read", + "or execute SDK binaries, and it does not infer a fact from a missing category.", + "", + "## Summary", + "", + "| Metric | Value |", + "| --- | ---: |", + "| Modules | {} |".format(summary["modules"]), + "| Classes/types | {} |".format(summary["types"]), + "| Exports | {} |".format(summary["exports"]), + "| Export rows | {} |".format(summary["export_rows"]), + "| Runtime facts | {} |".format(summary["runtime_facts"]), + "| Shader facts | {} |".format(summary["shader_facts"]), + "| Platforms | {} |".format(summary["platforms"]), + "| Normalised facts | {} |".format(summary["facts"]), + "| Conflicts | {} |".format(summary["conflicts"]), + "| Shim exports | {} |".format(summary["shims"]), + "| Shims without fact | {} |".format(summary["shims_without_fact"]), + "", + "## Categories", + "", + "| Category | State | Files | Facts |", + "| --- | --- | ---: | ---: |", + ] + for category in CATEGORIES: + info = report["categories"][category] + files = ", ".join(info["files"]) if info["files"] else "-" + lines.append( + "| {} | {} | {} | {} |".format( + category, + "present" if info["present"] else "missing", + _md_cell(files), + info["facts"], + ) + ) + lines.append("") + if report["missing"]: + lines.append( + "Missing categories: {}.".format(", ".join(report["missing"])) + ) + else: + lines.append("All six categories are present.") + if report["required"]: + if report["required_missing"]: + lines.append( + "Required categories missing: {}.".format( + ", ".join(report["required_missing"]) + ) + ) + else: + lines.append( + "Required categories present: {}.".format( + ", ".join(report["required"]) + ) + ) + + lines.extend(["", "## Conflicts", ""]) + if report["conflicts"]: + lines.extend( + [ + "| Kind | Module | Name | Values | Sources |", + "| --- | --- | --- | --- | --- |", + ] + ) + for conflict in report["conflicts"]: + lines.append( + "| {} | {} | {} | {} | {} |".format( + conflict["kind"], + _md_cell(conflict["module"]), + _md_cell(conflict["name"]), + _md_cell(_md_values(conflict["values"])), + _md_cell(", ".join(conflict["sources"])), + ) + ) + else: + lines.append("No conflicts detected.") + + lines.extend( + [ + "", + "## Coverage by module", + "", + "| Module | Classes/types | Exports | Runtime facts | Shader facts | Platform facts | Facts |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: |", + ] + ) + for module in report["modules"]: + lines.append( + "| {} | {} | {} | {} | {} | {} | {} |".format( + _md_cell(module["module"]), + module["types"], + module["exports"], + module["runtime_facts"], + module["shader_facts"], + module["platform_facts"], + module["facts"], + ) + ) + + lines.extend(["", "## Shims without associated fact", ""]) + if report["inputs"]["defs"] is None: + lines.append("Shim coverage was not checked; pass --defs or a mapping JSON.") + elif report["shims"]["without_fact"]: + lines.extend( + [ + "| Module | Shim export | Alias | Def |", + "| --- | --- | --- | --- |", + ] + ) + for shim in report["shims"]["without_fact"]: + lines.append( + "| {} | {} | {} | {} |".format( + _md_cell(shim["module"]), + _md_cell(shim["name"]), + _md_cell(shim["alias"] or "-"), + _md_cell(shim["source"]), + ) + ) + else: + lines.append( + "All {} shim exports match a fact.".format(report["shims"]["exports"]) + ) + + lines.extend( + [ + "", + "## Limits", + "", + "A header fact does not prove the runtime. Layout and ABI rows only describe", + "the header or compile-time probe that produced them; runtime observations are", + "separate facts with their own source and confidence. An absent category is", + "reported as missing and is not treated as a zero-valued fact. Ordinals are", + "compared only when both sources report one, and RVA differences between", + "debug, release, import-library and DLL records are not conflicts. Anonymous", + "MSVC tags are counted as types but are not compared by display name because", + "several distinct anonymous records can share the same text.", + ] + ) + return "\n".join(lines) + "\n" + + +def _write_text(path, text): + path = Path(path) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + except OSError as exc: + raise InputError("cannot write {}: {}".format(path, exc)) from exc + + +def _parse_required(value): + if value is None: + return [] + result = [] + for token in value.split(","): + category = token.strip().casefold() + if not category: + raise InputError("--require contains an empty category") + if category not in CATEGORIES: + raise InputError( + "--require has unknown category {}; expected one of {}".format( + category, ", ".join(CATEGORIES) + ) + ) + if category not in result: + result.append(category) + return result + + +def _run_report(args): + root = Path(args.root) + json_path = Path(args.json) + markdown_path = Path(args.markdown) + if json_path.resolve() == markdown_path.resolve(): + raise InputError("--json and --markdown must be different paths") + required = _parse_required(args.require) + report = build_report(root, args.defs, required) + + _write_text( + json_path, + json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False) + "\n", + ) + _write_text(markdown_path, render_markdown(report)) + + summary = report["summary"] + print( + "{}: {} facts, {} conflicts, {} shims without fact".format( + TOOL, + summary["facts"], + summary["conflicts"], + summary["shims_without_fact"], + ) + ) + + if args.check: + failures = [] + if report["conflicts"]: + failures.append("{} conflict(s)".format(len(report["conflicts"]))) + if report["required_missing"]: + failures.append( + "missing required categories: {}".format( + ", ".join(report["required_missing"]) + ) + ) + if failures: + print("error: " + "; ".join(failures), file=sys.stderr) + return 1 + return 0 + + +def _build_parser(): + parser = argparse.ArgumentParser( + description="Merge GDK knowledge facts and report coverage and conflicts." + ) + subparsers = parser.add_subparsers(dest="command", required=True) + report = subparsers.add_parser("report", help="write coverage JSON and Markdown") + report.add_argument("--root", required=True, help="knowledge root directory") + report.add_argument("--json", required=True, help="coverage JSON output") + report.add_argument("--markdown", required=True, help="Markdown report output") + report.add_argument( + "--defs", + help="repository src directory, one .def file, or a shim-mapping JSON", + ) + report.add_argument( + "--require", + help="comma-separated categories that must be present (with --check)", + ) + report.add_argument( + "--check", + action="store_true", + help="exit 1 on conflicts or missing categories listed by --require", + ) + return parser + + +def main(argv=None): + parser = _build_parser() + args = parser.parse_args(argv) + try: + if args.command == "report": + return _run_report(args) + parser.error("unknown command") + except InputError as exc: + print("error: {}".format(exc), file=sys.stderr) + return 2 + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_layouts.py b/tools/gdk_layouts.py new file mode 100644 index 0000000000..1ab95b588e --- /dev/null +++ b/tools/gdk_layouts.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Parse MSVC /d1reportAllClassLayout logs and compare two layout sets. + +The logs are produced outside the repository from GDK headers. This tool keeps +only sizes, offsets and member names, so the JSON can live in the local +knowledge base without copying header text. + +Commands: + parse <log>... --json <out> [--module M] [--platform P] [--header H] + [--header-sha256 SHA] [--msvc VERSION] [--prefix P]... + compare <left.json> <right.json> [--json <out>] + +compare exits 1 when a class size or a named member offset differs. +""" + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +HEADER_RE = re.compile(r"^(?:class|struct|union)\s+(.+?)\s+size\((\d+)\):") +MEMBER_RE = re.compile(r"^\s*(\d+)\s*\|\s*(.*?)\s*$") +ALIGNMENT_RE = re.compile(r"^\s*\|\s*<alignment member> \(size=(\d+)\)") +BASE_RE = re.compile(r"\+---\s*\(base class\s+(.+?)\)") +BITS_RE = re.compile(r":\s*(\d+)\s*$") +ARRAY_RE = re.compile(r"^(.*?)\s+([A-Za-z_]\w*)\s*\[(\d+)\]$") +NAMED_RE = re.compile(r"^(?P<type>.+?)\s+(?P<name>[A-Za-z_]\w*)$") +VFTABLE = "{vfptr}" + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def parse_member(offset, text): + if BASE_RE.search(text): + return { + "offset": offset, + "type": "", + "name": BASE_RE.search(text).group(1).strip(), + "bits": None, + "kind": "base", + } + if VFTABLE in text: + return {"offset": offset, "type": "void*", "name": VFTABLE, "bits": None, "kind": "vftable"} + + rest = text + bits = None + match = BITS_RE.search(rest) + if match: + bits = int(match.group(1)) + rest = rest[: match.start()].rstrip() + + array = None + match = ARRAY_RE.match(rest) + if match: + rest, count = match.group(1).strip(), int(match.group(3)) + array = count + name = match.group(2) + return { + "offset": offset, + "type": rest, + "name": name, + "bits": bits, + "kind": "field", + "array": array, + } + + match = NAMED_RE.match(rest) + if match: + return { + "offset": offset, + "type": match.group("type").strip(), + "name": match.group("name"), + "bits": bits, + "kind": "field", + } + if re.fullmatch(r"[A-Za-z_]\w*", rest): + return { + "offset": offset, + "type": "unknown", + "name": rest, + "bits": bits, + "kind": "field", + } + return { + "offset": offset, + "type": rest.strip(), + "name": "", + "bits": bits, + "kind": "unnamed", + } + + +def parse_log(path): + classes = [] + current = None + alignment = 0 + for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines(): + header = HEADER_RE.match(line) + if header: + if current is not None: + current["alignment"] = alignment + name = header.group(1).strip() + current = { + "name": name, + "size": int(header.group(2)), + "bases": [], + "members": [], + "alignment": 0, + "nested_in": name.rsplit("::", 1)[0] if "::" in name else None, + } + alignment = 0 + classes.append(current) + continue + if current is None: + continue + if line.strip().startswith("+---"): + continue + align = ALIGNMENT_RE.match(line) + if align: + alignment = int(align.group(1)) + current["members"].append( + { + "offset": current["size"] - alignment, + "type": "", + "name": "<alignment>", + "bits": None, + "kind": "alignment", + } + ) + continue + member = MEMBER_RE.match(line) + if not member: + continue + text = re.sub(r"^(?:\|\s*)+", "", member.group(2)) + if not text.strip(): + continue + parsed = parse_member(int(member.group(1)), text) + if parsed["kind"] == "base": + current["bases"].append({"offset": parsed["offset"], "name": parsed["name"]}) + else: + current["members"].append(parsed) + if current is not None: + current["alignment"] = alignment + for block in classes: + seen = set() + unique = [] + for member in block["members"]: + key = (member["offset"], member["name"], member["kind"]) + if key not in seen: + seen.add(key) + unique.append(member) + block["members"] = unique + return classes + + +def parse_command(args): + classes = [] + sources = [] + for path in args.logs: + block = parse_log(path) + classes.extend(block) + sources.append({"log": str(path), "sha256": sha256(path), "classes": len(block)}) + if args.prefix: + classes = [item for item in classes if any(item["name"].startswith(prefix) for prefix in args.prefix)] + document = { + "sdk": args.sdk, + "module": args.module, + "platform": args.platform, + "header": args.header, + "header_sha256": args.header_sha256 or (sha256(args.header) if args.header else ""), + "msvc": args.msvc, + "source": "msvc-layout", + "logs": sources, + "classes": classes, + "stats": {"classes": len(classes), "bytes": sum(item["size"] for item in classes)}, + } + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps(document["stats"])) + return 0 + + +def index_classes(document): + return {item["name"]: item for item in document.get("classes", [])} + + +def compare_command(args): + left = json.loads(Path(args.left).read_text(encoding="utf-8")) + right = json.loads(Path(args.right).read_text(encoding="utf-8")) + left_classes = index_classes(left) + right_classes = index_classes(right) + changes = [] + for name in sorted(set(left_classes) | set(right_classes)): + old = left_classes.get(name) + new = right_classes.get(name) + if old is None: + changes.append({"class": name, "kind": "added", "right_size": new["size"]}) + continue + if new is None: + changes.append({"class": name, "kind": "removed", "left_size": old["size"]}) + continue + if old["size"] != new["size"]: + changes.append( + {"class": name, "kind": "size", "left_size": old["size"], "right_size": new["size"]} + ) + old_members = {item["name"]: item["offset"] for item in old["members"] if item.get("name") and item["kind"] == "field"} + new_members = {item["name"]: item["offset"] for item in new["members"] if item.get("name") and item["kind"] == "field"} + for member in sorted(set(old_members) | set(new_members)): + if old_members.get(member) != new_members.get(member): + changes.append( + { + "class": name, + "member": member, + "kind": "offset", + "left_offset": old_members.get(member), + "right_offset": new_members.get(member), + } + ) + if args.json: + Path(args.json).write_text(json.dumps(changes, indent=2) + "\n", encoding="utf-8") + if not changes: + print("no layout differences") + return 0 + for change in changes: + print(json.dumps(change, sort_keys=True)) + return 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + parse = sub.add_parser("parse", help="parse MSVC layout logs") + parse.add_argument("logs", nargs="+") + parse.add_argument("--json", required=True) + parse.add_argument("--sdk", default="261000") + parse.add_argument("--module", default="") + parse.add_argument("--platform", default="") + parse.add_argument("--header", default="") + parse.add_argument("--header-sha256", default="") + parse.add_argument("--msvc", default="") + parse.add_argument("--prefix", action="append", default=[]) + parse.set_defaults(func=parse_command) + + compare = sub.add_parser("compare", help="compare two layout JSON files") + compare.add_argument("left") + compare.add_argument("right") + compare.add_argument("--json") + compare.set_defaults(func=compare_command) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_platform_profiles.py b/tools/gdk_platform_profiles.py new file mode 100644 index 0000000000..0bc98d22dc --- /dev/null +++ b/tools/gdk_platform_profiles.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +"""Extract GDK MSBuild platform properties into JSON. + +The GDK installation stays outside the repository. This reads the canonical +VS2022/flatDeployment platform files, keeps the MSBuild conditions and resolves +the simple variables defined in the same files. Unresolved variables remain +visible instead of being guessed. + +Commands: + list --root <GDK_ROOT> [--vs v170] [--sdk 261000] + scan --root <GDK_ROOT> --platform <name> --json <out> [--vs v170] [--sdk 261000] +""" + +import argparse +import hashlib +import json +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +NS = "{http://schemas.microsoft.com/developer/msbuild/2003}" +VARIABLE = re.compile(r"\$\(([A-Za-z_][A-Za-z0-9_]*)\)") +PROPERTY_NAMES = ("PropertyGroup", "ItemDefinitionGroup", "ItemGroup") + + +def tag(element): + return element.tag.rsplit("}", 1)[-1] + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def platform_dirs(root): + root = Path(root) + found = {} + for candidate in root.rglob("Platform.props"): + directory = candidate.parent + found[str(directory).lower()] = directory + return list(found.values()) + + +def score(directory, vs, sdk): + parts = [part.lower() for part in directory.parts] + value = 0 + if "vs2022" in parts: + value += 20 + if vs.lower() in parts: + value += 10 + if "flatdeployment" in parts: + value += 5 + if sdk in parts: + value += 3 + if (directory / sdk).is_dir(): + value += 15 + return value + + +def choose(root, platform, vs, sdk): + matches = [item for item in platform_dirs(root) if item.name.lower() == platform.lower()] + if not matches: + return None + versioned = [item for item in matches if (item / sdk).is_dir()] + if not versioned: + return None + return max(versioned, key=lambda item: (score(item, vs, sdk), -len(str(item)))) + + +def list_command(args): + rows = [] + by_name = {} + for directory in platform_dirs(args.root): + candidate = { + "platform": directory.name, + "path": str(directory), + "score": score(directory, args.vs, args.sdk), + } + key = directory.name.lower() + if key not in by_name or candidate["score"] > by_name[key]["score"]: + by_name[key] = candidate + rows = list(by_name.values()) + rows.sort(key=lambda item: item["platform"].lower()) + for row in rows: + print(f"{row['platform']}\t{row['path']}") + return 0 + + +def parse_file(path, properties, items, sources): + sources.append({"path": str(path), "sha256": sha256(path)}) + tree = ET.parse(path) + root = tree.getroot() + for group in root: + name = tag(group) + condition = group.get("Condition", "") + if name == "PropertyGroup": + for child in group: + key = tag(child) + value = (child.text or "").strip() + properties.setdefault(key, []).append( + { + "value": value, + "condition": child.get("Condition", condition), + "file": Path(path).name, + } + ) + elif name == "ItemDefinitionGroup": + for item in group: + item_name = tag(item) + bucket = items.setdefault(item_name, {}) + for child in item: + key = tag(child) + bucket.setdefault(key, []).append( + { + "value": (child.text or "").strip(), + "condition": child.get("Condition", condition), + } + ) + + +def table(properties): + result = {} + for key, entries in properties.items(): + value = entries[-1]["value"] + if f"$({key})" in value: + continue + result[key] = value + return result + + +def resolve(text, variables, depth=0, seen=None): + if depth > 8 or not text: + return text + seen = set() if seen is None else seen + + def replace(match): + name = match.group(1) + if name in seen: + return match.group(0) + value = variables.get(name) + if value is None: + return match.group(0) + return resolve(value, variables, depth + 1, seen | {name}) + + replaced = VARIABLE.sub(replace, text) + if len(replaced) > 16384: + return replaced[:16384] + if replaced == text: + return text + return resolve(replaced, variables, depth + 1, seen) + + +def split_list(text): + if not text: + return [] + values = [] + for item in text.split(";"): + item = item.strip() + if not item or item.startswith("%("): + continue + values.append(item) + return values + + +def last_item(items, group, key): + entries = items.get(group, {}).get(key, []) + return entries[-1]["value"] if entries else "" + + +def combined(items, group, key, separator): + entries = items.get(group, {}).get(key, []) + return separator.join(entry["value"] for entry in entries if entry["value"]) + + +def scan_command(args): + directory = choose(args.root, args.platform, args.vs, args.sdk) + if directory is None: + print( + f"platform not found for SDK {args.sdk}: {args.platform}", + file=sys.stderr, + ) + return 2 + sources = [] + properties = {} + items = {} + edition = directory / args.sdk + files = [ + directory / "Platform.default.props", + edition / "Platform.Common.props", + edition / "Platform.Edition.default.props", + edition / "Platform.Edition.props", + edition / "Platform.Edition.targets", + edition / "Platform.Commandline.targets", + directory / "Platform.props", + directory / "Platform.targets", + ] + toolset_root = directory / "PlatformToolsets" + if toolset_root.exists(): + files += sorted(toolset_root.glob("*/Toolset.props")) + for path in files: + if path.exists(): + parse_file(path, properties, items, sources) + variables = table(properties) + + def resolved(value): + return resolve(value, variables) + + defines = split_list(resolved(combined(items, "ClCompile", "PreprocessorDefinitions", ";"))) + includes = split_list( + resolved(combined(items, "ClCompile", "AdditionalIncludeDirectories", ";")) + ) + if not includes: + includes = split_list(resolved(variables.get("Console_EndpointIncludeRoot", ""))) + libs = split_list(resolved(combined(items, "Link", "AdditionalLibraryDirectories", ";"))) + if not libs: + libs = split_list(resolved(variables.get("Console_EndpointLibRoot", ""))) + dependencies = split_list( + resolved(combined(items, "Link", "AdditionalDependencies", ";")) + ) + if not dependencies: + dependencies = split_list(resolved(variables.get("Console_Libs", ""))) + + document = { + "sdk": args.sdk, + "platform": directory.name, + "toolset": args.vs, + "root": str(directory), + "sources": sources, + "defines": defines, + "includes": includes, + "libs": libs, + "dependencies": dependencies, + "console": { + "endpoint_include_root": resolved(variables.get("Console_EndpointIncludeRoot", "")), + "endpoint_lib_root": resolved(variables.get("Console_EndpointLibRoot", "")), + "libs": split_list(resolved(variables.get("Console_Libs", ""))), + "tool_path": resolved(variables.get("Console_SdkToolPath", "")), + "sdk_root": resolved(variables.get("Console_SdkRoot", "")), + }, + "flags": { + "additional_options": split_list( + resolved(combined(items, "ClCompile", "AdditionalOptions", " ")) + ), + "ignore_specific_default_libraries": split_list( + resolved(last_item(items, "Link", "IgnoreSpecificDefaultLibraries")) + ), + "runtime_library": resolved(last_item(items, "ClCompile", "RuntimeLibrary")), + "exception_handling": resolved(last_item(items, "ClCompile", "ExceptionHandling")), + "language_standard": resolved(last_item(items, "ClCompile", "LanguageStandard")), + "floating_point_model": resolved( + last_item(items, "ClCompile", "FloatingPointModel") + ), + "enable_enhanced_instruction_set": resolved( + last_item(items, "ClCompile", "EnableEnhancedInstructionSet") + ), + "target_machine": resolved(last_item(items, "Link", "TargetMachine")), + "use_debug_libraries": resolved(variables.get("UseDebugLibraries", "")), + "character_set": resolved(variables.get("CharacterSet", "")), + }, + "properties": { + key: [ + {"value": entry["value"], "condition": entry["condition"], "file": entry["file"]} + for entry in entries + ] + for key, entries in properties.items() + }, + "items": items, + } + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print( + json.dumps( + { + "platform": document["platform"], + "sources": len(sources), + "defines": len(document["defines"]), + "includes": len(document["includes"]), + "libs": len(document["libs"]), + "dependencies": len(document["dependencies"]), + } + ) + ) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + for name in ("list", "scan"): + command = sub.add_parser(name) + command.add_argument("--root", required=True) + command.add_argument("--vs", default="v170") + command.add_argument("--sdk", default="261000") + if name == "scan": + command.add_argument("--platform", required=True) + command.add_argument("--json", required=True) + command.set_defaults(func=scan_command) + else: + command.set_defaults(func=list_command) + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_runtime_oracle.py b/tools/gdk_runtime_oracle.py new file mode 100644 index 0000000000..107bd0d4ed --- /dev/null +++ b/tools/gdk_runtime_oracle.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Compare one GDK runtime fixture against the GRDK and the Xbox2Windows shim. + +The reference executable links the installed gaming runtime and is run with the +inbox xgameruntime.dll. The candidate links the shim's import library and runs +with that library next to it. Both print one observation per line. Only the +normalized lines are compared: handles, console ids and per-user temp paths are +masked so two runs can be diffed. + +Commands: + run --gdk-root <GRDK> --shim-dir <dir> --fixture <cpp> --out <dir> + normalize <log> + diff <reference.txt> <candidate.txt> + +run returns 77 when cl.exe or a required path is missing, so CI can skip a host +without the GDK. The normalization and diff commands need no SDK. +""" + +import argparse +import difflib +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SKIP = 77 + +HANDLE_RE = re.compile( + r"\b(queue_handle|xpackage_mount_handle)=(?:0x)?[0-9A-Fa-f]+\b" +) +CONSOLE_RE = re.compile(r"\b(console_value=)[0-9A-Fa-f.]+") +PATH_RE = re.compile( + r"\b(pls_path_value=|xpackage_path_value=)" + r"(?:[A-Za-z]:\\[^\r\n]*?)\\Temp\\(xbox-recomp-(?:pls|packages))\\([^\\\s]+)" +) + + +def normalize_line(line): + """Mask volatile handles, console ids and per-user temp paths.""" + line = HANDLE_RE.sub(lambda m: m.group(1) + "=<handle>", line) + line = CONSOLE_RE.sub(lambda m: m.group(1) + "<console-id>", line) + line = PATH_RE.sub( + lambda m: m.group(1) + "<localappdata>\\Temp\\" + m.group(2) + "\\" + m.group(3), + line, + ) + return line + + +def normalize(lines): + return [normalize_line(str(line).rstrip("\r\n")) for line in lines] + + +def diff_lines(reference, candidate): + """Return a unified diff of two normalized logs, without file timestamps.""" + return list( + difflib.unified_diff( + list(reference), + list(candidate), + fromfile="reference", + tofile="candidate", + lineterm="", + n=2, + ) + ) + + +def read_lines(path): + return Path(path).read_text(encoding="utf-8", errors="replace").splitlines() + + +def grdk_version(include_dir): + header = Path(include_dir) / "GRDK.h" + if not header.exists(): + return "unknown" + match = re.search( + r"#define _GRDKVER_PRODUCTBUILDVER_FULL\s+([0-9.]+)", + header.read_text(encoding="utf-8", errors="replace"), + ) + return match.group(1) if match else "unknown" + + +def file_version(path): + path = Path(path) + if not path.exists(): + return "missing" + if sys.platform != "win32": + return "unavailable" + command = [ + "powershell", + "-NoProfile", + "-Command", + "(Get-Item -LiteralPath '" + str(path).replace("'", "''") + "').VersionInfo.FileVersion", + ] + try: + result = subprocess.run(command, capture_output=True, text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + return "unknown" + value = result.stdout.strip() + return value or "unknown" + + +def build_command(cl, fixture, include, output, lib, shim_dir=None): + command = [str(cl), "/nologo", "/std:c++17", "/EHsc", "/W4"] + if shim_dir is not None: + command.append("/DX2W_SHIM") + command += ["/I" + str(include), str(fixture), "/link"] + command.append("/LIBPATH:" + str(shim_dir if shim_dir is not None else lib)) + command += ["advapi32.lib", "/OUT:" + str(output)] + return command + + +def run_fixture(executable, cwd, timeout): + result = subprocess.run( + [str(executable)], + cwd=str(cwd), + capture_output=True, + text=True, + timeout=timeout, + ) + lines = (result.stdout + result.stderr).splitlines() + return result.returncode, lines + + +def msvc_environment(vcvars): + """Return os.environ plus the variables vcvars64.bat sets, or (None, log).""" + command = 'call "' + str(vcvars) + '" >nul && set' + result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=120) + if result.returncode != 0: + return None, result.stdout + result.stderr + environment = os.environ.copy() + for line in result.stdout.splitlines(): + key, separator, value = line.partition("=") + if separator: + for existing in [name for name in environment if name.lower() == key.lower()]: + del environment[existing] + environment[key] = value + return environment, "" + + +def run_build(command, environment): + return subprocess.run( + command, capture_output=True, text=True, timeout=120, env=environment + ) + + +def command_run(args): + gdk_root = Path(args.gdk_root) + include = gdk_root / "GameKit" / "Include" + lib = gdk_root / "GameKit" / "Lib" / "amd64" + shim_dir = Path(args.shim_dir) + fixture = Path(args.fixture) + for path in (include, lib, shim_dir, fixture): + if not path.exists(): + print(f"missing required path: {path}", file=sys.stderr) + return 2 + + environment = None + if args.vcvars: + environment, error = msvc_environment(args.vcvars) + if environment is None: + print("vcvars failed: " + error, file=sys.stderr) + return 2 + path = next((value for key, value in environment.items() if key.lower() == "path"), "") + cl = args.cl or shutil.which("cl", path=path) + if cl is None: + print("cl.exe not found in the vcvars environment", file=sys.stderr) + return 2 + else: + cl = args.cl or shutil.which("cl") + if cl is None or not Path(cl).exists(): + print("cl.exe not found; skipping the GDK runtime oracle", file=sys.stderr) + return SKIP + + out = Path(args.out) + reference_dir = out / "reference" + candidate_dir = out / "candidate" + reference_dir.mkdir(parents=True, exist_ok=True) + candidate_dir.mkdir(parents=True, exist_ok=True) + + reference_exe = reference_dir / "fixture.exe" + candidate_exe = candidate_dir / "fixture.exe" + builds = ( + ("reference", build_command(cl, fixture, include, reference_exe, lib)), + ("candidate", build_command(cl, fixture, include, candidate_exe, lib, shim_dir)), + ) + for name, command in builds: + result = run_build(command, environment) + (out / f"build-{name}.log").write_text( + result.stdout + result.stderr, encoding="utf-8" + ) + if result.returncode != 0: + print(f"{name} fixture build failed; see {out / f'build-{name}.log'}", file=sys.stderr) + return 2 + + runtime_dll = shim_dir / "xgameruntime.dll" + if runtime_dll.exists(): + shutil.copy2(runtime_dll, candidate_dir / runtime_dll.name) + + reference_exit, reference_lines = run_fixture(reference_exe, reference_dir, args.timeout) + candidate_exit, candidate_lines = run_fixture(candidate_exe, candidate_dir, args.timeout) + reference_normalized = normalize(reference_lines) + candidate_normalized = normalize(candidate_lines) + differences = diff_lines(reference_normalized, candidate_normalized) + + (out / "reference.txt").write_text("\n".join(reference_lines) + "\n", encoding="utf-8") + (out / "candidate.txt").write_text("\n".join(candidate_lines) + "\n", encoding="utf-8") + (out / "diff.txt").write_text("\n".join(differences) + "\n", encoding="utf-8") + report = { + "sdk": grdk_version(include), + "fixture": str(fixture), + "reference": { + "exit": reference_exit, + "runtime": file_version(Path("C:/Windows/System32/xgameruntime.dll")), + "normalized": reference_normalized, + }, + "candidate": { + "exit": candidate_exit, + "shim": str(shim_dir), + "normalized": candidate_normalized, + }, + "differences": differences, + } + (out / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(f"reference exit={reference_exit}; candidate exit={candidate_exit}") + print("\n".join(differences) if differences else "no normalized differences") + if args.fail_on_difference and differences: + return 1 + return 0 + + +def command_normalize(args): + lines = normalize(read_lines(args.log)) + print("\n".join(lines)) + return 0 + + +def command_diff(args): + reference = normalize(read_lines(args.reference)) + candidate = normalize(read_lines(args.candidate)) + differences = diff_lines(reference, candidate) + print("\n".join(differences) if differences else "no normalized differences") + return 1 if differences else 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + run = sub.add_parser("run", help="build and run the reference and shim fixtures") + run.add_argument("--gdk-root", required=True, help="GRDK root (contains GameKit)") + run.add_argument("--shim-dir", required=True, help="directory with the shim import library") + run.add_argument("--fixture", required=True, help="C++ fixture source") + run.add_argument("--out", required=True, help="output directory") + run.add_argument("--cl", help="explicit cl.exe path") + run.add_argument("--vcvars", help="Visual Studio vcvars64.bat; runs cl in its environment") + run.add_argument("--timeout", type=int, default=120) + run.add_argument("--fail-on-difference", action="store_true") + run.set_defaults(func=command_run) + + normalize_command = sub.add_parser("normalize", help="print a normalized log") + normalize_command.add_argument("log") + normalize_command.set_defaults(func=command_normalize) + + diff = sub.add_parser("diff", help="compare two normalized logs") + diff.add_argument("reference") + diff.add_argument("candidate") + diff.set_defaults(func=command_diff) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_shader_corpus.py b/tools/gdk_shader_corpus.py new file mode 100644 index 0000000000..783131666f --- /dev/null +++ b/tools/gdk_shader_corpus.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Compile an original HLSL corpus with the GDK dxc and retarget it. + +The Xbox container and the desktop container stay outside the repository. The +HLSL sources are original and versioned; only SHA-256 values and sizes are +recorded in the manifest. + +Commands: + build --gdk-root <GXDK> --corpus <dir> --out <dir> [--dxc <path>] [--require] + verify --manifest <corpus.json> [--root <dir>] + +build returns 77 when dxc is missing, unless --require is set. verify needs no +SDK and checks the recorded hashes and the DXIL triples. +""" + +import argparse +import hashlib +import json +import shutil +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SKIP = 77 + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def load_cases(corpus): + corpus = Path(corpus) + manifest = corpus / "cases.json" + document = json.loads(manifest.read_text(encoding="utf-8")) + cases = document.get("cases", []) + names = set() + for case in cases: + name = case["name"] + if name in names: + raise ValueError("duplicate corpus case: " + name) + names.add(name) + source = corpus / case["source"] + if not source.exists(): + raise ValueError("missing corpus source: " + str(source)) + return cases + + +def find_dxc(gdk_root, explicit): + if explicit: + return Path(explicit) if Path(explicit).exists() else None + for relative in ("GXDK/bin/Scarlett/dxc.exe", "bin/Scarlett/dxc.exe", "dxc.exe", "dxc"): + candidate = Path(gdk_root) / relative + if candidate.exists(): + return candidate + found = shutil.which("dxc") + return Path(found) if found else None + + +def dxc_version(dxc): + result = subprocess.run([str(dxc), "--version"], capture_output=True, text=True, timeout=60) + return (result.stdout + result.stderr).strip() + + +def compile_case(case, corpus, out, dxc): + directory = out / case["name"] + directory.mkdir(parents=True, exist_ok=True) + source = (corpus / case["source"]).resolve() + xbox = directory / "xbox.cso" + desktop = directory / "desktop.cso" + args = [ + str(dxc), + "-noprecompile", + "-T", + case["profile"], + "-E", + case["entry"], + ] + list(case.get("args", [])) + [str(source), "-Fo", str(xbox)] + result = subprocess.run(args, capture_output=True, text=True, timeout=300) + if result.returncode != 0: + return {"name": case["name"], "error": (result.stdout + result.stderr).strip()} + retarget = subprocess.run( + [sys.executable, str(ROOT / "tools" / "dxil_retarget.py"), str(xbox), str(desktop)], + capture_output=True, + text=True, + timeout=300, + ) + if retarget.returncode != 0: + return {"name": case["name"], "error": (retarget.stdout + retarget.stderr).strip()} + try: + dxil = json.loads(retarget.stdout) + except json.JSONDecodeError: + dxil = {"raw": retarget.stdout.strip()} + return { + "name": case["name"], + "source": case["source"], + "source_sha256": sha256(source), + "profile": case["profile"], + "entry": case["entry"], + "args": list(case.get("args", [])), + "xbox": { + "file": str(xbox.relative_to(out)), + "bytes": xbox.stat().st_size, + "sha256": sha256(xbox), + }, + "desktop": { + "file": str(desktop.relative_to(out)), + "bytes": desktop.stat().st_size, + "sha256": sha256(desktop), + }, + "dxil": dxil.get("dxil", dxil), + } + + +def build_command(args): + corpus = Path(args.corpus) + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + cases = load_cases(corpus) + dxc = find_dxc(args.gdk_root, args.dxc) + if dxc is None: + print("dxc not found; skipping the GDK shader corpus", file=sys.stderr) + return 2 if args.require else SKIP + version = dxc_version(dxc) + results = [] + failures = [] + for case in cases: + result = compile_case(case, corpus, out, dxc) + results.append(result) + if "error" in result: + failures.append(result) + print(f"{case['name']}: failed", file=sys.stderr) + if not args.keep_going: + break + else: + print(f"{case['name']}: {result['xbox']['bytes']} -> {result['desktop']['bytes']} bytes") + document = { + "sdk": "261000", + "dxc": version, + "cases": results, + } + (out / "corpus.json").write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"cases": len(results), "failures": len(failures)})) + return 2 if failures else 0 + + +def verify_command(args): + manifest = Path(args.manifest) + root = Path(args.root) if args.root else manifest.parent + document = json.loads(manifest.read_text(encoding="utf-8")) + errors = [] + for case in document.get("cases", []): + if "error" in case: + errors.append(case["name"] + ": build error recorded") + continue + for kind in ("xbox", "desktop"): + record = case.get(kind) + if not record: + errors.append(f"{case['name']}: missing {kind} record") + continue + path = root / record["file"] + if not path.exists(): + errors.append(f"{case['name']}: missing {path}") + continue + if sha256(path) != record["sha256"]: + errors.append(f"{case['name']}: {kind} hash mismatch") + if path.stat().st_size != record["bytes"]: + errors.append(f"{case['name']}: {kind} size mismatch") + dxil = case.get("dxil", {}) + if dxil.get("original_triple") != "dxil-ms-xb2": + errors.append(f"{case['name']}: source triple {dxil.get('original_triple')!r}") + if dxil.get("target_triple") != "dxil-ms-dx": + errors.append(f"{case['name']}: target triple {dxil.get('target_triple')!r}") + removed = dxil.get("removed_named_metadata", []) + if "xbox.compiler.options" not in removed: + errors.append(f"{case['name']}: xbox.compiler.options not removed") + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + print(f"verified {len(document.get('cases', []))} cases") + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + build = sub.add_parser("build") + build.add_argument("--gdk-root", required=True) + build.add_argument("--corpus", required=True) + build.add_argument("--out", required=True) + build.add_argument("--dxc") + build.add_argument("--require", action="store_true") + build.add_argument("--keep-going", action="store_true") + build.set_defaults(func=build_command) + + verify = sub.add_parser("verify") + verify.add_argument("--manifest", required=True) + verify.add_argument("--root") + verify.set_defaults(func=verify_command) + + args = parser.parse_args(argv) + try: + return args.func(args) + except (OSError, ValueError, json.JSONDecodeError) as error: + print(str(error), file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_shim_coverage.py b/tools/gdk_shim_coverage.py new file mode 100644 index 0000000000..4361bce732 --- /dev/null +++ b/tools/gdk_shim_coverage.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Compare a GDK export inventory with the Xbox2Windows shim .def files. + +The inventory comes from tools/gdk_exports.py. An export name is not a +signature and not a test: this matrix prioritizes work, it does not claim full +coverage. + +Commands: + --exports <json> --repo <Xbox2Windows> [--json <out>] [--markdown <out>] + --exports <json> --def xmem=src/xmem_shim.def ... [--json <out>] +""" + +import argparse +import json +import re +import sys +from pathlib import Path + + +DEFAULT_DEFS = { + "xmem": "src/xmem_shim.def", + "d3d12_xs": "src/d3d12_xs_shim.def", + "acphal": "src/startup_stubs/acphal.def", + "xapu": "src/startup_stubs/xapu.def", + "chad": "src/startup_stubs/chad.def", + "xg_xs": "src/startup_stubs/xg_xs.def", + "xcrdapi": "src/startup_stubs/xcrdapi.def", + "gameinput": "src/startup_stubs/gameinput.def", +} +DATA_PREFIXES = ("IID_", "WKPDID_") + + +def is_data(name): + return name.startswith(DATA_PREFIXES) + + +def read_def(path): + names = set() + ordinals = {} + data = set() + for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines(): + text = line.strip() + if not text or text.startswith(";") or text.upper().startswith("LIBRARY"): + continue + if text.upper() == "EXPORTS": + continue + fields = text.split("=", 1)[0].split() + if not fields: + continue + name = fields[0] + ordinal = None + match = re.fullmatch(r"(.+)@(\d+)", name) + if match: + name, ordinal_text = match.groups() + ordinal = int(ordinal_text) + else: + for token in text.split(): + match = re.fullmatch(r"@(\d+)", token) + if match: + ordinal = int(match.group(1)) + break + if not name or name == "PRIVATE": + continue + if "DATA" in text.split(): + data.add(name) + names.add(name) + if ordinal is not None: + ordinals[name] = ordinal + return {"names": names, "ordinals": ordinals, "data": data} + + +def normalize_module(name): + name = Path(name).stem.lower() + for suffix in (".lib", ".dll"): + if name.endswith(suffix): + return name[:-len(suffix)] + return name + + +def load_exports(document): + if isinstance(document, list): + modules = document + else: + modules = document.get("modules") or [document] + result = {} + for module in modules: + stem = normalize_module(module.get("module") or Path(module["file"]).stem) + entry = result.get(stem) + if entry is None: + entry = {"file": module["file"], "exports": [], "errors": []} + result[stem] = entry + if module.get("error"): + entry["errors"].append(module["error"]) + entry["exports"].extend(module.get("exports", [])) + return result + + +def find_module(modules, name): + return modules.get(normalize_module(name)) + + +def rows_for(args): + document = json.loads(Path(args.exports).read_text(encoding="utf-8")) + modules = load_exports(document) + definitions = {} + if args.repo: + for module, relative in DEFAULT_DEFS.items(): + path = Path(args.repo) / relative + if path.exists(): + definitions[module] = path + for item in args.defs: + module, separator, path = item.partition("=") + if not separator: + raise SystemExit("--def expects module=path: " + item) + definitions[module] = Path(path) + rows = [] + for module, def_path in sorted(definitions.items()): + shim = read_def(def_path) + gdk = find_module(modules, module) + if gdk is None: + rows.append( + { + "module": module, + "gdk_lib": None, + "def": str(def_path), + "gdk_exports": 0, + "gdk_functions": 0, + "gdk_data": 0, + "shim_exports": len(shim["names"]), + "shim_functions": len(shim["names"]), + "shim_data": len(shim["data"]), + "covered_functions": 0, + "covered_data": 0, + "missing_functions": [], + "missing_data": [], + "extra": [], + "ordinals": {}, + "def_ordinals": { + name: shim["ordinals"][name] for name in sorted(shim["ordinals"]) + }, + "unmeasured": "no inventory entry", + } + ) + continue + gdk_names = {item["name"] for item in gdk["exports"] if item.get("name")} + gdk_functions = {name for name in gdk_names if not is_data(name)} + gdk_data = {name for name in gdk_names if is_data(name)} + shim_functions = {name for name in shim["names"] if name not in shim["data"] and not is_data(name)} + shim_data = {name for name in shim["data"] if is_data(name)} + missing_functions = sorted(gdk_functions - shim_functions) + missing_data = sorted(gdk_data - shim_data) + ordinals = { + item["name"]: item["ordinal"] + for item in gdk["exports"] + if item.get("name") and item.get("ordinal") is not None + } + row = { + "module": module, + "gdk_lib": gdk["file"], + "def": str(def_path), + "gdk_exports": len(gdk_names), + "gdk_functions": len(gdk_functions), + "gdk_data": len(gdk_data), + "shim_exports": len(shim["names"]), + "shim_functions": len(shim_functions), + "shim_data": len(shim_data), + "covered_functions": len(gdk_functions & shim_functions), + "covered_data": len(gdk_data & shim_data), + "missing_functions": missing_functions, + "missing_data": missing_data, + "extra": sorted(shim["names"] - gdk_names), + "ordinals": {name: ordinals[name] for name in sorted(ordinals)}, + "def_ordinals": { + name: shim["ordinals"][name] for name in sorted(shim["ordinals"]) + }, + } + if gdk["errors"]: + row["unmeasured"] = "; ".join(gdk["errors"]) + rows.append(row) + return rows + + +def render_markdown(rows): + lines = [ + "# GDK export coverage of the Xbox2Windows shims", + "", + "| Module | GDK functions | Shim functions | Covered | Missing | Status |", + "|---|---:|---:|---:|---:|---|", + ] + for row in rows: + unmeasured = row.get("unmeasured") + data = dict(row) + data.update( + missing="?" if unmeasured else len(row["missing_functions"]), + gdk_functions="?" if unmeasured else row["gdk_functions"], + covered_functions="?" if unmeasured else row["covered_functions"], + status=unmeasured or "ok", + ) + lines.append( + "| {module} | {gdk_functions} | {shim_functions} | {covered_functions} | {missing} | {status} |".format(**data) + ) + lines += [ + "", + "Names only: an export is not a signature and not a test. Data exports", + "(IID_ and WKPDID_) are counted separately, and x2w_* locals are listed", + "as extras.", + "", + ] + for row in rows: + lines.append("## " + row["module"]) + lines.append("") + if row.get("unmeasured"): + lines.append("Unmeasured: " + row["unmeasured"]) + lines.append("") + continue + lines.append( + "Missing functions: " + + (", ".join(row["missing_functions"]) if row["missing_functions"] else "none") + ) + if row["missing_data"]: + lines.append("") + lines.append("Missing data: " + ", ".join(row["missing_data"])) + if row["extra"]: + lines.append("") + lines.append("Local extras: " + ", ".join(row["extra"])) + if row["ordinals"]: + lines.append("") + lines.append("GDK ordinals: " + ", ".join( + f"{name}@{ordinal}" for name, ordinal in row["ordinals"].items() + )) + lines.append("") + return "\n".join(lines) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--exports", required=True) + parser.add_argument("--repo") + parser.add_argument("--def", dest="defs", action="append", default=[]) + parser.add_argument("--json") + parser.add_argument("--markdown") + parser.add_argument("--fail-on-missing", action="store_true") + args = parser.parse_args(argv) + rows = rows_for(args) + if args.json: + Path(args.json).write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") + markdown = render_markdown(rows) + if args.markdown: + Path(args.markdown).write_text(markdown + "\n", encoding="utf-8") + print(markdown) + missing = sum(len(row["missing_functions"]) for row in rows) + unmeasured = sum(1 for row in rows if row.get("unmeasured")) + return 1 if args.fail_on_missing and (missing or unmeasured) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gpu-check/README.md b/tools/gpu-check/README.md index 95286748f4..8e4e26e449 100644 --- a/tools/gpu-check/README.md +++ b/tools/gpu-check/README.md @@ -14,4 +14,6 @@ These synthetic Direct3D 12 tests run on x64 Windows with a D3D12 adapter. The r The hardware run uses the high-performance D3D12 adapter selected by DXGI. Check the adapter name in the output, especially on multi-GPU systems. To test another GPU, pass part of its name, for example `.\Run-GpuCheck.ps1 -Adapter Radeon`. The report records the filter, and each test prints the adapter it used. A name that matches no D3D12 hardware adapter fails every test rather than skipping it. To run Microsoft's software renderer separately, use `.\Run-GpuCheck.ps1 -Backend warp`. The runner prints the output and saves `gpu-report-hardware.md` or `gpu-report-warp.md` beside the executable. A reported failure gives exit code 1. An unsupported capability gives a named SKIP and remains visible in the report. +The package also carries compiled copies of the translated compute shader tests (the `cases` folder, 23 cases and 22 mutation controls from `tests/startup_gfx2hlsl_compute_check.py`, built with DXC `cs_6_0`). The runner dispatches each one on the selected adapter and compares every output word, so the report gets one `gfx2hlsl_shaders` section with a line per case. A control passes when the adapter rejects the deliberately wrong shader; a control that reproduces the unmutated output is reported as a failure. They need no compiler. Use `.\Run-GpuCheck.ps1 -NoShaders` to skip them. The recorded cases do not read any game data and nothing leaves your machine. + Review the report, then paste its full contents as a comment on the [hardware coverage thread (#1)](https://github.com/R0Y00/Xbox2Windows/issues/1). Do not open a new GitHub issue. The report includes a summary of the adapter, driver, lane range, per-test results and the shader-visible CBV/SRV/UAV descriptor heap limit when the runtime reports it. If you would like a name or handle displayed in the coverage table, say so in your comment. Reports are shared manually. No game startup or frame rate is measured. diff --git a/tools/gpu-check/Run-GpuCheck.ps1 b/tools/gpu-check/Run-GpuCheck.ps1 index 03af93beef..914203981f 100644 --- a/tools/gpu-check/Run-GpuCheck.ps1 +++ b/tools/gpu-check/Run-GpuCheck.ps1 @@ -4,7 +4,8 @@ param( [ValidateSet('hardware', 'warp')] [string]$Backend = 'hardware', [string]$ReportPath, - [Alias('Adapter')][string]$AdapterFilter + [Alias('Adapter')][string]$AdapterFilter, + [switch]$NoShaders ) $ErrorActionPreference = 'Stop' @@ -12,6 +13,12 @@ if (-not $ReportPath) { $ReportPath = Join-Path $PSScriptRoot "gpu-report-$Backe $binary = (Get-Item -LiteralPath (Join-Path $PSScriptRoot 'offscreen_check.exe')).FullName $revision = (Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'SOURCE_COMMIT.txt')).Trim() if ($revision -notmatch '^[0-9a-f]{40}$') { throw 'The package is missing a valid source revision.' } +$manifest = Join-Path $PSScriptRoot 'cases/manifest.tsv' +if (-not $NoShaders) { + if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) { throw 'The package is missing cases/manifest.tsv.' } + $rows = @(Get-Content -LiteralPath $manifest | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + if (-not $rows.Count) { throw 'The shader case manifest is empty.' } +} $windows = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' $threadUrl = 'https://github.com/R0Y00/Xbox2Windows/issues/1' @@ -72,6 +79,71 @@ foreach ($test in 'dual-uav', 'texture-mips', 'bvh-waves', 'bvh-wave64', 'bvh-di }) } +function Invoke-ShaderCase { + param([string]$Id, [string]$Expect, [string]$Mismatch) + $files = foreach ($extension in 'cso', 'case') { Join-Path $PSScriptRoot "cases/$Id.$extension" } + foreach ($file in $files) { + if (-not (Test-Path -LiteralPath $file)) { return [pscustomobject]@{ Status = 'FAIL'; Note = "missing $file" } } + } + $process = [System.Diagnostics.Process]::new() + $process.StartInfo.FileName = $binary + $process.StartInfo.Arguments = "$Backend --compute-store-case `"$($files[0])`" `"$($files[1])`"" + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + try { + if ($AdapterFilter -and $Backend -eq 'hardware') { $process.StartInfo.EnvironmentVariables['XBOX2WINDOWS_ADAPTER'] = $AdapterFilter } + [void]$process.Start() + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(60000)) { + $process.Kill() + $process.WaitForExit() + return [pscustomobject]@{ Status = 'FAIL'; Note = 'timed out after 60 seconds' } + } + $code = $process.ExitCode + # Adapter enumeration notices are not diagnostics of the case. + $lines = @(($stderr.Result -split "`r?`n") | Where-Object { $_ -and -not $_.StartsWith('XBOX2WINDOWS_ADAPTER: skipping ') }) + } catch { + return [pscustomobject]@{ Status = 'FAIL'; Note = $_.Exception.Message } + } finally { + $process.Dispose() + } + if ($code -eq 77) { return [pscustomobject]@{ Status = 'SKIP'; Note = 'capability skip (exit 77)' } } + $first = if ($lines.Count) { $lines[0] } else { '' } + if ($Expect -eq 'pass') { + if ($code -eq 0 -and -not $lines.Count) { return [pscustomobject]@{ Status = 'PASS'; Note = '' } } + return [pscustomobject]@{ Status = 'FAIL'; Note = "exit $code $first" } + } + # A mutation control must be rejected: a card that reproduces the unmutated result would hide a real difference. + $rejected = $code -eq 1 -and ($lines | Where-Object { $_ -like '*expected=*' }) -and (-not $Mismatch -or $first -eq $Mismatch) + if ($rejected) { return [pscustomobject]@{ Status = 'PASS'; Note = 'control rejected' } } + return [pscustomobject]@{ Status = 'FAIL'; Note = "control not rejected: exit $code $first" } +} + +# Compiled gfx2hlsl compute cases recorded by tools/record_gpu_cases.py: each one is dispatched on this adapter and +# its output words are compared inside offscreen_check. They need no compiler here. One report section sums them up. +if (-not $NoShaders) { + $shaderLines = [System.Collections.Generic.List[string]]::new() + $counts = @{ PASS = 0; FAIL = 0; SKIP = 0 } + $shaderLines.Add('translated compute shaders replayed from the package (compiler, case, result)') + foreach ($row in $rows) { + $field = $row -split "`t" + $result = Invoke-ShaderCase -Id $field[0] -Expect $field[2] -Mismatch $field[3] + $counts[$result.Status]++ + $shaderLines.Add(("{0} {1} {2}{3}" -f $field[1], $field[0], $result.Status, $(if ($result.Note) { ": $($result.Note)" } else { '' }))) + } + $shaderLines.Insert(1, "cases: $($counts.PASS) pass, $($counts.FAIL) fail, $($counts.SKIP) skip of $($rows.Count)") + $shaderStatus = if ($counts.FAIL) { 'FAIL' } elseif ($counts.PASS) { 'PASS' } else { 'SKIP' } + if ($shaderStatus -eq 'FAIL') { $failed = $true } + $cases.Add([pscustomobject]@{ + Name = "gfx2hlsl_shaders_${Backend}" + Status = $shaderStatus + Details = ($shaderLines -join [Environment]::NewLine) + }) +} + $blocks = @($cases | ForEach-Object { $_.Details }) $adapter = Get-GpuField $blocks '(?m)^adapter=(.+?)\s+vendor=' $vendor = Get-GpuField $blocks '(?m)^adapter=.+?\s+vendor=([0-9A-Fa-f]+)\s+device=' diff --git a/tools/hardware_reports.py b/tools/hardware_reports.py index 732cba8cb4..f52ff82d06 100644 --- a/tools/hardware_reports.py +++ b/tools/hardware_reports.py @@ -108,9 +108,12 @@ def load_comments(paths: list[Path]) -> list[dict]: break value, index = decoder.raw_decode(text, index) for item in value if isinstance(value, list) else [value]: - if not isinstance(item, dict) or not isinstance(item.get("id"), int) or "body" not in item: - raise ValueError(f"{path}: expected GitHub issue comment objects with id and body") - comments[item["id"]] = item + cid = item.get("id") if isinstance(item, dict) else None + if isinstance(cid, bool) or not isinstance(cid, int) or cid < 0 or "body" not in item: + raise ValueError( + f"{path}: expected GitHub issue comment objects with non-negative integer id and body" + ) + comments[cid] = item return [comments[key] for key in sorted(comments)] @@ -446,6 +449,17 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--json", action="store_true", help="print JSON instead of Markdown") args = parser.parse_args(argv) try: + if args.after is not None and args.after < 0: + raise ValueError(f"--after must be non-negative, got {args.after}") + for path in args.comments: + if path.is_dir(): + raise IsADirectoryError(f"comments path is a directory: {path}") + if not path.is_file(): + raise FileNotFoundError(f"comments file not found: {path}") + if args.readme.is_dir(): + raise IsADirectoryError(f"--readme path is a directory: {args.readme}") + if not args.readme.is_file(): + raise FileNotFoundError(f"--readme file not found: {args.readme}") comments = load_comments(args.comments) summary = summarize(comments, args.readme.read_text(encoding="utf-8"), args.after) except (OSError, ValueError) as error: diff --git a/tools/host_commit.py b/tools/host_commit.py index 8bdf263d84..1c5576bf92 100644 --- a/tools/host_commit.py +++ b/tools/host_commit.py @@ -4,10 +4,17 @@ amount of free physical RAM. This is a snapshot, not a reservation. """ +from collections.abc import Mapping import ctypes as C import sys MIB = 1 << 20 +_SNAPSHOT_KEYS = ("available_bytes", "limit_mib", "used_mib", "available_mib") + + +def _is_int(value): + """Return True only for exact integers, excluding bool.""" + return isinstance(value, int) and not isinstance(value, bool) class PerformanceInformation(C.Structure): @@ -33,10 +40,12 @@ class PerformanceInformation(C.Structure): def snapshot_from_pages(limit_pages, used_pages, page_size): """Pure conversion of GetPerformanceInfo page counts; never wrap under pressure.""" - if not page_size or not limit_pages: + if not _is_int(page_size) or page_size <= 0 or not _is_int(limit_pages) or limit_pages <= 0: raise ValueError("Windows reported an invalid commit page size or limit") - limit_bytes = int(limit_pages) * int(page_size) - used_bytes = int(used_pages) * int(page_size) + if not _is_int(used_pages) or used_pages < 0: + raise ValueError("Windows reported an invalid commit used page count") + limit_bytes = limit_pages * page_size + used_bytes = used_pages * page_size free_bytes = max(limit_bytes - used_bytes, 0) return {"limit_mib": limit_bytes // MIB, "used_mib": used_bytes // MIB, "available_mib": free_bytes // MIB, "available_bytes": free_bytes} @@ -60,8 +69,16 @@ def read_host_commit(): def require_commit_budget(minimum_mib, snapshot): """Reject a requested budget before any guest module is mapped or started.""" - if not isinstance(minimum_mib, int) or minimum_mib < 0 or minimum_mib > 1 << 20: + if not _is_int(minimum_mib) or minimum_mib < 0 or minimum_mib > 1 << 20: raise ValueError("--min-commit-mib must be between 0 and 1048576") + if not isinstance(snapshot, Mapping): + raise ValueError("commit snapshot must be a Mapping") + for key in _SNAPSHOT_KEYS: + if key not in snapshot: + raise ValueError(f"commit snapshot is missing required field: {key}") + value = snapshot[key] + if not _is_int(value) or value < 0: + raise ValueError(f"commit snapshot field {key} must be a non-negative integer") if snapshot["available_bytes"] < minimum_mib * MIB: raise ValueError( f"Windows system commit headroom {snapshot['available_mib']} MiB is below the " diff --git a/tools/import_routing.py b/tools/import_routing.py index b4ed416d7f..42e2d08eb0 100644 --- a/tools/import_routing.py +++ b/tools/import_routing.py @@ -4,6 +4,8 @@ prove a provider, or load the image. """ +from collections.abc import MutableMapping + POLICY_VERSION = 2 ROUTE_KIND = "candidate" RESOLUTION = "not_checked" @@ -61,8 +63,17 @@ } +def _validate_module(module): + """Reject non-str, empty, whitespace, or control-character module names.""" + if not isinstance(module, str): + raise ValueError(f"module name must be a str, got {type(module).__name__}") + if not module or any(ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in module): + raise ValueError(f"invalid module name: {module!r}") + + def classify(module): """Return (route, reason) for a module name. No route is inferred.""" + _validate_module(module) name = module.lower() if name in POLICY["hle"]: return "hle", POLICY["hle"][name] @@ -82,6 +93,10 @@ def annotate(row, module_key="module"): The caller keeps its own caller and symbol fields. No provider or export resolution is recorded. """ + if not isinstance(row, MutableMapping): + raise TypeError(f"row must be a MutableMapping, got {type(row).__name__}") + if module_key not in row: + raise KeyError(module_key) module = row[module_key] route, reason = classify(module) row.update({ diff --git a/tools/intake_exe.py b/tools/intake_exe.py index 6216ab76ef..df99d36238 100644 --- a/tools/intake_exe.py +++ b/tools/intake_exe.py @@ -230,14 +230,45 @@ def main(argv: list[str] | None = None) -> int: parser.error("Use --build to select a package") args.build = builds[0].parent try: + if not args.build.exists(): + raise FileNotFoundError(f"--build directory not found: {args.build}") + if not args.build.is_dir(): + raise NotADirectoryError(f"--build path is not a directory: {args.build}") + if args.reports.is_symlink(): + raise ValueError(f"failed to write report in {args.reports}: report directory must not be a symlink") + if args.reports.is_file(): + raise ValueError(f"failed to write report in {args.reports}: path is a regular file") + for parent in args.reports.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError( + f"failed to write report in {args.reports}: parent is not a directory: {parent}" + ) root = args.build.resolve() reports = args.reports.resolve() - except OSError as exc: + except (OSError, ValueError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 if reports.is_relative_to(root) or reports.is_relative_to(PROJECT / "game-files"): parser.error("Choose a report directory outside game files") integrity = args.integrity or PROJECT / "out/integrity" / (root.name + ".json") + try: + if ( + args.candidate is not None + and (args.candidate.exists() or args.candidate.is_symlink()) + and not args.candidate.is_file() + ): + raise ValueError(f"candidate path is not a regular file: {args.candidate}") + if args.baseline.is_dir(): + raise IsADirectoryError(f"--baseline path is a directory: {args.baseline}") + if not args.baseline.is_file(): + raise FileNotFoundError(f"--baseline file not found: {args.baseline}") + if integrity.is_dir(): + raise IsADirectoryError(f"--integrity path is a directory: {integrity}") + if not integrity.is_file(): + raise FileNotFoundError(f"--integrity file not found: {integrity}") + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 report = {"schema": 1, "status": "error"} try: code = collect(root, args.candidate.resolve() if args.candidate else None, diff --git a/tools/mesh_dynamic_aot.py b/tools/mesh_dynamic_aot.py index 836c607bd6..03def0a8f0 100644 --- a/tools/mesh_dynamic_aot.py +++ b/tools/mesh_dynamic_aot.py @@ -26,6 +26,7 @@ from mesh_clip_cull import decode_vs_out_cntl, hlsl_fields, hlsl_writes, vertex_distances from mesh_entry_aot import U32, UNDEF, Wave, decode_mesh, float4, live_barriers_agree, run_group +from mesh_param_link import hlsl_param_fields, hlsl_param_writes, merge_wave_params, validate_linkage MAX_VARIANTS = 32 @@ -153,6 +154,11 @@ def descriptor_scalar_op(self, op, args): """Handle sampler heap and texture descriptor words; False for any other scalar op.""" if self.geometry.sampler_heap_sgpr is None: return False + if op.startswith(("s_cmp_", "s_bitcmp")): + found = self.descriptor_operand(args) + if found: + self.refuse_descriptor_use(op, found) + return False dest, *sources = args if op == "s_load_dwordx8": self.load_texture(args) @@ -282,11 +288,11 @@ def lane_value(self, token, lane): raise ValueError(f"Unproven runtime geometry word {value.index} in {token}") return value - def scalar_op(self, op, args): + def scalar_op(self, op, args, *, dynamic_bitcmp=False): if op == "s_cmp_eq_u32": left, right = (super(RuntimeWave, self).scalar(t, True) for t in args) if left is UNDEF or right is UNDEF: - return super().scalar_op(op, args) + return super().scalar_op(op, args, dynamic_bitcmp=dynamic_bitcmp) if isinstance(right, RuntimeWord): left, right = right, left if isinstance(left, RuntimeWord) and type(right) is int: @@ -297,7 +303,7 @@ def scalar_op(self, op, args): return if self.descriptor_scalar_op(op, args): return - super().scalar_op(op, args) + super().scalar_op(op, args, dynamic_bitcmp=dynamic_bitcmp) def vector_op(self, op, args, expressions): found = self.descriptor_operand(args if op.startswith("v_cmpx_") else args[1:]) @@ -334,6 +340,7 @@ class Variant: indices: dict # {vertex: {(kind, vector): values}} for the enabled clip and cull distances. distances: dict = None + params: dict = None def run_variant(decoded, geometry, limits, conditions): @@ -344,16 +351,15 @@ def run_variant(decoded, geometry, limits, conditions): raise ValueError("Inconsistent mesh synchronization or allocation") nv, np = first.counts[0] pos = first.positions | second.positions - attrs = first.attributes | second.attributes + params = merge_wave_params([first, second], pos) + attrs = params.get(0, {}) indices = first.indices | second.indices if (not 0 <= nv <= limits[0] or not 0 <= np <= limits[1] or set(pos) != set(range(nv)) or set(indices) != set(range(np)) or any(max(triangle) >= nv for triangle in indices.values())): raise ValueError("Conflicting mesh counts, vertices or primitive indices") - if attrs and attrs.keys() != pos.keys(): - raise ValueError("Incomplete vertex attribute") distances = vertex_distances(first.position_exports | second.position_exports, geometry.distance_layout) - return Variant(conditions, (nv, np), expressions, pos, attrs, indices, distances) + return Variant(conditions, (nv, np), expressions, pos, attrs, indices, distances, params) def enumerate_variants(decoded, geometry_word_count, limits, sampler_heap_sgpr=None, vs_out_cntl=None): @@ -384,13 +390,21 @@ def enumerate_variants(decoded, geometry_word_count, limits, sampler_heap_sgpr=N pending.append((*conditions, (split.index, split.value, True))) if not any(variant.conditions for variant in variants): raise ValueError("No runtime geometry comparisons") - if len({bool(variant.attributes) for variant in variants if variant.positions}) > 1: + if len({frozenset(variant.params) for variant in variants if variant.positions}) > 1: raise ValueError("Runtime mesh branches disagree on the vertex signature") return variants -def emit_hlsl(variants, limits, distance_layout=None): - has_attributes = any(variant.attributes for variant in variants) +def emit_hlsl(variants, limits, distance_layout=None, param_linkage=None): + exported_params = tuple(sorted(next((v.params for v in variants if v.positions), {}))) + validate_linkage( + exported_params, + pixel_attrs=param_linkage.pixel_attrs if param_linkage is not None else None, + flat=param_linkage.flat if param_linkage is not None else (), + f16_plain=param_linkage.f16_plain if param_linkage is not None else (), + distance_vectors=len(distance_layout.fields()) if distance_layout else 0, + semantic=param_linkage.semantic if param_linkage is not None else ("param" if any(s > 0 for s in exported_params) else "texcoord"), + ) input_words = sorted({index for variant in variants for index, _, _ in variant.conditions}) samples = any(expr.startswith(TEXTURE_NAME + ".SampleLevel(") for variant in variants for expr in variant.expressions) @@ -402,7 +416,7 @@ def emit_hlsl(variants, limits, distance_layout=None): f"SamplerState qh[{SAMPLER_HEAP_SIZE}] : register(s0, space{SAMPLER_HEAP_SPACE});"] if samples else []), "struct Vertex { float4 position : SV_Position; " - + ("float4 attr : TEXCOORD0; " if has_attributes else "") + hlsl_fields(distance_layout) + "};", + + hlsl_param_fields(exported_params, param_linkage) + hlsl_fields(distance_layout) + "};", '[outputtopology("triangle")]', "[numthreads(128,1,1)]", "void main(uint id : SV_GroupIndex, " @@ -432,8 +446,14 @@ def emit_hlsl(variants, limits, distance_layout=None): for index, position in sorted(variant.positions.items()): lines.append(f" if (id == {index}) {{") lines.append(f" vertices[{index}].position = {float4(position)};") - if has_attributes: - lines.append(f" vertices[{index}].attr = {float4(variant.attributes[index])};") + for write_line in hlsl_param_writes( + f"vertices[{index}]", + {s: d[index] for s, d in variant.params.items()}, + exported_params, + float4, + param_linkage, + ): + lines.append(f" {write_line}") if variant.distances: lines.append(f" {hlsl_writes(f'vertices[{index}]', variant.distances[index])}") lines.append(" }") @@ -445,15 +465,15 @@ def emit_hlsl(variants, limits, distance_layout=None): return "\n".join(lines) + "\n" -def lower(decoded, geometry_word_count, limits, sampler_heap_sgpr=None, vs_out_cntl=None): +def lower(decoded, geometry_word_count, limits, sampler_heap_sgpr=None, vs_out_cntl=None, param_linkage=None): variants = enumerate_variants(decoded, geometry_word_count, limits, sampler_heap_sgpr, vs_out_cntl) layout = None if vs_out_cntl is None else decode_vs_out_cntl(vs_out_cntl) - return emit_hlsl(variants, limits, layout) + return emit_hlsl(variants, limits, layout, param_linkage) -def translate(blob, geometry_word_count, library, sampler_heap_sgpr=None, vs_out_cntl=None): +def translate(blob, geometry_word_count, library, sampler_heap_sgpr=None, vs_out_cntl=None, param_linkage=None): decoded, limits = decode_mesh(blob, library) - return lower(decoded, geometry_word_count, limits, sampler_heap_sgpr, vs_out_cntl) + return lower(decoded, geometry_word_count, limits, sampler_heap_sgpr, vs_out_cntl, param_linkage) def _same_path(left: Path, right: Path) -> bool: diff --git a/tools/mesh_entry_aot.py b/tools/mesh_entry_aot.py index 7da3427eef..b382779b5f 100644 --- a/tools/mesh_entry_aot.py +++ b/tools/mesh_entry_aot.py @@ -16,6 +16,7 @@ import zlib from mesh_clip_cull import decode_vs_out_cntl, hlsl_fields, hlsl_writes, vertex_distances +from mesh_param_link import hlsl_param_fields, hlsl_param_writes, merge_wave_params, validate_linkage from pixel_aot import MESH_WAVE64, container_code, disassemble from resource_inventory import parts @@ -162,6 +163,7 @@ def __init__(self, wave, geometry, vertex_header=None): self.counts = [] self.positions = {} self.attributes = {} + self.params = {} self.indices = {} self.m0 = None self.written = set() @@ -375,7 +377,7 @@ def join_arms(self, decoded, expressions, jumps, pc, target_offset, cond, *, bra self.s, self.pending, self.scc = merged, true_p | false_p, None return join - def scalar_op(self, op, args): + def scalar_op(self, op, args, *, dynamic_bitcmp=False): d, *src = args if op in ( "s_load_dwordx4", @@ -389,16 +391,31 @@ def scalar_op(self, op, args): if op in ("s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64"): if len(args) != 2: raise ValueError(f"Expected two operands for {op}") - a, b = (self.scalar(t, True) for t in args) + wide = op.endswith("_b64") + src0, src1 = args + if wide and (re.fullmatch(r"s\d+", src0) or src0 in ("exec_lo", "exec_hi", "vcc_lo", "vcc_hi")): + raise ValueError(f"Expected a 64-bit scalar operand for {op}") + if not wide and (src0.startswith("s[") or src0 in ("exec", "vcc")): + raise ValueError(f"Expected a 32-bit scalar operand for {op}") + if src1.startswith("s[") or src1 in ("exec", "vcc"): + raise ValueError(f"Expected a 32-bit bit-index operand for {op}") + a, b = (self.scalar(token, True) for token in args) if a is UNDEF or b is UNDEF: self.scc = None return + test_one = op.startswith("s_bitcmp1_") + if dynamic_bitcmp and not wide and {type(a), type(b)} <= {int, str} and str in (type(a), type(b)): + value = f"asuint({a})" if type(a) is str else f"{a & U32}u" + index = f"(asuint({b}) & 31u)" if type(b) is str else f"{b & 31}u" + cmp_op = "!=" if test_one else "==" + self.scc = Dyn(f"(({value} & (1u << {index})) {cmp_op} 0u)") + return if type(a) is not int or type(b) is not int: raise ValueError("Dynamic scalar predicate") - mask = 63 if op.endswith("_b64") else 31 - width = WAVE if op.endswith("_b64") else U32 + mask = 63 if wide else 31 + width = WAVE if wide else U32 bit = ((a & width) >> (b & mask)) & 1 - self.scc = bit == (1 if op.startswith("s_bitcmp1_") else 0) + self.scc = bit == test_one return if op.startswith("s_cmp_"): a, b = (self.scalar(t, True) for t in args) @@ -744,7 +761,10 @@ def steps(self, decoded, expressions): """Execute the wave, yielding at each group barrier.""" jumps = {offset: i for i, (offset, _) in enumerate(decoded)} for _, line in decoded: - dest = line.partition(" ")[2].split(", ")[0] + op, _, tail = line.partition(" ") + if op.startswith(("s_cmp_", "s_bitcmp")): + continue + dest = tail.split(", ")[0] if re.fullmatch(r"s\d+", dest): self.written.add(int(dest[1:])) elif dest.startswith("s["): @@ -884,7 +904,7 @@ def exec_range(self, decoded, expressions, jumps, pc, stop, arm=False): elif op in ("ds_write_b32", "ds_read_b32"): self.lds_op(op, tail) elif op == "exp": - m = re.fullmatch(r"(prim|pos[0-3]|param0),? (.+?)( done)?", tail) + m = re.fullmatch(r"(prim|pos[0-3]|param(?:[0-9]|1[0-2])),? (.+?)( done)?", tail) if not m: raise ValueError("Unsupported mesh export") # A position export may leave done to a later clip or cull distance export. @@ -910,14 +930,25 @@ def exec_range(self, decoded, expressions, jumps, pc, stop, arm=False): elif m[1].startswith("pos") and len(operands) == 4: values = [None if t == "off" else self.lane_value(t, lane) for t in operands] self.position_exports.setdefault(i, []).append((m[1], values, bool(m[3]))) - elif m[1] == "param0" and len(operands) == 4 and all(re.fullmatch(r"v\d+", t) for t in operands): - if i in self.attributes: - raise ValueError("Duplicate vertex attribute") - self.attributes[i] = [self.lane_value(t, lane) for t in operands] + elif m[1].startswith("param") and len(operands) == 4 and all(re.fullmatch(r"v\d+", t) for t in operands): + slot = int(m[1][5:]) + slot_map = self.params.setdefault(slot, {}) + if i in slot_map: + raise ValueError("Duplicate vertex attribute" if slot == 0 else f"Duplicate vertex parameter param{slot}") + vals = [self.lane_value(t, lane) for t in operands] + slot_map[i] = vals + if slot == 0: + self.attributes[i] = vals else: raise ValueError("Unsupported live export") elif op.startswith("image_"): self.image_op(op, tail, expressions) + elif op.startswith("s_bitcmp"): + # A runtime bit predicate is supported only as the input to a verified descriptor join. + next_is_join_branch = not arm and pc < stop and decoded[pc][1].split(" ", 1)[0] in ( + "s_cbranch_scc0", "s_cbranch_scc1", + ) + self.scalar_op(op, args, dynamic_bitcmp=next_is_join_branch) elif op.startswith("s_"): self.scalar_op(op, args) elif op.startswith("v_"): @@ -1025,7 +1056,7 @@ def emit_compute_draw(bindings, expressions, positions, indices, attributes): return "\n".join(lines) + "\n" -def lower(decoded, geometry, limits, vertex_header=None, *, compute_fallback=False, vs_out_cntl=None): +def lower(decoded, geometry, limits, vertex_header=None, *, compute_fallback=False, vs_out_cntl=None, param_linkage=None): layout = None if vs_out_cntl is None else decode_vs_out_cntl(vs_out_cntl) if vertex_header is not None and ( type(vertex_header) != int or not 0 <= vertex_header <= U32 @@ -1048,15 +1079,16 @@ def lower(decoded, geometry, limits, vertex_header=None, *, compute_fallback=Fal raise ValueError("Inconsistent mesh synchronization or allocation") nv, np = waves[0].counts[0] pos = waves[0].positions | waves[1].positions - attributes = waves[0].attributes | waves[1].attributes - if attributes and attributes.keys() != pos.keys(): - raise ValueError("Incomplete vertex attribute") + params = merge_wave_params(waves, pos) + attributes = params.get(0, {}) idx = waves[0].indices | waves[1].indices # The native mesh shader writes any allocation within the PSV0 bounds. Each of the # 128 threads exports at most one vertex and one primitive, so every allocated # slot must be exported exactly once and nothing outside the allocation may be. if compute_fallback and (nv, np) != (3, 1): raise ValueError("The compute fallback translates only a single three-vertex triangle") + if compute_fallback and (any(s != 0 for s in params) or (param_linkage is not None and param_linkage.semantic != "texcoord")): + raise ValueError("The compute fallback translates only param0") if ( not 0 < nv <= limits[0] or not 0 < np <= limits[1] @@ -1068,6 +1100,15 @@ def lower(decoded, geometry, limits, vertex_header=None, *, compute_fallback=Fal distances = vertex_distances(waves[0].position_exports | waves[1].position_exports, layout) if compute_fallback and layout and layout.vectors: raise ValueError("The compute fallback has no room for clip or cull distances") + exported_params = tuple(sorted(params)) + validate_linkage( + exported_params, + pixel_attrs=param_linkage.pixel_attrs if param_linkage is not None else None, + flat=param_linkage.flat if param_linkage is not None else (), + f16_plain=param_linkage.f16_plain if param_linkage is not None else (), + distance_vectors=len(layout.fields()) if layout else 0, + semantic=param_linkage.semantic if param_linkage is not None else ("param" if any(s > 0 for s in exported_params) else "texcoord"), + ) bindings = [ "cbuffer Points : register(b0) { float4 pointData[32]; };", "cbuffer Matrices : register(b1) { float4 matrixData[32]; };", @@ -1081,7 +1122,7 @@ def lower(decoded, geometry, limits, vertex_header=None, *, compute_fallback=Fal "#ifdef TRACE_EXPORTS", "RWByteAddressBuffer trace : register(u0);", "#endif", - "struct Vertex {float4 position:SV_Position;" + ("float4 attr:TEXCOORD0;" if attributes else "") + "struct Vertex {float4 position:SV_Position;" + hlsl_param_fields(exported_params, param_linkage) + hlsl_fields(layout) + "};", '[outputtopology("triangle")]', f"[numthreads(128,1,1)] void main(uint id:SV_GroupIndex, out vertices Vertex v[{nv}], out indices uint3 p[{np}]) {{", @@ -1099,8 +1140,12 @@ def lower(decoded, geometry, limits, vertex_header=None, *, compute_fallback=Fal " }", ] ) - if attributes: - lines.append(f" if(id=={i}) v[{i}].attr={float4(attributes[i])};") + param_writes = hlsl_param_writes(f"v[{i}]", {s: d[i] for s, d in params.items()}, exported_params, float4, param_linkage) + if param_writes: + if len(param_writes) == 1 and param_writes[0].startswith(f"v[{i}].attr = "): + lines.append(f" if(id=={i}) {param_writes[0].replace(' = ', '=')}") + else: + lines.append(f" if(id=={i}) {{ {' '.join(param_writes)} }}") if i in distances: lines.append(f" if(id=={i}) {{ {hlsl_writes(f'v[{i}]', distances[i])} }}") for i, tri in idx.items(): @@ -1175,10 +1220,10 @@ def decode_mesh(blob, library): return disassemble(code, library, offsets=True, features=MESH_WAVE64), limits -def translate(blob, geometry, library, vertex_header=None, *, compute_fallback=False, vs_out_cntl=None): +def translate(blob, geometry, library, vertex_header=None, *, compute_fallback=False, vs_out_cntl=None, param_linkage=None): decoded, limits = decode_mesh(blob, library) return lower(decoded, geometry, limits, vertex_header, compute_fallback=compute_fallback, - vs_out_cntl=vs_out_cntl) + vs_out_cntl=vs_out_cntl, param_linkage=param_linkage) def _same_path(left: Path, right: Path) -> bool: diff --git a/tools/mesh_param_link.py b/tools/mesh_param_link.py new file mode 100644 index 0000000000..596c883c0c --- /dev/null +++ b/tools/mesh_param_link.py @@ -0,0 +1,142 @@ +"""Parameter export and pixel-input linkage (param0..param12) for mesh shaders (#2413 T4). + +AMD RDNA 2 ISA section 10.2 (EXP targets): target 32 + N encodes paramN (0 <= N <= 31). +Desktop D3D12 SM 6.5 allows at most 32 float4 vectors in the vertex output / pixel input +signature (SV_Position, optional clip/cull distance vectors, PARAM0..PARAMk, plus any +flat FPARAM* and binary16 HPARAML*/HPARAMH* shadow semantics required by gfx2hlsl). +""" + +from dataclasses import dataclass + +MAX_PARAM = 12 +MAX_VERTEX_VECTORS = 32 + + +@dataclass(frozen=True) +class ParamLinkage: + params: tuple + flat: tuple = () + f16_plain: tuple = () + pixel_attrs: tuple = () + semantic: str = "param" + + +def _normalize_slots(slots, name): + out = set() + for s in slots: + if type(s) is not int or not 0 <= s <= MAX_PARAM: + raise ValueError(f"{name} index {s!r} must be an integer in 0..{MAX_PARAM}") + out.add(s) + return tuple(sorted(out)) + + +def validate_linkage( + exported_params, + *, + pixel_attrs=None, + flat=(), + f16_plain=(), + distance_vectors=0, + semantic="param", +): + """Validate mesh parameter exports against pixel reads and D3D12's 32-vector signature limit.""" + params = _normalize_slots(exported_params, "Mesh parameter") + flat_slots = _normalize_slots(flat, "Flat attribute") + f16_slots = _normalize_slots(f16_plain, "Binary16 attribute") + if semantic not in ("param", "texcoord"): + raise ValueError(f"Unsupported mesh parameter semantic {semantic!r}") + if semantic == "texcoord": + if set(params) - {0} or flat_slots or f16_slots: + raise ValueError("TEXCOORD0 linkage supports only interpolated param0") + param_set = set(params) + if not set(flat_slots) <= param_set: + raise ValueError(f"Flat attributes {sorted(set(flat_slots) - param_set)} not exported by mesh stage") + if not set(f16_slots) <= param_set: + raise ValueError(f"Binary16 attributes {sorted(set(f16_slots) - param_set)} not exported by mesh stage") + if pixel_attrs is not None: + attrs = _normalize_slots(pixel_attrs, "Pixel attribute") + missing = sorted(set(attrs) - param_set) + if missing: + raise ValueError(f"Pixel stage reads attributes {missing} the mesh stage does not export") + else: + attrs = () + param_count = (max(params) + 1) if params else 0 + total_vectors = 1 + distance_vectors + param_count + len(flat_slots) + 2 * len(f16_slots) + if total_vectors > MAX_VERTEX_VECTORS: + raise ValueError( + f"Mesh vertex signature needs {total_vectors} vectors, exceeding D3D12 limit {MAX_VERTEX_VECTORS}" + ) + return ParamLinkage(params=params, flat=flat_slots, f16_plain=f16_slots, pixel_attrs=attrs, semantic=semantic) + + +def merge_wave_params(waves, positions): + """Merge per-wave parameter exports and require every slot to cover every exported vertex.""" + merged = {} + for wave in waves: + for slot, vertex_map in wave.params.items(): + dest = merged.setdefault(slot, {}) + for vertex, values in vertex_map.items(): + if vertex in dest: + raise ValueError("Duplicate vertex attribute" if slot == 0 else f"Duplicate vertex parameter param{slot}") + dest[vertex] = values + expected = set(positions) + for slot, vertex_map in merged.items(): + if set(vertex_map) != expected: + raise ValueError("Incomplete vertex attribute" if slot == 0 else f"Incomplete vertex parameter param{slot}") + return merged + + +def _use_texcoord(exported_params, linkage): + if linkage is not None: + if set(exported_params) != set(linkage.params): + raise ValueError("Mesh exported parameters do not match declared pixel linkage") + return linkage.semantic == "texcoord" + return not any(s > 0 for s in exported_params) + + +def hlsl_param_fields(exported_params, linkage=None): + """HLSL Vertex struct fields for the mesh shader's exported parameters.""" + if _use_texcoord(exported_params, linkage): + return "float4 attr : TEXCOORD0; " if exported_params else "" + fields = [] + if exported_params: + for p in range(max(exported_params) + 1): + fields.append(f"float4 param{p} : PARAM{p};") + if linkage is not None: + for p in linkage.flat: + fields.append(f"nointerpolation uint4 fparam{p} : FPARAM{p};") + for p in linkage.f16_plain: + fields.append(f"float4 hparam{p}_lo : HPARAML{p};") + fields.append(f"float4 hparam{p}_hi : HPARAMH{p};") + return (" ".join(fields) + " ") if fields else "" + + +def hlsl_param_writes(vertex_expr, vertex_params, exported_params, float4_fn, linkage=None): + """HLSL statements assigning exported parameter fields for one vertex.""" + if not exported_params: + return [] + if _use_texcoord(exported_params, linkage): + return [f"{vertex_expr}.attr = {float4_fn(vertex_params[0])};"] + writes = [] + flat = set(linkage.flat) if linkage is not None else set() + f16_plain = set(linkage.f16_plain) if linkage is not None else set() + for p in range(max(exported_params) + 1): + if p not in vertex_params: + writes.append(f"{vertex_expr}.param{p} = float4(0.0f, 0.0f, 0.0f, 0.0f);") + continue + expr = float4_fn(vertex_params[p]) + need_flat = p in flat + need_f16 = p in f16_plain + if need_flat or need_f16: + writes.append(f"float4 p{p} = {expr}; {vertex_expr}.param{p} = p{p};") + if need_flat: + writes.append(f"{vertex_expr}.fparam{p} = asuint(p{p});") + if need_f16: + writes.append( + f"uint4 h{p} = asuint(p{p}); " + f"{vertex_expr}.hparam{p}_lo = f16tof32(h{p}); " + f"{vertex_expr}.hparam{p}_hi = f16tof32(h{p} >> 16);" + ) + else: + writes.append(f"{vertex_expr}.param{p} = {expr};") + return writes diff --git a/tools/package-gpu-check.ps1 b/tools/package-gpu-check.ps1 index 42eef63534..53697514fc 100644 --- a/tools/package-gpu-check.ps1 +++ b/tools/package-gpu-check.ps1 @@ -18,7 +18,19 @@ try { $stage = New-Item -ItemType Directory -Force -Path "$build/package" Copy-Item -LiteralPath "$build/offscreen_check.exe", "$PSScriptRoot/gpu-check/Run-GpuCheck.ps1", "$PSScriptRoot/gpu-check/README.md", 'LICENSE' -Destination $stage Set-Content -LiteralPath "$stage/SOURCE_COMMIT.txt" -Value $revision -Encoding ascii - $files = 'offscreen_check.exe', 'Run-GpuCheck.ps1', 'README.md', 'LICENSE', 'SOURCE_COMMIT.txt' | + + # Compile the gfx2hlsl compute cases here so the package needs no Python or DXC on the user's machine. + $dxcLine = Select-String -LiteralPath "$build/CMakeCache.txt" -Pattern '^DXC_EXECUTABLE:[A-Z]+=(.+)$' | Select-Object -First 1 + if (-not $dxcLine) { throw 'DXC_EXECUTABLE is not in the CMake cache.' } + $dxc = $dxcLine.Matches[0].Groups[1].Value + $python = Join-Path $root 'out/pe-env/Scripts/python.exe' + if (-not (Test-Path -LiteralPath $python)) { throw "Missing $python. Create out/pe-env and install requirements-dev.txt before packaging." } + $cases = Join-Path $stage 'cases' + if (Test-Path -LiteralPath $cases) { Remove-Item -LiteralPath $cases -Recurse -Force } + & $python -B tools/record_gpu_cases.py $dxc $cases + if ($LASTEXITCODE -ne 0) { throw 'Recording the shader cases failed.' } + + $files = 'offscreen_check.exe', 'Run-GpuCheck.ps1', 'README.md', 'LICENSE', 'SOURCE_COMMIT.txt', 'cases' | ForEach-Object { Join-Path $stage $_ } $name = 'Xbox2Windows-GpuCheck-win-x64.zip' $zip = Join-Path $output $name @@ -36,6 +48,9 @@ try { $report -notmatch "$_ - PASS" -and $report -notmatch "(?s)### $_ - SKIP[^#]*skip: fixture requires Shader Model 6\.5" } + if ($report -notmatch 'gfx2hlsl_shaders_warp - PASS' -or $report -notmatch 'cases: ([1-9][0-9]*) pass, 0 fail, 0 skip of \1\b') { + throw 'The extracted package did not replay every recorded shader case on WARP.' + } if ($report -notmatch 'dual_uav_warp - PASS' -or $report -notmatch 'texture_mips_warp - PASS' -or $sm65Missing -or $report -notmatch 'bvh_root_roundtrip_warp - PASS' -or $report -notmatch [regex]::Escape($revision) -or diff --git a/tools/paged_resource.py b/tools/paged_resource.py index c80271e45b..4d1ee1c266 100644 --- a/tools/paged_resource.py +++ b/tools/paged_resource.py @@ -5,6 +5,12 @@ import zlib +def _require_int(value: object, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{name} must be an integer") + return value + + @dataclass(frozen=True) class Segment: offset: int # Physical byte offset in the open file @@ -12,6 +18,11 @@ class Segment: size: int # Decoded bytes in logical order codec: str + def __post_init__(self) -> None: + _require_int(self.offset, "segment.offset") + _require_int(self.stored, "segment.stored") + _require_int(self.size, "segment.size") + class PagedResource: """The caller owns the binary file and supplies segments in logical order.""" @@ -23,13 +34,18 @@ def __init__(self, stream, segments): starts = [] physical_end = logical_end = 0 for segment in self.segments: - if segment.offset < physical_end or min(segment.stored, segment.size) <= 0: + offset = _require_int(segment.offset, "segment.offset") + stored = _require_int(segment.stored, "segment.stored") + size = _require_int(segment.size, "segment.size") + if not isinstance(segment.codec, str) or not segment.codec: + raise ValueError(f"Unsupported segment codec {segment.codec!r}") + if offset < physical_end or min(stored, size) <= 0: raise ValueError("Overlapping, descending or empty segment") - physical_end = segment.offset + segment.stored - if physical_end > file_size or (segment.codec == "raw" and segment.stored != segment.size): + physical_end = offset + stored + if physical_end > file_size or (segment.codec == "raw" and stored != size): raise ValueError("Segment extent disagrees with file or raw size") starts.append(logical_end) - logical_end += segment.size + logical_end += size self.starts = tuple(starts) self.size = logical_end @@ -47,7 +63,10 @@ def _read_at(self, offset: int, size: int) -> bytes: return bytes(data) def read(self, offset, length, *, limit=64 << 20): - if offset < 0 or length < 0 or length > limit or offset + length > self.size: + offset = _require_int(offset, "offset") + length = _require_int(length, "length") + limit = _require_int(limit, "limit") + if limit < 0 or offset < 0 or length < 0 or length > limit or offset + length > self.size: raise ValueError("Logical range outside resource or read budget") index = bisect_right(self.starts, offset) - 1 result = bytearray() diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py new file mode 100644 index 0000000000..a9d0f07d32 --- /dev/null +++ b/tools/patch_manifest.py @@ -0,0 +1,225 @@ +"""Load a patch manifest and check that it is bound to the given input file. + +A manifest is TOML: + + [target] + input_sha256 = "<sha256 of the exact input file>" + + [[patch]] + id = "p001" + kind = "memory" + why = "<issue or root cause>" + remove_when = "<condition>" + rva = 0x1010 # first byte to replace + expect_sha256 = "<sha256 of the len(bytes) original bytes at rva>" + bytes = "90c3" # the replacement, lowercase hex + + [[patch]] + id = "s001" + kind = "shader" # the translation files of one shader cache key + why = "<issue or root cause>" + remove_when = "<condition>" + key = "0123456789abcdef" # the cache key, 16 lowercase hex digits + pipeline = "compute" # graphics, compute or mesh86 + revision = "x2w-startup-shader-29cs" + files = [{ ext = ".txt", file = "s001.txt", sha256 = "<sha256>" }, + { ext = ".cs.cso", file = "s001.cs.cso", sha256 = "<sha256>" }] + +The whole manifest is validated and the input's SHA-256 compared before anything is returned, so +a manifest that fails any check applies nothing. The memory and shader kinds are defined, checked +for shape only; nothing applies them yet. +""" + +import argparse +import hashlib +import json +from pathlib import Path +import re +import tomllib + +SHA256 = re.compile(r"[0-9a-f]{64}") +HEX = re.compile(r"(?:[0-9a-f]{2})+") +KEY = re.compile(r"[0-9a-f]{16}") +# Names Windows opens as a device instead of a file in the directory, alone or before an extension (Microsoft, +# "Naming Files, Paths, and Namespaces"). Matched against the part before the first dot, trailing spaces dropped. +DEVICE = re.compile(r"(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)", + re.IGNORECASE) +COMMON = {"id", "kind", "why", "remove_when"} +# Every key of a kind is required. hook and data get their tables with their stages. +KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} +# Shader patches, per pipeline: the form of the runtime's key revision (src/startup_stubs/d3d12_draw.inl and +# mesh86_cache.inl; <n> is the number each revision bump raises), the translation files the runtime reads for one +# key, and the ones without which it has no translation. The fixed rectangle geometry stage, Python compute +# source, and mesh86 pixel stage are required only for their specific pipelines or requests. +PIPELINES = { + "graphics": ("x2w-startup-shader-<n>", (".txt", ".vs.cso", ".ps.cso", ".gs.cso"), (".txt", ".vs.cso", ".ps.cso")), + "compute": ("x2w-startup-shader-<n>cs", (".txt", ".cs.cso", ".cs.hlsl"), (".txt", ".cs.cso")), + "mesh86": ("x2w-startup-mesh-86-<n>", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), +} +REVISIONS = {name: re.compile(re.escape(form).replace("<n>", "[1-9][0-9]*")) + for name, (form, _, _) in PIPELINES.items()} + + +def _keys(table, keys, where): + if not isinstance(table, dict): + raise ValueError(f"{where} must be a table") + if extra := sorted(set(table) - keys): + raise ValueError(f"{where} has unknown keys: {', '.join(extra)}") + if missing := sorted(keys - set(table)): + raise ValueError(f"{where} is missing: {', '.join(missing)}") + + +def _text(value, where): + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{where} must be a non-empty string") + return value + + +def _sha256(value, where): + if not isinstance(value, str) or not SHA256.fullmatch(value): + raise ValueError(f"{where} must be 64 lowercase hex digits") + return value + + +def _file_name(value, where): + """A bare file name, for a later consumer to resolve in the manifest's directory. + + That consumer is the runtime, which runs on Windows, so a name that Windows would not resolve to a file of that + name in the directory is refused too: one it cannot hold, one whose trailing dot or space it drops, a device. + """ + name = _text(value, where) + if any(c in name for c in "/\\:") or name in (".", ".."): + raise ValueError(f"{where} {name!r} must be a bare file name, without a directory, drive or '..'") + if any(c in '<>"|?*' for c in name) or any(ord(c) < 32 for c in name): + raise ValueError(f"{where} {name!r} has a character a Windows file name cannot hold") + if name.endswith((".", " ")): + raise ValueError(f"{where} {name!r} ends in a dot or a space, which Windows drops") + if DEVICE.fullmatch(name.split(".", 1)[0].rstrip(" ")): + raise ValueError(f"{where} {name!r} is a Windows device name") + return name + + +def _shader(entry, where): + """The key, pipeline, revision and files of a shader patch, checked for shape only.""" + key = entry["key"] + if not isinstance(key, str) or not KEY.fullmatch(key): + raise ValueError(f"{where} key must be 16 lowercase hex digits") + pipeline = entry["pipeline"] + if not isinstance(pipeline, str) or pipeline not in PIPELINES: + raise ValueError(f"{where} pipeline must be one of: {', '.join(PIPELINES)}") + form, extensions, required = PIPELINES[pipeline] + revision = entry["revision"] + if not isinstance(revision, str) or not REVISIONS[pipeline].fullmatch(revision): + raise ValueError(f"{where} revision {revision!r} is not a {pipeline} key revision ({form})") + if not isinstance(entry["files"], list) or not entry["files"]: + raise ValueError(f"{where} files must be a non-empty array of tables") + files = {} + for index, item in enumerate(entry["files"]): + at = f"{where} files[{index}]" + _keys(item, {"ext", "file", "sha256"}, at) + ext = item["ext"] + if not isinstance(ext, str) or ext not in extensions: + raise ValueError(f"{at} ext {ext!r} is not a {pipeline} translation file ({', '.join(extensions)})") + if ext in files: + raise ValueError(f"{where} lists {ext} twice") + files[ext] = {"ext": ext, "file": _file_name(item["file"], f"{at} file"), + "sha256": _sha256(item["sha256"], f"{at} sha256")} + if missing := [ext for ext in required if ext not in files]: + raise ValueError(f"{where} {pipeline} override is missing: {', '.join(missing)}") + return {"key": key, "pipeline": pipeline, "revision": revision, "files": list(files.values())} + + +def parse(text): + """Return (input_sha256, patches) from manifest text, or raise ValueError.""" + try: + data = tomllib.loads(text) + except RecursionError: # tomllib recurses once per nested array or inline table + raise ValueError("manifest is nested too deeply to parse") from None + _keys(data, {"target", "patch"}, "manifest") + _keys(data["target"], {"input_sha256"}, "[target]") + target = _sha256(data["target"]["input_sha256"], "input_sha256") + if not isinstance(data["patch"], list) or not data["patch"]: + raise ValueError("manifest needs at least one [[patch]]") + patches, spans = [], [] + for index, entry in enumerate(data["patch"]): + where = f"[[patch]] {index}" + kind = entry.get("kind") if isinstance(entry, dict) else None + if not isinstance(kind, str) or kind not in KINDS: # a list or table kind is unhashable + raise ValueError(f"{where}: kind {kind!r} is not supported") + _keys(entry, COMMON | KINDS[kind], where) + pid = _text(entry["id"], f"{where} id") + if any(p["id"] == pid for p in patches): + raise ValueError(f"duplicate patch id: {pid}") + where = f"patch {pid}" + if kind == "shader": + patch = {"id": pid, "kind": kind, "why": _text(entry["why"], f"{where} why"), + "remove_when": _text(entry["remove_when"], f"{where} remove_when"), **_shader(entry, where)} + if other := next((p["id"] for p in patches if p.get("key") == patch["key"]), None): + raise ValueError(f"patches {other} and {pid} override the same key {patch['key']}") + patches.append(patch) + continue + rva = entry["rva"] + if type(rva) is not int or not 0 <= rva < 1 << 32: + raise ValueError(f"{where} rva must be an integer in [0, 2^32)") + if not isinstance(entry["bytes"], str) or not HEX.fullmatch(entry["bytes"]): + raise ValueError(f"{where} bytes must be a non-empty, even number of lowercase hex digits") + replacement = bytes.fromhex(entry["bytes"]) + end = rva + len(replacement) + if end > 1 << 32: + raise ValueError(f"{where} span [{rva:#x}, {end:#x}) does not fit in 32-bit RVAs") + spans.append((rva, end, pid)) + patches.append({ + "id": pid, + "kind": kind, + "why": _text(entry["why"], f"{where} why"), + "remove_when": _text(entry["remove_when"], f"{where} remove_when"), + "rva": rva, + "expect_sha256": _sha256(entry["expect_sha256"], f"{where} expect_sha256"), + "bytes": replacement, + }) + spans.sort() + for (_, end, first), (start, _, second) in zip(spans, spans[1:]): + if start < end: + raise ValueError(f"patches {first} and {second} overlap") + return target, patches + + +def load(manifest_path, input_path): + """Validate the manifest, then refuse it unless input_path is its target.""" + raw = Path(manifest_path).read_bytes() + target, patches = parse(raw.decode("utf-8")) + with open(input_path, "rb") as handle: + digest = hashlib.file_digest(handle, "sha256").hexdigest() + return _bound(raw, target, patches, digest) + + +def load_data(manifest_path, data): + """load() for an input the caller has already read: data is hashed, so the bytes that pass the gate are + the bytes the caller goes on to use, even if the file on disk changes in between.""" + raw = Path(manifest_path).read_bytes() + target, patches = parse(raw.decode("utf-8")) + return _bound(raw, target, patches, hashlib.sha256(data).hexdigest()) + + +def _bound(raw, target, patches, digest): + if digest != target: + raise ValueError(f"manifest is for another input: manifest input_sha256 {target}, input sha256 {digest}") + return {"manifest_sha256": hashlib.sha256(raw).hexdigest(), "input_sha256": digest, "patches": patches} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("manifest", type=Path) + parser.add_argument("input", type=Path) + args = parser.parse_args(argv) + try: + plan = load(args.manifest, args.input) + except (ValueError, OSError) as error: # TOMLDecodeError and UnicodeDecodeError are ValueErrors + parser.exit(1, f"patch manifest: {error}\n") + print(json.dumps({"manifest_sha256": plan["manifest_sha256"], "input_sha256": plan["input_sha256"], + "patch_ids": [p["id"] for p in plan["patches"]]}, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/pe_package_preflight.py b/tools/pe_package_preflight.py index 4af2e57a5b..89c3dd4626 100644 --- a/tools/pe_package_preflight.py +++ b/tools/pe_package_preflight.py @@ -9,6 +9,7 @@ import heapq import json from pathlib import Path +import struct import sys import tempfile @@ -35,7 +36,7 @@ def _relative(root, path): def _paths(root): result = {} total_bytes = 0 - for path in root.rglob("*"): + for path in sorted(root.rglob("*"), key=lambda p: (p.as_posix().casefold(), p.as_posix())): if path.suffix.casefold() not in (".dll", ".exe"): continue if path.is_symlink(): @@ -160,7 +161,25 @@ def packaged(module): ignored_images=sorted(set(images) - set(reached))) +def _validate_entry(entry): + if not isinstance(entry, str) or not entry.strip(): + raise ValueError("Entry must be a non-empty relative path to an .exe inside the package") + + +def _validate_output(output, root): + if output.is_symlink(): + raise ValueError(f"Output path must not be a symlink: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"Output parent is not a directory: {parent}") + if output.resolve().is_relative_to(root): + raise ValueError("Write reports outside the inspected package") + if output.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {output}") + + def inspect(root, entry): + _validate_entry(entry) root = Path(root).resolve(strict=True) if not root.is_dir(): raise ValueError("Package root must be a directory") @@ -183,11 +202,14 @@ def main(argv=None): args = parser.parse_args(argv) try: root = args.package.resolve(strict=True) - if args.output and args.output.resolve().is_relative_to(root): - raise ValueError("Write reports outside the inspected package") + if not root.is_dir(): + raise ValueError("Package root must be a directory") + _validate_entry(args.entry) + if args.output is not None: + _validate_output(args.output, root) report = inspect(root, args.entry) output = json.dumps(report, indent=2, sort_keys=True, ensure_ascii=True) + "\n" - if args.output: + if args.output is not None: args.output.parent.mkdir(parents=True, exist_ok=True) # Replace the directory entry instead of writing through a possible hard link. with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: @@ -196,7 +218,7 @@ def main(argv=None): report_path.replace(args.output) else: print(output, end="") - except (OSError, ValueError, KeyError, pefile.PEFormatError) as exc: + except (OSError, ValueError, KeyError, struct.error, pefile.PEFormatError) as exc: parser.exit(1, f"pe_package_preflight: {exc}\n") return 0 diff --git a/tools/pe_run_package.py b/tools/pe_run_package.py index 394846cce5..58f493e491 100644 --- a/tools/pe_run_package.py +++ b/tools/pe_run_package.py @@ -80,6 +80,32 @@ def prototype(lib, name, args, result): return function +SEM_FAILCRITICALERRORS = 0x0001 + + +def quiet_loader(kernel, load): + """LoadLibraryExW with SEM_FAILCRITICALERRORS set on the calling thread for the call only. + + A provider that is not a loadable image (empty, truncated or not a PE) raises a critical error + inside the loader. Without the flag Windows shows a modal "Bad Image" dialog and the load blocks + until someone closes it; with it the load just fails, and the provider's symbols are reported + missing. The thread's previous mode is restored, so the guest runs under the host's setting. + """ + get_mode = prototype(kernel, "GetThreadErrorMode", [], W.DWORD) + set_mode = prototype(kernel, "SetThreadErrorMode", [W.DWORD, C.POINTER(W.DWORD)], W.BOOL) + + def call(path, flags): + previous = W.DWORD() + changed = set_mode(get_mode() | SEM_FAILCRITICALERRORS, C.byref(previous)) + try: + return load(path, None, flags) + finally: + if changed: + set_mode(previous.value, None) + + return call + + def trap_key(name): """Parse a --trap-callable DLL!SYMBOL (or DLL!#ORDINAL) into an import key.""" dll, sep, symbol = name.partition("!") @@ -138,7 +164,7 @@ def run(root, report, mapper, shims, system, *, preflight_only=False, pin_shims= order, routes = plan(report) callback = C.WINFUNCTYPE(C.c_void_p, C.c_char_p, C.c_char_p, C.c_uint32) kernel = C.WinDLL("kernel32", use_last_error=True) - load = prototype(kernel, "LoadLibraryExW", [W.LPCWSTR, W.HANDLE, W.DWORD], W.HMODULE) + load = quiet_loader(kernel, prototype(kernel, "LoadLibraryExW", [W.LPCWSTR, W.HANDLE, W.DWORD], W.HMODULE)) release_host = prototype(kernel, "FreeLibrary", [W.HMODULE], W.BOOL) find = prototype(kernel, "GetProcAddress", [W.HMODULE, C.c_void_p], C.c_void_p) pin_module = prototype(kernel, "GetModuleHandleExW", [W.DWORD, C.c_void_p, C.POINTER(W.HMODULE)], W.BOOL) @@ -163,8 +189,8 @@ def run(root, report, mapper, shims, system, *, preflight_only=False, pin_shims= missing_keys[key].add(image) continue if dll not in modules: - module = (load(str(shims[dll]), None, 0x900) if dll in shims else - load(dll, None, 0x800) if dll in system else None) + module = (load(str(shims[dll]), 0x900) if dll in shims else + load(dll, 0x800) if dll in system else None) modules[dll] = module if module: stack.callback(release_host, module) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 20d01a27e9..ff1a546b0b 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -13,6 +13,7 @@ import zlib from resource_inventory import parts +from shader_minmax import FLOAT_MINMAX MESH_WAVE64 = b"+wavefrontsize64,-wavefrontsize32" @@ -78,7 +79,28 @@ def _bounded_code(image, start): return image[start:end] -def _check_two_exits(code, llvm, *, cpu, features, mesh=False): +def _calculated_early_out(code, instructions): + """Cross-check the decoded extent and instruction inventory before accepting a calculated continuation.""" + if not any(line.startswith("s_getpc_b64 ") for line in instructions.values()): + return None + # gfx2hlsl imports pixel_aot symbols lazily too. + from startup import gfx2hlsl as G + ins = G.decode(code) + if [(off, name) for off, _n, name, _asm in ins] != [(off, line.split()[0]) for off, line in instructions.items()]: + raise ValueError("Calculated early-out: LLVM and the repository decoder disagree on the instruction inventory") + if ins[-1][0] + ins[-1][1] != len(code): + raise ValueError("Calculated early-out: the decoded instructions do not consume the bounded span") + try: + calculated = G.calculated_pc_proof(ins, None) + profile = G.terminal_continuation_proof(ins, calculated) + except G.Unsupported as reason: + raise ValueError(str(reason)) from None + if profile is None: + raise ValueError("Calculated early-out: no proven transfer onto a terminating continuation") + return profile + + +def _check_two_exits(code, llvm, *, cpu, features, mesh=False, early_out=False): """Both decoded exits must be reachable from the single entry.""" instructions = dict(disassemble(code, llvm, offsets=True, cpu=cpu, features=features)) exits = [pc for pc, line in instructions.items() if line == "s_endpgm"] @@ -89,6 +111,7 @@ def _check_two_exits(code, llvm, *, cpu, features, mesh=False): mesh_alloc = "s_sendmsg sendmsg(MSG_GS_ALLOC_REQ)" if mesh and mesh_alloc not in instructions.values(): raise ValueError("Unverified multi-exit program: missing mesh allocation") + early_out = _calculated_early_out(code, instructions) if early_out and not mesh else None # An aligned word can be a literal or the second half of an instruction. # Follow branches only from decoded PCs and reject unresolved transfers. pcs = list(instructions) @@ -111,17 +134,22 @@ def _check_two_exits(code, llvm, *, cpu, features, mesh=False): pending.append(target) if op == "s_branch": continue - elif not ((mesh and instructions[pc] in ("s_barrier", mesh_alloc)) - or op.startswith(("v_", "image_", "buffer_", "tbuffer_", "ds_", "flat_", "global_", - "scratch_", "exp", "s_load_", "s_buffer_load_", "s_cmp", "s_bitcmp", - "s_mov_", "s_and", "s_or_", "s_xor_", "s_not_", "s_lsh", "s_ash", - "s_add", "s_sub", "s_mul", "s_min_", "s_max_", "s_cselect", "s_bfe", - "s_bfm", "s_brev", "s_ff", "s_bcnt", "s_wqm", "s_quadmask")) - or op in ("s_nop", "s_version", "s_inst_prefetch", "s_waitcnt", "s_clause", "s_delay_alu", - "s_setprio", "s_sleep", "s_movk_i32", "s_cmovk_i32", "s_mulk_i32", - "s_flbit_i32_b32", "s_abs_i32", "s_cmov_b32", "s_bitset0_b32", "s_bitset1_b32", - "s_bitreplicate_b64_b32", "s_bitset0_b64", "s_bitset1_b64", - "s_setreg_imm32_b32", "s_setreg_b32", "s_getreg_b32")): + elif early_out is not None and pc == early_out[0]: + targets.add(early_out[1]) + pending.append(early_out[1]) + continue + elif not (early_out is not None and pc in early_out[2]) and not ( + (mesh and instructions[pc] in ("s_barrier", mesh_alloc)) + or op.startswith(("v_", "image_", "buffer_", "tbuffer_", "ds_", "flat_", "global_", + "scratch_", "exp", "s_load_", "s_buffer_load_", "s_cmp", "s_bitcmp", + "s_mov_", "s_and", "s_or_", "s_xor_", "s_not_", "s_lsh", "s_ash", + "s_add", "s_sub", "s_mul", "s_min_", "s_max_", "s_cselect", "s_bfe", + "s_bfm", "s_brev", "s_ff", "s_bcnt", "s_wqm", "s_quadmask")) + or op in ("s_nop", "s_version", "s_inst_prefetch", "s_waitcnt", "s_clause", "s_delay_alu", + "s_setprio", "s_sleep", "s_movk_i32", "s_cmovk_i32", "s_mulk_i32", + "s_flbit_i32_b32", "s_abs_i32", "s_cmov_b32", "s_bitset0_b32", "s_bitset1_b32", + "s_bitreplicate_b64_b32", "s_bitset0_b64", "s_bitset1_b64", + "s_setreg_imm32_b32", "s_setreg_b32", "s_getreg_b32")): raise ValueError(f"Unverified multi-exit control flow: {op}") pending.append(following[pc]) # A direct branch may skip alignment NOPs. Keep them in the original span. @@ -188,8 +216,9 @@ def container_code(program, *, stage, llvm=None, cpu=b"gfx1013", features=b""): if markers == 1: return code mesh = stage == 13 and cpu == b"gfx1013" and features == MESH_WAVE64 + pixel = stage == 0 and cpu == b"gfx1013" and not features if (stage in (0, 5) or mesh) and markers == 2 and llvm is not None: - _check_two_exits(code, llvm, cpu=cpu, features=features, mesh=mesh) + _check_two_exits(code, llvm, cpu=cpu, features=features, mesh=mesh, early_out=pixel) return code raise ValueError("Unverified multi-exit program") # Older fixtures lack the section extent; preserve their unique-marker rule. @@ -315,6 +344,15 @@ def sample_offset_arg(reg, vector, sample_dest, known_ssa_bits): return f", int2({x}, {y})" +def check_sample_clamp_sampler(words, mips): + # Normalized clamp-to-last-texel in X/Y, point filters, zero sampler + # bias and minimum LOD. The sampler must leave the whole view accessible. + w0, w1, w2, w3 = words + if (w0 != 0x12 or w1 & ~0x00fff000 or (w1 >> 12) < ((mips - 1) << 8) + or w2 != 0x04000000 or w3 != 0): + raise ValueError("Sample clamp requires a normalized clamp sampler with point XY/mip filters and no LOD modifiers") + + # Word 2 bits 28-30 (value >> 28): MIP_POINT_PRECLAMP, ANISO_OVERRIDE, BLEND_ZERO_PRT. At an explicit level zero # with anisotropy refused and no partially resident texture, none of them changes the result. LEVEL_ZERO_IGNORED_W2 = 0x7 @@ -445,7 +483,9 @@ def comparison_resources(state): // The NaN test is on the encoding, because some desktop compilers fold float NaN tests. float med3_32(float a, float b, float c) { uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu); - return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c)); + return top > 0x7f800000u + ? minmax_zero32(minmax_zero32(a, b, false), c, false) + : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true); } // v_fract_f32: x - floor(x) clamped to 0x3f7fffff, so a tiny negative input cannot round up to 1.0. // D3D frac has no clamp and differs between adapters. NaN fails the comparison and propagates. @@ -525,12 +565,6 @@ def comparison_resources(state): float cos32(float value) { return cos(turns(value) * 6.28318548f); } -// Finite binary32 to binary16, round toward zero, then widen for the float target. -float export16(float value) { - uint h = f32tof16(value); - if (abs(f16tof32(h)) > abs(value)) h--; - return f16tof32(h); -} // v_cvt_f32_f16: widen the binary16 in the low half of a word, built from its encoding so that // desktop denormal handling cannot change it. Subnormal halves stay exact as m * 2^-24; NaN payloads widen. float widen16(uint word) { @@ -570,6 +604,14 @@ def comparison_resources(state): uint rounded = (full + 0xfffu + ((full >> 13) & 1u)) >> 13; return sign | min(((exponent - 113u) << 10) + rounded, 0x7c00u); } +// Finite binary32 to binary16, round toward zero, then widen for the float target. Built on the integer +// helpers: a driver may fold f16tof32(f32tof16(x)) into x and lose the correction. The round-to-nearest-even +// result is one step too large exactly when it exceeds the input in magnitude, so step it back toward zero. +float export16(float value) { + uint h = narrow16(value); + if (abs(widen16(h)) > abs(value)) h--; + return widen16(h); +} """ @@ -754,7 +796,7 @@ def vgpr_span(token, count): "rndne": (1, "round({0})"), # HLSL round is DXIL Round_ne: ties to even "sin": (1, "sin32({0})"), "cos": (1, "cos32({0})"), "add": (2, "({0} + {1})"), "mul": (2, "({0} * {1})"), - "max": (2, "max({0}, {1})"), "min": (2, "min({0}, {1})"), "sub": (2, "({0} - {1})"), + "max": (2, "minmax_zero32({0}, {1}, true)"), "min": (2, "minmax_zero32({0}, {1}, false)"), "sub": (2, "({0} - {1})"), "subrev": (2, "({1} - {0})"), "mul_legacy": (2, "(({0} == 0 || {1} == 0) ? 0.0f : {0} * {1})"), # Legacy multiply, then an unfused add: 0 * x is 0 even for an infinite or NaN x. @@ -764,7 +806,8 @@ def vgpr_span(token, count): "fma": (3, "mad({0}, {1}, {2})"), "fmac": (3, "mad({0}, {1}, {2})"), "mad": (3, "mad32({0}, {1}, {2})"), "mac": (3, "mad32({0}, {1}, {2})"), # Each result is one of the operands, so finite inputs need no rounding. - "min3": (3, "min(min({0}, {1}), {2})"), "max3": (3, "max(max({0}, {1}), {2})"), + "min3": (3, "minmax_zero32(minmax_zero32({0}, {1}, false), {2}, false)"), + "max3": (3, "minmax_zero32(minmax_zero32({0}, {1}, true), {2}, true)"), "med3": (3, "med3_32({0}, {1}, {2})"), } # LLVM 15 sets HasExtDPP = 0 for v_mac_legacy_f32, and fma, mad, mad_legacy, min3, max3 and med3 are VOP3-only, so @@ -1070,6 +1113,46 @@ def check_vopc_e32_dst(enc, dst): " return asuint(int(exp) - 14) & 0xffffu;\n" "}" ), + "cvt_norm_i16_f16": ( + "uint cvt_norm_i16_f16(uint bits) {\n" + " uint h = bits & 0xffffu;\n" + " uint sign = h & 0x8000u;\n" + " uint mag = h & 0x7fffu;\n" + " if (mag == 0u) return 0u;\n" + " uint q;\n" + " if (mag >= 0x3c00u) {\n" + " q = 32767u;\n" + " } else {\n" + " uint exp = mag >> 10u;\n" + " uint mant = exp == 0u ? mag : (0x400u | (mag & 0x3ffu));\n" + " uint shift = exp == 0u ? 24u : (25u - exp);\n" + " uint prod = mant * 32767u;\n" + " q = prod >> shift;\n" + " uint mid = 1u << (shift - 1u);\n" + " uint rem = prod & ((1u << shift) - 1u);\n" + " if (rem > mid || (rem == mid && (q & 1u) != 0u)) q += 1u;\n" + " }\n" + " return sign != 0u ? ((0u - q) & 0xffffu) : q;\n" + "}" + ), + "cvt_norm_u16_f16": ( + "uint cvt_norm_u16_f16(uint bits) {\n" + " uint h = bits & 0xffffu;\n" + " uint sign = h & 0x8000u;\n" + " uint mag = h & 0x7fffu;\n" + " if (sign != 0u || mag == 0u) return 0u;\n" + " if (mag >= 0x3c00u) return 0xffffu;\n" + " uint exp = mag >> 10u;\n" + " uint mant = exp == 0u ? mag : (0x400u | (mag & 0x3ffu));\n" + " uint shift = exp == 0u ? 24u : (25u - exp);\n" + " uint prod = mant * 65535u;\n" + " uint q = prod >> shift;\n" + " uint mid = 1u << (shift - 1u);\n" + " uint rem = prod & ((1u << shift) - 1u);\n" + " if (rem > mid || (rem == mid && (q & 1u) != 0u)) q += 1u;\n" + " return q;\n" + "}" + ), "dpp_dot4c_i32_i8": ( "uint dpp_dot4c_i32_i8(uint a, uint b, uint acc) {\n" " int s0 = (asint(a << 24) >> 24) * (asint(b << 24) >> 24);\n" @@ -1237,14 +1320,9 @@ def check_vopc_e32_dst(enc, dst): " return (res_sign << 15u) | sig;\n" "}" ), - "min16_num": ( - "float min16_num(float a, float b) {\n" - " return isnan(a) ? b : (isnan(b) ? a : min(a, b));\n" - "}" - ), - "max16_num": ( - "float max16_num(float a, float b) {\n" - " return isnan(a) ? b : (isnan(b) ? a : max(a, b));\n" + "minmax16_num": ( + "float minmax16_num(float a, float b, bool maximum) {\n" + " return isnan(a) ? b : (isnan(b) ? a : minmax_zero32(a, b, maximum));\n" "}" ), "dot_u64_add": ( @@ -1467,8 +1545,8 @@ def check_vopc_e32_dst(enc, dst): VOP3P_F16 = { "add": (2, "({0} + {1})"), "mul": (2, "({0} * {1})"), - "min": (2, "min16_num({0}, {1})"), - "max": (2, "max16_num({0}, {1})"), + "min": (2, "minmax16_num({0}, {1}, false)"), + "max": (2, "minmax16_num({0}, {1}, true)"), "fma": (3, "mad({0}, {1}, {2})"), } INLINE_F16 = { @@ -1927,6 +2005,50 @@ def f16_frexp_exp_result(bits): return (exp - 14) & 0xffff +def f16_cvt_norm_result(signed, bits): + """Exact low 16 bits of v_cvt_norm_i16_f16 or v_cvt_norm_u16_f16 on a finite binary16 operand. + + Computes round_rne(clamp(x, -1, 1) * 32767) for signed and round_rne(clamp(x, 0, 1) * 65535) for + unsigned in exact integer arithmetic (avoiding binary32 double-rounding on 0x3801..0x3804 / + 0xb801..0xb802 and preserving subnormal inputs under -denorm ftz). + """ + h = bits & 0xffff + if ((h >> 10) & 0x1f) == 0x1f: + raise ValueError(f"binary16 operand is not finite: {bits:#06x}") + sign = h & 0x8000 + mag = h & 0x7fff + if not signed: + if sign or mag == 0: + return 0 + if mag >= 0x3c00: + return 0xffff + exp = mag >> 10 + mant = mag if exp == 0 else (0x400 | (mag & 0x3ff)) + shift = 24 if exp == 0 else (25 - exp) + prod = mant * 65535 + q = prod >> shift + mid = 1 << (shift - 1) + rem = prod & ((1 << shift) - 1) + if rem > mid or (rem == mid and (q & 1)): + q += 1 + return q + if mag == 0: + return 0 + if mag >= 0x3c00: + q = 32767 + else: + exp = mag >> 10 + mant = mag if exp == 0 else (0x400 | (mag & 0x3ff)) + shift = 24 if exp == 0 else (25 - exp) + prod = mant * 32767 + q = prod >> shift + mid = 1 << (shift - 1) + rem = prod & ((1 << shift) - 1) + if rem > mid or (rem == mid and (q & 1)): + q += 1 + return ((-q) & 0xffff) if sign else q + + def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bits): """Return (HLSL uint word expression, 32-bit packed bits) for one v_pk_fmac_f16 source operand. @@ -3536,10 +3658,12 @@ def discard_dead_integer_temporaries(lines, candidates): def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor=None, *, texture_offset=0, second_texture_offset=None, integer_export=False, texcoord_components=2, extra_constants=(), title_ranges=None, flat_global_only=False, return_write_mask=False, wave_size=None, half_denorm=None, - pointer_constants=(), cpu="gfx1013", gather_mips=None): + pointer_constants=(), cpu="gfx1013", gather_mips=None, sample_clamp_mips=None): """Track descriptor provenance, interpolation and packed or uncompressed exports. texture_offset is the aligned byte offset of t0 in the texture descriptor table. + sample_clamp_mips opts into the experimental minimum-LOD interpretation of ordinary _cl + samples, with the declared number of visible mips in matching gfx1030 and desktop views. gather_mips declares the number of visible mips in matching gfx1030 and desktop 2D views. For comparison gather the selected red texel values and the reference must be in [0, 1]. Gather coordinates must map to the same half-texel lattice on both views (see experiments.md). @@ -3574,6 +3698,10 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= if (cpu != "gfx1030" or sampler is None or second_texture_offset is not None or integer_export or type(gather_mips) is not int or not 1 <= gather_mips <= 16): raise ValueError("Gather requires a gfx1030 float pixel profile with one texture and 1 to 16 visible mips") + if sample_clamp_mips is not None: + if (cpu != "gfx1030" or sampler is None or second_texture_offset is not None or integer_export + or type(sample_clamp_mips) is not int or not 1 <= sample_clamp_mips <= 16): + raise ValueError("Sample clamp requires a gfx1030 float pixel profile with one texture and 1 to 16 visible mips") if title_ranges is not None and (isinstance(title_ranges, bool) or not isinstance(title_ranges, int) or not 1 <= title_ranges <= 0xffffffff): raise ValueError("Invalid title range count") @@ -3680,6 +3808,7 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= mask = "entry" wqm_width = None samples = 0 + sample_clamp_used = False sampled_textures = set() sample_kind = None # "plain", "comparison" or "gather" resource interpretation vector_loads = 0 # image samples and title loads issued, in vmcnt order @@ -5016,7 +5145,7 @@ def match(pattern): vector[dst] = f"uv.{component}" if mask == "quad" else ("entry_uv", component) else: raise ValueError("Unpaired interpolation") - elif m := match(r"(image_sample(?:(?:_lz|_l|_b)?(?:_o)?|_c?d(?:_o)?(?:_g16)?)) (?:v\[(\d+):(\d+)\]|v(\d+)), " + elif m := match(r"(image_sample(?:(?:_lz|_l|_b|_cl|_b_cl)?(?:_o)?|_c?d(?:_o)?(?:_g16)?)) (?:v\[(\d+):(\d+)\]|v(\d+)), " r"v\[(\d+):(\d+)\], s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x([1-9a-f]) dim:SQ_RSRC_IMG_2D"): op, dst_first, dst_last, dst_single, *rest, dmask_hex = m.groups() dmask = int(dmask_hex, 16) @@ -5030,11 +5159,15 @@ def match(pattern): gradient = coarse or base_op == "image_sample_d" if coarse and cpu != "gfx1030": raise ValueError("Coarse-gradient sampling requires gfx1030") + has_clamp = base_op.endswith("_cl") + has_bias = base_op in ("image_sample_b", "image_sample_b_cl") + if has_clamp and sample_clamp_mips is None: + raise ValueError(f"{op} requires --sample-clamp-mips") if gradient: # LLVM disassembly lists only the live address operands. coord_width = (4 if g16 else 6) + has_offset else: - coord_width = (3 if base_op in ("image_sample_l", "image_sample_b") else 2) + has_offset + coord_width = 2 + (base_op == "image_sample_l" or has_bias) + has_offset + has_clamp channels = ["xyzw"[bit] for bit in range(4) if (dmask >> bit) & 1] if len(channels) == 1: if dst_single is None: @@ -5083,6 +5216,24 @@ def sample_coord(reg): return value return fp_operand(reg, scalar, vector, pending, sample_dest) + def known_sample_float(reg): + if reg in sample_dest: + raise ValueError("Sample LOD operand used before vmcnt wait") + raw = known_ssa_bits.get(vector[reg]) + return struct.unpack("<f", struct.pack("<I", raw))[0] if raw is not None else None + + clamp_arg = "" + if has_clamp: + check_sample_clamp_sampler(sampler, sample_clamp_mips) + # AMD tables 43/44 and LLVM place the clamp after the UV pair. + # The lower-bound interpretation here follows Mesa MinLod lowering. + floor = known_sample_float(coord_regs.pop()) + if floor is None or not 0 <= floor <= sample_clamp_mips - 1: + raise ValueError("Sample clamp requires a known minimum LOD inside the view") + offset_arg = offset_arg or ", int2(0, 0)" + clamp_arg = f", {floor!r}f" + sample_clamp_used = True + if gradient: u, v = [sample_coord(reg) for reg in coord_regs[-2:]] if coarse: @@ -5120,11 +5271,17 @@ def sample_coord(reg): if any(value not in quad_values for value in uv): raise ValueError("Unsupported texture coordinate") coordinate = f"float2({', '.join(uv)})" - if base_op == "image_sample_b": - bias = sample_coord(coord_regs[0]) - call = f"SampleBias(samp, {coordinate}, {bias}{offset_arg})" + if has_bias: + if has_clamp: + known_bias = known_sample_float(coord_regs[0]) + if known_bias is None or not -16 <= known_bias <= 15.99: + raise ValueError("Sample clamp requires a known LOD bias in the HLSL range") + bias = f"{known_bias!r}f" + else: + bias = sample_coord(coord_regs[0]) + call = f"SampleBias(samp, {coordinate}, {bias}{offset_arg}{clamp_arg})" else: - call = f"Sample(samp, {coordinate}{offset_arg})" + call = f"Sample(samp, {coordinate}{offset_arg}{clamp_arg})" lines.append(f" float4 sample{i} = {texture}.{call};") samples += 1 sampled_textures.add(texture) @@ -5199,17 +5356,26 @@ def sample_coord(reg): for dst, value in zip(dests, values): vector[dst] = value sample_dest[dst] = vector_loads - elif m := match(r"(image_sample_c(?:_lz)?(?:_o)?) (v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " + elif m := match(r"(image_sample_c(?:(?:_lz|_l|_b)?(?:_o)?|_d(?:_o)?(?:_g16)?)) " + r"(v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " r"s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x1 dim:SQ_RSRC_IMG_2D"): - # The optional packed offset precedes the reference, followed by the UV pair. + # RDNA 2 orders the address as offset, bias, reference, gradients, UV, explicit LOD. + # Only the reference and UV pair are present in every comparison form. op, dst, first, last, *nsa = m.groups()[:7] image = registers(*m.groups()[7:9], 8) state = registers(*m.groups()[9:11], 4) - has_offset = op.endswith("_o") - explicit_zero = op.removesuffix("_o") == "image_sample_c_lz" + g16 = op.endswith("_g16") + stem = op.removesuffix("_g16") + has_offset = stem.endswith("_o") + base_op = stem.removesuffix("_o") + gradient_words = (2 if g16 else 4) if base_op == "image_sample_c_d" else 0 + explicit_lod = base_op in ("image_sample_c_lz", "image_sample_c_l") + implicit_derivatives = not (explicit_lod or gradient_words) + has_level_operand = base_op in ("image_sample_c_l", "image_sample_c_b") if first is None and op != "image_sample_c_lz": raise ValueError("Comparison sample requires a contiguous address") - address = ([f"v{n}" for n in registers(first, last, 3 + has_offset)] + width = 3 + has_offset + has_level_operand + gradient_words + address = ([f"v{n}" for n in registers(first, last, width)] if first is not None else nsa) if any(int(reg[1:]) > 255 for reg in (dst, *address)): raise ValueError("Comparison sample VGPR out of range") @@ -5222,10 +5388,48 @@ def sample_coord(reg): or descriptor != [("tex", j) for j in range(8)] or [scalar.get(f"s{n}") for n in state] != list(sampler)): raise ValueError("Unsupported image or sampler binding") - if not explicit_zero and sampler[1] & 0xfff000: + if has_level_operand or gradient_words: + label = "Comparison gradient sampling" if gradient_words else "Comparison LOD/bias" + if sampler[1] & 0xfff000 != 0x100000 or (sampler[2] >> 26) & 3 != 1: + raise ValueError(f"{label} requires MAX_LOD 1 and point mip filtering") + if (sampler[2] >> 20) & 0xf: + raise ValueError(f"{label} requires point XY filtering") + elif implicit_derivatives and sampler[1] & 0xfff000: raise ValueError("Implicit comparison sampling requires MAX_LOD 0") offset_arg = sample_offset_arg(address.pop(0), vector, sample_dest, known_ssa_bits) if has_offset else "" - if not explicit_zero and any(vector.get(reg) not in quad_values for reg in address[1:]): + extra_args = "" + if has_level_operand: + operand = address.pop() if explicit_lod else address.pop(0) + if operand in sample_dest: + raise ValueError("Comparison LOD operand used before vmcnt wait") + value = vector.get(operand) + if not isinstance(value, str) or known_ssa_bits.get(value) not in (0, 0x3f800000): + raise ValueError("Comparison LOD or bias must be statically 0 or 1") + extra_args = f", {value}" + if gradient_words: + derivatives = address[1:1 + gradient_words] + del address[1:1 + gradient_words] + slope_components = [] + for reg in derivatives: + if reg in sample_dest: + raise ValueError("Comparison gradient used before vmcnt wait") + value = vector.get(reg) + bits = known_ssa_bits.get(value) if isinstance(value, str) else None + if bits is None: + raise ValueError("Comparison gradient must be statically known") + # Require normal values or zero in the input precision. + magnitudes = ((bits & 0x7fff, (bits >> 16) & 0x7fff) if g16 else (bits & 0x7fffffff,)) + lower, upper = (0x0400, 0x7c00) if g16 else (0x00800000, 0x7f800000) + if any(component and not lower <= component < upper for component in magnitudes): + raise ValueError("Comparison gradient components must be normal or zero") + if g16: + word = f"asuint({value})" + slope_components.extend((f"widen16({word})", f"widen16({word} >> 16)")) + else: + slope_components.append(value) + dudx, dvdx, dudy, dvdy = slope_components + extra_args = f", float2({dudx}, {dvdx}), float2({dudy}, {dvdy})" + if implicit_derivatives and any(vector.get(reg) not in quad_values for reg in address[1:]): raise ValueError("Implicit comparison sampling requires coordinates with quad provenance") if not xy_coordinates([vector.get(reg) for reg in address[1:]], quad_values): if attribute_scales: @@ -5242,8 +5446,11 @@ def sample_coord(reg): if not isinstance(value, str) or not (value in quad_values or value.startswith(("sample", "alu", "params"))): raise ValueError("Unsupported comparison sample operand") reference, u, v = values - method = "SampleCmpLevelZero" if explicit_zero else "SampleCmp" - lines.append(f" float sample{i} = tex.{method}(samp, float2({u}, {v}), {reference}{offset_arg});") + method = {"image_sample_c_lz": "SampleCmpLevelZero", "image_sample_c_l": "SampleCmpLevel", + "image_sample_c_b": "SampleCmpBias", "image_sample_c_d": "SampleCmpGrad", + "image_sample_c": "SampleCmp"}[base_op] + lines.append(f" float sample{i} = tex.{method}(samp, float2({u}, {v}), " + f"{reference}{extra_args}{offset_arg});") samples += 1 sampled_textures.add("tex") vector_loads += 1 @@ -5572,7 +5779,13 @@ def sample_coord(reg): lines.append(f" uint sb{i} = {b_expr};") lines.append(f" uint ci{i} = {condition[1]} ? 1u : 0u;") lines.append(f" uint cp{i} = {partial.format(f'sa{i}', f'sb{i}')};") - lines.append(f" uint co{i} = {result_tmpl.format(p=f'cp{i}', c=f'ci{i}')};") + if op == "sub": + # The RX 5700 XT returned the subtrahend for this uniform SDWA chain (#2731). + # In uint arithmetic ~(b - a) is a - b - 1. Select the completed difference. + result = f"{condition[1]} ? ~(sb{i} - sa{i}) : cp{i}" + else: + result = result_tmpl.format(p=f"cp{i}", c=f"ci{i}") + lines.append(f" uint co{i} = {result};") lines.append(f" bool cmp{i} = {carry_out_tmpl.format(f'sa{i}', f'sb{i}', p=f'cp{i}', c=f'ci{i}', r=f'co{i}')};") placed = sdwa_dest(f"co{i}", dst_sel, unused, vector.get(dst)) lines.append(f" precise float alu{i} = asfloat({placed});") @@ -5850,6 +6063,27 @@ def sample_coord(reg): lines.append(f" uint hf{i}_0 = {s0_bits};") emit_sdwa_f16_dest(lines, i, dst, f"{helper}(hf{i}_0)", dst_sel, unused, vector, known_ssa_bits, known_half, tag="half16" if is_mant else "low16", known_result=result) + elif m := match(r"v_cvt_norm_(i16|u16)_f16_sdwa (.+)"): + # SDWA binary16 to normalized i16/u16 conversion (exact RNE in 32-bit integer arithmetic). + kind, rest = m.groups() + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_cvt_norm_{kind}_f16_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_cvt_norm_result(kind == "i16", b0) + helper = f"cvt_norm_{kind}_f16" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = {s0_bits};") + emit_sdwa_f16_dest(lines, i, dst, f"{helper}(hf{i}_0)", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="low16", known_result=result) elif m := match(r"v_cvt_f16_(i16|u16)_sdwa (.+)"): # SDWA 16-bit integer to binary16 conversion (round to nearest even): integer src0 with # optional sext() and any SDWA selection. Runtime i16 is always finite; u16 requires a @@ -6955,6 +7189,29 @@ def sample_coord(reg): known_half[f"alu{i}"] = result else: vector[dst] = ("low16", f"alu{i}") + elif m := match(r"v_cvt_norm_(i16|u16)_f16_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 binary16 to normalized i16/u16 conversion under the finite-proof contract. + kind, dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, perm, is_dpp8 = parse_dpp(rest, 1) + s0_val, b0, abs0, neg0 = half16_dpp_source( + tokens[0], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + f16_cvt_norm_result(kind == "i16", b0) + s0_bits = f"(({emit_quad_swizzle_u32(lines, i, s0_val, perm)}) & 0xffffu)" + if abs0: + s0_bits = f"({s0_bits} & 0x7fffu)" + if neg0: + s0_bits = f"({s0_bits} ^ 0x8000u)" + helper = f"cvt_norm_{kind}_f16" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0));") + vector[dst] = ("low16", f"alu{i}") elif m := match(r"v_(fmac|ldexp)_f16_dpp (v\d+), (.+)"): # Quad-local DPP16/DPP8 binary16 fused multiply-accumulate (D = S0_swizzled * S1 + D) # and exponent scaling (D = S0_swizzled * 2^S1) under the static finite-proof contract @@ -7211,7 +7468,7 @@ def sample_coord(reg): packed_lanes.append(f"pack16_rne({lvar})") helpers.add("pack16_rne") if op in ("min", "max"): - helpers.add(f"{op}16_num") + helpers.add("minmax16_num") vector[dst] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({packed_lanes[0]} | ({packed_lanes[1]} << 16));") elif m := match(r"v_cvt_u32_f32_e32 (v\d+), ([vs]\d+|0x[0-9a-f]{1,8})"): @@ -7634,6 +7891,25 @@ def sample_coord(reg): lines.append(f" int cv{i}_0 = int(trunc(hs{i}));") lines.append(f" precise float alu{i} = asfloat(asuint(cv{i}_0) & 0xffffu);") vector[dst] = ("low16", f"alu{i}") + elif m := match(r"v_cvt_norm_(i16|u16)_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): + # Plain e32/e64 binary16 to normalized i16/u16 conversion (issue #839): exact RNE in 32-bit + # integer arithmetic on finite inputs, producing ("low16", alu). + kind, encoding, dst, token = m.groups() + if mask != "entry": + raise ValueError("Invalid binary16 to integer conversion operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if not 0 <= int(dst[1:]) <= 255: + raise ValueError(f"Register out of range: {dst}") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + word, proven = half16_arith_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + f16_cvt_norm_result(kind == "i16", proven) + helper = f"cvt_norm_{kind}_f16" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0));") + vector[dst] = ("low16", f"alu{i}") elif m := match(r"v_cvt_off_f32_i4(?:_e32|_e64)? (v\d+), ([vs]\d+|0x[0-9a-f]{1,8}|\d+)( clamp)?"): # Bits 3:0 of the source as a signed nibble in units of 1/16, so 0x7 gives 0.4375 # and 0x8 gives -0.5. The source is read as bits, so float modifiers do not apply. @@ -7864,6 +8140,8 @@ def sample_coord(reg): scalar.site = vector.site = None if region is not None: raise ValueError("Program ends inside a masked region") + if sample_clamp_mips is not None and not sample_clamp_used: + raise ValueError("A sample clamp binding requires a clamped sample") if gather_mips is not None and sample_kind != "gather": raise ValueError("Expected one gather for the declared view") if not ended or sampled_textures != set(bindings.values()): @@ -7882,7 +8160,7 @@ def sample_coord(reg): memory = TITLE_MEMORY + (TITLE_MEMORY_X2 if title_loads_x2 else "") memory += TITLE_MEMORY_X4 if title_loads_x4 else "" lines[:0] = [lookup, memory.format(slots=TITLE_ALIAS_SLOTS, count=title_ranges, miss=TITLE_MISS)] - source = "\n".join([*lines, "}", ""]) + source = "\n".join([FLOAT_MINMAX, *lines, "}", ""]) return (source, channel_mask) if return_write_mask else source @@ -7894,6 +8172,8 @@ def main(): parser.add_argument("--llvm", required=True, help="LLVM C library with AMDGPU support") parser.add_argument("--cpu", choices=("gfx1013", "gfx1030"), default="gfx1013", help="Source instruction set (gfx1030 uses the wave64 pixel profile)") + parser.add_argument("--sample-clamp-mips", type=int, + help="Opt in to experimental gfx1030 minimum-LOD samples with this visible mip count") parser.add_argument("--gather-mips", type=int, help="Declare the matching native and desktop 2D gather view mip count") parser.add_argument("--texture-sgpr", type=int, required=True, help="Entry register for the low descriptor-table address") parser.add_argument("--interp-sgpr", type=int, required=True, help="Entry register for the interpolation base") @@ -7937,7 +8217,7 @@ def main(): extra_constants=[tuple(entry) for entry in args.extra_constant], pointer_constants=[tuple(entry) for entry in args.pointer_constant], half_denorm=args.half_denorm, return_write_mask=args.rt0_write_mask, - cpu=args.cpu, gather_mips=args.gather_mips) + cpu=args.cpu, gather_mips=args.gather_mips, sample_clamp_mips=args.sample_clamp_mips) source, write_mask = result if args.rt0_write_mask else (result, None) except (ValueError, KeyError, struct.error, OSError, AttributeError, zlib.error) as exc: parser.exit(1, f"Translation failed: {exc}\n") diff --git a/tools/probe_root_devices.py b/tools/probe_root_devices.py index 696c178e45..9aa37697e7 100644 --- a/tools/probe_root_devices.py +++ b/tools/probe_root_devices.py @@ -32,8 +32,13 @@ def main(argv=None): backends.append("hardware") result = {"windows": sys.getwindowsversion().build, "controls": {}, "images": {}} try: + if not args.bin.is_dir(): + raise NotADirectoryError(f"--bin path is not a directory: {args.bin}") for name in ("compute_root", "compute_tables"): - rows = measure(command, (args.bin / (name + ".cso")).read_bytes()) + control_path = args.bin / (name + ".cso") + if not control_path.is_file(): + raise FileNotFoundError(f"Control shader is missing or not a file: {control_path}") + rows = measure(command, control_path.read_bytes()) if (len(rows) != 1 or not isinstance(rows[0], dict) or rows[0].get("cleared") != 0 or rows[0].get("remaining_flags") != 0 or any(rows[0].get(key) != "0x00000000" for key in ["serialize", *backends])): @@ -45,7 +50,16 @@ def main(argv=None): dest = PROJECT / "out/calls" / ("root-devices-warp.json" if args.warp_only else "root-devices.json") if dest.resolve().is_relative_to(args.build.resolve()): parser.error("Choose an input directory separate from the report directory") - inventory = json.loads((dest.parent / "six-apis.json").read_bytes()) + if not args.build.is_dir(): + raise NotADirectoryError(f"Build directory is not a directory: {args.build}") + if dest.parent.is_file(): + raise NotADirectoryError(f"Output parent is not a directory: {dest.parent}") + if dest.is_dir(): + raise IsADirectoryError(f"Output path is a directory: {dest}") + inventory_path = dest.parent / "six-apis.json" + if not inventory_path.is_file(): + raise FileNotFoundError(f"Inventory file is missing or not a file: {inventory_path}") + inventory = json.loads(inventory_path.read_bytes()) if not isinstance(inventory, dict): raise ValueError("Invalid six-apis.json inventory") for name in NAMES: @@ -58,7 +72,10 @@ def main(argv=None): container_specs = [(int(item["rva"], 16), item["bytes"], item["rva"]) for item in containers] except (KeyError, TypeError) as exc: raise ValueError(f"Invalid six-apis.json entry for {name}: {exc}") from exc - image = (args.build / name).read_bytes() + image_path = args.build / name + if not image_path.is_file(): + raise FileNotFoundError(f"Build image is missing or not a file: {image_path}") + image = image_path.read_bytes() if hashlib.sha256(image).hexdigest() != expected_sha256: raise ValueError(f"Regenerate six-apis.json for {name}") layouts = {} diff --git a/tools/rdna_cvt_pk_u8.py b/tools/rdna_cvt_pk_u8.py index d7dccdc75e..09a533e23e 100644 --- a/tools/rdna_cvt_pk_u8.py +++ b/tools/rdna_cvt_pk_u8.py @@ -28,6 +28,7 @@ import json import math import os +from pathlib import Path import re import shutil import struct @@ -526,7 +527,103 @@ def check(name, got, want): # ---------------------------------------------------------------- main -def main(): +def _same_path(left, right): + left_p = Path(left) + right_p = Path(right) + if os.path.normcase(str(left_p.resolve())) == os.path.normcase(str(right_p.resolve())): + return True + return left_p.exists() and right_p.exists() and left_p.samefile(right_p) + + +def _validate_output_path(flag, raw_path): + if not raw_path or not raw_path.strip(): + raise ValueError('%s path must not be empty' % flag) + if raw_path.endswith(('/', '\\')): + raise ValueError('%s path is a directory path: %s' % (flag, raw_path)) + p = Path(raw_path) + if p.is_symlink(): + raise ValueError('%s path must not be a symlink: %s' % (flag, raw_path)) + if p.is_dir(): + raise ValueError('%s path is a directory: %s' % (flag, raw_path)) + if p.exists() and not p.is_file(): + raise ValueError('%s path is not a regular file: %s' % (flag, raw_path)) + for parent in p.parents: + if parent.is_symlink() and not parent.is_dir(): + raise ValueError('%s parent path is a symlink to non-directory: %s' % (flag, parent)) + if parent.exists() and not parent.is_dir(): + raise ValueError('%s parent path is not a directory: %s' % (flag, parent)) + return p + + +def _validate_args(args): + if args.show < 0: + raise ValueError('--show must be >= 0, got %d' % args.show) + + keep_path = None + if args.keep is not None: + if not args.keep.strip(): + raise ValueError('--keep path must not be empty') + keep_path = Path(args.keep) + if keep_path.exists() and not keep_path.is_dir(): + raise ValueError('--keep path is not a directory: %s' % args.keep) + if keep_path.is_symlink() and not keep_path.is_dir(): + raise ValueError('--keep path is a broken symlink: %s' % args.keep) + for parent in keep_path.parents: + if parent.exists() and not parent.is_dir(): + raise ValueError('--keep parent path is not a directory: %s' % parent) + + cmp_path = None + if args.compare: + cmp_path = Path(args.compare) + if cmp_path.is_dir(): + raise ValueError('--compare path is a directory: %s' % args.compare) + + out_path = _validate_output_path('--out', args.out) + json_path = _validate_output_path('--json', args.json) if args.json is not None else None + + if cmp_path is not None and _same_path(out_path, cmp_path): + raise ValueError('--out path collides with --compare: %s' % args.out) + if json_path is not None and cmp_path is not None and _same_path(json_path, cmp_path): + raise ValueError('--json path collides with --compare: %s' % args.json) + if json_path is not None and _same_path(out_path, json_path): + raise ValueError('--out and --json paths must not collide: %s' % args.out) + if keep_path is not None: + if _same_path(keep_path, out_path): + raise ValueError('--keep and --out paths must not collide: %s' % args.out) + if json_path is not None and _same_path(keep_path, json_path): + raise ValueError('--keep and --json paths must not collide: %s' % args.json) + if cmp_path is not None and _same_path(keep_path, cmp_path): + raise ValueError('--keep and --compare paths must not collide: %s' % args.compare) + + +def _write_atomic(path, content): + """Write content to a sibling temp file and atomically replace path, cleaning up on failure.""" + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', + encoding='utf-8', + newline='\n', + dir=target.parent, + prefix='.%s.' % target.name, + suffix='.tmp', + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, target) + except BaseException: + if tmp_path is not None: + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + raise + + +def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--device', type=int, default=0, help='HIP device index (default 0; every device is listed)') ap.add_argument('--arch', help='target, e.g. gfx1030, gfx1032, gfx1100 (default: from the HIP device)') @@ -543,72 +640,89 @@ def main(): ap.add_argument('--clang', help='clang executable (--build hip)') ap.add_argument('--llvm-mc', help='llvm-mc executable (--build asm)') ap.add_argument('--lld', help='ld.lld executable (--build asm)') - args = ap.parse_args() + args = ap.parse_args(argv) if args.self_test: return self_test() - hip, arch = None, args.arch - if not args.asm_only: + temp_workdir = None + try: + _validate_args(args) + + hip, arch = None, args.arch + if not args.asm_only: + try: + hip = Hip() + hip.device = args.device + for i in range(hip.count()): + print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) + if not arch: + arch = hip.arch() + except RuntimeError as e: + print('error: %s' % e, file=sys.stderr) + return 2 + if not arch: + print('error: --asm-only needs --arch', file=sys.stderr) + return 2 + arch = arch.split(':')[0] + + if args.keep: + workdir = args.keep + os.makedirs(workdir, exist_ok=True) + else: + temp_workdir = tempfile.mkdtemp(prefix='cvt_pk_u8_') + workdir = temp_workdir + + images = {} + for var in VARIANTS: + images[var] = build(arch, var, workdir, args) + print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) + if args.asm_only: + return 0 + + rows = build_rows() + words = [(r[1], r[2]) for r in rows] + results = {} try: - hip = Hip() - hip.device = args.device - for i in range(hip.count()): - print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) - if not arch: - arch = hip.arch() + for var in VARIANTS: + results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) except RuntimeError as e: print('error: %s' % e, file=sys.stderr) - return 2 - if not arch: - sys.exit('error: --asm-only needs --arch') - arch = arch.split(':')[0] - - workdir = args.keep or tempfile.mkdtemp(prefix='cvt_pk_u8_') - os.makedirs(workdir, exist_ok=True) - images = {} - for var in VARIANTS: - images[var] = build(arch, var, workdir, args) - print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) - if args.asm_only: + return 3 + summary = analyse(rows, results, args.show) + print_report(rows, results, summary, arch, args.show) + header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', + '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, + '# columns (tab separated, words in hex): label in sel default rtz flush', + '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] + lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) + for i, r in enumerate(rows)] + _write_atomic(args.out, '\n'.join(header + lines) + '\n') + print('\nresults written to %s' % os.path.abspath(args.out)) + if args.json: + payload = json.dumps( + {'arch': arch, 'sentinel': SENTINEL, + 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], + **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], + 'summary': summary}, + indent=1, + ) + _write_atomic(args.json, payload) + print('verbose JSON written to %s' % os.path.abspath(args.json)) + if args.compare and os.path.exists(args.compare): + with open(args.compare, encoding='utf-8') as f: + stored = [l.rstrip('\n') for l in f if not l.startswith('#')] + if stored == lines: + print('rows identical to %s' % args.compare) + else: + print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) return 0 - - rows = build_rows() - words = [(r[1], r[2]) for r in rows] - results = {} - try: - for var in VARIANTS: - results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) - except RuntimeError as e: + except (OSError, ValueError, json.JSONDecodeError) as e: print('error: %s' % e, file=sys.stderr) - return 3 - summary = analyse(rows, results, args.show) - print_report(rows, results, summary, arch, args.show) - header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', - '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, - '# columns (tab separated, words in hex): label in sel default rtz flush', - '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] - lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) - for i, r in enumerate(rows)] - os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) - with open(args.out, 'w', newline='\n') as f: - f.write('\n'.join(header + lines) + '\n') - print('\nresults written to %s' % os.path.abspath(args.out)) - if args.json: - with open(args.json, 'w') as f: - json.dump({'arch': arch, 'sentinel': SENTINEL, - 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], - **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], - 'summary': summary}, f, indent=1) - print('verbose JSON written to %s' % os.path.abspath(args.json)) - if args.compare and os.path.exists(args.compare): - with open(args.compare) as f: - stored = [l.rstrip('\n') for l in f if not l.startswith('#')] - if stored == lines: - print('rows identical to %s' % args.compare) - else: - print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) - return 0 + return 1 + finally: + if temp_workdir is not None: + shutil.rmtree(temp_workdir, ignore_errors=True) if __name__ == '__main__': diff --git a/tools/record_gpu_cases.py b/tools/record_gpu_cases.py new file mode 100644 index 0000000000..4c7beb6525 --- /dev/null +++ b/tools/record_gpu_cases.py @@ -0,0 +1,136 @@ +"""Record the compiled gfx2hlsl compute cases for the GPU check package. + + python -B tools/record_gpu_cases.py <dxc> <output-dir> + +For every case and every mutation control of tests/startup_gfx2hlsl_compute_check.py this writes the DXC cs_6_0 +object and the case file that `offscreen_check <warp|hardware> --compute-store-case <cso> <case>` reads, plus a +manifest the package's Run-GpuCheck.ps1 replays on the user's own adapter. The cases are built by the same +run_case() the dispatch tests use, so the bytes are the ones those tests dispatch. Nothing here talks to a GPU: +run_case() is given a runner that does nothing. + +manifest.tsv, one row per case, tab separated, no header: + id <TAB> compiler <TAB> expect <TAB> mismatch + id gfx2hlsl_compute/<case> or gfx2hlsl_compute/control-<mutation>; the files are <id>.cso and <id>.case + compiler dxc (cs_6_0) + expect pass: exit 0 and no diagnostics; fail: exit 1 and a `word=... expected=...` diagnostic (a mutation + control that PASSES on a card is the failure) + mismatch for fail rows with a pinned first bad word, that diagnostic line; otherwise empty +""" +import argparse +import os +import shutil +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT / 'tests'), str(ROOT / 'tools'), str(ROOT / 'tools' / 'startup')] +import startup_gfx2hlsl_compute_check as check # noqa: E402 + +COMPILER = 'dxc' +GROUP = 'gfx2hlsl_compute' + + +def _samefile(a, b): + try: + return os.path.samefile(a, b) + except OSError: + return Path(a).resolve(strict=False) == Path(b).resolve(strict=False) + + +def _resolve_dxc(dxc): + if dxc is None or not str(dxc).strip(): + raise ValueError("dxc path must be non-empty") + candidate = Path(dxc) + if candidate.is_file(): + return candidate + if os.sep not in str(dxc) and "/" not in str(dxc) and "\\" not in str(dxc): + which = shutil.which(str(dxc)) + if which and Path(which).is_file(): + return Path(which) + raise ValueError(f"dxc must resolve to an existing regular file: {dxc}") + + +def _validate_output_dir(output, dxc_path): + if output is None or not str(output).strip(): + raise ValueError("output path must be non-empty") + out = Path(output) + if out.is_symlink(): + raise ValueError(f"output path cannot be a symlink: {out}") + if out.is_file() or (out.exists() and not out.is_dir()): + raise ValueError(f"output path is not a directory: {out}") + if _samefile(out, dxc_path): + raise ValueError(f"output path matches dxc executable: {out}") + if out.parent.is_file(): + raise ValueError(f"output parent is a file: {out.parent}") + for ancestor in (out.parent, *out.parent.parents): + if ancestor.exists(): + if not ancestor.is_dir(): + raise ValueError(f"output ancestor is not a directory: {ancestor}") + break + manifest = out / 'manifest.tsv' + if manifest.is_symlink() or manifest.is_dir(): + raise ValueError(f"manifest target cannot be a symlink or directory: {manifest}") + return out + + +def _write_manifest_atomic(path, rows): + text = ''.join('\t'.join(row) + '\n' for row in rows) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', + encoding='ascii', + newline='\n', + dir=path.parent, + prefix='.%s.' % path.name, + suffix='.tmp', + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(text) + handle.flush() + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def record(dxc, output, cases=None, controls=None): + """Write the cases and the manifest into `output`; return the manifest rows.""" + dxc_path = _resolve_dxc(dxc) + output = _validate_output_dir(output, dxc_path) + target = output / GROUP + target.mkdir(parents=True, exist_ok=True) + rows = [] + jobs = [(name, None) for name in (check.CASES if cases is None else cases)] + jobs += [(check.CONTROLS[m][0], m) for m in (check.CONTROLS if controls is None else controls)] + for name, mutation in jobs: + ident = '%s/%s' % (GROUP, 'control-' + mutation if mutation else name) + with tempfile.TemporaryDirectory() as tmp: + # The runner is only started to be refused: python rejects the adapter word as a script name. + check.run_case(name, str(dxc_path), sys.executable, 'warp', Path(tmp), mutation) + for ext in ('cso', 'case'): + shutil.copyfile(Path(tmp) / ('%s.%s' % (name, ext)), output / ('%s.%s' % (ident, ext))) + rows.append((ident, COMPILER, 'fail' if mutation else 'pass', check.CONTROL_MISMATCH.get(mutation, '') if mutation else '')) + _write_manifest_atomic(output / 'manifest.tsv', rows) + return rows + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('dxc') + parser.add_argument('output') + args = parser.parse_args(argv) + try: + rows = record(args.dxc, args.output) + except (OSError, ValueError, RuntimeError) as error: + sys.stderr.write(f'{error}\n') + return 1 + print('recorded %d cases (%d controls) into %s' % (len(rows), sum(r[2] == 'fail' for r in rows), args.output)) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/run_checks_parallel.py b/tools/run_checks_parallel.py index c6703aa635..2c1d702ee6 100644 --- a/tools/run_checks_parallel.py +++ b/tools/run_checks_parallel.py @@ -1,7 +1,11 @@ """Run independent Python check scripts side by side and fail if any of them fails. Usage: - python tools/run_checks_parallel.py [-j N] tests/a_check.py tests/b_check.py ... + python tools/run_checks_parallel.py [-j N] [--from-dir DIR] tests/a_check.py tests/b_check.py ... + +`--from-dir DIR` also runs the commands listed in `DIR/*.txt` (see `read_check_files`), after +the scripts given on the command line. `merge_checks(inline, directory)` does the same for +the pairs passed to `run_checks`. Each script runs as `python -B <script>` from the current directory. Output is printed one script at a time, in the order given, so a failure log stays readable. The exit status is 1 @@ -17,6 +21,7 @@ import concurrent.futures import os from pathlib import Path +import shlex import subprocess import sys import time @@ -24,6 +29,11 @@ SKIP_EXIT_CODE = 77 +def _command_key(command): + """Return a comparison key with the script path resolved to collapse spelling variants.""" + return (str(Path(command[0]).resolve()), *command[1:]) + + def _validate_script_path(raw_path: str) -> str: if not raw_path or not raw_path.strip(): raise ValueError("script path must not be empty") @@ -37,6 +47,93 @@ def _validate_script_path(raw_path: str) -> str: return raw_path +def _split_windows(line): + """Split on whitespace; quotes group text inside a word and are dropped, backslashes stay.""" + words, current, quote, started = [], [], None, False + for char in line: + if quote: + if char == quote: + quote = None + else: + current.append(char) + elif char in "\"'": + quote, started = char, True + elif char.isspace(): + if started: + words.append("".join(current)) + current, started = [], False + else: + current.append(char) + started = True + if quote: + raise ValueError("No closing quotation") + if started: + words.append("".join(current)) + return words + + +def split_command(line, windows=None): + """Split a listed line like a shell would, but keep backslashes in Windows paths. + + POSIX splitting treats a backslash as an escape and would turn `C:\\x2w\\a.py` into + `C:x2wa.py`. On Windows the line is split without escapes; quotes group words, also inside + one (`--llvm="C:\\Program Files\\a.dll"`), and are removed. + """ + if windows is None: + windows = os.name == "nt" + if not windows: + return shlex.split(line) + return _split_windows(line) + + +def read_check_files(directory): + """Return the check commands listed in `directory/*.txt`, files in name order. + + One command per line: a script path, optionally followed by its arguments (split like a + shell would). Blank lines and lines starting with `#` are ignored. A leading UTF-8 + byte-order mark is skipped. A missing directory, an + unreadable file, a script that does not exist, or the same command listed twice all raise, + so a typo cannot silently drop a check. + """ + root = Path(directory) + if not root.is_dir(): + raise FileNotFoundError(f"check list directory does not exist: {directory}") + commands = [] + seen = {} + for listing in sorted(root.glob("*.txt")): + for number, line in enumerate(listing.read_text(encoding="utf-8-sig").splitlines(), 1): + line = line.strip() + if not line or line.startswith("#"): + continue + where = f"{listing}:{number}" + try: + command = split_command(line) + except ValueError as exc: + raise ValueError(f"{where}: {exc}") from exc + try: + _validate_script_path(command[0]) + except (ValueError, OSError) as exc: + raise type(exc)(f"{where}: {exc}") from exc + key = _command_key(command) + if key in seen: + raise ValueError(f"{where}: duplicate of {seen[key]}: {line}") + seen[key] = where + commands.append(command) + return commands + + +def merge_checks(inline, directory): + """Return the inline `(command, extra_env)` pairs followed by the listed checks. + + Listed commands already present inline are dropped, so an entry can move from the inline + list to a file without running twice. The listed commands keep their sorted file order. + """ + inline = list(inline) + known = {_command_key(command) for command, _ in inline} + return inline + [(command, {}) for command in read_check_files(directory) + if _command_key(command) not in known] + + def run_one(check): command, extra_env = check if not command: @@ -84,11 +181,24 @@ def run_checks(checks, jobs=None): def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 2) - parser.add_argument("scripts", nargs="+") + parser.add_argument("--from-dir", metavar="DIR", + help="also run the checks listed in DIR/*.txt") + parser.add_argument("scripts", nargs="*") args = parser.parse_args(argv) + if not args.scripts and not args.from_dir: + parser.error("the following arguments are required: scripts (or --from-dir)") try: scripts = [_validate_script_path(script) for script in args.scripts] - return run_checks([([script], None) for script in scripts], jobs=args.jobs) + seen_scripts = set() + for script in scripts: + key = _command_key([script]) + if key in seen_scripts: + raise ValueError(f"duplicate command-line script: {script}") + seen_scripts.add(key) + checks = [([script], None) for script in scripts] + if args.from_dir: + checks = merge_checks(checks, args.from_dir) + return run_checks(checks, jobs=args.jobs) except (ValueError, OSError, subprocess.SubprocessError) as exc: detail = str(exc) msg = f"{detail}\n" if detail else f"{type(exc).__name__}\n" diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index 6e32ee9f6c..43ffd88784 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -310,14 +310,14 @@ def lower_rejection_causes(results: list[dict]) -> dict: rf"\s+{INT16_SOURCE},\s+{INT16_SOURCE},\s+{INT16_SOURCE}" ) # 64-bit VOP3 shifts (issue #928): a VGPR-pair destination, a 32-bit amount (VGPR, SGPR, inline integer or -# literal) and a 64-bit value (VGPR pair, SGPR pair or inline integer), with at most one SGPR or literal source. +# literal) and a 64-bit value (VGPR pair, SGPR pair, inline integer or 32-bit hex literal), with at most one SGPR or literal source. # This matches syntax only; pixel_aot also checks the pair ranges and that the sources are tracked. SHIFT64_AMOUNT = r"(?:v\d+|-?\d+)" SHIFT64_VALUE = r"(?:v\[\d+:\d+\]|-?\d+)" SUPPORTED_INSTRUCTIONS_REGEX.append( r"v_(?:lshlrev_b64|lshrrev_b64|ashrrev_i64)(?:_e64)?\s+v\[\d+:\d+\],\s+" rf"(?:{SHIFT64_AMOUNT},\s+{SHIFT64_VALUE}|(?:s\d+|0x[0-9a-f]{{1,8}}),\s+{SHIFT64_VALUE}" - rf"|{SHIFT64_AMOUNT},\s+s\[\d+:\d+\])" + rf"|{SHIFT64_AMOUNT},\s+s\[\d+:\d+\]|{SHIFT64_AMOUNT},\s+0x[0-9a-f]{{1,8}})" ) for name, (arity, _) in PIXEL_INTEGER.items(): @@ -482,11 +482,15 @@ def lower_rejection_causes(results: list[dict]) -> dict: } ) +OPCODE_ENCODING_SUFFIX = re.compile(r"_(?:e32|e64|sdwa|dpp.*)$") +CROSS_LANE_VALU_OPCODES = {"v_permlane16_b32", "v_permlanex16_b32"} +CROSS_LANE_VALU_CATEGORY = "VALU (Cross-lane)" + def is_opcode_recognized(opcode: str) -> bool: """Check if opcode belongs to recognized AMD RDNA 2 ISA instructions.""" clean = opcode.strip().lower() - base = re.sub(r"_(?:e32|e64|sdwa|dpp.*)$", "", clean) + base = OPCODE_ENCODING_SUFFIX.sub("", clean) if base in KNOWN_RDNA2_BASE_OPCODES or clean in KNOWN_RDNA2_BASE_OPCODES: return True if base.startswith(("v_cmp_", "v_cmpx_")) or clean.startswith(("v_cmp_", "v_cmpx_")): @@ -501,6 +505,8 @@ def is_opcode_recognized(opcode: str) -> bool: def classify_isa_category(opcode: str) -> str: """Classify instruction into RDNA 2 ISA category according to the AMD manual.""" op = opcode.lower() + if OPCODE_ENCODING_SUFFIX.sub("", op.strip()) in CROSS_LANE_VALU_OPCODES: + return CROSS_LANE_VALU_CATEGORY if op.startswith("v_interp"): return "VINTRP (Parameter Interpolation)" if op.startswith("v_"): @@ -899,6 +905,8 @@ def make_progress_bar(percentage: float, width: int = 24, unicode_blocks: bool = def get_implementation_target(opcode: str, category: str) -> str: """Identify target file and subsystem in Xbox2Windows for an opcode.""" op = opcode.lower() + if category == CROSS_LANE_VALU_CATEGORY: + return "`tools/pixel_aot.py` (Wave lane layout, active lanes and bound control)" if "VALU" in category or "Vector ALU" in category: if any(x in op for x in ["_f32", "_f16", "_i32", "_u32"]): return "`tools/pixel_aot.py` (ALU dictionary / table)" diff --git a/tools/script_state_probe.py b/tools/script_state_probe.py index cf741652b1..8b13d6d5b1 100644 --- a/tools/script_state_probe.py +++ b/tools/script_state_probe.py @@ -13,7 +13,11 @@ from section_probe import sections -def joaat(text): +def joaat(text, *, allow_empty=True): + if not isinstance(text, str): + raise ValueError("State label must be an ASCII string") + if not allow_empty and not text: + raise ValueError("State label must be non-empty ASCII") value = 0 for byte in text.encode("ascii"): value = (value + byte) & 0xffffffff @@ -24,6 +28,26 @@ def joaat(text): return (value + (value << 15)) & 0xffffffff +def _validate_state(state): + if not isinstance(state, str) or not state: + raise ValueError("State label must be non-empty ASCII") + try: + return joaat(state, allow_empty=False) + except UnicodeEncodeError as exc: + raise ValueError(f"State label must be ASCII: {state!r}") from exc + + +def _require_archive_file(path): + path = Path(path) + if not path.is_file(): + if path.is_dir(): + raise ValueError(f"archive path is a directory, not a file: {path}") + if not path.exists(): + raise FileNotFoundError(f"archive file not found: {path}") + raise ValueError(f"archive path is not a regular file: {path}") + return path + + CAMERA = {joaat(s): s for s in ("blendduration", "orbitdistance", "priority", "pitchlimits", "headinglimits")} NODE = struct.Struct("<I5H2B") ATTRIBUTE = struct.Struct("<IIIBBH") @@ -200,7 +224,8 @@ def inspect_tree(nodes, attrs, vectors, state_id, record_index=0): def inspect(path, state=None): totals = Counter() candidates = [] - state_id = joaat(state) if state is not None else None + state_id = _validate_state(state) if state is not None else None + path = _require_archive_file(path) with path.open("rb") as stream: if os.fstat(stream.fileno()).st_size == 0: raise ValueError("Empty archive; expected an RPF9 archive") @@ -229,7 +254,10 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--state", help="Report at most one hash-verified example for this state label") args = parser.parse_args(argv) try: - result = inspect(args.archive, args.state) + if args.state is not None: + _validate_state(args.state) + archive = _require_archive_file(args.archive) + result = inspect(archive, args.state) except (OSError, ValueError, struct.error, zlib.error) as exc: parser.exit(1, f"{args.archive}: {exc}\n") print(json.dumps(result, indent=2)) diff --git a/tools/sgd5_effects.py b/tools/sgd5_effects.py index c485ec52f9..f0c851ec1a 100644 --- a/tools/sgd5_effects.py +++ b/tools/sgd5_effects.py @@ -23,6 +23,8 @@ def __init__(self, view: PagedResource, start: int, end: int): self.end = end def skip(self, size: int) -> int: + if size < 0: + raise ValueError("Negative SGD5 field size") start = self.pos if size > self.end - start: raise ValueError("SGD5 field exceeds supplied range") @@ -30,7 +32,10 @@ def skip(self, size: int) -> int: return start def read(self, size: int) -> bytes: - return self.view.read(self.skip(size), size) + data = self.view.read(self.skip(size), size) + if len(data) != size: + raise ValueError("Truncated SGD5 field") + return data def word(self) -> int: return int.from_bytes(self.read(4), "little") @@ -158,7 +163,10 @@ def candidates(stream: BinaryIO, name: str, group_start: int, group_end: int, ar def offset(value: str) -> int: - return int(value, 0) + parsed = int(value, 0) + if parsed < 0: + raise argparse.ArgumentTypeError(f"Expected non-negative offset, got {value}") + return parsed def main(argv: Sequence[str] | None = None) -> int: @@ -172,10 +180,12 @@ def main(argv: Sequence[str] | None = None) -> int: help="Physical bounds of the selected effect, including its final name block") args = parser.parse_args(argv) try: + if not args.archive.is_file(): + raise ValueError(f"Expected an existing regular file: {args.archive}") with args.archive.open("rb") as stream: found = candidates(stream, args.effect, *args.group, args.arrays, *args.record) print(json.dumps({"effect": args.effect, "candidates": [asdict(item) for item in found]}, indent=2)) - except (OSError, ValueError) as exc: + except (OSError, ValueError, struct.error, zlib.error) as exc: sys.stderr.write(f"{args.archive}: {exc}\n") return 1 return 0 diff --git a/tools/shader_census.py b/tools/shader_census.py index 4f6d17b499..cff1f672a2 100644 --- a/tools/shader_census.py +++ b/tools/shader_census.py @@ -1,4 +1,6 @@ """Report shader populations separately; do not classify or execute programs.""" +from __future__ import annotations + import argparse from contextlib import ExitStack import hashlib @@ -6,6 +8,7 @@ import mmap from pathlib import Path import struct +import zlib from resource_inventory import scene_records @@ -64,30 +67,36 @@ def observe(stage, blob, sections): ) -def main(): +def _map_input(stack: ExitStack, path: Path): + if path.is_dir(): + raise ValueError(f"Expected a file, not a directory: {path}") + stream = stack.enter_context(path.open("rb")) + if stream.seek(0, 2) == 0: + return b"" + return stack.enter_context(mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)) + + +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--cache-blob", type=Path, help="Already decoded PS/9 cache from the same build") parser.add_argument("--code-base", type=lambda value: int(value, 0), help="Independently established code-area base in that cache (decimal or hex)") - args = parser.parse_args() + args = parser.parse_args(argv) if (args.cache_blob is None) != (args.code_base is None): parser.error("--cache-blob and --code-base must be supplied together") + if args.code_base is not None and args.code_base < 0: + parser.error("--code-base must be non-negative") try: with ExitStack() as stack: - def mapped(path): - stream = stack.enter_context(path.open("rb")) - if stream.seek(0, 2) == 0: - return b"" - return stack.enter_context(mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)) - - archive = mapped(args.archive) - blob = mapped(args.cache_blob) if args.cache_blob is not None else None + archive = _map_input(stack, args.archive) + blob = _map_input(stack, args.cache_blob) if args.cache_blob is not None else None result = census(archive, cache_blob=blob, code_base=args.code_base) - except (OSError, ValueError) as error: + except (OSError, ValueError, struct.error, zlib.error) as error: parser.exit(1, f"Shader census: {error}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/tools/shader_minmax.py b/tools/shader_minmax.py new file mode 100644 index 0000000000..96880b7dfa --- /dev/null +++ b/tools/shader_minmax.py @@ -0,0 +1,18 @@ +"""HLSL shared by the gfx1013 pixel and startup translators.""" + +# RDNA 2 ISA section 12.7 settles both operand orders for signed zeros: +# V_MIN_F32: S0 = +0, S1 = -0 -> S1; S0 = -0, S1 = +0 -> S0 (min returns -0 if either operand is -0) +# V_MAX_F32: S0 = +0, S1 = -0 -> S0; S0 = -0, S1 = +0 -> S1 (max returns +0 when the zeros differ) +# Equal zeros take the general branch, so max(-0, -0) stays -0. For two zeros, the OR of the bit +# patterns gives the min result and the AND gives the max result, in either order. V_MIN3_F32, +# V_MAX3_F32 and V_MED3_F32 are defined through nested V_MIN_F32/V_MAX_F32, so chaining this helper +# applies the same rule. The emitted HLSL below is unchanged by this note. +FLOAT_MINMAX = """// RDNA 2 ISA section 12.7 orders -0 below +0 for min and max. +float minmax_zero32(float a, float b, bool maximum) { + uint a_bits = asuint(a), b_bits = asuint(b); + uint either = a_bits | b_bits; + uint zero = maximum ? (a_bits & b_bits) : either; + // Keep the selection integer so the compiler cannot merge the two float zeros. + return asfloat((either & 0x7fffffffu) == 0u ? zero : asuint(maximum ? max(a, b) : min(a, b))); +} +""" diff --git a/tools/spirv_address_window.py b/tools/spirv_address_window.py index 304f6cb906..068f1c6504 100644 --- a/tools/spirv_address_window.py +++ b/tools/spirv_address_window.py @@ -665,6 +665,31 @@ def _same_path(left: Path, right: Path) -> bool: return False +def _validate_args(args: argparse.Namespace) -> tuple[str, str]: + if _same_path(args.output, args.source): + raise ValueError("use separate input assembly and output binary paths") + if args.source.is_dir(): + raise IsADirectoryError(f"source path must not be a directory: {args.source}") + if not args.source.exists(): + raise FileNotFoundError(f"source file not found: {args.source}") + if not args.source.is_file(): + raise ValueError(f"source path must be a regular file: {args.source}") + if args.output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {args.output}") + if args.output.is_dir(): + raise IsADirectoryError(f"output path must not be a directory: {args.output}") + for parent in args.output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + assembler = args.assembler.strip() + if not assembler: + raise ValueError("--assembler must be a non-empty string") + validator = args.validator.strip() + if not validator: + raise ValueError("--validator must be a non-empty string") + return assembler, validator + + def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) @@ -673,10 +698,7 @@ def main(argv=None) -> int: parser.add_argument("--validator", default="spirv-val") args = parser.parse_args(argv) try: - if _same_path(args.output, args.source): - raise ValueError("use separate input assembly and output binary paths") - if args.output.is_dir(): - raise ValueError(f"output path must not be a directory: {args.output}") + assembler, validator = _validate_args(args) original = args.source.read_text(encoding="utf-8") args.output.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: @@ -684,8 +706,8 @@ def main(argv=None) -> int: binary = path / "module.spv" def validate(source): - subprocess.run([args.assembler, "--target-env", "vulkan1.2", source, "-o", binary], check=True) - subprocess.run([args.validator, "--target-env", "vulkan1.2", binary], check=True) + subprocess.run([assembler, "--target-env", "vulkan1.2", source, "-o", binary], check=True) + subprocess.run([validator, "--target-env", "vulkan1.2", binary], check=True) snapshot = path / "original.spvasm" snapshot.write_text(original, encoding="utf-8") diff --git a/tools/spirv_ballot_extract.py b/tools/spirv_ballot_extract.py index 166bff52a7..55afb3603c 100644 --- a/tools/spirv_ballot_extract.py +++ b/tools/spirv_ballot_extract.py @@ -32,6 +32,8 @@ def _find_lsb(dst, ballot, glsl): def lower_ballot_extract(assembly): + if not isinstance(assembly, str): + raise TypeError("assembly must be a str") extracts = "OpGroupNonUniformBallotBitExtract" in assembly finds = any(FIND_LSB.fullmatch(line) for line in assembly.splitlines()) if not extracts and not finds: @@ -73,4 +75,8 @@ def lower_ballot_extract(assembly): f"{tmp}low = OpBitwiseAnd %uint {tmp}shifted %x2w_ballot_c1", f"{dst} = OpINotEqual %bool {tmp}low %x2w_ballot_c0", ]) + if not declared: + raise ValueError("Ballot lowering needs an OpFunction declaration") + if import_needed and not imported: + raise ValueError("Ballot find-lsb lowering needs an OpMemoryModel instruction") return "\n".join(lines) + "\n" diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp new file mode 100644 index 0000000000..7728f227e6 --- /dev/null +++ b/tools/startup/compile_dxil.cpp @@ -0,0 +1,1660 @@ +#include "shader_dxil_compiler.h" +#include "direct_compute_cache.h" +#include "native_compute_output.h" +#include "shader_compute_request.h" +#include "gfx1013_pixel.h" +#include "gfx1013_sampled_pixel.h" +#include "gfx1013_vertex_id.h" +#include "gfx1013_compute_clear.h" +#include "gfx1013_compute_native.h" +#include "startup_stubs/native_global_srv.h" +#include <d3d12.h> +#include <wrl/client.h> +#include <algorithm> +#include <atomic> +#include <cctype> +#include <charconv> +#include <chrono> +#include <cstdio> +#include <cstring> +#include <future> +#include <map> +#include <set> +#include <sstream> +#include <fstream> +#include <iostream> +#include <iterator> +#include <optional> +#include <stdexcept> +#include <string_view> +#include <thread> + +using Clock = std::chrono::steady_clock; +static double elapsed_ms(Clock::time_point since) { + return std::chrono::duration<double,std::milli>(Clock::now()-since).count(); +} + +namespace fs = std::filesystem; + +static void publish_atomic(const fs::path& destination, const void* data, size_t size) { + static std::atomic<unsigned long long> serial{}; + auto temp=destination; + temp += L"." + std::to_wstring(GetCurrentProcessId()) + L"." + std::to_wstring(serial++) + L".tmp"; + try { + std::ofstream file(temp,std::ios::binary); + file.exceptions(std::ios::badbit | std::ios::failbit); + if (size) file.write(static_cast<const char*>(data),size); + file.close(); + if(!MoveFileExW(temp.c_str(),destination.c_str(),MOVEFILE_REPLACE_EXISTING)) + throw std::runtime_error("could not publish output"); + } catch(...) { + std::error_code ignored; + fs::remove(temp,ignored); + throw; + } +} + +// The view metadata captured with a compute request (req_<key>.views), read before the program is translated. Absent: +// the request has no captured selection and a GPU-selected heap read is refused. Present: every refusal below happens +// before any output is published. +struct CapturedViews { + x2w::HeapViewContract contract = x2w::HeapViewContract::none; + x2w_startup::GlobalSrvRequest request; + bool present = false; +}; + +static CapturedViews read_captured_views(const fs::path& request_path) { + CapturedViews views; + const auto path = fs::path(request_path).replace_extension(L".views"); + std::ifstream file(path, std::ios::binary); + if (!file) return views; + std::string text((std::istreambuf_iterator<char>(file)), {}); + if (file.bad()) throw std::runtime_error("global SRV view metadata read failed"); + std::string error; + if (!x2w_startup::decode_global_srv_request(text, views.request, error)) throw std::runtime_error(error); + views.present = true; + const auto& request = views.request; + auto refusal = x2w_startup::refuse_global_srv_selection(request.views, request.selected, request.needed); + if (!refusal.empty()) throw std::runtime_error(refusal); + if (request.needed != x2w_startup::GlobalSrvType::raw_buffer) + throw std::runtime_error(std::string("GPU-selected heap slot view type ") + + x2w_startup::global_srv_type_name(request.needed) + + " is not raw_buffer; only raw buffer heap reads are translated"); + views.contract = x2w::HeapViewContract::raw_buffer; + return views; +} + +static std::vector<unsigned char> compile_to_dxil(x2w::ShaderDxilCompiler& compiler, const std::string& source, + const std::wstring& profile, const fs::path& cache, bool direct, + std::ostream& report) { + auto start=Clock::now(); + auto output=compiler.compile(source,profile,cache,direct?x2w::ShaderSourceFormat::dxil_ir:x2w::ShaderSourceFormat::hlsl); + report << (output.cache_hit?"cache_hit_ms=":"cold_compile_and_publish_ms=") + << elapsed_ms(start) << " bytes=" << output.dxil.size() << '\n'; + return std::move(output.dxil); +} + +static void compile_source(x2w::ShaderDxilCompiler& compiler,const std::string& source,const std::wstring& profile, + const fs::path& destination,const fs::path& cache,bool direct,std::ostream& report) { + auto dxil = compile_to_dxil(compiler, source, profile, cache, direct, report); + publish_atomic(destination, dxil.data(), dxil.size()); +} + +static std::optional<std::string> compile_one(x2w::ShaderDxilCompiler& compiler, std::wstring profile, + const fs::path& input_path, const fs::path& destination, + const fs::path& cache, std::ostream& report, + const x2w::NativeComputeShader *linked=nullptr, + bool emit_manifest=false, std::string *manifest_reason=nullptr) { + Clock::time_point start; + std::string source; + std::optional<std::string> manifest; + const std::wstring clear_prefix=L"gfx1013-group-clear@"; + const std::wstring direct_prefix=L"gfx1013-direct-cs@"; + const bool container=profile==L"gfx1013-container-cs"; + const bool graphics=profile==L"gfx1013-container-vs" || profile==L"gfx1013-container-ps"; + const bool mesh_pixel=profile==L"gfx1013-raw-mesh-ps"; + const bool mesh=profile==L"gfx1013-container-ms-uint-heap" || profile==L"gfx1013-container-ms" || profile==L"gfx1013-raw-ms"; + const bool direct=container || graphics || mesh || mesh_pixel || profile==L"gfx1013-direct-constant-ps" || profile.compare(0,direct_prefix.size(),direct_prefix)==0; + const std::wstring compute_prefix=direct?direct_prefix:L"gfx1013-compute-wave32@"; + if(container || profile.compare(0,compute_prefix.size(),compute_prefix)==0){ + auto offset=container?L"0":profile.substr(compute_prefix.size()); + if(offset.empty()||offset.size()>7||offset.find_first_not_of(L"0123456789")!=offset.npos)throw std::runtime_error("invalid compute entry"); + start=Clock::now(); + const auto entry=static_cast<unsigned>(std::stoul(offset)); + bool frontend_hit=false; + CapturedViews views; + if(container)views=read_captured_views(input_path); + auto program=direct?x2w::prepare_direct_compute(input_path,entry,container,cache,frontend_hit,views.contract) + :x2w::translate_compute(x2w::read_compute_request(input_path),entry,false); + report<<"frontend=native_cpp instructions="<<program.instruction_count<<" frontend_cache_hit="<<frontend_hit + <<" request_and_translation_ms="<<elapsed_ms(start)<<"\n"; + for (const auto &b : program.bindings) { + using Table = x2w::ComputeViewBinding::ScalarTable; + if (b.kind == x2w::ComputeViewKind::heap_sampler) { + report << "sampler_heap span=" << b.required_bytes << '\n'; + continue; + } + report << (x2w::compute_uav(b.kind) ? "u" : "t") << b.shader_register << " root=" << b.root_parameter + << " bytes=" << b.byte_offset << " min_size=" << b.required_bytes; + if (b.scalar_table == Table::reflected_cbv) report << " table_view=reflected-cbv"; + if (b.scalar_table == Table::declared_cbv) report << " table_view=declared-cbv"; + if (b.scalar_table == Table::srv) report << " table_view=srv"; + report << '\n'; + } + if(views.present){ + const bool heap_read=std::any_of(program.bindings.begin(),program.bindings.end(),[](const auto& b){ + return b.kind==x2w::ComputeViewKind::heap_buffer_srv || b.kind==x2w::ComputeViewKind::heap_stride_srv;}); + if(heap_read){ + auto refusal=x2w_startup::refuse_global_srv_selection(views.request.views,views.request.selected,views.request.needed); + if(!refusal.empty())throw std::runtime_error(refusal); + } + report<<"global_srv select="<<views.request.selected<<" need="<<x2w_startup::global_srv_type_name(views.request.needed)<<'\n'; + } + if (emit_manifest && !container) manifest = x2w::format_compute_runtime_manifest(program, manifest_reason); + source=direct?std::move(program.dxil_ir):std::move(program.hlsl);profile=L"cs_6_6"; + } else if (profile.compare(0,clear_prefix.size(),clear_prefix)==0) { + auto offset=profile.substr(clear_prefix.size()); + if (offset.empty() || offset.size()>7 || offset.find_first_not_of(L"0123456789")!=offset.npos) + throw std::runtime_error("expected entry byte offset"); + start=Clock::now(); + auto program=x2w::replay_group_clear(input_path,static_cast<unsigned>(std::stoul(offset))); + report << "request_and_translation_ms=" << elapsed_ms(start) << '\n'; + for(size_t reg=0;reg<program.bindings.size();++reg) + report << "u" << reg << " parameter=" << program.bindings[reg].parameter + << " byte_offset=" << program.bindings[reg].byte_offset << " R32_UINT[256]\n"; + source=std::move(program.hlsl); + profile=L"cs_6_0"; + } else if(graphics){ + if(!linked)source=x2w::read_shader_container_bytes(input_path); + } else { + std::ifstream input(input_path,std::ios::binary); + if (!input) throw std::runtime_error("cannot open source"); + source.assign(std::istreambuf_iterator<char>(input),{}); + if (input.bad()) throw std::runtime_error("source read failed"); + } + if(mesh){ + auto mesh_ir=[&](x2w::NativeComputeShader shader) { + for (const auto &read : shader.mesh_heap_reads) + report<<"requires_heap_r32_uint root="<<read.root_parameter<<" dword="<<read.dword<<" mask="<<read.mask<<'\n'; + return std::move(shader.dxil_ir); + }; + if(profile!=L"gfx1013-raw-ms") source=mesh_ir(x2w::translate_mesh_container(source,profile==L"gfx1013-container-ms-uint-heap")); + else { + std::ifstream meta(fs::path(input_path).replace_extension(L".mslayout")); + x2w::MeshStageLayout layout{}; + std::string version, extra; + unsigned wave=0; + if (!(meta>>version>>layout.threads>>layout.max_vertices>>layout.max_primitives>>layout.topology>> + layout.group_stride>>wave) || version!="mesh1" || (wave!=32 && wave!=64)) + throw std::runtime_error("raw mesh requires explicit mesh1 threads vertices primitives topology group_stride wave"); + layout.wave32=wave==32; + while (meta>>extra) { + if (extra=="packed_parameters") { + layout.packed_parameters=true; + continue; + } + if (extra=="validate_uint_heap_reads") { + layout.validate_uint_heap_reads=true; + continue; + } + if (extra=="resource_heap") { + unsigned sgpr; + if (layout.resource_heap_sgpr || !(meta>>sgpr)) throw std::runtime_error("invalid mesh resource heap"); + layout.resource_heap_sgpr=sgpr; + continue; + } + x2w::MeshRootInput input{}; + input.root_address=extra=="root_address"; + if ((extra!="table" && extra!="constants" && !input.root_address) || !(meta>>input.sgpr>>input.root_parameter) || + (extra=="constants" && (!(meta>>input.constant_count) || !input.constant_count))) + throw std::runtime_error("invalid mesh entry root mapping"); + layout.root_inputs.push_back(input); + } + if (layout.root_inputs.empty()) source=mesh_ir(x2w::translate_mesh_program(source,layout)); + else { + auto bytes=x2w::read_shader_container_bytes(fs::path(input_path).replace_extension(L".root")); + Microsoft::WRL::ComPtr<ID3D12VersionedRootSignatureDeserializer> signature; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *desc=nullptr; + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(bytes.data(),bytes.size(),IID_PPV_ARGS(&signature))) || + FAILED(signature->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1,&desc))) + throw std::runtime_error("invalid raw mesh root signature"); + source=mesh_ir(x2w::translate_mesh_program(source,layout,desc->Desc_1_1)); + } + } + profile=L"ms_6_6"; + } else if (mesh_pixel) { + std::ifstream meta(fs::path(input_path).replace_extension(L".pslayout")); + std::string tag, extra; + unsigned enable, address, wave; + if (!(meta >> tag)) + throw std::runtime_error("raw mesh PS needs a reviewed entry layout"); + if (tag == "meshps1") { + if (!(meta >> enable >> address >> wave)) + throw std::runtime_error("raw mesh PS needs meshps1 enable address wave (decimal)"); + } else if (tag == "meshps2") { + // As in Victory's native PS reflection, this record names the + // inputs delivered by ADDR when a separate ENA mask is unavailable. + if (!(meta >> address >> wave)) + throw std::runtime_error("raw mesh PS needs meshps2 input-address wave (decimal)"); + enable = address; + } else { + throw std::runtime_error("unknown raw mesh PS entry layout version"); + } + const bool guest_root = bool(meta >> extra); + if (guest_root && (extra!="guest_root" || (meta >> extra))) + throw std::runtime_error("unexpected raw mesh PS layout field"); + Microsoft::WRL::ComPtr<ID3D12VersionedRootSignatureDeserializer> signature; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC *desc=nullptr; + if (guest_root) { + auto bytes=x2w::read_shader_container_bytes(fs::path(input_path).replace_extension(L".root")); + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(bytes.data(),bytes.size(),IID_PPV_ARGS(&signature))) || + FAILED(signature->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1,&desc))) + throw std::runtime_error("invalid raw mesh PS root signature"); + } + source=x2w::translate_mesh_pixel_program(source,enable,address,wave,desc ? &desc->Desc_1_1 : nullptr).dxil_ir; + profile=L"ps_6_6"; + } else if(graphics){ + bool pixel=profile==L"gfx1013-container-ps"; + if(linked)source=linked->dxil_ir; + else source=x2w::translate_graphics_container(source,pixel).dxil_ir; + profile=pixel?L"ps_6_6":L"vs_6_6"; + } else if (profile == L"gfx1013-direct-constant-ps") { + source=x2w::direct_gfx1013_constant_pixel(source); + profile=L"ps_6_0"; + } else if (profile == L"gfx1013-constant-ps") { + start=Clock::now(); + source=x2w::translate_gfx1013_constant_pixel(source); + report << "translation_ms=" << elapsed_ms(start) << '\n'; + profile=L"ps_6_0"; + } else if (profile == L"gfx1013-vertex-id-vs") { + start=Clock::now(); + source=x2w::translate_gfx1013_vertex_id(source); + report << "translation_ms=" << elapsed_ms(start) << '\n'; + profile=L"vs_6_0"; + } else if (profile == L"gfx1013-buffered-vs") { + start=Clock::now(); + auto program=x2w::translate_gfx1013_buffered_vertex(source); + report << "translation_ms=" << elapsed_ms(start) << '\n' << program.bindings; + source=std::move(program.hlsl); + profile=L"vs_6_0"; + } else if (profile == L"gfx1013-rgb11-r16-ps") { + start=Clock::now(); + auto program=x2w::translate_gfx1013_sampled_pixel(source); + report << "translation_ms=" << elapsed_ms(start) << '\n' << program.bindings; + source=std::move(program.hlsl); + profile=L"ps_6_0"; + } + compile_source(compiler,source,profile,destination,cache,direct,report); + return manifest; +} + +// Outputs of concurrent jobs must be independent. Compare Windows paths +// case-insensitively, including junctions in their parent directories. +struct PathLess { + bool operator()(const fs::path& a, const fs::path& b) const { + return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_LESS_THAN; + } +}; + +static std::string collapse_ascii_line(std::string_view text) { + std::string out; + out.reserve(text.size()); + bool space = true; + for (unsigned char c : text) { + if (c == '\r' || c == '\n' || c == '\t' || c == ' ') { + if (!space) { + out.push_back(' '); + space = true; + } + } else { + out.push_back(static_cast<char>(c)); + space = false; + } + } + if (!out.empty() && out.back() == ' ') + out.pop_back(); + return out; +} + +static std::string format_fail_line(std::string_view message) { + std::string out = collapse_ascii_line(message); + if (out.empty()) + out = "unknown refusal"; + out.push_back('\n'); + return out; +} + +// A compute program that translates but has no runtime manifest: the runtime cannot dispatch it translated. +static std::string manifest_refusal(const std::string &reason) { + return "unsupported startup runtime manifest bindings: " + reason; +} + +static bool is_ident_char(unsigned char c) { return std::isalnum(c) != 0 || c == '_'; } + +static std::string normalize_refusal_reason(std::string_view raw) { + std::string s = collapse_ascii_line(raw); + if (s.rfind("native compute +0x", 0) == 0) { + const size_t colon = s.find(": "); + if (colon != std::string::npos) + s.erase(0, colon + 2); + } + auto replace_all_with = [](std::string& str, auto&& matcher) { + std::string out; + out.reserve(str.size()); + size_t i = 0; + while (i < str.size()) { + size_t end = 0; + std::string rep; + if (matcher(str, i, end, rep)) { + out += rep; + i = end; + } else { + out.push_back(str[i++]); + } + } + str.swap(out); + }; + replace_all_with(s, [](const std::string& str, size_t i, size_t& end, std::string& rep) { + if (i + 2 >= str.size() || str[i] != '0' || (str[i + 1] != 'x' && str[i + 1] != 'X')) + return false; + if (i > 0 && is_ident_char(static_cast<unsigned char>(str[i - 1]))) + return false; + size_t j = i + 2; + while (j < str.size() && std::isxdigit(static_cast<unsigned char>(str[j]))) + ++j; + if (j == i + 2) + return false; + if (j < str.size() && (str[j] == 'u' || str[j] == 'U') && + (j + 1 == str.size() || !is_ident_char(static_cast<unsigned char>(str[j + 1])))) + ++j; + end = j; + rep = "0xN"; + return true; + }); + for (const std::string_view prefix : {" at byte ", " VGPR "}) { + replace_all_with(s, [&](const std::string& str, size_t i, size_t& end, std::string& rep) { + if (str.compare(i, prefix.size(), prefix) != 0) + return false; + size_t j = i + prefix.size(); + if (j >= str.size() || !std::isdigit(static_cast<unsigned char>(str[j]))) + return false; + while (j < str.size() && std::isdigit(static_cast<unsigned char>(str[j]))) + ++j; + if (j < str.size() && is_ident_char(static_cast<unsigned char>(str[j]))) + return false; + end = j; + rep = std::string(prefix) + "N"; + return true; + }); + } + replace_all_with(s, [](const std::string& str, size_t i, size_t& end, std::string& rep) { + if (str[i] != 's' && str[i] != 'v') + return false; + if (i > 0 && is_ident_char(static_cast<unsigned char>(str[i - 1]))) + return false; + size_t j = i + 1; + if (j < str.size() && str[j] == '[') { + ++j; + const size_t a = j; + while (j < str.size() && std::isdigit(static_cast<unsigned char>(str[j]))) + ++j; + if (j == a || j >= str.size() || str[j] != ':') + return false; + const size_t b = ++j; + while (j < str.size() && std::isdigit(static_cast<unsigned char>(str[j]))) + ++j; + if (j == b || j >= str.size() || str[j] != ']') + return false; + ++j; + if (j < str.size() && is_ident_char(static_cast<unsigned char>(str[j]))) + return false; + end = j; + rep = std::string(1, str[i]) + "[N:N]"; + return true; + } + const size_t a = j; + while (j < str.size() && std::isdigit(static_cast<unsigned char>(str[j]))) + ++j; + if (j == a || (j < str.size() && is_ident_char(static_cast<unsigned char>(str[j])))) + return false; + end = j; + rep = std::string(1, str[i]) + "N"; + return true; + }); + if (s.empty()) + s = "unknown refusal"; + return s; +} + +static int parse_jobs_count(std::wstring_view number) { + if (number.empty() || number.size() > 2 || number.find_first_not_of(L"0123456789") != number.npos) + throw std::runtime_error("--jobs must be between 1 and 64"); + const int jobs = std::stoi(std::wstring(number)); + if (jobs < 1 || jobs > 64) + throw std::runtime_error("--jobs must be between 1 and 64"); + return jobs; +} + +static std::string json_escape(std::string_view text) { + std::string out; + out.reserve(text.size() + 2); + out.push_back('"'); + for (unsigned char c : text) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (c < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", c); + out += buf; + } else { + out.push_back(static_cast<char>(c)); + } + break; + } + } + out.push_back('"'); + return out; +} + +static void dedupe_graphics_markers(std::vector<fs::path>& paths) { + // Requires paths to be sorted so a stem's .a immediately precedes its .rtv. + // A key with both markers is one request, the variant, as in gfx2hlsl.py request_source. + for (size_t i = 0; i + 1 < paths.size();) { + if (paths[i].extension() == L".a" && paths[i + 1].extension() == L".rtv" && + paths[i].stem() == paths[i + 1].stem()) + paths.erase(paths.begin() + i); + else + ++i; + } +} + +static std::optional<fs::path> graphics_psin_path(const fs::path& marker) { + if (marker.extension() == L".a") + return fs::path(marker).replace_extension(L".psin"); + if (marker.extension() != L".rtv") + return std::nullopt; + std::ifstream file(marker, std::ios::binary); + if (!file) + return std::nullopt; + char buf[257]{}; + file.read(buf, 256); + const std::string_view text(buf, static_cast<size_t>(file.gcount())); + if (text.substr(0, 5) != "rtv1 ") + return std::nullopt; + const std::string_view rest = text.substr(5); + const std::string_view token = rest.substr(0, rest.find(' ')); + if (token.empty() || token.size() > 20 || token.find_first_not_of("0123456789") != token.npos) + return std::nullopt; + uint64_t base = 0; + const auto end = token.data() + token.size(); + const auto parsed = std::from_chars(token.data(), end, base); + if (parsed.ec != std::errc{} || parsed.ptr != end) + return std::nullopt; + wchar_t name[32]{}; + std::swprintf(name, std::size(name), L"req_%016llx.psin", static_cast<unsigned long long>(base)); + return marker.parent_path() / name; +} + +static int run_refusals(int argc, wchar_t** argv) { + fs::path request_dir; + bool has_dir = false; + bool json = false; + int jobs = 1; + try { + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--json") { + json = true; + } else if (arg == L"--jobs") { + if (i + 1 >= argc) + throw std::runtime_error("missing value for --jobs"); + jobs = parse_jobs_count(argv[++i]); + } else if (!arg.empty() && arg.front() == L'-') { + std::cerr << "usage: compile_dxil --refusals REQUEST_DIRECTORY [--jobs N] [--json]\n"; + return 2; + } else if (has_dir) { + std::cerr << "usage: compile_dxil --refusals REQUEST_DIRECTORY [--jobs N] [--json]\n"; + return 2; + } else { + request_dir = fs::path(arg); + has_dir = true; + } + } + if (!has_dir) { + std::cerr << "usage: compile_dxil --refusals REQUEST_DIRECTORY [--jobs N] [--json]\n"; + return 2; + } + if (!fs::exists(request_dir) || !fs::is_directory(request_dir)) { + std::cerr << "request path must be an existing directory\n"; + return 1; + } + std::vector<fs::path> graphics_inputs, compute_inputs; + for (const auto& file : fs::directory_iterator(request_dir)) { + if (!file.is_regular_file()) + continue; + const auto path = file.path(); + if (path.stem().wstring().rfind(L"req_", 0) != 0) + continue; + if (path.extension() == L".a" || path.extension() == L".rtv") + graphics_inputs.push_back(fs::weakly_canonical(path)); + else if (path.extension() == L".c67") + compute_inputs.push_back(fs::weakly_canonical(path)); + } + std::sort(graphics_inputs.begin(), graphics_inputs.end(), PathLess{}); + dedupe_graphics_markers(graphics_inputs); + std::sort(compute_inputs.begin(), compute_inputs.end(), PathLess{}); + + struct Task { + bool compute; + size_t index; + }; + std::vector<Task> tasks; + tasks.reserve(graphics_inputs.size() + compute_inputs.size()); + for (size_t i = 0; i < graphics_inputs.size(); ++i) + tasks.push_back({false, i}); + for (size_t i = 0; i < compute_inputs.size(); ++i) + tasks.push_back({true, i}); + + std::vector<std::string> results(tasks.size()); + if (!tasks.empty()) { + const int workers_count = (std::min)(jobs, static_cast<int>(tasks.size())); + std::atomic<size_t> next{}; + auto run_worker = [&]() { + for (size_t t = next++; t < tasks.size(); t = next++) { + const auto& task = tasks[t]; + try { + if (task.compute) { + auto req = x2w::read_compute_request(compute_inputs[task.index]); + std::string reason; + if (!x2w::format_compute_runtime_manifest(x2w::translate_compute(req, 0, true), &reason)) + throw std::runtime_error(manifest_refusal(reason)); + } else { + auto input = x2w::read_graphics_request(graphics_inputs[task.index]); + bool hit = false; + auto pair = x2w::prepare_direct_graphics(input.a, input.b, request_dir, hit, + input.root, input.input_layout, input.pixel_entry, + false, input.rtv_formats); + if (!input.rtv_request.empty() && + !x2w::format_graphics_runtime_manifest(pair, input.rtv_request)) + throw std::runtime_error( + "RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + } + } catch (const fs::filesystem_error&) { + results[t] = "unreadable shader request"; + } catch (const std::exception& error) { + results[t] = normalize_refusal_reason(error.what()); + } + } + }; + if (workers_count == 1) { + run_worker(); + } else { + std::vector<std::future<void>> workers; + workers.reserve(workers_count); + for (int w = 0; w < workers_count; ++w) + workers.emplace_back(std::async(std::launch::async, run_worker)); + for (auto& w : workers) + w.get(); + } + } + + struct Section { + unsigned examined = 0, no_refusal = 0, refused = 0; + std::map<std::string, unsigned> counts; + std::vector<std::pair<std::string, unsigned>> sorted_reasons() const { + std::vector<std::pair<std::string, unsigned>> rows(counts.begin(), counts.end()); + std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { + if (a.second != b.second) + return a.second > b.second; + return a.first < b.first; + }); + return rows; + } + } graphics_sec, compute_sec; + + for (size_t t = 0; t < tasks.size(); ++t) { + Section& sec = tasks[t].compute ? compute_sec : graphics_sec; + ++sec.examined; + if (results[t].empty()) { + ++sec.no_refusal; + } else { + ++sec.refused; + ++sec.counts[results[t]]; + } + } + + if (json) { + auto write_json_sec = [](std::ostream& os, const Section& sec) { + os << "{\"examined\":" << sec.examined + << ",\"no_refusal\":" << sec.no_refusal + << ",\"refused\":" << sec.refused + << ",\"reasons\":["; + const auto rows = sec.sorted_reasons(); + for (size_t i = 0; i < rows.size(); ++i) { + if (i) os << ','; + os << "{\"reason\":" << json_escape(rows[i].first) << ",\"count\":" << rows[i].second << '}'; + } + os << "]}"; + }; + std::cout << "{\"graphics\":"; + write_json_sec(std::cout, graphics_sec); + std::cout << ",\"compute\":"; + write_json_sec(std::cout, compute_sec); + std::cout << "}\n"; + } else { + auto write_text_sec = [](std::ostream& os, const char* title, const char* count_label, const Section& sec) { + os << title << '\n' + << count_label << ": " << sec.examined << '\n' + << "No refusal recorded (not compiled): " << sec.no_refusal << '\n' + << "Refused: " << sec.refused << '\n' + << "Count\tReason\n"; + for (const auto& [reason, count] : sec.sorted_reasons()) + os << count << '\t' << reason << '\n'; + }; + write_text_sec(std::cout, "Graphics requests", "Requests examined", graphics_sec); + write_text_sec(std::cout, "Compute requests (device slot 67)", "Compute requests examined", compute_sec); + } + return 0; + } catch (const fs::filesystem_error&) { + std::cerr << "unreadable shader request directory\n"; + return 1; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} + +static bool is_lower_hex16(std::wstring_view text) { + if (text.size() != 16) + return false; + for (wchar_t c : text) + if (!((c >= L'0' && c <= L'9') || (c >= L'a' && c <= L'f'))) + return false; + return true; +} + +static int parse_interval_ms(std::wstring_view number) { + if (number.empty() || number.size() > 5 || number.find_first_not_of(L"0123456789") != number.npos) + throw std::runtime_error("--interval must be between 10 and 60000 ms"); + const int ms = std::stoi(std::wstring(number)); + if (ms < 10 || ms > 60000) + throw std::runtime_error("--interval must be between 10 and 60000 ms"); + return ms; +} + +static bool has_complete_dxbc(const fs::path& path) { + std::error_code ec; + const auto actual = fs::file_size(path, ec); + if (ec || actual < 32 || actual > (256ull << 20)) + return false; + std::ifstream file(path, std::ios::binary); + if (!file) + return false; + unsigned char header[32]{}; + if (!file.read(reinterpret_cast<char*>(header), sizeof(header))) + return false; + if (std::memcmp(header, "DXBC", 4) != 0) + return false; + uint32_t total = 0, parts = 0; + std::memcpy(&total, header + 24, sizeof(total)); + std::memcpy(&parts, header + 28, sizeof(parts)); + return total == actual && parts > 0 && parts <= (total - 32) / 4; +} + +struct WatchRequest { + std::wstring key; + fs::path marker; + bool compute = false; +}; + +static bool read_small_file(const fs::path& path, size_t max_bytes, std::string& out) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file) + return false; + const auto size = file.tellg(); + if (size < 0 || static_cast<size_t>(size) > max_bytes) + return false; + out.assign(static_cast<size_t>(size), '\0'); + file.seekg(0); + return !size || static_cast<bool>(file.read(out.data(), size)); +} + +static bool is_watch_request_pending(const fs::path& request_dir, const WatchRequest& req, bool skip_failed) { + std::error_code ec; + const auto marker_mtime = fs::last_write_time(req.marker, ec); + if (ec) + return false; + const fs::path stem = request_dir / req.key; + const fs::path manifest_path = fs::path(stem) += L".txt"; + const fs::path fail_path = fs::path(stem) += L".fail"; + const fs::path psdep_path = fs::path(stem) += L".psdep"; + + std::optional<fs::file_time_type> psin_mtime; + bool dependency_changed = false; + bool lost = false; + bool sidecar_changed = false; + if (!req.compute) { + if (const auto psin_path = graphics_psin_path(req.marker)) { + const auto packed_path = fs::path(*psin_path).replace_extension(L".ps57in"); + const bool stream = fs::is_regular_file(*psin_path, ec); + const bool packed = fs::is_regular_file(packed_path, ec); + if (stream || packed) { + const auto time = fs::last_write_time(stream ? *psin_path : packed_path, ec); + if (!ec) + psin_mtime = time; + } + const bool has_psdep = fs::is_regular_file(psdep_path, ec); + std::string published_dep; + if (has_psdep && (!read_small_file(psdep_path, 256, published_dep) || published_dep.empty())) { + sidecar_changed = true; + } else { + try { + const std::string current_dep = + x2w::read_pixel_input_description(fs::path(*psin_path).replace_extension(L".a")); + sidecar_changed = current_dep != published_dep; + } catch (const std::exception&) { + sidecar_changed = true; + } + } + } + lost = !psin_mtime.has_value() && fs::is_regular_file(psdep_path, ec); + } + + const bool has_manifest = fs::is_regular_file(manifest_path, ec); + if (has_manifest && !sidecar_changed && !lost && !dependency_changed) { + if (req.compute) { + // A native manifest from another revision, or an unmarked one without the Python translator's + // <key>.cs.hlsl, is stale. Other outputs, and a manifest that cannot be read, go on to the usual + // timestamp and bytecode checks. + if (std::ifstream file{manifest_path, std::ios::binary}) { + const std::string manifest((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); + const auto output = x2w::native_compute_output(manifest); + const bool python = fs::is_regular_file(fs::path(stem) += L".cs.hlsl", ec); + if (output == x2w::NativeComputeOutput::incompatible || + (output == x2w::NativeComputeOutput::unmarked && !python)) + return true; + } + } + const auto manifest_mtime = fs::last_write_time(manifest_path, ec); + if (!ec && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) { + if (req.compute) { + if (has_complete_dxbc(fs::path(stem) += L".cs.cso")) + return false; + } else { + if (has_complete_dxbc(fs::path(stem) += L".vs.cso") && + has_complete_dxbc(fs::path(stem) += L".ps.cso")) + return false; + } + } + } + + const bool recheck = sidecar_changed && has_manifest; + if (skip_failed && !recheck && fs::is_regular_file(fail_path, ec)) { + const auto fail_mtime = fs::last_write_time(fail_path, ec); + const auto latest_input = + (psin_mtime.has_value() && *psin_mtime > marker_mtime) ? *psin_mtime : marker_mtime; + if (!ec && fail_mtime >= latest_input) + return false; + } + return true; +} + +static std::vector<WatchRequest> collect_watch_requests(const fs::path& request_dir, bool skip_failed) { + std::vector<WatchRequest> found; + for (const auto& file : fs::directory_iterator(request_dir)) { + std::error_code ec; + if (!file.is_regular_file(ec)) + continue; + const auto path = file.path(); + const auto ext = path.extension().wstring(); + const bool is_compute = ext == L".c67"; + if (!is_compute && ext != L".a" && ext != L".rtv") + continue; + const auto stem = path.stem().wstring(); + if (stem.size() != 20 || stem.rfind(L"req_", 0) != 0) + continue; + const auto key = stem.substr(4); + if (!is_lower_hex16(key)) + continue; + found.push_back({key, fs::weakly_canonical(path), is_compute}); + } + std::sort(found.begin(), found.end(), [](const WatchRequest& a, const WatchRequest& b) { + return PathLess{}(a.marker, b.marker); + }); + for (size_t i = 0; i + 1 < found.size();) { + if (!found[i].compute && !found[i + 1].compute && found[i].marker.extension() == L".a" && + found[i + 1].marker.extension() == L".rtv" && found[i].key == found[i + 1].key) + found.erase(found.begin() + i); + else + ++i; + } + std::vector<WatchRequest> pending; + for (auto& req : found) { + if (is_watch_request_pending(request_dir, req, skip_failed)) + pending.push_back(std::move(req)); + } + return pending; +} + +static const char* compile_watch_item(x2w::ShaderDxilCompiler& compiler, const fs::path& cache_dir, + const fs::path& request_dir, const WatchRequest& req) { + const fs::path stem = request_dir / req.key; + const fs::path manifest_path = fs::path(stem) += L".txt"; + const fs::path fail_path = fs::path(stem) += L".fail"; + std::error_code ignored; + fs::remove(manifest_path, ignored); + std::ostringstream sink; + if (req.compute) { + // A Python translation's sidecar must not outlive its manifest: the stand-in reads an unmarked manifest + // next to a <key>.cs.hlsl as the Python translator's output. + fs::remove(fs::path(stem) += L".cs.hlsl", ignored); + bool hit = false; + auto program = x2w::prepare_direct_compute(req.marker, 0, false, cache_dir, hit, x2w::HeapViewContract::none); + std::string reason; + auto manifest = x2w::format_compute_runtime_manifest(program, &reason); + if (!manifest) + throw std::runtime_error(manifest_refusal(reason)); + auto cs_dxil = compile_to_dxil(compiler, program.dxil_ir, L"cs_6_6", cache_dir, true, sink); + publish_atomic(fs::path(stem) += L".cs.cso", cs_dxil.data(), cs_dxil.size()); + publish_atomic(manifest_path, manifest->data(), manifest->size()); + fs::remove(fail_path, ignored); + return "compiled compute"; + } + auto input = x2w::read_graphics_request(req.marker); + bool hit = false; + auto pair = x2w::prepare_direct_graphics(input.a, input.b, cache_dir, hit, input.root, input.input_layout, + input.pixel_entry, true, input.rtv_formats); + auto manifest = x2w::format_graphics_runtime_manifest(pair, input.rtv_request); + if (!manifest) + throw std::runtime_error( + input.rtv_request.empty() + ? "unsupported startup runtime manifest bindings" + : "RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", cache_dir, true, sink); + auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", cache_dir, true, sink); + publish_atomic(fs::path(stem) += L".vs.cso", vs_dxil.data(), vs_dxil.size()); + publish_atomic(fs::path(stem) += L".ps.cso", ps_dxil.data(), ps_dxil.size()); + const fs::path psdep_path = fs::path(stem) += L".psdep"; + if (!input.pixel_input_description.empty()) + publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); + else + fs::remove(psdep_path, ignored); + publish_atomic(manifest_path, manifest->data(), manifest->size()); + fs::remove(fail_path, ignored); + return "compiled graphics"; +} + +static int run_watch(int argc, wchar_t** argv) { + fs::path sdk_dir, cache_dir, request_dir; + int positional = 0; + int jobs = 1; + int interval_ms = 2000; + bool once = false; + auto usage = []() { + std::cerr << "usage: compile_dxil --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY " + "[--jobs N] [--interval MS] [--once]\n"; + return 2; + }; + try { + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--once") { + once = true; + } else if (arg == L"--jobs") { + if (i + 1 >= argc) + throw std::runtime_error("missing value for --jobs"); + jobs = parse_jobs_count(argv[++i]); + } else if (arg == L"--interval") { + if (i + 1 >= argc) + throw std::runtime_error("missing value for --interval"); + interval_ms = parse_interval_ms(argv[++i]); + } else if (!arg.empty() && arg.front() == L'-') { + return usage(); + } else { + if (positional == 0) sdk_dir = fs::path(arg); + else if (positional == 1) cache_dir = fs::path(arg); + else if (positional == 2) request_dir = fs::path(arg); + else return usage(); + ++positional; + } + } + if (positional != 3) + return usage(); + if (!fs::exists(sdk_dir) || !fs::is_directory(sdk_dir)) { + std::cerr << "SDK path must be an existing directory\n"; + return 1; + } + if (!fs::exists(request_dir) || !fs::is_directory(request_dir)) { + std::cerr << "request path must be an existing directory\n"; + return 1; + } + request_dir = fs::weakly_canonical(request_dir); + fs::create_directories(cache_dir); + cache_dir = fs::weakly_canonical(cache_dir); + + x2w::ShaderDxilCompiler coordinator(sdk_dir); + bool skip_failed = false; + while (true) { + std::vector<WatchRequest> pending; + try { + pending = collect_watch_requests(request_dir, skip_failed); + } catch (const fs::filesystem_error& error) { + if (once) + throw; + std::cerr << "watch scan error, retrying: " << error.what() << '\n'; + std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); + continue; + } + if (!pending.empty()) { + std::vector<std::string> outcomes(pending.size()); + auto process_item = [&](x2w::ShaderDxilCompiler& compiler, size_t idx) { + const auto& req = pending[idx]; + try { + outcomes[idx] = compile_watch_item(compiler, cache_dir, request_dir, req); + } catch (const std::exception& error) { + const std::string line = format_fail_line(error.what()); + try { + publish_atomic((request_dir / req.key) += L".fail", line.data(), line.size()); + } catch (...) { + } + std::string summary = line; + if (!summary.empty() && summary.back() == '\n') + summary.pop_back(); + outcomes[idx] = "refused: " + summary; + } + }; + const int worker_count = (std::min)(jobs, static_cast<int>(pending.size())); + if (worker_count <= 1) { + for (size_t idx = 0; idx < pending.size(); ++idx) + process_item(coordinator, idx); + } else { + std::atomic<size_t> next{}; + std::vector<std::future<void>> workers; + workers.reserve(worker_count); + for (int w = 0; w < worker_count; ++w) { + workers.emplace_back(std::async(std::launch::async, [&]() { + auto compiler = coordinator.new_worker(); + for (size_t idx = next++; idx < pending.size(); idx = next++) + process_item(compiler, idx); + })); + } + for (auto& w : workers) + w.get(); + } + for (size_t idx = 0; idx < pending.size(); ++idx) { + std::string key_ascii; + key_ascii.reserve(pending[idx].key.size()); + for (wchar_t ch : pending[idx].key) + key_ascii.push_back(static_cast<char>(ch)); + std::cout << key_ascii << ": " << outcomes[idx] << '\n'; + } + std::cout.flush(); + } + if (once) + return 0; + skip_failed = true; + std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms)); + } + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} + +static std::string format_key16(uint64_t key) { + char buf[20]; + std::snprintf(buf, sizeof(buf), "%016llx", static_cast<unsigned long long>(key)); + return std::string(buf); +} + +static fs::path rekey_request_path(const fs::path& dir, const std::string& hex16, const char* ext) { + return dir / ("req_" + hex16 + ext); +} + +static bool read_rekey_bytes(const fs::path& path, size_t max_bytes, std::string& out, std::string& error) { + std::error_code ec; + if (!fs::is_regular_file(path, ec)) { + error = "unreadable " + path.filename().string() + ": not a regular file"; + return false; + } + const auto file_bytes = fs::file_size(path, ec); + if (ec || file_bytes > max_bytes) { + error = "unreadable " + path.filename().string() + ": " + (ec ? ec.message() : "oversized file"); + return false; + } + std::ifstream file(path, std::ios::binary); + if (!file) { + error = "unreadable " + path.filename().string() + ": cannot open"; + return false; + } + out.assign(static_cast<size_t>(file_bytes), '\0'); + if (file_bytes && !file.read(out.data(), static_cast<std::streamsize>(file_bytes))) { + error = "unreadable " + path.filename().string() + ": short read"; + return false; + } + return true; +} + +static void publish_rekey_file(const fs::path& dst_file, const void* data, size_t size, + size_t& written, size_t& kept) { + std::error_code ec; + if (fs::exists(dst_file, ec)) { + ++kept; + return; + } + if (ec) + throw fs::filesystem_error("cannot inspect destination file", dst_file, ec); + publish_atomic(dst_file, data, size); + ++written; +} + +static int run_rekey(int argc, wchar_t** argv) { + fs::path src_dir, dst_dir; + int positional = 0; + unsigned hw_threads = std::thread::hardware_concurrency(); + int jobs = static_cast<int>((std::min)(64u, (std::max)(1u, hw_threads))); + auto usage = []() { + std::cerr << "usage: compile_dxil --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N]\n"; + return 2; + }; + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--jobs") { + if (i + 1 >= argc) + return usage(); + try { + jobs = parse_jobs_count(argv[++i]); + } catch (const std::exception& error) { + std::cerr << "error: " << error.what() << '\n'; + return 2; + } + } else if (!arg.empty() && arg.front() == L'-') { + return usage(); + } else { + if (positional == 0) src_dir = fs::path(arg); + else if (positional == 1) dst_dir = fs::path(arg); + else return usage(); + ++positional; + } + } + if (positional != 2) + return usage(); + + std::error_code ec; + if (!fs::is_directory(src_dir, ec)) { + std::cerr << "error: " << src_dir.string() << " is not a directory\n"; + return 2; + } + if (fs::exists(dst_dir, ec)) { + if (!fs::is_directory(dst_dir, ec)) { + std::cerr << "error: " << dst_dir.string() << " is not a directory\n"; + return 2; + } + if (fs::equivalent(src_dir, dst_dir, ec)) { + std::cerr << "error: the new request dir must not be the old cache\n"; + return 2; + } + } else if (ec) { + std::cerr << "error: cannot inspect " << dst_dir.string() << ": " << ec.message() << '\n'; + return 2; + } + + enum class Kind { graphics, compute, m57 }; + struct Marker { + Kind kind; + uint64_t old_key = 0; + std::string old_hex; + }; + struct RtvMarker { + uint64_t old_key = 0; + std::string old_hex; + }; + + std::vector<Marker> graphics_markers, compute_markers, m57_markers; + std::vector<RtvMarker> rtv_markers; + size_t m86_count = 0; + + try { + for (const auto& entry : fs::directory_iterator(src_dir)) { + if (!entry.is_regular_file(ec)) { + ec.clear(); + continue; + } + const fs::path path = entry.path(); + const std::wstring wname = path.filename().wstring(); + if (wname.size() < 22 || wname.rfind(L"req_", 0) != 0) + continue; + const std::wstring wstem = path.stem().wstring(); + if (wstem.size() != 20) + continue; + const std::wstring_view whex = std::wstring_view(wstem).substr(4); + if (!is_lower_hex16(whex)) + continue; + std::string hex16; + hex16.reserve(16); + for (wchar_t ch : whex) + hex16.push_back(static_cast<char>(ch)); + uint64_t old_key = 0; + const auto parsed = std::from_chars(hex16.data(), hex16.data() + hex16.size(), old_key, 16); + if (parsed.ec != std::errc{} || parsed.ptr != hex16.data() + hex16.size()) + continue; + const std::wstring ext = path.extension().wstring(); + if (ext == L".a") + graphics_markers.push_back({Kind::graphics, old_key, std::move(hex16)}); + else if (ext == L".c67") + compute_markers.push_back({Kind::compute, old_key, std::move(hex16)}); + else if (ext == L".m57") + m57_markers.push_back({Kind::m57, old_key, std::move(hex16)}); + else if (ext == L".rtv") + rtv_markers.push_back({old_key, std::move(hex16)}); + else if (ext == L".m86") + ++m86_count; + } + } catch (const fs::filesystem_error& error) { + std::cerr << "error: cannot list " << src_dir.string() << ": " << error.what() << '\n'; + return 1; + } + + auto by_old_key = [](const auto& a, const auto& b) { return a.old_key < b.old_key; }; + std::sort(graphics_markers.begin(), graphics_markers.end(), by_old_key); + std::sort(compute_markers.begin(), compute_markers.end(), by_old_key); + std::sort(m57_markers.begin(), m57_markers.end(), by_old_key); + std::sort(rtv_markers.begin(), rtv_markers.end(), by_old_key); + + std::vector<Marker> work; + work.reserve(graphics_markers.size() + compute_markers.size() + m57_markers.size()); + work.insert(work.end(), graphics_markers.begin(), graphics_markers.end()); + work.insert(work.end(), compute_markers.begin(), compute_markers.end()); + work.insert(work.end(), m57_markers.begin(), m57_markers.end()); + + struct WorkResult { + uint64_t new_key = 0; + bool has_ia = false; + bool has_psin = false; + std::string rewritten_psin; + std::string error; + }; + std::vector<WorkResult> results(work.size()); + + auto hash_item = [&](size_t idx) { + const Marker& m = work[idx]; + WorkResult& res = results[idx]; + std::string err; + try { + if (m.kind == Kind::graphics) { + std::string a, b, root, ia, psin_raw; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".b"), 64ull << 20, b, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), 16ull << 20, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".a"), 64ull << 20, a, err)) { + res.error = std::move(err); + return; + } + const fs::path ia_path = rekey_request_path(src_dir, m.old_hex, ".ia"); + std::error_code file_ec; + if (fs::is_regular_file(ia_path, file_ec)) { + if (!read_rekey_bytes(ia_path, 1ull << 20, ia, err)) { + res.error = std::move(err); + return; + } + res.has_ia = true; + } + const fs::path psin_path = rekey_request_path(src_dir, m.old_hex, ".psin"); + std::string psin_entry; + if (fs::is_regular_file(psin_path, file_ec)) { + if (!read_rekey_bytes(psin_path, 128, psin_raw, err)) { + res.error = std::move(err); + return; + } + auto parsed_psin = x2w::parse_pixel_input_description(psin_raw, m.old_key); + psin_entry = std::move(parsed_psin.entry); + res.has_psin = true; + res.new_key = x2w::graphics_request_key(a, b, root, ia, psin_entry); + res.rewritten_psin = x2w::format_pixel_input_description(res.new_key, parsed_psin.ena, parsed_psin.addr); + } else { + res.new_key = x2w::graphics_request_key(a, b, root, ia); + } + } else if (m.kind == Kind::compute) { + std::string desc, sa, sb, data, root, c67; + constexpr size_t limit = 64ull << 20; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".desc"), limit, desc, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".sa"), limit, sa, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".sb"), limit, sb, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".data"), limit, data, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), limit, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".c67"), limit, c67, err)) { + res.error = std::move(err); + return; + } + res.new_key = x2w::compute_request_key(c67, data, root, desc, sa, sb); + } else { + std::string ps57, root, m57; + constexpr size_t limit = 64ull << 20; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".ps57"), limit, ps57, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), limit, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".m57"), limit, m57, err)) { + res.error = std::move(err); + return; + } + res.new_key = x2w::mesh57_request_key(m57, ps57, root); + } + } catch (const std::exception& ex) { + res.error = ex.what(); + } + }; + + if (!work.empty()) { + const int worker_count = (std::min)(jobs, static_cast<int>(work.size())); + if (worker_count <= 1) { + for (size_t i = 0; i < work.size(); ++i) + hash_item(i); + } else { + std::atomic<size_t> next{}; + std::vector<std::future<void>> workers; + workers.reserve(worker_count); + for (int w = 0; w < worker_count; ++w) { + workers.emplace_back(std::async(std::launch::async, [&]() { + for (size_t i = next++; i < work.size(); i = next++) + hash_item(i); + })); + } + for (auto& w : workers) + w.get(); + } + } + + std::vector<std::string> bad; + std::map<uint64_t, uint64_t> new_graphics_map; + for (size_t i = 0; i < work.size(); ++i) { + if (!results[i].error.empty()) { + bad.push_back("req_" + work[i].old_hex + ": " + results[i].error); + } else if (work[i].kind == Kind::graphics) { + new_graphics_map[work[i].old_key] = results[i].new_key; + } + } + + std::map<uint64_t, std::string> rtv_rewritten; + for (const auto& rm : rtv_markers) { + std::string raw, err; + if (!read_rekey_bytes(rekey_request_path(src_dir, rm.old_hex, ".rtv"), 256, raw, err)) { + bad.push_back("req_" + rm.old_hex + ".rtv: " + err); + continue; + } + try { + const auto parsed = x2w::parse_rtv_variant_text(raw, rm.old_key); + const auto it = new_graphics_map.find(parsed.base_key); + if (it == new_graphics_map.end()) { + bad.push_back("req_" + rm.old_hex + ".rtv: .rtv base request " + format_key16(parsed.base_key) + + " is not a complete graphics request"); + continue; + } + std::string rewritten = x2w::format_rtv_variant_text(it->second, parsed.formats); + const uint64_t new_rtv_key = x2w::fnv1a_64(rewritten); + rtv_rewritten.try_emplace(new_rtv_key, std::move(rewritten)); + } catch (const std::exception& ex) { + bad.push_back("req_" + rm.old_hex + ".rtv: " + ex.what()); + } + } + + if (!bad.empty()) { + std::cerr << "error: " << bad.size() << " of " << (work.size() + rtv_markers.size()) + << " requests are incomplete or unreadable; nothing written\n"; + const size_t limit = (std::min)(bad.size(), size_t{10}); + for (size_t i = 0; i < limit; ++i) + std::cerr << " " << bad[i] << '\n'; + return 1; + } + + try { + fs::create_directories(dst_dir); + size_t written = 0, kept = 0; + + const size_t gfx_end = graphics_markers.size(); + const size_t cmp_end = gfx_end + compute_markers.size(); + const size_t m57_end = cmp_end + m57_markers.size(); + + auto publish_group = [&](size_t begin, size_t end, const char* label) { + std::set<uint64_t> done_keys; + size_t already_current = 0; + for (size_t i = begin; i < end; ++i) { + const Marker& m = work[i]; + const WorkResult& res = results[i]; + if (m.old_key == res.new_key) + ++already_current; + if (!done_keys.insert(res.new_key).second) + continue; + const std::string new_hex = format_key16(res.new_key); + auto copy_part = [&](const char* ext, size_t max_bytes) { + const fs::path dst_file = rekey_request_path(dst_dir, new_hex, ext); + std::error_code file_ec; + if (fs::exists(dst_file, file_ec)) { + ++kept; + return; + } + if (file_ec) + throw fs::filesystem_error("cannot inspect destination file", dst_file, file_ec); + std::string bytes, err; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ext), max_bytes, bytes, err)) + throw std::runtime_error(err); + publish_atomic(dst_file, bytes.data(), bytes.size()); + ++written; + }; + if (m.kind == Kind::graphics) { + copy_part(".b", 64ull << 20); + copy_part(".root", 16ull << 20); + if (res.has_ia) + copy_part(".ia", 1ull << 20); + if (res.has_psin) + publish_rekey_file(rekey_request_path(dst_dir, new_hex, ".psin"), + res.rewritten_psin.data(), res.rewritten_psin.size(), written, kept); + copy_part(".a", 64ull << 20); + } else if (m.kind == Kind::compute) { + constexpr size_t limit = 64ull << 20; + copy_part(".desc", limit); + copy_part(".sa", limit); + copy_part(".sb", limit); + copy_part(".data", limit); + copy_part(".root", limit); + copy_part(".c67", limit); + } else { + constexpr size_t limit = 64ull << 20; + copy_part(".ps57", limit); + copy_part(".root", limit); + copy_part(".m57", limit); + } + } + std::cout << label << ": " << (end - begin) << " requests, " << already_current + << " already current -> " << done_keys.size() << " keys\n"; + }; + + publish_group(0, gfx_end, "graphics"); + publish_group(gfx_end, cmp_end, "compute"); + publish_group(cmp_end, m57_end, "m57"); + for (const auto& [new_key, text] : rtv_rewritten) + publish_rekey_file(rekey_request_path(dst_dir, format_key16(new_key), ".rtv"), + text.data(), text.size(), written, kept); + std::cout << "rtv variants: " << rtv_markers.size() << " requests -> " << rtv_rewritten.size() << " keys\n"; + std::cout << "not re-keyed (own key strings): m86 " << m86_count << '\n'; + std::cout << "files: " << written << " written, " << kept << " already present in " << dst_dir.string() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << "error: failed writing " << dst_dir.string() << ": " << error.what() << '\n'; + return 1; + } +} + +int wmain(int argc, wchar_t** argv) { + if (argc >= 2 && std::wstring_view(argv[1]) == L"--rekey") + return run_rekey(argc, argv); + if (argc >= 2 && std::wstring_view(argv[1]) == L"--watch") + return run_watch(argc, argv); + if (argc >= 2 && std::wstring_view(argv[1]) == L"--refusals") + return run_refusals(argc, argv); + if (argc == 5 && std::wstring_view(argv[1]) == L"--prepare-compute-pack") { + try { + std::wstring number(argv[4]); + if (number.empty() || number.size() > 7 || number.find_first_not_of(L"0123456789") != number.npos) + throw std::runtime_error("invalid compute entry byte offset"); + auto start = Clock::now(); + auto counts = x2w::build_compute_frontend_pack(argv[2], argv[3], static_cast<unsigned>(std::stoul(number))); + for (const auto &error : counts.errors) std::cerr << "unprepared " << error << "\n"; + std::cout << "prepared=" << counts.prepared << " unsupported=" << counts.unsupported + << " errors=" << counts.errors.size() << " elapsed_ms=" << std::chrono::duration<double,std::milli>(Clock::now()-start).count() << "\n"; + return counts.errors.empty() ? 0 : 1; + } catch (const std::exception &error) { + std::cerr << "pack not published: " << error.what() << "\n"; + return 1; + } + } + if (argc == 4 && std::wstring_view(argv[1]) == L"--index-graphics-interfaces") { + try { + const auto stages = x2w::index_graphics_interfaces(argv[2],argv[3]); + std::cout << "indexed_graphics_containers=" << stages << "\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << "\n"; + return 1; + } + } + const bool parallel = argc > 3 && std::wstring_view(argv[3]) == L"--jobs"; + const int profile_index = parallel ? 5 : 3; + const int first = profile_index+1; + const bool directory = argc > first && std::wstring_view(argv[first]) == L"--requests"; + if (directory ? argc != first+3 : (argc < first+2 || (argc-first)%2)) { + std::cerr << "usage: compile_dxil SDK_DIRECTORY CACHE_DIRECTORY [--jobs N] PROFILE INPUT OUTPUT.cso [INPUT OUTPUT ...]\n" + "Use a DXC profile for HLSL, gfx1013-constant-ps or gfx1013-rgb11-r16-ps for a raw pixel program, or\n" + "gfx1013-vertex-id-vs or gfx1013-buffered-vs for a raw vertex program. gfx1013-sampled-pair takes one VS and one PS (in order).\n" + "gfx1013-buffered-pair takes a buffered vertex program and a pixel HLSL source.\n" + "gfx1013-group-clear@BYTE_OFFSET and gfx1013-compute-wave32@BYTE_OFFSET take a req_<key>.c67.\n" + "Direct DXIL profiles: gfx1013-direct-cs@BYTE_OFFSET, gfx1013-container-cs, gfx1013-container-vs, gfx1013-container-ps, gfx1013-container-ms.\n" + "gfx1013-raw-ms reads guest mesh bytes and an explicit .mslayout sidecar.\n" + "gfx1013-raw-mesh-ps uses a reviewed .pslayout sidecar (meshps1 or meshps2).\n" + "gfx1013-container-cs reads an optional req_<key>.views next to the .cdx (GPU-selected heap slot view types).\n" + "gfx1013-container-pair accepts two containers and emits VS then PS using the runtime register allocation.\n" + "For capture directories use PROFILE --requests DIRECTORY OUTPUT_DIRECTORY. " + "gfx1013-container-pair also takes each req_<key>.rtv (rtv1 BASE_KEY FORMAT ...) and publishes it under its key.\n" + "gfx1013-container-rect also emits the rectangle geometry stage.\n" + "Use --refusals REQUEST_DIRECTORY [--jobs N] [--json] for a read-only refusal summary.\n" + "Use --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once] to translate pending requests.\n" + "Use --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] to copy requests under the current cache revision keys.\n" + "Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY to index native graphics interfaces.\n" + "Use --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY ENTRY_BYTE_OFFSET for captured compute.\n"; + return 2; + } + try { + const std::wstring_view profile = argv[profile_index]; + const bool rectangles=profile==L"gfx1013-container-rect"; + if(rectangles && !directory) throw std::runtime_error("rectangle compilation takes a graphics request directory"); + const bool direct_pair = profile == L"gfx1013-container-pair" || rectangles; + const bool graphics_batch = directory && direct_pair; + const bool compute_request = profile.rfind(L"gfx1013-group-clear@",0)==0 || + profile.rfind(L"gfx1013-compute-wave32@",0)==0 || profile.rfind(L"gfx1013-direct-cs@",0)==0 || profile==L"gfx1013-container-cs"; + std::vector<fs::path> inputs, outputs, stems; + if (directory) { + if (!compute_request && !graphics_batch) throw std::runtime_error("profile does not take capture directories"); + const auto extension = graphics_batch ? L".a" : profile == L"gfx1013-container-cs" ? L".cdx" : L".c67"; + for (const auto& file : fs::directory_iterator(argv[first+1])) { + const auto path = file.path(); + // An RTV variant (req_<key>.rtv) is a request of its own, translated from its base request's parts. + const bool marker = path.extension()==extension || (graphics_batch && !rectangles && path.extension()==L".rtv"); + if (file.is_regular_file() && marker && path.stem().wstring().rfind(L"req_",0)==0) + inputs.push_back(fs::weakly_canonical(path)); + } + if (inputs.empty()) throw std::runtime_error("no ready shader requests"); + std::sort(inputs.begin(),inputs.end()); + dedupe_graphics_markers(inputs); + fs::create_directories(argv[first+2]); + for (const auto& path : inputs) { + auto key_stem = path.stem().wstring().substr(4); + if (key_stem.empty()) key_stem = L"_invalid"; + stems.push_back(fs::weakly_canonical(fs::path(argv[first+2]) / key_stem)); + outputs.push_back(fs::path(stems.back()) += (graphics_batch ? L".vs.cso" : L".cs.cso")); + } + } else { + for(int i=first;i<argc;i+=2) { + inputs.push_back(fs::weakly_canonical(fs::absolute(argv[i]))); + outputs.push_back(fs::weakly_canonical(fs::absolute(argv[i+1]))); + } + } + const int count = static_cast<int>(inputs.size()); + const bool sampled_pair = std::wstring_view(argv[profile_index]) == L"gfx1013-sampled-pair"; + const bool buffered_pair = std::wstring_view(argv[profile_index]) == L"gfx1013-buffered-pair"; + if (!directory && (direct_pair || sampled_pair || buffered_pair) && count != 2) throw std::runtime_error("graphics pair requires a vertex and a pixel job"); + std::optional<x2w::DirectGraphicsPair> linked; + if (direct_pair && !directory) { + bool hit = false; + linked = x2w::prepare_direct_graphics(x2w::read_shader_container_bytes(inputs[0]), + x2w::read_shader_container_bytes(inputs[1]), argv[2], hit); + std::cout << "graphics_pair frontend_cache_hit=" << hit << "\n"; + } + auto linked_stage=[&](int index)->const x2w::NativeComputeShader*{ + if(!linked)return nullptr; + return index?&linked->pixel:&linked->vertex; + }; + const auto job_profile = [&](int index) -> const wchar_t* { + if(direct_pair)return index?L"gfx1013-container-ps":L"gfx1013-container-vs"; + if (sampled_pair) return index == 0 ? L"gfx1013-vertex-id-vs" : L"gfx1013-rgb11-r16-ps"; + if (buffered_pair) return index == 0 ? L"gfx1013-buffered-vs" : L"ps_6_0"; + return argv[profile_index]; + }; + int jobs=1; + if (parallel) + jobs = (std::min)(parse_jobs_count(argv[4]), count); + auto start=Clock::now(); + std::set<fs::path,PathLess> occupied(inputs.begin(),inputs.end()); + if(profile==L"gfx1013-raw-ms" || profile==L"gfx1013-raw-mesh-ps") { + for (const auto& input : inputs) { + const auto layout = profile==L"gfx1013-raw-ms" ? L".mslayout" : L".pslayout"; + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(layout))); + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(L".root"))); + } + } + if(compute_request) { + for(const auto& input : inputs) { + for(auto suffix : {L".root",L".data",L".sa",L".sb",L".desc",L".views"}) + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(suffix))); + } + } + if(graphics_batch) { + for(const auto& input : inputs) { + for(auto suffix : {L".b",L".root",L".ia",L".psin",L".ps57in"}) + occupied.insert(fs::weakly_canonical(fs::path(input).replace_extension(suffix))); + } + } + auto reserve_output = [&](const fs::path& path) { + if(!occupied.insert(path).second) + throw std::runtime_error("parallel outputs must be distinct from all inputs and other outputs"); + }; + for(int i=0;i<count;++i) { + reserve_output(outputs[i]); + if(directory) { + reserve_output(fs::path(stems[i]) += L".txt"); + reserve_output(fs::path(stems[i]) += L".fail"); + if(graphics_batch) { + reserve_output(fs::path(stems[i]) += L".ps.cso"); + reserve_output(fs::path(stems[i]) += L".psdep"); + if(rectangles) reserve_output(fs::path(stems[i]) += L".gs.cso"); + } + } + } + auto compile_job = [&](x2w::ShaderDxilCompiler &compiler, int i, std::ostream &report) { + if (!graphics_batch) { + if (!directory) { + compile_one(compiler, job_profile(i), inputs[i], outputs[i], argv[2], report, linked_stage(i)); + return; + } + const fs::path manifest_path = fs::path(stems[i]) += L".txt"; + std::error_code ignored; + fs::remove(manifest_path, ignored); + fs::remove(fs::path(stems[i]) += L".cs.hlsl", ignored); // see compile_watch_item + std::string reason; + auto manifest = compile_one(compiler, job_profile(i), inputs[i], outputs[i], argv[2], report, nullptr, true, &reason); + if (manifest) publish_atomic(manifest_path, manifest->data(), manifest->size()); + // Not a .fail: that file is the watchers' retry marker, and this compile succeeded. + if (!manifest && !reason.empty()) + report << "no_manifest input=" << inputs[i].filename().string() << ' ' << manifest_refusal(reason) << '\n'; + fs::remove(fs::path(stems[i]) += L".fail", ignored); + return; + } + const fs::path manifest_path = fs::path(stems[i]) += L".txt"; + const fs::path psdep_path = fs::path(stems[i]) += L".psdep"; + std::error_code ignored; + fs::remove(manifest_path, ignored); + auto input = x2w::read_graphics_request(inputs[i]); + bool hit = false; + auto pair = x2w::prepare_direct_graphics(input.a, input.b, argv[2], hit, input.root, input.input_layout, input.pixel_entry, + true, input.rtv_formats); + report << "graphics_pair frontend_cache_hit=" << hit << '\n'; + if (!input.rtv_request.empty()) { + report << "rtv_variant " << input.rtv_request << " types="; + for (size_t t = 0; t < input.rtv_formats.size(); ++t) + report << (t ? "," : "") << (pair.target_components[t] == 5 ? "u32" : pair.target_components[t] == 4 ? "i32" : "f32"); + report << '\n'; + } + auto manifest = rectangles ? std::nullopt : x2w::format_graphics_runtime_manifest(pair, input.rtv_request); + // A base pair without a manifest still publishes its stages. A variant is of use to the runtime only. + if (!manifest && !input.rtv_request.empty()) + throw std::runtime_error("RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described"); + std::vector<unsigned char> gs_dxil; + if (rectangles || (manifest && !pair.input_layout.empty())) { + std::string ir; + try { ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } + catch (const x2w::UnsupportedComputeShader&) { if (rectangles) throw; } + if (!ir.empty()) { + gs_dxil = compile_to_dxil(compiler, ir, L"gs_6_6", argv[2], true, report); + if (manifest) *manifest += "fixedrectgs\n"; + } + } + auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", argv[2], true, report); + auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", argv[2], true, report); + if (!gs_dxil.empty()) + publish_atomic(fs::path(stems[i]) += L".gs.cso", gs_dxil.data(), gs_dxil.size()); + publish_atomic(outputs[i], vs_dxil.data(), vs_dxil.size()); + publish_atomic(fs::path(stems[i]) += L".ps.cso", ps_dxil.data(), ps_dxil.size()); + if (manifest) { + if (!input.pixel_input_description.empty()) + publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); + else + fs::remove(psdep_path, ignored); + publish_atomic(manifest_path, manifest->data(), manifest->size()); + } + fs::remove(fs::path(stems[i]) += L".fail", ignored); + }; + if(jobs==1 && !directory) { + x2w::ShaderDxilCompiler compiler(argv[1]); + std::cout << "compiler_init_ms=" << elapsed_ms(start) << '\n'; + for(int i=0;i<count;++i) + compile_job(compiler, i, std::cout); + return 0; + } + std::atomic<int> next{}; + std::vector<std::string> reports(count), errors(count); + x2w::ShaderDxilCompiler coordinator(argv[1]); + std::cout << "compiler_init_ms=" << elapsed_ms(start) << '\n'; + std::vector<std::future<void>> workers; + for(int w=0;w<jobs;++w) { + workers.emplace_back(std::async(std::launch::async,[&] { + auto init=Clock::now(); + auto compiler=coordinator.new_worker(); + double init_ms=elapsed_ms(init); + for(int i=next++;i<count;i=next++) { + std::ostringstream report; + if(init_ms>=0) { report << "worker_init_ms=" << init_ms << '\n'; init_ms=-1; } + try { compile_job(compiler, i, report); } + catch(const std::exception& error) { + errors[i]=error.what(); + if (directory) { + try { + const auto line = format_fail_line(errors[i]); + publish_atomic(fs::path(stems[i]) += L".fail", line.data(), line.size()); + } catch (...) { + } + } + } + reports[i]=report.str(); + } + })); + } + for(auto& worker:workers) worker.get(); + int rejected=0; + for(int i=0;i<count;++i) { + std::cout << "job=" << i+1 << '\n' << reports[i]; + if(!errors[i].empty()) { + ++rejected; + std::cerr << "job=" << i+1 << " input=" << inputs[i].filename().string() << " " << errors[i] << '\n'; + } + } + std::cout << "batch_ms=" << elapsed_ms(start) << " workers=" << jobs << '\n'; + if(directory) std::cout << "requests=" << count << " compiled=" << count-rejected << " refused=" << rejected << '\n'; + return rejected ? 1 : 0; + } catch(const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tools/startup/compile_lds_request.py b/tools/startup/compile_lds_request.py new file mode 100644 index 0000000000..621323f88c --- /dev/null +++ b/tools/startup/compile_lds_request.py @@ -0,0 +1,266 @@ +"""Replay a forward-only compute capture with typed image feedback and workgroup LDS.""" +import argparse +from functools import partial +import hashlib +import json +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +_STARTUP_DIR = str(Path(__file__).resolve().parent) +if _STARTUP_DIR not in sys.path: + sys.path.insert(0, _STARTUP_DIR) +import gfx2hlsl as gfx + + +class ComputeStage(gfx.Stage): + def __init__(self, pipe, kind, code, **options): + self.code = gfx.strip_header(code) + super().__init__(pipe, kind, code, **options) + + def lower(self, op, asm, args, mods): + if op in {'v_add_f32', 'v_sub_f32', 'v_subrev_f32', 'v_mul_f32', + 'v_mul_u32_u24', 'v_lshlrev_b32', 'v_add_nc_u32'} and asm.startswith(op+'_e32 ') and not mods: + word, = struct.unpack_from('<I', self.code, self.pc) + src0 = word & 511 + if src0 >= 255 or 128 <= src0 <= 208: + # Leave the frontend's operand and register-liveness checks in place. + self.u(args[1]) + self.u(args[2]) + self.record_v_write(int(args[0][1:])) + raw = f'{word:08x}' + if src0 == 255: + literal, = struct.unpack_from('<I', self.code, self.pc+4) + raw += f' {literal:08x}' + self.emit('#pragma x2w_vop2 '+raw) + return + if op.startswith('ds_'): + if not 0 < self.pipe.lds_words <= 8192: + raise gfx.Unsupported('native LDS requires a nonzero allocation of at most 32 KiB') + self.uses_lds = True + has_result = op.startswith('ds_read') or '_rtn_' in op + for operand in args[1:] if has_result else args: + reg = gfx.reg_range(operand) + if not reg or reg[0] != 'v': + raise gfx.Unsupported('expected local DS VGPR operands') + self.u(operand) + if has_result: + # Check all inputs first: the destination can alias the address or data. + _, lo, hi = gfx.reg_range(args[0]) + for index in range(lo, hi+1): + self.record_v_write(index) + first, second = struct.unpack_from('<II', self.code, self.pc) + self.emit(f'#pragma x2w_lds {first:08x} {second:08x}') + return + if op == 's_barrier' and not mods and args in ([], ['0'], ['0x0']): + self.emit('GroupMemoryBarrierWithGroupSync();') + return + if op == 's_waitcnt_depctr' and args == ['0xffe3'] and not mods: + return # register dependencies are explicit in the generated HLSL + if op in ('image_load', 'image_store') and self.fixed_table_image(args[2],op) == self.pipe.feedback: + writing = op == 'image_store' + required = {'dmask:0xf' if writing else 'dmask:0x7', 'dim:SQ_RSRC_IMG_2D', 'unorm'} + packed = 'a16' in mods + if set(mods) != (required | ({'a16'} if packed else set())): + raise gfx.Unsupported('unsupported typed image feedback instruction') + _, x, y = gfx.reg_range(args[1]) + _, lo, hi = gfx.reg_range(args[0]) + coordinate_registers = 2 if writing or not packed else 1 + if hi-lo != (3 if writing else 2) or y-x+1 != coordinate_registers: + raise gfx.Unsupported('unexpected image feedback register count') + address = self.u(f'v{x}') + coord = f'uint2({address}&65535u,{address}>>16)' if packed else f'uint2({address},{self.u(f"v{y}")})' + uav = self.pipe.uav(self.pipe.feedback, 'tex2d') + if writing: + values = ','.join(self.u(f'v{i}') for i in range(lo,hi+1)) + self.emit(f'if(exec&1u) {uav}[{coord}]=asfloat(uint4({values}));') + else: + self.emit(f't={uav}[{coord}];') + for i in range(3): + self.set_v(lo+i,'asuint(t.'+'xyz'[i]+')') + return + return super().lower(op,asm,args,mods) + + def body(self): + # A barrier can be emitted outside per-wave control only when all paths + # from entry pass through its block. Reject loops in this frontend. + index = {offset:i for i,(offset,_,_) in enumerate(self.blocks)} + successors = [] + for i,(_,_,term) in enumerate(self.blocks): + if not term: + dest = [i+1] + elif term[0] == 'end': + dest = [] + elif term[0] == 'jump': + if term[1] not in index: + raise gfx.Unsupported(f'branch target {term[1]} is outside the compute stage') + dest = [index[term[1]]] + elif term[0] == 'branch': + if term[2] not in index: + raise gfx.Unsupported(f'branch target {term[2]} is outside the compute stage') + dest = [i+1,index[term[2]]] + else: + raise gfx.Unsupported('unsupported compute branch') + if any(not i < d < len(index) for d in dest): + raise gfx.Unsupported('native LDS requires forward control flow') + successors.append(dest) + post = {} + for i in reversed(range(len(index))): + dest = successors[i] + post[i] = {i} | (set.intersection(*(post[j] for j in dest)) if dest else set()) + + lines = ['uint pc=0;'] + for i,(_,statements,term) in enumerate(self.blocks): + guard = f'if(pc=={i}u){{' + lines.append(guard) + for statement in statements: + if statement == 'GroupMemoryBarrierWithGroupSync();': + if i not in post[0]: + raise gfx.Unsupported('workgroup barrier is conditional') + lines.extend(['}',statement,guard]) + else: + lines.append(statement) + dest = successors[i] + if len(dest) == 2: + cond = term[1] + for mask in ('exec','vcc'): + for op,neg in [('==','!'),('!=','')]: + if cond == f'({mask} & 1) {op} 0': + cond = f'{neg}WaveActiveAnyTrue(({mask}&1u)!=0u)' + lines.append(f'pc=({cond})?{dest[1]}u:{dest[0]}u;') + else: + lines.append(f'pc={dest[0] if dest else len(index)}u;') + lines.append('}') + return lines + + +class CompileLdsRequestError(ValueError): + """Error raised by this tool's own CLI and artifact guards. + + Only this type (plus gfx.Unsupported and subprocess.CalledProcessError) + is caught in main(); anything else keeps its traceback, so a real + translator bug is never mistaken for a deliberate refusal. + """ + + +class ComputePipeline(gfx.ComputePipeline): + stage_type = ComputeStage + + def __init__(self, *args, feedback, **kwargs): + self.feedback = feedback + super().__init__(*args, **kwargs) + + +def _validate_regular_file(path: Path, label: str) -> None: + if path.is_dir(): + raise CompileLdsRequestError(f'{label} path is a directory: {path}') + if not path.exists(): + raise CompileLdsRequestError(f'{label} file not found: {path}') + if not path.is_file(): + raise CompileLdsRequestError(f'{label} path is not a regular file: {path}') + + +def _validate_writable_dir(path: Path, label: str) -> None: + """Reject paths that are files or whose parents are files or dangling links. + + A symlink component is allowed: the bundle is written through a + TemporaryDirectory inside the output and moved into place with an atomic + rename, so a symlinked output or cache is simply the caller's chosen + location. Only a component that is not a directory at all is refused. + """ + if path.is_file() or (path.exists() and not path.is_dir()): + raise CompileLdsRequestError(f'{label} path is not a directory: {path}') + for parent in path.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise CompileLdsRequestError(f'{label} parent is not a directory: {parent}') + + +def _validate_paths(args: argparse.Namespace) -> None: + _validate_regular_file(args.marker, 'request marker') + for ext in ('.root', '.data', '.desc', '.sa', '.sb'): + _validate_regular_file(args.marker.with_suffix(ext), f'companion {ext}') + _validate_regular_file(args.compiler, 'compiler') + if not args.sdk.exists(): + raise CompileLdsRequestError(f'SDK directory not found: {args.sdk}') + if not args.sdk.is_dir(): + raise CompileLdsRequestError(f'SDK path is not a directory: {args.sdk}') + _validate_writable_dir(args.output, 'output') + _validate_writable_dir(args.cache, 'cache') + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('marker',type=Path) + parser.add_argument('output',type=Path) + parser.add_argument('--compiler',required=True,type=Path) + parser.add_argument('--sdk',required=True,type=Path) + parser.add_argument('--cache',required=True,type=Path) + parser.add_argument('--rw-image',required=True,nargs=2,type=int,metavar=('PARAM','BYTE_OFFSET')) + parser.add_argument('--wave-size',required=True,type=int,choices=[32,64]) + args = parser.parse_args(argv) + name = args.marker.name + if not re.fullmatch(r'req_[0-9a-f]{16}\.c67',name): + parser.error('expected req_<16 hex digits>.c67') + key = int(name[4:20],16) + param,off = args.rw_image + if param < 0 or off < 0 or off%32: + parser.error('expected a nonnegative parameter and a 32-byte-aligned descriptor offset') + try: + _validate_paths(args) + args.output.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=args.output) as temp: + bundle = Path(temp) / 'bundle' + request = bundle / 'request' + request.mkdir(parents=True) + for ext in ('.c67', '.root', '.data', '.desc', '.sa', '.sb'): + path = args.marker.with_suffix(ext) + shutil.copyfile(path, request / path.name) + pipeline = gfx.load_compute_request( + str(request), key, + pipeline_type=partial(ComputePipeline, feedback=(('table', param), off)), + ) + source = pipeline.hlsl_cs().replace('[numthreads(', f'[WaveSize({args.wave_size})]\n[numthreads(') + stage = bundle / f'{key:016x}.cs.hlsl' + stage.write_text(source, encoding='utf-8') + bytecode = stage.with_suffix('.cso') + subprocess.run([args.compiler, args.sdk, args.cache, 'cs_6_6', stage, bytecode], check=True) + manifest = bundle / f'{key:016x}.txt' + manifest.write_text(pipeline.manifest(), encoding='utf-8') + metadata = { + 'schema': 1, 'request': f'request/{name}', 'profile': 'cs_6_6', + 'rw_image': [param, off], 'wave_size': args.wave_size, 'sha256': {}, + } + for path in sorted(bundle.rglob('*')): + if path.is_file(): + metadata['sha256'][path.relative_to(bundle).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest() + replay = json.dumps(metadata, indent=2, sort_keys=True) + '\n' + (bundle / 'replay.json').write_bytes(replay.encode()) + dest = args.output / f'{key:016x}-{hashlib.sha256(replay.encode()).hexdigest()}' + try: + bundle.rename(dest) + except OSError as error: + if not dest.is_dir(): + raise CompileLdsRequestError(f'cannot move replay bundle to {dest}: {error}') from error + replay_path = dest / 'replay.json' + if not replay_path.is_file() or replay_path.read_bytes() != replay.encode(): + raise CompileLdsRequestError(f'damaged replay artifact replay.json in {dest}') from error + for relative, digest in metadata['sha256'].items(): + try: + data = (dest / relative).read_bytes() + except OSError: + raise CompileLdsRequestError(f'damaged replay artifact {relative}') from None + if hashlib.sha256(data).hexdigest() != digest: + raise CompileLdsRequestError(f'damaged replay artifact {relative}') + print(dest) + except (gfx.Unsupported, subprocess.CalledProcessError, CompileLdsRequestError) as error: + print(f'error: {error}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/startup/compile_sampled_pixel_request.py b/tools/startup/compile_sampled_pixel_request.py new file mode 100644 index 0000000000..30c2a3bf36 --- /dev/null +++ b/tools/startup/compile_sampled_pixel_request.py @@ -0,0 +1,134 @@ +"""Compile a captured graphics request as a matched desktop SM6 pair.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +from tempfile import TemporaryDirectory + +import gfx2hlsl as gfx + + +def bindings(lines, sampler_tags): + resources = [] + samplers = [] + for line in lines: + words = line.split() + if words[:1] == ['srv']: + resources.append(words) + if words and words[0] in sampler_tags: + samplers.append(tuple(int(word, 0) for word in words[1:])) + return resources, samplers + + +def write_program(path, container): + raw = gfx.strip_header(container) + instructions = gfx.decode(raw) + if not instructions or instructions[-1][2] != 's_endpgm': + raise ValueError('missing program boundary') + end, size, _, _ = instructions[-1] + path.write_bytes(raw[:end + size]) + return len(container) - len(raw) + + +def build(marker, dest, compiler, sdk, cache, buffered_vertex=False): + match = re.fullmatch(r'req_([0-9a-f]{16})\.rtv', marker.name) + if not match: + raise ValueError('expected a req_<16 hex digits>.rtv marker') + variant = int(match[1], 16) + request = marker.read_bytes() + parsed = re.fullmatch(rb'rtv1 ([0-9]{1,20}) ' + (b'10' if buffered_vertex else b'26 54'), request) + if not parsed or gfx.fnv(request) != variant: + raise ValueError('expected a matching ' + ('RGBA16_FLOAT' if buffered_vertex else 'R11G11B10_FLOAT / R16_FLOAT') + ' request') + base = int(parsed[1]) + stem = f'req_{base:016x}' + dest.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(dir=dest) as temp: + bundle = Path(temp) / 'bundle' + inputs = bundle / 'request' + inputs.mkdir(parents=True) + (inputs / marker.name).write_bytes(request) + pieces = [] + for suffix in ('.a', '.b', '.root', '.ia'): + path = marker.with_name(stem + suffix) + if suffix == '.ia' and not path.exists(): + continue + data = path.read_bytes() + pieces.append(data) + (inputs / path.name).write_bytes(data) + if gfx.pipeline_key(*pieces) != base: + raise ValueError('graphics stage, root or input layout key mismatch') + stages, root, formats, rtv, fetch, _, attr_map = gfx.load_request(str(inputs), variant) + if any(blob.startswith(b'DXBC') for blob in pieces[:2]) or fetch is not None or attr_map is not None or len(pieces) != 3: + raise ValueError('this profile requires the raw two-table graphics interface') + tables = [{'type': 0, 'vis': 0}] * 2 + if gfx.parse_root(root) != {'flags': 1, 'params': tables}: + raise ValueError('unexpected graphics root layout') + pair = gfx.Pipeline(stages['vs'], stages['ps'], root, sampler_heap=False, rtv_formats=formats) + manifest = pair.manifest() + if pair.params != ([0, 1] if buffered_vertex else [0]) or pair.flat or pair.notes or pair.lod_unvalidated: + raise ValueError('unsupported vertex parameters or unverified binding manifest') + name = match[1] + ps = bundle / (name + '.ps.bin') + ps_offset = write_program(ps, stages['ps']) + vs = bundle / (name + '.vs.bin') + vs_offset = write_program(vs, stages['vs']) + entry = ['udsrc 0 rect', 'udsrc 1 basevertex', 'udsrc 2 startinstance'] + if buffered_vertex: + entry.append('udsrc 3 stride 0') + if manifest.splitlines()[1:len(entry)+2] != [f'ud {len(entry)}', *entry]: + raise ValueError('unexpected vertex entry constants') + pixel_source = ps + if buffered_vertex: + pixel_source = bundle / (name + '.ps.hlsl') + pixel_source.write_text(pair.hlsl_ps(), encoding='utf-8') + batch = 'gfx1013-buffered-pair' if buffered_vertex else 'gfx1013-sampled-pair' + result = subprocess.run([compiler, sdk, cache, '--jobs', '2', batch, + vs, bundle / (name + '.vs.cso'), pixel_source, bundle / (name + '.ps.cso')], + check=True, text=True, stdout=subprocess.PIPE) + print(result.stdout, end='') + actual = bindings(result.stdout.splitlines(), {'sampler'}) + expected = bindings(manifest.splitlines(), {'smp', 'smpl'}) + if buffered_vertex: + rows, _ = actual + if not rows or rows != expected[0][:len(rows)]: + raise ValueError('native vertex buffer registers disagree with paired graphics manifest') + elif actual != expected: + raise ValueError('native pixel bindings disagree with paired graphics manifest') + (bundle / (name + '.txt')).write_text(manifest + rtv + '\n', encoding='utf-8') + metadata = {'profile': 'gfx1013-rgb11-r16-ps', 'request': 'request/' + marker.name, + 'pixel_offset': ps_offset, 'pixel_bytes': ps.stat().st_size, + 'vertex_profile': 'gfx1013-vertex-id-vs', 'vertex_offset': vs_offset, 'vertex_bytes': vs.stat().st_size, + 'entry': {'table_sgprs': [8, 9], 'primitive_mask_sgpr': 10, + 'perspective_center_vgprs': [0, 1], 'attr0': 'PARAM0'}, + 'rtv_formats': list(formats), + 'sha256': {file.relative_to(bundle).as_posix(): hashlib.sha256(file.read_bytes()).hexdigest() + for file in sorted(bundle.rglob('*')) if file.is_file()}} + if buffered_vertex: + metadata.update(profile='ps_6_0', vertex_profile='gfx1013-buffered-vs', + entry={'vertex_table_sgprs': [0, 1], 'base_vertex_sgpr': 2, 'root_table_sgprs': [8, 9], + 'vertex_stride_word': 3, 'pixel_frontend': 'gfx2hlsl'}) + record = json.dumps(metadata, indent=2, sort_keys=True).encode() + b'\n' + (bundle / 'replay.json').write_bytes(record) + output = dest / (name + '-' + hashlib.sha256(record).hexdigest()) + try: + bundle.rename(output) + except OSError: + if not output.is_dir() or (output / 'replay.json').read_bytes() != record: + raise + for path, expected in metadata['sha256'].items(): + if hashlib.sha256((output / path).read_bytes()).hexdigest() != expected: + raise ValueError('damaged replay bundle: ' + path) + return output + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('marker', type=Path) + parser.add_argument('output', type=Path) + parser.add_argument('--buffered-vertex', action='store_true', help='translate a raw buffered VS with an RGBA16_FLOAT pixel companion') + for option in ('compiler', 'sdk', 'cache'): + parser.add_argument('--' + option, type=Path, required=True) + args = parser.parse_args() + print(build(args.marker, args.output, args.compiler, args.sdk, args.cache, args.buffered_vertex)) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 2f0be7602f..c5f794f77e 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -1,11 +1,17 @@ """Run one EXE under a minimal debugger inside a kill-on-close job (startup diagnostics; see docs/startup-runtime.md). usage: debug_launch.py <exe> <cwd> <logdir> [--timeout S] [--memory-gib N] [--stop-first-chance 1] + [--suspend-others 0] [--capture-every S] + [--continue-asserts N] [--assert-sites N] Records module loads, every exception (code, address as module+offset, first/second chance) and, for the stopping exception, the integer registers, the stack words and the code bytes around RIP. Stops at a second-chance exception, an uncontinued main-image breakpoint, or the timeout. A timeout of zero disables the timer. An assertion continuation limit of -1 removes that limit. +--continue-asserts N steps over the first N main-image int3 hits in total. --assert-sites N instead +steps over every hit at up to N distinct main-image int3 sites, so a site that repeats does not use +the budget up however long the run lasts; the first hit at one more site stops the run. A hit is +stepped over when either budget allows it. A file named `stop` created in <logdir> during the run ends it as the timeout does (checked twice a second; a stop file left from an earlier run is removed at start). """ @@ -15,15 +21,21 @@ import re import struct import sys +import threading import time k32 = ctypes.WinDLL("kernel32", use_last_error=True) k32.OpenThread.restype = wt.HANDLE k32.CreateJobObjectW.restype = wt.HANDLE k32.CreateFileW.restype = wt.HANDLE +k32.SuspendThread.restype = wt.DWORD +nt_dll = ctypes.WinDLL("ntdll") +nt_dll.NtSuspendThread.restype = ctypes.c_ulong -from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file # noqa: E402 +from launch import STARTUPINFOW, PROCESS_INFORMATION, EXTENDED_LIMIT, inheritable_file, startup_for_create # noqa: E402 import host_cpu # noqa: E402 +from hook_window import StepWindow, ReturnBook, classify_hold, classify_status, GONE, HELD # noqa: E402 +from window_capture import FILE_CAP, Series, png_bytes # noqa: E402 class MemoryBasicInformation(ctypes.Structure): @@ -120,14 +132,40 @@ def main(): def print(*args, **kwargs): summary.append(" ".join(str(a) for a in args)) builtins.print(*args, **kwargs) - timeout = float(opts.get("--timeout", 15)) # zero leaves the session running until exit or a debug stop - memory = int(float(opts.get("--memory-gib", 16)) * 2**30) + try: + timeout = float(opts.get("--timeout", 15)) # zero leaves the session running until exit or a debug stop + memory_gib = float(opts.get("--memory-gib", 16)) + skip_asserts = int(opts.get("--continue-asserts", "0")) # -1 continues all diagnostic assertions + assert_sites = int(opts.get("--assert-sites", "0")) # distinct sites whose every hit is continued + except ValueError: + print("expected numeric --timeout and --memory-gib values and integer --continue-asserts and " + "--assert-sites values") + return 2 stop_first = opts.get("--stop-first-chance") == "1" - skip_asserts = int(opts.get("--continue-asserts", "0")) # -1 continues all diagnostic assertions + try: + capture_every = float(opts.get("--capture-every", 0)) # seconds between window pictures; 0 = off + except ValueError: + capture_every = -1 + if not (capture_every == 0 or 1 <= capture_every < float("inf")): + print("expected --capture-every of 0 (off) or a finite number of seconds that is at least 1") + return 2 if timeout < 0 or not timeout < float("inf") or skip_asserts < -1: print("expected a finite nonnegative timeout and an assertion limit of -1 or greater") return 2 + if assert_sites < 0: + print("expected an --assert-sites value of 0 or greater") + return 2 + # The job always sets JOB_MEMORY (0x200), so a limit of 0 would deny the process any commit. + if not 1 <= memory_gib * 2**30 < 2**(8 * ctypes.sizeof(ctypes.c_size_t)): + print("expected a finite --memory-gib that is at least one byte and fits the Windows size_t limit") + return 2 + memory = int(memory_gib * 2**30) asserts_seen = {} + # The two assert budgets keep their own books, so a hit one of them covers never uses up the other: + # assert_sites_admitted holds the sites --assert-sites covers (the first assert_sites distinct ones), + # asserts_counted the hits --continue-asserts stepped over. + assert_sites_admitted = set() + asserts_counted = 0 # X2W_NOP_SOFT_ASSERTS=1: after the first hit of a main-image int3 that is continued, replace the # trap byte with NOP. DBG_CONTINUE already bypasses the title's handler, so the visible behavior is # unchanged, but a long mapping that traps once per chunk then runs at native speed. @@ -179,8 +217,12 @@ def log(text): block = "".join(f"{k}={v}\0" for k, v in env.items()) + "\0" pi = PROCESS_INFORMATION() flags = 0x2 | 0x4 | 0x400 # DEBUG_ONLY_THIS_PROCESS | CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT + startup, extra_flags, startup_keep, startup_note = startup_for_create(si, env) + if startup_note: + print(startup_note) + flags |= extra_flags if not k32.CreateProcessW(exe, ctypes.create_unicode_buffer(f'"{exe}"'), None, None, True, flags, - ctypes.create_unicode_buffer(block), cwd, ctypes.byref(si), ctypes.byref(pi)): + ctypes.create_unicode_buffer(block), cwd, ctypes.byref(startup), ctypes.byref(pi)): print("CreateProcess failed", ctypes.get_last_error()) return 2 k32.AssignProcessToJobObject(wt.HANDLE(job), wt.HANDLE(pi.hProcess)) @@ -339,6 +381,97 @@ def oa_name(addr): # OBJECT_ATTRIBUTES* text = ustr(name) if name else "" return (f"[root {root:#x}]" if root else "") + text + def oa_string(addr): # the UNICODE_STRING* inside OBJECT_ATTRIBUTES, for rewriting it + raw = read(addr, 24) + return struct.unpack_from("<Q", raw, 16)[0] if len(raw) >= 24 else 0 + + # --map-drive G=C:\folder[;S=D:\folder]: a console executable opens its package at a fixed drive + # letter, so a package that sits on another volume never mounts. The file hooks rewrite the path + # of an open on a mapped letter to the real folder, in the caller's own UNICODE_STRING. + drive_map = {} + # Rewritten names live in buffers borrowed for the duration of one hooked call, so two calls that + # overlap on different threads cannot overwrite or free each other's name. A buffer goes back to + # the pool when that call's name is restored, so a serial run reuses one buffer instead of + # allocating per open and the allocation count does not follow the number of opens. + name_pool = {"free": [], "allocations": 0} + for item in filter(None, opts.get("--map-drive", "").split(";")): + letter, _, folder = item.partition("=") + letter = letter.strip().rstrip(":").upper() + # Letters are ASCII A-Z: isalpha() alone also accepts non-ASCII letters, which no NT path has. + if len(letter) == 1 and letter.isascii() and letter.isalpha() and folder.strip(): + # NT paths take backslashes; the option may arrive with either separator. + drive_map[letter] = folder.strip().rstrip("\\/").replace("/", "\\") + + def map_drive(text, string_address): + """Makes the call's name temporary: returns (new text, restore) or (None, None). + + The caller's UNICODE_STRING is changed only for the duration of the hooked call; restore() + puts back its length, buffer pointer and contents when the call returns.""" + if not drive_map or not string_address: + return None, None + body = text + # oa_name() marks a root-relative name with a "[root 0x...]" tag for the log. That tag is not + # part of the name, so it is dropped here and never written into the caller's UNICODE_STRING. + if body.startswith("[root ") and "]" in body: + body = body[body.index("]") + 1:] + prefix = "" + for candidate in ("\\??\\", "\\\\.\\", "\\\\?\\"): + if body.upper().startswith(candidate): + prefix, body = body[:len(candidate)], body[len(candidate):] + break + if len(body) < 2 or body[1] != ":" or body[0].upper() not in drive_map: + return None, None + replacement = prefix + drive_map[body[0].upper()] + body[2:] + raw = read(string_address, 16) + if len(raw) < 16: + return None, None + _, maximum, buffer = struct.unpack_from("<HH4xQ", raw) + encoded = replacement.encode("utf-16-le") + # A UNICODE_STRING length is a USHORT, so a longer name cannot be expressed at all. + if not 0 < len(encoded) <= 0xFFFF: + return None, None + if len(encoded) <= maximum: + original = read(buffer, len(encoded)) + if len(original) != len(encoded) or not write(buffer, encoded): + return None, None + if not write(string_address, struct.pack("<H", len(encoded))): + write(buffer, original) + return None, None + return replacement, lambda: (write(buffer, original), write(string_address, raw)) + # The replacement is longer than the caller's buffer, which is the common case: a folder path + # against a single letter. Borrow a buffer from the pool for this call only; it is returned + # when the name is restored, so serial opens reuse one buffer but overlapping calls get their + # own. + address, capacity = 0, 0 + for index, (candidate, room) in enumerate(name_pool["free"]): + if room >= len(encoded): + address, capacity = name_pool["free"].pop(index) + break + if not address: + k32.VirtualAllocEx.restype = ctypes.c_void_p + k32.VirtualAllocEx.argtypes = [wt.HANDLE, ctypes.c_void_p, ctypes.c_size_t, wt.DWORD, wt.DWORD] + fresh = k32.VirtualAllocEx(wt.HANDLE(pi.hProcess), None, len(encoded), 0x3000, 0x04) + if not fresh: + return None, None + address, capacity = fresh, len(encoded) + name_pool["allocations"] += 1 + if file_log: + file_log.write(f"{time.time() - start:7.3f} NAMEBUF alloc {len(encoded)} bytes at {fresh:#x} " + f"(live {name_pool['allocations']})\n") + file_log.flush() + if not write(address, encoded): + name_pool["free"].append((address, capacity)) + return None, None + if not write(string_address, struct.pack("<HH4xQ", len(encoded), len(encoded), address)): + name_pool["free"].append((address, capacity)) + return None, None + + def restore(): + write(string_address, raw) + name_pool["free"].append((address, capacity)) + + return replacement, restore + trace = opts.get("--trace-files") == "1" or opts.get("--offline", "1") == "1" # offline mode needs the hooks # --trace-calls 1: also break on gaming-runtime and movie-player calls. Every hit stops the whole # process, so these hooks are off by default; the movie-player report (bink_report) needs them. @@ -374,6 +507,9 @@ def oa_name(addr): # OBJECT_ATTRIBUTES* redirects = {} # Offline by default (--offline 0 turns it off): no sockets, NetBIOS name devices or DNS resolver. offline = opts.get("--offline", "1") == "1" + # Keep the same offline entry checks. An allowed file operation only + # needs a return breakpoint when collecting its completion status. + offline_entry_only = offline and os.environ.get("X2W_OFFLINE_ENTRY_ONLY") == "1" OFFLINE_DENY = ("\\device\\afd", "\\device\\netbt", "dnsresolver", "\\device\\tcp", "\\device\\udp", "\\device\\rawip", "\\device\\ws2ifsl") denied = {} @@ -435,9 +571,62 @@ def chunk(kind, payload): breakpoints = {} # addr -> original byte retired = set() # X2W_LOG_AT breakpoints removed at their hit limit late_hits = {} # retired addr -> INT3 events that arrived after the removal - returns = {} # addr -> list of (tid, rsp after return, description) + returns = ReturnBook() stepping = {} # tid -> addr to re-arm file_log = open(os.path.join(logdir, "files.txt"), "w", encoding="utf-8") if trace or log_at else None + hook_entries = [0] + held_threads = {} # tid -> handle of a thread held for the current step window + os_handles = {} # tid -> hThread of CREATE_*_DEBUG_EVENT: valid until its EXIT_THREAD is continued; never closed here + sync_raw = (ctypes.c_ubyte * (1232 + 16))() + sync_addr = (ctypes.addressof(sync_raw) + 15) & ~15 + + def hold_thread(tid): + handle = os_handles.get(tid) + owned = handle is None + if owned: # SUSPEND_RESUME | GET_CONTEXT | QUERY_INFORMATION | SYNCHRONIZE + handle = k32.OpenThread(0x0002 | 0x0008 | 0x0040 | 0x00100000, False, tid) + if not handle: + return classify_hold(None, ctypes.get_last_error()) + + def drop(): + if owned: + k32.CloseHandle(wt.HANDLE(handle)) + + # SuspendThread returns before the thread has stopped; GetThreadContext waits until it has. + struct.pack_into("<I", (ctypes.c_ubyte * 1232).from_address(sync_addr), 0x30, 0x100001) + previous = wt.ULONG() + status = nt_dll.NtSuspendThread(wt.HANDLE(handle), ctypes.byref(previous)) + suspended = status == 0 + if suspended and k32.GetThreadContext(wt.HANDLE(handle), ctypes.c_void_p(sync_addr)): + held_threads[tid] = (handle, owned) + return HELD + if suspended: + k32.ResumeThread(wt.HANDLE(handle)) + # A thread already exiting (waiting for its EXIT_THREAD event) refuses suspension with + # STATUS_THREAD_IS_TERMINATING while GetExitCodeThread still says STILL_ACTIVE: it runs no code. + if not suspended and classify_status(status) == GONE: + drop() + return GONE + # Classify after the failure: a thread that has called ExitThread is GONE (no code left to race + # with); a live thread that cannot be suspended stays FAILED and the window reports it. + code = wt.DWORD() + exit_code = code.value if k32.GetExitCodeThread(wt.HANDLE(handle), ctypes.byref(code)) else None + # A thread that is terminating may not have its exit code yet: its handle is signaled in moments. + signaled = k32.WaitForSingleObject(wt.HANDLE(handle), 20) == 0 + drop() + return classify_hold(exit_code, signaled=signaled) + + def release_thread(tid): + held = held_threads.pop(tid, None) + if held: + handle, owned = held + k32.ResumeThread(wt.HANDLE(handle)) + if owned: + k32.CloseHandle(wt.HANDLE(handle)) + + # A hook step-over restores the original byte for one instruction. Every other thread is held + # for that step (--suspend-others 0 turns this off to measure what the window costs). + window = StepWindow(hold_thread, release_thread, protect=opts.get("--suspend-others", "1") != "0") def arm(addr, *, skip_int3=False): if addr not in breakpoints: @@ -450,6 +639,12 @@ def handle_breakpoint(tid, addr): thread, ctx = get_ctx(tid) if not thread: return False + if window.defer(tid): + # This thread trapped before it was held. Back to the hook address: it traps again, and + # is traced, once the window is closed and the byte is patched again. + struct.pack_into("<Q", ctx, 0xF8, addr) + set_ctx(thread) + return True regs = dict(zip(REGS, struct.unpack_from("<16Q", ctx, 0x78) + struct.unpack_from("<Q", ctx, 0xF8))) rva = addr - main_base if log_at else None point = log_at.get(rva) @@ -465,8 +660,13 @@ def handle_breakpoint(tid, addr): file_log.flush() rsp = regs["Rsp"] if addr in hooks: + hook_entries[0] += 1 name, arg = hooks[addr] - ret = read_qword(read, rsp) or 0 + ret = struct.unpack("<Q", read(rsp, 8) or b"\0" * 8)[0] + # Every kind of trace reaches the common "if desc:" below, so the restore callback is + # initialised here: leaving it to the file-name branch would let a non-name trace see an + # unbound name or carry over the previous call's callback. + restore = None if arg == "valloc": # NtAllocateVirtualMemory(process, &base, zero bits, &size, type, protect) and # NtAllocateVirtualMemoryEx(process, &base, &size, type, protect, ...). @@ -514,10 +714,29 @@ def guid(address): desc = bink_call(name, regs, ret) else: if arg.startswith("ustr:"): - target = ustr(regs[arg[5:].capitalize()]) + string_address = regs[arg[5:].capitalize()] + target = ustr(string_address) else: - target = oa_name(regs[arg.capitalize()] if arg != 'r8' else regs['R8']) - desc = f"{name} {target} from {where(ret)}" + oa_address = regs['R8'] if arg == 'r8' else regs[arg.capitalize()] + target = oa_name(oa_address) + string_address = oa_string(oa_address) + if offline and any(pattern in target.lower() for pattern in OFFLINE_DENY): + # Offline mode: the call never runs, so the caller's name is left untouched. + denied[target] = denied.get(target, 0) + 1 + file_log.write(f"{time.time() - start:7.3f} DENIED (offline) {name} {target} " + f"from {where(ret)}\n") + file_log.flush() + struct.pack_into("<Q", ctx, 0x78, 0xC0000022) # rax + struct.pack_into("<Q", ctx, 0x98, rsp + 8) # rsp: pop the return address + struct.pack_into("<Q", ctx, 0xF8, ret) # rip + set_ctx(thread) + return True + mapped, restore = map_drive(target, string_address) + desc = f"{name} {mapped or target} from {where(ret)}" + if mapped: + desc += " (mapped from " + target + ")" + file_log.write(f"{time.time() - start:7.3f} MAP {target} -> {mapped}\n") + file_log.flush() if offline and any(pattern in target.lower() for pattern in OFFLINE_DENY): # Offline mode: the call never runs. Return STATUS_ACCESS_DENIED to the caller. denied[target] = denied.get(target, 0) + 1 @@ -528,6 +747,8 @@ def guid(address): struct.pack_into("<Q", ctx, 0xF8, ret) # rip set_ctx(thread) return True + if offline_entry_only: + desc = None if desc and ("memory:" in desc or "CALLERS" in os.environ.get("X2W_TRACE", "")): # Title-level callers: module addresses on the stack outside the system DLLs. words = struct.unpack_from("<160Q", (read(rsp, 8 * 160) or b"").ljust(8 * 160, b"\0")) @@ -535,24 +756,25 @@ def guid(address): chain = [c for c in chain if not c.lower().startswith(("ntdll", "kernelbase", "kernel32"))] desc += " callers: " + " ".join(chain[:8]) if desc: - returns.setdefault(ret, []).append((tid, rsp + 8, desc)) + # The name is temporary: take() puts the caller's own UNICODE_STRING back (restore) when the + # call returns, before anything else runs, so a failure or a retry sees the name it built. + returns.add(ret, tid, rsp + 8, desc, addr, restore) arm(ret) - for item in list(returns.get(addr, [])): - if item[0] == tid and item[1] == rsp: - returns[addr].remove(item) - file_log.write(f"{time.time() - start:7.3f} {item[2]} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") - file_log.flush() + for description in returns.take(addr, tid, rsp): + file_log.write(f"{time.time() - start:7.3f} {description} -> {regs['Rax'] & 0xFFFFFFFF:#010x}\n") + file_log.flush() struct.pack_into("<Q", ctx, 0xF8, addr) # After the final logged hit, let the restored instruction run at full speed unless # another hook still owns this breakpoint. - if (point and logged_hits[rva] == point[0] and addr not in hooks and not returns.get(addr) + if (point and logged_hits[rva] == point[0] and addr not in hooks and not returns.pending(addr) and write(addr, breakpoints[addr])): del breakpoints[addr] retired.add(addr) set_ctx(thread) return True - # Step over the original instruction, then re-arm. + # Hold other threads while stepping over the original instruction. eflags = struct.unpack_from("<I", ctx, 0x44)[0] + window.open(tid, [other for other in live_threads if other != tid], time.monotonic()) struct.pack_into("<I", ctx, 0x44, eflags | 0x100) set_ctx(thread) write(addr, breakpoints[addr]) @@ -622,6 +844,80 @@ def poll_watches(): watch_values[rva] = blob log(f"{time.time() - start:7.3f} watch +{rva:#x} = {blob.hex(' ')}") + def grab_window(): + """The title's window as (width, height, BGRA bytes, title text length), or the reason there is none. + + Runs on the capture thread as well as at the end of the run; every GDI object is released.""" + user32, gdi32 = ctypes.WinDLL("user32"), ctypes.WinDLL("gdi32") + found = [] + proto = ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM) + + def visit(hwnd, _): + owner = wt.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + if owner.value == pi.dwProcessId and user32.IsWindowVisible(hwnd): + found.append(hwnd) + return True + + user32.EnumWindows(proto(visit), 0) + if not found: + return "no visible window" + hwnd = found[0] + rect = wt.RECT() + user32.GetClientRect(wt.HWND(hwnd), ctypes.byref(rect)) + width, height = min(rect.right, 1920), min(rect.bottom, 1080) + if width <= 0 or height <= 0: + return "empty client area" + user32.GetDC.restype = wt.HDC + gdi32.CreateCompatibleDC.restype = wt.HDC + gdi32.CreateCompatibleBitmap.restype = wt.HBITMAP + source = user32.GetDC(wt.HWND(hwnd)) + memory = gdi32.CreateCompatibleDC(wt.HDC(source)) + bitmap = gdi32.CreateCompatibleBitmap(wt.HDC(source), width, height) + try: + gdi32.SelectObject(wt.HDC(memory), wt.HBITMAP(bitmap)) + gdi32.BitBlt(wt.HDC(memory), 0, 0, width, height, wt.HDC(source), 0, 0, 0x00CC0020) + header = struct.pack("<IiiHHIIiiII", 40, width, -height, 1, 32, 0, 0, 0, 0, 0, 0) + pixels = (ctypes.c_ubyte * (width * height * 4))() + gdi32.GetDIBits(wt.HDC(memory), wt.HBITMAP(bitmap), 0, height, pixels, header, 0) + raw = bytes(pixels) + finally: + gdi32.DeleteObject(wt.HGDIOBJ(bitmap)) + gdi32.DeleteDC(wt.HDC(memory)) + user32.ReleaseDC(wt.HWND(hwnd), wt.HDC(source)) + title = ctypes.create_unicode_buffer(128) + user32.GetWindowTextW(wt.HWND(hwnd), title, 128) + return width, height, raw, len(title.value) + + def capture_window(): + """Saves what the title's window currently shows on screen (client area) as window.png.""" + frame = grab_window() + if isinstance(frame, str): + print(f" window capture: {frame}") + return + width, height, raw, title_length = frame + with open(os.path.join(logdir, "window.png"), "wb") as handle: + handle.write(png_bytes(width, height, raw)) + print(f" window capture: {width}x{height} -> window.png (client area as on screen; title text length {title_length})") + + # --capture-every: a thread of its own grabs the window, so a slow capture never delays the debug events. + series = Series(logdir) if capture_every else None + capture_done = threading.Event() + + def capture_loop(): + while not capture_done.wait(capture_every): + try: + frame = grab_window() + if isinstance(frame, str): + series.miss() + else: + series.offer(time.time() - start, frame[0], frame[1], frame[2]) + except Exception: # diagnostics only: the run goes on, the tick is counted + series.miss() + + capture_thread = threading.Thread(target=capture_loop, name="window-capture", daemon=True) if series else None + if capture_thread: + capture_thread.start() stop_requested = False stop_next = 0.0 while not timeout or time.time() - start < timeout: @@ -636,13 +932,17 @@ def poll_watches(): if watches and time.time() >= watch_next: watch_next = time.time() + 1.0 poll_watches() + if window.expire(time.monotonic()): + log(f"{time.time() - start:7.3f} hook step window expired, held threads resumed") if not k32.WaitForDebugEvent(event, 200): continue code, pid, tid = struct.unpack_from("<III", event, 0) status = DBG_CONTINUE if code == CREATE_PROCESS: live_threads.add(tid) - h_file, _, _, base = struct.unpack_from("<QQQQ", event, 16) + h_file, _, h_thread, base = struct.unpack_from("<QQQQ", event, 16) + if h_thread: + os_handles[tid] = h_thread main_base = base for item in filter(None, os.environ.get("X2W_COUNT", "").split(",")): hooks[base + int(item, 16)] = (f"+{item}", "count") @@ -687,8 +987,14 @@ def poll_watches(): elif code == CREATE_THREAD: log(f"{time.time() - start:7.3f} thread {tid} created") live_threads.add(tid) + h_thread = struct.unpack_from("<Q", event, 16)[0] + if h_thread: + os_handles[tid] = h_thread + window.hold(tid) elif code == 4: # EXIT_THREAD live_threads.discard(tid) + window.finish(tid) + os_handles.pop(tid, None) elif code == EXIT_PROCESS: exit_code = struct.unpack_from("<I", event, 16)[0] log(f"{time.time() - start:7.3f} exit {exit_code:#010x}") @@ -724,6 +1030,7 @@ def poll_watches(): addr = stepping.pop(tid) if addr in breakpoints: write(addr, b"\xcc") + window.finish(tid) k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE) continue if (ex_code == 0xC000001D and first and host_cpu_on and not stop_first and main_base @@ -761,8 +1068,13 @@ def poll_watches(): log(f"X2W_LOG_AT ignored {rva:#x}: cannot arm a main-image instruction breakpoint") del log_at[rva] elif (ex_code == 0x80000003 and first and main_base and main_base <= ex_addr < main_base + 0x10000000 - and (skip_asserts == -1 or sum(asserts_seen.values()) < skip_asserts) + and (ex_addr in assert_sites_admitted or len(assert_sites_admitted) < assert_sites + or skip_asserts == -1 or asserts_counted < skip_asserts) and (ex_addr - main_base) not in stop_at): + if ex_addr in assert_sites_admitted or len(assert_sites_admitted) < assert_sites: + assert_sites_admitted.add(ex_addr) + else: + asserts_counted += 1 asserts_seen[ex_addr] = asserts_seen.get(ex_addr, 0) + 1 if nop_soft_asserts and ex_addr not in nop_sites and read(ex_addr, 1) == b"\xcc" and write(ex_addr, b"\x90"): nop_sites[ex_addr] = 1 @@ -778,6 +1090,7 @@ def poll_watches(): status = DBG_EXCEPTION_NOT_HANDLED k32.ContinueDebugEvent(pid, tid, status) + window.abandon() elapsed = time.time() - start if stop and stop_at: dump_threads(os.path.join(logdir, "threads_stop.txt")) @@ -888,6 +1201,11 @@ def poll_watches(): if late_hits: print(" LOG_AT late hits resumed after the limit: " + ", ".join(f"+{addr - main_base:x} x{n}" for addr, n in sorted(late_hits.items()))) + report = window.summary(hook_entries[0]) + print(" " + report) + if file_log: + file_log.write(report + "\n") + file_log.flush() if offline: print(f" offline: {sum(denied.values())} network opens refused" + ("" if not denied else " (" + ", ".join(f"{k} x{v}" for k, v in list(denied.items())[:6]) + ")")) @@ -898,61 +1216,10 @@ def poll_watches(): else: print(" call tracing: off (runtime and movie-player call hooks; --trace-calls 1)") - def capture_window(): - """Saves what the title's window currently shows on screen (client area) as window.png.""" - import zlib - user32, gdi32 = ctypes.WinDLL("user32"), ctypes.WinDLL("gdi32") - found = [] - proto = ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM) - - def visit(hwnd, _): - owner = wt.DWORD() - user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) - if owner.value == pi.dwProcessId and user32.IsWindowVisible(hwnd): - found.append(hwnd) - return True - - user32.EnumWindows(proto(visit), 0) - if not found: - print(" window capture: no visible window") - return - hwnd = found[0] - rect = wt.RECT() - user32.GetClientRect(wt.HWND(hwnd), ctypes.byref(rect)) - width, height = min(rect.right, 1920), min(rect.bottom, 1080) - if width <= 0 or height <= 0: - print(" window capture: empty client area") - return - user32.GetDC.restype = wt.HDC - gdi32.CreateCompatibleDC.restype = wt.HDC - gdi32.CreateCompatibleBitmap.restype = wt.HBITMAP - source = user32.GetDC(wt.HWND(hwnd)) - memory = gdi32.CreateCompatibleDC(wt.HDC(source)) - bitmap = gdi32.CreateCompatibleBitmap(wt.HDC(source), width, height) - gdi32.SelectObject(wt.HDC(memory), wt.HBITMAP(bitmap)) - gdi32.BitBlt(wt.HDC(memory), 0, 0, width, height, wt.HDC(source), 0, 0, 0x00CC0020) - header = struct.pack("<IiiHHIIiiII", 40, width, -height, 1, 32, 0, 0, 0, 0, 0, 0) - pixels = (ctypes.c_ubyte * (width * height * 4))() - gdi32.GetDIBits(wt.HDC(memory), wt.HBITMAP(bitmap), 0, height, pixels, header, 0) - raw = bytes(pixels) - rows = [] - for y in range(height): - line = raw[y * width * 4:(y + 1) * width * 4] - rows.append(bytes(1) + bytes(b for i in range(0, len(line), 4) for b in (line[i + 2], line[i + 1], line[i]))) - - def chunk(kind, payload): - body = kind + payload - return struct.pack(">I", len(payload)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) - - png = (bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) + - chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + - chunk(b"IDAT", zlib.compress(b"".join(rows), 6)) + chunk(b"IEND", b"")) - with open(os.path.join(logdir, "window.png"), "wb") as handle: - handle.write(png) - title = ctypes.create_unicode_buffer(128) - user32.GetWindowTextW(wt.HWND(hwnd), title, 128) - print(f" window capture: {width}x{height} -> window.png (client area as on screen; title text length {len(title.value)})") - + if capture_thread: + capture_done.set() + capture_thread.join(30) + print(" " + series.summary() + f" (every {capture_every:g} s, window_<sss>s.png, at most {FILE_CAP} files)") if exit_code is None: try: capture_window() diff --git a/tools/startup/exit_report.py b/tools/startup/exit_report.py new file mode 100644 index 0000000000..cfc217dc26 --- /dev/null +++ b/tools/startup/exit_report.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Summarize how one startup run ended, using the existing debug-launch logs. + +The report is deliberately small: an exit code, one of six fixed end-state +labels, the last present counter and the last presented surface. Input paths, +module names, raw addresses, exception parameters and free-form text are never +copied. The parser accepts the log formats written by +tools/startup/debug_launch.py, tools/startup/run.ps1 and the runtime heartbeats. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass, field +import json +from pathlib import Path +import re +import sys +from typing import Iterable + + +LOG_NAMES = ("events.txt", "finished.txt", "run.out", "stderr.txt", "stdout.txt", "trap.log") +MAX_BYTES = 16 * 1024 * 1024 +FILTERED_FIRST_CHANCE = {"0x80000003", "0x80000004", "0x406d1388", "0x40010006"} + +RE_EXIT_EVENT = re.compile(r"^\s*(\d{1,10}(?:\.\d{1,6})?)\s+exit\s+(0x[0-9a-fA-F]{8})\s*$") +RE_EXIT_SUMMARY = re.compile(r"^process exited with (0x[0-9a-fA-F]{8}) after (\d{1,10}(?:\.\d{1,6})?) s$") +RE_STOP_SUMMARY = re.compile( + r"^stopped at [^(]+\((0x[0-9a-fA-F]{8})\) at .+ after (\d{1,10}(?:\.\d{1,6})?) s " + r"\((first|second) chance\)" +) +RE_DEBUGGER_STOP = re.compile(r"^debugger stop (0x[0-9a-fA-F]{8}) (first|second)-chance$") +RE_EXCEPTION = re.compile( + r"^\s*(\d{1,10}(?:\.\d{1,6})?)\s+exception\s+(0x[0-9a-fA-F]{8})\b.*?\b(first|second)-chance\b" +) +RE_TIMEOUT = re.compile(r"^timeout after (\d{1,10}(?:\.\d{1,6})?) s$") +RE_STOP_REQUEST = re.compile(r"^stopped by request after (\d{1,10}(?:\.\d{1,6})?) s \(stop file\)$") +RE_HEARTBEAT = re.compile( + r"x2w-d3d12 heartbeat: (\d{1,10}) frames presented in (\d{1,10}(?:\.\d{1,6})?) s " + r"\((\d{1,10}(?:\.\d{1,6})?) fps overall\)" +) +RE_SURFACE = re.compile( + r"x2w-render presented surface (\d{1,5})x(\d{1,5}) format (\d{1,3}), readback (\d{1,10}), " + r"mean level (\d{1,3}(?:\.\d{1,6})?)/255" +) +RE_CAPTURE = re.compile(r"^present frame (\d{1,10}) surface \S+$") + + +@dataclass +class ExitSummary: + exit_code: str | None = None + end_elapsed_s: float | None = None + timed_out: bool = False + stop_requested: bool = False + confirmed_stop: tuple[str, str] | None = None + first_exception: tuple[str, str] | None = None + last_exception: tuple[str, str] | None = None + exception_events: int = 0 + last_present_frames: int | None = None + last_present_s: float | None = None + last_present_fps: float | None = None + last_surface: tuple[int, int, int, int, str] | None = None + last_capture_frame: int | None = None + lines_scanned: int = 0 + + def classification(self) -> str: + if self.confirmed_stop is not None: + return "exception stop" + if self.timed_out: + return "timeout" + if self.stop_requested: + return "stopped by request" + if self.exit_code is not None: + return "clean exit" if self.exit_code == "0x00000000" else "nonzero exit" + return "missing exit event" + + def observe(self, line: str) -> None: + self.lines_scanned += 1 + match = RE_HEARTBEAT.search(line) + if match: + elapsed = float(match.group(2)) + if self.last_present_s is None or elapsed >= self.last_present_s: + self.last_present_frames = int(match.group(1)) + self.last_present_s = elapsed + self.last_present_fps = float(match.group(3)) + return + match = RE_SURFACE.search(line) + if match: + self.last_surface = ( + int(match.group(1)), int(match.group(2)), int(match.group(3)), + int(match.group(4)), match.group(5), + ) + return + match = RE_CAPTURE.match(line) + if match: + self.last_capture_frame = int(match.group(1)) + return + match = RE_EXIT_EVENT.match(line) + if match: + self.exit_code = match.group(2).lower() + self.end_elapsed_s = float(match.group(1)) + return + match = RE_EXIT_SUMMARY.match(line) + if match: + self.exit_code = match.group(1).lower() + self.end_elapsed_s = float(match.group(2)) + return + match = RE_TIMEOUT.match(line) + if match: + self.timed_out = True + self.end_elapsed_s = float(match.group(1)) + return + match = RE_STOP_REQUEST.match(line) + if match: + self.stop_requested = True + self.end_elapsed_s = float(match.group(1)) + return + match = RE_DEBUGGER_STOP.match(line) + if match: + self.confirmed_stop = (match.group(1).lower(), match.group(2)) + return + match = RE_STOP_SUMMARY.match(line) + if match: + self.confirmed_stop = (match.group(1).lower(), match.group(3)) + self.end_elapsed_s = float(match.group(2)) + return + match = RE_EXCEPTION.match(line) + if match and (match.group(3) == "second" or match.group(2).lower() not in FILTERED_FIRST_CHANCE): + exception = (match.group(2).lower(), match.group(3)) + self.exception_events += 1 + if self.first_exception is None: + self.first_exception = exception + self.last_exception = exception + + +def _read_logs(root: Path) -> dict[str, list[str]]: + logs: dict[str, list[str]] = {} + for name in LOG_NAMES: + path = root / name + if not path.is_file(): + continue + try: + data = path.read_bytes()[:MAX_BYTES] + except OSError: + continue + logs[name] = data.decode("utf-8", errors="replace").splitlines() + return logs + + +def summarize(root: Path) -> ExitSummary: + logs = _read_logs(root) + summary = ExitSummary() + # finished.txt is authoritative for the final state, so parse it after the other logs and + # let its exit code and end time overwrite an earlier duplicate event. + for name in LOG_NAMES: + if name in ("finished.txt", "run.out"): + continue + for line in logs.get(name, ()): + summary.observe(line) + for name in ("finished.txt", "run.out"): + for line in logs.get(name, ()): + summary.observe(line) + return summary + + +def _exception_text(exception: tuple[str, str] | None) -> str: + return "not reported" if exception is None else f"`{exception[0]}` ({exception[1]}-chance)" + + +def _exit_text(code: str | None) -> str: + return "not reported" if code is None else f"`{code}` ({int(code, 16)})" + + +def _time_text(value: float | None) -> str: + return "not reported" if value is None else f"`{value:.1f}` s" + + +def _present_text(summary: ExitSummary) -> str: + if summary.last_present_frames is not None and summary.last_present_s is not None: + fps = "" if summary.last_present_fps is None else f" (`{summary.last_present_fps:g}` fps overall)" + return f"`{summary.last_present_frames}` frames at `{summary.last_present_s:g}` s{fps}" + if summary.last_capture_frame is not None: + return f"capture frame `{summary.last_capture_frame}`" + return "not reported" + + +def _surface_text(summary: ExitSummary) -> str: + if summary.last_surface is None: + return "not reported" + width, height, format_code, readback, mean = summary.last_surface + return f"`{width}x{height}` format `{format_code}`, readback `{readback}`, mean level `{mean}/255`" + + +def format_markdown(summary: ExitSummary) -> str: + return "\n".join([ + "## Startup Exit Summary", + "", + "| Item | Value |", + "| --- | --- |", + f"| Exit code | {_exit_text(summary.exit_code)} |", + f"| Classification | {summary.classification()} |", + f"| End time | {_time_text(summary.end_elapsed_s)} |", + f"| Last present | {_present_text(summary)} |", + f"| Last presented surface | {_surface_text(summary)} |", + f"| First observed exception | {_exception_text(summary.first_exception)} |", + f"| Last observed exception | {_exception_text(summary.last_exception)} |", + f"| Observed exceptions | `{summary.exception_events}` |", + "", + ]) + + +def as_json(summary: ExitSummary) -> dict[str, object]: + return { + "exit_code": summary.exit_code, + "classification": summary.classification(), + "end_elapsed_s": summary.end_elapsed_s, + "last_present_frames": summary.last_present_frames, + "last_present_s": summary.last_present_s, + "last_present_fps": summary.last_present_fps, + "last_surface": None if summary.last_surface is None else { + "width": summary.last_surface[0], + "height": summary.last_surface[1], + "format": summary.last_surface[2], + "readback": summary.last_surface[3], + "mean_level": summary.last_surface[4], + }, + "first_exception": None if summary.first_exception is None else { + "code": summary.first_exception[0], "chance": summary.first_exception[1], + }, + "last_exception": None if summary.last_exception is None else { + "code": summary.last_exception[0], "chance": summary.last_exception[1], + }, + "exception_events": summary.exception_events, + "lines_scanned": summary.lines_scanned, + } + + +def main(argv: Iterable[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Summarize how one startup run ended without copying private text.") + parser.add_argument("logdir", type=Path, help="directory written by debug_launch.py or run.ps1") + parser.add_argument("--json", type=Path, help="also write the allowlisted fields as JSON") + args = parser.parse_args(list(argv) if argv is not None else None) + if not args.logdir.is_dir(): + print(f"exit_report: not a directory: {args.logdir}", file=sys.stderr) + return 2 + summary = summarize(args.logdir) + print(format_markdown(summary)) + if args.json: + args.json.parent.mkdir(parents=True, exist_ok=True) + args.json.write_text(json.dumps(as_json(summary), indent=2, sort_keys=True) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a19e68b695..148e8b9e6f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -19,6 +19,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) import disasm_rdna2 as D # noqa: E402 +from shader_minmax import FLOAT_MINMAX # noqa: E402 class Unsupported(Exception): @@ -127,7 +128,8 @@ def strip_header(code): FETCH_DXGI = {2: ('BUF_FMT_32_32_32_32_FLOAT', 16), 6: ('BUF_FMT_32_32_32_FLOAT', 12), 16: ('BUF_FMT_32_32_FLOAT', 8), 41: ('BUF_FMT_32_FLOAT', 4), 28: ('BUF_FMT_8_8_8_8_UNORM', 4), 49: ('BUF_FMT_8_8_UNORM', 2), 61: ('BUF_FMT_8_UNORM', 1), 34: ('BUF_FMT_16_16_FLOAT', 4), 35: ('BUF_FMT_16_16_UNORM', 4), - 37: ('BUF_FMT_16_16_SNORM', 4), 30: ('BUF_FMT_8_8_8_8_UINT', 4)} + 37: ('BUF_FMT_16_16_SNORM', 4), 30: ('BUF_FMT_8_8_8_8_UINT', 4), + 24: ('BUF_FMT_2_10_10_10_UNORM', 4)} # Typed buffer loads: (word load or None, the four component expressions). Components a format lacks read as # 0, 0, 0, 1 here, as in the existing tbuffer translation; that default is an assumption, not a measurement. FETCH_FORMATS = { @@ -136,6 +138,8 @@ def strip_header(code): 'BUF_FMT_8_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', 'U(((w >> 8) & 255) / 255.0)', '0u', 'U(1.0)']), 'BUF_FMT_8_UNORM': ('ldu({0}, a)', ['U((w & 255) / 255.0)', '0u', '0u', 'U(1.0)']), 'BUF_FMT_8_UINT': ('{0}.Load(a & ~3u) >> ((a & 3u) * 8u)', ['w & 255u', '0u', '0u', '1u']), + # Three 10-bit fields and a 2-bit one in one dword, lowest bits first: x, y, z, then w. + 'BUF_FMT_2_10_10_10_UNORM': ('ldu({0}, a)', ['U((w & 1023) / 1023.0)', 'U(((w >> 10) & 1023) / 1023.0)', 'U(((w >> 20) & 1023) / 1023.0)', 'U((w >> 30) / 3.0)']), 'BUF_FMT_16_16_UNORM': ('ldu({0}, a)', ['U((w & 65535) / 65535.0)', 'U((w >> 16) / 65535.0)', '0u', 'U(1.0)']), # Two unsigned 16-bit fields, x in the low half (LLVM 15: BUF_DATA_FORMAT_16_16 with BUF_NUM_FORMAT_UINT, # gfx10 unified format 27); a missing W of an integer format reads 1. @@ -162,7 +166,7 @@ def strip_header(code): DESC_FORMAT_UNKNOWN = 0x7fc0f0f0 DESC_FORMAT_CODES = { 'BUF_FMT_8_UNORM': 1, 'BUF_FMT_8_UINT': 5, 'BUF_FMT_8_8_UNORM': 14, 'BUF_FMT_32_FLOAT': 22, - 'BUF_FMT_16_16_UNORM': 23, 'BUF_FMT_16_16_SNORM': 24, 'BUF_FMT_16_16_UINT': 27, 'BUF_FMT_16_16_FLOAT': 29, 'BUF_FMT_8_8_8_8_UNORM': 56, 'BUF_FMT_8_8_8_8_UINT': 60, + 'BUF_FMT_2_10_10_10_UNORM': 50, 'BUF_FMT_16_16_UNORM': 23, 'BUF_FMT_16_16_SNORM': 24, 'BUF_FMT_16_16_UINT': 27, 'BUF_FMT_16_16_FLOAT': 29, 'BUF_FMT_8_8_8_8_UNORM': 56, 'BUF_FMT_8_8_8_8_UINT': 60, 'BUF_FMT_32_32_FLOAT': 64, 'BUF_FMT_16_16_16_16_FLOAT': 71, 'BUF_FMT_32_32_32_FLOAT': 74, 'BUF_FMT_32_32_32_32_FLOAT': 77} DESC_FORMAT_SHIFT, DESC_FORMAT_MASK = 12, 127 @@ -262,7 +266,8 @@ def starts_with_fetch_call(code): def parse_input_layout(text): """'ia1 <n>' then one '<semantic> <index> <format> <slot> <offset> <class> <step>' line per element.""" lines = text.split('\n') - if not re.fullmatch(r'ia1 ([1-9]|[12][0-9]|3[0-2])', lines[0]) or lines[-1] != '' or len(lines) != int(lines[0][4:]) + 2: + # 'ia1 0' is a layout the pipeline declares with no elements: no fetched input has a source. + if not re.fullmatch(r'ia1 (0|[1-9]|[12][0-9]|3[0-2])', lines[0]) or lines[-1] != '' or len(lines) != int(lines[0][4:]) + 2: raise Unsupported('invalid input layout request') elements, ends = [], {} for line in lines[1:-1]: @@ -314,6 +319,12 @@ def stream_fetch(vs_container, layout_text): if register not in inputs: raise Unsupported('vertex fetch record for input register %d outside the signature' % register) name, index, _ = inputs[register] + if not layout: + # Declared layout without elements: the input has no vertex buffer; its registers read as zero + # (shortcut: the zero default is an assumption, not a measurement). + fetch.append(dict(vgpr=vgpr, count=count, empty=True)) + at += 5 + continue match = [e for e in layout if (e['name'], e['index']) == (name, index)] if len(match) != 1: raise Unsupported('input layout has %d elements for vertex input register %d' % (len(match), register)) @@ -456,6 +467,16 @@ def check_encoding(code, off, n, name, asm): raise Unsupported('image_load_mip tfe') if word1 & (1 << 30): raise Unsupported('image_load_mip a16') + if name == 'global_load_dword': + if n != 8 or off + 8 > len(code): + raise Unsupported('global_load_dword encoding length %d at +0x%x' % (n, off)) + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & (1 << 25): + raise Unsupported('global_load_dword reserved bit 25 set at +0x%x' % off) + if word1 & (1 << 23): + raise Unsupported('global_load_dword nv') + if word1 & 0x0000ff00: + raise Unsupported('global_load_dword unused data field set at +0x%x' % off) if name in LDS_UNUSED_W1_MASK: if n != 8 or off + 8 > len(code): raise Unsupported('%s encoding length %d at +0x%x' % (name, n, off)) @@ -471,7 +492,7 @@ def check_encoding(code, off, n, name, asm): word0, word1 = struct.unpack_from('<2I', code, off) if word0 & 0x700 or word1 & 0xe0000000: raise Unsupported('%s with neg/abs: not a 16-bit integer source modifier' % name) - if name in ('v_sad_u8', 'v_sad_u16', 'v_sad_u32', *VOP3_ONLY_VEC_U): + if name in ('v_lerp_u8', 'v_perm_b32', 'v_sad_u8', 'v_sad_hi_u8', 'v_sad_u16', 'v_sad_u32', 'v_msad_u8', *VOP3_ONLY_VEC_U): # VOP3A integer forms take no source abs/neg; refuse those bits here so neg on an inline # integer does not print as -N and get accepted as a negative constant. word0, word1 = struct.unpack_from('<2I', code, off) @@ -479,6 +500,16 @@ def check_encoding(code, off, n, name, asm): raise Unsupported('%s with neg/abs' % name) if name in VOP3_ONLY_VEC_U and (word1 >> 18) & 0x1ff: raise Unsupported('%s with unused src2 field set' % name) + if name.removesuffix('_e64') == 'v_ldexp_f32': + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x600 or word1 & 0xc0000000: + raise Unsupported('%s with neg/abs on exponent or unused source' % name) + if (word1 >> 18) & 0x1ff: + raise Unsupported('%s with unused src2 field set' % name) + if name == 'v_mad_i32_i16': + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x700 or word1 & 0xe0000000: + raise Unsupported('%s with neg/abs' % name) if name == 'v_cvt_off_f32_i4_e64': # Integer-nibble conversion: the instruction has one source, so only src0's VOP3A ABS (w0[8]) and NEG # (w1[29]) can carry a modifier. Masking all three bit positions of each field (w0[10:8], w1[31:29]) @@ -487,6 +518,20 @@ def check_encoding(code, off, n, name, asm): word0, word1 = struct.unpack_from('<2I', code, off) if word0 & 0x700 or word1 & 0xe0000000: raise Unsupported('%s with neg/abs: not a 4-bit integer source modifier' % name) + if name in ('v_add_nc_i32', 'v_sub_nc_i32'): + # VOP3A signed 32-bit add/sub take no source abs/neg and only two sources (src2 must be zero). + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x700 or word1 & 0xe0000000: + raise Unsupported('%s with neg/abs' % name) + if (word1 >> 18) & 0x1ff: + raise Unsupported('%s with unused src2 field set' % name) + if name == 'v_sat_pk_u8_i16_e64': + # 1-source integer VOP3A form: refuse abs/neg and any non-zero unused src1/src2 fields. + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x700 or word1 & 0xe0000000: + raise Unsupported('%s with neg/abs' % name) + if (word1 >> 9) & 0x3ffff: + raise Unsupported('%s with unused src1/src2 field set' % name) if name == 'v_cndmask_b32_e64': # The printed -1 is ambiguous: it can be plain inline -1 or inline 1 with NEG. word0, word1 = struct.unpack_from('<2I', code, off) @@ -528,6 +573,8 @@ def check_encoding(code, off, n, name, asm): float_sources = VEC_F[base][0] elif re.fullmatch(r'v_cmpx?_\w+_f32', base): float_sources = 1 if base in ('v_cmp_class_f32', 'v_cmpx_class_f32') else 2 + elif base == 'v_ldexp_f32': + float_sources = 1 rewritten = {} for i in range(3): if name == 'v_cndmask_b32_e64' and i < 2 or not word1 & (1 << (29 + i)): @@ -620,6 +667,16 @@ def fbits(x): return struct.unpack('<I', struct.pack('<f', x))[0] +def ptr_high_symbol(source, offset): + """High word of a 64-bit pointer advanced by a literal offset: the original word, or the one a completed + s_addc_u32 produced for exactly that accumulated offset (an advanced word never equals another offset's).""" + return ('ptrhi', source) if not offset else ('ptrhi', source, offset) + + +# Sources whose pointer is a 64-bit register pair (the low word 'ptr', the high word 'ptrhi'). +PTR64_SOURCES = ('root', 'vbtab') + + @functools.lru_cache(maxsize=None) def reg_range(tok): """'s[8:11]' -> ('s', 8, 11); 's8' -> ('s', 8, 8); 'v[1:3]' -> ('v', 1, 3); 'exec'/'vcc' pairs too.""" @@ -651,6 +708,7 @@ def reg_range(tok): EXECZ_REFUSED = ('s_endpgm', 's_store', 's_atomic', 's_buffer_store', 's_buffer_atomic', 's_barrier', 's_sendmsg', 's_setreg', 's_setpc', 's_swappc', 's_dcache', 's_icache', 's_gl1', 's_memtime', 's_memrealtime', 's_trap', 's_sleep', 'v_writelane', 's_movrel', 'v_movrel') +EXECZ_EXIT_WAITS = ('s_nop', 's_waitcnt', 's_waitcnt_depctr') def scalar_tokens(text): @@ -732,6 +790,93 @@ def clear_after(name, asm, may, clear): return out | {(word, h) for word, held in writes for h in held} +EXEC_SUBSET = frozenset({('exec', 0), ('exec_hi', 1)}) + + +def subset_after(name, asm, may, clear): + """Forward step before an s_cbranch_execz: scalar words known to have bit 0 wherever current EXEC has bit 0. + + When EXEC is unchanged, bitwise mask instructions propagate those subset facts via clear_after and non-mask + writes drop them. When EXEC is written, facts on the written wave half are dropped unless a move assigns EXEC + from a scalar mask word (so that word equals the new EXEC) or an OR widens EXEC with an existing bitmask. + Indirect scalar writes (s_movrel*) drop all non-EXEC facts.""" + base = re.sub(r'_e(32|64)$', '', name) + if base.startswith('s_movrel'): + return EXEC_SUBSET + if not (may & EXEC_KEYS): + return frozenset(clear_after(name, asm, may, clear)) | EXEC_SUBSET + kept = ({0} if 'exec' not in may else set()) | ({1} if 'exec_hi' not in may else set()) + shape = clear_shape(name, asm) + if shape and shape != 'cmpx': + op, saving, count, words = shape + if op == 'or' and (saving == '_saveexec' or any( + all(src[p] == ('exec', 'exec_hi')[p] for p in range(count)) for src in words[1:])): + return frozenset(clear_after(name, asm, may, clear)) | EXEC_SUBSET + out = {fact for fact in clear if fact[1] in kept and fact[0] not in may - EXEC_KEYS} + if op == 'mov' and saving is None: + dest, src = words + for p, dw in enumerate(dest): + if dw in EXEC_KEYS: + h = 0 if dw == 'exec' else 1 + sw = src[p] + if re.fullmatch(r's\d+|vcc(_hi)?', sw): + out.add((sw, h)) + return frozenset(out) | EXEC_SUBSET + return frozenset(fact for fact in clear if fact[1] in kept and fact[0] not in may - EXEC_KEYS) | EXEC_SUBSET + + +def mask_lanes(name, asm): + """(operation, destination words, source word lists) of a bitwise scalar mask instruction, or None. Word p of + every operand holds the same lanes: wave half p of a 64-bit form.""" + m = re.fullmatch(r's_(mov|and|andn2|or|orn2|nand|nor|xor|xnor)_b(32|64)', re.sub(r'_e(32|64)$', '', name)) + if not m: + return None + words = [mask_words(op, 2 if m.group(2) == '64' else 1) for op in parse(asm)[1]] + if None in words or len(words) != (2 if m.group(1) == 'mov' else 3): + return None + return m.group(1), words[0], words[1:] + + +def high_half_of_b32(lanes, word): + """True for a 32-bit form that names the high half of a mask (vcc_hi): its bit n is lane 32 + n, which the word + position of a one-word operand (always the low half) does not say, so no lane-wise rule applies to it.""" + return word.endswith('_hi') and len(lanes[1]) == 1 + + +def exec_absorbs(name, asm, word): + """True when an instruction reads `word` only through an operation whose result bit is fixed while the exec bit + of the same lanes is clear: W & exec and exec & W give 0, ~(W & exec) and W | ~exec give 1.""" + lanes = mask_lanes(name, asm) + if not lanes or lanes[0] not in ('and', 'nand', 'orn2') or high_half_of_b32(lanes, word): + return False + a, c = lanes[2] + pairs = [(a, c)] if lanes[0] == 'orn2' else [(a, c), (c, a)] + return any(word in w and word not in e and all(e[p] == ('exec', 'exec_hi')[p] for p in range(len(w)) if w[p] == word) + for w, e in pairs) + + +def kept_halves(name, asm, word, clear): + """Wave halves whose lanes keep their bit of `word` through `s_andn2 R, R, X` when X is clear for them: R & ~X + keeps bit n of R when bit n of X is clear. Empty for any other write of `word`.""" + lanes = mask_lanes(name, asm) + if not lanes or lanes[0] != 'andn2' or lanes[1] != lanes[2][0]: + return set() + return {h for p, w in enumerate(lanes[1]) if w == word for key, h in clear if key == lanes[2][1][p]} + + +def lane_read(name, asm, word, halves): + """True when an instruction reads `word` as a lane mask, bit n of each result from bit n of the sources, with + `word` in a position whose lanes are in `halves`, any exec operand there the exec word of those lanes, and the + result there written to that exec word or back to `word`, not copied to another register.""" + lanes = mask_lanes(name, asm) + if not lanes or high_half_of_b32(lanes, word): + return False + _, dest, srcs = lanes + at = {p for src in srcs for p, w in enumerate(src) if w == word} + return bool(at) and at <= halves and all(dest[p] in (word, ('exec', 'exec_hi')[p]) for p in at) and all( + w == ('exec', 'exec_hi')[p] for src in srcs for p, w in enumerate(src) if p in at and w in EXEC_KEYS) + + def scalar_effects(name, asm): """(reads, must-writes, may-writes) of scalar state for one decoded instruction.""" base = re.sub(r'_e(32|64)$', '', name) @@ -763,6 +908,10 @@ def scalar_effects(name, asm): may |= EXEC_KEYS if (base in SCA and SCA[base][1]) or 'saveexec' in base or 'wrexec' in base: writes.add('scc') + # Wave64 compare and carry-out instructions print vcc_lo but may also write vcc_hi. + if 'vcc' in writes and base.startswith(('v_cmp', 'v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale', + 'v_mad_u64_u32')): + may.add('vcc_hi') return reads, writes, writes | may | ({'scc'} if base.startswith('s_') else set()) # Forms with no scalar destination: their printed operands are all sources (v_cmpx writes only EXEC, which the @@ -773,6 +922,9 @@ def scalar_effects(name, asm): TWO_SCALAR_DESTINATIONS = ('v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale', 'v_mad_u64_u32', 'v_mad_i64_i32') # Symbols whose register also holds the value at run time: constants are assigned when set, entry root constants are # assigned at entry when a join needs it, and the others are assigned when tracked. +# Longest uniform HLSL expression a VGPR keeps for a first-lane read: a chain past it is no longer recomputable. +UNIFORM_EXPR_LIMIT = 4096 + RUN_TIME_SYMBOLS = ('const', 'ud', 'execcopy', 'fixed_buffer_word') @@ -789,14 +941,21 @@ def names_one_value(sym): if sym is None: return False if sym[0] == 'desc': - # ('desc', source, load offset, dword) and, in a compute stage, the offset of the s_load that read it: the - # source does not record an addend on the pointer, so only the same load proves the same words. + # A compute descriptor can also carry an integer tag identifying the load or constant high word. return len(sym) == 4 or (len(sym) == 5 and isinstance(sym[4], int)) - # An add on a pointer keeps its symbol and marks it 'added' (the offset is not in the tuple), so only an - # untouched pointer, exactly (kind, source), names one value. + # A table and a known byte offset identify one descriptor address. The legacy 'added' + # marker carries no offset, so two occurrences of it can denote different addresses. + if sym[0] == 'ptr' and len(sym) == 3 and sym[1][0] == 'table': + return isinstance(sym[2], int) return sym[0] in ('const', 'ud', 'execcopy') or (sym[0] in ('ptr', 'ptrhi') and len(sym) == 2) +def descriptor_select(sym): + """True for what Stage.scalar_select records for a compute s_cselect_b32 with a descnum arm: + ('descnum', 'cselect', select offset, arm, arm). It has no run-time value, so no consumer may read it as one.""" + return bool(sym) and sym[:2] == ('descnum', 'cselect') + + def scalar_destinations(name, asm): """The SGPRs (and 'm0') an instruction may write; 'any' for s_movrel*, whose register comes from m0.""" if name.startswith(NO_SCALAR_DESTINATION) or '_store' in name: @@ -863,6 +1022,12 @@ def smem_offset(tok): return '0' if tok == 'off' else tok +MODIFIER_FREE_HANDLERS = frozenset(( + 'op_v_mov_b32', 'op_v_cvt_pkrtz_f16_f32', 'op_v_interp_p1_f32', + 'op_v_interp_p2_f32', 'op_v_interp_mov_f32', +)) + + def smem_mods(mods): """Non-negative 21-bit signed immediate byte offset from SMEM modifiers, refusing unknown or negative forms.""" imm = None @@ -882,16 +1047,42 @@ def smem_mods(mods): # Each conversion uses only its input bits (including byte extraction for ubyte0). -# Multiply, fused multiply-add (including the literal form), reciprocal and median of three use +# Multiply, fused multiply-add (including the literal form), reciprocal, log2, ceil and median of three use # only local arithmetic. Move copies its input bits. None reads a lane ID or another lane. UNIFORM_VALU = frozenset(( 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_ubyte0', 'v_cvt_off_f32_i4', 'v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32', - 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', + 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_log_f32', 'v_ceil_f32', + 'v_med3_f32', 'v_mov_b32', + # Pure 32-bit integer ALU: each lane computes the result from its own sources only, so equal sources give + # equal results in every lane (no carry-out, no lane ID, no cross-lane read). + 'v_add_nc_u32', 'v_sub_nc_u32', 'v_subrev_nc_u32', 'v_add_nc_i32', 'v_sub_nc_i32', + 'v_and_b32', 'v_or_b32', 'v_xor_b32', 'v_not_b32', + 'v_lshlrev_b32', 'v_lshrrev_b32', 'v_ashrrev_i32', 'v_mul_lo_u32', 'v_mul_u32_u24', + 'v_min_u32', 'v_max_u32', 'v_min_i32', 'v_max_i32', )) +UNIFORM_LOAD_WORDS = {'buffer_load_dword': 1, 'buffer_load_dwordx2': 2, 'buffer_load_dwordx3': 3, 'buffer_load_dwordx4': 4, + 'buffer_load_format_x': 1, 'buffer_load_format_xy': 2, 'buffer_load_format_xyz': 3, + 'buffer_load_format_xyzw': 4} +UNIFORM_LOADS = frozenset(UNIFORM_LOAD_WORDS) +UNIFORM_IMAGE_LOADS = frozenset(('image_load', 'image_load_mip')) + # DPP quad_perm selections that exchange lanes of a 2x2 pixel quad (lane = 2 * y + x), with the SM 6.0 intrinsic. +# Image ops that take implicit derivatives of the pixel quad (see Stage.quad_vote). +DERIVATIVE_OPS = ('image_sample_b', 'image_get_lod') +# "Some lane of the 2x2 quad has bit 0 set": fine derivatives of a 0/1 value read the row neighbour (ddx_fine), then +# the other row (ddy_fine). Exact for 0/1 and defined only where the quad runs the statement together (SM 5.0 and 6.0). +# The derivatives are arithmetic operands, not operands of a short-circuit ||: a DXC build for some GPUs moved a derivative +# under the condition of an ||, where only some lanes ran it (measured on a hardware adapter). +QUAD_ANY_HLSL = [ + 'bool x2w_quad_any(uint bit) {', + ' float lane = (bit & 1u) != 0u ? 1.0 : 0.0;', + ' float row = (lane + abs(ddx_fine(lane)) != 0.0) ? 1.0 : 0.0;', + ' return row + abs(ddy_fine(row)) != 0.0;', + '}', +] QUAD_SWAPS = {(1, 0, 3, 2): 'QuadReadAcrossX', (2, 3, 0, 1): 'QuadReadAcrossY', (3, 2, 1, 0): 'QuadReadAcrossDiagonal'} @@ -920,6 +1111,87 @@ def writes_exec(name, ops): return 'saveexec' in name or 'wrexec' in name or name.startswith(('v_cmpx', 's_movreld')) +# In wave32 VCC is vcc_lo alone and vcc_hi is a free scalar register that compilers allocate like any other (RDNA 2 +# ISA, "VCC": in wave32 only VCC_LO is the condition mask). The translator models it as an ordinary SGPR the program +# never names, taken from the top of the 106 (beyond the user-data and system registers set at entry). +def vcc_hi_whole_word_writer(name, ops): + """True when the instruction's first operand is vcc_hi and its name is a scalar instruction or an actual lane-read + writer (v_readlane, v_readfirstlane): the register then holds one whole word, not one bit per lane.""" + return ops[:1] == ['vcc_hi'] and (name.startswith('s_') or name.startswith(('v_readlane', 'v_readfirstlane'))) + + +def vcc_hi_scalar_mask_read(ins): + """True when a VOP3 lane-mask source reads vcc_hi after a (whole-word) scalar or lane-read writer wrote it (or the + program branches, so the order is unknown): the renamed register then holds a whole word, not the current lane's + bit, and the lowering would test bit 0 of it for every lane. A compare or carry-out that wrote vcc_hi last keeps + the per-lane form.""" + scalar, branchy, read_after = False, False, False + reads = False + for _o, _n, name, asm in ins: + ops = parse(asm)[1] + branchy |= name.startswith(('s_cbranch', 's_branch')) + if (name.startswith('v_cmp_') and ops[:1] == ['vcc_hi']) or (VOP3B_SDST.match(name) and ops[1:2] == ['vcc_hi']): + scalar = False + elif vcc_hi_whole_word_writer(name, ops): + scalar = True + if name in ('v_cndmask_b32_e64', 'v_add_co_ci_u32_e64', 'v_sub_co_ci_u32_e64', 'v_subrev_co_ci_u32_e64') \ + and ops[-1:] == ['vcc_hi']: + reads = True + read_after |= scalar + return read_after or (reads and branchy and any( + vcc_hi_whole_word_writer(name, parse(asm)[1]) for _o, _n, name, asm in ins)) + + +def wave32_vcc_hi(ins): + """`ins` with every vcc_hi operand renamed to an unused SGPR when vcc_hi is provably an ordinary scalar register, + else `ins`. + + The decoder prints wave32 syntax, so the program text alone does not give the wave size. vcc_hi holds its own + word in both wave sizes as long as only scalar instructions write it; in wave64 a VALU write of VCC (a compare, + a carry-out, v_div_scale, printed as vcc_lo) also writes vcc_hi with the high lanes, and a VALU mask read of VCC + (v_cndmask_b32_e32, a carry-in, v_div_fmas) or s_cbranch_vccz/vccnz reads vcc_hi for them. So the rename is + exact when + - no instruction names the 64-bit pair `vcc` (whose high word would then be vcc_hi), and + - a VALU compare or carry writes vcc_hi or an odd SGPR, or a VOP3 mask source reads one (a misaligned pair in + wave64, so the program is wave32), or no VALU instruction and no vcc branch uses vcc_lo as a lane mask. + Otherwise, or when M0-relative s_movrel* could reach the chosen register, vcc_hi is left alone and refused.""" + if not any(re.search(r'\bvcc_hi\b', asm) for *_, asm in ins): + return ins + if any(re.search(r'\bvcc\b', asm) or name.startswith('s_movrel') for _o, _n, name, asm in ins): + return ins + masks = [] # lane-mask destinations of VALU compares and carry-outs (VOP3b SDST) + for _o, _n, name, asm in ins: + ops = parse(asm)[1] + if name.startswith('v_cmp_') and ops: + masks.append(ops[0]) + elif VOP3B_SDST.match(name) and len(ops) > 1: + masks.append(ops[1]) + if name in ('v_cndmask_b32_e64', 'v_add_co_ci_u32_e64', 'v_sub_co_ci_u32_e64', 'v_subrev_co_ci_u32_e64') \ + and ops[-1] != 'vcc_lo': + masks.append(ops[-1]) # a lane-mask source is a pair in wave64 too: vcc_hi or an odd SGPR proves wave32 + odd = any((reg_range(tok) or ('', 0, 1))[0] == 's' and reg_range(tok)[1] == reg_range(tok)[2] + and reg_range(tok)[1] % 2 for tok in masks) + # Without that proof the program may be wave64, where every VALU use of VCC as a lane mask (a write, an + # implicit or explicit mask source such as v_cndmask_b32_e32, a carry-in, v_div_fmas) and s_cbranch_vccz/vccnz + # see vcc_hi for lanes 32..63: none may be present. + vcc_mask_use = any((name.startswith('v_') and re.search(r'\bvcc_lo\b', asm)) or name.startswith('v_div_fmas') + or name in ('s_cbranch_vccz', 's_cbranch_vccnz') for _o, _n, name, asm in ins) + if 'vcc_hi' not in masks and not odd and vcc_mask_use: + return ins + if vcc_hi_scalar_mask_read(ins): + return ins + named = set() + for *_, asm in ins: + for lo, hi, single in re.findall(r'\bs\[(\d+):(\d+)\]|\bs(\d+)\b', asm): + if lo and int(lo) <= 107 <= int(hi): + return ins # a wide operand such as s[104:107] covers SGPR 107, which is vcc_hi: no free alias + named.update(range(int(lo), int(hi) + 1) if lo else (int(single),)) + free = next((n for n in range(105, 63, -1) if n not in named), None) + if free is None: + return ins + return [(off, n, name, re.sub(r'\bvcc_hi\b', 's%d' % free, asm)) for off, n, name, asm in ins] + + def pc_pair(token): """Only aligned pairs of ordinary SGPRs can carry a symbolic code address.""" r = reg_range(token) @@ -1109,7 +1381,7 @@ def clobber(written): scc = None elif not name.startswith(('v_', 's_branch', 's_cbranch_', 's_mov_', 's_movk_', 's_load_', 's_buffer_load_', 's_nop', 's_waitcnt', 's_inst_prefetch', 's_clause', - 'buffer_', 'tbuffer_', 'image_', 'exp', 'ds_')): + 'buffer_', 'tbuffer_', 'global_', 'image_', 'exp', 'ds_')): scc = -1 if name in ('s_swappc_b64', 's_call_b64', 's_rfe_b64'): @@ -1161,6 +1433,81 @@ def clobber(written): return lowered +TERMINAL_NOP_NAMES = ('s_nop', 'v_nop') + + +def terminal_continuation_proof(ins, calculated): + """Prove a single calculated forward transfer onto a pure terminating continuation in a two-exit program.""" + transfers = [(off, target) for off, target in calculated.items() if target is not None] + ends = [off for off, _, name, _ in ins if name == 's_endpgm'] + if len(transfers) != 1 or len(ends) != 2: + return None + setpc, target = transfers[0] + if target <= setpc: + raise Unsupported('far early-out: the calculated continuation target %#x is not forward' % target) + by_off = {off: (n, name, asm) for off, n, name, asm in ins} + if setpc not in by_off: + raise Unsupported('far early-out: the calculated transfer is not a decoded instruction') + # GETPC, ADD, ADDC and SETPC must be contiguous; a literal ADD occupies eight bytes. + elided = sorted(off for off in calculated if off < setpc) + chain = list(elided[-3:]) + [setpc] + if (len(elided) != 3 or any(off not in by_off for off in chain) + or chain[0] + by_off[chain[0]][0] != chain[1] or chain[1] + by_off[chain[1]][0] != chain[2] + or chain[2] + by_off[chain[2]][0] != chain[3]): + raise Unsupported('far early-out: the documented GETPC/ADD/ADDC/SETPC chain is not contiguous') + get_n, _, get_asm = by_off[chain[0]] + _, add_name, add_asm = by_off[chain[1]] + _, addc_name, addc_asm = by_off[chain[2]] + set_n, _, set_asm = by_off[chain[3]] + get_ops, get_mods = parse(get_asm)[1:] + add_ops, add_mods = parse(add_asm)[1:] + addc_ops, addc_mods = parse(addc_asm)[1:] + set_ops, set_mods = parse(set_asm)[1:] + pair = pc_pair(get_ops[0]) if len(get_ops) == 1 and not get_mods and get_n == 4 else None + if (pair is None or set_ops != ['s[%d:%d]' % (pair, pair + 1)] or set_mods or set_n != 4 + or add_name != 's_add_u32' or addc_name != 's_addc_u32'): + raise Unsupported('far early-out: the calculated transfer does not use the documented chain form') + displacement = pc_word(add_ops[2]) if len(add_ops) == 3 and add_ops[0] == add_ops[1] == 's%d' % pair and not add_mods else None + extension = pc_word(addc_ops[2]) if len(addc_ops) == 3 and addc_ops[0] == addc_ops[1] == 's%d' % (pair + 1) and not addc_mods else None + if displacement is None or extension is None or extension != (-1 if displacement < 0 else 0): + raise Unsupported('far early-out: the displacement is not a complete constant with its matching sign extension') + if target != chain[0] + get_n + displacement: + raise Unsupported('far early-out: the proven target disagrees with the chain displacement') + # An ordinary definition of either scratch register would outlive the elided chain. + for off, _n, name, asm in ins: + if off in calculated: + continue + if {pair, pair + 1} & scalar_registers(asm): + raise Unsupported('far early-out: the scratch pair s[%d:%d] is not fresh' % (pair, pair + 1)) + branch_targets = set() + for off, _n, name, asm in ins: + if name == 's_setpc_b64': + to = calculated.get(off) + elif name.startswith('s_cbranch') or name == 's_branch': + to = int(parse(asm)[1][0].split('_')[1], 16) + else: + continue + if to is not None: + branch_targets.add(to) + for off in chain[1:]: + if off in branch_targets: + raise Unsupported('far early-out: a branch enters the chain interior at +0x%x' % off) + # Even exp null with vm may change pixel validity; only observable no-op instructions are admitted. + at = target + while at in by_off: + _n, name, asm = by_off[at] + if name in TERMINAL_NOP_NAMES: + at += 4 + continue + if name == 's_endpgm': + if asm != 's_endpgm' or at != ends[-1]: + raise Unsupported('far early-out: the continuation ends at +0x%x, not the program\'s final exit' + % at) + return setpc, target, tuple(chain) + raise Unsupported('far early-out: the continuation instruction %s is not a pure terminating no-op' % asm.split()[0]) + raise Unsupported('far early-out: the continuation leaves the decoded program before ending') + + def _lds_single(tok): """Single hardware VGPR vN (v0..v255) for bounded LDS exchange validation.""" m = re.fullmatch(r'v(\d+)', tok) @@ -1221,7 +1568,7 @@ def lds_byte_offsets(name, mods): def check_lds_exchange(ins, group, words): - """Prove one race-free 32/64/128-bit fill of a contiguous LDS span, one uniform barrier, then mixed-width reads of initialized dwords. + """Prove a race-free LDS fill (or two disjoint dword fills), one uniform barrier, then reads of initialized dwords. RDNA 2 ISA (Ch. 9 DS): ds_write_b32 / ds_read_b32 / ds_read2_b32 access 4-byte dwords, ds_write_b64 / ds_read_b64 access two contiguous little-endian dwords (v[n] at addr+offset, v[n+1] at addr+offset+4), and @@ -1231,7 +1578,7 @@ def check_lds_exchange(ins, group, words): """ if not 0 < words <= 8192 or group[0] < 1 or group[1:] != (1, 1): raise Unsupported('LDS exchange needs a 1D group and a nonzero allocation of at most 32 KiB') - fill_span = None + fill_spans = [] published = False read = False prev = (None, [], []) @@ -1242,7 +1589,7 @@ def check_lds_exchange(ins, group, words): or base == 's_endpgm' and i + 1 < len(ins)): raise Unsupported('LDS exchange needs straight-line code and entry EXEC') if base == 's_barrier': - if (fill_span is None or published or prev != ('s_waitcnt', ['lgkmcnt(0)'], []) + if (not fill_spans or published or prev != ('s_waitcnt', ['lgkmcnt(0)'], []) or mods or ops not in ([], ['0'], ['0x0'])): raise Unsupported('LDS exchange needs one barrier after a completed fill') published = True @@ -1266,10 +1613,22 @@ def check_lds_exchange(ins, group, words): offset, = offsets # The prefix below preserves the entry X ID in v0. Each lane writes exactly one distinct element. # 8-byte / 16-byte alignment is not required for LDS dword-addressed writes. - if (fill_span is not None or producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] - or modifiers or offset % 4 or offset + group[0] * width > words * 4): + end = offset + group[0] * width + if (offset % 4 or end > words * 4 or published + or fill_spans and (base != 'ds_write_b32' or producer != 'ds_write_b32')): raise Unsupported('LDS exchange needs one bounded %s per local X ID' % unit_name) - fill_span = (offset, offset + group[0] * width) + if fill_spans: + if len(fill_spans) != 1: + raise Unsupported('LDS exchange allows at most two consecutive bounded dword fills') + # Consecutive DS writes preserve the proven address VGPR. + if addr_op != args[0]: + raise Unsupported('LDS dword fills must use the same byte address VGPR') + start0, end0 = fill_spans[0] + if offset < end0 and start0 < end: + raise Unsupported('LDS dword fills must be disjoint') + elif producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] or modifiers: + raise Unsupported('LDS exchange needs one bounded %s per local X ID' % unit_name) + fill_spans.append((offset, end)) else: if not published or modifiers or not args or args[0] != addr_op: raise Unsupported('LDS read needs a bounded address after the fill barrier') @@ -1280,11 +1639,10 @@ def check_lds_exchange(ins, group, words): low, high = 0, int(args[1], 0) else: raise Unsupported('LDS read needs a literal or literal-masked byte address') - fill_start, fill_end = fill_span - # Every byte offset in [a + offset, a + offset + width) must be 4-byte aligned and inside the filled span. - # Mixed 32/64/128-bit reads share the same dword-indexed LDS array once all read dwords lie in [fill_start, fill_end). + # Each read must fit entirely within one initialized span, even when the banks have a gap. if (low % 4 or high % 4 - or any(offset % 4 or low + offset < fill_start or high + offset + width > fill_end + or any(offset % 4 or not any(start <= low + offset and high + offset + width <= end + for start, end in fill_spans) for offset in offsets)): raise Unsupported('LDS read outside the aligned, initialized span') if i + 1 >= len(ins) or ins[i + 1][3] != 's_waitcnt lgkmcnt(0)': @@ -1292,7 +1650,7 @@ def check_lds_exchange(ins, group, words): read = True elif base.startswith('ds_') or 'lds' in mods: raise Unsupported('LDS exchange does not cover ' + asm) - elif fill_span is None and not base.startswith('s_'): + elif not fill_spans and not base.startswith('s_'): # Simple VALU instructions only write their single destination. Other forms, e.g. v_swap_b32, # can also change a source. After the fill, each read proves its own address without the entry X ID. if (base not in VEC_U and base not in VEC_F and base != 'v_mov_b32' @@ -1375,16 +1733,193 @@ def mesh_run(ins, at, what, patterns, env): MESH_VCC_BRANCHES = ('s_cbranch_vccz', 's_cbranch_vccnz') +# Vector ALU forms that take a lane mask as a per-lane select or carry, which the one-lane model handles. +MASK_AWARE_VALU = frozenset({'v_cndmask_b32', 'v_cndmask_b16', 'v_readlane_b32', 'v_writelane_b32', 'v_readfirstlane_b32'}) +MASK_AWARE_VALU_RE = re.compile(r'_co(_ci)?_|addc|subb|_co$|^v_mad_[iu]64_[iu]32$|^v_(cndmask|readlane|writelane|readfirstlane)_') +# Scalar ALU forms that move or combine lane masks bit by bit, which the one-lane model handles (s_ff1_i32_b32 refuses +# anything but exec_lo at the entry mask itself). Any other scalar op that +# reads a lane mask (s_cmp*, s_cmpk*, s_bcnt*, s_lshr, s_add ...) reads the whole wave's word as a number. +MASK_AWARE_SALU_RE = re.compile(r'^s_(mov|and|or|xor|andn2|orn2|nand|nor|xnor|not|cselect|wqm|cbranch|and_saveexec|or_saveexec|' + r'xor_saveexec|andn2_saveexec|orn2_saveexec|nand_saveexec|nor_saveexec|xnor_saveexec|' + r'ff1|bitset[01]|setpc|getpc|swappc|branch|waitcnt|endpgm|nop)(_|$)') +# Scalar ops whose result is a lane mask when a source is one (a copy or a bitwise combination), unlike s_ff1 or s_bitset. +MASK_COPY_SALU_RE = re.compile(r'^s_(mov|and|or|xor|andn2|orn2|nand|nor|xnor|not|wqm)_b(32|64)$') VCC_KEYS = {'vcc', 'vcc_hi'} -def mesh_skeleton(ins, vcc_branches, wave_limits): +MESH_LOOP_REFUSAL = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' +SCALAR_LOADS = ('s_buffer_load_dword', 's_buffer_load_dwordx2', 's_buffer_load_dwordx4', + 's_buffer_load_dwordx8', 's_buffer_load_dwordx16', 's_load_dword', 's_load_dwordx2', + 's_load_dwordx4', 's_load_dwordx8', 's_load_dwordx16') + + +def mesh_wave_block_scalar(name, asm): + """True for an instruction of a pre-exchange execz block that the lowering may run for every lane of a wave with + an active lane: a listed scalar buffer load or scalar ALU whose operands are SGPRs, SCC and constants only.""" + if name in SCALAR_LOADS: + pass + elif name.startswith('v_cmp_'): + # A per-lane compare whose only scalar effect is its VCC destination; the caller refuses a VCC live at the join. + return not re.search(r'\b(exec|m0|src_)', asm) and scalar_effects(name, asm)[2] <= VCC_KEYS + elif not name.startswith('s_') or name.startswith(EXECZ_REFUSED + NO_SCALAR_DESTINATION + ( + 's_load', 's_getpc', 's_setpc', 's_swappc', 's_call', 's_get', 's_set', 's_movrel', 's_rfe', 's_trap', + 's_memtime', 's_memrealtime', 's_buffer_load', 's_scratch', 's_dcache', 's_gl1', 's_wqm', 's_quadmask', + 's_denorm_mode', 's_round_mode')): + return name.startswith(('s_cmp_', 's_bitcmp')) and not re.search(r'\b(exec|vcc|m0|src_)', asm) + if re.search(r'\b(exec|m0|src_|ttmp|tba|tma|flat_scratch|xnack)', asm) or 'saveexec' in name: + return False + reads, must, may = scalar_effects(name, asm) + return all(reg in ('scc', 'vcc', 'vcc_hi') or re.fullmatch(r's\d+', reg) for reg in reads | must | may) + + +MESH_TRIP_STEPS = ('s_add_u32', 's_add_i32', 's_sub_u32', 's_sub_i32') +MESH_TRIP_MAX = 64 + + +def mesh_inline_u32(tok): + """An inline integer or float-bit SOP operand as a u32, or None.""" + if tok in FLOATS: + return fbits(FLOATS[tok]) & 0xffffffff + m = re.fullmatch(r'-?(?:0x[0-9a-f]+|\d+)', tok) + if not m: + return None + value = int(tok, 0) + return value & 0xffffffff if value >= 0 else (value + (1 << 32)) & 0xffffffff + + +def mesh_trip_count(init, step_name, step_imm, cmp_name, limit, latch_name, cmp_counter_left): + """Finite trip count for a scalar counted loop, or None when unbounded / unsupported.""" + counter = init & 0xffffffff + step = step_imm & 0xffffffff + signed = '_i32' in cmp_name # compare opcode alone + take_when_scc = latch_name == 's_cbranch_scc1' + + def as_signed(word): + return word - (1 << 32) if word >= (1 << 31) else word + + for trips in range(1, MESH_TRIP_MAX + 1): + if step_name.startswith('s_add'): + counter = (counter + step) & 0xffffffff + else: + counter = (counter - step) & 0xffffffff + left, right = (counter, limit) if cmp_counter_left else (limit, counter) + if signed: + left, right = as_signed(left), as_signed(right) + if cmp_name.endswith(('_eq_i32', '_eq_u32')): + scc = left == right + elif cmp_name.endswith(('_lg_i32', '_lg_u32')): + scc = left != right + elif cmp_name.endswith(('_gt_i32', '_gt_u32')): + scc = left > right + elif cmp_name.endswith(('_ge_i32', '_ge_u32')): + scc = left >= right + elif cmp_name.endswith(('_lt_i32', '_lt_u32')): + scc = left < right + elif cmp_name.endswith(('_le_i32', '_le_u32')): + scc = left <= right + else: + return None + if take_when_scc != scc: + return trips + return None + + +def mesh_constant_trip(ins, header, latch, offsets): + """Prove one constant-trip SCC back-edge: (trips,) or None. + + Shape (census "constant pattern", with an exact trip count): s_mov_b32 sN, C immediately before the + header; the body changes sN only by s_add/s_sub of a constant; the last body instruction is s_cmp of sN + against a constant; the latch is s_cbranch_scc0/scc1 back to the header. No other branch enters or leaves + the body, and the body does not write EXEC, touch a barrier, LDS, sendmsg, or export. + """ + if header <= 0 or latch <= header or latch >= len(ins): + return None + latch_name = ins[latch][2] + if latch_name not in ('s_cbranch_scc0', 's_cbranch_scc1'): + return None + init_name, init_ops, _ = parse(ins[header - 1][3]) + if init_name != 's_mov_b32' or len(init_ops) != 2 or not re.fullmatch(r's\d+', init_ops[0]): + return None + init_imm = mesh_inline_u32(init_ops[1]) + if init_imm is None: + return None + counter = init_ops[0] + counter_n = int(counter[1:]) + body = ins[header:latch] + if not body or not body[-1][2].startswith('s_cmp_'): + return None + cmp_name, cmp_ops, _ = parse(body[-1][3]) + if len(cmp_ops) != 2: + return None + if cmp_ops[0] == counter: + cmp_counter_left, limit_tok = True, cmp_ops[1] + elif cmp_ops[1] == counter: + cmp_counter_left, limit_tok = False, cmp_ops[0] + else: + return None + limit = mesh_inline_u32(limit_tok) + if limit is None: + return None + step = None + for off, size, name, asm in body[:-1]: + if name.startswith(('s_branch', 's_cbranch', 's_setpc', 's_call', 's_swappc')): + return None + if name.startswith(('ds_', 'exp')) or name in ('s_barrier', 's_sendmsg', 's_sendmsghalt'): + return None + _, ops, _ = parse(asm) + if writes_exec(name, ops) or name.startswith('v_cmpx') or name == 's_and_saveexec_b64': + return None + if name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm): + return None + writes = set() + for tok in destinations(name, ops): + r = reg_range(tok) + if r and r[0] == 's': + writes.update(range(r[1], r[2] + 1)) + if counter_n in writes: + if name not in MESH_TRIP_STEPS or len(ops) != 3 or ops[0] != counter: + return None + if ops[1] == counter and mesh_inline_u32(ops[2]) is not None: + imm = mesh_inline_u32(ops[2]) + elif (ops[2] == counter and mesh_inline_u32(ops[1]) is not None + and name.startswith('s_add')): + # Add is commutative; s_sub with the counter as SRC1 is a different recurrence. + imm = mesh_inline_u32(ops[1]) + else: + return None + if step is not None: + return None + step = (name, imm) + if step is None: + return None + # No other branch may enter the body past the header or leave it before the latch. + for i, (off, _, name, asm) in enumerate(ins): + if not name.startswith(('s_cbranch', 's_branch')): + continue + target = int(parse(asm)[1][0].split('_')[1], 16) + dest = offsets.get(target) + if dest is None: + continue + if i == latch: + continue + if header <= i < latch and not (header <= dest <= latch): + return None + if header < dest <= latch and not (header <= i <= latch): + return None + trips = mesh_trip_count(init_imm, step[0], step[1], cmp_name, limit, latch_name, cmp_counter_left) + return (trips,) if trips is not None else None + + +def mesh_skeleton(ins, vcc_branches, wave_limits, wave_loads): """Prove the one accepted group-memory shape of a slot 57 mesh program and replace it by per-thread instructions. Accepted shape, in program order (anything else is refused with its own message): - Exchange: exec = 1 (lane 0 of each wave), the mask saved in an SGPR pair; wave 0 (s3 bits 24..27 zero) stores entry v5 >> 7 at byte 8, waits and passes a barrier; every other wave passes a barrier and reads byte 8 to v5. - Code up to the next barrier. Its only read of v5 may be one v_readfirstlane_b32 under exec = -1. + After a full EXEC reset, an unsigned GT or LT EXEC compare with defined operands may guard a forward + execz branch to that barrier. The skipped instructions only affect active lanes or dead scalars, and + both exchange arms replace EXEC, so a per-lane skip has the same visible effects as a per-wave skip. - Counts: one barrier; the wave whose index (s_bfe_u32 of s3, 4 bits at 24) is zero stores SGPR P at byte 0 and SGPR V at byte 4 under the saved lane-0 mask, waits, passes a barrier and sends one allocation request with m0 = P << 12 | V; every other wave passes a barrier and reads both words back into the same P and V. @@ -1427,6 +1962,42 @@ def lands(key, index, what): offsets = {item[0]: i for i, item in enumerate(ins)} edges = {} + count_entry = count_entry_branch = None + # header index -> (latch index, trip count). Constant-trip loops are unrolled below. + constant_trips = {} + no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) + exchange_branch_refusal = 'slot 57 mesh: a branch enters or crosses a group-memory exchange' + + def lane_only(i): + _, _, name, asm = ins[i] + return (name.startswith(('v_', 'buffer_load')) and not name.startswith(EXECZ_REFUSED) + and not scalar_effects(name, asm)[2]) + + def dead_count_entry_scalar(i): + _, _, name, asm = ins[i] + if not re.fullmatch( + r's_(and|or|xor|andn2|orn2|bfe|max|min|mul|add|sub|lshl|lshr|ashr|mov|movk)_[biu]\d+', name): + return False + _, must, may = scalar_effects(name, asm) + written = must | may + regs = written - {'scc'} + if not written or any(not re.fullmatch(r's\d+', reg) for reg in regs): + return False + # Uses within the skipped block are fine. Every path out of it joins at the count exchange. + if any(regs & scalar_effects(*ins[j][2:])[0] for j in range(count_at, len(ins))): + return False + if 'scc' in written: + for j in range(count_at, len(ins)): + reads, must, may = scalar_effects(*ins[j][2:]) + if ins[j][2].startswith(('s_cbranch', 's_branch', 's_setpc', 's_call', 's_swappc', 's_endpgm')): + return False + if 'scc' in reads: + return False + if 'scc' in must: # a may-write alone (s_barrier) neither reads nor kills it + return True + return False + return True + for lo, hi in ((0, start), (a_end, count_at), (b_end, len(ins))): for i in range(lo, hi): off, _, name, asm = ins[i] @@ -1440,20 +2011,76 @@ def lands(key, index, what): dest = offsets.get(target) if dest is None: raise Unsupported('slot 57 mesh: a branch target is not an instruction boundary') - # The first instruction of an exchange is also the preceding region's join. - # Branches must reconverge before that instruction. if not lo <= dest < hi: - raise Unsupported('slot 57 mesh: a branch enters or crosses a group-memory exchange') + # Both count exchange arms replace the incoming EXEC before lane-dependent work. + if lo != a_end or dest != count_at or name != 's_cbranch_execz': + raise Unsupported(exchange_branch_refusal) + compare = i - 1 + while compare >= lo and ins[compare][2] in ('s_nop', 's_waitcnt'): + compare -= 1 + if (compare <= lo or ins[compare - 1][3] != 's_mov_b64 exec, -1' + or ins[compare][2] not in ('v_cmpx_gt_u32_e32', 'v_cmpx_lt_u32_e32') + or any(not (no_effect(k) or lane_only(k) or dead_count_entry_scalar(k)) + for k in range(i + 1, dest))): + raise Unsupported(exchange_branch_refusal) + _, sources, _ = parse(ins[compare][3]) + if len(sources) != 2 or any(not (re.fullmatch(r'[sv]\d+', tok) or tok in FLOATS + or pc_word(tok) is not None) for tok in sources): + raise Unsupported(exchange_branch_refusal) + count_entry, count_entry_branch = compare, i if target <= off: - raise Unsupported('slot 57 mesh: a loop outside the group-memory exchanges is not covered') + proven = mesh_constant_trip(ins, dest, i, offsets) + if proven is None or dest in constant_trips: + raise Unsupported(MESH_LOOP_REFUSAL) + constant_trips[dest] = (i, proven[0]) + continue if name not in ('s_branch', 's_cbranch_scc0', 's_cbranch_scc1', 's_cbranch_execz') + MESH_VCC_BRANCHES: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) edges[i] = dest targets = set(edges.values()) - no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) + if targets & set(constant_trips): + raise Unsupported(MESH_LOOP_REFUSAL) + if count_entry is not None and targets.intersection(range(count_entry, count_at)): + raise Unsupported(exchange_branch_refusal) first_post_count_branch = next((i for i in edges if i >= b_end), None) shift_branch = None + load_compares = {} # compare index -> thread VGPR of each accepted pre-exchange wave block + execz_effects = 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes' + + def live_at_join(reg, join): + pending, seen = [join], set() + while pending: + i = pending.pop() + if i >= len(ins) or i in seen: + continue + seen.add(i) + if i == count_at: + if reg in (env['prims'], env['verts']): + return True + if reg != env['b_tmp']: + pending.append(b_end) + continue + name, asm = ins[i][2:] + reads, writes, _ = scalar_effects(name, asm) + if reg in reads: + return True + if reg not in writes: + if i in edges: + pending.append(edges[i]) + if name not in ('s_branch', 's_endpgm'): + pending.append(i + 1) + return False + + def dead_block_scalar(i, join): + """Scalar ALU in a skipped block whose results no path reads past the join. Lanes that skip the block per lane + never read them, and lanes that run it compute the wave-uniform values the guest computes once per wave.""" + name, asm = ins[i][2:] + if name in SCALAR_LOADS or not name.startswith('s_') or not mesh_wave_block_scalar(name, asm): + return False + _, must, may = scalar_effects(name, asm) + return not any(live_at_join(reg, join) for reg in must | may) + for source, target in edges.items(): if ins[source][2] == 's_cbranch_execz': # A single scalar shift followed by a full EXEC restore has a separate wave-level proof below. @@ -1461,18 +2088,57 @@ def lands(key, index, what): and ins[source + 1][2] == 's_lshl_b32' and ins[target][3] == 's_mov_b64 exec, -1'): shift_branch = source continue + if a_end <= source < target < count_at: + loads = [i for i in range(source + 1, target) if ins[i][2] in SCALAR_LOADS] + if loads: + compare = source - 1 + while compare > a_end and not writes_exec(ins[compare][2], parse(ins[compare][3])[1]): + compare -= 1 + match = re.fullmatch(r'v_cmpx_gt_u32_e32 (s\d+), v(\d+)', ins[compare][3]) + scalar = [i for i in range(source + 1, target) if not (no_effect(i) or lane_only(i))] + # The guest runs every scalar instruction of the block once per wave that has an active lane. + # The lowering runs them for all lanes of such a wave, so they may only read and write SGPRs, + # SCC and a VCC that is dead at the join: no EXEC, M0, branch, barrier, message, store or atomic. + # A per-lane v_cmp into VCC is allowed under the same dead-at-join rule. + written, masks = set(), set() + for i in scalar: + reads, must, may = scalar_effects(*ins[i][2:]) + written |= {reg for reg in must | may if re.fullmatch(r's\d+', reg)} + masks |= ((must | may) & VCC_KEYS) | (must & {'scc'}) # every s_ op may-writes SCC + live = sorted((reg for reg in written if live_at_join(reg, target)), key=lambda r: int(r[1:])) + # EXEC is full at the compare when a reset precedes it with no EXEC or VCC use and no branch + # target in between. + reset = compare - 1 + while (reset > a_end and ins[reset][3] != 's_mov_b64 exec, -1' + and not writes_exec(ins[reset][2], parse(ins[reset][3])[1]) + and not re.search(r'\b(exec|vcc)', ins[reset][3])): + reset -= 1 + # A branch may land between the reset and the compare only from inside that range, none may + # land between the compare and the execz branch, and the block itself is straight-line code. + entries = [s for s, d in edges.items() if (reset < d <= compare and not reset <= s < d) + or compare < d <= source] + if (compare <= a_end or ins[reset][3] != 's_mov_b64 exec, -1' or not match or entries + or targets.intersection(range(source + 1, target)) + or any(s in edges for s in range(source + 1, target)) + or any(live_at_join(reg, target) for reg in masks) + or any(not mesh_wave_block_scalar(*ins[i][2:]) for i in scalar)): + raise Unsupported(exchange_branch_refusal if target == count_at else execz_effects) + load_compares[compare] = int(match[2]) + wave_loads[ins[source][0]] = (ins[compare][0], match[1], + tuple(ins[i][0] for i in loads), tuple(live)) + continue # The model skips per lane, while the guest skips per wave. The difference is invisible when # lanes with clear EXEC can only bypass predicated writes before the paths meet. A skipped # s_branch may land at the execz target or past it over instructions without effect (the # `s_branch .else` over `.empty: s_nop` of an if/else), so both paths meet with the same state. for i in range(source + 1, target): - _, _, name, asm = ins[i] + name = ins[i][2] if not (no_effect(i) or name == 'exp' or (name == 's_branch' and edges[i] >= target and all(no_effect(k) for k in range(target, edges[i]))) - or (name.startswith(('v_', 'buffer_load')) and not name.startswith(EXECZ_REFUSED) - and not scalar_effects(name, asm)[2])): - raise Unsupported('slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes') + or lane_only(i) or (source == count_entry_branch and dead_count_entry_scalar(i)) + or dead_block_scalar(i, target)): + raise Unsupported(execz_effects) elif any(ins[i][2] == 'exp' for i in range(source + 1, target)): raise Unsupported('slot 57 mesh: a branch bypasses an export') @@ -1494,8 +2160,22 @@ def lands(key, index, what): exports = [] incoming = {} falls = True - for index in (list(range(first, start)) + [start] + list(range(a_end, count_at)) + [None] - + list(range(b_end, len(ins)))): + def region_walk(lo, hi): + """Instruction indices in [lo, hi), with each proven constant-trip body repeated and its latch dropped.""" + order, i = [], lo + while i < hi: + if i in constant_trips: + latch, trips = constant_trips[i] + for _ in range(trips): + order.extend(range(i, latch)) + i = latch + 1 + continue + order.append(i) + i += 1 + return order + + for index in (region_walk(first, start) + [start] + region_walk(a_end, count_at + 1) + + region_walk(b_end, len(ins))): if index in targets: paths = incoming[index] if falls: @@ -1526,7 +2206,7 @@ def lands(key, index, what): if base == a_bits or base in lane: base = None continue - if index is None: + if index == count_at: if not wave_known: raise Unsupported('slot 57 mesh count exchange: the compared register is not the wave index') out.append(span(count_at, b_end - 2) + ( @@ -1568,7 +2248,11 @@ def lands(key, index, what): continue if name.startswith('ds_') or name in ('s_barrier', 's_sendmsg', 's_sendmsghalt'): raise Unsupported('slot 57 mesh: %s outside the group-memory exchanges' % name) - if name.startswith(('v_readlane', 'v_writelane')): + # Constant-lane v_writelane_b32 / v_readlane_b32 (#2413 T7, #2127): Stage lowers the idiom and + # refuses ordinary VGPR use, unwritten slots and non-constant lanes. The spill VGPR is not a + # per-lane value in this model, so it does not update the stale/pending sets below. + lane_spill = base_name in ('v_writelane_b32', 'v_readlane_b32') + if name.startswith(('v_readlane', 'v_writelane')) and not lane_spill: raise Unsupported('slot 57 mesh: lane spills are not covered') keep = ins[index] if base_name == 'v_readfirstlane_b32': @@ -1585,7 +2269,8 @@ def lands(key, index, what): writes_s.update(range(r[1], r[2] + 1)) if 3 in writes_s or writes_s & lane: raise Unsupported('slot 57 mesh: the wave word s3 or the saved lane-0 mask is written') - if writes_s and name.startswith('v_') and keep[2] != 'x2w_mesh_group': + if (writes_s and name.startswith('v_') and keep[2] != 'x2w_mesh_group' + and base_name != 'v_readlane_b32'): raise Unsupported('slot 57 mesh: %s into an SGPR is not covered' % base_name) # Only the wave index of s3 is modelled. if not re.fullmatch(r's_bfe_u32 s\d+, s3, 0x40018', asm) and any( @@ -1619,6 +2304,14 @@ def lands(key, index, what): stale |= pending pending.clear() mask, scc_stale = ('else', mask), True + elif index == count_entry: + if mask is not None or mesh_vregs(ops) & stale: + raise Unsupported(exchange_branch_refusal) + mask = 'count_entry' + elif index in load_compares: + if mask is not None or thread != load_compares[index] or thread in stale: + raise Unsupported(execz_effects) + mask = 'wave_load' elif base_name.startswith('v_cmpx'): count = {env['verts']: 'verts', env['prims']: 'prims'}.get(ops[0] if ops else None) if (base_name != 'v_cmpx_gt_i32' or not after or mask is not None or count is None @@ -1626,8 +2319,9 @@ def lands(key, index, what): raise Unsupported('slot 57 mesh: an EXEC compare other than output count > thread index under ' 'exec = -1 is not covered') mask = count - elif writes_exec(name, ops) or re.search(r'\b(?:exec(?:_lo|_hi)?|src_execz|src_vccz)\b', asm) or ( - name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm)): + elif (not lane_spill and ( + writes_exec(name, ops) or re.search(r'\b(?:exec(?:_lo|_hi)?|src_execz|src_vccz)\b', asm) or ( + name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm)))): raise Unsupported('slot 57 mesh: %s on a wave mask is not covered' % base_name) # The thread index: v_mbcnt_lo(-1, wave << 6) then v_mbcnt_hi(-1, that) under exec = -1. if asm == 's_bfe_u32 %s, s3, 0x40018' % env['wave']: @@ -1648,6 +2342,8 @@ def lands(key, index, what): thread_high = index + 1 elif thread in writes_v and index != thread_high: raise Unsupported('slot 57 mesh: the thread index register is rewritten') + if lane_spill: + reads_v, writes_v = set(), set() if keep[2] != 'x2w_mesh_group' and reads_v & stale: raise Unsupported('slot 57 mesh: v%d is read where it is not defined for every lane (an entry value, or ' 'left different per wave by an exchange)' % min(reads_v & stale)) @@ -1671,6 +2367,128 @@ def lands(key, index, what): return out +RESHEAP_RANGE_SPACE = 2 +RESHEAP_RANGE_MAX = 1024 + + +def _lit_u32(tok): + if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', tok) and tok not in FLOATS: + return int(tok, 0) & 0xffffffff + return None + + +def _join_vbound(a, b): + if a is None or b is None or a[0] != b[0]: + return None + return (a[0], max(a[1], b[1])) + + +def vgpr_heap_bounds(ins, succ): + """Forward CFG dataflow: map each instruction index to ({vreg: ('idx' | 'off5', max_idx)}, exec_is_entry). + + A bound enters only while every active lane that can reach a waterfall head executes the bounding write + (proven before any EXEC change, or joined with the prior bound on every path after EXEC changes).""" + if not ins: + return [] + before = [None] * len(ins) + before[0] = ({}, True) + work = [0] + for i in work: + regs, exec_entry = before[i] + _off, _n, name, asm = ins[i] + base, ops, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', base) + nxt_regs = dict(regs) + nxt_exec = exec_entry and not writes_exec(name, ops) + dst_v = set() + for tok in destinations(name, ops): + r = reg_range(tok) + if r and r[0] == 'v': + dst_v.update(range(r[1], r[2] + 1)) + if 'movrel' in name: + nxt_regs.clear() + elif dst_v: + new_val = None + r0 = reg_range(ops[0]) if ops else None + single = r0 and r0[0] == 'v' and r0[1] == r0[2] and r0[1] <= 255 and dst_v == {r0[1]} + if single and not mods: + def src_idx_max(tok): + k = _lit_u32(tok) + if k is not None: + return k + rs = reg_range(tok) + if rs and rs[0] == 'v' and rs[1] == rs[2] and regs.get(rs[1], ('',))[0] == 'idx': + return regs[rs[1]][1] + return None + + if base in ('v_and_b32', 'v_min_u32') and len(ops) == 3: + bounds = [b for b in (src_idx_max(ops[1]), src_idx_max(ops[2])) if b is not None] + if bounds and min(bounds) < RESHEAP_RANGE_MAX: + new_val = ('idx', min(bounds)) + elif base == 'v_bfe_u32' and len(ops) == 4: + width = _lit_u32(ops[3]) + if width is not None and width < 16 and ((1 << width) - 1) < RESHEAP_RANGE_MAX: + new_val = ('idx', (1 << width) - 1) + elif base == 'v_lshrrev_b32' and len(ops) == 3: + shift = _lit_u32(ops[1]) + if shift is not None: + shift &= 31 + rs = reg_range(ops[2]) + if rs and rs[0] == 'v' and rs[1] == rs[2] and regs.get(rs[1], ('',))[0] == 'idx': + new_val = ('idx', regs[rs[1]][1] >> shift) + elif (0xffffffff >> shift) < RESHEAP_RANGE_MAX: + new_val = ('idx', 0xffffffff >> shift) + elif base == 'v_lshlrev_b32' and len(ops) == 3: + shift = _lit_u32(ops[1]) + rs = reg_range(ops[2]) + if (shift is not None and (shift & 31) == 5 and rs and rs[0] == 'v' and rs[1] == rs[2] + and regs.get(rs[1], ('',))[0] == 'idx'): + new_val = ('off5', regs[rs[1]][1]) + elif base == 'v_mov_b32' and len(ops) == 2: + k = _lit_u32(ops[1]) + rs = reg_range(ops[1]) + if k is not None and k < RESHEAP_RANGE_MAX: + new_val = ('idx', k) + elif rs and rs[0] == 'v' and rs[1] == rs[2] and rs[1] in regs: + new_val = regs[rs[1]] + for v in dst_v: + merged = new_val if (single and exec_entry) else (_join_vbound(regs.get(v), new_val) if single else None) + if merged is not None: + nxt_regs[v] = merged + else: + nxt_regs.pop(v, None) + for s in succ[i]: + if before[s] is None: + before[s] = (nxt_regs, nxt_exec) + work.append(s) + else: + old_regs, old_exec = before[s] + m_exec = old_exec and nxt_exec + m_regs = {k: j for k, v in old_regs.items() if k in nxt_regs + for j in (_join_vbound(v, nxt_regs[k]),) if j is not None} + if (m_regs, m_exec) != before[s]: + before[s] = (m_regs, m_exec) + work.append(s) + return before + + +def adjacent_address_carries(ins, targets): + """Map each candidate low add to its high-word carry read in the same basic block.""" + pairs = {} + for index, (high_pc, _, name, asm) in enumerate(ins): + if name != 's_add_u32' or 'src_scc' not in asm or not index or high_pc in targets: + continue + low_pc, _, low_name, low_asm = ins[index - 1] + if low_name != 's_add_u32': + continue + low = parse(low_asm)[1] + if len(low) == 3 and re.fullmatch(r's\d+', low[0]): + reg = int(low[0][1:]) + if reg < 105 and parse(asm)[1] == ['s%d' % (reg + 1), '0', 'src_scc']: + pairs[low_pc] = high_pc + return pairs + + class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" @@ -1678,9 +2496,13 @@ class Stage: # per-instance sets, so nothing is shared across Stage instances. needs_sm6 = False # the lowering uses a shader model 6.0 intrinsic, so the stage cannot compile as 5.1 exec_known = False # unit probes without __init__ customize this explicitly when needed + has_image_writes = True # proved False in translate() only when no image write exists in the dispatch + loads_after_exec_write = () # compute loads reached from an EXEC writer through the block graph low16_only_v = () # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load pinned_low16_v = () # low16_only_v live across basic-block boundaries whole_read_v = () # VGPRs read outside a proven low-16-bit consumer + align4_v = () # VGPRs proven to hold a multiple of 4 in every lane + align4_s = () # SGPRs proven to hold a multiple of 4 used_atomic = () # atomic result types ('uint', 'int') needing declarations in main() # pixel: VGPR -> (attr, channel, high) of the v_interp_p1ll_f16 that wrote it. Created on first use, because # unit probes build a Stage without __init__. @@ -1692,6 +2514,8 @@ class Stage: bad_sgprs = None _uniform_written = None raw_code = b'' + address_carry_pairs = () + address_carry_reader = None def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.pipe, self.kind = pipe, kind @@ -1704,7 +2528,13 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): if kind == 'ms': self.mesh_vcc_branches = {} self.mesh_wave_limits = {} - self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches, self.mesh_wave_limits) + self.mesh_wave_loads = {} + # Keep the pre-skeleton program so spill-only proofs still see the exchange VGPRs + # (mesh_skeleton rewrites those ops to x2w_mesh_* / s_nop). + self.mesh_source_ins = list(self.ins) + self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches, self.mesh_wave_limits, self.mesh_wave_loads) + if kind in ('vs', 'ps'): + self.ins = wave32_vcc_hi(self.ins) # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept # there is known only afterwards: translate again with that register read at run time or refused there. A # register only moves from kept to 'run' to 'refuse', so this ends. @@ -1712,6 +2542,7 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): first_refusal = len(refusals) if refusals is not None else 0 while True: self.lines = [] # body statements (per block) + self.vconst = {} # VGPR -> literal 32-bit value while the program is straight-line self.sym = {} # scalar register -> symbolic value self.used_s, self.used_v = set(), set() self.used_atomic = set() @@ -1786,9 +2617,10 @@ def setup_entry(self): def setup_compute_entry(self, root_end): """Entry registers of a compute wave as compute_store_aot.entry_registers (#1608) gives them: the user SGPRs, - then one SGPR per enabled group-ID axis (SV_GroupID), and v0..v2 holding SV_GroupThreadID. Where the root - parameters sit inside the user SGPRs (from s4) is this translator's inference. User SGPRs the root does not - place (s0-s3 and any past the root's span) have no known value, so any numeric read of them is refused.""" + then one SGPR per enabled group-ID axis (SV_GroupID), optional TG_SIZE when TG_SIZE_EN is set (only accepted + for at most 32 threads per group, #2274), and v0..v2 holding SV_GroupThreadID. Where the root parameters sit + inside the user SGPRs (from s4) is this translator's inference. User SGPRs the root does not place (s0-s3 and + any past the root's span) have no known value, so any numeric read of them is refused.""" user, groups, threads = self.pipe.entry if root_end > user: raise Unsupported('root signature needs s4-s%d, COMPUTE_PGM_RSRC2 gives %d user SGPRs' % (root_end - 1, user)) @@ -1800,6 +2632,9 @@ def setup_compute_entry(self, root_end): self.used_s.add(n) self.entry_uniform_s.add(n) self.entry.append('s%d = gid.%s;' % (n, 'xyz'[axis])) + tg_size = getattr(self.pipe, 'tg_size_sgpr', None) + if tg_size is not None: + self.sym[tg_size] = ('tg_size',) for i in range(threads): self.used_v.add(i) self.entry.append('v%d = tid.%s;' % (i, 'xyz'[i])) @@ -1816,6 +2651,8 @@ def S(self, n): if s[0] in ('execcopy', 'fixed_buffer_word'): self.used_s.add(n) return 's%d' % n + if s[0] == 'tg_size': + raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % n) raise Unsupported('numeric use of s%d holding %s' % (n, s[0])) self.used_s.add(n) return 's%d' % n @@ -1828,6 +2665,12 @@ def note_whole_read(self, reg): def u(self, tok, *, low16_only=False): """uint expression for a 32-bit operand.""" + if tok == 'src_scc': + # Source code 253 reads SCC as 0 or 1 (fits in 16 bits, so low16_only=True needs no mask). + # Refuse unless a modeled writer set SCC on the reaching path in this block. + if not getattr(self, 'scc_verified', False): + raise Unsupported('src_scc with unverified SCC') + return '(scc ? 1u : 0u)' if tok in ('vcc_lo', 'vcc'): self.read_vcc() return 'vcc' @@ -1838,6 +2681,8 @@ def u(self, tok, *, low16_only=False): if m: raise Unsupported('numeric use of m0 holding %s' % m[0]) return 'm0' + if tok == 'null': + return '0x00000000u' r = reg_range(tok) if r: if r[0] == 'v': @@ -1871,13 +2716,37 @@ def split_neg(tok): return True, tok[1:] return False, tok + def reject_lane_mask_data(self, op, tok): + """The lane bit cannot represent a mask's word when it is read as data.""" + source = tok + while True: + neg, operand = self.split_neg(source) + if neg: + source = operand + elif source.startswith('|') and source.endswith('|') and len(source) >= 2: + source = source[1:-1] + elif source.startswith(('abs(', 'sext(')) and source.endswith(')'): + source = source[source.index('(') + 1:-1] + else: + break + if self.is_lane_mask(source): + raise Unsupported('%s data operand %s is a lane mask' % (op, tok)) + def u_src(self, tok): - """uint expression for an integer-context source that the disassembler may print negated.""" - # In an integer instruction the `-` modifier is the source's sign bit flipped: the same bit - # pattern a float negation produces. Only handlers that model it ask for this; other integer - # sources keep using u(), so an unexpected negation stays a refusal rather than a silent flip. + """uint expression for an integer-context source that the disassembler may print with abs/neg.""" + # In RDNA2 VOP3, `abs` clears bit 31 first and `-` / `neg(...)` flips bit 31 second (so `-|x|` + # forces bit 31 to 1, while `-x` flips bit 31). Only handlers that model them ask for this; + # other integer sources keep using u(), so an unexpected modifier stays refused. neg, tok = self.split_neg(tok) - return '(%s ^ 0x80000000u)' % self.u(tok) if neg else self.u(tok) + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + expr = self.u(tok) + if absolute: + expr = '(%s & 0x7fffffffu)' % expr + if neg: + expr = '(%s ^ 0x80000000u)' % expr + return expr def f(self, tok): """float expression, with the inline neg/abs operand modifiers.""" @@ -1893,13 +2762,15 @@ def f(self, tok): text = 'F(%s)' % self.u(tok) if absolute: text = 'abs(%s)' % text - return '(-%s)' % text if neg else text + return ('(-(%s))' % text) if (neg and text.startswith('-')) else ('(-%s)' % text if neg else text) def is_const(self, n): s = self.sym.get(n) return s[1] if s and s[0] == 'const' else None def const_u32(self, tok): + if tok == 'null': + return 0 r = reg_range(tok) if r: if r[0] == 's' and r[1] == r[2]: @@ -1913,12 +2784,71 @@ def const_u32(self, tok): except ValueError: return None + def operand_align4(self, tok): + """True when 32-bit operand tok is proven to be a multiple of 4 in every lane.""" + if self.is_lane_mask(tok): + return False + c = self.const_u32(tok) + if c is not None: + return (c & 3) == 0 + r = reg_range(tok) + if not r or r[1] != r[2]: + return False + if r[0] == 'v': + return r[1] in self.align4_v and r[1] not in self.low16_only_v + if r[0] == 's': + return r[1] in self.align4_s and self.sym.get(r[1]) is None + return False + + def valu_align4(self, base, srcs): + """True when a modifier-free VEC_U operation produces a multiple of 4 from srcs.""" + if base in ('v_add_nc_u32', 'v_sub_nc_u32', 'v_subrev_nc_u32', 'v_or_b32', 'v_xor_b32', + 'v_min_u32', 'v_max_u32', 'v_min_i32', 'v_max_i32', + 'v_add3_u32', 'v_or3_b32', 'v_xor3_b32', 'v_xad_u32', + 'v_min3_u32', 'v_max3_u32', 'v_med3_u32', 'v_min3_i32', 'v_max3_i32', 'v_med3_i32'): + return all(self.operand_align4(s) for s in srcs) + if base in ('v_and_b32', 'v_mul_lo_u32', 'v_mul_u32_u24', 'v_mul_i32_i24'): + return any(self.operand_align4(s) for s in srcs) + if base == 'v_lshlrev_b32': + return self.operand_align4(srcs[1]) or ((self.const_u32(srcs[0]) or 0) & 31) >= 2 + if base in ('v_lshl_add_u32', 'v_lshl_or_b32'): + return (self.operand_align4(srcs[0]) or ((self.const_u32(srcs[1]) or 0) & 31) >= 2) and self.operand_align4(srcs[2]) + if base == 'v_add_lshl_u32': + return ((self.const_u32(srcs[2]) or 0) & 31) >= 2 or (self.operand_align4(srcs[0]) and self.operand_align4(srcs[1])) + if base in ('v_and_or_b32', 'v_mad_u32_u24', 'v_mad_i32_i24', 'v_mad_u32_u16', 'v_mad_i32_i16'): + return (self.operand_align4(srcs[0]) or self.operand_align4(srcs[1])) and self.operand_align4(srcs[2]) + return False + + def salu_align4(self, base, srcs): + """True when a 32-bit non-mask Stage.scalar operation produces a multiple of 4 from srcs.""" + if base == 's_mov_b32': + return self.operand_align4(srcs[0]) + if base == 's_lshl_b32': + return self.operand_align4(srcs[0]) or ((self.const_u32(srcs[1]) or 0) & 31) >= 2 + if base in ('s_and_b32', 's_mul_i32'): + return any(self.operand_align4(s) for s in srcs) + if base == 's_andn2_b32': + return self.operand_align4(srcs[0]) or ((self.const_u32(srcs[1]) or 0) & 3) == 3 + if base in ('s_add_u32', 's_sub_u32', 's_add_i32', 's_sub_i32', 's_or_b32', 's_xor_b32', + 's_cselect_b32', 's_min_u32', 's_max_u32', 's_min_i32', 's_max_i32', 's_lshl1_add_u32'): + return all(self.operand_align4(s) for s in srcs) + if base in ('s_lshl2_add_u32', 's_lshl3_add_u32', 's_lshl4_add_u32'): + return self.operand_align4(srcs[1]) + return False + def read_vcc(self): if getattr(self, 'has_branches', False): self.vcc_events.setdefault(self.pc, []).append(('read_vcc', None)) elif getattr(self, 'vcc_lost', False): raise Unsupported('vcc read after a descriptor load into s106/s107') + def mark_vcc_descriptor(self): + self.vcc_lost = True + self.vcc_descriptor_overwritten = False + if getattr(self, 'has_branches', False): + value = tuple(self.sym[i] for i in (106, 107)) + self.vcc_events.setdefault(self.pc, []).append(('load_descriptor', value)) + def emit(self, text): if 'vcc' in text: assignment = re.match(r'vcc = (.*);$', text) @@ -1937,6 +2867,34 @@ def emit(self, text): self.sym.pop(107, None) self.lines.append(text) + def divergent_exit_loop(self, at): + """True when the offset sits in a loop (a backward branch of any kind, also an unconditional one) that holds a + wave-divergent branch: lanes of one quad can leave through the forward exit at different passes, so the next pass + runs the sample on uneven quads.""" + for _o, _n, name, asm in self.ins: + if name == 's_branch' or name.startswith('s_cbranch_'): + target = int(parse(asm)[1][0].split('_')[1], 16) + if target <= _o and target <= at <= _o and any(target <= d <= _o for d in self.divergent_branches): + return True + return False + + def resolve_plain_samples(self): + """Writes each plain image_sample past a join into the blocks: the implicit-LOD Sample unless a divergent back + edge spans it (the same proof as image_sample_b / image_get_lod), else the level-0 call as before. It never + refuses: a plain sample that translated before still does.""" + if not self.plain_samples: + return + choice = {} + for at, (level0, implicit) in self.plain_samples.items(): + spanned = any(target <= at <= branch for target, branch in self.divergent_back_edges) or self.divergent_exit_loop(at) + choice['X2W_PLAIN_SAMPLE<%x>' % at] = level0 if spanned else implicit + + def text(line): + for token, call in choice.items(): + line = line.replace(token, call) + return line + self.blocks = [(start, [text(l) for l in lines], term) for start, lines, term in self.blocks] + def check_vcc_paths(self): """An overlapping descriptor must reach its use on every path, and VCC must be numeric at a mask read.""" if not self.has_branches or not any(event == 'load_descriptor' for events in self.vcc_events.values() @@ -1978,12 +2936,19 @@ def clear_low16(self, n): if isinstance(self.low16_only_v, set) and self.exec_known and n not in self.pinned_low16_v: self.low16_only_v.discard(n) - def set_v(self, n, expr, *, low16_only=False): + def record_v_write(self, n, *, low16_only=False, align4=False): if getattr(self, 'interp_p1', None): self.interp_p1.pop(n, None) if hasattr(self, 'uniform_v'): self.uniform_v.discard(n) - self.last_v = (n, expr) + if isinstance(self.align4_v, set): + if align4 and not low16_only and (self.exec_known or n in self.align4_v): + self.align4_v.add(n) + else: + self.align4_v.discard(n) + vconst = getattr(self, 'vconst', None) + if isinstance(vconst, dict): + vconst.pop(n, None) if low16_only: if not isinstance(self.low16_only_v, set): self.low16_only_v = set() @@ -1991,7 +2956,21 @@ def set_v(self, n, expr, *, low16_only=False): else: self.clear_low16(n) self.used_v.add(n) + + def set_v(self, n, expr, *, low16_only=False, align4=False): + self.record_v_write(n, low16_only=low16_only, align4=align4) + self.last_v = (n, expr) + vconst = getattr(self, 'vconst', None) + if isinstance(vconst, dict): + literal = re.fullmatch(r'0x([0-9a-fA-F]{8})u', expr) + if literal: + vconst[n] = int(literal.group(1), 16) self.emit('v%d = %s;' % (n, expr) if self.exec_known else 'if (exec & 1) v%d = %s;' % (n, expr)) + temps = getattr(self, 'uniform_temps', None) + if temps is not None: # a uniform load past the entry block (one()): every lane keeps the words + temps[n] = 'ul%x_%d' % (self.pc, n) + self.uniform_load_temps.add(temps[n]) + self.emit('%s = %s;' % (temps[n], expr)) def f_mods(self, expr, mods=()): # The hardware applies the output modifier before the clamp, but the disassembler prints `clamp` @@ -2036,11 +3015,31 @@ def set_scc(self, expr, proof=None): """Emit an SCC assignment and track its uniformity from `proof` (an expression over the sources) when the emitted text names a register, such as m0, that the proof cannot judge.""" self.scc_effect = 'emitted' + self.scc_verified = True if self.tracks_uniformity(): self.scc_uniform = self.scalar_expr_uniform(expr if proof is None else proof) self.emit('scc = %s;' % expr) - def set_s(self, n, expr, sym=None, scc=None, uniform=None): + def record_scalar_uniformity(self, n, uniform): + if uniform: + self.varying_s.discard(n) + if self.defined_uniform_s is not None: + self.defined_uniform_s.add(n) + if self._uniform_written is not None: + self._uniform_written.add(n) + else: + self.varying_s.add(n) + if self.defined_uniform_s is not None: + self.defined_uniform_s.discard(n) + if self._uniform_written is not None: + self._uniform_written.discard(n) + if self.bad_sgprs is not None: + self.bad_sgprs.add(n) + # Only a proved assignment can add an SGPR to since_join. Unmodelled writes drop any stale mark. + if getattr(self, 'since_join', None) is not None: + (self.since_join.add if uniform else self.since_join.discard)(n) + + def set_s(self, n, expr, sym=None, scc=None, uniform=None, align4=False): """Assign scalar register n at run time and/or symbolically. Any write ends n's life as a lane mask; a caller that writes a mask marks n again after this call. @@ -2048,26 +3047,17 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None): if self.tracks_uniformity() and (sym is None or sym[0] == 'const'): if uniform is None: uniform = self.scalar_expr_uniform(expr) - if uniform: - self.varying_s.discard(n) - if self.defined_uniform_s is not None: - self.defined_uniform_s.add(n) - if self._uniform_written is not None: - self._uniform_written.add(n) - else: - self.varying_s.add(n) - if self.defined_uniform_s is not None: - self.defined_uniform_s.discard(n) - if self._uniform_written is not None: - self._uniform_written.discard(n) - if self.bad_sgprs is not None: - self.bad_sgprs.add(n) - # Invariant: since_join gains an SGPR only here, when set_s proves it uniform; forget_writes drops any SGPR - # an instruction writes first, so a write through an unmodelled path never keeps a stale mark. - if getattr(self, 'since_join', None) is not None: - (self.since_join.add if uniform else self.since_join.discard)(n) + self.record_scalar_uniformity(n, uniform) getattr(self, 'masks', set()).discard(n) # unit probes build a Stage without __init__ + getattr(self, 'mask_high', set()).discard(n) getattr(self, 'float_const_s', {}).pop(n, None) + if isinstance(self.align4_s, set): + if sym is not None and sym[0] == 'const': + (self.align4_s.add if (sym[1] & 3) == 0 else self.align4_s.discard)(n) + elif sym is None and align4: + self.align4_s.add(n) + else: + self.align4_s.discard(n) if sym is not None: self.sym[n] = sym if sym[0] != 'const': @@ -2082,6 +3072,14 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None): def descriptor(self, tok): """Resource key for a descriptor operand like s[8:11]: (source, byte offset or None).""" r = reg_range(tok) + held = self.select_word(tok) + if held is not None: + # Only the first word names the resource below; a select of descriptor data in any word (such as a + # size word zeroed on one arm) would be dropped, so the access refuses. + raise Unsupported('descriptor operand %s: s%d holds a select of descriptor data' % (tok, held)) + held = self.joined_word(tok) + if held is not None: + raise Unsupported('descriptor operand %s: s%d holds a word joined at a branch target' % (tok, held)) s = self.sym.get(r[1]) if r else None if r and r[0] == 's' and r[1] <= 107 and r[2] >= 106: if getattr(self, 'has_branches', False): @@ -2089,14 +3087,37 @@ def descriptor(self, tok): self.vcc_events.setdefault(self.pc, []).append(('read_descriptor', expected)) elif getattr(self, 'vcc_descriptor_overwritten', False): raise Unsupported('descriptor operand %s overlaps a redefined vcc' % tok) + if r == ('s', 104, 107) and s and s[0] == 'desc' and ( + s[3] % 4 or + any(self.sym.get(104 + i) != desc_word(s, s[3] + i) for i in range(1, 4))): + raise Unsupported('descriptor operand %s needs four consecutive words of the same descriptor' % tok) if s and s[0] == 'desc': # A descriptor can start inside a wider load (s_load_dwordx16 fetches two image # descriptors): its offset is the load's offset plus the first register's dword index. return s[1], (None if s[2] is None else s[2] + 4 * s[3]) if s and s[0] == 'ptr': + if len(s) > 2 and s[2]: + raise Unsupported('descriptor operand %s is a pointer with offset %s' % (tok, hex(s[2]) if isinstance(s[2], int) else s[2])) return s[1], None raise Unsupported('descriptor operand %s holds %s' % (tok, s)) + def select_word(self, tok): + """The first SGPR of operand tok that holds a select of descriptor data (descriptor_select), or None.""" + r = reg_range(tok) + if not r or r[0] != 's': + return None + return next((n for n in range(r[1], min(r[2], 105) + 1) if descriptor_select(self.sym.get(n))), None) + + def joined_word(self, tok): + """In compute, the first SGPR after the first word of operand tok that holds a value joined at a branch + target, or None. The paths bring different words there, a select of descriptor data possibly among them, + and the access names its resource by the first word only. A loop head joins the same way.""" + r = reg_range(tok) + if getattr(self, 'kind', None) != 'cs' or not r or r[0] != 's': + return None + return next((n for n in range(r[1] + 1, min(r[2], 105) + 1) + if (self.sym.get(n) or ('',))[0] == 'joined at a branch target'), None) + def heap_sampler(self, tok): """'qh[...]' when the four sampler words of tok came from one run-time sampler heap load.""" r = reg_range(tok) @@ -2119,6 +3140,59 @@ def const_words(self, tok): for n in range(r[1], r[2] + 1)] return None if any(w is None for w in words) else words + def sampler_join_shape(self, branches): + # A single forward SCC diamond, with all four final writes in each arm literal. + if (getattr(self, 'kind', None) != 'ps' or len(branches) != 2 or + not any(name in ('image_sample_l', 'image_sample_lz') for _, _, name, _ in self.ins)): + return None + (cond, taken), (skip, join) = sorted(branches) + if not cond < skip < taken < join: + return None + row = {off: (n, name) for off, n, name, _ in self.ins} + if (row[cond][1] not in ('s_cbranch_scc0', 's_cbranch_scc1') or + row[skip][1] != 's_branch' or skip + row[skip][0] != taken): + return None + literals = [set(), set()] + bases = set() + for off, _, name, asm in self.ins: + _, ops, mods = parse(asm) + if off < join and (writes_exec(name, ops) or (cond < off and name == 's_endpgm')): + return None + arm = 0 if cond < off < skip else 1 if taken <= off < join else None + if arm is not None: + dests = scalar_destinations(name, asm) + if 'any' in dests: + return None + literals[arm].difference_update(dests) + if (name == 's_mov_b32' and len(ops) == 2 and not mods and + re.fullmatch(r'(?:0x[0-9a-fA-F]+|\d+)', ops[1])): + literals[arm].update(dests) + if (off >= join and name in ('image_sample_l', 'image_sample_lz') and len(ops) == 4 + and 'dim:SQ_RSRC_IMG_2D' in mods): + r = reg_range(ops[3]) + if r and r[0] == 's' and r[2] == r[1] + 3 and r[2] <= 105: + regs = set(range(r[1], r[2] + 1)) + if all(regs <= written for written in literals): + bases.add(r[1]) + return cond, join, bases + + def joined_sampler_call(self, tex, operand, pair, uv, level, name): + for words in pair: + # Point-filtered normalized wrap/clamp, with an actual point mip filter. + w0, w1, w2, w3 = words + if (w0 & ~0x3f or (w0 & 7) not in (0, 2) or ((w0 >> 3) & 7) not in (0, 2) + or w1 & ~0xffffff or w2 != 1 << 26 or w3): + raise Unsupported('%s with unsupported joined sampler words' % name) + self.lod_sampler_words(name, words) + a, b = pair + base = reg_range(operand)[1] + k = next(i for i in range(4) if a[i] != b[i]) + self.used_s.add(base + k) + qa = self.pipe.sampler(a, lod_limits=True) + qb = self.pipe.sampler(b, lod_limits=True) + return '(s%d == 0x%08xu ? %s.SampleLevel(%s, %s, %s) : %s.SampleLevel(%s, %s, %s))' % ( + base + k, a[k], tex, qa, uv, level, tex, qb, uv, level) + def execz_refusals(self): """{offset: reason} for compute blocks that s_cbranch_execz skips and the one-lane model cannot run. @@ -2131,16 +3205,24 @@ def execz_refusals(self): the block (its branches and loops included), which masks have that lane's bit clear, and the write must leave exec among them. Such a lane's bit then stays clear at every instruction the wave runs in the block, so the wave changes nothing of that lane there and its exec at the join is the model's. The proof starts at - the branch, so a block that a branch from outside enters keeps its exec writes refused. A live definition, - an unproven exec write, a refused effect, a branch leaving the block or a backward s_cbranch_execz is - refused. - One live definition is accepted: the i1-phi lane mask of the compiler's if-conversion, a 32-bit M (vcc_lo + the branch, so a block that a branch from outside enters keeps its exec writes refused. A definition live at + the join is accepted when every read of it after the join is proven (execz_live_read), or when it has the + shape below. Any other live definition, an unproven exec write, a refused effect, a branch leaving the block + or a backward s_cbranch_execz is refused. A proven straight lane-exhaustion exit can leave the block for a + scalar run ending in an EXEC restore (execz_scalar_exit, #2645 T3). + + The other accepted live definition is the i1-phi lane mask of the compiler's if-conversion, a 32-bit M (vcc_lo or one sN) zeroed before the branch (`s_mov_b32 M, 0`) and set in the block from exec only (`s_mov_b32 M, exec_lo`, `s_and_b32 M, X, exec_lo` in either operand order). Every write of M in the block yields a value whose bit is 0 for any lane whose exec bit is clear there: the clear-mask proof keeps exec clear for that lane, and a copy of exec, or X & exec, has that bit clear. M is 0 at the branch on every path (nothing branches or lands between the zeroing and the branch). So for a lane the model skips, the wave's M has that lane's bit 0 whether the wave ran the block or not, which is the - model's M (0); a lane that runs the block runs it in the model too. This holds only while M is read per + model's M (0); a lane that runs the block runs it in the model too. Writes that leave a skipped lane's bit + as it was are accepted for any M: `s_andn2_b32 M, M, exec_lo` and `s_or_b32 M, M, T` where T is an exec-masked + value computed in the block (`s_and_b32 T, X, exec_lo` or a v_cmp result), the blend the compiler emits for an + i1 phi whose other input is a per-lane value. A v_cmp into M (not v_cmpx) needs M zeroed before the branch + like the moves above, and `s_orn2_b32 M, X, exec_lo` needs M set to all ones (`s_mov_b32 M, -1`). Zeroing + and all-ones writes do not mix. This holds only while M is read per lane. A whole-mask read (s_cbranch_vccz/vccnz, s_cmp, a plain copy, a data operand) sees the other lanes' bits, which the one-lane model does not have, so any such read of M reachable after the join, before M is rewritten, keeps the refusal. The reads accepted are the lane select of v_cndmask, the carry-in of v_addc / @@ -2168,7 +3250,30 @@ def execz_refusals(self): value = reads | (out - writes) if value != live_in[i]: live_in[i], changed = value, True - refused = {} + vbounds = vgpr_heap_bounds(self.ins, succ) + self.waterfall_reads = {} + self.waterfall_heap_bounds = {} + for close, target in jumps: + head = index.get(target) + if (head is not None and head + 3 < close and self.ins[close][2] == 's_cbranch_scc1' + and self.ins[head][2] == 'v_readfirstlane_b32' + and self.ins[close - 1][2] == 's_andn2_wrexec_b32'): + self.waterfall_reads[target] = self.waterfall_refusal(head, close, effects, live_in, jumps, vbounds) + pre_sub = [EXEC_SUBSET] + [None] * (len(self.ins) - 1) + changed = bool(self.ins) + while changed: + changed = False + for i in range(len(self.ins)): + if pre_sub[i] is None: + continue + after = subset_after(*self.ins[i][2:], effects[i][2], pre_sub[i]) + for s in succ[i]: + if pre_sub[s] is None or not pre_sub[s] <= after: + pre_sub[s] = after if pre_sub[s] is None else (pre_sub[s] & after) + changed = True + refused, into = {}, {} + for k, target in jumps: + into.setdefault(index.get(target), []).append(k) for b, (off, n, name, asm) in enumerate(self.ins): if name != 's_cbranch_execz': continue @@ -2178,7 +3283,7 @@ def execz_refusals(self): continue live = live_in[t] | {'m0'} # m0 is also read implicitly; treat it as live # Facts before each instruction the wave can reach from the branch: the largest sets every path keeps. - entry = frozenset({('exec', 0), ('exec_hi', 1)}) + entry = pre_sub[b] or EXEC_SUBSET before = {b + 1: entry} if b + 1 < t else {} entered = any(index.get(target) in range(b + 1, t) for k, target in jumps if not b < k < t) changed = not entered @@ -2186,7 +3291,7 @@ def execz_refusals(self): changed = False for i in range(b + 1, t): if i in before: - after = frozenset(clear_after(*self.ins[i][2:], effects[i][2], before[i])) | entry + after = frozenset(clear_after(*self.ins[i][2:], effects[i][2], before[i])) | EXEC_SUBSET for s in succ[i]: if b < s < t and before.get(s, after) & after != before.get(s): before[s], changed = before.get(s, after) & after, True @@ -2195,6 +3300,20 @@ def execz_refusals(self): not any(index.get(target) in range(b + 1, t) for target in targets) cand = {k for i in range(b + 1, t) for k in (effects[i][2] - EXEC_KEYS) & live if re.fullmatch(r'vcc|s\d+', k)} ok_masks = {k for k in cand if straight and self.phi_mask_ok(k, b, t, effects, succ, targets, index)} + # A live definition is still accepted when every read of it from the join on is proven (execz_live_read): + # the halves whose lanes keep their bit of the word through the block, and where exec is unchanged since + # the join on every path from it. + kept = {} + for i in range(b + 1, t): + for word in (effects[i][2] - EXEC_KEYS) & live: + if kept.get(word, True): # an empty set stays empty + andn2 = i in before and not entered and self.ins[i][2].startswith('s_andn2') + halves = kept_halves(*self.ins[i][2:], word, before[i]) if andn2 else set() + kept[word] = kept.get(word, halves) & halves + def quiet(j): # exec unchanged since the join on every path to j: a straight run from t, entered at t only + return t <= j and all(b <= k < t for k in into.get(t, ())) and not any( + effects[k][2] & EXEC_KEYS for k in range(t, j)) and not any(k in into for k in range(t + 1, j + 1)) + unread = {} for i in range(b + 1, t): at, _, inner, inner_asm = self.ins[i] may = effects[i][2] @@ -2202,68 +3321,472 @@ def execz_refusals(self): if inner.startswith(EXECZ_REFUSED): reason = 'effect outside scalar registers' elif inner.startswith(('s_cbranch', 's_branch')) and not ( - b < index.get(int(parse(inner_asm)[1][0].split('_')[1], 16), -1) <= t): - reason = 'branch out of the block' + b < (exit_index := index.get(int(parse(inner_asm)[1][0].split('_')[1], 16), -1)) <= t): + # A lane can leave while the wave takes the latch, or take the latch after the wave exits. + if inner == 's_cbranch_scc0' and any( + t <= latch < exit_index and self.ins[latch][2] == 's_cbranch_scc0' + and target in index and index[target] <= b for latch, target in jumps): + reason = 'loop exit crosses a backward s_cbranch_scc0' + elif not (inner == 's_cbranch_scc0' and exit_index > t and + self.execz_scalar_exit(b, i, t, exit_index, effects, live_in, into)): + reason = 'branch out of the block' elif may & EXEC_KEYS and (entered or i in before and - not entry <= clear_after(inner, inner_asm, may, before[i])): + not EXEC_SUBSET <= clear_after(inner, inner_asm, may, before[i])): reason = 'exec write' - elif (may - EXEC_KEYS - ok_masks) & live: - reason = 'definition of %s, live where the block joins' % ', '.join( - sorted((may - EXEC_KEYS - ok_masks) & live)) + elif words := [word for word in sorted((may - EXEC_KEYS - ok_masks) & live) + if self.execz_live_read(t, word, kept[word], effects, succ, quiet, unread) is not None]: + named = [unread[word] for word in words if unread[word] >= 0] + reason = 'definition of %s, live where the block joins' % ', '.join(words) + ( + ': read by %s after the join' % self.ins[min(named)][2] if named else '') if reason: refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason)) return refused - def phi_mask_ok(self, key, b, t, effects, succ, targets, index): - """True when lane mask `key` ('vcc' for vcc_lo, or 'sN'), live at the join t of the s_cbranch_execz at b, is - the zeroed-then-set-from-exec shape execz_refusals accepts (see its docstring): every write of it in the - block is a 32-bit move of exec_lo or an s_and with exec_lo into it alone, the last write before the branch - is `s_mov_b32 M, 0` with no branch and no branch target after it up to the branch, and after the join it is - only read per lane. The caller has checked that the block is straight-line.""" - name = 'vcc_lo' if key == 'vcc' else key - for i in range(b + 1, t): - if key not in effects[i][2]: - continue - _, ops, _ = parse(self.ins[i][3]) - base = re.sub(r'_e(32|64)$', '', self.ins[i][2]) - if not ops or ops[0] != name: - return False - if base == 's_mov_b32' and ops[1:] == ['exec_lo']: - continue - if base == 's_and_b32' and len(ops) == 3 and 'exec_lo' in ops[1:]: - continue + def execz_scalar_exit(self, guard, branch, join, target, effects, live_in, into): + """Prove the straight b32 lane-exhaustion exit and its shared scalar run before restoring EXEC (#2645 T3). + + ANDN2 clears the breaking lanes from a saved mask, SCC tests whether that mask is empty, and the staying + path installs it as EXEC. The proof is scoped to single-wave32 groups (`x * y * z <= 32`) and rejects if + `mask` or `scc` is live at `target`. The wave can do extra vector work only with the exiting lane disabled. + A lane that skipped the guard keeps its original mask bit through ANDN2 because EXEC was clear for that lane. + The shared run can read neither incoming EXEC nor scalar values that differ between the wave and model. + """ + x, y, z = self.pipe.group + if (x * y * z > 32 or into.get(join) != [guard] + or any(k in into for k in range(guard + 1, target) if k != join)): return False - # The zeroing: the last instruction before the branch that may write M. - z = next((k for k in range(b - 1, -1, -1) if key in effects[k][2]), None) - if z is None: + name, ops, mods = parse(self.ins[branch - 1][3]) + if (name != 's_andn2_b32' or mods or len(ops) != 3 or ops[0] != ops[1] + or ops[2] != 'exec_lo' or not re.fullmatch(r's\d+', ops[0])): return False - _, ops, _ = parse(self.ins[z][3]) - if self.ins[z][2] != 's_mov_b32' or ops != [name, '0']: + mask = ops[0] + if live_in[target] & {mask, 'scc'}: return False - if any(self.ins[k][2].startswith(('s_cbranch', 's_branch', 's_setpc')) for k in range(z + 1, b)) or \ - any(index.get(x) in range(z + 1, b + 1) for x in targets): + + def saved_exec(src, move, exec_reg): + words = scalar_tokens(src) + for k in range(guard - 1, -1, -1): + name, ops, mods = parse(self.ins[k][3]) + if k + 1 in into or name.startswith(('s_branch', 's_cbranch', 's_setpc', 's_swappc', 's_movrel', + 's_call', 's_endpgm', 's_rfe')): + break + if words & effects[k][2]: + return not mods and (name == move and ops == [src, exec_reg] or move == 's_mov_b32' and + name == 's_and_saveexec_b32' and len(ops) == 2 and ops[0] == src) return False - # After the join, until M is rewritten, every read must be per lane. - seen, todo = set(), [t] - while todo: - i = todo.pop() - if i in seen: + + if not saved_exec(mask, 's_mov_b32', 'exec_lo'): + return False + for k in range(guard + 1, branch - 1): + name, asm = self.ins[k][2:] + if mask in effects[k][2] or not (name in SCA or name in EXECZ_EXIT_WAITS or + name.startswith(('v_cmp_', 'v_cmpx_')) or + self.vector_only_instruction(name, asm)): + return False + if parse(self.ins[branch + 1][3]) != ('s_mov_b32', ['exec_lo', mask], []): + return False + for k in range(branch + 2, target): + name, asm = self.ins[k][2:] + if name not in EXECZ_EXIT_WAITS and ( + not self.vector_only_instruction(name, asm) or name.endswith('_dpp') or + name.startswith(('v_permlane', 'v_movrel')) or effects[k][0] & (EXEC_KEYS | {mask, 'scc'})): + return False + + for k in range(target, len(self.ins)): + if k != target and k in into: + return False + name, ops, mods = parse(self.ins[k][3]) + if effects[k][2] & EXEC_KEYS: + if mods or len(ops) != 2 or (name, ops[0]) not in (('s_mov_b32', 'exec_lo'), ('s_mov_b64', 'exec')): + return False + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[2] - src[1] != (1 if name == 's_mov_b64' else 0): + return False + words = scalar_tokens(ops[1]) + return saved_exec(ops[1], name, ops[0]) and all( + not words & effects[j][2] for j in range(guard + 1, k)) + if name in EXECZ_EXIT_WAITS: continue - seen.add(i) - reads, writes, _ = effects[i] - if key in reads and not self.per_lane_read(i, key): + if (mods or not (name in SCA or name in SCALAR_LOADS or name.startswith(('s_cmp_', 's_bitcmp'))) or + any(not (re.fullmatch(r's(?:\d+|\[\d+:\d+\])|src_scc|-?(?:0x[\da-f]+|\d+)', op) + or op in FLOATS) for op in ops)): return False - if key not in writes: - todo.extend(succ[i]) - return True + return False - def per_lane_read(self, i, key): - """True when instruction i reads mask `key` only as a lane select or carry, or into exec (s_and_saveexec, - s_and with exec): the lane's own bit is all it uses.""" - _, _, name, asm = self.ins[i] - base = re.sub(r'_e(32|64)$', '', name) - _, ops, _ = parse(asm) - if base.startswith(('v_cndmask', 'v_addc', 'v_subb', 'v_add_co_ci', 'v_sub_co_ci', 'v_subrev_co_ci')): + def execz_live_read(self, t, word, halves, effects, succ, quiet, unread): + """None when every read of `word` from the join t of an execz block on, until a write of it ends the block's + definition, gives a lane the model skipped the wave's result; else the first read that is not proven, or -1 + for m0 and SCC, which have implicit readers. + + Such a lane's exec bit is clear at the join, in the model and in the wave (execz_refusals proves the block's + exec writes), and the two differ there at most in `word`. A read is proven when: + - exec is unchanged on every path from the join to it (`quiet`: the read ends a straight run that starts at + the join, which only the block enters, with no exec write in it) and it reads `word` only as W & exec, + ~(W & exec) or W | ~exec, exec of the same lanes (exec_absorbs): the lane's bit of the result is fixed + whatever its bit of `word` is, so the result agrees, and when it overwrites `word` the definition ends; + - the block keeps the lane's bit of `word` for its half (kept_halves: every write of `word` in the block is + s_andn2 R, R, X with X clear for the lane, checked over every path from the branch) and the read is a lane + mask read of that half (lane_read): the lane's bit of `word` is the model's, so its bit of the result is + too, and `word` written back that way keeps the property. + Any other read, a data read or a copy into another register included, is not proven. The search stops at + the first such read, nearest the join; the result is kept in `unread` for the block.""" + if word in unread: + return unread[word] + if not re.fullmatch(r'vcc(_hi)?|s\d+', word): + unread[word] = -1 + return -1 + seen, work = {t}, [t] + for j in work: # breadth first: the list grows while it is read + name, asm = self.ins[j][2:] + kept_read = word in effects[j][0] and halves and lane_read(name, asm, word, halves) + if word in effects[j][0] and not kept_read and not (exec_absorbs(name, asm, word) and quiet(j)): + unread[word] = j + return j + if kept_read or word not in effects[j][1]: + for s in succ[j]: + if s not in seen: + seen.add(s) + work.append(s) + unread[word] = None + return None + + def compute_resheap_sgpr(self): + pipe = getattr(self, 'pipe', None) + root = getattr(pipe, 'root', None) + if not root or not (root['flags'] & 0x400): + return None + reg = 4 if getattr(self, 'kind', None) == 'cs' else 8 + for p in root['params']: + reg += 1 if p['type'] == 0 else p['count'] if p['type'] == 1 else 2 + return reg + + def waterfall_heap_check(self, head, close, effects, key, key_vtok, body_writes, numeric_writes, + buffer_descriptors, vbounds): + """Return ('idx' | 'off5', max_idx) when every key-dependent descriptor selection in the waterfall + body reads a resource heap record at a proven bounded per-lane index, else None.""" + if buffer_descriptors & numeric_writes: + return None + resheap_reg = self.compute_resheap_sgpr() + if resheap_reg is None or ('s%d' % resheap_reg) in body_writes or not vbounds: + return None + binfo = vbounds[head] + k_reg = int(key_vtok[1:]) + key_bound = binfo[0].get(k_reg) if binfo else None + if not key_bound: + return None + ins = self.ins + local_idx = {key} if key_bound[0] == 'idx' else set() + local_off5 = {key} if key_bound[0] == 'off5' else set() + local_ptrs = set() + heap_aliases = {'s%d' % resheap_reg} + local_descs = set() + pending_carry = None + for j in range(head + 2, close - 1): + base, ops, mods = parse(ins[j][3]) + base = re.sub(r'_e(32|64)$', '', base) + reads, _writes, may_write = effects[j] + if pending_carry is not None: + carry_d, want_j = pending_carry + pending_carry = None + hi_tok = 's%d' % (carry_d + 1) + carry_ok = (j == want_j and not mods and ( + (base == 's_add_u32' and ops == [hi_tok, '0', 'src_scc']) or + (base == 's_addc_u32' and len(ops) == 3 and ops[0] == hi_tok and ops[2] == '0' + and ops[1] not in body_writes))) + if not carry_ok: + return None + local_ptrs.add(('s%d' % carry_d, hi_tok)) + for w in may_write: + local_idx.discard(w) + local_off5.discard(w) + heap_aliases.discard(w) + local_descs = {tup for tup in local_descs if w not in tup} + continue + idx_hit = (base == 's_lshl_b32' and not mods and len(ops) == 3 and ops[1] in local_idx and ops[2] == '5') + mov_idx = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in local_idx + mov_off5 = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in local_off5 + mov_heap = base == 's_mov_b32' and not mods and len(ops) == 2 and ops[1] in heap_aliases + add_hit = (base == 's_add_u32' and not mods and len(ops) == 3 and ( + (ops[1] in heap_aliases and ops[2] in local_off5) or + (ops[2] in heap_aliases and ops[1] in local_off5))) + load_hit = False + if base == 's_load_dwordx4' and (reads & body_writes): + if mods or len(ops) != 3: + return None + br, dr = reg_range(ops[1]), reg_range(ops[0]) + if not br or br[0] != 's' or br[2] - br[1] != 1 or not dr or dr[0] != 's' or dr[2] - dr[1] != 3: + return None + b_lo, b_hi = 's%d' % br[1], 's%d' % br[2] + off_tok = smem_offset(ops[2]) + if not ((b_lo in heap_aliases and b_hi not in body_writes and off_tok in local_off5) or + ((b_lo, b_hi) in local_ptrs and _lit_u32(off_tok) == 0)): + return None + load_hit = tuple('s%d' % k for k in range(dr[1], dr[2] + 1)) + elif base == 'buffer_load_dword' and (reads & body_writes): + br = reg_range(ops[2]) if len(ops) >= 3 else None + dtup = tuple('s%d' % k for k in range(br[1], br[2] + 1)) if br and br[0] == 's' and br[2] - br[1] == 3 else None + if dtup not in local_descs or any(tok in body_writes and tok not in dtup for tok in scalar_tokens(ops[2])): + return None + for w in may_write: + local_idx.discard(w) + local_off5.discard(w) + heap_aliases.discard(w) + local_ptrs = {pair for pair in local_ptrs if w not in pair} + local_descs = {tup for tup in local_descs if w not in tup} + if idx_hit: + local_off5.add(ops[0]) + elif mov_idx: + local_idx.add(ops[0]) + elif mov_off5: + local_off5.add(ops[0]) + elif mov_heap: + heap_aliases.add(ops[0]) + elif add_hit: + dr = reg_range(ops[0]) + if not dr or dr[0] != 's' or dr[1] != dr[2] or dr[1] >= 105: + return None + pending_carry = (dr[1], j + 1) + elif load_hit: + local_descs.add(load_hit) + if pending_carry is not None: + return None + return key_bound + + def waterfall_refusal(self, head, close, effects, live_in, jumps, vbounds=None): + """Return None when the lane can pick its own key at the head of the waterfall. + + CMPX selects all remaining lanes with the first lane's key. WREXEC removes those lanes, + so each incoming lane participates exactly once. A lane-local body computes its value on + that visit. Other visits can only affect it through shared state or an escaping scalar. + """ + ins = self.ins + _, key_ops, mods = parse(ins[head][3]) + if (mods or len(key_ops) != 2 or not re.fullmatch(r's\d+', key_ops[0]) + or not re.fullmatch(r'v\d+', key_ops[1])): + return 'unsupported key operands' + key = key_ops[0] + name, ops, mods = parse(ins[head + 1][3]) + if re.sub(r'_e(32|64)$', '', name) != 'v_cmpx_eq_i32' or mods or ops != key_ops: + return 'the next instruction does not select lanes with the same key' + _, ops, mods = parse(ins[close - 1][3]) + if mods or len(ops) != 2 or ops[0] != ops[1] or not re.fullmatch(r's\d+', ops[0]) or ops[0] == key: + return 'the closing mask is not a distinct remaining-lanes register' + remaining = ops[0] + # The b32 close covers only the low 32 lanes when the hardware uses wave64. + x, y, z = self.pipe.group + if x * y * z > 32: + return 'b32 remaining mask requires at most 32 threads per group' + copy = None + for i in reversed(range(head)): + _, _, op, asm = ins[i] + if op.startswith(('s_branch', 's_cbranch', 's_setpc', 's_endpgm', 's_movrel')): + break + if remaining in effects[i][2] or effects[i][2] & EXEC_KEYS: + if op == 's_mov_b32' and parse(asm)[1] == [remaining, 'exec_lo']: + copy = i + break + if copy is None: + return 'remaining mask is not an unchanged copy of EXEC' + if any(ins[copy][0] < target <= ins[close][0] for branch, target in jumps if branch != close): + return 'another branch enters the saved mask or loop' + # Only ordinary lane-local operations and reads of a bound raw buffer. An instruction + # that observes the other lanes sharing this key cannot use this scalarization (e.g. mbcnt of EXEC). + body_writes = {key, 'scc'} # WREXEC supplies SCC for the next iteration. + numeric_writes = {key} + descriptor_inputs, buffer_descriptors = set(), set() + reads_before_write = set() + defined = {key} + keyed = {key} # scalars whose value depends on the key (so on the iteration) after the instructions so far + for j in range(head + 2, close - 1): + base, ops, mods = parse(ins[j][3]) + base = re.sub(r'_e(32|64)$', '', base) + if base not in ('s_add_u32', 's_addc_u32', 's_mov_b32', 's_and_b32', 's_or_b32', 's_lshl_b32', 's_waitcnt', + 'v_mov_b32', 'v_xor_b32', 'v_add_nc_u32', 's_load_dwordx4', 'buffer_load_dword'): + return 'body instruction %s is not proven lane-local' % base + if mods and not (base == 'buffer_load_dword' and mods == ['offen']): + return 'body instruction %s has unproved modifiers' % base + reads, writes, may_write = effects[j] + if (reads | may_write) & (EXEC_KEYS | {'vcc', 'vcc_hi', 'm0', remaining}): + return 'body reads or changes a lane mask or special register' + if base == 's_load_dwordx4': + dst = reg_range(ops[0]) if len(ops) == 3 else None + if not dst or dst[0] != 's' or dst[2] > 105: + return 'descriptor load overlaps a special register' + descriptor_inputs.update(reads) + else: + numeric_writes.update(may_write) + if base == 'buffer_load_dword': + if len(ops) < 3: + return 'buffer load has no descriptor' + buffer_descriptors.update(scalar_tokens(ops[2])) + reads_before_write.update(reads - defined) + defined.update(writes) + if base in ('s_add_u32', 's_addc_u32', 's_and_b32', 's_or_b32', 's_lshl_b32'): + defined.add('scc') + body_writes.update(may_write) + if (reads & keyed) or base == 'buffer_load_dword': + keyed.update(may_write) + else: + keyed -= writes + if reads_before_write & body_writes: + return 'body reads loop-carried scalar state' + # The data byte offset can use the key. Loading or modifying the resource descriptor + # with the key needs a separate proof that the runtime binds the whole range. + if descriptor_inputs & body_writes or buffer_descriptors & numeric_writes: + bound = self.waterfall_heap_check(head, close, effects, key, key_ops[1], body_writes, numeric_writes, + buffer_descriptors, vbounds) + if bound is None: + return 'per-lane descriptor selection requires a proven bound heap range' + self.waterfall_heap_bounds[ins[head][0]] = bound + # The close leaves EXEC and SCC zero. The last physical pass's other scalar + # values can differ per lane in this model and must be dead on every successor. + # A scalar written from loop-invariant inputs only (no read of the key or of a key-dependent scalar, no + # load through a body address) holds the same value in every iteration, so the last pass's value is each + # lane's own: it may be live. The key and anything computed from it may not. + if close + 1 < len(ins) and (body_writes - {'scc'}) & live_in[close + 1] & (keyed | {key}): + return 'body scalar is live at the loop exit' + if any(name.startswith('s_movrel') for _, _, name, _ in ins): + return 'relative scalar indexing can observe a loop register' + return None + + def phi_mask_ok(self, key, b, t, effects, succ, targets, index): + """True when lane mask `key` ('vcc' for vcc_lo, or 'sN'), live at the join t of the s_cbranch_execz at b, leaves the + bit of every lane the model skips as the wave has it (see execz_refusals), and after the join it is only read per + lane. A lane the model skips has its exec bit clear for the whole block (the exec proof), and the wave runs the block + iff some lane is active, so the model is exact iff the block never changes that lane's bit of M. Every write of M + in the block is one of (mask_write_class), a 32-bit M written alone. Every mask it uses must hold lane bits + (lane_bit_keys, or a block temp): the model keeps a lane's bit at bit 0 where the wave has it at bit `lane`: + 'keep' s_andn2 M, M, exec_lo; s_or M, M, T with T written in the block by s_and with exec_lo or a v_cmp + (bit 0 for a lane whose exec bit is clear): the lane's bit is unchanged, whatever M held before. + 'zero' s_mov M, exec_lo; s_and M, X, exec_lo; a v_cmp into M (VOPC writes 0 for an inactive lane): bit 0, + exact only when M was zero before the branch: the last write before it is `s_mov_b32 M, 0`. + 'ones' s_orn2 M, X, exec_lo: bit 1, exact only when M was all ones before it: `s_mov_b32 M, -1`. + Zeroing or setting M before the branch needs no branch and no branch target after it up to the branch; 'zero' and + 'ones' writes do not mix. Any other write (M reused as an offset) is accepted only if a later 'zero' or 'ones' + write overwrites it, since a 'keep' write would carry its bits for a skipped lane. The caller has checked that the block is straight-line.""" + name = 'vcc_lo' if key == 'vcc' else key + classes, temps, stale = set(), set(), False + enc = self.lane_bit_keys(b, effects, targets, index) + for i in range(b + 1, t): + wrote = effects[i][2] + _, ops, _ = parse(self.ins[i][3]) + base = re.sub(r'_e(32|64)$', '', self.ins[i][2]) + if key in wrote: + if not ops or ops[0] != name: + return False + kind = self.mask_write_class(base, ops, name, temps, enc) + if kind is None: + stale = True # data in M (an s_movk used as an offset): only a later full overwrite makes it exact + else: + classes.add(kind) + stale = stale and kind == 'keep' + for w in wrote - {key} - EXEC_KEYS: + # T must also hold lane bits: an s_and of exec with a lane mask (not with a group id or other data) + lane_src = base != 's_and_b32' or any( + ('vcc' if x == 'vcc_lo' else x) in temps | enc for x in ops[1:] if x != 'exec_lo') + if self.exec_masked_def(base, ops, w) and lane_src: + temps.add(w) + else: + temps.discard(w) + enc.discard(w) + if stale or ('zero' in classes and 'ones' in classes): + return False + if 'keep' in classes and key not in self.lane_bit_keys(b, effects, targets, index): + return False # M's bits before the block must already be lane bits (bit 0 = this lane), not data + need = {'zero': '0', 'ones': '-1'}.get(next(iter(classes & {'zero', 'ones'}), None)) + if need is not None: + # The setting: the last instruction before the branch that may write M. + z = next((k for k in range(b - 1, -1, -1) if key in effects[k][2]), None) + if z is None: + return False + _, ops, _ = parse(self.ins[z][3]) + if self.ins[z][2] not in ('s_mov_b32', 's_movk_i32') or ops != [name, need]: + return False + if any(self.ins[k][2].startswith(('s_cbranch', 's_branch', 's_setpc')) for k in range(z + 1, b)) or \ + any(index.get(x) in range(z + 1, b + 1) for x in targets): + return False + # After the join, until M is rewritten, every read must be per lane. + seen, todo = set(), [t] + while todo: + i = todo.pop() + if i in seen: + continue + seen.add(i) + reads, writes, _ = effects[i] + if key in reads and not self.per_lane_read(i, key): + return False + if key not in writes: + todo.extend(succ[i]) + return True + + def lane_bit_keys(self, b, effects, targets, index): + """Keys ('vcc' or 'sN') whose value at the s_cbranch_execz at b holds the lane's own bit as bit 0, the encoding the + one-lane model gives a lane mask: the last write before b is a v_cmp, an s_and with exec_lo, a copy of exec_lo, or + 0 / -1 (every bit alike), with no branch or branch target between it and b. A value from anywhere else (a group id, + an offset, `s_mov_b32 M, 16`) has the wave's lane bit at bit `lane`, which the model reads from bit 0.""" + entries = {index.get(target) for target in targets} + start = next((k + 1 for k in range(b - 1, -1, -1) + if self.ins[k][2].startswith(('s_cbranch', 's_branch', 's_setpc')) + or k + 1 in entries), 0) + found = set() + for k in range(start, b): + _, ops, _ = parse(self.ins[k][3]) + base = re.sub(r'_e(32|64)$', '', self.ins[k][2]) + writes = effects[k][2] - EXEC_KEYS + proven = set() + for w in writes: + name = 'vcc_lo' if w == 'vcc' else w + masked = self.exec_masked_def(base, ops, w) + if masked and base == 's_and_b32': + other = ops[2] if ops[1] == 'exec_lo' else ops[1] + key = 'vcc' if other == 'vcc_lo' else other + masked = key in found or other in ('0', '-1', 'exec_lo') + if masked or (base in ('s_mov_b32', 's_movk_i32') and len(ops) == 2 + and ops[0] == name and ops[1] in ('0', '-1', 'exec_lo')): + proven.add(w) + found.difference_update(writes) + found.update(proven) + return found + + @staticmethod + def exec_masked_def(base, ops, key): + """True when this instruction writes `key` ('sN' or 'vcc') with a value whose bit is 0 for a lane whose exec bit is + clear: s_and with exec_lo into it, or a v_cmp (not v_cmpx) into it.""" + name = 'vcc_lo' if key == 'vcc' else key + if not ops or ops[0] != name: + return False + if base == 's_and_b32': + return len(ops) == 3 and 'exec_lo' in ops[1:] + return base.startswith('v_cmp') and not base.startswith('v_cmpx') + + @staticmethod + def mask_write_class(base, ops, name, temps, enc=frozenset()): + """'keep', 'zero' or 'ones' for a write of mask `name` inside an execz block (see phi_mask_ok), else None.""" + key = 'vcc' if name == 'vcc_lo' else name + if base == 's_mov_b32' and ops[1:] == ['exec_lo']: + return 'zero' + lane = lambda x: ('vcc' if x == 'vcc_lo' else x) in temps | enc # a lane mask: bit 0 is this lane's bit + if base == 's_and_b32' and len(ops) == 3 and 'exec_lo' in ops[1:] and lane(ops[2] if ops[1] == 'exec_lo' else ops[1]): + return 'zero' + if base.startswith('v_cmp') and not base.startswith('v_cmpx'): + return 'zero' + if base == 's_orn2_b32' and len(ops) == 3 and ops[2] == 'exec_lo' and lane(ops[1]): + return 'ones' + if base == 's_andn2_b32' and ops == [name, name, 'exec_lo']: + return 'keep' + if base == 's_or_b32' and len(ops) == 3 and name in ops[1:]: + other = ops[2] if ops[1] == name else ops[1] + if other != name and ('vcc' if other == 'vcc_lo' else other) in temps: + return 'keep' + return None + + def per_lane_read(self, i, key): + """True when instruction i reads mask `key` only as a lane select or carry, or into exec (s_and_saveexec, + s_and with exec): the lane's own bit is all it uses.""" + _, _, name, asm = self.ins[i] + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + if base.startswith(('v_cndmask', 'v_addc', 'v_subb', 'v_add_co_ci', 'v_sub_co_ci', 'v_subrev_co_ci')): # the mask is the last operand and appears nowhere else (not as a data word, not as the destination) return len(ops) >= 4 and key in scalar_tokens(ops[-1]) and \ all(key not in scalar_tokens(op) for op in ops[:-1]) @@ -2287,10 +3810,12 @@ def joined_registers(self, with_cfg=False): With ``with_cfg=True``, returns ``(joined, forward_splits, div_targets)`` where ``forward_splits`` keeps only writes on non-dominating forward arms between a target's dominators and the target (excluding loop back edges) and ``div_targets`` maps each ``s_cbranch_*`` offset to ``(writes, affected_targets)`` inside its divergent - CFG region (between the branch and its immediate post-dominator, or over the loop range for a backward edge).""" + CFG region (between the branch and its immediate post-dominator, or over the loop range for a backward edge). + A fourth item, ``(bounds, block_of, succ, div_blocks)``, is the block graph and that region's blocks per + ``s_cbranch_*`` offset, for the spill-slot proof (spill_reaching).""" ins = self.ins if not ins: - return ({}, {}, {}) if with_cfg else {} + return ({}, {}, {}, ([], {}, [], {})) if with_cfg else {} index = {off: i for i, (off, *_) in enumerate(ins)} calculated = getattr(self, 'calculated_pc', {}) # unit probes build a Stage without translate() branch = lambda name: name.startswith('s_cbranch') or name in ('s_branch', 's_setpc_b64') @@ -2376,7 +3901,7 @@ def joined_registers(self, with_cfg=False): new = {b} | set.intersection(*(pdom[s] for s in succ[b])) if new != pdom[b]: pdom[b], changed = new, True - div_targets = {} + div_targets, div_blocks = {}, {} for b, (lo, hi) in enumerate(bounds): off, _n, name, asm = ins[hi - 1] if not name.startswith('s_cbranch'): @@ -2389,6 +3914,7 @@ def joined_registers(self, with_cfg=False): loop_blks = range(min(t_blk, b), b + 1) regs = set().union(*(writes[w] for w in loop_blks)) affected = {off_of[w] for w in loop_blks} & all_targets + div_blocks[off] = set(loop_blks) else: stop = pdom[b] - {b} ipd = max(stop, key=lambda x: len(pdom[x])) if stop else None @@ -2401,9 +3927,10 @@ def joined_registers(self, with_cfg=False): dtodo += succ[w] regs = set().union(*(writes[w] for w in div)) if div else set() affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets + div_blocks[off] = div div_targets[off] = (regs, affected) self.flow = (index, block_of, succ, dom, writes, {}) - return joined, forward_splits, div_targets + return joined, forward_splits, div_targets, (bounds, block_of, succ, div_blocks) def unjoined(self, target, last_write, regs): """The registers of regs whose program-order state is not proven at a branch target. A lane-mask mark or a @@ -2434,6 +3961,10 @@ def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ vcc_branches = getattr(self, 'mesh_vcc_branches', {}) wave_limits = getattr(self, 'mesh_wave_limits', {}) + wave_loads = getattr(self, 'mesh_wave_loads', {}) + wave_load_compares = {compare: bound for compare, bound, _, _ in wave_loads.values()} + wave_load_sites = {load for _, _, loads, _ in wave_loads.values() for load in loads} + execz_effects = 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes' vcc_compares = set().union(*vcc_branches.values()) try: self.calculated_pc = calculated_pc_proof(self.ins, getattr(self, 'kind', None)) @@ -2442,6 +3973,12 @@ def translate(self): raise refusals.append((str(reason), self.kind)) self.calculated_pc = {} + try: + terminal_continuation_proof(self.ins, self.calculated_pc) + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) targets = set() targets.update(target for target in self.calculated_pc.values() if target is not None) # (branch, target) of every branch, the proven s_setpc_b64 jumps included @@ -2451,11 +3988,19 @@ def translate(self): target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) branches.append((off, target)) + if getattr(self, 'kind', None) == 'cs': + self.address_carry_pairs = adjacent_address_carries(self.ins, targets) + # Forward edges reach each block in disassembly order. A back edge could + # repeat a pointer advance before the next table load. + self.forward_table_adds = (getattr(self, 'kind', None) in ('vs', 'ps') and bool(branches) + and all(target > pc for pc, target in branches)) # Targets that only forward s_cbranch_execz branches (and the fall-through) enter: on a taken edge the lane's # exec bit is 0 at the target. Compute stages have their own execz handling and are left out. names = {off: name for off, _n, name, _asm in self.ins} execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} + back_targets = {to for pc, to in branches if to <= pc} + sampler_diamond = self.sampler_join_shape(branches) if branches else None self.mesh_allocation_block = None splits = set(targets) if getattr(self, 'kind', None) == 'ms' and targets: @@ -2466,7 +4011,33 @@ def translate(self): splits.update((self.mesh_allocation_block, self.ins[at + 2][0])) join_writes = self.join_writes(branches) refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ - joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) + # A pixel program with an implicit-derivative op and no backward branch decides its EXEC branches per quad + # (quad vote): see Stage.quad_vote. Loops keep the rules of the back-edge proof below. + self.quad_exec = getattr(self, 'kind', None) == 'ps' and not any(t <= pc for pc, t in branches) and any( + name in DERIVATIVE_OPS for _off, _n, name, _asm in self.ins) + self.uses_quad_vote = False + joined, forward_splits, div_targets, self.spill_cfg = self.joined_registers(with_cfg=True) + self.has_image_writes = any(name.startswith(('image_store', 'image_atomic')) for _, _, name, _ in self.ins) + self.loads_after_exec_write = set() + all_uniform_loads = UNIFORM_LOADS | UNIFORM_IMAGE_LOADS + if (back_targets and getattr(self, 'kind', None) == 'cs' and + any(name in all_uniform_loads for _, _, name, _ in self.ins)): + # A later block can reach an earlier load through one or more edges. exec_known only sees + # instructions already translated. Follow the CFG, including paths outside a loop's textual range. + bounds, _, succ, _ = self.spill_cfg + pending = [] + for block, (lo, hi) in enumerate(bounds): + if any(writes_exec(name, parse(asm)[1]) for _, _, name, asm in self.ins[lo:hi]): + pending.extend(succ[block]) + visited = set() + while pending: + block = pending.pop() + if block not in visited: + visited.add(block) + lo, hi = bounds[block] + self.loads_after_exec_write.update(pc for pc, _, name, _ in self.ins[lo:hi] if name in all_uniform_loads) + pending.extend(succ[block]) + self.spill_reach = self.spill_reaching(self.spill_cfg) init_sym = dict(self.sym) init_exec_known = getattr(self, 'exec_known', True) init_wqm_exec = getattr(self, 'wqm_exec', False) @@ -2491,13 +4062,25 @@ def translate(self): for _ in range(max(4, len(self.ins) + 2)): scc_effects = {} + self.address_carry_reader = None uniform_vcc_compares = set() self.lines = [] + self.vconst = {} self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec + self.wqm_count, self.execcopy_epoch = 0, {} + self.helper_restore = False + # True until a wave-divergent branch: SampleBias / CalculateLevelOfDetail need uniform CF. + self.uniform_cf = True + self.derivative_sites = [] # (offset, name) of image_sample_b / image_get_lod, for the back-edge proof + self.divergent_back_edges = [] # (target, branch offset) of divergent backward branches + self.lane_exec_breaks = [] # (offset, what): the lane's EXEC bit may stop following the guest's from here + self.voted_branches = set() # EXEC branches decided per quad (x2w_quad_any); they part no quad + self.plain_samples = {} # offset -> (level-0 call, implicit-LOD call) of a plain image_sample past a join self.masks = set(init_masks) + self.mask_high = set() self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) last_write = {} # SGPR -> offset of its last write in program order self.attrs = dict(init_attrs) @@ -2511,19 +4094,44 @@ def translate(self): self.fetched = False self.uniform_v = set() self.varying_s = set() + self.align4_v = set() + self.align4_s = set() self.scc_uniform = True + self.scc_verified = False + # Offset of the emitted, uniform SCC write that reaches here (None: none, or not proven), and the one + # each forward branch carries to its target. + self.scc_def, scc_in = None, {} self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant self.has_branches = bool(targets) + self.quad_flow_reads = [] # (offset, mnemonic) of DPP quad reads lowered in a program with branches + self.divergent_branches = {} # s_cbranch offset -> mnemonic, for branches not proven wave-uniform + self.wqm_set_at = None # offset of the s_wqm exec, exec that proved whole-quad EXEC first + # Rebuilt every pass: a retry translates the program again, and a span recorded on an earlier pass + # would describe a chain that this pass must match itself. + self.wave_reduce_spans = [] + self.reduce_plan = {} + self.reduce_pending = {} + self.spill_slots = {} # (vgpr, lane) -> (sym, uniform, proven, mask) for constant-lane SGPR spills self.vcc_events = {} + self.vcc_lost = self.vcc_descriptor_overwritten = False self.entry_table_pointers = { reg: sym[1] for reg, sym in init_sym.items() if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table' } self.descriptor_block_first = 0 self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.uniform_load_temps = set() # temporaries of uniform loads past the entry block (set_v) + self.uniform_branches = set() # s_cbranch_* offsets proven uniform in this pass (spill-slot proof) + self.spill_writes = {} # instruction index of a v_writelane_b32 translated in this pass -> (sym, uniform, proven, mask) + self.heap_index = {} # SGPR -> what its word is for a resource-heap s_load (see heap_record) + self.heap_index_was = {} # the marks the current instruction's destinations held before it + self.per_lane_index = {} # SGPR -> (expr, max_idx) from bounded waterfall v_readfirstlane_b32 + self.per_lane_index_was = {} + self.resheap_low_add = None + self.resheap_index_temps = [] self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) self.bad_sgprs = set() @@ -2533,25 +4141,50 @@ def translate(self): incoming = {} kept = {} self.back_force = {} + self.sampler_joins = {} written = set(init_written) falls = True start = 0 raised_unsupported = None + self.exec_keep = {} # registers whose body-arm descriptor symbol is kept after an execz join (rule R1) for instruction_index, (off, n, name, asm) in enumerate(self.ins): + if self.exec_keep: + self.end_exec_keep(instruction_index, off, name, asm, targets) if off in splits and off != start: self.pinned_low16_v.update(self.low16_only_v) + self.align4_v.clear() + self.align4_s.clear() self.blocks.append((start, self.lines, None)) self.lines, start = [], off self.descriptor_block_first = instruction_index self.pc = off self.descriptor_instruction_index = instruction_index self.scc_effect = None + if off in targets: + # Every path in carries the same uniform emitted write, which the lane and the wave both ran + # last, whichever path each took (a per-lane s_cbranch_execz edge included); the SCC writes on a + # back edge are not known yet. + defs = ([self.scc_def] if falls else []) + scc_in.get(off, []) + one_def = off not in back_targets and len(set(defs)) == 1 + self.scc_def = defs[0] if one_def else None + elif not falls: + self.scc_def = None + if not falls: + self.scc_verified = False + self.resheap_low_add = None + self.align4_v.clear() + self.align4_s.clear() # Before the first branch target or terminator every path has run exactly the instructions above, so # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a # branch-free program is past it too (dead code). self.past_entry = bool(self.blocks) or 0 in targets if off in targets: + self.heap_index.clear() # another path into the join may hold a different word + self.per_lane_index.clear() + self.resheap_low_add = None + self.align4_v.clear() + self.align4_s.clear() pre_uniform = { r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) if r not in self.varying_s and r not in self.masks @@ -2561,9 +4194,28 @@ def translate(self): arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ incoming.get(off, []) written = (written - here) | set().union(*(w for _, w in arriving)) + self.sampler_joins.clear() + if (sampler_diamond and off == sampler_diamond[1] and falls and len(arriving) == 2 + and self.exec_known and self.uniform_cf and sampler_diamond[0] in self.uniform_branches): + for base in sampler_diamond[2]: + regs = range(base, base + 4) + if any(forced.get(off, {}).get(r) is not None for r in regs): + continue + if not all(all(r in w and s.get(r) and s[r][0] == 'const' and len(s[r]) == 2 + for r in regs) for s, w in arriving): + continue + pair = tuple(tuple(s[r][1] & 0xffffffff for r in regs) for s, _ in arriving) + if pair[0] != pair[1]: + self.sampler_joins[base] = pair for reg in here: paths = [s[reg] for s, w in arriving if reg in w] force = forced.get(off, {}).get(reg) + if falls and off in execz_targets and self.exec_zero_keepable(off, reg, arriving, paths, branches): + # R1: a descriptor word the fall-through arm wrote and every other edge (a taken execz edge, exec == 0) + # skipped. Until exec is written again only exec-masked reads can see it: keep the arm's symbol. + self.sym[reg] = paths[0] + self.exec_keep[reg] = paths[0] + continue if any(reg not in w for _, w in arriving) and any(p and not run_time_symbol(p) for p in paths): self.sym[reg] = ('joined at a branch target',) continue @@ -2595,6 +4247,7 @@ def translate(self): tentative_kept.update((kept_u & clobber) - blocked) self.uniform_v.clear() self.since_join, self.scc_uniform = kept_u, False + self.scc_verified = self.scc_def is not None # A constant is only known here if no other path into the join writes the register: a loop counter # set before the loop and incremented in it reaches the loop head with a new value on every pass. # set_s also assigns constants at run time, so the register reads its real value once it is dropped. @@ -2613,12 +4266,21 @@ def translate(self): (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') ) } + if off in targets and self.exec_keep and name.startswith('s_'): + # The join instruction itself runs with exec == 0 on the taken edge: a scalar read of a kept word ends it here. + self.end_exec_keep_scalar_read(name, asm) + if off in targets and self.exec_keep and ( + name.startswith('s_cbranch') or name in ('s_branch', 's_setpc_b64')): + # The join instruction is itself a branch: end_exec_keep only runs at the top of the next + # instruction, so retire the kept words before the branch records its incoming edge. + self.retire_exec_keep(set(self.exec_keep)) if name.startswith('s_cbranch') or name == 's_branch' or ( name == 's_setpc_b64' and self.calculated_pc.get(off) is not None): b_target = self.calculated_pc[off] if name == 's_setpc_b64' else int(parse(asm)[1][0].split('_')[1], 16) there = joined.get(b_target, set()) if b_target > off: incoming.setdefault(b_target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) + scc_in.setdefault(b_target, []).append(self.scc_def) else: for reg in there & written: back, sym = self.sym.get(reg), kept.get(b_target, {}).get(reg) @@ -2629,6 +4291,10 @@ def translate(self): reg, 'run' if run_time_symbol(sym) else 'refuse') falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) + if self.sampler_joins and dests: + for base in tuple(self.sampler_joins): + if 'any' in dests or any(r in dests for r in range(base, base + 4)): + del self.sampler_joins[base] written |= every_sgpr if 'any' in dests else dests last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) self._pre_fconst = dict(self.float_const_s) @@ -2641,6 +4307,17 @@ def translate(self): if off in refused: raise Unsupported(refused[off]) base = re.sub(r'_e(32|64)$', '', name) + if off in wave_load_compares: + bound = wave_load_compares[off] + if not self.uniform_source(bound) or int(bound[1:]) not in self.defined_uniform_s: + raise Unsupported(execz_effects) + # Capture the bound at the compare, before any intervening SGPR write. + self.emit('wave_any = (tid & ~63u) < %s;' % self.u(bound)) + if off in wave_load_sites: + offset = smem_offset(parse(asm)[1][2]) + if not self.uniform_source(offset) or ( + re.fullmatch(r's\d+', offset) and int(offset[1:]) not in self.defined_uniform_s): + raise Unsupported(execz_effects) if off in vcc_compares and all( not mesh_vregs([tok]) and self.uniform_source(tok) for tok in parse(asm)[1][1:] @@ -2648,24 +4325,59 @@ def translate(self): uniform_vcc_compares.add(off) if base.startswith('s_cbranch_'): cond = base[10:] - cond_uniform = (cond in ('scc0', 'scc1') and self.scc_uniform) or off in wave_limits + if off in wave_loads: + # An empty wave keeps the previous values of the scalars the block writes and the + # join reads, so each must be wave-uniform and defined before the block. + for dst in wave_loads[off][3]: + if not self.uniform_source(dst) or int(dst[1:]) not in self.defined_uniform_s: + raise Unsupported(execz_effects) + self.u(dst) # declare the variable; refuses a symbol with no run-time value + cond_uniform = ((cond in ('scc0', 'scc1') and self.scc_uniform) + or off in wave_limits or off in wave_loads) if off in vcc_branches: if not vcc_branches[off] <= uniform_vcc_compares: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) cond_uniform = True + if cond_uniform: + self.uniform_branches.add(off) + elif (cond in ('execz', 'execnz') and self.quad_exec and not self.exec_known + and self.uniform_cf and not self.lane_exec_breaks + and self.skipped_block_vector_only(off, int(parse(asm)[1][0].split('_')[1], 16))): + # Decided per quad (x2w_quad_any): every lane of a quad takes it together, so it parts no + # quad and the derivative ops after it still see their four lanes. It reads the quad, so it + # is only taken while the control flow so far is quad-uniform and every lane's EXEC bit + # still follows the guest's. + self.voted_branches.add(off) + cond_uniform = True if not cond_uniform: + # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. + self.uniform_cf = False + self.divergent_branches[off] = base b_target = int(parse(asm)[1][0].split('_')[1], 16) regs, affected = div_targets.get(off, (set(), set())) regs = {r for r in regs if isinstance(r, int)} if b_target <= off: + self.divergent_back_edges.append((b_target, off)) regs.update(r for r in joined.get(b_target, ()) if isinstance(r, int)) for tgt_off in affected: bad_at_target.setdefault(tgt_off, set()).update(regs) term = self.one(name, asm) if off in wave_limits: term = ('branch', '(tid & ~63u) >= %du' % wave_limits[off], term[2]) + if off in wave_loads: + term = ('branch', '!wave_any', term[2]) except Unsupported as reason: if refusals is None: + if self.has_branches and ('read_vcc', None) in self.vcc_events.get(off, ()): + # Some operand handlers refuse VCC before emitting code. Check whether + # a path to this instruction has already overwritten the mask. + self.blocks.append((start, self.lines, None)) + try: + self.check_vcc_paths() + except Unsupported as vcc_reason: + reason = vcc_reason + finally: + self.blocks.pop() if not hasattr(reason, 'instruction'): reason.instruction = name # for fail_reason(); the message itself is unchanged raised_unsupported = reason @@ -2679,8 +4391,14 @@ def translate(self): continue # A write proves the mark again: every path from here on runs it. s_movreld can write any SGPR. self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests + if not self.scc_effect and ('scc' in scalar_effects(name, asm)[1] or name.startswith(('s_wqm', 's_quadmask'))): + # The guest wrote SCC and the lowering emitted nothing for it: a later reader would see an older + # value (descriptor_scc_reads follows every path from here to the reader). + self.scc_effect = 'an SCC write that is not modelled' if self.scc_effect: scc_effects[off] = self.scc_effect + if self.scc_effect or not self.scc_verified: + self.scc_def = off if self.scc_effect == 'emitted' and self.scc_verified and self.scc_uniform else None if term: self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, term)) @@ -2706,6 +4424,18 @@ def translate(self): refusals.append((reason, self.kind)) if self.lines: self.blocks.append((start, self.lines, None)) + for at, reason in self.quad_flow_refusals(branches, targets): + if refusals is None: + error = Unsupported(reason) + error.instruction = names[at] + raise error + refusals.append((reason, self.kind)) + for at, reason in self.wave_reduce_branch_refusals(): + if refusals is None: + error = Unsupported(reason) + error.instruction = names[at] + raise error + refusals.append((reason, self.kind)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) if set(scc_effects.values()) - {'emitted'}: for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): @@ -2713,6 +4443,16 @@ def translate(self): if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) + for at, name in self.derivative_sites: + # A divergent back edge that spans the call lets lanes of one quad leave the loop at different passes, so + # the call runs again with uneven quads even though no divergent branch precedes it in program order. + if any(target <= at <= branch for target, branch in self.divergent_back_edges): + reason = ('%s needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform ' + 'control flow' % name) + if refusals is None: + raise Unsupported(reason) + refusals.append((reason, self.kind)) + self.resolve_plain_samples() self.pinned_low16_v.update(self.low16_only_v) try: self.check_vcc_paths() @@ -2738,7 +4478,8 @@ def descriptor_scc_reads(self, branches, effects): continue seen.add((off, stale)) size, name, asm = instructions[off] - if stale and off not in self.calculated_pc and reads_scc(name, asm): + if (stale and off not in self.calculated_pc and off not in getattr(self, 'ptr_addc_pcs', ()) + and reads_scc(name, asm)): yield stale, name if off in effects: stale = effects[off] if effects[off] != 'emitted' else None @@ -2771,6 +4512,194 @@ def join_writes(self, branches): def tracks_uniformity(self): return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform')) + def vgpr_writer(self, reg, before, after=-1): + """Index of the last instruction in self.ins[after + 1:before] that may write VGPR reg (the first operand, + and the second of v_swap_b32), or None.""" + for i in range(before - 1, after, -1): + _, _, name, asm = self.ins[i] + ops = parse(asm)[1] + for tok in (ops[:2] if name.startswith('v_swap') else ops[:1]): + r = reg_range(tok) + if r and r[0] == 'v' and r[1] <= reg <= r[2]: + return i + return None + + def tid_shift(self, count, source): + """The uniform expression of `v_lshrrev_b32 vD, count, source` in the entry block of a compute program, or None. + + The X thread id (v0, each local id has its own VGPR) is below the group's X size, so a right shift by n with + size <= 1 << n clears every thread-id bit. That gives 0 for the thread id itself, and for a vector built as + (uniform << K) + v0 with n <= K and size <= 1 << K the low K bits of the base are clear, the sum does not + carry, and the result is the same in every lane. Program order is execution order here, so the nearest + earlier writer is the definition; v0 must be unwritten at the definition and the scalar unwritten after it.""" + src, now = reg_range(source), self.pc_index() + if (not re.fullmatch(r'0x[0-9a-f]+|\d+', count) or int(count, 0) >= 32 or not src or src[0] != 'v' or + src[1] != src[2] or now is None): + return None + group = getattr(self.pipe, 'group', None) + if not group or group[0] <= 0: + return None + n, size = int(count, 0), group[0] + defined = self.vgpr_writer(src[1], now) + if defined is None: + return '0u' if src[1] == 0 and size <= 1 << n else None + _, _, name, asm = self.ins[defined] + _, d, mods = parse(asm) + base = re.sub(r'_e(32|64)$', '', name) + if (base not in ('v_lshl_add_u32', 'v_and_or_b32', 'v_bfe_u32') or mods or len(d) != 4 or + self.vgpr_writer(0, defined) is not None or not re.fullmatch(r'0x[0-9a-f]+|\d+', d[2])): + return None + imm = int(d[2], 0) + # The local id is in [0, size). These are all the bits that may vary before the shift. + tid_bits = (1 << (size - 1).bit_length()) - 1 + if base == 'v_bfe_u32': + if d[1] != 'v0' or imm >= 32 or not re.fullmatch(r'0x[0-9a-f]+|\d+', d[3]): + return None + width = int(d[3], 0) + if width >= 32 or (((tid_bits >> imm) & ((1 << width) - 1)) >> n): + return None + return '0u' + if base == 'v_and_or_b32': + if d[1] != 'v0' or imm > 0xffffffff or ((tid_bits & imm) >> n): + return None + scalar_token = d[3] + else: + if d[3] != 'v0' or imm >= 32 or n > imm or size > 1 << n: + return None + scalar_token = d[1] + scalar = reg_range(scalar_token) + if (not scalar or scalar[0] != 's' or scalar[1] != scalar[2] or scalar[1] > 105 or + not self.uniform_source(scalar_token)): + return None + for _, _, later, later_asm in self.ins[defined + 1:now]: + writes = scalar_destinations(later, later_asm) + if scalar[1] in writes or 'any' in writes: + return None + if base == 'v_and_or_b32': + return '(%s >> %du)' % (self.S(scalar[1]), n) + return '((s%d << %du) >> %du)' % (scalar[1], imm, n) + + def pc_index(self): + return next((i for i, ins in enumerate(self.ins) if ins[0] == self.pc), None) + + def helper_off_copy(self, tok, sym): + """Whether `tok` is a copy of EXEC saved before an `s_wqm_b64 exec, exec`: the guest's entry EXEC leaves the + helper lanes off, while every thread here starts with exec = 1, so writing it back would turn the guest's helper + lanes off (stale VGPRs) and keep the translation's on.""" + r = reg_range(tok) + return bool(r and r[0] == 's' and sym == ('execcopy',) + and getattr(self, 'execcopy_epoch', {}).get(r[1], 0) < getattr(self, 'wqm_count', 0)) + + def exec_write_exact(self, srcs, syms): + """Whether a scalar EXEC write takes every source from a lane mask (vcc, exec, a saved EXEC or a tagged mask) or + from the all-zero / all-ones constants: then each lane's bit is the guest's. Any other source (a mask built + from a number such as 1) selects guest lanes the one-lane model cannot tell apart.""" + for tok, sym in zip(srcs, syms): + r = reg_range(tok) + if self.helper_off_copy(tok, sym): + return False + # The 64-bit forms only (see also the exec_lo destination at the call site): in wave64 a 32-bit write + # (s_mov_b32 exec_lo, vcc_lo) keeps the old bits of lanes 32..63, while the model sets every lane. + if tok in ('exec', 'vcc') or sym == ('execcopy',) or ( + r and r[0] == 's' and r[1] in getattr(self, 'masks', ())): + continue + try: + if int(tok, 0) in (0, -1, 0xffffffff, 0xffffffffffffffff): + continue + except ValueError: + pass + return False + return True + + def skipped_block_vector_only(self, branch, target): + """Whether the instructions a forward EXEC branch can skip are per-lane vector work only. + + The guest takes the branch once for the whole wave, so a scalar write, a mask write or a branch inside the block + happens once for the wave when any quad takes the block. A quad that votes to skip it would miss that effect while + a later read in the same wave sees it. Only vector ALU/memory/export instructions and waits, which each lane + applies to its own registers, are allowed between the branch and its target; s_endpgm too (a quad that ends + reads nothing later).""" + if target <= branch: + return False + for off, _n, name, asm in self.ins: + if not branch < off < target: + continue + if name == 's_endpgm': + # A quad that ends reads nothing later, unless later code can turn it back on: an EXEC write after the + # branch (a restore of a saved mask) would reactivate every quad of the guest wave. + if any(o > branch and writes_exec(n, parse(a)[1]) for o, _s, n, a in self.ins): + return False + continue + if not (self.vector_only_instruction(name, asm) + or name.startswith(('image_', 'buffer_', 'tbuffer_', 'global_', 'flat_', 'exp')) + or name in ('s_waitcnt', 's_nop', 's_waitcnt_vscnt')): + return False + return True + + @staticmethod + def vector_only_instruction(name, asm): + """A vector ALU instruction whose only destination is a VGPR: no SGPR, VCC or EXEC write (a carry-out, a compare, + a readlane), which the guest performs once for the whole wave.""" + if not name.startswith('v_') or name.startswith(('v_cmp', 'v_readlane', 'v_readfirstlane', 'v_writelane', + 'v_div_scale', 'v_mad_u64', 'v_mad_i64')): + return False + if re.match(r'v_(add|sub|subrev)_co|v_addc|v_subb', name): + return False + for tok in destinations(name, parse(asm)[1]): + r = reg_range(tok) + if tok in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0') or (r and r[0] == 's'): + return False + return True + + def uniform_bias(self, tok): + """Whether a VGPR holds one value in every lane at the op: its last earlier write is a v_mov_b32 of a constant + that every lane ran (no EXEC write and no branch before it, so no lane skipped it and the other lanes keep an + older value). No backward branch exists in a quad program, so later writes cannot reach the op.""" + r = reg_range(tok) + if not r or r[0] != 'v' or r[1] != r[2]: + return False + last = None + for off, _n, name, asm in self.ins: + if off >= self.pc: + break + ops = parse(asm)[1] + first = reg_range(ops[0]) if ops else None + if first and first[0] == 'v' and first[1] <= r[1] <= first[2]: + const = (re.sub(r'_e(32|64)$', '', name) == 'v_mov_b32' and len(ops) == 2 and not reg_range(ops[1])) + last = off if const else None + if last is None: + return False + narrowed = 0 + for off, _n, name, asm in self.ins: + if off >= last: + break + base = re.sub(r'_e(32|64)$', '', name) + ops = parse(asm)[1] + if name.startswith('s_cbranch') or name == 's_branch': + target = int(ops[0].split('_')[1], 16) if '_' in ops[0] else None + if target is None or target > last: + return False # the write can be skipped by some lanes + elif base in ('s_or_b64', 's_or_b32') and ops[:2] in (['exec', 'exec'], ['exec_lo', 'exec_lo']): + narrowed = max(narrowed - 1, 0) # the restore that ends a saveexec region + elif base.startswith('s_and_saveexec') or (base.startswith('s_wqm') and ops[:2] not in (['exec', 'exec'], ['exec_lo', 'exec_lo'])): + narrowed += 1 + elif writes_exec(name, ops) and not (base.startswith('s_wqm') and ops[:2] in (['exec', 'exec'], ['exec_lo', 'exec_lo'])): + return False + return narrowed == 0 + + def derivative_exec_ok(self): + """Whether an implicit-derivative op may rely on the EXEC the lanes hold here. + + At the entry mask every lane runs the call. Past an EXEC write (v_cmpx, saveexec, a restore) the one-lane + model still follows the guest's bit of each lane exactly (EXEC is written per lane, set_v is EXEC guarded), + so a quad program (a pixel program with a derivative op and no backward branch) is proven as long as no + lane-exec break happened: an s_wqm of a narrowed EXEC (a no-op here, while the guest turns on the lanes of + every touched quad) or a discard under an unknown EXEC. The callers also need uniform_cf, which a branch + that parts a quad clears; an EXEC branch decided per quad (quad_vote) does not.""" + # A restored pre-s_wqm mask (helper_restore) is the entry mask, but the guest's helper lanes are off from here. + return ((self.exec_known and not getattr(self, 'helper_restore', False)) + or (getattr(self, 'quad_exec', False) and not getattr(self, 'lane_exec_breaks', None))) + def uniform_source(self, tok): r = reg_range(tok) if r: @@ -2787,7 +4716,7 @@ def uniform_source(self, tok): if sym: return sym[0] in ('const', 'ud', 'fixed_buffer_word') return lo not in self.varying_s - if tok in FLOATS: + if tok == 'null' or tok in FLOATS: return True try: int(tok, 0) @@ -2795,9 +4724,90 @@ def uniform_source(self, tok): return False return True + def uniform_image_load_regs(self, base, ops, mods): + """Return the range of destination VGPRs written uniformly by `image_load`, or () when unproved.""" + if (base not in UNIFORM_IMAGE_LOADS or len(ops) < 3 or not self.tracks_uniformity() or + getattr(self, 'kind', None) != 'cs' or not getattr(self, 'exec_known', False) or + getattr(self, 'has_image_writes', True)): + return () + past_entry = getattr(self, 'past_entry', None) + if past_entry is None or (past_entry and (getattr(self, 'uniform_expr', None) is None or + self.pc in getattr(self, 'loads_after_exec_write', ()))): + return () + rsrc = reg_range(ops[2]) + first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 7 and rsrc[2] <= 105 else None + if (not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or + first[3] % 8 or not names_one_value(first)): + return () + masks = getattr(self, 'masks', ()) + varying_s = getattr(self, 'varying_s', ()) + modified = getattr(self.pipe, 'modified', ()) + other_modified = getattr(self.pipe, 'other_modified', ()) + stored = self.pipe.stored_images() if hasattr(self.pipe, 'stored_images') else (getattr(self.pipe, 'uavs', None) or ()) + key = desc_key(first) + if key in modified or key in other_modified or key in stored: + return () + for i in range(8): + reg = rsrc[1] + i + word = desc_word(first, first[3] + i) + if (reg in masks or reg in varying_s or self.sym.get(reg) != word or + desc_key(word) in modified): + return () + dims = [m for m in mods if m.startswith('dim:')] + dmasks = [m for m in mods if m.startswith('dmask:')] + if len(dims) != 1 or len(dmasks) != 1: + return () + dim = dims[0][4:] + if dim not in ('SQ_RSRC_IMG_2D', 'SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY'): + return () + try: + dmask = int(dmasks[0][6:], 0) + except ValueError: + return () + if not dmask or (dmask & ~0xf): + return () + packed_2d = base == 'image_load' and dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods + allowed = ('unorm', 'glc', 'slc', 'dlc') + (('a16',) if packed_2d else ()) + if any(not m.startswith(('dim:', 'dmask:')) and m not in allowed for m in mods): + return () + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + if not r or r[0] != 'v': + return () + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] + axes = 3 if dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY') else 2 + expected_addr = 1 if packed_2d else (axes + 1 if base == 'image_load_mip' else axes) + if len(cs) != expected_addr: + return () + if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 and self.uniform_source(c) for c in cs): + return () + candidate = reg_range(ops[0]) + count = bin(dmask).count('1') + if not candidate or candidate[0] != 'v' or candidate[2] > 255 or candidate[2] - candidate[1] + 1 != count: + return () + return range(candidate[1], candidate[2] + 1) + def one(self, name, asm): _, ops, mods = parse(asm) - if name.endswith('_e32') and name[:-4] in VOP3_ONLY_VEC_U: + if (getattr(self, 'vcc_lost', False) or + (getattr(self, 'has_branches', False) and + ('vcc' in asm or name.startswith(IMPLICIT_VCC_READ)))): + # Read operands even in handlers that refuse a mask as numeric data before calling u(). + # VOPC's two-operand spelling has an implicit destination, and v_cmpx e64 prints an unused SDST. + if name.startswith('v_cmpx') and name.endswith('_e64') and len(ops) == 3: + reads = scalar_tokens(' '.join(ops[1:])) + elif name.startswith('v_cmp') and len(ops) == 2: + reads = scalar_tokens(' '.join(ops)) + else: + reads, _, _ = scalar_effects(name, asm) + if reads & {'vcc', 'vcc_hi'}: + self.read_vcc() + # v_bfm_b32 and v_ldexp_f32 exist only as VOP3; a VOP2 spelling is not an instruction. + if name.endswith('_e32') and (name[:-4] in VOP3_ONLY_VEC_U + or name[:-4] in ('v_bfm_b32', 'v_ldexp_f32', 'v_add_nc_i32', 'v_sub_nc_i32')): raise Unsupported(name) base = re.sub(r'_e(32|64)$', '', name) # Compute the proof before lowering, since a destination can also be a source. @@ -2814,7 +4824,8 @@ def one(self, name, asm): (getattr(self, 'past_entry', False) and hasattr(self, 'uniform_expr') or not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False)) and (not mods or (base in VEC_F or base in VEC_U_TO_F) and - all(m in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods))): + all(m in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods) or + base in ('v_add_nc_i32', 'v_sub_nc_i32') and mods == ['clamp'])): candidate = reg_range(ops[0]) if candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: sources = ops[1:] @@ -2822,8 +4833,64 @@ def one(self, name, asm): sources = [re.sub(r'^-(?=[^\d.])', '', tok).strip('|') for tok in sources] if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] + # A compute load through a read-only descriptor (a descriptor is never both loaded and stored) with a uniform + # address reads the same dword in every lane. In the entry block with known exec every lane ran it. + load_form = (dst is None and base in UNIFORM_LOADS and len(ops) == 4 and self.tracks_uniformity() and + getattr(self, 'kind', None) == 'cs' and + all(m in ('idxen', 'offen', 'glc', 'slc', 'dlc') or m.startswith('offset:') for m in mods) and + not ('idxen' in mods and 'offen' in mods) and (ops[1] == 'off') == ('idxen' not in mods and 'offen' not in mods) and + (ops[1] == 'off' or self.uniform_source(ops[1])) and self.uniform_source(ops[3])) + loaded = load_form and not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False) + # With empty EXEC, READFIRSTLANE uses the old VGPR in lane zero. An unguarded reload + # cannot reproduce it. Require the entry mask until the path proves a nonempty wave. + vaddr = reg_range(ops[1]) if load_form and ops[1] != 'off' else None + exprs = getattr(self, 'uniform_expr', None) + recomputed = (load_form and getattr(self, 'past_entry', False) and exprs is not None + and getattr(self, 'exec_known', False) and self.pc not in self.loads_after_exec_write) + loaded_regs = () + if loaded or recomputed: + candidate = reg_range(ops[0]) + # Exactly the registers the opcode writes, as many as its name says. + count = UNIFORM_LOAD_WORDS[base] + if candidate and candidate[0] == 'v' and candidate[2] <= 255 and candidate[2] - candidate[1] + 1 == count: + dst, loaded_regs = candidate[1], range(candidate[1], candidate[2] + 1) + else: + loaded = recomputed = False + if dst is None: + img_regs = self.uniform_image_load_regs(base, ops, mods) + if img_regs: + dst, loaded_regs = img_regs.start, img_regs + loaded = not getattr(self, 'past_entry', True) + recomputed = getattr(self, 'past_entry', False) + # A shift right of a value built from the X thread id that leaves no thread-id bit. + shifted = None + if (dst is None and base == 'v_lshrrev_b32' and not mods and len(ops) == 3 and + self.tracks_uniformity() and hasattr(self, 'uniform_expr') and getattr(self, 'kind', None) == 'cs' and + not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False)): + candidate = reg_range(ops[0]) + shifted = self.tid_shift(ops[1], ops[2]) + if shifted is not None and candidate and candidate[0] == 'v' and candidate[1] == candidate[2]: + dst = candidate[1] + else: + shifted = None + if recomputed: + # Read before the load can overwrite its own address register. + self.uniform_vaddr = '(%s)' % exprs[vaddr[1]] if vaddr and vaddr[1] in exprs else None + self.uniform_temps = {} self.last_v = None - term = self.lower(base, asm, ops, mods) + if hasattr(self, 'heap_index'): # unit probes build a Stage without the tracking state + # Any write ends a register's mark; the lowering below sets the new one, if any. + wrote = scalar_destinations(name, asm) + wrote_h = set(self.heap_index) if 'any' in wrote else wrote & set(self.heap_index) + self.heap_index_was = {r: self.heap_index.pop(r) for r in wrote_h} + pl = getattr(self, 'per_lane_index', {}) + wrote_p = set(pl) if 'any' in wrote else wrote & set(pl) + self.per_lane_index_was = {r: pl.pop(r) for r in wrote_p} + try: + term = self.lower(base, asm, ops, mods) + finally: + temps = getattr(self, 'uniform_temps', None) + self.uniform_vaddr = self.uniform_temps = None uniform_written = self._uniform_written if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: self.since_join -= (wrote_s - uniform_written) @@ -2837,18 +4904,100 @@ def one(self, name, asm): self.defined_uniform_s.discard(r) self.bad_sgprs.add(r) if dst is not None: - self.uniform_v.add(dst) + self.uniform_v.update(loaded_regs or (dst,)) + for reg in loaded_regs: + getattr(self, 'uniform_expr', {}).pop(reg, None) if hasattr(self, 'uniform_expr'): # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] - if expr is None or any(n not in self.uniform_expr for n in vs): + if shifted is not None: + self.uniform_expr[dst] = shifted + elif expr is None or loaded_regs or any(n not in self.uniform_expr for n in vs): + self.uniform_expr.pop(dst, None) + elif sum(len(self.uniform_expr[n]) for n in vs) > UNIFORM_EXPR_LIMIT: + # A VGPR used as both operands (v10 = v10 + v10) doubles the text each time: past the limit the + # chain has no recomputable expression, so a first-lane read of it is refused. self.uniform_expr.pop(dst, None) else: self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], expr) + if recomputed: + self.uniform_expr.update(temps) return term + def quad_flow_straight(self): + """Whether a DPP quad read sits in straight-line code (the quad intrinsics then run in uniform flow).""" + return not getattr(self, 'has_branches', True) and not getattr(self, 'blocks', []) + + def quad_flow_allowed(self): + """Whether a DPP quad read in a pixel program with branches or loops may be lowered now and proven over the + whole program after translation (Stage.quad_flow_refusals). Unit probes without translate() cannot.""" + return getattr(self, 'kind', None) == 'ps' and getattr(self, 'quad_flow_reads', None) is not None + + def note_quad_flow(self, base): + if not self.quad_flow_straight() and getattr(self, 'quad_flow_reads', None) is not None: + self.quad_flow_reads.append((self.pc, base)) + + def quad_flow_refusals(self, branches, targets): + """[(offset, reason)] for DPP quad reads lowered in a pixel program with branches or loops. + + The one-lane model runs each lane as its own HLSL thread through the pc dispatch, so the QuadReadLaneAt / + QuadReadAcross* of a lane reads its neighbours only when all four threads of the quad reach that statement + together (same block, same pass of the dispatch loop) with the word the guest lanes hold. The guest runs + the wave as one: its scalar branches are wave-wide, and the quad is whole when EXEC is the s_wqm mask. A + read is kept when, on every path to it: + - the s_wqm exec, exec that proved whole-quad EXEC ran first: it sits before every branch and target; + - no other instruction that can write EXEC reaches it (so EXEC is still that mask and every VGPR write ran + on all four lanes, helper lanes included); + - every conditional branch that reaches it is wave-uniform (SCC proven uniform by the translator), or an + execz/execnz branch, whose EXEC is the whole-quad mask by the rule above and so never taken. A vccz/vccnz + branch, or SCC from lane data, can split a quad, and the read is refused. + Then the four threads ran the same branch outcomes, so they are in the same block on the same dispatch + pass. No wave size is assumed: the SM 6.0 quad operations need only the 2x2 quad of four lanes.""" + reads = getattr(self, 'quad_flow_reads', []) + if not reads: + return [] + index, block_of, succ, _dom, _writes, _reached = self.flow + after = {} + + def reaches(src, dst): + a, b = index[src], index[dst] + if block_of[a] == block_of[b] and a < b: + return True + start = block_of[a] + if start not in after: + seen, todo = set(), list(succ[start]) + while todo: + blk = todo.pop() + if blk not in seen: + seen.add(blk) + todo += succ[blk] + after[start] = seen + return block_of[b] in after[start] + # No branch or target (a dead read behind an early s_endpgm): nothing for the s_wqm to precede. + first = min([off for off, _ in branches] + list(targets), default=float('inf')) + writers = [off for off, _n, name, asm in self.ins if writes_exec(name, parse(asm)[1]) + and not (re.sub(r'_e(32|64)$', '', name) in ('s_wqm_b32', 's_wqm_b64') + and parse(asm)[1] in (['exec', 'exec'], ['exec_lo', 'exec_lo']))] + out = [] + for at, base in reads: + if self.wqm_set_at is None or self.wqm_set_at >= first: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: the s_wqm exec, exec does not ' + 'run before every branch' % (base, at))) + continue + writer = next((w for w in writers if reaches(w, at)), None) + if writer is not None: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: the EXEC write at +0x%x reaches ' + 'it' % (base, at, writer))) + continue + split = next((b for b, name in sorted(self.divergent_branches.items()) + if name not in ('s_cbranch_execz', 's_cbranch_execnz') and reaches(b, at)), None) + if split is not None: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: %s at +0x%x is not proven ' + 'wave-uniform' % (base, at, self.divergent_branches[split], split))) + return out + def dpp_pair(self, base, asm, ops, mods): """A DPP16 spelling whose SRC0 is a quad pair broadcast (#2125 item C). @@ -2872,7 +5021,7 @@ def dpp_pair(self, base, asm, ops, mods): perm = tuple(int(c) for c in re.findall(r'\d', perms[0])) if perm not in DPP_PAIR: raise Unsupported('%s_dpp with %s' % (base, perms[0])) - if (self.kind != 'ps' or getattr(self, 'has_branches', True) or not getattr(self, 'exec_known', False) or + if (self.kind != 'ps' or not (self.quad_flow_straight() or self.quad_flow_allowed()) or not getattr(self, 'exec_known', False) or not getattr(self, 'wqm_exec', False) or getattr(self, 'fetched', False)): raise Unsupported('%s_dpp %s outside straight-line pixel code with a whole-quad exec mask (s_wqm exec, exec)' % (base, perms[0])) @@ -2884,9 +5033,12 @@ def dpp_pair(self, base, asm, ops, mods): if not src: raise Unsupported('%s_dpp source %s' % (base, ops[1])) word = self.u('v%s' % src.group(2)) # records the original source as a used VGPR + self.note_quad_flow(base) self.needs_sm6 = True self.used_v.add(DPP_SCRATCH) self.uniform_v.discard(DPP_SCRATCH) + if isinstance(self.align4_v, set): + self.align4_v.discard(DPP_SCRATCH) self.emit('{ uint x2w_q0 = QuadReadLaneAt(%s, 0), x2w_q1 = QuadReadLaneAt(%s, 1),' ' x2w_q2 = QuadReadLaneAt(%s, 2), x2w_q3 = QuadReadLaneAt(%s, 3);' ' uint x2w_lane = ((uint(i.pos.y) & 1u) << 1u) | (uint(i.pos.x) & 1u);' @@ -2915,7 +5067,125 @@ def forget_writes(self, name, ops, drop_since=True): del self.uniform_expr[v] return regs + MASK_NAMES_LOW = ('vcc', 'vcc_lo', 'exec', 'exec_lo') + MASK_NAMES_HIGH = ('vcc', 'vcc_hi', 'exec', 'exec_hi') + + def mask_source_tags(self, base, ops): + """(low, high): whether a source operand of the instruction carries a lane-mask word. low = a mask's low word + (vcc/exec, an SGPR in self.masks, a pair that starts in one); high = the high word of a wave64 mask (vcc_hi, + exec_hi, a pair holding one, an SGPR in self.mask_high). Read before the instruction runs: it may overwrite + its own source.""" + dests = destinations(base, ops) + srcs = ops[len(dests):] if dests and ops[:len(dests)] == dests else list(ops) + masks, high_regs = getattr(self, 'masks', ()), getattr(self, 'mask_high', ()) + low = high = False + for tok in (t.strip().lstrip('-|').rstrip('|') for t in srcs): + low |= tok in self.MASK_NAMES_LOW + high |= tok in self.MASK_NAMES_HIGH and tok not in ('vcc_lo', 'exec_lo') + r = reg_range(tok) + if r and r[0] == 's': + start_tagged = r[1] in masks + low |= start_tagged + high |= any(n in high_regs for n in range(r[1], r[2] + 1)) or (start_tagged and r[2] > r[1]) + return low, high + + def propagate_mask_tags(self, base, ops, tags): + """After an instruction ran: the SGPRs it wrote carry the lane-mask tag of what they were made from. This is the one + place the tag moves. A compare or carry writes its single-word mask itself (the decoder + names a wave64 compare destination s0, not s[0:1]); a mask-only scalar op (mov, bitwise, cselect, saveexec) + copies the tag of its sources to its destination, both words of a b64 pair; any other write cleared the tag + already (set_s). self.masks holds the low word, self.mask_high the high word of a wave64 pair: no numeric read of + either is lowered (lower()).""" + low, high = tags + self.tag_compare_pair(base, ops) + saveexec = base.startswith('s_') and 'saveexec' in base + if MASK_COPY_SALU_RE.match(base) and not base.startswith('s_wqm') and not (low or high): + # (s_wqm is a no-op in _lower(): it writes nothing, so the old mask stays in its destination.) + # a 32-bit copy of plain data: the destination no longer holds a lane mask, whatever an earlier path or join + # left. A 64-bit pair copy keeps its tag: scalar() lowers every b64 move as a mask copy (the lane bit only), + # so the truncated word must stay refused as numeric data. + for tok in destinations(base, ops): + r = reg_range(tok) + if r and r[0] == 's' and r[2] == r[1]: + self.masks.discard(r[1]) + scalar = bool(MASK_COPY_SALU_RE.match(base)) and (low or high) + pair_select = base.startswith('s_cselect') and base.endswith('b64') + if not (saveexec or scalar or pair_select): + return + for tok in destinations(base, ops): + r = reg_range(tok) + if not r or r[0] != 's': + continue + if r[2] > r[1]: # a pair: low word, and the high word it carries + self.masks.add(r[1]) + self.mask_high = getattr(self, 'mask_high', set()) | {r[1] + 1} + elif low or saveexec or pair_select: + self.masks.add(r[1]) + if r[2] == r[1] and high and not (saveexec or pair_select): + self.mask_high = getattr(self, 'mask_high', set()) | {r[1]} + + def tag_compare_pair(self, base, ops): + """A compare or carry-out into SGPR sN (the decoder prints a wave64 pair as s[N:N+1] by its low word only). In + wave64 the destination is an even-aligned pair and s(N+1) holds the other 32 lanes, which no one-lane value + has: tag s(N+1) as the high word. An odd sN is a wave32 destination (no high word); an even one that is a wave32 + destination loses the numeric reads of s(N+1), a refusal and never a wrong value. If s(N+1) already holds its own lane + mask (a wave32 compare or carry in the neighbouring register) the destination is not a pair: nothing is tagged.""" + if base.startswith('v_cmp') and not base.startswith('v_cmpx'): + tok = ops[0] if ops else '' + elif VOP3B_SDST.match(base) and len(ops) > 1: + tok = ops[1] + else: + return + r = reg_range(tok.strip()) + if r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks and r[1] % 2 == 0 and r[1] + 1 not in self.masks: + self.mask_high = getattr(self, 'mask_high', set()) | {r[1] + 1} + + def lane_mask_exact(self): + """True where the one-lane model of a wave mask is exact: a compute group of one thread has one participating lane + per wave, so the lane's bit is the whole mask and its high word is 0. Anywhere else the mask holds other lanes' + bits that a numeric read would see.""" + group = getattr(getattr(self, 'pipe', None), 'group', None) + return getattr(self, 'kind', None) == 'cs' and bool(group) and group[0] * group[1] * group[2] == 1 + + def reads_mask_high(self, toks): + """First single-register operand that is the high word of a wave64 lane mask, else None.""" + high = getattr(self, 'mask_high', ()) + for t in toks: + r = reg_range(t.strip().lstrip('-|').rstrip('|')) + if r and r[0] == 's' and r[1] == r[2] and r[1] in high: + return t.strip() + return None + def lower(self, base, asm, ops, mods): + """Lower one instruction; a vector ALU form that reads a lane mask as a number is refused. + + The model keeps one lane's bit of a wave mask. A vector ALU source that reads the mask as a number (the + llvm.amdgcn.ballot word) sees every lane's bit on hardware, so the lowered word would be silently wrong. + The mask-aware forms (select, carry, readlane) and v_mov_b32 (which the readfirstlane proofs handle) pass. + The check runs after the form's own refusals, so those keep their messages.""" + if self.wave_reduction(base, ops): + return None + masks = [] + if base.startswith('v_') and not base.startswith('v_mov_b32') and base not in MASK_AWARE_VALU and not MASK_AWARE_VALU_RE.search(base): + masks = [t for t in (o.strip().lstrip('-|').rstrip('|') for o in ops[1:]) if self.is_lane_mask(t)] + if base.startswith('s_') and not MASK_AWARE_SALU_RE.match(base): + masks = [t for t in (ops if base.startswith(('s_cmp', 's_bitcmp')) else ops[1:]) if self.is_lane_mask(t.strip())] + if base.startswith(('v_', 's_')) and not masks: # the high word of a wave64 mask has no one-lane value + skip = 2 if VOP3B_SDST.match(base) else 1 # the carry-out of a VOP3b form is a destination, not a read + high = self.reads_mask_high(ops if base.startswith(('s_cmp', 's_bitcmp')) else ops[skip:]) + masks = [high] if high else [] + tags = self.mask_source_tags(base, ops) + result = self._lower(base, asm, ops, mods) + for tok in destinations(base, ops): # an overwritten register no longer holds a mask's high word + r = reg_range(tok) + if r and r[0] == 's': + getattr(self, 'mask_high', set()).difference_update(range(r[1], r[2] + 1)) + if masks and not self.lane_mask_exact(): + raise Unsupported('%s reads lane mask %s as numeric data' % (base, masks[0])) + self.propagate_mask_tags(base, ops, tags) + return result + + def _lower(self, base, asm, ops, mods): pc = getattr(self, 'pc', None) calculated = getattr(self, 'calculated_pc', {}) if pc in calculated: @@ -2928,9 +5198,12 @@ def lower(self, base, asm, ops, mods): for reg in scalar_registers(ops[0]): self.sym.pop(reg, None) self.masks.discard(reg) + if isinstance(self.align4_s, set): + self.align4_s.discard(reg) self.varying_s.add(reg) if base in ('s_add_u32', 's_addc_u32'): self.scc_uniform = False + self.scc_verified = False return None if getattr(self, 'fetched', False): # unit probes build a Stage without __init__ # Behind a fetch call the definite-assignment guard relies on exec_known: every exec write must clear it. @@ -2945,10 +5218,20 @@ def lower(self, base, asm, ops, mods): if base in ('s_wqm_b32', 's_wqm_b64'): if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False): self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included + self.wqm_count = getattr(self, 'wqm_count', 0) + 1 + if getattr(self, 'wqm_set_at', False) is None: + self.wqm_set_at = getattr(self, 'pc', None) # where the quad-read flow proof starts + elif hasattr(self, 'lane_exec_breaks'): + # Any other s_wqm is a no-op here, while the guest turns on the inactive lanes of every touched quad + # (or writes a whole-quad mask somewhere): a lane's EXEC bit may be 0 where the guest's is 1. + self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) if hasattr(self, 'uniform_v'): self.uniform_v.clear() + if isinstance(self.align4_v, set): + self.align4_v.clear() if hasattr(self, 'scc_uniform'): self.scc_uniform = False # the hardware SCC result is not modelled + self.scc_verified = False return None if base == 's_setreg_imm32_b32': # The write itself changes nothing the lowering models, except MODE[1:0] (the binary32 rounding mode): @@ -2999,6 +5282,11 @@ def lower(self, base, asm, ops, mods): raise Unsupported('slot 57 mesh: a branch reads SCC that is not proven wave-uniform') cond = {'scc0': '!scc', 'scc1': 'scc', 'vccz': '(vcc & 1) == 0', 'vccnz': '(vcc & 1) != 0', 'execz': '(exec & 1) == 0', 'execnz': '(exec & 1) != 0'}[base[10:]] + if base[10:] in ('execz', 'execnz') and getattr(self, 'pc', None) in getattr(self, 'voted_branches', ()): + # The wave skips the block only when no lane is active; a quad with an active lane runs it whole, its + # other lanes masked (their VGPRs kept for the derivatives, writes guarded by EXEC), as the guest does. + self.uses_quad_vote = True + cond = ('!' if base.endswith('execz') else '') + 'x2w_quad_any(exec)' return ('branch', cond, int(ops[0].split('_')[1], 16)) if base == 'exp': return self.export(asm) @@ -3051,6 +5339,8 @@ def lower(self, base, asm, ops, mods): return self.dpp(base[:-len('_dpp')], ops, mods) handler = getattr(self, 'op_' + base, None) if handler: + if mods and handler.__name__ in MODIFIER_FREE_HANDLERS: + raise Unsupported('%s with %s' % (base, mods)) return handler(ops, mods) if base in MUBUF_ATOMIC_OPS: return self.buffer_atomic(base, ops, mods) @@ -3105,7 +5395,7 @@ def lower(self, base, asm, ops, mods): if sr is not None: if sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105): raise Unsupported('%s source %s' % (base, src)) - elif src not in FLOATS and src != 'm0': + elif src not in FLOATS and src not in ('m0', 'null'): try: val = int(src, 0) except ValueError: @@ -3116,15 +5406,39 @@ def lower(self, base, asm, ops, mods): c0, c1 = self.const_u32(ops[1]), self.const_u32(ops[2]) args = [self.u(ops[1], low16_only=c1 is not None and (c1 & 0xffff0000) == 0), self.u(ops[2], low16_only=c0 is not None and (c0 & 0xffff0000) == 0)] + elif base in ('v_mad_u32_u16', 'v_mad_i32_i16'): + # S0 and S1 read only bits [15:0]; S2 reads all 32 bits. + args = [self.u(ops[1], low16_only=True), + self.u(ops[2], low16_only=True), + self.u(ops[3])] else: args = [self.u(o) for o in ops[1:1 + arity]] - if base in ('v_sad_u8', 'v_sad_u16', 'v_sad_u32'): + if base in ('v_sad_u8', 'v_sad_hi_u8', 'v_sad_u16', 'v_sad_u32', 'v_msad_u8'): pipe = getattr(self, 'pipe', None) if pipe is not None and isinstance(getattr(pipe, 'uses_sad', None), set): pipe.uses_sad.add(base) - return self.set_v(reg_range(ops[0])[1], text.format(*args)) + elif base == 'v_lerp_u8': + pipe = getattr(self, 'pipe', None) + if pipe is not None and hasattr(pipe, 'uses_lerp_u8'): + pipe.uses_lerp_u8 = True + elif base == 'v_perm_b32': + pipe = getattr(self, 'pipe', None) + if pipe is not None and hasattr(pipe, 'uses_perm_b32'): + pipe.uses_perm_b32 = True + align4 = self.valu_align4(base, ops[1:1 + arity]) + return self.set_v(reg_range(ops[0])[1], text.format(*args), align4=align4) if base in SCA: - return self.scalar(base, ops) + return self.scalar(base, ops, mods) if mods else self.scalar(base, ops) + if base == 's_addc_u32': + # Only the high word of an advanced descriptor pointer; the carry is not modelled. + hi = reg_range(ops[1]) if len(ops) == 3 else None + if hasattr(self, 'scc_uniform') and self.tracks_uniformity(): + self.scc_uniform = False + if self._complete_resheap_carry(base, ops, mods): + return None + if hi and hi[0] == 's' and self.pointer_add(base, ops[0], ops[1:], [self.sym.get(hi[1]), None]): + return None + raise Unsupported(base) if base == 's_getpc_b64': # RDNA 2 GETPC returns the address of its successor: the shader's load address plus a known byte # offset, which is not an integer this model can emit. It is elided only when the program also @@ -3137,10 +5451,13 @@ def lower(self, base, asm, ops, mods): # lane k of its own quad (RDNA 2 ISA, "DPP": a lane reads lane (lane & ~3) | perm[lane & 3] of the row; LLVM 15 # AMDGPU DPP quad_perm). A pixel stage's four consecutive lanes are a 2x2 pixel quad (lane = x & 1 | (y & 1) << 1), # which is what SM 6.0 QuadReadLaneAt(value, k) reads, so the stage is compiled as ps_6_0 (Stage.needs_sm6). - # Accepted only where the whole quad is proven active: a straight-line pixel stage that ran s_wqm exec, exec and - # whose EXEC is still that mask (helper lanes are active, so no source lane is off). bound_ctrl then has - # nothing to decide (the source lane is never disabled), so it is accepted and ignored. Everything else a DPP word can say stays refused: other controls (pair - # broadcasts, row shifts, mirrors, DPP8), a masked row or bank, and a vertex stage (dpp() drops fi:1 first). + # Accepted only where the whole quad is proven active: the entry straight-line prefix of a pixel stage that ran + # s_wqm exec, exec and whose EXEC is still that mask (helper lanes are active, so no source lane is off). A later + # uniform loop or forward branch elsewhere in the stage does not drop the proof: every path still reaches the + # broadcast with the same EXEC and cannot jump back to the prefix. bound_ctrl then has nothing to + # decide (the source lane is never disabled), so it is accepted and ignored. A broadcast after a branch target, + # after EXEC changed, or with divergent EXEC stays refused, as do other DPP controls (pair broadcasts, row shifts, + # mirrors, DPP8), a masked row or bank, and a vertex stage (dpp() drops fi:1 first). DPP_TEMP = 256 # hidden VGPR that holds the quad read; the hardware has v0..v255 only DPP_OUTPUT_MODS = ('clamp', 'mul:2', 'mul:4', 'div:2') @@ -3162,9 +5479,13 @@ def dpp_broadcast(self, base, ops, mods): raise Unsupported('%s_dpp with a partial row_mask or bank_mask' % base) if fields.get('bound_ctrl', '1') != '1': raise Unsupported('%s_dpp bound_ctrl:%s' % (base, fields['bound_ctrl'])) - if (self.kind != 'ps' or getattr(self, 'has_branches', True) or getattr(self, 'blocks', []) - or not getattr(self, 'exec_known', False)): + if self.kind != 'ps': raise Unsupported('%s_dpp outside a straight-line pixel stage with the entry EXEC mask' % base) + # A branch to offset zero also makes the nominal entry block re-entrant. + # The whole-program proof (quad_flow_refusals) replaces the entry-prefix test once translate() runs it. + if (not getattr(self, 'exec_known', False) or + (not self.quad_flow_allowed() and getattr(self, 'past_entry', bool(getattr(self, 'blocks', ()))))): + raise Unsupported('%s_dpp outside the entry prefix of a pixel stage with the entry EXEC mask' % base) if not getattr(self, 'wqm_exec', False): # The entry EXEC can leave out lanes of a partly covered quad, and the guest then reads an inactive # source lane (bound_ctrl / fi), while QuadReadLaneAt would return a helper lane's value. @@ -3185,6 +5506,7 @@ def dpp_broadcast(self, base, ops, mods): rewritten = 'v%d' % self.DPP_TEMP rewritten = '|%s|' % rewritten if absolute else rewritten rewritten = '-' + rewritten if neg else rewritten + self.note_quad_flow(base) self.needs_sm6 = True self.set_v(self.DPP_TEMP, 'QuadReadLaneAt(%s, %su)' % (self.u(token), lanes.group(1))) operands = [ops[0], rewritten] + ops[2:] @@ -3201,7 +5523,7 @@ def dpp_broadcast(self, base, ops, mods): # proved whole-quad EXEC: the hardware can return 0 or the old value for a source lane whose EXEC bit # is off (an uncovered pixel of an edge quad), and the intrinsics have no such case. Other permutations, fi:1 without that proof, DPP8, row shifts and partial masks stay refused. def dpp(self, base, ops, mods): - if base in VOP3_ONLY_VEC_U: + if base in ('v_ldexp_f32', *VOP3_ONLY_VEC_U): raise Unsupported('DPP form of %s' % base) # fi:1 (fetch inactive, DPP16 dword bit 18; LLVM AMDGPU `fi`, Mesa ACO fetch_inactive) only decides what a # disabled source lane returns. Every lowering below is taken only with the whole quad proven active, so no @@ -3247,12 +5569,12 @@ def dpp(self, base, ops, mods): src_neg_abs.append((neg, absolute, base_tok)) elif len(ops) != arity + 1 or any(not re.fullmatch(r'v\d+', o) for o in ops): raise Unsupported('%s_dpp needs VGPR operands without modifiers' % base) - if (getattr(self, 'kind', None) != 'ps' or getattr(self, 'has_branches', True) or getattr(self, 'blocks', True) - or not getattr(self, 'exec_known', False)): + if getattr(self, 'kind', None) != 'ps' or not (self.quad_flow_straight() or self.quad_flow_allowed()) or not getattr(self, 'exec_known', False): raise Unsupported('%s_dpp requires a straight-line pixel shader with entry EXEC' % base) if not getattr(self, 'wqm_exec', False): raise Unsupported('%s_dpp requires whole-quad EXEC (s_wqm of exec first): a partly covered quad has ' 'inactive source lanes that the hardware masks and QuadReadAcross does not' % base) + self.note_quad_flow(base) self.needs_sm6 = True # src0 is the exchanged lane; a VOP2 src1 stays this lane's own register. if kind == 'f': @@ -3295,7 +5617,7 @@ def half_operand(self, tok, kind): text = 'f16tof32(%s & 0xffffu)' % self.u(tok) if absolute: text = 'abs(%s)' % text - return '(-%s)' % text if neg else text + return ('(-(%s))' % text) if (neg and text.startswith('-')) else ('(-%s)' % text if neg else text) def half_alu(self, base, ops, mods): """16-bit VALU: operands are the low 16 bits, the result fills the low 16 bits and zeroes the rest (RDNA 2).""" @@ -3316,11 +5638,68 @@ def half_alu(self, base, ops, mods): # VOP1/VOP2 with sub-dword addressing: select the source fields, run the same operation, then place # the low bits of the result in the destination field. The integer forms reuse VEC_U unchanged, - # v_mov_b32 is the same path with the selected source as its result, + # v_mov_b32 is the same path with the selected source as its result, v_cndmask_b32 selects with VCC, # VEC_U_TO_F conversions apply output modifiers before dst_sel, VEC_F forms stay refused, and # dst_unused UNUSED_SEXT has no lowering. + def sdwa_half(self, base, ops, mods): + """SDWA binary16 add, sub, subrev and mul: a selected half of each source, one rounding, one half written back. + + Sources: src0_sel/src1_sel WORD_0 or WORD_1 pick the half; DWORD reads the low half, as the 16-bit + operation does. Destination: dst_sel WORD_0 or WORD_1 with dst_unused UNUSED_PAD (other half zero) or + UNUSED_PRESERVE (other half of the old register kept). dst_sel DWORD stays refused: the upper half of a + 16-bit result is not claimed (an open question, see the low-16-only contract), and a byte selection, sext(), + clamp and the output modifiers have no lowering here. Sources are VGPRs with the abs/neg modifiers. + """ + _arity, _kind, text, _result = VEC_H[base] + fields = {} + for m in mods: + key, _, value = m.partition(':') + if key in ('src0_sel', 'src1_sel', 'dst_sel', 'dst_unused') and value and key not in fields: + fields[key] = value + else: + raise Unsupported('%s SDWA with modifier %s' % (base, m)) + if len(ops) != 3: + raise Unsupported('%s SDWA with %d operands, expected 3' % (base, len(ops))) + args = [] + for index in range(2): + selection = fields.get('src%d_sel' % index) + if selection not in ('DWORD', 'WORD_0', 'WORD_1'): + raise Unsupported('%s SDWA src%d_sel %s' % (base, index, selection)) + neg, token = self.split_neg(ops[1 + index]) + absolute = False + while True: + if token.startswith('|') and token.endswith('|') and len(token) > 2: + token = token[1:-1] + elif token.startswith('abs(') and token.endswith(')'): + token = token[len('abs('):-1] + else: + break + absolute = True + reg = reg_range(token) + if not reg or reg[0] != 'v' or reg[1] != reg[2]: + raise Unsupported('%s SDWA source %s: expected a single VGPR' % (base, ops[1 + index])) + word = self.u(token, low16_only=selection != 'WORD_1') + half = '(%s >> 16u)' % word if selection == 'WORD_1' else '(%s & 0xffffu)' % word + value = 'f16tof32(%s)' % half + if absolute: + value = 'abs(%s)' % value + args.append('(-%s)' % value if neg else value) + select = fields.get('dst_sel') + unused = fields.get('dst_unused', 'UNUSED_PAD') + if select not in ('WORD_0', 'WORD_1'): + raise Unsupported('%s SDWA dst_sel %s' % (base, select)) + if unused not in ('UNUSED_PAD', 'UNUSED_PRESERVE'): + raise Unsupported('%s SDWA dst_unused %s' % (base, unused)) + destination = reg_range(ops[0])[1] + result = '(f16rn(%s))' % text.format(*args) + # Keeping the old high half of a register whose high half is undefined leaves it undefined. + keep_low16 = select == 'WORD_0' and unused == 'UNUSED_PRESERVE' and destination in self.low16_only_v + self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + def sdwa(self, base, ops, mods): - if base in ('v_cvt_off_f32_i4', *VOP3_ONLY_VEC_U): + if base in ('v_add_f16', 'v_sub_f16', 'v_subrev_f16', 'v_mul_f16'): + return self.sdwa_half(base, ops, mods) + if base in ('v_cvt_off_f32_i4', 'v_ldexp_f32', *VOP3_ONLY_VEC_U): raise Unsupported('SDWA form of %s' % base) fields = {} out_mods = [] @@ -3341,8 +5720,15 @@ def sdwa(self, base, ops, mods): elif base == 'v_mov_b32': arity, text = 1, '{0}' # A lane mask is one bit per lane here, so a byte or word of it is not the hardware's field. - if fields.get('src0_sel') != 'DWORD' and self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): + if fields.get('src0_sel') == 'DWORD': + self.reject_lane_mask_data(base, ops[1]) + elif self.is_lane_mask(ops[1].removeprefix('sext(').removesuffix(')')): raise Unsupported('v_mov_b32 SDWA %s of lane mask %s' % (fields.get('src0_sel'), ops[1])) + elif base == 'v_cndmask_b32' and len(ops) == 4 and ops[3] == 'vcc_lo': + # The VOP2 select: its lane mask is always VCC, printed as the fourth operand, and read like the + # plain select's mask (op_v_cndmask_b32). + mask = self.u(ops[3]).replace('{', '{{').replace('}', '}}') + arity, text = 2, '(%s & 1) ? {1} : {0}' % mask else: raise Unsupported('SDWA form of %s' % base) sources = [] @@ -3374,6 +5760,105 @@ def sdwa(self, base, ops, mods): destination in self.low16_only_v) self.set_v(destination, sdwa_dest(result, select, unused, 'v%d' % destination), low16_only=keep_low16) + def pointer_add(self, base, dname, srcs, syms): + """Propagate a descriptor pointer through s_add_u32 sD, sP, <literal> / s_addc_u32 sD+1, sP+1, 0. + + The pair advances a table or root pointer by a literal byte offset, into the same or + another register pair. The offset rides in the low word as ('ptr', source, offset); the + high word keeps ('ptrhi', source). The low-word carry is taken as zero: the base is a + table or root address and the offset is below 1 MiB. Anything else returns False. + """ + if base not in ('s_add_u32', 's_addc_u32') or len(srcs) != 2 or not syms[0]: + return False + if getattr(self, 'has_branches', False): + if (not getattr(self, 'forward_table_adds', False) or base != 's_add_u32' + or syms[0][0] != 'ptr' or syms[0][1][0] != 'table'): + return False + reg = reg_range(dname) + if not reg or reg[0] != 's' or reg[1] != reg[2] or reg[1] > 105: + return False + d = reg[1] + if base == 's_add_u32': + if syms[0][0] != 'ptr' or not re.fullmatch(r'(?:0[xX][0-9a-fA-F]+|\d+)', srcs[1]): + return False + added = int(srcs[1], 0) + if added > 0xfffff: + raise Unsupported('descriptor pointer offset %s' % srcs[1]) + before = syms[0][2] if len(syms[0]) > 2 else 0 + if not isinstance(before, int): + raise Unsupported('add through a pointer with unknown byte offset') + if getattr(self, 'forward_table_adds', False) and before + added > 0xfffff: + raise Unsupported('accumulated table pointer offset %#x' % (before + added)) + self.sym[d] = ('ptr', syms[0][1], before + added) + if syms[0][1][0] in PTR64_SOURCES and d + 1 <= 105: + # The carry-in of an s_addc_u32 is only the carry of this very add: remember where the next + # instruction starts so that the high-word add is accepted right behind it and nowhere else. + size = next((n for off, n, _name, _asm in getattr(self, 'ins', ()) if off == self.pc), 0) + self.ptr_low_add = (d, self.pc + size, syms[0][1], before, before + added) + # The pair stays open until the matching s_addc_u32 completes it. The high register is left as it + # is (in place it is still the original high source); a load through an open pair is refused. + self.__dict__.setdefault('ptr_open_pairs', set()).add(d) + return True + low = self.sym.get(d - 1) + mark = getattr(self, 'ptr_low_add', None) + hi = reg_range(srcs[0]) + # The high operand is judged by what it holds, not by where it sits: a copied high word still counts. + if (not mark or srcs[1] != '0' or not low or low[0] != 'ptr' or not hi or hi[0] != 's' + or mark[:2] != (d - 1, getattr(self, 'pc', 0)) or low[1] != mark[2] + or self.sym.get(hi[1]) != ptr_high_symbol(mark[2], mark[3])): + return False + self.sym[d] = ptr_high_symbol(mark[2], mark[4]) + getattr(self, 'ptr_open_pairs', set()).discard(d - 1) + # This s_addc_u32 is the only reader of the low add's elided carry; any other SCC reader stays refused. + self.__dict__.setdefault('ptr_addc_pcs', set()).add(self.pc) + return True + + def exec_zero_keepable(self, target, reg, arriving, paths, branches): + """Rule R1: the fall-through arm of an s_cbranch_execz skip wrote a descriptor word and no other edge into the + target wrote the register, and exec is not written between the first skipping branch and the target (so on + the fall-through exec is still the arm's mask, and on every taken edge it is 0).""" + if len(paths) != 1 or not paths[0] or paths[0][0] != 'desc' or reg not in arriving[0][1]: + return False + if any(reg in w for _, w in arriving[1:]): + return False + first = min(pc for pc, to in branches if to == target) + for off, _n, name, asm in self.ins: + if first < off < target and writes_exec(name, parse(asm)[1]): + return False + return True + + def end_exec_keep(self, index, off, name, asm, targets): + """Ends the R1 window: from the next join, branch or exec write on, a register kept after an execz join is + joined again (a lane that skipped the arm is active again and would read the arm's stale word). A scalar + instruction reading a kept register ends it for that register at once: scalar work runs with exec == 0 too. + A descriptor load that redefines a kept register on every path retires its marker without poisoning it.""" + prev_name, prev_asm = self.ins[index - 1][2], self.ins[index - 1][3] + if prev_name.startswith(('s_load', 's_buffer_load')): + dest = reg_range(parse(prev_asm)[1][0]) + for reg in [r for r in self.exec_keep if dest and dest[0] == 's' and dest[1] <= r <= dest[2]]: + del self.exec_keep[reg] + if not self.exec_keep: + return + if (off in targets or name.startswith('s_cbranch') or name in ('s_branch', 's_setpc_b64') + or writes_exec(prev_name, parse(prev_asm)[1])): + self.retire_exec_keep(set(self.exec_keep)) + elif name.startswith('s_'): + self.end_exec_keep_scalar_read(name, asm) + + def end_exec_keep_scalar_read(self, name, asm): + doomed = set() + for tok in parse(asm)[1][1:]: + r = reg_range(tok) + if r and r[0] == 's': + doomed |= {reg for reg in self.exec_keep if r[1] <= reg <= r[2]} + self.retire_exec_keep(doomed) + + def retire_exec_keep(self, doomed): + for reg in doomed: + if self.sym.get(reg) == self.exec_keep[reg]: + self.sym[reg] = ('joined at a branch target',) + del self.exec_keep[reg] + # scalar ALU with descriptor-word bookkeeping def exec_absorbed_source(self, base, srcs): """Index of a joined source of the instruction at a branch target whose stale value cannot reach bit 0 of @@ -3393,7 +5878,27 @@ def exec_absorbed_source(self, base, srcs): return i return None - def scalar(self, base, ops): + def _complete_resheap_carry(self, base, ops, mods): + if getattr(self, 'resheap_low_add', None) is None: + return False + low_d, expect_pc, per_lane_info = self.resheap_low_add + self.resheap_low_add = None + hi_tok = 's%d' % (low_d + 1) + hi_carry_ok = (self.pc == expect_pc and not mods and ( + (base == 's_add_u32' and ops == [hi_tok, '0', 'src_scc']) or + (base == 's_addc_u32' and len(ops) == 3 and ops[0] == hi_tok and ops[2] == '0' + and reg_range(ops[1]) and reg_range(ops[1])[0] == 's' + and self.sym.get(reg_range(ops[1])[1]) == ('const', 0)))) + if not hi_carry_ok: + return False + self.sym[low_d + 1] = ('ptrhi', ('resheap',), per_lane_info) + getattr(self, 'ptr_open_pairs', set()).discard(low_d) + self.__dict__.setdefault('ptr_addc_pcs', set()).add(self.pc) + self.scc_effect = 'emitted' + self.scc_verified = False + return True + + def scalar(self, base, ops, mods=()): # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would # index past the end and leave `translator crash in <op>: IndexError` in the census instead of a # refusal. s_movk_i32 keeps its own exact check for the immediate it folds. @@ -3402,9 +5907,16 @@ def scalar(self, base, ops): if base == 's_movk_i32' and len(ops) != 2: raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) text, scc = SCA[base] - if base in SCC_UNMODELLED and self.tracks_uniformity(): - self.scc_uniform = False dst = reg_range(ops[0]) + if self._complete_resheap_carry(base, ops, mods): + return None + if base == 's_add_u32' and self.address_carry_reader is not None and self.pc == self.address_carry_reader: + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_add_u32 destination %s' % ops[0]) + # The immediately preceding numeric add emitted the carry; no branch can enter here. + self.set_s(dst[1], '(scc ? 1u : 0u)') + self.set_scc('false') # 0 + a single bit never produces another carry. + return None pair = base.endswith('_b64') srcs = ops[1:] # 64-bit operands name the low register; exec/vcc name themselves. @@ -3418,13 +5930,14 @@ def low(tok): shift_add = base in SHIFT_ADD word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') lane_complement = False - # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. - word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') + # s_mul_hi_{u,i}32 need the whole 32-bit word of each source, like the halfword pack. + word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32', 's_mul_hi_i32') word_absdiff = base == 's_absdiff_i32' if shift_add or word_complement or word_pack or word_absdiff: - # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_u32 into an + # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_{u,i}32 into an # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. - mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' + mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') + if base in ('s_mul_hi_u32', 's_mul_hi_i32') else self.is_lane_mask(dname)) # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. @@ -3442,6 +5955,8 @@ def mask_source(tok): if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) if word_pack: + if base in ('s_mul_hi_u32', 's_mul_hi_i32') and len(srcs) != 2: + raise Unsupported('%s with %d operands, expected 3' % (base, len(ops))) if dname != 'm0' and (dst is None or dst[0] != 's' or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) for source in srcs: @@ -3456,23 +5971,87 @@ def src_sym(t): r = reg_range(t) return self.sym.get(r[1]) if r and r[0] == 's' else None syms = [src_sym(t) for t in srcs] + mask_dest = dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo', 'exec_hi', 'vcc_hi') + if base == 's_mov_b64' and ops[0] == 'vcc' and len(ops) == 2: + source = reg_range(ops[1]) + if source and source[0] == 's': + words = (syms[0], self.sym.get(source[2])) + if any(word and word[0] == 'desc' for word in words): + if (source[1] % 2 or source[2] != source[1] + 1 or + any(not word or word[0] != 'desc' for word in words)): + raise Unsupported('mask from descriptor data: vcc needs an even pair of descriptor words') + self.sym[106], self.sym[107] = words + self.mark_vcc_descriptor() + return None + tg_srcs = [ + reg for tok in ops[1:] for r in (reg_range(tok),) if r and r[0] == 's' + for reg in range(r[1], r[2] + 1) if self.sym.get(reg) == ('tg_size',) + ] + if tg_srcs: + # Wave-ID bits TG_SIZE[11:6] (mask 0xfc0) are identically 0 for <= 32 threads per group (1 wave). + if (base == 's_and_b32' and not mods and len(srcs) == 2 + and dst and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105): + other = (srcs[1] if syms[0] == ('tg_size',) and syms[1] != ('tg_size',) + else srcs[0] if syms[1] == ('tg_size',) and syms[0] != ('tg_size',) + else None) + if other is not None and self.const_u32(other) == 0xfc0: + self.set_s(dst[1], '0u', ('const', 0), scc='false') + return None + raise Unsupported('TG_SIZE register s%d read outside s_and_b32 with 0xfc0' % tg_srcs[0]) + self.refuse_select_source(base, ops[1:]) # whole ranges: srcs names only the low word of a pair if any(s and s[0] in ('desc', 'descnum', 'ptr', 'ptrhi') for s in syms): + if 'src_scc' in srcs and not getattr(self, 'scc_verified', False): + raise Unsupported('src_scc with unverified SCC') if scc or base in SCC_UNMODELLED: self.scc_effect = 'descriptor' + self.scc_verified = False if self.tracks_uniformity(): self.scc_uniform = False if shift_add or word_complement or word_absdiff: raise Unsupported('scc from descriptor data') if word_pack: raise Unsupported('%s on descriptor data' % base) + # Every path below writes the destination's symbol directly, not through set_s, or refuses. The + # written word is descriptor data, so a lane-mask mark the SGPR held from an earlier write ends here as + # set_s ends it. lower() has already classified the sources, so a mask read by this instruction is + # still refused. + if dst and dst[0] == 's': + for reg in range(dst[1], dst[2] + 1): + getattr(self, 'masks', set()).discard(reg) + getattr(self, 'mask_high', set()).discard(reg) + if self.pointer_add(base, dname, srcs, syms): + return None + if (base == 's_add_u32' and not mods and len(srcs) == 2 and dst and dst[0] == 's' + and dst[1] == dst[2] and dst[1] < 105 and hasattr(self, 'heap_index')): + for i in (0, 1): + if syms[i] == ('ptr', ('resheap',)): + off_r = reg_range(srcs[1 - i]) + heap_mark = ({**self.heap_index, **self.heap_index_was}.get(off_r[1]) + if off_r and off_r[0] == 's' and off_r[1] == off_r[2] else None) + if heap_mark and heap_mark[0] == 'per_lane': + ptr_r = reg_range(srcs[i]) + if self.sym.get(ptr_r[1] + 1) != ('const', 0): + raise Unsupported('s_load of a resource heap record through a pointer whose high ' + 'word is not a constant zero') + size = next((n for off, n, _name, _asm in getattr(self, 'ins', ()) if off == self.pc), 0) + self.sym[dst[1]] = ('ptr', ('resheap',), heap_mark) + self.__dict__.setdefault('ptr_open_pairs', set()).add(dst[1]) + self.resheap_low_add = (dst[1], self.pc + size, heap_mark) + self.scc_verified = True + return None if dname == 'm0': if scc: raise Unsupported('scc from descriptor data') self.sym['m0'] = syms[0] if base == 's_mov_b32' else ('descnum',) return None - if dname in ('exec', 'vcc', 'exec_lo', 'vcc_lo'): + if mask_dest: raise Unsupported('mask from descriptor data') - d = reg_range(dname)[1] + if dname == 'null': + raise Unsupported('scc from descriptor data' if (scc or base in SCC_UNMODELLED) + else '%s into null on descriptor data' % base) + if not dst or dst[0] != 's': + raise Unsupported('%s destination %s' % (base, ops[0])) + d = dst[1] own = self.sym.get(d) raw = (raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) if getattr(self, 'kind', None) in ('cs', 'vs') and len(syms) == 2 else None) @@ -3491,6 +6070,10 @@ def src_sym(t): self.sym[d + 1] = hi elif self.tracks_uniformity(): self.varying_s.add(d + 1) + elif (own and own[0] == 'ptr' and base in ('s_add_u32', 's_addc_u32') + and not getattr(self, 'has_branches', False)): + # With branches the offset is not tracked: the 'added' mark below stays, and the join refuses it. + raise Unsupported('%s adds a non-literal to a descriptor pointer' % base) elif raw is not None: self.sym[d] = raw if raw[0] == 'desc': @@ -3502,7 +6085,7 @@ def src_sym(t): self.sym[d] = own[:4] + ('modified',) getattr(self.pipe, 'other_modified', set()).add(desc_key(own)) else: - self.sym[d] = own if len(own) > 2 else own + ('added',) # the added offset is not tracked + self.sym[d] = own[:2] + ('added',) # this operation has no proven byte offset else: self.sym[d] = ('descnum',) return None @@ -3514,11 +6097,40 @@ def src_sym(t): needed = max((int(i) for i in re.findall(r'\{(\d+)\}', text)), default=-1) + 1 if len(srcs) < needed: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), needed + 1)) + if dname == 'null': + if any(self.is_lane_mask(t) for t in srcs): + raise Unsupported('%s into null on a lane mask' % base) + if pair: + raise Unsupported('%s into null' % base) + deferred_scc = None absorbed = self.exec_absorbed_source(base, srcs) if absorbed is not None: self.used_s.add(reg_range(srcs[absorbed])[1]) values = [t if i == absorbed else self.u(t) for i, t in enumerate(srcs)] expr = text.format(*values) + if base == 's_add_u32' and getattr(self, 'pc', None) in self.address_carry_pairs: + for tok in srcs: + self.reject_lane_mask_data(base, tok) + r = reg_range(tok) + if r and r[1] in getattr(self, 'join_masks', ()): + raise Unsupported('address carry on a lane mask joined at a branch target') + # Compute carry before writing the low register, which can also be an addend. + self.set_scc('(%s) < %s' % (expr, values[0])) + self.address_carry_reader = self.address_carry_pairs[self.pc] + elif base in SCC_UNMODELLED: + scc_text = add_sub_min_max_scc(base, values[0], values[1], expr) + if re.search(r'\bscc\b', scc_text): + # An operand is the incoming SCC (src_scc): the destination must read it before this instruction's own + # SCC replaces it, so the destination is written first and the SCC after, from sources it did not change. + if dname in ('m0', 'exec', 'exec_lo', 'vcc', 'vcc_lo', 'null') or any( + reg_range(t) and dst and reg_range(t)[0] == 's' and dst[1] <= reg_range(t)[1] <= dst[2] + for t in srcs): + raise Unsupported('%s reads src_scc with a destination that is also a source or a special register' + % base) + deferred_scc = scc_text + else: + # From the sources, before the destination is written (it can be a source). + self.set_scc(scc_text) if shift_add: # carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written n = SHIFT_ADD[base] @@ -3534,19 +6146,34 @@ def src_sym(t): if dname in ('exec', 'exec_lo', 'vcc', 'vcc_lo'): var = dname[:4].rstrip('_') if dname.startswith('exec') else 'vcc' if var == 'exec': - copy = base in ('s_mov_b64', 's_mov_b32') and self.exec_known and (syms[0] == ('execcopy',)) + copy = base in ('s_mov_b64', 's_mov_b32') and dname == 'exec' and self.exec_known and (syms[0] == ('execcopy',)) if copy: + if hasattr(self, 'lane_exec_breaks') and self.helper_off_copy(srcs[0], syms[0]): + self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) + self.helper_restore = True # A restored copy can re-activate lanes a WQM added: drop every VGPR proof. self.wqm_exec = False # and the copy can be older than the WQM if hasattr(self, 'uniform_v'): self.uniform_v.clear() + if isinstance(self.align4_v, set): + self.align4_v.clear() return None self.exec_known = False + if hasattr(self, 'lane_exec_breaks') and (dname == 'exec_lo' or not self.exec_write_exact(srcs, syms)): + # exec = (expr) & 1 writes every pixel and helper lane alike; the guest enables only the lanes the + # source selects, so the lane's EXEC bit may stop following the guest's from here. + self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) self.emit('%s = (%s) & 1;' % (var, expr)) if scc: self.set_scc(scc.replace('$', var)) return None - d = reg_range(dname)[1] + if dname == 'null': + if scc: + self.set_scc(scc.replace('$', '(%s)' % expr)) + return None + if not dst or dst[0] != 's': + raise Unsupported('%s destination %s' % (base, ops[0])) + d = dst[1] is_mask = pair or any(t in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or (reg_range(t) and reg_range(t)[0] == 's' and reg_range(t)[1] in self.masks) for t in srcs) and base.split('_')[1] in ('mov', 'and', 'or', 'xor', 'andn2', 'orn2', 'nand', 'nor', 'xnor', 'not', 'cselect') if base in ('s_mov_b32', 's_mov_b64', 's_movk_i32') and re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', srcs[0]) and srcs[0] not in FLOATS: @@ -3556,6 +6183,15 @@ def src_sym(t): self.set_s(d + 1, '0x%08xu' % ((value >> 32) & 0xffffffff), ('const', (value >> 32) & 0xffffffff)) self.masks.discard(d) return None + if base == 's_mov_b32' and not pair and len(srcs) == 1 and reg_range(srcs[0]) and reg_range(srcs[0])[0] == 's' \ + and reg_range(srcs[0])[1] == reg_range(srcs[0])[2] and len(self.sym.get(reg_range(srcs[0])[1]) or ()) == 2 \ + and self.is_const(reg_range(srcs[0])[1]) is not None: + # A copy of an SGPR holding a plain known constant (not the tagged unassigned placeholder) is that constant (llc copies a zero into an inline + # sampler word: s_mov_b32 s12, s15 after s_mov_b32 s15, 0). + value = self.is_const(reg_range(srcs[0])[1]) + self.set_s(d, '0x%08xu' % value, ('const', value)) + self.masks.discard(d) + return None if base in SCALAR_CONST_FOLD: # Constant operands give a known word, so a descriptor built from them (an inline sampler from # s_movk_i32, s_bfm_b32, s_mov_b32 and s_brev_b32 into s[N:N+3]) is a constant descriptor. @@ -3564,6 +6200,8 @@ def known(tok): if r and r[0] == 's' and r[1] == r[2]: c = self.is_const(r[1]) return c if c is not None else getattr(self, '_pre_fconst', getattr(self, 'float_const_s', {})).get(r[1]) + if tok == 'null': + return 0 if tok in FLOATS: return fbits(FLOATS[tok]) if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', tok) and tok not in FLOATS: @@ -3578,6 +6216,9 @@ def known(tok): if base in ('s_mov_b64', 's_mov_b32') and srcs[0] in ('exec', 'exec_lo') and self.exec_known: self.set_s(d, 'exec') self.sym[d] = ('execcopy',) + if not hasattr(self, 'execcopy_epoch'): + self.execcopy_epoch = {} + self.execcopy_epoch[d] = getattr(self, 'wqm_count', 0) # the s_wqm count when the mask was saved self.masks.add(d) if pair: self.sym.pop(d + 1, None) @@ -3593,7 +6234,10 @@ def known(tok): high_source = 's%d' % high if high is not None else srcs[0] high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) - self.set_s(d, expr, scc=None if lane_complement else scc) + salu_align4 = not pair and not is_mask and self.salu_align4(base, srcs) + self.set_s(d, expr, scc=None if lane_complement else scc, align4=salu_align4) + if deferred_scc is not None: + self.set_scc(deferred_scc) if base == 's_mov_b32' and srcs[0] in FLOATS and not is_mask: # Keep the runtime SGPR assignment intact while letting const_words() read inline float patterns # such as 0x40000000 (OPAQUE_BLACK, encoded as inline 244 / '2.0'). @@ -3604,6 +6248,8 @@ def known(tok): self.scc_effect = 'a lane-mask complement' if self.tracks_uniformity(): self.scc_uniform = False + if hasattr(self, 'heap_index'): + self.mark_heap_index(base, d, srcs, syms) if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': @@ -3612,9 +6258,54 @@ def known(tok): self.set_s(d + 1, self.S(high) if high is not None else '0u', uniform=high_uniform) return None + def heap_word_offset(self, tok, sym): + """(param, word, scale, add) when tok, whose symbol before this instruction is sym, holds root constant word + (param, word) times scale plus add, modulo 2^32 (see mark_heap_index); else None.""" + if sym and sym[0] == 'ud' and self.pipe.uds[sym[1]][0] == 'rootconst': + return self.pipe.uds[sym[1]][1:] + (1, 0) + r = reg_range(tok) + mark = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + return mark[1:] if mark and mark[0] == 'rc' else None + + def mark_heap_index(self, base, d, srcs, syms): + """Marks of SGPR d for heap_record. index << 5 is the byte offset of a 32-byte resource-heap record; the index + is named when it is a root constant word (the dispatch knows it) or a word an s_buffer_load wrote (see + op_s_buffer_load_dword). A root constant word times a literal plus a literal ('rc') is the byte offset such a + load may read the index word at: the same for every thread of the dispatch.""" + lit = [int(t, 0) & 0xffffffff if re.fullmatch(r'0x[0-9a-f]+|[0-9]+', t) else None for t in srcs] + r = reg_range(srcs[0]) + if base == 's_lshl_b32' and lit[1:] == [5]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) if r and r[0] == 's' else None + per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1]) \ + if r and r[0] == 's' else None + if syms[0] and syms[0][0] == 'ud' and self.pipe.uds[syms[0][1]][0] == 'rootconst': + self.heap_index[d] = self.pipe.uds[syms[0][1]] + elif word and word[0] == 'bufword': + self.heap_index[d] = ('buffer',) + word[1:] + elif per_lane is not None: + expr, bound = per_lane + self.heap_index[d] = ('per_lane', ('(s%d >> 5)' % d) if d == r[1] else expr, bound) + elif base == 's_mov_b32' and len(srcs) == 1 and r and r[0] == 's' and r[1] == r[2]: + word = {**self.heap_index, **self.heap_index_was}.get(r[1]) + per_lane = {**getattr(self, 'per_lane_index', {}), **getattr(self, 'per_lane_index_was', {})}.get(r[1]) + if word and word[0] == 'per_lane': + self.heap_index[d] = word + elif per_lane is not None: + self.per_lane_index[d] = ('s%d' % d, per_lane[1]) + elif base in ('s_add_u32', 's_add_i32', 's_mul_i32') and len(srcs) == 2: + for i in (0, 1): + k = lit[1 - i] + offset = self.heap_word_offset(srcs[i], syms[i]) if k is not None else None + if offset: + p, w, scale, add = offset + self.heap_index[d] = (('rc', p, w, scale * k & 0xffffffff, add * k & 0xffffffff) if base == 's_mul_i32' + else ('rc', p, w, scale, add + k & 0xffffffff)) + break + def set_exec_scc(self, expr): self.exec_known = False self.scc_effect = 'emitted' + self.scc_verified = True self.emit('exec = (%s) & 1; scc = exec != 0;' % expr) if hasattr(self, 'scc_uniform'): self.scc_uniform = False @@ -3703,35 +6394,305 @@ def scalar_accumulate(self, base, ops, mods): if sym and sym[0] == 'const': value = (sym[1] + imm if add else sym[1] * imm) & 0xffffffff self.set_s(d, '0x%08xu' % value, ('const', value)) + else: + was_align4 = d in self.align4_s and sym is None + acc_align4 = (was_align4 and (imm & 3) == 0) if add else (was_align4 or (imm & 3) == 0) + self.set_s(d, result, align4=acc_align4) + offset = self.heap_word_offset(ops[0], sym) if hasattr(self, 'heap_index') else None + if offset: + p, w, scale, plus = offset + self.heap_index[d] = ('rc', p, w, scale, plus + imm & 0xffffffff) if add else ( + 'rc', p, w, scale * imm & 0xffffffff, plus * imm & 0xffffffff) + self.masks.discard(d) + return None + + def op_s_addk_i32(self, ops, mods): + return self.scalar_accumulate('s_addk_i32', ops, mods) + + def op_s_mulk_i32(self, ops, mods): + return self.scalar_accumulate('s_mulk_i32', ops, mods) + + def op_s_cselect_b32(self, ops, mods): + self.scalar_select(ops, False) + + def op_s_cselect_b64(self, ops, mods): + self.scalar_select(ops, True) + + def op_s_cmov_b32(self, ops, mods): + self.scalar_cmov(ops, mods, False) + + def op_s_cmov_b64(self, ops, mods): + self.scalar_cmov(ops, mods, True) + + def op_s_cmovk_i32(self, ops, mods): + # SOPK form: the 16-bit immediate is sign-extended to 32 bits. + if len(ops) != 2 or mods: + raise Unsupported('s_cmovk_i32 requires a destination and a 16-bit immediate') + value = sopk_imm(ops[1], True) + self.scalar_cmov([ops[0], '0x%x' % value], mods, False, 's_cmovk_i32') + + def op_s_bitset0_b32(self, ops, mods): + return self.scalar_bitset(ops, mods, clear=True) + + def op_s_bitset1_b32(self, ops, mods): + return self.scalar_bitset(ops, mods, clear=False) + + def op_s_bitset0_b64(self, ops, mods): + return self.scalar_bitset64(ops, mods, clear=True) + + def op_s_bitset1_b64(self, ops, mods): + return self.scalar_bitset64(ops, mods, clear=False) + + def scalar_bitset(self, ops, mods, clear): + """s_bitset0/1_b32: clear or set bit S0[4:0] of D in place; SCC unchanged. + + RDNA 2 ISA SOP1 0x1b / 0x1d (and the pixel_aot / #1579 lowering): D.u &= ~(1u << (S0.u & 31)) + or D.u |= (1u << (S0.u & 31)). The destination is also a source (READ_MODIFY_WRITE). Only a + plain user SGPR destination is accepted; lane masks and descriptor-bearing SGPRs stay refused + so a partial word cannot be treated as a full 32-bit scalar. + """ + name = 's_bitset%d_b32' % (0 if clear else 1) + if mods or len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2 unmodified' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + if self.is_lane_mask(ops[0]) or d in self.masks: + raise Unsupported('%s on a lane mask' % name) + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + bit_sym = None + if ops[1] == 'null': + index_imm = 0 + elif imm: + index_imm = int(ops[1], 0) & 31 + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('%s on a lane mask' % name) + bit_sym = self.sym.get(src[1]) + if bit_sym and bit_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, bit_sym[0])) + index_imm = bit_sym[1] & 31 if bit_sym and bit_sym[0] == 'const' else None + sym = self.sym.get(d) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + prev = self.S(d) + bit = self.u(ops[1]) + mask = '(1u << (%s & 31))' % bit + result = '(%s & ~%s)' % (prev, mask) if clear else '(%s | %s)' % (prev, mask) + if sym and sym[0] == 'const' and index_imm is not None: + value = ((sym[1] & ~(1 << index_imm)) if clear else (sym[1] | (1 << index_imm))) & 0xffffffff + self.set_s(d, '0x%08xu' % value, ('const', value)) else: self.set_s(d, result) self.masks.discard(d) return None - def op_s_addk_i32(self, ops, mods): - return self.scalar_accumulate('s_addk_i32', ops, mods) - - def op_s_mulk_i32(self, ops, mods): - return self.scalar_accumulate('s_mulk_i32', ops, mods) - - def op_s_cselect_b32(self, ops, mods): - self.scalar_select(ops, False) - - def op_s_cselect_b64(self, ops, mods): - self.scalar_select(ops, True) + def scalar_bitset64(self, ops, mods, clear): + """s_bitset0/1_b64: clear or set bit S0[5:0] of 64-bit pair D in place; SCC unchanged. + + RDNA 2 ISA SOP1 0x1c / 0x1e: bit 5 of S0 selects the high vs. low word of D, and + S0[4:0] selects the bit within that word. The destination pair is read-modify-write; + when S0 aliases the low word of D, the high word is updated first so S0 is read intact. + """ + name = 's_bitset%d_b64' % (0 if clear else 1) + if mods or len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2 unmodified' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[1] % 2 != 0 or dst[2] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + if self.is_lane_mask(ops[0]) or any(w in masks or w in mask_high for w in (d, d + 1)): + raise Unsupported('%s on a lane mask' % name) + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + src_reg = None + if ops[1] == 'null': + index_imm = 0 + elif imm: + index_imm = int(ops[1], 0) & 63 + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + src_reg = src[1] + if self.is_lane_mask(ops[1]) or src_reg in masks or src_reg in mask_high: + raise Unsupported('%s on a lane mask' % name) + bit_sym = self.sym.get(src_reg) + if bit_sym and bit_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, bit_sym[0])) + index_imm = bit_sym[1] & 63 if bit_sym and bit_sym[0] == 'const' else None + for r in (d, d + 1): + sym = self.sym.get(r) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + if index_imm is not None: + target = d + (index_imm >> 5) + shift = index_imm & 31 + sym = self.sym.get(target) + if sym and sym[0] == 'const': + val = ((sym[1] & ~(1 << shift)) if clear else (sym[1] | (1 << shift))) & 0xffffffff + self.set_s(target, '0x%08xu' % val, ('const', val)) + else: + prev = self.S(target) + mask = '0x%08xu' % (1 << shift) + self.set_s(target, '(%s & ~%s)' % (prev, mask) if clear else '(%s | %s)' % (prev, mask)) + else: + prev_lo, prev_hi = self.S(d), self.S(d + 1) + bit = self.u(ops[1]) + mask = '(1u << (%s & 31u))' % bit + upd_lo = '(%s & ~%s)' % (prev_lo, mask) if clear else '(%s | %s)' % (prev_lo, mask) + upd_hi = '(%s & ~%s)' % (prev_hi, mask) if clear else '(%s | %s)' % (prev_hi, mask) + lo_expr = '((%s & 32u) == 0u ? %s : %s)' % (bit, upd_lo, prev_lo) + hi_expr = '((%s & 32u) != 0u ? %s : %s)' % (bit, upd_hi, prev_hi) + if src_reg == d: + self.set_s(d + 1, hi_expr) + self.set_s(d, lo_expr) + else: + self.set_s(d, lo_expr) + self.set_s(d + 1, hi_expr) + if hasattr(self, 'masks'): + self.masks.difference_update((d, d + 1)) + return None + + def op_s_brev_b64(self, ops, mods): + """s_brev_b64: 64-bit bit reverse of S0 into SGPR pair D; SCC unchanged. - def op_s_cmov_b32(self, ops, mods): - self.scalar_cmov(ops, mods, False) + RDNA 2 ISA SOP1 0x0c: D.u[31:0] = reversebits(S0.u[63:32]), D.u[63:32] = reversebits(S0.u[31:0]). + When D == S0 (in-place reversal), a scoped temporary preserves both halves before overwriting. + """ + name = 's_brev_b64' + if mods or len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2 unmodified' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[1] % 2 != 0 or dst[2] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + if self.is_lane_mask(ops[0]) or any(w in masks or w in mask_high for w in (d, d + 1)): + raise Unsupported('%s on a lane mask' % name) + if self.is_lane_mask(ops[1]): + raise Unsupported('%s on a lane mask' % name) + src = reg_range(ops[1]) + src_reg = None + if src: + if src[0] != 's' or src[2] != src[1] + 1 or src[1] % 2 != 0 or src[2] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + src_reg = src[1] + if any(w in masks or w in mask_high for w in (src_reg, src_reg + 1)): + raise Unsupported('%s on a lane mask' % name) + for r in (src_reg, src_reg + 1): + sym = self.sym.get(r) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + lo, hi = self.S(src_reg), self.S(src_reg + 1) + c_lo = self.scalar_const('s%d' % src_reg) + c_hi = self.scalar_const('s%d' % (src_reg + 1)) + elif ops[1] == 'null': + lo, hi, c_lo, c_hi = '0u', '0u', 0, 0 + else: + lo, hi = self.i64_words(ops[1], False, True) + c_lo, c_hi = int(lo[:-1]), int(hi[:-1]) + if c_lo is not None and c_hi is not None: + rev_lo = int('{:032b}'.format(c_hi & 0xffffffff)[::-1], 2) + rev_hi = int('{:032b}'.format(c_lo & 0xffffffff)[::-1], 2) + self.set_s(d, '0x%08xu' % rev_lo, ('const', rev_lo)) + self.set_s(d + 1, '0x%08xu' % rev_hi, ('const', rev_hi)) + return None + if src_reg == d: + tracks = self.tracks_uniformity() + u_lo = self.scalar_expr_uniform(hi) if tracks else None + u_hi = self.scalar_expr_uniform(lo) if tracks else None + self.emit('{ uint _t0 = reversebits(%s); s%d = reversebits(%s); s%d = _t0; }' % (hi, d + 1, lo, d)) + for r, u in ((d, u_lo), (d + 1, u_hi)): + if tracks: + self.record_scalar_uniformity(r, u) + getattr(self, 'masks', set()).discard(r) + getattr(self, 'mask_high', set()).discard(r) + getattr(self, 'float_const_s', {}).pop(r, None) + if isinstance(self.align4_s, set): + self.align4_s.discard(r) + self.sym.pop(r, None) + self.used_s.add(r) + return None + if c_hi is not None: + rev_lo = int('{:032b}'.format(c_hi & 0xffffffff)[::-1], 2) + self.set_s(d, '0x%08xu' % rev_lo, ('const', rev_lo)) + else: + self.set_s(d, 'reversebits(%s)' % hi) + if c_lo is not None: + rev_hi = int('{:032b}'.format(c_lo & 0xffffffff)[::-1], 2) + self.set_s(d + 1, '0x%08xu' % rev_hi, ('const', rev_hi)) + else: + self.set_s(d + 1, 'reversebits(%s)' % lo) + return None - def op_s_cmov_b64(self, ops, mods): - self.scalar_cmov(ops, mods, True) + def op_s_bitreplicate_b64_b32(self, ops, mods): + """s_bitreplicate_b64_b32: replicate each bit of 32-bit S0 twice into 64-bit pair D; SCC unchanged. - def op_s_cmovk_i32(self, ops, mods): - # SOPK form: the 16-bit immediate is sign-extended to 32 bits. - if len(ops) != 2 or mods: - raise Unsupported('s_cmovk_i32 requires a destination and a 16-bit immediate') - value = sopk_imm(ops[1], True) - self.scalar_cmov([ops[0], '0x%x' % value], mods, False, 's_cmovk_i32') + RDNA 2 ISA SOP1 0x3b: D[2*i] = D[2*i+1] = S0[i] for i in 0..31. + When S0 aliases the low word of D (s[D:D+1], sD), the high word is written first so S0 stays intact. + """ + name = 's_bitreplicate_b64_b32' + if mods or len(ops) != 2: + raise Unsupported('%s with %d operands, expected 2 unmodified' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[1] % 2 != 0 or dst[2] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + d = dst[1] + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + if self.is_lane_mask(ops[0]) or any(w in masks or w in mask_high for w in (d, d + 1)): + raise Unsupported('%s on a lane mask' % name) + if self.is_lane_mask(ops[1]): + raise Unsupported('%s on a lane mask' % name) + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + src_reg = None + if ops[1] == 'null': + const_val = 0 + elif imm: + const_val = int(ops[1], 0) & 0xffffffff + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('%s source %s' % (name, ops[1])) + src_reg = src[1] + if src_reg in masks or src_reg in mask_high: + raise Unsupported('%s on a lane mask' % name) + sym = self.sym.get(src_reg) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('%s on %s data' % (name, sym[0])) + const_val = sym[1] & 0xffffffff if sym and sym[0] == 'const' else None + if const_val is not None: + def _rep16(x): + x &= 0xffff + x = (x | (x << 8)) & 0x00ff00ff + x = (x | (x << 4)) & 0x0f0f0f0f + x = (x | (x << 2)) & 0x33333333 + x = (x | (x << 1)) & 0x55555555 + return x | (x << 1) + lo_val, hi_val = _rep16(const_val), _rep16(const_val >> 16) + self.set_s(d, '0x%08xu' % lo_val, ('const', lo_val)) + self.set_s(d + 1, '0x%08xu' % hi_val, ('const', hi_val)) + return None + pipe = getattr(self, 'pipe', None) + if pipe is not None and hasattr(pipe, 'uses_bitreplicate'): + pipe.uses_bitreplicate = True + src_expr = self.u(ops[1]) + lo_expr = 'bitreplicate16(%s)' % src_expr + hi_expr = 'bitreplicate16(%s >> 16u)' % src_expr + if src_reg == d: + self.set_s(d + 1, hi_expr) + self.set_s(d, lo_expr) + else: + self.set_s(d, lo_expr) + self.set_s(d + 1, hi_expr) + return None def scalar_cmov(self, ops, mods, pair, name=None): """D = SCC ? S0 : D on plain SGPR destinations; SCC is unchanged.""" @@ -3766,6 +6727,16 @@ def scalar_select(self, ops, pair): low = [('s%d' % reg_range(t)[1]) if reg_range(t) and reg_range(t)[0] == 's' else t for t in ops] if pair and 'm0' in low: raise Unsupported('64-bit scalar operand m0') + r = reg_range(low[0]) + if not pair and getattr(self, 'kind', None) == 'cs' and r and r[0] == 's' and r[1] == r[2] <= 105: + # A select between descriptor-derived data (descnum, no run-time value) and constants, such as + # s_cselect_b32 sX, 0, sX, which can zero a buffer's size: record both arms and the offset whose SCC + # picks one. Nothing reads that symbol as a value (S, refuse_select_source, select_word), so neither + # arm is dropped. + arms = [self.select_arm(t) for t in low[1:]] + if None not in arms and any(arm[0] == 'descnum' for arm in arms): + self.set_s(r[1], None, ('descnum', 'cselect', self.pc, *arms)) + return expr = 'scc ? %s : %s' % (self.u(low[1]), self.u(low[2])) if low[0] == 'm0': self.sym.pop('m0', None) @@ -3787,6 +6758,28 @@ def scalar_select(self, ops, pair): self.masks.add(d) self.set_s(d + 1, '0u') + def select_arm(self, tok): + """An s_cselect_b32 source as a symbol: the descnum a register holds, ('const', value) for a literal or a + register holding a known constant, otherwise None.""" + r = reg_range(tok) + if r: + sym = self.sym.get(r[1]) if r[0] == 's' and r[1] == r[2] and r[1] <= 105 else None + return sym if sym and (sym[0] == 'descnum' or sym[0] == 'const' and len(sym) == 2) else None + value = self.const_u32(tok) + return None if value is None else ('const', value) + + def refuse_select_source(self, base, srcs): + """A scalar ALU source holding a select of descriptor data in any of its registers (the high word of a pair + too): a move copies the symbol, anything else would turn it into an unrelated descnum or descriptor edit, + losing the arm that SCC picks, so it refuses.""" + if base in ('s_mov_b32', 's_mov_b64'): + return + for tok in srcs: + r = reg_range(tok) + regs = ['m0'] if tok == 'm0' else range(r[1], r[2] + 1) if r and r[0] == 's' else () + if any(descriptor_select(self.sym.get(n)) for n in regs): + raise Unsupported('%s on a select of descriptor data' % base) + def smem_soffset(self, tok, record_use=True): """Runtime expression for an SMEM scalar offset operand (s0..s105 or m0).""" if tok == 'm0': @@ -3835,6 +6828,23 @@ def op_s_load_dwordx4(self, ops, mods, count=4): p = self.sym.get(base[1]) if not p or p[0] != 'ptr': raise Unsupported('s_load through s%d holding %s' % (base[1], p)) + if len(p) > 2 and p[1] == ('resheap',) and isinstance(p[2], tuple) and p[2][0] == 'per_lane': + if (getattr(self, 'kind', None) != 'cs' or count != 4 or into_vcc or imm is not None + or _lit_u32(smem_offset(ops[2])) != 0): + raise Unsupported('s_load of a resource heap record through %s' % (p,)) + if (base[1] in getattr(self, 'ptr_open_pairs', ()) + or self.sym.get(base[2]) != ('ptrhi', ('resheap',), p[2])): + raise Unsupported('s_load through s%d: its high word is not the matching advanced pair' % base[1]) + return self._capture_resheap_desc(dst, p[2][1], p[2][2]) + if len(p) > 2 and not isinstance(p[2], int): + # The 'added' mark (an add whose offset is not tracked, as in a program with branches): no byte offset. + raise Unsupported('s_load through s%d: the pointer was advanced by an untracked offset' % base[1]) + base_off = p[2] if len(p) > 2 else 0 # literal bytes added by s_add_u32 on the pointer + if (base_off or len(p) > 2) and p[1][0] in PTR64_SOURCES: + # An advanced 64-bit pointer needs its high word completed by the matching s_addc_u32; + # a table pointer is 32 bits wide and has no high word. + if base[1] in getattr(self, 'ptr_open_pairs', ()) or self.sym.get(base[1] + 1) != ptr_high_symbol(p[1], base_off): + raise Unsupported('s_load through s%d: its high word is not the matching advanced pair' % base[1]) # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. token = smem_offset(ops[2]) known = self.const_soffset(token) if p[1] != ('smpheap',) else None @@ -3856,12 +6866,10 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) buf = self.pipe.resource((p[1], None), 'buf') for i in range(count): - self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) + self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, base_off + off + 4 * i)) return - # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a - # pointer may read different words under the same (source, offset). In a compute or vertex stage (the - # stages that accept a raw descriptor conversion before a store) those loads are told apart by the - # offset of the s_load; loads through the untouched pair keep one identity. + # A compute or vertex raw-store conversion must distinguish loads through different high words + # even when the source and byte offset match. Keep the load PC for a changed pointer pair. # A 32-bit table pointer carries a high word the program sets to a constant: loads through the same # untouched low word and the same constant read the same words (tag -1 - constant). hi = self.sym.get(base[1] + 1) @@ -3872,16 +6880,14 @@ def op_s_load_dwordx4(self, ops, mods, count=4): else: load = (self.pc,) for i in range(count): - self.sym[dst[1] + i] = ('desc', p[1], off, i) + load + self.sym[dst[1] + i] = ('desc', p[1], base_off + off, i) + load if into_vcc: - self.vcc_lost = True - self.vcc_descriptor_overwritten = False - if getattr(self, 'has_branches', False): - value = tuple(self.sym.get(i) for i in (106, 107)) - self.vcc_events.setdefault(self.pc, []).append(('load_descriptor', value)) + self.mark_vcc_descriptor() return if into_vcc: raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) + if base_off: + raise Unsupported('s_load through %s advanced by %#x' % (p[1], base_off)) if p[1] == ('smpheap',): if self.pipe.sampler_heap and count == 4: # A sampler picked at run time from the sampler heap: keep the byte offset in the @@ -3904,8 +6910,47 @@ def op_s_load_dwordx4(self, ops, mods, count=4): self.sym[dst[1] + i] = ('const', 0, 'unassigned') self.pipe.notes.add('dynamic sampler index replaced by a default sampler') return + if p[1] == ('resheap',) and getattr(self, 'kind', None) == 'cs': + return self.heap_record(dst, base, token, imm, count) raise Unsupported('s_load with a register offset through %s' % (p[1],)) + def _capture_resheap_desc(self, dst, expr, bound): + if not hasattr(self, 'resheap_index_temps'): + self.resheap_index_temps = [] + temp = 'h%d' % len(self.resheap_index_temps) + self.resheap_index_temps.append(temp) + self.emit('%s = %s;' % (temp, expr)) + source = ('resheap', 'per_lane', temp, bound) + for i in range(4): + self.sym[dst[1] + i] = ('desc', source, 0, i) + + def heap_record(self, dst, base, token, imm, count): + """s_load_dwordx4 D, <resource heap pointer>, R in a compute program, where R is an index shifted left by 5 + with no later write of R and no branch target in between: D is the buffer descriptor in the 32-byte heap + record that the index names. The index is a root constant word, or a word an s_buffer_load read from an + unmodified table buffer at a literal byte offset or at a root constant word times a literal plus a literal + (the marks, see mark_heap_index, end at a branch target), or a bounded per-lane index in a proven waterfall + loop. Only these exact forms are modelled.""" + what = 's_load of a resource heap record' + r = reg_range(token) + index = getattr(self, 'heap_index', {}).get(r[1]) if r and r[0] == 's' and r[1] == r[2] else None + if index == ('buffer',): + raise Unsupported('%s whose index is read from a buffer other than a table buffer at a dispatch-constant ' + 'offset' % what) + if not index or index[0] not in ('rootconst', 'buffer', 'per_lane'): + raise Unsupported('%s whose offset is not a root constant shifted left by 5 since the last branch target' % what) + if count != 4: + raise Unsupported('%s of %d dwords' % (what, count)) + if imm is not None: + raise Unsupported('%s with offset:%#x' % (what, imm)) + if self.sym.get(base[2]) != ('const', 0): + raise Unsupported('%s through a pointer whose high word is not a constant zero' % what) + if index[0] == 'per_lane': + return self._capture_resheap_desc(dst, index[1], index[2]) + source = ('resheap',) + index[1:] if index[0] == 'rootconst' else ('resheap', 'word') + index[1:] + for i in range(count): + self.sym[dst[1] + i] = ('desc', source, 0, i) + def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" if len(ops) != 3: @@ -3915,6 +6960,8 @@ def op_s_bfm_b32(self, ops, mods): r = reg_range(o) if r and r[0] == 's': vals.append(self.is_const(r[1])) + elif o == 'null': + vals.append(0) else: try: vals.append(int(o, 0)) @@ -3929,7 +6976,16 @@ def op_s_bfm_b32(self, ops, mods): self.sym.pop('m0', None) self.emit('m0 = %s;' % expr) return None - d = reg_range(ops[0])[1] + if ops[0] == 'null': + if any(self.is_lane_mask(t) for t in ops[1:3]): + raise Unsupported('s_bfm_b32 into null on a lane mask') + self.u(ops[1]) + self.u(ops[2]) + return None + dst = reg_range(ops[0]) + if not dst: + raise Unsupported('s_bfm_b32 destination %s' % ops[0]) + d = dst[1] if None not in vals: value = (((1 << (vals[0] & 31)) - 1) << (vals[1] & 31)) & 0xffffffff self.set_s(d, '0x%08xu' % value, ('const', value)) @@ -3937,8 +6993,64 @@ def op_s_bfm_b32(self, ops, mods): self.set_s(d, '(((1u << (%s & 31)) - 1) << (%s & 31))' % (self.u(ops[1]), self.u(ops[2]))) return None + def op_s_bfm_b64(self, ops, mods): + """s_bfm_b64: D.u64 = ((1ULL << S0.u[5:0]) - 1) << S1.u[5:0], SCC unchanged. + + Unlike the mask-style 64-bit scalar ops (which keep one lane bit), this is a real 64-bit value, so both + destination words are written. The width is masked to six bits here and the offset inside shl64, which + also drops the bits shifted past bit 63; every HLSL shift count stays below 32.""" + if mods: + raise Unsupported('s_bfm_b64 with %s' % (mods,)) + if len(ops) != 3: + raise Unsupported('s_bfm_b64 with %d operands, expected 3' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[1] % 2 or dst[2] > 105: + raise Unsupported('s_bfm_b64 destination %s' % ops[0]) + vals = [] + for o in ops[1:]: + r = reg_range(o) + if o in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') or ( + r and (r[0] != 's' or r[1] != r[2] or r[1] > 105)): + raise Unsupported('s_bfm_b64 source %s' % o) + if r and r[1] in self.masks: + # A lane mask is not a number. Every source is read and checked before any destination state + # changes, so a source aliasing the destination cannot lose its mask flag first. + raise Unsupported('s_bfm_b64 source %s holds a lane mask' % o) + if r: + vals.append(self.is_const(r[1])) + else: + try: + vals.append(int(o, 0)) + except ValueError: + vals.append(None) + d = dst[1] + if None in vals: + width, offset = self.u(ops[1]), self.u(ops[2]) # may refuse; still before any write + # Both words are uniform only if both sources are. Judged before the destination changes, so an aliased + # source is classified by its old value and an older proof for s[d] or s[d+1] cannot survive. + uniform = self.tracks_uniformity() and all(self.uniform_source(o) for o in ops[1:]) + self.masks.discard(d) + self.masks.discard(d + 1) + if None not in vals: + value = (((1 << (vals[0] & 63)) - 1) << (vals[1] & 63)) & 0xffffffffffffffff + for i, word in enumerate((value & 0xffffffff, value >> 32)): + self.set_s(d + i, '0x%08xu' % word, ('const', word)) + return None + # Both words come from locals computed before either destination is written, so a source may be the destination. + self.sym.pop(d, None) + self.sym.pop(d + 1, None) + if self.tracks_uniformity(): + for word in (d, d + 1): + self.record_scalar_uniformity(word, uniform) + self.used_s.update((d, d + 1)) + self.emit('{ uint bw = %s & 63u; uint2 t = shl64(bw >= 32u ? 0xffffffffu : (1u << (bw & 31u)) - 1u, ' + 'bw >= 32u ? (1u << (bw & 31u)) - 1u : 0u, %s); s%d = t.x; s%d = t.y; }' % (width, offset, d, d + 1)) + return None + def scalar_const(self, tok): """Value of a 32-bit scalar source that is known at translation time, else None.""" + if tok == 'null': + return 0 r = reg_range(tok) if r: return self.is_const(r[1]) if r[0] == 's' and r[1] == r[2] else None @@ -3969,7 +7081,7 @@ def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=Non r0 = reg_range(ops[1]) if r0 and r0[0] != 's': raise Unsupported('%s source %s' % (name, ops[1])) - low, high = self.i64_words(ops[1]) + low, high = self.i64_words(ops[1], helper == 'shr64i' or signed is True, True) known = [self.scalar_const('s%d' % r0[1]), self.scalar_const('s%d' % r0[2])] if r0 else [ int(low[:-1]), int(high[:-1])] else: @@ -3997,10 +7109,13 @@ def scalar_wide_op(self, name, ops, mods, wide_src, wide_dst, helper, signed=Non self.emit('{ uint t = %s(%s, %s%s); s%d = t; scc = t != 0u; }' % (helper, low, amount, sg, d)) for r in range(d, d + width): self.sym.pop(r, None) + if isinstance(self.align4_s, set): + self.align4_s.discard(r) self.used_s.add(r) if self.tracks_uniformity(): (self.varying_s.discard if uniform else self.varying_s.add)(r) self.scc_effect = 'emitted' + self.scc_verified = True if self.tracks_uniformity(): self.scc_uniform = uniform return None @@ -4060,12 +7175,27 @@ def op_s_buffer_load_dword(self, ops, mods, count=1): if sreg and offset == ('s%d' % sreg[1]) and dst[1] <= sreg[1] < dst[2]: self.emit('a = %s;' % offset) offset = 'a' + # A word read from an unmodified table buffer at a literal offset or at a root constant word times a literal + # plus a literal is the same for the whole dispatch: heap_record names it by (table parameter, table byte, + # root constant parameter and word or None, scale, byte offset). Any other buffer word is only marked. + where = () + if hasattr(self, 'heap_index'): + key, r, sreg = self.descriptor(ops[1]), reg_range(ops[1]), reg_range(token) + first = self.sym.get(r[1]) + at = (None, None, 0, val) if is_lit else self.heap_word_offset( + token, self.sym.get(sreg[1]) if sreg and sreg[0] == 's' else None) + if (at and at[2] % 4 == 0 and (at[3] + extra) % 4 == 0 # a dword-aligned word for any root constant + and first[0] == 'desc' and key[0][0] == 'table' and key not in getattr(self.pipe, 'modified', ()) # probes build a bare pipe + and all(self.sym.get(r[1] + n) == first[:3] + (first[3] + n,) + first[4:] for n in range(4))): + where = key[0][1:] + key[1:] + at[:3] + (at[3] + extra,) # All words use the original offset, even when a destination overwrites its register. uniform = self.tracks_uniformity() and self.uniform_source(token) for i in range(count): self.set_s(dst[1] + i, '%s.Load(%s + %d)' % (buf, offset, extra + 4 * i), uniform=uniform) if is_lit: self.sym[dst[1] + i] = ('fixed_buffer_word',) + if hasattr(self, 'heap_index'): + self.heap_index[dst[1] + i] = ('bufword',) + (where[:5] + ((where[5] + 4 * i) & 0xffffffff,) if where else ()) def op_s_buffer_load_dwordx2(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 2) @@ -4079,7 +7209,7 @@ def op_s_buffer_load_dwordx8(self, ops, mods): def op_s_buffer_load_dwordx16(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 16) - def buffer_address(self, ops, mods): + def buffer_address(self, ops, mods, *, is_formatted=False): # MUBUF and MTBUF share the same address calculation: optional index * stride (idxen), # optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate # offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe @@ -4092,7 +7222,14 @@ def buffer_address(self, ops, mods): raise Unsupported('buffer modifier %s' % m) if len(ops) != 4: raise Unsupported('buffer load with %d operands, expected 4' % len(ops)) - key = self.descriptor(ops[2]) + idxen, offen = 'idxen' in mods, 'offen' in mods + what = 'indexed load' if idxen else 'buffer load' + if not is_formatted: + key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=not idxen) + else: + key = self.descriptor(ops[2]) + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane') and idxen: + raise Unsupported('indexed load through a per-lane resource heap descriptor') buf = self.pipe.resource(key, 'buf') soffset = None if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): @@ -4102,10 +7239,9 @@ def buffer_address(self, ops, mods): if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: raise Unsupported('buffer soffset %s' % ops[3]) soffset = self.S(sreg[1]) - idxen, offen = 'idxen' in mods, 'offen' in mods terms = [] if idxen and offen: - if key in self.pipe.modified: + if key in getattr(self.pipe, 'modified', ()): raise Unsupported('indexed load through a modified descriptor') r = reg_range(ops[1]) if not r or r[0] != 'v' or r[2] - r[1] != 1 or r[2] > 255: @@ -4114,18 +7250,18 @@ def buffer_address(self, ops, mods): terms.append('%s * ud%d' % (self.u('v%d' % r[1]), stride)) terms.append(self.u('v%d' % r[2])) elif idxen: - if key in self.pipe.modified: + if key in getattr(self.pipe, 'modified', ()): raise Unsupported('indexed load through a modified descriptor') r = reg_range(ops[1]) if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: raise Unsupported('buffer vaddr %s for idxen' % ops[1]) stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) - terms.append('%s * ud%d' % (self.u(ops[1]), stride)) + terms.append('%s * ud%d' % (getattr(self, 'uniform_vaddr', None) or self.u(ops[1]), stride)) elif offen: r = reg_range(ops[1]) if not r or r[0] != 'v' or r[1] != r[2] or r[1] > 255: raise Unsupported('buffer vaddr %s for offen' % ops[1]) - terms.append(self.u(ops[1])) + terms.append(getattr(self, 'uniform_vaddr', None) or self.u(ops[1])) elif ops[1] != 'off': raise Unsupported('buffer vaddr %s without idxen or offen' % ops[1]) if soffset is not None: @@ -4154,6 +7290,74 @@ def op_buffer_load_dwordx3(self, ops, mods): def op_buffer_load_dwordx4(self, ops, mods): self.op_buffer_load_dword(ops, mods, 4) + def op_global_load_dword(self, ops, mods): + # Compute-stage one-dword GLOBAL load in the saddr form (RDNA 2 ISA §9.2, LLVM 15 SelectGlobalSAddr): + # ADDR = SADDR[63:0] + zext(VADDR[31:0]) + sext(OFFSET[11:0]), where SADDR is a proven 64-bit root + # buffer pointer pair s[base:base+1] (optionally copied or advanced by completed literal s_add_u32 / + # s_addc_u32). Modifiers are checked before the operand count so the two-operand `lds` form refuses on + # its modifier rather than arity. + if getattr(self, 'kind', None) != 'cs': + raise Unsupported('global_load_dword') + offset = 0 + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'-?(?:0x[0-9a-f]+|\d+)', m[7:]): + imm = int(m[7:], 0) + if not -2048 <= imm <= 2047: + raise Unsupported('global load offset %s' % m[7:]) + offset += imm + elif m not in ('glc', 'slc', 'dlc'): + raise Unsupported('global load modifier %s' % m) + if len(ops) != 3: + raise Unsupported('global load with %d operands, expected 3' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('global load destination %s' % ops[0]) + if ops[2] == 'off': + raise Unsupported('global load without a scalar address pair') + base = reg_range(ops[2]) + if not base or base[0] != 's' or base[2] - base[1] != 1 or base[1] % 2 or base[2] > 105: + raise Unsupported('global load base %s' % ops[2]) + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('global load vaddr %s' % ops[1]) + p = self.sym.get(base[1]) + if not p or p[0] != 'ptr': + raise Unsupported('global load through s%d holding %s' % (base[1], p)) + if len(p) > 2 and not isinstance(p[2], int): + raise Unsupported('global load through s%d: the pointer was advanced by an untracked offset' % base[1]) + if p[1][0] != 'root': + raise Unsupported('global load through %s' % (p[1],)) + base_off = p[2] if len(p) > 2 else 0 + if not isinstance(base_off, int) or isinstance(base_off, bool) or base_off < 0: + raise Unsupported('global load through s%d: invalid pointer byte offset %r' % (base[1], base_off)) + if base[1] in getattr(self, 'ptr_open_pairs', ()) or self.sym.get(base[2]) != ptr_high_symbol(p[1], base_off): + raise Unsupported('global load through s%d: its high word is not the matching pair' % base[1]) + # RDNA 2 low-bit GLOBAL alignment depends on SH_MEM_CONFIG.ALIGNMENT_MODE (DWORD rounds down, STRICT / + # DWORD_STRICT faults, UNALIGNED gathers across neighbouring DWORDs; Scarlett's setting is unmeasured), + # and HLSL ByteAddressBuffer.Load requires a multiple of four. Require proven 4-byte-aligned components. + if offset % 4: + raise Unsupported('global load at unaligned immediate offset %d' % offset) + if base_off % 4: + raise Unsupported('global load through s%d at unaligned pointer offset %d' % (base[1], base_off)) + if not self.operand_align4(ops[1]): + raise Unsupported('global load vaddr %s is not proven 4-byte aligned' % ops[1]) + total_off = base_off + offset + if total_off > 0xffffffff or total_off < -0xffffffff: + raise Unsupported('global load byte offset %#x' % total_off) + buf = self.pipe.resource((p[1], None), 'buf') + # Guard the signed 64-bit view-relative byte offset (zext(vaddr) + base_off + sext(offset)) against + # [0, 0xffffffff] before converting to a 32-bit ByteAddressBuffer offset so overflow above 4 GiB or + # underflow below base cannot wrap into an in-bounds word of a bounded root view. + self.emit('a = %s;' % self.u(ops[1])) + if total_off > 0: + load_expr = '(a <= 0x%08xu ? %s.Load(a + %du) : 0u)' % (0xffffffff - total_off, buf, total_off) + elif total_off < 0: + mag = -total_off + load_expr = '(a >= %du ? %s.Load(a - %du) : 0u)' % (mag, buf, mag) + else: + load_expr = '%s.Load(a)' % buf + self.set_v(dst[1], load_expr) + def op_buffer_store_vs(self, ops, mods, count): # Vertex-stage store in the `off` form: scalar byte offset plus the 12-bit immediate, through a # descriptor read from a fixed root-table slot, written to a RWByteAddressBuffer (issue #1723). @@ -4196,6 +7400,37 @@ def op_buffer_store_vs(self, ops, mods, count): self.emit('a = (%s%d) & 0xfffffffcu;' % (soffset, offset) if soffset else 'a = %d;' % offset) self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) + def load_descriptor(self, tok, what, *, stride0_ok=False, raw_conversion_ok=False): + """Resource key for a 4-word buffer load descriptor operand, checking for unproved modifications. + + A descriptor modification is accepted only for proven safe transformations: + - stride0_ok: Allows word 1 (STRIDE[29:16]) to be zeroed via `s_and_b32 ... 0xc000ffff`. + Permitted on non-indexed buffer loads (offen or off) where byte addressing is used and + the hardware stride field is not consulted. + - raw_conversion_ok: Allows the complete RDNA2 structured-to-raw buffer conversion: + word 1 stride zeroed (`stride0`), word 2 scaled by the extracted stride (`byte_count`), + and word 3 OOB_SELECT set to raw mode (`oob3` via 0x30000000). Permitted when the load + is non-indexed and the resulting byte range is validated. + Any other scalar ALU modifications or unproven overwrites raise Unsupported. + """ + key = self.descriptor(tok) + rsrc = reg_range(tok) + first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 3 else None + if first and first[0] == 'desc': + loaded = tuple(desc_word(first, first[3] + k) for k in range(4)) + actual = tuple(self.sym.get(rsrc[1] + k) for k in range(4)) + valid = names_one_value(first) and actual == loaded + if names_one_value(first) and stride0_ok: + cleared = loaded[1] + ('stride0',) + valid = valid or actual == (loaded[0], cleared, *loaded[2:]) + if not valid and raw_conversion_ok: + valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + if (not valid or key in getattr(self.pipe, 'other_modified', ()) + or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)): + raise Unsupported('%s through a modified descriptor' % what) + return key + return key + def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False): """Resource key for a single loaded descriptor or a proven raw transformation of it.""" rsrc = reg_range(tok) @@ -4212,12 +7447,12 @@ def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok if not valid and raw_conversion_ok: valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) if (not valid or key in getattr(self.pipe, 'other_modified', ()) - or (key in self.pipe.modified and not stride0_ok)): + or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)): raise Unsupported('%s through a modified descriptor' % what) return key def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, - raw_conversion_ok=False): + raw_conversion_ok=False, uniform_off=False): """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" offset = 0 glc = False @@ -4229,7 +7464,7 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa elif m != 'offen': raise Unsupported('%s modifier %s' % (kind_label, m)) offen = 'offen' in mods - if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): + if len(ops) != 4 or not (offen or ops[1] == 'off' and (allow_scalar_address and glc or uniform_off)): raise Unsupported('%s without the offen address form' % kind_label) data = reg_range(ops[0]) if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: @@ -4241,7 +7476,7 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) terms = [self.u(ops[1])] if offen else [] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): - if not offen: + if not offen and not uniform_off: raise Unsupported('%s off requires a scalar register soffset' % kind_label) offset += int(ops[3], 0) else: @@ -4263,7 +7498,12 @@ def op_buffer_store_dword(self, ops, mods, count=1): return self.op_buffer_store_vs(ops, mods, count) if self.kind != 'cs': raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal - src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) + src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True, + uniform_off=True) + # The `off` form (no VGPR address, MUBUF offen = idxen = 0) gives every lane the same byte address, so the + # lanes race; with one proven value in all of them any order stores the same words. + if ops[1] == 'off' and not all(self.proven_uniform_v(n) for n in range(src[1], src[2] + 1)): + raise Unsupported('buffer store off with data not proven wave-uniform') words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: @@ -4444,6 +7684,10 @@ def op_s_swappc_b64(self, ops, mods): raise Unsupported('vertex stage calls a fetch routine and the pipeline declares no input layout') base = self.pipe.ud(('basevertex',)) for e in self.pipe.vs_fetch: + if e.get('empty'): + for i in range(e['count']): + self.set_v(e['vgpr'] + i, '0u') + continue key = (('vbtab',), 16 * e['slot']) buf = self.pipe.resource(key, 'buf') stride = self.pipe.ud(('stride', self.pipe.resources[key]['index'])) @@ -4526,9 +7770,32 @@ def formatted_pointer_copy(self, pointer, before): return None return source[1], index + def spill_word_proven(self, reg, sym): + """True when the descriptor word held in s<reg> would pass the formatted-load provenance proof here: it is + still in the entry block, or it is a word of one untouched local table load (or an already proven reload).""" + if sym[0] != 'desc' or not getattr(self, 'past_entry', False): + return True + return self.formatted_descriptor_from_block(('s', reg, reg), sym) + def formatted_descriptor_from_block(self, reg, first): - """Require one untouched local load and a table pointer that no incoming path can rewrite.""" + """Require one untouched local load and a table pointer that no incoming path can rewrite. A word written + by a v_readlane_b32 reload counts when every v_writelane_b32 that can supply it passed this same proof.""" + if not first: + return False start, end = self.descriptor_block_first, self.descriptor_instruction_index + reloads = {} + for w in range(reg[1], reg[2] + 1): + for at in range(end - 1, start - 1, -1): + _, _, name, asm = self.ins[at] + if w in self.descriptor_scalar_writes(name, parse(asm)[1]): + if re.sub(r'_e(32|64)$', '', name) == 'v_readlane_b32': + reloads[w] = at + break + if reloads: + return all( + getattr(self, 'reload_proven', {}).get(reloads[w], False) if w in reloads else + self.formatted_descriptor_from_block(('s', w, w), self.sym.get(w)) for w in range(reg[1], reg[2] + 1)) + width = reg[2] - reg[1] + 1 block = self.ins[start:end] words = set(range(reg[1], reg[2] + 1)) for index in range(len(block) - 1, -1, -1): @@ -4538,7 +7805,7 @@ def formatted_descriptor_from_block(self, reg, first): continue m = re.fullmatch(r's_load_dwordx(4|8|16)', name) load = reg_range(args[0]) - if not m or not load or load[1] + first[3] != reg[1] or int(m.group(1)) < first[3] + 4: + if not m or not load or load[1] + first[3] != reg[1] or int(m.group(1)) < first[3] + width: return False base = reg_range(args[1]) if not base or base[0] != 's': @@ -4574,7 +7841,7 @@ def mubuf_format(self, ops, mods, count): For compute, the caller must validate the native descriptor and reachable byte addresses, and bind the SRV and entry constants from that same descriptor snapshot. """ - buf, address = self.buffer_address(ops, mods) + buf, address = self.buffer_address(ops, mods, is_formatted=True) dst = reg_range(ops[0]) if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != count or dst[2] > 255: raise Unsupported('formatted buffer load destination %s for %d components' % (ops[0], count)) @@ -4799,22 +8066,71 @@ def image(self, ops, mods, how): raise Unsupported('image instruction without %s' % ('dim:' if not dims else 'dmask:')) dim = dims[0][4:] dmask = int(dmasks[0][6:], 0) - kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} + kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da', + 'SQ_RSRC_IMG_CUBE': 'texcube'} if dim not in kinds: raise Unsupported('image dimension %s' % dim) + # A cube sample addresses the face coordinates s and t and then the face id (#2943). The face coordinates + # are sc/|ma| + 1.5 and tc/|ma| + 1.5 with ma the v_cubema value, twice the major coordinate (Mesa + # ac_nir_lower_tex.c prepare_cube_coords; LLVM ConstantFoldAMDGCNCubeIntrinsic), so both lie in [1, 2]. + # The lowering rebuilds a direction for TextureCube (x2w_cube_dir). Loads, derivative and LOD queries, + # packed addresses and compute stages have no TextureCube equivalent here and are refused by name. + cube = dim == 'SQ_RSRC_IMG_CUBE' + if cube: + if how in ('load', 'load_mip'): + raise Unsupported('image dimension SQ_RSRC_IMG_CUBE: Load is not defined on a TextureCube') + if how == 'd': + raise Unsupported('image_sample_d on SQ_RSRC_IMG_CUBE: cube derivatives are not converted') + if how == 'get_lod': + raise Unsupported('image_get_lod on SQ_RSRC_IMG_CUBE') + for flag in ('a16', 'd16'): + if flag in mods: + raise Unsupported('image_sample%s on SQ_RSRC_IMG_CUBE with %s' + % ('' if how == 'sample' else '_' + how, flag)) + if getattr(self, 'kind', None) == 'cs': + raise Unsupported('cube image in a compute program (no texcube SRV binding)') # A 2D array takes the slice as its third address component, where a volume takes z. Sample and # Load on a Texture2DArray take it in the same place, so only the declared type differs. one = dim == 'SQ_RSRC_IMG_1D' - three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY') + three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY', 'SQ_RSRC_IMG_CUBE') coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] - if one and (how != 'sample' or len(cs) != 1 or not dmask or any(not m.startswith(('dim:', 'dmask:')) for m in mods)): - raise Unsupported('unverified 1D image sample address or modifiers') + # A 1D image has one coordinate. sample_lz and sample_l carry the explicit level in the next + # address dword, so their address is x then level; Texture1D.SampleLevel takes the location as a + # float, which is what the `one` branch below builds. Anything else stays refused by name. + if one: + expected = {'sample': 1, 'lz': 1, 'l': 2}.get(how) + if expected is None or len(cs) != expected or not dmask: + raise Unsupported('unverified 1D image %s address or modifiers' % how) + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or (how != 'sample' and m in ('dlc', 'glc', 'slc'))): + raise Unsupported('1D image %s modifier %s' % (how, m)) lod = bias = None + grads = None + if how == 'd': + # Address dwords are ddx then ddy (one per coordinate axis each) and then the coordinates, so a 2D + # sample is six registers, a 2D array seven and a volume nine. Offsets, bias, clamp, a16 and the + # other layout-changing modifiers are refused; only cache-policy bits are accepted. + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('image_sample_d modifier %s' % m) + if dmask == 0: + raise Unsupported('image_sample_d with an empty dmask') + if one: + raise Unsupported('image_sample_d on a 1D image') + axes = 3 if dim == 'SQ_RSRC_IMG_3D' else 2 + want = 3 * axes + (1 if dim == 'SQ_RSRC_IMG_2D_ARRAY' else 0) + if want == 9 and len(cs) == 16 and not ops[1].startswith('['): + # A contiguous nine-dword volume address is encoded as a sixteen-register range; the rest is padding. + cs = cs[:9] + if len(cs) != want: + raise Unsupported('image_sample_d with %d address registers' % len(cs)) + grads = (cs[:axes], cs[axes:2 * axes]) + cs = cs[2 * axes:] if how in ('l', 'b'): # image_sample_l: the address dwords are the coordinates and then the explicit level. image_sample_b: # the RDNA 2 ISA (section 8.2.5, "{ offset } { bias } { z-compare } { derivative } { body }") puts one @@ -4829,29 +8145,45 @@ def image(self, ops, mods, how): raise Unsupported('%s modifier %s' % (name, m)) if dmask == 0: raise Unsupported('%s with an empty dmask' % name) - if len(cs) != (4 if three else 3): + expected = 4 if three else (2 if one else 3) + if len(cs) != expected: raise Unsupported('%s with %d address registers' % (name, len(cs))) if how == 'l': lod, cs = cs[-1], cs[:-1] else: # The bias is added to the LOD derived from the coordinate derivatives of the pixel quad: only a - # pixel stage that still runs with its entry mask has them. Elsewhere the plain sample is lowered - # to level 0, which would drop the bias, so the bias form is refused instead. - if self.kind != 'ps' or not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_sample_b needs implicit derivatives: pixel stage, entry mask, no branches') + # pixel stage that still runs with its entry mask and wave-uniform control flow has them. + # Elsewhere the plain sample is lowered to level 0, which would drop the bias, so the bias form is + # refused instead. A uniform join (scc with scc_uniform) or later loop does not drop the proof + # (M200-01 B/L). Divergent EXEC or a vcc/exec-conditioned branch before the sample stays refused. + if (self.kind != 'ps' or not self.derivative_exec_ok() or + not getattr(self, 'uniform_cf', True)): + raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC ' + 'mask and wave-uniform control flow') + if hasattr(self, 'derivative_sites'): + self.derivative_sites.append((self.pc, 'image_sample_b')) + if not self.exec_known and not self.uniform_bias(cs[0]): + # Past a divergent EXEC the op is only drawn with one bias for the quad (tests/startup_image_sample_b_ + # flow_check.py); a bias that differs per lane (a join of different values) stays refused by name. + raise Unsupported('image_sample_b with a per-lane bias past a divergent EXEC') bias, cs = cs[0], cs[1:] if how == 'get_lod': - # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp - # (Mesa nir_texop_lod, which ACO emits as image_get_lod; GLSL textureQueryLod x/y). Only the 2D form with - # two address registers and dmask 0x1-0x3 is lowered; the cache-policy bits are the only other modifiers. + # Mesa nir_texop_lod returns the clamped LOD followed by the computed LOD. + # DXIL CalculateLOD uses only spatial coordinates, including on Texture2DArray; + # the guest array form still consumes a third address register for the slice. for m in mods: if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): raise Unsupported('image_get_lod modifier %s' % m) - if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: + want_addr = 3 if dim == 'SQ_RSRC_IMG_2D_ARRAY' else 2 + if (self.kind != 'ps' or dim not in ('SQ_RSRC_IMG_2D', 'SQ_RSRC_IMG_2D_ARRAY') or + not dmask or dmask & ~3 or len(cs) != want_addr): raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known or len(self.blocks) > 0: - raise Unsupported('image_get_lod needs implicit derivatives: pixel stage, entry mask, no branches') + if not self.derivative_exec_ok() or not getattr(self, 'uniform_cf', True): + raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC ' + 'mask and wave-uniform control flow') + if hasattr(self, 'derivative_sites'): + self.derivative_sites.append((self.pc, 'image_get_lod')) desc_key = self.descriptor(ops[2]) tex = self.pipe.resource(desc_key, kinds[dim]) if how in ('load', 'load_mip'): @@ -4904,6 +8236,16 @@ def image(self, ops, mods, how): heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) name = 'image_sample' + ('' if how == 'sample' else '_' + how) + if cube and words and (words[0] >> 28) & 1: + # SQ_IMG_SAMP_WORD0 bit 28 DISABLE_CUBE_WRAP (Mesa src/amd/registers/gfx10-rsrc.json): filtering then + # stops at a face edge, while a D3D12 TextureCube always filters across faces. With the bit clear both + # wrap across faces. A heap or register sampler is not read here, so its bit is not validated. + raise Unsupported('%s on SQ_RSRC_IMG_CUBE with DISABLE_CUBE_WRAP' % name) + sjoin = None + if dim == 'SQ_RSRC_IMG_2D' and how in ('l', 'lz') and not packed_2d and not heap and words is None: + r = reg_range(ops[3]) + if r and r[0] == 's' and r[2] == r[1] + 3: + sjoin = getattr(self, 'sampler_joins', {}).get(r[1]) if how == 'b': # The guest clamps the biased LOD to the sampler's MIN_LOD and MAX_LOD. Only a constant descriptor # can be read here, and only its limits are carried to the static sampler (line smpl), so a sampler @@ -4916,12 +8258,14 @@ def image(self, ops, mods, how): if heap or not words or self.default_sampler_words(words): raise Unsupported('image_get_lod with a sampler that is not constant (LOD limits and bias unknown)') smp = self.pipe.sampler(tuple(self.lod_sampler_words('image_get_lod', words)), lod_limits=True) - elif how in ('sample', 'l', 'lz') and (heap or (words and self.default_sampler_words(words))): + elif sjoin is not None: + smp = None + elif how in ('sample', 'l', 'lz', 'd') and (heap or (words and self.default_sampler_words(words))): # A heap sampler, or the fixed default that stands in for one, keeps its unbounded static LOD range: the # descriptor is read at run time, so its MIN_LOD, MAX_LOD and bias are not validated here (#2221). self.pipe.lod_unvalidated.add(name) smp = heap or self.pipe.sampler(tuple(words)) - elif how in ('sample', 'l', 'lz') and words: + elif how in ('sample', 'l', 'lz', 'd') and words: # A constant descriptor carries its LOD limits like image_sample_b, under the same bias and range # validation. A mip filter of 0 (base level only) keeps the ordinary sampler, as before: refusing it # would drop every pipeline with an all-zero inline sampler, and only the bias form needs it refused. @@ -4934,14 +8278,23 @@ def image(self, ops, mods, how): uv = 'float2(f16tof32(%s), f16tof32(%s >> 16))' % (packed, packed) elif one: uv = self.f(cs[0]) - elif three: + elif cube: + self.pipe.uses_cube_dir = True + uv = 'x2w_cube_dir(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) + elif three and how != 'get_lod': uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) else: uv = 'float2(%s, %s)' % (self.f(cs[0]), self.f(cs[1])) if how == 'sample' and self.kind == 'cs': # A compute lane has no pixel quad to supply derivatives; level 0 would be a guess. raise Unsupported('image_sample with implicit LOD in a compute program') - if how == 'l': + if how == 'd': + axes = len(grads[0]) + dx, dy = ['float%d(%s)' % (axes, ', '.join(self.f(r) for r in g)) for g in grads] + call = '%s.SampleGrad(%s, %s, %s, %s)' % (tex, smp, uv, dx, dy) + elif sjoin is not None: + call = self.joined_sampler_call(tex, ops[3], sjoin, uv, self.f(lod) if how == 'l' else '0', name) + elif how == 'l': call = '%s.SampleLevel(%s, %s, %s)' % (tex, smp, uv, self.f(lod)) elif how == 'b': # SampleBias adds the bias to the implicit LOD, like the ISA's _B suffix ("Add this BIAS to the LOD @@ -4949,12 +8302,19 @@ def image(self, ops, mods, how): # sample_b_sampler. call = '%s.SampleBias(%s, %s, %s)' % (tex, smp, uv, self.f(bias)) elif how == 'get_lod': - # HLSL CalculateLevelOfDetail (clamped) and CalculateLevelOfDetailUnclamped (SM 4.1+). Which clamps - # each side applies besides the sampler's (the view's mip range) is assumed to agree. + # The view mip-range clamp is assumed to agree on both sides. call = 'float4(%s.CalculateLevelOfDetail(%s, %s), %s.CalculateLevelOfDetailUnclamped(%s, %s), 0.0, 0.0)' % ( tex, smp, uv, tex, smp, uv) - elif how == 'lz' or not self.exec_known or self.kind != 'ps' or len(self.blocks) > 0: + elif how == 'lz' or not self.exec_known or self.kind != 'ps': call = '%s.SampleLevel(%s, %s, 0)' % (tex, smp, uv) + elif len(self.blocks) > 0: + # Past a join the guest still takes the LOD from the quad's derivatives. Where the rule of image_sample_b + # holds (entry EXEC, wave-uniform control flow, no divergent back edge over the call) the call is the + # implicit-LOD Sample; otherwise it stays level 0 (resolve_plain_samples). + call = '%s.SampleLevel(%s, %s, 0)' % (tex, smp, uv) + if getattr(self, 'uniform_cf', True) and hasattr(self, 'plain_samples'): + self.plain_samples[self.pc] = (call, '%s.Sample(%s, %s)' % (tex, smp, uv)) + call = 'X2W_PLAIN_SAMPLE<%x>' % self.pc else: call = '%s.Sample(%s, %s)' % (tex, smp, uv) self.emit('t = %s;' % call) @@ -5093,6 +8453,12 @@ def lod_sampler_words(self, name, words, mip_filter_none_ok=False): def op_image_sample_b(self, ops, mods): self.image(ops, mods, 'b') + def op_image_sample_d(self, ops, mods): + self.image(ops, mods, 'd') + + def op_image_sample_c_d(self, ops, mods): + raise Unsupported('image_sample_c_d: SampleCmpGrad needs shader model 6.8; only c and c_lz are lowered') + def op_image_get_lod(self, ops, mods): self.image(ops, mods, 'get_lod') @@ -5115,17 +8481,145 @@ def fixed_table_image(self, operand, name): raise Unsupported('%s through a modified image descriptor' % name) return self.descriptor(operand) + def bvh_descriptor(self, tok): + """The binding key and literal words of an inline constant BVH T#. + + The table-name form and the run-time descriptor are deliberately outside this first slice: the + host binding for a T# read from a descriptor heap is not part of this change, and passing the + four words as uninitialized SGPRs would read address zero. A constant T# built by four s_mov_b32 + instructions is fully proved here, so the emitted helper receives literals and the manifest can + name the node allocation by its base and size. + """ + name = 'image_bvh_intersect_ray' + r = reg_range(tok) + if not r or r[0] != 's' or r[2] - r[1] != 3: + raise Unsupported('%s descriptor %s is not four consecutive SGPRs' % (name, tok)) + values = [self.is_const(n) for n in range(r[1], r[2] + 1)] + if any(value is None for value in values): + first = self.sym.get(r[1]) + if first and first[0] == 'desc': + raise Unsupported('%s descriptor %s is loaded at run time: only a constant inline T# is ' + 'lowered in this slice' % (name, tok)) + raise Unsupported('%s descriptor %s is not four constant SGPRs' % (name, tok)) + words = ['0x%08xu' % (value & 0xffffffff) for value in values] + # The 40-bit base represents address bits 47:8, not a byte address. + base = (((values[1] & 0xff) << 32) | (values[0] & 0xffffffff)) << 8 + return (('bvhbase', base, values[2]), None), words, values + + def op_image_bvh_intersect_ray(self, ops, mods): + """Ray/box/triangle intersection for the 64-byte triangle (kinds 0..3), 64-byte binary16 + (kind 4) and 128-byte FP32 (kind 5) nodes. + + RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords + (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the + four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program + with a constant node base, a constant inline T# and a node whose kind bits are 0..5. + The descriptor base encodes address bits 47:8 in 256-byte units and binds a + ByteAddressBuffer at that byte address; the node pointer is an offset in 8-byte units from + that base. The emitted helper performs the four slab tests, clips against extent, replaces + misses with 0xffffffff in their original slots, and sorts by entry distance only when the + descriptor's box-sorting enable bit is set. Triangle nodes use the watertight test and + return {t, determinant, v, w} for triangle return mode 1; the instruction does not test + ray_extent for them. The 64-bit form, A16, non-sequential addresses and every other node + kind are refused by name. + """ + name = 'image_bvh_intersect_ray' + if self.kind != 'cs': + raise Unsupported('%s outside a compute stage' % name) + if mods: + raise Unsupported('%s modifier %s' % (name, ' '.join(mods))) + if len(ops) != 3: + raise Unsupported('%s with %d operands, expected 3' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: + raise Unsupported('%s destination %s is not four consecutive VGPRs' % (name, ops[0])) + if ops[1].startswith('['): + raise Unsupported('%s non-sequential address %s is not lowered' % (name, ops[1])) + addr = reg_range(ops[1]) + if not addr or addr[0] != 'v' or addr[2] > 255 or addr[2] - addr[1] + 1 not in (11, 16): + raise Unsupported('%s address %s is not an 11-dword VGPR range' % (name, ops[1])) + cs = ['v%d' % n for n in range(addr[1], addr[1] + 11)] + node = self.const_u32(cs[0]) + node_reg = reg_range(cs[0]) + if node is None and node_reg and node_reg[0] == 'v' and not getattr(self, 'has_branches', True): + node = getattr(self, 'vconst', {}).get(node_reg[1]) + if node is None: + raise Unsupported('%s non-constant node base %s' % (name, cs[0])) + kind = node & 7 + if kind not in (0, 1, 2, 3, 4, 5): + raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + triangle = kind <= 3 + half_box = kind == 4 + node_bytes = 64 if triangle or half_box else 128 + node_offset = (node & 0xfffffff8) << 3 + if node_offset > (0xffffffc0 if node_bytes == 64 else 0xffffff80) or \ + node_offset & (0x3f if node_bytes == 64 else 0x7f): + raise Unsupported('%s node base %#x is not an aligned %u-byte node' % (name, node_offset, node_bytes)) + key, words, vals = self.bvh_descriptor(ops[2]) + if vals[1] is not None: + if vals[1] & 0x7f800000: + raise Unsupported('%s box growing amount %d is not lowered' % (name, (vals[1] >> 23) & 0xff)) + if vals[1] & 0x007fff00: + raise Unsupported('%s descriptor reserved word 1 %#x' % (name, vals[1])) + if vals[3] is not None: + if (vals[3] >> 28) & 0xf != 8: + raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) + # The triangle return mode bit only selects the triangle result layout. One T# can + # cover both node types, so a box node ignores it; every other reserved bit is refused. + if triangle: + mode_ok = (vals[3] & 0x0fffffff) == 0x01000000 + else: + mode_ok = (vals[3] & 0x0effffff) == 0 + if not mode_ok: + raise Unsupported('%s descriptor word 3 %#x does not match node kind %d' % (name, vals[3], kind)) + base = key[0][1] + if base == 0: + raise Unsupported('%s absolute node base is not lowered' % name) + if vals[2] is not None: + if vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d is above 4 GiB' % (name, vals[2])) + # Size is a count minus one in 64-byte units, so size=0 is a one-unit span. + if (node_offset >> 6) + (node_bytes >> 6) - 1 > vals[2]: + raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) + if base + node_offset + node_bytes > 1 << 48: + raise Unsupported('%s node address wraps the 48-bit address space' % name) + extent = self.f(cs[1]) + origin = [self.f(cs[2 + i]) for i in range(3)] + direction = [self.f(cs[5 + i]) for i in range(3)] + inv_dir = [self.f(cs[8 + i]) for i in range(3)] + res = self.pipe.resource(key, 'bvh') + self.pipe.uses_bvh = True + if triangle: + call = ('x2w_bvh_intersect_triangle(%s, 0x%08xu, %s, %s, %s, %s, ' + 'float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s))') % ( + res, node, words[0], words[1], words[2], words[3], + origin[0], origin[1], origin[2], direction[0], direction[1], direction[2], + inv_dir[0], inv_dir[1], inv_dir[2]) + else: + call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', + res, node, words[0], words[1], words[2], words[3], extent, + origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) + self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) + for i in range(4): + self.set_v(dst[1] + i, 'bt%x.%s' % (self.pc or 0, 'xyzw'[i])) + + def op_image_bvh64_intersect_ray(self, ops, mods): + raise Unsupported('image_bvh64_intersect_ray: only the 32-bit image_bvh_intersect_ray is lowered') + def op_image_store(self, ops, mods): - """Write one four-channel 2D texel from pixel FP32 or compute packed FP16 data. + """Write a texel to a 2D or 2D-array image, or to a 1D or 3D compute image. MIMG opcode 0x08 (LLVM AMDGPU MIMGInstructions.td, IMAGE_STORE via MIMG_Store): VDATA is the - source, VADDR the integer texel address (x, y for dim 2D) and SRSRC the image descriptor; the - channels selected by DMASK are written in order from consecutive VDATA registers. HLSL's typed UAV - store writes every channel of the view, so only DMASK 0xf is exact here; a partial mask would need a - read-modify-write and is refused. The data is stored as float4, so the bound view must be of a - float or normalized format (the runtime side is not part of this lowering). The store runs under the - lane's exec bit, like the other per-lane writes, and D3D drops UAV writes from helper lanes as the - hardware drops them for lanes outside exec. + source, VADDR the integer texel address (x; x, y; x, y, z; or x, y, layer) and SRSRC + the image descriptor; the channels selected by DMASK are written in order from consecutive VDATA + registers. A full DMASK 0xf is a direct float4 assignment. A partial pixel-stage mask writes only + those components (a swizzle store). It does not read the texel: a float4 read-modify-write would + store every channel, so two invocations that hit one texel with disjoint masks can put stale + values back, and the load needs a typed-UAV-load format. Compute, D16 and array stores still + require DMASK 0xf. The bound view must be a float or normalized format (the runtime side is not + part of this lowering). The store runs under the lane's exec bit, and D3D drops UAV writes from + helper lanes as the hardware drops them for lanes outside exec. """ name = 'image_store' if self.kind not in ('ps', 'cs'): @@ -5143,26 +8637,42 @@ def op_image_store(self, ops, mods): masks = [m[6:] for m in mods if m.startswith('dmask:')] if len(dims) != 1 or len(masks) != 1: raise Unsupported('%s without exactly one dim and dmask' % name) - if dims[0] != 'SQ_RSRC_IMG_2D': - raise Unsupported('%s on %s: only 2D images are lowered' % (name, dims[0])) + shapes = { + 'SQ_RSRC_IMG_2D': ('tex2d', 2, 'x and y'), + 'SQ_RSRC_IMG_2D_ARRAY': ('tex2da', 3, 'x, y and layer'), + } + if self.kind == 'cs': + shapes.update({ + 'SQ_RSRC_IMG_1D': ('tex1d', 1, 'x'), + 'SQ_RSRC_IMG_3D': ('tex3d', 3, 'x, y and z'), + }) + if dims[0] not in shapes: + supported = '1D, 2D, 2D-array and 3D' if self.kind == 'cs' else '2D' + raise Unsupported('%s on %s: only %s images are lowered' % (name, dims[0], supported)) + kind, address, axes = shapes[dims[0]] + array = kind == 'tex2da' try: mask = int(masks[0], 0) except ValueError: raise Unsupported('%s with dmask %s: not an integer' % (name, masks[0])) from None - if mask != 0xf: + # Pixel 2D only. Compute, D16 and arrays keep the full-mask store. + sparse = self.kind == 'ps' and not array and not d16 and 0 < mask <= 0xf and mask != 0xf + if not sparse and mask != 0xf: raise Unsupported('%s with dmask %s: a typed UAV store writes all four channels' % (name, masks[0])) data = reg_range(ops[0]) - count = 2 if d16 else 4 + count = bin(mask).count('1') if sparse else (2 if d16 else 4) if not data or data[0] != 'v' or data[2] - data[1] + 1 != count or data[2] > 255: - raise Unsupported('%s data %s: %s VGPRs expected' % (name, ops[0], 'two' if d16 else 'four')) + raise Unsupported('%s data %s: %s VGPRs expected' % ( + name, ops[0], 'two' if d16 else ('four' if count == 4 else str(count)))) coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] else: r = reg_range(coords) cs = ['v%d' % n for n in range(r[1], r[2] + 1)] if r and r[0] == 'v' else [] - if len(cs) != 2: - raise Unsupported('%s with %d address registers: x and y expected' % (name, len(cs))) + if len(cs) != address: + raise Unsupported('%s with %d address registers: %s expected' + % (name, len(cs), axes)) words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] if self.kind == 'cs': if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 for c in cs): @@ -5170,14 +8680,23 @@ def op_image_store(self, ops, mods): key = self.fixed_table_image(ops[2], name) else: key = self.descriptor(ops[2]) + image = self.pipe.uav(key, kind) + index_type = 'uint' if address == 1 else 'uint%d' % address + index = '%s(%s)' % (index_type, ', '.join(self.u(c) for c in cs)) if d16: # RDNA 2 ISA §8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] value = 'float4(%s)' % ', '.join(rgba) + body = '%s[%s] = %s;' % (image, index, value) + elif sparse: + # Selected components only, in VDATA order. No texel read. + comps = [channel for bit, channel in enumerate('xyzw') if mask & (1 << bit)] + swizzle = ''.join(comps) + values = ', '.join('asfloat(%s)' % word for word in words) + rhs = values if len(comps) == 1 else 'float%d(%s)' % (len(comps), values) + body = '%s[%s].%s = %s;' % (image, index, swizzle, rhs) else: - value = 'asfloat(uint4(%s))' % ', '.join(words) - image = self.pipe.uav(key, 'tex2d') - body = '%s[uint2(%s, %s)] = %s;' % (image, self.u(cs[0]), self.u(cs[1]), value) + body = '%s[%s] = asfloat(uint4(%s));' % (image, index, ', '.join(words)) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_preclamp): @@ -5214,6 +8733,9 @@ def gather_2d_setup(self, name, ops, mods, addr_count, addr_label, *, mip_precla tex = self.pipe.resource(key, 'tex2d') return dst, addr, words, channels[masks[0]], tex + def op_image_gather4(self, ops, mods): + raise Unsupported('image_gather4 requires the guest implicit mip level') + def op_image_gather4_lz(self, ops, mods): dst, addr, words, (channel_name, _), tex = self.gather_2d_setup( 'image_gather4_lz', ops, mods, 2, 'two contiguous address registers', mip_preclamp=True) @@ -5289,6 +8811,44 @@ def op_v_cvt_i32_f32(self, ops, mods): dst = reg_range(ops[0])[1] self.set_v(dst, 'uint(int(F(%s)))' % self.u(ops[1])) + def op_v_pack_b32_f16(self, ops, mods): + """D[15:0] = S0.f16, D[31:16] = S1.f16 (AMD RDNA 2 ISA, VOP3 V_PACK_B32_F16). + + op_sel[i] selects the high half of source i (LLVM 15 VOP3Instructions.td: V_PACK_B32_F16 is VOP3_OPSEL). + The neg and abs source modifiers act on the sign bit (bit 15) of the selected half, abs first. The halves + are copied as bits, like pixel_aot's lowering of the same instruction: no binary16 denormal flush and no + NaN quieting is modelled (an assumption, not measured). Register sources only: an inline float constant + on a binary16 operand is a binary16 value, not the binary32 word u() would give. A destination op_sel bit + and clamp are refused, and so is any modifier other than the one op_sel:[a,b,c] spelling the decoder + prints.""" + sel = [0, 0, 0] + for m in mods: + match = re.fullmatch(r'op_sel:\[([01]),([01]),([01])\]', m) + if not match: + raise Unsupported('v_pack_b32_f16 modifier %s' % m) + sel = [int(x) for x in match.groups()] + dst = reg_range(ops[0]) if ops else None + if sel[2] or len(ops) != 3 or not dst or dst[0] != 'v' or dst[1] != dst[2]: + raise Unsupported('v_pack_b32_f16 form %s %s' % (', '.join(ops), ' '.join(mods))) + halves = [] + for i, tok in enumerate(ops[1:3]): + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + tok = tok[1:] if neg else tok + absolute = tok.startswith('|') and tok.endswith('|') + tok = tok[1:-1] if absolute else tok + reg = reg_range(tok) + if not reg or reg[1] != reg[2] or reg[0] not in ('v', 's'): + raise Unsupported('v_pack_b32_f16 source %s' % ops[1 + i]) + # The high half needs the whole word; the low half reads only bits 15:0, so a register whose high half + # is undefined (after an odd-count d16 load) stays readable here. + half = '(%s >> 16)' % self.u(tok) if sel[i] else '(%s & 0xffffu)' % self.u(tok, low16_only=True) + if absolute: + half = '(%s & 0x7fffu)' % half + if neg: + half = '(%s ^ 0x8000u)' % half + halves.append(half) + self.set_v(dst[1], '%s | (%s << 16)' % (halves[0], halves[1])) + def op_v_cvt_pk_u8_f32(self, ops, mods): # VOP3A opcode 350 of the RDNA 1.0 and RDNA 2 ISA guides: # D = (S2 & ~(0xff << 8 * S1[1:0])) | ((flt32_to_uint8(S0) & 0xff) << 8 * S1[1:0]) @@ -5319,17 +8879,339 @@ def op_v_cvt_pk_u8_f32(self, ops, mods): self.set_v(dst[1], '((%s & ~(0xffu << %s)) | (((((%s - 1u) < 0x7f800000u) ? uint(round(min(%s, 255.0))) : 0u) & 0xffu) << %s))' % (rest, shift, bits, value, shift)) + def _add_sub_nc_i32(self, base, ops, mods): + # RDNA 2 ISA VOP3A V_ADD_NC_I32 (0x37f) / V_SUB_NC_I32 (0x376): + # D.i32 = S0.i32 +/- S1.i32; with clamp, saturates to [-2^31, 2^31 - 1]. + clamped = mods == ['clamp'] + if mods and not clamped: + raise Unsupported('%s with %s' % (base, mods)) + if len(ops) != 3: + raise Unsupported('%s with %d operands, expected 3' % (base, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('%s destination %s' % (base, ops[0])) + for src in ops[1:3]: + if self.is_lane_mask(src): + raise Unsupported('%s on a lane mask' % base) + sr = reg_range(src) + if sr is not None: + if sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105): + raise Unsupported('%s source %s' % (base, src)) + elif src not in FLOATS and src not in ('m0', 'null'): + try: + val = int(src, 0) + except ValueError: + raise Unsupported('operand %r' % src) + if not -0x80000000 <= val <= 0xffffffff: + raise Unsupported('%s source %s' % (base, src)) + a, b = self.u(ops[1]), self.u(ops[2]) + if clamped: + pipe = getattr(self, 'pipe', None) + if pipe is not None and isinstance(getattr(pipe, 'uses_add_sub_sat_i32', None), set): + pipe.uses_add_sub_sat_i32.add(base) + fn = 'add_sat_i32' if base == 'v_add_nc_i32' else 'sub_sat_i32' + self.set_v(dst[1], '%s(%s, %s)' % (fn, a, b), align4=False) + else: + op = '+' if base == 'v_add_nc_i32' else '-' + align4 = self.operand_align4(ops[1]) and self.operand_align4(ops[2]) + self.set_v(dst[1], '%s %s %s' % (a, op, b), align4=align4) + + def op_v_add_nc_i32(self, ops, mods): + self._add_sub_nc_i32('v_add_nc_i32', ops, mods) + + def op_v_sub_nc_i32(self, ops, mods): + self._add_sub_nc_i32('v_sub_nc_i32', ops, mods) + + def op_s_ff0_i32_b32(self, ops, mods): + """Find first zero bit; SCC unchanged (#1723). + + RDNA 2 ISA SOP1 / pixel_aot ff0_i32_b32: D = firstbitlow(~S0) + (0xffffffff when every bit of S0 is set). Lane masks and descriptor-bearing + SGPRs are refused. + """ + if mods or len(ops) != 2: + raise Unsupported('s_ff0_i32_b32 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_ff0_i32_b32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_ff0_i32_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + zeros = (~value) & 0xffffffff + folded = 0xffffffff if zeros == 0 else (zeros & -zeros).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_ff0_i32_b32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_ff0_i32_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_ff0_i32_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + zeros = (~value) & 0xffffffff + folded = 0xffffffff if zeros == 0 else (zeros & -zeros).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src_u = self.u(ops[1]) + self.set_s(dst[1], 'firstbitlow(~%s)' % src_u) + return None + def op_s_ff1_i32_b32(self, ops, mods): - if self.kind != 'cs' or mods or len(ops) != 2 or ops[1] != 'exec_lo': - raise Unsupported('s_ff1_i32_b32 requires compute exec_lo') + """Find first set bit in a 32-bit scalar; SCC unchanged (#2022 Item F). + + The compute-entry special case on `exec_lo` still folds to lane 0; in a pixel stage `exec_lo` is the + first active lane for a later v_readlane_b32 (first_active_lane). Every other accepted + source uses `firstbitlow` (0xffffffff when the word is zero), matching `pixel_aot`. + """ + if mods or len(ops) != 2: + raise Unsupported('s_ff1_i32_b32 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_ff1_i32_b32 destination %s' % ops[0]) + if ops[1] == 'exec_lo': + if self.kind == 'ps': + self.first_active_lane(dst[1]) + return None + if self.kind != 'cs': + raise Unsupported('s_ff1_i32_b32 of exec_lo outside compute') + if getattr(self, 'past_entry', False) or not getattr(self, 'exec_known', False): + raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') + # At dispatch entry even the last partial wave starts at lane zero. + self.set_s(dst[1], '0u', ('const', 0)) + return None + if self.is_lane_mask(ops[0]) or self.is_lane_mask(ops[1]) or dst[1] in self.masks: + raise Unsupported('s_ff1_i32_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + # firstbitlow of zero is -1; otherwise the lowest set bit index. + folded = 0xffffffff if value == 0 else (value & -value).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_ff1_i32_b32 source %s' % ops[1]) + if src[1] in self.masks: + raise Unsupported('s_ff1_i32_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_ff1_i32_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + folded = 0xffffffff if value == 0 else (value & -value).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + self.set_s(dst[1], 'firstbitlow(%s)' % self.u(ops[1])) + return None + + def op_s_ff1_i32_b64(self, ops, mods): + """Find first set bit of a 64-bit source; SCC unchanged (#2022 Item F). + + A 32-bit SOP1 literal or inline constant zero-extends to 64 bits (high word 0) + and folds. An SGPR pair uses the same 64-bit firstbitlow scan as SCALAR_BITS + (`_ctz64` / #2072). Kept as a Stage method so immediates are not refused by the + pair-only SCALAR_BITS template. + """ + if mods or len(ops) != 2: + raise Unsupported('s_ff1_i32_b64 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_ff1_i32_b64 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_ff1_i32_b64 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + # Encoding: one 32-bit literal/inline; the ISA zero-extends it (hi = 0). + value = int(ops[1], 0) & 0xffffffff + folded = 0xffffffff if value == 0 else (value & -value).bit_length() - 1 + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if src is None or src[0] != 's' or src[2] > 105 or src[2] - src[1] != 1: + raise Unsupported('s_ff1_i32_b64 source %s' % ops[1]) + if any(r in self.masks for r in range(src[1], src[2] + 1)): + raise Unsupported('s_ff1_i32_b64 on a lane mask') + lo, hi = self.S(src[1]), self.S(src[2]) + self.masks.discard(dst[1]) + self.set_s(dst[1], _ctz64(lo, hi)) + return None + + def op_s_abs_i32(self, ops, mods): + """Signed absolute value; SCC = result != 0 (#1723). + + RDNA 2 ISA SOP1 / pixel_aot: D = asint(S0) < 0 ? (0u - S0) : S0 (INT_MIN stays). + Lane masks and descriptor-bearing SGPRs are refused so a projected bit is not treated + as a full signed word. + """ + if mods or len(ops) != 2: + raise Unsupported('s_abs_i32 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_abs_i32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_abs_i32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + src_sym = None + if imm: + value = int(ops[1], 0) & 0xffffffff + else: + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_abs_i32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_abs_i32 on a lane mask') + src_sym = self.sym.get(src[1]) + if src_sym and src_sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_abs_i32 on %s data' % src_sym[0]) + value = src_sym[1] & 0xffffffff if src_sym and src_sym[0] == 'const' else None + if value is not None: + folded = (-value if value & 0x80000000 else value) & 0xffffffff + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + expr = '(asint(%s) < 0 ? (0u - %s) : %s)' % ((self.u(ops[1]),) * 3) + self.set_s(dst[1], expr, scc='$ != 0') + return None + + def op_s_flbit_i32_b32(self, ops, mods): + """Find first bit high (leading-zero count); SCC unchanged (#1723). + + RDNA 2 ISA SOP1 / pixel_aot dpp_ffbh_u32: D = S0 == 0 ? 0xffffffff : 31 - firstbithigh(S0). + Lane masks and descriptor-bearing SGPRs are refused. + """ + if mods or len(ops) != 2: + raise Unsupported('s_flbit_i32_b32 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_flbit_i32_b32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_flbit_i32_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + folded = 0xffffffff if value == 0 else 31 - (value.bit_length() - 1) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_flbit_i32_b32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_flbit_i32_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_flbit_i32_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + folded = 0xffffffff if value == 0 else 31 - (value.bit_length() - 1) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded)) + return None + src_u = self.u(ops[1]) + self.set_s(dst[1], '(%s == 0u ? 0xffffffffu : 31u - firstbithigh(%s))' % (src_u, src_u)) + return None + + def op_s_quadmask_b64(self, ops, mods): + """Collapse each nibble of a 64-bit source into bits of D.lo; D.hi = 0 (#1723). + + RDNA 2 ISA SOP1 / pixel_aot: bit g of D.lo is 1 iff nibble g of the 64-bit source is + nonzero (sixteen nibbles → bits 0..15). SCC = (D.lo | D.hi) != 0. + Integer inline constants are 64-bit; 32-bit literals zero-extend. + Lane masks and descriptor SGPRs are refused. + """ + if mods or len(ops) != 2: + raise Unsupported('s_quadmask_b64 with %d operands, expected 2 unmodified' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[2] != dst[1] + 1 or dst[2] > 105 or dst[1] % 2: + raise Unsupported('s_quadmask_b64 destination %s' % ops[0]) + if any(r in self.masks for r in range(dst[1], dst[2] + 1)) or self.is_lane_mask(ops[0]): + raise Unsupported('s_quadmask_b64 on a lane mask') + + def nibble_mask(word): + folded = 0 + for group in range(8): + if word & (0xf << (group * 4)): + folded |= 1 << group + return folded + + def nibble_expr(src_u): + return '(%s)' % ' | '.join( + '((%s & 0x%xu) != 0u ? %du : 0u)' % (src_u, 0xf << (g * 4), 1 << g) + for g in range(8)) + + imm = re.fullmatch(r'0x[0-9a-fA-F]{1,8}|-?\d+', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffffffffffff + folded = nibble_mask(value & 0xffffffff) | (nibble_mask(value >> 32) << 8) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + self.set_s(dst[1] + 1, '0u', ('const', 0)) + return None + src = reg_range(ops[1]) + if src is None or src[0] != 's' or src[2] > 105 or src[2] - src[1] != 1 or src[1] % 2: + raise Unsupported('s_quadmask_b64 source %s' % ops[1]) + if any(r in self.masks for r in range(src[1], src[2] + 1)): + raise Unsupported('s_quadmask_b64 on a lane mask') + for n in range(src[1], src[2] + 1): + sym = self.sym.get(n) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_quadmask_b64 on %s data' % sym[0]) + lo_sym, hi_sym = self.sym.get(src[1]), self.sym.get(src[2]) + if (lo_sym and lo_sym[0] == 'const' and hi_sym and hi_sym[0] == 'const'): + folded = nibble_mask(lo_sym[1] & 0xffffffff) | (nibble_mask(hi_sym[1] & 0xffffffff) << 8) + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + self.set_s(dst[1] + 1, '0u', ('const', 0)) + return None + lo_u, hi_u = self.S(src[1]), self.S(src[2]) + # Low 8 bits from the low word; next 8 bits from the high word. High result word is 0. + expr = '((%s) | ((%s) << 8u))' % (nibble_expr(lo_u), nibble_expr(hi_u)) + self.set_s(dst[1], expr, scc='$ != 0') + self.set_s(dst[1] + 1, '0u', ('const', 0)) + return None + + def op_s_quadmask_b32(self, ops, mods): + """Collapse each nibble of S0 to one bit of D; SCC = result != 0 (#1723). + + RDNA 2 ISA SOP1 / pixel_aot: bit g of D is 1 iff nibble g of S0 is nonzero. + Lane masks and descriptor-bearing SGPRs are refused. + """ + if mods or len(ops) != 2: + raise Unsupported('s_quadmask_b32 with %d operands, expected 2 unmodified' % len(ops)) dst = reg_range(ops[0]) if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: - raise Unsupported('s_ff1_i32_b32 requires one SGPR destination') - if self.past_entry or not self.exec_known: - raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') - # At dispatch entry even the last partial wave starts at lane zero. - # FF1 reports its index and leaves SCC unchanged. - self.set_s(dst[1], '0u', ('const', 0)) + raise Unsupported('s_quadmask_b32 destination %s' % ops[0]) + if self.is_lane_mask(ops[0]) or dst[1] in self.masks: + raise Unsupported('s_quadmask_b32 on a lane mask') + imm = re.fullmatch(r'-?(0x[0-9a-fA-F]+|\d+)', ops[1]) + if imm: + value = int(ops[1], 0) & 0xffffffff + folded = 0 + for group in range(8): + if value & (0xf << (group * 4)): + folded |= 1 << group + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + src = reg_range(ops[1]) + if not src or src[0] != 's' or src[1] != src[2] or src[1] > 105: + raise Unsupported('s_quadmask_b32 source %s' % ops[1]) + if self.is_lane_mask(ops[1]) or src[1] in self.masks: + raise Unsupported('s_quadmask_b32 on a lane mask') + sym = self.sym.get(src[1]) + if sym and sym[0] not in ('const', 'ud', 'fixed_buffer_word'): + raise Unsupported('s_quadmask_b32 on %s data' % sym[0]) + if sym and sym[0] == 'const': + value = sym[1] & 0xffffffff + folded = 0 + for group in range(8): + if value & (0xf << (group * 4)): + folded |= 1 << group + self.set_s(dst[1], '0x%08xu' % folded, ('const', folded), scc='$ != 0') + return None + src_u = self.u(ops[1]) + parts = ['((%s & 0x%xu) != 0u ? %du : 0u)' % (src_u, 0xf << (g * 4), 1 << g) for g in range(8)] + self.set_s(dst[1], '(%s)' % ' | '.join(parts), scc='$ != 0') + return None # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- def op_x2w_mesh_lane0(self, ops, mods): @@ -5418,14 +9300,34 @@ def op_v_mbcnt_lo_u32_b32(self, ops, mods, high=False): def op_v_mbcnt_hi_u32_b32(self, ops, mods): self.op_v_mbcnt_lo_u32_b32(ops, mods, high=True) + def proven_uniform_v(self, n): + """VGPR n holds one value in every lane EXEC enables now. In the entry block EXEC is known; past it, a + recomputable expression proves no join, EXEC write or overwrite lies between the definition and here.""" + if not self.tracks_uniformity() or n not in self.uniform_v: + return False + # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. + if getattr(self, 'past_entry', True): + return n in getattr(self, 'uniform_expr', {}) and getattr(self, 'has_branches', False) + return getattr(self, 'exec_known', False) + def op_v_readfirstlane_b32(self, ops, mods): src, dst = reg_range(ops[1]), reg_range(ops[0]) past_entry = getattr(self, 'past_entry', True) - # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. - if (mods or not self.tracks_uniformity() or not dst or dst[0] != 's' or dst[1] != dst[2] or - not src or src[0] != 'v' or src[1] != src[2] or src[1] not in self.uniform_v or - (src[1] not in getattr(self, 'uniform_expr', {}) or not getattr(self, 'has_branches', False) - if past_entry else not getattr(self, 'exec_known', False))): + waterfalls = getattr(self, 'waterfall_reads', {}) + if getattr(self, 'pc', None) in waterfalls and not (src and self.proven_uniform_v(src[1])): + reason = waterfalls[self.pc] + if reason: + raise Unsupported('compute readfirstlane waterfall: ' + reason) + self.set_s(dst[1], self.u(ops[1]), uniform=False) # the selected key varies between lanes + bound = getattr(self, 'waterfall_heap_bounds', {}).get(self.pc) + if bound: + if bound[0] == 'idx': + self.per_lane_index[dst[1]] = ('s%d' % dst[1], bound[1]) + elif bound[0] == 'off5': + self.heap_index[dst[1]] = ('per_lane', '(s%d >> 5)' % dst[1], bound[1]) + return + if (mods or not dst or dst[0] != 's' or dst[1] != dst[2] or + not src or src[0] != 'v' or src[1] != src[2] or not self.proven_uniform_v(src[1])): raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') if past_entry: # The first active lane ran the definition: no join, EXEC write or overwrite of the VGPR and no write @@ -5435,13 +9337,151 @@ def op_v_readfirstlane_b32(self, ops, mods): else: self.set_s(dst[1], self.u(ops[1])) - # ---- SGPR spill to VGPR lanes (#2125, item E) -------------------------------------------- + # ---- SGPR spill to VGPR lanes (#2125 item E; mesh #2413 T7 / #2127) ---------------------- # The compiler parks a scalar in one lane of a VGPR: `v_writelane_b32 vN, sM, k` writes sM into lane k # and `v_readlane_b32 sD, vN, k` reads it back (AMD RDNA 2 ISA reference, VOP3 lane ops; LLVM 15 # AMDGPU spill lowering). Both ignore EXEC. With a constant k and a VGPR that no other instruction # touches, vN is only a table of scalar slots, so one scalar variable per (vN, k) is an exact model # and no other lane is ever read. Anything else keeps the one-lane model out of reach and is refused. - SPILL_LANES = 32 + # Lanes 0..63 cover a wave64 program. A wave32 program uses only bits 4:0 of the lane select (RDNA 2 ISA, + # v_readlane/v_writelane: the lane is taken modulo the wave size), so k and k + 32 name one slot there and two in + # wave64; the translator does not know the wave size, so a VGPR whose lanes include such a pair is refused. + # Slot 57 mesh is wave64 (#2127). Vertex stages use the same model: the two instructions touch no other lane and no stage input. + # + # With branches the slot variable is assigned on the pixel's own path, while the hardware slot holds the last + # write on the wave's path. The two paths differ only inside the region of a branch not proven uniform (an + # s_cbranch_execz or _vccz the pixel takes alone, or an SCC branch on varying data), where the wave also runs + # the blocks this pixel skips. spill_reaching gives the writes that can supply a read, written on every path. + # One write: every path into the read ran it, so the slot is one more scalar register; it is accepted unless + # the write lies in such a region that the read is outside (a loop or arm the wave can run after this pixel + # left it). Several writes: the value is chosen by the path, so every write must lie outside every such region; + # the reload then keeps a constant only if all of them stored it, and is not claimed uniform. + # Compute stages (cs) use the same proof, branches included. A spilled descriptor or pointer word (SPILL_SYMBOLS) is a + # symbol with no run-time value: the slot carries the symbol, the reload restores it, and the word keeps the + # provenance the formatted loads require (formatted_descriptor_from_block follows a reload to the writes that supply it). + # Lane masks (compute only). The translator models a lane mask (vcc_lo, or an SGPR in self.masks) per invocation + # as that invocation's own bit: `vcc` / `sN` hold bit 0 of the wave mask, and a v_cmp stores `w` (all lanes active) + # or `exec & w`, so an inactive lane's bit is already 0 in the variable. `v_writelane_b32 vN, M, k` copies the whole + # wave mask into lane k whatever EXEC is, `v_readlane_b32 D, vN, k` copies it back to every lane, so a mask that is + # only ever used as a mask afterwards (reject_lane_mask_data and the mask rules refuse every numeric read of a marked + # register, vcc included) has, after the reload, each invocation's bit equal to its bit at the write: the spill is + # the identity on the per-invocation bit. The slot variable spN_k is therefore assigned the mask's own variable at + # the write, in every invocation, and the reload copies it into the destination and marks it a mask again (or + # assigns vcc for a `vcc_lo` destination). The slot proof of spill_join (written on every path, no loop-carried + # read, no write in a region the wave runs while the invocation skips it; writes in s_cbranch_execz blocks are + # refused by execz_refusals) decides what a reload sees. A reload that may see two writes of which one is a mask + # is refused: nothing proves they store the same mask. exec, vcc and vcc_hi (64-bit forms), and m0 stay refused + # as sources, a mask register in join_masks (mark not proven on every path) too. + SPILL_LANES = 64 + SPILL_STAGES = ('ps', 'vs', 'ms', 'cs') + # Symbols a spill carries by identity: the SGPR holds no run-time value in the translation, so the slot holds none either. + SPILL_SYMBOLS = ('desc', 'ptr', 'ptrhi') + + def spill_reaching(self, cfg): + """Instruction index of each v_readlane_b32 -> the v_writelane_b32 indices that can supply its (VGPR, lane), or + None when some path from the entry reaches it with none. Forward must-dataflow over the blocks: a slot is + written at a join only if it is written on every incoming edge (intersection) and the writes that can supply + it are the union over those edges, iterated to a fixed point so a later write in a loop body reaches the loop + head through the back edge.""" + bounds, _, succ, _ = cfg + lane_ops = {} + for i, (_, _, name, asm) in enumerate(self.ins): + base = re.sub(r'_e(32|64)$', '', name) + ops = parse(asm)[1] if base in ('v_writelane_b32', 'v_readlane_b32') else () + if len(ops) == 3: + try: + lane = int(ops[2], 0) # 3 and 0x3 are one slot + except ValueError: + lane = ops[2] # an SGPR lane, refused by spill_operands + lane_ops[i] = (base == 'v_writelane_b32', ops[0 if base == 'v_writelane_b32' else 1], lane) + into = [{}] + [None] * (len(bounds) - 1) # None: no path reaches the block yet + reach = {} + changed = True + while changed: + changed = False + for b, (lo, hi) in enumerate(bounds): + if into[b] is None: + continue + state = dict(into[b]) + for i in range(lo, hi): + if i in lane_ops: + write, vreg, lane = lane_ops[i] + if write: + state[vreg, lane] = frozenset([i]) + else: + reach[i] = state.get((vreg, lane)) + for t in succ[b]: + new = state if into[t] is None else {k: into[t][k] | state[k] for k in into[t].keys() & state.keys()} + if new != into[t]: + into[t], changed = new, True + return reach + + def spill_join(self, n, lane): + """(sym, uniform) of the slot a v_readlane_b32 reads in a program with branches, or a refusal naming what + failed (see the comment above SPILL_LANES).""" + i = self.descriptor_instruction_index + writes = self.spill_reach.get(i) + if writes is None: + raise Unsupported('v_readlane_b32 reads v%d lane %d with no v_writelane_b32 of it on some path' % (n, lane)) + if max(writes) > i: + raise Unsupported('v_readlane_b32 reads v%d lane %d written later in a loop (loop-carried)' % (n, lane)) + if any(w not in self.spill_writes for w in writes): + raise Unsupported('v_readlane_b32 reads v%d lane %d from a v_writelane_b32 that was not translated' % (n, lane)) + _, block_of, _, div_blocks = self.spill_cfg + here = block_of[i] + for off, blocks in sorted(div_blocks.items()): + if off in self.uniform_branches or not any(block_of[w] in blocks for w in writes): + continue + if len(writes) > 1: + raise Unsupported('v_readlane_b32 joins %d writes of v%d lane %d, one inside the region of the branch at ' + '%#x, which is not proven uniform' % (len(writes), n, lane, off)) + if here not in blocks: + raise Unsupported('v_readlane_b32 reads v%d lane %d outside the region of the branch at %#x that writes ' + 'it, which is not proven uniform' % (n, lane, off)) + stored = [self.spill_writes[w] for w in sorted(writes)] + if any(s[3] for s in stored) and len(stored) > 1: + # Which mask the reload holds would depend on the path; nothing proves the writes store the same one. + raise Unsupported('v_readlane_b32 joins %d writes of v%d lane %d, one of them a lane mask' % (len(stored), n, lane)) + sym = stored[0][0] if all(s[0] == stored[0][0] for s in stored) else None + if sym is None and any(s[0] is not None and s[0][0] in self.SPILL_SYMBOLS for s in stored): + # A descriptor or pointer word has no run-time variable: only the same symbol on every path can be reloaded. + raise Unsupported('v_readlane_b32 joins different descriptor or pointer words of v%d lane %d' % (n, lane)) + return sym, len(stored) == 1 and stored[0][1], all(s[2] for s in stored), stored[0][3] + + def require_mask_reads_only(self, key): + """Refuse a reloaded lane mask (scalar state `key`: 'vcc' or 'sN') that an instruction reachable before its next + write reads as anything but a mask. The translator marks the register a mask but does not refuse every numeric + read of one, and a numeric read would see the whole wave mask where the model has one bit. Accepted reads: a lane + select or carry-in (per_lane_read), a read by s_cbranch_vccz / _vccnz, a copy into exec_lo or vcc_lo, and another + spill of it.""" + effects = [scalar_effects(name, asm) for _, _, name, asm in self.ins] + index = {off: i for i, (off, *_) in enumerate(self.ins)} + todo, seen = [self.descriptor_instruction_index + 1], set() + while todo: + j = todo.pop() + if j in seen or j >= len(self.ins): + continue + seen.add(j) + _, _, name, asm = self.ins[j] + base = re.sub(r'_e(32|64)$', '', name) + ops = parse(asm)[1] + if key in effects[j][0]: + copy = base == 's_mov_b32' and len(ops) == 2 and ops[0] in ('exec_lo', 'vcc_lo') and key in scalar_tokens(ops[1]) + if not (self.per_lane_read(j, key) or copy or base == 'v_writelane_b32' or + (key == 'vcc' and base in ('s_cbranch_vccz', 's_cbranch_vccnz'))): + raise Unsupported('v_readlane_b32 reloads a lane mask that %s reads as data' % name) + if key in effects[j][1]: + continue + target = None + if base == 's_branch' or base.startswith('s_cbranch'): + target = index.get(int(ops[0].split('_')[1], 16)) + if base not in ('s_branch', 's_endpgm'): + todo.append(j + 1) + if target is not None: + todo.append(target) + + def spills_lane_masks(self): + return getattr(self, 'kind', None) == 'cs' def spill_operands(self, name, ops, mods): if mods or len(ops) != 3: @@ -5455,18 +9495,42 @@ def spill_operands(self, name, ops, mods): lane = int(ops[2], 0) except ValueError: raise Unsupported('%s requires a constant lane, got %s' % (name, ops[2])) from None + kind = getattr(self, 'kind', None) if not 0 <= lane < self.SPILL_LANES: raise Unsupported('%s lane %d outside 0..%d' % (name, lane, self.SPILL_LANES - 1)) - if getattr(self, 'kind', None) != 'ps': - raise Unsupported('%s is lowered in pixel stages only' % name) - if getattr(self, 'has_branches', True) or not self.tracks_uniformity(): + if kind not in self.SPILL_STAGES: + raise Unsupported('%s is lowered in pixel, vertex, mesh and compute stages only' % name) + if not self.tracks_uniformity() or (getattr(self, 'has_branches', True) and + (kind not in ('ps', 'cs') or getattr(self, 'spill_reach', None) is None)): raise Unsupported('%s needs straight-line code to prove write-before-read' % name) self.require_spill_only(vreg[1], name) + if kind in ('ps', 'vs', 'cs'): # the wave size is unknown there; slot 57 mesh is always wave64, so k and k + 32 are two slots + self.require_spill_lanes_apart(vreg[1], name) return vreg[1], sreg, lane + def require_spill_lanes_apart(self, n, name): + """Refuse when two lanes of spill VGPR v<n> differ by 32: one slot in wave32, two in wave64.""" + lanes = set() + for _, _, op, asm in getattr(self, 'ins', ()): + if re.sub(r'_e(32|64)$', '', op) not in ('v_writelane_b32', 'v_readlane_b32'): + continue + ops = parse(asm)[1] + if len(ops) == 3 and n in [r[1] for r in map(reg_range, ops[:2]) if r and r[0] == 'v']: + try: + lanes.add(int(ops[2], 0)) + except ValueError: + continue # a register lane is refused where it is read + for lane in lanes: + if lane + 32 in lanes: + raise Unsupported('%s: v%d lanes %d and %d are one slot in wave32 and two in wave64' + % (name, n, lane, lane + 32)) + def require_spill_only(self, n, name): """Refuse unless every instruction naming v<n> is a lane write or read of it.""" - for _, _, op, asm in getattr(self, 'ins', ()): + # Mesh: scan the pre-skeleton program. The accepted group-memory exchanges rewrite to + # x2w_mesh_* / s_nop, which would hide ordinary use of exchange VGPRs (v5 and temps). + source = getattr(self, 'mesh_source_ins', None) or getattr(self, 'ins', ()) + for _, _, op, asm in source: if re.sub(r'_e(32|64)$', '', op) in ('v_writelane_b32', 'v_readlane_b32'): continue for lo, hi, single in re.findall(r'\bv\[(\d+):(\d+)\]|\bv(\d+)\b', asm): @@ -5476,38 +9540,135 @@ def require_spill_only(self, n, name): def op_v_writelane_b32(self, ops, mods): n, src, lane = self.spill_operands('v_writelane_b32', ops, mods) + mask = False if src is None: - if ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'): + # Slot 57 mesh keeps ordinary scalar spills only (R0Y00 on #2637). Raw EXEC words are not + # proven under the one-lane model (exec_hi would be wrong under full EXEC; exec_lo under + # a lane-0 mask would reload per thread). mesh_entry_aot still models EXEC for #2127. + if ops[1] == 'vcc_lo' and self.spills_lane_masks(): + value, sym, uniform, proven, mask = 'vcc', None, False, False, True + elif ops[1] in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0'): raise Unsupported('v_writelane_b32 source %s is a lane mask or m0' % ops[1]) - value, sym, uniform = self.u(ops[1]), None, True - if re.fullmatch(r'0x[0-9a-f]{8}u', value): - sym = ('const', int(value[2:-1], 16)) + else: + value, sym, uniform, proven = self.u(ops[1]), None, True, False + if re.fullmatch(r'0x[0-9a-f]{8}u', value): + sym = ('const', int(value[2:-1], 16)) else: - if self.is_lane_mask(ops[1]) or (self.sym.get(src[1]) or ('',))[0] not in ('', 'const', 'ud', 'fixed_buffer_word'): + held = self.sym.get(src[1]) or ('',) + carried = held[0] in self.SPILL_SYMBOLS and getattr(self, 'kind', None) == 'cs' + mask = self.spills_lane_masks() and src[1] in self.masks + if mask: + if src[1] in self.join_masks: + raise Unsupported('v_writelane_b32 source s%d holds a lane mask not proven on every path' % src[1]) + value, sym, uniform, proven = self.S(src[1]), (held if held[0] == 'execcopy' else None), False, False + elif not carried and (self.is_lane_mask(ops[1]) or held[0] not in ('', 'const', 'ud', 'fixed_buffer_word')): raise Unsupported('v_writelane_b32 source s%d holds a lane mask or descriptor' % src[1]) - value = self.S(src[1]) - sym = self.sym.get(src[1]) if (self.sym.get(src[1]) or ('',))[0] == 'const' else None - uniform = self.uniform_source(ops[1]) + elif carried: + # A descriptor or pointer word of a compute stage: the slot holds the symbol itself, so the reload + # restores the same word. Nothing is emitted: the translation has no run-time value for it. + if not names_one_value(held): + raise Unsupported('v_writelane_b32 source s%d holds a modified descriptor or pointer word' % src[1]) + value, sym, uniform, proven = None, held, True, self.spill_word_proven(src[1], held) + else: + value = self.S(src[1]) + sym = held if held[0] == 'const' else None + uniform = self.uniform_source(ops[1]) + proven = False slots = self.__dict__.setdefault('spill_slots', {}) - slots[(n, lane)] = (sym, uniform) - self.emit('sp%d_%d = %s;' % (n, lane, value)) + slots[(n, lane)] = (sym, uniform, proven, mask) + if getattr(self, 'spill_reach', None) is not None: + self.spill_writes[self.descriptor_instruction_index] = (sym, uniform, proven, mask) + if value is not None: + self.emit('sp%d_%d = %s;' % (n, lane, value)) + + # The first active lane of a pixel stage (#2618, the F rows). `s_ff1_i32_b32 sD, exec_lo` gives the index of the + # lowest lane in EXEC (RDNA 2 ISA, S_FF1_I32_B32) and `v_readlane_b32 sX, vY, sD` copies vY from that lane, so the + # pair reads vY from the first active lane. The console packs pixels into waves in its own way, so a correct + # program cannot depend on which pixel that is (the contract of the #2835 wave reductions), and the pair becomes + # WaveReadLaneFirst(vY) over the active lanes of the desktop wave. The lane number itself means nothing on the + # desktop, so sD is a symbol with no run-time value and every other read of it is refused. Accepted only where the + # one-lane model holds the whole wave's EXEC: a straight-line pixel stage whose EXEC is the entry mask at the + # s_ff1 and at each readlane, without s_wqm (helper lanes are then out of EXEC on the console, as they are out of + # desktop wave operations). The decoder prints wave32 syntax, and in wave64 exec_lo is half the wave (an empty + # low half gives -1, which v_readlane reads as lane 63), so a program that names exec_hi or the 64-bit exec is + # refused. + def first_active_lane(self, n): + what = 's_ff1_i32_b32 s%d, exec_lo in a pixel stage' % n + if getattr(self, 'has_branches', True) or getattr(self, 'blocks', True): + raise Unsupported('%s with branches: only straight-line pixel stages are lowered' % what) + if not getattr(self, 'exec_known', False): + raise Unsupported('%s: EXEC is not the entry mask' % what) + if getattr(self, 'wqm_exec', False): + raise Unsupported('%s after s_wqm exec, exec: the first lane may be a helper lane' % what) + ins = self.ins + if any('exec_hi' in scalar_tokens(' '.join(parse(asm)[1])) for _o, _n, _name, asm in ins): + raise Unsupported('%s of a program that names exec_hi or the 64-bit exec (in wave64, exec_lo is half the ' + 'wave)' % what) + index = next(i for i, item in enumerate(ins) if item[0] == self.pc) + key = 's%d' % n + for _off, _n, name, asm in ins[index + 1:]: + reads, writes, may = scalar_effects(name, asm) + ops = parse(asm)[1] + if key in reads and not (re.sub(r'_e(32|64)$', '', name) == 'v_readlane_b32' and len(ops) == 3 and + ops[2] == key): + raise Unsupported('%s: %s reads the lane number as data (the desktop numbers its lanes in its own ' + 'way); only the lane select of v_readlane_b32 is lowered' % (what, asm)) + if key in writes or key in may: + break + self.set_s(n, 'WaveReadLaneFirst(WaveGetLaneIndex())', sym=('first_lane',)) + + def read_first_lane(self, ops, mods): + """v_readlane_b32 sX, vY, sD with sD from first_active_lane: WaveReadLaneFirst(vY).""" + what = 'v_readlane_b32 %s of the first active lane' % ', '.join(ops) + dst, src = reg_range(ops[0]), reg_range(ops[1]) + if mods: + raise Unsupported('%s with %s' % (what, ' '.join(mods))) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105 or src[1] != src[2] or src[1] > 255: + raise Unsupported('%s: expected one SGPR destination and one VGPR' % what) + if not getattr(self, 'exec_known', False) or getattr(self, 'wqm_exec', False): + raise Unsupported('%s: EXEC is no longer the entry mask of the s_ff1_i32_b32' % what) + for _o, _n, name, asm in self.ins: + other = parse(asm)[1] + if re.sub(r'_e(32|64)$', '', name) == 'v_writelane_b32' and other and reg_range(other[0]) == src: + raise Unsupported('%s: v%d is a lane spill written by v_writelane_b32' % (what, src[1])) + self.set_s(dst[1], 'WaveReadLaneFirst(%s)' % self.u(ops[1]), uniform=False) def op_v_readlane_b32(self, ops, mods): if len(ops) != 3 or reg_range(ops[1]) is None or reg_range(ops[1])[0] != 'v': raise Unsupported('v_readlane_b32 requires a VGPR source') + lane = reg_range(ops[2]) + if lane and lane[0] == 's' and lane[1] == lane[2] and getattr(self, 'sym', {}).get(lane[1]) == ('first_lane',): + self.read_first_lane(ops, mods) + return n, dst, lane = self.spill_operands('v_readlane_b32', ops, mods) + if getattr(self, 'has_branches', False): + sym, uniform, proven, mask = self.spill_join(n, lane) + else: + slot = getattr(self, 'spill_slots', {}).get((n, lane)) + if slot is None: + raise Unsupported('v_readlane_b32 reads v%d lane %d before any v_writelane_b32 wrote it' % (n, lane)) + sym, uniform, proven, mask = slot if dst is None: - raise Unsupported('v_readlane_b32 requires an SGPR destination') - slot = getattr(self, 'spill_slots', {}).get((n, lane)) - if slot is None: - raise Unsupported('v_readlane_b32 reads v%d lane %d before any v_writelane_b32 wrote it' % (n, lane)) - sym, uniform = slot - self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=sym, uniform=uniform) + if not (mask and ops[0] == 'vcc_lo'): + raise Unsupported('v_readlane_b32 requires an SGPR destination') + self.emit('vcc = sp%d_%d;' % (n, lane)) + self.require_mask_reads_only('vcc') + return + self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=None if mask else sym, uniform=uniform) + if mask: + self.masks.add(dst[1]) + if sym is not None: + self.sym[dst[1]] = sym + self.require_mask_reads_only('s%d' % dst[1]) + if getattr(self, 'descriptor_instruction_index', None) is not None: # unit probes build a Stage without translate() + self.__dict__.setdefault('reload_proven', {})[self.descriptor_instruction_index] = proven def op_v_mov_b32(self, ops, mods): if len(ops) != 2: raise Unsupported('v_mov_b32 with %d operands, expected 2' % len(ops)) - self.set_v(reg_range(ops[0])[1], self.u(ops[1])) + self.reject_lane_mask_data('v_mov_b32', ops[1]) + align4 = not mods and self.operand_align4(ops[1]) + self.set_v(reg_range(ops[0])[1], self.u(ops[1]), align4=align4) def op_v_swap_b32(self, ops, mods): # VOP1 only (llvm-mc rejects the e64, DPP and SDWA spellings for gfx1013). Both registers exchange @@ -5528,6 +9689,10 @@ def op_v_swap_b32(self, ops, mods): uniform = (dst in self.uniform_v and self.exec_known, src in self.uniform_v and self.exec_known) for reg, flag in zip((src, dst), uniform): (self.uniform_v.add if flag else self.uniform_v.discard)(reg) + if isinstance(self.align4_v, set): + aligned = (dst in self.align4_v and self.exec_known, src in self.align4_v and self.exec_known) + for reg, flag in zip((src, dst), aligned): + (self.align4_v.add if flag else self.align4_v.discard)(reg) exprs = getattr(self, 'uniform_expr', {}) moved = {src: exprs.pop(dst, None), dst: exprs.pop(src, None)} exprs.update({reg: e for reg, e in moved.items() if e is not None and reg in self.uniform_v}) @@ -5541,16 +9706,25 @@ def op_v_cndmask_b32(self, ops, mods): raise Unsupported('v_cndmask_b32 with %s' % mods) if len(ops) not in (3, 4): raise Unsupported('v_cndmask_b32 with %d operands, expected 3 or 4' % len(ops)) + for source in ops[1:3]: + self.reject_lane_mask_data('v_cndmask_b32', source) mask = self.u(ops[3]) if len(ops) > 3 else 'vcc' + align4 = self.operand_align4(ops[1]) and self.operand_align4(ops[2]) self.set_v(reg_range(ops[0])[1], - '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1]))) + '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1])), align4=align4) def op_v_interp_p1_f32(self, ops, mods): + if ops[1].startswith(('-', '|')): + raise Unsupported('interpolation source modifier %s' % ops[1]) if hasattr(self, 'uniform_v'): self.uniform_v.discard(reg_range(ops[0])[1]) + if isinstance(self.align4_v, set): + self.align4_v.discard(reg_range(ops[0])[1]) self.note_attr(ops[2], 'linear') def op_v_interp_p2_f32(self, ops, mods): + if ops[1].startswith(('-', '|')): + raise Unsupported('interpolation source modifier %s' % ops[1]) attr, comp = self.note_attr(ops[2], 'linear') self.set_v(reg_range(ops[0])[1], 'U(i.param%d.%s)' % (attr, comp)) @@ -5588,8 +9762,11 @@ def interp_f16(self, op, ops, mods, vsrc, n_ops): raise Unsupported('%s interpolant %s: expected attrN.x/.y/.z/.w' % (op, ops[2])) attr, component = self.note_attr(ops[2], 'f16') chan, high = 'xyzw'.index(component), int('high' in mods) - vs = getattr(getattr(self, 'pipe', None), 'vs', None) - if vs is not None and attr in vs.plain_params and attr not in vs.compr_params: + pipe = getattr(self, 'pipe', None) + vs = getattr(pipe, 'vs', None) + mesh_plain = getattr(pipe, 'mesh_plain_params', None) + if (vs is not None and attr in vs.plain_params and attr not in vs.compr_params) or ( + mesh_plain is not None and attr in mesh_plain): self.f16_plain.setdefault(attr, set()).add(chan) return attr, 'hparam%d_%s.%s' % (attr, ('lo', 'hi')[high], component), high if chan > 1: @@ -5632,8 +9809,10 @@ def interp_f16_scan(self): if n.startswith('s_cbranch') or n == 's_branch': target = int(ops[0].split('_')[1], 16) if target is not None: - if target <= off: - raise Unsupported('a backward branch in a program with v_interp_p1ll_f16 / v_interp_p2_f16') + # A backward branch needs no refusal of its own: every branch instruction is a boundary below, where + # the scan requires that no p1ll result is pending, no p2 result is stale and no destination has an + # undefined upper half. Nothing the scan tracks therefore travels along a back edge, and the loop head + # (also a boundary, entered with the same empty state) starts clean on every iteration. targets.add(target) def regs(tok): @@ -5807,8 +9986,9 @@ def operand(tok, is_half, is_hi): return '(-%s)' % text if neg else text # v_fma_mix* is fused, but HLSL may round `a * b` before the add, so binary32 sources with long - # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). - expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) + # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). mix32 is a precise + # mad: without it an RDNA 1 and an RDNA 4 driver drop the sign of a -0 product (#2729, #2746). + expr = 'mix32(%s, %s, %s)' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) if clamp: expr = 'saturate(%s)' % expr d = reg_range(ops[0])[1] @@ -5831,6 +10011,110 @@ def op_v_fma_mixlo_f16(self, ops, mods): def op_v_fma_mixhi_f16(self, ops, mods): self.mix(ops, mods, 'hi') + def op_v_pk_mul_lo_u16(self, ops, mods): + self.packed_half('v_pk_mul_lo_u16', 2, '((({0}) * ({1})) & 0xffffu)', + ops, mods, select_bits=True) + + def _packed_mad_16(self, base, signed, ops, mods): + clamp_count = sum(1 for m in mods if m == 'clamp') + if clamp_count > 1: + raise Unsupported('%s with duplicate clamp' % base) + rest_mods = [m for m in mods if m != 'clamp'] + if clamp_count: + if signed: + expr = ('(asuint(clamp((asint(({0}) << 16) >> 16) * (asint(({1}) << 16) >> 16) ' + '+ (asint(({2}) << 16) >> 16), -32768, 32767)) & 0xffffu)') + else: + expr = 'min((({0}) * ({1}) + ({2})), 0xffffu)' + else: + expr = '((({0}) * ({1}) + ({2})) & 0xffffu)' + self.packed_half(base, 3, expr, ops, rest_mods, select_bits=True) + + def op_v_pk_mad_u16(self, ops, mods): + self._packed_mad_16('v_pk_mad_u16', False, ops, mods) + + def op_v_pk_mad_i16(self, ops, mods): + self._packed_mad_16('v_pk_mad_i16', True, ops, mods) + + def packed_half(self, base, arity, text, ops, mods, *, select_bits=False): + """Apply the same binary16 operation to each of two selected halves. + + Result low half = op(source i half op_sel[i], ...); high half = op(source i half op_sel_hi[i], ...). Absent + modifiers mean op_sel [0,0,0] and op_sel_hi [1,1,1] (LLVM VOP3P defaults). Both lanes are written (no zeroing). + Add, mul and fma require plain VGPRs. Min and max also accept numeric SGPRs, 32-bit hex literals and inline 0, + and select a result by its encoding. All forms refuse neg_lo, neg_hi, clamp and other modifiers. + """ + if len(ops) != arity + 1: + raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) + sel = {'op_sel': [0] * arity, 'op_sel_hi': [1] * arity} + for m in mods: + key, _, value = m.partition(':') + if key not in sel or not (value.startswith('[') and value.endswith(']')): + raise Unsupported('%s with %s' % (base, m)) + bits = value[1:-1].split(',') + if len(bits) != arity or any(b not in ('0', '1') for b in bits): + raise Unsupported('%s with %s' % (base, m)) + sel[key] = [int(b) for b in bits] + for i, tok in enumerate(ops): + r = reg_range(tok) + if select_bits and i: + if re.fullmatch(r'0x[0-9a-f]{1,8}|0', tok): + continue + if r and tok == '%s%d' % (r[0], r[1]) and r[1] <= (255 if r[0] == 'v' else 105): + continue + raise Unsupported('%s source %s requires a single VGPR, numeric SGPR, hex word or inline 0' + % (base, tok)) + if not r or r[0] != 'v' or r[1] != r[2] or tok != 'v%d' % r[1]: + raise Unsupported('%s operand %s is not a single VGPR' % (base, tok)) + if select_bits and r[1] > 255: + raise Unsupported('%s destination %s is out of range' % (base, tok)) + lanes = [] + for picks in (sel['op_sel'], sel['op_sel_hi']): + args = [] + for tok, hi, both in zip(ops[1:], picks, zip(sel['op_sel'], sel['op_sel_hi'])): + if select_bits and tok.startswith('s'): + self.reject_lane_mask_data(base, tok) + word = self.S(int(tok[1:])) + else: + word = self.u(tok, low16_only=not any(both)) + half = '(%s >> 16) & 0xffffu' % word if hi else '%s & 0xffffu' % word + args.append(half if select_bits else 'f16tof32(%s)' % half) + expr = text.format(*args) + lanes.append(expr if select_bits else 'f16rn(%s)' % expr) + d = reg_range(ops[0])[1] + self.set_v(d, '%s | (%s << 16)' % tuple(lanes)) + + def op_v_pk_mul_f16(self, ops, mods): + self.packed_half('v_pk_mul_f16', 2, 'mul16({0}, {1})', ops, mods) + + def op_v_pk_add_f16(self, ops, mods): + self.packed_half('v_pk_add_f16', 2, '{0} + {1}', ops, mods) + + def op_v_pk_fma_f16(self, ops, mods): + self.packed_half('v_pk_fma_f16', 3, 'fma16o({0}, {1}, {2})', ops, mods) + + def op_v_pk_max_f16(self, ops, mods): + self.packed_half('v_pk_max_f16', 2, 'minmax16_bits({0}, {1}, true)', ops, mods, select_bits=True) + + def op_v_pk_min_f16(self, ops, mods): + self.packed_half('v_pk_min_f16', 2, 'minmax16_bits({0}, {1}, false)', ops, mods, select_bits=True) + + def op_v_pk_max_u16(self, ops, mods): + self.packed_half('v_pk_max_u16', 2, 'max({0}, {1})', ops, mods, select_bits=True) + + def op_v_pk_min_u16(self, ops, mods): + self.packed_half('v_pk_min_u16', 2, 'min({0}, {1})', ops, mods, select_bits=True) + + def op_v_pk_max_i16(self, ops, mods): + self.packed_half('v_pk_max_i16', 2, + '(asuint(max(asint(({0}) << 16) >> 16, asint(({1}) << 16) >> 16)) & 0xffffu)', + ops, mods, select_bits=True) + + def op_v_pk_min_i16(self, ops, mods): + self.packed_half('v_pk_min_i16', 2, + '(asuint(min(asint(({0}) << 16) >> 16, asint(({1}) << 16) >> 16)) & 0xffffu)', + ops, mods, select_bits=True) + def cube(self, kind, ops, mods): """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. @@ -5864,6 +10148,19 @@ def cube(self, kind, ops, mods): }[kind] self.set_vf(dst[1], expression, mods) + def op_v_pk_lshlrev_b16(self, ops, mods): + self.packed_half('v_pk_lshlrev_b16', 2, '((({1}) << (({0}) & 15u)) & 0xffffu)', + ops, mods, select_bits=True) + + def op_v_pk_lshrrev_b16(self, ops, mods): + self.packed_half('v_pk_lshrrev_b16', 2, '(({1}) >> (({0}) & 15u))', + ops, mods, select_bits=True) + + def op_v_pk_ashrrev_i16(self, ops, mods): + self.packed_half('v_pk_ashrrev_i16', 2, + '(asuint(asint(({1}) << 16) >> (16u + (({0}) & 15u))) & 0xffffu)', + ops, mods, select_bits=True) + def op_v_cubeid_f32(self, ops, mods): self.cube('id', ops, mods) @@ -5876,8 +10173,158 @@ def op_v_cubetc_f32(self, ops, mods): def op_v_cubema_f32(self, ops, mods): self.cube('ma', ops, mods) - def i64_words(self, tok): - """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair or an inline int.""" + def _packed_add_sub_16(self, base, signed, is_sub, ops, mods): + clamp_count = sum(1 for m in mods if m == 'clamp') + if clamp_count > 1: + raise Unsupported('%s with duplicate clamp' % base) + rest_mods = [m for m in mods if m != 'clamp'] + if clamp_count: + if signed: + op = '-' if is_sub else '+' + expr = '(asuint(clamp((asint(({0}) << 16) >> 16) %s (asint(({1}) << 16) >> 16), -32768, 32767)) & 0xffffu)' % op + elif is_sub: + expr = '(({0}) > ({1}) ? (({0}) - ({1})) : 0u)' + else: + expr = 'min(({0}) + ({1}), 0xffffu)' + else: + op = '-' if is_sub else '+' + expr = '((({0}) %s ({1})) & 0xffffu)' % op + self.packed_half(base, 2, expr, ops, rest_mods, select_bits=True) + + def op_v_pk_add_i16(self, ops, mods): + self._packed_add_sub_16('v_pk_add_i16', True, False, ops, mods) + + def op_v_pk_sub_i16(self, ops, mods): + self._packed_add_sub_16('v_pk_sub_i16', True, True, ops, mods) + + def op_v_pk_add_u16(self, ops, mods): + self._packed_add_sub_16('v_pk_add_u16', False, False, ops, mods) + + def op_v_pk_sub_u16(self, ops, mods): + self._packed_add_sub_16('v_pk_sub_u16', False, True, ops, mods) + + def op_v_ldexp_f32(self, ops, mods): + if len(ops) != 3: + raise Unsupported('v_ldexp_f32 with %d operands, expected 3' % len(ops)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('v_ldexp_f32 destination %s' % ops[0]) + src0 = self.f(ops[1]) + src1_tok = ops[2] + if src1_tok.startswith('-') and not re.fullmatch(r'-\d+', src1_tok): + raise Unsupported('v_ldexp_f32 exponent %s has float modifier' % src1_tok) + if src1_tok.startswith('|') or src1_tok.endswith('|') or src1_tok.startswith('abs('): + raise Unsupported('v_ldexp_f32 exponent %s has float modifier' % src1_tok) + sr = reg_range(src1_tok) + if sr is not None: + if sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105): + raise Unsupported('v_ldexp_f32 source %s' % src1_tok) + elif src1_tok not in FLOATS and src1_tok not in ('m0', 'null'): + try: + val = int(src1_tok, 0) + except ValueError: + raise Unsupported('operand %r' % src1_tok) + if not -0x80000000 <= val <= 0xffffffff: + raise Unsupported('v_ldexp_f32 source %s' % src1_tok) + src1 = 'asint(%s)' % self.u(src1_tok) + self.set_vf(dst[1], 'ldexp32(%s, %s)' % (src0, src1), mods) + + def dot8_int(self, name, signed, ops, mods): + """VOP3P 8-nibble integer dot product with 32-bit accumulate and optional saturating clamp.""" + if len(ops) != 4: + raise Unsupported('%s with %d operands, expected 4' % (name, len(ops))) + if any(m != 'clamp' for m in mods): + raise Unsupported('%s with unsupported modifiers %s' % (name, mods)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + args = [] + for tok in ops[1:4]: + if (tok.startswith('|') or tok.endswith('|') or tok.startswith(('abs(', 'neg(')) + or (tok.startswith('-') and not re.fullmatch(r'-\d+', tok))): + raise Unsupported('%s source modifier %s' % (name, tok)) + sr = reg_range(tok) + if sr and (sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105)): + raise Unsupported('%s source %s' % (name, tok)) + args.append(self.u(tok)) + pipe = getattr(self, 'pipe', None) + if pipe is not None and isinstance(getattr(pipe, 'uses_dot8', None), set): + pipe.uses_dot8.add(name) + helper = 'dot8_i32_i4' if signed else 'dot8_u32_u4' + sat = 'true' if 'clamp' in mods else 'false' + self.set_v(dst[1], '%s(%s, %s, %s, %s)' % (helper, args[0], args[1], args[2], sat)) + + def op_v_dot8_i32_i4(self, ops, mods): + return self.dot8_int('v_dot8_i32_i4', True, ops, mods) + + def op_v_dot8_u32_u4(self, ops, mods): + return self.dot8_int('v_dot8_u32_u4', False, ops, mods) + + def dot2_int(self, name, signed, ops, mods): + """VOP3P 2-halfword integer dot product with 32-bit accumulate and optional saturating clamp.""" + if len(ops) != 4: + raise Unsupported('%s with %d operands, expected 4' % (name, len(ops))) + if any(m != 'clamp' for m in mods): + raise Unsupported('%s with unsupported modifiers %s' % (name, mods)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + args = [] + for tok in ops[1:4]: + if (tok.startswith('|') or tok.endswith('|') or tok.startswith(('abs(', 'neg(')) + or (tok.startswith('-') and not re.fullmatch(r'-\d+', tok))): + raise Unsupported('%s source modifier %s' % (name, tok)) + sr = reg_range(tok) + if sr and (sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105)): + raise Unsupported('%s source %s' % (name, tok)) + args.append(self.u(tok)) + pipe = getattr(self, 'pipe', None) + if pipe is not None and isinstance(getattr(pipe, 'uses_dot2', None), set): + pipe.uses_dot2.add(name) + helper = 'dot2_i32_i16' if signed else 'dot2_u32_u16' + sat = 'true' if 'clamp' in mods else 'false' + self.set_v(dst[1], '%s(%s, %s, %s, %s)' % (helper, args[0], args[1], args[2], sat)) + + def op_v_dot2_i32_i16(self, ops, mods): + return self.dot2_int('v_dot2_i32_i16', True, ops, mods) + + def op_v_dot2_u32_u16(self, ops, mods): + return self.dot2_int('v_dot2_u32_u16', False, ops, mods) + + def dot4_int(self, name, signed, ops, mods): + """VOP3P 4-byte integer dot product with 32-bit accumulate and optional saturating clamp.""" + if len(ops) != 4: + raise Unsupported('%s with %d operands, expected 4' % (name, len(ops))) + if any(m != 'clamp' for m in mods): + raise Unsupported('%s with unsupported modifiers %s' % (name, mods)) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + args = [] + for tok in ops[1:4]: + if (tok.startswith('|') or tok.endswith('|') or tok.startswith(('abs(', 'neg(')) + or (tok.startswith('-') and not re.fullmatch(r'-\d+', tok))): + raise Unsupported('%s source modifier %s' % (name, tok)) + sr = reg_range(tok) + if sr and (sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105)): + raise Unsupported('%s source %s' % (name, tok)) + args.append(self.u(tok)) + pipe = getattr(self, 'pipe', None) + if pipe is not None and isinstance(getattr(pipe, 'uses_dot4', None), set): + pipe.uses_dot4.add(name) + helper = 'dot4_i32_i8' if signed else 'dot4_u32_u8' + sat = 'true' if 'clamp' in mods else 'false' + self.set_v(dst[1], '%s(%s, %s, %s, %s)' % (helper, args[0], args[1], args[2], sat)) + + def op_v_dot4_i32_i8(self, ops, mods): + return self.dot4_int('v_dot4_i32_i8', True, ops, mods) + + def op_v_dot4_u32_u8(self, ops, mods): + return self.dot4_int('v_dot4_u32_u8', False, ops, mods) + + def i64_words(self, tok, signed=False, literal=False): + """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair, an inline int or a + 32-bit hex literal when `literal` is set (zero-extended, sign-extended when the operation is signed).""" pair = reg_range(tok) if pair and pair[2] == pair[1] + 1: if pair[0] == 'v' and pair[2] <= 255: @@ -5888,6 +10335,9 @@ def i64_words(self, tok): if re.fullmatch(r'0|-?[1-9]\d*', tok) and -16 <= int(tok) <= 64: value = int(tok) & 0xffffffffffffffff return '%du' % (value & 0xffffffff), '%du' % (value >> 32) + if literal and re.fullmatch(r'0x[0-9a-f]{1,8}', tok): + word = int(tok, 16) + return '%du' % word, ('4294967295u' if signed and word >> 31 else '0u') raise Unsupported('64-bit source %s' % tok) def shift64(self, ops, mods, helper): @@ -5903,16 +10353,30 @@ def shift64(self, ops, mods, helper): or ops[1] in ('vcc', 'exec') or ops[1] in FLOATS): raise Unsupported('64-bit shift amount %s' % ops[1]) amount = self.u(ops[1]) - low, high = self.i64_words(ops[2]) + low, high = self.i64_words(ops[2], helper == 'shr64i', True) body = '{ uint2 t = %s(%s, %s, %s); v%d = t.x; v%d = t.y; }' % ( helper, low, high, amount, dst[1], dst[2]) if hasattr(self, 'uniform_v'): self.uniform_v.discard(dst[1]) self.uniform_v.discard(dst[2]) + if isinstance(self.align4_v, set): + self.align4_v.discard(dst[1]) + self.align4_v.discard(dst[2]) self.clear_low16(dst[1]) self.clear_low16(dst[2]) self.used_v.update((dst[1], dst[2])) self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + # Scalar or literal sources give every lane the same result, under the conditions Stage.one uses for VALU. + pair = reg_range(ops[2]) + sources = [ops[1]] + (['%s%d' % (pair[0], pair[1]), '%s%d' % (pair[0], pair[2])] if pair else []) + if (self.tracks_uniformity() and not any(reg_range(t)[0] == 'v' for t in sources if reg_range(t)) and + all(self.uniform_source(t) for t in sources) and + (getattr(self, 'past_entry', False) and hasattr(self, 'uniform_expr') or + not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False))): + self.uniform_v.update((dst[1], dst[2])) + if hasattr(self, 'uniform_expr'): + for n, half in ((dst[1], 'x'), (dst[2], 'y')): + self.uniform_expr[n] = '%s(%s, %s, %s).%s' % (helper, low, high, amount, half) def carry_out_op(self, ops, mods, kind): """v_{add,sub,subrev}_co_u32 D, SDST, S0, S1: a 32-bit add or subtract with a carry or borrow out. @@ -5942,7 +10406,8 @@ def carry_out_op(self, ops, mods, kind): else: self.emit('a = %s - %s;' % (a, b)) self.emit('w = %s > %s ? 1u : 0u;' % (b, a)) - self.set_v(d[1], 'a') + align4 = self.operand_align4(ops[2]) and self.operand_align4(ops[3]) + self.set_v(d[1], 'a', align4=align4) predicate = 'w' if self.exec_known else '(exec & w)' if ops[1] in ('vcc', 'vcc_lo'): self.emit('vcc = %s;' % predicate) @@ -6027,6 +10492,60 @@ def op_v_lshrrev_b64(self, ops, mods): def op_v_ashrrev_i64(self, ops, mods): self.shift64(ops, mods, 'shr64i') + + def mad64(self, ops, mods, signed): + """v_mad_u64_u32 / v_mad_i64_i32: D = S0 * S1 + S2 modulo 2^64, two 32-bit factors, 64-bit S2. + + The unsigned form also writes the carry-out of the 64-bit add to a lane mask. The signed carry-out + is not established, so the signed form is accepted only with the discarding null destination.""" + name = 'v_mad_i64_i32' if signed else 'v_mad_u64_u32' + if mods: + raise Unsupported('%s with %s' % (name, mods)) + if len(ops) != 5: + raise Unsupported('%s with %d operands, expected 5' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] != dst[1] + 1 or dst[2] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + mask = ops[1] + mask_reg = reg_range(mask) + if signed: + if mask != 'null': + raise Unsupported('%s carry-out %s: only null is lowered' % (name, mask)) + elif mask not in ('vcc', 'vcc_lo') and not ( + mask_reg and mask_reg[0] == 's' and mask_reg[1] == mask_reg[2] and mask_reg[1] <= 105): + raise Unsupported('%s carry-out %s' % (name, mask)) + for tok in ops[2:4]: + r = reg_range(tok) + if tok in FLOATS or tok in ('exec', 'exec_lo') or ( + r and (r[1] != r[2] or (r[0] == 'v' and r[1] > 255) or (r[0] == 's' and r[1] > 105))): + raise Unsupported('%s factor %s' % (name, tok)) + for tok in ops[2:5]: + r = reg_range(tok) + if tok in ('vcc', 'vcc_lo', 'vcc_hi') or (r and r[0] == 's' and any( + w in self.masks for w in range(r[1], r[2] + 1))): + # u() would supply the per-lane 0/1 projection, not the architectural 32-bit mask. + raise Unsupported('%s reads the lane mask %s as an integer' % (name, tok)) + low, high = self.i64_words(ops[4]) + self.emit('{ uint3 r = %s(%s, %s, %s, %s);' % ('mad64i' if signed else 'mad64u', + self.u(ops[2]), self.u(ops[3]), low, high)) + self.set_v(dst[1], 'r.x') + self.set_v(dst[2], 'r.y') + if not signed: + expr = 'r.z' if self.exec_known else '(exec & r.z)' + if mask in ('vcc', 'vcc_lo'): + self.emit('vcc = %s;' % expr) + else: + # The carry is a per-lane bit: never a uniform scalar, whatever the scratch name hides. + self.set_s(mask_reg[1], expr, uniform=False) + self.masks.add(mask_reg[1]) + self.emit('}') + + def op_v_mad_u64_u32(self, ops, mods): + self.mad64(ops, mods, False) + + def op_v_mad_i64_i32(self, ops, mods): + self.mad64(ops, mods, True) + def op_v_cvt_pkrtz_f16_f32(self, ops, mods): if len(ops) != 3: raise Unsupported('v_cvt_pkrtz_f16_f32 with %d operands, expected 3' % len(ops)) @@ -6124,8 +10643,6 @@ def compare(self, base, ops, mods=()): f16 = name.endswith('_f16') writes_exec = name in ('v_cmpx_class_f32', 'v_cmpx_class_f16') sdwa = name != base - if f16 and sdwa: - raise Unsupported('SDWA form of %s' % name) if sdwa: self.check_compare_sdwa_destination(base, writes_exec, ops) if len(ops) == 3: @@ -6135,7 +10652,20 @@ def compare(self, base, ops, mods=()): dst, (value, mask) = 'exec', ops else: raise Unsupported('%s with %d operands' % (base, len(ops))) - if sdwa: + if sdwa and f16: + # SDWA half class: classes bits [15:0] of a plain register. src0_sel DWORD and WORD_0 both + # leave those bits where class16 reads them; WORD_1, a byte, sext() and the abs/neg spellings + # (which print |v|, -v, abs(), neg()) would classify other bits, so they are refused. + selections = [m for m in mods if m.startswith('src0_sel:')] + if selections not in (['src0_sel:DWORD'], ['src0_sel:WORD_0']): + raise Unsupported('SDWA form of %s with %s' % (name, ' '.join(selections) or 'no src0_sel')) + if not reg_range(value): + raise Unsupported('%s with source %s' % (base, value)) + if mask in FLOATS: + raise Unsupported('%s mask %s: expected an integer class mask' % (base, mask)) + _word, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods) + value = self.u(value) + elif sdwa: value, mask = self.compare_sdwa_sources(base, 'u32', [value, mask], mods, float_src0=True) elif f16: # abs() and - apply to bit 15 of the half, before the class test. @@ -6265,6 +10795,8 @@ def export(self, asm): % next(f for f in flags if f.startswith('en:'))[3:]) if 'vm' in flags and not self.exec_known: self.emit('if (!(exec & 1)) discard;') + if hasattr(self, 'lane_exec_breaks'): + self.lane_exec_breaks.append((self.pc, 'a discard')) if target == 'null': return None # the null target writes no render target; its only effect is the vm discard above if target == 'mrtz': @@ -6353,13 +10885,15 @@ def goto(off): raise Unsupported('branch into the middle of a block (+0x%x)' % off) return index[off] out.append(' uint pc = 0;') + wave_load_blocks = {off + n for off, n, _, _ in self.ins if off in getattr(self, 'mesh_wave_loads', {})} if loops: out.append(' [loop] for (uint guard = 0; guard < 65536 && pc != 0xffffu; ++guard) {') for i, (off, lines, term) in enumerate(self.blocks): if off == getattr(self, 'mesh_allocation_block', None): out.append(' {') else: - out.append(' %sif (pc == %d) {' % ('else ' if loops and i else '', i)) + attribute = '[branch] ' if off in wave_load_blocks else '' + out.append(' %s%sif (pc == %d) {' % ('else ' if loops and i else '', attribute, i)) out += [' ' + line for line in lines] nxt = i + 1 if i + 1 < len(self.blocks) else 0xffff if not term: @@ -6386,7 +10920,13 @@ def declarations(self): lines.append(' v%d = (uint(i.pos.x) & 0xffffu) | ((uint(i.pos.y) & 0xffffu) << 16);' % packed) if getattr(self, 'spill_slots', None): lines.append(' uint %s;' % ', '.join('sp%d_%d = 0' % k for k in sorted(self.spill_slots))) + if getattr(self, 'uniform_load_temps', None): + lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in sorted(self.uniform_load_temps))) + if getattr(self, 'resheap_index_temps', None): + lines.append(' uint %s;' % ', '.join('%s = 0' % n for n in self.resheap_index_temps)) lines.append(' uint vcc = 0, exec = 1, m0 = 0, a = 0, w = 0; bool scc = false; float4 t = 0;') + if getattr(self, 'mesh_wave_loads', {}): + lines.append(' bool wave_any = false;') if getattr(self, 'used_atomic', None): if 'uint' in self.used_atomic: lines.append(' uint ao = 0;') @@ -6395,6 +10935,300 @@ def declarations(self): lines += [' s%d = %s;' % kv for kv in sorted(getattr(self, 'materialized', {}).items())] return lines + # ---- whole-wave reductions (#2125 item D) -------------------------------------------------------------------------- + # A wave32 reduction reads lanes outside the pixel quad, so its instructions cannot be lowered one at a time. The + # whole chain is recognised instead, in the order the #2125 censuses report for every wave32 chain (LLVM 15 + # spelling; vT, vX, vP, sS, sD any registers, OP one operation, ID its identity): + # s_or_saveexec_b32 sS, -1 save EXEC, enable all 32 lanes + # v_cndmask_b32_e64 vT, ID, vX, sS the identity fill: vX where sS has the lane, ID elsewhere + # OP_dpp vT, vT, vT quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf lane pairs + # OP_dpp vT, vT, vT quad_perm:[2,3,0,1] ... quads + # OP_dpp vT, vT, vT row_half_mirror ... lane i with lane 7 - i: eight lanes + # OP_dpp vT, vT, vT row_mirror ... lane i with lane 15 - i: the row of sixteen + # v_permlanex16_b32 vP, vT, 0, 0 lane 0 of the other row + # OP vT, vP, vT every lane now holds the whole wave + # s_mov_b32 exec_lo, sS + # v_readlane_b32 sD, vT, 31 + # (RDNA 2 ISA: DPP16 quad_perm, row_half_mirror and row_mirror, V_PERMLANEX16_B32, V_READLANE_B32.) With every + # lane enabled no DPP or permlane source is disabled, so bound_ctrl and fi have nothing to decide. sD is OP over + # the lanes active before the chain, the others adding the identity. The census also shows a min chain whose + # readlane comes later: after its restore, one v_cndmask_b32_sdwa, then the s_or_saveexec_b32 sS2, -1 of a max + # chain, and only then v_readlane_b32 sD, vT, 31; the max chain takes that readlane between its saveexec and its + # fill. Readlane ignores EXEC, so the min result is still the one in vT as long as nothing in between writes vT + # (checked); the v_cndmask_b32_sdwa keeps its own handler, under the restored EXEC. The console packs pixels into + # waves in its own way, so a correct program cannot depend on which pixels share a wave: the chain becomes one + # WaveActiveBitOr / WaveActiveMin / WaveActiveMax of vX over the active lanes of the desktop wave, which leaves + # helper lanes out. Accepted in a pixel stage whose EXEC is the entry mask, not widened by s_wqm (helper lanes + # would then be counted on the console). The chain itself is straight: no branch instruction and no branch target + # inside it, and EXEC is saved and restored as in the shapes above. A uniform branch (SCC proven uniform, or an + # unconditional s_branch) may sit before the chain, after it, or both; every lane then reaches the chain together, + # which is what WaveActive* reduces. A branch that is not proven uniform is refused, as is a non-uniform branch + # that changes EXEC inside the chain. Wave64 stays refused. Every other shape that starts like a chain is refused + # with its reason: another fill, a wrong identity, missing or reordered steps, other or mixed operations, other + # lane selects, the readlane before the restore, an unrestored EXEC, a later readlane in another place or with vT + # rewritten before it, or vP read before it is rewritten. + WAVE_REDUCE = {'v_or_b32': ('WaveActiveBitOr({0})', 0), 'v_min_u32': ('WaveActiveMin({0})', 0xffffffff), + 'v_max_u32': ('WaveActiveMax({0})', 0)} + WAVE_REDUCE_STEPS = ('quad_perm:[1,0,3,2]', 'quad_perm:[2,3,0,1]', 'row_half_mirror', 'row_mirror') + + @staticmethod + def wave_reduce_cndmask_fill(stretch, ss): + """The identity fill of the census: exactly v_cndmask_b32_e64 vT, 0 | -1, vX, sS (the input where the saved + mask has the lane, the inline constant elsewhere). (vT, 'vX', identity), or None for any other stretch.""" + if len(stretch) != 1: + return None + base, ops, mods, _text = stretch[0] + if base != 'v_cndmask_b32' or mods or len(ops) != 4 or ops[3] != 's%d' % ss or ops[1] not in ('0', '-1') or \ + not re.fullmatch(r'v\d+', ops[0]) or not re.fullmatch(r'v\d+', ops[2]) or ops[0] == ops[2]: + return None + return int(ops[0][1:]), ops[2], int(ops[1]) & 0xffffffff + + # The identity fill, between s_or_saveexec_b32 sS, -1 and the first quad_perm step: each entry is a function + # (stretch, sS) -> (vT, input operand, identity) for a form it proves, or None; stretch is a list of + # (base, operands, modifiers, text). The identity itself is checked against OP afterwards. + WAVE_REDUCE_FILLS = (wave_reduce_cndmask_fill,) + # A VALU write of the first operand that keeps or reads the old value of that register does not end vP's life. + WAVE_REDUCE_KEEPS = re.compile(r'v_(f?mac|pk_fmac|dot\w*c|interp_p2|writelane|swap|movrel)|.*(16|_dpp|_dpp8|_sdwa)$') + + def wave_reduce_branch_reason(self, pc, end): + """None when this chain may run in the current pixel program. + + A straight-line program is unchanged. A program with branches is accepted only when the chain span itself + holds no branch, every branch already translated is proven uniform (it is in uniform_branches, not + divergent_branches), and EXEC is still the entry mask at the caller. A uniform branch that has not been + translated yet sits after the chain; wave_reduce_branch_refusals checks it once its condition is known. + Anything else keeps the straight-line refusal. A probe that never ran translate() has no uniformity map and + stays refused, which is the previous behaviour.""" + branched = getattr(self, 'has_branches', True) or bool(getattr(self, 'blocks', True)) + if not branched: + return None + for off, _n, name, _asm in self.ins: + if pc < off <= end and (name.startswith('s_cbranch') or name == 's_branch'): + return 'wave reduction: branch inside the chain' + divergent = getattr(self, 'divergent_branches', None) + if divergent is None: + return 'wave reduction in a program with branches: only straight-line pixel stages are lowered' + earlier = [(off, name) for off, name in divergent.items() if off <= end] + if earlier: + off, name = min(earlier) + return ('wave reduction in a program with branches: %s at +0x%x is not proven uniform' % (name, off)) + return None + + def wave_reduce_branch_refusals(self): + """[(offset, reason)] for a chain whose program has a divergent branch after it. + + The branch is classified only when translate() reaches it, which is after the chain has been matched.""" + out = [] + divergent = getattr(self, 'divergent_branches', {}) + for start, end in getattr(self, 'wave_reduce_spans', ()): + later = sorted((off, name) for off, name in divergent.items() if off > end) + if later: + off, name = later[0] + out.append((start, 'wave reduction in a program with branches: %s at +0x%x is not proven uniform' + % (name, off))) + return out + + def wave_reduction(self, base, ops): + """True when this instruction belongs to a recognised wave reduction (its result is lowered at the restore of + EXEC, its readlane at the readlane). False for anything that does not start like one; Unsupported for a chain of + the wrong shape.""" + plan, pc = getattr(self, 'reduce_plan', None), getattr(self, 'pc', None) + if plan and pc in plan: + action = plan[pc] + if action: + action() + return True + if pc is None or not isinstance(getattr(self, 'ins', None), list) or not ( + base in ('s_or_saveexec_b32', 's_or_saveexec_b64') and len(ops) == 2 and ops[1] == '-1'): + return False + index = next((i for i, item in enumerate(self.ins) if item[0] == pc), None) + if index is None: + return False + steps = [parse(asm) for _off, _n, _name, asm in self.ins[index:index + 17]] + if not any(name == 'v_permlanex16_b32' or name.endswith('_dpp') and ('row_mirror' in mods or + 'row_half_mirror' in mods) + for name, _ops, mods in steps[1:]): + return False # not a reduction: the instruction keeps its own handler + if base.endswith('_b64'): + raise Unsupported('wave reduction in the wave64 form (%s %s): only the wave32 chain is lowered' + % (base, ', '.join(ops))) + # A non-uniform branch and an EXEC write that is not the chain's own restore, both before the lane-31 + # readlane (or anywhere in the lookahead, if that readlane is not in it). The chain's s_mov of exec_lo and a + # following chain's s_or_saveexec_b32 are the writes the accepted shapes already have; either without an + # EXEC branch is left to the shape matcher. + read_at = next((k for k, (name, o, _m) in enumerate(steps) + if name == 'v_readlane_b32' and len(o) == 3 and o[2] == '31'), None) + region = steps[1:read_at] if read_at else steps[1:] + exec_branch = next((name for name, _o, _m in region + if name in ('s_cbranch_execz', 's_cbranch_execnz')), None) + extra_exec = any(writes_exec(name, o) and not (name == 's_mov_b32' and o[:1] == ['exec_lo']) + and name != 's_or_saveexec_b32' for name, o, _m in region) + if exec_branch and extra_exec: + raise Unsupported('wave reduction: non-uniform branch %s changes EXEC inside the chain' % exec_branch) + ss = reg_range(ops[0]) + if not ss or ss[0] != 's' or ss[1] != ss[2]: + raise Unsupported('wave reduction: s_or_saveexec_b32 %s, -1 does not save EXEC in one SGPR' % ops[0]) + ss = ss[1] + first = next((k for k, (name, _o, m) in enumerate(steps) + if name.endswith('_dpp') and set(m) & set(self.WAVE_REDUCE_STEPS)), len(steps)) + items = self.ins[index:index + first + 10] + + def at(k, what): + if k >= len(items): + raise Unsupported('wave reduction: the chain ends before %s' % what) + name, o, m = parse(items[k][3]) + return re.sub(r'_e(32|64)$', '', name), o, m, items[k][3] + + stretch = [at(k, 'the first quad_perm step') for k in range(1, first)] + pending = getattr(self, 'reduce_pending', {}) + taken = None # the later readlane of the min chain just before, which this chain carries before its fill + if stretch and stretch[0][0] == 'v_readlane_b32' and items[1][0] in pending: + taken = pending[items[1][0]] + stretch = stretch[1:] + fill = next((found for found in (form(stretch, ss) for form in self.WAVE_REDUCE_FILLS) if found), None) + if fill is None: + raise Unsupported('wave reduction: the identity fill after s_or_saveexec_b32 s%d, -1 (%s) is not a known ' + 'form' % (ss, ' / '.join(t[3] for t in stretch) or 'no instruction')) + vt, source, identity = fill + op = None + for k, want in enumerate(self.WAVE_REDUCE_STEPS): + b, o, m, text = at(first + k, want) + if not b.endswith('_dpp'): + raise Unsupported('wave reduction: missing step %s (found %s)' % (want, text)) + controls = [x for x in m if not x.startswith(('row_mask:', 'bank_mask:', 'bound_ctrl:', 'fi:'))] + if controls != [want]: + order = ' (steps out of order or missing)' if controls and controls[0] in self.WAVE_REDUCE_STEPS else '' + raise Unsupported('wave reduction: %s in place of %s%s' % (' '.join(controls) or 'no DPP control', want, + order)) + if 'row_mask:0xf' not in m or 'bank_mask:0xf' not in m: + raise Unsupported('wave reduction: %s with a partial row or bank mask' % text) + this = b[:-len('_dpp')] + if this not in self.WAVE_REDUCE: + raise Unsupported('wave reduction of %s: only v_or_b32, v_min_u32 and v_max_u32 are lowered' % this) + if op not in (None, this): + raise Unsupported('wave reduction mixes %s and %s' % (op, this)) + op = this + if o != ['v%d' % vt] * 3: + raise Unsupported('wave reduction: %s does not combine v%d with itself' % (text, vt)) + if identity != self.WAVE_REDUCE[op][1]: + raise Unsupported('wave reduction of %s: the inactive lanes get 0x%08x, the identity is 0x%08x' + % (op, identity, self.WAVE_REDUCE[op][1])) + if taken is not None and op != 'v_max_u32': + raise Unsupported('wave reduction: a %s chain carries the later readlane of the v_min_u32 chain before it; ' + 'only a v_max_u32 chain is lowered there' % op) + b, o, m, text = at(first + 4, 'v_permlanex16_b32') + if b != 'v_permlanex16_b32' or len(o) != 4 or o[1] != 'v%d' % vt or not re.fullmatch(r'v\d+', o[0]) or \ + o[0] == o[1]: + raise Unsupported('wave reduction: %s in place of v_permlanex16_b32 vN, v%d, 0, 0' % (text, vt)) + if m or o[2:] != ['0', '0']: + raise Unsupported('wave reduction: %s: only the lane selects 0, 0 without modifiers are lowered' % text) + vp = int(o[0][1:]) + b, o, m, text = at(first + 5, 'the two rows are combined') + if b != op or m or len(o) != 3 or o[0] != 'v%d' % vt or sorted(o[1:]) != sorted(['v%d' % vt, 'v%d' % vp]): + mixed = b in self.WAVE_REDUCE and b != op + raise Unsupported('wave reduction %s' % ('mixes %s and %s' % (op, b) if mixed else + ': %s in place of %s v%d, v%d, v%d' % (text, op, vt, vt, vp))) + b, o, m, text = at(first + 6, 'EXEC is restored') + if b != 's_mov_b32' or o != ['exec_lo', 's%d' % ss] or m: + raise Unsupported('wave reduction: %s in place of s_mov_b32 exec_lo, s%d (EXEC restored before the readlane)' + % (text, ss)) + read = first + 7 # the readlane: right after the restore, or later in the min chain + b, o, m, text = at(read, 'v_readlane_b32') + later = b == 'v_cndmask_b32_sdwa' + if later: + # The census's min form: restore, one v_cndmask_b32_sdwa (its own handler, under the restored EXEC), the + # s_or_saveexec_b32 sS2, -1 of the max chain that follows, then this chain's readlane. Readlane ignores + # EXEC; vT must still hold the result, and sS2 must survive the readlane for the max chain's fill and + # restore. + if op != 'v_min_u32': + raise Unsupported('wave reduction of %s: %s after the restore in place of v_readlane_b32 sN, v%d, 31 ' + '(only the v_min_u32 chain reads its lane later)' % (op, text, vt)) + if o and reg_range(o[0]) and reg_range(o[0])[0] == 'v' and \ + reg_range(o[0])[1] <= vt <= reg_range(o[0])[2]: + raise Unsupported('wave reduction: %s rewrites v%d before the readlane of the v_min_u32 chain' + % (text, vt)) + b, o, m, text = at(first + 8, 'the s_or_saveexec_b32 of the v_max_u32 chain') + nxt = reg_range(o[0]) if b == 's_or_saveexec_b32' and len(o) == 2 and o[1] == '-1' and not m else None + if not nxt or nxt[0] != 's' or nxt[1] != nxt[2]: + raise Unsupported('wave reduction: %s in place of the s_or_saveexec_b32 sN, -1 of the v_max_u32 chain ' + 'before the readlane of the v_min_u32 chain' % text) + read = first + 9 + b, o, m, text = at(read, 'the readlane of the v_min_u32 chain') + sd = reg_range(o[0]) if len(o) == 3 else None + if b != 'v_readlane_b32' or m or not sd or sd[0] != 's' or sd[1] != sd[2] or sd[1] == ss or \ + o[1] != 'v%d' % vt: + raise Unsupported('wave reduction: %s in place of v_readlane_b32 sN, v%d, 31' % (text, vt)) + if o[2] != '31': + raise Unsupported('wave reduction: %s reads lane %s: only lane 31 is lowered' % (text, o[2])) + if later and sd[1] == nxt[1]: + raise Unsupported('wave reduction: the readlane of the v_min_u32 chain overwrites s%d, the EXEC saved by ' + 'the v_max_u32 chain' % sd[1]) + end = items[read][0] + targets = {int(parse(asm)[1][0].split('_')[1], 16) for _off, _n, name, asm in self.ins + if name.startswith('s_cbranch') or name == 's_branch'} + inside = sorted(t for t in targets if pc < t <= end) + if inside: + raise Unsupported('wave reduction: branch target 0x%x inside the chain' % inside[0]) + if getattr(self, 'kind', None) != 'ps' or getattr(self, 'fetched', False): + raise Unsupported('wave reduction outside a pixel stage') + branch_reason = self.wave_reduce_branch_reason(pc, end) + if branch_reason: + raise Unsupported(branch_reason) + if not getattr(self, 'exec_known', False): + raise Unsupported('wave reduction: EXEC is not the entry mask') + if getattr(self, 'wqm_exec', False): + raise Unsupported('wave reduction after s_wqm exec, exec: helper lanes are in EXEC and would be counted') + for _off, _n, name, asm in self.ins[index + first + 7:]: # everything after the restore + _name, o, _m = parse(asm) + hits = [i for i, tok in enumerate(o) if any( + int(r.group(3) or r.group(1)) <= vp <= int(r.group(3) or r.group(2)) + for r in re.finditer(r'\bv\[(\d+):(\d+)\]|\bv(\d+)\b', tok))] + if not hits: + continue + short = re.sub(r'_e(32|64)$', '', name) + if hits == [0] and short.startswith('v_') and not self.WAVE_REDUCE_KEEPS.match(short): + break + raise Unsupported('wave reduction: v%d (the other row from v_permlanex16_b32) is read after the chain by %s' + % (vp, asm)) + # Nothing of the chain is emitted until the restore, so every register read there still holds its value from + # the fill (the only instruction lowered in between is the min chain's readlane carried here, an SGPR write + # that is not this chain's saved EXEC). The readlane then copies vT, which nothing has rewritten since. + plan = self.reduce_plan = getattr(self, 'reduce_plan', {}) + if taken is not None: + taken[0] = True + for k in range(1, read + 1): + if k in (first + 7, first + 8) and later: + continue # the v_cndmask_b32_sdwa keeps its handler; the max chain's saveexec starts that chain + plan.setdefault(items[k][0], None) + plan[items[first + 6][0]] = lambda: self.lower_wave_reduction(op, vt, vp, ss, source) + claim = [False] + if later: + self.reduce_pending = {**pending, items[read][0]: claim} + plan[items[read][0]] = lambda: self.lower_wave_readlane(sd[1], vt, claim if later else None) + # Record the span only after every refusal above has passed, so a chain that is refused for EXEC or a + # later read of vP is not also reported as a branched-program reduction. + if getattr(self, 'has_branches', True) or bool(getattr(self, 'blocks', True)): + self.wave_reduce_spans = getattr(self, 'wave_reduce_spans', []) + self.wave_reduce_spans.append((pc, end)) + return True + + def lower_wave_reduction(self, op, vt, vp, ss, source): + value = self.WAVE_REDUCE[op][0].format(self.u(source)) + self.needs_sm6 = True + self.set_s(ss, 'exec') + self.sym[ss] = ('execcopy',) + self.masks.add(ss) + self.set_v(vt, value) + if hasattr(self, 'uniform_v'): + self.uniform_v.discard(vp) + self.set_scc('true') # s_or_saveexec_b32 set SCC from the all-lanes EXEC + + def lower_wave_readlane(self, sd, vt, claim): + if claim is not None and not claim[0]: + raise Unsupported('wave reduction: the later readlane of the v_min_u32 chain is not carried by a v_max_u32 ' + 'chain') + self.set_s(sd, self.u('v%d' % vt), uniform=False) + # 32-bit raw MUBUF atomics: opcode_name -> (RWByteAddressBuffer method suffix, signed, is_sub, data_vgprs) MUBUF_ATOMIC_OPS = { @@ -6443,6 +11277,7 @@ def declarations(self): # Unused w1 register field masks in RDNA 2 DS encoding (must be zero): # w1[7:0]=ADDR, w1[15:8]=DATA0, w1[23:16]=DATA1, w1[31:24]=VDST. LDS_UNUSED_W1_MASK = { + 'ds_write_b32': 0xffff0000, 'ds_write2_b32': 0xff000000, 'ds_write2st64_b32': 0xff000000, 'ds_read2st64_b32': 0x00ffff00, @@ -6453,7 +11288,7 @@ def declarations(self): VEC_F = { 'v_add_f32': (2, '{0} + {1}'), 'v_sub_f32': (2, '{0} - {1}'), 'v_subrev_f32': (2, '{1} - {0}'), 'v_mul_f32': (2, '{0} * {1}'), 'v_mul_legacy_f32': (2, 'mul_legacy({0}, {1})'), - 'v_min_f32': (2, 'min({0}, {1})'), 'v_max_f32': (2, 'max({0}, {1})'), + 'v_min_f32': (2, 'minmax_zero32({0}, {1}, false)'), 'v_max_f32': (2, 'minmax_zero32({0}, {1}, true)'), 'v_fmac_f32': (2, '{0} * {1} + {2}'), 'v_mac_f32': (2, 'mad32({0}, {1}, {2}, false)'), 'v_fma_f32': (3, '{0} * {1} + {2}'), 'v_mad_f32': (3, 'mad32({0}, {1}, {2}, false)'), 'v_mad_legacy_f32': (3, 'mad32({0}, {1}, {2}, true)'), @@ -6463,15 +11298,19 @@ def declarations(self): 'v_exp_f32': (1, 'exp2({0})'), 'v_log_f32': (1, 'log2({0})'), 'v_floor_f32': (1, 'floor({0})'), 'v_ceil_f32': (1, 'ceil({0})'), 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'fract32({0})'), 'v_rndne_f32': (1, 'round({0})'), 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), - 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), + 'v_min3_f32': (3, 'minmax_zero32({0}, minmax_zero32({1}, {2}, false), false)'), + 'v_max3_f32': (3, 'minmax_zero32({0}, minmax_zero32({1}, {2}, true), true)'), } +# v_fma_mix*: precise keeps the sign of a zero result; mad still lets a backend fuse or round the product. +MIX32 = 'float mix32(float a, float b, float c) { precise float result = mad(a, b, c); return result; }' # 16-bit VALU: (sources, source kind, float or uint expression of the sources, result kind). 'h' sources are # binary16 read from the low half and computed in binary32; an 'h' result is rounded back to binary16. The # i16/u16 conversions to binary16 read the low half as an integer; the conversions to integers truncate toward # zero, saturate to the 16-bit range and read NaN as 0. VEC_H = { 'v_add_f16': (2, 'h', '{0} + {1}', 'h'), 'v_sub_f16': (2, 'h', '{0} - {1}', 'h'), - 'v_subrev_f16': (2, 'h', '{1} - {0}', 'h'), 'v_mul_f16': (2, 'h', '{0} * {1}', 'h'), + 'v_subrev_f16': (2, 'h', '{1} - {0}', 'h'), 'v_mul_f16': (2, 'h', 'mul16({0}, {1})', 'h'), 'v_min_f16': (2, 'h', 'min({0}, {1})', 'h'), 'v_max_f16': (2, 'h', 'max({0}, {1})', 'h'), 'v_fmac_f16': (2, 'h', 'fma16o({0}, {1}, {2})', 'h'), 'v_fmamk_f16': (3, 'h', 'fma16o({0}, {1}, {2})', 'h'), 'v_fmaak_f16': (3, 'h', 'fma16o({0}, {1}, {2})', 'h'), @@ -6492,7 +11331,7 @@ def declarations(self): # operands are uints; the result is a uint expression VEC_U = { 'v_add_nc_u32': (2, '{0} + {1}'), 'v_sub_nc_u32': (2, '{0} - {1}'), 'v_subrev_nc_u32': (2, '{1} - {0}'), - 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_mul_hi_u32': (2, 'mul_hi_u32({0}, {1})'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), + 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_mul_hi_u32': (2, 'mul_hi_u32({0}, {1})'), 'v_mul_hi_i32': (2, 'mul_hi_i32({0}, {1})'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), 'v_not_b32': (1, '~{0}'), 'v_lshlrev_b32': (2, '{1} << ({0} & 31)'), 'v_lshrrev_b32': (2, '{1} >> ({0} & 31)'), 'v_ashrrev_i32': (2, 'uint(int({1}) >> ({0} & 31))'), 'v_min_u32': (2, 'min({0}, {1})'), 'v_max_u32': (2, 'max({0}, {1})'), 'v_min_i32': (2, 'uint(min(int({0}), int({1})))'), 'v_max_i32': (2, 'uint(max(int({0}), int({1})))'), @@ -6506,10 +11345,14 @@ def declarations(self): 'v_cvt_f16_f32': (1, 'f32tof16(F({0}))'), 'v_bfe_u32': (3, '({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)'), 'v_mad_u32_u24': (3, '({0} & 0xffffffu) * ({1} & 0xffffffu) + {2}'), 'v_mad_i32_i24': (3, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8) + {2}'), + 'v_mad_u32_u16': (3, '({0} & 0xffffu) * ({1} & 0xffffu) + {2}'), + 'v_mad_i32_i16': (3, 'asuint(asint({0} << 16) >> 16) * asuint(asint({1} << 16) >> 16) + {2}'), 'v_lshl_add_u32': (3, '({0} << ({1} & 31)) + {2}'), 'v_add_lshl_u32': (3, '({0} + {1}) << ({2} & 31)'), 'v_add3_u32': (3, '{0} + {1} + {2}'), 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), 'v_mul_u32_u24': (2, '({0} & 0xffffffu) * ({1} & 0xffffffu)'), + # v_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0] (same field rule as s_bfm_b32). + 'v_bfm_b32': (2, '(((1u << ({0} & 31)) - 1) << ({1} & 31))'), 'v_mul_i32_i24': (2, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8)'), # Per-lane bit operations (AMD RDNA 2 ISA reference). The bitscan results count from the most significant # bit for the "h" forms and read 0xffffffff when no bit qualifies; firstbitlow(0) is already 0xffffffff. @@ -6521,14 +11364,25 @@ def declarations(self): 'v_ffbh_u32': (1, '({0} == 0u ? 0xffffffffu : 31u - firstbithigh({0}))'), 'v_ffbh_i32': (1, '({0} == 0u || {0} == 0xffffffffu ? 0xffffffffu : 31u - firstbithigh(asint({0}) < 0 ? ~{0} : {0}))'), 'v_bfrev_b32': (1, 'reversebits({0})'), + # Unsigned sums of absolute differences (AMD RDNA 2 ISA reference, VOP3 opcodes 0x15a to 0x15d and 0x171), all + # modulo 2^32. src1 is the reference: v_msad_u8 leaves out each byte lane whose src1 byte is zero, as in + # tools/pixel_aot.py. + 'v_lerp_u8': (3, 'lerp_u8({0}, {1}, {2})'), + 'v_perm_b32': (3, 'perm_b32({0}, {1}, {2})'), 'v_sad_u8': (3, 'sad_u8({0}, {1}, {2})'), + 'v_sad_hi_u8': (3, 'sad_hi_u8({0}, {1}, {2})'), 'v_sad_u16': (3, 'sad_u16({0}, {1}, {2})'), 'v_sad_u32': (3, 'sad_u32({0}, {1}, {2})'), + 'v_msad_u8': (3, 'msad_u8({0}, {1}, {2})'), # Saturating 32-to-16-bit integer packs (AMD RDNA 2 ISA reference, VOP3A opcodes 0x36a and 0x36b; saturation # bounds per Mesa NIR pack_uvec2_to_uint / pack_ivec2_to_uint selected in ACO): src0 -> low 16 bits, src1 -> high 16 bits. 'v_cvt_pk_u16_u32': (2, 'min({0}, 0xffffu) | (min({1}, 0xffffu) << 16u)'), 'v_cvt_pk_i16_i32': (2, '(asuint(clamp(asint({0}), -32768, 32767)) & 0xffffu) | ' '(asuint(clamp(asint({1}), -32768, 32767)) << 16u)'), + # Saturate two signed 16-bit lanes in S0 to unsigned 8-bit lanes packed in D[15:0]; D[31:16] = 0 + # (AMD RDNA 2 ISA, VOP1 0x62 / VOP3A 0x1e2). + 'v_sat_pk_u8_i16': (1, '(asuint(clamp(asint(({0} & 0xffffu) << 16u) >> 16, 0, 255)) & 0xffu) | ' + '((asuint(clamp(asint({0}) >> 16, 0, 255)) & 0xffu) << 8u)'), } @@ -6575,6 +11429,22 @@ def low(n): SCC_UNMODELLED = frozenset(('s_add_i32', 's_add_u32', 's_sub_i32', 's_sub_u32', 's_min_i32', 's_min_u32', 's_max_i32', 's_max_u32')) + +def add_sub_min_max_scc(base, a, b, result): + """The SCC expression of s_add/s_sub/s_min/s_max_{i,u}32 over the source texts a and b and the result text. + s_add_u32: carry out; s_sub_u32: borrow (S0 < S1); s_add_i32 / s_sub_i32: signed overflow (the sign of the result + differs from the sign the operands imply); s_min / s_max: SCC = (D == S0), the first source was chosen.""" + if base == 's_add_u32': + return '(%s) < (%s)' % (result, a) + if base == 's_sub_u32': + return '(%s) < (%s)' % (a, b) + if base == 's_add_i32': + return '(((((%s) ^ (%s)) & ((%s) ^ (%s))) >> 31) != 0)' % (a, result, b, result) + if base == 's_sub_i32': + return '(((((%s) ^ (%s)) & ((%s) ^ (%s))) >> 31) != 0)' % (a, b, a, result) + cast = 'int' if base.endswith('_i32') else '' + return '(%s(%s) %s %s(%s))' % (cast, a, '<=' if base.startswith('s_min') else '>=', cast, b) + PACK_B16 = frozenset(('s_pack_ll_b32_b16', 's_pack_lh_b32_b16', 's_pack_hh_b32_b16')) SCA = { 's_mov_b32': ('{0}', None), 's_mov_b64': ('{0}', None), 's_movk_i32': ('{0}', None), @@ -6591,8 +11461,9 @@ def low(n): 's_min_i32': ('uint(min(int({0}), int({1})))', None), 's_max_i32': ('uint(max(int({0}), int({1})))', None), 's_bfe_u32': ('({0} >> ({1} & 31)) & ((({1} >> 16) & 127) >= 32 ? 0xffffffffu : ((1u << (({1} >> 16) & 31)) - 1))', '$ != 0'), 's_brev_b32': ('reversebits({0})', None), - # s_mul_hi_u32: high 32 bits of the unsigned 64-bit product; SCC unchanged. + # s_mul_hi_{u,i}32: high 32 bits of the unsigned/signed 64-bit product; SCC unchanged. 's_mul_hi_u32': ('mul_hi_u32({0}, {1})', None), + 's_mul_hi_i32': ('mul_hi_i32({0}, {1})', None), # s_sext_i32_iN: sign-extend the low N bits of S0; SCC unchanged. 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), @@ -6636,6 +11507,76 @@ def handler(self, ops, mods): self.set_scc((cast % op).format(self.u(ops[0]), '0x%08xu' % sopk_imm(ops[1], signed))) return handler setattr(Stage, 'op_s_cmpk_%s_%s' % (_name, _typ), _make_cmpk()) +# s_cmp_eq_u64 / s_cmp_lg_u64: SCC = (S0.u64 == S1.u64) / (S0.u64 != S1.u64). +for _name, _op, _join in (('eq', '==', '&&'), ('lg', '!=', '||')): + def _make_cmp64(op=_op, join=_join, name='s_cmp_%s_u64' % _name): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('%s requires two unmodified operands' % name) + if any(self.is_lane_mask(tok) for tok in ops): + raise Unsupported('%s on a lane mask' % name) + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + words = [] + for tok in ops: + r = reg_range(tok) + if r: + if r[0] != 's': + raise Unsupported('%s source %s' % (name, tok)) + if any(w in masks or w in mask_high for w in range(r[1], r[2] + 1)): + raise Unsupported('%s on a lane mask' % name) + words.append(('0u', '0u') if tok == 'null' else self.i64_words(tok, False, True)) + (a0, a1), (b0, b1) = words + self.set_scc('((%s %s %s) %s (%s %s %s))' % (a0, op, b0, join, a1, op, b1)) + return handler + setattr(Stage, 'op_s_cmp_%s_u64' % _name, _make_cmp64()) +# Scalar bit counts and scans with a 32-bit result. `lo`/`hi` are the uint words of the source: a 32-bit source has only +# `lo`. The scans return 0xffffffff (-1) when no bit qualifies. Only the counts set SCC (result != 0). +def _clz64(lo, hi): + return ('(%(h)s != 0u ? 31u - firstbithigh(%(h)s) : (%(l)s != 0u ? 63u - firstbithigh(%(l)s) : 0xffffffffu))' + % {'l': lo, 'h': hi}) + + +def _ctz64(lo, hi): + return ('(%(l)s != 0u ? firstbitlow(%(l)s) : (%(h)s != 0u ? 32u + firstbitlow(%(h)s) : 0xffffffffu))' + % {'l': lo, 'h': hi}) + + +def _flbit_i64(lo, hi): + # first bit that differs from the sign bit: complement a negative value, then count leading zeros + neg = '((%s & 0x80000000u) != 0u)' % hi + return _clz64('(%s ? ~%s : %s)' % (neg, lo, lo), '(%s ? ~%s : %s)' % (neg, hi, hi)) + + +# name -> (source is a register pair, expression over (lo, hi), SCC rule or None) +SCALAR_BITS = { + 's_bcnt0_i32_b32': (False, lambda lo, hi: '(32u - countbits(%s))' % lo, '$ != 0'), + 's_bcnt1_i32_b32': (False, lambda lo, hi: 'countbits(%s)' % lo, '$ != 0'), + 's_bcnt0_i32_b64': (True, lambda lo, hi: '(64u - countbits(%s) - countbits(%s))' % (lo, hi), '$ != 0'), + 's_bcnt1_i32_b64': (True, lambda lo, hi: '(countbits(%s) + countbits(%s))' % (lo, hi), '$ != 0'), + 's_ff0_i32_b64': (True, lambda lo, hi: _ctz64('(~%s)' % lo, '(~%s)' % hi), None), + # s_ff1_i32_b64 stays on Stage.op_s_ff1_i32_b64 (immediates + SGPR pairs) so SCALAR_BITS + # does not overwrite the zero-extended immediate fold from #2022 Item F. + 's_flbit_i32_b64': (True, _clz64, None), + 's_flbit_i32_i64': (True, _flbit_i64, None), +} +for _name, (_pair, _expr, _scc) in SCALAR_BITS.items(): + def _make_scalar_bits(name=_name, pair=_pair, expr=_expr, scc=_scc): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('%s requires two unmodified operands' % name) + dst, src = reg_range(ops[0]), reg_range(ops[1]) + if dst is None or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('%s destination %s' % (name, ops[0])) + if src is None or src[0] != 's' or src[2] > 105 or src[2] - src[1] != (1 if pair else 0): + raise Unsupported('%s source %s' % (name, ops[1])) + if any(r in self.masks for r in range(src[1], src[2] + 1)): + raise Unsupported('%s on a lane mask' % name) + lo, hi = self.S(src[1]), self.S(src[2]) + self.masks.discard(dst[1]) + self.set_s(dst[1], expr(lo, hi), scc=scc) + return handler + setattr(Stage, 'op_' + _name, _make_scalar_bits()) # s_bitcmp1_b32 / s_bitcmp0_b32: SCC = S0[S1[4:0]] == 1 / == 0. for _bit in (0, 1): def _make_bitcmp(bit=_bit): @@ -6647,6 +11588,32 @@ def handler(self, ops, mods): self.set_scc('((%s >> (%s & 31)) & 1u) == %du' % (self.u(ops[0]), self.u(ops[1]), bit)) return handler setattr(Stage, 'op_s_bitcmp%d_b32' % _bit, _make_bitcmp()) +# s_bitcmp1_b64 / s_bitcmp0_b64: SCC = S0.u64[S1.u[5:0]] == 1 / == 0. +for _bit in (0, 1): + def _make_bitcmp64(bit=_bit, name='s_bitcmp%d_b64' % _bit): + def handler(self, ops, mods): + if len(ops) != 2 or mods: + raise Unsupported('%s requires two unmodified operands' % name) + if any(self.is_lane_mask(tok) for tok in ops): + raise Unsupported('%s on a lane mask' % name) + r0, r1 = reg_range(ops[0]), reg_range(ops[1]) + masks = getattr(self, 'masks', ()) + mask_high = getattr(self, 'mask_high', ()) + if r0: + if r0[0] != 's': + raise Unsupported('%s source %s' % (name, ops[0])) + if any(w in masks or w in mask_high for w in range(r0[1], r0[2] + 1)): + raise Unsupported('%s on a lane mask' % name) + if (r1 and (r1[0] != 's' or r1[1] != r1[2] or r1[1] > 105)) or ops[1] in FLOATS: + raise Unsupported('%s bit index %s' % (name, ops[1])) + if r1 and r1[1] in mask_high: + raise Unsupported('%s on a lane mask' % name) + low, high = ('0u', '0u') if ops[0] == 'null' else self.i64_words(ops[0], False, True) + idx = self.u(ops[1]) + word = '((%s & 32u) != 0u ? %s : %s)' % (idx, high, low) + self.set_scc('((%s >> (%s & 31u)) & 1u) == %du' % (word, idx, bit)) + return handler + setattr(Stage, 'op_s_bitcmp%d_b64' % _bit, _make_bitcmp64()) def scalar_wide_fold(helper, x, amount, signed): @@ -6725,18 +11692,242 @@ def read(fmt, data, offset): VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) +BVH_HELPERS = ( + 'static const uint X2W_BVH_MISS = 0xffffffffu;', + # The 128-bit BVH T# (RDNA 2 ISA Table 49): base in 256-byte units at 39:0, + # box growing 62:55, sort enable 63, + # size 105:64 and type 8 at 127:124. This slice binds a ByteAddressBuffer at the base and + # keeps the descriptor in a 32-bit address window, so the size-high ten bits and every + # reserved field must be zero. A zero base selects the absolute pointer form, which this + # slice does not bind, so it is refused here as a miss rather than read at address zero. + 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word1 & 0x7fffff00u) == 0u &&', + ' (word3 & 0xfeffffffu) == 0x80000000u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + # A triangle node is 64 bytes: five float3 vertices at 0..59 and one ID dword at 60. + # The kind selects one of four 8-bit maps: two bits for i, two for j, and a base vertex + # triple from RADV's radv_bvh_triangle_node (Mesa 25.1.0 bvh/bvh.h, MIT). + 'float x2w_bvh_component(float3 value, uint axis) {', + ' return axis == 0u ? value.x : (axis == 1u ? value.y : value.z);', + '}', + 'uint x2w_bvh_triangle_index(uint kind, uint slot) {', + ' if (slot == 0u) return kind == 0u ? 0u : (kind == 1u ? 1u : 2u);', + ' if (slot == 1u) return kind == 0u ? 1u : (kind == 1u ? 3u : (kind == 2u ? 3u : 4u));', + ' if (slot == 2u) return kind == 0u ? 2u : (kind == 1u ? 2u : (kind == 2u ? 4u : 0u));', + ' return 0u;', + '}', + 'float3 x2w_bvh_triangle_vertex(ByteAddressBuffer nodes, uint offset, uint kind, uint slot) {', + ' uint at = offset + 12u * x2w_bvh_triangle_index(kind, slot);', + ' return float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + '}', + 'float3 x2w_bvh_shear(float3 vertex, float3 origin, float sx, float sy, float sz,', + ' uint kx, uint ky, uint kz) {', + ' float3 rel = vertex - origin;', + ' float rx = x2w_bvh_component(rel, kx);', + ' float ry = x2w_bvh_component(rel, ky);', + ' float rz = x2w_bvh_component(rel, kz);', + ' return float3(rx - sx * rz, ry - sy * rz, sz * rz);', + '}', + # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. A box + # node ignores bit 120 because one T# covers both node types; its helper checks every + # other word-3 bit. + 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', + ' (word3 >> 28u) == 8u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + 'uint4 x2w_bvh_intersect_triangle(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float3 origin, float3 direction,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(0x7f800000u, 0x3f800000u, 0u, 0u);', + ' uint kind = node & 7u;', + ' if (kind > 3u || !x2w_bvh_triangle_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) > word2) return miss;', + ' uint id = nodes.Load(offset + 60u);', + ' uint id_byte = (id >> (8u * kind)) & 0xffu;', + ' uint i = id_byte & 3u;', + ' uint j = (id_byte >> 2u) & 3u;', + ' uint first = (3u - i - j) & 3u;', + ' float3 a = x2w_bvh_triangle_vertex(nodes, offset, kind, first);', + ' float3 b = x2w_bvh_triangle_vertex(nodes, offset, kind, i);', + ' float3 c = x2w_bvh_triangle_vertex(nodes, offset, kind, j);', + ' float3 ad = abs(direction);', + ' uint kz;', + ' if (ad.x >= ad.y) kz = ad.x >= ad.z ? 0u : 2u;', + ' else kz = ad.y >= ad.z ? 1u : 2u;', + ' uint kx = (kz + 1u) % 3u;', + ' uint ky = (kx + 1u) % 3u;', + ' if (x2w_bvh_component(direction, kz) < 0.0) {', + ' uint swap = kx; kx = ky; ky = swap;', + ' }', + ' float sz = x2w_bvh_component(inv_dir, kz);', + ' float sx = x2w_bvh_component(direction, kx) * sz;', + ' float sy = x2w_bvh_component(direction, ky) * sz;', + ' float3 sa = x2w_bvh_shear(a, origin, sx, sy, sz, kx, ky, kz);', + ' float3 sb = x2w_bvh_shear(b, origin, sx, sy, sz, kx, ky, kz);', + ' float3 sc = x2w_bvh_shear(c, origin, sx, sy, sz, kx, ky, kz);', + ' float u = sc.x * sb.y - sc.y * sb.x;', + ' float v = sa.x * sc.y - sa.y * sc.x;', + ' float w = sb.x * sa.y - sb.y * sa.x;', + ' bool behind = u < 0.0 || v < 0.0 || w < 0.0;', + ' bool before = u > 0.0 || v > 0.0 || w > 0.0;', + ' float det = u + (v + w);', + ' float t = (u * sa.z + v * sb.z) + w * sc.z;', + ' bool ahead = (det > 0.0 && t >= 0.0) || (det < 0.0 && t <= 0.0);', + ' if ((behind && before) || !ahead) return miss;', + ' return uint4(asuint(t), asuint(det), asuint(v), asuint(w));', + '}', + # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at + # bytes 0..15, coords[4][2][3] at 16..111 (lo then hi per child) and reserved at 112..127. + 'float x2w_bvh_box32_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 24u * index;', + ' float3 lo = float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + ' float3 hi = float3(asfloat(nodes.Load(at + 12u)), asfloat(nodes.Load(at + 16u)),', + ' asfloat(nodes.Load(at + 20u)));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + # A NaN in min.x marks an inactive box (Vulkan inactive primitive rule; Mesa tests NaN != NaN). + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : asfloat(0x7f800000u);', + '}', + # One binary16 box from a radv_bvh_box16_node: children[4] at 0..15, coords[4][2][3] at + # 16..63, six binary16 values per child. The half values widen exactly to binary32. + 'float x2w_bvh_box16_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 12u * index;', + ' uint h0 = nodes.Load(at), h1 = nodes.Load(at + 4u), h2 = nodes.Load(at + 8u);', + ' float3 lo = float3(f16tof32(h0), f16tof32(h0 >> 16u), f16tof32(h1));', + ' float3 hi = float3(f16tof32(h1 >> 16u), f16tof32(h2), f16tof32(h2 >> 16u));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : asfloat(0x7f800000u);', + '}', + # The five compare-exchange stages of Mesa radv_nir_rt_common.c: a strict comparison + # sorts misses (key +inf) to the end without swapping equal keys within each pair. + 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', + ' if (kb < ka) { uint ti = ia; ia = ib; ib = ti; float tk = ka; ka = kb; kb = tk; }', + '}', + 'uint4 x2w_bvh_intersect_box32(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 5u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + # Mesa clamps the inverse direction so a zero direction component cannot turn 0 * inf + # into NaN. The box test then follows the software reference exactly. + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box32_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box32_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box32_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box32_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + # A disabled child stores 0xffffffff and must not enter the hit list even if its box is valid. + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + # With sorting disabled, each result remains in its original child slot. + ' if (!sort_boxes) return uint4(c0, c1, c2, c3);', + ' float k0 = h0 ? d0 : asfloat(0x7f800000u);', + ' float k1 = h1 ? d1 : asfloat(0x7f800000u);', + ' float k2 = h2 ? d2 : asfloat(0x7f800000u);', + ' float k3 = h3 ? d3 : asfloat(0x7f800000u);', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', + 'uint4 x2w_bvh_intersect_box16(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 4u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) > word2) return miss;', + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box16_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box16_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box16_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box16_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + # With sorting disabled, each result remains in its original child slot. + ' if (!sort_boxes) return uint4(c0, c1, c2, c3);', + ' float k0 = h0 ? d0 : asfloat(0x7f800000u);', + ' float k1 = h1 ? d1 : asfloat(0x7f800000u);', + ' float k2 = h2 ? d2 : asfloat(0x7f800000u);', + ' float k3 = h3 ? d3 : asfloat(0x7f800000u);', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', +) + + class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False + uses_bvh = False + uses_cube_dir = False uses_gather_2d_lod = False uses_store_d16_x = False + uses_dot2 = () uses_sad = () + uses_dot8 = () + uses_lerp_u8 = False + uses_perm_b32 = False + uses_add_sub_sat_i32 = () + uses_dot4 = () + uses_bitreplicate = False uses_store_format_xyzw = False srv_formats = () uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store - def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, - refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): + def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, + ps_attr_map=None, srv_formats=()): self.root = parse_root(root_blob) self.ps_attr_map = ps_attr_map # stream_interface(): pixel attribute -> (vertex parameter, component mask); None pairs by number self.vs_fetch = vs_fetch # stream_fetch(): the loads the vertex stage's entry call stands for @@ -6745,10 +11936,17 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( # one is enabled). Without hardware inputs the model assumes the center pair alone: v0, v1. self.persp_center_vgpr = 0 if ps_hw_inputs is not None: + # SPI_PS_INPUT_ADDR allocates the entry VGPRs in bit order; SPI_PS_INPUT_ENA chooses which of the + # allocated inputs are loaded. Every enabled input is also allocated (LLVM AMDGPUAsmPrinter + # getSIProgramInfo: "all enabled inputs are tagged in InputAddr as well"; SIISelLowering + # processPSInputArgs marks an input allocated, then enabled only when it is used). ena, addr = ps_hw_inputs - if ena != addr or not 0 <= ena <= 0xffff: + if not (0 <= ena <= 0xffff and 0 <= addr <= 0xffff): raise Unsupported('unverified pixel input enable/address combination') - self.persp_center_vgpr = (2 if addr & 1 else 0) if addr & 2 else None + if ena & ~addr: + raise Unsupported('contradictory pixel input enable/address masks: an enabled input is not allocated') + # Layout from the address mask; an input allocated but not enabled holds no loaded value. + self.persp_center_vgpr = (2 if addr & 1 else 0) if ena & 2 else None if ena & (1 << 15): # SPI PS inputs 0..6 supply IJ pairs (the pull model supplies three); # line stipple through sample coverage each occupy one VGPR. @@ -6758,10 +11956,20 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.srv_formats = dict(srv_formats) if isinstance(srv_formats, dict) else dict(enumerate(srv_formats)) self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.resheap_count = 0 self.uses_pack16_rne = False + self.uses_bvh = False + self.uses_cube_dir = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_dot2 = set() self.uses_sad = set() + self.uses_dot8 = set() + self.uses_lerp_u8 = False + self.uses_perm_b32 = False + self.uses_add_sub_sat_i32 = set() + self.uses_dot4 = set() + self.uses_bitreplicate = False self.uses_store_format_xyzw = False self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index @@ -6769,6 +11977,11 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.notes = set() # shortcuts taken (written to the manifest as comments) self.lod_unvalidated = set() # image_sample forms read through a heap sampler (LOD fields unchecked, #2221) self.modified, self.other_modified = set(), set() # other: unproved descriptor writes + + def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, + refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): + self._init_pixel_context(root_blob, sampler_heap, rtv_formats, ps_hw_inputs, vs_fetch, + ps_attr_map, srv_formats) self.rect = self.ud(('rect',)) if refusals is None: self.vs = Stage(self, self.vertex_kind, vs_code) @@ -6823,6 +12036,13 @@ def ud(self, source): return self.uds.index(source) def resource(self, key, kind): + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane'): + if kind != 'buf': + raise Unsupported('per-lane resource heap descriptor used as %s' % kind) + _tag, _sub, expr, bound = key[0] + if self.resheap_count <= bound: + self.resheap_count = bound + 1 + return 'rh[NonUniformResourceIndex(%s)]' % expr if key in self.stored_images(): raise Unsupported('resource %s is both read and stored to' % (key,)) r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) @@ -6834,6 +12054,8 @@ def stored_images(self): return self.uavs or {} def uav(self, key, kind): + if isinstance(key[0], tuple) and key[0][:2] == ('resheap', 'per_lane'): + raise Unsupported('store through %s' % (key[0],)) if key in self.resources: raise Unsupported('resource %s is both read and stored to' % (key,)) if self.uavs is None: @@ -6862,7 +12084,7 @@ def sampler_lines(self): def common(self): import pixel_aot - out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', + out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', FLOAT_MINMAX, 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', # Match pixel_aot: round the product before adding and flush denormals to signed zero. 'float ftz32(float value) {', @@ -6887,23 +12109,70 @@ def common(self): ' float f = frac(value);', ' return asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f;', '}', + # v_ldexp_f32: exact binary32 scaling by 2^delta, preserving +/-0, +/-Inf and NaN (same as pixel_aot). + 'float ldexp32(float value, int delta) {', + ' uint bits = asuint(value);', + ' uint sign = bits & 0x80000000u;', + ' uint exp = (bits >> 23) & 0xffu;', + ' uint mant = bits & 0x7fffffu;', + ' if (exp == 0xffu || (exp == 0u && mant == 0u)) return value;', + ' int e = (int)exp;', + ' if (exp == 0u) {', + ' uint shift = 23u - firstbithigh(mant);', + ' mant = (mant << shift) & 0x7fffffu;', + ' e = 1 - (int)shift;', + ' }', + ' e += clamp(delta, -512, 512);', + ' if (e >= 255) return asfloat(sign | 0x7f800000u);', + ' if (e <= 0) {', + ' if (e < -23) return asfloat(sign);', + ' uint full = mant | 0x800000u;', + ' uint shift = (uint)(1 - e);', + ' uint half_bit = 1u << (shift - 1u);', + ' uint mask = (1u << shift) - 1u;', + ' uint rem = full & mask;', + ' uint q = full >> shift;', + ' if (rem > half_bit || (rem == half_bit && (q & 1u) != 0u)) q++;', + ' return asfloat(sign | q);', + ' }', + ' return asfloat(sign | ((uint)e << 23) | mant);', + '}', # v_med3_f32 with a NaN source is the minimum of the three (ISA "343 V_MED3_F32"), so the test is # on the encoding: a float isnan() may be folded away by the compiler. D3D min() returns the - # other operand, so min(min(a, b), c) over a NaN source is the smallest of the non-NaN ones. + # other operand, so the min3 chain over a NaN source is the smallest of the non-NaN ones. min, max + # and med3 go through minmax_zero32, which orders -0 below +0 and passes a NaN to D3D min/max. # Same body as med3_32 in tools/pixel_aot.py. 'float med3_32(float a, float b, float c) {', ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);', - ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));', + ' return top > 0x7f800000u', + ' ? minmax_zero32(minmax_zero32(a, b, false), c, false)', + ' : minmax_zero32(minmax_zero32(a, b, false), minmax_zero32(minmax_zero32(a, b, true), c, false), true);', + '}', + 'uint minmax16_bits(uint a, uint b, bool maximum) {', + ' bool a_nan = (a & 0x7fffu) > 0x7c00u;', + ' bool b_nan = (b & 0x7fffu) > 0x7c00u;', + # Two NaNs produce a canonical quiet NaN. This payload choice is not hardware-proven. + ' if (a_nan) return b_nan ? 0x7e00u : b;', + ' if (b_nan) return a;', + # Reverse negative encodings and put positives above them, ordering -0 below +0. + ' uint a_key = a ^ ((a & 0x8000u) != 0u ? 0xffffu : 0x8000u);', + ' uint b_key = b ^ ((b & 0x8000u) != 0u ? 0xffffu : 0x8000u);', + ' return (maximum ? a_key > b_key : a_key < b_key) ? a : b;', '}', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' ' return (a >> 16) * (b >> 16) + (middle >> 16) + (((middle & 0xffffu) + la * (b >> 16)) >> 16); }', + 'uint mul_hi_i32(uint a, uint b) { return mul_hi_u32(a, b) - ((a >> 31) != 0u ? b : 0u)' + ' - ((b >> 31) != 0u ? a : 0u); }', # a * b + c for binary16 inputs with one rounding (#2073). The first form recovered the binary32 sum error # with a floating-point TwoSum; an NVIDIA driver (RTX 3070 Ti, 32.0.16.2101) simplified that error term to # zero despite `precise`, so ties rounded the wrong way. fma16_rne works on the encodings in 32-bit integer # arithmetic, so no driver floating-point rewrite can reach it. Infinities and NaNs keep float semantics. pixel_aot.SALU_HELPERS['fma16_rne'], + # A binary16 product is exact in binary32. Keep its sign when the result is zero (#2746). + 'float mul16(float a, float b) { precise float product = a * b; return product; }', + MIX32, 'float fma16o(float a, float b, float c) {', ' if (!isfinite(a) || !isfinite(b) || !isfinite(c)) return a * b + c;', ' return f16tof32(fma16_rne(f32tof16(a), f32tof16(b), f32tof16(c)));', @@ -6941,6 +12210,19 @@ def common(self): 'uint2 shr64i(uint lo, uint hi, uint sh) { sh &= 63u; uint sb = sh & 31u, sc = (32u - sb) & 31u;' ' uint cy = sb == 0u ? 0u : (hi << sc); uint h = asuint(asint(hi) >> sb);' ' return uint2(sh < 32u ? ((lo >> sb) | cy) : h, sh < 32u ? h : asuint(asint(hi) >> 31u)); }', + # v_mad_u64_u32 / v_mad_i64_i32: a * b + (chi:clo) from 16-bit partial products, so no 64-bit type. + # z is the carry of the 64-bit add (the unsigned form's lane-mask carry-out). + 'uint mulhi32(uint a, uint b) {' + ' uint a0 = a & 0xffffu, a1 = a >> 16, b0 = b & 0xffffu, b1 = b >> 16;' + ' uint p00 = a0 * b0, p01 = a0 * b1, p10 = a1 * b0, p11 = a1 * b1;' + ' uint mid = (p00 >> 16) + (p01 & 0xffffu) + (p10 & 0xffffu);' + ' return p11 + (p01 >> 16) + (p10 >> 16) + (mid >> 16); }', + 'uint3 mad64u(uint a, uint b, uint clo, uint chi) {' + ' uint ph = mulhi32(a, b), pl = a * b, lo = pl + clo, c0 = lo < pl ? 1u : 0u, hs = ph + chi, hi = hs + c0;' + ' return uint3(lo, hi, (hs < ph || hi < hs) ? 1u : 0u); }', + 'uint3 mad64i(uint a, uint b, uint clo, uint chi) {' + ' uint ph = mulhi32(a, b) - (asint(a) < 0 ? b : 0u) - (asint(b) < 0 ? a : 0u), pl = a * b, lo = pl + clo;' + ' return uint3(lo, ph + chi + (lo < pl ? 1u : 0u), 0u); }', 'uint2 bfe64(uint lo, uint hi, uint s1, uint sg) { uint w = min((s1 >> 16u) & 127u, 64u - (s1 & 63u)); uint2 e = shr64u(lo, hi, s1);' ' e = uint2(e.x & (w >= 32u ? 0xffffffffu : ((1u << (w & 31u)) - 1u)),' ' e.y & (w >= 64u ? 0xffffffffu : (w > 32u ? ((1u << ((w - 32u) & 31u)) - 1u) : 0u)));' @@ -6952,16 +12234,41 @@ def common(self): 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] + if self.uses_bvh: + out.extend(BVH_HELPERS) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D<float4>', 'tex2d': 'Texture2D<float4>', 'tex2da': 'Texture2DArray<float4>', 'tex3d': 'Texture3D<float4>'}[r['kind']], r['index'], r['index'])) + out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D<float4>', 'tex2d': 'Texture2D<float4>', 'tex2da': 'Texture2DArray<float4>', 'tex3d': 'Texture3D<float4>', 'texcube': 'TextureCube<float4>'}[r['kind']], r['index'], r['index'])) + if getattr(self, 'resheap_count', 0): + out.append('ByteAddressBuffer rh[%d] : register(t0, space%d);' % (self.resheap_count, RESHEAP_RANGE_SPACE)) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): - out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D<float4>', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) + out.append('%s %s%d : register(u%d);' % ({'tex1d': 'RWTexture1D<float4>', 'tex2d': 'RWTexture2D<float4>', 'tex2da': 'RWTexture2DArray<float4>', 'tex3d': 'RWTexture3D<float4>', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) if self.uses_sampler_heap: out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' % (16 * SAMPLER_HEAP_FALLBACK, SAMPLER_HEAP_FALLBACK)) + if self.uses_cube_dir: + # A direction for TextureCube from a gfx10 cube address (#2943): s and t are the face coordinates + # sc/|ma| + 1.5 and tc/|ma| + 1.5 and f the face id, with the per-face sc and tc of v_cubesc and + # v_cubetc (cube() above). A major component of +-1 reproduces u = sc/|major| and v = tc/|major|. + # A cube-array id (8 * layer + face) keeps only its face, so layer 0 is sampled; faces 6 and 7, a + # negative or NaN id become faces 5 and 0. Coordinates outside [1, 2] are assumed to clamp to face edges + # (untested outside [1, 2]). + out.extend(( + 'float3 x2w_cube_dir(float s, float t, float f) {', + ' float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);', + ' float v = clamp(2.0 * (t - 1.5), -1.0, 1.0);', + ' int k = (f >= 0.0 && f < 2147483648.0) ? ((int)f & 7) : 0;', + ' k = min(k, 5);', + ' if (k == 0) return float3(1.0, -v, -u);', + ' if (k == 1) return float3(-1.0, -v, u);', + ' if (k == 2) return float3(u, 1.0, v);', + ' if (k == 3) return float3(u, -1.0, -v);', + ' if (k == 4) return float3(u, -v, 1.0);', + ' return float3(-u, -v, -1.0);', + '}', + )) if self.uses_pack16_rne: # IEEE binary32 to binary16 round-to-nearest-even (quieting NaN while preserving its sign, # matching RDNA 2 hardware on binary32 inputs), plus exact UNORM16 ratio-to-half conversion @@ -7098,6 +12405,81 @@ def common(self): ' }', '}', )) + if 'v_dot2_u32_u16' in self.uses_dot2: + # RDNA 2 ISA V_DOT2_U32_U16: two unsigned 16-bit products + S2, exact uint32 clamp. + out.append( + 'uint dot2_u32_u16(uint a, uint b, uint c, bool sat) {' + ' uint p0 = (a & 0xffffu) * (b & 0xffffu);' + ' uint p1 = (a >> 16u) * (b >> 16u);' + ' uint r0 = c + p0; uint carry = (r0 < c) ? 1u : 0u;' + ' uint r1 = r0 + p1; carry += (r1 < r0) ? 1u : 0u;' + ' return (sat && carry != 0u) ? 0xffffffffu : r1; }') + if 'v_dot2_i32_i16' in self.uses_dot2: + # RDNA 2 ISA V_DOT2_I32_I16: two signed 16-bit products + int(S2), exact int32 clamp via 64-bit acc. + out.append( + 'uint dot2_i32_i16(uint a, uint b, uint c, bool sat) {' + ' int p0 = (asint((a & 0xffffu) << 16u) >> 16) * (asint((b & 0xffffu) << 16u) >> 16);' + ' int p1 = (asint(a) >> 16) * (asint(b) >> 16);' + ' uint lo = c; int hi = (asint(c) < 0) ? -1 : 0;' + ' uint t0 = lo + asuint(p0); hi += ((p0 < 0) ? -1 : 0) + ((t0 < lo) ? 1 : 0); lo = t0;' + ' uint t1 = lo + asuint(p1); hi += ((p1 < 0) ? -1 : 0) + ((t1 < lo) ? 1 : 0); lo = t1;' + ' if (sat) {' + ' if (hi > 0 || (hi == 0 && (lo & 0x80000000u) != 0u)) return 0x7fffffffu;' + ' if (hi < -1 || (hi == -1 && (lo & 0x80000000u) == 0u)) return 0x80000000u; }' + ' return lo; }') + if 'v_dot4_u32_u8' in self.uses_dot4: + # RDNA 2 ISA V_DOT4_U32_U8: sum of 4 unsigned byte products + S2, optional uint32 clamp. + out.append( + 'uint dot4_u32_u8(uint a, uint b, uint c, bool sat) {' + ' uint s = (a & 0xffu) * (b & 0xffu)' + ' + ((a >> 8u) & 0xffu) * ((b >> 8u) & 0xffu)' + ' + ((a >> 16u) & 0xffu) * ((b >> 16u) & 0xffu)' + ' + ((a >> 24u) & 0xffu) * ((b >> 24u) & 0xffu);' + ' uint r = c + s;' + ' return (sat && r < c) ? 0xffffffffu : r; }') + if 'v_dot4_i32_i8' in self.uses_dot4: + # RDNA 2 ISA V_DOT4_I32_I8: sum of 4 signed byte products + int(S2), optional int32 clamp. + out.append( + 'uint dot4_i32_i8(uint a, uint b, uint c, bool sat) {' + ' int s = (asint((a & 0xffu) << 24u) >> 24) * (asint((b & 0xffu) << 24u) >> 24)' + ' + (asint(((a >> 8u) & 0xffu) << 24u) >> 24) * (asint(((b >> 8u) & 0xffu) << 24u) >> 24)' + ' + (asint(((a >> 16u) & 0xffu) << 24u) >> 24) * (asint(((b >> 16u) & 0xffu) << 24u) >> 24)' + ' + (asint(((a >> 24u) & 0xffu) << 24u) >> 24) * (asint(((b >> 24u) & 0xffu) << 24u) >> 24);' + ' uint r = c + asuint(s);' + ' if (sat && asint(c) > 0 && s > 0 && asint(r) < 0) return 0x7fffffffu;' + ' if (sat && asint(c) < 0 && s < 0 && asint(r) >= 0) return 0x80000000u;' + ' return r; }') + if self.uses_bitreplicate: + # RDNA 2 ISA S_BITREPLICATE_B64_B32: replicate each of the low 16 bits twice into 32 bits. + out.append( + 'uint bitreplicate16(uint x) {' + ' x &= 0xffffu;' + ' x = (x | (x << 8u)) & 0x00ff00ffu;' + ' x = (x | (x << 4u)) & 0x0f0f0f0fu;' + ' x = (x | (x << 2u)) & 0x33333333u;' + ' x = (x | (x << 1u)) & 0x55555555u;' + ' return x | (x << 1u); }') + if self.uses_lerp_u8: + # RDNA 2 ISA V_LERP_U8: for each byte lane i, D_i = (S0_i + S1_i + (S2_i & 1)) >> 1. + out.append( + 'uint lerp_u8(uint a, uint b, uint c) {' + ' return (((a & 0xffu) + (b & 0xffu) + (c & 1u)) >> 1)' + ' | (((((a >> 8) & 0xffu) + ((b >> 8) & 0xffu) + ((c >> 8) & 1u)) >> 1) << 8)' + ' | (((((a >> 16) & 0xffu) + ((b >> 16) & 0xffu) + ((c >> 16) & 1u)) >> 1) << 16)' + ' | (((((a >> 24) & 0xffu) + ((b >> 24) & 0xffu) + ((c >> 24) & 1u)) >> 1) << 24); }') + if self.uses_perm_b32: + # RDNA 2 ISA V_PERM_B32: {S0, S1} bytes 0..7, selectors 8..11 sign-extend bytes 1/3/5/7, 12 -> 0x00, >=13 -> 0xff. + out.append( + 'uint perm_byte(uint hi, uint lo, uint sel) {' + ' return sel >= 13u ? 0xffu : sel == 12u ? 0u' + ' : sel >= 8u ? ((((sel >= 10u ? hi : lo) >> ((sel & 1u) != 0u ? 31u : 15u)) & 1u) != 0u ? 0xffu : 0u)' + ' : (((sel >= 4u ? hi : lo) >> ((sel & 3u) * 8u)) & 0xffu); }') + out.append( + 'uint perm_b32(uint hi, uint lo, uint sel) {' + ' return perm_byte(hi, lo, sel & 0xffu)' + ' | (perm_byte(hi, lo, (sel >> 8) & 0xffu) << 8)' + ' | (perm_byte(hi, lo, (sel >> 16) & 0xffu) << 16)' + ' | (perm_byte(hi, lo, (sel >> 24) & 0xffu) << 24); }') if 'v_sad_u8' in self.uses_sad: out.append( 'uint sad_u8(uint a, uint b, uint c) {' @@ -7105,6 +12487,16 @@ def common(self): ' + uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu)))' ' + uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu)))' ' + uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu))) + c; }') + if 'v_add_nc_i32' in self.uses_add_sub_sat_i32: + out.append( + 'uint add_sat_i32(uint a, uint b) {' + ' uint s = a + b;' + ' return ((~(a ^ b)) & (a ^ s) & 0x80000000u) != 0u ? (0x7fffffffu + (a >> 31)) : s; }') + if 'v_sub_nc_i32' in self.uses_add_sub_sat_i32: + out.append( + 'uint sub_sat_i32(uint a, uint b) {' + ' uint d = a - b;' + ' return ((a ^ b) & (a ^ d) & 0x80000000u) != 0u ? (0x7fffffffu + (a >> 31)) : d; }') if 'v_sad_u16' in self.uses_sad: out.append( 'uint sad_u16(uint a, uint b, uint c) {' @@ -7114,6 +12506,46 @@ def common(self): out.append( 'uint sad_u32(uint a, uint b, uint c) {' ' return (a > b ? a - b : b - a) + c; }') + # v_sad_hi_u8 and v_msad_u8 share the four-lane absolute-difference sum of sad_u8, so it is factored into + # sad4_u8, whose `masked` argument leaves out each byte lane whose src1 byte is zero (v_msad_u8's reference + # rule). The table formulas match tools/pixel_aot.py exactly: sad_hi_u8 is (sad4_u8(a, b, false) << 16) + c + # and msad_u8 is sad4_u8(a, b, true) + c, both modulo 2^32. sad_u8 above keeps its inlined four-term form so + # a translation that uses only v_sad_u8 is unchanged. + if 'v_sad_hi_u8' in self.uses_sad or 'v_msad_u8' in self.uses_sad: + out.append( + 'uint sad4_u8(uint a, uint b, bool masked) {' + ' return (masked && ((b & 0xffu) == 0u) ? 0u : uint(abs(int(a & 0xffu) - int(b & 0xffu))))' + ' + (masked && (((b >> 8) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu))))' + ' + (masked && (((b >> 16) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu))))' + ' + (masked && (((b >> 24) & 0xffu) == 0u) ? 0u : uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu)))); }') + if 'v_sad_hi_u8' in self.uses_sad: + out.append( + 'uint sad_hi_u8(uint a, uint b, uint c) { return (sad4_u8(a, b, false) << 16u) + c; }') + if 'v_msad_u8' in self.uses_sad: + out.append( + 'uint msad_u8(uint a, uint b, uint c) { return sad4_u8(a, b, true) + c; }') + if 'v_dot8_u32_u4' in self.uses_dot8: + # RDNA 2 ISA V_DOT8_U32_U4: sum of 8 unsigned nibble products + S2, optional uint32 clamp. + out.append( + 'uint dot8_u32_u4(uint a, uint b, uint c, bool sat) {' + ' uint s = 0u;' + ' [unroll] for (uint k = 0u; k < 8u; ++k)' + ' s += ((a >> (k * 4u)) & 0xfu) * ((b >> (k * 4u)) & 0xfu);' + ' uint r = c + s;' + ' return (sat && r < c) ? 0xffffffffu : r; }') + if 'v_dot8_i32_i4' in self.uses_dot8: + # RDNA 2 ISA V_DOT8_I32_I4: sum of 8 signed nibble products + int(S2), optional int32 clamp. + out.append( + 'uint dot8_i32_i4(uint a, uint b, uint c, bool sat) {' + ' int s = 0;' + ' [unroll] for (uint k = 0u; k < 8u; ++k) {' + ' int x = asint(((a >> (k * 4u)) & 0xfu) << 28u) >> 28;' + ' int y = asint(((b >> (k * 4u)) & 0xfu) << 28u) >> 28;' + ' s += x * y; }' + ' uint r = c + asuint(s);' + ' if (sat && asint(c) > 0 && s > 0 && asint(r) < 0) return 0x7fffffffu;' + ' if (sat && asint(c) < 0 && s < 0 && asint(r) >= 0) return 0x80000000u;' + ' return r; }') if self.uses_store_format_xyzw: legacy = [' %sif (field == %du) fmt = %du;' % ('' if i == 0 else 'else ', field, code) for i, (field, code) in enumerate(sorted(STORE_FORMAT_XYZW_LEGACY_FORMATS.items()))] @@ -7238,7 +12670,8 @@ def hlsl_ps(self): s = self.ps targets = sorted(int(k[3:]) for k in s.exports if k.startswith('mrt')) depth = 'depth' in s.exports - out = self.common() + ['struct PSIn {'] + self.interface(True) + ['};'] + quad = QUAD_ANY_HLSL if getattr(s, 'uses_quad_vote', False) else [] + out = self.common() + quad + ['struct PSIn {'] + self.interface(True) + ['};'] if not targets and not depth: out += ['void main(PSIn i) {'] + s.declarations() + s.body() + ['}'] return '\n'.join(out) + '\n' @@ -7259,8 +12692,12 @@ def manifest(self): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): source, off = key - where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), 'vbtab': 'vb %d' % ((off or 0) // 16), - 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + else: + where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), + 'vbtab': 'vb %d' % ((off or 0) // 16), + 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) if where is None: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) @@ -7272,6 +12709,8 @@ def manifest(self): raise Unsupported('stored image through %s' % (source,)) lines.append('uav %d %s table %d %d' % (r['index'], r['kind'], source[1] if len(source) > 1 else 0, off or 0)) lines += self.sampler_lines() + if self.resheap_count: + lines.append('resheap %d %d' % (self.resheap_count, RESHEAP_RANGE_SPACE)) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) @@ -7292,26 +12731,43 @@ class ComputePipeline(Pipeline): size are pipeline register state the caller supplies; COMPUTE_PGM_RSRC2 is decoded as compute_store_aot does (#1608). Root parameters from s4 are an inference (see Stage.setup_entry).""" + stage_type = Stage + def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals=None, decoded=None): from compute_store_aot import checked_group, entry_registers try: - self.entry = entry_registers(rsrc2) # (user SGPRs, {axis: group-ID SGPR}, thread-ID VGPRs) + tg_size_en = (isinstance(rsrc2, int) and not isinstance(rsrc2, bool) + and 0 <= rsrc2 < (1 << 32) and bool((rsrc2 >> 10) & 1)) + self.entry = entry_registers(rsrc2 & ~(1 << 10) if tg_size_en else rsrc2) self.group = checked_group(group) except ValueError as reason: raise Unsupported(str(reason)) from None + if tg_size_en and self.group[0] * self.group[1] * self.group[2] > 32: + raise Unsupported('COMPUTE_PGM_RSRC2 TG_SIZE_EN requires at most 32 threads per group') + user, groups, _ = self.entry + self.tg_size_sgpr = (user + len(groups)) if tg_size_en else None self.root = parse_root(root_blob) self.vs_fetch, self.packed_position_vgpr, self.rtv_formats = None, None, () self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False + self.resheap_count = 0 self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_dot2 = set() + self.uses_bvh = False self.uses_sad = set() + self.uses_dot8 = set() + self.uses_lerp_u8 = False + self.uses_perm_b32 = False + self.uses_add_sub_sat_i32 = set() + self.uses_dot4 = set() + self.uses_bitreplicate = False self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: unproved descriptor writes self.lod_unvalidated = set() # LLVM AMDGPUUsage, COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE on gfx10: 128 dwords per unit. self.lds_words = ((rsrc2 >> 15) & 0x1ff) * 128 - self.cs = Stage(self, 'cs', cs_code, refusals=refusals, decoded=decoded) + self.cs = self.stage_type(self, 'cs', cs_code, refusals=refusals, decoded=decoded) def resource(self, key, kind): if key in self.uavs: @@ -7348,25 +12804,80 @@ def manifest(self): lines = ['x2w-manifest 2', 'stage cs', 'group %d %d %d' % self.group, 'ud %d' % len(self.uds)] lines += ['udsrc %d %s' % (i, ' '.join(str(x) for x in source)) for i, source in enumerate(self.uds)] for (source, off), r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - if source[0] == 'table': + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + elif source[0] == 'table': where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] + elif source[0] == 'resheap' and len(source) == 3 and r['kind'] == 'buf': + where = 'heap rootconst %d %d' % source[1:] # the 32-byte heap record that root constant word indexes + elif source[0] == 'resheap' and source[1] == 'word' and r['kind'] == 'buf': + # The record the word at byte `at` (+ root constant word * `times`) of table buffer <param> <byte> indexes. + table, byte, param, word, scale, at = source[2:] + where = 'heap word table %d %d at %d' % (table, byte, at) + ( + '' if param is None else ' rootconst %d %d times %d' % (param, word, scale)) else: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) for (source, off), r in self.uavs.items(): + if source[0] != 'table': + raise Unsupported('store through %s' % (source,)) where = 'table %d %d' % (source[1], off) if r['kind'] == 'raw': lines.append('uav %d %s' % (r['index'], where)) else: - lines.append('uav %d tex2d float %s channels 4' % (r['index'], where)) + lines.append('uav %d %s float %s channels 4' % (r['index'], r['kind'], where)) lines += self.sampler_lines() + if self.resheap_count: + lines.append('resheap %d %d' % (self.resheap_count, RESHEAP_RANGE_SPACE)) if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) return '\n'.join(lines) + '\n' +class MeshPixelStage(Pipeline): + """Pixel stage paired with a mesh shader exporting param0..param12 (#2413 T4).""" + + def __init__(self, mesh_params, ps_code, root_blob, *, rtv_formats=(), ps_hw_inputs=None, ps_attr_map=None, + sampler_heap=None, srv_formats=(), refusals=None, decoded=None): + from mesh_param_link import MAX_PARAM, validate_linkage + self._init_pixel_context(root_blob, sampler_heap, rtv_formats, ps_hw_inputs, None, + ps_attr_map, srv_formats) + clean_params = [] + for p in mesh_params: + if type(p) is not int or not 0 <= p <= MAX_PARAM: + raise Unsupported('mesh parameter %r outside 0..%d' % (p, MAX_PARAM)) + clean_params.append(p) + self.params = sorted(set(clean_params)) + self.mesh_plain_params = frozenset(self.params) + self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded) + self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) + for a, how in self.ps.attrs.items(): + if 'f16' not in how: + continue + if how != {'f16'} or a not in self.params: + raise Unsupported('attribute %d is read as binary16 by the pixel stage but not only so, or not ' + 'exported as a plain 32-bit parameter by the mesh stage' % a) + self.f16_plain = sorted(a for a in self.ps.f16_plain if a in self.params) + missing = sorted(a for a in self.ps.attrs if a not in self.params) + if missing: + raise Unsupported('pixel stage reads attributes %s the mesh stage does not export' % missing) + try: + validate_linkage(self.params, pixel_attrs=sorted(self.ps.attrs), flat=self.flat, + f16_plain=self.f16_plain, semantic='param') + except ValueError as error: + raise Unsupported(str(error)) from None + + def common(self): + return [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] + + def linkage(self, *, distance_vectors=0): + from mesh_param_link import validate_linkage + return validate_linkage(self.params, pixel_attrs=sorted(self.ps.attrs), flat=self.flat, + f16_plain=self.f16_plain, distance_vectors=distance_vectors, semantic='param') + + class MeshPipeline(Pipeline): """A slot 57 mesh pipeline with an optional pixel stage. The mesh stage is self.vs.""" vertex_kind = 'ms' @@ -7396,10 +12907,16 @@ def fnv(data, h=1469598103934665603): return h -def pipeline_key(vs_code, ps_code, root_blob, layout=b''): - """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) - return fnv(layout, key) if layout else key +def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): + """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout. + + A pipeline with a stream description (req_<key>.psin) also hashes its pixel input masks: b'psin1' and then + SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root + signature and input layout but different masks are then two requests with their own results. Without a + description the key is unchanged.""" + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-29')))) + key = fnv(layout, key) if layout else key + return key if ps_inputs is None else fnv(b'psin1' + struct.pack('<II', *ps_inputs), key) def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): @@ -7407,7 +12924,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-17cs') + key = fnv(b'x2w-startup-shader-29cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack('<Q', len(part)), key)) return key @@ -7426,7 +12943,7 @@ def compute_entry(state_a): return words[6], (words[3] & 0xffff, words[3] >> 16, words[4] & 0xffff) -def load_compute_request(out_dir, key, refusals=None): +def load_compute_request(out_dir, key, refusals=None, *, pipeline_type=ComputePipeline): """The ComputePipeline of a slot 67 request, after checking the files against .desc and the key.""" name = os.path.join(out_dir, 'req_%016x' % key) try: @@ -7448,7 +12965,7 @@ def load_compute_request(out_dir, key, refusals=None): if S_ENDPGM not in struct.unpack('<%dI' % (len(code) // 4), code): raise Unsupported('compute code without s_endpgm') rsrc2, group = compute_entry(parts['.sa']) - return ComputePipeline(code, parts['.root'], rsrc2, group, refusals=refusals) + return pipeline_type(code, parts['.root'], rsrc2, group, refusals=refusals) def compute_refusals(out_dir, key): @@ -7589,14 +13106,15 @@ def has_complete_mesh57_bytecode(path): def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_formats=(), rtv_request='', vs_fetch=None, - ps_attr_map=None): + ps_attr_map=None, ps_hw_inputs=None): """Writes <key>.vs.hlsl, <key>.ps.hlsl and <key>.txt (last), or <key>.fail with the reason. With check, the pair is compiled to .vs.cso and .ps.cso first and a missing fxc is a failure. check=False, or X2W_FXC set to the empty string, publishes the manifest without bytecode.""" name = os.path.join(out_dir, '%016x' % key) try: - pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map) + pipe = Pipeline(vs_code, ps_code, root_blob, rtv_formats=rtv_formats, vs_fetch=vs_fetch, ps_attr_map=ps_attr_map, + ps_hw_inputs=ps_hw_inputs) vs, ps, manifest = pipe.hlsl_vs(), pipe.hlsl_ps(), pipe.manifest() if rtv_request: manifest += rtv_request + '\n' @@ -7685,27 +13203,21 @@ def classify_stage(blob): decoded[kind] = ins return kind - name = os.path.join(out_dir, 'req_%016x' % key) - request = '' - formats = () - base = key - if os.path.isfile(name + '.rtv'): - with open(name + '.rtv', encoding='ascii') as file: - request = file.read(256) - if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: - raise Unsupported('invalid RTV variant request') - base, *formats = map(int, request.split()[1:]) - if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): - raise Unsupported('invalid RTV variant values') - name = os.path.join(out_dir, 'req_%016x' % base) + request, base, formats, description = request_source(out_dir, key) + name = os.path.join(out_dir, 'req_%016x' % base) a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) if pair_info is not None and not request: import hashlib pair_info.append((hashlib.sha256(struct.pack('<Q', len(a)) + a + b).digest(), root)) # A stream with an input layout publishes it as .ia (before .a) and hashes it into the key. layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' - if (request or validate_base_key) and pipeline_key(a, b, root, layout) != base: - raise Unsupported('RTV variant source key mismatch' if request else 'shader request source key mismatch') + if request or validate_base_key: + # The masks of a stream description are part of the key (pipeline_key). + masks = read_ps_inputs(description, base) + if pipeline_key(a, b, root, layout, masks) != base: + raise Unsupported('RTV variant source key mismatch' if request else + 'pixel input description names another pipeline' if masks is not None else + 'shader request source key mismatch') fetch = attr_map = None if a.startswith(b'DXBC') or b.startswith(b'DXBC'): # Slot 86 records complete containers in canonical (VS, PS) order. @@ -7730,13 +13242,132 @@ def classify_stage(blob): return kinds, root, formats, request, fetch, decoded, attr_map +def request_source(out_dir, key): + """The source of a graphics request: (rtv1 line or '', source key, RTV formats, stream description path). + + A base request is its own source. An RTV variant (req_<key>.rtv) names its source pipeline and is translated + from that pipeline's blobs and stream description, req_<source>.psin. This is the one place that names the + description a request depends on: the translation reads its masks from that path, and pending_keys checks + the same path to withdraw a published result or retry a failure after the description changes or, for a + result recorded as translated with it (dependency_record), is removed. The path is returned whether or not the + file exists. An invalid variant line is refused by name.""" + name = os.path.join(out_dir, 'req_%016x' % key) + request = '' + formats = () + base = key + if os.path.isfile(name + '.rtv'): + with open(name + '.rtv', encoding='ascii') as file: + request = file.read(256) + if not re.fullmatch(r'rtv1 [0-9]{1,20}(?: [0-9]{1,10}){1,8}', request) or fnv(request.encode('ascii')) != key: + raise Unsupported('invalid RTV variant request') + base, *formats = map(int, request.split()[1:]) + if base > 0xffffffffffffffff or any(fmt > 0xffffffff for fmt in formats): + raise Unsupported('invalid RTV variant values') + return request, base, formats, os.path.join(out_dir, 'req_%016x.psin' % base) + + +def request_ps_inputs(out_dir, key): + """The pixel input masks (SPI_PS_INPUT_ENA, SPI_PS_INPUT_ADDR) of one graphics request, or None. + + They come from the stream description request_source() names: req_<key>.psin, the separately captured + description of exactly that pipeline (see read_ps_inputs), or for an RTV variant its source pipeline's. The + masks are part of the request's identity: the key must equal pipeline_key() of the stage blobs, root + signature, input layout and these masks, so a description copied from another pipeline, left stale after a + stage change or rewritten with another mask pair is refused, never applied. No file means no captured + description: the translation keeps its model without hardware inputs.""" + _, base, _, description = request_source(out_dir, key) + masks = read_ps_inputs(description, base) + if masks is None: + return None + name = os.path.join(out_dir, 'req_%016x' % base) + a, b, root = (open(name + ext, 'rb').read() for ext in ('.a', '.b', '.root')) + layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' + if pipeline_key(a, b, root, layout, masks) != base: + raise Unsupported('pixel input description names another pipeline') + return masks + + +def dependency_record(out_dir, key): + """<key>.psdep: written when a graphics request is translated with a stream description, before its manifest. + + It marks a result as known to depend on the description request_source() names, so pending_keys can withdraw + that result when the description is removed. A legacy request that never had a description has no record, and + its inputs are not read again. The record holds the description line the result was translated with.""" + return os.path.join(out_dir, '%016x.psdep' % key) + + +def record_dependency(out_dir, key, base, masks): + path = dependency_record(out_dir, key) + line = 'psin1 %016x ena=0x%04x addr=0x%04x\n' % (base, *masks) + with suppress(FileNotFoundError, UnicodeError), open(path) as existing: + if existing.read() == line: + return + temporary = '%s.%d.tmp' % (path, os.getpid()) + try: + with open(temporary, 'w') as record: + record.write(line) + os.replace(temporary, path) + finally: + with suppress(FileNotFoundError): + os.remove(temporary) + + +def read_ps_inputs(path, key): + """The (enable, address) masks in the stream description at `path` (req_<key>.psin), one ASCII line + 'psin1 <key> ena=<mask> addr=<mask>' (the key as 16 hex digits, the masks as 0x-prefixed 16-bit values), or + None without the file. The line must name `key`; a malformed line or a missing mask is refused by name.""" + if not os.path.isfile(path): + return None + with open(path, 'rb') as file: + line = file.read(128) + fields = line.decode('ascii', 'replace').split() + if not re.fullmatch(rb'psin1 [0-9a-f]{16}(?: (?:ena|addr)=0x[0-9a-f]{1,4}){0,2}\n?', line): + raise Unsupported('invalid pixel input description') + masks = dict(field.split('=') for field in fields[2:]) + if len(masks) != len(fields) - 2: + raise Unsupported('invalid pixel input description') + if int(fields[1], 16) != key: + raise Unsupported('pixel input description names another pipeline') + for field, label in (('ena', 'enable'), ('addr', 'address')): + if field not in masks: + raise Unsupported('pixel input %s mask missing from the stream description' % label) + return int(masks['ena'], 16), int(masks['addr'], 16) + + def mesh57_key(ms, ps, root): - value = fnv(b'x2w-startup-mesh-57-2') + value = fnv(b'x2w-startup-mesh-57-3') for part in (ms, ps, root): value = fnv(part, fnv(struct.pack('<Q', len(part)), value)) return value +def kill_exit_block(pixel): + """True when the only null export of a decoded pixel stage is the early exit of a kill. + + LLVM SILateBranchLowering and Mesa ACO place that exit after the program's s_endpgm: the block is + `exp null off, off, off, off done vm` then the final s_endpgm, and every branch into it enters with EXEC zero, + so the export writes nothing. The stage's other lanes end at the earlier s_endpgm. An entry is s_cbranch_execz, + or the demote form: s_cbranch_scc0 directly after `s_cselect exec, exec, 0` (s_cselect leaves SCC, so the taken + branch follows the select of 0) with no branch landing on the s_cbranch_scc0 itself.""" + at = [i for i, (_, _, op, a) in enumerate(pixel) if op == 'exp' and a.split()[1] == 'null'] + if len(at) != 1 or at[0] != len(pixel) - 2 or pixel[at[0] - 1][2] != 's_endpgm': + return False + if pixel[at[0]][3] != 'exp null off, off, off, off done vm': + return False + label = 'label_0x%x' % pixel[at[0]][0] + end = 'label_0x%x' % pixel[-1][0] + targets = {a.split()[-1] for _, _, op, a in pixel if op.startswith('s_cbranch') or op == 's_branch'} + entries = [i for i, (_, _, _, a) in enumerate(pixel) if a.split()[-1:] in ([label], [end])] + + def zero_exec(i): + if pixel[i][2] == 's_cbranch_execz': + return True + return (pixel[i][2] == 's_cbranch_scc0' and i > 0 + and pixel[i - 1][3] in ('s_cselect_b64 exec, exec, 0', 's_cselect_b32 exec_lo, exec_lo, 0') + and 'label_0x%x' % pixel[i][0] not in targets) + return bool(entries) and all(zero_exec(i) for i in entries) + + def translate_mesh57(out_dir, key): """Translate a fixed-descriptor mesh request of the accepted shape (mesh_skeleton), or raise Unsupported. @@ -7756,11 +13387,14 @@ def translate_mesh57(out_dir, key): if ps: pixel = decode(strip_header(ps)) # A pixel shader with no colour output ends in a null-target export (LLVM SILateBranchLowering, Mesa ACO create_fs_null_export): depth-only. - null_only = {a.split()[1] for _, _, op, a in pixel if op == 'exp'} == {'null'} + targets = {a.split()[1] for _, _, op, a in pixel if op == 'exp'} + null_only = targets == {'null'} if not pixel or pixel[-1][2] != 's_endpgm' or classify_decoded(pixel) != 'ps' and not null_only: raise Unsupported('slot 57 pixel stage has an incompatible export or termination') - if null_only: - raise Unsupported('slot 57 mesh with a depth-only pixel stage is not covered') + # The slot 57 depth-only profile is the null export alone; the general pixel path keeps its mixed forms. + # A colour stage may also hold the null export as the early exit of a kill (kill_exit_block). + if 'null' in targets and not null_only and not kill_exit_block(pixel): + raise Unsupported('slot 57 pixel stage mixes the null export with another export') pipe = MeshPipeline(ms, ps or None, root) sources = [('ms', 'ms_6_5', pipe.hlsl_ms())] if ps: @@ -7806,15 +13440,32 @@ def translate_request(out_dir, key): open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason try: - kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) + try: + _, base, _, description = request_source(out_dir, key) + if os.path.isfile(dependency_record(out_dir, key)) and not os.path.isfile(description): + raise Unsupported('pixel input description missing for a request translated with one') + kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) + ps_inputs = request_ps_inputs(out_dir, key) + if ps_inputs is not None: + record_dependency(out_dir, key, base, ps_inputs) # before the manifest is published + except Unsupported: + # A result published earlier was translated from sources or masks this request no longer confirms. + with suppress(FileNotFoundError): + os.remove(os.path.join(out_dir, '%016x.txt' % key)) + raise except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason if set(kinds) != {'vs', 'ps'}: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write('stages %s\n' % sorted(kinds)) return 'stages %s' % sorted(kinds) - return translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, vs_fetch=fetch, - ps_attr_map=attr_map) + result = translate_to(out_dir, key, kinds['vs'], kinds['ps'], root, rtv_formats=formats, rtv_request=request, + vs_fetch=fetch, ps_attr_map=attr_map, ps_hw_inputs=ps_inputs) + if ps_inputs is not None and result == 'ok': + # An unchanged manifest is not rewritten; mark it as checked against this description (pending_keys). + with suppress(FileNotFoundError): + os.utime(os.path.join(out_dir, '%016x.txt' % key)) + return result REFUSALS_CAVEAT = ('Counts after the first refusal are approximate. Skipped instructions leave later state ' @@ -7825,7 +13476,16 @@ def translate_request(out_dir, key): def request_keys(out_dir, compute=False): """Graphics request keys (ready marker .a or .rtv), or with compute, slot 67 compute keys (.c67).""" pattern = r'req_([0-9a-f]{16})\.c67' if compute else r'req_([0-9a-f]{16})\.(?:a|rtv)' - for name in sorted(os.listdir(out_dir)): + names = [] + try: + for entry in os.scandir(out_dir): + # Fast filename pre-filter before regex matching. + if entry.name.startswith('req_') and entry.is_file(): + names.append(entry.name) + except OSError: + # Directory does not exist or cannot be scanned; yields no requests. + return + for name in sorted(names): match = re.fullmatch(pattern, name) if match: yield int(match.group(1), 16) @@ -7865,7 +13525,8 @@ def request_refusals(out_dir, key, pair_info=None): """Collect reached refusal sites for one request without publishing a translation.""" refusals = [] try: - kinds, root, formats, _, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + kinds, root, formats, request, fetch, decoded, attr_map = load_request(out_dir, key, refusals, pair_info) + ps_inputs = request_ps_inputs(out_dir, key) except Unsupported as reason: refusals.append((str(reason), 'pipeline')) return refusals @@ -7885,7 +13546,7 @@ def request_refusals(out_dir, key, pair_info=None): if set(kinds) != {'vs', 'ps'}: raise Unsupported('stages %s' % sorted(kinds)) pipe = Pipeline(kinds['vs'], kinds['ps'], root, rtv_formats=formats, vs_fetch=fetch, - refusals=refusals, decoded=decoded, ps_attr_map=attr_map) + refusals=refusals, decoded=decoded, ps_attr_map=attr_map, ps_hw_inputs=ps_inputs) op = 'hlsl_vs' pipe.hlsl_vs() op = 'hlsl_ps' @@ -8030,27 +13691,59 @@ def main(): for ext, blob in (('.a', a), ('.b', b), ('.root', root)): open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb').write(blob) print('pso %x -> request %016x' % (w & 0xffffff, key)) + skip_failed = any(arg in ('--skip-failed', '-s') for arg in sys.argv[1:]) or os.environ.get('X2W_SKIP_FAILED') in ('1', 'true', 'True') + jobs = None + args = sys.argv[1:] + i = 0 + while i < len(args): + arg = args[i] + if arg.startswith('--jobs='): + with suppress(ValueError): + jobs = int(arg.split('=', 1)[1]) + elif arg in ('-j', '--jobs') and i + 1 < len(args): + i += 1 + with suppress(ValueError): + jobs = int(args[i]) + i += 1 + if sys.argv[1] == '--watch': # --watch <dir> [seconds]: translate requests as a running title writes them, until stopped - interval = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0 - # The first pass retries earlier failures once (the runtime never rewrites a request, so a - # translator fix would otherwise not reach them); later passes skip failures already written. - skip_failed = False + interval = 2.0 + args3 = sys.argv[3:] + i = 0 + while i < len(args3): + arg = args3[i] + if arg in ('-j', '--jobs'): + i += 2 + continue + if arg.startswith('-'): + i += 1 + continue + with suppress(ValueError): + interval = float(arg) + break + i += 1 + # The first pass retries earlier failures once unless --skip-failed / X2W_SKIP_FAILED is set; + # later passes skip failures already written. + completed = {} while True: - if watch_pass(out_dir, skip_failed): + if watch_pass(out_dir, skip_failed, jobs=jobs, completed=completed): skip_failed = True time.sleep(interval) - translate_pending(out_dir) + translate_pending(out_dir, skip_failed=skip_failed, jobs=jobs) -def watch_pass(out_dir, skip_failed): +def watch_pass(out_dir, skip_failed, jobs=None, completed=None): """One --watch pass. A worker killed from outside (out of memory) breaks the pool; the pass is - reported and its requests are retried on the next pass instead of ending the watcher.""" + reported and its requests are retried on the next pass instead of ending the watcher. + + The completed dict is threaded across watch iterations to avoid re-reading published stage bytecode. + """ from concurrent.futures.process import BrokenProcessPool try: - translate_pending(out_dir, skip_failed=skip_failed) + translate_pending(out_dir, skip_failed=skip_failed, jobs=jobs, completed=completed) return True except BrokenProcessPool as error: print('translation pass interrupted, retrying: %s' % error, file=sys.stderr, flush=True) @@ -8095,23 +13788,31 @@ def translate_one(out_dir, key): return reason -def translation_jobs(): - try: - jobs = int(os.environ.get('X2W_TRANSLATE_JOBS') or 0) - except ValueError: - jobs = 0 +def translation_jobs(jobs=None): + if jobs is None: + try: + jobs = int(os.environ.get('X2W_TRANSLATE_JOBS') or 0) + except ValueError: + jobs = 0 + else: + try: + jobs = int(jobs) + except (ValueError, TypeError): + jobs = 0 jobs = jobs if jobs > 0 else os.cpu_count() or 1 return min(jobs, 61) if os.name == 'nt' else jobs # ProcessPoolExecutor refuses more than 61 on Windows -def translate_pending(out_dir, skip_failed=False, jobs=None): +def translate_pending(out_dir, skip_failed=False, jobs=None, completed=None): """Translate every request that has no result yet. The runtime writes the ready markers last. Requests are independent (each writes only its own <key>.* files), so several run in parallel - processes; X2W_TRANSLATE_JOBS (default: the processor count, at most 61 on Windows) sets how many. + processes; X2W_TRANSLATE_JOBS or --jobs (default: the processor count, at most 61 on Windows) sets how many. """ - keys = pending_keys(out_dir, skip_failed) - jobs = min(jobs or translation_jobs(), len(keys)) + keys = pending_keys(out_dir, skip_failed, completed=completed) + if not keys: + return + jobs = min(translation_jobs(jobs), len(keys)) if jobs < 2: for key in keys: print('%016x: %s' % (key, translate_one(out_dir, key)), flush=True) @@ -8123,31 +13824,140 @@ def translate_pending(out_dir, skip_failed=False, jobs=None): print('%016x: %s' % (key, result), flush=True) -def pending_keys(out_dir, skip_failed): +def pending_keys(out_dir, skip_failed, completed=None): keys = [] manifest_only = os.environ.get('X2W_FXC') == '' - for name in sorted(os.listdir(out_dir)): - m = re.fullmatch(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57)', name) - if not m: + try: + entries = list(os.scandir(out_dir)) + except OSError: + return keys + + files = {} + req_items = [] + for entry in entries: + try: + if entry.is_file(): + files[entry.name] = entry + if entry.name.startswith('req_'): + m = re.fullmatch(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57)', entry.name) + if m: + req_items.append((entry.name, entry, m)) + except OSError: continue + + req_items.sort(key=lambda item: item[0]) + + for name, entry, m in req_items: key = int(m.group(1), 16) - result = os.path.join(out_dir, '%016x' % key) - mesh = m.group(2) == 'm57' - stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') - ready_bytecode = has_complete_mesh57_bytecode if mesh else has_bytecode - manifest = result + ('.ms57.txt' if mesh else '.txt') - # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if os.path.isfile(manifest): - if manifest_only or all(ready_bytecode(result + s) for s in stages): - continue - if mesh and has_complete_mesh57_bytecode(result + '.ms57.cso'): - with suppress(OSError), open(manifest, 'rb') as published: - if b'ps none' in published.read().splitlines(): + ext = m.group(2) + base_name = '%016x' % key + mesh = ext == 'm57' + stages = ('.cs.cso',) if ext == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') + manifest_name = base_name + ('.ms57.txt' if mesh else '.txt') + + if completed is not None and key in completed: + saved = completed[key] + saved_req_mtime, saved_base, saved_psin_mtime = saved[:3] + saved_stage_meta = saved[3] if len(saved) > 3 else None + try: + current_req_mtime = entry.stat().st_mtime + except OSError: + current_req_mtime = None + if current_req_mtime == saved_req_mtime and manifest_name in files: + psin_name = 'req_%016x.psin' % saved_base + psin_entry = files.get(psin_name) + try: + current_psin_mtime = psin_entry.stat().st_mtime if psin_entry else None + except OSError: + current_psin_mtime = None + lost = current_psin_mtime is None and ((base_name + '.psdep') in files) + if current_psin_mtime == saved_psin_mtime and not lost: + if manifest_only: continue - fail = os.path.join(out_dir, '%016x.fail' % key) - # A repeated pass retries a failure only once its request is rewritten. - if skip_failed and os.path.exists(fail) and os.path.getmtime(fail) >= os.path.getmtime(os.path.join(out_dir, name)): - continue + if saved_stage_meta is not None: + def stage_valid(s_name, s_size, s_mtime): + se = files.get(s_name) + if se is None: + return False + try: + st = se.stat() + return st.st_size == s_size and st.st_mtime == s_mtime + except OSError: + return False + if saved_stage_meta and all(stage_valid(sn, sz, mt) for sn, sz, mt in saved_stage_meta): + continue + + described = None + lost = False + base = key + if ext in ('a', 'rtv'): + if ext == 'rtv': + with suppress(Unsupported, OSError, UnicodeError): + _, base, _, _ = request_source(out_dir, key) + psin_name = 'req_%016x.psin' % base + psin_entry = files.get(psin_name) + if psin_entry is not None: + with suppress(OSError): + described = psin_entry.stat().st_mtime + lost = described is None and ((base_name + '.psdep') in files) + + manifest_entry = files.get(manifest_name) + manifest_mtime = None + if manifest_entry is not None: + with suppress(OSError): + manifest_mtime = manifest_entry.stat().st_mtime + + if manifest_entry is not None and not lost and not ( + described is not None and manifest_mtime is not None and described > manifest_mtime): + ready = False + published_stages = [] + if manifest_only: + ready = True + published_stages = [manifest_name] + elif mesh: + if all((base_name + s) in files and has_complete_mesh57_bytecode(os.path.join(out_dir, base_name + s)) for s in stages): + ready = True + published_stages = [manifest_name] + [base_name + s for s in stages] + elif (base_name + '.ms57.cso') in files and has_complete_mesh57_bytecode(os.path.join(out_dir, base_name + '.ms57.cso')): + with suppress(OSError), open(os.path.join(out_dir, manifest_name), 'rb') as published: + if b'ps none' in published.read().splitlines(): + ready = True + published_stages = [manifest_name, base_name + '.ms57.cso'] + else: + def stage_ok(s): + se = files.get(base_name + s) + if se is None: + return False + try: + return se.stat().st_size > 0 + except OSError: + return False + if all(stage_ok(s) for s in stages): + ready = True + published_stages = [manifest_name] + [base_name + s for s in stages] + + if ready: + if completed is not None: + with suppress(OSError): + stage_meta = tuple((name, files[name].stat().st_size, files[name].stat().st_mtime) + for name in published_stages if name in files) + completed[key] = (entry.stat().st_mtime, base, described, stage_meta) + continue + + if completed is not None: + completed.pop(key, None) + + fail_name = base_name + '.fail' + fail_entry = files.get(fail_name) + recheck = lost and (manifest_entry is not None) + if skip_failed and not recheck and fail_entry is not None: + try: + fail_mtime = fail_entry.stat().st_mtime + req_mtime = entry.stat().st_mtime + if fail_mtime >= max(req_mtime, described or 0): + continue + except OSError: + pass keys.append(key) return keys diff --git a/tools/startup/hook_window.py b/tools/startup/hook_window.py new file mode 100644 index 0000000000..61af3550fd --- /dev/null +++ b/tools/startup/hook_window.py @@ -0,0 +1,160 @@ +"""Step-over window of the startup debugger's one-byte hooks (docs/startup-runtime.md). + +A hook is one patched byte per function. To run the original instruction the debugger restores the +byte, single-steps the thread that hit it and patches the byte again. A second thread that enters +the function inside that window would run the original instruction untraced, so the window holds +every other thread for the step: the owner steps alone and the others resume when it is done. + +This module is the bookkeeping only (no Win32 calls); debug_launch.py passes the suspend and resume +functions. Every window has a deadline, a thread that cannot be held is counted, and the counters +are always reported so a run says how many calls it may have missed. +""" + +HELD, GONE, FAILED = "held", "gone", "failed" +ERROR_INVALID_PARAMETER = 87 # OpenThread: no thread has this id +STILL_ACTIVE = 259 # GetExitCodeThread of a thread that has not exited +STATUS_INVALID_HANDLE = 0xC0000008 +STATUS_THREAD_IS_TERMINATING = 0xC000004B # NtSuspendThread: the thread is exiting and runs no more code + + +def classify_status(status): + """GONE for an NtSuspendThread status that says the thread cannot run again, else FAILED.""" + return GONE if status in (STATUS_THREAD_IS_TERMINATING, STATUS_INVALID_HANDLE) else FAILED + + +def classify_hold(exit_code, error=0, signaled=False): + """Outcome of a hold that did not take: GONE when the thread has exited, FAILED when it is alive. + + A thread that called ExitThread stays in the debugger's thread list until its EXIT_THREAD event is + read, and by then OpenThread still works but SuspendThread and GetThreadContext fail (access + denied). That thread runs no more code, so nothing can race with it: GONE. A live thread that + cannot be suspended is a real hole in the window and stays FAILED. `exit_code` is + GetExitCodeThread (None when it could not be read), `signaled` whether the thread handle is + already signaled, `error` the GetLastError of an OpenThread that returned no handle.""" + if error == ERROR_INVALID_PARAMETER: + return GONE + if signaled or (exit_code is not None and exit_code != STILL_ACTIVE): + return GONE + return FAILED + + +class ReturnBook: + """Pending hooked calls, keyed by return address; each is traced once, when its call returns. + + A call is identified by its thread, the stack slot of its return address, and the hooked entry + address. The entry hook can trap twice for one call when protection is off: another thread + re-patches the byte before this one has run the original instruction, so the thread traps again + at the same entry, thread and slot. That is the same call, so it replaces the first + registration; two entries made the return write two lines and a run counted 88 opens for 64 + made. A hooked function that tail-calls another hooked function shares (tid, slot) with a + different entry address, so both registrations are kept.""" + + def __init__(self): + # return address -> list of (tid, stack slot, description, entry, restore) + self._pending = {} + + def add(self, address, tid, slot, description, entry=None, restore=None): + """Registers a call. restore, if given, undoes a change made to the call's arguments; it runs + once, when the call returns. A re-trap of the same call keeps the first restore: it holds the + caller's original state, the second one would hold the already changed one.""" + items = self._pending.get(address, []) + for item in items: + if (item[0], item[1], item[3]) == (tid, slot, entry): + restore = item[4] or restore + kept = [item for item in items if (item[0], item[1], item[3]) != (tid, slot, entry)] + kept.append((tid, slot, description, entry, restore)) + self._pending[address] = kept + + def pending(self, address): + """Whether any call is still waiting to return to this address (any thread).""" + return bool(self._pending.get(address)) + + def take(self, address, tid, slot): + """Descriptions of the calls that return here on this thread and slot. Their restore callbacks + have run when this returns.""" + items = self._pending.get(address, []) + taken = [item for item in items if (item[0], item[1]) == (tid, slot)] + if taken: + self._pending[address] = [item for item in items if (item[0], item[1]) != (tid, slot)] + for item in taken: + if item[4]: + item[4]() + return [item[2] for item in taken] + + +class StepWindow: + def __init__(self, hold, release, protect=True, limit=2.0): + self._hold, self._release = hold, release # hold(tid) -> HELD | GONE | FAILED; release(tid) + self.protect, self.limit = protect, limit + self.owner = None + self._held = [] + self._deadline = 0.0 + self._exposed = False + self.windows = self.unprotected = self.deferred = self.timeouts = 0 + + def open(self, owner, others, now): + """The owner is about to step over its hook: hold every other thread first.""" + self.windows += 1 + if self.owner is not None: + # A thread that was not held (or reached another hook) steps while a window is open: the + # window stays with its owner and is reported as exposed. + self._expose() + return + if not self.protect: # measuring mode: nothing is held, every window with company is exposed + self.unprotected += 1 if others else 0 + return + self.owner, self._deadline, self._exposed = owner, now + self.limit, False + for tid in others: + self.hold(tid) + + def hold(self, tid): + """Holds one more thread while a window is open (a thread created during the step).""" + if self.owner is None or tid == self.owner or tid in self._held: + return + result = self._hold(tid) + if result == HELD: + self._held.append(tid) + elif result == FAILED: + self._expose() + + def defer(self, tid): + """True when a hook hit comes from a thread held by the open window: it trapped before it was held, so it + must go back to the hook address and trap again once the window is closed.""" + if tid not in self._held: + return False + self.deferred += 1 + return True + + def finish(self, tid): + """The owner's step is done (or the owner is gone): the held threads resume.""" + if self.owner is None or tid != self.owner: + return False + self._close() + return True + + def expire(self, now): + """A window that is still open at its deadline is closed and counted as exposed.""" + if self.owner is None or now < self._deadline: + return False + self.timeouts += 1 + self._expose() + self._close() + return True + + def abandon(self): + """The run is over: resume whatever is held without counting a timeout.""" + self._close() + + def summary(self, entries): + return (f"hook windows: entries={entries} windows={self.windows} unprotected={self.unprotected} " + f"deferred={self.deferred} timeouts={self.timeouts} protection={'on' if self.protect else 'off'}") + + def _expose(self): + if not self._exposed: + self._exposed = True + self.unprotected += 1 + + def _close(self): + held, self._held, self.owner = self._held, [], None + for tid in held: + self._release(tid) diff --git a/tools/startup/import_gfx10_tables.py b/tools/startup/import_gfx10_tables.py new file mode 100644 index 0000000000..198656a8ef --- /dev/null +++ b/tools/startup/import_gfx10_tables.py @@ -0,0 +1,125 @@ +"""Regenerate the C++ GFX10 name tables from the pinned Mesa-derived Victory tables.""" +import argparse +import hashlib +import os +from pathlib import Path +import re +import sys +import tempfile + +_TOOLS_DIR = str(Path(__file__).resolve().parents[1]) +if _TOOLS_DIR not in sys.path: + sys.path.insert(0, _TOOLS_DIR) +import disasm_rdna2 as x2w + +SHA256 = "1ee1228584a611b26cae949efb248fe00fd5e835a550353cc1d33c2f7c262acc" +TABLES = ("SOPP", "SOP1", "SOP2", "SOPC", "SOPK", "VOP1", "VOP2", "VOPC", + "VOP3", "VOP3P", "VINTRP", "SMEM", "MUBUF", "MTBUF", "MIMG", "DS", + "FLAT", "GLOBAL", "SCRATCH") + + +def _validate_source_file(source: Path) -> None: + if source.is_dir(): + raise IsADirectoryError(f"opcodes.rs path is a directory: {source}") + if not source.exists(): + raise FileNotFoundError(f"opcodes.rs file not found: {source}") + if not source.is_file(): + raise ValueError(f"opcodes.rs path is not a regular file: {source}") + + +def _validate_paths(opcodes_rs: Path, output: Path) -> None: + _validate_source_file(opcodes_rs) + if output.is_symlink(): + raise ValueError(f"output path must not be a symlink: {output}") + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + for parent in output.parents: + if parent.is_file() or ((parent.exists() or parent.is_symlink()) and not parent.is_dir()): + raise NotADirectoryError(f"output parent is not a directory: {parent}") + if output.resolve() == opcodes_rs.resolve() or (output.exists() and opcodes_rs.samefile(output)): + raise ValueError(f"output path must differ from opcodes.rs input: {output}") + + +def _write_atomic(path: Path, content: str) -> None: + """Write UTF-8 text to a sibling temp file and atomically replace path, leaving 0 temp files on failure.""" + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + newline="\n", + dir=path.parent, + prefix=f".{path.stem}.", + suffix=".tmp", + delete=False, + ) as handle: + tmp_path = Path(handle.name) + handle.write(content) + os.replace(tmp_path, path) + except BaseException: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + raise + + +def generate(source, expected_sha256=SHA256): + """Parse pinned opcodes.rs and merge X2W disassembler additions into C++ table arrays.""" + source_path = Path(source) + _validate_source_file(source_path) + data = source_path.read_bytes().replace(b"\r\n", b"\n") + if hashlib.sha256(data).hexdigest() != expected_sha256: + raise ValueError("expected victory-shader gfx10/opcodes.rs at 9376fd6") + rust = data.decode("utf-8") + marker = "// Each table" + marker_idx = rust.find(marker) + if marker_idx == -1: + raise ValueError(f"missing {marker!r} marker in {source_path}") + notice = rust[:marker_idx] + out = [notice, "// Generated by tools/startup/import_gfx10_tables.py.\n" + "// The secondary entries come from X2W's gfx1013 disassembler.\n"] + total = extra = 0 + for table in TABLES: + match = re.search(r"const " + table + r": [^=]+?= &\[(.*?)\];", rust, re.S) + if match is None: + raise ValueError(f"missing {table} table in {source_path}") + entries = {int(op, 16): name for op, name in re.findall(r'\(0x([0-9a-f]+), "(\w+)"\)', match.group(1))} + if not entries: + raise ValueError(f"empty {table} table in {source_path}") + total += len(entries) + local = getattr(x2w, table + "_OPS", {}) + if table == "VOP3": + local = {**x2w.VOP3_NATIVE_OPS, **x2w.INTERP_F16_OPS} + if table == "MIMG": + local = {**local, **x2w.MIMG_BVH_OPS} + for op, info in local.items(): + name = info if isinstance(info, str) else info[0] + if op not in entries and isinstance(name, str) and re.fullmatch(r"\w+", name): + entries[op] = re.sub(r"_e(?:32|64)$", "", name) + extra += 1 + out.append(f"constexpr const char* {table.lower()}_names[] = {{") + for offset in range(0, max(entries) + 1, 4): + row = [f'"{entries[i]}"' if i in entries else "nullptr" + for i in range(offset, min(offset + 4, max(entries) + 1))] + out.append(" " + ", ".join(row) + ",") + out.append("};\n") + print(f"Imported {total} Mesa/Victory entries and {extra} X2W additions") + return "\n".join(out) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("opcodes_rs", type=Path) + parser.add_argument("output", type=Path) + args = parser.parse_args(argv) + try: + _validate_paths(args.opcodes_rs, args.output) + _write_atomic(args.output, generate(args.opcodes_rs, expected_sha256=SHA256)) + except (OSError, ValueError, UnicodeDecodeError) as error: + print(f"error: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/startup/launch.py b/tools/startup/launch.py index e2a0ccf207..aeec90a26b 100644 --- a/tools/startup/launch.py +++ b/tools/startup/launch.py @@ -28,6 +28,45 @@ class PROCESS_INFORMATION(ctypes.Structure): _fields_ = [("hProcess", wt.HANDLE), ("hThread", wt.HANDLE), ("dwProcessId", wt.DWORD), ("dwThreadId", wt.DWORD)] +class STARTUPINFOEXW(ctypes.Structure): + _fields_ = [("StartupInfo", STARTUPINFOW), ("lpAttributeList", ctypes.c_void_p)] + + +# X2W_LOW_ADDRESSES=1: the title starts with bottom-up ASLR always off, so its VirtualAlloc blocks come from the low end of the +# address space instead of a random point above 2^40. The package acceleration-structure builder refuses a destination address +# with bits set above bit 39 (#1758). Source: Microsoft documentation of UpdateProcThreadAttribute, +# PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY and PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF. +PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = 0x00020007 +PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF = 0x2 << 16 +EXTENDED_STARTUPINFO_PRESENT = 0x00080000 + + +def low_addresses_requested(env=None): + return (os.environ if env is None else env).get("X2W_LOW_ADDRESSES") == "1" + + +def startup_for_create(si, env=None): + """(structure to pass, extra creation flags, objects to keep alive, note) for CreateProcessW. + + Without X2W_LOW_ADDRESSES=1, or when the attribute list cannot be built, `si` is passed unchanged.""" + if not low_addresses_requested(env) or k32 is None: + return si, 0, None, None + size = ctypes.c_size_t() + k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size)) + buffer = ctypes.create_string_buffer(size.value) + if not k32.InitializeProcThreadAttributeList(buffer, 1, 0, ctypes.byref(size)): + return si, 0, None, f"X2W_LOW_ADDRESSES: attribute list unavailable (error {ctypes.get_last_error()})" + policy = ctypes.c_uint64(PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF) + if not k32.UpdateProcThreadAttribute(buffer, 0, PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, ctypes.byref(policy), + ctypes.sizeof(policy), None, None): + return si, 0, None, f"X2W_LOW_ADDRESSES: mitigation policy refused (error {ctypes.get_last_error()})" + extended = STARTUPINFOEXW() + extended.StartupInfo = si + extended.StartupInfo.cb = ctypes.sizeof(extended) + extended.lpAttributeList = ctypes.cast(buffer, ctypes.c_void_p) + return extended, EXTENDED_STARTUPINFO_PRESENT, (buffer, policy), "X2W_LOW_ADDRESSES: bottom-up ASLR off for the title" + + class IO_COUNTERS(ctypes.Structure): _fields_ = [(n, ctypes.c_ulonglong) for n in ("r", "w", "o", "rb", "wb", "ob")] @@ -255,8 +294,12 @@ def main(argv=None): cmdline = ctypes.create_unicode_buffer(" ".join(quote_argument(a) for a in [exe, *extra])) pi = PROCESS_INFORMATION() flags = 0x4 | 0x400 # CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT + startup, extra_flags, startup_keep, startup_note = startup_for_create(si, env) + if startup_note: + print(startup_note) + flags |= extra_flags if not k32.CreateProcessW(exe, cmdline, None, None, True, flags, ctypes.create_unicode_buffer(block), - cwd, ctypes.byref(si), ctypes.byref(pi)): + cwd, ctypes.byref(startup), ctypes.byref(pi)): print(f"CreateProcess failed: error {ctypes.get_last_error()}") return 2 process_handle = pi.hProcess diff --git a/tools/startup/live_view.py b/tools/startup/live_view.py index 350681ec41..f94bfa3a9d 100644 --- a/tools/startup/live_view.py +++ b/tools/startup/live_view.py @@ -12,19 +12,42 @@ import time +def _storage_completed(line): + """Requests the DirectStorage stand-in has finished, from a status or heartbeat line. + + New lines carry "completed=N" (raw + inflated + bcpack-blank). Older lines have "done=N" (uncompressed copies + only) next to "inflated=N" and, in the heartbeat, "bcpack-blank=N": the same total is rebuilt from those.""" + m = re.search(r"\bcompleted=(\d+)", line) + if m: + return int(m.group(1)) + total = 0 + for name in ("done", "raw", "inflated", "bcpack-blank"): + m = re.search(rf"\b{name}=(\d+)", line) + if m: + total += int(m.group(1)) + return total + + class _LogViewer: """Stateful log parser and status tracker for a single live_view session.""" def __init__(self, package=None): # The package root the run uses as its working directory (run.ps1 -DataDir), next to the G:\ mount. - roots = ["G:\\"] + ([os.path.join(os.path.abspath(package), "")] if package is not None else []) + roots = ["G:\\"] + if package is not None: + # Windows may spell the same root with an 8.3 alias or a different case; the log can + # carry the resolved form while run.ps1 passes the short one. Accept both spellings. + for candidate in (os.path.abspath(package), os.path.realpath(package)): + root = os.path.join(candidate, "") + if root not in roots: + roots.append(root) self.game_file = re.compile( r"Nt(?:CreateFile|OpenFile) (?:\\\?\?\\)?((?i:" + "|".join(map(re.escape, roots)) + r").+)(?= from (?:[^+]*\+)?0x[0-9a-fA-F]+ )" ) self.start = time.time() - self.counts = {"modules": 0, "files": 0, "refused": 0, "chunks": 0, "gpu calls first seen": 0} + self.counts = {"modules": 0, "files": 0, "refused": 0, "chunks": 0, "completed": 0, "gpu calls first seen": 0} self.last_status = 0.0 self.state = "?" self.frames = "0" @@ -87,13 +110,17 @@ def on_shim(self, line): m = re.search(r"inflated=(\d+) failed=(\d+)", line) if m: self.counts["chunks"] = int(m.group(1)) - self.say("storage", f"read batch complete: {m.group(1)} compressed chunks decompressed so far, {m.group(2)} failed") + completed = _storage_completed(line) + self.counts["completed"] = completed + self.say("storage", f"read batch complete: {completed} requests completed so far, " + f"{m.group(1)} compressed chunks decompressed, {m.group(2)} failed") elif "EnqueueRequest" in line or "options=" in line or "Queue::Submit" in line or "IsComplete" in line: return elif line.startswith("x2w-dstorage heartbeat "): m = re.search(r"\binflated=(\d+)", line) if m: self.counts["chunks"] = int(m.group(1)) + self.counts["completed"] = _storage_completed(line) self.say("storage", line) elif line.startswith("x2w-render totals:"): self.say("render", line) @@ -180,6 +207,7 @@ def main(argv=None) -> int: "status", f"state {viewer.state}, {viewer.frames} frames, {viewer.counts['modules']} modules, " f"{viewer.counts['files']} game-file opens, {viewer.counts['chunks']} chunks decompressed, " + f"{viewer.counts['completed']} storage requests completed, " f"{viewer.counts['refused']} network opens refused, " f"{viewer.counts.get('handled probes', 0)} handled probes", ) diff --git a/tools/startup/mesh57_pixel_entry.py b/tools/startup/mesh57_pixel_entry.py new file mode 100644 index 0000000000..89d356d647 --- /dev/null +++ b/tools/startup/mesh57_pixel_entry.py @@ -0,0 +1,75 @@ +"""Read a reviewed pixel entry only when a slot 57 creation archive and all six profile spans match.""" +import argparse +from pathlib import Path +import struct +import sys + +from gfx2hlsl import fnv, mesh57_key + + +def pixel_entry(request, archive, profile): + ms, ps, root = (request.with_suffix(ext).read_bytes() for ext in (".m57", ".ps57", ".root")) + key = mesh57_key(ms, ps, root) + if request.name != f"req_{key:016x}.ps57": + raise ValueError("raw MS, PS or creation root disagrees with request key") + data = archive.read_bytes() + if len(data) < 20: + raise ValueError("truncated fixed creation archive") + recorded, desc_size, a_size, b_size = struct.unpack_from("<Q3I", data) + if recorded != key or desc_size != 0x300 or max(a_size,b_size) > 0x1000 or len(data) != 20 + desc_size + a_size + b_size: + raise ValueError("creation archive key or lengths disagree") + desc = data[20:20 + desc_size] + a = data[20 + desc_size:20 + desc_size + a_size] + b = data[20 + desc_size + a_size:] + fields = struct.unpack_from("<15Q", desc) + if (any(fields[i] for i in (0,1,3,5,9,10,13)) or + (fields[2], fields[4], fields[6], fields[14]) != (len(a), len(b), len(ps), len(ms))): + raise ValueError("normalized mesh descriptor disagrees with request and state lengths") + variant = key + for part in (desc, a, b): + variant = fnv(part, fnv(struct.pack("<Q", len(part)), variant)) + if archive.name != f"req_{variant:016x}.s57" or profile.name != f"{variant:016x}.mesh57-state": + raise ValueError("fixed-state variant disagrees with archive or profile name") + data = profile.read_bytes() + # Mesh57Profile has a fixed Win32 ABI; the static assertion in mesh57_profile.h protects this offset. + header_size = 532 + if len(data) < header_size + 12 or data[:8] not in (b"X2WM572\0", b"X2WM573\0", b"X2WM574\0", b"X2WM575\0", b"X2WM576\0"): + raise ValueError("profile lacks a reviewed pixel entry") + enable, address, wave = struct.unpack_from("<3I", data, header_size) + if address > 0xffff or enable & ~address or wave not in (32, 64): + raise ValueError("invalid reviewed pixel entry") + parts = (desc, a, b, root, ms, ps) + if struct.unpack_from("<6I", data, 8) != tuple(map(len, parts)): + raise ValueError("profile span lengths disagree") + offset = header_size + 12 + version = data[6] - ord("0") + if version >= 3: + offset += 12 # MS constant mapping + if version >= 4: + if offset + 4 > len(data): + raise ValueError("truncated view count") + count, = struct.unpack_from("<I", data, offset) + if not 1 <= count <= 15: + raise ValueError("invalid MS view entry count") + offset += 4 + 12 * count + if version >= 5: + offset += 4 # MS resource heap SGPR + for part in parts: + if data[offset:offset + len(part)] != part: + raise ValueError("profile creation or shader bytes differ") + offset += len(part) + if offset != len(data): + raise ValueError("trailing profile data") + return f"meshps1 {enable} {address} {wave}" + (" guest_root" if version == 6 else "") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("request", type=Path, help="req_<request>.ps57 with adjacent .m57 and .root") + parser.add_argument("archive", type=Path, help="req_<variant>.s57 from the same creation") + parser.add_argument("reviewed_profile", type=Path, help="<variant>.mesh57-state carrying reviewed pixel entry metadata") + args = parser.parse_args() + try: + print(pixel_entry(args.request, args.archive, args.reviewed_profile)) + except (OSError, ValueError) as error: + sys.exit(str(error)) diff --git a/tools/startup/ps_input_scan.py b/tools/startup/ps_input_scan.py index e788b2ba02..8eaeae1a36 100644 --- a/tools/startup/ps_input_scan.py +++ b/tools/startup/ps_input_scan.py @@ -122,35 +122,81 @@ def parse_instruction(asm): return mnemonic, base, ops, mods, destination if has_destination else None, sources, writes +def branch_of(name, asm): + """-> (target byte offset or None, falls through, unknown) for one instruction. `unknown` is set + for a branch whose target the text does not give and for indirect forms.""" + base = base_name(name) + if base == 's_branch' or base.startswith('s_cbranch'): + m = re.search(r'label_0x([0-9a-f]+)', asm) + if m is None or 'fork' in base or 'join' in base: + return None, base != 's_branch', True + return int(m.group(1), 16), base != 's_branch', False + if base in UNKNOWN_FLOW: + return None, base in ('s_swappc_b64', 's_call_b64'), True + return None, not base.startswith('s_endpgm'), False + + def control_flow(decoded): - """-> (branch targets, backward spans (target, source), unknown): offsets from the label text. - `unknown` is set for a branch whose target the text does not give and for indirect forms.""" + """-> (branch targets, backward spans (target, source), unknown): offsets from the label text.""" targets, spans, unknown = set(), [], False for off, _, name, asm in decoded: - base = base_name(name) - if base == 's_branch' or base.startswith('s_cbranch'): - m = re.search(r'label_0x([0-9a-f]+)', asm) - if m is None or 'fork' in base or 'join' in base: - unknown = True - else: - target = int(m.group(1), 16) - targets.add(target) - if target <= off: - spans.append((target, off)) - elif base in UNKNOWN_FLOW: - unknown = True + target, _, indirect = branch_of(name, asm) + unknown |= indirect + if target is not None: + targets.add(target) + if target <= off: + spans.append((target, off)) return targets, spans, unknown +def must_defined(decoded, writes): + """-> per instruction, a bit set of the vector registers written on every path from the entry + to it (the definitions available on all incoming edges, intersected at each join). + + `writes[i]` lists the spans instruction i writes. A branch with an unknown target may reach any + instruction, so its state joins every instruction. An instruction no path reaches keeps every + bit set (-1), which leaves the linear rule in charge there.""" + count = len(decoded) + index = {off: i for i, (off, _, _, _) in enumerate(decoded)} + gen = [sum(((1 << (last + 1)) - (1 << first)) for first, last in spans) for spans in writes] + preds, anywhere = [[] for _ in range(count)], [] + for i, (_, _, name, asm) in enumerate(decoded): + target, falls, indirect = branch_of(name, asm) + if indirect: + anywhere.append(i) + if target in index: + preds[index[target]].append(i) + if falls and i + 1 < count: + preds[i + 1].append(i) + state, out = [-1] * count, [-1] * count + changed = True + while changed: # the sets only lose bits, so this ends + changed = False + everywhere = -1 + for u in anywhere: + everywhere &= out[u] + for i in range(count): + value = 0 if i == 0 else everywhere + for p in preds[i]: + value &= out[p] + if value != state[i]: + state[i], out[i], changed = value, value | gen[i], True + return state + + def contract_of_decoded(decoded): """Scan decoded instructions, (offset, length, name, asm) as gfx2hlsl.decode returns them. - A register first read before any write is live-in, unless the read sits inside a loop (a - backward branch spans it) and the register is written later in program order: then the value may - be loop-carried, the register is `ambiguous` and takes no part in any rule. Evidence taken from - a read that is unsafe in that sense is dropped, and aliases do not cross basic blocks.""" + A register read where it may still hold its entry value is live-in: it is not written earlier in + program order, or it is not written on every path to the read (a forward branch can skip the + write, so the definitions of the incoming edges are intersected at each join). The exception is + a read inside a loop (a backward branch spans it) of a register written later in program order: + then the value may be loop-carried, the register is `ambiguous` and takes no part in any rule. + Evidence taken from a read that is unsafe in that sense is dropped, and aliases do not cross + basic blocks.""" parsed = [(off,) + parse_instruction(asm) for off, _, _, asm in decoded] targets, spans, unknown = control_flow(decoded) + defined = must_defined(decoded, [item[-1] for item in parsed]) last_write = {} for item in parsed: for first, last in item[-1]: @@ -169,12 +215,13 @@ def single(token): span = operand_vregs(token) return span[0] if span and span[0] == span[1] else None - for off, mnemonic, base, ops, mods, destination, sources, writes in parsed: + for position, (off, mnemonic, base, ops, mods, destination, sources, writes) in enumerate(parsed): if off in targets: holds.clear() if not ops: continue in_loop = unknown or any(t <= off <= s for t, s in spans) + everywhere = defined[position] def unsafe(register): later = last_write.get(register) @@ -184,7 +231,7 @@ def unsafe(register): span = operand_vregs(token) if span: for register in range(span[0], span[1] + 1): - if register not in written: + if register not in written or not everywhere >> register & 1: (ambiguous if unsafe(register) else live_in).add(register) fields = {} diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 8132b595e2..36582acecb 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -19,29 +19,38 @@ param( [string]$BuildDir = "out/build/release", [int]$MemoryGiB = 14, [int]$ContinueAsserts = 0, # main-image int3s to log and step over (title soft asserts) + [int]$AssertSites = 0, # distinct main-image int3 sites whose every hit is stepped over [string]$InputScript = "", # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s - [string]$StoragePath = "", # X2W_STORAGE_PATH: persistent local storage root (a trailing \ is added when missing) + [string]$MapDrive = "", # e.g. "G=D:\package": rewrite opens on a console letter + [string]$StoragePath = "", # X2W_STORAGE_PATH: root of the console drive the title sees (it appends x2w-gamesave) [string]$ShaderCache = "out/startup/shader_cache", [switch]$Render, # draw through translated pipelines [switch]$FakeUser, # answer the user API for one local user [switch]$GpuMirror, # map CPU-view pages into the paired GPU-view reservation [switch]$HostCpu, # rewrite instructions the host processor lacks (X2W_HOST_CPU) [switch]$Translate, # with -Render: translate new shader requests during the run (gfx2hlsl.py --watch) + [string]$NativeShaders = "", # with -Render: the directory of dxcompiler.dll and dxil.dll; compute requests are translated in the stand-in (X2W_NATIVE_SHADERS) + [switch]$FreshShaderCache, # with -Render: move a shader cache that is not empty aside first [switch]$StartupBelow40, # place the 0x283 large-page startup blocks below 2^40 (X2W_XMEM_STARTUP_BELOW_40) + [switch]$LowAddresses, # start the title with bottom-up ASLR off, so its own allocations stay below 2^40 (X2W_LOW_ADDRESSES, #1758) + [switch]$LazyMemory, # commit physical pages and large startup blocks on first touch (X2W_XMEM_LAZY_COMMIT, X2W_XMEM_LAZY_STARTUP, X2W_XMEM_SHARED_VIEWS) [switch]$TraceCalls, # also break on runtime and movie-player calls (--trace-calls 1; slows the process) + [double]$CaptureEvery = 0, # --capture-every: save the title window as window_<sss>s.png every N seconds (0 = off) + [ValidateSet(0, 1)] [int]$SuspendOthers = 1, # --suspend-others: 0 = don't hold other threads while a hook steps (faster, can miss traced calls) [switch]$TraceApi # log runtime provider method calls (X2W_TRACE_API) ) $ErrorActionPreference = "Stop" $repo = Resolve-Path (Join-Path $PSScriptRoot "..\..") $runDir = Split-Path -Parent (Resolve-Path $Exe) +$buildRoot = if ([System.IO.Path]::IsPathRooted($BuildDir)) { $BuildDir } else { Join-Path $repo $BuildDir } foreach ($dll in "xmem", "d3d12_xs", "AcpHal", "XCRDAPI", "chad", "xapu", "xg_xs", "GameInput") { - Copy-Item (Join-Path $repo "$BuildDir\$dll.dll") $runDir -Force + Copy-Item -LiteralPath (Join-Path $buildRoot "$dll.dll") -Destination $runDir -Force } $env:X2W_AUDIO_PERMISSIVE = "1"; $env:X2W_D3D12_DEVICE_NOOP = "1"; $env:X2W_D3D12_LIST_NOOP = "1" $env:X2W_D3D12_PERMISSIVE = "1"; $env:X2W_XMEM_PERMISSIVE = "1"; $env:X2W_RUNTIME_PROXY = "1" $config = Join-Path $DataDir "MicrosoftGame.config" -if (Test-Path $config) { - $text = Get-Content $config -Raw +if (Test-Path -LiteralPath $config) { + $text = Get-Content -LiteralPath $config -Raw if ($text -match "<TitleId>([^<]*)") { $env:X2W_TITLE_ID = $Matches[1] } if ($text -match "<SizeMB>([^<]*)") { $env:X2W_STORAGE_MB = $Matches[1] } } @@ -55,27 +64,62 @@ if ($GpuMirror) { $env:X2W_XMEM_GPU_MIRROR = "1" } if ($HostCpu) { $env:X2W_HOST_CPU = "1" } if ($TraceApi) { $env:X2W_TRACE_API = "1" } if ($StartupBelow40) { $env:X2W_XMEM_STARTUP_BELOW_40 = "1" } +if ($LowAddresses) { $env:X2W_LOW_ADDRESSES = "1" } +if ($LazyMemory) { + $env:X2W_XMEM_LAZY_COMMIT = "1"; $env:X2W_XMEM_LAZY_STARTUP = "1"; $env:X2W_XMEM_SHARED_VIEWS = "1" +} +$python = Join-Path $repo "out\pe-env\Scripts\python.exe" +if (-not (Test-Path -LiteralPath $python)) { $python = "python" } +$revisionTool = Join-Path $PSScriptRoot "shader_cache_revision.py" +if ($FreshShaderCache -and -not $Render) { Write-Warning "-FreshShaderCache needs -Render (no shader cache without it); ignored" } if ($Render) { + if ($FreshShaderCache) { + $cachePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ShaderCache) + & $python -B $revisionTool $cachePath --fresh | ForEach-Object { Write-Host $_ } + } New-Item -ItemType Directory -Force $ShaderCache | Out-Null $env:X2W_D3D12_RENDER = "1"; $env:X2W_DRAW_NULL_IDENTITY = "1" $env:X2W_SHADER_CACHE = (Resolve-Path $ShaderCache).Path + if ($NativeShaders) { $env:X2W_NATIVE_SHADERS = (Resolve-Path $NativeShaders).Path } } +if ($NativeShaders -and -not $Render) { Write-Warning "-NativeShaders needs -Render (no shader requests without it); ignored" } New-Item -ItemType Directory -Force $LogDir | Out-Null -$python = Join-Path $repo "out\pe-env\Scripts\python.exe" -if (-not (Test-Path -LiteralPath $python)) { $python = "python" } +# Requests keyed by another revision are all refused, and the translator's log does not say why: warn once, +# before the watcher starts (revision.txt of an earlier run) or after the run (the one this run's stand-ins wrote). +$checkRevision = { + $note = & $python -B $revisionTool $env:X2W_SHADER_CACHE --translator (Join-Path $PSScriptRoot 'gfx2hlsl.py') + if ($LASTEXITCODE -eq 0) { return $false } + if ($LASTEXITCODE -eq 1) { Write-Warning ($note -join ' ') } + else { Write-Warning "the shader cache revision was not checked (python exit $LASTEXITCODE)" } + return $true +} +$revisionWarned = $false $translator = $null +$watchShaders = $Translate -and $Render if ($Translate -and -not $Render) { Write-Warning "-Translate needs -Render (no shader cache without it); ignored" } -if ($Translate -and $Render) { +if ($watchShaders) { + $revisionWarned = & $checkRevision $translator = Start-Process -FilePath $python -PassThru -NoNewWindow ` -ArgumentList "-B", "`"$(Join-Path $PSScriptRoot 'gfx2hlsl.py')`"", "--watch", "`"$env:X2W_SHADER_CACHE`"" ` -RedirectStandardOutput (Join-Path $LogDir "translate.txt") -RedirectStandardError (Join-Path $LogDir "translate_err.txt") } $traceArgs = @() if ($TraceCalls) { $traceArgs = @("--trace-calls", "1") } +$mapArgs = @() +if ($MapDrive) { $mapArgs = @("--map-drive", $MapDrive) } +$captureArgs = @() +if ($CaptureEvery -ne 0) { $captureArgs = @("--capture-every", "$CaptureEvery") } +$holdArgs = @() +if ($SuspendOthers -eq 0) { $holdArgs = @("--suspend-others", "0") } try { - & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` - --trace-files 1 --continue-asserts $ContinueAsserts @traceArgs *> "$LogDir.out" - $debuggerExit = $LASTEXITCODE + # Windows PowerShell 5.1 wraps redirected native stderr as an error record. Keep that + # from aborting the launcher before it can report the debugger's exit code. + & { + $ErrorActionPreference = "Continue" + & $python -B (Join-Path $PSScriptRoot "debug_launch.py") $Exe $DataDir $LogDir --timeout $Seconds --memory-gib $MemoryGiB ` + --trace-files 1 --continue-asserts $ContinueAsserts --assert-sites $AssertSites @mapArgs @traceArgs @captureArgs @holdArgs + $script:debuggerExit = $LASTEXITCODE + } *> "$LogDir.out" } finally { # taskkill /T needs a live parent PID to reach the watcher's workers. if ($translator -and -not $translator.HasExited) { @@ -87,5 +131,6 @@ try { } } } +if ($watchShaders -and -not $revisionWarned) { $null = & $checkRevision } Get-Content "$LogDir.out" -TotalCount 5 exit $debuggerExit diff --git a/tools/startup/run.sh b/tools/startup/run.sh index 01a32d4872..60fc617682 100755 --- a/tools/startup/run.sh +++ b/tools/startup/run.sh @@ -15,6 +15,7 @@ # X2W_FXC the FXC the shader watcher runs under --translate (docs/startup-runtime.md); # a host path is passed in its Z: spelling # WINEDLLOVERRIDES, WINEFSYNC, WINEDEBUG default to the docs/wine.md values when unset +# X2W_HOST_PYTHON the host python that compares the shader cache with the translator (default: python3) # Paths may be host paths or drive paths such as 'G:\'. The debugger and the watcher get them as # given (host paths in their Z: spelling); this script reads and creates drive paths through the # prefix's dosdevices links. Needs bash 4.4 or newer, GNU realpath and setsid (Linux). @@ -26,30 +27,33 @@ set -uo pipefail usage() { echo "usage: run.sh --exe EXE --data DIR --log DIR [--seconds 120] [--build-dir out/build/release]" >&2 - echo " [--memory-gib 14] [--continue-asserts 0] [--input-script S] [--storage DIR]" >&2 + echo " [--memory-gib 14] [--continue-asserts 0] [--assert-sites 0] [--input-script S] [--storage DIR]" >&2 echo " [--shader-cache out/startup/shader_cache] [--console 0|1] [--render] [--fake-user]" >&2 echo " [--gpu-mirror] [--host-cpu] [--translate] [--startup-below-40] [--trace-calls]" >&2 - echo " [--hide-title-window]" >&2 + echo " [--hide-title-window] [--capture-every S] [--fresh-shader-cache] [--suspend-others 0|1]" >&2 exit 64 } repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) here="$repo/tools/startup" -exe="" data="" log="" seconds=120 build_dir=out/build/release memory_gib=14 continue_asserts=0 -input_script="" storage="" shader_cache=out/startup/shader_cache console=1 -render="" fake_user="" gpu_mirror="" host_cpu="" translate="" below_40="" trace_calls="" hide_title="" +exe="" data="" log="" seconds=120 build_dir=out/build/release memory_gib=14 continue_asserts=0 assert_sites=0 +input_script="" storage="" shader_cache=out/startup/shader_cache console=1 capture_every=0 suspend_others=1 +render="" fake_user="" gpu_mirror="" host_cpu="" translate="" below_40="" trace_calls="" hide_title="" fresh_cache="" while [ $# -gt 0 ]; do case $1 in - --exe|--data|--log|--seconds|--build-dir|--memory-gib|--continue-asserts|--input-script|--storage|\ - --shader-cache|--console) + --exe|--data|--log|--seconds|--build-dir|--memory-gib|--continue-asserts|--assert-sites|--input-script|--storage|\ + --shader-cache|--console|--capture-every|--suspend-others) [ $# -ge 2 ] || usage case $1 in --exe) exe=$2 ;; --data) data=$2 ;; --log) log=$2 ;; --seconds) seconds=$2 ;; --build-dir) build_dir=$2 ;; --memory-gib) memory_gib=$2 ;; --continue-asserts) continue_asserts=$2 ;; # main-image int3s to log and step over + --assert-sites) assert_sites=$2 ;; # distinct int3 sites whose every hit is stepped over --input-script) input_script=$2 ;; # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s --storage) storage=$2 ;; # X2W_STORAGE_PATH: persistent local storage root --shader-cache) shader_cache=$2 ;; --console) console=$2 ;; + --capture-every) capture_every=$2 ;; # window_<sss>s.png every N seconds (0 = off) + --suspend-others) suspend_others=$2 ;; # 0 = don't hold other threads while a hook steps esac shift 2 ;; --render) render=1; shift ;; # draw through translated pipelines @@ -60,11 +64,13 @@ while [ $# -gt 0 ]; do --startup-below-40) below_40=1; shift ;; # X2W_XMEM_STARTUP_BELOW_40 --trace-calls) trace_calls=1; shift ;; # also break on runtime and movie-player calls (slow) --hide-title-window) hide_title=1; shift ;; # X2W_HIDE_TITLE_WINDOW: hide the title's own window + --fresh-shader-cache) fresh_cache=1; shift ;; # with --render: move a cache that is not empty aside first -h|--help) usage ;; *) echo "run.sh: unknown argument '$1'" >&2; usage ;; esac done [ -n "$exe" ] && [ -n "$data" ] && [ -n "$log" ] || usage +case $suspend_others in 0|1) ;; *) echo "run.sh: --suspend-others takes 0 or 1" >&2; exit 64 ;; esac [ -n "${WINEPREFIX:-}" ] || { echo "run.sh: set WINEPREFIX (docs/non-windows-hosts.md)" >&2; exit 64; } [ -n "${X2W_WIN_PYTHON:-}" ] || { echo "run.sh: set X2W_WIN_PYTHON to a Windows python.exe (docs/wine.md)" >&2; exit 64; } export WINEPREFIX @@ -100,6 +106,9 @@ export X2W_AUDIO_PERMISSIVE=1 X2W_D3D12_DEVICE_NOOP=1 X2W_D3D12_LIST_NOOP=1 export X2W_D3D12_PERMISSIVE=1 X2W_XMEM_PERMISSIVE=1 X2W_RUNTIME_PROXY=1 # Under Wine, one section and view per page did not get past start-up (docs/wine.md). export X2W_XMEM_SHARED_VIEWS=${X2W_XMEM_SHARED_VIEWS:-1} +# Mapping calls join the shared view that ends at their address: fewer views, and under Wine each map costs more +# the more views there are (docs/wine.md). +export X2W_XMEM_JOIN_CALLS=${X2W_XMEM_JOIN_CALLS:-1} export WINEDEBUG=${WINEDEBUG:--all} WINEFSYNC=${WINEFSYNC:-1} # Wine's built-in D3D12 is not enough (docs/wine.md); the prefix holds vkd3d-proton and DXVK. export WINEDLLOVERRIDES=${WINEDLLOVERRIDES:-d3d12,d3d12core,dxgi,d3d11=n} @@ -139,7 +148,14 @@ fi if [ -n "$hide_title" ] && [ -z "$render" ]; then echo "WARNING: --hide-title-window needs --render (no output window without it); it has no effect" >&2 fi +host_python=${X2W_HOST_PYTHON:-python3} +if [ -n "$fresh_cache" ] && [ -z "$render" ]; then + echo "WARNING: --fresh-shader-cache needs --render (no shader cache without it); ignored" >&2 +fi if [ -n "$render" ]; then + if [ -n "$fresh_cache" ]; then + "$host_python" -B "$here/shader_cache_revision.py" "$(host_path "$shader_cache")" --fresh >&2 + fi mkdir -p "$(host_path "$shader_cache")" export X2W_D3D12_RENDER=1 X2W_DRAW_NULL_IDENTITY=1 X2W_SHADER_CACHE=$(win_path "$shader_cache") @@ -176,6 +192,22 @@ on_signal() { kill -s "$1" $$ } trap 'on_signal INT' INT +# Requests keyed by another revision are all refused, and the translator's log does not say why: warn once, +# before the watcher starts (revision.txt of an earlier run) or after the run (the one this run's stand-ins wrote). +revision_warned="" +check_cache_revision() { + local note rc + note=$("$host_python" -B "$here/shader_cache_revision.py" "$(host_path "$shader_cache")" \ + --translator "$here/gfx2hlsl.py" 2>&1) + rc=$? + if [ $rc -eq 1 ]; then + echo "WARNING: $note" >&2 + revision_warned=1 + elif [ $rc -ne 0 ]; then + echo "WARNING: the shader cache revision was not checked ($host_python exit $rc)" >&2 + revision_warned=1 + fi +} if [ -n "$translate" ] && [ -z "$render" ]; then echo "WARNING: --translate needs --render (no shader cache without it); ignored" >&2 fi @@ -186,6 +218,7 @@ if [ -n "$translate" ] && [ -n "$render" ]; then # before setsid, so setsid does not fork and $! is the new group's id. # An empty X2W_FXC (manifest only) is passed on as it is. if [ -n "${X2W_FXC:-}" ]; then X2W_FXC=$(win_path "$X2W_FXC"); export X2W_FXC; fi + check_cache_revision WINEDLLOVERRIDES="$WINEDLLOVERRIDES;d3dcompiler_47=n" \ setsid "$wine" "$X2W_WIN_PYTHON" -B "$(win_path "$here/gfx2hlsl.py")" --watch "$X2W_SHADER_CACHE" \ > "$log_host/translate.txt" 2> "$log_host/translate_err.txt" < /dev/null & @@ -195,9 +228,14 @@ trace_args=() [ -z "$trace_calls" ] || trace_args=(--trace-calls 1) console_args=() [ "$console" = 1 ] || console_args=(--console "$console") +capture_args=() +[ "$capture_every" = 0 ] || capture_args=(--capture-every "$capture_every") +hold_args=() +[ "$suspend_others" = 1 ] || hold_args=(--suspend-others 0) "$wine" "$X2W_WIN_PYTHON" -B "$(win_path "$here/debug_launch.py")" "$(win_path "$exe")" "$(win_path "$data")" \ "$(win_path "$log")" --timeout "$seconds" --memory-gib "$memory_gib" --trace-files 1 \ - --continue-asserts "$continue_asserts" "${trace_args[@]}" "${console_args[@]}" > "$log_host.out" 2>&1 + --continue-asserts "$continue_asserts" --assert-sites "$assert_sites" "${trace_args[@]}" "${console_args[@]}" "${capture_args[@]}" "${hold_args[@]}" > "$log_host.out" 2>&1 debugger_exit=$? +if [ -n "$translate" ] && [ -n "$render" ] && [ -z "$revision_warned" ]; then check_cache_revision; fi head -n 5 "$log_host.out" exit $debugger_exit diff --git a/tools/startup/scene_color_report.py b/tools/startup/scene_color_report.py new file mode 100644 index 0000000000..56e326ae92 --- /dev/null +++ b/tools/startup/scene_color_report.py @@ -0,0 +1,832 @@ +#!/usr/bin/env python3 +"""Build a bounded Markdown report from a per-draw texel history. + +Refs #870. The startup draw dump writes ``pixel_history.txt`` when +``X2W_DRAW_DUMP_FRAME`` and ``X2W_DRAW_DUMP_PIXEL`` are set (see +``src/startup_stubs/pixel_history.h``). This tool turns that history into a +small review artifact for the first scene-colour write: it selects a frame and +a pixel, names the first retained draw whose sample changes the value, and +reports the last retained writer. Full-dump BMPs are read only to check the +selected pixel and the target dimensions; they are not merged into the history. + +The report never copies raw log lines, paths, arbitrary text or game filenames. +Only allowlisted values (numbers, DXGI format names, opaque 64-bit keys and the +fixed labels below) reach the output. + +Uses only the Python 3 standard library. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from pathlib import Path +import re +import struct +import sys +from typing import Iterable, Sequence + + +TOOL_VERSION = 1 +HISTORY_FILE = "pixel_history.txt" +RUNTIME_SAMPLE_LIMIT = 48 + +MAX_HISTORY_BYTES = 1 << 20 +MAX_HISTORY_RECORDS = 4096 +MAX_LINE_BYTES = 4096 +MAX_BMPS = 64 +MAX_BMP_BYTES = 64 << 20 +MAX_BMP_DIMENSION = 16384 +DEFAULT_MAX_ROWS = 24 +MAX_MAX_ROWS = 64 +MIN_MAX_ROWS = 8 +MAX_GROUPS = 8 + +# DXGI_FORMAT values that pixel_history_decode() can turn into RGBA channels. +# The second member is True when the 32-bit word stores B8G8R8A8. +RGBA8_FORMATS: dict[int, tuple[str, bool]] = { + 28: ("DXGI_FORMAT_R8G8B8A8_UNORM", False), + 29: ("DXGI_FORMAT_R8G8B8A8_UNORM_SRGB", False), + 87: ("DXGI_FORMAT_B8G8R8A8_UNORM", True), + 91: ("DXGI_FORMAT_B8G8R8A8_UNORM_SRGB", True), +} + +CLASS_LABELS = { + "no_draw": "aucun draw", + "ui_only": "draw UI seulement", + "target_write": "écriture de cible", + "value_unchanged": "valeur inchangée", + "history_truncated": "historique tronqué", + "target_non_rgba8": "cible non-RGBA8", +} + +HEADER_RE = re.compile(r"\Ax2w-pixel-history 1 samples=([0-9]+)\Z") +SAMPLE_RE = re.compile( + r"\Adraw=([0-9]+) frame=(-?[0-9]+) x=([0-9]+) y=([0-9]+) " + r"key=([0-9A-Fa-f]{16}) count=([0-9]+) format=([0-9]+) raw=([0-9A-Fa-f]{8})" + r"(?: rgba=([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}))?\Z" +) +BMP_NAME_RE = re.compile(r"\Adraw_([0-9]+)_([0-9A-Fa-f]{16})_([0-9]+)\.bmp\Z", re.IGNORECASE) + +UINT64_MAX = (1 << 64) - 1 +INT64_MIN = -(1 << 63) +INT64_MAX = (1 << 63) - 1 +UINT32_MAX = (1 << 32) - 1 +INT32_MAX = (1 << 31) - 1 + + +class ReportError(Exception): + """A controlled input error whose text is safe to print.""" + + +@dataclass(frozen=True) +class Sample: + draw: int + frame: int + x: int + y: int + key: int + count: int + format: int + raw: int + rgba: tuple[int, int, int, int] | None + order: int + + +@dataclass +class History: + declared: int + samples: list[Sample] + physical_records: int + malformed: int + read_truncated: bool + header_mismatch: bool + duplicate_draws: int + rgba_mismatches: int + rgba_missing: int + rgba_ignored: int + + @property + def cap_reached(self) -> bool: + return ( + self.read_truncated + or self.header_mismatch + or self.declared >= RUNTIME_SAMPLE_LIMIT + or len(self.samples) >= RUNTIME_SAMPLE_LIMIT + ) + + +@dataclass(frozen=True) +class Group: + frame: int + x: int + y: int + format: int + samples: tuple[Sample, ...] + + +@dataclass(frozen=True) +class BmpInfo: + path: Path + draw: int + key: int + count: int + width: int + height: int + top_down: bool + bits_per_pixel: int + pixel_offset: int + row_bytes: int + file_size: int + + +@dataclass +class BmpSummary: + total: int = 0 + valid: int = 0 + invalid: int = 0 + dimensions: tuple[tuple[int, int], ...] = () + matched: int = 0 + mismatched: int = 0 + out_of_range: int = 0 + unreadable: int = 0 + skipped: int = 0 + mismatch_rows: tuple[tuple[int, str, str], ...] = () + + +def _format_label(fmt: int) -> str: + entry = RGBA8_FORMATS.get(fmt) + if entry is not None: + return entry[0] + return "unknown" + + +def _format_cell(fmt: int) -> str: + return f"{_format_label(fmt)} (`{fmt}`)" + + +def _key_cell(key: int) -> str: + return f"`{key:016x}`" + + +def _raw_cell(raw: int) -> str: + return f"`0x{raw:08x}`" + + +def _rgba_cell(rgba: tuple[int, int, int, int] | None) -> str: + if rgba is None: + return "_n/a_" + return f"`{rgba[0]},{rgba[1]},{rgba[2]},{rgba[3]}`" + + +def decode_rgba(raw: int, fmt: int) -> tuple[int, int, int, int] | None: + """Decode a raw 32-bit word the same way pixel_history_decode() does.""" + entry = RGBA8_FORMATS.get(fmt) + if entry is None: + return None + bgra = entry[1] + if bgra: + return (raw >> 16) & 0xFF, (raw >> 8) & 0xFF, raw & 0xFF, (raw >> 24) & 0xFF + return raw & 0xFF, (raw >> 8) & 0xFF, (raw >> 16) & 0xFF, (raw >> 24) & 0xFF + + +def parse_history(path: Path) -> History: + """Parse pixel_history.txt with bounded reads and strict allowlisted fields.""" + try: + size = path.stat().st_size + with path.open("rb") as handle: + data = handle.read(MAX_HISTORY_BYTES + 1) + except OSError as exc: + raise ReportError("pixel_history.txt is not readable") from exc + + read_truncated = size > MAX_HISTORY_BYTES + if read_truncated: + data = data[:MAX_HISTORY_BYTES] + # Drop a final partial record rather than report it as malformed. + if data and not data.endswith((b"\n", b"\r")): + cut = data.rfind(b"\n") + data = data[:cut] if cut >= 0 else b"" + + lines = data.splitlines() + if not lines: + raise ReportError("pixel_history.txt is empty or has no header") + + try: + header = lines[0].decode("ascii").rstrip("\r") + except UnicodeDecodeError as exc: + raise ReportError("pixel_history.txt has a non-ASCII header") from exc + match = HEADER_RE.fullmatch(header) + if match is None: + raise ReportError("pixel_history.txt has a missing or unsupported header") + declared = int(match.group(1)) + if declared > MAX_HISTORY_RECORDS: + read_truncated = True + + records = lines[1:] + if len(records) > MAX_HISTORY_RECORDS: + read_truncated = True + records = records[:MAX_HISTORY_RECORDS] + physical_records = len(records) + header_mismatch = read_truncated or declared != physical_records + + samples: list[Sample] = [] + malformed = 0 + duplicates = 0 + rgba_mismatches = 0 + rgba_missing = 0 + rgba_ignored = 0 + seen_draws: set[int] = set() + + for order, raw_line in enumerate(records): + if not raw_line or len(raw_line) > MAX_LINE_BYTES: + malformed += 1 + continue + text = raw_line.decode("ascii", "replace").rstrip("\r") + match = SAMPLE_RE.fullmatch(text) + if match is None: + malformed += 1 + continue + try: + draw = int(match.group(1)) + frame = int(match.group(2)) + x = int(match.group(3)) + y = int(match.group(4)) + key = int(match.group(5), 16) + count = int(match.group(6)) + fmt = int(match.group(7)) + raw = int(match.group(8), 16) + declared_rgba = None + if match.group(9) is not None: + declared_rgba = tuple(int(match.group(index)) for index in range(9, 13)) + except (TypeError, ValueError): + malformed += 1 + continue + + if not (0 <= draw <= UINT64_MAX and INT64_MIN <= frame <= INT64_MAX + and 0 <= x <= UINT32_MAX and 0 <= y <= UINT32_MAX + and 0 <= count <= UINT32_MAX and 0 <= fmt <= INT32_MAX + and 0 <= raw <= UINT32_MAX): + malformed += 1 + continue + if declared_rgba is not None and any(channel > 255 for channel in declared_rgba): + malformed += 1 + continue + + decoded = decode_rgba(raw, fmt) + if decoded is None: + if declared_rgba is not None: + rgba_ignored += 1 + elif declared_rgba is None: + rgba_missing += 1 + elif declared_rgba != decoded: + rgba_mismatches += 1 + + if draw in seen_draws: + duplicates += 1 + else: + seen_draws.add(draw) + samples.append(Sample(draw=draw, frame=frame, x=x, y=y, key=key, count=count, + format=fmt, raw=raw, rgba=decoded, order=order)) + + return History( + declared=declared, + samples=samples, + physical_records=physical_records, + malformed=malformed, + read_truncated=read_truncated, + header_mismatch=header_mismatch, + duplicate_draws=duplicates, + rgba_mismatches=rgba_mismatches, + rgba_missing=rgba_missing, + rgba_ignored=rgba_ignored, + ) + + +def build_groups(samples: Iterable[Sample]) -> list[Group]: + grouped: dict[tuple[int, int, int, int], list[Sample]] = {} + for sample in samples: + grouped.setdefault((sample.frame, sample.x, sample.y, sample.format), []).append(sample) + groups = [ + Group(frame=key[0], x=key[1], y=key[2], format=key[3], + samples=tuple(sorted(value, key=lambda item: (item.draw, item.order)))) + for key, value in grouped.items() + ] + groups.sort(key=lambda group: (-len(group.samples), group.frame, group.x, group.y, group.format)) + return groups + + +def select_group(groups: Sequence[Group], frame: int | None, + pixel: tuple[int, int] | None) -> tuple[Group | None, int]: + choices = list(groups) + if frame is not None: + choices = [group for group in choices if group.frame == frame] + if pixel is not None: + choices = [group for group in choices if group.x == pixel[0] and group.y == pixel[1]] + if not choices: + return None, 0 + choices.sort(key=lambda group: (-len(group.samples), group.frame, group.x, group.y, group.format)) + return choices[0], len(choices) + + +def find_baseline(samples: Sequence[Sample], selected: Group) -> Sample | None: + first = selected.samples[0] + best = None + for sample in samples: + if sample.x != selected.x or sample.y != selected.y or sample.format != selected.format: + continue + if (sample.frame, sample.draw, sample.order) >= (first.frame, first.draw, first.order): + continue + if best is None or (sample.draw, sample.order) > (best.draw, best.order): + best = sample + return best + + +def _read_bmp_info(path: Path) -> BmpInfo | None: + try: + size = path.stat().st_size + if size < 54 or size > MAX_BMP_BYTES: + return None + with path.open("rb") as handle: + header = handle.read(54) + except OSError: + return None + if len(header) != 54: + return None + try: + bf_type, _, _, _, bf_off_bits = struct.unpack_from("<2sIHHI", header, 0) + bi_size, width, height, planes, bit_count, compression, _, _, _, _, _ = struct.unpack_from( + "<IiiHHIIiiII", header, 14) + except struct.error: + return None + if bf_type != b"BM" or bi_size < 40 or planes != 1 or compression != 0: + return None + if bit_count not in (24, 32) or width <= 0 or height == 0: + return None + if width > MAX_BMP_DIMENSION or abs(height) > MAX_BMP_DIMENSION: + return None + top_down = height < 0 + rows = abs(height) + row_bytes = ((width * bit_count + 31) // 32) * 4 + if bf_off_bits < 54 or bf_off_bits >= size: + return None + if bf_off_bits + row_bytes * rows > size: + return None + return BmpInfo(path=path, draw=0, key=0, count=0, width=width, height=rows, + top_down=top_down, bits_per_pixel=bit_count, pixel_offset=bf_off_bits, + row_bytes=row_bytes, file_size=size) + + +def _bmp_pixel(info: BmpInfo, x: int, y: int) -> tuple[int, int, int] | None: + if x < 0 or y < 0 or x >= info.width or y >= info.height: + return None + row = y if info.top_down else info.height - 1 - y + offset = info.pixel_offset + row * info.row_bytes + x * (info.bits_per_pixel // 8) + try: + with info.path.open("rb") as handle: + handle.seek(offset) + data = handle.read(info.bits_per_pixel // 8) + except OSError: + return None + if len(data) != info.bits_per_pixel // 8: + return None + return data[2], data[1], data[0] + + +def scan_bmps(folder: Path, selected: Group | None) -> BmpSummary: + summary = BmpSummary() + try: + entries = sorted(entry for entry in folder.iterdir() if entry.is_file()) + except OSError: + return summary + + valid: list[BmpInfo] = [] + for entry in entries: + if summary.total >= MAX_BMPS: + break + name_match = BMP_NAME_RE.fullmatch(entry.name) + if name_match is None: + continue + summary.total += 1 + info = _read_bmp_info(entry) + if info is None: + summary.invalid += 1 + continue + try: + draw = int(name_match.group(1)) + key = int(name_match.group(2), 16) + count = int(name_match.group(3)) + except ValueError: + summary.invalid += 1 + continue + if not (0 <= draw <= UINT64_MAX and 0 <= count <= UINT32_MAX): + summary.invalid += 1 + continue + info = BmpInfo(path=info.path, draw=draw, key=key, count=count, width=info.width, + height=info.height, top_down=info.top_down, + bits_per_pixel=info.bits_per_pixel, pixel_offset=info.pixel_offset, + row_bytes=info.row_bytes, file_size=info.file_size) + valid.append(info) + + summary.valid = len(valid) + summary.dimensions = tuple(sorted({(info.width, info.height) for info in valid})) + if selected is None or not selected.samples: + return summary + + index = {(info.draw, info.key, info.count): info for info in valid} + mismatches: list[tuple[int, str, str]] = [] + for sample in selected.samples: + info = index.get((sample.draw, sample.key, sample.count)) + if info is None: + continue + rgb = _bmp_pixel(info, sample.x, sample.y) + if rgb is None: + if not (0 <= sample.x < info.width and 0 <= sample.y < info.height): + summary.out_of_range += 1 + else: + summary.unreadable += 1 + continue + if sample.rgba is None: + summary.skipped += 1 + continue + expected = sample.rgba[:3] + if rgb == expected: + summary.matched += 1 + else: + summary.mismatched += 1 + if len(mismatches) < 3: + mismatches.append((sample.draw, f"{expected[0]},{expected[1]},{expected[2]}", + f"{rgb[0]},{rgb[1]},{rgb[2]}")) + summary.mismatch_rows = tuple(mismatches) + return summary + + +def _choose_rows(count: int, maximum: int, must: Iterable[int]) -> tuple[list[int], int]: + if count <= maximum: + return list(range(count)), 0 + chosen = {index for index in must if 0 <= index < count} + left, right = 0, count - 1 + while len(chosen) < maximum and left <= right: + chosen.add(left) + left += 1 + if len(chosen) < maximum and left <= right: + chosen.add(right) + right -= 1 + ordered = sorted(chosen) + return ordered, count - len(ordered) + + +def _classification(history: History, selected: Group | None, + baseline_known: bool, baseline_raw: int, + transition_count: int) -> tuple[str, str]: + """Return (primary classification, write outcome).""" + if selected is None or not selected.samples: + return "no_draw", "no_draw" + if selected.format not in RGBA8_FORMATS: + return "target_non_rgba8", "target_non_rgba8" + if transition_count == 0: + if len(selected.samples) == 1 and not baseline_known: + outcome = "value_unchanged" + else: + outcome = "ui_only" + elif selected.samples[-1].raw != baseline_raw: + outcome = "target_write" + else: + outcome = "value_unchanged" + if history.cap_reached: + return "history_truncated", outcome + return outcome, outcome + + +def _render_group_table(groups: Sequence[Group], maximum: int = MAX_GROUPS) -> list[str]: + if not groups: + return ["_No valid history sample._", ""] + lines = [ + "| Frame | Pixel | Format | Samples |", + "| --- | --- | --- | --- |", + ] + for group in groups[:maximum]: + lines.append( + f"| `{group.frame}` | `{group.x},{group.y}` | {_format_cell(group.format)} " + f"| `{len(group.samples)}` |" + ) + if len(groups) > maximum: + lines.append(f"_`{len(groups) - maximum}` more group(s) not shown._") + lines.append("") + return lines + + +def format_report(history: History, groups: Sequence[Group], selected: Group | None, + baseline_sample: Sample | None, baseline_raw: int, + baseline_supplied: bool, bmps: BmpSummary, + max_rows: int, requested_frame: int | None, + requested_pixel: tuple[int, int] | None) -> str: + lines: list[str] = [ + "# Startup scene-colour write report", + "", + f"- Tool: `scene_color_report` v`{TOOL_VERSION}`", + f"- Input: `X2W_DRAW_DUMP_DIR` (path omitted)", + f"- History: `{HISTORY_FILE}` version `1`", + "", + "## Selection", + "", + ] + + if selected is None: + if requested_frame is not None: + lines.append(f"- Requested frame: `{requested_frame}`") + if requested_pixel is not None: + lines.append(f"- Requested pixel: `{requested_pixel[0]},{requested_pixel[1]}`") + lines.extend(["- Selected sample group: _none_", ""]) + else: + lines.extend([ + f"- Frame: `{selected.frame}`", + f"- Pixel: `{selected.x},{selected.y}`", + f"- Format: {_format_cell(selected.format)}", + f"- Retained samples: `{len(selected.samples)}`", + "", + ]) + + if selected is None: + baseline_known = False + transition_count = 0 + first_change = None + last_writer = None + changed_flags: list[bool] = [] + else: + baseline_known = baseline_supplied or baseline_sample is not None + first_change = None + last_writer = None + transition_count = 0 + changed_flags = [] + previous = baseline_raw + for sample in selected.samples: + changed = sample.raw != previous + changed_flags.append(changed) + if changed: + transition_count += 1 + if first_change is None: + first_change = sample + last_writer = sample + previous = sample.raw + + primary, outcome = _classification(history, selected, baseline_known, baseline_raw, + transition_count) + lines.extend([ + "## Classification", + "", + f"- Classification: `{primary}` ({CLASS_LABELS[primary]})", + f"- Write outcome: `{outcome}` ({CLASS_LABELS[outcome]})", + ]) + if selected is not None: + if baseline_supplied: + baseline_text = f"`raw=0x{baseline_raw:08x}` (supplied)" + elif baseline_sample is not None: + baseline_text = (f"`draw={baseline_sample.draw}`, `frame={baseline_sample.frame}`, " + f"`raw=0x{baseline_sample.raw:08x}`") + elif selected.samples: + baseline_text = ("first retained sample; the pre-draw value is not recorded " + f"(`raw=0x{baseline_raw:08x}`)") + else: + baseline_text = "_none_" + lines.append(f"- Baseline: {baseline_text}") + + if selected.format not in RGBA8_FORMATS: + lines.append("- First observed change: _not evaluated (target is not RGBA8)_") + lines.append("- Last observed writer: _not evaluated (target is not RGBA8)_") + elif first_change is None: + if baseline_known: + lines.append("- First observed change: _none_") + else: + lines.append("- First observed change: _none among the retained samples; the first " + "sample is only a baseline_") + lines.append("- Last observed writer: _none_") + else: + lines.append( + f"- First observed change: `draw={first_change.draw}`, `key={first_change.key:016x}`, " + f"`raw=0x{first_change.raw:08x}`, {_rgba_cell(first_change.rgba)}" + ) + lines.append( + f"- Last observed writer: `draw={last_writer.draw}`, `key={last_writer.key:016x}`, " + f"`raw=0x{last_writer.raw:08x}`, {_rgba_cell(last_writer.rgba)}" + ) + if history.cap_reached: + lines.append("- History limit: the runtime cap or input bound was reached; later draws " + "may be missing from the conclusion above.") + lines.append("") + + lines.extend([ + "## Retained timeline", + "", + "Draw ordinals are the runtime copy ordinals (`draw=`), not title draw-call numbers.", + "", + ]) + + if selected is None or not selected.samples: + lines.extend(["_No retained sample for the selected frame and pixel._", ""]) + else: + must = [0, len(selected.samples) - 1] + if first_change is not None: + must.append(selected.samples.index(first_change)) + if last_writer is not None: + must.append(selected.samples.index(last_writer)) + indices, omitted = _choose_rows(len(selected.samples), max_rows, must) + lines.extend([ + "| # | Draw ordinal | Frame | Key | Count | Format | Raw | RGBA | Observation |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", + ]) + for index in indices: + sample = selected.samples[index] + observation = "" + if index == 0 and not baseline_known: + observation = "baseline; pre-draw value unknown" + if changed_flags[index]: + if sample is first_change and sample is last_writer: + observation = "first change; last writer" + elif sample is first_change: + observation = "first change" + elif sample is last_writer: + observation = "last writer" + else: + observation = "change" + lines.append( + f"| `{index + 1}` | `{sample.draw}` | `{sample.frame}` | {_key_cell(sample.key)} " + f"| `{sample.count}` | {_format_cell(sample.format)} | {_raw_cell(sample.raw)} " + f"| {_rgba_cell(sample.rgba)} | {observation} |" + ) + if omitted: + lines.append(f"_`{omitted}` timeline row(s) omitted from this bounded table._") + lines.append("") + + lines.extend([ + "## Input accounting", + "", + f"- Header declares: `{history.declared}` sample(s)", + f"- Physical records: `{history.physical_records}`", + f"- Valid samples: `{len(history.samples)}`", + f"- Malformed records ignored: `{history.malformed}`", + f"- Duplicate draw ordinals: `{history.duplicate_draws}`", + f"- RGBA/raw mismatches: `{history.rgba_mismatches}`", + f"- RGBA omitted on a supported format (decoded from raw): `{history.rgba_missing}`", + f"- RGBA ignored on a non-RGBA8 format: `{history.rgba_ignored}`", + ]) + if history.read_truncated: + lines.append("- Input read: stopped at the built-in byte or record bound") + if history.header_mismatch: + lines.append("- Header count and physical record count differ") + lines.append("") + + lines.extend([ + "## BMP cross-check", + "", + f"- BMP files: `{bmps.total}` (valid `{bmps.valid}`, invalid `{bmps.invalid}`)", + ]) + if bmps.dimensions: + dims = ", ".join(f"`{width}x{height}`" for width, height in bmps.dimensions) + lines.append(f"- Target dimensions: {dims}") + else: + lines.append("- Target dimensions: _not available_") + lines.extend([ + f"- Matching selected samples: `{bmps.matched}` matched, `{bmps.mismatched}` mismatched, " + f"`{bmps.out_of_range}` out of range, `{bmps.unreadable}` unreadable, `{bmps.skipped}` skipped", + ]) + for draw, expected, observed in bmps.mismatch_rows: + lines.append(f"- BMP mismatch at `draw={draw}`: history RGB `{expected}`, BMP RGB `{observed}`") + lines.extend([ + "- BMPs carry no frame field and the runtime writes either the full dump or the texel " + "history, not both; only a matching `draw`/`key`/`count` is compared.", + "", + "## Available groups", + "", + ]) + lines.extend(_render_group_table(groups)) + + lines.extend([ + "## Scope", + "", + "- Reads translated draws recorded for render target 0 only.", + "- Does not run the title, inspect shaders, or prove that a draw is a scene or UI draw.", + "- `ui_only` means draws were retained but no retained sample changed the selected " + "pixel; a scene draw that writes the same value cannot be excluded.", + "- `value_unchanged` means a change was observed but the final retained value equals the " + "baseline, including a write that restores the earlier value.", + "- The first retained sample has no pre-draw value. A write by that first draw is not " + "visible unless a baseline is supplied.", + "- The report says nothing about the presented image or about draws outside the dump window.", + "", + ]) + return "\n".join(lines) + + +def _parse_pixel(value: str) -> tuple[int, int]: + parts = value.split(",") + if len(parts) != 2 or not all(part.isdigit() for part in parts): + raise argparse.ArgumentTypeError("expected X,Y with non-negative decimal integers") + x, y = int(parts[0]), int(parts[1]) + if x > UINT32_MAX or y > UINT32_MAX: + raise argparse.ArgumentTypeError("pixel coordinate is out of range") + return x, y + + +def _parse_raw(value: str) -> int: + try: + raw = int(value, 0) + except ValueError as exc: + raise argparse.ArgumentTypeError("expected a 32-bit integer (for example 0x00000000)") from exc + if not 0 <= raw <= UINT32_MAX: + raise argparse.ArgumentTypeError("raw value is outside 0..0xffffffff") + return raw + + +def _parse_non_negative(value: str) -> int: + if not value.isdigit(): + raise argparse.ArgumentTypeError("expected a non-negative decimal integer") + return int(value) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="scene_color_report.py", + description="Summarize a per-draw texel history into a bounded Markdown report.", + ) + parser.add_argument("dump_dir", type=Path, help="X2W_DRAW_DUMP_DIR containing pixel_history.txt") + parser.add_argument("--frame", type=int, default=None, help="frame to select") + parser.add_argument("--pixel", type=_parse_pixel, default=None, help="pixel X,Y to select") + parser.add_argument("--baseline-raw", type=_parse_raw, default=None, + help="known pre-draw raw word for the selected format") + parser.add_argument("--max-rows", type=_parse_non_negative, default=DEFAULT_MAX_ROWS, + help=f"maximum timeline rows (default {DEFAULT_MAX_ROWS}, max {MAX_MAX_ROWS})") + args = parser.parse_args(argv) + + if args.max_rows < MIN_MAX_ROWS or args.max_rows > MAX_MAX_ROWS: + print(f"scene_color_report: --max-rows must be between {MIN_MAX_ROWS} and {MAX_MAX_ROWS}", + file=sys.stderr) + return 2 + dump_dir: Path = args.dump_dir + if not dump_dir.is_dir(): + print("scene_color_report: dump directory not found", file=sys.stderr) + return 2 + history_path = dump_dir / HISTORY_FILE + if not history_path.is_file(): + print("scene_color_report: pixel_history.txt not found in the dump directory", file=sys.stderr) + return 2 + + try: + history = parse_history(history_path) + except ReportError as exc: + print(f"scene_color_report: {exc}", file=sys.stderr) + return 2 + except OSError: + print("scene_color_report: pixel_history.txt is not readable", file=sys.stderr) + return 2 + + groups = build_groups(history.samples) + selected, matching_groups = select_group(groups, args.frame, args.pixel) + + if selected is not None: + if args.baseline_raw is not None: + baseline_raw = args.baseline_raw + baseline_sample = None + baseline_supplied = True + else: + baseline_sample = find_baseline(history.samples, selected) + if baseline_sample is not None: + baseline_raw = baseline_sample.raw + baseline_supplied = False + else: + baseline_raw = selected.samples[0].raw + baseline_supplied = False + else: + baseline_sample = None + baseline_raw = 0 + baseline_supplied = args.baseline_raw is not None + + bmps = scan_bmps(dump_dir, selected) + report = format_report( + history=history, + groups=groups, + selected=selected, + baseline_sample=baseline_sample, + baseline_raw=baseline_raw, + baseline_supplied=baseline_supplied, + bmps=bmps, + max_rows=args.max_rows, + requested_frame=args.frame, + requested_pixel=args.pixel, + ) + if selected is not None and matching_groups > 1: + report = report.replace( + "## Classification", + f"_`{matching_groups}` sample groups match the requested frame and pixel; the largest " + "one is shown._\n\n## Classification", + 1, + ) + try: + sys.stdout.reconfigure(encoding="utf-8") + except (AttributeError, OSError): + pass + print(report) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 2e49127a82..a1baf93941 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -3,16 +3,18 @@ usage: shader_cache_rekey.py <old cache dir> <new request dir> -The key of a graphics request (req_<key>.a), of an RTV variant (req_<key>.rtv) and of a device slot 67 compute -request (req_<key>.c67) hashes the translation revision string (pipeline_key and compute_key in gfx2hlsl.py). +Graphics (req_<key>.a), slot 67 compute (req_<key>.c67) and slot 57 mesh (req_<key>.m57) request keys hash their +translation revision strings (pipeline_key, compute_key and mesh57_key in gfx2hlsl.py). RTV variants +(req_<key>.rtv) hash text containing the graphics key. After a revision change the runtime asks for new keys, so a kept cache is cold again. This tool recomputes the key of every such request with the gfx2hlsl.py next to it and copies the request files under the new names into <new request dir>. `gfx2hlsl.py --pending <new request dir>` can then translate them without a running title. The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file that already exists in <new request dir> is left as it is. Each file is written to a temporary name and renamed; -the ready marker (.a, .c67) goes last, as the runtime writes it. Slot 57 and slot 86 mesh requests have their own -key strings and are only counted. +the ready marker (.a, .c67, .m57) goes last, as the runtime writes it. A stream description (.psin) is written +again under the new key with the same masks, since its line names the key and its masks are part of the key. +Slot 86 mesh requests are only counted. All requests are read before anything is written. When a request part is missing or unreadable, or an RTV variant is malformed, does not match its own name or names a base request that is not in the cache, the tool @@ -29,8 +31,9 @@ REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)') # Request files of each kind; the ready marker is last. -PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67')} -OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia +PARTS = {'g': ('.b', '.root', '.ia', '.psin', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67'), + 'm57': ('.ps57', '.root', '.m57')} +OPTIONAL = {'.ia', '.psin'} # a graphics request may have no input layout (.ia) and no stream description (.psin) class Incomplete(Exception): @@ -60,7 +63,14 @@ def current_key(job): except OSError as error: return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror) if kind == 'g': - return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None + # The pixel input masks of a stream description are part of the key; the description names its key. + try: + masks = g.read_ps_inputs(request_name(src, key, '.psin'), key) + except g.Unsupported as reason: + return kind, key, None, str(reason) + return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b''), masks), None + if kind == 'm57': + return kind, key, g.mesh57_key(p['.m57'], p['.ps57'], p['.root']), None return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None @@ -111,7 +121,8 @@ def rekey(src, dst, jobs=None, out=None): if os.path.exists(dst) and os.path.samefile(src, dst): print('error: the new request dir must not be the old cache', file=sys.stderr) return 2 - found = {'g': [], 'c': [], 'rtv': [], 'm57': 0, 'm86': 0} + found = {kind: [] for kind in (*PARTS, 'rtv')} + m86 = 0 try: entries = sorted(os.listdir(src)) except OSError as error: @@ -122,12 +133,12 @@ def rekey(src, dst, jobs=None, out=None): if not m: continue key, ext = int(m.group(1), 16), m.group(2) - if ext in ('m57', 'm86'): - found[ext] += 1 + if ext == 'm86': + m86 += 1 else: - found[{'a': 'g', 'c67': 'c', 'rtv': 'rtv'}[ext]].append(key) + found[{'a': 'g', 'c67': 'c'}.get(ext, ext)].append(key) - work = [(src, kind, key) for kind in ('g', 'c') for key in found[kind]] + work = [(src, kind, key) for kind in PARTS for key in found[kind]] jobs = min(jobs or g.translation_jobs(), len(work)) if jobs < 2: results = [current_key(job) for job in work] @@ -136,7 +147,7 @@ def rekey(src, dst, jobs=None, out=None): with ProcessPoolExecutor(max_workers=jobs) as pool: results = list(pool.map(current_key, work, chunksize=max(1, len(work) // (jobs * 4)))) - new = {'g': {}, 'c': {}} + new = {kind: {} for kind in PARTS} bad = [] for kind, old, key, reason in results: if reason: @@ -165,7 +176,7 @@ def rekey(src, dst, jobs=None, out=None): return 1 stats = {'written': 0, 'kept': 0} try: - for kind, label in (('g', 'graphics'), ('c', 'compute')): + for kind, label in (('g', 'graphics'), ('c', 'compute'), ('m57', 'm57')): done = set() for old, key in sorted(new[kind].items()): if key in done: # requests of the same pipeline from several revisions @@ -173,6 +184,9 @@ def rekey(src, dst, jobs=None, out=None): done.add(key) # Read again, not checked against the hashing pass: nothing may write the old cache meanwhile. for ext, data in read_parts(src, kind, old).items(): + if ext == '.psin': # the line names the new key + data = ('psin1 %016x ena=0x%04x addr=0x%04x\n' % ( + key, *g.read_ps_inputs(request_name(src, old, '.psin'), old))).encode('ascii') publish(request_name(dst, key, ext), data, stats) current = sum(old == key for old, key in new[kind].items()) print('%s: %d requests, %d already current -> %d keys' % (label, len(new[kind]), current, len(done)), file=out) @@ -182,7 +196,7 @@ def rekey(src, dst, jobs=None, out=None): print('error: failed writing %s: %s' % (dst, error), file=sys.stderr) return 1 print('rtv variants: %d requests -> %d keys' % (len(found['rtv']), len(rtv)), file=out) - print('not re-keyed (own key strings): m57 %d, m86 %d' % (found['m57'], found['m86']), file=out) + print('not re-keyed (own key strings): m86 %d' % m86, file=out) print('files: %d written, %d already present in %s' % (stats['written'], stats['kept'], dst), file=out) return 0 diff --git a/tools/startup/shader_cache_revision.py b/tools/startup/shader_cache_revision.py new file mode 100644 index 0000000000..5886e6f88d --- /dev/null +++ b/tools/startup/shader_cache_revision.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Warn when a shader cache and the translator about to read it come from different revisions (#2815). + +usage: shader_cache_revision.py <cache dir> [--translator <gfx2hlsl.py>] + shader_cache_revision.py <cache dir> --fresh + +Request keys start with a revision string on both sides: the runtime's (src/startup_stubs/d3d12_draw.inl) and +the translator's (pipeline_key, compute_key and mesh57_key in gfx2hlsl.py). Before its first request a process +writes its revisions to <cache dir>/revision.txt, one `<kind> <revision>` line each (graphics, compute, mesh57). +This tool compares that file with the revision literals of the translator (default: the gfx2hlsl.py next to +it). When they differ, every cached request is refused as a key mismatch and nothing says why, so it prints +one warning line on stdout with both revisions and the two fixes, and exits with 1. A cache that holds +requests (req_*) but no revision.txt comes from a runtime older than this check and gets the same warning. +A cache with no requests, or whose revisions match, prints nothing and exits with 0. + +--fresh moves a cache folder that is not empty aside to <cache dir>.old-<date>-<time> and prints where it went +(exit 0), so the run starts with an empty cache. Usage errors exit with 2. The launchers (run.ps1, run.sh) +print the line as their own warning: only stdout is written, so Windows PowerShell does not take the output +for an error. +""" +import datetime +import os +import re +import sys + +REVISION_FILE = 'revision.txt' +KINDS = ('graphics', 'compute', 'mesh57') +# The literals the translator hashes first: b'x2w-startup-shader-<n>' (graphics), the same with 'cs' (compute) +# and b'x2w-startup-mesh-57-<n>' (slot 57 mesh). +LITERALS = { + 'graphics': re.compile(rb"b'(x2w-startup-shader-[0-9]+)'"), + 'compute': re.compile(rb"b'(x2w-startup-shader-[0-9]+cs)'"), + 'mesh57': re.compile(rb"b'(x2w-startup-mesh-57-[0-9]+)'"), +} +FIXES = ('Fix: rebuild the stand-ins from this checkout, or start with an empty shader cache ' + '(run.ps1 -FreshShaderCache, run.sh --fresh-shader-cache, or another cache folder).') + + +def translator_revisions(path): + """{kind: revision} from the translator's source; a kind whose literal is missing or not unique is left out.""" + with open(path, 'rb') as f: + text = f.read() + found = {} + for kind, pattern in LITERALS.items(): + values = set(pattern.findall(text)) + if len(values) == 1: + found[kind] = values.pop().decode('ascii') + return found + + +def cache_revisions(cache): + """{kind: revision} from <cache>/revision.txt, or None when the file does not exist.""" + try: + with open(os.path.join(cache, REVISION_FILE), 'rb') as f: + text = f.read().decode('ascii', 'replace') + except FileNotFoundError: + return None + found = {} + for line in text.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[0] in KINDS: + found[parts[0]] = parts[1] + return found + + +def has_requests(cache): + try: + return any(name.startswith('req_') for name in os.listdir(cache)) + except FileNotFoundError: + return False + + +def spell(revisions): + return ', '.join('%s %s' % (kind, revisions[kind]) for kind in KINDS if kind in revisions) or 'none readable' + + +def warning(cache, translator): + """The warning line, or None when the cache and the translator agree (or the cache holds nothing to refuse).""" + cached = cache_revisions(cache) + if cached is None and not has_requests(cache): + return None + ours = translator_revisions(translator) + if cached is None: + return ('shader cache %s holds requests but no %s, so their revision is unknown: requests of a stand-in ' + 'build older than this check (or written by archive_requests.py or shader_cache_rekey.py) may be ' + 'keyed for another revision than the translator %s (%s). %s' + % (cache, REVISION_FILE, translator, spell(ours), FIXES)) + shared = [kind for kind in KINDS if kind in cached and kind in ours] + if shared and all(cached[kind] == ours[kind] for kind in shared): + return None + return ('shader cache %s was written by stand-ins of revision %s, but the translator %s is revision %s: ' + 'every cached request will be refused as a key mismatch. %s' + % (cache, spell(cached), translator, spell(ours), FIXES)) + + +def move_aside(cache, now=None): + """Rename a cache folder that is not empty to <cache>.old-<date>-<time>; return the new path or None.""" + try: + if not os.listdir(cache): + return None + except FileNotFoundError: + return None + stamp = (now or datetime.datetime.now()).strftime('%Y%m%d-%H%M%S') + target = '%s.old-%s' % (os.path.normpath(cache), stamp) + os.rename(cache, target) + return target + + +def main(argv): + args = list(argv) + fresh = '--fresh' in args + if fresh: + args.remove('--fresh') + translator = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'gfx2hlsl.py') + if '--translator' in args: + at = args.index('--translator') + if at + 1 >= len(args): + print(__doc__.split('\n\n')[1]) + return 2 + translator = args.pop(at + 1) + args.pop(at) + if len(args) != 1 or args[0].startswith('-') or (fresh and '--translator' in argv): + print(__doc__.split('\n\n')[1]) + return 2 + cache = args[0] + if fresh: + moved = move_aside(cache) + if moved: + print('moved the old shader cache %s to %s' % (cache, moved)) + return 0 + try: + line = warning(cache, translator) + except OSError as error: + print('cannot compare the shader cache %s with the translator %s: %s' % (cache, translator, error)) + return 1 + if line: + print(line) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/tools/startup/stage_package.ps1 b/tools/startup/stage_package.ps1 index 422b6e7db5..e9105bea6c 100644 --- a/tools/startup/stage_package.ps1 +++ b/tools/startup/stage_package.ps1 @@ -13,7 +13,7 @@ param( ) $ErrorActionPreference = "Stop" -$package = (Resolve-Path -LiteralPath $PackageDir).Path.TrimEnd('\') +$package = (Resolve-Path -LiteralPath $PackageDir).Path $source = if ([IO.Path]::IsPathRooted($Exe)) { (Resolve-Path -LiteralPath $Exe).Path } else { @@ -23,7 +23,7 @@ $sourceDir = Split-Path -Parent $source $provider = $null $drive = $null $run = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath( - $RunDir, [ref]$provider, [ref]$drive).TrimEnd('\') + $RunDir, [ref]$provider, [ref]$drive) if ($provider.Name -ne 'FileSystem') { throw "RunDir must be a filesystem path." } if (-not (Test-Path -LiteralPath $source -PathType Leaf) -or [IO.Path]::GetExtension($source) -ine '.exe') { throw "Exe must name an executable file." @@ -34,6 +34,52 @@ function Test-PathInside([string]$Path, [string]$Parent) { return $Path.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase) } +# Resolve drive aliases and junctions before comparing package and staging paths. +# A destination may not exist yet, so resolve its nearest existing ancestor and +# append the remaining names without creating anything. +if (-not ("X2wStagingFinalPath" -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using Microsoft.Win32.SafeHandles; + +public static class X2wStagingFinalPath { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr security, + uint creation, uint flags, IntPtr template); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, + uint length, uint flags); + public static string Resolve(string name) { + using (var handle = CreateFileW(name, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) { + if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); + var path = new StringBuilder(32768); + uint length = GetFinalPathNameByHandleW(handle, path, (uint)path.Capacity, 0); + if (length == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); + if (length >= path.Capacity) throw new InvalidOperationException("Resolved path is too long."); + return path.ToString(); + } + } +} +'@ +} +function Get-FinalStagingPath([string]$Path) { + $missing = [System.Collections.Generic.List[string]]::new() + $existing = $Path + while (-not (Test-Path -LiteralPath $existing)) { + $parent = Split-Path -Parent $existing + if (-not $parent -or $parent -eq $existing) { throw "Cannot resolve staging path." } + $missing.Insert(0, (Split-Path -Leaf $existing)) + $existing = $parent + } + $nativePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($existing) + $final = [X2wStagingFinalPath]::Resolve($nativePath) + foreach ($part in $missing) { $final = [IO.Path]::Combine($final, $part) } + return $final +} + if (-not (Test-PathInside $source $package)) { throw "Exe must be inside PackageDir." } @@ -49,6 +95,14 @@ for ($ancestor = $run; $ancestor; $ancestor = Split-Path -Parent $ancestor) { throw "RunDir must not pass through a reparse point." } } +$packageFinal = Get-FinalStagingPath $package +$runFinal = Get-FinalStagingPath $run +$sourceFinal = Get-FinalStagingPath $source +if (-not (Test-PathInside $sourceFinal $packageFinal)) { throw "Exe must be inside PackageDir." } +if ($runFinal.Equals($packageFinal, [StringComparison]::OrdinalIgnoreCase) -or + (Test-PathInside $runFinal $packageFinal) -or (Test-PathInside $packageFinal $runFinal)) { + throw "RunDir must be separate from PackageDir and its parent directories." +} if ((Test-Path -LiteralPath $run) -and (-not (Test-Path -LiteralPath $run -PathType Container) -or @(Get-ChildItem -LiteralPath $run -Force).Count)) { diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index fee383915f..d516728e8d 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -44,8 +44,15 @@ "unsupported_description", "destination_outside_view_heaps", "gpu_written_resource", + # the acceleration-structure holds of publish_as_srv (memory_srv_as.h, as_srv_refusal_name) + "as_unaligned", + "as_not_placed", + "as_wrong_state", "buffer_unavailable", "texture_unavailable", + "texture_no_resource", + "texture_unreadable", + "texture_over_64mib", # the partial-tile holds of device_memory_srv "partial_tile_xg_rows", "partial_tile_beyond_xg_size", @@ -85,6 +92,10 @@ rf"\+(?P<retained>{BUDGET_DECIMAL})/(?P<objects>{BUDGET_DECIMAL})" + "".join(rf" {name}={BUDGET_CATEGORY}" for name in ("buffer", "upload", "readback", "heap")) + rf" unmeasured={BUDGET_DECIMAL}" + # Added with the system commit and pool counters (absent in older logs): commit=<used>/<limit> avail=<free> in MiB. + + rf"(?: commit=(?:{BUDGET_DECIMAL}/{BUDGET_DECIMAL}|n/a) avail=(?:{BUDGET_DECIMAL}|n/a)" + + rf" sections=(?:{BUDGET_DECIMAL}|n/a) slabs=(?:{BUDGET_DECIMAL}|n/a) slots=(?:{BUDGET_DECIMAL}/{BUDGET_DECIMAL}|n/a)" + + rf" job_peak=(?:{BUDGET_DECIMAL}|n/a) job_limit=(?:{BUDGET_DECIMAL}|none|n/a))?" ) OTHER = "other (text omitted)" RE_DEC = re.compile(r"[0-9]{1,10}\Z") @@ -94,6 +105,29 @@ RE_OPENFILE_FAIL = re.compile(r"fail(?: \(err (\d{1,10})\))?\Z") MNEMONIC_FAMILY = r"(v|s|ds|buffer|tbuffer|image|flat|global|scratch|exp|lds)_[a-z0-9_]{1,40}" SHADER_REASONS: list[tuple[re.Pattern[str], str]] = [ + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unsupported instruction " + MNEMONIC_FAMILY + r"\b"), + r"\1_* instruction"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unsupported opcode\b"), "unsupported opcode"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unsupported pixel entry VGPR\b"), "unsupported pixel entry VGPR"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unproven resource descriptor\b"), "unproven resource descriptor"), + (re.compile(r"native compute \+0x[0-9a-fA-F]+: unbound numeric SGPR\b"), "unbound numeric SGPR"), + (re.compile(r"(?:unknown gfx1013 instruction format|truncated or misaligned gfx1013 instruction|" + r"reserved FLAT segment) at byte \d+\Z"), "undecodable word"), + # The fixed reasons of format_compute_runtime_manifest (src/direct_compute_cache.cpp); kind names are enum names. + (re.compile(r"unsupported startup runtime manifest bindings: (" + r"(?:SRV|UAV) kind [a-z0-9_]{1,32}(?: [a-z0-9-]{1,20})?(?: array)?|" + r"(?:SRV|UAV) registers not contiguous|group size has a zero dimension|" + r"root constants above root parameter 15|view above root parameter 15|" + r"more than (?:8 root constants in one root parameter|32 user data words|32 SRVs|8 UAVs)|" + r"resource heap view|sampler heap|comparison sampler|" + r"stride words from a view that is not one raw vector SRV)\Z"), r"runtime manifest: \1"), + (re.compile(r"graphics request key mismatch\b"), "graphics request key mismatch"), + (re.compile(r"compute request key mismatch\b"), "compute request key mismatch"), + (re.compile(r"stale pixel input description\b"), "stale pixel input description"), + (re.compile(r"pixel input description names another pipeline\Z"), "pixel input description names another pipeline"), + (re.compile(r"contradictory pixel input enable/address masks\Z"), "contradictory pixel input enable/address masks"), + (re.compile(r"pixel input (?:enable|address) mask missing\b"), "invalid pixel input description"), + (re.compile(r"invalid pixel input description\Z"), "invalid pixel input description"), (re.compile(r"(image_load_mip) (tfe|a16)\Z"), r"\1 \2"), (re.compile(r"buffer_load_format_(?:x|xy|xyz|xyzw) requires descriptor FORMAT and DST_SEL\Z"), "buffer_* instruction"), @@ -833,6 +867,20 @@ def _line_stream() -> Iterable[str]: ) +def _validate_args(args: argparse.Namespace) -> None: + if not args.logdir.exists(): + raise FileNotFoundError(f"log path not found: {args.logdir}") + if not (args.logdir.is_file() or args.logdir.is_dir()): + raise ValueError(f"log path must be a regular file or directory: {args.logdir}") + if args.shader_cache is not None: + if not args.shader_cache.exists(): + raise FileNotFoundError(f"shader cache directory not found: {args.shader_cache}") + if not args.shader_cache.is_dir(): + raise NotADirectoryError(f"shader cache path is not a directory: {args.shader_cache}") + if args.max_items < 1: + raise ValueError(f"--max-items must be at least 1, got {args.max_items}") + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( description="Summarize startup logs and optional shader cache into allowlisted Markdown." @@ -851,9 +899,15 @@ def main(argv: list[str] | None = None) -> int: help="Maximum rows per summary table (default: 16)", ) args = parser.parse_args(argv) - print(triage_run(args.logdir, shader_cache=args.shader_cache, max_items=args.max_items)) + try: + _validate_args(args) + report = triage_run(args.logdir, shader_cache=args.shader_cache, max_items=args.max_items) + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(report) return 0 if __name__ == "__main__": - sys.exit(main()) + raise SystemExit(main()) diff --git a/tools/startup/ui_regression_matrix.py b/tools/startup/ui_regression_matrix.py new file mode 100644 index 0000000000..8c85d21cf4 --- /dev/null +++ b/tools/startup/ui_regression_matrix.py @@ -0,0 +1,435 @@ +#!/usr/bin/env python3 +"""Run the startup UI CTest fixtures and write a Markdown/JSON regression matrix. + +The default selection covers the sampler/BC7 fixes from #3153, the XG mip-0 and +CopyTextureRegion paths from #3141, and the indexed rectangle fixture from #3142. +Only tests registered in the supplied build are run. A test process that exits +with 77 is reported by CTest as skipped when its CTest property says so; this +tool keeps that state separate from both pass and fail. +""" + +from __future__ import annotations + +import argparse +import datetime as datetime_module +import json +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import xml.etree.ElementTree as ET + + +DEFAULT_FILTER = ( + r"^(startup_sampler_heap_wrapped|startup_xg_bc7_draw|startup_rect_gap|" + r"startup_ui_texture_bands)_(warp|hardware)$" +) +ADAPTERS = ("warp", "hardware") +PASS = "pass" +SKIP = "skip" +FAIL = "fail" + +EXIT_OK = 0 +EXIT_FAILED = 1 +EXIT_USAGE = 2 +EXIT_INCOMPLETE = 3 + + +class MatrixError(Exception): + """A setup or selection error that prevents a trustworthy matrix.""" + + +def _ctest_command(value: str) -> list[str]: + """Resolve --ctest to a command; a .py fixture runs under this interpreter.""" + value = value.strip() + if not value: + raise MatrixError("--ctest must not be empty") + candidate = Path(value).expanduser() + if candidate.is_file(): + path = candidate.resolve() + if path.suffix.lower() == ".py": + return [sys.executable, "-B", str(path)] + return [str(path)] + found = shutil.which(value) + if found: + return [found] + raise MatrixError(f"CTest executable not found: {value}") + + +def _run(command: list[str], build_dir: Path) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run( + command, + cwd=build_dir, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except OSError as error: + raise MatrixError(f"cannot run {command[0]!r}: {error}") from error + + +def _diagnostic(proc: subprocess.CompletedProcess[str]) -> str: + text = (proc.stderr or "").strip() or (proc.stdout or "").strip() + if not text: + return f"exit code {proc.returncode}" + tail = text.splitlines()[-8:] + return "\n".join(tail)[:2000] + + +def selected_test_names(ctest: list[str], build_dir: Path, pattern: str) -> list[str]: + """Return the CTest names matching pattern, in CTest's reported order.""" + proc = _run([*ctest, "--show-only=json-v1", "-R", pattern], build_dir) + if proc.returncode != 0: + raise MatrixError(f"CTest could not list tests (exit {proc.returncode}):\n{_diagnostic(proc)}") + text = proc.stdout.lstrip("\ufeff \r\n\t") + start = text.find("{") + if start < 0: + raise MatrixError("CTest --show-only=json-v1 did not return JSON:\n" + text[-2000:]) + try: + listing = json.loads(text[start:]) + except json.JSONDecodeError as error: + raise MatrixError(f"invalid CTest JSON listing: {error}") from error + tests = listing.get("tests") if isinstance(listing, dict) else None + if not isinstance(tests, list): + raise MatrixError("CTest JSON listing has no tests array") + names = [] + seen = set() + for test in tests: + name = test.get("name") if isinstance(test, dict) else None + if not isinstance(name, str) or not name.strip(): + raise MatrixError("CTest JSON listing contains a test without a name") + if name not in seen: + seen.add(name) + names.append(name) + return names + + +def adapter_of(name: str) -> str | None: + for adapter in ADAPTERS: + if name.endswith("_" + adapter): + return adapter + return None + + +def _exact_filter(names: list[str]) -> str: + return "^(" + "|".join(re.escape(name) for name in names) + ")$" + + +def _node_detail(case: ET.Element) -> str: + for tag in ("failure", "error", "skipped"): + node = case.find(tag) + if node is None: + continue + pieces = [] + message = (node.get("message") or "").strip() + if message: + pieces.append(message) + text = (node.text or "").strip() + if text and text != message: + pieces.append(text) + return "\n".join(pieces)[:4000] + return "" + + +def _duration(case: ET.Element) -> float | None: + try: + value = float(case.get("time", "")) + except (TypeError, ValueError): + return None + return value if value >= 0 else None + + +def _case_status(case: ET.Element) -> tuple[str, str]: + """Classify a CTest JUnit case without treating an unknown state as a pass.""" + status = case.get("status", "") + if case.find("failure") is not None or case.find("error") is not None: + return FAIL, _node_detail(case) or "CTest reported a failure" + detail = _node_detail(case) + if status == "notrun": + # CTest also uses notrun for a missing executable, a missing configuration or a + # disabled test. Only the explicit capability markers are skips; the rest failed + # before the fixture could measure anything. + if detail.startswith(("SKIP_RETURN_CODE", "SKIP_REGULAR_EXPRESSION")): + return SKIP, detail + return FAIL, detail or "CTest marked the test not run" + if case.find("skipped") is not None: + return SKIP, detail or "CTest reported a skip" + if status == "run": + return PASS, "" + return FAIL, f"unrecognized CTest result status {status!r}" + + +def read_junit(junit: Path) -> list[dict[str, object]]: + try: + root = ET.parse(junit).getroot() + except (ET.ParseError, OSError) as error: + raise MatrixError(f"cannot read CTest JUnit report {junit}: {error}") from error + if root.tag != "testsuite": + raise MatrixError(f"expected a single CTest <testsuite> root, found <{root.tag}>") + results = [] + for case in root.iter("testcase"): + name = (case.get("name") or "").strip() + if not name: + raise MatrixError("CTest JUnit contains a testcase without a name") + status, detail = _case_status(case) + results.append({ + "name": name, + "adapter": adapter_of(name), + "status": status, + "duration_seconds": _duration(case), + "detail": detail, + }) + return results + + +def run_tests( + ctest: list[str], build_dir: Path, names: list[str] +) -> tuple[list[dict[str, object]], int, list[str]]: + """Run exactly names and return results, CTest exit status and its command.""" + exact = _exact_filter(names) + with tempfile.TemporaryDirectory(prefix="x2w-ui-matrix-") as temporary: + junit = Path(temporary) / "ctest-junit.xml" + command = [ + *ctest, + "--output-junit", + str(junit), + "--output-on-failure", + "--no-tests=error", + "-R", + exact, + ] + proc = _run(command, build_dir) + if not junit.is_file(): + if "No tests were found" in (proc.stdout or "") + (proc.stderr or ""): + raise MatrixError("CTest selected no tests") + raise MatrixError( + f"CTest did not write a JUnit report (exit {proc.returncode}):\n{_diagnostic(proc)}" + ) + results = read_junit(junit) + by_name = {str(item["name"]): item for item in results} + missing = [name for name in names if name not in by_name] + if missing: + raise MatrixError("CTest did not report: " + ", ".join(missing)) + if not results: + raise MatrixError("CTest selected no tests") + # Keep exactly the selected order; a concurrent registration cannot inject a row. + ordered = [by_name[name] for name in names] + return ordered, proc.returncode, command + + +def _source_commit() -> str | None: + root = Path(__file__).resolve().parents[2] + try: + proc = subprocess.run( + ["git", "-C", str(root), "rev-parse", "HEAD"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except OSError: + return None + value = proc.stdout.strip() + return value if proc.returncode == 0 and re.fullmatch(r"[0-9a-f]{40,64}", value) else None + + +def summarize(results: list[dict[str, object]]) -> dict[str, int]: + return { + "selected": len(results), + "passed": sum(item["status"] == PASS for item in results), + "skipped": sum(item["status"] == SKIP for item in results), + "failed": sum(item["status"] == FAIL for item in results), + } + + +def _display_path(path: Path) -> str: + try: + return str(path.resolve()) + except OSError: + return str(path) + + +def _md_code(value: str) -> str: + return "`" + value.replace("`", "'") + "`" + + +def _short_detail(value: object, limit: int = 260) -> str: + text = " ".join(str(value or "").split()) + if len(text) > limit: + text = text[:limit - 3].rstrip() + "..." + return text.replace("|", "\\|") + + +def markdown_report( + build_dir: Path, + selection: str, + adapter: str, + ctest_returncode: int, + results: list[dict[str, object]], + summary: dict[str, int], +) -> str: + lines = [ + "# Startup UI regression matrix", + "", + f"- Build directory: {_md_code(_display_path(build_dir))}", + f"- Selection: {_md_code(selection)}", + f"- Adapter: {_md_code(adapter)}", + f"- CTest exit code: {ctest_returncode}", + f"- Result: {summary['passed']} passed, {summary['skipped']} skipped, " + f"{summary['failed']} failed ({summary['selected']} selected)", + "", + "| Test | Result | Time | Detail |", + "| --- | --- | ---: | --- |", + ] + for item in results: + status = str(item["status"]).upper() + duration = item["duration_seconds"] + when = f"{duration:.3f} s" if isinstance(duration, float) else "-" + lines.append( + f"| {_md_code(str(item['name']))} | {status} | {when} | " + f"{_short_detail(item['detail'])} |" + ) + lines += [ + "", + "A skipped fixture did not complete its measurement. It is not a pass; " + "its capability or environment requirement has to be satisfied before " + "that row can support a result.", + "", + ] + return "\n".join(lines) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Run selected startup UI CTest fixtures and write pass/skip/fail " + "Markdown and JSON matrices. Empty selections are errors." + ) + ) + parser.add_argument( + "--build-dir", + type=Path, + default=Path("out/build/dev"), + help="CMake build directory (default: out/build/dev)", + ) + parser.add_argument( + "--ctest", + default="ctest", + help="CTest executable, or a Python fixture script (default: ctest)", + ) + parser.add_argument( + "--adapter", + choices=("all",) + ADAPTERS, + default="all", + help="restrict rows to tests ending _warp or _hardware (default: all)", + ) + parser.add_argument("--json", type=Path, help="write the matrix as JSON") + parser.add_argument("--output", type=Path, help="write the matrix as Markdown") + parser.add_argument( + "--filter", + dest="filter_option", + help="CTest name regex; default is the sampler/BC7/rect/bands matrix", + ) + parser.add_argument( + "positional_filter", + nargs="?", + metavar="FILTER", + help="CTest name regex (alternative to --filter)", + ) + return parser + + +def _write(path: Path, content: str) -> None: + path = path.expanduser() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + if args.filter_option is not None and args.positional_filter is not None: + parser.error("give the filter either positionally or with --filter, not both") + selection = args.filter_option if args.filter_option is not None else args.positional_filter + if selection is None: + selection = DEFAULT_FILTER + if not selection.strip(): + parser.error("the filter must not be empty") + + build_dir = args.build_dir.expanduser().resolve() + if not build_dir.is_dir(): + parser.error(f"build directory does not exist: {build_dir}") + try: + ctest = _ctest_command(args.ctest) + except MatrixError as error: + parser.error(str(error)) + + try: + names = selected_test_names(ctest, build_dir, selection) + if args.adapter != "all": + names = [name for name in names if adapter_of(name) == args.adapter] + if not names: + raise MatrixError( + f"no CTest tests matched the selection for adapter {args.adapter!r}: {selection}" + ) + results, ctest_returncode, command = run_tests(ctest, build_dir, names) + except MatrixError as error: + print(f"ui_regression_matrix: error: {error}", file=sys.stderr) + return EXIT_USAGE + + summary = summarize(results) + unexplained_failure = ctest_returncode != 0 and summary["failed"] == 0 + markdown = markdown_report(build_dir, selection, args.adapter, ctest_returncode, results, summary) + payload = { + "schema": "xbox2windows-startup-ui-regression-matrix-v1", + "generated_at": datetime_module.datetime.now( + datetime_module.timezone.utc + ).isoformat(timespec="seconds"), + "source_commit": _source_commit(), + "build_dir": _display_path(build_dir), + "ctest": args.ctest, + "ctest_command": command, + "ctest_returncode": ctest_returncode, + "selection": selection, + "adapter": args.adapter, + "tests": results, + "summary": summary, + } + + if args.output: + _write(args.output, markdown) + print(f"ui_regression_matrix: wrote {args.output}") + else: + print(markdown) + if args.json: + _write(args.json, json.dumps(payload, indent=2) + "\n") + print(f"ui_regression_matrix: wrote {args.json}") + print( + "ui_regression_matrix: " + f"{summary['passed']} passed, {summary['skipped']} skipped, " + f"{summary['failed']} failed ({summary['selected']} selected)" + ) + + if summary["failed"] or unexplained_failure: + if unexplained_failure: + print( + "ui_regression_matrix: CTest exited with " + f"{ctest_returncode} without a failed test result", + file=sys.stderr, + ) + return EXIT_FAILED + if summary["skipped"]: + return EXIT_INCOMPLETE + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/window_capture.py b/tools/startup/window_capture.py new file mode 100644 index 0000000000..17f9971c0d --- /dev/null +++ b/tools/startup/window_capture.py @@ -0,0 +1,96 @@ +"""Periodic window pictures of a startup run (docs/startup-runtime.md, "Window captures"). + +debug_launch.py grabs the client area of the title's window as raw 32-bit BGRA rows. This module is the part +that needs no Windows API: the fast BGRA -> PNG conversion, the file names, the skip of a frame that equals +the previous one, the file cap and the one summary line. tests/startup_window_capture_check.py covers it. + +PNG: ISO/IEC 15948 (W3C PNG Specification, Second Edition), truecolour 8 bit, filter type 0 on every row. +""" +import hashlib +import os +import struct +import zlib + +FILE_CAP = 120 # periodic files per run; window.png at the end is not counted +PNG_SIGNATURE = bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) + + +def _chunk(kind, payload): + body = kind + payload + return struct.pack(">I", len(payload)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) + + +def png_bytes(width, height, bgra, level=6): + """PNG of width x height BGRA pixels (the alpha byte is dropped). Whole-buffer slice copies, no per-byte loop.""" + if width <= 0 or height <= 0 or len(bgra) != width * height * 4: + raise ValueError("pixel buffer does not match %dx%d" % (width, height)) + rgb = bytearray(width * height * 3) + rgb[0::3], rgb[1::3], rgb[2::3] = bgra[2::4], bgra[1::4], bgra[0::4] + line = width * 3 + rows = bytearray((1 + line) * height) # each row starts with its filter byte (0 = none) + for y in range(height): + rows[y * (1 + line) + 1:(y + 1) * (1 + line)] = rgb[y * line:(y + 1) * line] + return (PNG_SIGNATURE + _chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + _chunk(b"IDAT", zlib.compress(bytes(rows), level)) + _chunk(b"IEND", b"")) + + +def frame_name(seconds): + """window_<sss>s.png: whole seconds since the process started, at least three digits.""" + return "window_%03ds.png" % int(seconds) + + +def frame_hash(width, height, bgra): + return hashlib.blake2b(bgra, digest_size=16, key=struct.pack("<II", width, height)).digest() + + +class Series: + """The periodic frames of one run. Frames are offered in time order; one is saved when its pixels differ from + the previous frame (an unchanged screen costs no file and no PNG conversion), until the file cap is reached.""" + + def __init__(self, logdir, cap=FILE_CAP, level=1, write=None): + self.logdir, self.cap, self.level = logdir, cap, level + self._write = write or self._write_file + self._last = None + self.saved = self.unchanged = self.missed = self.dropped = 0 + self.first_change = None # seconds of the first saved frame after the baseline + self.names = [] + + @staticmethod + def _write_file(path, data): + with open(path, "wb") as handle: + handle.write(data) + + @property + def full(self): + return self.saved >= self.cap + + def miss(self): + """A tick with no usable window (none visible yet, empty client area, capture error).""" + self.missed += 1 + + def offer(self, seconds, width, height, bgra): + """Returns "saved", "unchanged" or "capped".""" + digest = frame_hash(width, height, bgra) + if digest == self._last: + self.unchanged += 1 + return "unchanged" + if self.full: + self.dropped += 1 + return "capped" + name = frame_name(seconds) + self._write(os.path.join(self.logdir, name), png_bytes(width, height, bgra, self.level)) + if self.saved and self.first_change is None: + self.first_change = int(seconds) + self._last = digest + self.saved += 1 + self.names.append(name) + return "saved" + + def summary(self): + text = "window captures: %d saved, %d unchanged skipped, " % (self.saved, self.unchanged) + text += "first change at %d s" % self.first_change if self.first_change is not None else "no change seen" + if self.dropped: + text += ", file cap %d reached (%d changed frames dropped)" % (self.cap, self.dropped) + if self.missed: + text += ", %d ticks without a window" % self.missed + return text diff --git a/tools/texture_blocks.py b/tools/texture_blocks.py index 48529ede0e..c23890badf 100644 --- a/tools/texture_blocks.py +++ b/tools/texture_blocks.py @@ -33,7 +33,7 @@ def block_extent(self) -> tuple[int, int, int]: "BC1_UNORM": Format("BC1_UNORM", 71, 4, 4, 1, 8, 2), "BC2_UNORM": Format("BC2_UNORM", 74, 4, 4, 1, 16, 2), "BC3_UNORM": Format("BC3_UNORM", 77, 4, 4, 1, 16, 2), - "BC4_UNORM": Format("BC4_UNORM", 79, 4, 4, 1, 8, 2), + "BC4_UNORM": Format("BC4_UNORM", 80, 4, 4, 1, 8, 2), "BC5_UNORM": Format("BC5_UNORM", 83, 4, 4, 1, 16, 2), "BC6H_UF16": Format("BC6H_UF16", 95, 4, 4, 1, 16, 2), "BC7_UNORM": Format("BC7_UNORM", 98, 4, 4, 1, 16, 2), @@ -42,13 +42,20 @@ def block_extent(self) -> tuple[int, int, int]: def format_info(name: str) -> Format: - try: - return FORMATS[name] - except KeyError: - raise ValueError(f"Unknown texture format {name!r}") from None + if not isinstance(name, str) or name not in FORMATS: + raise ValueError(f"Unknown texture format {name!r}") + return FORMATS[name] + + +def _require_int(value, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"Expected integer {name}, got {type(value).__name__}") + return value def _grid(width: int, height: int, format: Format) -> tuple[int, int]: + width = _require_int(width, "width") + height = _require_int(height, "height") if width <= 0 or height <= 0: raise ValueError("Expected positive pixel dimensions") return ((width + format.block_width - 1) // format.block_width, @@ -75,7 +82,7 @@ def surface_bytes(width: int, height: int, format_name: str, *, pitch_blocks: in """Bytes in one block-row surface, including any row pitch padding.""" format = _two_dimensional(format_name) columns, rows = _grid(width, height, format) - pitch = columns if pitch_blocks is None else pitch_blocks + pitch = columns if pitch_blocks is None else _require_int(pitch_blocks, "pitch_blocks") if pitch < columns: raise ValueError(f"Block pitch {pitch} is narrower than the {columns}-block surface") return rows * pitch * format.bytes_per_block @@ -86,7 +93,7 @@ def linearize_blocks(payload, width: int, height: int, format_name: str, *, """Copy the visible blocks of a pitched block-row surface into tight rows.""" format = _two_dimensional(format_name) columns, rows = _grid(width, height, format) - pitch = columns if pitch_blocks is None else pitch_blocks + pitch = columns if pitch_blocks is None else _require_int(pitch_blocks, "pitch_blocks") expected = surface_bytes(width, height, format_name, pitch_blocks=pitch) if len(payload) != expected: raise ValueError(f"Expected {expected} bytes for {format.name}, got {len(payload)}") @@ -100,21 +107,27 @@ def linearize_blocks(payload, width: int, height: int, format_name: str, *, def tile_blocks(blocks, width: int, height: int, format_name: str, *, - pitch_blocks: int | None = None, padding: bytes | None = None) -> bytes: + pitch_blocks: int | None = None, padding: bytes | bytearray | memoryview | None = None) -> bytes: """Write tight block rows into a pitched block-row surface.""" format = _two_dimensional(format_name) columns, rows = _grid(width, height, format) + pitch = columns if pitch_blocks is None else _require_int(pitch_blocks, "pitch_blocks") + expected = surface_bytes(width, height, format_name, pitch_blocks=pitch) block_bytes = format.bytes_per_block tight = columns * rows * block_bytes if len(blocks) != tight: raise ValueError(f"Expected {tight} tight bytes for {format.name}, got {len(blocks)}") - pitch = columns if pitch_blocks is None else pitch_blocks - expected = surface_bytes(width, height, format_name, pitch_blocks=pitch) if padding is None: - padding = b"\xff" * block_bytes - if len(padding) != block_bytes: + padding_bytes = b"\xff" * block_bytes + elif isinstance(padding, (bytes, bytearray)): + padding_bytes = bytes(padding) + elif isinstance(padding, memoryview) and padding.ndim == 1 and padding.format == "B": + padding_bytes = bytes(padding) + else: + raise ValueError(f"Expected bytes-like padding of {block_bytes} bytes, got {type(padding).__name__}") + if len(padding_bytes) != block_bytes: raise ValueError(f"Expected one {block_bytes}-byte padding block") - output = bytearray(padding * (rows * pitch)) + output = bytearray(padding_bytes * (rows * pitch)) row_bytes = columns * block_bytes for y in range(rows): source = y * row_bytes @@ -136,12 +149,13 @@ def _volume_geometry(width: int, height: int, format: Format) -> tuple[int, int, def tile_volume_4k_s(slices, width: int, height: int, depth: int, format_name: str) -> bytes: """Tile tight BC7 volume slices, one padded 4 KiB surface per Z slice.""" format = _volume(format_name) + depth = _require_int(depth, "depth") if depth <= 0: raise ValueError("Expected a positive volume depth") + _, _, slice_bytes, _ = _volume_geometry(width, height, format) slices = list(slices) if len(slices) != depth: raise ValueError(f"Expected {depth} volume slices, got {len(slices)}") - _, _, slice_bytes, _ = _volume_geometry(width, height, format) output = bytearray() for z, blocks in enumerate(slices): if len(blocks) != slice_bytes: @@ -154,6 +168,7 @@ def tile_volume_4k_s(slices, width: int, height: int, depth: int, format_name: s def linearize_volume_4k_s(payload, width: int, height: int, depth: int, format_name: str) -> bytes: """Read tight BC7 volume slices from one 4 KiB surface per Z slice.""" format = _volume(format_name) + depth = _require_int(depth, "depth") if depth <= 0: raise ValueError("Expected a positive volume depth") _, _, _, slice_stride = _volume_geometry(width, height, format) diff --git a/tools/texture_descriptors.py b/tools/texture_descriptors.py index e9efb974ba..7dcc0ede21 100644 --- a/tools/texture_descriptors.py +++ b/tools/texture_descriptors.py @@ -229,13 +229,26 @@ def main(argv: list[str] | None = None) -> int: mode.add_argument("--lookup-key", metavar="KEY", help="Find all descriptor indices for a decimal or 0x-prefixed 64-bit texture key") args = parser.parse_args(argv) + if args.lookup_key is None and len(args.archives) != 1: + parser.error("Multiple archives require --lookup-key") archive = args.archives[0] try: for index in (args.descriptor, args.raw_page_map, args.zlib_segment): if index is not None and index < 0: raise ValueError("Descriptor index outside the ETPF table (must be nonnegative)") + key: int | None = None if args.lookup_key is not None: key = int(args.lookup_key, 16 if args.lookup_key.lower().startswith("0x") else 10) + if not 0 <= key < 1 << 64: + raise ValueError("Texture key must be an unsigned 64-bit integer") + for candidate in args.archives: + archive = candidate + if not candidate.exists(): + raise FileNotFoundError("Archive file not found") + if not candidate.is_file(): + raise ValueError("Archive path is not a regular file") + archive = args.archives[0] + if key is not None: seen: set[tuple[int, int]] = set() matches: list[dict[str, str | int]] = [] for archive in args.archives: @@ -250,8 +263,6 @@ def main(argv: list[str] | None = None) -> int: json.dump({"matches": matches}, sys.stdout, indent=2) print() else: - if len(args.archives) != 1: - parser.error("Multiple archives require --lookup-key") with archive.open("rb") as file: if args.descriptor is not None: print(json.dumps(describe_descriptor(file, args.descriptor), indent=2)) diff --git a/tools/ttpf_batch_export.py b/tools/ttpf_batch_export.py index 77b565ddbe..ef6226d69c 100644 --- a/tools/ttpf_batch_export.py +++ b/tools/ttpf_batch_export.py @@ -285,6 +285,9 @@ def batch_export(pool_path: Path, out_dir: Path, raise ValueError(f"--manifest path collides with --out: {resolved_manifest}") if resolved_manifest.resolve() in out_dir.resolve().parents: raise ValueError(f"--manifest path cannot be an ancestor of --out: {resolved_manifest}") + for option, source_path in (("history", history_path), ("calibration", calibration_path)): + if source_path is not None and _same_path(resolved_manifest, source_path): + raise ValueError(f"--manifest path collides with --{option}: {resolved_manifest}") if calibration_path is not None and (allow_provisional or history_path is not None): raise ValueError("--calibration cannot be combined with --allow-provisional or --history") @@ -349,7 +352,6 @@ def fitted_decoder(pool): finally: pool.close() - out_dir.mkdir(parents=True, exist_ok=True) manifest_path = resolved_manifest if indices is None: @@ -359,6 +361,13 @@ def fitted_decoder(pool): else: target_indices = [i for i in indices if 0 <= i < total_textures] + # The manifest is published after the workers finish. Its path must not name + # a requested DDS, including one preserved after a failed or skipped export. + for index in target_indices: + if _same_path(manifest_path, out_dir / f"tex_{index:05d}.dds"): + raise ValueError(f"--manifest path collides with DDS output: {manifest_path}") + out_dir.mkdir(parents=True, exist_ok=True) + manifest_entries: list[dict] = [] stats = {"strict": 0, "provisional": 0, "failed": 0, "skipped": 0} if fitted_decoder is not None: